From 790fdd798e25386213d88e035c79b4d63cde290e Mon Sep 17 00:00:00 2001 From: pombredanne Date: Sat, 21 Oct 2006 23:19:54 +0000 Subject: [PATCH] A massive organize imports and formatting of the sources using default Eclipse code style --- .../net/sourceforge/phpeclipse/core/WebCore.java | 15 +- .../phpeclipse/core/model/ISourceModel.java | 8 +- .../phpeclipse/core/model/ISourceReference.java | 12 +- .../phpeclipse/core/model/SourceReference.java | 29 +- .../phpdt/debug/core/PHPDebugModel.java | 222 +- .../phpdt/internal/debug/core/PHPDBGMod.java | 27 +- .../internal/debug/core/PHPDebugCorePlugin.java | 50 +- .../debug/core/PHPDegugCorePluginImages.java | 236 +- .../phpdt/internal/debug/core/SocketUtil.java | 57 +- .../debug/core/breakpoints/PHPBreakpoint.java | 243 +- .../debug/core/breakpoints/PHPLineBreakpoint.java | 98 +- .../internal/debug/core/model/IPHPDebugTarget.java | 23 +- .../internal/debug/core/model/PHPDebugElement.java | 70 +- .../internal/debug/core/model/PHPExpression.java | 75 +- .../debug/core/model/PHPVariableComparator.java | 4 +- .../debug/core/watch/PHPEvalException.java | 7 +- .../core/watch/PHPWatchExpressionDelegate.java | 36 +- .../debug/core/watch/PHPWatchExpressionResult.java | 61 +- .../phpdt/debug/ui/PHPDebugUiConstants.java | 6 +- .../phpdt/debug/ui/PHPDebugUiImages.java | 65 +- .../phpdt/internal/debug/ui/PHPDebugHover.java | 172 +- .../debug/ui/PHPDebugModelPresentation.java | 144 +- .../internal/debug/ui/PHPDebugUiMessages.java | 10 +- .../phpdt/internal/debug/ui/PHPDebugUiPlugin.java | 100 +- .../debug/ui/PHPExecutionArgumentsPage.java | 52 +- .../internal/debug/ui/actions/ActionMessages.java | 10 +- .../debug/ui/actions/PHPDebugBreakpointAction.java | 46 +- .../ui/actions/PHPManageBreakpointRulerAction.java | 220 +- .../PHPManageBreakpointRulerActionDelegate.java | 24 +- .../actions/RetargettableActionAdapterFactory.java | 30 +- .../debug/ui/actions/ToggleBreakpointAdapter.java | 1166 ++-- .../debug/ui/launcher/ExecutionArguments.java | 41 +- .../ui/launcher/LoadPathEntryLabelProvider.java | 10 +- .../debug/ui/launcher/PHPApplicationTabGroup.java | 15 +- .../debug/ui/launcher/PHPArgumentsTab.java | 97 +- .../debug/ui/launcher/PHPEntryPointTab.java | 56 +- .../debug/ui/launcher/PHPEnvironmentTab.java | 1212 ++-- .../debug/ui/launcher/PHPEnvironmentTab2.java | 449 +- .../debug/ui/launcher/PHPLaunchShortcut.java | 79 +- .../debug/ui/preferences/EditPathMapDialog.java | 82 +- .../ui/preferences/PHPBasePreferencePage.java | 9 +- .../preferences/PHPInterpreterContentProvider.java | 6 +- .../preferences/PHPInterpreterLabelProvider.java | 24 +- .../preferences/PHPInterpreterPreferencePage.java | 443 +- .../properties/PHPBreakpointPropertiesDialog.java | 213 +- .../externaltools/actions/ExternalPHPParser.java | 617 +- .../actions/PHPExternalParserAction.java | 144 +- .../actions/PHPRestartApacheAction.java | 38 +- .../actions/PHPStartApacheAction.java | 93 +- .../externaltools/actions/PHPStartMySQLAction.java | 37 +- .../externaltools/actions/PHPStartXAMPPAction.java | 89 +- .../externaltools/actions/PHPStopApacheAction.java | 37 +- .../externaltools/actions/PHPStopXAMPPAction.java | 89 +- .../externaltools/group/IGroupDialogPage.java | 59 +- .../internal/dialog/ExternalToolVariableForm.java | 100 +- .../internal/model/ExternalToolsImages.java | 231 +- .../internal/model/ExternalToolsModelMessages.java | 55 +- .../internal/model/IHelpContextIds.java | 102 +- .../internal/model/IPreferenceConstants.java | 35 +- .../externaltools/internal/model/ToolMessages.java | 55 +- .../internal/model/VariableContextManager.java | 74 +- .../BackgroundResourceRefresher.java | 55 +- .../ProgramBuilderTabGroup.java | 19 +- .../ProgramLaunchDelegate.java | 86 +- .../launchConfigurations/ProgramMainTab.java | 8 +- .../launchConfigurations/ProgramTabGroup.java | 19 +- .../internal/registry/ArgumentVariable.java | 48 +- .../registry/ArgumentVariableRegistry.java | 29 +- .../internal/registry/ExternalToolMigration.java | 223 +- .../internal/registry/ExternalToolVariable.java | 116 +- .../registry/ExternalToolVariableRegistry.java | 102 +- .../internal/registry/PathLocationVariable.java | 48 +- .../registry/PathLocationVariableRegistry.java | 29 +- .../internal/registry/RefreshScopeVariable.java | 48 +- .../registry/RefreshScopeVariableRegistry.java | 29 +- .../internal/ui/ExternalToolsContentProvider.java | 15 +- .../internal/ui/FileSelectionDialog.java | 327 +- .../internal/ui/IExternalToolsUIConstants.java | 89 +- .../internal/ui/MessageDialogWithToggle.java | 205 +- .../externaltools/internal/ui/MessageLine.java | 39 +- .../externaltools/internal/ui/StatusDialog.java | 85 +- .../externaltools/internal/ui/StatusInfo.java | 69 +- .../internal/ui/TreeAndListGroup.java | 181 +- .../ExternalToolsLaunchConfigurationMessages.java | 14 +- .../launchConfigurations/ExternalToolsMainTab.java | 1155 ++-- .../ExternalToolsRefreshTab.java | 129 +- .../launchConfigurations/ExternalToolsUtil.java | 654 ++- .../model/IExternalToolConstants.java | 227 +- .../phpdt/externaltools/model/IRunnerLog.java | 42 +- .../phpdt/externaltools/model/StringMatcher.java | 359 +- .../phpdt/externaltools/model/ToolUtil.java | 426 +- .../preferences/ApachePrefencePage.java | 17 +- .../preferences/MySQLPreferencePage.java | 6 +- .../PHPExternalToolsPreferencePage.java | 2 +- .../preferences/PHPPreferencesMessages.java | 15 +- .../preferences/XamppPrefencePage.java | 2 +- .../phpdt/externaltools/util/StringUtil.java | 46 +- .../externaltools/variable/BuildTypeExpander.java | 3 +- .../variable/ExpandVariableContext.java | 101 +- .../phpdt/externaltools/variable/FileExpander.java | 45 +- .../externaltools/variable/IVariableComponent.java | 72 +- .../variable/IVariableLocationExpander.java | 51 +- .../variable/IVariableResourceExpander.java | 49 +- .../variable/IVariableTextExpander.java | 45 +- .../externaltools/variable/LocalhostExpander.java | 10 +- .../variable/ProjectNameExpander.java | 9 +- .../externaltools/variable/ResourceComponent.java | 154 +- .../variable/ResourceContainerExpander.java | 23 +- .../externaltools/variable/ResourceExpander.java | 86 +- .../variable/ResourceProjectExpander.java | 31 +- .../variable/SpecificFileResourceComponent.java | 48 +- .../variable/SpecificFolderResourceComponent.java | 68 +- .../phpdt/externaltools/variable/UrlExpander.java | 66 +- .../externaltools/variable/WorkingSetExpander.java | 34 +- .../externaltools/variable/WorkspaceExpander.java | 23 +- .../externaltools/ExternalToolsPlugin.java | 465 +- .../phpeclipse/externaltools/PHPConsole.java | 168 +- .../internal/launching/ConsoleLineTracker.java | 108 +- .../phpdt/internal/launching/DebuggerRunner.java | 187 +- .../internal/launching/InterpreterRunner.java | 91 +- .../launching/InterpreterRunnerConfiguration.java | 162 +- .../phpdt/internal/launching/PHPInterpreter.java | 138 +- .../launching/PHPLaunchConfigurationAttribute.java | 55 +- .../launching/PHPLaunchConfigurationDelegate.java | 35 +- .../internal/launching/PHPLaunchingMessages.java | 11 +- .../internal/launching/PHPLaunchingPlugin.java | 9 +- .../phpdt/internal/launching/PHPRuntime.java | 109 +- .../phpdt/httpquery/AbstractHTTPQueryAction.java | 27 +- .../phpdt/httpquery/HTTPQueryAction.java | 9 +- .../sourceforge/phpdt/httpquery/KodersAction.java | 23 +- .../sourceforge/phpdt/httpquery/PHPHelpAction.java | 24 +- .../phpdt/httpquery/config/Configuration.java | 697 +-- .../httpquery/config/ConfigurationManager.java | 35 +- .../httpquery/config/ConfigurationWorkingCopy.java | 14 +- .../phpdt/httpquery/config/IConfiguration.java | 5 +- .../httpquery/config/IConfigurationListener.java | 5 +- .../config/IConfigurationWorkingCopy.java | 7 +- .../phpdt/httpquery/config/IMemento.java | 165 +- .../phpdt/httpquery/config/XMLMemento.java | 123 +- .../preferences/ConfigurationComposite.java | 66 +- .../preferences/ConfigurationContentProvider.java | 28 +- .../httpquery/preferences/ConfigurationDialog.java | 113 +- .../preferences/ConfigurationPreferencePage.java | 39 +- .../ConfigurationPreferencesDialog.java | 82 +- .../ConfigurationTableLabelProvider.java | 180 +- .../phpdt/httpquery/preferences/SWTUtil.java | 32 +- .../sourceforge/phpdt/phphelp/PHPHelpPlugin.java | 25 +- .../phphelp/actions/PHPFunctionHelpResource.java | 4 +- .../phpeclipse/phpunit/PHPUnitImages.java | 85 +- .../phpeclipse/phpunit/PHPUnitPlugin.java | 73 +- .../phpeclipse/phpunit/PHPUnitView.java | 365 +- .../phpeclipse/phpunit/ProgressInfoComposite.java | 57 +- .../phpeclipse/phpunit/ResultsInfoComposite.java | 34 +- .../phpeclipse/phpunit/SettingsInfoComposite.java | 35 +- .../phpunit/TestPoolContentProvider.java | 61 +- .../phpeclipse/phpunit/TestPoolLabelProvider.java | 76 +- .../phpunit/preferences/PHPUnitPreferencePage.java | 57 +- .../phpunit/reporthandling/ConnectionListener.java | 16 +- .../phpunit/reporthandling/ReportListener.java | 17 +- .../phpunit/reporthandling/XMLReportHandler.java | 149 +- .../phpeclipse/phpunit/testpool/TestCase.java | 41 +- .../phpeclipse/phpunit/testpool/TestPool.java | 152 +- .../phpeclipse/phpunit/testpool/TestSuite.java | 103 +- .../phpdt/smarty/ui/internal/SmartyUIMessages.java | 34 +- .../ui/internal/editor/SmartyDocumentProvider.java | 3 +- .../editor/SmartyDocumentSetupParticipant.java | 3 +- .../smarty/ui/internal/editor/SmartyEditor.java | 83 +- .../editor/SmartyEditorActionContributor.java | 9 +- .../ui/internal/editor/SmartyEditorMessages.java | 31 +- .../internal/text/SmartyCompletionProcessor.java | 12 +- .../ui/internal/text/SmartyConfiguration.java | 153 +- .../smarty/ui/internal/text/SmartyTagRule.java | 86 +- .../smarty/ui/internal/text/SmartyTagScanner.java | 14 +- .../core/tests/util/AbstractCompilerTest.java | 244 +- .../sourceforge/phpdt/core/tests/util/Util.java | 95 +- .../phpeclipse/example/outline/Import2Console.java | 123 +- .../phpeclipse/example/outline/Type2Console.java | 144 +- .../php/test/DualParseSyntaxErrorTest.java | 192 +- .../phpeditor/php/test/DummyDocument.java | 811 ++-- .../php/test/IdentifierIndexManagerTest.java | 67 +- .../phpeditor/php/test/PHPFormatterTest.java | 23 +- .../phpeclipse/tests/parser/OverlibTestCase.java | 923 ++-- .../phpeclipse/tests/parser/PHPManualTestCase.java | 430 +- .../phpeclipse/tests/parser/PHPParserTestCase.java | 325 +- .../tests/parser/PHPParserTestSuite.java | 5 +- .../tests/parser/SmartyCompilerTestCase.java | 3773 ++++++------ .../sourceforge/phpeclipse/ui/ColorManager.java | 26 +- .../phpeclipse/ui/IPreferenceConstants.java | 26 +- .../phpeclipse/ui/PreferenceConstants.java | 43 +- .../src/net/sourceforge/phpeclipse/ui/WebUI.java | 283 +- .../phpeclipse/ui/editor/BrowserUtil.java | 53 +- .../phpeclipse/ui/editor/EditorMessages.java | 26 +- .../phpeclipse/ui/editor/I18NDocumentProvider.java | 19 +- .../ui/editor/ShowExternalPreviewAction.java | 184 +- .../phpeclipse/ui/editor/StructuredTextEditor.java | 116 +- .../phpeclipse/ui/internal/WebUIMessages.java | 34 +- .../ui/overlaypages/FieldEditorOverlayPage.java | 682 ++- .../phpeclipse/ui/overlaypages/Messages.java | 15 +- .../phpeclipse/ui/overlaypages/OverlayPage.java | 135 +- .../ui/overlaypages/ProjectPrefUtil.java | 124 +- .../phpeclipse/ui/overlaypages/PropertyStore.java | 110 +- .../ui/preferences/IMiscProjectPreferences.java | 44 +- .../ui/preferences/ITextStylePreferences.java | 10 +- .../ui/preferences/OverlayPreferenceStore.java | 26 +- .../ui/preferences/PHPMiscProjectPreferences.java | 108 +- .../ui/preferences/PHPPreferencesMessages.java | 15 +- .../preferences/PHPPreviewProjectPreferences.java | 120 +- .../ui/preferences/PreferenceDescriptor.java | 23 +- .../preferences/TemplatesPreferencePage.java | 15 +- .../template/BasicCompletionProcessor.java | 310 +- .../ui/templates/template/HTMLContextType.java | 5 +- .../ui/templates/template/JSContextType.java | 5 +- .../ui/templates/template/SmartyContextType.java | 5 +- .../ui/templates/template/XMLContextType.java | 5 +- .../phpeclipse/ui/text/AbstractTextTools.java | 12 +- .../ui/text/IReconcilingParticipant.java | 6 +- .../ui/text/TextDoubleClickStrategy.java | 6 +- .../ui/text/rules/AbstractPartitioner.java | 1104 ++-- .../ui/text/rules/InnerDocumentView.java | 248 +- .../ui/text/rules/MultiViewPartitioner.java | 1485 +++--- .../ui/text/rules/OuterDocumentView.java | 100 +- .../phpeclipse/ui/text/rules/ViewNode.java | 4 +- .../source/DefaultSourceViewerConfiguration.java | 8 +- .../ui/views/outline/ModelBasedOutlinePage.java | 66 +- .../ui/views/outline/ProblemsLabelDecorator.java | 282 +- .../ui/views/util/ImageDescriptorRegistry.java | 25 +- .../ui/views/util/ImageImageDescriptor.java | 10 +- .../ui/views/util/OverlayImageDescriptor.java | 27 +- .../phpeclipse/webbrowser/ExtendedBrowser.java | 12 +- .../phpeclipse/webbrowser/IExternalWebBrowser.java | 9 +- .../webbrowser/IExternalWebBrowserWorkingCopy.java | 5 +- .../phpeclipse/webbrowser/IInternalWebBrowser.java | 7 +- .../webbrowser/IInternalWebBrowserWorkingCopy.java | 5 +- .../sourceforge/phpeclipse/webbrowser/IURLMap.java | 6 +- .../phpeclipse/webbrowser/IWebBrowser.java | 1 + .../webbrowser/IWebBrowserEditorInput.java | 29 +- .../phpeclipse/webbrowser/OpenBrowserAction.java | 7 +- .../webbrowser/OpenBrowserWorkbenchAction.java | 50 +- .../phpeclipse/webbrowser/WebBrowser.java | 38 +- .../webbrowser/WebBrowserEditorInput.java | 146 +- .../internal/BrowserContentProvider.java | 56 +- .../webbrowser/internal/BrowserManager.java | 525 +- .../webbrowser/internal/BrowserSearcher.java | 40 +- .../webbrowser/internal/BrowserTableComposite.java | 176 +- .../internal/BrowserTableLabelProvider.java | 43 +- .../webbrowser/internal/BusyIndicator.java | 50 +- .../phpeclipse/webbrowser/internal/ContextIds.java | 37 +- .../webbrowser/internal/ExternalBrowserDialog.java | 105 +- .../webbrowser/internal/ExternalWebBrowser.java | 58 +- .../internal/ExternalWebBrowserWorkingCopy.java | 25 +- .../phpeclipse/webbrowser/internal/Favorite.java | 17 +- .../webbrowser/internal/IWebBrowserListener.java | 6 +- .../webbrowser/internal/ImageResource.java | 77 +- .../webbrowser/internal/InternalBrowserDialog.java | 33 +- .../webbrowser/internal/InternalWebBrowser.java | 28 +- .../internal/InternalWebBrowserWorkingCopy.java | 12 +- .../internal/InternetPreferencePage.java | 30 +- .../internal/OpenWithBrowserActionDelegate.java | 37 +- .../internal/OrganizeFavoritesDialog.java | 105 +- .../phpeclipse/webbrowser/internal/SWTUtil.java | 32 +- .../webbrowser/internal/StandardURLMap.java | 3 +- .../internal/SwitchBrowserWorkbenchAction.java | 83 +- .../internal/SwitchDefaultBrowserAction.java | 13 +- .../phpeclipse/webbrowser/internal/TextAction.java | 106 +- .../phpeclipse/webbrowser/internal/Trace.java | 22 +- .../phpeclipse/webbrowser/internal/WebBrowser.java | 1202 ++-- .../webbrowser/internal/WebBrowserEditor.java | 227 +- .../WebBrowserEditorActionBarContributor.java | 41 +- .../webbrowser/internal/WebBrowserPreference.java | 64 +- .../internal/WebBrowserPreferencePage.java | 38 +- .../webbrowser/internal/WebBrowserUIPlugin.java | 26 +- .../webbrowser/internal/WebBrowserUtil.java | 185 +- .../phpeclipse/webbrowser/views/BrowserView.java | 6 +- .../webbrowser/views/ShowInContextBrowser.java | 7 +- .../sourceforge/phpeclipse/xdebug/core/Base64.java | 2835 +++++----- .../xdebug/core/BreakpointResponseData.java | 19 +- .../phpeclipse/xdebug/core/DebugConnection.java | 311 +- .../xdebug/core/IXDebugPreferenceConstants.java | 2 + .../phpeclipse/xdebug/core/PHPDebugUtils.java | 47 +- .../phpeclipse/xdebug/core/ResponseData.java | 7 +- .../phpeclipse/xdebug/core/XDebugCorePlugin.java | 53 +- .../xdebug/php/launching/IXDebugConstants.java | 37 +- .../launching/PHPLaunchConfigurationDelegate.java | 109 +- .../php/launching/PHPSourceLookupDirector.java | 2 +- .../php/launching/PHPSourceLookupParticipant.java | 2 +- .../launching/PHPSourcePathComputerDelegate.java | 56 +- .../xdebug/php/model/XDebugAbstractValue.java | 108 +- .../xdebug/php/model/XDebugArrayValue.java | 6 +- .../xdebug/php/model/XDebugBooleanValue.java | 33 +- .../phpeclipse/xdebug/php/model/XDebugElement.java | 83 +- .../xdebug/php/model/XDebugFloatValue.java | 14 +- .../xdebug/php/model/XDebugIntValue.java | 21 +- .../xdebug/php/model/XDebugLineBreakpoint.java | 140 +- .../xdebug/php/model/XDebugObjectValue.java | 10 +- .../xdebug/php/model/XDebugStackFrame.java | 227 +- .../xdebug/php/model/XDebugStringValue.java | 12 +- .../phpeclipse/xdebug/php/model/XDebugTarget.java | 454 +- .../phpeclipse/xdebug/php/model/XDebugThread.java | 194 +- .../phpeclipse/xdebug/php/model/XDebugValue.java | 7 +- .../xdebug/php/model/XDebugVariable.java | 198 +- .../phpeclipse/xdebug/ui/EnvironmentVariable.java | 47 +- .../phpeclipse/xdebug/ui/MultipleInputDialog.java | 262 +- .../phpeclipse/xdebug/ui/XDebugUIPlugin.java | 84 +- .../phpeclipse/xdebug/ui/XDebugUIPluginImages.java | 176 +- .../ui/actions/BreakpointRulerActionDelegate.java | 4 +- .../ui/actions/ToggleBreakpointRulerAction.java | 106 +- .../php/launching/PHPDebugModelPresentation.java | 38 +- .../xdebug/ui/php/launching/PHPEnvironmentTab.java | 40 +- .../xdebug/ui/php/launching/PHPMainTab.java | 127 +- .../xdebug/ui/php/launching/PHPTabGroup.java | 11 +- .../xdebug/ui/php/launching/XDebugTab.java | 58 +- .../ui/php/model/PHPBreakpointAdapterFactory.java | 2 +- .../ui/php/model/PHPLineBreakpointAdapter.java | 24 +- .../xdebug/ui/preference/XDebugPreferencePage.java | 38 +- .../xml/core/internal/model/XMLDocument.java | 249 +- .../xml/core/internal/model/XMLElement.java | 21 +- .../xml/core/internal/parser/DefaultProblem.java | 6 +- .../xml/core/internal/parser/XMLParser.java | 85 +- .../phpeclipse/xml/core/parser/IProblem.java | 10 +- .../xml/core/parser/IProblemCollector.java | 5 +- .../xml/core/parser/IProblemReporter.java | 5 +- .../sourceforge/phpeclipse/xml/ui/XMLPlugin.java | 16 +- .../xml/ui/internal/compare/DTDMergeViewer.java | 28 +- .../xml/ui/internal/compare/XMLMergeViewer.java | 13 +- .../xml/ui/internal/editor/DTDEditor.java | 34 +- .../ui/internal/editor/XMLDocumentProvider.java | 28 +- .../editor/XMLDocumentSetupParticipant.java | 4 +- .../xml/ui/internal/editor/XMLEditor.java | 303 +- .../editor/XMLEditorActionContributor.java | 9 +- .../xml/ui/internal/editor/XMLEditorMessages.java | 31 +- .../outline/XMLOutlineContentProvider.java | 7 +- .../internal/outline/XMLOutlineLabelProvider.java | 4 +- .../xml/ui/internal/outline/XMLOutlinePage.java | 17 +- .../preferences/ContentAssistPreference.java | 100 +- .../preferences/XMLPreferenceInitializer.java | 86 +- .../preferences/XMLSyntaxPreferencePage.java | 959 ++-- .../ui/internal/text/AbstractDocumentProvider.java | 80 +- .../xml/ui/internal/text/AnnotationAdapter.java | 4 +- .../internal/text/AttValueDoubleClickStrategy.java | 6 +- .../xml/ui/internal/text/DTDConfiguration.java | 70 +- .../xml/ui/internal/text/DTDDocumentProvider.java | 19 +- .../xml/ui/internal/text/DeclScanner.java | 4 +- .../xml/ui/internal/text/NameDetector.java | 18 +- .../xml/ui/internal/text/NmtokenDetector.java | 12 +- .../ui/internal/text/PHPXMLPartitionScanner.java | 536 +- .../internal/text/SimpleDoubleClickStrategy.java | 22 +- .../ui/internal/text/TagDoubleClickStrategy.java | 64 +- .../xml/ui/internal/text/TextScanner.java | 4 +- .../xml/ui/internal/text/WhitespaceDetector.java | 16 +- .../xml/ui/internal/text/XMLAnnotation.java | 14 +- .../xml/ui/internal/text/XMLAnnotationHover.java | 12 +- .../ui/internal/text/XMLAnnotationIterator.java | 8 +- .../xml/ui/internal/text/XMLConfiguration.java | 385 +- .../xml/ui/internal/text/XMLPartitionScanner.java | 552 +- .../xml/ui/internal/text/XMLReconcileStep.java | 34 +- .../ui/internal/text/XMLReconcilingStrategy.java | 24 +- .../xml/ui/internal/text/XMLTagRule.java | 14 +- .../xml/ui/internal/text/XMLTagScanner.java | 8 +- .../xml/ui/internal/text/XMLTextHover.java | 10 +- .../xml/ui/internal/text/XMLWordFinder.java | 3 +- .../phpeclipse/xml/ui/text/DTDTextTools.java | 74 +- .../xml/ui/text/IXMLSyntaxConstants.java | 8 +- .../phpeclipse/xml/ui/text/XMLTextTools.java | 120 +- .../sourceforge/phpdt/core/BufferChangedEvent.java | 140 +- .../phpdt/core/ClasspathVariableInitializer.java | 51 +- .../sourceforge/phpdt/core/CompletionProposal.java | 843 ++-- .../phpdt/core/CompletionRequestor.java | 129 +- .../phpdt/core/CompletionRequestorAdapter.java | 181 +- .../phpdt/core/ElementChangedEvent.java | 88 +- .../src/net/sourceforge/phpdt/core/Flags.java | 379 +- .../src/net/sourceforge/phpdt/core/IBuffer.java | 537 +- .../phpdt/core/IBufferChangedListener.java | 15 +- .../net/sourceforge/phpdt/core/IBufferFactory.java | 13 +- .../sourceforge/phpdt/core/IClasspathEntry.java | 483 +- .../net/sourceforge/phpdt/core/ICodeAssist.java | 318 +- .../phpdt/core/ICodeCompletionRequestor.java | 530 +- .../net/sourceforge/phpdt/core/ICodeFormatter.java | 45 +- .../sourceforge/phpdt/core/ICompilationUnit.java | 604 ++- .../phpdt/core/ICompletionRequestor.java | 854 ++-- .../phpdt/core/IElementChangedListener.java | 18 +- .../src/net/sourceforge/phpdt/core/IField.java | 59 +- .../sourceforge/phpdt/core/IImportContainer.java | 30 +- .../sourceforge/phpdt/core/IImportDeclaration.java | 64 +- .../net/sourceforge/phpdt/core/IJavaElement.java | 272 +- .../sourceforge/phpdt/core/IJavaElementDelta.java | 319 +- .../src/net/sourceforge/phpdt/core/IJavaModel.java | 530 +- .../sourceforge/phpdt/core/IJavaModelMarker.java | 96 +- .../sourceforge/phpdt/core/IJavaModelStatus.java | 99 +- .../phpdt/core/IJavaModelStatusConstants.java | 224 +- .../net/sourceforge/phpdt/core/IJavaProject.java | 772 ++- .../net/sourceforge/phpdt/core/ILocalVariable.java | 32 +- .../src/net/sourceforge/phpdt/core/IMember.java | 176 +- .../src/net/sourceforge/phpdt/core/IMethod.java | 279 +- .../src/net/sourceforge/phpdt/core/IOpenable.java | 346 +- .../phpdt/core/IPackageDeclaration.java | 11 +- .../sourceforge/phpdt/core/IPackageFragment.java | 210 +- .../phpdt/core/IPackageFragmentRoot.java | 629 ++- .../src/net/sourceforge/phpdt/core/IParent.java | 43 +- .../sourceforge/phpdt/core/IProblemRequestor.java | 24 +- .../src/net/sourceforge/phpdt/core/IRegion.java | 59 +- .../phpdt/core/ISourceManipulation.java | 225 +- .../net/sourceforge/phpdt/core/ISourceRange.java | 39 +- .../sourceforge/phpdt/core/ISourceReference.java | 91 +- .../src/net/sourceforge/phpdt/core/IType.java | 942 ++-- .../net/sourceforge/phpdt/core/ITypeHierarchy.java | 588 +- .../phpdt/core/ITypeHierarchyChangedListener.java | 7 +- .../net/sourceforge/phpdt/core/IWorkingCopy.java | 487 +- .../sourceforge/phpdt/core/JavaConventions.java | 465 +- .../src/net/sourceforge/phpdt/core/JavaCore.java | 4752 ++++++++------- .../sourceforge/phpdt/core/JavaModelException.java | 211 +- .../sourceforge/phpdt/core/NamingConventions.java | 1096 ++-- .../src/net/sourceforge/phpdt/core/Signature.java | 2295 ++++---- .../net/sourceforge/phpdt/core/ToolFactory.java | 229 +- .../sourceforge/phpdt/core/WorkingCopyOwner.java | 64 +- .../phpdt/core/compiler/CharOperation.java | 2789 +++++---- .../sourceforge/phpdt/core/compiler/IProblem.java | 575 ++- .../sourceforge/phpdt/core/compiler/IScanner.java | 160 +- .../phpdt/core/compiler/ITerminalSymbols.java | 529 +- .../phpdt/core/compiler/InvalidInputException.java | 23 +- .../phpdt/core/dom/CompilationUnit.java | 1655 +++--- .../phpdt/core/formatter/CodeFormatter.java | 55 +- .../formatter/DefaultCodeFormatterConstants.java | 2893 ++++++---- .../sourceforge/phpdt/core/jdom/DOMException.java | 35 +- .../sourceforge/phpdt/core/jdom/DOMFactory.java | 283 +- .../phpdt/core/jdom/IDOMCompilationUnit.java | 99 +- .../sourceforge/phpdt/core/jdom/IDOMFactory.java | 337 +- .../net/sourceforge/phpdt/core/jdom/IDOMField.java | 124 +- .../sourceforge/phpdt/core/jdom/IDOMImport.java | 53 +- .../phpdt/core/jdom/IDOMInitializer.java | 66 +- .../sourceforge/phpdt/core/jdom/IDOMMember.java | 83 +- .../sourceforge/phpdt/core/jdom/IDOMMethod.java | 358 +- .../net/sourceforge/phpdt/core/jdom/IDOMNode.java | 496 +- .../sourceforge/phpdt/core/jdom/IDOMPackage.java | 39 +- .../net/sourceforge/phpdt/core/jdom/IDOMType.java | 237 +- .../phpdt/core/search/IJavaSearchConstants.java | 141 +- .../phpdt/core/search/ITypeNameRequestor.java | 104 +- .../phpdt/corext/refactoring/nls/NLSElement.java | 39 +- .../phpdt/corext/refactoring/nls/NLSLine.java | 36 +- .../internal/codeassist/ISearchRequestor.java | 47 +- .../codeassist/ISearchableNameEnvironment.java | 39 +- .../internal/codeassist/impl/AssistOptions.java | 95 +- .../phpdt/internal/compiler/ASTVisitor.java | 501 +- .../compiler/AbstractSyntaxTreeVisitorAdapter.java | 376 +- .../phpdt/internal/compiler/CompilationResult.java | 299 +- .../phpdt/internal/compiler/Compiler.java | 1118 ++-- .../internal/compiler/ConfigurableOption.java | 384 +- .../compiler/DefaultErrorHandlingPolicies.java | 127 +- .../internal/compiler/DocumentElementParser.java | 2565 ++++---- .../compiler/IAbstractSyntaxTreeVisitor.java | 230 +- .../internal/compiler/ICompilerRequestor.java | 2 +- .../compiler/IDocumentElementRequestor.java | 841 ++-- .../internal/compiler/IErrorHandlingPolicy.java | 17 +- .../phpdt/internal/compiler/IProblemFactory.java | 32 +- .../internal/compiler/ISourceElementRequestor.java | 209 +- .../internal/compiler/SourceElementParser.java | 2623 +++++---- .../internal/compiler/ast/AND_AND_Expression.java | 513 +- .../phpdt/internal/compiler/ast/ASTNode.java | 336 +- .../compiler/ast/AbstractMethodDeclaration.java | 372 +- .../compiler/ast/AbstractVariableDeclaration.java | 21 +- .../compiler/ast/AllocationExpression.java | 238 +- .../ast/AnonymousLocalTypeDeclaration.java | 86 +- .../phpdt/internal/compiler/ast/Argument.java | 33 +- .../compiler/ast/ArrayAllocationExpression.java | 121 +- .../internal/compiler/ast/ArrayInitializer.java | 393 +- .../compiler/ast/ArrayQualifiedTypeReference.java | 79 +- .../internal/compiler/ast/ArrayReference.java | 243 +- .../internal/compiler/ast/ArrayTypeReference.java | 80 +- .../internal/compiler/ast/AssertStatement.java | 167 +- .../phpdt/internal/compiler/ast/Assignment.java | 149 +- .../internal/compiler/ast/BinaryExpression.java | 3275 +++++----- .../phpdt/internal/compiler/ast/Block.java | 87 +- .../internal/compiler/ast/BranchStatement.java | 105 +- .../internal/compiler/ast/BreakStatement.java | 123 +- .../phpdt/internal/compiler/ast/CaseStatement.java | 56 +- .../internal/compiler/ast/CastExpression.java | 276 +- .../phpdt/internal/compiler/ast/Clinit.java | 307 +- .../compiler/ast/CompilationUnitDeclaration.java | 624 +- .../internal/compiler/ast/CompoundAssignment.java | 226 +- .../compiler/ast/ConditionalExpression.java | 733 ++-- .../compiler/ast/ConstructorDeclaration.java | 521 +- .../internal/compiler/ast/ContinueStatement.java | 129 +- .../phpdt/internal/compiler/ast/DefaultCase.java | 147 +- .../phpdt/internal/compiler/ast/DoStatement.java | 165 +- .../phpdt/internal/compiler/ast/DoubleLiteral.java | 119 +- .../internal/compiler/ast/EmptyStatement.java | 16 +- .../internal/compiler/ast/EqualExpression.java | 1048 ++-- .../compiler/ast/ExplicitConstructorCall.java | 244 +- .../phpdt/internal/compiler/ast/Expression.java | 743 ++-- .../compiler/ast/ExtendedStringLiteral.java | 61 +- .../phpdt/internal/compiler/ast/FalseLiteral.java | 106 +- .../internal/compiler/ast/FieldDeclaration.java | 460 +- .../internal/compiler/ast/FieldReference.java | 690 ++- .../phpdt/internal/compiler/ast/FloatLiteral.java | 125 +- .../phpdt/internal/compiler/ast/ForStatement.java | 375 +- .../phpdt/internal/compiler/ast/IfStatement.java | 318 +- .../compiler/ast/ImplicitDocTypeReference.java | 34 +- .../internal/compiler/ast/ImportReference.java | 203 +- .../phpdt/internal/compiler/ast/Initializer.java | 56 +- .../compiler/ast/InnerTypeDeclaration.java | 6 +- .../compiler/ast/InstanceOfExpression.java | 182 +- .../phpdt/internal/compiler/ast/IntLiteral.java | 282 +- .../internal/compiler/ast/IntLiteralMinValue.java | 22 +- .../ast/JavadocArrayQualifiedTypeReference.java | 23 +- .../ast/JavadocArraySingleTypeReference.java | 16 +- .../ast/JavadocQualifiedTypeReference.java | 36 +- .../compiler/ast/JavadocReturnStatement.java | 19 +- .../compiler/ast/JavadocSingleTypeReference.java | 37 +- .../internal/compiler/ast/LabeledStatement.java | 121 +- .../phpdt/internal/compiler/ast/Literal.java | 58 +- .../internal/compiler/ast/LocalDeclaration.java | 212 +- .../compiler/ast/LocalTypeDeclaration.java | 80 +- .../phpdt/internal/compiler/ast/LongLiteral.java | 266 +- .../internal/compiler/ast/LongLiteralMinValue.java | 21 +- .../phpdt/internal/compiler/ast/MagicLiteral.java | 39 +- .../compiler/ast/MemberTypeDeclaration.java | 83 +- .../phpdt/internal/compiler/ast/MessageSend.java | 544 +- .../internal/compiler/ast/MethodDeclaration.java | 280 +- .../phpdt/internal/compiler/ast/NameReference.java | 105 +- .../phpdt/internal/compiler/ast/NullLiteral.java | 36 +- .../phpdt/internal/compiler/ast/NumberLiteral.java | 42 +- .../internal/compiler/ast/OR_OR_Expression.java | 514 +- .../internal/compiler/ast/OperatorExpression.java | 3221 ++++++----- .../phpdt/internal/compiler/ast/OperatorIds.java | 42 +- .../internal/compiler/ast/PostfixExpression.java | 66 +- .../internal/compiler/ast/PrefixExpression.java | 20 +- .../ast/QualifiedAllocationExpression.java | 314 +- .../compiler/ast/QualifiedNameReference.java | 1170 ++-- .../compiler/ast/QualifiedSuperReference.java | 6 +- .../compiler/ast/QualifiedThisReference.java | 88 +- .../compiler/ast/QualifiedTypeReference.java | 107 +- .../phpdt/internal/compiler/ast/Reference.java | 116 +- .../internal/compiler/ast/ReturnStatement.java | 468 +- .../internal/compiler/ast/SingleNameReference.java | 1257 +++-- .../internal/compiler/ast/SingleTypeReference.java | 104 +- .../phpdt/internal/compiler/ast/Statement.java | 56 +- .../phpdt/internal/compiler/ast/StringLiteral.java | 263 +- .../internal/compiler/ast/StringLiteralDQ.java | 85 +- .../internal/compiler/ast/StringLiteralSQ.java | 85 +- .../internal/compiler/ast/SuperReference.java | 85 +- .../internal/compiler/ast/SwitchStatement.java | 355 +- .../phpdt/internal/compiler/ast/ThisReference.java | 225 +- .../internal/compiler/ast/ThrowStatement.java | 55 +- .../phpdt/internal/compiler/ast/TrueLiteral.java | 109 +- .../phpdt/internal/compiler/ast/TryStatement.java | 685 ++- .../internal/compiler/ast/TypeDeclaration.java | 2183 ++++---- .../phpdt/internal/compiler/ast/TypeReference.java | 179 +- .../internal/compiler/ast/UnaryExpression.java | 437 +- .../internal/compiler/ast/WhileStatement.java | 325 +- .../compiler/batch/ClasspathDirectory.java | 224 +- .../internal/compiler/batch/CompilationUnit.java | 133 +- .../phpdt/internal/compiler/batch/FileFinder.java | 59 +- .../phpdt/internal/compiler/batch/FileSystem.java | 287 +- .../phpdt/internal/compiler/codegen/CaseLabel.java | 133 +- .../phpdt/internal/compiler/codegen/Label.java | 488 +- .../internal/compiler/codegen/ObjectCache.java | 271 +- .../phpdt/internal/compiler/env/IBinaryField.java | 31 +- .../phpdt/internal/compiler/env/IBinaryMethod.java | 53 +- .../internal/compiler/env/IBinaryNestedType.java | 41 +- .../phpdt/internal/compiler/env/IBinaryType.java | 171 +- .../internal/compiler/env/ICompilationUnit.java | 40 +- .../phpdt/internal/compiler/env/IConstants.java | 19 +- .../phpdt/internal/compiler/env/IDependent.java | 28 +- .../phpdt/internal/compiler/env/IGenericField.java | 20 +- .../internal/compiler/env/IGenericMethod.java | 36 +- .../phpdt/internal/compiler/env/IGenericType.java | 30 +- .../internal/compiler/env/INameEnvironment.java | 100 +- .../phpdt/internal/compiler/env/ISourceField.java | 56 +- .../phpdt/internal/compiler/env/ISourceImport.java | 59 +- .../phpdt/internal/compiler/env/ISourceMethod.java | 100 +- .../phpdt/internal/compiler/env/ISourceType.java | 219 +- .../compiler/env/NameEnvironmentAnswer.java | 32 +- .../compiler/flow/ConditionalFlowInfo.java | 126 +- .../flow/ExceptionHandlingFlowContext.java | 169 +- .../internal/compiler/flow/FinallyFlowContext.java | 87 +- .../phpdt/internal/compiler/flow/FlowContext.java | 278 +- .../phpdt/internal/compiler/flow/FlowInfo.java | 41 +- .../compiler/flow/InitializationFlowContext.java | 86 +- .../compiler/flow/InsideSubRoutineFlowContext.java | 34 +- .../internal/compiler/flow/LabelFlowContext.java | 25 +- .../internal/compiler/flow/LoopingFlowContext.java | 93 +- .../internal/compiler/flow/SwitchFlowContext.java | 22 +- .../compiler/flow/UnconditionalFlowInfo.java | 384 +- .../internal/compiler/impl/BooleanConstant.java | 45 +- .../internal/compiler/impl/CompilerOptions.java | 969 ++- .../phpdt/internal/compiler/impl/Constant.java | 4036 ++++++++----- .../internal/compiler/impl/DoubleConstant.java | 24 +- .../internal/compiler/impl/ITypeRequestor.java | 10 +- .../phpdt/internal/compiler/impl/IntConstant.java | 24 +- .../internal/compiler/impl/ReferenceContext.java | 8 +- .../internal/compiler/impl/StringConstant.java | 63 +- .../internal/compiler/lookup/ArrayBinding.java | 268 +- .../internal/compiler/lookup/BaseTypeBinding.java | 273 +- .../phpdt/internal/compiler/lookup/BaseTypes.java | 42 +- .../compiler/lookup/BinaryTypeBinding.java | 889 ++-- .../phpdt/internal/compiler/lookup/Binding.java | 48 +- .../phpdt/internal/compiler/lookup/BindingIds.java | 6 + .../phpdt/internal/compiler/lookup/BlockScope.java | 1494 +++--- .../phpdt/internal/compiler/lookup/ClassScope.java | 568 ++- .../compiler/lookup/CompilationUnitScope.java | 1289 +++-- .../compiler/lookup/CompilerModifiers.java | 47 +- .../internal/compiler/lookup/FieldBinding.java | 390 +- .../internal/compiler/lookup/ImportBinding.java | 51 +- .../compiler/lookup/InnerEmulationDependency.java | 8 +- .../internal/compiler/lookup/InvocationSite.java | 11 +- .../internal/compiler/lookup/LocalTypeBinding.java | 242 +- .../compiler/lookup/LocalVariableBinding.java | 79 +- .../compiler/lookup/LookupEnvironment.java | 1067 ++-- .../compiler/lookup/MemberTypeBinding.java | 50 +- .../internal/compiler/lookup/MethodBinding.java | 937 ++-- .../internal/compiler/lookup/MethodScope.java | 421 +- .../internal/compiler/lookup/MethodVerifier.java | 1004 ++-- .../compiler/lookup/NestedTypeBinding.java | 201 +- .../internal/compiler/lookup/PackageBinding.java | 374 +- .../internal/compiler/lookup/ProblemBinding.java | 74 +- .../compiler/lookup/ProblemFieldBinding.java | 38 +- .../compiler/lookup/ProblemMethodBinding.java | 57 +- .../compiler/lookup/ProblemPackageBinding.java | 35 +- .../internal/compiler/lookup/ProblemReasons.java | 27 +- .../compiler/lookup/ProblemReferenceBinding.java | 63 +- .../internal/compiler/lookup/ReferenceBinding.java | 1175 ++-- .../phpdt/internal/compiler/lookup/Scope.java | 1310 +++-- .../compiler/lookup/SourceTypeBinding.java | 1916 ++++--- .../lookup/SyntheticAccessMethodBinding.java | 206 +- .../compiler/lookup/SyntheticArgumentBinding.java | 51 +- .../compiler/lookup/SyntheticFieldBinding.java | 10 +- .../phpdt/internal/compiler/lookup/TagBits.java | 14 +- .../internal/compiler/lookup/TypeBinding.java | 239 +- .../internal/compiler/lookup/TypeConstants.java | 116 +- .../phpdt/internal/compiler/lookup/TypeIds.java | 107 +- .../lookup/UnresolvedReferenceBinding.java | 63 +- .../internal/compiler/lookup/VariableBinding.java | 48 +- .../compiler/parser/AbstractCommentParser.java | 1483 +++-- .../phpdt/internal/compiler/parser/NLSLine.java | 21 +- .../phpdt/internal/compiler/parser/Parser.java | 762 ++- .../compiler/parser/ParserBasicInformation.java | 27 +- .../phpdt/internal/compiler/parser/ParserUtil.java | 18 +- .../internal/compiler/parser/RecoveredElement.java | 603 +- .../phpdt/internal/compiler/parser/Scanner.java | 1153 +++-- .../compiler/parser/SourceTypeConverter.java | 279 +- .../internal/compiler/parser/SyntaxError.java | 116 +- .../parser/UninitializedVariableHandler.java | 40 +- .../phpdt/internal/compiler/parser/UnitParser.java | 939 ++-- .../internal/compiler/parser/VariableInfo.java | 36 +- .../compiler/problem/AbortCompilation.java | 27 +- .../compiler/problem/AbortCompilationUnit.java | 11 +- .../internal/compiler/problem/AbortMethod.java | 11 +- .../phpdt/internal/compiler/problem/AbortType.java | 11 +- .../internal/compiler/problem/DefaultProblem.java | 192 +- .../compiler/problem/DefaultProblemFactory.java | 257 +- .../internal/compiler/problem/ProblemHandler.java | 265 +- .../internal/compiler/problem/ProblemReporter.java | 6461 +++++++++++--------- .../compiler/problem/ProblemSeverities.java | 12 +- .../compiler/problem/ShouldNotImplement.java | 19 +- .../internal/compiler/util/CompoundNameVector.java | 109 +- .../internal/compiler/util/HashtableOfInt.java | 154 +- .../compiler/util/HashtableOfIntValues.java | 26 +- .../internal/compiler/util/HashtableOfLong.java | 154 +- .../internal/compiler/util/HashtableOfObject.java | 39 +- .../internal/compiler/util/HashtableOfPackage.java | 151 +- .../internal/compiler/util/HashtableOfType.java | 153 +- .../phpdt/internal/compiler/util/ObjectVector.java | 56 +- .../internal/compiler/util/SimpleNameVector.java | 61 +- .../internal/compiler/util/SuffixConstants.java | 57 +- .../phpdt/internal/compiler/util/Util.java | 307 +- .../sourceforge/phpdt/internal/core/Assert.java | 177 +- .../phpdt/internal/core/BasicCompilationUnit.java | 265 +- .../phpdt/internal/core/BatchOperation.java | 22 +- .../internal/core/BecomeWorkingCopyOperation.java | 48 +- .../sourceforge/phpdt/internal/core/Buffer.java | 736 ++- .../phpdt/internal/core/BufferCache.java | 58 +- .../phpdt/internal/core/BufferFactoryWrapper.java | 38 +- .../phpdt/internal/core/BufferManager.java | 138 +- .../phpdt/internal/core/ClasspathEntry.java | 1466 +++-- .../internal/core/CommitWorkingCopyOperation.java | 365 +- .../phpdt/internal/core/CompilationUnit.java | 2749 +++++---- .../internal/core/CompilationUnitElementInfo.java | 51 +- .../core/CompilationUnitProblemFinder.java | 358 +- .../core/CompilationUnitStructureRequestor.java | 1123 ++-- .../phpdt/internal/core/CopyElementsOperation.java | 464 +- .../core/CopyResourceElementsOperation.java | 591 ++- .../internal/core/CreateElementInCUOperation.java | 254 +- .../core/CreatePackageDeclarationOperation.java | 207 +- .../internal/core/DefaultWorkingCopyOwner.java | 16 +- .../internal/core/DeleteElementsOperation.java | 106 +- .../core/DeleteResourceElementsOperation.java | 219 +- .../phpdt/internal/core/DeltaProcessingState.java | 556 +- .../phpdt/internal/core/DeltaProcessor.java | 4517 ++++++++------- .../internal/core/DiscardWorkingCopyOperation.java | 36 +- .../phpdt/internal/core/ElementCache.java | 78 +- .../phpdt/internal/core/IJavaElementRequestor.java | 36 +- .../phpdt/internal/core/INamingRequestor.java | 6 +- .../phpdt/internal/core/ImportContainer.java | 212 +- .../phpdt/internal/core/ImportDeclaration.java | 182 +- .../core/ImportDeclarationElementInfo.java | 15 +- .../internal/core/InternalNamingConventions.java | 317 +- .../phpdt/internal/core/JavaElement.java | 254 +- .../phpdt/internal/core/JavaElementDelta.java | 1343 +++-- .../internal/core/JavaElementDeltaBuilder.java | 628 +- .../phpdt/internal/core/JavaElementInfo.java | 55 +- .../phpdt/internal/core/JavaElementRequestor.java | 347 +- .../sourceforge/phpdt/internal/core/JavaModel.java | 1027 ++-- .../phpdt/internal/core/JavaModelCache.java | 91 +- .../phpdt/internal/core/JavaModelInfo.java | 79 +- .../phpdt/internal/core/JavaModelManager.java | 2258 ++++--- .../phpdt/internal/core/JavaModelOperation.java | 1765 +++--- .../phpdt/internal/core/JavaModelStatus.java | 907 ++-- .../phpdt/internal/core/JavaProject.java | 3124 +++++----- .../internal/core/JavaProjectElementInfo.java | 192 +- .../phpdt/internal/core/LRUCacheEnumerator.java | 67 +- .../phpdt/internal/core/LocalVariable.java | 79 +- .../sourceforge/phpdt/internal/core/Member.java | 404 +- .../phpdt/internal/core/MemberElementInfo.java | 40 +- .../phpdt/internal/core/ModelUpdater.java | 170 +- .../phpdt/internal/core/MoveElementsOperation.java | 57 +- .../core/MoveResourceElementsOperation.java | 58 +- .../phpdt/internal/core/MultiOperation.java | 301 +- .../phpdt/internal/core/NameLookup.java | 824 ++-- .../sourceforge/phpdt/internal/core/Openable.java | 1188 ++-- .../phpdt/internal/core/OpenableElementInfo.java | 3 +- .../phpdt/internal/core/OverflowingLRUCache.java | 554 +- .../phpdt/internal/core/PackageDeclaration.java | 68 +- .../phpdt/internal/core/PackageFragment.java | 797 ++-- .../phpdt/internal/core/PackageFragmentInfo.java | 71 +- .../phpdt/internal/core/PackageFragmentRoot.java | 2028 ++++--- .../internal/core/PackageFragmentRootInfo.java | 274 +- .../core/ReconcileWorkingCopyOperation.java | 239 +- .../sourceforge/phpdt/internal/core/Region.java | 222 +- .../internal/core/RenameElementsOperation.java | 125 +- .../core/RenameResourceElementsOperation.java | 87 +- .../phpdt/internal/core/SearchableEnvironment.java | 585 +- .../core/SearchableEnvironmentRequestor.java | 114 +- .../phpdt/internal/core/SetClasspathOperation.java | 1078 ++-- .../phpdt/internal/core/SimpleDelta.java | 36 +- .../phpdt/internal/core/SourceField.java | 120 +- .../internal/core/SourceFieldElementInfo.java | 61 +- .../phpdt/internal/core/SourceMethod.java | 407 +- .../internal/core/SourceMethodElementInfo.java | 134 +- .../phpdt/internal/core/SourceRange.java | 57 +- .../phpdt/internal/core/SourceRefElement.java | 371 +- .../phpdt/internal/core/SourceRefElementInfo.java | 70 +- .../phpdt/internal/core/SourceType.java | 1230 ++-- .../phpdt/internal/core/SourceTypeElementInfo.java | 469 +- .../phpdt/internal/core/TypeVector.java | 197 +- .../sourceforge/phpdt/internal/core/XMLWriter.java | 56 +- .../builder/AbortIncrementalBuildException.java | 14 +- .../core/builder/AbstractImageBuilder.java | 947 ++-- .../internal/core/builder/BatchImageBuilder.java | 390 +- .../phpdt/internal/core/builder/BuildNotifier.java | 482 +- .../internal/core/builder/ClasspathDirectory.java | 178 +- .../internal/core/builder/ClasspathLocation.java | 53 +- .../core/builder/ClasspathMultiDirectory.java | 68 +- .../builder/ImageBuilderInternalException.java | 34 +- .../core/builder/IncrementalImageBuilder.java | 1463 +++--- .../core/builder/MissingClassFileException.java | 12 +- .../core/builder/MissingSourceFileException.java | 11 +- .../internal/core/builder/NameEnvironment.java | 654 ++- .../phpdt/internal/core/builder/PHPBuilder.java | 1414 +++-- .../phpdt/internal/core/builder/ParserVisitor.java | 151 +- .../internal/core/builder/ProblemFactory.java | 20 +- .../phpdt/internal/core/builder/SourceFile.java | 29 +- .../phpdt/internal/core/builder/State.java | 1118 ++-- .../phpdt/internal/core/builder/WorkQueue.java | 61 +- .../internal/core/jdom/AbstractDOMBuilder.java | 327 +- .../phpdt/internal/core/jdom/CompilationUnit.java | 76 +- .../phpdt/internal/core/jdom/DOMBuilder.java | 1300 ++-- .../internal/core/jdom/DOMCompilationUnit.java | 307 +- .../phpdt/internal/core/jdom/DOMField.java | 1152 ++-- .../phpdt/internal/core/jdom/DOMImport.java | 273 +- .../phpdt/internal/core/jdom/DOMInitializer.java | 409 +- .../phpdt/internal/core/jdom/DOMMember.java | 596 +- .../phpdt/internal/core/jdom/DOMMethod.java | 1277 +++-- .../phpdt/internal/core/jdom/DOMNode.java | 1663 +++--- .../phpdt/internal/core/jdom/DOMPackage.java | 240 +- .../phpdt/internal/core/jdom/DOMType.java | 1275 +++-- .../phpdt/internal/core/jdom/ILineStartFinder.java | 16 +- .../internal/core/jdom/SiblingEnumeration.java | 58 +- .../phpdt/internal/core/jdom/SimpleDOMBuilder.java | 469 +- .../phpdt/internal/core/util/ASTNodeFinder.java | 171 +- .../phpdt/internal/core/util/CharArrayBuffer.java | 317 +- .../phpdt/internal/core/util/CharArrayOps.java | 252 +- .../internal/core/util/CommentRecorderParser.java | 301 +- .../internal/core/util/CommentRecorderScanner.java | 31 +- .../internal/core/util/ICacheEnumeration.java | 33 +- .../phpdt/internal/core/util/ILRUCacheable.java | 14 +- .../phpdt/internal/core/util/LRUCache.java | 377 +- .../phpdt/internal/core/util/MementoTokenizer.java | 141 +- .../phpdt/internal/core/util/PerThreadObject.java | 21 +- .../internal/core/util/ReferenceInfoAdapter.java | 77 +- .../phpdt/internal/core/util/SimpleDocument.java | 216 +- .../internal/core/util/SimpleLookupTable.java | 249 +- .../phpdt/internal/core/util/SimpleSet.java | 169 +- .../phpdt/internal/core/util/SimpleWordSet.java | 98 +- .../phpdt/internal/core/util/ToStringSorter.java | 117 +- .../sourceforge/phpdt/internal/core/util/Util.java | 3605 ++++++------ .../sourceforge/phpdt/internal/corext/Assert.java | 91 +- .../phpdt/internal/corext/CorextMessages.java | 14 +- .../codemanipulation/CodeGenerationMessages.java | 16 +- .../codemanipulation/CodeGenerationSettings.java | 36 +- .../corext/codemanipulation/GetterSetterUtil.java | 258 +- .../corext/codemanipulation/IRequestQuery.java | 20 +- .../corext/codemanipulation/StubUtility.java | 2243 ++++--- .../corext/phpdoc/PHPDocBufferCommentReader.java | 52 +- .../phpdoc/PHPDocCharArrayCommentReader.java | 111 +- .../phpdt/internal/corext/phpdoc/PHPDocUtil.java | 139 +- .../internal/corext/phpdoc/SingleCharReader.java | 35 +- .../corext/refactoring/util/ResourceUtil.java | 49 +- .../internal/corext/template/TemplateMessages.java | 15 +- .../corext/template/php/CodeTemplateContext.java | 51 +- .../template/php/CodeTemplateContextType.java | 554 ++- .../corext/template/php/CodeTemplates.java | 46 +- .../template/php/CompilationUnitCompletion.java | 231 +- .../template/php/CompilationUnitContext.java | 58 +- .../template/php/CompilationUnitContextType.java | 179 +- .../corext/template/php/HTMLContextType.java | 40 +- .../corext/template/php/HTMLUnitContext.java | 301 +- .../internal/corext/template/php/JavaContext.java | 1170 ++-- .../corext/template/php/JavaContextType.java | 352 +- .../corext/template/php/JavaDocContext.java | 156 +- .../corext/template/php/JavaDocContextType.java | 26 +- .../corext/template/php/JavaFormatter.java | 653 ++- .../corext/template/php/JavaTemplateMessages.java | 15 +- .../internal/corext/template/php/TemplateSet.java | 264 +- .../internal/corext/template/php/Templates.java | 46 +- .../corext/textmanipulation/MoveTextEdit.java | 124 +- .../corext/textmanipulation/MultiTextEdit.java | 81 +- .../corext/textmanipulation/NopTextEdit.java | 51 +- .../corext/textmanipulation/SimpleTextEdit.java | 74 +- .../corext/textmanipulation/SwapTextEdit.java | 14 +- .../corext/textmanipulation/TextBuffer.java | 343 +- .../corext/textmanipulation/TextBufferEditor.java | 213 +- .../corext/textmanipulation/TextBufferFactory.java | 125 +- .../internal/corext/textmanipulation/TextEdit.java | 77 +- .../corext/textmanipulation/TextEditNode.java | 478 +- .../textmanipulation/TextEditNodeComparator.java | 34 +- .../textmanipulation/TextManipulationMessages.java | 13 +- .../corext/textmanipulation/TextRange.java | 135 +- .../corext/textmanipulation/TextRegion.java | 29 +- .../corext/textmanipulation/UndoMemento.java | 23 +- .../internal/corext/util/CodeFormatterUtil.java | 430 +- .../phpdt/internal/corext/util/IOCloser.java | 10 +- .../phpdt/internal/corext/util/JavaModelUtil.java | 790 ++-- .../phpdt/internal/corext/util/JdtFlags.java | 403 +- .../phpdt/internal/corext/util/Resources.java | 153 +- .../phpdt/internal/corext/util/Strings.java | 306 +- .../phpdt/internal/formatter/AbortFormatting.java | 5 +- .../phpdt/internal/formatter/CodeFormatter.java | 5296 +++++++++-------- .../internal/formatter/OptimizedReplaceEdit.java | 8 +- .../formatter/align/AlignmentException.java | 39 +- .../internal/formatter/impl/FormatterOptions.java | 431 +- .../phpdt/internal/formatter/impl/SplitLine.java | 405 +- .../phpdt/internal/ui/IJavaHelpContextIds.java | 996 +++- .../phpdt/internal/ui/IJavaStatusConstants.java | 38 +- .../internal/ui/JavaElementAdapterFactory.java | 205 +- .../phpdt/internal/ui/JavaElementProperties.java | 28 +- .../phpdt/internal/ui/PHPStatusConstants.java | 22 +- .../phpdt/internal/ui/PHPUIException.java | 9 +- .../phpdt/internal/ui/PHPUIMessages.java | 13 +- .../sourceforge/phpdt/internal/ui/PHPUIStatus.java | 76 +- .../sourceforge/phpdt/internal/ui/PHPUiImages.java | 1134 +++-- .../phpdt/internal/ui/ResourceAdapterFactory.java | 13 +- .../ui/actions/AbstractToggleLinkingAction.java | 13 +- .../phpdt/internal/ui/actions/ActionMessages.java | 59 +- .../phpdt/internal/ui/actions/ActionUtil.java | 66 +- .../internal/ui/actions/AddBlockCommentAction.java | 366 +- .../phpdt/internal/ui/actions/AddTaskAction.java | 14 +- .../internal/ui/actions/BlockCommentAction.java | 250 +- .../internal/ui/actions/CompositeActionGroup.java | 30 +- .../internal/ui/actions/FoldingActionGroup.java | 78 +- .../ui/actions/FoldingExpandAllRulerAction.java | 13 +- .../ui/actions/FoldingToggleRulerAction.java | 32 +- .../phpdt/internal/ui/actions/IndentAction.java | 491 +- .../phpdt/internal/ui/actions/OpenActionUtil.java | 72 +- .../ui/actions/RemoveBlockCommentAction.java | 62 +- .../internal/ui/actions/SelectionConverter.java | 218 +- .../ui/actions/SelectionDispatchAction.java | 126 +- .../ui/actions/WorkbenchRunnableAdapter.java | 19 +- .../AbstractElementListSelectionDialog.java | 347 +- .../ui/dialogs/CheckedTreeSelectionDialog.java | 77 +- .../ui/dialogs/ElementListSelectionDialog.java | 22 +- .../phpdt/internal/ui/dialogs/MessageLine.java | 30 +- .../internal/ui/dialogs/SelectionStatusDialog.java | 112 +- .../phpdt/internal/ui/dialogs/StatusDialog.java | 109 +- .../phpdt/internal/ui/dialogs/StatusInfo.java | 39 +- .../phpdt/internal/ui/dialogs/StatusUtil.java | 62 +- .../ui/dnd/BasicSelectionTransferDragAdapter.java | 45 +- .../internal/ui/dnd/DelegatingDragAdapter.java | 89 +- .../internal/ui/dnd/DelegatingDropAdapter.java | 83 +- .../internal/ui/dnd/JdtViewerDragAdapter.java | 14 +- .../internal/ui/dnd/JdtViewerDropAdapter.java | 222 +- .../internal/ui/dnd/LocalSelectionTransfer.java | 59 +- .../ui/dnd/ResourceTransferDragAdapter.java | 85 +- .../ui/dnd/TransferDragSourceListener.java | 3 +- .../ui/dnd/TransferDropTargetListener.java | 3 +- .../phpdt/internal/ui/filters/ClassFilter.java | 4 +- .../internal/ui/filters/ClosedProjectFilter.java | 8 +- .../internal/ui/filters/CustomFiltersDialog.java | 284 +- .../internal/ui/filters/FilterDescriptor.java | 198 +- .../phpdt/internal/ui/filters/FilterMessages.java | 23 +- .../ui/filters/ImportDeclarationFilter.java | 2 - .../phpdt/internal/ui/filters/InterfaceFilter.java | 4 +- .../phpdt/internal/ui/filters/JavaFileFilter.java | 33 +- .../internal/ui/filters/NamePatternFilter.java | 50 +- .../internal/ui/filters/NonJavaElementFilter.java | 22 +- .../internal/ui/filters/NonJavaProjectsFilter.java | 5 +- .../internal/ui/filters/NonPublicTypeFilter.java | 4 +- .../ui/filters/NonSharedProjectFilter.java | 9 +- .../internal/ui/filters/OutputFolderFilter.java | 46 +- .../ui/phpdocexport/JavadocExportMessages.java | 16 +- .../AbstractConfigurationBlockPreferencePage.java | 28 +- .../preferences/CodeAssistConfigurationBlock.java | 689 ++- .../ui/preferences/CodeAssistPreferencePage.java | 10 +- .../preferences/CodeFormatterPreferencePage.java | 513 +- .../internal/ui/preferences/CodeTemplateBlock.java | 956 ++-- .../ui/preferences/CodeTemplatePreferencePage.java | 28 +- .../phpdt/internal/ui/preferences/ColorEditor.java | 71 +- .../ui/preferences/CompilerConfigurationBlock.java | 1130 ++-- .../ui/preferences/CompilerPreferencePage.java | 20 +- .../ui/preferences/CompilerPropertyPage.java | 81 +- .../ui/preferences/EditTemplateDialog.java | 363 +- .../ui/preferences/FoldingConfigurationBlock.java | 266 +- .../preferences/IPreferenceConfigurationBlock.java | 23 +- .../JavaEditorHoverConfigurationBlock.java | 344 +- .../ui/preferences/JavaEditorPreferencePage.java | 3557 ++++++----- .../ui/preferences/JavaPreferencesSettings.java | 58 +- .../ui/preferences/JavaSourcePreviewerUpdater.java | 37 +- .../MarkOccurrencesConfigurationBlock.java | 255 +- .../preferences/MarkOccurrencesPreferencePage.java | 11 +- .../preferences/MembersOrderPreferenceCache.java | 192 +- .../ui/preferences/MembersOrderPreferencePage.java | 227 +- .../ui/preferences/MockupPreferenceStore.java | 41 +- .../ui/preferences/OptionsConfigurationBlock.java | 500 +- .../ui/preferences/OverlayPreferenceStore.java | 219 +- .../ui/preferences/PreferencesMessages.java | 15 +- .../ui/preferences/SpellingConfigurationBlock.java | 360 +- .../ui/preferences/SpellingPreferencePage.java | 16 +- .../TemplateEditorSourceViewerConfiguration.java | 118 +- .../ui/preferences/TodoTaskConfigurationBlock.java | 260 +- .../ui/preferences/TodoTaskInputDialog.java | 99 +- .../ui/preferences/TodoTaskPreferencePage.java | 22 +- .../ui/preferences/TodoTaskPropertyPage.java | 88 +- .../internal/ui/text/AbstractJavaScanner.java | 149 +- .../internal/ui/text/BufferedDocumentScanner.java | 99 +- .../phpdt/internal/ui/text/CombinedWordRule.java | 313 +- .../ui/text/CompositeReconcilingStrategy.java | 48 +- .../internal/ui/text/ContentAssistPreference.java | 567 +- .../ui/text/CustomSourceInformationControl.java | 162 +- .../ui/text/DocumentCharacterIterator.java | 69 +- .../internal/ui/text/FastJavaPartitionScanner.java | 64 +- .../phpdt/internal/ui/text/HTML2TextReader.java | 209 +- .../phpdt/internal/ui/text/HTMLPrinter.java | 84 +- .../phpdt/internal/ui/text/HTMLTextPresenter.java | 191 +- .../phpdt/internal/ui/text/IPHPPartitions.java | 20 +- .../phpdt/internal/ui/text/ITypingRunListener.java | 12 +- .../internal/ui/text/JavaAnnotationHover.java | 343 +- .../phpdt/internal/ui/text/JavaBreakIterator.java | 252 +- .../phpdt/internal/ui/text/JavaColorManager.java | 76 +- .../ui/text/JavaCompositeReconcilingStrategy.java | 216 +- .../internal/ui/text/JavaElementProvider.java | 28 +- .../internal/ui/text/JavaHeuristicScanner.java | 925 ++-- .../phpdt/internal/ui/text/JavaIndenter.java | 1341 +++-- .../ui/text/JavaOutlineInformationControl.java | 327 +- .../ui/text/JavaPresentationReconciler.java | 20 +- .../phpdt/internal/ui/text/JavaReconciler.java | 357 +- .../phpdt/internal/ui/text/JavaWordIterator.java | 98 +- .../phpdt/internal/ui/text/LineBreakingReader.java | 88 +- .../phpdt/internal/ui/text/PHPCodeReader.java | 469 +- .../phpdt/internal/ui/text/PHPPairMatcher.java | 331 +- .../phpdt/internal/ui/text/PreferencesAdapter.java | 46 +- .../ui/text/SequenceCharacterIterator.java | 57 +- .../internal/ui/text/SmartBackspaceManager.java | 163 +- .../ui/text/SmartSemicolonAutoEditStrategy.java | 1112 +++-- .../internal/ui/text/SubstitutionTextReader.java | 120 +- .../phpdt/internal/ui/text/Symbols.java | 92 +- .../phpdt/internal/ui/text/TypingRun.java | 64 +- .../phpdt/internal/ui/text/TypingRunDetector.java | 191 +- .../ui/text/comment/CommentFormattingContext.java | 23 +- .../folding/DefaultJavaFoldingPreferenceBlock.java | 58 +- .../DefaultJavaFoldingStructureProvider.java | 278 +- .../folding/EmptyJavaFoldingPreferenceBlock.java | 30 +- .../internal/ui/text/folding/FoldingMessages.java | 5 +- .../JavaFoldingStructureProviderDescriptor.java | 62 +- .../JavaFoldingStructureProviderRegistry.java | 66 +- .../internal/ui/text/java/IInvocationContext.java | 43 +- .../ui/text/java/IJavaReconcilingListener.java | 18 +- .../ui/text/java/IPHPCompletionProposal.java | 8 +- .../ui/text/java/IProblemRequestorExtension.java | 25 +- .../ui/text/java/IReconcilingParticipant.java | 4 +- .../ui/text/java/JavaFormattingStrategy.java | 78 +- .../internal/ui/text/java/JavaHoverMessages.java | 37 +- .../ui/text/java/JavaParameterListValidator.java | 190 +- .../ui/text/java/JavaReconcilingStrategy.java | 370 +- .../text/java/JavaStringAutoIndentStrategyDQ.java | 157 +- .../text/java/JavaStringAutoIndentStrategySQ.java | 157 +- .../text/java/PHPCompletionProposalComparator.java | 25 +- .../text/java/hover/AbstractAnnotationHover.java | 91 +- .../java/hover/AbstractJavaEditorTextHover.java | 132 +- .../ui/text/java/hover/AnnotationExpandHover.java | 166 +- .../java/hover/AnnotationExpansionControl.java | 447 +- .../ui/text/java/hover/AnnotationHover.java | 89 +- .../ui/text/java/hover/BestMatchHover.java | 49 +- .../java/hover/JavaEditorTextHoverDescriptor.java | 266 +- .../text/java/hover/JavaEditorTextHoverProxy.java | 11 +- .../ui/text/java/hover/JavaExpandHover.java | 116 +- .../ui/text/java/hover/JavaHoverMessages.java | 36 +- .../text/java/hover/JavaInformationProvider.java | 81 +- .../ui/text/java/hover/JavaSourceHover.java | 54 +- .../internal/ui/text/java/hover/JavaTypeHover.java | 27 +- .../internal/ui/text/java/hover/ProblemHover.java | 10 +- .../java/hover/SourceViewerInformationControl.java | 312 +- .../ui/text/link/ILinkedPositionListener.java | 30 +- .../ui/text/link/LinkedPositionListener.java | 36 +- .../ui/text/link/LinkedPositionManager.java | 687 ++- .../ui/text/link/LinkedPositionMessages.java | 15 +- .../internal/ui/text/link/LinkedPositionUI.java | 628 ++- .../internal/ui/text/link/ProposalPosition.java | 27 +- .../internal/ui/text/phpdoc/IHtmlTagConstants.java | 15 +- .../ui/text/phpdoc/IJavaDocTagConstants.java | 32 +- .../ui/text/phpdoc/JavaDocAutoIndentStrategy.java | 645 ++- .../internal/ui/text/phpdoc/PHPDocCodeScanner.java | 297 +- .../ui/text/phpdoc/PHPDocCompletionProcessor.java | 339 +- .../internal/ui/text/spelling/AddWordProposal.java | 23 +- .../ui/text/spelling/ChangeCaseProposal.java | 20 +- .../ui/text/spelling/HtmlTagDictionary.java | 12 +- .../ui/text/spelling/JavaDocTagDictionary.java | 10 +- .../ui/text/spelling/SpellCheckEngine.java | 136 +- .../ui/text/spelling/SpellCheckIterator.java | 173 +- .../ui/text/spelling/SpellReconcileDictionary.java | 10 +- .../ui/text/spelling/SpellReconcileStrategy.java | 159 +- .../ui/text/spelling/TaskTagDictionary.java | 11 +- .../ui/text/spelling/WordCorrectionProposal.java | 57 +- .../ui/text/spelling/WordIgnoreProposal.java | 27 +- .../spelling/engine/AbstractSpellDictionary.java | 236 +- .../engine/DefaultPhoneticDistanceAlgorithm.java | 77 +- .../engine/DefaultPhoneticHashProvider.java | 1145 ++-- .../text/spelling/engine/DefaultSpellChecker.java | 166 +- .../engine/IPhoneticDistanceAlgorithm.java | 4 +- .../spelling/engine/IPhoneticHashProvider.java | 2 +- .../ui/text/spelling/engine/ISpellCheckEngine.java | 32 +- .../spelling/engine/ISpellCheckPreferenceKeys.java | 25 +- .../ui/text/spelling/engine/ISpellChecker.java | 33 +- .../ui/text/spelling/engine/ISpellDictionary.java | 21 +- .../ui/text/spelling/engine/ISpellEvent.java | 3 +- .../text/spelling/engine/ISpellEventListener.java | 3 +- .../engine/LocaleSensitiveSpellDictionary.java | 16 +- .../spelling/engine/PersistentSpellDictionary.java | 9 +- .../text/spelling/engine/RankedWordProposal.java | 16 +- .../ui/text/spelling/engine/SpellEvent.java | 32 +- .../ui/text/template/AbstractProposal.java | 6 +- .../internal/ui/text/template/BuiltInEngine.java | 166 +- .../internal/ui/text/template/BuiltInProposal.java | 32 +- .../ui/text/template/DeclarationEngine.java | 498 +- .../ui/text/template/DeclarationProposal.java | 41 +- .../ui/text/template/IdentifierEngine.java | 182 +- .../ui/text/template/IdentifierProposal.java | 155 +- .../ui/text/template/LocalVariableProposal.java | 241 +- .../internal/ui/text/template/SQLProposal.java | 273 +- .../contentassist/InclusivePositionUpdater.java | 42 +- .../text/template/contentassist/MultiVariable.java | 40 +- .../template/contentassist/MultiVariableGuess.java | 192 +- .../PositionBasedCompletionProposal.java | 147 +- .../TemplateContentAssistMessages.java | 15 +- .../template/contentassist/TemplateEngine.java | 109 +- .../TemplateInformationControlCreator.java | 14 +- .../template/contentassist/TemplateProposal.java | 220 +- .../template/contentassist/VariablePosition.java | 26 +- .../preferences/TemplatePreferencesMessages.java | 15 +- .../preferences/TemplateVariableProcessor.java | 80 +- .../preferences/TemplateVariableProposal.java | 44 +- .../phpdt/internal/ui/util/DirectorySelector.java | 6 +- .../phpdt/internal/ui/util/ExceptionHandler.java | 54 +- .../phpdt/internal/ui/util/FilteredList.java | 442 +- .../phpdt/internal/ui/util/PHPElementVisitor.java | 26 +- .../phpdt/internal/ui/util/PHPFileSelector.java | 156 +- .../phpdt/internal/ui/util/PHPFileUtil.java | 32 +- .../phpdt/internal/ui/util/PHPProjectSelector.java | 12 +- .../phpdt/internal/ui/util/PixelConverter.java | 14 +- .../phpdt/internal/ui/util/ResourceSelector.java | 7 + .../phpdt/internal/ui/util/SWTUtil.java | 85 +- .../phpdt/internal/ui/util/StreamUtil.java | 41 +- .../phpdt/internal/ui/util/StringMatcher.java | 405 +- .../phpdt/internal/ui/util/TabFolderLayout.java | 37 +- .../internal/ui/util/TableLayoutComposite.java | 139 +- .../internal/ui/util/TwoArrayQuickSorter.java | 93 +- .../viewsupport/AppearanceAwareLabelProvider.java | 54 +- .../ui/viewsupport/ContainerCheckedTreeViewer.java | 24 +- .../viewsupport/DecoratingJavaLabelProvider.java | 82 +- .../internal/ui/viewsupport/FilterUpdater.java | 22 +- .../ui/viewsupport/IProblemChangedListener.java | 24 +- .../ui/viewsupport/ISelectionListenerWithAST.java | 27 +- .../ui/viewsupport/IViewPartInputProvider.java | 4 +- .../ui/viewsupport/ImageDescriptorRegistry.java | 51 +- .../ui/viewsupport/ImageImageDescriptor.java | 19 +- .../ui/viewsupport/JavaElementImageProvider.java | 792 ++-- .../internal/ui/viewsupport/JavaElementLabels.java | 1506 +++--- .../ui/viewsupport/JavaUILabelProvider.java | 152 +- .../ui/viewsupport/ListContentProvider.java | 16 +- .../internal/ui/viewsupport/MemberFilter.java | 66 +- .../ui/viewsupport/MemberFilterAction.java | 8 +- .../ui/viewsupport/ProblemMarkerManager.java | 132 +- .../ui/viewsupport/ProblemTableViewer.java | 44 +- .../internal/ui/viewsupport/ProblemTreeViewer.java | 51 +- .../ui/viewsupport/ResourceToItemsMapper.java | 120 +- .../SelectionListenerWithASTManager.java | 140 +- .../internal/ui/viewsupport/StatusBarUpdater.java | 58 +- .../ui/viewsupport/StorageLabelProvider.java | 78 +- .../internal/ui/wizards/IStatusChangeListener.java | 5 +- .../ui/wizards/NewClassCreationWizard.java | 33 +- .../internal/ui/wizards/NewElementWizard.java | 213 +- .../internal/ui/wizards/NewWizardMessages.java | 18 +- .../dialogfields/CheckedListDialogField.java | 123 +- .../ui/wizards/dialogfields/ComboDialogField.java | 139 +- .../ui/wizards/dialogfields/DialogField.java | 177 +- .../wizards/dialogfields/IDialogFieldListener.java | 2 +- .../ui/wizards/dialogfields/IListAdapter.java | 13 +- .../wizards/dialogfields/IStringButtonAdapter.java | 2 +- .../ui/wizards/dialogfields/ITreeListAdapter.java | 6 +- .../ui/wizards/dialogfields/LayoutUtil.java | 115 +- .../ui/wizards/dialogfields/ListDialogField.java | 644 +- .../dialogfields/SelectionButtonDialogField.java | 125 +- .../SelectionButtonDialogFieldGroup.java | 210 +- .../ui/wizards/dialogfields/Separator.java | 64 +- .../dialogfields/StringButtonDialogField.java | 86 +- .../StringButtonStatusDialogField.java | 123 +- .../ui/wizards/dialogfields/StringDialogField.java | 96 +- .../wizards/dialogfields/TreeListDialogField.java | 500 +- .../net/sourceforge/phpdt/ltk/core/CoreTexts.java | 2 +- .../phpdt/ltk/core/RenameIdentifierDelegate.java | 79 +- .../phpdt/ltk/core/RenameIdentifierInfo.java | 2 +- .../ltk/core/RenameIdentifierRefactoring.java | 4 +- .../ltk/core/RenameLocalVariableDelegate.java | 391 +- .../phpdt/ltk/core/RenamePHPProcessor.java | 111 +- .../src/net/sourceforge/phpdt/ltk/ui/UITexts.java | 2 +- .../phpdt/ltk/ui/actions/RenameLocalVariable.java | 49 +- .../phpdt/ltk/ui/actions/RenamePHPIdentifier.java | 32 +- .../phpdt/ltk/ui/wizards/RenameIdentifierPage.java | 303 +- .../ltk/ui/wizards/RenameIdentifierWizard.java | 49 +- .../ltk/ui/wizards/RenameLocalVariablePage.java | 7 +- .../ltk/ui/wizards/RenameLocalVariableWizard.java | 45 +- .../net/sourceforge/phpdt/ui/CodeGeneration.java | 510 ++- .../phpdt/ui/IContextMenuConstants.java | 132 +- .../phpdt/ui/IJavaElementSearchConstants.java | 45 +- .../sourceforge/phpdt/ui/IPackagesViewPart.java | 15 +- .../phpdt/ui/ITypeHierarchyViewPart.java | 48 +- .../sourceforge/phpdt/ui/IWorkingCopyManager.java | 69 +- .../phpdt/ui/IWorkingCopyManagerExtension.java | 25 +- .../sourceforge/phpdt/ui/IWorkingCopyProvider.java | 16 +- .../phpdt/ui/JavaElementImageDescriptor.java | 217 +- .../phpdt/ui/JavaElementLabelProvider.java | 209 +- .../sourceforge/phpdt/ui/JavaElementSorter.java | 302 +- .../src/net/sourceforge/phpdt/ui/JavaUI.java | 1058 ++-- .../phpdt/ui/OverrideIndicatorLabelDecorator.java | 169 +- .../sourceforge/phpdt/ui/PreferenceConstants.java | 5568 +++++++++-------- .../phpdt/ui/ProblemsLabelDecorator.java | 324 +- .../ui/StandardJavaElementContentProvider.java | 482 +- .../phpdt/ui/actions/CustomFiltersActionGroup.java | 605 ++- .../phpdt/ui/actions/GenerateActionGroup.java | 458 +- .../ui/actions/GotoMatchingBracketAction.java | 13 +- .../phpdt/ui/actions/MemberFilterActionGroup.java | 278 +- .../phpdt/ui/actions/OpenEditorActionGroup.java | 71 +- .../phpdt/ui/actions/OpenPHPPerspectiveAction.java | 27 +- .../ui/actions/PHPEditorActionDefinitionIds.java | 69 +- .../phpdt/ui/actions/PHPdtActionConstants.java | 176 +- .../phpdt/ui/actions/SelectionDispatchAction.java | 126 +- .../sourceforge/phpdt/ui/text/IColorManager.java | 33 +- .../phpdt/ui/text/IColorManagerExtension.java | 24 +- .../phpdt/ui/text/IJavaColorConstants.java | 83 +- .../sourceforge/phpdt/ui/text/JavaTextTools.java | 1341 +++-- .../ui/text/PHPSourceViewerConfiguration.java | 1912 ++++--- .../phpdt/ui/text/PHPStringDQCodeScanner.java | 146 +- .../phpdt/ui/text/SingleTokenPHPScanner.java | 15 +- .../text/folding/IJavaFoldingPreferenceBlock.java | 15 +- .../folding/IJavaFoldingStructureProvider.java | 8 +- .../ui/text/java/hover/IJavaEditorTextHover.java | 13 +- .../phpdt/ui/wizards/NewClassWizardPage.java | 459 +- .../phpdt/ui/wizards/NewContainerWizardPage.java | 506 +- .../phpdt/ui/wizards/NewElementWizardPage.java | 48 +- .../phpdt/ui/wizards/NewTypeWizardPage.java | 3513 ++++++----- .../phpeclipse/IPreferenceConstants.java | 589 +- .../net/sourceforge/phpeclipse/LoadPathEntry.java | 47 +- .../src/net/sourceforge/phpeclipse/PHPConsole.java | 168 +- .../phpeclipse/PHPPerspectiveFactory.java | 1 + .../sourceforge/phpeclipse/PHPeclipsePlugin.java | 2854 +++++---- .../phpeclipse/actions/IncludesScanner.java | 305 +- .../actions/OpenDeclarationEditorAction.java | 451 +- .../phpeclipse/actions/PHPActionMessages.java | 8 +- .../phpeclipse/actions/PHPEclipseShowAction.java | 209 +- .../actions/PHPOpenAllIncludesEditorAction.java | 378 +- .../actions/PHPOpenDeclarationAction.java | 146 +- .../actions/PHPOpenDeclarationEditorAction.java | 83 +- .../phpeclipse/builder/ExternalEditorInput.java | 147 +- .../builder/ExternalStorageDocumentProvider.java | 67 +- .../phpeclipse/builder/FileStorage.java | 196 +- .../phpeclipse/builder/IdentifierIndexManager.java | 1884 +++--- .../phpeclipse/builder/PHPIdentifierLocation.java | 363 +- .../phpeclipse/obfuscator/ObfuscatorIgnoreSet.java | 265 +- .../phpeclipse/obfuscator/ObfuscatorIgnores.java | 184 +- .../phpeclipse/obfuscator/ObfuscatorMessages.java | 15 +- .../obfuscator/ObfuscatorPass1Exporter.java | 411 +- .../obfuscator/ObfuscatorPass2Exporter.java | 639 +- .../phpeclipse/obfuscator/PHPIdentifier.java | 212 +- .../export/ObfuscatorExportMessages.java | 68 +- .../export/ObfuscatorExportOperation.java | 1291 +++-- .../obfuscator/export/ObfuscatorExportWizard.java | 148 +- .../WizardObfuscatorResourceExportPage1.java | 343 +- .../phpeclipse/phpeditor/AnnotationType.java | 46 +- .../phpeditor/BasicEditorActionContributor.java | 126 +- .../BasicJavaEditorActionContributor.java | 335 +- .../phpeclipse/phpeditor/BracketPainter.java | 86 +- .../phpeditor/BreakpointImageProvider.java | 15 +- .../CompilationUnitAnnotationModelEvent.java | 44 +- .../CompilationUnitEditorActionContributor.java | 85 +- .../phpeclipse/phpeditor/CustomBufferFactory.java | 28 +- .../phpeclipse/phpeditor/DocumentAdapter.java | 274 +- .../phpeditor/EditorHighlightingSynchronizer.java | 33 +- .../phpeclipse/phpeditor/EditorUtility.java | 350 +- .../phpeclipse/phpeditor/GotoAnnotationAction.java | 11 +- .../phpeclipse/phpeditor/GotoErrorAction.java | 11 +- .../phpeditor/HTMLDocumentSetupParticipant.java | 26 +- .../ICompilationUnitDocumentProvider.java | 60 +- .../phpeclipse/phpeditor/IJavaAnnotation.java | 63 +- .../phpeditor/IJavaEditorActionConstants.java | 9 +- .../sourceforge/phpeclipse/phpeditor/IPainter.java | 61 +- .../phpeclipse/phpeditor/IPositionManager.java | 5 +- .../phpeclipse/phpeditor/IProblemAnnotation.java | 35 +- .../phpeclipse/phpeditor/ISavePolicy.java | 11 +- .../phpeditor/JavaAnnotationImageProvider.java | 149 +- .../phpeditor/JavaAnnotationIterator.java | 53 +- .../phpeclipse/phpeditor/JavaDocumentFactory.java | 21 +- .../phpeditor/JavaDocumentSetupParticipant.java | 29 +- .../phpeditor/JavaEditorErrorTickUpdater.java | 53 +- .../phpeclipse/phpeditor/JavaMarkerAnnotation.java | 90 +- .../phpeclipse/phpeditor/JavaOutlinePage.java | 1554 +++--- .../phpeditor/JavaSelectMarkerRulerAction.java | 86 +- .../phpeditor/JavaSelectMarkerRulerAction2.java | 72 +- .../phpeditor/JavaSelectRulerAction.java | 10 +- .../phpeclipse/phpeditor/JavaSourceViewer.java | 359 +- .../phpeditor/JavaStorageDocumentProvider.java | 37 +- .../phpeclipse/phpeditor/LinePainter.java | 121 +- .../phpeclipse/phpeditor/PHPAnnotationHover.java | 316 +- .../phpeclipse/phpeditor/PHPDocumentProvider.java | 2082 ++++--- .../phpeclipse/phpeditor/PHPEditor.java | 1243 +++-- .../phpeditor/PHPEditorActionDefinitionIds.java | 110 +- .../phpeclipse/phpeditor/PHPEditorMessages.java | 3 +- .../phpeclipse/phpeditor/PHPSyntaxRdr.java | 563 +- .../phpeclipse/phpeditor/PHPTextHover.java | 44 +- .../phpeclipse/phpeditor/PHPUnitEditor.java | 4720 ++++++++------- .../phpeclipse/phpeditor/PaintManager.java | 159 +- .../phpeditor/PartiallySynchronizedDocument.java | 139 +- .../phpeclipse/phpeditor/PresentationAction.java | 85 +- .../phpeclipse/phpeditor/PrintMarginPainter.java | 69 +- .../phpeditor/ProblemAnnotationIterator.java | 29 +- .../phpeclipse/phpeditor/ProblemPainter.java | 214 +- .../phpeditor/SmartyDocumentSetupParticipant.java | 27 +- .../phpeclipse/phpeditor/ToggleCommentAction.java | 310 +- .../phpeditor/TogglePresentationAction.java | 87 +- .../phpeclipse/phpeditor/WorkingCopyManager.java | 42 +- .../phpeclipse/phpeditor/actions/RTrimAction.java | 48 +- .../phpeclipse/phpeditor/php/HTMLCodeScanner.java | 317 +- .../phpeditor/php/HTMLCompletionProcessor.java | 513 +- .../phpeditor/php/HTMLPartitionScanner.java | 844 ++-- .../phpeditor/php/HTMLWordExtractor.java | 127 +- .../phpeditor/php/PHPAutoIndentStrategy.java | 305 +- .../phpeclipse/phpeditor/php/PHPCodeScanner.java | 76 +- .../phpeditor/php/PHPCompletionProcessor.java | 566 +- .../phpeclipse/phpeditor/php/PHPConstant.java | 41 +- .../phpeditor/php/PHPDocumentPartitioner.java | 112 +- .../phpeditor/php/PHPDoubleClickSelector.java | 79 +- .../phpeditor/php/PHPEditorMessages.java | 39 +- .../phpeclipse/phpeditor/php/PHPElement.java | 72 +- .../phpeclipse/phpeditor/php/PHPFunction.java | 40 +- .../phpeclipse/phpeditor/php/PHPKeyword.java | 40 +- .../phpeditor/php/PHPPartitionScanner.java | 18 +- .../phpeclipse/phpeditor/php/PHPType.java | 13 +- .../phpeclipse/phpeditor/php/PHPWordExtractor.java | 39 +- .../phpeditor/php/SmartyCodeScanner.java | 336 +- .../phpeditor/php/SmartyDocCodeScanner.java | 317 +- .../phpeditor/util/HTMLWordDetector.java | 33 +- .../phpeditor/util/PHPColorProvider.java | 123 +- .../phpeditor/util/PHPVariableDetector.java | 33 +- .../phpeditor/util/PHPWhitespaceDetector.java | 22 +- .../phpeclipse/phpeditor/util/PHPWordDetector.java | 28 +- .../phpeclipse/preferences/ColorEditor.java | 71 +- .../preferences/OverlayPreferenceStore.java | 853 ++-- .../preferences/PHPPreferencesMessages.java | 15 +- .../preferences/PHPProjectLibraryPage.java | 251 +- .../preferences/PHPProjectPropertyPage.java | 153 +- .../phpeclipse/wizards/HTMLFileWizard.java | 258 +- .../phpeclipse/wizards/HTMLFileWizardPage.java | 306 +- .../wizards/NewProjectCreationWizard.java | 49 +- .../phpeclipse/wizards/PHPFileWizard.java | 354 +- .../phpeclipse/wizards/PHPFileWizardPage.java | 38 +- .../phpeclipse/wizards/PHPWizardMessages.java | 24 +- .../phpeclipse/wizards/TempnewPHPProject.java | 133 +- .../phpeclipse/wizards/html/EditElementWizard.java | 191 +- .../wizards/html/EditElementWizardPage.java | 304 +- .../phpeclipse/wizards/html/ElementWriter.java | 88 +- .../wizards/html/FormElementWizardPage.java | 30 +- .../phpeclipse/wizards/html/HTMLUtilities.java | 30 +- .../phpeclipse/wizards/html/IPreviewer.java | 6 +- .../wizards/html/InsertHTMLElementAction.java | 19 +- .../wizards/html/ListElementWizardPage.java | 62 +- .../wizards/html/NewElementWizardPage.java | 40 +- .../phpeclipse/wizards/html/NumVerifyListener.java | 9 +- .../wizards/html/SomeItemInputDialog.java | 54 +- .../phpeclipse/wizards/html/StringDivider.java | 38 +- .../wizards/html/TableElementCellModifier.java | 36 +- .../wizards/html/TableElementContentProvider.java | 6 +- .../wizards/html/TableElementLabelProvider.java | 11 +- .../phpeclipse/wizards/html/TableElementModel.java | 205 +- .../wizards/html/TableElementWizardPage.java | 489 +- .../wizards/html/UnknownElementWizardPage.java | 204 +- 1311 files changed, 183122 insertions(+), 152011 deletions(-) diff --git a/net.sourceforge.phpeclipse.core/src/net/sourceforge/phpeclipse/core/WebCore.java b/net.sourceforge.phpeclipse.core/src/net/sourceforge/phpeclipse/core/WebCore.java index 52621b2..33b1e66 100644 --- a/net.sourceforge.phpeclipse.core/src/net/sourceforge/phpeclipse/core/WebCore.java +++ b/net.sourceforge.phpeclipse.core/src/net/sourceforge/phpeclipse/core/WebCore.java @@ -8,14 +8,14 @@ * Contributors: * Christopher Lenz - initial API and implementation * - * $Id: WebCore.java,v 1.1 2004-09-02 18:05:22 jsurfer Exp $ + * $Id: WebCore.java,v 1.2 2006-10-21 23:14:29 pombredanne Exp $ */ package net.sourceforge.phpeclipse.core; import org.eclipse.core.runtime.Plugin; -//import net.sourceforge.phpeclipse.core.parser.ISourceParser; +// import net.sourceforge.phpeclipse.core.parser.ISourceParser; /** * The main plugin class to be used in the desktop. @@ -49,12 +49,13 @@ public class WebCore extends Plugin { * Creates and returns a parser that can handle resources of the specified * MIME type. * - * @param mimeType the MIME type of the resource for which a parser should - * be created + * @param mimeType + * the MIME type of the resource for which a parser should be + * created * @return the instantiated parser, or null if no parser for that * MIME type is registered */ -// public ISourceParser createParser(String mimeType) { -// return null; -// } + // public ISourceParser createParser(String mimeType) { + // return null; + // } } diff --git a/net.sourceforge.phpeclipse.core/src/net/sourceforge/phpeclipse/core/model/ISourceModel.java b/net.sourceforge.phpeclipse.core/src/net/sourceforge/phpeclipse/core/model/ISourceModel.java index 7c63cbb..e2d2c83 100644 --- a/net.sourceforge.phpeclipse.core/src/net/sourceforge/phpeclipse/core/model/ISourceModel.java +++ b/net.sourceforge.phpeclipse.core/src/net/sourceforge/phpeclipse/core/model/ISourceModel.java @@ -8,7 +8,7 @@ * Contributors: * Christopher Lenz - initial implementation * - * $Id: ISourceModel.java,v 1.1 2004-09-02 18:05:21 jsurfer Exp $ + * $Id: ISourceModel.java,v 1.2 2006-10-21 23:14:29 pombredanne Exp $ */ package net.sourceforge.phpeclipse.core.model; @@ -28,7 +28,8 @@ public interface ISourceModel { /** * Returns the elements that are direct children of the given element. * - * @param element the element for which to return the child elements + * @param element + * the element for which to return the child elements * @return an array of child elements, or an empty array if the given * element has no children */ @@ -37,7 +38,8 @@ public interface ISourceModel { /** * Returns the direct parent element of the specified element. * - * @param element the element for which the parent should be returned + * @param element + * the element for which the parent should be returned * @return the parent element, or null if the specified element * does not have a parent (meaning it is a top-level element) */ diff --git a/net.sourceforge.phpeclipse.core/src/net/sourceforge/phpeclipse/core/model/ISourceReference.java b/net.sourceforge.phpeclipse.core/src/net/sourceforge/phpeclipse/core/model/ISourceReference.java index b5efffa..2954ba4 100644 --- a/net.sourceforge.phpeclipse.core/src/net/sourceforge/phpeclipse/core/model/ISourceReference.java +++ b/net.sourceforge.phpeclipse.core/src/net/sourceforge/phpeclipse/core/model/ISourceReference.java @@ -8,7 +8,7 @@ * Contributors: * Christopher Lenz - initial API * - * $Id: ISourceReference.java,v 1.1 2004-09-02 18:05:21 jsurfer Exp $ + * $Id: ISourceReference.java,v 1.2 2006-10-21 23:14:29 pombredanne Exp $ */ package net.sourceforge.phpeclipse.core.model; @@ -24,12 +24,12 @@ public interface ISourceReference { * Returns the source code associated with this model element. * *

- * This method extracts the substring from the source buffer containing - * this source element. This corresponds to the source regione that would - * be returned by {@link ISourceReference#getSourceRegion()}. + * This method extracts the substring from the source buffer containing this + * source element. This corresponds to the source regione that would be + * returned by {@link ISourceReference#getSourceRegion()}. *

* - * @return The source code, or null if this element has no + * @return The source code, or null if this element has no * associated source code */ String getSource(); @@ -37,7 +37,7 @@ public interface ISourceReference { /** * Returns the source range associated with this element. * - * @return The source region, or null if this element has no + * @return The source region, or null if this element has no * associated source code */ IRegion getSourceRegion(); diff --git a/net.sourceforge.phpeclipse.core/src/net/sourceforge/phpeclipse/core/model/SourceReference.java b/net.sourceforge.phpeclipse.core/src/net/sourceforge/phpeclipse/core/model/SourceReference.java index ece105c..72b5c82 100644 --- a/net.sourceforge.phpeclipse.core/src/net/sourceforge/phpeclipse/core/model/SourceReference.java +++ b/net.sourceforge.phpeclipse.core/src/net/sourceforge/phpeclipse/core/model/SourceReference.java @@ -8,7 +8,7 @@ * Contributors: * Christopher Lenz - initial API and implementation * - * $Id: SourceReference.java,v 1.1 2004-09-02 18:05:21 jsurfer Exp $ + * $Id: SourceReference.java,v 1.2 2006-10-21 23:14:29 pombredanne Exp $ */ package net.sourceforge.phpeclipse.core.model; @@ -19,8 +19,7 @@ import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.Region; /** - * Default implementation of {@link ISourceReference} based on - * {@link IDocument}. + * Default implementation of {@link ISourceReference} based on {@link IDocument}. */ public class SourceReference implements ISourceReference { @@ -37,7 +36,8 @@ public class SourceReference implements ISourceReference { /** * Constructor. * - * @param document The document that contains the source reference + * @param document + * The document that contains the source reference */ public SourceReference(IDocument document) { this(document, 0, 0); @@ -46,7 +46,8 @@ public class SourceReference implements ISourceReference { /** * Constructor. * - * @param document The document that contains the source reference + * @param document + * The document that contains the source reference */ public SourceReference(IDocument document, int offset) { this(document, offset, 0); @@ -55,7 +56,8 @@ public class SourceReference implements ISourceReference { /** * Constructor. * - * @param document The document that contains the source reference + * @param document + * The document that contains the source reference */ public SourceReference(IDocument document, int offset, int length) { this.document = document; @@ -69,11 +71,11 @@ public class SourceReference implements ISourceReference { */ public String getSource() { try { - return document.get(sourceRegion.getOffset(), - sourceRegion.getLength()); + return document.get(sourceRegion.getOffset(), sourceRegion + .getLength()); } catch (BadLocationException e) { throw new IllegalStateException( - "Model not synchronized with document"); //$NON-NLS-1$ + "Model not synchronized with document"); //$NON-NLS-1$ } } @@ -89,8 +91,10 @@ public class SourceReference implements ISourceReference { /** * Sets the source region covered by the element. * - * @param offset the offset of the region - * @param length the length of the region + * @param offset + * the offset of the region + * @param length + * the length of the region */ public final void setSourceRegion(int offset, int length) { sourceRegion = new Region(offset, length); @@ -99,7 +103,8 @@ public class SourceReference implements ISourceReference { /** * Sets the source region covered by the element. * - * @param region the source region to set + * @param region + * the source region to set */ public final void setSourceRegion(IRegion region) { setSourceRegion(region.getOffset(), region.getLength()); diff --git a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/debug/core/PHPDebugModel.java b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/debug/core/PHPDebugModel.java index 63231ae..7da4a4d 100644 --- a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/debug/core/PHPDebugModel.java +++ b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/debug/core/PHPDebugModel.java @@ -1,14 +1,14 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html -Contributors: - IBM Corporation - Initial implementation - Vicente Fernando - www.alfersoft.com.ar -**********************************************************************/ + Contributors: + IBM Corporation - Initial implementation + Vicente Fernando - www.alfersoft.com.ar + **********************************************************************/ package net.sourceforge.phpdt.debug.core; import java.util.HashMap; @@ -28,109 +28,131 @@ import org.eclipse.debug.core.model.IBreakpoint; * Provides utility methods for creating debug targets and breakpoints specific * to the PHP debug model. *

- * Clients are not intended to instantiate or subclass this class; - * this class provides static utility methods only. + * Clients are not intended to instantiate or subclass this class; this class + * provides static utility methods only. *

*/ public class PHPDebugModel { - + /** * Not to be instantiated. */ private PHPDebugModel() { super(); } - + /** * Returns the identifier for the PHP debug model plug-in - * + * * @return plugin identifier */ -// public static String getPluginIdentifier() { -// return PHPDebugCorePlugin.getUniqueIdentifier(); -// } - + // public static String getPluginIdentifier() { + // return PHPDebugCorePlugin.getUniqueIdentifier(); + // } /** - * Creates and returns a line breakpoint in the type with - * at the given line number. The marker associated with the - * breakpoint will be created on the specified resource. If a character - * range within the line is known, it may be specified by charStart/charEnd. - * If hitCount is > 0, the breakpoint will suspend execution when it is - * "hit" the specified number of times. + * Creates and returns a line breakpoint in the type with at the given line + * number. The marker associated with the breakpoint will be created on the + * specified resource. If a character range within the line is known, it may + * be specified by charStart/charEnd. If hitCount is > 0, the breakpoint + * will suspend execution when it is "hit" the specified number of times. * - * @param resource the resource on which to create the associated breakpoint - * marker - * @param lineNumber the lineNumber on which the breakpoint is set - line - * numbers are 1 based, associated with the source file in which - * the breakpoint is set - * @param charStart the first character index associated with the breakpoint, - * or -1 if unspecified, in the source file in which the breakpoint is set - * @param charEnd the last character index associated with the breakpoint, - * or -1 if unspecified, in the source file in which the breakpoint is set - * @param hitCount the number of times the breakpoint will be hit before - * suspending execution - 0 if it should always suspend - * @param register whether to add this breakpoint to the breakpoint manager - * @param attributes a map of client defined attributes that should be assigned - * to the underlying breakpoint marker on creation, or null if none. + * @param resource + * the resource on which to create the associated breakpoint + * marker + * @param lineNumber + * the lineNumber on which the breakpoint is set - line numbers + * are 1 based, associated with the source file in which the + * breakpoint is set + * @param charStart + * the first character index associated with the breakpoint, or + * -1 if unspecified, in the source file in which the breakpoint + * is set + * @param charEnd + * the last character index associated with the breakpoint, or -1 + * if unspecified, in the source file in which the breakpoint is + * set + * @param hitCount + * the number of times the breakpoint will be hit before + * suspending execution - 0 if it should always suspend + * @param register + * whether to add this breakpoint to the breakpoint manager + * @param attributes + * a map of client defined attributes that should be assigned to + * the underlying breakpoint marker on creation, or + * null if none. * @return a line breakpoint - * @exception CoreException If this method fails. Reasons include: + * @exception CoreException + * If this method fails. Reasons include: + * * @since 2.0 */ - public static void createLineBreakpoint(IResource resource, int lineNumber, int charStart, int charEnd, int hitCount, boolean register, Map attributes) throws CoreException { + public static void createLineBreakpoint(IResource resource, int lineNumber, + int charStart, int charEnd, int hitCount, boolean register, + Map attributes) throws CoreException { if (attributes == null) { attributes = new HashMap(10); } - new PHPLineBreakpoint(resource, lineNumber, charStart, charEnd, hitCount, true, attributes); + new PHPLineBreakpoint(resource, lineNumber, charStart, charEnd, + hitCount, true, attributes); } - - public static PHPLineBreakpoint createLineBreakpoint(IResource resource, int lineNumber, int hitCount, boolean register, Map attributes) throws CoreException { + + public static PHPLineBreakpoint createLineBreakpoint(IResource resource, + int lineNumber, int hitCount, boolean register, Map attributes) + throws CoreException { if (attributes == null) { attributes = new HashMap(10); } - return new PHPLineBreakpoint(resource, lineNumber, hitCount, true, attributes); + return new PHPLineBreakpoint(resource, lineNumber, hitCount, true, + attributes); } - /** * Returns true if line breakpoint is already registered with the breakpoint * manager for the given line number. * - * @param typeName fully qualified type name - * @param lineNumber line number + * @param typeName + * fully qualified type name + * @param lineNumber + * line number * @return true if line breakpoint is already registered with the breakpoint - * manager for the given line number or false - * if no such breakpoint is registered - * @exception CoreException If this method fails. + * manager for the given line number or false if no + * such breakpoint is registered + * @exception CoreException + * If this method fails. */ - public static PHPLineBreakpoint lineBreakpointExists(int lineNumber) throws CoreException { - String modelId= PHPDebugCorePlugin.PLUGIN_ID; // getPluginIdentifier(); - String markerType= PHPLineBreakpoint.getMarkerType(); - IBreakpointManager manager= DebugPlugin.getDefault().getBreakpointManager(); - IBreakpoint[] breakpoints= manager.getBreakpoints(modelId); + public static PHPLineBreakpoint lineBreakpointExists(int lineNumber) + throws CoreException { + String modelId = PHPDebugCorePlugin.PLUGIN_ID; // getPluginIdentifier(); + String markerType = PHPLineBreakpoint.getMarkerType(); + IBreakpointManager manager = DebugPlugin.getDefault() + .getBreakpointManager(); + IBreakpoint[] breakpoints = manager.getBreakpoints(modelId); for (int i = 0; i < breakpoints.length; i++) { if (!(breakpoints[i] instanceof PHPLineBreakpoint)) { continue; } PHPLineBreakpoint breakpoint = (PHPLineBreakpoint) breakpoints[i]; if (breakpoint.getMarker().getType().equals(markerType)) { - if (breakpoint.getLineNumber() == lineNumber) { - return breakpoint; - } + if (breakpoint.getLineNumber() == lineNumber) { + return breakpoint; + } } } return null; - } + } /** - * Returns the preference store for this plug-in or null - * if the store is not available. + * Returns the preference store for this plug-in or null if + * the store is not available. * * @return the preference store for this plug-in */ public static Preferences getPreferences() { - PHPDebugCorePlugin deflt= PHPDebugCorePlugin.getDefault(); + PHPDebugCorePlugin deflt = PHPDebugCorePlugin.getDefault(); if (deflt != null) { return deflt.getPluginPreferences(); } @@ -145,50 +167,48 @@ public class PHPDebugModel { public static void savePreferences() { PHPDebugCorePlugin.getDefault().savePluginPreferences(); } - + /** - * Creates and returns a debug target for the given VM, with - * the specified name, and associates the debug target with the - * given process for console I/O. The allow terminate flag specifies whether - * the debug target will support termination (ITerminate). - * The allow disconnect flag specifies whether the debug target will - * support disconnection (IDisconnect). The resume - * flag specifies if the target VM should be resumed on startup (has - * no effect if the VM was already running when the connection to the + * Creates and returns a debug target for the given VM, with the specified + * name, and associates the debug target with the given process for console + * I/O. The allow terminate flag specifies whether the debug target will + * support termination (ITerminate). The allow disconnect + * flag specifies whether the debug target will support disconnection (IDisconnect). + * The resume flag specifies if the target VM should be resumed on startup + * (has no effect if the VM was already running when the connection to the * VM was esatbished). Launching the actual VM is a client responsibility. * The debug target is added to the given launch. - * - * @param launch the launch the new debug target will be contained in - * @param vm the VM to create a debug target for - * @param name the name to associate with the VM, which will be - * returned from IDebugTarget.getName. If null - * the name will be retrieved from the underlying VM. - * @param process the process to associate with the debug target, - * which will be returned from IDebugTarget.getProcess - * @param allowTerminate whether the target will support termianation - * @param allowDisconnect whether the target will support disconnection - * @param resume whether the target is to be resumed on startup. Has - * no effect if the target was already running when the connection - * to the VM was established. + * + * @param launch + * the launch the new debug target will be contained in + * @param vm + * the VM to create a debug target for + * @param name + * the name to associate with the VM, which will be returned from + * IDebugTarget.getName. If null + * the name will be retrieved from the underlying VM. + * @param process + * the process to associate with the debug target, which will be + * returned from IDebugTarget.getProcess + * @param allowTerminate + * whether the target will support termianation + * @param allowDisconnect + * whether the target will support disconnection + * @param resume + * whether the target is to be resumed on startup. Has no effect + * if the target was already running when the connection to the + * VM was established. * @return a debug target * @see org.eclipse.debug.core.model.ITerminate * @see org.eclipse.debug.core.model.IDisconnect * @since 2.0 */ /* - public static IDebugTarget newDebugTarget(final ILaunch launch, final String name, final IProcess process) { - final IDebugTarget[] target = new IDebugTarget[1]; - IWorkspaceRunnable r = new IWorkspaceRunnable() { - public void run(IProgressMonitor m) { - target[0]= new PHPDebugTarget(launch, process); - } - }; - try { - ResourcesPlugin.getWorkspace().run(r, null); - } catch (CoreException e) { - //PHPDebugPlugin.log(e); - } - return target[0]; - } - */ + * public static IDebugTarget newDebugTarget(final ILaunch launch, final + * String name, final IProcess process) { final IDebugTarget[] target = new + * IDebugTarget[1]; IWorkspaceRunnable r = new IWorkspaceRunnable() { public + * void run(IProgressMonitor m) { target[0]= new PHPDebugTarget(launch, + * process); } }; try { ResourcesPlugin.getWorkspace().run(r, null); } catch + * (CoreException e) { //PHPDebugPlugin.log(e); } return target[0]; } + */ } diff --git a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/PHPDBGMod.java b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/PHPDBGMod.java index f973f8d..b393a07 100644 --- a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/PHPDBGMod.java +++ b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/PHPDBGMod.java @@ -1,25 +1,26 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - Vicente Fernando - www.alfersoft.com.ar - Initial implementation -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + Vicente Fernando - www.alfersoft.com.ar - Initial implementation + **********************************************************************/ package net.sourceforge.phpdt.internal.debug.core; public class PHPDBGMod { private int modNo; + private String modName; public PHPDBGMod() { } public PHPDBGMod(int modNo, String modName) { - this.modNo= modNo; - this.modName= modName; + this.modNo = modNo; + this.modName = modName; } public int getNo() { @@ -31,10 +32,10 @@ public class PHPDBGMod { } public void setNo(int modNo) { - this.modNo= modNo; + this.modNo = modNo; } public void setName(String modName) { - this.modName= modName; + this.modName = modName; } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/PHPDebugCorePlugin.java b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/PHPDebugCorePlugin.java index 4efdb76..8e080dd 100644 --- a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/PHPDebugCorePlugin.java +++ b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/PHPDebugCorePlugin.java @@ -18,16 +18,19 @@ import org.osgi.framework.BundleContext; * The main plugin class to be used in the desktop. */ public class PHPDebugCorePlugin extends AbstractUIPlugin { - // The shared instance. + // The shared instance. protected static PHPDebugCorePlugin plugin; + public static final String PLUGIN_ID = "net.sourceforge.phpeclipse.debug.core"; //$NON-NLS-1$ - + public static IWorkbenchPage getActivePage() { return getDefault().internalGetActivePage(); } + public static Shell getActiveWorkbenchShell() { return getActiveWorkbenchWindow().getShell(); } + public static IWorkbenchWindow getActiveWorkbenchWindow() { return getDefault().getWorkbench().getActiveWorkbenchWindow(); } @@ -36,19 +39,20 @@ public class PHPDebugCorePlugin extends AbstractUIPlugin { * Returns the shared instance. */ public static PHPDebugCorePlugin getDefault() { - return plugin; + return plugin; } - + public static String getFormattedMessage(String key, String arg) { String text = getResourceString(key); return java.text.MessageFormat.format(text, new Object[] { arg }); } + public static String getResourceString(String key) { ResourceBundle bundle = plugin.getResourceBundle(); if (bundle != null) { try { String bundleString = bundle.getString(key); - //return "$"+bundleString; + // return "$"+bundleString; return bundleString; } catch (MissingResourceException e) { // default actions is to return key, which is OK @@ -70,10 +74,11 @@ public class PHPDebugCorePlugin extends AbstractUIPlugin { public static IWorkspace getWorkspace() { return PHPeclipsePlugin.getWorkspace(); } - + public static void log(int severity, String message) { - Status status = new Status(severity, PLUGIN_ID, IStatus.OK, message, null) ; - PHPDebugCorePlugin.log(status) ; + Status status = new Status(severity, PLUGIN_ID, IStatus.OK, message, + null); + PHPDebugCorePlugin.log(status); } public static void log(IStatus status) { @@ -81,9 +86,12 @@ public class PHPDebugCorePlugin extends AbstractUIPlugin { } public static void log(Throwable e) { - log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.ERROR, "PHPLaunchingPlugin.internalErrorOccurred", e)); //$NON-NLS-1$ + log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.ERROR, + "PHPLaunchingPlugin.internalErrorOccurred", e)); //$NON-NLS-1$ } + private ResourceBundle resourceBundle; + /** * The constructor. */ @@ -91,30 +99,28 @@ public class PHPDebugCorePlugin extends AbstractUIPlugin { super(); plugin = this; try { - resourceBundle = - ResourceBundle.getBundle( - "net.sourceforge.phpdt.internal.debug.core.debugresources"); //$NON-NLS-1$ + resourceBundle = ResourceBundle + .getBundle("net.sourceforge.phpdt.internal.debug.core.debugresources"); //$NON-NLS-1$ } catch (MissingResourceException x) { resourceBundle = null; } - } - + } + public java.util.ResourceBundle getResourceBundle() { return resourceBundle; } - + private IWorkbenchPage internalGetActivePage() { return getWorkbench().getActiveWorkbenchWindow().getActivePage(); } - + /** * @see Plugin#shutdown() */ -/* public void shutdown() throws CoreException { - plugin = null; - super.shutdown(); - } -*/ + /* + * public void shutdown() throws CoreException { plugin = null; + * super.shutdown(); } + */ /** * This method is called upon plug-in activation */ @@ -126,7 +132,7 @@ public class PHPDebugCorePlugin extends AbstractUIPlugin { * This method is called when the plug-in is stopped */ public void stop(BundleContext context) throws Exception { - plugin=null; + plugin = null; super.stop(context); } } diff --git a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/PHPDegugCorePluginImages.java b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/PHPDegugCorePluginImages.java index 42de200..cb042db 100644 --- a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/PHPDegugCorePluginImages.java +++ b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/PHPDegugCorePluginImages.java @@ -19,130 +19,162 @@ import org.eclipse.swt.graphics.Image; public class PHPDegugCorePluginImages { - private final static URL BASE_URL = - PHPDebugCorePlugin.getDefault().getBundle().getEntry("/"); + private final static URL BASE_URL = PHPDebugCorePlugin.getDefault() + .getBundle().getEntry("/"); - private final static ImageRegistry PLUGIN_REGISTRY = - PHPDebugCorePlugin.getDefault().getImageRegistry(); + private final static ImageRegistry PLUGIN_REGISTRY = PHPDebugCorePlugin + .getDefault().getImageRegistry(); public final static String ICONS_PATH = "icons/"; //$NON-NLS-1$ private static final String PATH_OBJ = ICONS_PATH + "obj16/"; //$NON-NLS-1$ + private static final String PATH_LCL = ICONS_PATH + "elcl16/"; //$NON-NLS-1$ + private static final String PATH_LCL_DISABLED = ICONS_PATH + "dlcl16/"; //$NON-NLS-1$ + private static final String PATH_OVR = ICONS_PATH + "ovr16/"; //$NON-NLS-1$ + private static final String PATH_EVENTS = ICONS_PATH + "eview16/"; //$NON-NLS-1$ + public static final ImageDescriptor DESC_ERROR_ST_OBJ = create(PATH_OBJ, + "error_st_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_ERROR_STACK_OBJ = create(PATH_OBJ, + "error_stack.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_EXT_POINT_OBJ = create(PATH_OBJ, + "ext_point_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_EXT_POINTS_OBJ = create(PATH_OBJ, + "ext_points_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_EXTENSION_OBJ = create(PATH_OBJ, + "extension_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_EXTENSIONS_OBJ = create(PATH_OBJ, + "extensions_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_GENERIC_XML_OBJ = create(PATH_OBJ, + "generic_xml_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_INFO_ST_OBJ = create(PATH_OBJ, + "info_st_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_JAVA_LIB_OBJ = create(PATH_OBJ, + "java_lib_obj.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_ERROR_ST_OBJ = - create(PATH_OBJ, "error_st_obj.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_ERROR_STACK_OBJ = - create(PATH_OBJ, "error_stack.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_EXT_POINT_OBJ = - create(PATH_OBJ, "ext_point_obj.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_EXT_POINTS_OBJ = - create(PATH_OBJ, "ext_points_obj.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_EXTENSION_OBJ = - create(PATH_OBJ, "extension_obj.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_EXTENSIONS_OBJ = - create(PATH_OBJ, "extensions_obj.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_GENERIC_XML_OBJ = - create(PATH_OBJ, "generic_xml_obj.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_INFO_ST_OBJ = - create(PATH_OBJ, "info_st_obj.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_JAVA_LIB_OBJ = - create(PATH_OBJ, "java_lib_obj.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_NATIVE_LIB_OBJ = - create(PATH_OBJ, "native_lib_obj.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_OK_ST_OBJ = - create(PATH_OBJ, "ok_st_obj.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_PLUGIN_OBJ = - create(PATH_OBJ, "plugin_obj.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_REQ_PLUGIN_OBJ = - create(PATH_OBJ, "req_plugin_obj.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_REQ_PLUGINS_OBJ = - create(PATH_OBJ, "req_plugins_obj.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_RUNTIME_OBJ = - create(PATH_OBJ, "runtime_obj.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_WARNING_ST_OBJ = - create(PATH_OBJ, "warning_st_obj.gif"); //$NON-NLS-1$ + public static final ImageDescriptor DESC_NATIVE_LIB_OBJ = create(PATH_OBJ, + "native_lib_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OK_ST_OBJ = create(PATH_OBJ, + "ok_st_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_PLUGIN_OBJ = create(PATH_OBJ, + "plugin_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_REQ_PLUGIN_OBJ = create(PATH_OBJ, + "req_plugin_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_REQ_PLUGINS_OBJ = create(PATH_OBJ, + "req_plugins_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_RUNTIME_OBJ = create(PATH_OBJ, + "runtime_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WARNING_ST_OBJ = create(PATH_OBJ, + "warning_st_obj.gif"); //$NON-NLS-1$ /* * Local tool bar image descriptors */ - public static final ImageDescriptor DESC_PROPERTIES = - create(PATH_LCL, "properties.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_OPEN_LOG = - create(PATH_LCL, "open_log.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_OPEN_LOG_DISABLED = - create(PATH_LCL_DISABLED, "open_log.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_PROPERTIES_DISABLED = - create(PATH_LCL_DISABLED, "properties.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_REFRESH = - create(PATH_LCL, "refresh.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_REFRESH_DISABLED = - create(PATH_LCL_DISABLED, "refresh.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_CLEAR = create(PATH_LCL, "clear.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_CLEAR_DISABLED = - create(PATH_LCL_DISABLED, "clear.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_READ_LOG = - create(PATH_LCL, "restore_log.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_READ_LOG_DISABLED = - create(PATH_LCL_DISABLED, "restore_log.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_REMOVE_LOG = - create(PATH_LCL, "remove.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_REMOVE_LOG_DISABLED = - create(PATH_LCL_DISABLED, "remove.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_FILTER = - create(PATH_LCL, "filter_ps.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_FILTER_DISABLED = - create(PATH_LCL_DISABLED, "filter_ps.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_EXPORT = - create(PATH_LCL, "export_log.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_EXPORT_DISABLED = - create(PATH_LCL_DISABLED, "export_log.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_IMPORT = - create(PATH_LCL, "import_log.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_IMPORT_DISABLED = - create(PATH_LCL_DISABLED, "import_log.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_COLLAPSE_ALL = - create(PATH_LCL, "collapseall.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_HORIZONTAL_VIEW = - create(PATH_LCL, "th_horizontal.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_HORIZONTAL_VIEW_DISABLED = - create(PATH_LCL_DISABLED, "th_horizontal.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_VERTICAL_VIEW = - create(PATH_LCL, "th_vertical.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_VERTICAL_VIEW_DISABLED = - create(PATH_LCL_DISABLED, "th_vertical.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_HIDE_PANE = - create(PATH_EVENTS, "hide_pane.gif"); //$NON-NLS-1$ + public static final ImageDescriptor DESC_PROPERTIES = create(PATH_LCL, + "properties.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OPEN_LOG = create(PATH_LCL, + "open_log.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OPEN_LOG_DISABLED = create( + PATH_LCL_DISABLED, "open_log.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_PROPERTIES_DISABLED = create( + PATH_LCL_DISABLED, "properties.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_REFRESH = create(PATH_LCL, + "refresh.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_REFRESH_DISABLED = create( + PATH_LCL_DISABLED, "refresh.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_CLEAR = create(PATH_LCL, + "clear.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_CLEAR_DISABLED = create( + PATH_LCL_DISABLED, "clear.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_READ_LOG = create(PATH_LCL, + "restore_log.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_READ_LOG_DISABLED = create( + PATH_LCL_DISABLED, "restore_log.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_REMOVE_LOG = create(PATH_LCL, + "remove.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_REMOVE_LOG_DISABLED = create( + PATH_LCL_DISABLED, "remove.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_FILTER = create(PATH_LCL, + "filter_ps.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_FILTER_DISABLED = create( + PATH_LCL_DISABLED, "filter_ps.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_EXPORT = create(PATH_LCL, + "export_log.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_EXPORT_DISABLED = create( + PATH_LCL_DISABLED, "export_log.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_IMPORT = create(PATH_LCL, + "import_log.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_IMPORT_DISABLED = create( + PATH_LCL_DISABLED, "import_log.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_COLLAPSE_ALL = create(PATH_LCL, + "collapseall.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_HORIZONTAL_VIEW = create(PATH_LCL, + "th_horizontal.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_HORIZONTAL_VIEW_DISABLED = create( + PATH_LCL_DISABLED, "th_horizontal.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_VERTICAL_VIEW = create(PATH_LCL, + "th_vertical.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_VERTICAL_VIEW_DISABLED = create( + PATH_LCL_DISABLED, "th_vertical.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_HIDE_PANE = create(PATH_EVENTS, + "hide_pane.gif"); //$NON-NLS-1$ /* * Event Details */ - public static final ImageDescriptor DESC_PREV_EVENT = - create(PATH_EVENTS, "event_prev.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_NEXT_EVENT = - create(PATH_EVENTS, "event_next.gif"); //$NON-NLS-1$ + public static final ImageDescriptor DESC_PREV_EVENT = create(PATH_EVENTS, + "event_prev.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_NEXT_EVENT = create(PATH_EVENTS, + "event_next.gif"); //$NON-NLS-1$ + /* * Overlays */ - public static final ImageDescriptor DESC_RUN_CO = - create(PATH_OVR, "run_co.gif"); //$NON-NLS-1$ + public static final ImageDescriptor DESC_RUN_CO = create(PATH_OVR, + "run_co.gif"); //$NON-NLS-1$ private static ImageDescriptor create(String prefix, String name) { return ImageDescriptor.createFromURL(makeIconURL(prefix, name)); @@ -151,6 +183,7 @@ public class PHPDegugCorePluginImages { public static Image get(String key) { return PLUGIN_REGISTRY.get(key); } + private static URL makeIconURL(String prefix, String name) { String path = prefix + name; URL url = null; @@ -161,6 +194,7 @@ public class PHPDegugCorePluginImages { } return url; } + public static Image manage(String key, ImageDescriptor desc) { Image image = desc.createImage(); PLUGIN_REGISTRY.put(key, image); diff --git a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/SocketUtil.java b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/SocketUtil.java index dac0f05..39f97f5 100644 --- a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/SocketUtil.java +++ b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/SocketUtil.java @@ -1,14 +1,14 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html -Contributors: - IBM Corporation - Initial implementation - Vicente Fernando - www.alfersoft.com.ar -**********************************************************************/ + Contributors: + IBM Corporation - Initial implementation + Vicente Fernando - www.alfersoft.com.ar + **********************************************************************/ package net.sourceforge.phpdt.internal.debug.core; import java.io.IOException; @@ -20,25 +20,30 @@ import java.util.Random; * Utility class to find a port to debug on. */ public class SocketUtil { - private static final Random fgRandom= new Random(System.currentTimeMillis()); - + private static final Random fgRandom = new Random(System + .currentTimeMillis()); + /** * Returns a free port number on the specified host within the given range, * or -1 if none found. * - * @param host name or IP addres of host on which to find a free port - * @param searchFrom the port number from which to start searching - * @param searchTo the port number at which to stop searching + * @param host + * name or IP addres of host on which to find a free port + * @param searchFrom + * the port number from which to start searching + * @param searchTo + * the port number at which to stop searching * @return a free port in the specified range, or -1 of none found */ - public static int findUnusedLocalPort(String host, int searchFrom, int searchTo) { + public static int findUnusedLocalPort(String host, int searchFrom, + int searchTo) { - // First look at the five first ports starting on searchFrom - for (int i= searchFrom; i <= searchFrom + 5; i++) { - Socket s= null; - int port= i; + // First look at the five first ports starting on searchFrom + for (int i = searchFrom; i <= searchFrom + 5; i++) { + Socket s = null; + int port = i; try { - s= new Socket(host, port); + s = new Socket(host, port); } catch (ConnectException e) { return port; } catch (IOException e) { @@ -52,11 +57,11 @@ public class SocketUtil { } } // No free port found then look at 5 random ports numbers - for (int i= 0; i < 5; i++) { - Socket s= null; - int port= getRandomPort(searchFrom, searchTo); + for (int i = 0; i < 5; i++) { + Socket s = null; + int port = getRandomPort(searchFrom, searchTo); try { - s= new Socket(host, port); + s = new Socket(host, port); } catch (ConnectException e) { return port; } catch (IOException e) { @@ -71,8 +76,8 @@ public class SocketUtil { } return -1; } - + private static int getRandomPort(int low, int high) { - return (int)(fgRandom.nextFloat() * (high-low)) + low; + return (int) (fgRandom.nextFloat() * (high - low)) + low; } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/breakpoints/PHPBreakpoint.java b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/breakpoints/PHPBreakpoint.java index 8d4b084..a434a36 100644 --- a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/breakpoints/PHPBreakpoint.java +++ b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/breakpoints/PHPBreakpoint.java @@ -1,14 +1,14 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - IBM Corporation - Initial implementation - Vicente Fernando - www.alfersoft.com.ar -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + Vicente Fernando - www.alfersoft.com.ar + **********************************************************************/ package net.sourceforge.phpdt.internal.debug.core.breakpoints; import net.sourceforge.phpdt.internal.debug.core.PHPDebugCorePlugin; @@ -23,50 +23,54 @@ import org.eclipse.debug.core.model.Breakpoint; import org.eclipse.debug.core.model.IBreakpoint; /** - * A breakpoint is capable of suspending the execution of a - * program at a specific location when a program is running - * in debug mode. Each breakpoint has an associated marker which - * stores and persists all attributes associated with a breakpoint. + * A breakpoint is capable of suspending the execution of a program at a + * specific location when a program is running in debug mode. Each breakpoint + * has an associated marker which stores and persists all attributes associated + * with a breakpoint. *

* A breakpoint is defined in two parts: *

    - *
  1. By an extension of kind "org.eclipse.debug.core.breakpoints"
  2. - *
  3. By a marker definition that corresponds to the above breakpoint extension
  4. + *
  5. By an extension of kind + * "org.eclipse.debug.core.breakpoints"
  6. + *
  7. By a marker definition that corresponds to the above breakpoint + * extension
  8. *
*

- * For example, following is a definition of corresponding breakpoint - * and breakpoint marker definitions. Note that the markerType - * attribute defined by the breakpoint extension corresponds to the - * type of the marker definition. + * For example, following is a definition of corresponding breakpoint and + * breakpoint marker definitions. Note that the markerType + * attribute defined by the breakpoint extension corresponds to the type of the + * marker definition. + * *

- * <extension point="org.eclipse.debug.core.breakpoints">
- *   <breakpoint 
- *      id="com.example.Breakpoint"
- *      class="com.example.Breakpoint"
- *      markerType="com.example.BreakpointMarker">
- *   </breakpoint>
- * </extension>
- * <extension point="org.eclipse.core.resources.markers">
- *   <marker 
- *      id="com.example.BreakpointMarker"
- *      super type="org.eclipse.debug.core.breakpointMarker"
- *      attribute name ="exampleAttribute">
- *   </marker>
- * </extension>
+ *  <extension point="org.eclipse.debug.core.breakpoints">
+ *    <breakpoint 
+ *       id="com.example.Breakpoint"
+ *       class="com.example.Breakpoint"
+ *       markerType="com.example.BreakpointMarker">
+ *    </breakpoint>
+ *  </extension>
+ *  <extension point="org.eclipse.core.resources.markers">
+ *    <marker 
+ *       id="com.example.BreakpointMarker"
+ *       super type="org.eclipse.debug.core.breakpointMarker"
+ *       attribute name ="exampleAttribute">
+ *    </marker>
+ *  </extension>
  * 
+ * *

- * The breakpoint manager instantiates persisted breakpoints by - * traversing all markers that are a subtype of - * "org.eclipse.debug.core.breakpointMarker", and - * instantiating the class defined by the class attribute - * on the associated breakpoint extension. The method setMarker - * is then called to associate a marker with the breakpoint. + * The breakpoint manager instantiates persisted breakpoints by traversing all + * markers that are a subtype of + * "org.eclipse.debug.core.breakpointMarker", and instantiating + * the class defined by the class attribute on the associated + * breakpoint extension. The method setMarker is then called to + * associate a marker with the breakpoint. *

*

- * Breakpoints may or may not be registered with the breakpoint manager, and - * are persisted and restored as such. Since marker definitions only allow - * all or none of a specific marker type to be persisted, breakpoints define - * a PERSISTED attribute for selective persistence of breakpoints + * Breakpoints may or may not be registered with the breakpoint manager, and are + * persisted and restored as such. Since marker definitions only allow all or + * none of a specific marker type to be persisted, breakpoints define a + * PERSISTED attribute for selective persistence of breakpoints * of the same type. *

* @@ -76,98 +80,109 @@ import org.eclipse.debug.core.model.IBreakpoint; public abstract class PHPBreakpoint extends Breakpoint implements IBreakpoint { /** - * Breakpoint attribute storing a breakpoint's hit count value - * (value "net.sourceforge.phpeclipse.debug.hitCount"). This attribute is stored as an - * int. + * Breakpoint attribute storing a breakpoint's hit count value (value + * "net.sourceforge.phpeclipse.debug.hitCount"). This + * attribute is stored as an int. * - * For DBG the hit count is really a skip count. - * Explanation: A hit count of e.g. 4 would break on the fourth occurence of the breakpoint. - * A skip count means skip the first four occurences of the breakpoint, and break on the fifth occurence. + * For DBG the hit count is really a skip count. Explanation: A hit count of + * e.g. 4 would break on the fourth occurence of the breakpoint. A skip + * count means skip the first four occurences of the breakpoint, and break + * on the fifth occurence. */ protected static final String HIT_COUNT = "net.sourceforge.phpeclipse.debug.hitCount"; //$NON-NLS-1$ /** - * Breakpoint attribute storing a breakpoint's changeID. - * This is used for checking whether the breakpoint properties menu was finished with - * a OK-button. Which means a possible change of breakpoint condition or skip count. - * This is necessary because in method breakpointChanged in class PHPDebugTarget we need to know, - * whether the breakpoint has changed or not (breakpointChanged is called also when - * a PHP source file is modified and saved). + * Breakpoint attribute storing a breakpoint's changeID. This is used for + * checking whether the breakpoint properties menu was finished with a + * OK-button. Which means a possible change of breakpoint condition or skip + * count. This is necessary because in method breakpointChanged in class + * PHPDebugTarget we need to know, whether the breakpoint has changed or not + * (breakpointChanged is called also when a PHP source file is modified and + * saved). */ protected static final String CHANGE_ID = "net.sourceforge.phpeclipse.debug.changeID"; //$NON-NLS-1$ /** - * Breakpoint attribute storing a breakpoint's condition - * (value "net.sourceforge.phpeclipse.debug.condition"). This attribute is stored as an - * string. + * Breakpoint attribute storing a breakpoint's condition (value + * "net.sourceforge.phpeclipse.debug.condition"). This + * attribute is stored as an string. */ protected static final String CONDITION = "net.sourceforge.phpeclipse.debug.condition"; //$NON-NLS-1$ /** - * Breakpoint attribute storing whether a breakpoint's condition is enabled or not - * (value "net.sourceforge.phpeclipse.debug.conditionEnabled"). This attribute is stored as an - * boolean. + * Breakpoint attribute storing whether a breakpoint's condition is enabled + * or not (value + * "net.sourceforge.phpeclipse.debug.conditionEnabled"). + * This attribute is stored as an boolean. */ protected static final String CONDITION_ENABLED = "net.sourceforge.phpeclipse.debug.conditionEnabled"; //$NON-NLS-1$ /** - * Breakpoint attribute storing the fully qualified name of the type - * this breakpoint is located in. - * (value "net.sourceforge.phpeclipse.debug.typeName"). This attribute is a String. + * Breakpoint attribute storing the fully qualified name of the type this + * breakpoint is located in. (value + * "net.sourceforge.phpeclipse.debug.typeName"). This + * attribute is a String. */ protected static final String TYPE_NAME = "net.sourceforge.phpeclipse.debug.typeName"; //$NON-NLS-1$ /** - * Root breakpoint marker type - * (value "org.eclipse.debug.core.breakpoint"). + * Root breakpoint marker type (value + * "org.eclipse.debug.core.breakpoint"). */ - public static final String BREAKPOINT_MARKER = DebugPlugin.getUniqueIdentifier() + ".breakpointMarker"; //$NON-NLS-1$ - + public static final String BREAKPOINT_MARKER = DebugPlugin + .getUniqueIdentifier() + + ".breakpointMarker"; //$NON-NLS-1$ + /** - * Line breakpoint marker type - * (value "org.eclipse.debug.core.lineBreakpoint"). + * Line breakpoint marker type (value + * "org.eclipse.debug.core.lineBreakpoint"). */ - public static final String LINE_BREAKPOINT_MARKER = DebugPlugin.getUniqueIdentifier() + ".lineBreakpointMarker"; //$NON-NLS-1$ - + public static final String LINE_BREAKPOINT_MARKER = DebugPlugin + .getUniqueIdentifier() + + ".lineBreakpointMarker"; //$NON-NLS-1$ + /** - * Enabled breakpoint marker attribute (value "org.eclipse.debug.core.enabled"). - * The attribute is a boolean corresponding to the - * enabled state of a breakpoint. - * + * Enabled breakpoint marker attribute (value + * "org.eclipse.debug.core.enabled"). The attribute is a + * boolean corresponding to the enabled state of a + * breakpoint. + * * @see org.eclipse.core.resources.IMarker#getAttribute(String, boolean) */ - public static final String ENABLED= "org.eclipse.debug.core.enabled"; //$NON-NLS-1$ - + public static final String ENABLED = "org.eclipse.debug.core.enabled"; //$NON-NLS-1$ + /** - * Debug model identifier breakpoint marker attribute (value "org.eclipse.debug.core.id"). - * The attribute is a String corresponding to the - * identifier of the debug model a breakpoint is associated with. + * Debug model identifier breakpoint marker attribute (value + * "org.eclipse.debug.core.id"). The attribute is a + * String corresponding to the identifier of the debug model + * a breakpoint is associated with. */ - public static final String ID= "org.eclipse.debug.core.id"; //$NON-NLS-1$ - + public static final String ID = "org.eclipse.debug.core.id"; //$NON-NLS-1$ + /** - * Registered breakpoint marker attribute (value "org.eclipse.debug.core.registered"). - * The attribute is a boolean corresponding to - * whether a breakpoint has been registered with the breakpoint manager. - * + * Registered breakpoint marker attribute (value + * "org.eclipse.debug.core.registered"). The attribute is a + * boolean corresponding to whether a breakpoint has been + * registered with the breakpoint manager. + * * @see org.eclipse.core.resources.IMarker#getAttribute(String, boolean) */ - public static final String REGISTERED= "org.eclipse.debug.core.registered"; //$NON-NLS-1$ - + public static final String REGISTERED = "org.eclipse.debug.core.registered"; //$NON-NLS-1$ + /** - * Persisted breakpoint marker attribute (value "org.eclipse.debug.core.persisted"). - * The attribute is a boolean corresponding to - * whether a breakpoint is to be persisted accross workspace - * invocations. - * + * Persisted breakpoint marker attribute (value + * "org.eclipse.debug.core.persisted"). The attribute is a + * boolean corresponding to whether a breakpoint is to be + * persisted accross workspace invocations. + * * @see org.eclipse.core.resources.IMarker#getAttribute(String, boolean) */ - public static final String PERSISTED= "org.eclipse.debug.core.persisted"; //$NON-NLS-1$ + public static final String PERSISTED = "org.eclipse.debug.core.persisted"; //$NON-NLS-1$ - private int DBGBpNo=0; + private int DBGBpNo = 0; public PHPBreakpoint() { - } + } /** * @see IBreakpoint#setMarker(IMarker) @@ -175,10 +190,10 @@ public abstract class PHPBreakpoint extends Breakpoint implements IBreakpoint { public void setMarker(IMarker marker) throws CoreException { super.setMarker(marker); } - + /** - * Add this breakpoint to the breakpoint manager, - * or sets it as unregistered. + * Add this breakpoint to the breakpoint manager, or sets it as + * unregistered. */ protected void register(boolean register) throws CoreException { if (register) { @@ -187,7 +202,7 @@ public abstract class PHPBreakpoint extends Breakpoint implements IBreakpoint { setRegistered(false); } } - + /** * Execute the given workspace runnable */ @@ -196,7 +211,7 @@ public abstract class PHPBreakpoint extends Breakpoint implements IBreakpoint { ResourcesPlugin.getWorkspace().run(wr, null); } catch (CoreException e) { throw new DebugException(e.getStatus()); - } + } } /** @@ -205,26 +220,26 @@ public abstract class PHPBreakpoint extends Breakpoint implements IBreakpoint { public String getModelIdentifier() { return PHPDebugCorePlugin.getUniqueIdentifier(); } - + public void setDBGBpNo(int bpNo) { this.DBGBpNo = bpNo; } - + public int getDBGBpNo() { return this.DBGBpNo; } - - public int getHitCount () throws CoreException { - return getMarker ().getAttribute (HIT_COUNT, -1); + + public int getHitCount() throws CoreException { + return getMarker().getAttribute(HIT_COUNT, -1); } - - public void setHitCount (int hitCount) throws CoreException { + + public void setHitCount(int hitCount) throws CoreException { if (hitCount > 0) { - if (!isEnabled ()) { - getMarker ().setAttribute (ENABLED, true); + if (!isEnabled()) { + getMarker().setAttribute(ENABLED, true); } } - - getMarker ().setAttribute (HIT_COUNT, hitCount); + + getMarker().setAttribute(HIT_COUNT, hitCount); } } diff --git a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/breakpoints/PHPLineBreakpoint.java b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/breakpoints/PHPLineBreakpoint.java index 3d5ac2b..3196ff8 100644 --- a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/breakpoints/PHPLineBreakpoint.java +++ b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/breakpoints/PHPLineBreakpoint.java @@ -1,13 +1,13 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - Vicente Fernando - Initial implementation - www.alfersoft.com.ar -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + Vicente Fernando - Initial implementation - www.alfersoft.com.ar + **********************************************************************/ package net.sourceforge.phpdt.internal.debug.core.breakpoints; import java.util.Map; @@ -24,65 +24,67 @@ import org.eclipse.debug.core.model.ILineBreakpoint; /** * A breakpoint that can be located at a specific line of source code. */ -public class PHPLineBreakpoint extends PHPBreakpoint implements IBreakpoint, ILineBreakpoint { +public class PHPLineBreakpoint extends PHPBreakpoint implements IBreakpoint, + ILineBreakpoint { private static final String PHP_LINE_BREAKPOINT = "net.sourceforge.phpeclipse.debug.core.phpLineBreakpointMarker"; //$NON-NLS-1$ public PHPLineBreakpoint() { } - public PHPLineBreakpoint(IResource resource, int lineNumber, int charStart, int charEnd, int hitCount, boolean add, Map attributes) throws DebugException { - this(resource, lineNumber, charStart, charEnd, hitCount, add, attributes, PHP_LINE_BREAKPOINT); + public PHPLineBreakpoint(IResource resource, int lineNumber, int charStart, + int charEnd, int hitCount, boolean add, Map attributes) + throws DebugException { + this(resource, lineNumber, charStart, charEnd, hitCount, add, + attributes, PHP_LINE_BREAKPOINT); } - - public PHPLineBreakpoint(IResource resource, int lineNumber, int hitCount, boolean add, Map attributes) throws DebugException { - this(resource, lineNumber, -1, -1, hitCount, add, attributes, PHP_LINE_BREAKPOINT); + + public PHPLineBreakpoint(IResource resource, int lineNumber, int hitCount, + boolean add, Map attributes) throws DebugException { + this(resource, lineNumber, -1, -1, hitCount, add, attributes, + PHP_LINE_BREAKPOINT); } - - protected PHPLineBreakpoint (final IResource resource, - final int lineNumber, - final int charStart, - final int charEnd, - final int hitCount, - final boolean add, - final Map attributes, - final String markerType) throws DebugException { - IWorkspaceRunnable wr= new IWorkspaceRunnable() { + protected PHPLineBreakpoint(final IResource resource, final int lineNumber, + final int charStart, final int charEnd, final int hitCount, + final boolean add, final Map attributes, final String markerType) + throws DebugException { + IWorkspaceRunnable wr = new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { - + // create the marker setMarker(resource.createMarker(markerType)); // add attributes - addLineBreakpointAttributes(attributes, getModelIdentifier(), true, lineNumber, charStart, charEnd, hitCount); + addLineBreakpointAttributes(attributes, getModelIdentifier(), + true, lineNumber, charStart, charEnd, hitCount); // set attributes ensureMarker().setAttributes(attributes); - + // add to breakpoint manager if requested - register(add); + register(add); } }; run(wr); } - - public void addLineBreakpointAttributes(Map attributes, String modelIdentifier, boolean enabled, int lineNumber, int charStart, int charEnd, int hitCount) { + public void addLineBreakpointAttributes(Map attributes, + String modelIdentifier, boolean enabled, int lineNumber, + int charStart, int charEnd, int hitCount) { attributes.put(IBreakpoint.ID, modelIdentifier); attributes.put(IBreakpoint.ENABLED, new Boolean(enabled)); attributes.put(IMarker.LINE_NUMBER, new Integer(lineNumber)); - if (charStart!=-1) - { + if (charStart != -1) { attributes.put(IMarker.CHAR_START, new Integer(charStart)); attributes.put(IMarker.CHAR_END, new Integer(charEnd)); } - attributes.put(TYPE_NAME, "typeName"); + attributes.put(TYPE_NAME, "typeName"); attributes.put(PHPBreakpoint.HIT_COUNT, new Integer(hitCount)); attributes.put(PHPBreakpoint.CONDITION, new String("")); attributes.put(PHPBreakpoint.CONDITION_ENABLED, new Boolean(false)); attributes.put(PHPBreakpoint.CHANGE_ID, new Integer(0)); - } + } /** * @see ILineBreakpoint#getLineNumber() @@ -104,39 +106,39 @@ public class PHPLineBreakpoint extends PHPBreakpoint implements IBreakpoint, ILi public int getCharEnd() throws CoreException { return ensureMarker().getAttribute(IMarker.CHAR_END, -1); } - + /** * Returns the type of marker associated with Java line breakpoints */ public static String getMarkerType() { return PHP_LINE_BREAKPOINT; } - + public int getHitCount() throws CoreException { return ensureMarker().getAttribute(PHPBreakpoint.HIT_COUNT, 1); } - + public int getChangeID() throws CoreException { return ensureMarker().getAttribute(CHANGE_ID, 1); } - + public void setChangeID(int changeID) throws CoreException { ensureMarker().setAttribute(CHANGE_ID, changeID); } - public String getCondition () throws CoreException { - return ensureMarker ().getAttribute (CONDITION, ""); + public String getCondition() throws CoreException { + return ensureMarker().getAttribute(CONDITION, ""); } - - public void setCondition (String condition) throws CoreException { - ensureMarker ().setAttribute (CONDITION, condition); + + public void setCondition(String condition) throws CoreException { + ensureMarker().setAttribute(CONDITION, condition); } - public void setConditionEnabled (boolean enabled) throws CoreException { - ensureMarker ().setAttribute (CONDITION_ENABLED, enabled); + public void setConditionEnabled(boolean enabled) throws CoreException { + ensureMarker().setAttribute(CONDITION_ENABLED, enabled); } - public boolean isConditionEnabled () throws CoreException { - return ensureMarker ().getAttribute (CONDITION_ENABLED, false); + public boolean isConditionEnabled() throws CoreException { + return ensureMarker().getAttribute(CONDITION_ENABLED, false); } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/model/IPHPDebugTarget.java b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/model/IPHPDebugTarget.java index 6bcd61c..597fd5c 100644 --- a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/model/IPHPDebugTarget.java +++ b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/model/IPHPDebugTarget.java @@ -1,14 +1,14 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - IBM Corporation - Initial implementation - Vicente Fernando - www.alfersoft.com.ar -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + Vicente Fernando - www.alfersoft.com.ar + **********************************************************************/ package net.sourceforge.phpdt.internal.debug.core.model; import net.sourceforge.phpdt.internal.debug.core.PHPDBGProxy; @@ -18,7 +18,10 @@ import org.eclipse.debug.core.model.IDebugTarget; public interface IPHPDebugTarget extends IDebugTarget { public final static String MODEL_IDENTIFIER = "net.sourceforge.phpdt.debug.core"; + public void terminate(); + public void setPHPDBGProxy(PHPDBGProxy phpDBGProxy); + public void addThread(PHPThread phpThread); } diff --git a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/model/PHPDebugElement.java b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/model/PHPDebugElement.java index e66ac6d..5cc42ea 100644 --- a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/model/PHPDebugElement.java +++ b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/model/PHPDebugElement.java @@ -24,42 +24,54 @@ import org.eclipse.debug.core.model.IDebugTarget; /** * Common function of PHP debug model elements */ -public abstract class PHPDebugElement extends PlatformObject implements IDebugElement { +public abstract class PHPDebugElement extends PlatformObject implements + IDebugElement { // containing target - protected PHPDebugTarget fTarget; + protected PHPDebugTarget fTarget; /** - * Constructs a new debug element contained in the given - * debug target. - * - * @param target debug target (PHP VM) + * Constructs a new debug element contained in the given debug target. + * + * @param target + * debug target (PHP VM) */ - public PHPDebugElement(PHPDebugTarget target) { + public PHPDebugElement(PHPDebugTarget target) { fTarget = target; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IDebugElement#getModelIdentifier() */ public String getModelIdentifier() { return null; - // return PHPDebugCorePlugin.PLUGIN_ID; - // return IPDAConstants.ID_PDA_DEBUG_MODEL; + // return PHPDebugCorePlugin.PLUGIN_ID; + // return IPDAConstants.ID_PDA_DEBUG_MODEL; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IDebugElement#getDebugTarget() */ public IDebugTarget getDebugTarget() { return fTarget; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IDebugElement#getLaunch() */ public ILaunch getLaunch() { return getDebugTarget().getLaunch(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class) */ public Object getAdapter(Class adapter) { @@ -70,17 +82,21 @@ public abstract class PHPDebugElement extends PlatformObject implements IDebugEl } protected void abort(String message, Throwable e) throws DebugException { - throw new DebugException(new Status(IStatus.ERROR, null /*DebugExamplesPlugin.getDefault().getDescriptor().getUniqueIdentifier()*/, - DebugPlugin.INTERNAL_ERROR, message, e)); + throw new DebugException( + new Status( + IStatus.ERROR, + null /* DebugExamplesPlugin.getDefault().getDescriptor().getUniqueIdentifier() */, + DebugPlugin.INTERNAL_ERROR, message, e)); } /** * Fires a debug event - * - * @param event the event to be fired + * + * @param event + * the event to be fired */ protected void fireEvent(DebugEvent event) { - DebugPlugin.getDefault().fireDebugEventSet(new DebugEvent[] {event}); + DebugPlugin.getDefault().fireDebugEventSet(new DebugEvent[] { event }); } /** @@ -91,20 +107,22 @@ public abstract class PHPDebugElement extends PlatformObject implements IDebugEl } /** - * Fires a RESUME event for this element with - * the given detail. - * - * @param detail event detail code + * Fires a RESUME event for this element with the given + * detail. + * + * @param detail + * event detail code */ public void fireResumeEvent(int detail) { fireEvent(new DebugEvent(this, DebugEvent.RESUME, detail)); } /** - * Fires a SUSPEND event for this element with - * the given detail. - * - * @param detail event detail code + * Fires a SUSPEND event for this element with the given + * detail. + * + * @param detail + * event detail code */ public void fireSuspendEvent(int detail) { fireEvent(new DebugEvent(this, DebugEvent.SUSPEND, detail)); diff --git a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/model/PHPExpression.java b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/model/PHPExpression.java index 9ca57f1..80b40dc 100644 --- a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/model/PHPExpression.java +++ b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/model/PHPExpression.java @@ -1,14 +1,14 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - IBM Corporation - Initial implementation - Vicente Fernando - www.alfersoft.com.ar -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + Vicente Fernando - www.alfersoft.com.ar + **********************************************************************/ package net.sourceforge.phpdt.internal.debug.core.model; import org.eclipse.debug.core.ILaunch; @@ -18,41 +18,42 @@ import org.eclipse.debug.core.model.IValue; public class PHPExpression implements IExpression { - private PHPVariable inspectionResult; - private String expression; - - public PHPExpression(String expression, PHPVariable inspectionResult) { - this.inspectionResult = inspectionResult; - this.expression = expression; + private PHPVariable inspectionResult; - } + private String expression; - public String getExpressionText() { - return expression; - } + public PHPExpression(String expression, PHPVariable inspectionResult) { + this.inspectionResult = inspectionResult; + this.expression = expression; - public IValue getValue() { - return inspectionResult.getValue(); - } + } - public IDebugTarget getDebugTarget() { - return inspectionResult.getDebugTarget(); - } + public String getExpressionText() { + return expression; + } - public void dispose() { + public IValue getValue() { + return inspectionResult.getValue(); + } - } + public IDebugTarget getDebugTarget() { + return inspectionResult.getDebugTarget(); + } - public String getModelIdentifier() { - return this.getDebugTarget().getModelIdentifier(); - } + public void dispose() { - public ILaunch getLaunch() { - return this.getDebugTarget().getLaunch(); - } + } - public Object getAdapter(Class arg0) { - return null; - } + public String getModelIdentifier() { + return this.getDebugTarget().getModelIdentifier(); + } + + public ILaunch getLaunch() { + return this.getDebugTarget().getLaunch(); + } + + public Object getAdapter(Class arg0) { + return null; + } } diff --git a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/model/PHPVariableComparator.java b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/model/PHPVariableComparator.java index 1cd86e3..b0d152e 100644 --- a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/model/PHPVariableComparator.java +++ b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/model/PHPVariableComparator.java @@ -5,8 +5,8 @@ import java.util.Comparator; public class PHPVariableComparator implements Comparator { public int compare(Object arg0, Object arg1) { - PHPVariable left=(PHPVariable) arg0; - PHPVariable right=(PHPVariable) arg1; + PHPVariable left = (PHPVariable) arg0; + PHPVariable right = (PHPVariable) arg1; return left.getName().compareTo(right.getName()); } diff --git a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/watch/PHPEvalException.java b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/watch/PHPEvalException.java index cfe1108..52f02be 100644 --- a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/watch/PHPEvalException.java +++ b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/watch/PHPEvalException.java @@ -2,9 +2,8 @@ package net.sourceforge.phpdt.internal.debug.core.watch; public class PHPEvalException extends Exception { - public PHPEvalException(String s) - { - super(s); - } + public PHPEvalException(String s) { + super(s); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/watch/PHPWatchExpressionDelegate.java b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/watch/PHPWatchExpressionDelegate.java index e37deff..1f38d53 100644 --- a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/watch/PHPWatchExpressionDelegate.java +++ b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/watch/PHPWatchExpressionDelegate.java @@ -11,40 +11,40 @@ import org.eclipse.debug.core.model.IWatchExpressionListener; import org.eclipse.debug.core.model.IWatchExpressionResult; /** - * + * */ public class PHPWatchExpressionDelegate implements IWatchExpressionDelegate { - public void evaluateExpression (String expression, IDebugElement context, IWatchExpressionListener listener) { - IWatchExpressionResult x; - PHPDBGProxy dbg; - PHPStackFrame s; + public void evaluateExpression(String expression, IDebugElement context, + IWatchExpressionListener listener) { + IWatchExpressionResult x; + PHPDBGProxy dbg; + PHPStackFrame s; - dbg = ((PHPDebugTarget) context.getDebugTarget ()).getPHPDBGProxy (); - s = null; + dbg = ((PHPDebugTarget) context.getDebugTarget()).getPHPDBGProxy(); + s = null; if (context instanceof PHPStackFrame) { s = (PHPStackFrame) context; } try { - PHPVariable result[] = dbg.eval (s, expression); + PHPVariable result[] = dbg.eval(s, expression); if (result.length == 0) { - x = new PHPWatchExpressionResult (expression, null, null); + x = new PHPWatchExpressionResult(expression, null, null); + } else { + x = new PHPWatchExpressionResult(expression, result[0] + .getValue(), null); } - else { - x = new PHPWatchExpressionResult (expression, result[0].getValue (), null); - } - } - catch (Exception e) { + } catch (Exception e) { String[] s1; - s1 = new String[1]; - s1[0] = e.toString (); - x = new PHPWatchExpressionResult (expression, null, s1); + s1 = new String[1]; + s1[0] = e.toString(); + x = new PHPWatchExpressionResult(expression, null, s1); } - listener.watchEvaluationFinished (x); + listener.watchEvaluationFinished(x); } } diff --git a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/watch/PHPWatchExpressionResult.java b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/watch/PHPWatchExpressionResult.java index 14b6c19..2d01e1c 100644 --- a/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/watch/PHPWatchExpressionResult.java +++ b/net.sourceforge.phpeclipse.debug.core/src/net/sourceforge/phpdt/internal/debug/core/watch/PHPWatchExpressionResult.java @@ -6,35 +6,36 @@ import org.eclipse.debug.core.model.IWatchExpressionResult; public class PHPWatchExpressionResult implements IWatchExpressionResult { - String text; - IValue result; - String[] err; - - public PHPWatchExpressionResult(String t,IValue v,String[] e) - { - text=t; - result=v; - err=e; - } - - public IValue getValue() { - return result; - } - - public boolean hasErrors() { - return err != null; - } - - public String[] getErrorMessages() { - return err; - } - - public String getExpressionText() { - return text; - } - - public DebugException getException() { - return null; - } + String text; + + IValue result; + + String[] err; + + public PHPWatchExpressionResult(String t, IValue v, String[] e) { + text = t; + result = v; + err = e; + } + + public IValue getValue() { + return result; + } + + public boolean hasErrors() { + return err != null; + } + + public String[] getErrorMessages() { + return err; + } + + public String getExpressionText() { + return text; + } + + public DebugException getException() { + return null; + } } diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/debug/ui/PHPDebugUiConstants.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/debug/ui/PHPDebugUiConstants.java index d2a0475..7f6d137 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/debug/ui/PHPDebugUiConstants.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/debug/ui/PHPDebugUiConstants.java @@ -3,7 +3,9 @@ package net.sourceforge.phpdt.debug.ui; import net.sourceforge.phpdt.internal.debug.ui.PHPDebugUiPlugin; public interface PHPDebugUiConstants { - public static final String DEFAULT_WORKING_DIRECTORY = PHPDebugUiPlugin.getWorkspace().getRoot().getLocation().toString(); + public static final String DEFAULT_WORKING_DIRECTORY = PHPDebugUiPlugin + .getWorkspace().getRoot().getLocation().toString(); - public static final String PREFERENCE_KEYWORDS = PHPDebugUiPlugin.PLUGIN_ID + ".preference_keywords"; + public static final String PREFERENCE_KEYWORDS = PHPDebugUiPlugin.PLUGIN_ID + + ".preference_keywords"; } diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/debug/ui/PHPDebugUiImages.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/debug/ui/PHPDebugUiImages.java index 1cd7a0b..26bffa7 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/debug/ui/PHPDebugUiImages.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/debug/ui/PHPDebugUiImages.java @@ -13,36 +13,38 @@ import org.eclipse.swt.graphics.Image; public class PHPDebugUiImages { protected static final String NAME_PREFIX = "net.sourceforge.phpdt.debug.ui."; + protected static final int NAME_PREFIX_LENGTH = NAME_PREFIX.length(); + protected static URL iconBaseURL; - - static { - iconBaseURL= PHPDebugUiPlugin.getDefault().getBundle().getEntry("/icons/"); //$NON-NLS-1$ - } -/* static { - String pathSuffix = "icons/"; - try { - iconBaseURL = new URL(PHPDebugUiPlugin.getDefault().getDescriptor().getInstallURL(), pathSuffix); - } catch (MalformedURLException e) { - PHPDebugUiPlugin.log(e); - } + iconBaseURL = PHPDebugUiPlugin.getDefault().getBundle().getEntry( + "/icons/"); //$NON-NLS-1$ } -*/ + + /* + * static { String pathSuffix = "icons/"; try { iconBaseURL = new + * URL(PHPDebugUiPlugin.getDefault().getDescriptor().getInstallURL(), + * pathSuffix); } catch (MalformedURLException e) { PHPDebugUiPlugin.log(e); } } + */ protected static final ImageRegistry IMAGE_REGISTRY = new ImageRegistry(); protected static final String CTOOL_PREFIX = "ctool16"; + protected static final String EVIEW_PREFIX = "eview16"; - public static final String IMG_EVIEW_ARGUMENTS_TAB = NAME_PREFIX + "arguments_tab.gif"; + public static final String IMG_EVIEW_ARGUMENTS_TAB = NAME_PREFIX + + "arguments_tab.gif"; - public static final ImageDescriptor DESC_EVIEW_ARGUMENTS_TAB = createManaged(EVIEW_PREFIX, IMG_EVIEW_ARGUMENTS_TAB); + public static final ImageDescriptor DESC_EVIEW_ARGUMENTS_TAB = createManaged( + EVIEW_PREFIX, IMG_EVIEW_ARGUMENTS_TAB); /** * Returns the image managed under the given key in this registry. * - * @param key the image's key + * @param key + * the image's key * @return the image managed under the given key */ public static Image get(String key) { @@ -50,16 +52,16 @@ public class PHPDebugUiImages { } /** - * Sets the three image descriptors for enabled, disabled, and hovered to an action. The actions - * are retrieved from the *tool16 folders. + * Sets the three image descriptors for enabled, disabled, and hovered to an + * action. The actions are retrieved from the *tool16 folders. */ public static void setToolImageDescriptors(IAction action, String iconName) { setImageDescriptors(action, "tool16", iconName); } /** - * Sets the three image descriptors for enabled, disabled, and hovered to an action. The actions - * are retrieved from the *lcl16 folders. + * Sets the three image descriptors for enabled, disabled, and hovered to an + * action. The actions are retrieved from the *lcl16 folders. */ public static void setLocalImageDescriptors(IAction action, String iconName) { setImageDescriptors(action, "lcl16", iconName); @@ -69,28 +71,36 @@ public class PHPDebugUiImages { return IMAGE_REGISTRY; } - //---- Helper methods to access icons on the file system -------------------------------------- + // ---- Helper methods to access icons on the file system + // -------------------------------------- - protected static void setImageDescriptors(IAction action, String type, String relPath) { + protected static void setImageDescriptors(IAction action, String type, + String relPath) { try { - ImageDescriptor id = ImageDescriptor.createFromURL(makeIconFileURL("d" + type, relPath)); + ImageDescriptor id = ImageDescriptor.createFromURL(makeIconFileURL( + "d" + type, relPath)); if (id != null) action.setDisabledImageDescriptor(id); - } catch (MalformedURLException e) {} + } catch (MalformedURLException e) { + } try { - ImageDescriptor id = ImageDescriptor.createFromURL(makeIconFileURL("c" + type, relPath)); + ImageDescriptor id = ImageDescriptor.createFromURL(makeIconFileURL( + "c" + type, relPath)); if (id != null) action.setHoverImageDescriptor(id); - } catch (MalformedURLException e) {} + } catch (MalformedURLException e) { + } action.setImageDescriptor(create("e" + type, relPath)); } protected static ImageDescriptor createManaged(String prefix, String name) { try { - ImageDescriptor result = ImageDescriptor.createFromURL(makeIconFileURL(prefix, name.substring(NAME_PREFIX_LENGTH))); + ImageDescriptor result = ImageDescriptor + .createFromURL(makeIconFileURL(prefix, name + .substring(NAME_PREFIX_LENGTH))); IMAGE_REGISTRY.put(name, result); return result; } catch (MalformedURLException e) { @@ -106,7 +116,8 @@ public class PHPDebugUiImages { } } - protected static URL makeIconFileURL(String prefix, String name) throws MalformedURLException { + protected static URL makeIconFileURL(String prefix, String name) + throws MalformedURLException { if (iconBaseURL == null) throw new MalformedURLException(); diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/PHPDebugHover.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/PHPDebugHover.java index 8510396..d9053a9 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/PHPDebugHover.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/PHPDebugHover.java @@ -1,4 +1,3 @@ - /******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials @@ -11,7 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.debug.ui; - import net.sourceforge.phpdt.internal.debug.core.model.PHPStackFrame; import net.sourceforge.phpdt.internal.debug.core.model.PHPValue; import net.sourceforge.phpdt.internal.ui.text.HTMLTextPresenter; @@ -42,25 +40,32 @@ import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; +public class PHPDebugHover implements IJavaEditorTextHover, + ITextHoverExtension, ISelectionListener, IPartListener { -public class PHPDebugHover implements IJavaEditorTextHover, ITextHoverExtension, ISelectionListener, IPartListener { - protected IEditorPart fEditor; + protected ISelection fSelection = null; - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.ui.IPartListener#partActivated(org.eclipse.ui.IWorkbenchPart) */ public void partActivated(IWorkbenchPart part) { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.ui.IPartListener#partBroughtToTop(org.eclipse.ui.IWorkbenchPart) */ public void partBroughtToTop(IWorkbenchPart part) { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.ui.IPartListener#partClosed(org.eclipse.ui.IWorkbenchPart) */ public void partClosed(IWorkbenchPart part) { @@ -73,20 +78,27 @@ public class PHPDebugHover implements IJavaEditorTextHover, ITextHoverExtension, } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.ui.IPartListener#partDeactivated(org.eclipse.ui.IWorkbenchPart) */ public void partDeactivated(IWorkbenchPart part) { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.ui.IPartListener#partOpened(org.eclipse.ui.IWorkbenchPart) */ public void partOpened(IWorkbenchPart part) { } - /* (non-Javadoc) - * @see org.eclipse.ui.ISelectionListener#selectionChanged(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection) + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.ISelectionListener#selectionChanged(org.eclipse.ui.IWorkbenchPart, + * org.eclipse.jface.viewers.ISelection) */ public void selectionChanged(IWorkbenchPart part, ISelection selection) { fSelection = selection; @@ -95,82 +107,94 @@ public class PHPDebugHover implements IJavaEditorTextHover, ITextHoverExtension, public PHPDebugHover() { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jdt.ui.text.java.hover.IJavaEditorTextHover#setEditor(org.eclipse.ui.IEditorPart) */ public void setEditor(IEditorPart editor) { if (editor != null) { - fEditor= editor; + fEditor = editor; final IWorkbenchPage page = editor.getSite().getPage(); page.addSelectionListener(IDebugUIConstants.ID_DEBUG_VIEW, this); page.addPartListener(this); // initialize selection Runnable r = new Runnable() { public void run() { - fSelection = page.getSelection(IDebugUIConstants.ID_DEBUG_VIEW); + fSelection = page + .getSelection(IDebugUIConstants.ID_DEBUG_VIEW); } }; PHPDebugUiPlugin.getStandardDisplay().asyncExec(r); } } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.ITextHover#getHoverRegion(org.eclipse.jface.text.ITextViewer, int) + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.ITextHover#getHoverRegion(org.eclipse.jface.text.ITextViewer, + * int) */ public IRegion getHoverRegion(ITextViewer textViewer, int offset) { return JavaWordFinder.findWord(textViewer.getDocument(), offset); } - + /** - * Returns the stack frame in which to search for variables, or null - * if none. + * Returns the stack frame in which to search for variables, or + * null if none. * - * @return the stack frame in which to search for variables, or null - * if none + * @return the stack frame in which to search for variables, or + * null if none */ protected PHPStackFrame getFrame() { if (fSelection instanceof IStructuredSelection) { - IStructuredSelection selection = (IStructuredSelection)fSelection; + IStructuredSelection selection = (IStructuredSelection) fSelection; if (selection.size() == 1) { Object el = selection.getFirstElement(); if (el instanceof IAdaptable) { - return (PHPStackFrame)((IAdaptable)el).getAdapter(PHPStackFrame.class); + return (PHPStackFrame) ((IAdaptable) el) + .getAdapter(PHPStackFrame.class); } } } return null; } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.ITextHover#getHoverInfo(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion) + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.ITextHover#getHoverInfo(org.eclipse.jface.text.ITextViewer, + * org.eclipse.jface.text.IRegion) */ public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { - PHPStackFrame frame = getFrame(); + PHPStackFrame frame = getFrame(); if (frame != null) { try { - - IDocument document= textViewer.getDocument(); + + IDocument document = textViewer.getDocument(); if (document == null) return null; - - String variableName= document.get(hoverRegion.getOffset(), hoverRegion.getLength()); - - StringBuffer buffer= new StringBuffer(); + + String variableName = document.get(hoverRegion.getOffset(), + hoverRegion.getLength()); + + StringBuffer buffer = new StringBuffer(); try { - IVariable variable= frame.findVariable(variableName); + IVariable variable = frame.findVariable(variableName); if (variable != null) { appendVariable(buffer, variable); } } catch (DebugException x) { -// if (x.getStatus().getCode() != IJavaThread.ERR_THREAD_NOT_SUSPENDED) { - PHPDebugUiPlugin.log(x); -// } + // if (x.getStatus().getCode() != + // IJavaThread.ERR_THREAD_NOT_SUSPENDED) { + PHPDebugUiPlugin.log(x); + // } } - + if (buffer.length() > 0) { return buffer.toString(); } - + } catch (BadLocationException x) { PHPDebugUiPlugin.log(x); } @@ -182,15 +206,16 @@ public class PHPDebugHover implements IJavaEditorTextHover, ITextHoverExtension, /** * Append HTML for the given variable to the given buffer */ - private static void appendVariable(StringBuffer buffer, IVariable variable) throws DebugException { + private static void appendVariable(StringBuffer buffer, IVariable variable) + throws DebugException { buffer.append("

"); //$NON-NLS-1$ buffer.append("

").append(variable.getName()).append("
"); //$NON-NLS-1$ //$NON-NLS-2$ buffer.append(" ="); //$NON-NLS-1$ - - String type= getTypeName(variable); - String value= "
" + variable.getValue().getValueString() + "
"; //$NON-NLS-1$ //$NON-NLS-2$ - + + String type = getTypeName(variable); + String value = "
" + variable.getValue().getValueString() + "
"; //$NON-NLS-1$ //$NON-NLS-2$ + if (type == null) { buffer.append(" null"); //$NON-NLS-1$ } else if (type.equals("java.lang.String")) { //$NON-NLS-1$ @@ -204,46 +229,53 @@ public class PHPDebugHover implements IJavaEditorTextHover, ITextHoverExtension, buffer.append(" ("); //$NON-NLS-1$ buffer.append("
").append(type).append("
"); //$NON-NLS-1$ //$NON-NLS-2$ buffer.append(") "); //$NON-NLS-1$ - buffer.append(value); - } + buffer.append(value); + } buffer.append("

"); //$NON-NLS-1$ } private static String getTypeName(IVariable variable) throws DebugException { - IValue value= variable.getValue(); - if (value instanceof PHPValue) - return((PHPValue) value).getReferenceTypeName(); + IValue value = variable.getValue(); + if (value instanceof PHPValue) + return ((PHPValue) value).getReferenceTypeName(); return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.ITextHoverExtension#getInformationControlCreator() */ public IInformationControlCreator getInformationControlCreator() { -// if (Platform.getPlugin("org.eclipse.jdt.ui").getPluginPreferences().getBoolean(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE)) { //$NON-NLS-1$ - return new IInformationControlCreator() { - public IInformationControl createInformationControl(Shell parent) { - return new DefaultInformationControl(parent, SWT.NONE, - new HTMLTextPresenter(true), - PHPDebugUiMessages.getString("JavaDebugHover.16")); //$NON-NLS-1$ - } - }; -// } -// return null; + // if + // (Platform.getPlugin("org.eclipse.jdt.ui").getPluginPreferences().getBoolean(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE)) + // { //$NON-NLS-1$ + return new IInformationControlCreator() { + public IInformationControl createInformationControl(Shell parent) { + return new DefaultInformationControl(parent, SWT.NONE, + new HTMLTextPresenter(true), PHPDebugUiMessages + .getString("JavaDebugHover.16")); //$NON-NLS-1$ + } + }; + // } + // return null; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.ITextHoverExtension#getHoverControlCreator() */ public IInformationControlCreator getHoverControlCreator() { - if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE)) { //$NON-NLS-1$ + if (PreferenceConstants.getPreferenceStore().getBoolean( + PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE)) { //$NON-NLS-1$ return new IInformationControlCreator() { public IInformationControl createInformationControl(Shell parent) { - return new DefaultInformationControl(parent, SWT.NONE, - new HTMLTextPresenter(true), - PHPDebugUiMessages.getString("PHPDebugHover.16")); //$NON-NLS-1$ - } - }; + return new DefaultInformationControl(parent, SWT.NONE, + new HTMLTextPresenter(true), PHPDebugUiMessages + .getString("PHPDebugHover.16")); //$NON-NLS-1$ + } + }; } return null; } diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/PHPDebugModelPresentation.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/PHPDebugModelPresentation.java index 79821fa..866fab9 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/PHPDebugModelPresentation.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/PHPDebugModelPresentation.java @@ -1,14 +1,14 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - IBM Corporation - Initial implementation - Vicente Fernando - www.alfersoft.com.ar -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + Vicente Fernando - www.alfersoft.com.ar + **********************************************************************/ package net.sourceforge.phpdt.internal.debug.ui; import java.util.HashMap; @@ -41,24 +41,29 @@ import org.eclipse.ui.part.FileEditorInput; /** * @see IDebugModelPresentation */ -public class PHPDebugModelPresentation extends LabelProvider implements IDebugModelPresentation { +public class PHPDebugModelPresentation extends LabelProvider implements + IDebugModelPresentation { - protected HashMap fAttributes= new HashMap(3); + protected HashMap fAttributes = new HashMap(3); public PHPDebugModelPresentation() { super(); } + /** * @see IDebugModelPresentation#getEditorId(IEditorInput, Object) */ public String getEditorId(IEditorInput input, Object inputObject) { - IEditorRegistry registry= PlatformUI.getWorkbench().getEditorRegistry(); - IEditorDescriptor descriptor= registry.getDefaultEditor(input.getName()); + IEditorRegistry registry = PlatformUI.getWorkbench() + .getEditorRegistry(); + IEditorDescriptor descriptor = registry.getDefaultEditor(input + .getName()); if (descriptor != null) return descriptor.getId(); - + return null; } + /** * @see IDebugModelPresentation#setAttribute(String, Object) */ @@ -68,17 +73,18 @@ public class PHPDebugModelPresentation extends LabelProvider implements IDebugMo } fAttributes.put(id, value); } - + /** * @see IDebugModelPresentation#getEditorInput(Object) */ public IEditorInput getEditorInput(Object item) { if (item instanceof PHPLineBreakpoint) { - IBreakpoint bp= (IBreakpoint)item; - IMarker ma= bp.getMarker(); - IFile eclipseFile = PHPDebugUiPlugin.getWorkspace().getRoot().getFileForLocation(ma.getResource().getLocation()); - if (eclipseFile == null) { + IBreakpoint bp = (IBreakpoint) item; + IMarker ma = bp.getMarker(); + IFile eclipseFile = PHPDebugUiPlugin.getWorkspace().getRoot() + .getFileForLocation(ma.getResource().getLocation()); + if (eclipseFile == null) { return null; } return new FileEditorInput(eclipseFile); @@ -94,24 +100,25 @@ public class PHPDebugModelPresentation extends LabelProvider implements IDebugMo return DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_BREAKPOINT); } else if (element instanceof IMarker) { return DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_BREAKPOINT); - } else if (element instanceof PHPStackFrame || element instanceof PHPThread || element instanceof IPHPDebugTarget) { + } else if (element instanceof PHPStackFrame + || element instanceof PHPThread + || element instanceof IPHPDebugTarget) { return getDebugElementImage(element); } else if (element instanceof PHPVariable) { - return getVariableImage((PHPVariable)element); + return getVariableImage((PHPVariable) element); } else if (element instanceof PHPValue) { - return getValueImage((PHPValue)element); + return getValueImage((PHPValue) element); } return DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_BREAKPOINT); } private Image getVariableImage(PHPVariable phpVar) { -/* if (phpVar != null) { - if (phpVar.isLocal()) - return DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_VARIABLE); - if (phpVar.isHashValue()) - return DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_VARIABLE); - } - */ + /* + * if (phpVar != null) { if (phpVar.isLocal()) return + * DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_VARIABLE); if + * (phpVar.isHashValue()) return + * DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_VARIABLE); } + */ return DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_VARIABLE); } @@ -128,17 +135,18 @@ public class PHPDebugModelPresentation extends LabelProvider implements IDebugMo public String getText(Object element) { try { if (element instanceof PHPLineBreakpoint) { - return getBreakpointText((IBreakpoint)element); + return getBreakpointText((IBreakpoint) element); } else if (element instanceof PHPVariable) { - PHPVariable phpVar= (PHPVariable) element; + PHPVariable phpVar = (PHPVariable) element; return phpVar.toString(); } } catch (CoreException e) { - return PHPDebugUiMessages.getString("PHPDebugModelPresentation."); //$NON-NLS-1$ + return PHPDebugUiMessages + .getString("PHPDebugModelPresentation."); //$NON-NLS-1$ } return null; } - + /** * @see IDebugModelPresentation#computeDetail(IValue, IValueDetailListener) */ @@ -147,62 +155,72 @@ public class PHPDebugModelPresentation extends LabelProvider implements IDebugMo } protected IBreakpoint getBreakpoint(IMarker marker) { - return DebugPlugin.getDefault().getBreakpointManager().getBreakpoint(marker); + return DebugPlugin.getDefault().getBreakpointManager().getBreakpoint( + marker); } - protected String getBreakpointText(IBreakpoint breakpoint) throws CoreException { + protected String getBreakpointText(IBreakpoint breakpoint) + throws CoreException { if (breakpoint instanceof PHPLineBreakpoint) { return getLineBreakpointText((PHPLineBreakpoint) breakpoint); } return ""; //$NON-NLS-1$ } - - protected String getLineBreakpointText(PHPLineBreakpoint breakpoint) throws CoreException { + + protected String getLineBreakpointText(PHPLineBreakpoint breakpoint) + throws CoreException { StringBuffer label = new StringBuffer(); - label.append (breakpoint.getMarker().getResource().getFullPath()); - label.append (" ["); //$NON-NLS-1$ - label.append (PHPDebugUiMessages.getString("PHPDebugModelPresentation.line")); //$NON-NLS-1$ - label.append (' '); - label.append (breakpoint.getLineNumber()); - label.append (']'); - - if (breakpoint.getHitCount () > 0) { - label.append (" [skip count "); - label.append (breakpoint.getHitCount ()); - label.append (']'); + label.append(breakpoint.getMarker().getResource().getFullPath()); + label.append(" ["); //$NON-NLS-1$ + label.append(PHPDebugUiMessages + .getString("PHPDebugModelPresentation.line")); //$NON-NLS-1$ + label.append(' '); + label.append(breakpoint.getLineNumber()); + label.append(']'); + + if (breakpoint.getHitCount() > 0) { + label.append(" [skip count "); + label.append(breakpoint.getHitCount()); + label.append(']'); } - - if (breakpoint.isConditionEnabled ()){ - label.append (" [conditional]"); + + if (breakpoint.isConditionEnabled()) { + label.append(" [conditional]"); } - + return label.toString(); } - + /** * Returns the image associated with the given element or null * if none is defined. */ protected Image getDebugElementImage(Object element) { - Image image= null; + Image image = null; if (element instanceof PHPThread) { - PHPThread thread = (PHPThread)element; + PHPThread thread = (PHPThread) element; if (thread.isSuspended()) { - image= DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_THREAD_SUSPENDED); + image = DebugUITools + .getImage(IDebugUIConstants.IMG_OBJS_THREAD_SUSPENDED); } else if (thread.isTerminated()) { - image= DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_THREAD_TERMINATED); + image = DebugUITools + .getImage(IDebugUIConstants.IMG_OBJS_THREAD_TERMINATED); } else { - image= DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_THREAD_RUNNING); + image = DebugUITools + .getImage(IDebugUIConstants.IMG_OBJS_THREAD_RUNNING); } } else if (element instanceof PHPStackFrame) { - image= DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_STACKFRAME); + image = DebugUITools + .getImage(IDebugUIConstants.IMG_OBJS_STACKFRAME); } else if (element instanceof IPHPDebugTarget) { - IPHPDebugTarget debugTarget=(IPHPDebugTarget) element; + IPHPDebugTarget debugTarget = (IPHPDebugTarget) element; if (debugTarget.isTerminated()) { - image= DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_DEBUG_TARGET_TERMINATED); + image = DebugUITools + .getImage(IDebugUIConstants.IMG_OBJS_DEBUG_TARGET_TERMINATED); } else { - image= DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_DEBUG_TARGET); + image = DebugUITools + .getImage(IDebugUIConstants.IMG_OBJS_DEBUG_TARGET); } } return image; diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/PHPDebugUiMessages.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/PHPDebugUiMessages.java index dc23fa0..e6e28cd 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/PHPDebugUiMessages.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/PHPDebugUiMessages.java @@ -6,10 +6,14 @@ import java.util.ResourceBundle; public class PHPDebugUiMessages { - private static final String BUNDLE_NAME = PHPDebugUiMessages.class.getName(); - private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); + private static final String BUNDLE_NAME = PHPDebugUiMessages.class + .getName(); - private PHPDebugUiMessages() {} + private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle + .getBundle(BUNDLE_NAME); + + private PHPDebugUiMessages() { + } public static String getString(String key) { try { diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/PHPDebugUiPlugin.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/PHPDebugUiPlugin.java index 7d66455..f914e46 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/PHPDebugUiPlugin.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/PHPDebugUiPlugin.java @@ -15,6 +15,7 @@ import org.osgi.framework.BundleContext; public class PHPDebugUiPlugin extends AbstractUIPlugin { public static final String PLUGIN_ID = "net.sourceforge.phpeclipse.debug.ui"; //$NON-NLS-1$ + protected static PHPDebugUiPlugin plugin; public PHPDebugUiPlugin() { @@ -37,35 +38,34 @@ public class PHPDebugUiPlugin extends AbstractUIPlugin { public static IWorkspace getWorkspace() { return PHPeclipsePlugin.getWorkspace(); } - + /** * Convenience method which returns the unique identifier of this plugin. */ -// public static String getUniqueIdentifier() -// { -// if ( getDefault() == null ) -// { -// // If the default instance is not yet initialized, -// // return a static identifier. This identifier must -// // match the plugin id defined in plugin.xml -// return PLUGIN_ID; -// } -// return getDefault().getDescriptor().getUniqueIdentifier(); -// } - + // public static String getUniqueIdentifier() + // { + // if ( getDefault() == null ) + // { + // // If the default instance is not yet initialized, + // // return a static identifier. This identifier must + // // match the plugin id defined in plugin.xml + // return PLUGIN_ID; + // } + // return getDefault().getDescriptor().getUniqueIdentifier(); + // } /** - * Returns the standard display to be used. The method first checks, if - * the thread calling this method has an associated display. If so, this - * display is returned. Otherwise the method returns the default display. + * Returns the standard display to be used. The method first checks, if the + * thread calling this method has an associated display. If so, this display + * is returned. Otherwise the method returns the default display. */ public static Display getStandardDisplay() { Display display; - display= Display.getCurrent(); + display = Display.getCurrent(); if (display == null) - display= Display.getDefault(); - return display; + display = Display.getDefault(); + return display; } - + /** * Returns the active workbench shell or null if none * @@ -78,34 +78,33 @@ public class PHPDebugUiPlugin extends AbstractUIPlugin { } return null; } - - public static void errorDialog( String message, IStatus status ) - { - log( status ); - Shell shell = getActiveWorkbenchShell(); - if ( shell != null ) - { - ErrorDialog.openError( shell, "Error", message, status ); - } + + public static void errorDialog(String message, IStatus status) { + log(status); + Shell shell = getActiveWorkbenchShell(); + if (shell != null) { + ErrorDialog.openError(shell, "Error", message, status); } + } - public static void errorDialog( String message, Throwable t ) - { - log( t ); - Shell shell = getActiveWorkbenchShell(); - if ( shell != null ) - { - IStatus status = new Status( IStatus.ERROR, PLUGIN_ID, /*ICDebugUIConstants.INTERNAL_ERROR*/ 150, t.getMessage(), null ); //$NON-NLS-1$ - ErrorDialog.openError( shell, "Error", message, status ); - } - } + public static void errorDialog(String message, Throwable t) { + log(t); + Shell shell = getActiveWorkbenchShell(); + if (shell != null) { + IStatus status = new Status(IStatus.ERROR, PLUGIN_ID, /* ICDebugUIConstants.INTERNAL_ERROR */ + 150, t.getMessage(), null); //$NON-NLS-1$ + ErrorDialog.openError(shell, "Error", message, status); + } + } public static void log(IStatus status) { getDefault().getLog().log(status); } public static void log(Throwable e) { - log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.ERROR, PHPDebugUiMessages.getString("RdtDebugUiPlugin.internalErrorOccurred"), e)); //$NON-NLS-1$ + log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.ERROR, + PHPDebugUiMessages + .getString("RdtDebugUiPlugin.internalErrorOccurred"), e)); //$NON-NLS-1$ } /** @@ -121,14 +120,15 @@ public class PHPDebugUiPlugin extends AbstractUIPlugin { public void stop(BundleContext context) throws Exception { super.stop(context); } - -// protected void initializeDefaultPreferences(IPreferenceStore store) { -// super.initializeDefaultPreferences(store); -// -// store.setDefault(RdtDebugUiConstants.PREFERENCE_KEYWORDS, getDefaultKeywords()); -// } - -// protected String getDefaultKeywords() { -// return "class,def,end,if,module,new,puts,require,rescue,throw,while"; -// } + + // protected void initializeDefaultPreferences(IPreferenceStore store) { + // super.initializeDefaultPreferences(store); + // + // store.setDefault(RdtDebugUiConstants.PREFERENCE_KEYWORDS, + // getDefaultKeywords()); + // } + + // protected String getDefaultKeywords() { + // return "class,def,end,if,module,new,puts,require,rescue,throw,while"; + // } } diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/PHPExecutionArgumentsPage.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/PHPExecutionArgumentsPage.java index bc3200b..25fdd7b 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/PHPExecutionArgumentsPage.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/PHPExecutionArgumentsPage.java @@ -13,53 +13,67 @@ import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IWorkbenchPropertyPage; import org.eclipse.ui.dialogs.PropertyPage; -public class PHPExecutionArgumentsPage extends PropertyPage implements IWorkbenchPropertyPage { +public class PHPExecutionArgumentsPage extends PropertyPage implements + IWorkbenchPropertyPage { protected Text interpreterArgumentsText, programArgumentsText; - + public PHPExecutionArgumentsPage() { } - protected Control createContents(Composite parent) { + protected Control createContents(Composite parent) { noDefaultAndApplyButton(); Composite composite = new Composite(parent, SWT.NONE); - + GridLayout layout = new GridLayout(); layout.numColumns = 2; composite.setLayout(layout); - new Label(composite, SWT.NONE).setText(PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPArguments.interpreter_args_box_title")); + new Label(composite, SWT.NONE) + .setText(PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPArguments.interpreter_args_box_title")); new Label(composite, SWT.NONE).setText(" "); interpreterArgumentsText = new Text(composite, SWT.BORDER); - GridData interpreterArgumentsData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + GridData interpreterArgumentsData = new GridData( + GridData.HORIZONTAL_ALIGN_FILL); interpreterArgumentsData.horizontalSpan = 2; interpreterArgumentsText.setLayoutData(interpreterArgumentsData); interpreterArgumentsText.setText(getArgument("interpreter")); - - new Label(composite, SWT.NONE).setText(PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPArguments.program_args_box_title")); + + new Label(composite, SWT.NONE) + .setText(PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPArguments.program_args_box_title")); programArgumentsText = new Text(composite, SWT.BORDER); - GridData programArgumentsData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + GridData programArgumentsData = new GridData( + GridData.HORIZONTAL_ALIGN_FILL); programArgumentsData.horizontalSpan = 2; programArgumentsText.setLayoutData(programArgumentsData); programArgumentsText.setText(getArgument("program")); - + return composite; } - + protected String getArgument(String name) { String argumentValue = null; try { - argumentValue = ((IFile)getElement()).getPersistentProperty(new QualifiedName("executionArguments", name)); - } catch(CoreException e) {} - + argumentValue = ((IFile) getElement()) + .getPersistentProperty(new QualifiedName( + "executionArguments", name)); + } catch (CoreException e) { + } + return argumentValue != null ? argumentValue : ""; } - + public boolean performOk() { - IFile phpFile = (IFile)getElement(); + IFile phpFile = (IFile) getElement(); try { - phpFile.setPersistentProperty(new QualifiedName("executionArguments", "interpreter"), interpreterArgumentsText.getText()); - phpFile.setPersistentProperty(new QualifiedName("executionArguments", "program"), programArgumentsText.getText()); - } catch(CoreException e) { + phpFile.setPersistentProperty(new QualifiedName( + "executionArguments", "interpreter"), + interpreterArgumentsText.getText()); + phpFile.setPersistentProperty(new QualifiedName( + "executionArguments", "program"), programArgumentsText + .getText()); + } catch (CoreException e) { PHPDebugUiPlugin.log(e); return false; } diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/actions/ActionMessages.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/actions/ActionMessages.java index 090d847..23e28bc 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/actions/ActionMessages.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/actions/ActionMessages.java @@ -10,17 +10,15 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.debug.ui.actions; - import java.util.MissingResourceException; import java.util.ResourceBundle; public class ActionMessages { - private static final String BUNDLE_NAME = - "org.eclipse.jdt.internal.debug.ui.actions.ActionMessages";//$NON-NLS-1$ + private static final String BUNDLE_NAME = "org.eclipse.jdt.internal.debug.ui.actions.ActionMessages";//$NON-NLS-1$ - private static final ResourceBundle RESOURCE_BUNDLE = - ResourceBundle.getBundle(BUNDLE_NAME); + private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle + .getBundle(BUNDLE_NAME); private ActionMessages() { } @@ -32,7 +30,7 @@ public class ActionMessages { return '!' + key + '!'; } } - + public static ResourceBundle getResourceBundle() { return RESOURCE_BUNDLE; } diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/actions/PHPDebugBreakpointAction.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/actions/PHPDebugBreakpointAction.java index 28d4954..44dd7ba 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/actions/PHPDebugBreakpointAction.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/actions/PHPDebugBreakpointAction.java @@ -1,51 +1,57 @@ package net.sourceforge.phpdt.internal.debug.ui.actions; +import net.sourceforge.phpdt.internal.debug.core.breakpoints.PHPLineBreakpoint; +import net.sourceforge.phpdt.internal.debug.ui.properties.PHPBreakpointPropertiesDialog; + import org.eclipse.jface.action.IAction; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IViewActionDelegate; import org.eclipse.ui.IViewPart; -import net.sourceforge.phpdt.internal.debug.ui.properties.*; -import net.sourceforge.phpdt.internal.debug.core.breakpoints.*; - /** - * Enables the context menu entry if object is of type PHPLineBreakpoint. - * This is used for Breakpoint properties menu. - * Properties menu let you set 'skip count' and condition of a PHP breakpoint. + * Enables the context menu entry if object is of type PHPLineBreakpoint. This + * is used for Breakpoint properties menu. Properties menu let you set 'skip + * count' and condition of a PHP breakpoint. * */ public class PHPDebugBreakpointAction implements IViewActionDelegate { protected PHPLineBreakpoint fBreakpoint = null; - + public void init(IViewPart view) { } public void run(IAction action) { - PHPBreakpointPropertiesDialog dialog = new PHPBreakpointPropertiesDialog (null, fBreakpoint); - dialog.open(); + PHPBreakpointPropertiesDialog dialog = new PHPBreakpointPropertiesDialog( + null, fBreakpoint); + dialog.open(); } public void selectionChanged(IAction action, ISelection selection) { IStructuredSelection bpSelection; - Object bpObject; - + Object bpObject; + if (selection instanceof IStructuredSelection) { bpSelection = (IStructuredSelection) selection; - - if (bpSelection.size () == 1) { // Do we have something selected - bpObject = bpSelection.getFirstElement(); // Get the selected object - - if (bpObject instanceof PHPLineBreakpoint) { // Is the object of type PHPLineBreakpoint? + + if (bpSelection.size() == 1) { // Do we have something selected + bpObject = bpSelection.getFirstElement(); // Get the selected + // object + + if (bpObject instanceof PHPLineBreakpoint) { // Is the object + // of type + // PHPLineBreakpoint? fBreakpoint = (PHPLineBreakpoint) bpObject; - action.setEnabled (true); // Then enable the context menu item + action.setEnabled(true); // Then enable the context menu + // item return; } } - } - - action.setEnabled (false); // It isn't a PHPLineBreakpoint, so disable the menu item + } + + action.setEnabled(false); // It isn't a PHPLineBreakpoint, so disable + // the menu item } } diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/actions/PHPManageBreakpointRulerAction.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/actions/PHPManageBreakpointRulerAction.java index 5b1c7ef..585a9c3 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/actions/PHPManageBreakpointRulerAction.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/actions/PHPManageBreakpointRulerAction.java @@ -1,14 +1,14 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - IBM Corporation - Initial implementation - Vicente Fernando - www.alfersoft.com.ar -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + Vicente Fernando - www.alfersoft.com.ar + **********************************************************************/ package net.sourceforge.phpdt.internal.debug.ui.actions; import java.util.ArrayList; @@ -43,91 +43,102 @@ import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.IUpdate; -public class PHPManageBreakpointRulerAction extends Action implements IUpdate { - +public class PHPManageBreakpointRulerAction extends Action implements IUpdate { + private IVerticalRulerInfo fRuler; + private ITextEditor fTextEditor; + private String fMarkerType; + private List fMarkers; private String fAddLabel; + private String fRemoveLabel; - - public PHPManageBreakpointRulerAction(IVerticalRulerInfo ruler, ITextEditor editor) { - fRuler= ruler; - fTextEditor= editor; - fMarkerType= IBreakpoint.BREAKPOINT_MARKER; - fAddLabel= PHPDebugUiMessages.getString("PHPManageBreakpointRulerAction.ToggleBreakpoint"); //$NON-NLS-1$ - fRemoveLabel= PHPDebugUiMessages.getString("PHPManageBreakpointRulerAction.ToggleBreakpoint"); //$NON-NLS-1$ + + public PHPManageBreakpointRulerAction(IVerticalRulerInfo ruler, + ITextEditor editor) { + fRuler = ruler; + fTextEditor = editor; + fMarkerType = IBreakpoint.BREAKPOINT_MARKER; + fAddLabel = PHPDebugUiMessages + .getString("PHPManageBreakpointRulerAction.ToggleBreakpoint"); //$NON-NLS-1$ + fRemoveLabel = PHPDebugUiMessages + .getString("PHPManageBreakpointRulerAction.ToggleBreakpoint"); //$NON-NLS-1$ } - - /** - * Returns the resource for which to create the marker, - * or null if there is no applicable resource. - * + + /** + * Returns the resource for which to create the marker, or null + * if there is no applicable resource. + * * @return the resource for which to create the marker or null */ protected IResource getResource() { - IEditorInput input= fTextEditor.getEditorInput(); - - IResource resource= (IResource) input.getAdapter(IFile.class); - + IEditorInput input = fTextEditor.getEditorInput(); + + IResource resource = (IResource) input.getAdapter(IFile.class); + if (resource == null) { - resource= (IResource) input.getAdapter(IResource.class); + resource = (IResource) input.getAdapter(IResource.class); } - + return resource; } - + /** * Checks whether a position includes the ruler's line of activity. - * - * @param position the position to be checked - * @param document the document the position refers to + * + * @param position + * the position to be checked + * @param document + * the document the position refers to * @return true if the line is included by the given position */ protected boolean includesRulerLine(Position position, IDocument document) { if (position != null) { try { - int markerLine= document.getLineOfOffset(position.getOffset()); - int line= fRuler.getLineOfLastMouseButtonActivity(); + int markerLine = document.getLineOfOffset(position.getOffset()); + int line = fRuler.getLineOfLastMouseButtonActivity(); if (line == markerLine) { return true; } } catch (BadLocationException x) { } } - + return false; } - + /** * Returns this action's vertical ruler info. - * + * * @return this action's vertical ruler */ protected IVerticalRulerInfo getVerticalRulerInfo() { return fRuler; } - + /** * Returns this action's editor. - * + * * @return this action's editor */ protected ITextEditor getTextEditor() { return fTextEditor; } - + /** - * Returns the AbstractMarkerAnnotationModel of the editor's input. - * + * Returns the AbstractMarkerAnnotationModel of the editor's + * input. + * * @return the marker annotation model */ protected AbstractMarkerAnnotationModel getAnnotationModel() { - IDocumentProvider provider= fTextEditor.getDocumentProvider(); - IAnnotationModel model= provider.getAnnotationModel(fTextEditor.getEditorInput()); + IDocumentProvider provider = fTextEditor.getDocumentProvider(); + IAnnotationModel model = provider.getAnnotationModel(fTextEditor + .getEditorInput()); if (model instanceof AbstractMarkerAnnotationModel) { return (AbstractMarkerAnnotationModel) model; } @@ -136,19 +147,19 @@ public class PHPManageBreakpointRulerAction extends Action implements IUpdate { /** * Returns the IDocument of the editor's input. - * + * * @return the document of the editor's input */ protected IDocument getDocument() { - IDocumentProvider provider= fTextEditor.getDocumentProvider(); + IDocumentProvider provider = fTextEditor.getDocumentProvider(); return provider.getDocument(fTextEditor.getEditorInput()); } - + /** * @see IUpdate#update() */ public void update() { - fMarkers= getMarkers(); + fMarkers = getMarkers(); setText(fMarkers.isEmpty() ? fAddLabel : fRemoveLabel); } @@ -162,70 +173,85 @@ public class PHPManageBreakpointRulerAction extends Action implements IUpdate { removeMarkers(fMarkers); } } - + protected List getMarkers() { - List breakpoints= new ArrayList(); - - IResource resource= getResource(); - IDocument document= getDocument(); - AbstractMarkerAnnotationModel model= getAnnotationModel(); - + List breakpoints = new ArrayList(); + + IResource resource = getResource(); + IDocument document = getDocument(); + AbstractMarkerAnnotationModel model = getAnnotationModel(); + if (model != null) { try { - - IMarker[] markers= null; + + IMarker[] markers = null; if (resource instanceof IFile) - markers= resource.findMarkers(IBreakpoint.BREAKPOINT_MARKER, true, IResource.DEPTH_INFINITE); + markers = resource.findMarkers( + IBreakpoint.BREAKPOINT_MARKER, true, + IResource.DEPTH_INFINITE); else { - IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot(); - markers= root.findMarkers(IBreakpoint.BREAKPOINT_MARKER, true, IResource.DEPTH_INFINITE); + IWorkspaceRoot root = ResourcesPlugin.getWorkspace() + .getRoot(); + markers = root.findMarkers(IBreakpoint.BREAKPOINT_MARKER, + true, IResource.DEPTH_INFINITE); } - + if (markers != null) { - IBreakpointManager breakpointManager= DebugPlugin.getDefault().getBreakpointManager(); - int iFe =0; - for (iFe= 0; iFe < markers.length; iFe++) { - IBreakpoint breakpoint= breakpointManager.getBreakpoint(markers[iFe]); - if (breakpoint != null && breakpointManager.isRegistered(breakpoint) && - includesRulerLine(model.getMarkerPosition(markers[iFe]), document)) + IBreakpointManager breakpointManager = DebugPlugin + .getDefault().getBreakpointManager(); + int iFe = 0; + for (iFe = 0; iFe < markers.length; iFe++) { + IBreakpoint breakpoint = breakpointManager + .getBreakpoint(markers[iFe]); + if (breakpoint != null + && breakpointManager.isRegistered(breakpoint) + && includesRulerLine(model + .getMarkerPosition(markers[iFe]), + document)) breakpoints.add(markers[iFe]); } } } catch (CoreException x) { System.out.println(x.getStatus()); -// JDIDebugUIPlugin.log(x.getStatus()); + // JDIDebugUIPlugin.log(x.getStatus()); } } return breakpoints; } - + protected void addMarker() { - //IResource resource= getResource(); - IEditorInput editorInput= getTextEditor().getEditorInput(); - IDocument document= getDocument(); - //IBreakpointManager breakpointManager= DebugPlugin.getDefault().getBreakpointManager(); + // IResource resource= getResource(); + IEditorInput editorInput = getTextEditor().getEditorInput(); + IDocument document = getDocument(); + // IBreakpointManager breakpointManager= + // DebugPlugin.getDefault().getBreakpointManager(); - int rulerLine= getVerticalRulerInfo().getLineOfLastMouseButtonActivity(); + int rulerLine = getVerticalRulerInfo() + .getLineOfLastMouseButtonActivity(); // create the marker try { - // Falta verificar si la ubicación del Breakpoint es válida - int lineNumber= rulerLine + 1; + // Falta verificar si la ubicaci�n del Breakpoint es v�lida + int lineNumber = rulerLine + 1; if (lineNumber > 0) { - if (PHPDebugModel.lineBreakpointExists(lineNumber)==null) { -// Map attributes = new HashMap(10); - IRegion line= document.getLineInformation(lineNumber - 1); - int start= line.getOffset(); - int lenline= line.getLength(); - //int end= start + ((lenline > 0)?lenline:0); - int end= start + lenline; - - //PHPDebugModel.createLineBreakpoint(getResource(), lineNumber, start, end, 0, true, attributes); - PHPDebugModel.createLineBreakpoint(((IFileEditorInput) editorInput).getFile(), lineNumber, start, end, 0, true, null); -// PHPDebugModel.createLineBreakpoint(((IFileEditorInput) editorInput).getFile(), lineNumber, 0, true, attributes); - + if (PHPDebugModel.lineBreakpointExists(lineNumber) == null) { + // Map attributes = new HashMap(10); + IRegion line = document.getLineInformation(lineNumber - 1); + int start = line.getOffset(); + int lenline = line.getLength(); + // int end= start + ((lenline > 0)?lenline:0); + int end = start + lenline; + + // PHPDebugModel.createLineBreakpoint(getResource(), + // lineNumber, start, end, 0, true, attributes); + PHPDebugModel.createLineBreakpoint( + ((IFileEditorInput) editorInput).getFile(), + lineNumber, start, end, 0, true, null); + // PHPDebugModel.createLineBreakpoint(((IFileEditorInput) + // editorInput).getFile(), lineNumber, 0, true, attributes); + } } } catch (DebugException e) { @@ -236,13 +262,15 @@ public class PHPManageBreakpointRulerAction extends Action implements IUpdate { System.out.println("Error"); } } - + protected void removeMarkers(List markers) { - IBreakpointManager breakpointManager= DebugPlugin.getDefault().getBreakpointManager(); + IBreakpointManager breakpointManager = DebugPlugin.getDefault() + .getBreakpointManager(); try { - Iterator e= markers.iterator(); + Iterator e = markers.iterator(); while (e.hasNext()) { - IBreakpoint breakpoint= breakpointManager.getBreakpoint((IMarker) e.next()); + IBreakpoint breakpoint = breakpointManager + .getBreakpoint((IMarker) e.next()); breakpointManager.removeBreakpoint(breakpoint, true); } } catch (CoreException e) { @@ -250,7 +278,7 @@ public class PHPManageBreakpointRulerAction extends Action implements IUpdate { } public IResource getUnderlyingResource(String fName) { - IResource parentResource = getResource(); //fParent.getUnderlyingResource(); + IResource parentResource = getResource(); // fParent.getUnderlyingResource(); if (parentResource == null) { return null; } @@ -259,7 +287,7 @@ public class PHPManageBreakpointRulerAction extends Action implements IUpdate { IContainer folder = (IContainer) parentResource; IResource resource = folder.findMember(fName); if (resource == null) { - //throw newNotPresentException(); + // throw newNotPresentException(); return null; } else { return resource; diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/actions/PHPManageBreakpointRulerActionDelegate.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/actions/PHPManageBreakpointRulerActionDelegate.java index f374e92..ef0aedd 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/actions/PHPManageBreakpointRulerActionDelegate.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/actions/PHPManageBreakpointRulerActionDelegate.java @@ -1,14 +1,14 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html -Contributors: - IBM Corporation - Initial implementation - Vicente Fernando - www.alfersoft.com.ar -**********************************************************************/ + Contributors: + IBM Corporation - Initial implementation + Vicente Fernando - www.alfersoft.com.ar + **********************************************************************/ package net.sourceforge.phpdt.internal.debug.ui.actions; import org.eclipse.jface.action.IAction; @@ -16,12 +16,14 @@ import org.eclipse.jface.text.source.IVerticalRulerInfo; import org.eclipse.ui.texteditor.AbstractRulerActionDelegate; import org.eclipse.ui.texteditor.ITextEditor; -public class PHPManageBreakpointRulerActionDelegate extends AbstractRulerActionDelegate { +public class PHPManageBreakpointRulerActionDelegate extends + AbstractRulerActionDelegate { /** * @see AbstractRulerActionDelegate#createAction() */ - protected IAction createAction(ITextEditor editor, IVerticalRulerInfo rulerInfo) { + protected IAction createAction(ITextEditor editor, + IVerticalRulerInfo rulerInfo) { return new PHPManageBreakpointRulerAction(rulerInfo, editor); } } diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/actions/RetargettableActionAdapterFactory.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/actions/RetargettableActionAdapterFactory.java index 0779dba..bff33b2 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/actions/RetargettableActionAdapterFactory.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/actions/RetargettableActionAdapterFactory.java @@ -14,30 +14,36 @@ import org.eclipse.core.runtime.IAdapterFactory; import org.eclipse.debug.ui.actions.IToggleBreakpointsTarget; /** - * Creates adapters for retargettable actions in debug platform. - * Contributed via org.eclipse.core.runtime.adapters - * extension point. + * Creates adapters for retargettable actions in debug platform. Contributed via + * org.eclipse.core.runtime.adapters extension point. * * @since 3.0 */ public class RetargettableActionAdapterFactory implements IAdapterFactory { - /* (non-Javadoc) - * @see org.eclipse.core.runtime.IAdapterFactory#getAdapter(java.lang.Object, java.lang.Class) + /* + * (non-Javadoc) + * + * @see org.eclipse.core.runtime.IAdapterFactory#getAdapter(java.lang.Object, + * java.lang.Class) */ public Object getAdapter(Object adaptableObject, Class adapterType) { -// if (adapterType == IRunToLineTarget.class) { -// return new RunToLineAdapter(); -// } + // if (adapterType == IRunToLineTarget.class) { + // return new RunToLineAdapter(); + // } if (adapterType == IToggleBreakpointsTarget.class) { return new ToggleBreakpointAdapter(); - } + } return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.core.runtime.IAdapterFactory#getAdapterList() */ public Class[] getAdapterList() { - // return new Class[]{IRunToLineTarget.class, IToggleBreakpointsTarget.class}; - return new Class[]{IToggleBreakpointsTarget.class}; + // return new Class[]{IRunToLineTarget.class, + // IToggleBreakpointsTarget.class}; + return new Class[] { IToggleBreakpointsTarget.class }; } } diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/actions/ToggleBreakpointAdapter.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/actions/ToggleBreakpointAdapter.java index dfdc1ea..7725750 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/actions/ToggleBreakpointAdapter.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/actions/ToggleBreakpointAdapter.java @@ -24,6 +24,7 @@ import net.sourceforge.phpdt.core.Signature; import net.sourceforge.phpdt.debug.core.PHPDebugModel; import net.sourceforge.phpdt.internal.debug.core.breakpoints.PHPLineBreakpoint; import net.sourceforge.phpdt.internal.debug.ui.PHPDebugUiPlugin; + import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; @@ -42,13 +43,14 @@ import org.eclipse.ui.texteditor.ITextEditor; /** * Toggles a line breakpoint in a Java editor. - * + * * @since 3.0 */ public class ToggleBreakpointAdapter implements IToggleBreakpointsTarget { protected void report(String message, IWorkbenchPart part) { - IEditorStatusLine statusLine= (IEditorStatusLine) part.getAdapter(IEditorStatusLine.class); + IEditorStatusLine statusLine = (IEditorStatusLine) part + .getAdapter(IEditorStatusLine.class); if (statusLine != null) { if (message != null) { statusLine.setMessage(true, message, null); @@ -56,204 +58,257 @@ public class ToggleBreakpointAdapter implements IToggleBreakpointsTarget { statusLine.setMessage(true, null, null); } } - if (message != null && PHPDebugUiPlugin.getActiveWorkbenchShell() != null) { + if (message != null + && PHPDebugUiPlugin.getActiveWorkbenchShell() != null) { PHPDebugUiPlugin.getActiveWorkbenchShell().getDisplay().beep(); } } -// protected IType getType(ITextSelection selection) { -// IMember member= ActionDelegateHelper.getDefault().getCurrentMember(selection); -// IType type= null; -// if (member instanceof IType) { -// type = (IType)member; -// } else if (member != null) { -// type= member.getDeclaringType(); -// } -// // bug 52385: we don't want local and anonymous types from compilation unit, -// // we are getting 'not-always-correct' names for them. -// try { -// while (type != null && !type.isBinary() && type.isLocal()) { -// type= type.getDeclaringType(); -// } -// } catch (JavaModelException e) { -// PHPDebugUiPlugin.log(e); -// } -// return type; -// } + // protected IType getType(ITextSelection selection) { + // IMember member= + // ActionDelegateHelper.getDefault().getCurrentMember(selection); + // IType type= null; + // if (member instanceof IType) { + // type = (IType)member; + // } else if (member != null) { + // type= member.getDeclaringType(); + // } + // // bug 52385: we don't want local and anonymous types from compilation + // unit, + // // we are getting 'not-always-correct' names for them. + // try { + // while (type != null && !type.isBinary() && type.isLocal()) { + // type= type.getDeclaringType(); + // } + // } catch (JavaModelException e) { + // PHPDebugUiPlugin.log(e); + // } + // return type; + // } - /* (non-Javadoc) - * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#toggleLineBreakpoints(IWorkbenchPart, ISelection) + /* + * (non-Javadoc) + * + * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#toggleLineBreakpoints(IWorkbenchPart, + * ISelection) */ - public void toggleLineBreakpoints(IWorkbenchPart part, ISelection selection) throws CoreException { + public void toggleLineBreakpoints(IWorkbenchPart part, ISelection selection) + throws CoreException { if (selection instanceof ITextSelection) { report(null, part); - IEditorPart editorPart = (IEditorPart)part; - ITextSelection textSelection = (ITextSelection)selection; -// IType type = getType(textSelection); + IEditorPart editorPart = (IEditorPart) part; + ITextSelection textSelection = (ITextSelection) selection; + // IType type = getType(textSelection); IEditorInput editorInput = editorPart.getEditorInput(); - IDocument document= ((ITextEditor)editorPart).getDocumentProvider().getDocument(editorInput); - int lineNumber= textSelection.getStartLine() + 1; - int offset= textSelection.getOffset(); + IDocument document = ((ITextEditor) editorPart) + .getDocumentProvider().getDocument(editorInput); + int lineNumber = textSelection.getStartLine() + 1; + int offset = textSelection.getOffset(); try { -// if (type == null) { -// IClassFile classFile= (IClassFile)editorInput.getAdapter(IClassFile.class); -// if (classFile != null) { -// type= classFile.getType(); -// // bug 34856 - if this is an inner type, ensure the breakpoint is not -// // being added to the outer type -// if (type.getDeclaringType() != null) { -// ISourceRange sourceRange= type.getSourceRange(); -// int start= sourceRange.getOffset(); -// int end= start + sourceRange.getLength(); -// if (offset < start || offset > end) { -// // not in the inner type -// IStatusLineManager statusLine = editorPart.getEditorSite().getActionBars().getStatusLineManager(); -// statusLine .setErrorMessage(MessageFormat.format(ActionMessages.getString("ManageBreakpointRulerAction.Breakpoints_can_only_be_created_within_the_type_associated_with_the_editor__{0}._1"), new String[] { type.getTypeQualifiedName()})); //$NON-NLS-1$ -// Display.getCurrent().beep(); -// return; -// } -// } -// } -// } + // if (type == null) { + // IClassFile classFile= + // (IClassFile)editorInput.getAdapter(IClassFile.class); + // if (classFile != null) { + // type= classFile.getType(); + // // bug 34856 - if this is an inner type, ensure the + // breakpoint is not + // // being added to the outer type + // if (type.getDeclaringType() != null) { + // ISourceRange sourceRange= type.getSourceRange(); + // int start= sourceRange.getOffset(); + // int end= start + sourceRange.getLength(); + // if (offset < start || offset > end) { + // // not in the inner type + // IStatusLineManager statusLine = + // editorPart.getEditorSite().getActionBars().getStatusLineManager(); + // statusLine + // .setErrorMessage(MessageFormat.format(ActionMessages.getString("ManageBreakpointRulerAction.Breakpoints_can_only_be_created_within_the_type_associated_with_the_editor__{0}._1"), + // new String[] { type.getTypeQualifiedName()})); //$NON-NLS-1$ + // Display.getCurrent().beep(); + // return; + // } + // } + // } + // } -// String typeName= null; + // String typeName= null; IResource resource; - PHPLineBreakpoint breakpoint= null; -// if (type == null) { - if (editorInput instanceof IFileEditorInput) { - resource= ((IFileEditorInput)editorInput).getFile(); - } else { - resource= ResourcesPlugin.getWorkspace().getRoot(); - } -// } else { -// typeName= type.getFullyQualifiedName(); -// PHPLineBreakpoint breakpoint=PHPDebugModel.lineBreakpointExists(lineNumber); -// if (breakpoint==null) -// PHPDebugModel.createLineBreakpoint(getFile(), lineNumber, 0, true, null); -// else -// DebugPlugin.getDefault().getBreakpointManager().removeBreakpoint( breakpoint, true ); -// - PHPLineBreakpoint existingBreakpoint= PHPDebugModel.lineBreakpointExists(lineNumber); //typeName, lineNumber); - if (existingBreakpoint != null) { - DebugPlugin.getDefault().getBreakpointManager().removeBreakpoint(existingBreakpoint, true); - return; - } else { - breakpoint = PHPDebugModel.createLineBreakpoint(resource, lineNumber, 0, true, null); - } - // } -// new BreakpointLocationVerifierJob(document, breakpoint, lineNumber, typeName, type, resource, (IEditorStatusLine) editorPart.getAdapter(IEditorStatusLine.class)).schedule(); + PHPLineBreakpoint breakpoint = null; + // if (type == null) { + if (editorInput instanceof IFileEditorInput) { + resource = ((IFileEditorInput) editorInput).getFile(); + } else { + resource = ResourcesPlugin.getWorkspace().getRoot(); + } + // } else { + // typeName= type.getFullyQualifiedName(); + // PHPLineBreakpoint + // breakpoint=PHPDebugModel.lineBreakpointExists(lineNumber); + // if (breakpoint==null) + // PHPDebugModel.createLineBreakpoint(getFile(), lineNumber, 0, + // true, null); + // else + // DebugPlugin.getDefault().getBreakpointManager().removeBreakpoint( + // breakpoint, true ); + // + PHPLineBreakpoint existingBreakpoint = PHPDebugModel + .lineBreakpointExists(lineNumber); // typeName, + // lineNumber); + if (existingBreakpoint != null) { + DebugPlugin.getDefault().getBreakpointManager() + .removeBreakpoint(existingBreakpoint, true); + return; + } else { + breakpoint = PHPDebugModel.createLineBreakpoint(resource, + lineNumber, 0, true, null); + } + // } + // new BreakpointLocationVerifierJob(document, breakpoint, + // lineNumber, typeName, type, resource, (IEditorStatusLine) + // editorPart.getAdapter(IEditorStatusLine.class)).schedule(); } catch (CoreException ce) { - // TODO: no message in ActionMessages - //ExceptionHandler.handle(ce, ActionMessages.getString("ManageBreakpointActionDelegate.error.title1"), ActionMessages.getString("ManageBreakpointActionDelegate.error.message1")); //$NON-NLS-1$ //$NON-NLS-2$ + // TODO: no message in ActionMessages + // ExceptionHandler.handle(ce, + // ActionMessages.getString("ManageBreakpointActionDelegate.error.title1"), + // ActionMessages.getString("ManageBreakpointActionDelegate.error.message1")); + // //$NON-NLS-1$ //$NON-NLS-2$ return; } } } - /*(non-Javadoc) - * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#canToggleLineBreakpoints(IWorkbenchPart, ISelection) + + /* + * (non-Javadoc) + * + * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#canToggleLineBreakpoints(IWorkbenchPart, + * ISelection) */ - public boolean canToggleLineBreakpoints(IWorkbenchPart part, ISelection selection) { + public boolean canToggleLineBreakpoints(IWorkbenchPart part, + ISelection selection) { return selection instanceof ITextSelection; } - /* (non-Javadoc) - * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#toggleMethodBreakpoints(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection) + /* + * (non-Javadoc) + * + * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#toggleMethodBreakpoints(org.eclipse.ui.IWorkbenchPart, + * org.eclipse.jface.viewers.ISelection) */ - public void toggleMethodBreakpoints(IWorkbenchPart part, ISelection selection) throws CoreException { -// report(null, part); -// selection = translateToMembers(part, selection); -// if (selection instanceof ITextSelection) { -// ITextSelection textSelection = (ITextSelection) selection; -// if (selection != null) { -// CompilationUnit compilationUnit= parseCompilationUnit((ITextEditor)part); -// if (compilationUnit != null) { -// BreakpointMethodLocator locator= new BreakpointMethodLocator(textSelection.getOffset()); -// compilationUnit.accept(locator); -// String methodName= locator.getMethodName(); -// if (methodName == null) { -// report(ActionMessages.getString("ManageMethodBreakpointActionDelegate.CantAdd"), part); //$NON-NLS-1$ -// return; -// } -// String typeName= locator.getTypeName(); -// String methodSignature= locator.getMethodSignature(); -// if (methodSignature == null) { -// report(ActionMessages.getString("ManageMethodBreakpointActionDelegate.methodNonAvailable"), part); //$NON-NLS-1$ -// return; -// } -// // check if this method breakpoint already exist. If yes, remove it. -// IBreakpointManager breakpointManager= DebugPlugin.getDefault().getBreakpointManager(); -// IBreakpoint[] breakpoints= breakpointManager.getBreakpoints(JDIDebugModel.getPluginIdentifier()); -// for (int i= 0; i < breakpoints.length; i++) { -// IBreakpoint breakpoint= breakpoints[i]; -// if (breakpoint instanceof IJavaMethodBreakpoint) { -// IJavaMethodBreakpoint methodBreakpoint= (IJavaMethodBreakpoint)breakpoint; -// if (typeName.equals(methodBreakpoint.getTypeName()) -// && methodName.equals(methodBreakpoint.getMethodName()) -// && methodSignature.equals(methodBreakpoint.getMethodSignature())) { -// breakpointManager.removeBreakpoint(methodBreakpoint, true); -// return; -// } -// } -// } -// // add the breakpoint -// JDIDebugModel.createMethodBreakpoint(getResource((IEditorPart)part), typeName, methodName, methodSignature, true, false, false, -1, -1, -1, 0, true, new HashMap(10)); -// } -// } -// } else if (selection instanceof IStructuredSelection) { -// IMethod[] members= getMethods((IStructuredSelection)selection); -// if (members.length == 0) { -// report(ActionMessages.getString("ToggleBreakpointAdapter.9"), part); //$NON-NLS-1$ -// return; -// } -// // add or remove the breakpoint -// IBreakpointManager breakpointManager= DebugPlugin.getDefault().getBreakpointManager(); -// for (int i= 0, length= members.length; i < length; i++) { -// IMethod method= members[i]; -// IJavaBreakpoint breakpoint= getBreakpoint(method); -// if (breakpoint == null) { -// // add breakpoint -// int start = -1; -// int end = -1; -// ISourceRange range = method.getNameRange(); -// if (range != null) { -// start = range.getOffset(); -// end = start + range.getLength(); -// } -// Map attributes = new HashMap(10); -// BreakpointUtils.addJavaBreakpointAttributes(attributes, method); -// String methodName = method.getElementName(); -// if (method.isConstructor()) { -// methodName = ""; //$NON-NLS-1$ -// } -// IType type= method.getDeclaringType(); -// String methodSignature= method.getSignature(); -// if (!type.isBinary()) { -// //resolve the type names -// methodSignature= resolveMethodSignature(type, methodSignature); -// if (methodSignature == null) { -// IStatus status = new Status(IStatus.ERROR, JDIDebugUIPlugin.getUniqueIdentifier(), IStatus.ERROR, "Source method signature could not be resolved", null); //$NON-NLS-1$ -// throw new CoreException(status); -// } -// } -// JDIDebugModel.createMethodBreakpoint(BreakpointUtils.getBreakpointResource(method), type.getFullyQualifiedName(), methodName, methodSignature, true, false, false, -1, start, end, 0, true, attributes); -// } else { -// // remove breakpoint -// breakpointManager.removeBreakpoint(breakpoint, true); -// } -// } -// } + public void toggleMethodBreakpoints(IWorkbenchPart part, + ISelection selection) throws CoreException { + // report(null, part); + // selection = translateToMembers(part, selection); + // if (selection instanceof ITextSelection) { + // ITextSelection textSelection = (ITextSelection) selection; + // if (selection != null) { + // CompilationUnit compilationUnit= + // parseCompilationUnit((ITextEditor)part); + // if (compilationUnit != null) { + // BreakpointMethodLocator locator= new + // BreakpointMethodLocator(textSelection.getOffset()); + // compilationUnit.accept(locator); + // String methodName= locator.getMethodName(); + // if (methodName == null) { + // report(ActionMessages.getString("ManageMethodBreakpointActionDelegate.CantAdd"), + // part); //$NON-NLS-1$ + // return; + // } + // String typeName= locator.getTypeName(); + // String methodSignature= locator.getMethodSignature(); + // if (methodSignature == null) { + // report(ActionMessages.getString("ManageMethodBreakpointActionDelegate.methodNonAvailable"), + // part); //$NON-NLS-1$ + // return; + // } + // // check if this method breakpoint already exist. If yes, remove it. + // IBreakpointManager breakpointManager= + // DebugPlugin.getDefault().getBreakpointManager(); + // IBreakpoint[] breakpoints= + // breakpointManager.getBreakpoints(JDIDebugModel.getPluginIdentifier()); + // for (int i= 0; i < breakpoints.length; i++) { + // IBreakpoint breakpoint= breakpoints[i]; + // if (breakpoint instanceof IJavaMethodBreakpoint) { + // IJavaMethodBreakpoint methodBreakpoint= + // (IJavaMethodBreakpoint)breakpoint; + // if (typeName.equals(methodBreakpoint.getTypeName()) + // && methodName.equals(methodBreakpoint.getMethodName()) + // && methodSignature.equals(methodBreakpoint.getMethodSignature())) { + // breakpointManager.removeBreakpoint(methodBreakpoint, true); + // return; + // } + // } + // } + // // add the breakpoint + // JDIDebugModel.createMethodBreakpoint(getResource((IEditorPart)part), + // typeName, methodName, methodSignature, true, false, false, -1, -1, + // -1, 0, true, new HashMap(10)); + // } + // } + // } else if (selection instanceof IStructuredSelection) { + // IMethod[] members= getMethods((IStructuredSelection)selection); + // if (members.length == 0) { + // report(ActionMessages.getString("ToggleBreakpointAdapter.9"), part); + // //$NON-NLS-1$ + // return; + // } + // // add or remove the breakpoint + // IBreakpointManager breakpointManager= + // DebugPlugin.getDefault().getBreakpointManager(); + // for (int i= 0, length= members.length; i < length; i++) { + // IMethod method= members[i]; + // IJavaBreakpoint breakpoint= getBreakpoint(method); + // if (breakpoint == null) { + // // add breakpoint + // int start = -1; + // int end = -1; + // ISourceRange range = method.getNameRange(); + // if (range != null) { + // start = range.getOffset(); + // end = start + range.getLength(); + // } + // Map attributes = new HashMap(10); + // BreakpointUtils.addJavaBreakpointAttributes(attributes, method); + // String methodName = method.getElementName(); + // if (method.isConstructor()) { + // methodName = ""; //$NON-NLS-1$ + // } + // IType type= method.getDeclaringType(); + // String methodSignature= method.getSignature(); + // if (!type.isBinary()) { + // //resolve the type names + // methodSignature= resolveMethodSignature(type, methodSignature); + // if (methodSignature == null) { + // IStatus status = new Status(IStatus.ERROR, + // JDIDebugUIPlugin.getUniqueIdentifier(), IStatus.ERROR, "Source method + // signature could not be resolved", null); //$NON-NLS-1$ + // throw new CoreException(status); + // } + // } + // JDIDebugModel.createMethodBreakpoint(BreakpointUtils.getBreakpointResource(method), + // type.getFullyQualifiedName(), methodName, methodSignature, true, + // false, false, -1, start, end, 0, true, attributes); + // } else { + // // remove breakpoint + // breakpointManager.removeBreakpoint(breakpoint, true); + // } + // } + // } } - /* (non-Javadoc) - * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#canToggleMethodBreakpoints(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection) + /* + * (non-Javadoc) + * + * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#canToggleMethodBreakpoints(org.eclipse.ui.IWorkbenchPart, + * org.eclipse.jface.viewers.ISelection) */ - public boolean canToggleMethodBreakpoints(IWorkbenchPart part, ISelection selection) { -// if (selection instanceof IStructuredSelection) { -// IStructuredSelection ss = (IStructuredSelection) selection; -// return getMethods(ss).length > 0; -// } else { -// return selection instanceof ITextSelection; -// } + public boolean canToggleMethodBreakpoints(IWorkbenchPart part, + ISelection selection) { + // if (selection instanceof IStructuredSelection) { + // IStructuredSelection ss = (IStructuredSelection) selection; + // return getMethods(ss).length > 0; + // } else { + // return selection instanceof ITextSelection; + // } return false; } @@ -266,7 +321,8 @@ public class ToggleBreakpointAdapter implements IToggleBreakpointsTarget { while (iterator.hasNext()) { Object thing = iterator.next(); try { - if (thing instanceof IMethod && !Flags.isAbstract(((IMethod)thing).getFlags())) { + if (thing instanceof IMethod + && !Flags.isAbstract(((IMethod) thing).getFlags())) { methods.add(thing); } } catch (JavaModelException e) { @@ -276,128 +332,153 @@ public class ToggleBreakpointAdapter implements IToggleBreakpointsTarget { } } -// protected IField[] getFields(IStructuredSelection selection) { -// if (selection.isEmpty()) { -// return new IField[0]; -// } else { -// List fields = new ArrayList(selection.size()); -// Iterator iterator = selection.iterator(); -// while (iterator.hasNext()) { -// Object thing = iterator.next(); -// if (thing instanceof IField) { -// fields.add(thing); -// } else if (thing instanceof IJavaFieldVariable) { -// IField field= getField((IJavaFieldVariable) thing); -// if (field != null) { -// fields.add(field); -// } -// } -// } -// return (IField[]) fields.toArray(new IField[fields.size()]); -// } -// } + // protected IField[] getFields(IStructuredSelection selection) { + // if (selection.isEmpty()) { + // return new IField[0]; + // } else { + // List fields = new ArrayList(selection.size()); + // Iterator iterator = selection.iterator(); + // while (iterator.hasNext()) { + // Object thing = iterator.next(); + // if (thing instanceof IField) { + // fields.add(thing); + // } else if (thing instanceof IJavaFieldVariable) { + // IField field= getField((IJavaFieldVariable) thing); + // if (field != null) { + // fields.add(field); + // } + // } + // } + // return (IField[]) fields.toArray(new IField[fields.size()]); + // } + // } - /* (non-Javadoc) - * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#toggleWatchpoints(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection) + /* + * (non-Javadoc) + * + * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#toggleWatchpoints(org.eclipse.ui.IWorkbenchPart, + * org.eclipse.jface.viewers.ISelection) */ - public void toggleWatchpoints(IWorkbenchPart part, ISelection selection) throws CoreException { -// report(null, part); -// selection = translateToMembers(part, selection); -// if (selection instanceof ITextSelection) { -// ITextSelection textSelection= (ITextSelection) selection; -// CompilationUnit compilationUnit= parseCompilationUnit((ITextEditor)part); -// if (compilationUnit != null) { -// BreakpointFieldLocator locator= new BreakpointFieldLocator(textSelection.getOffset()); -// compilationUnit.accept(locator); -// String fieldName= locator.getFieldName(); -// if (fieldName == null) { -// report(ActionMessages.getString("ManageWatchpointActionDelegate.CantAdd"), part); //$NON-NLS-1$ -// return; -// } -// String typeName= locator.getTypeName(); -// // check if the watchpoint already exists. If yes, remove it -// IBreakpointManager breakpointManager= DebugPlugin.getDefault().getBreakpointManager(); -// IBreakpoint[] breakpoints= breakpointManager.getBreakpoints(JDIDebugModel.getPluginIdentifier()); -// for (int i= 0; i < breakpoints.length; i++) { -// IBreakpoint breakpoint= breakpoints[i]; -// if (breakpoint instanceof IJavaWatchpoint) { -// IJavaWatchpoint watchpoint= (IJavaWatchpoint)breakpoint; -// if (typeName.equals(watchpoint.getTypeName()) && fieldName.equals(watchpoint.getFieldName())) { -// breakpointManager.removeBreakpoint(watchpoint, true); -// return; -// } -// } -// } -// // add the watchpoint -// JDIDebugModel.createWatchpoint(getResource((IEditorPart)part), typeName, fieldName, -1, -1, -1, 0, true, new HashMap(10)); -// } -// } else if (selection instanceof IStructuredSelection) { -// IField[] members = getFields((IStructuredSelection)selection); -// if (members.length == 0) { -// report(ActionMessages.getString("ToggleBreakpointAdapter.10"), part); //$NON-NLS-1$ -// return; -// } -// // add or remove watchpoint -// IBreakpointManager breakpointManager= DebugPlugin.getDefault().getBreakpointManager(); -// for (int i= 0, length= members.length; i < length; i++) { -// IField element= members[i]; -// IJavaBreakpoint breakpoint= getBreakpoint(element); -// if (breakpoint == null) { -// IType type = element.getDeclaringType(); -// int start = -1; -// int end = -1; -// ISourceRange range = element.getNameRange(); -// if (range != null) { -// start = range.getOffset(); -// end = start + range.getLength(); -// } -// Map attributes = new HashMap(10); -// BreakpointUtils.addJavaBreakpointAttributes(attributes, element); -// JDIDebugModel.createWatchpoint(BreakpointUtils.getBreakpointResource(type), type.getFullyQualifiedName(), element.getElementName(), -1, start, end, 0, true, attributes); -// } else { -// // remove breakpoint -// breakpointManager.removeBreakpoint(breakpoint, true); -// } -// } -// } + public void toggleWatchpoints(IWorkbenchPart part, ISelection selection) + throws CoreException { + // report(null, part); + // selection = translateToMembers(part, selection); + // if (selection instanceof ITextSelection) { + // ITextSelection textSelection= (ITextSelection) selection; + // CompilationUnit compilationUnit= + // parseCompilationUnit((ITextEditor)part); + // if (compilationUnit != null) { + // BreakpointFieldLocator locator= new + // BreakpointFieldLocator(textSelection.getOffset()); + // compilationUnit.accept(locator); + // String fieldName= locator.getFieldName(); + // if (fieldName == null) { + // report(ActionMessages.getString("ManageWatchpointActionDelegate.CantAdd"), + // part); //$NON-NLS-1$ + // return; + // } + // String typeName= locator.getTypeName(); + // // check if the watchpoint already exists. If yes, remove it + // IBreakpointManager breakpointManager= + // DebugPlugin.getDefault().getBreakpointManager(); + // IBreakpoint[] breakpoints= + // breakpointManager.getBreakpoints(JDIDebugModel.getPluginIdentifier()); + // for (int i= 0; i < breakpoints.length; i++) { + // IBreakpoint breakpoint= breakpoints[i]; + // if (breakpoint instanceof IJavaWatchpoint) { + // IJavaWatchpoint watchpoint= (IJavaWatchpoint)breakpoint; + // if (typeName.equals(watchpoint.getTypeName()) && + // fieldName.equals(watchpoint.getFieldName())) { + // breakpointManager.removeBreakpoint(watchpoint, true); + // return; + // } + // } + // } + // // add the watchpoint + // JDIDebugModel.createWatchpoint(getResource((IEditorPart)part), + // typeName, fieldName, -1, -1, -1, 0, true, new HashMap(10)); + // } + // } else if (selection instanceof IStructuredSelection) { + // IField[] members = getFields((IStructuredSelection)selection); + // if (members.length == 0) { + // report(ActionMessages.getString("ToggleBreakpointAdapter.10"), part); + // //$NON-NLS-1$ + // return; + // } + // // add or remove watchpoint + // IBreakpointManager breakpointManager= + // DebugPlugin.getDefault().getBreakpointManager(); + // for (int i= 0, length= members.length; i < length; i++) { + // IField element= members[i]; + // IJavaBreakpoint breakpoint= getBreakpoint(element); + // if (breakpoint == null) { + // IType type = element.getDeclaringType(); + // int start = -1; + // int end = -1; + // ISourceRange range = element.getNameRange(); + // if (range != null) { + // start = range.getOffset(); + // end = start + range.getLength(); + // } + // Map attributes = new HashMap(10); + // BreakpointUtils.addJavaBreakpointAttributes(attributes, element); + // JDIDebugModel.createWatchpoint(BreakpointUtils.getBreakpointResource(type), + // type.getFullyQualifiedName(), element.getElementName(), -1, start, + // end, 0, true, attributes); + // } else { + // // remove breakpoint + // breakpointManager.removeBreakpoint(breakpoint, true); + // } + // } + // } } - public static String resolveMethodSignature(IType type, String methodSignature) throws JavaModelException { - String[] parameterTypes= Signature.getParameterTypes(methodSignature); - int length= length= parameterTypes.length; - String[] resolvedParameterTypes= new String[length]; + public static String resolveMethodSignature(IType type, + String methodSignature) throws JavaModelException { + String[] parameterTypes = Signature.getParameterTypes(methodSignature); + int length = length = parameterTypes.length; + String[] resolvedParameterTypes = new String[length]; for (int i = 0; i < length; i++) { - resolvedParameterTypes[i]= resolveType(type, parameterTypes[i]); + resolvedParameterTypes[i] = resolveType(type, parameterTypes[i]); if (resolvedParameterTypes[i] == null) { return null; } } - String resolvedReturnType= resolveType(type, Signature.getReturnType(methodSignature)); + String resolvedReturnType = resolveType(type, Signature + .getReturnType(methodSignature)); if (resolvedReturnType == null) { return null; } - return Signature.createMethodSignature(resolvedParameterTypes, resolvedReturnType); + return Signature.createMethodSignature(resolvedParameterTypes, + resolvedReturnType); } - private static String resolveType(IType type, String typeSignature) throws JavaModelException { -// int count= Signature.getArrayCount(typeSignature); -// String elementTypeSignature= Signature.getElementType(typeSignature); -// if (elementTypeSignature.length() == 1) { -// // no need to resolve primitive types -// return typeSignature; -// } -// String elementTypeName= Signature.toString(elementTypeSignature); -// String[][] resolvedElementTypeNames= type.resolveType(elementTypeName); -// if (resolvedElementTypeNames == null || resolvedElementTypeNames.length != 1) { -// // the type name cannot be resolved -// return null; -// } -// String resolvedElementTypeName= Signature.toQualifiedName(resolvedElementTypeNames[0]); -// String resolvedElementTypeSignature= Signature.createTypeSignature(resolvedElementTypeName, true).replace('.', '/'); -// return Signature.createArraySignature(resolvedElementTypeSignature, count); + private static String resolveType(IType type, String typeSignature) + throws JavaModelException { + // int count= Signature.getArrayCount(typeSignature); + // String elementTypeSignature= Signature.getElementType(typeSignature); + // if (elementTypeSignature.length() == 1) { + // // no need to resolve primitive types + // return typeSignature; + // } + // String elementTypeName= Signature.toString(elementTypeSignature); + // String[][] resolvedElementTypeNames= + // type.resolveType(elementTypeName); + // if (resolvedElementTypeNames == null || + // resolvedElementTypeNames.length != 1) { + // // the type name cannot be resolved + // return null; + // } + // String resolvedElementTypeName= + // Signature.toQualifiedName(resolvedElementTypeNames[0]); + // String resolvedElementTypeSignature= + // Signature.createTypeSignature(resolvedElementTypeName, + // true).replace('.', '/'); + // return Signature.createArraySignature(resolvedElementTypeSignature, + // count); return ""; } @@ -405,27 +486,30 @@ public class ToggleBreakpointAdapter implements IToggleBreakpointsTarget { IResource resource; IEditorInput editorInput = editor.getEditorInput(); if (editorInput instanceof IFileEditorInput) { - resource= ((IFileEditorInput)editorInput).getFile(); + resource = ((IFileEditorInput) editorInput).getFile(); } else { - resource= ResourcesPlugin.getWorkspace().getRoot(); + resource = ResourcesPlugin.getWorkspace().getRoot(); } return resource; } /** * Returns a handle to the specified method or null if none. - * - * @param editorPart the editor containing the method + * + * @param editorPart + * the editor containing the method * @param typeName * @param methodName * @param signature * @return handle or null */ - protected IMethod getMethodHandle(IEditorPart editorPart, String typeName, String methodName, String signature) throws CoreException { - IJavaElement element = (IJavaElement) editorPart.getEditorInput().getAdapter(IJavaElement.class); + protected IMethod getMethodHandle(IEditorPart editorPart, String typeName, + String methodName, String signature) throws CoreException { + IJavaElement element = (IJavaElement) editorPart.getEditorInput() + .getAdapter(IJavaElement.class); IType type = null; if (element instanceof ICompilationUnit) { - IType[] types = ((ICompilationUnit)element).getAllTypes(); + IType[] types = ((ICompilationUnit) element).getAllTypes(); for (int i = 0; i < types.length; i++) { if (types[i].getFullyQualifiedName().equals(typeName)) { type = types[i]; @@ -433,9 +517,9 @@ public class ToggleBreakpointAdapter implements IToggleBreakpointsTarget { } } } -// else if (element instanceof IClassFile) { -// type = ((IClassFile)element).getType(); -// } + // else if (element instanceof IClassFile) { + // type = ((IClassFile)element).getType(); + // } if (type != null) { String[] sigs = Signature.getParameterTypes(signature); return type.getMethod(methodName, sigs); @@ -443,260 +527,280 @@ public class ToggleBreakpointAdapter implements IToggleBreakpointsTarget { return null; } -// protected IJavaBreakpoint getBreakpoint(IMember element) { -// IBreakpointManager breakpointManager= DebugPlugin.getDefault().getBreakpointManager(); -// IBreakpoint[] breakpoints= breakpointManager.getBreakpoints(JDIDebugModel.getPluginIdentifier()); -// if (element instanceof IMethod) { -// IMethod method= (IMethod)element; -// for (int i= 0; i < breakpoints.length; i++) { -// IBreakpoint breakpoint= breakpoints[i]; -// if (breakpoint instanceof IJavaMethodBreakpoint) { -// IJavaMethodBreakpoint methodBreakpoint= (IJavaMethodBreakpoint)breakpoint; -// IMember container = null; -// try { -// container= BreakpointUtils.getMember(methodBreakpoint); -// } catch (CoreException e) { -// JDIDebugUIPlugin.log(e); -// return null; -// } -// if (container == null) { -// try { -// if (method.getDeclaringType().getFullyQualifiedName().equals(methodBreakpoint.getTypeName()) -// && method.getElementName().equals(methodBreakpoint.getMethodName()) -// && method.getSignature().equals(methodBreakpoint.getMethodSignature())) { -// return methodBreakpoint; -// } -// } catch (CoreException e) { -// JDIDebugUIPlugin.log(e); -// } -// } else { -// if (container instanceof IMethod) { -// if (method.getDeclaringType().getFullyQualifiedName().equals(container.getDeclaringType().getFullyQualifiedName())) { -// if (method.isSimilar((IMethod)container)) { -// return methodBreakpoint; -// } -// } -// } -// } -// } -// } -// } else if (element instanceof IField) { -// for (int i= 0; i < breakpoints.length; i++) { -// IBreakpoint breakpoint= breakpoints[i]; -// if (breakpoint instanceof IJavaWatchpoint) { -// try { -// if (equalFields(element, (IJavaWatchpoint)breakpoint)) -// return (IJavaBreakpoint)breakpoint; -// } catch (CoreException e) { -// JDIDebugUIPlugin.log(e); -// } -// } -// } -// } -// return null; -// } + // protected IJavaBreakpoint getBreakpoint(IMember element) { + // IBreakpointManager breakpointManager= + // DebugPlugin.getDefault().getBreakpointManager(); + // IBreakpoint[] breakpoints= + // breakpointManager.getBreakpoints(JDIDebugModel.getPluginIdentifier()); + // if (element instanceof IMethod) { + // IMethod method= (IMethod)element; + // for (int i= 0; i < breakpoints.length; i++) { + // IBreakpoint breakpoint= breakpoints[i]; + // if (breakpoint instanceof IJavaMethodBreakpoint) { + // IJavaMethodBreakpoint methodBreakpoint= + // (IJavaMethodBreakpoint)breakpoint; + // IMember container = null; + // try { + // container= BreakpointUtils.getMember(methodBreakpoint); + // } catch (CoreException e) { + // JDIDebugUIPlugin.log(e); + // return null; + // } + // if (container == null) { + // try { + // if + // (method.getDeclaringType().getFullyQualifiedName().equals(methodBreakpoint.getTypeName()) + // && method.getElementName().equals(methodBreakpoint.getMethodName()) + // && method.getSignature().equals(methodBreakpoint.getMethodSignature())) { + // return methodBreakpoint; + // } + // } catch (CoreException e) { + // JDIDebugUIPlugin.log(e); + // } + // } else { + // if (container instanceof IMethod) { + // if + // (method.getDeclaringType().getFullyQualifiedName().equals(container.getDeclaringType().getFullyQualifiedName())) + // { + // if (method.isSimilar((IMethod)container)) { + // return methodBreakpoint; + // } + // } + // } + // } + // } + // } + // } else if (element instanceof IField) { + // for (int i= 0; i < breakpoints.length; i++) { + // IBreakpoint breakpoint= breakpoints[i]; + // if (breakpoint instanceof IJavaWatchpoint) { + // try { + // if (equalFields(element, (IJavaWatchpoint)breakpoint)) + // return (IJavaBreakpoint)breakpoint; + // } catch (CoreException e) { + // JDIDebugUIPlugin.log(e); + // } + // } + // } + // } + // return null; + // } /** - * Compare two fields. The default equals() - * method for IField doesn't give the comparison desired. + * Compare two fields. The default equals() method for + * IField doesn't give the comparison desired. */ -// private boolean equalFields(IMember breakpointField, IJavaWatchpoint watchpoint) throws CoreException { -// return (breakpointField.getElementName().equals(watchpoint.getFieldName()) && -// breakpointField.getDeclaringType().getFullyQualifiedName().equals(watchpoint.getTypeName())); -// } -// -// protected CompilationUnit parseCompilationUnit(ITextEditor editor) { -// IEditorInput editorInput = editor.getEditorInput(); -// IDocument document= editor.getDocumentProvider().getDocument(editorInput); -// ASTParser parser = ASTParser.newParser(AST.JLS2); -// parser.setSource(document.get().toCharArray()); -// return (CompilationUnit) parser.createAST(null); -// } - - /* (non-Javadoc) - * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#canToggleWatchpoints(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection) + // private boolean equalFields(IMember breakpointField, IJavaWatchpoint + // watchpoint) throws CoreException { + // return + // (breakpointField.getElementName().equals(watchpoint.getFieldName()) && + // breakpointField.getDeclaringType().getFullyQualifiedName().equals(watchpoint.getTypeName())); + // } + // + // protected CompilationUnit parseCompilationUnit(ITextEditor editor) { + // IEditorInput editorInput = editor.getEditorInput(); + // IDocument document= + // editor.getDocumentProvider().getDocument(editorInput); + // ASTParser parser = ASTParser.newParser(AST.JLS2); + // parser.setSource(document.get().toCharArray()); + // return (CompilationUnit) parser.createAST(null); + // } + /* + * (non-Javadoc) + * + * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#canToggleWatchpoints(org.eclipse.ui.IWorkbenchPart, + * org.eclipse.jface.viewers.ISelection) */ - public boolean canToggleWatchpoints(IWorkbenchPart part, ISelection selection) { -// if (selection instanceof IStructuredSelection) { -// IStructuredSelection ss = (IStructuredSelection) selection; -// return getFields(ss).length > 0; -// } else { -// return selection instanceof ITextSelection; -// } + public boolean canToggleWatchpoints(IWorkbenchPart part, + ISelection selection) { + // if (selection instanceof IStructuredSelection) { + // IStructuredSelection ss = (IStructuredSelection) selection; + // return getFields(ss).length > 0; + // } else { + // return selection instanceof ITextSelection; + // } return false; } /** - * Returns a selection of the member in the given text selection, - * or the original selection if none. - * + * Returns a selection of the member in the given text selection, or the + * original selection if none. + * * @param part * @param selection * @return a structured selection of the member in the given text selection, - * or the original selection if none - * @exception CoreException if an exceptoin occurrs + * or the original selection if none + * @exception CoreException + * if an exceptoin occurrs */ -// protected ISelection translateToMembers(IWorkbenchPart part, ISelection selection) throws CoreException { -// if (selection instanceof ITextSelection && part instanceof IEditorPart) { -// ITextSelection textSelection = (ITextSelection)selection; -// IEditorPart editorPart = (IEditorPart) part; -// IEditorInput editorInput = editorPart.getEditorInput(); -// IMember m= null; -// IClassFile classFile= (IClassFile)editorInput.getAdapter(IClassFile.class); -// if (classFile != null) { -// IJavaElement e= classFile.getElementAt(textSelection.getOffset()); -// if (e instanceof IMember) { -// m= (IMember)e; -// } -// } else { -// IWorkingCopyManager manager= JavaUI.getWorkingCopyManager(); -// ICompilationUnit unit= manager.getWorkingCopy(editorInput); -// if (unit != null) { -// synchronized (unit) { -// unit.reconcile(ICompilationUnit.NO_AST /*don't create ast*/, false/*don't force problem detection*/, null/*use primary owner*/, null/*no progress monitor*/); -// } -// IJavaElement e = unit.getElementAt(textSelection.getOffset()); -// if (e instanceof IMember) { -// m= (IMember)e; -// } -// } -// } -// if (m != null) { -// return new StructuredSelection(m); -// } -// } -// return selection; -// } - + // protected ISelection translateToMembers(IWorkbenchPart part, ISelection + // selection) throws CoreException { + // if (selection instanceof ITextSelection && part instanceof IEditorPart) { + // ITextSelection textSelection = (ITextSelection)selection; + // IEditorPart editorPart = (IEditorPart) part; + // IEditorInput editorInput = editorPart.getEditorInput(); + // IMember m= null; + // IClassFile classFile= + // (IClassFile)editorInput.getAdapter(IClassFile.class); + // if (classFile != null) { + // IJavaElement e= classFile.getElementAt(textSelection.getOffset()); + // if (e instanceof IMember) { + // m= (IMember)e; + // } + // } else { + // IWorkingCopyManager manager= JavaUI.getWorkingCopyManager(); + // ICompilationUnit unit= manager.getWorkingCopy(editorInput); + // if (unit != null) { + // synchronized (unit) { + // unit.reconcile(ICompilationUnit.NO_AST /*don't create ast*/, false/*don't + // force problem detection*/, null/*use primary owner*/, null/*no progress + // monitor*/); + // } + // IJavaElement e = unit.getElementAt(textSelection.getOffset()); + // if (e instanceof IMember) { + // m= (IMember)e; + // } + // } + // } + // if (m != null) { + // return new StructuredSelection(m); + // } + // } + // return selection; + // } /** - * Returns a list of matching types (IType - Java model) that correspond to the - * declaring type (ReferenceType - JDI model) of the given variable. + * Returns a list of matching types (IType - Java model) that correspond to + * the declaring type (ReferenceType - JDI model) of the given variable. */ -// protected static List searchForDeclaringType(IJavaFieldVariable variable) { -// List types= new ArrayList(); -// ILaunch launch = variable.getDebugTarget().getLaunch(); -// if (launch == null) { -// return types; -// } -// -// ILaunchConfiguration configuration= launch.getLaunchConfiguration(); -// IJavaProject[] javaProjects = null; -// IWorkspace workspace= ResourcesPlugin.getWorkspace(); -// if (configuration != null) { -// // Launch configuration support -// try { -// String projectName= configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$ -// if (projectName.length() != 0) { -// javaProjects= new IJavaProject[] {JavaCore.create(workspace.getRoot().getProject(projectName))}; -// } else { -// IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects(); -// IProject project; -// List projectList= new ArrayList(); -// for (int i= 0, numProjects= projects.length; i < numProjects; i++) { -// project= projects[i]; -// if (project.isAccessible() && project.hasNature(JavaCore.NATURE_ID)) { -// projectList.add(JavaCore.create(project)); -// } -// } -// javaProjects= new IJavaProject[projectList.size()]; -// projectList.toArray(javaProjects); -// } -// } catch (CoreException e) { -// JDIDebugUIPlugin.log(e); -// } -// } -// if (javaProjects == null) { -// return types; -// } -// -// SearchEngine engine= new SearchEngine(); -// IJavaSearchScope scope= SearchEngine.createJavaSearchScope(javaProjects, true); -// String declaringType= null; -// try { -// declaringType= variable.getDeclaringType().getName(); -// } catch (DebugException x) { -// JDIDebugUIPlugin.log(x); -// return types; -// } -// ArrayList typeRefsFound= new ArrayList(3); -// ITypeNameRequestor requestor= new TypeInfoRequestor(typeRefsFound); -// try { -// engine.searchAllTypeNames( -// getPackage(declaringType), -// getTypeName(declaringType), -// SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE, -// IJavaSearchConstants.CLASS, -// scope, -// requestor, -// IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, -// null); -// } catch (JavaModelException x) { -// JDIDebugUIPlugin.log(x); -// return types; -// } -// Iterator iter= typeRefsFound.iterator(); -// TypeInfo typeInfo= null; -// while (iter.hasNext()) { -// typeInfo= (TypeInfo)iter.next(); -// try { -// types.add(typeInfo.resolveType(scope)); -// } catch (JavaModelException jme) { -// JDIDebugUIPlugin.log(jme); -// } -// } -// return types; -// } - + // protected static List searchForDeclaringType(IJavaFieldVariable variable) + // { + // List types= new ArrayList(); + // ILaunch launch = variable.getDebugTarget().getLaunch(); + // if (launch == null) { + // return types; + // } + // + // ILaunchConfiguration configuration= launch.getLaunchConfiguration(); + // IJavaProject[] javaProjects = null; + // IWorkspace workspace= ResourcesPlugin.getWorkspace(); + // if (configuration != null) { + // // Launch configuration support + // try { + // String projectName= + // configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, + // ""); //$NON-NLS-1$ + // if (projectName.length() != 0) { + // javaProjects= new IJavaProject[] + // {JavaCore.create(workspace.getRoot().getProject(projectName))}; + // } else { + // IProject[] projects= + // ResourcesPlugin.getWorkspace().getRoot().getProjects(); + // IProject project; + // List projectList= new ArrayList(); + // for (int i= 0, numProjects= projects.length; i < numProjects; i++) { + // project= projects[i]; + // if (project.isAccessible() && project.hasNature(JavaCore.NATURE_ID)) { + // projectList.add(JavaCore.create(project)); + // } + // } + // javaProjects= new IJavaProject[projectList.size()]; + // projectList.toArray(javaProjects); + // } + // } catch (CoreException e) { + // JDIDebugUIPlugin.log(e); + // } + // } + // if (javaProjects == null) { + // return types; + // } + // + // SearchEngine engine= new SearchEngine(); + // IJavaSearchScope scope= SearchEngine.createJavaSearchScope(javaProjects, + // true); + // String declaringType= null; + // try { + // declaringType= variable.getDeclaringType().getName(); + // } catch (DebugException x) { + // JDIDebugUIPlugin.log(x); + // return types; + // } + // ArrayList typeRefsFound= new ArrayList(3); + // ITypeNameRequestor requestor= new TypeInfoRequestor(typeRefsFound); + // try { + // engine.searchAllTypeNames( + // getPackage(declaringType), + // getTypeName(declaringType), + // SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE, + // IJavaSearchConstants.CLASS, + // scope, + // requestor, + // IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, + // null); + // } catch (JavaModelException x) { + // JDIDebugUIPlugin.log(x); + // return types; + // } + // Iterator iter= typeRefsFound.iterator(); + // TypeInfo typeInfo= null; + // while (iter.hasNext()) { + // typeInfo= (TypeInfo)iter.next(); + // try { + // types.add(typeInfo.resolveType(scope)); + // } catch (JavaModelException jme) { + // JDIDebugUIPlugin.log(jme); + // } + // } + // return types; + // } /** - * Returns the package name of the given fully qualified type name. - * The package name is assumed to be the dot-separated prefix of the - * type name. + * Returns the package name of the given fully qualified type name. The + * package name is assumed to be the dot-separated prefix of the type name. */ -// protected static char[] getPackage(String fullyQualifiedName) { -// int index= fullyQualifiedName.lastIndexOf('.'); -// if (index == -1) { -// return new char[0]; -// } -// return fullyQualifiedName.substring(0, index).toCharArray(); -// } -// -// /** -// * Returns a simple type name from the given fully qualified type name. -// * The type name is assumed to be the last contiguous segment of the -// * fullyQualifiedName not containing a '.' or '$' -// */ -// protected static char[] getTypeName(String fullyQualifiedName) { -// int index= fullyQualifiedName.lastIndexOf('.'); -// String typeName= fullyQualifiedName.substring(index + 1); -// int lastInnerClass= typeName.lastIndexOf('$'); -// if (lastInnerClass != -1) { -// typeName= typeName.substring(lastInnerClass + 1); -// } -// return typeName.toCharArray(); -// } -// -// /** -// * Return the associated IField (Java model) for the given -// * IJavaFieldVariable (JDI model) -// */ -// private IField getField(IJavaFieldVariable variable) { -// String varName= null; -// try { -// varName= variable.getName(); -// } catch (DebugException x) { -// JDIDebugUIPlugin.log(x); -// return null; -// } -// IField field; -// List types= searchForDeclaringType(variable); -// Iterator iter= types.iterator(); -// while (iter.hasNext()) { -// IType type= (IType)iter.next(); -// field= type.getField(varName); -// if (field.exists()) { -// return field; -// } -// } -// return null; -// } + // protected static char[] getPackage(String fullyQualifiedName) { + // int index= fullyQualifiedName.lastIndexOf('.'); + // if (index == -1) { + // return new char[0]; + // } + // return fullyQualifiedName.substring(0, index).toCharArray(); + // } + // + // /** + // * Returns a simple type name from the given fully qualified type name. + // * The type name is assumed to be the last contiguous segment of the + // * fullyQualifiedName not containing a '.' or '$' + // */ + // protected static char[] getTypeName(String fullyQualifiedName) { + // int index= fullyQualifiedName.lastIndexOf('.'); + // String typeName= fullyQualifiedName.substring(index + 1); + // int lastInnerClass= typeName.lastIndexOf('$'); + // if (lastInnerClass != -1) { + // typeName= typeName.substring(lastInnerClass + 1); + // } + // return typeName.toCharArray(); + // } + // + // /** + // * Return the associated IField (Java model) for the given + // * IJavaFieldVariable (JDI model) + // */ + // private IField getField(IJavaFieldVariable variable) { + // String varName= null; + // try { + // varName= variable.getName(); + // } catch (DebugException x) { + // JDIDebugUIPlugin.log(x); + // return null; + // } + // IField field; + // List types= searchForDeclaringType(variable); + // Iterator iter= types.iterator(); + // while (iter.hasNext()) { + // IType type= (IType)iter.next(); + // field= type.getField(varName); + // if (field.exists()) { + // return field; + // } + // } + // return null; + // } } diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/ExecutionArguments.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/ExecutionArguments.java index 108e2fb..79311cd 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/ExecutionArguments.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/ExecutionArguments.java @@ -5,32 +5,45 @@ import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.QualifiedName; public class ExecutionArguments { - protected static final QualifiedName EXECUTION_ARGUMENTS_PROPERTY = new QualifiedName("net.sourceforge.phpdt", "executionArguments"); + protected static final QualifiedName EXECUTION_ARGUMENTS_PROPERTY = new QualifiedName( + "net.sourceforge.phpdt", "executionArguments"); + protected static final String ARGUMENT_SEPARATOR = "****"; - + protected String interpreterArguments, phpFileArguments; public static ExecutionArguments getExecutionArguments(IFile phpScriptFile) { try { - String executionArgumentsPersistableFormat = phpScriptFile.getPersistentProperty(EXECUTION_ARGUMENTS_PROPERTY); + String executionArgumentsPersistableFormat = phpScriptFile + .getPersistentProperty(EXECUTION_ARGUMENTS_PROPERTY); ExecutionArguments executionArguments = new ExecutionArguments(); - - if (executionArgumentsPersistableFormat != null) { - int argBreakIndex = executionArgumentsPersistableFormat.indexOf(ARGUMENT_SEPARATOR); - executionArguments.setInterpreterArguments(executionArgumentsPersistableFormat.substring(0, argBreakIndex)); - executionArguments.setPHPFileArguments(executionArgumentsPersistableFormat.substring(argBreakIndex + ARGUMENT_SEPARATOR.length())); + + if (executionArgumentsPersistableFormat != null) { + int argBreakIndex = executionArgumentsPersistableFormat + .indexOf(ARGUMENT_SEPARATOR); + executionArguments + .setInterpreterArguments(executionArgumentsPersistableFormat + .substring(0, argBreakIndex)); + executionArguments + .setPHPFileArguments(executionArgumentsPersistableFormat + .substring(argBreakIndex + + ARGUMENT_SEPARATOR.length())); } - + return executionArguments; - } catch (CoreException e) {} - + } catch (CoreException e) { + } + return null; } - public static void setExecutionArguments(IFile phpScriptFile, ExecutionArguments arguments) { + public static void setExecutionArguments(IFile phpScriptFile, + ExecutionArguments arguments) { try { - phpScriptFile.setPersistentProperty(EXECUTION_ARGUMENTS_PROPERTY, arguments.toPersistableFormat()); - } catch (CoreException e) {} + phpScriptFile.setPersistentProperty(EXECUTION_ARGUMENTS_PROPERTY, + arguments.toPersistableFormat()); + } catch (CoreException e) { + } } public void setInterpreterArguments(String theArguments) { diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/LoadPathEntryLabelProvider.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/LoadPathEntryLabelProvider.java index 6784d49..7831922 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/LoadPathEntryLabelProvider.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/LoadPathEntryLabelProvider.java @@ -10,7 +10,7 @@ import org.eclipse.swt.graphics.Image; /** * @author xp4 - * + * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. */ @@ -28,9 +28,11 @@ public class LoadPathEntryLabelProvider implements ILabelProvider { */ public String getText(Object element) { if (element != null && element.getClass() == LoadPathEntry.class) - return ((LoadPathEntry) element).getProject().getLocation().toOSString(); - - PHPDebugUiPlugin.log(new RuntimeException("Unable to render load path.")); + return ((LoadPathEntry) element).getProject().getLocation() + .toOSString(); + + PHPDebugUiPlugin + .log(new RuntimeException("Unable to render load path.")); return null; } diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/PHPApplicationTabGroup.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/PHPApplicationTabGroup.java index f4e47f6..6b0ea92 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/PHPApplicationTabGroup.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/PHPApplicationTabGroup.java @@ -6,24 +6,21 @@ import org.eclipse.debug.ui.ILaunchConfigurationDialog; import org.eclipse.debug.ui.ILaunchConfigurationTab; import org.eclipse.debug.ui.ILaunchConfigurationTabGroup; -public class PHPApplicationTabGroup - extends AbstractLaunchConfigurationTabGroup { +public class PHPApplicationTabGroup extends AbstractLaunchConfigurationTabGroup { public PHPApplicationTabGroup() { super(); } /** - * @see ILaunchConfigurationTabGroup#createTabs(ILaunchConfigurationDialog, String) + * @see ILaunchConfigurationTabGroup#createTabs(ILaunchConfigurationDialog, + * String) */ public void createTabs(ILaunchConfigurationDialog dialog, String mode) { ILaunchConfigurationTab[] tabs = new ILaunchConfigurationTab[] { - new PHPEntryPointTab(), - new PHPArgumentsTab(), - new PHPEnvironmentTab(), - new PHPEnvironmentTab2(), - new CommonTab() - }; + new PHPEntryPointTab(), new PHPArgumentsTab(), + new PHPEnvironmentTab(), new PHPEnvironmentTab2(), + new CommonTab() }; setTabs(tabs); } diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/PHPArgumentsTab.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/PHPArgumentsTab.java index 26ff6c7..2368be5 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/PHPArgumentsTab.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/PHPArgumentsTab.java @@ -26,7 +26,9 @@ import org.eclipse.swt.widgets.Text; public class PHPArgumentsTab extends AbstractLaunchConfigurationTab { protected Text interpreterArgsText, programArgsText; + protected DirectorySelector workingDirectorySelector; + protected Button useDefaultWorkingDirectoryButton; public PHPArgumentsTab() { @@ -36,35 +38,51 @@ public class PHPArgumentsTab extends AbstractLaunchConfigurationTab { public void createControl(Composite parent) { Composite composite = createPageRoot(parent); - new Label(composite, SWT.NONE).setText(PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPArguments.working_dir")); + new Label(composite, SWT.NONE).setText(PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPArguments.working_dir")); workingDirectorySelector = new DirectorySelector(composite); - workingDirectorySelector.setBrowseDialogMessage(PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPArguments.working_dir_browser_message")); - workingDirectorySelector.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + workingDirectorySelector + .setBrowseDialogMessage(PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPArguments.working_dir_browser_message")); + workingDirectorySelector.setLayoutData(new GridData( + GridData.FILL_HORIZONTAL)); workingDirectorySelector.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { updateLaunchConfigurationDialog(); } }); - Composite defaultWorkingDirectoryComposite = new Composite(composite, SWT.NONE); + Composite defaultWorkingDirectoryComposite = new Composite(composite, + SWT.NONE); GridLayout layout = new GridLayout(); layout.numColumns = 2; defaultWorkingDirectoryComposite.setLayout(layout); - useDefaultWorkingDirectoryButton = new Button(defaultWorkingDirectoryComposite, SWT.CHECK); - useDefaultWorkingDirectoryButton.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - setUseDefaultWorkingDirectory(((Button) e.getSource()).getSelection()); - } - }); - new Label(defaultWorkingDirectoryComposite, SWT.NONE).setText(PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPArguments.working_dir_use_default_message")); + useDefaultWorkingDirectoryButton = new Button( + defaultWorkingDirectoryComposite, SWT.CHECK); + useDefaultWorkingDirectoryButton + .addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + setUseDefaultWorkingDirectory(((Button) e.getSource()) + .getSelection()); + } + }); + new Label(defaultWorkingDirectoryComposite, SWT.NONE) + .setText(PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPArguments.working_dir_use_default_message")); defaultWorkingDirectoryComposite.pack(); - new Label(composite, SWT.NONE).setText(PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPArguments.interpreter_args_box_title")); - interpreterArgsText = new Text(composite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); + new Label(composite, SWT.NONE) + .setText(PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPArguments.interpreter_args_box_title")); + interpreterArgsText = new Text(composite, SWT.MULTI | SWT.V_SCROLL + | SWT.BORDER); interpreterArgsText.setLayoutData(new GridData(GridData.FILL_BOTH)); - new Label(composite, SWT.NONE).setText(PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPArguments.program_args_box_title")); - programArgsText = new Text(composite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); + new Label(composite, SWT.NONE) + .setText(PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPArguments.program_args_box_title")); + programArgsText = new Text(composite, SWT.MULTI | SWT.V_SCROLL + | SWT.BORDER); programArgsText.setLayoutData(new GridData(GridData.FILL_BOTH)); } @@ -72,24 +90,34 @@ public class PHPArgumentsTab extends AbstractLaunchConfigurationTab { if (!useDefaultWorkingDirectoryButton.getSelection() == useDefault) useDefaultWorkingDirectoryButton.setSelection(useDefault); if (useDefault) - workingDirectorySelector.setSelectionText(PHPDebugUiConstants.DEFAULT_WORKING_DIRECTORY); + workingDirectorySelector + .setSelectionText(PHPDebugUiConstants.DEFAULT_WORKING_DIRECTORY); workingDirectorySelector.setEnabled(!useDefault); } public void setDefaults(ILaunchConfigurationWorkingCopy configuration) { - configuration.setAttribute(PHPLaunchConfigurationAttribute.WORKING_DIRECTORY, PHPDebugUiConstants.DEFAULT_WORKING_DIRECTORY); + configuration.setAttribute( + PHPLaunchConfigurationAttribute.WORKING_DIRECTORY, + PHPDebugUiConstants.DEFAULT_WORKING_DIRECTORY); // set hidden attribute - configuration.setAttribute(ILaunchConfiguration.ATTR_SOURCE_LOCATOR_ID, "net.sourceforge.phpdt.debug.ui.PHPSourceLocator") ; + configuration.setAttribute(ILaunchConfiguration.ATTR_SOURCE_LOCATOR_ID, + "net.sourceforge.phpdt.debug.ui.PHPSourceLocator"); } public void initializeFrom(ILaunchConfiguration configuration) { String workingDirectory = "", interpreterArgs = "", programArgs = ""; boolean useDefaultWorkDir = true; try { - workingDirectory = configuration.getAttribute(PHPLaunchConfigurationAttribute.WORKING_DIRECTORY, ""); - interpreterArgs = configuration.getAttribute(PHPLaunchConfigurationAttribute.INTERPRETER_ARGUMENTS, ""); - programArgs = configuration.getAttribute(PHPLaunchConfigurationAttribute.PROGRAM_ARGUMENTS, ""); - useDefaultWorkDir = configuration.getAttribute(PHPLaunchConfigurationAttribute.USE_DEFAULT_WORKING_DIRECTORY, true); + workingDirectory = configuration.getAttribute( + PHPLaunchConfigurationAttribute.WORKING_DIRECTORY, ""); + interpreterArgs = configuration.getAttribute( + PHPLaunchConfigurationAttribute.INTERPRETER_ARGUMENTS, ""); + programArgs = configuration.getAttribute( + PHPLaunchConfigurationAttribute.PROGRAM_ARGUMENTS, ""); + useDefaultWorkDir = configuration + .getAttribute( + PHPLaunchConfigurationAttribute.USE_DEFAULT_WORKING_DIRECTORY, + true); } catch (CoreException e) { log(e); } @@ -101,10 +129,18 @@ public class PHPArgumentsTab extends AbstractLaunchConfigurationTab { } public void performApply(ILaunchConfigurationWorkingCopy configuration) { - configuration.setAttribute(PHPLaunchConfigurationAttribute.WORKING_DIRECTORY, workingDirectorySelector.getValidatedSelectionText()); - configuration.setAttribute(PHPLaunchConfigurationAttribute.INTERPRETER_ARGUMENTS, interpreterArgsText.getText()); - configuration.setAttribute(PHPLaunchConfigurationAttribute.PROGRAM_ARGUMENTS, programArgsText.getText()); - configuration.setAttribute(PHPLaunchConfigurationAttribute.USE_DEFAULT_WORKING_DIRECTORY, useDefaultWorkingDirectoryButton.getSelection()); + configuration.setAttribute( + PHPLaunchConfigurationAttribute.WORKING_DIRECTORY, + workingDirectorySelector.getValidatedSelectionText()); + configuration.setAttribute( + PHPLaunchConfigurationAttribute.INTERPRETER_ARGUMENTS, + interpreterArgsText.getText()); + configuration.setAttribute( + PHPLaunchConfigurationAttribute.PROGRAM_ARGUMENTS, + programArgsText.getText()); + configuration.setAttribute( + PHPLaunchConfigurationAttribute.USE_DEFAULT_WORKING_DIRECTORY, + useDefaultWorkingDirectoryButton.getSelection()); } protected Composite createPageRoot(Composite parent) { @@ -119,14 +155,17 @@ public class PHPArgumentsTab extends AbstractLaunchConfigurationTab { } public String getName() { - return PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPArguments.name"); + return PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPArguments.name"); } public boolean isValid(ILaunchConfiguration launchConfig) { try { - String workingDirectory = launchConfig.getAttribute(PHPLaunchConfigurationAttribute.WORKING_DIRECTORY, ""); + String workingDirectory = launchConfig.getAttribute( + PHPLaunchConfigurationAttribute.WORKING_DIRECTORY, ""); if (workingDirectory.length() == 0) { - setErrorMessage(PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPArguments.working_dir_error_message")); + setErrorMessage(PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPArguments.working_dir_error_message")); return false; } } catch (CoreException e) { diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/PHPEntryPointTab.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/PHPEntryPointTab.java index 37007fb..57c3e81 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/PHPEntryPointTab.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/PHPEntryPointTab.java @@ -42,10 +42,13 @@ public class PHPEntryPointTab extends AbstractLaunchConfigurationTab { public void createControl(Composite parent) { Composite composite = createPageRoot(parent); - new Label(composite, SWT.NONE).setText(PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPEntryPoint.projectLabel")); + new Label(composite, SWT.NONE) + .setText(PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPEntryPoint.projectLabel")); projectSelector = new PHPProjectSelector(composite); - projectSelector.setBrowseDialogMessage(PHPDebugUiMessages - .getString("LaunchConfigurationTab.PHPEntryPoint.projectSelectorMessage")); + projectSelector + .setBrowseDialogMessage(PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPEntryPoint.projectSelectorMessage")); projectSelector.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); projectSelector.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent evt) { @@ -53,9 +56,12 @@ public class PHPEntryPointTab extends AbstractLaunchConfigurationTab { } }); - new Label(composite, SWT.NONE).setText(PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPEntryPoint.fileLabel")); + new Label(composite, SWT.NONE).setText(PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPEntryPoint.fileLabel")); fileSelector = new PHPFileSelector(composite, projectSelector); - fileSelector.setBrowseDialogMessage(PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPEntryPoint.fileSelectorMessage")); + fileSelector + .setBrowseDialogMessage(PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPEntryPoint.fileSelectorMessage")); fileSelector.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fileSelector.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent evt) { @@ -91,29 +97,38 @@ public class PHPEntryPointTab extends AbstractLaunchConfigurationTab { public void setDefaults(ILaunchConfigurationWorkingCopy configuration) { IResource file = getContext(); if (file != null) { - configuration.setAttribute(PHPLaunchConfigurationAttribute.PROJECT_NAME, file.getProject().getName()); - configuration.setAttribute(PHPLaunchConfigurationAttribute.FILE_NAME,file.getProjectRelativePath().toOSString()); + configuration.setAttribute( + PHPLaunchConfigurationAttribute.PROJECT_NAME, file + .getProject().getName()); + configuration.setAttribute( + PHPLaunchConfigurationAttribute.FILE_NAME, file + .getProjectRelativePath().toOSString()); } } public void initializeFrom(ILaunchConfiguration configuration) { try { - originalProjectName = configuration.getAttribute(PHPLaunchConfigurationAttribute.PROJECT_NAME, ""); - originalFileName = configuration.getAttribute(PHPLaunchConfigurationAttribute.FILE_NAME, ""); + originalProjectName = configuration.getAttribute( + PHPLaunchConfigurationAttribute.PROJECT_NAME, ""); + originalFileName = configuration.getAttribute( + PHPLaunchConfigurationAttribute.FILE_NAME, ""); } catch (CoreException e) { log(e); } projectSelector.setSelectionText(originalProjectName); if (!"".equals(originalFileName)) - fileSelector.setSelectionText(new Path(originalFileName).toOSString()); + fileSelector.setSelectionText(new Path(originalFileName) + .toOSString()); } public void performApply(ILaunchConfigurationWorkingCopy configuration) { - configuration.setAttribute(PHPLaunchConfigurationAttribute.PROJECT_NAME, projectSelector.getSelectionText()); + configuration.setAttribute( + PHPLaunchConfigurationAttribute.PROJECT_NAME, projectSelector + .getSelectionText()); IFile file = fileSelector.getSelection(); - configuration.setAttribute(PHPLaunchConfigurationAttribute.FILE_NAME, file == null ? "" : file.getProjectRelativePath() - .toString()); + configuration.setAttribute(PHPLaunchConfigurationAttribute.FILE_NAME, + file == null ? "" : file.getProjectRelativePath().toString()); } protected Composite createPageRoot(Composite parent) { @@ -127,21 +142,26 @@ public class PHPEntryPointTab extends AbstractLaunchConfigurationTab { } public String getName() { - return PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPEntryPoint.name"); + return PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPEntryPoint.name"); } public boolean isValid(ILaunchConfiguration launchConfig) { try { - String projectName = launchConfig.getAttribute(PHPLaunchConfigurationAttribute.PROJECT_NAME, ""); + String projectName = launchConfig.getAttribute( + PHPLaunchConfigurationAttribute.PROJECT_NAME, ""); if (projectName.length() == 0) { - setErrorMessage(PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPEntryPoint.invalidProjectSelectionMessage")); + setErrorMessage(PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPEntryPoint.invalidProjectSelectionMessage")); return false; } - String fileName = launchConfig.getAttribute(PHPLaunchConfigurationAttribute.FILE_NAME, ""); + String fileName = launchConfig.getAttribute( + PHPLaunchConfigurationAttribute.FILE_NAME, ""); if (fileName.length() == 0) { - setErrorMessage(PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPEntryPoint.invalidFileSelectionMessage")); + setErrorMessage(PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPEntryPoint.invalidFileSelectionMessage")); return false; } } catch (CoreException e) { diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/PHPEnvironmentTab.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/PHPEnvironmentTab.java index 7146d15..0257ce1 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/PHPEnvironmentTab.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/PHPEnvironmentTab.java @@ -49,406 +49,461 @@ import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; public class PHPEnvironmentTab extends AbstractLaunchConfigurationTab { - protected ListViewer loadPathListViewer; + protected ListViewer loadPathListViewer; - protected java.util.List installedInterpretersWorkingCopy; + protected java.util.List installedInterpretersWorkingCopy; - protected Combo interpreterCombo; + protected Combo interpreterCombo; - // protected Button loadPathDefaultButton; - protected Button fRemoteDebugCheckBox; - protected Button fRemoteDebugTranslate; + // protected Button loadPathDefaultButton; + protected Button fRemoteDebugCheckBox; - protected Button fOpenDBGSessionInBrowserCheckBox; + protected Button fRemoteDebugTranslate; - protected Button fPathMapRemoveButton; + protected Button fOpenDBGSessionInBrowserCheckBox; - protected Button fPathMapAddButton; + protected Button fPathMapRemoveButton; - protected Button fPathMapEditButton; + protected Button fPathMapAddButton; - protected Text fRemoteSourcePath; + protected Button fPathMapEditButton; - protected Table fRemoteDebugPathMapTable; + protected Text fRemoteSourcePath; - protected TabFolder tabFolder; + protected Table fRemoteDebugPathMapTable; - private class RemoteDebugTabListener extends SelectionAdapter implements ModifyListener { + protected TabFolder tabFolder; + + private class RemoteDebugTabListener extends SelectionAdapter implements + ModifyListener { + + /* + * (non-Javadoc) + * + * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent) + */ + public void modifyText(ModifyEvent e) { + updateLaunchConfigurationDialog(); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent) + */ + public void widgetSelected(SelectionEvent e) { + Object source = e.getSource(); + if (source == fRemoteDebugPathMapTable) { + setPathMapButtonsEnableState(); + } else if (source == fPathMapAddButton) { + handlePathMapAddButtonSelected(); + } else if (source == fPathMapEditButton) { + handlePathMapEditButtonSelected(); + } else if (source == fPathMapRemoveButton) { + handlePathMapRemoveButtonSelected(); + } else if (source == fRemoteDebugCheckBox) { + setRemoteTabEnableState(); + } else if (source == fRemoteDebugTranslate) { + setRemoteTabEnableState(); + } else { + updateLaunchConfigurationDialog(); + ; + } + + } - /* - * (non-Javadoc) - * - * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent) - */ - public void modifyText(ModifyEvent e) { - updateLaunchConfigurationDialog(); } - /* - * (non-Javadoc) - * - * @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent) - */ - public void widgetSelected(SelectionEvent e) { - Object source = e.getSource(); - if (source == fRemoteDebugPathMapTable) { + private static final String EMPTY_STRING = ""; //$NON-NLS-1$ + + private RemoteDebugTabListener fListener = new RemoteDebugTabListener(); + + private static final boolean DEFAULT_REMOTE_DEBUG = false; + + private static final boolean DEFAULT_REMOTE_DEBUG_TRANSLATE = false; + + private static final boolean DEFAULT_OPEN_DBGSESSION_IN_BROWSER = true; + + static String[] columnTitles = { + PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPEnvironment.remoteDebugTab.PathMapTableTitle.local"), + PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPEnvironment.remoteDebugTab.PathMapTableTitle.remote") }; + + public PHPEnvironmentTab() { + super(); + } + + public void createControl(Composite parent) { + Composite composite = createPageRoot(parent); + + tabFolder = new TabFolder(composite, SWT.NONE); + GridData gridData = new GridData(GridData.FILL_BOTH); + tabFolder.setLayoutData(gridData); + + // addLoadPathTab(tabFolder); + addInterpreterTab(tabFolder); + addRemoteDebugTab(tabFolder); + } + + protected void addRemoteDebugTab(TabFolder tabFolder) { + Label label; + + TabItem remoteDebugTab = new TabItem(tabFolder, SWT.NONE, 0); + remoteDebugTab + .setText(PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPEnvironment.remoteDebugTab.label")); + + Composite comp = new Composite(tabFolder, SWT.NONE); + comp.setLayout(new GridLayout()); + remoteDebugTab.setControl(comp); + GridData gd; + + fRemoteDebugCheckBox = new Button(comp, SWT.CHECK); + fRemoteDebugCheckBox + .setText(PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPEnvironment.remoteDebugTab.RemoteCheckBox.label")); + fRemoteDebugCheckBox.setLayoutData(new GridData( + GridData.HORIZONTAL_ALIGN_BEGINNING)); + fRemoteDebugCheckBox.addSelectionListener(fListener); + + fRemoteDebugTranslate = new Button(comp, SWT.CHECK); + fRemoteDebugTranslate + .setText(PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPEnvironment.remoteDebugTab.RemoteTranslate.label")); + fRemoteDebugTranslate.setLayoutData(new GridData( + GridData.HORIZONTAL_ALIGN_BEGINNING)); + fRemoteDebugTranslate.addSelectionListener(fListener); + + fOpenDBGSessionInBrowserCheckBox = new Button(comp, SWT.CHECK); + fOpenDBGSessionInBrowserCheckBox + .setText(PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPEnvironment.remoteDebugTab.OpenDBGSessionInBrowserCheckBox.label")); + fOpenDBGSessionInBrowserCheckBox.setLayoutData(new GridData( + GridData.HORIZONTAL_ALIGN_BEGINNING)); + fOpenDBGSessionInBrowserCheckBox.addSelectionListener(fListener); + + label = new Label(comp, SWT.NONE); + label + .setText(PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPEnvironment.remoteDebugTab.RemoteSourcePath.label")); + fRemoteSourcePath = new Text(comp, SWT.BORDER | SWT.SINGLE); + gd = new GridData(GridData.FILL_HORIZONTAL); + fRemoteSourcePath.setLayoutData(gd); + fRemoteSourcePath.addModifyListener(fListener); + + createVerticalSpacer(comp, 1); + + Composite pathMapComp = new Composite(comp, SWT.NONE); + gd = new GridData(GridData.FILL_BOTH); + pathMapComp.setLayoutData(gd); + GridLayout parametersLayout = new GridLayout(); + parametersLayout.numColumns = 2; + parametersLayout.marginHeight = 0; + parametersLayout.marginWidth = 0; + pathMapComp.setLayout(parametersLayout); + + Label pathMapLabel = new Label(pathMapComp, SWT.NONE); + pathMapLabel + .setText(PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPEnvironment.remoteDebugTab.PathMap.label")); + gd = new GridData(); + gd.horizontalSpan = 2; + pathMapLabel.setLayoutData(gd); + + fRemoteDebugPathMapTable = new Table(pathMapComp, SWT.BORDER + | SWT.MULTI); + TableLayout tableLayout = new TableLayout(); + fRemoteDebugPathMapTable.setLayout(tableLayout); + + gd = new GridData(GridData.FILL_BOTH); + fRemoteDebugPathMapTable.setLayoutData(gd); + TableColumn column1 = new TableColumn(this.fRemoteDebugPathMapTable, + SWT.NONE); + column1 + .setText(PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPEnvironment.remoteDebugTab.PathMap.Table.Title.local")); //$NON-NLS-1$ + TableColumn column2 = new TableColumn(this.fRemoteDebugPathMapTable, + SWT.NONE); + column2 + .setText(PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPEnvironment.remoteDebugTab.PathMap.Table.Title.remote")); //$NON-NLS-1$ + tableLayout.addColumnData(new ColumnWeightData(100)); + tableLayout.addColumnData(new ColumnWeightData(100)); + fRemoteDebugPathMapTable.setHeaderVisible(true); + fRemoteDebugPathMapTable.setLinesVisible(true); + fRemoteDebugPathMapTable.addSelectionListener(fListener); + fRemoteDebugPathMapTable.addMouseListener(new MouseAdapter() { + public void mouseDoubleClick(MouseEvent e) { + setPathMapButtonsEnableState(); + if (fPathMapEditButton.isEnabled()) { + handlePathMapEditButtonSelected(); + } + } + }); + // fRemoteDebugPathMapTable.setEnabled(false); + + Composite envButtonComp = new Composite(pathMapComp, SWT.NONE); + GridLayout envButtonLayout = new GridLayout(); + envButtonLayout.marginHeight = 0; + envButtonLayout.marginWidth = 0; + envButtonComp.setLayout(envButtonLayout); + gd = new GridData(GridData.VERTICAL_ALIGN_BEGINNING + | GridData.HORIZONTAL_ALIGN_FILL); + envButtonComp.setLayoutData(gd); + + fPathMapAddButton = createPushButton( + envButtonComp, + PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPEnvironment.remoteDebugTab.PathMap.Button.Add.label"), null); //$NON-NLS-1$ + fPathMapAddButton.addSelectionListener(fListener); + // fPathMapAddButton.setEnabled(false); + + fPathMapEditButton = createPushButton( + envButtonComp, + PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPEnvironment.remoteDebugTab.PathMap.Button.Edit.label"), null); //$NON-NLS-1$ + fPathMapEditButton.addSelectionListener(fListener); + // fPathMapEditButton.setEnabled(false); + + fPathMapRemoveButton = createPushButton( + envButtonComp, + PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPEnvironment.remoteDebugTab.PathMap.Button.Remove.label"), null); //$NON-NLS-1$ + fPathMapRemoveButton.addSelectionListener(fListener); + // fPathMapRemoveButton.setEnabled(false); + + } + + void handlePathMapAddButtonSelected() { + EditPathMapDialog dialog = new EditPathMapDialog(getShell(), + "Edit File Map", new String[] { EMPTY_STRING, EMPTY_STRING }); + openNewPathMapDialog(dialog, null); + // dialog.create(); + // if (dialog.open()==EditPathMapDialog.OK) + // { + // TableItem item = new TableItem (fRemoteDebugPathMapTable, SWT.NONE); + // item.setText(0,dialog.getLocalPath()); + // item.setText(1,dialog.getRemotePath()); + // updateLaunchConfigurationDialog(); + // } + // updateLaunchConfigurationDialog(); + setPathMapButtonsEnableState(); + } + + void handlePathMapRemoveButtonSelected() { + int[] selectedIndices = this.fRemoteDebugPathMapTable + .getSelectionIndices(); + this.fRemoteDebugPathMapTable.remove(selectedIndices); setPathMapButtonsEnableState(); - } else if (source == fPathMapAddButton) { - handlePathMapAddButtonSelected(); - } else if (source == fPathMapEditButton) { - handlePathMapEditButtonSelected(); - } else if (source == fPathMapRemoveButton) { - handlePathMapRemoveButtonSelected(); - } else if (source == fRemoteDebugCheckBox) { - setRemoteTabEnableState(); - } else if (source == fRemoteDebugTranslate) { - setRemoteTabEnableState(); - } else { updateLaunchConfigurationDialog(); - ; - } + } + void handlePathMapEditButtonSelected() { + TableItem selectedItem = this.fRemoteDebugPathMapTable.getSelection()[0]; + String local = selectedItem.getText(0); + String remote = selectedItem.getText(1); + EditPathMapDialog dialog = new EditPathMapDialog(getShell(), + "Edit File Map", new String[] { local, remote }); + openNewPathMapDialog(dialog, selectedItem); } - } - - private static final String EMPTY_STRING = ""; //$NON-NLS-1$ - - private RemoteDebugTabListener fListener = new RemoteDebugTabListener(); - - private static final boolean DEFAULT_REMOTE_DEBUG = false; - - private static final boolean DEFAULT_REMOTE_DEBUG_TRANSLATE = false; - - private static final boolean DEFAULT_OPEN_DBGSESSION_IN_BROWSER = true; - - static String[] columnTitles = { - PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPEnvironment.remoteDebugTab.PathMapTableTitle.local"), - PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPEnvironment.remoteDebugTab.PathMapTableTitle.remote") }; - - public PHPEnvironmentTab() { - super(); - } - - public void createControl(Composite parent) { - Composite composite = createPageRoot(parent); - - tabFolder = new TabFolder(composite, SWT.NONE); - GridData gridData = new GridData(GridData.FILL_BOTH); - tabFolder.setLayoutData(gridData); - - // addLoadPathTab(tabFolder); - addInterpreterTab(tabFolder); - addRemoteDebugTab(tabFolder); - } - - protected void addRemoteDebugTab(TabFolder tabFolder) { - Label label; - - TabItem remoteDebugTab = new TabItem(tabFolder, SWT.NONE, 0); - remoteDebugTab.setText(PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPEnvironment.remoteDebugTab.label")); - - Composite comp = new Composite(tabFolder, SWT.NONE); - comp.setLayout(new GridLayout()); - remoteDebugTab.setControl(comp); - GridData gd; - - fRemoteDebugCheckBox = new Button(comp, SWT.CHECK); - fRemoteDebugCheckBox.setText(PHPDebugUiMessages - .getString("LaunchConfigurationTab.PHPEnvironment.remoteDebugTab.RemoteCheckBox.label")); - fRemoteDebugCheckBox.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); - fRemoteDebugCheckBox.addSelectionListener(fListener); - - fRemoteDebugTranslate = new Button(comp, SWT.CHECK); - fRemoteDebugTranslate.setText(PHPDebugUiMessages - .getString("LaunchConfigurationTab.PHPEnvironment.remoteDebugTab.RemoteTranslate.label")); - fRemoteDebugTranslate.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); - fRemoteDebugTranslate.addSelectionListener(fListener); - - fOpenDBGSessionInBrowserCheckBox = new Button(comp, SWT.CHECK); - fOpenDBGSessionInBrowserCheckBox.setText(PHPDebugUiMessages - .getString("LaunchConfigurationTab.PHPEnvironment.remoteDebugTab.OpenDBGSessionInBrowserCheckBox.label")); - fOpenDBGSessionInBrowserCheckBox.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); - fOpenDBGSessionInBrowserCheckBox.addSelectionListener(fListener); - - label = new Label(comp, SWT.NONE); - label.setText(PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPEnvironment.remoteDebugTab.RemoteSourcePath.label")); - fRemoteSourcePath = new Text(comp, SWT.BORDER | SWT.SINGLE); - gd = new GridData(GridData.FILL_HORIZONTAL); - fRemoteSourcePath.setLayoutData(gd); - fRemoteSourcePath.addModifyListener(fListener); - - createVerticalSpacer(comp, 1); - - Composite pathMapComp = new Composite(comp, SWT.NONE); - gd = new GridData(GridData.FILL_BOTH); - pathMapComp.setLayoutData(gd); - GridLayout parametersLayout = new GridLayout(); - parametersLayout.numColumns = 2; - parametersLayout.marginHeight = 0; - parametersLayout.marginWidth = 0; - pathMapComp.setLayout(parametersLayout); - - Label pathMapLabel = new Label(pathMapComp, SWT.NONE); - pathMapLabel.setText(PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPEnvironment.remoteDebugTab.PathMap.label")); - gd = new GridData(); - gd.horizontalSpan = 2; - pathMapLabel.setLayoutData(gd); - - fRemoteDebugPathMapTable = new Table(pathMapComp, SWT.BORDER | SWT.MULTI); - TableLayout tableLayout = new TableLayout(); - fRemoteDebugPathMapTable.setLayout(tableLayout); - - gd = new GridData(GridData.FILL_BOTH); - fRemoteDebugPathMapTable.setLayoutData(gd); - TableColumn column1 = new TableColumn(this.fRemoteDebugPathMapTable, SWT.NONE); - column1.setText(PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPEnvironment.remoteDebugTab.PathMap.Table.Title.local")); //$NON-NLS-1$ - TableColumn column2 = new TableColumn(this.fRemoteDebugPathMapTable, SWT.NONE); - column2 - .setText(PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPEnvironment.remoteDebugTab.PathMap.Table.Title.remote")); //$NON-NLS-1$ - tableLayout.addColumnData(new ColumnWeightData(100)); - tableLayout.addColumnData(new ColumnWeightData(100)); - fRemoteDebugPathMapTable.setHeaderVisible(true); - fRemoteDebugPathMapTable.setLinesVisible(true); - fRemoteDebugPathMapTable.addSelectionListener(fListener); - fRemoteDebugPathMapTable.addMouseListener(new MouseAdapter() { - public void mouseDoubleClick(MouseEvent e) { - setPathMapButtonsEnableState(); - if (fPathMapEditButton.isEnabled()) { - handlePathMapEditButtonSelected(); + /** + * Set the enabled state of whole tab. + */ + private void setRemoteTabEnableState() { + boolean state = fRemoteDebugCheckBox.getSelection(); + fRemoteSourcePath.setEnabled(state); + fRemoteDebugTranslate.setEnabled(state); + + fRemoteDebugPathMapTable.setEnabled(state); + if (!state) { + fPathMapEditButton.setEnabled(false); + fPathMapRemoveButton.setEnabled(false); + fPathMapAddButton.setEnabled(false); + fOpenDBGSessionInBrowserCheckBox.setEnabled(false); + } else { + setPathMapButtonsEnableState(); } - } - }); - // fRemoteDebugPathMapTable.setEnabled(false); - - Composite envButtonComp = new Composite(pathMapComp, SWT.NONE); - GridLayout envButtonLayout = new GridLayout(); - envButtonLayout.marginHeight = 0; - envButtonLayout.marginWidth = 0; - envButtonComp.setLayout(envButtonLayout); - gd = new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.HORIZONTAL_ALIGN_FILL); - envButtonComp.setLayoutData(gd); - - fPathMapAddButton = createPushButton(envButtonComp, PHPDebugUiMessages - .getString("LaunchConfigurationTab.PHPEnvironment.remoteDebugTab.PathMap.Button.Add.label"), null); //$NON-NLS-1$ - fPathMapAddButton.addSelectionListener(fListener); - // fPathMapAddButton.setEnabled(false); - - fPathMapEditButton = createPushButton(envButtonComp, PHPDebugUiMessages - .getString("LaunchConfigurationTab.PHPEnvironment.remoteDebugTab.PathMap.Button.Edit.label"), null); //$NON-NLS-1$ - fPathMapEditButton.addSelectionListener(fListener); - // fPathMapEditButton.setEnabled(false); - - fPathMapRemoveButton = createPushButton(envButtonComp, PHPDebugUiMessages - .getString("LaunchConfigurationTab.PHPEnvironment.remoteDebugTab.PathMap.Button.Remove.label"), null); //$NON-NLS-1$ - fPathMapRemoveButton.addSelectionListener(fListener); - // fPathMapRemoveButton.setEnabled(false); - - } - - void handlePathMapAddButtonSelected() { - EditPathMapDialog dialog = new EditPathMapDialog(getShell(), "Edit File Map", new String[] { EMPTY_STRING, EMPTY_STRING }); - openNewPathMapDialog(dialog, null); - // dialog.create(); - // if (dialog.open()==EditPathMapDialog.OK) - // { - // TableItem item = new TableItem (fRemoteDebugPathMapTable, SWT.NONE); - // item.setText(0,dialog.getLocalPath()); - // item.setText(1,dialog.getRemotePath()); - // updateLaunchConfigurationDialog(); - // } - // updateLaunchConfigurationDialog(); - setPathMapButtonsEnableState(); - } - - void handlePathMapRemoveButtonSelected() { - int[] selectedIndices = this.fRemoteDebugPathMapTable.getSelectionIndices(); - this.fRemoteDebugPathMapTable.remove(selectedIndices); - setPathMapButtonsEnableState(); - updateLaunchConfigurationDialog(); - } - - void handlePathMapEditButtonSelected() { - TableItem selectedItem = this.fRemoteDebugPathMapTable.getSelection()[0]; - String local = selectedItem.getText(0); - String remote = selectedItem.getText(1); - EditPathMapDialog dialog = new EditPathMapDialog(getShell(), "Edit File Map", new String[] { local, remote }); - openNewPathMapDialog(dialog, selectedItem); - } - - /** - * Set the enabled state of whole tab. - */ - private void setRemoteTabEnableState() { - boolean state = fRemoteDebugCheckBox.getSelection(); - fRemoteSourcePath.setEnabled(state); - fRemoteDebugTranslate.setEnabled(state); - - fRemoteDebugPathMapTable.setEnabled(state); - if (!state) { - fPathMapEditButton.setEnabled(false); - fPathMapRemoveButton.setEnabled(false); - fPathMapAddButton.setEnabled(false); - fOpenDBGSessionInBrowserCheckBox.setEnabled(false); - } else { - setPathMapButtonsEnableState(); + + updateLaunchConfigurationDialog(); } - updateLaunchConfigurationDialog(); - } + /** + * Set the enabled state of the three environment variable-related buttons + * based on the selection in the PathMapTable widget. + */ + private void setPathMapButtonsEnableState() { + // just do nothing for now + // + if (fRemoteDebugCheckBox.getSelection()) { + fOpenDBGSessionInBrowserCheckBox.setEnabled(true); + fRemoteDebugTranslate.setEnabled(true); + int selectCount = this.fRemoteDebugPathMapTable + .getSelectionIndices().length; + if (selectCount < 1) { + fPathMapEditButton.setEnabled(false); + fPathMapRemoveButton.setEnabled(false); + } else { + fPathMapRemoveButton.setEnabled(true); + if (selectCount == 1) { + fPathMapEditButton.setEnabled(true); + } else { + fPathMapEditButton.setEnabled(false); + } + } + fPathMapAddButton.setEnabled(true); + } + } - /** - * Set the enabled state of the three environment variable-related buttons based on the selection in the PathMapTable widget. - */ - private void setPathMapButtonsEnableState() { - // just do nothing for now - // - if (fRemoteDebugCheckBox.getSelection()) { - fOpenDBGSessionInBrowserCheckBox.setEnabled(true); - fRemoteDebugTranslate.setEnabled(true); - int selectCount = this.fRemoteDebugPathMapTable.getSelectionIndices().length; - if (selectCount < 1) { - fPathMapEditButton.setEnabled(false); - fPathMapRemoveButton.setEnabled(false); - } else { - fPathMapRemoveButton.setEnabled(true); - if (selectCount == 1) { - fPathMapEditButton.setEnabled(true); - } else { - fPathMapEditButton.setEnabled(false); + /** + * Show the specified dialog and update the pathMapTable table based on its + * results. + * + * @param updateItem + * the item to update, or null if adding a new + * item + */ + private void openNewPathMapDialog(EditPathMapDialog dialog, + TableItem updateItem) { + if (dialog.open() != EditPathMapDialog.OK) { + return; + } + String[] pathPair = dialog.getPathPair(); + TableItem tableItem = updateItem; + if (tableItem == null) { + tableItem = getTableItemForName(pathPair[0]); + if (tableItem == null) { + tableItem = new TableItem(this.fRemoteDebugPathMapTable, + SWT.NONE); + } + } + tableItem.setText(pathPair); + this.fRemoteDebugPathMapTable + .setSelection(new TableItem[] { tableItem }); + updateLaunchConfigurationDialog(); + } + + /** + * Helper method that indicates whether the specified parameter name is + * already present in the parameters table. + */ + private TableItem getTableItemForName(String candidateName) { + TableItem[] items = this.fRemoteDebugPathMapTable.getItems(); + for (int i = 0; i < items.length; i++) { + String name = items[i].getText(0); + if (name.equals(candidateName)) { + return items[i]; + } } - } - fPathMapAddButton.setEnabled(true); + return null; + } + + // protected void addLoadPathTab(TabFolder tabFolder) { + // Composite loadPathComposite = new Composite(tabFolder, SWT.NONE); + // loadPathComposite.setLayout(new GridLayout()); + // + // loadPathListViewer = new ListViewer(loadPathComposite, SWT.BORDER | + // SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL); + // loadPathListViewer.setContentProvider(new ListContentProvider()); + // loadPathListViewer.setLabelProvider(new LoadPathEntryLabelProvider()); + // loadPathListViewer.getList().setLayoutData(new + // GridData(GridData.FILL_BOTH)); + // + // TabItem loadPathTab = new TabItem(tabFolder, SWT.NONE, 0); + // loadPathTab.setText(PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPEnvironment.loadPathTab.label")); + // loadPathTab.setControl(loadPathComposite); + // loadPathTab.setData(loadPathListViewer); + + // loadPathDefaultButton = new Button(loadPathComposite, SWT.CHECK); + // loadPathDefaultButton.setText(PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPEnvironment.loadPathDefaultButton.label")); + // loadPathDefaultButton.setLayoutData(new + // GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); + // loadPathDefaultButton.addSelectionListener(getLoadPathDefaultButtonSelectionListener()); + // + // loadPathDefaultButton.setEnabled(false); //for now, until the load path + // is customizable on the configuration + // } + + protected SelectionListener getLoadPathSelectionListener() { + return new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + System.out.println("Loadpath list selection occurred: " + + e.getSource()); + } + }; } - } - - /** - * Show the specified dialog and update the pathMapTable table based on its results. - * - * @param updateItem - * the item to update, or null if adding a new item - */ - private void openNewPathMapDialog(EditPathMapDialog dialog, TableItem updateItem) { - if (dialog.open() != EditPathMapDialog.OK) { - return; + + protected SelectionListener getLoadPathDefaultButtonSelectionListener() { + return new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + setUseLoadPathDefaults(((Button) e.getSource()).getSelection()); + } + }; } - String[] pathPair = dialog.getPathPair(); - TableItem tableItem = updateItem; - if (tableItem == null) { - tableItem = getTableItemForName(pathPair[0]); - if (tableItem == null) { - tableItem = new TableItem(this.fRemoteDebugPathMapTable, SWT.NONE); - } + + protected void addInterpreterTab(TabFolder tabFolder) { + Composite interpreterComposite = new Composite(tabFolder, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.numColumns = 2; + layout.marginHeight = 0; + layout.marginWidth = 0; + interpreterComposite.setLayout(layout); + interpreterComposite.setLayoutData(new GridData( + GridData.FILL_HORIZONTAL)); + + createVerticalSpacer(interpreterComposite, 2); + + interpreterCombo = new Combo(interpreterComposite, SWT.READ_ONLY); + interpreterCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + initializeInterpreterCombo(interpreterCombo); + interpreterCombo.addModifyListener(getInterpreterComboModifyListener()); + + Button interpreterAddButton = new Button(interpreterComposite, SWT.PUSH); + interpreterAddButton + .setText(PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPEnvironment.interpreterAddButton.label")); + interpreterAddButton.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent evt) { + PHPInterpreter newInterpreter = new PHPInterpreter(null); + File phpRuntime = PHPInterpreterPreferencePage.getFile( + getShell(), null); + if (phpRuntime != null) { + newInterpreter.setInstallLocation(phpRuntime); + PHPRuntime.getDefault().addInstalledInterpreter( + newInterpreter); + interpreterCombo.add(newInterpreter.getInstallLocation() + .toString()); + interpreterCombo.select(interpreterCombo + .indexOf(newInterpreter.getInstallLocation() + .toString())); + } + } + }); + + TabItem interpreterTab = new TabItem(tabFolder, SWT.NONE); + interpreterTab + .setText(PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPEnvironment.interpreterTab.label")); + interpreterTab.setControl(interpreterComposite); } - tableItem.setText(pathPair); - this.fRemoteDebugPathMapTable.setSelection(new TableItem[] { tableItem }); - updateLaunchConfigurationDialog(); - } - - /** - * Helper method that indicates whether the specified parameter name is already present in the parameters table. - */ - private TableItem getTableItemForName(String candidateName) { - TableItem[] items = this.fRemoteDebugPathMapTable.getItems(); - for (int i = 0; i < items.length; i++) { - String name = items[i].getText(0); - if (name.equals(candidateName)) { - return items[i]; - } + + protected ModifyListener getInterpreterComboModifyListener() { + return new ModifyListener() { + public void modifyText(ModifyEvent evt) { + updateLaunchConfigurationDialog(); + } + }; } - return null; - } - - // protected void addLoadPathTab(TabFolder tabFolder) { - // Composite loadPathComposite = new Composite(tabFolder, SWT.NONE); - // loadPathComposite.setLayout(new GridLayout()); - // - // loadPathListViewer = new ListViewer(loadPathComposite, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL); - // loadPathListViewer.setContentProvider(new ListContentProvider()); - // loadPathListViewer.setLabelProvider(new LoadPathEntryLabelProvider()); - // loadPathListViewer.getList().setLayoutData(new GridData(GridData.FILL_BOTH)); - // - // TabItem loadPathTab = new TabItem(tabFolder, SWT.NONE, 0); - // loadPathTab.setText(PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPEnvironment.loadPathTab.label")); - // loadPathTab.setControl(loadPathComposite); - // loadPathTab.setData(loadPathListViewer); - - // loadPathDefaultButton = new Button(loadPathComposite, SWT.CHECK); - // loadPathDefaultButton.setText(PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPEnvironment.loadPathDefaultButton.label")); - // loadPathDefaultButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); - // loadPathDefaultButton.addSelectionListener(getLoadPathDefaultButtonSelectionListener()); - // - // loadPathDefaultButton.setEnabled(false); //for now, until the load path is customizable on the configuration - // } - - protected SelectionListener getLoadPathSelectionListener() { - return new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - System.out.println("Loadpath list selection occurred: " + e.getSource()); - } - }; - } - - protected SelectionListener getLoadPathDefaultButtonSelectionListener() { - return new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - setUseLoadPathDefaults(((Button) e.getSource()).getSelection()); - } - }; - } - - protected void addInterpreterTab(TabFolder tabFolder) { - Composite interpreterComposite = new Composite(tabFolder, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.numColumns = 2; - layout.marginHeight = 0; - layout.marginWidth = 0; - interpreterComposite.setLayout(layout); - interpreterComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - - createVerticalSpacer(interpreterComposite, 2); - - interpreterCombo = new Combo(interpreterComposite, SWT.READ_ONLY); - interpreterCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - initializeInterpreterCombo(interpreterCombo); - interpreterCombo.addModifyListener(getInterpreterComboModifyListener()); - - Button interpreterAddButton = new Button(interpreterComposite, SWT.PUSH); - interpreterAddButton.setText(PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPEnvironment.interpreterAddButton.label")); - interpreterAddButton.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent evt) { - PHPInterpreter newInterpreter = new PHPInterpreter(null); - File phpRuntime = PHPInterpreterPreferencePage.getFile(getShell(), null); - if (phpRuntime != null) { - newInterpreter.setInstallLocation(phpRuntime); - PHPRuntime.getDefault().addInstalledInterpreter(newInterpreter); - interpreterCombo.add(newInterpreter.getInstallLocation().toString()); - interpreterCombo.select(interpreterCombo.indexOf(newInterpreter.getInstallLocation().toString())); - } - } - }); - TabItem interpreterTab = new TabItem(tabFolder, SWT.NONE); - interpreterTab.setText(PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPEnvironment.interpreterTab.label")); - interpreterTab.setControl(interpreterComposite); - } + protected void createVerticalSpacer(Composite comp, int colSpan) { + Label label = new Label(comp, SWT.NONE); + GridData gd = new GridData(); + gd.horizontalSpan = colSpan; + label.setLayoutData(gd); + } - protected ModifyListener getInterpreterComboModifyListener() { - return new ModifyListener() { - public void modifyText(ModifyEvent evt) { - updateLaunchConfigurationDialog(); - } - }; - } - - protected void createVerticalSpacer(Composite comp, int colSpan) { - Label label = new Label(comp, SWT.NONE); - GridData gd = new GridData(); - gd.horizontalSpan = colSpan; - label.setLayoutData(gd); - } - - public void setDefaults(ILaunchConfigurationWorkingCopy configuration) { + public void setDefaults(ILaunchConfigurationWorkingCopy configuration) { PHPInterpreter selectedInterpreter = PHPRuntime.getDefault() .getSelectedInterpreter(); if (selectedInterpreter != null) { @@ -459,17 +514,23 @@ public class PHPEnvironmentTab extends AbstractLaunchConfigurationTab { interpreterLocation); } try { - String projectName = configuration.getAttribute(PHPLaunchConfigurationAttribute.PROJECT_NAME,""); - if (projectName!="") { - IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName); - if (project!=null) { + String projectName = configuration.getAttribute( + PHPLaunchConfigurationAttribute.PROJECT_NAME, ""); + if (projectName != "") { + IProject project = ResourcesPlugin.getWorkspace().getRoot() + .getProject(projectName); + if (project != null) { IPath remotePath = project.getLocation(); - String fileName=configuration.getAttribute(PHPLaunchConfigurationAttribute.FILE_NAME,""); - if (fileName!="") { + String fileName = configuration.getAttribute( + PHPLaunchConfigurationAttribute.FILE_NAME, ""); + if (fileName != "") { Path filePath = new Path(fileName); - remotePath=remotePath.append(filePath.removeLastSegments(1)); + remotePath = remotePath.append(filePath + .removeLastSegments(1)); } - configuration.setAttribute(PHPLaunchConfigurationAttribute.REMOTE_PATH, remotePath.toOSString()); + configuration.setAttribute( + PHPLaunchConfigurationAttribute.REMOTE_PATH, + remotePath.toOSString()); } } } catch (CoreException e) { @@ -478,200 +539,237 @@ public class PHPEnvironmentTab extends AbstractLaunchConfigurationTab { } } - public void initializeFrom(ILaunchConfiguration configuration) { - // initializeLoadPath(configuration); - initializeInterpreterSelection(configuration); - initializeRemoteDebug(configuration); - } - - protected void initializeRemoteDebug(ILaunchConfiguration configuration) { - try { - fRemoteDebugCheckBox.setSelection(configuration.getAttribute(PHPLaunchConfigurationAttribute.REMOTE_DEBUG, - DEFAULT_REMOTE_DEBUG)); - } catch (CoreException ce) { - fRemoteDebugCheckBox.setSelection(DEFAULT_REMOTE_DEBUG); - } - try { - fRemoteDebugTranslate.setSelection(configuration.getAttribute( - PHPLaunchConfigurationAttribute.REMOTE_DEBUG_TRANSLATE, DEFAULT_REMOTE_DEBUG_TRANSLATE)); - } catch (CoreException ce) { - fRemoteDebugTranslate.setSelection(DEFAULT_REMOTE_DEBUG_TRANSLATE); - } - try { - fOpenDBGSessionInBrowserCheckBox.setSelection(configuration.getAttribute( - PHPLaunchConfigurationAttribute.OPEN_DBGSESSION_IN_BROWSER, DEFAULT_OPEN_DBGSESSION_IN_BROWSER)); - } catch (CoreException ce) { - fOpenDBGSessionInBrowserCheckBox.setSelection(DEFAULT_OPEN_DBGSESSION_IN_BROWSER); - } - setRemoteTabEnableState(); - try { - fRemoteSourcePath.setText(configuration.getAttribute(PHPLaunchConfigurationAttribute.REMOTE_PATH, "")); - } catch (CoreException ce) { - fRemoteSourcePath.setText(""); + public void initializeFrom(ILaunchConfiguration configuration) { + // initializeLoadPath(configuration); + initializeInterpreterSelection(configuration); + initializeRemoteDebug(configuration); } - updatePathMapFromConfig(configuration); + protected void initializeRemoteDebug(ILaunchConfiguration configuration) { + try { + fRemoteDebugCheckBox.setSelection(configuration.getAttribute( + PHPLaunchConfigurationAttribute.REMOTE_DEBUG, + DEFAULT_REMOTE_DEBUG)); + } catch (CoreException ce) { + fRemoteDebugCheckBox.setSelection(DEFAULT_REMOTE_DEBUG); + } + try { + fRemoteDebugTranslate.setSelection(configuration.getAttribute( + PHPLaunchConfigurationAttribute.REMOTE_DEBUG_TRANSLATE, + DEFAULT_REMOTE_DEBUG_TRANSLATE)); + } catch (CoreException ce) { + fRemoteDebugTranslate.setSelection(DEFAULT_REMOTE_DEBUG_TRANSLATE); + } + try { + fOpenDBGSessionInBrowserCheckBox + .setSelection(configuration + .getAttribute( + PHPLaunchConfigurationAttribute.OPEN_DBGSESSION_IN_BROWSER, + DEFAULT_OPEN_DBGSESSION_IN_BROWSER)); + } catch (CoreException ce) { + fOpenDBGSessionInBrowserCheckBox + .setSelection(DEFAULT_OPEN_DBGSESSION_IN_BROWSER); + } + setRemoteTabEnableState(); + try { + fRemoteSourcePath.setText(configuration.getAttribute( + PHPLaunchConfigurationAttribute.REMOTE_PATH, "")); + } catch (CoreException ce) { + fRemoteSourcePath.setText(""); + } - } + updatePathMapFromConfig(configuration); + + } + + private void updatePathMapFromConfig(ILaunchConfiguration config) { + Map envVars = null; + try { + if (config != null) { + envVars = config.getAttribute( + PHPLaunchConfigurationAttribute.FILE_MAP, (Map) null); + } + updatePathMapTable(envVars, this.fRemoteDebugPathMapTable); + setPathMapButtonsEnableState(); + } catch (CoreException ce) { + log(ce); + } + } - private void updatePathMapFromConfig(ILaunchConfiguration config) { - Map envVars = null; - try { - if (config != null) { - envVars = config.getAttribute(PHPLaunchConfigurationAttribute.FILE_MAP, (Map) null); - } - updatePathMapTable(envVars, this.fRemoteDebugPathMapTable); - setPathMapButtonsEnableState(); - } catch (CoreException ce) { - log(ce); + private void updatePathMapTable(Map map, Table tableWidget) { + tableWidget.removeAll(); + if (map == null) { + return; + } + Iterator iterator = map.keySet().iterator(); + while (iterator.hasNext()) { + String key = (String) iterator.next(); + String value = (String) map.get(key); + TableItem tableItem = new TableItem(tableWidget, SWT.NONE); + tableItem.setText(new String[] { key, value }); + } } - } - private void updatePathMapTable(Map map, Table tableWidget) { - tableWidget.removeAll(); - if (map == null) { - return; + // protected void initializeLoadPath(ILaunchConfiguration configuration) { + // boolean useDefaultLoadPath = true; + // try { + // useDefaultLoadPath = + // configuration.getAttribute(PHPLaunchConfigurationAttribute.USE_DEFAULT_LOAD_PATH, + // true); + // setUseLoadPathDefaults(useDefaultLoadPath); + // if (useDefaultLoadPath) { + // String projectName = + // configuration.getAttribute(PHPLaunchConfigurationAttribute.PROJECT_NAME, + // ""); + // if (projectName != "") { + // IProject aProject = + // PHPeclipsePlugin.getWorkspace().getRoot().getProject(projectName); + // if ((aProject != null) && JavaCore.isPHPProject(aProject)) { + // JavaProject thePHPProject = new JavaProject(); + // thePHPProject.setProject(aProject); + // List loadPathEntries = thePHPProject.getLoadPathEntries(); + // loadPathListViewer.setInput(loadPathEntries); + // } + // } + // } + // } catch (CoreException e) { + // log(e); + // } + // } + + protected void setUseLoadPathDefaults(boolean useDefaults) { + loadPathListViewer.getList().setEnabled(!useDefaults); + // loadPathDefaultButton.setSelection(useDefaults); } - Iterator iterator = map.keySet().iterator(); - while (iterator.hasNext()) { - String key = (String) iterator.next(); - String value = (String) map.get(key); - TableItem tableItem = new TableItem(tableWidget, SWT.NONE); - tableItem.setText(new String[] { key, value }); + + protected void initializeInterpreterSelection( + ILaunchConfiguration configuration) { + String interpreterName = null; + try { + interpreterName = configuration.getAttribute( + PHPLaunchConfigurationAttribute.SELECTED_INTERPRETER, ""); + } catch (CoreException e) { + log(e); + } + if (interpreterName != null && !interpreterName.equals("")) + interpreterCombo.select(interpreterCombo.indexOf(interpreterName)); } - } - - // protected void initializeLoadPath(ILaunchConfiguration configuration) { - // boolean useDefaultLoadPath = true; - // try { - // useDefaultLoadPath = configuration.getAttribute(PHPLaunchConfigurationAttribute.USE_DEFAULT_LOAD_PATH, true); - // setUseLoadPathDefaults(useDefaultLoadPath); - // if (useDefaultLoadPath) { - // String projectName = configuration.getAttribute(PHPLaunchConfigurationAttribute.PROJECT_NAME, ""); - // if (projectName != "") { - // IProject aProject = PHPeclipsePlugin.getWorkspace().getRoot().getProject(projectName); - // if ((aProject != null) && JavaCore.isPHPProject(aProject)) { - // JavaProject thePHPProject = new JavaProject(); - // thePHPProject.setProject(aProject); - // List loadPathEntries = thePHPProject.getLoadPathEntries(); - // loadPathListViewer.setInput(loadPathEntries); - // } - // } - // } - // } catch (CoreException e) { - // log(e); - // } - // } - - protected void setUseLoadPathDefaults(boolean useDefaults) { - loadPathListViewer.getList().setEnabled(!useDefaults); - // loadPathDefaultButton.setSelection(useDefaults); - } - - protected void initializeInterpreterSelection(ILaunchConfiguration configuration) { - String interpreterName = null; - try { - interpreterName = configuration.getAttribute(PHPLaunchConfigurationAttribute.SELECTED_INTERPRETER, ""); - } catch (CoreException e) { - log(e); + + protected void initializeInterpreterCombo(Combo interpreterCombo) { + installedInterpretersWorkingCopy = new ArrayList(); + installedInterpretersWorkingCopy.addAll(PHPRuntime.getDefault() + .getInstalledInterpreters()); + + String[] interpreterNames = new String[installedInterpretersWorkingCopy + .size()]; + for (int interpreterIndex = 0; interpreterIndex < installedInterpretersWorkingCopy + .size(); interpreterIndex++) { + PHPInterpreter interpreter = (PHPInterpreter) installedInterpretersWorkingCopy + .get(interpreterIndex); + interpreterNames[interpreterIndex] = interpreter + .getInstallLocation().toString(); + } + interpreterCombo.setItems(interpreterNames); + + PHPInterpreter selectedInterpreter = PHPRuntime.getDefault() + .getSelectedInterpreter(); + if (selectedInterpreter != null) + interpreterCombo.select(interpreterCombo + .indexOf(selectedInterpreter.getInstallLocation() + .toString())); } - if (interpreterName != null && !interpreterName.equals("")) - interpreterCombo.select(interpreterCombo.indexOf(interpreterName)); - } - - protected void initializeInterpreterCombo(Combo interpreterCombo) { - installedInterpretersWorkingCopy = new ArrayList(); - installedInterpretersWorkingCopy.addAll(PHPRuntime.getDefault().getInstalledInterpreters()); - - String[] interpreterNames = new String[installedInterpretersWorkingCopy.size()]; - for (int interpreterIndex = 0; interpreterIndex < installedInterpretersWorkingCopy.size(); interpreterIndex++) { - PHPInterpreter interpreter = (PHPInterpreter) installedInterpretersWorkingCopy.get(interpreterIndex); - interpreterNames[interpreterIndex] = interpreter.getInstallLocation().toString(); + + public void performApply(ILaunchConfigurationWorkingCopy configuration) { + int selectionIndex = interpreterCombo.getSelectionIndex(); + if (selectionIndex >= 0) + configuration.setAttribute( + PHPLaunchConfigurationAttribute.SELECTED_INTERPRETER, + interpreterCombo.getItem(selectionIndex)); + + // configuration.setAttribute(PHPLaunchConfigurationAttribute.USE_DEFAULT_LOAD_PATH, + // loadPathDefaultButton.getSelection()); + + // if (!loadPathDefaultButton.getSelection()) { + // List loadPathEntries = (List) loadPathListViewer.getInput(); + // List loadPathStrings = new ArrayList(); + // for (Iterator iterator = loadPathEntries.iterator(); + // iterator.hasNext();) { + // LoadPathEntry entry = (LoadPathEntry) iterator.next(); + // loadPathStrings.add(entry.getPath().toString()); + // } + // configuration.setAttribute(PHPLaunchConfigurationAttribute.CUSTOM_LOAD_PATH, + // loadPathStrings); + // } + + configuration.setAttribute( + PHPLaunchConfigurationAttribute.REMOTE_DEBUG, + fRemoteDebugCheckBox.getSelection()); + configuration.setAttribute( + PHPLaunchConfigurationAttribute.REMOTE_DEBUG_TRANSLATE, + fRemoteDebugTranslate.getSelection()); + configuration.setAttribute(PHPLaunchConfigurationAttribute.FILE_MAP, + getMapFromPathMapTable()); + configuration.setAttribute(PHPLaunchConfigurationAttribute.REMOTE_PATH, + fRemoteSourcePath.getText()); + configuration.setAttribute( + PHPLaunchConfigurationAttribute.OPEN_DBGSESSION_IN_BROWSER, + fOpenDBGSessionInBrowserCheckBox.getSelection()); } - interpreterCombo.setItems(interpreterNames); - - PHPInterpreter selectedInterpreter = PHPRuntime.getDefault().getSelectedInterpreter(); - if (selectedInterpreter != null) - interpreterCombo.select(interpreterCombo.indexOf(selectedInterpreter.getInstallLocation().toString())); - } - - public void performApply(ILaunchConfigurationWorkingCopy configuration) { - int selectionIndex = interpreterCombo.getSelectionIndex(); - if (selectionIndex >= 0) - configuration.setAttribute(PHPLaunchConfigurationAttribute.SELECTED_INTERPRETER, interpreterCombo.getItem(selectionIndex)); - - // configuration.setAttribute(PHPLaunchConfigurationAttribute.USE_DEFAULT_LOAD_PATH, loadPathDefaultButton.getSelection()); - - // if (!loadPathDefaultButton.getSelection()) { - // List loadPathEntries = (List) loadPathListViewer.getInput(); - // List loadPathStrings = new ArrayList(); - // for (Iterator iterator = loadPathEntries.iterator(); iterator.hasNext();) { - // LoadPathEntry entry = (LoadPathEntry) iterator.next(); - // loadPathStrings.add(entry.getPath().toString()); - // } - // configuration.setAttribute(PHPLaunchConfigurationAttribute.CUSTOM_LOAD_PATH, loadPathStrings); - // } - - configuration.setAttribute(PHPLaunchConfigurationAttribute.REMOTE_DEBUG, fRemoteDebugCheckBox.getSelection()); - configuration.setAttribute(PHPLaunchConfigurationAttribute.REMOTE_DEBUG_TRANSLATE, fRemoteDebugTranslate.getSelection()); - configuration.setAttribute(PHPLaunchConfigurationAttribute.FILE_MAP, getMapFromPathMapTable()); - configuration.setAttribute(PHPLaunchConfigurationAttribute.REMOTE_PATH, fRemoteSourcePath.getText()); - configuration.setAttribute(PHPLaunchConfigurationAttribute.OPEN_DBGSESSION_IN_BROWSER, fOpenDBGSessionInBrowserCheckBox - .getSelection()); - } - - protected Composite createPageRoot(Composite parent) { - Composite composite = new Composite(parent, SWT.NULL); - GridLayout layout = new GridLayout(); - layout.numColumns = 2; - composite.setLayout(layout); - createVerticalSpacer(composite, 2); - setControl(composite); - - return composite; - } - - private Map getMapFromPathMapTable() { - TableItem[] items = fRemoteDebugPathMapTable.getItems(); - if (items.length == 0) { - return null; + + protected Composite createPageRoot(Composite parent) { + Composite composite = new Composite(parent, SWT.NULL); + GridLayout layout = new GridLayout(); + layout.numColumns = 2; + composite.setLayout(layout); + createVerticalSpacer(composite, 2); + setControl(composite); + + return composite; } - Map map = new HashMap(items.length); - for (int i = 0; i < items.length; i++) { - TableItem item = items[i]; - String key = item.getText(0); - String value = item.getText(1); - map.put(key, value); + + private Map getMapFromPathMapTable() { + TableItem[] items = fRemoteDebugPathMapTable.getItems(); + if (items.length == 0) { + return null; + } + Map map = new HashMap(items.length); + for (int i = 0; i < items.length; i++) { + TableItem item = items[i]; + String key = item.getText(0); + String value = item.getText(1); + map.put(key, value); + } + return map; } - return map; - } - - public String getName() { - return PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPEnvironment.name"); - } - - public boolean isValid(ILaunchConfiguration launchConfig) { - try { - String selectedInterpreter = launchConfig.getAttribute(PHPLaunchConfigurationAttribute.SELECTED_INTERPRETER, ""); - if (selectedInterpreter.length() == 0) { - setErrorMessage(PHPDebugUiMessages - .getString("LaunchConfigurationTab.PHPEnvironment.interpreter_not_selected_error_message")); - return false; - } - } catch (CoreException e) { - log(e); + + public String getName() { + return PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPEnvironment.name"); } - setErrorMessage(null); - return true; - } + public boolean isValid(ILaunchConfiguration launchConfig) { + try { + String selectedInterpreter = launchConfig.getAttribute( + PHPLaunchConfigurationAttribute.SELECTED_INTERPRETER, ""); + if (selectedInterpreter.length() == 0) { + setErrorMessage(PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPEnvironment.interpreter_not_selected_error_message")); + return false; + } + } catch (CoreException e) { + log(e); + } + + setErrorMessage(null); + return true; + } - protected void log(Throwable t) { - PHPDebugUiPlugin.log(t); - } + protected void log(Throwable t) { + PHPDebugUiPlugin.log(t); + } - public Image getImage() { - return PHPUiImages.get(PHPUiImages.IMG_CTOOLS_PHP); - } + public Image getImage() { + return PHPUiImages.get(PHPUiImages.IMG_CTOOLS_PHP); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/PHPEnvironmentTab2.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/PHPEnvironmentTab2.java index 390d7c1..288910f 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/PHPEnvironmentTab2.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/PHPEnvironmentTab2.java @@ -69,53 +69,62 @@ import org.eclipse.ui.dialogs.ListSelectionDialog; /** * @author Christian - * - * TODO To change the template for this generated type comment go to - * Window - Preferences - Java - Code Style - Code Templates + * + * TODO To change the template for this generated type comment go to Window - + * Preferences - Java - Code Style - Code Templates */ public class PHPEnvironmentTab2 extends AbstractLaunchConfigurationTab { - protected TableViewer environmentTable; - protected String[] envTableColumnHeaders = - { - LaunchConfigurationsMessages.EnvironmentTab_Variable_1, //$NON-NLS-1$ - LaunchConfigurationsMessages.EnvironmentTab_Value_2 //$NON-NLS-1$ - }; - protected ColumnLayoutData[] envTableColumnLayouts = - { - new ColumnWeightData(50), - new ColumnWeightData(50) + + protected String[] envTableColumnHeaders = { + LaunchConfigurationsMessages.EnvironmentTab_Variable_1, //$NON-NLS-1$ + LaunchConfigurationsMessages.EnvironmentTab_Value_2 //$NON-NLS-1$ }; - private static final String NAME_LABEL= LaunchConfigurationsMessages.EnvironmentTab_8; //$NON-NLS-1$ - private static final String VALUE_LABEL= LaunchConfigurationsMessages.EnvironmentTab_9; //$NON-NLS-1$ + + protected ColumnLayoutData[] envTableColumnLayouts = { + new ColumnWeightData(50), new ColumnWeightData(50) }; + + private static final String NAME_LABEL = LaunchConfigurationsMessages.EnvironmentTab_8; //$NON-NLS-1$ + + private static final String VALUE_LABEL = LaunchConfigurationsMessages.EnvironmentTab_9; //$NON-NLS-1$ + protected static final String P_VARIABLE = "variable"; //$NON-NLS-1$ + protected static final String P_VALUE = "value"; //$NON-NLS-1$ - protected static String[] envTableColumnProperties = - { - P_VARIABLE, - P_VALUE - }; + + protected static String[] envTableColumnProperties = { P_VARIABLE, P_VALUE }; + protected Button envAddButton; + protected Button envAddCGIButton; + protected Button envEditButton; + protected Button envRemoveButton; + protected Button appendEnvironment; + protected Button replaceEnvironment; + protected Button envSelectButton; /** * Content provider for the environment table */ - protected class EnvironmentVariableContentProvider implements IStructuredContentProvider { + protected class EnvironmentVariableContentProvider implements + IStructuredContentProvider { public Object[] getElements(Object inputElement) { EnvironmentVariable[] elements = new EnvironmentVariable[0]; ILaunchConfiguration config = (ILaunchConfiguration) inputElement; Map m; try { - m = config.getAttribute(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES, (Map) null); + m = config.getAttribute( + ILaunchManager.ATTR_ENVIRONMENT_VARIABLES, (Map) null); } catch (CoreException e) { - DebugUIPlugin.log(new Status(IStatus.ERROR, DebugUIPlugin.getUniqueIdentifier(), IStatus.ERROR, "Error reading configuration", e)); //$NON-NLS-1$ + DebugUIPlugin.log(new Status(IStatus.ERROR, DebugUIPlugin + .getUniqueIdentifier(), IStatus.ERROR, + "Error reading configuration", e)); //$NON-NLS-1$ return elements; } if (m != null && !m.isEmpty()) { @@ -123,19 +132,22 @@ public class PHPEnvironmentTab2 extends AbstractLaunchConfigurationTab { String[] varNames = new String[m.size()]; m.keySet().toArray(varNames); for (int i = 0; i < m.size(); i++) { - elements[i] = new EnvironmentVariable(varNames[i], (String) m.get(varNames[i])); + elements[i] = new EnvironmentVariable(varNames[i], + (String) m.get(varNames[i])); } } return elements; } + public void dispose() { } + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - if (newInput == null){ + if (newInput == null) { return; } - if (viewer instanceof TableViewer){ - TableViewer tableViewer= (TableViewer) viewer; + if (viewer instanceof TableViewer) { + TableViewer tableViewer = (TableViewer) viewer; if (tableViewer.getTable().isDisposed()) { return; } @@ -146,7 +158,10 @@ public class PHPEnvironmentTab2 extends AbstractLaunchConfigurationTab { } else if (e2 == null) { return 1; } else { - return ((EnvironmentVariable)e1).getName().compareToIgnoreCase(((EnvironmentVariable)e2).getName()); + return ((EnvironmentVariable) e1).getName() + .compareToIgnoreCase( + ((EnvironmentVariable) e2) + .getName()); } } }); @@ -157,35 +172,44 @@ public class PHPEnvironmentTab2 extends AbstractLaunchConfigurationTab { /** * Label provider for the environment table */ - public class EnvironmentVariableLabelProvider extends LabelProvider implements ITableLabelProvider { - public String getColumnText(Object element, int columnIndex) { + public class EnvironmentVariableLabelProvider extends LabelProvider + implements ITableLabelProvider { + public String getColumnText(Object element, int columnIndex) { String result = null; if (element != null) { EnvironmentVariable var = (EnvironmentVariable) element; switch (columnIndex) { - case 0: // variable - result = var.getName(); - break; - case 1: // value - result = var.getValue(); - break; + case 0: // variable + result = var.getName(); + break; + case 1: // value + result = var.getValue(); + break; } } return result; } + public Image getColumnImage(Object element, int columnIndex) { return null; } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.debug.ui.ILaunchConfigurationTab#createControl(org.eclipse.swt.widgets.Composite) */ public void createControl(Composite parent) { // Create main composite Composite mainComposite = new Composite(parent, SWT.NONE); setControl(mainComposite); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IDebugHelpContextIds.LAUNCH_CONFIGURATION_DIALOG_ENVIRONMENT_TAB); + PlatformUI + .getWorkbench() + .getHelpSystem() + .setHelp( + getControl(), + IDebugHelpContextIds.LAUNCH_CONFIGURATION_DIALOG_ENVIRONMENT_TAB); GridLayout layout = new GridLayout(); layout.numColumns = 2; GridData gridData = new GridData(GridData.FILL_HORIZONTAL); @@ -201,46 +225,52 @@ public class PHPEnvironmentTab2 extends AbstractLaunchConfigurationTab { } /** - * Creates and configures the widgets which allow the user to - * choose whether the specified environment should be appended - * to the native environment or if it should completely replace it. - * @param parent the composite in which the widgets should be created + * Creates and configures the widgets which allow the user to choose whether + * the specified environment should be appended to the native environment or + * if it should completely replace it. + * + * @param parent + * the composite in which the widgets should be created */ protected void createAppendReplace(Composite parent) { - Composite appendReplaceComposite= new Composite(parent, SWT.NONE); - GridData gridData= new GridData(); - gridData.horizontalSpan= 2; - GridLayout layout= new GridLayout(); + Composite appendReplaceComposite = new Composite(parent, SWT.NONE); + GridData gridData = new GridData(); + gridData.horizontalSpan = 2; + GridLayout layout = new GridLayout(); appendReplaceComposite.setLayoutData(gridData); appendReplaceComposite.setLayout(layout); appendReplaceComposite.setFont(parent.getFont()); - appendEnvironment= createRadioButton(appendReplaceComposite, LaunchConfigurationsMessages.EnvironmentTab_16); //$NON-NLS-1$ + appendEnvironment = createRadioButton(appendReplaceComposite, + LaunchConfigurationsMessages.EnvironmentTab_16); //$NON-NLS-1$ appendEnvironment.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { updateLaunchConfigurationDialog(); } }); - replaceEnvironment= createRadioButton(appendReplaceComposite, LaunchConfigurationsMessages.EnvironmentTab_17); //$NON-NLS-1$ + replaceEnvironment = createRadioButton(appendReplaceComposite, + LaunchConfigurationsMessages.EnvironmentTab_17); //$NON-NLS-1$ } /** - * Updates the enablement of the append/replace widgets. The - * widgets should disable when there are no environment variables specified. + * Updates the enablement of the append/replace widgets. The widgets should + * disable when there are no environment variables specified. */ protected void updateAppendReplace() { - boolean enable= environmentTable.getTable().getItemCount() > 0; + boolean enable = environmentTable.getTable().getItemCount() > 0; appendEnvironment.setEnabled(enable); replaceEnvironment.setEnabled(enable); } /** - * Creates and configures the table that displayed the key/value - * pairs that comprise the environment. - * @param parent the composite in which the table should be created + * Creates and configures the table that displayed the key/value pairs that + * comprise the environment. + * + * @param parent + * the composite in which the table should be created */ protected void createEnvironmentTable(Composite parent) { - Font font= parent.getFont(); + Font font = parent.getFont(); // Create table composite Composite tableComposite = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); @@ -255,9 +285,11 @@ public class PHPEnvironmentTab2 extends AbstractLaunchConfigurationTab { // Create label Label label = new Label(tableComposite, SWT.NONE); label.setFont(font); - label.setText(LaunchConfigurationsMessages.EnvironmentTab_Environment_variables_to_set__3); //$NON-NLS-1$ + label + .setText(LaunchConfigurationsMessages.EnvironmentTab_Environment_variables_to_set__3); //$NON-NLS-1$ // Create table - environmentTable = new TableViewer(tableComposite, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.FULL_SELECTION); + environmentTable = new TableViewer(tableComposite, SWT.BORDER + | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.FULL_SELECTION); Table table = environmentTable.getTable(); TableLayout tableLayout = new TableLayout(); table.setLayout(tableLayout); @@ -265,14 +297,17 @@ public class PHPEnvironmentTab2 extends AbstractLaunchConfigurationTab { table.setFont(font); gridData = new GridData(GridData.FILL_BOTH); environmentTable.getControl().setLayoutData(gridData); - environmentTable.setContentProvider(new EnvironmentVariableContentProvider()); - environmentTable.setLabelProvider(new EnvironmentVariableLabelProvider()); + environmentTable + .setContentProvider(new EnvironmentVariableContentProvider()); + environmentTable + .setLabelProvider(new EnvironmentVariableLabelProvider()); environmentTable.setColumnProperties(envTableColumnProperties); - environmentTable.addSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - handleTableSelectionChanged(event); - } - }); + environmentTable + .addSelectionChangedListener(new ISelectionChangedListener() { + public void selectionChanged(SelectionChangedEvent event) { + handleTableSelectionChanged(event); + } + }); environmentTable.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { if (!environmentTable.getSelection().isEmpty()) { @@ -291,17 +326,21 @@ public class PHPEnvironmentTab2 extends AbstractLaunchConfigurationTab { /** * Responds to a selection changed event in the environment table - * @param event the selection change event + * + * @param event + * the selection change event */ protected void handleTableSelectionChanged(SelectionChangedEvent event) { - int size = ((IStructuredSelection)event.getSelection()).size(); + int size = ((IStructuredSelection) event.getSelection()).size(); envEditButton.setEnabled(size == 1); envRemoveButton.setEnabled(size > 0); } /** * Creates the add/edit/remove buttons for the environment table - * @param parent the composite in which the buttons should be created + * + * @param parent + * the composite in which the buttons should be created */ protected void createTableButtons(Composite parent) { // Create button composite @@ -310,44 +349,49 @@ public class PHPEnvironmentTab2 extends AbstractLaunchConfigurationTab { glayout.marginHeight = 0; glayout.marginWidth = 0; glayout.numColumns = 1; - GridData gdata = new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.HORIZONTAL_ALIGN_END); + GridData gdata = new GridData(GridData.VERTICAL_ALIGN_BEGINNING + | GridData.HORIZONTAL_ALIGN_END); buttonComposite.setLayout(glayout); buttonComposite.setLayoutData(gdata); buttonComposite.setFont(parent.getFont()); createVerticalSpacer(buttonComposite, 1); // Create buttons - envAddButton = createPushButton(buttonComposite, LaunchConfigurationsMessages.EnvironmentTab_New_4, null); //$NON-NLS-1$ - envAddButton.addSelectionListener(new SelectionAdapter() - { + envAddButton = createPushButton(buttonComposite, + LaunchConfigurationsMessages.EnvironmentTab_New_4, null); //$NON-NLS-1$ + envAddButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { handleEnvAddButtonSelected(); } - }); - envAddCGIButton = createPushButton(buttonComposite, PHPDebugUiMessages.getString("LaunchConfigurationTab.PHPEnvironment2.CGIButton"), null); //$NON-NLS-1$ + }); + envAddCGIButton = createPushButton( + buttonComposite, + PHPDebugUiMessages + .getString("LaunchConfigurationTab.PHPEnvironment2.CGIButton"), null); //$NON-NLS-1$ envAddCGIButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { handleEnvAddCGIButtonSelected(); } }); - envSelectButton = createPushButton(buttonComposite, LaunchConfigurationsMessages.EnvironmentTab_18, null); //$NON-NLS-1$ + envSelectButton = createPushButton(buttonComposite, + LaunchConfigurationsMessages.EnvironmentTab_18, null); //$NON-NLS-1$ envSelectButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { handleEnvSelectButtonSelected(); } }); - envEditButton = createPushButton(buttonComposite, LaunchConfigurationsMessages.EnvironmentTab_Edit_5, null); //$NON-NLS-1$ - envEditButton.addSelectionListener(new SelectionAdapter() - { + envEditButton = createPushButton(buttonComposite, + LaunchConfigurationsMessages.EnvironmentTab_Edit_5, null); //$NON-NLS-1$ + envEditButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { handleEnvEditButtonSelected(); } }); envEditButton.setEnabled(false); - envRemoveButton = createPushButton(buttonComposite, LaunchConfigurationsMessages.EnvironmentTab_Remove_6, null); //$NON-NLS-1$ - envRemoveButton.addSelectionListener(new SelectionAdapter() - { + envRemoveButton = createPushButton(buttonComposite, + LaunchConfigurationsMessages.EnvironmentTab_Remove_6, null); //$NON-NLS-1$ + envRemoveButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { handleEnvRemoveButtonSelected(); } @@ -359,7 +403,8 @@ public class PHPEnvironmentTab2 extends AbstractLaunchConfigurationTab { * Adds a new environment variable to the table. */ protected void handleEnvAddButtonSelected() { - MultipleInputDialog dialog = new MultipleInputDialog(getShell(), LaunchConfigurationsMessages.EnvironmentTab_22); //$NON-NLS-1$ + MultipleInputDialog dialog = new MultipleInputDialog(getShell(), + LaunchConfigurationsMessages.EnvironmentTab_22); //$NON-NLS-1$ dialog.addTextField(NAME_LABEL, null, false); dialog.addVariablesField(VALUE_LABEL, null, true); @@ -370,26 +415,34 @@ public class PHPEnvironmentTab2 extends AbstractLaunchConfigurationTab { String name = dialog.getStringValue(NAME_LABEL); String value = dialog.getStringValue(VALUE_LABEL); - if (name != null && value != null && name.length() > 0 && value.length() >0) { + if (name != null && value != null && name.length() > 0 + && value.length() > 0) { addVariable(new EnvironmentVariable(name.trim(), value.trim())); updateAppendReplace(); } } /** - * Attempts to add the given variable. Returns whether the variable - * was added or not (as when the user answers not to overwrite an - * existing variable). - * @param variable the variable to add + * Attempts to add the given variable. Returns whether the variable was + * added or not (as when the user answers not to overwrite an existing + * variable). + * + * @param variable + * the variable to add * @return whether the variable was added */ protected boolean addVariable(EnvironmentVariable variable) { - String name= variable.getName(); + String name = variable.getName(); TableItem[] items = environmentTable.getTable().getItems(); for (int i = 0; i < items.length; i++) { - EnvironmentVariable existingVariable = (EnvironmentVariable) items[i].getData(); + EnvironmentVariable existingVariable = (EnvironmentVariable) items[i] + .getData(); if (existingVariable.getName().equals(name)) { - boolean overWrite= MessageDialog.openQuestion(getShell(), LaunchConfigurationsMessages.EnvironmentTab_12, MessageFormat.format(LaunchConfigurationsMessages.EnvironmentTab_13, new String[] {name})); //$NON-NLS-1$ //$NON-NLS-2$ + boolean overWrite = MessageDialog.openQuestion(getShell(), + LaunchConfigurationsMessages.EnvironmentTab_12, + MessageFormat.format( + LaunchConfigurationsMessages.EnvironmentTab_13, + new String[] { name })); //$NON-NLS-1$ //$NON-NLS-2$ if (!overWrite) { return false; } @@ -407,18 +460,21 @@ public class PHPEnvironmentTab2 extends AbstractLaunchConfigurationTab { * to add to the table. */ private void handleEnvSelectButtonSelected() { - //get Environment Variables from the OS + // get Environment Variables from the OS Map envVariables = getNativeEnvironment(); - //get Environment Variables from the table + // get Environment Variables from the table TableItem[] items = environmentTable.getTable().getItems(); for (int i = 0; i < items.length; i++) { EnvironmentVariable var = (EnvironmentVariable) items[i].getData(); envVariables.remove(var.getName()); } - ListSelectionDialog dialog = new NativeEnvironmentDialog(getShell(), envVariables, createSelectionDialogContentProvider(), createSelectionDialogLabelProvider(), LaunchConfigurationsMessages.EnvironmentTab_19); //$NON-NLS-1$ - dialog.setTitle(LaunchConfigurationsMessages.EnvironmentTab_20); //$NON-NLS-1$ + ListSelectionDialog dialog = new NativeEnvironmentDialog(getShell(), + envVariables, createSelectionDialogContentProvider(), + createSelectionDialogLabelProvider(), + LaunchConfigurationsMessages.EnvironmentTab_19); //$NON-NLS-1$ + dialog.setTitle(LaunchConfigurationsMessages.EnvironmentTab_20); //$NON-NLS-1$ int button = dialog.open(); if (button == Window.OK) { @@ -440,35 +496,50 @@ public class PHPEnvironmentTab2 extends AbstractLaunchConfigurationTab { Map envVariables = new HashMap(); - - envVariables.put("HTTP_COOKIE",new EnvironmentVariable("HTTP_COOKIE", "TestCookie=1")); - envVariables.put("REDIRECT_QUERY_STRING",new EnvironmentVariable("REDIRECT_QUERY_STRING", "")); - envVariables.put("REDIRECT_STATUS",new EnvironmentVariable("REDIRECT_STATUS", "200")); - envVariables.put("REDIRECT_URL",new EnvironmentVariable("REDIRECT_URL", "")); - envVariables.put("SERVER_SOFTWARE",new EnvironmentVariable("SERVER_SOFTWARE","DBG / 2.1")); - envVariables.put("SERVER_NAME",new EnvironmentVariable("SERVER_NAME","localhost")); - envVariables.put("SERVER_ADDR",new EnvironmentVariable("SERVER_ADDR","127.0.0.1")); - envVariables.put("SERVER_PORT",new EnvironmentVariable("SERVER_PORT","80")); - envVariables.put("REMOTE_ADDR",new EnvironmentVariable("REMOTE_ADDR","127.0.0.1")); - envVariables.put("GATEWAY_INTERFACE",new EnvironmentVariable("GATEWAY_INTERFACE","CGI / 1.1")); - envVariables.put("SERVER_PROTOCOL",new EnvironmentVariable("SERVER_PROTOCOL","HTTP / 1.1")); - envVariables.put("REQUEST_METHOD",new EnvironmentVariable("REQUEST_METHOD","GET")); - envVariables.put("QUERY_STRING",new EnvironmentVariable("QUERY_STRING","")); - envVariables.put("REDIRECT_QUERY_STRING",new EnvironmentVariable("REDIRECT_QUERY_STRING","")); -// envVariables.put("REQUEST_URI" + OSFilePath; -// envVariables.put("PATH_INFO=" + OSFilePath; -// envVariables.put("PATH_TRANSLATED=" + OSFilePath; - - - //get Environment Variables from the table + envVariables.put("HTTP_COOKIE", new EnvironmentVariable("HTTP_COOKIE", + "TestCookie=1")); + envVariables.put("REDIRECT_QUERY_STRING", new EnvironmentVariable( + "REDIRECT_QUERY_STRING", "")); + envVariables.put("REDIRECT_STATUS", new EnvironmentVariable( + "REDIRECT_STATUS", "200")); + envVariables.put("REDIRECT_URL", new EnvironmentVariable( + "REDIRECT_URL", "")); + envVariables.put("SERVER_SOFTWARE", new EnvironmentVariable( + "SERVER_SOFTWARE", "DBG / 2.1")); + envVariables.put("SERVER_NAME", new EnvironmentVariable("SERVER_NAME", + "localhost")); + envVariables.put("SERVER_ADDR", new EnvironmentVariable("SERVER_ADDR", + "127.0.0.1")); + envVariables.put("SERVER_PORT", new EnvironmentVariable("SERVER_PORT", + "80")); + envVariables.put("REMOTE_ADDR", new EnvironmentVariable("REMOTE_ADDR", + "127.0.0.1")); + envVariables.put("GATEWAY_INTERFACE", new EnvironmentVariable( + "GATEWAY_INTERFACE", "CGI / 1.1")); + envVariables.put("SERVER_PROTOCOL", new EnvironmentVariable( + "SERVER_PROTOCOL", "HTTP / 1.1")); + envVariables.put("REQUEST_METHOD", new EnvironmentVariable( + "REQUEST_METHOD", "GET")); + envVariables.put("QUERY_STRING", new EnvironmentVariable( + "QUERY_STRING", "")); + envVariables.put("REDIRECT_QUERY_STRING", new EnvironmentVariable( + "REDIRECT_QUERY_STRING", "")); + // envVariables.put("REQUEST_URI" + OSFilePath; + // envVariables.put("PATH_INFO=" + OSFilePath; + // envVariables.put("PATH_TRANSLATED=" + OSFilePath; + + // get Environment Variables from the table TableItem[] items = environmentTable.getTable().getItems(); for (int i = 0; i < items.length; i++) { EnvironmentVariable var = (EnvironmentVariable) items[i].getData(); envVariables.remove(var.getName()); } - ListSelectionDialog dialog = new NativeEnvironmentDialog(getShell(), envVariables, createSelectionDialogContentProvider(), createSelectionDialogLabelProvider(), LaunchConfigurationsMessages.EnvironmentTab_19); //$NON-NLS-1$ - dialog.setTitle(LaunchConfigurationsMessages.EnvironmentTab_20); //$NON-NLS-1$ + ListSelectionDialog dialog = new NativeEnvironmentDialog(getShell(), + envVariables, createSelectionDialogContentProvider(), + createSelectionDialogLabelProvider(), + LaunchConfigurationsMessages.EnvironmentTab_19); //$NON-NLS-1$ + dialog.setTitle(LaunchConfigurationsMessages.EnvironmentTab_20); //$NON-NLS-1$ int button = dialog.open(); if (button == Window.OK) { @@ -482,35 +553,45 @@ public class PHPEnvironmentTab2 extends AbstractLaunchConfigurationTab { updateLaunchConfigurationDialog(); } - /** - * Creates a label provider for the native native environment variable selection dialog. - * @return A label provider for the native native environment variable selection dialog. + * Creates a label provider for the native native environment variable + * selection dialog. + * + * @return A label provider for the native native environment variable + * selection dialog. */ private ILabelProvider createSelectionDialogLabelProvider() { return new ILabelProvider() { public Image getImage(Object element) { return null; } + public String getText(Object element) { EnvironmentVariable var = (EnvironmentVariable) element; return var.getName() + " [" + var.getValue() + "]"; //$NON-NLS-1$ //$NON-NLS-2$ } + public void addListener(ILabelProviderListener listener) { } + public void dispose() { } + public boolean isLabelProperty(Object element, String property) { return false; } + public void removeListener(ILabelProviderListener listener) { } }; } /** - * Creates a content provider for the native native environment variable selection dialog. - * @return A content provider for the native native environment variable selection dialog. + * Creates a content provider for the native native environment variable + * selection dialog. + * + * @return A content provider for the native native environment variable + * selection dialog. */ private IStructuredContentProvider createSelectionDialogContentProvider() { return new IStructuredContentProvider() { @@ -519,38 +600,47 @@ public class PHPEnvironmentTab2 extends AbstractLaunchConfigurationTab { if (inputElement instanceof HashMap) { Comparator comparator = new Comparator() { public int compare(Object o1, Object o2) { - String s1 = (String)o1; - String s2 = (String)o2; + String s1 = (String) o1; + String s2 = (String) o2; return s1.compareTo(s2); } }; TreeMap envVars = new TreeMap(comparator); - envVars.putAll((Map)inputElement); + envVars.putAll((Map) inputElement); elements = new EnvironmentVariable[envVars.size()]; int index = 0; - for (Iterator iterator = envVars.keySet().iterator(); iterator.hasNext(); index++) { + for (Iterator iterator = envVars.keySet().iterator(); iterator + .hasNext(); index++) { Object key = iterator.next(); - elements[index] = (EnvironmentVariable) envVars.get(key); + elements[index] = (EnvironmentVariable) envVars + .get(key); } } return elements; } + public void dispose() { } - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + + public void inputChanged(Viewer viewer, Object oldInput, + Object newInput) { } }; } /** - * Gets native environment variable from the LaunchManager. Creates EnvironmentVariable objects. - * @return Map of name - EnvironmentVariable pairs based on native environment. + * Gets native environment variable from the LaunchManager. Creates + * EnvironmentVariable objects. + * + * @return Map of name - EnvironmentVariable pairs based on native + * environment. */ private Map getNativeEnvironment() { - Map stringVars = DebugPlugin.getDefault().getLaunchManager().getNativeEnvironment(); + Map stringVars = DebugPlugin.getDefault().getLaunchManager() + .getNativeEnvironment(); HashMap vars = new HashMap(); - for (Iterator i = stringVars.keySet().iterator(); i.hasNext(); ) { + for (Iterator i = stringVars.keySet().iterator(); i.hasNext();) { String key = (String) i.next(); String value = (String) stringVars.get(key); vars.put(key, new EnvironmentVariable(key, value)); @@ -562,22 +652,24 @@ public class PHPEnvironmentTab2 extends AbstractLaunchConfigurationTab { * Creates an editor for the value of the selected environment variable. */ private void handleEnvEditButtonSelected() { - IStructuredSelection sel= (IStructuredSelection) environmentTable.getSelection(); - EnvironmentVariable var= (EnvironmentVariable) sel.getFirstElement(); + IStructuredSelection sel = (IStructuredSelection) environmentTable + .getSelection(); + EnvironmentVariable var = (EnvironmentVariable) sel.getFirstElement(); if (var == null) { return; } - String originalName= var.getName(); - String value= var.getValue(); - MultipleInputDialog dialog= new MultipleInputDialog(getShell(), LaunchConfigurationsMessages.EnvironmentTab_11); //$NON-NLS-1$ + String originalName = var.getName(); + String value = var.getValue(); + MultipleInputDialog dialog = new MultipleInputDialog(getShell(), + LaunchConfigurationsMessages.EnvironmentTab_11); //$NON-NLS-1$ dialog.addTextField(NAME_LABEL, originalName, false); dialog.addVariablesField(VALUE_LABEL, value, true); if (dialog.open() != Window.OK) { return; } - String name= dialog.getStringValue(NAME_LABEL); - value= dialog.getStringValue(VALUE_LABEL); + String name = dialog.getStringValue(NAME_LABEL); + value = dialog.getStringValue(VALUE_LABEL); if (!originalName.equals(name)) { if (addVariable(new EnvironmentVariable(name, value))) { environmentTable.remove(var); @@ -593,11 +685,12 @@ public class PHPEnvironmentTab2 extends AbstractLaunchConfigurationTab { * Removes the selected environment variable from the table. */ private void handleEnvRemoveButtonSelected() { - IStructuredSelection sel = (IStructuredSelection) environmentTable.getSelection(); + IStructuredSelection sel = (IStructuredSelection) environmentTable + .getSelection(); environmentTable.getControl().setRedraw(false); - for (Iterator i = sel.iterator(); i.hasNext(); ) { + for (Iterator i = sel.iterator(); i.hasNext();) { EnvironmentVariable var = (EnvironmentVariable) i.next(); - environmentTable.remove(var); + environmentTable.remove(var); } environmentTable.getControl().setRedraw(true); updateAppendReplace(); @@ -606,31 +699,37 @@ public class PHPEnvironmentTab2 extends AbstractLaunchConfigurationTab { /** * Updates the environment table for the given launch configuration + * * @param configuration */ protected void updateEnvironment(ILaunchConfiguration configuration) { environmentTable.setInput(configuration); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.debug.ui.ILaunchConfigurationTab#setDefaults(org.eclipse.debug.core.ILaunchConfigurationWorkingCopy) */ public void setDefaults(ILaunchConfigurationWorkingCopy configuration) { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.debug.ui.ILaunchConfigurationTab#initializeFrom(org.eclipse.debug.core.ILaunchConfiguration) */ public void initializeFrom(ILaunchConfiguration configuration) { - boolean append= true; + boolean append = true; try { - append = configuration.getAttribute(ILaunchManager.ATTR_APPEND_ENVIRONMENT_VARIABLES, true); + append = configuration.getAttribute( + ILaunchManager.ATTR_APPEND_ENVIRONMENT_VARIABLES, true); } catch (CoreException e) { DebugUIPlugin.log(e.getStatus()); } if (append) { appendEnvironment.setSelection(true); - replaceEnvironment.setSelection(false); + replaceEnvironment.setSelection(false); } else { replaceEnvironment.setSelection(true); appendEnvironment.setSelection(false); @@ -641,6 +740,7 @@ public class PHPEnvironmentTab2 extends AbstractLaunchConfigurationTab { /** * Stores the environment in the given configuration + * * @see org.eclipse.debug.ui.ILaunchConfigurationTab#performApply(org.eclipse.debug.core.ILaunchConfigurationWorkingCopy) */ public void performApply(ILaunchConfigurationWorkingCopy configuration) { @@ -648,41 +748,53 @@ public class PHPEnvironmentTab2 extends AbstractLaunchConfigurationTab { // configuration's attributes. TableItem[] items = environmentTable.getTable().getItems(); Map map = new HashMap(items.length); - for (int i = 0; i < items.length; i++) - { + for (int i = 0; i < items.length; i++) { EnvironmentVariable var = (EnvironmentVariable) items[i].getData(); map.put(var.getName(), var.getValue()); } if (map.size() == 0) { - configuration.setAttribute(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES, (Map) null); + configuration.setAttribute( + ILaunchManager.ATTR_ENVIRONMENT_VARIABLES, (Map) null); } else { - configuration.setAttribute(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES, map); + configuration.setAttribute( + ILaunchManager.ATTR_ENVIRONMENT_VARIABLES, map); } - configuration.setAttribute(ILaunchManager.ATTR_APPEND_ENVIRONMENT_VARIABLES, appendEnvironment.getSelection()); + configuration.setAttribute( + ILaunchManager.ATTR_APPEND_ENVIRONMENT_VARIABLES, + appendEnvironment.getSelection()); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.debug.ui.ILaunchConfigurationTab#getName() */ public String getName() { - return LaunchConfigurationsMessages.EnvironmentTab_Environment_7; //$NON-NLS-1$ + return LaunchConfigurationsMessages.EnvironmentTab_Environment_7; //$NON-NLS-1$ } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.debug.ui.ILaunchConfigurationTab#getImage() */ public Image getImage() { - return DebugPluginImages.getImage(IDebugUIConstants.IMG_OBJS_ENVIRONMENT); + return DebugPluginImages + .getImage(IDebugUIConstants.IMG_OBJS_ENVIRONMENT); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.debug.ui.ILaunchConfigurationTab#activated(org.eclipse.debug.core.ILaunchConfigurationWorkingCopy) */ public void activated(ILaunchConfigurationWorkingCopy workingCopy) { // do nothing when activated } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.debug.ui.ILaunchConfigurationTab#deactivated(org.eclipse.debug.core.ILaunchConfigurationWorkingCopy) */ public void deactivated(ILaunchConfigurationWorkingCopy workingCopy) { @@ -690,29 +802,34 @@ public class PHPEnvironmentTab2 extends AbstractLaunchConfigurationTab { } private class NativeEnvironmentDialog extends ListSelectionDialog { - public NativeEnvironmentDialog(Shell parentShell, Object input, IStructuredContentProvider contentProvider, ILabelProvider labelProvider, String message) { + public NativeEnvironmentDialog(Shell parentShell, Object input, + IStructuredContentProvider contentProvider, + ILabelProvider labelProvider, String message) { super(parentShell, input, contentProvider, labelProvider, message); setShellStyle(getShellStyle() | SWT.RESIZE); } protected IDialogSettings getDialogSettings() { - IDialogSettings settings = DebugUIPlugin.getDefault().getDialogSettings(); - IDialogSettings section = settings.getSection(getDialogSettingsSectionName()); + IDialogSettings settings = DebugUIPlugin.getDefault() + .getDialogSettings(); + IDialogSettings section = settings + .getSection(getDialogSettingsSectionName()); if (section == null) { - section = settings.addNewSection(getDialogSettingsSectionName()); + section = settings + .addNewSection(getDialogSettingsSectionName()); } return section; } /** - * Returns the name of the section that this dialog stores its settings in - * + * Returns the name of the section that this dialog stores its settings + * in + * * @return String */ protected String getDialogSettingsSectionName() { - return IDebugUIConstants.PLUGIN_ID + ".ENVIRONMENT_TAB.NATIVE_ENVIROMENT_DIALOG"; //$NON-NLS-1$ + return IDebugUIConstants.PLUGIN_ID + + ".ENVIRONMENT_TAB.NATIVE_ENVIROMENT_DIALOG"; //$NON-NLS-1$ } } } - - diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/PHPLaunchShortcut.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/PHPLaunchShortcut.java index 53b337f..dbe826f 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/PHPLaunchShortcut.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/launcher/PHPLaunchShortcut.java @@ -27,13 +27,15 @@ import org.eclipse.ui.IEditorPart; public class PHPLaunchShortcut implements ILaunchShortcut { public PHPLaunchShortcut() { } - - public void launch(ISelection selection, String mode) { - if (selection instanceof IStructuredSelection) { - Object firstSelection = ((IStructuredSelection)selection).getFirstElement(); - if (firstSelection instanceof IFile) { + + public void launch(ISelection selection, String mode) { + if (selection instanceof IStructuredSelection) { + Object firstSelection = ((IStructuredSelection) selection) + .getFirstElement(); + if (firstSelection instanceof IFile) { if (PHPFileUtil.isPHPFile((IFile) firstSelection)) { - ILaunchConfiguration config = findLaunchConfiguration((IFile)firstSelection, mode); + ILaunchConfiguration config = findLaunchConfiguration( + (IFile) firstSelection, mode); try { if (config != null) config.launch(mode, null); @@ -48,36 +50,43 @@ public class PHPLaunchShortcut implements ILaunchShortcut { log("The resource selected is not a PHP file."); } - public void launch(IEditorPart editor, String mode) { + public void launch(IEditorPart editor, String mode) { IEditorInput input = editor.getEditorInput(); - ISelection selection = new StructuredSelection(input.getAdapter(IFile.class)); + ISelection selection = new StructuredSelection(input + .getAdapter(IFile.class)); launch(selection, mode); } - protected ILaunchConfiguration findLaunchConfiguration(IFile phpFile, String mode) { + protected ILaunchConfiguration findLaunchConfiguration(IFile phpFile, + String mode) { ILaunchConfigurationType configType = getPHPLaunchConfigType(); List candidateConfigs = null; try { - ILaunchConfiguration[] configs = getLaunchManager().getLaunchConfigurations(configType); + ILaunchConfiguration[] configs = getLaunchManager() + .getLaunchConfigurations(configType); candidateConfigs = new ArrayList(configs.length); for (int i = 0; i < configs.length; i++) { ILaunchConfiguration config = configs[i]; - if (config.getAttribute(PHPLaunchConfigurationAttribute.FILE_NAME, "").equals(phpFile.getFullPath().toString())) { - candidateConfigs.add(config); + if (config.getAttribute( + PHPLaunchConfigurationAttribute.FILE_NAME, "").equals( + phpFile.getFullPath().toString())) { + candidateConfigs.add(config); } } } catch (CoreException e) { log(e); } - + switch (candidateConfigs.size()) { - case 0 : - return createConfiguration(phpFile); - case 1 : - return (ILaunchConfiguration) candidateConfigs.get(0); - default : - log(new RuntimeException(PHPDebugUiMessages.getString("LaunchConfigurationShortcut.PHP.multipleConfigurationsError"))); - return null; + case 0: + return createConfiguration(phpFile); + case 1: + return (ILaunchConfiguration) candidateConfigs.get(0); + default: + log(new RuntimeException( + PHPDebugUiMessages + .getString("LaunchConfigurationShortcut.PHP.multipleConfigurationsError"))); + return null; } } @@ -85,29 +94,37 @@ public class PHPLaunchShortcut implements ILaunchShortcut { ILaunchConfiguration config = null; try { ILaunchConfigurationType configType = getPHPLaunchConfigType(); - ILaunchConfigurationWorkingCopy wc = configType.newInstance(null, getLaunchManager().generateUniqueLaunchConfigurationNameFrom(phpFile.getName())); - wc.setAttribute(PHPLaunchConfigurationAttribute.PROJECT_NAME, phpFile.getProject().getName()); - wc.setAttribute(PHPLaunchConfigurationAttribute.FILE_NAME, phpFile.getProjectRelativePath().toString()); - wc.setAttribute(PHPLaunchConfigurationAttribute.WORKING_DIRECTORY, PHPDebugUiConstants.DEFAULT_WORKING_DIRECTORY); - config = wc.doSave(); + ILaunchConfigurationWorkingCopy wc = configType.newInstance(null, + getLaunchManager() + .generateUniqueLaunchConfigurationNameFrom( + phpFile.getName())); + wc.setAttribute(PHPLaunchConfigurationAttribute.PROJECT_NAME, + phpFile.getProject().getName()); + wc.setAttribute(PHPLaunchConfigurationAttribute.FILE_NAME, phpFile + .getProjectRelativePath().toString()); + wc.setAttribute(PHPLaunchConfigurationAttribute.WORKING_DIRECTORY, + PHPDebugUiConstants.DEFAULT_WORKING_DIRECTORY); + config = wc.doSave(); } catch (CoreException ce) { - log(ce); + log(ce); } return config; } protected ILaunchConfigurationType getPHPLaunchConfigType() { - return getLaunchManager().getLaunchConfigurationType(PHPLaunchConfigurationAttribute.PHP_LAUNCH_CONFIGURATION_TYPE); + return getLaunchManager().getLaunchConfigurationType( + PHPLaunchConfigurationAttribute.PHP_LAUNCH_CONFIGURATION_TYPE); } - + protected ILaunchManager getLaunchManager() { return DebugPlugin.getDefault().getLaunchManager(); } - + protected void log(String message) { - PHPDebugUiPlugin.log(new Status(Status.INFO, PHPDebugUiPlugin.PLUGIN_ID, Status.INFO, message, null)); + PHPDebugUiPlugin.log(new Status(Status.INFO, + PHPDebugUiPlugin.PLUGIN_ID, Status.INFO, message, null)); } - + protected void log(Throwable t) { PHPDebugUiPlugin.log(t); } diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/preferences/EditPathMapDialog.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/preferences/EditPathMapDialog.java index c6e88e8..1d15279 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/preferences/EditPathMapDialog.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/preferences/EditPathMapDialog.java @@ -24,82 +24,90 @@ import org.eclipse.swt.widgets.Text; /** * @author Christian - * + * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */ public class EditPathMapDialog extends StatusDialog { - private Text fLocalPathText; + private Text fRemotePathText; + private String[] fInitialValues; + private String fLocalPath; - private String fRemotePath; - - public EditPathMapDialog(Shell parentShell, String aDialogTitle, String[] initialValues) { + + private String fRemotePath; + + public EditPathMapDialog(Shell parentShell, String aDialogTitle, + String[] initialValues) { super(parentShell); setTitle(aDialogTitle); - fInitialValues= initialValues; + fInitialValues = initialValues; } - + protected void okPressed() { - fLocalPath= fLocalPathText.getText(); + fLocalPath = fLocalPathText.getText(); fRemotePath = fRemotePathText.getText(); super.okPressed(); } + protected Control createDialogArea(Composite composite) { Composite comp = new Composite(composite, SWT.NONE); - comp.setLayout(new GridLayout()); - - Composite fileComp= new Composite(comp,SWT.NONE); - GridLayout gridLayout = new GridLayout(); + comp.setLayout(new GridLayout()); + + Composite fileComp = new Composite(comp, SWT.NONE); + GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 3; -// gridLayout.marginHeight = 0; -// gridLayout.marginWidth = 0; + // gridLayout.marginHeight = 0; + // gridLayout.marginWidth = 0; fileComp.setLayout(gridLayout); - - Label label= new Label(fileComp,SWT.NONE); - label.setText(PHPDebugUiMessages.getString("EditPathDialog.Local_Path"));//$NON-NLS-1$ - - - fLocalPathText = new Text(fileComp,SWT.SINGLE | SWT.BORDER); + + Label label = new Label(fileComp, SWT.NONE); + label + .setText(PHPDebugUiMessages + .getString("EditPathDialog.Local_Path"));//$NON-NLS-1$ + + fLocalPathText = new Text(fileComp, SWT.SINGLE | SWT.BORDER); GridData gd = new GridData(); - gd.widthHint=250; + gd.widthHint = 250; fLocalPathText.setLayoutData(gd); fLocalPathText.setText(fInitialValues[0]); - Button button= new Button(fileComp, SWT.PUSH); - button.setText(PHPDebugUiMessages.getString("EditPathMapDialog.Browse")); //$NON-NLS-1$ + Button button = new Button(fileComp, SWT.PUSH); + button + .setText(PHPDebugUiMessages + .getString("EditPathMapDialog.Browse")); //$NON-NLS-1$ button.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { handleBrowseButtonSelected(); } }); - label= new Label(fileComp,SWT.NONE); - label.setText(PHPDebugUiMessages.getString("EditPathMapDialog.Remote_Path")); //$NON-NLS-1$ - fRemotePathText = new Text(fileComp,SWT.SINGLE | SWT.BORDER); + label = new Label(fileComp, SWT.NONE); + label.setText(PHPDebugUiMessages + .getString("EditPathMapDialog.Remote_Path")); //$NON-NLS-1$ + fRemotePathText = new Text(fileComp, SWT.SINGLE | SWT.BORDER); fRemotePathText.setText(fInitialValues[1]); gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan = 2; fRemotePathText.setLayoutData(gd); - + return composite; } - + public String[] getPathPair() { - return new String[] {fLocalPath,fRemotePath}; + return new String[] { fLocalPath, fRemotePath }; } - - + private void handleBrowseButtonSelected() { - DirectoryDialog dd = new DirectoryDialog(getShell(),SWT.OPEN); - dd.setMessage(PHPDebugUiMessages.getString("EditPathMapDialog.Select_the_directory_to_map")); //$NON-NLS-1$ - String path=dd.open(); - + DirectoryDialog dd = new DirectoryDialog(getShell(), SWT.OPEN); + dd.setMessage(PHPDebugUiMessages + .getString("EditPathMapDialog.Select_the_directory_to_map")); //$NON-NLS-1$ + String path = dd.open(); + if (path != null) fLocalPathText.setText(path); - - } + } } diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/preferences/PHPBasePreferencePage.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/preferences/PHPBasePreferencePage.java index b7ecbcc..4d56fce 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/preferences/PHPBasePreferencePage.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/preferences/PHPBasePreferencePage.java @@ -11,13 +11,15 @@ import org.eclipse.swt.widgets.Label; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; -public class PHPBasePreferencePage extends PreferencePage implements IWorkbenchPreferencePage { +public class PHPBasePreferencePage extends PreferencePage implements + IWorkbenchPreferencePage { public PHPBasePreferencePage() { super(); } - public void init(IWorkbench workbench) {} + public void init(IWorkbench workbench) { + } protected Control createContents(Composite parent) { noDefaultAndApplyButton(); @@ -28,7 +30,8 @@ public class PHPBasePreferencePage extends PreferencePage implements IWorkbenchP layout.marginWidth = 0; composite.setLayout(layout); - new Label(composite, SWT.NONE).setText(PHPDebugUiMessages.getString("PHPBasePreferencePage.label")); //$NON-NLS-1$ + new Label(composite, SWT.NONE).setText(PHPDebugUiMessages + .getString("PHPBasePreferencePage.label")); //$NON-NLS-1$ return composite; } diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/preferences/PHPInterpreterContentProvider.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/preferences/PHPInterpreterContentProvider.java index 329d7ac..1db48a4 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/preferences/PHPInterpreterContentProvider.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/preferences/PHPInterpreterContentProvider.java @@ -5,7 +5,8 @@ import java.util.List; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.Viewer; -public class PHPInterpreterContentProvider implements IStructuredContentProvider { +public class PHPInterpreterContentProvider implements + IStructuredContentProvider { protected List interpreters; public PHPInterpreterContentProvider() { @@ -16,7 +17,8 @@ public class PHPInterpreterContentProvider implements IStructuredContentProvider return interpreters.toArray(); } - public void dispose() {} + public void dispose() { + } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { interpreters = (List) newInput; diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/preferences/PHPInterpreterLabelProvider.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/preferences/PHPInterpreterLabelProvider.java index 84b52f9..1ebb99f 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/preferences/PHPInterpreterLabelProvider.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/preferences/PHPInterpreterLabelProvider.java @@ -19,24 +19,28 @@ public class PHPInterpreterLabelProvider implements ITableLabelProvider { public String getColumnText(Object element, int columnIndex) { PHPInterpreter interpreter = (PHPInterpreter) element; switch (columnIndex) { - case 0 : - return interpreter.getInstallLocation().toString(); -// case 1 : -// IPath installLocation = interpreter.getInstallLocation(); -// return installLocation != null ? installLocation.toOSString() : "In user path"; - default : - return "Unknown Column Index"; + case 0: + return interpreter.getInstallLocation().toString(); + // case 1 : + // IPath installLocation = interpreter.getInstallLocation(); + // return installLocation != null ? installLocation.toOSString() : + // "In user path"; + default: + return "Unknown Column Index"; } } - public void addListener(ILabelProviderListener listener) {} + public void addListener(ILabelProviderListener listener) { + } - public void dispose() {} + public void dispose() { + } public boolean isLabelProperty(Object element, String property) { return false; } - public void removeListener(ILabelProviderListener listener) {} + public void removeListener(ILabelProviderListener listener) { + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/preferences/PHPInterpreterPreferencePage.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/preferences/PHPInterpreterPreferencePage.java index 689b864..84a4f31 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/preferences/PHPInterpreterPreferencePage.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/preferences/PHPInterpreterPreferencePage.java @@ -34,219 +34,232 @@ import org.eclipse.swt.widgets.TableItem; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; -public class PHPInterpreterPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { - protected CheckboxTableViewer tableViewer; - - protected Button addButton, editButton, removeButton; - - public PHPInterpreterPreferencePage() { - super(); - } - - public void init(IWorkbench workbench) { - } - - protected Control createContents(Composite parent) { - noDefaultAndApplyButton(); - - Composite composite = createPageRoot(parent); - Table table = createInstalledInterpretersTable(composite); - createInstalledInterpretersTableViewer(table); - createButtonGroup(composite); - - tableViewer.setInput(PHPRuntime.getDefault().getInstalledInterpreters()); - PHPInterpreter selectedInterpreter = PHPRuntime.getDefault().getSelectedInterpreter(); - if (selectedInterpreter != null) - tableViewer.setChecked(selectedInterpreter, true); - - enableButtons(); - - return composite; - } - - protected void createButtonGroup(Composite composite) { - Composite buttons = new Composite(composite, SWT.NULL); - buttons.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING)); - GridLayout layout = new GridLayout(); - layout.marginHeight = 0; - layout.marginWidth = 0; - buttons.setLayout(layout); - - addButton = new Button(buttons, SWT.PUSH); - addButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - addButton.setText(PHPDebugUiMessages.getString("PHPInterpreterPreferencePage.addButton.label")); //$NON-NLS-1$ - addButton.addListener(SWT.Selection, new Listener() { - public void handleEvent(Event evt) { - addInterpreter(); - } - }); - - editButton = new Button(buttons, SWT.PUSH); - editButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - editButton.setText(PHPDebugUiMessages.getString("PHPInterpreterPreferencePage.editButton.label")); //$NON-NLS-1$ - editButton.addListener(SWT.Selection, new Listener() { - public void handleEvent(Event evt) { - editInterpreter(); - } - }); - - removeButton = new Button(buttons, SWT.PUSH); - removeButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - removeButton.setText(PHPDebugUiMessages.getString("PHPInterpreterPreferencePage.removeButton.label")); //$NON-NLS-1$ - removeButton.addListener(SWT.Selection, new Listener() { - public void handleEvent(Event evt) { - removeInterpreter(); - } - }); - } - - protected void createInstalledInterpretersTableViewer(Table table) { - tableViewer = new CheckboxTableViewer(table); - - tableViewer.setLabelProvider(new PHPInterpreterLabelProvider()); - tableViewer.setContentProvider(new PHPInterpreterContentProvider()); - - tableViewer.addSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent evt) { - enableButtons(); - } - }); - - tableViewer.addCheckStateListener(new ICheckStateListener() { - public void checkStateChanged(CheckStateChangedEvent event) { - updateSelectedInterpreter(event.getElement()); - } - }); - - tableViewer.addDoubleClickListener(new IDoubleClickListener() { - public void doubleClick(DoubleClickEvent e) { - editInterpreter(); - } - }); - } - - protected Table createInstalledInterpretersTable(Composite composite) { - Table table = new Table(composite, SWT.CHECK | SWT.BORDER | SWT.FULL_SELECTION); - - GridData data = new GridData(GridData.FILL_BOTH); - data.widthHint = convertWidthInCharsToPixels(80); - data.heightHint = convertHeightInCharsToPixels(10); - table.setLayoutData(data); - table.setHeaderVisible(true); - table.setLinesVisible(false); - - TableColumn column = new TableColumn(table, SWT.NULL); - column.setText(PHPDebugUiMessages.getString("PHPInterpreterPreferencePage.PHPInterpreterTable.interpreterPath")); //$NON-NLS-1$ - column.setWidth(400); - - // column = new TableColumn(table, SWT.NULL); - // column.setText(PHPDebugUiMessages.getString("PHPInterpreterPreferencePage.PHPInterpreterTable.interpreterPath")); - // //$NON-NLS-1$ - // column.setWidth(350); - - return table; - } - - protected Composite createPageRoot(Composite parent) { - Composite composite = new Composite(parent, SWT.NULL); - GridLayout layout = new GridLayout(); - layout.numColumns = 2; - composite.setLayout(layout); - return composite; - } - - protected void addInterpreter() { - PHPInterpreter newInterpreter = new PHPInterpreter(null); - File phpRuntime = getFile(getShell(), null); - if (phpRuntime != null) { - newInterpreter.setInstallLocation(phpRuntime); - tableViewer.add(newInterpreter); - } - } - - protected void removeInterpreter() { - tableViewer.remove(getSelectedInterpreter()); - } - - protected void enableButtons() { - if (getSelectedInterpreter() != null) { - editButton.setEnabled(true); - removeButton.setEnabled(true); - } else { - editButton.setEnabled(false); - removeButton.setEnabled(false); - } - } - - protected void updateSelectedInterpreter(Object interpreter) { - Object[] checkedElements = tableViewer.getCheckedElements(); - for (int i = 0; i < checkedElements.length; i++) { - tableViewer.setChecked(checkedElements[i], false); - } - - tableViewer.setChecked(interpreter, true); - } - - protected void editInterpreter() { - PHPInterpreter anInterpreter = getSelectedInterpreter(); - File phpRuntime = anInterpreter.getInstallLocation(); - if (phpRuntime != null) { - File parent = phpRuntime.getParentFile(); - phpRuntime = getFile(getShell(), parent); - } else { - phpRuntime = getFile(getShell(), null); - } - if (phpRuntime != null) { - anInterpreter.setInstallLocation(phpRuntime); - tableViewer.update(anInterpreter, null); - } - - } - - protected PHPInterpreter getSelectedInterpreter() { - IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection(); - return (PHPInterpreter) selection.getFirstElement(); - } - - public boolean performOk() { - TableItem[] tableItems = tableViewer.getTable().getItems(); - List installedInterpreters = new ArrayList(tableItems.length); - for (int i = 0; i < tableItems.length; i++) - installedInterpreters.add(tableItems[i].getData()); - PHPRuntime.getDefault().setInstalledInterpreters(installedInterpreters); - - Object[] checkedElements = tableViewer.getCheckedElements(); - if (checkedElements.length > 0) - PHPRuntime.getDefault().setSelectedInterpreter((PHPInterpreter) checkedElements[0]); - - return super.performOk(); - } - - /** - * Helper to open the file chooser dialog. - * - * @param startingDirectory - * the directory to open the dialog on. - * @return File The File the user selected or null if they do not. - */ - public static File getFile(Shell shell, File startingDirectory) { - - FileDialog dialog = new FileDialog(shell, SWT.OPEN); - if (startingDirectory != null) { - dialog.setFileName(startingDirectory.getPath()); - } - String operatingSystem = Platform.getOS(); - if (operatingSystem.equals(Platform.OS_WIN32)) { - String[] extensions = { "*.exe" }; - dialog.setFilterExtensions(extensions); - } - String file = dialog.open(); - if (file != null) { - file = file.trim(); - if (file.length() > 0) - return new File(file); - } - - return null; - } +public class PHPInterpreterPreferencePage extends PreferencePage implements + IWorkbenchPreferencePage { + protected CheckboxTableViewer tableViewer; + + protected Button addButton, editButton, removeButton; + + public PHPInterpreterPreferencePage() { + super(); + } + + public void init(IWorkbench workbench) { + } + + protected Control createContents(Composite parent) { + noDefaultAndApplyButton(); + + Composite composite = createPageRoot(parent); + Table table = createInstalledInterpretersTable(composite); + createInstalledInterpretersTableViewer(table); + createButtonGroup(composite); + + tableViewer + .setInput(PHPRuntime.getDefault().getInstalledInterpreters()); + PHPInterpreter selectedInterpreter = PHPRuntime.getDefault() + .getSelectedInterpreter(); + if (selectedInterpreter != null) + tableViewer.setChecked(selectedInterpreter, true); + + enableButtons(); + + return composite; + } + + protected void createButtonGroup(Composite composite) { + Composite buttons = new Composite(composite, SWT.NULL); + buttons.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING)); + GridLayout layout = new GridLayout(); + layout.marginHeight = 0; + layout.marginWidth = 0; + buttons.setLayout(layout); + + addButton = new Button(buttons, SWT.PUSH); + addButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + addButton.setText(PHPDebugUiMessages + .getString("PHPInterpreterPreferencePage.addButton.label")); //$NON-NLS-1$ + addButton.addListener(SWT.Selection, new Listener() { + public void handleEvent(Event evt) { + addInterpreter(); + } + }); + + editButton = new Button(buttons, SWT.PUSH); + editButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + editButton.setText(PHPDebugUiMessages + .getString("PHPInterpreterPreferencePage.editButton.label")); //$NON-NLS-1$ + editButton.addListener(SWT.Selection, new Listener() { + public void handleEvent(Event evt) { + editInterpreter(); + } + }); + + removeButton = new Button(buttons, SWT.PUSH); + removeButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + removeButton.setText(PHPDebugUiMessages + .getString("PHPInterpreterPreferencePage.removeButton.label")); //$NON-NLS-1$ + removeButton.addListener(SWT.Selection, new Listener() { + public void handleEvent(Event evt) { + removeInterpreter(); + } + }); + } + + protected void createInstalledInterpretersTableViewer(Table table) { + tableViewer = new CheckboxTableViewer(table); + + tableViewer.setLabelProvider(new PHPInterpreterLabelProvider()); + tableViewer.setContentProvider(new PHPInterpreterContentProvider()); + + tableViewer + .addSelectionChangedListener(new ISelectionChangedListener() { + public void selectionChanged(SelectionChangedEvent evt) { + enableButtons(); + } + }); + + tableViewer.addCheckStateListener(new ICheckStateListener() { + public void checkStateChanged(CheckStateChangedEvent event) { + updateSelectedInterpreter(event.getElement()); + } + }); + + tableViewer.addDoubleClickListener(new IDoubleClickListener() { + public void doubleClick(DoubleClickEvent e) { + editInterpreter(); + } + }); + } + + protected Table createInstalledInterpretersTable(Composite composite) { + Table table = new Table(composite, SWT.CHECK | SWT.BORDER + | SWT.FULL_SELECTION); + + GridData data = new GridData(GridData.FILL_BOTH); + data.widthHint = convertWidthInCharsToPixels(80); + data.heightHint = convertHeightInCharsToPixels(10); + table.setLayoutData(data); + table.setHeaderVisible(true); + table.setLinesVisible(false); + + TableColumn column = new TableColumn(table, SWT.NULL); + column + .setText(PHPDebugUiMessages + .getString("PHPInterpreterPreferencePage.PHPInterpreterTable.interpreterPath")); //$NON-NLS-1$ + column.setWidth(400); + + // column = new TableColumn(table, SWT.NULL); + // column.setText(PHPDebugUiMessages.getString("PHPInterpreterPreferencePage.PHPInterpreterTable.interpreterPath")); + // //$NON-NLS-1$ + // column.setWidth(350); + + return table; + } + + protected Composite createPageRoot(Composite parent) { + Composite composite = new Composite(parent, SWT.NULL); + GridLayout layout = new GridLayout(); + layout.numColumns = 2; + composite.setLayout(layout); + return composite; + } + + protected void addInterpreter() { + PHPInterpreter newInterpreter = new PHPInterpreter(null); + File phpRuntime = getFile(getShell(), null); + if (phpRuntime != null) { + newInterpreter.setInstallLocation(phpRuntime); + tableViewer.add(newInterpreter); + } + } + + protected void removeInterpreter() { + tableViewer.remove(getSelectedInterpreter()); + } + + protected void enableButtons() { + if (getSelectedInterpreter() != null) { + editButton.setEnabled(true); + removeButton.setEnabled(true); + } else { + editButton.setEnabled(false); + removeButton.setEnabled(false); + } + } + + protected void updateSelectedInterpreter(Object interpreter) { + Object[] checkedElements = tableViewer.getCheckedElements(); + for (int i = 0; i < checkedElements.length; i++) { + tableViewer.setChecked(checkedElements[i], false); + } + + tableViewer.setChecked(interpreter, true); + } + + protected void editInterpreter() { + PHPInterpreter anInterpreter = getSelectedInterpreter(); + File phpRuntime = anInterpreter.getInstallLocation(); + if (phpRuntime != null) { + File parent = phpRuntime.getParentFile(); + phpRuntime = getFile(getShell(), parent); + } else { + phpRuntime = getFile(getShell(), null); + } + if (phpRuntime != null) { + anInterpreter.setInstallLocation(phpRuntime); + tableViewer.update(anInterpreter, null); + } + + } + + protected PHPInterpreter getSelectedInterpreter() { + IStructuredSelection selection = (IStructuredSelection) tableViewer + .getSelection(); + return (PHPInterpreter) selection.getFirstElement(); + } + + public boolean performOk() { + TableItem[] tableItems = tableViewer.getTable().getItems(); + List installedInterpreters = new ArrayList(tableItems.length); + for (int i = 0; i < tableItems.length; i++) + installedInterpreters.add(tableItems[i].getData()); + PHPRuntime.getDefault().setInstalledInterpreters(installedInterpreters); + + Object[] checkedElements = tableViewer.getCheckedElements(); + if (checkedElements.length > 0) + PHPRuntime.getDefault().setSelectedInterpreter( + (PHPInterpreter) checkedElements[0]); + + return super.performOk(); + } + + /** + * Helper to open the file chooser dialog. + * + * @param startingDirectory + * the directory to open the dialog on. + * @return File The File the user selected or null if they do + * not. + */ + public static File getFile(Shell shell, File startingDirectory) { + + FileDialog dialog = new FileDialog(shell, SWT.OPEN); + if (startingDirectory != null) { + dialog.setFileName(startingDirectory.getPath()); + } + String operatingSystem = Platform.getOS(); + if (operatingSystem.equals(Platform.OS_WIN32)) { + String[] extensions = { "*.exe" }; + dialog.setFilterExtensions(extensions); + } + String file = dialog.open(); + if (file != null) { + file = file.trim(); + if (file.length() > 0) + return new File(file); + } + + return null; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/properties/PHPBreakpointPropertiesDialog.java b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/properties/PHPBreakpointPropertiesDialog.java index 423b927..3774832 100644 --- a/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/properties/PHPBreakpointPropertiesDialog.java +++ b/net.sourceforge.phpeclipse.debug.ui/src/net/sourceforge/phpdt/internal/debug/ui/properties/PHPBreakpointPropertiesDialog.java @@ -1,8 +1,9 @@ - package net.sourceforge.phpdt.internal.debug.ui.properties; +import net.sourceforge.phpdt.internal.debug.core.breakpoints.PHPLineBreakpoint; + import org.eclipse.core.runtime.CoreException; -import org.eclipse.debug.internal.ui.actions.*; +import org.eclipse.debug.internal.ui.actions.StatusInfo; import org.eclipse.jface.dialogs.StatusDialog; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.text.Document; @@ -22,148 +23,150 @@ import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Spinner; -import net.sourceforge.phpdt.internal.debug.core.breakpoints.PHPLineBreakpoint; - public class PHPBreakpointPropertiesDialog extends StatusDialog { private PHPLineBreakpoint fBreakpoint; - private SourceViewer fSnippetViewer; - private Button fCheckBox; - private Spinner fSpinner; - + + private SourceViewer fSnippetViewer; + + private Button fCheckBox; + + private Spinner fSpinner; + public PHPBreakpointPropertiesDialog(Shell parentShell, PHPLineBreakpoint bp) { super(parentShell); - + fBreakpoint = bp; } - - protected Control createDialogArea (Composite parent) { - Composite container; + protected Control createDialogArea(Composite parent) { + Composite container; GridLayout layout; - GridData gd; - IDocument document; - Control control; - Label label; - Spinner spinner; - String condition = ""; - boolean enabled = false; - int hitCount = 0; - + GridData gd; + IDocument document; + Control control; + Label label; + Spinner spinner; + String condition = ""; + boolean enabled = false; + int hitCount = 0; + try { - condition = fBreakpoint.getCondition (); - enabled = fBreakpoint.isConditionEnabled (); - hitCount = fBreakpoint.getHitCount(); - } - catch (CoreException e) { + condition = fBreakpoint.getCondition(); + enabled = fBreakpoint.isConditionEnabled(); + hitCount = fBreakpoint.getHitCount(); + } catch (CoreException e) { } - - Font font = parent.getFont(); // Get the dialog's font - container = new Composite(parent, SWT.NONE); // Create a new container for our controls - layout = new GridLayout(); // Create a grid for control layouting - - container.setLayout (layout); // Set the grid to the container - gd = new GridData (SWT.FILL, SWT.FILL, true, true); - container.setLayoutData (gd); - - label = new Label (container, SWT.NONE); // spinner label - label.setText ("Skip count"); // $NON-NLS-1$ - - gd = new GridData (SWT.BEGINNING); // Left align of label text - label.setLayoutData (gd); // - label.setFont (font); // Set the label's font - - fSpinner = new Spinner (container, SWT.BORDER); - fSpinner.setMinimum (0); - fSpinner.setMaximum (100000); - fSpinner.setIncrement (1); - fSpinner.setPageIncrement (100); - fSpinner.setSelection (hitCount); - gd = new GridData (SWT.BEGINNING); - label.setLayoutData (gd); // - label.setFont (font); // Set the label's font - - label = new Label (container, SWT.NONE); // snippet label - label.setText ("Break Condition"); // $NON-NLS-1$ - - gd = new GridData (SWT.BEGINNING); // Left align of label text - label.setLayoutData (gd); // - label.setFont (font); // Set the label's font - - fSnippetViewer = new SourceViewer (container, null, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); - fSnippetViewer.setInput (this); - - document = new Document(); - - //IDocumentPartitioner partitioner= new RuleBasedPartitioner(...); - //document.setDocumentPartitioner(partitioner); - //partitioner.connect(document); - - fSnippetViewer.configure (new SourceViewerConfiguration()); - fSnippetViewer.setEditable (true); - fSnippetViewer.setDocument (document); - - document.addDocumentListener (new IDocumentListener() { + + Font font = parent.getFont(); // Get the dialog's font + container = new Composite(parent, SWT.NONE); // Create a new + // container for our + // controls + layout = new GridLayout(); // Create a grid for control layouting + + container.setLayout(layout); // Set the grid to the container + gd = new GridData(SWT.FILL, SWT.FILL, true, true); + container.setLayoutData(gd); + + label = new Label(container, SWT.NONE); // spinner label + label.setText("Skip count"); // $NON-NLS-1$ + + gd = new GridData(SWT.BEGINNING); // Left align of label text + label.setLayoutData(gd); // + label.setFont(font); // Set the label's font + + fSpinner = new Spinner(container, SWT.BORDER); + fSpinner.setMinimum(0); + fSpinner.setMaximum(100000); + fSpinner.setIncrement(1); + fSpinner.setPageIncrement(100); + fSpinner.setSelection(hitCount); + gd = new GridData(SWT.BEGINNING); + label.setLayoutData(gd); // + label.setFont(font); // Set the label's font + + label = new Label(container, SWT.NONE); // snippet label + label.setText("Break Condition"); // $NON-NLS-1$ + + gd = new GridData(SWT.BEGINNING); // Left align of label text + label.setLayoutData(gd); // + label.setFont(font); // Set the label's font + + fSnippetViewer = new SourceViewer(container, null, SWT.BORDER + | SWT.V_SCROLL | SWT.H_SCROLL); + fSnippetViewer.setInput(this); + + document = new Document(); + + // IDocumentPartitioner partitioner= new RuleBasedPartitioner(...); + // document.setDocumentPartitioner(partitioner); + // partitioner.connect(document); + + fSnippetViewer.configure(new SourceViewerConfiguration()); + fSnippetViewer.setEditable(true); + fSnippetViewer.setDocument(document); + + document.addDocumentListener(new IDocumentListener() { public void documentAboutToBeChanged(DocumentEvent event) { } + public void documentChanged(DocumentEvent event) { checkValues(); } }); - fSnippetViewer.getTextWidget ().setFont (JFaceResources.getTextFont()); + fSnippetViewer.getTextWidget().setFont(JFaceResources.getTextFont()); - control = fSnippetViewer.getControl (); - gd = new GridData (GridData.FILL_BOTH); - gd.heightHint = convertHeightInCharsToPixels (10); - gd.widthHint = convertWidthInCharsToPixels (80); - - control.setLayoutData (gd); - fSnippetViewer.getDocument ().set (condition); + control = fSnippetViewer.getControl(); + gd = new GridData(GridData.FILL_BOTH); + gd.heightHint = convertHeightInCharsToPixels(10); + gd.widthHint = convertWidthInCharsToPixels(80); + + control.setLayoutData(gd); + fSnippetViewer.getDocument().set(condition); // enable checkbox - fCheckBox = new Button (container, SWT.CHECK | SWT.LEFT); - fCheckBox.setText ("Enable Condition"); //$NON-NLS-1$ - fCheckBox.setSelection (enabled); - fCheckBox.setFont (font); + fCheckBox = new Button(container, SWT.CHECK | SWT.LEFT); + fCheckBox.setText("Enable Condition"); //$NON-NLS-1$ + fCheckBox.setSelection(enabled); + fCheckBox.setFont(font); applyDialogFont(container); fSnippetViewer.getControl().setFocus(); - - checkValues (); - + + checkValues(); + return container; } - - protected void okPressed () { + + protected void okPressed() { try { - fBreakpoint.setCondition (fSnippetViewer.getDocument().get()); - fBreakpoint.setConditionEnabled (fCheckBox.getSelection()); + fBreakpoint.setCondition(fSnippetViewer.getDocument().get()); + fBreakpoint.setConditionEnabled(fCheckBox.getSelection()); fBreakpoint.setHitCount(fSpinner.getSelection()); - + int id = fBreakpoint.getChangeID(); id++; fBreakpoint.setChangeID(id); + } catch (CoreException e) { } - catch (CoreException e) { - } - - super.okPressed (); + + super.okPressed(); } - + /** * Check the field values and display a message in the status if needed. */ private void checkValues() { StatusInfo status; - - status = new StatusInfo (); + + status = new StatusInfo(); /* - StatusInfo status = new StatusInfo(); - if (fSnippetViewer.getDocument().get().trim().length() == 0) { - status.setError(ActionMessages.WatchExpressionDialog_4); //$NON-NLS-1$ - } - */ + * StatusInfo status = new StatusInfo(); if + * (fSnippetViewer.getDocument().get().trim().length() == 0) { + * status.setError(ActionMessages.WatchExpressionDialog_4); + * //$NON-NLS-1$ } + */ updateStatus(status); } } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/ExternalPHPParser.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/ExternalPHPParser.java index 9169c71..ffb9ca7 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/ExternalPHPParser.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/ExternalPHPParser.java @@ -20,299 +20,326 @@ import org.eclipse.ui.texteditor.MarkerUtilities; * Calls the external parser and generates problem markers if necessary */ public class ExternalPHPParser { - private final static String PROBLEM_ID = "net.sourceforge.phpeclipse.problem"; - - // strings for external parser call - private static final String PARSE_ERROR_STRING = "Parse error"; //$NON-NLS-1$ - - private static final String PARSE_WARNING_STRING = "Warning"; //$NON-NLS-1$ - - public static final int ERROR = 2; - - public static final int WARNING = 1; - - public static final int INFO = 0; - - public static final int TASK = 3; - - // TODO design error? Analyze why fileToParse must be static ??? - final protected IFile fFileToParse; - - public ExternalPHPParser(IFile file) { - fFileToParse = file; - } - - /** - * Call the php parse command ( php -l -f <filename> ) and create markers according to the external parser output. - * - * @param file - * the file that will be parsed - */ - public void phpExternalParse() { - //IFile file = (IFile) resource; - // final IPath path = file.getFullPath(); - final IPreferenceStore store = ExternalToolsPlugin.getDefault().getPreferenceStore(); - final String filename = fFileToParse.getLocation().toString(); - - final String[] arguments = { filename }; - final MessageFormat form = new MessageFormat(store.getString(ExternalToolsPlugin.EXTERNAL_PARSER_PREF)); - final String command = form.format(arguments); - - final String parserResult = getParserOutput(command, "External parser: "); - - try { - // parse the buffer to find the errors and warnings - createMarkers(parserResult, fFileToParse); - } catch (CoreException e) { - } - } - - /** - * Create markers according to the external parser output. - * - * @param output - * the external parser output - * @param file - * the file that was parsed. - */ - protected void createMarkers(final String output, final IFile file) throws CoreException { - // delete all markers - file.deleteMarkers(PROBLEM_ID, false, 0); - - int indx = 0; - int brIndx; - boolean flag = true; - while ((brIndx = output.indexOf("
", indx)) != -1) { - // newer php error output (tested with 4.2.3) - scanLine(output, file, indx, brIndx); - indx = brIndx + 6; - flag = false; - } - if (flag) { - while ((brIndx = output.indexOf("
", indx)) != -1) { - // older php error output (tested with 4.2.3) - scanLine(output, file, indx, brIndx); - indx = brIndx + 4; - } - } - } - - private void scanLine(final String output, final IFile file, final int indx, final int brIndx) throws CoreException { - String current; - // String outLineNumberString; never used - final StringBuffer lineNumberBuffer = new StringBuffer(10); - char ch; - current = output.substring(indx, brIndx); - - if (current.indexOf(PARSE_WARNING_STRING) != -1 || current.indexOf(PARSE_ERROR_STRING) != -1) { - final int onLine = current.indexOf("on line "); - if (onLine != -1) { - lineNumberBuffer.delete(0, lineNumberBuffer.length()); - for (int i = onLine; i < current.length(); i++) { - ch = current.charAt(i); - if ('0' <= ch && '9' >= ch) { - lineNumberBuffer.append(ch); - } - } - - final int lineNumber = Integer.parseInt(lineNumberBuffer.toString()); - - final Hashtable attributes = new Hashtable(); - - current = StringUtil.replaceAll(current, "\n", ""); - current = StringUtil.replaceAll(current, "", ""); - current = StringUtil.replaceAll(current, "", ""); - MarkerUtilities.setMessage(attributes, current); - - if (current.indexOf(PARSE_ERROR_STRING) != -1) - attributes.put(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_ERROR)); - else if (current.indexOf(PARSE_WARNING_STRING) != -1) - attributes.put(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_WARNING)); - else - attributes.put(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_INFO)); - MarkerUtilities.setLineNumber(attributes, lineNumber); - MarkerUtilities.createMarker(file, attributes, PROBLEM_ID); - } - } - } - - /** - * This will set a marker. - * - * @param file - * the file that generated the marker - * @param message - * the message - * @param charStart - * the starting character - * @param charEnd - * the end character - * @param errorLevel - * the error level ({@link ExternalPHPParser#ERROR},{@link ExternalPHPParser#INFO},{@link ExternalPHPParser#WARNING}), - * {@link ExternalPHPParser#TASK}) - * @throws CoreException - * an exception throwed by the MarkerUtilities - */ - private void setMarker(final IFile file, final String message, final int charStart, final int charEnd, final int errorLevel) - throws CoreException { - if (file != null) { - final Hashtable attributes = new Hashtable(); - MarkerUtilities.setMessage(attributes, message); - switch (errorLevel) { - case ERROR: - attributes.put(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_ERROR)); - break; - case WARNING: - attributes.put(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_WARNING)); - break; - case INFO: - attributes.put(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_INFO)); - break; - case TASK: - attributes.put(IMarker.SEVERITY, new Integer(IMarker.TASK)); - break; - } - MarkerUtilities.setCharStart(attributes, charStart); - MarkerUtilities.setCharEnd(attributes, charEnd); - MarkerUtilities.createMarker(file, attributes, PROBLEM_ID); - } - } - - /** - * This will set a marker. - * - * @param file - * the file that generated the marker - * @param message - * the message - * @param line - * the line number - * @param errorLevel - * the error level ({@link ExternalPHPParser#ERROR},{@link ExternalPHPParser#INFO},{@link ExternalPHPParser#WARNING}) - * @throws CoreException - * an exception throwed by the MarkerUtilities - */ - private void setMarker(final IFile file, final String message, final int line, final int errorLevel, final String location) - throws CoreException { - if (file != null) { - String markerKind = PROBLEM_ID; - final Hashtable attributes = new Hashtable(); - MarkerUtilities.setMessage(attributes, message); - switch (errorLevel) { - case ERROR: - attributes.put(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_ERROR)); - break; - case WARNING: - attributes.put(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_WARNING)); - break; - case INFO: - attributes.put(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_INFO)); - break; - case TASK: - attributes.put(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_INFO)); - markerKind = IMarker.TASK; - break; - } - attributes.put(IMarker.LOCATION, location); - MarkerUtilities.setLineNumber(attributes, line); - MarkerUtilities.createMarker(file, attributes, markerKind); - } - } - - /** - * This will set a marker. - * - * @param message - * the message - * @param charStart - * the starting character - * @param charEnd - * the end character - * @param errorLevel - * the error level ({@link ExternalPHPParser#ERROR},{@link ExternalPHPParser#INFO},{@link ExternalPHPParser#WARNING}) - * @throws CoreException - * an exception throwed by the MarkerUtilities - */ - private void setMarker(final String message, final int charStart, final int charEnd, final int errorLevel, final String location) - throws CoreException { - if (fFileToParse != null) { - setMarker(fFileToParse, message, charStart, charEnd, errorLevel, location); - } - } - - /** - * This will set a marker. - * - * @param file - * the file that generated the marker - * @param message - * the message - * @param charStart - * the starting character - * @param charEnd - * the end character - * @param errorLevel - * the error level ({@link ExternalPHPParser#ERROR},{@link ExternalPHPParser#INFO},{@link ExternalPHPParser#WARNING}) - * @param location - * the location of the error - * @throws CoreException - * an exception throwed by the MarkerUtilities - */ - private void setMarker(final IFile file, final String message, final int charStart, final int charEnd, final int errorLevel, - final String location) throws CoreException { - if (file != null) { - final Hashtable attributes = new Hashtable(); - MarkerUtilities.setMessage(attributes, message); - switch (errorLevel) { - case ERROR: - attributes.put(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_ERROR)); - break; - case WARNING: - attributes.put(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_WARNING)); - break; - case INFO: - attributes.put(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_INFO)); - break; - case TASK: - attributes.put(IMarker.SEVERITY, new Integer(IMarker.TASK)); - break; - } - attributes.put(IMarker.LOCATION, location); - MarkerUtilities.setCharStart(attributes, charStart); - MarkerUtilities.setCharEnd(attributes, charEnd); - MarkerUtilities.createMarker(file, attributes, PROBLEM_ID); //IMarker.PROBLEM); - } - } - - private String getParserOutput(String command, String consoleMessage) { - try { - PHPConsole console = new PHPConsole(); - try { - console.println(consoleMessage + command); - } catch (Throwable th) { - - } - - Runtime runtime = Runtime.getRuntime(); - - // runs the command - Process p = runtime.exec(command); - - // gets the input stream to have the post-compile-time information - InputStream stream = p.getInputStream(); - - // get the string from Stream - String consoleOutput = PHPConsole.getStringFromStream(stream); - - // prints out the information - if (console != null) { - console.print(consoleOutput); - } - return consoleOutput; - - } catch (IOException e) { - MessageDialog.openInformation(null, "IOException: ", e.getMessage()); - } - return ""; - } + private final static String PROBLEM_ID = "net.sourceforge.phpeclipse.problem"; + + // strings for external parser call + private static final String PARSE_ERROR_STRING = "Parse error"; //$NON-NLS-1$ + + private static final String PARSE_WARNING_STRING = "Warning"; //$NON-NLS-1$ + + public static final int ERROR = 2; + + public static final int WARNING = 1; + + public static final int INFO = 0; + + public static final int TASK = 3; + + // TODO design error? Analyze why fileToParse must be static ??? + final protected IFile fFileToParse; + + public ExternalPHPParser(IFile file) { + fFileToParse = file; + } + + /** + * Call the php parse command ( php -l -f <filename> ) and create + * markers according to the external parser output. + * + * @param file + * the file that will be parsed + */ + public void phpExternalParse() { + // IFile file = (IFile) resource; + // final IPath path = file.getFullPath(); + final IPreferenceStore store = ExternalToolsPlugin.getDefault() + .getPreferenceStore(); + final String filename = fFileToParse.getLocation().toString(); + + final String[] arguments = { filename }; + final MessageFormat form = new MessageFormat(store + .getString(ExternalToolsPlugin.EXTERNAL_PARSER_PREF)); + final String command = form.format(arguments); + + final String parserResult = getParserOutput(command, + "External parser: "); + + try { + // parse the buffer to find the errors and warnings + createMarkers(parserResult, fFileToParse); + } catch (CoreException e) { + } + } + + /** + * Create markers according to the external parser output. + * + * @param output + * the external parser output + * @param file + * the file that was parsed. + */ + protected void createMarkers(final String output, final IFile file) + throws CoreException { + // delete all markers + file.deleteMarkers(PROBLEM_ID, false, 0); + + int indx = 0; + int brIndx; + boolean flag = true; + while ((brIndx = output.indexOf("
", indx)) != -1) { + // newer php error output (tested with 4.2.3) + scanLine(output, file, indx, brIndx); + indx = brIndx + 6; + flag = false; + } + if (flag) { + while ((brIndx = output.indexOf("
", indx)) != -1) { + // older php error output (tested with 4.2.3) + scanLine(output, file, indx, brIndx); + indx = brIndx + 4; + } + } + } + + private void scanLine(final String output, final IFile file, + final int indx, final int brIndx) throws CoreException { + String current; + // String outLineNumberString; never used + final StringBuffer lineNumberBuffer = new StringBuffer(10); + char ch; + current = output.substring(indx, brIndx); + + if (current.indexOf(PARSE_WARNING_STRING) != -1 + || current.indexOf(PARSE_ERROR_STRING) != -1) { + final int onLine = current.indexOf("on line "); + if (onLine != -1) { + lineNumberBuffer.delete(0, lineNumberBuffer.length()); + for (int i = onLine; i < current.length(); i++) { + ch = current.charAt(i); + if ('0' <= ch && '9' >= ch) { + lineNumberBuffer.append(ch); + } + } + + final int lineNumber = Integer.parseInt(lineNumberBuffer + .toString()); + + final Hashtable attributes = new Hashtable(); + + current = StringUtil.replaceAll(current, "\n", ""); + current = StringUtil.replaceAll(current, "", ""); + current = StringUtil.replaceAll(current, "", ""); + MarkerUtilities.setMessage(attributes, current); + + if (current.indexOf(PARSE_ERROR_STRING) != -1) + attributes.put(IMarker.SEVERITY, new Integer( + IMarker.SEVERITY_ERROR)); + else if (current.indexOf(PARSE_WARNING_STRING) != -1) + attributes.put(IMarker.SEVERITY, new Integer( + IMarker.SEVERITY_WARNING)); + else + attributes.put(IMarker.SEVERITY, new Integer( + IMarker.SEVERITY_INFO)); + MarkerUtilities.setLineNumber(attributes, lineNumber); + MarkerUtilities.createMarker(file, attributes, PROBLEM_ID); + } + } + } + + /** + * This will set a marker. + * + * @param file + * the file that generated the marker + * @param message + * the message + * @param charStart + * the starting character + * @param charEnd + * the end character + * @param errorLevel + * the error level ({@link ExternalPHPParser#ERROR},{@link ExternalPHPParser#INFO},{@link ExternalPHPParser#WARNING}), + * {@link ExternalPHPParser#TASK}) + * @throws CoreException + * an exception throwed by the MarkerUtilities + */ + private void setMarker(final IFile file, final String message, + final int charStart, final int charEnd, final int errorLevel) + throws CoreException { + if (file != null) { + final Hashtable attributes = new Hashtable(); + MarkerUtilities.setMessage(attributes, message); + switch (errorLevel) { + case ERROR: + attributes.put(IMarker.SEVERITY, new Integer( + IMarker.SEVERITY_ERROR)); + break; + case WARNING: + attributes.put(IMarker.SEVERITY, new Integer( + IMarker.SEVERITY_WARNING)); + break; + case INFO: + attributes.put(IMarker.SEVERITY, new Integer( + IMarker.SEVERITY_INFO)); + break; + case TASK: + attributes.put(IMarker.SEVERITY, new Integer(IMarker.TASK)); + break; + } + MarkerUtilities.setCharStart(attributes, charStart); + MarkerUtilities.setCharEnd(attributes, charEnd); + MarkerUtilities.createMarker(file, attributes, PROBLEM_ID); + } + } + + /** + * This will set a marker. + * + * @param file + * the file that generated the marker + * @param message + * the message + * @param line + * the line number + * @param errorLevel + * the error level ({@link ExternalPHPParser#ERROR},{@link ExternalPHPParser#INFO},{@link ExternalPHPParser#WARNING}) + * @throws CoreException + * an exception throwed by the MarkerUtilities + */ + private void setMarker(final IFile file, final String message, + final int line, final int errorLevel, final String location) + throws CoreException { + if (file != null) { + String markerKind = PROBLEM_ID; + final Hashtable attributes = new Hashtable(); + MarkerUtilities.setMessage(attributes, message); + switch (errorLevel) { + case ERROR: + attributes.put(IMarker.SEVERITY, new Integer( + IMarker.SEVERITY_ERROR)); + break; + case WARNING: + attributes.put(IMarker.SEVERITY, new Integer( + IMarker.SEVERITY_WARNING)); + break; + case INFO: + attributes.put(IMarker.SEVERITY, new Integer( + IMarker.SEVERITY_INFO)); + break; + case TASK: + attributes.put(IMarker.SEVERITY, new Integer( + IMarker.SEVERITY_INFO)); + markerKind = IMarker.TASK; + break; + } + attributes.put(IMarker.LOCATION, location); + MarkerUtilities.setLineNumber(attributes, line); + MarkerUtilities.createMarker(file, attributes, markerKind); + } + } + + /** + * This will set a marker. + * + * @param message + * the message + * @param charStart + * the starting character + * @param charEnd + * the end character + * @param errorLevel + * the error level ({@link ExternalPHPParser#ERROR},{@link ExternalPHPParser#INFO},{@link ExternalPHPParser#WARNING}) + * @throws CoreException + * an exception throwed by the MarkerUtilities + */ + private void setMarker(final String message, final int charStart, + final int charEnd, final int errorLevel, final String location) + throws CoreException { + if (fFileToParse != null) { + setMarker(fFileToParse, message, charStart, charEnd, errorLevel, + location); + } + } + + /** + * This will set a marker. + * + * @param file + * the file that generated the marker + * @param message + * the message + * @param charStart + * the starting character + * @param charEnd + * the end character + * @param errorLevel + * the error level ({@link ExternalPHPParser#ERROR},{@link ExternalPHPParser#INFO},{@link ExternalPHPParser#WARNING}) + * @param location + * the location of the error + * @throws CoreException + * an exception throwed by the MarkerUtilities + */ + private void setMarker(final IFile file, final String message, + final int charStart, final int charEnd, final int errorLevel, + final String location) throws CoreException { + if (file != null) { + final Hashtable attributes = new Hashtable(); + MarkerUtilities.setMessage(attributes, message); + switch (errorLevel) { + case ERROR: + attributes.put(IMarker.SEVERITY, new Integer( + IMarker.SEVERITY_ERROR)); + break; + case WARNING: + attributes.put(IMarker.SEVERITY, new Integer( + IMarker.SEVERITY_WARNING)); + break; + case INFO: + attributes.put(IMarker.SEVERITY, new Integer( + IMarker.SEVERITY_INFO)); + break; + case TASK: + attributes.put(IMarker.SEVERITY, new Integer(IMarker.TASK)); + break; + } + attributes.put(IMarker.LOCATION, location); + MarkerUtilities.setCharStart(attributes, charStart); + MarkerUtilities.setCharEnd(attributes, charEnd); + MarkerUtilities.createMarker(file, attributes, PROBLEM_ID); // IMarker.PROBLEM); + } + } + + private String getParserOutput(String command, String consoleMessage) { + try { + PHPConsole console = new PHPConsole(); + try { + console.println(consoleMessage + command); + } catch (Throwable th) { + + } + + Runtime runtime = Runtime.getRuntime(); + + // runs the command + Process p = runtime.exec(command); + + // gets the input stream to have the post-compile-time information + InputStream stream = p.getInputStream(); + + // get the string from Stream + String consoleOutput = PHPConsole.getStringFromStream(stream); + + // prints out the information + if (console != null) { + console.print(consoleOutput); + } + return consoleOutput; + + } catch (IOException e) { + MessageDialog + .openInformation(null, "IOException: ", e.getMessage()); + } + return ""; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPExternalParserAction.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPExternalParserAction.java index 58a5a2e..f255449 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPExternalParserAction.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPExternalParserAction.java @@ -1,14 +1,14 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ package net.sourceforge.phpdt.externaltools.actions; import java.util.Iterator; @@ -23,67 +23,71 @@ import org.eclipse.ui.IActionDelegate; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; - public class PHPExternalParserAction implements IObjectActionDelegate { - private IWorkbenchPart workbenchPart; - /** - * Constructor for Action1. - */ - public PHPExternalParserAction() { - super(); - } - - /** - * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart) - */ - public void setActivePart(IAction action, IWorkbenchPart targetPart) { - workbenchPart = targetPart; - } - - // public static void open(final URL url, final Shell shell, final String dialogTitle) { - // IHelp help= WorkbenchHelp.getHelpSupport(); - // if (help != null) { - // WorkbenchHelp.getHelpSupport().displayHelpResource(url.toExternalForm()); - // } else { - // showMessage(shell, dialogTitle, ActionMessages.getString("OpenBrowserUtil.help_not_available"), false); //$NON-NLS-1$ - // } - // } - - public void run(IAction action) { - ISelectionProvider selectionProvider = null; - selectionProvider = workbenchPart.getSite().getSelectionProvider(); - - StructuredSelection selection = null; - selection = (StructuredSelection) selectionProvider.getSelection(); - - //Shell shell = null; - Iterator iterator = null; - iterator = selection.iterator(); - while (iterator.hasNext()) { - // obj => selected object in the view - Object obj = iterator.next(); - - // is it a resource - if (obj instanceof IResource) { - IResource resource = (IResource) obj; - - // check if it's a file resource - switch (resource.getType()) { - - case IResource.FILE : - // single file: - ExternalPHPParser parser = new ExternalPHPParser((IFile)resource); - parser.phpExternalParse(); - } - } - } - } - - /** - * @see IActionDelegate#selectionChanged(IAction, ISelection) - */ - public void selectionChanged(IAction action, ISelection selection) { - } + private IWorkbenchPart workbenchPart; + + /** + * Constructor for Action1. + */ + public PHPExternalParserAction() { + super(); + } + + /** + * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart) + */ + public void setActivePart(IAction action, IWorkbenchPart targetPart) { + workbenchPart = targetPart; + } + + // public static void open(final URL url, final Shell shell, final String + // dialogTitle) { + // IHelp help= WorkbenchHelp.getHelpSupport(); + // if (help != null) { + // WorkbenchHelp.getHelpSupport().displayHelpResource(url.toExternalForm()); + // } else { + // showMessage(shell, dialogTitle, + // ActionMessages.getString("OpenBrowserUtil.help_not_available"), false); + // //$NON-NLS-1$ + // } + // } + + public void run(IAction action) { + ISelectionProvider selectionProvider = null; + selectionProvider = workbenchPart.getSite().getSelectionProvider(); + + StructuredSelection selection = null; + selection = (StructuredSelection) selectionProvider.getSelection(); + + // Shell shell = null; + Iterator iterator = null; + iterator = selection.iterator(); + while (iterator.hasNext()) { + // obj => selected object in the view + Object obj = iterator.next(); + + // is it a resource + if (obj instanceof IResource) { + IResource resource = (IResource) obj; + + // check if it's a file resource + switch (resource.getType()) { + + case IResource.FILE: + // single file: + ExternalPHPParser parser = new ExternalPHPParser( + (IFile) resource); + parser.phpExternalParse(); + } + } + } + } + + /** + * @see IActionDelegate#selectionChanged(IAction, ISelection) + */ + public void selectionChanged(IAction action, ISelection selection) { + } } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPRestartApacheAction.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPRestartApacheAction.java index 0a13cfa..5eb021d 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPRestartApacheAction.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPRestartApacheAction.java @@ -1,30 +1,30 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html -Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de -**********************************************************************/ + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ package net.sourceforge.phpdt.externaltools.actions; - import net.sourceforge.phpeclipse.externaltools.ExternalToolsPlugin; import org.eclipse.jface.action.IAction; import org.eclipse.jface.preference.IPreferenceStore; public class PHPRestartApacheAction extends PHPStartApacheAction { - public void run(IAction action) { - final IPreferenceStore store = ExternalToolsPlugin.getDefault().getPreferenceStore(); - // execute(store.getString(PHPeclipsePlugin.APACHE_RESTART_PREF), "Restart Apache: "); - execute( - "apache_restart", - store.getString(ExternalToolsPlugin.APACHE_RUN_PREF), - store.getString(ExternalToolsPlugin.APACHE_RESTART_PREF), - store.getBoolean(ExternalToolsPlugin.APACHE_RESTART_BACKGROUND)); - } + public void run(IAction action) { + final IPreferenceStore store = ExternalToolsPlugin.getDefault() + .getPreferenceStore(); + // execute(store.getString(PHPeclipsePlugin.APACHE_RESTART_PREF), + // "Restart Apache: "); + execute("apache_restart", store + .getString(ExternalToolsPlugin.APACHE_RUN_PREF), store + .getString(ExternalToolsPlugin.APACHE_RESTART_PREF), store + .getBoolean(ExternalToolsPlugin.APACHE_RESTART_BACKGROUND)); + } } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPStartApacheAction.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPStartApacheAction.java index ebe3de7..28e2ed8 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPStartApacheAction.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPStartApacheAction.java @@ -20,57 +20,66 @@ import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.IWorkbenchWindowActionDelegate; public class PHPStartApacheAction implements IWorkbenchWindowActionDelegate { - protected IWorkbenchWindow activeWindow = null; + protected IWorkbenchWindow activeWindow = null; - public void run(IAction action) { - final IPreferenceStore webUIStore = WebUI.getDefault().getPreferenceStore(); + public void run(IAction action) { + final IPreferenceStore webUIStore = WebUI.getDefault() + .getPreferenceStore(); - String documentRoot = webUIStore.getString(WebUI.PHP_DOCUMENTROOT_PREF); - final IPreferenceStore store = ExternalToolsPlugin.getDefault().getPreferenceStore(); + String documentRoot = webUIStore.getString(WebUI.PHP_DOCUMENTROOT_PREF); + final IPreferenceStore store = ExternalToolsPlugin.getDefault() + .getPreferenceStore(); - // replace backslash with slash in the DocumentRoot under Windows - documentRoot = documentRoot.replace('\\', '/'); - String[] arguments = { documentRoot }; - MessageFormat form = new MessageFormat(store.getString(ExternalToolsPlugin.APACHE_START_PREF)); - execute("apache_start", store.getString(ExternalToolsPlugin.APACHE_RUN_PREF), form.format(arguments), store - .getBoolean(ExternalToolsPlugin.APACHE_START_BACKGROUND)); - } + // replace backslash with slash in the DocumentRoot under Windows + documentRoot = documentRoot.replace('\\', '/'); + String[] arguments = { documentRoot }; + MessageFormat form = new MessageFormat(store + .getString(ExternalToolsPlugin.APACHE_START_PREF)); + execute("apache_start", store + .getString(ExternalToolsPlugin.APACHE_RUN_PREF), form + .format(arguments), store + .getBoolean(ExternalToolsPlugin.APACHE_START_BACKGROUND)); + } - /** - * Executes an external progam and saves the LaunchConfiguration under external tools - * - * @param command - * external tools command name - * @param executable - * executable path i.e.c:\apache\apache.exe - * @param arguments - * arguments for this configuration - * @param background - * run this configuration in background mode - */ - public static void execute(String command, String executable, String arguments, boolean background) { -// PHPConsole console = new PHPConsole(); -// String consoleMessage; -// if (background) { -// consoleMessage = "run in background mode-" + command + ": " + executable + " " + arguments; -// } else { -// consoleMessage = "run in foreground mode-" + command + ": " + executable + " " + arguments; -// } -// console.println(consoleMessage); + /** + * Executes an external progam and saves the LaunchConfiguration under + * external tools + * + * @param command + * external tools command name + * @param executable + * executable path i.e.c:\apache\apache.exe + * @param arguments + * arguments for this configuration + * @param background + * run this configuration in background mode + */ + public static void execute(String command, String executable, + String arguments, boolean background) { + // PHPConsole console = new PHPConsole(); + // String consoleMessage; + // if (background) { + // consoleMessage = "run in background mode-" + command + ": " + + // executable + " " + arguments; + // } else { + // consoleMessage = "run in foreground mode-" + command + ": " + + // executable + " " + arguments; + // } + // console.println(consoleMessage); - ExternalToolsUtil.execute(command, executable, arguments, background); - } + ExternalToolsUtil.execute(command, executable, arguments, background); + } - public void selectionChanged(IAction action, ISelection selection) { + public void selectionChanged(IAction action, ISelection selection) { - } + } - public void init(IWorkbenchWindow window) { - this.activeWindow = window; - } + public void init(IWorkbenchWindow window) { + this.activeWindow = window; + } - public void dispose() { + public void dispose() { - } + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPStartMySQLAction.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPStartMySQLAction.java index 860302a..b26aa69 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPStartMySQLAction.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPStartMySQLAction.java @@ -1,14 +1,14 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html -Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de -**********************************************************************/ + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ package net.sourceforge.phpdt.externaltools.actions; import net.sourceforge.phpeclipse.externaltools.ExternalToolsPlugin; @@ -17,13 +17,14 @@ import org.eclipse.jface.action.IAction; import org.eclipse.jface.preference.IPreferenceStore; public class PHPStartMySQLAction extends PHPStartApacheAction { - public void run(IAction action) { - final IPreferenceStore store = ExternalToolsPlugin.getDefault().getPreferenceStore(); - // execute(store.getString(PHPeclipsePlugin.MYSQL_PREF), "Start MySQL: "); - execute( - "mysql_start", - store.getString(ExternalToolsPlugin.MYSQL_RUN_PREF), - store.getString(ExternalToolsPlugin.MYSQL_PREF), - store.getBoolean(ExternalToolsPlugin.MYSQL_START_BACKGROUND)); - } + public void run(IAction action) { + final IPreferenceStore store = ExternalToolsPlugin.getDefault() + .getPreferenceStore(); + // execute(store.getString(PHPeclipsePlugin.MYSQL_PREF), "Start MySQL: + // "); + execute("mysql_start", store + .getString(ExternalToolsPlugin.MYSQL_RUN_PREF), store + .getString(ExternalToolsPlugin.MYSQL_PREF), store + .getBoolean(ExternalToolsPlugin.MYSQL_START_BACKGROUND)); + } } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPStartXAMPPAction.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPStartXAMPPAction.java index 9956b60..49d5a50 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPStartXAMPPAction.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPStartXAMPPAction.java @@ -19,54 +19,61 @@ import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.IWorkbenchWindowActionDelegate; public class PHPStartXAMPPAction implements IWorkbenchWindowActionDelegate { - protected IWorkbenchWindow activeWindow = null; + protected IWorkbenchWindow activeWindow = null; - public void run(IAction action) { - final IPreferenceStore store = ExternalToolsPlugin.getDefault().getPreferenceStore(); - String executable = store.getString(ExternalToolsPlugin.XAMPP_START_PREF); - String workingDirectory = null; - if (executable != null && executable.length() > 0) { - int index = executable.lastIndexOf(File.separatorChar); - if (index > 0) { - workingDirectory = executable.substring(0, index); - } - } - execute("xampp_start", executable, workingDirectory, true); - } + public void run(IAction action) { + final IPreferenceStore store = ExternalToolsPlugin.getDefault() + .getPreferenceStore(); + String executable = store + .getString(ExternalToolsPlugin.XAMPP_START_PREF); + String workingDirectory = null; + if (executable != null && executable.length() > 0) { + int index = executable.lastIndexOf(File.separatorChar); + if (index > 0) { + workingDirectory = executable.substring(0, index); + } + } + execute("xampp_start", executable, workingDirectory, true); + } - /** - * Executes an external progam and saves the LaunchConfiguration under external tools - * - * @param command - * external tools command name - * @param executable - * executable path i.e.c:\apache\apache.exe - * @param background - * run this configuration in background mode - */ - public static void execute(String command, String executable, String workingDirectory, boolean background) { -// PHPConsole console = new PHPConsole(); -// String consoleMessage; -// if (background) { -// consoleMessage = "run in background mode-" + command + ": " + executable; -// } else { -// consoleMessage = "run in foreground mode-" + command + ": " + executable; -// } -// console.println(consoleMessage); + /** + * Executes an external progam and saves the LaunchConfiguration under + * external tools + * + * @param command + * external tools command name + * @param executable + * executable path i.e.c:\apache\apache.exe + * @param background + * run this configuration in background mode + */ + public static void execute(String command, String executable, + String workingDirectory, boolean background) { + // PHPConsole console = new PHPConsole(); + // String consoleMessage; + // if (background) { + // consoleMessage = "run in background mode-" + command + ": " + + // executable; + // } else { + // consoleMessage = "run in foreground mode-" + command + ": " + + // executable; + // } + // console.println(consoleMessage); - ExternalToolsUtil.execute(command, executable, workingDirectory, null, background); - } + ExternalToolsUtil.execute(command, executable, workingDirectory, null, + background); + } - public void selectionChanged(IAction action, ISelection selection) { + public void selectionChanged(IAction action, ISelection selection) { - } + } - public void init(IWorkbenchWindow window) { - this.activeWindow = window; - } + public void init(IWorkbenchWindow window) { + this.activeWindow = window; + } - public void dispose() { + public void dispose() { - } + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPStopApacheAction.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPStopApacheAction.java index 1bdf89b..05880d2 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPStopApacheAction.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPStopApacheAction.java @@ -1,14 +1,14 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html -Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de -**********************************************************************/ + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ package net.sourceforge.phpdt.externaltools.actions; import net.sourceforge.phpeclipse.externaltools.ExternalToolsPlugin; @@ -17,13 +17,14 @@ import org.eclipse.jface.action.IAction; import org.eclipse.jface.preference.IPreferenceStore; public class PHPStopApacheAction extends PHPStartApacheAction { - public void run(IAction action) { - final IPreferenceStore store = ExternalToolsPlugin.getDefault().getPreferenceStore(); - // execute(store.getString(PHPeclipsePlugin.APACHE_STOP_PREF), "Stop Apache: "); - execute( - "apache_stop", - store.getString(ExternalToolsPlugin.APACHE_RUN_PREF), - store.getString(ExternalToolsPlugin.APACHE_STOP_PREF), - store.getBoolean(ExternalToolsPlugin.APACHE_STOP_BACKGROUND)); - } + public void run(IAction action) { + final IPreferenceStore store = ExternalToolsPlugin.getDefault() + .getPreferenceStore(); + // execute(store.getString(PHPeclipsePlugin.APACHE_STOP_PREF), "Stop + // Apache: "); + execute("apache_stop", store + .getString(ExternalToolsPlugin.APACHE_RUN_PREF), store + .getString(ExternalToolsPlugin.APACHE_STOP_PREF), store + .getBoolean(ExternalToolsPlugin.APACHE_STOP_BACKGROUND)); + } } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPStopXAMPPAction.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPStopXAMPPAction.java index de26291..cd816ee 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPStopXAMPPAction.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/actions/PHPStopXAMPPAction.java @@ -19,54 +19,61 @@ import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.IWorkbenchWindowActionDelegate; public class PHPStopXAMPPAction implements IWorkbenchWindowActionDelegate { - protected IWorkbenchWindow activeWindow = null; + protected IWorkbenchWindow activeWindow = null; - public void run(IAction action) { - final IPreferenceStore store = ExternalToolsPlugin.getDefault().getPreferenceStore(); - String executable = store.getString(ExternalToolsPlugin.XAMPP_STOP_PREF); - String workingDirectory = null; - if (executable != null && executable.length() > 0) { - int index = executable.lastIndexOf(File.separatorChar); - if (index > 0) { - workingDirectory = executable.substring(0, index); - } - } - execute("xampp_stop", executable, workingDirectory, true); - } + public void run(IAction action) { + final IPreferenceStore store = ExternalToolsPlugin.getDefault() + .getPreferenceStore(); + String executable = store + .getString(ExternalToolsPlugin.XAMPP_STOP_PREF); + String workingDirectory = null; + if (executable != null && executable.length() > 0) { + int index = executable.lastIndexOf(File.separatorChar); + if (index > 0) { + workingDirectory = executable.substring(0, index); + } + } + execute("xampp_stop", executable, workingDirectory, true); + } - /** - * Executes an external progam and saves the LaunchConfiguration under external tools - * - * @param command - * external tools command name - * @param executable - * executable path i.e.c:\apache\apache.exe - * @param background - * run this configuration in background mode - */ - public static void execute(String command, String executable, String workingDirectory, boolean background) { -// PHPConsole console = new PHPConsole(); -// String consoleMessage; -// if (background) { -// consoleMessage = "run in background mode-" + command + ": " + executable; -// } else { -// consoleMessage = "run in foreground mode-" + command + ": " + executable; -// } -// console.println(consoleMessage); + /** + * Executes an external progam and saves the LaunchConfiguration under + * external tools + * + * @param command + * external tools command name + * @param executable + * executable path i.e.c:\apache\apache.exe + * @param background + * run this configuration in background mode + */ + public static void execute(String command, String executable, + String workingDirectory, boolean background) { + // PHPConsole console = new PHPConsole(); + // String consoleMessage; + // if (background) { + // consoleMessage = "run in background mode-" + command + ": " + + // executable; + // } else { + // consoleMessage = "run in foreground mode-" + command + ": " + + // executable; + // } + // console.println(consoleMessage); - ExternalToolsUtil.execute(command, executable, workingDirectory, null, background); - } + ExternalToolsUtil.execute(command, executable, workingDirectory, null, + background); + } - public void selectionChanged(IAction action, ISelection selection) { + public void selectionChanged(IAction action, ISelection selection) { - } + } - public void init(IWorkbenchWindow window) { - this.activeWindow = window; - } + public void init(IWorkbenchWindow window) { + this.activeWindow = window; + } - public void dispose() { + public void dispose() { - } + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/group/IGroupDialogPage.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/group/IGroupDialogPage.java index d441165..1eaed85 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/group/IGroupDialogPage.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/group/IGroupDialogPage.java @@ -1,61 +1,64 @@ package net.sourceforge.phpdt.externaltools.group; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -  -Contributors: -**********************************************************************/ - + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ + import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Button; /** - * Represents the API for a group of visual components - * to access the dialog page that contains it. + * Represents the API for a group of visual components to access the dialog page + * that contains it. *

- * This interface is not intended to be extended - * nor implemented by clients. + * This interface is not intended to be extended nor implemented by clients. *

*/ public interface IGroupDialogPage extends IMessageProvider { /** - * Sets the GridData on the specified button to - * be one that is spaced for the current dialog page units. + * Sets the GridData on the specified button to be one that + * is spaced for the current dialog page units. * - * @param button the button to set the GridData + * @param button + * the button to set the GridData * @return the GridData set on the specified button */ public GridData setButtonGridData(Button button); /** - * Sets the message for this page with an indication of what type - * of message it is. + * Sets the message for this page with an indication of what type of message + * it is. *

- * The valid message types are one of NONE, - * INFORMATION, WARNING, or ERROR. + * The valid message types are one of NONE, + * INFORMATION, WARNING, or + * ERROR. *

- * - * @param newMessage the message, or null to clear the message - * @param newType the message type + * + * @param newMessage + * the message, or null to clear the message + * @param newType + * the message type */ public void setMessage(String newMessage, int newType); /** - * Updates the page's valid state using the group's - * current valid state. This will cause the dialog's - * buttons dependent on the page's valid state to - * update to reflect the new state. + * Updates the page's valid state using the group's current valid state. + * This will cause the dialog's buttons dependent on the page's valid state + * to update to reflect the new state. */ public void updateValidState(); - + /** * Converts a height in characters to a height in pixels. * - * @param chars the height in characters to be converted + * @param chars + * the height in characters to be converted * @return the corresponding height in pixels */ public int convertHeightHint(int chars); diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/dialog/ExternalToolVariableForm.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/dialog/ExternalToolVariableForm.java index 5a9de70..f528485 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/dialog/ExternalToolVariableForm.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/dialog/ExternalToolVariableForm.java @@ -1,13 +1,13 @@ package net.sourceforge.phpdt.externaltools.internal.dialog; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -� -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import net.sourceforge.phpdt.externaltools.group.IGroupDialogPage; import net.sourceforge.phpdt.externaltools.internal.registry.ExternalToolVariable; @@ -28,31 +28,40 @@ import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; /** - * Visual grouping of controls that allows the user to - * select a variable and configure it with extra - * information. + * Visual grouping of controls that allows the user to select a variable and + * configure it with extra information. */ public class ExternalToolVariableForm { private static final int VISIBLE_ITEM_COUNT = 9; - + private String variableListLabelText; + private ExternalToolVariable[] variables; + private IVariableComponent[] components; + private IGroupDialogPage page; - + private Label variableListLabel; + private List variableList; + private Composite variableComposite; + private StackLayout variableLayout; + private int activeComponentIndex = -1; - + /** * Creates the visual grouping * - * @param variableListLabelText the label text to use for identifying the list of variables - * @param variables the collection of variables to display to the user + * @param variableListLabelText + * the label text to use for identifying the list of variables + * @param variables + * the collection of variables to display to the user */ - public ExternalToolVariableForm(String variableListLabelText, ExternalToolVariable[] variables) { + public ExternalToolVariableForm(String variableListLabelText, + ExternalToolVariable[] variables) { super(); this.variableListLabelText = variableListLabelText; this.variables = variables; @@ -61,9 +70,9 @@ public class ExternalToolVariableForm { public Composite createContents(Composite parent, IGroupDialogPage page) { Font font = parent.getFont(); - + this.page = page; - + Composite mainComposite = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.marginWidth = 0; @@ -79,8 +88,9 @@ public class ExternalToolVariableForm { data.horizontalSpan = 1; variableListLabel.setLayoutData(data); variableListLabel.setFont(font); - - variableList = new List(mainComposite, SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL); + + variableList = new List(mainComposite, SWT.SINGLE | SWT.BORDER + | SWT.H_SCROLL | SWT.V_SCROLL); data = new GridData(GridData.FILL_HORIZONTAL); data.heightHint = variableList.getItemHeight() * VISIBLE_ITEM_COUNT; variableList.setLayoutData(data); @@ -94,25 +104,24 @@ public class ExternalToolVariableForm { variableComposite.setLayout(variableLayout); variableComposite.setLayoutData(data); variableComposite.setFont(font); - + createVariableComponents(data); - + populateVariableList(); - + variableList.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { updateVariableComposite(null, false); } }); - + setEnabled(true); return mainComposite; } - + /** - * Creates the visual component for each variable - * and determine the initial size so the form - * can be layout properly. + * Creates the visual component for each variable and determine the initial + * size so the form can be layout properly. */ private void createVariableComponents(GridData data) { for (int i = 0; i < variables.length; i++) { @@ -121,34 +130,36 @@ public class ExternalToolVariableForm { components[i].createContents(variableComposite, var.getTag(), page); Control control = components[i].getControl(); if (control != null) { - Point newSize = control.computeSize(SWT.DEFAULT, SWT.DEFAULT, true); + Point newSize = control.computeSize(SWT.DEFAULT, SWT.DEFAULT, + true); data.widthHint = Math.max(newSize.x, data.widthHint); data.heightHint = Math.max(newSize.y, data.heightHint); } } } - + /** - * Returns the formatted variable or null if - * none selected. + * Returns the formatted variable or null if none selected. */ public String getSelectedVariable() { if (activeComponentIndex != -1) { - String varValue = components[activeComponentIndex].getVariableValue(); - return ToolUtil.buildVariableTag(variables[activeComponentIndex].getTag(), varValue); + String varValue = components[activeComponentIndex] + .getVariableValue(); + return ToolUtil.buildVariableTag(variables[activeComponentIndex] + .getTag(), varValue); } return null; } /** - * Returns whether the current variable selection is - * valid, including the selected variable value. + * Returns whether the current variable selection is valid, including the + * selected variable value. */ public boolean isValid() { if (activeComponentIndex != -1) return components[activeComponentIndex].isValid(); - + return true; } @@ -165,7 +176,7 @@ public class ExternalToolVariableForm { variableList.setItems(items); } - public void selectVariable(String varName, String varValue) { + public void selectVariable(String varName, String varValue) { if (varName != null && varName.length() > 0) { for (int i = 0; i < variables.length; i++) { if (varName.equals(variables[i].getTag())) { @@ -175,11 +186,11 @@ public class ExternalToolVariableForm { } } } - + variableList.deselectAll(); updateVariableComposite(varValue, false); } - + private void setComponentVisible(int index) { if (index == -1) variableLayout.topControl = null; @@ -187,7 +198,7 @@ public class ExternalToolVariableForm { variableLayout.topControl = components[index].getControl(); variableComposite.layout(); } - + /** * Enables or disables the variable form controls. */ @@ -197,12 +208,12 @@ public class ExternalToolVariableForm { if (enabled && variableList.getSelection().length == 0) { if (variableList.getItemCount() > 0) { variableList.select(0); - activeComponentIndex= 0; + activeComponentIndex = 0; } } variableComposite.setVisible(enabled); } - + private void updateVariableComposite(String value, boolean setValue) { activeComponentIndex = variableList.getSelectionIndex(); setComponentVisible(activeComponentIndex); @@ -211,8 +222,7 @@ public class ExternalToolVariableForm { } /** - * Validates the current variable selection is and - * its value are acceptable. + * Validates the current variable selection is and its value are acceptable. */ public void validate() { if (activeComponentIndex != -1) diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/model/ExternalToolsImages.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/model/ExternalToolsImages.java index e333652..c765760 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/model/ExternalToolsImages.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/model/ExternalToolsImages.java @@ -1,13 +1,13 @@ package net.sourceforge.phpdt.externaltools.internal.model; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -� -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import java.net.MalformedURLException; import java.net.URL; @@ -26,99 +26,143 @@ import org.eclipse.ui.externaltools.internal.model.ExternalToolsPlugin; */ public class ExternalToolsImages { - /** + /** * The image registry containing Images. */ private static ImageRegistry imageRegistry; - + /** * A table of all the ImageDescriptors. */ private static HashMap imageDescriptors; private static final String ATTR_LAUNCH_CONFIG_TYPE_ICON = "icon"; //$NON-NLS-1$ + private static final String ATTR_LAUNCH_CONFIG_TYPE_ID = "configTypeID"; //$NON-NLS-1$ - + /* Declare Common paths */ - private static URL ICON_BASE_URL= null; - -// static { -// String pathSuffix = "icons/externaltools/full/"; //$NON-NLS-1$ -// -// try { -// ICON_BASE_URL= new URL(PHPeclipsePlugin.getDefault().getDescriptor().getInstallURL(), pathSuffix); -// } catch (MalformedURLException e) { -// // do nothing -// } -// } + private static URL ICON_BASE_URL = null; + + // static { + // String pathSuffix = "icons/externaltools/full/"; //$NON-NLS-1$ + // + // try { + // ICON_BASE_URL= new + // URL(PHPeclipsePlugin.getDefault().getDescriptor().getInstallURL(), + // pathSuffix); + // } catch (MalformedURLException e) { + // // do nothing + // } + // } static { String pathSuffix = "icons/full/"; //$NON-NLS-1$ - ICON_BASE_URL= ExternalToolsPlugin.getDefault().getBundle().getEntry(pathSuffix); + ICON_BASE_URL = ExternalToolsPlugin.getDefault().getBundle().getEntry( + pathSuffix); } - // Use IPath and toOSString to build the names to ensure they have the slashes correct - private final static String CTOOL= "ctool16/"; //basic colors - size 16x16 //$NON-NLS-1$ - private final static String LOCALTOOL= "clcl16/"; //basic colors - size 16x16 //$NON-NLS-1$ - private final static String DLCL= "dlcl16/"; //disabled - size 16x16 //$NON-NLS-1$ - private final static String ELCL= "elcl16/"; //enabled - size 16x16 //$NON-NLS-1$ - private final static String OBJECT= "obj16/"; //basic colors - size 16x16 //$NON-NLS-1$ - private final static String WIZBAN= "wizban/"; //basic colors - size 16x16 //$NON-NLS-1$ - private final static String OVR= "ovr16/"; //basic colors - size 7x8 //$NON-NLS-1$ - private final static String VIEW= "cview16/"; // views //$NON-NLS-1$ - + // Use IPath and toOSString to build the names to ensure they have the + // slashes correct + private final static String CTOOL = "ctool16/"; // basic colors - size 16x16 + // //$NON-NLS-1$ + + private final static String LOCALTOOL = "clcl16/"; // basic colors - size + // 16x16 //$NON-NLS-1$ + + private final static String DLCL = "dlcl16/"; // disabled - size 16x16 + // //$NON-NLS-1$ + + private final static String ELCL = "elcl16/"; // enabled - size 16x16 + // //$NON-NLS-1$ + + private final static String OBJECT = "obj16/"; // basic colors - size 16x16 + // //$NON-NLS-1$ + + private final static String WIZBAN = "wizban/"; // basic colors - size 16x16 + // //$NON-NLS-1$ + + private final static String OVR = "ovr16/"; // basic colors - size 7x8 + // //$NON-NLS-1$ + + private final static String VIEW = "cview16/"; // views //$NON-NLS-1$ + /** * Declare all images */ private static void declareImages() { // Ant View Actions - declareRegistryImage(IExternalToolsUIConstants.IMG_REMOVE, LOCALTOOL + "remove_co.gif"); //$NON-NLS-1$ - declareRegistryImage(IExternalToolsUIConstants.IMG_REMOVE_ALL, LOCALTOOL + "removeAll_co.gif"); //$NON-NLS-1$ - declareRegistryImage(IExternalToolsUIConstants.IMG_ADD, LOCALTOOL + "add_co.gif"); //$NON-NLS-1$ - declareRegistryImage(IExternalToolsUIConstants.IMG_RUN, LOCALTOOL + "run_tool.gif"); //$NON-NLS-1$ - declareRegistryImage(IExternalToolsUIConstants.IMG_SEARCH, LOCALTOOL + "search.gif"); //$NON-NLS-1$ - declareRegistryImage(IExternalToolsUIConstants.IMG_MOVE_UP, LOCALTOOL + "moveUp.gif"); //$NON-NLS-1$ - declareRegistryImage(IExternalToolsUIConstants.IMG_MOVE_DOWN, LOCALTOOL + "moveDown.gif"); //$NON-NLS-1$ - declareRegistryImage(IExternalToolsUIConstants.IMG_ACTIVATE, LOCALTOOL + "activate.gif"); //$NON-NLS-1$ - declareRegistryImage(IExternalToolsUIConstants.IMG_DEACTIVATE, LOCALTOOL + "deactivate.gif"); //$NON-NLS-1$ - declareRegistryImage(IExternalToolsUIConstants.IMG_GO_TO_FILE, LOCALTOOL + "gotoobj_tsk.gif"); //$NON-NLS-1$ + declareRegistryImage(IExternalToolsUIConstants.IMG_REMOVE, LOCALTOOL + + "remove_co.gif"); //$NON-NLS-1$ + declareRegistryImage(IExternalToolsUIConstants.IMG_REMOVE_ALL, + LOCALTOOL + "removeAll_co.gif"); //$NON-NLS-1$ + declareRegistryImage(IExternalToolsUIConstants.IMG_ADD, LOCALTOOL + + "add_co.gif"); //$NON-NLS-1$ + declareRegistryImage(IExternalToolsUIConstants.IMG_RUN, LOCALTOOL + + "run_tool.gif"); //$NON-NLS-1$ + declareRegistryImage(IExternalToolsUIConstants.IMG_SEARCH, LOCALTOOL + + "search.gif"); //$NON-NLS-1$ + declareRegistryImage(IExternalToolsUIConstants.IMG_MOVE_UP, LOCALTOOL + + "moveUp.gif"); //$NON-NLS-1$ + declareRegistryImage(IExternalToolsUIConstants.IMG_MOVE_DOWN, LOCALTOOL + + "moveDown.gif"); //$NON-NLS-1$ + declareRegistryImage(IExternalToolsUIConstants.IMG_ACTIVATE, LOCALTOOL + + "activate.gif"); //$NON-NLS-1$ + declareRegistryImage(IExternalToolsUIConstants.IMG_DEACTIVATE, + LOCALTOOL + "deactivate.gif"); //$NON-NLS-1$ + declareRegistryImage(IExternalToolsUIConstants.IMG_GO_TO_FILE, + LOCALTOOL + "gotoobj_tsk.gif"); //$NON-NLS-1$ // Ant View Labels -// declareRegistryImage(IExternalToolsUIConstants.IMG_ANT_PROJECT, OBJECT + "file_obj.gif"); //$NON-NLS-1$ -// declareRegistryImage(IExternalToolsUIConstants.IMG_ANT_PROJECT_ERROR, LOCALTOOL + "ant_project_err.gif"); //$NON-NLS-1$ -// declareRegistryImage(IExternalToolsUIConstants.IMG_ANT_TARGET, LOCALTOOL + "ant_target.gif"); //$NON-NLS-1$ -// declareRegistryImage(IExternalToolsUIConstants.IMG_ANT_TARGET_ERROR, LOCALTOOL + "error.gif"); //$NON-NLS-1$ -// declareRegistryImage(IExternalToolsUIConstants.IMG_ANT_TARGET_ELEMENTS, LOCALTOOL + "elements.gif"); //$NON-NLS-1$ -// declareRegistryImage(IExternalToolsUIConstants.IMG_ANT_TARGET_ELEMENT, LOCALTOOL + "element.gif"); //$NON-NLS-1$ + // declareRegistryImage(IExternalToolsUIConstants.IMG_ANT_PROJECT, + // OBJECT + "file_obj.gif"); //$NON-NLS-1$ + // declareRegistryImage(IExternalToolsUIConstants.IMG_ANT_PROJECT_ERROR, + // LOCALTOOL + "ant_project_err.gif"); //$NON-NLS-1$ + // declareRegistryImage(IExternalToolsUIConstants.IMG_ANT_TARGET, + // LOCALTOOL + "ant_target.gif"); //$NON-NLS-1$ + // declareRegistryImage(IExternalToolsUIConstants.IMG_ANT_TARGET_ERROR, + // LOCALTOOL + "error.gif"); //$NON-NLS-1$ + // declareRegistryImage(IExternalToolsUIConstants.IMG_ANT_TARGET_ELEMENTS, + // LOCALTOOL + "elements.gif"); //$NON-NLS-1$ + // declareRegistryImage(IExternalToolsUIConstants.IMG_ANT_TARGET_ELEMENT, + // LOCALTOOL + "element.gif"); //$NON-NLS-1$ // Wizards - declareRegistryImage(IExternalToolConstants.IMG_WIZBAN_EXTERNAL_TOOLS, WIZBAN + "ext_tools_wiz.gif"); //$NON-NLS-1$ - + declareRegistryImage(IExternalToolConstants.IMG_WIZBAN_EXTERNAL_TOOLS, + WIZBAN + "ext_tools_wiz.gif"); //$NON-NLS-1$ + // Actions - declareRegistryImage(IExternalToolConstants.IMG_ACTION_REFRESH, LOCALTOOL + "refresh.gif"); //$NON-NLS-1$ - + declareRegistryImage(IExternalToolConstants.IMG_ACTION_REFRESH, + LOCALTOOL + "refresh.gif"); //$NON-NLS-1$ + // Objects - declareRegistryImage(IExternalToolConstants.IMG_TAB_MAIN, OBJECT + "main_tab.gif"); //$NON-NLS-1$ - declareRegistryImage(IExternalToolConstants.IMG_TAB_OPTIONS, OBJECT + "options_tab.gif"); //$NON-NLS-1$ - - //ANT object - declareRegistryImage(IExternalToolConstants.IMG_TAB_ANT_TARGETS, LOCALTOOL + "ant_tsk_check.gif"); //$NON-NLS-1$ + declareRegistryImage(IExternalToolConstants.IMG_TAB_MAIN, OBJECT + + "main_tab.gif"); //$NON-NLS-1$ + declareRegistryImage(IExternalToolConstants.IMG_TAB_OPTIONS, OBJECT + + "options_tab.gif"); //$NON-NLS-1$ + + // ANT object + declareRegistryImage(IExternalToolConstants.IMG_TAB_ANT_TARGETS, + LOCALTOOL + "ant_tsk_check.gif"); //$NON-NLS-1$ } /** * Declare an Image in the registry table. - * @param key The key to use when registering the image - * @param path The path where the image can be found. This path is relative to where - * this plugin class is found (i.e. typically the packages directory) + * + * @param key + * The key to use when registering the image + * @param path + * The path where the image can be found. This path is relative + * to where this plugin class is found (i.e. typically the + * packages directory) */ private final static void declareRegistryImage(String key, String path) { - ImageDescriptor desc= ImageDescriptor.getMissingImageDescriptor(); + ImageDescriptor desc = ImageDescriptor.getMissingImageDescriptor(); try { - desc= ImageDescriptor.createFromURL(makeIconFileURL(path)); + desc = ImageDescriptor.createFromURL(makeIconFileURL(path)); } catch (MalformedURLException me) { - //ExternalToolsPlugin.log(me); + // ExternalToolsPlugin.log(me); } imageRegistry.put(key, desc); imageDescriptors.put(key, desc); } - + /** * Returns the ImageRegistry. */ @@ -130,35 +174,27 @@ public class ExternalToolsImages { } /** - * Initialize the image registry by declaring all of the required - * graphics. This involves creating JFace image descriptors describing - * how to create/find the image should it be needed. - * The image is not actually allocated until requested. - * - * Prefix conventions - * Wizard Banners WIZBAN_ - * Preference Banners PREF_BAN_ - * Property Page Banners PROPBAN_ - * Color toolbar CTOOL_ - * Enable toolbar ETOOL_ - * Disable toolbar DTOOL_ - * Local enabled toolbar ELCL_ - * Local Disable toolbar DLCL_ - * Object large OBJL_ - * Object small OBJS_ - * View VIEW_ - * Product images PROD_ - * Misc images MISC_ - * - * Where are the images? - * The images (typically gifs) are found in the same location as this plugin class. - * This may mean the same package directory as the package holding this class. - * The images are declared using this.getClass() to ensure they are looked up via - * this plugin class. - * @see JFace's ImageRegistry + * Initialize the image registry by declaring all of the required graphics. + * This involves creating JFace image descriptors describing how to + * create/find the image should it be needed. The image is not actually + * allocated until requested. + * + * Prefix conventions Wizard Banners WIZBAN_ Preference Banners PREF_BAN_ + * Property Page Banners PROPBAN_ Color toolbar CTOOL_ Enable toolbar ETOOL_ + * Disable toolbar DTOOL_ Local enabled toolbar ELCL_ Local Disable toolbar + * DLCL_ Object large OBJL_ Object small OBJS_ View VIEW_ Product images + * PROD_ Misc images MISC_ + * + * Where are the images? The images (typically gifs) are found in the same + * location as this plugin class. This may mean the same package directory + * as the package holding this class. The images are declared using + * this.getClass() to ensure they are looked up via this plugin class. + * + * @see JFace's ImageRegistry */ public static ImageRegistry initializeImageRegistry() { - imageRegistry= new ImageRegistry(ExternalToolsPlugin.getStandardDisplay()); + imageRegistry = new ImageRegistry(ExternalToolsPlugin + .getStandardDisplay()); imageDescriptors = new HashMap(30); declareImages(); return imageRegistry; @@ -171,7 +207,7 @@ public class ExternalToolsImages { public static Image getImage(String key) { return getImageRegistry().get(key); } - + /** * Returns the ImageDescriptor identified by the given key, * or null if it does not exist. @@ -180,16 +216,15 @@ public class ExternalToolsImages { if (imageDescriptors == null) { initializeImageRegistry(); } - return (ImageDescriptor)imageDescriptors.get(key); + return (ImageDescriptor) imageDescriptors.get(key); } - - private static URL makeIconFileURL(String iconPath) throws MalformedURLException { + + private static URL makeIconFileURL(String iconPath) + throws MalformedURLException { if (ICON_BASE_URL == null) { throw new MalformedURLException(); } - + return new URL(ICON_BASE_URL, iconPath); } } - - diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/model/ExternalToolsModelMessages.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/model/ExternalToolsModelMessages.java index 7e56a8b..e234173 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/model/ExternalToolsModelMessages.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/model/ExternalToolsModelMessages.java @@ -1,13 +1,13 @@ package net.sourceforge.phpdt.externaltools.internal.model; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -  -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import java.text.MessageFormat; import java.util.MissingResourceException; @@ -17,33 +17,36 @@ import java.util.ResourceBundle; * Utility class which helps managing messages */ public final class ExternalToolsModelMessages { - private static final String RESOURCE_BUNDLE= "net.sourceforge.phpdt.externaltools.internal.model.ExternalToolsModelMessages"; //$NON-NLS-1$ - private static ResourceBundle bundle = ResourceBundle.getBundle(RESOURCE_BUNDLE); - - private ExternalToolsModelMessages(){ + private static final String RESOURCE_BUNDLE = "net.sourceforge.phpdt.externaltools.internal.model.ExternalToolsModelMessages"; //$NON-NLS-1$ + + private static ResourceBundle bundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); + + private ExternalToolsModelMessages() { // prevent instantiation of class } - + /** - * Returns the formatted message for the given key in - * the resource bundle. - * - * @param key the message name - * @param args the message arguments + * Returns the formatted message for the given key in the resource bundle. + * + * @param key + * the message name + * @param args + * the message arguments * @return the formatted message - */ + */ public static String format(String key, Object[] args) { return MessageFormat.format(getString(key), args); } - + /** - * Returns the message with the given key in - * the resource bundle. If there isn't any value under - * the given key, the key is returned. - * - * @param key the message name + * Returns the message with the given key in the resource bundle. If there + * isn't any value under the given key, the key is returned. + * + * @param key + * the message name * @return the message - */ + */ public static String getString(String key) { try { return bundle.getString(key); @@ -51,7 +54,7 @@ public final class ExternalToolsModelMessages { return key; } } - + /** * Returns the resource bundle for the plug-in */ diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/model/IHelpContextIds.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/model/IHelpContextIds.java index 1517fc2..3a0ebc0 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/model/IHelpContextIds.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/model/IHelpContextIds.java @@ -1,13 +1,13 @@ package net.sourceforge.phpdt.externaltools.internal.model; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -  -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ /** * Help context ids for the external tools. @@ -20,39 +20,75 @@ public interface IHelpContextIds { public static final String PREFIX = "net.sourceforge.phpdt.externaltools."; //$NON-NLS-1$ // Actions - public static final String NEW_TOOL_ACTION = PREFIX + "new_tool_action_context"; //$NON-NLS-1$ - public static final String DUPLICATE_TOOL_ACTION = PREFIX + "duplicate_tool_action_context"; //$NON-NLS-1$ - public static final String DELETE_TOOL_ACTION = PREFIX + "delete_tool_action_context"; //$NON-NLS-1$ - public static final String RENAME_TOOL_ACTION = PREFIX + "rename_tool_action_context"; //$NON-NLS-1$ - public static final String REFRESH_VIEW_ACTION = PREFIX + "refresh_view_action_context"; //$NON-NLS-1$ - public static final String RUN_TOOL_ACTION = PREFIX + "run_tool_action_context"; //$NON-NLS-1$ - public static final String RUN_WITH_TOOL_ACTION = PREFIX + "run_with_tool_action_context"; //$NON-NLS-1$ - public static final String EDIT_TOOL_PROPERTIES_ACTION = PREFIX + "edit_tool_properties_action_context"; //$NON-NLS-1$ - //public static final String ANT_ACTION = PREFIX + "ant_action_context"; //$NON-NLS-1$ - + public static final String NEW_TOOL_ACTION = PREFIX + + "new_tool_action_context"; //$NON-NLS-1$ + + public static final String DUPLICATE_TOOL_ACTION = PREFIX + + "duplicate_tool_action_context"; //$NON-NLS-1$ + + public static final String DELETE_TOOL_ACTION = PREFIX + + "delete_tool_action_context"; //$NON-NLS-1$ + + public static final String RENAME_TOOL_ACTION = PREFIX + + "rename_tool_action_context"; //$NON-NLS-1$ + + public static final String REFRESH_VIEW_ACTION = PREFIX + + "refresh_view_action_context"; //$NON-NLS-1$ + + public static final String RUN_TOOL_ACTION = PREFIX + + "run_tool_action_context"; //$NON-NLS-1$ + + public static final String RUN_WITH_TOOL_ACTION = PREFIX + + "run_with_tool_action_context"; //$NON-NLS-1$ + + public static final String EDIT_TOOL_PROPERTIES_ACTION = PREFIX + + "edit_tool_properties_action_context"; //$NON-NLS-1$ + + // public static final String ANT_ACTION = PREFIX + "ant_action_context"; + // //$NON-NLS-1$ + // Dialogs - public static final String RESOURCE_SELECTION_DIALOG = PREFIX + "resource_selection_dialog_context"; //$NON-NLS-1$ + public static final String RESOURCE_SELECTION_DIALOG = PREFIX + + "resource_selection_dialog_context"; //$NON-NLS-1$ // Preference Pages - //public static final String ANT_PREFERENCE_PAGE = PREFIX + "ant_preference_page_context"; //$NON-NLS-1$ - public static final String ADD_TASK_DIALOG = PREFIX + "add_task_dialog_context"; //$NON-NLS-1$ + // public static final String ANT_PREFERENCE_PAGE = PREFIX + + // "ant_preference_page_context"; //$NON-NLS-1$ + public static final String ADD_TASK_DIALOG = PREFIX + + "add_task_dialog_context"; //$NON-NLS-1$ // Property Pages - public static final String TOOL_MAIN_PROPERTY_PAGE = PREFIX + "tool_main_property_page_context"; //$NON-NLS-1$ - public static final String TOOL_OPTION_PROPERTY_PAGE = PREFIX + "tool_option_property_page_context"; //$NON-NLS-1$ - public static final String TOOL_REFRESH_PROPERTY_PAGE = PREFIX + "tool_refresh_property_page_context"; //$NON-NLS-1$ - public static final String ANT_TARGETS_PROPERTY_PAGE = PREFIX + "ant_targets_property_page_context"; //$NON-NLS-1$ - + public static final String TOOL_MAIN_PROPERTY_PAGE = PREFIX + + "tool_main_property_page_context"; //$NON-NLS-1$ + + public static final String TOOL_OPTION_PROPERTY_PAGE = PREFIX + + "tool_option_property_page_context"; //$NON-NLS-1$ + + public static final String TOOL_REFRESH_PROPERTY_PAGE = PREFIX + + "tool_refresh_property_page_context"; //$NON-NLS-1$ + + public static final String ANT_TARGETS_PROPERTY_PAGE = PREFIX + + "ant_targets_property_page_context"; //$NON-NLS-1$ + // Views - public static final String EXTERNAL_TOOLS_VIEW = PREFIX + "external_tools_view_context"; //$NON-NLS-1$ + public static final String EXTERNAL_TOOLS_VIEW = PREFIX + + "external_tools_view_context"; //$NON-NLS-1$ // Wizards -// public static final String ANT_LAUNCH_WIZARD = PREFIX + "ant_launch_wizard_context"; //$NON-NLS-1$ - + // public static final String ANT_LAUNCH_WIZARD = PREFIX + + // "ant_launch_wizard_context"; //$NON-NLS-1$ + // Wizard Pages - public static final String TOOL_MAIN_WIZARD_PAGE = PREFIX + "tool_main_wizard_page_context"; //$NON-NLS-1$ - public static final String TOOL_OPTION_WIZARD_PAGE = PREFIX + "tool_option_wizard_page_context"; //$NON-NLS-1$ - public static final String TOOL_REFRESH_WIZARD_PAGE = PREFIX + "tool_refresh_wizard_page_context"; //$NON-NLS-1$ -// public static final String ANT_TARGETS_WIZARD_PAGE = PREFIX + "ant_targets_wizard_page_context"; //$NON-NLS-1$ -// public static final String ANT_LAUNCH_WIZARD_PAGE = PREFIX + "ant_launch_wizard_page_context"; //$NON-NLS-1$ + public static final String TOOL_MAIN_WIZARD_PAGE = PREFIX + + "tool_main_wizard_page_context"; //$NON-NLS-1$ + + public static final String TOOL_OPTION_WIZARD_PAGE = PREFIX + + "tool_option_wizard_page_context"; //$NON-NLS-1$ + + public static final String TOOL_REFRESH_WIZARD_PAGE = PREFIX + + "tool_refresh_wizard_page_context"; //$NON-NLS-1$ + // public static final String ANT_TARGETS_WIZARD_PAGE = PREFIX + + // "ant_targets_wizard_page_context"; //$NON-NLS-1$ + // public static final String ANT_LAUNCH_WIZARD_PAGE = PREFIX + + // "ant_launch_wizard_page_context"; //$NON-NLS-1$ } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/model/IPreferenceConstants.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/model/IPreferenceConstants.java index c6b52fb..3979be6 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/model/IPreferenceConstants.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/model/IPreferenceConstants.java @@ -1,31 +1,38 @@ package net.sourceforge.phpdt.externaltools.internal.model; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -  -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ /** * Constants used to identify user preferences. */ public interface IPreferenceConstants { - + public static final String PROMPT_FOR_MIGRATION = "externaltools.builders.promptForMigration"; //$NON-NLS-1$ - + public static final String CONSOLE_ERROR_RGB = "externaltools.console.errorColor"; //$NON-NLS-1$ + public static final String CONSOLE_WARNING_RGB = "externaltools.console.warningColor"; //$NON-NLS-1$ - public static final String CONSOLE_INFO_RGB = "externaltools.console.infoColor"; //$NON-NLS-1$ - public static final String CONSOLE_VERBOSE_RGB = "externaltools.console.verboseColor"; //$NON-NLS-1$ - public static final String CONSOLE_DEBUG_RGB = "externaltools.console.debugColor"; //$NON-NLS-1$ - + + public static final String CONSOLE_INFO_RGB = "externaltools.console.infoColor"; //$NON-NLS-1$ + + public static final String CONSOLE_VERBOSE_RGB = "externaltools.console.verboseColor"; //$NON-NLS-1$ + + public static final String CONSOLE_DEBUG_RGB = "externaltools.console.debugColor"; //$NON-NLS-1$ + public static final String ANTVIEW_INCLUDE_ERROR_SEARCH_RESULTS = "externaltools.antview.includeErrorSearchResults"; //$NON-NLS-1$ + public static final String ANTVIEW_LAST_SEARCH_STRING = "externaltools.antview.lastSearchString"; //$NON-NLS-1$ + public static final String ANTVIEW_LAST_WORKINGSET_SEARCH_SCOPE = "externaltools.antview.lastSearchScope"; //$NON-NLS-1$ + public static final String ANTVIEW_USE_WORKINGSET_SEARCH_SCOPE = "externaltools.antview.useWorkingSetSearchScope"; //$NON-NLS-1$ - + public static final String ANT_FIND_BUILD_FILE_NAMES = "ant.findBuildFileNames"; //$NON-NLS-1$ } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/model/ToolMessages.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/model/ToolMessages.java index c2b9bf7..d0cfc96 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/model/ToolMessages.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/model/ToolMessages.java @@ -1,13 +1,13 @@ package net.sourceforge.phpdt.externaltools.internal.model; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -  -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import java.text.MessageFormat; import java.util.MissingResourceException; @@ -17,33 +17,36 @@ import java.util.ResourceBundle; * Utility class which helps managing messages */ public final class ToolMessages { - private static final String RESOURCE_BUNDLE= "net.sourceforge.phpdt.externaltools.internal.model.messages"; //$NON-NLS-1$ - private static ResourceBundle bundle = ResourceBundle.getBundle(RESOURCE_BUNDLE); - - private ToolMessages(){ + private static final String RESOURCE_BUNDLE = "net.sourceforge.phpdt.externaltools.internal.model.messages"; //$NON-NLS-1$ + + private static ResourceBundle bundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); + + private ToolMessages() { // prevent instantiation of class } - + /** - * Returns the formatted message for the given key in - * the resource bundle. - * - * @param key the message name - * @param args the message arguments + * Returns the formatted message for the given key in the resource bundle. + * + * @param key + * the message name + * @param args + * the message arguments * @return the formatted message - */ + */ public static String format(String key, Object[] args) { return MessageFormat.format(getString(key), args); } - + /** - * Returns the message with the given key in - * the resource bundle. If there isn't any value under - * the given key, the key is returned. - * - * @param key the message name + * Returns the message with the given key in the resource bundle. If there + * isn't any value under the given key, the key is returned. + * + * @param key + * the message name * @return the message - */ + */ public static String getString(String key) { try { return bundle.getString(key); @@ -51,7 +54,7 @@ public final class ToolMessages { return key; } } - + /** * Returns the resource bundle for the plug-in */ diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/model/VariableContextManager.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/model/VariableContextManager.java index 686413e..c604f13 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/model/VariableContextManager.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/model/VariableContextManager.java @@ -1,11 +1,11 @@ package net.sourceforge.phpdt.externaltools.internal.model; /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + **********************************************************************/ import java.util.Map; @@ -30,32 +30,36 @@ import org.eclipse.ui.PlatformUI; import org.eclipse.ui.externaltools.internal.model.ExternalToolBuilder; /** - * Maintains the context used to expand variables. The context is based on - * the selected resource, unless a build is in progress - in which case - * the context is based on the project being built.. + * Maintains the context used to expand variables. The context is based on the + * selected resource, unless a build is in progress - in which case the context + * is based on the project being built.. */ -public class VariableContextManager implements IWindowListener, ISelectionListener { +public class VariableContextManager implements IWindowListener, + ISelectionListener { // singleton private static VariableContextManager fgDefault; - + private IResource fSelectedResource = null; - + private boolean fBuilding = false; + private IProject fProject = null; + private int fKind; - + private VariableContextManager() { IWorkbench workbench = PlatformUI.getWorkbench(); - if (workbench != null) { //may be running headless + if (workbench != null) { // may be running headless workbench.addWindowListener(this); - IWorkbenchWindow activeWindow = workbench.getActiveWorkbenchWindow(); + IWorkbenchWindow activeWindow = workbench + .getActiveWorkbenchWindow(); if (activeWindow != null) { windowActivated(activeWindow); } - } + } } - + /** * Returns the singleton resource selection manager * @@ -63,22 +67,22 @@ public class VariableContextManager implements IWindowListener, ISelectionListen */ public static VariableContextManager getDefault() { if (fgDefault == null) { - fgDefault = new VariableContextManager(); + fgDefault = new VariableContextManager(); } return fgDefault; } - + /** * @see org.eclipse.ui.IWindowListener#windowActivated(org.eclipse.ui.IWorkbenchWindow) */ public void windowActivated(IWorkbenchWindow window) { fSelectedResource = null; - ISelectionService service = window.getSelectionService(); + ISelectionService service = window.getSelectionService(); service.addSelectionListener(this); IWorkbenchPage page = window.getActivePage(); if (page != null) { IWorkbenchPart part = page.getActivePart(); - if (part != null) { + if (part != null) { ISelection selection = service.getSelection(); if (selection != null) { selectionChanged(part, selection); @@ -108,31 +112,36 @@ public class VariableContextManager implements IWindowListener, ISelectionListen } /** - * @see org.eclipse.ui.ISelectionListener#selectionChanged(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection) + * @see org.eclipse.ui.ISelectionListener#selectionChanged(org.eclipse.ui.IWorkbenchPart, + * org.eclipse.jface.viewers.ISelection) */ public void selectionChanged(IWorkbenchPart part, ISelection selection) { IResource selectedResource = null; if (selection instanceof IStructuredSelection) { - Object result = ((IStructuredSelection)selection).getFirstElement(); + Object result = ((IStructuredSelection) selection) + .getFirstElement(); if (result instanceof IResource) { selectedResource = (IResource) result; } else if (result instanceof IAdaptable) { - selectedResource = (IResource)((IAdaptable) result).getAdapter(IResource.class); + selectedResource = (IResource) ((IAdaptable) result) + .getAdapter(IResource.class); } } - + if (selectedResource == null) { - // If the active part is an editor, get the file resource used as input. + // If the active part is an editor, get the file resource used as + // input. if (part instanceof IEditorPart) { IEditorPart editorPart = (IEditorPart) part; IEditorInput input = editorPart.getEditorInput(); - selectedResource = (IResource) input.getAdapter(IResource.class); - } + selectedResource = (IResource) input + .getAdapter(IResource.class); + } } - + fSelectedResource = selectedResource; } - + /** * Returns the active variable context. The context is that of the selected * resource, or a project being built. @@ -146,7 +155,7 @@ public class VariableContextManager implements IWindowListener, ISelectionListen return new ExpandVariableContext(fSelectedResource); } } - + /** * Notification that the given project is being built. * @@ -159,13 +168,14 @@ public class VariableContextManager implements IWindowListener, ISelectionListen fProject = project; fKind = kind; } - + /** * Notification the building the current project has completed. + * * @see ExternalToolBuilder#build(int, Map, IProgressMonitor) */ public void buildEnded() { fBuilding = false; - fProject= null; + fProject = null; } } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/program/launchConfigurations/BackgroundResourceRefresher.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/program/launchConfigurations/BackgroundResourceRefresher.java index 1625a08..5a7f8bc 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/program/launchConfigurations/BackgroundResourceRefresher.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/program/launchConfigurations/BackgroundResourceRefresher.java @@ -1,13 +1,13 @@ package net.sourceforge.phpdt.externaltools.internal.program.launchConfigurations; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -� -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import java.lang.reflect.InvocationTargetException; @@ -26,21 +26,25 @@ import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; /** - * Refreshes resources as specified by a lanunch configuration, when - * an associated process terminates. + * Refreshes resources as specified by a lanunch configuration, when an + * associated process terminates. */ -public class BackgroundResourceRefresher implements IDebugEventSetListener, Runnable, IRunnableWithProgress { +public class BackgroundResourceRefresher implements IDebugEventSetListener, + Runnable, IRunnableWithProgress { private ExpandVariableContext fContext; + private ILaunchConfiguration fConfiguration; + private IProcess fProcess; - - public BackgroundResourceRefresher(ILaunchConfiguration configuration, IProcess process, ExpandVariableContext context) { + + public BackgroundResourceRefresher(ILaunchConfiguration configuration, + IProcess process, ExpandVariableContext context) { fConfiguration = configuration; fProcess = process; fContext = context; } - + /** * If the process has already terminated, resource refreshing is done * immediately in the current thread. Otherwise, refreshing is done when the @@ -55,35 +59,37 @@ public class BackgroundResourceRefresher implements IDebugEventSetListener, Runn } } } - + /** * @see org.eclipse.debug.core.IDebugEventSetListener#handleDebugEvents(org.eclipse.debug.core.DebugEvent) */ public void handleDebugEvents(DebugEvent[] events) { for (int i = 0; i < events.length; i++) { DebugEvent event = events[i]; - if (event.getSource() == fProcess && event.getKind() == DebugEvent.TERMINATE) { + if (event.getSource() == fProcess + && event.getKind() == DebugEvent.TERMINATE) { DebugPlugin.getDefault().removeDebugEventListener(this); refresh(); break; } } } - + /** * Submits a runnable to do the refresh */ protected void refresh() { - ExternalToolsPlugin.getStandardDisplay().asyncExec(this); + ExternalToolsPlugin.getStandardDisplay().asyncExec(this); } - - /** + + /** * Creates a dialog to run the refresh * * @see java.lang.Runnable#run() */ public void run() { - ProgressMonitorDialog dialog = new ProgressMonitorDialog(ExternalToolsPlugin.getStandardDisplay().getActiveShell()); + ProgressMonitorDialog dialog = new ProgressMonitorDialog( + ExternalToolsPlugin.getStandardDisplay().getActiveShell()); try { dialog.run(true, true, this); } catch (InvocationTargetException e) { @@ -91,17 +97,20 @@ public class BackgroundResourceRefresher implements IDebugEventSetListener, Runn } catch (InterruptedException e) { } } + /** * Peforms the refresh * * @see org.eclipse.jface.operation.IRunnableWithProgress#run(org.eclipse.core.runtime.IProgressMonitor) */ - public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { + public void run(IProgressMonitor monitor) throws InvocationTargetException, + InterruptedException { try { - ExternalToolsUtil.refreshResources(fConfiguration, fContext, monitor); + ExternalToolsUtil.refreshResources(fConfiguration, fContext, + monitor); } catch (CoreException e) { throw new InvocationTargetException(e); - } + } } } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/program/launchConfigurations/ProgramBuilderTabGroup.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/program/launchConfigurations/ProgramBuilderTabGroup.java index 46c3b6d..f0501e9 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/program/launchConfigurations/ProgramBuilderTabGroup.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/program/launchConfigurations/ProgramBuilderTabGroup.java @@ -1,11 +1,11 @@ package net.sourceforge.phpdt.externaltools.internal.program.launchConfigurations; /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + **********************************************************************/ import net.sourceforge.phpdt.externaltools.launchConfigurations.ExternalToolsRefreshTab; @@ -16,14 +16,13 @@ import org.eclipse.debug.ui.ILaunchConfigurationTab; public class ProgramBuilderTabGroup extends AbstractLaunchConfigurationTabGroup { /** - * @see org.eclipse.debug.ui.ILaunchConfigurationTabGroup#createTabs(org.eclipse.debug.ui.ILaunchConfigurationDialog, java.lang.String) + * @see org.eclipse.debug.ui.ILaunchConfigurationTabGroup#createTabs(org.eclipse.debug.ui.ILaunchConfigurationDialog, + * java.lang.String) */ public void createTabs(ILaunchConfigurationDialog dialog, String mode) { ILaunchConfigurationTab[] tabs = new ILaunchConfigurationTab[] { - new ProgramMainTab(), - new ExternalToolsRefreshTab(), - }; + new ProgramMainTab(), new ExternalToolsRefreshTab(), }; setTabs(tabs); } - + } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/program/launchConfigurations/ProgramLaunchDelegate.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/program/launchConfigurations/ProgramLaunchDelegate.java index 7df974e..38d227a 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/program/launchConfigurations/ProgramLaunchDelegate.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/program/launchConfigurations/ProgramLaunchDelegate.java @@ -1,13 +1,13 @@ package net.sourceforge.phpdt.externaltools.internal.program.launchConfigurations; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -  -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import java.io.File; @@ -36,42 +36,49 @@ public class ProgramLaunchDelegate implements ILaunchConfigurationDelegate { } /** - * @see org.eclipse.debug.core.model.ILaunchConfigurationDelegate#launch(org.eclipse.debug.core.ILaunchConfiguration, java.lang.String, org.eclipse.debug.core.ILaunch, org.eclipse.core.runtime.IProgressMonitor) + * @see org.eclipse.debug.core.model.ILaunchConfigurationDelegate#launch(org.eclipse.debug.core.ILaunchConfiguration, + * java.lang.String, org.eclipse.debug.core.ILaunch, + * org.eclipse.core.runtime.IProgressMonitor) */ - public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { - + public void launch(ILaunchConfiguration configuration, String mode, + ILaunch launch, IProgressMonitor monitor) throws CoreException { + if (monitor.isCanceled()) { return; } - + // get variable context - ExpandVariableContext resourceContext = ExternalToolsUtil.getVariableContext(); + ExpandVariableContext resourceContext = ExternalToolsUtil + .getVariableContext(); if (monitor.isCanceled()) { return; } - + // resolve location - IPath location = ExternalToolsUtil.getLocation(configuration, resourceContext); - + IPath location = ExternalToolsUtil.getLocation(configuration, + resourceContext); + if (monitor.isCanceled()) { return; - } - + } + // resolve working directory - IPath workingDirectory = ExternalToolsUtil.getWorkingDirectory(configuration, resourceContext); - + IPath workingDirectory = ExternalToolsUtil.getWorkingDirectory( + configuration, resourceContext); + if (monitor.isCanceled()) { return; } - + // resolve arguments - String[] arguments = ExternalToolsUtil.getArguments(configuration, resourceContext); - + String[] arguments = ExternalToolsUtil.getArguments(configuration, + resourceContext); + if (monitor.isCanceled()) { return; } - + int cmdLineLength = 1; if (arguments != null) { cmdLineLength += arguments.length; @@ -81,29 +88,30 @@ public class ProgramLaunchDelegate implements ILaunchConfigurationDelegate { if (arguments != null) { System.arraycopy(arguments, 0, cmdLine, 1, arguments.length); } - + File workingDir = null; if (workingDirectory != null) { workingDir = workingDirectory.toFile(); } - + if (monitor.isCanceled()) { return; } - + Process p = DebugPlugin.exec(cmdLine, workingDir); IProcess process = null; if (p != null) { process = DebugPlugin.newProcess(launch, p, location.toOSString()); } process.setAttribute(IProcess.ATTR_CMDLINE, renderCommandLine(cmdLine)); - + if (ExternalToolsUtil.isBackground(configuration)) { // refresh resources after process finishes if (ExternalToolsUtil.getRefreshScope(configuration) != null) { - BackgroundResourceRefresher refresher = new BackgroundResourceRefresher(configuration, process, resourceContext); + BackgroundResourceRefresher refresher = new BackgroundResourceRefresher( + configuration, process, resourceContext); refresher.startBackgroundRefresh(); - } + } } else { // wait for process to exit while (!process.isTerminated()) { @@ -116,23 +124,23 @@ public class ProgramLaunchDelegate implements ILaunchConfigurationDelegate { } catch (InterruptedException e) { } } - + // refresh resources - ExternalToolsUtil.refreshResources(configuration, resourceContext, monitor); + ExternalToolsUtil.refreshResources(configuration, resourceContext, + monitor); } - - + } - + protected static String renderCommandLine(String[] commandLine) { if (commandLine.length < 1) return ""; //$NON-NLS-1$ - StringBuffer buf= new StringBuffer(commandLine[0]); - for (int i= 1; i < commandLine.length; i++) { + StringBuffer buf = new StringBuffer(commandLine[0]); + for (int i = 1; i < commandLine.length; i++) { buf.append(' '); buf.append(commandLine[i]); - } + } return buf.toString(); - } - + } + } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/program/launchConfigurations/ProgramMainTab.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/program/launchConfigurations/ProgramMainTab.java index 6217692..b788580 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/program/launchConfigurations/ProgramMainTab.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/program/launchConfigurations/ProgramMainTab.java @@ -17,15 +17,17 @@ public class ProgramMainTab extends ExternalToolsMainTab { */ protected void handleWorkspaceLocationButtonSelected() { FileSelectionDialog dialog; - dialog = new FileSelectionDialog(getShell(), ResourcesPlugin.getWorkspace().getRoot(), "&Select a program"); + dialog = new FileSelectionDialog(getShell(), ResourcesPlugin + .getWorkspace().getRoot(), "&Select a program"); dialog.open(); IFile file = dialog.getResult(); if (file == null) { return; } StringBuffer buf = new StringBuffer(); - ToolUtil.buildVariableTag(IExternalToolConstants.VAR_WORKSPACE_LOC, file.getFullPath().toString(), buf); - String text= buf.toString(); + ToolUtil.buildVariableTag(IExternalToolConstants.VAR_WORKSPACE_LOC, + file.getFullPath().toString(), buf); + String text = buf.toString(); if (text != null) { locationField.setText(text); } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/program/launchConfigurations/ProgramTabGroup.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/program/launchConfigurations/ProgramTabGroup.java index 19d81a9..55bf044 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/program/launchConfigurations/ProgramTabGroup.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/program/launchConfigurations/ProgramTabGroup.java @@ -1,11 +1,11 @@ package net.sourceforge.phpdt.externaltools.internal.program.launchConfigurations; /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + **********************************************************************/ import net.sourceforge.phpdt.externaltools.launchConfigurations.ExternalToolsRefreshTab; @@ -17,14 +17,13 @@ import org.eclipse.debug.ui.ILaunchConfigurationTab; public class ProgramTabGroup extends AbstractLaunchConfigurationTabGroup { /** - * @see org.eclipse.debug.ui.ILaunchConfigurationTabGroup#createTabs(org.eclipse.debug.ui.ILaunchConfigurationDialog, java.lang.String) + * @see org.eclipse.debug.ui.ILaunchConfigurationTabGroup#createTabs(org.eclipse.debug.ui.ILaunchConfigurationDialog, + * java.lang.String) */ public void createTabs(ILaunchConfigurationDialog dialog, String mode) { ILaunchConfigurationTab[] tabs = new ILaunchConfigurationTab[] { - new ProgramMainTab(), - new ExternalToolsRefreshTab(), - new CommonTab() - }; + new ProgramMainTab(), new ExternalToolsRefreshTab(), + new CommonTab() }; setTabs(tabs); } } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/ArgumentVariable.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/ArgumentVariable.java index e3fc7b2..da01310 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/ArgumentVariable.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/ArgumentVariable.java @@ -1,13 +1,13 @@ package net.sourceforge.phpdt.externaltools.internal.registry; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -� -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import net.sourceforge.phpdt.externaltools.variable.ExpandVariableContext; import net.sourceforge.phpdt.externaltools.variable.IVariableTextExpander; @@ -19,23 +19,26 @@ import org.eclipse.core.runtime.IConfigurationElement; */ public final class ArgumentVariable extends ExternalToolVariable { private static final DefaultTextExpander defaultExpander = new DefaultTextExpander(); - + private IVariableTextExpander expander = null; /** * Creates an argument variable * - * @param tag the variable tag - * @param description a short description of what the variable will expand to - * @param element the configuration element + * @param tag + * the variable tag + * @param description + * a short description of what the variable will expand to + * @param element + * the configuration element */ - /*package*/ ArgumentVariable(String tag, String description, IConfigurationElement element) { + /* package */ArgumentVariable(String tag, String description, + IConfigurationElement element) { super(tag, description, element); } /** - * Returns the object that can expand the variable - * as text. + * Returns the object that can expand the variable as text. */ public IVariableTextExpander getExpander() { if (expander == null) { @@ -50,16 +53,17 @@ public final class ArgumentVariable extends ExternalToolVariable { return expander; } - /** - * Default variable text expander implementation which does - * not expand variables, but just returns null. - */ - private static final class DefaultTextExpander implements IVariableTextExpander { - /* (non-Javadoc) - * Method declared on IVariableTextExpander. + * Default variable text expander implementation which does not expand + * variables, but just returns null. + */ + private static final class DefaultTextExpander implements + IVariableTextExpander { + /* + * (non-Javadoc) Method declared on IVariableTextExpander. */ - public String getText(String varTag, String varValue, ExpandVariableContext context) { + public String getText(String varTag, String varValue, + ExpandVariableContext context) { return null; } } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/ArgumentVariableRegistry.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/ArgumentVariableRegistry.java index 5e02868..8c9a5cf 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/ArgumentVariableRegistry.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/ArgumentVariableRegistry.java @@ -1,13 +1,13 @@ package net.sourceforge.phpdt.externaltools.internal.registry; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -� -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import net.sourceforge.phpdt.externaltools.model.IExternalToolConstants; @@ -26,13 +26,13 @@ public class ArgumentVariableRegistry extends ExternalToolVariableRegistry { } /** - * Returns the argument variable for the given tag - * or null if none. + * Returns the argument variable for the given tag or null if + * none. */ public ArgumentVariable getArgumentVariable(String tag) { return (ArgumentVariable) findVariable(tag); } - + /** * Returns the list of argument variables in the registry. */ @@ -41,11 +41,12 @@ public class ArgumentVariableRegistry extends ExternalToolVariableRegistry { copyVariables(results); return results; } - - /* (non-Javadoc) - * Method declared on ExternalToolVariableRegistry. + + /* + * (non-Javadoc) Method declared on ExternalToolVariableRegistry. */ - protected ExternalToolVariable newVariable(String tag, String description, IConfigurationElement element) { + protected ExternalToolVariable newVariable(String tag, String description, + IConfigurationElement element) { return new ArgumentVariable(tag, description, element); } } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/ExternalToolMigration.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/ExternalToolMigration.java index 3ca3b59..babbcc6 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/ExternalToolMigration.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/ExternalToolMigration.java @@ -1,13 +1,13 @@ package net.sourceforge.phpdt.externaltools.internal.registry; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -� -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import java.io.File; import java.io.FileInputStream; @@ -34,70 +34,107 @@ import org.eclipse.ui.WorkbenchException; import org.eclipse.ui.XMLMemento; /** - * Responsible reading an old external tool format and creating - * and migrating it to create a new external tool. + * Responsible reading an old external tool format and creating and migrating it + * to create a new external tool. */ public final class ExternalToolMigration { private static final String SEPERATOR = ";"; //$NON-NLS-1$ + private static final String STATE_FILE_NAME_OLD = "oldexternaltools.xml"; //$NON-NLS-1$ + private static final String STATE_FILE_NAME = "externaltools.xml"; //$NON-NLS-1$ + private static final String TAG_EXTERNALTOOLS = "externaltools"; //$NON-NLS-1$ + private static final String TAG_TOOL = "tool"; //$NON-NLS-1$ + private static final String TAG_ENTRY = "entry"; //$NON-NLS-1$ - //private static final String TAG_KEY = "key"; //$NON-NLS-1$ + + // private static final String TAG_KEY = "key"; //$NON-NLS-1$ private static final String TAG_VALUE = "value"; //$NON-NLS-1$ /* * Ant tags */ - //public static final String RUN_TARGETS_ATTRIBUTE = IExternalToolConstants.TOOL_TYPE_ANT_BUILD + ".runTargets"; //$NON-NLS-1$; - + // public static final String RUN_TARGETS_ATTRIBUTE = + // IExternalToolConstants.TOOL_TYPE_ANT_BUILD + ".runTargets"; + // //$NON-NLS-1$; /* * 2.0 External Tool Tags */ private static final String TAG_TOOL_TYPE = "!{tool_type}"; //$NON-NLS-1$ + private static final String TAG_TOOL_NAME = "!{tool_name}"; //$NON-NLS-1$ + private static final String TAG_TOOL_LOCATION = "!{tool_loc}"; //$NON-NLS-1$ + private static final String TAG_TOOL_ARGUMENTS = "!{tool_args}"; //$NON-NLS-1$ + private static final String TAG_TOOL_DIRECTORY = "!{tool_dir}"; //$NON-NLS-1$ + private static final String TAG_TOOL_REFRESH = "!{tool_refresh}"; //$NON-NLS-1$ + private static final String TAG_TOOL_SHOW_LOG = "!{tool_show_log}"; //$NON-NLS-1$ + private static final String TAG_TOOL_BUILD_TYPES = "!{tool_build_types}"; //$NON-NLS-1$ + private static final String TAG_TOOL_BLOCK = "!{tool_block}"; //$NON-NLS-1$ // Known kind of tools private static final String TOOL_TYPE_PROGRAM = "net.sourceforge.phpdt.externaltools.type.program"; //$NON-NLS-1$ - //private static final String TOOL_TYPE_ANT = "org.eclipse.ui.externaltools.type.ant"; //$NON-NLS-1$ + + // private static final String TOOL_TYPE_ANT = + // "org.eclipse.ui.externaltools.type.ant"; //$NON-NLS-1$ /* * 2.1 External Tool Keys */ private static final String TAG_EXTERNAL_TOOL = "externalTool"; //$NON-NLS-1$ + private static final String TAG_TYPE = "type"; //$NON-NLS-1$ + private static final String TAG_NAME = "name"; //$NON-NLS-1$ + private static final String TAG_LOCATION = "location"; //$NON-NLS-1$ + private static final String TAG_WORK_DIR = "workDirectory"; //$NON-NLS-1$ + private static final String TAG_CAPTURE_OUTPUT = "captureOutput"; //$NON-NLS-1$ + private static final String TAG_SHOW_CONSOLE = "showConsole"; //$NON-NLS-1$ + private static final String TAG_RUN_BKGRND = "runInBackground"; //$NON-NLS-1$ + private static final String TAG_OPEN_PERSP = "openPerspective"; //$NON-NLS-1$ + private static final String TAG_PROMPT_ARGS = "promptForArguments"; //$NON-NLS-1$ + private static final String TAG_SHOW_MENU = "showInMenu"; //$NON-NLS-1$ + private static final String TAG_SAVE_DIRTY = "saveDirtyEditors"; //$NON-NLS-1$ + private static final String TAG_ARGS = "arguments"; //$NON-NLS-1$ + private static final String TAG_REFRESH_SCOPE = "refreshScope"; //$NON-NLS-1$ + private static final String TAG_REFRESH_RECURSIVE = "refreshRecursive"; //$NON-NLS-1$ + private static final String TAG_RUN_BUILD_KINDS = "runForBuildKinds"; //$NON-NLS-1$ + private static final String TAG_EXTRA_ATTR = "extraAttribute"; //$NON-NLS-1$ + private static final String TAG_KEY = "key"; //$NON-NLS-1$ + private static final String TAG_VERSION = "version"; //$NON-NLS-1$ private static final String BUILD_TYPE_SEPARATOR = ","; //$NON-NLS-1$ + private static final String EXTRA_ATTR_SEPARATOR = "="; //$NON-NLS-1$ private static final String VERSION_21 = "2.1"; //$NON-NLS-1$; private static final String TRUE = "true"; //$NON-NLS-1$ + private static final String FALSE = "false"; //$NON-NLS-1$ /** @@ -108,11 +145,10 @@ public final class ExternalToolMigration { } /** - * Loads the external tools from storage and - * adds them to the registry. + * Loads the external tools from storage and adds them to the registry. */ - /*package*/ - // This method is not called. It is left here in case + /* package */ + // This method is not called. It is left here in case // we decide to do tool migration in the future private static void readInOldTools() { readIn20Tools(); @@ -159,35 +195,44 @@ public final class ExternalToolMigration { } catch (FileNotFoundException e) { // Silently ignore this... } catch (IOException e) { - ExternalToolsPlugin.getDefault().log("File I/O error with reading old external tools.", e); + ExternalToolsPlugin.getDefault().log( + "File I/O error with reading old external tools.", e); migrationSuccessful = false; } catch (WorkbenchException e) { - ExternalToolsPlugin.getDefault().getLog().log(e.getStatus()); - System.err.println("Error reading old external tools. See .log file for more details"); + ExternalToolsPlugin.getDefault().getLog().log(e.getStatus()); + System.err + .println("Error reading old external tools. See .log file for more details"); migrationSuccessful = false; } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { - ExternalToolsPlugin.getDefault().log("Unable to close external tool old state reader.", e); + ExternalToolsPlugin.getDefault().log( + "Unable to close external tool old state reader.", + e); } } } if (migrationSuccessful) { if (!file.renameTo(path.append(STATE_FILE_NAME_OLD).toFile())) { - ExternalToolsPlugin.getDefault().log("Unable to rename old external tool state file. Please rename externaltools.xml to oldexternaltools.xml manually.", null); - System.err.println("Unable to rename old external tool state file. Please rename externaltools.xml to oldexternaltools.xml manually."); + ExternalToolsPlugin + .getDefault() + .log( + "Unable to rename old external tool state file. Please rename externaltools.xml to oldexternaltools.xml manually.", + null); + System.err + .println("Unable to rename old external tool state file. Please rename externaltools.xml to oldexternaltools.xml manually."); } } } /** - * Returns a launch configuration working copy from the argument map or - * null if the given map cannot be interpreted as a 2.0 or 2.1 - * branch external tool. The returned working copy will be unsaved and its - * location will be set to the metadata area. + * Returns a launch configuration working copy from the argument map or + * null if the given map cannot be interpreted as a 2.0 or + * 2.1 branch external tool. The returned working copy will be unsaved and + * its location will be set to the metadata area. */ public static ILaunchConfigurationWorkingCopy configFromArgumentMap(Map args) { String version = (String) args.get(TAG_VERSION); @@ -197,43 +242,56 @@ public final class ExternalToolMigration { return configFrom20ArgumentMap(args); } - public static ILaunchConfigurationWorkingCopy configFrom21ArgumentMap(Map commandArgs) { + public static ILaunchConfigurationWorkingCopy configFrom21ArgumentMap( + Map commandArgs) { String name = (String) commandArgs.get(TAG_NAME); String type = (String) commandArgs.get(TAG_TYPE); - + ILaunchConfigurationWorkingCopy config = newConfig(type, name); if (config == null) { return null; } - - config.setAttribute(IExternalToolConstants.ATTR_LOCATION, (String) commandArgs.get(TAG_LOCATION)); - config.setAttribute(IExternalToolConstants.ATTR_WORKING_DIRECTORY, (String) commandArgs.get(TAG_WORK_DIR)); - config.setAttribute(IExternalToolConstants.ATTR_CAPTURE_OUTPUT, TRUE.equals((String) commandArgs.get(TAG_CAPTURE_OUTPUT))); - config.setAttribute(IExternalToolConstants.ATTR_SHOW_CONSOLE, TRUE.equals((String) commandArgs.get(TAG_SHOW_CONSOLE))); - config.setAttribute(IExternalToolConstants.ATTR_RUN_IN_BACKGROUND, TRUE.equals((String) commandArgs.get(TAG_RUN_BKGRND))); - config.setAttribute(IExternalToolConstants.ATTR_PROMPT_FOR_ARGUMENTS, TRUE.equals((String) commandArgs.get(TAG_PROMPT_ARGS))); - config.setAttribute(IExternalToolConstants.ATTR_REFRESH_SCOPE, (String) commandArgs.get(TAG_REFRESH_SCOPE)); - config.setAttribute(IExternalToolConstants.ATTR_REFRESH_RECURSIVE, TRUE.equals((String) commandArgs.get(TAG_REFRESH_RECURSIVE))); - - config.setAttribute(IExternalToolConstants.ATTR_RUN_BUILD_KINDS, (String) commandArgs.get(TAG_RUN_BUILD_KINDS)); - + + config.setAttribute(IExternalToolConstants.ATTR_LOCATION, + (String) commandArgs.get(TAG_LOCATION)); + config.setAttribute(IExternalToolConstants.ATTR_WORKING_DIRECTORY, + (String) commandArgs.get(TAG_WORK_DIR)); + config.setAttribute(IExternalToolConstants.ATTR_CAPTURE_OUTPUT, TRUE + .equals((String) commandArgs.get(TAG_CAPTURE_OUTPUT))); + config.setAttribute(IExternalToolConstants.ATTR_SHOW_CONSOLE, TRUE + .equals((String) commandArgs.get(TAG_SHOW_CONSOLE))); + config.setAttribute(IExternalToolConstants.ATTR_RUN_IN_BACKGROUND, TRUE + .equals((String) commandArgs.get(TAG_RUN_BKGRND))); + config.setAttribute(IExternalToolConstants.ATTR_PROMPT_FOR_ARGUMENTS, + TRUE.equals((String) commandArgs.get(TAG_PROMPT_ARGS))); + config.setAttribute(IExternalToolConstants.ATTR_REFRESH_SCOPE, + (String) commandArgs.get(TAG_REFRESH_SCOPE)); + config.setAttribute(IExternalToolConstants.ATTR_REFRESH_RECURSIVE, TRUE + .equals((String) commandArgs.get(TAG_REFRESH_RECURSIVE))); + + config.setAttribute(IExternalToolConstants.ATTR_RUN_BUILD_KINDS, + (String) commandArgs.get(TAG_RUN_BUILD_KINDS)); + String args = (String) commandArgs.get(TAG_ARGS); if (args != null) { - config.setAttribute(IExternalToolConstants.ATTR_TOOL_ARGUMENTS, args); + config.setAttribute(IExternalToolConstants.ATTR_TOOL_ARGUMENTS, + args); } String extraAttributes = (String) commandArgs.get(TAG_EXTRA_ATTR); if (extraAttributes != null) { - StringTokenizer tokenizer = new StringTokenizer(extraAttributes, EXTRA_ATTR_SEPARATOR); + StringTokenizer tokenizer = new StringTokenizer(extraAttributes, + EXTRA_ATTR_SEPARATOR); while (tokenizer.hasMoreTokens()) { String key = tokenizer.nextToken(); if (!tokenizer.hasMoreTokens()) break; String value = tokenizer.nextToken(); -// if (key.equals(RUN_TARGETS_ATTRIBUTE)) { -// // 2.1 implementation only defined 1 "extra attribute" -// config.setAttribute(IExternalToolConstants.ATTR_ANT_TARGETS, value); -// } + // if (key.equals(RUN_TARGETS_ATTRIBUTE)) { + // // 2.1 implementation only defined 1 "extra attribute" + // config.setAttribute(IExternalToolConstants.ATTR_ANT_TARGETS, + // value); + // } } } return config; @@ -242,16 +300,17 @@ public final class ExternalToolMigration { /** * Creates an external tool from the map. */ - public static ILaunchConfigurationWorkingCopy configFrom20ArgumentMap(Map args) { + public static ILaunchConfigurationWorkingCopy configFrom20ArgumentMap( + Map args) { // Update the type... String type = (String) args.get(TAG_TOOL_TYPE); -// if (TOOL_TYPE_ANT.equals(type)) -// type = IExternalToolConstants.TOOL_TYPE_ANT_BUILD; -// else - type = IExternalToolConstants.TOOL_TYPE_PROGRAM; + // if (TOOL_TYPE_ANT.equals(type)) + // type = IExternalToolConstants.TOOL_TYPE_ANT_BUILD; + // else + type = IExternalToolConstants.TOOL_TYPE_PROGRAM; String name = (String) args.get(TAG_TOOL_NAME); - + ILaunchConfigurationWorkingCopy config = newConfig(type, name); if (config == null) { return null; @@ -260,9 +319,12 @@ public final class ExternalToolMigration { // Update the location... String location = (String) args.get(TAG_TOOL_LOCATION); if (location != null) { - ToolUtil.VariableDefinition varDef = ToolUtil.extractVariableTag(location, 0); + ToolUtil.VariableDefinition varDef = ToolUtil.extractVariableTag( + location, 0); if (IExternalToolConstants.VAR_WORKSPACE_LOC.equals(varDef.name)) { - location = ToolUtil.buildVariableTag(IExternalToolConstants.VAR_RESOURCE_LOC, varDef.argument); + location = ToolUtil.buildVariableTag( + IExternalToolConstants.VAR_RESOURCE_LOC, + varDef.argument); } config.setAttribute(IExternalToolConstants.ATTR_LOCATION, location); } @@ -270,11 +332,13 @@ public final class ExternalToolMigration { // Update the refresh scope... String refresh = (String) args.get(TAG_TOOL_REFRESH); if (refresh != null) { - ToolUtil.VariableDefinition varDef = ToolUtil.extractVariableTag(refresh, 0); + ToolUtil.VariableDefinition varDef = ToolUtil.extractVariableTag( + refresh, 0); if ("none".equals(varDef.name)) { //$NON-NLS-1$ refresh = null; } - config.setAttribute(IExternalToolConstants.ATTR_REFRESH_SCOPE, refresh); + config.setAttribute(IExternalToolConstants.ATTR_REFRESH_SCOPE, + refresh); } // Update the arguments @@ -284,7 +348,8 @@ public final class ExternalToolMigration { int start = 0; ArrayList targets = new ArrayList(); StringBuffer buffer = new StringBuffer(); - ToolUtil.VariableDefinition varDef = ToolUtil.extractVariableTag(arguments, start); + ToolUtil.VariableDefinition varDef = ToolUtil.extractVariableTag( + arguments, start); while (varDef.end != -1) { if ("ant_target".equals(varDef.name) && varDef.argument != null) { //$NON-NLS-1$ targets.add(varDef.argument); @@ -309,16 +374,23 @@ public final class ExternalToolMigration { targetNames = buffer.toString(); } if (targetNames != null && targetNames.length() > 0) { - config.setAttribute(IExternalToolConstants.ATTR_ANT_TARGETS, targetNames); + config.setAttribute(IExternalToolConstants.ATTR_ANT_TARGETS, + targetNames); } // Collect the rest of the information - config.setAttribute(IExternalToolConstants.ATTR_SHOW_CONSOLE, TRUE.equals((String) args.get(TAG_TOOL_SHOW_LOG))); - config.setAttribute(IExternalToolConstants.ATTR_CAPTURE_OUTPUT, TRUE.equals((String) args.get(TAG_TOOL_SHOW_LOG))); - config.setAttribute(IExternalToolConstants.ATTR_RUN_IN_BACKGROUND, FALSE.equals((String) args.get(TAG_TOOL_BLOCK))); - config.setAttribute(IExternalToolConstants.ATTR_RUN_BUILD_KINDS, (String) args.get(TAG_TOOL_BUILD_TYPES)); - config.setAttribute(IExternalToolConstants.ATTR_TOOL_ARGUMENTS, arguments); - config.setAttribute(IExternalToolConstants.ATTR_WORKING_DIRECTORY, (String) args.get(TAG_TOOL_DIRECTORY)); + config.setAttribute(IExternalToolConstants.ATTR_SHOW_CONSOLE, TRUE + .equals((String) args.get(TAG_TOOL_SHOW_LOG))); + config.setAttribute(IExternalToolConstants.ATTR_CAPTURE_OUTPUT, TRUE + .equals((String) args.get(TAG_TOOL_SHOW_LOG))); + config.setAttribute(IExternalToolConstants.ATTR_RUN_IN_BACKGROUND, + FALSE.equals((String) args.get(TAG_TOOL_BLOCK))); + config.setAttribute(IExternalToolConstants.ATTR_RUN_BUILD_KINDS, + (String) args.get(TAG_TOOL_BUILD_TYPES)); + config.setAttribute(IExternalToolConstants.ATTR_TOOL_ARGUMENTS, + arguments); + config.setAttribute(IExternalToolConstants.ATTR_WORKING_DIRECTORY, + (String) args.get(TAG_TOOL_DIRECTORY)); return config; } @@ -326,17 +398,20 @@ public final class ExternalToolMigration { * Returns a new working copy with the given external tool name and external * tool type or null if no config could be created. */ - private static ILaunchConfigurationWorkingCopy newConfig(String type, String name) { + private static ILaunchConfigurationWorkingCopy newConfig(String type, + String name) { if (type == null || name == null) { return null; } ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager(); ILaunchConfigurationType configType; -// if (IExternalToolConstants.TOOL_TYPE_ANT_BUILD.equals(type)) { -// configType = manager.getLaunchConfigurationType(IExternalToolConstants.ID_ANT_BUILDER_LAUNCH_CONFIGURATION_TYPE); -// } else + // if (IExternalToolConstants.TOOL_TYPE_ANT_BUILD.equals(type)) { + // configType = + // manager.getLaunchConfigurationType(IExternalToolConstants.ID_ANT_BUILDER_LAUNCH_CONFIGURATION_TYPE); + // } else if (IExternalToolConstants.TOOL_TYPE_PROGRAM.equals(type)) { - configType = manager.getLaunchConfigurationType(IExternalToolConstants.ID_PROGRAM_BUILDER_LAUNCH_CONFIGURATION_TYPE); + configType = manager + .getLaunchConfigurationType(IExternalToolConstants.ID_PROGRAM_BUILDER_LAUNCH_CONFIGURATION_TYPE); } else { return null; } @@ -346,17 +421,17 @@ public final class ExternalToolMigration { return null; } } - + /** * Returns the tool name extracted from the given command argument map. * Extraction is attempted using 2.0 and 2.1 external tool formats. */ public static String getNameFromCommandArgs(Map commandArgs) { - String name= (String) commandArgs.get(TAG_NAME); + String name = (String) commandArgs.get(TAG_NAME); if (name == null) { - name= (String) commandArgs.get(TAG_TOOL_NAME); + name = (String) commandArgs.get(TAG_TOOL_NAME); } return name; } - + } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/ExternalToolVariable.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/ExternalToolVariable.java index ea4a706..c0416e6 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/ExternalToolVariable.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/ExternalToolVariable.java @@ -1,13 +1,13 @@ package net.sourceforge.phpdt.externaltools.internal.registry; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -� -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import net.sourceforge.phpdt.externaltools.group.IGroupDialogPage; import net.sourceforge.phpdt.externaltools.internal.model.ExternalToolsModelMessages; @@ -27,57 +27,64 @@ import org.eclipse.swt.widgets.Label; * Abtract representation of the different variables. */ public abstract class ExternalToolVariable { - private static final IVariableComponent defaultComponent = new DefaultVariableComponent(false); - + private static final IVariableComponent defaultComponent = new DefaultVariableComponent( + false); + private String tag; + private String description; + private IConfigurationElement element; /** * Creates an variable definition * - * @param tag the variable tag - * @param description a short description of what the variable will expand to - * @param element the configuration element + * @param tag + * the variable tag + * @param description + * a short description of what the variable will expand to + * @param element + * the configuration element */ - /*package*/ ExternalToolVariable(String tag, String description, IConfigurationElement element) { + /* package */ExternalToolVariable(String tag, String description, + IConfigurationElement element) { super(); this.tag = tag; this.description = description; this.element = element; } - + /** - * Creates an instance of the class specified by - * the given element attribute name. Can return - * null if none or if problems creating - * the instance. + * Creates an instance of the class specified by the given element attribute + * name. Can return null if none or if problems creating the + * instance. */ protected final Object createObject(String attributeName) { try { return element.createExecutableExtension(attributeName); } catch (CoreException e) { - ExternalToolsPlugin.getDefault().getLog().log(e.getStatus()); + ExternalToolsPlugin.getDefault().getLog().log(e.getStatus()); return null; } } - + /** - * Returns the component class to allow - * visual editing of the variable's value. + * Returns the component class to allow visual editing of the variable's + * value. */ public final IVariableComponent getComponent() { - String className = element.getAttribute(ExternalToolVariableRegistry.TAG_COMPONENT_CLASS); + String className = element + .getAttribute(ExternalToolVariableRegistry.TAG_COMPONENT_CLASS); if (className == null || className.trim().length() == 0) return defaultComponent; - + Object component = createObject(ExternalToolVariableRegistry.TAG_COMPONENT_CLASS); if (component == null) return new DefaultVariableComponent(true); else - return (IVariableComponent)component; + return (IVariableComponent) component; } - + /** * Returns the variable's description */ @@ -92,63 +99,68 @@ public abstract class ExternalToolVariable { return tag; } - /** - * Default variable component implementation which does not - * allow variable value editing visually. - */ - private static final class DefaultVariableComponent implements IVariableComponent { + * Default variable component implementation which does not allow variable + * value editing visually. + */ + private static final class DefaultVariableComponent implements + IVariableComponent { private boolean showError = false; + private Label message = null; - + public DefaultVariableComponent(boolean showError) { super(); this.showError = showError; } - - /* (non-Javadoc) - * Method declared on IVariableComponent. + + /* + * (non-Javadoc) Method declared on IVariableComponent. */ public Control getControl() { return message; } - - /* (non-Javadoc) - * Method declared on IVariableComponent. + + /* + * (non-Javadoc) Method declared on IVariableComponent. */ - public void createContents(Composite parent, String varTag, IGroupDialogPage page) { + public void createContents(Composite parent, String varTag, + IGroupDialogPage page) { if (showError) { message = new Label(parent, SWT.NONE); GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); message.setLayoutData(data); message.setFont(parent.getFont()); - message.setText(ExternalToolsModelMessages.getString("ExternalToolVariable.componentErrorMessage")); //$NON-NLS-1$ - message.setForeground(JFaceColors.getErrorText(message.getDisplay())); + message + .setText(ExternalToolsModelMessages + .getString("ExternalToolVariable.componentErrorMessage")); //$NON-NLS-1$ + message.setForeground(JFaceColors.getErrorText(message + .getDisplay())); } } - - /* (non-Javadoc) - * Method declared on IVariableComponent. + + /* + * (non-Javadoc) Method declared on IVariableComponent. */ public String getVariableValue() { return null; } - - /* (non-Javadoc) - * Method declared on IVariableComponent. + + /* + * (non-Javadoc) Method declared on IVariableComponent. */ public boolean isValid() { return true; } - - /* (non-Javadoc) - * Method declared on IVariableComponent. + + /* + * (non-Javadoc) Method declared on IVariableComponent. */ public void setVariableValue(String varValue) { } - /* (non-Javadoc) - * Method declared on IVariableComponent. + /* + * (non-Javadoc) Method declared on IVariableComponent. */ public void validate() { } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/ExternalToolVariableRegistry.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/ExternalToolVariableRegistry.java index d1b6b90..09b94b4 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/ExternalToolVariableRegistry.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/ExternalToolVariableRegistry.java @@ -1,13 +1,13 @@ package net.sourceforge.phpdt.externaltools.internal.registry; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -� -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import java.util.HashMap; @@ -26,47 +26,48 @@ import org.eclipse.core.runtime.Platform; public abstract class ExternalToolVariableRegistry { // Format of the variable extension points // null if none found. + * Returns the variable for the specified tag, or null if + * none found. */ protected final ExternalToolVariable findVariable(String tag) { return (ExternalToolVariable) variables.get(tag); @@ -88,50 +89,65 @@ public abstract class ExternalToolVariableRegistry { public final int getVariableCount() { return variables.size(); } - + /** * Load the available variables */ private void loadVariables() { variables = new HashMap(); - IExtensionRegistry registry= Platform.getExtensionRegistry(); -// IPluginRegistry registry = Platform.getPluginRegistry(); - IExtensionPoint point = registry.getExtensionPoint(IExternalToolConstants.PLUGIN_ID, extensionPointId); + IExtensionRegistry registry = Platform.getExtensionRegistry(); + // IPluginRegistry registry = Platform.getPluginRegistry(); + IExtensionPoint point = registry.getExtensionPoint( + IExternalToolConstants.PLUGIN_ID, extensionPointId); if (point != null) { IExtension[] extensions = point.getExtensions(); for (int i = 0; i < extensions.length; i++) { - IConfigurationElement[] elements = extensions[i].getConfigurationElements(); + IConfigurationElement[] elements = extensions[i] + .getConfigurationElements(); for (int j = 0; j < elements.length; j++) { IConfigurationElement element = elements[j]; if (element.getName().equals(TAG_VARIABLE)) { String tag = element.getAttribute(TAG_TAG); - String description = element.getAttribute(TAG_DESCRIPTION); - String className = element.getAttribute(TAG_EXPANDER_CLASS); - + String description = element + .getAttribute(TAG_DESCRIPTION); + String className = element + .getAttribute(TAG_EXPANDER_CLASS); + boolean valid = true; if (tag == null || tag.length() == 0) { valid = false; - ExternalToolsPlugin.getDefault().log("Missing tag attribute value for variable element.", null); //$NON-NLS-1$ + ExternalToolsPlugin + .getDefault() + .log( + "Missing tag attribute value for variable element.", null); //$NON-NLS-1$ } if (description == null || description.length() == 0) { valid = false; - ExternalToolsPlugin.getDefault().log("Missing description attribute value for variable element.", null); //$NON-NLS-1$ + ExternalToolsPlugin + .getDefault() + .log( + "Missing description attribute value for variable element.", null); //$NON-NLS-1$ } if (className == null || className.length() == 0) { valid = false; - ExternalToolsPlugin.getDefault().log("Missing expander class attribute value for variable element.", null); //$NON-NLS-1$ + ExternalToolsPlugin + .getDefault() + .log( + "Missing expander class attribute value for variable element.", null); //$NON-NLS-1$ } if (valid) - variables.put(tag, newVariable(tag, description, element)); + variables.put(tag, newVariable(tag, description, + element)); } } } } } - + /** * Creates a new variable from the specified information. */ - protected abstract ExternalToolVariable newVariable(String tag, String description, IConfigurationElement element); + protected abstract ExternalToolVariable newVariable(String tag, + String description, IConfigurationElement element); } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/PathLocationVariable.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/PathLocationVariable.java index 4385da3..004cf8c 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/PathLocationVariable.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/PathLocationVariable.java @@ -1,13 +1,13 @@ package net.sourceforge.phpdt.externaltools.internal.registry; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -� -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import net.sourceforge.phpdt.externaltools.variable.ExpandVariableContext; import net.sourceforge.phpdt.externaltools.variable.IVariableLocationExpander; @@ -20,23 +20,26 @@ import org.eclipse.core.runtime.IPath; */ public final class PathLocationVariable extends ExternalToolVariable { private static final DefaultLocationExpander defaultExpander = new DefaultLocationExpander(); - + private IVariableLocationExpander expander = null; /** * Creates a path location variable * - * @param tag the variable tag - * @param description a short description of what the variable will expand to - * @param element the configuration element + * @param tag + * the variable tag + * @param description + * a short description of what the variable will expand to + * @param element + * the configuration element */ - /*package*/ PathLocationVariable(String tag, String description, IConfigurationElement element) { + /* package */PathLocationVariable(String tag, String description, + IConfigurationElement element) { super(tag, description, element); } /** - * Returns the object that can expand the variable - * into a path location. + * Returns the object that can expand the variable into a path location. */ public IVariableLocationExpander getExpander() { if (expander == null) { @@ -47,16 +50,17 @@ public final class PathLocationVariable extends ExternalToolVariable { return expander; } - /** - * Default variable location implementation which does - * not expand variables, but just returns null. - */ - private static final class DefaultLocationExpander implements IVariableLocationExpander { - /* (non-Javadoc) - * Method declared on IVariableLocationExpander. + * Default variable location implementation which does not expand variables, + * but just returns null. + */ + private static final class DefaultLocationExpander implements + IVariableLocationExpander { + /* + * (non-Javadoc) Method declared on IVariableLocationExpander. */ - public IPath getPath(String varTag, String varValue, ExpandVariableContext context) { + public IPath getPath(String varTag, String varValue, + ExpandVariableContext context) { return null; } } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/PathLocationVariableRegistry.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/PathLocationVariableRegistry.java index 1a2fa3e..70fc909 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/PathLocationVariableRegistry.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/PathLocationVariableRegistry.java @@ -1,13 +1,13 @@ package net.sourceforge.phpdt.externaltools.internal.registry; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -� -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import org.eclipse.core.runtime.IConfigurationElement; @@ -24,13 +24,13 @@ public class PathLocationVariableRegistry extends ExternalToolVariableRegistry { } /** - * Returns the path location variable for the given tag - * or null if none. + * Returns the path location variable for the given tag or null + * if none. */ public PathLocationVariable getPathLocationVariable(String tag) { return (PathLocationVariable) findVariable(tag); } - + /** * Returns the list of path location variables in the registry. */ @@ -39,11 +39,12 @@ public class PathLocationVariableRegistry extends ExternalToolVariableRegistry { copyVariables(results); return results; } - - /* (non-Javadoc) - * Method declared on ExternalToolVariableRegistry. + + /* + * (non-Javadoc) Method declared on ExternalToolVariableRegistry. */ - protected ExternalToolVariable newVariable(String tag, String description, IConfigurationElement element) { + protected ExternalToolVariable newVariable(String tag, String description, + IConfigurationElement element) { return new PathLocationVariable(tag, description, element); } } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/RefreshScopeVariable.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/RefreshScopeVariable.java index ea634ec..14f2866 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/RefreshScopeVariable.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/RefreshScopeVariable.java @@ -1,13 +1,13 @@ package net.sourceforge.phpdt.externaltools.internal.registry; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -� -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import net.sourceforge.phpdt.externaltools.variable.ExpandVariableContext; import net.sourceforge.phpdt.externaltools.variable.IVariableResourceExpander; @@ -20,23 +20,26 @@ import org.eclipse.core.runtime.IConfigurationElement; */ public final class RefreshScopeVariable extends ExternalToolVariable { private static final DefaultResourceExpander defaultExpander = new DefaultResourceExpander(); - + private IVariableResourceExpander expander = null; /** * Creates a refresh scope variable * - * @param tag the variable tag - * @param description a short description of what the variable will expand to - * @param element the configuration element + * @param tag + * the variable tag + * @param description + * a short description of what the variable will expand to + * @param element + * the configuration element */ - /*package*/ RefreshScopeVariable(String tag, String description, IConfigurationElement element) { + /* package */RefreshScopeVariable(String tag, String description, + IConfigurationElement element) { super(tag, description, element); } /** - * Returns the object that can expand the variable - * as resources. + * Returns the object that can expand the variable as resources. */ public IVariableResourceExpander getExpander() { if (expander == null) { @@ -47,16 +50,17 @@ public final class RefreshScopeVariable extends ExternalToolVariable { return expander; } - /** - * Default variable resource expander implementation which does - * not expand variables, but just returns null. - */ - private static final class DefaultResourceExpander implements IVariableResourceExpander { - /* (non-Javadoc) - * Method declared on IVariableResourceExpander. + * Default variable resource expander implementation which does not expand + * variables, but just returns null. + */ + private static final class DefaultResourceExpander implements + IVariableResourceExpander { + /* + * (non-Javadoc) Method declared on IVariableResourceExpander. */ - public IResource[] getResources(String varTag, String varValue, ExpandVariableContext context) { + public IResource[] getResources(String varTag, String varValue, + ExpandVariableContext context) { return null; } } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/RefreshScopeVariableRegistry.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/RefreshScopeVariableRegistry.java index d0b3d99..5c8f437 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/RefreshScopeVariableRegistry.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/registry/RefreshScopeVariableRegistry.java @@ -1,13 +1,13 @@ package net.sourceforge.phpdt.externaltools.internal.registry; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -� -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import net.sourceforge.phpdt.externaltools.model.IExternalToolConstants; @@ -26,13 +26,13 @@ public class RefreshScopeVariableRegistry extends ExternalToolVariableRegistry { } /** - * Returns the refresh scope variable for the given tag - * or null if none. + * Returns the refresh scope variable for the given tag or null + * if none. */ public RefreshScopeVariable getRefreshVariable(String tag) { return (RefreshScopeVariable) findVariable(tag); } - + /** * Returns the list of refresh scope variables in the registry. */ @@ -41,11 +41,12 @@ public class RefreshScopeVariableRegistry extends ExternalToolVariableRegistry { copyVariables(results); return results; } - - /* (non-Javadoc) - * Method declared on ExternalToolVariableRegistry. + + /* + * (non-Javadoc) Method declared on ExternalToolVariableRegistry. */ - protected ExternalToolVariable newVariable(String tag, String description, IConfigurationElement element) { + protected ExternalToolVariable newVariable(String tag, String description, + IConfigurationElement element) { return new RefreshScopeVariable(tag, description, element); } } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/ExternalToolsContentProvider.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/ExternalToolsContentProvider.java index 1227293..5c0083e 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/ExternalToolsContentProvider.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/ExternalToolsContentProvider.java @@ -1,11 +1,11 @@ package net.sourceforge.phpdt.externaltools.internal.ui; /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + **********************************************************************/ import java.util.ArrayList; import java.util.Arrays; @@ -22,6 +22,7 @@ import org.eclipse.jface.viewers.Viewer; */ public class ExternalToolsContentProvider implements IStructuredContentProvider { protected List elements = new ArrayList(); + protected TableViewer viewer; public void add(Object o) { @@ -55,9 +56,9 @@ public class ExternalToolsContentProvider implements IStructuredContentProvider elements.remove(o); viewer.remove(o); } - + public void remove(IStructuredSelection selection) { - Object[] array= selection.toArray(); + Object[] array = selection.toArray(); elements.removeAll(Arrays.asList(array)); viewer.remove(array); } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/FileSelectionDialog.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/FileSelectionDialog.java index 01f95f9..26f7b68 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/FileSelectionDialog.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/FileSelectionDialog.java @@ -26,185 +26,210 @@ import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; /** - * Dialog for selecting a file in the workspace. Derived from + * Dialog for selecting a file in the workspace. Derived from * org.eclipse.ui.dialogs.ResourceSelectionDialog */ public class FileSelectionDialog extends MessageDialog { // the root element to populate the viewer with - private IAdaptable root; + private IAdaptable root; // the visual selection widget group - private TreeAndListGroup selectionGroup; + private TreeAndListGroup selectionGroup; + // constants - private final static int SIZING_SELECTION_WIDGET_WIDTH = 400; - private final static int SIZING_SELECTION_WIDGET_HEIGHT = 300; + private final static int SIZING_SELECTION_WIDGET_WIDTH = 400; + + private final static int SIZING_SELECTION_WIDGET_HEIGHT = 300; + /** * The file selected by the user. */ - private IFile result= null; + private IFile result = null; + /** * String matcher used to filter content */ - private StringMatcher stringMatcher= null; -/** - * Creates a resource selection dialog rooted at the given element. - * - * @param parentShell the parent shell - * @param rootElement the root element to populate this dialog with - * @param message the message to be displayed at the top of this dialog, or - * null to display a default message - */ -public FileSelectionDialog(Shell parentShell, IAdaptable rootElement, String message) { - super(parentShell, "Add Build File", null, message, MessageDialog.NONE, new String[] {"Ok", "Cancel"}, 0); - root = rootElement; - setShellStyle(getShellStyle() | SWT.RESIZE); -} -/** - * Limits the files displayed in this dialog to files matching the given - * pattern. The string can be a filename or a regular expression containing - * '*' for any series of characters or '?' for any single character. - * - * @param pattern a pattern used to filter the displayed files or - * null to display all files. If a pattern is supplied, only files - * whose names match the given pattern will be available for selection. - * @param ignoreCase if true, case is ignored. If the pattern argument is - * null, this argument is ignored. - */ -public void setFileFilter(String pattern, boolean ignoreCase) { - if (pattern != null) { - stringMatcher= new StringMatcher(pattern, ignoreCase, false); - } else { - stringMatcher= null; + private StringMatcher stringMatcher = null; + + /** + * Creates a resource selection dialog rooted at the given element. + * + * @param parentShell + * the parent shell + * @param rootElement + * the root element to populate this dialog with + * @param message + * the message to be displayed at the top of this dialog, or + * null to display a default message + */ + public FileSelectionDialog(Shell parentShell, IAdaptable rootElement, + String message) { + super(parentShell, "Add Build File", null, message, MessageDialog.NONE, + new String[] { "Ok", "Cancel" }, 0); + root = rootElement; + setShellStyle(getShellStyle() | SWT.RESIZE); } -} -/* (non-Javadoc) - * Method declared in Window. - */ -protected void configureShell(Shell shell) { - super.configureShell(shell); - //WorkbenchHelp.setHelp(shell, IHelpContextIds.RESOURCE_SELECTION_DIALOG); -} -protected void createButtonsForButtonBar(Composite parent) { - super.createButtonsForButtonBar(parent); - initializeDialog(); -} -/* (non-Javadoc) - * Method declared on Dialog. - */ -protected Control createDialogArea(Composite parent) { - // page group - Composite composite = (Composite) super.createDialogArea(parent); - - //create the input element, which has the root resource - //as its only child - - selectionGroup = - new TreeAndListGroup( - composite, - root, - getResourceProvider(IResource.FOLDER | IResource.PROJECT | IResource.ROOT), - new WorkbenchLabelProvider(), - getResourceProvider(IResource.FILE), - new WorkbenchLabelProvider(), - SWT.NONE, - // since this page has no other significantly-sized - // widgets we need to hardcode the combined widget's - // size, otherwise it will open too small - SIZING_SELECTION_WIDGET_WIDTH, - SIZING_SELECTION_WIDGET_HEIGHT); - - composite.addControlListener(new ControlListener() { - public void controlMoved(ControlEvent e) {}; - public void controlResized(ControlEvent e) { - //Also try and reset the size of the columns as appropriate - TableColumn[] columns = selectionGroup.getListTable().getColumns(); - for (int i = 0; i < columns.length; i++) { - columns[i].pack(); - } + /** + * Limits the files displayed in this dialog to files matching the given + * pattern. The string can be a filename or a regular expression containing + * '*' for any series of characters or '?' for any single character. + * + * @param pattern + * a pattern used to filter the displayed files or + * null to display all files. If a pattern is + * supplied, only files whose names match the given pattern will + * be available for selection. + * @param ignoreCase + * if true, case is ignored. If the pattern argument is + * null, this argument is ignored. + */ + public void setFileFilter(String pattern, boolean ignoreCase) { + if (pattern != null) { + stringMatcher = new StringMatcher(pattern, ignoreCase, false); + } else { + stringMatcher = null; } - }); + } - return composite; -} -/** - * Returns a content provider for IResources that returns - * only children of the given resource type. - */ -private ITreeContentProvider getResourceProvider(final int resourceType) { - return new WorkbenchContentProvider() { - public Object[] getChildren(Object o) { - if (o instanceof IContainer) { - IResource[] members = null; - try { - members = ((IContainer)o).members(); - List accessibleMembers= new ArrayList(members.length); - for (int i = 0; i < members.length; i++) { - IResource resource = members[i]; - if (resource.isAccessible()) { - accessibleMembers.add(resource); + /* + * (non-Javadoc) Method declared in Window. + */ + protected void configureShell(Shell shell) { + super.configureShell(shell); + // WorkbenchHelp.setHelp(shell, + // IHelpContextIds.RESOURCE_SELECTION_DIALOG); + } + + protected void createButtonsForButtonBar(Composite parent) { + super.createButtonsForButtonBar(parent); + initializeDialog(); + } + + /* + * (non-Javadoc) Method declared on Dialog. + */ + protected Control createDialogArea(Composite parent) { + // page group + Composite composite = (Composite) super.createDialogArea(parent); + + // create the input element, which has the root resource + // as its only child + + selectionGroup = new TreeAndListGroup(composite, root, + getResourceProvider(IResource.FOLDER | IResource.PROJECT + | IResource.ROOT), new WorkbenchLabelProvider(), + getResourceProvider(IResource.FILE), + new WorkbenchLabelProvider(), SWT.NONE, + // since this page has no other significantly-sized + // widgets we need to hardcode the combined widget's + // size, otherwise it will open too small + SIZING_SELECTION_WIDGET_WIDTH, SIZING_SELECTION_WIDGET_HEIGHT); + + composite.addControlListener(new ControlListener() { + public void controlMoved(ControlEvent e) { + }; + + public void controlResized(ControlEvent e) { + // Also try and reset the size of the columns as appropriate + TableColumn[] columns = selectionGroup.getListTable() + .getColumns(); + for (int i = 0; i < columns.length; i++) { + columns[i].pack(); + } + } + }); + + return composite; + } + + /** + * Returns a content provider for IResources that returns + * only children of the given resource type. + */ + private ITreeContentProvider getResourceProvider(final int resourceType) { + return new WorkbenchContentProvider() { + public Object[] getChildren(Object o) { + if (o instanceof IContainer) { + IResource[] members = null; + try { + members = ((IContainer) o).members(); + List accessibleMembers = new ArrayList(members.length); + for (int i = 0; i < members.length; i++) { + IResource resource = members[i]; + if (resource.isAccessible()) { + accessibleMembers.add(resource); + } } + members = (IResource[]) accessibleMembers + .toArray(new IResource[accessibleMembers.size()]); + } catch (CoreException e) { + // just return an empty set of children + return new Object[0]; } - members= (IResource[])accessibleMembers.toArray(new IResource[accessibleMembers.size()]); - } catch (CoreException e) { - //just return an empty set of children - return new Object[0]; - } - //filter out the desired resource types - ArrayList results = new ArrayList(); - for (int i = 0; i < members.length; i++) { - //And the test bits with the resource types to see if they are what we want - if ((members[i].getType() & resourceType) > 0) { - if (members[i].getType() == IResource.FILE && - stringMatcher != null && - !stringMatcher.match(members[i].getName())) { - continue; + // filter out the desired resource types + ArrayList results = new ArrayList(); + for (int i = 0; i < members.length; i++) { + // And the test bits with the resource types to see if + // they are what we want + if ((members[i].getType() & resourceType) > 0) { + if (members[i].getType() == IResource.FILE + && stringMatcher != null + && !stringMatcher.match(members[i] + .getName())) { + continue; + } + results.add(members[i]); } - results.add(members[i]); } + return results.toArray(); + } else { + return new Object[0]; } - return results.toArray(); - } else { - return new Object[0]; } - } - }; -} -/** - * Initializes this dialog's controls. - */ -private void initializeDialog() { - selectionGroup.addSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - getOkButton().setEnabled(!selectionGroup.getListTableSelection().isEmpty()); - } - }); + }; + } - getOkButton().setEnabled(false); -} + /** + * Initializes this dialog's controls. + */ + private void initializeDialog() { + selectionGroup + .addSelectionChangedListener(new ISelectionChangedListener() { + public void selectionChanged(SelectionChangedEvent event) { + getOkButton().setEnabled( + !selectionGroup.getListTableSelection() + .isEmpty()); + } + }); -/** - * Returns this dialog's OK button. - */ -protected Button getOkButton() { - return getButton(0); -} -/** - * Returns the file the user chose or null if none. - */ -public IFile getResult() { - return result; -} + getOkButton().setEnabled(false); + } + + /** + * Returns this dialog's OK button. + */ + protected Button getOkButton() { + return getButton(0); + } -protected void buttonPressed(int buttonId) { - if (buttonId == 0) { - Object resource= selectionGroup.getListTableSelection().getFirstElement(); - if (resource instanceof IFile) { - result = (IFile) resource; + /** + * Returns the file the user chose or null if none. + */ + public IFile getResult() { + return result; + } + + protected void buttonPressed(int buttonId) { + if (buttonId == 0) { + Object resource = selectionGroup.getListTableSelection() + .getFirstElement(); + if (resource instanceof IFile) { + result = (IFile) resource; + } } + super.buttonPressed(buttonId); } - super.buttonPressed(buttonId); -} } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/IExternalToolsUIConstants.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/IExternalToolsUIConstants.java index 10b049e..225c688 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/IExternalToolsUIConstants.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/IExternalToolsUIConstants.java @@ -1,39 +1,70 @@ package net.sourceforge.phpdt.externaltools.internal.ui; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + **********************************************************************/ import net.sourceforge.phpdt.externaltools.model.IExternalToolConstants; - public interface IExternalToolsUIConstants { - + // Action images - public static final String IMG_REMOVE= IExternalToolConstants.PLUGIN_ID + ".remove"; //$NON-NLS-1$ - public static final String IMG_MOVE_UP = IExternalToolConstants.PLUGIN_ID + ".moveUp"; //$NON-NLS-1$ - public static final String IMG_MOVE_DOWN = IExternalToolConstants.PLUGIN_ID + ".moveDown"; //$NON-NLS-1$ - public static final String IMG_ACTIVATE = IExternalToolConstants.PLUGIN_ID + ".activate"; //$NON-NLS-1$ - public static final String IMG_DEACTIVATE = IExternalToolConstants.PLUGIN_ID + ".deactivate"; //$NON-NLS-1$ - public static final String IMG_REMOVE_ALL= IExternalToolConstants.PLUGIN_ID + ".removeAll"; //$NON-NLS-1$ - public static final String IMG_ADD= IExternalToolConstants.PLUGIN_ID + ".add"; //$NON-NLS-1$ - public static final String IMG_RUN= IExternalToolConstants.PLUGIN_ID + ".run"; //$NON-NLS-1$ - public static final String IMG_SEARCH= IExternalToolConstants.PLUGIN_ID + ".search"; //$NON-NLS-1$ - public static final String IMG_GO_TO_FILE= IExternalToolConstants.PLUGIN_ID + ".goToFile"; //$NON-NLS-1$ - + public static final String IMG_REMOVE = IExternalToolConstants.PLUGIN_ID + + ".remove"; //$NON-NLS-1$ + + public static final String IMG_MOVE_UP = IExternalToolConstants.PLUGIN_ID + + ".moveUp"; //$NON-NLS-1$ + + public static final String IMG_MOVE_DOWN = IExternalToolConstants.PLUGIN_ID + + ".moveDown"; //$NON-NLS-1$ + + public static final String IMG_ACTIVATE = IExternalToolConstants.PLUGIN_ID + + ".activate"; //$NON-NLS-1$ + + public static final String IMG_DEACTIVATE = IExternalToolConstants.PLUGIN_ID + + ".deactivate"; //$NON-NLS-1$ + + public static final String IMG_REMOVE_ALL = IExternalToolConstants.PLUGIN_ID + + ".removeAll"; //$NON-NLS-1$ + + public static final String IMG_ADD = IExternalToolConstants.PLUGIN_ID + + ".add"; //$NON-NLS-1$ + + public static final String IMG_RUN = IExternalToolConstants.PLUGIN_ID + + ".run"; //$NON-NLS-1$ + + public static final String IMG_SEARCH = IExternalToolConstants.PLUGIN_ID + + ".search"; //$NON-NLS-1$ + + public static final String IMG_GO_TO_FILE = IExternalToolConstants.PLUGIN_ID + + ".goToFile"; //$NON-NLS-1$ + // Label images -// public static final String IMG_ANT_PROJECT= IExternalToolConstants.PLUGIN_ID + ".antProject"; //$NON-NLS-1$ -// public static final String IMG_ANT_PROJECT_ERROR = IExternalToolConstants.PLUGIN_ID + ".antProjectError"; //$NON-NLS-1$ -// public static final String IMG_ANT_TARGET= IExternalToolConstants.PLUGIN_ID + ".antTarget"; //$NON-NLS-1$ -// public static final String IMG_ANT_TARGET_ERROR = IExternalToolConstants.PLUGIN_ID + ".antTargetError"; //$NON-NLS-1$ -// public static final String IMG_ANT_TARGET_ELEMENTS= IExternalToolConstants.PLUGIN_ID + ".antTargetElements"; //$NON-NLS-1$ -// public static final String IMG_ANT_TARGET_ELEMENT= IExternalToolConstants.PLUGIN_ID + ".antTargetElement"; //$NON-NLS-1$ - - public static final String DIALOGSTORE_LASTEXTJAR= IExternalToolConstants.PLUGIN_ID + ".lastextjar"; //$NON-NLS-1$ - public static final String DIALOGSTORE_LASTEXTFILE= IExternalToolConstants.PLUGIN_ID + ".lastextfile"; //$NON-NLS-1$ - public static final String DIALOGSTORE_LASTFOLDER= IExternalToolConstants.PLUGIN_ID + ".lastfolder"; //$NON-NLS-1$ - public static final String DIALOGSTORE_LASTANTHOME= IExternalToolConstants.PLUGIN_ID + ".lastanthome"; //$NON-NLS-1$ + // public static final String IMG_ANT_PROJECT= + // IExternalToolConstants.PLUGIN_ID + ".antProject"; //$NON-NLS-1$ + // public static final String IMG_ANT_PROJECT_ERROR = + // IExternalToolConstants.PLUGIN_ID + ".antProjectError"; //$NON-NLS-1$ + // public static final String IMG_ANT_TARGET= + // IExternalToolConstants.PLUGIN_ID + ".antTarget"; //$NON-NLS-1$ + // public static final String IMG_ANT_TARGET_ERROR = + // IExternalToolConstants.PLUGIN_ID + ".antTargetError"; //$NON-NLS-1$ + // public static final String IMG_ANT_TARGET_ELEMENTS= + // IExternalToolConstants.PLUGIN_ID + ".antTargetElements"; //$NON-NLS-1$ + // public static final String IMG_ANT_TARGET_ELEMENT= + // IExternalToolConstants.PLUGIN_ID + ".antTargetElement"; //$NON-NLS-1$ + + public static final String DIALOGSTORE_LASTEXTJAR = IExternalToolConstants.PLUGIN_ID + + ".lastextjar"; //$NON-NLS-1$ + + public static final String DIALOGSTORE_LASTEXTFILE = IExternalToolConstants.PLUGIN_ID + + ".lastextfile"; //$NON-NLS-1$ + + public static final String DIALOGSTORE_LASTFOLDER = IExternalToolConstants.PLUGIN_ID + + ".lastfolder"; //$NON-NLS-1$ + + public static final String DIALOGSTORE_LASTANTHOME = IExternalToolConstants.PLUGIN_ID + + ".lastanthome"; //$NON-NLS-1$ } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/MessageDialogWithToggle.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/MessageDialogWithToggle.java index 959db60..1e3e84f 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/MessageDialogWithToggle.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/MessageDialogWithToggle.java @@ -1,11 +1,11 @@ package net.sourceforge.phpdt.externaltools.internal.ui; /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + **********************************************************************/ import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; @@ -25,29 +25,36 @@ import org.eclipse.swt.widgets.Shell; * should be shown in the future */ public class MessageDialogWithToggle extends MessageDialog { - + /** - * The preference key which is set by the toggle button. - * This key must be a boolean preference in the preference store. + * The preference key which is set by the toggle button. This key must be a + * boolean preference in the preference store. */ private String fPreferenceKey = null; + /** * The message displayed to the user, with the toggle button */ private String fToggleMessage = null; + private Button fToggleButton = null; + /** * The preference store which will be affected by the toggle button */ IPreferenceStore fStore = null; - public MessageDialogWithToggle(Shell parentShell, String dialogTitle, Image image, String message, int dialogImageType, String[] dialogButtonLabels, int defaultIndex, String preferenceKey, String toggleMessage, IPreferenceStore store) { - super(parentShell, dialogTitle, image, message, dialogImageType, dialogButtonLabels, defaultIndex); + public MessageDialogWithToggle(Shell parentShell, String dialogTitle, + Image image, String message, int dialogImageType, + String[] dialogButtonLabels, int defaultIndex, + String preferenceKey, String toggleMessage, IPreferenceStore store) { + super(parentShell, dialogTitle, image, message, dialogImageType, + dialogButtonLabels, defaultIndex); fStore = store; fPreferenceKey = preferenceKey; fToggleMessage = toggleMessage; } - + protected Control createDialogArea(Composite parent) { Composite dialogArea = (Composite) super.createDialogArea(parent); fToggleButton = createCheckButton(dialogArea, fToggleMessage); @@ -56,16 +63,16 @@ public class MessageDialogWithToggle extends MessageDialog { } /** - * Creates a button with the given label and sets the default - * configuration data. + * Creates a button with the given label and sets the default configuration + * data. */ protected Button createCheckButton(Composite parent, String label) { - Button button= new Button(parent, SWT.CHECK | SWT.LEFT); + Button button = new Button(parent, SWT.CHECK | SWT.LEFT); button.setText(label); GridData data = new GridData(SWT.NONE); - data.horizontalSpan= 2; - data.horizontalAlignment= GridData.CENTER; + data.horizontalSpan = 2; + data.horizontalAlignment = GridData.CENTER; button.setLayoutData(data); button.setFont(parent.getFont()); @@ -78,7 +85,7 @@ public class MessageDialogWithToggle extends MessageDialog { * @see org.eclipse.jface.dialogs.Dialog#buttonPressed(int) */ protected void buttonPressed(int id) { - if (id == IDialogConstants.OK_ID) { // was the OK button pressed? + if (id == IDialogConstants.OK_ID) { // was the OK button pressed? storePreference(); } super.buttonPressed(id); @@ -99,110 +106,116 @@ public class MessageDialogWithToggle extends MessageDialog { protected Button getToggleButton() { return fToggleButton; } - + /** * Convenience method to open a simple confirm (OK/Cancel) dialog. - * - * @param parent the parent shell of the dialog, or null if none - * @param title the dialog's title, or null if none - * @param message the message + * + * @param parent + * the parent shell of the dialog, or null if none + * @param title + * the dialog's title, or null if none + * @param message + * the message * @return true if the user presses the OK button, - * false otherwise + * false otherwise */ - public static boolean openConfirm(Shell parent, String title, String message, String preferenceKey, String toggleMessage, IPreferenceStore store) { - MessageDialogWithToggle dialog = new MessageDialogWithToggle( - parent, - title, - null, // accept the default window icon - message, - QUESTION, - new String[] {IDialogConstants.OK_LABEL, IDialogConstants.CANCEL_LABEL}, - 0, // OK is the default - preferenceKey, - toggleMessage, - store); + public static boolean openConfirm(Shell parent, String title, + String message, String preferenceKey, String toggleMessage, + IPreferenceStore store) { + MessageDialogWithToggle dialog = new MessageDialogWithToggle(parent, + title, null, // accept the default window icon + message, QUESTION, new String[] { IDialogConstants.OK_LABEL, + IDialogConstants.CANCEL_LABEL }, 0, // OK is the default + preferenceKey, toggleMessage, store); return dialog.open() == 0; } + /** * Convenience method to open a standard error dialog. - * - * @param parent the parent shell of the dialog, or null if none - * @param title the dialog's title, or null if none - * @param message the message + * + * @param parent + * the parent shell of the dialog, or null if none + * @param title + * the dialog's title, or null if none + * @param message + * the message */ - public static void openError(Shell parent, String title, String message, String preferenceKey, String toggleMessage, IPreferenceStore store) { - MessageDialogWithToggle dialog = new MessageDialogWithToggle( - parent, - title, - null, // accept the default window icon - message, - ERROR, - new String[] {IDialogConstants.OK_LABEL}, - 0, // ok is the default - preferenceKey, - toggleMessage, - store); + public static void openError(Shell parent, String title, String message, + String preferenceKey, String toggleMessage, IPreferenceStore store) { + MessageDialogWithToggle dialog = new MessageDialogWithToggle(parent, + title, null, // accept the default window icon + message, ERROR, new String[] { IDialogConstants.OK_LABEL }, 0, // ok + // is + // the + // default + preferenceKey, toggleMessage, store); dialog.open(); } + /** * Convenience method to open a standard information dialog. - * - * @param parent the parent shell of the dialog, or null if none - * @param title the dialog's title, or null if none - * @param message the message + * + * @param parent + * the parent shell of the dialog, or null if none + * @param title + * the dialog's title, or null if none + * @param message + * the message */ - public static void openInformation( - Shell parent, - String title, - String message, String preferenceKey, String toggleMessage, IPreferenceStore store) { - MessageDialogWithToggle dialog = - new MessageDialogWithToggle(parent, title, null, // accept the default window icon - message, INFORMATION, new String[] { IDialogConstants.OK_LABEL }, 0, // ok is the default - preferenceKey, toggleMessage, store); + public static void openInformation(Shell parent, String title, + String message, String preferenceKey, String toggleMessage, + IPreferenceStore store) { + MessageDialogWithToggle dialog = new MessageDialogWithToggle(parent, + title, + null, // accept the default window icon + message, INFORMATION, + new String[] { IDialogConstants.OK_LABEL }, 0, // ok is the + // default + preferenceKey, toggleMessage, store); dialog.open(); } + /** * Convenience method to open a simple Yes/No question dialog. - * - * @param parent the parent shell of the dialog, or null if none - * @param title the dialog's title, or null if none - * @param message the message + * + * @param parent + * the parent shell of the dialog, or null if none + * @param title + * the dialog's title, or null if none + * @param message + * the message * @return true if the user presses the OK button, - * false otherwise + * false otherwise */ - public static boolean openQuestion(Shell parent, String title, String message, String preferenceKey, String toggleMessage, IPreferenceStore store) { - MessageDialogWithToggle dialog = new MessageDialogWithToggle( - parent, - title, - null, // accept the default window icon - message, - QUESTION, - new String[] {IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL}, - 0, // yes is the default - preferenceKey, - toggleMessage, - store); + public static boolean openQuestion(Shell parent, String title, + String message, String preferenceKey, String toggleMessage, + IPreferenceStore store) { + MessageDialogWithToggle dialog = new MessageDialogWithToggle(parent, + title, null, // accept the default window icon + message, QUESTION, new String[] { IDialogConstants.YES_LABEL, + IDialogConstants.NO_LABEL }, 0, // yes is the default + preferenceKey, toggleMessage, store); return dialog.open() == 0; } + /** * Convenience method to open a standard warning dialog. - * - * @param parent the parent shell of the dialog, or null if none - * @param title the dialog's title, or null if none - * @param message the message + * + * @param parent + * the parent shell of the dialog, or null if none + * @param title + * the dialog's title, or null if none + * @param message + * the message */ - public static void openWarning(Shell parent, String title, String message, String preferenceKey, String toggleMessage, IPreferenceStore store) { - MessageDialogWithToggle dialog = new MessageDialogWithToggle( - parent, - title, - null, // accept the default window icon - message, - WARNING, - new String[] {IDialogConstants.OK_LABEL}, - 0, // ok is the default - preferenceKey, - toggleMessage, - store); + public static void openWarning(Shell parent, String title, String message, + String preferenceKey, String toggleMessage, IPreferenceStore store) { + MessageDialogWithToggle dialog = new MessageDialogWithToggle(parent, + title, + null, // accept the default window icon + message, WARNING, new String[] { IDialogConstants.OK_LABEL }, + 0, // ok is the default + preferenceKey, toggleMessage, store); dialog.open(); } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/MessageLine.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/MessageLine.java index b724f3b..12189a1 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/MessageLine.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/MessageLine.java @@ -1,11 +1,11 @@ package net.sourceforge.phpdt.externaltools.internal.ui; /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + **********************************************************************/ import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.SWT; @@ -25,6 +25,7 @@ public class MessageLine extends CLabel { private static final RGB ERROR_BACKGROUND_RGB = new RGB(230, 226, 221); private Color fNormalMsgAreaBackground; + private Color fErrorMsgAreaBackground; /** @@ -35,40 +36,44 @@ public class MessageLine extends CLabel { } /** - * Creates a new message line as a child of the parent and with the given SWT stylebits. + * Creates a new message line as a child of the parent and with the given + * SWT stylebits. */ public MessageLine(Composite parent, int style) { super(parent, style); - fNormalMsgAreaBackground= getBackground(); - fErrorMsgAreaBackground= null; + fNormalMsgAreaBackground = getBackground(); + fErrorMsgAreaBackground = null; } - private Image findImage(IStatus status) { if (status.isOK()) { return null; } else if (status.matches(IStatus.ERROR)) { - return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJS_ERROR_TSK); + return PlatformUI.getWorkbench().getSharedImages().getImage( + ISharedImages.IMG_OBJS_ERROR_TSK); } else if (status.matches(IStatus.WARNING)) { - return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJS_WARN_TSK); + return PlatformUI.getWorkbench().getSharedImages().getImage( + ISharedImages.IMG_OBJS_WARN_TSK); } else if (status.matches(IStatus.INFO)) { - return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJS_INFO_TSK); + return PlatformUI.getWorkbench().getSharedImages().getImage( + ISharedImages.IMG_OBJS_INFO_TSK); } return null; } /** - * Sets the message and image to the given status. - * null is a valid argument and will set the empty text and no image + * Sets the message and image to the given status. null is a + * valid argument and will set the empty text and no image */ public void setErrorStatus(IStatus status) { if (status != null) { - String message= status.getMessage(); + String message = status.getMessage(); if (message != null && message.length() > 0) { setText(message); setImage(findImage(status)); if (fErrorMsgAreaBackground == null) { - fErrorMsgAreaBackground= new Color(getDisplay(), ERROR_BACKGROUND_RGB); + fErrorMsgAreaBackground = new Color(getDisplay(), + ERROR_BACKGROUND_RGB); } setBackground(fErrorMsgAreaBackground); return; @@ -85,7 +90,7 @@ public class MessageLine extends CLabel { public void dispose() { if (fErrorMsgAreaBackground != null) { fErrorMsgAreaBackground.dispose(); - fErrorMsgAreaBackground= null; + fErrorMsgAreaBackground = null; } super.dispose(); } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/StatusDialog.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/StatusDialog.java index 5b19da3..b809c79 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/StatusDialog.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/StatusDialog.java @@ -1,11 +1,11 @@ package net.sourceforge.phpdt.externaltools.internal.ui; /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + **********************************************************************/ import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.dialogs.Dialog; @@ -21,16 +21,20 @@ import org.eclipse.swt.widgets.Shell; /** * An abstract base class for dialogs with a status bar and ok/cancel buttons. - * The status message must be passed over as StatusInfo object and can be - * an error, warning or ok. The OK button is enabled or disabled depending - * on the status. + * The status message must be passed over as StatusInfo object and can be an + * error, warning or ok. The OK button is enabled or disabled depending on the + * status. */ public abstract class StatusDialog extends Dialog { private Button fOkButton; + private MessageLine fStatusLine; + private IStatus fLastStatus; + private String fTitle; + private Image fImage; private boolean fStatusLineAboveButtons; @@ -40,27 +44,28 @@ public abstract class StatusDialog extends Dialog { */ public StatusDialog(Shell parent) { super(parent); - fStatusLineAboveButtons= false; - fLastStatus= new StatusInfo(); + fStatusLineAboveButtons = false; + fLastStatus = new StatusInfo(); } /** - * Specifies whether status line appears to the left of the buttons (default) - * or above them. - * - * @param aboveButtons if true status line is placed above buttons; if - * false to the right + * Specifies whether status line appears to the left of the buttons + * (default) or above them. + * + * @param aboveButtons + * if true status line is placed above buttons; if + * false to the right */ public void setStatusLineAboveButtons(boolean aboveButtons) { - fStatusLineAboveButtons= aboveButtons; + fStatusLineAboveButtons = aboveButtons; } /** - * Update the dialog's status line to reflect the given status. - * It is save to call this method before the dialog has been opened. + * Update the dialog's status line to reflect the given status. It is save + * to call this method before the dialog has been opened. */ protected void updateStatus(IStatus status) { - fLastStatus= status; + fLastStatus = status; if (fStatusLine != null && !fStatusLine.isDisposed()) { updateButtonsEnableState(status); fStatusLine.setErrorStatus(status); @@ -77,7 +82,9 @@ public abstract class StatusDialog extends Dialog { /** * Updates the status of the ok button to reflect the given status. * Subclasses may override this method to update additional buttons. - * @param status the status. + * + * @param status + * the status. */ protected void updateButtonsEnableState(IStatus status) { if (fOkButton != null && !fOkButton.isDisposed()) @@ -101,9 +108,9 @@ public abstract class StatusDialog extends Dialog { if (fLastStatus != null) { // policy: dialogs are not allowed to come up with an error message if (fLastStatus.matches(IStatus.ERROR)) { - StatusInfo status= new StatusInfo(); + StatusInfo status = new StatusInfo(); status.setError(""); //$NON-NLS-1$ - fLastStatus= status; + fLastStatus = status; } updateStatus(fLastStatus); } @@ -113,23 +120,25 @@ public abstract class StatusDialog extends Dialog { * @see Dialog#createButtonsForButtonBar(Composite) */ protected void createButtonsForButtonBar(Composite parent) { - fOkButton= createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); - createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); + fOkButton = createButton(parent, IDialogConstants.OK_ID, + IDialogConstants.OK_LABEL, true); + createButton(parent, IDialogConstants.CANCEL_ID, + IDialogConstants.CANCEL_LABEL, false); } /* * @see Dialog#createButtonBar(Composite) */ protected Control createButtonBar(Composite parent) { - Composite composite= new Composite(parent, SWT.NULL); - GridLayout layout= new GridLayout(); - layout.numColumns= 1; - layout.marginHeight= 0; - layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); + Composite composite = new Composite(parent, SWT.NULL); + GridLayout layout = new GridLayout(); + layout.numColumns = 1; + layout.marginHeight = 0; + layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); composite.setLayout(layout); composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - fStatusLine= new MessageLine(composite); + fStatusLine = new MessageLine(composite); fStatusLine.setAlignment(SWT.LEFT); fStatusLine.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fStatusLine.setErrorStatus(null); //$NON-NLS-1$ @@ -140,22 +149,26 @@ public abstract class StatusDialog extends Dialog { /** * Sets the title for this dialog. - * @param title the title. + * + * @param title + * the title. */ public void setTitle(String title) { - fTitle= title != null ? title : ""; //$NON-NLS-1$ - Shell shell= getShell(); + fTitle = title != null ? title : ""; //$NON-NLS-1$ + Shell shell = getShell(); if ((shell != null) && !shell.isDisposed()) shell.setText(fTitle); } /** * Sets the image for this dialog. - * @param image the image. + * + * @param image + * the image. */ public void setImage(Image image) { - fImage= image; - Shell shell= getShell(); + fImage = image; + Shell shell = getShell(); if ((shell != null) && !shell.isDisposed()) shell.setImage(fImage); } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/StatusInfo.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/StatusInfo.java index 418cef8..a06bce9 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/StatusInfo.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/StatusInfo.java @@ -1,11 +1,11 @@ package net.sourceforge.phpdt.externaltools.internal.ui; /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + **********************************************************************/ import net.sourceforge.phpdt.externaltools.model.IExternalToolConstants; @@ -13,13 +13,13 @@ import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.util.Assert; /** - * A settable IStatus. - * Can be an error, warning, info or ok. For error, info and warning states, - * a message describes the problem. + * A settable IStatus. Can be an error, warning, info or ok. For error, info and + * warning states, a message describes the problem. */ public class StatusInfo implements IStatus { private String fStatusMessage; + private int fSeverity; /** @@ -31,38 +31,41 @@ public class StatusInfo implements IStatus { /** * Creates a status . - * @param severity The status severity: ERROR, WARNING, INFO and OK. - * @param message The message of the status. Applies only for ERROR, - * WARNING and INFO. + * + * @param severity + * The status severity: ERROR, WARNING, INFO and OK. + * @param message + * The message of the status. Applies only for ERROR, WARNING and + * INFO. */ public StatusInfo(int severity, String message) { - fStatusMessage= message; - fSeverity= severity; + fStatusMessage = message; + fSeverity = severity; } /** - * Returns if the status' severity is OK. + * Returns if the status' severity is OK. */ public boolean isOK() { return fSeverity == IStatus.OK; } /** - * Returns if the status' severity is WARNING. + * Returns if the status' severity is WARNING. */ public boolean isWarning() { return fSeverity == IStatus.WARNING; } /** - * Returns if the status' severity is INFO. + * Returns if the status' severity is INFO. */ public boolean isInfo() { return fSeverity == IStatus.INFO; } /** - * Returns if the status' severity is ERROR. + * Returns if the status' severity is ERROR. */ public boolean isError() { return fSeverity == IStatus.ERROR; @@ -77,40 +80,46 @@ public class StatusInfo implements IStatus { /** * Sets the status to ERROR. - * @param The error message (can be empty, but not null) + * + * @param The + * error message (can be empty, but not null) */ public void setError(String errorMessage) { Assert.isNotNull(errorMessage); - fStatusMessage= errorMessage; - fSeverity= IStatus.ERROR; + fStatusMessage = errorMessage; + fSeverity = IStatus.ERROR; } /** * Sets the status to WARNING. - * @param The warning message (can be empty, but not null) + * + * @param The + * warning message (can be empty, but not null) */ public void setWarning(String warningMessage) { Assert.isNotNull(warningMessage); - fStatusMessage= warningMessage; - fSeverity= IStatus.WARNING; + fStatusMessage = warningMessage; + fSeverity = IStatus.WARNING; } /** * Sets the status to INFO. - * @param The info message (can be empty, but not null) + * + * @param The + * info message (can be empty, but not null) */ public void setInfo(String infoMessage) { Assert.isNotNull(infoMessage); - fStatusMessage= infoMessage; - fSeverity= IStatus.INFO; + fStatusMessage = infoMessage; + fSeverity = IStatus.INFO; } /** * Sets the status to OK. */ public void setOK() { - fStatusMessage= null; - fSeverity= IStatus.OK; + fStatusMessage = null; + fSeverity = IStatus.OK; } /* @@ -122,6 +131,7 @@ public class StatusInfo implements IStatus { /** * Returns always false. + * * @see IStatus#isMultiStatus() */ public boolean isMultiStatus() { @@ -144,6 +154,7 @@ public class StatusInfo implements IStatus { /** * Returns always null. + * * @see IStatus#getException() */ public Throwable getException() { @@ -152,6 +163,7 @@ public class StatusInfo implements IStatus { /** * Returns always the error severity. + * * @see IStatus#getCode() */ public int getCode() { @@ -160,6 +172,7 @@ public class StatusInfo implements IStatus { /** * Returns always null. + * * @see IStatus#getChildren() */ public IStatus[] getChildren() { diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/TreeAndListGroup.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/TreeAndListGroup.java index 9da2dea..1255b2f 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/TreeAndListGroup.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/internal/ui/TreeAndListGroup.java @@ -1,11 +1,11 @@ package net.sourceforge.phpdt.externaltools.internal.ui; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + **********************************************************************/ import java.util.Collection; import java.util.HashSet; @@ -30,39 +30,59 @@ import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.Tree; /** - * This class was derived from org.eclipse.ui.internal.misc.CheckboxTreeAndListGroup - * + * This class was derived from + * org.eclipse.ui.internal.misc.CheckboxTreeAndListGroup + * */ public class TreeAndListGroup implements ISelectionChangedListener { private Object root; + private Object currentTreeSelection; + private Collection listeners = new HashSet(); private ITreeContentProvider treeContentProvider; + private IStructuredContentProvider listContentProvider; + private ILabelProvider treeLabelProvider; + private ILabelProvider listLabelProvider; // widgets private TreeViewer treeViewer; + private TableViewer listViewer; - private boolean allowMultiselection= false; + + private boolean allowMultiselection = false; /** - * Create an instance of this class. Use this constructor if you wish to specify - * the width and/or height of the combined widget (to only hardcode one of the - * sizing dimensions, specify the other dimension's value as -1) - * - * @param parent org.eclipse.swt.widgets.Composite - * @param style int - * @param rootObject java.lang.Object - * @param childPropertyName java.lang.String - * @param parentPropertyName java.lang.String - * @param listPropertyName java.lang.String - * @param width int - * @param height int + * Create an instance of this class. Use this constructor if you wish to + * specify the width and/or height of the combined widget (to only hardcode + * one of the sizing dimensions, specify the other dimension's value as -1) + * + * @param parent + * org.eclipse.swt.widgets.Composite + * @param style + * int + * @param rootObject + * java.lang.Object + * @param childPropertyName + * java.lang.String + * @param parentPropertyName + * java.lang.String + * @param listPropertyName + * java.lang.String + * @param width + * int + * @param height + * int */ - public TreeAndListGroup(Composite parent, Object rootObject, ITreeContentProvider treeContentProvider, ILabelProvider treeLabelProvider, IStructuredContentProvider listContentProvider, ILabelProvider listLabelProvider, int style, int width, int height) { + public TreeAndListGroup(Composite parent, Object rootObject, + ITreeContentProvider treeContentProvider, + ILabelProvider treeLabelProvider, + IStructuredContentProvider listContentProvider, + ILabelProvider listLabelProvider, int style, int width, int height) { root = rootObject; this.treeContentProvider = treeContentProvider; @@ -71,13 +91,14 @@ public class TreeAndListGroup implements ISelectionChangedListener { this.listLabelProvider = listLabelProvider; createContents(parent, width, height, style); } + /** * This method must be called just before this window becomes visible. */ public void aboutToOpen() { currentTreeSelection = null; - //select the first element in the list + // select the first element in the list Object[] elements = treeContentProvider.getElements(root); Object primary = elements.length > 0 ? elements[0] : null; if (primary != null) { @@ -85,35 +106,42 @@ public class TreeAndListGroup implements ISelectionChangedListener { } treeViewer.getControl().setFocus(); } + /** - * Add the passed listener to collection of clients - * that listen for changes to list viewer selection state - * - * @param listener ISelectionChangedListener + * Add the passed listener to collection of clients that listen for changes + * to list viewer selection state + * + * @param listener + * ISelectionChangedListener */ public void addSelectionChangedListener(ISelectionChangedListener listener) { listeners.add(listener); } /** - * Notify all checked state listeners that the passed element - *has had its checked state changed to the passed state - */ + * Notify all checked state listeners that the passed element has had its + * checked state changed to the passed state + */ protected void notifySelectionListeners(SelectionChangedEvent event) { Iterator listenersEnum = listeners.iterator(); while (listenersEnum.hasNext()) { - ((ISelectionChangedListener) listenersEnum.next()).selectionChanged(event); + ((ISelectionChangedListener) listenersEnum.next()) + .selectionChanged(event); } } /** - * Lay out and initialize self's visual components. - * - * @param parent org.eclipse.swt.widgets.Composite - * @param width int - * @param height int + * Lay out and initialize self's visual components. + * + * @param parent + * org.eclipse.swt.widgets.Composite + * @param width + * int + * @param height + * int */ - protected void createContents(Composite parent, int width, int height, int style) { + protected void createContents(Composite parent, int width, int height, + int style) { // group pane Composite composite = new Composite(parent, style); composite.setFont(parent.getFont()); @@ -130,15 +158,16 @@ public class TreeAndListGroup implements ISelectionChangedListener { initialize(); } + /** - * Create this group's list viewer. + * Create this group's list viewer. */ protected void createListViewer(Composite parent, int width, int height) { int style; if (allowMultiselection) { - style= SWT.MULTI; + style = SWT.MULTI; } else { - style= SWT.SINGLE; + style = SWT.SINGLE; } listViewer = new TableViewer(parent, SWT.BORDER | style); GridData data = new GridData(GridData.FILL_BOTH); @@ -154,8 +183,9 @@ public class TreeAndListGroup implements ISelectionChangedListener { } }); } + /** - * Create this group's tree viewer. + * Create this group's tree viewer. */ protected void createTreeViewer(Composite parent, int width, int height) { Tree tree = new Tree(parent, SWT.BORDER); @@ -170,31 +200,31 @@ public class TreeAndListGroup implements ISelectionChangedListener { treeViewer.setLabelProvider(treeLabelProvider); treeViewer.addSelectionChangedListener(this); } - + public Table getListTable() { return listViewer.getTable(); } - + public IStructuredSelection getListTableSelection() { - ISelection selection= this.listViewer.getSelection(); + ISelection selection = this.listViewer.getSelection(); if (selection instanceof IStructuredSelection) { - return (IStructuredSelection)selection; + return (IStructuredSelection) selection; } else { return StructuredSelection.EMPTY; } } - + protected void initialListItem(Object element) { Object parent = treeContentProvider.getParent(element); selectAndRevealFolder(parent); } - + public void selectAndRevealFolder(Object treeElement) { treeViewer.reveal(treeElement); IStructuredSelection selection = new StructuredSelection(treeElement); treeViewer.setSelection(selection); } - + public void selectAndRevealFile(Object treeElement) { listViewer.reveal(treeElement); IStructuredSelection selection = new StructuredSelection(treeElement); @@ -202,19 +232,21 @@ public class TreeAndListGroup implements ISelectionChangedListener { } /** - * Initialize this group's viewers after they have been laid out. + * Initialize this group's viewers after they have been laid out. */ protected void initialize() { treeViewer.setInput(root); } /** - * Handle the selection of an item in the tree viewer - * - * @param selection ISelection + * Handle the selection of an item in the tree viewer + * + * @param selection + * ISelection */ public void selectionChanged(SelectionChangedEvent event) { - IStructuredSelection selection = (IStructuredSelection) event.getSelection(); + IStructuredSelection selection = (IStructuredSelection) event + .getSelection(); Object selectedElement = selection.getFirstElement(); if (selectedElement == null) { currentTreeSelection = null; @@ -229,25 +261,32 @@ public class TreeAndListGroup implements ISelectionChangedListener { currentTreeSelection = selectedElement; } + /** - * Set the list viewer's providers to those passed - * - * @param contentProvider ITreeContentProvider - * @param labelProvider ILabelProvider + * Set the list viewer's providers to those passed + * + * @param contentProvider + * ITreeContentProvider + * @param labelProvider + * ILabelProvider */ - public void setListProviders(IStructuredContentProvider contentProvider, ILabelProvider labelProvider) { + public void setListProviders(IStructuredContentProvider contentProvider, + ILabelProvider labelProvider) { listViewer.setContentProvider(contentProvider); listViewer.setLabelProvider(labelProvider); } + /** - * Set the sorter that is to be applied to self's list viewer + * Set the sorter that is to be applied to self's list viewer */ public void setListSorter(ViewerSorter sorter) { listViewer.setSorter(sorter); } + /** - * Set the root of the widget to be new Root. Regenerate all of the tables and lists from this - * value. + * Set the root of the widget to be new Root. Regenerate all of the tables + * and lists from this value. + * * @param newRoot */ public void setRoot(Object newRoot) { @@ -256,17 +295,21 @@ public class TreeAndListGroup implements ISelectionChangedListener { } /** - * Set the tree viewer's providers to those passed - * - * @param contentProvider ITreeContentProvider - * @param labelProvider ILabelProvider + * Set the tree viewer's providers to those passed + * + * @param contentProvider + * ITreeContentProvider + * @param labelProvider + * ILabelProvider */ - public void setTreeProviders(ITreeContentProvider contentProvider, ILabelProvider labelProvider) { + public void setTreeProviders(ITreeContentProvider contentProvider, + ILabelProvider labelProvider) { treeViewer.setContentProvider(contentProvider); treeViewer.setLabelProvider(labelProvider); } + /** - * Set the sorter that is to be applied to self's tree viewer + * Set the sorter that is to be applied to self's tree viewer */ public void setTreeSorter(ViewerSorter sorter) { treeViewer.setSorter(sorter); @@ -279,9 +322,9 @@ public class TreeAndListGroup implements ISelectionChangedListener { this.treeViewer.getTree().setFocus(); } - + public void setAllowMultiselection(boolean allowMultiselection) { - this.allowMultiselection= allowMultiselection; - + this.allowMultiselection = allowMultiselection; + } } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/launchConfigurations/ExternalToolsLaunchConfigurationMessages.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/launchConfigurations/ExternalToolsLaunchConfigurationMessages.java index 56b3319..39df965 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/launchConfigurations/ExternalToolsLaunchConfigurationMessages.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/launchConfigurations/ExternalToolsLaunchConfigurationMessages.java @@ -1,11 +1,11 @@ package net.sourceforge.phpdt.externaltools.launchConfigurations; /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + **********************************************************************/ import java.util.MissingResourceException; import java.util.ResourceBundle; @@ -14,8 +14,8 @@ public class ExternalToolsLaunchConfigurationMessages { private static final String BUNDLE_NAME = "net.sourceforge.phpdt.externaltools.launchConfigurations.ExternalToolsLaunchConfigurationMessages"; //$NON-NLS-1$ - private static final ResourceBundle RESOURCE_BUNDLE = - ResourceBundle.getBundle(BUNDLE_NAME); + private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle + .getBundle(BUNDLE_NAME); private ExternalToolsLaunchConfigurationMessages() { } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/launchConfigurations/ExternalToolsMainTab.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/launchConfigurations/ExternalToolsMainTab.java index 49102df..f9a4f9f 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/launchConfigurations/ExternalToolsMainTab.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/launchConfigurations/ExternalToolsMainTab.java @@ -54,545 +54,620 @@ import org.eclipse.ui.dialogs.SelectionDialog; public class ExternalToolsMainTab extends AbstractLaunchConfigurationTab { - protected Combo locationField; - - protected Text workDirectoryField; - - protected Button fileLocationButton; - - protected Button workspaceLocationButton; - - protected Button fileWorkingDirectoryButton; - - protected Button workspaceWorkingDirectoryButton; - - protected Button runBackgroundButton; - - protected Text argumentField; - - protected Button variableButton; - - protected SelectionAdapter selectionAdapter; - - protected ModifyListener modifyListener = new ModifyListener() { - public void modifyText(ModifyEvent e) { - updateLaunchConfigurationDialog(); - } - }; - - /** - * @see org.eclipse.debug.ui.ILaunchConfigurationTab#createControl(org.eclipse.swt.widgets.Composite) - */ - public void createControl(Composite parent) { - Composite mainComposite = new Composite(parent, SWT.NONE); - setControl(mainComposite); - GridLayout layout = new GridLayout(); - layout.numColumns = 2; - GridData gridData = new GridData(GridData.FILL_HORIZONTAL); - mainComposite.setLayout(layout); - mainComposite.setLayoutData(gridData); - mainComposite.setFont(parent.getFont()); - createLocationComponent(mainComposite); - createWorkDirectoryComponent(mainComposite); - createArgumentComponent(mainComposite); - createVerticalSpacer(mainComposite, 2); - createRunBackgroundComponent(mainComposite); - } - - /** - * Creates the controls needed to edit the location attribute of an external tool - * - * @param parent - * the composite to create the controls in - */ - protected void createLocationComponent(Composite parent) { - Font font = parent.getFont(); - - Composite composite = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.marginWidth = 0; - layout.marginHeight = 0; - layout.numColumns = 1; - GridData gridData = new GridData(GridData.FILL_HORIZONTAL); - composite.setLayout(layout); - composite.setLayoutData(gridData); - - Label label = new Label(composite, SWT.NONE); - label.setText(ExternalToolsLaunchConfigurationMessages.getString("ExternalToolsMainTab.&Location___2")); //$NON-NLS-1$ - label.setFont(font); - - final IPreferenceStore store = ExternalToolsPlugin.getDefault().getPreferenceStore(); - locationField = new Combo(composite, SWT.DROP_DOWN | SWT.BORDER); - GridData data = new GridData(GridData.FILL_HORIZONTAL); - data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH; - locationField.setLayoutData(data); - locationField.setFont(font); - locationField.add(store.getString(ExternalToolsPlugin.PHP_RUN_PREF), 0); - locationField.add(store.getString(ExternalToolsPlugin.APACHE_RUN_PREF), 1); - locationField.add(store.getString(ExternalToolsPlugin.MYSQL_RUN_PREF), 2); - locationField.add(store.getString(ExternalToolsPlugin.XAMPP_START_PREF), 3); - locationField.add(store.getString(ExternalToolsPlugin.XAMPP_STOP_PREF), 4); - Composite buttonComposite = new Composite(parent, SWT.NONE); - layout = new GridLayout(); - layout.marginWidth = 0; - layout.marginHeight = 0; - layout.numColumns = 1; - gridData = new GridData(GridData.HORIZONTAL_ALIGN_END); - buttonComposite.setLayout(layout); - buttonComposite.setLayoutData(gridData); - buttonComposite.setFont(font); - - createVerticalSpacer(buttonComposite, 1); - - workspaceLocationButton = createPushButton(buttonComposite, ExternalToolsLaunchConfigurationMessages - .getString("ExternalToolsMainTab.&Browse_Workspace..._3"), null); //$NON-NLS-1$ - workspaceLocationButton.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent evt) { - handleWorkspaceLocationButtonSelected(); - } - }); - fileLocationButton = createPushButton(buttonComposite, ExternalToolsLaunchConfigurationMessages - .getString("ExternalToolsMainTab.Brows&e_File_System..._4"), null); //$NON-NLS-1$ - fileLocationButton.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent evt) { - handleLocationButtonSelected(); - } - }); - } - - /** - * Creates the controls needed to edit the working directory attribute of an external tool - * - * @param parent - * the composite to create the controls in - */ - protected void createWorkDirectoryComponent(Composite parent) { - Font font = parent.getFont(); - - Composite composite = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.marginWidth = 0; - layout.marginHeight = 0; - layout.numColumns = 1; - GridData gridData = new GridData(GridData.FILL_HORIZONTAL); - composite.setLayout(layout); - composite.setLayoutData(gridData); - - Label label = new Label(composite, SWT.NONE); - label.setText(ExternalToolsLaunchConfigurationMessages.getString("ExternalToolsMainTab.Working_&Directory__5")); //$NON-NLS-1$ - label.setFont(font); - - workDirectoryField = new Text(composite, SWT.BORDER); - GridData data = new GridData(GridData.FILL_HORIZONTAL); - data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH; - workDirectoryField.setLayoutData(data); - workDirectoryField.setFont(font); - - Composite buttonComposite = new Composite(parent, SWT.NONE); - layout = new GridLayout(); - layout.marginWidth = 0; - layout.marginHeight = 0; - layout.numColumns = 1; - gridData = new GridData(GridData.HORIZONTAL_ALIGN_END); - buttonComposite.setLayout(layout); - buttonComposite.setLayoutData(gridData); - buttonComposite.setFont(font); - - createVerticalSpacer(buttonComposite, 1); - workspaceWorkingDirectoryButton = createPushButton(buttonComposite, ExternalToolsLaunchConfigurationMessages - .getString("ExternalToolsMainTab.Browse_Wor&kspace..._6"), null); //$NON-NLS-1$ - workspaceWorkingDirectoryButton.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent evt) { - handleWorkspaceWorkingDirectoryButtonSelected(); - } - }); - fileWorkingDirectoryButton = createPushButton(buttonComposite, ExternalToolsLaunchConfigurationMessages - .getString("ExternalToolsMainTab.Browse_F&ile_System..._7"), null); //$NON-NLS-1$ - fileWorkingDirectoryButton.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent evt) { - handleFileWorkingDirectoryButtonSelected(); - } - }); - } - - /** - * Creates the controls needed to edit the argument and prompt for argument attributes of an external tool - * - * @param parent - * the composite to create the controls in - */ - protected void createArgumentComponent(Composite parent) { - Font font = parent.getFont(); - - Label label = new Label(parent, SWT.NONE); - label.setText(ExternalToolsLaunchConfigurationMessages.getString("ExternalToolsOptionTab.&Arguments___1")); //$NON-NLS-1$ - GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - data.horizontalSpan = 2; - label.setLayoutData(data); - label.setFont(font); - - argumentField = new Text(parent, SWT.BORDER); - data = new GridData(GridData.FILL_HORIZONTAL); - data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH; - argumentField.setLayoutData(data); - argumentField.setFont(font); - argumentField.addModifyListener(new ModifyListener() { - public void modifyText(ModifyEvent e) { - updateLaunchConfigurationDialog(); - } - }); - - variableButton = createPushButton(parent, ExternalToolsLaunchConfigurationMessages - .getString("ExternalToolsOptionTab.Varia&bles..._2"), null); //$NON-NLS-1$ - variableButton.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - VariableSelectionDialog dialog = new VariableSelectionDialog(getShell()); - if (dialog.open() == SelectionDialog.OK) { - argumentField.insert(dialog.getForm().getSelectedVariable()); - } - } - }); - - Label instruction = new Label(parent, SWT.NONE); - instruction - .setText(ExternalToolsLaunchConfigurationMessages - .getString("ExternalToolsOptionTab.Note__Enclose_an_argument_containing_spaces_using_double-quotes_(__)._Not_applicable_for_variables._3")); //$NON-NLS-1$ - data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - data.horizontalSpan = 2; - instruction.setLayoutData(data); - instruction.setFont(font); - } - - /** - * Creates the controls needed to edit the run in background attribute of an external tool - * - * @param parent - * the composite to create the controls in - */ - protected void createRunBackgroundComponent(Composite parent) { - runBackgroundButton = new Button(parent, SWT.CHECK); - runBackgroundButton.setText(ExternalToolsLaunchConfigurationMessages - .getString("ExternalToolsOptionTab.Run_tool_in_bac&kground_4")); //$NON-NLS-1$ - GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - runBackgroundButton.setLayoutData(data); - runBackgroundButton.setFont(parent.getFont()); - runBackgroundButton.addSelectionListener(getSelectionAdapter()); - } - - /** - * @see org.eclipse.debug.ui.ILaunchConfigurationTab#setDefaults(org.eclipse.debug.core.ILaunchConfigurationWorkingCopy) - */ - public void setDefaults(ILaunchConfigurationWorkingCopy configuration) { - configuration.setAttribute(IExternalToolConstants.ATTR_RUN_IN_BACKGROUND, false); - } - - /** - * @see org.eclipse.debug.ui.ILaunchConfigurationTab#initializeFrom(org.eclipse.debug.core.ILaunchConfiguration) - */ - public void initializeFrom(ILaunchConfiguration configuration) { - updateLocation(configuration); - updateWorkingDirectory(configuration); - updateArgument(configuration); - updateRunBackground(configuration); - } - - protected void updateWorkingDirectory(ILaunchConfiguration configuration) { - String workingDir = ""; //$NON-NLS-1$ - try { - workingDir = configuration.getAttribute(IExternalToolConstants.ATTR_WORKING_DIRECTORY, ""); //$NON-NLS-1$ - } catch (CoreException ce) { - ExternalToolsPlugin.getDefault().log( - ExternalToolsLaunchConfigurationMessages.getString("ExternalToolsMainTab.Error_reading_configuration_10"), ce); //$NON-NLS-1$ - } - workDirectoryField.setText(workingDir); - workDirectoryField.addModifyListener(modifyListener); - - } - - protected void updateLocation(ILaunchConfiguration configuration) { - String location = ""; //$NON-NLS-1$ - try { - location = configuration.getAttribute(IExternalToolConstants.ATTR_LOCATION, ""); //$NON-NLS-1$ - } catch (CoreException ce) { - ExternalToolsPlugin.getDefault().log( - ExternalToolsLaunchConfigurationMessages.getString("ExternalToolsMainTab.Error_reading_configuration_10"), ce); //$NON-NLS-1$ - } - locationField.setText(location); - locationField.addModifyListener(modifyListener); - } - - protected void updateArgument(ILaunchConfiguration configuration) { - String arguments = ""; //$NON-NLS-1$ - try { - arguments = configuration.getAttribute(IExternalToolConstants.ATTR_TOOL_ARGUMENTS, ""); //$NON-NLS-1$ - } catch (CoreException ce) { - ExternalToolsPlugin.getDefault().log( - ExternalToolsLaunchConfigurationMessages.getString("ExternalToolsOptionTab.Error_reading_configuration_7"), ce); //$NON-NLS-1$ - } - argumentField.setText(arguments); - } - - protected void updateRunBackground(ILaunchConfiguration configuration) { - boolean runInBackgroud = true; - try { - runInBackgroud = configuration.getAttribute(IExternalToolConstants.ATTR_RUN_IN_BACKGROUND, false); - } catch (CoreException ce) { - ExternalToolsPlugin.getDefault().log( - ExternalToolsLaunchConfigurationMessages.getString("ExternalToolsOptionTab.Error_reading_configuration_7"), ce); //$NON-NLS-1$ - } - runBackgroundButton.setSelection(runInBackgroud); - } - - /** - * @see org.eclipse.debug.ui.ILaunchConfigurationTab#performApply(org.eclipse.debug.core.ILaunchConfigurationWorkingCopy) - */ - public void performApply(ILaunchConfigurationWorkingCopy configuration) { - String location = locationField.getText().trim(); - if (location.length() == 0) { - configuration.setAttribute(IExternalToolConstants.ATTR_LOCATION, (String) null); - } else { - configuration.setAttribute(IExternalToolConstants.ATTR_LOCATION, location); - } - - String workingDirectory = workDirectoryField.getText().trim(); - if (workingDirectory.length() == 0) { - configuration.setAttribute(IExternalToolConstants.ATTR_WORKING_DIRECTORY, (String) null); - } else { - configuration.setAttribute(IExternalToolConstants.ATTR_WORKING_DIRECTORY, workingDirectory); - } - - setAttribute(IExternalToolConstants.ATTR_RUN_IN_BACKGROUND, configuration, runBackgroundButton.getSelection(), false); - - String arguments = argumentField.getText().trim(); - if (arguments.length() == 0) { - configuration.setAttribute(IExternalToolConstants.ATTR_TOOL_ARGUMENTS, (String) null); - } else { - configuration.setAttribute(IExternalToolConstants.ATTR_TOOL_ARGUMENTS, arguments); - } - } - - /** - * @see org.eclipse.debug.ui.ILaunchConfigurationTab#getName() - */ - public String getName() { - return ExternalToolsLaunchConfigurationMessages.getString("ExternalToolsMainTab.&Main_17"); //$NON-NLS-1$ - } - - /** - * @see ILaunchConfigurationTab#isValid(org.eclipse.debug.core.ILaunchConfiguration) - */ - public boolean isValid(ILaunchConfiguration launchConfig) { - setErrorMessage(null); - setMessage(null); - return validateLocation() && validateWorkDirectory(); - } - - /** - * Validates the content of the location field. - */ - protected boolean validateLocation() { - String value = locationField.getText().trim(); - if (value.length() < 1) { - setErrorMessage(ExternalToolsLaunchConfigurationMessages - .getString("ExternalToolsMainTab.External_tool_location_cannot_be_empty_18")); //$NON-NLS-1$ - setMessage(null); - return false; - } - - // Translate field contents to the actual file location so we - // can check to ensure the file actually exists. - MultiStatus multiStatus = new MultiStatus(IExternalToolConstants.PLUGIN_ID, 0, "", null); //$NON-NLS-1$ - value = ToolUtil.expandFileLocation(value, ExpandVariableContext.EMPTY_CONTEXT, multiStatus); - if (!multiStatus.isOK()) { - IStatus[] children = multiStatus.getChildren(); - if (children.length > 0) { - setErrorMessage(children[0].getMessage()); - setMessage(null); - } - return false; - } - - File file = new File(value); - if (!file.exists()) { // The file does not exist. - setErrorMessage(ExternalToolsLaunchConfigurationMessages - .getString("ExternalToolsMainTab.External_tool_location_does_not_exist_19")); //$NON-NLS-1$ - return false; - } - if (!file.isFile()) { - setErrorMessage(ExternalToolsLaunchConfigurationMessages - .getString("ExternalToolsMainTab.External_tool_location_specified_is_not_a_file_20")); //$NON-NLS-1$ - return false; - } - return true; - } - - /** - * Validates the content of the working directory field. - */ - protected boolean validateWorkDirectory() { - - String value = workDirectoryField.getText().trim(); - if (value.length() > 0) { - // Translate field contents to the actual directory location so we - // can check to ensure the directory actually exists. - MultiStatus multiStatus = new MultiStatus(IExternalToolConstants.PLUGIN_ID, 0, "", null); //$NON-NLS-1$ - value = ToolUtil.expandDirectoryLocation(value, ExpandVariableContext.EMPTY_CONTEXT, multiStatus); - if (!multiStatus.isOK()) { - IStatus[] children = multiStatus.getChildren(); - if (children.length > 0) { - setErrorMessage(children[0].getMessage()); - } - return false; - } - - File file = new File(value); - if (!file.exists()) { // The directory does not exist. - setErrorMessage(ExternalToolsLaunchConfigurationMessages - .getString("ExternalToolsMainTab.External_tool_working_directory_does_not_exist_or_is_invalid_21")); //$NON-NLS-1$ - return false; - } - } - return true; - } - - protected void handleLocationButtonSelected() { - FileDialog fileDialog = new FileDialog(getShell(), SWT.NONE); - fileDialog.setFileName(locationField.getText()); - String text = fileDialog.open(); - if (text != null) { - locationField.setText(text); - } - } - - /** - * Prompts the user for a workspace location within the workspace and sets the location as a String containing the workspace_loc - * variable or null if no location was obtained from the user. - */ - protected void handleWorkspaceLocationButtonSelected() { - ResourceSelectionDialog dialog; - dialog = new ResourceSelectionDialog(getShell(), ResourcesPlugin.getWorkspace().getRoot(), - ExternalToolsLaunchConfigurationMessages.getString("ExternalToolsMainTab.Select_a_resource_22")); //$NON-NLS-1$ - dialog.open(); - Object[] results = dialog.getResult(); - if (results == null || results.length < 1) { - return; - } - IResource resource = (IResource) results[0]; - StringBuffer buf = new StringBuffer(); - ToolUtil.buildVariableTag(IExternalToolConstants.VAR_WORKSPACE_LOC, resource.getFullPath().toString(), buf); - String text = buf.toString(); - if (text != null) { - locationField.setText(text); - } - } - - /** - * Prompts the user for a working directory location within the workspace and sets the working directory as a String containing - * the workspace_loc variable or null if no location was obtained from the user. - */ - protected void handleWorkspaceWorkingDirectoryButtonSelected() { - ContainerSelectionDialog containerDialog; - containerDialog = new ContainerSelectionDialog(getShell(), ResourcesPlugin.getWorkspace().getRoot(), false, - ExternalToolsLaunchConfigurationMessages.getString("ExternalToolsMainTab.&Select_a_directory__23")); //$NON-NLS-1$ - containerDialog.open(); - Object[] resource = containerDialog.getResult(); - String text = null; - if (resource != null && resource.length > 0) { - text = ToolUtil.buildVariableTag(IExternalToolConstants.VAR_RESOURCE_LOC, ((IPath) resource[0]).toString()); - } - if (text != null) { - workDirectoryField.setText(text); - } - } - - protected void handleFileWorkingDirectoryButtonSelected() { - DirectoryDialog dialog = new DirectoryDialog(getShell(), SWT.SAVE); - dialog.setMessage(ExternalToolsLaunchConfigurationMessages.getString("ExternalToolsMainTab.&Select_a_directory__23")); //$NON-NLS-1$ - dialog.setFilterPath(workDirectoryField.getText()); - String text = dialog.open(); - if (text != null) { - workDirectoryField.setText(text); - } - } - - /** - * @see org.eclipse.debug.ui.ILaunchConfigurationTab#getImage() - */ - public Image getImage() { - return ExternalToolsImages.getImage(IExternalToolConstants.IMG_TAB_MAIN); - } - - /** - * Method getSelectionAdapter. - * - * @return SelectionListener - */ - protected SelectionListener getSelectionAdapter() { - if (selectionAdapter == null) { - selectionAdapter = new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - updateLaunchConfigurationDialog(); - } - }; - } - return selectionAdapter; - } - - private class VariableSelectionDialog extends SelectionDialog { - private ExternalToolVariableForm form; - - private VariableSelectionDialog(Shell parent) { - super(parent); - setTitle(ExternalToolsLaunchConfigurationMessages.getString("ExternalToolsOptionTab.Select_variable_10")); //$NON-NLS-1$ - } - - protected Control createDialogArea(Composite parent) { - // Create the dialog area - Composite composite = (Composite) super.createDialogArea(parent); - ExternalToolVariable[] variables = ExternalToolsPlugin.getDefault().getArgumentVariableRegistry().getArgumentVariables(); - form = new ExternalToolVariableForm(ExternalToolsLaunchConfigurationMessages - .getString("ExternalToolsOptionTab.&Choose_a_variable__11"), variables); //$NON-NLS-1$ - form.createContents(composite, new IGroupDialogPage() { - public GridData setButtonGridData(Button button) { - GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - data.heightHint = convertVerticalDLUsToPixels(IDialogConstants.BUTTON_HEIGHT); - int widthHint = convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH); - data.widthHint = Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x); - button.setLayoutData(data); - return data; - } - - public void setMessage(String newMessage, int newType) { - VariableSelectionDialog.this.setMessage(newMessage); - } - - public void updateValidState() { - } - - public int convertHeightHint(int chars) { - return convertHeightInCharsToPixels(chars); - } - - public String getMessage() { - if (!form.isValid()) { - return ExternalToolsLaunchConfigurationMessages.getString("ExternalToolsOptionTab.Invalid_selection_12"); //$NON-NLS-1$ - } - return null; - } - - public int getMessageType() { - if (!form.isValid()) { - return IMessageProvider.ERROR; - } - return 0; - } - }); - return composite; - } - - private ExternalToolVariableForm getForm() { - return form; - } - } + protected Combo locationField; + + protected Text workDirectoryField; + + protected Button fileLocationButton; + + protected Button workspaceLocationButton; + + protected Button fileWorkingDirectoryButton; + + protected Button workspaceWorkingDirectoryButton; + + protected Button runBackgroundButton; + + protected Text argumentField; + + protected Button variableButton; + + protected SelectionAdapter selectionAdapter; + + protected ModifyListener modifyListener = new ModifyListener() { + public void modifyText(ModifyEvent e) { + updateLaunchConfigurationDialog(); + } + }; + + /** + * @see org.eclipse.debug.ui.ILaunchConfigurationTab#createControl(org.eclipse.swt.widgets.Composite) + */ + public void createControl(Composite parent) { + Composite mainComposite = new Composite(parent, SWT.NONE); + setControl(mainComposite); + GridLayout layout = new GridLayout(); + layout.numColumns = 2; + GridData gridData = new GridData(GridData.FILL_HORIZONTAL); + mainComposite.setLayout(layout); + mainComposite.setLayoutData(gridData); + mainComposite.setFont(parent.getFont()); + createLocationComponent(mainComposite); + createWorkDirectoryComponent(mainComposite); + createArgumentComponent(mainComposite); + createVerticalSpacer(mainComposite, 2); + createRunBackgroundComponent(mainComposite); + } + + /** + * Creates the controls needed to edit the location attribute of an external + * tool + * + * @param parent + * the composite to create the controls in + */ + protected void createLocationComponent(Composite parent) { + Font font = parent.getFont(); + + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginWidth = 0; + layout.marginHeight = 0; + layout.numColumns = 1; + GridData gridData = new GridData(GridData.FILL_HORIZONTAL); + composite.setLayout(layout); + composite.setLayoutData(gridData); + + Label label = new Label(composite, SWT.NONE); + label.setText(ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsMainTab.&Location___2")); //$NON-NLS-1$ + label.setFont(font); + + final IPreferenceStore store = ExternalToolsPlugin.getDefault() + .getPreferenceStore(); + locationField = new Combo(composite, SWT.DROP_DOWN | SWT.BORDER); + GridData data = new GridData(GridData.FILL_HORIZONTAL); + data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH; + locationField.setLayoutData(data); + locationField.setFont(font); + locationField.add(store.getString(ExternalToolsPlugin.PHP_RUN_PREF), 0); + locationField.add(store.getString(ExternalToolsPlugin.APACHE_RUN_PREF), + 1); + locationField.add(store.getString(ExternalToolsPlugin.MYSQL_RUN_PREF), + 2); + locationField.add( + store.getString(ExternalToolsPlugin.XAMPP_START_PREF), 3); + locationField.add(store.getString(ExternalToolsPlugin.XAMPP_STOP_PREF), + 4); + Composite buttonComposite = new Composite(parent, SWT.NONE); + layout = new GridLayout(); + layout.marginWidth = 0; + layout.marginHeight = 0; + layout.numColumns = 1; + gridData = new GridData(GridData.HORIZONTAL_ALIGN_END); + buttonComposite.setLayout(layout); + buttonComposite.setLayoutData(gridData); + buttonComposite.setFont(font); + + createVerticalSpacer(buttonComposite, 1); + + workspaceLocationButton = createPushButton( + buttonComposite, + ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsMainTab.&Browse_Workspace..._3"), null); //$NON-NLS-1$ + workspaceLocationButton.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent evt) { + handleWorkspaceLocationButtonSelected(); + } + }); + fileLocationButton = createPushButton( + buttonComposite, + ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsMainTab.Brows&e_File_System..._4"), null); //$NON-NLS-1$ + fileLocationButton.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent evt) { + handleLocationButtonSelected(); + } + }); + } + + /** + * Creates the controls needed to edit the working directory attribute of an + * external tool + * + * @param parent + * the composite to create the controls in + */ + protected void createWorkDirectoryComponent(Composite parent) { + Font font = parent.getFont(); + + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginWidth = 0; + layout.marginHeight = 0; + layout.numColumns = 1; + GridData gridData = new GridData(GridData.FILL_HORIZONTAL); + composite.setLayout(layout); + composite.setLayoutData(gridData); + + Label label = new Label(composite, SWT.NONE); + label.setText(ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsMainTab.Working_&Directory__5")); //$NON-NLS-1$ + label.setFont(font); + + workDirectoryField = new Text(composite, SWT.BORDER); + GridData data = new GridData(GridData.FILL_HORIZONTAL); + data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH; + workDirectoryField.setLayoutData(data); + workDirectoryField.setFont(font); + + Composite buttonComposite = new Composite(parent, SWT.NONE); + layout = new GridLayout(); + layout.marginWidth = 0; + layout.marginHeight = 0; + layout.numColumns = 1; + gridData = new GridData(GridData.HORIZONTAL_ALIGN_END); + buttonComposite.setLayout(layout); + buttonComposite.setLayoutData(gridData); + buttonComposite.setFont(font); + + createVerticalSpacer(buttonComposite, 1); + workspaceWorkingDirectoryButton = createPushButton( + buttonComposite, + ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsMainTab.Browse_Wor&kspace..._6"), null); //$NON-NLS-1$ + workspaceWorkingDirectoryButton + .addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent evt) { + handleWorkspaceWorkingDirectoryButtonSelected(); + } + }); + fileWorkingDirectoryButton = createPushButton( + buttonComposite, + ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsMainTab.Browse_F&ile_System..._7"), null); //$NON-NLS-1$ + fileWorkingDirectoryButton.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent evt) { + handleFileWorkingDirectoryButtonSelected(); + } + }); + } + + /** + * Creates the controls needed to edit the argument and prompt for argument + * attributes of an external tool + * + * @param parent + * the composite to create the controls in + */ + protected void createArgumentComponent(Composite parent) { + Font font = parent.getFont(); + + Label label = new Label(parent, SWT.NONE); + label.setText(ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsOptionTab.&Arguments___1")); //$NON-NLS-1$ + GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + data.horizontalSpan = 2; + label.setLayoutData(data); + label.setFont(font); + + argumentField = new Text(parent, SWT.BORDER); + data = new GridData(GridData.FILL_HORIZONTAL); + data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH; + argumentField.setLayoutData(data); + argumentField.setFont(font); + argumentField.addModifyListener(new ModifyListener() { + public void modifyText(ModifyEvent e) { + updateLaunchConfigurationDialog(); + } + }); + + variableButton = createPushButton( + parent, + ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsOptionTab.Varia&bles..._2"), null); //$NON-NLS-1$ + variableButton.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + VariableSelectionDialog dialog = new VariableSelectionDialog( + getShell()); + if (dialog.open() == SelectionDialog.OK) { + argumentField + .insert(dialog.getForm().getSelectedVariable()); + } + } + }); + + Label instruction = new Label(parent, SWT.NONE); + instruction + .setText(ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsOptionTab.Note__Enclose_an_argument_containing_spaces_using_double-quotes_(__)._Not_applicable_for_variables._3")); //$NON-NLS-1$ + data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + data.horizontalSpan = 2; + instruction.setLayoutData(data); + instruction.setFont(font); + } + + /** + * Creates the controls needed to edit the run in background attribute of an + * external tool + * + * @param parent + * the composite to create the controls in + */ + protected void createRunBackgroundComponent(Composite parent) { + runBackgroundButton = new Button(parent, SWT.CHECK); + runBackgroundButton.setText(ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsOptionTab.Run_tool_in_bac&kground_4")); //$NON-NLS-1$ + GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + runBackgroundButton.setLayoutData(data); + runBackgroundButton.setFont(parent.getFont()); + runBackgroundButton.addSelectionListener(getSelectionAdapter()); + } + + /** + * @see org.eclipse.debug.ui.ILaunchConfigurationTab#setDefaults(org.eclipse.debug.core.ILaunchConfigurationWorkingCopy) + */ + public void setDefaults(ILaunchConfigurationWorkingCopy configuration) { + configuration.setAttribute( + IExternalToolConstants.ATTR_RUN_IN_BACKGROUND, false); + } + + /** + * @see org.eclipse.debug.ui.ILaunchConfigurationTab#initializeFrom(org.eclipse.debug.core.ILaunchConfiguration) + */ + public void initializeFrom(ILaunchConfiguration configuration) { + updateLocation(configuration); + updateWorkingDirectory(configuration); + updateArgument(configuration); + updateRunBackground(configuration); + } + + protected void updateWorkingDirectory(ILaunchConfiguration configuration) { + String workingDir = ""; //$NON-NLS-1$ + try { + workingDir = configuration.getAttribute( + IExternalToolConstants.ATTR_WORKING_DIRECTORY, ""); //$NON-NLS-1$ + } catch (CoreException ce) { + ExternalToolsPlugin + .getDefault() + .log( + ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsMainTab.Error_reading_configuration_10"), ce); //$NON-NLS-1$ + } + workDirectoryField.setText(workingDir); + workDirectoryField.addModifyListener(modifyListener); + + } + + protected void updateLocation(ILaunchConfiguration configuration) { + String location = ""; //$NON-NLS-1$ + try { + location = configuration.getAttribute( + IExternalToolConstants.ATTR_LOCATION, ""); //$NON-NLS-1$ + } catch (CoreException ce) { + ExternalToolsPlugin + .getDefault() + .log( + ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsMainTab.Error_reading_configuration_10"), ce); //$NON-NLS-1$ + } + locationField.setText(location); + locationField.addModifyListener(modifyListener); + } + + protected void updateArgument(ILaunchConfiguration configuration) { + String arguments = ""; //$NON-NLS-1$ + try { + arguments = configuration.getAttribute( + IExternalToolConstants.ATTR_TOOL_ARGUMENTS, ""); //$NON-NLS-1$ + } catch (CoreException ce) { + ExternalToolsPlugin + .getDefault() + .log( + ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsOptionTab.Error_reading_configuration_7"), ce); //$NON-NLS-1$ + } + argumentField.setText(arguments); + } + + protected void updateRunBackground(ILaunchConfiguration configuration) { + boolean runInBackgroud = true; + try { + runInBackgroud = configuration.getAttribute( + IExternalToolConstants.ATTR_RUN_IN_BACKGROUND, false); + } catch (CoreException ce) { + ExternalToolsPlugin + .getDefault() + .log( + ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsOptionTab.Error_reading_configuration_7"), ce); //$NON-NLS-1$ + } + runBackgroundButton.setSelection(runInBackgroud); + } + + /** + * @see org.eclipse.debug.ui.ILaunchConfigurationTab#performApply(org.eclipse.debug.core.ILaunchConfigurationWorkingCopy) + */ + public void performApply(ILaunchConfigurationWorkingCopy configuration) { + String location = locationField.getText().trim(); + if (location.length() == 0) { + configuration.setAttribute(IExternalToolConstants.ATTR_LOCATION, + (String) null); + } else { + configuration.setAttribute(IExternalToolConstants.ATTR_LOCATION, + location); + } + + String workingDirectory = workDirectoryField.getText().trim(); + if (workingDirectory.length() == 0) { + configuration.setAttribute( + IExternalToolConstants.ATTR_WORKING_DIRECTORY, + (String) null); + } else { + configuration.setAttribute( + IExternalToolConstants.ATTR_WORKING_DIRECTORY, + workingDirectory); + } + + setAttribute(IExternalToolConstants.ATTR_RUN_IN_BACKGROUND, + configuration, runBackgroundButton.getSelection(), false); + + String arguments = argumentField.getText().trim(); + if (arguments.length() == 0) { + configuration.setAttribute( + IExternalToolConstants.ATTR_TOOL_ARGUMENTS, (String) null); + } else { + configuration.setAttribute( + IExternalToolConstants.ATTR_TOOL_ARGUMENTS, arguments); + } + } + + /** + * @see org.eclipse.debug.ui.ILaunchConfigurationTab#getName() + */ + public String getName() { + return ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsMainTab.&Main_17"); //$NON-NLS-1$ + } + + /** + * @see ILaunchConfigurationTab#isValid(org.eclipse.debug.core.ILaunchConfiguration) + */ + public boolean isValid(ILaunchConfiguration launchConfig) { + setErrorMessage(null); + setMessage(null); + return validateLocation() && validateWorkDirectory(); + } + + /** + * Validates the content of the location field. + */ + protected boolean validateLocation() { + String value = locationField.getText().trim(); + if (value.length() < 1) { + setErrorMessage(ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsMainTab.External_tool_location_cannot_be_empty_18")); //$NON-NLS-1$ + setMessage(null); + return false; + } + + // Translate field contents to the actual file location so we + // can check to ensure the file actually exists. + MultiStatus multiStatus = new MultiStatus( + IExternalToolConstants.PLUGIN_ID, 0, "", null); //$NON-NLS-1$ + value = ToolUtil.expandFileLocation(value, + ExpandVariableContext.EMPTY_CONTEXT, multiStatus); + if (!multiStatus.isOK()) { + IStatus[] children = multiStatus.getChildren(); + if (children.length > 0) { + setErrorMessage(children[0].getMessage()); + setMessage(null); + } + return false; + } + + File file = new File(value); + if (!file.exists()) { // The file does not exist. + setErrorMessage(ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsMainTab.External_tool_location_does_not_exist_19")); //$NON-NLS-1$ + return false; + } + if (!file.isFile()) { + setErrorMessage(ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsMainTab.External_tool_location_specified_is_not_a_file_20")); //$NON-NLS-1$ + return false; + } + return true; + } + + /** + * Validates the content of the working directory field. + */ + protected boolean validateWorkDirectory() { + + String value = workDirectoryField.getText().trim(); + if (value.length() > 0) { + // Translate field contents to the actual directory location so we + // can check to ensure the directory actually exists. + MultiStatus multiStatus = new MultiStatus( + IExternalToolConstants.PLUGIN_ID, 0, "", null); //$NON-NLS-1$ + value = ToolUtil.expandDirectoryLocation(value, + ExpandVariableContext.EMPTY_CONTEXT, multiStatus); + if (!multiStatus.isOK()) { + IStatus[] children = multiStatus.getChildren(); + if (children.length > 0) { + setErrorMessage(children[0].getMessage()); + } + return false; + } + + File file = new File(value); + if (!file.exists()) { // The directory does not exist. + setErrorMessage(ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsMainTab.External_tool_working_directory_does_not_exist_or_is_invalid_21")); //$NON-NLS-1$ + return false; + } + } + return true; + } + + protected void handleLocationButtonSelected() { + FileDialog fileDialog = new FileDialog(getShell(), SWT.NONE); + fileDialog.setFileName(locationField.getText()); + String text = fileDialog.open(); + if (text != null) { + locationField.setText(text); + } + } + + /** + * Prompts the user for a workspace location within the workspace and sets + * the location as a String containing the workspace_loc variable or + * null if no location was obtained from the user. + */ + protected void handleWorkspaceLocationButtonSelected() { + ResourceSelectionDialog dialog; + dialog = new ResourceSelectionDialog(getShell(), ResourcesPlugin + .getWorkspace().getRoot(), + ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsMainTab.Select_a_resource_22")); //$NON-NLS-1$ + dialog.open(); + Object[] results = dialog.getResult(); + if (results == null || results.length < 1) { + return; + } + IResource resource = (IResource) results[0]; + StringBuffer buf = new StringBuffer(); + ToolUtil.buildVariableTag(IExternalToolConstants.VAR_WORKSPACE_LOC, + resource.getFullPath().toString(), buf); + String text = buf.toString(); + if (text != null) { + locationField.setText(text); + } + } + + /** + * Prompts the user for a working directory location within the workspace + * and sets the working directory as a String containing the workspace_loc + * variable or null if no location was obtained from the + * user. + */ + protected void handleWorkspaceWorkingDirectoryButtonSelected() { + ContainerSelectionDialog containerDialog; + containerDialog = new ContainerSelectionDialog( + getShell(), + ResourcesPlugin.getWorkspace().getRoot(), + false, + ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsMainTab.&Select_a_directory__23")); //$NON-NLS-1$ + containerDialog.open(); + Object[] resource = containerDialog.getResult(); + String text = null; + if (resource != null && resource.length > 0) { + text = ToolUtil.buildVariableTag( + IExternalToolConstants.VAR_RESOURCE_LOC, + ((IPath) resource[0]).toString()); + } + if (text != null) { + workDirectoryField.setText(text); + } + } + + protected void handleFileWorkingDirectoryButtonSelected() { + DirectoryDialog dialog = new DirectoryDialog(getShell(), SWT.SAVE); + dialog.setMessage(ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsMainTab.&Select_a_directory__23")); //$NON-NLS-1$ + dialog.setFilterPath(workDirectoryField.getText()); + String text = dialog.open(); + if (text != null) { + workDirectoryField.setText(text); + } + } + + /** + * @see org.eclipse.debug.ui.ILaunchConfigurationTab#getImage() + */ + public Image getImage() { + return ExternalToolsImages + .getImage(IExternalToolConstants.IMG_TAB_MAIN); + } + + /** + * Method getSelectionAdapter. + * + * @return SelectionListener + */ + protected SelectionListener getSelectionAdapter() { + if (selectionAdapter == null) { + selectionAdapter = new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + updateLaunchConfigurationDialog(); + } + }; + } + return selectionAdapter; + } + + private class VariableSelectionDialog extends SelectionDialog { + private ExternalToolVariableForm form; + + private VariableSelectionDialog(Shell parent) { + super(parent); + setTitle(ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsOptionTab.Select_variable_10")); //$NON-NLS-1$ + } + + protected Control createDialogArea(Composite parent) { + // Create the dialog area + Composite composite = (Composite) super.createDialogArea(parent); + ExternalToolVariable[] variables = ExternalToolsPlugin.getDefault() + .getArgumentVariableRegistry().getArgumentVariables(); + form = new ExternalToolVariableForm( + ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsOptionTab.&Choose_a_variable__11"), variables); //$NON-NLS-1$ + form.createContents(composite, new IGroupDialogPage() { + public GridData setButtonGridData(Button button) { + GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + data.heightHint = convertVerticalDLUsToPixels(IDialogConstants.BUTTON_HEIGHT); + int widthHint = convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH); + data.widthHint = Math.max(widthHint, button.computeSize( + SWT.DEFAULT, SWT.DEFAULT, true).x); + button.setLayoutData(data); + return data; + } + + public void setMessage(String newMessage, int newType) { + VariableSelectionDialog.this.setMessage(newMessage); + } + + public void updateValidState() { + } + + public int convertHeightHint(int chars) { + return convertHeightInCharsToPixels(chars); + } + + public String getMessage() { + if (!form.isValid()) { + return ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsOptionTab.Invalid_selection_12"); //$NON-NLS-1$ + } + return null; + } + + public int getMessageType() { + if (!form.isValid()) { + return IMessageProvider.ERROR; + } + return 0; + } + }); + return composite; + } + + private ExternalToolVariableForm getForm() { + return form; + } + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/launchConfigurations/ExternalToolsRefreshTab.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/launchConfigurations/ExternalToolsRefreshTab.java index a097c92..c0a3258 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/launchConfigurations/ExternalToolsRefreshTab.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/launchConfigurations/ExternalToolsRefreshTab.java @@ -1,11 +1,11 @@ package net.sourceforge.phpdt.externaltools.launchConfigurations; /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + **********************************************************************/ import net.sourceforge.phpdt.externaltools.group.IGroupDialogPage; import net.sourceforge.phpdt.externaltools.internal.dialog.ExternalToolVariableForm; @@ -29,20 +29,22 @@ import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; -public class ExternalToolsRefreshTab extends AbstractLaunchConfigurationTab implements IGroupDialogPage { +public class ExternalToolsRefreshTab extends AbstractLaunchConfigurationTab + implements IGroupDialogPage { private ExternalToolVariableForm variableForm; - + protected Button refreshField; + protected Button recursiveField; - + /** * @see org.eclipse.debug.ui.ILaunchConfigurationTab#createControl(org.eclipse.swt.widgets.Composite) */ public void createControl(Composite parent) { Composite mainComposite = new Composite(parent, SWT.NONE); setControl(mainComposite); - + GridLayout layout = new GridLayout(); layout.numColumns = 1; GridData gridData = new GridData(GridData.FILL_HORIZONTAL); @@ -54,16 +56,19 @@ public class ExternalToolsRefreshTab extends AbstractLaunchConfigurationTab impl createRecursiveComponent(mainComposite); createScopeComponent(mainComposite); } - + /** - * Creates the controls needed to edit the refresh recursive - * attribute of an external tool + * Creates the controls needed to edit the refresh recursive attribute of an + * external tool * - * @param parent the composite to create the controls in + * @param parent + * the composite to create the controls in */ protected void createRecursiveComponent(Composite parent) { recursiveField = new Button(parent, SWT.CHECK); - recursiveField.setText(ExternalToolsLaunchConfigurationMessages.getString("ExternalToolsRefreshTab.Recursively_&include_sub-folders_1")); //$NON-NLS-1$ + recursiveField + .setText(ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsRefreshTab.Recursively_&include_sub-folders_1")); //$NON-NLS-1$ GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); recursiveField.setLayoutData(data); recursiveField.setFont(parent.getFont()); @@ -73,16 +78,19 @@ public class ExternalToolsRefreshTab extends AbstractLaunchConfigurationTab impl } }); } - + /** - * Creates the controls needed to edit the refresh scope - * attribute of an external tool + * Creates the controls needed to edit the refresh scope attribute of an + * external tool * - * @param parent the composite to create the controls in + * @param parent + * the composite to create the controls in */ protected void createRefreshComponent(Composite parent) { refreshField = new Button(parent, SWT.CHECK); - refreshField.setText(ExternalToolsLaunchConfigurationMessages.getString("ExternalToolsRefreshTab.&Refresh_resources_after_running_tool_1")); //$NON-NLS-1$ + refreshField + .setText(ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsRefreshTab.&Refresh_resources_after_running_tool_1")); //$NON-NLS-1$ GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); refreshField.setLayoutData(data); refreshField.setFont(parent.getFont()); @@ -93,20 +101,22 @@ public class ExternalToolsRefreshTab extends AbstractLaunchConfigurationTab impl } }); } - + /** - * Creates the controls needed to edit the refresh scope variable - * attribute of an external tool + * Creates the controls needed to edit the refresh scope variable attribute + * of an external tool * - * @param parent the composite to create the controls in + * @param parent + * the composite to create the controls in */ protected void createScopeComponent(Composite parent) { - String label = ExternalToolsLaunchConfigurationMessages.getString("ExternalToolsRefreshTab.Choose_scope_v&ariable___2"); //$NON-NLS-1$ - ExternalToolVariable[] vars = ExternalToolsPlugin.getDefault().getRefreshVariableRegistry().getRefreshVariables(); + String label = ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsRefreshTab.Choose_scope_v&ariable___2"); //$NON-NLS-1$ + ExternalToolVariable[] vars = ExternalToolsPlugin.getDefault() + .getRefreshVariableRegistry().getRefreshVariables(); variableForm = new ExternalToolVariableForm(label, vars); variableForm.createContents(parent, this); } - /** * @see org.eclipse.debug.ui.ILaunchConfigurationTab#setDefaults(org.eclipse.debug.core.ILaunchConfigurationWorkingCopy) @@ -122,52 +132,74 @@ public class ExternalToolsRefreshTab extends AbstractLaunchConfigurationTab impl updateRecursive(configuration); updateScope(configuration); } + /** * Method udpateScope. + * * @param configuration */ private void updateScope(ILaunchConfiguration configuration) { String scope = null; try { - scope= configuration.getAttribute(IExternalToolConstants.ATTR_REFRESH_SCOPE, (String)null); + scope = configuration.getAttribute( + IExternalToolConstants.ATTR_REFRESH_SCOPE, (String) null); } catch (CoreException ce) { - ExternalToolsPlugin.getDefault().log(ExternalToolsLaunchConfigurationMessages.getString("ExternalToolsRefreshTab.Exception_reading_launch_configuration_3"), ce); //$NON-NLS-1$ + ExternalToolsPlugin + .getDefault() + .log( + ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsRefreshTab.Exception_reading_launch_configuration_3"), ce); //$NON-NLS-1$ } String varName = null; String varValue = null; if (scope != null) { - ToolUtil.VariableDefinition varDef = ToolUtil.extractVariableTag(scope, 0); + ToolUtil.VariableDefinition varDef = ToolUtil.extractVariableTag( + scope, 0); varName = varDef.name; varValue = varDef.argument; } variableForm.selectVariable(varName, varValue); } + /** * Method updateRecursive. + * * @param configuration */ private void updateRecursive(ILaunchConfiguration configuration) { - boolean recursive= true; + boolean recursive = true; try { - recursive= configuration.getAttribute(IExternalToolConstants.ATTR_REFRESH_RECURSIVE, false); + recursive = configuration.getAttribute( + IExternalToolConstants.ATTR_REFRESH_RECURSIVE, false); } catch (CoreException ce) { - ExternalToolsPlugin.getDefault().log(ExternalToolsLaunchConfigurationMessages.getString("ExternalToolsRefreshTab.Exception_reading_launch_configuration_3"), ce); //$NON-NLS-1$ + ExternalToolsPlugin + .getDefault() + .log( + ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsRefreshTab.Exception_reading_launch_configuration_3"), ce); //$NON-NLS-1$ } recursiveField.setSelection(recursive); } + /** * Method updateRefresh. + * * @param configuration */ private void updateRefresh(ILaunchConfiguration configuration) { - String scope= null; + String scope = null; try { - scope= configuration.getAttribute(IExternalToolConstants.ATTR_REFRESH_SCOPE, (String)null); + scope = configuration.getAttribute( + IExternalToolConstants.ATTR_REFRESH_SCOPE, (String) null); } catch (CoreException ce) { - ExternalToolsPlugin.getDefault().log(ExternalToolsLaunchConfigurationMessages.getString("ExternalToolsRefreshTab.Exception_reading_launch_configuration_3"), ce); //$NON-NLS-1$ + ExternalToolsPlugin + .getDefault() + .log( + ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsRefreshTab.Exception_reading_launch_configuration_3"), ce); //$NON-NLS-1$ } refreshField.setSelection(scope != null); - updateEnabledState(); + updateEnabledState(); } /** @@ -176,21 +208,26 @@ public class ExternalToolsRefreshTab extends AbstractLaunchConfigurationTab impl public void performApply(ILaunchConfigurationWorkingCopy configuration) { if (refreshField.getSelection()) { - configuration.setAttribute(IExternalToolConstants.ATTR_REFRESH_SCOPE, variableForm.getSelectedVariable()); + configuration.setAttribute( + IExternalToolConstants.ATTR_REFRESH_SCOPE, variableForm + .getSelectedVariable()); } else { - configuration.setAttribute(IExternalToolConstants.ATTR_REFRESH_SCOPE, (String)null); + configuration.setAttribute( + IExternalToolConstants.ATTR_REFRESH_SCOPE, (String) null); } - - setAttribute(IExternalToolConstants.ATTR_REFRESH_RECURSIVE, configuration, recursiveField.getSelection(), false); + + setAttribute(IExternalToolConstants.ATTR_REFRESH_RECURSIVE, + configuration, recursiveField.getSelection(), false); } /** * @see org.eclipse.debug.ui.ILaunchConfigurationTab#getName() */ public String getName() { - return ExternalToolsLaunchConfigurationMessages.getString("ExternalToolsRefreshTab.Refres&h_6"); //$NON-NLS-1$ + return ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsRefreshTab.Refres&h_6"); //$NON-NLS-1$ } - + /** * Updates the enablement state of the fields. */ @@ -204,6 +241,7 @@ public class ExternalToolsRefreshTab extends AbstractLaunchConfigurationTab impl } } } + /** * @see net.sourceforge.phpdt.externaltools.group.IGroupDialogPage#convertHeightHint(int) */ @@ -219,7 +257,8 @@ public class ExternalToolsRefreshTab extends AbstractLaunchConfigurationTab impl } /** - * @see net.sourceforge.phpdt.externaltools.group.IGroupDialogPage#setMessage(java.lang.String, int) + * @see net.sourceforge.phpdt.externaltools.group.IGroupDialogPage#setMessage(java.lang.String, + * int) */ public void setMessage(String newMessage, int newType) { setMessage(newMessage); @@ -243,11 +282,13 @@ public class ExternalToolsRefreshTab extends AbstractLaunchConfigurationTab impl } return IMessageProvider.NONE; } + /** * @see org.eclipse.debug.ui.ILaunchConfigurationTab#getImage() */ public Image getImage() { - return ExternalToolsImages.getImage(IExternalToolConstants.IMG_ACTION_REFRESH); + return ExternalToolsImages + .getImage(IExternalToolConstants.IMG_ACTION_REFRESH); } } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/launchConfigurations/ExternalToolsUtil.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/launchConfigurations/ExternalToolsUtil.java index c5c5555..3d4a295 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/launchConfigurations/ExternalToolsUtil.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/launchConfigurations/ExternalToolsUtil.java @@ -45,319 +45,389 @@ import org.eclipse.debug.core.ILaunchManager; */ public class ExternalToolsUtil { - private static final String LAUNCH_CONFIG_HANDLE = "LaunchConfigHandle"; //$NON-NLS-1$ + private static final String LAUNCH_CONFIG_HANDLE = "LaunchConfigHandle"; //$NON-NLS-1$ - /** - * Not to be instantiated. - */ - private ExternalToolsUtil() { - }; + /** + * Not to be instantiated. + */ + private ExternalToolsUtil() { + }; - /** - * Throws a core exception with an error status object built from the given message, lower level exception, and error code. - * - * @param message - * the status message - * @param exception - * lower level exception associated with the error, or null if none - * @param code - * error code - */ - protected static void abort(String message, Throwable exception, int code) throws CoreException { - throw new CoreException(new Status(IStatus.ERROR, IExternalToolConstants.PLUGIN_ID, code, message, exception)); - } + /** + * Throws a core exception with an error status object built from the given + * message, lower level exception, and error code. + * + * @param message + * the status message + * @param exception + * lower level exception associated with the error, or + * null if none + * @param code + * error code + */ + protected static void abort(String message, Throwable exception, int code) + throws CoreException { + throw new CoreException(new Status(IStatus.ERROR, + IExternalToolConstants.PLUGIN_ID, code, message, exception)); + } - /** - * Returns active variable context. The active variable context is used to expand variable expressions. If the workspace is - * currently being built, the context is associated with the project being built. Otherwise, the context is associated with the - * selected resource. - * - * @return active variable context - */ - public static ExpandVariableContext getVariableContext() { - return VariableContextManager.getDefault().getVariableContext(); - } + /** + * Returns active variable context. The active variable context is used to + * expand variable expressions. If the workspace is currently being built, + * the context is associated with the project being built. Otherwise, the + * context is associated with the selected resource. + * + * @return active variable context + */ + public static ExpandVariableContext getVariableContext() { + return VariableContextManager.getDefault().getVariableContext(); + } - /** - * Expands and returns the location attribute of the given launch configuration, based on the given variable context. The location - * is verified to point to an existing file, in the local file system. - * - * @param configuration - * launch configuration - * @param context - * context used to expand variables - * @return an absolute path to a file in the local file system - * @throws CoreException - * if unable to retrieve the associated launch configuration attribute, if unable to resolve any variables, or if the - * resolved location does not point to an existing file in the local file system - */ - public static IPath getLocation(ILaunchConfiguration configuration, ExpandVariableContext context) throws CoreException { - String location = configuration.getAttribute(IExternalToolConstants.ATTR_LOCATION, (String) null); - if (location == null) { - abort(MessageFormat.format(ExternalToolsLaunchConfigurationMessages - .getString("ExternalToolsUtil.Location_not_specified_by_{0}_1"), new String[] { configuration.getName() }), null, 0); //$NON-NLS-1$ - } else { - MultiStatus status = new MultiStatus(IExternalToolConstants.PLUGIN_ID, 0, ExternalToolsModelMessages - .getString("RunExternalToolAction.runProblem"), null); //$NON-NLS-1$; - String expandedLocation = ToolUtil.expandFileLocation(location, context, status); - if (status.isOK()) { - if (expandedLocation == null || expandedLocation.length() == 0) { - String msg = ExternalToolsModelMessages.format( - "DefaultRunnerContext.invalidLocation", new Object[] { configuration.getName() }); //$NON-NLS-1$ - abort(msg, null, 0); - } else { - File file = new File(expandedLocation); - if (file.isFile()) { - return new Path(expandedLocation); - } else { - String msg = ExternalToolsModelMessages.format( - "DefaultRunnerContext.invalidLocation", new Object[] { configuration.getName() }); //$NON-NLS-1$ - abort(msg, null, 0); - } - } - } else { - throw new CoreException(status); - } - } - // execution will not reach here - return null; - } + /** + * Expands and returns the location attribute of the given launch + * configuration, based on the given variable context. The location is + * verified to point to an existing file, in the local file system. + * + * @param configuration + * launch configuration + * @param context + * context used to expand variables + * @return an absolute path to a file in the local file system + * @throws CoreException + * if unable to retrieve the associated launch configuration + * attribute, if unable to resolve any variables, or if the + * resolved location does not point to an existing file in the + * local file system + */ + public static IPath getLocation(ILaunchConfiguration configuration, + ExpandVariableContext context) throws CoreException { + String location = configuration.getAttribute( + IExternalToolConstants.ATTR_LOCATION, (String) null); + if (location == null) { + abort( + MessageFormat + .format( + ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsUtil.Location_not_specified_by_{0}_1"), new String[] { configuration.getName() }), null, 0); //$NON-NLS-1$ + } else { + MultiStatus status = new MultiStatus( + IExternalToolConstants.PLUGIN_ID, + 0, + ExternalToolsModelMessages + .getString("RunExternalToolAction.runProblem"), null); //$NON-NLS-1$; + String expandedLocation = ToolUtil.expandFileLocation(location, + context, status); + if (status.isOK()) { + if (expandedLocation == null || expandedLocation.length() == 0) { + String msg = ExternalToolsModelMessages + .format( + "DefaultRunnerContext.invalidLocation", new Object[] { configuration.getName() }); //$NON-NLS-1$ + abort(msg, null, 0); + } else { + File file = new File(expandedLocation); + if (file.isFile()) { + return new Path(expandedLocation); + } else { + String msg = ExternalToolsModelMessages + .format( + "DefaultRunnerContext.invalidLocation", new Object[] { configuration.getName() }); //$NON-NLS-1$ + abort(msg, null, 0); + } + } + } else { + throw new CoreException(status); + } + } + // execution will not reach here + return null; + } - /** - * Expands and returns the working directory attribute of the given launch configuration, based on the given variable context. - * Returns null if a working directory is not specified. If specified, the working is verified to point to an - * existing directory in the local file system. - * - * @param configuration - * launch configuration - * @param context - * context used to expand variables - * @return an absolute path to a direcoty in the local file system, or null if unspecified - * @throws CoreException - * if unable to retrieve the associated launch configuration attribute, if unable to resolve any variables, or if the - * resolved location does not point to an existing directory in the local file system - */ - public static IPath getWorkingDirectory(ILaunchConfiguration configuration, ExpandVariableContext context) throws CoreException { - String location = configuration.getAttribute(IExternalToolConstants.ATTR_WORKING_DIRECTORY, (String) null); - if (location != null) { - MultiStatus status = new MultiStatus(IExternalToolConstants.PLUGIN_ID, 0, ExternalToolsModelMessages - .getString("RunExternalToolAction.runProblem"), null); //$NON-NLS-1$; - String expandedLocation = ToolUtil.expandDirectoryLocation(location, context, status); - if (status.isOK()) { - if (expandedLocation != null && expandedLocation.length() > 0) { - File path = new File(expandedLocation); - if (path.isDirectory()) { - return new Path(expandedLocation); - } else { - String msg = ExternalToolsModelMessages.format( - "DefaultRunnerContext.invalidDirectory", new Object[] { configuration.getName() }); //$NON-NLS-1$ - abort(msg, null, 0); - } - } - } else { - throw new CoreException(status); - } - } - return null; - } + /** + * Expands and returns the working directory attribute of the given launch + * configuration, based on the given variable context. Returns + * null if a working directory is not specified. If + * specified, the working is verified to point to an existing directory in + * the local file system. + * + * @param configuration + * launch configuration + * @param context + * context used to expand variables + * @return an absolute path to a direcoty in the local file system, or + * null if unspecified + * @throws CoreException + * if unable to retrieve the associated launch configuration + * attribute, if unable to resolve any variables, or if the + * resolved location does not point to an existing directory in + * the local file system + */ + public static IPath getWorkingDirectory(ILaunchConfiguration configuration, + ExpandVariableContext context) throws CoreException { + String location = configuration.getAttribute( + IExternalToolConstants.ATTR_WORKING_DIRECTORY, (String) null); + if (location != null) { + MultiStatus status = new MultiStatus( + IExternalToolConstants.PLUGIN_ID, + 0, + ExternalToolsModelMessages + .getString("RunExternalToolAction.runProblem"), null); //$NON-NLS-1$; + String expandedLocation = ToolUtil.expandDirectoryLocation( + location, context, status); + if (status.isOK()) { + if (expandedLocation != null && expandedLocation.length() > 0) { + File path = new File(expandedLocation); + if (path.isDirectory()) { + return new Path(expandedLocation); + } else { + String msg = ExternalToolsModelMessages + .format( + "DefaultRunnerContext.invalidDirectory", new Object[] { configuration.getName() }); //$NON-NLS-1$ + abort(msg, null, 0); + } + } + } else { + throw new CoreException(status); + } + } + return null; + } - /** - * Expands and returns the arguments attribute of the given launch configuration, based on the given variable context. Returns - * null if arguments are not specified. - * - * @param configuration - * launch configuration - * @param context - * context used to expand variables - * @return an array of resolved arguments, or null if unspecified - * @throws CoreException - * if unable to retrieve the associated launch configuration attribute, or if unable to resolve any variables - */ - public static String[] getArguments(ILaunchConfiguration configuration, ExpandVariableContext context) throws CoreException { - String args = configuration.getAttribute(IExternalToolConstants.ATTR_TOOL_ARGUMENTS, (String) null); - if (args != null) { - MultiStatus status = new MultiStatus(IExternalToolConstants.PLUGIN_ID, 0, ExternalToolsModelMessages - .getString("RunExternalToolAction.runProblem"), null); //$NON-NLS-1$; - String[] expandedArgs = ToolUtil.expandArguments(args, context, status); - if (status.isOK()) { - return expandedArgs; - } else { - throw new CoreException(status); - } - } - return null; - } + /** + * Expands and returns the arguments attribute of the given launch + * configuration, based on the given variable context. Returns + * null if arguments are not specified. + * + * @param configuration + * launch configuration + * @param context + * context used to expand variables + * @return an array of resolved arguments, or null if + * unspecified + * @throws CoreException + * if unable to retrieve the associated launch configuration + * attribute, or if unable to resolve any variables + */ + public static String[] getArguments(ILaunchConfiguration configuration, + ExpandVariableContext context) throws CoreException { + String args = configuration.getAttribute( + IExternalToolConstants.ATTR_TOOL_ARGUMENTS, (String) null); + if (args != null) { + MultiStatus status = new MultiStatus( + IExternalToolConstants.PLUGIN_ID, + 0, + ExternalToolsModelMessages + .getString("RunExternalToolAction.runProblem"), null); //$NON-NLS-1$; + String[] expandedArgs = ToolUtil.expandArguments(args, context, + status); + if (status.isOK()) { + return expandedArgs; + } else { + throw new CoreException(status); + } + } + return null; + } - /** - * Returns the refresh scope specified by the given launch configuration or null if none. - * - * @param configuration - * @return refresh scope - * @throws CoreException - * if unable to access the associated attribute - */ - public static String getRefreshScope(ILaunchConfiguration configuration) throws CoreException { - return configuration.getAttribute(IExternalToolConstants.ATTR_REFRESH_SCOPE, (String) null); - } + /** + * Returns the refresh scope specified by the given launch configuration or + * null if none. + * + * @param configuration + * @return refresh scope + * @throws CoreException + * if unable to access the associated attribute + */ + public static String getRefreshScope(ILaunchConfiguration configuration) + throws CoreException { + return configuration.getAttribute( + IExternalToolConstants.ATTR_REFRESH_SCOPE, (String) null); + } - /** - * Returns whether the refresh scope specified by the given launch configuration is recursive. - * - * @param configuration - * @return whether the refresh scope is recursive - * @throws CoreException - * if unable to access the associated attribute - */ - public static boolean isRefreshRecursive(ILaunchConfiguration configuration) throws CoreException { - return configuration.getAttribute(IExternalToolConstants.ATTR_REFRESH_RECURSIVE, false); - } + /** + * Returns whether the refresh scope specified by the given launch + * configuration is recursive. + * + * @param configuration + * @return whether the refresh scope is recursive + * @throws CoreException + * if unable to access the associated attribute + */ + public static boolean isRefreshRecursive(ILaunchConfiguration configuration) + throws CoreException { + return configuration.getAttribute( + IExternalToolConstants.ATTR_REFRESH_RECURSIVE, false); + } - /** - * Refreshes the resources as specified by the given launch configuration. - * - * @param configuration - * launch configuration - * @param context - * context used to expand variables - * @param monitor - * progress monitor - * @throws CoreException - * if an exception occurrs while refreshing resources - */ - public static void refreshResources(ILaunchConfiguration configuration, ExpandVariableContext context, IProgressMonitor monitor) - throws CoreException { - String scope = getRefreshScope(configuration); - if (scope == null) - return; + /** + * Refreshes the resources as specified by the given launch configuration. + * + * @param configuration + * launch configuration + * @param context + * context used to expand variables + * @param monitor + * progress monitor + * @throws CoreException + * if an exception occurrs while refreshing resources + */ + public static void refreshResources(ILaunchConfiguration configuration, + ExpandVariableContext context, IProgressMonitor monitor) + throws CoreException { + String scope = getRefreshScope(configuration); + if (scope == null) + return; - ToolUtil.VariableDefinition varDef = ToolUtil.extractVariableTag(scope, 0); - if (varDef.start == -1 || varDef.end == -1 || varDef.name == null) { - String msg = ExternalToolsModelMessages.format( - "DefaultRunnerContext.invalidRefreshVarFormat", new Object[] { configuration.getName() }); //$NON-NLS-1$ - abort(msg, null, 0); - } + ToolUtil.VariableDefinition varDef = ToolUtil.extractVariableTag(scope, + 0); + if (varDef.start == -1 || varDef.end == -1 || varDef.name == null) { + String msg = ExternalToolsModelMessages + .format( + "DefaultRunnerContext.invalidRefreshVarFormat", new Object[] { configuration.getName() }); //$NON-NLS-1$ + abort(msg, null, 0); + } - RefreshScopeVariableRegistry registry = ExternalToolsPlugin.getDefault().getRefreshVariableRegistry(); - RefreshScopeVariable variable = registry.getRefreshVariable(varDef.name); - if (variable == null) { - String msg = ExternalToolsModelMessages.format( - "DefaultRunnerContext.noRefreshVarNamed", new Object[] { configuration.getName(), varDef.name }); //$NON-NLS-1$ - abort(msg, null, 0); - } + RefreshScopeVariableRegistry registry = ExternalToolsPlugin + .getDefault().getRefreshVariableRegistry(); + RefreshScopeVariable variable = registry + .getRefreshVariable(varDef.name); + if (variable == null) { + String msg = ExternalToolsModelMessages + .format( + "DefaultRunnerContext.noRefreshVarNamed", new Object[] { configuration.getName(), varDef.name }); //$NON-NLS-1$ + abort(msg, null, 0); + } - int depth = IResource.DEPTH_ZERO; - if (isRefreshRecursive(configuration)) - depth = IResource.DEPTH_INFINITE; + int depth = IResource.DEPTH_ZERO; + if (isRefreshRecursive(configuration)) + depth = IResource.DEPTH_INFINITE; - if (monitor.isCanceled()) - return; + if (monitor.isCanceled()) + return; - IResource[] resources = variable.getExpander().getResources(varDef.name, varDef.argument, context); - if (resources == null || resources.length == 0) - return; + IResource[] resources = variable.getExpander().getResources( + varDef.name, varDef.argument, context); + if (resources == null || resources.length == 0) + return; - monitor.beginTask(ExternalToolsModelMessages.getString("DefaultRunnerContext.refreshResources"), //$NON-NLS-1$ - resources.length); + monitor.beginTask(ExternalToolsModelMessages + .getString("DefaultRunnerContext.refreshResources"), //$NON-NLS-1$ + resources.length); - MultiStatus status = new MultiStatus(IExternalToolConstants.PLUGIN_ID, 0, ExternalToolsLaunchConfigurationMessages - .getString("ExternalToolsUtil.Exception(s)_occurred_during_refresh._2"), null); //$NON-NLS-1$ - for (int i = 0; i < resources.length; i++) { - if (monitor.isCanceled()) - break; - if (resources[i] != null && resources[i].isAccessible()) { - try { - resources[i].refreshLocal(depth, null); - } catch (CoreException e) { - status.merge(e.getStatus()); - } - } - monitor.worked(1); - } + MultiStatus status = new MultiStatus( + IExternalToolConstants.PLUGIN_ID, + 0, + ExternalToolsLaunchConfigurationMessages + .getString("ExternalToolsUtil.Exception(s)_occurred_during_refresh._2"), null); //$NON-NLS-1$ + for (int i = 0; i < resources.length; i++) { + if (monitor.isCanceled()) + break; + if (resources[i] != null && resources[i].isAccessible()) { + try { + resources[i].refreshLocal(depth, null); + } catch (CoreException e) { + status.merge(e.getStatus()); + } + } + monitor.worked(1); + } - monitor.done(); - if (!status.isOK()) { - throw new CoreException(status); - } - } + monitor.done(); + if (!status.isOK()) { + throw new CoreException(status); + } + } - /** - * Returns whether this tool is to be run in the background.. - * - * @param configuration - * @return whether this tool is to be run in the background - * @throws CoreException - * if unable to access the associated attribute - */ - public static boolean isBackground(ILaunchConfiguration configuration) throws CoreException { - return configuration.getAttribute(IExternalToolConstants.ATTR_RUN_IN_BACKGROUND, false); - } + /** + * Returns whether this tool is to be run in the background.. + * + * @param configuration + * @return whether this tool is to be run in the background + * @throws CoreException + * if unable to access the associated attribute + */ + public static boolean isBackground(ILaunchConfiguration configuration) + throws CoreException { + return configuration.getAttribute( + IExternalToolConstants.ATTR_RUN_IN_BACKGROUND, false); + } - /** - * Returns a launch configuration from the given ICommand arguments. If the given arguments are from an old-style external tool, - * an unsaved working copy will be created from the arguments and returned. - * - * @param commandArgs - * the builder ICommand arguments - * @param newName - * a new name for the config if the one in the command is invalid - * @return a launch configuration, a launch configuration working copy, or null if not possible. - */ - public static ILaunchConfiguration configFromBuildCommandArgs(Map commandArgs) { - String configHandle = (String) commandArgs.get(LAUNCH_CONFIG_HANDLE); - if (configHandle == null) { - // Probably an old-style external tool. Try to migrate. - return ExternalToolMigration.configFromArgumentMap(commandArgs); - } - try { - return DebugPlugin.getDefault().getLaunchManager().getLaunchConfiguration(configHandle); - } catch (CoreException e) { - return null; - } - } + /** + * Returns a launch configuration from the given ICommand arguments. If the + * given arguments are from an old-style external tool, an unsaved working + * copy will be created from the arguments and returned. + * + * @param commandArgs + * the builder ICommand arguments + * @param newName + * a new name for the config if the one in the command is invalid + * @return a launch configuration, a launch configuration working copy, or + * null if not possible. + */ + public static ILaunchConfiguration configFromBuildCommandArgs( + Map commandArgs) { + String configHandle = (String) commandArgs.get(LAUNCH_CONFIG_HANDLE); + if (configHandle == null) { + // Probably an old-style external tool. Try to migrate. + return ExternalToolMigration.configFromArgumentMap(commandArgs); + } + try { + return DebugPlugin.getDefault().getLaunchManager() + .getLaunchConfiguration(configHandle); + } catch (CoreException e) { + return null; + } + } - /** - * Executes an external progam and saves the LaunchConfiguration under external tools - * - * @param command - * external tools command name - * @param executable - * executable path i.e.c:\apache\apache.exe - * @param arguments - * arguments for this configuration - * @param background - * run this configuration in background mode - */ - public static void execute(String command, String executable, String arguments, boolean background) { - execute(command, executable, null, arguments, background); - } - - - public static void execute(String command, String executable, String workingDirectory, String arguments, boolean background) { - ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager(); - ILaunchConfigurationType type = manager.getLaunchConfigurationType(IExternalToolConstants.ID_PROGRAM_LAUNCH_CONFIGURATION_TYPE); + /** + * Executes an external progam and saves the LaunchConfiguration under + * external tools + * + * @param command + * external tools command name + * @param executable + * executable path i.e.c:\apache\apache.exe + * @param arguments + * arguments for this configuration + * @param background + * run this configuration in background mode + */ + public static void execute(String command, String executable, + String arguments, boolean background) { + execute(command, executable, null, arguments, background); + } - ILaunchConfigurationWorkingCopy wc = null; - try { - wc = type.newInstance(null, command); - } catch (CoreException e) { - //some exception handling - } - wc.setAttribute(IExternalToolConstants.ATTR_LOCATION, executable); - if (workingDirectory != null) { - wc.setAttribute(IExternalToolConstants.ATTR_WORKING_DIRECTORY, workingDirectory); - } - if (arguments != null) { - wc.setAttribute(IExternalToolConstants.ATTR_TOOL_ARGUMENTS, arguments); - } - wc.setAttribute(IExternalToolConstants.ATTR_RUN_IN_BACKGROUND, background); + public static void execute(String command, String executable, + String workingDirectory, String arguments, boolean background) { + ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager(); + ILaunchConfigurationType type = manager + .getLaunchConfigurationType(IExternalToolConstants.ID_PROGRAM_LAUNCH_CONFIGURATION_TYPE); - // saving will add the configuration to the external tools configurations - ILaunchConfiguration config; - try { - config = wc.doSave(); - config.launch(ILaunchManager.RUN_MODE, null); - } catch (CoreException e) { - } + ILaunchConfigurationWorkingCopy wc = null; + try { + wc = type.newInstance(null, command); + } catch (CoreException e) { + // some exception handling + } + wc.setAttribute(IExternalToolConstants.ATTR_LOCATION, executable); + if (workingDirectory != null) { + wc.setAttribute(IExternalToolConstants.ATTR_WORKING_DIRECTORY, + workingDirectory); + } + if (arguments != null) { + wc.setAttribute(IExternalToolConstants.ATTR_TOOL_ARGUMENTS, + arguments); + } + wc.setAttribute(IExternalToolConstants.ATTR_RUN_IN_BACKGROUND, + background); - } + // saving will add the configuration to the external tools + // configurations + ILaunchConfiguration config; + try { + config = wc.doSave(); + config.launch(ILaunchManager.RUN_MODE, null); + } catch (CoreException e) { + } + + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/model/IExternalToolConstants.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/model/IExternalToolConstants.java index 43bb50a..a7f2dde 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/model/IExternalToolConstants.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/model/IExternalToolConstants.java @@ -1,13 +1,13 @@ package net.sourceforge.phpdt.externaltools.model; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -� -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ /** * Defines the constants available for client use. @@ -17,7 +17,8 @@ Contributors: */ public interface IExternalToolConstants { /** - * Plugin identifier for external tools (value org.eclipse.ui.externaltools). + * Plugin identifier for external tools (value + * org.eclipse.ui.externaltools). */ public static final String PLUGIN_ID = "net.sourceforge.phpeclipse.externaltools"; //$NON-NLS-1$; @@ -27,60 +28,61 @@ public interface IExternalToolConstants { * created when duplicating an existing configuration as a project builder. */ public static final String EXTENSION_POINT_CONFIGURATION_DUPLICATION_MAPS = "configurationDuplicationMaps"; //$NON-NLS-1$ + /** - * Extension point to declare argument variables - * (value argumentVariables). + * Extension point to declare argument variables (value + * argumentVariables). */ public static final String EXTENSION_POINT_ARGUMENT_VARIABLES = "argumentVariables"; //$NON-NLS-1$ /** - * Extension point to declare file variables - * (value fileVariables). + * Extension point to declare file variables (value + * fileVariables). */ public static final String EXTENSION_POINT_FILE_VARIABLES = "fileVariables"; //$NON-NLS-1$ /** - * Extension point to declare directory variables - * (value directoryVariables). + * Extension point to declare directory variables (value + * directoryVariables). */ public static final String EXTENSION_POINT_DIRECTORY_VARIABLES = "directoryVariables"; //$NON-NLS-1$ /** - * Extension point to declare refresh scope variables - * (value refreshVariables). + * Extension point to declare refresh scope variables (value + * refreshVariables). */ public static final String EXTENSION_POINT_REFRESH_VARIABLES = "refreshVariables"; //$NON-NLS-1$ // ------- Views ------- /** - * Ant View identifier (value org.eclipse.ui.externaltools.AntView). + * Ant View identifier (value + * org.eclipse.ui.externaltools.AntView). */ - //public static final String ANT_VIEW_ID = PLUGIN_ID + ".AntView"; //$NON-NLS-1$ - + // public static final String ANT_VIEW_ID = PLUGIN_ID + ".AntView"; + // //$NON-NLS-1$ // ------- Tool Types ------- /** - * External tool type for programs such as executables, batch files, - * shell scripts, etc (value programType). + * External tool type for programs such as executables, batch files, shell + * scripts, etc (value programType). */ public static final String TOOL_TYPE_PROGRAM = "programType"; //$NON-NLS-1$; /** * External tool type for Ant build files (value antBuildType). */ - //public static final String TOOL_TYPE_ANT_BUILD = "antBuildType"; //$NON-NLS-1$; - + // public static final String TOOL_TYPE_ANT_BUILD = "antBuildType"; + // //$NON-NLS-1$; // ------- Variables ------- - /** - * Variable that expands to the absolute path on the system's hard drive - * to the workspace directory (value workspace_loc). + * Variable that expands to the absolute path on the system's hard drive to + * the workspace directory (value workspace_loc). */ public static final String VAR_WORKSPACE_LOC = "workspace_loc"; //$NON-NLS-1$ /** - * Variable that expands to the absolute path on the system's hard drive - * to a project's directory (value project_loc). + * Variable that expands to the absolute path on the system's hard drive to + * a project's directory (value project_loc). */ public static final String VAR_PROJECT_LOC = "project_loc"; //$NON-NLS-1$ @@ -91,13 +93,14 @@ public interface IExternalToolConstants { public static final String VAR_PROJECT_PATH = "project_path"; //$NON-NLS-1$ /** - * Variable that expands to the name of a project (value project_name). + * Variable that expands to the name of a project (value + * project_name). */ public static final String VAR_PROJECT_NAME = "project_name"; //$NON-NLS-1$ /** - * Variable that expands to the absolute path on the system's hard drive - * to a resource's location (value resource_loc). + * Variable that expands to the absolute path on the system's hard drive to + * a resource's location (value resource_loc). */ public static final String VAR_RESOURCE_LOC = "resource_loc"; //$NON-NLS-1$ @@ -108,13 +111,14 @@ public interface IExternalToolConstants { public static final String VAR_RESOURCE_PATH = "resource_path"; //$NON-NLS-1$ /** - * Variable that expands to the name of a resource (value resource_name). + * Variable that expands to the name of a resource (value + * resource_name). */ public static final String VAR_RESOURCE_NAME = "resource_name"; //$NON-NLS-1$ /** - * Variable that expands to the absolute path on the system's hard drive - * to a resource's containing directory (value container_loc). + * Variable that expands to the absolute path on the system's hard drive to + * a resource's containing directory (value container_loc). */ public static final String VAR_CONTAINER_LOC = "container_loc"; //$NON-NLS-1$ @@ -125,34 +129,39 @@ public interface IExternalToolConstants { public static final String VAR_CONTAINER_PATH = "container_path"; //$NON-NLS-1$ /** - * Variable that expands to the name of a resource's parent (value container_name). + * Variable that expands to the name of a resource's parent (value + * container_name). */ public static final String VAR_CONTAINER_NAME = "container_name"; //$NON-NLS-1$ /** - * Variable that expands to the type of build (value build_type). See - * BUILD_TYPE_* constants for possible values. + * Variable that expands to the type of build (value build_type). + * See BUILD_TYPE_* constants for possible values. */ public static final String VAR_BUILD_TYPE = "build_type"; //$NON-NLS-1$ /** - * Variable that expands to the current editor cursor column (value editor_cur_col). + * Variable that expands to the current editor cursor column (value + * editor_cur_col). */ public static final String VAR_EDITOR_CUR_COL = "editor_cur_col"; //$NON-NLS-1$ /** - * Variable that expands to the current editor cursor line (value editor_cur_line). + * Variable that expands to the current editor cursor line (value + * editor_cur_line). */ public static final String VAR_EDITOR_CUR_LINE = "editor_cur_line"; //$NON-NLS-1$ /** - * Variable that expands to the current editor selected text (value editor_sel_text). + * Variable that expands to the current editor selected text (value + * editor_sel_text). */ public static final String VAR_EDITOR_SEL_TEXT = "editor_sel_text"; //$NON-NLS-1$ // ------- Refresh Variables ------- /** - * Variable that expands to the workspace root object (value workspace). + * Variable that expands to the workspace root object (value + * workspace). */ public static final String VAR_WORKSPACE = "workspace"; //$NON-NLS-1$ @@ -162,7 +171,8 @@ public interface IExternalToolConstants { public static final String VAR_PROJECT = "project"; //$NON-NLS-1$ /** - * Variable that expands to the container resource (value container). + * Variable that expands to the container resource (value + * container). */ public static final String VAR_CONTAINER = "container"; //$NON-NLS-1$ @@ -172,32 +182,33 @@ public interface IExternalToolConstants { public static final String VAR_RESOURCE = "resource"; //$NON-NLS-1$ /** - * Variable that expands to the working set object (value working_set). + * Variable that expands to the working set object (value + * working_set). */ public static final String VAR_WORKING_SET = "working_set"; //$NON-NLS-1$ // ------- Build Types ------- /** - * Build type indicating an incremental project build request for - * the external tool running as a builder (value incremental). + * Build type indicating an incremental project build request for the + * external tool running as a builder (value incremental). */ public static final String BUILD_TYPE_INCREMENTAL = "incremental"; //$NON-NLS-1$ /** - * Build type indicating a full project build request for - * the external tool running as a builder (value full). + * Build type indicating a full project build request for the external tool + * running as a builder (value full). */ public static final String BUILD_TYPE_FULL = "full"; //$NON-NLS-1$ /** - * Build type indicating an automatic project build request for - * the external tool running as a builder (value incremental). + * Build type indicating an automatic project build request for the external + * tool running as a builder (value incremental). */ public static final String BUILD_TYPE_AUTO = "auto"; //$NON-NLS-1$ /** - * Build type indicating an no project build request for - * the external tool running as a builder (value none). + * Build type indicating an no project build request for the external tool + * running as a builder (value none). */ public static final String BUILD_TYPE_NONE = "none"; //$NON-NLS-1$ @@ -205,12 +216,14 @@ public interface IExternalToolConstants { /** * External tools wizard banner image */ - public static final String IMG_WIZBAN_EXTERNAL_TOOLS = PLUGIN_ID + ".IMG_WIZBAN_EXTERNAL_TOOLS"; //$NON-NLS-1$ + public static final String IMG_WIZBAN_EXTERNAL_TOOLS = PLUGIN_ID + + ".IMG_WIZBAN_EXTERNAL_TOOLS"; //$NON-NLS-1$ /** * Refresh action image */ - public static final String IMG_ACTION_REFRESH = PLUGIN_ID + ".IMG_ACTION_REFRESH"; //$NON-NLS-1$ + public static final String IMG_ACTION_REFRESH = PLUGIN_ID + + ".IMG_ACTION_REFRESH"; //$NON-NLS-1$ /** * Main tab image. @@ -225,30 +238,33 @@ public interface IExternalToolConstants { /** * Ant Targets tab image. */ - public static final String IMG_TAB_ANT_TARGETS = PLUGIN_ID + ".IMG_TAB_ANT_TARGETS"; //$NON-NLS-1$ + public static final String IMG_TAB_ANT_TARGETS = PLUGIN_ID + + ".IMG_TAB_ANT_TARGETS"; //$NON-NLS-1$ // ------- Launch configuration types -------- /** * Ant launch configuration type identifier. */ -// public static final String ID_ANT_LAUNCH_CONFIGURATION_TYPE = "org.eclipse.ant.AntLaunchConfigurationType"; //$NON-NLS-1$ - + // public static final String ID_ANT_LAUNCH_CONFIGURATION_TYPE = + // "org.eclipse.ant.AntLaunchConfigurationType"; //$NON-NLS-1$ /** * Ant builder launch configuration type identifier. Ant project builders * are of this type. */ -// public static final String ID_ANT_BUILDER_LAUNCH_CONFIGURATION_TYPE = "org.eclipse.ant.AntBuilderLaunchConfigurationType"; //$NON-NLS-1$ - + // public static final String ID_ANT_BUILDER_LAUNCH_CONFIGURATION_TYPE = + // "org.eclipse.ant.AntBuilderLaunchConfigurationType"; //$NON-NLS-1$ /** * Program launch configuration type identifier. */ - public static final String ID_PROGRAM_LAUNCH_CONFIGURATION_TYPE = PLUGIN_ID + ".ProgramLaunchConfigurationType"; //$NON-NLS-1$ - + public static final String ID_PROGRAM_LAUNCH_CONFIGURATION_TYPE = PLUGIN_ID + + ".ProgramLaunchConfigurationType"; //$NON-NLS-1$ + /** * Program builder launch configuration type identifier. Program project * builders are of this type. */ - public static final String ID_PROGRAM_BUILDER_LAUNCH_CONFIGURATION_TYPE = PLUGIN_ID + ".ProgramBuilderLaunchConfigurationType"; //$NON-NLS-1$ + public static final String ID_PROGRAM_BUILDER_LAUNCH_CONFIGURATION_TYPE = PLUGIN_ID + + ".ProgramBuilderLaunchConfigurationType"; //$NON-NLS-1$ // ------- Launch configuration category -------- /** @@ -257,6 +273,7 @@ public interface IExternalToolConstants { * launch configuration dialog should belong to this category. */ public static final String ID_EXTERNAL_TOOLS_LAUNCH_CATEGORY = "net.sourceforge.phpdt.externaltools"; //$NON-NLS-1$ + /** * Identifier for external tools launch configuration builders category. * Launch configuration types that can be added as project builders should @@ -270,19 +287,21 @@ public interface IExternalToolConstants { * tools launch configuration group corresponds to the external tools * category in run mode. */ - //public static final String ID_EXTERNAL_TOOLS_LAUNCH_GROUP = "net.sourceforge.phpdt.externaltools.launchGroup"; //$NON-NLS-1$ + // public static final String ID_EXTERNAL_TOOLS_LAUNCH_GROUP = + // "net.sourceforge.phpdt.externaltools.launchGroup"; //$NON-NLS-1$ /** * Identifier for external tools launch configuration group */ - //public static final String ID_EXTERNAL_TOOLS_BUILDER_LAUNCH_GROUP = "net.sourceforge.phpdt.externaltools.launchGroup.builder"; //$NON-NLS-1$ - + // public static final String ID_EXTERNAL_TOOLS_BUILDER_LAUNCH_GROUP = + // "net.sourceforge.phpdt.externaltools.launchGroup.builder"; //$NON-NLS-1$ // ------- Common External Tool Launch Configuration Attributes ------- - /** * Boolean attribute indicating if external tool output should be captured. * Default value is false. */ - public static final String ATTR_CAPTURE_OUTPUT = PLUGIN_ID + ".ATTR_CAPTURE_OUTPUT"; //$NON-NLS-1$ + public static final String ATTR_CAPTURE_OUTPUT = PLUGIN_ID + + ".ATTR_CAPTURE_OUTPUT"; //$NON-NLS-1$ + /** * String attribute identifying the location of an external. Default value * is null. Encoding is tool specific. @@ -290,54 +309,63 @@ public interface IExternalToolConstants { public static final String ATTR_LOCATION = PLUGIN_ID + ".ATTR_LOCATION"; //$NON-NLS-1$ /** - * Boolean attribute indicating if the user should be prompted for - * arguments before running a tool. Default value is false. + * Boolean attribute indicating if the user should be prompted for arguments + * before running a tool. Default value is false. */ - public static final String ATTR_PROMPT_FOR_ARGUMENTS = PLUGIN_ID + ".ATTR_PROMPT_FOR_ARGUMENTS"; //$NON-NLS-1$ + public static final String ATTR_PROMPT_FOR_ARGUMENTS = PLUGIN_ID + + ".ATTR_PROMPT_FOR_ARGUMENTS"; //$NON-NLS-1$ /** * Boolean attribute indicating if a refresh scope is recursive. Default * value is false. */ - public static final String ATTR_REFRESH_RECURSIVE = PLUGIN_ID + ".ATTR_REFRESH_RECURSIVE"; //$NON-NLS-1$ + public static final String ATTR_REFRESH_RECURSIVE = PLUGIN_ID + + ".ATTR_REFRESH_RECURSIVE"; //$NON-NLS-1$ /** * String attribute identifying the scope of resources that should be * refreshed after an external tool is run. Default value is * null, indicating no refresh. Format is ??? */ - public static final String ATTR_REFRESH_SCOPE = PLUGIN_ID + ".ATTR_REFRESH_SCOPE"; //$NON-NLS-1$ - + public static final String ATTR_REFRESH_SCOPE = PLUGIN_ID + + ".ATTR_REFRESH_SCOPE"; //$NON-NLS-1$ + /** - * String attribute containing an array of build kinds for which an - * external tool builder should be run. + * String attribute containing an array of build kinds for which an external + * tool builder should be run. */ - public static final String ATTR_RUN_BUILD_KINDS = PLUGIN_ID + ".ATTR_RUN_BUILD_KINDS"; //$NON-NLS-1$ + public static final String ATTR_RUN_BUILD_KINDS = PLUGIN_ID + + ".ATTR_RUN_BUILD_KINDS"; //$NON-NLS-1$ /** * Boolean attribute indicating if an external tool should be run in the * background. Default value is false. */ - public static final String ATTR_RUN_IN_BACKGROUND = PLUGIN_ID + ".ATTR_RUN_IN_BACKGROUND"; //$NON-NLS-1$ - + public static final String ATTR_RUN_IN_BACKGROUND = PLUGIN_ID + + ".ATTR_RUN_IN_BACKGROUND"; //$NON-NLS-1$ + /** * Boolean attribute indicating if the console should be shown on external * tool output. Default value is false. */ - public static final String ATTR_SHOW_CONSOLE = PLUGIN_ID + ".ATTR_SHOW_CONSOLE"; //$NON-NLS-1$ + public static final String ATTR_SHOW_CONSOLE = PLUGIN_ID + + ".ATTR_SHOW_CONSOLE"; //$NON-NLS-1$ /** * String attribute containing the arguments that should be passed to the - * tool. Default value is null, and encoding is tool specific. + * tool. Default value is null, and encoding is tool + * specific. */ - public static final String ATTR_TOOL_ARGUMENTS = PLUGIN_ID + ".ATTR_TOOL_ARGUMENTS"; //$NON-NLS-1$ + public static final String ATTR_TOOL_ARGUMENTS = PLUGIN_ID + + ".ATTR_TOOL_ARGUMENTS"; //$NON-NLS-1$ /** * String attribute identifying the working directory of an external tool. * Default value is null, which indicates a default working * directory, which is tool specific. */ - public static final String ATTR_WORKING_DIRECTORY = PLUGIN_ID + ".ATTR_WORKING_DIRECTORY"; //$NON-NLS-1$ + public static final String ATTR_WORKING_DIRECTORY = PLUGIN_ID + + ".ATTR_WORKING_DIRECTORY"; //$NON-NLS-1$ // ------- Common Ant Launch Configuration Attributes ------- /** @@ -345,40 +373,43 @@ public interface IExternalToolConstants { * null which indicates that the default target is to be * executed. Format is a comma separated listing of targets. */ - public static final String ATTR_ANT_TARGETS = PLUGIN_ID + ".ATTR_ANT_TARGETS"; //$NON-NLS-1$ + public static final String ATTR_ANT_TARGETS = PLUGIN_ID + + ".ATTR_ANT_TARGETS"; //$NON-NLS-1$ /** * Map attribute indicating the Ant properties to be defined during the * build. Default value is null which indicates no additional * properties will be defined. */ - public static final String ATTR_ANT_PROPERTIES = PLUGIN_ID + ".ATTR_ANT_PROPERTIES"; //$NON-NLS-1$ + public static final String ATTR_ANT_PROPERTIES = PLUGIN_ID + + ".ATTR_ANT_PROPERTIES"; //$NON-NLS-1$ /** * String attribute indicating the Ant targets to execute. Default value is * null which indicates that no additional property files * will be defined. Format is a comma separated listing of property files. */ - //public static final String ATTR_ANT_PROPERTY_FILES = PLUGIN_ID + ".ATTR_ANT_PROPERTY_FILES"; //$NON-NLS-1$ - + // public static final String ATTR_ANT_PROPERTY_FILES = PLUGIN_ID + + // ".ATTR_ANT_PROPERTY_FILES"; //$NON-NLS-1$ /** - * String attribute indicating the custom runtime classpath to use for an Ant - * build. Default value is null which indicates that the global - * classpath is to be used. Format is a comma separated listing of URLs. - */ - //public static final String ATTR_ANT_CUSTOM_CLASSPATH = PLUGIN_ID + ".ATTR_ANT_CUSTOM_CLASSPATH"; //$NON-NLS-1$ - + * String attribute indicating the custom runtime classpath to use for an + * Ant build. Default value is null which indicates that the + * global classpath is to be used. Format is a comma separated listing of + * URLs. + */ + // public static final String ATTR_ANT_CUSTOM_CLASSPATH = PLUGIN_ID + + // ".ATTR_ANT_CUSTOM_CLASSPATH"; //$NON-NLS-1$ /** * String attribute indicating the custom Ant home to use for an Ant build. - * Default value is null which indicates that no Ant homeis to - * be set + * Default value is null which indicates that no Ant homeis + * to be set */ - //public static final String ATTR_ANT_HOME = PLUGIN_ID + ".ATTR_ANT_HOME"; //$NON-NLS-1$ - + // public static final String ATTR_ANT_HOME = PLUGIN_ID + ".ATTR_ANT_HOME"; + // //$NON-NLS-1$ /** - * Identifier for ant processes (value ant). This identifier is - * set as the value for the IProcess.ATTR_PROCESS_TYPE + * Identifier for ant processes (value ant). This identifier + * is set as the value for the IProcess.ATTR_PROCESS_TYPE * attribute in processes create by the ant launch delegate. */ - //public static final String ID_ANT_PROCESS_TYPE = "ant"; //$NON-NLS-1$ + // public static final String ID_ANT_PROCESS_TYPE = "ant"; //$NON-NLS-1$ } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/model/IRunnerLog.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/model/IRunnerLog.java index 5172569..d3a64ac 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/model/IRunnerLog.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/model/IRunnerLog.java @@ -1,42 +1,46 @@ package net.sourceforge.phpdt.externaltools.model; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -  -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ /** - * Provides an API for IExternalToolRunner implementors - * to log messages captured from the running tool's output. + * Provides an API for IExternalToolRunner implementors to log + * messages captured from the running tool's output. *

* This interface is not be extended nor implemented by clients. *

*/ public interface IRunnerLog { public static final int LEVEL_ERROR = 0; + public static final int LEVEL_WARNING = 10; + public static final int LEVEL_INFO = 20; + public static final int LEVEL_VERBOSE = 30; + public static final int LEVEL_DEBUG = 40; - + /** - * Places the specified message text into the log. Ignored - * if the specified message level is higher than the - * current filter level. + * Places the specified message text into the log. Ignored if the specified + * message level is higher than the current filter level. * - * @param message the text to add to the log - * @param level the message priority + * @param message + * the text to add to the log + * @param level + * the message priority */ public void append(String message, int level); - + /** - * Returns the current level used for filtering - * messages. Any calls to append with - * a level greater than this filter value will be + * Returns the current level used for filtering messages. Any calls to + * append with a level greater than this filter value will be * ignored. */ public int getFilterLevel(); diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/model/StringMatcher.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/model/StringMatcher.java index e4c530b..797be51 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/model/StringMatcher.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/model/StringMatcher.java @@ -1,74 +1,90 @@ package net.sourceforge.phpdt.externaltools.model; + /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + **********************************************************************/ import java.util.Vector; /** * Copied from net.sourceforge.phpdt.internal.ui.util.StringMatcher * - * A string pattern matcher, suppporting * and ? wildcards. + * A string pattern matcher, suppporting * and ? wildcards. */ public class StringMatcher { protected String fPattern; + protected int fLength; // pattern length + protected boolean fIgnoreWildCards; + protected boolean fIgnoreCase; + protected boolean fHasLeadingStar; + protected boolean fHasTrailingStar; - protected String fSegments[]; //the given pattern is split into * separated segments - /* boundary value beyond which we don't need to search in the text */ - protected int fBound= 0; + protected String fSegments[]; // the given pattern is split into * + // separated segments + /* boundary value beyond which we don't need to search in the text */ + protected int fBound = 0; - protected static final char fSingleWildCard= '\u0000'; + protected static final char fSingleWildCard = '\u0000'; public static class Position { - int start; //inclusive - int end; //exclusive + int start; // inclusive + + int end; // exclusive + public Position(int start, int end) { - this.start= start; - this.end= end; + this.start = start; + this.end = end; } + public int getStart() { return start; } + public int getEnd() { return end; } } + /** * StringMatcher constructor takes in a String object that is a simple - * pattern which may contain �*� for 0 and many characters and - * �?� for exactly one character. - * - * Literal '*' and '?' characters must be escaped in the pattern - * e.g., "\*" means literal "*", etc. - * + * pattern which may contain �*� for 0 and many characters and �?� for + * exactly one character. + * + * Literal '*' and '?' characters must be escaped in the pattern e.g., "\*" + * means literal "*", etc. + * * Escaping any other character (including the escape character itself), - * just results in that character in the pattern. - * e.g., "\a" means "a" and "\\" means "\" - * + * just results in that character in the pattern. e.g., "\a" means "a" and + * "\\" means "\" + * * If invoking the StringMatcher with string literals in Java, don't forget * escape characters are represented by "\\". - * - * @param pattern the pattern to match text against - * @param ignoreCase if true, case is ignored - * @param ignoreWildCards if true, wild cards and their escape sequences are ignored - * (everything is taken literally). + * + * @param pattern + * the pattern to match text against + * @param ignoreCase + * if true, case is ignored + * @param ignoreWildCards + * if true, wild cards and their escape sequences are ignored + * (everything is taken literally). */ - public StringMatcher(String pattern, boolean ignoreCase, boolean ignoreWildCards) { + public StringMatcher(String pattern, boolean ignoreCase, + boolean ignoreWildCards) { if (pattern == null) throw new IllegalArgumentException(); - fIgnoreCase= ignoreCase; - fIgnoreWildCards= ignoreWildCards; - fPattern= pattern; - fLength= pattern.length(); + fIgnoreCase = ignoreCase; + fIgnoreWildCards = ignoreWildCards; + fPattern = pattern; + fLength = pattern.length(); if (fIgnoreWildCards) { parseNoWildCards(); @@ -76,8 +92,10 @@ public class StringMatcher { parseWildCards(); } } + /** - * Find the first occurrence of the pattern between startstartend(exclusive). * @param text, the String object to search in * @param start, the starting index of the search range, inclusive @@ -93,56 +111,64 @@ public class StringMatcher { if (text == null) throw new IllegalArgumentException(); - int tlen= text.length(); + int tlen = text.length(); if (start < 0) - start= 0; + start = 0; if (end > tlen) - end= tlen; - if (end < 0 ||start >= end ) + end = tlen; + if (end < 0 || start >= end) return null; if (fLength == 0) return new Position(start, start); if (fIgnoreWildCards) { - int x= posIn(text, start, end); + int x = posIn(text, start, end); if (x < 0) return null; - return new Position(x, x+fLength); + return new Position(x, x + fLength); } - int segCount= fSegments.length; - if (segCount == 0)//pattern contains only '*'(s) - return new Position (start, end); + int segCount = fSegments.length; + if (segCount == 0)// pattern contains only '*'(s) + return new Position(start, end); - int curPos= start; - int matchStart= -1; + int curPos = start; + int matchStart = -1; int i; - for (i= 0; i < segCount && curPos < end; ++i) { - String current= fSegments[i]; - int nextMatch= regExpPosIn(text, curPos, end, current); - if (nextMatch < 0 ) + for (i = 0; i < segCount && curPos < end; ++i) { + String current = fSegments[i]; + int nextMatch = regExpPosIn(text, curPos, end, current); + if (nextMatch < 0) return null; - if(i == 0) - matchStart= nextMatch; - curPos= nextMatch + current.length(); + if (i == 0) + matchStart = nextMatch; + curPos = nextMatch + current.length(); } if (i < segCount) return null; return new Position(matchStart, curPos); } + /** * match the given text with the pattern + * * @return true if matched eitherwise false * @param text, a String object */ public boolean match(String text) { return match(text, 0, text.length()); } + /** - * Given the starting (inclusive) and the ending (exclusive) positions in the - * text, determine if the given substring matches with aPattern + * Given the starting (inclusive) and the ending (exclusive) positions in + * the text, determine if the given substring matches with + * aPattern + * * @return true if the specified portion of the text matches the pattern - * @param String text, a String object that contains the substring to match - * @param int start marks the starting position (inclusive) of the substring + * @param String + * text, a String object that contains the + * substring to match + * @param int + * start marks the starting position (inclusive) of the substring * @param int end marks the ending index (exclusive) of the substring */ public boolean match(String text, int start, int end) { @@ -153,123 +179,135 @@ public class StringMatcher { return false; if (fIgnoreWildCards) - return (end - start == fLength) && fPattern.regionMatches(fIgnoreCase, 0, text, start, fLength); - int segCount= fSegments.length; - if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) // pattern contains only '*'(s) + return (end - start == fLength) + && fPattern.regionMatches(fIgnoreCase, 0, text, start, + fLength); + int segCount = fSegments.length; + if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) // pattern + // contains + // only + // '*'(s) return true; if (start == end) return fLength == 0; if (fLength == 0) return start == end; - int tlen= text.length(); + int tlen = text.length(); if (start < 0) - start= 0; + start = 0; if (end > tlen) - end= tlen; + end = tlen; - int tCurPos= start; - int bound= end - fBound; - if ( bound < 0) + int tCurPos = start; + int bound = end - fBound; + if (bound < 0) return false; - int i=0; - String current= fSegments[i]; - int segLength= current.length(); + int i = 0; + String current = fSegments[i]; + int segLength = current.length(); /* process first segment */ - if (!fHasLeadingStar){ - if(!regExpRegionMatches(text, start, current, 0, segLength)) { + if (!fHasLeadingStar) { + if (!regExpRegionMatches(text, start, current, 0, segLength)) { return false; } else { ++i; - tCurPos= tCurPos + segLength; + tCurPos = tCurPos + segLength; } } /* process middle segments */ while (i < segCount) { - current= fSegments[i]; + current = fSegments[i]; int currentMatch; - int k= current.indexOf(fSingleWildCard); + int k = current.indexOf(fSingleWildCard); if (k < 0) { - currentMatch= textPosIn(text, tCurPos, end, current); + currentMatch = textPosIn(text, tCurPos, end, current); if (currentMatch < 0) return false; } else { - currentMatch= regExpPosIn(text, tCurPos, end, current); + currentMatch = regExpPosIn(text, tCurPos, end, current); if (currentMatch < 0) return false; } - tCurPos= currentMatch + current.length(); + tCurPos = currentMatch + current.length(); i++; } /* process final segment */ if (!fHasTrailingStar && tCurPos != end) { - int clen= current.length(); + int clen = current.length(); return regExpRegionMatches(text, end - clen, current, 0, clen); } - return i == segCount ; + return i == segCount; } + /** - * This method parses the given pattern into segments seperated by wildcard '*' characters. - * Since wildcards are not being used in this case, the pattern consists of a single segment. + * This method parses the given pattern into segments seperated by wildcard + * '*' characters. Since wildcards are not being used in this case, the + * pattern consists of a single segment. */ private void parseNoWildCards() { - fSegments= new String[1]; - fSegments[0]= fPattern; - fBound= fLength; + fSegments = new String[1]; + fSegments[0] = fPattern; + fBound = fLength; } + /** - * Parses the given pattern into segments seperated by wildcard '*' characters. - * @param p, a String object that is a simple regular expression with �*� and/or �?� + * Parses the given pattern into segments seperated by wildcard '*' + * characters. + * + * @param p, + * a String object that is a simple regular expression with �*� + * and/or �?� */ private void parseWildCards() { - if(fPattern.startsWith("*"))//$NON-NLS-1$ - fHasLeadingStar= true; - if(fPattern.endsWith("*")) {//$NON-NLS-1$ + if (fPattern.startsWith("*"))//$NON-NLS-1$ + fHasLeadingStar = true; + if (fPattern.endsWith("*")) {//$NON-NLS-1$ /* make sure it's not an escaped wildcard */ if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') { - fHasTrailingStar= true; + fHasTrailingStar = true; } } - Vector temp= new Vector(); + Vector temp = new Vector(); - int pos= 0; - StringBuffer buf= new StringBuffer(); + int pos = 0; + StringBuffer buf = new StringBuffer(); while (pos < fLength) { - char c= fPattern.charAt(pos++); + char c = fPattern.charAt(pos++); switch (c) { - case '\\': - if (pos >= fLength) { - buf.append(c); + case '\\': + if (pos >= fLength) { + buf.append(c); + } else { + char next = fPattern.charAt(pos++); + /* if it's an escape sequence */ + if (next == '*' || next == '?' || next == '\\') { + buf.append(next); } else { - char next= fPattern.charAt(pos++); - /* if it's an escape sequence */ - if (next == '*' || next == '?' || next == '\\') { - buf.append(next); - } else { - /* not an escape sequence, just insert literally */ - buf.append(c); - buf.append(next); - } + /* not an escape sequence, just insert literally */ + buf.append(c); + buf.append(next); } + } break; - case '*': - if (buf.length() > 0) { - /* new segment */ - temp.addElement(buf.toString()); - fBound += buf.length(); - buf.setLength(0); - } + case '*': + if (buf.length() > 0) { + /* new segment */ + temp.addElement(buf.toString()); + fBound += buf.length(); + buf.setLength(0); + } break; - case '?': - /* append special character representing single match wildcard */ - buf.append(fSingleWildCard); + case '?': + /* append special character representing single match wildcard */ + buf.append(fSingleWildCard); break; - default: - buf.append(c); + default: + buf.append(c); } } @@ -279,63 +317,77 @@ public class StringMatcher { fBound += buf.length(); } - fSegments= new String[temp.size()]; + fSegments = new String[temp.size()]; temp.copyInto(fSegments); } + /** * @param text, a string which contains no wildcard - * @param start, the starting index in the text for search, inclusive + * @param start, the starting index in the text for search, + * inclusive * @param end, the stopping point of search, exclusive - * @return the starting index in the text of the pattern , or -1 if not found + * @return the starting index in the text of the pattern , or -1 if not + * found */ - protected int posIn(String text, int start, int end) {//no wild card in pattern - int max= end - fLength; + protected int posIn(String text, int start, int end) {// no wild card in + // pattern + int max = end - fLength; if (!fIgnoreCase) { - int i= text.indexOf(fPattern, start); + int i = text.indexOf(fPattern, start); if (i == -1 || i > max) return -1; return i; } - for (int i= start; i <= max; ++i) { + for (int i = start; i <= max; ++i) { if (text.regionMatches(true, i, fPattern, 0, fLength)) return i; } return -1; } + /** - * @param text, a simple regular expression that may only contain '?'(s) - * @param start, the starting index in the text for search, inclusive + * @param text, a simple regular expression that may only + * contain '?'(s) + * @param start, the starting index in the text for search, + * inclusive * @param end, the stopping point of search, exclusive * @param p, a simple regular expression that may contains '?' * @param caseIgnored, wether the pattern is not casesensitive - * @return the starting index in the text of the pattern , or -1 if not found + * @return the starting index in the text of the pattern , or -1 if not + * found */ protected int regExpPosIn(String text, int start, int end, String p) { - int plen= p.length(); + int plen = p.length(); - int max= end - plen; - for (int i= start; i <= max; ++i) { + int max = end - plen; + for (int i = start; i <= max; ++i) { if (regExpRegionMatches(text, i, p, 0, plen)) return i; } return -1; } + /** - * + * * @return boolean * @param text, a String to match - * @param start, int that indicates the starting index of match, inclusive - * @param end int that indicates the ending index of match, exclusive - * @param p, String, String, a simple regular expression that may contain '?' - * @param ignoreCase, boolean indicating wether code>p is case sensitive + * @param start, int that indicates the starting index of + * match, inclusive + * @param end int that indicates the ending index of match, + * exclusive + * @param p, String, String, a simple regular expression that + * may contain '?' + * @param ignoreCase, boolean indicating wether code>p + * is case sensitive */ - protected boolean regExpRegionMatches(String text, int tStart, String p, int pStart, int plen) { + protected boolean regExpRegionMatches(String text, int tStart, String p, + int pStart, int plen) { while (plen-- > 0) { - char tchar= text.charAt(tStart++); - char pchar= p.charAt(pStart++); + char tchar = text.charAt(tStart++); + char pchar = p.charAt(pStart++); /* process wild cards */ if (!fIgnoreWildCards) { @@ -347,38 +399,47 @@ public class StringMatcher { if (pchar == tchar) continue; if (fIgnoreCase) { - if (Character.toUpperCase(tchar) == Character.toUpperCase(pchar)) + if (Character.toUpperCase(tchar) == Character + .toUpperCase(pchar)) continue; - // comparing after converting to upper case doesn't handle all cases; + // comparing after converting to upper case doesn't handle all + // cases; // also compare after converting to lower case - if (Character.toLowerCase(tchar) == Character.toLowerCase(pchar)) + if (Character.toLowerCase(tchar) == Character + .toLowerCase(pchar)) continue; } return false; } return true; } + /** * @param text, the string to match - * @param start, the starting index in the text for search, inclusive + * @param start, the starting index in the text for search, + * inclusive * @param end, the stopping point of search, exclusive - * @param code>p, a string that has no wildcard - * @param ignoreCase, boolean indicating wether code>p is case sensitive - * @return the starting index in the text of the pattern , or -1 if not found + * @param code>p + * , a string that has no wildcard + * @param + * ignoreCase, boolean indicating wether code>p + * is case sensitive + * @return the starting index in the text of the pattern , or -1 if not + * found */ protected int textPosIn(String text, int start, int end, String p) { - int plen= p.length(); - int max= end - plen; + int plen = p.length(); + int max = end - plen; if (!fIgnoreCase) { - int i= text.indexOf(p, start); + int i = text.indexOf(p, start); if (i == -1 || i > max) return -1; return i; } - for (int i= start; i <= max; ++i) { + for (int i = start; i <= max; ++i) { if (text.regionMatches(true, i, p, 0, plen)) return i; } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/model/ToolUtil.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/model/ToolUtil.java index 13d90a6..88002f5 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/model/ToolUtil.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/model/ToolUtil.java @@ -1,13 +1,13 @@ package net.sourceforge.phpdt.externaltools.model; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -� -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import java.util.ArrayList; @@ -30,16 +30,22 @@ public final class ToolUtil { * Argument parsing constants */ private static final char ARG_DELIMITER = ' '; //$NON-NLS-1$ + private static final char ARG_DBL_QUOTE = '"'; //$NON-NLS-1$ - + /** * Variable tag indentifiers */ private static final char VAR_TAG_START_CHAR1 = '$'; //$NON-NLS-1$ + private static final char VAR_TAG_START_CHAR2 = '{'; //$NON-NLS-1$ + private static final char VAR_TAG_END_CHAR1 = '}'; //$NON-NLS-1$ + private static final String VAR_TAG_START = "${"; //$NON-NLS-1$ + private static final String VAR_TAG_END = "}"; //$NON-NLS-1$ + private static final String VAR_TAG_SEP = ":"; //$NON-NLS-1$ /** @@ -50,27 +56,35 @@ public final class ToolUtil { } /** - * Builds a variable tag that will be auto-expanded before - * the tool is run. + * Builds a variable tag that will be auto-expanded before the tool is run. * - * @param varName the name of a known variable (one of the VAR_* constants for instance) - * @param varArgument an optional argument for the variable, null if none + * @param varName + * the name of a known variable (one of the VAR_* constants for + * instance) + * @param varArgument + * an optional argument for the variable, null if + * none */ public static String buildVariableTag(String varName, String varArgument) { StringBuffer buf = new StringBuffer(); - buildVariableTag(varName,varArgument, buf); + buildVariableTag(varName, varArgument, buf); return buf.toString(); } - + /** - * Builds a variable tag that will be auto-expanded before - * the tool is run. + * Builds a variable tag that will be auto-expanded before the tool is run. * - * @param varName the name of a known variable (one of the VAR_* constants for instance) - * @param varArgument an optional argument for the variable, null if none - * @param buffer the buffer to write the constructed variable tag + * @param varName + * the name of a known variable (one of the VAR_* constants for + * instance) + * @param varArgument + * an optional argument for the variable, null if + * none + * @param buffer + * the buffer to write the constructed variable tag */ - public static void buildVariableTag(String varName, String varArgument, StringBuffer buffer) { + public static void buildVariableTag(String varName, String varArgument, + StringBuffer buffer) { buffer.append(VAR_TAG_START); buffer.append(varName); if (varArgument != null && varArgument.length() > 0) { @@ -79,23 +93,27 @@ public final class ToolUtil { } buffer.append(VAR_TAG_END); } - + /** - * Expands all the variables found in an individual - * argument text. + * Expands all the variables found in an individual argument text. * - * @param argument one of the argument text in the list of arguments - * @param context the context to use for expanding variables - * @param status multi status to report any problems expanding variables - * @return the argument text with all variables expanded, or null if not possible + * @param argument + * one of the argument text in the list of arguments + * @param context + * the context to use for expanding variables + * @param status + * multi status to report any problems expanding variables + * @return the argument text with all variables expanded, or + * null if not possible */ - public static String expandArgument(String argument, ExpandVariableContext context, MultiStatus status) { + public static String expandArgument(String argument, + ExpandVariableContext context, MultiStatus status) { StringBuffer buffer = new StringBuffer(); - + int start = 0; while (true) { VariableDefinition varDef = extractVariableTag(argument, start); - + // No more variables found... if (varDef.start == -1) { if (start == 0) @@ -106,74 +124,92 @@ public final class ToolUtil { } // Invalid variable format - if (varDef.end == -1 || varDef.name == null || varDef.name.length() == 0) { - String msg = ExternalToolsModelMessages.getString("ToolUtil.argumentVarFormatWrong"); //$NON-NLS-1$ + if (varDef.end == -1 || varDef.name == null + || varDef.name.length() == 0) { + String msg = ExternalToolsModelMessages + .getString("ToolUtil.argumentVarFormatWrong"); //$NON-NLS-1$ status.merge(ExternalToolsPlugin.newErrorStatus(msg, null)); return null; } - // Copy text between start and variable. + // Copy text between start and variable. if (varDef.start > start) buffer.append(argument.substring(start, varDef.start)); start = varDef.end; - + // Lookup the variable if it exist ArgumentVariableRegistry registry; - registry = ExternalToolsPlugin.getDefault().getArgumentVariableRegistry(); - ArgumentVariable variable = registry.getArgumentVariable(varDef.name); + registry = ExternalToolsPlugin.getDefault() + .getArgumentVariableRegistry(); + ArgumentVariable variable = registry + .getArgumentVariable(varDef.name); if (variable == null) { - String msg = ExternalToolsModelMessages.format("ToolUtil.argumentVarMissing", new Object[] {varDef.name}); //$NON-NLS-1$ + String msg = ExternalToolsModelMessages + .format( + "ToolUtil.argumentVarMissing", new Object[] { varDef.name }); //$NON-NLS-1$ status.merge(ExternalToolsPlugin.newErrorStatus(msg, null)); return null; } - + // Expand the variable as text if possible - String text = variable.getExpander().getText(varDef.name, varDef.argument, context); + String text = variable.getExpander().getText(varDef.name, + varDef.argument, context); if (text == null) { - String msg = ExternalToolsModelMessages.format("ToolUtil.argumentVarExpandFailed", new Object[] {varDef.name}); //$NON-NLS-1$ + String msg = ExternalToolsModelMessages + .format( + "ToolUtil.argumentVarExpandFailed", new Object[] { varDef.name }); //$NON-NLS-1$ status.merge(ExternalToolsPlugin.newErrorStatus(msg, null)); return null; } buffer.append(text); } - + return buffer.toString(); } - + /** - * Returns a list of individual arguments where all - * variables have been expanded. + * Returns a list of individual arguments where all variables have been + * expanded. * - * @param arguments the arguments with leading and trailing - * spaces already removed. - * @param context the context used to expand the variable(s) - * @param status multi status to report any problems expanding variables - * @return the list of individual arguments where some elements in the - * list maybe null if problems expanding variable(s). + * @param arguments + * the arguments with leading and trailing spaces already + * removed. + * @param context + * the context used to expand the variable(s) + * @param status + * multi status to report any problems expanding variables + * @return the list of individual arguments where some elements in the list + * maybe null if problems expanding variable(s). */ - public static String[] expandArguments(String arguments, ExpandVariableContext context, MultiStatus status) { + public static String[] expandArguments(String arguments, + ExpandVariableContext context, MultiStatus status) { if (arguments == null || arguments.length() == 0) return new String[0]; String[] argList = parseArgumentsIntoList(arguments); for (int i = 0; i < argList.length; i++) argList[i] = expandArgument(argList[i], context, status); - + return argList; } - + /** - * Returns the expanded directory location if represented by a - * directory variable. Otherwise, the directory location given is - * return unless an unknown variable was detected. + * Returns the expanded directory location if represented by a directory + * variable. Otherwise, the directory location given is return unless an + * unknown variable was detected. * - * @param dirLocation a directory location either as a path or a variable - * with leading and trailing spaces already removed. - * @param context the context used to expand the variable - * @param status multi status to report any problems expanding variables - * @return the directory location as a string or null if not possible + * @param dirLocation + * a directory location either as a path or a variable with + * leading and trailing spaces already removed. + * @param context + * the context used to expand the variable + * @param status + * multi status to report any problems expanding variables + * @return the directory location as a string or null if not + * possible */ - public static String expandDirectoryLocation(String dirLocation, ExpandVariableContext context, MultiStatus status) { + public static String expandDirectoryLocation(String dirLocation, + ExpandVariableContext context, MultiStatus status) { if (dirLocation == null || dirLocation.length() == 0) return ""; //$NON-NLS-1$ @@ -181,54 +217,69 @@ public final class ToolUtil { // Return if no variable found if (varDef.start < 0) return dirLocation; - + // Disallow text before/after variable - if (varDef.start != 0 || (varDef.end < dirLocation.length() && varDef.end != -1)) { - String msg = ExternalToolsModelMessages.getString("ToolUtil.dirLocVarBetweenText"); //$NON-NLS-1$ + if (varDef.start != 0 + || (varDef.end < dirLocation.length() && varDef.end != -1)) { + String msg = ExternalToolsModelMessages + .getString("ToolUtil.dirLocVarBetweenText"); //$NON-NLS-1$ status.merge(ExternalToolsPlugin.newErrorStatus(msg, null)); return null; } - + // Invalid variable format - if (varDef.name == null || varDef.name.length() == 0 || varDef.end == -1) { - String msg = ExternalToolsModelMessages.getString("ToolUtil.dirLocVarFormatWrong"); //$NON-NLS-1$ + if (varDef.name == null || varDef.name.length() == 0 + || varDef.end == -1) { + String msg = ExternalToolsModelMessages + .getString("ToolUtil.dirLocVarFormatWrong"); //$NON-NLS-1$ status.merge(ExternalToolsPlugin.newErrorStatus(msg, null)); return null; } - + // Lookup the variable if it exist PathLocationVariableRegistry registry; - registry = ExternalToolsPlugin.getDefault().getDirectoryLocationVariableRegistry(); - PathLocationVariable variable = registry.getPathLocationVariable(varDef.name); + registry = ExternalToolsPlugin.getDefault() + .getDirectoryLocationVariableRegistry(); + PathLocationVariable variable = registry + .getPathLocationVariable(varDef.name); if (variable == null) { - String msg = ExternalToolsModelMessages.format("ToolUtil.dirLocVarMissing", new Object[] {varDef.name}); //$NON-NLS-1$ + String msg = ExternalToolsModelMessages.format( + "ToolUtil.dirLocVarMissing", new Object[] { varDef.name }); //$NON-NLS-1$ status.merge(ExternalToolsPlugin.newErrorStatus(msg, null)); return null; } - + // Expand the variable into a IPath if possible - IPath path = variable.getExpander().getPath(varDef.name, varDef.argument, context); + IPath path = variable.getExpander().getPath(varDef.name, + varDef.argument, context); if (path == null) { - String msg = ExternalToolsModelMessages.format("ToolUtil.dirLocVarExpandFailed", new Object[] {varDef.name}); //$NON-NLS-1$ + String msg = ExternalToolsModelMessages + .format( + "ToolUtil.dirLocVarExpandFailed", new Object[] { varDef.name }); //$NON-NLS-1$ status.merge(ExternalToolsPlugin.newErrorStatus(msg, null)); return null; } - + return path.toOSString(); } - + /** - * Returns the expanded file location if represented by a - * file variable. Otherwise, the file location given is - * return unless an unknown variable was detected. + * Returns the expanded file location if represented by a file variable. + * Otherwise, the file location given is return unless an unknown variable + * was detected. * - * @param fileLocation a file location either as a path or a variable - * with leading and trailing spaces already removed. - * @param context the context used to expand the variable - * @param status multi status to report any problems expanding variables - * @return the file location as a string or null if not possible + * @param fileLocation + * a file location either as a path or a variable with leading + * and trailing spaces already removed. + * @param context + * the context used to expand the variable + * @param status + * multi status to report any problems expanding variables + * @return the file location as a string or null if not + * possible */ - public static String expandFileLocation(String fileLocation, ExpandVariableContext context, MultiStatus status) { + public static String expandFileLocation(String fileLocation, + ExpandVariableContext context, MultiStatus status) { if (fileLocation == null || fileLocation.length() == 0) return ""; //$NON-NLS-1$ @@ -236,65 +287,77 @@ public final class ToolUtil { // Return if no variable found if (varDef.start < 0) return fileLocation; - + // Disallow text before/after variable - if (varDef.start != 0 || (varDef.end < fileLocation.length() && varDef.end != -1)) { - String msg = ExternalToolsModelMessages.getString("ToolUtil.fileLocVarBetweenText"); //$NON-NLS-1$ + if (varDef.start != 0 + || (varDef.end < fileLocation.length() && varDef.end != -1)) { + String msg = ExternalToolsModelMessages + .getString("ToolUtil.fileLocVarBetweenText"); //$NON-NLS-1$ status.merge(ExternalToolsPlugin.newErrorStatus(msg, null)); return null; } - + // Invalid variable format - if (varDef.name == null || varDef.name.length() == 0 || varDef.end == -1) { - String msg = ExternalToolsModelMessages.getString("ToolUtil.fileLocVarFormatWrong"); //$NON-NLS-1$ + if (varDef.name == null || varDef.name.length() == 0 + || varDef.end == -1) { + String msg = ExternalToolsModelMessages + .getString("ToolUtil.fileLocVarFormatWrong"); //$NON-NLS-1$ status.merge(ExternalToolsPlugin.newErrorStatus(msg, null)); return null; } - + // Lookup the variable if it exist PathLocationVariableRegistry registry; - registry = ExternalToolsPlugin.getDefault().getFileLocationVariableRegistry(); - PathLocationVariable variable = registry.getPathLocationVariable(varDef.name); + registry = ExternalToolsPlugin.getDefault() + .getFileLocationVariableRegistry(); + PathLocationVariable variable = registry + .getPathLocationVariable(varDef.name); if (variable == null) { - String msg = ExternalToolsModelMessages.format("ToolUtil.fileLocVarMissing", new Object[] {varDef.name}); //$NON-NLS-1$ + String msg = ExternalToolsModelMessages.format( + "ToolUtil.fileLocVarMissing", new Object[] { varDef.name }); //$NON-NLS-1$ status.merge(ExternalToolsPlugin.newErrorStatus(msg, null)); return null; } - + // Expand the variable into a IPath if possible - IPath path = variable.getExpander().getPath(varDef.name, varDef.argument, context); + IPath path = variable.getExpander().getPath(varDef.name, + varDef.argument, context); if (path == null) { - String msg = ExternalToolsModelMessages.format("The variable {0} with argument {1} could not be expanded to a valid path.", new Object[] {varDef.name, varDef.argument}); + String msg = ExternalToolsModelMessages + .format( + "The variable {0} with argument {1} could not be expanded to a valid path.", + new Object[] { varDef.name, varDef.argument }); status.merge(ExternalToolsPlugin.newErrorStatus(msg, null)); return null; } - + return path.toString(); } - + /** - * Extracts from the source text the variable tag's name - * and argument. + * Extracts from the source text the variable tag's name and argument. * - * @param text the source text to parse for a variable tag - * @param start the index in the string to start the search + * @param text + * the source text to parse for a variable tag + * @param start + * the index in the string to start the search * @return the variable definition */ public static VariableDefinition extractVariableTag(String text, int start) { VariableDefinition varDef = new VariableDefinition(); - + varDef.start = text.indexOf(VAR_TAG_START, start); if (varDef.start < 0) return varDef; start = varDef.start + VAR_TAG_START.length(); - + int end = text.indexOf(VAR_TAG_END, start); if (end < 0) return varDef; varDef.end = end + VAR_TAG_END.length(); if (end == start) return varDef; - + int mid = text.indexOf(VAR_TAG_SEP, start); if (mid < 0 || mid > end) { varDef.name = text.substring(start, end); @@ -305,140 +368,135 @@ public final class ToolUtil { if (mid < end) varDef.argument = text.substring(mid, end); } - + return varDef; } - + /** - * Parses the argument text into an array of individual - * arguments using the space character as the delimiter. - * An individual argument containing spaces must have a - * double quote (") at the start and end. Two double - * quotes together is taken to mean an embedded double - * quote in the argument text. Variables are treated as - * a single unit and therefore spaces and double quotes - * inside a variable are copied as is and not parsed. + * Parses the argument text into an array of individual arguments using the + * space character as the delimiter. An individual argument containing + * spaces must have a double quote (") at the start and end. Two double + * quotes together is taken to mean an embedded double quote in the argument + * text. Variables are treated as a single unit and therefore spaces and + * double quotes inside a variable are copied as is and not parsed. * - * @param arguments the arguments as one string + * @param arguments + * the arguments as one string * @return the array of arguments */ public static String[] parseArgumentsIntoList(String arguments) { if (arguments == null || arguments.length() == 0) return new String[0]; - + ArrayList list = new ArrayList(10); boolean inQuotes = false; boolean inVar = false; int start = 0; int end = arguments.length(); StringBuffer buffer = new StringBuffer(end); - + while (start < end) { char ch = arguments.charAt(start); start++; - + switch (ch) { - case ARG_DELIMITER : - if (inQuotes || inVar) { - buffer.append(ch); - } else { - if (buffer.length() > 0) { - list.add(buffer.toString()); - buffer.setLength(0); - } + case ARG_DELIMITER: + if (inQuotes || inVar) { + buffer.append(ch); + } else { + if (buffer.length() > 0) { + list.add(buffer.toString()); + buffer.setLength(0); } - break; + } + break; - case ARG_DBL_QUOTE : - if (inVar) { - buffer.append(ch); - } else { - if (start < end) { - if (arguments.charAt(start) == ARG_DBL_QUOTE) { - // Two quotes together represents one quote - buffer.append(ch); - start++; - } else { - inQuotes = !inQuotes; - } - } else { - // A lone quote at the end, just drop it. - inQuotes = false; - } - } - break; - - case VAR_TAG_START_CHAR1 : + case ARG_DBL_QUOTE: + if (inVar) { buffer.append(ch); - if (!inVar && start < end) { - if (arguments.charAt(start) == VAR_TAG_START_CHAR2) { - buffer.append(VAR_TAG_START_CHAR2); - inVar = true; + } else { + if (start < end) { + if (arguments.charAt(start) == ARG_DBL_QUOTE) { + // Two quotes together represents one quote + buffer.append(ch); start++; + } else { + inQuotes = !inQuotes; } + } else { + // A lone quote at the end, just drop it. + inQuotes = false; + } + } + break; + + case VAR_TAG_START_CHAR1: + buffer.append(ch); + if (!inVar && start < end) { + if (arguments.charAt(start) == VAR_TAG_START_CHAR2) { + buffer.append(VAR_TAG_START_CHAR2); + inVar = true; + start++; } - break; + } + break; - case VAR_TAG_END_CHAR1 : - buffer.append(ch); - inVar = false; - break; + case VAR_TAG_END_CHAR1: + buffer.append(ch); + inVar = false; + break; - default : - buffer.append(ch); - break; + default: + buffer.append(ch); + break; } - + } - + if (buffer.length() > 0) list.add(buffer.toString()); - + String[] results = new String[list.size()]; list.toArray(results); return results; } - /** - * Structure to represent a variable definition within a - * source string. + * Structure to represent a variable definition within a source string. */ public static final class VariableDefinition { /** - * Index in the source text where the variable started - * or -1 if no valid variable start tag - * identifier found. + * Index in the source text where the variable started or + * -1 if no valid variable start tag identifier found. */ public int start = -1; - + /** - * Index in the source text of the character following - * the end of the variable or -1 if no - * valid variable end tag found. + * Index in the source text of the character following the end of the + * variable or -1 if no valid variable end tag found. */ public int end = -1; - + /** - * The variable's name found in the source text, or - * null if no valid variable found. + * The variable's name found in the source text, or null + * if no valid variable found. */ public String name = null; - + /** * The variable's argument found in the source text, or - * null if no valid variable found or if - * the variable did not specify an argument + * null if no valid variable found or if the variable did + * not specify an argument */ public String argument = null; - + /** * Create an initialized variable definition. */ private VariableDefinition() { super(); } - + /** * Create an initialized variable definition. */ diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/preferences/ApachePrefencePage.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/preferences/ApachePrefencePage.java index 1f410f3..6cd1984 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/preferences/ApachePrefencePage.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/preferences/ApachePrefencePage.java @@ -51,7 +51,7 @@ public class ApachePrefencePage extends PreferencePage implements apacheStartSFE = new StringFieldEditor( ExternalToolsPlugin.APACHE_START_PREF, PHPPreferencesMessages .getString("PHPBasePreferencePage.apacheGroup.start"), - composite); + composite); apacheStartSFE.setPage(this); apacheStartSFE.setPreferenceStore(getPreferenceStore()); apacheStartSFE.load(); @@ -62,17 +62,16 @@ public class ApachePrefencePage extends PreferencePage implements ExternalToolsPlugin.APACHE_START_BACKGROUND, PHPPreferencesMessages .getString("PHPBasePreferencePage.apacheGroup.start_background"), - composite); + composite); apacheStartBFE.setPage(this); apacheStartBFE.setPreferenceStore(getPreferenceStore()); apacheStartBFE.load(); new Label(composite, SWT.NONE); - apacheStopSFE = new StringFieldEditor( ExternalToolsPlugin.APACHE_STOP_PREF, PHPPreferencesMessages .getString("PHPBasePreferencePage.apacheGroup.stop"), - composite); + composite); apacheStopSFE.setPage(this); apacheStopSFE.setPreferenceStore(getPreferenceStore()); apacheStopSFE.load(); @@ -83,18 +82,17 @@ public class ApachePrefencePage extends PreferencePage implements ExternalToolsPlugin.APACHE_STOP_BACKGROUND, PHPPreferencesMessages .getString("PHPBasePreferencePage.apacheGroup.stop_background"), - composite); + composite); apacheStopBFE.setPage(this); apacheStopBFE.setPreferenceStore(getPreferenceStore()); apacheStopBFE.load(); new Label(composite, SWT.NONE); - apacheRestartSFE = new StringFieldEditor( ExternalToolsPlugin.APACHE_RESTART_PREF, PHPPreferencesMessages .getString("PHPBasePreferencePage.apacheGroup.restart"), - composite); + composite); apacheRestartSFE.setPage(this); apacheRestartSFE.setPreferenceStore(getPreferenceStore()); apacheRestartSFE.load(); @@ -105,17 +103,16 @@ public class ApachePrefencePage extends PreferencePage implements ExternalToolsPlugin.APACHE_RESTART_BACKGROUND, PHPPreferencesMessages .getString("PHPBasePreferencePage.apacheGroup.restart_background"), - composite); + composite); apacheRestartBFE.setPage(this); apacheRestartBFE.setPreferenceStore(getPreferenceStore()); apacheRestartBFE.load(); new Label(composite, SWT.NONE); - apacheRunFFE = new FileFieldEditor(ExternalToolsPlugin.APACHE_RUN_PREF, PHPPreferencesMessages .getString("PHPBasePreferencePage.apacheGroup.run"), - composite); + composite); apacheRunFFE.setPage(this); apacheRunFFE.setPreferenceStore(getPreferenceStore()); apacheRunFFE.load(); diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/preferences/MySQLPreferencePage.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/preferences/MySQLPreferencePage.java index 11875a3..cf0c8aa 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/preferences/MySQLPreferencePage.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/preferences/MySQLPreferencePage.java @@ -40,7 +40,7 @@ public class MySQLPreferencePage extends PreferencePage implements ExternalToolsPlugin.MYSQL_START_BACKGROUND, PHPPreferencesMessages .getString("PHPBasePreferencePage.mySQLGroup.start_background"), - composite); + composite); mysqlStartBFE.setPage(this); mysqlStartBFE.setPreferenceStore(getPreferenceStore()); mysqlStartBFE.load(); @@ -50,7 +50,7 @@ public class MySQLPreferencePage extends PreferencePage implements mySQLCommandSFE = new StringFieldEditor(ExternalToolsPlugin.MYSQL_PREF, PHPPreferencesMessages .getString("PHPBasePreferencePage.mySQLGroup.command"), - composite); + composite); mySQLCommandSFE.setPage(this); mySQLCommandSFE.setPreferenceStore(getPreferenceStore()); mySQLCommandSFE.load(); @@ -59,7 +59,7 @@ public class MySQLPreferencePage extends PreferencePage implements mysqlRunFFE = new FileFieldEditor(ExternalToolsPlugin.MYSQL_RUN_PREF, PHPPreferencesMessages .getString("PHPBasePreferencePage.mySQLGroup.run"), - composite); + composite); mysqlRunFFE.setPage(this); mysqlRunFFE.setPreferenceStore(getPreferenceStore()); mysqlRunFFE.load(); diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/preferences/PHPExternalToolsPreferencePage.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/preferences/PHPExternalToolsPreferencePage.java index f730439..ec95211 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/preferences/PHPExternalToolsPreferencePage.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/preferences/PHPExternalToolsPreferencePage.java @@ -65,7 +65,7 @@ public class PHPExternalToolsPreferencePage extends PreferencePage implements externalParserSFE.load(); new Label(composite, SWT.NONE); - composite.setLayout(new GridLayout(3,false)); + composite.setLayout(new GridLayout(3, false)); return composite; } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/preferences/PHPPreferencesMessages.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/preferences/PHPPreferencesMessages.java index 6eecbdc..c1dbe52 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/preferences/PHPPreferencesMessages.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/preferences/PHPPreferencesMessages.java @@ -6,8 +6,11 @@ import java.util.ResourceBundle; public class PHPPreferencesMessages { - private static final String RESOURCE_BUNDLE= PHPPreferencesMessages.class.getName(); - private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); + private static final String RESOURCE_BUNDLE = PHPPreferencesMessages.class + .getName(); + + private static ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); private PHPPreferencesMessages() { } @@ -19,20 +22,20 @@ public class PHPPreferencesMessages { return '!' + key + '!'; } } - + /** * Gets a string from the resource bundle and formats it with the argument * - * @param key the string used to get the bundle value, must not be null + * @param key + * the string used to get the bundle value, must not be null */ public static String getFormattedString(String key, Object arg) { return MessageFormat.format(getString(key), new Object[] { arg }); } - /** * Gets a string from the resource bundle and formats it with arguments - */ + */ public static String getFormattedString(String key, Object[] args) { return MessageFormat.format(getString(key), args); } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/preferences/XamppPrefencePage.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/preferences/XamppPrefencePage.java index a6c001f..af1fefa 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/preferences/XamppPrefencePage.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/preferences/XamppPrefencePage.java @@ -44,7 +44,7 @@ public class XamppPrefencePage extends PreferencePage implements ExternalToolsPlugin.XAMPP_STOP_PREF, PHPPreferencesMessages .getString("PHPBasePreferencePage.apacheGroup.xampp_stop"), - composite); + composite); xamppStopSFE.setPage(this); xamppStopSFE.setPreferenceStore(getPreferenceStore()); xamppStopSFE.load(); diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/util/StringUtil.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/util/StringUtil.java index c5ef81d..75bc572 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/util/StringUtil.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/util/StringUtil.java @@ -6,29 +6,33 @@ package net.sourceforge.phpdt.externaltools.util; /** * some string utilities - * + * */ public class StringUtil { - /** - * Replace each substring of str which matches findStr with replaceStr - * - * @param str the string the substrings should be replaced in - * @param findStr the substring to be replaced - * @param replaceStr the replacement - * @return the resultstring - */ - public static final String replaceAll(String str, String findStr, String replaceStr) { - StringBuffer buf = new StringBuffer(); + /** + * Replace each substring of str which matches findStr with replaceStr + * + * @param str + * the string the substrings should be replaced in + * @param findStr + * the substring to be replaced + * @param replaceStr + * the replacement + * @return the resultstring + */ + public static final String replaceAll(String str, String findStr, + String replaceStr) { + StringBuffer buf = new StringBuffer(); + + int lastindex = 0; + int indexOf = 0; + while ((indexOf = str.indexOf(findStr, lastindex)) != -1) { + buf.append(str.substring(lastindex, indexOf)).append(replaceStr); + lastindex = indexOf + findStr.length(); + } + buf.append(str.substring(lastindex)); + return buf.toString(); + } - int lastindex = 0; - int indexOf = 0; - while ((indexOf=str.indexOf(findStr, lastindex)) != -1) { - buf.append(str.substring(lastindex, indexOf)).append(replaceStr); - lastindex = indexOf + findStr.length(); - } - buf.append(str.substring(lastindex)); - return buf.toString(); - } - } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/BuildTypeExpander.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/BuildTypeExpander.java index 306d459..7da48fd 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/BuildTypeExpander.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/BuildTypeExpander.java @@ -2,7 +2,8 @@ package net.sourceforge.phpdt.externaltools.variable; public class BuildTypeExpander implements IVariableTextExpander { - public String getText(String varTag, String varValue, ExpandVariableContext context) { + public String getText(String varTag, String varValue, + ExpandVariableContext context) { return context.getBuildType(); } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/ExpandVariableContext.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/ExpandVariableContext.java index b5eeb46..bfbf30e 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/ExpandVariableContext.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/ExpandVariableContext.java @@ -1,13 +1,13 @@ package net.sourceforge.phpdt.externaltools.variable; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -  -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import net.sourceforge.phpdt.externaltools.model.IExternalToolConstants; @@ -16,49 +16,55 @@ import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IncrementalProjectBuilder; /** - * Represents the context the external tool is running in - * that a variable uses to expand itself. + * Represents the context the external tool is running in that a variable uses + * to expand itself. */ public final class ExpandVariableContext { - public static final ExpandVariableContext EMPTY_CONTEXT = new ExpandVariableContext(null); - + public static final ExpandVariableContext EMPTY_CONTEXT = new ExpandVariableContext( + null); + private IProject project = null; + private IResource selectedResource = null; + private String buildType = IExternalToolConstants.BUILD_TYPE_NONE; - + /** - * Create a context for an external tool running - * as a builder on the given project. + * Create a context for an external tool running as a builder on the given + * project. * - * @param project the IProject being built. - * @param buildKind the kind of build being performed - * (see IncrementalProjectBuilder). + * @param project + * the IProject being built. + * @param buildKind + * the kind of build being performed (see + * IncrementalProjectBuilder). */ public ExpandVariableContext(IProject project, int buildKind) { super(); this.project = project; switch (buildKind) { - case IncrementalProjectBuilder.INCREMENTAL_BUILD : - this.buildType = IExternalToolConstants.BUILD_TYPE_INCREMENTAL; - break; - case IncrementalProjectBuilder.FULL_BUILD : - this.buildType = IExternalToolConstants.BUILD_TYPE_FULL; - break; - case IncrementalProjectBuilder.AUTO_BUILD : - this.buildType = IExternalToolConstants.BUILD_TYPE_AUTO; - break; - default : - this.buildType = IExternalToolConstants.BUILD_TYPE_NONE; - break; + case IncrementalProjectBuilder.INCREMENTAL_BUILD: + this.buildType = IExternalToolConstants.BUILD_TYPE_INCREMENTAL; + break; + case IncrementalProjectBuilder.FULL_BUILD: + this.buildType = IExternalToolConstants.BUILD_TYPE_FULL; + break; + case IncrementalProjectBuilder.AUTO_BUILD: + this.buildType = IExternalToolConstants.BUILD_TYPE_AUTO; + break; + default: + this.buildType = IExternalToolConstants.BUILD_TYPE_NONE; + break; } } - + /** - * Create a context for an external tool running - * with the given resource selected. + * Create a context for an external tool running with the given resource + * selected. * - * @param selectedResource the IResource selected - * or null if none. + * @param selectedResource + * the IResource selected or null + * if none. */ public ExpandVariableContext(IResource selectedResource) { super(); @@ -67,34 +73,35 @@ public final class ExpandVariableContext { this.project = selectedResource.getProject(); } } - + /** - * Returns the build type being performed if the - * external tool is being run as a project builder. + * Returns the build type being performed if the external tool is being run + * as a project builder. * - * @return one of the IExternalToolConstants.BUILD_TYPE_* constants. + * @return one of the IExternalToolConstants.BUILD_TYPE_* + * constants. */ public String getBuildType() { return buildType; } - + /** - * Returns the project which the variable can use. This - * will the the project being built if the tool is being - * run as a builder. Otherwise, it is the project of the - * selected resource, or null if none. + * Returns the project which the variable can use. This will the the project + * being built if the tool is being run as a builder. Otherwise, it is the + * project of the selected resource, or null if none. * * @return the IProject or null if none */ public IProject getProject() { return project; } - + /** - * Returns the resource selected at the time the tool - * is run, or null if none selected. + * Returns the resource selected at the time the tool is run, or + * null if none selected. * - * @return the IResource selected, or null if none + * @return the IResource selected, or null if + * none */ public IResource getSelectedResource() { return selectedResource; diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/FileExpander.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/FileExpander.java index 17779cb..2313ea4 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/FileExpander.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/FileExpander.java @@ -3,32 +3,35 @@ package net.sourceforge.phpdt.externaltools.variable; import org.eclipse.core.runtime.IPath; /** - * Expands a variable into the last opened PHP file + * Expands a variable into the last opened PHP file *

* This class is not intended to be extended by clients. *

*/ -public class FileExpander extends ResourceExpander { //implements IVariableTextExpander { +public class FileExpander extends ResourceExpander { // implements + // IVariableTextExpander + // { - /** - * Create an instance - */ - public FileExpander() { - super(); - } + /** + * Create an instance + */ + public FileExpander() { + super(); + } - /** - * Returns a string representation of the path to a file or directory - * for the given variable tag and value or null. - * - * @see IVariableTextExpander#getText(String, String, ExpandVariableContext) - */ - public String getText(String varTag, String varValue, ExpandVariableContext context) { - IPath path = getPath(varTag, varValue, context); - if (path != null) { - return path.toString(); - } - return ""; - } + /** + * Returns a string representation of the path to a file or directory for + * the given variable tag and value or null. + * + * @see IVariableTextExpander#getText(String, String, ExpandVariableContext) + */ + public String getText(String varTag, String varValue, + ExpandVariableContext context) { + IPath path = getPath(varTag, varValue, context); + if (path != null) { + return path.toString(); + } + return ""; + } } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/IVariableComponent.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/IVariableComponent.java index 722ffb2..eafb791 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/IVariableComponent.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/IVariableComponent.java @@ -1,13 +1,13 @@ package net.sourceforge.phpdt.externaltools.variable; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -  -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import net.sourceforge.phpdt.externaltools.group.IGroupDialogPage; @@ -15,63 +15,65 @@ import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; /** - * Represents the API for a client extending one of the - * variable extension points to provide visual editing - * of the variable. + * Represents the API for a client extending one of the variable extension + * points to provide visual editing of the variable. *

- * This interface is not to be extended by clients. Clients - * may implement this interface. + * This interface is not to be extended by clients. Clients may implement this + * interface. *

*/ public interface IVariableComponent { /** - * Returns the control to edit the variable - * value, otherwise null if no editing - * supported or if createContents has - * not been called yet + * Returns the control to edit the variable value, otherwise + * null if no editing supported or if + * createContents has not been called yet * - * @return the main control for the variable component - * or null if none + * @return the main control for the variable component or null + * if none */ public Control getControl(); - + /** - * Creates the control to edit the variable. Does nothing - * if no editing supported. + * Creates the control to edit the variable. Does nothing if no editing + * supported. * - * @param parent the composite to parent all controls to - * @param varTag the variable tag name to create the controls for - * @param page the dialog page this visual component will be part of + * @param parent + * the composite to parent all controls to + * @param varTag + * the variable tag name to create the controls for + * @param page + * the dialog page this visual component will be part of */ - public void createContents(Composite parent, String varTag, IGroupDialogPage page); + public void createContents(Composite parent, String varTag, + IGroupDialogPage page); /** - * Returns the variable value as specified by - * the user thru the visual component. + * Returns the variable value as specified by the user thru the visual + * component. * * @return the variable value as indicated by the visual component */ public String getVariableValue(); /** - * Returns whether the variable's visual component has an - * acceptable value. + * Returns whether the variable's visual component has an acceptable value. * - * @return true if all value acceptable, or false otherwise + * @return true if all value acceptable, or + * false otherwise */ public boolean isValid(); /** - * Sets the visual component to represent the - * given variable value. + * Sets the visual component to represent the given variable value. * - * @param varValue the variable value the visual component should indicate + * @param varValue + * the variable value the visual component should indicate */ public void setVariableValue(String varValue); /** - * Validates visual component current values entered by the - * user and updates it's valid state if needed + * Validates visual component current values entered by the user and updates + * it's valid state if needed */ public void validate(); } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/IVariableLocationExpander.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/IVariableLocationExpander.java index 0a79960..c2b6b3c 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/IVariableLocationExpander.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/IVariableLocationExpander.java @@ -1,39 +1,42 @@ package net.sourceforge.phpdt.externaltools.variable; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -  -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import org.eclipse.core.runtime.IPath; /** - * Responsible for expanding a variable into the location - * path of a file or directory. + * Responsible for expanding a variable into the location path of a file or + * directory. *

- * Implementation of this interface will be treated like - * a singleton. That is, only one instance will be created - * per variable extension. - *

- * This interface is not to be extended by clients. Clients - * may implement this interface. + * Implementation of this interface will be treated like a singleton. That is, + * only one instance will be created per variable extension. + *

+ *

+ * This interface is not to be extended by clients. Clients may implement this + * interface. *

*/ public interface IVariableLocationExpander { /** - * Returns the path location to a file or directory - * for the given variable tag and value. The path does - * not need to exist. + * Returns the path location to a file or directory for the given variable + * tag and value. The path does not need to exist. * - * @param varTag the variable tag name - * @param varValue the value for the variable - * @param context the context the variable should use to expand itself - * @return the IPath to a file/directory - * or null if not possible + * @param varTag + * the variable tag name + * @param varValue + * the value for the variable + * @param context + * the context the variable should use to expand itself + * @return the IPath to a file/directory or null + * if not possible */ - public IPath getPath(String varTag, String varValue, ExpandVariableContext context); + public IPath getPath(String varTag, String varValue, + ExpandVariableContext context); } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/IVariableResourceExpander.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/IVariableResourceExpander.java index a1aac20..c044e1c 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/IVariableResourceExpander.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/IVariableResourceExpander.java @@ -1,38 +1,41 @@ package net.sourceforge.phpdt.externaltools.variable; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -  -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import org.eclipse.core.resources.IResource; /** - * Responsible for expanding a variable into a list of - * IResource. + * Responsible for expanding a variable into a list of IResource. *

- * Implementation of this interface will be treated like - * a singleton. That is, only one instance will be created - * per variable extension. - *

- * This interface is not to be extended by clients. Clients - * may implement this interface. + * Implementation of this interface will be treated like a singleton. That is, + * only one instance will be created per variable extension. + *

+ *

+ * This interface is not to be extended by clients. Clients may implement this + * interface. *

*/ public interface IVariableResourceExpander { /** - * Returns the IResource list - * for the given variable tag and value. + * Returns the IResource list for the given variable tag and + * value. * - * @param varTag the variable tag name - * @param varValue the value for the variable - * @param context the context the variable should use to expand itself - * @return the list of IResource or null if not - * possible (note, elements of the list can be null) + * @param varTag + * the variable tag name + * @param varValue + * the value for the variable + * @param context + * the context the variable should use to expand itself + * @return the list of IResource or null if + * not possible (note, elements of the list can be null) */ - public IResource[] getResources(String varTag, String varValue, ExpandVariableContext context); + public IResource[] getResources(String varTag, String varValue, + ExpandVariableContext context); } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/IVariableTextExpander.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/IVariableTextExpander.java index 16ee242..77c13ec 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/IVariableTextExpander.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/IVariableTextExpander.java @@ -1,35 +1,38 @@ package net.sourceforge.phpdt.externaltools.variable; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -  -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ /** * Responsible for expanding a variable into text format. *

- * Implementation of this interface will be treated like - * a singleton. That is, only one instance will be created - * per variable extension. - *

- * This interface is not to be extended by clients. Clients - * may implement this interface. + * Implementation of this interface will be treated like a singleton. That is, + * only one instance will be created per variable extension. + *

+ *

+ * This interface is not to be extended by clients. Clients may implement this + * interface. *

*/ public interface IVariableTextExpander { /** - * Returns the expanded text for the given variable - * tag and value. + * Returns the expanded text for the given variable tag and value. * - * @param varTag the variable tag name - * @param varValue the value for the variable - * @param context the context the variable should use to expand itself - * @return the text of the expanded variable - * or null if not possible + * @param varTag + * the variable tag name + * @param varValue + * the value for the variable + * @param context + * the context the variable should use to expand itself + * @return the text of the expanded variable or null if not + * possible */ - public String getText(String varTag, String varValue, ExpandVariableContext context); + public String getText(String varTag, String varValue, + ExpandVariableContext context); } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/LocalhostExpander.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/LocalhostExpander.java index 857168b..b4883d6 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/LocalhostExpander.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/LocalhostExpander.java @@ -12,9 +12,11 @@ import org.eclipse.jface.preference.IPreferenceStore; */ public class LocalhostExpander implements IVariableTextExpander { - public String getText(String varTag, String varValue, ExpandVariableContext context) { - final IPreferenceStore webUIStore = WebUI.getDefault().getPreferenceStore(); - return webUIStore.getString(WebUI.PHP_LOCALHOST_PREF); - } + public String getText(String varTag, String varValue, + ExpandVariableContext context) { + final IPreferenceStore webUIStore = WebUI.getDefault() + .getPreferenceStore(); + return webUIStore.getString(WebUI.PHP_LOCALHOST_PREF); + } } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/ProjectNameExpander.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/ProjectNameExpander.java index 11fe671..df87812 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/ProjectNameExpander.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/ProjectNameExpander.java @@ -8,11 +8,12 @@ import org.eclipse.core.resources.IProject; public class ProjectNameExpander implements IVariableTextExpander { /** - * Returns the name of the project in the given context or - * null if there is no project in the context. + * Returns the name of the project in the given context or null + * if there is no project in the context. */ - public String getText(String varTag, String varValue, ExpandVariableContext context) { - IProject project= context.getProject(); + public String getText(String varTag, String varValue, + ExpandVariableContext context) { + IProject project = context.getProject(); if (project != null) { return project.getName(); } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/ResourceComponent.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/ResourceComponent.java index 143a6e6..a4b422b 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/ResourceComponent.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/ResourceComponent.java @@ -1,13 +1,13 @@ package net.sourceforge.phpdt.externaltools.variable; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -  -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import net.sourceforge.phpdt.externaltools.group.IGroupDialogPage; import net.sourceforge.phpdt.externaltools.internal.model.ExternalToolsModelMessages; @@ -35,22 +35,26 @@ import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; /** - * Visual component to edit the resource type variable - * value. + * Visual component to edit the resource type variable value. *

* This class is not intended to be extended by clients. *

*/ public class ResourceComponent implements IVariableComponent { private IGroupDialogPage page; + private boolean isValid = true; - + protected Group mainGroup; + protected Button selectedResourceButton; + protected Button specificResourceButton; + protected TreeViewer resourceList; + private IResource selectedResource; - + /** * Creates the component */ @@ -58,12 +62,13 @@ public class ResourceComponent implements IVariableComponent { super(); } - /* (non-Javadoc) - * Method declared on IVariableComponent. + /* + * (non-Javadoc) Method declared on IVariableComponent. */ - public void createContents(Composite parent, String varTag, IGroupDialogPage page) { + public void createContents(Composite parent, String varTag, + IGroupDialogPage page) { this.page = page; - + // main composite mainGroup = new Group(parent, SWT.NONE); GridLayout layout = new GridLayout(); @@ -75,11 +80,11 @@ public class ResourceComponent implements IVariableComponent { mainGroup.setLayoutData(gridData); mainGroup.setFont(parent.getFont()); mainGroup.setText(ToolUtil.buildVariableTag(varTag, null)); - + createSelectedResourceOption(); createSpecificResourceOption(); createResourceList(); - + updateResourceListEnablement(); } @@ -92,53 +97,55 @@ public class ResourceComponent implements IVariableComponent { data.heightHint = tree.getItemHeight() * getInitialVisibleItemCount(); tree.setLayoutData(data); tree.setFont(mainGroup.getFont()); - + resourceList = new TreeViewer(tree); - resourceList.addSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - validateResourceListSelection(); - selectedResource= (IResource) ((IStructuredSelection)event.getSelection()).getFirstElement(); - } - }); + resourceList + .addSelectionChangedListener(new ISelectionChangedListener() { + public void selectionChanged(SelectionChangedEvent event) { + validateResourceListSelection(); + selectedResource = (IResource) ((IStructuredSelection) event + .getSelection()).getFirstElement(); + } + }); resourceList.setContentProvider(new WorkbenchContentProvider()); resourceList.setLabelProvider(new WorkbenchLabelProvider()); resourceList.setInput(ResourcesPlugin.getWorkspace().getRoot()); } - + /** - * Creates the option button for using the selected - * resource. + * Creates the option button for using the selected resource. */ protected void createSelectedResourceOption() { selectedResourceButton = new Button(mainGroup, SWT.RADIO); - selectedResourceButton.setText(ExternalToolsModelMessages.getString("ResourceComponent.selectedResLabel")); //$NON-NLS-1$ + selectedResourceButton.setText(ExternalToolsModelMessages + .getString("ResourceComponent.selectedResLabel")); //$NON-NLS-1$ GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); selectedResourceButton.setLayoutData(data); selectedResourceButton.setFont(mainGroup.getFont()); selectedResourceButton.setSelection(true); } - + /** - * Creates the option button for using a specific - * resource. + * Creates the option button for using a specific resource. */ protected void createSpecificResourceOption() { specificResourceButton = new Button(mainGroup, SWT.RADIO); - specificResourceButton.setText(ExternalToolsModelMessages.getString("ResourceComponent.specificResLabel")); //$NON-NLS-1$ + specificResourceButton.setText(ExternalToolsModelMessages + .getString("ResourceComponent.specificResLabel")); //$NON-NLS-1$ GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); specificResourceButton.setLayoutData(data); specificResourceButton.setFont(mainGroup.getFont()); specificResourceButton.setSelection(false); - + specificResourceButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { updateResourceListEnablement(); } }); } - - /* (non-Javadoc) - * Method declared on IVariableComponent. + + /* + * (non-Javadoc) Method declared on IVariableComponent. */ public Control getControl() { return mainGroup; @@ -150,44 +157,46 @@ public class ResourceComponent implements IVariableComponent { protected final IGroupDialogPage getPage() { return page; } - - /* (non-Javadoc) - * Method declared on IVariableComponent. + + /* + * (non-Javadoc) Method declared on IVariableComponent. */ public String getVariableValue() { - if (selectedResourceButton != null && selectedResourceButton.getSelection()) + if (selectedResourceButton != null + && selectedResourceButton.getSelection()) return null; - + if (resourceList != null) { if (selectedResource != null) return selectedResource.getFullPath().toString(); } - + return null; } /** - * Returns the number of items to be visible in the - * resource list. This will determine the initial height. + * Returns the number of items to be visible in the resource list. This will + * determine the initial height. */ protected int getInitialVisibleItemCount() { return 10; } - - /* (non-Javadoc) - * Method declared on IVariableComponent. + + /* + * (non-Javadoc) Method declared on IVariableComponent. */ public boolean isValid() { return isValid; } /** - * Sets whether the component's values are all valid. - * Updates the components's page valid state. No action - * taken if new valid state same as current one. + * Sets whether the component's values are all valid. Updates the + * components's page valid state. No action taken if new valid state same as + * current one. * - * @param isValid true if all values valid, - * false otherwise + * @param isValid + * true if all values valid, false + * otherwise */ protected final void setIsValid(boolean isValid) { if (this.isValid != isValid) { @@ -195,17 +204,18 @@ public class ResourceComponent implements IVariableComponent { this.page.updateValidState(); } } - + /** * Updates the enablement of the resource list if needed */ protected void updateResourceListEnablement() { if (specificResourceButton != null && resourceList != null) - resourceList.getTree().setEnabled(specificResourceButton.getSelection()); + resourceList.getTree().setEnabled( + specificResourceButton.getSelection()); } - - /* (non-Javadoc) - * Method declared on IVariableComponent. + + /* + * (non-Javadoc) Method declared on IVariableComponent. */ public void setVariableValue(String varValue) { if (varValue == null || varValue.length() == 0) { @@ -222,20 +232,23 @@ public class ResourceComponent implements IVariableComponent { specificResourceButton.setSelection(true); if (resourceList != null) { resourceList.getTree().setEnabled(true); - IResource member = ResourcesPlugin.getWorkspace().getRoot().findMember(varValue); + IResource member = ResourcesPlugin.getWorkspace().getRoot() + .findMember(varValue); if (member != null) - resourceList.setSelection(new StructuredSelection(member), true); + resourceList.setSelection(new StructuredSelection(member), + true); else resourceList.setSelection(StructuredSelection.EMPTY); } } } - - /* (non-Javadoc) - * Method declared on IVariableComponent. + + /* + * (non-Javadoc) Method declared on IVariableComponent. */ public void validate() { - if (specificResourceButton != null && specificResourceButton.getSelection()) { + if (specificResourceButton != null + && specificResourceButton.getSelection()) { validateResourceListSelection(); } @@ -244,22 +257,25 @@ public class ResourceComponent implements IVariableComponent { } /** - * Returns whether that the resource list selection is valid. - * If the list was not created, returns true. + * Returns whether that the resource list selection is valid. If the list + * was not created, returns true. * - * @return true to continue validating other - * fields, false to stop. + * @return true to continue validating other fields, + * false to stop. */ protected boolean validateResourceListSelection() { if (resourceList == null) return true; if (resourceList.getSelection().isEmpty()) { - getPage().setMessage(ExternalToolsModelMessages.getString("ResourceComponent.selectionRequired"), IMessageProvider.WARNING); //$NON-NLS-1$ + getPage() + .setMessage( + ExternalToolsModelMessages + .getString("ResourceComponent.selectionRequired"), IMessageProvider.WARNING); //$NON-NLS-1$ setIsValid(false); return false; } - + return true; } } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/ResourceContainerExpander.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/ResourceContainerExpander.java index 5e8bf04..837c8bd 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/ResourceContainerExpander.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/ResourceContainerExpander.java @@ -1,19 +1,18 @@ package net.sourceforge.phpdt.externaltools.variable; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -  -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import org.eclipse.core.resources.IResource; /** - * Expands a resource's container type variable into the desired - * result format. + * Expands a resource's container type variable into the desired result format. *

* This class is not intended to be extended by clients. *

@@ -27,10 +26,10 @@ public class ResourceContainerExpander extends ResourceExpander { super(); } - /* (non-Javadoc) - * Method declared on ResourceExpander. + /* + * (non-Javadoc) Method declared on ResourceExpander. */ - /*package*/ IResource expand(String varValue, ExpandVariableContext context) { + /* package */IResource expand(String varValue, ExpandVariableContext context) { IResource resource = super.expand(varValue, context); if (resource != null) return resource.getParent(); diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/ResourceExpander.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/ResourceExpander.java index fe5cfa8..5fef23e 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/ResourceExpander.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/ResourceExpander.java @@ -1,13 +1,13 @@ package net.sourceforge.phpdt.externaltools.variable; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -� -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import net.sourceforge.phpdt.externaltools.model.IExternalToolConstants; @@ -17,13 +17,13 @@ import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; /** - * Expands a resource type variable into the desired - * result format. + * Expands a resource type variable into the desired result format. *

* This class is not intended to be extended by clients. *

*/ -public class ResourceExpander implements IVariableLocationExpander, IVariableResourceExpander, IVariableTextExpander { +public class ResourceExpander implements IVariableLocationExpander, + IVariableResourceExpander, IVariableTextExpander { /** * Create an instance @@ -35,36 +35,36 @@ public class ResourceExpander implements IVariableLocationExpander, IVariableRes /** * Expands the variable to a resource. */ - /*package*/ IResource expand(String varValue, ExpandVariableContext context) { + /* package */IResource expand(String varValue, ExpandVariableContext context) { if (varValue != null && varValue.length() > 0) { return expandToMember(varValue); } else { return expandUsingContext(context); } } - + /** - * Expands using the current context information. - * By default, return the selected resource of the - * context. + * Expands using the current context information. By default, return the + * selected resource of the context. */ - /*package*/ IResource expandUsingContext(ExpandVariableContext context) { + /* package */IResource expandUsingContext(ExpandVariableContext context) { return context.getSelectedResource(); } - + /** - * Expands the variable value to a resource. The value - * will not be null nor empty. By default, - * lookup the member from the workspace root. + * Expands the variable value to a resource. The value will not be + * null nor empty. By default, lookup the member from the + * workspace root. */ - /*package*/ IResource expandToMember(String varValue) { + /* package */IResource expandToMember(String varValue) { return getWorkspaceRoot().findMember(varValue); } - - /* (non-Javadoc) - * Method declared on IVariableLocationExpander. + + /* + * (non-Javadoc) Method declared on IVariableLocationExpander. */ - public IPath getPath(String varTag, String varValue, ExpandVariableContext context) { + public IPath getPath(String varTag, String varValue, + ExpandVariableContext context) { IResource resource = expand(varValue, context); if (resource != null) { if (isPathVariable(varTag)) { @@ -76,45 +76,47 @@ public class ResourceExpander implements IVariableLocationExpander, IVariableRes return null; } } - + /** - * Returns whether the given variable tag is a known path - * variable tag. Path variable tags represent variables that - * expand to paths relative to the workspace root. + * Returns whether the given variable tag is a known path variable tag. Path + * variable tags represent variables that expand to paths relative to the + * workspace root. */ private boolean isPathVariable(String varTag) { - return varTag.equals(IExternalToolConstants.VAR_CONTAINER_PATH) || - varTag.equals(IExternalToolConstants.VAR_PROJECT_PATH) || - varTag.equals(IExternalToolConstants.VAR_RESOURCE_PATH); + return varTag.equals(IExternalToolConstants.VAR_CONTAINER_PATH) + || varTag.equals(IExternalToolConstants.VAR_PROJECT_PATH) + || varTag.equals(IExternalToolConstants.VAR_RESOURCE_PATH); } - /* (non-Javadoc) - * Method declared on IVariableResourceExpander. + /* + * (non-Javadoc) Method declared on IVariableResourceExpander. */ - public IResource[] getResources(String varTag, String varValue, ExpandVariableContext context) { + public IResource[] getResources(String varTag, String varValue, + ExpandVariableContext context) { IResource resource = expand(varValue, context); if (resource != null) { - return new IResource[] {resource}; + return new IResource[] { resource }; } else { return null; } } - + /** * Returns the workspace root resource. */ protected final IWorkspaceRoot getWorkspaceRoot() { return ResourcesPlugin.getWorkspace().getRoot(); } - + /** - * Returns a string representation of the path to a file or directory - * for the given variable tag and value or null. + * Returns a string representation of the path to a file or directory for + * the given variable tag and value or null. * * @see IVariableTextExpander#getText(String, String, ExpandVariableContext) */ - public String getText(String varTag, String varValue, ExpandVariableContext context) { - IPath path= getPath(varTag, varValue, context); + public String getText(String varTag, String varValue, + ExpandVariableContext context) { + IPath path = getPath(varTag, varValue, context); if (path != null) { return path.toString(); } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/ResourceProjectExpander.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/ResourceProjectExpander.java index 9df7758..fd9014a 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/ResourceProjectExpander.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/ResourceProjectExpander.java @@ -1,19 +1,18 @@ package net.sourceforge.phpdt.externaltools.variable; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -  -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import org.eclipse.core.resources.IResource; /** - * Expands a resource's project type variable into the desired - * result format. + * Expands a resource's project type variable into the desired result format. *

* This class is not intended to be extended by clients. *

@@ -27,17 +26,17 @@ public class ResourceProjectExpander extends ResourceExpander { super(); } - /* (non-Javadoc) - * Method declared on ResourceExpander. + /* + * (non-Javadoc) Method declared on ResourceExpander. */ - /*package*/ IResource expandUsingContext(ExpandVariableContext context) { + /* package */IResource expandUsingContext(ExpandVariableContext context) { return context.getProject(); } - - /* (non-Javadoc) - * Method declared on ResourceExpander. + + /* + * (non-Javadoc) Method declared on ResourceExpander. */ - /*package*/ IResource expandToMember(String varValue) { + /* package */IResource expandToMember(String varValue) { IResource member = super.expandToMember(varValue); if (member != null) return member.getProject(); diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/SpecificFileResourceComponent.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/SpecificFileResourceComponent.java index cdeb292..72bb34a 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/SpecificFileResourceComponent.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/SpecificFileResourceComponent.java @@ -1,13 +1,13 @@ package net.sourceforge.phpdt.externaltools.variable; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -  -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import net.sourceforge.phpdt.externaltools.internal.model.ExternalToolsModelMessages; @@ -19,9 +19,8 @@ import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Label; /** - * Visual component to edit the resource type variable - * value for the file location. Variable is limited to a specific - * IFile resource. + * Visual component to edit the resource type variable value for the file + * location. Variable is limited to a specific IFile resource. *

* This class is not intended to be extended by clients. *

@@ -35,39 +34,44 @@ public class SpecificFileResourceComponent extends ResourceComponent { super(); } - /* (non-Javadoc) - * Method declared on ResourceComponent. + /* + * (non-Javadoc) Method declared on ResourceComponent. */ protected void createSelectedResourceOption() { // Do not present this option... } - - /* (non-Javadoc) - * Method declared on ResourceComponent. + + /* + * (non-Javadoc) Method declared on ResourceComponent. */ protected void createSpecificResourceOption() { Label label = new Label(mainGroup, SWT.NONE); GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); label.setLayoutData(data); label.setFont(mainGroup.getFont()); - label.setText(ExternalToolsModelMessages.getString("ResourceComponent.specificResLabel")); //$NON-NLS-1$ + label.setText(ExternalToolsModelMessages + .getString("ResourceComponent.specificResLabel")); //$NON-NLS-1$ } - /* (non-Javadoc) - * Method declared on ResourceComponent. + /* + * (non-Javadoc) Method declared on ResourceComponent. */ protected boolean validateResourceListSelection() { if (resourceList == null) return true; - - IStructuredSelection sel = (IStructuredSelection) resourceList.getSelection(); + + IStructuredSelection sel = (IStructuredSelection) resourceList + .getSelection(); IResource resource = (IResource) sel.getFirstElement(); if (resource == null || resource.getType() != IResource.FILE) { - getPage().setMessage(ExternalToolsModelMessages.getString("ResourceComponent.selectionRequired"), IMessageProvider.WARNING); //$NON-NLS-1$ + getPage() + .setMessage( + ExternalToolsModelMessages + .getString("ResourceComponent.selectionRequired"), IMessageProvider.WARNING); //$NON-NLS-1$ setIsValid(false); return false; } - + return true; } } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/SpecificFolderResourceComponent.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/SpecificFolderResourceComponent.java index e0b4aa7..b217d5c 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/SpecificFolderResourceComponent.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/SpecificFolderResourceComponent.java @@ -1,13 +1,13 @@ package net.sourceforge.phpdt.externaltools.variable; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -  -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import net.sourceforge.phpdt.externaltools.internal.model.ExternalToolsModelMessages; @@ -22,9 +22,9 @@ import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Label; /** - * Visual component to edit the resource type variable - * value for the working directory. Variable is limited to a specific - * IContainer resource. + * Visual component to edit the resource type variable value for the working + * directory. Variable is limited to a specific IContainer + * resource. *

* This class is not intended to be extended by clients. *

@@ -38,15 +38,15 @@ public class SpecificFolderResourceComponent extends ResourceComponent { super(); } - /* (non-Javadoc) - * Method declared on ResourceComponent. + /* + * (non-Javadoc) Method declared on ResourceComponent. */ protected void createSelectedResourceOption() { // Do not present this option... } - - /* (non-Javadoc) - * Method declared on ResourceComponent. + + /* + * (non-Javadoc) Method declared on ResourceComponent. */ protected void createResourceList() { super.createResourceList(); @@ -54,54 +54,60 @@ public class SpecificFolderResourceComponent extends ResourceComponent { resourceList.addFilter(new FileFilter()); } - /* (non-Javadoc) - * Method declared on ResourceComponent. + /* + * (non-Javadoc) Method declared on ResourceComponent. */ protected void createSpecificResourceOption() { Label label = new Label(mainGroup, SWT.NONE); GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); label.setLayoutData(data); label.setFont(mainGroup.getFont()); - label.setText(ExternalToolsModelMessages.getString("ResourceComponent.specificResLabel")); //$NON-NLS-1$ + label.setText(ExternalToolsModelMessages + .getString("ResourceComponent.specificResLabel")); //$NON-NLS-1$ } - /* (non-Javadoc) - * Method declared on ResourceComponent. + /* + * (non-Javadoc) Method declared on ResourceComponent. */ protected boolean validateResourceListSelection() { if (resourceList == null) return true; - - IStructuredSelection sel = (IStructuredSelection) resourceList.getSelection(); + + IStructuredSelection sel = (IStructuredSelection) resourceList + .getSelection(); IResource resource = (IResource) sel.getFirstElement(); if (resource == null || resource.getType() == IResource.FILE) { - getPage().setMessage(ExternalToolsModelMessages.getString("ResourceComponent.selectionRequired"), IMessageProvider.WARNING); //$NON-NLS-1$ + getPage() + .setMessage( + ExternalToolsModelMessages + .getString("ResourceComponent.selectionRequired"), IMessageProvider.WARNING); //$NON-NLS-1$ setIsValid(false); return false; } - + return true; } - - + /** * Filter to remove any IFile resources. */ private static final class FileFilter extends ViewerFilter { - /* (non-Javadoc) - * Method declared on ViewerFilter. + /* + * (non-Javadoc) Method declared on ViewerFilter. */ - public boolean select(Viewer viewer, Object parentElement, Object element) { + public boolean select(Viewer viewer, Object parentElement, + Object element) { IResource resource = null; if (element instanceof IResource) { resource = (IResource) element; } else { if (element instanceof IAdaptable) { IAdaptable adaptable = (IAdaptable) element; - resource = (IResource) adaptable.getAdapter(IResource.class); + resource = (IResource) adaptable + .getAdapter(IResource.class); } } - + if (resource != null) return resource.getType() != IResource.FILE; else diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/UrlExpander.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/UrlExpander.java index 5971985..88c6d42 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/UrlExpander.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/UrlExpander.java @@ -7,43 +7,47 @@ import org.eclipse.core.runtime.IPath; import org.eclipse.jface.preference.IPreferenceStore; /** - * Expands a variable into a localhost/documentRoot URL string + * Expands a variable into a localhost/documentRoot URL string *

* This class is not intended to be extended by clients. *

*/ -public class UrlExpander extends ResourceExpander { //implements IVariableTextExpander { +public class UrlExpander extends ResourceExpander { // implements + // IVariableTextExpander { - /** - * Create an instance - */ - public UrlExpander() { - super(); - } + /** + * Create an instance + */ + public UrlExpander() { + super(); + } - /** - * Returns a string representation to a localhost/documentRoot URL - * for the given variable tag and value or null. - * - * @see IVariableTextExpander#getText(String, String, ExpandVariableContext) - */ - public String getText(String varTag, String varValue, ExpandVariableContext context) { - IPath path = getPath(varTag, varValue, context); - if (path != null) { - IPreferenceStore store = ExternalToolsPlugin.getDefault().getPreferenceStore(); - String localhostURL = path.toString(); - String lowerCaseFileName = localhostURL.toLowerCase(); - String documentRoot = store.getString(WebUI.PHP_DOCUMENTROOT_PREF); - documentRoot = documentRoot.replace('\\', '/'); - documentRoot = documentRoot.toLowerCase(); + /** + * Returns a string representation to a localhost/documentRoot URL for the + * given variable tag and value or null. + * + * @see IVariableTextExpander#getText(String, String, ExpandVariableContext) + */ + public String getText(String varTag, String varValue, + ExpandVariableContext context) { + IPath path = getPath(varTag, varValue, context); + if (path != null) { + IPreferenceStore store = ExternalToolsPlugin.getDefault() + .getPreferenceStore(); + String localhostURL = path.toString(); + String lowerCaseFileName = localhostURL.toLowerCase(); + String documentRoot = store.getString(WebUI.PHP_DOCUMENTROOT_PREF); + documentRoot = documentRoot.replace('\\', '/'); + documentRoot = documentRoot.toLowerCase(); - if (lowerCaseFileName.startsWith(documentRoot)) { - localhostURL = localhostURL.substring(documentRoot.length()); - localhostURL = store.getString(WebUI.PHP_LOCALHOST_PREF)+ localhostURL; - } - return localhostURL; - } - return ""; - } + if (lowerCaseFileName.startsWith(documentRoot)) { + localhostURL = localhostURL.substring(documentRoot.length()); + localhostURL = store.getString(WebUI.PHP_LOCALHOST_PREF) + + localhostURL; + } + return localhostURL; + } + return ""; + } } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/WorkingSetExpander.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/WorkingSetExpander.java index 73474d0..0727bb9 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/WorkingSetExpander.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/WorkingSetExpander.java @@ -1,13 +1,13 @@ package net.sourceforge.phpdt.externaltools.variable; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -  -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IAdaptable; @@ -15,8 +15,7 @@ import org.eclipse.ui.IWorkingSet; import org.eclipse.ui.PlatformUI; /** - * Expands a working set type variable into the desired - * result format. + * Expands a working set type variable into the desired result format. *

* This class is not intended to be extended by clients. *

@@ -30,17 +29,19 @@ public class WorkingSetExpander implements IVariableResourceExpander { super(); } - /* (non-Javadoc) - * Method declared on IVariableResourceExpander. + /* + * (non-Javadoc) Method declared on IVariableResourceExpander. */ - public IResource[] getResources(String varTag, String varValue, ExpandVariableContext context) { + public IResource[] getResources(String varTag, String varValue, + ExpandVariableContext context) { if (varValue == null || varValue.length() == 0) return null; - IWorkingSet set = PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSet(varValue); + IWorkingSet set = PlatformUI.getWorkbench().getWorkingSetManager() + .getWorkingSet(varValue); if (set == null) return null; - + IAdaptable[] elements = set.getElements(); IResource[] resources = new IResource[elements.length]; for (int i = 0; i < elements.length; i++) { @@ -48,9 +49,10 @@ public class WorkingSetExpander implements IVariableResourceExpander { if (adaptable instanceof IResource) resources[i] = (IResource) adaptable; else - resources[i] = (IResource) adaptable.getAdapter(IResource.class); + resources[i] = (IResource) adaptable + .getAdapter(IResource.class); } - + return resources; } } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/WorkspaceExpander.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/WorkspaceExpander.java index cf2ab3c..5c18add 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/WorkspaceExpander.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpdt/externaltools/variable/WorkspaceExpander.java @@ -1,19 +1,18 @@ package net.sourceforge.phpdt.externaltools.variable; /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. All rights reserved. -This file is made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html -  -Contributors: -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. All rights reserved. + This file is made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + � + Contributors: + **********************************************************************/ import org.eclipse.core.resources.IResource; /** - * Expands a workspace variable into the desired - * result format. + * Expands a workspace variable into the desired result format. *

* This class is not intended to be extended by clients. *

@@ -27,10 +26,10 @@ public class WorkspaceExpander extends ResourceExpander { super(); } - /* (non-Javadoc) - * Method declared on ResourceExpander. + /* + * (non-Javadoc) Method declared on ResourceExpander. */ - /*package*/ IResource expandUsingContext(ExpandVariableContext context) { + /* package */IResource expandUsingContext(ExpandVariableContext context) { return getWorkspaceRoot(); } } diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpeclipse/externaltools/ExternalToolsPlugin.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpeclipse/externaltools/ExternalToolsPlugin.java index df3f577..8283e94 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpeclipse/externaltools/ExternalToolsPlugin.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpeclipse/externaltools/ExternalToolsPlugin.java @@ -43,242 +43,271 @@ import org.osgi.framework.BundleContext; * External tools plug-in class */ public final class ExternalToolsPlugin extends AbstractUIPlugin { - public static final String XAMPP_START_PREF = "_xampp_start_pref"; + public static final String XAMPP_START_PREF = "_xampp_start_pref"; - public static final String XAMPP_STOP_PREF = "_xampp_stop_pref"; + public static final String XAMPP_STOP_PREF = "_xampp_stop_pref"; - public static final String MYSQL_RUN_PREF = "_mysql_run_pref"; + public static final String MYSQL_RUN_PREF = "_mysql_run_pref"; - public static final String MYSQL_START_BACKGROUND = "_mysql_start_background"; + public static final String MYSQL_START_BACKGROUND = "_mysql_start_background"; - public static final String MYSQL_PREF = "__mysql_start"; + public static final String MYSQL_PREF = "__mysql_start"; - public static final String APACHE_RUN_PREF = "_apache_run_pref"; + public static final String APACHE_RUN_PREF = "_apache_run_pref"; - public static final String APACHE_START_BACKGROUND = "_apache_start_background"; + public static final String APACHE_START_BACKGROUND = "_apache_start_background"; - public static final String APACHE_START_PREF = "__apache_start"; + public static final String APACHE_START_PREF = "__apache_start"; - public static final String APACHE_STOP_BACKGROUND = "_apache_stop_background"; + public static final String APACHE_STOP_BACKGROUND = "_apache_stop_background"; - public static final String APACHE_STOP_PREF = "__apache_stop"; + public static final String APACHE_STOP_PREF = "__apache_stop"; - public static final String APACHE_RESTART_BACKGROUND = "_apache_restart_background"; + public static final String APACHE_RESTART_BACKGROUND = "_apache_restart_background"; - public static final String APACHE_RESTART_PREF = "__apache_restart"; + public static final String APACHE_RESTART_PREF = "__apache_restart"; - public static final String HTTPD_CONF_PATH_PREF = "__httpd_conf_path"; + public static final String HTTPD_CONF_PATH_PREF = "__httpd_conf_path"; - public static final String ETC_HOSTS_PATH_PREF = "__etc_hosts_path"; - // public static final String SHOW_OUTPUT_IN_CONSOLE = "_show_output_in_console"; + public static final String ETC_HOSTS_PATH_PREF = "__etc_hosts_path"; - public static final String PHP_RUN_PREF = "_php_run_pref"; + // public static final String SHOW_OUTPUT_IN_CONSOLE = + // "_show_output_in_console"; - public static final String EXTERNAL_PARSER_PREF = "_external_parser"; + public static final String PHP_RUN_PREF = "_php_run_pref"; - /** - * Status representing no problems encountered during operation. - */ - public static final IStatus OK_STATUS = new Status(IStatus.OK, IExternalToolConstants.PLUGIN_ID, 0, "", null); //$NON-NLS-1$ - - private static ExternalToolsPlugin plugin; - - private RefreshScopeVariableRegistry refreshVarRegistry; - - private PathLocationVariableRegistry fileLocVarRegistry; - - private PathLocationVariableRegistry dirLocVarRegistry; - - private ArgumentVariableRegistry argumentVarRegistry; - - - /** - * This version is recommended for eclipse3.0 and above - */ - public ExternalToolsPlugin() { - super(); - plugin = this; - } - - /** - * Returns the default instance of the receiver. This represents the runtime plugin. - */ - public static ExternalToolsPlugin getDefault() { - return plugin; - } - - /** - * Returns a new IStatus for this plug-in - */ - public static IStatus newErrorStatus(String message, Throwable exception) { - return new Status(Status.ERROR, IExternalToolConstants.PLUGIN_ID, 0, message, exception); - } - - /** - * Returns a new CoreException for this plug-in - */ - public static CoreException newError(String message, Throwable exception) { - return new CoreException(new Status(Status.ERROR, IExternalToolConstants.PLUGIN_ID, 0, message, exception)); - } - - /** - * Returns the registry of refresh scope variables. - */ - public ArgumentVariableRegistry getArgumentVariableRegistry() { - if (argumentVarRegistry == null) - argumentVarRegistry = new ArgumentVariableRegistry(); - return argumentVarRegistry; - } - - /** - * Returns the registry of directory location variables. - */ - public PathLocationVariableRegistry getDirectoryLocationVariableRegistry() { - if (dirLocVarRegistry == null) - dirLocVarRegistry = new PathLocationVariableRegistry(IExternalToolConstants.EXTENSION_POINT_DIRECTORY_VARIABLES); - return dirLocVarRegistry; - } - - /** - * Returns the registry of file location variables. - */ - public PathLocationVariableRegistry getFileLocationVariableRegistry() { - if (fileLocVarRegistry == null) - fileLocVarRegistry = new PathLocationVariableRegistry(IExternalToolConstants.EXTENSION_POINT_FILE_VARIABLES); - return fileLocVarRegistry; - } - - /** - * Returns the registry of refresh scope variables. - */ - public RefreshScopeVariableRegistry getRefreshVariableRegistry() { - if (refreshVarRegistry == null) - refreshVarRegistry = new RefreshScopeVariableRegistry(); - return refreshVarRegistry; - } - - /** - * Writes the message to the plug-in's log - * - * @param message - * the text to write to the log - */ - public void log(String message, Throwable exception) { - IStatus status = newErrorStatus(message, exception); - // getLog().log(status); - ExternalToolsPlugin.log(status); - } - - public static void log(IStatus status) { - getDefault().getLog().log(status); - } - - /** - * Returns the ImageDescriptor for the icon with the given path - * - * @return the ImageDescriptor object - */ - public ImageDescriptor getImageDescriptor(String path) { - try { - Bundle bundle = ExternalToolsPlugin.getDefault().getBundle(); - URL installURL = bundle.getEntry("/"); //$NON-NLS-1$ - URL url = new URL(installURL, path); - return ImageDescriptor.createFromURL(url); - } catch (MalformedURLException e) { - return null; + public static final String EXTERNAL_PARSER_PREF = "_external_parser"; + + /** + * Status representing no problems encountered during operation. + */ + public static final IStatus OK_STATUS = new Status(IStatus.OK, + IExternalToolConstants.PLUGIN_ID, 0, "", null); //$NON-NLS-1$ + + private static ExternalToolsPlugin plugin; + + private RefreshScopeVariableRegistry refreshVarRegistry; + + private PathLocationVariableRegistry fileLocVarRegistry; + + private PathLocationVariableRegistry dirLocVarRegistry; + + private ArgumentVariableRegistry argumentVarRegistry; + + /** + * This version is recommended for eclipse3.0 and above + */ + public ExternalToolsPlugin() { + super(); + plugin = this; + } + + /** + * Returns the default instance of the receiver. This represents the runtime + * plugin. + */ + public static ExternalToolsPlugin getDefault() { + return plugin; + } + + /** + * Returns a new IStatus for this plug-in + */ + public static IStatus newErrorStatus(String message, Throwable exception) { + return new Status(Status.ERROR, IExternalToolConstants.PLUGIN_ID, 0, + message, exception); + } + + /** + * Returns a new CoreException for this plug-in + */ + public static CoreException newError(String message, Throwable exception) { + return new CoreException(new Status(Status.ERROR, + IExternalToolConstants.PLUGIN_ID, 0, message, exception)); + } + + /** + * Returns the registry of refresh scope variables. + */ + public ArgumentVariableRegistry getArgumentVariableRegistry() { + if (argumentVarRegistry == null) + argumentVarRegistry = new ArgumentVariableRegistry(); + return argumentVarRegistry; + } + + /** + * Returns the registry of directory location variables. + */ + public PathLocationVariableRegistry getDirectoryLocationVariableRegistry() { + if (dirLocVarRegistry == null) + dirLocVarRegistry = new PathLocationVariableRegistry( + IExternalToolConstants.EXTENSION_POINT_DIRECTORY_VARIABLES); + return dirLocVarRegistry; } - } - - /* - * (non-Javadoc) Method declared in AbstractUIPlugin. - */ - - protected void initializeDefaultPreferences(IPreferenceStore store) { - String operatingSystem = Platform.getOS(); - // maxosx, linux, solaris, win32,... - try { - InputStream is = getDefault().openStream(new Path("prefs/default_" + operatingSystem + ".properties")); - PropertyResourceBundle resourceBundle = new PropertyResourceBundle(is); - Enumeration e = resourceBundle.getKeys(); - String key; - while (e.hasMoreElements()) { - key = (String) e.nextElement(); - store.setDefault(key, resourceBundle.getString(key)); - } - } catch (Exception e) { - // no default properties found - if (operatingSystem.equals(Platform.OS_WIN32)) { - store.setDefault(PHP_RUN_PREF, "c:\\apache\\php\\php.exe"); - store.setDefault(EXTERNAL_PARSER_PREF, "c:\\apache\\php\\php -l -f {0}"); - store.setDefault(MYSQL_RUN_PREF, "c:\\apache\\mysql\\bin\\mysqld-nt.exe"); - store.setDefault(APACHE_RUN_PREF, "c:\\apache\\apache.exe"); - store.setDefault(XAMPP_START_PREF, "c:\\xampp\\xampp_start.exe"); - store.setDefault(XAMPP_STOP_PREF, "c:\\xampp\\xampp_stop.exe"); - store.setDefault(ETC_HOSTS_PATH_PREF, "c:\\windows\\system32\\drivers\\etc\\hosts"); - } else { - store.setDefault(PHP_RUN_PREF, "/apache/php/php"); - store.setDefault(EXTERNAL_PARSER_PREF, "/apache/php/php -l -f {0}"); - store.setDefault(MYSQL_RUN_PREF, "/apache/mysql/bin/mysqld"); - store.setDefault(APACHE_RUN_PREF, "/apache/apache"); - store.setDefault(XAMPP_START_PREF, "xamp/xampp_start"); - store.setDefault(XAMPP_STOP_PREF, "xampp/xampp_stop"); - } - store.setDefault(MYSQL_PREF, "--standalone"); - store.setDefault(APACHE_START_PREF, "-c \"DocumentRoot \"{0}\"\""); - store.setDefault(APACHE_STOP_PREF, "-k shutdown"); - store.setDefault(APACHE_RESTART_PREF, "-k restart"); - store.setDefault(MYSQL_START_BACKGROUND, "true"); - store.setDefault(APACHE_START_BACKGROUND, "true"); - store.setDefault(APACHE_STOP_BACKGROUND, "true"); - store.setDefault(APACHE_RESTART_BACKGROUND, "true"); + + /** + * Returns the registry of file location variables. + */ + public PathLocationVariableRegistry getFileLocationVariableRegistry() { + if (fileLocVarRegistry == null) + fileLocVarRegistry = new PathLocationVariableRegistry( + IExternalToolConstants.EXTENSION_POINT_FILE_VARIABLES); + return fileLocVarRegistry; + } + + /** + * Returns the registry of refresh scope variables. + */ + public RefreshScopeVariableRegistry getRefreshVariableRegistry() { + if (refreshVarRegistry == null) + refreshVarRegistry = new RefreshScopeVariableRegistry(); + return refreshVarRegistry; + } + + /** + * Writes the message to the plug-in's log + * + * @param message + * the text to write to the log + */ + public void log(String message, Throwable exception) { + IStatus status = newErrorStatus(message, exception); + // getLog().log(status); + ExternalToolsPlugin.log(status); + } + + public static void log(IStatus status) { + getDefault().getLog().log(status); + } + + /** + * Returns the ImageDescriptor for the icon with the given path + * + * @return the ImageDescriptor object + */ + public ImageDescriptor getImageDescriptor(String path) { + try { + Bundle bundle = ExternalToolsPlugin.getDefault().getBundle(); + URL installURL = bundle.getEntry("/"); //$NON-NLS-1$ + URL url = new URL(installURL, path); + return ImageDescriptor.createFromURL(url); + } catch (MalformedURLException e) { + return null; + } + } + + /* + * (non-Javadoc) Method declared in AbstractUIPlugin. + */ + + protected void initializeDefaultPreferences(IPreferenceStore store) { + String operatingSystem = Platform.getOS(); + // maxosx, linux, solaris, win32,... + try { + InputStream is = getDefault() + .openStream( + new Path("prefs/default_" + operatingSystem + + ".properties")); + PropertyResourceBundle resourceBundle = new PropertyResourceBundle( + is); + Enumeration e = resourceBundle.getKeys(); + String key; + while (e.hasMoreElements()) { + key = (String) e.nextElement(); + store.setDefault(key, resourceBundle.getString(key)); + } + } catch (Exception e) { + // no default properties found + if (operatingSystem.equals(Platform.OS_WIN32)) { + store.setDefault(PHP_RUN_PREF, "c:\\apache\\php\\php.exe"); + store.setDefault(EXTERNAL_PARSER_PREF, + "c:\\apache\\php\\php -l -f {0}"); + store.setDefault(MYSQL_RUN_PREF, + "c:\\apache\\mysql\\bin\\mysqld-nt.exe"); + store.setDefault(APACHE_RUN_PREF, "c:\\apache\\apache.exe"); + store + .setDefault(XAMPP_START_PREF, + "c:\\xampp\\xampp_start.exe"); + store.setDefault(XAMPP_STOP_PREF, "c:\\xampp\\xampp_stop.exe"); + store.setDefault(ETC_HOSTS_PATH_PREF, + "c:\\windows\\system32\\drivers\\etc\\hosts"); + } else { + store.setDefault(PHP_RUN_PREF, "/apache/php/php"); + store.setDefault(EXTERNAL_PARSER_PREF, + "/apache/php/php -l -f {0}"); + store.setDefault(MYSQL_RUN_PREF, "/apache/mysql/bin/mysqld"); + store.setDefault(APACHE_RUN_PREF, "/apache/apache"); + store.setDefault(XAMPP_START_PREF, "xamp/xampp_start"); + store.setDefault(XAMPP_STOP_PREF, "xampp/xampp_stop"); + } + store.setDefault(MYSQL_PREF, "--standalone"); + store.setDefault(APACHE_START_PREF, "-c \"DocumentRoot \"{0}\"\""); + store.setDefault(APACHE_STOP_PREF, "-k shutdown"); + store.setDefault(APACHE_RESTART_PREF, "-k restart"); + store.setDefault(MYSQL_START_BACKGROUND, "true"); + store.setDefault(APACHE_START_BACKGROUND, "true"); + store.setDefault(APACHE_STOP_BACKGROUND, "true"); + store.setDefault(APACHE_RESTART_BACKGROUND, "true"); + } + + // store.setDefault(SHOW_OUTPUT_IN_CONSOLE, "true"); + + store.setDefault(IPreferenceConstants.PROMPT_FOR_MIGRATION, true); + + PreferenceConverter.setDefault(store, + IPreferenceConstants.CONSOLE_ERROR_RGB, new RGB(255, 0, 0)); // red + // - + // exactly + // the + // same + // as + // debug Console + PreferenceConverter.setDefault(store, + IPreferenceConstants.CONSOLE_WARNING_RGB, new RGB(255, 100, 0)); // orange + PreferenceConverter.setDefault(store, + IPreferenceConstants.CONSOLE_INFO_RGB, new RGB(0, 0, 255)); // blue + PreferenceConverter.setDefault(store, + IPreferenceConstants.CONSOLE_VERBOSE_RGB, new RGB(0, 200, 125)); // green + PreferenceConverter.setDefault(store, + IPreferenceConstants.CONSOLE_DEBUG_RGB, new RGB(0, 0, 0)); // black + } + + public static IWorkbenchWindow getActiveWorkbenchWindow() { + return ExternalToolsPlugin.getDefault().getWorkbench() + .getActiveWorkbenchWindow(); + } + + /** + * Returns the standard display to be used. The method first checks, if the + * thread calling this method has an associated display. If so, this display + * is returned. Otherwise the method returns the default display. + */ + public static Display getStandardDisplay() { + Display display = Display.getCurrent(); + if (display == null) { + display = Display.getDefault(); + } + return display; + } + + /** + * @see org.eclipse.ui.plugin.AbstractUIPlugin#createImageRegistry() + */ + protected ImageRegistry createImageRegistry() { + return ExternalToolsImages.initializeImageRegistry(); } - // store.setDefault(SHOW_OUTPUT_IN_CONSOLE, "true"); - - store.setDefault(IPreferenceConstants.PROMPT_FOR_MIGRATION, true); - - PreferenceConverter.setDefault(store, IPreferenceConstants.CONSOLE_ERROR_RGB, new RGB(255, 0, 0)); // red - exactly the same as - // debug Console - PreferenceConverter.setDefault(store, IPreferenceConstants.CONSOLE_WARNING_RGB, new RGB(255, 100, 0)); // orange - PreferenceConverter.setDefault(store, IPreferenceConstants.CONSOLE_INFO_RGB, new RGB(0, 0, 255)); // blue - PreferenceConverter.setDefault(store, IPreferenceConstants.CONSOLE_VERBOSE_RGB, new RGB(0, 200, 125)); // green - PreferenceConverter.setDefault(store, IPreferenceConstants.CONSOLE_DEBUG_RGB, new RGB(0, 0, 0)); // black - } - - public static IWorkbenchWindow getActiveWorkbenchWindow() { - return ExternalToolsPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow(); - } - - /** - * Returns the standard display to be used. The method first checks, if the thread calling this method has an associated display. - * If so, this display is returned. Otherwise the method returns the default display. - */ - public static Display getStandardDisplay() { - Display display = Display.getCurrent(); - if (display == null) { - display = Display.getDefault(); + /** + * @throws Exception + * @see org.eclipse.core.runtime.Plugin#start(BundleContext context) + */ + public void start(BundleContext context) throws Exception { + super.start(context); + getStandardDisplay().asyncExec(new Runnable() { + public void run() { + // initialize the variable context manager + VariableContextManager.getDefault(); + } + }); } - return display; - } - - /** - * @see org.eclipse.ui.plugin.AbstractUIPlugin#createImageRegistry() - */ - protected ImageRegistry createImageRegistry() { - return ExternalToolsImages.initializeImageRegistry(); - } - - /** - * @throws Exception - * @see org.eclipse.core.runtime.Plugin#start(BundleContext context) - */ - public void start(BundleContext context) throws Exception { - super.start(context); - getStandardDisplay().asyncExec(new Runnable() { - public void run() { - //initialize the variable context manager - VariableContextManager.getDefault(); - } - }); - } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpeclipse/externaltools/PHPConsole.java b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpeclipse/externaltools/PHPConsole.java index 817ec47..a5f1820 100644 --- a/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpeclipse/externaltools/PHPConsole.java +++ b/net.sourceforge.phpeclipse.externaltools/src/net/sourceforge/phpeclipse/externaltools/PHPConsole.java @@ -10,98 +10,102 @@ import org.eclipse.ui.console.MessageConsole; import org.eclipse.ui.console.MessageConsoleStream; public class PHPConsole { - private MessageConsole myConsole; + private MessageConsole myConsole; - private MessageConsoleStream stream; + private MessageConsoleStream stream; - private boolean hasMessages; + private boolean hasMessages; - public PHPConsole() { - hasMessages = false; - myConsole = new MessageConsole("PHPeclipse Console", null); - ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[] { myConsole }); - ConsolePlugin.getDefault().getConsoleManager().showConsoleView(myConsole); - // layout.addView(IConsoleConstants.ID_CONSOLE_VIEW, IPageLayout.BOTTOM, .5f,IPageLayout.ID_EDITOR_AREA); - stream = myConsole.newMessageStream(); - } + public PHPConsole() { + hasMessages = false; + myConsole = new MessageConsole("PHPeclipse Console", null); + ConsolePlugin.getDefault().getConsoleManager().addConsoles( + new IConsole[] { myConsole }); + ConsolePlugin.getDefault().getConsoleManager().showConsoleView( + myConsole); + // layout.addView(IConsoleConstants.ID_CONSOLE_VIEW, IPageLayout.BOTTOM, + // .5f,IPageLayout.ID_EDITOR_AREA); + stream = myConsole.newMessageStream(); + } - /** - * @return - */ - public Color getColor() { - return stream.getColor(); - } + /** + * @return + */ + public Color getColor() { + return stream.getColor(); + } - /** - * @return - */ - public MessageConsole getConsole() { - return stream.getConsole(); - } + /** + * @return + */ + public MessageConsole getConsole() { + return stream.getConsole(); + } - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - public int hashCode() { - return stream.hashCode(); - } + /* + * (non-Javadoc) + * + * @see java.lang.Object#hashCode() + */ + public int hashCode() { + return stream.hashCode(); + } - /** - * @param message - */ - public void print(String message) { - hasMessages = true; - stream.print(message); - } + /** + * @param message + */ + public void print(String message) { + hasMessages = true; + stream.print(message); + } - /** - * - */ - public void println() { - hasMessages = true; - stream.println(); - } + /** + * + */ + public void println() { + hasMessages = true; + stream.println(); + } - /** - * @param message - */ - public void println(String message) { - hasMessages = true; - stream.println(message); - } + /** + * @param message + */ + public void println(String message) { + hasMessages = true; + stream.println(message); + } - /** - * @param color - */ - public void setColor(Color color) { - stream.setColor(color); - } + /** + * @param color + */ + public void setColor(Color color) { + stream.setColor(color); + } - // public void reportError(String title, String message) { - // if (hasMessages) { - // WikiEditorPlugin.getDefault().reportError(title, message); - // } - // } + // public void reportError(String title, String message) { + // if (hasMessages) { + // WikiEditorPlugin.getDefault().reportError(title, message); + // } + // } - // public void reportError() { - // reportError("Problems listed", "Open console view for problems log!"); - // } - /** - * Creates a string buffer from the given input stream - */ - public static String getStringFromStream(InputStream stream) throws IOException { - StringBuffer buffer = new StringBuffer(); - byte[] b = new byte[100]; - int finished = 0; - while (finished != -1) { - finished = stream.read(b); - if (finished != -1) { - String current = new String(b, 0, finished); - buffer.append(current); - } - } - return buffer.toString(); - } + // public void reportError() { + // reportError("Problems listed", "Open console view for problems log!"); + // } + /** + * Creates a string buffer from the given input stream + */ + public static String getStringFromStream(InputStream stream) + throws IOException { + StringBuffer buffer = new StringBuffer(); + byte[] b = new byte[100]; + int finished = 0; + while (finished != -1) { + finished = stream.read(b); + if (finished != -1) { + String current = new String(b, 0, finished); + buffer.append(current); + } + } + return buffer.toString(); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.launching/src/net/sourceforge/phpdt/internal/launching/ConsoleLineTracker.java b/net.sourceforge.phpeclipse.launching/src/net/sourceforge/phpdt/internal/launching/ConsoleLineTracker.java index 5eb4656..49d1b3c 100644 --- a/net.sourceforge.phpeclipse.launching/src/net/sourceforge/phpdt/internal/launching/ConsoleLineTracker.java +++ b/net.sourceforge.phpeclipse.launching/src/net/sourceforge/phpdt/internal/launching/ConsoleLineTracker.java @@ -8,7 +8,6 @@ import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.debug.ui.console.IConsole; -// TODO XXX Disabled for 3.1 import org.eclipse.debug.ui.console.IConsoleHyperlink; import org.eclipse.debug.ui.console.IConsoleLineTracker; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; @@ -17,41 +16,53 @@ import org.eclipse.ui.IEditorPart; import org.eclipse.ui.PartInitException; import org.eclipse.ui.texteditor.ITextEditor; - public class ConsoleLineTracker implements IConsoleLineTracker { - - private static class JavadocConsoleHyperLink /* TODO XXX Disabled for 3.1 implements IConsoleHyperlink */ { - + + private static class JavadocConsoleHyperLink /* + * TODO XXX Disabled for 3.1 + * implements + * IConsoleHyperlink + */{ + private IPath fExternalPath; + private int fLineNumber; public JavadocConsoleHyperLink(IPath externalPath, int lineNumber) { - fExternalPath= externalPath; - fLineNumber= lineNumber; + fExternalPath = externalPath; + fLineNumber = lineNumber; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.debug.ui.console.IConsoleHyperlink#linkEntered() */ public void linkEntered() { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.debug.ui.console.IConsoleHyperlink#linkExited() */ public void linkExited() { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.debug.ui.console.IConsoleHyperlink#linkActivated() */ public void linkActivated() { try { - IFile[] files= ResourcesPlugin.getWorkspace().getRoot().findFilesForLocation(fExternalPath); + IFile[] files = ResourcesPlugin.getWorkspace().getRoot() + .findFilesForLocation(fExternalPath); if (files.length > 0) { for (int i = 0; i < files.length; i++) { - IFile curr= files[0]; - IEditorPart part= EditorUtility.openInEditor(curr, true); + IFile curr = files[0]; + IEditorPart part = EditorUtility.openInEditor(curr, + true); if (part != null) { if (part instanceof ITextEditor) { revealLine((ITextEditor) part, fLineNumber); @@ -59,39 +70,44 @@ public class ConsoleLineTracker implements IConsoleLineTracker { return; } } - } + } } catch (BadLocationException e) { PHPLaunchingPlugin.log(e); } catch (PartInitException e) { - PHPLaunchingPlugin.log(e); + PHPLaunchingPlugin.log(e); } catch (JavaModelException e) { - PHPLaunchingPlugin.log(e); + PHPLaunchingPlugin.log(e); } } - - private void revealLine(ITextEditor editor, int lineNumber) throws BadLocationException { - IDocument document= editor.getDocumentProvider().getDocument(editor.getEditorInput()); - IRegion region= document.getLineInformation(lineNumber - 1); + + private void revealLine(ITextEditor editor, int lineNumber) + throws BadLocationException { + IDocument document = editor.getDocumentProvider().getDocument( + editor.getEditorInput()); + IRegion region = document.getLineInformation(lineNumber - 1); editor.selectAndReveal(region.getOffset(), 0); } - + } - private IConsole fConsole; - + public ConsoleLineTracker() { - super(); + super(); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.ui.console.IConsoleLineTracker#init(org.eclipse.debug.ui.console.IConsole) */ public void init(IConsole console) { - fConsole= console; + fConsole = console; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.debug.ui.console.IConsoleLineTracker#lineAppended(org.eclipse.jface.text.IRegion) */ public void lineAppended(IRegion line) { @@ -99,32 +115,34 @@ public class ConsoleLineTracker implements IConsoleLineTracker { int offset = line.getOffset(); int length = line.getLength(); String text = fConsole.getDocument().get(offset, length); - - int index1= text.indexOf(':'); + + int index1 = text.indexOf(':'); if (index1 == -1) { return; } - - int lineNumber= -1; - IPath path= null; - int index2= text.indexOf(':', index1 + 1); + + int lineNumber = -1; + IPath path = null; + int index2 = text.indexOf(':', index1 + 1); while ((index2 != -1) && (path == null)) { if (index1 < index2) { try { - String substr= text.substring(index1 + 1, index2); - lineNumber= Integer.parseInt(substr); - path= new Path(text.substring(0, index1)); + String substr = text.substring(index1 + 1, index2); + lineNumber = Integer.parseInt(substr); + path = new Path(text.substring(0, index1)); } catch (NumberFormatException e) { // ignore } } - index1= index2; - index2= text.indexOf(':', index1 + 1); + index1 = index2; + index2 = text.indexOf(':', index1 + 1); } - + if (lineNumber != -1) { - JavadocConsoleHyperLink link= new JavadocConsoleHyperLink(path, lineNumber); - // TODO XXX Disabled for 3.1 fConsole.addLink(link, line.getOffset(), index1); + JavadocConsoleHyperLink link = new JavadocConsoleHyperLink( + path, lineNumber); + // TODO XXX Disabled for 3.1 fConsole.addLink(link, + // line.getOffset(), index1); } } catch (BadLocationException e) { @@ -132,9 +150,9 @@ public class ConsoleLineTracker implements IConsoleLineTracker { } } - - - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.debug.ui.console.IConsoleLineTracker#dispose() */ public void dispose() { diff --git a/net.sourceforge.phpeclipse.launching/src/net/sourceforge/phpdt/internal/launching/DebuggerRunner.java b/net.sourceforge.phpeclipse.launching/src/net/sourceforge/phpdt/internal/launching/DebuggerRunner.java index 9a2f1af..ffb100b 100644 --- a/net.sourceforge.phpeclipse.launching/src/net/sourceforge/phpdt/internal/launching/DebuggerRunner.java +++ b/net.sourceforge.phpeclipse.launching/src/net/sourceforge/phpdt/internal/launching/DebuggerRunner.java @@ -20,94 +20,107 @@ import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.model.IProcess; import org.eclipse.swt.widgets.Display; -//import net.sourceforge.phpeclipse.resourcesview.PHPProject; +// import net.sourceforge.phpeclipse.resourcesview.PHPProject; public class DebuggerRunner extends InterpreterRunner { - public IProcess run(InterpreterRunnerConfiguration configuration, ILaunch launch) { - String[] env; - String name, value; - PHPDBGProxy newPHPDBGProxy = new PHPDBGProxy(configuration.useRemoteDebugger(), configuration.getRemoteSourcePath(), - configuration.usePathTranslation(),configuration.getPathMap()); - int pos; - - IProcess process = null; - PHPDebugTarget debugTarget = new PHPDebugTarget(launch, process); - newPHPDBGProxy.setDebugTarget(debugTarget); - newPHPDBGProxy.start(); - if (configuration.useRemoteDebugger()) { - // listener for remote debuger is started - if (configuration.useDBGSessionInBrowser()) { - activateDBGSESSIDPreview(configuration,newPHPDBGProxy.getPort()); - } - } else { - setEnvironmentVariables(configuration, newPHPDBGProxy.getPort()); - // env=configuration.getEnvironment(); - process = super.run(configuration, launch); - debugTarget.setProcess(process); - } - launch.addDebugTarget(debugTarget); - - return process; - } - - /** - * Open the browser in the UI thread with the current debugger URL - * - * @param configuration - * @param port - */ - protected static void activateDBGSESSIDPreview(final InterpreterRunnerConfiguration configuration, final int port) { - Display.getDefault().asyncExec(new Runnable() { - public void run() { - String fileName = configuration.getFileName(); - JavaProject jproject = configuration.getProject(); - IProject project = jproject.getProject(); - IFile file = project.getFile(fileName); - BrowserUtil.showPreview(file, true, "?DBGSESSID=1@clienthost:"+port); - } - }); - } - protected void setEnvironmentVariables(InterpreterRunnerConfiguration configuration, int listenPort) { - String DBGSessID; - String env[] = new String[18]; - long id = Math.round(Math.random() * 100000); - - DBGSessID = "DBGSESSID=" + id + "@clienthost:" + listenPort; - configuration.addEnvironmentValue("HTTP_COOKIE", DBGSessID, false); - /* - * configuration.addEnvironmentValue("REDIRECT_URL",OSFilePath,true); - * configuration.addEnvironmentValue("REQUEST_URI",OSFilePath,true); - * configuration.addEnvironmentValue("PATH_INFO",OSFilePath,true); - * configuration.addEnvironmentValue("PATH_TRANSLATED",OSFilePath,true); - * configuration.addEnvironmentValue("SCRIPT_FILENAME",interpreter,true); - * configuration.addEnvironmentValue("SERVER_PROTOCOL","HTTP / 1.1",true); - */ - /* - * env[0]= "HTTP_COOKIE=" + DBGSessID; env[1]= "REDIRECT_QUERY_STRING="; env[2]= "REDIRECT_STATUS=200"; env[3]= "REDIRECT_URL=" + - * OSFilePath; env[4]= "SERVER_SOFTWARE=DBG / 2.1"; env[5]= "SERVER_NAME=localhost"; env[6]= "SERVER_ADDR=127.0.0.1"; env[7]= - * "SERVER_PORT=80"; env[8]= "REMOTE_ADDR=127.0.0.1"; env[9]= "SCRIPT_FILENAME=" + interpreter; env[10]= "GATEWAY_INTERFACE=CGI / - * 1.1"; env[11]= "SERVER_PROTOCOL=HTTP / 1.1"; env[12]= "REQUEST_METHOD=GET"; env[13]= "QUERY_STRING=test=1"; env[14]= - * "REQUEST_URI=" + OSFilePath; env[15]= "PATH_INFO=" + OSFilePath; env[16]= "PATH_TRANSLATED=" + OSFilePath; env[17]= - * "SystemRoot=" + Environment.getenv("SystemRoot"); - */ - // return env; - } - - protected String getDebugCommandLineArgument() { - return ""; - } - - protected String renderLoadPath(InterpreterRunnerConfiguration configuration) { - StringBuffer loadPath = new StringBuffer(); - - JavaProject project = configuration.getProject(); - addToLoadPath(loadPath, project.getProject()); - - Iterator referencedProjects = project.getReferencedProjects().iterator(); - while (referencedProjects.hasNext()) - addToLoadPath(loadPath, (IProject) referencedProjects.next()); - - return loadPath.toString(); - } + public IProcess run(InterpreterRunnerConfiguration configuration, + ILaunch launch) { + String[] env; + String name, value; + PHPDBGProxy newPHPDBGProxy = new PHPDBGProxy(configuration + .useRemoteDebugger(), configuration.getRemoteSourcePath(), + configuration.usePathTranslation(), configuration.getPathMap()); + int pos; + + IProcess process = null; + PHPDebugTarget debugTarget = new PHPDebugTarget(launch, process); + newPHPDBGProxy.setDebugTarget(debugTarget); + newPHPDBGProxy.start(); + if (configuration.useRemoteDebugger()) { + // listener for remote debuger is started + if (configuration.useDBGSessionInBrowser()) { + activateDBGSESSIDPreview(configuration, newPHPDBGProxy + .getPort()); + } + } else { + setEnvironmentVariables(configuration, newPHPDBGProxy.getPort()); + // env=configuration.getEnvironment(); + process = super.run(configuration, launch); + debugTarget.setProcess(process); + } + launch.addDebugTarget(debugTarget); + + return process; + } + + /** + * Open the browser in the UI thread with the current debugger URL + * + * @param configuration + * @param port + */ + protected static void activateDBGSESSIDPreview( + final InterpreterRunnerConfiguration configuration, final int port) { + Display.getDefault().asyncExec(new Runnable() { + public void run() { + String fileName = configuration.getFileName(); + JavaProject jproject = configuration.getProject(); + IProject project = jproject.getProject(); + IFile file = project.getFile(fileName); + BrowserUtil.showPreview(file, true, "?DBGSESSID=1@clienthost:" + + port); + } + }); + } + + protected void setEnvironmentVariables( + InterpreterRunnerConfiguration configuration, int listenPort) { + String DBGSessID; + String env[] = new String[18]; + long id = Math.round(Math.random() * 100000); + + DBGSessID = "DBGSESSID=" + id + "@clienthost:" + listenPort; + configuration.addEnvironmentValue("HTTP_COOKIE", DBGSessID, false); + /* + * configuration.addEnvironmentValue("REDIRECT_URL",OSFilePath,true); + * configuration.addEnvironmentValue("REQUEST_URI",OSFilePath,true); + * configuration.addEnvironmentValue("PATH_INFO",OSFilePath,true); + * configuration.addEnvironmentValue("PATH_TRANSLATED",OSFilePath,true); + * configuration.addEnvironmentValue("SCRIPT_FILENAME",interpreter,true); + * configuration.addEnvironmentValue("SERVER_PROTOCOL","HTTP / + * 1.1",true); + */ + /* + * env[0]= "HTTP_COOKIE=" + DBGSessID; env[1]= "REDIRECT_QUERY_STRING="; + * env[2]= "REDIRECT_STATUS=200"; env[3]= "REDIRECT_URL=" + OSFilePath; + * env[4]= "SERVER_SOFTWARE=DBG / 2.1"; env[5]= "SERVER_NAME=localhost"; + * env[6]= "SERVER_ADDR=127.0.0.1"; env[7]= "SERVER_PORT=80"; env[8]= + * "REMOTE_ADDR=127.0.0.1"; env[9]= "SCRIPT_FILENAME=" + interpreter; + * env[10]= "GATEWAY_INTERFACE=CGI / 1.1"; env[11]= + * "SERVER_PROTOCOL=HTTP / 1.1"; env[12]= "REQUEST_METHOD=GET"; env[13]= + * "QUERY_STRING=test=1"; env[14]= "REQUEST_URI=" + OSFilePath; env[15]= + * "PATH_INFO=" + OSFilePath; env[16]= "PATH_TRANSLATED=" + OSFilePath; + * env[17]= "SystemRoot=" + Environment.getenv("SystemRoot"); + */ + // return env; + } + + protected String getDebugCommandLineArgument() { + return ""; + } + + protected String renderLoadPath(InterpreterRunnerConfiguration configuration) { + StringBuffer loadPath = new StringBuffer(); + + JavaProject project = configuration.getProject(); + addToLoadPath(loadPath, project.getProject()); + + Iterator referencedProjects = project.getReferencedProjects() + .iterator(); + while (referencedProjects.hasNext()) + addToLoadPath(loadPath, (IProject) referencedProjects.next()); + + return loadPath.toString(); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.launching/src/net/sourceforge/phpdt/internal/launching/InterpreterRunner.java b/net.sourceforge.phpeclipse.launching/src/net/sourceforge/phpdt/internal/launching/InterpreterRunner.java index cf8141a..6aa5738 100644 --- a/net.sourceforge.phpeclipse.launching/src/net/sourceforge/phpdt/internal/launching/InterpreterRunner.java +++ b/net.sourceforge.phpeclipse.launching/src/net/sourceforge/phpdt/internal/launching/InterpreterRunner.java @@ -20,7 +20,8 @@ public class InterpreterRunner { public InterpreterRunner() { } - public IProcess run(InterpreterRunnerConfiguration configuration, ILaunch launch) { + public IProcess run(InterpreterRunnerConfiguration configuration, + ILaunch launch) { String commandLine = renderCommandLine(configuration); File workingDirectory = configuration.getAbsoluteWorkingDirectory(); @@ -28,16 +29,22 @@ public class InterpreterRunner { String[] env = configuration.getEnvironment(); Process nativePHPProcess = null; try { - nativePHPProcess = configuration.getInterpreter().exec(commandLine, workingDirectory, env); + nativePHPProcess = configuration.getInterpreter().exec(commandLine, + workingDirectory, env); } catch (IOException e) { - throw new RuntimeException("Unable to execute interpreter: " + commandLine + workingDirectory); + throw new RuntimeException("Unable to execute interpreter: " + + commandLine + workingDirectory); } - IProcess process = DebugPlugin.newProcess(launch, nativePHPProcess, renderLabel(configuration)); - process.setAttribute(PHPLaunchingPlugin.PLUGIN_ID + ".launcher.cmdline", commandLine); - process.setAttribute(IProcess.ATTR_PROCESS_TYPE, PHPLaunchConfigurationAttribute.PHP_LAUNCH_PROCESS_TYPE); + IProcess process = DebugPlugin.newProcess(launch, nativePHPProcess, + renderLabel(configuration)); + process + .setAttribute(PHPLaunchingPlugin.PLUGIN_ID + + ".launcher.cmdline", commandLine); + process.setAttribute(IProcess.ATTR_PROCESS_TYPE, + PHPLaunchConfigurationAttribute.PHP_LAUNCH_PROCESS_TYPE); - return process ; + return process; } protected String renderLabel(InterpreterRunnerConfiguration configuration) { @@ -52,44 +59,52 @@ public class InterpreterRunner { return buffer.toString(); } - protected String renderCommandLine(InterpreterRunnerConfiguration configuration) { + protected String renderCommandLine( + InterpreterRunnerConfiguration configuration) { PHPInterpreter interpreter = configuration.getInterpreter(); StringBuffer buffer = new StringBuffer(); buffer.append(this.getDebugCommandLineArgument()); - // buffer.append(renderLoadPath(configuration)); + // buffer.append(renderLoadPath(configuration)); buffer.append(" " + configuration.getInterpreterArguments()); - // buffer.append(interpreter.endOfOptionsDelimeter); - buffer.append(" " + osDependentPath(configuration.getAbsoluteFileName())); + // buffer.append(interpreter.endOfOptionsDelimeter); + buffer.append(" " + + osDependentPath(configuration.getAbsoluteFileName())); buffer.append(" " + configuration.getProgramArguments()); return buffer.toString(); } - protected void setEnvironmentVariables(InterpreterRunnerConfiguration configuration) { - IPath FilePath= new Path(configuration.getAbsoluteFileName()); - String OSFilePath= FilePath.toOSString(); - configuration.addEnvironmentValue("REDIRECT_URL",OSFilePath,true); - configuration.addEnvironmentValue("REQUEST_URI",OSFilePath,true); - configuration.addEnvironmentValue("PATH_INFO",OSFilePath,true); - configuration.addEnvironmentValue("PATH_TRANSLATED",OSFilePath,true); - configuration.addEnvironmentValue("SCRIPT_FILENAME",configuration.getInterpreter().getCommand(),true); - configuration.addEnvironmentValue("SERVER_PROTOCOL","HTTP / 1.1",true); - - configuration.addEnvironmentValue("REDIRECT_QUERY_STRING","",true); - configuration.addEnvironmentValue("REDIRECT_STATUS","200",true); - configuration.addEnvironmentValue("SERVER_SOFTWARE","DBG / 2.1",true); - configuration.addEnvironmentValue("SERVER_NAME","localhost",true); - configuration.addEnvironmentValue("SERVER_ADDR","127.0.0.1",true); - configuration.addEnvironmentValue("SERVER_PORT","80",true); - configuration.addEnvironmentValue("REMOTE_ADDR","127.0.0.1",true); - - configuration.addEnvironmentValue("GATEWAY_INTERFACE","CGI / 1.1",true); - configuration.addEnvironmentValue("REQUEST_METHOD","GET",true); - - Map stringVars = DebugPlugin.getDefault().getLaunchManager().getNativeEnvironment(); + protected void setEnvironmentVariables( + InterpreterRunnerConfiguration configuration) { + IPath FilePath = new Path(configuration.getAbsoluteFileName()); + String OSFilePath = FilePath.toOSString(); + configuration.addEnvironmentValue("REDIRECT_URL", OSFilePath, true); + configuration.addEnvironmentValue("REQUEST_URI", OSFilePath, true); + configuration.addEnvironmentValue("PATH_INFO", OSFilePath, true); + configuration.addEnvironmentValue("PATH_TRANSLATED", OSFilePath, true); + configuration.addEnvironmentValue("SCRIPT_FILENAME", configuration + .getInterpreter().getCommand(), true); + configuration + .addEnvironmentValue("SERVER_PROTOCOL", "HTTP / 1.1", true); + + configuration.addEnvironmentValue("REDIRECT_QUERY_STRING", "", true); + configuration.addEnvironmentValue("REDIRECT_STATUS", "200", true); + configuration.addEnvironmentValue("SERVER_SOFTWARE", "DBG / 2.1", true); + configuration.addEnvironmentValue("SERVER_NAME", "localhost", true); + configuration.addEnvironmentValue("SERVER_ADDR", "127.0.0.1", true); + configuration.addEnvironmentValue("SERVER_PORT", "80", true); + configuration.addEnvironmentValue("REMOTE_ADDR", "127.0.0.1", true); + + configuration.addEnvironmentValue("GATEWAY_INTERFACE", "CGI / 1.1", + true); + configuration.addEnvironmentValue("REQUEST_METHOD", "GET", true); + + Map stringVars = DebugPlugin.getDefault().getLaunchManager() + .getNativeEnvironment(); if (stringVars.containsKey("SYSTEMROOT")) - configuration.addEnvironmentValue("SYSTEMROOT",(String) stringVars.get("SYSTEMROOT"),true); + configuration.addEnvironmentValue("SYSTEMROOT", (String) stringVars + .get("SYSTEMROOT"), true); } @@ -99,7 +114,8 @@ public class InterpreterRunner { JavaProject project = configuration.getProject(); addToLoadPath(loadPath, project.getProject()); - Iterator referencedProjects = project.getReferencedProjects().iterator(); + Iterator referencedProjects = project.getReferencedProjects() + .iterator(); while (referencedProjects.hasNext()) addToLoadPath(loadPath, (IProject) referencedProjects.next()); @@ -107,7 +123,8 @@ public class InterpreterRunner { } protected void addToLoadPath(StringBuffer loadPath, IProject project) { - loadPath.append(" -I " + osDependentPath(project.getLocation().toOSString())); + loadPath.append(" -I " + + osDependentPath(project.getLocation().toOSString())); } protected String osDependentPath(String aPath) { @@ -118,6 +135,6 @@ public class InterpreterRunner { } protected String getDebugCommandLineArgument() { - return "" ; + return ""; } } diff --git a/net.sourceforge.phpeclipse.launching/src/net/sourceforge/phpdt/internal/launching/InterpreterRunnerConfiguration.java b/net.sourceforge.phpeclipse.launching/src/net/sourceforge/phpdt/internal/launching/InterpreterRunnerConfiguration.java index cd25d13..52fa78a 100644 --- a/net.sourceforge.phpeclipse.launching/src/net/sourceforge/phpdt/internal/launching/InterpreterRunnerConfiguration.java +++ b/net.sourceforge.phpeclipse.launching/src/net/sourceforge/phpdt/internal/launching/InterpreterRunnerConfiguration.java @@ -16,174 +16,190 @@ import org.eclipse.core.runtime.Path; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.internal.ui.launchConfigurations.EnvironmentVariable; - public class InterpreterRunnerConfiguration { protected ILaunchConfiguration configuration; + private HashMap fEnvironment; public InterpreterRunnerConfiguration(ILaunchConfiguration aConfiguration) { configuration = aConfiguration; - fEnvironment= new HashMap(); + fEnvironment = new HashMap(); } - + public String getAbsoluteFileName() { IPath path = new Path(getFileName()); IProject project = getProject().getProject(); return project.getLocation().toOSString() + "/" + getFileName(); } - + public String getFileName() { String fileName = ""; try { - fileName = configuration.getAttribute(PHPLaunchConfigurationAttribute.FILE_NAME, "No file specified in configuration"); - } catch(CoreException e) {} - + fileName = configuration.getAttribute( + PHPLaunchConfigurationAttribute.FILE_NAME, + "No file specified in configuration"); + } catch (CoreException e) { + } + return fileName.replace('\\', '/'); - } - + } + public JavaProject getProject() { String projectName = ""; - + try { - projectName = configuration.getAttribute(PHPLaunchConfigurationAttribute.PROJECT_NAME, ""); - } catch(CoreException e) { + projectName = configuration.getAttribute( + PHPLaunchConfigurationAttribute.PROJECT_NAME, ""); + } catch (CoreException e) { PHPLaunchingPlugin.log(e); } - IProject project = PHPLaunchingPlugin.getWorkspace().getRoot().getProject(projectName); + IProject project = PHPLaunchingPlugin.getWorkspace().getRoot() + .getProject(projectName); JavaProject phpProject = new JavaProject(); phpProject.setProject(project); return phpProject; } - + public File getAbsoluteWorkingDirectory() { String file = null; try { - file = configuration.getAttribute(PHPLaunchConfigurationAttribute.WORKING_DIRECTORY, ""); - } catch(CoreException e) { + file = configuration.getAttribute( + PHPLaunchConfigurationAttribute.WORKING_DIRECTORY, ""); + } catch (CoreException e) { PHPLaunchingPlugin.log(e); } return new File(file); } - + public String getInterpreterArguments() { try { - return configuration.getAttribute(PHPLaunchConfigurationAttribute.INTERPRETER_ARGUMENTS, ""); - } catch(CoreException e) {} - + return configuration.getAttribute( + PHPLaunchConfigurationAttribute.INTERPRETER_ARGUMENTS, ""); + } catch (CoreException e) { + } + return ""; } - + public String getProgramArguments() { try { - return configuration.getAttribute(PHPLaunchConfigurationAttribute.PROGRAM_ARGUMENTS, ""); - } catch (CoreException e) {} - + return configuration.getAttribute( + PHPLaunchConfigurationAttribute.PROGRAM_ARGUMENTS, ""); + } catch (CoreException e) { + } + return ""; } public PHPInterpreter getInterpreter() { String selectedInterpreter = null; try { - selectedInterpreter = configuration.getAttribute(PHPLaunchConfigurationAttribute.SELECTED_INTERPRETER, ""); - } catch(CoreException e) {} + selectedInterpreter = configuration.getAttribute( + PHPLaunchConfigurationAttribute.SELECTED_INTERPRETER, ""); + } catch (CoreException e) { + } return PHPRuntime.getDefault().getInterpreter(selectedInterpreter); } - + public boolean useRemoteDebugger() { try { - return configuration.getAttribute(PHPLaunchConfigurationAttribute.REMOTE_DEBUG, false); - } catch(CoreException e) { + return configuration.getAttribute( + PHPLaunchConfigurationAttribute.REMOTE_DEBUG, false); + } catch (CoreException e) { PHPLaunchingPlugin.log(e); } return false; } - + public boolean usePathTranslation() { try { - return configuration.getAttribute(PHPLaunchConfigurationAttribute.REMOTE_DEBUG_TRANSLATE, false); - } catch(CoreException e) { + return configuration.getAttribute( + PHPLaunchConfigurationAttribute.REMOTE_DEBUG_TRANSLATE, + false); + } catch (CoreException e) { PHPLaunchingPlugin.log(e); } return false; } - - public Map getPathMap() { + + public Map getPathMap() { try { - return configuration.getAttribute(PHPLaunchConfigurationAttribute.FILE_MAP, (Map) null); - } catch(CoreException e) { - PHPLaunchingPlugin.log(e); + return configuration.getAttribute( + PHPLaunchConfigurationAttribute.FILE_MAP, (Map) null); + } catch (CoreException e) { + PHPLaunchingPlugin.log(e); } return (Map) null; } - + public boolean useDBGSessionInBrowser() { try { - return configuration.getAttribute(PHPLaunchConfigurationAttribute.OPEN_DBGSESSION_IN_BROWSER, true); - } catch(CoreException e) { + return configuration.getAttribute( + PHPLaunchConfigurationAttribute.OPEN_DBGSESSION_IN_BROWSER, + true); + } catch (CoreException e) { PHPLaunchingPlugin.log(e); } return false; } - - public void setEnvironment(String[] envp) - { - if (envp== null) + + public void setEnvironment(String[] envp) { + if (envp == null) return; - for (int i = 0; i 0) - setSelectedInterpreter((PHPInterpreter)installedInterpreters.get(0)); + setSelectedInterpreter((PHPInterpreter) installedInterpreters + .get(0)); else setSelectedInterpreter(null); } @@ -92,9 +96,11 @@ public class PHPRuntime { protected Writer getRuntimeConfigurationWriter() { try { - OutputStream stream = new BufferedOutputStream(new FileOutputStream(getRuntimeConfigurationFile())); + OutputStream stream = new BufferedOutputStream( + new FileOutputStream(getRuntimeConfigurationFile())); return new OutputStreamWriter(stream); - } catch (FileNotFoundException e) {} + } catch (FileNotFoundException e) { + } return null; } @@ -104,11 +110,14 @@ public class PHPRuntime { try { File file = getRuntimeConfigurationFile(); if (file.exists()) { - XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); - reader.setContentHandler(getRuntimeConfigurationContentHandler()); - reader.parse(new InputSource(getRuntimeConfigurationReader(file))); + XMLReader reader = SAXParserFactory.newInstance() + .newSAXParser().getXMLReader(); + reader + .setContentHandler(getRuntimeConfigurationContentHandler()); + reader.parse(new InputSource( + getRuntimeConfigurationReader(file))); } - } catch(Exception e) { + } catch (Exception e) { PHPLaunchingPlugin.log(e); } } @@ -116,19 +125,22 @@ public class PHPRuntime { protected Reader getRuntimeConfigurationReader(File file) { try { return new FileReader(file); - } catch(FileNotFoundException e) {} + } catch (FileNotFoundException e) { + } return new StringReader(""); } protected void writeXML(Writer writer) { try { - writer.write(""); + writer + .write(""); Iterator interpretersIterator = installedInterpreters.iterator(); while (interpretersIterator.hasNext()) { writer.write(""); writer.flush(); - } catch(IOException e) { + } catch (IOException e) { PHPLaunchingPlugin.log(e); } } protected ContentHandler getRuntimeConfigurationContentHandler() { return new ContentHandler() { - public void setDocumentLocator(Locator locator) {} - public void startDocument() throws SAXException {} - public void endDocument() throws SAXException {} - public void startPrefixMapping(String prefix, String uri) throws SAXException {} - public void endPrefixMapping(String prefix) throws SAXException {} - public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { + public void setDocumentLocator(Locator locator) { + } + + public void startDocument() throws SAXException { + } + + public void endDocument() throws SAXException { + } + + public void startPrefixMapping(String prefix, String uri) + throws SAXException { + } + + public void endPrefixMapping(String prefix) throws SAXException { + } + + public void startElement(String namespaceURI, String localName, + String qName, Attributes atts) throws SAXException { if ("interpreter".equals(qName)) { - String interpreterName = atts.getValue("name"); - java.io.File installLocation; - if (interpreterName!=null) { - installLocation = new File(atts.getValue("path")+File.separatorChar+interpreterName); - } else { - installLocation = new File(atts.getValue("path")); - } - PHPInterpreter interpreter = new PHPInterpreter(installLocation); + String interpreterName = atts.getValue("name"); + java.io.File installLocation; + if (interpreterName != null) { + installLocation = new File(atts.getValue("path") + + File.separatorChar + interpreterName); + } else { + installLocation = new File(atts.getValue("path")); + } + PHPInterpreter interpreter = new PHPInterpreter( + installLocation); installedInterpreters.add(interpreter); if (atts.getValue("selected") != null) selectedInterpreter = interpreter; } } - public void endElement(String namespaceURI, String localName, String qName) throws SAXException {} - public void characters(char[] ch, int start, int length) throws SAXException {} - public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {} - public void processingInstruction(String target, String data) throws SAXException {} - public void skippedEntity(String name) throws SAXException {} + + public void endElement(String namespaceURI, String localName, + String qName) throws SAXException { + } + + public void characters(char[] ch, int start, int length) + throws SAXException { + } + + public void ignorableWhitespace(char[] ch, int start, int length) + throws SAXException { + } + + public void processingInstruction(String target, String data) + throws SAXException { + } + + public void skippedEntity(String name) throws SAXException { + } }; } protected File getRuntimeConfigurationFile() { - IPath stateLocation = PHPLaunchingPlugin.getDefault().getStateLocation(); + IPath stateLocation = PHPLaunchingPlugin.getDefault() + .getStateLocation(); IPath fileLocation = stateLocation.append("runtimeConfiguration.xml"); return new File(fileLocation.toOSString()); } diff --git a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/AbstractHTTPQueryAction.java b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/AbstractHTTPQueryAction.java index 1592734..2191117 100644 --- a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/AbstractHTTPQueryAction.java +++ b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/AbstractHTTPQueryAction.java @@ -27,16 +27,19 @@ public abstract class AbstractHTTPQueryAction implements IEditorActionDelegate { abstract protected Configuration getConfiguration(String name); public void setActiveEditor(IAction action, IEditorPart targetEditor) { - if (targetEditor != null && (targetEditor instanceof AbstractTextEditor)) { + if (targetEditor != null + && (targetEditor instanceof AbstractTextEditor)) { editor = (AbstractTextEditor) targetEditor; } } public void run(IAction action) { - IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + IWorkbenchWindow window = PlatformUI.getWorkbench() + .getActiveWorkbenchWindow(); if (editor == null) { IEditorPart targetEditor = window.getActivePage().getActiveEditor(); - if (targetEditor != null && (targetEditor instanceof AbstractTextEditor)) { + if (targetEditor != null + && (targetEditor instanceof AbstractTextEditor)) { editor = (AbstractTextEditor) targetEditor; } } @@ -66,11 +69,13 @@ public abstract class AbstractHTTPQueryAction implements IEditorActionDelegate { } public IDocument getDocument() { - IDocument doc = editor.getDocumentProvider().getDocument(editor.getEditorInput()); + IDocument doc = editor.getDocumentProvider().getDocument( + editor.getEditorInput()); return doc; } - public static String getSelectedText(AbstractTextEditor editor, IDocument document, int initialPos) { + public static String getSelectedText(AbstractTextEditor editor, + IDocument document, int initialPos) { try { int pos = initialPos; int line = document.getLineOfOffset(pos); @@ -78,9 +83,9 @@ public abstract class AbstractHTTPQueryAction implements IEditorActionDelegate { int end = start + document.getLineInformation(line).getLength(); /* - * The line does not include \n or \r so pos can be > end. Making pos = - * end in this case is safe for the purposes of determining the TextRegion - * at the cursor position + * The line does not include \n or \r so pos can be > end. Making + * pos = end in this case is safe for the purposes of determining + * the TextRegion at the cursor position */ if (pos > end) { pos = end; @@ -105,7 +110,8 @@ public abstract class AbstractHTTPQueryAction implements IEditorActionDelegate { } } if (textStart != (-1) && textEnd != (-1) && textStart < textEnd) { - return new String(word.toCharArray(), textStart, textEnd - textStart); + return new String(word.toCharArray(), textStart, textEnd + - textStart); } } catch (Exception e) { @@ -115,7 +121,8 @@ public abstract class AbstractHTTPQueryAction implements IEditorActionDelegate { public String generateUrl(Configuration config, String template) { IDocument doc = getDocument(); - ITextSelection selection = (ITextSelection) editor.getSelectionProvider().getSelection(); + ITextSelection selection = (ITextSelection) editor + .getSelectionProvider().getSelection(); int pos = selection.getOffset(); int len = selection.getLength(); String wikiTitle; diff --git a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/HTTPQueryAction.java b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/HTTPQueryAction.java index fe5a211..7b0381c 100644 --- a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/HTTPQueryAction.java +++ b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/HTTPQueryAction.java @@ -21,7 +21,8 @@ public class HTTPQueryAction extends AbstractHTTPQueryAction { } protected Configuration getConfiguration(String name) { - List allConfigsList = ConfigurationManager.getInstance().getConfigurations(); + List allConfigsList = ConfigurationManager.getInstance() + .getConfigurations(); ArrayList configsList = new ArrayList(); for (int i = 0; i < allConfigsList.size(); i++) { IConfiguration temp = (IConfiguration) allConfigsList.get(i); @@ -37,8 +38,10 @@ public class HTTPQueryAction extends AbstractHTTPQueryAction { } Collections.sort(configsList); - ListSelectionDialog listSelectionDialog = new ListSelectionDialog(PHPHelpPlugin.getDefault().getWorkbench() - .getActiveWorkbenchWindow().getShell(), configsList, new ListContentProvider(), new LabelProvider(), "Select URL"); + ListSelectionDialog listSelectionDialog = new ListSelectionDialog( + PHPHelpPlugin.getDefault().getWorkbench() + .getActiveWorkbenchWindow().getShell(), configsList, + new ListContentProvider(), new LabelProvider(), "Select URL"); listSelectionDialog.setTitle("Multiple configuration found"); if (listSelectionDialog.open() == Window.OK) { Object[] configurations = listSelectionDialog.getResult(); diff --git a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/KodersAction.java b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/KodersAction.java index d9834ef..f6794c1 100644 --- a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/KodersAction.java +++ b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/KodersAction.java @@ -4,22 +4,21 @@ import net.sourceforge.phpdt.httpquery.config.Configuration; import net.sourceforge.phpdt.httpquery.config.ConfigurationWorkingCopy; import net.sourceforge.phpdt.phphelp.PHPHelpPlugin; - public class KodersAction extends HTTPQueryAction { - public KodersAction() { - super(); - } + public KodersAction() { + super(); + } - protected Configuration getConfiguration(String name) { - Configuration conf = super.getConfiguration("Koders.com"); + protected Configuration getConfiguration(String name) { + Configuration conf = super.getConfiguration("Koders.com"); if (conf != null) { return conf; } - ConfigurationWorkingCopy config = new ConfigurationWorkingCopy(); - config.setName("Koders.com"); - config.setURL("http://koders.com/?s=$text.selection"); - config.setType(PHPHelpPlugin.HTTP_QUERY); - return config; - } + ConfigurationWorkingCopy config = new ConfigurationWorkingCopy(); + config.setName("Koders.com"); + config.setURL("http://koders.com/?s=$text.selection"); + config.setType(PHPHelpPlugin.HTTP_QUERY); + return config; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/PHPHelpAction.java b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/PHPHelpAction.java index d5e5423..e0c5b2b 100644 --- a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/PHPHelpAction.java +++ b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/PHPHelpAction.java @@ -4,22 +4,22 @@ import net.sourceforge.phpdt.httpquery.config.Configuration; import net.sourceforge.phpdt.httpquery.config.ConfigurationWorkingCopy; import net.sourceforge.phpdt.phphelp.PHPHelpPlugin; - public class PHPHelpAction extends HTTPQueryAction { - public PHPHelpAction() { - super(); - } + public PHPHelpAction() { + super(); + } - protected Configuration getConfiguration(String name) { - Configuration conf = super.getConfiguration("PHP Manual"); + protected Configuration getConfiguration(String name) { + Configuration conf = super.getConfiguration("PHP Manual"); if (conf != null) { return conf; } - ConfigurationWorkingCopy config = new ConfigurationWorkingCopy(); - config.setName("PHP Manual"); - config.setURL("http://www.php.net/manual/en/function.$php.selection.php"); - config.setType(PHPHelpPlugin.HTTP_QUERY); - return config; - } + ConfigurationWorkingCopy config = new ConfigurationWorkingCopy(); + config.setName("PHP Manual"); + config + .setURL("http://www.php.net/manual/en/function.$php.selection.php"); + config.setType(PHPHelpPlugin.HTTP_QUERY); + return config; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/Configuration.java b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/Configuration.java index 98eb4d6..dcc6d84 100644 --- a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/Configuration.java +++ b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/Configuration.java @@ -13,472 +13,237 @@ package net.sourceforge.phpdt.httpquery.config; import net.sourceforge.phpdt.phphelp.PHPHelpPlugin; /** - * + * */ public class Configuration implements IConfiguration, Comparable { - private static final String MEMENTO_ID = "id"; - - private static final String MEMENTO_NAME = "name"; - - private static final String MEMENTO_USER = "user"; - - private static final String MEMENTO_URL = "url"; - - private static final String MEMENTO_PASSWORD = "password"; - - private static final String MEMENTO_TYPE_ID = "type-id"; - - protected String fId = ""; - - protected String fName = ""; - - protected String fUrl = ""; - - protected String fPassword = ""; - - protected String fUser = ""; - - protected String fType = ""; - - private static final char[] SCRAMBLING_TABLE = new char[] { - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 16, - 17, - 18, - 19, - 20, - 21, - 22, - 23, - 24, - 25, - 26, - 27, - 28, - 29, - 30, - 31, - 114, - 120, - 53, - 79, - 96, - 109, - 72, - 108, - 70, - 64, - 76, - 67, - 116, - 74, - 68, - 87, - 111, - 52, - 75, - 119, - 49, - 34, - 82, - 81, - 95, - 65, - 112, - 86, - 118, - 110, - 122, - 105, - 41, - 57, - 83, - 43, - 46, - 102, - 40, - 89, - 38, - 103, - 45, - 50, - 42, - 123, - 91, - 35, - 125, - 55, - 54, - 66, - 124, - 126, - 59, - 47, - 92, - 71, - 115, - 78, - 88, - 107, - 106, - 56, - 36, - 121, - 117, - 104, - 101, - 100, - 69, - 73, - 99, - 63, - 94, - 93, - 39, - 37, - 61, - 48, - 58, - 113, - 32, - 90, - 44, - 98, - 60, - 51, - 33, - 97, - 62, - 77, - 84, - 80, - 85, - 223, - 225, - 216, - 187, - 166, - 229, - 189, - 222, - 188, - 141, - 249, - 148, - 200, - 184, - 136, - 248, - 190, - 199, - 170, - 181, - 204, - 138, - 232, - 218, - 183, - 255, - 234, - 220, - 247, - 213, - 203, - 226, - 193, - 174, - 172, - 228, - 252, - 217, - 201, - 131, - 230, - 197, - 211, - 145, - 238, - 161, - 179, - 160, - 212, - 207, - 221, - 254, - 173, - 202, - 146, - 224, - 151, - 140, - 196, - 205, - 130, - 135, - 133, - 143, - 246, - 192, - 159, - 244, - 239, - 185, - 168, - 215, - 144, - 139, - 165, - 180, - 157, - 147, - 186, - 214, - 176, - 227, - 231, - 219, - 169, - 175, - 156, - 206, - 198, - 129, - 164, - 150, - 210, - 154, - 177, - 134, - 127, - 182, - 128, - 158, - 208, - 162, - 132, - 167, - 209, - 149, - 241, - 153, - 251, - 237, - 236, - 171, - 195, - 243, - 233, - 253, - 240, - 194, - 250, - 191, - 155, - 142, - 137, - 245, - 235, - 163, - 242, - 178, - 152 }; - - /** - * Construct a Configuration with the defult type: - * net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin.HTTP_QUERY - * - */ - public Configuration() { - this(PHPHelpPlugin.HTTP_QUERY); // default type - } - - /** - * Construct a Configuration with a type - * @param type Example: net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin.HTTP_QUERY - * - * @see net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin - */ - public Configuration(String type) { - this.fType = type; - } - - public String getId() { - return fId; - } - - public String getName() { - return fName; - } - - public String getURL() { - return fUrl; - } - - public String getPassword() { - return fPassword; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.monitor.internal.IConfiguration#getLocalPort() - */ - public String getUser() { - return fUser; - } - - /** - */ - public String getType() { - return fType; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.monitor.internal.IConfiguration#isRunning() - */ - public boolean isActive() { - return ConfigurationManager.getInstance().isActive(this); - } - - public void delete() { - ConfigurationManager.getInstance().removeConfiguration(this); - } - - public boolean isWorkingCopy() { - return false; - } - - public IConfigurationWorkingCopy getWorkingCopy() { - return new ConfigurationWorkingCopy(this); - } - - protected void setInternal(IConfiguration monitor) { - fId = monitor.getId(); - fName = monitor.getName(); - fUrl = monitor.getURL(); - fPassword = monitor.getPassword(); - fUser = monitor.getUser(); - fType = monitor.getType(); - } - - protected void save(IMemento memento) { - memento.putString(MEMENTO_ID, fId); - memento.putString(MEMENTO_NAME, fName); - memento.putString(MEMENTO_TYPE_ID, fType); - memento.putString(MEMENTO_USER, fUser); - memento.putString(MEMENTO_URL, fUrl); - String result = 'A' + scramblePassword(fPassword); - memento.putString(MEMENTO_PASSWORD, result); - } - - protected void load(IMemento memento) { - fId = memento.getString(MEMENTO_ID); - if (fId == null) { - fId = ""; - } - fName = memento.getString(MEMENTO_NAME); - if (fName == null) { - fName = ""; - } - fType = memento.getString(MEMENTO_TYPE_ID); - if (fType == null) { - fType = ""; - } - fUser = memento.getString(MEMENTO_USER); - if (fUser == null) { - fUser = ""; - } - fUrl = memento.getString(MEMENTO_URL); - if (fUrl == null) { - fUrl = ""; - } - String result = memento.getString(MEMENTO_PASSWORD); - - if (result == null) { - fPassword = ""; - } else { - fPassword = scramblePassword(result.substring(1)); - } - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - public String toString() { - StringBuffer buffer = new StringBuffer(); - buffer.append(fName); - buffer.append(" - "); - buffer.append(fUser); - buffer.append(" - "); - buffer.append(fUrl); - buffer.append(" - "); - buffer.append(fType); - return buffer.toString(); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Comparable#compareTo(java.lang.Object) - */ - public int compareTo(Object o) { - if (o instanceof IConfiguration) { - return fName.compareTo(((IConfiguration) o).getName()); - } - return 1; - } - - private static String scramblePassword(String password) { - int length = password.length(); - char[] out = new char[length]; - for (int i = 0; i < length; i++) { - char value = password.charAt(i); - out[i] = SCRAMBLING_TABLE[value]; - } - return new String(out); - } - - public boolean isUserComplete() { - if (fUser == null || fUser.equals("")) { - return false; - } - if (fPassword == null || fPassword.equals("")) { - return false; - } - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object obj) { - if (obj instanceof Configuration) { - if (fName == null || ((Configuration) obj).fName == null) { - return false; - } - return fName.equals(((Configuration) obj).fName); - } - return false; - } + private static final String MEMENTO_ID = "id"; + + private static final String MEMENTO_NAME = "name"; + + private static final String MEMENTO_USER = "user"; + + private static final String MEMENTO_URL = "url"; + + private static final String MEMENTO_PASSWORD = "password"; + + private static final String MEMENTO_TYPE_ID = "type-id"; + + protected String fId = ""; + + protected String fName = ""; + + protected String fUrl = ""; + + protected String fPassword = ""; + + protected String fUser = ""; + + protected String fType = ""; + + private static final char[] SCRAMBLING_TABLE = new char[] { 0, 1, 2, 3, 4, + 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, + 23, 24, 25, 26, 27, 28, 29, 30, 31, 114, 120, 53, 79, 96, 109, 72, + 108, 70, 64, 76, 67, 116, 74, 68, 87, 111, 52, 75, 119, 49, 34, 82, + 81, 95, 65, 112, 86, 118, 110, 122, 105, 41, 57, 83, 43, 46, 102, + 40, 89, 38, 103, 45, 50, 42, 123, 91, 35, 125, 55, 54, 66, 124, + 126, 59, 47, 92, 71, 115, 78, 88, 107, 106, 56, 36, 121, 117, 104, + 101, 100, 69, 73, 99, 63, 94, 93, 39, 37, 61, 48, 58, 113, 32, 90, + 44, 98, 60, 51, 33, 97, 62, 77, 84, 80, 85, 223, 225, 216, 187, + 166, 229, 189, 222, 188, 141, 249, 148, 200, 184, 136, 248, 190, + 199, 170, 181, 204, 138, 232, 218, 183, 255, 234, 220, 247, 213, + 203, 226, 193, 174, 172, 228, 252, 217, 201, 131, 230, 197, 211, + 145, 238, 161, 179, 160, 212, 207, 221, 254, 173, 202, 146, 224, + 151, 140, 196, 205, 130, 135, 133, 143, 246, 192, 159, 244, 239, + 185, 168, 215, 144, 139, 165, 180, 157, 147, 186, 214, 176, 227, + 231, 219, 169, 175, 156, 206, 198, 129, 164, 150, 210, 154, 177, + 134, 127, 182, 128, 158, 208, 162, 132, 167, 209, 149, 241, 153, + 251, 237, 236, 171, 195, 243, 233, 253, 240, 194, 250, 191, 155, + 142, 137, 245, 235, 163, 242, 178, 152 }; + + /** + * Construct a Configuration with the defult type: + * net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin.HTTP_QUERY + * + */ + public Configuration() { + this(PHPHelpPlugin.HTTP_QUERY); // default type + } + + /** + * Construct a Configuration with a type + * + * @param type + * Example: + * net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin.HTTP_QUERY + * + * @see net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin + */ + public Configuration(String type) { + this.fType = type; + } + + public String getId() { + return fId; + } + + public String getName() { + return fName; + } + + public String getURL() { + return fUrl; + } + + public String getPassword() { + return fPassword; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.monitor.internal.IConfiguration#getLocalPort() + */ + public String getUser() { + return fUser; + } + + /** + */ + public String getType() { + return fType; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.monitor.internal.IConfiguration#isRunning() + */ + public boolean isActive() { + return ConfigurationManager.getInstance().isActive(this); + } + + public void delete() { + ConfigurationManager.getInstance().removeConfiguration(this); + } + + public boolean isWorkingCopy() { + return false; + } + + public IConfigurationWorkingCopy getWorkingCopy() { + return new ConfigurationWorkingCopy(this); + } + + protected void setInternal(IConfiguration monitor) { + fId = monitor.getId(); + fName = monitor.getName(); + fUrl = monitor.getURL(); + fPassword = monitor.getPassword(); + fUser = monitor.getUser(); + fType = monitor.getType(); + } + + protected void save(IMemento memento) { + memento.putString(MEMENTO_ID, fId); + memento.putString(MEMENTO_NAME, fName); + memento.putString(MEMENTO_TYPE_ID, fType); + memento.putString(MEMENTO_USER, fUser); + memento.putString(MEMENTO_URL, fUrl); + String result = 'A' + scramblePassword(fPassword); + memento.putString(MEMENTO_PASSWORD, result); + } + + protected void load(IMemento memento) { + fId = memento.getString(MEMENTO_ID); + if (fId == null) { + fId = ""; + } + fName = memento.getString(MEMENTO_NAME); + if (fName == null) { + fName = ""; + } + fType = memento.getString(MEMENTO_TYPE_ID); + if (fType == null) { + fType = ""; + } + fUser = memento.getString(MEMENTO_USER); + if (fUser == null) { + fUser = ""; + } + fUrl = memento.getString(MEMENTO_URL); + if (fUrl == null) { + fUrl = ""; + } + String result = memento.getString(MEMENTO_PASSWORD); + + if (result == null) { + fPassword = ""; + } else { + fPassword = scramblePassword(result.substring(1)); + } + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + public String toString() { + StringBuffer buffer = new StringBuffer(); + buffer.append(fName); + buffer.append(" - "); + buffer.append(fUser); + buffer.append(" - "); + buffer.append(fUrl); + buffer.append(" - "); + buffer.append(fType); + return buffer.toString(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + public int compareTo(Object o) { + if (o instanceof IConfiguration) { + return fName.compareTo(((IConfiguration) o).getName()); + } + return 1; + } + + private static String scramblePassword(String password) { + int length = password.length(); + char[] out = new char[length]; + for (int i = 0; i < length; i++) { + char value = password.charAt(i); + out[i] = SCRAMBLING_TABLE[value]; + } + return new String(out); + } + + public boolean isUserComplete() { + if (fUser == null || fUser.equals("")) { + return false; + } + if (fPassword == null || fPassword.equals("")) { + return false; + } + return true; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + public boolean equals(Object obj) { + if (obj instanceof Configuration) { + if (fName == null || ((Configuration) obj).fName == null) { + return false; + } + return fName.equals(((Configuration) obj).fName); + } + return false; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/ConfigurationManager.java b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/ConfigurationManager.java index 2b23dea..8c75aac 100644 --- a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/ConfigurationManager.java +++ b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/ConfigurationManager.java @@ -4,7 +4,7 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html -�* + �* * Contributors: * IBM - Initial API and implementation **********************************************************************/ @@ -20,21 +20,26 @@ import java.util.Map; import net.sourceforge.phpdt.phphelp.PHPHelpPlugin; import org.eclipse.core.runtime.Preferences; + /** - * + * */ public class ConfigurationManager { private static final int ADD = 0; + private static final int CHANGE = 1; + private static final int REMOVE = 2; // configurations protected List configurations; + protected Map threads = new HashMap(); protected List configurationListeners = new ArrayList(); private Preferences.IPropertyChangeListener pcl; + protected boolean ignorePreferenceChanges = false; protected static ConfigurationManager instance; @@ -59,11 +64,13 @@ public class ConfigurationManager { } }; - PHPHelpPlugin.getDefault().getPluginPreferences().addPropertyChangeListener(pcl); + PHPHelpPlugin.getDefault().getPluginPreferences() + .addPropertyChangeListener(pcl); } protected void dispose() { - PHPHelpPlugin.getDefault().getPluginPreferences().removePropertyChangeListener(pcl); + PHPHelpPlugin.getDefault().getPluginPreferences() + .removePropertyChangeListener(pcl); } public IConfigurationWorkingCopy createConfiguration() { @@ -98,7 +105,7 @@ public class ConfigurationManager { /** * Add monitor listener. - * + * * @param listener */ public void addConfigurationListener(IConfigurationListener listener) { @@ -107,7 +114,7 @@ public class ConfigurationManager { /** * Remove monitor listener. - * + * * @param listener */ public void removeConfigurationListener(IConfigurationListener listener) { @@ -116,6 +123,7 @@ public class ConfigurationManager { /** * Fire a monitor event. + * * @param rr * @param fType */ @@ -134,17 +142,16 @@ public class ConfigurationManager { } } - - - protected void loadConfigurations() { configurations = new ArrayList(); Preferences prefs = PHPHelpPlugin.getDefault().getPluginPreferences(); - String xmlString = prefs.getString(PHPHelpPlugin.PREF_STRING_CONFIGURATIONS); + String xmlString = prefs + .getString(PHPHelpPlugin.PREF_STRING_CONFIGURATIONS); if (xmlString != null && xmlString.length() > 0) { try { - ByteArrayInputStream in = new ByteArrayInputStream(xmlString.getBytes()); + ByteArrayInputStream in = new ByteArrayInputStream(xmlString + .getBytes()); IMemento memento = XMLMemento.loadMemento(in); IMemento[] children = memento.getChildren("config"); @@ -164,7 +171,8 @@ public class ConfigurationManager { protected void saveConfigurations() { try { ignorePreferenceChanges = true; - XMLMemento memento = XMLMemento.createWriteRoot(PHPHelpPlugin.PREF_STRING_CONFIGURATIONS); + XMLMemento memento = XMLMemento + .createWriteRoot(PHPHelpPlugin.PREF_STRING_CONFIGURATIONS); Iterator iterator = configurations.iterator(); while (iterator.hasNext()) { @@ -174,7 +182,8 @@ public class ConfigurationManager { } String xmlString = memento.saveToString(); - Preferences prefs = PHPHelpPlugin.getDefault().getPluginPreferences(); + Preferences prefs = PHPHelpPlugin.getDefault() + .getPluginPreferences(); prefs.setValue(PHPHelpPlugin.PREF_STRING_CONFIGURATIONS, xmlString); PHPHelpPlugin.getDefault().savePluginPreferences(); } catch (Exception e) { diff --git a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/ConfigurationWorkingCopy.java b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/ConfigurationWorkingCopy.java index 97742a3..8556ee6 100644 --- a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/ConfigurationWorkingCopy.java +++ b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/ConfigurationWorkingCopy.java @@ -4,20 +4,22 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation **********************************************************************/ package net.sourceforge.phpdt.httpquery.config; /** - * + * */ -public class ConfigurationWorkingCopy extends Configuration implements IConfigurationWorkingCopy { +public class ConfigurationWorkingCopy extends Configuration implements + IConfigurationWorkingCopy { protected Configuration configuration; // creation - public ConfigurationWorkingCopy() { } + public ConfigurationWorkingCopy() { + } // working copy public ConfigurationWorkingCopy(Configuration configuration) { @@ -33,22 +35,18 @@ public class ConfigurationWorkingCopy extends Configuration implements IConfigur fName = name; } - public void setURL(String url) { fUrl = url; } - public void setPassword(String password) { fPassword = password; } - public void setUser(String user) { fUser = user; } - public void setType(String t) { fType = t; } diff --git a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/IConfiguration.java b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/IConfiguration.java index c6d44bf..b96e918 100644 --- a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/IConfiguration.java +++ b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/IConfiguration.java @@ -4,13 +4,14 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation **********************************************************************/ package net.sourceforge.phpdt.httpquery.config; + /** - * + * */ public interface IConfiguration { public String getId(); diff --git a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/IConfigurationListener.java b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/IConfigurationListener.java index e44b5f6..55e2c3b 100644 --- a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/IConfigurationListener.java +++ b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/IConfigurationListener.java @@ -4,13 +4,14 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation **********************************************************************/ package net.sourceforge.phpdt.httpquery.config; + /** - * + * */ public interface IConfigurationListener { public void configurationAdded(IConfiguration monitor); diff --git a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/IConfigurationWorkingCopy.java b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/IConfigurationWorkingCopy.java index 1da0389..e410182 100644 --- a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/IConfigurationWorkingCopy.java +++ b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/IConfigurationWorkingCopy.java @@ -4,13 +4,14 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation **********************************************************************/ package net.sourceforge.phpdt.httpquery.config; + /** - * + * */ public interface IConfigurationWorkingCopy extends IConfiguration { public void setId(String id); @@ -23,7 +24,7 @@ public interface IConfigurationWorkingCopy extends IConfiguration { public void setUser(String port); - public void setType(String type); + public void setType(String type); public IConfiguration save(); } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/IMemento.java b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/IMemento.java index 2b6a743..43f9ead 100644 --- a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/IMemento.java +++ b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/IMemento.java @@ -4,7 +4,7 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM Corporation - Initial API and implementation **********************************************************************/ @@ -14,41 +14,44 @@ import java.util.List; import org.eclipse.ui.IElementFactory; import org.eclipse.ui.IPersistableElement; + /** - * Interface to a memento used for saving the important state of an object - * in a form that can be persisted in the file system. + * Interface to a memento used for saving the important state of an object in a + * form that can be persisted in the file system. *

* Mementos were designed with the following requirements in mind: *

    - *
  1. Certain objects need to be saved and restored across platform sessions. - *
  2. - *
  3. When an object is restored, an appropriate class for an object might not - * be available. It must be possible to skip an object in this case.
  4. - *
  5. When an object is restored, the appropriate class for the object may be - * different from the one when the object was originally saved. If so, the - * new class should still be able to read the old form of the data.
  6. + *
  7. Certain objects need to be saved and restored across platform sessions. + *
  8. + *
  9. When an object is restored, an appropriate class for an object might not + * be available. It must be possible to skip an object in this case.
  10. + *
  11. When an object is restored, the appropriate class for the object may be + * different from the one when the object was originally saved. If so, the new + * class should still be able to read the old form of the data.
  12. *
*

*

- * Mementos meet these requirements by providing support for storing a - * mapping of arbitrary string keys to primitive values, and by allowing - * mementos to have other mementos as children (arranged into a tree). - * A robust external storage format based on XML is used. - *

- * The key for an attribute may be any alpha numeric value. However, the - * value of TAG_ID is reserved for internal use. - *

+ * Mementos meet these requirements by providing support for storing a mapping + * of arbitrary string keys to primitive values, and by allowing mementos to + * have other mementos as children (arranged into a tree). A robust external + * storage format based on XML is used. + *

+ *

+ * The key for an attribute may be any alpha numeric value. However, the value + * of TAG_ID is reserved for internal use. + *

+ *

* This interface is not intended to be implemented by clients. *

- * + * * @see IPersistableElement * @see IElementFactory */ public interface IMemento { /** - * Special reserved key used to store the memento id - * (value "org.eclipse.ui.id"). - * + * Special reserved key used to store the memento id (value + * "org.eclipse.ui.id"). + * * @see #getId */ public static final String TAG_ID = "IMemento.internal.id"; //$NON-NLS-1$ @@ -56,11 +59,12 @@ public interface IMemento { /** * Creates a new child of this memento with the given fType. *

- * The getChild and getChildren methods - * are used to retrieve children of a given fType. + * The getChild and getChildren methods are + * used to retrieve children of a given fType. *

- * - * @param fType the fType + * + * @param fType + * the fType * @return a new child memento * @see #getChild * @see #getChildren @@ -68,16 +72,18 @@ public interface IMemento { public IMemento createChild(String type); /** - * Creates a new child of this memento with the given fType and id. - * The id is stored in the child memento (using a special reserved - * key, TAG_ID) and can be retrieved using getId. + * Creates a new child of this memento with the given fType and id. The id + * is stored in the child memento (using a special reserved key, + * TAG_ID) and can be retrieved using getId. *

- * The getChild and getChildren methods - * are used to retrieve children of a given fType. + * The getChild and getChildren methods are + * used to retrieve children of a given fType. *

- * - * @param fType the fType - * @param id the child id + * + * @param fType + * the fType + * @param id + * the child id * @return a new child memento with the given fType and id * @see #getId */ @@ -85,32 +91,35 @@ public interface IMemento { /** * Returns the first child with the given fType id. - * - * @param fType the fType id + * + * @param fType + * the fType id * @return the first child with the given fType */ public IMemento getChild(String type); /** * Returns all children with the given fType id. - * - * @param fType the fType id + * + * @param fType + * the fType id * @return the list of children with the given fType */ public IMemento[] getChildren(String type); /** * Returns the floating point value of the given key. - * - * @param key the key - * @return the value, or null if the key was not found or was found - * but was not a floating point number + * + * @param key + * the key + * @return the value, or null if the key was not found or was + * found but was not a floating point number */ public Float getFloat(String key); /** * Returns the id for this memento. - * + * * @return the memento id, or null if none * @see #createChild(java.lang.String,java.lang.String) */ @@ -118,7 +127,7 @@ public interface IMemento { /** * Returns the name for this memento. - * + * * @return the memento name, or null if none * @see #createChild(java.lang.String,java.lang.String) */ @@ -126,28 +135,31 @@ public interface IMemento { /** * Returns the integer value of the given key. - * - * @param key the key - * @return the value, or null if the key was not found or was found - * but was not an integer + * + * @param key + * the key + * @return the value, or null if the key was not found or was + * found but was not an integer */ public Integer getInteger(String key); /** * Returns the string value of the given key. - * - * @param key the key - * @return the value, or null if the key was not found or was found - * but was not an integer + * + * @param key + * the key + * @return the value, or null if the key was not found or was + * found but was not an integer */ public String getString(String key); /** * Returns the boolean value of the given key. - * - * @param key the key - * @return the value, or null if the key was not found or was found - * but was not a boolean + * + * @param key + * the key + * @return the value, or null if the key was not found or was + * found but was not a boolean */ public Boolean getBoolean(String key); @@ -155,41 +167,50 @@ public interface IMemento { /** * Sets the value of the given key to the given floating point number. - * - * @param key the key - * @param value the value + * + * @param key + * the key + * @param value + * the value */ public void putFloat(String key, float value); /** * Sets the value of the given key to the given integer. - * - * @param key the key - * @param value the value + * + * @param key + * the key + * @param value + * the value */ public void putInteger(String key, int value); /** * Sets the value of the given key to the given boolean value. - * - * @param key the key - * @param value the value + * + * @param key + * the key + * @param value + * the value */ public void putBoolean(String key, boolean value); /** - * Copy the attributes and children from memento - * to the receiver. - * - * @param memento the IMemento to be copied. + * Copy the attributes and children from memento to the + * receiver. + * + * @param memento + * the IMemento to be copied. */ public void putMemento(IMemento memento); /** * Sets the value of the given key to the given string. - * - * @param key the key - * @param value the value + * + * @param key + * the key + * @param value + * the value */ public void putString(String key, String value); } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/XMLMemento.java b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/XMLMemento.java index dc1954d..d9d80df 100644 --- a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/XMLMemento.java +++ b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/config/XMLMemento.java @@ -4,7 +4,7 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM Corporation - Initial API and implementation **********************************************************************/ @@ -43,30 +43,31 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; + /** - * A Memento is a class independent container for persistence - * info. It is a reflection of 3 storage requirements. - * - * 1) We need the ability to persist an object and restore it. - * 2) The class for an object may be absent. If so we would - * like to skip the object and keep reading. - * 3) The class for an object may change. If so the new class - * should be able to read the old persistence info. - * - * We could ask the objects to serialize themselves into an - * ObjectOutputStream, DataOutputStream, or Hashtable. However - * all of these approaches fail to meet the second requirement. - * + * A Memento is a class independent container for persistence info. It is a + * reflection of 3 storage requirements. + * + * 1) We need the ability to persist an object and restore it. 2) The class for + * an object may be absent. If so we would like to skip the object and keep + * reading. 3) The class for an object may change. If so the new class should be + * able to read the old persistence info. + * + * We could ask the objects to serialize themselves into an ObjectOutputStream, + * DataOutputStream, or Hashtable. However all of these approaches fail to meet + * the second requirement. + * * Memento supports binary persistance with a version ID. */ public final class XMLMemento implements IMemento { private Document factory; + private Element element; /** - * Answer a memento for the document and element. For simplicity - * you should use createReadRoot and createWriteRoot to create the initial - * mementos on a document. + * Answer a memento for the document and element. For simplicity you should + * use createReadRoot and createWriteRoot to create the initial mementos on + * a document. */ public XMLMemento(Document doc, Element el) { factory = doc; @@ -93,13 +94,14 @@ public final class XMLMemento implements IMemento { } /** - * Create a Document from a Reader and answer a root memento for reading - * a document. + * Create a Document from a Reader and answer a root memento for reading a + * document. */ protected static XMLMemento createReadRoot(Reader reader) { Document document = null; try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilderFactory factory = DocumentBuilderFactory + .newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); document = parser.parse(new InputSource(reader)); Node node = document.getFirstChild(); @@ -111,7 +113,8 @@ public final class XMLMemento implements IMemento { } finally { try { reader.close(); - } catch (Exception e) { } + } catch (Exception e) { + } } return null; } @@ -122,7 +125,8 @@ public final class XMLMemento implements IMemento { public static XMLMemento createWriteRoot(String type) { Document document; try { - document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); + document = DocumentBuilderFactory.newInstance() + .newDocumentBuilder().newDocument(); Element element = document.createElement(type); document.appendChild(element); return new XMLMemento(document, element); @@ -142,10 +146,10 @@ public final class XMLMemento implements IMemento { return null; // Find the first node which is a child of this node. - for (int nX = 0; nX < size; nX ++) { + for (int nX = 0; nX < size; nX++) { Node node = nodes.item(nX); if (node instanceof Element) { - Element element2 = (Element)node; + Element element2 = (Element) node; if (element2.getNodeName().equals(type)) return new XMLMemento(factory, element2); } @@ -158,7 +162,7 @@ public final class XMLMemento implements IMemento { /** * @see IMemento. */ - public IMemento [] getChildren(String type) { + public IMemento[] getChildren(String type) { // Get the nodes. NodeList nodes = element.getChildNodes(); int size = nodes.getLength(); @@ -167,10 +171,10 @@ public final class XMLMemento implements IMemento { // Extract each node with given fType. ArrayList list = new ArrayList(size); - for (int nX = 0; nX < size; nX ++) { + for (int nX = 0; nX < size; nX++) { Node node = nodes.item(nX); if (node instanceof Element) { - Element element2 = (Element)node; + Element element2 = (Element) node; if (element2.getNodeName().equals(type)) list.add(element2); } @@ -178,16 +182,16 @@ public final class XMLMemento implements IMemento { // Create a memento for each node. size = list.size(); - IMemento [] results = new IMemento[size]; - for (int x = 0; x < size; x ++) { - results[x] = new XMLMemento(factory, (Element)list.get(x)); + IMemento[] results = new IMemento[size]; + for (int x = 0; x < size; x++) { + results[x] = new XMLMemento(factory, (Element) list.get(x)); } return results; } /** * Return the contents of this memento as a byte array. - * + * * @return byte[] */ public byte[] getContents() throws IOException { @@ -198,7 +202,7 @@ public final class XMLMemento implements IMemento { /** * Returns an input stream for writing to the disk with a local locale. - * + * * @return java.io.InputStream */ public InputStream getInputStream() throws IOException { @@ -275,8 +279,9 @@ public final class XMLMemento implements IMemento { /** * Loads a memento from the given filename. - * - * @param in java.io.InputStream + * + * @param in + * java.io.InputStream * @return org.eclipse.ui.IMemento * @exception java.io.IOException */ @@ -286,15 +291,17 @@ public final class XMLMemento implements IMemento { /** * Loads a memento from the given filename. - * - * @param in java.io.InputStream + * + * @param in + * java.io.InputStream * @return org.eclipse.ui.IMemento * @exception java.io.IOException */ public static IMemento loadCorruptMemento(InputStream in) { Document document = null; try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilderFactory factory = DocumentBuilderFactory + .newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); document = parser.parse(in); Node node = document.getFirstChild(); @@ -306,15 +313,17 @@ public final class XMLMemento implements IMemento { } finally { try { in.close(); - } catch (Exception e) { } + } catch (Exception e) { + } } return null; } /** * Loads a memento from the given filename. - * - * @param filename java.lang.String + * + * @param filename + * java.lang.String * @return org.eclipse.ui.IMemento * @exception java.io.IOException */ @@ -324,13 +333,15 @@ public final class XMLMemento implements IMemento { /** * Loads a memento from the given filename. - * - * @param url java.net.URL + * + * @param url + * java.net.URL * @return org.eclipse.ui.IMemento * @exception java.io.IOException */ public static IMemento loadMemento(URL url) throws IOException { - return XMLMemento.createReadRoot(new InputStreamReader(url.openStream())); + return XMLMemento + .createReadRoot(new InputStreamReader(url.openStream())); } /** @@ -339,18 +350,18 @@ public final class XMLMemento implements IMemento { private void putElement(Element element2) { NamedNodeMap nodeMap = element2.getAttributes(); int size = nodeMap.getLength(); - for (int i = 0; i < size; i++){ - Attr attr = (Attr)nodeMap.item(i); - putString(attr.getName(),attr.getValue()); + for (int i = 0; i < size; i++) { + Attr attr = (Attr) nodeMap.item(i); + putString(attr.getName(), attr.getValue()); } NodeList nodes = element2.getChildNodes(); size = nodes.getLength(); - for (int i = 0; i < size; i ++) { + for (int i = 0; i < size; i++) { Node node = nodes.item(i); if (node instanceof Element) { - XMLMemento child = (XMLMemento)createChild(node.getNodeName()); - child.putElement((Element)node); + XMLMemento child = (XMLMemento) createChild(node.getNodeName()); + child.putElement((Element) node); } } } @@ -393,7 +404,8 @@ public final class XMLMemento implements IMemento { Result result = new StreamResult(writer); Source source = new DOMSource(factory); try { - Transformer transformer = TransformerFactory.newInstance().newTransformer(); + Transformer transformer = TransformerFactory.newInstance() + .newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$ transformer.transform(source, result); @@ -409,7 +421,8 @@ public final class XMLMemento implements IMemento { Result result = new StreamResult(os); Source source = new DOMSource(factory); try { - Transformer transformer = TransformerFactory.newInstance().newTransformer(); + Transformer transformer = TransformerFactory.newInstance() + .newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$ transformer.transform(source, result); @@ -420,8 +433,9 @@ public final class XMLMemento implements IMemento { /** * Saves the memento to the given file. - * - * @param filename java.lang.String + * + * @param filename + * java.lang.String * @exception java.io.IOException */ public void saveToFile(String filename) throws IOException { @@ -437,7 +451,8 @@ public final class XMLMemento implements IMemento { if (w != null) { try { w.close(); - } catch (Exception e) { } + } catch (Exception e) { + } } } } diff --git a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/ConfigurationComposite.java b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/ConfigurationComposite.java index 47ba4b6..7eed4fe 100644 --- a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/ConfigurationComposite.java +++ b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/ConfigurationComposite.java @@ -4,7 +4,7 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation **********************************************************************/ @@ -37,17 +37,21 @@ import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; + /** - * + * */ public class ConfigurationComposite extends Composite { protected Table table; + protected TableViewer tableViewer; protected Button edit; + protected Button remove; -// protected Button start; -// protected Button stop; + + // protected Button start; + // protected Button stop; protected List selection2; @@ -71,15 +75,18 @@ public class ConfigurationComposite extends Composite { Label label = new Label(this, SWT.WRAP); label.setText(PHPHelpPlugin.getResource("%configurationsList")); - label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_CENTER)); + label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL + | GridData.VERTICAL_ALIGN_CENTER)); label = new Label(this, SWT.NONE); - table = new Table(this, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.FULL_SELECTION); - data = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL); + table = new Table(this, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL + | SWT.MULTI | SWT.FULL_SELECTION); + data = new GridData(GridData.FILL_HORIZONTAL + | GridData.VERTICAL_ALIGN_FILL); data.widthHint = 300; data.heightHint = 300; -// WorkbenchHelp.setHelp(table, ContextIds.PREF_MONITORS); + // WorkbenchHelp.setHelp(table, ContextIds.PREF_MONITORS); table.setLayoutData(data); table.setHeaderVisible(true); @@ -97,10 +104,10 @@ public class ConfigurationComposite extends Composite { colData = new ColumnWeightData(5, 30, true); tableLayout.addColumnData(colData); -// TableColumn urlColumn = new TableColumn(table, SWT.NONE); -// urlColumn.setText(PHPHelpPlugin.getResource("%columnUser")); -// colData = new ColumnWeightData(5, 30, true); -// tableLayout.addColumnData(colData); + // TableColumn urlColumn = new TableColumn(table, SWT.NONE); + // urlColumn.setText(PHPHelpPlugin.getResource("%columnUser")); + // colData = new ColumnWeightData(5, 30, true); + // tableLayout.addColumnData(colData); TableColumn localColumn = new TableColumn(table, SWT.NONE); localColumn.setText(PHPHelpPlugin.getResource("%columnURL")); @@ -113,11 +120,12 @@ public class ConfigurationComposite extends Composite { tableViewer.setContentProvider(new ConfigurationContentProvider()); tableViewer.setLabelProvider(new ConfigurationTableLabelProvider()); tableViewer.setInput("root"); - tableViewer.addSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - setSelection(event.getSelection()); - } - }); + tableViewer + .addSelectionChangedListener(new ISelectionChangedListener() { + public void selectionChanged(SelectionChangedEvent event) { + setSelection(event.getSelection()); + } + }); Composite buttonComp = new Composite(this, SWT.NONE); layout = new GridLayout(); @@ -127,10 +135,12 @@ public class ConfigurationComposite extends Composite { layout.marginHeight = 0; layout.numColumns = 1; buttonComp.setLayout(layout); - data = new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.VERTICAL_ALIGN_FILL); + data = new GridData(GridData.HORIZONTAL_ALIGN_END + | GridData.VERTICAL_ALIGN_FILL); buttonComp.setLayoutData(data); - Button add = SWTUtil.createButton(buttonComp, PHPHelpPlugin.getResource("%add")); + Button add = SWTUtil.createButton(buttonComp, PHPHelpPlugin + .getResource("%add")); add.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { ConfigurationDialog dialog = new ConfigurationDialog(getShell()); @@ -140,27 +150,32 @@ public class ConfigurationComposite extends Composite { List list = PHPHelpPlugin.getConfigurations(); Object configuration = list.get(list.size() - 1); - tableViewer.setSelection(new StructuredSelection(configuration)); + tableViewer + .setSelection(new StructuredSelection(configuration)); } }); - edit = SWTUtil.createButton(buttonComp, PHPHelpPlugin.getResource("%edit")); + edit = SWTUtil.createButton(buttonComp, PHPHelpPlugin + .getResource("%edit")); edit.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { IConfiguration monitor = (IConfiguration) getSelection().get(0); IConfigurationWorkingCopy wc = monitor.getWorkingCopy(); - ConfigurationDialog dialog = new ConfigurationDialog(getShell(), wc); + ConfigurationDialog dialog = new ConfigurationDialog( + getShell(), wc); if (dialog.open() != Window.CANCEL) { try { tableViewer.refresh(wc.save()); - } catch (Exception ex) { } + } catch (Exception ex) { + } } } }); edit.setEnabled(false); - remove = SWTUtil.createButton(buttonComp, PHPHelpPlugin.getResource("%remove")); + remove = SWTUtil.createButton(buttonComp, PHPHelpPlugin + .getResource("%remove")); remove.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { Iterator iterator = getSelection().iterator(); @@ -168,7 +183,8 @@ public class ConfigurationComposite extends Composite { IConfiguration monitor = (IConfiguration) iterator.next(); try { monitor.delete(); - } catch (Exception ex) { } + } catch (Exception ex) { + } tableViewer.remove(monitor); List list = PHPHelpPlugin.getConfigurations(); diff --git a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/ConfigurationContentProvider.java b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/ConfigurationContentProvider.java index 0fd236f..87d989b 100644 --- a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/ConfigurationContentProvider.java +++ b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/ConfigurationContentProvider.java @@ -4,7 +4,7 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html -  * + �* * Contributors: * IBM - Initial API and implementation **********************************************************************/ @@ -32,19 +32,19 @@ public class ConfigurationContentProvider implements IStructuredContentProvider } /** - * Disposes of this content provider. This is called by the viewer when it is - * disposed. + * Disposes of this content provider. This is called by the viewer when it + * is disposed. */ public void dispose() { } /** - * Returns the elements to display in the viewer when its input is set to the - * given element. These elements can be presented as rows in a table, items in - * a list, etc. The result is not modified by the viewer. - * + * Returns the elements to display in the viewer when its input is set to + * the given element. These elements can be presented as rows in a table, + * items in a list, etc. The result is not modified by the viewer. + * * @param inputElement - * the input element + * the input element * @return the array of elements to display in the viewer */ public Object[] getElements(Object inputElement) { @@ -66,15 +66,15 @@ public class ConfigurationContentProvider implements IStructuredContentProvider * deregistering the viewer from the old input. In response to these change * notifications, the content provider propagates the changes to the viewer. *

- * + * * @param viewer - * the viewer + * the viewer * @param oldInput - * the old input element, or null if the viewer did - * not previously have an input + * the old input element, or null if the viewer + * did not previously have an input * @param newInput - * the new input element, or null if the viewer does - * not have an input + * the new input element, or null if the viewer + * does not have an input */ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } diff --git a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/ConfigurationDialog.java b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/ConfigurationDialog.java index 634befb..70effbe 100644 --- a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/ConfigurationDialog.java +++ b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/ConfigurationDialog.java @@ -34,7 +34,7 @@ import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; /** - * + * */ public class ConfigurationDialog extends Dialog { protected IConfigurationWorkingCopy fConfiguration; @@ -47,7 +47,7 @@ public class ConfigurationDialog extends Dialog { private Text fUrl; -// private Text fPassword; + // private Text fPassword; interface StringModifyListener { public void valueChanged(String s); @@ -64,7 +64,8 @@ public class ConfigurationDialog extends Dialog { /** * @param parentShell */ - public ConfigurationDialog(Shell parentShell, IConfigurationWorkingCopy configuration) { + public ConfigurationDialog(Shell parentShell, + IConfigurationWorkingCopy configuration) { super(parentShell); this.fConfiguration = configuration; isEdit = true; @@ -87,15 +88,18 @@ public class ConfigurationDialog extends Dialog { protected Label createLabel(Composite comp, String txt) { Label label = new Label(comp, SWT.NONE); label.setText(txt); - label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_BEGINNING)); + label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING + | GridData.VERTICAL_ALIGN_BEGINNING)); return label; } - protected Text createPassword(Composite comp, String txt, final StringModifyListener listener) { + protected Text createPassword(Composite comp, String txt, + final StringModifyListener listener) { final Text text = new Text(comp, SWT.BORDER | SWT.PASSWORD); if (txt != null) text.setText(txt); - GridData data = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); + GridData data = new GridData(GridData.FILL_HORIZONTAL + | GridData.VERTICAL_ALIGN_BEGINNING); data.widthHint = 150; text.setLayoutData(data); if (listener != null) @@ -107,11 +111,13 @@ public class ConfigurationDialog extends Dialog { return text; } - protected Text createText(Composite comp, String txt, final StringModifyListener listener) { + protected Text createText(Composite comp, String txt, + final StringModifyListener listener) { final Text text = new Text(comp, SWT.BORDER); if (txt != null) text.setText(txt); - GridData data = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); + GridData data = new GridData(GridData.FILL_HORIZONTAL + | GridData.VERTICAL_ALIGN_BEGINNING); data.widthHint = 150; text.setLayoutData(data); if (listener != null) @@ -123,7 +129,8 @@ public class ConfigurationDialog extends Dialog { return text; } - protected Combo createTypeCombo(Composite comp, final ArrayList types, String sel, final TypeModifyListener listener) { + protected Combo createTypeCombo(Composite comp, final ArrayList types, + String sel, final TypeModifyListener listener) { final Combo combo = new Combo(comp, SWT.DROP_DOWN | SWT.READ_ONLY); int size = types.size(); String[] items = new String[size]; @@ -136,13 +143,15 @@ public class ConfigurationDialog extends Dialog { combo.setItems(items); if (index >= 0) combo.select(index); - GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_BEGINNING); + GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL + | GridData.VERTICAL_ALIGN_BEGINNING); data.widthHint = 150; combo.setLayoutData(data); if (listener != null) combo.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { - listener.valueChanged((String) types.get(combo.getSelectionIndex())); + listener.valueChanged((String) types.get(combo + .getSelectionIndex())); } public void widgetDefaultSelected(SelectionEvent e) { @@ -159,12 +168,13 @@ public class ConfigurationDialog extends Dialog { // WorkbenchHelp.setHelp(composite, ContextIds.PREF_DIALOG); createLabel(composite, PHPHelpPlugin.getResource("%name")); - fName = createText(composite, fConfiguration.getName() + "", new StringModifyListener() { - public void valueChanged(String name) { - fConfiguration.setName(name); - validateFields(); - } - }); + fName = createText(composite, fConfiguration.getName() + "", + new StringModifyListener() { + public void valueChanged(String name) { + fConfiguration.setName(name); + validateFields(); + } + }); Group group = new Group(composite, SWT.NONE); GridLayout layout = new GridLayout(2, false); @@ -175,26 +185,28 @@ public class ConfigurationDialog extends Dialog { group.setLayoutData(data); group.setText(PHPHelpPlugin.getResource("%configGroup")); -// createLabel(group, PHPHelpPlugin.getResource("%user")); -// fUserName = createText(group, fConfiguration.getUser() + "", new StringModifyListener() { -// public void valueChanged(String s) { -// fConfiguration.setUser(s); -// validateFields(); -// } -// }); - -// Composite warningComposite = new Composite(group, SWT.NONE); -// layout = new GridLayout(); -// layout.numColumns = 2; -// layout.marginHeight = 0; -// layout.marginHeight = 0; -// warningComposite.setLayout(layout); -// data = new GridData(GridData.FILL_HORIZONTAL); -// data.horizontalSpan = 3; -// warningComposite.setLayoutData(data); + // createLabel(group, PHPHelpPlugin.getResource("%user")); + // fUserName = createText(group, fConfiguration.getUser() + "", new + // StringModifyListener() { + // public void valueChanged(String s) { + // fConfiguration.setUser(s); + // validateFields(); + // } + // }); + + // Composite warningComposite = new Composite(group, SWT.NONE); + // layout = new GridLayout(); + // layout.numColumns = 2; + // layout.marginHeight = 0; + // layout.marginHeight = 0; + // warningComposite.setLayout(layout); + // data = new GridData(GridData.FILL_HORIZONTAL); + // data.horizontalSpan = 3; + // warningComposite.setLayoutData(data); // Label warningLabel = new Label(warningComposite, SWT.NONE); // warningLabel.setImage(getImage(DLG_IMG_MESSAGE_WARNING)); - // warningLabel.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING + // warningLabel.setLayoutData(new + // GridData(GridData.VERTICAL_ALIGN_BEGINNING // | GridData.HORIZONTAL_ALIGN_BEGINNING)); // Label warningText = new Label(warningComposite, SWT.WRAP); // warningText.setText(PHPHelpPlugin.getResource("%scrambledPassword")); @@ -203,24 +215,27 @@ public class ConfigurationDialog extends Dialog { // data.widthHint = 300; // warningText.setLayoutData(data); -// createLabel(group, PHPHelpPlugin.getResource("%password")); -// fPassword = createPassword(group, fConfiguration.getPassword() + "", new StringModifyListener() { -// public void valueChanged(String s) { -// fConfiguration.setPassword(s); -// validateFields(); -// } -// }); + // createLabel(group, PHPHelpPlugin.getResource("%password")); + // fPassword = createPassword(group, fConfiguration.getPassword() + "", + // new StringModifyListener() { + // public void valueChanged(String s) { + // fConfiguration.setPassword(s); + // validateFields(); + // } + // }); createLabel(group, PHPHelpPlugin.getResource("%url")); - fUrl = createText(group, fConfiguration.getURL(), new StringModifyListener() { - public void valueChanged(String s) { - fConfiguration.setURL(s); - validateFields(); - } - }); + fUrl = createText(group, fConfiguration.getURL(), + new StringModifyListener() { + public void valueChanged(String s) { + fConfiguration.setURL(s); + validateFields(); + } + }); createLabel(group, PHPHelpPlugin.getResource("%parseType")); - createTypeCombo(group, PHPHelpPlugin.getTypes(), fConfiguration.getType(), new TypeModifyListener() { + createTypeCombo(group, PHPHelpPlugin.getTypes(), fConfiguration + .getType(), new TypeModifyListener() { public void valueChanged(String fType) { fConfiguration.setType(fType); } diff --git a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/ConfigurationPreferencePage.java b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/ConfigurationPreferencePage.java index ad23c6f..3602db5 100644 --- a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/ConfigurationPreferencePage.java +++ b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/ConfigurationPreferencePage.java @@ -4,13 +4,12 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation **********************************************************************/ package net.sourceforge.phpdt.httpquery.preferences; - import net.sourceforge.phpdt.phphelp.PHPHelpPlugin; import org.eclipse.jface.dialogs.Dialog; @@ -23,10 +22,12 @@ import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; + /** * The preference page that holds monitor properties. */ -public class ConfigurationPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { +public class ConfigurationPreferencePage extends PreferencePage implements + IWorkbenchPreferencePage { /** * ConfigurationPreferencePage constructor comment. @@ -38,8 +39,9 @@ public class ConfigurationPreferencePage extends PreferencePage implements IWork /** * Create the preference options. - * - * @param parent org.eclipse.swt.widgets.Composite + * + * @param parent + * org.eclipse.swt.widgets.Composite * @return org.eclipse.swt.widgets.Control */ protected Control createContents(Composite parent) { @@ -53,9 +55,10 @@ public class ConfigurationPreferencePage extends PreferencePage implements IWork layout.marginWidth = 0; layout.marginHeight = 0; composite.setLayout(layout); - GridData data = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL); + GridData data = new GridData(GridData.FILL_HORIZONTAL + | GridData.VERTICAL_ALIGN_FILL); composite.setLayoutData(data); -// WorkbenchHelp.setHelp(composite, ContextIds.PREF); + // WorkbenchHelp.setHelp(composite, ContextIds.PREF); Label label = new Label(composite, SWT.WRAP); label.setText(PHPHelpPlugin.getResource("%preferenceDescription")); @@ -65,7 +68,8 @@ public class ConfigurationPreferencePage extends PreferencePage implements IWork label = new Label(composite, SWT.NONE); label.setText(""); - ConfigurationComposite monitorComp = new ConfigurationComposite(composite, SWT.NONE); + ConfigurationComposite monitorComp = new ConfigurationComposite( + composite, SWT.NONE); data = new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL); monitorComp.setLayoutData(data); @@ -76,31 +80,32 @@ public class ConfigurationPreferencePage extends PreferencePage implements IWork /** * Initializes this preference page using the passed desktop. - * - * @param desktop the current desktop + * + * @param desktop + * the current desktop */ public void init(IWorkbench workbench) { } /** - * Performs special processing when this page's Defaults button has been pressed. + * Performs special processing when this page's Defaults button has been + * pressed. *

* This is a framework hook method for sublcasses to do special things when - * the Defaults button has been pressed. - * Subclasses may override, but should call super.performDefaults. + * the Defaults button has been pressed. Subclasses may override, but should + * call super.performDefaults. *

*/ protected void performDefaults() { -// displayButton.setSelection(WikiEditorPlugin.getDefaultShowOnActivityPreference()); + // displayButton.setSelection(WikiEditorPlugin.getDefaultShowOnActivityPreference()); super.performDefaults(); } /** - * Method declared on IPreferencePage. - * Subclasses should override + * Method declared on IPreferencePage. Subclasses should override */ public boolean performOk() { -// WikiEditorPlugin.setShowOnActivityPreference(displayButton.getSelection()); + // WikiEditorPlugin.setShowOnActivityPreference(displayButton.getSelection()); PHPHelpPlugin.getDefault().savePluginPreferences(); return true; } diff --git a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/ConfigurationPreferencesDialog.java b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/ConfigurationPreferencesDialog.java index 98682f7..aeb8d8e 100644 --- a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/ConfigurationPreferencesDialog.java +++ b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/ConfigurationPreferencesDialog.java @@ -4,7 +4,7 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html -  * + �* * Contributors: * IBM - Initial API and implementation **********************************************************************/ @@ -23,53 +23,55 @@ import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; public class ConfigurationPreferencesDialog extends Dialog { - protected IConfigurationWorkingCopy monitor; + protected IConfigurationWorkingCopy monitor; - protected boolean isEdit; + protected boolean isEdit; - /** - * @param parentShell - */ - public ConfigurationPreferencesDialog(Shell parentShell, IConfigurationWorkingCopy monitor) { - super(parentShell); - this.monitor = monitor; - isEdit = true; - } + /** + * @param parentShell + */ + public ConfigurationPreferencesDialog(Shell parentShell, + IConfigurationWorkingCopy monitor) { + super(parentShell); + this.monitor = monitor; + isEdit = true; + } - public ConfigurationPreferencesDialog(Shell composite) { - super(composite); - isEdit = false; - } + public ConfigurationPreferencesDialog(Shell composite) { + super(composite); + isEdit = false; + } - protected void configureShell(Shell shell) { - super.configureShell(shell); - shell.setText(PHPHelpPlugin.getResource("%preferenceTitle")); - } + protected void configureShell(Shell shell) { + super.configureShell(shell); + shell.setText(PHPHelpPlugin.getResource("%preferenceTitle")); + } - protected Control createDialogArea(Composite parent) { - Composite compositeParent = (Composite) super.createDialogArea(parent); + protected Control createDialogArea(Composite parent) { + Composite compositeParent = (Composite) super.createDialogArea(parent); - Composite composite = new Composite(compositeParent, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.marginHeight = convertHorizontalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); - layout.marginWidth = convertVerticalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); - layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); - composite.setLayout(layout); - GridData data = new GridData(GridData.FILL_BOTH); - composite.setLayoutData(data); - // WorkbenchHelp.setHelp(composite, ContextIds.PREF); + Composite composite = new Composite(compositeParent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginHeight = convertHorizontalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); + layout.marginWidth = convertVerticalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); + layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); + composite.setLayout(layout); + GridData data = new GridData(GridData.FILL_BOTH); + composite.setLayoutData(data); + // WorkbenchHelp.setHelp(composite, ContextIds.PREF); - ConfigurationComposite monitorComp = new ConfigurationComposite(composite, SWT.NONE); - data = new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL); - monitorComp.setLayoutData(data); + ConfigurationComposite monitorComp = new ConfigurationComposite( + composite, SWT.NONE); + data = new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL); + monitorComp.setLayoutData(data); - Dialog.applyDialogFont(composite); + Dialog.applyDialogFont(composite); - return composite; - } + return composite; + } - protected void okPressed() { - PHPHelpPlugin.getDefault().savePluginPreferences(); - super.okPressed(); - } + protected void okPressed() { + PHPHelpPlugin.getDefault().savePluginPreferences(); + super.okPressed(); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/ConfigurationTableLabelProvider.java b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/ConfigurationTableLabelProvider.java index 8d7229e..1f25835 100644 --- a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/ConfigurationTableLabelProvider.java +++ b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/ConfigurationTableLabelProvider.java @@ -4,7 +4,7 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html -  * + �* * Contributors: * IBM - Initial API and implementation **********************************************************************/ @@ -20,96 +20,104 @@ import org.eclipse.swt.graphics.Image; * Configuration table label provider. */ public class ConfigurationTableLabelProvider implements ITableLabelProvider { - /** - * ConfigurationTableLabelProvider constructor comment. - */ - public ConfigurationTableLabelProvider() { - super(); - } + /** + * ConfigurationTableLabelProvider constructor comment. + */ + public ConfigurationTableLabelProvider() { + super(); + } - /** - * Adds a listener to this label provider. Has no effect if an identical listener is already registered. - *

- * Label provider listeners are informed about state changes that affect the rendering of the viewer that uses this label - * provider. - *

- * - * @param listener - * a label provider listener - */ - public void addListener(ILabelProviderListener listener) { - } + /** + * Adds a listener to this label provider. Has no effect if an identical + * listener is already registered. + *

+ * Label provider listeners are informed about state changes that affect the + * rendering of the viewer that uses this label provider. + *

+ * + * @param listener + * a label provider listener + */ + public void addListener(ILabelProviderListener listener) { + } - /** - * Disposes of this label provider. When a label provider is attached to a viewer, the viewer will automatically call this method - * when the viewer is being closed. When label providers are used outside of the context of a viewer, it is the client's - * responsibility to ensure that this method is called when the provider is no longer needed. - */ - public void dispose() { - } + /** + * Disposes of this label provider. When a label provider is attached to a + * viewer, the viewer will automatically call this method when the viewer is + * being closed. When label providers are used outside of the context of a + * viewer, it is the client's responsibility to ensure that this method is + * called when the provider is no longer needed. + */ + public void dispose() { + } - /** - * Returns the label image for the given column of the given element. - * - * @param element - * the object representing the entire row, or null indicating that no input object is set in the viewer - * @param columnIndex - * the zero-based index of the column in which the label appears - */ - public Image getColumnImage(Object element, int columnIndex) { - return null; - } + /** + * Returns the label image for the given column of the given element. + * + * @param element + * the object representing the entire row, or null + * indicating that no input object is set in the viewer + * @param columnIndex + * the zero-based index of the column in which the label appears + */ + public Image getColumnImage(Object element, int columnIndex) { + return null; + } - /** - * Returns the label text for the given column of the given element. - * - * @param element - * the object representing the entire row, or null indicating that no input object is set in the viewer - * @param columnIndex - * the zero-based index of the column in which the label appears - */ - public String getColumnText(Object element, int columnIndex) { - IConfiguration configuration = (IConfiguration) element; - if (columnIndex == 0) { - return configuration.getName(); - } else if (columnIndex == 1) - return configuration.getType(); -// else if (columnIndex == 2) -// return configuration.getUser(); - else if (columnIndex == 2) - return configuration.getURL(); - else - return "X"; - } + /** + * Returns the label text for the given column of the given element. + * + * @param element + * the object representing the entire row, or null + * indicating that no input object is set in the viewer + * @param columnIndex + * the zero-based index of the column in which the label appears + */ + public String getColumnText(Object element, int columnIndex) { + IConfiguration configuration = (IConfiguration) element; + if (columnIndex == 0) { + return configuration.getName(); + } else if (columnIndex == 1) + return configuration.getType(); + // else if (columnIndex == 2) + // return configuration.getUser(); + else if (columnIndex == 2) + return configuration.getURL(); + else + return "X"; + } - protected String notNull(String s) { - if (s != null) - return s; - else - return ""; - } + protected String notNull(String s) { + if (s != null) + return s; + else + return ""; + } - /** - * Returns whether the label would be affected by a change to the given property of the given element. This can be used to - * optimize a non-structural viewer update. If the property mentioned in the update does not affect the label, then the viewer - * need not update the label. - * - * @param element - * the element - * @param property - * the property - * @return true if the label would be affected, and false if it would be unaffected - */ - public boolean isLabelProperty(Object element, String property) { - return false; - } + /** + * Returns whether the label would be affected by a change to the given + * property of the given element. This can be used to optimize a + * non-structural viewer update. If the property mentioned in the update + * does not affect the label, then the viewer need not update the label. + * + * @param element + * the element + * @param property + * the property + * @return true if the label would be affected, and + * false if it would be unaffected + */ + public boolean isLabelProperty(Object element, String property) { + return false; + } - /** - * Removes a listener to this label provider. Has no affect if an identical listener is not registered. - * - * @param listener - * a label provider listener - */ - public void removeListener(ILabelProviderListener listener) { - } + /** + * Removes a listener to this label provider. Has no affect if an identical + * listener is not registered. + * + * @param listener + * a label provider listener + */ + public void removeListener(ILabelProviderListener listener) { + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/SWTUtil.java b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/SWTUtil.java index 2701b21..10223cf 100644 --- a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/SWTUtil.java +++ b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/httpquery/preferences/SWTUtil.java @@ -1,10 +1,10 @@ /********************************************************************** * Copyright (c) 2003 IBM Corporation and others. - * All rights reserved.   This program and the accompanying materials + * All rights reserved. � This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation **********************************************************************/ @@ -22,6 +22,7 @@ import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; + /** * SWT Utility class. */ @@ -40,38 +41,45 @@ public class SWTUtil { * Returns a width hint for a button control. */ protected static int getButtonWidthHint(Button button) { - int widthHint = Dialog.convertHorizontalDLUsToPixels(fontMetrics, IDialogConstants.BUTTON_WIDTH); - return Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x); + int widthHint = Dialog.convertHorizontalDLUsToPixels(fontMetrics, + IDialogConstants.BUTTON_WIDTH); + return Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAULT, + true).x); } - + public static Button createButton(Composite comp, String label) { Button b = new Button(comp, SWT.PUSH); b.setText(label); if (fontMetrics == null) initializeDialogUnits(comp); - GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_BEGINNING); + GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL + | GridData.VERTICAL_ALIGN_BEGINNING); data.widthHint = getButtonWidthHint(b); - data.heightHint = Dialog.convertVerticalDLUsToPixels(fontMetrics, IDialogConstants.BUTTON_HEIGHT); + data.heightHint = Dialog.convertVerticalDLUsToPixels(fontMetrics, + IDialogConstants.BUTTON_HEIGHT); b.setLayoutData(data); return b; } - - public static Button createCheckbox(Composite comp, String txt, boolean isSelected){ + + public static Button createCheckbox(Composite comp, String txt, + boolean isSelected) { Button button = new Button(comp, SWT.CHECK); button.setText(txt); GridLayout layout = new GridLayout(); comp.setLayout(layout); - GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_BEGINNING); + GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL + | GridData.VERTICAL_ALIGN_BEGINNING); data.horizontalIndent = 10; button.setLayoutData(data); button.setSelection(isSelected); return button; } - + public static Label createLabel(Composite comp, String txt) { Label label = new Label(comp, SWT.NONE); label.setText(txt); - label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_BEGINNING)); + label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING + | GridData.VERTICAL_ALIGN_BEGINNING)); return label; } } diff --git a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/phphelp/PHPHelpPlugin.java b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/phphelp/PHPHelpPlugin.java index 0b1567a..e388fb1 100644 --- a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/phphelp/PHPHelpPlugin.java +++ b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/phphelp/PHPHelpPlugin.java @@ -66,6 +66,7 @@ public class PHPHelpPlugin extends AbstractUIPlugin { private static PHPHelpPlugin plugin; private static ConfigurationManager manager; + /** * The constructor. */ @@ -93,7 +94,8 @@ public class PHPHelpPlugin extends AbstractUIPlugin { } private IWorkbenchPage internalGetActivePage() { - IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + IWorkbenchWindow window = PlatformUI.getWorkbench() + .getActiveWorkbenchWindow(); if (window != null) return window.getActivePage(); return null; @@ -112,12 +114,14 @@ public class PHPHelpPlugin extends AbstractUIPlugin { } public static void log(int severity, String message) { - Status status = new Status(severity, PLUGIN_ID, IStatus.OK, message, null); + Status status = new Status(severity, PLUGIN_ID, IStatus.OK, message, + null); log(status); } public static void log(Throwable e) { - log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.ERROR, "PHPeclipsePlugin.internalErrorOccurred", e)); //$NON-NLS-1$ + log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.ERROR, + "PHPeclipsePlugin.internalErrorOccurred", e)); //$NON-NLS-1$ } public static boolean isDebug() { @@ -132,8 +136,11 @@ public class PHPHelpPlugin extends AbstractUIPlugin { if (windowsSystem.equals(Platform.WS_WIN32)) { store.setDefault(PHP_CHM_ENABLED, "false"); - store.setDefault(PHP_CHM_FILE, "c:\\wampp2\\php\\php_manual_en.chm"); - store.setDefault(PHP_CHM_COMMAND, "hh.exe \"mk:@MSITStore:{0}::/en/function.{1}.html\""); + store + .setDefault(PHP_CHM_FILE, + "c:\\wampp2\\php\\php_manual_en.chm"); + store.setDefault(PHP_CHM_COMMAND, + "hh.exe \"mk:@MSITStore:{0}::/en/function.{1}.html\""); } else { store.setDefault(PHP_CHM_ENABLED, "false"); store.setDefault(PHP_CHM_FILE, ""); @@ -203,10 +210,10 @@ public class PHPHelpPlugin extends AbstractUIPlugin { /** * Returns the translated String found with the given key. - * + * * @return java.lang.String * @param key - * java.lang.String + * java.lang.String */ public static String getResource(String key) { try { @@ -218,7 +225,7 @@ public class PHPHelpPlugin extends AbstractUIPlugin { /** * Return a list of all the existing configurations. - * + * * @return java.util.List */ public static List getConfigurations() { @@ -227,7 +234,7 @@ public class PHPHelpPlugin extends AbstractUIPlugin { /** * Create a new monitor. - * + * * @return working copy */ public static IConfigurationWorkingCopy createConfiguration() { diff --git a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/phphelp/actions/PHPFunctionHelpResource.java b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/phphelp/actions/PHPFunctionHelpResource.java index d07bfc7..3aca93f 100644 --- a/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/phphelp/actions/PHPFunctionHelpResource.java +++ b/net.sourceforge.phpeclipse.phphelp/src/net/sourceforge/phpdt/phphelp/actions/PHPFunctionHelpResource.java @@ -14,7 +14,7 @@ package net.sourceforge.phpdt.phphelp.actions; import org.eclipse.help.IHelpResource; /** - * + * */ public class PHPFunctionHelpResource implements IHelpResource { @@ -26,7 +26,7 @@ public class PHPFunctionHelpResource implements IHelpResource { /** * Get standard PHPEclipse html help URL - * + * * @return String */ public String getHref() { diff --git a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/PHPUnitImages.java b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/PHPUnitImages.java index f5126d3..89b5108 100644 --- a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/PHPUnitImages.java +++ b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/PHPUnitImages.java @@ -15,11 +15,10 @@ import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.swt.graphics.Image; - public class PHPUnitImages { - protected static final String NAME_PREFIX = - "net.sourceforge.phpeclipse.phpunit"; + protected static final String NAME_PREFIX = "net.sourceforge.phpeclipse.phpunit"; + protected static final int NAME_PREFIX_LENGTH = NAME_PREFIX.length(); protected static URL iconBaseURL; @@ -27,12 +26,10 @@ public class PHPUnitImages { static { String pathSuffix = "icons/"; try { - iconBaseURL = - new URL( - PHPUnitPlugin.getDefault().getDescriptor().getInstallURL(), - pathSuffix); + iconBaseURL = new URL(PHPUnitPlugin.getDefault().getDescriptor() + .getInstallURL(), pathSuffix); } catch (MalformedURLException e) { - //PHPUnitPlugin.log(e); + // PHPUnitPlugin.log(e); e.printStackTrace(); } } @@ -43,46 +40,55 @@ public class PHPUnitImages { * Available cached Images in the Java plugin image registry. */ - public static final String IMG_SELECT_TEST_SUITE = - NAME_PREFIX + "tsuite.gif"; + public static final String IMG_SELECT_TEST_SUITE = NAME_PREFIX + + "tsuite.gif"; + public static final String IMG_RUN_TEST_SUITE = NAME_PREFIX + "start.gif"; + public static final String IMG_TEST_ERROR = NAME_PREFIX + "testerr.gif"; + public static final String IMG_TEST_FAILURE = NAME_PREFIX + "testfail.gif"; + public static final String IMG_TEST_PASS = NAME_PREFIX + "testok.gif"; - public static final String IMG_TEST_SUITE_ERROR = - NAME_PREFIX + "tsuiteerror.gif"; - public static final String IMG_TEST_SUITE_PASS = - NAME_PREFIX + "tsuiteok.gif"; - public static final String IMG_TEST_SUITE_FAILURE = - NAME_PREFIX + "tsuitefail.gif"; + + public static final String IMG_TEST_SUITE_ERROR = NAME_PREFIX + + "tsuiteerror.gif"; + + public static final String IMG_TEST_SUITE_PASS = NAME_PREFIX + + "tsuiteok.gif"; + + public static final String IMG_TEST_SUITE_FAILURE = NAME_PREFIX + + "tsuitefail.gif"; public static final String IMG_ERROR = NAME_PREFIX + "error.gif"; + public static final String IMG_FAILURE = NAME_PREFIX + "failure.gif"; - public static final ImageDescriptor DESC_SELECT_TEST_SUITE = - createManaged(IMG_SELECT_TEST_SUITE); - public static final ImageDescriptor DESC_RUN_TEST_SUITE = - createManaged(IMG_RUN_TEST_SUITE); - public static final ImageDescriptor DESC_TEST_ERROR = - createManaged(IMG_TEST_ERROR); - public static final ImageDescriptor DESC_TEST_FAILURE = - createManaged(IMG_TEST_FAILURE); - public static final ImageDescriptor DESC_TEST_PASS = - createManaged(IMG_TEST_PASS); - public static final ImageDescriptor DESC_TEST_SUITE_ERROR = - createManaged(IMG_TEST_SUITE_ERROR); - public static final ImageDescriptor DESC_TEST_SUITE_PASS = - createManaged(IMG_TEST_SUITE_PASS); - public static final ImageDescriptor DESC_TEST_SUITE_FAILURE = - createManaged(IMG_TEST_SUITE_FAILURE); + public static final ImageDescriptor DESC_SELECT_TEST_SUITE = createManaged(IMG_SELECT_TEST_SUITE); + + public static final ImageDescriptor DESC_RUN_TEST_SUITE = createManaged(IMG_RUN_TEST_SUITE); + + public static final ImageDescriptor DESC_TEST_ERROR = createManaged(IMG_TEST_ERROR); + + public static final ImageDescriptor DESC_TEST_FAILURE = createManaged(IMG_TEST_FAILURE); + + public static final ImageDescriptor DESC_TEST_PASS = createManaged(IMG_TEST_PASS); + + public static final ImageDescriptor DESC_TEST_SUITE_ERROR = createManaged(IMG_TEST_SUITE_ERROR); + + public static final ImageDescriptor DESC_TEST_SUITE_PASS = createManaged(IMG_TEST_SUITE_PASS); + + public static final ImageDescriptor DESC_TEST_SUITE_FAILURE = createManaged(IMG_TEST_SUITE_FAILURE); public static final ImageDescriptor DESC_ERROR = createManaged(IMG_ERROR); - public static final ImageDescriptor DESC_FAILURE = - createManaged(IMG_FAILURE); + + public static final ImageDescriptor DESC_FAILURE = createManaged(IMG_FAILURE); + /** * Returns the image managed under the given key in this registry. * - * @param key the image's key + * @param key + * the image's key * @return the image managed under the given key */ public static Image get(String key) { @@ -93,12 +99,11 @@ public class PHPUnitImages { return IMAGE_REGISTRY; } - protected static ImageDescriptor createManaged(String name) { try { - ImageDescriptor result = - ImageDescriptor.createFromURL( - makeIconFileURL(name.substring(NAME_PREFIX_LENGTH))); + ImageDescriptor result = ImageDescriptor + .createFromURL(makeIconFileURL(name + .substring(NAME_PREFIX_LENGTH))); IMAGE_REGISTRY.put(name, result); return result; } catch (MalformedURLException e) { @@ -107,7 +112,7 @@ public class PHPUnitImages { } protected static URL makeIconFileURL(String name) - throws MalformedURLException { + throws MalformedURLException { if (iconBaseURL == null) throw new MalformedURLException(); diff --git a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/PHPUnitPlugin.java b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/PHPUnitPlugin.java index e59bcab..006266b 100644 --- a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/PHPUnitPlugin.java +++ b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/PHPUnitPlugin.java @@ -16,31 +16,30 @@ import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.plugin.AbstractUIPlugin; - public class PHPUnitPlugin extends AbstractUIPlugin { - private static PHPUnitPlugin plugin; - public static final String PLUGIN_ID= "net.sourceforge.phpeclipse.phpunit"; //$NON-NLS-1$ + + public static final String PLUGIN_ID = "net.sourceforge.phpeclipse.phpunit"; //$NON-NLS-1$ /** * @param descriptor */ public PHPUnitPlugin(IPluginDescriptor descriptor) { - + super(descriptor); - - plugin= this; - - } - + plugin = this; + + } public static PHPUnitPlugin getDefault() { return plugin; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.ui.plugin.AbstractUIPlugin#createImageRegistry() */ protected ImageRegistry createImageRegistry() { @@ -48,7 +47,9 @@ public class PHPUnitPlugin extends AbstractUIPlugin { return super.createImageRegistry(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.ui.plugin.AbstractUIPlugin#getDialogSettings() */ public IDialogSettings getDialogSettings() { @@ -56,7 +57,9 @@ public class PHPUnitPlugin extends AbstractUIPlugin { return super.getDialogSettings(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.ui.plugin.AbstractUIPlugin#getImageRegistry() */ public ImageRegistry getImageRegistry() { @@ -64,7 +67,9 @@ public class PHPUnitPlugin extends AbstractUIPlugin { return super.getImageRegistry(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.ui.plugin.AbstractUIPlugin#getPreferenceStore() */ public IPreferenceStore getPreferenceStore() { @@ -72,7 +77,9 @@ public class PHPUnitPlugin extends AbstractUIPlugin { return super.getPreferenceStore(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.ui.plugin.AbstractUIPlugin#getWorkbench() */ public IWorkbench getWorkbench() { @@ -80,7 +87,9 @@ public class PHPUnitPlugin extends AbstractUIPlugin { return super.getWorkbench(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.core.runtime.Plugin#initializeDefaultPluginPreferences() */ protected void initializeDefaultPluginPreferences() { @@ -88,7 +97,9 @@ public class PHPUnitPlugin extends AbstractUIPlugin { super.initializeDefaultPluginPreferences(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.ui.plugin.AbstractUIPlugin#initializeDefaultPreferences(org.eclipse.jface.preference.IPreferenceStore) */ protected void initializeDefaultPreferences(IPreferenceStore store) { @@ -96,7 +107,9 @@ public class PHPUnitPlugin extends AbstractUIPlugin { super.initializeDefaultPreferences(store); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.ui.plugin.AbstractUIPlugin#initializeImageRegistry(org.eclipse.jface.resource.ImageRegistry) */ protected void initializeImageRegistry(ImageRegistry reg) { @@ -104,7 +117,9 @@ public class PHPUnitPlugin extends AbstractUIPlugin { super.initializeImageRegistry(reg); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.ui.plugin.AbstractUIPlugin#loadDialogSettings() */ protected void loadDialogSettings() { @@ -112,9 +127,9 @@ public class PHPUnitPlugin extends AbstractUIPlugin { super.loadDialogSettings(); } - - - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.ui.plugin.AbstractUIPlugin#refreshPluginActions() */ protected void refreshPluginActions() { @@ -122,7 +137,9 @@ public class PHPUnitPlugin extends AbstractUIPlugin { super.refreshPluginActions(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.ui.plugin.AbstractUIPlugin#saveDialogSettings() */ protected void saveDialogSettings() { @@ -130,9 +147,9 @@ public class PHPUnitPlugin extends AbstractUIPlugin { super.saveDialogSettings(); } - - - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.core.runtime.Plugin#shutdown() */ public void shutdown() throws CoreException { @@ -140,7 +157,9 @@ public class PHPUnitPlugin extends AbstractUIPlugin { super.shutdown(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.core.runtime.Plugin#startup() */ public void startup() throws CoreException { @@ -148,6 +167,4 @@ public class PHPUnitPlugin extends AbstractUIPlugin { super.startup(); } - - } diff --git a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/PHPUnitView.java b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/PHPUnitView.java index 46a1f82..8d4c5c2 100644 --- a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/PHPUnitView.java +++ b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/PHPUnitView.java @@ -8,8 +8,6 @@ package net.sourceforge.phpeclipse.phpunit; - - import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -31,115 +29,106 @@ import org.eclipse.swt.widgets.FileDialog; import org.eclipse.ui.IActionBars; import org.eclipse.ui.part.ViewPart; - - public class PHPUnitView extends ViewPart { - - - /* - * like J Unit - * a tree. - * The first level nodes are the test suites. - * children are nested test suites. - * leafs: test functions. - * hierarchy: package->testsuite1->testcase->test_function + * like J Unit a tree. The first level nodes are the test suites. children + * are nested test suites. leafs: test functions. hierarchy: + * package->testsuite1->testcase->test_function */ private static PHPUnitView view = null; private XMLReportHandler handler; - + private TestPool testPool; - //private Button startButton; + // private Button startButton; private ProgressInfoComposite progressInfoComposite; + private ResultsInfoComposite resultsInfoComposite; - //private SettingsInfoComposite settingsInfoComposite; //TODO: move somewhere else, launcher, wizard or preferences. + + // private SettingsInfoComposite settingsInfoComposite; //TODO: move + // somewhere else, launcher, wizard or preferences. private FileDialog dialog; + private String testSuiteToRun; + private Action selectTestAction; - private Action selectTestAction; private Action startTestAction; - public PHPUnitView() { - - if(view == null) + + if (view == null) view = this; - - } - + public static PHPUnitView getDefault() { - - - return view; + + return view; } public void createPartControl(Composite parent) { - //parent.setLayout(new FillLayout(SWT.VERTICAL)); + // parent.setLayout(new FillLayout(SWT.VERTICAL)); dialog = new FileDialog(parent.getShell()); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 1; - + // set title and layout - parent.setLayout(gridLayout); - + parent.setLayout(gridLayout); - //Launch ToolBar: + // Launch ToolBar: setActions(); - //Build the progress info Composites + // Build the progress info Composites progressInfoComposite = new ProgressInfoComposite(parent); - progressInfoComposite.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING)); - - - - //Build the result info composite + progressInfoComposite.setLayoutData(new GridData( + GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL + | GridData.VERTICAL_ALIGN_BEGINNING)); + + // Build the result info composite resultsInfoComposite = new ResultsInfoComposite(parent); - resultsInfoComposite.setLayoutData(new GridData(GridData.GRAB_VERTICAL | GridData.FILL_BOTH)); - - //build the settings composite - //buildSettingsComposite(parent); - - //settingsInfoComposite = new SettingsInfoComposite(parent, SWT.NONE); - - -// startButton = new Button(parent, SWT.CENTER); -// startButton.setText("Start Tests"); -// startButton.addMouseListener(new MouseListener() { -// -// public void mouseDoubleClick(MouseEvent arg0) { -// -// } -// -// public void mouseDown(MouseEvent arg0) { -// -// try { -// String testFile = settingsInfoComposite.getTestSuite(); -// startTests(testFile); -// } catch (IOException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } -// -// -// } -// -// public void mouseUp(MouseEvent arg0) { -// -// -// } -// -// }); // end add action listener. + resultsInfoComposite.setLayoutData(new GridData(GridData.GRAB_VERTICAL + | GridData.FILL_BOTH)); + + // build the settings composite + // buildSettingsComposite(parent); + + // settingsInfoComposite = new SettingsInfoComposite(parent, SWT.NONE); + + // startButton = new Button(parent, SWT.CENTER); + // startButton.setText("Start Tests"); + // startButton.addMouseListener(new MouseListener() { + // + // public void mouseDoubleClick(MouseEvent arg0) { + // + // } + // + // public void mouseDown(MouseEvent arg0) { + // + // try { + // String testFile = settingsInfoComposite.getTestSuite(); + // startTests(testFile); + // } catch (IOException e) { + // // TODO Auto-generated catch block + // e.printStackTrace(); + // } + // + // + // } + // + // public void mouseUp(MouseEvent arg0) { + // + // + // } + // + // }); // end add action listener. } @@ -147,85 +136,83 @@ public class PHPUnitView extends ViewPart { * @param parent */ private void buildSettingsComposite(Composite parent) { - - - //settingsInfoComposite = new Group(parent, SWT.NONE); - //settingsInfoComposite.setText("Settings"); -// settingsInfoComposite.setLayout(new GridLayout(2,false)); -// -// -// //the test suite to launch -// Label testSuiteLabel = new Label(settingsInfoComposite, SWT.NONE); -// testSuiteLabel.setText("Test suite to run:"); -// //testSuiteLabel.setLayoutData(new GridData()) -// Text testSuiteText = new Text(settingsInfoComposite, SWT.NONE); -// -// //the path to php -// Label phpPathLabel = new Label(settingsInfoComposite, SWT.NONE); -// phpPathLabel.setText("php Path:"); -// //testSuiteLabel.setLayoutData(new GridData()) -// Text phpPathText = new Text(settingsInfoComposite, SWT.NONE); + + // settingsInfoComposite = new Group(parent, SWT.NONE); + // settingsInfoComposite.setText("Settings"); + // settingsInfoComposite.setLayout(new GridLayout(2,false)); + // + // + // //the test suite to launch + // Label testSuiteLabel = new Label(settingsInfoComposite, SWT.NONE); + // testSuiteLabel.setText("Test suite to run:"); + // //testSuiteLabel.setLayoutData(new GridData()) + // Text testSuiteText = new Text(settingsInfoComposite, SWT.NONE); + // + // //the path to php + // Label phpPathLabel = new Label(settingsInfoComposite, SWT.NONE); + // phpPathLabel.setText("php Path:"); + // //testSuiteLabel.setLayoutData(new GridData()) + // Text phpPathText = new Text(settingsInfoComposite, SWT.NONE); } private void setActions() { - + final IActionBars actionBars = getViewSite().getActionBars(); IToolBarManager toolBarManager = actionBars.getToolBarManager(); selectTestAction = new Action() { - + public void run() { - + testSuiteToRun = dialog.open(); - startTestAction.setEnabled(true); + startTestAction.setEnabled(true); } }; - + selectTestAction.setText("Select Test Suite"); - selectTestAction.setToolTipText("Select Test Suite"); - selectTestAction.setImageDescriptor(PHPUnitImages.DESC_SELECT_TEST_SUITE); - - + selectTestAction.setToolTipText("Select Test Suite"); + selectTestAction + .setImageDescriptor(PHPUnitImages.DESC_SELECT_TEST_SUITE); + toolBarManager.add(selectTestAction); - - + startTestAction = new Action() { - + public void run() { - - + try { - if(testSuiteToRun == null || testSuiteToRun == "") + if (testSuiteToRun == null || testSuiteToRun == "") return; - + startTests(testSuiteToRun); - //setEnabled(false); - + // setEnabled(false); + } catch (IOException e) { - + e.printStackTrace(); } - + } - + }; - + startTestAction.setText("Start Test"); - startTestAction.setToolTipText("Start Test Suite. Select a Test Suite first."); + startTestAction + .setToolTipText("Start Test Suite. Select a Test Suite first."); startTestAction.setImageDescriptor(PHPUnitImages.DESC_RUN_TEST_SUITE); - startTestAction.setEnabled(false); - + startTestAction.setEnabled(false); + toolBarManager.add(startTestAction); } - - - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.ui.IWorkbenchPart#setFocus() */ public void setFocus() { - + } /** @@ -239,107 +226,103 @@ public class PHPUnitView extends ViewPart { // change icon color, increment pass counter, etc... testPool.getTest(testID).setVerdict(TestCase.PASS); - } - private void markTestFail(String testID) { - + testPool.getTest(testID).setVerdict(TestCase.FAIL); - + } + public void startTests(String testSuite) throws IOException { + // testSuite: the name of the file containing the suite we want to run. + // we will put that test suite inside a contained that uses our + // SocketResult. - public void startTests(String testSuite) throws IOException { - - //testSuite: the name of the file containing the suite we want to run. - // we will put that test suite inside a contained that uses our SocketResult. - - //reset from previous run + // reset from previous run reset(); - - + testSuite = testSuite.replaceAll("\\\\", "/"); - - System.out.println("new: " + testSuite); - - //where the plugin's temp files should go - String tempFolder = "C:\\tmp"; + + System.out.println("new: " + testSuite); + + // where the plugin's temp files should go + String tempFolder = "C:\\tmp"; String tempFileName = "temTest.php"; - - //create the file. + + // create the file. File testFile = new File(tempFolder + "/" + tempFileName); BufferedWriter out = new BufferedWriter(new FileWriter(testFile)); out.write("addTest(new TestSuite(\"" + testSuiteName + "\"));" + "\n"); - - + out.write("$suite->addTest(new TestSuite(\"" + testSuiteName + "\"));" + + "\n"); + out.write("$result = new SocketTestResult();" + "\n"); out.write("$suite->run($result);" + "\n"); out.write("$result->report(); " + "\n"); out.write("" + "\n"); out.write("" + "\n"); - + out.write("$output = ob_get_contents();" + "\n"); out.write("$fileHandle = fopen('c:/tmp/phpOut.txt');" + "\n"); out.write("fclose($fileHandle);" + "\n"); - - + out.write("ob_end();" + "\n"); out.write("?>" + "\n"); - + out.flush(); out.close(); - + listenForReports(); - + try { - Runtime.getRuntime().exec("php.exe " + tempFolder + "/" + tempFileName); + Runtime.getRuntime().exec( + "php.exe " + tempFolder + "/" + tempFileName); } catch (Exception e) { - + e.printStackTrace(); } - - //testFile.delete(); - + + // testFile.delete(); + } /** * */ private void reset() { - + handler = new XMLReportHandler(); testPool = new TestPool("Ali Baba"); - + progressInfoComposite.resetInfo(); resultsInfoComposite.resetInfo(); - + } /** @@ -350,41 +333,40 @@ public class PHPUnitView extends ViewPart { ConnectionListener conListener = new ConnectionListener(); conListener.start(this); - } //end of method + } // end of method /** * handle this report: test passed, faile, end of all. + * * @param report */ public void handleReport(String report) { - //delegate to the XML report handler. + // delegate to the XML report handler. handler.handle(report, this); } - /** * @param command * @param testCount * @param testID */ - public void handleCommand( - String command, String[] args) { - + public void handleCommand(String command, String[] args) { if (command.equals("startAll")) { - - //markTestingStarted(new Integer(testCount).intValue()); - - + + // markTestingStarted(new Integer(testCount).intValue()); + } else if (command.equals("testSuiteStarted")) { String testID = args[0]; String testCount = args[1]; - - //createNewTestSuite("TestSuiteName: " + testID, testID, new Integer(testCount).intValue()); - TestSuite suite = new TestSuite(null, "TestSuiteName: " + testID, testID, new Integer(testCount).intValue()); + + // createNewTestSuite("TestSuiteName: " + testID, testID, new + // Integer(testCount).intValue()); + TestSuite suite = new TestSuite(null, "TestSuiteName: " + testID, + testID, new Integer(testCount).intValue()); testPool.addTestSuite(suite); } else if (command.equals("testStarted")) { @@ -393,36 +375,31 @@ public class PHPUnitView extends ViewPart { String testCount = args[1]; String testName = args[2]; String parentTestSuiteName = args[3]; - - testPool.addTest(new TestCase(testID, testName, parentTestSuiteName)); + + testPool + .addTest(new TestCase(testID, testName, parentTestSuiteName)); } else if (command.equals("testFINISHED")) { - - } else if (command.equals("endAll")) { - } - update(); - - } /** * */ private void update() { - - //progressInfoComposite.updateInfo(numTests, testPool.getNumTestsRun(), numFailures, numErrors); + + // progressInfoComposite.updateInfo(numTests, testPool.getNumTestsRun(), + // numFailures, numErrors); progressInfoComposite.updateInfo(testPool); resultsInfoComposite.updateInfo(testPool); - - } + } /** * @param currentTestID @@ -443,12 +420,10 @@ public class PHPUnitView extends ViewPart { */ public void addTestException(String currentTestID, String exception) { - //TODO: decide how to show exceptions. don't show them for now. - //reportArea.append(" test " + currentTestID + " exception: " + exception + "\n"); + // TODO: decide how to show exceptions. don't show them for now. + // reportArea.append(" test " + currentTestID + " exception: " + + // exception + "\n"); } - - - -} //end of class +} // end of class diff --git a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/ProgressInfoComposite.java b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/ProgressInfoComposite.java index 92e19dd..f1a80a3 100644 --- a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/ProgressInfoComposite.java +++ b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/ProgressInfoComposite.java @@ -6,7 +6,6 @@ * *************************************************************************/ - package net.sourceforge.phpeclipse.phpunit; import net.sourceforge.phpeclipse.phpunit.testpool.TestPool; @@ -19,15 +18,14 @@ import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.ProgressBar; - public class ProgressInfoComposite extends Composite { - private Label labelRuns, labelRunsVal; // Runs: 12 + private Label labelErrors, labelErrorsImage, labelErrorsVal; + private Label labelFailures, labelFailuresImage, labelFailuresVal; - - + private ProgressBar progressBar; /** @@ -35,28 +33,25 @@ public class ProgressInfoComposite extends Composite { * @param arg1 */ public ProgressInfoComposite(Composite parent) { - + super(parent, SWT.NONE); - + GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 1; - + // set title and layout setLayout(gridLayout); - // set the progress bar progressBar = new ProgressBar(this, SWT.HORIZONTAL); - progressBar.setLayoutData( - new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL)); + progressBar.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL + | GridData.FILL_HORIZONTAL)); progressBar.setMinimum(0); - - Composite labelsComposite = - new Composite(this, SWT.NONE); - - labelsComposite.setLayoutData( - new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL)); + Composite labelsComposite = new Composite(this, SWT.NONE); + + labelsComposite.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL + | GridData.FILL_HORIZONTAL)); labelsComposite.setLayout(new FillLayout(SWT.HORIZONTAL)); @@ -72,43 +67,39 @@ public class ProgressInfoComposite extends Composite { labelFailuresVal = new Label(labelsComposite, SWT.NONE); labelFailuresVal.setText("0"); - labelErrorsImage = new Label(labelsComposite, SWT.NONE); labelErrorsImage.setImage(PHPUnitImages.DESC_ERROR.createImage()); labelErrors = new Label(labelsComposite, SWT.NONE); labelErrors.setText("Errors: "); labelErrorsVal = new Label(labelsComposite, SWT.NONE); - labelErrorsVal.setText("0"); + labelErrorsVal.setText("0"); } public void resetInfo() { - + labelErrorsVal.setText("0"); labelFailuresVal.setText("0"); labelRunsVal.setText("0 / 0"); - progressBar.setSelection(0); - + progressBar.setSelection(0); + } public void updateInfo(TestPool testPool) { - + int numTestsOverall = testPool.getNumTestsOverall(); int numTestsRun = testPool.getNumTestsRun(); - - //update progress bar + + // update progress bar progressBar.setMaximum(numTestsOverall); progressBar.setSelection(numTestsRun); - - - //update labels + + // update labels labelRunsVal.setText(numTestsRun + " / " + numTestsOverall); labelFailuresVal.setText("" + testPool.getNumFailures()); labelErrorsVal.setText("" + testPool.getNumErrors()); - - //TODO: change Failures label to red if some exist. - - - + + // TODO: change Failures label to red if some exist. + } } diff --git a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/ResultsInfoComposite.java b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/ResultsInfoComposite.java index efaa99b..ae43e74 100644 --- a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/ResultsInfoComposite.java +++ b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/ResultsInfoComposite.java @@ -6,7 +6,6 @@ * *************************************************************************/ - package net.sourceforge.phpeclipse.phpunit; import net.sourceforge.phpeclipse.phpunit.testpool.TestPool; @@ -17,13 +16,10 @@ import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; - public class ResultsInfoComposite extends Composite { - - private TreeViewer treeViewer; - + /** * @param arg0 * @param arg1 @@ -34,34 +30,34 @@ public class ResultsInfoComposite extends Composite { GridLayout layout = new GridLayout(); layout.numColumns = 1; - + setLayout(layout); - + treeViewer = new TreeViewer(this, SWT.BORDER | SWT.SHADOW_ETCHED_IN); - treeViewer.getControl().setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.FILL_BOTH | GridData.GRAB_VERTICAL)); - - + treeViewer.getControl().setLayoutData( + new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.FILL_BOTH + | GridData.GRAB_VERTICAL)); + TestPoolLabelProvider labelProvider = new TestPoolLabelProvider(); - TestPoolContentProvider contentProvider= new TestPoolContentProvider(); - + TestPoolContentProvider contentProvider = new TestPoolContentProvider(); + treeViewer.setContentProvider(contentProvider); treeViewer.setLabelProvider(labelProvider); - + } - public void resetInfo() { - + treeViewer.setInput(null); } - + public void updateInfo(TestPool testPool) { - + // take care of the TreeView and its content and label providers. - + treeViewer.setInput(testPool.getRoot()); - + } } diff --git a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/SettingsInfoComposite.java b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/SettingsInfoComposite.java index 53539a0..f815d87 100644 --- a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/SettingsInfoComposite.java +++ b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/SettingsInfoComposite.java @@ -6,7 +6,6 @@ * *************************************************************************/ - package net.sourceforge.phpeclipse.phpunit; import org.eclipse.swt.SWT; @@ -16,13 +15,12 @@ import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.FileDialog; - - public class SettingsInfoComposite extends Composite { FileDialog dialog; + Button button; - + String testSuitePath; /** @@ -30,14 +28,14 @@ public class SettingsInfoComposite extends Composite { * @param arg1 */ public SettingsInfoComposite(Composite parent, int style) { - + super(parent, style); - + dialog = new FileDialog(parent.getShell()); - + button = new Button(parent, SWT.NONE); button.setText("Browser for test..."); - + button.addMouseListener(new MouseListener() { public void mouseDoubleClick(MouseEvent arg0) { // TODO Auto-generated method stub @@ -45,7 +43,7 @@ public class SettingsInfoComposite extends Composite { } public void mouseDown(MouseEvent arg0) { - + testSuitePath = dialog.open(); System.out.println("file: " + testSuitePath); @@ -56,31 +54,22 @@ public class SettingsInfoComposite extends Composite { } }); - - - - - + } - - + public String getTestSuite() { - + return testSuitePath; } - /** * */ protected void showFileDialog() { - + testSuitePath = dialog.open(); System.out.println("file: " + testSuitePath); - - + } - - } diff --git a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/TestPoolContentProvider.java b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/TestPoolContentProvider.java index b099ef6..b93d3b2 100644 --- a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/TestPoolContentProvider.java +++ b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/TestPoolContentProvider.java @@ -6,7 +6,6 @@ * *************************************************************************/ - package net.sourceforge.phpeclipse.phpunit; import java.util.Vector; @@ -17,46 +16,47 @@ import net.sourceforge.phpeclipse.phpunit.testpool.TestSuite; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.Viewer; - - public class TestPoolContentProvider implements ITreeContentProvider { - - - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object) */ public Object[] getChildren(Object parentElement) { - if(parentElement instanceof TestSuite) { + if (parentElement instanceof TestSuite) { Vector allChildren = new Vector(); - allChildren.addAll(((TestSuite)parentElement).getTestCases()); - allChildren.addAll(((TestSuite)parentElement).getTestSuites()); - + allChildren.addAll(((TestSuite) parentElement).getTestCases()); + allChildren.addAll(((TestSuite) parentElement).getTestSuites()); + return allChildren.toArray(); - + } else { return new Object[0]; } - - + } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object) */ public Object getParent(Object element) { - - if(element instanceof TestSuite) - return ((TestSuite)element).getParent(); - else if (element instanceof TestCase) - return ((TestCase)element).getParentSuite(); + + if (element instanceof TestSuite) + return ((TestSuite) element).getParent(); + else if (element instanceof TestCase) + return ((TestCase) element).getParentSuite(); else return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object) */ public boolean hasChildren(Object element) { @@ -64,24 +64,31 @@ public class TestPoolContentProvider implements ITreeContentProvider { return getChildren(element).length > 0; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object) */ public Object[] getElements(Object inputElement) { - + return getChildren(inputElement); - + } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.viewers.IContentProvider#dispose() */ public void dispose() { - + } - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object) + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, + * java.lang.Object, java.lang.Object) */ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { // TODO Auto-generated method stub diff --git a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/TestPoolLabelProvider.java b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/TestPoolLabelProvider.java index 1aec92c..40614c3 100644 --- a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/TestPoolLabelProvider.java +++ b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/TestPoolLabelProvider.java @@ -6,7 +6,6 @@ * *************************************************************************/ - package net.sourceforge.phpeclipse.phpunit; import net.sourceforge.phpeclipse.phpunit.testpool.TestCase; @@ -15,69 +14,64 @@ import net.sourceforge.phpeclipse.phpunit.testpool.TestSuite; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.graphics.Image; - - + public class TestPoolLabelProvider extends LabelProvider { public String getText(Object element) { - + String text = ""; - - if(element instanceof TestSuite) - return ((TestSuite)element).getName(); - else if(element instanceof TestCase) { - - text = ((TestCase)element).getTestName(); - - //has the form: TESTSUITENAME_TESTNAME - - } - else + + if (element instanceof TestSuite) + return ((TestSuite) element).getName(); + else if (element instanceof TestCase) { + + text = ((TestCase) element).getTestName(); + + // has the form: TESTSUITENAME_TESTNAME + + } else text = "UNKNOWN ELEMENT TYPE"; - + return text; - + } public Image getImage(Object element) { - + Image image = null; ImageDescriptor descriptor = null; - - if(element instanceof TestSuite) { - - TestSuite suite = (TestSuite)element; - descriptor = PHPUnitImages.DESC_TEST_SUITE_PASS; + if (element instanceof TestSuite) { + + TestSuite suite = (TestSuite) element; + descriptor = PHPUnitImages.DESC_TEST_SUITE_PASS; - if(suite.hasError()) + if (suite.hasError()) descriptor = PHPUnitImages.DESC_TEST_SUITE_ERROR; - else if(suite.hasFailure()) + else if (suite.hasFailure()) descriptor = PHPUnitImages.DESC_TEST_SUITE_FAILURE; - else if(suite.isAllPass()) + else if (suite.isAllPass()) descriptor = PHPUnitImages.DESC_TEST_SUITE_PASS; - - - } else if(element instanceof TestCase) { - - TestCase test = (TestCase)element; - + + } else if (element instanceof TestCase) { + + TestCase test = (TestCase) element; + descriptor = PHPUnitImages.DESC_TEST_PASS; - - if(test.isError()) + + if (test.isError()) descriptor = PHPUnitImages.DESC_TEST_ERROR; - else if(test.isFailure()) + else if (test.isFailure()) descriptor = PHPUnitImages.DESC_TEST_FAILURE; - else if(test.isPass()) + else if (test.isPass()) descriptor = PHPUnitImages.DESC_TEST_PASS; - + } - + image = descriptor.createImage(); - - + return image; - + } } diff --git a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/preferences/PHPUnitPreferencePage.java b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/preferences/PHPUnitPreferencePage.java index c00c15b..ffd19f1 100644 --- a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/preferences/PHPUnitPreferencePage.java +++ b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/preferences/PHPUnitPreferencePage.java @@ -6,7 +6,6 @@ * *************************************************************************/ - package net.sourceforge.phpeclipse.phpunit.preferences; import net.sourceforge.phpeclipse.phpunit.PHPUnitPlugin; @@ -18,26 +17,20 @@ import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; /** - * This class represents a preference page that - * is contributed to the Preferences dialog. By - * subclassing FieldEditorPreferencePage, we - * can use the field support built into JFace that allows - * us to create a page that is small and knows how to - * save, restore and apply itself. + * This class represents a preference page that is contributed to the + * Preferences dialog. By subclassing FieldEditorPreferencePage, + * we can use the field support built into JFace that allows us to create a page + * that is small and knows how to save, restore and apply itself. *

- * This page is used to modify preferences only. They - * are stored in the preference store that belongs to - * the main plug-in class. That way, preferences can - * be accessed directly via the preference store. + * This page is used to modify preferences only. They are stored in the + * preference store that belongs to the main plug-in class. That way, + * preferences can be accessed directly via the preference store. */ -public class PHPUnitPreferencePage - extends FieldEditorPreferencePage - implements IWorkbenchPreferencePage { - - - public static final String PHPUNIT_PATH = "PHPUnitPathPreference"; +public class PHPUnitPreferencePage extends FieldEditorPreferencePage implements + IWorkbenchPreferencePage { + public static final String PHPUNIT_PATH = "PHPUnitPathPreference"; public PHPUnitPreferencePage() { super(GRID); @@ -45,31 +38,29 @@ public class PHPUnitPreferencePage setDescription("Please browse for the folder containing the PHPUnit files (among them: \"phpunit.php\" and \"socketTestResult.php\"). If you don't have it, please download the latest version from http://sourceforge.net/projects/phpunit/ first. "); initializeDefaults(); } -/** - * Sets the default values of the preferences. - */ + + /** + * Sets the default values of the preferences. + */ private void initializeDefaults() { IPreferenceStore store = getPreferenceStore(); } - -/** - * Creates the field editors. Field editors are abstractions of - * the common GUI blocks needed to manipulate various types - * of preferences. Each field editor knows how to save and - * restore itself. - */ - public void createFieldEditors() { + /** + * Creates the field editors. Field editors are abstractions of the common + * GUI blocks needed to manipulate various types of preferences. Each field + * editor knows how to save and restore itself. + */ - addField(new DirectoryFieldEditor(PHPUNIT_PATH, - "&PHPUnit Path:", getFieldEditorParent())); - + public void createFieldEditors() { + addField(new DirectoryFieldEditor(PHPUNIT_PATH, "&PHPUnit Path:", + getFieldEditorParent())); } - + public void init(IWorkbench workbench) { - + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/reporthandling/ConnectionListener.java b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/reporthandling/ConnectionListener.java index 7e5b74f..012a65d 100644 --- a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/reporthandling/ConnectionListener.java +++ b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/reporthandling/ConnectionListener.java @@ -6,8 +6,6 @@ * *************************************************************************/ - - package net.sourceforge.phpeclipse.phpunit.reporthandling; import java.net.ServerSocket; @@ -15,25 +13,25 @@ import java.net.Socket; import net.sourceforge.phpeclipse.phpunit.PHPUnitView; - public class ConnectionListener extends Thread { private ServerSocket sSocket = null; + private Socket serviceSocket = null; + private PHPUnitView view; - - + public void start(PHPUnitView view) { - + this.view = view; super.start(); } - + public void run() { try { - //reportArea.append("listening at port 12345"); + // reportArea.append("listening at port 12345"); sSocket = new ServerSocket(12345); @@ -53,7 +51,7 @@ public class ConnectionListener extends Thread { } // end of run() public static void main(String[] args) { - + (new ConnectionListener()).start(new PHPUnitView()); } diff --git a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/reporthandling/ReportListener.java b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/reporthandling/ReportListener.java index 18238a5..f0fb4a7 100644 --- a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/reporthandling/ReportListener.java +++ b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/reporthandling/ReportListener.java @@ -6,8 +6,6 @@ * *************************************************************************/ - - package net.sourceforge.phpeclipse.phpunit.reporthandling; import java.io.BufferedReader; @@ -20,8 +18,9 @@ import net.sourceforge.phpeclipse.phpunit.PHPUnitView; public class ReportListener extends Thread { Socket serviceSocket; + PHPUnitView view; - + public ReportListener(Socket serviceSocket, PHPUnitView view) { this.view = view; this.serviceSocket = serviceSocket; @@ -38,16 +37,16 @@ public class ReportListener extends Thread { BufferedReader in = new BufferedReader(reader); String report = null; int i = 0; - // keep listening until the - while ( (report = in.readLine()) != null && - (report != "end_all_tests") ) { + // keep listening until the + while ((report = in.readLine()) != null + && (report != "end_all_tests")) { - //System.out.println("received something..."); + // System.out.println("received something..."); view.handleReport(report); - //System.out.println(report); + // System.out.println(report); } - //reportArea.append("Finished!"); + // reportArea.append("Finished!"); System.out.println("Finished"); serviceSocket.close(); diff --git a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/reporthandling/XMLReportHandler.java b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/reporthandling/XMLReportHandler.java index 27ddbc3..4638cfe 100644 --- a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/reporthandling/XMLReportHandler.java +++ b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/reporthandling/XMLReportHandler.java @@ -6,7 +6,6 @@ * *************************************************************************/ - package net.sourceforge.phpeclipse.phpunit.reporthandling; import java.io.File; @@ -27,36 +26,42 @@ import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class XMLReportHandler extends DefaultHandler { - + private String currentVerdict; - private PHPUnitView view; + + private PHPUnitView view; + private String currentCommand; + private String currentTestCount; + private String currentTestID; + private String currentTestName; + private String currentTestParentTestSuiteName; - + private void doAsyncRunnable(Runnable runnable) { - + view.getSite().getShell().getDisplay().asyncExec(runnable); } - + public void handle(String report, PHPUnitView view) { - //TODO : how to parse directly a string? + // TODO : how to parse directly a string? // now doing it with a stream. this.view = view; SAXParser parser; - + System.out.println("handling: " + report); - + try { - + File file = new File("tmp3.xml"); FileOutputStream out = null; FileInputStream in = null; out = new FileOutputStream(file); - //OutputStreamWriter outS = new OutputStreamWriter(out, UTF8); + // OutputStreamWriter outS = new OutputStreamWriter(out, UTF8); report += "\n \r"; out.write(report.getBytes("UTF8")); out.close(); @@ -65,7 +70,7 @@ public class XMLReportHandler extends DefaultHandler { parser.parse(in, this); in.close(); file.delete(); - + } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); @@ -75,7 +80,7 @@ public class XMLReportHandler extends DefaultHandler { } catch (FactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); - } catch (FileNotFoundException e1) { + } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e) { @@ -83,102 +88,104 @@ public class XMLReportHandler extends DefaultHandler { e.printStackTrace(); } - - } - - /* (non-Javadoc) - * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String) + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#endElement(java.lang.String, + * java.lang.String, java.lang.String) */ public void endElement(String arg0, String arg1, String elementName) - throws SAXException { - - // send this current command to view + throws SAXException { + + // send this current command to view } - /* (non-Javadoc) - * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#startElement(java.lang.String, + * java.lang.String, java.lang.String, org.xml.sax.Attributes) */ - public void startElement( - String arg0, - String arg1, - String elementName, - Attributes attributes) - throws SAXException { - - System.out.println(arg0 + " - " + arg1 + " - " + elementName); - - - if(elementName.equals("report")) { - + public void startElement(String arg0, String arg1, String elementName, + Attributes attributes) throws SAXException { + + System.out.println(arg0 + " - " + arg1 + " - " + elementName); + + if (elementName.equals("report")) { + currentCommand = attributes.getValue("command"); currentTestCount = attributes.getValue("testCount"); currentTestID = attributes.getValue("testID"); currentTestName = attributes.getValue("testName"); - currentTestParentTestSuiteName = attributes.getValue("parentTestSuiteName"); - + currentTestParentTestSuiteName = attributes + .getValue("parentTestSuiteName"); + doAsyncRunnable(new Runnable() { - + public void run() { - - //view.handleCommand(currentCommand, currentTestCount, currentTestID, ); - view.handleCommand(currentCommand, new String[] {currentTestID, currentTestCount, currentTestName, currentTestParentTestSuiteName}); - - } + + // view.handleCommand(currentCommand, currentTestCount, + // currentTestID, ); + view.handleCommand(currentCommand, new String[] { + currentTestID, currentTestCount, currentTestName, + currentTestParentTestSuiteName }); + + } }); } else if (elementName.equals("verdict")) { - - currentVerdict = attributes.getValue("desc"); - //view.setTestVerdict(currentTestID, currentVerdict); - + + currentVerdict = attributes.getValue("desc"); + // view.setTestVerdict(currentTestID, currentVerdict); + doAsyncRunnable(new Runnable() { - + public void run() { - - view.setTestVerdict(currentTestID, currentVerdict); + + view.setTestVerdict(currentTestID, currentVerdict); } - - }); + + }); } else if (elementName.equals("exceptions")) { - - //do nothing - + + // do nothing + } else if (elementName.equals("exception")) { - + final String exception = attributes.getValue("desc"); - + doAsyncRunnable(new Runnable() { - + public void run() { - - view.addTestException(currentTestID, exception); + + view.addTestException(currentTestID, exception); } - - }); - + + }); + } - - + } public static void main(String[] args) { - + XMLReportHandler handler = new XMLReportHandler(); String xml = ""; xml = " "; - handler.handle(xml, null); - + handler.handle(xml, null); + xml = " "; handler.handle(xml, null); - + xml = " "; handler.handle(xml, null); - + xml = " "; - handler.handle(xml, null); + handler.handle(xml, null); } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/testpool/TestCase.java b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/testpool/TestCase.java index 5f3a8ed..3456c37 100644 --- a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/testpool/TestCase.java +++ b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/testpool/TestCase.java @@ -6,40 +6,37 @@ * *************************************************************************/ - package net.sourceforge.phpeclipse.phpunit.testpool; - - public class TestCase { public static final String PASS = "PASS"; + public static final String FAIL = "FAIL"; - public static final String ERROR = "ERROR"; + public static final String ERROR = "ERROR"; private TestSuite parentSuite; + private String testName; + private String testID; + private String verdict; + private String parentTestSuiteName; - - - /** * @param testName * @param testID */ public TestCase(String testID, String testName, String parentTestSuiteName) { - + this.testName = testName; this.testID = testID; this.parentTestSuiteName = parentTestSuiteName; } - - /** * @return */ @@ -66,10 +63,8 @@ public class TestCase { */ public void setTestID(String string) { testID = string; - - } - + } /** * @param string @@ -83,12 +78,12 @@ public class TestCase { */ public void setVerdict(String string) { verdict = string; - - if(isFailure()) + + if (isFailure()) parentSuite.setHasFailure(); - if(isError()) + if (isError()) parentSuite.setHasError(); - + } /** @@ -97,14 +92,14 @@ public class TestCase { public void setParentSuite(TestSuite suite) { this.parentSuite = suite; suite.setName(parentTestSuiteName); - + } /** * @return */ public Object getParentSuite() { - + return parentSuite; } @@ -112,7 +107,7 @@ public class TestCase { * @return */ public boolean isError() { - + return getVerdict().equals(TestCase.ERROR); } @@ -120,16 +115,16 @@ public class TestCase { * @return */ public boolean isFailure() { - + return getVerdict().equals(TestCase.FAIL); - + } /** * @return */ public boolean isPass() { - + return getVerdict().equals(TestCase.PASS); } diff --git a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/testpool/TestPool.java b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/testpool/TestPool.java index 8e6a7fb..ddd0422 100644 --- a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/testpool/TestPool.java +++ b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/testpool/TestPool.java @@ -6,79 +6,75 @@ * *************************************************************************/ - package net.sourceforge.phpeclipse.phpunit.testpool; import java.util.HashMap; - public class TestPool { - //private TestSuite currentParentTestSuite; + // private TestSuite currentParentTestSuite; private HashMap tests; + private TestSuite root; + private TestSuite currentTestSuite; - - + /** * */ public TestPool(String rootTitle) { - + tests = new HashMap(); - root = null; + root = null; currentTestSuite = root; - + } /** * @param test */ public void addTest(TestCase test) { - + tests.put(test.getTestID(), test); - + currentTestSuite.addTestCase(test); - - - //if we run all tests. then this is the end of this test suite. - if( currentTestSuite != root && currentTestSuite.isFinished()) { - + + // if we run all tests. then this is the end of this test suite. + if (currentTestSuite != root && currentTestSuite.isFinished()) { + currentTestSuite = currentTestSuite.getParent(); - } - - } + } + + } /** * @param suite * @param numTestsRunSinceStartOfTestSuite */ public void addTestSuite(TestSuite suite) { - - - if(root == null) { - root = suite; - } - else { - - //add as sibling + + if (root == null) { + root = suite; + } else { + + // add as sibling currentTestSuite.addTestSuite(suite); suite.setParent(currentTestSuite); - } - - currentTestSuite = suite; + } + + currentTestSuite = suite; } /** * @return */ public TestSuite getRoot() { - + return root; } - + /** * @param r */ @@ -86,87 +82,81 @@ public class TestPool { this.root = r; } - - /** * @param testID * @return */ public TestCase getTest(String testID) { - + return (TestCase) tests.get(testID); } public String toString() { - + String string = ""; - + TestSuite node = root; - + string = root.toString(); - return string; - - } + return string; + } public int getNumTestsOverall() { - + int total = root.getNumTestCasesExpected(); System.out.println("total: " + total); return total; - + } - + public int getNumTestsRun() { - + return tests.size(); - - + } - + public int getNumFailures() { - + int total = 0; - -// Iterator i = tests.keySet().iterator(); -// String key = ""; -// while (i.hasNext()) { -// -// -// key = (String) i.next(); -// TestCase element = (TestCase) tests.get(key); -// -// -// if(element.isFailure()) -// total++; -// -// } - + + // Iterator i = tests.keySet().iterator(); + // String key = ""; + // while (i.hasNext()) { + // + // + // key = (String) i.next(); + // TestCase element = (TestCase) tests.get(key); + // + // + // if(element.isFailure()) + // total++; + // + // } + return total; } - + public int getNumErrors() { int total = 0; - -// Iterator i = tests.keySet().iterator(); -// String key = ""; -// while (i.hasNext()) { -// -// -// key = (String) i.next(); -// TestCase element = (TestCase) tests.get(key); -// -// if(element.isError()) -// total++; -// -// } - + + // Iterator i = tests.keySet().iterator(); + // String key = ""; + // while (i.hasNext()) { + // + // + // key = (String) i.next(); + // TestCase element = (TestCase) tests.get(key); + // + // if(element.isError()) + // total++; + // + // } + return total; - + } - - } diff --git a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/testpool/TestSuite.java b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/testpool/TestSuite.java index 90cea9e..301b9fd 100644 --- a/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/testpool/TestSuite.java +++ b/net.sourceforge.phpeclipse.phpunit/src/net/sourceforge/phpeclipse/phpunit/testpool/TestSuite.java @@ -6,28 +6,31 @@ * *************************************************************************/ - package net.sourceforge.phpeclipse.phpunit.testpool; import java.util.Vector; - public class TestSuite { - - private boolean hasFailure; + private boolean isAllPass; + private boolean hasError; + private Vector testCases; // current or actual. + private Vector testSuites; // current or actual. + private String name; + private String id; - private int numTestCasesExpected; //expected - private int numTestCasesRunSoFar; - TestSuite parent; + private int numTestCasesExpected; // expected + private int numTestCasesRunSoFar; + + TestSuite parent; /** * @param name @@ -35,52 +38,52 @@ public class TestSuite { * @param testCount */ public TestSuite(TestSuite parent, String name, String testID, int testCount) { - + this.parent = parent; this.id = testID; this.name = name; this.numTestCasesExpected = testCount; - + testCases = new Vector(); testSuites = new Vector(); - + hasError = false; isAllPass = true; hasFailure = false; } - + public void addTestCase(TestCase test) { testCases.addElement(test); test.setParentSuite(this); numTestCasesRunSoFar++; } - - public void removeTestCase(TestCase test) {} - + + public void removeTestCase(TestCase test) { + } + public boolean contains(TestCase test) { - + return false; - + } - + public String toString() { - + String string = ""; - - //print test cases. + + // print test cases. TestCase tc = null; - for(int i = 0; i < testCases.size(); i++) { - + for (int i = 0; i < testCases.size(); i++) { + tc = (TestCase) testCases.elementAt(i); string += " - " + tc.getTestID() + ", " + tc.getTestName() + "\n"; - - + } - - for(int i = 0; i < testSuites.size(); i++) + + for (int i = 0; i < testSuites.size(); i++) string += ((TestSuite) testSuites.elementAt(i)).toString(); - - //print its own test suites. + + // print its own test suites. return string; } @@ -131,16 +134,16 @@ public class TestSuite { */ public void addTestSuite(TestSuite suite) { testSuites.addElement(suite); - + } /** * @return */ public boolean isFinished() { - + return numTestCasesRunSoFar >= numTestCasesExpected; - + } /** @@ -161,7 +164,7 @@ public class TestSuite { * @return */ public int getNumTestCases() { - + return testCases.size(); } @@ -198,46 +201,44 @@ public class TestSuite { */ public boolean hasError() { - return hasError; + return hasError; } - + public void setHasError() { - - if(hasError) + + if (hasError) return; - + hasError = true; - - if(parent != null) + + if (parent != null) parent.setHasError(); } - /** * @return */ public boolean hasFailure() { - return hasFailure; + return hasFailure; } - + public void setHasFailure() { - - if(hasFailure) + + if (hasFailure) return; - + hasFailure = true; - - if(parent != null) + + if (parent != null) parent.setHasFailure(); } - public boolean isAllPass() { - + return !hasError() && !hasFailure(); - - } + + } } diff --git a/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/SmartyUIMessages.java b/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/SmartyUIMessages.java index 3549dab..371817b 100644 --- a/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/SmartyUIMessages.java +++ b/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/SmartyUIMessages.java @@ -8,7 +8,7 @@ * Contributors: * Christopher Lenz - initial API and implementation * - * $Id: SmartyUIMessages.java,v 1.1 2004-09-03 17:31:19 jsurfer Exp $ + * $Id: SmartyUIMessages.java,v 1.2 2006-10-21 23:19:32 pombredanne Exp $ */ package net.sourceforge.phpdt.smarty.ui.internal; @@ -27,16 +27,15 @@ public final class SmartyUIMessages { /** * Qualified name of the resource bundle containing the localized messages. */ - private static final String RESOURCE_BUNDLE = - "net.sourceforge.phpdt.smarty.ui.internal.SmartyUIMessages"; //$NON-NLS-1$ + private static final String RESOURCE_BUNDLE = "net.sourceforge.phpdt.smarty.ui.internal.SmartyUIMessages"; //$NON-NLS-1$ // Class Variables --------------------------------------------------------- /** * The resource bundle. */ - private static ResourceBundle resourceBundle = - ResourceBundle.getBundle(RESOURCE_BUNDLE); + private static ResourceBundle resourceBundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); // Constructors ------------------------------------------------------------ @@ -61,7 +60,8 @@ public final class SmartyUIMessages { /** * Returns the message identified by the specified key. * - * @param key the message key + * @param key + * the message key * @return the localized message, or the key enclosed by exclamation marks * if no message was found for the key */ @@ -77,10 +77,12 @@ public final class SmartyUIMessages { * Returns the message identified by the specified key, replacing a single * parameter with the provided value. * - * @param key the message key - * @param arg the parameter value - * @return the formatted string, or the key enclosed by exclamation marks - * if no message was found for the key + * @param key + * the message key + * @param arg + * the parameter value + * @return the formatted string, or the key enclosed by exclamation marks if + * no message was found for the key */ public static String getString(String key, String arg) { return getString(key, new String[] { arg }); @@ -90,13 +92,15 @@ public final class SmartyUIMessages { * Returns the message identified by the specified key, replacing all * parameters with the provided values. * - * @param key the message key - * @param args the parameter values - * @return the formatted string, or the key enclosed by exclamation marks - * if no message was found for the key + * @param key + * the message key + * @param args + * the parameter values + * @return the formatted string, or the key enclosed by exclamation marks if + * no message was found for the key */ public static String getString(String key, String[] args) { - return MessageFormat.format(getString(key), args); + return MessageFormat.format(getString(key), args); } } diff --git a/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/editor/SmartyDocumentProvider.java b/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/editor/SmartyDocumentProvider.java index c6a5b6e..be57b5b 100644 --- a/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/editor/SmartyDocumentProvider.java +++ b/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/editor/SmartyDocumentProvider.java @@ -8,14 +8,13 @@ * Contributors: * Christopher Lenz - initial API and implementation * - * $Id: SmartyDocumentProvider.java,v 1.1 2004-09-03 17:31:18 jsurfer Exp $ + * $Id: SmartyDocumentProvider.java,v 1.2 2006-10-21 23:19:32 pombredanne Exp $ */ package net.sourceforge.phpdt.smarty.ui.internal.editor; import net.sourceforge.phpeclipse.xml.ui.internal.editor.XMLDocumentProvider; - /** * Document provider for HTML files. */ diff --git a/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/editor/SmartyDocumentSetupParticipant.java b/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/editor/SmartyDocumentSetupParticipant.java index b8fac8b..a92b365 100644 --- a/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/editor/SmartyDocumentSetupParticipant.java +++ b/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/editor/SmartyDocumentSetupParticipant.java @@ -8,14 +8,13 @@ * Contributors: * Christopher Lenz - initial implementation * - * $Id: SmartyDocumentSetupParticipant.java,v 1.1 2004-09-03 17:31:18 jsurfer Exp $ + * $Id: SmartyDocumentSetupParticipant.java,v 1.2 2006-10-21 23:19:32 pombredanne Exp $ */ package net.sourceforge.phpdt.smarty.ui.internal.editor; import net.sourceforge.phpeclipse.xml.ui.internal.editor.XMLDocumentSetupParticipant; - /** * Document setup participant that sets up the HTML specific partitioning. */ diff --git a/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/editor/SmartyEditor.java b/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/editor/SmartyEditor.java index 77aa1b4..93639a6 100644 --- a/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/editor/SmartyEditor.java +++ b/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/editor/SmartyEditor.java @@ -8,7 +8,7 @@ * Contributors: * Christopher Lenz - initial implementation * - * $Id: SmartyEditor.java,v 1.1 2004-09-03 17:31:18 jsurfer Exp $ + * $Id: SmartyEditor.java,v 1.2 2006-10-21 23:19:32 pombredanne Exp $ */ package net.sourceforge.phpdt.smarty.ui.internal.editor; @@ -24,33 +24,31 @@ import org.eclipse.jface.action.IAction; import org.eclipse.ui.texteditor.ContentAssistAction; import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; - /** * HTML editor implementation. */ public class SmartyEditor extends XMLEditor { - public SmartyEditor() { - super(ShowExternalPreviewAction.SMARTY_TYPE); - } + public SmartyEditor() { + super(ShowExternalPreviewAction.SMARTY_TYPE); + } + // Instance Variables ------------------------------------------------------ - - /** The associated preview page. */ -// private HTMLPreviewPage previewPage; + /** The associated preview page. */ + // private HTMLPreviewPage previewPage; // XMLEditor Implementation ------------------------------------------------ - - /* + /* * @see org.eclipse.core.runtime.IAdaptable#getAdapter(Class) */ public Object getAdapter(Class adapter) { -// if (adapter == IBrowserPreviewPage.class) { -// if (previewPage == null) { -// previewPage = createPreviewPage(); -// } -// return previewPage; -// } + // if (adapter == IBrowserPreviewPage.class) { + // if (previewPage == null) { + // previewPage = createPreviewPage(); + // } + // return previewPage; + // } return super.getAdapter(adapter); } @@ -59,36 +57,37 @@ public class SmartyEditor extends XMLEditor { /** * Creates the HTML preview page. */ -// private HTMLPreviewPage createPreviewPage() { -// IEditorInput input = getEditorInput(); -// if (input instanceof IFileEditorInput) { -// IFile file = ((IFileEditorInput) input).getFile(); -// try { -// URL location = file.getLocation().toFile().toURL(); -// return new HTMLPreviewPage(location); -// } catch (MalformedURLException e) { } -// } -// return null; -// } + // private HTMLPreviewPage createPreviewPage() { + // IEditorInput input = getEditorInput(); + // if (input instanceof IFileEditorInput) { + // IFile file = ((IFileEditorInput) input).getFile(); + // try { + // URL location = file.getLocation().toFile().toURL(); + // return new HTMLPreviewPage(location); + // } catch (MalformedURLException e) { } + // } + // return null; + // } protected void createActions() { super.createActions(); - IAction action = new ContentAssistAction(SmartyEditorMessages.getResourceBundle(), - "ContentAssistProposal.", this); //$NON-NLS-1$ - action - .setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); - setAction("ContentAssistProposal", action); //$NON-NLS-1$ - markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$ - -// IAction action= new TextOperationAction( -// TemplateMessages.getResourceBundle(), -// "Editor." + TEMPLATE_PROPOSALS + ".", //$NON-NLS-1$ //$NON-NLS-2$ -// this, -// ISourceViewer.CONTENTASSIST_PROPOSALS); -// action.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); -// setAction(TEMPLATE_PROPOSALS, action); -// markAsStateDependentAction(TEMPLATE_PROPOSALS, true); + IAction action = new ContentAssistAction(SmartyEditorMessages + .getResourceBundle(), "ContentAssistProposal.", this); //$NON-NLS-1$ + action + .setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); + setAction("ContentAssistProposal", action); //$NON-NLS-1$ + markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$ + + // IAction action= new TextOperationAction( + // TemplateMessages.getResourceBundle(), + // "Editor." + TEMPLATE_PROPOSALS + ".", //$NON-NLS-1$ //$NON-NLS-2$ + // this, + // ISourceViewer.CONTENTASSIST_PROPOSALS); + // action.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); + // setAction(TEMPLATE_PROPOSALS, action); + // markAsStateDependentAction(TEMPLATE_PROPOSALS, true); } + /* * @see org.eclipse.ui.editors.text.TextEditor#initializeEditor() */ diff --git a/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/editor/SmartyEditorActionContributor.java b/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/editor/SmartyEditorActionContributor.java index 4196b46..9dd8c26 100644 --- a/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/editor/SmartyEditorActionContributor.java +++ b/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/editor/SmartyEditorActionContributor.java @@ -22,7 +22,8 @@ import org.eclipse.ui.texteditor.ITextEditor; /** * Common base class for action contributors for Java editors. */ -public class SmartyEditorActionContributor extends BasicTextEditorActionContributor { +public class SmartyEditorActionContributor extends + BasicTextEditorActionContributor { /* * (non-Javadoc) @@ -43,11 +44,13 @@ public class SmartyEditorActionContributor extends BasicTextEditorActionContribu file = ((IFileEditorInput) editorInput).getFile(); } - ShowExternalPreviewAction fShowExternalPreviewAction = ShowExternalPreviewAction.getInstance(); + ShowExternalPreviewAction fShowExternalPreviewAction = ShowExternalPreviewAction + .getInstance(); fShowExternalPreviewAction.setEditor(textEditor); fShowExternalPreviewAction.update(); if (fShowExternalPreviewAction != null) - fShowExternalPreviewAction.doRun(ShowExternalPreviewAction.SMARTY_TYPE); + fShowExternalPreviewAction + .doRun(ShowExternalPreviewAction.SMARTY_TYPE); } } } diff --git a/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/editor/SmartyEditorMessages.java b/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/editor/SmartyEditorMessages.java index 395dbfa..405d06d 100644 --- a/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/editor/SmartyEditorMessages.java +++ b/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/editor/SmartyEditorMessages.java @@ -1,14 +1,14 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ package net.sourceforge.phpdt.smarty.ui.internal.editor; import java.text.MessageFormat; @@ -17,9 +17,10 @@ import java.util.ResourceBundle; public class SmartyEditorMessages { - private static final String RESOURCE_BUNDLE= "net.sourceforge.phpdt.smarty.ui.internal.editor.SmartyEditorMessages";//$NON-NLS-1$ + private static final String RESOURCE_BUNDLE = "net.sourceforge.phpdt.smarty.ui.internal.editor.SmartyEditorMessages";//$NON-NLS-1$ - private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); + private static ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); private SmartyEditorMessages() { } @@ -31,14 +32,14 @@ public class SmartyEditorMessages { return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$ } } - + /** * Gets a string from the resource bundle and formats it with arguments - */ + */ public static String getFormattedString(String key, Object[] args) { return MessageFormat.format(getString(key), args); } - + public static ResourceBundle getResourceBundle() { return fgResourceBundle; } diff --git a/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/text/SmartyCompletionProcessor.java b/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/text/SmartyCompletionProcessor.java index d20fead..1aef925 100644 --- a/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/text/SmartyCompletionProcessor.java +++ b/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/text/SmartyCompletionProcessor.java @@ -18,18 +18,18 @@ import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.templates.TemplateContextType; - /** * A completion processor for XML templates. */ public class SmartyCompletionProcessor extends BasicCompletionProcessor { - + /** - * Return the XML context type that is supported by this plugin. + * Return the XML context type that is supported by this plugin. */ - protected TemplateContextType getContextType(ITextViewer viewer, IRegion region) { - return WebUI.getDefault().getContextTypeRegistry().getContextType(HTMLContextType.HTML_CONTEXT_TYPE); + protected TemplateContextType getContextType(ITextViewer viewer, + IRegion region) { + return WebUI.getDefault().getContextTypeRegistry().getContextType( + HTMLContextType.HTML_CONTEXT_TYPE); } - } diff --git a/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/text/SmartyConfiguration.java b/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/text/SmartyConfiguration.java index cc272c1..f64ad38 100644 --- a/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/text/SmartyConfiguration.java +++ b/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/text/SmartyConfiguration.java @@ -23,96 +23,111 @@ import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.ui.texteditor.ITextEditor; public class SmartyConfiguration extends XMLConfiguration { - private SmartyTagScanner smartyTagScanner; - public SmartyConfiguration(XMLTextTools tools) { - this(tools, null); - } - - public SmartyConfiguration(XMLTextTools tools, ITextEditor editor) { - super(tools, editor); - Map tokens = tools.getTokens(); - smartyTagScanner = new SmartyTagScanner(tokens); - } - - public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { - ContentAssistant assistant = new ContentAssistant(); - assistant.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); - - IContentAssistProcessor processor = new SmartyCompletionProcessor(); - assistant.setContentAssistProcessor(processor, IDocument.DEFAULT_CONTENT_TYPE); - assistant.setContentAssistProcessor(processor, XMLPartitionScanner.XML_TAG); - assistant.setContentAssistProcessor(processor, XMLPartitionScanner.XML_PI); - assistant.setContentAssistProcessor(processor, XMLPartitionScanner.XML_COMMENT); - assistant.setContentAssistProcessor(processor, XMLPartitionScanner.XML_DECL); - assistant.setContentAssistProcessor(processor, XMLPartitionScanner.XML_TAG); - assistant.setContentAssistProcessor(processor, XMLPartitionScanner.XML_ATTRIBUTE); - assistant.setContentAssistProcessor(processor, XMLPartitionScanner.XML_CDATA); - - assistant.setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE); - assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer)); - - return assistant; - } + private SmartyTagScanner smartyTagScanner; + + public SmartyConfiguration(XMLTextTools tools) { + this(tools, null); + } + + public SmartyConfiguration(XMLTextTools tools, ITextEditor editor) { + super(tools, editor); + Map tokens = tools.getTokens(); + smartyTagScanner = new SmartyTagScanner(tokens); + } + + public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { + ContentAssistant assistant = new ContentAssistant(); + assistant + .setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); + + IContentAssistProcessor processor = new SmartyCompletionProcessor(); + assistant.setContentAssistProcessor(processor, + IDocument.DEFAULT_CONTENT_TYPE); + assistant.setContentAssistProcessor(processor, + XMLPartitionScanner.XML_TAG); + assistant.setContentAssistProcessor(processor, + XMLPartitionScanner.XML_PI); + assistant.setContentAssistProcessor(processor, + XMLPartitionScanner.XML_COMMENT); + assistant.setContentAssistProcessor(processor, + XMLPartitionScanner.XML_DECL); + assistant.setContentAssistProcessor(processor, + XMLPartitionScanner.XML_TAG); + assistant.setContentAssistProcessor(processor, + XMLPartitionScanner.XML_ATTRIBUTE); + assistant.setContentAssistProcessor(processor, + XMLPartitionScanner.XML_CDATA); + + assistant + .setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE); + assistant + .setInformationControlCreator(getInformationControlCreator(sourceViewer)); + + return assistant; + } + /** * Returns a scanner which is configured to scan XML text. * - * @return an XML text scanner + * @return an XML text scanner */ public SmartyTagScanner getSmartyScanner() { return smartyTagScanner; } - /* - * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getPresentationReconciler(ISourceViewer) - */ - public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) { - PresentationReconciler reconciler = new PresentationReconciler(); - DefaultDamagerRepairer dr; + /* + * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getPresentationReconciler(ISourceViewer) + */ + public IPresentationReconciler getPresentationReconciler( + ISourceViewer sourceViewer) { + PresentationReconciler reconciler = new PresentationReconciler(); - dr = new DefaultDamagerRepairer(getSmartyScanner()); - reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE); - reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE); + DefaultDamagerRepairer dr; - dr = new DefaultDamagerRepairer(xmlTextTools.getDTDTextScanner()); - reconciler.setDamager(dr, XMLPartitionScanner.DTD_INTERNAL); - reconciler.setRepairer(dr, XMLPartitionScanner.DTD_INTERNAL); + dr = new DefaultDamagerRepairer(getSmartyScanner()); + reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE); + reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE); - dr = new DefaultDamagerRepairer(xmlTextTools.getXMLPIScanner()); + dr = new DefaultDamagerRepairer(xmlTextTools.getDTDTextScanner()); + reconciler.setDamager(dr, XMLPartitionScanner.DTD_INTERNAL); + reconciler.setRepairer(dr, XMLPartitionScanner.DTD_INTERNAL); - reconciler.setDamager(dr, XMLPartitionScanner.XML_PI); - reconciler.setRepairer(dr, XMLPartitionScanner.XML_PI); - reconciler.setDamager(dr, XMLPartitionScanner.DTD_INTERNAL_PI); - reconciler.setRepairer(dr, XMLPartitionScanner.DTD_INTERNAL_PI); + dr = new DefaultDamagerRepairer(xmlTextTools.getXMLPIScanner()); - dr = new DefaultDamagerRepairer(xmlTextTools.getXMLCommentScanner()); + reconciler.setDamager(dr, XMLPartitionScanner.XML_PI); + reconciler.setRepairer(dr, XMLPartitionScanner.XML_PI); + reconciler.setDamager(dr, XMLPartitionScanner.DTD_INTERNAL_PI); + reconciler.setRepairer(dr, XMLPartitionScanner.DTD_INTERNAL_PI); - reconciler.setDamager(dr, XMLPartitionScanner.XML_COMMENT); - reconciler.setRepairer(dr, XMLPartitionScanner.XML_COMMENT); - reconciler.setDamager(dr, XMLPartitionScanner.DTD_INTERNAL_COMMENT); - reconciler.setRepairer(dr, XMLPartitionScanner.DTD_INTERNAL_COMMENT); + dr = new DefaultDamagerRepairer(xmlTextTools.getXMLCommentScanner()); - dr = new DefaultDamagerRepairer(xmlTextTools.getXMLDeclScanner()); + reconciler.setDamager(dr, XMLPartitionScanner.XML_COMMENT); + reconciler.setRepairer(dr, XMLPartitionScanner.XML_COMMENT); + reconciler.setDamager(dr, XMLPartitionScanner.DTD_INTERNAL_COMMENT); + reconciler.setRepairer(dr, XMLPartitionScanner.DTD_INTERNAL_COMMENT); - reconciler.setDamager(dr, XMLPartitionScanner.XML_DECL); - reconciler.setRepairer(dr, XMLPartitionScanner.XML_DECL); - reconciler.setDamager(dr, XMLPartitionScanner.DTD_INTERNAL_DECL); - reconciler.setRepairer(dr, XMLPartitionScanner.DTD_INTERNAL_DECL); + dr = new DefaultDamagerRepairer(xmlTextTools.getXMLDeclScanner()); - dr = new DefaultDamagerRepairer(xmlTextTools.getXMLTagScanner()); + reconciler.setDamager(dr, XMLPartitionScanner.XML_DECL); + reconciler.setRepairer(dr, XMLPartitionScanner.XML_DECL); + reconciler.setDamager(dr, XMLPartitionScanner.DTD_INTERNAL_DECL); + reconciler.setRepairer(dr, XMLPartitionScanner.DTD_INTERNAL_DECL); - reconciler.setDamager(dr, XMLPartitionScanner.XML_TAG); - reconciler.setRepairer(dr, XMLPartitionScanner.XML_TAG); + dr = new DefaultDamagerRepairer(xmlTextTools.getXMLTagScanner()); - dr = new DefaultDamagerRepairer(xmlTextTools.getXMLAttributeScanner()); + reconciler.setDamager(dr, XMLPartitionScanner.XML_TAG); + reconciler.setRepairer(dr, XMLPartitionScanner.XML_TAG); - reconciler.setDamager(dr, XMLPartitionScanner.XML_ATTRIBUTE); - reconciler.setRepairer(dr, XMLPartitionScanner.XML_ATTRIBUTE); + dr = new DefaultDamagerRepairer(xmlTextTools.getXMLAttributeScanner()); - dr = new DefaultDamagerRepairer(xmlTextTools.getXMLCDATAScanner()); + reconciler.setDamager(dr, XMLPartitionScanner.XML_ATTRIBUTE); + reconciler.setRepairer(dr, XMLPartitionScanner.XML_ATTRIBUTE); - reconciler.setDamager(dr, XMLPartitionScanner.XML_CDATA); - reconciler.setRepairer(dr, XMLPartitionScanner.XML_CDATA); + dr = new DefaultDamagerRepairer(xmlTextTools.getXMLCDATAScanner()); - return reconciler; - } + reconciler.setDamager(dr, XMLPartitionScanner.XML_CDATA); + reconciler.setRepairer(dr, XMLPartitionScanner.XML_CDATA); + + return reconciler; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/text/SmartyTagRule.java b/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/text/SmartyTagRule.java index 1e22864..0312be1 100644 --- a/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/text/SmartyTagRule.java +++ b/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/text/SmartyTagRule.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: SmartyTagRule.java,v 1.2 2004-12-29 21:30:33 axelcl Exp $ + * $Id: SmartyTagRule.java,v 1.3 2006-10-21 23:19:32 pombredanne Exp $ */ package net.sourceforge.phpdt.smarty.ui.internal.text; @@ -23,50 +23,50 @@ import org.eclipse.jface.text.rules.Token; */ public class SmartyTagRule implements IRule { - private IToken token; + private IToken token; - public SmartyTagRule(IToken token) { - this.token = token; - } + public SmartyTagRule(IToken token) { + this.token = token; + } - public IToken evaluate(ICharacterScanner scanner) { - int ch = scanner.read(); - if (ch == '}') { - return token; - } - if (ch == '/') { - ch = scanner.read(); - if (ch == '}') { - return token; - } + public IToken evaluate(ICharacterScanner scanner) { + int ch = scanner.read(); + if (ch == '}') { + return token; + } + if (ch == '/') { + ch = scanner.read(); + if (ch == '}') { + return token; + } - scanner.unread(); - scanner.unread(); - return Token.UNDEFINED; - } - if (ch == '{') { - ch = scanner.read(); - if (ch == '/') { - ch = scanner.read(); - } - loop: while (true) { - switch (ch) { - case ICharacterScanner.EOF: - case 0x09: - case 0x0A: - case 0x0D: - case 0x20: - scanner.unread(); - break loop; - case '}': - break loop; - } + scanner.unread(); + scanner.unread(); + return Token.UNDEFINED; + } + if (ch == '{') { + ch = scanner.read(); + if (ch == '/') { + ch = scanner.read(); + } + loop: while (true) { + switch (ch) { + case ICharacterScanner.EOF: + case 0x09: + case 0x0A: + case 0x0D: + case 0x20: + scanner.unread(); + break loop; + case '}': + break loop; + } - ch = scanner.read(); - } - return token; - } - scanner.unread(); - return Token.UNDEFINED; - } + ch = scanner.read(); + } + return token; + } + scanner.unread(); + return Token.UNDEFINED; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/text/SmartyTagScanner.java b/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/text/SmartyTagScanner.java index 22be5dc..b4571bb 100644 --- a/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/text/SmartyTagScanner.java +++ b/net.sourceforge.phpeclipse.smarty.ui/src/net/sourceforge/phpdt/smarty/ui/internal/text/SmartyTagScanner.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: SmartyTagScanner.java,v 1.1 2004-09-02 18:25:04 jsurfer Exp $ + * $Id: SmartyTagScanner.java,v 1.2 2006-10-21 23:19:32 pombredanne Exp $ */ package net.sourceforge.phpdt.smarty.ui.internal.text; @@ -29,22 +29,20 @@ import org.eclipse.jface.text.rules.WordRule; * @author Igor Malinin */ public class SmartyTagScanner extends BufferedRuleBasedScanner { - + /** * Creates a color token scanner. */ public SmartyTagScanner(Map tokens) { - setDefaultReturnToken((Token) tokens.get( - IXMLSyntaxConstants.XML_DEFAULT)); + setDefaultReturnToken((Token) tokens + .get(IXMLSyntaxConstants.XML_DEFAULT)); IToken tag = (Token) tokens.get(IXMLSyntaxConstants.XML_TAG); IToken smartyTag = (Token) tokens.get(IXMLSyntaxConstants.XML_SMARTY); IToken attribute = (Token) tokens.get(IXMLSyntaxConstants.XML_ATT_NAME); - IRule[] rules = { - new XMLTagRule(tag), - new SmartyTagRule(smartyTag), - new WordRule(new NameDetector(), attribute),}; + IRule[] rules = { new XMLTagRule(tag), new SmartyTagRule(smartyTag), + new WordRule(new NameDetector(), attribute), }; setRules(rules); } diff --git a/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpdt/core/tests/util/AbstractCompilerTest.java b/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpdt/core/tests/util/AbstractCompilerTest.java index c334f5f..19da326 100644 --- a/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpdt/core/tests/util/AbstractCompilerTest.java +++ b/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpdt/core/tests/util/AbstractCompilerTest.java @@ -34,35 +34,35 @@ import net.sourceforge.phpdt.internal.compiler.problem.DefaultProblem; import net.sourceforge.phpdt.internal.compiler.problem.DefaultProblemFactory; import net.sourceforge.phpdt.internal.compiler.problem.ProblemReporter; -//import net.sourceforge.phpdt.core.tests.junit.extension.TestCase; -//import net.sourceforge.phpdt.internal.compiler.impl.CompilerOptions; +// import net.sourceforge.phpdt.core.tests.junit.extension.TestCase; +// import net.sourceforge.phpdt.internal.compiler.impl.CompilerOptions; public class AbstractCompilerTest extends TestCase { private static int possibleComplianceLevels = -1; protected String complianceLevel; - public void checkParsePHP( - char[] source, - String expectedSyntaxErrorDiagnosis) { -// String testName) { - UnitParser parser = - new UnitParser( - new ProblemReporter( - DefaultErrorHandlingPolicies.proceedWithAllProblems(), - new CompilerOptions(getCompilerOptions()), - new DefaultProblemFactory(Locale.getDefault()))); + public void checkParsePHP(char[] source, String expectedSyntaxErrorDiagnosis) { + // String testName) { + + UnitParser parser = new UnitParser(new ProblemReporter( + DefaultErrorHandlingPolicies.proceedWithAllProblems(), + new CompilerOptions(getCompilerOptions()), + new DefaultProblemFactory(Locale.getDefault()))); ICompilationUnit sourceUnit = new CompilationUnit(source, "", null); - CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, 0); + CompilationResult compilationResult = new CompilationResult(sourceUnit, + 0, 0, 0); - CompilationUnitDeclaration computedUnit = parser.dietParse(sourceUnit, compilationResult, true); -// if (computedUnit.types != null) { -// for (int i = computedUnit.types.size(); --i >= 0;){ -// ((TypeDeclaration)computedUnit.types.get(i)).parseMethod(parser, computedUnit); -// } -// } + CompilationUnitDeclaration computedUnit = parser.dietParse(sourceUnit, + compilationResult, true); + // if (computedUnit.types != null) { + // for (int i = computedUnit.types.size(); --i >= 0;){ + // ((TypeDeclaration)computedUnit.types.get(i)).parseMethod(parser, + // computedUnit); + // } + // } StringBuffer buffer = new StringBuffer(100); if (compilationResult.hasProblems() || compilationResult.hasTasks()) { @@ -75,10 +75,16 @@ public class AbstractCompilerTest extends TestCase { if (problemCount == 0) buffer.append("----------\n"); problemCount++; - buffer.append(problemCount + (problems[i].isError() ? ". ERROR" : ". WARNING")); - buffer.append(" in " + new String(problems[i].getOriginatingFileName()).replace('/', '\\')); + buffer + .append(problemCount + + (problems[i].isError() ? ". ERROR" + : ". WARNING")); + buffer.append(" in " + + new String(problems[i].getOriginatingFileName()) + .replace('/', '\\')); try { - buffer.append(((DefaultProblem)problems[i]).errorReportSource(unitSource)); + buffer.append(((DefaultProblem) problems[i]) + .errorReportSource(unitSource)); buffer.append("\n"); buffer.append(problems[i].getMessage()); buffer.append("\n"); @@ -92,35 +98,35 @@ public class AbstractCompilerTest extends TestCase { } } String computedSyntaxErrorDiagnosis = buffer.toString(); - if(!expectedSyntaxErrorDiagnosis.equals(computedSyntaxErrorDiagnosis)) { - System.out.println(Util.displayString(computedSyntaxErrorDiagnosis)); + if (!expectedSyntaxErrorDiagnosis.equals(computedSyntaxErrorDiagnosis)) { + System.out + .println(Util.displayString(computedSyntaxErrorDiagnosis)); } - assertEquals( - "Invalid syntax error diagnosis", - expectedSyntaxErrorDiagnosis, - computedSyntaxErrorDiagnosis); + assertEquals("Invalid syntax error diagnosis", + expectedSyntaxErrorDiagnosis, computedSyntaxErrorDiagnosis); } - public void checkParseHTML( - char[] source, - String expectedSyntaxErrorDiagnosis) { -// String testName) { - UnitParser parser = - new UnitParser( - new ProblemReporter( - DefaultErrorHandlingPolicies.proceedWithAllProblems(), - new CompilerOptions(getCompilerOptions()), - new DefaultProblemFactory(Locale.getDefault()))); + public void checkParseHTML(char[] source, + String expectedSyntaxErrorDiagnosis) { + // String testName) { + + UnitParser parser = new UnitParser(new ProblemReporter( + DefaultErrorHandlingPolicies.proceedWithAllProblems(), + new CompilerOptions(getCompilerOptions()), + new DefaultProblemFactory(Locale.getDefault()))); ICompilationUnit sourceUnit = new CompilationUnit(source, "", null); - CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, 0); + CompilationResult compilationResult = new CompilationResult(sourceUnit, + 0, 0, 0); - CompilationUnitDeclaration computedUnit = parser.dietParse(sourceUnit, compilationResult, false); -// if (computedUnit.types != null) { -// for (int i = computedUnit.types.size(); --i >= 0;){ -// ((TypeDeclaration)computedUnit.types.get(i)).parseMethod(parser, computedUnit); -// } -// } + CompilationUnitDeclaration computedUnit = parser.dietParse(sourceUnit, + compilationResult, false); + // if (computedUnit.types != null) { + // for (int i = computedUnit.types.size(); --i >= 0;){ + // ((TypeDeclaration)computedUnit.types.get(i)).parseMethod(parser, + // computedUnit); + // } + // } StringBuffer buffer = new StringBuffer(100); if (compilationResult.hasProblems() || compilationResult.hasTasks()) { @@ -133,10 +139,16 @@ public class AbstractCompilerTest extends TestCase { if (problemCount == 0) buffer.append("----------\n"); problemCount++; - buffer.append(problemCount + (problems[i].isError() ? ". ERROR" : ". WARNING")); - buffer.append(" in " + new String(problems[i].getOriginatingFileName()).replace('/', '\\')); + buffer + .append(problemCount + + (problems[i].isError() ? ". ERROR" + : ". WARNING")); + buffer.append(" in " + + new String(problems[i].getOriginatingFileName()) + .replace('/', '\\')); try { - buffer.append(((DefaultProblem)problems[i]).errorReportSource(unitSource)); + buffer.append(((DefaultProblem) problems[i]) + .errorReportSource(unitSource)); buffer.append("\n"); buffer.append(problems[i].getMessage()); buffer.append("\n"); @@ -150,61 +162,65 @@ public class AbstractCompilerTest extends TestCase { } } String computedSyntaxErrorDiagnosis = buffer.toString(); - if(!expectedSyntaxErrorDiagnosis.equals(computedSyntaxErrorDiagnosis)) { - System.out.println(Util.displayString(computedSyntaxErrorDiagnosis)); + if (!expectedSyntaxErrorDiagnosis.equals(computedSyntaxErrorDiagnosis)) { + System.out + .println(Util.displayString(computedSyntaxErrorDiagnosis)); } - assertEquals( - "Invalid syntax error diagnosis", - expectedSyntaxErrorDiagnosis, - computedSyntaxErrorDiagnosis); + assertEquals("Invalid syntax error diagnosis", + expectedSyntaxErrorDiagnosis, computedSyntaxErrorDiagnosis); } + /* * Returns the possible compliance levels this VM instance can run. */ -// public static int getPossibleComplianceLevels() { -// if (possibleComplianceLevels == -1) { -// String compliance = System.getProperty("compliance"); -// if (compliance != null) { -// if (COMPLIANCE_1_3.equals(compliance)) { -// possibleComplianceLevels = F_1_3; -// } else if (COMPLIANCE_1_4.equals(compliance)) { -// possibleComplianceLevels = F_1_4; -// } else if (COMPLIANCE_1_5.equals(compliance)) { -// possibleComplianceLevels = F_1_5; -// } else { -// System.out.println("Invalid compliance specified (" + compliance + ")"); -// System.out.println("Use one of " + COMPLIANCE_1_3 + ", " + COMPLIANCE_1_4 + ", " + COMPLIANCE_1_5); -// System.out.println("Defaulting to all possible compliances"); -// } -// } -// if (possibleComplianceLevels == -1) { -// possibleComplianceLevels = F_1_3; -// String specVersion = System.getProperty("java.specification.version"); -// boolean canRun1_4 = !"1.0".equals(specVersion) && !"1.1".equals(specVersion) && !"1.2".equals(specVersion) && !"1.3".equals(specVersion); -// if (canRun1_4) { -// possibleComplianceLevels |= F_1_4; -// } -// boolean canRun1_5 = canRun1_4 && !"1.4".equals(specVersion); -// if (canRun1_5) { -// possibleComplianceLevels |= F_1_5; -// } -// } -// } -// return possibleComplianceLevels; -// } - + // public static int getPossibleComplianceLevels() { + // if (possibleComplianceLevels == -1) { + // String compliance = System.getProperty("compliance"); + // if (compliance != null) { + // if (COMPLIANCE_1_3.equals(compliance)) { + // possibleComplianceLevels = F_1_3; + // } else if (COMPLIANCE_1_4.equals(compliance)) { + // possibleComplianceLevels = F_1_4; + // } else if (COMPLIANCE_1_5.equals(compliance)) { + // possibleComplianceLevels = F_1_5; + // } else { + // System.out.println("Invalid compliance specified (" + compliance + ")"); + // System.out.println("Use one of " + COMPLIANCE_1_3 + ", " + COMPLIANCE_1_4 + // + ", " + COMPLIANCE_1_5); + // System.out.println("Defaulting to all possible compliances"); + // } + // } + // if (possibleComplianceLevels == -1) { + // possibleComplianceLevels = F_1_3; + // String specVersion = System.getProperty("java.specification.version"); + // boolean canRun1_4 = !"1.0".equals(specVersion) && + // !"1.1".equals(specVersion) && !"1.2".equals(specVersion) && + // !"1.3".equals(specVersion); + // if (canRun1_4) { + // possibleComplianceLevels |= F_1_4; + // } + // boolean canRun1_5 = canRun1_4 && !"1.4".equals(specVersion); + // if (canRun1_5) { + // possibleComplianceLevels |= F_1_5; + // } + // } + // } + // return possibleComplianceLevels; + // } /* - * Returns a test suite including the tests defined by the given classes for the given complianceLevel - * (see AbstractCompilerTest for valid values) and using the given setup class (CompilerTestSetup or a subclass) + * Returns a test suite including the tests defined by the given classes for + * the given complianceLevel (see AbstractCompilerTest for valid values) and + * using the given setup class (CompilerTestSetup or a subclass) */ - public static Test suiteForComplianceLevel(String complianceLevel, Class setupClass, ArrayList testClasses) { + public static Test suiteForComplianceLevel(String complianceLevel, + Class setupClass, ArrayList testClasses) { TestSuite suite; if (testClasses.size() == 1) { - suite = new TestSuite((Class)testClasses.get(0), complianceLevel); + suite = new TestSuite((Class) testClasses.get(0), complianceLevel); } else { suite = new TestSuite(complianceLevel); for (int i = 0, length = testClasses.size(); i < length; i++) { - Class testClass = (Class)testClasses.get(i); + Class testClass = (Class) testClasses.get(i); TestSuite innerSuite = new TestSuite(testClass); suite.addTest(innerSuite); } @@ -212,8 +228,10 @@ public class AbstractCompilerTest extends TestCase { // call the setup constructor with the suite and compliance level try { - Constructor constructor = setupClass.getConstructor(new Class[]{Test.class, String.class}); - Test setUp = (Test)constructor.newInstance(new Object[]{suite, complianceLevel}); + Constructor constructor = setupClass.getConstructor(new Class[] { + Test.class, String.class }); + Test setUp = (Test) constructor.newInstance(new Object[] { suite, + complianceLevel }); return setUp; } catch (IllegalAccessException e) { e.printStackTrace(); @@ -235,12 +253,19 @@ public class AbstractCompilerTest extends TestCase { protected Map getCompilerOptions() { Map options = new CompilerOptions().getMap(); // ignore warnings - options.put(CompilerOptions.OPTION_PHPVarDeprecatedWarning, CompilerOptions.IGNORE); - options.put(CompilerOptions.OPTION_PHPBadStyleKeywordWarning, CompilerOptions.IGNORE); - options.put(CompilerOptions.OPTION_PHPBadStyleUppercaseIdentifierWarning, CompilerOptions.IGNORE); - options.put(CompilerOptions.OPTION_PHPIncludeNotExistWarning, CompilerOptions.IGNORE); - options.put(CompilerOptions.OPTION_UninitializedLocalVariableWarning, CompilerOptions.IGNORE); - options.put(CompilerOptions.OPTION_CodeCannotBeReachedWarning, CompilerOptions.IGNORE); + options.put(CompilerOptions.OPTION_PHPVarDeprecatedWarning, + CompilerOptions.IGNORE); + options.put(CompilerOptions.OPTION_PHPBadStyleKeywordWarning, + CompilerOptions.IGNORE); + options.put( + CompilerOptions.OPTION_PHPBadStyleUppercaseIdentifierWarning, + CompilerOptions.IGNORE); + options.put(CompilerOptions.OPTION_PHPIncludeNotExistWarning, + CompilerOptions.IGNORE); + options.put(CompilerOptions.OPTION_UninitializedLocalVariableWarning, + CompilerOptions.IGNORE); + options.put(CompilerOptions.OPTION_CodeCannotBeReachedWarning, + CompilerOptions.IGNORE); return options; } @@ -251,11 +276,12 @@ public class AbstractCompilerTest extends TestCase { } return name; } - + protected void checkPHP(String strEval) { - checkPHP(strEval,""); + checkPHP(strEval, ""); } - protected void checkPHP(String strEval, String expectedSyntaxErrorDiagnosis ) { + + protected void checkPHP(String strEval, String expectedSyntaxErrorDiagnosis) { if (Scanner.DEBUG) { System.out.println("\n------------------------------------"); System.out.println(strEval); @@ -264,12 +290,10 @@ public class AbstractCompilerTest extends TestCase { } protected void checkHTML(String strEval) { - if (Scanner.DEBUG) { - System.out.println("\n------------------------------------"); - System.out.println(strEval); - } - checkParseHTML( - strEval.toCharArray(), - ""); - } + if (Scanner.DEBUG) { + System.out.println("\n------------------------------------"); + System.out.println(strEval); + } + checkParseHTML(strEval.toCharArray(), ""); + } } diff --git a/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpdt/core/tests/util/Util.java b/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpdt/core/tests/util/Util.java index 5c91332..5316029 100644 --- a/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpdt/core/tests/util/Util.java +++ b/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpdt/core/tests/util/Util.java @@ -10,21 +10,15 @@ *******************************************************************************/ package net.sourceforge.phpdt.core.tests.util; -import java.io.*; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.PrintWriter; import java.net.ServerSocket; -import java.util.Locale; -import java.util.Map; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; -// import net.sourceforge.phpdt.core.tests.compiler.regression.Requestor; -import net.sourceforge.phpdt.internal.compiler.Compiler; -import net.sourceforge.phpdt.internal.compiler.IErrorHandlingPolicy; -import net.sourceforge.phpdt.internal.compiler.IProblemFactory; import net.sourceforge.phpdt.internal.compiler.batch.CompilationUnit; -// import net.sourceforge.phpdt.internal.compiler.batch.FileSystem; -import net.sourceforge.phpdt.internal.compiler.env.INameEnvironment; -import net.sourceforge.phpdt.internal.compiler.problem.DefaultProblemFactory; public class Util { public static String OUTPUT_DIRECTORY = "comptest"; @@ -34,7 +28,8 @@ public class Util { CompilationUnit[] result = new CompilationUnit[length]; int index = 0; for (int i = 0; i < length; i++) { - result[i] = new CompilationUnit(testFiles[index + 1].toCharArray(), testFiles[index], null); + result[i] = new CompilationUnit(testFiles[index + 1].toCharArray(), + testFiles[index], null); index += 2; } return result; @@ -71,8 +66,8 @@ public class Util { } /** - * Copy the given source (a file or a directory that must exists) to the given - * destination (a directory that must exists). + * Copy the given source (a file or a directory that must exists) to the + * given destination (a directory that must exists). */ public static void copy(String sourcePath, String destPath) { sourcePath = toNativePath(sourcePath); @@ -136,7 +131,8 @@ public class Util { } } - // public static void createJar(String[] pathsAndContents, Map options, String + // public static void createJar(String[] pathsAndContents, Map options, + // String // jarPath) throws IOException { // String classesPath = getOutputDirectory() + File.separator + "classes"; // File classesDir = new File(classesPath); @@ -148,7 +144,7 @@ public class Util { * Generate a display string from the given String. * * @param indent - * number of tabs are added at the begining of each line. + * number of tabs are added at the begining of each line. * * Example of use: * [org.eclipse.jdt.core.tests.util.Util.displayString("abc\ndef\tghi")] @@ -176,30 +172,30 @@ public class Util { *

  • * *
    -	 *  input string = "abc\ndef\tghi",
    -	 *  indent = 3
    -	 *  result = "\"\t\t\tabc\\n" +
    -	 *  			"\t\t\tdef\tghi\""
    +	 *   input string = "abc\ndef\tghi",
    +	 *   indent = 3
    +	 *   result = "\"\t\t\tabc\\n" +
    +	 *   			"\t\t\tdef\tghi\""
     	 * 
    * *
  • *
  • * *
    -	 *  input string = "abc\ndef\tghi\n",
    -	 *  indent = 3
    -	 *  result = "\"\t\t\tabc\\n" +
    -	 *  			"\t\t\tdef\tghi\\n\""
    +	 *   input string = "abc\ndef\tghi\n",
    +	 *   indent = 3
    +	 *   result = "\"\t\t\tabc\\n" +
    +	 *   			"\t\t\tdef\tghi\\n\""
     	 * 
    * *
  • *
  • * *
    -	 *  input string = "abc\r\ndef\tghi\r\n",
    -	 *  indent = 3
    -	 *  result = "\"\t\t\tabc\\r\\n" +
    -	 *  			"\t\t\tdef\tghi\\r\\n\""
    +	 *   input string = "abc\r\ndef\tghi\r\n",
    +	 *   indent = 3
    +	 *   result = "\"\t\t\tabc\\r\\n" +
    +	 *   			"\t\t\tdef\tghi\\r\\n\""
     	 * 
    * *
  • @@ -207,16 +203,17 @@ public class Util { *

    * * @param inputString - * the given input string + * the given input string * @param indent - * number of tabs are added at the begining of each line. + * number of tabs are added at the begining of each line. * * @return the displayed string */ public static String displayString(String inputString, int indent) { int length = inputString.length(); StringBuffer buffer = new StringBuffer(length); - java.util.StringTokenizer tokenizer = new java.util.StringTokenizer(inputString, "\n\r", true); + java.util.StringTokenizer tokenizer = new java.util.StringTokenizer( + inputString, "\n\r", true); for (int i = 0; i < indent; i++) buffer.append("\t"); buffer.append("\""); @@ -302,7 +299,8 @@ public class Util { * [org.eclipse.jdt.core.tests.util.Util.fileContentToDisplayString("c:/temp/X.java", * 0)] */ - public static String fileContentToDisplayString(String sourceFilePath, int indent, boolean independantLineDelimiter) { + public static String fileContentToDisplayString(String sourceFilePath, + int indent, boolean independantLineDelimiter) { File sourceFile = new File(sourceFilePath); if (!sourceFile.exists()) { System.out.println("File " + sourceFilePath + " does not exists."); @@ -346,16 +344,18 @@ public class Util { /** * Reads the content of the given source file, converts it to a display - * string. If the destination file path is not null, writes the result to this - * file. Otherwise writes it to the console. + * string. If the destination file path is not null, writes the result to + * this file. Otherwise writes it to the console. * * Example of use: * [org.eclipse.jdt.core.tests.util.Util.fileContentToDisplayString("c:/temp/X.java", * 0, null)] */ - public static void fileContentToDisplayString(String sourceFilePath, int indent, String destinationFilePath, + public static void fileContentToDisplayString(String sourceFilePath, + int indent, String destinationFilePath, boolean independantLineDelimiter) { - String displayString = fileContentToDisplayString(sourceFilePath, indent, independantLineDelimiter); + String displayString = fileContentToDisplayString(sourceFilePath, + indent, independantLineDelimiter); if (destinationFilePath == null) { System.out.println(displayString); return; @@ -395,13 +395,16 @@ public class Util { } else { final String vmName = System.getProperty("java.vm.name"); if ("J9".equals(vmName)) { - return new String[] { toNativePath(jreDir + "/lib/jclMax/classes.zip") }; + return new String[] { toNativePath(jreDir + + "/lib/jclMax/classes.zip") }; } else { File file = new File(jreDir + "/lib/rt.jar"); if (file.exists()) { return new String[] { toNativePath(jreDir + "/lib/rt.jar") }; } else { - return new String[] { toNativePath(jreDir + "/lib/core.jar"), toNativePath(jreDir + "/lib/security.jar"), + return new String[] { + toNativePath(jreDir + "/lib/core.jar"), + toNativePath(jreDir + "/lib/security.jar"), toNativePath(jreDir + "/lib/graphics.jar") }; } } @@ -429,10 +432,11 @@ public class Util { } /** - * Search the user hard-drive for a possible output directory. Returns null if - * none could be found. + * Search the user hard-drive for a possible output directory. Returns null + * if none could be found. * - * Example of use: [org.eclipse.jdt.core.tests.util.Util.getOutputDirectory()] + * Example of use: + * [org.eclipse.jdt.core.tests.util.Util.getOutputDirectory()] */ public static String getOutputDirectory() { String container = System.getProperty("user.home"); @@ -470,8 +474,11 @@ public class Util { * File.getPath() and trimming any extra slash. */ public static String toNativePath(String path) { - String nativePath = path.replace('\\', File.separatorChar).replace('/', File.separatorChar); - return nativePath.endsWith("/") || nativePath.endsWith("\\") ? nativePath.substring(0, nativePath.length() - 1) : nativePath; + String nativePath = path.replace('\\', File.separatorChar).replace('/', + File.separatorChar); + return nativePath.endsWith("/") || nativePath.endsWith("\\") ? nativePath + .substring(0, nativePath.length() - 1) + : nativePath; } public static void writeToFile(String contents, String destinationFilePath) { diff --git a/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/example/outline/Import2Console.java b/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/example/outline/Import2Console.java index 61848af..ac1a01b 100644 --- a/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/example/outline/Import2Console.java +++ b/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/example/outline/Import2Console.java @@ -1,65 +1,72 @@ package net.sourceforge.phpeclipse.example.outline; -import org.eclipse.core.resources.*; -import net.sourceforge.phpdt.core.*; -import org.eclipse.jface.action.*; -import org.eclipse.jface.viewers.*; -import org.eclipse.ui.*; +import net.sourceforge.phpdt.core.IImportDeclaration; + +import org.eclipse.core.resources.IWorkspace; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.ui.IActionDelegate; +import org.eclipse.ui.IObjectActionDelegate; +import org.eclipse.ui.IWorkbenchPart; +import org.eclipse.ui.IWorkbenchPartSite; public class Import2Console implements IObjectActionDelegate { - private IWorkbenchPartSite myPartSite = null; - - private IWorkspace myWorkspace = null; - - private IWorkbenchPart myWorkbenchPart = null; - - private IImportDeclaration myType = null; - - public Import2Console() { - // this(new PackageSelector()); - } - - // public CreateMock(IPackageSelector aPackageSelector) { - // myPackageSelector = aPackageSelector; - // } - - /** - * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart) - */ - public void setActivePart(IAction action, IWorkbenchPart targetPart) { - myWorkspace = ResourcesPlugin.getWorkspace(); - myWorkbenchPart = targetPart; - } - - /** - * @see IActionDelegate#run(IAction) - */ - public void run(IAction action) { - try { - String actionId = action.getId(); - showSourceInConsole(actionId); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * @see IActionDelegate#selectionChanged(IAction, ISelection) - */ - public void selectionChanged(IAction action, ISelection selection) { - if (selection instanceof IStructuredSelection) { - Object item = ((IStructuredSelection) selection).getFirstElement(); - myType = (IImportDeclaration) item; // this plugin only reacts to IImportDeclaration's - } - } - - private void showSourceInConsole(String actionId) throws Exception { - - String src = myType.getSource(); - System.out.println(actionId); - System.out.println("Source :"+src); - - } + private IWorkbenchPartSite myPartSite = null; + + private IWorkspace myWorkspace = null; + + private IWorkbenchPart myWorkbenchPart = null; + + private IImportDeclaration myType = null; + + public Import2Console() { + // this(new PackageSelector()); + } + + // public CreateMock(IPackageSelector aPackageSelector) { + // myPackageSelector = aPackageSelector; + // } + + /** + * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart) + */ + public void setActivePart(IAction action, IWorkbenchPart targetPart) { + myWorkspace = ResourcesPlugin.getWorkspace(); + myWorkbenchPart = targetPart; + } + + /** + * @see IActionDelegate#run(IAction) + */ + public void run(IAction action) { + try { + String actionId = action.getId(); + showSourceInConsole(actionId); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * @see IActionDelegate#selectionChanged(IAction, ISelection) + */ + public void selectionChanged(IAction action, ISelection selection) { + if (selection instanceof IStructuredSelection) { + Object item = ((IStructuredSelection) selection).getFirstElement(); + myType = (IImportDeclaration) item; // this plugin only reacts to + // IImportDeclaration's + } + } + + private void showSourceInConsole(String actionId) throws Exception { + + String src = myType.getSource(); + System.out.println(actionId); + System.out.println("Source :" + src); + + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/example/outline/Type2Console.java b/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/example/outline/Type2Console.java index 9c08fa7..e310315 100644 --- a/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/example/outline/Type2Console.java +++ b/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/example/outline/Type2Console.java @@ -1,75 +1,81 @@ package net.sourceforge.phpeclipse.example.outline; - -import org.eclipse.core.resources.*; -import net.sourceforge.phpdt.core.*; -import org.eclipse.jface.action.*; -import org.eclipse.jface.viewers.*; -import org.eclipse.swt.widgets.*; -import org.eclipse.ui.*; +import net.sourceforge.phpdt.core.IMethod; +import net.sourceforge.phpdt.core.IType; + +import org.eclipse.core.resources.IWorkspace; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IActionDelegate; +import org.eclipse.ui.IObjectActionDelegate; +import org.eclipse.ui.IWorkbenchPart; +import org.eclipse.ui.IWorkbenchPartSite; public class Type2Console implements IObjectActionDelegate { - private IWorkbenchPartSite myPartSite = null; - - private IWorkspace myWorkspace = null; - - private IWorkbenchPart myWorkbenchPart = null; - - private IType myType = null; - - private Shell myShell = new Shell(); // TBReplaced with getShell() - - public Type2Console() { - } - - /** - * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart) - */ - public void setActivePart(IAction action, IWorkbenchPart targetPart) { - myWorkspace = ResourcesPlugin.getWorkspace(); - myWorkbenchPart = targetPart; - } - - /** - * @see IActionDelegate#run(IAction) - */ - public void run(IAction action) { - try { - - String actionId = action.getId(); - showSourceInConsole(actionId); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * @see IActionDelegate#selectionChanged(IAction, ISelection) - */ - public void selectionChanged(IAction action, ISelection selection) { - if (selection instanceof IStructuredSelection) { - Object item = ((IStructuredSelection) selection).getFirstElement(); - myType = (IType) item; // this plugin only reacts to - // "org.eclipse.jdt.core.IType" objects - } - } - - private void showSourceInConsole(String actionId) throws Exception { - System.out.println(actionId); - if (!(myType.isInterface() || myType.isClass())) { - throw new Exception("incompatible Type"); - } - - IMethod[] methods = myType.getMethods(); - - String fqname = myType.getFullyQualifiedName(); // a.b.c.d.MyClass - System.out.println(fqname + '\n'); - for (int i = 0; i < methods.length; i++) { - System.out.println("Method " + i + ":" - + methods[i].getElementName()); - } - - } + private IWorkbenchPartSite myPartSite = null; + + private IWorkspace myWorkspace = null; + + private IWorkbenchPart myWorkbenchPart = null; + + private IType myType = null; + + private Shell myShell = new Shell(); // TBReplaced with getShell() + + public Type2Console() { + } + + /** + * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart) + */ + public void setActivePart(IAction action, IWorkbenchPart targetPart) { + myWorkspace = ResourcesPlugin.getWorkspace(); + myWorkbenchPart = targetPart; + } + + /** + * @see IActionDelegate#run(IAction) + */ + public void run(IAction action) { + try { + + String actionId = action.getId(); + showSourceInConsole(actionId); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * @see IActionDelegate#selectionChanged(IAction, ISelection) + */ + public void selectionChanged(IAction action, ISelection selection) { + if (selection instanceof IStructuredSelection) { + Object item = ((IStructuredSelection) selection).getFirstElement(); + myType = (IType) item; // this plugin only reacts to + // "org.eclipse.jdt.core.IType" objects + } + } + + private void showSourceInConsole(String actionId) throws Exception { + System.out.println(actionId); + if (!(myType.isInterface() || myType.isClass())) { + throw new Exception("incompatible Type"); + } + + IMethod[] methods = myType.getMethods(); + + String fqname = myType.getFullyQualifiedName(); // a.b.c.d.MyClass + System.out.println(fqname + '\n'); + for (int i = 0; i < methods.length; i++) { + System.out.println("Method " + i + ":" + + methods[i].getElementName()); + } + + } } diff --git a/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/phpeditor/php/test/DualParseSyntaxErrorTest.java b/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/phpeditor/php/test/DualParseSyntaxErrorTest.java index 44df779..15b4590 100644 --- a/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/phpeditor/php/test/DualParseSyntaxErrorTest.java +++ b/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/phpeditor/php/test/DualParseSyntaxErrorTest.java @@ -9,138 +9,108 @@ package net.sourceforge.phpeclipse.phpeditor.php.test; import net.sourceforge.phpdt.core.tests.util.AbstractCompilerTest; public class DualParseSyntaxErrorTest extends AbstractCompilerTest { - public static boolean optimizeStringLiterals = false; - - public DualParseSyntaxErrorTest(String testName){ + public static boolean optimizeStringLiterals = false; + + public DualParseSyntaxErrorTest(String testName) { super(testName); } - + public void test01() { - String s = - "$login =1; " + - "final class test {\n" + - "\n" + - "private function f1() {\n" + - "\n" + - "}\n" + - "public function f2() {\n" + - "\n" + - " \n" + - "} \n" + - "}"; - - String expectedSyntaxErrorDiagnosis = - ""; + String s = "$login =1; " + "final class test {\n" + "\n" + + "private function f1() {\n" + "\n" + "}\n" + + "public function f2() {\n" + "\n" + " \n" + "} \n" + "}"; + + String expectedSyntaxErrorDiagnosis = ""; String testName = ""; - checkParsePHP( - s.toCharArray(), - expectedSyntaxErrorDiagnosis); -// testName); + checkParsePHP(s.toCharArray(), expectedSyntaxErrorDiagnosis); + // testName); } + public void test02() { - String s = - "class test { \n"+ - " function f0() \n"+ - " { \n"+ - " } \n"+ - "} \n"; + String s = "class test { \n" + " function f0() \n" + + " { \n" + " } \n" + + "} \n"; - String expectedSyntaxErrorDiagnosis = - ""; + String expectedSyntaxErrorDiagnosis = ""; String testName = ""; - checkParsePHP( - s.toCharArray(), - expectedSyntaxErrorDiagnosis); -// testName); + checkParsePHP(s.toCharArray(), expectedSyntaxErrorDiagnosis); + // testName); } + public void test03() { - String s = - "$chars = ( isset($HTTP_GET_VARS['chars']) ) ? intval($HTTP_GET_VARS['chars']) : 200;"; - String expectedSyntaxErrorDiagnosis = - ""; - - checkParsePHP( - s.toCharArray(), - expectedSyntaxErrorDiagnosis); -// testName); -} + String s = "$chars = ( isset($HTTP_GET_VARS['chars']) ) ? intval($HTTP_GET_VARS['chars']) : 200;"; + String expectedSyntaxErrorDiagnosis = ""; + + checkParsePHP(s.toCharArray(), expectedSyntaxErrorDiagnosis); + // testName); + } + public void test96() { String s = "$str = <<foo = 'Foo';\n" - + " $this->bar = array('Bar1', 'Bar2', 'Bar3');\n" + " }\n" - + "}\n" + "\n" + "$foo = new foo();\n" + "$name = 'MyName';\n" + "\n" - + "echo <<foo.\n" - + "Now, I am printing some {$foo->bar[1]}.\n" - + "This should print a capital 'A': \\x41\n" + "EOT;\n"; - String expectedSyntaxErrorDiagnosis = - ""; - - checkParsePHP( - s.toCharArray(), - expectedSyntaxErrorDiagnosis); -// testName); + + "spanning multiple lines\n" + "using heredoc syntax.\n" + + "EOD;\n" + "\n" + + "/* More complex example, with variables. */\n" + + "class foo\n" + "{\n" + " var $foo;\n" + " var $bar;\n" + + "\n" + " function foo()\n" + " {\n" + + " $this->foo = 'Foo';\n" + + " $this->bar = array('Bar1', 'Bar2', 'Bar3');\n" + + " }\n" + "}\n" + "\n" + "$foo = new foo();\n" + + "$name = 'MyName';\n" + "\n" + "echo <<foo.\n" + + "Now, I am printing some {$foo->bar[1]}.\n" + + "This should print a capital 'A': \\x41\n" + "EOT;\n"; + String expectedSyntaxErrorDiagnosis = ""; + + checkParsePHP(s.toCharArray(), expectedSyntaxErrorDiagnosis); + // testName); } + public void test97() { - String s = - "class momo { \n"+ - " function &fetchRow($result, $fetchmode = DB_FETCHMODE_DEFAULT, $rownum=null) \n"+ - " { \n"+ - " } \n"+ - "} \n"; - - String expectedSyntaxErrorDiagnosis = - ""; - - checkParsePHP( - s.toCharArray(), - expectedSyntaxErrorDiagnosis); -// testName); + String s = "class momo { \n" + + " function &fetchRow($result, $fetchmode = DB_FETCHMODE_DEFAULT, $rownum=null) \n" + + " { \n" + " } \n" + + "} \n"; + + String expectedSyntaxErrorDiagnosis = ""; + + checkParsePHP(s.toCharArray(), expectedSyntaxErrorDiagnosis); + // testName); } + public void test98() { - String s = - "return(array());"+ - "if(!$result = mysql_query($sql)) return(array());\n"; + String s = "return(array());" + + "if(!$result = mysql_query($sql)) return(array());\n"; - String expectedSyntaxErrorDiagnosis = - ""; + String expectedSyntaxErrorDiagnosis = ""; - checkParsePHP( - s.toCharArray(), - expectedSyntaxErrorDiagnosis); -// testName); + checkParsePHP(s.toCharArray(), expectedSyntaxErrorDiagnosis); + // testName); } - + public void test99() { - String s = - "class test { \n"+ - " murks; \n"+ - " function &fetchRow($result, $fetchmode = DB_FETCHMODE_DEFAULT, $rownum=null) \n"+ - " { \n"+ - " } \n"+ - "} \n"; - - String expectedSyntaxErrorDiagnosis = "----------\n" - + "1. ERROR in (at line 1)\n" - + " murks; \n" - + " ^^^^^^\n" - + "Parser error \"\'public\' \'private\' or \'protected\' modifier expected for field declarations.\"\n" - + "----------\n" -// + "2. ERROR in (at line 1)\n" -// + " } \n" -// + " ^\n" -// + "Parser error \"Too many closing \'}\'; end-of-file not reached.\"\n" -// + "----------\n" - ; - - checkParsePHP( - s.toCharArray(), - expectedSyntaxErrorDiagnosis); -// testName); + String s = "class test { \n" + + " murks; \n" + + " function &fetchRow($result, $fetchmode = DB_FETCHMODE_DEFAULT, $rownum=null) \n" + + " { \n" + " } \n" + + "} \n"; + + String expectedSyntaxErrorDiagnosis = "----------\n" + + "1. ERROR in (at line 1)\n" + + " murks; \n" + + " ^^^^^^\n" + + "Parser error \"\'public\' \'private\' or \'protected\' modifier expected for field declarations.\"\n" + + "----------\n" + // + "2. ERROR in (at line 1)\n" + // + " } \n" + // + " ^\n" + // + "Parser error \"Too many closing \'}\'; end-of-file not + // reached.\"\n" + // + "----------\n" + ; + + checkParsePHP(s.toCharArray(), expectedSyntaxErrorDiagnosis); + // testName); } } diff --git a/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/phpeditor/php/test/DummyDocument.java b/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/phpeditor/php/test/DummyDocument.java index b758fa9..4b17910 100644 --- a/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/phpeditor/php/test/DummyDocument.java +++ b/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/phpeditor/php/test/DummyDocument.java @@ -4,388 +4,447 @@ */ package net.sourceforge.phpeclipse.phpeditor.php.test; -import org.eclipse.jface.text.*; - -/** +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.BadPositionCategoryException; +import org.eclipse.jface.text.Document; +import org.eclipse.jface.text.IDocumentListener; +import org.eclipse.jface.text.IDocumentPartitioner; +import org.eclipse.jface.text.IDocumentPartitioningListener; +import org.eclipse.jface.text.IPositionUpdater; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITypedRegion; +import org.eclipse.jface.text.Position; + +/** * Mockobject for Testing. * * @author Stefan Langer - * @version $Revision: 1.2 $ + * @version $Revision: 1.3 $ */ public class DummyDocument extends Document // implements IDocument { private char[] fTextBuffer; - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#getChar(int) - */ - public char getChar(int offset) throws BadLocationException - { - if(offset >= 0 && offset < fTextBuffer.length) - return fTextBuffer[offset]; - else - throw new BadLocationException("Offset out of range!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#getLength() - */ - public int getLength() - { - return fTextBuffer.length; - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#get() - */ - public String get() - { - return String.copyValueOf(fTextBuffer); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#get(int, int) - */ - public String get(int offset, int length) throws BadLocationException - { - if(offset >= 0 && (offset + length) < fTextBuffer.length) - return String.copyValueOf(fTextBuffer, offset, length); - else - throw new BadLocationException("Out of range!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#set(java.lang.String) - */ - public void set(String text) - { - fTextBuffer = text.toCharArray(); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#replace(int, int, java.lang.String) - */ - public void replace(int offset, int length, String text) - throws BadLocationException - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#addDocumentListener(org.eclipse.jface.text.IDocumentListener) - */ - public void addDocumentListener(IDocumentListener listener) - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#removeDocumentListener(org.eclipse.jface.text.IDocumentListener) - */ - public void removeDocumentListener(IDocumentListener listener) - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#addPrenotifiedDocumentListener(org.eclipse.jface.text.IDocumentListener) - */ - public void addPrenotifiedDocumentListener(IDocumentListener documentAdapter) - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#removePrenotifiedDocumentListener(org.eclipse.jface.text.IDocumentListener) - */ - public void removePrenotifiedDocumentListener(IDocumentListener documentAdapter) - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#addPositionCategory(java.lang.String) - */ -// public void addPositionCategory(String category) -// { -// throw new UnsupportedOperationException("Not implemented!"); -// } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#removePositionCategory(java.lang.String) - */ - public void removePositionCategory(String category) - throws BadPositionCategoryException - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#getPositionCategories() - */ - public String[] getPositionCategories() - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#containsPositionCategory(java.lang.String) - */ -// public boolean containsPositionCategory(String category) -// { -// throw new UnsupportedOperationException("Not implemented!"); -// } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#addPosition(org.eclipse.jface.text.Position) - */ - public void addPosition(Position position) throws BadLocationException - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#removePosition(org.eclipse.jface.text.Position) - */ - public void removePosition(Position position) - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#addPosition(java.lang.String, org.eclipse.jface.text.Position) - */ - public void addPosition(String category, Position position) - throws BadLocationException, BadPositionCategoryException - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#removePosition(java.lang.String, org.eclipse.jface.text.Position) - */ - public void removePosition(String category, Position position) - throws BadPositionCategoryException - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#getPositions(java.lang.String) - */ - public Position[] getPositions(String category) - throws BadPositionCategoryException - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#containsPosition(java.lang.String, int, int) - */ - public boolean containsPosition(String category, int offset, int length) - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#computeIndexInCategory(java.lang.String, int) - */ - public int computeIndexInCategory(String category, int offset) - throws BadLocationException, BadPositionCategoryException - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#addPositionUpdater(org.eclipse.jface.text.IPositionUpdater) - */ -// public void addPositionUpdater(IPositionUpdater updater) -// { -// throw new UnsupportedOperationException("Not implemented!"); -// } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#removePositionUpdater(org.eclipse.jface.text.IPositionUpdater) - */ - public void removePositionUpdater(IPositionUpdater updater) - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#insertPositionUpdater(org.eclipse.jface.text.IPositionUpdater, int) - */ -// public void insertPositionUpdater(IPositionUpdater updater, int index) -// { -// throw new UnsupportedOperationException("Not implemented!"); -// } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#getPositionUpdaters() - */ - public IPositionUpdater[] getPositionUpdaters() - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#getLegalContentTypes() - */ - public String[] getLegalContentTypes() - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#getContentType(int) - */ - public String getContentType(int offset) throws BadLocationException - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#getPartition(int) - */ - public ITypedRegion getPartition(int offset) throws BadLocationException - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#computePartitioning(int, int) - */ - public ITypedRegion[] computePartitioning(int offset, int length) - throws BadLocationException - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#addDocumentPartitioningListener(org.eclipse.jface.text.IDocumentPartitioningListener) - */ - public void addDocumentPartitioningListener(IDocumentPartitioningListener listener) - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#removeDocumentPartitioningListener(org.eclipse.jface.text.IDocumentPartitioningListener) - */ - public void removeDocumentPartitioningListener(IDocumentPartitioningListener listener) - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#setDocumentPartitioner(org.eclipse.jface.text.IDocumentPartitioner) - */ - public void setDocumentPartitioner(IDocumentPartitioner partitioner) - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#getDocumentPartitioner() - */ - public IDocumentPartitioner getDocumentPartitioner() - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#getLineLength(int) - */ - public int getLineLength(int line) throws BadLocationException - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#getLineOfOffset(int) - */ - public int getLineOfOffset(int offset) throws BadLocationException - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#getLineOffset(int) - */ - public int getLineOffset(int line) throws BadLocationException - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#getLineInformation(int) - */ - public IRegion getLineInformation(int line) throws BadLocationException - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#getLineInformationOfOffset(int) - */ - public IRegion getLineInformationOfOffset(int offset) - throws BadLocationException - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#getNumberOfLines() - */ - public int getNumberOfLines() - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#getNumberOfLines(int, int) - */ - public int getNumberOfLines(int offset, int length) - throws BadLocationException - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#computeNumberOfLines(java.lang.String) - */ - public int computeNumberOfLines(String text) - { - throw new UnsupportedOperationException("Not implemented!"); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#getLegalLineDelimiters() - */ -// public String[] getLegalLineDelimiters() -// { -// throw new UnsupportedOperationException("Not implemented!"); -// } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#getLineDelimiter(int) - */ -// public String getLineDelimiter(int line) throws BadLocationException -// { -// throw new UnsupportedOperationException("Not implemented!"); -// } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#search(int, java.lang.String, boolean, boolean, boolean) - */ - public int search( - int startOffset, - String findString, - boolean forwardSearch, - boolean caseSensitive, - boolean wholeWord) - throws BadLocationException - { - throw new UnsupportedOperationException("Not implemented!"); - } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#getChar(int) + */ + public char getChar(int offset) throws BadLocationException { + if (offset >= 0 && offset < fTextBuffer.length) + return fTextBuffer[offset]; + else + throw new BadLocationException("Offset out of range!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#getLength() + */ + public int getLength() { + return fTextBuffer.length; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#get() + */ + public String get() { + return String.copyValueOf(fTextBuffer); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#get(int, int) + */ + public String get(int offset, int length) throws BadLocationException { + if (offset >= 0 && (offset + length) < fTextBuffer.length) + return String.copyValueOf(fTextBuffer, offset, length); + else + throw new BadLocationException("Out of range!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#set(java.lang.String) + */ + public void set(String text) { + fTextBuffer = text.toCharArray(); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#replace(int, int, java.lang.String) + */ + public void replace(int offset, int length, String text) + throws BadLocationException { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#addDocumentListener(org.eclipse.jface.text.IDocumentListener) + */ + public void addDocumentListener(IDocumentListener listener) { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#removeDocumentListener(org.eclipse.jface.text.IDocumentListener) + */ + public void removeDocumentListener(IDocumentListener listener) { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#addPrenotifiedDocumentListener(org.eclipse.jface.text.IDocumentListener) + */ + public void addPrenotifiedDocumentListener(IDocumentListener documentAdapter) { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#removePrenotifiedDocumentListener(org.eclipse.jface.text.IDocumentListener) + */ + public void removePrenotifiedDocumentListener( + IDocumentListener documentAdapter) { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#addPositionCategory(java.lang.String) + */ + // public void addPositionCategory(String category) + // { + // throw new UnsupportedOperationException("Not implemented!"); + // } + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#removePositionCategory(java.lang.String) + */ + public void removePositionCategory(String category) + throws BadPositionCategoryException { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#getPositionCategories() + */ + public String[] getPositionCategories() { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#containsPositionCategory(java.lang.String) + */ + // public boolean containsPositionCategory(String category) + // { + // throw new UnsupportedOperationException("Not implemented!"); + // } + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#addPosition(org.eclipse.jface.text.Position) + */ + public void addPosition(Position position) throws BadLocationException { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#removePosition(org.eclipse.jface.text.Position) + */ + public void removePosition(Position position) { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#addPosition(java.lang.String, + * org.eclipse.jface.text.Position) + */ + public void addPosition(String category, Position position) + throws BadLocationException, BadPositionCategoryException { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#removePosition(java.lang.String, + * org.eclipse.jface.text.Position) + */ + public void removePosition(String category, Position position) + throws BadPositionCategoryException { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#getPositions(java.lang.String) + */ + public Position[] getPositions(String category) + throws BadPositionCategoryException { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#containsPosition(java.lang.String, + * int, int) + */ + public boolean containsPosition(String category, int offset, int length) { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#computeIndexInCategory(java.lang.String, + * int) + */ + public int computeIndexInCategory(String category, int offset) + throws BadLocationException, BadPositionCategoryException { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#addPositionUpdater(org.eclipse.jface.text.IPositionUpdater) + */ + // public void addPositionUpdater(IPositionUpdater updater) + // { + // throw new UnsupportedOperationException("Not implemented!"); + // } + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#removePositionUpdater(org.eclipse.jface.text.IPositionUpdater) + */ + public void removePositionUpdater(IPositionUpdater updater) { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#insertPositionUpdater(org.eclipse.jface.text.IPositionUpdater, + * int) + */ + // public void insertPositionUpdater(IPositionUpdater updater, int index) + // { + // throw new UnsupportedOperationException("Not implemented!"); + // } + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#getPositionUpdaters() + */ + public IPositionUpdater[] getPositionUpdaters() { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#getLegalContentTypes() + */ + public String[] getLegalContentTypes() { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#getContentType(int) + */ + public String getContentType(int offset) throws BadLocationException { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#getPartition(int) + */ + public ITypedRegion getPartition(int offset) throws BadLocationException { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#computePartitioning(int, int) + */ + public ITypedRegion[] computePartitioning(int offset, int length) + throws BadLocationException { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#addDocumentPartitioningListener(org.eclipse.jface.text.IDocumentPartitioningListener) + */ + public void addDocumentPartitioningListener( + IDocumentPartitioningListener listener) { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#removeDocumentPartitioningListener(org.eclipse.jface.text.IDocumentPartitioningListener) + */ + public void removeDocumentPartitioningListener( + IDocumentPartitioningListener listener) { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#setDocumentPartitioner(org.eclipse.jface.text.IDocumentPartitioner) + */ + public void setDocumentPartitioner(IDocumentPartitioner partitioner) { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#getDocumentPartitioner() + */ + public IDocumentPartitioner getDocumentPartitioner() { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#getLineLength(int) + */ + public int getLineLength(int line) throws BadLocationException { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#getLineOfOffset(int) + */ + public int getLineOfOffset(int offset) throws BadLocationException { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#getLineOffset(int) + */ + public int getLineOffset(int line) throws BadLocationException { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#getLineInformation(int) + */ + public IRegion getLineInformation(int line) throws BadLocationException { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#getLineInformationOfOffset(int) + */ + public IRegion getLineInformationOfOffset(int offset) + throws BadLocationException { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#getNumberOfLines() + */ + public int getNumberOfLines() { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#getNumberOfLines(int, int) + */ + public int getNumberOfLines(int offset, int length) + throws BadLocationException { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#computeNumberOfLines(java.lang.String) + */ + public int computeNumberOfLines(String text) { + throw new UnsupportedOperationException("Not implemented!"); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#getLegalLineDelimiters() + */ + // public String[] getLegalLineDelimiters() + // { + // throw new UnsupportedOperationException("Not implemented!"); + // } + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#getLineDelimiter(int) + */ + // public String getLineDelimiter(int line) throws BadLocationException + // { + // throw new UnsupportedOperationException("Not implemented!"); + // } + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#search(int, java.lang.String, + * boolean, boolean, boolean) + */ + public int search(int startOffset, String findString, + boolean forwardSearch, boolean caseSensitive, boolean wholeWord) + throws BadLocationException { + throw new UnsupportedOperationException("Not implemented!"); + } } diff --git a/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/phpeditor/php/test/IdentifierIndexManagerTest.java b/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/phpeditor/php/test/IdentifierIndexManagerTest.java index f3969a7..ec1fe7b 100644 --- a/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/phpeditor/php/test/IdentifierIndexManagerTest.java +++ b/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/phpeditor/php/test/IdentifierIndexManagerTest.java @@ -8,42 +8,47 @@ package net.sourceforge.phpeclipse.phpeditor.php.test; import java.io.StringBufferInputStream; -import org.eclipse.core.runtime.CoreException; - import junit.framework.TestCase; import net.sourceforge.phpeclipse.builder.IdentifierIndexManager; +import org.eclipse.core.runtime.CoreException; + /** * */ public class IdentifierIndexManagerTest extends TestCase { - IdentifierIndexManager fManager; - - public void testManager() { - System.out.println("----- testManager -----"); - String testString = "]*script*\\\"?[^>]*>\", $secvalue)) ||\r\n" + - " (eregi(\"<[^>]*object*\\\"?[^>]*>\", $secvalue)) ||\r\n" + - " (eregi(\"<[^>]*iframe*\\\"?[^>]*>\", $secvalue)) ||\r\n" + - " (eregi(\"<[^>]*applet*\\\"?[^>]*>\", $secvalue)) ||\r\n" + - " (eregi(\"<[^>]*meta*\\\"?[^>]*>\", $secvalue)) ||\r\n" + - " (eregi(\"<[^>]*style*\\\"?[^>]*>\", $secvalue)) ||\r\n" + - " (eregi(\"<[^>]*form*\\\"?[^>]*>\", $secvalue)) ||\r\n" + - " (eregi(\"\\([^>]*\\\"?[^)]*\\)\", $secvalue)) ||\r\n" + - " (eregi(\"\\\"\", $secvalue))) {\r\n" + - " die (\"


    The html tags you attempted to use are not allowed

    [ Go Back ]\");\r\n" + - " } ?>"; - IdentifierIndexManager.LineCreator lineCreator = fManager.createLineCreator(); - try { - fManager.addInputStream(new StringBufferInputStream(testString), "test", lineCreator); - } catch (CoreException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - /* (non-Javadoc) - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception { - fManager = new IdentifierIndexManager("c:\\temp\\test"); - } + IdentifierIndexManager fManager; + + public void testManager() { + System.out.println("----- testManager -----"); + String testString = "]*script*\\\"?[^>]*>\", $secvalue)) ||\r\n" + + " (eregi(\"<[^>]*object*\\\"?[^>]*>\", $secvalue)) ||\r\n" + + " (eregi(\"<[^>]*iframe*\\\"?[^>]*>\", $secvalue)) ||\r\n" + + " (eregi(\"<[^>]*applet*\\\"?[^>]*>\", $secvalue)) ||\r\n" + + " (eregi(\"<[^>]*meta*\\\"?[^>]*>\", $secvalue)) ||\r\n" + + " (eregi(\"<[^>]*style*\\\"?[^>]*>\", $secvalue)) ||\r\n" + + " (eregi(\"<[^>]*form*\\\"?[^>]*>\", $secvalue)) ||\r\n" + + " (eregi(\"\\([^>]*\\\"?[^)]*\\)\", $secvalue)) ||\r\n" + + " (eregi(\"\\\"\", $secvalue))) {\r\n" + + " die (\"


    The html tags you attempted to use are not allowed

    [ Go Back ]\");\r\n" + + " } ?>"; + IdentifierIndexManager.LineCreator lineCreator = fManager + .createLineCreator(); + try { + fManager.addInputStream(new StringBufferInputStream(testString), + "test", lineCreator); + } catch (CoreException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + /* + * (non-Javadoc) + * + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + fManager = new IdentifierIndexManager("c:\\temp\\test"); + } } diff --git a/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/phpeditor/php/test/PHPFormatterTest.java b/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/phpeditor/php/test/PHPFormatterTest.java index c13f010..a6915be 100644 --- a/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/phpeditor/php/test/PHPFormatterTest.java +++ b/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/phpeditor/php/test/PHPFormatterTest.java @@ -19,7 +19,7 @@ import org.eclipse.jface.text.IDocument; * Testcase for the PHP CodeFormatter * * @author Stefan Langer - * @version $Revision: 1.6 $ + * @version $Revision: 1.7 $ */ public class PHPFormatterTest extends TestCase { private CodeFormatter fFormatter; @@ -136,7 +136,7 @@ public class PHPFormatterTest extends TestCase { + lineDelimiter + ");" + lineDelimiter + "?>"; junit.framework.Assert.assertEquals(formatedString, testResult); } - + public void testDoubleArrayFormatting() throws Exception { System.out.println("-----testDoubleArrayFormatting-----"); String text = " 'ok'," + lineDelimiter - + "\t'snd' => array (" + lineDelimiter - + "\t\t'1' => '11'," + lineDelimiter - + "\t\t'2' => '22'" + lineDelimiter - + "\t)," + lineDelimiter - + "\t'3th' => 'super'" + lineDelimiter - + ");" + lineDelimiter - + "?>"; + String testResult = " 'ok'," + lineDelimiter + + "\t'snd' => array (" + lineDelimiter + "\t\t'1' => '11'," + + lineDelimiter + "\t\t'2' => '22'" + lineDelimiter + "\t)," + + lineDelimiter + "\t'3th' => 'super'" + lineDelimiter + ");" + + lineDelimiter + "?>"; junit.framework.Assert.assertEquals(formatedString, testResult); } - - + } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/tests/parser/OverlibTestCase.java b/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/tests/parser/OverlibTestCase.java index 54011e6..f6278a2 100644 --- a/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/tests/parser/OverlibTestCase.java +++ b/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/tests/parser/OverlibTestCase.java @@ -1,4 +1,5 @@ package net.sourceforge.phpeclipse.tests.parser; + /******************************************************************************* * Copyright (c) 2002 www.phpeclipse.de All rights * reserved. This program and the accompanying materials are made available @@ -6,475 +7,463 @@ package net.sourceforge.phpeclipse.tests.parser; * distribution, and is available at http://www.eclipse.org/legal/cpl-v10.html ******************************************************************************/ import net.sourceforge.phpdt.core.tests.util.AbstractCompilerTest; -import net.sourceforge.phpdt.internal.compiler.parser.Scanner; + /** * Tests the php parser */ public class OverlibTestCase extends AbstractCompilerTest { -// Parser parser; - public OverlibTestCase(String name) { - super(name); - } - /** - * Test the PHP Parser with different PHP snippets - */ - public void testPHPParser() { - checkPHP( - "\r\n" + - " /*\r\n" + - "\r\n" + - " This is version 1.11 of class.overlib for php (http://www.php.net) \r\n" + - "\r\n" + - " written 1999, 2000, 2001 Patrick Hess \r\n" + - "\r\n" + - " This software is distributed under GPL.\r\n" + - " \r\n" + - " overLib is from Eric Bosrup (http://www.bosrup.com/web/overlib/)\r\n" + - "\r\n" + - " This class is just a driver/container, so most of this wonderful\r\n" + - " \r\n" + - " work is done by Eric Bosrup! Keep this in mind... \r\n" + - " \r\n" + - " */\r\n" + - "\r\n" + - "include(\"hello_world\"); \r\n" + - "function foo() {" + - "} \r\n" + - "\r\n" + - " class Overlib {\r\n" + - "\r\n" + - " public $ol_path = \"modules/Forums\";\r\n" + - "\r\n" + - " public $ol_sticky = false;\r\n" + - "\r\n" + - " public $ol_align = 0;\r\n" + - "\r\n" + - " public $ol_valign = 0;\r\n" + - "\r\n" + - " public $ol_fgcolor = \"#fcfcfc\";\r\n" + - "\r\n" + - " public $ol_bgcolor = \"#0080C0\";\r\n" + - "\r\n" + - " public $ol_capcolor = \"#ffffff\";\r\n" + - "\r\n" + - " public $ol_textcolor = \"\";\r\n" + - "\r\n" + - " public $ol_closecolor = \"\";\r\n" + - "\r\n" + - " public $ol_textfont = \"\";\r\n" + - "\r\n" + - " public $ol_captionfont = \"\";\r\n" + - "\r\n" + - " public $ol_closefont = \"\";\r\n" + - "\r\n" + - " public $ol_textsize = 0;\r\n" + - "\r\n" + - " public $ol_captionsize = 0;\r\n" + - "\r\n" + - " public $ol_closesize = 0;\r\n" + - "\r\n" + - " public $ol_height = 0;\r\n" + - "\r\n" + - " public $ol_width = 0;\r\n" + - "\r\n" + - " public $ol_border = 3;\r\n" + - "\r\n" + - " public $ol_offsetx = 0;\r\n" + - "\r\n" + - " public $ol_offsety = 0;\r\n" + - "\r\n" + - " public $ol_fgbackground = \"\";\r\n" + - "\r\n" + - " public $ol_bgbackground = \"\";\r\n" + - "\r\n" + - " public $ol_closetext = \"Close\";\r\n" + - "\r\n" + - " public $ol_close = true;\r\n" + - "\r\n" + - " public $ol_noclosetext = false;\r\n" + - "\r\n" + - " public $ol_autostatus = false;\r\n" + - "\r\n" + - " public $ol_autostatuscap = false;\r\n" + - "\r\n" + - " public $ol_capicon = \"images/forum/question.gif\";\r\n" + - "\r\n" + - " public $ol_snapx = 0;\r\n" + - "\r\n" + - " public $ol_snapy = 0;\r\n" + - "\r\n" + - " public $ol_padxl = 0;\r\n" + - "\r\n" + - " public $ol_padxr = 0;\r\n" + - "\r\n" + - " public $ol_padyt = 0;\r\n" + - "\r\n" + - " public $ol_padyb = 0;\r\n" + - "\r\n" + - " public $ol_fixy = 0;\r\n" + - "\r\n" + - " public $ol_background = \"\";\r\n" + - "\r\n" + - " public $ol_fullhtml = false;\r\n" + - "\r\n" + - " public $ol_timeout = -1;\r\n" + - "\r\n" + - " public $ol_delay = -1;\r\n" + - "\r\n" + - " public $ol_vauto = false;\r\n" + - "\r\n" + - " public $ol_hauto = false;\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " function overLib($path = \"\") {\r\n" + - "\r\n" + - " if (strlen($path)) $this->ol_path = $path;\r\n" + - "\r\n" + - "?>\r\n" + - "\r\n" + - "ol_path/overlib.css\' \"; ?> \r\n" + - "\r\n" + - " type=\'text/css\'>\r\n" + - "\r\n" + - "
    \r\n" + - "\r\n" + - "
    \r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - "$v = $value;\r\n" + - "\r\n" + - " }\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " function get($var) {\r\n" + - "\r\n" + - " $v = \"ol_$var\";\r\n" + - "\r\n" + - " return($this->$v);\r\n" + - "\r\n" + - " }\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " function over($text, $title = \"\", $status = \"\")\r\n" + - "\r\n" + - " {\r\n" + - "\r\n" + - " $cmd = \"\'$text\'\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if(strlen($title)) \r\n" + - "\r\n" + - " $cmd .= \", CAPTION, \'$title\'\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if(strlen($status)) \r\n" + - "\r\n" + - " $cmd .= \", STATUS, \'$status\'\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if($this->ol_sticky) \r\n" + - "\r\n" + - " $cmd .= \", STICKY\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if($this->ol_align) {\r\n" + - "\r\n" + - " switch($this->ol_align) {\r\n" + - "\r\n" + - " case 1: $cmd .= \", LEFT\"; break;\r\n" + - "\r\n" + - " case 2: $cmd .= \", CENTER\"; break;\r\n" + - "\r\n" + - " case 3: $cmd .= \", RIGHT\"; break;\r\n" + - "\r\n" + - " default: break;\r\n" + - "\r\n" + - " }\r\n" + - "\r\n" + - " }\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if($this->ol_valign) {\r\n" + - "\r\n" + - " switch($this->ol_valign) {\r\n" + - "\r\n" + - " case 1: $cmd .= \", ABOVE\"; break;\r\n" + - "\r\n" + - " case 2: $cmd .= \", BELOW\"; break;\r\n" + - "\r\n" + - " default: break;\r\n" + - "\r\n" + - " }\r\n" + - "\r\n" + - " }\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if (strlen($this->ol_fgbackground)) {\r\n" + - "\r\n" + - " $cmd .= \", FGCOLOR, \'\', FGBACKGROUND, \'$this->ol_fgbackground\'\";\r\n" + - "\r\n" + - " } else {\r\n" + - "\r\n" + - " if (strlen($this->ol_fgcolor))\r\n" + - "\r\n" + - " $cmd .= \", FGCOLOR, \'$this->ol_fgcolor\'\";\r\n" + - "\r\n" + - " }\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if (strlen($this->ol_bgbackground)) {\r\n" + - "\r\n" + - " $cmd .= \", BGCOLOR, \'\', BGBACKGROUND, \'$this->ol_bgbackground\'\";\r\n" + - "\r\n" + - " } else {\r\n" + - "\r\n" + - " if (strlen($this->ol_bgcolor))\r\n" + - "\r\n" + - " $cmd .= \", BGCOLOR, \'$this->ol_bgcolor\'\";\r\n" + - "\r\n" + - " }\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if (strlen($this->ol_capcolor))\r\n" + - "\r\n" + - " $cmd .= \", CAPCOLOR, \'$this->ol_capcolor\'\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if (strlen($this->ol_textcolor))\r\n" + - "\r\n" + - " $cmd .= \", TEXTCOLOR, \'$this->ol_textcolor\'\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if (strlen($this->ol_closecolor))\r\n" + - "\r\n" + - " $cmd .= \", CLOSECOLOR, \'$this->ol_closecolor\'\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if (strlen($this->ol_textfont))\r\n" + - "\r\n" + - " $cmd .= \", TEXTFONT, \'$this->ol_textfont\'\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if (strlen($this->ol_captionfont))\r\n" + - "\r\n" + - " $cmd .= \", CAPTIONFONT, \'$this->ol_captionfont\'\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if (strlen($this->ol_closefont))\r\n" + - "\r\n" + - " $cmd .= \", CLOSEFONT, \'$this->ol_closefont\'\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if ($this->ol_textsize)\r\n" + - "\r\n" + - " $cmd .= \", TEXTSIZE, $this->ol_textsize\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if ($this->ol_captionsize)\r\n" + - "\r\n" + - " $cmd .= \", CAPTIONSIZE, $this->ol_captionsize\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if ($this->ol_closesize)\r\n" + - "\r\n" + - " $cmd .= \", CLOSESIZE, $this->ol_closesize\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if ($this->ol_width)\r\n" + - "\r\n" + - " $cmd .= \", WIDTH, $this->ol_width\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if ($this->ol_height)\r\n" + - "\r\n" + - " $cmd .= \", HEIGHT, $this->ol_height\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if ($this->ol_border >= 0)\r\n" + - "\r\n" + - " $cmd .= \", BORDER, $this->ol_border\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if ($this->ol_offsetx)\r\n" + - "\r\n" + - " $cmd .= \", OFFSETX, $this->ol_offsetx\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if ($this->ol_offsety)\r\n" + - "\r\n" + - " $cmd .= \", OFFSETY, $this->ol_offsety\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if (strlen($this->ol_closetext))\r\n" + - "\r\n" + - " $cmd .= \", CLOSETEXT, \'$this->ol_closetext\'\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if ($this->ol_noclose)\r\n" + - "\r\n" + - " $cmd .= \", NOCLOSETEXT\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if ($this->ol_autostatus)\r\n" + - "\r\n" + - " $cmd .= \", AUTOSTATUS\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if ($this->ol_autostatuscap)\r\n" + - "\r\n" + - " $cmd .= \", AUTOSTATUSCAP\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if (strlen($this->ol_capicon))\r\n" + - "\r\n" + - " $cmd .= \", CAPICON, \'$this->ol_capicon\'\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if ($this->ol_snapx)\r\n" + - "\r\n" + - " $cmd .= \", SNAPX, $this->ol_snapx\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if ($this->ol_snapy)\r\n" + - "\r\n" + - " $cmd .= \", SNAPY, $this->ol_snapy\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if ($this->ol_fixy)\r\n" + - "\r\n" + - " $cmd .= \", FIXY, $this->ol_fixy\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if ($this->ol_padxl || $this->ol_padxr)\r\n" + - "\r\n" + - " $cmd .= \", PADX, $this->ol_padxl, $this->ol_padxr\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if ($this->ol_padyt || $this->ol_padyb)\r\n" + - "\r\n" + - " $cmd .= \", PADY, $this->ol_padyt, $this->ol_padyb\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if (strlen($this->ol_background))\r\n" + - "\r\n" + - " $cmd .= \", BACKGROUND, \'$this->ol_background\'\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if ($this->ol_fullhtml)\r\n" + - "\r\n" + - " $cmd .= \", FULLHTML\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if ($this->ol_timeout >= 0)\r\n" + - "\r\n" + - " $cmd .= \", TIMEOUT, $this->ol_timeout\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if ($this->ol_delay >= 0)\r\n" + - "\r\n" + - " $cmd .= \", DELAY, $this->ol_delay\";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if ($this->ol_hauto) {\r\n" + - "\r\n" + - " $cmd .= \", HAUTO\";\r\n" + - "\r\n" + - " $this->ol_hauto = false;\r\n" + - "\r\n" + - " }\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " if ($this->ol_vauto) {\r\n" + - "\r\n" + - " $cmd .= \", VAUTO\";\r\n" + - "\r\n" + - " $this->ol_hauto = false;\r\n" + - "\r\n" + - " }\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " $output=\" onMouseOver=\\\"return overlib($cmd);\\\" \";\r\n" + - "\r\n" + - " $output.=\" onMouseOut=\\\"nd();\\\" \";\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " return ($output);\r\n" + - "\r\n" + - " }\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " function pover ($text, $title = \"\", $status = \"\") \r\n" + - "\r\n" + - " {\r\n" + - "\r\n" + - " echo $this->over($text, $title, $status);\r\n" + - "\r\n" + - " }\r\n" + - "\r\n" + - " }\r\n" + - "\r\n" + - "?>\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - ""); - } + // Parser parser; + public OverlibTestCase(String name) { + super(name); + } + + /** + * Test the PHP Parser with different PHP snippets + */ + public void testPHPParser() { + checkPHP("\r\n" + + " /*\r\n" + + "\r\n" + + " This is version 1.11 of class.overlib for php (http://www.php.net) \r\n" + + "\r\n" + + " written 1999, 2000, 2001 Patrick Hess \r\n" + + "\r\n" + + " This software is distributed under GPL.\r\n" + + " \r\n" + + " overLib is from Eric Bosrup (http://www.bosrup.com/web/overlib/)\r\n" + + "\r\n" + + " This class is just a driver/container, so most of this wonderful\r\n" + + " \r\n" + + " work is done by Eric Bosrup! Keep this in mind... \r\n" + + " \r\n" + + " */\r\n" + + "\r\n" + + "include(\"hello_world\"); \r\n" + + "function foo() {" + + "} \r\n" + + "\r\n" + + " class Overlib {\r\n" + + "\r\n" + + " public $ol_path = \"modules/Forums\";\r\n" + + "\r\n" + + " public $ol_sticky = false;\r\n" + + "\r\n" + + " public $ol_align = 0;\r\n" + + "\r\n" + + " public $ol_valign = 0;\r\n" + + "\r\n" + + " public $ol_fgcolor = \"#fcfcfc\";\r\n" + + "\r\n" + + " public $ol_bgcolor = \"#0080C0\";\r\n" + + "\r\n" + + " public $ol_capcolor = \"#ffffff\";\r\n" + + "\r\n" + + " public $ol_textcolor = \"\";\r\n" + + "\r\n" + + " public $ol_closecolor = \"\";\r\n" + + "\r\n" + + " public $ol_textfont = \"\";\r\n" + + "\r\n" + + " public $ol_captionfont = \"\";\r\n" + + "\r\n" + + " public $ol_closefont = \"\";\r\n" + + "\r\n" + + " public $ol_textsize = 0;\r\n" + + "\r\n" + + " public $ol_captionsize = 0;\r\n" + + "\r\n" + + " public $ol_closesize = 0;\r\n" + + "\r\n" + + " public $ol_height = 0;\r\n" + + "\r\n" + + " public $ol_width = 0;\r\n" + + "\r\n" + + " public $ol_border = 3;\r\n" + + "\r\n" + + " public $ol_offsetx = 0;\r\n" + + "\r\n" + + " public $ol_offsety = 0;\r\n" + + "\r\n" + + " public $ol_fgbackground = \"\";\r\n" + + "\r\n" + + " public $ol_bgbackground = \"\";\r\n" + + "\r\n" + + " public $ol_closetext = \"Close\";\r\n" + + "\r\n" + + " public $ol_close = true;\r\n" + + "\r\n" + + " public $ol_noclosetext = false;\r\n" + + "\r\n" + + " public $ol_autostatus = false;\r\n" + + "\r\n" + + " public $ol_autostatuscap = false;\r\n" + + "\r\n" + + " public $ol_capicon = \"images/forum/question.gif\";\r\n" + + "\r\n" + + " public $ol_snapx = 0;\r\n" + + "\r\n" + + " public $ol_snapy = 0;\r\n" + + "\r\n" + + " public $ol_padxl = 0;\r\n" + + "\r\n" + + " public $ol_padxr = 0;\r\n" + + "\r\n" + + " public $ol_padyt = 0;\r\n" + + "\r\n" + + " public $ol_padyb = 0;\r\n" + + "\r\n" + + " public $ol_fixy = 0;\r\n" + + "\r\n" + + " public $ol_background = \"\";\r\n" + + "\r\n" + + " public $ol_fullhtml = false;\r\n" + + "\r\n" + + " public $ol_timeout = -1;\r\n" + + "\r\n" + + " public $ol_delay = -1;\r\n" + + "\r\n" + + " public $ol_vauto = false;\r\n" + + "\r\n" + + " public $ol_hauto = false;\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " function overLib($path = \"\") {\r\n" + + "\r\n" + + " if (strlen($path)) $this->ol_path = $path;\r\n" + + "\r\n" + + "?>\r\n" + + "\r\n" + + "ol_path/overlib.css\' \"; ?> \r\n" + + "\r\n" + + " type=\'text/css\'>\r\n" + + "\r\n" + + "
    \r\n" + + "\r\n" + + "
    \r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + "$v = $value;\r\n" + + "\r\n" + + " }\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " function get($var) {\r\n" + + "\r\n" + + " $v = \"ol_$var\";\r\n" + + "\r\n" + + " return($this->$v);\r\n" + + "\r\n" + + " }\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " function over($text, $title = \"\", $status = \"\")\r\n" + + "\r\n" + + " {\r\n" + + "\r\n" + + " $cmd = \"\'$text\'\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if(strlen($title)) \r\n" + + "\r\n" + + " $cmd .= \", CAPTION, \'$title\'\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if(strlen($status)) \r\n" + + "\r\n" + + " $cmd .= \", STATUS, \'$status\'\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if($this->ol_sticky) \r\n" + + "\r\n" + + " $cmd .= \", STICKY\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if($this->ol_align) {\r\n" + + "\r\n" + + " switch($this->ol_align) {\r\n" + + "\r\n" + + " case 1: $cmd .= \", LEFT\"; break;\r\n" + + "\r\n" + + " case 2: $cmd .= \", CENTER\"; break;\r\n" + + "\r\n" + + " case 3: $cmd .= \", RIGHT\"; break;\r\n" + + "\r\n" + + " default: break;\r\n" + + "\r\n" + + " }\r\n" + + "\r\n" + + " }\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if($this->ol_valign) {\r\n" + + "\r\n" + + " switch($this->ol_valign) {\r\n" + + "\r\n" + + " case 1: $cmd .= \", ABOVE\"; break;\r\n" + + "\r\n" + + " case 2: $cmd .= \", BELOW\"; break;\r\n" + + "\r\n" + + " default: break;\r\n" + + "\r\n" + + " }\r\n" + + "\r\n" + + " }\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if (strlen($this->ol_fgbackground)) {\r\n" + + "\r\n" + + " $cmd .= \", FGCOLOR, \'\', FGBACKGROUND, \'$this->ol_fgbackground\'\";\r\n" + + "\r\n" + + " } else {\r\n" + + "\r\n" + + " if (strlen($this->ol_fgcolor))\r\n" + + "\r\n" + + " $cmd .= \", FGCOLOR, \'$this->ol_fgcolor\'\";\r\n" + + "\r\n" + + " }\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if (strlen($this->ol_bgbackground)) {\r\n" + + "\r\n" + + " $cmd .= \", BGCOLOR, \'\', BGBACKGROUND, \'$this->ol_bgbackground\'\";\r\n" + + "\r\n" + + " } else {\r\n" + + "\r\n" + + " if (strlen($this->ol_bgcolor))\r\n" + + "\r\n" + + " $cmd .= \", BGCOLOR, \'$this->ol_bgcolor\'\";\r\n" + + "\r\n" + + " }\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if (strlen($this->ol_capcolor))\r\n" + + "\r\n" + + " $cmd .= \", CAPCOLOR, \'$this->ol_capcolor\'\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if (strlen($this->ol_textcolor))\r\n" + + "\r\n" + + " $cmd .= \", TEXTCOLOR, \'$this->ol_textcolor\'\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if (strlen($this->ol_closecolor))\r\n" + + "\r\n" + + " $cmd .= \", CLOSECOLOR, \'$this->ol_closecolor\'\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if (strlen($this->ol_textfont))\r\n" + + "\r\n" + + " $cmd .= \", TEXTFONT, \'$this->ol_textfont\'\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if (strlen($this->ol_captionfont))\r\n" + + "\r\n" + + " $cmd .= \", CAPTIONFONT, \'$this->ol_captionfont\'\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if (strlen($this->ol_closefont))\r\n" + + "\r\n" + + " $cmd .= \", CLOSEFONT, \'$this->ol_closefont\'\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if ($this->ol_textsize)\r\n" + + "\r\n" + + " $cmd .= \", TEXTSIZE, $this->ol_textsize\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if ($this->ol_captionsize)\r\n" + + "\r\n" + + " $cmd .= \", CAPTIONSIZE, $this->ol_captionsize\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if ($this->ol_closesize)\r\n" + + "\r\n" + + " $cmd .= \", CLOSESIZE, $this->ol_closesize\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if ($this->ol_width)\r\n" + + "\r\n" + + " $cmd .= \", WIDTH, $this->ol_width\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if ($this->ol_height)\r\n" + + "\r\n" + + " $cmd .= \", HEIGHT, $this->ol_height\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if ($this->ol_border >= 0)\r\n" + + "\r\n" + + " $cmd .= \", BORDER, $this->ol_border\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if ($this->ol_offsetx)\r\n" + + "\r\n" + + " $cmd .= \", OFFSETX, $this->ol_offsetx\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if ($this->ol_offsety)\r\n" + + "\r\n" + + " $cmd .= \", OFFSETY, $this->ol_offsety\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if (strlen($this->ol_closetext))\r\n" + + "\r\n" + + " $cmd .= \", CLOSETEXT, \'$this->ol_closetext\'\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if ($this->ol_noclose)\r\n" + + "\r\n" + + " $cmd .= \", NOCLOSETEXT\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if ($this->ol_autostatus)\r\n" + + "\r\n" + + " $cmd .= \", AUTOSTATUS\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if ($this->ol_autostatuscap)\r\n" + + "\r\n" + + " $cmd .= \", AUTOSTATUSCAP\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if (strlen($this->ol_capicon))\r\n" + + "\r\n" + + " $cmd .= \", CAPICON, \'$this->ol_capicon\'\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if ($this->ol_snapx)\r\n" + + "\r\n" + + " $cmd .= \", SNAPX, $this->ol_snapx\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if ($this->ol_snapy)\r\n" + + "\r\n" + + " $cmd .= \", SNAPY, $this->ol_snapy\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if ($this->ol_fixy)\r\n" + + "\r\n" + + " $cmd .= \", FIXY, $this->ol_fixy\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if ($this->ol_padxl || $this->ol_padxr)\r\n" + + "\r\n" + + " $cmd .= \", PADX, $this->ol_padxl, $this->ol_padxr\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if ($this->ol_padyt || $this->ol_padyb)\r\n" + + "\r\n" + + " $cmd .= \", PADY, $this->ol_padyt, $this->ol_padyb\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if (strlen($this->ol_background))\r\n" + + "\r\n" + + " $cmd .= \", BACKGROUND, \'$this->ol_background\'\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if ($this->ol_fullhtml)\r\n" + + "\r\n" + + " $cmd .= \", FULLHTML\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if ($this->ol_timeout >= 0)\r\n" + + "\r\n" + + " $cmd .= \", TIMEOUT, $this->ol_timeout\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if ($this->ol_delay >= 0)\r\n" + + "\r\n" + + " $cmd .= \", DELAY, $this->ol_delay\";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if ($this->ol_hauto) {\r\n" + + "\r\n" + + " $cmd .= \", HAUTO\";\r\n" + + "\r\n" + + " $this->ol_hauto = false;\r\n" + + "\r\n" + + " }\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " if ($this->ol_vauto) {\r\n" + + "\r\n" + + " $cmd .= \", VAUTO\";\r\n" + + "\r\n" + + " $this->ol_hauto = false;\r\n" + + "\r\n" + + " }\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " $output=\" onMouseOver=\\\"return overlib($cmd);\\\" \";\r\n" + + "\r\n" + + " $output.=\" onMouseOut=\\\"nd();\\\" \";\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " return ($output);\r\n" + + "\r\n" + + " }\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + " function pover ($text, $title = \"\", $status = \"\") \r\n" + + "\r\n" + " {\r\n" + "\r\n" + + " echo $this->over($text, $title, $status);\r\n" + "\r\n" + + " }\r\n" + "\r\n" + " }\r\n" + "\r\n" + "?>\r\n" + "\r\n" + + "\r\n" + "\r\n" + "\r\n" + "\r\n" + ""); + } } diff --git a/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/tests/parser/PHPManualTestCase.java b/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/tests/parser/PHPManualTestCase.java index 3dd624b..4233c80 100644 --- a/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/tests/parser/PHPManualTestCase.java +++ b/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/tests/parser/PHPManualTestCase.java @@ -1,4 +1,5 @@ package net.sourceforge.phpeclipse.tests.parser; + /******************************************************************************* * Copyright (c) 2002 www.phpeclipse.de All rights * reserved. This program and the accompanying materials are made available @@ -6,211 +7,238 @@ package net.sourceforge.phpeclipse.tests.parser; * distribution, and is available at http://www.eclipse.org/legal/cpl-v10.html ******************************************************************************/ import net.sourceforge.phpdt.core.tests.util.AbstractCompilerTest; -import net.sourceforge.phpdt.internal.compiler.parser.Scanner; + /** * Tests the php parser */ public class PHPManualTestCase extends AbstractCompilerTest { -// Parser parser; - public PHPManualTestCase(String name) { - super(name); - } - /** - * Test the PHP Parser with different PHP snippets - */ - public void testPHPParser() { - checkPHP("self::$instance = new Singleton();"); - checkPHP("if ((eregi(\"<[^>]*script*\\\"?[^>]*>\", $secvalue)) ||\r\n" + - " (eregi(\"<[^>]*object*\\\"?[^>]*>\", $secvalue)) ||\r\n" + - " (eregi(\"<[^>]*iframe*\\\"?[^>]*>\", $secvalue)) ||\r\n" + - " (eregi(\"<[^>]*applet*\\\"?[^>]*>\", $secvalue)) ||\r\n" + - " (eregi(\"<[^>]*meta*\\\"?[^>]*>\", $secvalue)) ||\r\n" + - " (eregi(\"<[^>]*style*\\\"?[^>]*>\", $secvalue)) ||\r\n" + - " (eregi(\"<[^>]*form*\\\"?[^>]*>\", $secvalue)) ||\r\n" + - " (eregi(\"\\([^>]*\\\"?[^)]*\\)\", $secvalue)) ||\r\n" + - " (eregi(\"\\\"\", $secvalue))) {\r\n" + - " die (\"


    The html tags you attempted to use are not allowed

    [ Go Back ]\");\r\n" + - " }"); - checkPHP("function foo()" + "{" + " echo \"In foo()
    \\n\";" + "}" - + "" + "function bar($arg = '')" + "{" - + " echo \"In bar(); argument was '$arg'.
    \\n\";" + "}" + "" - + "// This is a wrapper function around echo" - + "function echoit($string)" + "{" + " echo $string;" + "}" + "" - + "$func = 'foo';" + "$func(); // This calls foo()" + "" - + "$func = 'bar';" + "$func('test'); // This calls bar()" + "" - + "$func = 'echoit';" + "$func('test'); // This calls echoit()" + ""); - checkPHP("class Foo" + "{" + " function Vari()" + " {" - + " $name = 'Bar';" - + " $this->$name(); // This calls the Bar() method\n" + " }" - + " " + " function Bar()" + " {" - + " echo \"This is Bar\";" + " }" + "}" + "" - + "$foo = new Foo();" + "$funcname = \"Var\";" - + "$foo->$varname(); // This calls $foo->Var()\n" + ""); - checkPHP("function square ($num)" + "{" + " return $num * $num;" + "}" - + "echo square (4); // outputs '16'." + ""); - checkPHP("function small_numbers()" + "{" + " return array (0, 1, 2);" - + "}" + "list ($zero, $one, $two) = small_numbers();" + ""); - checkPHP("function &returns_reference()" + "{" + " return $someref;" - + "}" + "" + "$newref =& returns_reference();" + " " + ""); - checkPHP("function add_some_extra(&$string)" + "{" - + " $string .= 'and something extra.';" + "}" - + "$str = 'This is a string, ';" + "add_some_extra($str);" - + "echo $str; "); - checkPHP("function makecoffee ($type = \"cappuccino\")\n" + "{\n" - + " return \"Making a cup of $type.\\n\";\n" + "}" - + "echo makecoffee ();" + "echo makecoffee (\"espresso\");" + ""); - checkPHP("$makefoo = true;" + "" + "/* We can't call foo() from here " - + " since it doesn't exist yet," + " but we can call bar() */" + "" - + "bar();" + "" + "if ($makefoo) {" + " function foo ()" + " {" - + " echo \"I don't exist until program execution reaches me.\\n\";" - + " }" + "}" + "" + "/* Now we can safely call foo()" - + " since $makefoo evaluated to true */" + "" - + "if ($makefoo) foo();" + "" + "function bar() " + "{" - + " echo \"I exist immediately upon program start.\\n\";" + "}" + "" - + ""); - checkPHP("function foo() " + "{" + " function bar() " + " {" - + " echo \"I don't exist until foo() is called.\\n\";" + " }" + "}" - + "" + "/* We can't call bar() yet" + " since it doesn't exist. */" - + "" + "foo();\n" + "" + "/* Now we can call bar()," - + " foo()'s processesing has" + " made it accessable. */" + "" - + "bar();" + ""); - // Bugs item #690938 - checkPHP(" echo \"This is a test\"; // This is a one-line c++ style comment\n" - + " /* This is a multi line comment\n" - + " yet another line of comment */\n" - + " echo \"This is yet another test\";\n" - + " echo \"One Final Test\"; # This is shell-style style comment \n"); - checkPHP("$bool = TRUE; // a boolean\n" - + "$str = \"foo\"; // a string\n" + "$int = 12; // an integer\n" - + "\n" + "echo gettype($bool); // prints out \"boolean\"\n" - + "echo gettype($str); // prints out \"string\"\n" + "" - + "// If this is an integer, increment it by four\n" - + "if (is_int($int)) {\n" + " $int += 4;\n" + "}\n" + "\n" - + "// If $bool is a string, print it out\n" - + "// (does not print out anything)\n" + "if (is_string($bool)) {\n" - + " echo \"String: $bool\";\n" + "}\n"); - checkPHP("$foo = True; // assign the value TRUE to $foo"); - checkPHP("// == is an operator which test\n" - + "// equality and returns a boolean\n" - + "if ($action == \"show_version\") {\n" - + " echo \"The version is 1.23\";\n" + "}\n" + "\n" - + "// this is not necessary...\n" + "if ($show_separators == TRUE) {\n" - + " echo \"
    \\n\";\n" + "}\n" + "\n" - + "// ...because you can simply type\n" + "if ($show_separators) {\n" - + " echo \"
    \\n\";\n" + "}"); - checkPHP( // "echo gettype((bool) \"\"); // bool(false)\n" - "echo gettype((bool) 1); // bool(true)\n" - + "echo gettype((bool) -2); // bool(true)\n" - + "echo gettype((bool) \"foo\"); // bool(true)\n" - + "echo gettype((bool) 2.3e5); // bool(true)\n" - + "echo gettype((bool) array(12)); // bool(true)\n" - + "echo gettype((bool) array()); // bool(false)\n"); - checkPHP("$a = 1234; # decimal number\n" - + "$a = -123; # a negative number\n" - + "$a = 0123; # octal number (equivalent to 83 decimal)\n" - + "$a = 0x1A; # hexadecimal number (equivalent to 26 decimal)\n"); - checkPHP("$large_number = 2147483647;\n" + "var_dump($large_number);\n" - + "// output: int(2147483647)\n" + "\n" - + "$large_number = 2147483648;\n" + "var_dump($large_number);\n" - + "// output: float(2147483648)\n" + "" - + "// this goes also for hexadecimal specified integers:\n" - + "var_dump( 0x80000000 );\n" + "// output: float(2147483648)\n" + "\n" - + "$million = 1000000;\n" + "$large_number = 50000 * $million;\n" - + "var_dump($large_number);\n" + "// output: float(50000000000)\n"); - checkPHP("var_dump(25/7); // float(3.5714285714286)\n" - + "var_dump((int) (25/7)); // int(3)\n" - + "var_dump(round(25/7)); // float(4)"); - checkPHP("echo (int) ( (0.1+0.7) * 10 ); // echoes 7!"); - checkPHP("$a = 1.234; " + "$b = 1.2e3; " + "$c = 7E-10;"); - checkPHP("echo 'this is a simple string';\n" + "\n" - + "echo 'You can also have embedded newlines in \n" - + "strings this way as it is\n" + "okay to do';\n" + "\n" - + "// Outputs: \"I'll be back\"\n" - + "echo 'Arnold once said: \"I\\'ll be back\"';\n" + "\n" - + "// Outputs: You deleted C:\\*.*?\n" - + "echo 'You deleted C:\\\\*.*?';\n" + "\n" - + "// Outputs: You deleted C:\\*.*?\n" - + "echo 'You deleted C:\\\\*.*?';\n" + "\n" - + "// Outputs: This will not expand: \\n a newline\n" - + "echo 'This will not expand: \\n a newline';\n" + "\n" - + "// Outputs: Variables do not $expand $either\n" - + "echo 'Variables do not $expand $either';\n"); + // Parser parser; + public PHPManualTestCase(String name) { + super(name); + } + + /** + * Test the PHP Parser with different PHP snippets + */ + public void testPHPParser() { + checkPHP("self::$instance = new Singleton();"); + checkPHP("if ((eregi(\"<[^>]*script*\\\"?[^>]*>\", $secvalue)) ||\r\n" + + " (eregi(\"<[^>]*object*\\\"?[^>]*>\", $secvalue)) ||\r\n" + + " (eregi(\"<[^>]*iframe*\\\"?[^>]*>\", $secvalue)) ||\r\n" + + " (eregi(\"<[^>]*applet*\\\"?[^>]*>\", $secvalue)) ||\r\n" + + " (eregi(\"<[^>]*meta*\\\"?[^>]*>\", $secvalue)) ||\r\n" + + " (eregi(\"<[^>]*style*\\\"?[^>]*>\", $secvalue)) ||\r\n" + + " (eregi(\"<[^>]*form*\\\"?[^>]*>\", $secvalue)) ||\r\n" + + " (eregi(\"\\([^>]*\\\"?[^)]*\\)\", $secvalue)) ||\r\n" + + " (eregi(\"\\\"\", $secvalue))) {\r\n" + + " die (\"


    The html tags you attempted to use are not allowed

    [ Go Back ]\");\r\n" + + " }"); + checkPHP("function foo()" + "{" + " echo \"In foo()
    \\n\";" + "}" + + "" + "function bar($arg = '')" + "{" + + " echo \"In bar(); argument was '$arg'.
    \\n\";" + "}" + + "" + "// This is a wrapper function around echo" + + "function echoit($string)" + "{" + " echo $string;" + "}" + + "" + "$func = 'foo';" + "$func(); // This calls foo()" + + "" + "$func = 'bar';" + "$func('test'); // This calls bar()" + + "" + "$func = 'echoit';" + + "$func('test'); // This calls echoit()" + ""); + checkPHP("class Foo" + "{" + " function Vari()" + " {" + + " $name = 'Bar';" + + " $this->$name(); // This calls the Bar() method\n" + + " }" + " " + " function Bar()" + " {" + + " echo \"This is Bar\";" + " }" + "}" + "" + + "$foo = new Foo();" + "$funcname = \"Var\";" + + "$foo->$varname(); // This calls $foo->Var()\n" + ""); + checkPHP("function square ($num)" + "{" + " return $num * $num;" + + "}" + "echo square (4); // outputs '16'." + ""); + checkPHP("function small_numbers()" + "{" + + " return array (0, 1, 2);" + "}" + + "list ($zero, $one, $two) = small_numbers();" + ""); + checkPHP("function &returns_reference()" + "{" + " return $someref;" + + "}" + "" + "$newref =& returns_reference();" + " " + ""); + checkPHP("function add_some_extra(&$string)" + "{" + + " $string .= 'and something extra.';" + "}" + + "$str = 'This is a string, ';" + "add_some_extra($str);" + + "echo $str; "); + checkPHP("function makecoffee ($type = \"cappuccino\")\n" + "{\n" + + " return \"Making a cup of $type.\\n\";\n" + "}" + + "echo makecoffee ();" + "echo makecoffee (\"espresso\");" + + ""); + checkPHP("$makefoo = true;" + + "" + + "/* We can't call foo() from here " + + " since it doesn't exist yet," + + " but we can call bar() */" + + "" + + "bar();" + + "" + + "if ($makefoo) {" + + " function foo ()" + + " {" + + " echo \"I don't exist until program execution reaches me.\\n\";" + + " }" + "}" + "" + "/* Now we can safely call foo()" + + " since $makefoo evaluated to true */" + "" + + "if ($makefoo) foo();" + "" + "function bar() " + "{" + + " echo \"I exist immediately upon program start.\\n\";" + + "}" + "" + ""); + checkPHP("function foo() " + "{" + " function bar() " + " {" + + " echo \"I don't exist until foo() is called.\\n\";" + + " }" + "}" + "" + "/* We can't call bar() yet" + + " since it doesn't exist. */" + "" + "foo();\n" + "" + + "/* Now we can call bar()," + " foo()'s processesing has" + + " made it accessable. */" + "" + "bar();" + ""); + // Bugs item #690938 + checkPHP(" echo \"This is a test\"; // This is a one-line c++ style comment\n" + + " /* This is a multi line comment\n" + + " yet another line of comment */\n" + + " echo \"This is yet another test\";\n" + + " echo \"One Final Test\"; # This is shell-style style comment \n"); + checkPHP("$bool = TRUE; // a boolean\n" + + "$str = \"foo\"; // a string\n" + + "$int = 12; // an integer\n" + "\n" + + "echo gettype($bool); // prints out \"boolean\"\n" + + "echo gettype($str); // prints out \"string\"\n" + "" + + "// If this is an integer, increment it by four\n" + + "if (is_int($int)) {\n" + " $int += 4;\n" + "}\n" + "\n" + + "// If $bool is a string, print it out\n" + + "// (does not print out anything)\n" + + "if (is_string($bool)) {\n" + " echo \"String: $bool\";\n" + + "}\n"); + checkPHP("$foo = True; // assign the value TRUE to $foo"); + checkPHP("// == is an operator which test\n" + + "// equality and returns a boolean\n" + + "if ($action == \"show_version\") {\n" + + " echo \"The version is 1.23\";\n" + "}\n" + "\n" + + "// this is not necessary...\n" + + "if ($show_separators == TRUE) {\n" + + " echo \"
    \\n\";\n" + "}\n" + "\n" + + "// ...because you can simply type\n" + + "if ($show_separators) {\n" + " echo \"
    \\n\";\n" + "}"); + checkPHP( // "echo gettype((bool) \"\"); // bool(false)\n" + "echo gettype((bool) 1); // bool(true)\n" + + "echo gettype((bool) -2); // bool(true)\n" + + "echo gettype((bool) \"foo\"); // bool(true)\n" + + "echo gettype((bool) 2.3e5); // bool(true)\n" + + "echo gettype((bool) array(12)); // bool(true)\n" + + "echo gettype((bool) array()); // bool(false)\n"); + checkPHP("$a = 1234; # decimal number\n" + + "$a = -123; # a negative number\n" + + "$a = 0123; # octal number (equivalent to 83 decimal)\n" + + "$a = 0x1A; # hexadecimal number (equivalent to 26 decimal)\n"); + checkPHP("$large_number = 2147483647;\n" + + "var_dump($large_number);\n" + "// output: int(2147483647)\n" + + "\n" + "$large_number = 2147483648;\n" + + "var_dump($large_number);\n" + + "// output: float(2147483648)\n" + "" + + "// this goes also for hexadecimal specified integers:\n" + + "var_dump( 0x80000000 );\n" + + "// output: float(2147483648)\n" + "\n" + + "$million = 1000000;\n" + + "$large_number = 50000 * $million;\n" + + "var_dump($large_number);\n" + + "// output: float(50000000000)\n"); + checkPHP("var_dump(25/7); // float(3.5714285714286)\n" + + "var_dump((int) (25/7)); // int(3)\n" + + "var_dump(round(25/7)); // float(4)"); + checkPHP("echo (int) ( (0.1+0.7) * 10 ); // echoes 7!"); + checkPHP("$a = 1.234; " + "$b = 1.2e3; " + "$c = 7E-10;"); + checkPHP("echo 'this is a simple string';\n" + "\n" + + "echo 'You can also have embedded newlines in \n" + + "strings this way as it is\n" + "okay to do';\n" + "\n" + + "// Outputs: \"I'll be back\"\n" + + "echo 'Arnold once said: \"I\\'ll be back\"';\n" + "\n" + + "// Outputs: You deleted C:\\*.*?\n" + + "echo 'You deleted C:\\\\*.*?';\n" + "\n" + + "// Outputs: You deleted C:\\*.*?\n" + + "echo 'You deleted C:\\\\*.*?';\n" + "\n" + + "// Outputs: This will not expand: \\n a newline\n" + + "echo 'This will not expand: \\n a newline';\n" + "\n" + + "// Outputs: Variables do not $expand $either\n" + + "echo 'Variables do not $expand $either';\n"); - checkPHP("echo \"This works: \" . $arr['foo'][3];"); - checkPHP("echo \"\\$foo==$foo; type is \" . gettype ($foo) . \"
    \\n\";"); - checkPHP("$arr = array(\"foo\" => \"bar\", 12 => true);\n" + "\n" - + "echo $arr[\"foo\"]; // bar\n" + "echo $arr[12]; // 1\n"); - checkPHP("// This array is the same as ...\n" - + "array(5 => 43, 32, 56, \"b\" => 12);\n" + "\n" - + "// ...this array\n" - + "array(5 => 43, 6 => 32, 7 => 56, \"b\" => 12);\n"); - checkPHP("$arr = array(5 => 1, 12 => 2);\n" + "\n" - + "$arr[] = 56; // This is the same as $arr[13] = 56;\n" - + " // at this point of the script\n" + "\n" - + "$arr[\"x\"] = 42; // This adds a new element to\n" - + " // the array with key \"x\"\n" - + " \n" - + "unset($arr[5]); // This removes the element from the array\n" + "\n" - + "unset($arr); // This deletes the whole array\n"); - checkPHP("$foo[bar] = 'enemy';\n" + "echo $foo[bar];"); - checkPHP("$a = array( 'color' => 'red',\n" - + " 'taste' => 'sweet',\n" - + " 'shape' => 'round',\n" - + " 'name' => 'apple',\n" - + " 4 // key will be 0\n" - + " );\n" - + "\n" - + "// is completely equivalent with\n" - + "$a['color'] = 'red';\n" - + "$a['taste'] = 'sweet';\n" - + "$a['shape'] = 'round';\n" - + "$a['name'] = 'apple';\n" - + "$a[] = 4; // key will be 0\n" - + "\n" - + "$b[] = 'a';\n" - + "$b[] = 'b';\n" - + "$b[] = 'c';\n" - + "// will result in the array array(0 => 'a' , 1 => 'b' , 2 => 'c'),\n" - + "// or simply array('a', 'b', 'c')\n"); - checkPHP("foreach ($colors as $key => $color) {\n" + " // won't work:\n" - + " //$color = strtoupper($color);\n" + " \n" + " // works:\n" - + " $colors[$key] = strtoupper($color);\n" + "}\n" - + "print_r($colors);\n"); - checkPHP("$fruits = array ( \"fruits\" => array ( \"a\" => \"orange\",\n" - + " \"b\" => \"banana\",\n" - + " \"c\" => \"apple\"\n" - + " ),\n" - + " \"numbers\" => array ( 1,\n" - + " 2,\n" - + " 3,\n" - + " 4,\n" - + " 5,\n" - + " 6,\n" - + " ),\n" - + " \"holes\" => array ( \"first\",\n" - + " 5 => \"second\",\n" - + " \"third\"\n" - + " )\n" + " );\n" - + "\n" + "// Some examples to address values in the array above \n" - + "echo $fruits[\"holes\"][5]; // prints \"second\"\n" - + "echo $fruits[\"fruits\"][\"a\"]; // prints \"orange\"\n" - + "unset($fruits[\"holes\"][0]); // remove \"first\"\n" + "\n" - + "// Create a new multi-dimensional array\n" - + "$juices[\"apple\"][\"green\"] = \"good\"; \n"); - checkPHP("$arr3 = &$arr1;"); - checkPHP("class foo\n" + "{\n" + " function do_foo()\n" + " {\n" - + " echo \"Doing foo.\"; \n" + " }\n" + "}\n" + "\n" - + "$bar = new foo;\n" + "$bar->do_foo();\n"); - checkPHP("$obj = (object) 'ciao';\n" - + "echo $obj->scalar; // outputs 'ciao'"); - checkPHP("$var = NULL;"); - checkPHP("$var = \"Bob\";\n" + "$Var = \"Joe\";\n" - + "echo \"$var, $Var\"; // outputs \"Bob, Joe\"\n" + "\n" + - // "$4site = 'not yet'; // invalid; starts with a number\n" + - "$_4site = 'not yet'; // valid; starts with an underscore\n" - + "$täyte = 'mansikka'; \n"); + checkPHP("echo \"This works: \" . $arr['foo'][3];"); + checkPHP("echo \"\\$foo==$foo; type is \" . gettype ($foo) . \"
    \\n\";"); + checkPHP("$arr = array(\"foo\" => \"bar\", 12 => true);\n" + "\n" + + "echo $arr[\"foo\"]; // bar\n" + "echo $arr[12]; // 1\n"); + checkPHP("// This array is the same as ...\n" + + "array(5 => 43, 32, 56, \"b\" => 12);\n" + "\n" + + "// ...this array\n" + + "array(5 => 43, 6 => 32, 7 => 56, \"b\" => 12);\n"); + checkPHP("$arr = array(5 => 1, 12 => 2);\n" + + "\n" + + "$arr[] = 56; // This is the same as $arr[13] = 56;\n" + + " // at this point of the script\n" + + "\n" + + "$arr[\"x\"] = 42; // This adds a new element to\n" + + " // the array with key \"x\"\n" + + " \n" + + "unset($arr[5]); // This removes the element from the array\n" + + "\n" + "unset($arr); // This deletes the whole array\n"); + checkPHP("$foo[bar] = 'enemy';\n" + "echo $foo[bar];"); + checkPHP("$a = array( 'color' => 'red',\n" + + " 'taste' => 'sweet',\n" + + " 'shape' => 'round',\n" + + " 'name' => 'apple',\n" + + " 4 // key will be 0\n" + + " );\n" + + "\n" + + "// is completely equivalent with\n" + + "$a['color'] = 'red';\n" + + "$a['taste'] = 'sweet';\n" + + "$a['shape'] = 'round';\n" + + "$a['name'] = 'apple';\n" + + "$a[] = 4; // key will be 0\n" + + "\n" + + "$b[] = 'a';\n" + + "$b[] = 'b';\n" + + "$b[] = 'c';\n" + + "// will result in the array array(0 => 'a' , 1 => 'b' , 2 => 'c'),\n" + + "// or simply array('a', 'b', 'c')\n"); + checkPHP("foreach ($colors as $key => $color) {\n" + + " // won't work:\n" + + " //$color = strtoupper($color);\n" + " \n" + + " // works:\n" + + " $colors[$key] = strtoupper($color);\n" + "}\n" + + "print_r($colors);\n"); + checkPHP("$fruits = array ( \"fruits\" => array ( \"a\" => \"orange\",\n" + + " \"b\" => \"banana\",\n" + + " \"c\" => \"apple\"\n" + + " ),\n" + + " \"numbers\" => array ( 1,\n" + + " 2,\n" + + " 3,\n" + + " 4,\n" + + " 5,\n" + + " 6,\n" + + " ),\n" + + " \"holes\" => array ( \"first\",\n" + + " 5 => \"second\",\n" + + " \"third\"\n" + + " )\n" + + " );\n" + + "\n" + + "// Some examples to address values in the array above \n" + + "echo $fruits[\"holes\"][5]; // prints \"second\"\n" + + "echo $fruits[\"fruits\"][\"a\"]; // prints \"orange\"\n" + + "unset($fruits[\"holes\"][0]); // remove \"first\"\n" + + "\n" + + "// Create a new multi-dimensional array\n" + + "$juices[\"apple\"][\"green\"] = \"good\"; \n"); + checkPHP("$arr3 = &$arr1;"); + checkPHP("class foo\n" + "{\n" + " function do_foo()\n" + " {\n" + + " echo \"Doing foo.\"; \n" + " }\n" + "}\n" + "\n" + + "$bar = new foo;\n" + "$bar->do_foo();\n"); + checkPHP("$obj = (object) 'ciao';\n" + + "echo $obj->scalar; // outputs 'ciao'"); + checkPHP("$var = NULL;"); + checkPHP("$var = \"Bob\";\n" + "$Var = \"Joe\";\n" + + "echo \"$var, $Var\"; // outputs \"Bob, Joe\"\n" + "\n" + + + // "$4site = 'not yet'; // invalid; starts with a number\n" + + "$_4site = 'not yet'; // valid; starts with an underscore\n" + + "$t�yte = 'mansikka'; \n"); - checkPHP(""); - checkPHP(""); - } + checkPHP(""); + checkPHP(""); + } } diff --git a/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/tests/parser/PHPParserTestCase.java b/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/tests/parser/PHPParserTestCase.java index 0f9e6b8..0f3e50e 100644 --- a/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/tests/parser/PHPParserTestCase.java +++ b/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/tests/parser/PHPParserTestCase.java @@ -19,135 +19,114 @@ public class PHPParserTestCase extends AbstractCompilerTest { /** * Test the PHP Parser with failing PHP snippets - * + * */ public void testPHPParserFailingSyntax() { - checkPHP("i=10;", - "----------\n" + - "1. ERROR in (at line 1)\n" + - " i=10;\n" + - " ^^\n" + - "Parser error \"Assignment operator \'=\' not allowed after identifier \'i\' (use \'define(...)\' to define constants).\"\n" + - "----------\n"); + checkPHP( + "i=10;", + "----------\n" + + "1. ERROR in (at line 1)\n" + + " i=10;\n" + + " ^^\n" + + "Parser error \"Assignment operator \'=\' not allowed after identifier \'i\' (use \'define(...)\' to define constants).\"\n" + + "----------\n"); } - + /** * Test Interface Extending multiple Interfaces * - * This is valid PHP5 syntax - * Bug 1431425 + * This is valid PHP5 syntax Bug 1431425 */ public void testMIInterfaceExtendsInterface() { // valid PHP5 - checkPHP("interface a {}\n" - + "interface b {}\n" - + "\n" - + "interface c extends a, b\n" - + "{}\n"); + checkPHP("interface a {}\n" + "interface b {}\n" + "\n" + + "interface c extends a, b\n" + "{}\n"); } - + /** * Test Interface implementing multiple Interfaces * - * This is invalid PHP5 syntax - * Bug 1431425 + * This is invalid PHP5 syntax Bug 1431425 */ public void testMIInterfaceImplementsInterface() { // invalid PHP5 - checkPHP("interface a {}\n" - + "interface b {}\n" - + "\n" - + "interface c implements a, b\n" - + "{}\n" - , + checkPHP( + "interface a {}\n" + "interface b {}\n" + "\n" + + "interface c implements a, b\n" + "{}\n", "----------\n" - + "1. ERROR in (at line 1)\n" - + " interface c implements a, b\n" - + " ^^^^^^^^^^^\n" - + "Parser error \"'{' expected at start of class body.\"\n" - + "----------\n" - + "2. ERROR in (at line 1)\n" - + " {}\n" - + "\n" - + " ^^\n" - + "Parser error \"Too many closing '}'; end-of-file not reached.\"\n" - + "----------\n"); - + + "1. ERROR in (at line 1)\n" + + " interface c implements a, b\n" + + " ^^^^^^^^^^^\n" + + "Parser error \"'{' expected at start of class body.\"\n" + + "----------\n" + + "2. ERROR in (at line 1)\n" + + " {}\n" + + "\n" + + " ^^\n" + + "Parser error \"Too many closing '}'; end-of-file not reached.\"\n" + + "----------\n"); + } - + /** * Test Class Extending multiple Interfaces * - * This is invalid PHP5 syntax - * Bug 1431425 + * This is invalid PHP5 syntax Bug 1431425 */ public void testMIClassExtendsInterface() { // invalid PHP5 - checkPHP("interface a {}\n" - + "interface b {}\n" - + "\n" - + "class c extends a, b\n" - + "{}\n" - ,"----------\n" + - "1. ERROR in (at line 1)\n" + - " class c extends a, b\n" + - " ^^\n" + - "Parser error \"No multiple inheritence allowed. Expected token \'implements\' or \'{\'.\"\n" + - "----------\n"); + checkPHP( + "interface a {}\n" + "interface b {}\n" + "\n" + + "class c extends a, b\n" + "{}\n", + "----------\n" + + "1. ERROR in (at line 1)\n" + + " class c extends a, b\n" + + " ^^\n" + + "Parser error \"No multiple inheritence allowed. Expected token \'implements\' or \'{\'.\"\n" + + "----------\n"); } - + /** * Test Class implementing multiple Interfaces * - * This is valid PHP5 syntax - * Bug 1431425 + * This is valid PHP5 syntax Bug 1431425 */ public void testMIClassImplementsInterfaces() { // valid PHP5 - checkPHP("interface a {}\n" - + "interface b {}\n" - + "\n" - + "class c implements a, b\n" - + "{}\n"); + checkPHP("interface a {}\n" + "interface b {}\n" + "\n" + + "class c implements a, b\n" + "{}\n"); } - + /** * Test Class Implementing multiple classes * - * This is invalid PHP5 syntax - * Bug 1431425 + * This is invalid PHP5 syntax Bug 1431425 */ public void testMIClassImplementsClasses() { // invalid PHP5 - checkPHP("class a {}\n" - + "class b {}\n" - + "\n" - + "class c implements a, b\n" - + "{}\n" - ,"This should fail, but doesn't currently."); + checkPHP("class a {}\n" + "class b {}\n" + "\n" + + "class c implements a, b\n" + "{}\n", + "This should fail, but doesn't currently."); } - + /** * Test Class Extending multiple Classes * - * This is invalid PHP5 syntax - * Bug 1431425 + * This is invalid PHP5 syntax Bug 1431425 */ public void testMIClassExtendsClasses() { // invalid PHP5 - checkPHP("class a {}\n" - + "class b {}\n" - + "\n" - + "class c extends a, b\n" - + "{}\n" - ,"----------\n" + - "1. ERROR in (at line 1)\n" + - " class c extends a, b\n" + - " ^^\n" + - "Parser error \"No multiple inheritence allowed. Expected token \'implements\' or \'{\'.\"\n" + - "----------\n"); + checkPHP( + "class a {}\n" + "class b {}\n" + "\n" + + "class c extends a, b\n" + "{}\n", + "----------\n" + + "1. ERROR in (at line 1)\n" + + " class c extends a, b\n" + + " ^^\n" + + "Parser error \"No multiple inheritence allowed. Expected token \'implements\' or \'{\'.\"\n" + + "----------\n"); } - + /** * Test the PHP Parser with different PHP snippets */ @@ -159,48 +138,49 @@ public class PHPParserTestCase extends AbstractCompilerTest { checkPHP("$schema_create .= \" DEFAULT \'$row[Default]\'\";"); checkPHP("$stringVar=\"ein normaler $varText\";"); checkPHP("$stringVar=\'ein normaler $varText\';"); - checkPHP("switch ($aItem[ELM_NAME]) {\r\n" + checkPHP("switch ($aItem[ELM_NAME]) {\r\n" + " case \'channel\':\r\n" - + " $this->readChannel($aItem);\r\n" + + " $this->readChannel($aItem);\r\n" + " break;\r\n" - + " case \'item\':\r\n" + + " case \'item\':\r\n" + " $this->readItem($aItem);\r\n" - + " break;\r\n" - + " default:\r\n" - + " //printr($aItem);\r\n" - + " }"); - checkPHP("try {echo $Stream->readAll(); } catch (Exception $e) {\r\n" + + " break;\r\n" + + " default:\r\n" + + " //printr($aItem);\r\n" + " }"); + checkPHP("try {echo $Stream->readAll(); } catch (Exception $e) {\r\n" + " // Swallow exception\r\n" + " }"); - checkHTML("ol_path = $path;\n" - + "\n" - + "?>\n" - + "\n" + "ol_path/overlib.css\' \"; ?> \n" + "\n" - + " type=\'text/css\'>\n" + "\n" - + "
    \n" - + "\n" + "
    \n" + + "?>\n" + "\n" - + "\n" + + "ol_path/overlib.css\' \"; ?> \n" + "\n" - + "\n" + + "\n" + + "
    \n" + + "\n" + + "
    \n" + + "\n" + + "\n" + "\n" + ""); checkPHP("$t = \') {$ya[]=\'.$this->iFunc.\';$xa[]=\'.$this->iXFunc.\';}\';"); - checkPHP("$output .= \n" + " \"\\$_smarty_tpl_vars = \\$this->_tpl_vars;\\n\" . \n" + checkPHP("$output .= \n" + + " \"\\$_smarty_tpl_vars = \\$this->_tpl_vars;\\n\" . \n" + " \"\\$this->_smarty_include(\".$include_file.\", array(\".implode(\',\', (array)$arg_list).\"));\\n\" .\n" - + " \"\\$this->_tpl_vars = \\$_smarty_tpl_vars;\\n\" .\n" + + " \"\\$this->_tpl_vars = \\$_smarty_tpl_vars;\\n\" .\n" + " \"unset(\\$_smarty_tpl_vars);\\n\";"); checkPHP("$test=\"=$post_id#$post_id\""); checkPHP("$comments .= \" \\${$attrname}[\'xmlns\'] = \'{$this->namespaces[$_argtype[\'namespace\']]}\';\\n\";"); checkPHP("$this->_raiseSoapFault(\"method \'{{$this->method_namespace}}$this->methodname\' not defined in service\",\'\',\'\',\'Server\');"); - checkPHP("$emailer->assign_vars(array(\r\n" + checkPHP("$emailer->assign_vars(array(\r\n" + " \'U_TOPIC\' => $server_protocol . POST_POST_URL . \"=$post_id#$post_id\",\r\n" - + " \'U_STOP_WATCHING_TOPIC\' => $server_protocol . $server_name . $server_port . $script_name . \'&\' . POST_TOPIC_URL . \"=$topic_id&unwatch=topic\")\r\n" + + " \'U_STOP_WATCHING_TOPIC\' => $server_protocol . $server_name . $server_port . $script_name . \'&\' . POST_TOPIC_URL . \"=$topic_id&unwatch=topic\")\r\n" + " );"); checkPHP("$_compile_data = \'\';"); checkPHP("$output = \' \"$myrow[uname]\"); } while($myrow = mysql_fetch_array($result));"); checkPHP("\"\\\"\";"); checkPHP(" print \"$value\"; \n"); - checkPHP("if ($shape instanceof Rectangle) { \n" + " print \'$shape is a Rectangle\'; \n" + "} "); + checkPHP("if ($shape instanceof Rectangle) { \n" + + " print \'$shape is a Rectangle\'; \n" + "} "); checkPHP("$test=\"values(\'$user\',\'${res[\"name\"]}\' \";"); checkPHP("$this->raiseError(\"The auth mode: $mode isn\'t implemented\");"); checkPHP("\'{$this->_keycolumn[$i]};"); - checkPHP("$this->_reg_objects[$object] =\n" + " array(&$object_impl, $allowed, $smarty_args);"); - checkPHP("echo <<< EOF\n" + "
    \n" + "EOF;"); - checkPHP("interface Shape { \n" + " function draw(); \n" + "} \n" + "\n" + "class Rectangle implements Shape { \n" - + " function draw() { \n" + " print \"Drawing a rectangle\"; \n" + " } \n" + "}"); - checkPHP("class MyClass { \n" + " private $priv; \n" + "\n" + " public function getVar() { \n" + checkPHP("$this->_reg_objects[$object] =\n" + + " array(&$object_impl, $allowed, $smarty_args);"); + checkPHP("echo <<< EOF\n" + "
    \n" + + "EOF;"); + checkPHP("interface Shape { \n" + " function draw(); \n" + "} \n" + + "\n" + "class Rectangle implements Shape { \n" + + " function draw() { \n" + + " print \"Drawing a rectangle\"; \n" + " } \n" + + "}"); + checkPHP("class MyClass { \n" + " private $priv; \n" + "\n" + + " public function getVar() { \n" + " return $this->priv; \n" + " } \n" + "} "); - checkPHP("class Test { \n" + " function __construct() { \n" + " print \"Test constructor\"; \n" + " } \n" + "}"); - checkPHP("class Test { \n" + " function __destruct() { \n" + " print \"Destroying Test object\"; \n" + " } \n" + checkPHP("class Test { \n" + " function __construct() { \n" + + " print \"Test constructor\"; \n" + " } \n" + "}"); + checkPHP("class Test { \n" + " function __destruct() { \n" + + " print \"Destroying Test object\"; \n" + " } \n" + "}"); - checkPHP("class Test { \n" + " final function doNotOverload() { \n" + " return __CLASS__; \n" + " } \n" + "}"); - checkPHP("final class Test { \n" + "} \n" + "\n" + "class DoNotInherit extends Test { \n" + "}"); - checkPHP("class Test { \n" + " function __clone() { \n" + " print \"Clone test object\"; \n" + " } \n" + "} \n" - + "$test = new Test(); \n" + "clone $test; "); - checkPHP("class Test { \n" + " const SEMICOLON = \";\"; \n" + " const QUESTIONMARK = \"?\"; \n" + "} \n" + checkPHP("class Test { \n" + " final function doNotOverload() { \n" + + " return __CLASS__; \n" + " } \n" + "}"); + checkPHP("final class Test { \n" + "} \n" + "\n" + + "class DoNotInherit extends Test { \n" + "}"); + checkPHP("class Test { \n" + " function __clone() { \n" + + " print \"Clone test object\"; \n" + " } \n" + + "} \n" + "$test = new Test(); \n" + "clone $test; "); + checkPHP("class Test { \n" + " const SEMICOLON = \";\"; \n" + + " const QUESTIONMARK = \"?\"; \n" + "} \n" + "print Test::SEMICOLON; "); - checkPHP("class Singleton { \n" + " static $instance = NULL; \n" + " function getInstance() { \n" - + " if ($this->instance == NULL) { \n" + " $this->instance = new Singleton(); \n" + " } \n" - + " return $this->instance; \n" + " } \n" + "} "); - checkPHP("class Test { \n" + " static function helloWorld() { \n" + " print \"Hello, world\"; \n" + " } \n" - + "} \n" + "Test::helloWorld();"); - checkPHP("abstract class Test { \n" + " function draw() { \n" + " print \"Inside draw()\"; \n" + " } \n" + "} "); - checkPHP("abstract class Test { \n" + " abstract function draw(); \n" + "} "); + checkPHP("class Singleton { \n" + " static $instance = NULL; \n" + + " function getInstance() { \n" + + " if ($this->instance == NULL) { \n" + + " $this->instance = new Singleton(); \n" + + " } \n" + " return $this->instance; \n" + + " } \n" + "} "); + checkPHP("class Test { \n" + " static function helloWorld() { \n" + + " print \"Hello, world\"; \n" + " } \n" + "} \n" + + "Test::helloWorld();"); + checkPHP("abstract class Test { \n" + " function draw() { \n" + + " print \"Inside draw()\"; \n" + " } \n" + "} "); + checkPHP("abstract class Test { \n" + + " abstract function draw(); \n" + "} "); checkPHP("function f1(Test $test) { \n" + "\n" + "}"); checkPHP("$test->m1()->m2(); "); - checkPHP("$test = new IteratorImpl(); \n" + "foreach ($test as $value) { \n" + " print \"$value\"; \n" + "}"); - checkPHP("function __autoload($clazz) { \n" + " include_once($clazz . \"php\"); \n" + "} \n" + "\n" + checkPHP("$test = new IteratorImpl(); \n" + + "foreach ($test as $value) { \n" + " print \"$value\"; \n" + + "}"); + checkPHP("function __autoload($clazz) { \n" + + " include_once($clazz . \"php\"); \n" + "} \n" + "\n" + "$obj = new Test1(); \n" + "$obj2 = new Test2(); "); - checkPHP("class SQLException extends Exception { \n" + " public $problem; \n" + " function __construct($problem) { \n" - + " $this->problem = $problem; \n" + " } \n" + "} \n" + "\n" + "try { \n" - + " throw new SQLException(\"Couldn’t connect to database\"); \n" + "} catch (SQLException $e) { \n" - + " print \"Caught an SQLException with problem $obj->problem\"; \n" + "} catch (Exception $e) { \n" + checkPHP("class SQLException extends Exception { \n" + + " public $problem; \n" + + " function __construct($problem) { \n" + + " $this->problem = $problem; \n" + + " } \n" + + "} \n" + + "\n" + + "try { \n" + + " throw new SQLException(\"Couldn’t connect to database\"); \n" + + "} catch (SQLException $e) { \n" + + " print \"Caught an SQLException with problem $obj->problem\"; \n" + + "} catch (Exception $e) { \n" + " print \"Caught unrecognized exception\"; \n" + "}"); - checkPHP("function my_func(&$arg = null) { \n" + " if ($arg === NULL) { \n" + " print \'$arg is empty\'; \n" - + " } \n" + "} \n" + "my_func();"); - checkPHP("foreach ($array as &$value) { \n" + " if ($value === \"NULL\") { \n" + " $value = NULL; \n" + " } \n" - + "}"); - checkPHP("$testxml = simplexml_load_file(\'test.xml\'); \n" + "foreach ($$testxml->client as $test) { \n" - + " print \"$test->name has account number $test->account_number \"; \n" + "} "); + checkPHP("function my_func(&$arg = null) { \n" + + " if ($arg === NULL) { \n" + + " print \'$arg is empty\'; \n" + " } \n" + "} \n" + + "my_func();"); + checkPHP("foreach ($array as &$value) { \n" + + " if ($value === \"NULL\") { \n" + + " $value = NULL; \n" + " } \n" + "}"); + checkPHP("$testxml = simplexml_load_file(\'test.xml\'); \n" + + "foreach ($$testxml->client as $test) { \n" + + " print \"$test->name has account number $test->account_number \"; \n" + + "} "); checkHTML(" "); - checkHTML("\n" + "test me\n" + ""); + checkHTML("\n" + + "test me\n" + ""); checkHTML(""); checkPHP("function clean_words($mode, &$entry, &$stopword_list, &$synonym_list)\r\n" @@ -281,9 +299,12 @@ public class PHPParserTestCase extends AbstractCompilerTest { checkPHP("if(!$result = mysql_query($sql)) return(array());"); checkPHP("class test { function &fetchRow($result, $fetchmode = DB_FETCHMODE_DEFAULT, $rownum=null) \n{ \n } \n }"); // Bugs item #690938 - checkPHP("$ebus_sql['sel_url_list'] = <<>\n" - + "and appl_sect_deftn_sk = <>\n" + "order by url_ord\n" + "EOS;\n"); + checkPHP("$ebus_sql['sel_url_list'] = <<>\n" + + "and appl_sect_deftn_sk = <>\n" + "order by url_ord\n" + + "EOS;\n"); checkPHP("foreach ($HTTP_GET_VARS as $secvalue) { }"); checkPHP("\"\\[addsig]\""); @@ -321,9 +342,13 @@ public class PHPParserTestCase extends AbstractCompilerTest { checkPHP("class Cmd extends PEAR { var $arrSetting = array(), $i=10; }"); checkPHP("if (isset($test)) { } elseif (isset($lang)) { }"); checkPHP("require_once(\"mainfile.php\"); "); - checkPHP("if (eregi(\"footer.php\",$PHP_SELF)) {\n" + "Header(\"Location: index.php\");\n" + "die();\n" + "}\n"); - checkPHP("while (eregi(\"footer.php\",$PHP_SELF)) {\n" + "Header(\"Location: index.php\");\n" + "die();\n" + "}\n"); - checkPHP("while (eregi(\"footer.php\",$PHP_SELF)) :\n" + "Header(\"Location: index.php\");\n" + "die();\n" + "endwhile;\n"); + checkPHP("if (eregi(\"footer.php\",$PHP_SELF)) {\n" + + "Header(\"Location: index.php\");\n" + "die();\n" + "}\n"); + checkPHP("while (eregi(\"footer.php\",$PHP_SELF)) {\n" + + "Header(\"Location: index.php\");\n" + "die();\n" + "}\n"); + checkPHP("while (eregi(\"footer.php\",$PHP_SELF)) :\n" + + "Header(\"Location: index.php\");\n" + "die();\n" + + "endwhile;\n"); checkPHP("$tipath = \"images/topics/\";"); checkPHP("$reasons = array(\"1\", \"2\",\"test\");"); checkPHP("if ($home == 1) { message_box(); blocks(Center);}"); @@ -344,9 +369,11 @@ public class PHPParserTestCase extends AbstractCompilerTest { checkPHP("/* \n overLib is from Eric Bosrup (http://www.bosrup.com/web/overlib/) \n */"); checkPHP("if ($arrAtchCookie[1]==0 && $IdAtchPostId!=null){ } "); checkPHP("$arrAtchCookie[1] -= filesize(realpath($AtchTempDir).\"/\".$xattachlist)/ 1024; "); - checkPHP("if (!isset($message)){ \n" + "$message = $myrow[post_text];\n" + checkPHP("if (!isset($message)){ \n" + + "$message = $myrow[post_text];\n" + "$message = eregi_replace(\"\\[addsig]\", \"\\n-----------------\\n\" . $myrow[user_sig], $message); \n" - + "$message = str_replace(\"
    \", \"\\n\", $message); \n" + "$message = str_replace(\"
    \", \"\\n\", $message); \n } "); + + "$message = str_replace(\"
    \", \"\\n\", $message); \n" + + "$message = str_replace(\"
    \", \"\\n\", $message); \n } "); checkPHP("$ol = new Overlib();"); checkPHP("$risultato = mysql_query($sql) or\n die(mysql_error());"); checkHTML("\n\n\n\n "); diff --git a/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/tests/parser/PHPParserTestSuite.java b/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/tests/parser/PHPParserTestSuite.java index 8320b5b..a1dcd97 100644 --- a/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/tests/parser/PHPParserTestSuite.java +++ b/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/tests/parser/PHPParserTestSuite.java @@ -12,9 +12,8 @@ import junit.framework.TestCase; import junit.framework.TestSuite; /** - * PHPeclipse Parser Test Suite - * Runs all PHP parser test cases - * + * PHPeclipse Parser Test Suite Runs all PHP parser test cases + * */ public class PHPParserTestSuite extends TestCase { diff --git a/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/tests/parser/SmartyCompilerTestCase.java b/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/tests/parser/SmartyCompilerTestCase.java index 423d0de..9244622 100644 --- a/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/tests/parser/SmartyCompilerTestCase.java +++ b/net.sourceforge.phpeclipse.tests/src/net/sourceforge/phpeclipse/tests/parser/SmartyCompilerTestCase.java @@ -1,4 +1,5 @@ package net.sourceforge.phpeclipse.tests.parser; + /******************************************************************************* * Copyright (c) 2002 www.phpeclipse.de All rights * reserved. This program and the accompanying materials are made available @@ -6,1901 +7,1887 @@ package net.sourceforge.phpeclipse.tests.parser; * distribution, and is available at http://www.eclipse.org/legal/cpl-v10.html ******************************************************************************/ import net.sourceforge.phpdt.core.tests.util.AbstractCompilerTest; -import net.sourceforge.phpdt.internal.compiler.parser.Scanner; + /** * Tests the php parser */ public class SmartyCompilerTestCase extends AbstractCompilerTest { -// Parser parser; - public SmartyCompilerTestCase(String name) { - super(name); - } - /** - * Test the PHP Parser with different PHP snippets - */ - public void testPHPParser() { - checkHTML("\n" + - " * Andrei Zmievski \n" + - " *\n" + - " * Version: 2.4.2\n" + - " * Copyright: 2001,2002 ispi of Lincoln, Inc.\n" + - " *\n" + - " * This library is free software; you can redistribute it and/or\n" + - " * modify it under the terms of the GNU Lesser General Public\n" + - " * License as published by the Free Software Foundation; either\n" + - " * version 2.1 of the License, or (at your option) any later version.\n" + - " *\n" + - " * This library is distributed in the hope that it will be useful,\n" + - " * but WITHOUT ANY WARRANTY; without even the implied warranty of\n" + - " * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n" + - " * Lesser General Public License for more details.\n" + - " *\n" + - " * You should have received a copy of the GNU Lesser General Public\n" + - " * License along with this library; if not, write to the Free Software\n" + - " * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n" + - " *\n" + - " * You may contact the authors of Smarty by e-mail at:\n" + - " * monte@ispi.net\n" + - " * andrei@php.net\n" + - " *\n" + - " * Or, write to:\n" + - " * Monte Ohrt\n" + - " * Director of Technology, ispi\n" + - " * 237 S. 70th suite 220\n" + - " * Lincoln, NE 68510\n" + - " *\n" + - " * The latest version of Smarty can be obtained from:\n" + - " * http://www.phpinsider.com/\n" + - " *\n" + - " */\n" + - "\n" + - "class Smarty_Compiler extends Smarty {\n" + - " \n" + - " // internal vars\n" + - " public $_sectionelse_stack = array(); // keeps track of whether section had \'else\' part\n" + - " public $_foreachelse_stack = array(); // keeps track of whether foreach had \'else\' part\n" + - " public $_literal_blocks = array(); // keeps literal template blocks\n" + - " public $_php_blocks = array(); // keeps php code blocks\n" + - " public $_current_file = null; // the current template being compiled\n" + - " public $_current_line_no = 1; // line number for error messages\n" + - " public $_capture_stack = array(); // keeps track of nested capture buffers\n" + - " public $_plugin_info = array(); // keeps track of plugins to load\n" + - " public $_init_smarty_vars = false;\n" + - " public $_permitted_tokens = array(\'true\',\'false\',\'yes\',\'no\',\'on\',\'off\');\n" + - " public $_db_qstr_regexp = null; // regexps are setup in the constructor\n" + - " public $_si_qstr_regexp = null;\n" + - " public $_qstr_regexp = null;\n" + - " public $_func_regexp = null;\n" + - " public $_var_bracket_regexp = null;\n" + - " public $_dvar_guts_regexp = null;\n" + - " public $_dvar_regexp = null;\n" + - " public $_cvar_regexp = null;\n" + - " public $_svar_regexp = null;\n" + - " public $_avar_regexp = null;\n" + - " public $_mod_regexp = null;\n" + - " public $_var_regexp = null;\n" + - " public $_parenth_param_regexp = null;\n" + - " public $_func_call_regexp = null;\n" + - " public $_obj_ext_regexp = null;\n" + - " public $_obj_start_regexp = null;\n" + - " public $_obj_params_regexp = null;\n" + - " public $_obj_call_regexp = null;\n" + - "\n" + - " /**\n" + - " * The class constructor.\n" + - " *\n" + - " * @access public\n" + - " */\n" + - " function Smarty_Compiler()\n" + - " {\n" + - " // matches double quoted strings:\n" + - " // \"foobar\"\n" + - " // \"foo\\\"bar\"\n" + - " $this->_db_qstr_regexp = \'\"[^\"\\\\\\\\]*(?:\\\\\\\\.[^\"\\\\\\\\]*)*\"\';\n" + - "\n" + - " // matches single quoted strings:\n" + - " // \'foobar\'\n" + - " // \'foo\\\'bar\'\n" + - " $this->_si_qstr_regexp = \'\\\'[^\\\'\\\\\\\\]*(?:\\\\\\\\.[^\\\'\\\\\\\\]*)*\\\'\';\n" + - "\n" + - " // matches single or double quoted strings\n" + - " $this->_qstr_regexp = \'(?:\' . $this->_db_qstr_regexp . \'|\' . $this->_si_qstr_regexp . \')\';\n" + - "\n" + - " // matches bracket portion of vars\n" + - " // [0]\n" + - " // [foo]\n" + - " // [$bar]\n" + - " $this->_var_bracket_regexp = \'\\[\\$?[\\w\\.]+\\]\';\n" + - " \n" + - " // matches $ vars (not objects):\n" + - " // $foo\n" + - " // $foo.bar\n" + - " // $foo.bar.foobar\n" + - " // $foo[0]\n" + - " // $foo[$bar]\n" + - " // $foo[5][blah]\n" + - " // $foo[5].bar[$foobar][4]\n" + - " $this->_dvar_guts_regexp = \'\\w+(?:\' . $this->_var_bracket_regexp\n" + - " . \')*(?:\\.\\$?\\w+(?:\' . $this->_var_bracket_regexp . \')*)*\';\n" + - " $this->_dvar_regexp = \'\\$\' . $this->_dvar_guts_regexp;\n" + - "\n" + - " // matches config vars:\n" + - " // #foo#\n" + - " // #foobar123_foo#\n" + - " $this->_cvar_regexp = \'\\#\\w+\\#\';\n" + - "\n" + - " // matches section vars:\n" + - " // %foo.bar%\n" + - " $this->_svar_regexp = \'\\%\\w+\\.\\w+\\%\';\n" + - "\n" + - " // matches all valid variables (no quotes, no modifiers)\n" + - " $this->_avar_regexp = \'(?:\' . $this->_dvar_regexp . \'|\'\n" + - " . $this->_cvar_regexp . \'|\' . $this->_svar_regexp . \')\';\n" + - "\n" + - " // matches valid modifier syntax:\n" + - " // |foo\n" + - " // |@foo\n" + - " // |foo:\"bar\"\n" + - " // |foo:$bar\n" + - " // |foo:\"bar\":$foobar\n" + - " // |foo|bar\n" + - " // |foo\n" + - " $this->_mod_regexp = \'(?:\\|@?\\w+(?::(?>\\w+|\'\n" + - " . $this->_avar_regexp . \'|\' . $this->_qstr_regexp .\'))*)\';\n" + - "\n" + - " // matches valid variable syntax:\n" + - " // $foo\n" + - " // $foo\n" + - " // #foo#\n" + - " // #foo#\n" + - " // \"text\"\n" + - " // \"text\"\n" + - " $this->_var_regexp = \'(?:\' . $this->_avar_regexp . \'|\' . $this->_qstr_regexp . \')\';\n" + - " \n" + - " // matches valid object call (no objects allowed in parameters):\n" + - " // $foo->bar\n" + - " // $foo->bar()\n" + - " // $foo->bar(\"text\")\n" + - " // $foo->bar($foo, $bar, \"text\")\n" + - " // $foo->bar($foo|bar, \"foo\"|bar)\n" + - " // $foo->bar->foo()\n" + - " // $foo->bar->foo->bar()\n" + - " $this->_obj_ext_regexp = \'\\->(?:\\w+|\' . $this->_dvar_regexp . \')\';\n" + - " $this->_obj_params_regexp = \'\\((?:\\w+|\'\n" + - " . $this->_var_regexp . \'(?>\' . $this->_mod_regexp . \'*)(?:\\s*,\\s*(?:(?:\\w+|\'\n" + - " . $this->_var_regexp . \'(?>\' . $this->_mod_regexp . \'*))))*)?\\)\'; \n" + - " $this->_obj_start_regexp = \'(?:\' . $this->_dvar_regexp . \'(?:\' . $this->_obj_ext_regexp . \')+)\';\n" + - " $this->_obj_call_regexp = \'(?:\' . $this->_obj_start_regexp . \'(?:\' . $this->_obj_params_regexp . \')?)\';\n" + - " \n" + - " // matches valid function name:\n" + - " // foo123\n" + - " // _foo_bar\n" + - " $this->_func_regexp = \'[a-zA-Z_]\\w*\';\n" + - "\n" + - " // matches valid registered object:\n" + - " // foo.bar\n" + - " $this->_reg_obj_regexp = \'[a-zA-Z_]\\w*->[a-zA-Z_]\\w*\';\n" + - " \n" + - " // matches valid parameter values:\n" + - " // true\n" + - " // $foo\n" + - " // $foo|bar\n" + - " // #foo#\n" + - " // #foo#|bar\n" + - " // \"text\"\n" + - " // \"text\"|bar\n" + - " // $foo->bar\n" + - " $this->_param_regexp = \'(?:\\s*(?:\' . $this->_obj_call_regexp . \'|\'\n" + - " . $this->_var_regexp . \'|\\w+)(?>\' . $this->_mod_regexp . \'*)\\s*)\'; \n" + - " \n" + - " // matches valid parenthesised function parameters:\n" + - " // \n" + - " // \"text\"\n" + - " // $foo, $bar, \"text\"\n" + - " // $foo|bar, \"foo\"|bar, $foo->bar($foo)|bar\n" + - " $this->_parenth_param_regexp = \'(?:\\((?:\\w+|\'\n" + - " . $this->_param_regexp . \'(?:\\s*,\\s*(?:(?:\\w+|\'\n" + - " . $this->_param_regexp . \')))*)?\\))\';\n" + - " \n" + - " // matches valid function call:\n" + - " // foo()\n" + - " // foo_bar($foo)\n" + - " // _foo_bar($foo,\"bar\")\n" + - " // foo123($foo,$foo->bar(),\"foo\")\n" + - " $this->_func_call_regexp = \'(?:\' . $this->_func_regexp . \'\\s*(?:\'\n" + - " . $this->_parenth_param_regexp . \'))\'; \n" + - "\n" + - " } \n" + - " \n" + - " /**\n" + - " * compile a template file\n" + - " *\n" + - " * @access public\n" + - " * @param $tpl_file\n" + - " * @param $template_source\n" + - " * @param $template_compiled\n" + - " */\n" + - " function _compile_file($tpl_file, $template_source, &$template_compiled)\n" + - " {\n" + - " if ($this->security) {\n" + - " // do not allow php syntax to be executed unless specified\n" + - " if ($this->php_handling == SMARTY_PHP_ALLOW &&\n" + - " !$this->security_settings[\'PHP_HANDLING\']) {\n" + - " $this->php_handling = SMARTY_PHP_PASSTHRU;\n" + - " }\n" + - " }\n" + - "\n" + - " $this->_load_filters();\n" + - "\n" + - " $this->_current_file = $tpl_file;\n" + - " $this->_current_line_no = 1;\n" + - " $ldq = preg_quote($this->left_delimiter, \'!\');\n" + - " $rdq = preg_quote($this->right_delimiter, \'!\');\n" + - "\n" + - " // run template source through prefilter functions\n" + - " if (count($this->_plugins[\'prefilter\']) > 0) {\n" + - " foreach ($this->_plugins[\'prefilter\'] as $filter_name => $prefilter) {\n" + - " if ($prefilter === false) continue; \n" + - " if ($prefilter[3] || function_exists($prefilter[0])) {\n" + - " $template_source = $prefilter[0]($template_source, $this);\n" + - " $this->_plugins[\'prefilter\'][$filter_name][3] = true;\n" + - " } else {\n" + - " $this->_trigger_fatal_error(\"[plugin] prefilter \'$filter_name\' is not implemented\");\n" + - " }\n" + - " }\n" + - " }\n" + - "\n" + - " /* Annihilate the comments. */\n" + - " $template_source = preg_replace(\"!({$ldq})\\*(.*?)\\*({$rdq})!se\",\n" + - " \"\'\\\\1*\'.str_repeat(\\\"\\n\\\", substr_count(\'\\\\2\', \\\"\\n\\\")) .\'*\\\\3\'\",\n" + - " $template_source);\n" + - "\n" + - " /* Pull out the literal blocks. */\n" + - " preg_match_all(\"!{$ldq}literal{$rdq}(.*?){$ldq}/literal{$rdq}!s\", $template_source, $match);\n" + - " $this->_literal_blocks = $match[1];\n" + - " $template_source = preg_replace(\"!{$ldq}literal{$rdq}(.*?){$ldq}/literal{$rdq}!s\",\n" + - " $this->quote_replace($this->left_delimiter.\'literal\'.$this->right_delimiter), $template_source);\n" + - "\n" + - " /* Pull out the php code blocks. */\n" + - " preg_match_all(\"!{$ldq}php{$rdq}(.*?){$ldq}/php{$rdq}!s\", $template_source, $match);\n" + - " $this->_php_blocks = $match[1];\n" + - " $template_source = preg_replace(\"!{$ldq}php{$rdq}(.*?){$ldq}/php{$rdq}!s\",\n" + - " $this->quote_replace($this->left_delimiter.\'php\'.$this->right_delimiter), $template_source);\n" + - "\n" + - " /* Gather all template tags. */\n" + - " preg_match_all(\"!{$ldq}\\s*(.*?)\\s*{$rdq}!s\", $template_source, $match);\n" + - " $template_tags = $match[1];\n" + - " /* Split content by template tags to obtain non-template content. */\n" + - " $text_blocks = preg_split(\"!{$ldq}.*?{$rdq}!s\", $template_source);\n" + - " \n" + - " /* loop through text blocks */\n" + - " for ($curr_tb = 0, $for_max = count($text_blocks); $curr_tb < $for_max; $curr_tb++) {\n" + - " /* match anything resembling php tags */\n" + - " if (preg_match_all(\'!(<\\?(?:\\w+|=)?|\\?>|language\\s*=\\s*[\\\"\\\']?php[\\\"\\\']?)!is\', $text_blocks[$curr_tb], $sp_match)) {\n" + - " /* replace tags with placeholders to prevent recursive replacements */\n" + - " $sp_match[1] = array_unique($sp_match[1]);\n" + - " usort($sp_match[1], \'_smarty_sort_length\');\n" + - " for ($curr_sp = 0, $for_max2 = count($sp_match[1]); $curr_sp < $for_max2; $curr_sp++) {\n" + - " $text_blocks[$curr_tb] = str_replace($sp_match[1][$curr_sp],\'%%%SMARTYSP\'.$curr_sp.\'%%%\',$text_blocks[$curr_tb]);\n" + - " }\n" + - " /* process each one */\n" + - " for ($curr_sp = 0, $for_max2 = count($sp_match[0]); $curr_sp < $for_max2; $curr_sp++) {\n" + - " if ($this->php_handling == SMARTY_PHP_PASSTHRU) {\n" + - " /* echo php contents */\n" + - " $text_blocks[$curr_tb] = str_replace(\'%%%SMARTYSP\'.$curr_sp.\'%%%\', \'\'.\"\\n\", $text_blocks[$curr_tb]);\n" + - " } else if ($this->php_handling == SMARTY_PHP_QUOTE) {\n" + - " /* quote php tags */\n" + - " $text_blocks[$curr_tb] = str_replace(\'%%%SMARTYSP\'.$curr_sp.\'%%%\', htmlspecialchars($sp_match[1][$curr_sp]), $text_blocks[$curr_tb]);\n" + - " } else if ($this->php_handling == SMARTY_PHP_REMOVE) {\n" + - " /* remove php tags */\n" + - " $text_blocks[$curr_tb] = str_replace(\'%%%SMARTYSP\'.$curr_sp.\'%%%\', \'\', $text_blocks[$curr_tb]);\n" + - " } else {\n" + - " /* SMARTY_PHP_ALLOW, but echo non php starting tags */\n" + - " $sp_match[1][$curr_sp] = preg_replace(\'%(<\\?(?!php|=|$))%i\', \'\'.\"\\n\", $sp_match[1][$curr_sp]);\n" + - " $text_blocks[$curr_tb] = str_replace(\'%%%SMARTYSP\'.$curr_sp.\'%%%\', $sp_match[1][$curr_sp], $text_blocks[$curr_tb]);\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - "\n" + - " /* Compile the template tags into PHP code. */\n" + - " $compiled_tags = array();\n" + - " for ($i = 0, $for_max = count($template_tags); $i < $for_max; $i++) {\n" + - " $this->_current_line_no += substr_count($text_blocks[$i], \"\\n\");\n" + - " $compiled_tags[] = $this->_compile_tag($template_tags[$i]);\n" + - " $this->_current_line_no += substr_count($template_tags[$i], \"\\n\");\n" + - " }\n" + - "\n" + - " $template_compiled = \'\';\n" + - "\n" + - " /* Interleave the compiled contents and text blocks to get the final result. */\n" + - " for ($i = 0, $for_max = count($compiled_tags); $i < $for_max; $i++) {\n" + - " $template_compiled .= $text_blocks[$i].$compiled_tags[$i];\n" + - " }\n" + - " $template_compiled .= $text_blocks[$i];\n" + - "\n" + - " /* Reformat data between \'strip\' and \'/strip\' tags, removing spaces, tabs and newlines. */\n" + - " if (preg_match_all(\"!{$ldq}strip{$rdq}.*?{$ldq}/strip{$rdq}!s\", $template_compiled, $match)) {\n" + - " $strip_tags = $match[0];\n" + - " $strip_tags_modified = preg_replace(\"!{$ldq}/?strip{$rdq}|[\\t ]+$|^[\\t ]+!m\", \'\', $strip_tags);\n" + - " $strip_tags_modified = preg_replace(\'![\\r\\n]+!m\', \'\', $strip_tags_modified);\n" + - " for ($i = 0, $for_max = count($strip_tags); $i < $for_max; $i++)\n" + - " $template_compiled = preg_replace(\"!{$ldq}strip{$rdq}.*?{$ldq}/strip{$rdq}!s\",\n" + - " $this->quote_replace($strip_tags_modified[$i]),\n" + - " $template_compiled, 1);\n" + - " }\n" + - "\n" + - " // remove \\n from the end of the file, if any\n" + - " if ($template_compiled{strlen($template_compiled) - 1} == \"\\n\" ) {\n" + - " $template_compiled = substr($template_compiled, 0, -1);\n" + - " }\n" + - "\n" + - " // run compiled template through postfilter functions\n" + - " if (count($this->_plugins[\'postfilter\']) > 0) {\n" + - " foreach ($this->_plugins[\'postfilter\'] as $filter_name => $postfilter) {\n" + - " if ($postfilter === false) continue;\n" + - " if ($postfilter[3] || function_exists($postfilter[0])) {\n" + - " $template_compiled = $postfilter[0]($template_compiled, $this);\n" + - " $this->_plugins[\'postfilter\'][$filter_name][3] = true;\n" + - " } else {\n" + - " $this->_trigger_plugin_error(\"Smarty plugin error: postfilter \'$filter_name\' is not implemented\");\n" + - " }\n" + - " }\n" + - " }\n" + - "\n" + - " // put header at the top of the compiled template\n" + - " $template_header = \"_version.\", created on \".strftime(\"%Y-%m-%d %H:%M:%S\").\"\\n\";\n" + - " $template_header .= \" compiled from \".$tpl_file.\" */ ?>\\n\";\n" + - "\n" + - " /* Emit code to load needed plugins. */\n" + - " if (count($this->_plugin_info)) {\n" + - " $plugins_code = \'_load_plugins(array(\';\n" + - " foreach ($this->_plugin_info as $plugin_type => $plugins) {\n" + - " foreach ($plugins as $plugin_name => $plugin_info) {\n" + - " $plugins_code .= \"\\narray(\'$plugin_type\', \'$plugin_name\', \'$plugin_info[0]\', $plugin_info[1], \";\n" + - " $plugins_code .= $plugin_info[2] ? \'true),\' : \'false),\';\n" + - " }\n" + - " }\n" + - " $plugins_code .= \")); ?>\";\n" + - " $template_header .= $plugins_code;\n" + - " $this->_plugin_info = array();\n" + - " }\n" + - "\n" + - " if ($this->_init_smarty_vars) {\n" + - " $template_header .= \"_assign_smarty_interface(); ?>\\n\";\n" + - " $this->_init_smarty_vars = false;\n" + - " }\n" + - "\n" + - " $template_compiled = $template_header . $template_compiled;\n" + - "\n" + - " return true;\n" + - " }\n" + - "\n" + - " /**\n" + - " * Compile a template tag\n" + - " *\n" + - " * @access public\n" + - " * @param $template_tag\n" + - " */\n" + - " function _compile_tag($template_tag)\n" + - " { \n" + - " \n" + - " /* Matched comment. */\n" + - " if ($template_tag{0} == \'*\' && $template_tag{strlen($template_tag) - 1} == \'*\')\n" + - " return \'\';\n" + - " \n" + - " /* Split tag into two three parts: command, command modifiers and the arguments. */\n" + - " if(! preg_match(\'/^(?:(\' . $this->_obj_call_regexp . \'|\' . $this->_var_regexp\n" + - " . \'|\' . $this->_reg_obj_regexp . \'|\\/?\' . $this->_func_regexp . \')(\' . $this->_mod_regexp . \'*))\n" + - " (?:\\s+(.*))?$\n" + - " /xs\', $template_tag, $match)) {\n" + - " $this->_syntax_error(\"unrecognized tag: $template_tag\", E_USER_ERROR, __FILE__, __LINE__);\n" + - " }\n" + - "\n" + - " $tag_command = $match[1];\n" + - " $tag_modifier = isset($match[2]) ? $match[2] : null;\n" + - " $tag_args = isset($match[3]) ? $match[3] : null;\n" + - " \n" + - " \n" + - " /* If the tag name is a variable or object, we process it. */\n" + - " if (preg_match(\'!^\' . $this->_obj_call_regexp . \'|\' . $this->_var_regexp . \'$!\', $tag_command)) {\n" + - " $return = $this->_parse_var_props($tag_command . $tag_modifier, $this->_parse_attrs($tag_args));\n" + - " if(isset($_tag_attrs[\'assign\'])) {\n" + - " return \"assign(\'\" . $this->_dequote($_tag_attrs[\'assign\']) . \"\', $return ); ?>\\n\"; \n" + - " } else {\n" + - " return \"\\n\";\n" + - " }\n" + - " }\n" + - " \n" + - " /* If the tag name is a registered object, we process it. */\n" + - " if (preg_match(\'!^\' . $this->_reg_obj_regexp . \'$!\', $tag_command)) {\n" + - " return $this->_compile_registered_object_tag($tag_command, $this->_parse_attrs($tag_args), $tag_modifier);\n" + - " }\n" + - "\n" + - " switch ($tag_command) {\n" + - " case \'include\':\n" + - " return $this->_compile_include_tag($tag_args);\n" + - "\n" + - " case \'include_php\':\n" + - " return $this->_compile_include_php_tag($tag_args);\n" + - "\n" + - " case \'if\':\n" + - " return $this->_compile_if_tag($tag_args);\n" + - "\n" + - " case \'else\':\n" + - " return \'\';\n" + - "\n" + - " case \'elseif\':\n" + - " return $this->_compile_if_tag($tag_args, true);\n" + - "\n" + - " case \'/if\':\n" + - " return \'\';\n" + - "\n" + - " case \'capture\':\n" + - " return $this->_compile_capture_tag(true, $tag_args);\n" + - "\n" + - " case \'/capture\':\n" + - " return $this->_compile_capture_tag(false);\n" + - "\n" + - " case \'ldelim\':\n" + - " return $this->left_delimiter;\n" + - "\n" + - " case \'rdelim\':\n" + - " return $this->right_delimiter;\n" + - "\n" + - " case \'section\':\n" + - " array_push($this->_sectionelse_stack, false);\n" + - " return $this->_compile_section_start($tag_args);\n" + - "\n" + - " case \'sectionelse\':\n" + - " $this->_sectionelse_stack[count($this->_sectionelse_stack)-1] = true;\n" + - " return \"\";\n" + - "\n" + - " case \'/section\':\n" + - " if (array_pop($this->_sectionelse_stack))\n" + - " return \"\";\n" + - " else\n" + - " return \"\";\n" + - "\n" + - " case \'foreach\':\n" + - " array_push($this->_foreachelse_stack, false);\n" + - " return $this->_compile_foreach_start($tag_args);\n" + - " break;\n" + - "\n" + - " case \'foreachelse\':\n" + - " $this->_foreachelse_stack[count($this->_foreachelse_stack)-1] = true;\n" + - " return \"\";\n" + - "\n" + - " case \'/foreach\':\n" + - " if (array_pop($this->_foreachelse_stack))\n" + - " return \"\";\n" + - " else\n" + - " return \"\";\n" + - "\n" + - " case \'config_load\':\n" + - " return $this->_compile_config_load_tag($tag_args);\n" + - "\n" + - " case \'strip\':\n" + - " case \'/strip\':\n" + - " return $this->left_delimiter.$tag_command.$this->right_delimiter;\n" + - "\n" + - " case \'literal\':\n" + - " list (,$literal_block) = each($this->_literal_blocks);\n" + - " $this->_current_line_no += substr_count($literal_block, \"\\n\");\n" + - " return \"\\n\";\n" + - "\n" + - " case \'php\':\n" + - " if ($this->security && !$this->security_settings[\'PHP_TAGS\']) {\n" + - " $this->_syntax_error(\"(secure mode) php tags not permitted\", E_USER_WARNING, __FILE__, __LINE__);\n" + - " return;\n" + - " }\n" + - " list (,$php_block) = each($this->_php_blocks);\n" + - " $this->_current_line_no += substr_count($php_block, \"\\n\");\n" + - " return \'\';\n" + - "\n" + - " case \'insert\':\n" + - " return $this->_compile_insert_tag($tag_args);\n" + - "\n" + - " default:\n" + - " if ($this->_compile_compiler_tag($tag_command, $tag_args, $output)) {\n" + - " return $output;\n" + - " } else if ($this->_compile_block_tag($tag_command, $tag_args, $tag_modifier, $output)) {\n" + - " return $output;\n" + - " } else {\n" + - " return $this->_compile_custom_tag($tag_command, $tag_args, $tag_modifier);\n" + - " }\n" + - " }\n" + - " }\n" + - "\n" + - "\n" + - " /**\n" + - " * compile the custom compiler tag\n" + - " *\n" + - " * @access public\n" + - " * @param $tag_command\n" + - " * @param $tag_args\n" + - " * @param $output\n" + - " */\n" + - " function _compile_compiler_tag($tag_command, $tag_args, &$output)\n" + - " {\n" + - " $found = false;\n" + - " $have_function = true;\n" + - "\n" + - " /*\n" + - " * First we check if the compiler function has already been registered\n" + - " * or loaded from a plugin file.\n" + - " */\n" + - " if (isset($this->_plugins[\'compiler\'][$tag_command])) {\n" + - " $found = true;\n" + - " $plugin_func = $this->_plugins[\'compiler\'][$tag_command][0];\n" + - " if (!function_exists($plugin_func)) {\n" + - " $message = \"compiler function \'$tag_command\' is not implemented\";\n" + - " $have_function = false;\n" + - " }\n" + - " }\n" + - " /*\n" + - " * Otherwise we need to load plugin file and look for the function\n" + - " * inside it.\n" + - " */\n" + - " else if ($plugin_file = $this->_get_plugin_filepath(\'compiler\', $tag_command)) {\n" + - " $found = true;\n" + - "\n" + - " include_once $plugin_file;\n" + - "\n" + - " $plugin_func = \'smarty_compiler_\' . $tag_command;\n" + - " if (!function_exists($plugin_func)) {\n" + - " $message = \"plugin function $plugin_func() not found in $plugin_file\\n\";\n" + - " $have_function = false;\n" + - " } else {\n" + - " $this->_plugins[\'compiler\'][$tag_command] = array($plugin_func, null, null);\n" + - " }\n" + - " }\n" + - "\n" + - " /*\n" + - " * True return value means that we either found a plugin or a\n" + - " * dynamically registered function. False means that we didn\'t and the\n" + - " * compiler should now emit code to load custom function plugin for this\n" + - " * tag.\n" + - " */\n" + - " if ($found) {\n" + - " if ($have_function) {\n" + - " $output = \'\';\n" + - " } else {\n" + - " $this->_syntax_error($message, E_USER_WARNING, __FILE__, __LINE__);\n" + - " }\n" + - " return true;\n" + - " } else {\n" + - " return false;\n" + - " }\n" + - " }\n" + - "\n" + - "\n" + - " /**\n" + - " * compile block function tag\n" + - " *\n" + - " * @access public\n" + - " * @param $tag_command\n" + - " * @param $tag_args\n" + - " * @param $tag_modifier\n" + - " * @param $output\n" + - " */\n" + - " function _compile_block_tag($tag_command, $tag_args, $tag_modifier, &$output)\n" + - " {\n" + - " if ($tag_command{0} == \'/\') {\n" + - " $start_tag = false;\n" + - " $tag_command = substr($tag_command, 1);\n" + - " } else\n" + - " $start_tag = true;\n" + - "\n" + - " $found = false;\n" + - " $have_function = true;\n" + - "\n" + - " /*\n" + - " * First we check if the block function has already been registered\n" + - " * or loaded from a plugin file.\n" + - " */\n" + - " if (isset($this->_plugins[\'block\'][$tag_command])) {\n" + - " $found = true;\n" + - " $plugin_func = $this->_plugins[\'block\'][$tag_command][0];\n" + - " if (!function_exists($plugin_func)) {\n" + - " $message = \"block function \'$tag_command\' is not implemented\";\n" + - " $have_function = false;\n" + - " }\n" + - " }\n" + - " /*\n" + - " * Otherwise we need to load plugin file and look for the function\n" + - " * inside it.\n" + - " */\n" + - " else if ($plugin_file = $this->_get_plugin_filepath(\'block\', $tag_command)) {\n" + - " $found = true;\n" + - "\n" + - " include_once $plugin_file;\n" + - "\n" + - " $plugin_func = \'smarty_block_\' . $tag_command;\n" + - " if (!function_exists($plugin_func)) {\n" + - " $message = \"plugin function $plugin_func() not found in $plugin_file\\n\";\n" + - " $have_function = false;\n" + - " } else {\n" + - " $this->_plugins[\'block\'][$tag_command] = array($plugin_func, null, null);\n" + - " }\n" + - " }\n" + - "\n" + - " if (!$found) {\n" + - " return false;\n" + - " } else if (!$have_function) {\n" + - " $this->_syntax_error($message, E_USER_WARNING, __FILE__, __LINE__);\n" + - " return true;\n" + - " }\n" + - "\n" + - " /*\n" + - " * Even though we\'ve located the plugin function, compilation\n" + - " * happens only once, so the plugin will still need to be loaded\n" + - " * at runtime for future requests.\n" + - " */\n" + - " $this->_add_plugin(\'block\', $tag_command);\n" + - "\n" + - " if ($start_tag) {\n" + - " $arg_list = array();\n" + - " $attrs = $this->_parse_attrs($tag_args);\n" + - " foreach ($attrs as $arg_name => $arg_value) {\n" + - " if (is_bool($arg_value))\n" + - " $arg_value = $arg_value ? \'true\' : \'false\';\n" + - " $arg_list[] = \"\'$arg_name\' => $arg_value\";\n" + - " }\n" + - "\n" + - " $output = \"_tag_stack[] = array(\'$tag_command\', array(\".implode(\',\', (array)$arg_list).\")); \\$this->_plugins[\'block\'][\'$tag_command\'][0](array(\".implode(\',\', (array)$arg_list).\"), null, \\$this); ob_start(); ?>\";\n" + - " } else {\n" + - " $output = \"_block_content = ob_get_contents(); ob_end_clean(); \";\n" + - " $out_tag_text = \"\\$this->_plugins[\'block\'][\'$tag_command\'][0](\\$this->_tag_stack[count(\\$this->_tag_stack)-1][1], \\$this->_block_content, \\$this)\";\n" + - " if($tag_modifier != \'\') {\n" + - " $this->_parse_modifiers($out_tag_text, $tag_modifier);\n" + - " }\n" + - " $output .= \'echo \' . $out_tag_text . \';\';\n" + - " $output .= \" array_pop(\\$this->_tag_stack); ?>\";\n" + - " }\n" + - "\n" + - " return true;\n" + - " }\n" + - "\n" + - "\n" + - " /**\n" + - " * compile custom function tag\n" + - " *\n" + - " * @access public\n" + - " * @param $tag_command\n" + - " * @param $tag_args\n" + - " * @param $tag_modifier\n" + - " */\n" + - " function _compile_custom_tag($tag_command, $tag_args, $tag_modifier)\n" + - " {\n" + - " $this->_add_plugin(\'function\', $tag_command);\n" + - "\n" + - " $arg_list = array();\n" + - " $attrs = $this->_parse_attrs($tag_args);\n" + - " foreach ($attrs as $arg_name => $arg_value) {\n" + - " if (is_bool($arg_value))\n" + - " $arg_value = $arg_value ? \'true\' : \'false\';\n" + - " $arg_list[] = \"\'$arg_name\' => $arg_value\";\n" + - " }\n" + - " \n" + - " $return = \"\\$this->_plugins[\'function\'][\'$tag_command\'][0](array(\".implode(\',\', (array)$arg_list).\"), \\$this)\";\n" + - " \n" + - " if($tag_modifier != \'\') {\n" + - " $this->_parse_modifiers($return, $tag_modifier);\n" + - " }\n" + - " \n" + - " return \'\\n\";\n" + - " }\n" + - "\n" + - " /**\n" + - " * compile a registered object tag\n" + - " *\n" + - " * @access public\n" + - " * @param $tag_command\n" + - " * @param $attrs\n" + - " * @param $tag_modifier\n" + - " */\n" + - " function _compile_registered_object_tag($tag_command, $attrs, $tag_modifier)\n" + - " {\n" + - " list($object, $obj_comp) = explode(\'->\', $tag_command);\n" + - "\n" + - " $arg_list = array();\n" + - " if(count($attrs)) {\n" + - " $_assign_var = false;\n" + - " foreach ($attrs as $arg_name => $arg_value) {\n" + - " if($arg_name == \'assign\') {\n" + - " $_assign_var = $arg_value;\n" + - " unset($attrs[\'assign\']);\n" + - " continue;\n" + - " }\n" + - " if (is_bool($arg_value))\n" + - " $arg_value = $arg_value ? \'true\' : \'false\';\n" + - " $arg_list[] = \"\'$arg_name\' => $arg_value\";\n" + - " }\n" + - " }\n" + - " \n" + - " if(!is_object($this->_reg_objects[$object][0])) {\n" + - " $this->_trigger_fatal_error(\"registered \'$object\' is not an object\");\n" + - " } elseif(!empty($this->_reg_objects[$object][1]) && !in_array($obj_comp, $this->_reg_objects[$object][1])) {\n" + - " $this->_trigger_fatal_error(\"\'$obj_comp\' is not a registered component of object \'$object\'\");\n" + - " } elseif(method_exists($this->_reg_objects[$object][0], $obj_comp)) {\n" + - " // method\n" + - " if($this->_reg_objects[$object][2]) {\n" + - " // smarty object argument format\n" + - " $return = \"\\$this->_reg_objects[\'$object\'][0]->$obj_comp(array(\".implode(\',\', (array)$arg_list).\"), \\$this)\";\n" + - " } else {\n" + - " // traditional argument format\n" + - " $return = \"\\$this->_reg_objects[\'$object\'][0]->$obj_comp(\".implode(\',\', array_values($attrs)).\")\";\n" + - " }\n" + - " } else {\n" + - " // property\n" + - " $return = \"\\$this->_reg_objects[\'$object\'][0]->$obj_comp\";\n" + - " }\n" + - " \n" + - " if($tag_modifier != \'\') {\n" + - " $this->_parse_modifiers($return, $tag_modifier);\n" + - " }\n" + - " \n" + - " if($_assign_var) {\n" + - " return \"assign(\'\" . $this->_dequote($_assign_var) .\"\', $return); ?>\\n\";\n" + - " } else {\n" + - " return \'\\n\";\n" + - " }\n" + - " }\n" + - " \n" + - " \n" + - "\n" + - " /**\n" + - " * Compile {insert ...} tag\n" + - " *\n" + - " * @access public\n" + - " * @param $tag_args\n" + - " */\n" + - " function _compile_insert_tag($tag_args)\n" + - " {\n" + - " $attrs = $this->_parse_attrs($tag_args);\n" + - " $name = $this->_dequote($attrs[\'name\']);\n" + - "\n" + - " if (empty($name)) {\n" + - " $this->_syntax_error(\"missing insert name\", E_USER_ERROR, __FILE__, __LINE__);\n" + - " }\n" + - "\n" + - " if (!empty($attrs[\'script\'])) {\n" + - " $delayed_loading = true;\n" + - " } else {\n" + - " $delayed_loading = false; \n" + - " }\n" + - "\n" + - " foreach ($attrs as $arg_name => $arg_value) {\n" + - " if (is_bool($arg_value))\n" + - " $arg_value = $arg_value ? \'true\' : \'false\';\n" + - " $arg_list[] = \"\'$arg_name\' => $arg_value\";\n" + - " }\n" + - "\n" + - " $this->_add_plugin(\'insert\', $name, $delayed_loading);\n" + - "\n" + - " return \"_run_insert_handler(array(\".implode(\', \', (array)$arg_list).\")); ?>\\n\";\n" + - " }\n" + - "\n" + - "\n" + - " /**\n" + - " * Compile {config_load ...} tag\n" + - " *\n" + - " * @access public\n" + - " * @param $tag_args\n" + - " */\n" + - " function _compile_config_load_tag($tag_args)\n" + - " {\n" + - " $attrs = $this->_parse_attrs($tag_args);\n" + - "\n" + - " if (empty($attrs[\'file\'])) {\n" + - " $this->_syntax_error(\"missing \'file\' attribute in config_load tag\", E_USER_ERROR, __FILE__, __LINE__);\n" + - " }\n" + - "\n" + - " if (empty($attrs[\'section\'])) {\n" + - " $attrs[\'section\'] = \'null\';\n" + - " }\n" + - "\n" + - " if (isset($attrs[\'scope\'])) {\n" + - " $scope = @$this->_dequote($attrs[\'scope\']);\r\n" + - " if ($scope != \'local\' &&\r\n" + - " $scope != \'parent\' &&\r\n" + - " $scope != \'global\') {\r\n" + - " $this->_syntax_error(\"invalid \'scope\' attribute value\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + - " }\r\n" + - " } else {\r\n" + - " if (isset($attrs[\'global\']) && $attrs[\'global\'])\r\n" + - " $scope = \'parent\';\r\n" + - " else\r\n" + - " $scope = \'local\';\r\n" + - " }\r\n" + - "\r\n" + - " return \'config_load(\' . $attrs[\'file\'] . \', \' . $attrs[\'section\'] . \", \'$scope\'); ?>\";\r\n" + - " }\r\n" + - "\r\n" + - "\r\n" + - " /**\r\n" + - " * Compile {include ...} tag\r\n" + - " *\r\n" + - " * @access public\r\n" + - " * $param $tag_args\r\n" + - " */\r\n" + - " function _compile_include_tag($tag_args)\r\n" + - " {\r\n" + - " $attrs = $this->_parse_attrs($tag_args);\r\n" + - " $arg_list = array();\r\n" + - "\r\n" + - " if (empty($attrs[\'file\'])) {\r\n" + - " $this->_syntax_error(\"missing \'file\' attribute in include tag\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + - " }\r\n" + - "\r\n" + - " foreach ($attrs as $arg_name => $arg_value) {\r\n" + - " if ($arg_name == \'file\') {\r\n" + - " $include_file = $arg_value;\r\n" + - " continue;\r\n" + - " } else if ($arg_name == \'assign\') {\r\n" + - " $assign_var = $arg_value;\r\n" + - " continue;\r\n" + - " }\r\n" + - " if (is_bool($arg_value))\r\n" + - " $arg_value = $arg_value ? \'true\' : \'false\';\r\n" + - " $arg_list[] = \"\'$arg_name\' => $arg_value\";\r\n" + - " }\r\n" + - "\r\n" + - " $output = \'_tpl_vars;\\n\" .\r\n" + - " \"\\$this->_smarty_include(\".$include_file.\", array(\".implode(\',\', (array)$arg_list).\"));\\n\" .\r\n" + - " \"\\$this->_tpl_vars = \\$_smarty_tpl_vars;\\n\" .\r\n" + - " \"unset(\\$_smarty_tpl_vars);\\n\";\r\n" + - "\r\n" + - " if (isset($assign_var)) {\r\n" + - " $output .= \"\\$this->assign(\" . $assign_var . \", ob_get_contents()); ob_end_clean();\\n\";\r\n" + - " }\r\n" + - "\r\n" + - " $output .= \' ?>\';\r\n" + - "\r\n" + - " return $output;\r\n" + - "\r\n" + - " }\r\n" + - "\r\n" + - " /**\r\n" + - " * Compile {include ...} tag\r\n" + - " *\r\n" + - " * @access public\r\n" + - " * @param $tag_args\r\n" + - " */\r\n" + - " function _compile_include_php_tag($tag_args)\r\n" + - " {\r\n" + - " $attrs = $this->_parse_attrs($tag_args);\r\n" + - "\r\n" + - " if (empty($attrs[\'file\'])) {\r\n" + - " $this->_syntax_error(\"missing \'file\' attribute in include_php tag\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + - " }\r\n" + - "\r\n" + - " $assign_var = $this->_dequote($attrs[\'assign\']);\r\n" + - "\r\n" + - " $once_var = ( $attrs[\'once\'] === false ) ? \'false\' : \'true\';\r\n" + - "\r\n" + - " foreach($attrs as $arg_name => $arg_value) {\r\n" + - " if($arg_name != \'file\' AND $arg_name != \'once\' AND $arg_name != \'assign\') {\r\n" + - " if(is_bool($arg_value))\r\n" + - " $arg_value = $arg_value ? \'true\' : \'false\';\r\n" + - " $arg_list[] = \"\'$arg_name\' => $arg_value\";\r\n" + - " }\r\n" + - " }\r\n" + - "\r\n" + - " $output =\r\n" + - " \"_smarty_include_php($attrs[file], \'$assign_var\', $once_var, \" .\r\n" + - " \"array(\".implode(\',\', (array)$arg_list).\")); ?>\";\r\n" + - " \r\n" + - " return $output;\r\n" + - " }\r\n" + - " \r\n" + - "\r\n" + - " /**\r\n" + - " * Compile {section ...} tag\r\n" + - " *\r\n" + - " * @access public\r\n" + - " * @param $tag_args\r\n" + - " */\r\n" + - " function _compile_section_start($tag_args)\r\n" + - " {\r\n" + - " $attrs = $this->_parse_attrs($tag_args);\r\n" + - " $arg_list = array();\r\n" + - "\r\n" + - " $output = \'_syntax_error(\"missing section name\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + - " }\r\n" + - "\r\n" + - " $output .= \"if (isset(\\$this->_sections[$section_name])) unset(\\$this->_sections[$section_name]);\\n\";\r\n" + - " $section_props = \"\\$this->_sections[$section_name]\";\r\n" + - "\r\n" + - " foreach ($attrs as $attr_name => $attr_value) {\r\n" + - " switch ($attr_name) {\r\n" + - " case \'loop\':\r\n" + - " $output .= \"{$section_props}[\'loop\'] = is_array($attr_value) ? count($attr_value) : max(0, (int)$attr_value);\\n\";\r\n" + - " break;\r\n" + - "\r\n" + - " case \'show\':\r\n" + - " if (is_bool($attr_value))\r\n" + - " $show_attr_value = $attr_value ? \'true\' : \'false\';\r\n" + - " else\r\n" + - " $show_attr_value = \"(bool)$attr_value\";\r\n" + - " $output .= \"{$section_props}[\'show\'] = $show_attr_value;\\n\";\r\n" + - " break;\r\n" + - "\r\n" + - " case \'name\':\r\n" + - " $output .= \"{$section_props}[\'$attr_name\'] = $attr_value;\\n\";\r\n" + - " break;\r\n" + - "\r\n" + - " case \'max\':\r\n" + - " case \'start\':\r\n" + - " $output .= \"{$section_props}[\'$attr_name\'] = (int)$attr_value;\\n\";\r\n" + - " break;\r\n" + - "\r\n" + - " case \'step\':\r\n" + - " $output .= \"{$section_props}[\'$attr_name\'] = ((int)$attr_value) == 0 ? 1 : (int)$attr_value;\\n\";\r\n" + - " break;\r\n" + - "\r\n" + - " default:\r\n" + - " $this->_syntax_error(\"unknown section attribute - \'$attr_name\'\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + - " break;\r\n" + - " }\r\n" + - " }\r\n" + - "\r\n" + - " if (!isset($attrs[\'show\']))\r\n" + - " $output .= \"{$section_props}[\'show\'] = true;\\n\";\r\n" + - "\r\n" + - " if (!isset($attrs[\'loop\']))\r\n" + - " $output .= \"{$section_props}[\'loop\'] = 1;\\n\";\r\n" + - "\r\n" + - " if (!isset($attrs[\'max\']))\r\n" + - " $output .= \"{$section_props}[\'max\'] = {$section_props}[\'loop\'];\\n\";\r\n" + - " else\r\n" + - " $output .= \"if ({$section_props}[\'max\'] < 0)\\n\" .\r\n" + - " \" {$section_props}[\'max\'] = {$section_props}[\'loop\'];\\n\";\r\n" + - "\r\n" + - " if (!isset($attrs[\'step\']))\r\n" + - " $output .= \"{$section_props}[\'step\'] = 1;\\n\";\r\n" + - "\r\n" + - " if (!isset($attrs[\'start\']))\r\n" + - " $output .= \"{$section_props}[\'start\'] = {$section_props}[\'step\'] > 0 ? 0 : {$section_props}[\'loop\']-1;\\n\";\r\n" + - " else {\r\n" + - " $output .= \"if ({$section_props}[\'start\'] < 0)\\n\" .\r\n" + - " \" {$section_props}[\'start\'] = max({$section_props}[\'step\'] > 0 ? 0 : -1, {$section_props}[\'loop\'] + {$section_props}[\'start\']);\\n\" .\r\n" + - " \"else\\n\" .\r\n" + - " \" {$section_props}[\'start\'] = min({$section_props}[\'start\'], {$section_props}[\'step\'] > 0 ? {$section_props}[\'loop\'] : {$section_props}[\'loop\']-1);\\n\";\r\n" + - " }\r\n" + - "\r\n" + - " $output .= \"if ({$section_props}[\'show\']) {\\n\";\r\n" + - " if (!isset($attrs[\'start\']) && !isset($attrs[\'step\']) && !isset($attrs[\'max\'])) {\r\n" + - " $output .= \" {$section_props}[\'total\'] = {$section_props}[\'loop\'];\\n\";\r\n" + - " } else {\r\n" + - " $output .= \" {$section_props}[\'total\'] = min(ceil(({$section_props}[\'step\'] > 0 ? {$section_props}[\'loop\'] - {$section_props}[\'start\'] : {$section_props}[\'start\']+1)/abs({$section_props}[\'step\'])), {$section_props}[\'max\']);\\n\";\r\n" + - " }\r\n" + - " $output .= \" if ({$section_props}[\'total\'] == 0)\\n\" .\r\n" + - " \" {$section_props}[\'show\'] = false;\\n\" .\r\n" + - " \"} else\\n\" .\r\n" + - " \" {$section_props}[\'total\'] = 0;\\n\";\r\n" + - "\r\n" + - " $output .= \"if ({$section_props}[\'show\']):\\n\";\r\n" + - " $output .= \"\r\n" + - " for ({$section_props}[\'index\'] = {$section_props}[\'start\'], {$section_props}[\'iteration\'] = 1;\r\n" + - " {$section_props}[\'iteration\'] <= {$section_props}[\'total\'];\r\n" + - " {$section_props}[\'index\'] += {$section_props}[\'step\'], {$section_props}[\'iteration\']++):\\n\";\r\n" + - " $output .= \"{$section_props}[\'rownum\'] = {$section_props}[\'iteration\'];\\n\";\r\n" + - " $output .= \"{$section_props}[\'index_prev\'] = {$section_props}[\'index\'] - {$section_props}[\'step\'];\\n\";\r\n" + - " $output .= \"{$section_props}[\'index_next\'] = {$section_props}[\'index\'] + {$section_props}[\'step\'];\\n\";\r\n" + - " $output .= \"{$section_props}[\'first\'] = ({$section_props}[\'iteration\'] == 1);\\n\";\r\n" + - " $output .= \"{$section_props}[\'last\'] = ({$section_props}[\'iteration\'] == {$section_props}[\'total\']);\\n\";\r\n" + - "\r\n" + - " $output .= \"?>\";\r\n" + - "\r\n" + - " return $output;\r\n" + - " }\r\n" + - "\r\n" + - " \r\n" + - " /**\r\n" + - " * Compile {foreach ...} tag.\r\n" + - " *\r\n" + - " * @access public\r\n" + - " * @param $tag_args\r\n" + - " */\r\n" + - " function _compile_foreach_start($tag_args)\r\n" + - " {\r\n" + - " $attrs = $this->_parse_attrs($tag_args);\r\n" + - " $arg_list = array();\r\n" + - "\r\n" + - " if (empty($attrs[\'from\'])) {\r\n" + - " $this->_syntax_error(\"missing \'from\' attribute\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + - " }\r\n" + - "\r\n" + - " if (empty($attrs[\'item\'])) {\r\n" + - " $this->_syntax_error(\"missing \'item\' attribute\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + - " }\r\n" + - "\r\n" + - " $from = $attrs[\'from\'];\r\n" + - " $item = $this->_dequote($attrs[\'item\']);\r\n" + - " if (isset($attrs[\'name\']))\r\n" + - " $name = $attrs[\'name\'];\r\n" + - "\r\n" + - " $output = \'_foreach[$name])) unset(\\$this->_foreach[$name]);\\n\";\r\n" + - " $foreach_props = \"\\$this->_foreach[$name]\";\r\n" + - " }\r\n" + - "\r\n" + - " $key_part = \'\';\r\n" + - "\r\n" + - " foreach ($attrs as $attr_name => $attr_value) {\r\n" + - " switch ($attr_name) {\r\n" + - " case \'key\':\r\n" + - " $key = $this->_dequote($attrs[\'key\']);\r\n" + - " $key_part = \"\\$this->_tpl_vars[\'$key\'] => \";\r\n" + - " break;\r\n" + - "\r\n" + - " case \'name\':\r\n" + - " $output .= \"{$foreach_props}[\'$attr_name\'] = $attr_value;\\n\";\r\n" + - " break;\r\n" + - " }\r\n" + - " }\r\n" + - "\r\n" + - " if (isset($name)) {\r\n" + - " $output .= \"{$foreach_props}[\'total\'] = count((array)$from);\\n\";\r\n" + - " $output .= \"{$foreach_props}[\'show\'] = {$foreach_props}[\'total\'] > 0;\\n\";\r\n" + - " $output .= \"if ({$foreach_props}[\'show\']):\\n\";\r\n" + - " $output .= \"{$foreach_props}[\'iteration\'] = 0;\\n\";\r\n" + - " $output .= \" foreach ((array)$from as $key_part\\$this->_tpl_vars[\'$item\']):\\n\";\r\n" + - " $output .= \" {$foreach_props}[\'iteration\']++;\\n\";\r\n" + - " $output .= \" {$foreach_props}[\'first\'] = ({$foreach_props}[\'iteration\'] == 1);\\n\";\r\n" + - " $output .= \" {$foreach_props}[\'last\'] = ({$foreach_props}[\'iteration\'] == {$foreach_props}[\'total\']);\\n\";\r\n" + - " } else {\r\n" + - " $output .= \"if (count((array)$from)):\\n\";\r\n" + - " $output .= \" foreach ((array)$from as $key_part\\$this->_tpl_vars[\'$item\']):\\n\";\r\n" + - " }\r\n" + - " $output .= \'?>\';\r\n" + - "\r\n" + - " return $output;\r\n" + - " }\r\n" + - "\r\n" + - "\r\n" + - " /**\r\n" + - " * Compile {capture} .. {/capture} tags\r\n" + - " *\r\n" + - " * @access public\r\n" + - " * @param $start\r\n" + - " * @param $tag_args\r\n" + - " */\r\n" + - " function _compile_capture_tag($start, $tag_args = \'\')\r\n" + - " {\r\n" + - " $attrs = $this->_parse_attrs($tag_args);\r\n" + - "\r\n" + - " if ($start) {\r\n" + - " if (isset($attrs[\'name\']))\r\n" + - " $buffer = $attrs[\'name\'];\r\n" + - " else\r\n" + - " $buffer = \"\'default\'\";\r\n" + - "\r\n" + - " $output = \"\";\r\n" + - " $this->_capture_stack[] = $buffer;\r\n" + - " } else {\r\n" + - " $buffer = array_pop($this->_capture_stack);\r\n" + - " $output = \"_smarty_vars[\'capture\'][$buffer] = ob_get_contents(); ob_end_clean(); ?>\";\r\n" + - " }\r\n" + - "\r\n" + - " return $output;\r\n" + - " }\r\n" + - "\r\n" + - " /**\r\n" + - " * Compile {if ...} tag\r\n" + - " *\r\n" + - " * @access public\r\n" + - " * @param $tag_args\r\n" + - " * @param $elseif\r\n" + - " */\r\n" + - " function _compile_if_tag($tag_args, $elseif = false)\r\n" + - " {\r\n" + - "\r\n" + - " /* Tokenize args for \'if\' tag. */\r\n" + - " preg_match_all(\'/(?>\r\n" + - " \' . $this->_obj_call_regexp . \'(?:\' . $this->_mod_regexp . \'*) | # valid object call\r\n" + - " \' . $this->_var_regexp . \'(?:\' . $this->_mod_regexp . \'*) | # public or quoted string\r\n" + - " \\-?\\d+|!==|<=>|==|!=|<=|>=|\\&\\&|\\|\\||\\(|\\)|,|\\!|\\^|=|<|>|\\||\\%|\\+|\\-|\\/|\\* | # valid non-word token\r\n" + - " \\b\\w+\\b | # valid word token\r\n" + - " \\S+ # anything else\r\n" + - " )/x\', $tag_args, $match);\r\n" + - " \r\n" + - " $tokens = $match[0];\r\n" + - " \r\n" + - " // make sure we have balanced parenthesis\r\n" + - " $token_count = array_count_values($tokens);\r\n" + - " if(isset($token_count[\'(\']) && $token_count[\'(\'] != $token_count[\')\']) {\r\n" + - " $this->_syntax_error(\"unbalanced parenthesis in if statement\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + - " }\r\n" + - " \r\n" + - " $is_arg_stack = array();\r\n" + - "\r\n" + - " for ($i = 0; $i < count($tokens); $i++) {\r\n" + - "\r\n" + - " $token = &$tokens[$i];\r\n" + - " \r\n" + - " switch (strtolower($token)) {\r\n" + - " case \'!\':\r\n" + - " case \'%\':\r\n" + - " case \'!==\':\r\n" + - " case \'==\':\r\n" + - " case \'>\':\r\n" + - " case \'<\':\r\n" + - " case \'!=\':\r\n" + - " case \'<=\':\r\n" + - " case \'>=\':\r\n" + - " case \'&&\':\r\n" + - " case \'||\':\r\n" + - " case \'|\':\r\n" + - " case \'^\':\r\n" + - " case \'&\':\r\n" + - " case \'~\':\r\n" + - " case \')\':\r\n" + - " case \',\':\r\n" + - " case \'+\':\r\n" + - " case \'-\':\r\n" + - " case \'*\':\r\n" + - " case \'/\':\r\n" + - " break; \r\n" + - "\r\n" + - " case \'eq\':\r\n" + - " $token = \'==\';\r\n" + - " break;\r\n" + - "\r\n" + - " case \'ne\':\r\n" + - " case \'neq\':\r\n" + - " $token = \'!=\';\r\n" + - " break;\r\n" + - "\r\n" + - " case \'lt\':\r\n" + - " $token = \'<\';\r\n" + - " break;\r\n" + - "\r\n" + - " case \'le\':\r\n" + - " case \'lte\':\r\n" + - " $token = \'<=\';\r\n" + - " break;\r\n" + - "\r\n" + - " case \'gt\':\r\n" + - " $token = \'>\';\r\n" + - " break;\r\n" + - "\r\n" + - " case \'ge\':\r\n" + - " case \'gte\':\r\n" + - " $token = \'>=\';\r\n" + - " break;\r\n" + - "\r\n" + - " case \'and\':\r\n" + - " $token = \'&&\';\r\n" + - " break;\r\n" + - "\r\n" + - " case \'or\':\r\n" + - " $token = \'||\';\r\n" + - " break;\r\n" + - "\r\n" + - " case \'not\':\r\n" + - " $token = \'!\';\r\n" + - " break;\r\n" + - "\r\n" + - " case \'mod\':\r\n" + - " $token = \'%\';\r\n" + - " break;\r\n" + - "\r\n" + - " case \'(\':\r\n" + - " array_push($is_arg_stack, $i);\r\n" + - " break;\r\n" + - " \r\n" + - " case \'is\':\r\n" + - " /* If last token was a \')\', we operate on the parenthesized\r\n" + - " expression. The start of the expression is on the stack.\r\n" + - " Otherwise, we operate on the last encountered token. */\r\n" + - " if ($tokens[$i-1] == \')\')\r\n" + - " $is_arg_start = array_pop($is_arg_stack);\r\n" + - " else\r\n" + - " $is_arg_start = $i-1;\r\n" + - " /* Construct the argument for \'is\' expression, so it knows\r\n" + - " what to operate on. */\r\n" + - " $is_arg = implode(\' \', array_slice($tokens, $is_arg_start, $i - $is_arg_start));\r\n" + - " \r\n" + - " /* Pass all tokens from next one until the end to the\r\n" + - " \'is\' expression parsing function. The function will\r\n" + - " return modified tokens, where the first one is the result\r\n" + - " of the \'is\' expression and the rest are the tokens it\r\n" + - " didn\'t touch. */ \r\n" + - " $new_tokens = $this->_parse_is_expr($is_arg, array_slice($tokens, $i+1));\r\n" + - " \r\n" + - " /* Replace the old tokens with the new ones. */\r\n" + - " array_splice($tokens, $is_arg_start, count($tokens), $new_tokens);\r\n" + - "\r\n" + - " /* Adjust argument start so that it won\'t change from the\r\n" + - " current position for the next iteration. */\r\n" + - " $i = $is_arg_start;\r\n" + - " break;\r\n" + - " \r\n" + - " default:\r\n" + - " if(preg_match(\'!^\' . $this->_func_regexp . \'$!\', $token) ) {\r\n" + - " // function call \r\n" + - " if($this->security &&\r\n" + - " !in_array($token, $this->security_settings[\'IF_FUNCS\'])) {\r\n" + - " $this->_syntax_error(\"(secure mode) \'$token\' not allowed in if statement\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + - " } \r\n" + - " } elseif(preg_match(\'!^\' . $this->_var_regexp . \'(?:\' . $this->_mod_regexp . \'*)$!\', $token)) {\r\n" + - " // variable\r\n" + - " $token = $this->_parse_var_props($token);\r\n" + - " } elseif(preg_match(\'!^\' . $this->_obj_call_regexp . \'(?:\' . $this->_mod_regexp . \'*)$!\', $token)) {\r\n" + - " // object\r\n" + - " $token = $this->_parse_var_props($token);\r\n" + - " } elseif(is_numeric($token)) {\r\n" + - " // number, skip it\r\n" + - " } else {\r\n" + - " $this->_syntax_error(\"unidentified token \'$token\'\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + - " }\r\n" + - " break;\r\n" + - " }\r\n" + - " }\r\n" + - " \r\n" + - " if ($elseif)\r\n" + - " return \'\';\r\n" + - " else\r\n" + - " return \'\';\r\n" + - " }\r\n" + - "\r\n" + - "\r\n" + - " /**\r\n" + - " * Parse is expression\r\n" + - " *\r\n" + - " * @access public\r\n" + - " * @param $is_arg\r\n" + - " * @param $tokens\r\n" + - " */\r\n" + - " function _parse_is_expr($is_arg, $tokens)\r\n" + - " {\r\n" + - " $expr_end = 0;\r\n" + - " $negate_expr = false;\r\n" + - "\r\n" + - " if (($first_token = array_shift($tokens)) == \'not\') {\r\n" + - " $negate_expr = true;\r\n" + - " $expr_type = array_shift($tokens);\r\n" + - " } else\r\n" + - " $expr_type = $first_token;\r\n" + - "\r\n" + - " switch ($expr_type) {\r\n" + - " case \'even\':\r\n" + - " if (@$tokens[$expr_end] == \'by\') {\r\n" + - " $expr_end++;\r\n" + - " $expr_arg = $tokens[$expr_end++];\r\n" + - " $expr = \"!(($is_arg / $expr_arg) % \" . $this->_parse_var_props($expr_arg) . \")\";\r\n" + - " } else\r\n" + - " $expr = \"!($is_arg % 2)\";\r\n" + - " break;\r\n" + - "\r\n" + - " case \'odd\':\r\n" + - " if (@$tokens[$expr_end] == \'by\') {\r\n" + - " $expr_end++;\r\n" + - " $expr_arg = $tokens[$expr_end++];\r\n" + - " $expr = \"(($is_arg / $expr_arg) % \". $this->_parse_var_props($expr_arg) . \")\";\r\n" + - " } else\r\n" + - " $expr = \"($is_arg % 2)\";\r\n" + - " break;\r\n" + - "\r\n" + - " case \'div\':\r\n" + - " if (@$tokens[$expr_end] == \'by\') {\r\n" + - " $expr_end++;\r\n" + - " $expr_arg = $tokens[$expr_end++];\r\n" + - " $expr = \"!($is_arg % \" . $this->_parse_var_props($expr_arg) . \")\";\r\n" + - " } else {\r\n" + - " $this->_syntax_error(\"expecting \'by\' after \'div\'\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + - " }\r\n" + - " break;\r\n" + - "\r\n" + - " default:\r\n" + - " $this->_syntax_error(\"unknown \'is\' expression - \'$expr_type\'\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + - " break;\r\n" + - " }\r\n" + - "\r\n" + - " if ($negate_expr) {\r\n" + - " $expr = \"!($expr)\";\r\n" + - " }\r\n" + - " \r\n" + - " array_splice($tokens, 0, $expr_end, $expr); \r\n" + - " \r\n" + - " return $tokens;\r\n" + - " }\r\n" + - "\r\n" + - "\r\n" + - " /**\r\n" + - " * Parse attribute string\r\n" + - " *\r\n" + - " * @access public\r\n" + - " * @param $tag_args\r\n" + - " * @param $quote\r\n" + - " */\r\n" + - " function _parse_attrs($tag_args, $quote = true)\r\n" + - " {\r\n" + - " \r\n" + - " /* Tokenize tag attributes. */\r\n" + - " preg_match_all(\'/(?:\' . $this->_obj_call_regexp . \'|\' . $this->_qstr_regexp . \' | (?>[^\"\\\'=\\s]+)\r\n" + - " )+ |\r\n" + - " [=]\r\n" + - " /x\', $tag_args, $match);\r\n" + - " $tokens = $match[0]; \r\n" + - " \r\n" + - " $attrs = array();\r\n" + - " /* Parse state:\r\n" + - " 0 - expecting attribute name\r\n" + - " 1 - expecting \'=\'\r\n" + - " 2 - expecting attribute value (not \'=\') */\r\n" + - " $state = 0;\r\n" + - " \r\n" + - " foreach ($tokens as $token) {\r\n" + - " switch ($state) {\r\n" + - " case 0:\r\n" + - " /* If the token is a valid identifier, we set attribute name\r\n" + - " and go to state 1. */\r\n" + - " if (preg_match(\'!^\\w+$!\', $token)) {\r\n" + - " $attr_name = $token;\r\n" + - " $state = 1;\r\n" + - " } else\r\n" + - " $this->_syntax_error(\"invalid attribute name - \'$token\'\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + - " break;\r\n" + - "\r\n" + - " case 1:\r\n" + - " /* If the token is \'=\', then we go to state 2. */\r\n" + - " if ($token == \'=\') {\r\n" + - " $state = 2;\r\n" + - " } else\r\n" + - " $this->_syntax_error(\"expecting \'=\' after attribute name \'$last_token\'\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + - " break;\r\n" + - "\r\n" + - " case 2:\r\n" + - " /* If token is not \'=\', we set the attribute value and go to\r\n" + - " state 0. */\r\n" + - " if ($token != \'=\') {\r\n" + - " /* We booleanize the token if it\'s a non-quoted possible\r\n" + - " boolean value. */\r\n" + - " if (preg_match(\'!^(on|yes|true)$!\', $token))\r\n" + - " $token = true;\r\n" + - " else if (preg_match(\'!^(off|no|false)$!\', $token))\r\n" + - " $token = false;\r\n" + - " /* If the token is just a string,\r\n" + - " we double-quote it. */\r\n" + - " else if (preg_match(\'!^\\w+$!\', $token)) {\r\n" + - " $token = \'\"\'.$token.\'\"\';\r\n" + - " }\r\n" + - "\r\n" + - " $attrs[$attr_name] = $token;\r\n" + - " $state = 0;\r\n" + - " } else\r\n" + - " $this->_syntax_error(\"\'=\' cannot be an attribute value\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + - " break;\r\n" + - " }\r\n" + - " $last_token = $token;\r\n" + - " }\r\n" + - "\r\n" + - " if($state != 0) {\r\n" + - " if($state == 1) {\r\n" + - " $this->_syntax_error(\"expecting \'=\' after attribute name \'$last_token\'\", E_USER_ERROR, __FILE__, __LINE__); \r\n" + - " } else {\r\n" + - " $this->_syntax_error(\"missing attribute value\", E_USER_ERROR, __FILE__, __LINE__); \r\n" + - " }\r\n" + - " }\r\n" + - " \r\n" + - " $this->_parse_vars_props($attrs);\r\n" + - "\r\n" + - " return $attrs;\r\n" + - " }\r\n" + - "\r\n" + - " /**\r\n" + - " * compile multiple variables and section properties tokens into\r\n" + - " * PHP code\r\n" + - " *\r\n" + - " * @access public\r\n" + - " * @param $tokens\r\n" + - " */\r\n" + - " function _parse_vars_props(&$tokens)\r\n" + - " {\r\n" + - " foreach($tokens as $key => $val) { \r\n" + - " $tokens[$key] = $this->_parse_var_props($val);\r\n" + - " }\r\n" + - " }\r\n" + - " \r\n" + - " /**\r\n" + - " * compile single variable and section properties token into\r\n" + - " * PHP code\r\n" + - " *\r\n" + - " * @access public\r\n" + - " * @param $val\r\n" + - " * @param $tag_attrs\r\n" + - " */\r\n" + - " function _parse_var_props($val, $tag_attrs = null)\r\n" + - " { \r\n" + - "\r\n" + - " $val = trim($val);\r\n" + - "\r\n" + - " if(preg_match(\'!^(\' . $this->_obj_call_regexp . \'|\' . $this->_dvar_regexp . \')(?:\' . $this->_mod_regexp . \'*)$!\', $val)) {\r\n" + - " // $ variable or object\r\n" + - " return $this->_parse_var($val, $tag_attrs);\r\n" + - " } \r\n" + - " elseif(preg_match(\'!^\' . $this->_db_qstr_regexp . \'(?:\' . $this->_mod_regexp . \'*)$!\', $val)) {\r\n" + - " // double quoted text\r\n" + - " preg_match(\'!^(\' . $this->_db_qstr_regexp . \')(\'. $this->_mod_regexp . \'*)$!\', $val, $match);\r\n" + - " $return = $this->_expand_quoted_text($match[1]);\r\n" + - " if($match[2] != \'\') {\r\n" + - " $this->_parse_modifiers($return, $match[2]);\r\n" + - " }\r\n" + - " return $return;\r\n" + - " } \r\n" + - " elseif(preg_match(\'!^\' . $this->_si_qstr_regexp . \'(?:\' . $this->_mod_regexp . \'*)$!\', $val)) {\r\n" + - " // single quoted text\r\n" + - " preg_match(\'!^(\' . $this->_si_qstr_regexp . \')(\'. $this->_mod_regexp . \'*)$!\', $val, $match);\r\n" + - " if($match[2] != \'\') {\r\n" + - " $this->_parse_modifiers($match[1], $match[2]);\r\n" + - " return $match[1];\r\n" + - " } \r\n" + - " } \r\n" + - " elseif(preg_match(\'!^\' . $this->_cvar_regexp . \'(?:\' . $this->_mod_regexp . \'*)$!\', $val)) {\r\n" + - " // config var\r\n" + - " return $this->_parse_conf_var($val);\r\n" + - " } \r\n" + - " elseif(preg_match(\'!^\' . $this->_svar_regexp . \'(?:\' . $this->_mod_regexp . \'*)$!\', $val)) {\r\n" + - " // section var\r\n" + - " return $this->_parse_section_prop($val);\r\n" + - " }\r\n" + - " elseif(!in_array($val, $this->_permitted_tokens) && !is_numeric($val)) {\r\n" + - " // literal string\r\n" + - " return $this->_expand_quoted_text(\'\"\' . $val .\'\"\');\r\n" + - " }\r\n" + - " return $val;\r\n" + - " }\r\n" + - "\r\n" + - " /**\r\n" + - " * expand quoted text with embedded variables\r\n" + - " *\r\n" + - " * @access public\r\n" + - " * @param $var_expr\r\n" + - " */\r\n" + - " function _expand_quoted_text($var_expr)\r\n" + - " {\r\n" + - " // if contains unescaped $, expand it\r\n" + - " if(preg_match_all(\'|(?_dvar_guts_regexp . \'|\', $var_expr, $match)) {\r\n" + - " rsort($match[0]);\r\n" + - " reset($match[0]);\r\n" + - " foreach($match[0] as $var) {\r\n" + - " $var_expr = str_replace ($var, \'\".\' . $this->_parse_var($var) . \'.\"\', $var_expr);\r\n" + - " }\r\n" + - " return preg_replace(\'!\\.\"\"|\"\"\\.!\', \'\', $var_expr);\r\n" + - " } else {\r\n" + - " return $var_expr;\r\n" + - " }\r\n" + - " }\r\n" + - " \r\n" + - " /**\r\n" + - " * parse variable expression into PHP code\r\n" + - " *\r\n" + - " * @access public\r\n" + - " * @param $var_expr\r\n" + - " */\r\n" + - " function _parse_var($var_expr)\r\n" + - " {\r\n" + - " \r\n" + - " preg_match(\'!(\' . $this->_obj_call_regexp . \'|\' . $this->_var_regexp . \')(\' . $this->_mod_regexp . \'*)$!\', $var_expr, $match);\r\n" + - " \r\n" + - " $var_ref = substr($match[1],1);\r\n" + - " $modifiers = $match[2];\r\n" + - " \r\n" + - " if(!empty($this->default_modifiers) && !preg_match(\'!(^|\\|)smarty:nodefaults($|\\|)!\',$modifiers)) {\r\n" + - " $_default_mod_string = implode(\'|\',(array)$this->default_modifiers);\r\n" + - " $modifiers = empty($modifiers) ? $_default_mod_string : $_default_mod_string . \'|\' . $modifiers;\r\n" + - " }\r\n" + - "\r\n" + - " // get [foo] and .foo and ->foo() pieces \r\n" + - " preg_match_all(\'!(?:^\\w+)|(?:\' . $this->_obj_ext_regexp . \')+(?:\' . $this->_obj_params_regexp . \')?|(?:\' . $this->_var_bracket_regexp . \')|\\.\\$?\\w+!\', $var_ref, $match); \r\n" + - " \r\n" + - " $indexes = $match[0];\r\n" + - " $var_name = array_shift($indexes);\r\n" + - " \r\n" + - " /* Handle $smarty.* variable references as a special case. */\r\n" + - " if ($var_name == \'smarty\') {\r\n" + - " /*\r\n" + - " * If the reference could be compiled, use the compiled output;\r\n" + - " * otherwise, fall back on the $smarty variable generated at\r\n" + - " * run-time.\r\n" + - " */\r\n" + - " if (($smarty_ref = $this->_compile_smarty_ref($indexes)) !== null) {\r\n" + - " $output = $smarty_ref;\r\n" + - " } else {\r\n" + - " $var_name = substr(array_shift($indexes), 1);\r\n" + - " $output = \"\\$this->_smarty_vars[\'$var_name\']\";\r\n" + - " }\r\n" + - " } else {\r\n" + - " $output = \"\\$this->_tpl_vars[\'$var_name\']\";\r\n" + - " }\r\n" + - "\r\n" + - " foreach ($indexes as $index) { \r\n" + - " if ($index{0} == \'[\') {\r\n" + - " $index = substr($index, 1, -1);\r\n" + - " if (is_numeric($index)) {\r\n" + - " $output .= \"[$index]\";\r\n" + - " } elseif ($index{0} == \'$\') {\r\n" + - " $output .= \"[\\$this->_tpl_vars[\'\" . substr($index, 1) . \"\']]\";\r\n" + - " } else {\r\n" + - " $parts = explode(\'.\', $index);\r\n" + - " $section = $parts[0];\r\n" + - " $section_prop = isset($parts[1]) ? $parts[1] : \'index\';\r\n" + - " $output .= \"[\\$this->_sections[\'$section\'][\'$section_prop\']]\";\r\n" + - " }\r\n" + - " } else if ($index{0} == \'.\') {\r\n" + - " if ($index{1} == \'$\')\r\n" + - " $output .= \"[\\$this->_tpl_vars[\'\" . substr($index, 2) . \"\']]\";\r\n" + - " else\r\n" + - " $output .= \"[\'\" . substr($index, 1) . \"\']\";\r\n" + - " } else if (substr($index,0,2) == \'->\') {\r\n" + - " if(substr($index,2,2) == \'__\') {\r\n" + - " $this->_syntax_error(\'call to internal object members is not allowed\', E_USER_ERROR, __FILE__, __LINE__);\r\n" + - " } elseif($this->security && substr($index,2,1) == \'_\') {\r\n" + - " $this->_syntax_error(\'(secure) call to private object member is not allowed\', E_USER_ERROR, __FILE__, __LINE__);\r\n" + - " } else {\r\n" + - " if(preg_match(\'!((?:\' . $this->_obj_ext_regexp . \')+)(\' . $this->_obj_params_regexp . \')?!\', $index, $match)) {\r\n" + - " if(!empty($match[2])) {\r\n" + - " // parse object parameters\r\n" + - " $index = str_replace($match[2], $this->_parse_parenth_args($match[2]), $index);\r\n" + - " }\r\n" + - " if(preg_match_all(\'!\' . $this->_dvar_regexp . \'!\', $match[1], $_dvar_match)) {\r\n" + - " // parse embedded variables\r\n" + - " $_match_replace = $match[1];\r\n" + - " foreach($_dvar_match[0] as $_curr_var) {\r\n" + - " $_match_replace = str_replace($_curr_var, \'{\' . $this->_parse_var($_curr_var) . \'}\', $_match_replace);\r\n" + - " }\r\n" + - " $index = str_replace($match[1], $_match_replace, $index);\r\n" + - " }\r\n" + - " }\r\n" + - " $output .= $index;\r\n" + - " }\r\n" + - " } else {\r\n" + - " $output .= $index;\r\n" + - " }\r\n" + - " }\r\n" + - "\r\n" + - " // look for variables imbedded in quoted strings, replace them\r\n" + - " if(preg_match(\'!\' . $this->_qstr_regexp . \'!\', $output, $match)) {\r\n" + - " $output = str_replace($match[0], $this->_expand_quoted_text($match[0]), $output);\r\n" + - " }\r\n" + - " \r\n" + - " $this->_parse_modifiers($output, $modifiers);\r\n" + - "\r\n" + - " return $output;\r\n" + - " }\r\n" + - "\r\n" + - " /**\r\n" + - " * parse arguments in function call parenthesis\r\n" + - " *\r\n" + - " * @access public\r\n" + - " * @param $parenth_args\r\n" + - " */\r\n" + - " function _parse_parenth_args($parenth_args)\r\n" + - " {\r\n" + - " preg_match_all(\'!\' . $this->_param_regexp . \'!\',$parenth_args, $match);\r\n" + - " $match = $match[0];\r\n" + - " rsort($match);\r\n" + - " reset($match); \r\n" + - " $orig_vals = $match;\r\n" + - " $this->_parse_vars_props($match);\r\n" + - " return str_replace($orig_vals, $match, $parenth_args);\r\n" + - " } \r\n" + - " \r\n" + - " /**\r\n" + - " * parse configuration variable expression into PHP code\r\n" + - " *\r\n" + - " * @access public\r\n" + - " * @param $conf_var_expr\r\n" + - " */\r\n" + - " function _parse_conf_var($conf_var_expr)\r\n" + - " {\r\n" + - " $parts = explode(\'|\', $conf_var_expr, 2);\r\n" + - " $var_ref = $parts[0];\r\n" + - " $modifiers = isset($parts[1]) ? $parts[1] : \'\';\r\n" + - "\r\n" + - " $var_name = substr($var_ref, 1, -1);\r\n" + - "\r\n" + - " $output = \"\\$this->_config[0][\'vars\'][\'$var_name\']\";\r\n" + - "\r\n" + - " $this->_parse_modifiers($output, $modifiers);\r\n" + - "\r\n" + - " return $output;\r\n" + - " }\r\n" + - "\r\n" + - "\r\n" + - " /**\r\n" + - " * parse section property expression into PHP code\r\n" + - " *\r\n" + - " * @access public\r\n" + - " * @param $section_prop_expr\r\n" + - " */\r\n" + - " function _parse_section_prop($section_prop_expr)\r\n" + - " {\r\n" + - " $parts = explode(\'|\', $section_prop_expr, 2);\r\n" + - " $var_ref = $parts[0];\r\n" + - " $modifiers = isset($parts[1]) ? $parts[1] : \'\';\r\n" + - "\r\n" + - " preg_match(\'!%(\\w+)\\.(\\w+)%!\', $var_ref, $match);\r\n" + - " $section_name = $match[1];\r\n" + - " $prop_name = $match[2];\r\n" + - "\r\n" + - " $output = \"\\$this->_sections[\'$section_name\'][\'$prop_name\']\";\r\n" + - "\r\n" + - " $this->_parse_modifiers($output, $modifiers);\r\n" + - "\r\n" + - " return $output;\r\n" + - " }\r\n" + - "\r\n" + - "\r\n" + - " /**\r\n" + - " * parse modifier chain into PHP code\r\n" + - " *\r\n" + - " * @access public\r\n" + - " * @param $output\r\n" + - " * @param $modifier_string\r\n" + - " */\r\n" + - " function _parse_modifiers(&$output, $modifier_string)\r\n" + - " {\r\n" + - " preg_match_all(\'!\\|(@?\\w+)((?>:(?:\'. $this->_qstr_regexp . \'|[^|]+))*)!\', \'|\' . $modifier_string, $match);\r\n" + - " list(, $modifiers, $modifier_arg_strings) = $match;\r\n" + - "\r\n" + - " for ($i = 0, $for_max = count($modifiers); $i < $for_max; $i++) {\r\n" + - " $modifier_name = $modifiers[$i];\r\n" + - " \r\n" + - " if($modifier_name == \'smarty\') {\r\n" + - " // skip smarty modifier\r\n" + - " continue;\r\n" + - " }\r\n" + - " \r\n" + - " preg_match_all(\'!:(\' . $this->_qstr_regexp . \'|[^:]+)!\', $modifier_arg_strings[$i], $match);\r\n" + - " $modifier_args = $match[1];\r\n" + - "\r\n" + - " if ($modifier_name{0} == \'@\') {\r\n" + - " $map_array = \'false\';\r\n" + - " $modifier_name = substr($modifier_name, 1);\r\n" + - " } else {\r\n" + - " $map_array = \'true\';\r\n" + - " }\r\n" + - " \r\n" + - " $this->_add_plugin(\'modifier\', $modifier_name);\r\n" + - "\r\n" + - " $this->_parse_vars_props($modifier_args);\r\n" + - "\r\n" + - " if (count($modifier_args) > 0)\r\n" + - " $modifier_args = \', \'.implode(\', \', $modifier_args);\r\n" + - " else\r\n" + - " $modifier_args = \'\';\r\n" + - "\r\n" + - " $output = \"\\$this->_run_mod_handler(\'$modifier_name\', $map_array, $output$modifier_args)\";\r\n" + - " }\r\n" + - " }\r\n" + - "\r\n" + - "\r\n" + - " /**\r\n" + - " * add plugin\r\n" + - " *\r\n" + - " * @access public\r\n" + - " * @param $type\r\n" + - " * @param $name\r\n" + - " * @param $delayed_loading\r\n" + - " */\r\n" + - " function _add_plugin($type, $name, $delayed_loading = null)\r\n" + - " {\r\n" + - " if (!isset($this->_plugin_info[$type])) {\r\n" + - " $this->_plugin_info[$type] = array();\r\n" + - " }\r\n" + - " if (!isset($this->_plugin_info[$type][$name])) {\r\n" + - " $this->_plugin_info[$type][$name] = array($this->_current_file,\r\n" + - " $this->_current_line_no,\r\n" + - " $delayed_loading);\r\n" + - " }\r\n" + - " }\r\n" + - " \r\n" + - "\r\n" + - " /**\r\n" + - " * Compiles references of type $smarty.foo\r\n" + - " *\r\n" + - " * @access public\r\n" + - " * @param $indexes\r\n" + - " */\r\n" + - " function _compile_smarty_ref(&$indexes)\r\n" + - " {\r\n" + - " /* Extract the reference name. */\r\n" + - " $ref = substr($indexes[0], 1);\r\n" + - "\r\n" + - " switch ($ref) {\r\n" + - " case \'now\':\r\n" + - " $compiled_ref = \'time()\';\r\n" + - " if (count($indexes) > 1) {\r\n" + - " $this->_syntax_error(\'$smarty\' . implode(\'\', $indexes) .\' is an invalid reference\', E_USER_ERROR, __FILE__, __LINE__);\r\n" + - " }\r\n" + - " break;\r\n" + - "\r\n" + - " case \'foreach\':\r\n" + - " case \'section\':\r\n" + - " if ($indexes[1]{0} != \'.\') {\r\n" + - " $this->_syntax_error(\'$smarty\' . implode(\'\', array_slice($indexes, 0, 2)) . \' is an invalid reference\', E_USER_ERROR, __FILE__, __LINE__);\r\n" + - " }\r\n" + - " $name = substr($indexes[1], 1);\r\n" + - " array_shift($indexes);\r\n" + - " if ($ref == \'foreach\')\r\n" + - " $compiled_ref = \"\\$this->_foreach[\'$name\']\";\r\n" + - " else\r\n" + - " $compiled_ref = \"\\$this->_sections[\'$name\']\";\r\n" + - " break;\r\n" + - "\r\n" + - " case \'get\':\r\n" + - " array_shift($indexes);\r\n" + - " $compiled_ref = \"\\$_GET\";\r\n" + - " if ($name = substr($indexes[0], 1))\r\n" + - " $compiled_ref .= \"[\'$name\']\";\r\n" + - " break;\r\n" + - "\r\n" + - " case \'post\':\r\n" + - " array_shift($indexes);\r\n" + - " $name = substr($indexes[0], 1);\r\n" + - " $compiled_ref = \"\\$_POST\";\r\n" + - " if ($name = substr($indexes[0], 1))\r\n" + - " $compiled_ref .= \"[\'$name\']\";\r\n" + - " break;\r\n" + - "\r\n" + - " case \'cookies\':\r\n" + - " array_shift($indexes);\r\n" + - " $name = substr($indexes[0], 1);\r\n" + - " $compiled_ref = \"\\$_COOKIE\";\r\n" + - " if ($name = substr($indexes[0], 1))\r\n" + - " $compiled_ref .= \"[\'$name\']\";\r\n" + - " break;\r\n" + - "\r\n" + - " case \'env\':\r\n" + - " array_shift($indexes);\r\n" + - " $compiled_ref = \"\\$_ENV\";\r\n" + - " if ($name = substr($indexes[0], 1))\r\n" + - " $compiled_ref .= \"[\'$name\']\";\r\n" + - " break;\r\n" + - "\r\n" + - " case \'server\':\r\n" + - " array_shift($indexes);\r\n" + - " $name = substr($indexes[0], 1);\r\n" + - " $compiled_ref = \"\\$_SERVER\";\r\n" + - " if ($name = substr($indexes[0], 1))\r\n" + - " $compiled_ref .= \"[\'$name\']\";\r\n" + - " break;\r\n" + - "\r\n" + - " case \'session\':\r\n" + - " array_shift($indexes);\r\n" + - " $name = substr($indexes[0], 1);\r\n" + - " $compiled_ref = \"\\$_SESSION\";\r\n" + - " if ($name = substr($indexes[0], 1))\r\n" + - " $compiled_ref .= \"[\'$name\']\";\r\n" + - " break;\r\n" + - "\r\n" + - " /*\r\n" + - " * These cases are handled either at run-time or elsewhere in the\r\n" + - " * compiler.\r\n" + - " */\r\n" + - " case \'request\':\r\n" + - " $this->_init_smarty_vars = true;\r\n" + - " return null;\r\n" + - "\r\n" + - " case \'capture\':\r\n" + - " return null;\r\n" + - "\r\n" + - " case \'template\':\r\n" + - " $compiled_ref = \"\'$this->_current_file\'\";\r\n" + - " if (count($indexes) > 1) {\r\n" + - " $this->_syntax_error(\'$smarty\' . implode(\'\', $indexes) .\' is an invalid reference\', E_USER_ERROR, __FILE__, __LINE__);\r\n" + - " }\r\n" + - " break;\r\n" + - " \r\n" + - " case \'version\':\r\n" + - " $compiled_ref = \"\'$this->_version\'\";\r\n" + - " break;\r\n" + - "\r\n" + - " case \'const\':\r\n" + - " array_shift($indexes);\r\n" + - " $compiled_ref = \'defined(\\\'\' . substr($indexes[0],1) . \'\\\') ? \' . substr($indexes[0],1) . \' : null\';\r\n" + - " break;\r\n" + - "\r\n" + - " default:\r\n" + - " $this->_syntax_error(\'$smarty.\' . $ref . \' is an unknown reference\', E_USER_ERROR, __FILE__, __LINE__);\r\n" + - " break;\r\n" + - " }\r\n" + - "\r\n" + - " array_shift($indexes);\r\n" + - " return $compiled_ref;\r\n" + - " }\r\n" + - "\r\n" + - "\r\n" + - " /**\r\n" + - " * load pre- and post-filters\r\n" + - " *\r\n" + - " * @access public\r\n" + - " */\r\n" + - " function _load_filters()\r\n" + - " {\r\n" + - " if (count($this->_plugins[\'prefilter\']) > 0) {\r\n" + - " foreach ($this->_plugins[\'prefilter\'] as $filter_name => $prefilter) {\r\n" + - " if ($prefilter === false) {\r\n" + - " unset($this->_plugins[\'prefilter\'][$filter_name]);\r\n" + - " $this->_load_plugins(array(array(\'prefilter\', $filter_name, null, null, false)));\r\n" + - " }\r\n" + - " }\r\n" + - " }\r\n" + - " if (count($this->_plugins[\'postfilter\']) > 0) {\r\n" + - " foreach ($this->_plugins[\'postfilter\'] as $filter_name => $postfilter) {\r\n" + - " if ($postfilter === false) {\r\n" + - " unset($this->_plugins[\'postfilter\'][$filter_name]);\r\n" + - " $this->_load_plugins(array(array(\'postfilter\', $filter_name, null, null, false)));\r\n" + - " }\r\n" + - " }\r\n" + - " }\r\n" + - " }\r\n" + - "\r\n" + - "\r\n" + - " /**\r\n" + - " * display Smarty syntax error\r\n" + - " *\r\n" + - " * @access public\r\n" + - " * @param $error_msg\r\n" + - " * @param $error_type\r\n" + - " * @param $file\r\n" + - " * @param $line\r\n" + - " */\r\n" + - " function _syntax_error($error_msg, $error_type = E_USER_ERROR, $file=null, $line=null)\r\n" + - " {\r\n" + - " if(isset($file) && isset($line)) {\r\n" + - " $info = \' (\'.basename($file).\", line $line)\";\r\n" + - " } else {\r\n" + - " $info = null;\r\n" + - " }\r\n" + - " trigger_error(\'Smarty: [in \' . $this->_current_file . \' line \' .\r\n" + - " $this->_current_line_no . \"]: syntax error: $error_msg$info\", $error_type);\r\n" + - " }\r\n" + - "}\r\n" + - "\r\n" + - "/**\r\n" + - " * compare to values by their string length\r\n" + - " *\r\n" + - " * @access private\r\n" + - " * @param $a\r\n" + - " * @param $b\r\n" + - " */\r\n" + - "function _smarty_sort_length($a, $b)\r\n" + - "{\r\n" + - " if($a == $b)\r\n" + - " return 0;\r\n" + - "\r\n" + - " if(strlen($a) == strlen($b))\r\n" + - " return ($a > $b) ? -1 : 1;\r\n" + - "\r\n" + - " return (strlen($a) > strlen($b)) ? -1 : 1;\r\n" + - "}\r\n" + - "\r\n" + - "\r\n" + - "/* vim: set et: */\r\n" + - "\r\n" + - "?>\r\n" + - ""); - } + // Parser parser; + public SmartyCompilerTestCase(String name) { + super(name); + } + + /** + * Test the PHP Parser with different PHP snippets + */ + public void testPHPParser() { + checkHTML("\n" + + " * Andrei Zmievski \n" + + " *\n" + + " * Version: 2.4.2\n" + + " * Copyright: 2001,2002 ispi of Lincoln, Inc.\n" + + " *\n" + + " * This library is free software; you can redistribute it and/or\n" + + " * modify it under the terms of the GNU Lesser General Public\n" + + " * License as published by the Free Software Foundation; either\n" + + " * version 2.1 of the License, or (at your option) any later version.\n" + + " *\n" + + " * This library is distributed in the hope that it will be useful,\n" + + " * but WITHOUT ANY WARRANTY; without even the implied warranty of\n" + + " * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n" + + " * Lesser General Public License for more details.\n" + + " *\n" + + " * You should have received a copy of the GNU Lesser General Public\n" + + " * License along with this library; if not, write to the Free Software\n" + + " * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n" + + " *\n" + + " * You may contact the authors of Smarty by e-mail at:\n" + + " * monte@ispi.net\n" + + " * andrei@php.net\n" + + " *\n" + + " * Or, write to:\n" + + " * Monte Ohrt\n" + + " * Director of Technology, ispi\n" + + " * 237 S. 70th suite 220\n" + + " * Lincoln, NE 68510\n" + + " *\n" + + " * The latest version of Smarty can be obtained from:\n" + + " * http://www.phpinsider.com/\n" + + " *\n" + + " */\n" + + "\n" + + "class Smarty_Compiler extends Smarty {\n" + + " \n" + + " // internal vars\n" + + " public $_sectionelse_stack = array(); // keeps track of whether section had \'else\' part\n" + + " public $_foreachelse_stack = array(); // keeps track of whether foreach had \'else\' part\n" + + " public $_literal_blocks = array(); // keeps literal template blocks\n" + + " public $_php_blocks = array(); // keeps php code blocks\n" + + " public $_current_file = null; // the current template being compiled\n" + + " public $_current_line_no = 1; // line number for error messages\n" + + " public $_capture_stack = array(); // keeps track of nested capture buffers\n" + + " public $_plugin_info = array(); // keeps track of plugins to load\n" + + " public $_init_smarty_vars = false;\n" + + " public $_permitted_tokens = array(\'true\',\'false\',\'yes\',\'no\',\'on\',\'off\');\n" + + " public $_db_qstr_regexp = null; // regexps are setup in the constructor\n" + + " public $_si_qstr_regexp = null;\n" + + " public $_qstr_regexp = null;\n" + + " public $_func_regexp = null;\n" + + " public $_var_bracket_regexp = null;\n" + + " public $_dvar_guts_regexp = null;\n" + + " public $_dvar_regexp = null;\n" + + " public $_cvar_regexp = null;\n" + + " public $_svar_regexp = null;\n" + + " public $_avar_regexp = null;\n" + + " public $_mod_regexp = null;\n" + + " public $_var_regexp = null;\n" + + " public $_parenth_param_regexp = null;\n" + + " public $_func_call_regexp = null;\n" + + " public $_obj_ext_regexp = null;\n" + + " public $_obj_start_regexp = null;\n" + + " public $_obj_params_regexp = null;\n" + + " public $_obj_call_regexp = null;\n" + + "\n" + + " /**\n" + + " * The class constructor.\n" + + " *\n" + + " * @access public\n" + + " */\n" + + " function Smarty_Compiler()\n" + + " {\n" + + " // matches double quoted strings:\n" + + " // \"foobar\"\n" + + " // \"foo\\\"bar\"\n" + + " $this->_db_qstr_regexp = \'\"[^\"\\\\\\\\]*(?:\\\\\\\\.[^\"\\\\\\\\]*)*\"\';\n" + + "\n" + + " // matches single quoted strings:\n" + + " // \'foobar\'\n" + + " // \'foo\\\'bar\'\n" + + " $this->_si_qstr_regexp = \'\\\'[^\\\'\\\\\\\\]*(?:\\\\\\\\.[^\\\'\\\\\\\\]*)*\\\'\';\n" + + "\n" + + " // matches single or double quoted strings\n" + + " $this->_qstr_regexp = \'(?:\' . $this->_db_qstr_regexp . \'|\' . $this->_si_qstr_regexp . \')\';\n" + + "\n" + + " // matches bracket portion of vars\n" + + " // [0]\n" + + " // [foo]\n" + + " // [$bar]\n" + + " $this->_var_bracket_regexp = \'\\[\\$?[\\w\\.]+\\]\';\n" + + " \n" + + " // matches $ vars (not objects):\n" + + " // $foo\n" + + " // $foo.bar\n" + + " // $foo.bar.foobar\n" + + " // $foo[0]\n" + + " // $foo[$bar]\n" + + " // $foo[5][blah]\n" + + " // $foo[5].bar[$foobar][4]\n" + + " $this->_dvar_guts_regexp = \'\\w+(?:\' . $this->_var_bracket_regexp\n" + + " . \')*(?:\\.\\$?\\w+(?:\' . $this->_var_bracket_regexp . \')*)*\';\n" + + " $this->_dvar_regexp = \'\\$\' . $this->_dvar_guts_regexp;\n" + + "\n" + + " // matches config vars:\n" + + " // #foo#\n" + + " // #foobar123_foo#\n" + + " $this->_cvar_regexp = \'\\#\\w+\\#\';\n" + + "\n" + + " // matches section vars:\n" + + " // %foo.bar%\n" + + " $this->_svar_regexp = \'\\%\\w+\\.\\w+\\%\';\n" + + "\n" + + " // matches all valid variables (no quotes, no modifiers)\n" + + " $this->_avar_regexp = \'(?:\' . $this->_dvar_regexp . \'|\'\n" + + " . $this->_cvar_regexp . \'|\' . $this->_svar_regexp . \')\';\n" + + "\n" + + " // matches valid modifier syntax:\n" + + " // |foo\n" + + " // |@foo\n" + + " // |foo:\"bar\"\n" + + " // |foo:$bar\n" + + " // |foo:\"bar\":$foobar\n" + + " // |foo|bar\n" + + " // |foo\n" + + " $this->_mod_regexp = \'(?:\\|@?\\w+(?::(?>\\w+|\'\n" + + " . $this->_avar_regexp . \'|\' . $this->_qstr_regexp .\'))*)\';\n" + + "\n" + + " // matches valid variable syntax:\n" + + " // $foo\n" + + " // $foo\n" + + " // #foo#\n" + + " // #foo#\n" + + " // \"text\"\n" + + " // \"text\"\n" + + " $this->_var_regexp = \'(?:\' . $this->_avar_regexp . \'|\' . $this->_qstr_regexp . \')\';\n" + + " \n" + + " // matches valid object call (no objects allowed in parameters):\n" + + " // $foo->bar\n" + + " // $foo->bar()\n" + + " // $foo->bar(\"text\")\n" + + " // $foo->bar($foo, $bar, \"text\")\n" + + " // $foo->bar($foo|bar, \"foo\"|bar)\n" + + " // $foo->bar->foo()\n" + + " // $foo->bar->foo->bar()\n" + + " $this->_obj_ext_regexp = \'\\->(?:\\w+|\' . $this->_dvar_regexp . \')\';\n" + + " $this->_obj_params_regexp = \'\\((?:\\w+|\'\n" + + " . $this->_var_regexp . \'(?>\' . $this->_mod_regexp . \'*)(?:\\s*,\\s*(?:(?:\\w+|\'\n" + + " . $this->_var_regexp . \'(?>\' . $this->_mod_regexp . \'*))))*)?\\)\'; \n" + + " $this->_obj_start_regexp = \'(?:\' . $this->_dvar_regexp . \'(?:\' . $this->_obj_ext_regexp . \')+)\';\n" + + " $this->_obj_call_regexp = \'(?:\' . $this->_obj_start_regexp . \'(?:\' . $this->_obj_params_regexp . \')?)\';\n" + + " \n" + + " // matches valid function name:\n" + + " // foo123\n" + + " // _foo_bar\n" + + " $this->_func_regexp = \'[a-zA-Z_]\\w*\';\n" + + "\n" + + " // matches valid registered object:\n" + + " // foo.bar\n" + + " $this->_reg_obj_regexp = \'[a-zA-Z_]\\w*->[a-zA-Z_]\\w*\';\n" + + " \n" + + " // matches valid parameter values:\n" + + " // true\n" + + " // $foo\n" + + " // $foo|bar\n" + + " // #foo#\n" + + " // #foo#|bar\n" + + " // \"text\"\n" + + " // \"text\"|bar\n" + + " // $foo->bar\n" + + " $this->_param_regexp = \'(?:\\s*(?:\' . $this->_obj_call_regexp . \'|\'\n" + + " . $this->_var_regexp . \'|\\w+)(?>\' . $this->_mod_regexp . \'*)\\s*)\'; \n" + + " \n" + + " // matches valid parenthesised function parameters:\n" + + " // \n" + + " // \"text\"\n" + + " // $foo, $bar, \"text\"\n" + + " // $foo|bar, \"foo\"|bar, $foo->bar($foo)|bar\n" + + " $this->_parenth_param_regexp = \'(?:\\((?:\\w+|\'\n" + + " . $this->_param_regexp . \'(?:\\s*,\\s*(?:(?:\\w+|\'\n" + + " . $this->_param_regexp . \')))*)?\\))\';\n" + + " \n" + + " // matches valid function call:\n" + + " // foo()\n" + + " // foo_bar($foo)\n" + + " // _foo_bar($foo,\"bar\")\n" + + " // foo123($foo,$foo->bar(),\"foo\")\n" + + " $this->_func_call_regexp = \'(?:\' . $this->_func_regexp . \'\\s*(?:\'\n" + + " . $this->_parenth_param_regexp . \'))\'; \n" + + "\n" + + " } \n" + + " \n" + + " /**\n" + + " * compile a template file\n" + + " *\n" + + " * @access public\n" + + " * @param $tpl_file\n" + + " * @param $template_source\n" + + " * @param $template_compiled\n" + + " */\n" + + " function _compile_file($tpl_file, $template_source, &$template_compiled)\n" + + " {\n" + + " if ($this->security) {\n" + + " // do not allow php syntax to be executed unless specified\n" + + " if ($this->php_handling == SMARTY_PHP_ALLOW &&\n" + + " !$this->security_settings[\'PHP_HANDLING\']) {\n" + + " $this->php_handling = SMARTY_PHP_PASSTHRU;\n" + + " }\n" + + " }\n" + + "\n" + + " $this->_load_filters();\n" + + "\n" + + " $this->_current_file = $tpl_file;\n" + + " $this->_current_line_no = 1;\n" + + " $ldq = preg_quote($this->left_delimiter, \'!\');\n" + + " $rdq = preg_quote($this->right_delimiter, \'!\');\n" + + "\n" + + " // run template source through prefilter functions\n" + + " if (count($this->_plugins[\'prefilter\']) > 0) {\n" + + " foreach ($this->_plugins[\'prefilter\'] as $filter_name => $prefilter) {\n" + + " if ($prefilter === false) continue; \n" + + " if ($prefilter[3] || function_exists($prefilter[0])) {\n" + + " $template_source = $prefilter[0]($template_source, $this);\n" + + " $this->_plugins[\'prefilter\'][$filter_name][3] = true;\n" + + " } else {\n" + + " $this->_trigger_fatal_error(\"[plugin] prefilter \'$filter_name\' is not implemented\");\n" + + " }\n" + + " }\n" + + " }\n" + + "\n" + + " /* Annihilate the comments. */\n" + + " $template_source = preg_replace(\"!({$ldq})\\*(.*?)\\*({$rdq})!se\",\n" + + " \"\'\\\\1*\'.str_repeat(\\\"\\n\\\", substr_count(\'\\\\2\', \\\"\\n\\\")) .\'*\\\\3\'\",\n" + + " $template_source);\n" + + "\n" + + " /* Pull out the literal blocks. */\n" + + " preg_match_all(\"!{$ldq}literal{$rdq}(.*?){$ldq}/literal{$rdq}!s\", $template_source, $match);\n" + + " $this->_literal_blocks = $match[1];\n" + + " $template_source = preg_replace(\"!{$ldq}literal{$rdq}(.*?){$ldq}/literal{$rdq}!s\",\n" + + " $this->quote_replace($this->left_delimiter.\'literal\'.$this->right_delimiter), $template_source);\n" + + "\n" + + " /* Pull out the php code blocks. */\n" + + " preg_match_all(\"!{$ldq}php{$rdq}(.*?){$ldq}/php{$rdq}!s\", $template_source, $match);\n" + + " $this->_php_blocks = $match[1];\n" + + " $template_source = preg_replace(\"!{$ldq}php{$rdq}(.*?){$ldq}/php{$rdq}!s\",\n" + + " $this->quote_replace($this->left_delimiter.\'php\'.$this->right_delimiter), $template_source);\n" + + "\n" + + " /* Gather all template tags. */\n" + + " preg_match_all(\"!{$ldq}\\s*(.*?)\\s*{$rdq}!s\", $template_source, $match);\n" + + " $template_tags = $match[1];\n" + + " /* Split content by template tags to obtain non-template content. */\n" + + " $text_blocks = preg_split(\"!{$ldq}.*?{$rdq}!s\", $template_source);\n" + + " \n" + + " /* loop through text blocks */\n" + + " for ($curr_tb = 0, $for_max = count($text_blocks); $curr_tb < $for_max; $curr_tb++) {\n" + + " /* match anything resembling php tags */\n" + + " if (preg_match_all(\'!(<\\?(?:\\w+|=)?|\\?>|language\\s*=\\s*[\\\"\\\']?php[\\\"\\\']?)!is\', $text_blocks[$curr_tb], $sp_match)) {\n" + + " /* replace tags with placeholders to prevent recursive replacements */\n" + + " $sp_match[1] = array_unique($sp_match[1]);\n" + + " usort($sp_match[1], \'_smarty_sort_length\');\n" + + " for ($curr_sp = 0, $for_max2 = count($sp_match[1]); $curr_sp < $for_max2; $curr_sp++) {\n" + + " $text_blocks[$curr_tb] = str_replace($sp_match[1][$curr_sp],\'%%%SMARTYSP\'.$curr_sp.\'%%%\',$text_blocks[$curr_tb]);\n" + + " }\n" + + " /* process each one */\n" + + " for ($curr_sp = 0, $for_max2 = count($sp_match[0]); $curr_sp < $for_max2; $curr_sp++) {\n" + + " if ($this->php_handling == SMARTY_PHP_PASSTHRU) {\n" + + " /* echo php contents */\n" + + " $text_blocks[$curr_tb] = str_replace(\'%%%SMARTYSP\'.$curr_sp.\'%%%\', \'\'.\"\\n\", $text_blocks[$curr_tb]);\n" + + " } else if ($this->php_handling == SMARTY_PHP_QUOTE) {\n" + + " /* quote php tags */\n" + + " $text_blocks[$curr_tb] = str_replace(\'%%%SMARTYSP\'.$curr_sp.\'%%%\', htmlspecialchars($sp_match[1][$curr_sp]), $text_blocks[$curr_tb]);\n" + + " } else if ($this->php_handling == SMARTY_PHP_REMOVE) {\n" + + " /* remove php tags */\n" + + " $text_blocks[$curr_tb] = str_replace(\'%%%SMARTYSP\'.$curr_sp.\'%%%\', \'\', $text_blocks[$curr_tb]);\n" + + " } else {\n" + + " /* SMARTY_PHP_ALLOW, but echo non php starting tags */\n" + + " $sp_match[1][$curr_sp] = preg_replace(\'%(<\\?(?!php|=|$))%i\', \'\'.\"\\n\", $sp_match[1][$curr_sp]);\n" + + " $text_blocks[$curr_tb] = str_replace(\'%%%SMARTYSP\'.$curr_sp.\'%%%\', $sp_match[1][$curr_sp], $text_blocks[$curr_tb]);\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + "\n" + + " /* Compile the template tags into PHP code. */\n" + + " $compiled_tags = array();\n" + + " for ($i = 0, $for_max = count($template_tags); $i < $for_max; $i++) {\n" + + " $this->_current_line_no += substr_count($text_blocks[$i], \"\\n\");\n" + + " $compiled_tags[] = $this->_compile_tag($template_tags[$i]);\n" + + " $this->_current_line_no += substr_count($template_tags[$i], \"\\n\");\n" + + " }\n" + + "\n" + + " $template_compiled = \'\';\n" + + "\n" + + " /* Interleave the compiled contents and text blocks to get the final result. */\n" + + " for ($i = 0, $for_max = count($compiled_tags); $i < $for_max; $i++) {\n" + + " $template_compiled .= $text_blocks[$i].$compiled_tags[$i];\n" + + " }\n" + + " $template_compiled .= $text_blocks[$i];\n" + + "\n" + + " /* Reformat data between \'strip\' and \'/strip\' tags, removing spaces, tabs and newlines. */\n" + + " if (preg_match_all(\"!{$ldq}strip{$rdq}.*?{$ldq}/strip{$rdq}!s\", $template_compiled, $match)) {\n" + + " $strip_tags = $match[0];\n" + + " $strip_tags_modified = preg_replace(\"!{$ldq}/?strip{$rdq}|[\\t ]+$|^[\\t ]+!m\", \'\', $strip_tags);\n" + + " $strip_tags_modified = preg_replace(\'![\\r\\n]+!m\', \'\', $strip_tags_modified);\n" + + " for ($i = 0, $for_max = count($strip_tags); $i < $for_max; $i++)\n" + + " $template_compiled = preg_replace(\"!{$ldq}strip{$rdq}.*?{$ldq}/strip{$rdq}!s\",\n" + + " $this->quote_replace($strip_tags_modified[$i]),\n" + + " $template_compiled, 1);\n" + + " }\n" + + "\n" + + " // remove \\n from the end of the file, if any\n" + + " if ($template_compiled{strlen($template_compiled) - 1} == \"\\n\" ) {\n" + + " $template_compiled = substr($template_compiled, 0, -1);\n" + + " }\n" + + "\n" + + " // run compiled template through postfilter functions\n" + + " if (count($this->_plugins[\'postfilter\']) > 0) {\n" + + " foreach ($this->_plugins[\'postfilter\'] as $filter_name => $postfilter) {\n" + + " if ($postfilter === false) continue;\n" + + " if ($postfilter[3] || function_exists($postfilter[0])) {\n" + + " $template_compiled = $postfilter[0]($template_compiled, $this);\n" + + " $this->_plugins[\'postfilter\'][$filter_name][3] = true;\n" + + " } else {\n" + + " $this->_trigger_plugin_error(\"Smarty plugin error: postfilter \'$filter_name\' is not implemented\");\n" + + " }\n" + + " }\n" + + " }\n" + + "\n" + + " // put header at the top of the compiled template\n" + + " $template_header = \"_version.\", created on \".strftime(\"%Y-%m-%d %H:%M:%S\").\"\\n\";\n" + + " $template_header .= \" compiled from \".$tpl_file.\" */ ?>\\n\";\n" + + "\n" + + " /* Emit code to load needed plugins. */\n" + + " if (count($this->_plugin_info)) {\n" + + " $plugins_code = \'_load_plugins(array(\';\n" + + " foreach ($this->_plugin_info as $plugin_type => $plugins) {\n" + + " foreach ($plugins as $plugin_name => $plugin_info) {\n" + + " $plugins_code .= \"\\narray(\'$plugin_type\', \'$plugin_name\', \'$plugin_info[0]\', $plugin_info[1], \";\n" + + " $plugins_code .= $plugin_info[2] ? \'true),\' : \'false),\';\n" + + " }\n" + + " }\n" + + " $plugins_code .= \")); ?>\";\n" + + " $template_header .= $plugins_code;\n" + + " $this->_plugin_info = array();\n" + + " }\n" + + "\n" + + " if ($this->_init_smarty_vars) {\n" + + " $template_header .= \"_assign_smarty_interface(); ?>\\n\";\n" + + " $this->_init_smarty_vars = false;\n" + + " }\n" + + "\n" + + " $template_compiled = $template_header . $template_compiled;\n" + + "\n" + + " return true;\n" + + " }\n" + + "\n" + + " /**\n" + + " * Compile a template tag\n" + + " *\n" + + " * @access public\n" + + " * @param $template_tag\n" + + " */\n" + + " function _compile_tag($template_tag)\n" + + " { \n" + + " \n" + + " /* Matched comment. */\n" + + " if ($template_tag{0} == \'*\' && $template_tag{strlen($template_tag) - 1} == \'*\')\n" + + " return \'\';\n" + + " \n" + + " /* Split tag into two three parts: command, command modifiers and the arguments. */\n" + + " if(! preg_match(\'/^(?:(\' . $this->_obj_call_regexp . \'|\' . $this->_var_regexp\n" + + " . \'|\' . $this->_reg_obj_regexp . \'|\\/?\' . $this->_func_regexp . \')(\' . $this->_mod_regexp . \'*))\n" + + " (?:\\s+(.*))?$\n" + + " /xs\', $template_tag, $match)) {\n" + + " $this->_syntax_error(\"unrecognized tag: $template_tag\", E_USER_ERROR, __FILE__, __LINE__);\n" + + " }\n" + + "\n" + + " $tag_command = $match[1];\n" + + " $tag_modifier = isset($match[2]) ? $match[2] : null;\n" + + " $tag_args = isset($match[3]) ? $match[3] : null;\n" + + " \n" + + " \n" + + " /* If the tag name is a variable or object, we process it. */\n" + + " if (preg_match(\'!^\' . $this->_obj_call_regexp . \'|\' . $this->_var_regexp . \'$!\', $tag_command)) {\n" + + " $return = $this->_parse_var_props($tag_command . $tag_modifier, $this->_parse_attrs($tag_args));\n" + + " if(isset($_tag_attrs[\'assign\'])) {\n" + + " return \"assign(\'\" . $this->_dequote($_tag_attrs[\'assign\']) . \"\', $return ); ?>\\n\"; \n" + + " } else {\n" + + " return \"\\n\";\n" + + " }\n" + + " }\n" + + " \n" + + " /* If the tag name is a registered object, we process it. */\n" + + " if (preg_match(\'!^\' . $this->_reg_obj_regexp . \'$!\', $tag_command)) {\n" + + " return $this->_compile_registered_object_tag($tag_command, $this->_parse_attrs($tag_args), $tag_modifier);\n" + + " }\n" + + "\n" + + " switch ($tag_command) {\n" + + " case \'include\':\n" + + " return $this->_compile_include_tag($tag_args);\n" + + "\n" + + " case \'include_php\':\n" + + " return $this->_compile_include_php_tag($tag_args);\n" + + "\n" + + " case \'if\':\n" + + " return $this->_compile_if_tag($tag_args);\n" + + "\n" + + " case \'else\':\n" + + " return \'\';\n" + + "\n" + + " case \'elseif\':\n" + + " return $this->_compile_if_tag($tag_args, true);\n" + + "\n" + + " case \'/if\':\n" + + " return \'\';\n" + + "\n" + + " case \'capture\':\n" + + " return $this->_compile_capture_tag(true, $tag_args);\n" + + "\n" + + " case \'/capture\':\n" + + " return $this->_compile_capture_tag(false);\n" + + "\n" + + " case \'ldelim\':\n" + + " return $this->left_delimiter;\n" + + "\n" + + " case \'rdelim\':\n" + + " return $this->right_delimiter;\n" + + "\n" + + " case \'section\':\n" + + " array_push($this->_sectionelse_stack, false);\n" + + " return $this->_compile_section_start($tag_args);\n" + + "\n" + + " case \'sectionelse\':\n" + + " $this->_sectionelse_stack[count($this->_sectionelse_stack)-1] = true;\n" + + " return \"\";\n" + + "\n" + + " case \'/section\':\n" + + " if (array_pop($this->_sectionelse_stack))\n" + + " return \"\";\n" + + " else\n" + + " return \"\";\n" + + "\n" + + " case \'foreach\':\n" + + " array_push($this->_foreachelse_stack, false);\n" + + " return $this->_compile_foreach_start($tag_args);\n" + + " break;\n" + + "\n" + + " case \'foreachelse\':\n" + + " $this->_foreachelse_stack[count($this->_foreachelse_stack)-1] = true;\n" + + " return \"\";\n" + + "\n" + + " case \'/foreach\':\n" + + " if (array_pop($this->_foreachelse_stack))\n" + + " return \"\";\n" + + " else\n" + + " return \"\";\n" + + "\n" + + " case \'config_load\':\n" + + " return $this->_compile_config_load_tag($tag_args);\n" + + "\n" + + " case \'strip\':\n" + + " case \'/strip\':\n" + + " return $this->left_delimiter.$tag_command.$this->right_delimiter;\n" + + "\n" + + " case \'literal\':\n" + + " list (,$literal_block) = each($this->_literal_blocks);\n" + + " $this->_current_line_no += substr_count($literal_block, \"\\n\");\n" + + " return \"\\n\";\n" + + "\n" + + " case \'php\':\n" + + " if ($this->security && !$this->security_settings[\'PHP_TAGS\']) {\n" + + " $this->_syntax_error(\"(secure mode) php tags not permitted\", E_USER_WARNING, __FILE__, __LINE__);\n" + + " return;\n" + + " }\n" + + " list (,$php_block) = each($this->_php_blocks);\n" + + " $this->_current_line_no += substr_count($php_block, \"\\n\");\n" + + " return \'\';\n" + + "\n" + + " case \'insert\':\n" + + " return $this->_compile_insert_tag($tag_args);\n" + + "\n" + + " default:\n" + + " if ($this->_compile_compiler_tag($tag_command, $tag_args, $output)) {\n" + + " return $output;\n" + + " } else if ($this->_compile_block_tag($tag_command, $tag_args, $tag_modifier, $output)) {\n" + + " return $output;\n" + + " } else {\n" + + " return $this->_compile_custom_tag($tag_command, $tag_args, $tag_modifier);\n" + + " }\n" + + " }\n" + + " }\n" + + "\n" + + "\n" + + " /**\n" + + " * compile the custom compiler tag\n" + + " *\n" + + " * @access public\n" + + " * @param $tag_command\n" + + " * @param $tag_args\n" + + " * @param $output\n" + + " */\n" + + " function _compile_compiler_tag($tag_command, $tag_args, &$output)\n" + + " {\n" + + " $found = false;\n" + + " $have_function = true;\n" + + "\n" + + " /*\n" + + " * First we check if the compiler function has already been registered\n" + + " * or loaded from a plugin file.\n" + + " */\n" + + " if (isset($this->_plugins[\'compiler\'][$tag_command])) {\n" + + " $found = true;\n" + + " $plugin_func = $this->_plugins[\'compiler\'][$tag_command][0];\n" + + " if (!function_exists($plugin_func)) {\n" + + " $message = \"compiler function \'$tag_command\' is not implemented\";\n" + + " $have_function = false;\n" + + " }\n" + + " }\n" + + " /*\n" + + " * Otherwise we need to load plugin file and look for the function\n" + + " * inside it.\n" + + " */\n" + + " else if ($plugin_file = $this->_get_plugin_filepath(\'compiler\', $tag_command)) {\n" + + " $found = true;\n" + + "\n" + + " include_once $plugin_file;\n" + + "\n" + + " $plugin_func = \'smarty_compiler_\' . $tag_command;\n" + + " if (!function_exists($plugin_func)) {\n" + + " $message = \"plugin function $plugin_func() not found in $plugin_file\\n\";\n" + + " $have_function = false;\n" + + " } else {\n" + + " $this->_plugins[\'compiler\'][$tag_command] = array($plugin_func, null, null);\n" + + " }\n" + + " }\n" + + "\n" + + " /*\n" + + " * True return value means that we either found a plugin or a\n" + + " * dynamically registered function. False means that we didn\'t and the\n" + + " * compiler should now emit code to load custom function plugin for this\n" + + " * tag.\n" + + " */\n" + + " if ($found) {\n" + + " if ($have_function) {\n" + + " $output = \'\';\n" + + " } else {\n" + + " $this->_syntax_error($message, E_USER_WARNING, __FILE__, __LINE__);\n" + + " }\n" + + " return true;\n" + + " } else {\n" + + " return false;\n" + + " }\n" + + " }\n" + + "\n" + + "\n" + + " /**\n" + + " * compile block function tag\n" + + " *\n" + + " * @access public\n" + + " * @param $tag_command\n" + + " * @param $tag_args\n" + + " * @param $tag_modifier\n" + + " * @param $output\n" + + " */\n" + + " function _compile_block_tag($tag_command, $tag_args, $tag_modifier, &$output)\n" + + " {\n" + + " if ($tag_command{0} == \'/\') {\n" + + " $start_tag = false;\n" + + " $tag_command = substr($tag_command, 1);\n" + + " } else\n" + + " $start_tag = true;\n" + + "\n" + + " $found = false;\n" + + " $have_function = true;\n" + + "\n" + + " /*\n" + + " * First we check if the block function has already been registered\n" + + " * or loaded from a plugin file.\n" + + " */\n" + + " if (isset($this->_plugins[\'block\'][$tag_command])) {\n" + + " $found = true;\n" + + " $plugin_func = $this->_plugins[\'block\'][$tag_command][0];\n" + + " if (!function_exists($plugin_func)) {\n" + + " $message = \"block function \'$tag_command\' is not implemented\";\n" + + " $have_function = false;\n" + + " }\n" + + " }\n" + + " /*\n" + + " * Otherwise we need to load plugin file and look for the function\n" + + " * inside it.\n" + + " */\n" + + " else if ($plugin_file = $this->_get_plugin_filepath(\'block\', $tag_command)) {\n" + + " $found = true;\n" + + "\n" + + " include_once $plugin_file;\n" + + "\n" + + " $plugin_func = \'smarty_block_\' . $tag_command;\n" + + " if (!function_exists($plugin_func)) {\n" + + " $message = \"plugin function $plugin_func() not found in $plugin_file\\n\";\n" + + " $have_function = false;\n" + + " } else {\n" + + " $this->_plugins[\'block\'][$tag_command] = array($plugin_func, null, null);\n" + + " }\n" + + " }\n" + + "\n" + + " if (!$found) {\n" + + " return false;\n" + + " } else if (!$have_function) {\n" + + " $this->_syntax_error($message, E_USER_WARNING, __FILE__, __LINE__);\n" + + " return true;\n" + + " }\n" + + "\n" + + " /*\n" + + " * Even though we\'ve located the plugin function, compilation\n" + + " * happens only once, so the plugin will still need to be loaded\n" + + " * at runtime for future requests.\n" + + " */\n" + + " $this->_add_plugin(\'block\', $tag_command);\n" + + "\n" + + " if ($start_tag) {\n" + + " $arg_list = array();\n" + + " $attrs = $this->_parse_attrs($tag_args);\n" + + " foreach ($attrs as $arg_name => $arg_value) {\n" + + " if (is_bool($arg_value))\n" + + " $arg_value = $arg_value ? \'true\' : \'false\';\n" + + " $arg_list[] = \"\'$arg_name\' => $arg_value\";\n" + + " }\n" + + "\n" + + " $output = \"_tag_stack[] = array(\'$tag_command\', array(\".implode(\',\', (array)$arg_list).\")); \\$this->_plugins[\'block\'][\'$tag_command\'][0](array(\".implode(\',\', (array)$arg_list).\"), null, \\$this); ob_start(); ?>\";\n" + + " } else {\n" + + " $output = \"_block_content = ob_get_contents(); ob_end_clean(); \";\n" + + " $out_tag_text = \"\\$this->_plugins[\'block\'][\'$tag_command\'][0](\\$this->_tag_stack[count(\\$this->_tag_stack)-1][1], \\$this->_block_content, \\$this)\";\n" + + " if($tag_modifier != \'\') {\n" + + " $this->_parse_modifiers($out_tag_text, $tag_modifier);\n" + + " }\n" + + " $output .= \'echo \' . $out_tag_text . \';\';\n" + + " $output .= \" array_pop(\\$this->_tag_stack); ?>\";\n" + + " }\n" + + "\n" + + " return true;\n" + + " }\n" + + "\n" + + "\n" + + " /**\n" + + " * compile custom function tag\n" + + " *\n" + + " * @access public\n" + + " * @param $tag_command\n" + + " * @param $tag_args\n" + + " * @param $tag_modifier\n" + + " */\n" + + " function _compile_custom_tag($tag_command, $tag_args, $tag_modifier)\n" + + " {\n" + + " $this->_add_plugin(\'function\', $tag_command);\n" + + "\n" + + " $arg_list = array();\n" + + " $attrs = $this->_parse_attrs($tag_args);\n" + + " foreach ($attrs as $arg_name => $arg_value) {\n" + + " if (is_bool($arg_value))\n" + + " $arg_value = $arg_value ? \'true\' : \'false\';\n" + + " $arg_list[] = \"\'$arg_name\' => $arg_value\";\n" + + " }\n" + + " \n" + + " $return = \"\\$this->_plugins[\'function\'][\'$tag_command\'][0](array(\".implode(\',\', (array)$arg_list).\"), \\$this)\";\n" + + " \n" + + " if($tag_modifier != \'\') {\n" + + " $this->_parse_modifiers($return, $tag_modifier);\n" + + " }\n" + + " \n" + + " return \'\\n\";\n" + + " }\n" + + "\n" + + " /**\n" + + " * compile a registered object tag\n" + + " *\n" + + " * @access public\n" + + " * @param $tag_command\n" + + " * @param $attrs\n" + + " * @param $tag_modifier\n" + + " */\n" + + " function _compile_registered_object_tag($tag_command, $attrs, $tag_modifier)\n" + + " {\n" + + " list($object, $obj_comp) = explode(\'->\', $tag_command);\n" + + "\n" + + " $arg_list = array();\n" + + " if(count($attrs)) {\n" + + " $_assign_var = false;\n" + + " foreach ($attrs as $arg_name => $arg_value) {\n" + + " if($arg_name == \'assign\') {\n" + + " $_assign_var = $arg_value;\n" + + " unset($attrs[\'assign\']);\n" + + " continue;\n" + + " }\n" + + " if (is_bool($arg_value))\n" + + " $arg_value = $arg_value ? \'true\' : \'false\';\n" + + " $arg_list[] = \"\'$arg_name\' => $arg_value\";\n" + + " }\n" + + " }\n" + + " \n" + + " if(!is_object($this->_reg_objects[$object][0])) {\n" + + " $this->_trigger_fatal_error(\"registered \'$object\' is not an object\");\n" + + " } elseif(!empty($this->_reg_objects[$object][1]) && !in_array($obj_comp, $this->_reg_objects[$object][1])) {\n" + + " $this->_trigger_fatal_error(\"\'$obj_comp\' is not a registered component of object \'$object\'\");\n" + + " } elseif(method_exists($this->_reg_objects[$object][0], $obj_comp)) {\n" + + " // method\n" + + " if($this->_reg_objects[$object][2]) {\n" + + " // smarty object argument format\n" + + " $return = \"\\$this->_reg_objects[\'$object\'][0]->$obj_comp(array(\".implode(\',\', (array)$arg_list).\"), \\$this)\";\n" + + " } else {\n" + + " // traditional argument format\n" + + " $return = \"\\$this->_reg_objects[\'$object\'][0]->$obj_comp(\".implode(\',\', array_values($attrs)).\")\";\n" + + " }\n" + + " } else {\n" + + " // property\n" + + " $return = \"\\$this->_reg_objects[\'$object\'][0]->$obj_comp\";\n" + + " }\n" + + " \n" + + " if($tag_modifier != \'\') {\n" + + " $this->_parse_modifiers($return, $tag_modifier);\n" + + " }\n" + + " \n" + + " if($_assign_var) {\n" + + " return \"assign(\'\" . $this->_dequote($_assign_var) .\"\', $return); ?>\\n\";\n" + + " } else {\n" + + " return \'\\n\";\n" + + " }\n" + + " }\n" + + " \n" + + " \n" + + "\n" + + " /**\n" + + " * Compile {insert ...} tag\n" + + " *\n" + + " * @access public\n" + + " * @param $tag_args\n" + + " */\n" + + " function _compile_insert_tag($tag_args)\n" + + " {\n" + + " $attrs = $this->_parse_attrs($tag_args);\n" + + " $name = $this->_dequote($attrs[\'name\']);\n" + + "\n" + + " if (empty($name)) {\n" + + " $this->_syntax_error(\"missing insert name\", E_USER_ERROR, __FILE__, __LINE__);\n" + + " }\n" + + "\n" + + " if (!empty($attrs[\'script\'])) {\n" + + " $delayed_loading = true;\n" + + " } else {\n" + + " $delayed_loading = false; \n" + + " }\n" + + "\n" + + " foreach ($attrs as $arg_name => $arg_value) {\n" + + " if (is_bool($arg_value))\n" + + " $arg_value = $arg_value ? \'true\' : \'false\';\n" + + " $arg_list[] = \"\'$arg_name\' => $arg_value\";\n" + + " }\n" + + "\n" + + " $this->_add_plugin(\'insert\', $name, $delayed_loading);\n" + + "\n" + + " return \"_run_insert_handler(array(\".implode(\', \', (array)$arg_list).\")); ?>\\n\";\n" + + " }\n" + + "\n" + + "\n" + + " /**\n" + + " * Compile {config_load ...} tag\n" + + " *\n" + + " * @access public\n" + + " * @param $tag_args\n" + + " */\n" + + " function _compile_config_load_tag($tag_args)\n" + + " {\n" + + " $attrs = $this->_parse_attrs($tag_args);\n" + + "\n" + + " if (empty($attrs[\'file\'])) {\n" + + " $this->_syntax_error(\"missing \'file\' attribute in config_load tag\", E_USER_ERROR, __FILE__, __LINE__);\n" + + " }\n" + + "\n" + + " if (empty($attrs[\'section\'])) {\n" + + " $attrs[\'section\'] = \'null\';\n" + + " }\n" + + "\n" + + " if (isset($attrs[\'scope\'])) {\n" + + " $scope = @$this->_dequote($attrs[\'scope\']);\r\n" + + " if ($scope != \'local\' &&\r\n" + + " $scope != \'parent\' &&\r\n" + + " $scope != \'global\') {\r\n" + + " $this->_syntax_error(\"invalid \'scope\' attribute value\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + + " }\r\n" + + " } else {\r\n" + + " if (isset($attrs[\'global\']) && $attrs[\'global\'])\r\n" + + " $scope = \'parent\';\r\n" + + " else\r\n" + + " $scope = \'local\';\r\n" + + " }\r\n" + + "\r\n" + + " return \'config_load(\' . $attrs[\'file\'] . \', \' . $attrs[\'section\'] . \", \'$scope\'); ?>\";\r\n" + + " }\r\n" + + "\r\n" + + "\r\n" + + " /**\r\n" + + " * Compile {include ...} tag\r\n" + + " *\r\n" + + " * @access public\r\n" + + " * $param $tag_args\r\n" + + " */\r\n" + + " function _compile_include_tag($tag_args)\r\n" + + " {\r\n" + + " $attrs = $this->_parse_attrs($tag_args);\r\n" + + " $arg_list = array();\r\n" + + "\r\n" + + " if (empty($attrs[\'file\'])) {\r\n" + + " $this->_syntax_error(\"missing \'file\' attribute in include tag\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + + " }\r\n" + + "\r\n" + + " foreach ($attrs as $arg_name => $arg_value) {\r\n" + + " if ($arg_name == \'file\') {\r\n" + + " $include_file = $arg_value;\r\n" + + " continue;\r\n" + + " } else if ($arg_name == \'assign\') {\r\n" + + " $assign_var = $arg_value;\r\n" + + " continue;\r\n" + + " }\r\n" + + " if (is_bool($arg_value))\r\n" + + " $arg_value = $arg_value ? \'true\' : \'false\';\r\n" + + " $arg_list[] = \"\'$arg_name\' => $arg_value\";\r\n" + + " }\r\n" + + "\r\n" + + " $output = \'_tpl_vars;\\n\" .\r\n" + + " \"\\$this->_smarty_include(\".$include_file.\", array(\".implode(\',\', (array)$arg_list).\"));\\n\" .\r\n" + + " \"\\$this->_tpl_vars = \\$_smarty_tpl_vars;\\n\" .\r\n" + + " \"unset(\\$_smarty_tpl_vars);\\n\";\r\n" + + "\r\n" + + " if (isset($assign_var)) {\r\n" + + " $output .= \"\\$this->assign(\" . $assign_var . \", ob_get_contents()); ob_end_clean();\\n\";\r\n" + + " }\r\n" + + "\r\n" + + " $output .= \' ?>\';\r\n" + + "\r\n" + + " return $output;\r\n" + + "\r\n" + + " }\r\n" + + "\r\n" + + " /**\r\n" + + " * Compile {include ...} tag\r\n" + + " *\r\n" + + " * @access public\r\n" + + " * @param $tag_args\r\n" + + " */\r\n" + + " function _compile_include_php_tag($tag_args)\r\n" + + " {\r\n" + + " $attrs = $this->_parse_attrs($tag_args);\r\n" + + "\r\n" + + " if (empty($attrs[\'file\'])) {\r\n" + + " $this->_syntax_error(\"missing \'file\' attribute in include_php tag\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + + " }\r\n" + + "\r\n" + + " $assign_var = $this->_dequote($attrs[\'assign\']);\r\n" + + "\r\n" + + " $once_var = ( $attrs[\'once\'] === false ) ? \'false\' : \'true\';\r\n" + + "\r\n" + + " foreach($attrs as $arg_name => $arg_value) {\r\n" + + " if($arg_name != \'file\' AND $arg_name != \'once\' AND $arg_name != \'assign\') {\r\n" + + " if(is_bool($arg_value))\r\n" + + " $arg_value = $arg_value ? \'true\' : \'false\';\r\n" + + " $arg_list[] = \"\'$arg_name\' => $arg_value\";\r\n" + + " }\r\n" + + " }\r\n" + + "\r\n" + + " $output =\r\n" + + " \"_smarty_include_php($attrs[file], \'$assign_var\', $once_var, \" .\r\n" + + " \"array(\".implode(\',\', (array)$arg_list).\")); ?>\";\r\n" + + " \r\n" + + " return $output;\r\n" + + " }\r\n" + + " \r\n" + + "\r\n" + + " /**\r\n" + + " * Compile {section ...} tag\r\n" + + " *\r\n" + + " * @access public\r\n" + + " * @param $tag_args\r\n" + + " */\r\n" + + " function _compile_section_start($tag_args)\r\n" + + " {\r\n" + + " $attrs = $this->_parse_attrs($tag_args);\r\n" + + " $arg_list = array();\r\n" + + "\r\n" + + " $output = \'_syntax_error(\"missing section name\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + + " }\r\n" + + "\r\n" + + " $output .= \"if (isset(\\$this->_sections[$section_name])) unset(\\$this->_sections[$section_name]);\\n\";\r\n" + + " $section_props = \"\\$this->_sections[$section_name]\";\r\n" + + "\r\n" + + " foreach ($attrs as $attr_name => $attr_value) {\r\n" + + " switch ($attr_name) {\r\n" + + " case \'loop\':\r\n" + + " $output .= \"{$section_props}[\'loop\'] = is_array($attr_value) ? count($attr_value) : max(0, (int)$attr_value);\\n\";\r\n" + + " break;\r\n" + + "\r\n" + + " case \'show\':\r\n" + + " if (is_bool($attr_value))\r\n" + + " $show_attr_value = $attr_value ? \'true\' : \'false\';\r\n" + + " else\r\n" + + " $show_attr_value = \"(bool)$attr_value\";\r\n" + + " $output .= \"{$section_props}[\'show\'] = $show_attr_value;\\n\";\r\n" + + " break;\r\n" + + "\r\n" + + " case \'name\':\r\n" + + " $output .= \"{$section_props}[\'$attr_name\'] = $attr_value;\\n\";\r\n" + + " break;\r\n" + + "\r\n" + + " case \'max\':\r\n" + + " case \'start\':\r\n" + + " $output .= \"{$section_props}[\'$attr_name\'] = (int)$attr_value;\\n\";\r\n" + + " break;\r\n" + + "\r\n" + + " case \'step\':\r\n" + + " $output .= \"{$section_props}[\'$attr_name\'] = ((int)$attr_value) == 0 ? 1 : (int)$attr_value;\\n\";\r\n" + + " break;\r\n" + + "\r\n" + + " default:\r\n" + + " $this->_syntax_error(\"unknown section attribute - \'$attr_name\'\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + + " break;\r\n" + + " }\r\n" + + " }\r\n" + + "\r\n" + + " if (!isset($attrs[\'show\']))\r\n" + + " $output .= \"{$section_props}[\'show\'] = true;\\n\";\r\n" + + "\r\n" + + " if (!isset($attrs[\'loop\']))\r\n" + + " $output .= \"{$section_props}[\'loop\'] = 1;\\n\";\r\n" + + "\r\n" + + " if (!isset($attrs[\'max\']))\r\n" + + " $output .= \"{$section_props}[\'max\'] = {$section_props}[\'loop\'];\\n\";\r\n" + + " else\r\n" + + " $output .= \"if ({$section_props}[\'max\'] < 0)\\n\" .\r\n" + + " \" {$section_props}[\'max\'] = {$section_props}[\'loop\'];\\n\";\r\n" + + "\r\n" + + " if (!isset($attrs[\'step\']))\r\n" + + " $output .= \"{$section_props}[\'step\'] = 1;\\n\";\r\n" + + "\r\n" + + " if (!isset($attrs[\'start\']))\r\n" + + " $output .= \"{$section_props}[\'start\'] = {$section_props}[\'step\'] > 0 ? 0 : {$section_props}[\'loop\']-1;\\n\";\r\n" + + " else {\r\n" + + " $output .= \"if ({$section_props}[\'start\'] < 0)\\n\" .\r\n" + + " \" {$section_props}[\'start\'] = max({$section_props}[\'step\'] > 0 ? 0 : -1, {$section_props}[\'loop\'] + {$section_props}[\'start\']);\\n\" .\r\n" + + " \"else\\n\" .\r\n" + + " \" {$section_props}[\'start\'] = min({$section_props}[\'start\'], {$section_props}[\'step\'] > 0 ? {$section_props}[\'loop\'] : {$section_props}[\'loop\']-1);\\n\";\r\n" + + " }\r\n" + + "\r\n" + + " $output .= \"if ({$section_props}[\'show\']) {\\n\";\r\n" + + " if (!isset($attrs[\'start\']) && !isset($attrs[\'step\']) && !isset($attrs[\'max\'])) {\r\n" + + " $output .= \" {$section_props}[\'total\'] = {$section_props}[\'loop\'];\\n\";\r\n" + + " } else {\r\n" + + " $output .= \" {$section_props}[\'total\'] = min(ceil(({$section_props}[\'step\'] > 0 ? {$section_props}[\'loop\'] - {$section_props}[\'start\'] : {$section_props}[\'start\']+1)/abs({$section_props}[\'step\'])), {$section_props}[\'max\']);\\n\";\r\n" + + " }\r\n" + + " $output .= \" if ({$section_props}[\'total\'] == 0)\\n\" .\r\n" + + " \" {$section_props}[\'show\'] = false;\\n\" .\r\n" + + " \"} else\\n\" .\r\n" + + " \" {$section_props}[\'total\'] = 0;\\n\";\r\n" + + "\r\n" + + " $output .= \"if ({$section_props}[\'show\']):\\n\";\r\n" + + " $output .= \"\r\n" + + " for ({$section_props}[\'index\'] = {$section_props}[\'start\'], {$section_props}[\'iteration\'] = 1;\r\n" + + " {$section_props}[\'iteration\'] <= {$section_props}[\'total\'];\r\n" + + " {$section_props}[\'index\'] += {$section_props}[\'step\'], {$section_props}[\'iteration\']++):\\n\";\r\n" + + " $output .= \"{$section_props}[\'rownum\'] = {$section_props}[\'iteration\'];\\n\";\r\n" + + " $output .= \"{$section_props}[\'index_prev\'] = {$section_props}[\'index\'] - {$section_props}[\'step\'];\\n\";\r\n" + + " $output .= \"{$section_props}[\'index_next\'] = {$section_props}[\'index\'] + {$section_props}[\'step\'];\\n\";\r\n" + + " $output .= \"{$section_props}[\'first\'] = ({$section_props}[\'iteration\'] == 1);\\n\";\r\n" + + " $output .= \"{$section_props}[\'last\'] = ({$section_props}[\'iteration\'] == {$section_props}[\'total\']);\\n\";\r\n" + + "\r\n" + + " $output .= \"?>\";\r\n" + + "\r\n" + + " return $output;\r\n" + + " }\r\n" + + "\r\n" + + " \r\n" + + " /**\r\n" + + " * Compile {foreach ...} tag.\r\n" + + " *\r\n" + + " * @access public\r\n" + + " * @param $tag_args\r\n" + + " */\r\n" + + " function _compile_foreach_start($tag_args)\r\n" + + " {\r\n" + + " $attrs = $this->_parse_attrs($tag_args);\r\n" + + " $arg_list = array();\r\n" + + "\r\n" + + " if (empty($attrs[\'from\'])) {\r\n" + + " $this->_syntax_error(\"missing \'from\' attribute\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + + " }\r\n" + + "\r\n" + + " if (empty($attrs[\'item\'])) {\r\n" + + " $this->_syntax_error(\"missing \'item\' attribute\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + + " }\r\n" + + "\r\n" + + " $from = $attrs[\'from\'];\r\n" + + " $item = $this->_dequote($attrs[\'item\']);\r\n" + + " if (isset($attrs[\'name\']))\r\n" + + " $name = $attrs[\'name\'];\r\n" + + "\r\n" + + " $output = \'_foreach[$name])) unset(\\$this->_foreach[$name]);\\n\";\r\n" + + " $foreach_props = \"\\$this->_foreach[$name]\";\r\n" + + " }\r\n" + + "\r\n" + + " $key_part = \'\';\r\n" + + "\r\n" + + " foreach ($attrs as $attr_name => $attr_value) {\r\n" + + " switch ($attr_name) {\r\n" + + " case \'key\':\r\n" + + " $key = $this->_dequote($attrs[\'key\']);\r\n" + + " $key_part = \"\\$this->_tpl_vars[\'$key\'] => \";\r\n" + + " break;\r\n" + + "\r\n" + + " case \'name\':\r\n" + + " $output .= \"{$foreach_props}[\'$attr_name\'] = $attr_value;\\n\";\r\n" + + " break;\r\n" + + " }\r\n" + + " }\r\n" + + "\r\n" + + " if (isset($name)) {\r\n" + + " $output .= \"{$foreach_props}[\'total\'] = count((array)$from);\\n\";\r\n" + + " $output .= \"{$foreach_props}[\'show\'] = {$foreach_props}[\'total\'] > 0;\\n\";\r\n" + + " $output .= \"if ({$foreach_props}[\'show\']):\\n\";\r\n" + + " $output .= \"{$foreach_props}[\'iteration\'] = 0;\\n\";\r\n" + + " $output .= \" foreach ((array)$from as $key_part\\$this->_tpl_vars[\'$item\']):\\n\";\r\n" + + " $output .= \" {$foreach_props}[\'iteration\']++;\\n\";\r\n" + + " $output .= \" {$foreach_props}[\'first\'] = ({$foreach_props}[\'iteration\'] == 1);\\n\";\r\n" + + " $output .= \" {$foreach_props}[\'last\'] = ({$foreach_props}[\'iteration\'] == {$foreach_props}[\'total\']);\\n\";\r\n" + + " } else {\r\n" + + " $output .= \"if (count((array)$from)):\\n\";\r\n" + + " $output .= \" foreach ((array)$from as $key_part\\$this->_tpl_vars[\'$item\']):\\n\";\r\n" + + " }\r\n" + + " $output .= \'?>\';\r\n" + + "\r\n" + + " return $output;\r\n" + + " }\r\n" + + "\r\n" + + "\r\n" + + " /**\r\n" + + " * Compile {capture} .. {/capture} tags\r\n" + + " *\r\n" + + " * @access public\r\n" + + " * @param $start\r\n" + + " * @param $tag_args\r\n" + + " */\r\n" + + " function _compile_capture_tag($start, $tag_args = \'\')\r\n" + + " {\r\n" + + " $attrs = $this->_parse_attrs($tag_args);\r\n" + + "\r\n" + + " if ($start) {\r\n" + + " if (isset($attrs[\'name\']))\r\n" + + " $buffer = $attrs[\'name\'];\r\n" + + " else\r\n" + + " $buffer = \"\'default\'\";\r\n" + + "\r\n" + + " $output = \"\";\r\n" + + " $this->_capture_stack[] = $buffer;\r\n" + + " } else {\r\n" + + " $buffer = array_pop($this->_capture_stack);\r\n" + + " $output = \"_smarty_vars[\'capture\'][$buffer] = ob_get_contents(); ob_end_clean(); ?>\";\r\n" + + " }\r\n" + + "\r\n" + + " return $output;\r\n" + + " }\r\n" + + "\r\n" + + " /**\r\n" + + " * Compile {if ...} tag\r\n" + + " *\r\n" + + " * @access public\r\n" + + " * @param $tag_args\r\n" + + " * @param $elseif\r\n" + + " */\r\n" + + " function _compile_if_tag($tag_args, $elseif = false)\r\n" + + " {\r\n" + + "\r\n" + + " /* Tokenize args for \'if\' tag. */\r\n" + + " preg_match_all(\'/(?>\r\n" + + " \' . $this->_obj_call_regexp . \'(?:\' . $this->_mod_regexp . \'*) | # valid object call\r\n" + + " \' . $this->_var_regexp . \'(?:\' . $this->_mod_regexp . \'*) | # public or quoted string\r\n" + + " \\-?\\d+|!==|<=>|==|!=|<=|>=|\\&\\&|\\|\\||\\(|\\)|,|\\!|\\^|=|<|>|\\||\\%|\\+|\\-|\\/|\\* | # valid non-word token\r\n" + + " \\b\\w+\\b | # valid word token\r\n" + + " \\S+ # anything else\r\n" + + " )/x\', $tag_args, $match);\r\n" + + " \r\n" + + " $tokens = $match[0];\r\n" + + " \r\n" + + " // make sure we have balanced parenthesis\r\n" + + " $token_count = array_count_values($tokens);\r\n" + + " if(isset($token_count[\'(\']) && $token_count[\'(\'] != $token_count[\')\']) {\r\n" + + " $this->_syntax_error(\"unbalanced parenthesis in if statement\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + + " }\r\n" + + " \r\n" + + " $is_arg_stack = array();\r\n" + + "\r\n" + + " for ($i = 0; $i < count($tokens); $i++) {\r\n" + + "\r\n" + + " $token = &$tokens[$i];\r\n" + + " \r\n" + + " switch (strtolower($token)) {\r\n" + + " case \'!\':\r\n" + + " case \'%\':\r\n" + + " case \'!==\':\r\n" + + " case \'==\':\r\n" + + " case \'>\':\r\n" + + " case \'<\':\r\n" + + " case \'!=\':\r\n" + + " case \'<=\':\r\n" + + " case \'>=\':\r\n" + + " case \'&&\':\r\n" + + " case \'||\':\r\n" + + " case \'|\':\r\n" + + " case \'^\':\r\n" + + " case \'&\':\r\n" + + " case \'~\':\r\n" + + " case \')\':\r\n" + + " case \',\':\r\n" + + " case \'+\':\r\n" + + " case \'-\':\r\n" + + " case \'*\':\r\n" + + " case \'/\':\r\n" + + " break; \r\n" + + "\r\n" + + " case \'eq\':\r\n" + + " $token = \'==\';\r\n" + + " break;\r\n" + + "\r\n" + + " case \'ne\':\r\n" + + " case \'neq\':\r\n" + + " $token = \'!=\';\r\n" + + " break;\r\n" + + "\r\n" + + " case \'lt\':\r\n" + + " $token = \'<\';\r\n" + + " break;\r\n" + + "\r\n" + + " case \'le\':\r\n" + + " case \'lte\':\r\n" + + " $token = \'<=\';\r\n" + + " break;\r\n" + + "\r\n" + + " case \'gt\':\r\n" + + " $token = \'>\';\r\n" + + " break;\r\n" + + "\r\n" + + " case \'ge\':\r\n" + + " case \'gte\':\r\n" + + " $token = \'>=\';\r\n" + + " break;\r\n" + + "\r\n" + + " case \'and\':\r\n" + + " $token = \'&&\';\r\n" + + " break;\r\n" + + "\r\n" + + " case \'or\':\r\n" + + " $token = \'||\';\r\n" + + " break;\r\n" + + "\r\n" + + " case \'not\':\r\n" + + " $token = \'!\';\r\n" + + " break;\r\n" + + "\r\n" + + " case \'mod\':\r\n" + + " $token = \'%\';\r\n" + + " break;\r\n" + + "\r\n" + + " case \'(\':\r\n" + + " array_push($is_arg_stack, $i);\r\n" + + " break;\r\n" + + " \r\n" + + " case \'is\':\r\n" + + " /* If last token was a \')\', we operate on the parenthesized\r\n" + + " expression. The start of the expression is on the stack.\r\n" + + " Otherwise, we operate on the last encountered token. */\r\n" + + " if ($tokens[$i-1] == \')\')\r\n" + + " $is_arg_start = array_pop($is_arg_stack);\r\n" + + " else\r\n" + + " $is_arg_start = $i-1;\r\n" + + " /* Construct the argument for \'is\' expression, so it knows\r\n" + + " what to operate on. */\r\n" + + " $is_arg = implode(\' \', array_slice($tokens, $is_arg_start, $i - $is_arg_start));\r\n" + + " \r\n" + + " /* Pass all tokens from next one until the end to the\r\n" + + " \'is\' expression parsing function. The function will\r\n" + + " return modified tokens, where the first one is the result\r\n" + + " of the \'is\' expression and the rest are the tokens it\r\n" + + " didn\'t touch. */ \r\n" + + " $new_tokens = $this->_parse_is_expr($is_arg, array_slice($tokens, $i+1));\r\n" + + " \r\n" + + " /* Replace the old tokens with the new ones. */\r\n" + + " array_splice($tokens, $is_arg_start, count($tokens), $new_tokens);\r\n" + + "\r\n" + + " /* Adjust argument start so that it won\'t change from the\r\n" + + " current position for the next iteration. */\r\n" + + " $i = $is_arg_start;\r\n" + + " break;\r\n" + + " \r\n" + + " default:\r\n" + + " if(preg_match(\'!^\' . $this->_func_regexp . \'$!\', $token) ) {\r\n" + + " // function call \r\n" + + " if($this->security &&\r\n" + + " !in_array($token, $this->security_settings[\'IF_FUNCS\'])) {\r\n" + + " $this->_syntax_error(\"(secure mode) \'$token\' not allowed in if statement\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + + " } \r\n" + + " } elseif(preg_match(\'!^\' . $this->_var_regexp . \'(?:\' . $this->_mod_regexp . \'*)$!\', $token)) {\r\n" + + " // variable\r\n" + + " $token = $this->_parse_var_props($token);\r\n" + + " } elseif(preg_match(\'!^\' . $this->_obj_call_regexp . \'(?:\' . $this->_mod_regexp . \'*)$!\', $token)) {\r\n" + + " // object\r\n" + + " $token = $this->_parse_var_props($token);\r\n" + + " } elseif(is_numeric($token)) {\r\n" + + " // number, skip it\r\n" + + " } else {\r\n" + + " $this->_syntax_error(\"unidentified token \'$token\'\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + + " }\r\n" + + " break;\r\n" + + " }\r\n" + + " }\r\n" + + " \r\n" + + " if ($elseif)\r\n" + + " return \'\';\r\n" + + " else\r\n" + + " return \'\';\r\n" + + " }\r\n" + + "\r\n" + + "\r\n" + + " /**\r\n" + + " * Parse is expression\r\n" + + " *\r\n" + + " * @access public\r\n" + + " * @param $is_arg\r\n" + + " * @param $tokens\r\n" + + " */\r\n" + + " function _parse_is_expr($is_arg, $tokens)\r\n" + + " {\r\n" + + " $expr_end = 0;\r\n" + + " $negate_expr = false;\r\n" + + "\r\n" + + " if (($first_token = array_shift($tokens)) == \'not\') {\r\n" + + " $negate_expr = true;\r\n" + + " $expr_type = array_shift($tokens);\r\n" + + " } else\r\n" + + " $expr_type = $first_token;\r\n" + + "\r\n" + + " switch ($expr_type) {\r\n" + + " case \'even\':\r\n" + + " if (@$tokens[$expr_end] == \'by\') {\r\n" + + " $expr_end++;\r\n" + + " $expr_arg = $tokens[$expr_end++];\r\n" + + " $expr = \"!(($is_arg / $expr_arg) % \" . $this->_parse_var_props($expr_arg) . \")\";\r\n" + + " } else\r\n" + + " $expr = \"!($is_arg % 2)\";\r\n" + + " break;\r\n" + + "\r\n" + + " case \'odd\':\r\n" + + " if (@$tokens[$expr_end] == \'by\') {\r\n" + + " $expr_end++;\r\n" + + " $expr_arg = $tokens[$expr_end++];\r\n" + + " $expr = \"(($is_arg / $expr_arg) % \". $this->_parse_var_props($expr_arg) . \")\";\r\n" + + " } else\r\n" + + " $expr = \"($is_arg % 2)\";\r\n" + + " break;\r\n" + + "\r\n" + + " case \'div\':\r\n" + + " if (@$tokens[$expr_end] == \'by\') {\r\n" + + " $expr_end++;\r\n" + + " $expr_arg = $tokens[$expr_end++];\r\n" + + " $expr = \"!($is_arg % \" . $this->_parse_var_props($expr_arg) . \")\";\r\n" + + " } else {\r\n" + + " $this->_syntax_error(\"expecting \'by\' after \'div\'\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + + " }\r\n" + + " break;\r\n" + + "\r\n" + + " default:\r\n" + + " $this->_syntax_error(\"unknown \'is\' expression - \'$expr_type\'\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + + " break;\r\n" + + " }\r\n" + + "\r\n" + + " if ($negate_expr) {\r\n" + + " $expr = \"!($expr)\";\r\n" + + " }\r\n" + + " \r\n" + + " array_splice($tokens, 0, $expr_end, $expr); \r\n" + + " \r\n" + + " return $tokens;\r\n" + + " }\r\n" + + "\r\n" + + "\r\n" + + " /**\r\n" + + " * Parse attribute string\r\n" + + " *\r\n" + + " * @access public\r\n" + + " * @param $tag_args\r\n" + + " * @param $quote\r\n" + + " */\r\n" + + " function _parse_attrs($tag_args, $quote = true)\r\n" + + " {\r\n" + + " \r\n" + + " /* Tokenize tag attributes. */\r\n" + + " preg_match_all(\'/(?:\' . $this->_obj_call_regexp . \'|\' . $this->_qstr_regexp . \' | (?>[^\"\\\'=\\s]+)\r\n" + + " )+ |\r\n" + + " [=]\r\n" + + " /x\', $tag_args, $match);\r\n" + + " $tokens = $match[0]; \r\n" + + " \r\n" + + " $attrs = array();\r\n" + + " /* Parse state:\r\n" + + " 0 - expecting attribute name\r\n" + + " 1 - expecting \'=\'\r\n" + + " 2 - expecting attribute value (not \'=\') */\r\n" + + " $state = 0;\r\n" + + " \r\n" + + " foreach ($tokens as $token) {\r\n" + + " switch ($state) {\r\n" + + " case 0:\r\n" + + " /* If the token is a valid identifier, we set attribute name\r\n" + + " and go to state 1. */\r\n" + + " if (preg_match(\'!^\\w+$!\', $token)) {\r\n" + + " $attr_name = $token;\r\n" + + " $state = 1;\r\n" + + " } else\r\n" + + " $this->_syntax_error(\"invalid attribute name - \'$token\'\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + + " break;\r\n" + + "\r\n" + + " case 1:\r\n" + + " /* If the token is \'=\', then we go to state 2. */\r\n" + + " if ($token == \'=\') {\r\n" + + " $state = 2;\r\n" + + " } else\r\n" + + " $this->_syntax_error(\"expecting \'=\' after attribute name \'$last_token\'\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + + " break;\r\n" + + "\r\n" + + " case 2:\r\n" + + " /* If token is not \'=\', we set the attribute value and go to\r\n" + + " state 0. */\r\n" + + " if ($token != \'=\') {\r\n" + + " /* We booleanize the token if it\'s a non-quoted possible\r\n" + + " boolean value. */\r\n" + + " if (preg_match(\'!^(on|yes|true)$!\', $token))\r\n" + + " $token = true;\r\n" + + " else if (preg_match(\'!^(off|no|false)$!\', $token))\r\n" + + " $token = false;\r\n" + + " /* If the token is just a string,\r\n" + + " we double-quote it. */\r\n" + + " else if (preg_match(\'!^\\w+$!\', $token)) {\r\n" + + " $token = \'\"\'.$token.\'\"\';\r\n" + + " }\r\n" + + "\r\n" + + " $attrs[$attr_name] = $token;\r\n" + + " $state = 0;\r\n" + + " } else\r\n" + + " $this->_syntax_error(\"\'=\' cannot be an attribute value\", E_USER_ERROR, __FILE__, __LINE__);\r\n" + + " break;\r\n" + + " }\r\n" + + " $last_token = $token;\r\n" + + " }\r\n" + + "\r\n" + + " if($state != 0) {\r\n" + + " if($state == 1) {\r\n" + + " $this->_syntax_error(\"expecting \'=\' after attribute name \'$last_token\'\", E_USER_ERROR, __FILE__, __LINE__); \r\n" + + " } else {\r\n" + + " $this->_syntax_error(\"missing attribute value\", E_USER_ERROR, __FILE__, __LINE__); \r\n" + + " }\r\n" + + " }\r\n" + + " \r\n" + + " $this->_parse_vars_props($attrs);\r\n" + + "\r\n" + + " return $attrs;\r\n" + + " }\r\n" + + "\r\n" + + " /**\r\n" + + " * compile multiple variables and section properties tokens into\r\n" + + " * PHP code\r\n" + + " *\r\n" + + " * @access public\r\n" + + " * @param $tokens\r\n" + + " */\r\n" + + " function _parse_vars_props(&$tokens)\r\n" + + " {\r\n" + + " foreach($tokens as $key => $val) { \r\n" + + " $tokens[$key] = $this->_parse_var_props($val);\r\n" + + " }\r\n" + + " }\r\n" + + " \r\n" + + " /**\r\n" + + " * compile single variable and section properties token into\r\n" + + " * PHP code\r\n" + + " *\r\n" + + " * @access public\r\n" + + " * @param $val\r\n" + + " * @param $tag_attrs\r\n" + + " */\r\n" + + " function _parse_var_props($val, $tag_attrs = null)\r\n" + + " { \r\n" + + "\r\n" + + " $val = trim($val);\r\n" + + "\r\n" + + " if(preg_match(\'!^(\' . $this->_obj_call_regexp . \'|\' . $this->_dvar_regexp . \')(?:\' . $this->_mod_regexp . \'*)$!\', $val)) {\r\n" + + " // $ variable or object\r\n" + + " return $this->_parse_var($val, $tag_attrs);\r\n" + + " } \r\n" + + " elseif(preg_match(\'!^\' . $this->_db_qstr_regexp . \'(?:\' . $this->_mod_regexp . \'*)$!\', $val)) {\r\n" + + " // double quoted text\r\n" + + " preg_match(\'!^(\' . $this->_db_qstr_regexp . \')(\'. $this->_mod_regexp . \'*)$!\', $val, $match);\r\n" + + " $return = $this->_expand_quoted_text($match[1]);\r\n" + + " if($match[2] != \'\') {\r\n" + + " $this->_parse_modifiers($return, $match[2]);\r\n" + + " }\r\n" + + " return $return;\r\n" + + " } \r\n" + + " elseif(preg_match(\'!^\' . $this->_si_qstr_regexp . \'(?:\' . $this->_mod_regexp . \'*)$!\', $val)) {\r\n" + + " // single quoted text\r\n" + + " preg_match(\'!^(\' . $this->_si_qstr_regexp . \')(\'. $this->_mod_regexp . \'*)$!\', $val, $match);\r\n" + + " if($match[2] != \'\') {\r\n" + + " $this->_parse_modifiers($match[1], $match[2]);\r\n" + + " return $match[1];\r\n" + + " } \r\n" + + " } \r\n" + + " elseif(preg_match(\'!^\' . $this->_cvar_regexp . \'(?:\' . $this->_mod_regexp . \'*)$!\', $val)) {\r\n" + + " // config var\r\n" + + " return $this->_parse_conf_var($val);\r\n" + + " } \r\n" + + " elseif(preg_match(\'!^\' . $this->_svar_regexp . \'(?:\' . $this->_mod_regexp . \'*)$!\', $val)) {\r\n" + + " // section var\r\n" + + " return $this->_parse_section_prop($val);\r\n" + + " }\r\n" + + " elseif(!in_array($val, $this->_permitted_tokens) && !is_numeric($val)) {\r\n" + + " // literal string\r\n" + + " return $this->_expand_quoted_text(\'\"\' . $val .\'\"\');\r\n" + + " }\r\n" + + " return $val;\r\n" + + " }\r\n" + + "\r\n" + + " /**\r\n" + + " * expand quoted text with embedded variables\r\n" + + " *\r\n" + + " * @access public\r\n" + + " * @param $var_expr\r\n" + + " */\r\n" + + " function _expand_quoted_text($var_expr)\r\n" + + " {\r\n" + + " // if contains unescaped $, expand it\r\n" + + " if(preg_match_all(\'|(?_dvar_guts_regexp . \'|\', $var_expr, $match)) {\r\n" + + " rsort($match[0]);\r\n" + + " reset($match[0]);\r\n" + + " foreach($match[0] as $var) {\r\n" + + " $var_expr = str_replace ($var, \'\".\' . $this->_parse_var($var) . \'.\"\', $var_expr);\r\n" + + " }\r\n" + + " return preg_replace(\'!\\.\"\"|\"\"\\.!\', \'\', $var_expr);\r\n" + + " } else {\r\n" + + " return $var_expr;\r\n" + + " }\r\n" + + " }\r\n" + + " \r\n" + + " /**\r\n" + + " * parse variable expression into PHP code\r\n" + + " *\r\n" + + " * @access public\r\n" + + " * @param $var_expr\r\n" + + " */\r\n" + + " function _parse_var($var_expr)\r\n" + + " {\r\n" + + " \r\n" + + " preg_match(\'!(\' . $this->_obj_call_regexp . \'|\' . $this->_var_regexp . \')(\' . $this->_mod_regexp . \'*)$!\', $var_expr, $match);\r\n" + + " \r\n" + + " $var_ref = substr($match[1],1);\r\n" + + " $modifiers = $match[2];\r\n" + + " \r\n" + + " if(!empty($this->default_modifiers) && !preg_match(\'!(^|\\|)smarty:nodefaults($|\\|)!\',$modifiers)) {\r\n" + + " $_default_mod_string = implode(\'|\',(array)$this->default_modifiers);\r\n" + + " $modifiers = empty($modifiers) ? $_default_mod_string : $_default_mod_string . \'|\' . $modifiers;\r\n" + + " }\r\n" + + "\r\n" + + " // get [foo] and .foo and ->foo() pieces \r\n" + + " preg_match_all(\'!(?:^\\w+)|(?:\' . $this->_obj_ext_regexp . \')+(?:\' . $this->_obj_params_regexp . \')?|(?:\' . $this->_var_bracket_regexp . \')|\\.\\$?\\w+!\', $var_ref, $match); \r\n" + + " \r\n" + + " $indexes = $match[0];\r\n" + + " $var_name = array_shift($indexes);\r\n" + + " \r\n" + + " /* Handle $smarty.* variable references as a special case. */\r\n" + + " if ($var_name == \'smarty\') {\r\n" + + " /*\r\n" + + " * If the reference could be compiled, use the compiled output;\r\n" + + " * otherwise, fall back on the $smarty variable generated at\r\n" + + " * run-time.\r\n" + + " */\r\n" + + " if (($smarty_ref = $this->_compile_smarty_ref($indexes)) !== null) {\r\n" + + " $output = $smarty_ref;\r\n" + + " } else {\r\n" + + " $var_name = substr(array_shift($indexes), 1);\r\n" + + " $output = \"\\$this->_smarty_vars[\'$var_name\']\";\r\n" + + " }\r\n" + + " } else {\r\n" + + " $output = \"\\$this->_tpl_vars[\'$var_name\']\";\r\n" + + " }\r\n" + + "\r\n" + + " foreach ($indexes as $index) { \r\n" + + " if ($index{0} == \'[\') {\r\n" + + " $index = substr($index, 1, -1);\r\n" + + " if (is_numeric($index)) {\r\n" + + " $output .= \"[$index]\";\r\n" + + " } elseif ($index{0} == \'$\') {\r\n" + + " $output .= \"[\\$this->_tpl_vars[\'\" . substr($index, 1) . \"\']]\";\r\n" + + " } else {\r\n" + + " $parts = explode(\'.\', $index);\r\n" + + " $section = $parts[0];\r\n" + + " $section_prop = isset($parts[1]) ? $parts[1] : \'index\';\r\n" + + " $output .= \"[\\$this->_sections[\'$section\'][\'$section_prop\']]\";\r\n" + + " }\r\n" + + " } else if ($index{0} == \'.\') {\r\n" + + " if ($index{1} == \'$\')\r\n" + + " $output .= \"[\\$this->_tpl_vars[\'\" . substr($index, 2) . \"\']]\";\r\n" + + " else\r\n" + + " $output .= \"[\'\" . substr($index, 1) . \"\']\";\r\n" + + " } else if (substr($index,0,2) == \'->\') {\r\n" + + " if(substr($index,2,2) == \'__\') {\r\n" + + " $this->_syntax_error(\'call to internal object members is not allowed\', E_USER_ERROR, __FILE__, __LINE__);\r\n" + + " } elseif($this->security && substr($index,2,1) == \'_\') {\r\n" + + " $this->_syntax_error(\'(secure) call to private object member is not allowed\', E_USER_ERROR, __FILE__, __LINE__);\r\n" + + " } else {\r\n" + + " if(preg_match(\'!((?:\' . $this->_obj_ext_regexp . \')+)(\' . $this->_obj_params_regexp . \')?!\', $index, $match)) {\r\n" + + " if(!empty($match[2])) {\r\n" + + " // parse object parameters\r\n" + + " $index = str_replace($match[2], $this->_parse_parenth_args($match[2]), $index);\r\n" + + " }\r\n" + + " if(preg_match_all(\'!\' . $this->_dvar_regexp . \'!\', $match[1], $_dvar_match)) {\r\n" + + " // parse embedded variables\r\n" + + " $_match_replace = $match[1];\r\n" + + " foreach($_dvar_match[0] as $_curr_var) {\r\n" + + " $_match_replace = str_replace($_curr_var, \'{\' . $this->_parse_var($_curr_var) . \'}\', $_match_replace);\r\n" + + " }\r\n" + + " $index = str_replace($match[1], $_match_replace, $index);\r\n" + + " }\r\n" + + " }\r\n" + + " $output .= $index;\r\n" + + " }\r\n" + + " } else {\r\n" + + " $output .= $index;\r\n" + + " }\r\n" + + " }\r\n" + + "\r\n" + + " // look for variables imbedded in quoted strings, replace them\r\n" + + " if(preg_match(\'!\' . $this->_qstr_regexp . \'!\', $output, $match)) {\r\n" + + " $output = str_replace($match[0], $this->_expand_quoted_text($match[0]), $output);\r\n" + + " }\r\n" + + " \r\n" + + " $this->_parse_modifiers($output, $modifiers);\r\n" + + "\r\n" + + " return $output;\r\n" + + " }\r\n" + + "\r\n" + + " /**\r\n" + + " * parse arguments in function call parenthesis\r\n" + + " *\r\n" + + " * @access public\r\n" + + " * @param $parenth_args\r\n" + + " */\r\n" + + " function _parse_parenth_args($parenth_args)\r\n" + + " {\r\n" + + " preg_match_all(\'!\' . $this->_param_regexp . \'!\',$parenth_args, $match);\r\n" + + " $match = $match[0];\r\n" + + " rsort($match);\r\n" + + " reset($match); \r\n" + + " $orig_vals = $match;\r\n" + + " $this->_parse_vars_props($match);\r\n" + + " return str_replace($orig_vals, $match, $parenth_args);\r\n" + + " } \r\n" + + " \r\n" + + " /**\r\n" + + " * parse configuration variable expression into PHP code\r\n" + + " *\r\n" + + " * @access public\r\n" + + " * @param $conf_var_expr\r\n" + + " */\r\n" + + " function _parse_conf_var($conf_var_expr)\r\n" + + " {\r\n" + + " $parts = explode(\'|\', $conf_var_expr, 2);\r\n" + + " $var_ref = $parts[0];\r\n" + + " $modifiers = isset($parts[1]) ? $parts[1] : \'\';\r\n" + + "\r\n" + + " $var_name = substr($var_ref, 1, -1);\r\n" + + "\r\n" + + " $output = \"\\$this->_config[0][\'vars\'][\'$var_name\']\";\r\n" + + "\r\n" + + " $this->_parse_modifiers($output, $modifiers);\r\n" + + "\r\n" + + " return $output;\r\n" + + " }\r\n" + + "\r\n" + + "\r\n" + + " /**\r\n" + + " * parse section property expression into PHP code\r\n" + + " *\r\n" + + " * @access public\r\n" + + " * @param $section_prop_expr\r\n" + + " */\r\n" + + " function _parse_section_prop($section_prop_expr)\r\n" + + " {\r\n" + + " $parts = explode(\'|\', $section_prop_expr, 2);\r\n" + + " $var_ref = $parts[0];\r\n" + + " $modifiers = isset($parts[1]) ? $parts[1] : \'\';\r\n" + + "\r\n" + + " preg_match(\'!%(\\w+)\\.(\\w+)%!\', $var_ref, $match);\r\n" + + " $section_name = $match[1];\r\n" + + " $prop_name = $match[2];\r\n" + + "\r\n" + + " $output = \"\\$this->_sections[\'$section_name\'][\'$prop_name\']\";\r\n" + + "\r\n" + + " $this->_parse_modifiers($output, $modifiers);\r\n" + + "\r\n" + + " return $output;\r\n" + + " }\r\n" + + "\r\n" + + "\r\n" + + " /**\r\n" + + " * parse modifier chain into PHP code\r\n" + + " *\r\n" + + " * @access public\r\n" + + " * @param $output\r\n" + + " * @param $modifier_string\r\n" + + " */\r\n" + + " function _parse_modifiers(&$output, $modifier_string)\r\n" + + " {\r\n" + + " preg_match_all(\'!\\|(@?\\w+)((?>:(?:\'. $this->_qstr_regexp . \'|[^|]+))*)!\', \'|\' . $modifier_string, $match);\r\n" + + " list(, $modifiers, $modifier_arg_strings) = $match;\r\n" + + "\r\n" + + " for ($i = 0, $for_max = count($modifiers); $i < $for_max; $i++) {\r\n" + + " $modifier_name = $modifiers[$i];\r\n" + + " \r\n" + + " if($modifier_name == \'smarty\') {\r\n" + + " // skip smarty modifier\r\n" + + " continue;\r\n" + + " }\r\n" + + " \r\n" + + " preg_match_all(\'!:(\' . $this->_qstr_regexp . \'|[^:]+)!\', $modifier_arg_strings[$i], $match);\r\n" + + " $modifier_args = $match[1];\r\n" + + "\r\n" + + " if ($modifier_name{0} == \'@\') {\r\n" + + " $map_array = \'false\';\r\n" + + " $modifier_name = substr($modifier_name, 1);\r\n" + + " } else {\r\n" + + " $map_array = \'true\';\r\n" + + " }\r\n" + + " \r\n" + + " $this->_add_plugin(\'modifier\', $modifier_name);\r\n" + + "\r\n" + + " $this->_parse_vars_props($modifier_args);\r\n" + + "\r\n" + + " if (count($modifier_args) > 0)\r\n" + + " $modifier_args = \', \'.implode(\', \', $modifier_args);\r\n" + + " else\r\n" + + " $modifier_args = \'\';\r\n" + + "\r\n" + + " $output = \"\\$this->_run_mod_handler(\'$modifier_name\', $map_array, $output$modifier_args)\";\r\n" + + " }\r\n" + + " }\r\n" + + "\r\n" + + "\r\n" + + " /**\r\n" + + " * add plugin\r\n" + + " *\r\n" + + " * @access public\r\n" + + " * @param $type\r\n" + + " * @param $name\r\n" + + " * @param $delayed_loading\r\n" + + " */\r\n" + + " function _add_plugin($type, $name, $delayed_loading = null)\r\n" + + " {\r\n" + + " if (!isset($this->_plugin_info[$type])) {\r\n" + + " $this->_plugin_info[$type] = array();\r\n" + + " }\r\n" + + " if (!isset($this->_plugin_info[$type][$name])) {\r\n" + + " $this->_plugin_info[$type][$name] = array($this->_current_file,\r\n" + + " $this->_current_line_no,\r\n" + + " $delayed_loading);\r\n" + + " }\r\n" + + " }\r\n" + + " \r\n" + + "\r\n" + + " /**\r\n" + + " * Compiles references of type $smarty.foo\r\n" + + " *\r\n" + + " * @access public\r\n" + + " * @param $indexes\r\n" + + " */\r\n" + + " function _compile_smarty_ref(&$indexes)\r\n" + + " {\r\n" + + " /* Extract the reference name. */\r\n" + + " $ref = substr($indexes[0], 1);\r\n" + + "\r\n" + + " switch ($ref) {\r\n" + + " case \'now\':\r\n" + + " $compiled_ref = \'time()\';\r\n" + + " if (count($indexes) > 1) {\r\n" + + " $this->_syntax_error(\'$smarty\' . implode(\'\', $indexes) .\' is an invalid reference\', E_USER_ERROR, __FILE__, __LINE__);\r\n" + + " }\r\n" + + " break;\r\n" + + "\r\n" + + " case \'foreach\':\r\n" + + " case \'section\':\r\n" + + " if ($indexes[1]{0} != \'.\') {\r\n" + + " $this->_syntax_error(\'$smarty\' . implode(\'\', array_slice($indexes, 0, 2)) . \' is an invalid reference\', E_USER_ERROR, __FILE__, __LINE__);\r\n" + + " }\r\n" + + " $name = substr($indexes[1], 1);\r\n" + + " array_shift($indexes);\r\n" + + " if ($ref == \'foreach\')\r\n" + + " $compiled_ref = \"\\$this->_foreach[\'$name\']\";\r\n" + + " else\r\n" + + " $compiled_ref = \"\\$this->_sections[\'$name\']\";\r\n" + + " break;\r\n" + + "\r\n" + + " case \'get\':\r\n" + + " array_shift($indexes);\r\n" + + " $compiled_ref = \"\\$_GET\";\r\n" + + " if ($name = substr($indexes[0], 1))\r\n" + + " $compiled_ref .= \"[\'$name\']\";\r\n" + + " break;\r\n" + + "\r\n" + + " case \'post\':\r\n" + + " array_shift($indexes);\r\n" + + " $name = substr($indexes[0], 1);\r\n" + + " $compiled_ref = \"\\$_POST\";\r\n" + + " if ($name = substr($indexes[0], 1))\r\n" + + " $compiled_ref .= \"[\'$name\']\";\r\n" + + " break;\r\n" + + "\r\n" + + " case \'cookies\':\r\n" + + " array_shift($indexes);\r\n" + + " $name = substr($indexes[0], 1);\r\n" + + " $compiled_ref = \"\\$_COOKIE\";\r\n" + + " if ($name = substr($indexes[0], 1))\r\n" + + " $compiled_ref .= \"[\'$name\']\";\r\n" + + " break;\r\n" + + "\r\n" + + " case \'env\':\r\n" + + " array_shift($indexes);\r\n" + + " $compiled_ref = \"\\$_ENV\";\r\n" + + " if ($name = substr($indexes[0], 1))\r\n" + + " $compiled_ref .= \"[\'$name\']\";\r\n" + + " break;\r\n" + + "\r\n" + + " case \'server\':\r\n" + + " array_shift($indexes);\r\n" + + " $name = substr($indexes[0], 1);\r\n" + + " $compiled_ref = \"\\$_SERVER\";\r\n" + + " if ($name = substr($indexes[0], 1))\r\n" + + " $compiled_ref .= \"[\'$name\']\";\r\n" + + " break;\r\n" + + "\r\n" + + " case \'session\':\r\n" + + " array_shift($indexes);\r\n" + + " $name = substr($indexes[0], 1);\r\n" + + " $compiled_ref = \"\\$_SESSION\";\r\n" + + " if ($name = substr($indexes[0], 1))\r\n" + + " $compiled_ref .= \"[\'$name\']\";\r\n" + + " break;\r\n" + + "\r\n" + + " /*\r\n" + + " * These cases are handled either at run-time or elsewhere in the\r\n" + + " * compiler.\r\n" + + " */\r\n" + + " case \'request\':\r\n" + + " $this->_init_smarty_vars = true;\r\n" + + " return null;\r\n" + + "\r\n" + + " case \'capture\':\r\n" + + " return null;\r\n" + + "\r\n" + + " case \'template\':\r\n" + + " $compiled_ref = \"\'$this->_current_file\'\";\r\n" + + " if (count($indexes) > 1) {\r\n" + + " $this->_syntax_error(\'$smarty\' . implode(\'\', $indexes) .\' is an invalid reference\', E_USER_ERROR, __FILE__, __LINE__);\r\n" + + " }\r\n" + + " break;\r\n" + + " \r\n" + + " case \'version\':\r\n" + + " $compiled_ref = \"\'$this->_version\'\";\r\n" + + " break;\r\n" + + "\r\n" + + " case \'const\':\r\n" + + " array_shift($indexes);\r\n" + + " $compiled_ref = \'defined(\\\'\' . substr($indexes[0],1) . \'\\\') ? \' . substr($indexes[0],1) . \' : null\';\r\n" + + " break;\r\n" + + "\r\n" + + " default:\r\n" + + " $this->_syntax_error(\'$smarty.\' . $ref . \' is an unknown reference\', E_USER_ERROR, __FILE__, __LINE__);\r\n" + + " break;\r\n" + + " }\r\n" + + "\r\n" + + " array_shift($indexes);\r\n" + + " return $compiled_ref;\r\n" + + " }\r\n" + + "\r\n" + + "\r\n" + + " /**\r\n" + + " * load pre- and post-filters\r\n" + + " *\r\n" + + " * @access public\r\n" + + " */\r\n" + + " function _load_filters()\r\n" + + " {\r\n" + + " if (count($this->_plugins[\'prefilter\']) > 0) {\r\n" + + " foreach ($this->_plugins[\'prefilter\'] as $filter_name => $prefilter) {\r\n" + + " if ($prefilter === false) {\r\n" + + " unset($this->_plugins[\'prefilter\'][$filter_name]);\r\n" + + " $this->_load_plugins(array(array(\'prefilter\', $filter_name, null, null, false)));\r\n" + + " }\r\n" + + " }\r\n" + + " }\r\n" + + " if (count($this->_plugins[\'postfilter\']) > 0) {\r\n" + + " foreach ($this->_plugins[\'postfilter\'] as $filter_name => $postfilter) {\r\n" + + " if ($postfilter === false) {\r\n" + + " unset($this->_plugins[\'postfilter\'][$filter_name]);\r\n" + + " $this->_load_plugins(array(array(\'postfilter\', $filter_name, null, null, false)));\r\n" + + " }\r\n" + + " }\r\n" + + " }\r\n" + + " }\r\n" + + "\r\n" + + "\r\n" + + " /**\r\n" + + " * display Smarty syntax error\r\n" + + " *\r\n" + + " * @access public\r\n" + + " * @param $error_msg\r\n" + + " * @param $error_type\r\n" + + " * @param $file\r\n" + + " * @param $line\r\n" + + " */\r\n" + + " function _syntax_error($error_msg, $error_type = E_USER_ERROR, $file=null, $line=null)\r\n" + + " {\r\n" + + " if(isset($file) && isset($line)) {\r\n" + + " $info = \' (\'.basename($file).\", line $line)\";\r\n" + + " } else {\r\n" + + " $info = null;\r\n" + + " }\r\n" + + " trigger_error(\'Smarty: [in \' . $this->_current_file . \' line \' .\r\n" + + " $this->_current_line_no . \"]: syntax error: $error_msg$info\", $error_type);\r\n" + + " }\r\n" + "}\r\n" + "\r\n" + "/**\r\n" + + " * compare to values by their string length\r\n" + " *\r\n" + + " * @access private\r\n" + " * @param $a\r\n" + + " * @param $b\r\n" + " */\r\n" + + "function _smarty_sort_length($a, $b)\r\n" + "{\r\n" + + " if($a == $b)\r\n" + " return 0;\r\n" + "\r\n" + + " if(strlen($a) == strlen($b))\r\n" + + " return ($a > $b) ? -1 : 1;\r\n" + "\r\n" + + " return (strlen($a) > strlen($b)) ? -1 : 1;\r\n" + "}\r\n" + + "\r\n" + "\r\n" + "/* vim: set et: */\r\n" + "\r\n" + + "?>\r\n" + ""); + } } diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/ColorManager.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/ColorManager.java index 469b9c6..c72c31b 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/ColorManager.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/ColorManager.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: ColorManager.java,v 1.1 2004-09-02 18:26:49 jsurfer Exp $ + * $Id: ColorManager.java,v 1.2 2006-10-21 23:13:54 pombredanne Exp $ */ package net.sourceforge.phpeclipse.ui; @@ -27,33 +27,33 @@ import org.eclipse.swt.widgets.Display; * @author Igor Malinin */ public class ColorManager { - protected Map colors = new HashMap( 10 ); + protected Map colors = new HashMap(10); - public void bindColor( String key, RGB rgb ) { - Object value = colors.get( key ); - if ( value != null ) { + public void bindColor(String key, RGB rgb) { + Object value = colors.get(key); + if (value != null) { throw new UnsupportedOperationException(); } - Color color = new Color( Display.getCurrent(), rgb ); + Color color = new Color(Display.getCurrent(), rgb); - colors.put( key, color ); + colors.put(key, color); } - public void unbindColor( String key ) { - Color color = (Color) colors.remove( key ); - if ( color != null ) { + public void unbindColor(String key) { + Color color = (Color) colors.remove(key); + if (color != null) { color.dispose(); } } - public Color getColor( String key ) { - return (Color) colors.get( key ); + public Color getColor(String key) { + return (Color) colors.get(key); } public void dispose() { Iterator i = colors.values().iterator(); - while ( i.hasNext() ) { + while (i.hasNext()) { ((Color) i.next()).dispose(); } } diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/IPreferenceConstants.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/IPreferenceConstants.java index 1e88ded..73cd6f5 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/IPreferenceConstants.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/IPreferenceConstants.java @@ -1,15 +1,19 @@ - package net.sourceforge.phpeclipse.ui; - public interface IPreferenceConstants { -// public static final String PHP_BOOKMARK_DEFAULT = "_php_bookmark_default"; - public static final String PHP_LOCALHOST_PREF = "_php_localhost"; - public static final String PHP_DOCUMENTROOT_PREF = "_php_documentroot"; - public static final String PHP_INCLUDE_PATHS = "_php_include_paths"; - - public static final String PHP_AUTO_PREVIEW_DEFAULT = "_auto_preview"; - public static final String PHP_BRING_TO_TOP_PREVIEW_DEFAULT = "_bring_to_top_preview"; -// public static final String PHP_SHOW_HTML_FILES_LOCAL = "_show_html_files_local"; -// public static final String PHP_SHOW_XML_FILES_LOCAL = "_show_xml_files_local"; + // public static final String PHP_BOOKMARK_DEFAULT = + // "_php_bookmark_default"; + public static final String PHP_LOCALHOST_PREF = "_php_localhost"; + + public static final String PHP_DOCUMENTROOT_PREF = "_php_documentroot"; + + public static final String PHP_INCLUDE_PATHS = "_php_include_paths"; + + public static final String PHP_AUTO_PREVIEW_DEFAULT = "_auto_preview"; + + public static final String PHP_BRING_TO_TOP_PREVIEW_DEFAULT = "_bring_to_top_preview"; + // public static final String PHP_SHOW_HTML_FILES_LOCAL = + // "_show_html_files_local"; + // public static final String PHP_SHOW_XML_FILES_LOCAL = + // "_show_xml_files_local"; } diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/PreferenceConstants.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/PreferenceConstants.java index 6697534..7c0e987 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/PreferenceConstants.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/PreferenceConstants.java @@ -3,26 +3,31 @@ package net.sourceforge.phpeclipse.ui; import org.eclipse.jface.preference.IPreferenceStore; public class PreferenceConstants { - /** - * A named preference that holds the characters that auto activate code assist in XML/HTML. - *

    - * Value is of type Sring. All characters that trigger auto code assist in XML/HTML. - *

    - */ - public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_HTML = "content_assist_autoactivation_triggers_html"; //$NON-NLS-1$ + /** + * A named preference that holds the characters that auto activate code + * assist in XML/HTML. + *

    + * Value is of type Sring. All characters that trigger auto + * code assist in XML/HTML. + *

    + */ + public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_HTML = "content_assist_autoactivation_triggers_html"; //$NON-NLS-1$ - /** - * A named preference that defines if code assist proposals are sorted in alphabetical order. - *

    - * Value is of type Boolean. If true that are sorted in alphabetical - * order. If false that are unsorted. - *

    - */ - public final static String CODEASSIST_ORDER_PROPOSALS = "content_assist_order_proposals"; //$NON-NLS-1$ + /** + * A named preference that defines if code assist proposals are sorted in + * alphabetical order. + *

    + * Value is of type Boolean. If true that are + * sorted in alphabetical order. If false that are unsorted. + *

    + */ + public final static String CODEASSIST_ORDER_PROPOSALS = "content_assist_order_proposals"; //$NON-NLS-1$ - public static void initializeDefaultValues(IPreferenceStore store) { - store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_HTML, "<&#"); //$NON-NLS-1$ - store.setDefault(PreferenceConstants.CODEASSIST_ORDER_PROPOSALS, false); + public static void initializeDefaultValues(IPreferenceStore store) { + store.setDefault( + PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_HTML, + "<&#"); //$NON-NLS-1$ + store.setDefault(PreferenceConstants.CODEASSIST_ORDER_PROPOSALS, false); - } + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/WebUI.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/WebUI.java index 76ccbd5..8404335 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/WebUI.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/WebUI.java @@ -8,7 +8,7 @@ * Contributors: * Christopher Lenz - initial implementation * - * $Id: WebUI.java,v 1.6 2005-10-13 18:38:19 axelcl Exp $ + * $Id: WebUI.java,v 1.7 2006-10-21 23:13:54 pombredanne Exp $ */ package net.sourceforge.phpeclipse.ui; @@ -41,139 +41,150 @@ import org.eclipse.ui.plugin.AbstractUIPlugin; * The web development tools UI plugin. */ public class WebUI extends AbstractUIPlugin implements IPreferenceConstants { - private static final String CUSTOM_TEMPLATES_KEY = "net.sourceforge.phpeclipse.ui.templates"; //$NON-NLS-1$ - - // Constants --------------------------------------------------------------- - - public static final String ICON_OVERLAY_ERROR = "full/ovr16/error_co.gif"; //$NON-NLS-1$ - - public static final String ICON_OVERLAY_WARNING = "full/ovr16/warning_co.gif"; //$NON-NLS-1$ - - // Instance Variables ------------------------------------------------------ - - /** The shared instance. */ - private static WebUI plugin; - - public static IWorkbenchPage getActivePage() { - return getDefault().internalGetActivePage(); - } - - private IWorkbenchPage internalGetActivePage() { - return getWorkbench().getActiveWorkbenchWindow().getActivePage(); - } - - public static Shell getActiveWorkbenchShell() { - return getActiveWorkbenchWindow().getShell(); - } - - public static IWorkbenchWindow getActiveWorkbenchWindow() { - return getDefault().getWorkbench().getActiveWorkbenchWindow(); - } - // Public Methods ---------------------------------------------------------- - - /** - * Returns the shared instance. - */ - public static WebUI getDefault() { - return plugin; - } - - /** - * Returns the workspace instance. - */ - public static IWorkspace getWorkspace() { - return ResourcesPlugin.getWorkspace(); - } - - /** The context type registry. */ - private ContributionContextTypeRegistry fRegistry; - - /** The template store. */ - private TemplateStore fStore; - - // Constructors ------------------------------------------------------------ - - /** - * The constructor. - */ - public WebUI() { - plugin = this; - } - - /** - * Returns this plug-in's context type registry. - * - * @return the context type registry for this plug-in instance - */ - public ContextTypeRegistry getContextTypeRegistry() { - if (fRegistry == null) { - // create an configure the contexts available in the editor - fRegistry = new ContributionContextTypeRegistry(); - fRegistry.addContextType(XMLContextType.XML_CONTEXT_TYPE); - fRegistry.addContextType(HTMLContextType.HTML_CONTEXT_TYPE); - fRegistry.addContextType(SmartyContextType.SMARTY_CONTEXT_TYPE); - fRegistry.addContextType(JSContextType.JS_CONTEXT_TYPE); - } - return fRegistry; - } - - // Private Methods --------------------------------------------------------- - - /** - * Returns an image descriptor for the image corresponding to the specified key (which is the name of the image file). - * - * @param key - * The key of the image - * @return The descriptor for the requested image, or null if the image could not be found - */ - private ImageDescriptor getImageDescriptor(String key) { - try { - URL url = getBundle().getEntry("/icons/" + key); //$NON-NLS-1$ - return ImageDescriptor.createFromURL(url); - } catch (IllegalStateException e) { - return null; - } - } - - /** - * Returns this plug-in's template store. - * - * @return the template store of this plug-in instance - */ - public TemplateStore getTemplateStore() { - if (fStore == null) { - fStore = new ContributionTemplateStore(getContextTypeRegistry(), getDefault().getPreferenceStore(), CUSTOM_TEMPLATES_KEY); - try { - fStore.load(); - } catch (IOException e) { - WebUI.getDefault().getLog().log(new Status(IStatus.ERROR, "net.sourceforge.phpeclipse.ui", IStatus.OK, "", e)); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - return fStore; - } - - protected void initializeDefaultPreferences(IPreferenceStore store) { - store.setDefault(PHP_LOCALHOST_PREF, "http://localhost"); - store.setDefault(PHP_DOCUMENTROOT_PREF, getWorkspace().getRoot().getLocation().toString()); -// store.setDefault(PHP_BOOKMARK_DEFAULT, ""); - - store.setDefault(PHP_AUTO_PREVIEW_DEFAULT, "true"); - store.setDefault(PHP_BRING_TO_TOP_PREVIEW_DEFAULT, "true"); -// store.setDefault(PHP_SHOW_HTML_FILES_LOCAL, "true"); -// store.setDefault(PHP_SHOW_XML_FILES_LOCAL, "false"); - } - - /* - * @see AbstractUIPlugin#initializeImageRegistry(ImageRegistry) - */ - protected void initializeImageRegistry(ImageRegistry reg) { - reg.put(ICON_OVERLAY_ERROR, getImageDescriptor(ICON_OVERLAY_ERROR)); - reg.put(ICON_OVERLAY_WARNING, getImageDescriptor(ICON_OVERLAY_WARNING)); - } - // private IWorkbenchPage internalGetActivePage() { - // IWorkbenchWindow window = getWorkbench().getActiveWorkbenchWindow(); - // if (window != null) - // return window.getActivePage(); - // return null; - // } + private static final String CUSTOM_TEMPLATES_KEY = "net.sourceforge.phpeclipse.ui.templates"; //$NON-NLS-1$ + + // Constants --------------------------------------------------------------- + + public static final String ICON_OVERLAY_ERROR = "full/ovr16/error_co.gif"; //$NON-NLS-1$ + + public static final String ICON_OVERLAY_WARNING = "full/ovr16/warning_co.gif"; //$NON-NLS-1$ + + // Instance Variables ------------------------------------------------------ + + /** The shared instance. */ + private static WebUI plugin; + + public static IWorkbenchPage getActivePage() { + return getDefault().internalGetActivePage(); + } + + private IWorkbenchPage internalGetActivePage() { + return getWorkbench().getActiveWorkbenchWindow().getActivePage(); + } + + public static Shell getActiveWorkbenchShell() { + return getActiveWorkbenchWindow().getShell(); + } + + public static IWorkbenchWindow getActiveWorkbenchWindow() { + return getDefault().getWorkbench().getActiveWorkbenchWindow(); + } + + // Public Methods ---------------------------------------------------------- + + /** + * Returns the shared instance. + */ + public static WebUI getDefault() { + return plugin; + } + + /** + * Returns the workspace instance. + */ + public static IWorkspace getWorkspace() { + return ResourcesPlugin.getWorkspace(); + } + + /** The context type registry. */ + private ContributionContextTypeRegistry fRegistry; + + /** The template store. */ + private TemplateStore fStore; + + // Constructors ------------------------------------------------------------ + + /** + * The constructor. + */ + public WebUI() { + plugin = this; + } + + /** + * Returns this plug-in's context type registry. + * + * @return the context type registry for this plug-in instance + */ + public ContextTypeRegistry getContextTypeRegistry() { + if (fRegistry == null) { + // create an configure the contexts available in the editor + fRegistry = new ContributionContextTypeRegistry(); + fRegistry.addContextType(XMLContextType.XML_CONTEXT_TYPE); + fRegistry.addContextType(HTMLContextType.HTML_CONTEXT_TYPE); + fRegistry.addContextType(SmartyContextType.SMARTY_CONTEXT_TYPE); + fRegistry.addContextType(JSContextType.JS_CONTEXT_TYPE); + } + return fRegistry; + } + + // Private Methods --------------------------------------------------------- + + /** + * Returns an image descriptor for the image corresponding to the specified + * key (which is the name of the image file). + * + * @param key + * The key of the image + * @return The descriptor for the requested image, or null if + * the image could not be found + */ + private ImageDescriptor getImageDescriptor(String key) { + try { + URL url = getBundle().getEntry("/icons/" + key); //$NON-NLS-1$ + return ImageDescriptor.createFromURL(url); + } catch (IllegalStateException e) { + return null; + } + } + + /** + * Returns this plug-in's template store. + * + * @return the template store of this plug-in instance + */ + public TemplateStore getTemplateStore() { + if (fStore == null) { + fStore = new ContributionTemplateStore(getContextTypeRegistry(), + getDefault().getPreferenceStore(), CUSTOM_TEMPLATES_KEY); + try { + fStore.load(); + } catch (IOException e) { + WebUI + .getDefault() + .getLog() + .log( + new Status( + IStatus.ERROR, + "net.sourceforge.phpeclipse.ui", IStatus.OK, "", e)); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + return fStore; + } + + protected void initializeDefaultPreferences(IPreferenceStore store) { + store.setDefault(PHP_LOCALHOST_PREF, "http://localhost"); + store.setDefault(PHP_DOCUMENTROOT_PREF, getWorkspace().getRoot() + .getLocation().toString()); + // store.setDefault(PHP_BOOKMARK_DEFAULT, ""); + + store.setDefault(PHP_AUTO_PREVIEW_DEFAULT, "true"); + store.setDefault(PHP_BRING_TO_TOP_PREVIEW_DEFAULT, "true"); + // store.setDefault(PHP_SHOW_HTML_FILES_LOCAL, "true"); + // store.setDefault(PHP_SHOW_XML_FILES_LOCAL, "false"); + } + + /* + * @see AbstractUIPlugin#initializeImageRegistry(ImageRegistry) + */ + protected void initializeImageRegistry(ImageRegistry reg) { + reg.put(ICON_OVERLAY_ERROR, getImageDescriptor(ICON_OVERLAY_ERROR)); + reg.put(ICON_OVERLAY_WARNING, getImageDescriptor(ICON_OVERLAY_WARNING)); + } + // private IWorkbenchPage internalGetActivePage() { + // IWorkbenchWindow window = getWorkbench().getActiveWorkbenchWindow(); + // if (window != null) + // return window.getActivePage(); + // return null; + // } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/editor/BrowserUtil.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/editor/BrowserUtil.java index a70b636..f5781be 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/editor/BrowserUtil.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/editor/BrowserUtil.java @@ -18,7 +18,8 @@ import org.eclipse.ui.part.ShowInContext; public class BrowserUtil { - public static ShowInContextBrowser getShowInContext(IFile previewFile, boolean forceDBGPreview, String postFix) { + public static ShowInContextBrowser getShowInContext(IFile previewFile, + boolean forceDBGPreview, String postFix) { String extension = previewFile.getFileExtension().toLowerCase(); // boolean showHTMLFilesLocal = false; // boolean showXMLFilesLocal = false; @@ -29,17 +30,21 @@ public class BrowserUtil { // showHTMLFilesLocal = // ProjectPrefUtil.getPreviewBooleanValue(previewFile, // IPreferenceConstants.PHP_SHOW_HTML_FILES_LOCAL); - // showXMLFilesLocal = ProjectPrefUtil.getPreviewBooleanValue(previewFile, + // showXMLFilesLocal = + // ProjectPrefUtil.getPreviewBooleanValue(previewFile, // IPreferenceConstants.PHP_SHOW_XML_FILES_LOCAL); - isHTMLFileName = "html".equals(extension) || "htm".equals(extension) || "xhtml".equals(extension); - isXMLFileName = "xml".equals(extension) || "xsd".equals(extension) || "dtd".equals(extension); + isHTMLFileName = "html".equals(extension) + || "htm".equals(extension) || "xhtml".equals(extension); + isXMLFileName = "xml".equals(extension) || "xsd".equals(extension) + || "dtd".equals(extension); } // if (showHTMLFilesLocal && isHTMLFileName) { // localhostURL = previewFile.getLocation().toString(); // } else if (showXMLFilesLocal && isXMLFileName) { // localhostURL = previewFile.getLocation().toString(); // } else - if ((localhostURL = ShowExternalPreviewAction.getLocalhostURL(null, previewFile)) == null) { + if ((localhostURL = ShowExternalPreviewAction.getLocalhostURL(null, + previewFile)) == null) { return new ShowInContextBrowser(previewFile, null, null); } localhostURL += postFix; @@ -49,9 +54,9 @@ public class BrowserUtil { /** * Returns the IShowInTarget for the given part, or * null if it does not provide one. - * + * * @param targetPart - * the target part + * the target part * @return the IShowInTarget or null */ private static IShowInTarget getShowInTarget(IWorkbenchPart targetPart) { @@ -65,7 +70,8 @@ public class BrowserUtil { return null; } - public static void showPreview(IFile previewFile, boolean forceDBGPreview, String postFix) { + public static void showPreview(IFile previewFile, boolean forceDBGPreview, + String postFix) { if (previewFile == null) { // should never happen return; @@ -79,7 +85,9 @@ public class BrowserUtil { // boolean isHTMLFileName = false; // boolean isXMLFileName = false; if (!forceDBGPreview) { - autoPreview = ProjectPrefUtil.getPreviewBooleanValue(previewFile, IPreferenceConstants.PHP_AUTO_PREVIEW_DEFAULT); + autoPreview = ProjectPrefUtil.getPreviewBooleanValue( + previewFile, + IPreferenceConstants.PHP_AUTO_PREVIEW_DEFAULT); // showHTMLFilesLocal = // ProjectPrefUtil.getPreviewBooleanValue(previewFile, @@ -87,9 +95,11 @@ public class BrowserUtil { // showXMLFilesLocal = // ProjectPrefUtil.getPreviewBooleanValue(previewFile, // IPreferenceConstants.PHP_SHOW_XML_FILES_LOCAL); - // isHTMLFileName = "html".equals(extension) || "htm".equals(extension) + // isHTMLFileName = "html".equals(extension) || + // "htm".equals(extension) // || "xhtml".equals(extension); - // isXMLFileName = "xml".equals(extension) || "xsd".equals(extension) || + // isXMLFileName = "xml".equals(extension) || + // "xsd".equals(extension) || // "dtd".equals(extension); } if (autoPreview) { @@ -99,23 +109,27 @@ public class BrowserUtil { // } else if (showXMLFilesLocal && isXMLFileName) { // localhostURL = previewFile.getLocation().toString(); // } else if ((localhostURL = - // ShowExternalPreviewAction.getLocalhostURL(null, previewFile)) == + // ShowExternalPreviewAction.getLocalhostURL(null, previewFile)) + // == // null) { // return; // } // localhostURL += postFix; - ShowInContext context = getShowInContext(previewFile, forceDBGPreview, postFix); + ShowInContext context = getShowInContext(previewFile, + forceDBGPreview, postFix); IWorkbenchPart sourcePart = page.getActivePart(); if (sourcePart == null && context != null) { return; } // try { - Perspective persp = ((WorkbenchPage) page).getActivePerspective(); + Perspective persp = ((WorkbenchPage) page) + .getActivePerspective(); if (persp != null) { // If this view is already visible just return. - IViewReference ref = persp.findView(BrowserView.ID_BROWSER, null); + IViewReference ref = persp.findView(BrowserView.ID_BROWSER, + null); IViewPart view = null; if (ref != null) { view = ref.getView(true); @@ -125,17 +139,20 @@ public class BrowserUtil { if (target != null && target.show(context)) { // success } - ((WorkbenchPage) page).performedShowIn(BrowserView.ID_BROWSER); + ((WorkbenchPage) page) + .performedShowIn(BrowserView.ID_BROWSER); } } // IViewPart view = page.showView(BrowserView.ID_BROWSER); // IShowInTarget target = getShowInTarget(view); - // if (target != null && target.show(new ShowInContext(localhostURL, + // if (target != null && target.show(new + // ShowInContext(localhostURL, // null))) { // // success // } - // ((WorkbenchPage) page).performedShowIn(BrowserView.ID_BROWSER); // + // ((WorkbenchPage) + // page).performedShowIn(BrowserView.ID_BROWSER); // // TODO: move back up // } catch (PartInitException e) { // WorkbenchPlugin.log( diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/editor/EditorMessages.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/editor/EditorMessages.java index 2f7b552..2c826cd 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/editor/EditorMessages.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/editor/EditorMessages.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: EditorMessages.java,v 1.2 2004-09-03 17:30:33 jsurfer Exp $ + * $Id: EditorMessages.java,v 1.3 2006-10-21 23:13:54 pombredanne Exp $ */ package net.sourceforge.phpeclipse.ui.editor; @@ -21,21 +21,23 @@ import java.util.ResourceBundle; */ public class EditorMessages { private static ResourceBundle bundle = ResourceBundle - .getBundle("net.sourceforge.phpeclipse.ui.editor.EditorMessages"); //$NON-NLS-1$ + .getBundle("net.sourceforge.phpeclipse.ui.editor.EditorMessages"); //$NON-NLS-1$ - private EditorMessages() {} + private EditorMessages() { + } - public static String getString( String key ) { + public static String getString(String key) { try { - return bundle.getString( key ); - } catch ( MissingResourceException e ) { + return bundle.getString(key); + } catch (MissingResourceException e) { return "!" + key + "!"; //$NON-NLS-1$ //$NON-NLS-2$ } } - /** - * @return Returns the bundle. - */ - public static ResourceBundle getResourceBundle() { - return bundle; - } + + /** + * @return Returns the bundle. + */ + public static ResourceBundle getResourceBundle() { + return bundle; + } } diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/editor/I18NDocumentProvider.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/editor/I18NDocumentProvider.java index 7aaf2ed..6c4c71a 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/editor/I18NDocumentProvider.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/editor/I18NDocumentProvider.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: I18NDocumentProvider.java,v 1.1 2004-09-02 18:26:30 jsurfer Exp $ + * $Id: I18NDocumentProvider.java,v 1.2 2006-10-21 23:13:54 pombredanne Exp $ */ package net.sourceforge.phpeclipse.ui.editor; @@ -81,10 +81,11 @@ public class I18NDocumentProvider extends FileDocumentProvider { throw new CoreException(s); } finally { - if (in != null) try { - in.close(); - } catch (IOException x) { - } + if (in != null) + try { + in.close(); + } catch (IOException x) { + } } } @@ -240,16 +241,16 @@ public class I18NDocumentProvider extends FileDocumentProvider { } /** - * Tries to determine encoding from contents of the stream. Returns null - * if encoding is unknown. + * Tries to determine encoding from contents of the stream. Returns + * null if encoding is unknown. */ public String getDeclaredEncoding(InputStream in) throws IOException { return getBOMEncoding(in); } /** - * Tries to determine encoding from the byte order mark. Returns null - * if encoding is unknown. + * Tries to determine encoding from the byte order mark. Returns + * null if encoding is unknown. */ private String getBOMEncoding(InputStream in) throws IOException { int first = in.read(); diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/editor/ShowExternalPreviewAction.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/editor/ShowExternalPreviewAction.java index 8ba89aa..abe117e 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/editor/ShowExternalPreviewAction.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/editor/ShowExternalPreviewAction.java @@ -19,105 +19,111 @@ import org.eclipse.ui.texteditor.TextEditorAction; * ClassDeclaration that defines the action for parsing the current PHP file */ public class ShowExternalPreviewAction extends TextEditorAction { - public final static int XML_TYPE = 1; + public final static int XML_TYPE = 1; - public final static int HTML_TYPE = 2; + public final static int HTML_TYPE = 2; - public final static int SMARTY_TYPE = 3; + public final static int SMARTY_TYPE = 3; - public final static int PHP_TYPE = 4; + public final static int PHP_TYPE = 4; - private static ShowExternalPreviewAction instance = new ShowExternalPreviewAction(); + private static ShowExternalPreviewAction instance = new ShowExternalPreviewAction(); - /** - * Constructs and updates the action. - */ - private ShowExternalPreviewAction() { - super(EditorMessages.getResourceBundle(), "ParserAction.", null); //$NON-NLS-1$ - update(); - } + /** + * Constructs and updates the action. + */ + private ShowExternalPreviewAction() { + super(EditorMessages.getResourceBundle(), "ParserAction.", null); //$NON-NLS-1$ + update(); + } - public static ShowExternalPreviewAction getInstance() { - return instance; - } + public static ShowExternalPreviewAction getInstance() { + return instance; + } - /** - * Code called when the action is fired. - */ - public void run() { - doRun(PHP_TYPE); - } + /** + * Code called when the action is fired. + */ + public void run() { + doRun(PHP_TYPE); + } - public void doRun(int type) { - IFile previewFile = getFile(); - BrowserUtil.showPreview(previewFile, false, ""); - } + public void doRun(int type) { + IFile previewFile = getFile(); + BrowserUtil.showPreview(previewFile, false, ""); + } - public void refresh(int type) { - IFile fileToParse = getFile(); - if (fileToParse == null) { - // should never happen - return; - } - boolean autoPreview = ProjectPrefUtil.getPreviewBooleanValue(fileToParse, IPreferenceConstants.PHP_AUTO_PREVIEW_DEFAULT); - boolean bringToTopPreview = ProjectPrefUtil.getPreviewBooleanValue(fileToParse, - IPreferenceConstants.PHP_BRING_TO_TOP_PREVIEW_DEFAULT); + public void refresh(int type) { + IFile fileToParse = getFile(); + if (fileToParse == null) { + // should never happen + return; + } + boolean autoPreview = ProjectPrefUtil.getPreviewBooleanValue( + fileToParse, IPreferenceConstants.PHP_AUTO_PREVIEW_DEFAULT); + boolean bringToTopPreview = ProjectPrefUtil.getPreviewBooleanValue( + fileToParse, + IPreferenceConstants.PHP_BRING_TO_TOP_PREVIEW_DEFAULT); - if (autoPreview) { - IWorkbenchPage page = WebUI.getActivePage(); - try { - IViewPart part = page.findView(BrowserView.ID_BROWSER); - if (part == null) { - part = page.showView(BrowserView.ID_BROWSER); - } else { - if (bringToTopPreview) { - page.bringToTop(part); - } - } - if (part != null) { - ((BrowserView) part).refresh(); - } - } catch (Exception e) { - // PHPeclipsePlugin.log(e); - } - } - } + if (autoPreview) { + IWorkbenchPage page = WebUI.getActivePage(); + try { + IViewPart part = page.findView(BrowserView.ID_BROWSER); + if (part == null) { + part = page.showView(BrowserView.ID_BROWSER); + } else { + if (bringToTopPreview) { + page.bringToTop(part); + } + } + if (part != null) { + ((BrowserView) part).refresh(); + } + } catch (Exception e) { + // PHPeclipsePlugin.log(e); + } + } + } - /** - * Finds the file that's currently opened in the PHP Text Editor - */ - protected IFile getFile() { - ITextEditor editor = getTextEditor(); - IEditorInput editorInput = null; - if (editor != null) { - editorInput = editor.getEditorInput(); - } - if (editorInput instanceof IFileEditorInput) - return ((IFileEditorInput) editorInput).getFile(); - // if nothing was found, which should never happen - return null; - } + /** + * Finds the file that's currently opened in the PHP Text Editor + */ + protected IFile getFile() { + ITextEditor editor = getTextEditor(); + IEditorInput editorInput = null; + if (editor != null) { + editorInput = editor.getEditorInput(); + } + if (editorInput instanceof IFileEditorInput) + return ((IFileEditorInput) editorInput).getFile(); + // if nothing was found, which should never happen + return null; + } - public static String getLocalhostURL(IPreferenceStore store, IFile file) { - if (file != null) { - if (store == null) { - store = WebUI.getDefault().getPreferenceStore(); - } - // IPath path = file.getFullPath(); - String localhostURL = file.getLocation().toString(); - String lowerCaseFileName = localhostURL.toLowerCase(); - // String documentRoot = store.getString(PHPeclipsePlugin.DOCUMENTROOT_PREF); - IPath documentRootPath = ProjectPrefUtil.getDocumentRoot(file.getProject()); - String documentRoot = documentRootPath.toString().toLowerCase(); - if (lowerCaseFileName.startsWith(documentRoot)) { - localhostURL = localhostURL.substring(documentRoot.length()); - } else { - return null; - } - // return store.getString(PHPeclipsePlugin.LOCALHOST_PREF) + localhostURL; - return ProjectPrefUtil.getMiscProjectsPreferenceValue(file.getProject(), IPreferenceConstants.PHP_LOCALHOST_PREF) - + localhostURL; - } - return "http://localhost"; - } + public static String getLocalhostURL(IPreferenceStore store, IFile file) { + if (file != null) { + if (store == null) { + store = WebUI.getDefault().getPreferenceStore(); + } + // IPath path = file.getFullPath(); + String localhostURL = file.getLocation().toString(); + String lowerCaseFileName = localhostURL.toLowerCase(); + // String documentRoot = + // store.getString(PHPeclipsePlugin.DOCUMENTROOT_PREF); + IPath documentRootPath = ProjectPrefUtil.getDocumentRoot(file + .getProject()); + String documentRoot = documentRootPath.toString().toLowerCase(); + if (lowerCaseFileName.startsWith(documentRoot)) { + localhostURL = localhostURL.substring(documentRoot.length()); + } else { + return null; + } + // return store.getString(PHPeclipsePlugin.LOCALHOST_PREF) + + // localhostURL; + return ProjectPrefUtil.getMiscProjectsPreferenceValue(file + .getProject(), IPreferenceConstants.PHP_LOCALHOST_PREF) + + localhostURL; + } + return "http://localhost"; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/editor/StructuredTextEditor.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/editor/StructuredTextEditor.java index c09a5be..5ee45b2 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/editor/StructuredTextEditor.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/editor/StructuredTextEditor.java @@ -8,7 +8,7 @@ * Contributors: * Christopher Lenz - initial API and implementation * - * $Id: StructuredTextEditor.java,v 1.1 2004-09-02 18:26:30 jsurfer Exp $ + * $Id: StructuredTextEditor.java,v 1.2 2006-10-21 23:13:54 pombredanne Exp $ */ package net.sourceforge.phpeclipse.ui.editor; @@ -34,34 +34,34 @@ import org.eclipse.ui.views.contentoutline.IContentOutlinePage; * Abstract base class for editors that keep a source model synchronized with * the textual contants being edited. */ -public abstract class StructuredTextEditor extends TextEditor - implements IReconcilingParticipant { +public abstract class StructuredTextEditor extends TextEditor implements + IReconcilingParticipant { // Inner Classes ----------------------------------------------------------- - /** - * Listens to changes to the selection in the outline page, and changes the - * selection and highlight range in the editor accordingly. - */ - private class OutlineSelectionChangedListener - implements ISelectionChangedListener { - - /* - * @see ISelectionChangedListener#selectionChanged(SelectionChangedEvent) - */ - public void selectionChanged(SelectionChangedEvent event) { - IStructuredSelection selection = - (IStructuredSelection) event.getSelection(); - if (selection.isEmpty()) { - resetHighlightRange(); - } else { - ISourceReference element = (ISourceReference) - selection.getFirstElement(); - highlightElement(element, true); - } - } - - } + /** + * Listens to changes to the selection in the outline page, and changes the + * selection and highlight range in the editor accordingly. + */ + private class OutlineSelectionChangedListener implements + ISelectionChangedListener { + + /* + * @see ISelectionChangedListener#selectionChanged(SelectionChangedEvent) + */ + public void selectionChanged(SelectionChangedEvent event) { + IStructuredSelection selection = (IStructuredSelection) event + .getSelection(); + if (selection.isEmpty()) { + resetHighlightRange(); + } else { + ISourceReference element = (ISourceReference) selection + .getFirstElement(); + highlightElement(element, true); + } + } + + } // Instance Variables ------------------------------------------------------ @@ -85,10 +85,9 @@ public abstract class StructuredTextEditor extends TextEditor if (adapter.equals(IContentOutlinePage.class)) { if (outlinePage == null) { outlinePage = createOutlinePage(); - outlinePageSelectionListener = - new OutlineSelectionChangedListener(); - outlinePage.addSelectionChangedListener( - outlinePageSelectionListener); + outlinePageSelectionListener = new OutlineSelectionChangedListener(); + outlinePage + .addSelectionChangedListener(outlinePageSelectionListener); } return outlinePage; } @@ -106,7 +105,7 @@ public abstract class StructuredTextEditor extends TextEditor // IReconcilingParticipant Implementation ---------------------------------- - /* + /* * @see IReconcilingParticipant#reconciled() */ public void reconciled() { @@ -150,9 +149,10 @@ public abstract class StructuredTextEditor extends TextEditor /** * Returns the source model element at the specified offset. * - * @param offset the offset into the document - * @return the element at the given offset, or null if no model is - * available or there is no element at the offset + * @param offset + * the offset into the document + * @return the element at the given offset, or null if no model + * is available or there is no element at the offset */ public ISourceReference getElementAt(int offset) { ISourceReference retVal = null; @@ -178,33 +178,34 @@ public abstract class StructuredTextEditor extends TextEditor /** * Informs the editor that its outliner has been closed. * - * TODO There must be a more elegant way to get notified when the outline - * page was closed. Otherwise move this method into an interface + * TODO There must be a more elegant way to get notified when the outline + * page was closed. Otherwise move this method into an interface */ public void outlinePageClosed() { if (outlinePage != null) { - outlinePage.removeSelectionChangedListener( - outlinePageSelectionListener); + outlinePage + .removeSelectionChangedListener(outlinePageSelectionListener); outlinePage = null; resetHighlightRange(); } } /** - * Synchronizes the outliner selection with the given element position in + * Synchronizes the outliner selection with the given element position in * the editor. * - * @param element the java element to select + * @param element + * the java element to select */ public void synchronizeOutlinePage(ISourceReference element) { if (outlinePage != null) { - outlinePage.removeSelectionChangedListener( - outlinePageSelectionListener); + outlinePage + .removeSelectionChangedListener(outlinePageSelectionListener); if (outlinePage instanceof ModelBasedOutlinePage) { ((ModelBasedOutlinePage) outlinePage).select(element); } - outlinePage.addSelectionChangedListener( - outlinePageSelectionListener); + outlinePage + .addSelectionChangedListener(outlinePageSelectionListener); } } @@ -224,15 +225,17 @@ public abstract class StructuredTextEditor extends TextEditor /** * Highlights the given element. * - * @param element the element that should be highlighted - * @param moveCursor whether the cursor should be moved to the element + * @param element + * the element that should be highlighted + * @param moveCursor + * whether the cursor should be moved to the element */ protected final void highlightElement(ISourceReference element, boolean moveCursor) { if (element != null) { IRegion highlightRegion = element.getSourceRegion(); - setHighlightRange(highlightRegion.getOffset(), - highlightRegion.getLength(), moveCursor); + setHighlightRange(highlightRegion.getOffset(), highlightRegion + .getLength(), moveCursor); } else { resetHighlightRange(); } @@ -252,23 +255,26 @@ public abstract class StructuredTextEditor extends TextEditor /** * Recursively searches the specified list of elements managed by the given - * model for the element that covers the specified offfset with minimal + * model for the element that covers the specified offfset with minimal * padding. * - * @param model the source model - * @param elements the current list of elements - * @param offset the offset into the document + * @param model + * the source model + * @param elements + * the current list of elements + * @param offset + * the offset into the document * @return the model element at the specified offset, or null if * no element could be found */ - private static ISourceReference getElementAt( - ISourceModel model, ISourceReference elements[], int offset) { + private static ISourceReference getElementAt(ISourceModel model, + ISourceReference elements[], int offset) { ISourceReference retVal = null; for (int i = 0; i < elements.length; i++) { ISourceReference element = elements[i]; IRegion region = element.getSourceRegion(); if ((offset > region.getOffset()) - && (offset < (region.getOffset() + region.getLength()))) { + && (offset < (region.getOffset() + region.getLength()))) { ISourceReference[] children = model.getChildren(element); if (children.length > 0) { retVal = getElementAt(model, children, offset); diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/internal/WebUIMessages.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/internal/WebUIMessages.java index 885d41b..874983b 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/internal/WebUIMessages.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/internal/WebUIMessages.java @@ -8,7 +8,7 @@ * Contributors: * Christopher Lenz - initial API and implementation * - * $Id: WebUIMessages.java,v 1.1 2004-09-02 18:26:29 jsurfer Exp $ + * $Id: WebUIMessages.java,v 1.2 2006-10-21 23:13:54 pombredanne Exp $ */ package net.sourceforge.phpeclipse.ui.internal; @@ -27,16 +27,15 @@ public final class WebUIMessages { /** * Qualified name of the resource bundle containing the localized messages. */ - private static final String RESOURCE_BUNDLE = - "net.sourceforge.phpeclipse.ui.internal.WebUIMessages"; //$NON-NLS-1$ + private static final String RESOURCE_BUNDLE = "net.sourceforge.phpeclipse.ui.internal.WebUIMessages"; //$NON-NLS-1$ // Class Variables --------------------------------------------------------- /** * The resource bundle. */ - private static ResourceBundle resourceBundle = - ResourceBundle.getBundle(RESOURCE_BUNDLE); + private static ResourceBundle resourceBundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); // Constructors ------------------------------------------------------------ @@ -61,7 +60,8 @@ public final class WebUIMessages { /** * Returns the message identified by the specified key. * - * @param key the message key + * @param key + * the message key * @return the localized message, or the key enclosed by exclamation marks * if no message was found for the key */ @@ -77,10 +77,12 @@ public final class WebUIMessages { * Returns the message identified by the specified key, replacing a single * parameter with the provided value. * - * @param key the message key - * @param arg the parameter value - * @return the formatted string, or the key enclosed by exclamation marks - * if no message was found for the key + * @param key + * the message key + * @param arg + * the parameter value + * @return the formatted string, or the key enclosed by exclamation marks if + * no message was found for the key */ public static String getString(String key, String arg) { return getString(key, new String[] { arg }); @@ -90,13 +92,15 @@ public final class WebUIMessages { * Returns the message identified by the specified key, replacing all * parameters with the provided values. * - * @param key the message key - * @param args the parameter values - * @return the formatted string, or the key enclosed by exclamation marks - * if no message was found for the key + * @param key + * the message key + * @param args + * the parameter values + * @return the formatted string, or the key enclosed by exclamation marks if + * no message was found for the key */ public static String getString(String key, String[] args) { - return MessageFormat.format(getString(key), args); + return MessageFormat.format(getString(key), args); } } diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/overlaypages/FieldEditorOverlayPage.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/overlaypages/FieldEditorOverlayPage.java index 7564fe2..fd3fa65 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/overlaypages/FieldEditorOverlayPage.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/overlaypages/FieldEditorOverlayPage.java @@ -9,6 +9,7 @@ * Berthold Daum *******************************************************************************/ package net.sourceforge.phpeclipse.ui.overlaypages; + import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -36,331 +37,366 @@ import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.ui.IWorkbenchPropertyPage; + /** * @author Berthold Daum */ public abstract class FieldEditorOverlayPage extends FieldEditorPreferencePage - implements - IWorkbenchPropertyPage { - /** - * * Name of resource property for the selection of workbench or project - * settings ** - */ - public static final String USEPROJECTSETTINGS = "useProjectSettings"; //$NON-NLS-1$ - private static final String FALSE = "false"; //$NON-NLS-1$ - private static final String TRUE = "true"; //$NON-NLS-1$ - private boolean fUseFileSettings = false; - // Stores all created field editors - private List editors = new ArrayList(); - // Stores owning element of properties - private IAdaptable element; - // Additional buttons for property pages - private Button useWorkspaceSettingsButton, useProjectSettingsButton, - configureButton; - // Overlay preference store for property pages - private IPreferenceStore overlayStore; - // The image descriptor of this pages title image - private ImageDescriptor image; - // Cache for page id - private String pageId; - /** - * Constructor - * - * @param style - - * layout style - */ - public FieldEditorOverlayPage(int style) { - super(style); - } - /** - * Constructor - * - * @param style - - * layout style - */ - public FieldEditorOverlayPage(int style, boolean isFileSettings) { - super(style); - fUseFileSettings = isFileSettings; - } - /** - * Constructor - * - * @param title - - * title string - * @param style - - * layout style - */ - public FieldEditorOverlayPage(String title, int style) { - super(title, style); - } - public FieldEditorOverlayPage(String title, int style, boolean isFileSettings) { - super(title, style); - fUseFileSettings = isFileSettings; - } - /** - * Constructor - * - * @param title - - * title string - * @param image - - * title image - * @param style - - * layout style - */ - public FieldEditorOverlayPage(String title, ImageDescriptor image, int style) { - super(title, image, style); - this.image = image; - } - /** - * Returns the id of the current preference page as defined in plugin.xml - * Subclasses must implement. - * - * @return - the qualifier - */ - protected abstract String getPageId(); - /** - * Receives the object that owns the properties shown in this property page. - * - * @see org.eclipse.ui.IWorkbenchPropertyPage#setElement(org.eclipse.core.runtime.IAdaptable) - */ - public void setElement(IAdaptable element) { - this.element = element; - } - /** - * Delivers the object that owns the properties shown in this property page. - * - * @see org.eclipse.ui.IWorkbenchPropertyPage#getElement() - */ - public IAdaptable getElement() { - return element; - } - /** - * Returns true if this instance represents a property page - * - * @return - true for property pages, false for preference pages - */ - public boolean isPropertyPage() { - return getElement() != null; - } - /** - * We override the addField method. This allows us to store each field editor - * added by subclasses in a list for later processing. - * - * @see org.eclipse.jface.preference.FieldEditorPreferencePage#addField(org.eclipse.jface.preference.FieldEditor) - */ - protected void addField(FieldEditor editor) { - editors.add(editor); - super.addField(editor); - } - /** - * We override the createControl method. In case of property pages we create - * a new PropertyStore as local preference store. After all control have been - * create, we enable/disable these controls. - * - * @see org.eclipse.jface.preference.PreferencePage#createControl() - */ - public void createControl(Composite parent) { - // Special treatment for property pages - if (isPropertyPage()) { - // Cache the page id - pageId = getPageId(); - // Create an overlay preference store and fill it with properties - overlayStore = new PropertyStore((IResource) getElement(), super - .getPreferenceStore(), pageId); - // Set overlay store as current preference store - } - super.createControl(parent); - // Update state of all subclass controls - if (isPropertyPage()) - updateFieldEditors(); - } - /** - * We override the createContents method. In case of property pages we insert - * two radio buttons at the top of the page. - * - * @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite) - */ - protected Control createContents(Composite parent) { - if (isPropertyPage()) - createSelectionGroup(parent); - return super.createContents(parent); - } - /** - * Creates and initializes a selection group with two choice buttons and one - * push button. - * - * @param parent - - * the parent composite - */ - private void createSelectionGroup(Composite parent) { - Composite comp = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(2, false); - layout.marginHeight = 0; - layout.marginWidth = 0; - comp.setLayout(layout); - comp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - Composite radioGroup = new Composite(comp, SWT.NONE); - radioGroup.setLayout(new GridLayout()); - radioGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - useWorkspaceSettingsButton = createRadioButton(radioGroup, Messages - .getString("OverlayPage.Use_Workspace_Settings")); //$NON-NLS-1$ - if (fUseFileSettings) { - useProjectSettingsButton = createRadioButton(radioGroup, Messages - .getString("OverlayPage.Use_File_Settings")); //$NON-NLS-1$ - } else { - useProjectSettingsButton = createRadioButton(radioGroup, Messages - .getString("OverlayPage.Use_Project_Settings")); //$NON-NLS-1$ - } - configureButton = new Button(comp, SWT.PUSH); - configureButton.setText(Messages - .getString("OverlayPage.Configure_Workspace_Settings")); //$NON-NLS-1$ - configureButton.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - configureWorkspaceSettings(); - } - }); - // Set workspace/project radio buttons - try { - String use = ((IResource) getElement()) - .getPersistentProperty(new QualifiedName(pageId, USEPROJECTSETTINGS)); - if (TRUE.equals(use)) { - useProjectSettingsButton.setSelection(true); - configureButton.setEnabled(false); - } else - useWorkspaceSettingsButton.setSelection(true); - } catch (CoreException e) { - useWorkspaceSettingsButton.setSelection(true); - } - } - /** - * Convenience method creating a radio button - * - * @param parent - - * the parent composite - * @param label - - * the button label - * @return - the new button - */ - private Button createRadioButton(Composite parent, String label) { - final Button button = new Button(parent, SWT.RADIO); - button.setText(label); - button.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - configureButton.setEnabled(button == useWorkspaceSettingsButton); - updateFieldEditors(); - } - }); - return button; - } - /** - * Returns in case of property pages the overlay store, in case of preference - * pages the standard preference store - * - * @see org.eclipse.jface.preference.PreferencePage#getPreferenceStore() - */ - public IPreferenceStore getPreferenceStore() { - if (isPropertyPage()) - return overlayStore; - return super.getPreferenceStore(); - } - /* - * Enables or disables the field editors and buttons of this page - */ - private void updateFieldEditors() { - // We iterate through all field editors - boolean enabled = useProjectSettingsButton.getSelection(); - updateFieldEditors(enabled); - } - /** - * Enables or disables the field editors and buttons of this page Subclasses - * may override. - * - * @param enabled - - * true if enabled - */ - protected void updateFieldEditors(boolean enabled) { - Composite parent = getFieldEditorParent(); - Iterator it = editors.iterator(); - while (it.hasNext()) { - FieldEditor editor = (FieldEditor) it.next(); - editor.setEnabled(enabled, parent); - } - } - /** - * We override the performOk method. In case of property pages we copy the - * values in the overlay store into the property values of the selected - * project. We also save the state of the radio buttons. - * - * @see org.eclipse.jface.preference.IPreferencePage#performOk() - */ - public boolean performOk() { - boolean result = super.performOk(); - if (result && isPropertyPage()) { - // Save state of radiobuttons in project properties - IResource resource = (IResource) getElement(); - try { - String value = (useProjectSettingsButton.getSelection()) ? TRUE : FALSE; - resource.setPersistentProperty(new QualifiedName(pageId, - USEPROJECTSETTINGS), value); - } catch (CoreException e) { - } - } - return result; - } - /** - * We override the performDefaults method. In case of property pages we - * switch back to the workspace settings and disable the field editors. - * - * @see org.eclipse.jface.preference.PreferencePage#performDefaults() - */ - protected void performDefaults() { - if (isPropertyPage()) { - useWorkspaceSettingsButton.setSelection(true); - useProjectSettingsButton.setSelection(false); - configureButton.setEnabled(true); - updateFieldEditors(); - } - super.performDefaults(); - } - /** - * Creates a new preferences page and opens it - * - * @see com.bdaum.SpellChecker.preferences.SpellCheckerPreferencePage#configureWorkspaceSettings() - */ - protected void configureWorkspaceSettings() { - try { - // create a new instance of the current class - IPreferencePage page = (IPreferencePage) this.getClass().newInstance(); - page.setTitle(getTitle()); - page.setImageDescriptor(image); - // and show it - showPreferencePage(pageId, page); - } catch (InstantiationException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - } - /** - * Show a single preference pages - * - * @param id - - * the preference page identification - * @param page - - * the preference page - */ - protected void showPreferencePage(String id, IPreferencePage page) { - final IPreferenceNode targetNode = new PreferenceNode(id, page); - PreferenceManager manager = new PreferenceManager(); - manager.addToRoot(targetNode); - final PreferenceDialog dialog = new PreferenceDialog(getControl() - .getShell(), manager); - BusyIndicator.showWhile(getControl().getDisplay(), new Runnable() { - public void run() { - dialog.create(); - dialog.setMessage(targetNode.getLabelText()); - dialog.open(); - } - }); - } + implements IWorkbenchPropertyPage { + /** + * * Name of resource property for the selection of workbench or project + * settings ** + */ + public static final String USEPROJECTSETTINGS = "useProjectSettings"; //$NON-NLS-1$ + + private static final String FALSE = "false"; //$NON-NLS-1$ + + private static final String TRUE = "true"; //$NON-NLS-1$ + + private boolean fUseFileSettings = false; + + // Stores all created field editors + private List editors = new ArrayList(); + + // Stores owning element of properties + private IAdaptable element; + + // Additional buttons for property pages + private Button useWorkspaceSettingsButton, useProjectSettingsButton, + configureButton; + + // Overlay preference store for property pages + private IPreferenceStore overlayStore; + + // The image descriptor of this pages title image + private ImageDescriptor image; + + // Cache for page id + private String pageId; + + /** + * Constructor + * + * @param style - + * layout style + */ + public FieldEditorOverlayPage(int style) { + super(style); + } + + /** + * Constructor + * + * @param style - + * layout style + */ + public FieldEditorOverlayPage(int style, boolean isFileSettings) { + super(style); + fUseFileSettings = isFileSettings; + } + + /** + * Constructor + * + * @param title - + * title string + * @param style - + * layout style + */ + public FieldEditorOverlayPage(String title, int style) { + super(title, style); + } + + public FieldEditorOverlayPage(String title, int style, + boolean isFileSettings) { + super(title, style); + fUseFileSettings = isFileSettings; + } + + /** + * Constructor + * + * @param title - + * title string + * @param image - + * title image + * @param style - + * layout style + */ + public FieldEditorOverlayPage(String title, ImageDescriptor image, int style) { + super(title, image, style); + this.image = image; + } + + /** + * Returns the id of the current preference page as defined in plugin.xml + * Subclasses must implement. + * + * @return - the qualifier + */ + protected abstract String getPageId(); + + /** + * Receives the object that owns the properties shown in this property page. + * + * @see org.eclipse.ui.IWorkbenchPropertyPage#setElement(org.eclipse.core.runtime.IAdaptable) + */ + public void setElement(IAdaptable element) { + this.element = element; + } + + /** + * Delivers the object that owns the properties shown in this property page. + * + * @see org.eclipse.ui.IWorkbenchPropertyPage#getElement() + */ + public IAdaptable getElement() { + return element; + } + + /** + * Returns true if this instance represents a property page + * + * @return - true for property pages, false for preference pages + */ + public boolean isPropertyPage() { + return getElement() != null; + } + + /** + * We override the addField method. This allows us to store each field + * editor added by subclasses in a list for later processing. + * + * @see org.eclipse.jface.preference.FieldEditorPreferencePage#addField(org.eclipse.jface.preference.FieldEditor) + */ + protected void addField(FieldEditor editor) { + editors.add(editor); + super.addField(editor); + } + + /** + * We override the createControl method. In case of property pages we create + * a new PropertyStore as local preference store. After all control have + * been create, we enable/disable these controls. + * + * @see org.eclipse.jface.preference.PreferencePage#createControl() + */ + public void createControl(Composite parent) { + // Special treatment for property pages + if (isPropertyPage()) { + // Cache the page id + pageId = getPageId(); + // Create an overlay preference store and fill it with properties + overlayStore = new PropertyStore((IResource) getElement(), super + .getPreferenceStore(), pageId); + // Set overlay store as current preference store + } + super.createControl(parent); + // Update state of all subclass controls + if (isPropertyPage()) + updateFieldEditors(); + } + + /** + * We override the createContents method. In case of property pages we + * insert two radio buttons at the top of the page. + * + * @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite) + */ + protected Control createContents(Composite parent) { + if (isPropertyPage()) + createSelectionGroup(parent); + return super.createContents(parent); + } + + /** + * Creates and initializes a selection group with two choice buttons and one + * push button. + * + * @param parent - + * the parent composite + */ + private void createSelectionGroup(Composite parent) { + Composite comp = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(2, false); + layout.marginHeight = 0; + layout.marginWidth = 0; + comp.setLayout(layout); + comp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + Composite radioGroup = new Composite(comp, SWT.NONE); + radioGroup.setLayout(new GridLayout()); + radioGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + useWorkspaceSettingsButton = createRadioButton(radioGroup, Messages + .getString("OverlayPage.Use_Workspace_Settings")); //$NON-NLS-1$ + if (fUseFileSettings) { + useProjectSettingsButton = createRadioButton(radioGroup, Messages + .getString("OverlayPage.Use_File_Settings")); //$NON-NLS-1$ + } else { + useProjectSettingsButton = createRadioButton(radioGroup, Messages + .getString("OverlayPage.Use_Project_Settings")); //$NON-NLS-1$ + } + configureButton = new Button(comp, SWT.PUSH); + configureButton.setText(Messages + .getString("OverlayPage.Configure_Workspace_Settings")); //$NON-NLS-1$ + configureButton.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + configureWorkspaceSettings(); + } + }); + // Set workspace/project radio buttons + try { + String use = ((IResource) getElement()) + .getPersistentProperty(new QualifiedName(pageId, + USEPROJECTSETTINGS)); + if (TRUE.equals(use)) { + useProjectSettingsButton.setSelection(true); + configureButton.setEnabled(false); + } else + useWorkspaceSettingsButton.setSelection(true); + } catch (CoreException e) { + useWorkspaceSettingsButton.setSelection(true); + } + } + + /** + * Convenience method creating a radio button + * + * @param parent - + * the parent composite + * @param label - + * the button label + * @return - the new button + */ + private Button createRadioButton(Composite parent, String label) { + final Button button = new Button(parent, SWT.RADIO); + button.setText(label); + button.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + configureButton + .setEnabled(button == useWorkspaceSettingsButton); + updateFieldEditors(); + } + }); + return button; + } + + /** + * Returns in case of property pages the overlay store, in case of + * preference pages the standard preference store + * + * @see org.eclipse.jface.preference.PreferencePage#getPreferenceStore() + */ + public IPreferenceStore getPreferenceStore() { + if (isPropertyPage()) + return overlayStore; + return super.getPreferenceStore(); + } + + /* + * Enables or disables the field editors and buttons of this page + */ + private void updateFieldEditors() { + // We iterate through all field editors + boolean enabled = useProjectSettingsButton.getSelection(); + updateFieldEditors(enabled); + } + + /** + * Enables or disables the field editors and buttons of this page Subclasses + * may override. + * + * @param enabled - + * true if enabled + */ + protected void updateFieldEditors(boolean enabled) { + Composite parent = getFieldEditorParent(); + Iterator it = editors.iterator(); + while (it.hasNext()) { + FieldEditor editor = (FieldEditor) it.next(); + editor.setEnabled(enabled, parent); + } + } + + /** + * We override the performOk method. In case of property pages we copy the + * values in the overlay store into the property values of the selected + * project. We also save the state of the radio buttons. + * + * @see org.eclipse.jface.preference.IPreferencePage#performOk() + */ + public boolean performOk() { + boolean result = super.performOk(); + if (result && isPropertyPage()) { + // Save state of radiobuttons in project properties + IResource resource = (IResource) getElement(); + try { + String value = (useProjectSettingsButton.getSelection()) ? TRUE + : FALSE; + resource.setPersistentProperty(new QualifiedName(pageId, + USEPROJECTSETTINGS), value); + } catch (CoreException e) { + } + } + return result; + } + + /** + * We override the performDefaults method. In case of property pages we + * switch back to the workspace settings and disable the field editors. + * + * @see org.eclipse.jface.preference.PreferencePage#performDefaults() + */ + protected void performDefaults() { + if (isPropertyPage()) { + useWorkspaceSettingsButton.setSelection(true); + useProjectSettingsButton.setSelection(false); + configureButton.setEnabled(true); + updateFieldEditors(); + } + super.performDefaults(); + } + + /** + * Creates a new preferences page and opens it + * + * @see com.bdaum.SpellChecker.preferences.SpellCheckerPreferencePage#configureWorkspaceSettings() + */ + protected void configureWorkspaceSettings() { + try { + // create a new instance of the current class + IPreferencePage page = (IPreferencePage) this.getClass() + .newInstance(); + page.setTitle(getTitle()); + page.setImageDescriptor(image); + // and show it + showPreferencePage(pageId, page); + } catch (InstantiationException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + } + + /** + * Show a single preference pages + * + * @param id - + * the preference page identification + * @param page - + * the preference page + */ + protected void showPreferencePage(String id, IPreferencePage page) { + final IPreferenceNode targetNode = new PreferenceNode(id, page); + PreferenceManager manager = new PreferenceManager(); + manager.addToRoot(targetNode); + final PreferenceDialog dialog = new PreferenceDialog(getControl() + .getShell(), manager); + BusyIndicator.showWhile(getControl().getDisplay(), new Runnable() { + public void run() { + dialog.create(); + dialog.setMessage(targetNode.getLabelText()); + dialog.open(); + } + }); + } } diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/overlaypages/Messages.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/overlaypages/Messages.java index efc0f8e..417990b 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/overlaypages/Messages.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/overlaypages/Messages.java @@ -13,29 +13,29 @@ package net.sourceforge.phpeclipse.ui.overlaypages; import java.util.ResourceBundle; - public class Messages { - private final static String RESOURCE_BUNDLE= "net.sourceforge.phpeclipse.ui.overlaypages.Messages";//$NON-NLS-1$ - + private final static String RESOURCE_BUNDLE = "net.sourceforge.phpeclipse.ui.overlaypages.Messages";//$NON-NLS-1$ + private static ResourceBundle fgResourceBundle = null; - + private static boolean notRead = true; public Messages() { } + public static ResourceBundle getResourceBundle() { if (notRead) { notRead = false; try { fgResourceBundle = ResourceBundle.getBundle(RESOURCE_BUNDLE); - } - catch (Exception e) { + } catch (Exception e) { } } - + return fgResourceBundle; } + public static String getString(String key) { try { return getResourceBundle().getString(key); @@ -44,4 +44,3 @@ public class Messages { } } } - diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/overlaypages/OverlayPage.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/overlaypages/OverlayPage.java index a501786..50ecf07 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/overlaypages/OverlayPage.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/overlaypages/OverlayPage.java @@ -39,16 +39,19 @@ import org.eclipse.ui.part.PageBook; */ public abstract class OverlayPage extends PropertyPage { - /*** Name of resource property for the selection of workbench or project settings ***/ + /** + * * Name of resource property for the selection of workbench or project + * settings ** + */ public static final String USEPROJECTSETTINGS = "useProjectSettings"; //$NON-NLS-1$ - + private static final String FALSE = "false"; //$NON-NLS-1$ + private static final String TRUE = "true"; //$NON-NLS-1$ // Additional buttons for property pages - private Button useWorkspaceSettingsButton, - useProjectSettingsButton, - configureButton; + private Button useWorkspaceSettingsButton, useProjectSettingsButton, + configureButton; // Overlay preference store for property pages private PropertyStore overlayStore; @@ -71,7 +74,9 @@ public abstract class OverlayPage extends PropertyPage { /** * Constructor - * @param title - title string + * + * @param title - + * title string */ public OverlayPage(String title) { super(); @@ -80,8 +85,11 @@ public abstract class OverlayPage extends PropertyPage { /** * Constructor - * @param title - title string - * @param image - title image + * + * @param title - + * title string + * @param image - + * title image */ public OverlayPage(String title, ImageDescriptor image) { super(); @@ -92,7 +100,7 @@ public abstract class OverlayPage extends PropertyPage { /** * Returns the id of the current preference page as defined in plugin.xml - * Subclasses must implement. + * Subclasses must implement. * * @return - the qualifier */ @@ -100,6 +108,7 @@ public abstract class OverlayPage extends PropertyPage { /** * Returns true if this instance represents a property page + * * @return - true for property pages, false for preference pages */ public boolean isPropertyPage() { @@ -107,9 +116,10 @@ public abstract class OverlayPage extends PropertyPage { } /** - * We need to implement createContents method. In case of property pages we insert two radio buttons - * and a push button at the top of the page. Below this group we create a new composite for the contents - * created by subclasses. + * We need to implement createContents method. In case of property pages we + * insert two radio buttons and a push button at the top of the page. Below + * this group we create a new composite for the contents created by + * subclasses. * * @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite) */ @@ -126,8 +136,11 @@ public abstract class OverlayPage extends PropertyPage { } /** - * Creates and initializes a selection group with two choice buttons and one push button. - * @param parent - the parent composite + * Creates and initializes a selection group with two choice buttons and one + * push button. + * + * @param parent - + * the parent composite */ private void createSelectionGroup(Composite parent) { Composite comp = new Composite(parent, SWT.NONE); @@ -139,10 +152,13 @@ public abstract class OverlayPage extends PropertyPage { Composite radioGroup = new Composite(comp, SWT.NONE); radioGroup.setLayout(new GridLayout()); radioGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - useWorkspaceSettingsButton = createRadioButton(radioGroup, Messages.getString("OverlayPage.Use_Workspace_Settings")); //$NON-NLS-1$ - useProjectSettingsButton = createRadioButton(radioGroup, Messages.getString("OverlayPage.Use_Project_Settings")); //$NON-NLS-1$ + useWorkspaceSettingsButton = createRadioButton(radioGroup, Messages + .getString("OverlayPage.Use_Workspace_Settings")); //$NON-NLS-1$ + useProjectSettingsButton = createRadioButton(radioGroup, Messages + .getString("OverlayPage.Use_Project_Settings")); //$NON-NLS-1$ configureButton = new Button(comp, SWT.PUSH); - configureButton.setText(Messages.getString("OverlayPage.Configure_Workspace_Settings")); //$NON-NLS-1$ + configureButton.setText(Messages + .getString("OverlayPage.Configure_Workspace_Settings")); //$NON-NLS-1$ configureButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { configureWorkspaceSettings(); @@ -150,9 +166,9 @@ public abstract class OverlayPage extends PropertyPage { }); // Set workspace/project radio buttons try { - String use = - ((IResource) getElement()).getPersistentProperty( - new QualifiedName(pageId, USEPROJECTSETTINGS)); + String use = ((IResource) getElement()) + .getPersistentProperty(new QualifiedName(pageId, + USEPROJECTSETTINGS)); if (TRUE.equals(use)) { useProjectSettingsButton.setSelection(true); configureButton.setEnabled(false); @@ -165,8 +181,11 @@ public abstract class OverlayPage extends PropertyPage { /** * Convenience method creating a radio button - * @param parent - the parent composite - * @param label - the button label + * + * @param parent - + * the parent composite + * @param label - + * the button label * @return - the new button */ private Button createRadioButton(Composite parent, String label) { @@ -174,8 +193,8 @@ public abstract class OverlayPage extends PropertyPage { button.setText(label); button.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { - configureButton.setEnabled( - button == useWorkspaceSettingsButton); + configureButton + .setEnabled(button == useWorkspaceSettingsButton); setControlsEnabled(); } }); @@ -183,8 +202,9 @@ public abstract class OverlayPage extends PropertyPage { } /** - * In case of property pages we create a new PropertyStore as local overlay store. - * After all controls have been create, we enable/disable these controls + * In case of property pages we create a new PropertyStore as local overlay + * store. After all controls have been create, we enable/disable these + * controls * * @see org.eclipse.jface.preference.PreferencePage#createControl() */ @@ -194,11 +214,8 @@ public abstract class OverlayPage extends PropertyPage { // Cache the page id pageId = getPageId(); // Create an overlay preference store and fill it with properties - overlayStore = - new PropertyStore( - (IResource) getElement(), - super.getPreferenceStore(), - pageId); + overlayStore = new PropertyStore((IResource) getElement(), super + .getPreferenceStore(), pageId); // Set overlay store as current preference store } super.createControl(parent); @@ -207,8 +224,10 @@ public abstract class OverlayPage extends PropertyPage { setControlsEnabled(); } - /* - * Returns in case of property pages the overlay store - otherwise the standard preference store + /* + * Returns in case of property pages the overlay store - otherwise the + * standard preference store + * * @see org.eclipse.jface.preference.PreferencePage#getPreferenceStore() */ public IPreferenceStore getPreferenceStore() { @@ -226,36 +245,39 @@ public abstract class OverlayPage extends PropertyPage { } /** - * Enables or disables the controls of this page - * Subclasses may override. + * Enables or disables the controls of this page Subclasses may override. * - * @param enabled - true if controls shall be enabled + * @param enabled - + * true if controls shall be enabled */ protected void setControlsEnabled(boolean enabled) { setControlsEnabled(contents, enabled); } /** - * Enables or disables a tree of controls starting at the specified root. - * We spare tabbed notebooks and pagebooks to allow for user navigation. + * Enables or disables a tree of controls starting at the specified root. We + * spare tabbed notebooks and pagebooks to allow for user navigation. * - * @param root - the root composite - * @param enabled - true if controls shall be enabled + * @param root - + * the root composite + * @param enabled - + * true if controls shall be enabled */ private void setControlsEnabled(Composite root, boolean enabled) { Control[] children = root.getChildren(); for (int i = 0; i < children.length; i++) { Control child = children[i]; - if (!(child instanceof CTabFolder) && !(child instanceof TabFolder) && !(child instanceof PageBook)) + if (!(child instanceof CTabFolder) && !(child instanceof TabFolder) + && !(child instanceof PageBook)) child.setEnabled(enabled); if (child instanceof Composite) setControlsEnabled((Composite) child, enabled); } } - /** - * We override the performOk method. In case of property pages - * we save the state of the radio buttons. + /** + * We override the performOk method. In case of property pages we save the + * state of the radio buttons. * * @see org.eclipse.jface.preference.IPreferencePage#performOk() */ @@ -265,11 +287,10 @@ public abstract class OverlayPage extends PropertyPage { // Save state of radiobuttons in project properties IResource resource = (IResource) getElement(); try { - String value = - (useProjectSettingsButton.getSelection()) ? TRUE : FALSE; - resource.setPersistentProperty( - new QualifiedName(pageId, USEPROJECTSETTINGS), - value); + String value = (useProjectSettingsButton.getSelection()) ? TRUE + : FALSE; + resource.setPersistentProperty(new QualifiedName(pageId, + USEPROJECTSETTINGS), value); } catch (CoreException e) { } } @@ -294,13 +315,14 @@ public abstract class OverlayPage extends PropertyPage { /** * Creates a new preferences page and opens it + * * @see com.bdaum.SpellChecker.preferences.SpellCheckerPreferencePage#configureWorkspaceSettings() */ protected void configureWorkspaceSettings() { try { // create a new instance of the current class - IPreferencePage page = - (IPreferencePage) this.getClass().newInstance(); + IPreferencePage page = (IPreferencePage) this.getClass() + .newInstance(); page.setTitle(getTitle()); page.setImageDescriptor(image); // and show it @@ -314,15 +336,18 @@ public abstract class OverlayPage extends PropertyPage { /** * Show a single preference pages - * @param id - the preference page identification - * @param page - the preference page + * + * @param id - + * the preference page identification + * @param page - + * the preference page */ protected void showPreferencePage(String id, IPreferencePage page) { final IPreferenceNode targetNode = new PreferenceNode(id, page); PreferenceManager manager = new PreferenceManager(); manager.addToRoot(targetNode); - final PreferenceDialog dialog = - new PreferenceDialog(getControl().getShell(), manager); + final PreferenceDialog dialog = new PreferenceDialog(getControl() + .getShell(), manager); BusyIndicator.showWhile(getControl().getDisplay(), new Runnable() { public void run() { dialog.create(); diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/overlaypages/ProjectPrefUtil.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/overlaypages/ProjectPrefUtil.java index e292e31..7737f47 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/overlaypages/ProjectPrefUtil.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/overlaypages/ProjectPrefUtil.java @@ -18,68 +18,80 @@ import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.QualifiedName; public class ProjectPrefUtil { - public static String getMiscProjectsPreferenceValue(IResource resource, String key) { - return getOverlayedPrefProjectValue(resource, PHPMiscProjectPreferences.PREF_ID, key); - } + public static String getMiscProjectsPreferenceValue(IResource resource, + String key) { + return getOverlayedPrefProjectValue(resource, + PHPMiscProjectPreferences.PREF_ID, key); + } - public static List getIncludePaths(IResource resource) { - String includePaths = getMiscProjectsPreferenceValue(resource, IPreferenceConstants.PHP_INCLUDE_PATHS); - ArrayList list = new ArrayList(); - if (includePaths != null) { - StringTokenizer st = new StringTokenizer(includePaths, File.pathSeparator + "\n\r");//$NON-NLS-1$ - while (st.hasMoreElements()) { - list.add(st.nextElement()); - } - } - return list; - } + public static List getIncludePaths(IResource resource) { + String includePaths = getMiscProjectsPreferenceValue(resource, + IPreferenceConstants.PHP_INCLUDE_PATHS); + ArrayList list = new ArrayList(); + if (includePaths != null) { + StringTokenizer st = new StringTokenizer(includePaths, + File.pathSeparator + "\n\r");//$NON-NLS-1$ + while (st.hasMoreElements()) { + list.add(st.nextElement()); + } + } + return list; + } - public static IPath getDocumentRoot(IResource resource) { - String documentRoot = getMiscProjectsPreferenceValue(resource, IPreferenceConstants.PHP_DOCUMENTROOT_PREF); - IPath path = new Path(documentRoot); - // documentRoot = documentRoot.replace('\\', '/'); - return path; - } + public static IPath getDocumentRoot(IResource resource) { + String documentRoot = getMiscProjectsPreferenceValue(resource, + IPreferenceConstants.PHP_DOCUMENTROOT_PREF); + IPath path = new Path(documentRoot); + // documentRoot = documentRoot.replace('\\', '/'); + return path; + } - public static String getOverlayedPrefProjectValue(IResource resource, String pageId, String key) { - IProject project = resource.getProject(); - String value = null; - if (useProjectSettings(project, pageId)) { - value = getProperty(resource, pageId, key); - } - if (value != null) - return value; - return WebUI.getDefault().getPreferenceStore().getString(key); - } + public static String getOverlayedPrefProjectValue(IResource resource, + String pageId, String key) { + IProject project = resource.getProject(); + String value = null; + if (useProjectSettings(project, pageId)) { + value = getProperty(resource, pageId, key); + } + if (value != null) + return value; + return WebUI.getDefault().getPreferenceStore().getString(key); + } - public static String getOverlayedPrefResourceValue(IResource resource, String pageId, String key) { - String value = null; - if (useProjectSettings(resource, pageId)) { - value = getProperty(resource, pageId, key); - } - if (value != null) - return value; - return WebUI.getDefault().getPreferenceStore().getString(key); - } + public static String getOverlayedPrefResourceValue(IResource resource, + String pageId, String key) { + String value = null; + if (useProjectSettings(resource, pageId)) { + value = getProperty(resource, pageId, key); + } + if (value != null) + return value; + return WebUI.getDefault().getPreferenceStore().getString(key); + } - public static boolean getPreviewBooleanValue(IResource resource, String key) { - return getOverlayedPrefResourceValue(resource, PHPPreviewProjectPreferences.PREF_ID, key).equals("true"); - } + public static boolean getPreviewBooleanValue(IResource resource, String key) { + return getOverlayedPrefResourceValue(resource, + PHPPreviewProjectPreferences.PREF_ID, key).equals("true"); + } - public static String getPreviewStringValue(IResource resource, String key) { - return getOverlayedPrefResourceValue(resource, PHPPreviewProjectPreferences.PREF_ID, key); - } + public static String getPreviewStringValue(IResource resource, String key) { + return getOverlayedPrefResourceValue(resource, + PHPPreviewProjectPreferences.PREF_ID, key); + } - private static String getProperty(IResource resource, String pageId, String key) { - try { - return resource.getPersistentProperty(new QualifiedName(pageId, key)); - } catch (CoreException e) { - } - return null; - } + private static String getProperty(IResource resource, String pageId, + String key) { + try { + return resource + .getPersistentProperty(new QualifiedName(pageId, key)); + } catch (CoreException e) { + } + return null; + } - private static boolean useProjectSettings(IResource resource, String pageId) { - String use = getProperty(resource, pageId, FieldEditorOverlayPage.USEPROJECTSETTINGS); - return "true".equals(use); - } + private static boolean useProjectSettings(IResource resource, String pageId) { + String use = getProperty(resource, pageId, + FieldEditorOverlayPage.USEPROJECTSETTINGS); + return "true".equals(use); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/overlaypages/PropertyStore.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/overlaypages/PropertyStore.java index 8d968e8..60fdcc9 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/overlaypages/PropertyStore.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/overlaypages/PropertyStore.java @@ -22,35 +22,41 @@ import org.eclipse.jface.preference.PreferenceStore; /** * @author Berthold Daum - * + * */ public class PropertyStore extends PreferenceStore { private IResource resource; + private IPreferenceStore workbenchStore; + private String pageId; + private boolean inserting = false; - public PropertyStore( - IResource resource, - IPreferenceStore workbenchStore, - String pageId) { + public PropertyStore(IResource resource, IPreferenceStore workbenchStore, + String pageId) { this.resource = resource; this.workbenchStore = workbenchStore; this.pageId = pageId; } - /*** Write modified values back to properties ***/ + /** * Write modified values back to properties ** */ - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.preference.IPersistentPreferenceStore#save() */ public void save() throws IOException { writeProperties(); } - /* (non-Javadoc) - * @see org.eclipse.jface.preference.PreferenceStore#save(java.io.OutputStream, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.preference.PreferenceStore#save(java.io.OutputStream, + * java.lang.String) */ public void save(OutputStream out, String header) throws IOException { writeProperties(); @@ -66,68 +72,87 @@ public class PropertyStore extends PreferenceStore { try { setProperty(name, getString(name)); } catch (CoreException e) { - throw new IOException(Messages.getString("PropertyStore.Cannot_write_resource_property") + name); //$NON-NLS-1$ + throw new IOException( + Messages + .getString("PropertyStore.Cannot_write_resource_property") + name); //$NON-NLS-1$ } } } /** * Convenience method to set a property - * @param name - the preference name - * @param value - the property value or null to delete the property + * + * @param name - + * the preference name + * @param value - + * the property value or null to delete the property * @throws CoreException */ private void setProperty(String name, String value) throws CoreException { resource.setPersistentProperty(new QualifiedName(pageId, name), value); } - /*** Get default values (Delegate to workbench store) ***/ + /** * Get default values (Delegate to workbench store) ** */ - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.preference.IPreferenceStore#getDefaultBoolean(java.lang.String) */ public boolean getDefaultBoolean(String name) { return workbenchStore.getDefaultBoolean(name); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.preference.IPreferenceStore#getDefaultDouble(java.lang.String) */ public double getDefaultDouble(String name) { return workbenchStore.getDefaultDouble(name); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.preference.IPreferenceStore#getDefaultFloat(java.lang.String) */ public float getDefaultFloat(String name) { return workbenchStore.getDefaultFloat(name); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.preference.IPreferenceStore#getDefaultInt(java.lang.String) */ public int getDefaultInt(String name) { return workbenchStore.getDefaultInt(name); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.preference.IPreferenceStore#getDefaultLong(java.lang.String) */ public long getDefaultLong(String name) { return workbenchStore.getDefaultLong(name); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.preference.IPreferenceStore#getDefaultString(java.lang.String) */ public String getDefaultString(String name) { return workbenchStore.getDefaultString(name); } - /*** Get property values ***/ + /** * Get property values ** */ - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.preference.IPreferenceStore#getBoolean(java.lang.String) */ public boolean getBoolean(String name) { @@ -135,7 +160,9 @@ public class PropertyStore extends PreferenceStore { return super.getBoolean(name); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.preference.IPreferenceStore#getDouble(java.lang.String) */ public double getDouble(String name) { @@ -143,7 +170,9 @@ public class PropertyStore extends PreferenceStore { return super.getDouble(name); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.preference.IPreferenceStore#getFloat(java.lang.String) */ public float getFloat(String name) { @@ -151,7 +180,9 @@ public class PropertyStore extends PreferenceStore { return super.getFloat(name); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.preference.IPreferenceStore#getInt(java.lang.String) */ public int getInt(String name) { @@ -159,7 +190,9 @@ public class PropertyStore extends PreferenceStore { return super.getInt(name); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.preference.IPreferenceStore#getLong(java.lang.String) */ public long getLong(String name) { @@ -167,7 +200,9 @@ public class PropertyStore extends PreferenceStore { return super.getLong(name); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.preference.IPreferenceStore#getString(java.lang.String) */ public String getString(String name) { @@ -198,7 +233,9 @@ public class PropertyStore extends PreferenceStore { /** * Convenience method to fetch a property - * @param name - the preference name + * + * @param name - + * the preference name * @return - the property value * @throws CoreException */ @@ -206,28 +243,35 @@ public class PropertyStore extends PreferenceStore { return resource.getPersistentProperty(new QualifiedName(pageId, name)); } - /*** Misc ***/ + /** * Misc ** */ - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.preference.IPreferenceStore#contains(java.lang.String) */ public boolean contains(String name) { return workbenchStore.contains(name); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.preference.IPreferenceStore#setToDefault(java.lang.String) */ public void setToDefault(String name) { - setValue(name, getDefaultString(name)); + setValue(name, getDefaultString(name)); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.preference.IPreferenceStore#isDefault(java.lang.String) */ public boolean isDefault(String name) { String defaultValue = getDefaultString(name); - if (defaultValue == null) return false; + if (defaultValue == null) + return false; return defaultValue.equals(getString(name)); } diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/IMiscProjectPreferences.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/IMiscProjectPreferences.java index ef42982..5a0959a 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/IMiscProjectPreferences.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/IMiscProjectPreferences.java @@ -1,32 +1,30 @@ package net.sourceforge.phpeclipse.ui.preferences; - /** * constnats for project preferences */ public interface IMiscProjectPreferences { - /** - * namespace URI for the properties - */ -// public static final String PROPERTY_NAMESPACE = "http://phpeclipse.org"; - - // public static final String PREF_ID = "net.sourceforge.phpeclipse.preferences.PHPMiscProjectPreferences"; -// /** -// * property local name for the publish directory -// */ -// public static final String PUBLISH_PROPERTY = "publish"; -// -// /** -// * property qualified name for the publish directory -// */ -// public static final QualifiedName PUBLISH_PROPERTY_NAME = -// new QualifiedName(PROPERTY_NAMESPACE,PUBLISH_PROPERTY); -// -// /** -// * default value for the publish directory name -// */ -// public static final String DEFAULT_PUBLISH_DIR = "c:\\temp"; - + /** + * namespace URI for the properties + */ + // public static final String PROPERTY_NAMESPACE = "http://phpeclipse.org"; + // public static final String PREF_ID = + // "net.sourceforge.phpeclipse.preferences.PHPMiscProjectPreferences"; + // /** + // * property local name for the publish directory + // */ + // public static final String PUBLISH_PROPERTY = "publish"; + // + // /** + // * property qualified name for the publish directory + // */ + // public static final QualifiedName PUBLISH_PROPERTY_NAME = + // new QualifiedName(PROPERTY_NAMESPACE,PUBLISH_PROPERTY); + // + // /** + // * default value for the publish directory name + // */ + // public static final String DEFAULT_PUBLISH_DIR = "c:\\temp"; } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/ITextStylePreferences.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/ITextStylePreferences.java index 6235a01..71ac80b 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/ITextStylePreferences.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/ITextStylePreferences.java @@ -8,12 +8,11 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: ITextStylePreferences.java,v 1.1 2004-09-02 18:26:30 jsurfer Exp $ + * $Id: ITextStylePreferences.java,v 1.2 2006-10-21 23:13:54 pombredanne Exp $ */ package net.sourceforge.phpeclipse.ui.preferences; - /** * * @@ -21,9 +20,12 @@ package net.sourceforge.phpeclipse.ui.preferences; */ public interface ITextStylePreferences { public static final String SUFFIX_FOREGROUND = "_foreground"; //$NON-NLS-1$ + public static final String SUFFIX_BACKGROUND = "_background"; //$NON-NLS-1$ - public static final String SUFFIX_STYLE = "_style"; //$NON-NLS-1$ + + public static final String SUFFIX_STYLE = "_style"; //$NON-NLS-1$ public static final String STYLE_NORMAL = "normal"; //$NON-NLS-1$ - public static final String STYLE_BOLD = "bold"; //$NON-NLS-1$ + + public static final String STYLE_BOLD = "bold"; //$NON-NLS-1$ } diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/OverlayPreferenceStore.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/OverlayPreferenceStore.java index 61951fa..e1f123c 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/OverlayPreferenceStore.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/OverlayPreferenceStore.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: OverlayPreferenceStore.java,v 1.1 2004-09-02 18:26:30 jsurfer Exp $ + * $Id: OverlayPreferenceStore.java,v 1.2 2006-10-21 23:13:54 pombredanne Exp $ */ package net.sourceforge.phpeclipse.ui.preferences; @@ -18,7 +18,6 @@ import org.eclipse.jface.preference.PreferenceStore; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; - /** * An overlaying preference store. */ @@ -33,15 +32,15 @@ public class OverlayPreferenceStore implements IPreferenceStore { } IPreferenceStore parent; + IPreferenceStore store; private PreferenceDescriptor[] keys; private PropertyListener fPropertyListener; - public OverlayPreferenceStore( - IPreferenceStore parent, PreferenceDescriptor[] overlayKeys - ) { + public OverlayPreferenceStore(IPreferenceStore parent, + PreferenceDescriptor[] overlayKeys) { this.parent = parent; this.keys = overlayKeys; @@ -62,10 +61,8 @@ public class OverlayPreferenceStore implements IPreferenceStore { return (findOverlayKey(key) != null); } - void propagateProperty( - IPreferenceStore orgin, PreferenceDescriptor key, - IPreferenceStore target - ) { + void propagateProperty(IPreferenceStore orgin, PreferenceDescriptor key, + IPreferenceStore target) { if (orgin.isDefault(key.key)) { if (!target.isDefault(key.key)) { target.setToDefault(key.key); @@ -121,10 +118,8 @@ public class OverlayPreferenceStore implements IPreferenceStore { } } - private void loadProperty( - IPreferenceStore orgin, PreferenceDescriptor key, - IPreferenceStore target, boolean forceInitialization - ) { + private void loadProperty(IPreferenceStore orgin, PreferenceDescriptor key, + IPreferenceStore target, boolean forceInitialization) { PreferenceDescriptor.Type d = key.type; if (PreferenceDescriptor.BOOLEAN == d) { if (forceInitialization) { @@ -208,9 +203,8 @@ public class OverlayPreferenceStore implements IPreferenceStore { /* * @see IPreferenceStore#firePropertyChangeEvent(String, Object, Object) */ - public void firePropertyChangeEvent( - String name, Object oldValue, Object newValue - ) { + public void firePropertyChangeEvent(String name, Object oldValue, + Object newValue) { store.firePropertyChangeEvent(name, oldValue, newValue); } diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/PHPMiscProjectPreferences.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/PHPMiscProjectPreferences.java index 40d9136..cd74b70 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/PHPMiscProjectPreferences.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/PHPMiscProjectPreferences.java @@ -1,4 +1,5 @@ package net.sourceforge.phpeclipse.ui.preferences; + import net.sourceforge.phpeclipse.ui.IPreferenceConstants; import net.sourceforge.phpeclipse.ui.WebUI; import net.sourceforge.phpeclipse.ui.overlaypages.FieldEditorOverlayPage; @@ -9,64 +10,73 @@ import org.eclipse.jface.preference.StringFieldEditor; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; + /** - * + * * This page will be added to the project's property page dialog when the * "Properties..." popup menu item is selected */ -public class PHPMiscProjectPreferences extends FieldEditorOverlayPage - implements - IWorkbenchPreferencePage, - IMiscProjectPreferences { +public class PHPMiscProjectPreferences extends FieldEditorOverlayPage implements + IWorkbenchPreferencePage, IMiscProjectPreferences { + + public final static String PREF_ID = "net.sourceforge.phpeclipse.preferences.PHPMiscProjectPreferences"; + + public PHPMiscProjectPreferences() { + super(GRID); + } - public final static String PREF_ID = "net.sourceforge.phpeclipse.preferences.PHPMiscProjectPreferences"; - public PHPMiscProjectPreferences() { - super(GRID); - } - /* - * (non-Javadoc) - * - * @see com.bdaum.overlayPages.FieldEditorOverlayPage#getPageId() - */ - protected String getPageId() { - return PREF_ID; - } + /* + * (non-Javadoc) + * + * @see com.bdaum.overlayPages.FieldEditorOverlayPage#getPageId() + */ + protected String getPageId() { + return PREF_ID; + } - protected void createFieldEditors() { - Composite composite = getFieldEditorParent(); + protected void createFieldEditors() { + Composite composite = getFieldEditorParent(); - addField(new StringFieldEditor(IPreferenceConstants.PHP_LOCALHOST_PREF, - PHPPreferencesMessages.getString("PHPMiscProjectPreferences.localhost"), - composite)); -// addField(new StringFieldEditor(IPreferenceConstants.PHP_BOOKMARK_DEFAULT, -// PHPPreferencesMessages.getString("PHPMiscProjectPreferences.bookmark"), -// composite)); - addField(new StringFieldEditor(IPreferenceConstants.PHP_DOCUMENTROOT_PREF, - PHPPreferencesMessages.getString("PHPMiscProjectPreferences.documentroot"), - composite)); + addField(new StringFieldEditor(IPreferenceConstants.PHP_LOCALHOST_PREF, + PHPPreferencesMessages + .getString("PHPMiscProjectPreferences.localhost"), + composite)); + // addField(new + // StringFieldEditor(IPreferenceConstants.PHP_BOOKMARK_DEFAULT, + // PHPPreferencesMessages.getString("PHPMiscProjectPreferences.bookmark"), + // composite)); + addField(new StringFieldEditor( + IPreferenceConstants.PHP_DOCUMENTROOT_PREF, + PHPPreferencesMessages + .getString("PHPMiscProjectPreferences.documentroot"), + composite)); - PathEditor pe = new PathEditor(IPreferenceConstants.PHP_INCLUDE_PATHS, - PHPPreferencesMessages.getString("PHPMiscProjectPreferences.include_paths"), - "Choose Path...", - composite); - addField(pe); + PathEditor pe = new PathEditor(IPreferenceConstants.PHP_INCLUDE_PATHS, + PHPPreferencesMessages + .getString("PHPMiscProjectPreferences.include_paths"), + "Choose Path...", composite); + addField(pe); + // if (!isPropertyPage)) { + // + // } + } + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.preference.PreferencePage#doGetPreferenceStore() + */ + protected IPreferenceStore doGetPreferenceStore() { + return WebUI.getDefault().getPreferenceStore(); + } - //if (!isPropertyPage)) { - // - //} - } - /* (non-Javadoc) - * @see org.eclipse.jface.preference.PreferencePage#doGetPreferenceStore() - */ - protected IPreferenceStore doGetPreferenceStore() { - return WebUI.getDefault().getPreferenceStore(); - } - /* (non-Javadoc) - * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) - */ - public void init(IWorkbench workbench) { - setDescription("Default entries for PHP projects."); - } + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) + */ + public void init(IWorkbench workbench) { + setDescription("Default entries for PHP projects."); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/PHPPreferencesMessages.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/PHPPreferencesMessages.java index f1a4928..7426439 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/PHPPreferencesMessages.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/PHPPreferencesMessages.java @@ -6,8 +6,11 @@ import java.util.ResourceBundle; public class PHPPreferencesMessages { - private static final String RESOURCE_BUNDLE= PHPPreferencesMessages.class.getName(); - private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); + private static final String RESOURCE_BUNDLE = PHPPreferencesMessages.class + .getName(); + + private static ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); private PHPPreferencesMessages() { } @@ -19,20 +22,20 @@ public class PHPPreferencesMessages { return '!' + key + '!'; } } - + /** * Gets a string from the resource bundle and formats it with the argument * - * @param key the string used to get the bundle value, must not be null + * @param key + * the string used to get the bundle value, must not be null */ public static String getFormattedString(String key, Object arg) { return MessageFormat.format(getString(key), new Object[] { arg }); } - /** * Gets a string from the resource bundle and formats it with arguments - */ + */ public static String getFormattedString(String key, Object[] args) { return MessageFormat.format(getString(key), args); } diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/PHPPreviewProjectPreferences.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/PHPPreviewProjectPreferences.java index 8ff6e31..4c521b3 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/PHPPreviewProjectPreferences.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/PHPPreviewProjectPreferences.java @@ -1,4 +1,5 @@ package net.sourceforge.phpeclipse.ui.preferences; + import net.sourceforge.phpeclipse.ui.IPreferenceConstants; import net.sourceforge.phpeclipse.ui.WebUI; import net.sourceforge.phpeclipse.ui.overlaypages.FieldEditorOverlayPage; @@ -8,64 +9,75 @@ import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; + /** - * + * * This page will be added to the project's property page dialog when the * "Properties..." popup menu item is selected */ public class PHPPreviewProjectPreferences extends FieldEditorOverlayPage - implements - IWorkbenchPreferencePage { - public final static String PREF_ID = "net.sourceforge.phpeclipse.preferences.PHPPreviewProjectPreferences"; + implements IWorkbenchPreferencePage { + public final static String PREF_ID = "net.sourceforge.phpeclipse.preferences.PHPPreviewProjectPreferences"; + + public PHPPreviewProjectPreferences() { + super(GRID, true); + } + + /* + * (non-Javadoc) + * + * @see com.bdaum.overlayPages.FieldEditorOverlayPage#getPageId() + */ + protected String getPageId() { + return PREF_ID; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.preference.FieldEditorPreferencePage#createFieldEditors() + */ + protected void createFieldEditors() { + Composite composite = getFieldEditorParent(); + addField(new BooleanFieldEditor( + IPreferenceConstants.PHP_AUTO_PREVIEW_DEFAULT, + PHPPreferencesMessages + .getString("PHPPreviewProjectPreferences.auto_preview"), + composite)); + addField(new BooleanFieldEditor( + IPreferenceConstants.PHP_BRING_TO_TOP_PREVIEW_DEFAULT, + PHPPreferencesMessages + .getString("PHPPreviewProjectPreferences.bring_to_top_preview"), + composite)); + // addField(new BooleanFieldEditor( + // IPreferenceConstants.PHP_SHOW_HTML_FILES_LOCAL, + // PHPPreferencesMessages + // .getString("PHPPreviewProjectPreferences.show_html_files_local"), + // composite)); + // addField(new BooleanFieldEditor( + // IPreferenceConstants.PHP_SHOW_XML_FILES_LOCAL, PHPPreferencesMessages + // .getString("PHPPreviewProjectPreferences.show_xml_files_local"), + // composite)); + // if (!isPropertyPage)) { + // + // } + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.preference.PreferencePage#doGetPreferenceStore() + */ + protected IPreferenceStore doGetPreferenceStore() { + return WebUI.getDefault().getPreferenceStore(); + } - public PHPPreviewProjectPreferences() { - super(GRID, true); - } - /* - * (non-Javadoc) - * - * @see com.bdaum.overlayPages.FieldEditorOverlayPage#getPageId() - */ - protected String getPageId() { - return PREF_ID; - } - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.preference.FieldEditorPreferencePage#createFieldEditors() - */ - protected void createFieldEditors() { - Composite composite = getFieldEditorParent(); - addField(new BooleanFieldEditor( - IPreferenceConstants.PHP_AUTO_PREVIEW_DEFAULT, PHPPreferencesMessages - .getString("PHPPreviewProjectPreferences.auto_preview"), composite)); - addField(new BooleanFieldEditor( - IPreferenceConstants.PHP_BRING_TO_TOP_PREVIEW_DEFAULT, PHPPreferencesMessages - .getString("PHPPreviewProjectPreferences.bring_to_top_preview"), composite)); -// addField(new BooleanFieldEditor( -// IPreferenceConstants.PHP_SHOW_HTML_FILES_LOCAL, PHPPreferencesMessages -// .getString("PHPPreviewProjectPreferences.show_html_files_local"), composite)); -// addField(new BooleanFieldEditor( -// IPreferenceConstants.PHP_SHOW_XML_FILES_LOCAL, PHPPreferencesMessages -// .getString("PHPPreviewProjectPreferences.show_xml_files_local"), composite)); - //if (!isPropertyPage)) { - // - //} - } - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.preference.PreferencePage#doGetPreferenceStore() - */ - protected IPreferenceStore doGetPreferenceStore() { - return WebUI.getDefault().getPreferenceStore(); - } - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) - */ - public void init(IWorkbench workbench) { - setDescription("Default entries for Previewer."); - } + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) + */ + public void init(IWorkbench workbench) { + setDescription("Default entries for Previewer."); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/PreferenceDescriptor.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/PreferenceDescriptor.java index d8b8610..46bf488 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/PreferenceDescriptor.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/preferences/PreferenceDescriptor.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: PreferenceDescriptor.java,v 1.1 2004-09-02 18:26:30 jsurfer Exp $ + * $Id: PreferenceDescriptor.java,v 1.2 2006-10-21 23:13:54 pombredanne Exp $ */ package net.sourceforge.phpeclipse.ui.preferences; @@ -20,17 +20,24 @@ package net.sourceforge.phpeclipse.ui.preferences; */ public final class PreferenceDescriptor { public static final Type BOOLEAN = new Type(); - public static final Type DOUBLE = new Type(); - public static final Type FLOAT = new Type(); - public static final Type INT = new Type(); - public static final Type LONG = new Type(); - public static final Type STRING = new Type(); + + public static final Type DOUBLE = new Type(); + + public static final Type FLOAT = new Type(); + + public static final Type INT = new Type(); + + public static final Type LONG = new Type(); + + public static final Type STRING = new Type(); public static final class Type { - Type() {} + Type() { + } } - public final Type type; + public final Type type; + public final String key; public PreferenceDescriptor(Type type, String key) { diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/templates/preferences/TemplatesPreferencePage.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/templates/preferences/TemplatesPreferencePage.java index ecdc770..b40982d 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/templates/preferences/TemplatesPreferencePage.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/templates/preferences/TemplatesPreferencePage.java @@ -14,11 +14,13 @@ import net.sourceforge.phpeclipse.ui.WebUI; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.texteditor.templates.TemplatePreferencePage; + /** * @see org.eclipse.jface.preference.PreferencePage */ -public class TemplatesPreferencePage extends TemplatePreferencePage implements IWorkbenchPreferencePage { - +public class TemplatesPreferencePage extends TemplatePreferencePage implements + IWorkbenchPreferencePage { + public TemplatesPreferencePage() { setPreferenceStore(WebUI.getDefault().getPreferenceStore()); setTemplateStore(WebUI.getDefault().getTemplateStore()); @@ -28,13 +30,12 @@ public class TemplatesPreferencePage extends TemplatePreferencePage implements I protected boolean isShowFormatterSetting() { return false; } - - + public boolean performOk() { - boolean ok= super.performOk(); - + boolean ok = super.performOk(); + WebUI.getDefault().savePluginPreferences(); - + return ok; } } diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/templates/template/BasicCompletionProcessor.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/templates/template/BasicCompletionProcessor.java index fcffda1..5e355e3 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/templates/template/BasicCompletionProcessor.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/templates/template/BasicCompletionProcessor.java @@ -31,151 +31,175 @@ import org.eclipse.jface.text.templates.TemplateContext; import org.eclipse.jface.text.templates.TemplateContextType; import org.eclipse.jface.text.templates.TemplateException; import org.eclipse.swt.graphics.Image; + /** * A completion processor for XML templates. */ public class BasicCompletionProcessor extends TemplateCompletionProcessor { - private static final String DEFAULT_IMAGE = "icons/template.gif"; //$NON-NLS-1$ - private char[] fProposalAutoActivationSet; -// private PHPCompletionProposalComparator fComparator; - public BasicCompletionProcessor() { - super(); -// fComparator = new PHPCompletionProposalComparator(); - } - /** - * We watch for angular brackets since those are often part of XML templates. - */ - protected String extractPrefix(ITextViewer viewer, int offset) { - IDocument document = viewer.getDocument(); - int i = offset; - if (i > document.getLength()) - return ""; //$NON-NLS-1$ - - try { - while (i > 0) { - char ch = document.getChar(i - 1); - if (ch != '<' && ch != '&' && ch != '{' && !Character.isJavaIdentifierPart(ch)) - break; - i--; - } - - return document.get(i, offset - i); - } catch (BadLocationException e) { - return ""; //$NON-NLS-1$ - } - } - - /** - * Cut out angular brackets for relevance sorting, since the template name does not contain the brackets. - */ - protected int getRelevance(Template template, String prefix) { - // if (prefix.startsWith("<")) //$NON-NLS-1$ - // prefix= prefix.substring(1); - if (template.getName().startsWith(prefix)) - return 90; - return 0; - } - - /** - * Simply return all templates. - */ - protected Template[] getTemplates(String contextTypeId) { - return WebUI.getDefault().getTemplateStore().getTemplates(); - } - - /** - * Return the XML context type that is supported by this plugin. - */ - protected TemplateContextType getContextType(ITextViewer viewer, IRegion region) { - return WebUI.getDefault().getContextTypeRegistry().getContextType(XMLContextType.XML_CONTEXT_TYPE); - } - - /** - * Always return the default image. - */ - protected Image getImage(Template template) { - ImageRegistry registry = WebUI.getDefault().getImageRegistry(); - Image image = registry.get(DEFAULT_IMAGE); - if (image == null) { - ImageDescriptor desc = WebUI.imageDescriptorFromPlugin("org.eclipse.ui.examples.javaeditor", DEFAULT_IMAGE); //$NON-NLS-1$ - registry.put(DEFAULT_IMAGE, desc); - image = registry.get(DEFAULT_IMAGE); - } - return image; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeCompletionProposals(org.eclipse.jface.text.ITextViewer, - * int) - */ - public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) { - ITextSelection selection = (ITextSelection) viewer.getSelectionProvider().getSelection(); - - // adjust offset to end of normalized selection - if (selection.getOffset() == offset) - offset = selection.getOffset() + selection.getLength(); - - String prefix = extractPrefix(viewer, offset); - prefix = prefix.toLowerCase(); - IRegion region = new Region(offset - prefix.length(), prefix.length()); - TemplateContext context = createContext(viewer, region); - if (context == null) - return new ICompletionProposal[0]; - - context.setVariable("selection", selection.getText()); // name of the selection variables {line, word}_selection //$NON-NLS-1$ - - Template[] templates = getTemplates(context.getContextType().getId()); - - List matches = new ArrayList(); - for (int i = 0; i < templates.length; i++) { - Template template = templates[i]; - try { - context.getContextType().validate(template.getPattern()); - } catch (TemplateException e) { - continue; - } - - if (template.getName().startsWith(prefix)) { //&& template.matches(prefix, context.getContextType().getId())) - matches.add(createProposal(template, context, region, getRelevance(template, prefix))); - } - } - - return (ICompletionProposal[]) matches.toArray(new ICompletionProposal[matches.size()]); - - } - /** - * @see IContentAssistProcessor#getCompletionProposalAutoActivationCharacters() - */ - public char[] getCompletionProposalAutoActivationCharacters() { - return fProposalAutoActivationSet; - } - - /** - * Sets this processor's set of characters triggering the activation of the - * completion proposal computation. - * - * @param activationSet the activation set - */ - public void setCompletionProposalAutoActivationCharacters(char[] activationSet) { - fProposalAutoActivationSet= activationSet; - } - - /** - * Order the given proposals. - */ -// private ICompletionProposal[] order(ICompletionProposal[] proposals) { -// Arrays.sort(proposals, fComparator); -// return proposals; -// } - - /** - * Tells this processor to order the proposals alphabetically. - * - * @param order true if proposals should be ordered. - */ -// public void orderProposalsAlphabetically(boolean order) { -// fComparator.setOrderAlphabetically(order); -// } + private static final String DEFAULT_IMAGE = "icons/template.gif"; //$NON-NLS-1$ + + private char[] fProposalAutoActivationSet; + + // private PHPCompletionProposalComparator fComparator; + public BasicCompletionProcessor() { + super(); + // fComparator = new PHPCompletionProposalComparator(); + } + + /** + * We watch for angular brackets since those are often part of XML + * templates. + */ + protected String extractPrefix(ITextViewer viewer, int offset) { + IDocument document = viewer.getDocument(); + int i = offset; + if (i > document.getLength()) + return ""; //$NON-NLS-1$ + + try { + while (i > 0) { + char ch = document.getChar(i - 1); + if (ch != '<' && ch != '&' && ch != '{' + && !Character.isJavaIdentifierPart(ch)) + break; + i--; + } + + return document.get(i, offset - i); + } catch (BadLocationException e) { + return ""; //$NON-NLS-1$ + } + } + + /** + * Cut out angular brackets for relevance sorting, since the template name + * does not contain the brackets. + */ + protected int getRelevance(Template template, String prefix) { + // if (prefix.startsWith("<")) //$NON-NLS-1$ + // prefix= prefix.substring(1); + if (template.getName().startsWith(prefix)) + return 90; + return 0; + } + + /** + * Simply return all templates. + */ + protected Template[] getTemplates(String contextTypeId) { + return WebUI.getDefault().getTemplateStore().getTemplates(); + } + + /** + * Return the XML context type that is supported by this plugin. + */ + protected TemplateContextType getContextType(ITextViewer viewer, + IRegion region) { + return WebUI.getDefault().getContextTypeRegistry().getContextType( + XMLContextType.XML_CONTEXT_TYPE); + } + + /** + * Always return the default image. + */ + protected Image getImage(Template template) { + ImageRegistry registry = WebUI.getDefault().getImageRegistry(); + Image image = registry.get(DEFAULT_IMAGE); + if (image == null) { + ImageDescriptor desc = WebUI.imageDescriptorFromPlugin( + "org.eclipse.ui.examples.javaeditor", DEFAULT_IMAGE); //$NON-NLS-1$ + registry.put(DEFAULT_IMAGE, desc); + image = registry.get(DEFAULT_IMAGE); + } + return image; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeCompletionProposals(org.eclipse.jface.text.ITextViewer, + * int) + */ + public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, + int offset) { + ITextSelection selection = (ITextSelection) viewer + .getSelectionProvider().getSelection(); + + // adjust offset to end of normalized selection + if (selection.getOffset() == offset) + offset = selection.getOffset() + selection.getLength(); + + String prefix = extractPrefix(viewer, offset); + prefix = prefix.toLowerCase(); + IRegion region = new Region(offset - prefix.length(), prefix.length()); + TemplateContext context = createContext(viewer, region); + if (context == null) + return new ICompletionProposal[0]; + + context.setVariable("selection", selection.getText()); // name of the + // selection + // variables + // {line, + // word}_selection + // //$NON-NLS-1$ + + Template[] templates = getTemplates(context.getContextType().getId()); + + List matches = new ArrayList(); + for (int i = 0; i < templates.length; i++) { + Template template = templates[i]; + try { + context.getContextType().validate(template.getPattern()); + } catch (TemplateException e) { + continue; + } + + if (template.getName().startsWith(prefix)) { // && + // template.matches(prefix, + // context.getContextType().getId())) + matches.add(createProposal(template, context, region, + getRelevance(template, prefix))); + } + } + + return (ICompletionProposal[]) matches + .toArray(new ICompletionProposal[matches.size()]); + + } + + /** + * @see IContentAssistProcessor#getCompletionProposalAutoActivationCharacters() + */ + public char[] getCompletionProposalAutoActivationCharacters() { + return fProposalAutoActivationSet; + } + + /** + * Sets this processor's set of characters triggering the activation of the + * completion proposal computation. + * + * @param activationSet + * the activation set + */ + public void setCompletionProposalAutoActivationCharacters( + char[] activationSet) { + fProposalAutoActivationSet = activationSet; + } + + /** + * Order the given proposals. + */ + // private ICompletionProposal[] order(ICompletionProposal[] proposals) { + // Arrays.sort(proposals, fComparator); + // return proposals; + // } + /** + * Tells this processor to order the proposals alphabetically. + * + * @param order + * true if proposals should be ordered. + */ + // public void orderProposalsAlphabetically(boolean order) { + // fComparator.setOrderAlphabetically(order); + // } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/templates/template/HTMLContextType.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/templates/template/HTMLContextType.java index 908b084..365f53d 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/templates/template/HTMLContextType.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/templates/template/HTMLContextType.java @@ -13,17 +13,16 @@ package net.sourceforge.phpeclipse.ui.templates.template; import org.eclipse.jface.text.templates.GlobalTemplateVariables; import org.eclipse.jface.text.templates.TemplateContextType; - /** * A very simple context type. */ public class HTMLContextType extends TemplateContextType { /** This context's id */ - public static final String HTML_CONTEXT_TYPE= "html"; //$NON-NLS-1$ + public static final String HTML_CONTEXT_TYPE = "html"; //$NON-NLS-1$ /** - * Creates a new XML context type. + * Creates a new XML context type. */ public HTMLContextType() { addGlobalResolvers(); diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/templates/template/JSContextType.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/templates/template/JSContextType.java index 63d51da..e0dca6a 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/templates/template/JSContextType.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/templates/template/JSContextType.java @@ -13,17 +13,16 @@ package net.sourceforge.phpeclipse.ui.templates.template; import org.eclipse.jface.text.templates.GlobalTemplateVariables; import org.eclipse.jface.text.templates.TemplateContextType; - /** * A very simple context type. */ public class JSContextType extends TemplateContextType { /** This context's id */ - public static final String JS_CONTEXT_TYPE= "javascript"; //$NON-NLS-1$ + public static final String JS_CONTEXT_TYPE = "javascript"; //$NON-NLS-1$ /** - * Creates a new XML context type. + * Creates a new XML context type. */ public JSContextType() { addGlobalResolvers(); diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/templates/template/SmartyContextType.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/templates/template/SmartyContextType.java index e42270e..d5d9efa 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/templates/template/SmartyContextType.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/templates/template/SmartyContextType.java @@ -13,17 +13,16 @@ package net.sourceforge.phpeclipse.ui.templates.template; import org.eclipse.jface.text.templates.GlobalTemplateVariables; import org.eclipse.jface.text.templates.TemplateContextType; - /** * A very simple context type. */ public class SmartyContextType extends TemplateContextType { /** This context's id */ - public static final String SMARTY_CONTEXT_TYPE= "smarty"; //$NON-NLS-1$ + public static final String SMARTY_CONTEXT_TYPE = "smarty"; //$NON-NLS-1$ /** - * Creates a new XML context type. + * Creates a new XML context type. */ public SmartyContextType() { addGlobalResolvers(); diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/templates/template/XMLContextType.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/templates/template/XMLContextType.java index 9944dfb..7765baa 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/templates/template/XMLContextType.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/templates/template/XMLContextType.java @@ -13,17 +13,16 @@ package net.sourceforge.phpeclipse.ui.templates.template; import org.eclipse.jface.text.templates.GlobalTemplateVariables; import org.eclipse.jface.text.templates.TemplateContextType; - /** * A very simple context type. */ public class XMLContextType extends TemplateContextType { /** This context's id */ - public static final String XML_CONTEXT_TYPE= "xml"; //$NON-NLS-1$ + public static final String XML_CONTEXT_TYPE = "xml"; //$NON-NLS-1$ /** - * Creates a new XML context type. + * Creates a new XML context type. */ public XMLContextType() { addGlobalResolvers(); diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/AbstractTextTools.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/AbstractTextTools.java index 8fbea65..cfa3247 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/AbstractTextTools.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/AbstractTextTools.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: AbstractTextTools.java,v 1.2 2004-09-22 18:51:51 jsurfer Exp $ + * $Id: AbstractTextTools.java,v 1.3 2006-10-21 23:13:54 pombredanne Exp $ */ package net.sourceforge.phpeclipse.ui.text; @@ -55,12 +55,14 @@ public class AbstractTextTools { * Creates a new text tools collection. */ public AbstractTextTools(IPreferenceStore store, String[] properties) { - this(store, properties, new ColorManager()); + this(store, properties, new ColorManager()); } + /** * Creates a new text tools collection. */ - public AbstractTextTools(IPreferenceStore store, String[] properties, ColorManager manager) { + public AbstractTextTools(IPreferenceStore store, String[] properties, + ColorManager manager) { this.store = store; this.properties = properties; @@ -140,8 +142,8 @@ public class AbstractTextTools { } /** - * Returns the color manager which is used to manage any XML-specific - * colors needed for such things like syntax highlighting. + * Returns the color manager which is used to manage any XML-specific colors + * needed for such things like syntax highlighting. * * @return the color manager to be used for XML text viewers */ diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/IReconcilingParticipant.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/IReconcilingParticipant.java index 26f9f62..b232899 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/IReconcilingParticipant.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/IReconcilingParticipant.java @@ -8,16 +8,16 @@ * Contributors: * Christopher Lenz - initial API * - * $Id: IReconcilingParticipant.java,v 1.1 2004-09-02 18:26:49 jsurfer Exp $ + * $Id: IReconcilingParticipant.java,v 1.2 2006-10-21 23:13:54 pombredanne Exp $ */ package net.sourceforge.phpeclipse.ui.text; /** - * Interface for classes participating in reconciling. + * Interface for classes participating in reconciling. */ public interface IReconcilingParticipant { - + /** * Called after reconciling has been finished. */ diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/TextDoubleClickStrategy.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/TextDoubleClickStrategy.java index c3e70a5..def4daf 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/TextDoubleClickStrategy.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/TextDoubleClickStrategy.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: TextDoubleClickStrategy.java,v 1.1 2004-09-02 18:26:49 jsurfer Exp $ + * $Id: TextDoubleClickStrategy.java,v 1.2 2006-10-21 23:13:54 pombredanne Exp $ */ package net.sourceforge.phpeclipse.ui.text; @@ -28,7 +28,9 @@ public class TextDoubleClickStrategy implements ITextDoubleClickStrategy { */ public void doubleClicked(ITextViewer viewer) { int offset = viewer.getSelectedRange().x; - if (offset < 0) { return; } + if (offset < 0) { + return; + } selectWord(viewer, viewer.getDocument(), offset); } diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/rules/AbstractPartitioner.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/rules/AbstractPartitioner.java index ab96dd5..04819c8 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/rules/AbstractPartitioner.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/rules/AbstractPartitioner.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: AbstractPartitioner.java,v 1.3 2004-12-29 21:42:31 axelcl Exp $ + * $Id: AbstractPartitioner.java,v 1.4 2006-10-21 23:13:53 pombredanne Exp $ */ package net.sourceforge.phpeclipse.ui.text.rules; @@ -29,548 +29,568 @@ import org.eclipse.jface.text.rules.IPartitionTokenScanner; import org.eclipse.jface.text.rules.IToken; /** - * Advanced partitioner which maintains partitions as views to connected document. Views have own partitioners themselves. This - * class is designed as a base for complex partitioners such as for JSP, PHP, ASP, etc. languages. + * Advanced partitioner which maintains partitions as views to connected + * document. Views have own partitioners themselves. This class is designed as a + * base for complex partitioners such as for JSP, PHP, ASP, etc. languages. * * @author Igor Malinin */ -public abstract class AbstractPartitioner implements IDocumentPartitioner, IDocumentPartitionerExtension { - public final static boolean DEBUG = false; - - /** Partition scanner */ - protected IPartitionTokenScanner scanner; - - /** Connected document */ - protected IDocument document; - - /** Flat structure of the document */ - protected List nodes = new ArrayList(); - - /** The offset at which the first changed partition starts */ - protected int regionStart; - - /** The offset at which the last changed partition ends */ - protected int regionEnd; - - public AbstractPartitioner(IPartitionTokenScanner scanner) { - this.scanner = scanner; - } - - protected FlatNode createNode(String type, int offset, int length) { - if (DEBUG) { - Assert.isTrue(offset >= 0, Integer.toString(offset)); - } - FlatNode node = new FlatNode(type); - node.offset = offset; - node.length = length; - return node; - } - - protected void addInnerRegion(FlatNode position) { - nodes.add(computeFlatNodeIndex(position.offset), position); - } - - protected void removeInnerRegion(FlatNode position) { - nodes.remove(position); // TODO: Indexed remove? - } - - protected void deleteInnerRegion(FlatNode position) { - nodes.remove(position); // TODO: Indexed remove? - } - - protected void resizeInnerRegion(FlatNode position) { - } - - /* - * @see org.eclipse.jface.text.IDocumentPartitioner#connect(IDocument) - */ - public void connect(IDocument document) { - this.document = document; - - initialize(); - } - - /* - * @see org.eclipse.jface.text.IDocumentPartitioner#disconnect() - */ - public void disconnect() { - nodes.clear(); - document = null; - } - - /** - * Performs the initial partitioning of the partitioner's document. - */ - protected void initialize() { - scanner.setRange(document, 0, document.getLength()); - // axelcl start - nodes.clear(); - // axelcl end - IToken token = scanner.nextToken(); - while (!token.isEOF()) { - String contentType = getTokenContentType(token); - - if (isSupportedContentType(contentType)) { - addInnerRegion(createNode(contentType, scanner.getTokenOffset(), scanner.getTokenLength())); - } - - token = scanner.nextToken(); - } - } - - /* - * @see org.eclipse.jface.text.IDocumentPartitioner#documentAboutToBeChanged(DocumentEvent) - */ - public void documentAboutToBeChanged(DocumentEvent event) { - regionStart = regionEnd = -1; - } - - /* - * @see org.eclipse.jface.text.IDocumentPartitioner#documentChanged(DocumentEvent) - */ - public boolean documentChanged(DocumentEvent event) { - return (documentChanged2(event) != null); - } - - /* - * @see org.eclipse.jface.text.IDocumentPartitionerExtension#documentChanged2(DocumentEvent) - */ - public IRegion documentChanged2(DocumentEvent event) { - int first = fixupPartitions(event); - - FlatNode[] category = (FlatNode[]) nodes.toArray(new FlatNode[nodes.size()]); - - // repartition changed region - - String contentType = IDocument.DEFAULT_CONTENT_TYPE; - - int offset; - - if (first == 0) { - offset = 0; // Bug #697414: first offset - } else { - offset = event.getOffset(); - - FlatNode partition = category[first - 1]; - if (partition.includes(offset)) { - offset = partition.offset; - contentType = partition.type; - --first; - } else if (offset == partition.offset + partition.length) { - offset = partition.offset; - contentType = partition.type; - --first; - } else { - offset = partition.offset + partition.length; - } - } - - // should not be changed since last conversion - // category = (FlatNode[]) nodes.toArray(new FlatNode[nodes.size()]); - if (DEBUG) { - Assert.isTrue(offset >= 0, Integer.toString(offset)); - } - scanner.setPartialRange(document, offset, document.getLength(), contentType, offset); - - int lastScannedPosition = offset; - IToken token = scanner.nextToken(); - while (!token.isEOF()) { - contentType = getTokenContentType(token); - - if (!isSupportedContentType(contentType)) { - token = scanner.nextToken(); - continue; - } - - offset = scanner.getTokenOffset(); - if (DEBUG) { - Assert.isTrue(offset >= 0, scanner.toString()); - } - int length = scanner.getTokenLength(); - - lastScannedPosition = offset + length; - - // remove all affected positions - while (first < category.length) { - FlatNode p = category[first]; - if (p.offset + p.length < lastScannedPosition - || (p.overlapsWith(offset, length) && (!containsPosition(offset, length) || !contentType.equals(p.type)))) { - removeInnerRegion(p); - rememberRegion(p.offset, p.length); - ++first; - } else { - break; - } - } - - // if position already exists we are done - if (containsPosition(offset, length)) { - if (lastScannedPosition > event.getOffset()) { - // TODO: optional repartition till end of doc - return createRegion(); - } - - ++first; - } else { - // insert the new type position - addInnerRegion(createNode(contentType, offset, length)); - rememberRegion(offset, length); - } - // try { - token = scanner.nextToken(); - // } catch (ArrayIndexOutOfBoundsException e) { - // System.out.println(this.getClass().toString()); - // throw e; - // } - } - - // remove all positions behind lastScannedPosition - // since there aren't any further types - - // Do not need to recalculate (lost remove events)! - // first = computeIndexInInnerDocuments(lastScannedPosition); - while (first < category.length) { - FlatNode p = category[first++]; - removeInnerRegion(p); - rememberRegion(p.offset, p.length); - } - - return createRegion(); - } - - protected int fixupPartitions(DocumentEvent event) { - int offset = event.getOffset(); - int length = event.getLength(); - int end = offset + length; - - // fixup flat nodes laying on change boundaries - - int first = computeFlatNodeIndex(offset); - if (first > 0) { - FlatNode p = (FlatNode) nodes.get(first - 1); - - int right = p.offset + p.length; - if (offset < right) { - // change overlaps with partition - if (end < right) { - // cahnge completely inside partition - String text = event.getText(); - p.length -= length; - if (text != null) { - p.length += text.length(); - } - } else { - // cut partition at right - int cut = p.offset + p.length - offset; - p.length -= cut; - } - } - } - - int last = computeFlatNodeIndex(end); - if (first < last) { - FlatNode p = (FlatNode) nodes.get(last - 1); - - int right = p.offset + p.length; - if (end < right) { - // cut partition at left - int cut = end - p.offset; - p.length -= cut; - p.offset = offset; - - String text = event.getText(); - if (text != null) { - p.offset += text.length(); - } - - --last; - } - } - - // fixup flat nodes laying afrer change - - String text = event.getText(); - if (text != null) { - length -= text.length(); - } - - for (int i = last, size = nodes.size(); i < size; i++) { - ((FlatNode) nodes.get(i)).offset -= length; - } - - // delete flat nodes laying completely inside change boundaries - - if (first < last) { - do { - deleteInnerRegion((FlatNode) nodes.get(--last)); - } while (first < last); - - rememberRegion(offset, 0); - } - - return first; - } - - /** - * Returns whether the given type is one of the legal content types. - * - * @param contentType - * the content type to check - * @return true if the content type is a legal content type - */ - protected boolean isSupportedContentType(String contentType) { - /* TODO: implementation */ - // if (contentType != null) { - // for (int i= 0; i < fLegalContentTypes.length; i++) { - // if (fLegalContentTypes[i].equals(contentType)) { - // return true; - // } - // } - // } - // return false; - return (contentType != null); - } - - /** - * Returns a content type encoded in the given token. If the token's data is not null and a string it is assumed - * that it is the encoded content type. - * - * @param token - * the token whose content type is to be determined - * @return the token's content type - */ - protected String getTokenContentType(IToken token) { - Object data = token.getData(); - if (data instanceof String) { - return (String) data; - } - - return null; - } - - /* - * @see org.eclipse.jface.text.IDocumentPartitioner#getLegalContentTypes() - */ - public String[] getLegalContentTypes() { - // TODO: implementation - return null; - } - - /* - * @see org.eclipse.jface.text.IDocumentPartitioner#getContentType(int) - */ - public String getContentType(int offset) { - return getPartition(offset).getType(); - } - - /* - * @see org.eclipse.jface.text.IDocumentPartitioner#getPartition(int) - */ - public ITypedRegion getPartition(int offset) { - if (nodes.size() == 0) { - return new TypedRegion(0, document.getLength(), IDocument.DEFAULT_CONTENT_TYPE); - } - - int index = computeFlatNodeIndex(offset); - if (index < nodes.size()) { - FlatNode next = (FlatNode) nodes.get(index); - - if (offset == next.offset) { - return new TypedRegion(next.offset, next.length, next.type); - } - - if (index == 0) { - return new TypedRegion(0, next.offset, IDocument.DEFAULT_CONTENT_TYPE); - } - - FlatNode prev = (FlatNode) nodes.get(index - 1); - - if (prev.includes(offset)) { - return new TypedRegion(prev.offset, prev.length, prev.type); - } - - int end = prev.offset + prev.length; - return new TypedRegion(end, next.offset - end, IDocument.DEFAULT_CONTENT_TYPE); - } - - FlatNode prev = (FlatNode) nodes.get(nodes.size() - 1); - - if (prev.includes(offset)) { - return new TypedRegion(prev.offset, prev.length, prev.type); - } - - int end = prev.offset + prev.length; - - return new TypedRegion(end, document.getLength() - end, IDocument.DEFAULT_CONTENT_TYPE); - } - - /* - * @see org.eclipse.jface.text.IDocumentPartitioner#computePartitioning(int, int) - */ - public ITypedRegion[] computePartitioning(int offset, int length) { - List list = new ArrayList(); - - int end = offset + length; - - int index = computeFlatNodeIndex(offset); - while (true) { - FlatNode prev = (index > 0) ? (FlatNode) nodes.get(index - 1) : null; - - if (prev != null) { - if (prev.overlapsWith(offset, length)) { - list.add(new TypedRegion(prev.offset, prev.length, prev.type)); - } - - if (end <= prev.offset + prev.length) { - break; - } - } - - FlatNode next = (index < nodes.size()) ? (FlatNode) nodes.get(index) : null; - - if (next == null || offset < next.offset) { - int off0 = offset; - int off1 = offset + length; - - if (prev != null && off0 < prev.offset + prev.length) { - off0 = prev.offset + prev.length; - } - - if (next != null && next.offset < off1) { - off1 = next.offset; - } - - if (off0 < off1) { - list.add(new TypedRegion(off0, off1 - off0, IDocument.DEFAULT_CONTENT_TYPE)); - } - } - - if (next == null) { - break; - } - - ++index; - } - - return (TypedRegion[]) list.toArray(new TypedRegion[list.size()]); - } - - /** - * Computes the index in the list of flat nodes at which an flat node with the given offset would be inserted. The flat node is - * supposed to become the first in this list of all flat nodes with the same offset. - * - * @param offset - * the offset for which the index is computed - * @return the computed index - */ - protected int computeFlatNodeIndex(int offset) { - if (nodes.size() == 0) { - return 0; - } - - int left = 0, mid = 0; - int right = nodes.size() - 1; - - FlatNode p = null; - - while (left < right) { - mid = (left + right) / 2; - - p = (FlatNode) nodes.get(mid); - - if (offset < p.offset) { - right = (left == mid) ? left : mid - 1; - } else if (offset > p.offset) { - left = (right == mid) ? right : mid + 1; - } else if (offset == p.offset) { - left = right = mid; - } - } - - int pos = left; - p = (FlatNode) nodes.get(pos); - if (offset > p.offset) { - // append to the end - pos++; - } else { - // entry will became the first of all entries with the same offset - do { - --pos; - if (pos < 0) { - break; - } - p = (FlatNode) nodes.get(pos); - } while (offset == p.offset); - ++pos; - } - - return pos; - } - - public boolean containsPosition(int offset, int length) { - int size = nodes.size(); - if (size == 0) { - return false; - } - - int index = computeFlatNodeIndex(offset); - if (index < size) { - FlatNode p = (FlatNode) nodes.get(index); - - while (p.offset == offset) { - if (p.length == length) { - return true; - } - - if (++index < size) { - p = (FlatNode) nodes.get(index); - } else { - break; - } - } - } - - return false; - } - - /** - * Helper method for tracking the minimal region containg all partition changes. If offset is smaller than the - * remembered offset, offset will from now on be remembered. If offset + length is greater than the - * remembered end offset, it will be remembered from now on. - * - * @param offset - * the offset - * @param length - * the length - */ - protected final void rememberRegion(int offset, int length) { - // remember start offset - if (regionStart == -1) { - regionStart = offset; - } else if (offset < regionStart) { - regionStart = offset; - } - - // remember end offset - int endOffset = offset + length; - - if (regionEnd == -1) { - regionEnd = endOffset; - } else if (endOffset > regionEnd) { - regionEnd = endOffset; - } - } - - /** - * Creates the minimal region containing all partition changes using the remembered offsets. - * - * @return the minimal region containing all the partition changes - */ - protected final IRegion createRegion() { - if (regionStart == -1 || regionEnd == -1) { - return null; - } - - return new Region(regionStart, regionEnd - regionStart); - } +public abstract class AbstractPartitioner implements IDocumentPartitioner, + IDocumentPartitionerExtension { + public final static boolean DEBUG = false; + + /** Partition scanner */ + protected IPartitionTokenScanner scanner; + + /** Connected document */ + protected IDocument document; + + /** Flat structure of the document */ + protected List nodes = new ArrayList(); + + /** The offset at which the first changed partition starts */ + protected int regionStart; + + /** The offset at which the last changed partition ends */ + protected int regionEnd; + + public AbstractPartitioner(IPartitionTokenScanner scanner) { + this.scanner = scanner; + } + + protected FlatNode createNode(String type, int offset, int length) { + if (DEBUG) { + Assert.isTrue(offset >= 0, Integer.toString(offset)); + } + FlatNode node = new FlatNode(type); + node.offset = offset; + node.length = length; + return node; + } + + protected void addInnerRegion(FlatNode position) { + nodes.add(computeFlatNodeIndex(position.offset), position); + } + + protected void removeInnerRegion(FlatNode position) { + nodes.remove(position); // TODO: Indexed remove? + } + + protected void deleteInnerRegion(FlatNode position) { + nodes.remove(position); // TODO: Indexed remove? + } + + protected void resizeInnerRegion(FlatNode position) { + } + + /* + * @see org.eclipse.jface.text.IDocumentPartitioner#connect(IDocument) + */ + public void connect(IDocument document) { + this.document = document; + + initialize(); + } + + /* + * @see org.eclipse.jface.text.IDocumentPartitioner#disconnect() + */ + public void disconnect() { + nodes.clear(); + document = null; + } + + /** + * Performs the initial partitioning of the partitioner's document. + */ + protected void initialize() { + scanner.setRange(document, 0, document.getLength()); + // axelcl start + nodes.clear(); + // axelcl end + IToken token = scanner.nextToken(); + while (!token.isEOF()) { + String contentType = getTokenContentType(token); + + if (isSupportedContentType(contentType)) { + addInnerRegion(createNode(contentType, + scanner.getTokenOffset(), scanner.getTokenLength())); + } + + token = scanner.nextToken(); + } + } + + /* + * @see org.eclipse.jface.text.IDocumentPartitioner#documentAboutToBeChanged(DocumentEvent) + */ + public void documentAboutToBeChanged(DocumentEvent event) { + regionStart = regionEnd = -1; + } + + /* + * @see org.eclipse.jface.text.IDocumentPartitioner#documentChanged(DocumentEvent) + */ + public boolean documentChanged(DocumentEvent event) { + return (documentChanged2(event) != null); + } + + /* + * @see org.eclipse.jface.text.IDocumentPartitionerExtension#documentChanged2(DocumentEvent) + */ + public IRegion documentChanged2(DocumentEvent event) { + int first = fixupPartitions(event); + + FlatNode[] category = (FlatNode[]) nodes.toArray(new FlatNode[nodes + .size()]); + + // repartition changed region + + String contentType = IDocument.DEFAULT_CONTENT_TYPE; + + int offset; + + if (first == 0) { + offset = 0; // Bug #697414: first offset + } else { + offset = event.getOffset(); + + FlatNode partition = category[first - 1]; + if (partition.includes(offset)) { + offset = partition.offset; + contentType = partition.type; + --first; + } else if (offset == partition.offset + partition.length) { + offset = partition.offset; + contentType = partition.type; + --first; + } else { + offset = partition.offset + partition.length; + } + } + + // should not be changed since last conversion + // category = (FlatNode[]) nodes.toArray(new FlatNode[nodes.size()]); + if (DEBUG) { + Assert.isTrue(offset >= 0, Integer.toString(offset)); + } + scanner.setPartialRange(document, offset, document.getLength(), + contentType, offset); + + int lastScannedPosition = offset; + IToken token = scanner.nextToken(); + while (!token.isEOF()) { + contentType = getTokenContentType(token); + + if (!isSupportedContentType(contentType)) { + token = scanner.nextToken(); + continue; + } + + offset = scanner.getTokenOffset(); + if (DEBUG) { + Assert.isTrue(offset >= 0, scanner.toString()); + } + int length = scanner.getTokenLength(); + + lastScannedPosition = offset + length; + + // remove all affected positions + while (first < category.length) { + FlatNode p = category[first]; + if (p.offset + p.length < lastScannedPosition + || (p.overlapsWith(offset, length) && (!containsPosition( + offset, length) || !contentType.equals(p.type)))) { + removeInnerRegion(p); + rememberRegion(p.offset, p.length); + ++first; + } else { + break; + } + } + + // if position already exists we are done + if (containsPosition(offset, length)) { + if (lastScannedPosition > event.getOffset()) { + // TODO: optional repartition till end of doc + return createRegion(); + } + + ++first; + } else { + // insert the new type position + addInnerRegion(createNode(contentType, offset, length)); + rememberRegion(offset, length); + } + // try { + token = scanner.nextToken(); + // } catch (ArrayIndexOutOfBoundsException e) { + // System.out.println(this.getClass().toString()); + // throw e; + // } + } + + // remove all positions behind lastScannedPosition + // since there aren't any further types + + // Do not need to recalculate (lost remove events)! + // first = computeIndexInInnerDocuments(lastScannedPosition); + while (first < category.length) { + FlatNode p = category[first++]; + removeInnerRegion(p); + rememberRegion(p.offset, p.length); + } + + return createRegion(); + } + + protected int fixupPartitions(DocumentEvent event) { + int offset = event.getOffset(); + int length = event.getLength(); + int end = offset + length; + + // fixup flat nodes laying on change boundaries + + int first = computeFlatNodeIndex(offset); + if (first > 0) { + FlatNode p = (FlatNode) nodes.get(first - 1); + + int right = p.offset + p.length; + if (offset < right) { + // change overlaps with partition + if (end < right) { + // cahnge completely inside partition + String text = event.getText(); + p.length -= length; + if (text != null) { + p.length += text.length(); + } + } else { + // cut partition at right + int cut = p.offset + p.length - offset; + p.length -= cut; + } + } + } + + int last = computeFlatNodeIndex(end); + if (first < last) { + FlatNode p = (FlatNode) nodes.get(last - 1); + + int right = p.offset + p.length; + if (end < right) { + // cut partition at left + int cut = end - p.offset; + p.length -= cut; + p.offset = offset; + + String text = event.getText(); + if (text != null) { + p.offset += text.length(); + } + + --last; + } + } + + // fixup flat nodes laying afrer change + + String text = event.getText(); + if (text != null) { + length -= text.length(); + } + + for (int i = last, size = nodes.size(); i < size; i++) { + ((FlatNode) nodes.get(i)).offset -= length; + } + + // delete flat nodes laying completely inside change boundaries + + if (first < last) { + do { + deleteInnerRegion((FlatNode) nodes.get(--last)); + } while (first < last); + + rememberRegion(offset, 0); + } + + return first; + } + + /** + * Returns whether the given type is one of the legal content types. + * + * @param contentType + * the content type to check + * @return true if the content type is a legal content type + */ + protected boolean isSupportedContentType(String contentType) { + /* TODO: implementation */ + // if (contentType != null) { + // for (int i= 0; i < fLegalContentTypes.length; i++) { + // if (fLegalContentTypes[i].equals(contentType)) { + // return true; + // } + // } + // } + // return false; + return (contentType != null); + } + + /** + * Returns a content type encoded in the given token. If the token's data is + * not null and a string it is assumed that it is the encoded + * content type. + * + * @param token + * the token whose content type is to be determined + * @return the token's content type + */ + protected String getTokenContentType(IToken token) { + Object data = token.getData(); + if (data instanceof String) { + return (String) data; + } + + return null; + } + + /* + * @see org.eclipse.jface.text.IDocumentPartitioner#getLegalContentTypes() + */ + public String[] getLegalContentTypes() { + // TODO: implementation + return null; + } + + /* + * @see org.eclipse.jface.text.IDocumentPartitioner#getContentType(int) + */ + public String getContentType(int offset) { + return getPartition(offset).getType(); + } + + /* + * @see org.eclipse.jface.text.IDocumentPartitioner#getPartition(int) + */ + public ITypedRegion getPartition(int offset) { + if (nodes.size() == 0) { + return new TypedRegion(0, document.getLength(), + IDocument.DEFAULT_CONTENT_TYPE); + } + + int index = computeFlatNodeIndex(offset); + if (index < nodes.size()) { + FlatNode next = (FlatNode) nodes.get(index); + + if (offset == next.offset) { + return new TypedRegion(next.offset, next.length, next.type); + } + + if (index == 0) { + return new TypedRegion(0, next.offset, + IDocument.DEFAULT_CONTENT_TYPE); + } + + FlatNode prev = (FlatNode) nodes.get(index - 1); + + if (prev.includes(offset)) { + return new TypedRegion(prev.offset, prev.length, prev.type); + } + + int end = prev.offset + prev.length; + return new TypedRegion(end, next.offset - end, + IDocument.DEFAULT_CONTENT_TYPE); + } + + FlatNode prev = (FlatNode) nodes.get(nodes.size() - 1); + + if (prev.includes(offset)) { + return new TypedRegion(prev.offset, prev.length, prev.type); + } + + int end = prev.offset + prev.length; + + return new TypedRegion(end, document.getLength() - end, + IDocument.DEFAULT_CONTENT_TYPE); + } + + /* + * @see org.eclipse.jface.text.IDocumentPartitioner#computePartitioning(int, + * int) + */ + public ITypedRegion[] computePartitioning(int offset, int length) { + List list = new ArrayList(); + + int end = offset + length; + + int index = computeFlatNodeIndex(offset); + while (true) { + FlatNode prev = (index > 0) ? (FlatNode) nodes.get(index - 1) + : null; + + if (prev != null) { + if (prev.overlapsWith(offset, length)) { + list.add(new TypedRegion(prev.offset, prev.length, + prev.type)); + } + + if (end <= prev.offset + prev.length) { + break; + } + } + + FlatNode next = (index < nodes.size()) ? (FlatNode) nodes + .get(index) : null; + + if (next == null || offset < next.offset) { + int off0 = offset; + int off1 = offset + length; + + if (prev != null && off0 < prev.offset + prev.length) { + off0 = prev.offset + prev.length; + } + + if (next != null && next.offset < off1) { + off1 = next.offset; + } + + if (off0 < off1) { + list.add(new TypedRegion(off0, off1 - off0, + IDocument.DEFAULT_CONTENT_TYPE)); + } + } + + if (next == null) { + break; + } + + ++index; + } + + return (TypedRegion[]) list.toArray(new TypedRegion[list.size()]); + } + + /** + * Computes the index in the list of flat nodes at which an flat node with + * the given offset would be inserted. The flat node is supposed to become + * the first in this list of all flat nodes with the same offset. + * + * @param offset + * the offset for which the index is computed + * @return the computed index + */ + protected int computeFlatNodeIndex(int offset) { + if (nodes.size() == 0) { + return 0; + } + + int left = 0, mid = 0; + int right = nodes.size() - 1; + + FlatNode p = null; + + while (left < right) { + mid = (left + right) / 2; + + p = (FlatNode) nodes.get(mid); + + if (offset < p.offset) { + right = (left == mid) ? left : mid - 1; + } else if (offset > p.offset) { + left = (right == mid) ? right : mid + 1; + } else if (offset == p.offset) { + left = right = mid; + } + } + + int pos = left; + p = (FlatNode) nodes.get(pos); + if (offset > p.offset) { + // append to the end + pos++; + } else { + // entry will became the first of all entries with the same offset + do { + --pos; + if (pos < 0) { + break; + } + p = (FlatNode) nodes.get(pos); + } while (offset == p.offset); + ++pos; + } + + return pos; + } + + public boolean containsPosition(int offset, int length) { + int size = nodes.size(); + if (size == 0) { + return false; + } + + int index = computeFlatNodeIndex(offset); + if (index < size) { + FlatNode p = (FlatNode) nodes.get(index); + + while (p.offset == offset) { + if (p.length == length) { + return true; + } + + if (++index < size) { + p = (FlatNode) nodes.get(index); + } else { + break; + } + } + } + + return false; + } + + /** + * Helper method for tracking the minimal region containg all partition + * changes. If offset is smaller than the remembered offset, + * offset will from now on be remembered. If + * offset + length is greater than the remembered end offset, + * it will be remembered from now on. + * + * @param offset + * the offset + * @param length + * the length + */ + protected final void rememberRegion(int offset, int length) { + // remember start offset + if (regionStart == -1) { + regionStart = offset; + } else if (offset < regionStart) { + regionStart = offset; + } + + // remember end offset + int endOffset = offset + length; + + if (regionEnd == -1) { + regionEnd = endOffset; + } else if (endOffset > regionEnd) { + regionEnd = endOffset; + } + } + + /** + * Creates the minimal region containing all partition changes using the + * remembered offsets. + * + * @return the minimal region containing all the partition changes + */ + protected final IRegion createRegion() { + if (regionStart == -1 || regionEnd == -1) { + return null; + } + + return new Region(regionStart, regionEnd - regionStart); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/rules/InnerDocumentView.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/rules/InnerDocumentView.java index f1b0ce2..be8ed24 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/rules/InnerDocumentView.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/rules/InnerDocumentView.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: InnerDocumentView.java,v 1.2 2004-09-22 18:51:51 jsurfer Exp $ + * $Id: InnerDocumentView.java,v 1.3 2006-10-21 23:13:53 pombredanne Exp $ */ package net.sourceforge.phpeclipse.ui.text.rules; @@ -25,126 +25,128 @@ import org.eclipse.jface.text.ITextStore; * * @author Igor Malinin */ -public class InnerDocumentView extends AbstractDocument implements IDocumentView { - - /** - * Implements ITextStore based on IDocument. - */ - class TextStore implements ITextStore { - - /* - * @see ITextStore#set - */ - public void set(String txt) { - try { - parent.replace(range.offset, range.length, txt); - } catch (BadLocationException x) { - } - } - - /* - * @see ITextStore#replace - */ - public void replace(int offset, int length, String txt) { - try { - parent.replace(range.offset + offset, length, txt); - } catch (BadLocationException x) { - } - } - - /* - * @see ITextStore#getLength - */ - public int getLength() { - return range.length; - } - - /* - * @see ITextStore#get - */ - public String get(int offset, int length) { - try { - return parent.get(range.offset + offset, length); - } catch (BadLocationException x) { - } - - return null; - } - - /* - * @see ITextStore#get - */ - public char get(int offset) { - try { - return parent.getChar(range.offset + offset); - } catch (BadLocationException x) { - } - - return (char) 0; - } - } - - /** The parent document */ - IDocument parent; - - /** The section inside the parent document */ - ViewNode range; - - /** - * Constructs inner view to parent document. - * - * @param parent - * parent document - * @param range - */ - public InnerDocumentView(IDocument parent, ViewNode range) { - this.parent = parent; - this.range = range; - - setTextStore(new TextStore()); - setLineTracker(new DefaultLineTracker()); - getTracker().set(getStore().get(0, getLength())); - completeInitialization(); - } - - /* - * @see net.sourceforge.phpeclipse.text.rules.IDocumentView#getParentDocument() - */ - public IDocument getParentDocument() { - return parent; - } - - /* - * @see org.eclipse.jface.text.AbstractDocument#fireDocumentAboutToBeChanged(DocumentEvent) - */ - protected void fireDocumentAboutToBeChanged(DocumentEvent event) { - super.fireDocumentAboutToBeChanged(event); - } - - /* - * @see org.eclipse.jface.text.AbstractDocument#fireDocumentChanged(DocumentEvent) - */ - protected void fireDocumentChanged(DocumentEvent event) { - try { - // TODO: move to a better place - getTracker().replace(event.getOffset(), event.getLength(), event.getText()); - } catch (BadLocationException x) { - } - - super.fireDocumentChanged(event); - } - - /* - * @see net.sf.wdte.text.rules.IDocumentView#getParentOffset(int) - */ - public int getParentOffset(int localOffset) { - return localOffset + range.offset; - } - - /* - * @see net.sf.wdte.text.rules.IDocumentView#getLocalOffset(int) - */ - public int getLocalOffset(int parentOffset) { - return parentOffset - range.offset; - } +public class InnerDocumentView extends AbstractDocument implements + IDocumentView { + + /** + * Implements ITextStore based on IDocument. + */ + class TextStore implements ITextStore { + + /* + * @see ITextStore#set + */ + public void set(String txt) { + try { + parent.replace(range.offset, range.length, txt); + } catch (BadLocationException x) { + } + } + + /* + * @see ITextStore#replace + */ + public void replace(int offset, int length, String txt) { + try { + parent.replace(range.offset + offset, length, txt); + } catch (BadLocationException x) { + } + } + + /* + * @see ITextStore#getLength + */ + public int getLength() { + return range.length; + } + + /* + * @see ITextStore#get + */ + public String get(int offset, int length) { + try { + return parent.get(range.offset + offset, length); + } catch (BadLocationException x) { + } + + return null; + } + + /* + * @see ITextStore#get + */ + public char get(int offset) { + try { + return parent.getChar(range.offset + offset); + } catch (BadLocationException x) { + } + + return (char) 0; + } + } + + /** The parent document */ + IDocument parent; + + /** The section inside the parent document */ + ViewNode range; + + /** + * Constructs inner view to parent document. + * + * @param parent + * parent document + * @param range + */ + public InnerDocumentView(IDocument parent, ViewNode range) { + this.parent = parent; + this.range = range; + + setTextStore(new TextStore()); + setLineTracker(new DefaultLineTracker()); + getTracker().set(getStore().get(0, getLength())); + completeInitialization(); + } + + /* + * @see net.sourceforge.phpeclipse.text.rules.IDocumentView#getParentDocument() + */ + public IDocument getParentDocument() { + return parent; + } + + /* + * @see org.eclipse.jface.text.AbstractDocument#fireDocumentAboutToBeChanged(DocumentEvent) + */ + protected void fireDocumentAboutToBeChanged(DocumentEvent event) { + super.fireDocumentAboutToBeChanged(event); + } + + /* + * @see org.eclipse.jface.text.AbstractDocument#fireDocumentChanged(DocumentEvent) + */ + protected void fireDocumentChanged(DocumentEvent event) { + try { + // TODO: move to a better place + getTracker().replace(event.getOffset(), event.getLength(), + event.getText()); + } catch (BadLocationException x) { + } + + super.fireDocumentChanged(event); + } + + /* + * @see net.sf.wdte.text.rules.IDocumentView#getParentOffset(int) + */ + public int getParentOffset(int localOffset) { + return localOffset + range.offset; + } + + /* + * @see net.sf.wdte.text.rules.IDocumentView#getLocalOffset(int) + */ + public int getLocalOffset(int parentOffset) { + return parentOffset - range.offset; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/rules/MultiViewPartitioner.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/rules/MultiViewPartitioner.java index b33b381..c51a4aa 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/rules/MultiViewPartitioner.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/rules/MultiViewPartitioner.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: MultiViewPartitioner.java,v 1.9 2005-05-13 20:17:31 axelcl Exp $ + * $Id: MultiViewPartitioner.java,v 1.10 2006-10-21 23:13:53 pombredanne Exp $ */ package net.sourceforge.phpeclipse.ui.text.rules; @@ -29,723 +29,778 @@ import org.eclipse.jface.text.TypedRegion; import org.eclipse.jface.text.rules.IPartitionTokenScanner; /** - * Advanced partitioner which maintains partitions as views to connected document. Views have own partitioners themselves. This - * class is designed as a base for complex partitioners such as for JSP, PHP, ASP, etc. languages. + * Advanced partitioner which maintains partitions as views to connected + * document. Views have own partitioners themselves. This class is designed as a + * base for complex partitioners such as for JSP, PHP, ASP, etc. languages. * * @author Igor Malinin */ public abstract class MultiViewPartitioner extends AbstractPartitioner { - class ViewListener implements IDocumentPartitioningListener, IDocumentPartitioningListenerExtension { - - /* - * @see org.eclipse.jface.text.IDocumentPartitioningListener#documentPartitioningChanged(IDocument) - */ - public void documentPartitioningChanged(IDocument document) { - IDocumentView view = (IDocumentView) document; - - int start = view.getParentOffset(0); - int end = view.getParentOffset(view.getLength()); - - rememberRegion(start, end - start); - } - - /* - * @see org.eclipse.jface.text.IDocumentPartitioningListenerExtension#documentPartitioningChanged(IDocument, IRegion) - */ - public void documentPartitioningChanged(IDocument document, IRegion region) { - IDocumentView view = (IDocumentView) document; - - int offset = region.getOffset(); - - int start = view.getParentOffset(offset); - int end = view.getParentOffset(offset + region.getLength()); - - rememberRegion(start, end - start); - } - } - - private ViewListener viewListener = new ViewListener(); - - private OuterDocumentView outerDocument; - - private DocumentEvent outerDocumentEvent; - - public MultiViewPartitioner(IPartitionTokenScanner scanner) { - super(scanner); - } - - public void setOuterPartitioner(IDocumentPartitioner partitioner) { - if (outerDocument == null) { - if (partitioner == null) { - return; - } - - outerDocument = new OuterDocumentView(document, nodes); - outerDocument.addDocumentPartitioningListener(viewListener); - } - - IDocumentPartitioner old = outerDocument.getDocumentPartitioner(); - if (old != null) { - outerDocument.setDocumentPartitioner(null); - old.disconnect(); - } - - if (partitioner != null) { - partitioner.connect(outerDocument); - } - - outerDocument.setDocumentPartitioner(partitioner); - - if (partitioner == null) { - outerDocument.removeDocumentPartitioningListener(viewListener); - outerDocument = null; - } - } - - /** - * Create subpartitioner. - * - * @param contentType - * name of inner partition or null for outer partition - */ - protected abstract IDocumentPartitioner createPartitioner(String contentType); - - protected void addInnerRegion(FlatNode position) { - if (outerDocument != null) { - if (DEBUG) { - Assert.isTrue(position.offset >= 0, Integer.toString(position.offset)); - } - int outerOffset = outerDocument.getLocalOffset(position.offset); - // axelcl start - DocumentEvent event = null; - if (outerOffset >= 0) { - // axelcl end - event = new DocumentEvent(outerDocument, outerOffset, position.length, null); - - outerDocument.fireDocumentAboutToBeChanged(event); - } - super.addInnerRegion(position); - // axelcl start - if (event != null) { - // axelcl end - outerDocument.fireDocumentChanged(event); - } - } else { - super.addInnerRegion(position); - } - - if (position instanceof ViewNode) { - // TODO: revisit condition - IDocumentPartitioner partitioner = createPartitioner(position.type); - if (partitioner != null) { - InnerDocumentView innerDocument = new InnerDocumentView(document, (ViewNode) position); - - ((ViewNode) position).view = innerDocument; - - partitioner.connect(innerDocument); - innerDocument.setDocumentPartitioner(partitioner); - innerDocument.addDocumentPartitioningListener(viewListener); - } - } - } - - protected void removeInnerRegion(FlatNode position) { - try { - if (outerDocument != null) { - DocumentEvent event = null; - if (position.offset >= 0 && position.length >= 0) { - int outerOffset = outerDocument.getLocalOffset(position.offset); - if (outerOffset > 0) { - event = new DocumentEvent(outerDocument, outerOffset, 0, document.get(position.offset, position.length)); - - outerDocument.fireDocumentAboutToBeChanged(event); - } - } - super.removeInnerRegion(position); - if (position.offset >= 0) { - if (event != null) { - outerDocument.fireDocumentChanged(event); - } - } - } else { - super.removeInnerRegion(position); - } - - if (position instanceof ViewNode) { - // TODO: revisit condition - InnerDocumentView innerDocument = ((ViewNode) position).view; - if (innerDocument != null) { - IDocumentPartitioner partitioner = innerDocument.getDocumentPartitioner(); - - innerDocument.removeDocumentPartitioningListener(viewListener); - innerDocument.setDocumentPartitioner(null); - partitioner.disconnect(); - } - } - } catch (BadLocationException e) { - } - } - - protected void deleteInnerRegion(FlatNode position) { - super.deleteInnerRegion(position); - - if (position instanceof ViewNode) { - // TODO: revisit condition - InnerDocumentView innerDocument = ((ViewNode) position).view; - if (innerDocument != null) { - IDocumentPartitioner partitioner = innerDocument.getDocumentPartitioner(); - - innerDocument.removeDocumentPartitioningListener(viewListener); - innerDocument.setDocumentPartitioner(null); - partitioner.disconnect(); - } - } - } - - public void connect(IDocument document) { - // outerDocument = new OuterDocumentView(document, innerPositions); - - super.connect(document); - - setOuterPartitioner(createPartitioner(null)); - // IDocumentPartitioner partitioner = - // partitioner.connect(outerDocument); - // outerDocument.setDocumentPartitioner(partitioner); - // outerDocument.addDocumentPartitioningListener(viewListener); - } - - public void disconnect() { - try { - if (outerDocument != null) { - outerDocument.removeDocumentPartitioningListener(viewListener); - - IDocumentPartitioner partitioner = outerDocument.getDocumentPartitioner(); - - outerDocument.setDocumentPartitioner(null); - partitioner.disconnect(); - } - } finally { - // TODO: cleanup listeners - outerDocument = null; - } - } - - /* - * @see org.eclipse.jface.text.IDocumentPartitioner#documentAboutToBeChanged(DocumentEvent) - */ - public void documentAboutToBeChanged(DocumentEvent event) { - super.documentAboutToBeChanged(event); - - outerDocumentEvent = null; - - int offset = event.getOffset(); - int length = event.getLength(); - int end = offset + length; - - // find left partition - int first = computeFlatNodeIndex(offset); - if (first > 0) { - FlatNode p = (FlatNode) nodes.get(first - 1); - - int right = p.offset + p.length; - if (offset < right) { - // change overlaps with partition - InnerDocumentView innerDocument = null; - if (p instanceof ViewNode) { - // TODO: revisit condition - innerDocument = ((ViewNode) p).view; - } - - if (end < right) { - if (innerDocument != null) { - // cahnge completely inside partition - int start = innerDocument.getLocalOffset(offset); - innerDocument.fireDocumentAboutToBeChanged(new DocumentEvent(innerDocument, start, length, event.getText())); - } - - return; - } - - if (innerDocument != null) { - // cut partition at right - int start = innerDocument.getLocalOffset(offset); - innerDocument.fireDocumentAboutToBeChanged(new DocumentEvent(innerDocument, start, innerDocument.getLength() - start, - null)); - } - } - } - - // find right partition - int last = computeFlatNodeIndex(end); - if (last > 0) { - FlatNode p = (FlatNode) nodes.get(last - 1); - - if (p instanceof ViewNode) { - // TODO: revisit condition - InnerDocumentView innerDocument = ((ViewNode) p).view; - if (innerDocument != null) { - int right = p.offset + p.length; - if (end < right) { - // cut partition at left - int cut = innerDocument.getLocalOffset(end); - innerDocument.fireDocumentAboutToBeChanged(new DocumentEvent(innerDocument, 0, cut, null)); - } - } - } - } - - if (outerDocument != null) { - int left = outerDocument.getLocalOffset(offset); - int right = outerDocument.getLocalOffset(end); - - String text = event.getText(); - - if (left >= 0 && (right - left >= 0)) { - if (left != right || text != null && text.length() > 0) { - outerDocumentEvent = new DocumentEvent(outerDocument, left, right - left, text); - - outerDocument.fireDocumentAboutToBeChanged(outerDocumentEvent); - } - } - } - } - - protected int fixupPartitions(DocumentEvent event) { - int offset = event.getOffset(); - int length = event.getLength(); - int end = offset + length; - - // fixup/notify inner views laying on change boundaries - - int first = computeFlatNodeIndex(offset); - if (first > 0) { - FlatNode p = (FlatNode) nodes.get(first - 1); - - int right = p.offset + p.length; - if (offset < right) { - // change overlaps with partition - if (end < right) { - // cahnge completely inside partition - String text = event.getText(); - p.length -= length; - if (text != null) { - p.length += text.length(); - } - - if (p instanceof ViewNode) { - // TODO: revisit condition - InnerDocumentView innerDocument = ((ViewNode) p).view; - if (innerDocument != null) { - int start = innerDocument.getLocalOffset(offset); - innerDocument.fireDocumentChanged(new DocumentEvent(innerDocument, start, length, text)); - } - } - } else { - // cut partition at right - int cut = p.offset + p.length - offset; - p.length -= cut; - - if (p instanceof ViewNode) { - // TODO: revisit condition - InnerDocumentView innerDocument = ((ViewNode) p).view; - if (innerDocument != null) { - int start = innerDocument.getLocalOffset(offset); - // TODO: ???fireDocumentAboutToBeChanged??? - innerDocument.fireDocumentChanged(new DocumentEvent(innerDocument, start, cut, null)); - } - } - } - } - } - - int last = computeFlatNodeIndex(end); - if (last > 0 && first != last) { - FlatNode p = (FlatNode) nodes.get(last - 1); - - int right = p.offset + p.length; - if (end < right) { - // cut partition at left - int cut = end - p.offset; - p.length -= cut; - p.offset = offset; - - String text = event.getText(); - if (text != null) { - p.offset += text.length(); - } - - if (p instanceof ViewNode) { - // TODO: revisit condition - InnerDocumentView innerDocument = ((ViewNode) p).view; - if (innerDocument != null) { - // TODO: ???fireDocumentAboutToBeChanged??? - innerDocument.fireDocumentChanged(new DocumentEvent(innerDocument, 0, cut, null)); - } - } - - --last; - } - } - - // fixup inner views laying afrer change - - String text = event.getText(); - if (text != null) { - length -= text.length(); - } - - for (int i = last, size = nodes.size(); i < size; i++) { - ((FlatNode) nodes.get(i)).offset -= length; - } - - // delete inner views laying completely inside change boundaries - - if (first < last) { - do { - deleteInnerRegion((FlatNode) nodes.get(--last)); - } while (first < last); - - rememberRegion(offset, 0); - } - - // notify outer view - - if (outerDocumentEvent != null) { - outerDocument.fireDocumentChanged(outerDocumentEvent); - } - - return first; - } - - /* - * @see org.eclipse.jface.text.IDocumentPartitioner#computePartitioning(int, int) - */ - protected String getContentType(String parent, String view) { - if (view != null) { - return view; - } - - if (parent != null) { - return parent; - } - - return IDocument.DEFAULT_CONTENT_TYPE; - } - - /* - * @see org.eclipse.jface.text.IDocumentPartitioner#computePartitioning(int, int) - */ - public ITypedRegion[] computePartitioning(int offset, int length) { - List list = new ArrayList(); -// if (DEBUG) { -// if (length>=9400) { -// length--; -// } -// System.out.print("MultiViewPartitioner::computePartitioning - Offset: "); -// System.out.print(offset); -// System.out.print(", Length: "); -// System.out.print(length); -// System.out.println(""); -// } - int end = offset + length; - - int index = computeFlatNodeIndex(offset); - while (true) { - FlatNode prev = (index > 0) ? (FlatNode) nodes.get(index - 1) : null; - - if (prev != null) { - if (prev.overlapsWith(offset, length)) { - addInnerPartitions(list, offset, length, prev); - } - - if (end <= prev.offset + prev.length) { - break; - } - } - - FlatNode next = (index < nodes.size()) ? (FlatNode) nodes.get(index) : null; - - if (next == null || offset < next.offset) { - addOuterPartitions(list, offset, length, prev, next); - } - - if (next == null) { - break; - } - - ++index; - } - // if (DEBUG) { - // showList(list); - // } - - return (TypedRegion[]) list.toArray(new TypedRegion[list.size()]); - } - - private void showList(List list) { - try { - throw new NullPointerException(); - } catch (Exception e) { - e.printStackTrace(); - } - System.out.println(">>>>>List start"); - TypedRegion temp; - for (int i = 0; i < list.size(); i++) { - temp = (TypedRegion) list.get(i); - System.out.print("Offset: "); - System.out.print(temp.getOffset()); - System.out.print(", Length: "); - System.out.print(temp.getLength()); - System.out.print(", Type: "); - System.out.print(temp.getType()); - System.out.println(""); - } - System.out.println("<<<<= 0) { - ITypedRegion[] regions = null; - try { - regions = outerDocument.computePartitioning(start, len); - } catch (Exception e) { - // nasty workaround, which prevents cursor from moveing backwards in the editor - // but doesn't solve the partitioning problem - regions = new ITypedRegion[0]; - System.out.println("MultiViewerPartitioner#addOuterPartitions failure\n"+"start:"+start +" length:" +len+"\n"+outerDocument.get(start,len)); - } - for (int i = 0; i < regions.length; i++) { - ITypedRegion region = regions[i]; - - // convert back to parent offsets - start = outerDocument.getParentOffset(region.getOffset()); - end = start + region.getLength(); - - if (prev != null) { - offset = prev.offset + prev.length; - if (start < offset) { - start = offset; - } - } - - if (next != null) { - offset = next.offset; - if (offset < end) { - end = offset; - } - } - // if (DEBUG) { - // if (end - start<0) { - // showList(list); - // System.out.print("MultiViewPartitioner::addOuterPartitions - Offset: "); - // System.out.print(offset); - // System.out.print(", Start: "); - // System.out.print(start); - // System.out.print(", End: "); - // System.out.print(end); - // System.out.print(", Type: "); - // System.out.print(region.getType()); - // System.out.println(""); - // throw new IndexOutOfBoundsException(); - // } - // } - list.add(new TypedRegion(start, end - start, getContentType(null, region.getType()))); - } - } - } catch (BadLocationException x) { - } - } - - private void addInnerPartitions(List list, int offset, int length, FlatNode position) { - InnerDocumentView innerDocument = null; - if (position instanceof ViewNode) { - // TODO: revisit condition - innerDocument = ((ViewNode) position).view; - } - - if (innerDocument == null) { - // simple partition - // if (DEBUG) { - // if (position.length<0) { - // throw new IndexOutOfBoundsException(); - // } - // } - list.add(new TypedRegion(position.offset, position.length, getContentType(position.type, null))); - return; - } - - // multiplexing to inner view - try { - // limit region - int start = Math.max(offset, position.offset); - int end = Math.min(offset + length, position.offset + position.length); - - // convert to document offsets - length = end - start; - offset = innerDocument.getLocalOffset(start); - - ITypedRegion[] regions = innerDocument.computePartitioning(offset, length); - - for (int i = 0; i < regions.length; i++) { - ITypedRegion region = regions[i]; - - // convert back to parent offsets - offset = innerDocument.getParentOffset(region.getOffset()); - length = region.getLength(); - // if (DEBUG) { - // if (length<0) { - // throw new IndexOutOfBoundsException(); - // } - // } - list.add(new TypedRegion(offset, length, getContentType(position.type, region.getType()))); - } - } catch (BadLocationException x) { - } - } - - /* - * @see org.eclipse.jface.text.IDocumentPartitioner#getPartition(int) - */ - public ITypedRegion getPartition(int offset) { - if (nodes.size() == 0) { - return getOuterPartition(offset, null, null); - } - - int index = computeFlatNodeIndex(offset); - if (index < nodes.size()) { - FlatNode next = (FlatNode) nodes.get(index); - - if (offset == next.offset) { - return getInnerPartition(offset, next); - } - - if (index == 0) { - return getOuterPartition(offset, null, next); - } - - FlatNode prev = (FlatNode) nodes.get(index - 1); - - if (prev.includes(offset)) { - return getInnerPartition(offset, prev); - } - - return getOuterPartition(offset, prev, next); - } - - FlatNode prev = (FlatNode) nodes.get(nodes.size() - 1); - - if (prev.includes(offset)) { - return getInnerPartition(offset, prev); - } - - return getOuterPartition(offset, prev, null); - } - - protected ITypedRegion getOuterPartition(int offset, FlatNode prev, FlatNode next) { - try { - int start, end; - String type; - - if (outerDocument == null) { - start = 0; - end = document.getLength(); - type = getContentType(null, IDocument.DEFAULT_CONTENT_TYPE); - } else { - int outerOffset = outerDocument.getLocalOffset(offset); - //axelcl start - if (outerOffset < 0) { - start = 0; - end = document.getLength(); - type = getContentType(null, IDocument.DEFAULT_CONTENT_TYPE); - } else { - // axelcl end - ITypedRegion region = outerDocument.getPartition(outerOffset); - - start = region.getOffset(); - end = start + region.getLength(); - - // convert to parent offset - start = outerDocument.getParentOffset(start); - end = outerDocument.getParentOffset(end); - - type = getContentType(null, region.getType()); - } - } - - if (prev != null) { - offset = prev.offset + prev.length; - if (start < offset) { - start = offset; - } - } - - if (next != null) { - offset = next.offset; - if (offset < end) { - end = offset; - } - } - - return new TypedRegion(start, end - start, type); - } catch (BadLocationException x) { - x.printStackTrace(); - throw new IllegalArgumentException(); - } - } - - protected ITypedRegion getInnerPartition(int offset, FlatNode position) { - if (position instanceof ViewNode) { - // TODO: revisit condition - InnerDocumentView innerDocument = ((ViewNode) position).view; - - if (innerDocument != null) { - // multiplexing to inner view - try { - // convert to inner offset - ITypedRegion region = innerDocument.getPartition(innerDocument.getLocalOffset(offset)); - - // convert to parent offset - offset = innerDocument.getParentOffset(region.getOffset()); - - return new TypedRegion(offset, region.getLength(), getContentType(position.type, region.getType())); - } catch (BadLocationException x) { - } - } - } - - // simple partition - return new TypedRegion(position.offset, position.length, position.type); - } + class ViewListener implements IDocumentPartitioningListener, + IDocumentPartitioningListenerExtension { + + /* + * @see org.eclipse.jface.text.IDocumentPartitioningListener#documentPartitioningChanged(IDocument) + */ + public void documentPartitioningChanged(IDocument document) { + IDocumentView view = (IDocumentView) document; + + int start = view.getParentOffset(0); + int end = view.getParentOffset(view.getLength()); + + rememberRegion(start, end - start); + } + + /* + * @see org.eclipse.jface.text.IDocumentPartitioningListenerExtension#documentPartitioningChanged(IDocument, + * IRegion) + */ + public void documentPartitioningChanged(IDocument document, + IRegion region) { + IDocumentView view = (IDocumentView) document; + + int offset = region.getOffset(); + + int start = view.getParentOffset(offset); + int end = view.getParentOffset(offset + region.getLength()); + + rememberRegion(start, end - start); + } + } + + private ViewListener viewListener = new ViewListener(); + + private OuterDocumentView outerDocument; + + private DocumentEvent outerDocumentEvent; + + public MultiViewPartitioner(IPartitionTokenScanner scanner) { + super(scanner); + } + + public void setOuterPartitioner(IDocumentPartitioner partitioner) { + if (outerDocument == null) { + if (partitioner == null) { + return; + } + + outerDocument = new OuterDocumentView(document, nodes); + outerDocument.addDocumentPartitioningListener(viewListener); + } + + IDocumentPartitioner old = outerDocument.getDocumentPartitioner(); + if (old != null) { + outerDocument.setDocumentPartitioner(null); + old.disconnect(); + } + + if (partitioner != null) { + partitioner.connect(outerDocument); + } + + outerDocument.setDocumentPartitioner(partitioner); + + if (partitioner == null) { + outerDocument.removeDocumentPartitioningListener(viewListener); + outerDocument = null; + } + } + + /** + * Create subpartitioner. + * + * @param contentType + * name of inner partition or null for outer + * partition + */ + protected abstract IDocumentPartitioner createPartitioner(String contentType); + + protected void addInnerRegion(FlatNode position) { + if (outerDocument != null) { + if (DEBUG) { + Assert.isTrue(position.offset >= 0, Integer + .toString(position.offset)); + } + int outerOffset = outerDocument.getLocalOffset(position.offset); + // axelcl start + DocumentEvent event = null; + if (outerOffset >= 0) { + // axelcl end + event = new DocumentEvent(outerDocument, outerOffset, + position.length, null); + + outerDocument.fireDocumentAboutToBeChanged(event); + } + super.addInnerRegion(position); + // axelcl start + if (event != null) { + // axelcl end + outerDocument.fireDocumentChanged(event); + } + } else { + super.addInnerRegion(position); + } + + if (position instanceof ViewNode) { + // TODO: revisit condition + IDocumentPartitioner partitioner = createPartitioner(position.type); + if (partitioner != null) { + InnerDocumentView innerDocument = new InnerDocumentView( + document, (ViewNode) position); + + ((ViewNode) position).view = innerDocument; + + partitioner.connect(innerDocument); + innerDocument.setDocumentPartitioner(partitioner); + innerDocument.addDocumentPartitioningListener(viewListener); + } + } + } + + protected void removeInnerRegion(FlatNode position) { + try { + if (outerDocument != null) { + DocumentEvent event = null; + if (position.offset >= 0 && position.length >= 0) { + int outerOffset = outerDocument + .getLocalOffset(position.offset); + if (outerOffset > 0) { + event = new DocumentEvent(outerDocument, outerOffset, + 0, document.get(position.offset, + position.length)); + + outerDocument.fireDocumentAboutToBeChanged(event); + } + } + super.removeInnerRegion(position); + if (position.offset >= 0) { + if (event != null) { + outerDocument.fireDocumentChanged(event); + } + } + } else { + super.removeInnerRegion(position); + } + + if (position instanceof ViewNode) { + // TODO: revisit condition + InnerDocumentView innerDocument = ((ViewNode) position).view; + if (innerDocument != null) { + IDocumentPartitioner partitioner = innerDocument + .getDocumentPartitioner(); + + innerDocument + .removeDocumentPartitioningListener(viewListener); + innerDocument.setDocumentPartitioner(null); + partitioner.disconnect(); + } + } + } catch (BadLocationException e) { + } + } + + protected void deleteInnerRegion(FlatNode position) { + super.deleteInnerRegion(position); + + if (position instanceof ViewNode) { + // TODO: revisit condition + InnerDocumentView innerDocument = ((ViewNode) position).view; + if (innerDocument != null) { + IDocumentPartitioner partitioner = innerDocument + .getDocumentPartitioner(); + + innerDocument.removeDocumentPartitioningListener(viewListener); + innerDocument.setDocumentPartitioner(null); + partitioner.disconnect(); + } + } + } + + public void connect(IDocument document) { + // outerDocument = new OuterDocumentView(document, innerPositions); + + super.connect(document); + + setOuterPartitioner(createPartitioner(null)); + // IDocumentPartitioner partitioner = + // partitioner.connect(outerDocument); + // outerDocument.setDocumentPartitioner(partitioner); + // outerDocument.addDocumentPartitioningListener(viewListener); + } + + public void disconnect() { + try { + if (outerDocument != null) { + outerDocument.removeDocumentPartitioningListener(viewListener); + + IDocumentPartitioner partitioner = outerDocument + .getDocumentPartitioner(); + + outerDocument.setDocumentPartitioner(null); + partitioner.disconnect(); + } + } finally { + // TODO: cleanup listeners + outerDocument = null; + } + } + + /* + * @see org.eclipse.jface.text.IDocumentPartitioner#documentAboutToBeChanged(DocumentEvent) + */ + public void documentAboutToBeChanged(DocumentEvent event) { + super.documentAboutToBeChanged(event); + + outerDocumentEvent = null; + + int offset = event.getOffset(); + int length = event.getLength(); + int end = offset + length; + + // find left partition + int first = computeFlatNodeIndex(offset); + if (first > 0) { + FlatNode p = (FlatNode) nodes.get(first - 1); + + int right = p.offset + p.length; + if (offset < right) { + // change overlaps with partition + InnerDocumentView innerDocument = null; + if (p instanceof ViewNode) { + // TODO: revisit condition + innerDocument = ((ViewNode) p).view; + } + + if (end < right) { + if (innerDocument != null) { + // cahnge completely inside partition + int start = innerDocument.getLocalOffset(offset); + innerDocument + .fireDocumentAboutToBeChanged(new DocumentEvent( + innerDocument, start, length, event + .getText())); + } + + return; + } + + if (innerDocument != null) { + // cut partition at right + int start = innerDocument.getLocalOffset(offset); + innerDocument + .fireDocumentAboutToBeChanged(new DocumentEvent( + innerDocument, start, innerDocument + .getLength() + - start, null)); + } + } + } + + // find right partition + int last = computeFlatNodeIndex(end); + if (last > 0) { + FlatNode p = (FlatNode) nodes.get(last - 1); + + if (p instanceof ViewNode) { + // TODO: revisit condition + InnerDocumentView innerDocument = ((ViewNode) p).view; + if (innerDocument != null) { + int right = p.offset + p.length; + if (end < right) { + // cut partition at left + int cut = innerDocument.getLocalOffset(end); + innerDocument + .fireDocumentAboutToBeChanged(new DocumentEvent( + innerDocument, 0, cut, null)); + } + } + } + } + + if (outerDocument != null) { + int left = outerDocument.getLocalOffset(offset); + int right = outerDocument.getLocalOffset(end); + + String text = event.getText(); + + if (left >= 0 && (right - left >= 0)) { + if (left != right || text != null && text.length() > 0) { + outerDocumentEvent = new DocumentEvent(outerDocument, left, + right - left, text); + + outerDocument + .fireDocumentAboutToBeChanged(outerDocumentEvent); + } + } + } + } + + protected int fixupPartitions(DocumentEvent event) { + int offset = event.getOffset(); + int length = event.getLength(); + int end = offset + length; + + // fixup/notify inner views laying on change boundaries + + int first = computeFlatNodeIndex(offset); + if (first > 0) { + FlatNode p = (FlatNode) nodes.get(first - 1); + + int right = p.offset + p.length; + if (offset < right) { + // change overlaps with partition + if (end < right) { + // cahnge completely inside partition + String text = event.getText(); + p.length -= length; + if (text != null) { + p.length += text.length(); + } + + if (p instanceof ViewNode) { + // TODO: revisit condition + InnerDocumentView innerDocument = ((ViewNode) p).view; + if (innerDocument != null) { + int start = innerDocument.getLocalOffset(offset); + innerDocument + .fireDocumentChanged(new DocumentEvent( + innerDocument, start, length, text)); + } + } + } else { + // cut partition at right + int cut = p.offset + p.length - offset; + p.length -= cut; + + if (p instanceof ViewNode) { + // TODO: revisit condition + InnerDocumentView innerDocument = ((ViewNode) p).view; + if (innerDocument != null) { + int start = innerDocument.getLocalOffset(offset); + // TODO: ???fireDocumentAboutToBeChanged??? + innerDocument + .fireDocumentChanged(new DocumentEvent( + innerDocument, start, cut, null)); + } + } + } + } + } + + int last = computeFlatNodeIndex(end); + if (last > 0 && first != last) { + FlatNode p = (FlatNode) nodes.get(last - 1); + + int right = p.offset + p.length; + if (end < right) { + // cut partition at left + int cut = end - p.offset; + p.length -= cut; + p.offset = offset; + + String text = event.getText(); + if (text != null) { + p.offset += text.length(); + } + + if (p instanceof ViewNode) { + // TODO: revisit condition + InnerDocumentView innerDocument = ((ViewNode) p).view; + if (innerDocument != null) { + // TODO: ???fireDocumentAboutToBeChanged??? + innerDocument.fireDocumentChanged(new DocumentEvent( + innerDocument, 0, cut, null)); + } + } + + --last; + } + } + + // fixup inner views laying afrer change + + String text = event.getText(); + if (text != null) { + length -= text.length(); + } + + for (int i = last, size = nodes.size(); i < size; i++) { + ((FlatNode) nodes.get(i)).offset -= length; + } + + // delete inner views laying completely inside change boundaries + + if (first < last) { + do { + deleteInnerRegion((FlatNode) nodes.get(--last)); + } while (first < last); + + rememberRegion(offset, 0); + } + + // notify outer view + + if (outerDocumentEvent != null) { + outerDocument.fireDocumentChanged(outerDocumentEvent); + } + + return first; + } + + /* + * @see org.eclipse.jface.text.IDocumentPartitioner#computePartitioning(int, + * int) + */ + protected String getContentType(String parent, String view) { + if (view != null) { + return view; + } + + if (parent != null) { + return parent; + } + + return IDocument.DEFAULT_CONTENT_TYPE; + } + + /* + * @see org.eclipse.jface.text.IDocumentPartitioner#computePartitioning(int, + * int) + */ + public ITypedRegion[] computePartitioning(int offset, int length) { + List list = new ArrayList(); + // if (DEBUG) { + // if (length>=9400) { + // length--; + // } + // System.out.print("MultiViewPartitioner::computePartitioning - Offset: + // "); + // System.out.print(offset); + // System.out.print(", Length: "); + // System.out.print(length); + // System.out.println(""); + // } + int end = offset + length; + + int index = computeFlatNodeIndex(offset); + while (true) { + FlatNode prev = (index > 0) ? (FlatNode) nodes.get(index - 1) + : null; + + if (prev != null) { + if (prev.overlapsWith(offset, length)) { + addInnerPartitions(list, offset, length, prev); + } + + if (end <= prev.offset + prev.length) { + break; + } + } + + FlatNode next = (index < nodes.size()) ? (FlatNode) nodes + .get(index) : null; + + if (next == null || offset < next.offset) { + addOuterPartitions(list, offset, length, prev, next); + } + + if (next == null) { + break; + } + + ++index; + } + // if (DEBUG) { + // showList(list); + // } + + return (TypedRegion[]) list.toArray(new TypedRegion[list.size()]); + } + + private void showList(List list) { + try { + throw new NullPointerException(); + } catch (Exception e) { + e.printStackTrace(); + } + System.out.println(">>>>>List start"); + TypedRegion temp; + for (int i = 0; i < list.size(); i++) { + temp = (TypedRegion) list.get(i); + System.out.print("Offset: "); + System.out.print(temp.getOffset()); + System.out.print(", Length: "); + System.out.print(temp.getLength()); + System.out.print(", Type: "); + System.out.print(temp.getType()); + System.out.println(""); + } + System.out.println("<<<<= 0) { + ITypedRegion[] regions = null; + try { + regions = outerDocument.computePartitioning(start, len); + } catch (Exception e) { + // nasty workaround, which prevents cursor from moveing + // backwards in the editor + // but doesn't solve the partitioning problem + regions = new ITypedRegion[0]; + System.out + .println("MultiViewerPartitioner#addOuterPartitions failure\n" + + "start:" + + start + + " length:" + + len + + "\n" + outerDocument.get(start, len)); + } + for (int i = 0; i < regions.length; i++) { + ITypedRegion region = regions[i]; + + // convert back to parent offsets + start = outerDocument.getParentOffset(region.getOffset()); + end = start + region.getLength(); + + if (prev != null) { + offset = prev.offset + prev.length; + if (start < offset) { + start = offset; + } + } + + if (next != null) { + offset = next.offset; + if (offset < end) { + end = offset; + } + } + // if (DEBUG) { + // if (end - start<0) { + // showList(list); + // System.out.print("MultiViewPartitioner::addOuterPartitions + // - Offset: "); + // System.out.print(offset); + // System.out.print(", Start: "); + // System.out.print(start); + // System.out.print(", End: "); + // System.out.print(end); + // System.out.print(", Type: "); + // System.out.print(region.getType()); + // System.out.println(""); + // throw new IndexOutOfBoundsException(); + // } + // } + list.add(new TypedRegion(start, end - start, + getContentType(null, region.getType()))); + } + } + } catch (BadLocationException x) { + } + } + + private void addInnerPartitions(List list, int offset, int length, + FlatNode position) { + InnerDocumentView innerDocument = null; + if (position instanceof ViewNode) { + // TODO: revisit condition + innerDocument = ((ViewNode) position).view; + } + + if (innerDocument == null) { + // simple partition + // if (DEBUG) { + // if (position.length<0) { + // throw new IndexOutOfBoundsException(); + // } + // } + list.add(new TypedRegion(position.offset, position.length, + getContentType(position.type, null))); + return; + } + + // multiplexing to inner view + try { + // limit region + int start = Math.max(offset, position.offset); + int end = Math.min(offset + length, position.offset + + position.length); + + // convert to document offsets + length = end - start; + offset = innerDocument.getLocalOffset(start); + + ITypedRegion[] regions = innerDocument.computePartitioning(offset, + length); + + for (int i = 0; i < regions.length; i++) { + ITypedRegion region = regions[i]; + + // convert back to parent offsets + offset = innerDocument.getParentOffset(region.getOffset()); + length = region.getLength(); + // if (DEBUG) { + // if (length<0) { + // throw new IndexOutOfBoundsException(); + // } + // } + list.add(new TypedRegion(offset, length, getContentType( + position.type, region.getType()))); + } + } catch (BadLocationException x) { + } + } + + /* + * @see org.eclipse.jface.text.IDocumentPartitioner#getPartition(int) + */ + public ITypedRegion getPartition(int offset) { + if (nodes.size() == 0) { + return getOuterPartition(offset, null, null); + } + + int index = computeFlatNodeIndex(offset); + if (index < nodes.size()) { + FlatNode next = (FlatNode) nodes.get(index); + + if (offset == next.offset) { + return getInnerPartition(offset, next); + } + + if (index == 0) { + return getOuterPartition(offset, null, next); + } + + FlatNode prev = (FlatNode) nodes.get(index - 1); + + if (prev.includes(offset)) { + return getInnerPartition(offset, prev); + } + + return getOuterPartition(offset, prev, next); + } + + FlatNode prev = (FlatNode) nodes.get(nodes.size() - 1); + + if (prev.includes(offset)) { + return getInnerPartition(offset, prev); + } + + return getOuterPartition(offset, prev, null); + } + + protected ITypedRegion getOuterPartition(int offset, FlatNode prev, + FlatNode next) { + try { + int start, end; + String type; + + if (outerDocument == null) { + start = 0; + end = document.getLength(); + type = getContentType(null, IDocument.DEFAULT_CONTENT_TYPE); + } else { + int outerOffset = outerDocument.getLocalOffset(offset); + // axelcl start + if (outerOffset < 0) { + start = 0; + end = document.getLength(); + type = getContentType(null, IDocument.DEFAULT_CONTENT_TYPE); + } else { + // axelcl end + ITypedRegion region = outerDocument + .getPartition(outerOffset); + + start = region.getOffset(); + end = start + region.getLength(); + + // convert to parent offset + start = outerDocument.getParentOffset(start); + end = outerDocument.getParentOffset(end); + + type = getContentType(null, region.getType()); + } + } + + if (prev != null) { + offset = prev.offset + prev.length; + if (start < offset) { + start = offset; + } + } + + if (next != null) { + offset = next.offset; + if (offset < end) { + end = offset; + } + } + + return new TypedRegion(start, end - start, type); + } catch (BadLocationException x) { + x.printStackTrace(); + throw new IllegalArgumentException(); + } + } + + protected ITypedRegion getInnerPartition(int offset, FlatNode position) { + if (position instanceof ViewNode) { + // TODO: revisit condition + InnerDocumentView innerDocument = ((ViewNode) position).view; + + if (innerDocument != null) { + // multiplexing to inner view + try { + // convert to inner offset + ITypedRegion region = innerDocument + .getPartition(innerDocument.getLocalOffset(offset)); + + // convert to parent offset + offset = innerDocument.getParentOffset(region.getOffset()); + + return new TypedRegion(offset, region.getLength(), + getContentType(position.type, region.getType())); + } catch (BadLocationException x) { + } + } + } + + // simple partition + return new TypedRegion(position.offset, position.length, position.type); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/rules/OuterDocumentView.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/rules/OuterDocumentView.java index d68b599..efb1284 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/rules/OuterDocumentView.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/rules/OuterDocumentView.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: OuterDocumentView.java,v 1.4 2004-11-12 20:15:58 axelcl Exp $ + * $Id: OuterDocumentView.java,v 1.5 2006-10-21 23:13:53 pombredanne Exp $ */ package net.sourceforge.phpeclipse.ui.text.rules; @@ -149,52 +149,52 @@ public class OuterDocumentView extends AbstractDocument implements setTextStore(new TextStore()); setLineTracker(new DefaultLineTracker()); int length = getLength(); - if (length<0) { - length = 0; + if (length < 0) { + length = 0; } getTracker().set(getStore().get(0, length)); - + completeInitialization(); } -// public void addRange(Position range) { -// DocumentEvent event = new DocumentEvent(this, -// getLocalOffset(range.offset), range.length, ""); -// fireDocumentAboutToBeChanged(event); -// ranges.add(-getIndex(range) - 1, range); -// fireDocumentChanged(event); -// } -// -// public void removeRange(Position range) { -// String text; -// try { -// text = parent.get(range.offset, range.length); -// } catch (BadLocationException e) { -// return; -// } -// DocumentEvent event = new DocumentEvent(this, -// getLocalOffset(range.offset), 0, text); -// fireDocumentAboutToBeChanged(event); -// deleteRange(range); -// fireDocumentChanged(event); -// } -// -// public void deleteRange(Position range) { -// ranges.remove(getIndex(range)); -// } -// -// private int getIndex(Position range) { -// return Collections.binarySearch(ranges, range, new Comparator() { -// public int compare(Object o1, Object o2) { -// int offset1 = ((Position) o1).offset; -// int offset2 = ((Position) o2).offset; -// -// if (offset1 < offset2) return -1; -// if (offset1 > offset2) return 1; -// return 0; -// } -// }); -// } + // public void addRange(Position range) { + // DocumentEvent event = new DocumentEvent(this, + // getLocalOffset(range.offset), range.length, ""); + // fireDocumentAboutToBeChanged(event); + // ranges.add(-getIndex(range) - 1, range); + // fireDocumentChanged(event); + // } + // + // public void removeRange(Position range) { + // String text; + // try { + // text = parent.get(range.offset, range.length); + // } catch (BadLocationException e) { + // return; + // } + // DocumentEvent event = new DocumentEvent(this, + // getLocalOffset(range.offset), 0, text); + // fireDocumentAboutToBeChanged(event); + // deleteRange(range); + // fireDocumentChanged(event); + // } + // + // public void deleteRange(Position range) { + // ranges.remove(getIndex(range)); + // } + // + // private int getIndex(Position range) { + // return Collections.binarySearch(ranges, range, new Comparator() { + // public int compare(Object o1, Object o2) { + // int offset1 = ((Position) o1).offset; + // int offset2 = ((Position) o2).offset; + // + // if (offset1 < offset2) return -1; + // if (offset1 > offset2) return 1; + // return 0; + // } + // }); + // } /* * @see org.eclipse.jface.text.AbstractDocument#fireDocumentAboutToBeChanged(DocumentEvent) @@ -212,7 +212,7 @@ public class OuterDocumentView extends AbstractDocument implements getTracker().replace(event.getOffset(), event.getLength(), event.getText()); } catch (IndexOutOfBoundsException x) { - + } catch (BadLocationException x) { } @@ -250,7 +250,7 @@ public class OuterDocumentView extends AbstractDocument implements * @see net.sf.wdte.text.rules.IDocumentView#getLocalOffset(int) */ public int getLocalOffset(int parentOffset) { -// Assert.isTrue(parentOffset>=0); + // Assert.isTrue(parentOffset>=0); int localOffset = parentOffset; Iterator i = ranges.iterator(); @@ -269,12 +269,12 @@ public class OuterDocumentView extends AbstractDocument implements localOffset -= range.length; } // TODO jsurfer change start - check this - if (localOffset<0) { - return 0; - } else if (localOffset>getLength()) { - return getLength(); - } - // jsurfer change end + if (localOffset < 0) { + return 0; + } else if (localOffset > getLength()) { + return getLength(); + } + // jsurfer change end return localOffset; } } diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/rules/ViewNode.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/rules/ViewNode.java index 2b37763..ea79491 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/rules/ViewNode.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/rules/ViewNode.java @@ -8,13 +8,13 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: ViewNode.java,v 1.2 2005-06-14 05:04:09 axelcl Exp $ + * $Id: ViewNode.java,v 1.3 2006-10-21 23:13:53 pombredanne Exp $ */ package net.sourceforge.phpeclipse.ui.text.rules; /** - * @author Igor Malinin + * @author Igor Malinin */ public class ViewNode extends FlatNode { diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/source/DefaultSourceViewerConfiguration.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/source/DefaultSourceViewerConfiguration.java index 7e7309b..efbb61e 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/source/DefaultSourceViewerConfiguration.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/text/source/DefaultSourceViewerConfiguration.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: DefaultSourceViewerConfiguration.java,v 1.1 2004-09-02 18:26:32 jsurfer Exp $ + * $Id: DefaultSourceViewerConfiguration.java,v 1.2 2006-10-21 23:13:54 pombredanne Exp $ */ package net.sourceforge.phpeclipse.ui.text.source; @@ -23,12 +23,10 @@ import org.eclipse.jface.text.source.SourceViewerConfiguration; public class DefaultSourceViewerConfiguration extends SourceViewerConfiguration { /** Preference key used to look up display tab width. */ - public static final String PREFERENCE_TAB_WIDTH = - "net.sourceforge.phpeclipse.ui.editor.tabWidth"; //$NON-NLS-1$ + public static final String PREFERENCE_TAB_WIDTH = "net.sourceforge.phpeclipse.ui.editor.tabWidth"; //$NON-NLS-1$ /** Preference key for inserting spaces rather than tabs. */ - public static final String PREFERENCE_SPACES_FOR_TABS = - "net.sourceforge.phpeclipse.ui.editor.spacesForTabs"; //$NON-NLS-1$ + public static final String PREFERENCE_SPACES_FOR_TABS = "net.sourceforge.phpeclipse.ui.editor.spacesForTabs"; //$NON-NLS-1$ private IPreferenceStore store; diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/views/outline/ModelBasedOutlinePage.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/views/outline/ModelBasedOutlinePage.java index 8f9fda4..4a4709e 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/views/outline/ModelBasedOutlinePage.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/views/outline/ModelBasedOutlinePage.java @@ -8,7 +8,7 @@ * Contributors: * Christopher Lenz - initial implementation * - * $Id: ModelBasedOutlinePage.java,v 1.1 2004-09-02 18:26:28 jsurfer Exp $ + * $Id: ModelBasedOutlinePage.java,v 1.2 2006-10-21 23:13:54 pombredanne Exp $ */ package net.sourceforge.phpeclipse.ui.views.outline; @@ -40,8 +40,8 @@ import org.eclipse.ui.views.contentoutline.ContentOutlinePage; /** * */ -public class ModelBasedOutlinePage extends ContentOutlinePage - implements IUpdate { +public class ModelBasedOutlinePage extends ContentOutlinePage implements + IUpdate { // Inner Classes ----------------------------------------------------------- @@ -81,41 +81,42 @@ public class ModelBasedOutlinePage extends ContentOutlinePage return model.getElements(); } - /* + /* * @see org.eclipse.jface.viewers.IContentProvider#dispose() */ public void dispose() { } /* - * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(Viewer, Object, Object) + * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(Viewer, + * Object, Object) */ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { if (oldInput != newInput) { if (newInput instanceof ISourceModel) { model = (ISourceModel) newInput; - } + } } } } /** - * This action toggles whether this outline page links its selection - * to the active editor. + * This action toggles whether this outline page links its selection to the + * active editor. */ private class ToggleLinkingAction extends ResourceAction { - + /** * Constructs a new action. */ public ToggleLinkingAction() { super(WebUIMessages.getResourceBundle(), - "OutlinePage.linkWithEditor."); //$NON-NLS-1$ + "OutlinePage.linkWithEditor."); //$NON-NLS-1$ if ((preferenceStore != null) - && (linkWithEditorPreferenceKey != null)) { - boolean checked = preferenceStore.getBoolean( - linkWithEditorPreferenceKey); + && (linkWithEditorPreferenceKey != null)) { + boolean checked = preferenceStore + .getBoolean(linkWithEditorPreferenceKey); valueChanged(checked, false); } else { setEnabled(false); @@ -127,31 +128,32 @@ public class ModelBasedOutlinePage extends ContentOutlinePage */ public void run() { if ((preferenceStore != null) - && (linkWithEditorPreferenceKey != null)) { + && (linkWithEditorPreferenceKey != null)) { valueChanged(isChecked(), true); } } - + // Private Methods ----------------------------------------------------- /** * Updates whether the outline page is linked to the active editor. * - * @param checked Whether linking is enabled - * @param store Whether the new state should be written back as a - * preference + * @param checked + * Whether linking is enabled + * @param store + * Whether the new state should be written back as a + * preference */ private void valueChanged(final boolean checked, boolean store) { setChecked(checked); BusyIndicator.showWhile(getTreeViewer().getControl().getDisplay(), - new Runnable() { - public void run() { - editor.synchronizeOutlinePage(); - } - }); + new Runnable() { + public void run() { + editor.synchronizeOutlinePage(); + } + }); if (store) { - preferenceStore.setValue( - linkWithEditorPreferenceKey, checked); + preferenceStore.setValue(linkWithEditorPreferenceKey, checked); } } @@ -185,7 +187,8 @@ public class ModelBasedOutlinePage extends ContentOutlinePage /** * Constructor. * - * @param editor The associated structured text editor + * @param editor + * The associated structured text editor */ public ModelBasedOutlinePage(StructuredTextEditor editor) { this.editor = editor; @@ -214,10 +217,11 @@ public class ModelBasedOutlinePage extends ContentOutlinePage } /* - * @see org.eclipse.ui.part.Page#makeContributions(IMenuManager, IToolBarManager, IStatusLineManager) + * @see org.eclipse.ui.part.Page#makeContributions(IMenuManager, + * IToolBarManager, IStatusLineManager) */ public void makeContributions(IMenuManager menuManager, - IToolBarManager toolBarManager, IStatusLineManager statusLineManager) { + IToolBarManager toolBarManager, IStatusLineManager statusLineManager) { if (toolBarManager != null) { toolBarManager.add(new ToggleLinkingAction()); } @@ -250,15 +254,15 @@ public class ModelBasedOutlinePage extends ContentOutlinePage /** * Selects a specific element in the outline page. * - * @param element the element to select + * @param element + * the element to select */ public void select(ISourceReference element) { TreeViewer viewer = getTreeViewer(); if (viewer != null) { ISelection selection = viewer.getSelection(); if (selection instanceof IStructuredSelection) { - IStructuredSelection structuredSelection = - (IStructuredSelection) selection; + IStructuredSelection structuredSelection = (IStructuredSelection) selection; List elements = structuredSelection.toList(); if (!elements.contains(element)) { if (element == null) { diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/views/outline/ProblemsLabelDecorator.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/views/outline/ProblemsLabelDecorator.java index 60b2fd1..598ce41 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/views/outline/ProblemsLabelDecorator.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/views/outline/ProblemsLabelDecorator.java @@ -8,7 +8,7 @@ * Contributors: * Christopher Lenz - initial implementation * - * $Id: ProblemsLabelDecorator.java,v 1.2 2005-03-06 21:09:52 axelcl Exp $ + * $Id: ProblemsLabelDecorator.java,v 1.3 2006-10-21 23:13:54 pombredanne Exp $ */ package net.sourceforge.phpeclipse.ui.views.outline; @@ -35,140 +35,152 @@ import org.eclipse.ui.IEditorInput; import org.eclipse.ui.texteditor.ITextEditor; /** - * Label decorator for the outline page that adds error and warning overlay icons to elements in the outline. The information is - * retrieved from the annotation model corresponding to the input of the associated text editor. + * Label decorator for the outline page that adds error and warning overlay + * icons to elements in the outline. The information is retrieved from the + * annotation model corresponding to the input of the associated text editor. */ -public class ProblemsLabelDecorator extends LabelProvider implements ILabelDecorator { - - // Constants --------------------------------------------------------------- - - private static final String ANNOTATION_TYPE_ERROR = "org.eclipse.ui.workbench.texteditor.error"; //$NON-NLS-1$ - - private static final String ANNOTATION_TYPE_WARNING = "org.eclipse.ui.workbench.texteditor.warning"; //$NON-NLS-1$ - - // Instance Variables ------------------------------------------------------ - - /** The associated text editor if the decorator is used in the outline. */ - private ITextEditor editor; - - /** Registry of icons and overlay icons. */ - private ImageDescriptorRegistry registry = new ImageDescriptorRegistry(); - - // Constructors ------------------------------------------------------------ - - /** - * Constructor. - * - * @param editor - * the associated text editor - */ - public ProblemsLabelDecorator(ITextEditor editor) { - this.editor = editor; - } - - // ILabelDecorator Implementation ------------------------------------------ - - /* - * @see org.eclipse.jface.viewers.IBaseLabelProvider#dispose() - */ - public void dispose() { - super.dispose(); - registry.dispose(); - } - - /* - * @see ILabelDecorator#decorateImage(Image, Object) - */ - public Image decorateImage(Image image, Object element) { - Annotation annotations[] = getAssociatedAnnotations((ISourceReference) element); - ImageDescriptor overlay = null; - for (int i = 0; i < annotations.length; i++) { - if (isError(annotations[i])) { - overlay = WebUI.getDefault().getImageRegistry().getDescriptor(WebUI.ICON_OVERLAY_ERROR); - } else if (isWarning(annotations[i])) { - overlay = WebUI.getDefault().getImageRegistry().getDescriptor(WebUI.ICON_OVERLAY_WARNING); - } - } - if (overlay != null) { - ImageDescriptor base = new ImageImageDescriptor(image); - return registry.get(new OverlayImageDescriptor(base, new ImageDescriptor[][] { null, null, { overlay }, null }, null)); - } else { - } - return image; - } - - /* - * @see ILabelDecorator#decorateText(String, Object) - */ - public String decorateText(String text, Object element) { - return text; - } - - // Private Methods --------------------------------------------------------- - - /** - * Returns all annotations associated with the given model element. - * - * @param element - * the model element for which annotations should be collected - * @return an array containing all annotations for the given element, or an empty array if no annotations are found - */ - private Annotation[] getAssociatedAnnotations(ISourceReference element) { - List retVal = new ArrayList(); - if (editor != null) { - IEditorInput input = editor.getEditorInput(); - IAnnotationModel model = editor.getDocumentProvider().getAnnotationModel(input); - if (model != null) { // bug #1120670 - for (Iterator i = model.getAnnotationIterator(); i.hasNext();) { - Annotation annotation = (Annotation) i.next(); - Position pos = model.getPosition(annotation); - if (pos != null && isInside(pos.getOffset(), element)) { - retVal.add(annotation); - } - } - } - } - return (Annotation[]) retVal.toArray(new Annotation[retVal.size()]); - } - - /** - * Determines whether the given annotation is an error. - * - * @param annotation - * the annotation to check - * @return true if the annotation is to be displayed as an error, false otherwise - */ - private boolean isError(Annotation annotation) { - return ANNOTATION_TYPE_ERROR.equals(annotation.getType()); - } - - /** - * Determines whether the given annotation is a warning. - * - * @param annotation - * the annotation to check - * @return true if the annotation is to be displayed as a warning, false otherwise - */ - private boolean isWarning(Annotation annotation) { - return ANNOTATION_TYPE_WARNING.equals(annotation.getType()); - } - - /** - * Tests if the given position is inside the source region of a model element. - * - * @param pos - * the position to be tested - * @param element - * the source element - * @return boolean true if position is located inside the element, otherwise false - */ - private boolean isInside(int pos, ISourceReference element) { - IRegion region = element.getSourceRegion(); - if (region != null) { - int offset = region.getOffset(); - return ((offset <= pos) && (offset + region.getLength() > pos)); - } - return false; - } +public class ProblemsLabelDecorator extends LabelProvider implements + ILabelDecorator { + + // Constants --------------------------------------------------------------- + + private static final String ANNOTATION_TYPE_ERROR = "org.eclipse.ui.workbench.texteditor.error"; //$NON-NLS-1$ + + private static final String ANNOTATION_TYPE_WARNING = "org.eclipse.ui.workbench.texteditor.warning"; //$NON-NLS-1$ + + // Instance Variables ------------------------------------------------------ + + /** The associated text editor if the decorator is used in the outline. */ + private ITextEditor editor; + + /** Registry of icons and overlay icons. */ + private ImageDescriptorRegistry registry = new ImageDescriptorRegistry(); + + // Constructors ------------------------------------------------------------ + + /** + * Constructor. + * + * @param editor + * the associated text editor + */ + public ProblemsLabelDecorator(ITextEditor editor) { + this.editor = editor; + } + + // ILabelDecorator Implementation ------------------------------------------ + + /* + * @see org.eclipse.jface.viewers.IBaseLabelProvider#dispose() + */ + public void dispose() { + super.dispose(); + registry.dispose(); + } + + /* + * @see ILabelDecorator#decorateImage(Image, Object) + */ + public Image decorateImage(Image image, Object element) { + Annotation annotations[] = getAssociatedAnnotations((ISourceReference) element); + ImageDescriptor overlay = null; + for (int i = 0; i < annotations.length; i++) { + if (isError(annotations[i])) { + overlay = WebUI.getDefault().getImageRegistry().getDescriptor( + WebUI.ICON_OVERLAY_ERROR); + } else if (isWarning(annotations[i])) { + overlay = WebUI.getDefault().getImageRegistry().getDescriptor( + WebUI.ICON_OVERLAY_WARNING); + } + } + if (overlay != null) { + ImageDescriptor base = new ImageImageDescriptor(image); + return registry.get(new OverlayImageDescriptor(base, + new ImageDescriptor[][] { null, null, { overlay }, null }, + null)); + } else { + } + return image; + } + + /* + * @see ILabelDecorator#decorateText(String, Object) + */ + public String decorateText(String text, Object element) { + return text; + } + + // Private Methods --------------------------------------------------------- + + /** + * Returns all annotations associated with the given model element. + * + * @param element + * the model element for which annotations should be collected + * @return an array containing all annotations for the given element, or an + * empty array if no annotations are found + */ + private Annotation[] getAssociatedAnnotations(ISourceReference element) { + List retVal = new ArrayList(); + if (editor != null) { + IEditorInput input = editor.getEditorInput(); + IAnnotationModel model = editor.getDocumentProvider() + .getAnnotationModel(input); + if (model != null) { // bug #1120670 + for (Iterator i = model.getAnnotationIterator(); i.hasNext();) { + Annotation annotation = (Annotation) i.next(); + Position pos = model.getPosition(annotation); + if (pos != null && isInside(pos.getOffset(), element)) { + retVal.add(annotation); + } + } + } + } + return (Annotation[]) retVal.toArray(new Annotation[retVal.size()]); + } + + /** + * Determines whether the given annotation is an error. + * + * @param annotation + * the annotation to check + * @return true if the annotation is to be displayed as an error, + * false otherwise + */ + private boolean isError(Annotation annotation) { + return ANNOTATION_TYPE_ERROR.equals(annotation.getType()); + } + + /** + * Determines whether the given annotation is a warning. + * + * @param annotation + * the annotation to check + * @return true if the annotation is to be displayed as a + * warning, false otherwise + */ + private boolean isWarning(Annotation annotation) { + return ANNOTATION_TYPE_WARNING.equals(annotation.getType()); + } + + /** + * Tests if the given position is inside the source region of a model + * element. + * + * @param pos + * the position to be tested + * @param element + * the source element + * @return boolean true if position is located inside the + * element, otherwise false + */ + private boolean isInside(int pos, ISourceReference element) { + IRegion region = element.getSourceRegion(); + if (region != null) { + int offset = region.getOffset(); + return ((offset <= pos) && (offset + region.getLength() > pos)); + } + return false; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/views/util/ImageDescriptorRegistry.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/views/util/ImageDescriptorRegistry.java index c3b15af..4b90d9a 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/views/util/ImageDescriptorRegistry.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/views/util/ImageDescriptorRegistry.java @@ -9,7 +9,7 @@ * Christopher Lenz - initial implementation based on the internal Eclipse * class of the same name, defined in multiple packages * - * $Id: ImageDescriptorRegistry.java,v 1.1 2004-09-02 18:26:28 jsurfer Exp $ + * $Id: ImageDescriptorRegistry.java,v 1.2 2006-10-21 23:13:53 pombredanne Exp $ */ package net.sourceforge.phpeclipse.ui.views.util; @@ -41,30 +41,31 @@ public class ImageDescriptorRegistry { * display, respectively. */ public ImageDescriptorRegistry() { - this(Display.getCurrent() != null ? - Display.getCurrent() : Display.getDefault()); + this(Display.getCurrent() != null ? Display.getCurrent() : Display + .getDefault()); } /** * Creates a new image descriptor registry for the given display. All images * managed by this registry will be disposed when the display gets disposed. * - * @param display the display the images managed by this registry are - * allocated for + * @param display + * the display the images managed by this registry are allocated + * for */ public ImageDescriptorRegistry(Display display) { display.disposeExec(new Runnable() { public void run() { dispose(); - } + } }); } - + /** * Returns the image assiciated with the given image descriptor. * - * @param descriptor the image descriptor for which the registry manages an - * image + * @param descriptor + * the image descriptor for which the registry manages an image * @return the image associated with the image descriptor or null * if the image descriptor can't create the requested image. */ @@ -84,12 +85,12 @@ public class ImageDescriptorRegistry { /** * Disposes all images managed by this registry. - */ + */ public void dispose() { - for (Iterator i = registry.values().iterator(); i.hasNext(); ) { + for (Iterator i = registry.values().iterator(); i.hasNext();) { ((Image) i.next()).dispose(); } registry.clear(); } - + } diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/views/util/ImageImageDescriptor.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/views/util/ImageImageDescriptor.java index e1af923..f10b11a 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/views/util/ImageImageDescriptor.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/views/util/ImageImageDescriptor.java @@ -9,7 +9,7 @@ * Christopher Lenz - initial version based on the Eclipse class of the same * name in org.eclipse.jdt.internal.ui.viewsupport * - * $Id: ImageImageDescriptor.java,v 1.1 2004-09-02 18:26:28 jsurfer Exp $ + * $Id: ImageImageDescriptor.java,v 1.2 2006-10-21 23:13:53 pombredanne Exp $ */ package net.sourceforge.phpeclipse.ui.views.util; @@ -19,7 +19,8 @@ import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; /** - * ImageDescriptor implementation that wraps an existing {@link Image}. + * ImageDescriptor implementation that wraps an existing + * {@link Image}. */ public class ImageImageDescriptor extends ImageDescriptor { @@ -33,10 +34,11 @@ public class ImageImageDescriptor extends ImageDescriptor { /** * Constructor. * - * @param image the image to wrap + * @param image + * the image to wrap */ public ImageImageDescriptor(Image image) { - this.image= image; + this.image = image; } // ImageDescriptor Implementation ------------------------------------------ diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/views/util/OverlayImageDescriptor.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/views/util/OverlayImageDescriptor.java index e9e995a..fb1477d 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/views/util/OverlayImageDescriptor.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/views/util/OverlayImageDescriptor.java @@ -9,7 +9,7 @@ * Christopher Lenz - initial version based on the internal Eclipse class * org.eclipse.ui.internal.ide.misc.OverlayIcon * - * $Id: OverlayImageDescriptor.java,v 1.1 2004-09-02 18:26:28 jsurfer Exp $ + * $Id: OverlayImageDescriptor.java,v 1.2 2006-10-21 23:13:53 pombredanne Exp $ */ package net.sourceforge.phpeclipse.ui.views.util; @@ -31,7 +31,7 @@ public class OverlayImageDescriptor extends CompositeImageDescriptor { /** The base image. */ private ImageDescriptor base; - + /** The overlay images. */ private ImageDescriptor overlays[][]; @@ -41,8 +41,10 @@ public class OverlayImageDescriptor extends CompositeImageDescriptor { * Creates the image descriptor. The size of the resulting image will be the * same as the size of the base image. * - * @param base the descriptor of the base image - * @param overlays descriptors of the overlay images + * @param base + * the descriptor of the base image + * @param overlays + * descriptors of the overlay images */ public OverlayImageDescriptor(ImageDescriptor base, ImageDescriptor[][] overlays) { @@ -52,10 +54,13 @@ public class OverlayImageDescriptor extends CompositeImageDescriptor { /** * Creates the image descriptor. * - * @param base the descriptor of the base image - * @param overlays descriptors of the overlay images - * @param size the size of the composite image, or null to use the - * size of the base image + * @param base + * the descriptor of the base image + * @param overlays + * descriptors of the overlay images + * @param size + * the size of the composite image, or null to use the + * size of the base image */ public OverlayImageDescriptor(ImageDescriptor base, ImageDescriptor[][] overlays, Point size) { @@ -63,14 +68,14 @@ public class OverlayImageDescriptor extends CompositeImageDescriptor { this.overlays = overlays; if (size == null) { ImageData data = base.getImageData(); - size = new Point(data.width, data.height); + size = new Point(data.width, data.height); } this.size = size; } // CompositeImageDescriptor Implementation --------------------------------- - /* + /* * @see CompositeImageDescriptor#drawCompositeImage(int, int) */ protected void drawCompositeImage(int width, int height) { @@ -95,7 +100,7 @@ public class OverlayImageDescriptor extends CompositeImageDescriptor { } } - /* + /* * @see CompositeImageDescriptor#getSize() */ protected Point getSize() { diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/ExtendedBrowser.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/ExtendedBrowser.java index 349f98e..a1b23ba 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/ExtendedBrowser.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/ExtendedBrowser.java @@ -1,10 +1,10 @@ /** * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved.   This program and the accompanying materials + * All rights reserved. � This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation */ @@ -14,12 +14,14 @@ import net.sourceforge.phpeclipse.webbrowser.internal.WebBrowser; import org.eclipse.swt.browser.Browser; import org.eclipse.swt.widgets.Composite; + /** - * Web browser widget. Extends the eclipse Browser widget by adding an - * optional toolbar and statusbar. + * Web browser widget. Extends the eclipse Browser widget by adding an optional + * toolbar and statusbar. */ public class ExtendedBrowser extends WebBrowser { - public ExtendedBrowser(Composite parent, final boolean showToolbar, final boolean showStatusbar) { + public ExtendedBrowser(Composite parent, final boolean showToolbar, + final boolean showStatusbar) { super(parent, showToolbar, showStatusbar); } diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IExternalWebBrowser.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IExternalWebBrowser.java index e096266..18659dd 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IExternalWebBrowser.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IExternalWebBrowser.java @@ -1,15 +1,16 @@ package net.sourceforge.phpeclipse.webbrowser; + /** * */ public interface IExternalWebBrowser extends IWebBrowser { public String getLocation(); - + public String getParameters(); - + public void delete(); - + public boolean isWorkingCopy(); - + public IExternalWebBrowserWorkingCopy getWorkingCopy(); } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IExternalWebBrowserWorkingCopy.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IExternalWebBrowserWorkingCopy.java index f33fff7..fb2a37a 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IExternalWebBrowserWorkingCopy.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IExternalWebBrowserWorkingCopy.java @@ -1,4 +1,5 @@ package net.sourceforge.phpeclipse.webbrowser; + /** * */ @@ -6,8 +7,8 @@ public interface IExternalWebBrowserWorkingCopy extends IExternalWebBrowser { public void setName(String name); public void setLocation(String location); - + public void setParameters(String params); - + public IExternalWebBrowser save(); } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IInternalWebBrowser.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IInternalWebBrowser.java index 9c996d2..0ca2336 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IInternalWebBrowser.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IInternalWebBrowser.java @@ -1,13 +1,14 @@ package net.sourceforge.phpeclipse.webbrowser; + /** * */ public interface IInternalWebBrowser extends IWebBrowser { public boolean getUseNewPage(); - + public boolean getClearHistoryOnExit(); - + public boolean isWorkingCopy(); - + public IInternalWebBrowserWorkingCopy getWorkingCopy(); } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IInternalWebBrowserWorkingCopy.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IInternalWebBrowserWorkingCopy.java index 83ed611..18d2f2b 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IInternalWebBrowserWorkingCopy.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IInternalWebBrowserWorkingCopy.java @@ -1,11 +1,12 @@ package net.sourceforge.phpeclipse.webbrowser; + /** * */ public interface IInternalWebBrowserWorkingCopy extends IInternalWebBrowser { public void setUseNewPage(boolean b); - + public void setClearHistoryOnExit(boolean b); - + public IInternalWebBrowser save(); } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IURLMap.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IURLMap.java index 3b18121..c58bc86 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IURLMap.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IURLMap.java @@ -4,11 +4,12 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation */ package net.sourceforge.phpeclipse.webbrowser; + /** * Interface for mapping special URLs to other locations. */ @@ -16,7 +17,8 @@ public interface IURLMap { /** * Returns a mapped URL * - * @param url java.lang.String + * @param url + * java.lang.String * @return java.lang.String */ public String getMappedURL(String url); diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IWebBrowser.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IWebBrowser.java index 012458b..7d4ff17 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IWebBrowser.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IWebBrowser.java @@ -1,6 +1,7 @@ package net.sourceforge.phpeclipse.webbrowser; import java.net.URL; + /** * */ diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IWebBrowserEditorInput.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IWebBrowserEditorInput.java index 58af19f..2663f7a 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IWebBrowserEditorInput.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/IWebBrowserEditorInput.java @@ -4,7 +4,7 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation */ @@ -13,42 +13,41 @@ package net.sourceforge.phpeclipse.webbrowser; import java.net.URL; import org.eclipse.ui.IEditorInput; + /** - * The editor input for the Web browser editor. If the - * integrated Web browser exists for this platform, (and - * the user has chosen to use it) this information will - * be used to populate the Web browser. If not, this - * information will be used to launch an external Web - * browser. + * The editor input for the Web browser editor. If the integrated Web browser + * exists for this platform, (and the user has chosen to use it) this + * information will be used to populate the Web browser. If not, this + * information will be used to launch an external Web browser. */ public interface IWebBrowserEditorInput extends IEditorInput { /** - * Returns true if this page can reuse the browser that the - * given input is being displayed in, or false if it should - * open up in a new page. - * - * @param input net.sourceforge.phpeclipse.webbrowser.IWebBrowserEditorInput + * Returns true if this page can reuse the browser that the given input is + * being displayed in, or false if it should open up in a new page. + * + * @param input + * net.sourceforge.phpeclipse.webbrowser.IWebBrowserEditorInput * @return boolean */ public boolean canReplaceInput(IWebBrowserEditorInput input); /** * Returns the url that should be displayed in the browser. - * + * * @return java.net.URL */ public URL getURL(); /** * Returns true if the Web statusbar should be shown. - * + * * @return boolean */ public boolean isStatusbarVisible(); /** * Returns true if the Web toolbar should be shown. - * + * * @return boolean */ public boolean isToolbarVisible(); diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/OpenBrowserAction.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/OpenBrowserAction.java index 67bc2c7..866b55a 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/OpenBrowserAction.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/OpenBrowserAction.java @@ -4,13 +4,14 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation */ package net.sourceforge.phpeclipse.webbrowser; import org.eclipse.jface.action.Action; + /** * Action to open the Web browser. */ @@ -26,6 +27,8 @@ public class OpenBrowserAction extends Action { * Implementation of method defined on IAction. */ public void run() { - WebBrowser.openURL(new WebBrowserEditorInput(null, WebBrowserEditorInput.SHOW_ALL | WebBrowserEditorInput.FORCE_NEW_PAGE)); + WebBrowser.openURL(new WebBrowserEditorInput(null, + WebBrowserEditorInput.SHOW_ALL + | WebBrowserEditorInput.FORCE_NEW_PAGE)); } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/OpenBrowserWorkbenchAction.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/OpenBrowserWorkbenchAction.java index 966d2e3..6991e19 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/OpenBrowserWorkbenchAction.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/OpenBrowserWorkbenchAction.java @@ -4,7 +4,7 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation */ @@ -14,10 +14,12 @@ import org.eclipse.jface.action.IAction; import org.eclipse.jface.viewers.ISelection; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.IWorkbenchWindowActionDelegate; + /** * Action to open the Web broswer. */ -public class OpenBrowserWorkbenchAction implements IWorkbenchWindowActionDelegate { +public class OpenBrowserWorkbenchAction implements + IWorkbenchWindowActionDelegate { /** * OpenBrowserWorkbenchAction constructor comment. */ @@ -26,17 +28,21 @@ public class OpenBrowserWorkbenchAction implements IWorkbenchWindowActionDelegat } /** - * Disposes this action delegate. The implementor should unhook any references - * to itself so that garbage collection can occur. + * Disposes this action delegate. The implementor should unhook any + * references to itself so that garbage collection can occur. */ - public void dispose() { } + public void dispose() { + } /** - * Initializes this action delegate with the workbench window it will work in. - * - * @param window the window that provides the context for this delegate + * Initializes this action delegate with the workbench window it will work + * in. + * + * @param window + * the window that provides the context for this delegate */ - public void init(IWorkbenchWindow window) { } + public void init(IWorkbenchWindow window) { + } /** * Performs this action. @@ -44,23 +50,31 @@ public class OpenBrowserWorkbenchAction implements IWorkbenchWindowActionDelegat * This method is called when the delegating action has been triggered. * Implement this method to do the actual work. *

    - * - * @param action the action proxy that handles the presentation portion of the - * action + * + * @param action + * the action proxy that handles the presentation portion of the + * action */ public void run(IAction action) { - WebBrowser.openURL(new WebBrowserEditorInput(null, WebBrowserEditorInput.SHOW_ALL | WebBrowserEditorInput.FORCE_NEW_PAGE)); + WebBrowser.openURL(new WebBrowserEditorInput(null, + WebBrowserEditorInput.SHOW_ALL + | WebBrowserEditorInput.FORCE_NEW_PAGE)); } /** - * Notifies this action delegate that the selection in the workbench has changed. + * Notifies this action delegate that the selection in the workbench has + * changed. *

    * Implementers can use this opportunity to change the availability of the * action or to modify other presentation properties. *

    - * - * @param action the action proxy that handles presentation portion of the action - * @param selection the current selection in the workbench + * + * @param action + * the action proxy that handles presentation portion of the + * action + * @param selection + * the current selection in the workbench */ - public void selectionChanged(IAction action, ISelection selection) { } + public void selectionChanged(IAction action, ISelection selection) { + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/WebBrowser.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/WebBrowser.java index 9016046..69c82a7 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/WebBrowser.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/WebBrowser.java @@ -4,7 +4,7 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation */ @@ -21,10 +21,10 @@ import net.sourceforge.phpeclipse.webbrowser.internal.WebBrowserUIPlugin; import net.sourceforge.phpeclipse.webbrowser.internal.WebBrowserUtil; import org.eclipse.swt.widgets.Display; + /** - * The main interface to the internal Web browser. If allows - * you to query the file types supported by the Web browser - * and open a URL. + * The main interface to the internal Web browser. If allows you to query the + * file types supported by the Web browser and open a URL. */ public class WebBrowser { /** @@ -35,9 +35,9 @@ public class WebBrowser { } /** - * Returns true if the internal Web browser is supported on this - * platform and the user has chosen to use it. - * + * Returns true if the internal Web browser is supported on this platform + * and the user has chosen to use it. + * * @return boolean */ public static boolean isUsingInternalBrowser() { @@ -45,22 +45,22 @@ public class WebBrowser { } /** - * Display the given URL in a Web browser. If the user has chosen not - * to use the internal browser, an external browser will be used. If - * not, a browser in the current page will be reused if forceNewPage - * is not true and the user preference is not set. Finally, showToolbar - * will decide when the toolbar should be shown in the internal browser. - * + * Display the given URL in a Web browser. If the user has chosen not to use + * the internal browser, an external browser will be used. If not, a browser + * in the current page will be reused if forceNewPage is not true and the + * user preference is not set. Finally, showToolbar will decide when the + * toolbar should be shown in the internal browser. + * * @param input */ public static void openURL(final IWebBrowserEditorInput input) { Trace.trace(Trace.FINEST, "openURL() " + input); if (input == null) return; - + Display.getDefault().asyncExec(new Runnable() { public void run() { - if (!isUsingInternalBrowser()){ + if (!isUsingInternalBrowser()) { IWebBrowser browser = getCurrentWebBrowser(); browser.openURL(input.getURL()); } else @@ -107,8 +107,9 @@ public class WebBrowser { /** * Display the given URL in a Web browser. - * - * @param url java.net.URL + * + * @param url + * java.net.URL */ public static void openURL(URL url) { IWebBrowser browser = getCurrentWebBrowser(); @@ -117,7 +118,8 @@ public class WebBrowser { else { Display.getDefault().asyncExec(new Runnable() { public void run() { - WebBrowserUtil.openError(WebBrowserUIPlugin.getResource("%errorNoBrowser")); + WebBrowserUtil.openError(WebBrowserUIPlugin + .getResource("%errorNoBrowser")); } }); } diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/WebBrowserEditorInput.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/WebBrowserEditorInput.java index aeec7e4..1f4681f 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/WebBrowserEditorInput.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/WebBrowserEditorInput.java @@ -4,7 +4,7 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation */ @@ -22,10 +22,12 @@ import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.ui.IElementFactory; import org.eclipse.ui.IMemento; import org.eclipse.ui.IPersistableElement; + /** * The editor input for the integrated web browser. */ -public class WebBrowserEditorInput implements IWebBrowserEditorInput, IPersistableElement, IElementFactory { +public class WebBrowserEditorInput implements IWebBrowserEditorInput, + IPersistableElement, IElementFactory { // --- constants to pass into constructor --- // if used, the toolbar will be available @@ -42,7 +44,7 @@ public class WebBrowserEditorInput implements IWebBrowserEditorInput, IPersistab // the page can reopen to the same URL after // shutting down public static final int SAVE_URL = 1 << 5; - + // if used, the browser will be transient and will not appear // in the most recently used file list, nor will it reopen after // restarting Eclipse @@ -51,12 +53,17 @@ public class WebBrowserEditorInput implements IWebBrowserEditorInput, IPersistab public static final int SHOW_ALL = SHOW_TOOLBAR | SHOW_STATUSBAR; private static final String ELEMENT_FACTORY_ID = "net.sourceforge.phpeclipse.webbrowser.elementFactory"; + private static final String MEMENTO_URL = "url"; + private static final String MEMENTO_STYLE = "style"; + private static final String MEMENTO_ID = "id"; private URL url; + private int style; + private String id = null; /** @@ -98,13 +105,13 @@ public class WebBrowserEditorInput implements IWebBrowserEditorInput, IPersistab public WebBrowserEditorInput(URL url, boolean b) { this(url); } - + /** - * Returns true if this page can reuse the browser that the - * given input is being displayed in, or false if it should - * open up in a new page. - * - * @param input net.sourceforge.phpeclipse.webbrowser.IWebBrowserEditorInput + * Returns true if this page can reuse the browser that the given input is + * being displayed in, or false if it should open up in a new page. + * + * @param input + * net.sourceforge.phpeclipse.webbrowser.IWebBrowserEditorInput * @return boolean */ public boolean canReplaceInput(IWebBrowserEditorInput input) { @@ -123,13 +130,15 @@ public class WebBrowserEditorInput implements IWebBrowserEditorInput, IPersistab } else return false; } - + /** - * Creates an IElement from the state captured within - * an IMemento. - * - * @param memento a memento containing the state for an element - * @return an element, or null if the element could not be created + * Creates an IElement from the state captured within an + * IMemento. + * + * @param memento + * a memento containing the state for an element + * @return an element, or null if the element could not be + * created */ public IAdaptable createElement(IMemento memento) { URL url2 = null; @@ -142,26 +151,27 @@ public class WebBrowserEditorInput implements IWebBrowserEditorInput, IPersistab int newStyle = SHOW_TOOLBAR | SHOW_STATUSBAR; try { newStyle = memento.getInteger(MEMENTO_STYLE).intValue(); - + if ((newStyle & SAVE_URL) != 0) url = new URL(memento.getString(MEMENTO_URL)); } catch (Exception e) { // could not determine the style } - + String id2 = null; try { id2 = memento.getString(MEMENTO_ID); if (id2 != null && id2.length() < 1) id2 = null; - } catch (Exception e) { } - + } catch (Exception e) { + } + return new WebBrowserEditorInput(url2, newStyle, id2); } - + /** - * Indicates whether some other object is "equal to" this one. - * In this case it means that the underlying IFolders are equal. + * Indicates whether some other object is "equal to" this one. In this case + * it means that the underlying IFolders are equal. */ public boolean equals(Object obj) { if (this == obj) @@ -169,23 +179,23 @@ public class WebBrowserEditorInput implements IWebBrowserEditorInput, IPersistab if (!(obj instanceof WebBrowserEditorInput)) return false; WebBrowserEditorInput other = (WebBrowserEditorInput) obj; - + if (url != null && !url.equals(obj)) return false; - + return canReplaceInput(other); } - + /** - * Returns whether the editor input exists. + * Returns whether the editor input exists. *

    - * This method is primarily used to determine if an editor input should - * appear in the "File Most Recently Used" menu. An editor input will appear - * in the list until the return value of exists becomes + * This method is primarily used to determine if an editor input should + * appear in the "File Most Recently Used" menu. An editor input will appear + * in the list until the return value of exists becomes * false or it drops off the bottom of the list. - * - * @return true if the editor input exists; false - * otherwise + * + * @return true if the editor input exists; + * false otherwise */ public boolean exists() { if ((style & TRANSIENT) != 0) @@ -193,54 +203,55 @@ public class WebBrowserEditorInput implements IWebBrowserEditorInput, IPersistab else return true; } - + /** - * Returns an object which is an instance of the given class - * associated with this object. Returns null if - * no such object can be found. - * - * @param adapter the adapter class to look up - * @return a object castable to the given class, - * or null if this object does not - * have an adapter for the given class + * Returns an object which is an instance of the given class associated with + * this object. Returns null if no such object can be found. + * + * @param adapter + * the adapter class to look up + * @return a object castable to the given class, or null if + * this object does not have an adapter for the given class */ public Object getAdapter(Class adapter) { return null; } - + /** - * Returns the ID of an element factory which can be used to recreate - * this object. An element factory extension with this ID must exist - * within the workbench registry. + * Returns the ID of an element factory which can be used to recreate this + * object. An element factory extension with this ID must exist within the + * workbench registry. * * @return the element factory ID */ public String getFactoryId() { return ELEMENT_FACTORY_ID; } - + public ImageDescriptor getImageDescriptor() { - return ImageResource.getImageDescriptor(ImageResource.IMG_INTERNAL_BROWSER); + return ImageResource + .getImageDescriptor(ImageResource.IMG_INTERNAL_BROWSER); } - + /** * Returns the name of this editor input for display purposes. *

    * For instance, if the fully qualified input name is * "a\b\MyFile.gif", the return value would be just * "MyFile.gif". - * + * * @return the file name string */ public String getName() { return WebBrowserUIPlugin.getResource("%viewWebBrowserTitle"); } - + /* - * Returns an object that can be used to save the state of this editor input. - * - * @return the persistable element, or null if this editor input - * cannot be persisted + * Returns an object that can be used to save the state of this editor + * input. + * + * @return the persistable element, or null if this editor + * input cannot be persisted */ public IPersistableElement getPersistable() { if ((style & TRANSIENT) != 0) @@ -248,23 +259,23 @@ public class WebBrowserEditorInput implements IWebBrowserEditorInput, IPersistab else return this; } - + public String getToolTipText() { if (url != null) return url.toExternalForm(); else return WebBrowserUIPlugin.getResource("%viewWebBrowserTitle"); } - + /** * Returns the url. - * + * * @return java.net.URL */ public URL getURL() { return url; } - + /** * Returns the browser id. Browsers with a set id will always & only be * replaced by browsers with the same id. @@ -274,43 +285,44 @@ public class WebBrowserEditorInput implements IWebBrowserEditorInput, IPersistab public String getBrowserId() { return id; } - + /** * Returns true if the status bar should be shown. - * + * * @return boolean */ public boolean isStatusbarVisible() { return (style & SHOW_STATUSBAR) != 0; } - + /** * Returns true if the toolbar should be shown. - * + * * @return boolean */ public boolean isToolbarVisible() { return (style & SHOW_TOOLBAR) != 0; } - + /** * Saves the state of an element within a memento. - * - * @param memento the storage area for element state + * + * @param memento + * the storage area for element state */ public void saveState(IMemento memento) { if ((style & SAVE_URL) != 0 && url != null) memento.putString(MEMENTO_URL, url.toExternalForm()); memento.putInteger(MEMENTO_STYLE, style); - + if (id != null) memento.putString(MEMENTO_ID, id); } /** * Converts this object to a string. - * + * * @return java.lang.String */ public String toString() { diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/BrowserContentProvider.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/BrowserContentProvider.java index fd2696f..da3842f 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/BrowserContentProvider.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/BrowserContentProvider.java @@ -4,7 +4,7 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation **********************************************************************/ @@ -31,45 +31,51 @@ public class BrowserContentProvider implements IStructuredContentProvider { } /** - * Disposes of this content provider. - * This is called by the viewer when it is disposed. + * Disposes of this content provider. This is called by the viewer when it + * is disposed. */ - public void dispose() { } + public void dispose() { + } /** - * Returns the elements to display in the viewer - * when its input is set to the given element. - * These elements can be presented as rows in a table, items in a list, etc. - * The result is not modified by the viewer. - * - * @param inputElement the input element + * Returns the elements to display in the viewer when its input is set to + * the given element. These elements can be presented as rows in a table, + * items in a list, etc. The result is not modified by the viewer. + * + * @param inputElement + * the input element * @return the array of elements to display in the viewer */ public Object[] getElements(Object inputElement) { List list = new ArrayList(); - Iterator iterator = BrowserManager.getInstance().getWebBrowsers().iterator(); + Iterator iterator = BrowserManager.getInstance().getWebBrowsers() + .iterator(); while (iterator.hasNext()) { IWebBrowser browser = (IWebBrowser) iterator.next(); list.add(browser); } return list.toArray(); - } + } /** - * Notifies this content provider that the given viewer's input - * has been switched to a different element. + * Notifies this content provider that the given viewer's input has been + * switched to a different element. *

    - * A typical use for this method is registering the content provider as a listener - * to changes on the new input (using model-specific means), and deregistering the viewer - * from the old input. In response to these change notifications, the content provider - * propagates the changes to the viewer. + * A typical use for this method is registering the content provider as a + * listener to changes on the new input (using model-specific means), and + * deregistering the viewer from the old input. In response to these change + * notifications, the content provider propagates the changes to the viewer. *

    - * - * @param viewer the viewer - * @param oldInput the old input element, or null if the viewer - * did not previously have an input - * @param newInput the new input element, or null if the viewer - * does not have an input + * + * @param viewer + * the viewer + * @param oldInput + * the old input element, or null if the viewer + * did not previously have an input + * @param newInput + * the new input element, or null if the viewer + * does not have an input */ - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {} + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/BrowserManager.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/BrowserManager.java index d5dea45..cd2b875 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/BrowserManager.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/BrowserManager.java @@ -4,7 +4,7 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html -  * + �* * Contributors: * IBM - Initial API and implementation **********************************************************************/ @@ -30,262 +30,273 @@ import org.eclipse.ui.IMemento; import org.eclipse.ui.XMLMemento; /** - * + * */ public class BrowserManager { - private static final int ADD = 0; - - private static final int CHANGE = 1; - - private static final int REMOVE = 2; - - protected List browsers; - - protected IWebBrowser currentBrowser; - - protected List browserListeners = new ArrayList(); - - private Preferences.IPropertyChangeListener pcl; - - protected boolean ignorePreferenceChanges = false; - - protected static BrowserManager instance; - - public static BrowserManager getInstance() { - if (instance == null) - instance = new BrowserManager(); - return instance; - } - - private BrowserManager() { - pcl = new Preferences.IPropertyChangeListener() { - public void propertyChange(Preferences.PropertyChangeEvent event) { - if (ignorePreferenceChanges) - return; - String property = event.getProperty(); - if (property.equals("browsers")) { - loadBrowsers(); - } - } - }; - - WebBrowserUIPlugin.getInstance().getPluginPreferences().addPropertyChangeListener(pcl); - } - - protected void dispose() { - WebBrowserUIPlugin.getInstance().getPluginPreferences().removePropertyChangeListener(pcl); - - // clear the cache - if (browsers != null) { - Iterator iterator = browsers.iterator(); - while (iterator.hasNext()) { - Object obj = iterator.next(); - if (obj instanceof IInternalWebBrowser) { - IInternalWebBrowser wb = (IInternalWebBrowser) obj; - if (wb.getClearHistoryOnExit()) - WebBrowserPreference.setInternalWebBrowserHistory(null); - } - } - } - } - - public IExternalWebBrowserWorkingCopy createExternalWebBrowser() { - return new ExternalWebBrowserWorkingCopy(); - } - - public List getWebBrowsers() { - if (browsers == null) - loadBrowsers(); - return new ArrayList(browsers); - } - - protected void loadBrowsers() { - Trace.trace(Trace.FINEST, "Loading web browsers"); - - Preferences prefs = WebBrowserUIPlugin.getInstance().getPluginPreferences(); - String xmlString = prefs.getString("browsers"); - if (xmlString != null && xmlString.length() > 0) { - browsers = new ArrayList(); - - try { - ByteArrayInputStream in = new ByteArrayInputStream(xmlString.getBytes()); - Reader reader = new InputStreamReader(in); - IMemento memento = XMLMemento.createReadRoot(reader); - - IMemento child = memento.getChild("internal"); - if (child != null) { - InternalWebBrowser browser = new InternalWebBrowser(); - browser.load(child); - browsers.add(browser); - } - - IMemento[] children = memento.getChildren("external"); - int size = children.length; - for (int i = 0; i < size; i++) { - ExternalWebBrowser browser = new ExternalWebBrowser(); - browser.load(children[i]); - browsers.add(browser); - } - - Integer current = memento.getInteger("current"); - if (current != null) { - currentBrowser = (IWebBrowser) browsers.get(current.intValue()); - } - } catch (Exception e) { - Trace.trace(Trace.WARNING, "Could not load browsers: " + e.getMessage()); - } - addInternalBrowser(browsers); - if (currentBrowser == null && browsers.size() > 0) - currentBrowser = (IWebBrowser) browsers.get(0); - } else { - setupDefaultBrowsers(); - saveBrowsers(); - return; - } - } - - protected void saveBrowsers() { - try { - ignorePreferenceChanges = true; - XMLMemento memento = XMLMemento.createWriteRoot("web-browsers"); - - Iterator iterator = browsers.iterator(); - while (iterator.hasNext()) { - Object obj = iterator.next(); - if (obj instanceof InternalWebBrowser) { - InternalWebBrowser browser = (InternalWebBrowser) obj; - IMemento child = memento.createChild("internal"); - browser.save(child); - } else if (obj instanceof ExternalWebBrowser) { - ExternalWebBrowser browser = (ExternalWebBrowser) obj; - IMemento child = memento.createChild("external"); - browser.save(child); - } - } - - memento.putInteger("current", browsers.indexOf(currentBrowser)); - - StringWriter writer = new StringWriter(); - memento.save(writer); - String xmlString = writer.getBuffer().toString(); - Preferences prefs = WebBrowserUIPlugin.getInstance().getPluginPreferences(); - prefs.setValue("browsers", xmlString); - WebBrowserUIPlugin.getInstance().savePluginPreferences(); - } catch (Exception e) { - Trace.trace(Trace.SEVERE, "Could not save browsers", e); - } - ignorePreferenceChanges = false; - } - - protected void addInternalBrowser(List browserList) { - if (browserList == null) - return; - - Iterator iterator = browserList.iterator(); - while (iterator.hasNext()) { - IWebBrowser browser = (IWebBrowser) iterator.next(); - if (browser instanceof IInternalWebBrowser) - return; - } - - // add the internal browser if we can -// WebBrowserUIPlugin.getInstance().getLog().log( -// new Status(IStatus.INFO, WebBrowserUIPlugin.PLUGIN_ID, 0, WebBrowserUtil.canUseInternalWebBrowser() + "/" -// + WebBrowserUtil.isInternalBrowserOperational(), null)); -// if (!WebBrowserUtil.canUseInternalWebBrowser() || !WebBrowserUtil.isInternalBrowserOperational()) -// return; - WebBrowserUIPlugin.getInstance().getLog().log( - new Status(IStatus.INFO, WebBrowserUIPlugin.PLUGIN_ID, 0, - "-"+WebBrowserUtil.isInternalBrowserOperational(), null)); - if (!WebBrowserUtil.isInternalBrowserOperational()) - return; - browserList.add(0, new InternalWebBrowser()); - } - - private void setupDefaultBrowsers() { - browsers = new ArrayList(); - - addInternalBrowser(browsers); - - // handle all the EXTERNAL browsers by criteria and add those too at startup - WebBrowserUtil.addFoundBrowsers(browsers); - - // by default, if internal is there, that is current, else set the first external one - if (!browsers.isEmpty()) - currentBrowser = (IWebBrowser) browsers.get(0); - } - - protected void addBrowser(IExternalWebBrowser browser) { - if (browsers == null) - loadBrowsers(); - if (!browsers.contains(browser)) - browsers.add(browser); - fireWebBrowserEvent(browser, ADD); - saveBrowsers(); - } - - protected void removeWebBrowser(IExternalWebBrowser browser) { - if (browsers == null) - loadBrowsers(); - browsers.remove(browser); - fireWebBrowserEvent(browser, REMOVE); - } - - // Internal Web browser CAN be "edited", just not created or removed - protected void browserChanged(IWebBrowser browser) { - fireWebBrowserEvent(browser, CHANGE); - saveBrowsers(); - } - - /** - * Add Web browser listener. - * - * @param listener - */ - public void addWebBrowserListener(IWebBrowserListener listener) { - browserListeners.add(listener); - } - - /** - * Remove Web browser listener. - * - * @param listener - */ - public void removeWebBrowserListener(IWebBrowserListener listener) { - browserListeners.remove(listener); - } - - /** - * Fire a Web browser event. - * - * @param browser - * @param type - */ - protected void fireWebBrowserEvent(IWebBrowser browser, int type) { - Object[] obj = browserListeners.toArray(); - - int size = obj.length; - for (int i = 0; i < size; i++) { - IWebBrowserListener listener = (IWebBrowserListener) obj[i]; - if (type == ADD) - listener.browserAdded(browser); - else if (type == CHANGE) - listener.browserChanged(browser); - else if (type == REMOVE) - listener.browserRemoved(browser); - } - } - - public IWebBrowser getCurrentWebBrowser() { - if (browsers == null) - loadBrowsers(); - - return currentBrowser; - } - - public void setCurrentWebBrowser(IWebBrowser wb) { - if (browsers.contains(wb)) - currentBrowser = wb; - saveBrowsers(); - } + private static final int ADD = 0; + + private static final int CHANGE = 1; + + private static final int REMOVE = 2; + + protected List browsers; + + protected IWebBrowser currentBrowser; + + protected List browserListeners = new ArrayList(); + + private Preferences.IPropertyChangeListener pcl; + + protected boolean ignorePreferenceChanges = false; + + protected static BrowserManager instance; + + public static BrowserManager getInstance() { + if (instance == null) + instance = new BrowserManager(); + return instance; + } + + private BrowserManager() { + pcl = new Preferences.IPropertyChangeListener() { + public void propertyChange(Preferences.PropertyChangeEvent event) { + if (ignorePreferenceChanges) + return; + String property = event.getProperty(); + if (property.equals("browsers")) { + loadBrowsers(); + } + } + }; + + WebBrowserUIPlugin.getInstance().getPluginPreferences() + .addPropertyChangeListener(pcl); + } + + protected void dispose() { + WebBrowserUIPlugin.getInstance().getPluginPreferences() + .removePropertyChangeListener(pcl); + + // clear the cache + if (browsers != null) { + Iterator iterator = browsers.iterator(); + while (iterator.hasNext()) { + Object obj = iterator.next(); + if (obj instanceof IInternalWebBrowser) { + IInternalWebBrowser wb = (IInternalWebBrowser) obj; + if (wb.getClearHistoryOnExit()) + WebBrowserPreference.setInternalWebBrowserHistory(null); + } + } + } + } + + public IExternalWebBrowserWorkingCopy createExternalWebBrowser() { + return new ExternalWebBrowserWorkingCopy(); + } + + public List getWebBrowsers() { + if (browsers == null) + loadBrowsers(); + return new ArrayList(browsers); + } + + protected void loadBrowsers() { + Trace.trace(Trace.FINEST, "Loading web browsers"); + + Preferences prefs = WebBrowserUIPlugin.getInstance() + .getPluginPreferences(); + String xmlString = prefs.getString("browsers"); + if (xmlString != null && xmlString.length() > 0) { + browsers = new ArrayList(); + + try { + ByteArrayInputStream in = new ByteArrayInputStream(xmlString + .getBytes()); + Reader reader = new InputStreamReader(in); + IMemento memento = XMLMemento.createReadRoot(reader); + + IMemento child = memento.getChild("internal"); + if (child != null) { + InternalWebBrowser browser = new InternalWebBrowser(); + browser.load(child); + browsers.add(browser); + } + + IMemento[] children = memento.getChildren("external"); + int size = children.length; + for (int i = 0; i < size; i++) { + ExternalWebBrowser browser = new ExternalWebBrowser(); + browser.load(children[i]); + browsers.add(browser); + } + + Integer current = memento.getInteger("current"); + if (current != null) { + currentBrowser = (IWebBrowser) browsers.get(current + .intValue()); + } + } catch (Exception e) { + Trace.trace(Trace.WARNING, "Could not load browsers: " + + e.getMessage()); + } + addInternalBrowser(browsers); + if (currentBrowser == null && browsers.size() > 0) + currentBrowser = (IWebBrowser) browsers.get(0); + } else { + setupDefaultBrowsers(); + saveBrowsers(); + return; + } + } + + protected void saveBrowsers() { + try { + ignorePreferenceChanges = true; + XMLMemento memento = XMLMemento.createWriteRoot("web-browsers"); + + Iterator iterator = browsers.iterator(); + while (iterator.hasNext()) { + Object obj = iterator.next(); + if (obj instanceof InternalWebBrowser) { + InternalWebBrowser browser = (InternalWebBrowser) obj; + IMemento child = memento.createChild("internal"); + browser.save(child); + } else if (obj instanceof ExternalWebBrowser) { + ExternalWebBrowser browser = (ExternalWebBrowser) obj; + IMemento child = memento.createChild("external"); + browser.save(child); + } + } + + memento.putInteger("current", browsers.indexOf(currentBrowser)); + + StringWriter writer = new StringWriter(); + memento.save(writer); + String xmlString = writer.getBuffer().toString(); + Preferences prefs = WebBrowserUIPlugin.getInstance() + .getPluginPreferences(); + prefs.setValue("browsers", xmlString); + WebBrowserUIPlugin.getInstance().savePluginPreferences(); + } catch (Exception e) { + Trace.trace(Trace.SEVERE, "Could not save browsers", e); + } + ignorePreferenceChanges = false; + } + + protected void addInternalBrowser(List browserList) { + if (browserList == null) + return; + + Iterator iterator = browserList.iterator(); + while (iterator.hasNext()) { + IWebBrowser browser = (IWebBrowser) iterator.next(); + if (browser instanceof IInternalWebBrowser) + return; + } + + // add the internal browser if we can + // WebBrowserUIPlugin.getInstance().getLog().log( + // new Status(IStatus.INFO, WebBrowserUIPlugin.PLUGIN_ID, 0, + // WebBrowserUtil.canUseInternalWebBrowser() + "/" + // + WebBrowserUtil.isInternalBrowserOperational(), null)); + // if (!WebBrowserUtil.canUseInternalWebBrowser() || + // !WebBrowserUtil.isInternalBrowserOperational()) + // return; + WebBrowserUIPlugin.getInstance().getLog().log( + new Status(IStatus.INFO, WebBrowserUIPlugin.PLUGIN_ID, 0, "-" + + WebBrowserUtil.isInternalBrowserOperational(), null)); + if (!WebBrowserUtil.isInternalBrowserOperational()) + return; + browserList.add(0, new InternalWebBrowser()); + } + + private void setupDefaultBrowsers() { + browsers = new ArrayList(); + + addInternalBrowser(browsers); + + // handle all the EXTERNAL browsers by criteria and add those too at + // startup + WebBrowserUtil.addFoundBrowsers(browsers); + + // by default, if internal is there, that is current, else set the first + // external one + if (!browsers.isEmpty()) + currentBrowser = (IWebBrowser) browsers.get(0); + } + + protected void addBrowser(IExternalWebBrowser browser) { + if (browsers == null) + loadBrowsers(); + if (!browsers.contains(browser)) + browsers.add(browser); + fireWebBrowserEvent(browser, ADD); + saveBrowsers(); + } + + protected void removeWebBrowser(IExternalWebBrowser browser) { + if (browsers == null) + loadBrowsers(); + browsers.remove(browser); + fireWebBrowserEvent(browser, REMOVE); + } + + // Internal Web browser CAN be "edited", just not created or removed + protected void browserChanged(IWebBrowser browser) { + fireWebBrowserEvent(browser, CHANGE); + saveBrowsers(); + } + + /** + * Add Web browser listener. + * + * @param listener + */ + public void addWebBrowserListener(IWebBrowserListener listener) { + browserListeners.add(listener); + } + + /** + * Remove Web browser listener. + * + * @param listener + */ + public void removeWebBrowserListener(IWebBrowserListener listener) { + browserListeners.remove(listener); + } + + /** + * Fire a Web browser event. + * + * @param browser + * @param type + */ + protected void fireWebBrowserEvent(IWebBrowser browser, int type) { + Object[] obj = browserListeners.toArray(); + + int size = obj.length; + for (int i = 0; i < size; i++) { + IWebBrowserListener listener = (IWebBrowserListener) obj[i]; + if (type == ADD) + listener.browserAdded(browser); + else if (type == CHANGE) + listener.browserChanged(browser); + else if (type == REMOVE) + listener.browserRemoved(browser); + } + } + + public IWebBrowser getCurrentWebBrowser() { + if (browsers == null) + loadBrowsers(); + + return currentBrowser; + } + + public void setCurrentWebBrowser(IWebBrowser wb) { + if (browsers.contains(wb)) + currentBrowser = wb; + saveBrowsers(); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/BrowserSearcher.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/BrowserSearcher.java index 7884159..6e6d30b 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/BrowserSearcher.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/BrowserSearcher.java @@ -1,11 +1,12 @@ package net.sourceforge.phpeclipse.webbrowser.internal; + /********************************************************************** * Copyright (c) 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html -  * + �* * Contributors: * IBM - Initial API and implementation **********************************************************************/ @@ -23,11 +24,13 @@ import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.Shell; + /** * */ public class BrowserSearcher { private static boolean cancelled; + private BrowserSearcher() { super(); } @@ -47,17 +50,17 @@ public class BrowserSearcher { String path = dialog.open(); if (path == null) return null; - + cancelled = false; - + final File rootDir = new File(path); ProgressMonitorDialog pm = new ProgressMonitorDialog(shell); IRunnableWithProgress r = new IRunnableWithProgress() { public void run(IProgressMonitor monitor) { - monitor.beginTask( - WebBrowserUIPlugin.getResource("%searchingTaskName"), - IProgressMonitor.UNKNOWN); + monitor.beginTask(WebBrowserUIPlugin + .getResource("%searchingTaskName"), + IProgressMonitor.UNKNOWN); search(rootDir, existingPaths, foundBrowsers, monitor); monitor.done(); if (monitor.isCanceled()) @@ -68,23 +71,26 @@ public class BrowserSearcher { try { pm.run(true, true, r); } catch (InvocationTargetException e) { - Trace.trace(Trace.SEVERE, "Invocation Exception occured running monitor: " + e); + Trace.trace(Trace.SEVERE, + "Invocation Exception occured running monitor: " + e); } catch (InterruptedException e) { - Trace.trace(Trace.SEVERE, "Interrupted exception occured running monitor: " + e); + Trace.trace(Trace.SEVERE, + "Interrupted exception occured running monitor: " + e); return null; } - + if (cancelled) return null; return foundBrowsers; } - + protected static void setCancelled(boolean b) { cancelled = b; } - protected static void search(File directory, List existingPaths, List foundBrowsers, IProgressMonitor monitor) { + protected static void search(File directory, List existingPaths, + List foundBrowsers, IProgressMonitor monitor) { if (monitor.isCanceled()) return; @@ -96,18 +102,20 @@ public class BrowserSearcher { return; File file = new File(directory, names[i]); - + if (existingPaths.contains(file.getAbsolutePath().toLowerCase())) continue; - IExternalWebBrowserWorkingCopy wc = WebBrowserUtil.createExternalBrowser(file); + IExternalWebBrowserWorkingCopy wc = WebBrowserUtil + .createExternalBrowser(file); if (wc != null) foundBrowsers.add(wc); try { - monitor.subTask( - MessageFormat.format(WebBrowserUIPlugin.getResource("%searching"), - new String[] { Integer.toString(foundBrowsers.size()), file.getCanonicalPath()})); + monitor.subTask(MessageFormat.format(WebBrowserUIPlugin + .getResource("%searching"), new String[] { + Integer.toString(foundBrowsers.size()), + file.getCanonicalPath() })); } catch (IOException ioe) { } diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/BrowserTableComposite.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/BrowserTableComposite.java index c8aeec5..6bab84a 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/BrowserTableComposite.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/BrowserTableComposite.java @@ -4,7 +4,7 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation **********************************************************************/ @@ -40,18 +40,25 @@ import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.ui.PlatformUI; + /** - * + * */ public class BrowserTableComposite extends Composite { protected Table table; + protected CheckboxTableViewer tableViewer; + protected Button edit; + protected Button remove; + protected Button search; + protected IWebBrowser selection; protected Label location; + protected Label parameters; public BrowserTableComposite(Composite parent, int style) { @@ -73,12 +80,15 @@ public class BrowserTableComposite extends Composite { Label label = new Label(this, SWT.NONE); label.setText(WebBrowserUIPlugin.getResource("%browserList")); - data = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_CENTER); + data = new GridData(GridData.FILL_HORIZONTAL + | GridData.VERTICAL_ALIGN_CENTER); data.horizontalSpan = 2; label.setLayoutData(data); - table = new Table(this, SWT.CHECK | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.SINGLE | SWT.FULL_SELECTION); - data = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL); + table = new Table(this, SWT.CHECK | SWT.BORDER | SWT.V_SCROLL + | SWT.H_SCROLL | SWT.SINGLE | SWT.FULL_SELECTION); + data = new GridData(GridData.FILL_HORIZONTAL + | GridData.VERTICAL_ALIGN_FILL); data.widthHint = 300; table.setLayoutData(data); table.setHeaderVisible(false); @@ -98,27 +108,35 @@ public class BrowserTableComposite extends Composite { tableViewer.setInput("root"); - // uncheck any other elements that might be checked and leave only the element checked to - // remain checked since one can only chose one brower at a time to be current. + // uncheck any other elements that might be checked and leave only the + // element checked to + // remain checked since one can only chose one brower at a time to be + // current. tableViewer.addCheckStateListener(new ICheckStateListener() { public void checkStateChanged(CheckStateChangedEvent e) { checkNewDefaultBrowser(e.getElement()); IWebBrowser browser = (IWebBrowser) e.getElement(); BrowserManager.getInstance().setCurrentWebBrowser(browser); - // if no other browsers are checked, don't allow the single one currently - // checked to become unchecked, and lose a current browser. That is, don't - // permit unchecking if no other item is checked which is supposed to be the case. + // if no other browsers are checked, don't allow the single one + // currently + // checked to become unchecked, and lose a current browser. That + // is, don't + // permit unchecking if no other item is checked which is + // supposed to be the case. Object[] obj = tableViewer.getCheckedElements(); - if (obj.length == 0) - tableViewer.setChecked(e.getElement(), true); + if (obj.length == 0) + tableViewer.setChecked(e.getElement(), true); } }); - // set a default, checked browser based on the current browser. If there is not a + // set a default, checked browser based on the current browser. If there + // is not a // current browser, but the first item exists, use that instead. - // This will work currently until workbench shutdown, because current browser is not yet persisted. - IWebBrowser browser = BrowserManager.getInstance().getCurrentWebBrowser(); + // This will work currently until workbench shutdown, because current + // browser is not yet persisted. + IWebBrowser browser = BrowserManager.getInstance() + .getCurrentWebBrowser(); if (browser != null) tableViewer.setChecked(browser, true); else { @@ -127,27 +145,28 @@ public class BrowserTableComposite extends Composite { tableViewer.setChecked(obj, true); } - tableViewer.addSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - Object obj = getSelection(event.getSelection()); - - if (obj instanceof IInternalWebBrowser) { - selection = (IInternalWebBrowser) obj; - remove.setEnabled(false); - edit.setEnabled(true); - } else if (obj instanceof IExternalWebBrowser) { - selection = (IExternalWebBrowser) obj; - remove.setEnabled(true); - edit.setEnabled(true); - } else - selection = null; - - if (selection == null) { - edit.setEnabled(false); - remove.setEnabled(false); - } - } - }); + tableViewer + .addSelectionChangedListener(new ISelectionChangedListener() { + public void selectionChanged(SelectionChangedEvent event) { + Object obj = getSelection(event.getSelection()); + + if (obj instanceof IInternalWebBrowser) { + selection = (IInternalWebBrowser) obj; + remove.setEnabled(false); + edit.setEnabled(true); + } else if (obj instanceof IExternalWebBrowser) { + selection = (IExternalWebBrowser) obj; + remove.setEnabled(true); + edit.setEnabled(true); + } else + selection = null; + + if (selection == null) { + edit.setEnabled(false); + remove.setEnabled(false); + } + } + }); Composite buttonComp = new Composite(this, SWT.NONE); layout = new GridLayout(); @@ -157,99 +176,120 @@ public class BrowserTableComposite extends Composite { layout.marginHeight = 0; layout.numColumns = 1; buttonComp.setLayout(layout); - data = new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.VERTICAL_ALIGN_FILL); + data = new GridData(GridData.HORIZONTAL_ALIGN_END + | GridData.VERTICAL_ALIGN_FILL); buttonComp.setLayoutData(data); - Button add = SWTUtil.createButton(buttonComp, WebBrowserUIPlugin.getResource("%add")); + Button add = SWTUtil.createButton(buttonComp, WebBrowserUIPlugin + .getResource("%add")); add.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { - ExternalBrowserDialog dialog = new ExternalBrowserDialog(getShell()); + ExternalBrowserDialog dialog = new ExternalBrowserDialog( + getShell()); if (dialog.open() == Window.CANCEL) return; tableViewer.refresh(); } }); - edit = SWTUtil.createButton(buttonComp, WebBrowserUIPlugin.getResource("%edit")); + edit = SWTUtil.createButton(buttonComp, WebBrowserUIPlugin + .getResource("%edit")); edit.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { IWebBrowser browser2 = getSelectedWebBrowser(); if (browser2 instanceof IInternalWebBrowser) { - IInternalWebBrowserWorkingCopy wc = ((IInternalWebBrowser) browser2).getWorkingCopy(); - InternalBrowserDialog dialog = new InternalBrowserDialog(getShell(), wc); + IInternalWebBrowserWorkingCopy wc = ((IInternalWebBrowser) browser2) + .getWorkingCopy(); + InternalBrowserDialog dialog = new InternalBrowserDialog( + getShell(), wc); if (dialog.open() != Window.CANCEL) { try { tableViewer.refresh(wc.save()); - } catch (Exception ex) { } + } catch (Exception ex) { + } } - } - else if(browser2 instanceof IExternalWebBrowser) { - IExternalWebBrowserWorkingCopy wc = ((IExternalWebBrowser) browser2).getWorkingCopy(); - ExternalBrowserDialog dialog = new ExternalBrowserDialog(getShell(), wc); + } else if (browser2 instanceof IExternalWebBrowser) { + IExternalWebBrowserWorkingCopy wc = ((IExternalWebBrowser) browser2) + .getWorkingCopy(); + ExternalBrowserDialog dialog = new ExternalBrowserDialog( + getShell(), wc); if (dialog.open() != Window.CANCEL) { try { tableViewer.refresh(wc.save()); - } catch (Exception ex) { } + } catch (Exception ex) { + } } } - } + } }); edit.setEnabled(false); - remove = SWTUtil.createButton(buttonComp, WebBrowserUIPlugin.getResource("%remove")); + remove = SWTUtil.createButton(buttonComp, WebBrowserUIPlugin + .getResource("%remove")); remove.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { IWebBrowser browser2 = getSelectedWebBrowser(); try { - if (browser2 instanceof IInternalWebBrowser){ + if (browser2 instanceof IInternalWebBrowser) { remove.setEnabled(false); return; // nothing else possible to do - } - else if(browser2 instanceof IExternalWebBrowser) { + } else if (browser2 instanceof IExternalWebBrowser) { remove.setEnabled(true); - ((IExternalWebBrowser) browser2).delete(); + ((IExternalWebBrowser) browser2).delete(); tableViewer.remove(browser2); - // need here to ensure that if the item deleted was checked, ie, was - // the current browser, that the new current browser will be the first in the - // list, typically, the internal browser, which cannot be deleted, and be current. - if(((IExternalWebBrowser) browser2) == BrowserManager.getInstance().getCurrentWebBrowser()){ + // need here to ensure that if the item deleted was + // checked, ie, was + // the current browser, that the new current browser + // will be the first in the + // list, typically, the internal browser, which cannot + // be deleted, and be current. + if (((IExternalWebBrowser) browser2) == BrowserManager + .getInstance().getCurrentWebBrowser()) { Object obj = tableViewer.getElementAt(0); - if(obj != null){ - BrowserManager.getInstance().setCurrentWebBrowser((InternalWebBrowser)obj); - tableViewer.setChecked(obj, true); - } + if (obj != null) { + BrowserManager.getInstance() + .setCurrentWebBrowser( + (InternalWebBrowser) obj); + tableViewer.setChecked(obj, true); + } } } - } catch (Exception ex) { } + } catch (Exception ex) { + } } }); remove.setEnabled(false); - search = SWTUtil.createButton(buttonComp, WebBrowserUIPlugin.getResource("%search")); + search = SWTUtil.createButton(buttonComp, WebBrowserUIPlugin + .getResource("%search")); search.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { - java.util.List browsersToCreate = BrowserSearcher.search(getShell()); + java.util.List browsersToCreate = BrowserSearcher + .search(getShell()); if (browsersToCreate == null) // cancelled return; if (browsersToCreate.isEmpty()) { // no browsers found - WebBrowserUtil.openMessage(WebBrowserUIPlugin.getResource("%searchingNoneFound")); + WebBrowserUtil.openMessage(WebBrowserUIPlugin + .getResource("%searchingNoneFound")); return; } Iterator iterator = browsersToCreate.iterator(); while (iterator.hasNext()) { - IExternalWebBrowserWorkingCopy browser2 = (IExternalWebBrowserWorkingCopy) iterator.next(); + IExternalWebBrowserWorkingCopy browser2 = (IExternalWebBrowserWorkingCopy) iterator + .next(); browser2.save(); } tableViewer.refresh(); } }); - PlatformUI.getWorkbench().getHelpSystem().setHelp(search, ContextIds.PREF_BROWSER_EXTERNAL_SEARCH); + PlatformUI.getWorkbench().getHelpSystem().setHelp(search, + ContextIds.PREF_BROWSER_EXTERNAL_SEARCH); tableViewer.addCheckStateListener(new ICheckStateListener() { public void checkStateChanged(CheckStateChangedEvent e) { diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/BrowserTableLabelProvider.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/BrowserTableLabelProvider.java index bdbc77c..05904ad 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/BrowserTableLabelProvider.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/BrowserTableLabelProvider.java @@ -4,7 +4,7 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation **********************************************************************/ @@ -17,6 +17,7 @@ import net.sourceforge.phpeclipse.webbrowser.IWebBrowser; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.swt.graphics.Image; + /** * Web browser table label provider. */ @@ -31,12 +32,14 @@ public class BrowserTableLabelProvider implements ITableLabelProvider { /** * */ - public void addListener(ILabelProviderListener listener) { } + public void addListener(ILabelProviderListener listener) { + } /** * */ - public void dispose() { } + public void dispose() { + } /** * @@ -44,37 +47,40 @@ public class BrowserTableLabelProvider implements ITableLabelProvider { public Image getColumnImage(Object element, int columnIndex) { if (columnIndex == 0) { if (element instanceof IInternalWebBrowser) - return ImageResource.getImage(ImageResource.IMG_INTERNAL_BROWSER); + return ImageResource + .getImage(ImageResource.IMG_INTERNAL_BROWSER); else - return ImageResource.getImage(ImageResource.IMG_EXTERNAL_BROWSER); + return ImageResource + .getImage(ImageResource.IMG_EXTERNAL_BROWSER); } return null; } /** * Returns the label text for the given column of the given element. - * - * @param element the object representing the entire row, or - * null indicating that no input object is set - * in the viewer - * @param columnIndex the zero-based index of the column in which the label appears + * + * @param element + * the object representing the entire row, or null + * indicating that no input object is set in the viewer + * @param columnIndex + * the zero-based index of the column in which the label appears */ public String getColumnText(Object element, int columnIndex) { - IWebBrowser browser = (IWebBrowser)element; + IWebBrowser browser = (IWebBrowser) element; if (browser instanceof IExternalWebBrowser) { if (columnIndex == 0) - return notNull(((IExternalWebBrowser)browser).getName()); + return notNull(((IExternalWebBrowser) browser).getName()); else if (columnIndex == 1) - return notNull(((IExternalWebBrowser)browser).getLocation()); + return notNull(((IExternalWebBrowser) browser).getLocation()); else if (columnIndex == 2) - return notNull(((IExternalWebBrowser)browser).getParameters()); - } else if(browser instanceof IInternalWebBrowser) { + return notNull(((IExternalWebBrowser) browser).getParameters()); + } else if (browser instanceof IInternalWebBrowser) { if (columnIndex == 0) - return notNull(((IInternalWebBrowser)browser).getName()); + return notNull(((IInternalWebBrowser) browser).getName()); } return ""; } - + protected String notNull(String s) { if (s != null) return s; @@ -92,5 +98,6 @@ public class BrowserTableLabelProvider implements ITableLabelProvider { /** * */ - public void removeListener(ILabelProviderListener listener) { } + public void removeListener(ILabelProviderListener listener) { + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/BusyIndicator.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/BusyIndicator.java index 1b4caa2..958eba1 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/BusyIndicator.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/BusyIndicator.java @@ -1,10 +1,10 @@ /** * Copyright (c) 2003 IBM Corporation and others. - * All rights reserved.   This program and the accompanying materials + * All rights reserved. � This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation */ @@ -19,49 +19,56 @@ import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; + /** * An animated image to show busy status of the Web browser. */ public class BusyIndicator extends Canvas { protected Image[] images; + protected Image image; protected Thread busyThread; + protected boolean stop; /** * BusyWidget constructor comment. - * @param parent org.eclipse.swt.widgets.Composite - * @param style int + * + * @param parent + * org.eclipse.swt.widgets.Composite + * @param style + * int */ public BusyIndicator(Composite parent, int style) { super(parent, style); - + images = ImageResource.getBusyImages(); - + addPaintListener(new PaintListener() { public void paintControl(PaintEvent event) { onPaint(event); } }); - + image = images[0]; } - + public Point computeSize(int wHint, int hHint, boolean changed) { return new Point(25, 25); } - + /** * Creates a thread to animate the image. */ protected synchronized void createBusyThread() { if (busyThread != null) return; - + stop = false; busyThread = new Thread() { protected int count; + public void run() { try { count = 1; @@ -79,7 +86,8 @@ public class BusyIndicator extends Canvas { }); try { sleep(125); - } catch (Exception e) { } + } catch (Exception e) { + } } if (busyThread == null) Display.getDefault().syncExec(new Thread() { @@ -92,18 +100,18 @@ public class BusyIndicator extends Canvas { } } }; - + busyThread.setPriority(Thread.NORM_PRIORITY + 2); busyThread.setDaemon(true); busyThread.start(); } - + public void dispose() { stop = true; busyThread = null; super.dispose(); } - + /** * Return the image or null. */ @@ -113,21 +121,21 @@ public class BusyIndicator extends Canvas { /** * Returns true if it is currently busy. - * + * * @return boolean */ public boolean isBusy() { return (busyThread != null); } - /* + /* * Process the paint event */ protected void onPaint(PaintEvent event) { Rectangle rect = getClientArea(); if (rect.width == 0 || rect.height == 0) return; - + GC gc = event.gc; if (image != null) gc.drawImage(image, 2, 2); @@ -135,8 +143,9 @@ public class BusyIndicator extends Canvas { /** * Sets the indicators busy count up (true) or down (false) one. - * - * @param busy boolean + * + * @param busy + * boolean */ public synchronized void setBusy(boolean busy) { if (busy) { @@ -151,8 +160,7 @@ public class BusyIndicator extends Canvas { } /** - * Set the image. - * The value null clears it. + * Set the image. The value null clears it. */ public void setImage(Image image) { if (image != this.image && !isDisposed()) { diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/ContextIds.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/ContextIds.java index dbfb19e..613ede8 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/ContextIds.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/ContextIds.java @@ -1,25 +1,40 @@ /** * Copyright (c) 2003 IBM Corporation and others. - * All rights reserved.   This program and the accompanying materials + * All rights reserved. � This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation */ package net.sourceforge.phpeclipse.webbrowser.internal; + /** * Context help id constants. */ public interface ContextIds { - public static final String PREF_BROWSER = WebBrowserUIPlugin.PLUGIN_ID + ".wbpr0000"; - public static final String PREF_BROWSER_INTERNAL = WebBrowserUIPlugin.PLUGIN_ID + ".wbpr0002"; - public static final String PREF_BROWSER_EXTERNAL_ADD = WebBrowserUIPlugin.PLUGIN_ID + ".wbpr0004"; - public static final String PREF_BROWSER_EXTERNAL_EDIT = WebBrowserUIPlugin.PLUGIN_ID + ".wbpr0005"; - public static final String PREF_BROWSER_EXTERNAL_SEARCH = WebBrowserUIPlugin.PLUGIN_ID + ".wbpr0006"; - - public static final String WEB_BROWSER = WebBrowserUIPlugin.PLUGIN_ID + ".sewb0000"; - public static final String WEB_BROWSER_URL = WebBrowserUIPlugin.PLUGIN_ID + ".sewb0002"; - public static final String WEB_BROWSER_WEB = WebBrowserUIPlugin.PLUGIN_ID + ".sewb0004"; + public static final String PREF_BROWSER = WebBrowserUIPlugin.PLUGIN_ID + + ".wbpr0000"; + + public static final String PREF_BROWSER_INTERNAL = WebBrowserUIPlugin.PLUGIN_ID + + ".wbpr0002"; + + public static final String PREF_BROWSER_EXTERNAL_ADD = WebBrowserUIPlugin.PLUGIN_ID + + ".wbpr0004"; + + public static final String PREF_BROWSER_EXTERNAL_EDIT = WebBrowserUIPlugin.PLUGIN_ID + + ".wbpr0005"; + + public static final String PREF_BROWSER_EXTERNAL_SEARCH = WebBrowserUIPlugin.PLUGIN_ID + + ".wbpr0006"; + + public static final String WEB_BROWSER = WebBrowserUIPlugin.PLUGIN_ID + + ".sewb0000"; + + public static final String WEB_BROWSER_URL = WebBrowserUIPlugin.PLUGIN_ID + + ".sewb0002"; + + public static final String WEB_BROWSER_WEB = WebBrowserUIPlugin.PLUGIN_ID + + ".sewb0004"; } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/ExternalBrowserDialog.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/ExternalBrowserDialog.java index 4b3b9c9..2c42ad3 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/ExternalBrowserDialog.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/ExternalBrowserDialog.java @@ -4,7 +4,7 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation **********************************************************************/ @@ -31,18 +31,27 @@ import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.PlatformUI; + /** - * + * */ public class ExternalBrowserDialog extends Dialog { protected IExternalWebBrowserWorkingCopy browser; + protected boolean isEdit; + protected Button newPageCheckbox; + protected Button clearHistoryCheckbox; + protected Button browseButton; + protected Text browserNameTextfield; + protected Text browserLocationTextfield; + protected Text browserParametersTextfield; + private Button okButton; interface StringModifyListener { @@ -52,7 +61,8 @@ public class ExternalBrowserDialog extends Dialog { /** * @param parentShell */ - public ExternalBrowserDialog(Shell parentShell, IExternalWebBrowserWorkingCopy browser) { + public ExternalBrowserDialog(Shell parentShell, + IExternalWebBrowserWorkingCopy browser) { super(parentShell); this.browser = browser; isEdit = true; @@ -68,16 +78,19 @@ public class ExternalBrowserDialog extends Dialog { super.configureShell(shell); if (isEdit) - shell.setText(WebBrowserUIPlugin.getResource("%editExternalBrowser")); + shell.setText(WebBrowserUIPlugin + .getResource("%editExternalBrowser")); else shell.setText(WebBrowserUIPlugin.getResource("%createBrowser")); } - protected Text createText(Composite comp, String txt, final StringModifyListener listener) { + protected Text createText(Composite comp, String txt, + final StringModifyListener listener) { final Text text = new Text(comp, SWT.BORDER); if (txt != null) text.setText(txt); - GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_BEGINNING); + GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL + | GridData.VERTICAL_ALIGN_BEGINNING); data.widthHint = 250; text.setLayoutData(data); if (listener != null) @@ -89,41 +102,51 @@ public class ExternalBrowserDialog extends Dialog { return text; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite) */ protected Control createDialogArea(Composite parent) { Composite composite = (Composite) super.createDialogArea(parent); - ((GridLayout)composite.getLayout()).numColumns = 3; + ((GridLayout) composite.getLayout()).numColumns = 3; if (isEdit) - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, ContextIds.PREF_BROWSER_EXTERNAL_EDIT); + PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, + ContextIds.PREF_BROWSER_EXTERNAL_EDIT); else - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, ContextIds.PREF_BROWSER_EXTERNAL_ADD); + PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, + ContextIds.PREF_BROWSER_EXTERNAL_ADD); SWTUtil.createLabel(composite, WebBrowserUIPlugin.getResource("%name")); - browserNameTextfield = createText(composite, browser.getName(), new StringModifyListener() { - public void valueChanged(String s) { - browser.setName(s); - validateFields(); - } - }); + browserNameTextfield = createText(composite, browser.getName(), + new StringModifyListener() { + public void valueChanged(String s) { + browser.setName(s); + validateFields(); + } + }); new Label(composite, SWT.NONE); - SWTUtil.createLabel(composite, WebBrowserUIPlugin.getResource("%location")); - browserLocationTextfield = createText(composite, browser.getLocation(), new StringModifyListener() { - public void valueChanged(String s) { - browser.setLocation(s); - validateFields(); - } - }); - - browseButton = SWTUtil.createButton(composite, WebBrowserUIPlugin.getResource("%browse")); + SWTUtil.createLabel(composite, WebBrowserUIPlugin + .getResource("%location")); + browserLocationTextfield = createText(composite, browser.getLocation(), + new StringModifyListener() { + public void valueChanged(String s) { + browser.setLocation(s); + validateFields(); + } + }); + + browseButton = SWTUtil.createButton(composite, WebBrowserUIPlugin + .getResource("%browse")); browseButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { FileDialog dialog = new FileDialog(getShell(), SWT.OPEN); - dialog.setText(WebBrowserUIPlugin.getResource("%browseMessage")); + dialog + .setText(WebBrowserUIPlugin + .getResource("%browseMessage")); String fname = browserLocationTextfield.getText(); @@ -135,8 +158,10 @@ public class ExternalBrowserDialog extends Dialog { } }); - SWTUtil.createLabel(composite, WebBrowserUIPlugin.getResource("%parameters")); - browserParametersTextfield = createText(composite, browser.getParameters(), new StringModifyListener() { + SWTUtil.createLabel(composite, WebBrowserUIPlugin + .getResource("%parameters")); + browserParametersTextfield = createText(composite, browser + .getParameters(), new StringModifyListener() { public void valueChanged(String s) { browser.setParameters(s); } @@ -146,26 +171,30 @@ public class ExternalBrowserDialog extends Dialog { new Label(composite, SWT.NONE); Label urlLabel = new Label(composite, SWT.NONE); - urlLabel.setText(WebBrowserUIPlugin.getResource("%parametersMessage", WebBrowserPreference.URL_PARAMETER)); - + urlLabel.setText(WebBrowserUIPlugin.getResource("%parametersMessage", + WebBrowserPreference.URL_PARAMETER)); return composite; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.dialogs.Dialog#okPressed() */ protected void okPressed() { - // do simple field validation to at least ensure target directory entered is valid pathname + // do simple field validation to at least ensure target directory + // entered is valid pathname try { - File file = new File(browser.getLocation()); - if(!file.isFile()){ - WebBrowserUtil.openError(WebBrowserUIPlugin.getResource("%locationInvalid")); + File file = new File(browser.getLocation()); + if (!file.isFile()) { + WebBrowserUtil.openError(WebBrowserUIPlugin + .getResource("%locationInvalid")); return; } - } - catch(Exception e){ - WebBrowserUtil.openError(WebBrowserUIPlugin.getResource("%locationInvalid")); + } catch (Exception e) { + WebBrowserUtil.openError(WebBrowserUIPlugin + .getResource("%locationInvalid")); return; } diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/ExternalWebBrowser.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/ExternalWebBrowser.java index 10e5086..879aea1 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/ExternalWebBrowser.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/ExternalWebBrowser.java @@ -7,39 +7,50 @@ import net.sourceforge.phpeclipse.webbrowser.IExternalWebBrowserWorkingCopy; import org.eclipse.swt.program.Program; import org.eclipse.ui.IMemento; + /** * */ public class ExternalWebBrowser implements IExternalWebBrowser { private static final String MEMENTO_NAME = "name"; + private static final String MEMENTO_LOCATION = "location"; + private static final String MEMENTO_PARAMETERS = "parameters"; protected String name; + protected String location; + protected String parameters; - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see net.sourceforge.phpeclipse.webbrowser.IWebBrowser#getName() */ public String getName() { return name; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpeclipse.webbrowser.IExternalWebBrowser#getLocation() */ public String getLocation() { return location; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpeclipse.webbrowser.IExternalWebBrowser#getParameters() */ public String getParameters() { return parameters; } - + public void delete() { BrowserManager.getInstance().removeWebBrowser(this); } @@ -58,12 +69,14 @@ public class ExternalWebBrowser implements IExternalWebBrowser { parameters = browser.getParameters(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpeclipse.webbrowser.IWebBrowser#openURL(java.net.URL) */ public void openURL(URL url) { String urlText = WebBrowserPreference.getHomePageURL(); - + if (url != null) urlText = url.toExternalForm(); else if (urlText.startsWith("file:") & urlText.length() > 6) { @@ -75,12 +88,14 @@ public class ExternalWebBrowser implements IExternalWebBrowser { if (!WebBrowserUtil.isWindows()) { int index = urlText.indexOf(" "); while (index >= 0) { - urlText = urlText.substring(0, index) + "%20" + urlText.substring(index + 1); + urlText = urlText.substring(0, index) + "%20" + + urlText.substring(index + 1); index = urlText.indexOf(" "); } } - Trace.trace(Trace.FINEST, "Launching external Web browser: " + location + " - " + parameters + " - " + urlText); + Trace.trace(Trace.FINEST, "Launching external Web browser: " + location + + " - " + parameters + " - " + urlText); if (location == null || location.length() == 0) { try { String extension = null; @@ -94,31 +109,39 @@ public class ExternalWebBrowser implements IExternalWebBrowser { Program program = Program.findProgram(extension); program.execute(urlText); } catch (Exception e) { - Trace.trace(Trace.SEVERE, "Error launching default external browser", e); - WebBrowserUtil.openError(WebBrowserUIPlugin.getResource("%errorCouldNotLaunchWebBrowser", urlText)); + Trace.trace(Trace.SEVERE, + "Error launching default external browser", e); + WebBrowserUtil.openError(WebBrowserUIPlugin.getResource( + "%errorCouldNotLaunchWebBrowser", urlText)); } return; } - + String params = parameters; if (params == null) params = ""; - + int urlIndex = params.indexOf(WebBrowserPreference.URL_PARAMETER); if (urlIndex >= 0) - params = params.substring(0, urlIndex) + " " + urlText + " " + params.substring(urlIndex + WebBrowserPreference.URL_PARAMETER.length()); + params = params.substring(0, urlIndex) + + " " + + urlText + + " " + + params.substring(urlIndex + + WebBrowserPreference.URL_PARAMETER.length()); else { if (!params.endsWith(" ")) params += " "; params += urlText; } - + try { Trace.trace(Trace.FINEST, "Launching " + location + " " + params); Runtime.getRuntime().exec(location + " " + params); } catch (Exception e) { Trace.trace(Trace.SEVERE, "Could not launch external browser", e); - WebBrowserUtil.openError(WebBrowserUIPlugin.getResource("%errorCouldNotLaunchWebBrowser", urlText)); + WebBrowserUtil.openError(WebBrowserUIPlugin.getResource( + "%errorCouldNotLaunchWebBrowser", urlText)); } } @@ -135,6 +158,7 @@ public class ExternalWebBrowser implements IExternalWebBrowser { } public String toString() { - return "External Web browser: " + getName() + " / " + getLocation() + " / " + getParameters(); + return "External Web browser: " + getName() + " / " + getLocation() + + " / " + getParameters(); } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/ExternalWebBrowserWorkingCopy.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/ExternalWebBrowserWorkingCopy.java index c3ef3c7..6f4c213 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/ExternalWebBrowserWorkingCopy.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/ExternalWebBrowserWorkingCopy.java @@ -2,14 +2,17 @@ package net.sourceforge.phpeclipse.webbrowser.internal; import net.sourceforge.phpeclipse.webbrowser.IExternalWebBrowser; import net.sourceforge.phpeclipse.webbrowser.IExternalWebBrowserWorkingCopy; + /** * */ -public class ExternalWebBrowserWorkingCopy extends ExternalWebBrowser implements IExternalWebBrowserWorkingCopy { +public class ExternalWebBrowserWorkingCopy extends ExternalWebBrowser implements + IExternalWebBrowserWorkingCopy { protected ExternalWebBrowser browser; // creation - public ExternalWebBrowserWorkingCopy() { } + public ExternalWebBrowserWorkingCopy() { + } // working copy public ExternalWebBrowserWorkingCopy(ExternalWebBrowser browser) { @@ -17,21 +20,27 @@ public class ExternalWebBrowserWorkingCopy extends ExternalWebBrowser implements setInternal(browser); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpeclipse.webbrowser.IExternalWebBrowserWorkingCopy#setName(java.lang.String) */ public void setName(String name) { this.name = name; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpeclipse.webbrowser.IExternalWebBrowserWorkingCopy#setLocation(java.lang.String) */ public void setLocation(String location) { this.location = location; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpeclipse.webbrowser.IExternalWebBrowserWorkingCopy#setParameters(java.lang.String) */ public void setParameters(String params) { @@ -41,12 +50,14 @@ public class ExternalWebBrowserWorkingCopy extends ExternalWebBrowser implements public boolean isWorkingCopy() { return true; } - + public IExternalWebBrowserWorkingCopy getWorkingCopy() { return this; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpeclipse.webbrowser.IExternalWebBrowserWorkingCopy#save() */ public IExternalWebBrowser save() { diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/Favorite.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/Favorite.java index 1009eff..41aface 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/Favorite.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/Favorite.java @@ -1,23 +1,26 @@ /** * Copyright (c) 2003 IBM Corporation and others. - * All rights reserved.   This program and the accompanying materials + * All rights reserved. � This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation */ package net.sourceforge.phpeclipse.webbrowser.internal; + /** * */ public class Favorite { protected String url; + protected String name; - public Favorite() { } - + public Favorite() { + } + public Favorite(String name, String url) { if (name == null) name = ""; @@ -42,15 +45,15 @@ public class Favorite { public void setURL(String url) { this.url = url; } - + public boolean equals(Object obj) { if (!(obj instanceof Favorite)) return false; - + Favorite f = (Favorite) obj; return (name.equals(f.name) && url.equals(f.url)); } - + public String toString() { return "(" + name + "/" + url + ")"; } diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/IWebBrowserListener.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/IWebBrowserListener.java index 97e20dc..5f3cf12 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/IWebBrowserListener.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/IWebBrowserListener.java @@ -4,7 +4,7 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation **********************************************************************/ @@ -17,8 +17,8 @@ import net.sourceforge.phpeclipse.webbrowser.IWebBrowser; */ public interface IWebBrowserListener { public void browserAdded(IWebBrowser browser); - + public void browserChanged(IWebBrowser browser); - + public void browserRemoved(IWebBrowser browser); } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/ImageResource.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/ImageResource.java index 5548430..259085d 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/ImageResource.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/ImageResource.java @@ -1,10 +1,10 @@ /** * Copyright (c) 2003 IBM Corporation and others. - * All rights reserved.   This program and the accompanying materials + * All rights reserved. � This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation */ @@ -17,6 +17,7 @@ import java.util.Map; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.swt.graphics.Image; + /** * Utility class to handle image resources. */ @@ -34,7 +35,8 @@ public class ImageResource { static { try { String pathSuffix = "icons/"; - ICON_BASE_URL = WebBrowserUIPlugin.getInstance().getBundle().getEntry(pathSuffix); + ICON_BASE_URL = WebBrowserUIPlugin.getInstance().getBundle() + .getEntry(pathSuffix); } catch (Exception e) { Trace.trace(Trace.SEVERE, "Could not set icon base URL", e); } @@ -43,7 +45,9 @@ public class ImageResource { private static Image[] busyImages; private static final String URL_CLCL = "clcl16/"; + private static final String URL_ELCL = "elcl16/"; + private static final String URL_DLCL = "dlcl16/"; private static final String URL_OBJ = "obj16/"; @@ -51,45 +55,69 @@ public class ImageResource { // --- constants for images --- // toolbar images public static final String IMG_CLCL_NAV_BACKWARD = "IMG_CLCL_NAV_BACKWARD"; + public static final String IMG_CLCL_NAV_FORWARD = "IMG_CLCL_NAV_FORWARD"; + public static final String IMG_CLCL_NAV_STOP = "IMG_CLCL_NAV_STOP"; + public static final String IMG_CLCL_NAV_REFRESH = "IMG_CLCL_NAV_REFRESH"; + public static final String IMG_CLCL_NAV_GO = "IMG_CLCL_NAV_GO"; + public static final String IMG_CLCL_NAV_FAVORITES = "cfavorites"; + public static final String IMG_CLCL_NAV_HOME = "IMG_CLCL_NAV_HOME"; + public static final String IMG_CLCL_NAV_PRINT = "IMG_CLCL_NAV_PRINT"; public static final String IMG_ELCL_NAV_BACKWARD = "IMG_ELCL_NAV_BACKWARD"; + public static final String IMG_ELCL_NAV_FORWARD = "IMG_ELCL_NAV_FORWARD"; + public static final String IMG_ELCL_NAV_STOP = "IMG_ELCL_NAV_STOP"; + public static final String IMG_ELCL_NAV_REFRESH = "IMG_ELCL_NAV_REFRESH"; + public static final String IMG_ELCL_NAV_GO = "IMG_ELCL_NAV_GO"; + public static final String IMG_ELCL_NAV_FAVORITES = "efavorites"; + public static final String IMG_ELCL_NAV_HOME = "IMG_ELCL_NAV_HOME"; + public static final String IMG_ELCL_NAV_PRINT = "IMG_ELCL_NAV_PRINT"; public static final String IMG_DLCL_NAV_BACKWARD = "IMG_DLCL_NAV_BACKWARD"; + public static final String IMG_DLCL_NAV_FORWARD = "IMG_DLCL_NAV_FORWARD"; + public static final String IMG_DLCL_NAV_STOP = "IMG_DLCL_NAV_STOP"; + public static final String IMG_DLCL_NAV_REFRESH = "IMG_DLCL_NAV_REFRESH"; + public static final String IMG_DLCL_NAV_GO = "IMG_DLCL_NAV_GO"; + public static final String IMG_DLCL_NAV_FAVORITES = "dfavorites"; + public static final String IMG_DLCL_NAV_HOME = "IMG_DLCL_NAV_HOME"; + public static final String IMG_DLCL_NAV_PRINT = "IMG_DLCL_NAV_PRINT"; // general object images public static final String IMG_INTERNAL_BROWSER = "internalBrowser"; + public static final String IMG_EXTERNAL_BROWSER = "externalBrowser"; + public static final String IMG_FAVORITE = "favorite"; /** * Cannot construct an ImageResource. Use static methods only. */ - private ImageResource() { } + private ImageResource() { + } /** * Returns the busy images for the Web browser. - * + * * @return org.eclipse.swt.graphics.Image[] */ public static Image[] getBusyImages() { @@ -98,8 +126,9 @@ public class ImageResource { /** * Return the image with the given key. - * - * @param key java.lang.String + * + * @param key + * java.lang.String * @return org.eclipse.swt.graphics.Image */ public static Image getImage(String key) { @@ -110,8 +139,9 @@ public class ImageResource { /** * Return the image descriptor with the given key. - * - * @param key java.lang.String + * + * @param key + * java.lang.String * @return org.eclipse.jface.resource.ImageDescriptor */ public static ImageDescriptor getImageDescriptor(String key) { @@ -126,7 +156,7 @@ public class ImageResource { protected static void initializeImageRegistry() { imageRegistry = new ImageRegistry(); imageDescriptors = new HashMap(); - + // load Web browser images registerImage(IMG_ELCL_NAV_BACKWARD, URL_ELCL + "nav_backward.gif"); registerImage(IMG_ELCL_NAV_FORWARD, URL_ELCL + "nav_forward.gif"); @@ -136,7 +166,7 @@ public class ImageResource { registerImage(IMG_ELCL_NAV_FAVORITES, URL_ELCL + "add_favorite.gif"); registerImage(IMG_ELCL_NAV_HOME, URL_ELCL + "nav_home.gif"); registerImage(IMG_ELCL_NAV_PRINT, URL_ELCL + "nav_print.gif"); - + registerImage(IMG_CLCL_NAV_BACKWARD, URL_CLCL + "nav_backward.gif"); registerImage(IMG_CLCL_NAV_FORWARD, URL_CLCL + "nav_forward.gif"); registerImage(IMG_CLCL_NAV_STOP, URL_CLCL + "nav_stop.gif"); @@ -145,7 +175,7 @@ public class ImageResource { registerImage(IMG_CLCL_NAV_FAVORITES, URL_CLCL + "add_favorite.gif"); registerImage(IMG_CLCL_NAV_HOME, URL_CLCL + "nav_home.gif"); registerImage(IMG_CLCL_NAV_PRINT, URL_CLCL + "nav_print.gif"); - + registerImage(IMG_DLCL_NAV_BACKWARD, URL_DLCL + "nav_backward.gif"); registerImage(IMG_DLCL_NAV_FORWARD, URL_DLCL + "nav_forward.gif"); registerImage(IMG_DLCL_NAV_STOP, URL_DLCL + "nav_stop.gif"); @@ -154,33 +184,38 @@ public class ImageResource { registerImage(IMG_DLCL_NAV_FAVORITES, URL_DLCL + "add_favorite.gif"); registerImage(IMG_DLCL_NAV_HOME, URL_DLCL + "nav_home.gif"); registerImage(IMG_DLCL_NAV_PRINT, URL_DLCL + "nav_print.gif"); - + registerImage(IMG_INTERNAL_BROWSER, URL_OBJ + "internal_browser.gif"); registerImage(IMG_EXTERNAL_BROWSER, URL_OBJ + "external_browser.gif"); - + registerImage(IMG_FAVORITE, URL_OBJ + "favorite.gif"); - + // busy images busyImages = new Image[13]; for (int i = 0; i < 13; i++) { - registerImage("busy" + i, URL_OBJ + "frames" + java.io.File.separator + "frame" + (i+1) + ".gif"); + registerImage("busy" + i, URL_OBJ + "frames" + + java.io.File.separator + "frame" + (i + 1) + ".gif"); busyImages[i] = getImage("busy" + i); } } /** * Register an image with the registry. - * - * @param key java.lang.String - * @param partialURL java.lang.String + * + * @param key + * java.lang.String + * @param partialURL + * java.lang.String */ private static void registerImage(String key, String partialURL) { try { - ImageDescriptor id = ImageDescriptor.createFromURL(new URL(ICON_BASE_URL, partialURL)); + ImageDescriptor id = ImageDescriptor.createFromURL(new URL( + ICON_BASE_URL, partialURL)); imageRegistry.put(key, id); imageDescriptors.put(key, id); } catch (Exception e) { - Trace.trace(Trace.WARNING, "Error registering image " + key + " from " + partialURL, e); + Trace.trace(Trace.WARNING, "Error registering image " + key + + " from " + partialURL, e); } } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/InternalBrowserDialog.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/InternalBrowserDialog.java index e0261e8..75f74e3 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/InternalBrowserDialog.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/InternalBrowserDialog.java @@ -4,7 +4,7 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation **********************************************************************/ @@ -21,19 +21,24 @@ import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.PlatformUI; + /** - * + * */ public class InternalBrowserDialog extends Dialog { protected IInternalWebBrowserWorkingCopy browser; + protected boolean isEdit; + protected Button newPageCheckbox; + protected Button clearURLHistoryCheckbox; /** * @param parentShell */ - public InternalBrowserDialog(Shell parentShell, IInternalWebBrowserWorkingCopy browser) { + public InternalBrowserDialog(Shell parentShell, + IInternalWebBrowserWorkingCopy browser) { super(parentShell); this.browser = browser; isEdit = true; @@ -43,15 +48,18 @@ public class InternalBrowserDialog extends Dialog { super.configureShell(shell); if (isEdit) - shell.setText(WebBrowserUIPlugin.getResource("%editInternalBrowser")); + shell.setText(WebBrowserUIPlugin + .getResource("%editInternalBrowser")); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite) */ protected Control createDialogArea(Composite parent) { Composite composite = (Composite) super.createDialogArea(parent); - ((GridLayout)composite.getLayout()).numColumns = 1; + ((GridLayout) composite.getLayout()).numColumns = 1; Composite comp = new Composite(composite, SWT.NONE); GridLayout layout = new GridLayout(1, true); @@ -59,10 +67,13 @@ public class InternalBrowserDialog extends Dialog { layout.marginWidth = 10; comp.setLayout(layout); comp.setLayoutData(new GridData(GridData.FILL_BOTH)); - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, ContextIds.PREF_BROWSER_INTERNAL); + PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, + ContextIds.PREF_BROWSER_INTERNAL); - newPageCheckbox = SWTUtil.createCheckbox(comp, WebBrowserUIPlugin.getResource("%prefBrowserNewPage"), false); - clearURLHistoryCheckbox = SWTUtil.createCheckbox(comp, WebBrowserUIPlugin.getResource("%clearURLHistory"), true); + newPageCheckbox = SWTUtil.createCheckbox(comp, WebBrowserUIPlugin + .getResource("%prefBrowserNewPage"), false); + clearURLHistoryCheckbox = SWTUtil.createCheckbox(comp, + WebBrowserUIPlugin.getResource("%clearURLHistory"), true); newPageCheckbox.setSelection(browser.getUseNewPage()); clearURLHistoryCheckbox.setSelection(browser.getClearHistoryOnExit()); @@ -70,7 +81,9 @@ public class InternalBrowserDialog extends Dialog { return composite; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.dialogs.Dialog#okPressed() */ protected void okPressed() { diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/InternalWebBrowser.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/InternalWebBrowser.java index 05a02ac..de5958b 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/InternalWebBrowser.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/InternalWebBrowser.java @@ -7,31 +7,36 @@ import net.sourceforge.phpeclipse.webbrowser.IInternalWebBrowserWorkingCopy; import net.sourceforge.phpeclipse.webbrowser.WebBrowserEditorInput; import org.eclipse.ui.IMemento; + /** * */ public class InternalWebBrowser implements IInternalWebBrowser { private static final String MEMENTO_NEW_PAGE = "new_page"; + private static final String MEMENTO_CLEAR_HISTORY_ON_EXIT = "clear_history"; protected boolean useNewPage; + protected boolean clearHistory; - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpeclipse.webbrowser.IWebBrowser#getName() */ public String getName() { return WebBrowserUIPlugin.getResource("%internalWebBrowserName"); } - + public boolean getUseNewPage() { return useNewPage; } - + public boolean getClearHistoryOnExit() { return clearHistory; } - + public boolean isWorkingCopy() { return false; } @@ -39,22 +44,25 @@ public class InternalWebBrowser implements IInternalWebBrowser { public IInternalWebBrowserWorkingCopy getWorkingCopy() { return new InternalWebBrowserWorkingCopy(this); } - + protected void setInternal(IInternalWebBrowser browser) { useNewPage = browser.getUseNewPage(); clearHistory = browser.getClearHistoryOnExit(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpeclipse.webbrowser.IWebBrowser#openURL(java.net.URL) */ public void openURL(URL url) { WebBrowserEditor.open(new WebBrowserEditorInput(url)); } - + protected void save(IMemento memento) { memento.putString(MEMENTO_NEW_PAGE, useNewPage ? "true" : "false"); - memento.putString(MEMENTO_CLEAR_HISTORY_ON_EXIT, clearHistory ? "true" : "false"); + memento.putString(MEMENTO_CLEAR_HISTORY_ON_EXIT, clearHistory ? "true" + : "false"); } protected void load(IMemento memento) { @@ -63,14 +71,14 @@ public class InternalWebBrowser implements IInternalWebBrowser { useNewPage = true; else useNewPage = false; - + s = memento.getString(MEMENTO_CLEAR_HISTORY_ON_EXIT); if ("true".equals(s)) clearHistory = true; else clearHistory = false; } - + public String toString() { return "Internal Web browser"; } diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/InternalWebBrowserWorkingCopy.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/InternalWebBrowserWorkingCopy.java index 671f74b..b333362 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/InternalWebBrowserWorkingCopy.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/InternalWebBrowserWorkingCopy.java @@ -2,10 +2,12 @@ package net.sourceforge.phpeclipse.webbrowser.internal; import net.sourceforge.phpeclipse.webbrowser.IInternalWebBrowser; import net.sourceforge.phpeclipse.webbrowser.IInternalWebBrowserWorkingCopy; + /** * */ -public class InternalWebBrowserWorkingCopy extends InternalWebBrowser implements IInternalWebBrowserWorkingCopy { +public class InternalWebBrowserWorkingCopy extends InternalWebBrowser implements + IInternalWebBrowserWorkingCopy { protected InternalWebBrowser browser; // working copy @@ -17,7 +19,7 @@ public class InternalWebBrowserWorkingCopy extends InternalWebBrowser implements public void setUseNewPage(boolean b) { useNewPage = b; } - + public void setClearHistoryOnExit(boolean b) { clearHistory = b; } @@ -25,12 +27,14 @@ public class InternalWebBrowserWorkingCopy extends InternalWebBrowser implements public boolean isWorkingCopy() { return true; } - + public IInternalWebBrowserWorkingCopy getWorkingCopy() { return this; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpeclipse.webbrowser.IExternalWebBrowserWorkingCopy#save() */ public IInternalWebBrowser save() { diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/InternetPreferencePage.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/InternetPreferencePage.java index 0b5c512..e88ffbd 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/InternetPreferencePage.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/InternetPreferencePage.java @@ -1,10 +1,10 @@ /** * Copyright (c) 2003 IBM Corporation and others. - * All rights reserved.   This program and the accompanying materials + * All rights reserved. � This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation */ @@ -21,10 +21,12 @@ import org.eclipse.swt.widgets.Label; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.PlatformUI; + /** * A preference page that holds internet preferences. */ -public class InternetPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { +public class InternetPreferencePage extends PreferencePage implements + IWorkbenchPreferencePage { /** * InternetPreferencePage constructor comment. */ @@ -35,8 +37,9 @@ public class InternetPreferencePage extends PreferencePage implements IWorkbench /** * Create the preference options. - * - * @param parent org.eclipse.swt.widgets.Composite + * + * @param parent + * org.eclipse.swt.widgets.Composite * @return org.eclipse.swt.widgets.Control */ protected Control createContents(Composite parent) { @@ -50,12 +53,15 @@ public class InternetPreferencePage extends PreferencePage implements IWorkbench layout.marginWidth = 0; layout.marginHeight = 0; composite.setLayout(layout); - GridData data = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL); + GridData data = new GridData(GridData.FILL_HORIZONTAL + | GridData.VERTICAL_ALIGN_FILL); composite.setLayoutData(data); - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, ContextIds.PREF_BROWSER); + PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, + ContextIds.PREF_BROWSER); Label label = new Label(composite, SWT.WRAP); - label.setText(WebBrowserUIPlugin.getResource("%preferenceInternetDescription")); + label.setText(WebBrowserUIPlugin + .getResource("%preferenceInternetDescription")); data = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); label.setLayoutData(data); @@ -66,8 +72,10 @@ public class InternetPreferencePage extends PreferencePage implements IWorkbench /** * Initializes this preference page using the passed desktop. - * - * @param desktop the current desktop + * + * @param desktop + * the current desktop */ - public void init(IWorkbench workbench) { } + public void init(IWorkbench workbench) { + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/OpenWithBrowserActionDelegate.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/OpenWithBrowserActionDelegate.java index 7445daf..18cdc65 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/OpenWithBrowserActionDelegate.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/OpenWithBrowserActionDelegate.java @@ -1,10 +1,10 @@ /** * Copyright (c) 2003 IBM Corporation and others. - * All rights reserved.   This program and the accompanying materials + * All rights reserved. � This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation */ @@ -21,6 +21,7 @@ import org.eclipse.jface.action.IAction; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IActionDelegate; + /** * Action to open the Web broswer on a resource. */ @@ -40,49 +41,57 @@ public class OpenWithBrowserActionDelegate implements IActionDelegate { * This method is called when the delegating action has been triggered. * Implement this method to do the actual work. *

    - * - * @param action the action proxy that handles the presentation portion of the - * action + * + * @param action + * the action proxy that handles the presentation portion of the + * action */ public void run(IAction action) { URL url = null; try { url = new URL("file://" + resource.getLocation()); - WebBrowser.openURL(new WebBrowserEditorInput(url, WebBrowserEditorInput.SHOW_ALL | WebBrowserEditorInput.FORCE_NEW_PAGE)); + WebBrowser.openURL(new WebBrowserEditorInput(url, + WebBrowserEditorInput.SHOW_ALL + | WebBrowserEditorInput.FORCE_NEW_PAGE)); } catch (Exception e) { Trace.trace(Trace.SEVERE, "Error opening browser on file", e); } } /** - * Notifies this action delegate that the selection in the workbench has changed. + * Notifies this action delegate that the selection in the workbench has + * changed. *

    * Implementers can use this opportunity to change the availability of the * action or to modify other presentation properties. *

    - * - * @param action the action proxy that handles presentation portion of the action - * @param selection the current selection in the workbench + * + * @param action + * the action proxy that handles presentation portion of the + * action + * @param selection + * the current selection in the workbench */ public void selectionChanged(IAction action, ISelection sel) { if (sel.isEmpty() || !(sel instanceof IStructuredSelection)) { action.setEnabled(false); return; } - + IStructuredSelection select = (IStructuredSelection) sel; Iterator iterator = select.iterator(); Object selection = iterator.next(); - if (iterator.hasNext()) { // more than one selection (should never happen) + if (iterator.hasNext()) { // more than one selection (should never + // happen) action.setEnabled(false); return; } - + if (!(selection instanceof IResource)) { action.setEnabled(false); return; } - + resource = (IResource) selection; action.setEnabled(true); } diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/OrganizeFavoritesDialog.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/OrganizeFavoritesDialog.java index 3c74e02..fd9f89f 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/OrganizeFavoritesDialog.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/OrganizeFavoritesDialog.java @@ -1,11 +1,12 @@ package net.sourceforge.phpeclipse.webbrowser.internal; + /********************************************************************** * Copyright (c) 2003 IBM Corporation and others. - * All rights reserved.   This program and the accompanying materials + * All rights reserved. � This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation **********************************************************************/ @@ -39,34 +40,40 @@ import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; + /** * Dialog to manage the favorites list. */ public class OrganizeFavoritesDialog extends Dialog { - protected List favorites = WebBrowserPreference.getInternalWebBrowserFavorites(); - + protected List favorites = WebBrowserPreference + .getInternalWebBrowserFavorites(); + public class FavoriteContentProvider implements IStructuredContentProvider { public FavoriteContentProvider() { super(); } - public void dispose() { } + public void dispose() { + } public Object[] getElements(Object inputElement) { return favorites.toArray(); } - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {} + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + } } - + public class FavoriteLabelProvider implements ITableLabelProvider { public FavoriteLabelProvider() { super(); } - public void addListener(ILabelProviderListener listener) { } + public void addListener(ILabelProviderListener listener) { + } - public void dispose() { } + public void dispose() { + } public Image getColumnImage(Object element, int columnIndex) { if (columnIndex == 0) @@ -86,13 +93,15 @@ public class OrganizeFavoritesDialog extends Dialog { return false; } - public void removeListener(ILabelProviderListener listener) { } + public void removeListener(ILabelProviderListener listener) { + } } /** * ManageFavoritesDialog constructor comment. - * @param parentShell org.eclipse.swt.widgets.Shell - * @ + * + * @param parentShell + * org.eclipse.swt.widgets.Shell @ */ public OrganizeFavoritesDialog(Shell parentShell) { super(parentShell); @@ -101,11 +110,12 @@ public class OrganizeFavoritesDialog extends Dialog { } /** - * + * */ protected void configureShell(Shell newShell) { super.configureShell(newShell); - newShell.setText(WebBrowserUIPlugin.getResource("%dialogOrganizeFavoritesTitle")); + newShell.setText(WebBrowserUIPlugin + .getResource("%dialogOrganizeFavoritesTitle")); } /** @@ -122,42 +132,47 @@ public class OrganizeFavoritesDialog extends Dialog { composite.setLayout(layout); composite.setLayoutData(new GridData(GridData.FILL_BOTH)); composite.setFont(parent.getFont()); - //WorkbenchHelp.setHelp(composite, ContextIds.TERMINATE_SERVER_DIALOG); - + // WorkbenchHelp.setHelp(composite, ContextIds.TERMINATE_SERVER_DIALOG); + Label label = new Label(composite, SWT.NONE); - label.setText(WebBrowserUIPlugin.getResource("%dialogOrganizeFavoritesMessage")); + label.setText(WebBrowserUIPlugin + .getResource("%dialogOrganizeFavoritesMessage")); GridData data = new GridData(); data.horizontalSpan = 2; label.setLayoutData(data); - - final Table table = new Table(composite, SWT.BORDER | SWT.FULL_SELECTION | SWT.V_SCROLL | SWT.H_SCROLL | SWT.SINGLE); + + final Table table = new Table(composite, SWT.BORDER + | SWT.FULL_SELECTION | SWT.V_SCROLL | SWT.H_SCROLL | SWT.SINGLE); data = new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL); data.widthHint = 300; data.heightHint = 150; table.setLayoutData(data); table.setLinesVisible(true); - + TableLayout tableLayout = new TableLayout(); table.setLayout(tableLayout); table.setHeaderVisible(true); - + tableLayout.addColumnData(new ColumnWeightData(5, 50, true)); TableColumn col = new TableColumn(table, SWT.NONE); - col.setText(WebBrowserUIPlugin.getResource("%dialogOrganizeFavoritesName")); - + col.setText(WebBrowserUIPlugin + .getResource("%dialogOrganizeFavoritesName")); + tableLayout.addColumnData(new ColumnWeightData(6, 60, true)); col = new TableColumn(table, SWT.NONE); - col.setText(WebBrowserUIPlugin.getResource("%dialogOrganizeFavoritesURL")); + col.setText(WebBrowserUIPlugin + .getResource("%dialogOrganizeFavoritesURL")); table.setLayout(tableLayout); - - final TableViewer tableViewer = new TableViewer(table); + + final TableViewer tableViewer = new TableViewer(table); tableViewer.setContentProvider(new FavoriteContentProvider()); tableViewer.setLabelProvider(new FavoriteLabelProvider()); tableViewer.setInput("root"); - tableViewer.setColumnProperties(new String[] {"name", "url"}); - - tableViewer.setCellEditors(new CellEditor[] {new TextCellEditor(table), new TextCellEditor(table)}); - + tableViewer.setColumnProperties(new String[] { "name", "url" }); + + tableViewer.setCellEditors(new CellEditor[] { + new TextCellEditor(table), new TextCellEditor(table) }); + ICellModifier cellModifier = new ICellModifier() { public Object getValue(Object element, String property) { Favorite f = (Favorite) element; @@ -166,11 +181,11 @@ public class OrganizeFavoritesDialog extends Dialog { else return f.getURL(); } - + public boolean canModify(Object element, String property) { return true; } - + public void modify(Object element, String property, Object value) { if (element instanceof Item) element = ((Item) element).getData(); @@ -189,29 +204,31 @@ public class OrganizeFavoritesDialog extends Dialog { } }; tableViewer.setCellModifier(cellModifier); - - final Button remove = SWTUtil.createButton(composite, WebBrowserUIPlugin.getResource("%remove")); + + final Button remove = SWTUtil.createButton(composite, + WebBrowserUIPlugin.getResource("%remove")); remove.setEnabled(false); - - tableViewer.addSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - remove.setEnabled(!event.getSelection().isEmpty()); - } - }); - + + tableViewer + .addSelectionChangedListener(new ISelectionChangedListener() { + public void selectionChanged(SelectionChangedEvent event) { + remove.setEnabled(!event.getSelection().isEmpty()); + } + }); + remove.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { int index = table.getSelectionIndex(); if (index < 0 || index >= favorites.size()) return; - + tableViewer.remove(favorites.get(index)); favorites.remove(index); } }); - + Dialog.applyDialogFont(composite); - + return composite; } diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/SWTUtil.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/SWTUtil.java index 4381e6c..9598768 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/SWTUtil.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/SWTUtil.java @@ -1,10 +1,10 @@ /********************************************************************** * Copyright (c) 2003 IBM Corporation and others. - * All rights reserved.   This program and the accompanying materials + * All rights reserved. � This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation **********************************************************************/ @@ -22,6 +22,7 @@ import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; + /** * SWT Utility class. */ @@ -40,38 +41,45 @@ public class SWTUtil { * Returns a width hint for a button control. */ protected static int getButtonWidthHint(Button button) { - int widthHint = Dialog.convertHorizontalDLUsToPixels(fontMetrics, IDialogConstants.BUTTON_WIDTH); - return Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x); + int widthHint = Dialog.convertHorizontalDLUsToPixels(fontMetrics, + IDialogConstants.BUTTON_WIDTH); + return Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAULT, + true).x); } - + public static Button createButton(Composite comp, String label) { Button b = new Button(comp, SWT.PUSH); b.setText(label); if (fontMetrics == null) initializeDialogUnits(comp); - GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_BEGINNING); + GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL + | GridData.VERTICAL_ALIGN_BEGINNING); data.widthHint = getButtonWidthHint(b); - data.heightHint = Dialog.convertVerticalDLUsToPixels(fontMetrics, IDialogConstants.BUTTON_HEIGHT); + data.heightHint = Dialog.convertVerticalDLUsToPixels(fontMetrics, + IDialogConstants.BUTTON_HEIGHT); b.setLayoutData(data); return b; } - - public static Button createCheckbox(Composite comp, String txt, boolean isSelected){ + + public static Button createCheckbox(Composite comp, String txt, + boolean isSelected) { Button button = new Button(comp, SWT.CHECK); button.setText(txt); GridLayout layout = new GridLayout(); comp.setLayout(layout); - GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_BEGINNING); + GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL + | GridData.VERTICAL_ALIGN_BEGINNING); data.horizontalIndent = 10; button.setLayoutData(data); button.setSelection(isSelected); return button; } - + public static Label createLabel(Composite comp, String txt) { Label label = new Label(comp, SWT.NONE); label.setText(txt); - label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_BEGINNING)); + label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING + | GridData.VERTICAL_ALIGN_BEGINNING)); return label; } } diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/StandardURLMap.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/StandardURLMap.java index 95ba794..1cc4d58 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/StandardURLMap.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/StandardURLMap.java @@ -4,13 +4,14 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation */ package net.sourceforge.phpeclipse.webbrowser.internal; import net.sourceforge.phpeclipse.webbrowser.IURLMap; + /** * Standard URL mappings. */ diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/SwitchBrowserWorkbenchAction.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/SwitchBrowserWorkbenchAction.java index 829bf49..33e1e68 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/SwitchBrowserWorkbenchAction.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/SwitchBrowserWorkbenchAction.java @@ -4,7 +4,7 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation */ @@ -24,15 +24,17 @@ import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.IWorkbenchWindowPulldownDelegate2; + /** * Action to open the Web broswer. */ -public class SwitchBrowserWorkbenchAction implements IWorkbenchWindowPulldownDelegate2 { +public class SwitchBrowserWorkbenchAction implements + IWorkbenchWindowPulldownDelegate2 { /** * The menu created by this action */ private Menu fMenu; - + protected boolean recreateMenu = false; /** @@ -45,11 +47,12 @@ public class SwitchBrowserWorkbenchAction implements IWorkbenchWindowPulldownDel public void dispose() { setMenu(null); } - + /** * Sets this action's drop-down menu, disposing the previous menu. * - * @param menu the new menu + * @param menu + * the new menu */ private void setMenu(Menu menu) { if (fMenu != null) { @@ -58,43 +61,51 @@ public class SwitchBrowserWorkbenchAction implements IWorkbenchWindowPulldownDel fMenu = menu; } - public void init(IWorkbenchWindow window) { } - + public void init(IWorkbenchWindow window) { + } + /** * Adds the given action to the specified menu with an accelerator specified * by the given number. * - * @param menu the menu to add the action to - * @param action the action to add - * @param accelerator the number that should appear as an accelerator + * @param menu + * the menu to add the action to + * @param action + * the action to add + * @param accelerator + * the number that should appear as an accelerator */ protected void addToMenu(Menu menu, IAction action, int accelerator) { - StringBuffer label= new StringBuffer(); + StringBuffer label = new StringBuffer(); if (accelerator >= 0 && accelerator < 10) { - //add the numerical accelerator + // add the numerical accelerator label.append('&'); label.append(accelerator); label.append(' '); } label.append(action.getText()); action.setText(label.toString()); - ActionContributionItem item= new ActionContributionItem(action); + ActionContributionItem item = new ActionContributionItem(action); item.fill(menu, -1); } - + /** - * Fills the drop-down menu with favorites and launch history, - * launch shortcuts, and an action to open the launch configuration dialog. - * - * @param menu the menu to fill + * Fills the drop-down menu with favorites and launch history, launch + * shortcuts, and an action to open the launch configuration dialog. + * + * @param menu + * the menu to fill */ protected void fillMenu(Menu menu) { - IWebBrowser current = BrowserManager.getInstance().getCurrentWebBrowser(); - Iterator iterator = BrowserManager.getInstance().getWebBrowsers().iterator(); + IWebBrowser current = BrowserManager.getInstance() + .getCurrentWebBrowser(); + Iterator iterator = BrowserManager.getInstance().getWebBrowsers() + .iterator(); int i = 0; while (iterator.hasNext()) { IWebBrowser browser = (IWebBrowser) iterator.next(); - addToMenu(menu, new SwitchDefaultBrowserAction(browser, browser.equals(current)), i++); + addToMenu(menu, new SwitchDefaultBrowserAction(browser, browser + .equals(current)), i++); } } @@ -106,33 +117,35 @@ public class SwitchBrowserWorkbenchAction implements IWorkbenchWindowPulldownDel // it is shown because of dynamic history list fMenu.addMenuListener(new MenuAdapter() { public void menuShown(MenuEvent e) { - //if (recreateMenu) { - Menu m = (Menu) e.widget; - MenuItem[] items = m.getItems(); - for (int i = 0; i < items.length; i++) { - items[i].dispose(); - } - fillMenu(m); - recreateMenu = false; - //} + // if (recreateMenu) { + Menu m = (Menu) e.widget; + MenuItem[] items = m.getItems(); + for (int i = 0; i < items.length; i++) { + items[i].dispose(); + } + fillMenu(m); + recreateMenu = false; + // } } }); } - public void selectionChanged(IAction action, ISelection selection) { } - - public void run(IAction action) { } + public void selectionChanged(IAction action, ISelection selection) { + } + + public void run(IAction action) { + } public Menu getMenu(Menu parent) { setMenu(new Menu(parent)); - //fillMenu(fMenu); + // fillMenu(fMenu); initMenu(); return fMenu; } public Menu getMenu(Control parent) { setMenu(new Menu(parent)); - //fillMenu(fMenu); + // fillMenu(fMenu); initMenu(); return fMenu; } diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/SwitchDefaultBrowserAction.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/SwitchDefaultBrowserAction.java index a2bab5b..22d54c5 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/SwitchDefaultBrowserAction.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/SwitchDefaultBrowserAction.java @@ -4,7 +4,7 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation */ @@ -14,6 +14,7 @@ import net.sourceforge.phpeclipse.webbrowser.IInternalWebBrowser; import net.sourceforge.phpeclipse.webbrowser.IWebBrowser; import org.eclipse.jface.action.Action; + /** * Action to open the Web browser. */ @@ -25,14 +26,16 @@ public class SwitchDefaultBrowserAction extends Action { */ public SwitchDefaultBrowserAction(IWebBrowser webbrowser, boolean current) { super(); - + this.webbrowser = webbrowser; setText(webbrowser.getName()); if (webbrowser instanceof IInternalWebBrowser) - setImageDescriptor(ImageResource.getImageDescriptor(ImageResource.IMG_INTERNAL_BROWSER)); + setImageDescriptor(ImageResource + .getImageDescriptor(ImageResource.IMG_INTERNAL_BROWSER)); else - setImageDescriptor(ImageResource.getImageDescriptor(ImageResource.IMG_EXTERNAL_BROWSER)); - + setImageDescriptor(ImageResource + .getImageDescriptor(ImageResource.IMG_EXTERNAL_BROWSER)); + if (current) setChecked(true); } diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/TextAction.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/TextAction.java index 54cf481..1d7206d 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/TextAction.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/TextAction.java @@ -1,10 +1,10 @@ /** * Copyright (c) 2003 IBM Corporation and others. - * All rights reserved.   This program and the accompanying materials + * All rights reserved. � This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation */ @@ -16,17 +16,21 @@ import org.eclipse.swt.SWTException; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.graphics.Point; + /** * Text actions (cut, copy, paste) for the Web browser. */ public class TextAction extends Action { protected WebBrowser browser; + protected byte type; public static final byte CUT = 0; + public static final byte COPY = 1; + public static final byte PASTE = 2; - + /** * TextAction constructor comment. */ @@ -35,97 +39,108 @@ public class TextAction extends Action { this.browser = browser; this.type = type; } - + /** - * Copies the selected text to the clipboard. The text will be put in the + * Copies the selected text to the clipboard. The text will be put in the * clipboard in plain text format. *

    - * - * @exception SWTException

      - *
    • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
    • - *
    • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
    • - *
    + * + * @exception SWTException + *
      + *
    • ERROR_WIDGET_DISPOSED - if the receiver has been + * disposed
    • + *
    • ERROR_THREAD_INVALID_ACCESS - if not called from the + * thread that created the receiver
    • + *
    */ public void copy() { Point selection = browser.combo.getSelection(); - + int length = selection.y - selection.x; if (length > 0) { TextTransfer plainTextTransfer = TextTransfer.getInstance(); try { - browser.clipboard.setContents( - new String[] { browser.combo.getText().substring(selection.x, selection.y) }, - new Transfer[] { plainTextTransfer }); + browser.clipboard.setContents(new String[] { browser.combo + .getText().substring(selection.x, selection.y) }, + new Transfer[] { plainTextTransfer }); } catch (SWTError error) { - // Copy to clipboard failed. This happens when another application + // Copy to clipboard failed. This happens when another + // application // is accessing the clipboard while we copy. Ignore the error. // Fixes 1GDQAVN } } } - + /** - * Moves the selected text to the clipboard. The text will be put in the + * Moves the selected text to the clipboard. The text will be put in the * clipboard in plain text format and RTF format. *

    - * - * @exception SWTException

      - *
    • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
    • - *
    • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
    • - *
    + * + * @exception SWTException + *
      + *
    • ERROR_WIDGET_DISPOSED - if the receiver has been + * disposed
    • + *
    • ERROR_THREAD_INVALID_ACCESS - if not called from the + * thread that created the receiver
    • + *
    */ - public void cut(){ + public void cut() { Point selection = browser.combo.getSelection(); - + if (selection.y > selection.x) { copy(); delete(); } } - + /** - * Deletes the character to the right of the caret. Delete the selected text if any. + * Deletes the character to the right of the caret. Delete the selected text + * if any. */ public void delete() { Point selection = browser.combo.getSelection(); String text = browser.combo.getText(); - + if (selection.x != selection.y) { text = text.substring(0, selection.x) + text.substring(selection.y); browser.combo.setText(text); browser.combo.setSelection(new Point(selection.x, selection.x)); } } - - /** - * Replaces the selection with the clipboard text or insert the text at - * the current caret offset if there is no selection. - * If the widget has the SWT.SINGLE style and the clipboard text contains - * more than one line, only the first line without line delimiters is - * inserted in the widget. + + /** + * Replaces the selection with the clipboard text or insert the text at the + * current caret offset if there is no selection. If the widget has the + * SWT.SINGLE style and the clipboard text contains more than one line, only + * the first line without line delimiters is inserted in the widget. *

    - * - * @exception SWTException

      - *
    • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
    • - *
    • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
    • - *
    + * + * @exception SWTException + *
      + *
    • ERROR_WIDGET_DISPOSED - if the receiver has been + * disposed
    • + *
    • ERROR_THREAD_INVALID_ACCESS - if not called from the + * thread that created the receiver
    • + *
    */ public void paste() { TextTransfer transfer = TextTransfer.getInstance(); Point selection = browser.combo.getSelection(); String text = browser.combo.getText(); - + String newText = (String) browser.clipboard.getContents(transfer); if (newText != null && newText.length() > 0) { - text = text.substring(0, selection.x) + newText + text.substring(selection.y); + text = text.substring(0, selection.x) + newText + + text.substring(selection.y); browser.combo.setText(text); - + // set the selection to the end of the paste int x = selection.x + newText.length(); browser.combo.setSelection(new Point(x, x)); } } - + /** * Implementation of method defined on IAction. */ @@ -139,9 +154,10 @@ public class TextAction extends Action { else if (type == PASTE) paste(); } - + /** * */ - protected void update() { } + protected void update() { + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/Trace.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/Trace.java index 550cd7d..db21a7c 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/Trace.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/Trace.java @@ -1,22 +1,27 @@ /** * Copyright (c) 2003 IBM Corporation and others. - * All rights reserved.   This program and the accompanying materials + * All rights reserved. � This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation */ package net.sourceforge.phpeclipse.webbrowser.internal; + /** * Helper class to route trace output. */ public class Trace { public static int CONFIG = 0; + public static int WARNING = 2; + public static int SEVERE = 3; + public static int FINER = 4; + public static int FINEST = 5; /** @@ -28,8 +33,9 @@ public class Trace { /** * Trace the given text. - * - * @param s java.lang.String + * + * @param s + * java.lang.String */ public static void trace(int level, String s) { Trace.trace(level, s, null); @@ -37,9 +43,11 @@ public class Trace { /** * Trace the given message and exception. - * - * @param s java.lang.String - * @param t java.lang.Throwable + * + * @param s + * java.lang.String + * @param t + * java.lang.Throwable */ public static void trace(int level, String s, Throwable t) { if (!WebBrowserUIPlugin.getInstance().isDebugging()) diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowser.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowser.java index 24cfb5d..4c4f9ee 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowser.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowser.java @@ -1,11 +1,13 @@ /** - * Copyright (c) 2003 IBM Corporation and others. All rights reserved.   This program and the accompanying materials are made - * available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html  * Contributors: IBM - Initial API and implementation + * Copyright (c) 2003 IBM Corporation and others. All rights reserved. � This + * program and the accompanying materials are made available under the terms of + * the Common Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/cpl-v10.html �* Contributors: IBM - + * Initial API and implementation */ -//TODO 1. Handle the sizing of a popup running in shelled out secondary window. -//TODO 2. Support printing: waiting on eclipse bug 47937/44823. +// TODO 1. Handle the sizing of a popup running in shelled out secondary window. +// TODO 2. Support printing: waiting on eclipse bug 47937/44823. package net.sourceforge.phpeclipse.webbrowser.internal; import java.util.Iterator; @@ -48,590 +50,644 @@ import org.eclipse.swt.widgets.ToolItem; import org.eclipse.ui.PlatformUI; public class WebBrowser extends Composite { - protected Composite toolbarComp; + protected Composite toolbarComp; - protected Composite statusComp; + protected Composite statusComp; - protected Combo combo; + protected Combo combo; - protected Clipboard clipboard; + protected Clipboard clipboard; - protected boolean showToolbar; + protected boolean showToolbar; - protected ToolItem back; + protected ToolItem back; - protected ToolItem forward; + protected ToolItem forward; - protected ToolItem stop; + protected ToolItem stop; - protected ToolItem favorites; + protected ToolItem favorites; - protected ToolItem refresh; + protected ToolItem refresh; - protected BusyIndicator busy; + protected BusyIndicator busy; - protected boolean showStatusbar; + protected boolean showStatusbar; - protected ProgressBar progress; + protected ProgressBar progress; - protected Label status; + protected Label status; - private static int MAX_HISTORY = 50; + private static int MAX_HISTORY = 50; - protected static java.util.List history; + protected static java.util.List history; - protected Browser browser; + protected Browser browser; - protected Shell shell; + protected Shell shell; + + protected WebBrowserEditor editor; + + protected String title; + + public WebBrowser(Composite parent, final boolean showToolbar, + final boolean showStatusbar) { + super(parent, SWT.NONE); + + this.showToolbar = showToolbar; + this.showStatusbar = showStatusbar; - protected WebBrowserEditor editor; - - protected String title; - - public WebBrowser(Composite parent, final boolean showToolbar, final boolean showStatusbar) { - super(parent, SWT.NONE); - - this.showToolbar = showToolbar; - this.showStatusbar = showStatusbar; - - GridLayout layout = new GridLayout(); - layout.marginHeight = 3; - layout.marginWidth = 3; - layout.horizontalSpacing = 3; - layout.verticalSpacing = 3; - layout.numColumns = 1; - setLayout(layout); - setLayoutData(new GridData(GridData.FILL_BOTH)); - clipboard = new Clipboard(parent.getDisplay()); - PlatformUI.getWorkbench().getHelpSystem().setHelp(this, ContextIds.WEB_BROWSER); - - if (showToolbar) { - toolbarComp = new Composite(this, SWT.NONE); - GridLayout outerLayout = new GridLayout(); - outerLayout.numColumns = 2; - outerLayout.marginWidth = 0; - outerLayout.marginHeight = 0; - toolbarComp.setLayout(outerLayout); - toolbarComp.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL)); - - // create the top line, with a combo box for history and a "go" button - Composite top = new Composite(toolbarComp, SWT.NONE); - GridLayout topLayout = new GridLayout(); - topLayout.numColumns = 2; - topLayout.marginWidth = 0; - topLayout.marginHeight = 0; - top.setLayout(topLayout); - top.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_CENTER | GridData.FILL_HORIZONTAL)); - - combo = new Combo(top, SWT.DROP_DOWN); - - updateHistory(); - - combo.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent we) { - try { - if (combo.getSelectionIndex() != -1) - setURL(combo.getItem(combo.getSelectionIndex())); - } catch (Exception e) { - } - } - }); - combo.addListener(SWT.DefaultSelection, new Listener() { - public void handleEvent(Event e) { - setURL(combo.getText()); - } - }); - combo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - PlatformUI.getWorkbench().getHelpSystem().setHelp(combo, ContextIds.WEB_BROWSER_URL); - - ToolBar toolbar = new ToolBar(top, SWT.FLAT); - fillToolBar(toolbar); - - new ToolItem(toolbar, SWT.SEPARATOR); - - busy = new BusyIndicator(toolbarComp, SWT.NONE); - busy.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); - } - - // create a new SWT Web browser widget, checking once again to make sure we can use it in this environment -// if (WebBrowserUtil.canUseInternalWebBrowser() & WebBrowserUtil.isInternalBrowserOperational()) - if (WebBrowserUtil.isInternalBrowserOperational()) - this.browser = new Browser(this, SWT.NONE); - else { - WebBrowserUtil.openError(WebBrowserUIPlugin.getResource("%errorCouldNotLaunchInternalWebBrowser")); - return; - } - - if (showToolbar) { - back.setEnabled(browser.isBackEnabled()); - forward.setEnabled(browser.isForwardEnabled()); - } - - PlatformUI.getWorkbench().getHelpSystem().setHelp(browser, ContextIds.WEB_BROWSER_WEB); - GridData data = new GridData(); - data.horizontalAlignment = GridData.FILL; - data.verticalAlignment = GridData.FILL; - data.horizontalSpan = 3; - data.grabExcessHorizontalSpace = true; - data.grabExcessVerticalSpace = true; - browser.setLayoutData(data); - - if (showStatusbar) - createStatusArea(this); - - addBrowserListeners(); - } - - /** - * - */ - protected void addBrowserListeners() { - if (showStatusbar) { - // respond to Browser StatusTextEvents events by updating the status Text label - browser.addStatusTextListener(new StatusTextListener() { - public void changed(StatusTextEvent event) { - status.setText(event.text); - } - }); - } - - /** - * Add listener for new window creation so that we can instead of opening a separate new window in which the session is lost, we - * can instead open a new window in a new shell within the browser area thereby maintaining the session. - */ - browser.addOpenWindowListener(new OpenWindowListener() { - public void open(WindowEvent event) { - Shell shell2 = new Shell(getDisplay()); - shell2.setLayout(new FillLayout()); - shell2.setText(WebBrowserUIPlugin.getResource("%viewWebBrowserTitle")); - shell2.setImage(getShell().getImage()); - WebBrowser browser2 = new WebBrowser(shell2, showToolbar, showStatusbar); - browser2.shell = shell2; - event.browser = browser2.browser; - shell2.open(); - } - }); - - browser.addCloseWindowListener(new CloseWindowListener() { - public void close(WindowEvent event) { - // if shell is not null, it must be a secondary popup window, else its an editor window - if (shell != null) - shell.dispose(); - else - editor.closeEditor(); - } - }); - - browser.addProgressListener(new ProgressListener() { - public void changed(ProgressEvent event) { - if (event.total == 0) - return; - - boolean done = (event.current == event.total); - - int percentProgress = event.current * 100 / event.total; - if (showStatusbar) { - if (done) - progress.setSelection(0); - else - progress.setSelection(percentProgress); - } - - if (showToolbar) { - if (!busy.isBusy() && (percentProgress > 0 && percentProgress < 100)) { - busy.setBusy(true); - } - // Once the progress hits 100 percent, done, set busy to false - else if (busy.isBusy() && done) { - busy.setBusy(false); - } - } - } - - public void completed(ProgressEvent event) { - if (showStatusbar) - progress.setSelection(0); - if (showToolbar) { - busy.setBusy(false); - back.setEnabled(browser.isBackEnabled()); - forward.setEnabled(browser.isForwardEnabled()); - } - } - }); - - if (showToolbar) { - browser.addLocationListener(new LocationListener() { - public void changed(LocationEvent event) { - if (!event.top) - return; - if (!isHome()) { - combo.setText(event.location); - addToHistory(event.location); - updateHistory(); - } else - combo.setText(""); - } - - public void changing(LocationEvent event) { - } - }); - } - - browser.addTitleListener(new TitleListener() { - public void changed(TitleEvent event) { - title = event.title; - } - }); - } - - /** - * Return the underlying browser control. - * - * @return org.eclipse.swt.browser.Browser - */ - public Browser getBrowser() { - return browser; - } - - /** - * - */ - protected void forward() { - browser.forward(); - } - - /** - * - */ - protected void back() { - browser.back(); - } - - /** - * - */ - protected void stop() { - browser.stop(); - } - - /** - * - */ - protected void navigate(String url) { - Trace.trace(Trace.FINER, "Navigate: " + url); - if (url != null && url.equals(getURL())) { - refresh(); - return; - } - browser.setUrl(url); - } - - /** - * Refresh the currently viewed page. - */ - public void refresh() { - browser.refresh(); - } - - protected void setURL(String url, boolean browse) { - Trace.trace(Trace.FINEST, "setURL: " + url + " " + browse); - if (url == null) { - home(); - return; - } - - if (url.endsWith(WebBrowserPreference.getHomePageURL().substring(9))) - return; - - // check URL maps - Iterator iterator = WebBrowserUtil.getURLMaps().iterator(); - String newURL = null; - while (iterator.hasNext() && newURL == null) { - try { - IURLMap map = (IURLMap) iterator.next(); - newURL = map.getMappedURL(url); - } catch (Exception e) { - } - } - if (newURL != null) - url = newURL; - - if (browse) - navigate(url); - - addToHistory(url); - updateHistory(); - } - - protected void addToHistory(String url) { - if (history == null) - history = WebBrowserPreference.getInternalWebBrowserHistory(); - int found = -1; - int size = history.size(); - for (int i = 0; i < size; i++) { - String s = (String) history.get(i); - if (s.equals(url)) { - found = i; - break; - } - } - - if (found == -1) { - if (size >= MAX_HISTORY) - history.remove(size - 1); - history.add(0, url); - WebBrowserPreference.setInternalWebBrowserHistory(history); - } else if (found != 0) { - history.remove(found); - history.add(0, url); - WebBrowserPreference.setInternalWebBrowserHistory(history); - } - } - - public void setURL(String url) { - setURL(url, true); - } - - /** - * Creates the Web browser status area. - */ - private void createStatusArea(Composite parent) { - Composite composite = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.numColumns = 2; - layout.marginHeight = 0; - layout.marginWidth = 0; - layout.horizontalSpacing = 4; - layout.verticalSpacing = 0; - composite.setLayout(layout); - composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - - // Add a label for displaying status messages as they are received from the control - status = new Label(composite, SWT.SINGLE | SWT.READ_ONLY); - GridData gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL); - gridData.horizontalIndent = 2; - status.setLayoutData(gridData); - - // Add a progress bar to display downloading progress information - progress = new ProgressBar(composite, SWT.BORDER); - gridData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_FILL); - gridData.widthHint = 100; - gridData.heightHint = 10; - progress.setLayoutData(gridData); - } - - /** - * - */ - public void dispose() { - super.dispose(); - - showStatusbar = false; - showToolbar = false; - - if (busy != null) - busy.dispose(); - busy = null; - - browser = null; - } - - /** - * Populate the toolbar. - * - * @param toolbar - * org.eclipse.swt.widgets.ToolBar - */ - private void fillToolBar(final ToolBar toolbar) { - ToolItem go = new ToolItem(toolbar, SWT.NONE); - go.setImage(ImageResource.getImage(ImageResource.IMG_ELCL_NAV_GO)); - go.setHotImage(ImageResource.getImage(ImageResource.IMG_CLCL_NAV_GO)); - go.setDisabledImage(ImageResource.getImage(ImageResource.IMG_DLCL_NAV_GO)); - go.setToolTipText(WebBrowserUIPlugin.getResource("%actionWebBrowserGo")); - go.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - setURL(combo.getText()); - } - }); - - new ToolItem(toolbar, SWT.SEPARATOR); - - favorites = new ToolItem(toolbar, SWT.DROP_DOWN); - favorites.setImage(ImageResource.getImage(ImageResource.IMG_ELCL_NAV_FAVORITES)); - favorites.setHotImage(ImageResource.getImage(ImageResource.IMG_CLCL_NAV_FAVORITES)); - favorites.setDisabledImage(ImageResource.getImage(ImageResource.IMG_DLCL_NAV_FAVORITES)); - favorites.setToolTipText(WebBrowserUIPlugin.getResource("%actionWebBrowserFavorites")); - - favorites.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - if (event.detail == SWT.ARROW) { - Rectangle r = favorites.getBounds(); - showFavorites(toolbar, toolbar.toDisplay(r.x, r.y + r.height)); - } else - addFavorite(); - } - }); - - // create back and forward actions - back = new ToolItem(toolbar, SWT.NONE); - back.setImage(ImageResource.getImage(ImageResource.IMG_ELCL_NAV_BACKWARD)); - back.setHotImage(ImageResource.getImage(ImageResource.IMG_CLCL_NAV_BACKWARD)); - back.setDisabledImage(ImageResource.getImage(ImageResource.IMG_DLCL_NAV_BACKWARD)); - back.setToolTipText(WebBrowserUIPlugin.getResource("%actionWebBrowserBack")); - back.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - back(); - } - }); - - forward = new ToolItem(toolbar, SWT.NONE); - forward.setImage(ImageResource.getImage(ImageResource.IMG_ELCL_NAV_FORWARD)); - forward.setHotImage(ImageResource.getImage(ImageResource.IMG_CLCL_NAV_FORWARD)); - forward.setDisabledImage(ImageResource.getImage(ImageResource.IMG_DLCL_NAV_FORWARD)); - forward.setToolTipText(WebBrowserUIPlugin.getResource("%actionWebBrowserForward")); - forward.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - forward(); - } - }); - - // create refresh, stop, and print actions - stop = new ToolItem(toolbar, SWT.NONE); - stop.setImage(ImageResource.getImage(ImageResource.IMG_ELCL_NAV_STOP)); - stop.setHotImage(ImageResource.getImage(ImageResource.IMG_CLCL_NAV_STOP)); - stop.setDisabledImage(ImageResource.getImage(ImageResource.IMG_DLCL_NAV_STOP)); - stop.setToolTipText(WebBrowserUIPlugin.getResource("%actionWebBrowserStop")); - stop.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - stop(); - } - }); - - refresh = new ToolItem(toolbar, SWT.NONE); - refresh.setImage(ImageResource.getImage(ImageResource.IMG_ELCL_NAV_REFRESH)); - refresh.setHotImage(ImageResource.getImage(ImageResource.IMG_CLCL_NAV_REFRESH)); - refresh.setDisabledImage(ImageResource.getImage(ImageResource.IMG_DLCL_NAV_REFRESH)); - refresh.setToolTipText(WebBrowserUIPlugin.getResource("%actionWebBrowserRefresh")); - refresh.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - refresh(); - } - }); - } - - protected void addFavorite() { - java.util.List list = WebBrowserPreference.getInternalWebBrowserFavorites(); - Favorite f = new Favorite(title, browser.getUrl()); - if (!list.contains(f)) { - list.add(f); - WebBrowserPreference.setInternalWebBrowserFavorites(list); - } - } - - protected void showFavorites(Control parent, Point p) { - Menu perspectiveBarMenu = null; - if (perspectiveBarMenu == null) { - Menu menu = new Menu(parent); - - // locked favorites - Iterator iterator = WebBrowserUtil.getLockedFavorites().iterator(); - if (iterator.hasNext()) { - while (iterator.hasNext()) { - final Favorite f = (Favorite) iterator.next(); - MenuItem item = new MenuItem(menu, SWT.NONE); - item.setText(f.getName()); - item.setImage(ImageResource.getImage(ImageResource.IMG_FAVORITE)); - item.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - setURL(f.getURL()); - } - }); - } - - new MenuItem(menu, SWT.SEPARATOR); - } - - iterator = WebBrowserPreference.getInternalWebBrowserFavorites().iterator(); - if (!iterator.hasNext()) { - MenuItem item = new MenuItem(menu, SWT.NONE); - item.setText(WebBrowserUIPlugin.getResource("%actionWebBrowserNoFavorites")); - } - while (iterator.hasNext()) { - final Favorite f = (Favorite) iterator.next(); - MenuItem item = new MenuItem(menu, SWT.NONE); - item.setText(f.getName()); - item.setImage(ImageResource.getImage(ImageResource.IMG_FAVORITE)); - item.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - setURL(f.getURL()); - } - }); - } - - new MenuItem(menu, SWT.SEPARATOR); - - MenuItem item = new MenuItem(menu, SWT.NONE); - item.setText(WebBrowserUIPlugin.getResource("%actionWebBrowserOrganizeFavorites")); - item.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - OrganizeFavoritesDialog dialog = new OrganizeFavoritesDialog(shell); - dialog.open(); - } - }); - - perspectiveBarMenu = menu; - } - - if (perspectiveBarMenu != null) { - perspectiveBarMenu.setLocation(p.x, p.y); - perspectiveBarMenu.setVisible(true); - } - } - - public void home() { - navigate(WebBrowserPreference.getHomePageURL()); - } - - /** - * Returns true if the homepage is currently being displayed. - * - * @return boolean - */ - protected boolean isHome() { - return getURL() != null && getURL().endsWith(WebBrowserPreference.getHomePageURL().substring(9)); - } - - protected String getURL() { - return browser.getUrl(); - } - - /** - * Update the history list to the global copy. - */ - protected void updateHistory() { - if (combo == null) - return; - - String temp = combo.getText(); - if (history == null) - history = WebBrowserPreference.getInternalWebBrowserHistory(); - - String[] historyList = new String[history.size()]; - history.toArray(historyList); - combo.setItems(historyList); - - combo.setText(temp); - } - - public void addProgressListener(ProgressListener listener) { - browser.addProgressListener(listener); - } - - public void addStatusTextListener(StatusTextListener listener) { - browser.addStatusTextListener(listener); - } - - public void addTitleListener(TitleListener listener) { - browser.addTitleListener(listener); - } + GridLayout layout = new GridLayout(); + layout.marginHeight = 3; + layout.marginWidth = 3; + layout.horizontalSpacing = 3; + layout.verticalSpacing = 3; + layout.numColumns = 1; + setLayout(layout); + setLayoutData(new GridData(GridData.FILL_BOTH)); + clipboard = new Clipboard(parent.getDisplay()); + PlatformUI.getWorkbench().getHelpSystem().setHelp(this, + ContextIds.WEB_BROWSER); + + if (showToolbar) { + toolbarComp = new Composite(this, SWT.NONE); + GridLayout outerLayout = new GridLayout(); + outerLayout.numColumns = 2; + outerLayout.marginWidth = 0; + outerLayout.marginHeight = 0; + toolbarComp.setLayout(outerLayout); + toolbarComp.setLayoutData(new GridData( + GridData.VERTICAL_ALIGN_BEGINNING + | GridData.FILL_HORIZONTAL)); + + // create the top line, with a combo box for history and a "go" + // button + Composite top = new Composite(toolbarComp, SWT.NONE); + GridLayout topLayout = new GridLayout(); + topLayout.numColumns = 2; + topLayout.marginWidth = 0; + topLayout.marginHeight = 0; + top.setLayout(topLayout); + top.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_CENTER + | GridData.FILL_HORIZONTAL)); + + combo = new Combo(top, SWT.DROP_DOWN); + + updateHistory(); + + combo.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent we) { + try { + if (combo.getSelectionIndex() != -1) + setURL(combo.getItem(combo.getSelectionIndex())); + } catch (Exception e) { + } + } + }); + combo.addListener(SWT.DefaultSelection, new Listener() { + public void handleEvent(Event e) { + setURL(combo.getText()); + } + }); + combo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + PlatformUI.getWorkbench().getHelpSystem().setHelp(combo, + ContextIds.WEB_BROWSER_URL); + + ToolBar toolbar = new ToolBar(top, SWT.FLAT); + fillToolBar(toolbar); + + new ToolItem(toolbar, SWT.SEPARATOR); + + busy = new BusyIndicator(toolbarComp, SWT.NONE); + busy.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); + } + + // create a new SWT Web browser widget, checking once again to make sure + // we can use it in this environment + // if (WebBrowserUtil.canUseInternalWebBrowser() & + // WebBrowserUtil.isInternalBrowserOperational()) + if (WebBrowserUtil.isInternalBrowserOperational()) + this.browser = new Browser(this, SWT.NONE); + else { + WebBrowserUtil.openError(WebBrowserUIPlugin + .getResource("%errorCouldNotLaunchInternalWebBrowser")); + return; + } + + if (showToolbar) { + back.setEnabled(browser.isBackEnabled()); + forward.setEnabled(browser.isForwardEnabled()); + } + + PlatformUI.getWorkbench().getHelpSystem().setHelp(browser, + ContextIds.WEB_BROWSER_WEB); + GridData data = new GridData(); + data.horizontalAlignment = GridData.FILL; + data.verticalAlignment = GridData.FILL; + data.horizontalSpan = 3; + data.grabExcessHorizontalSpace = true; + data.grabExcessVerticalSpace = true; + browser.setLayoutData(data); + + if (showStatusbar) + createStatusArea(this); + + addBrowserListeners(); + } + + /** + * + */ + protected void addBrowserListeners() { + if (showStatusbar) { + // respond to Browser StatusTextEvents events by updating the status + // Text label + browser.addStatusTextListener(new StatusTextListener() { + public void changed(StatusTextEvent event) { + status.setText(event.text); + } + }); + } + + /** + * Add listener for new window creation so that we can instead of + * opening a separate new window in which the session is lost, we can + * instead open a new window in a new shell within the browser area + * thereby maintaining the session. + */ + browser.addOpenWindowListener(new OpenWindowListener() { + public void open(WindowEvent event) { + Shell shell2 = new Shell(getDisplay()); + shell2.setLayout(new FillLayout()); + shell2.setText(WebBrowserUIPlugin + .getResource("%viewWebBrowserTitle")); + shell2.setImage(getShell().getImage()); + WebBrowser browser2 = new WebBrowser(shell2, showToolbar, + showStatusbar); + browser2.shell = shell2; + event.browser = browser2.browser; + shell2.open(); + } + }); + + browser.addCloseWindowListener(new CloseWindowListener() { + public void close(WindowEvent event) { + // if shell is not null, it must be a secondary popup window, + // else its an editor window + if (shell != null) + shell.dispose(); + else + editor.closeEditor(); + } + }); + + browser.addProgressListener(new ProgressListener() { + public void changed(ProgressEvent event) { + if (event.total == 0) + return; + + boolean done = (event.current == event.total); + + int percentProgress = event.current * 100 / event.total; + if (showStatusbar) { + if (done) + progress.setSelection(0); + else + progress.setSelection(percentProgress); + } + + if (showToolbar) { + if (!busy.isBusy() + && (percentProgress > 0 && percentProgress < 100)) { + busy.setBusy(true); + } + // Once the progress hits 100 percent, done, set busy to + // false + else if (busy.isBusy() && done) { + busy.setBusy(false); + } + } + } + + public void completed(ProgressEvent event) { + if (showStatusbar) + progress.setSelection(0); + if (showToolbar) { + busy.setBusy(false); + back.setEnabled(browser.isBackEnabled()); + forward.setEnabled(browser.isForwardEnabled()); + } + } + }); + + if (showToolbar) { + browser.addLocationListener(new LocationListener() { + public void changed(LocationEvent event) { + if (!event.top) + return; + if (!isHome()) { + combo.setText(event.location); + addToHistory(event.location); + updateHistory(); + } else + combo.setText(""); + } + + public void changing(LocationEvent event) { + } + }); + } + + browser.addTitleListener(new TitleListener() { + public void changed(TitleEvent event) { + title = event.title; + } + }); + } + + /** + * Return the underlying browser control. + * + * @return org.eclipse.swt.browser.Browser + */ + public Browser getBrowser() { + return browser; + } + + /** + * + */ + protected void forward() { + browser.forward(); + } + + /** + * + */ + protected void back() { + browser.back(); + } + + /** + * + */ + protected void stop() { + browser.stop(); + } + + /** + * + */ + protected void navigate(String url) { + Trace.trace(Trace.FINER, "Navigate: " + url); + if (url != null && url.equals(getURL())) { + refresh(); + return; + } + browser.setUrl(url); + } + + /** + * Refresh the currently viewed page. + */ + public void refresh() { + browser.refresh(); + } + + protected void setURL(String url, boolean browse) { + Trace.trace(Trace.FINEST, "setURL: " + url + " " + browse); + if (url == null) { + home(); + return; + } + + if (url.endsWith(WebBrowserPreference.getHomePageURL().substring(9))) + return; + + // check URL maps + Iterator iterator = WebBrowserUtil.getURLMaps().iterator(); + String newURL = null; + while (iterator.hasNext() && newURL == null) { + try { + IURLMap map = (IURLMap) iterator.next(); + newURL = map.getMappedURL(url); + } catch (Exception e) { + } + } + if (newURL != null) + url = newURL; + + if (browse) + navigate(url); + + addToHistory(url); + updateHistory(); + } + + protected void addToHistory(String url) { + if (history == null) + history = WebBrowserPreference.getInternalWebBrowserHistory(); + int found = -1; + int size = history.size(); + for (int i = 0; i < size; i++) { + String s = (String) history.get(i); + if (s.equals(url)) { + found = i; + break; + } + } + + if (found == -1) { + if (size >= MAX_HISTORY) + history.remove(size - 1); + history.add(0, url); + WebBrowserPreference.setInternalWebBrowserHistory(history); + } else if (found != 0) { + history.remove(found); + history.add(0, url); + WebBrowserPreference.setInternalWebBrowserHistory(history); + } + } + + public void setURL(String url) { + setURL(url, true); + } + + /** + * Creates the Web browser status area. + */ + private void createStatusArea(Composite parent) { + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.numColumns = 2; + layout.marginHeight = 0; + layout.marginWidth = 0; + layout.horizontalSpacing = 4; + layout.verticalSpacing = 0; + composite.setLayout(layout); + composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + // Add a label for displaying status messages as they are received from + // the control + status = new Label(composite, SWT.SINGLE | SWT.READ_ONLY); + GridData gridData = new GridData(GridData.FILL_HORIZONTAL + | GridData.VERTICAL_ALIGN_FILL); + gridData.horizontalIndent = 2; + status.setLayoutData(gridData); + + // Add a progress bar to display downloading progress information + progress = new ProgressBar(composite, SWT.BORDER); + gridData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING + | GridData.VERTICAL_ALIGN_FILL); + gridData.widthHint = 100; + gridData.heightHint = 10; + progress.setLayoutData(gridData); + } + + /** + * + */ + public void dispose() { + super.dispose(); + + showStatusbar = false; + showToolbar = false; + + if (busy != null) + busy.dispose(); + busy = null; + + browser = null; + } + + /** + * Populate the toolbar. + * + * @param toolbar + * org.eclipse.swt.widgets.ToolBar + */ + private void fillToolBar(final ToolBar toolbar) { + ToolItem go = new ToolItem(toolbar, SWT.NONE); + go.setImage(ImageResource.getImage(ImageResource.IMG_ELCL_NAV_GO)); + go.setHotImage(ImageResource.getImage(ImageResource.IMG_CLCL_NAV_GO)); + go.setDisabledImage(ImageResource + .getImage(ImageResource.IMG_DLCL_NAV_GO)); + go + .setToolTipText(WebBrowserUIPlugin + .getResource("%actionWebBrowserGo")); + go.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent event) { + setURL(combo.getText()); + } + }); + + new ToolItem(toolbar, SWT.SEPARATOR); + + favorites = new ToolItem(toolbar, SWT.DROP_DOWN); + favorites.setImage(ImageResource + .getImage(ImageResource.IMG_ELCL_NAV_FAVORITES)); + favorites.setHotImage(ImageResource + .getImage(ImageResource.IMG_CLCL_NAV_FAVORITES)); + favorites.setDisabledImage(ImageResource + .getImage(ImageResource.IMG_DLCL_NAV_FAVORITES)); + favorites.setToolTipText(WebBrowserUIPlugin + .getResource("%actionWebBrowserFavorites")); + + favorites.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent event) { + if (event.detail == SWT.ARROW) { + Rectangle r = favorites.getBounds(); + showFavorites(toolbar, toolbar.toDisplay(r.x, r.y + + r.height)); + } else + addFavorite(); + } + }); + + // create back and forward actions + back = new ToolItem(toolbar, SWT.NONE); + back.setImage(ImageResource + .getImage(ImageResource.IMG_ELCL_NAV_BACKWARD)); + back.setHotImage(ImageResource + .getImage(ImageResource.IMG_CLCL_NAV_BACKWARD)); + back.setDisabledImage(ImageResource + .getImage(ImageResource.IMG_DLCL_NAV_BACKWARD)); + back.setToolTipText(WebBrowserUIPlugin + .getResource("%actionWebBrowserBack")); + back.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent event) { + back(); + } + }); + + forward = new ToolItem(toolbar, SWT.NONE); + forward.setImage(ImageResource + .getImage(ImageResource.IMG_ELCL_NAV_FORWARD)); + forward.setHotImage(ImageResource + .getImage(ImageResource.IMG_CLCL_NAV_FORWARD)); + forward.setDisabledImage(ImageResource + .getImage(ImageResource.IMG_DLCL_NAV_FORWARD)); + forward.setToolTipText(WebBrowserUIPlugin + .getResource("%actionWebBrowserForward")); + forward.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent event) { + forward(); + } + }); + + // create refresh, stop, and print actions + stop = new ToolItem(toolbar, SWT.NONE); + stop.setImage(ImageResource.getImage(ImageResource.IMG_ELCL_NAV_STOP)); + stop.setHotImage(ImageResource + .getImage(ImageResource.IMG_CLCL_NAV_STOP)); + stop.setDisabledImage(ImageResource + .getImage(ImageResource.IMG_DLCL_NAV_STOP)); + stop.setToolTipText(WebBrowserUIPlugin + .getResource("%actionWebBrowserStop")); + stop.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent event) { + stop(); + } + }); + + refresh = new ToolItem(toolbar, SWT.NONE); + refresh.setImage(ImageResource + .getImage(ImageResource.IMG_ELCL_NAV_REFRESH)); + refresh.setHotImage(ImageResource + .getImage(ImageResource.IMG_CLCL_NAV_REFRESH)); + refresh.setDisabledImage(ImageResource + .getImage(ImageResource.IMG_DLCL_NAV_REFRESH)); + refresh.setToolTipText(WebBrowserUIPlugin + .getResource("%actionWebBrowserRefresh")); + refresh.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent event) { + refresh(); + } + }); + } + + protected void addFavorite() { + java.util.List list = WebBrowserPreference + .getInternalWebBrowserFavorites(); + Favorite f = new Favorite(title, browser.getUrl()); + if (!list.contains(f)) { + list.add(f); + WebBrowserPreference.setInternalWebBrowserFavorites(list); + } + } + + protected void showFavorites(Control parent, Point p) { + Menu perspectiveBarMenu = null; + if (perspectiveBarMenu == null) { + Menu menu = new Menu(parent); + + // locked favorites + Iterator iterator = WebBrowserUtil.getLockedFavorites().iterator(); + if (iterator.hasNext()) { + while (iterator.hasNext()) { + final Favorite f = (Favorite) iterator.next(); + MenuItem item = new MenuItem(menu, SWT.NONE); + item.setText(f.getName()); + item.setImage(ImageResource + .getImage(ImageResource.IMG_FAVORITE)); + item.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent event) { + setURL(f.getURL()); + } + }); + } + + new MenuItem(menu, SWT.SEPARATOR); + } + + iterator = WebBrowserPreference.getInternalWebBrowserFavorites() + .iterator(); + if (!iterator.hasNext()) { + MenuItem item = new MenuItem(menu, SWT.NONE); + item.setText(WebBrowserUIPlugin + .getResource("%actionWebBrowserNoFavorites")); + } + while (iterator.hasNext()) { + final Favorite f = (Favorite) iterator.next(); + MenuItem item = new MenuItem(menu, SWT.NONE); + item.setText(f.getName()); + item.setImage(ImageResource + .getImage(ImageResource.IMG_FAVORITE)); + item.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent event) { + setURL(f.getURL()); + } + }); + } + + new MenuItem(menu, SWT.SEPARATOR); + + MenuItem item = new MenuItem(menu, SWT.NONE); + item.setText(WebBrowserUIPlugin + .getResource("%actionWebBrowserOrganizeFavorites")); + item.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent event) { + OrganizeFavoritesDialog dialog = new OrganizeFavoritesDialog( + shell); + dialog.open(); + } + }); + + perspectiveBarMenu = menu; + } + + if (perspectiveBarMenu != null) { + perspectiveBarMenu.setLocation(p.x, p.y); + perspectiveBarMenu.setVisible(true); + } + } + + public void home() { + navigate(WebBrowserPreference.getHomePageURL()); + } + + /** + * Returns true if the homepage is currently being displayed. + * + * @return boolean + */ + protected boolean isHome() { + return getURL() != null + && getURL().endsWith( + WebBrowserPreference.getHomePageURL().substring(9)); + } + + protected String getURL() { + return browser.getUrl(); + } + + /** + * Update the history list to the global copy. + */ + protected void updateHistory() { + if (combo == null) + return; + + String temp = combo.getText(); + if (history == null) + history = WebBrowserPreference.getInternalWebBrowserHistory(); + + String[] historyList = new String[history.size()]; + history.toArray(historyList); + combo.setItems(historyList); + + combo.setText(temp); + } + + public void addProgressListener(ProgressListener listener) { + browser.addProgressListener(listener); + } + + public void addStatusTextListener(StatusTextListener listener) { + browser.addStatusTextListener(listener); + } + + public void addTitleListener(TitleListener listener) { + browser.addTitleListener(listener); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowserEditor.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowserEditor.java index c55f9d4..f266e11 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowserEditor.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowserEditor.java @@ -1,10 +1,10 @@ /** * Copyright (c) 2003 IBM Corporation and others. - * All rights reserved.   This program and the accompanying materials + * All rights reserved. � This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation */ @@ -39,20 +39,26 @@ import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.part.EditorPart; + /** - * An integrated Web browser, defined as an editor to make - * better use of the desktop. + * An integrated Web browser, defined as an editor to make better use of the + * desktop. */ public class WebBrowserEditor extends EditorPart { public static final String WEB_BROWSER_EDITOR_ID = "net.sourceforge.phpeclipse.webbrowser"; + protected WebBrowser webBrowser; + protected String initialURL; + protected Image image; protected TextAction cutAction; + protected TextAction copyAction; + protected TextAction pasteAction; - + protected IResourceChangeListener resourceListener; /** @@ -61,7 +67,7 @@ public class WebBrowserEditor extends EditorPart { public WebBrowserEditor() { super(); } - + /** * Creates the SWT controls for this workbench part. *

    @@ -71,95 +77,97 @@ public class WebBrowserEditor extends EditorPart { *

    * For implementors this is a multi-step process: *

      - *
    1. Create one or more controls within the parent.
    2. - *
    3. Set the parent layout as needed.
    4. - *
    5. Register any global actions with the IActionService.
    6. - *
    7. Register any popup menus with the IActionService.
    8. - *
    9. Register a selection provider with the ISelectionService - * (optional).
    10. + *
    11. Create one or more controls within the parent.
    12. + *
    13. Set the parent layout as needed.
    14. + *
    15. Register any global actions with the IActionService.
    16. + *
    17. Register any popup menus with the IActionService.
    18. + *
    19. Register a selection provider with the + * ISelectionService (optional).
    20. *
    *

    - * - * @param parent the parent control + * + * @param parent + * the parent control */ public void createPartControl(Composite parent) { IWebBrowserEditorInput input = getWebBrowserEditorInput(); - - + if (input == null || input.isToolbarVisible() == false) - webBrowser = new WebBrowser(parent, false, input.isStatusbarVisible()); + webBrowser = new WebBrowser(parent, false, input + .isStatusbarVisible()); else { - webBrowser = new WebBrowser(parent, true, input.isStatusbarVisible()); + webBrowser = new WebBrowser(parent, true, input + .isStatusbarVisible()); cutAction = new TextAction(webBrowser, TextAction.CUT); copyAction = new TextAction(webBrowser, TextAction.COPY); pasteAction = new TextAction(webBrowser, TextAction.PASTE); } - + webBrowser.setURL(initialURL); webBrowser.editor = this; } - + public void dispose() { if (image != null && !image.isDisposed()) image.dispose(); image = null; if (resourceListener != null) - ResourcesPlugin.getWorkspace().removeResourceChangeListener(resourceListener); + ResourcesPlugin.getWorkspace().removeResourceChangeListener( + resourceListener); } - - /* (non-Javadoc) - * Saves the contents of this editor. - *

    - * Subclasses must override this method to implement the open-save-close lifecycle - * for an editor. For greater details, see IEditorPart - *

    - * + + /* + * (non-Javadoc) Saves the contents of this editor.

    Subclasses must + * override this method to implement the open-save-close lifecycle for an + * editor. For greater details, see IEditorPart

    + * * @see IEditorPart */ - public void doSave(IProgressMonitor monitor) { } + public void doSave(IProgressMonitor monitor) { + } - /* (non-Javadoc) - * Saves the contents of this editor to another object. - *

    - * Subclasses must override this method to implement the open-save-close lifecycle - * for an editor. For greater details, see IEditorPart + /* + * (non-Javadoc) Saves the contents of this editor to another object.

    + * Subclasses must override this method to implement the open-save-close + * lifecycle for an editor. For greater details, see IEditorPart *

    - * + * * @see IEditorPart */ - public void doSaveAs() { } - + public void doSaveAs() { + } + /** * Returns the copy action. - * + * * @return org.eclipse.jface.action.IAction */ public IAction getCopyAction() { return copyAction; } - + /** * Returns the cut action. - * + * * @return org.eclipse.jface.action.IAction */ public IAction getCutAction() { return cutAction; } - + /** * Returns the paste action. - * + * * @return org.eclipse.jface.action.IAction */ public IAction getPasteAction() { return pasteAction; } - + /** * Returns the web editor input, if available. - * + * * @return net.sourceforge.phpeclipse.webbrowser.IWebBrowserEditorInput */ protected IWebBrowserEditorInput getWebBrowserEditorInput() { @@ -168,31 +176,25 @@ public class WebBrowserEditor extends EditorPart { return (IWebBrowserEditorInput) input; return null; } - - /* (non-Javadoc) - * Sets the cursor and selection state for this editor to the passage defined - * by the given marker. - *

    - * Subclasses may override. For greater details, see IEditorPart - *

    - * + + /* + * (non-Javadoc) Sets the cursor and selection state for this editor to the + * passage defined by the given marker.

    Subclasses may override. For + * greater details, see IEditorPart

    + * * @see IEditorPart */ - public void gotoMarker(IMarker marker) { } - - /* (non-Javadoc) - * Initializes the editor part with a site and input. - *

    - * Subclasses of EditorPart must implement this method. Within - * the implementation subclasses should verify that the input type is acceptable - * and then save the site and input. Here is sample code: - *

    - *
    -	 *		if (!(input instanceof IFileEditorInput))
    -	 *			throw new PartInitException("Invalid Input: Must be IFileEditorInput");
    -	 *		setSite(site);
    -	 *		setInput(editorInput);
    -	 * 
    + public void gotoMarker(IMarker marker) { + } + + /* + * (non-Javadoc) Initializes the editor part with a site and input.

    + * Subclasses of EditorPart must implement this method. + * Within the implementation subclasses should verify that the input type is + * acceptable and then save the site and input. Here is sample code:

    + *
     if (!(input instanceof IFileEditorInput)) throw new
    +	 * PartInitException("Invalid Input: Must be IFileEditorInput");
    +	 * setSite(site); setInput(editorInput); 
    */ public void init(IEditorSite site, IEditorInput input) { Trace.trace(Trace.FINEST, "Opening browser: " + input); @@ -207,7 +209,9 @@ public class WebBrowserEditor extends EditorPart { Trace.trace(Trace.SEVERE, "Error getting URL to file"); } addResourceListener(file); - input = new WebBrowserEditorInput(url, WebBrowserEditorInput.SHOW_ALL | WebBrowserEditorInput.SAVE_URL); + input = new WebBrowserEditorInput(url, + WebBrowserEditorInput.SHOW_ALL + | WebBrowserEditorInput.SAVE_URL); } if (input instanceof IWebBrowserEditorInput) { IWebBrowserEditorInput wbei = (IWebBrowserEditorInput) input; @@ -218,7 +222,7 @@ public class WebBrowserEditor extends EditorPart { webBrowser.setURL(initialURL); site.getWorkbenchWindow().getActivePage().bringToTop(this); } - + setPartName(wbei.getName()); setTitleToolTip(wbei.getToolTipText()); @@ -233,37 +237,34 @@ public class WebBrowserEditor extends EditorPart { setSite(site); setInput(input); } - - /* (non-Javadoc) - * Returns whether the contents of this editor have changed since the last save - * operation. - *

    - * Subclasses must override this method to implement the open-save-close lifecycle - * for an editor. For greater details, see IEditorPart - *

    - * + + /* + * (non-Javadoc) Returns whether the contents of this editor have changed + * since the last save operation.

    Subclasses must override this method + * to implement the open-save-close lifecycle for an editor. For greater + * details, see IEditorPart

    + * * @see IEditorPart */ public boolean isDirty() { return false; } - - /* (non-Javadoc) - * Returns whether the "save as" operation is supported by this editor. - *

    - * Subclasses must override this method to implement the open-save-close lifecycle - * for an editor. For greater details, see IEditorPart + + /* + * (non-Javadoc) Returns whether the "save as" operation is supported by + * this editor.

    Subclasses must override this method to implement the + * open-save-close lifecycle for an editor. For greater details, see IEditorPart *

    - * + * * @see IEditorPart */ public boolean isSaveAsAllowed() { return false; } - + /** * Returns true if this editor has a toolbar. - * + * * @return boolean */ public boolean isToolbarVisible() { @@ -273,12 +274,13 @@ public class WebBrowserEditor extends EditorPart { else return false; } - + /** * Open the input in the internal Web browser. */ public static void open(IWebBrowserEditorInput input) { - IWorkbenchWindow workbenchWindow = WebBrowserUIPlugin.getInstance().getWorkbench().getActiveWorkbenchWindow(); + IWorkbenchWindow workbenchWindow = WebBrowserUIPlugin.getInstance() + .getWorkbench().getActiveWorkbenchWindow(); IWorkbenchPage page = workbenchWindow.getActivePage(); try { @@ -289,20 +291,21 @@ public class WebBrowserEditor extends EditorPart { IEditorPart editor = editors[i].getEditor(true); if (editor != null && editor instanceof WebBrowserEditor) { WebBrowserEditor webEditor = (WebBrowserEditor) editor; - if (input.canReplaceInput(webEditor.getWebBrowserEditorInput())) { + if (input.canReplaceInput(webEditor + .getWebBrowserEditorInput())) { editor.init(editor.getEditorSite(), input); return; } } } } - + page.openEditor(input, WebBrowserEditor.WEB_BROWSER_EDITOR_ID); } catch (Exception e) { Trace.trace(Trace.SEVERE, "Error opening Web browser", e); } } - + /** * Asks this part to take focus within the workbench. *

    @@ -319,7 +322,7 @@ public class WebBrowserEditor extends EditorPart { webBrowser.updateHistory(); } } - + /** * Update the actions. */ @@ -338,37 +341,49 @@ public class WebBrowserEditor extends EditorPart { protected void closeEditor() { Display.getDefault().asyncExec(new Runnable() { public void run() { - getEditorSite().getPage().closeEditor(WebBrowserEditor.this, false); + getEditorSite().getPage().closeEditor(WebBrowserEditor.this, + false); } }); } - + /** * Adds a resource change listener to see if the file is deleted. */ protected void addResourceListener(final IResource resource) { if (resource == null) return; - + resourceListener = new IResourceChangeListener() { public void resourceChanged(IResourceChangeEvent event) { try { event.getDelta().accept(new IResourceDeltaVisitor() { public boolean visit(IResourceDelta delta) { IResource res = delta.getResource(); - + if (res == null || !res.equals(resource)) return true; if (delta.getKind() != IResourceDelta.REMOVED) return true; - + Display.getDefault().asyncExec(new Runnable() { public void run() { - String title = WebBrowserUIPlugin.getResource("%dialogResourceDeletedTitle"); - String message = WebBrowserUIPlugin.getResource("%dialogResourceDeletedMessage", resource.getName()); - String[] labels = new String[] {WebBrowserUIPlugin.getResource("%dialogResourceDeletedIgnore"), IDialogConstants.CLOSE_LABEL}; - MessageDialog dialog = new MessageDialog(getEditorSite().getShell(), title, null, message, MessageDialog.INFORMATION, labels, 0); + String title = WebBrowserUIPlugin + .getResource("%dialogResourceDeletedTitle"); + String message = WebBrowserUIPlugin + .getResource( + "%dialogResourceDeletedMessage", + resource.getName()); + String[] labels = new String[] { + WebBrowserUIPlugin + .getResource("%dialogResourceDeletedIgnore"), + IDialogConstants.CLOSE_LABEL }; + MessageDialog dialog = new MessageDialog( + getEditorSite().getShell(), title, + null, message, + MessageDialog.INFORMATION, labels, + 0); if (dialog.open() != 0) closeEditor(); @@ -378,10 +393,12 @@ public class WebBrowserEditor extends EditorPart { } }); } catch (Exception e) { - Trace.trace(Trace.SEVERE, "Error listening for resource deletion", e); + Trace.trace(Trace.SEVERE, + "Error listening for resource deletion", e); } } }; - ResourcesPlugin.getWorkspace().addResourceChangeListener(resourceListener); + ResourcesPlugin.getWorkspace().addResourceChangeListener( + resourceListener); } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowserEditorActionBarContributor.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowserEditorActionBarContributor.java index 4c9d702..f5ba6ad 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowserEditorActionBarContributor.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowserEditorActionBarContributor.java @@ -1,10 +1,10 @@ /** * Copyright (c) 2003 IBM Corporation and others. - * All rights reserved.   This program and the accompanying materials + * All rights reserved. � This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation */ @@ -15,11 +15,12 @@ import org.eclipse.ui.IEditorActionBarContributor; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.actions.ActionFactory; + /** - * ActionBarContributor for the Web browser. - * Just adds cut, copy, paste actions. + * ActionBarContributor for the Web browser. Just adds cut, copy, paste actions. */ -public class WebBrowserEditorActionBarContributor implements IEditorActionBarContributor { +public class WebBrowserEditorActionBarContributor implements + IEditorActionBarContributor { protected IActionBars actionBars; /** @@ -32,34 +33,40 @@ public class WebBrowserEditorActionBarContributor implements IEditorActionBarCon /** * Initializes this contributor, which is expected to add contributions as * required to the given action bars and global action handlers. - * - * @param bars the action bars + * + * @param bars + * the action bars */ public void init(IActionBars bars, IWorkbenchPage page) { this.actionBars = bars; } /** - * Sets the active editor for the contributor. - * Implementors should disconnect from the old editor, connect to the - * new editor, and update the actions to reflect the new editor. - * - * @param targetEditor the new editor target + * Sets the active editor for the contributor. Implementors should + * disconnect from the old editor, connect to the new editor, and update the + * actions to reflect the new editor. + * + * @param targetEditor + * the new editor target */ public void setActiveEditor(IEditorPart targetEditor) { if (targetEditor instanceof WebBrowserEditor) { WebBrowserEditor editor = (WebBrowserEditor) targetEditor; - actionBars.setGlobalActionHandler(ActionFactory.COPY.getId(), editor.getCopyAction()); - actionBars.setGlobalActionHandler(ActionFactory.CUT.getId(), editor.getCutAction()); - actionBars.setGlobalActionHandler(ActionFactory.PASTE.getId(), editor.getPasteAction()); + actionBars.setGlobalActionHandler(ActionFactory.COPY.getId(), + editor.getCopyAction()); + actionBars.setGlobalActionHandler(ActionFactory.CUT.getId(), editor + .getCutAction()); + actionBars.setGlobalActionHandler(ActionFactory.PASTE.getId(), + editor.getPasteAction()); editor.updateActions(); } } /** - * Disposes this contributor. + * Disposes this contributor. */ - public void dispose() { } + public void dispose() { + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowserPreference.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowserPreference.java index f8eea79..5c83893 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowserPreference.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowserPreference.java @@ -4,7 +4,7 @@ * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html -�* + �* * Contributors: * IBM - Initial API and implementation */ @@ -18,16 +18,21 @@ import java.util.StringTokenizer; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.preference.IPreferenceStore; + /** * Preferences for the Web browser. */ public class WebBrowserPreference { protected static final String PREF_BROWSER_HISTORY = "webBrowserHistory"; + protected static final String PREF_INTERNAL_WEB_BROWSER_HISTORY = "internalWebBrowserHistory"; + protected static final String PREF_INTERNAL_WEB_BROWSER_FAVORITES = "internalWebBrowserFavorites"; + protected static final String PREF_INTERNAL_WEB_BROWSER_OLD_FAVORITES = "internalWebBrowserOldFavorites"; + protected static final String URL_PARAMETER = "%URL%"; - + /** * WebBrowserPreference constructor comment. */ @@ -43,7 +48,8 @@ public class WebBrowserPreference { public static String getHomePageURL() { try { // get the default home page - URL url = WebBrowserUIPlugin.getInstance().getBundle().getEntry("home/home.html"); + URL url = WebBrowserUIPlugin.getInstance().getBundle().getEntry( + "home/home.html"); url = Platform.resolve(url); return url.toExternalForm(); } catch (Exception e) { @@ -53,20 +59,21 @@ public class WebBrowserPreference { /** * Returns the preference store. - * + * * @return org.eclipse.jface.preference.IPreferenceStore */ protected static IPreferenceStore getPreferenceStore() { return WebBrowserUIPlugin.getInstance().getPreferenceStore(); } - + /** * Returns the Web browser history list. * * @return java.util.List */ public static List getInternalWebBrowserHistory() { - String temp = getPreferenceStore().getString(PREF_INTERNAL_WEB_BROWSER_HISTORY); + String temp = getPreferenceStore().getString( + PREF_INTERNAL_WEB_BROWSER_HISTORY); StringTokenizer st = new StringTokenizer(temp, "|*|"); List l = new ArrayList(); while (st.hasMoreTokens()) { @@ -75,22 +82,23 @@ public class WebBrowserPreference { } return l; } - + /** * Returns the Web browser favorites. * * @return java.util.List */ public static List getInternalWebBrowserFavorites() { - String temp = getPreferenceStore().getString(PREF_INTERNAL_WEB_BROWSER_FAVORITES); + String temp = getPreferenceStore().getString( + PREF_INTERNAL_WEB_BROWSER_FAVORITES); StringTokenizer st = new StringTokenizer(temp, "|*|"); List l = new ArrayList(); try { - while (st.hasMoreTokens()) { - l.add(new Favorite(st.nextToken(), st.nextToken())); - } + while (st.hasMoreTokens()) { + l.add(new Favorite(st.nextToken(), st.nextToken())); + } } catch (Exception e) { - // ignore + // ignore } return l; } @@ -100,18 +108,18 @@ public class WebBrowserPreference { */ public static void initializeDefaultPreferences() { IPreferenceStore store = getPreferenceStore(); - + String temp = store.getString(PREF_INTERNAL_WEB_BROWSER_OLD_FAVORITES); StringTokenizer st = new StringTokenizer(temp, "|*|"); List def = new ArrayList(); try { - while (st.hasMoreTokens()) { - def.add(new Favorite(st.nextToken(), st.nextToken())); - } - } catch (Exception e) { - // ignore - } - List list = getInternalWebBrowserFavorites(); + while (st.hasMoreTokens()) { + def.add(new Favorite(st.nextToken(), st.nextToken())); + } + } catch (Exception e) { + // ignore + } + List list = getInternalWebBrowserFavorites(); Iterator iterator = WebBrowserUtil.getUnlockedFavorites().iterator(); while (iterator.hasNext()) { Favorite f = (Favorite) iterator.next(); @@ -119,7 +127,7 @@ public class WebBrowserPreference { list.add(f); } setInternalWebBrowserFavorites(list); - + StringBuffer sb = new StringBuffer(); iterator = WebBrowserUtil.getUnlockedFavorites().iterator(); while (iterator.hasNext()) { @@ -132,10 +140,10 @@ public class WebBrowserPreference { store.setValue(PREF_INTERNAL_WEB_BROWSER_OLD_FAVORITES, sb.toString()); WebBrowserUIPlugin.getInstance().savePluginPreferences(); } - + /** * Sets the Web browser history. - * + * * @param java.util.List */ public static void setInternalWebBrowserHistory(List list) { @@ -148,13 +156,14 @@ public class WebBrowserPreference { sb.append("|*|"); } } - getPreferenceStore().setValue(PREF_INTERNAL_WEB_BROWSER_HISTORY, sb.toString()); + getPreferenceStore().setValue(PREF_INTERNAL_WEB_BROWSER_HISTORY, + sb.toString()); WebBrowserUIPlugin.getInstance().savePluginPreferences(); } - + /** * Sets the Web browser favorites. - * + * * @param java.util.List */ public static void setInternalWebBrowserFavorites(List list) { @@ -169,7 +178,8 @@ public class WebBrowserPreference { sb.append("|*|"); } } - getPreferenceStore().setValue(PREF_INTERNAL_WEB_BROWSER_FAVORITES, sb.toString()); + getPreferenceStore().setValue(PREF_INTERNAL_WEB_BROWSER_FAVORITES, + sb.toString()); WebBrowserUIPlugin.getInstance().savePluginPreferences(); } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowserPreferencePage.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowserPreferencePage.java index cda95fd..4a6d28a 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowserPreferencePage.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowserPreferencePage.java @@ -1,10 +1,10 @@ /** * Copyright (c) 2003 IBM Corporation and others. - * All rights reserved.   This program and the accompanying materials + * All rights reserved. � This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation */ @@ -21,10 +21,12 @@ import org.eclipse.swt.widgets.Label; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.PlatformUI; + /** * The preference page that holds webbrowser preferences. */ -public class WebBrowserPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { +public class WebBrowserPreferencePage extends PreferencePage implements + IWorkbenchPreferencePage { /** * WebBrowserPreferencePage constructor comment. */ @@ -35,8 +37,9 @@ public class WebBrowserPreferencePage extends PreferencePage implements IWorkben /** * Create the preference options. - * - * @param parent org.eclipse.swt.widgets.Composite + * + * @param parent + * org.eclipse.swt.widgets.Composite * @return org.eclipse.swt.widgets.Control */ protected Control createContents(Composite parent) { @@ -50,16 +53,20 @@ public class WebBrowserPreferencePage extends PreferencePage implements IWorkben layout.marginWidth = 0; layout.marginHeight = 0; composite.setLayout(layout); - GridData data = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL); + GridData data = new GridData(GridData.FILL_HORIZONTAL + | GridData.VERTICAL_ALIGN_FILL); composite.setLayoutData(data); - PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, ContextIds.PREF_BROWSER); + PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, + ContextIds.PREF_BROWSER); Label label = new Label(composite, SWT.WRAP); - label.setText(WebBrowserUIPlugin.getResource("%preferenceWebBrowserDescription")); + label.setText(WebBrowserUIPlugin + .getResource("%preferenceWebBrowserDescription")); data = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); label.setLayoutData(data); - BrowserTableComposite browserComposite = new BrowserTableComposite(composite, SWT.NONE); + BrowserTableComposite browserComposite = new BrowserTableComposite( + composite, SWT.NONE); data = new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL); browserComposite.setLayoutData(data); @@ -71,17 +78,20 @@ public class WebBrowserPreferencePage extends PreferencePage implements IWorkben /** * Initializes this preference page using the passed desktop. - * - * @param desktop the current desktop + * + * @param desktop + * the current desktop */ - public void init(IWorkbench workbench) { } + public void init(IWorkbench workbench) { + } /** - * + * */ public void setVisible(boolean visible) { super.setVisible(visible); if (visible) - setTitle(WebBrowserUIPlugin.getResource("%preferenceWebBrowserTitleLong")); + setTitle(WebBrowserUIPlugin + .getResource("%preferenceWebBrowserTitleLong")); } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowserUIPlugin.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowserUIPlugin.java index 89927d4..72d5d5a 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowserUIPlugin.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowserUIPlugin.java @@ -1,10 +1,10 @@ /** * Copyright (c) 2003 IBM Corporation and others. - * All rights reserved.   This program and the accompanying materials + * All rights reserved. � This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation */ @@ -15,6 +15,7 @@ import java.text.MessageFormat; import org.eclipse.core.runtime.Platform; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; + /** * The main web browser plugin class. */ @@ -35,7 +36,7 @@ public class WebBrowserUIPlugin extends AbstractUIPlugin { /** * Returns the singleton instance of this plugin. - * + * * @return net.sourceforge.phpeclipse.webbrowser.WebBrowserPlugin */ public static WebBrowserUIPlugin getInstance() { @@ -44,8 +45,9 @@ public class WebBrowserUIPlugin extends AbstractUIPlugin { /** * Returns the translated String found with the given key. - * - * @param key java.lang.String + * + * @param key + * java.lang.String * @return java.lang.String */ public static String getResource(String key) { @@ -57,11 +59,13 @@ public class WebBrowserUIPlugin extends AbstractUIPlugin { } /** - * Returns the translated String found with the given key, - * and formatted with the given arguments using java.text.MessageFormat. - * - * @param key java.lang.String - * @param arg java.lang.String + * Returns the translated String found with the given key, and formatted + * with the given arguments using java.text.MessageFormat. + * + * @param key + * java.lang.String + * @param arg + * java.lang.String * @return java.lang.String */ public static String getResource(String key, String arg) { @@ -80,7 +84,7 @@ public class WebBrowserUIPlugin extends AbstractUIPlugin { /** * Shuts down this plug-in and saves all plug-in state. - * + * * @exception Exception */ public void stop(BundleContext context) throws Exception { diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowserUtil.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowserUtil.java index 865f645..e5e0e72 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowserUtil.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/internal/WebBrowserUtil.java @@ -1,10 +1,10 @@ /** * Copyright (c) 2003 IBM Corporation and others. - * All rights reserved.   This program and the accompanying materials + * All rights reserved. � This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html - * + �* * Contributors: * IBM - Initial API and implementation */ @@ -35,25 +35,34 @@ import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IMemento; import org.eclipse.ui.XMLMemento; + /** * Utility class for the Web browser tooling. */ public class WebBrowserUtil { private static List urlMaps; + private static List lockedFavorites; + private static List unlockedFavorites; + private static final String BROWSER_PACKAGE_NAME = "org.eclipse.swt.browser.Browser"; + public static Boolean isInternalBrowserOperational; - + private static List defaultBrowsers2; static class DefaultBrowser { String name; + String params; + String executable; + String[] locations; - - public DefaultBrowser(String name, String executable, String params, String[] locations) { + + public DefaultBrowser(String name, String executable, String params, + String[] locations) { if (name == null) name = ""; else if (name.startsWith("%")) @@ -64,9 +73,10 @@ public class WebBrowserUtil { this.params = params; this.locations = locations; } - + public String toString() { - String s = "Browser: " + name + ", " + executable + ", " + params + ", "; + String s = "Browser: " + name + ", " + executable + ", " + params + + ", "; if (locations != null) { int size = locations.length; for (int i = 0; i < size; i++) { @@ -86,7 +96,7 @@ public class WebBrowserUtil { /** * Returns true if we're running on Windows. - * + * * @return boolean */ public static boolean isWindows() { @@ -99,7 +109,7 @@ public class WebBrowserUtil { /** * Returns true if we're running on linux. - * + * * @return boolean */ public static boolean isLinux() { @@ -112,37 +122,43 @@ public class WebBrowserUtil { /** * Open a dialog window. - * - * @param title java.lang.String - * @param message java.lang.String + * + * @param title + * java.lang.String + * @param message + * java.lang.String */ public static void openError(String message) { Display d = Display.getCurrent(); if (d == null) d = Display.getDefault(); - + Shell shell = d.getActiveShell(); - MessageDialog.openError(shell, WebBrowserUIPlugin.getResource("%errorDialogTitle"), message); + MessageDialog.openError(shell, WebBrowserUIPlugin + .getResource("%errorDialogTitle"), message); } - + /** * Open a dialog window. - * - * @param title java.lang.String - * @param message java.lang.String + * + * @param title + * java.lang.String + * @param message + * java.lang.String */ public static void openMessage(String message) { Display d = Display.getCurrent(); if (d == null) d = Display.getDefault(); - + Shell shell = d.getActiveShell(); - MessageDialog.openInformation(shell, WebBrowserUIPlugin.getResource("%searchingTaskName"), message); + MessageDialog.openInformation(shell, WebBrowserUIPlugin + .getResource("%searchingTaskName"), message); } - + /** * Returns a List of all URL maps. - * + * * @return java.util.List */ public static List getURLMaps() { @@ -150,33 +166,38 @@ public class WebBrowserUtil { loadURLMaps(); return urlMaps; } - + /** * Load the url map extension point. */ private static void loadURLMaps() { Trace.trace(Trace.FINEST, "->- Loading .urlMap extension point ->-"); IExtensionRegistry registry = Platform.getExtensionRegistry(); - IConfigurationElement[] cf = registry.getConfigurationElementsFor(WebBrowserUIPlugin.PLUGIN_ID, "urlMap"); + IConfigurationElement[] cf = registry.getConfigurationElementsFor( + WebBrowserUIPlugin.PLUGIN_ID, "urlMap"); int size = cf.length; urlMaps = new ArrayList(size); for (int i = 0; i < size; i++) { try { - IURLMap mapper = (IURLMap) cf[i].createExecutableExtension("class"); + IURLMap mapper = (IURLMap) cf[i] + .createExecutableExtension("class"); urlMaps.add(mapper); - Trace.trace(Trace.FINEST, " Loaded url map: " + cf[i].getAttribute("id")); + Trace.trace(Trace.FINEST, " Loaded url map: " + + cf[i].getAttribute("id")); } catch (Throwable t) { - Trace.trace(Trace.SEVERE, " Could not load url map: " + cf[i].getAttribute("id"), t); + Trace.trace(Trace.SEVERE, " Could not load url map: " + + cf[i].getAttribute("id"), t); } } - - Trace.trace(Trace.FINEST, "-<- Done loading .urlMap extension point -<-"); + + Trace.trace(Trace.FINEST, + "-<- Done loading .urlMap extension point -<-"); } - + /** * Returns a List of all unlocked favorites. - * + * * @return java.util.List */ public static List getUnlockedFavorites() { @@ -184,10 +205,10 @@ public class WebBrowserUtil { loadFavorites(); return unlockedFavorites; } - + /** * Returns a List of all locked favorites. - * + * * @return java.util.List */ public static List getLockedFavorites() { @@ -195,40 +216,47 @@ public class WebBrowserUtil { loadFavorites(); return lockedFavorites; } - + /** * Load the favorites extension point. */ private static void loadFavorites() { Trace.trace(Trace.FINEST, "->- Loading .favorites extension point ->-"); IExtensionRegistry registry = Platform.getExtensionRegistry(); - IConfigurationElement[] cf = registry.getConfigurationElementsFor(WebBrowserUIPlugin.PLUGIN_ID, "favorites"); + IConfigurationElement[] cf = registry.getConfigurationElementsFor( + WebBrowserUIPlugin.PLUGIN_ID, "favorites"); int size = cf.length; unlockedFavorites = new ArrayList(size); lockedFavorites = new ArrayList(size); for (int i = 0; i < size; i++) { try { - Favorite f = new Favorite(cf[i].getAttribute("name"), cf[i].getAttribute("url")); + Favorite f = new Favorite(cf[i].getAttribute("name"), cf[i] + .getAttribute("url")); String locked = cf[i].getAttribute("locked"); if (!"true".equals(locked)) unlockedFavorites.add(f); else lockedFavorites.add(f); - Trace.trace(Trace.FINEST, " Loaded favorite: " + cf[i].getAttribute("id")); + Trace.trace(Trace.FINEST, " Loaded favorite: " + + cf[i].getAttribute("id")); } catch (Throwable t) { - Trace.trace(Trace.SEVERE, " Could not load favorite: " + cf[i].getAttribute("id"), t); + Trace.trace(Trace.SEVERE, " Could not load favorite: " + + cf[i].getAttribute("id"), t); } } - - Trace.trace(Trace.FINEST, "-<- Done loading .favorites extension point -<-"); + + Trace.trace(Trace.FINEST, + "-<- Done loading .favorites extension point -<-"); } - + /** - * Returns whether it should be possible to use the internal browser or not, based on whether or not - * the org.eclipse.swt.Browser class can be found/loaded. If it can it means is is supported on the platform in which - * this plugin is running. If not, disable the ability to use the internal browser. - * + * Returns whether it should be possible to use the internal browser or not, + * based on whether or not the org.eclipse.swt.Browser class can be + * found/loaded. If it can it means is is supported on the platform in which + * this plugin is running. If not, disable the ability to use the internal + * browser. + * * @return boolean */ public static boolean canUseInternalWebBrowser() { @@ -236,16 +264,19 @@ public class WebBrowserUtil { Class clazz = Class.forName(BROWSER_PACKAGE_NAME); if (clazz != null) return true; - } catch (ClassNotFoundException e) { } + } catch (ClassNotFoundException e) { + } return false; } /** - * This method checks to see if it can new up a new Browser. If the SWT widget can not be bound - * to the particular operating system it throws an SWTException. We catch that and set a boolean - * flag which represents whether or not we were successfully able to create a Browser instance or not. - * If not, don't bother adding the Internal Web Browser that uses this widget. Designed to be attemped - * only once and the flag set used throughout. + * This method checks to see if it can new up a new Browser. If the SWT + * widget can not be bound to the particular operating system it throws an + * SWTException. We catch that and set a boolean flag which represents + * whether or not we were successfully able to create a Browser instance or + * not. If not, don't bother adding the Internal Web Browser that uses this + * widget. Designed to be attemped only once and the flag set used + * throughout. * * @return boolean */ @@ -253,21 +284,23 @@ public class WebBrowserUtil { // if we have already figured this out, don't do it again. if (isInternalBrowserOperational != null) return isInternalBrowserOperational.booleanValue(); - + try { new Browser(new Shell(Display.getCurrent()), SWT.NONE); - isInternalBrowserOperational = new Boolean(true); + isInternalBrowserOperational = new Boolean(true); } catch (Throwable t) { - WebBrowserUIPlugin.getInstance().getLog().log(new Status(IStatus.WARNING, - WebBrowserUIPlugin.PLUGIN_ID, 0, "Internal browser is not operational", t)); + WebBrowserUIPlugin.getInstance().getLog().log( + new Status(IStatus.WARNING, WebBrowserUIPlugin.PLUGIN_ID, + 0, "Internal browser is not operational", t)); isInternalBrowserOperational = new Boolean(false); } return isInternalBrowserOperational.booleanValue(); } - + public static List getExternalBrowserPaths() { List paths = new ArrayList(); - Iterator iterator = BrowserManager.getInstance().getWebBrowsers().iterator(); + Iterator iterator = BrowserManager.getInstance().getWebBrowsers() + .iterator(); while (iterator.hasNext()) { IWebBrowser wb = (IWebBrowser) iterator.next(); if (wb instanceof IExternalWebBrowser) { @@ -278,7 +311,8 @@ public class WebBrowserUtil { return paths; } - // Add any supported EXTERNAL web browsers found after an arbitrary check in specific paths + // Add any supported EXTERNAL web browsers found after an arbitrary check in + // specific paths public static void addFoundBrowsers(List list) { List paths = getExternalBrowserPaths(); @@ -298,11 +332,14 @@ public class WebBrowserUtil { browser.location = location; browser.parameters = browser2.params; list.add(browser); - //Add browser here so that it get added to the table - BrowserManager.getInstance().addBrowser(browser); + // Add browser here so that it get added to the + // table + BrowserManager.getInstance() + .addBrowser(browser); j += size; } - } catch (Exception e) { } + } catch (Exception e) { + } } } } @@ -310,38 +347,42 @@ public class WebBrowserUtil { } /** - * Create an external Web browser if the file matches the default (known) browsers. + * Create an external Web browser if the file matches the default (known) + * browsers. + * * @param file * @return */ public static IExternalWebBrowserWorkingCopy createExternalBrowser(File file) { if (file == null || !file.isFile()) return null; - + String executable = file.getName(); Iterator iterator = getDefaultBrowsers().iterator(); while (iterator.hasNext()) { DefaultBrowser db = (DefaultBrowser) iterator.next(); if (executable.equals(db.executable)) { - IExternalWebBrowserWorkingCopy browser = BrowserManager.getInstance().createExternalWebBrowser(); + IExternalWebBrowserWorkingCopy browser = BrowserManager + .getInstance().createExternalWebBrowser(); browser.setName(db.name); browser.setLocation(file.getAbsolutePath()); browser.setParameters(db.params); return browser; } } - + return null; } protected static List getDefaultBrowsers() { if (defaultBrowsers2 != null) return defaultBrowsers2; - + Reader reader = null; defaultBrowsers2 = new ArrayList(); try { - URL url = WebBrowserUIPlugin.getInstance().getBundle().getEntry("defaultBrowsers.xml"); + URL url = WebBrowserUIPlugin.getInstance().getBundle().getEntry( + "defaultBrowsers.xml"); URL url2 = Platform.resolve(url); reader = new InputStreamReader(url2.openStream()); IMemento memento = XMLMemento.createReadRoot(reader); @@ -354,17 +395,18 @@ public class WebBrowserUtil { String executable = child.getString("executable"); String params = child.getString("params"); List locations = new ArrayList(); - + IMemento[] locat = child.getChildren("location"); if (locat != null) { int size2 = locat.length; for (int j = 0; j < size2; j++) locations.add(locat[j].getTextData()); } - + String[] loc = new String[locations.size()]; locations.toArray(loc); - DefaultBrowser db = new DefaultBrowser(name, executable, params, loc); + DefaultBrowser db = new DefaultBrowser(name, executable, + params, loc); Trace.trace(Trace.CONFIG, "Default browser: " + db); defaultBrowsers2.add(db); } @@ -374,7 +416,8 @@ public class WebBrowserUtil { } finally { try { reader.close(); - } catch (Exception e) { } + } catch (Exception e) { + } } return defaultBrowsers2; } diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/views/BrowserView.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/views/BrowserView.java index db5d321..92face4 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/views/BrowserView.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/views/BrowserView.java @@ -26,7 +26,7 @@ import org.eclipse.ui.part.ViewPart; * BrowserView is a simple demonstration of the SWT Browser * widget. It consists of a workbench view and tab folder where each tab in the * folder allows the user to interact with a control. - * + * * @see ViewPart */ public class BrowserView extends ViewPart implements IShowInTarget { @@ -38,7 +38,7 @@ public class BrowserView extends ViewPart implements IShowInTarget { /** * Create the example - * + * * @see ViewPart#createPartControl */ public void createPartControl(Composite frame) { @@ -53,7 +53,7 @@ public class BrowserView extends ViewPart implements IShowInTarget { /** * Called when we must grab focus. - * + * * @see org.eclipse.ui.part.ViewPart#setFocus */ public void setFocus() { diff --git a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/views/ShowInContextBrowser.java b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/views/ShowInContextBrowser.java index 20c3a98..c0fa7b5 100644 --- a/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/views/ShowInContextBrowser.java +++ b/net.sourceforge.phpeclipse.webbrowser/src/net/sourceforge/phpeclipse/webbrowser/views/ShowInContextBrowser.java @@ -5,13 +5,14 @@ import org.eclipse.ui.part.ShowInContext; /** * Adds an URL String to the ShowInContext for the BrowserUtil - * - * + * + * */ public class ShowInContextBrowser extends ShowInContext { String fLocalhostUrl; - public ShowInContextBrowser(Object input, ISelection selection, String localhostUrl) { + public ShowInContextBrowser(Object input, ISelection selection, + String localhostUrl) { super(input, selection); fLocalhostUrl = localhostUrl; } diff --git a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/Base64.java b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/Base64.java index 64cd0ae..1499af2 100644 --- a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/Base64.java +++ b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/Base64.java @@ -1,1450 +1,1413 @@ package net.sourceforge.phpeclipse.xdebug.core; + /** * Encodes and decodes to and from Base64 notation. - * + * *

    * Change Log: *

    *
      - *
    • v2.1 - Cleaned up javadoc comments and unused variables and methods. Added - * some convenience methods for reading and writing to and from files.
    • - *
    • v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems - * with other encodings (like EBCDIC).
    • - *
    • v2.0.1 - Fixed an error when decoding a single byte, that is, when the - * encoded data was a single byte.
    • - *
    • v2.0 - I got rid of methods that used booleans to set options. - * Now everything is more consolidated and cleaner. The code now detects - * when data that's being decoded is gzip-compressed and will decompress it - * automatically. Generally things are cleaner. You'll probably have to - * change some method calls that you were making to support the new - * options format (ints that you "OR" together).
    • - *
    • v1.5.1 - Fixed bug when decompressing and decoding to a - * byte[] using decode( String s, boolean gzipCompressed ). - * Added the ability to "suspend" encoding in the Output Stream so - * you can turn on and off the encoding if you need to embed base64 - * data in an otherwise "normal" stream (like an XML file).
    • - *
    • v1.5 - Output stream pases on flush() command but doesn't do anything itself. - * This helps when using GZIP streams. - * Added the ability to GZip-compress objects before encoding them.
    • - *
    • v1.4 - Added helper methods to read/write files.
    • - *
    • v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.
    • - *
    • v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream - * where last buffer being read, if not completely full, was not returned.
    • - *
    • v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.
    • - *
    • v1.3.3 - Fixed I/O streams which were totally messed up.
    • + *
    • v2.1 - Cleaned up javadoc comments and unused variables and methods. + * Added some convenience methods for reading and writing to and from files.
    • + *
    • v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on + * systems with other encodings (like EBCDIC).
    • + *
    • v2.0.1 - Fixed an error when decoding a single byte, that is, when the + * encoded data was a single byte.
    • + *
    • v2.0 - I got rid of methods that used booleans to set options. Now + * everything is more consolidated and cleaner. The code now detects when data + * that's being decoded is gzip-compressed and will decompress it automatically. + * Generally things are cleaner. You'll probably have to change some method + * calls that you were making to support the new options format (ints + * that you "OR" together).
    • + *
    • v1.5.1 - Fixed bug when decompressing and decoding to a byte[] using + * decode( String s, boolean gzipCompressed ). Added the ability to + * "suspend" encoding in the Output Stream so you can turn on and off the + * encoding if you need to embed base64 data in an otherwise "normal" stream + * (like an XML file).
    • + *
    • v1.5 - Output stream pases on flush() command but doesn't do anything + * itself. This helps when using GZIP streams. Added the ability to + * GZip-compress objects before encoding them.
    • + *
    • v1.4 - Added helper methods to read/write files.
    • + *
    • v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.
    • + *
    • v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input + * stream where last buffer being read, if not completely full, was not + * returned.
    • + *
    • v1.3.4 - Fixed when "improperly padded stream" error was thrown at the + * wrong time.
    • + *
    • v1.3.3 - Fixed I/O streams which were totally messed up.
    • *
    - * + * *

    - * I am placing this code in the Public Domain. Do with it as you will. - * This software comes with no guarantees or warranties but with - * plenty of well-wishing instead! - * Please visit http://iharder.net/base64 - * periodically to check for updates or to contribute improvements. + * I am placing this code in the Public Domain. Do with it as you will. This + * software comes with no guarantees or warranties but with plenty of + * well-wishing instead! Please visit http://iharder.net/base64 periodically + * to check for updates or to contribute improvements. *

    - * + * * @author Robert Harder * @author rob@iharder.net * @version 2.1 */ -public class Base64 -{ - -/* ******** P U B L I C F I E L D S ******** */ - - - /** No options specified. Value is zero. */ - public final static int NO_OPTIONS = 0; - - /** Specify encoding. */ - public final static int ENCODE = 1; - - - /** Specify decoding. */ - public final static int DECODE = 0; - - - /** Specify that data should be gzip-compressed. */ - public final static int GZIP = 2; - - - /** Don't break lines when encoding (violates strict Base64 specification) */ - public final static int DONT_BREAK_LINES = 8; - - -/* ******** P R I V A T E F I E L D S ******** */ - - - /** Maximum line length (76) of Base64 output. */ - private final static int MAX_LINE_LENGTH = 76; - - - /** The equals sign (=) as a byte. */ - private final static byte EQUALS_SIGN = (byte)'='; - - - /** The new line character (\n) as a byte. */ - private final static byte NEW_LINE = (byte)'\n'; - - - /** Preferred encoding. */ - private final static String PREFERRED_ENCODING = "UTF-8"; - - - /** The 64 valid Base64 values. */ - private final static byte[] ALPHABET; - private final static byte[] _NATIVE_ALPHABET = /* May be something funny like EBCDIC */ - { - (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', - (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', - (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', - (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', - (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', - (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', - (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', - (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', - (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', - (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' - }; - - /** Determine which ALPHABET to use. */ - static - { - byte[] __bytes; - try - { - __bytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".getBytes( PREFERRED_ENCODING ); - } // end try - catch (java.io.UnsupportedEncodingException use) - { - __bytes = _NATIVE_ALPHABET; // Fall back to native encoding - } // end catch - ALPHABET = __bytes; - } // end static - - - /** - * Translates a Base64 value to either its 6-bit reconstruction value - * or a negative number indicating some other meaning. - **/ - private final static byte[] DECODABET = - { - -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 - -5,-5, // Whitespace: Tab and Linefeed - -9,-9, // Decimal 11 - 12 - -5, // Whitespace: Carriage Return - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 - -9,-9,-9,-9,-9, // Decimal 27 - 31 - -5, // Whitespace: Space - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 - 62, // Plus sign at decimal 43 - -9,-9,-9, // Decimal 44 - 46 - 63, // Slash at decimal 47 - 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine - -9,-9,-9, // Decimal 58 - 60 - -1, // Equals sign at decimal 61 - -9,-9,-9, // Decimal 62 - 64 - 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' - 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' - -9,-9,-9,-9,-9,-9, // Decimal 91 - 96 - 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' - 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' - -9,-9,-9,-9 // Decimal 123 - 126 - /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ - }; - - // I think I end up not using the BAD_ENCODING indicator. - //private final static byte BAD_ENCODING = -9; // Indicates error in encoding - private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding - private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding - - - /** Defeats instantiation. */ - private Base64(){} - - - -/* ******** E N C O D I N G M E T H O D S ******** */ - - - /** - * Encodes up to the first three bytes of array threeBytes - * and returns a four-byte array in Base64 notation. - * The actual number of significant bytes in your array is - * given by numSigBytes. - * The array threeBytes needs only be as big as - * numSigBytes. - * Code can reuse a byte array by passing a four-byte array as b4. - * - * @param b4 A reusable byte array to reduce array instantiation - * @param threeBytes the array to convert - * @param numSigBytes the number of significant bytes in your array - * @return four byte array in Base64 notation. - * @since 1.5.1 - */ - private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes ) - { - encode3to4( threeBytes, 0, numSigBytes, b4, 0 ); - return b4; - } // end encode3to4 - - - /** - * Encodes up to three bytes of the array source - * and writes the resulting four Base64 bytes to destination. - * The source and destination arrays can be manipulated - * anywhere along their length by specifying - * srcOffset and destOffset. - * This method does not check to make sure your arrays - * are large enough to accomodate srcOffset + 3 for - * the source array or destOffset + 4 for - * the destination array. - * The actual number of significant bytes in your array is - * given by numSigBytes. - * - * @param source the array to convert - * @param srcOffset the index where conversion begins - * @param numSigBytes the number of significant bytes in your array - * @param destination the array to hold the conversion - * @param destOffset the index where output will be put - * @return the destination array - * @since 1.3 - */ - private static byte[] encode3to4( - byte[] source, int srcOffset, int numSigBytes, - byte[] destination, int destOffset ) - { - // 1 2 3 - // 01234567890123456789012345678901 Bit position - // --------000000001111111122222222 Array position from threeBytes - // --------| || || || | Six bit groups to index ALPHABET - // >>18 >>12 >> 6 >> 0 Right shift necessary - // 0x3f 0x3f 0x3f Additional AND - - // Create buffer with zero-padding if there are only one or two - // significant bytes passed in the array. - // We have to shift left 24 in order to flush out the 1's that appear - // when Java treats a value as negative that is cast from a byte to an int. - int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 ) - | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 ) - | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 ); - - switch( numSigBytes ) - { - case 3: - destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; - destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; - destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; - destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ]; - return destination; - - case 2: - destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; - destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; - destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; - destination[ destOffset + 3 ] = EQUALS_SIGN; - return destination; - - case 1: - destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; - destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; - destination[ destOffset + 2 ] = EQUALS_SIGN; - destination[ destOffset + 3 ] = EQUALS_SIGN; - return destination; - - default: - return destination; - } // end switch - } // end encode3to4 - - - - /** - * Serializes an object and returns the Base64-encoded - * version of that serialized object. If the object - * cannot be serialized or there is another error, - * the method will return null. - * The object is not GZip-compressed before being encoded. - * - * @param serializableObject The object to encode - * @return The Base64-encoded object - * @since 1.4 - */ - public static String encodeObject( java.io.Serializable serializableObject ) - { - return encodeObject( serializableObject, NO_OPTIONS ); - } // end encodeObject - - - - /** - * Serializes an object and returns the Base64-encoded - * version of that serialized object. If the object - * cannot be serialized or there is another error, - * the method will return null. - *

    - * Valid options:

    -     *   GZIP: gzip-compresses object before encoding it.
    -     *   DONT_BREAK_LINES: don't break lines at 76 characters
    -     *     Note: Technically, this makes your encoding non-compliant.
    -     * 
    - *

    - * Example: encodeObject( myObj, Base64.GZIP ) or - *

    - * Example: encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES ) - * - * @param serializableObject The object to encode - * @param options Specified options - * @return The Base64-encoded object - * @see Base64#GZIP - * @see Base64#DONT_BREAK_LINES - * @since 2.0 - */ - public static String encodeObject( java.io.Serializable serializableObject, int options ) - { - // Streams - java.io.ByteArrayOutputStream baos = null; - java.io.OutputStream b64os = null; - java.io.ObjectOutputStream oos = null; - java.util.zip.GZIPOutputStream gzos = null; - - // Isolate options - int gzip = (options & GZIP); - int dontBreakLines = (options & DONT_BREAK_LINES); - - try - { - // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream - baos = new java.io.ByteArrayOutputStream(); - b64os = new Base64.OutputStream( baos, ENCODE | dontBreakLines ); - - // GZip? - if( gzip == GZIP ) - { - gzos = new java.util.zip.GZIPOutputStream( b64os ); - oos = new java.io.ObjectOutputStream( gzos ); - } // end if: gzip - else - oos = new java.io.ObjectOutputStream( b64os ); - - oos.writeObject( serializableObject ); - } // end try - catch( java.io.IOException e ) - { - e.printStackTrace(); - return null; - } // end catch - finally - { - try{ oos.close(); } catch( Exception e ){} - try{ gzos.close(); } catch( Exception e ){} - try{ b64os.close(); } catch( Exception e ){} - try{ baos.close(); } catch( Exception e ){} - } // end finally - - // Return value according to relevant encoding. - try - { - return new String( baos.toByteArray(), PREFERRED_ENCODING ); - } // end try - catch (java.io.UnsupportedEncodingException uue) - { - return new String( baos.toByteArray() ); - } // end catch - - } // end encode - - - - /** - * Encodes a byte array into Base64 notation. - * Does not GZip-compress data. - * - * @param source The data to convert - * @since 1.4 - */ - public static String encodeBytes( byte[] source ) - { - return encodeBytes( source, 0, source.length, NO_OPTIONS ); - } // end encodeBytes - - - - /** - * Encodes a byte array into Base64 notation. - *

    - * Valid options:

    -     *   GZIP: gzip-compresses object before encoding it.
    -     *   DONT_BREAK_LINES: don't break lines at 76 characters
    -     *     Note: Technically, this makes your encoding non-compliant.
    -     * 
    - *

    - * Example: encodeBytes( myData, Base64.GZIP ) or - *

    - * Example: encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES ) - * - * - * @param source The data to convert - * @param options Specified options - * @see Base64#GZIP - * @see Base64#DONT_BREAK_LINES - * @since 2.0 - */ - public static String encodeBytes( byte[] source, int options ) - { - return encodeBytes( source, 0, source.length, options ); - } // end encodeBytes - - - /** - * Encodes a byte array into Base64 notation. - * Does not GZip-compress data. - * - * @param source The data to convert - * @param off Offset in array where conversion should begin - * @param len Length of data to convert - * @since 1.4 - */ - public static String encodeBytes( byte[] source, int off, int len ) - { - return encodeBytes( source, off, len, NO_OPTIONS ); - } // end encodeBytes - - - - /** - * Encodes a byte array into Base64 notation. - *

    - * Valid options:

    -     *   GZIP: gzip-compresses object before encoding it.
    -     *   DONT_BREAK_LINES: don't break lines at 76 characters
    -     *     Note: Technically, this makes your encoding non-compliant.
    -     * 
    - *

    - * Example: encodeBytes( myData, Base64.GZIP ) or - *

    - * Example: encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES ) - * - * - * @param source The data to convert - * @param off Offset in array where conversion should begin - * @param len Length of data to convert - * @param options Specified options - * @see Base64#GZIP - * @see Base64#DONT_BREAK_LINES - * @since 2.0 - */ - public static String encodeBytes( byte[] source, int off, int len, int options ) - { - // Isolate options - int dontBreakLines = ( options & DONT_BREAK_LINES ); - int gzip = ( options & GZIP ); - - // Compress? - if( gzip == GZIP ) - { - java.io.ByteArrayOutputStream baos = null; - java.util.zip.GZIPOutputStream gzos = null; - Base64.OutputStream b64os = null; - - - try - { - // GZip -> Base64 -> ByteArray - baos = new java.io.ByteArrayOutputStream(); - b64os = new Base64.OutputStream( baos, ENCODE | dontBreakLines ); - gzos = new java.util.zip.GZIPOutputStream( b64os ); - - gzos.write( source, off, len ); - gzos.close(); - } // end try - catch( java.io.IOException e ) - { - e.printStackTrace(); - return null; - } // end catch - finally - { - try{ gzos.close(); } catch( Exception e ){} - try{ b64os.close(); } catch( Exception e ){} - try{ baos.close(); } catch( Exception e ){} - } // end finally - - // Return value according to relevant encoding. - try - { - return new String( baos.toByteArray(), PREFERRED_ENCODING ); - } // end try - catch (java.io.UnsupportedEncodingException uue) - { - return new String( baos.toByteArray() ); - } // end catch - } // end if: compress - - // Else, don't compress. Better not to use streams at all then. - else - { - // Convert option to boolean in way that code likes it. - boolean breakLines = dontBreakLines == 0; - - int len43 = len * 4 / 3; - byte[] outBuff = new byte[ ( len43 ) // Main 4:3 - + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding - + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines - int d = 0; - int e = 0; - int len2 = len - 2; - int lineLength = 0; - for( ; d < len2; d+=3, e+=4 ) - { - encode3to4( source, d+off, 3, outBuff, e ); - - lineLength += 4; - if( breakLines && lineLength == MAX_LINE_LENGTH ) - { - outBuff[e+4] = NEW_LINE; - e++; - lineLength = 0; - } // end if: end of line - } // en dfor: each piece of array - - if( d < len ) - { - encode3to4( source, d+off, len - d, outBuff, e ); - e += 4; - } // end if: some padding needed - - - // Return value according to relevant encoding. - try - { - return new String( outBuff, 0, e, PREFERRED_ENCODING ); - } // end try - catch (java.io.UnsupportedEncodingException uue) - { - return new String( outBuff, 0, e ); - } // end catch - - } // end else: don't compress - - } // end encodeBytes - - - - - -/* ******** D E C O D I N G M E T H O D S ******** */ - - - /** - * Decodes four bytes from array source - * and writes the resulting bytes (up to three of them) - * to destination. - * The source and destination arrays can be manipulated - * anywhere along their length by specifying - * srcOffset and destOffset. - * This method does not check to make sure your arrays - * are large enough to accomodate srcOffset + 4 for - * the source array or destOffset + 3 for - * the destination array. - * This method returns the actual number of bytes that - * were converted from the Base64 encoding. - * - * - * @param source the array to convert - * @param srcOffset the index where conversion begins - * @param destination the array to hold the conversion - * @param destOffset the index where output will be put - * @return the number of decoded bytes converted - * @since 1.3 - */ - private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset ) - { - // Example: Dk== - if( source[ srcOffset + 2] == EQUALS_SIGN ) - { - // Two ways to do the same thing. Don't know which way I like best. - //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) - // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); - int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) - | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 ); - - destination[ destOffset ] = (byte)( outBuff >>> 16 ); - return 1; - } - - // Example: DkL= - else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) - { - // Two ways to do the same thing. Don't know which way I like best. - //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) - // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) - // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); - int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) - | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) - | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 ); - - destination[ destOffset ] = (byte)( outBuff >>> 16 ); - destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 ); - return 2; - } - - // Example: DkLE - else - { - try{ - // Two ways to do the same thing. Don't know which way I like best. - //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) - // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) - // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) - // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); - int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) - | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) - | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6) - | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) ); - - - destination[ destOffset ] = (byte)( outBuff >> 16 ); - destination[ destOffset + 1 ] = (byte)( outBuff >> 8 ); - destination[ destOffset + 2 ] = (byte)( outBuff ); - - return 3; - }catch( Exception e){ - System.out.println(""+source[srcOffset]+ ": " + ( DECODABET[ source[ srcOffset ] ] ) ); - System.out.println(""+source[srcOffset+1]+ ": " + ( DECODABET[ source[ srcOffset + 1 ] ] ) ); - System.out.println(""+source[srcOffset+2]+ ": " + ( DECODABET[ source[ srcOffset + 2 ] ] ) ); - System.out.println(""+source[srcOffset+3]+ ": " + ( DECODABET[ source[ srcOffset + 3 ] ] ) ); - return -1; - } //e nd catch - } - } // end decodeToBytes - - - - - /** - * Very low-level access to decoding ASCII characters in - * the form of a byte array. Does not support automatically - * gunzipping or any other "fancy" features. - * - * @param source The Base64 encoded data - * @param off The offset of where to begin decoding - * @param len The length of characters to decode - * @return decoded data - * @since 1.3 - */ - public static byte[] decode( byte[] source, int off, int len ) - { - int len34 = len * 3 / 4; - byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output - int outBuffPosn = 0; - - byte[] b4 = new byte[4]; - int b4Posn = 0; - int i = 0; - byte sbiCrop = 0; - byte sbiDecode = 0; - for( i = off; i < off+len; i++ ) - { - sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits - sbiDecode = DECODABET[ sbiCrop ]; - - if( sbiDecode >= WHITE_SPACE_ENC ) // White space, Equals sign or better - { - if( sbiDecode >= EQUALS_SIGN_ENC ) - { - b4[ b4Posn++ ] = sbiCrop; - if( b4Posn > 3 ) - { - outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn ); - b4Posn = 0; - - // If that was the equals sign, break out of 'for' loop - if( sbiCrop == EQUALS_SIGN ) - break; - } // end if: quartet built - - } // end if: equals sign or better - - } // end if: white space, equals sign or better - else - { - System.err.println( "Bad Base64 input character at " + i + ": " + source[i] + "(decimal)" ); - return null; - } // end else: - } // each input character - - byte[] out = new byte[ outBuffPosn ]; - System.arraycopy( outBuff, 0, out, 0, outBuffPosn ); - return out; - } // end decode - - - - - /** - * Decodes data from Base64 notation, automatically - * detecting gzip-compressed data and decompressing it. - * - * @param s the string to decode - * @return the decoded data - * @since 1.4 - */ - public static byte[] decode( String s ) - { - byte[] bytes; - try - { - bytes = s.getBytes( PREFERRED_ENCODING ); - } // end try - catch( java.io.UnsupportedEncodingException uee ) - { - bytes = s.getBytes(); - } // end catch - // - - // Decode - bytes = decode( bytes, 0, bytes.length ); - - - // Check to see if it's gzip-compressed - // GZIP Magic Two-Byte Number: 0x8b1f (35615) - if( bytes != null && bytes.length >= 4 ) - { - - int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); - if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) - { - java.io.ByteArrayInputStream bais = null; - java.util.zip.GZIPInputStream gzis = null; - java.io.ByteArrayOutputStream baos = null; - byte[] buffer = new byte[2048]; - int length = 0; - - try - { - baos = new java.io.ByteArrayOutputStream(); - bais = new java.io.ByteArrayInputStream( bytes ); - gzis = new java.util.zip.GZIPInputStream( bais ); - - while( ( length = gzis.read( buffer ) ) >= 0 ) - { - baos.write(buffer,0,length); - } // end while: reading input - - // No error? Get new bytes. - bytes = baos.toByteArray(); - - } // end try - catch( java.io.IOException e ) - { - // Just return originally-decoded bytes - } // end catch - finally - { - try{ baos.close(); } catch( Exception e ){} - try{ gzis.close(); } catch( Exception e ){} - try{ bais.close(); } catch( Exception e ){} - } // end finally - - } // end if: gzipped - } // end if: bytes.length >= 2 - - return bytes; - } // end decode - - - - - /** - * Attempts to decode Base64 data and deserialize a Java - * Object within. Returns null if there was an error. - * - * @param encodedObject The Base64 data to decode - * @return The decoded and deserialized object - * @since 1.5 - */ - public static Object decodeToObject( String encodedObject ) - { - // Decode and gunzip if necessary - byte[] objBytes = decode( encodedObject ); - - java.io.ByteArrayInputStream bais = null; - java.io.ObjectInputStream ois = null; - Object obj = null; - - try - { - bais = new java.io.ByteArrayInputStream( objBytes ); - ois = new java.io.ObjectInputStream( bais ); - - obj = ois.readObject(); - } // end try - catch( java.io.IOException e ) - { - e.printStackTrace(); - obj = null; - } // end catch - catch( java.lang.ClassNotFoundException e ) - { - e.printStackTrace(); - obj = null; - } // end catch - finally - { - try{ bais.close(); } catch( Exception e ){} - try{ ois.close(); } catch( Exception e ){} - } // end finally - - return obj; - } // end decodeObject - - - - /** - * Convenience method for encoding data to a file. - * - * @param dataToEncode byte array of data to encode in base64 form - * @param filename Filename for saving encoded data - * @return true if successful, false otherwise - * - * @since 2.1 - */ - public static boolean encodeToFile( byte[] dataToEncode, String filename ) - { - boolean success = false; - Base64.OutputStream bos = null; - try - { - bos = new Base64.OutputStream( - new java.io.FileOutputStream( filename ), Base64.ENCODE ); - bos.write( dataToEncode ); - success = true; - } // end try - catch( java.io.IOException e ) - { - - success = false; - } // end catch: IOException - finally - { - try{ bos.close(); } catch( Exception e ){} - } // end finally - - return success; - } // end encodeToFile - - - /** - * Convenience method for decoding data to a file. - * - * @param dataToDecode Base64-encoded data as a string - * @param filename Filename for saving decoded data - * @return true if successful, false otherwise - * - * @since 2.1 - */ - public static boolean decodeToFile( String dataToDecode, String filename ) - { - boolean success = false; - Base64.OutputStream bos = null; - try - { - bos = new Base64.OutputStream( - new java.io.FileOutputStream( filename ), Base64.DECODE ); - bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) ); - success = true; - } // end try - catch( java.io.IOException e ) - { - success = false; - } // end catch: IOException - finally - { - try{ bos.close(); } catch( Exception e ){} - } // end finally - - return success; - } // end decodeToFile - - - - - /** - * Convenience method for reading a base64-encoded - * file and decoding it. - * - * @param filename Filename for reading encoded data - * @return decoded byte array or null if unsuccessful - * - * @since 2.1 - */ - public static byte[] decodeFromFile( String filename ) - { - byte[] decodedData = null; - Base64.InputStream bis = null; - try - { - // Set up some useful variables - java.io.File file = new java.io.File( filename ); - byte[] buffer = null; - int length = 0; - int numBytes = 0; - - // Check for size of file - if( file.length() > Integer.MAX_VALUE ) - { - System.err.println( "File is too big for this convenience method (" + file.length() + " bytes)." ); - return null; - } // end if: file too big for int index - buffer = new byte[ (int)file.length() ]; - - // Open a stream - bis = new Base64.InputStream( - new java.io.BufferedInputStream( - new java.io.FileInputStream( file ) ), Base64.DECODE ); - - // Read until done - while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) - length += numBytes; - - // Save in a variable to return - decodedData = new byte[ length ]; - System.arraycopy( buffer, 0, decodedData, 0, length ); - - } // end try - catch( java.io.IOException e ) - { - System.err.println( "Error decoding from file " + filename ); - } // end catch: IOException - finally - { - try{ bis.close(); } catch( Exception e) {} - } // end finally - - return decodedData; - } // end decodeFromFile - - - - /** - * Convenience method for reading a binary file - * and base64-encoding it. - * - * @param filename Filename for reading binary data - * @return base64-encoded string or null if unsuccessful - * - * @since 2.1 - */ - public static String encodeFromFile( String filename ) - { - String encodedData = null; - Base64.InputStream bis = null; - try - { - // Set up some useful variables - java.io.File file = new java.io.File( filename ); - byte[] buffer = new byte[ (int)(file.length() * 1.4) ]; - int length = 0; - int numBytes = 0; - - // Open a stream - bis = new Base64.InputStream( - new java.io.BufferedInputStream( - new java.io.FileInputStream( file ) ), Base64.ENCODE ); - - // Read until done - while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) - length += numBytes; - - // Save in a variable to return - encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING ); - - } // end try - catch( java.io.IOException e ) - { - System.err.println( "Error encoding from file " + filename ); - } // end catch: IOException - finally - { - try{ bis.close(); } catch( Exception e) {} - } // end finally - - return encodedData; - } // end encodeFromFile - - - - - /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */ - - - - /** - * A {@link Base64.InputStream} will read data from another - * java.io.InputStream, given in the constructor, - * and encode/decode to/from Base64 notation on the fly. - * - * @see Base64 - * @since 1.3 - */ - public static class InputStream extends java.io.FilterInputStream - { - private boolean encode; // Encoding or decoding - private int position; // Current position in the buffer - private byte[] buffer; // Small buffer holding converted data - private int bufferLength; // Length of buffer (3 or 4) - private int numSigBytes; // Number of meaningful bytes in the buffer - private int lineLength; - private boolean breakLines; // Break lines at less than 80 characters - - - /** - * Constructs a {@link Base64.InputStream} in DECODE mode. - * - * @param in the java.io.InputStream from which to read data. - * @since 1.3 - */ - public InputStream( java.io.InputStream in ) - { - this( in, DECODE ); - } // end constructor - - - /** - * Constructs a {@link Base64.InputStream} in - * either ENCODE or DECODE mode. - *

    - * Valid options:

    -         *   ENCODE or DECODE: Encode or Decode as data is read.
    -         *   DONT_BREAK_LINES: don't break lines at 76 characters
    -         *     (only meaningful when encoding)
    -         *     Note: Technically, this makes your encoding non-compliant.
    -         * 
    - *

    - * Example: new Base64.InputStream( in, Base64.DECODE ) - * - * - * @param in the java.io.InputStream from which to read data. - * @param options Specified options - * @see Base64#ENCODE - * @see Base64#DECODE - * @see Base64#DONT_BREAK_LINES - * @since 2.0 - */ - public InputStream( java.io.InputStream in, int options ) - { - super( in ); - this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES; - this.encode = (options & ENCODE) == ENCODE; - this.bufferLength = encode ? 4 : 3; - this.buffer = new byte[ bufferLength ]; - this.position = -1; - this.lineLength = 0; - } // end constructor - - /** - * Reads enough of the input stream to convert - * to/from Base64 and returns the next byte. - * - * @return next byte - * @since 1.3 - */ - public int read() throws java.io.IOException - { - // Do we need to get data? - if( position < 0 ) - { - if( encode ) - { - byte[] b3 = new byte[3]; - int numBinaryBytes = 0; - for( int i = 0; i < 3; i++ ) - { - try - { - int b = in.read(); - - // If end of stream, b is -1. - if( b >= 0 ) - { - b3[i] = (byte)b; - numBinaryBytes++; - } // end if: not end of stream - - } // end try: read - catch( java.io.IOException e ) - { - // Only a problem if we got no data at all. - if( i == 0 ) - throw e; - - } // end catch - } // end for: each needed input byte - - if( numBinaryBytes > 0 ) - { - encode3to4( b3, 0, numBinaryBytes, buffer, 0 ); - position = 0; - numSigBytes = 4; - } // end if: got data - else - { - return -1; - } // end else - } // end if: encoding - - // Else decoding - else - { - byte[] b4 = new byte[4]; - int i = 0; - for( i = 0; i < 4; i++ ) - { - // Read four "meaningful" bytes: - int b = 0; - do{ b = in.read(); } - while( b >= 0 && DECODABET[ b & 0x7f ] <= WHITE_SPACE_ENC ); - - if( b < 0 ) - break; // Reads a -1 if end of stream - - b4[i] = (byte)b; - } // end for: each needed input byte - - if( i == 4 ) - { - numSigBytes = decode4to3( b4, 0, buffer, 0 ); - position = 0; - } // end if: got four characters - else if( i == 0 ){ - return -1; - } // end else if: also padded correctly - else - { - // Must have broken out from above. - throw new java.io.IOException( "Improperly padded Base64 input." ); - } // end - - } // end else: decode - } // end else: get data - - // Got data? - if( position >= 0 ) - { - // End of relevant data? - if( /*!encode &&*/ position >= numSigBytes ) - return -1; - - if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) - { - lineLength = 0; - return '\n'; - } // end if - else - { - lineLength++; // This isn't important when decoding - // but throwing an extra "if" seems - // just as wasteful. - - int b = buffer[ position++ ]; - - if( position >= bufferLength ) - position = -1; - - return b & 0xFF; // This is how you "cast" a byte that's - // intended to be unsigned. - } // end else - } // end if: position >= 0 - - // Else error - else - { - // When JDK1.4 is more accepted, use an assertion here. - throw new java.io.IOException( "Error in Base64 code reading stream." ); - } // end else - } // end read - - - /** - * Calls {@link #read()} repeatedly until the end of stream - * is reached or len bytes are read. - * Returns number of bytes read into array or -1 if - * end of stream is encountered. - * - * @param dest array to hold values - * @param off offset for array - * @param len max number of bytes to read into array - * @return bytes read into array or -1 if end of stream is encountered. - * @since 1.3 - */ - public int read( byte[] dest, int off, int len ) throws java.io.IOException - { - int i; - int b; - for( i = 0; i < len; i++ ) - { - b = read(); - - //if( b < 0 && i == 0 ) - // return -1; - - if( b >= 0 ) - dest[off + i] = (byte)b; - else if( i == 0 ) - return -1; - else - break; // Out of 'for' loop - } // end for: each byte read - return i; - } // end read - - } // end inner class InputStream - - - - - - - /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */ - - - - /** - * A {@link Base64.OutputStream} will write data to another - * java.io.OutputStream, given in the constructor, - * and encode/decode to/from Base64 notation on the fly. - * - * @see Base64 - * @since 1.3 - */ - public static class OutputStream extends java.io.FilterOutputStream - { - private boolean encode; - private int position; - private byte[] buffer; - private int bufferLength; - private int lineLength; - private boolean breakLines; - private byte[] b4; // Scratch used in a few places - private boolean suspendEncoding; - - /** - * Constructs a {@link Base64.OutputStream} in ENCODE mode. - * - * @param out the java.io.OutputStream to which data will be written. - * @since 1.3 - */ - public OutputStream( java.io.OutputStream out ) - { - this( out, ENCODE ); - } // end constructor - - - /** - * Constructs a {@link Base64.OutputStream} in - * either ENCODE or DECODE mode. - *

    - * Valid options:

    -         *   ENCODE or DECODE: Encode or Decode as data is read.
    -         *   DONT_BREAK_LINES: don't break lines at 76 characters
    -         *     (only meaningful when encoding)
    -         *     Note: Technically, this makes your encoding non-compliant.
    -         * 
    - *

    - * Example: new Base64.OutputStream( out, Base64.ENCODE ) - * - * @param out the java.io.OutputStream to which data will be written. - * @param options Specified options. - * @see Base64#ENCODE - * @see Base64#DECODE - * @see Base64#DONT_BREAK_LINES - * @since 1.3 - */ - public OutputStream( java.io.OutputStream out, int options ) - { - super( out ); - this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES; - this.encode = (options & ENCODE) == ENCODE; - this.bufferLength = encode ? 3 : 4; - this.buffer = new byte[ bufferLength ]; - this.position = 0; - this.lineLength = 0; - this.suspendEncoding = false; - this.b4 = new byte[4]; - } // end constructor - - - /** - * Writes the byte to the output stream after - * converting to/from Base64 notation. - * When encoding, bytes are buffered three - * at a time before the output stream actually - * gets a write() call. - * When decoding, bytes are buffered four - * at a time. - * - * @param theByte the byte to write - * @since 1.3 - */ - public void write(int theByte) throws java.io.IOException - { - // Encoding suspended? - if( suspendEncoding ) - { - super.out.write( theByte ); - return; - } // end if: supsended - - // Encode? - if( encode ) - { - buffer[ position++ ] = (byte)theByte; - if( position >= bufferLength ) // Enough to encode. - { - out.write( encode3to4( b4, buffer, bufferLength ) ); - - lineLength += 4; - if( breakLines && lineLength >= MAX_LINE_LENGTH ) - { - out.write( NEW_LINE ); - lineLength = 0; - } // end if: end of line - - position = 0; - } // end if: enough to output - } // end if: encoding - - // Else, Decoding - else - { - // Meaningful Base64 character? - if( DECODABET[ theByte & 0x7f ] > WHITE_SPACE_ENC ) - { - buffer[ position++ ] = (byte)theByte; - if( position >= bufferLength ) // Enough to output. - { - int len = Base64.decode4to3( buffer, 0, b4, 0 ); - out.write( b4, 0, len ); - //out.write( Base64.decode4to3( buffer ) ); - position = 0; - } // end if: enough to output - } // end if: meaningful base64 character - else if( DECODABET[ theByte & 0x7f ] != WHITE_SPACE_ENC ) - { - throw new java.io.IOException( "Invalid character in Base64 data." ); - } // end else: not white space either - } // end else: decoding - } // end write - - - - /** - * Calls {@link #write(int)} repeatedly until len - * bytes are written. - * - * @param theBytes array from which to read bytes - * @param off offset for array - * @param len max number of bytes to read into array - * @since 1.3 - */ - public void write( byte[] theBytes, int off, int len ) throws java.io.IOException - { - // Encoding suspended? - if( suspendEncoding ) - { - super.out.write( theBytes, off, len ); - return; - } // end if: supsended - - for( int i = 0; i < len; i++ ) - { - write( theBytes[ off + i ] ); - } // end for: each byte written - - } // end write - - - - /** - * Method added by PHIL. [Thanks, PHIL. -Rob] - * This pads the buffer without closing the stream. - */ - public void flushBase64() throws java.io.IOException - { - if( position > 0 ) - { - if( encode ) - { - out.write( encode3to4( b4, buffer, position ) ); - position = 0; - } // end if: encoding - else - { - throw new java.io.IOException( "Base64 input not properly padded." ); - } // end else: decoding - } // end if: buffer partially full - - } // end flush - - - /** - * Flushes and closes (I think, in the superclass) the stream. - * - * @since 1.3 - */ - public void close() throws java.io.IOException - { - // 1. Ensure that pending characters are written - flushBase64(); - - // 2. Actually close the stream - // Base class both flushes and closes. - super.close(); - - buffer = null; - out = null; - } // end close - - - - /** - * Suspends encoding of the stream. - * May be helpful if you need to embed a piece of - * base640-encoded data in a stream. - * - * @since 1.5.1 - */ - public void suspendEncoding() throws java.io.IOException - { - flushBase64(); - this.suspendEncoding = true; - } // end suspendEncoding - - - /** - * Resumes encoding of the stream. - * May be helpful if you need to embed a piece of - * base640-encoded data in a stream. - * - * @since 1.5.1 - */ - public void resumeEncoding() - { - this.suspendEncoding = false; - } // end resumeEncoding - - - - } // end inner class OutputStream - - -} // end class Base64 +public class Base64 { + + /* ******** P U B L I C F I E L D S ******** */ + + /** No options specified. Value is zero. */ + public final static int NO_OPTIONS = 0; + + /** Specify encoding. */ + public final static int ENCODE = 1; + + /** Specify decoding. */ + public final static int DECODE = 0; + + /** Specify that data should be gzip-compressed. */ + public final static int GZIP = 2; + + /** Don't break lines when encoding (violates strict Base64 specification) */ + public final static int DONT_BREAK_LINES = 8; + + /* ******** P R I V A T E F I E L D S ******** */ + + /** Maximum line length (76) of Base64 output. */ + private final static int MAX_LINE_LENGTH = 76; + + /** The equals sign (=) as a byte. */ + private final static byte EQUALS_SIGN = (byte) '='; + + /** The new line character (\n) as a byte. */ + private final static byte NEW_LINE = (byte) '\n'; + + /** Preferred encoding. */ + private final static String PREFERRED_ENCODING = "UTF-8"; + + /** The 64 valid Base64 values. */ + private final static byte[] ALPHABET; + + private final static byte[] _NATIVE_ALPHABET = /* + * May be something funny + * like EBCDIC + */ + { (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', + (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', + (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', + (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', + (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', + (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', + (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', + (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', + (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', + (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', + (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', + (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', + (byte) '9', (byte) '+', (byte) '/' }; + + /** Determine which ALPHABET to use. */ + static { + byte[] __bytes; + try { + __bytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" + .getBytes(PREFERRED_ENCODING); + } // end try + catch (java.io.UnsupportedEncodingException use) { + __bytes = _NATIVE_ALPHABET; // Fall back to native encoding + } // end catch + ALPHABET = __bytes; + } // end static + + /** + * Translates a Base64 value to either its 6-bit reconstruction value or a + * negative number indicating some other meaning. + */ + private final static byte[] DECODABET = { -9, -9, -9, -9, -9, -9, -9, -9, + -9, // Decimal 0 - 8 + -5, -5, // Whitespace: Tab and Linefeed + -9, -9, // Decimal 11 - 12 + -5, // Whitespace: Carriage Return + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - + // 26 + -9, -9, -9, -9, -9, // Decimal 27 - 31 + -5, // Whitespace: Space + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 + 62, // Plus sign at decimal 43 + -9, -9, -9, // Decimal 44 - 46 + 63, // Slash at decimal 47 + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine + -9, -9, -9, // Decimal 58 - 60 + -1, // Equals sign at decimal 61 + -9, -9, -9, // Decimal 62 - 64 + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' + // through 'N' + 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' + // through 'Z' + -9, -9, -9, -9, -9, -9, // Decimal 91 - 96 + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' + // through 'm' + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' + // through 'z' + -9, -9, -9, -9 // Decimal 123 - 126 + /* + * ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 + * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 + */ + }; + + // I think I end up not using the BAD_ENCODING indicator. + // private final static byte BAD_ENCODING = -9; // Indicates error in + // encoding + private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in + // encoding + + private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in + // encoding + + /** Defeats instantiation. */ + private Base64() { + } + + /* ******** E N C O D I N G M E T H O D S ******** */ + + /** + * Encodes up to the first three bytes of array threeBytes and + * returns a four-byte array in Base64 notation. The actual number of + * significant bytes in your array is given by numSigBytes. The + * array threeBytes needs only be as big as numSigBytes. + * Code can reuse a byte array by passing a four-byte array as b4. + * + * @param b4 + * A reusable byte array to reduce array instantiation + * @param threeBytes + * the array to convert + * @param numSigBytes + * the number of significant bytes in your array + * @return four byte array in Base64 notation. + * @since 1.5.1 + */ + private static byte[] encode3to4(byte[] b4, byte[] threeBytes, + int numSigBytes) { + encode3to4(threeBytes, 0, numSigBytes, b4, 0); + return b4; + } // end encode3to4 + + /** + * Encodes up to three bytes of the array source and writes the + * resulting four Base64 bytes to destination. The source and + * destination arrays can be manipulated anywhere along their length by + * specifying srcOffset and destOffset. This method + * does not check to make sure your arrays are large enough to accomodate + * srcOffset + 3 for the source array or + * destOffset + 4 for the destination array. The + * actual number of significant bytes in your array is given by + * numSigBytes. + * + * @param source + * the array to convert + * @param srcOffset + * the index where conversion begins + * @param numSigBytes + * the number of significant bytes in your array + * @param destination + * the array to hold the conversion + * @param destOffset + * the index where output will be put + * @return the destination array + * @since 1.3 + */ + private static byte[] encode3to4(byte[] source, int srcOffset, + int numSigBytes, byte[] destination, int destOffset) { + // 1 2 3 + // 01234567890123456789012345678901 Bit position + // --------000000001111111122222222 Array position from threeBytes + // --------| || || || | Six bit groups to index ALPHABET + // >>18 >>12 >> 6 >> 0 Right shift necessary + // 0x3f 0x3f 0x3f Additional AND + + // Create buffer with zero-padding if there are only one or two + // significant bytes passed in the array. + // We have to shift left 24 in order to flush out the 1's that appear + // when Java treats a value as negative that is cast from a byte to an + // int. + int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0) + | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) + | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0); + + switch (numSigBytes) { + case 3: + destination[destOffset] = ALPHABET[(inBuff >>> 18)]; + destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; + destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f]; + destination[destOffset + 3] = ALPHABET[(inBuff) & 0x3f]; + return destination; + + case 2: + destination[destOffset] = ALPHABET[(inBuff >>> 18)]; + destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; + destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f]; + destination[destOffset + 3] = EQUALS_SIGN; + return destination; + + case 1: + destination[destOffset] = ALPHABET[(inBuff >>> 18)]; + destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; + destination[destOffset + 2] = EQUALS_SIGN; + destination[destOffset + 3] = EQUALS_SIGN; + return destination; + + default: + return destination; + } // end switch + } // end encode3to4 + + /** + * Serializes an object and returns the Base64-encoded version of that + * serialized object. If the object cannot be serialized or there is another + * error, the method will return null. The object is not + * GZip-compressed before being encoded. + * + * @param serializableObject + * The object to encode + * @return The Base64-encoded object + * @since 1.4 + */ + public static String encodeObject(java.io.Serializable serializableObject) { + return encodeObject(serializableObject, NO_OPTIONS); + } // end encodeObject + + /** + * Serializes an object and returns the Base64-encoded version of that + * serialized object. If the object cannot be serialized or there is another + * error, the method will return null. + *

    + * Valid options: + * + *

    +	 *    GZIP: gzip-compresses object before encoding it.
    +	 *    DONT_BREAK_LINES: don't break lines at 76 characters
    +	 *      <i>Note: Technically, this makes your encoding non-compliant.</i>
    +	 * 
    + * + *

    + * Example: encodeObject( myObj, Base64.GZIP ) or + *

    + * Example: + * encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES ) + * + * @param serializableObject + * The object to encode + * @param options + * Specified options + * @return The Base64-encoded object + * @see Base64#GZIP + * @see Base64#DONT_BREAK_LINES + * @since 2.0 + */ + public static String encodeObject(java.io.Serializable serializableObject, + int options) { + // Streams + java.io.ByteArrayOutputStream baos = null; + java.io.OutputStream b64os = null; + java.io.ObjectOutputStream oos = null; + java.util.zip.GZIPOutputStream gzos = null; + + // Isolate options + int gzip = (options & GZIP); + int dontBreakLines = (options & DONT_BREAK_LINES); + + try { + // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream + baos = new java.io.ByteArrayOutputStream(); + b64os = new Base64.OutputStream(baos, ENCODE | dontBreakLines); + + // GZip? + if (gzip == GZIP) { + gzos = new java.util.zip.GZIPOutputStream(b64os); + oos = new java.io.ObjectOutputStream(gzos); + } // end if: gzip + else + oos = new java.io.ObjectOutputStream(b64os); + + oos.writeObject(serializableObject); + } // end try + catch (java.io.IOException e) { + e.printStackTrace(); + return null; + } // end catch + finally { + try { + oos.close(); + } catch (Exception e) { + } + try { + gzos.close(); + } catch (Exception e) { + } + try { + b64os.close(); + } catch (Exception e) { + } + try { + baos.close(); + } catch (Exception e) { + } + } // end finally + + // Return value according to relevant encoding. + try { + return new String(baos.toByteArray(), PREFERRED_ENCODING); + } // end try + catch (java.io.UnsupportedEncodingException uue) { + return new String(baos.toByteArray()); + } // end catch + + } // end encode + + /** + * Encodes a byte array into Base64 notation. Does not GZip-compress data. + * + * @param source + * The data to convert + * @since 1.4 + */ + public static String encodeBytes(byte[] source) { + return encodeBytes(source, 0, source.length, NO_OPTIONS); + } // end encodeBytes + + /** + * Encodes a byte array into Base64 notation. + *

    + * Valid options: + * + *

    +	 *    GZIP: gzip-compresses object before encoding it.
    +	 *    DONT_BREAK_LINES: don't break lines at 76 characters
    +	 *      <i>Note: Technically, this makes your encoding non-compliant.</i>
    +	 * 
    + * + *

    + * Example: encodeBytes( myData, Base64.GZIP ) or + *

    + * Example: + * encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES ) + * + * + * @param source + * The data to convert + * @param options + * Specified options + * @see Base64#GZIP + * @see Base64#DONT_BREAK_LINES + * @since 2.0 + */ + public static String encodeBytes(byte[] source, int options) { + return encodeBytes(source, 0, source.length, options); + } // end encodeBytes + + /** + * Encodes a byte array into Base64 notation. Does not GZip-compress data. + * + * @param source + * The data to convert + * @param off + * Offset in array where conversion should begin + * @param len + * Length of data to convert + * @since 1.4 + */ + public static String encodeBytes(byte[] source, int off, int len) { + return encodeBytes(source, off, len, NO_OPTIONS); + } // end encodeBytes + + /** + * Encodes a byte array into Base64 notation. + *

    + * Valid options: + * + *

    +	 *    GZIP: gzip-compresses object before encoding it.
    +	 *    DONT_BREAK_LINES: don't break lines at 76 characters
    +	 *      <i>Note: Technically, this makes your encoding non-compliant.</i>
    +	 * 
    + * + *

    + * Example: encodeBytes( myData, Base64.GZIP ) or + *

    + * Example: + * encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES ) + * + * + * @param source + * The data to convert + * @param off + * Offset in array where conversion should begin + * @param len + * Length of data to convert + * @param options + * Specified options + * @see Base64#GZIP + * @see Base64#DONT_BREAK_LINES + * @since 2.0 + */ + public static String encodeBytes(byte[] source, int off, int len, + int options) { + // Isolate options + int dontBreakLines = (options & DONT_BREAK_LINES); + int gzip = (options & GZIP); + + // Compress? + if (gzip == GZIP) { + java.io.ByteArrayOutputStream baos = null; + java.util.zip.GZIPOutputStream gzos = null; + Base64.OutputStream b64os = null; + + try { + // GZip -> Base64 -> ByteArray + baos = new java.io.ByteArrayOutputStream(); + b64os = new Base64.OutputStream(baos, ENCODE | dontBreakLines); + gzos = new java.util.zip.GZIPOutputStream(b64os); + + gzos.write(source, off, len); + gzos.close(); + } // end try + catch (java.io.IOException e) { + e.printStackTrace(); + return null; + } // end catch + finally { + try { + gzos.close(); + } catch (Exception e) { + } + try { + b64os.close(); + } catch (Exception e) { + } + try { + baos.close(); + } catch (Exception e) { + } + } // end finally + + // Return value according to relevant encoding. + try { + return new String(baos.toByteArray(), PREFERRED_ENCODING); + } // end try + catch (java.io.UnsupportedEncodingException uue) { + return new String(baos.toByteArray()); + } // end catch + } // end if: compress + + // Else, don't compress. Better not to use streams at all then. + else { + // Convert option to boolean in way that code likes it. + boolean breakLines = dontBreakLines == 0; + + int len43 = len * 4 / 3; + byte[] outBuff = new byte[(len43) // Main 4:3 + + ((len % 3) > 0 ? 4 : 0) // Account for padding + + (breakLines ? (len43 / MAX_LINE_LENGTH) : 0)]; // New + // lines + int d = 0; + int e = 0; + int len2 = len - 2; + int lineLength = 0; + for (; d < len2; d += 3, e += 4) { + encode3to4(source, d + off, 3, outBuff, e); + + lineLength += 4; + if (breakLines && lineLength == MAX_LINE_LENGTH) { + outBuff[e + 4] = NEW_LINE; + e++; + lineLength = 0; + } // end if: end of line + } // en dfor: each piece of array + + if (d < len) { + encode3to4(source, d + off, len - d, outBuff, e); + e += 4; + } // end if: some padding needed + + // Return value according to relevant encoding. + try { + return new String(outBuff, 0, e, PREFERRED_ENCODING); + } // end try + catch (java.io.UnsupportedEncodingException uue) { + return new String(outBuff, 0, e); + } // end catch + + } // end else: don't compress + + } // end encodeBytes + + /* ******** D E C O D I N G M E T H O D S ******** */ + + /** + * Decodes four bytes from array source and writes the resulting + * bytes (up to three of them) to destination. The source and + * destination arrays can be manipulated anywhere along their length by + * specifying srcOffset and destOffset. This method + * does not check to make sure your arrays are large enough to accomodate + * srcOffset + 4 for the source array or + * destOffset + 3 for the destination array. This + * method returns the actual number of bytes that were converted from the + * Base64 encoding. + * + * + * @param source + * the array to convert + * @param srcOffset + * the index where conversion begins + * @param destination + * the array to hold the conversion + * @param destOffset + * the index where output will be put + * @return the number of decoded bytes converted + * @since 1.3 + */ + private static int decode4to3(byte[] source, int srcOffset, + byte[] destination, int destOffset) { + // Example: Dk== + if (source[srcOffset + 2] == EQUALS_SIGN) { + // Two ways to do the same thing. Don't know which way I like best. + // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 + // ) + // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); + int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) + | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12); + + destination[destOffset] = (byte) (outBuff >>> 16); + return 1; + } + + // Example: DkL= + else if (source[srcOffset + 3] == EQUALS_SIGN) { + // Two ways to do the same thing. Don't know which way I like best. + // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 + // ) + // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) + // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); + int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) + | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12) + | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6); + + destination[destOffset] = (byte) (outBuff >>> 16); + destination[destOffset + 1] = (byte) (outBuff >>> 8); + return 2; + } + + // Example: DkLE + else { + try { + // Two ways to do the same thing. Don't know which way I like + // best. + // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) + // >>> 6 ) + // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) + // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) + // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); + int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) + | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12) + | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6) + | ((DECODABET[source[srcOffset + 3]] & 0xFF)); + + destination[destOffset] = (byte) (outBuff >> 16); + destination[destOffset + 1] = (byte) (outBuff >> 8); + destination[destOffset + 2] = (byte) (outBuff); + + return 3; + } catch (Exception e) { + System.out.println("" + source[srcOffset] + ": " + + (DECODABET[source[srcOffset]])); + System.out.println("" + source[srcOffset + 1] + ": " + + (DECODABET[source[srcOffset + 1]])); + System.out.println("" + source[srcOffset + 2] + ": " + + (DECODABET[source[srcOffset + 2]])); + System.out.println("" + source[srcOffset + 3] + ": " + + (DECODABET[source[srcOffset + 3]])); + return -1; + } // e nd catch + } + } // end decodeToBytes + + /** + * Very low-level access to decoding ASCII characters in the form of a byte + * array. Does not support automatically gunzipping or any other "fancy" + * features. + * + * @param source + * The Base64 encoded data + * @param off + * The offset of where to begin decoding + * @param len + * The length of characters to decode + * @return decoded data + * @since 1.3 + */ + public static byte[] decode(byte[] source, int off, int len) { + int len34 = len * 3 / 4; + byte[] outBuff = new byte[len34]; // Upper limit on size of output + int outBuffPosn = 0; + + byte[] b4 = new byte[4]; + int b4Posn = 0; + int i = 0; + byte sbiCrop = 0; + byte sbiDecode = 0; + for (i = off; i < off + len; i++) { + sbiCrop = (byte) (source[i] & 0x7f); // Only the low seven bits + sbiDecode = DECODABET[sbiCrop]; + + if (sbiDecode >= WHITE_SPACE_ENC) // White space, Equals sign or + // better + { + if (sbiDecode >= EQUALS_SIGN_ENC) { + b4[b4Posn++] = sbiCrop; + if (b4Posn > 3) { + outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn); + b4Posn = 0; + + // If that was the equals sign, break out of 'for' loop + if (sbiCrop == EQUALS_SIGN) + break; + } // end if: quartet built + + } // end if: equals sign or better + + } // end if: white space, equals sign or better + else { + System.err.println("Bad Base64 input character at " + i + ": " + + source[i] + "(decimal)"); + return null; + } // end else: + } // each input character + + byte[] out = new byte[outBuffPosn]; + System.arraycopy(outBuff, 0, out, 0, outBuffPosn); + return out; + } // end decode + + /** + * Decodes data from Base64 notation, automatically detecting + * gzip-compressed data and decompressing it. + * + * @param s + * the string to decode + * @return the decoded data + * @since 1.4 + */ + public static byte[] decode(String s) { + byte[] bytes; + try { + bytes = s.getBytes(PREFERRED_ENCODING); + } // end try + catch (java.io.UnsupportedEncodingException uee) { + bytes = s.getBytes(); + } // end catch + // + + // Decode + bytes = decode(bytes, 0, bytes.length); + + // Check to see if it's gzip-compressed + // GZIP Magic Two-Byte Number: 0x8b1f (35615) + if (bytes != null && bytes.length >= 4) { + + int head = ((int) bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); + if (java.util.zip.GZIPInputStream.GZIP_MAGIC == head) { + java.io.ByteArrayInputStream bais = null; + java.util.zip.GZIPInputStream gzis = null; + java.io.ByteArrayOutputStream baos = null; + byte[] buffer = new byte[2048]; + int length = 0; + + try { + baos = new java.io.ByteArrayOutputStream(); + bais = new java.io.ByteArrayInputStream(bytes); + gzis = new java.util.zip.GZIPInputStream(bais); + + while ((length = gzis.read(buffer)) >= 0) { + baos.write(buffer, 0, length); + } // end while: reading input + + // No error? Get new bytes. + bytes = baos.toByteArray(); + + } // end try + catch (java.io.IOException e) { + // Just return originally-decoded bytes + } // end catch + finally { + try { + baos.close(); + } catch (Exception e) { + } + try { + gzis.close(); + } catch (Exception e) { + } + try { + bais.close(); + } catch (Exception e) { + } + } // end finally + + } // end if: gzipped + } // end if: bytes.length >= 2 + + return bytes; + } // end decode + + /** + * Attempts to decode Base64 data and deserialize a Java Object within. + * Returns null if there was an error. + * + * @param encodedObject + * The Base64 data to decode + * @return The decoded and deserialized object + * @since 1.5 + */ + public static Object decodeToObject(String encodedObject) { + // Decode and gunzip if necessary + byte[] objBytes = decode(encodedObject); + + java.io.ByteArrayInputStream bais = null; + java.io.ObjectInputStream ois = null; + Object obj = null; + + try { + bais = new java.io.ByteArrayInputStream(objBytes); + ois = new java.io.ObjectInputStream(bais); + + obj = ois.readObject(); + } // end try + catch (java.io.IOException e) { + e.printStackTrace(); + obj = null; + } // end catch + catch (java.lang.ClassNotFoundException e) { + e.printStackTrace(); + obj = null; + } // end catch + finally { + try { + bais.close(); + } catch (Exception e) { + } + try { + ois.close(); + } catch (Exception e) { + } + } // end finally + + return obj; + } // end decodeObject + + /** + * Convenience method for encoding data to a file. + * + * @param dataToEncode + * byte array of data to encode in base64 form + * @param filename + * Filename for saving encoded data + * @return true if successful, false otherwise + * + * @since 2.1 + */ + public static boolean encodeToFile(byte[] dataToEncode, String filename) { + boolean success = false; + Base64.OutputStream bos = null; + try { + bos = new Base64.OutputStream( + new java.io.FileOutputStream(filename), Base64.ENCODE); + bos.write(dataToEncode); + success = true; + } // end try + catch (java.io.IOException e) { + + success = false; + } // end catch: IOException + finally { + try { + bos.close(); + } catch (Exception e) { + } + } // end finally + + return success; + } // end encodeToFile + + /** + * Convenience method for decoding data to a file. + * + * @param dataToDecode + * Base64-encoded data as a string + * @param filename + * Filename for saving decoded data + * @return true if successful, false otherwise + * + * @since 2.1 + */ + public static boolean decodeToFile(String dataToDecode, String filename) { + boolean success = false; + Base64.OutputStream bos = null; + try { + bos = new Base64.OutputStream( + new java.io.FileOutputStream(filename), Base64.DECODE); + bos.write(dataToDecode.getBytes(PREFERRED_ENCODING)); + success = true; + } // end try + catch (java.io.IOException e) { + success = false; + } // end catch: IOException + finally { + try { + bos.close(); + } catch (Exception e) { + } + } // end finally + + return success; + } // end decodeToFile + + /** + * Convenience method for reading a base64-encoded file and decoding it. + * + * @param filename + * Filename for reading encoded data + * @return decoded byte array or null if unsuccessful + * + * @since 2.1 + */ + public static byte[] decodeFromFile(String filename) { + byte[] decodedData = null; + Base64.InputStream bis = null; + try { + // Set up some useful variables + java.io.File file = new java.io.File(filename); + byte[] buffer = null; + int length = 0; + int numBytes = 0; + + // Check for size of file + if (file.length() > Integer.MAX_VALUE) { + System.err + .println("File is too big for this convenience method (" + + file.length() + " bytes)."); + return null; + } // end if: file too big for int index + buffer = new byte[(int) file.length()]; + + // Open a stream + bis = new Base64.InputStream(new java.io.BufferedInputStream( + new java.io.FileInputStream(file)), Base64.DECODE); + + // Read until done + while ((numBytes = bis.read(buffer, length, 4096)) >= 0) + length += numBytes; + + // Save in a variable to return + decodedData = new byte[length]; + System.arraycopy(buffer, 0, decodedData, 0, length); + + } // end try + catch (java.io.IOException e) { + System.err.println("Error decoding from file " + filename); + } // end catch: IOException + finally { + try { + bis.close(); + } catch (Exception e) { + } + } // end finally + + return decodedData; + } // end decodeFromFile + + /** + * Convenience method for reading a binary file and base64-encoding it. + * + * @param filename + * Filename for reading binary data + * @return base64-encoded string or null if unsuccessful + * + * @since 2.1 + */ + public static String encodeFromFile(String filename) { + String encodedData = null; + Base64.InputStream bis = null; + try { + // Set up some useful variables + java.io.File file = new java.io.File(filename); + byte[] buffer = new byte[(int) (file.length() * 1.4)]; + int length = 0; + int numBytes = 0; + + // Open a stream + bis = new Base64.InputStream(new java.io.BufferedInputStream( + new java.io.FileInputStream(file)), Base64.ENCODE); + + // Read until done + while ((numBytes = bis.read(buffer, length, 4096)) >= 0) + length += numBytes; + + // Save in a variable to return + encodedData = new String(buffer, 0, length, + Base64.PREFERRED_ENCODING); + + } // end try + catch (java.io.IOException e) { + System.err.println("Error encoding from file " + filename); + } // end catch: IOException + finally { + try { + bis.close(); + } catch (Exception e) { + } + } // end finally + + return encodedData; + } // end encodeFromFile + + /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */ + + /** + * A {@link Base64.InputStream} will read data from another + * java.io.InputStream, given in the constructor, and + * encode/decode to/from Base64 notation on the fly. + * + * @see Base64 + * @since 1.3 + */ + public static class InputStream extends java.io.FilterInputStream { + private boolean encode; // Encoding or decoding + + private int position; // Current position in the buffer + + private byte[] buffer; // Small buffer holding converted data + + private int bufferLength; // Length of buffer (3 or 4) + + private int numSigBytes; // Number of meaningful bytes in the buffer + + private int lineLength; + + private boolean breakLines; // Break lines at less than 80 characters + + /** + * Constructs a {@link Base64.InputStream} in DECODE mode. + * + * @param in + * the java.io.InputStream from which to read + * data. + * @since 1.3 + */ + public InputStream(java.io.InputStream in) { + this(in, DECODE); + } // end constructor + + /** + * Constructs a {@link Base64.InputStream} in either ENCODE or DECODE + * mode. + *

    + * Valid options: + * + *

    +		 *    ENCODE or DECODE: Encode or Decode as data is read.
    +		 *    DONT_BREAK_LINES: don't break lines at 76 characters
    +		 *      (only meaningful when encoding)
    +		 *      <i>Note: Technically, this makes your encoding non-compliant.</i>
    +		 * 
    + * + *

    + * Example: new Base64.InputStream( in, Base64.DECODE ) + * + * + * @param in + * the java.io.InputStream from which to read + * data. + * @param options + * Specified options + * @see Base64#ENCODE + * @see Base64#DECODE + * @see Base64#DONT_BREAK_LINES + * @since 2.0 + */ + public InputStream(java.io.InputStream in, int options) { + super(in); + this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES; + this.encode = (options & ENCODE) == ENCODE; + this.bufferLength = encode ? 4 : 3; + this.buffer = new byte[bufferLength]; + this.position = -1; + this.lineLength = 0; + } // end constructor + + /** + * Reads enough of the input stream to convert to/from Base64 and + * returns the next byte. + * + * @return next byte + * @since 1.3 + */ + public int read() throws java.io.IOException { + // Do we need to get data? + if (position < 0) { + if (encode) { + byte[] b3 = new byte[3]; + int numBinaryBytes = 0; + for (int i = 0; i < 3; i++) { + try { + int b = in.read(); + + // If end of stream, b is -1. + if (b >= 0) { + b3[i] = (byte) b; + numBinaryBytes++; + } // end if: not end of stream + + } // end try: read + catch (java.io.IOException e) { + // Only a problem if we got no data at all. + if (i == 0) + throw e; + + } // end catch + } // end for: each needed input byte + + if (numBinaryBytes > 0) { + encode3to4(b3, 0, numBinaryBytes, buffer, 0); + position = 0; + numSigBytes = 4; + } // end if: got data + else { + return -1; + } // end else + } // end if: encoding + + // Else decoding + else { + byte[] b4 = new byte[4]; + int i = 0; + for (i = 0; i < 4; i++) { + // Read four "meaningful" bytes: + int b = 0; + do { + b = in.read(); + } while (b >= 0 + && DECODABET[b & 0x7f] <= WHITE_SPACE_ENC); + + if (b < 0) + break; // Reads a -1 if end of stream + + b4[i] = (byte) b; + } // end for: each needed input byte + + if (i == 4) { + numSigBytes = decode4to3(b4, 0, buffer, 0); + position = 0; + } // end if: got four characters + else if (i == 0) { + return -1; + } // end else if: also padded correctly + else { + // Must have broken out from above. + throw new java.io.IOException( + "Improperly padded Base64 input."); + } // end + + } // end else: decode + } // end else: get data + + // Got data? + if (position >= 0) { + // End of relevant data? + if ( /* !encode && */position >= numSigBytes) + return -1; + + if (encode && breakLines && lineLength >= MAX_LINE_LENGTH) { + lineLength = 0; + return '\n'; + } // end if + else { + lineLength++; // This isn't important when decoding + // but throwing an extra "if" seems + // just as wasteful. + + int b = buffer[position++]; + + if (position >= bufferLength) + position = -1; + + return b & 0xFF; // This is how you "cast" a byte that's + // intended to be unsigned. + } // end else + } // end if: position >= 0 + + // Else error + else { + // When JDK1.4 is more accepted, use an assertion here. + throw new java.io.IOException( + "Error in Base64 code reading stream."); + } // end else + } // end read + + /** + * Calls {@link #read()} repeatedly until the end of stream is reached + * or len bytes are read. Returns number of bytes read into + * array or -1 if end of stream is encountered. + * + * @param dest + * array to hold values + * @param off + * offset for array + * @param len + * max number of bytes to read into array + * @return bytes read into array or -1 if end of stream is encountered. + * @since 1.3 + */ + public int read(byte[] dest, int off, int len) + throws java.io.IOException { + int i; + int b; + for (i = 0; i < len; i++) { + b = read(); + + // if( b < 0 && i == 0 ) + // return -1; + + if (b >= 0) + dest[off + i] = (byte) b; + else if (i == 0) + return -1; + else + break; // Out of 'for' loop + } // end for: each byte read + return i; + } // end read + + } // end inner class InputStream + + /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */ + + /** + * A {@link Base64.OutputStream} will write data to another + * java.io.OutputStream, given in the constructor, and + * encode/decode to/from Base64 notation on the fly. + * + * @see Base64 + * @since 1.3 + */ + public static class OutputStream extends java.io.FilterOutputStream { + private boolean encode; + + private int position; + + private byte[] buffer; + + private int bufferLength; + + private int lineLength; + + private boolean breakLines; + + private byte[] b4; // Scratch used in a few places + + private boolean suspendEncoding; + + /** + * Constructs a {@link Base64.OutputStream} in ENCODE mode. + * + * @param out + * the java.io.OutputStream to which data will be + * written. + * @since 1.3 + */ + public OutputStream(java.io.OutputStream out) { + this(out, ENCODE); + } // end constructor + + /** + * Constructs a {@link Base64.OutputStream} in either ENCODE or DECODE + * mode. + *

    + * Valid options: + * + *

    +		 *    ENCODE or DECODE: Encode or Decode as data is read.
    +		 *    DONT_BREAK_LINES: don't break lines at 76 characters
    +		 *      (only meaningful when encoding)
    +		 *      <i>Note: Technically, this makes your encoding non-compliant.</i>
    +		 * 
    + * + *

    + * Example: new Base64.OutputStream( out, Base64.ENCODE ) + * + * @param out + * the java.io.OutputStream to which data will be + * written. + * @param options + * Specified options. + * @see Base64#ENCODE + * @see Base64#DECODE + * @see Base64#DONT_BREAK_LINES + * @since 1.3 + */ + public OutputStream(java.io.OutputStream out, int options) { + super(out); + this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES; + this.encode = (options & ENCODE) == ENCODE; + this.bufferLength = encode ? 3 : 4; + this.buffer = new byte[bufferLength]; + this.position = 0; + this.lineLength = 0; + this.suspendEncoding = false; + this.b4 = new byte[4]; + } // end constructor + + /** + * Writes the byte to the output stream after converting to/from Base64 + * notation. When encoding, bytes are buffered three at a time before + * the output stream actually gets a write() call. When decoding, bytes + * are buffered four at a time. + * + * @param theByte + * the byte to write + * @since 1.3 + */ + public void write(int theByte) throws java.io.IOException { + // Encoding suspended? + if (suspendEncoding) { + super.out.write(theByte); + return; + } // end if: supsended + + // Encode? + if (encode) { + buffer[position++] = (byte) theByte; + if (position >= bufferLength) // Enough to encode. + { + out.write(encode3to4(b4, buffer, bufferLength)); + + lineLength += 4; + if (breakLines && lineLength >= MAX_LINE_LENGTH) { + out.write(NEW_LINE); + lineLength = 0; + } // end if: end of line + + position = 0; + } // end if: enough to output + } // end if: encoding + + // Else, Decoding + else { + // Meaningful Base64 character? + if (DECODABET[theByte & 0x7f] > WHITE_SPACE_ENC) { + buffer[position++] = (byte) theByte; + if (position >= bufferLength) // Enough to output. + { + int len = Base64.decode4to3(buffer, 0, b4, 0); + out.write(b4, 0, len); + // out.write( Base64.decode4to3( buffer ) ); + position = 0; + } // end if: enough to output + } // end if: meaningful base64 character + else if (DECODABET[theByte & 0x7f] != WHITE_SPACE_ENC) { + throw new java.io.IOException( + "Invalid character in Base64 data."); + } // end else: not white space either + } // end else: decoding + } // end write + + /** + * Calls {@link #write(int)} repeatedly until len bytes are + * written. + * + * @param theBytes + * array from which to read bytes + * @param off + * offset for array + * @param len + * max number of bytes to read into array + * @since 1.3 + */ + public void write(byte[] theBytes, int off, int len) + throws java.io.IOException { + // Encoding suspended? + if (suspendEncoding) { + super.out.write(theBytes, off, len); + return; + } // end if: supsended + + for (int i = 0; i < len; i++) { + write(theBytes[off + i]); + } // end for: each byte written + + } // end write + + /** + * Method added by PHIL. [Thanks, PHIL. -Rob] This pads the buffer + * without closing the stream. + */ + public void flushBase64() throws java.io.IOException { + if (position > 0) { + if (encode) { + out.write(encode3to4(b4, buffer, position)); + position = 0; + } // end if: encoding + else { + throw new java.io.IOException( + "Base64 input not properly padded."); + } // end else: decoding + } // end if: buffer partially full + + } // end flush + + /** + * Flushes and closes (I think, in the superclass) the stream. + * + * @since 1.3 + */ + public void close() throws java.io.IOException { + // 1. Ensure that pending characters are written + flushBase64(); + + // 2. Actually close the stream + // Base class both flushes and closes. + super.close(); + + buffer = null; + out = null; + } // end close + + /** + * Suspends encoding of the stream. May be helpful if you need to embed + * a piece of base640-encoded data in a stream. + * + * @since 1.5.1 + */ + public void suspendEncoding() throws java.io.IOException { + flushBase64(); + this.suspendEncoding = true; + } // end suspendEncoding + + /** + * Resumes encoding of the stream. May be helpful if you need to embed a + * piece of base640-encoded data in a stream. + * + * @since 1.5.1 + */ + public void resumeEncoding() { + this.suspendEncoding = false; + } // end resumeEncoding + + } // end inner class OutputStream + +} // end class Base64 diff --git a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/BreakpointResponseData.java b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/BreakpointResponseData.java index a316b5b..b0f3444 100644 --- a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/BreakpointResponseData.java +++ b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/BreakpointResponseData.java @@ -2,17 +2,18 @@ package net.sourceforge.phpeclipse.xdebug.core; public class BreakpointResponseData extends ResponseData { - private int BreakpointID=-1; + private int BreakpointID = -1; - BreakpointResponseData(int transactionID,int breakpointID) { + BreakpointResponseData(int transactionID, int breakpointID) { super(transactionID); - BreakpointID=breakpointID; + BreakpointID = breakpointID; } -// public BreakpointResponseData(ResponseData data,int breakpointID) { -// setTransactionID(data.getTransactionID()); -// BreakpointID=breakpointID; -// } - + + // public BreakpointResponseData(ResponseData data,int breakpointID) { + // setTransactionID(data.getTransactionID()); + // BreakpointID=breakpointID; + // } + public int getBreakpointID() { return BreakpointID; } @@ -20,5 +21,5 @@ public class BreakpointResponseData extends ResponseData { public void setBreakpointID(int breakpointID) { BreakpointID = breakpointID; } - + } diff --git a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/DebugConnection.java b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/DebugConnection.java index 64c8550..e28b56b 100644 --- a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/DebugConnection.java +++ b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/DebugConnection.java @@ -9,17 +9,13 @@ import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.util.HashMap; -import java.util.LinkedList; -import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; - import net.sourceforge.phpeclipse.xdebug.php.model.XDebugLineBreakpoint; import net.sourceforge.phpeclipse.xdebug.php.model.XDebugTarget; -import net.sourceforge.phpeclipse.xdebug.php.model.XDebugThread; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; @@ -29,51 +25,68 @@ import org.eclipse.core.runtime.jobs.Job; import org.eclipse.debug.core.DebugEvent; import org.eclipse.debug.core.DebugException; import org.eclipse.debug.core.model.IBreakpoint; -import org.eclipse.debug.core.model.IThread; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.xml.sax.SAXException; public class DebugConnection { - + private ServerSocket fDebugServerSocket; + private DebugResponse lastResponse; + private Socket fDebugSocket; + private OutputStreamWriter fDebugWriter; + private DataInputStream fDebugReader; + private ResponseListenerJob fResponseListener; - + // Settings for Debug Process - private int fTransactionID=0; + private int fTransactionID = 0; + private String fileuri = ""; - private String appID=""; + + private String appID = ""; + private String lastCommand = ""; + private XDebugTarget fDebugTarget; + private HashMap ResponseList; public class DebugResponse { private Node parentNode; - private int fTransactionID=-1; - private String fCommand=""; + + private int fTransactionID = -1; + + private String fCommand = ""; + private String fStatus; + private String fReason; + private String fName; - private boolean fError; - public synchronized void setParentNode (String xmlInput){ - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder=null; - Document doc=null; + private boolean fError; + + public synchronized void setParentNode(String xmlInput) { + DocumentBuilderFactory factory = DocumentBuilderFactory + .newInstance(); + DocumentBuilder builder = null; + Document doc = null; try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } - ByteArrayInputStream InputXMLStream = new ByteArrayInputStream(xmlInput.getBytes()); - + ByteArrayInputStream InputXMLStream = new ByteArrayInputStream( + xmlInput.getBytes()); + try { doc = builder.parse(InputXMLStream); } catch (SAXException e) { @@ -83,49 +96,49 @@ public class DebugConnection { // TODO Auto-generated catch block e.printStackTrace(); } - parentNode=doc.getFirstChild(); - fName=parentNode.getNodeName(); + parentNode = doc.getFirstChild(); + fName = parentNode.getNodeName(); String idStr = getAttributeValue("transaction_id"); - if (idStr!="") + if (idStr != "") fTransactionID = Integer.parseInt(idStr); fCommand = getAttributeValue("command"); fStatus = getAttributeValue("status"); fReason = getAttributeValue("reason"); -// notifyAll(); + // notifyAll(); } - - public String getAttributeValue (String AttributeName) { + + public String getAttributeValue(String AttributeName) { String strValue = ""; if (parentNode.hasAttributes()) { NamedNodeMap listAttribute = parentNode.getAttributes(); Node attribute = listAttribute.getNamedItem(AttributeName); - if (attribute !=null) + if (attribute != null) strValue = attribute.getNodeValue(); } return strValue; } - - public synchronized Node getParentNode(){ + + public synchronized Node getParentNode() { return parentNode; } - + public synchronized String getCommand() { return fCommand; } + public synchronized String getName() { return fName; } - - - DebugResponse () { + + DebugResponse() { fTransactionID = -1; fCommand = ""; fStatus = ""; - fReason = ""; - fName= ""; + fReason = ""; + fName = ""; } - - DebugResponse (String XMLInput) { + + DebugResponse(String XMLInput) { setParentNode(XMLInput); } @@ -140,56 +153,53 @@ public class DebugConnection { public synchronized int getTransactionID() { return fTransactionID; } - + private synchronized DebugResponse waitforTransactionID(int id) { - while (fTransactionID!= id) { + while (fTransactionID != id) { try { wait(); } catch (InterruptedException e) { } } -// XDebugCorePlugin.log(IStatus.INFO,"got TransID: "+id); + // XDebugCorePlugin.log(IStatus.INFO,"got TransID: "+id); return this; } - public boolean isError() { + public boolean isError() { return fError; } public void setError(boolean error) { fError = error; } - + protected synchronized void notifyWait() { notifyAll(); } } - - + /** - * Listens to events from the XDebug and fires corresponding - * debug events. + * Listens to events from the XDebug and fires corresponding debug events. */ class ResponseListenerJob extends Job { - + public ResponseListenerJob() { super("XDebug Event Dispatch"); setSystem(true); - + } - - - - + private void checkResponse(DebugResponse response) { - Node node=response.getParentNode(); + Node node = response.getParentNode(); if (node.hasChildNodes()) { - Node child=node.getFirstChild(); + Node child = node.getFirstChild(); if (child.getNodeName().equals("error")) { - int code = Integer.parseInt(PHPDebugUtils.getAttributeValue(child, "code")); - String text=(child.getFirstChild()).getNodeValue(); - XDebugCorePlugin.log(IStatus.ERROR,lastCommand+" ERROR "+code+": "+text); + int code = Integer.parseInt(PHPDebugUtils + .getAttributeValue(child, "code")); + String text = (child.getFirstChild()).getNodeValue(); + XDebugCorePlugin.log(IStatus.ERROR, lastCommand + " ERROR " + + code + ": " + text); lastResponse.setError(true); return; } @@ -197,11 +207,12 @@ public class DebugConnection { lastResponse.setError(false); if (response.getStatus().equals("stopped")) terminated(); - else if (response.getStatus().equals("break") && response.getReason().equals("ok")){ - if (response.getCommand().equals("run")) { // breakpoint hit - int id=-1; + else if (response.getStatus().equals("break") + && response.getReason().equals("ok")) { + if (response.getCommand().equals("run")) { // breakpoint hit + int id = -1; try { - id=sendRequest("stack_get"); + id = sendRequest("stack_get"); } catch (DebugException e) { // TODO Auto-generated catch block e.printStackTrace(); @@ -210,31 +221,38 @@ public class DebugConnection { if (InputXML != null) { XDebugCorePlugin.log(IStatus.INFO, InputXML); lastResponse.setParentNode(InputXML); - fDebugTarget.breakpointHit(lastResponse.getParentNode()); + fDebugTarget + .breakpointHit(lastResponse.getParentNode()); } - + } else if (response.getCommand().equals("step_into")) { // step_into fDebugTarget.suspended(DebugEvent.STEP_END); -// XDebugCorePlugin.log(IStatus.INFO,response.getCommand()+" STEP_END sent"); + // XDebugCorePlugin.log(IStatus.INFO,response.getCommand()+" + // STEP_END sent"); } else if (response.getCommand().equals("step_over")) { // step_over fDebugTarget.suspended(DebugEvent.STEP_END); -// XDebugCorePlugin.log(IStatus.INFO,response.getCommand()+" STEP_END sent"); + // XDebugCorePlugin.log(IStatus.INFO,response.getCommand()+" + // STEP_END sent"); } else if (response.getCommand().equals("step_out")) { // step_over fDebugTarget.suspended(DebugEvent.STEP_END); -// XDebugCorePlugin.log(IStatus.INFO,response.getCommand()+" STEP_END sent"); - } + // XDebugCorePlugin.log(IStatus.INFO,response.getCommand()+" + // STEP_END sent"); + } } else if (response.getCommand().equals("breakpoint_set")) { // step_over - String idStr=response.getAttributeValue("id"); - if (idStr!="") { - int targetID=response.getTransactionID(); - BreakpointResponseData ResponseData= new BreakpointResponseData(response.getTransactionID(),Integer.parseInt(idStr)); + String idStr = response.getAttributeValue("id"); + if (idStr != "") { + int targetID = response.getTransactionID(); + BreakpointResponseData ResponseData = new BreakpointResponseData( + response.getTransactionID(), Integer + .parseInt(idStr)); fDebugTarget.fireDebugResponseEvent(ResponseData); - IBreakpoint[] breakpoints=XDebugCorePlugin.getBreakpoints(); - for(int i=0;i< breakpoints.length;i++) { - XDebugLineBreakpoint breakpoint=(XDebugLineBreakpoint)breakpoints[i]; + IBreakpoint[] breakpoints = XDebugCorePlugin + .getBreakpoints(); + for (int i = 0; i < breakpoints.length; i++) { + XDebugLineBreakpoint breakpoint = (XDebugLineBreakpoint) breakpoints[i]; try { - if (breakpoint.getID()==targetID) + if (breakpoint.getID() == targetID) breakpoint.setID(Integer.parseInt(idStr)); } catch (NumberFormatException e) { // TODO Auto-generated catch block @@ -246,10 +264,12 @@ public class DebugConnection { } } } - + } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor) */ protected IStatus run(IProgressMonitor monitor) { @@ -260,49 +280,53 @@ public class DebugConnection { XDebugCorePlugin.log(IStatus.INFO, InputXML); lastResponse.setParentNode(InputXML); if (lastResponse.getName() == "init") { - Node myNode=lastResponse.getParentNode(); - appID = PHPDebugUtils.getAttributeValue(myNode, "appid"); - fileuri = PHPDebugUtils.getAttributeValue(myNode, "fileuri"); -// fDebugTarget.started(); + Node myNode = lastResponse.getParentNode(); + appID = PHPDebugUtils + .getAttributeValue(myNode, "appid"); + fileuri = PHPDebugUtils.getAttributeValue(myNode, + "fileuri"); + // fDebugTarget.started(); fDebugTarget.fireCreationEvent(); } else if (lastResponse.getName() == "response") { checkResponse(lastResponse); } - ResponseList.put(new Integer(lastResponse.getTransactionID()),lastResponse); + ResponseList.put(new Integer(lastResponse + .getTransactionID()), lastResponse); lastResponse.notifyWait(); } } return Status.OK_STATUS; } - + } - - public DebugConnection (XDebugTarget debugTarget,int debugPort) { - fDebugTarget=debugTarget; - lastResponse=new DebugResponse(); - ResponseList= new HashMap(); - + public DebugConnection(XDebugTarget debugTarget, int debugPort) { + fDebugTarget = debugTarget; + lastResponse = new DebugResponse(); + ResponseList = new HashMap(); + try { fDebugServerSocket = new ServerSocket(debugPort); fDebugSocket = fDebugServerSocket.accept(); - fDebugWriter = new OutputStreamWriter(fDebugSocket.getOutputStream(), "UTF8"); - fDebugReader = new DataInputStream(fDebugSocket.getInputStream()); -// fDebugReader = new BufferedReader(new InputStreamReader(fDebugSocket.getInputStream())); - + fDebugWriter = new OutputStreamWriter(fDebugSocket + .getOutputStream(), "UTF8"); + fDebugReader = new DataInputStream(fDebugSocket.getInputStream()); + // fDebugReader = new BufferedReader(new + // InputStreamReader(fDebugSocket.getInputStream())); + } catch (UnknownHostException e) { -// abort("Unable to connect to PHP Debuger", e); + // abort("Unable to connect to PHP Debuger", e); } catch (IOException e) { -// abort("Unable to connect to PHP Debuger", e); + // abort("Unable to connect to PHP Debuger", e); } fResponseListener = new ResponseListenerJob(); fResponseListener.schedule(); } - + private void terminated() { try { - fDebugReader.close(); + fDebugReader.close(); fDebugWriter.close(); fDebugSocket.close(); fDebugServerSocket.close(); @@ -313,96 +337,95 @@ public class DebugConnection { fDebugTarget.terminated(); } - - private String readData() - { - byte byteBuffer[]=null,b; - int count=0; - + + private String readData() { + byte byteBuffer[] = null, b; + int count = 0; + try { - while ( (b =fDebugReader.readByte())!=0) - { - count=count*10+b-'0'; -// count=count*10+Integer.parseInt(b); + while ((b = fDebugReader.readByte()) != 0) { + count = count * 10 + b - '0'; + // count=count*10+Integer.parseInt(b); } -// System.out.println(count); + // System.out.println(count); byteBuffer = new byte[count]; - int readCount=0; - int attempts=0; - while ((count >0) && (attempts <5)) { - int rc=fDebugReader.read(byteBuffer,readCount,count); - count-=rc; - readCount+=rc; + int readCount = 0; + int attempts = 0; + while ((count > 0) && (attempts < 5)) { + int rc = fDebugReader.read(byteBuffer, readCount, count); + count -= rc; + readCount += rc; attempts++; } - if((b= fDebugReader.readByte())!=0) // reads the NULL Byte at the end; - System.out.println("NULL-Byte missing!!"); + if ((b = fDebugReader.readByte()) != 0) // reads the NULL Byte at + // the end; + System.out.println("NULL-Byte missing!!"); } catch (IOException e) { // TODO Auto-generated catch block - if (e instanceof EOFException==false) + if (e instanceof EOFException == false) e.printStackTrace(); return null; } return new String(byteBuffer); } - /** * Sends a request to the Debugengine and waits for an OK. * - * @param command debug command - * @throws DebugException if the request fails + * @param command + * debug command + * @throws DebugException + * if the request fails */ - - - public int sendRequest(String command) throws DebugException { - return sendRequest(command,""); + + public int sendRequest(String command) throws DebugException { + return sendRequest(command, ""); } - + /** * Sends a request to the Debugengine and waits for an OK. * - * @param command debug command + * @param command + * debug command * @arguments arguments for the command - * @throws DebugException if the request fails + * @throws DebugException + * if the request fails */ - - public synchronized int sendRequest(String command, String arguments) throws DebugException { - -// System.out.println(command+" -i "+transactionID+" "+arguments); - XDebugCorePlugin.log(IStatus.INFO,command+" -i "+fTransactionID+" "+arguments); + + public synchronized int sendRequest(String command, String arguments) + throws DebugException { + + // System.out.println(command+" -i "+transactionID+" "+arguments); + XDebugCorePlugin.log(IStatus.INFO, command + " -i " + fTransactionID + + " " + arguments); synchronized (fDebugSocket) { try { fDebugWriter.write(command); fDebugWriter.write(" -i " + fTransactionID); - if (arguments!="") + if (arguments != "") fDebugWriter.write(" " + arguments); fDebugWriter.write(0); fDebugWriter.flush(); } catch (IOException e) { e.printStackTrace(); - } + } } return fTransactionID++; } - + public DebugResponse waitforTransID(int id) { - if (ResponseList.containsKey(new Integer(id))) - { -// return (DebugResponse)ResponseList.get(new Integer(id)); - return (DebugResponse)ResponseList.remove(new Integer(id)); - } - else + if (ResponseList.containsKey(new Integer(id))) { + // return (DebugResponse)ResponseList.get(new Integer(id)); + return (DebugResponse) ResponseList.remove(new Integer(id)); + } else return lastResponse.waitforTransactionID(id); } - + public DebugResponse getResponse(int id) { if (ResponseList.containsKey(new Integer(id))) - return (DebugResponse)ResponseList.get(new Integer(id)); + return (DebugResponse) ResponseList.get(new Integer(id)); else return waitforTransID(id); } - - } diff --git a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/IXDebugPreferenceConstants.java b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/IXDebugPreferenceConstants.java index 51486ae..0662af4 100644 --- a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/IXDebugPreferenceConstants.java +++ b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/IXDebugPreferenceConstants.java @@ -2,6 +2,8 @@ package net.sourceforge.phpeclipse.xdebug.core; public interface IXDebugPreferenceConstants { public static final String DEBUGPORT_PREFERENCE = "debugport"; + public static final int DEFAULT_DEBUGPORT = 9000; + public static final String PHP_INTERPRETER_PREFERENCE = "phpInterpreter"; } diff --git a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/PHPDebugUtils.java b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/PHPDebugUtils.java index 8b377a7..8bdba0b 100644 --- a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/PHPDebugUtils.java +++ b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/PHPDebugUtils.java @@ -7,51 +7,52 @@ import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; public class PHPDebugUtils { - public static String getAttributeValue (Node CurrentNode, String AttributeName) { + public static String getAttributeValue(Node CurrentNode, + String AttributeName) { String strValue = ""; if (CurrentNode.hasAttributes()) { NamedNodeMap listAttribute = CurrentNode.getAttributes(); Node attribute = listAttribute.getNamedItem(AttributeName); - if (attribute !=null) + if (attribute != null) strValue = attribute.getNodeValue(); } return strValue; } - + public static String escapeString(String string) { - StringBuffer escString=new StringBuffer(); - Pattern pattern = Pattern.compile("[a-zA-Z0-9\\._-]"); - Matcher matcher; - for (int i= 0; i2) - string.append(s[i].substring(2)); - + for (int i = 1; i < s.length; i++) { + int c = Integer.parseInt(s[i].substring(0, 2), 16); + string.append((char) c); + if (s[i].length() > 2) + string.append(s[i].substring(2)); + } return string.toString(); } - } diff --git a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/ResponseData.java b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/ResponseData.java index b01ebf4..58e4b9b 100644 --- a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/ResponseData.java +++ b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/ResponseData.java @@ -2,11 +2,12 @@ package net.sourceforge.phpeclipse.xdebug.core; public class ResponseData { - private int fTransactionID =-1; + private int fTransactionID = -1; - ResponseData(int transactionID){ - fTransactionID=transactionID; + ResponseData(int transactionID) { + fTransactionID = transactionID; } + public int getTransactionID() { return fTransactionID; } diff --git a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/XDebugCorePlugin.java b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/XDebugCorePlugin.java index 716b582..a7ffee0 100644 --- a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/XDebugCorePlugin.java +++ b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/core/XDebugCorePlugin.java @@ -1,9 +1,7 @@ package net.sourceforge.phpeclipse.xdebug.core; - import net.sourceforge.phpeclipse.xdebug.php.launching.IXDebugConstants; -import org.eclipse.ui.plugin.*; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IStatus; @@ -12,6 +10,7 @@ import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.IBreakpointManager; import org.eclipse.debug.core.model.IBreakpoint; import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; /** @@ -19,11 +18,11 @@ import org.osgi.framework.BundleContext; */ public class XDebugCorePlugin extends AbstractUIPlugin { - //The shared instance. + // The shared instance. private static XDebugCorePlugin plugin; + public static final String PLUGIN_ID = "net.sourceforge.phpeclipse.xdebug.core"; //$NON-NLS-1$ - /** * The constructor. */ @@ -52,29 +51,33 @@ public class XDebugCorePlugin extends AbstractUIPlugin { public static XDebugCorePlugin getDefault() { return plugin; } - + public static IBreakpoint[] getBreakpoints() { - return getBreakpointManager().getBreakpoints(IXDebugConstants.ID_PHP_DEBUG_MODEL); + return getBreakpointManager().getBreakpoints( + IXDebugConstants.ID_PHP_DEBUG_MODEL); } - + public static IBreakpointManager getBreakpointManager() { return DebugPlugin.getDefault().getBreakpointManager(); } /** - * Returns an image descriptor for the image file at the given - * plug-in relative path. - * - * @param path the path + * Returns an image descriptor for the image file at the given plug-in + * relative path. + * + * @param path + * the path * @return the image descriptor */ public static ImageDescriptor getImageDescriptor(String path) { - return AbstractUIPlugin.imageDescriptorFromPlugin("net.sourceforge.phpeclipse.xdebug.core", path); + return AbstractUIPlugin.imageDescriptorFromPlugin( + "net.sourceforge.phpeclipse.xdebug.core", path); } - + public static void log(int severity, String message) { - Status status = new Status(severity, PLUGIN_ID, IStatus.OK, message, null) ; - XDebugCorePlugin.log(status) ; + Status status = new Status(severity, PLUGIN_ID, IStatus.OK, message, + null); + XDebugCorePlugin.log(status); } public static void log(IStatus status) { @@ -82,15 +85,15 @@ public class XDebugCorePlugin extends AbstractUIPlugin { } public static void log(Throwable e) { - log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.ERROR, "PHPLaunchingPlugin.internalErrorOccurred", e)); //$NON-NLS-1$ + log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.ERROR, + "PHPLaunchingPlugin.internalErrorOccurred", e)); //$NON-NLS-1$ } - - /** - * Returns the workspace instance. - */ - public static IWorkspace getWorkspace() { - return ResourcesPlugin.getWorkspace(); - } - - + + /** + * Returns the workspace instance. + */ + public static IWorkspace getWorkspace() { + return ResourcesPlugin.getWorkspace(); + } + } diff --git a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/launching/IXDebugConstants.java b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/launching/IXDebugConstants.java index 81007f3..9dc1bac 100644 --- a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/launching/IXDebugConstants.java +++ b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/launching/IXDebugConstants.java @@ -4,34 +4,37 @@ package net.sourceforge.phpeclipse.xdebug.php.launching; * Constants for the PDA debugger. */ public interface IXDebugConstants { - + /** - * Unique identifier for the PHP debug model (value + * Unique identifier for the PHP debug model (value * et.sourceforge.phpeclipse.debug.). */ public static final String ID_PHP_DEBUG_MODEL = "net.sourceforge.phpeclipse.xdebug.php"; - + /** - * Launch configuration key. Value is a PHPProject name - * program. The path is a string representing a full path - * to a perl program in the workspace. + * Launch configuration key. Value is a PHPProject name program. The path is + * a string representing a full path to a perl program in the workspace. */ - public static final String ATTR_PHP_PROJECT = ID_PHP_DEBUG_MODEL + ".ATTR_PDA_PROFECT"; + public static final String ATTR_PHP_PROJECT = ID_PHP_DEBUG_MODEL + + ".ATTR_PDA_PROFECT"; + /** - * Launch configuration key. Value is a php program. - * The path is a string representing a relative path - * to a php program in the project. + * Launch configuration key. Value is a php program. The path is a string + * representing a relative path to a php program in the project. */ - public static final String ATTR_PHP_FILE = ID_PHP_DEBUG_MODEL + ".ATTR_PDA_FILE"; + public static final String ATTR_PHP_FILE = ID_PHP_DEBUG_MODEL + + ".ATTR_PDA_FILE"; - public static final String ATTR_PHP_DEFAULT_INTERPRETER = ID_PHP_DEBUG_MODEL + ".ATTR_PHP_DEFAULT_INTERPRETER"; + public static final String ATTR_PHP_DEFAULT_INTERPRETER = ID_PHP_DEBUG_MODEL + + ".ATTR_PHP_DEFAULT_INTERPRETER"; - public static final String ATTR_PHP_INTERPRETER = ID_PHP_DEBUG_MODEL + ".ATTR_PHP_INTERPRETER"; + public static final String ATTR_PHP_INTERPRETER = ID_PHP_DEBUG_MODEL + + ".ATTR_PHP_INTERPRETER"; - public static final String ATTR_PHP_DEFAULT_DEBUGPORT = ID_PHP_DEBUG_MODEL + ".ATTR_PHP_DEFAULT_DEBUGPORT"; - - public static final String ATTR_PHP_DEBUGPORT = ID_PHP_DEBUG_MODEL + ".ATTR_PHP_DEBUGPORT"; + public static final String ATTR_PHP_DEFAULT_DEBUGPORT = ID_PHP_DEBUG_MODEL + + ".ATTR_PHP_DEFAULT_DEBUGPORT"; + public static final String ATTR_PHP_DEBUGPORT = ID_PHP_DEBUG_MODEL + + ".ATTR_PHP_DEBUGPORT"; } - diff --git a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/launching/PHPLaunchConfigurationDelegate.java b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/launching/PHPLaunchConfigurationDelegate.java index 6117961..5880ca0 100644 --- a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/launching/PHPLaunchConfigurationDelegate.java +++ b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/launching/PHPLaunchConfigurationDelegate.java @@ -38,93 +38,118 @@ import org.eclipse.debug.core.model.ILaunchConfigurationDelegate; import org.eclipse.debug.core.model.IProcess; import org.eclipse.debug.core.model.LaunchConfigurationDelegate; - public class PHPLaunchConfigurationDelegate extends LaunchConfigurationDelegate { - + /** - * @see ILaunchConfigurationDelegate#launch(ILaunchConfiguration, String, ILaunch, IProgressMonitor) + * @see ILaunchConfigurationDelegate#launch(ILaunchConfiguration, String, + * ILaunch, IProgressMonitor) */ - public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { + public void launch(ILaunchConfiguration configuration, String mode, + ILaunch launch, IProgressMonitor monitor) throws CoreException { List commandList = new ArrayList(); - - String phpInterpreter = configuration.getAttribute(IXDebugConstants.ATTR_PHP_INTERPRETER, (String)null); - boolean useDefaultInterpreter= configuration.getAttribute(IXDebugConstants.ATTR_PHP_DEFAULT_INTERPRETER, true); - if (useDefaultInterpreter) - phpInterpreter=XDebugCorePlugin.getDefault().getPreferenceStore().getString(IXDebugPreferenceConstants.PHP_INTERPRETER_PREFERENCE); + String phpInterpreter = configuration.getAttribute( + IXDebugConstants.ATTR_PHP_INTERPRETER, (String) null); + boolean useDefaultInterpreter = configuration.getAttribute( + IXDebugConstants.ATTR_PHP_DEFAULT_INTERPRETER, true); + + if (useDefaultInterpreter) + phpInterpreter = XDebugCorePlugin + .getDefault() + .getPreferenceStore() + .getString( + IXDebugPreferenceConstants.PHP_INTERPRETER_PREFERENCE); File exe = new File(phpInterpreter); // Just to get sure that the interpreter exists if (!exe.exists()) { - abort(MessageFormat.format("Specified PHP executable {0} does not exist. Check value of PHP-Interpreter.", new String[]{phpInterpreter}), null); + abort( + MessageFormat + .format( + "Specified PHP executable {0} does not exist. Check value of PHP-Interpreter.", + new String[] { phpInterpreter }), null); } commandList.add(phpInterpreter); - + // Project name - String projectName = configuration.getAttribute(IXDebugConstants.ATTR_PHP_PROJECT, (String)null); - IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName); -// Just to get sure that the project exists + String projectName = configuration.getAttribute( + IXDebugConstants.ATTR_PHP_PROJECT, (String) null); + IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject( + projectName); + // Just to get sure that the project exists if (project == null) { abort("Project does not exist.", null); } - String fileName = configuration.getAttribute(IXDebugConstants.ATTR_PHP_FILE, (String)null); + String fileName = configuration.getAttribute( + IXDebugConstants.ATTR_PHP_FILE, (String) null); IFile file = project.getFile(fileName); // Just to get sure that the script exists if (!file.exists()) { - abort(MessageFormat.format("PHP-Script {0} does not exist.", new String[] {file.getFullPath().toString()}), null); + abort(MessageFormat.format("PHP-Script {0} does not exist.", + new String[] { file.getFullPath().toString() }), null); } - + commandList.add(file.getLocation().toOSString()); // Get de Debugport form the Launchconfiguration or from the preferences - int debugPort = configuration.getAttribute(IXDebugConstants.ATTR_PHP_DEBUGPORT,-1); - boolean useDefaultPort= configuration.getAttribute(IXDebugConstants.ATTR_PHP_DEFAULT_DEBUGPORT, true); + int debugPort = configuration.getAttribute( + IXDebugConstants.ATTR_PHP_DEBUGPORT, -1); + boolean useDefaultPort = configuration.getAttribute( + IXDebugConstants.ATTR_PHP_DEFAULT_DEBUGPORT, true); if (useDefaultPort) - debugPort=XDebugCorePlugin.getDefault().getPreferenceStore().getInt(IXDebugPreferenceConstants.DEBUGPORT_PREFERENCE); - if (debugPort<1024) - debugPort=IXDebugPreferenceConstants.DEFAULT_DEBUGPORT; + debugPort = XDebugCorePlugin.getDefault().getPreferenceStore() + .getInt(IXDebugPreferenceConstants.DEBUGPORT_PREFERENCE); + if (debugPort < 1024) + debugPort = IXDebugPreferenceConstants.DEFAULT_DEBUGPORT; - String[] envp=DebugPlugin.getDefault().getLaunchManager().getEnvironment(configuration); + String[] envp = DebugPlugin.getDefault().getLaunchManager() + .getEnvironment(configuration); // appends the environment to the native environment - if (envp==null) { - Map stringVars = DebugPlugin.getDefault().getLaunchManager().getNativeEnvironment(); - int idx=0; - envp= new String[stringVars.size()]; + if (envp == null) { + Map stringVars = DebugPlugin.getDefault().getLaunchManager() + .getNativeEnvironment(); + int idx = 0; + envp = new String[stringVars.size()]; for (Iterator i = stringVars.keySet().iterator(); i.hasNext();) { String key = (String) i.next(); String value = (String) stringVars.get(key); - envp[idx++]=key+"="+value; + envp[idx++] = key + "=" + value; } } if (mode.equals(ILaunchManager.DEBUG_MODE)) { - String[] env = new String[envp.length+1]; - for(int i=0;i0); + return (fVariables.length > 0); } - + public boolean isArray() { return ((fType & VALUETYPE_ARRAY) > 0); } - + public abstract void setType(String typeName); + public abstract void renderValueString(String data); public abstract boolean verifyValue(String expression); - + public boolean setValue(String expression) { if (!verifyValue(expression)) return false; - if(fTarget.setVarValue(fVariable.getFullName(),expression)) { + if (fTarget.setVarValue(fVariable.getFullName(), expression)) { renderValueString(expression); return true; } diff --git a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugArrayValue.java b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugArrayValue.java index dd01675..e7075f8 100644 --- a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugArrayValue.java +++ b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugArrayValue.java @@ -10,13 +10,13 @@ public class XDebugArrayValue extends XDebugAbstractValue { } public void setType(String typeName) { - fType=XDebugAbstractValue.VALUETYPE_ARRAY; - fTypeName=typeName; + fType = XDebugAbstractValue.VALUETYPE_ARRAY; + fTypeName = typeName; } public void renderValueString(String data) { - fValueString= data +" element(s)"; + fValueString = data + " element(s)"; } public boolean verifyValue(String expression) { diff --git a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugBooleanValue.java b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugBooleanValue.java index 6216046..678a955 100644 --- a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugBooleanValue.java +++ b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugBooleanValue.java @@ -14,40 +14,41 @@ public class XDebugBooleanValue extends XDebugAbstractValue { } public void setType(String typeName) { - fType=XDebugAbstractValue.VALUETYPE_BOOLEAN; - fTypeName=typeName; } + fType = XDebugAbstractValue.VALUETYPE_BOOLEAN; + fTypeName = typeName; + } public void renderValueString(String data) { - int value=-1; + int value = -1; try { - value=Integer.parseInt(data); + value = Integer.parseInt(data); } catch (NumberFormatException e) { - data=data.toLowerCase(); + data = data.toLowerCase(); if (data.equals("true") || data.equals("false")) - fValueString=data; + fValueString = data; else - fValueString="not defined"; + fValueString = "not defined"; } - if (value==0) - fValueString="false"; - else if (value==1) - fValueString="true"; + if (value == 0) + fValueString = "false"; + else if (value == 1) + fValueString = "true"; else - fValueString="not defined"; + fValueString = "not defined"; } public boolean verifyValue(String expression) { - int value=-1; + int value = -1; try { - value=Integer.parseInt(expression); + value = Integer.parseInt(expression); } catch (NumberFormatException e) { - expression=expression.toLowerCase(); + expression = expression.toLowerCase(); if (expression.equals("true") || expression.equals("false")) return true; else return false; } - if ((value>=0)&& (value <=1)) + if ((value >= 0) && (value <= 1)) return true; return false; } diff --git a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugElement.java b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugElement.java index fcfd8af..7242bd4 100644 --- a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugElement.java +++ b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugElement.java @@ -3,7 +3,6 @@ */ package net.sourceforge.phpeclipse.xdebug.php.model; - import net.sourceforge.phpeclipse.xdebug.core.ResponseData; import net.sourceforge.phpeclipse.xdebug.php.launching.IXDebugConstants; @@ -17,42 +16,53 @@ import org.eclipse.debug.core.model.IDebugTarget; /** * @author Christian - * + * */ public class XDebugElement extends PlatformObject implements IDebugElement { - - // containing target + + // containing target protected XDebugTarget fTarget; - + /** - * Constructs a new debug element contained in the given - * debug target. + * Constructs a new debug element contained in the given debug target. * - * @param target debug target (PDA VM) + * @param target + * debug target (PDA VM) */ public XDebugElement(XDebugTarget target) { fTarget = target; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IDebugElement#getModelIdentifier() */ public String getModelIdentifier() { return IXDebugConstants.ID_PHP_DEBUG_MODEL; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IDebugElement#getDebugTarget() */ public IDebugTarget getDebugTarget() { return fTarget; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IDebugElement#getLaunch() */ public ILaunch getLaunch() { return getDebugTarget().getLaunch(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class) */ public Object getAdapter(Class adapter) { @@ -61,59 +71,64 @@ public class XDebugElement extends PlatformObject implements IDebugElement { } return super.getAdapter(adapter); } - + protected void abort(String message, Throwable e) throws DebugException { -/* Axel auskommentiert - throw new DebugException(new Status(IStatus.ERROR, DebugExamplesPlugin.getDefault().getDescriptor().getUniqueIdentifier(), - DebugPlugin.INTERNAL_ERROR, message, e)); -*/ - } - + /* + * Axel auskommentiert throw new DebugException(new + * Status(IStatus.ERROR, + * DebugExamplesPlugin.getDefault().getDescriptor().getUniqueIdentifier(), + * DebugPlugin.INTERNAL_ERROR, message, e)); + */ + } + /** * Fires a debug event * - * @param event the event to be fired + * @param event + * the event to be fired */ protected void fireEvent(DebugEvent event) { - DebugPlugin.getDefault().fireDebugEventSet(new DebugEvent[] {event}); + DebugPlugin.getDefault().fireDebugEventSet(new DebugEvent[] { event }); } - + /** * Fires a CREATE event for this element. */ public void fireCreationEvent() { fireEvent(new DebugEvent(this, DebugEvent.CREATE)); - } - + } + /** - * Fires a RESUME event for this element with - * the given detail. + * Fires a RESUME event for this element with the given + * detail. * - * @param detail event detail code + * @param detail + * event detail code */ public void fireResumeEvent(int detail) { fireEvent(new DebugEvent(this, DebugEvent.RESUME, detail)); } /** - * Fires a SUSPEND event for this element with - * the given detail. + * Fires a SUSPEND event for this element with the given + * detail. * - * @param detail event detail code + * @param detail + * event detail code */ public void fireSuspendEvent(int detail) { fireEvent(new DebugEvent(this, DebugEvent.SUSPEND, detail)); } - + /** * Fires a TERMINATE event for this element. */ protected void fireTerminateEvent() { fireEvent(new DebugEvent(this, DebugEvent.TERMINATE)); } - + public void fireDebugResponseEvent(ResponseData data) { - DebugEvent de=new DebugEvent(this, DebugEvent.MODEL_SPECIFIC); + DebugEvent de = new DebugEvent(this, DebugEvent.MODEL_SPECIFIC); de.setData(data); fireEvent(de); } diff --git a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugFloatValue.java b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugFloatValue.java index 5d2d4ee..03a6439 100644 --- a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugFloatValue.java +++ b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugFloatValue.java @@ -4,23 +4,23 @@ import org.w3c.dom.Node; public class XDebugFloatValue extends XDebugAbstractValue { - public XDebugFloatValue(XDebugVariable variable, Node varNode,String TypeName) { - super(variable, varNode,TypeName); - + public XDebugFloatValue(XDebugVariable variable, Node varNode, + String TypeName) { + super(variable, varNode, TypeName); + } public boolean supportsValueModification() { return true; } - public void setType(String typeName) { - fType=XDebugAbstractValue.VALUETYPE_FLOAT; - fTypeName=typeName; + fType = XDebugAbstractValue.VALUETYPE_FLOAT; + fTypeName = typeName; } public void renderValueString(String data) { - fValueString=data; + fValueString = data; } public boolean verifyValue(String expression) { diff --git a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugIntValue.java b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugIntValue.java index b7e0418..9002c3e 100644 --- a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugIntValue.java +++ b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugIntValue.java @@ -4,25 +4,24 @@ import org.w3c.dom.Node; public class XDebugIntValue extends XDebugAbstractValue { - public XDebugIntValue(XDebugVariable variable, Node varNode,String TypeName) { - super(variable, varNode,TypeName); - + public XDebugIntValue(XDebugVariable variable, Node varNode, String TypeName) { + super(variable, varNode, TypeName); + } - + public void setType(String typeName) { - fType=XDebugAbstractValue.VALUETYPE_INT; - fTypeName=typeName; + fType = XDebugAbstractValue.VALUETYPE_INT; + fTypeName = typeName; } - + public boolean supportsValueModification() { return true; } - + public void renderValueString(String dataString) { - fValueString=dataString; + fValueString = dataString; } - public boolean verifyValue(String expression) { try { Integer.parseInt(expression); @@ -31,7 +30,7 @@ public class XDebugIntValue extends XDebugAbstractValue { } return true; } - + public String toString() { return fValueString; } diff --git a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugLineBreakpoint.java b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugLineBreakpoint.java index a626e8c..bdfe73d 100644 --- a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugLineBreakpoint.java +++ b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugLineBreakpoint.java @@ -1,4 +1,3 @@ - /* * Created on 25.11.2004 * @@ -7,7 +6,6 @@ */ package net.sourceforge.phpeclipse.xdebug.php.model; - import java.util.HashMap; import java.util.Map; @@ -22,85 +20,96 @@ import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.model.IBreakpoint; import org.eclipse.debug.core.model.LineBreakpoint; - /** * @author Axel - * - * TODO To change the template for this generated type comment go to - * Window - Preferences - Java - Code Style - Code Templates + * + * TODO To change the template for this generated type comment go to Window - + * Preferences - Java - Code Style - Code Templates */ -public class XDebugLineBreakpoint extends LineBreakpoint { - +public class XDebugLineBreakpoint extends LineBreakpoint { + /** - * Default constructor is required for the breakpoint manager - * to re-create persisted breakpoints. After instantiating a breakpoint, - * the setMarker(...) method is called to restore - * this breakpoint's attributes. + * Default constructor is required for the breakpoint manager to re-create + * persisted breakpoints. After instantiating a breakpoint, the + * setMarker(...) method is called to restore this + * breakpoint's attributes. */ private static final String XDEBUG_LINE_BREAKPOINT = "net.sourceforge.phpeclipse.xdebug.core.XDebugLineBreakpoint"; //$NON-NLS-1$ /** - * Breakpoint attribute storing the fully qualified name of the type - * this breakpoint is located in. - * (value "net.sourceforge.phpeclipse.debug.typeName"). This attribute is a String. + * Breakpoint attribute storing the fully qualified name of the type this + * breakpoint is located in. (value + * "net.sourceforge.phpeclipse.debug.typeName"). This + * attribute is a String. */ protected static final String TYPE_NAME = "net.sourceforge.phpeclipse.debug.typeName"; //$NON-NLS-1$ -// public PHPLineBreakpoint() { -// } -// -// public PHPLineBreakpoint(IResource resource, int lineNumber, int charStart, int charEnd, int hitCount, boolean add, Map attributes) throws DebugException { -// this(resource, lineNumber, charStart, charEnd, hitCount, add, attributes, PHP_LINE_BREAKPOINT); -// } -// -// public PHPLineBreakpoint(IResource resource, int lineNumber, int hitCount, boolean add, Map attributes) throws DebugException { -// this(resource, lineNumber, -1, -1, hitCount, add, attributes, PHP_LINE_BREAKPOINT); -// } - - - public static final String BREAKPOINT_ID ="XDebugLineBreakpointID"; - + // public PHPLineBreakpoint() { + // } + // + // public PHPLineBreakpoint(IResource resource, int lineNumber, int + // charStart, int charEnd, int hitCount, boolean add, Map attributes) throws + // DebugException { + // this(resource, lineNumber, charStart, charEnd, hitCount, add, attributes, + // PHP_LINE_BREAKPOINT); + // } + // + // public PHPLineBreakpoint(IResource resource, int lineNumber, int + // hitCount, boolean add, Map attributes) throws DebugException { + // this(resource, lineNumber, -1, -1, hitCount, add, attributes, + // PHP_LINE_BREAKPOINT); + // } + + public static final String BREAKPOINT_ID = "XDebugLineBreakpointID"; + public XDebugLineBreakpoint() { } - + /** - * Constructs a line breakpoint on the given resource at the given - * line number. The line number is 1-based (i.e. the first line of a - * file is line number 1). + * Constructs a line breakpoint on the given resource at the given line + * number. The line number is 1-based (i.e. the first line of a file is line + * number 1). * - * @param resource file on which to set the breakpoint - * @param lineNumber 1-based line number of the breakpoint - * @throws CoreException if unable to create the breakpoint + * @param resource + * file on which to set the breakpoint + * @param lineNumber + * 1-based line number of the breakpoint + * @throws CoreException + * if unable to create the breakpoint */ - public XDebugLineBreakpoint(final IResource resource, final int lineNumber) throws CoreException { -// IMarker marker = resource.createMarker("net.sourceforge.phpeclipse.xdebug.core.XDebugLineBreakpoint"); -// setMarker(marker); -// setEnabled(true); -// XDebugCorePlugin.log(IStatus.INFO,"Markertype: "+ marker.getType()); -// ensureMarker().setAttribute(IMarker.LINE_NUMBER, lineNumber); -// ensureMarker().setAttribute(IBreakpoint.ID, IXDebugConstants.ID_PHP_DEBUG_MODEL); -// ensureMarker().setAttribute(BREAKPOINT_ID,-1); - IWorkspaceRunnable wr= new IWorkspaceRunnable() { + public XDebugLineBreakpoint(final IResource resource, final int lineNumber) + throws CoreException { + // IMarker marker = + // resource.createMarker("net.sourceforge.phpeclipse.xdebug.core.XDebugLineBreakpoint"); + // setMarker(marker); + // setEnabled(true); + // XDebugCorePlugin.log(IStatus.INFO,"Markertype: "+ marker.getType()); + // ensureMarker().setAttribute(IMarker.LINE_NUMBER, lineNumber); + // ensureMarker().setAttribute(IBreakpoint.ID, + // IXDebugConstants.ID_PHP_DEBUG_MODEL); + // ensureMarker().setAttribute(BREAKPOINT_ID,-1); + IWorkspaceRunnable wr = new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { - + // create the marker setMarker(resource.createMarker(XDEBUG_LINE_BREAKPOINT)); // add attributes Map attributes = new HashMap(10); - addLineBreakpointAttributes(attributes, getModelIdentifier(), true, lineNumber, -1, -1); + addLineBreakpointAttributes(attributes, getModelIdentifier(), + true, lineNumber, -1, -1); // set attributes ensureMarker().setAttributes(attributes); - + // add to breakpoint manager if requested - register(true); + register(true); } }; run(getMarkerRule(resource), wr); } - + protected void register(boolean register) throws CoreException { if (register) { DebugPlugin.getDefault().getBreakpointManager().addBreakpoint(this); @@ -108,34 +117,35 @@ public class XDebugLineBreakpoint extends LineBreakpoint { setRegistered(false); } } - - public void addLineBreakpointAttributes(Map attributes, String modelIdentifier, boolean enabled, int lineNumber, int charStart, int charEnd) { + + public void addLineBreakpointAttributes(Map attributes, + String modelIdentifier, boolean enabled, int lineNumber, + int charStart, int charEnd) { attributes.put(IBreakpoint.ID, modelIdentifier); attributes.put(IBreakpoint.ENABLED, new Boolean(enabled)); attributes.put(IMarker.LINE_NUMBER, new Integer(lineNumber)); - if (charStart!=-1) - { + if (charStart != -1) { attributes.put(IMarker.CHAR_START, new Integer(charStart)); attributes.put(IMarker.CHAR_END, new Integer(charEnd)); } attributes.put(TYPE_NAME, "typeName"); - attributes.put(BREAKPOINT_ID,new Integer(-1)); - } + attributes.put(BREAKPOINT_ID, new Integer(-1)); + } - - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IBreakpoint#getModelIdentifier() */ public String getModelIdentifier() { return IXDebugConstants.ID_PHP_DEBUG_MODEL; } - - public void setID(int id) throws CoreException - { - ensureMarker().setAttribute(BREAKPOINT_ID,id); + + public void setID(int id) throws CoreException { + ensureMarker().setAttribute(BREAKPOINT_ID, id); } - public int getID() throws CoreException - { - return ensureMarker().getAttribute(BREAKPOINT_ID,-1); + + public int getID() throws CoreException { + return ensureMarker().getAttribute(BREAKPOINT_ID, -1); } } diff --git a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugObjectValue.java b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugObjectValue.java index 370e44d..2f3c66d 100644 --- a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugObjectValue.java +++ b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugObjectValue.java @@ -10,18 +10,18 @@ public class XDebugObjectValue extends XDebugAbstractValue { } public void setType(String typeName) { - fType=XDebugAbstractValue.VALUETYPE_OBJECT; - fTypeName=typeName; + fType = XDebugAbstractValue.VALUETYPE_OBJECT; + fTypeName = typeName; } public void renderValueString(String data) { - fValueString= data; + fValueString = data; } - + public String toString() { - return "class "+fValueString; + return "class " + fValueString; } public boolean verifyValue(String expression) { diff --git a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugStackFrame.java b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugStackFrame.java index ece6842..575520d 100644 --- a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugStackFrame.java +++ b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugStackFrame.java @@ -6,9 +6,6 @@ */ package net.sourceforge.phpeclipse.xdebug.php.model; -import java.net.URI; -import java.net.URISyntaxException; - import net.sourceforge.phpeclipse.xdebug.core.PHPDebugUtils; import net.sourceforge.phpeclipse.xdebug.core.DebugConnection.DebugResponse; @@ -23,29 +20,37 @@ import org.w3c.dom.NodeList; /** * @author Axel - * - * TODO To change the template for this generated type comment go to - * Window - Preferences - Java - Code Style - Code Templates + * + * TODO To change the template for this generated type comment go to Window - + * Preferences - Java - Code Style - Code Templates */ -public class XDebugStackFrame extends XDebugElement implements IStackFrame { - +public class XDebugStackFrame extends XDebugElement implements IStackFrame { + private XDebugThread fThread; -// private String fName; + + // private String fName; private int fLineNo; + private String fFileName; + private int fId; + private IVariable[] fVariables; + private String fLevel; + private String fType; + private String fWhere; - + /** - * Constructs a stack frame in the given thread with the given - * frame data. + * Constructs a stack frame in the given thread with the given frame data. * * @param thread - * @param data frame data - * @param id stack frame id (0 is the bottom of the stack) + * @param data + * frame data + * @param id + * stack frame id (0 is the bottom of the stack) */ public XDebugStackFrame(XDebugThread thread, Node stackNode, int id) { super((XDebugTarget) thread.getDebugTarget()); @@ -53,33 +58,36 @@ public class XDebugStackFrame extends XDebugElement implements IStackFrame { fThread = thread; init(stackNode); } - + /** * Initializes this frame based on its data * * @param data */ private void init(Node stackNode) { - - fLevel=PHPDebugUtils.getAttributeValue(stackNode,"level"); - fType=PHPDebugUtils.getAttributeValue(stackNode,"type"); - String fileName=PHPDebugUtils.unescapeString(PHPDebugUtils.getAttributeValue(stackNode,"filename")); - String lineNo=PHPDebugUtils.getAttributeValue(stackNode,"lineno"); - - if (lineNo!="") - fLineNo= Integer.parseInt(lineNo); - - fWhere=PHPDebugUtils.getAttributeValue(stackNode,"where"); - + + fLevel = PHPDebugUtils.getAttributeValue(stackNode, "level"); + fType = PHPDebugUtils.getAttributeValue(stackNode, "type"); + String fileName = PHPDebugUtils.unescapeString(PHPDebugUtils + .getAttributeValue(stackNode, "filename")); + String lineNo = PHPDebugUtils.getAttributeValue(stackNode, "lineno"); + + if (lineNo != "") + fLineNo = Integer.parseInt(lineNo); + + fWhere = PHPDebugUtils.getAttributeValue(stackNode, "where"); + fFileName = (new Path(fileName)).lastSegment(); - int id=-1; + int id = -1; try { - id=((XDebugTarget)getDebugTarget()).sendRequest("context_get","-d "+fLevel); + id = ((XDebugTarget) getDebugTarget()).sendRequest("context_get", + "-d " + fLevel); } catch (DebugException e) { // TODO Auto-generated catch block e.printStackTrace(); } - DebugResponse response=((XDebugTarget)getDebugTarget()).getResponse(id); + DebugResponse response = ((XDebugTarget) getDebugTarget()) + .getResponse(id); Node responseNode = response.getParentNode(); NodeList property = responseNode.getChildNodes(); fVariables = new IVariable[property.getLength()]; @@ -88,190 +96,265 @@ public class XDebugStackFrame extends XDebugElement implements IStackFrame { fVariables[i] = new XDebugVariable(this, propertyNode); } -// int numVars = strings.length - 3; -// fVariables = new IVariable[numVars]; -// for (int i = 0; i < numVars; i++) { -// fVariables[i] = new XDebugVariable(this, strings[i + 3]); -// } + // int numVars = strings.length - 3; + // fVariables = new IVariable[numVars]; + // for (int i = 0; i < numVars; i++) { + // fVariables[i] = new XDebugVariable(this, strings[i + 3]); + // } } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IStackFrame#getThread() */ public IThread getThread() { return fThread; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IStackFrame#getVariables() */ public IVariable[] getVariables() throws DebugException { return fVariables; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IStackFrame#hasVariables() */ public boolean hasVariables() throws DebugException { return fVariables.length > 0; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IStackFrame#getLineNumber() */ public int getLineNumber() throws DebugException { return fLineNo; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IStackFrame#getCharStart() */ public int getCharStart() throws DebugException { return -1; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IStackFrame#getCharEnd() */ public int getCharEnd() throws DebugException { return -1; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IStackFrame#getName() */ public String getName() throws DebugException { - return fFileName+"::"+fWhere+ " : lineno "+ fLineNo; + return fFileName + "::" + fWhere + " : lineno " + fLineNo; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IStackFrame#getRegisterGroups() */ public IRegisterGroup[] getRegisterGroups() throws DebugException { return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IStackFrame#hasRegisterGroups() */ public boolean hasRegisterGroups() throws DebugException { return false; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IStep#canStepInto() */ public boolean canStepInto() { return getThread().canStepInto(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IStep#canStepOver() */ public boolean canStepOver() { return getThread().canStepOver(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IStep#canStepReturn() */ public boolean canStepReturn() { return getThread().canStepReturn(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IStep#isStepping() */ public boolean isStepping() { return getThread().isStepping(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IStep#stepInto() */ public void stepInto() throws DebugException { getThread().stepInto(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IStep#stepOver() */ public void stepOver() throws DebugException { getThread().stepOver(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IStep#stepReturn() */ public void stepReturn() throws DebugException { getThread().stepReturn(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.ISuspendResume#canResume() */ public boolean canResume() { return getThread().canResume(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.ISuspendResume#canSuspend() */ public boolean canSuspend() { return getThread().canSuspend(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.ISuspendResume#isSuspended() */ public boolean isSuspended() { return getThread().isSuspended(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.ISuspendResume#resume() */ public void resume() throws DebugException { getThread().resume(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.ISuspendResume#suspend() */ public void suspend() throws DebugException { getThread().suspend(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.ITerminate#canTerminate() */ public boolean canTerminate() { return getThread().canTerminate(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.ITerminate#isTerminated() */ public boolean isTerminated() { return getThread().isTerminated(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.ITerminate#terminate() */ public void terminate() throws DebugException { getThread().terminate(); } - + /** - * Returns the name of the source file this stack frame is associated - * with. + * Returns the name of the source file this stack frame is associated with. * - * @return the name of the source file this stack frame is associated - * with + * @return the name of the source file this stack frame is associated with */ public String getSourceName() { return fFileName; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (obj instanceof XDebugStackFrame) { - XDebugStackFrame sf = (XDebugStackFrame)obj; + XDebugStackFrame sf = (XDebugStackFrame) obj; try { - return sf.getSourceName().equals(getSourceName()) && - sf.getLineNumber() == getLineNumber() && - sf.fId == fId; + return sf.getSourceName().equals(getSourceName()) + && sf.getLineNumber() == getLineNumber() + && sf.fId == fId; } catch (DebugException e) { } } return false; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see java.lang.Object#hashCode() */ public int hashCode() { return getSourceName().hashCode() + fId; } - + /** * Returns this stack frame's unique identifier within its thread * diff --git a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugStringValue.java b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugStringValue.java index 388c412..b2d0231 100644 --- a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugStringValue.java +++ b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugStringValue.java @@ -5,28 +5,28 @@ import org.w3c.dom.Node; public class XDebugStringValue extends XDebugAbstractValue { private String fDataString; + public XDebugStringValue(XDebugVariable variable, Node varNode, String typeName) { super(variable, varNode, typeName); - fDataString=null; + fDataString = null; } public void setType(String typeName) { - fType=XDebugAbstractValue.VALUETYPE_STRING; - fTypeName=typeName; + fType = XDebugAbstractValue.VALUETYPE_STRING; + fTypeName = typeName; } public void renderValueString(String data) { - fDataString=data; - fValueString="\""+data+"\""; + fDataString = data; + fValueString = "\"" + data + "\""; } public boolean supportsValueModification() { return true; } - public String toString() { return fDataString; } diff --git a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugTarget.java b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugTarget.java index b8d3f86..04099c4 100644 --- a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugTarget.java +++ b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugTarget.java @@ -31,193 +31,256 @@ import org.w3c.dom.NodeList; /** * @author Christian - * + * */ -public class XDebugTarget extends XDebugElement implements IDebugTarget, IDebugEventSetListener{ +public class XDebugTarget extends XDebugElement implements IDebugTarget, + IDebugEventSetListener { // associated system process (VM) private IProcess fProcess; - + // containing launch object private ILaunch fLaunch; - + // debugPort private int fDebugPort; - + // program name -// private String fName; - - + // private String fName; + // suspend state private boolean fSuspended = true; - + // terminated state private boolean fTerminated = false; - + // threads private XDebugThread fThread; + private IThread[] fThreads; - + // event dispatch job -// private EventDispatchJob fEventDispatch; - + // private EventDispatchJob fEventDispatch; private DebugConnection fDebugConnection; -// private DebugResponse lastResponse; + // private DebugResponse lastResponse; - /** - * Constructs a new debug target in the given launch for the - * associated PDA VM process. + * Constructs a new debug target in the given launch for the associated PDA + * VM process. * - * @param launch containing launch - * @param debugPort port to read events from - * @exception CoreException if unable to connect to host - */ - public XDebugTarget(ILaunch launch, IProcess process, int debugPort) throws CoreException { + * @param launch + * containing launch + * @param debugPort + * port to read events from + * @exception CoreException + * if unable to connect to host + */ + public XDebugTarget(ILaunch launch, IProcess process, int debugPort) + throws CoreException { super(null); fLaunch = launch; fProcess = process; fTarget = this; - fDebugConnection= new DebugConnection(this,debugPort); + fDebugConnection = new DebugConnection(this, debugPort); fThread = new XDebugThread(this); - fThreads = new IThread[] {fThread}; - DebugPlugin.getDefault().getBreakpointManager().addBreakpointListener(this); + fThreads = new IThread[] { fThread }; + DebugPlugin.getDefault().getBreakpointManager().addBreakpointListener( + this); DebugPlugin.getDefault().addDebugEventListener(this); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IDebugTarget#getProcess() */ public IProcess getProcess() { return fProcess; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IDebugTarget#getThreads() */ public IThread[] getThreads() throws DebugException { return fThreads; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IDebugTarget#hasThreads() */ public boolean hasThreads() throws DebugException { - return (fThreads.length>0); + return (fThreads.length > 0); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IDebugTarget#getName() */ public String getName() throws DebugException { return "PHP XDebug Client at localhost:" + fDebugPort; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IDebugTarget#supportsBreakpoint(org.eclipse.debug.core.model.IBreakpoint) */ public boolean supportsBreakpoint(IBreakpoint breakpoint) { - if (breakpoint.getModelIdentifier().equals(IXDebugConstants.ID_PHP_DEBUG_MODEL)) { + if (breakpoint.getModelIdentifier().equals( + IXDebugConstants.ID_PHP_DEBUG_MODEL)) { return true; } return false; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IDebugElement#getDebugTarget() */ public IDebugTarget getDebugTarget() { return this; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IDebugElement#getLaunch() */ public ILaunch getLaunch() { return fLaunch; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.ITerminate#canTerminate() */ public boolean canTerminate() { return getProcess().canTerminate(); -// return false; + // return false; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.ITerminate#isTerminated() */ public boolean isTerminated() { -// return getProcess().isTerminated(); + // return getProcess().isTerminated(); return fTerminated; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.ITerminate#terminate() */ public void terminate() throws DebugException { - fDebugConnection.sendRequest ("stop"); + fDebugConnection.sendRequest("stop"); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.ISuspendResume#canResume() */ public boolean canResume() { return !isTerminated() && isSuspended(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.ISuspendResume#canSuspend() */ public boolean canSuspend() { return !isTerminated() && !isSuspended(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.ISuspendResume#isSuspended() */ public boolean isSuspended() { return fSuspended; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.ISuspendResume#resume() */ public void resume() throws DebugException { fDebugConnection.sendRequest("run"); } - + /** * Notification the target has resumed for the given reason * - * @param detail reason for the resume + * @param detail + * reason for the resume */ private void resumed(int detail) { fSuspended = false; fThread.fireResumeEvent(detail); } - + /** * Notification the target has suspended for the given reason * - * @param detail reason for the suspend + * @param detail + * reason for the suspend */ public void suspended(int detail) { fSuspended = true; fThread.fireSuspendEvent(detail); - } - - /* (non-Javadoc) + } + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.ISuspendResume#suspend() */ public void suspend() throws DebugException { } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.IBreakpointListener#breakpointAdded(org.eclipse.debug.core.model.IBreakpoint) */ public void breakpointAdded(IBreakpoint breakpoint) { - + if (supportsBreakpoint(breakpoint)) { try { if (breakpoint.isEnabled()) { IMarker marker = breakpoint.getMarker(); if (marker != null) { try { - String fileName = PHPDebugUtils.escapeString(marker.getResource().getLocation().toString()); - String arg="-t line -f file:///"+fileName+" -n "+((ILineBreakpoint)breakpoint).getLineNumber(); - int id =fDebugConnection.sendRequest("breakpoint_set",arg); - // set the marker Attribute to make later idetification possible -// TODO: make sure that attribute is set before response from debugger is beeing prosessed - marker.setAttribute(XDebugLineBreakpoint.BREAKPOINT_ID,id); - + String fileName = PHPDebugUtils.escapeString(marker + .getResource().getLocation().toString()); + String arg = "-t line -f file:///" + + fileName + + " -n " + + ((ILineBreakpoint) breakpoint) + .getLineNumber(); + int id = fDebugConnection.sendRequest( + "breakpoint_set", arg); + // set the marker Attribute to make later + // idetification possible + // TODO: make sure that attribute is set before + // response from debugger is beeing prosessed + marker.setAttribute( + XDebugLineBreakpoint.BREAKPOINT_ID, id); + } catch (CoreException e) { } } @@ -227,61 +290,87 @@ public class XDebugTarget extends XDebugElement implements IDebugTarget, IDebugE } } } - /* (non-Javadoc) - * @see org.eclipse.debug.core.IBreakpointListener#breakpointRemoved(org.eclipse.debug.core.model.IBreakpoint, org.eclipse.core.resources.IMarkerDelta) + + /* + * (non-Javadoc) + * + * @see org.eclipse.debug.core.IBreakpointListener#breakpointRemoved(org.eclipse.debug.core.model.IBreakpoint, + * org.eclipse.core.resources.IMarkerDelta) */ public void breakpointRemoved(IBreakpoint breakpoint, IMarkerDelta delta) { if (supportsBreakpoint(breakpoint)) { try { - int id =((XDebugLineBreakpoint)breakpoint).getID(); - if (id >0) - fDebugConnection.sendRequest("breakpoint_remove","-d "+id); + int id = ((XDebugLineBreakpoint) breakpoint).getID(); + if (id > 0) + fDebugConnection.sendRequest("breakpoint_remove", "-d " + + id); } catch (CoreException e) { } } } - /* (non-Javadoc) - * @see org.eclipse.debug.core.IBreakpointListener#breakpointChanged(org.eclipse.debug.core.model.IBreakpoint, org.eclipse.core.resources.IMarkerDelta) + + /* + * (non-Javadoc) + * + * @see org.eclipse.debug.core.IBreakpointListener#breakpointChanged(org.eclipse.debug.core.model.IBreakpoint, + * org.eclipse.core.resources.IMarkerDelta) */ public void breakpointChanged(IBreakpoint breakpoint, IMarkerDelta delta) { -// if (supportsBreakpoint(breakpoint)) { -// try { -// if (breakpoint.isEnabled()) { -// breakpointAdded(breakpoint); -// } else { -// breakpointRemoved(breakpoint, null); -// } -// } catch (CoreException e) { -// } -// } - } - /* (non-Javadoc) + // if (supportsBreakpoint(breakpoint)) { + // try { + // if (breakpoint.isEnabled()) { + // breakpointAdded(breakpoint); + // } else { + // breakpointRemoved(breakpoint, null); + // } + // } catch (CoreException e) { + // } + // } + } + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IDisconnect#canDisconnect() */ public boolean canDisconnect() { return false; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IDisconnect#disconnect() */ public void disconnect() throws DebugException { } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IDisconnect#isDisconnected() */ public boolean isDisconnected() { return false; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IMemoryBlockRetrieval#supportsStorageRetrieval() */ public boolean supportsStorageRetrieval() { return false; } - /* (non-Javadoc) - * @see org.eclipse.debug.core.model.IMemoryBlockRetrieval#getMemoryBlock(long, long) + + /* + * (non-Javadoc) + * + * @see org.eclipse.debug.core.model.IMemoryBlockRetrieval#getMemoryBlock(long, + * long) */ - public IMemoryBlock getMemoryBlock(long startAddress, long length) throws DebugException { + public IMemoryBlock getMemoryBlock(long startAddress, long length) + throws DebugException { return null; } @@ -297,11 +386,11 @@ public class XDebugTarget extends XDebugElement implements IDebugTarget, IDebugE installDeferredBreakpoints(); try { resume(); -// step(); + // step(); } catch (DebugException e) { } } - + /** * Install breakpoints that are already registered with the breakpoint * manager. @@ -312,7 +401,7 @@ public class XDebugTarget extends XDebugElement implements IDebugTarget, IDebugE breakpointAdded(breakpoints[i]); } } - + /** * Called when this debug target terminates. */ @@ -324,16 +413,17 @@ public class XDebugTarget extends XDebugElement implements IDebugTarget, IDebugE DebugPlugin.getDefault().removeDebugEventListener(this); fThread.removeEventListeners(); } - + /** * Returns the current stack frames in the target. * * @return the current stack frames in the target - * @throws DebugException if unable to perform the request + * @throws DebugException + * if unable to perform the request */ protected IStackFrame[] getStackFrames() throws DebugException { - int id=fDebugConnection.sendRequest("stack_get"); - DebugResponse lastResponse=fDebugConnection.waitforTransID(id); + int id = fDebugConnection.sendRequest("stack_get"); + DebugResponse lastResponse = fDebugConnection.waitforTransID(id); if (lastResponse.isError()) return new IStackFrame[0]; Node response = lastResponse.getParentNode(); @@ -345,33 +435,36 @@ public class XDebugTarget extends XDebugElement implements IDebugTarget, IDebugE } return theFrames; } - + /** * Single step the interpreter. * - * @throws DebugException if the request fails + * @throws DebugException + * if the request fails */ protected void step_over() throws DebugException { fThread.setStepping(true); resumed(DebugEvent.STEP_OVER); fDebugConnection.sendRequest("step_over"); } - + /** * Single step the interpreter. * - * @throws DebugException if the request fails + * @throws DebugException + * if the request fails */ protected void step_into() throws DebugException { fThread.setStepping(true); resumed(DebugEvent.STEP_INTO); fDebugConnection.sendRequest("step_into"); } - + /** * Single step the interpreter. * - * @throws DebugException if the request fails + * @throws DebugException + * if the request fails */ protected void step_out() throws DebugException { fThread.setStepping(true); @@ -379,73 +472,76 @@ public class XDebugTarget extends XDebugElement implements IDebugTarget, IDebugE fDebugConnection.sendRequest("step_out"); } - - /** * Returns the current value of the given variable. * * @param variable * @return variable value - * @throws DebugException if the request fails - */ - protected IValue getVariableValue(XDebugVariable variable) throws DebugException { -// synchronized (fDebugSocket) { -// fDebugConnection.sendRequest("var","" + variable.getStackFrame().getIdentifier() + " " + variable.getName()); -// try { -// String value = fDebugReader.readLine(); -// //return new XDebugValue(this, value); -// -// } catch (IOException e) { -// abort(MessageFormat.format("Unable to retrieve value for variable {0}", new String[]{variable.getName()}), e); -// } -// } + * @throws DebugException + * if the request fails + */ + protected IValue getVariableValue(XDebugVariable variable) + throws DebugException { + // synchronized (fDebugSocket) { + // fDebugConnection.sendRequest("var","" + + // variable.getStackFrame().getIdentifier() + " " + variable.getName()); + // try { + // String value = fDebugReader.readLine(); + // //return new XDebugValue(this, value); + // + // } catch (IOException e) { + // abort(MessageFormat.format("Unable to retrieve value for variable + // {0}", new String[]{variable.getName()}), e); + // } + // } return null; } - + /** * Returns the values on the data stack (top down) * * @return the values on the data stack (top down) */ public IValue[] getDataStack() throws DebugException { -// synchronized (fDebugSocket) { -// fDebugConnection.sendRequest ("data"); -// try { -// String valueString = fDebugReader.readLine(); -// if (valueString != null && valueString.length() > 0) { -// String[] values = valueString.split("\\|"); -// IValue[] theValues = new IValue[values.length]; -// for (int i = 0; i < values.length; i++) { -// String value = values[values.length - i - 1]; -//// theValues[i] = new XDebugValue(this, value); -// } -// return theValues; -// } -// } catch (IOException e) { -// abort("Unable to retrieve data stack", e); -// } -// } - return new IValue[0]; - } - + // synchronized (fDebugSocket) { + // fDebugConnection.sendRequest ("data"); + // try { + // String valueString = fDebugReader.readLine(); + // if (valueString != null && valueString.length() > 0) { + // String[] values = valueString.split("\\|"); + // IValue[] theValues = new IValue[values.length]; + // for (int i = 0; i < values.length; i++) { + // String value = values[values.length - i - 1]; + // // theValues[i] = new XDebugValue(this, value); + // } + // return theValues; + // } + // } catch (IOException e) { + // abort("Unable to retrieve data stack", e); + // } + // } + return new IValue[0]; + } + public boolean setVarValue(String name, String value) { - int id=-1; - String str=Base64.encodeBytes(value.getBytes()); - int len=str.length(); + int id = -1; + String str = Base64.encodeBytes(value.getBytes()); + int len = str.length(); try { - id =fDebugConnection.sendRequest("property_set","-n "+name+" -l "+len + " -- "+str); + id = fDebugConnection.sendRequest("property_set", "-n " + name + + " -l " + len + " -- " + str); } catch (DebugException e) { // TODO Auto-generated catch block e.printStackTrace(); } - DebugResponse dr=getResponse(id); + DebugResponse dr = getResponse(id); if ((dr.getAttributeValue("success")).equals("1")) return true; - + return false; } - + public DebugResponse getResponse(int id) { return fDebugConnection.waitforTransID(id); } @@ -453,57 +549,69 @@ public class XDebugTarget extends XDebugElement implements IDebugTarget, IDebugE /** * Sends a request to the Debugengine and waits for an OK. * - * @param command debug command - * @throws DebugException if the request fails + * @param command + * debug command + * @throws DebugException + * if the request fails */ - - public int sendRequest(String command) throws DebugException { - return fDebugConnection.sendRequest(command,""); + + public int sendRequest(String command) throws DebugException { + return fDebugConnection.sendRequest(command, ""); } - /** * Sends a request to the Debugengine and waits for an OK. * - * @param command debug command + * @param command + * debug command * @arguments arguments for the command - * @throws DebugException if the request fails + * @throws DebugException + * if the request fails */ - - public int sendRequest(String command, String arguments) throws DebugException { - return fDebugConnection.sendRequest(command,arguments); + + public int sendRequest(String command, String arguments) + throws DebugException { + return fDebugConnection.sendRequest(command, arguments); } - + /** - * Notification a breakpoint was encountered. Determine - * which breakpoint was hit and fire a suspend event. + * Notification a breakpoint was encountered. Determine which breakpoint was + * hit and fire a suspend event. * - * @param event debug event + * @param event + * debug event */ public void breakpointHit(Node node) { // determine which breakpoint was hit, and set the thread's breakpoint - Node child=node.getFirstChild(); + Node child = node.getFirstChild(); if (child.getNodeName().equals("stack")) { - int lineNumber = Integer.parseInt(PHPDebugUtils.getAttributeValue(child, "lineno")); - String filename=PHPDebugUtils.getAttributeValue(child, "filename").substring(8); // remove file:/// + int lineNumber = Integer.parseInt(PHPDebugUtils.getAttributeValue( + child, "lineno")); + String filename = PHPDebugUtils + .getAttributeValue(child, "filename").substring(8); // remove + // file:/// IBreakpoint[] breakpoints = XDebugCorePlugin.getBreakpoints(); for (int i = 0; i < breakpoints.length; i++) { IBreakpoint breakpoint = breakpoints[i]; if (supportsBreakpoint(breakpoint)) { if (breakpoint instanceof ILineBreakpoint) { ILineBreakpoint lineBreakpoint = (ILineBreakpoint) breakpoint; - try { + try { if (breakpoint.isEnabled()) { IMarker marker = breakpoint.getMarker(); if (marker != null) { - - String name = marker.getResource().getLocation().toOSString(); - if(name.equals(PHPDebugUtils.unescapeString(filename)) && (lineBreakpoint.getLineNumber() == lineNumber)) { - fThread.setBreakpoints(new IBreakpoint[]{breakpoint}); + + String name = marker.getResource() + .getLocation().toOSString(); + if (name.equals(PHPDebugUtils + .unescapeString(filename)) + && (lineBreakpoint.getLineNumber() == lineNumber)) { + fThread + .setBreakpoints(new IBreakpoint[] { breakpoint }); break; } } - + } } catch (CoreException e) { } @@ -513,16 +621,18 @@ public class XDebugTarget extends XDebugElement implements IDebugTarget, IDebugE } suspended(DebugEvent.BREAKPOINT); } + public void handleDebugEvents(DebugEvent[] events) { - for (int i=0;inull - * if none. + * Breakpoints this thread is suspended at or null if none. */ - - private IStackFrame[] fStackFrames=null; - + + private IStackFrame[] fStackFrames = null; + private IBreakpoint[] fBreakpoints; - + /** * Whether this thread is stepping */ private boolean fStepping = false; - + /** * Constructs a new thread for the given target * - * @param target VM + * @param target + * VM */ public XDebugThread(XDebugTarget target) { super(target); DebugPlugin.getDefault().addDebugEventListener(this); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IThread#getStackFrames() */ public IStackFrame[] getStackFrames() throws DebugException { if (isSuspended()) { - if (fStackFrames==null) - { -// XDebugCorePlugin.log(IStatus.INFO,"vor getStackFrames"); - fStackFrames=((XDebugTarget) getDebugTarget()).getStackFrames(); -// XDebugCorePlugin.log(IStatus.INFO,"nach getStackFrames"); + if (fStackFrames == null) { + // XDebugCorePlugin.log(IStatus.INFO,"vor getStackFrames"); + fStackFrames = ((XDebugTarget) getDebugTarget()) + .getStackFrames(); + // XDebugCorePlugin.log(IStatus.INFO,"nach getStackFrames"); } return fStackFrames; } else { return new IStackFrame[0]; } } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IThread#hasStackFrames() */ public boolean hasStackFrames() throws DebugException { return isSuspended(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IThread#getPriority() */ public int getPriority() throws DebugException { return 0; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IThread#getTopStackFrame() */ public IStackFrame getTopStackFrame() throws DebugException { @@ -84,16 +96,22 @@ public class XDebugThread extends XDebugElement implements IThread, IDebugEventS } return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IThread#getName() */ public String getName() throws DebugException { -// if (fStackFrames!=null) -// return fStackFrames[0].getName(); -// else - return "Thread[1]"; + // if (fStackFrames!=null) + // return fStackFrames[0].getName(); + // else + return "Thread[1]"; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IThread#getBreakpoints() */ public IBreakpoint[] getBreakpoints() { @@ -102,136 +120,184 @@ public class XDebugThread extends XDebugElement implements IThread, IDebugEventS } return fBreakpoints; } + /** * Sets the breakpoints this thread is suspended at, or null * if none. * - * @param breakpoints the breakpoints this thread is suspended at, or null - * if none + * @param breakpoints + * the breakpoints this thread is suspended at, or + * null if none */ protected void setBreakpoints(IBreakpoint[] breakpoints) { fBreakpoints = breakpoints; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.ISuspendResume#canResume() */ public boolean canResume() { return isSuspended(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.ISuspendResume#canSuspend() */ public boolean canSuspend() { return !isSuspended(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.ISuspendResume#isSuspended() */ public boolean isSuspended() { return getDebugTarget().isSuspended(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.ISuspendResume#resume() */ public void resume() throws DebugException { - fStackFrames=null; - fBreakpoints=null; + fStackFrames = null; + fBreakpoints = null; getDebugTarget().resume(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.ISuspendResume#suspend() */ public void suspend() throws DebugException { getDebugTarget().suspend(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IStep#canStepInto() */ public boolean canStepInto() { return isSuspended(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IStep#canStepOver() */ public boolean canStepOver() { return isSuspended(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IStep#canStepReturn() */ public boolean canStepReturn() { - if (fStackFrames!=null) - return (fStackFrames.length>1); + if (fStackFrames != null) + return (fStackFrames.length > 1); else return false; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IStep#isStepping() */ public boolean isStepping() { return fStepping; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IStep#stepInto() */ public void stepInto() throws DebugException { - fStackFrames=null; - fBreakpoints=null; - ((XDebugTarget)getDebugTarget()).step_into(); + fStackFrames = null; + fBreakpoints = null; + ((XDebugTarget) getDebugTarget()).step_into(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IStep#stepOver() */ public void stepOver() throws DebugException { - fStackFrames=null; - fBreakpoints=null; - ((XDebugTarget)getDebugTarget()).step_over(); + fStackFrames = null; + fBreakpoints = null; + ((XDebugTarget) getDebugTarget()).step_over(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IStep#stepReturn() */ public void stepReturn() throws DebugException { - fStackFrames=null; - fBreakpoints=null; - ((XDebugTarget)getDebugTarget()).step_out(); + fStackFrames = null; + fBreakpoints = null; + ((XDebugTarget) getDebugTarget()).step_out(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.ITerminate#canTerminate() */ public boolean canTerminate() { return !isTerminated(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.ITerminate#isTerminated() */ public boolean isTerminated() { return getDebugTarget().isTerminated(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.ITerminate#terminate() */ public void terminate() throws DebugException { getDebugTarget().terminate(); } - + /** * Sets whether this thread is stepping * - * @param stepping whether stepping + * @param stepping + * whether stepping */ protected void setStepping(boolean stepping) { fStepping = stepping; } public void handleDebugEvents(DebugEvent[] events) { - DebugEvent de=events[0]; + DebugEvent de = events[0]; System.out.println(de.toString()); - + } public void removeEventListeners() { DebugPlugin.getDefault().removeDebugEventListener(this); - + } } diff --git a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugValue.java b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugValue.java index cc158a9..72a1e70 100644 --- a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugValue.java +++ b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugValue.java @@ -10,11 +10,12 @@ public class XDebugValue extends XDebugAbstractValue { } public void setType(String typeName) { - fType=XDebugAbstractValue.VALUETYPE_UNINITIALIZED; - fTypeName="unknown"; + fType = XDebugAbstractValue.VALUETYPE_UNINITIALIZED; + fTypeName = "unknown"; } + public void renderValueString(String data) { - fValueString="uninitialized"; + fValueString = "uninitialized"; } public boolean verifyValue(String expression) { diff --git a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugVariable.java b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugVariable.java index a6646da..21663d3 100644 --- a/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugVariable.java +++ b/net.sourceforge.phpeclipse.xdebug.core/src/net/sourceforge/phpeclipse/xdebug/php/model/XDebugVariable.java @@ -6,7 +6,6 @@ */ package net.sourceforge.phpeclipse.xdebug.php.model; - import net.sourceforge.phpeclipse.xdebug.core.PHPDebugUtils; import org.eclipse.debug.core.DebugEvent; @@ -17,39 +16,53 @@ import org.w3c.dom.Node; /** * @author Axel - * - * TODO To change the template for this generated type comment go to - * Window - Preferences - Java - Code Style - Code Templates + * + * TODO To change the template for this generated type comment go to Window - + * Preferences - Java - Code Style - Code Templates */ -public class XDebugVariable extends XDebugElement implements IVariable { - +public class XDebugVariable extends XDebugElement implements IVariable { + public static final int VARTYPE_UNKNOWN = -1; + public static final int VARTYPE_UNINITIALIZED = 0; + public static final int VARTYPE_STRING = 1; + public static final int VARTYPE_INT = 2; + public static final int VARTYPE_FLOAT = 3; + public static final int VARTYPE_ARRAY = 8; + public static final int VARTYPE_HASH = 9; + public static final int VARTYPE_OBJECT = 10; - // name & stack frmae private String fName; + private XDebugStackFrame fFrame; + private String fFullName; -// private String fTypeName; -// private int fType; + + // private String fTypeName; + // private int fType; private XDebugAbstractValue fValue; + private String fEncoding; + private int fNumChildren; -// private Node fVariableNode; - + + // private Node fVariableNode; + /** - * Constructs a variable contained in the given stack frame - * with the given name. + * Constructs a variable contained in the given stack frame with the given + * name. * - * @param frame owning stack frame - * @param name variable name + * @param frame + * owning stack frame + * @param name + * variable name */ public XDebugVariable(XDebugStackFrame frame, Node property) { super((XDebugTarget) frame.getDebugTarget()); @@ -57,62 +70,67 @@ public class XDebugVariable extends XDebugElement implements IVariable { init(property); } - - private void init(Node property) { - fFullName=PHPDebugUtils.getAttributeValue(property,"fullname"); - fName=PHPDebugUtils.getAttributeValue(property,"name"); - fEncoding=PHPDebugUtils.getAttributeValue(property,"encoding"); - if (PHPDebugUtils.getAttributeValue(property,"numchildren").equals("")) + + private void init(Node property) { + fFullName = PHPDebugUtils.getAttributeValue(property, "fullname"); + fName = PHPDebugUtils.getAttributeValue(property, "name"); + fEncoding = PHPDebugUtils.getAttributeValue(property, "encoding"); + if (PHPDebugUtils.getAttributeValue(property, "numchildren").equals("")) fNumChildren = 0; else - fNumChildren=Integer.parseInt(PHPDebugUtils.getAttributeValue(property,"numchildren")); - - String typeName=PHPDebugUtils.getAttributeValue(property,"type"); - -// if (typeName.equals("uninitialized") ) -// fValue= new XDebugValue(this,property,typeName); - if (typeName.equals("int") ) - fValue= new XDebugIntValue(this,property,typeName); - else if (typeName.equals("float") ) - fValue= new XDebugFloatValue(this,property,typeName); - else if (typeName.equals("bool") ) - fValue= new XDebugBooleanValue(this,property,typeName); - else if (typeName.equals("string") ) - fValue= new XDebugStringValue(this,property,typeName); - else if (typeName.equals("array") ) - fValue= new XDebugArrayValue(this,property,typeName); - else if (typeName.equals("hash") ) - fValue= new XDebugArrayValue(this,property,typeName); - else if (typeName.equals("object") ) - fValue= new XDebugArrayValue(this,property,typeName); + fNumChildren = Integer.parseInt(PHPDebugUtils.getAttributeValue( + property, "numchildren")); + + String typeName = PHPDebugUtils.getAttributeValue(property, "type"); + + // if (typeName.equals("uninitialized") ) + // fValue= new XDebugValue(this,property,typeName); + if (typeName.equals("int")) + fValue = new XDebugIntValue(this, property, typeName); + else if (typeName.equals("float")) + fValue = new XDebugFloatValue(this, property, typeName); + else if (typeName.equals("bool")) + fValue = new XDebugBooleanValue(this, property, typeName); + else if (typeName.equals("string")) + fValue = new XDebugStringValue(this, property, typeName); + else if (typeName.equals("array")) + fValue = new XDebugArrayValue(this, property, typeName); + else if (typeName.equals("hash")) + fValue = new XDebugArrayValue(this, property, typeName); + else if (typeName.equals("object")) + fValue = new XDebugArrayValue(this, property, typeName); else - fValue= new XDebugValue(this,property,typeName); - -// else if (typeName.equals("float") ) -// fTypeName= VARTYPE_FLOAT; -// else if (typeName.equals("string") ) -// fTypeName= VARTYPE_STRING; -// else if (typeName.equals("hash") ) -// fTypeName= VARTYPE_HASH; -// else if (typeName.equals("array") ) -// fTypeName= VARTYPE_ARRAY; -// else if (typeName.equals("object") ) -// fTypeName= VARTYPE_OBJECT; - - - -// fTypeName=type; -// -// fValue= new XDebugValue(this,property); - } - /* (non-Javadoc) + fValue = new XDebugValue(this, property, typeName); + + // else if (typeName.equals("float") ) + // fTypeName= VARTYPE_FLOAT; + // else if (typeName.equals("string") ) + // fTypeName= VARTYPE_STRING; + // else if (typeName.equals("hash") ) + // fTypeName= VARTYPE_HASH; + // else if (typeName.equals("array") ) + // fTypeName= VARTYPE_ARRAY; + // else if (typeName.equals("object") ) + // fTypeName= VARTYPE_OBJECT; + + // fTypeName=type; + // + // fValue= new XDebugValue(this,property); + } + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IVariable#getValue() */ public IValue getValue() throws DebugException { return fValue; -// return ((XDebugTarget)getDebugTarget()).getVariableValue(this); + // return ((XDebugTarget)getDebugTarget()).getVariableValue(this); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IVariable#getName() */ public String getName() throws DebugException { @@ -121,50 +139,72 @@ public class XDebugVariable extends XDebugElement implements IVariable { else return fName; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IVariable#getReferenceTypeName() */ public String getReferenceTypeName() throws DebugException { return fValue.getReferenceTypeName(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IVariable#hasValueChanged() */ public boolean hasValueChanged() throws DebugException { // TODO Auto-generated method stub return false; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IValueModification#setValue(java.lang.String) */ public void setValue(String expression) throws DebugException { - if(fValue.setValue(expression)) - fireEvent(new DebugEvent(this, DebugEvent.CHANGE, DebugEvent.CONTENT)); + if (fValue.setValue(expression)) + fireEvent(new DebugEvent(this, DebugEvent.CHANGE, + DebugEvent.CONTENT)); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IValueModification#setValue(org.eclipse.debug.core.model.IValue) */ public void setValue(IValue value) throws DebugException { } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IValueModification#supportsValueModification() */ public boolean supportsValueModification() { return fValue.supportsValueModification(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IValueModification#verifyValue(java.lang.String) */ public boolean verifyValue(String expression) throws DebugException { return fValue.verifyValue(expression); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.core.model.IValueModification#verifyValue(org.eclipse.debug.core.model.IValue) */ public boolean verifyValue(IValue value) throws DebugException { return false; } - + /** * Returns the stack frame owning this variable. * @@ -174,16 +214,16 @@ public class XDebugVariable extends XDebugElement implements IVariable { return fFrame; } -// public int getType() { -// return fType; -// } + // public int getType() { + // return fType; + // } public String getValueString() throws DebugException { return fValue.getValueString(); } - + public boolean hasChildren() { - return (fNumChildren>0); + return (fNumChildren > 0); } public boolean isArray() { @@ -197,7 +237,7 @@ public class XDebugVariable extends XDebugElement implements IVariable { public void setEncoding(String encoding) { fEncoding = encoding; } - + public String toString() { return fValue.toString(); } diff --git a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/EnvironmentVariable.java b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/EnvironmentVariable.java index f615429..293bfe4 100644 --- a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/EnvironmentVariable.java +++ b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/EnvironmentVariable.java @@ -3,16 +3,14 @@ package net.sourceforge.phpeclipse.xdebug.ui; /** * A key/value set whose data is passed into Runtime.exec(...) */ -public class EnvironmentVariable -{ +public class EnvironmentVariable { // The name of the environment variable private String name; - + // The value of the environment variable private String value; - - public EnvironmentVariable(String name, String value) - { + + public EnvironmentVariable(String name, String value) { this.name = name; this.value = value; } @@ -23,54 +21,57 @@ public class EnvironmentVariable * * @return this variable's name */ - public String getName() - { + public String getName() { return name; } - + /** * Returns this variables value. * * @return this variable's value */ - public String getValue() - { + public String getValue() { return value; } - + /** * Sets this variable's value + * * @param value */ - public void setValue(String value) - { + public void setValue(String value) { this.value = value; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ public String toString() { return getName(); } - - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { boolean equal = false; if (obj instanceof EnvironmentVariable) { - EnvironmentVariable var = (EnvironmentVariable)obj; + EnvironmentVariable var = (EnvironmentVariable) obj; equal = var.getName().equals(name); } - return equal; + return equal; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see java.lang.Object#hashCode() */ public int hashCode() { return name.hashCode(); } } - diff --git a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/MultipleInputDialog.java b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/MultipleInputDialog.java index 3af109a..0f23c3e 100644 --- a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/MultipleInputDialog.java +++ b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/MultipleInputDialog.java @@ -28,28 +28,34 @@ import org.eclipse.swt.widgets.Text; public class MultipleInputDialog extends Dialog { protected static final String FIELD_NAME = "FIELD_NAME"; //$NON-NLS-1$ + protected static final int TEXT = 100; + protected static final int BROWSE = 101; + protected static final int VARIABLE = 102; - + protected Composite panel; - + protected List fieldList = new ArrayList(); + protected List controlList = new ArrayList(); + protected List validators = new ArrayList(); + protected Map valueMap = new HashMap(); private String title; - - - + public MultipleInputDialog(Shell shell, String title) { super(shell); this.title = title; setShellStyle(getShellStyle() | SWT.RESIZE); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell) */ protected void configureShell(Shell shell) { @@ -57,10 +63,12 @@ public class MultipleInputDialog extends Dialog { if (title != null) { shell.setText(title); } - + } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.jface.dialogs.Dialog#createButtonBar(org.eclipse.swt.widgets.Composite) */ protected Control createButtonBar(Composite parent) { @@ -68,66 +76,80 @@ public class MultipleInputDialog extends Dialog { validateFields(); return bar; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite) */ protected Control createDialogArea(Composite parent) { - Composite container = (Composite)super.createDialogArea(parent); + Composite container = (Composite) super.createDialogArea(parent); container.setLayout(new GridLayout(2, false)); container.setLayoutData(new GridData(GridData.FILL_BOTH)); - + panel = new Composite(container, SWT.NONE); GridLayout layout = new GridLayout(2, false); panel.setLayout(layout); panel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - + for (Iterator i = fieldList.iterator(); i.hasNext();) { - FieldSummary field = (FieldSummary)i.next(); - switch(field.type) { - case TEXT: - createTextField(field.name, field.initialValue, field.allowsEmpty); - break; - case BROWSE: - createBrowseField(field.name, field.initialValue, field.allowsEmpty); - break; - case VARIABLE: - createVariablesField(field.name, field.initialValue, field.allowsEmpty); - break; + FieldSummary field = (FieldSummary) i.next(); + switch (field.type) { + case TEXT: + createTextField(field.name, field.initialValue, + field.allowsEmpty); + break; + case BROWSE: + createBrowseField(field.name, field.initialValue, + field.allowsEmpty); + break; + case VARIABLE: + createVariablesField(field.name, field.initialValue, + field.allowsEmpty); + break; } } - + fieldList = null; // allow it to be gc'd Dialog.applyDialogFont(container); return container; } - - public void addBrowseField(String labelText, String initialValue, boolean allowsEmpty) { - fieldList.add(new FieldSummary(BROWSE, labelText, initialValue, allowsEmpty)); + + public void addBrowseField(String labelText, String initialValue, + boolean allowsEmpty) { + fieldList.add(new FieldSummary(BROWSE, labelText, initialValue, + allowsEmpty)); } - public void addTextField(String labelText, String initialValue, boolean allowsEmpty) { - fieldList.add(new FieldSummary(TEXT, labelText, initialValue, allowsEmpty)); + + public void addTextField(String labelText, String initialValue, + boolean allowsEmpty) { + fieldList.add(new FieldSummary(TEXT, labelText, initialValue, + allowsEmpty)); } - public void addVariablesField(String labelText, String initialValue, boolean allowsEmpty) { - fieldList.add(new FieldSummary(VARIABLE, labelText, initialValue, allowsEmpty)); + + public void addVariablesField(String labelText, String initialValue, + boolean allowsEmpty) { + fieldList.add(new FieldSummary(VARIABLE, labelText, initialValue, + allowsEmpty)); } - protected void createTextField(String labelText, String initialValue, boolean allowEmpty) { + protected void createTextField(String labelText, String initialValue, + boolean allowEmpty) { Label label = new Label(panel, SWT.NONE); label.setText(labelText); label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); - + final Text text = new Text(panel, SWT.SINGLE | SWT.BORDER); text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); text.setData(FIELD_NAME, labelText); - + // make sure rows are the same height on both panels. - label.setSize(label.getSize().x, text.getSize().y); - + label.setSize(label.getSize().x, text.getSize().y); + if (initialValue != null) { text.setText(initialValue); } - + if (!allowEmpty) { validators.add(new Validator() { public boolean validate() { @@ -140,22 +162,23 @@ public class MultipleInputDialog extends Dialog { } }); } - + controlList.add(text); } - - protected void createBrowseField(String labelText, String initialValue, boolean allowEmpty) { + + protected void createBrowseField(String labelText, String initialValue, + boolean allowEmpty) { Label label = new Label(panel, SWT.NONE); label.setText(labelText); label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); - + Composite comp = new Composite(panel, SWT.NONE); GridLayout layout = new GridLayout(); - layout.marginHeight=0; - layout.marginWidth=0; + layout.marginHeight = 0; + layout.marginWidth = 0; comp.setLayout(layout); comp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - + final Text text = new Text(comp, SWT.SINGLE | SWT.BORDER); GridData data = new GridData(GridData.FILL_HORIZONTAL); data.widthHint = 200; @@ -163,8 +186,8 @@ public class MultipleInputDialog extends Dialog { text.setData(FIELD_NAME, labelText); // make sure rows are the same height on both panels. - label.setSize(label.getSize().x, text.getSize().y); - + label.setSize(label.getSize().x, text.getSize().y); + if (initialValue != null) { text.setText(initialValue); } @@ -182,44 +205,45 @@ public class MultipleInputDialog extends Dialog { } }); } - - Button button = createButton(comp, IDialogConstants.IGNORE_ID, "&Browse...", false); + + Button button = createButton(comp, IDialogConstants.IGNORE_ID, + "&Browse...", false); button.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { DirectoryDialog dialog = new DirectoryDialog(getShell()); - dialog.setMessage("Select a file:"); + dialog.setMessage("Select a file:"); String currentWorkingDir = text.getText(); if (!currentWorkingDir.trim().equals("")) { //$NON-NLS-1$ File path = new File(currentWorkingDir); if (path.exists()) { dialog.setFilterPath(currentWorkingDir); - } + } } - + String selectedDirectory = dialog.open(); if (selectedDirectory != null) { text.setText(selectedDirectory); - } + } } }); controlList.add(text); - + } - - - public void createVariablesField(String labelText, String initialValue, boolean allowEmpty) { + + public void createVariablesField(String labelText, String initialValue, + boolean allowEmpty) { Label label = new Label(panel, SWT.NONE); label.setText(labelText); label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); - + Composite comp = new Composite(panel, SWT.NONE); GridLayout layout = new GridLayout(); - layout.marginHeight=0; - layout.marginWidth=0; + layout.marginHeight = 0; + layout.marginWidth = 0; comp.setLayout(layout); comp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - + final Text text = new Text(comp, SWT.SINGLE | SWT.BORDER); GridData data = new GridData(GridData.FILL_HORIZONTAL); data.widthHint = 200; @@ -227,8 +251,8 @@ public class MultipleInputDialog extends Dialog { text.setData(FIELD_NAME, labelText); // make sure rows are the same height on both panels. - label.setSize(label.getSize().x, text.getSize().y); - + label.setSize(label.getSize().x, text.getSize().y); + if (initialValue != null) { text.setText(initialValue); } @@ -246,11 +270,13 @@ public class MultipleInputDialog extends Dialog { } }); } - - Button button = createButton(comp, IDialogConstants.IGNORE_ID, "Varia&bles...", false); + + Button button = createButton(comp, IDialogConstants.IGNORE_ID, + "Varia&bles...", false); button.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { - StringVariableSelectionDialog dialog = new StringVariableSelectionDialog(getShell()); + StringVariableSelectionDialog dialog = new StringVariableSelectionDialog( + getShell()); int code = dialog.open(); if (code == IDialogConstants.OK_ID) { String variable = dialog.getVariableExpression(); @@ -262,42 +288,46 @@ public class MultipleInputDialog extends Dialog { }); controlList.add(text); - + } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.jface.dialogs.Dialog#okPressed() */ protected void okPressed() { - for (Iterator i = controlList.iterator(); i.hasNext(); ) { - Control control = (Control)i.next(); + for (Iterator i = controlList.iterator(); i.hasNext();) { + Control control = (Control) i.next(); if (control instanceof Text) { - valueMap.put(control.getData(FIELD_NAME), ((Text)control).getText()); + valueMap.put(control.getData(FIELD_NAME), ((Text) control) + .getText()); } } controlList = null; super.okPressed(); } - - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.window.Window#open() */ public int open() { applyDialogFont(panel); return super.open(); } - + public Object getValue(String key) { return valueMap.get(key); } - + public String getStringValue(String key) { - return (String) getValue(key); + return (String) getValue(key); } - + public void validateFields() { - for(Iterator i = validators.iterator(); i.hasNext(); ) { + for (Iterator i = validators.iterator(); i.hasNext();) { Validator validator = (Validator) i.next(); if (!validator.validate()) { getButton(IDialogConstants.OK_ID).setEnabled(false); @@ -307,52 +337,60 @@ public class MultipleInputDialog extends Dialog { getButton(IDialogConstants.OK_ID).setEnabled(true); } -// /* (non-Javadoc) -// * @see org.eclipse.jface.window.Window#getInitialLocation(org.eclipse.swt.graphics.Point) -// */ -// protected Point getInitialLocation(Point initialSize) { -// Point initialLocation= DialogSettingsHelper.getInitialLocation(getDialogSettingsSectionName()); -// if (initialLocation != null) { -// return initialLocation; -// } -// return super.getInitialLocation(initialSize); -// } - - + // /* (non-Javadoc) + // * @see + // org.eclipse.jface.window.Window#getInitialLocation(org.eclipse.swt.graphics.Point) + // */ + // protected Point getInitialLocation(Point initialSize) { + // Point initialLocation= + // DialogSettingsHelper.getInitialLocation(getDialogSettingsSectionName()); + // if (initialLocation != null) { + // return initialLocation; + // } + // return super.getInitialLocation(initialSize); + // } + protected String getDialogSettingsSectionName() { return IDebugUIConstants.PLUGIN_ID + ".MULTIPLE_INPUT_DIALOG_2"; //$NON-NLS-1$ } - -// /* (non-Javadoc) -// * @see org.eclipse.jface.window.Window#getInitialSize() -// */ -// protected Point getInitialSize() { -// Point size = super.getInitialSize(); -// return DialogSettingsHelper.getInitialSize(getDialogSettingsSectionName(), size); -// } - -// /* (non-Javadoc) -// * @see org.eclipse.jface.window.Window#close() -// */ -// public boolean close() { -// DialogSettingsHelper.persistShellGeometry(getShell(), getDialogSettingsSectionName()); -// return super.close(); -// } + + // /* (non-Javadoc) + // * @see org.eclipse.jface.window.Window#getInitialSize() + // */ + // protected Point getInitialSize() { + // Point size = super.getInitialSize(); + // return + // DialogSettingsHelper.getInitialSize(getDialogSettingsSectionName(), + // size); + // } + + // /* (non-Javadoc) + // * @see org.eclipse.jface.window.Window#close() + // */ + // public boolean close() { + // DialogSettingsHelper.persistShellGeometry(getShell(), + // getDialogSettingsSectionName()); + // return super.close(); + // } protected class FieldSummary { int type; + String name; + String initialValue; + boolean allowsEmpty; - - public FieldSummary(int type, String name, String initialValue, boolean allowsEmpty) { + + public FieldSummary(int type, String name, String initialValue, + boolean allowsEmpty) { this.type = type; this.name = name; this.initialValue = initialValue; this.allowsEmpty = allowsEmpty; } } - + protected class Validator { boolean validate() { return true; diff --git a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/XDebugUIPlugin.java b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/XDebugUIPlugin.java index 03dc4a5..a069314 100644 --- a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/XDebugUIPlugin.java +++ b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/XDebugUIPlugin.java @@ -3,14 +3,14 @@ package net.sourceforge.phpeclipse.xdebug.ui; import java.util.MissingResourceException; import java.util.ResourceBundle; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.plugin.*; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; /** @@ -22,13 +22,12 @@ public class XDebugUIPlugin extends AbstractUIPlugin { private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle .getBundle(BUNDLE_NAME); - - private static final String PLUGIN_ID ="net.sourceforge.phpeclipse.xdebug.ui"; - - //The shared instance. + private static final String PLUGIN_ID = "net.sourceforge.phpeclipse.xdebug.ui"; + + // The shared instance. private static XDebugUIPlugin plugin; - + /** * The constructor. */ @@ -59,51 +58,57 @@ public class XDebugUIPlugin extends AbstractUIPlugin { } /** - * Returns an image descriptor for the image file at the given - * plug-in relative path. - * - * @param path the path + * Returns an image descriptor for the image file at the given plug-in + * relative path. + * + * @param path + * the path * @return the image descriptor */ public static ImageDescriptor getImageDescriptor(String path) { - return AbstractUIPlugin.imageDescriptorFromPlugin("net.sourceforge.phpeclipse.xdebug.ui", path); + return AbstractUIPlugin.imageDescriptorFromPlugin( + "net.sourceforge.phpeclipse.xdebug.ui", path); } - + /** * Convenience method which returns the unique identifier of this plugin. */ public static String getUniqueIdentifier() { return PLUGIN_ID; } - + /** * Utility method with conventions */ - public static void errorDialog(Shell shell, String title, String message, IStatus s) { - // if the 'message' resource string and the IStatus' message are the same, + public static void errorDialog(Shell shell, String title, String message, + IStatus s) { + // if the 'message' resource string and the IStatus' message are the + // same, // don't show both in the dialog if (s != null && message.equals(s.getMessage())) { - message= null; + message = null; } ErrorDialog.openError(shell, title, message, s); } - /** * Utility method with conventions */ - public static void errorDialog(Shell shell, String title, String message, Throwable t) { + public static void errorDialog(Shell shell, String title, String message, + Throwable t) { IStatus status; if (t instanceof CoreException) { - status= ((CoreException)t).getStatus(); - // if the 'message' resource string and the IStatus' message are the same, + status = ((CoreException) t).getStatus(); + // if the 'message' resource string and the IStatus' message are the + // same, // don't show both in the dialog if (status != null && message.equals(status.getMessage())) { - message= null; + message = null; } } else { - status= new Status(IStatus.ERROR, getUniqueIdentifier(), IStatus.ERROR, "Error within Debug UI: ", t); //$NON-NLS-1$ - log(status); + status = new Status(IStatus.ERROR, getUniqueIdentifier(), + IStatus.ERROR, "Error within Debug UI: ", t); //$NON-NLS-1$ + log(status); } ErrorDialog.openError(shell, title, message, status); } @@ -111,32 +116,35 @@ public class XDebugUIPlugin extends AbstractUIPlugin { /** * Logs the specified status with this plug-in's log. * - * @param status status to log + * @param status + * status to log */ public static void log(IStatus status) { getDefault().getLog().log(status); } - + /** * Logs an internal error with the specified throwable * - * @param e the exception to be logged - */ + * @param e + * the exception to be logged + */ public static void log(Throwable e) { - log(new Status(IStatus.ERROR, getUniqueIdentifier(), IStatus.ERROR, "Internal Error", e)); + log(new Status(IStatus.ERROR, getUniqueIdentifier(), IStatus.ERROR, + "Internal Error", e)); } - + /** - * Returns the standard display to be used. The method first checks, if - * the thread calling this method has an associated display. If so, this - * display is returned. Otherwise the method returns the default display. + * Returns the standard display to be used. The method first checks, if the + * thread calling this method has an associated display. If so, this display + * is returned. Otherwise the method returns the default display. */ public static Display getStandardDisplay() { Display display; - display= Display.getCurrent(); + display = Display.getCurrent(); if (display == null) - display= Display.getDefault(); - return display; + display = Display.getDefault(); + return display; } public static String getString(String key) { @@ -146,5 +154,5 @@ public class XDebugUIPlugin extends AbstractUIPlugin { return '!' + key + '!'; } } - + } diff --git a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/XDebugUIPluginImages.java b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/XDebugUIPluginImages.java index 69e49cc..1c48a08 100644 --- a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/XDebugUIPluginImages.java +++ b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/XDebugUIPluginImages.java @@ -10,7 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpeclipse.xdebug.ui; - import java.net.MalformedURLException; import java.net.URL; @@ -20,143 +19,160 @@ import org.eclipse.swt.graphics.Image; public class XDebugUIPluginImages { - /* Declare Common paths */ - private static URL ICON_BASE_URL= null; + private static URL ICON_BASE_URL = null; static { String pathSuffix = "icons/"; //$NON-NLS-1$ - ICON_BASE_URL= XDebugUIPlugin.getDefault().getBundle().getEntry(pathSuffix); + ICON_BASE_URL = XDebugUIPlugin.getDefault().getBundle().getEntry( + pathSuffix); } - + // The plugin registry private static ImageRegistry fgImageRegistry = null; - + /* * Set of predefined Image Descriptors. */ - private static final String T_OBJ= "obj16/"; //$NON-NLS-1$ -// private static final String T_OVR= "ovr16/"; //$NON-NLS-1$ - private static final String T_EVIEW= "eview16/"; //$NON-NLS-1$ - private static final String T_LCL="elcl16/"; + private static final String T_OBJ = "obj16/"; //$NON-NLS-1$ + // private static final String T_OVR= "ovr16/"; //$NON-NLS-1$ + + private static final String T_EVIEW = "eview16/"; //$NON-NLS-1$ + + private static final String T_LCL = "elcl16/"; public static final String IMG_EVIEW_ARGUMENTS_TAB = "IMG_EVIEW_ARGUMENTS_TAB"; + public static final String IMG_EVIEW_ENVIROMENT_TAB = "IMG_EVIEW_ENVIROMENT_TAB"; - - public static final String IMG_PREV_EVENT="IMG_PREV_EVENT"; - public static final String DESC_NEXT_EVENT="DESC_NEXT_EVENT"; - public static final String IMG_ERROR_ST_OBJ="IMG_ERROR_ST_OBJ"; - public static final String IMG_WARNING_ST_OBJ="IMG_WARNING_ST_OBJ"; - public static final String IMG_INFO_ST_OBJ="IMG_INFO_ST_OBJ"; - public static final String IMG_ERROR_STACK_OBJ="IMG_ERROR_STACK_OBJ"; + public static final String IMG_PREV_EVENT = "IMG_PREV_EVENT"; + + public static final String DESC_NEXT_EVENT = "DESC_NEXT_EVENT"; + public static final String IMG_ERROR_ST_OBJ = "IMG_ERROR_ST_OBJ"; - public static final String IMG_PROPERTIES = "IMG_PROPERTIES"; -// public static final String IMG_PROPERTIES_DISABLED = "IMG_PROPERTIES_DISABLED"; - public static final String IMG_CLEAR = "IMG_CLEAR"; -// public static final String IMG_CLEAR_DISABLED = "IMG_CLEAR_DISABLED"; - public static final String IMG_READ_LOG = "IMG_READ_LOG"; -// public static final String IMG_READ_LOG_DISABLED = "IMG_READ_LOG_DISABLED"; - public static final String IMG_REMOVE_LOG = "IMG_REMOVE_LOG"; -// public static final String IMG_REMOVE_LOG_DISABLED = "IMG_REMOVE_LOG_DISABLED"; - public static final String IMG_FILTER = "IMG_FILTER"; -// public static final String IMG_FILTER_DISABLED = "IMG_FILTER_DISABLED"; - public static final String IMG_EXPORT = "IMG_EXPORT"; -// public static final String IMG_EXPORT_DISABLED = "IMG_EXPORT_DISABLED"; - public static final String IMG_IMPORT = "IMG_IMPORT"; -// public static final String IMG_IMPORT_DISABLED = "IMG_IMPORT_DISABLED"; - public static final String IMG_OPEN_LOG = "IMG_OPEN_LOG"; + public static final String IMG_WARNING_ST_OBJ = "IMG_WARNING_ST_OBJ"; + public static final String IMG_INFO_ST_OBJ = "IMG_INFO_ST_OBJ"; + public static final String IMG_ERROR_STACK_OBJ = "IMG_ERROR_STACK_OBJ"; + public static final String IMG_PROPERTIES = "IMG_PROPERTIES"; + // public static final String IMG_PROPERTIES_DISABLED = + // "IMG_PROPERTIES_DISABLED"; + public static final String IMG_CLEAR = "IMG_CLEAR"; + + // public static final String IMG_CLEAR_DISABLED = "IMG_CLEAR_DISABLED"; + public static final String IMG_READ_LOG = "IMG_READ_LOG"; + + // public static final String IMG_READ_LOG_DISABLED = + // "IMG_READ_LOG_DISABLED"; + public static final String IMG_REMOVE_LOG = "IMG_REMOVE_LOG"; + + // public static final String IMG_REMOVE_LOG_DISABLED = + // "IMG_REMOVE_LOG_DISABLED"; + public static final String IMG_FILTER = "IMG_FILTER"; + + // public static final String IMG_FILTER_DISABLED = "IMG_FILTER_DISABLED"; + public static final String IMG_EXPORT = "IMG_EXPORT"; + + // public static final String IMG_EXPORT_DISABLED = "IMG_EXPORT_DISABLED"; + public static final String IMG_IMPORT = "IMG_IMPORT"; + + // public static final String IMG_IMPORT_DISABLED = "IMG_IMPORT_DISABLED"; + public static final String IMG_OPEN_LOG = "IMG_OPEN_LOG"; /** * Returns the image managed under the given key in this registry. * - * @param key the image's key + * @param key + * the image's key * @return the image managed under the given key - */ + */ public static Image get(String key) { return getImageRegistry().get(key); } - + /** * Returns the ImageDescriptor identified by the given key, * or null if it does not exist. */ public static ImageDescriptor getImageDescriptor(String key) { return getImageRegistry().getDescriptor(key); - } - + } + /* * Helper method to access the image registry from the XDebugUIPlugin class. */ - public static ImageRegistry getImageRegistry() { + public static ImageRegistry getImageRegistry() { if (fgImageRegistry == null) { initializeImageRegistry(); } return fgImageRegistry; } - + public static void initializeImageRegistry() { - fgImageRegistry= new ImageRegistry(XDebugUIPlugin.getStandardDisplay()); + fgImageRegistry = new ImageRegistry(XDebugUIPlugin.getStandardDisplay()); declareImages(); } - + private static void declareImages() { - declareRegistryImage(IMG_EVIEW_ARGUMENTS_TAB, T_EVIEW + "arguments_tab.gif"); //$NON-NLS-1$ - declareRegistryImage(IMG_EVIEW_ENVIROMENT_TAB, T_EVIEW + "environment_tab.gif"); //$NON-NLS-1$ - - declareRegistryImage(IMG_ERROR_ST_OBJ,T_OBJ+"error_st_obj.gif"); - declareRegistryImage(IMG_WARNING_ST_OBJ,T_OBJ + "warning_st_obj.gif"); - declareRegistryImage(IMG_INFO_ST_OBJ,T_OBJ +"info_st_obj.gif"); - declareRegistryImage(IMG_ERROR_STACK_OBJ,T_OBJ +"error_stack.gif"); - - declareRegistryImage(IMG_PROPERTIES,T_LCL + "properties.gif"); -// declareRegistryImage(IMG_PROPERTIES_DISABLED - declareRegistryImage(IMG_CLEAR,T_LCL + "clear_log.gif"); -// declareRegistryImage(IMG_CLEAR_DISABLED - declareRegistryImage(IMG_READ_LOG ,T_LCL + "restore_log.gif"); -// declareRegistryImage(IMG_READ_LOG_DISABLED - declareRegistryImage(IMG_REMOVE_LOG,T_LCL + "remove_log.gif"); -// declareRegistryImage(IMG_REMOVE_LOG_DISABLED - declareRegistryImage(IMG_FILTER,T_LCL + "filter_log.gif"); -// declareRegistryImage(IMG_FILTER_DISABLED - declareRegistryImage(IMG_EXPORT,T_LCL + "export_log.gif"); -// declareRegistryImage(IMG_EXPORT_DISABLED - declareRegistryImage(IMG_IMPORT,T_LCL + "import_log.gif"); -// declareRegistryImage(IMG_IMPORT_DISABLED - declareRegistryImage(IMG_OPEN_LOG,T_LCL + "open_log.gif"); - - } - + declareRegistryImage(IMG_EVIEW_ARGUMENTS_TAB, T_EVIEW + + "arguments_tab.gif"); //$NON-NLS-1$ + declareRegistryImage(IMG_EVIEW_ENVIROMENT_TAB, T_EVIEW + + "environment_tab.gif"); //$NON-NLS-1$ + + declareRegistryImage(IMG_ERROR_ST_OBJ, T_OBJ + "error_st_obj.gif"); + declareRegistryImage(IMG_WARNING_ST_OBJ, T_OBJ + "warning_st_obj.gif"); + declareRegistryImage(IMG_INFO_ST_OBJ, T_OBJ + "info_st_obj.gif"); + declareRegistryImage(IMG_ERROR_STACK_OBJ, T_OBJ + "error_stack.gif"); + + declareRegistryImage(IMG_PROPERTIES, T_LCL + "properties.gif"); + // declareRegistryImage(IMG_PROPERTIES_DISABLED + declareRegistryImage(IMG_CLEAR, T_LCL + "clear_log.gif"); + // declareRegistryImage(IMG_CLEAR_DISABLED + declareRegistryImage(IMG_READ_LOG, T_LCL + "restore_log.gif"); + // declareRegistryImage(IMG_READ_LOG_DISABLED + declareRegistryImage(IMG_REMOVE_LOG, T_LCL + "remove_log.gif"); + // declareRegistryImage(IMG_REMOVE_LOG_DISABLED + declareRegistryImage(IMG_FILTER, T_LCL + "filter_log.gif"); + // declareRegistryImage(IMG_FILTER_DISABLED + declareRegistryImage(IMG_EXPORT, T_LCL + "export_log.gif"); + // declareRegistryImage(IMG_EXPORT_DISABLED + declareRegistryImage(IMG_IMPORT, T_LCL + "import_log.gif"); + // declareRegistryImage(IMG_IMPORT_DISABLED + declareRegistryImage(IMG_OPEN_LOG, T_LCL + "open_log.gif"); + + } + /** * Declare an Image in the registry table. - * @param key The key to use when registering the image - * @param path The path where the image can be found. This path is relative to where - * this plugin class is found (i.e. typically the packages directory) + * + * @param key + * The key to use when registering the image + * @param path + * The path where the image can be found. This path is relative + * to where this plugin class is found (i.e. typically the + * packages directory) */ private final static void declareRegistryImage(String key, String path) { - ImageDescriptor desc= ImageDescriptor.getMissingImageDescriptor(); + ImageDescriptor desc = ImageDescriptor.getMissingImageDescriptor(); try { - desc= ImageDescriptor.createFromURL(makeIconFileURL(path)); + desc = ImageDescriptor.createFromURL(makeIconFileURL(path)); } catch (MalformedURLException me) { XDebugUIPlugin.log(me); } fgImageRegistry.put(key, desc); - } - - private static URL makeIconFileURL(String iconPath) throws MalformedURLException { + } + + private static URL makeIconFileURL(String iconPath) + throws MalformedURLException { if (ICON_BASE_URL == null) { throw new MalformedURLException(); } - - return new URL(ICON_BASE_URL, iconPath); - } - - + return new URL(ICON_BASE_URL, iconPath); + } } diff --git a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/actions/BreakpointRulerActionDelegate.java b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/actions/BreakpointRulerActionDelegate.java index 5f906be..d222c4e 100644 --- a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/actions/BreakpointRulerActionDelegate.java +++ b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/actions/BreakpointRulerActionDelegate.java @@ -5,15 +5,13 @@ import org.eclipse.jface.text.source.IVerticalRulerInfo; import org.eclipse.ui.texteditor.AbstractRulerActionDelegate; import org.eclipse.ui.texteditor.ITextEditor; - - public class BreakpointRulerActionDelegate extends AbstractRulerActionDelegate { private ToggleBreakpointRulerAction fTargetAction; protected IAction createAction(ITextEditor editor, IVerticalRulerInfo rulerInfo) { - fTargetAction = new ToggleBreakpointRulerAction( editor, rulerInfo ); + fTargetAction = new ToggleBreakpointRulerAction(editor, rulerInfo); return fTargetAction; } diff --git a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/actions/ToggleBreakpointRulerAction.java b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/actions/ToggleBreakpointRulerAction.java index d6a03d2..98e294d 100644 --- a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/actions/ToggleBreakpointRulerAction.java +++ b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/actions/ToggleBreakpointRulerAction.java @@ -1,14 +1,14 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - IBM Corporation - Initial implementation - Vicente Fernando - www.alfersoft.com.ar -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + Vicente Fernando - www.alfersoft.com.ar + **********************************************************************/ package net.sourceforge.phpeclipse.xdebug.ui.actions; import net.sourceforge.phpeclipse.xdebug.ui.XDebugUIPlugin; @@ -27,47 +27,52 @@ import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.ITextEditor; -public class ToggleBreakpointRulerAction extends Action { - +public class ToggleBreakpointRulerAction extends Action { + static class EmptySelection implements ISelection { public boolean isEmpty() { return true; - } + } } - + private IVerticalRulerInfo fRuler; + private IWorkbenchPart fTargetPart; + private PHPLineBreakpointAdapter fBreakpointAdapter; - private static final ISelection EMPTY_SELECTION = new EmptySelection(); - - public ToggleBreakpointRulerAction( IWorkbenchPart part, IVerticalRulerInfo ruler ) { - super( "Toggle Breakpoint" ); //$NON-NLS-1$ - fRuler= ruler; + private static final ISelection EMPTY_SELECTION = new EmptySelection(); + + public ToggleBreakpointRulerAction(IWorkbenchPart part, + IVerticalRulerInfo ruler) { + super("Toggle Breakpoint"); //$NON-NLS-1$ + + fRuler = ruler; fRuler = ruler; - setTargetPart( part ); + setTargetPart(part); fBreakpointAdapter = new PHPLineBreakpointAdapter(); -// part.getSite().getWorkbenchWindow().getWorkbench().getHelpSystem().setHelp( this, ICDebugHelpContextIds.TOGGLE_BREAKPOINT_ACTION ); -// setId( IInternalCDebugUIConstants.ACTION_TOGGLE_BREAKPOINT ); + // part.getSite().getWorkbenchWindow().getWorkbench().getHelpSystem().setHelp( + // this, ICDebugHelpContextIds.TOGGLE_BREAKPOINT_ACTION ); + // setId( IInternalCDebugUIConstants.ACTION_TOGGLE_BREAKPOINT ); } - - + /** * @see Action#run() */ public void run() { try { - fBreakpointAdapter.toggleLineBreakpoints( getTargetPart(), getTargetSelection() ); - } - catch( CoreException e ) { - XDebugUIPlugin.errorDialog( getTargetPart().getSite().getShell(),"Error", "Operation failed" , e.getStatus() ); + fBreakpointAdapter.toggleLineBreakpoints(getTargetPart(), + getTargetSelection()); + } catch (CoreException e) { + XDebugUIPlugin.errorDialog(getTargetPart().getSite().getShell(), + "Error", "Operation failed", e.getStatus()); } } - + /** * Returns this action's vertical ruler info. - * + * * @return this action's vertical ruler */ protected IVerticalRulerInfo getVerticalRulerInfo() { @@ -78,45 +83,46 @@ public class ToggleBreakpointRulerAction extends Action { return this.fTargetPart; } - private void setTargetPart( IWorkbenchPart targetPart ) { + private void setTargetPart(IWorkbenchPart targetPart) { this.fTargetPart = targetPart; } /** - * Returns the current selection in the active part, possibly - * and empty selection, but never null. + * Returns the current selection in the active part, possibly and empty + * selection, but never null. * * @return the selection in the active part, possibly empty */ private ISelection getTargetSelection() { IDocument doc = getDocument(); - if ( doc != null ) { - int line = getVerticalRulerInfo().getLineOfLastMouseButtonActivity(); + if (doc != null) { + int line = getVerticalRulerInfo() + .getLineOfLastMouseButtonActivity(); try { - IRegion region = doc.getLineInformation( line ); - return new TextSelection( doc, region.getOffset(), region.getLength() ); + IRegion region = doc.getLineInformation(line); + return new TextSelection(doc, region.getOffset(), region + .getLength()); + } catch (BadLocationException e) { + DebugPlugin.log(e); } - catch( BadLocationException e ) { - DebugPlugin.log( e ); - } } return EMPTY_SELECTION; } private IDocument getDocument() { IWorkbenchPart targetPart = getTargetPart(); - if ( targetPart instanceof ITextEditor ) { - ITextEditor textEditor = (ITextEditor)targetPart; + if (targetPart instanceof ITextEditor) { + ITextEditor textEditor = (ITextEditor) targetPart; IDocumentProvider provider = textEditor.getDocumentProvider(); - if ( provider != null ) - return provider.getDocument( textEditor.getEditorInput() ); + if (provider != null) + return provider.getDocument(textEditor.getEditorInput()); } -// else if ( targetPart instanceof DisassemblyView ) { -// DisassemblyView dv = (DisassemblyView)targetPart; -// IDocumentProvider provider = dv.getDocumentProvider(); -// if ( provider != null ) -// return provider.getDocument( dv.getInput() ); -// } + // else if ( targetPart instanceof DisassemblyView ) { + // DisassemblyView dv = (DisassemblyView)targetPart; + // IDocumentProvider provider = dv.getDocumentProvider(); + // if ( provider != null ) + // return provider.getDocument( dv.getInput() ); + // } return null; } diff --git a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/launching/PHPDebugModelPresentation.java b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/launching/PHPDebugModelPresentation.java index 858937f..07b24f1 100644 --- a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/launching/PHPDebugModelPresentation.java +++ b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/launching/PHPDebugModelPresentation.java @@ -1,7 +1,5 @@ package net.sourceforge.phpeclipse.xdebug.ui.php.launching; - - import net.sourceforge.phpeclipse.xdebug.php.model.XDebugLineBreakpoint; import net.sourceforge.phpeclipse.xdebug.php.model.XDebugStackFrame; import net.sourceforge.phpeclipse.xdebug.php.model.XDebugTarget; @@ -40,26 +38,28 @@ public class PHPDebugModelPresentation implements IDebugModelPresentation { return DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_BREAKPOINT); } else if (element instanceof IMarker) { return DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_BREAKPOINT); - } else if (element instanceof XDebugStackFrame || element instanceof XDebugThread || element instanceof XDebugTarget) { + } else if (element instanceof XDebugStackFrame + || element instanceof XDebugThread + || element instanceof XDebugTarget) { return null; } else if (element instanceof XDebugVariable) { - return getVariableImage((XDebugVariable)element); + return getVariableImage((XDebugVariable) element); } else if (element instanceof XDebugValue) { - return getValueImage((XDebugValue)element); + return getValueImage((XDebugValue) element); } return DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_BREAKPOINT); } + private Image getVariableImage(XDebugVariable phpVar) { - /* if (phpVar != null) { - if (phpVar.isLocal()) - return DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_VARIABLE); - if (phpVar.isHashValue()) - return DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_VARIABLE); - } + /* + * if (phpVar != null) { if (phpVar.isLocal()) return + * DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_VARIABLE); if + * (phpVar.isHashValue()) return + * DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_VARIABLE); } */ return DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_VARIABLE); } - + private Image getValueImage(XDebugValue phpVar) { if (phpVar != null) { return DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_VARIABLE); @@ -67,7 +67,6 @@ public class PHPDebugModelPresentation implements IDebugModelPresentation { return DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_VARIABLE); } - public String getText(Object element) { // TODO Auto-generated method stub return null; @@ -101,20 +100,23 @@ public class PHPDebugModelPresentation implements IDebugModelPresentation { public IEditorInput getEditorInput(Object element) { if (element instanceof IFile) { - return new FileEditorInput((IFile)element); + return new FileEditorInput((IFile) element); } if (element instanceof ILineBreakpoint) { - return new FileEditorInput((IFile)((ILineBreakpoint)element).getMarker().getResource()); + return new FileEditorInput((IFile) ((ILineBreakpoint) element) + .getMarker().getResource()); } return null; } public String getEditorId(IEditorInput input, Object element) { - IEditorRegistry registry= PlatformUI.getWorkbench().getEditorRegistry(); - IEditorDescriptor descriptor= registry.getDefaultEditor(input.getName()); + IEditorRegistry registry = PlatformUI.getWorkbench() + .getEditorRegistry(); + IEditorDescriptor descriptor = registry.getDefaultEditor(input + .getName()); if (descriptor != null) return descriptor.getId(); - + return null; } diff --git a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/launching/PHPEnvironmentTab.java b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/launching/PHPEnvironmentTab.java index 9133de0..eb99160 100644 --- a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/launching/PHPEnvironmentTab.java +++ b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/launching/PHPEnvironmentTab.java @@ -419,8 +419,14 @@ public class PHPEnvironmentTab extends AbstractLaunchConfigurationTab { EnvironmentVariable existingVariable = (EnvironmentVariable) items[i] .getData(); if (existingVariable.getName().equals(name)) { - boolean overWrite = MessageDialog.openQuestion(getShell(),"Overwrite variable?", - MessageFormat.format("A variable named {0} already exists. Overwrite?",new String[] { name })); + boolean overWrite = MessageDialog + .openQuestion( + getShell(), + "Overwrite variable?", + MessageFormat + .format( + "A variable named {0} already exists. Overwrite?", + new String[] { name })); if (!overWrite) { return false; } @@ -756,8 +762,9 @@ public class PHPEnvironmentTab extends AbstractLaunchConfigurationTab { * * @see org.eclipse.debug.ui.ILaunchConfigurationTab#getImage() */ - public Image getImage() { - return XDebugUIPluginImages.get(XDebugUIPluginImages.IMG_EVIEW_ENVIROMENT_TAB); + public Image getImage() { + return XDebugUIPluginImages + .get(XDebugUIPluginImages.IMG_EVIEW_ENVIROMENT_TAB); } /* @@ -826,16 +833,19 @@ public class PHPEnvironmentTab extends AbstractLaunchConfigurationTab { // * @see org.eclipse.jface.window.Window#getInitialSize() // */ // protected Point getInitialSize() { - // Point size = super.getInitialSize(); - // return DialogSettingsHelper.getInitialSize(getDialogSettingsSectionName(), size); - // } - - // /* (non-Javadoc) - // * @see org.eclipse.jface.window.Window#close() - // */ - // public boolean close() { - // DialogSettingsHelper.persistShellGeometry(getShell(), getDialogSettingsSectionName()); - // return super.close(); - // } + // Point size = super.getInitialSize(); + // return + // DialogSettingsHelper.getInitialSize(getDialogSettingsSectionName(), + // size); + // } + + // /* (non-Javadoc) + // * @see org.eclipse.jface.window.Window#close() + // */ + // public boolean close() { + // DialogSettingsHelper.persistShellGeometry(getShell(), + // getDialogSettingsSectionName()); + // return super.close(); + // } } } diff --git a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/launching/PHPMainTab.java b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/launching/PHPMainTab.java index ba510c2..ed5f1b0 100644 --- a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/launching/PHPMainTab.java +++ b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/launching/PHPMainTab.java @@ -1,6 +1,7 @@ package net.sourceforge.phpeclipse.xdebug.ui.php.launching; import java.io.File; + import net.sourceforge.phpdt.internal.ui.PHPUiImages; import net.sourceforge.phpdt.internal.ui.util.PHPFileSelector; import net.sourceforge.phpdt.internal.ui.util.PHPProjectSelector; @@ -39,15 +40,22 @@ public class PHPMainTab extends AbstractLaunchConfigurationTab { // Project UI widgets protected Text fProjText; + protected Button fProjButton; // Main class UI widgets protected Text fMainText; + protected Button fSearchButton; + protected PHPProjectSelector projectSelector; + protected PHPFileSelector fileSelector; + private Button fUseDefaultInterpreterButton; + private Button fInterpreterButton; + private Text fInterpreterText; public PHPMainTab() { @@ -59,7 +67,8 @@ public class PHPMainTab extends AbstractLaunchConfigurationTab { Composite comp = new Composite(parent, SWT.NONE); setControl(comp); -// PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaDebugHelpContextIds.LAUNCH_CONFIGURATION_DIALOG_MAIN_TAB); + // PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), + // IJavaDebugHelpContextIds.LAUNCH_CONFIGURATION_DIALOG_MAIN_TAB); GridLayout topLayout = new GridLayout(); topLayout.verticalSpacing = 0; comp.setLayout(topLayout); @@ -74,12 +83,13 @@ public class PHPMainTab extends AbstractLaunchConfigurationTab { /** * Creates the widgets for specifying a main type. - * - * @param parent the parent composite + * + * @param parent + * the parent composite */ private void createProjectEditor(Composite parent) { - Font font= parent.getFont(); - Group group= new Group(parent, SWT.NONE); + Font font = parent.getFont(); + Group group = new Group(parent, SWT.NONE); group.setText("Project:"); GridData gd = new GridData(GridData.FILL_HORIZONTAL); group.setLayoutData(gd); @@ -89,7 +99,8 @@ public class PHPMainTab extends AbstractLaunchConfigurationTab { group.setFont(font); projectSelector = new PHPProjectSelector(group); - projectSelector.setBrowseDialogMessage("Choose the project containing the application entry point:"); + projectSelector + .setBrowseDialogMessage("Choose the project containing the application entry point:"); projectSelector.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); projectSelector.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent evt) { @@ -98,15 +109,15 @@ public class PHPMainTab extends AbstractLaunchConfigurationTab { }); } - /** * Creates the widgets for specifying a php file. - * - * @param parent the parent composite + * + * @param parent + * the parent composite */ private void createMainTypeEditor(Composite parent) { - Font font= parent.getFont(); - Group mainGroup= new Group(parent, SWT.NONE); + Font font = parent.getFont(); + Group mainGroup = new Group(parent, SWT.NONE); mainGroup.setText("File: "); GridData gd = new GridData(GridData.FILL_HORIZONTAL); mainGroup.setLayoutData(gd); @@ -116,7 +127,8 @@ public class PHPMainTab extends AbstractLaunchConfigurationTab { mainGroup.setFont(font); fileSelector = new PHPFileSelector(mainGroup, projectSelector); - fileSelector.setBrowseDialogMessage("Choose the PHP file that represents the application entry point:"); + fileSelector + .setBrowseDialogMessage("Choose the PHP file that represents the application entry point:"); fileSelector.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fileSelector.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent evt) { @@ -127,12 +139,13 @@ public class PHPMainTab extends AbstractLaunchConfigurationTab { /** * Creates the widgets for specifying debug settings. - * - * @param parent the parent composite + * + * @param parent + * the parent composite */ private void createInterpreterEditor(Composite parent) { - Font font= parent.getFont(); - Group interpreterGroup= new Group(parent, SWT.NONE); + Font font = parent.getFont(); + Group interpreterGroup = new Group(parent, SWT.NONE); interpreterGroup.setText("Interpreter: "); GridData gd = new GridData(GridData.FILL_HORIZONTAL); interpreterGroup.setLayoutData(gd); @@ -141,8 +154,8 @@ public class PHPMainTab extends AbstractLaunchConfigurationTab { interpreterGroup.setLayout(layout); interpreterGroup.setFont(font); - fInterpreterText= new Text(interpreterGroup, SWT.SINGLE | SWT.BORDER); - gd= new GridData(GridData.FILL_HORIZONTAL); + fInterpreterText = new Text(interpreterGroup, SWT.SINGLE | SWT.BORDER); + gd = new GridData(GridData.FILL_HORIZONTAL); fInterpreterText.setLayoutData(gd); fInterpreterText.setFont(font); fInterpreterText.addModifyListener(new ModifyListener() { @@ -151,24 +164,25 @@ public class PHPMainTab extends AbstractLaunchConfigurationTab { } }); - - fInterpreterButton= createPushButton(interpreterGroup,"Browse..", null); + fInterpreterButton = createPushButton(interpreterGroup, "Browse..", + null); fInterpreterButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { handleBrowseSellected(event); } }); - fUseDefaultInterpreterButton = new Button(interpreterGroup,SWT.CHECK); + fUseDefaultInterpreterButton = new Button(interpreterGroup, SWT.CHECK); fUseDefaultInterpreterButton.setText("Use default interpreter"); gd = new GridData(GridData.FILL_HORIZONTAL); fUseDefaultInterpreterButton.setLayoutData(gd); fUseDefaultInterpreterButton.setFont(font); - fUseDefaultInterpreterButton.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - handleDefaultSellected(event); - } - }); + fUseDefaultInterpreterButton + .addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent event) { + handleDefaultSellected(event); + } + }); } @@ -192,28 +206,27 @@ public class PHPMainTab extends AbstractLaunchConfigurationTab { return fUseDefaultInterpreterButton.getSelection(); } - - protected void handleDefaultSellected(SelectionEvent event) { setInterpreterTextEnabledState(); updateLaunchConfigurationDialog(); -// if (isDefaultInterpreter()) { -// fInterpreterText.setText("default Interpreter"); -// } + // if (isDefaultInterpreter()) { + // fInterpreterText.setText("default Interpreter"); + // } } protected void handleBrowseSellected(SelectionEvent event) { - FileDialog dlg=new FileDialog(getShell(),SWT.OPEN); - String fileName=dlg.open(); - if (fileName!=null) { + FileDialog dlg = new FileDialog(getShell(), SWT.OPEN); + String fileName = dlg.open(); + if (fileName != null) { fInterpreterText.setText(fileName); updateLaunchConfigurationDialog(); } } protected IProject getContext() { - IWorkbenchPage page= XDebugCorePlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage(); + IWorkbenchPage page = XDebugCorePlugin.getDefault().getWorkbench() + .getActiveWorkbenchWindow().getActivePage(); if (page != null) { ISelection selection = page.getSelection(); if (selection instanceof IStructuredSelection) { @@ -239,25 +252,29 @@ public class PHPMainTab extends AbstractLaunchConfigurationTab { public void setDefaults(ILaunchConfigurationWorkingCopy configuration) { IProject project = getContext(); if (project != null) - configuration.setAttribute(IXDebugConstants.ATTR_PHP_PROJECT, project.getName()); + configuration.setAttribute(IXDebugConstants.ATTR_PHP_PROJECT, + project.getName()); } - public void initializeFrom(ILaunchConfiguration configuration) { try { - String project = configuration.getAttribute(IXDebugConstants.ATTR_PHP_PROJECT, (String)null); + String project = configuration.getAttribute( + IXDebugConstants.ATTR_PHP_PROJECT, (String) null); if (project != null) { - projectSelector.setSelectionText(project); + projectSelector.setSelectionText(project); } - String file = configuration.getAttribute(IXDebugConstants.ATTR_PHP_FILE, (String)null); + String file = configuration.getAttribute( + IXDebugConstants.ATTR_PHP_FILE, (String) null); if (file != null) { fileSelector.setSelectionText(file); } - String interpreterFile=configuration.getAttribute(IXDebugConstants.ATTR_PHP_INTERPRETER, (String) null); - if(interpreterFile!=null) + String interpreterFile = configuration.getAttribute( + IXDebugConstants.ATTR_PHP_INTERPRETER, (String) null); + if (interpreterFile != null) fInterpreterText.setText(interpreterFile); - boolean selection=configuration.getAttribute(IXDebugConstants.ATTR_PHP_DEFAULT_INTERPRETER, true); + boolean selection = configuration.getAttribute( + IXDebugConstants.ATTR_PHP_DEFAULT_INTERPRETER, true); fUseDefaultInterpreterButton.setSelection(selection); setInterpreterTextEnabledState(); @@ -274,30 +291,36 @@ public class PHPMainTab extends AbstractLaunchConfigurationTab { configuration.setAttribute(IXDebugConstants.ATTR_PHP_PROJECT, project); IFile file = fileSelector.getSelection(); - configuration.setAttribute(IXDebugConstants.ATTR_PHP_FILE, file == null ? "" : file.getProjectRelativePath() - .toString()); - configuration.setAttribute(IXDebugConstants.ATTR_PHP_DEFAULT_INTERPRETER, this.fUseDefaultInterpreterButton.getSelection()); - configuration.setAttribute(IXDebugConstants.ATTR_PHP_INTERPRETER, this.fInterpreterText.getText()); + configuration.setAttribute(IXDebugConstants.ATTR_PHP_FILE, + file == null ? "" : file.getProjectRelativePath().toString()); + configuration.setAttribute( + IXDebugConstants.ATTR_PHP_DEFAULT_INTERPRETER, + this.fUseDefaultInterpreterButton.getSelection()); + configuration.setAttribute(IXDebugConstants.ATTR_PHP_INTERPRETER, + this.fInterpreterText.getText()); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.debug.ui.ILaunchConfigurationTab#isValid(org.eclipse.debug.core.ILaunchConfiguration) */ public boolean isValid(ILaunchConfiguration launchConfig) { setErrorMessage(null); - String projectName=projectSelector.getSelectionText().trim(); - IProject project=ResourcesPlugin.getWorkspace().getRoot().getProject(projectName); + String projectName = projectSelector.getSelectionText().trim(); + IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject( + projectName); if (!project.exists()) { setErrorMessage("Project does not exist"); return false; } - String fileName=fileSelector.getSelectionText().trim(); + String fileName = fileSelector.getSelectionText().trim(); if (fileName.equals("")) { setErrorMessage("No file selected."); return false; } - IFile file=project.getFile(fileName); + IFile file = project.getFile(fileName); if (!file.exists()) { setErrorMessage("File does not exist"); return false; diff --git a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/launching/PHPTabGroup.java b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/launching/PHPTabGroup.java index 74e0284..7f2c6e4 100644 --- a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/launching/PHPTabGroup.java +++ b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/launching/PHPTabGroup.java @@ -8,14 +8,9 @@ import org.eclipse.debug.ui.sourcelookup.SourceLookupTab; public class PHPTabGroup extends AbstractLaunchConfigurationTabGroup { - public void createTabs(ILaunchConfigurationDialog dialog, String mode) { - setTabs(new ILaunchConfigurationTab[] { - new PHPMainTab(), - new XDebugTab(), - new SourceLookupTab(), - new PHPEnvironmentTab(), - new CommonTab() - }); + setTabs(new ILaunchConfigurationTab[] { new PHPMainTab(), + new XDebugTab(), new SourceLookupTab(), + new PHPEnvironmentTab(), new CommonTab() }); } } diff --git a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/launching/XDebugTab.java b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/launching/XDebugTab.java index 70dd943..e3ed6ac 100644 --- a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/launching/XDebugTab.java +++ b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/launching/XDebugTab.java @@ -23,7 +23,9 @@ import org.eclipse.swt.widgets.Text; public class XDebugTab extends AbstractLaunchConfigurationTab { private Label fPortLabel; + private Button fUseDefaultPortButton; + private Text fPortText; public XDebugTab() { @@ -32,10 +34,11 @@ public class XDebugTab extends AbstractLaunchConfigurationTab { public void createControl(Composite parent) { Font font = parent.getFont(); - + Composite comp = new Composite(parent, SWT.NONE); setControl(comp); -// PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaDebugHelpContextIds.LAUNCH_CONFIGURATION_DIALOG_MAIN_TAB); + // PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), + // IJavaDebugHelpContextIds.LAUNCH_CONFIGURATION_DIALOG_MAIN_TAB); GridLayout topLayout = new GridLayout(); topLayout.verticalSpacing = 0; comp.setLayout(topLayout); @@ -43,27 +46,26 @@ public class XDebugTab extends AbstractLaunchConfigurationTab { createDebugPortEditor(comp); } - + private void createDebugPortEditor(Composite parent) { - Font font= parent.getFont(); - Group debugGroup= new Group(parent, SWT.NONE); - debugGroup.setText("Debug: "); + Font font = parent.getFont(); + Group debugGroup = new Group(parent, SWT.NONE); + debugGroup.setText("Debug: "); GridData gd = new GridData(GridData.FILL_HORIZONTAL); debugGroup.setLayoutData(gd); GridLayout layout = new GridLayout(); layout.numColumns = 2; debugGroup.setLayout(layout); debugGroup.setFont(font); - + fPortLabel = new Label(debugGroup, SWT.NONE); fPortLabel.setText("&DebugPort:"); -// gd = new GridData(GridData.BEGINNING); -// fPortLabel.setLayoutData(gd); + // gd = new GridData(GridData.BEGINNING); + // fPortLabel.setLayoutData(gd); fPortLabel.setFont(font); - fPortText = new Text(debugGroup, SWT.SINGLE | SWT.BORDER); - gd= new GridData(GridData.FILL_HORIZONTAL); + gd = new GridData(GridData.FILL_HORIZONTAL); fPortText.setLayoutData(gd); fPortText.setFont(font); fPortText.addModifyListener(new ModifyListener() { @@ -72,9 +74,7 @@ public class XDebugTab extends AbstractLaunchConfigurationTab { } }); - - - fUseDefaultPortButton = new Button(debugGroup,SWT.CHECK); + fUseDefaultPortButton = new Button(debugGroup, SWT.CHECK); fUseDefaultPortButton.setText("Use default interpreter"); gd = new GridData(GridData.FILL_HORIZONTAL); fUseDefaultPortButton.setLayoutData(gd); @@ -85,7 +85,7 @@ public class XDebugTab extends AbstractLaunchConfigurationTab { } }); } - + /** * Set the appropriate enabled state for the appletviewqer text widget. */ @@ -98,7 +98,7 @@ public class XDebugTab extends AbstractLaunchConfigurationTab { fPortLabel.setEnabled(true); } } - + /** * Returns whether the default appletviewer is to be used */ @@ -106,13 +106,11 @@ public class XDebugTab extends AbstractLaunchConfigurationTab { return fUseDefaultPortButton.getSelection(); } - protected void handleDefaultSellected(SelectionEvent event) { setDebugportEnabledState(); updateLaunchConfigurationDialog(); } - public void setDefaults(ILaunchConfigurationWorkingCopy configuration) { // TODO Auto-generated method stub @@ -120,36 +118,42 @@ public class XDebugTab extends AbstractLaunchConfigurationTab { public void initializeFrom(ILaunchConfiguration configuration) { try { - String portText=""+configuration.getAttribute(IXDebugConstants.ATTR_PHP_DEBUGPORT, 9000); + String portText = "" + + configuration.getAttribute( + IXDebugConstants.ATTR_PHP_DEBUGPORT, 9000); fPortText.setText(portText); - boolean selection=configuration.getAttribute(IXDebugConstants.ATTR_PHP_DEFAULT_DEBUGPORT, true); + boolean selection = configuration.getAttribute( + IXDebugConstants.ATTR_PHP_DEFAULT_DEBUGPORT, true); fUseDefaultPortButton.setSelection(selection); setDebugportEnabledState(); } catch (CoreException e) { setErrorMessage(e.getMessage()); } - } public void performApply(ILaunchConfigurationWorkingCopy configuration) { - configuration.setAttribute(IXDebugConstants.ATTR_PHP_DEFAULT_DEBUGPORT, this.fUseDefaultPortButton.getSelection()); + configuration.setAttribute(IXDebugConstants.ATTR_PHP_DEFAULT_DEBUGPORT, + this.fUseDefaultPortButton.getSelection()); try { - configuration.setAttribute(IXDebugConstants.ATTR_PHP_DEBUGPORT, Integer.parseInt(this.fPortText.getText().trim())); + configuration.setAttribute(IXDebugConstants.ATTR_PHP_DEBUGPORT, + Integer.parseInt(this.fPortText.getText().trim())); } catch (NumberFormatException nfe) { } } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.debug.ui.ILaunchConfigurationTab#isValid(org.eclipse.debug.core.ILaunchConfiguration) */ public boolean isValid(ILaunchConfiguration launchConfig) { setErrorMessage(null); try { Integer.parseInt(fPortText.getText().trim()); - } catch(NumberFormatException nfe) { - setErrorMessage("Debugport is not a valid integer"); + } catch (NumberFormatException nfe) { + setErrorMessage("Debugport is not a valid integer"); return false; } return true; diff --git a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/model/PHPBreakpointAdapterFactory.java b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/model/PHPBreakpointAdapterFactory.java index 1124273..7defbc5 100644 --- a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/model/PHPBreakpointAdapterFactory.java +++ b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/model/PHPBreakpointAdapterFactory.java @@ -13,7 +13,7 @@ public class PHPBreakpointAdapterFactory implements IAdapterFactory { } public Class[] getAdapterList() { - return new Class[]{IToggleBreakpointsTarget.class}; + return new Class[] { IToggleBreakpointsTarget.class }; } } diff --git a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/model/PHPLineBreakpointAdapter.java b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/model/PHPLineBreakpointAdapter.java index e2a5415..0138aee 100644 --- a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/model/PHPLineBreakpointAdapter.java +++ b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/php/model/PHPLineBreakpointAdapter.java @@ -18,26 +18,30 @@ public class PHPLineBreakpointAdapter implements IToggleBreakpointsTarget { public void toggleLineBreakpoints(IWorkbenchPart part, ISelection selection) throws CoreException { - IEditorPart editorPart = (IEditorPart)part; + IEditorPart editorPart = (IEditorPart) part; - IResource resource = (IResource) editorPart.getEditorInput().getAdapter(IResource.class); + IResource resource = (IResource) editorPart.getEditorInput() + .getAdapter(IResource.class); ITextSelection textSelection = (ITextSelection) selection; - int lineNumber = textSelection.getStartLine()+1; - IBreakpoint[] breakpoints = DebugPlugin.getDefault().getBreakpointManager().getBreakpoints(IXDebugConstants.ID_PHP_DEBUG_MODEL); + int lineNumber = textSelection.getStartLine() + 1; + IBreakpoint[] breakpoints = DebugPlugin.getDefault() + .getBreakpointManager().getBreakpoints( + IXDebugConstants.ID_PHP_DEBUG_MODEL); for (int i = 0; i < breakpoints.length; i++) { IBreakpoint breakpoint = breakpoints[i]; if (resource.equals(breakpoint.getMarker().getResource())) { - if (((ILineBreakpoint)breakpoint).getLineNumber() == (lineNumber )) { - // remove + if (((ILineBreakpoint) breakpoint).getLineNumber() == (lineNumber)) { + // remove breakpoint.delete(); return; } } } - // create line breakpoint (doc line numbers start at 0) - XDebugLineBreakpoint lineBreakpoint = new XDebugLineBreakpoint(resource, lineNumber); -// DebugPlugin.getDefault().getBreakpointManager().addBreakpoint(lineBreakpoint); - + // create line breakpoint (doc line numbers start at 0) + XDebugLineBreakpoint lineBreakpoint = new XDebugLineBreakpoint( + resource, lineNumber); + // DebugPlugin.getDefault().getBreakpointManager().addBreakpoint(lineBreakpoint); + } public boolean canToggleLineBreakpoints(IWorkbenchPart part, diff --git a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/preference/XDebugPreferencePage.java b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/preference/XDebugPreferencePage.java index 58580b8..50435bf 100644 --- a/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/preference/XDebugPreferencePage.java +++ b/net.sourceforge.phpeclipse.xdebug.ui/src/net/sourceforge/phpeclipse/xdebug/ui/preference/XDebugPreferencePage.java @@ -11,22 +11,25 @@ import org.eclipse.jface.preference.IntegerFieldEditor; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; - public class XDebugPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { /* Preference page for the default XDebug-Settings */ - + public XDebugPreferencePage() { super(FieldEditorPreferencePage.GRID); // Set the preference store for the preference page. - IPreferenceStore store = - XDebugCorePlugin.getDefault().getPreferenceStore(); - store.setDefault(IXDebugPreferenceConstants.DEBUGPORT_PREFERENCE,IXDebugPreferenceConstants.DEFAULT_DEBUGPORT); - // get the default form the externalToolsPlugin - String interpreter=ExternalToolsPlugin.getDefault().getPreferenceStore().getString(ExternalToolsPlugin.PHP_RUN_PREF); - store.setDefault(IXDebugPreferenceConstants.PHP_INTERPRETER_PREFERENCE,interpreter); + IPreferenceStore store = XDebugCorePlugin.getDefault() + .getPreferenceStore(); + store.setDefault(IXDebugPreferenceConstants.DEBUGPORT_PREFERENCE, + IXDebugPreferenceConstants.DEFAULT_DEBUGPORT); + // get the default form the externalToolsPlugin + String interpreter = ExternalToolsPlugin.getDefault() + .getPreferenceStore().getString( + ExternalToolsPlugin.PHP_RUN_PREF); + store.setDefault(IXDebugPreferenceConstants.PHP_INTERPRETER_PREFERENCE, + interpreter); setPreferenceStore(store); } @@ -35,18 +38,19 @@ public class XDebugPreferencePage extends FieldEditorPreferencePage implements } protected void createFieldEditors() { - IntegerFieldEditor debugPort = new IntegerFieldEditor(IXDebugPreferenceConstants.DEBUGPORT_PREFERENCE, "&Debugport:", getFieldEditorParent(),5); - debugPort.setValidRange(1025,65535); + IntegerFieldEditor debugPort = new IntegerFieldEditor( + IXDebugPreferenceConstants.DEBUGPORT_PREFERENCE, "&Debugport:", + getFieldEditorParent(), 5); + debugPort.setValidRange(1025, 65535); debugPort.setErrorMessage("Debugport must be between 1024 and 65536"); addField(debugPort); - - FileFieldEditor phpInterpreter = new FileFieldEditor(IXDebugPreferenceConstants.PHP_INTERPRETER_PREFERENCE, "PHP &Interpreter:",true,getFieldEditorParent()); - phpInterpreter.setErrorMessage("File not found"); - addField(phpInterpreter); - - } - + FileFieldEditor phpInterpreter = new FileFieldEditor( + IXDebugPreferenceConstants.PHP_INTERPRETER_PREFERENCE, + "PHP &Interpreter:", true, getFieldEditorParent()); + phpInterpreter.setErrorMessage("File not found"); + addField(phpInterpreter); + } } diff --git a/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/internal/model/XMLDocument.java b/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/internal/model/XMLDocument.java index 7fb5ab3..c0b5680 100644 --- a/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/internal/model/XMLDocument.java +++ b/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/internal/model/XMLDocument.java @@ -8,7 +8,7 @@ * Contributors: * Christopher Lenz - initial API * - * $Id: XMLDocument.java,v 1.1 2004-09-02 18:26:55 jsurfer Exp $ + * $Id: XMLDocument.java,v 1.2 2006-10-21 23:13:43 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.core.internal.model; @@ -26,124 +26,135 @@ import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentListener; /** - * + * */ -public class XMLDocument extends SourceReference implements IXMLDocument, IDocumentListener { - // Instance Variables ------------------------------------------------------ - - private IXMLElement root; - - private String systemId; - - private Object dirtyLock = new Object(); - - private boolean dirty = true; - - // Constructors ------------------------------------------------------------ - - public XMLDocument(IDocument document, String systemId) { - super(document, 0, document.getLength()); - this.systemId = systemId; - } - - // IXMLDocument Implementation --------------------------------------------- - - /* - * @see IXMLDocument#getRoot() - */ - public IXMLElement getRoot() { - return root; - } - - /* - * @see net.sourceforge.phpeclipse.xml.core.model.IXMLDocument#getSystemId() - */ - public String getSystemId() { - return systemId; - } - - /* - * @see IStyleSheet#reconcile(IProblemCollector) - */ - public void reconcile(IProblemCollector problemCollector, IFile file) { - synchronized (dirtyLock) { - if (!dirty) { - return; - } - dirty = false; - } - - synchronized (this) { - boolean doParse = false; - root = null; - if (file != null) { - String filename = file.getLocation().toString(); - int len = filename.length(); - if (len >= 4) { - if ((filename.charAt(len - 1) != 'l' && filename.charAt(len - 1) != 'L') - || (filename.charAt(len - 2) != 'p' && filename.charAt(len - 2) != 'P') - || (filename.charAt(len - 3) != 't' && filename.charAt(len - 3) != 'T') - || (filename.charAt(len - 4) != '.')) { - if ((filename.charAt(len - 1) != 'm' && filename.charAt(len - 1) != 'M') - || (filename.charAt(len - 2) != 't' && filename.charAt(len - 2) != 'T') - || (filename.charAt(len - 3) != 'h' && filename.charAt(len - 3) != 'H') - || (filename.charAt(len - 4) != '.')) { - if (len >= 5) { - if ((filename.charAt(len - 1) != 'l' && filename.charAt(len - 1) != 'L') - || (filename.charAt(len - 2) != 'm' && filename.charAt(len - 2) != 'M') - || (filename.charAt(len - 3) != 't' && filename.charAt(len - 3) != 'T') - || (filename.charAt(len - 4) != 'h' && filename.charAt(len - 4) != 'H') - || (filename.charAt(len - 5) != '.')) { - doParse = true; - } - } - } - } - } else { - doParse = true; - } - } - if (doParse) { - IXMLParser parser = new XMLParser(); - parser.setProblemCollector(problemCollector); - parser.setSource(getDocument()); - parser.setSystemId(systemId); - IXMLDocument model = parser.parse(); - if (model != null) { - root = model.getRoot(); - } - } - } - } - - // IDocumentListener Implementation ---------------------------------------- - - /* - * @see IDocumentListener#documentAboutToBeChanged(DocumentEvent) - */ - public void documentAboutToBeChanged(DocumentEvent event) { - // do nothing - } - - /* - * @see IDocumentListener#documentChanged(DocumentEvent) - */ - public void documentChanged(DocumentEvent event) { - synchronized (dirtyLock) { - dirty = true; - } - } - - // Public Methods ---------------------------------------------------------- - - /** - * Sets the root element. - * - * @param root - * the root element to set - */ - public void setRoot(IXMLElement root) { - this.root = root; - } +public class XMLDocument extends SourceReference implements IXMLDocument, + IDocumentListener { + // Instance Variables ------------------------------------------------------ + + private IXMLElement root; + + private String systemId; + + private Object dirtyLock = new Object(); + + private boolean dirty = true; + + // Constructors ------------------------------------------------------------ + + public XMLDocument(IDocument document, String systemId) { + super(document, 0, document.getLength()); + this.systemId = systemId; + } + + // IXMLDocument Implementation --------------------------------------------- + + /* + * @see IXMLDocument#getRoot() + */ + public IXMLElement getRoot() { + return root; + } + + /* + * @see net.sourceforge.phpeclipse.xml.core.model.IXMLDocument#getSystemId() + */ + public String getSystemId() { + return systemId; + } + + /* + * @see IStyleSheet#reconcile(IProblemCollector) + */ + public void reconcile(IProblemCollector problemCollector, IFile file) { + synchronized (dirtyLock) { + if (!dirty) { + return; + } + dirty = false; + } + + synchronized (this) { + boolean doParse = false; + root = null; + if (file != null) { + String filename = file.getLocation().toString(); + int len = filename.length(); + if (len >= 4) { + if ((filename.charAt(len - 1) != 'l' && filename + .charAt(len - 1) != 'L') + || (filename.charAt(len - 2) != 'p' && filename + .charAt(len - 2) != 'P') + || (filename.charAt(len - 3) != 't' && filename + .charAt(len - 3) != 'T') + || (filename.charAt(len - 4) != '.')) { + if ((filename.charAt(len - 1) != 'm' && filename + .charAt(len - 1) != 'M') + || (filename.charAt(len - 2) != 't' && filename + .charAt(len - 2) != 'T') + || (filename.charAt(len - 3) != 'h' && filename + .charAt(len - 3) != 'H') + || (filename.charAt(len - 4) != '.')) { + if (len >= 5) { + if ((filename.charAt(len - 1) != 'l' && filename + .charAt(len - 1) != 'L') + || (filename.charAt(len - 2) != 'm' && filename + .charAt(len - 2) != 'M') + || (filename.charAt(len - 3) != 't' && filename + .charAt(len - 3) != 'T') + || (filename.charAt(len - 4) != 'h' && filename + .charAt(len - 4) != 'H') + || (filename.charAt(len - 5) != '.')) { + doParse = true; + } + } + } + } + } else { + doParse = true; + } + } + if (doParse) { + IXMLParser parser = new XMLParser(); + parser.setProblemCollector(problemCollector); + parser.setSource(getDocument()); + parser.setSystemId(systemId); + IXMLDocument model = parser.parse(); + if (model != null) { + root = model.getRoot(); + } + } + } + } + + // IDocumentListener Implementation ---------------------------------------- + + /* + * @see IDocumentListener#documentAboutToBeChanged(DocumentEvent) + */ + public void documentAboutToBeChanged(DocumentEvent event) { + // do nothing + } + + /* + * @see IDocumentListener#documentChanged(DocumentEvent) + */ + public void documentChanged(DocumentEvent event) { + synchronized (dirtyLock) { + dirty = true; + } + } + + // Public Methods ---------------------------------------------------------- + + /** + * Sets the root element. + * + * @param root + * the root element to set + */ + public void setRoot(IXMLElement root) { + this.root = root; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/internal/model/XMLElement.java b/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/internal/model/XMLElement.java index 2200619..3499412 100644 --- a/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/internal/model/XMLElement.java +++ b/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/internal/model/XMLElement.java @@ -8,7 +8,7 @@ * Contributors: * Christopher Lenz - initial API * - * $Id: XMLElement.java,v 1.1 2004-09-02 18:26:55 jsurfer Exp $ + * $Id: XMLElement.java,v 1.2 2006-10-21 23:13:43 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.core.internal.model; @@ -31,7 +31,9 @@ public class XMLElement extends SourceReference implements IXMLElement { private List children; private String localName; + private String namespaceURI; + private String prefix; private IXMLElement parent; @@ -50,41 +52,42 @@ public class XMLElement extends SourceReference implements IXMLElement { super(document, offset, length); } - // IXMLElement Implementation ------------------------------------------------- + // IXMLElement Implementation + // ------------------------------------------------- - /* + /* * @see IXMLElement#getChildren() */ public IXMLElement[] getChildren() { if (children != null) { - return (IXMLElement[]) children.toArray( - new IXMLElement[children.size()]); + return (IXMLElement[]) children.toArray(new IXMLElement[children + .size()]); } return new IXMLElement[0]; } - /* + /* * @see IXMLElement#getLocalName() */ public String getLocalName() { return localName; } - /* + /* * @see IXMLElement#getNamespaceURI() */ public String getNamespaceURI() { return namespaceURI; } - /* + /* * @see IXMLElement#getPrefix() */ public String getPrefix() { return prefix; } - /* + /* * @see IXMLElement#getParent() */ public IXMLElement getParent() { diff --git a/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/internal/parser/DefaultProblem.java b/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/internal/parser/DefaultProblem.java index bb933e1..39ca7e5 100644 --- a/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/internal/parser/DefaultProblem.java +++ b/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/internal/parser/DefaultProblem.java @@ -8,7 +8,7 @@ * Contributors: * Christopher Lenz - initial API and implementation * - * $Id: DefaultProblem.java,v 1.1 2004-09-02 18:26:55 jsurfer Exp $ + * $Id: DefaultProblem.java,v 1.2 2006-10-21 23:13:43 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.core.internal.parser; @@ -20,9 +20,13 @@ public class DefaultProblem implements IProblem { // Instance Variables ------------------------------------------------------ private String message; + private int sourceStart; + private int sourceEnd; + private int sourceLineNumber; + private boolean error; // Constructors ------------------------------------------------------------ diff --git a/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/internal/parser/XMLParser.java b/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/internal/parser/XMLParser.java index 81a0e64..0428da4 100644 --- a/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/internal/parser/XMLParser.java +++ b/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/internal/parser/XMLParser.java @@ -8,7 +8,7 @@ * Contributors: * Christopher Lenz - initial API * - * $Id: XMLParser.java,v 1.1 2004-09-02 18:26:55 jsurfer Exp $ + * $Id: XMLParser.java,v 1.2 2006-10-21 23:13:43 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.core.internal.parser; @@ -39,13 +39,12 @@ import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; - /** * SAX-based default implementation of the {@link IXMLParser} interface. * * TODO This implementation doesn't do error recovery, as SAX doesn't allow it. - * Maybe we partition the document and parse individual fragments so that - * errors can be isolated to their source + * Maybe we partition the document and parse individual fragments so that errors + * can be isolated to their source */ public class XMLParser implements IXMLParser { /** @@ -58,7 +57,7 @@ public class XMLParser implements IXMLParser { XMLDocument document; /** - * The current top element. That is the element that has been most + * The current top element. That is the element that has been most * recently opened by a start tag. */ private XMLElement top; @@ -83,11 +82,11 @@ public class XMLParser implements IXMLParser { } /* - * @see org.xml.sax.ContentHandler#startElement(String, String, String, Attributes) + * @see org.xml.sax.ContentHandler#startElement(String, String, String, + * Attributes) */ - public void startElement( - String namespaceURI, String localName, String qName, Attributes atts - ) throws SAXException { + public void startElement(String namespaceURI, String localName, + String qName, Attributes atts) throws SAXException { if (System.currentTimeMillis() > timeout) { throw new SAXException("timeout"); } @@ -103,9 +102,8 @@ public class XMLParser implements IXMLParser { } } - int offset = computeOffset(newTop, - locator.getLineNumber(), - locator.getColumnNumber()); + int offset = computeOffset(newTop, locator.getLineNumber(), locator + .getColumnNumber()); if (offset >= 0) { newTop.setSourceRegion(offset, 0); @@ -119,12 +117,10 @@ public class XMLParser implements IXMLParser { /* * @see org.xml.sax.ContentHandler#endElement(String, String, String) */ - public void endElement( - String namespaceURI, String localName, String qName - ) throws SAXException { - int length = computeLength(top, - locator.getLineNumber(), - locator.getColumnNumber()); + public void endElement(String namespaceURI, String localName, + String qName) throws SAXException { + int length = computeLength(top, locator.getLineNumber(), locator + .getColumnNumber()); if (length >= 0) { top.setSourceRegion(top.getSourceRegion().getOffset(), length); @@ -136,11 +132,11 @@ public class XMLParser implements IXMLParser { } else { // this is the root element document.setRoot(top); - } + } top = previousTop; } - /* + /* * @see org.xml.sax.ErrorHandler#error(SAXParseException) */ public void error(SAXParseException e) throws SAXException { @@ -149,7 +145,7 @@ public class XMLParser implements IXMLParser { } } - /* + /* * @see org.xml.sax.ErrorHandler#fatalError(SAXParseException) */ public void fatalError(SAXParseException e) throws SAXException { @@ -158,7 +154,7 @@ public class XMLParser implements IXMLParser { } } - /* + /* * @see org.xml.sax.ErrorHandler#warning(SAXParseException) */ public void warning(SAXParseException e) throws SAXException { @@ -182,8 +178,10 @@ public class XMLParser implements IXMLParser { * * TODO Limit the location to the current top element * - * @param e the SAX parse exception - * @param error whether the problem is an error or a warning + * @param e + * the SAX parse exception + * @param error + * whether the problem is an error or a warning * @return the created problem object */ private IProblem createProblem(SAXParseException e, boolean error) { @@ -204,8 +202,8 @@ public class XMLParser implements IXMLParser { ble.printStackTrace(); } - return new DefaultProblem(e.getLocalizedMessage(), - offset, offset + length, line, error); + return new DefaultProblem(e.getLocalizedMessage(), offset, offset + + length, line, error); } } @@ -262,21 +260,21 @@ public class XMLParser implements IXMLParser { return null; } - /* + /* * @see IProblemReporter#setProblemCollector(IProblemCollector) */ public void setProblemCollector(IProblemCollector problemCollector) { this.problemCollector = problemCollector; } - /* + /* * @see IXMLParser#setSource(IDocument) */ public void setSource(IDocument source) { this.source = source; } - /* + /* * @see IXMLParser#setSystemId(String) */ public void setSystemId(String systemId) { @@ -337,8 +335,8 @@ public class XMLParser implements IXMLParser { if (column <= 0) { offset = getOffset(line, 0); int lastCharColumn = getLastCharColumn(line); - String lineText = source - .get(source.getLineOffset(line - 1), lastCharColumn); + String lineText = source.get(source.getLineOffset(line - 1), + lastCharColumn); String startTag = getStartTag(element); int lastIndex = lineText.indexOf(startTag); @@ -364,9 +362,8 @@ public class XMLParser implements IXMLParser { return -1; } - private IRegion findStringBackward( - int startOffset, String string - ) throws BadLocationException { + private IRegion findStringBackward(int startOffset, String string) + throws BadLocationException { int offset = startOffset; int length = string.length(); @@ -382,9 +379,8 @@ public class XMLParser implements IXMLParser { return null; } - private IRegion findStringForward( - int startOffset, String string - ) throws BadLocationException { + private IRegion findStringForward(int startOffset, String string) + throws BadLocationException { int offset = startOffset; int length = string.length(); @@ -403,9 +399,10 @@ public class XMLParser implements IXMLParser { /** * Given an XML element, this method reconstructs the corresponding end tag - * of the element, including the namespace prefix if there was one. + * of the element, including the namespace prefix if there was one. * - * @param element the XML element for which the end tag should be contructed + * @param element + * the XML element for which the end tag should be contructed * @return the end tag as string */ private String getEndTag(IXMLElement element) { @@ -422,11 +419,11 @@ public class XMLParser implements IXMLParser { /** * Reconstructs and returns the start tag corresponding to the given XML - * element, excluding any attribute specifications or the closing + * element, excluding any attribute specifications or the closing * > character. * - * @param element the XML element for which the start tag should be - * constructed + * @param element + * the XML element for which the start tag should be constructed * @return the start tag as string, excluding everything after the tag name * itself */ @@ -451,8 +448,8 @@ public class XMLParser implements IXMLParser { int getLastCharColumn(int line) throws BadLocationException { String lineDelimiter = source.getLineDelimiter(line - 1); - int lineDelimiterLength = (lineDelimiter != null) - ? lineDelimiter.length() : 0; + int lineDelimiterLength = (lineDelimiter != null) ? lineDelimiter + .length() : 0; return source.getLineLength(line - 1) - lineDelimiterLength; } diff --git a/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/parser/IProblem.java b/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/parser/IProblem.java index 89e0c2b..cb3cc0b 100644 --- a/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/parser/IProblem.java +++ b/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/parser/IProblem.java @@ -8,7 +8,7 @@ * Contributors: * Christopher Lenz - initial API * - * $Id: IProblem.java,v 1.1 2004-09-02 18:26:55 jsurfer Exp $ + * $Id: IProblem.java,v 1.2 2006-10-21 23:13:43 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.core.parser; @@ -50,16 +50,16 @@ public interface IProblem { /** * Returns whether the problem is an error. * - * @return true if the problem is an error, false - * otherwise + * @return true if the problem is an error, + * false otherwise */ boolean isError(); /** * Returns whether the problem is a warning. * - * @return true if the problem is a warning, false - * otherwise + * @return true if the problem is a warning, + * false otherwise */ boolean isWarning(); diff --git a/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/parser/IProblemCollector.java b/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/parser/IProblemCollector.java index 72b88fa..0956439 100644 --- a/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/parser/IProblemCollector.java +++ b/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/parser/IProblemCollector.java @@ -8,7 +8,7 @@ * Contributors: * Christopher Lenz - initial API * - * $Id: IProblemCollector.java,v 1.1 2004-09-02 18:26:55 jsurfer Exp $ + * $Id: IProblemCollector.java,v 1.2 2006-10-21 23:13:43 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.core.parser; @@ -21,7 +21,8 @@ public interface IProblemCollector { /** * Notification of an error or warning. * - * @param problem the discovered problem + * @param problem + * the discovered problem */ void addProblem(IProblem problem); diff --git a/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/parser/IProblemReporter.java b/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/parser/IProblemReporter.java index 6d74ec8..7e61474 100644 --- a/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/parser/IProblemReporter.java +++ b/net.sourceforge.phpeclipse.xml.core/src/net/sourceforge/phpeclipse/xml/core/parser/IProblemReporter.java @@ -8,7 +8,7 @@ * Contributors: * Christopher Lenz - initial API * - * $Id: IProblemReporter.java,v 1.1 2004-09-02 18:26:55 jsurfer Exp $ + * $Id: IProblemReporter.java,v 1.2 2006-10-21 23:13:43 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.core.parser; @@ -21,7 +21,8 @@ public interface IProblemReporter { /** * Sets the problem collector that should be used by the reporter. * - * @param problemCollector the problem collector to use + * @param problemCollector + * the problem collector to use */ void setProblemCollector(IProblemCollector problemCollector); diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/XMLPlugin.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/XMLPlugin.java index bbbf329..d886c5a 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/XMLPlugin.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/XMLPlugin.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: XMLPlugin.java,v 1.1 2004-09-02 18:28:04 jsurfer Exp $ + * $Id: XMLPlugin.java,v 1.2 2006-10-21 23:14:13 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui; @@ -30,7 +30,7 @@ import org.osgi.framework.BundleContext; */ public class XMLPlugin extends AbstractUIPlugin { public static final String ICON_ELEMENT = "element_obj.gif"; //$NON-NLS-1$ - + // The shared instance. private static XMLPlugin plugin; @@ -38,6 +38,7 @@ public class XMLPlugin extends AbstractUIPlugin { private ResourceBundle resources; private XMLTextTools xmlTextTools; + private DTDTextTools dtdTextTools; /** @@ -47,8 +48,8 @@ public class XMLPlugin extends AbstractUIPlugin { plugin = this; try { - resources = ResourceBundle.getBundle( - "net.sourceforge.phpeclipse.xml.ui.XMLPluginResources"); //$NON-NLS-1$ + resources = ResourceBundle + .getBundle("net.sourceforge.phpeclipse.xml.ui.XMLPluginResources"); //$NON-NLS-1$ } catch (MissingResourceException x) { } } @@ -130,8 +131,9 @@ public class XMLPlugin extends AbstractUIPlugin { * Returns an image descriptor for the image corresponding to the specified * key (which is the name of the image file). * - * @param key The key of the image - * @return The descriptor for the requested image, or null if + * @param key + * The key of the image + * @return The descriptor for the requested image, or null if * the image could not be found */ private ImageDescriptor getImageDescriptor(String key) { @@ -142,7 +144,5 @@ public class XMLPlugin extends AbstractUIPlugin { return null; } } - - } diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/compare/DTDMergeViewer.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/compare/DTDMergeViewer.java index ac2567d..a833e92 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/compare/DTDMergeViewer.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/compare/DTDMergeViewer.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: DTDMergeViewer.java,v 1.2 2005-05-06 00:55:42 stefanbjarni Exp $ + * $Id: DTDMergeViewer.java,v 1.3 2006-10-21 23:14:13 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.compare; @@ -42,7 +42,7 @@ public class DTDMergeViewer extends TextMergeViewer { private IPreferenceStore preferenceStore; /** - * The listener for changes to the preference store. + * The listener for changes to the preference store. */ private IPropertyChangeListener propertyChangeListener; @@ -52,11 +52,11 @@ public class DTDMergeViewer extends TextMergeViewer { private DTDTextTools textTools; /* - * @see TextMergeViewer#TextMergeViewer(Composite, int, CompareConfiguration) + * @see TextMergeViewer#TextMergeViewer(Composite, int, + * CompareConfiguration) */ - public DTDMergeViewer( - Composite parent, int style, CompareConfiguration configuration - ) { + public DTDMergeViewer(Composite parent, int style, + CompareConfiguration configuration) { super(parent, style, configuration); } @@ -109,7 +109,7 @@ public class DTDMergeViewer extends TextMergeViewer { if (propertyChangeListener != null) { if (preferenceStore != null) { preferenceStore - .removePropertyChangeListener(propertyChangeListener); + .removePropertyChangeListener(propertyChangeListener); } propertyChangeListener = null; @@ -121,10 +121,9 @@ public class DTDMergeViewer extends TextMergeViewer { protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { String p = event.getProperty(); - if (p.equals(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND) || - p.equals(AbstractTextEditor - .PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT) - ) { + if (p.equals(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND) + || p + .equals(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) { updateBackgroundColor(); } else if (textTools.affectsBehavior(event)) { invalidateTextPresentation(); @@ -132,14 +131,13 @@ public class DTDMergeViewer extends TextMergeViewer { } private void updateBackgroundColor() { - boolean defaultBackgroundColor = preferenceStore.getBoolean( - AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT); + boolean defaultBackgroundColor = preferenceStore + .getBoolean(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT); if (defaultBackgroundColor) { setBackgroundColor(null); } else { - RGB backgroundColor = PreferenceConverter - .getColor(preferenceStore, + RGB backgroundColor = PreferenceConverter.getColor(preferenceStore, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND); setBackgroundColor(backgroundColor); } diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/compare/XMLMergeViewer.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/compare/XMLMergeViewer.java index f4f309c..7947a8e 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/compare/XMLMergeViewer.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/compare/XMLMergeViewer.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: XMLMergeViewer.java,v 1.2 2005-05-06 00:55:42 stefanbjarni Exp $ + * $Id: XMLMergeViewer.java,v 1.3 2006-10-21 23:14:13 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.compare; @@ -109,8 +109,8 @@ public class XMLMergeViewer extends TextMergeViewer { protected void handleDispose(DisposeEvent event) { if (propertyChangeListener != null) { if (preferenceStore != null) { - preferenceStore.removePropertyChangeListener( - propertyChangeListener); + preferenceStore + .removePropertyChangeListener(propertyChangeListener); } propertyChangeListener = null; @@ -123,7 +123,8 @@ public class XMLMergeViewer extends TextMergeViewer { String p = event.getProperty(); if (p.equals(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND) - || p.equals(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) { + || p + .equals(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) { updateBackgroundColor(); } else if (textTools.affectsBehavior(event)) { invalidateTextPresentation(); @@ -131,8 +132,8 @@ public class XMLMergeViewer extends TextMergeViewer { } private void updateBackgroundColor() { - boolean defaultBackgroundColor = preferenceStore.getBoolean( - AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT); + boolean defaultBackgroundColor = preferenceStore + .getBoolean(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT); if (defaultBackgroundColor) { setBackgroundColor(null); diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/DTDEditor.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/DTDEditor.java index 953cdbf..43f76d7 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/DTDEditor.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/DTDEditor.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: DTDEditor.java,v 1.2 2005-05-06 00:55:42 stefanbjarni Exp $ + * $Id: DTDEditor.java,v 1.3 2006-10-21 23:14:14 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.editor; @@ -24,7 +24,6 @@ import org.eclipse.ui.editors.text.TextEditor; import org.eclipse.ui.texteditor.ContentAssistAction; import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; - /** * DTD Editor. * @@ -52,23 +51,24 @@ public class DTDEditor extends TextEditor { protected boolean affectsTextPresentation(PropertyChangeEvent event) { return XMLPlugin.getDefault().getDTDTextTools().affectsBehavior(event); } + protected void createActions() { super.createActions(); - IAction action = new ContentAssistAction(XMLEditorMessages.getResourceBundle(), - "ContentAssistProposal.", this); //$NON-NLS-1$ - action - .setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); - setAction("ContentAssistProposal", action); //$NON-NLS-1$ - markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$ - -// IAction action= new TextOperationAction( -// TemplateMessages.getResourceBundle(), -// "Editor." + TEMPLATE_PROPOSALS + ".", //$NON-NLS-1$ //$NON-NLS-2$ -// this, -// ISourceViewer.CONTENTASSIST_PROPOSALS); -// action.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); -// setAction(TEMPLATE_PROPOSALS, action); -// markAsStateDependentAction(TEMPLATE_PROPOSALS, true); + IAction action = new ContentAssistAction(XMLEditorMessages + .getResourceBundle(), "ContentAssistProposal.", this); //$NON-NLS-1$ + action + .setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); + setAction("ContentAssistProposal", action); //$NON-NLS-1$ + markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$ + + // IAction action= new TextOperationAction( + // TemplateMessages.getResourceBundle(), + // "Editor." + TEMPLATE_PROPOSALS + ".", //$NON-NLS-1$ //$NON-NLS-2$ + // this, + // ISourceViewer.CONTENTASSIST_PROPOSALS); + // action.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); + // setAction(TEMPLATE_PROPOSALS, action); + // markAsStateDependentAction(TEMPLATE_PROPOSALS, true); } } diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLDocumentProvider.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLDocumentProvider.java index 5d751b7..999fd08 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLDocumentProvider.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLDocumentProvider.java @@ -8,7 +8,7 @@ * Contributors: * Christopher Lenz - initial API and implementation * - * $Id: XMLDocumentProvider.java,v 1.2 2005-05-06 00:55:42 stefanbjarni Exp $ + * $Id: XMLDocumentProvider.java,v 1.3 2006-10-21 23:14:14 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.editor; @@ -23,16 +23,14 @@ import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentListener; import org.eclipse.ui.editors.text.TextFileDocumentProvider; - /** * Document provider for XML files. * * TODO Merge the encoding detection support from I18NDocumentProvider and - * AbstractDocumentProvider into this class + * AbstractDocumentProvider into this class * - * TODO This class currently doubles as a model manager which will need to be - * moved into core at some point, and would make this class pretty much - * useless + * TODO This class currently doubles as a model manager which will need to be + * moved into core at some point, and would make this class pretty much useless */ public class XMLDocumentProvider extends TextFileDocumentProvider { @@ -80,7 +78,8 @@ public class XMLDocumentProvider extends TextFileDocumentProvider { } /* - * @see TextFileDocumentProvider#disposeFileInfo(Object, TextFileDocumentProvider.FileInfo) + * @see TextFileDocumentProvider#disposeFileInfo(Object, + * TextFileDocumentProvider.FileInfo) */ protected void disposeFileInfo(Object element, FileInfo info) { if (info instanceof XMLFileInfo) { @@ -88,8 +87,8 @@ public class XMLDocumentProvider extends TextFileDocumentProvider { if (document != null) { IXMLDocument xmlDocument = ((XMLFileInfo) info).xmlDocument; if (xmlDocument instanceof IDocumentListener) { - document.removeDocumentListener( - (IDocumentListener) xmlDocument); + document + .removeDocumentListener((IDocumentListener) xmlDocument); } } } @@ -100,11 +99,13 @@ public class XMLDocumentProvider extends TextFileDocumentProvider { // Public Methods ---------------------------------------------------------- /** - * Creates the XML document model object corresponding to the specified + * Creates the XML document model object corresponding to the specified * document. * - * @param document the document to parse - * @param systemId the system ID of the document + * @param document + * the document to parse + * @param systemId + * the system ID of the document * @return the document model object */ public IXMLDocument createModel(IDocument document, String systemId) { @@ -114,7 +115,8 @@ public class XMLDocumentProvider extends TextFileDocumentProvider { /** * Returns the XML document model associated with the specified element. * - * @param element the element + * @param element + * the element * @return the document model associated with the element */ public IXMLDocument getModel(Object element) { diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLDocumentSetupParticipant.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLDocumentSetupParticipant.java index 3da7597..40fa9a4 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLDocumentSetupParticipant.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLDocumentSetupParticipant.java @@ -8,7 +8,7 @@ * Contributors: * Christopher Lenz - initial implementation * - * $Id: XMLDocumentSetupParticipant.java,v 1.2 2005-05-06 00:55:42 stefanbjarni Exp $ + * $Id: XMLDocumentSetupParticipant.java,v 1.3 2006-10-21 23:14:14 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.editor; @@ -25,7 +25,7 @@ import org.eclipse.jface.text.IDocumentPartitioner; */ public class XMLDocumentSetupParticipant implements IDocumentSetupParticipant { - /* + /* * @see IDocumentSetupParticipant#setup(IDocument) */ public void setup(IDocument document) { diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLEditor.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLEditor.java index 282e5db..bd096c2 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLEditor.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLEditor.java @@ -9,7 +9,7 @@ * Igor Malinin - initial contribution * Christopher Lenz - integrated outline page * - * $Id: XMLEditor.java,v 1.3 2004-09-22 18:57:42 jsurfer Exp $ + * $Id: XMLEditor.java,v 1.4 2006-10-21 23:14:14 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.editor; @@ -46,147 +46,162 @@ import org.eclipse.ui.views.contentoutline.IContentOutlinePage; * @author Igor Malinin */ public class XMLEditor extends TextEditor implements IReconcilingParticipant { - - - /** - * Listens to changes to the selection in the outline page, and changes the selection and highlight range in the editor - * accordingly. - */ - private class OutlineSelectionChangedListener implements ISelectionChangedListener { - - /* - * @see ISelectionChangedListener#selectionChanged(SelectionChangedEvent) - */ - public void selectionChanged(SelectionChangedEvent event) { - IStructuredSelection selection = (IStructuredSelection) event.getSelection(); - if (selection.isEmpty()) { - resetHighlightRange(); - } else { - ISourceReference element = (ISourceReference) selection.getFirstElement(); - highlightElement(element, true); - } - } - - } - - /** - * The associated outline page. - */ - XMLOutlinePage outlinePage; - int fType; - /** - * Listens to changes in the outline page's selection to update the editor selection and highlight range. - */ - private ISelectionChangedListener outlineSelectionChangedListener; - - public XMLEditor() { - this(ShowExternalPreviewAction.XML_TYPE); - } - /** - * Constructor. - */ - public XMLEditor(int type) { - fType = type; - List stores = new ArrayList(3); - - stores.add(XMLPlugin.getDefault().getPreferenceStore()); - stores.add(EditorsUI.getPreferenceStore()); - - setPreferenceStore(new ChainedPreferenceStore((IPreferenceStore[]) stores.toArray(new IPreferenceStore[stores.size()]))); - } - - /* - * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class) - */ - public Object getAdapter(Class adapter) { - if (adapter.equals(IContentOutlinePage.class)) { - if (outlinePage == null) { - outlinePage = new XMLOutlinePage(this); - outlineSelectionChangedListener = new OutlineSelectionChangedListener(); - outlinePage.addSelectionChangedListener(outlineSelectionChangedListener); - } - - return outlinePage; - } - - return super.getAdapter(adapter); - } - - /* - * @see IReconcilingParticipant#reconciled() - */ - public void reconciled() { - Shell shell = getSite().getShell(); - if ((shell != null) && !shell.isDisposed()) { - shell.getDisplay().asyncExec(new Runnable() { - public void run() { - if (outlinePage != null) { - outlinePage.update(); - } - } - }); - } - } - - /* - * @see org.eclipse.ui.editors.text.TextEditor#initializeEditor() - */ - protected void initializeEditor() { - super.initializeEditor(); - - XMLTextTools xmlTextTools = XMLPlugin.getDefault().getXMLTextTools(); - setSourceViewerConfiguration(new XMLConfiguration(xmlTextTools, this)); - setDocumentProvider(new XMLDocumentProvider()); - - ShowExternalPreviewAction fShowExternalPreviewAction = ShowExternalPreviewAction.getInstance(); - fShowExternalPreviewAction.setEditor(this); - fShowExternalPreviewAction.update(); - if (fShowExternalPreviewAction != null) - fShowExternalPreviewAction.doRun(fType); - } - - /* - * @see org.eclipse.ui.texteditor.AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent) - */ - protected boolean affectsTextPresentation(PropertyChangeEvent event) { - return XMLPlugin.getDefault().getXMLTextTools().affectsBehavior(event); - } - - void highlightElement(ISourceReference element, boolean moveCursor) { - if (element != null) { - IRegion highlightRegion = element.getSourceRegion(); - setHighlightRange(highlightRegion.getOffset(), highlightRegion.getLength(), moveCursor); - } else { - resetHighlightRange(); - } - } - - protected void createActions() { - super.createActions(); - - IAction action = new ContentAssistAction(XMLEditorMessages.getResourceBundle(), "ContentAssistProposal.", this); //$NON-NLS-1$ - action.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); - setAction("ContentAssistProposal", action); //$NON-NLS-1$ - markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$ - - // IAction action= new TextOperationAction( - // TemplateMessages.getResourceBundle(), - // "Editor." + TEMPLATE_PROPOSALS + ".", //$NON-NLS-1$ //$NON-NLS-2$ - // this, - // ISourceViewer.CONTENTASSIST_PROPOSALS); - // action.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); - // setAction(TEMPLATE_PROPOSALS, action); - // markAsStateDependentAction(TEMPLATE_PROPOSALS, true); - } - - /* (non-Javadoc) - * @see org.eclipse.ui.texteditor.AbstractTextEditor#editorSaved() - */ - protected void editorSaved() { - super.editorSaved(); - ShowExternalPreviewAction a = ShowExternalPreviewAction.getInstance(); - if (a != null) { - a.refresh(fType); - } - } + + /** + * Listens to changes to the selection in the outline page, and changes the + * selection and highlight range in the editor accordingly. + */ + private class OutlineSelectionChangedListener implements + ISelectionChangedListener { + + /* + * @see ISelectionChangedListener#selectionChanged(SelectionChangedEvent) + */ + public void selectionChanged(SelectionChangedEvent event) { + IStructuredSelection selection = (IStructuredSelection) event + .getSelection(); + if (selection.isEmpty()) { + resetHighlightRange(); + } else { + ISourceReference element = (ISourceReference) selection + .getFirstElement(); + highlightElement(element, true); + } + } + + } + + /** + * The associated outline page. + */ + XMLOutlinePage outlinePage; + + int fType; + + /** + * Listens to changes in the outline page's selection to update the editor + * selection and highlight range. + */ + private ISelectionChangedListener outlineSelectionChangedListener; + + public XMLEditor() { + this(ShowExternalPreviewAction.XML_TYPE); + } + + /** + * Constructor. + */ + public XMLEditor(int type) { + fType = type; + List stores = new ArrayList(3); + + stores.add(XMLPlugin.getDefault().getPreferenceStore()); + stores.add(EditorsUI.getPreferenceStore()); + + setPreferenceStore(new ChainedPreferenceStore( + (IPreferenceStore[]) stores.toArray(new IPreferenceStore[stores + .size()]))); + } + + /* + * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class) + */ + public Object getAdapter(Class adapter) { + if (adapter.equals(IContentOutlinePage.class)) { + if (outlinePage == null) { + outlinePage = new XMLOutlinePage(this); + outlineSelectionChangedListener = new OutlineSelectionChangedListener(); + outlinePage + .addSelectionChangedListener(outlineSelectionChangedListener); + } + + return outlinePage; + } + + return super.getAdapter(adapter); + } + + /* + * @see IReconcilingParticipant#reconciled() + */ + public void reconciled() { + Shell shell = getSite().getShell(); + if ((shell != null) && !shell.isDisposed()) { + shell.getDisplay().asyncExec(new Runnable() { + public void run() { + if (outlinePage != null) { + outlinePage.update(); + } + } + }); + } + } + + /* + * @see org.eclipse.ui.editors.text.TextEditor#initializeEditor() + */ + protected void initializeEditor() { + super.initializeEditor(); + + XMLTextTools xmlTextTools = XMLPlugin.getDefault().getXMLTextTools(); + setSourceViewerConfiguration(new XMLConfiguration(xmlTextTools, this)); + setDocumentProvider(new XMLDocumentProvider()); + + ShowExternalPreviewAction fShowExternalPreviewAction = ShowExternalPreviewAction + .getInstance(); + fShowExternalPreviewAction.setEditor(this); + fShowExternalPreviewAction.update(); + if (fShowExternalPreviewAction != null) + fShowExternalPreviewAction.doRun(fType); + } + + /* + * @see org.eclipse.ui.texteditor.AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent) + */ + protected boolean affectsTextPresentation(PropertyChangeEvent event) { + return XMLPlugin.getDefault().getXMLTextTools().affectsBehavior(event); + } + + void highlightElement(ISourceReference element, boolean moveCursor) { + if (element != null) { + IRegion highlightRegion = element.getSourceRegion(); + setHighlightRange(highlightRegion.getOffset(), highlightRegion + .getLength(), moveCursor); + } else { + resetHighlightRange(); + } + } + + protected void createActions() { + super.createActions(); + + IAction action = new ContentAssistAction(XMLEditorMessages + .getResourceBundle(), "ContentAssistProposal.", this); //$NON-NLS-1$ + action + .setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); + setAction("ContentAssistProposal", action); //$NON-NLS-1$ + markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$ + + // IAction action= new TextOperationAction( + // TemplateMessages.getResourceBundle(), + // "Editor." + TEMPLATE_PROPOSALS + ".", //$NON-NLS-1$ //$NON-NLS-2$ + // this, + // ISourceViewer.CONTENTASSIST_PROPOSALS); + // action.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); + // setAction(TEMPLATE_PROPOSALS, action); + // markAsStateDependentAction(TEMPLATE_PROPOSALS, true); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.texteditor.AbstractTextEditor#editorSaved() + */ + protected void editorSaved() { + super.editorSaved(); + ShowExternalPreviewAction a = ShowExternalPreviewAction.getInstance(); + if (a != null) { + a.refresh(fType); + } + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLEditorActionContributor.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLEditorActionContributor.java index 95c2f5c..8d65d7c 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLEditorActionContributor.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLEditorActionContributor.java @@ -22,7 +22,8 @@ import org.eclipse.ui.texteditor.ITextEditor; /** * Common base class for action contributors for Java editors. */ -public class XMLEditorActionContributor extends BasicTextEditorActionContributor { +public class XMLEditorActionContributor extends + BasicTextEditorActionContributor { /* * (non-Javadoc) @@ -43,11 +44,13 @@ public class XMLEditorActionContributor extends BasicTextEditorActionContributor file = ((IFileEditorInput) editorInput).getFile(); } - ShowExternalPreviewAction fShowExternalPreviewAction = ShowExternalPreviewAction.getInstance(); + ShowExternalPreviewAction fShowExternalPreviewAction = ShowExternalPreviewAction + .getInstance(); fShowExternalPreviewAction.setEditor(textEditor); fShowExternalPreviewAction.update(); if (fShowExternalPreviewAction != null) - fShowExternalPreviewAction.doRun(ShowExternalPreviewAction.PHP_TYPE); + fShowExternalPreviewAction + .doRun(ShowExternalPreviewAction.PHP_TYPE); } } } diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLEditorMessages.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLEditorMessages.java index f63bc52..906e74b 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLEditorMessages.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLEditorMessages.java @@ -1,14 +1,14 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ package net.sourceforge.phpeclipse.xml.ui.internal.editor; import java.text.MessageFormat; @@ -17,9 +17,10 @@ import java.util.ResourceBundle; public class XMLEditorMessages { - private static final String RESOURCE_BUNDLE= "net.sourceforge.phpeclipse.xml.ui.internal.editor.XMLEditorMessages";//$NON-NLS-1$ + private static final String RESOURCE_BUNDLE = "net.sourceforge.phpeclipse.xml.ui.internal.editor.XMLEditorMessages";//$NON-NLS-1$ - private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); + private static ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); private XMLEditorMessages() { } @@ -31,14 +32,14 @@ public class XMLEditorMessages { return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$ } } - + /** * Gets a string from the resource bundle and formats it with arguments - */ + */ public static String getFormattedString(String key, Object[] args) { return MessageFormat.format(getString(key), args); } - + public static ResourceBundle getResourceBundle() { return fgResourceBundle; } diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/outline/XMLOutlineContentProvider.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/outline/XMLOutlineContentProvider.java index a42a47d..4484e94 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/outline/XMLOutlineContentProvider.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/outline/XMLOutlineContentProvider.java @@ -8,7 +8,7 @@ * Contributors: * Christopher Lenz - initial API and implementation * - * $Id: XMLOutlineContentProvider.java,v 1.2 2005-05-06 00:55:42 stefanbjarni Exp $ + * $Id: XMLOutlineContentProvider.java,v 1.3 2006-10-21 23:14:14 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.outline; @@ -78,7 +78,8 @@ public class XMLOutlineContentProvider implements ITreeContentProvider { } /* - * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(Viewer, Object, Object) + * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(Viewer, + * Object, Object) */ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { if (oldInput != newInput) { @@ -87,7 +88,7 @@ public class XMLOutlineContentProvider implements ITreeContentProvider { } if (newInput instanceof IXMLDocument) { document = (IXMLDocument) newInput; - } + } } } diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/outline/XMLOutlineLabelProvider.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/outline/XMLOutlineLabelProvider.java index e895ce3..38fd25c 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/outline/XMLOutlineLabelProvider.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/outline/XMLOutlineLabelProvider.java @@ -8,7 +8,7 @@ * Contributors: * Christopher Lenz - initial API and implementation * - * $Id: XMLOutlineLabelProvider.java,v 1.2 2005-05-06 00:55:42 stefanbjarni Exp $ + * $Id: XMLOutlineLabelProvider.java,v 1.3 2006-10-21 23:14:14 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.outline; @@ -32,7 +32,7 @@ public class XMLOutlineLabelProvider extends LabelProvider { public Image getImage(Object element) { if (element instanceof IXMLElement) { return XMLPlugin.getDefault().getImageRegistry().get( - XMLPlugin.ICON_ELEMENT); + XMLPlugin.ICON_ELEMENT); } return null; } diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/outline/XMLOutlinePage.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/outline/XMLOutlinePage.java index e1da92e..0daae7d 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/outline/XMLOutlinePage.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/outline/XMLOutlinePage.java @@ -8,7 +8,7 @@ * Contributors: * Christopher Lenz - initial API and implementation * - * $Id: XMLOutlinePage.java,v 1.2 2005-05-06 00:55:42 stefanbjarni Exp $ + * $Id: XMLOutlinePage.java,v 1.3 2006-10-21 23:14:14 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.outline; @@ -48,7 +48,8 @@ public class XMLOutlinePage extends ContentOutlinePage { /** * Constructor. * - * @param editor The associated text editor + * @param editor + * The associated text editor */ public XMLOutlinePage(XMLEditor editor) { this.editor = editor; @@ -64,8 +65,8 @@ public class XMLOutlinePage extends ContentOutlinePage { TreeViewer viewer = getTreeViewer(); viewer.setContentProvider(new XMLOutlineContentProvider()); viewer.setLabelProvider(new DecoratingLabelProvider( - new XMLOutlineLabelProvider(), - new ProblemsLabelDecorator(editor))); + new XMLOutlineLabelProvider(), new ProblemsLabelDecorator( + editor))); viewer.setInput(getDocument()); } @@ -74,15 +75,15 @@ public class XMLOutlinePage extends ContentOutlinePage { /** * Selects a specific element in the outline page. * - * @param element the element to select + * @param element + * the element to select */ public void select(ISourceReference element) { TreeViewer viewer = getTreeViewer(); if (viewer != null) { ISelection selection = viewer.getSelection(); if (selection instanceof IStructuredSelection) { - IStructuredSelection structuredSelection = - (IStructuredSelection) selection; + IStructuredSelection structuredSelection = (IStructuredSelection) selection; List elements = structuredSelection.toList(); if (!elements.contains(element)) { if (element == null) { @@ -118,7 +119,7 @@ public class XMLOutlinePage extends ContentOutlinePage { // Private Methods --------------------------------------------------------- /** - * Returns the parsed model of the XML document that is loaded into the + * Returns the parsed model of the XML document that is loaded into the * associated editor. * * @return the parsed XML document diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/preferences/ContentAssistPreference.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/preferences/ContentAssistPreference.java index 46eeace..25b27d1 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/preferences/ContentAssistPreference.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/preferences/ContentAssistPreference.java @@ -8,52 +8,58 @@ import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.contentassist.ContentAssistant; import org.eclipse.jface.text.contentassist.IContentAssistProcessor; - public class ContentAssistPreference { - /** Preference key for html content assist auto activation triggers */ - private final static String AUTOACTIVATION_TRIGGERS_HTML = PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_HTML; - - /** Preference key for alphabetic ordering of proposals */ - private final static String ORDER_PROPOSALS = PreferenceConstants.CODEASSIST_ORDER_PROPOSALS; - - private static BasicCompletionProcessor getHTMLProcessor(ContentAssistant assistant) { - IContentAssistProcessor p = assistant.getContentAssistProcessor(XMLPartitionScanner.XML_TAG); - if (p instanceof BasicCompletionProcessor) - return (BasicCompletionProcessor) p; - return null; - } - - private static void configureHTMLProcessor(ContentAssistant assistant, IPreferenceStore store) { - BasicCompletionProcessor hcp = getHTMLProcessor(assistant); - if (hcp == null) - return; - - String triggers = store.getString(AUTOACTIVATION_TRIGGERS_HTML); - if (triggers != null) - hcp.setCompletionProposalAutoActivationCharacters(triggers.toCharArray()); - - boolean enabled; - // boolean enabled = store.getBoolean(CASE_SENSITIVITY); - // jdcp.restrictProposalsToMatchingCases(enabled); - - enabled = store.getBoolean(ORDER_PROPOSALS); - // hcp.orderProposalsAlphabetically(enabled); - } - private static void changeHTMLProcessor(ContentAssistant assistant, IPreferenceStore store, String key) { - BasicCompletionProcessor jdcp = getHTMLProcessor(assistant); - if (jdcp == null) - return; - - if (AUTOACTIVATION_TRIGGERS_HTML.equals(key)) { - String triggers = store.getString(AUTOACTIVATION_TRIGGERS_HTML); - if (triggers != null) - jdcp.setCompletionProposalAutoActivationCharacters(triggers.toCharArray()); - // } else if (CASE_SENSITIVITY.equals(key)) { - // boolean enabled = store.getBoolean(CASE_SENSITIVITY); - // jdcp.restrictProposalsToMatchingCases(enabled); - } else if (ORDER_PROPOSALS.equals(key)) { - boolean enable = store.getBoolean(ORDER_PROPOSALS); - // jdcp.orderProposalsAlphabetically(enable); - } - } + /** Preference key for html content assist auto activation triggers */ + private final static String AUTOACTIVATION_TRIGGERS_HTML = PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_HTML; + + /** Preference key for alphabetic ordering of proposals */ + private final static String ORDER_PROPOSALS = PreferenceConstants.CODEASSIST_ORDER_PROPOSALS; + + private static BasicCompletionProcessor getHTMLProcessor( + ContentAssistant assistant) { + IContentAssistProcessor p = assistant + .getContentAssistProcessor(XMLPartitionScanner.XML_TAG); + if (p instanceof BasicCompletionProcessor) + return (BasicCompletionProcessor) p; + return null; + } + + private static void configureHTMLProcessor(ContentAssistant assistant, + IPreferenceStore store) { + BasicCompletionProcessor hcp = getHTMLProcessor(assistant); + if (hcp == null) + return; + + String triggers = store.getString(AUTOACTIVATION_TRIGGERS_HTML); + if (triggers != null) + hcp.setCompletionProposalAutoActivationCharacters(triggers + .toCharArray()); + + boolean enabled; + // boolean enabled = store.getBoolean(CASE_SENSITIVITY); + // jdcp.restrictProposalsToMatchingCases(enabled); + + enabled = store.getBoolean(ORDER_PROPOSALS); + // hcp.orderProposalsAlphabetically(enabled); + } + + private static void changeHTMLProcessor(ContentAssistant assistant, + IPreferenceStore store, String key) { + BasicCompletionProcessor jdcp = getHTMLProcessor(assistant); + if (jdcp == null) + return; + + if (AUTOACTIVATION_TRIGGERS_HTML.equals(key)) { + String triggers = store.getString(AUTOACTIVATION_TRIGGERS_HTML); + if (triggers != null) + jdcp.setCompletionProposalAutoActivationCharacters(triggers + .toCharArray()); + // } else if (CASE_SENSITIVITY.equals(key)) { + // boolean enabled = store.getBoolean(CASE_SENSITIVITY); + // jdcp.restrictProposalsToMatchingCases(enabled); + } else if (ORDER_PROPOSALS.equals(key)) { + boolean enable = store.getBoolean(ORDER_PROPOSALS); + // jdcp.orderProposalsAlphabetically(enable); + } + } } diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/preferences/XMLPreferenceInitializer.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/preferences/XMLPreferenceInitializer.java index aac1795..2099183 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/preferences/XMLPreferenceInitializer.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/preferences/XMLPreferenceInitializer.java @@ -9,7 +9,7 @@ * Roberto Gonzalez Rocha - Initial version * Igor Malinin - refactoring, minor changes * - * $Id: XMLPreferenceInitializer.java,v 1.2 2005-12-18 15:50:53 bananeweizen Exp $ + * $Id: XMLPreferenceInitializer.java,v 1.3 2006-10-21 23:14:13 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.preferences; @@ -24,7 +24,6 @@ import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.texteditor.AbstractTextEditor; - /** * @author Igor Malinin */ @@ -33,73 +32,78 @@ public class XMLPreferenceInitializer extends AbstractPreferenceInitializer { * @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences() */ public void initializeDefaultPreferences() { - final IPreferenceStore store = XMLPlugin.getDefault().getPreferenceStore(); - final Display display=Display.getDefault(); + final IPreferenceStore store = XMLPlugin.getDefault() + .getPreferenceStore(); + final Display display = Display.getDefault(); // TODO: ChainedPreferenceStore does not work for preferences preview display.syncExec(new Runnable() { public void run() { PreferenceConverter.setDefault(store, - AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND, - display.getSystemColor(SWT.COLOR_LIST_FOREGROUND).getRGB()); - }}); + AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND, display + .getSystemColor(SWT.COLOR_LIST_FOREGROUND) + .getRGB()); + } + }); store.setDefault( - AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT, - true); + AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT, + true); display.syncExec(new Runnable() { public void run() { PreferenceConverter.setDefault(store, - AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND, - display.getSystemColor(SWT.COLOR_LIST_BACKGROUND).getRGB()); - }}); + AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND, display + .getSystemColor(SWT.COLOR_LIST_BACKGROUND) + .getRGB()); + } + }); store.setDefault( - AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT, - true); + AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT, + true); // end of common preferences - setDefault(store, IXMLSyntaxConstants.XML_DEFAULT, - "0,0,0", ITextStylePreferences.STYLE_NORMAL); + setDefault(store, IXMLSyntaxConstants.XML_DEFAULT, "0,0,0", + ITextStylePreferences.STYLE_NORMAL); + + setDefault(store, IXMLSyntaxConstants.XML_TAG, "127,0,127", + ITextStylePreferences.STYLE_NORMAL); - setDefault(store, IXMLSyntaxConstants.XML_TAG, - "127,0,127", ITextStylePreferences.STYLE_NORMAL); + setDefault(store, IXMLSyntaxConstants.XML_ATT_NAME, "0,127,0", + ITextStylePreferences.STYLE_NORMAL); - setDefault(store, IXMLSyntaxConstants.XML_ATT_NAME, - "0,127,0", ITextStylePreferences.STYLE_NORMAL); + setDefault(store, IXMLSyntaxConstants.XML_ATT_VALUE, "0,0,255", + ITextStylePreferences.STYLE_NORMAL); - setDefault(store, IXMLSyntaxConstants.XML_ATT_VALUE, - "0,0,255", ITextStylePreferences.STYLE_NORMAL); + setDefault(store, IXMLSyntaxConstants.XML_ENTITY, "127,127,0", + ITextStylePreferences.STYLE_NORMAL); - setDefault(store, IXMLSyntaxConstants.XML_ENTITY, - "127,127,0", ITextStylePreferences.STYLE_NORMAL); + setDefault(store, IXMLSyntaxConstants.XML_CDATA, "127,127,0", + ITextStylePreferences.STYLE_NORMAL); - setDefault(store, IXMLSyntaxConstants.XML_CDATA, - "127,127,0", ITextStylePreferences.STYLE_NORMAL); + setDefault(store, IXMLSyntaxConstants.XML_PI, "127,127,127", + ITextStylePreferences.STYLE_BOLD); - setDefault(store, IXMLSyntaxConstants.XML_PI, - "127,127,127", ITextStylePreferences.STYLE_BOLD); + setDefault(store, IXMLSyntaxConstants.XML_COMMENT, "127,0,0", + ITextStylePreferences.STYLE_NORMAL); - setDefault(store, IXMLSyntaxConstants.XML_COMMENT, - "127,0,0", ITextStylePreferences.STYLE_NORMAL); + setDefault(store, IXMLSyntaxConstants.XML_DECL, "127,0,127", + ITextStylePreferences.STYLE_BOLD); - setDefault(store, IXMLSyntaxConstants.XML_DECL, - "127,0,127", ITextStylePreferences.STYLE_BOLD); + setDefault(store, IXMLSyntaxConstants.XML_SMARTY, "255,0,127", + ITextStylePreferences.STYLE_BOLD); - setDefault(store, IXMLSyntaxConstants.XML_SMARTY, - "255,0,127", ITextStylePreferences.STYLE_BOLD); - - setDefault(store, IXMLSyntaxConstants.DTD_CONDITIONAL, - "127,127,0", ITextStylePreferences.STYLE_BOLD); + setDefault(store, IXMLSyntaxConstants.DTD_CONDITIONAL, "127,127,0", + ITextStylePreferences.STYLE_BOLD); } - private static void setDefault( - IPreferenceStore store, String constant, String color, String style - ) { - store.setDefault(constant + ITextStylePreferences.SUFFIX_FOREGROUND, color); + private static void setDefault(IPreferenceStore store, String constant, + String color, String style) { + store.setDefault(constant + ITextStylePreferences.SUFFIX_FOREGROUND, + color); store.setDefault(constant + ITextStylePreferences.SUFFIX_STYLE, style); } } diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/preferences/XMLSyntaxPreferencePage.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/preferences/XMLSyntaxPreferencePage.java index a0f8a5b..e855df2 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/preferences/XMLSyntaxPreferencePage.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/preferences/XMLSyntaxPreferencePage.java @@ -9,7 +9,7 @@ * Roberto Gonzalez Rocha - Initial version * Igor Malinin - refactoring, minor changes * - * $Id: XMLSyntaxPreferencePage.java,v 1.2 2005-05-06 00:55:41 stefanbjarni Exp $ + * $Id: XMLSyntaxPreferencePage.java,v 1.3 2006-10-21 23:14:13 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.preferences; @@ -59,440 +59,529 @@ import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.texteditor.AbstractTextEditor; /** - * The XMLSyntaxPreferencePage is a preference page that handles setting the colors used by the XML editors. + * The XMLSyntaxPreferencePage is a preference page that handles setting the + * colors used by the XML editors. */ -public class XMLSyntaxPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { +public class XMLSyntaxPreferencePage extends PreferencePage implements + IWorkbenchPreferencePage { + + public final PreferenceDescriptor[] fKeys = new PreferenceDescriptor[] { + new PreferenceDescriptor( + PreferenceDescriptor.BOOLEAN, + AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT), + new PreferenceDescriptor(PreferenceDescriptor.STRING, + AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND), + + new PreferenceDescriptor(PreferenceDescriptor.STRING, + IXMLSyntaxConstants.XML_DEFAULT + + ITextStylePreferences.SUFFIX_FOREGROUND), + new PreferenceDescriptor(PreferenceDescriptor.STRING, + IXMLSyntaxConstants.XML_DEFAULT + + ITextStylePreferences.SUFFIX_STYLE), + + new PreferenceDescriptor(PreferenceDescriptor.STRING, + IXMLSyntaxConstants.XML_TAG + + ITextStylePreferences.SUFFIX_FOREGROUND), + new PreferenceDescriptor(PreferenceDescriptor.STRING, + IXMLSyntaxConstants.XML_TAG + + ITextStylePreferences.SUFFIX_STYLE), + + new PreferenceDescriptor(PreferenceDescriptor.STRING, + IXMLSyntaxConstants.XML_ATT_NAME + + ITextStylePreferences.SUFFIX_FOREGROUND), + new PreferenceDescriptor(PreferenceDescriptor.STRING, + IXMLSyntaxConstants.XML_ATT_NAME + + ITextStylePreferences.SUFFIX_STYLE), + + new PreferenceDescriptor(PreferenceDescriptor.STRING, + IXMLSyntaxConstants.XML_ATT_VALUE + + ITextStylePreferences.SUFFIX_FOREGROUND), + new PreferenceDescriptor(PreferenceDescriptor.STRING, + IXMLSyntaxConstants.XML_ATT_VALUE + + ITextStylePreferences.SUFFIX_STYLE), + + new PreferenceDescriptor(PreferenceDescriptor.STRING, + IXMLSyntaxConstants.XML_ENTITY + + ITextStylePreferences.SUFFIX_FOREGROUND), + new PreferenceDescriptor(PreferenceDescriptor.STRING, + IXMLSyntaxConstants.XML_ENTITY + + ITextStylePreferences.SUFFIX_STYLE), + + new PreferenceDescriptor(PreferenceDescriptor.STRING, + IXMLSyntaxConstants.XML_CDATA + + ITextStylePreferences.SUFFIX_FOREGROUND), + new PreferenceDescriptor(PreferenceDescriptor.STRING, + IXMLSyntaxConstants.XML_CDATA + + ITextStylePreferences.SUFFIX_STYLE), + + new PreferenceDescriptor(PreferenceDescriptor.STRING, + IXMLSyntaxConstants.XML_PI + + ITextStylePreferences.SUFFIX_FOREGROUND), + new PreferenceDescriptor(PreferenceDescriptor.STRING, + IXMLSyntaxConstants.XML_PI + + ITextStylePreferences.SUFFIX_STYLE), + + new PreferenceDescriptor(PreferenceDescriptor.STRING, + IXMLSyntaxConstants.XML_COMMENT + + ITextStylePreferences.SUFFIX_FOREGROUND), + new PreferenceDescriptor(PreferenceDescriptor.STRING, + IXMLSyntaxConstants.XML_COMMENT + + ITextStylePreferences.SUFFIX_STYLE), + + new PreferenceDescriptor(PreferenceDescriptor.STRING, + IXMLSyntaxConstants.XML_DECL + + ITextStylePreferences.SUFFIX_FOREGROUND), + new PreferenceDescriptor(PreferenceDescriptor.STRING, + IXMLSyntaxConstants.XML_DECL + + ITextStylePreferences.SUFFIX_STYLE), + + new PreferenceDescriptor(PreferenceDescriptor.STRING, + IXMLSyntaxConstants.XML_SMARTY + + ITextStylePreferences.SUFFIX_FOREGROUND), + new PreferenceDescriptor(PreferenceDescriptor.STRING, + IXMLSyntaxConstants.XML_SMARTY + + ITextStylePreferences.SUFFIX_STYLE), + + new PreferenceDescriptor(PreferenceDescriptor.STRING, + IXMLSyntaxConstants.DTD_CONDITIONAL + + ITextStylePreferences.SUFFIX_FOREGROUND), + new PreferenceDescriptor(PreferenceDescriptor.STRING, + IXMLSyntaxConstants.DTD_CONDITIONAL + + ITextStylePreferences.SUFFIX_STYLE), }; + + OverlayPreferenceStore overlay; + + final String[][] fSyntaxColorListModel = new String[][] { + { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.others"), //$NON-NLS-1$ + IXMLSyntaxConstants.XML_DEFAULT }, + { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.Tag"), //$NON-NLS-1$ + IXMLSyntaxConstants.XML_TAG }, + { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.AttName"), //$NON-NLS-1$ + IXMLSyntaxConstants.XML_ATT_NAME }, + { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.AttValue"), //$NON-NLS-1$ + IXMLSyntaxConstants.XML_ATT_VALUE }, + { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.Entity"), //$NON-NLS-1$ + IXMLSyntaxConstants.XML_ENTITY }, + { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.CDATA"), //$NON-NLS-1$ + IXMLSyntaxConstants.XML_CDATA }, + { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.PI"), //$NON-NLS-1$ + IXMLSyntaxConstants.XML_PI }, + { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.Comment"), //$NON-NLS-1$ + IXMLSyntaxConstants.XML_COMMENT }, + { + XMLPlugin + .getResourceString("XmlSyntaxPreferencePage.Declaration"), //$NON-NLS-1$ + IXMLSyntaxConstants.XML_DECL }, + { + XMLPlugin + .getResourceString("XmlSyntaxPreferencePage.Conditional"), //$NON-NLS-1$ + IXMLSyntaxConstants.XML_SMARTY }, + { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.SmartyTag"), //$NON-NLS-1$ + IXMLSyntaxConstants.DTD_CONDITIONAL }, }; + + private XMLTextTools xmlTextTools; + + private Color bgColor; + + Button bgDefault; + + Button bgCustom; + + ColorEditor bgColorEditor; + + List colors; + + ColorEditor fgColorEditor; + + Button fgBold; + + SourceViewer preview; + + /** + * Constructor for XMLSyntaxPreferencePage. + */ + public XMLSyntaxPreferencePage() { + setDescription(XMLPlugin + .getResourceString("XmlSyntaxPreferencePage.description")); //$NON-NLS-1$ + + setPreferenceStore(XMLPlugin.getDefault().getPreferenceStore()); + + overlay = new OverlayPreferenceStore(getPreferenceStore(), fKeys); + } + + protected Control createContents(Composite parent) { + overlay.load(); + overlay.start(); + + Composite colorComposite = new Composite(parent, SWT.NULL); + colorComposite.setLayout(new GridLayout()); + + Group backgroundComposite = new Group(colorComposite, + SWT.SHADOW_ETCHED_IN); + + backgroundComposite.setLayout(new RowLayout()); + backgroundComposite.setText(XMLPlugin + .getResourceString("XmlSyntaxPreferencePage.backgroundColor")); //$NON-NLS-1$ + + SelectionListener backgroundSelectionListener = new SelectionListener() { + public void widgetSelected(SelectionEvent e) { + boolean custom = bgCustom.getSelection(); + bgColorEditor.getButton().setEnabled(custom); + overlay + .setValue( + AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT, + !custom); + } + + public void widgetDefaultSelected(SelectionEvent e) { + } + }; + + bgDefault = new Button(backgroundComposite, SWT.RADIO | SWT.LEFT); + bgDefault.setText(XMLPlugin + .getResourceString("XmlSyntaxPreferencePage.systemDefault")); //$NON-NLS-1$ + bgDefault.addSelectionListener(backgroundSelectionListener); + + bgCustom = new Button(backgroundComposite, SWT.RADIO | SWT.LEFT); + bgCustom.setText(XMLPlugin + .getResourceString("XmlSyntaxPreferencePage.custom")); //$NON-NLS-1$ + bgCustom.addSelectionListener(backgroundSelectionListener); + + bgColorEditor = new ColorEditor(backgroundComposite); + + Label label = new Label(colorComposite, SWT.LEFT); + label.setText(XMLPlugin + .getResourceString("XmlSyntaxPreferencePage.foreground")); //$NON-NLS-1$ + label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + Composite editorComposite = new Composite(colorComposite, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.numColumns = 2; + layout.marginHeight = 0; + layout.marginWidth = 0; + editorComposite.setLayout(layout); + GridData gd = new GridData(GridData.FILL_BOTH); + editorComposite.setLayoutData(gd); + + colors = new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL + | SWT.BORDER); + gd = new GridData(GridData.FILL_BOTH); + gd.heightHint = convertHeightInCharsToPixels(5); + colors.setLayoutData(gd); + + Composite stylesComposite = new Composite(editorComposite, SWT.NONE); + layout = new GridLayout(); + layout.marginHeight = 0; + layout.marginWidth = 0; + layout.numColumns = 2; + stylesComposite.setLayout(layout); + stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); - public final PreferenceDescriptor[] fKeys = new PreferenceDescriptor[] { - new PreferenceDescriptor(PreferenceDescriptor.BOOLEAN, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT), - new PreferenceDescriptor(PreferenceDescriptor.STRING, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND), - - new PreferenceDescriptor(PreferenceDescriptor.STRING, IXMLSyntaxConstants.XML_DEFAULT - + ITextStylePreferences.SUFFIX_FOREGROUND), - new PreferenceDescriptor(PreferenceDescriptor.STRING, IXMLSyntaxConstants.XML_DEFAULT + ITextStylePreferences.SUFFIX_STYLE), - - new PreferenceDescriptor(PreferenceDescriptor.STRING, IXMLSyntaxConstants.XML_TAG + ITextStylePreferences.SUFFIX_FOREGROUND), - new PreferenceDescriptor(PreferenceDescriptor.STRING, IXMLSyntaxConstants.XML_TAG + ITextStylePreferences.SUFFIX_STYLE), - - new PreferenceDescriptor(PreferenceDescriptor.STRING, IXMLSyntaxConstants.XML_ATT_NAME - + ITextStylePreferences.SUFFIX_FOREGROUND), - new PreferenceDescriptor(PreferenceDescriptor.STRING, IXMLSyntaxConstants.XML_ATT_NAME + ITextStylePreferences.SUFFIX_STYLE), - - new PreferenceDescriptor(PreferenceDescriptor.STRING, IXMLSyntaxConstants.XML_ATT_VALUE - + ITextStylePreferences.SUFFIX_FOREGROUND), - new PreferenceDescriptor(PreferenceDescriptor.STRING, IXMLSyntaxConstants.XML_ATT_VALUE + ITextStylePreferences.SUFFIX_STYLE), - - new PreferenceDescriptor(PreferenceDescriptor.STRING, IXMLSyntaxConstants.XML_ENTITY - + ITextStylePreferences.SUFFIX_FOREGROUND), - new PreferenceDescriptor(PreferenceDescriptor.STRING, IXMLSyntaxConstants.XML_ENTITY + ITextStylePreferences.SUFFIX_STYLE), - - new PreferenceDescriptor(PreferenceDescriptor.STRING, IXMLSyntaxConstants.XML_CDATA + ITextStylePreferences.SUFFIX_FOREGROUND), - new PreferenceDescriptor(PreferenceDescriptor.STRING, IXMLSyntaxConstants.XML_CDATA + ITextStylePreferences.SUFFIX_STYLE), - - new PreferenceDescriptor(PreferenceDescriptor.STRING, IXMLSyntaxConstants.XML_PI + ITextStylePreferences.SUFFIX_FOREGROUND), - new PreferenceDescriptor(PreferenceDescriptor.STRING, IXMLSyntaxConstants.XML_PI + ITextStylePreferences.SUFFIX_STYLE), - - new PreferenceDescriptor(PreferenceDescriptor.STRING, IXMLSyntaxConstants.XML_COMMENT - + ITextStylePreferences.SUFFIX_FOREGROUND), - new PreferenceDescriptor(PreferenceDescriptor.STRING, IXMLSyntaxConstants.XML_COMMENT + ITextStylePreferences.SUFFIX_STYLE), - - new PreferenceDescriptor(PreferenceDescriptor.STRING, IXMLSyntaxConstants.XML_DECL + ITextStylePreferences.SUFFIX_FOREGROUND), - new PreferenceDescriptor(PreferenceDescriptor.STRING, IXMLSyntaxConstants.XML_DECL + ITextStylePreferences.SUFFIX_STYLE), - - new PreferenceDescriptor(PreferenceDescriptor.STRING, IXMLSyntaxConstants.XML_SMARTY + ITextStylePreferences.SUFFIX_FOREGROUND), - new PreferenceDescriptor(PreferenceDescriptor.STRING, IXMLSyntaxConstants.XML_SMARTY + ITextStylePreferences.SUFFIX_STYLE), - - new PreferenceDescriptor(PreferenceDescriptor.STRING, IXMLSyntaxConstants.DTD_CONDITIONAL - + ITextStylePreferences.SUFFIX_FOREGROUND), - new PreferenceDescriptor(PreferenceDescriptor.STRING, IXMLSyntaxConstants.DTD_CONDITIONAL - + ITextStylePreferences.SUFFIX_STYLE),}; - - OverlayPreferenceStore overlay; - - final String[][] fSyntaxColorListModel = new String[][] { { - XMLPlugin.getResourceString("XmlSyntaxPreferencePage.others"), //$NON-NLS-1$ - IXMLSyntaxConstants.XML_DEFAULT }, { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.Tag"), //$NON-NLS-1$ - IXMLSyntaxConstants.XML_TAG }, { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.AttName"), //$NON-NLS-1$ - IXMLSyntaxConstants.XML_ATT_NAME }, { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.AttValue"), //$NON-NLS-1$ - IXMLSyntaxConstants.XML_ATT_VALUE }, { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.Entity"), //$NON-NLS-1$ - IXMLSyntaxConstants.XML_ENTITY }, { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.CDATA"), //$NON-NLS-1$ - IXMLSyntaxConstants.XML_CDATA }, { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.PI"), //$NON-NLS-1$ - IXMLSyntaxConstants.XML_PI }, { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.Comment"), //$NON-NLS-1$ - IXMLSyntaxConstants.XML_COMMENT }, { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.Declaration"), //$NON-NLS-1$ - IXMLSyntaxConstants.XML_DECL }, { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.Conditional"), //$NON-NLS-1$ - IXMLSyntaxConstants.XML_SMARTY }, { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.SmartyTag"), //$NON-NLS-1$ - IXMLSyntaxConstants.DTD_CONDITIONAL }, - }; - - private XMLTextTools xmlTextTools; - - private Color bgColor; - - Button bgDefault; - - Button bgCustom; - - ColorEditor bgColorEditor; - - List colors; - - ColorEditor fgColorEditor; - - Button fgBold; - - SourceViewer preview; - - /** - * Constructor for XMLSyntaxPreferencePage. - */ - public XMLSyntaxPreferencePage() { - setDescription(XMLPlugin.getResourceString("XmlSyntaxPreferencePage.description")); //$NON-NLS-1$ - - setPreferenceStore(XMLPlugin.getDefault().getPreferenceStore()); - - overlay = new OverlayPreferenceStore(getPreferenceStore(), fKeys); - } - - protected Control createContents(Composite parent) { - overlay.load(); - overlay.start(); - - Composite colorComposite = new Composite(parent, SWT.NULL); - colorComposite.setLayout(new GridLayout()); - - Group backgroundComposite = new Group(colorComposite, SWT.SHADOW_ETCHED_IN); - - backgroundComposite.setLayout(new RowLayout()); - backgroundComposite.setText(XMLPlugin.getResourceString("XmlSyntaxPreferencePage.backgroundColor")); //$NON-NLS-1$ - - SelectionListener backgroundSelectionListener = new SelectionListener() { - public void widgetSelected(SelectionEvent e) { - boolean custom = bgCustom.getSelection(); - bgColorEditor.getButton().setEnabled(custom); - overlay.setValue(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT, !custom); - } - - public void widgetDefaultSelected(SelectionEvent e) { - } - }; - - bgDefault = new Button(backgroundComposite, SWT.RADIO | SWT.LEFT); - bgDefault.setText(XMLPlugin.getResourceString("XmlSyntaxPreferencePage.systemDefault")); //$NON-NLS-1$ - bgDefault.addSelectionListener(backgroundSelectionListener); - - bgCustom = new Button(backgroundComposite, SWT.RADIO | SWT.LEFT); - bgCustom.setText(XMLPlugin.getResourceString("XmlSyntaxPreferencePage.custom")); //$NON-NLS-1$ - bgCustom.addSelectionListener(backgroundSelectionListener); - - bgColorEditor = new ColorEditor(backgroundComposite); - - Label label = new Label(colorComposite, SWT.LEFT); - label.setText(XMLPlugin.getResourceString("XmlSyntaxPreferencePage.foreground")); //$NON-NLS-1$ - label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - - Composite editorComposite = new Composite(colorComposite, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.numColumns = 2; - layout.marginHeight = 0; - layout.marginWidth = 0; - editorComposite.setLayout(layout); - GridData gd = new GridData(GridData.FILL_BOTH); - editorComposite.setLayoutData(gd); - - colors = new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); - gd = new GridData(GridData.FILL_BOTH); - gd.heightHint = convertHeightInCharsToPixels(5); - colors.setLayoutData(gd); - - Composite stylesComposite = new Composite(editorComposite, SWT.NONE); - layout = new GridLayout(); - layout.marginHeight = 0; - layout.marginWidth = 0; - layout.numColumns = 2; - stylesComposite.setLayout(layout); - stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); - - label = new Label(stylesComposite, SWT.LEFT); - label.setText(XMLPlugin.getResourceString("XmlSyntaxPreferencePage.color")); //$NON-NLS-1$ - gd = new GridData(); - gd.horizontalAlignment = GridData.BEGINNING; - label.setLayoutData(gd); - - fgColorEditor = new ColorEditor(stylesComposite); - - Button fgColorButton = fgColorEditor.getButton(); - gd = new GridData(GridData.FILL_HORIZONTAL); - gd.horizontalAlignment = GridData.BEGINNING; - fgColorButton.setLayoutData(gd); - - label = new Label(stylesComposite, SWT.LEFT); - label.setText(XMLPlugin.getResourceString("XmlSyntaxPreferencePage.bold")); //$NON-NLS-1$ - gd = new GridData(); - gd.horizontalAlignment = GridData.BEGINNING; - label.setLayoutData(gd); - - fgBold = new Button(stylesComposite, SWT.CHECK); - gd = new GridData(GridData.FILL_HORIZONTAL); - gd.horizontalAlignment = GridData.BEGINNING; - fgBold.setLayoutData(gd); - - label = new Label(colorComposite, SWT.LEFT); - label.setText(XMLPlugin.getResourceString("XmlSyntaxPreferencePage.preview")); //$NON-NLS-1$ - label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - - Control previewer = createPreviewer(colorComposite); - gd = new GridData(GridData.FILL_BOTH); - gd.widthHint = convertWidthInCharsToPixels(20); - gd.heightHint = convertHeightInCharsToPixels(5); - previewer.setLayoutData(gd); - - colors.addSelectionListener(new SelectionListener() { - - public void widgetDefaultSelected(SelectionEvent e) { - } - - public void widgetSelected(SelectionEvent e) { - handleSyntaxColorListSelection(); - } - }); - - bgColorEditor.getButton().addSelectionListener(new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - } - - public void widgetSelected(SelectionEvent e) { - PreferenceConverter.setValue(overlay, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND, bgColorEditor.getColorValue()); - } - }); - - fgColorButton.addSelectionListener(new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - } - - public void widgetSelected(SelectionEvent e) { - int i = colors.getSelectionIndex(); - - String key = fSyntaxColorListModel[i][1]; - - PreferenceConverter.setValue(overlay, key + ITextStylePreferences.SUFFIX_FOREGROUND, fgColorEditor.getColorValue()); - } - }); - - fgBold.addSelectionListener(new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - } - - public void widgetSelected(SelectionEvent e) { - int i = colors.getSelectionIndex(); - - String key = fSyntaxColorListModel[i][1]; - - String value = (fgBold.getSelection()) ? ITextStylePreferences.STYLE_BOLD : ITextStylePreferences.STYLE_NORMAL; - - overlay.setValue(key + ITextStylePreferences.SUFFIX_STYLE, value); - } - }); - - initialize(); - - return colorComposite; - } - - private Control createPreviewer(Composite parent) { - xmlTextTools = new XMLTextTools(overlay); // REVISIT: DTD - - preview = new SourceViewer(parent, null, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER); - - preview.configure(new XMLConfiguration(xmlTextTools)); - preview.getTextWidget().setFont(JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT)); - preview.setEditable(false); - - initializeViewerColors(preview); - - String content = loadPreviewContentFromFile("preview.xml"); //$NON-NLS-1$ - IDocument document = new Document(content); - - // REVISIT: DTD - IDocumentPartitioner partitioner = xmlTextTools.createXMLPartitioner(); - - partitioner.connect(document); - document.setDocumentPartitioner(partitioner); - - preview.setDocument(document); - - overlay.addPropertyChangeListener(new IPropertyChangeListener() { - public void propertyChange(PropertyChangeEvent event) { - String p = event.getProperty(); - if (p.equals(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND) - || p.equals(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) { - initializeViewerColors(preview); - } - - preview.invalidateTextPresentation(); - } - }); - - return preview.getControl(); - } - - /** - * Initializes the given viewer's colors. - * - * @param viewer - * the viewer to be initialized - */ - void initializeViewerColors(ISourceViewer viewer) { - if (overlay != null) { - StyledText styledText = viewer.getTextWidget(); - - // ---------- background color ---------------------- - Color color = null; - if (!overlay.getBoolean(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) { - color = createColor(overlay, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND, styledText.getDisplay()); - } - - styledText.setBackground(color); - - if (bgColor != null) { - bgColor.dispose(); - } - - bgColor = color; - } - } - - /** - * Creates a color from the information stored in the given preference store. Returns null if there is no such - * information available. - */ - private Color createColor(IPreferenceStore store, String key, Display display) { - RGB rgb = null; - - if (store.contains(key)) { - if (store.isDefault(key)) { - rgb = PreferenceConverter.getDefaultColor(store, key); - } else { - rgb = PreferenceConverter.getColor(store, key); - } - - if (rgb != null) { - return new Color(display, rgb); - } - } - - return null; - } - - void handleSyntaxColorListSelection() { - int i = colors.getSelectionIndex(); - - String key = fSyntaxColorListModel[i][1]; - - RGB rgb = PreferenceConverter.getColor(overlay, key + ITextStylePreferences.SUFFIX_FOREGROUND); - - fgColorEditor.setColorValue(rgb); - - // REVISIT - fgBold.setSelection(overlay.getString(key + ITextStylePreferences.SUFFIX_STYLE).indexOf(ITextStylePreferences.STYLE_BOLD) >= 0); - } - - private String loadPreviewContentFromFile(String filename) { - StringBuffer string = new StringBuffer(512); - - try { - char[] buf = new char[512]; - BufferedReader reader = new BufferedReader(new InputStreamReader(XMLSyntaxPreferencePage.class.getResourceAsStream(filename))); - - try { - while (true) { - int n = reader.read(buf); - if (n < 0) { - break; - } - - string.append(buf, 0, n); - } - } finally { - reader.close(); - } - } catch (IOException e) { - } - - return string.toString(); - } - - /** - * - */ - private void initialize() { - initializeFields(); - - for (int i = 0; i < fSyntaxColorListModel.length; i++) { - colors.add(fSyntaxColorListModel[i][0]); - } - - colors.getDisplay().asyncExec(new Runnable() { - - public void run() { - colors.select(0); - handleSyntaxColorListSelection(); - } - }); - } - - private void initializeFields() { - RGB rgb = PreferenceConverter.getColor(overlay, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND); - bgColorEditor.setColorValue(rgb); - - boolean def = overlay.getBoolean(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT); - bgDefault.setSelection(def); - bgCustom.setSelection(!def); - bgColorEditor.getButton().setEnabled(!def); - } - - /* - * @see IWorkbenchPreferencePage#init(IWorkbench) - */ - public void init(IWorkbench workbench) { - } - - /* - * @see PreferencePage#performDefaults() - */ - protected void performDefaults() { - overlay.loadDefaults(); - //initializeFields(); - handleSyntaxColorListSelection(); - - super.performDefaults(); - - preview.invalidateTextPresentation(); - } - - /* - * @see org.eclipse.jface.preference.IPreferencePage#performOk() - */ - public boolean performOk() { - overlay.propagate(); - XMLPlugin.getDefault().savePluginPreferences(); - - return true; - } - - /* - * @see org.eclipse.jface.dialogs.IDialogPage#dispose() - */ - public void dispose() { - if (xmlTextTools != null) { - xmlTextTools.dispose(); - xmlTextTools = null; - } - - if (overlay != null) { - overlay.stop(); - overlay = null; - } - - super.dispose(); - } + label = new Label(stylesComposite, SWT.LEFT); + label.setText(XMLPlugin + .getResourceString("XmlSyntaxPreferencePage.color")); //$NON-NLS-1$ + gd = new GridData(); + gd.horizontalAlignment = GridData.BEGINNING; + label.setLayoutData(gd); + + fgColorEditor = new ColorEditor(stylesComposite); + + Button fgColorButton = fgColorEditor.getButton(); + gd = new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalAlignment = GridData.BEGINNING; + fgColorButton.setLayoutData(gd); + + label = new Label(stylesComposite, SWT.LEFT); + label.setText(XMLPlugin + .getResourceString("XmlSyntaxPreferencePage.bold")); //$NON-NLS-1$ + gd = new GridData(); + gd.horizontalAlignment = GridData.BEGINNING; + label.setLayoutData(gd); + + fgBold = new Button(stylesComposite, SWT.CHECK); + gd = new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalAlignment = GridData.BEGINNING; + fgBold.setLayoutData(gd); + + label = new Label(colorComposite, SWT.LEFT); + label.setText(XMLPlugin + .getResourceString("XmlSyntaxPreferencePage.preview")); //$NON-NLS-1$ + label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + Control previewer = createPreviewer(colorComposite); + gd = new GridData(GridData.FILL_BOTH); + gd.widthHint = convertWidthInCharsToPixels(20); + gd.heightHint = convertHeightInCharsToPixels(5); + previewer.setLayoutData(gd); + + colors.addSelectionListener(new SelectionListener() { + + public void widgetDefaultSelected(SelectionEvent e) { + } + + public void widgetSelected(SelectionEvent e) { + handleSyntaxColorListSelection(); + } + }); + + bgColorEditor.getButton().addSelectionListener(new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + } + + public void widgetSelected(SelectionEvent e) { + PreferenceConverter.setValue(overlay, + AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND, + bgColorEditor.getColorValue()); + } + }); + + fgColorButton.addSelectionListener(new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + } + + public void widgetSelected(SelectionEvent e) { + int i = colors.getSelectionIndex(); + + String key = fSyntaxColorListModel[i][1]; + + PreferenceConverter.setValue(overlay, key + + ITextStylePreferences.SUFFIX_FOREGROUND, + fgColorEditor.getColorValue()); + } + }); + + fgBold.addSelectionListener(new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + } + + public void widgetSelected(SelectionEvent e) { + int i = colors.getSelectionIndex(); + + String key = fSyntaxColorListModel[i][1]; + + String value = (fgBold.getSelection()) ? ITextStylePreferences.STYLE_BOLD + : ITextStylePreferences.STYLE_NORMAL; + + overlay.setValue(key + ITextStylePreferences.SUFFIX_STYLE, + value); + } + }); + + initialize(); + + return colorComposite; + } + + private Control createPreviewer(Composite parent) { + xmlTextTools = new XMLTextTools(overlay); // REVISIT: DTD + + preview = new SourceViewer(parent, null, SWT.V_SCROLL | SWT.H_SCROLL + | SWT.BORDER); + + preview.configure(new XMLConfiguration(xmlTextTools)); + preview.getTextWidget().setFont( + JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT)); + preview.setEditable(false); + + initializeViewerColors(preview); + + String content = loadPreviewContentFromFile("preview.xml"); //$NON-NLS-1$ + IDocument document = new Document(content); + + // REVISIT: DTD + IDocumentPartitioner partitioner = xmlTextTools.createXMLPartitioner(); + + partitioner.connect(document); + document.setDocumentPartitioner(partitioner); + + preview.setDocument(document); + + overlay.addPropertyChangeListener(new IPropertyChangeListener() { + public void propertyChange(PropertyChangeEvent event) { + String p = event.getProperty(); + if (p.equals(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND) + || p + .equals(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) { + initializeViewerColors(preview); + } + + preview.invalidateTextPresentation(); + } + }); + + return preview.getControl(); + } + + /** + * Initializes the given viewer's colors. + * + * @param viewer + * the viewer to be initialized + */ + void initializeViewerColors(ISourceViewer viewer) { + if (overlay != null) { + StyledText styledText = viewer.getTextWidget(); + + // ---------- background color ---------------------- + Color color = null; + if (!overlay + .getBoolean(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) { + color = createColor(overlay, + AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND, + styledText.getDisplay()); + } + + styledText.setBackground(color); + + if (bgColor != null) { + bgColor.dispose(); + } + + bgColor = color; + } + } + + /** + * Creates a color from the information stored in the given preference + * store. Returns null if there is no such information + * available. + */ + private Color createColor(IPreferenceStore store, String key, + Display display) { + RGB rgb = null; + + if (store.contains(key)) { + if (store.isDefault(key)) { + rgb = PreferenceConverter.getDefaultColor(store, key); + } else { + rgb = PreferenceConverter.getColor(store, key); + } + + if (rgb != null) { + return new Color(display, rgb); + } + } + + return null; + } + + void handleSyntaxColorListSelection() { + int i = colors.getSelectionIndex(); + + String key = fSyntaxColorListModel[i][1]; + + RGB rgb = PreferenceConverter.getColor(overlay, key + + ITextStylePreferences.SUFFIX_FOREGROUND); + + fgColorEditor.setColorValue(rgb); + + // REVISIT + fgBold.setSelection(overlay.getString( + key + ITextStylePreferences.SUFFIX_STYLE).indexOf( + ITextStylePreferences.STYLE_BOLD) >= 0); + } + + private String loadPreviewContentFromFile(String filename) { + StringBuffer string = new StringBuffer(512); + + try { + char[] buf = new char[512]; + BufferedReader reader = new BufferedReader( + new InputStreamReader(XMLSyntaxPreferencePage.class + .getResourceAsStream(filename))); + + try { + while (true) { + int n = reader.read(buf); + if (n < 0) { + break; + } + + string.append(buf, 0, n); + } + } finally { + reader.close(); + } + } catch (IOException e) { + } + + return string.toString(); + } + + /** + * + */ + private void initialize() { + initializeFields(); + + for (int i = 0; i < fSyntaxColorListModel.length; i++) { + colors.add(fSyntaxColorListModel[i][0]); + } + + colors.getDisplay().asyncExec(new Runnable() { + + public void run() { + colors.select(0); + handleSyntaxColorListSelection(); + } + }); + } + + private void initializeFields() { + RGB rgb = PreferenceConverter.getColor(overlay, + AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND); + bgColorEditor.setColorValue(rgb); + + boolean def = overlay + .getBoolean(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT); + bgDefault.setSelection(def); + bgCustom.setSelection(!def); + bgColorEditor.getButton().setEnabled(!def); + } + + /* + * @see IWorkbenchPreferencePage#init(IWorkbench) + */ + public void init(IWorkbench workbench) { + } + + /* + * @see PreferencePage#performDefaults() + */ + protected void performDefaults() { + overlay.loadDefaults(); + // initializeFields(); + handleSyntaxColorListSelection(); + + super.performDefaults(); + + preview.invalidateTextPresentation(); + } + + /* + * @see org.eclipse.jface.preference.IPreferencePage#performOk() + */ + public boolean performOk() { + overlay.propagate(); + XMLPlugin.getDefault().savePluginPreferences(); + + return true; + } + + /* + * @see org.eclipse.jface.dialogs.IDialogPage#dispose() + */ + public void dispose() { + if (xmlTextTools != null) { + xmlTextTools.dispose(); + xmlTextTools = null; + } + + if (overlay != null) { + overlay.stop(); + overlay = null; + } + + super.dispose(); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/AbstractDocumentProvider.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/AbstractDocumentProvider.java index 67489c2..10d4fee 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/AbstractDocumentProvider.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/AbstractDocumentProvider.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: AbstractDocumentProvider.java,v 1.2 2005-05-06 00:55:41 stefanbjarni Exp $ + * $Id: AbstractDocumentProvider.java,v 1.3 2006-10-21 23:14:13 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.text; @@ -21,7 +21,6 @@ import net.sourceforge.phpeclipse.ui.editor.I18NDocumentProvider; import org.eclipse.jface.text.rules.IWhitespaceDetector; - /** * * @@ -37,41 +36,41 @@ public abstract class AbstractDocumentProvider extends I18NDocumentProvider { return "UTF-8"; } - public String getDeclaredEncoding( InputStream in ) throws IOException { - if ( !in.markSupported() ) { - in = new BufferedInputStream( in, 512 ); + public String getDeclaredEncoding(InputStream in) throws IOException { + if (!in.markSupported()) { + in = new BufferedInputStream(in, 512); } - in.mark( 512 ); - String encoding = super.getDeclaredEncoding( in ); - if ( encoding != null ) { + in.mark(512); + String encoding = super.getDeclaredEncoding(in); + if (encoding != null) { return encoding; } in.reset(); // check Prolog-Start ': - state = STATE_DEFAULT; - return getToken(XML_TAG); + case ICharacterScanner.EOF: + case '>': + state = STATE_DEFAULT; + return getToken(XML_TAG); - case '"': case '\'': - while (true) { - int ch = read(); + case '"': + case '\'': + while (true) { + int ch = read(); - if (ch == quot) { - state = STATE_TAG; - return getToken(XML_ATTRIBUTE); - } + if (ch == quot) { + state = STATE_TAG; + return getToken(XML_ATTRIBUTE); + } - switch (ch) { - case '<': - unread(); + switch (ch) { + case '<': + unread(); - case ICharacterScanner.EOF: - state = STATE_DEFAULT; - return getToken(XML_ATTRIBUTE); - } + case ICharacterScanner.EOF: + state = STATE_DEFAULT; + return getToken(XML_ATTRIBUTE); } - default: - unread(); + } + default: + unread(); } while (true) { switch (read()) { - case '<': - unread(); + case '<': + unread(); - case ICharacterScanner.EOF: - case '>': - state = STATE_DEFAULT; - return getToken(XML_TAG); + case ICharacterScanner.EOF: + case '>': + state = STATE_DEFAULT; + return getToken(XML_TAG); - case '"': case '\'': - unread(); + case '"': + case '\'': + unread(); - state = STATE_TAG; - return getToken(XML_TAG); + state = STATE_TAG; + return getToken(XML_TAG); } } } @@ -253,38 +266,38 @@ loop: private IToken nextDeclToken() { loop: while (true) { switch (read()) { - case ICharacterScanner.EOF: - state = STATE_DEFAULT; - return getToken(isInternal() ? DTD_INTERNAL_DECL : XML_DECL); + case ICharacterScanner.EOF: + state = STATE_DEFAULT; + return getToken(isInternal() ? DTD_INTERNAL_DECL : XML_DECL); - case '<': - if (parsedtd || isInternal()) { - switch (read()) { - case ICharacterScanner.EOF: - state = STATE_DEFAULT; - return getToken(isInternal() ? DTD_INTERNAL : null); - - case '!': - case '?': - unread(); - break; - - default: - continue loop; - } + case '<': + if (parsedtd || isInternal()) { + switch (read()) { + case ICharacterScanner.EOF: + state = STATE_DEFAULT; + return getToken(isInternal() ? DTD_INTERNAL : null); + + case '!': + case '?': + unread(); + break; + + default: + continue loop; } + } - unread(); + unread(); - case '>': - state &= STATE_INTERNAL; - return getToken(isInternal() ? DTD_INTERNAL_DECL : XML_DECL); + case '>': + state &= STATE_INTERNAL; + return getToken(isInternal() ? DTD_INTERNAL_DECL : XML_DECL); - case '[': // - if (!isInternal()) { - state = STATE_INTERNAL; - return getToken(XML_DECL); - } + case '[': // + if (!isInternal()) { + state = STATE_INTERNAL; + return getToken(XML_DECL); + } } } } @@ -294,24 +307,24 @@ loop: loop: while (true) { switch (read()) { + case ICharacterScanner.EOF: + break loop; + + case '-': // - --> + switch (read()) { case ICharacterScanner.EOF: break loop; - case '-': // - --> + case '-': // -- --> switch (read()) { - case ICharacterScanner.EOF: - break loop; - - case '-': // -- --> - switch (read()) { - case ICharacterScanner.EOF: - case '>': - break loop; - } - - unread(); - continue loop; + case ICharacterScanner.EOF: + case '>': + break loop; } + + unread(); + continue loop; + } } } @@ -321,28 +334,27 @@ loop: private IToken nextCDATAToken() { state = STATE_DEFAULT; -loop: - while (true) { + loop: while (true) { switch (read()) { + case ICharacterScanner.EOF: + break loop; + + case ']': // ] ]]> + switch (read()) { case ICharacterScanner.EOF: break loop; - case ']': // ] ]]> + case ']': // ]] ]]> switch (read()) { - case ICharacterScanner.EOF: - break loop; - - case ']': // ]] ]]> - switch (read()) { - case ICharacterScanner.EOF: - case '>': // ]]> - break loop; - } - - unread(); - unread(); - continue loop; + case ICharacterScanner.EOF: + case '>': // ]]> + break loop; } + + unread(); + unread(); + continue loop; + } } } @@ -354,54 +366,53 @@ loop: int level = 1; -loop: - while (true) { + loop: while (true) { switch (read()) { + case ICharacterScanner.EOF: + break loop; + + case '<': // - --> + switch (read()) { case ICharacterScanner.EOF: break loop; - case '<': // - --> + case '!': // -- --> switch (read()) { - case ICharacterScanner.EOF: - break loop; - - case '!': // -- --> - switch (read()) { - case ICharacterScanner.EOF: - break loop; - - case '[': - ++level; - continue loop; - } + case ICharacterScanner.EOF: + break loop; - unread(); - continue loop; + case '[': + ++level; + continue loop; } unread(); continue loop; + } - case ']': // - --> - switch (read()) { - case ICharacterScanner.EOF: - break loop; + unread(); + continue loop; - case ']': // -- --> - switch (read()) { - case ICharacterScanner.EOF: - case '>': - if (--level == 0) { - break loop; - } + case ']': // - --> + switch (read()) { + case ICharacterScanner.EOF: + break loop; - continue loop; - } + case ']': // -- --> + switch (read()) { + case ICharacterScanner.EOF: + case '>': + if (--level == 0) { + break loop; + } - unread(); - unread(); - continue loop; + continue loop; } + + unread(); + unread(); + continue loop; + } } } @@ -453,7 +464,7 @@ loop: * @see org.eclipse.jface.text.rules.ITokenScanner#getTokenOffset() */ public int getTokenOffset() { - Assert.isTrue(offset>=0, Integer.toString(offset)); + Assert.isTrue(offset >= 0, Integer.toString(offset)); return offset; } @@ -465,7 +476,8 @@ loop: } /* - * @see org.eclipse.jface.text.rules.ITokenScanner#setRange(IDocument, int, int) + * @see org.eclipse.jface.text.rules.ITokenScanner#setRange(IDocument, int, + * int) */ public void setRange(IDocument document, int offset, int length) { this.document = document; @@ -475,48 +487,47 @@ loop: this.position = offset; this.length = 0; - this.state = STATE_DEFAULT; + this.state = STATE_DEFAULT; } /* - * @see org.eclipse.jface.text.rules.IPartitionTokenScanner - */ -// public void setPartialRange(IDocument document, int offset, int length, String contentType, int partitionOffset) { -// state = STATE_DEFAULT; -// if (partitionOffset > -1) { -// int delta = offset - partitionOffset; -// if (delta > 0) { -// setRange(document, partitionOffset, length + delta); -// return; -// } -// } -// setRange(document, partitionOffset, length); -// } + * @see org.eclipse.jface.text.rules.IPartitionTokenScanner + */ + // public void setPartialRange(IDocument document, int offset, int length, + // String contentType, int partitionOffset) { + // state = STATE_DEFAULT; + // if (partitionOffset > -1) { + // int delta = offset - partitionOffset; + // if (delta > 0) { + // setRange(document, partitionOffset, length + delta); + // return; + // } + // } + // setRange(document, partitionOffset, length); + // } /* * @see org.eclipse.jface.text.rules.IPartitionTokenScanner */ - public void setPartialRange( - IDocument document, int offset, int length, - String contentType, int partitionOffset - ) { -// boolean flag = false; + public void setPartialRange(IDocument document, int offset, int length, + String contentType, int partitionOffset) { + // boolean flag = false; this.document = document; this.end = offset + length; // NB! Undocumented value: -1 if (partitionOffset >= 0) { offset = partitionOffset; -// flag = true; + // flag = true; } this.offset = offset; this.position = offset; this.length = 0; -// if (flag) { -// state = STATE_DEFAULT; -// return; -// } + // if (flag) { + // state = STATE_DEFAULT; + // return; + // } if (contentType == XML_ATTRIBUTE) { state = STATE_TAG; return; @@ -532,10 +543,8 @@ loop: return; } - if (contentType == DTD_INTERNAL || - contentType == DTD_INTERNAL_DECL || - contentType == DTD_INTERNAL_COMMENT - ) { + if (contentType == DTD_INTERNAL || contentType == DTD_INTERNAL_DECL + || contentType == DTD_INTERNAL_COMMENT) { state = STATE_INTERNAL; return; } @@ -550,7 +559,8 @@ loop: if (type != IDocument.DEFAULT_CONTENT_TYPE) { return true; } - } catch (BadLocationException e) {} + } catch (BadLocationException e) { + } return false; } diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/SimpleDoubleClickStrategy.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/SimpleDoubleClickStrategy.java index d61fb9e..3eb545a 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/SimpleDoubleClickStrategy.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/SimpleDoubleClickStrategy.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: SimpleDoubleClickStrategy.java,v 1.2 2005-05-06 00:55:41 stefanbjarni Exp $ + * $Id: SimpleDoubleClickStrategy.java,v 1.3 2006-10-21 23:14:13 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.text; @@ -20,7 +20,6 @@ import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.ITypedRegion; - /** * * @@ -30,33 +29,34 @@ public class SimpleDoubleClickStrategy extends TextDoubleClickStrategy { /* * @see org.eclipse.jface.text.ITextDoubleClickStrategy#doubleClicked(ITextViewer) */ - public void doubleClicked( ITextViewer viewer ) { + public void doubleClicked(ITextViewer viewer) { int offset = viewer.getSelectedRange().x; - if ( offset < 0 ) { + if (offset < 0) { return; } try { IDocument document = viewer.getDocument(); - ITypedRegion region = document.getPartition( offset ); + ITypedRegion region = document.getPartition(offset); int start = region.getOffset(); int length = region.getLength(); - if ( offset == start ) { - viewer.setSelectedRange( start, length ); + if (offset == start) { + viewer.setSelectedRange(start, length); return; } int end = start + length - 1; - if ( offset == end && document.getChar(end) == '>' ) { - viewer.setSelectedRange( start, length ); + if (offset == end && document.getChar(end) == '>') { + viewer.setSelectedRange(start, length); return; } - super.doubleClicked( viewer ); - } catch ( BadLocationException e ) {} + super.doubleClicked(viewer); + } catch (BadLocationException e) { + } } } diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/TagDoubleClickStrategy.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/TagDoubleClickStrategy.java index 696b909..3e70d8f 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/TagDoubleClickStrategy.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/TagDoubleClickStrategy.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: TagDoubleClickStrategy.java,v 1.2 2005-05-06 00:55:41 stefanbjarni Exp $ + * $Id: TagDoubleClickStrategy.java,v 1.3 2006-10-21 23:14:13 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.text; @@ -20,7 +20,6 @@ import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.ITypedRegion; - /** * * @@ -30,44 +29,44 @@ public class TagDoubleClickStrategy extends TextDoubleClickStrategy { /* * @see org.eclipse.jface.text.ITextDoubleClickStrategy#doubleClicked(ITextViewer) */ - public void doubleClicked( ITextViewer viewer ) { + public void doubleClicked(ITextViewer viewer) { int offset = viewer.getSelectedRange().x; - if ( offset < 0 ) { + if (offset < 0) { return; } try { IDocument document = viewer.getDocument(); - ITypedRegion region = document.getPartition( offset ); + ITypedRegion region = document.getPartition(offset); int start = region.getOffset(); - if ( offset == start && document.getChar(offset) == '<' ) { - region = document.getPartition( offset ); + if (offset == start && document.getChar(offset) == '<') { + region = document.getPartition(offset); offset = region.getOffset() + region.getLength(); - if ( document.getChar(offset - 1) != '>' ) { - while ( true ) { - if ( offset >= document.getLength() ) { + if (document.getChar(offset - 1) != '>') { + while (true) { + if (offset >= document.getLength()) { break; } - region = document.getPartition( offset ); + region = document.getPartition(offset); offset = region.getOffset() + region.getLength(); - if ( XMLPartitionScanner.XML_ATTRIBUTE - .equals(region.getType()) ) { + if (XMLPartitionScanner.XML_ATTRIBUTE.equals(region + .getType())) { continue; } - if ( XMLPartitionScanner.XML_TAG - .equals(region.getType()) ) { - if ( document.getChar(region.getOffset()) == '<' ) { + if (XMLPartitionScanner.XML_TAG + .equals(region.getType())) { + if (document.getChar(region.getOffset()) == '<') { break; } - if ( document.getChar(offset - 1) == '>' ) { + if (document.getChar(offset - 1) == '>') { break; } @@ -79,33 +78,33 @@ public class TagDoubleClickStrategy extends TextDoubleClickStrategy { } } - viewer.setSelectedRange( start, offset - start ); + viewer.setSelectedRange(start, offset - start); return; } int end = start + region.getLength(); - if ( offset == end - 1 && document.getChar(offset) == '>' ) { - region = document.getPartition( offset ); + if (offset == end - 1 && document.getChar(offset) == '>') { + region = document.getPartition(offset); offset = region.getOffset(); - if ( document.getChar(offset) != '<' ) { - while ( true ) { - if ( offset <= 0 ) { + if (document.getChar(offset) != '<') { + while (true) { + if (offset <= 0) { break; } - region = document.getPartition( offset - 1 ); + region = document.getPartition(offset - 1); offset = region.getOffset(); - if ( XMLPartitionScanner.XML_ATTRIBUTE - .equals(region.getType()) ) { + if (XMLPartitionScanner.XML_ATTRIBUTE.equals(region + .getType())) { continue; } - if ( XMLPartitionScanner.XML_TAG - .equals(region.getType()) ) { - if ( document.getChar(offset) == '<' ) { + if (XMLPartitionScanner.XML_TAG + .equals(region.getType())) { + if (document.getChar(offset) == '<') { break; } @@ -117,11 +116,12 @@ public class TagDoubleClickStrategy extends TextDoubleClickStrategy { } } - viewer.setSelectedRange( offset, end - offset ); + viewer.setSelectedRange(offset, end - offset); return; } - super.doubleClicked( viewer ); - } catch ( BadLocationException e ) {} + super.doubleClicked(viewer); + } catch (BadLocationException e) { + } } } diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/TextScanner.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/TextScanner.java index 6eb0912..3ef9542 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/TextScanner.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/TextScanner.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: TextScanner.java,v 1.2 2005-05-06 00:55:41 stefanbjarni Exp $ + * $Id: TextScanner.java,v 1.3 2006-10-21 23:14:13 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.text; @@ -35,7 +35,7 @@ public class TextScanner extends BufferedRuleBasedScanner { IToken entity = (Token) tokens.get(IXMLSyntaxConstants.XML_ENTITY); - IRule[] rules = { new EntityRule(startEntity, entity)}; + IRule[] rules = { new EntityRule(startEntity, entity) }; setRules(rules); } diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/WhitespaceDetector.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/WhitespaceDetector.java index 7591394..3efcc3e 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/WhitespaceDetector.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/WhitespaceDetector.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: WhitespaceDetector.java,v 1.1 2004-09-02 18:28:03 jsurfer Exp $ + * $Id: WhitespaceDetector.java,v 1.2 2006-10-21 23:14:13 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.text; @@ -27,14 +27,14 @@ public class WhitespaceDetector implements IWhitespaceDetector { */ public boolean isWhitespace(char ch) { switch (ch) { - case 0x09: - case 0x0A: - case 0x0D: - case 0x20: - return true; + case 0x09: + case 0x0A: + case 0x0D: + case 0x20: + return true; - default: - return false; + default: + return false; } } } diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLAnnotation.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLAnnotation.java index 153c7f7..fb371b8 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLAnnotation.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLAnnotation.java @@ -8,23 +8,21 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: XMLAnnotation.java,v 1.1 2004-09-02 18:28:03 jsurfer Exp $ + * $Id: XMLAnnotation.java,v 1.2 2006-10-21 23:14:13 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.text; import org.eclipse.jface.text.source.Annotation; - /** * @author Igor Malinin */ public class XMLAnnotation extends Annotation { - public static final String TYPE_ERROR = - "org.eclipse.ui.workbench.texteditor.warning"; //$NON-NLS-1$ - public static final String TYPE_WARNING = - "org.eclipse.ui.workbench.texteditor.error"; //$NON-NLS-1$ - public static final String TYPE_INFO = - "org.eclipse.ui.workbench.texteditor.info"; //$NON-NLS-1$ + public static final String TYPE_ERROR = "org.eclipse.ui.workbench.texteditor.warning"; //$NON-NLS-1$ + + public static final String TYPE_WARNING = "org.eclipse.ui.workbench.texteditor.error"; //$NON-NLS-1$ + + public static final String TYPE_INFO = "org.eclipse.ui.workbench.texteditor.info"; //$NON-NLS-1$ public XMLAnnotation(String type, boolean persistent, String text) { super(type, persistent, text); diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLAnnotationHover.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLAnnotationHover.java index 11d45ca..3e38663 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLAnnotationHover.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLAnnotationHover.java @@ -8,7 +8,7 @@ * Contributors: * Christopher Lenz - initial API and implementation * - * $Id: XMLAnnotationHover.java,v 1.1 2004-09-02 18:28:03 jsurfer Exp $ + * $Id: XMLAnnotationHover.java,v 1.2 2006-10-21 23:14:13 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.text; @@ -24,13 +24,13 @@ import org.eclipse.jface.text.source.IAnnotationHover; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.jface.text.source.ISourceViewer; - /** * Implements simple annotation hover to show the associated messages. */ public class XMLAnnotationHover implements IAnnotationHover { /* - * @see org.eclipse.jface.text.source.IAnnotationHover#getHoverInfo(org.eclipse.jface.text.source.ISourceViewer, int) + * @see org.eclipse.jface.text.source.IAnnotationHover#getHoverInfo(org.eclipse.jface.text.source.ISourceViewer, + * int) */ public String getHoverInfo(ISourceViewer sourceViewer, int lineNumber) { List annotations = getAnnotationsForLine(sourceViewer, lineNumber); @@ -69,7 +69,7 @@ public class XMLAnnotationHover implements IAnnotationHover { StringBuffer buffer = new StringBuffer(); Iterator e = messages.iterator(); - while (e.hasNext()) { + while (e.hasNext()) { buffer.append("- "); //$NON-NLS-1$ buffer.append(e.next()); buffer.append('\n'); @@ -98,8 +98,8 @@ public class XMLAnnotationHover implements IAnnotationHover { Position position = model.getPosition(a); if (position != null) { try { - int annotationLine = document - .getLineOfOffset(position.getOffset()); + int annotationLine = document.getLineOfOffset(position + .getOffset()); if (annotationLine == line) { retVal.add(a); } diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLAnnotationIterator.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLAnnotationIterator.java index 838bd66..b86dea6 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLAnnotationIterator.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLAnnotationIterator.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: XMLAnnotationIterator.java,v 1.1 2004-09-02 18:28:03 jsurfer Exp $ + * $Id: XMLAnnotationIterator.java,v 1.2 2006-10-21 23:14:13 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.text; @@ -17,7 +17,6 @@ import java.util.Iterator; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.IAnnotationModel; - /** * @author Igor Malinin */ @@ -25,11 +24,10 @@ public class XMLAnnotationIterator implements Iterator { private boolean skipIrrelevants; private Iterator iterator; + private Annotation next; - public XMLAnnotationIterator( - IAnnotationModel model, boolean skipIrrelevants - ) { + public XMLAnnotationIterator(IAnnotationModel model, boolean skipIrrelevants) { this.skipIrrelevants = skipIrrelevants; iterator = model.getAnnotationIterator(); diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLConfiguration.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLConfiguration.java index eeb3235..14a17c9 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLConfiguration.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLConfiguration.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: XMLConfiguration.java,v 1.1 2004-09-02 18:28:03 jsurfer Exp $ + * $Id: XMLConfiguration.java,v 1.2 2006-10-21 23:14:13 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.text; @@ -43,184 +43,209 @@ import org.eclipse.ui.texteditor.ITextEditor; * @author Igor Malinin */ public class XMLConfiguration extends TextSourceViewerConfiguration { - protected XMLTextTools xmlTextTools; - - private ITextDoubleClickStrategy dcsDefault; - - private ITextDoubleClickStrategy dcsSimple; - - private ITextDoubleClickStrategy dcsTag; - - private ITextDoubleClickStrategy dcsAttValue; - - /** The associated editor. */ - private ITextEditor editor; - - public XMLConfiguration(XMLTextTools tools) { - this(tools, null); - } - - public XMLConfiguration(XMLTextTools tools, ITextEditor editor) { - xmlTextTools = tools; - this.editor = editor; - dcsDefault = new TextDoubleClickStrategy(); - dcsSimple = new SimpleDoubleClickStrategy(); - dcsTag = new TagDoubleClickStrategy(); - dcsAttValue = new AttValueDoubleClickStrategy(); - } - - /* - * @see SourceViewerConfiguration#getAnnotationHover(ISourceViewer) - */ - public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) { - return new XMLAnnotationHover(); - } - - /* - * @see SourceViewerConfiguration#getTextHover(ISourceViewer, String) - */ - public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) { - if (editor != null) { - IDocumentProvider provider = editor.getDocumentProvider(); - IEditorInput input = editor.getEditorInput(); - IAnnotationModel model = provider.getAnnotationModel(input); - return new XMLTextHover(model); - } - - return super.getTextHover(sourceViewer, contentType); - } - - /* - * @see SourceViewerConfiguration#getDoubleClickStrategy(ISourceViewer, String) - */ - public ITextDoubleClickStrategy getDoubleClickStrategy(ISourceViewer sourceViewer, String contentType) { - if (XMLPartitionScanner.XML_COMMENT.equals(contentType)) { - return dcsSimple; - } - - if (XMLPartitionScanner.XML_PI.equals(contentType)) { - return dcsSimple; - } - - if (XMLPartitionScanner.XML_TAG.equals(contentType)) { - return dcsTag; - } - - if (XMLPartitionScanner.XML_ATTRIBUTE.equals(contentType)) { - return dcsAttValue; - } - - if (XMLPartitionScanner.XML_CDATA.equals(contentType)) { - return dcsSimple; - } - - if (contentType.startsWith(XMLPartitionScanner.DTD_INTERNAL)) { - return dcsSimple; - } - - return dcsDefault; - } - - /* - * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getConfiguredContentTypes(ISourceViewer) - */ - public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) { - return new String[] { IDocument.DEFAULT_CONTENT_TYPE, XMLPartitionScanner.XML_PI, XMLPartitionScanner.XML_COMMENT, - XMLPartitionScanner.XML_DECL, XMLPartitionScanner.XML_TAG, XMLPartitionScanner.XML_ATTRIBUTE, - XMLPartitionScanner.XML_CDATA, XMLPartitionScanner.DTD_INTERNAL, XMLPartitionScanner.DTD_INTERNAL_PI, - XMLPartitionScanner.DTD_INTERNAL_COMMENT, XMLPartitionScanner.DTD_INTERNAL_DECL, }; - } - - /* - * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getPresentationReconciler(ISourceViewer) - */ - public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) { - PresentationReconciler reconciler = new PresentationReconciler(); - - DefaultDamagerRepairer dr; - - dr = new DefaultDamagerRepairer(xmlTextTools.getXMLTextScanner()); - reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE); - reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE); - - dr = new DefaultDamagerRepairer(xmlTextTools.getDTDTextScanner()); - reconciler.setDamager(dr, XMLPartitionScanner.DTD_INTERNAL); - reconciler.setRepairer(dr, XMLPartitionScanner.DTD_INTERNAL); - - dr = new DefaultDamagerRepairer(xmlTextTools.getXMLPIScanner()); - - reconciler.setDamager(dr, XMLPartitionScanner.XML_PI); - reconciler.setRepairer(dr, XMLPartitionScanner.XML_PI); - reconciler.setDamager(dr, XMLPartitionScanner.DTD_INTERNAL_PI); - reconciler.setRepairer(dr, XMLPartitionScanner.DTD_INTERNAL_PI); - - dr = new DefaultDamagerRepairer(xmlTextTools.getXMLCommentScanner()); - - reconciler.setDamager(dr, XMLPartitionScanner.XML_COMMENT); - reconciler.setRepairer(dr, XMLPartitionScanner.XML_COMMENT); - reconciler.setDamager(dr, XMLPartitionScanner.DTD_INTERNAL_COMMENT); - reconciler.setRepairer(dr, XMLPartitionScanner.DTD_INTERNAL_COMMENT); - - dr = new DefaultDamagerRepairer(xmlTextTools.getXMLDeclScanner()); - - reconciler.setDamager(dr, XMLPartitionScanner.XML_DECL); - reconciler.setRepairer(dr, XMLPartitionScanner.XML_DECL); - reconciler.setDamager(dr, XMLPartitionScanner.DTD_INTERNAL_DECL); - reconciler.setRepairer(dr, XMLPartitionScanner.DTD_INTERNAL_DECL); - - dr = new DefaultDamagerRepairer(xmlTextTools.getXMLTagScanner()); - - reconciler.setDamager(dr, XMLPartitionScanner.XML_TAG); - reconciler.setRepairer(dr, XMLPartitionScanner.XML_TAG); - - dr = new DefaultDamagerRepairer(xmlTextTools.getXMLAttributeScanner()); - - reconciler.setDamager(dr, XMLPartitionScanner.XML_ATTRIBUTE); - reconciler.setRepairer(dr, XMLPartitionScanner.XML_ATTRIBUTE); - - dr = new DefaultDamagerRepairer(xmlTextTools.getXMLCDATAScanner()); - - reconciler.setDamager(dr, XMLPartitionScanner.XML_CDATA); - reconciler.setRepairer(dr, XMLPartitionScanner.XML_CDATA); - - return reconciler; - } - - /* - * @see SourceViewerConfiguration#getReconciler(ISourceViewer) - */ - public IReconciler getReconciler(ISourceViewer sourceViewer) { - if ((editor != null) && editor.isEditable()) { - MonoReconciler reconciler = new MonoReconciler(new XMLReconcilingStrategy(editor), false); - reconciler.setProgressMonitor(new NullProgressMonitor()); - reconciler.setDelay(500); - return reconciler; - } - - return null; - } - - public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { - ContentAssistant assistant = new ContentAssistant(); - assistant.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); - - IContentAssistProcessor processor = new BasicCompletionProcessor(); - assistant.setContentAssistProcessor(processor, IDocument.DEFAULT_CONTENT_TYPE); - assistant.setContentAssistProcessor(processor, XMLPartitionScanner.XML_TAG); - assistant.setContentAssistProcessor(processor, XMLPartitionScanner.XML_PI); - assistant.setContentAssistProcessor(processor, XMLPartitionScanner.XML_COMMENT); - assistant.setContentAssistProcessor(processor, XMLPartitionScanner.XML_DECL); - assistant.setContentAssistProcessor(processor, XMLPartitionScanner.XML_TAG); - assistant.setContentAssistProcessor(processor, XMLPartitionScanner.XML_ATTRIBUTE); - assistant.setContentAssistProcessor(processor, XMLPartitionScanner.XML_CDATA); - assistant.setContentAssistProcessor(processor, XMLPartitionScanner.DTD_INTERNAL); - assistant.setContentAssistProcessor(processor, XMLPartitionScanner.DTD_INTERNAL_PI); - assistant.setContentAssistProcessor(processor, XMLPartitionScanner.DTD_INTERNAL_COMMENT); - assistant.setContentAssistProcessor(processor, XMLPartitionScanner.DTD_INTERNAL_DECL); - assistant.setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE); - assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer)); - - return assistant; - } + protected XMLTextTools xmlTextTools; + + private ITextDoubleClickStrategy dcsDefault; + + private ITextDoubleClickStrategy dcsSimple; + + private ITextDoubleClickStrategy dcsTag; + + private ITextDoubleClickStrategy dcsAttValue; + + /** The associated editor. */ + private ITextEditor editor; + + public XMLConfiguration(XMLTextTools tools) { + this(tools, null); + } + + public XMLConfiguration(XMLTextTools tools, ITextEditor editor) { + xmlTextTools = tools; + this.editor = editor; + dcsDefault = new TextDoubleClickStrategy(); + dcsSimple = new SimpleDoubleClickStrategy(); + dcsTag = new TagDoubleClickStrategy(); + dcsAttValue = new AttValueDoubleClickStrategy(); + } + + /* + * @see SourceViewerConfiguration#getAnnotationHover(ISourceViewer) + */ + public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) { + return new XMLAnnotationHover(); + } + + /* + * @see SourceViewerConfiguration#getTextHover(ISourceViewer, String) + */ + public ITextHover getTextHover(ISourceViewer sourceViewer, + String contentType) { + if (editor != null) { + IDocumentProvider provider = editor.getDocumentProvider(); + IEditorInput input = editor.getEditorInput(); + IAnnotationModel model = provider.getAnnotationModel(input); + return new XMLTextHover(model); + } + + return super.getTextHover(sourceViewer, contentType); + } + + /* + * @see SourceViewerConfiguration#getDoubleClickStrategy(ISourceViewer, + * String) + */ + public ITextDoubleClickStrategy getDoubleClickStrategy( + ISourceViewer sourceViewer, String contentType) { + if (XMLPartitionScanner.XML_COMMENT.equals(contentType)) { + return dcsSimple; + } + + if (XMLPartitionScanner.XML_PI.equals(contentType)) { + return dcsSimple; + } + + if (XMLPartitionScanner.XML_TAG.equals(contentType)) { + return dcsTag; + } + + if (XMLPartitionScanner.XML_ATTRIBUTE.equals(contentType)) { + return dcsAttValue; + } + + if (XMLPartitionScanner.XML_CDATA.equals(contentType)) { + return dcsSimple; + } + + if (contentType.startsWith(XMLPartitionScanner.DTD_INTERNAL)) { + return dcsSimple; + } + + return dcsDefault; + } + + /* + * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getConfiguredContentTypes(ISourceViewer) + */ + public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) { + return new String[] { IDocument.DEFAULT_CONTENT_TYPE, + XMLPartitionScanner.XML_PI, XMLPartitionScanner.XML_COMMENT, + XMLPartitionScanner.XML_DECL, XMLPartitionScanner.XML_TAG, + XMLPartitionScanner.XML_ATTRIBUTE, + XMLPartitionScanner.XML_CDATA, + XMLPartitionScanner.DTD_INTERNAL, + XMLPartitionScanner.DTD_INTERNAL_PI, + XMLPartitionScanner.DTD_INTERNAL_COMMENT, + XMLPartitionScanner.DTD_INTERNAL_DECL, }; + } + + /* + * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getPresentationReconciler(ISourceViewer) + */ + public IPresentationReconciler getPresentationReconciler( + ISourceViewer sourceViewer) { + PresentationReconciler reconciler = new PresentationReconciler(); + + DefaultDamagerRepairer dr; + + dr = new DefaultDamagerRepairer(xmlTextTools.getXMLTextScanner()); + reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE); + reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE); + + dr = new DefaultDamagerRepairer(xmlTextTools.getDTDTextScanner()); + reconciler.setDamager(dr, XMLPartitionScanner.DTD_INTERNAL); + reconciler.setRepairer(dr, XMLPartitionScanner.DTD_INTERNAL); + + dr = new DefaultDamagerRepairer(xmlTextTools.getXMLPIScanner()); + + reconciler.setDamager(dr, XMLPartitionScanner.XML_PI); + reconciler.setRepairer(dr, XMLPartitionScanner.XML_PI); + reconciler.setDamager(dr, XMLPartitionScanner.DTD_INTERNAL_PI); + reconciler.setRepairer(dr, XMLPartitionScanner.DTD_INTERNAL_PI); + + dr = new DefaultDamagerRepairer(xmlTextTools.getXMLCommentScanner()); + + reconciler.setDamager(dr, XMLPartitionScanner.XML_COMMENT); + reconciler.setRepairer(dr, XMLPartitionScanner.XML_COMMENT); + reconciler.setDamager(dr, XMLPartitionScanner.DTD_INTERNAL_COMMENT); + reconciler.setRepairer(dr, XMLPartitionScanner.DTD_INTERNAL_COMMENT); + + dr = new DefaultDamagerRepairer(xmlTextTools.getXMLDeclScanner()); + + reconciler.setDamager(dr, XMLPartitionScanner.XML_DECL); + reconciler.setRepairer(dr, XMLPartitionScanner.XML_DECL); + reconciler.setDamager(dr, XMLPartitionScanner.DTD_INTERNAL_DECL); + reconciler.setRepairer(dr, XMLPartitionScanner.DTD_INTERNAL_DECL); + + dr = new DefaultDamagerRepairer(xmlTextTools.getXMLTagScanner()); + + reconciler.setDamager(dr, XMLPartitionScanner.XML_TAG); + reconciler.setRepairer(dr, XMLPartitionScanner.XML_TAG); + + dr = new DefaultDamagerRepairer(xmlTextTools.getXMLAttributeScanner()); + + reconciler.setDamager(dr, XMLPartitionScanner.XML_ATTRIBUTE); + reconciler.setRepairer(dr, XMLPartitionScanner.XML_ATTRIBUTE); + + dr = new DefaultDamagerRepairer(xmlTextTools.getXMLCDATAScanner()); + + reconciler.setDamager(dr, XMLPartitionScanner.XML_CDATA); + reconciler.setRepairer(dr, XMLPartitionScanner.XML_CDATA); + + return reconciler; + } + + /* + * @see SourceViewerConfiguration#getReconciler(ISourceViewer) + */ + public IReconciler getReconciler(ISourceViewer sourceViewer) { + if ((editor != null) && editor.isEditable()) { + MonoReconciler reconciler = new MonoReconciler( + new XMLReconcilingStrategy(editor), false); + reconciler.setProgressMonitor(new NullProgressMonitor()); + reconciler.setDelay(500); + return reconciler; + } + + return null; + } + + public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { + ContentAssistant assistant = new ContentAssistant(); + assistant + .setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); + + IContentAssistProcessor processor = new BasicCompletionProcessor(); + assistant.setContentAssistProcessor(processor, + IDocument.DEFAULT_CONTENT_TYPE); + assistant.setContentAssistProcessor(processor, + XMLPartitionScanner.XML_TAG); + assistant.setContentAssistProcessor(processor, + XMLPartitionScanner.XML_PI); + assistant.setContentAssistProcessor(processor, + XMLPartitionScanner.XML_COMMENT); + assistant.setContentAssistProcessor(processor, + XMLPartitionScanner.XML_DECL); + assistant.setContentAssistProcessor(processor, + XMLPartitionScanner.XML_TAG); + assistant.setContentAssistProcessor(processor, + XMLPartitionScanner.XML_ATTRIBUTE); + assistant.setContentAssistProcessor(processor, + XMLPartitionScanner.XML_CDATA); + assistant.setContentAssistProcessor(processor, + XMLPartitionScanner.DTD_INTERNAL); + assistant.setContentAssistProcessor(processor, + XMLPartitionScanner.DTD_INTERNAL_PI); + assistant.setContentAssistProcessor(processor, + XMLPartitionScanner.DTD_INTERNAL_COMMENT); + assistant.setContentAssistProcessor(processor, + XMLPartitionScanner.DTD_INTERNAL_DECL); + assistant + .setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE); + assistant + .setInformationControlCreator(getInformationControlCreator(sourceViewer)); + + return assistant; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLPartitionScanner.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLPartitionScanner.java index fd44b54..eca1657 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLPartitionScanner.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLPartitionScanner.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: XMLPartitionScanner.java,v 1.4 2006-01-15 12:24:16 bananeweizen Exp $ + * $Id: XMLPartitionScanner.java,v 1.5 2006-10-21 23:14:13 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.text; @@ -24,40 +24,54 @@ import org.eclipse.jface.text.rules.IPartitionTokenScanner; import org.eclipse.jface.text.rules.IToken; import org.eclipse.jface.text.rules.Token; - /** - * - * + * + * * @author Igor Malinin */ public class XMLPartitionScanner implements IPartitionTokenScanner { - public static final String XML_PI = "__xml_processing_instruction"; - public static final String XML_COMMENT = "__xml_comment"; - public static final String XML_DECL = "__xml_declaration"; - public static final String XML_TAG = "__xml_tag"; - public static final String XML_ATTRIBUTE = "__xml_attribute"; - public static final String XML_CDATA = "__xml_cdata"; - - public static final String DTD_INTERNAL = "__dtd_internal"; - public static final String DTD_INTERNAL_PI = "__dtd_internal_pi"; + public static final String XML_PI = "__xml_processing_instruction"; + + public static final String XML_COMMENT = "__xml_comment"; + + public static final String XML_DECL = "__xml_declaration"; + + public static final String XML_TAG = "__xml_tag"; + + public static final String XML_ATTRIBUTE = "__xml_attribute"; + + public static final String XML_CDATA = "__xml_cdata"; + + public static final String DTD_INTERNAL = "__dtd_internal"; + + public static final String DTD_INTERNAL_PI = "__dtd_internal_pi"; + public static final String DTD_INTERNAL_COMMENT = "__dtd_internal_comment"; - public static final String DTD_INTERNAL_DECL = "__dtd_internal_declaration"; - public static final String DTD_CONDITIONAL = "__dtd_conditional"; - public static final int STATE_DEFAULT = 0; - public static final int STATE_TAG = 1; - public static final int STATE_DECL = 2; - public static final int STATE_CDATA = 4; + public static final String DTD_INTERNAL_DECL = "__dtd_internal_declaration"; + + public static final String DTD_CONDITIONAL = "__dtd_conditional"; + + public static final int STATE_DEFAULT = 0; - public static final int STATE_INTERNAL = 8; + public static final int STATE_TAG = 1; + + public static final int STATE_DECL = 2; + + public static final int STATE_CDATA = 4; + + public static final int STATE_INTERNAL = 8; protected IDocument document; + protected int end; protected int offset; + protected int length; protected int position; + protected int state; protected boolean parsedtd; @@ -75,125 +89,124 @@ public class XMLPartitionScanner implements IPartitionTokenScanner { offset += length; switch (state) { - case STATE_TAG: - return nextTagToken(); + case STATE_TAG: + return nextTagToken(); - case STATE_DECL: - return nextDeclToken(); + case STATE_DECL: + return nextDeclToken(); - case STATE_CDATA: - return nextCDATAToken(); + case STATE_CDATA: + return nextCDATAToken(); } switch (read()) { + case ICharacterScanner.EOF: + state = STATE_DEFAULT; + return getToken(null); + + case '<': + switch (read()) { case ICharacterScanner.EOF: + if (parsedtd || isInternal()) { + break; + } + state = STATE_DEFAULT; - return getToken(null); + return getToken(XML_TAG); - case '<': + case '?': // ': - state = STATE_DEFAULT; - return getToken(XML_TAG); + case ICharacterScanner.EOF: + case '>': + state = STATE_DEFAULT; + return getToken(XML_TAG); - case '"': case '\'': - while (true) { - int ch = read(); + case '"': + case '\'': + while (true) { + int ch = read(); - if (ch == quot) { - state = STATE_TAG; - return getToken(XML_ATTRIBUTE); - } + if (ch == quot) { + state = STATE_TAG; + return getToken(XML_ATTRIBUTE); + } - switch (ch) { - case '<': - unread(); + switch (ch) { + case '<': + unread(); - case ICharacterScanner.EOF: - state = STATE_DEFAULT; - return getToken(XML_ATTRIBUTE); - } + case ICharacterScanner.EOF: + state = STATE_DEFAULT; + return getToken(XML_ATTRIBUTE); } - default: - unread(); + } + default: + unread(); } while (true) { switch (read()) { - case '<': - unread(); + case '<': + unread(); - case ICharacterScanner.EOF: - case '>': - state = STATE_DEFAULT; - return getToken(XML_TAG); + case ICharacterScanner.EOF: + case '>': + state = STATE_DEFAULT; + return getToken(XML_TAG); - case '"': case '\'': - unread(); + case '"': + case '\'': + unread(); - state = STATE_TAG; - return getToken(XML_TAG); + state = STATE_TAG; + return getToken(XML_TAG); } } } @@ -251,38 +266,38 @@ loop: private IToken nextDeclToken() { loop: while (true) { switch (read()) { - case ICharacterScanner.EOF: - state = STATE_DEFAULT; - return getToken(isInternal() ? DTD_INTERNAL_DECL : XML_DECL); + case ICharacterScanner.EOF: + state = STATE_DEFAULT; + return getToken(isInternal() ? DTD_INTERNAL_DECL : XML_DECL); - case '<': - if (parsedtd || isInternal()) { - switch (read()) { - case ICharacterScanner.EOF: - state = STATE_DEFAULT; - return getToken(isInternal() ? DTD_INTERNAL : null); - - case '!': - case '?': - unread(); - break; - - default: - continue loop; - } + case '<': + if (parsedtd || isInternal()) { + switch (read()) { + case ICharacterScanner.EOF: + state = STATE_DEFAULT; + return getToken(isInternal() ? DTD_INTERNAL : null); + + case '!': + case '?': + unread(); + break; + + default: + continue loop; } + } - unread(); + unread(); - case '>': - state &= STATE_INTERNAL; - return getToken(isInternal() ? DTD_INTERNAL_DECL : XML_DECL); + case '>': + state &= STATE_INTERNAL; + return getToken(isInternal() ? DTD_INTERNAL_DECL : XML_DECL); - case '[': // - if (!isInternal()) { - state = STATE_INTERNAL; - return getToken(XML_DECL); - } + case '[': // + if (!isInternal()) { + state = STATE_INTERNAL; + return getToken(XML_DECL); + } } } } @@ -292,24 +307,24 @@ loop: loop: while (true) { switch (read()) { + case ICharacterScanner.EOF: + break loop; + + case '-': // - --> + switch (read()) { case ICharacterScanner.EOF: break loop; - case '-': // - --> + case '-': // -- --> switch (read()) { - case ICharacterScanner.EOF: - break loop; - - case '-': // -- --> - switch (read()) { - case ICharacterScanner.EOF: - case '>': - break loop; - } - - unread(); - continue loop; + case ICharacterScanner.EOF: + case '>': + break loop; } + + unread(); + continue loop; + } } } @@ -321,17 +336,17 @@ loop: loop: while (true) { switch (read()) { + case ICharacterScanner.EOF: + break loop; + + case '?': // ? ?> + switch (read()) { case ICharacterScanner.EOF: + case '>': break loop; + } - case '?': // ? ?> - switch (read()) { - case ICharacterScanner.EOF: - case '>': - break loop; - } - - unread(); + unread(); } } @@ -341,28 +356,27 @@ loop: private IToken nextCDATAToken() { state = STATE_DEFAULT; -loop: - while (true) { + loop: while (true) { switch (read()) { + case ICharacterScanner.EOF: + break loop; + + case ']': // ] ]]> + switch (read()) { case ICharacterScanner.EOF: break loop; - case ']': // ] ]]> + case ']': // ]] ]]> switch (read()) { - case ICharacterScanner.EOF: - break loop; - - case ']': // ]] ]]> - switch (read()) { - case ICharacterScanner.EOF: - case '>': // ]]> - break loop; - } - - unread(); - unread(); - continue loop; + case ICharacterScanner.EOF: + case '>': // ]]> + break loop; } + + unread(); + unread(); + continue loop; + } } } @@ -374,54 +388,53 @@ loop: int level = 1; -loop: - while (true) { + loop: while (true) { switch (read()) { + case ICharacterScanner.EOF: + break loop; + + case '<': // - --> + switch (read()) { case ICharacterScanner.EOF: break loop; - case '<': // - --> + case '!': // -- --> switch (read()) { - case ICharacterScanner.EOF: - break loop; - - case '!': // -- --> - switch (read()) { - case ICharacterScanner.EOF: - break loop; - - case '[': - ++level; - continue loop; - } + case ICharacterScanner.EOF: + break loop; - unread(); - continue loop; + case '[': + ++level; + continue loop; } unread(); continue loop; + } - case ']': // - --> - switch (read()) { - case ICharacterScanner.EOF: - break loop; + unread(); + continue loop; - case ']': // -- --> - switch (read()) { - case ICharacterScanner.EOF: - case '>': - if (--level == 0) { - break loop; - } + case ']': // - --> + switch (read()) { + case ICharacterScanner.EOF: + break loop; - continue loop; - } + case ']': // -- --> + switch (read()) { + case ICharacterScanner.EOF: + case '>': + if (--level == 0) { + break loop; + } - unread(); - unread(); - continue loop; + continue loop; } + + unread(); + unread(); + continue loop; + } } } @@ -473,7 +486,7 @@ loop: * @see org.eclipse.jface.text.rules.ITokenScanner#getTokenOffset() */ public int getTokenOffset() { - Assert.isTrue(offset>=0, Integer.toString(offset)); + Assert.isTrue(offset >= 0, Integer.toString(offset)); return offset; } @@ -485,7 +498,8 @@ loop: } /* - * @see org.eclipse.jface.text.rules.ITokenScanner#setRange(IDocument, int, int) + * @see org.eclipse.jface.text.rules.ITokenScanner#setRange(IDocument, int, + * int) */ public void setRange(IDocument document, int offset, int length) { this.document = document; @@ -495,48 +509,47 @@ loop: this.position = offset; this.length = 0; - this.state = STATE_DEFAULT; + this.state = STATE_DEFAULT; } /* - * @see org.eclipse.jface.text.rules.IPartitionTokenScanner - */ -// public void setPartialRange(IDocument document, int offset, int length, String contentType, int partitionOffset) { -// state = STATE_DEFAULT; -// if (partitionOffset > -1) { -// int delta = offset - partitionOffset; -// if (delta > 0) { -// setRange(document, partitionOffset, length + delta); -// return; -// } -// } -// setRange(document, partitionOffset, length); -// } + * @see org.eclipse.jface.text.rules.IPartitionTokenScanner + */ + // public void setPartialRange(IDocument document, int offset, int length, + // String contentType, int partitionOffset) { + // state = STATE_DEFAULT; + // if (partitionOffset > -1) { + // int delta = offset - partitionOffset; + // if (delta > 0) { + // setRange(document, partitionOffset, length + delta); + // return; + // } + // } + // setRange(document, partitionOffset, length); + // } /* * @see org.eclipse.jface.text.rules.IPartitionTokenScanner */ - public void setPartialRange( - IDocument document, int offset, int length, - String contentType, int partitionOffset - ) { -// boolean flag = false; + public void setPartialRange(IDocument document, int offset, int length, + String contentType, int partitionOffset) { + // boolean flag = false; this.document = document; this.end = offset + length; // NB! Undocumented value: -1 if (partitionOffset >= 0) { offset = partitionOffset; -// flag = true; + // flag = true; } this.offset = offset; this.position = offset; this.length = 0; -// if (flag) { -// state = STATE_DEFAULT; -// return; -// } + // if (flag) { + // state = STATE_DEFAULT; + // return; + // } if (contentType == XML_ATTRIBUTE) { state = STATE_TAG; return; @@ -552,11 +565,9 @@ loop: return; } - if (contentType == DTD_INTERNAL || - contentType == DTD_INTERNAL_PI || - contentType == DTD_INTERNAL_DECL || - contentType == DTD_INTERNAL_COMMENT - ) { + if (contentType == DTD_INTERNAL || contentType == DTD_INTERNAL_PI + || contentType == DTD_INTERNAL_DECL + || contentType == DTD_INTERNAL_COMMENT) { state = STATE_INTERNAL; return; } @@ -571,7 +582,8 @@ loop: if (type != IDocument.DEFAULT_CONTENT_TYPE) { return true; } - } catch (BadLocationException e) {} + } catch (BadLocationException e) { + } return false; } diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLReconcileStep.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLReconcileStep.java index 3b54d70..4bfbac7 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLReconcileStep.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLReconcileStep.java @@ -8,7 +8,7 @@ * Contributors: * Christopher Lenz - initial API and implementation * - * $Id: XMLReconcileStep.java,v 1.1 2004-09-02 18:28:03 jsurfer Exp $ + * $Id: XMLReconcileStep.java,v 1.2 2006-10-21 23:14:13 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.text; @@ -95,13 +95,14 @@ public class XMLReconcileStep extends AbstractReconcileStep { */ private class ProblemAdapter extends AnnotationAdapter { private IProblem problem; + private Position position; - public ProblemAdapter(IProblem problem) { + public ProblemAdapter(IProblem problem) { this.problem = problem; } - public Position getPosition() { + public Position getPosition() { if (position == null) { position = createPositionFromProblem(); } @@ -168,8 +169,10 @@ public class XMLReconcileStep extends AbstractReconcileStep { /** * Constructor. * - * @param step the step to add to the pipe - * @param editor the associated text editor + * @param step + * the step to add to the pipe + * @param editor + * the associated text editor */ public XMLReconcileStep(IReconcileStep step, ITextEditor editor) { super(step); @@ -184,21 +187,19 @@ public class XMLReconcileStep extends AbstractReconcileStep { /* * @see AbstractReconcileStep#reconcileModel(DirtyRegion, IRegion) */ - protected IReconcileResult[] reconcileModel( - DirtyRegion dirtyRegion, IRegion subRegion - ) { + protected IReconcileResult[] reconcileModel(DirtyRegion dirtyRegion, + IRegion subRegion) { IXMLDocument model = xmlDocumentAdapter.getDocument(); - IEditorInput editorInput = null; IFile file = null; - if (editor != null) { - editorInput = editor.getEditorInput(); - } + if (editor != null) { + editorInput = editor.getEditorInput(); + } - if (editorInput instanceof IFileEditorInput) - file = ((IFileEditorInput) editorInput).getFile(); - ProblemCollector problemCollector = new ProblemCollector(); + if (editorInput instanceof IFileEditorInput) + file = ((IFileEditorInput) editorInput).getFile(); + ProblemCollector problemCollector = new ProblemCollector(); model.reconcile(problemCollector, file); List problems = problemCollector.getProblems(); @@ -226,8 +227,7 @@ public class XMLReconcileStep extends AbstractReconcileStep { private IXMLDocument getXMLDocument() { IDocumentProvider documentProvider = editor.getDocumentProvider(); if (documentProvider instanceof XMLDocumentProvider) { - XMLDocumentProvider xmlDocumentProvider = - (XMLDocumentProvider) documentProvider; + XMLDocumentProvider xmlDocumentProvider = (XMLDocumentProvider) documentProvider; return xmlDocumentProvider.getModel(editor.getEditorInput()); } diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLReconcilingStrategy.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLReconcilingStrategy.java index 9ee1eba..47a7798 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLReconcilingStrategy.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLReconcilingStrategy.java @@ -8,11 +8,10 @@ * Contributors: * Christopher Lenz - initial API and implementation * - * $Id: XMLReconcilingStrategy.java,v 1.2 2005-05-06 00:55:41 stefanbjarni Exp $ + * $Id: XMLReconcilingStrategy.java,v 1.3 2006-10-21 23:14:13 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.text; - import java.lang.reflect.InvocationTargetException; import java.util.Iterator; @@ -38,8 +37,8 @@ import org.eclipse.ui.texteditor.ITextEditor; * Reconciling strategy for XML document. This class is responsible for keeping * the parsed model in sync with the text. */ -public class XMLReconcilingStrategy - implements IReconcilingStrategy, IReconcilingStrategyExtension { +public class XMLReconcilingStrategy implements IReconcilingStrategy, + IReconcilingStrategyExtension { // Instance Variables ------------------------------------------------------ @@ -88,7 +87,7 @@ public class XMLReconcilingStrategy */ public void setDocument(IDocument document) { // FIXME - firstStep.setInputModel(null); //new DocumentAdapter(document); + firstStep.setInputModel(null); // new DocumentAdapter(document); } // IReconcilingStrategyExtension Implementation ---------------------------- @@ -115,7 +114,7 @@ public class XMLReconcilingStrategy * * @return the annotation model */ - IAnnotationModel getAnnotationModel() { + IAnnotationModel getAnnotationModel() { IEditorInput input = editor.getEditorInput(); return editor.getDocumentProvider().getAnnotationModel(input); } @@ -130,10 +129,9 @@ public class XMLReconcilingStrategy IRunnableWithProgress runnable = new WorkspaceModifyOperation() { protected void execute(IProgressMonitor monitor) { - for (int i = 0; i < results.length; i++) { - if ((progressMonitor != null) && - (progressMonitor.isCanceled())) - { + for (int i = 0; i < results.length; i++) { + if ((progressMonitor != null) + && (progressMonitor.isCanceled())) { return; } @@ -162,11 +160,11 @@ public class XMLReconcilingStrategy /* * TODO A "real" implementation must be smarter, i.e. don't remove and add - * the annotations which are the same. - */ + * the annotations which are the same. + */ private void removeTemporaryAnnotations() { Iterator i = getAnnotationModel().getAnnotationIterator(); - while (i.hasNext()) { + while (i.hasNext()) { Annotation annotation = (Annotation) i.next(); if (!annotation.isPersistent()) { getAnnotationModel().removeAnnotation(annotation); diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLTagRule.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLTagRule.java index 7c4c4f7..da8fa87 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLTagRule.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLTagRule.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: XMLTagRule.java,v 1.1 2004-09-02 18:28:03 jsurfer Exp $ + * $Id: XMLTagRule.java,v 1.2 2006-10-21 23:14:13 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.text; @@ -53,12 +53,12 @@ public class XMLTagRule implements IRule { } loop: while (true) { switch (ch) { - case ICharacterScanner.EOF: - case 0x09: - case 0x0A: - case 0x0D: - case 0x20: - break loop; + case ICharacterScanner.EOF: + case 0x09: + case 0x0A: + case 0x0D: + case 0x20: + break loop; } ch = scanner.read(); diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLTagScanner.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLTagScanner.java index 991212e..f0ef3d1 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLTagScanner.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLTagScanner.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: XMLTagScanner.java,v 1.2 2005-05-06 00:55:41 stefanbjarni Exp $ + * $Id: XMLTagScanner.java,v 1.3 2006-10-21 23:14:13 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.text; @@ -32,14 +32,14 @@ public class XMLTagScanner extends BufferedRuleBasedScanner { * Creates a color token scanner. */ public XMLTagScanner(Map tokens) { - setDefaultReturnToken((Token) tokens.get( - IXMLSyntaxConstants.XML_DEFAULT)); + setDefaultReturnToken((Token) tokens + .get(IXMLSyntaxConstants.XML_DEFAULT)); IToken tag = (Token) tokens.get(IXMLSyntaxConstants.XML_TAG); IToken attribute = (Token) tokens.get(IXMLSyntaxConstants.XML_ATT_NAME); IRule[] rules = { new XMLTagRule(tag), - new WordRule(new NameDetector(), attribute),}; + new WordRule(new NameDetector(), attribute), }; setRules(rules); } diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLTextHover.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLTextHover.java index 29a61dc..998f415 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLTextHover.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLTextHover.java @@ -8,7 +8,7 @@ * Contributors: * Christopher Lenz - initial API and implementation * - * $Id: XMLTextHover.java,v 1.1 2004-09-02 18:28:03 jsurfer Exp $ + * $Id: XMLTextHover.java,v 1.2 2006-10-21 23:14:13 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.text; @@ -21,7 +21,6 @@ import org.eclipse.jface.text.Position; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.IAnnotationModel; - /** * Implements simple annotation hover to show the associated messages. */ @@ -34,12 +33,13 @@ public class XMLTextHover implements ITextHover { /** * Creates a new annotation hover. * - * @param model this hover's annotation model + * @param model + * this hover's annotation model */ - public XMLTextHover(IAnnotationModel model) { + public XMLTextHover(IAnnotationModel model) { this.model = model; } - + /* * @see ITextHover#getHoverInfo(ITextViewer, IRegion) */ diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLWordFinder.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLWordFinder.java index 7348ff5..4e2fbd8 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLWordFinder.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLWordFinder.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial implementation * - * $Id: XMLWordFinder.java,v 1.1 2004-09-02 18:28:03 jsurfer Exp $ + * $Id: XMLWordFinder.java,v 1.2 2006-10-21 23:14:13 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.internal.text; @@ -17,7 +17,6 @@ import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.Region; - /** * * diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/text/DTDTextTools.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/text/DTDTextTools.java index 032b700..bb2fbbc 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/text/DTDTextTools.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/text/DTDTextTools.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: DTDTextTools.java,v 1.2 2005-05-06 00:55:41 stefanbjarni Exp $ + * $Id: DTDTextTools.java,v 1.3 2006-10-21 23:14:13 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.text; @@ -27,30 +27,21 @@ import org.eclipse.jface.text.rules.DefaultPartitioner; import org.eclipse.jface.text.rules.IPartitionTokenScanner; import org.eclipse.jface.text.rules.RuleBasedScanner; - /** * * * @author Igor Malinin */ public class DTDTextTools extends AbstractTextTools { - private static final String[] TOKENS = { - IXMLSyntaxConstants.XML_DEFAULT, - IXMLSyntaxConstants.XML_ATT_NAME, - IXMLSyntaxConstants.XML_ATT_VALUE, - IXMLSyntaxConstants.XML_ENTITY, - IXMLSyntaxConstants.XML_PI, - IXMLSyntaxConstants.XML_COMMENT, - IXMLSyntaxConstants.XML_DECL, - IXMLSyntaxConstants.DTD_CONDITIONAL, - }; - - private static final String[] TYPES = { - XMLPartitionScanner.XML_PI, - XMLPartitionScanner.XML_COMMENT, - XMLPartitionScanner.XML_DECL, - XMLPartitionScanner.DTD_CONDITIONAL, - }; + private static final String[] TOKENS = { IXMLSyntaxConstants.XML_DEFAULT, + IXMLSyntaxConstants.XML_ATT_NAME, + IXMLSyntaxConstants.XML_ATT_VALUE, IXMLSyntaxConstants.XML_ENTITY, + IXMLSyntaxConstants.XML_PI, IXMLSyntaxConstants.XML_COMMENT, + IXMLSyntaxConstants.XML_DECL, IXMLSyntaxConstants.DTD_CONDITIONAL, }; + + private static final String[] TYPES = { XMLPartitionScanner.XML_PI, + XMLPartitionScanner.XML_COMMENT, XMLPartitionScanner.XML_DECL, + XMLPartitionScanner.DTD_CONDITIONAL, }; /** The DTD partitions scanner */ private XMLPartitionScanner dtdPartitionScanner; @@ -64,7 +55,7 @@ public class DTDTextTools extends AbstractTextTools { /** The XML processing instructions scanner */ private SingleTokenScanner xmlPIScanner; - /** The XML comments scanner */ + /** The XML comments scanner */ private SingleTokenScanner xmlCommentScanner; /** The XML declarations scanner */ @@ -73,33 +64,33 @@ public class DTDTextTools extends AbstractTextTools { /** * Creates a new DTD text tools collection. */ - public DTDTextTools( IPreferenceStore store ) { - super( store, TOKENS ); + public DTDTextTools(IPreferenceStore store) { + super(store, TOKENS); - dtdPartitionScanner = new XMLPartitionScanner( true ); + dtdPartitionScanner = new XMLPartitionScanner(true); Map tokens = getTokens(); - dtdTextScanner = new TextScanner( - tokens, '%', IXMLSyntaxConstants.XML_DEFAULT ); + dtdTextScanner = new TextScanner(tokens, '%', + IXMLSyntaxConstants.XML_DEFAULT); - dtdConditionalScanner = new SingleTokenScanner( - tokens, IXMLSyntaxConstants.DTD_CONDITIONAL ); //cond + dtdConditionalScanner = new SingleTokenScanner(tokens, + IXMLSyntaxConstants.DTD_CONDITIONAL); // cond - xmlPIScanner = new SingleTokenScanner( - tokens, IXMLSyntaxConstants.XML_PI ); + xmlPIScanner = new SingleTokenScanner(tokens, + IXMLSyntaxConstants.XML_PI); - xmlCommentScanner = new SingleTokenScanner( - tokens, IXMLSyntaxConstants.XML_COMMENT ); + xmlCommentScanner = new SingleTokenScanner(tokens, + IXMLSyntaxConstants.XML_COMMENT); - xmlDeclScanner = new DeclScanner( tokens ); + xmlDeclScanner = new DeclScanner(tokens); } /** * */ public IDocumentPartitioner createDTDPartitioner() { - return new DefaultPartitioner( dtdPartitionScanner, TYPES ); + return new DefaultPartitioner(dtdPartitionScanner, TYPES); } /** @@ -112,27 +103,26 @@ public class DTDTextTools extends AbstractTextTools { /** * Returns a scanner which is configured to scan DTD text. * - * @return an DTD text scanner + * @return an DTD text scanner */ public RuleBasedScanner getDTDTextScanner() { return dtdTextScanner; } /** - * Returns a scanner which is configured to scan DTD - * conditional sections. + * Returns a scanner which is configured to scan DTD conditional sections. * - * @return an DTD conditional section scanner + * @return an DTD conditional section scanner */ public RuleBasedScanner getDTDConditionalScanner() { return dtdConditionalScanner; } /** - * Returns a scanner which is configured to scan XML - * processing instructions. + * Returns a scanner which is configured to scan XML processing + * instructions. * - * @return an XML processing instruction scanner + * @return an XML processing instruction scanner */ public RuleBasedScanner getXMLPIScanner() { return xmlPIScanner; @@ -141,7 +131,7 @@ public class DTDTextTools extends AbstractTextTools { /** * Returns a scanner which is configured to scan XML comments. * - * @return an XML comment scanner + * @return an XML comment scanner */ public RuleBasedScanner getXMLCommentScanner() { return xmlCommentScanner; @@ -150,7 +140,7 @@ public class DTDTextTools extends AbstractTextTools { /** * Returns a scanner which is configured to scan XML declarations. * - * @return an XML declaration scanner + * @return an XML declaration scanner */ public RuleBasedScanner getXMLDeclScanner() { return xmlDeclScanner; diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/text/IXMLSyntaxConstants.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/text/IXMLSyntaxConstants.java index e279c65..7f3e194 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/text/IXMLSyntaxConstants.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/text/IXMLSyntaxConstants.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: IXMLSyntaxConstants.java,v 1.1 2004-09-02 18:28:03 jsurfer Exp $ + * $Id: IXMLSyntaxConstants.java,v 1.2 2006-10-21 23:14:13 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.text; @@ -19,8 +19,8 @@ package net.sourceforge.phpeclipse.xml.ui.text; public interface IXMLSyntaxConstants { /** - * Note: This constant is for internal use only. Clients should not use - * this constant. The prefix all color constants start with. + * Note: This constant is for internal use only. Clients should not use this + * constant. The prefix all color constants start with. */ String PREFIX = "xml_"; //$NON-NLS-1$ @@ -53,7 +53,7 @@ public interface IXMLSyntaxConstants { /** The style key for external DTD conditional sections. */ String DTD_CONDITIONAL = PREFIX + "conditional"; //$NON-NLS-1$ - + /** The style key for SMARTY tag names. */ String XML_SMARTY = PREFIX + "smarty"; //$NON-NLS-1$ } diff --git a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/text/XMLTextTools.java b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/text/XMLTextTools.java index 8d05650..5c6d32b 100644 --- a/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/text/XMLTextTools.java +++ b/net.sourceforge.phpeclipse.xml.ui/src/net/sourceforge/phpeclipse/xml/ui/text/XMLTextTools.java @@ -8,7 +8,7 @@ * Contributors: * Igor Malinin - initial contribution * - * $Id: XMLTextTools.java,v 1.3 2005-05-15 23:23:02 axelcl Exp $ + * $Id: XMLTextTools.java,v 1.4 2006-10-21 23:14:13 pombredanne Exp $ */ package net.sourceforge.phpeclipse.xml.ui.text; @@ -30,7 +30,6 @@ import org.eclipse.jface.text.rules.DefaultPartitioner; import org.eclipse.jface.text.rules.ITokenScanner; import org.eclipse.jface.text.rules.RuleBasedScanner; - /** * * @@ -38,37 +37,27 @@ import org.eclipse.jface.text.rules.RuleBasedScanner; */ public class XMLTextTools extends AbstractTextTools { /** Text Attributes for XML editors */ - public static final String[] TOKENS = { - IXMLSyntaxConstants.XML_DEFAULT, - IXMLSyntaxConstants.XML_TAG, - IXMLSyntaxConstants.XML_ATT_NAME, - IXMLSyntaxConstants.XML_ATT_VALUE, - IXMLSyntaxConstants.XML_ENTITY, - IXMLSyntaxConstants.XML_PI, - IXMLSyntaxConstants.XML_CDATA, - IXMLSyntaxConstants.XML_COMMENT, - IXMLSyntaxConstants.XML_SMARTY, - IXMLSyntaxConstants.XML_DECL, - }; + public static final String[] TOKENS = { IXMLSyntaxConstants.XML_DEFAULT, + IXMLSyntaxConstants.XML_TAG, IXMLSyntaxConstants.XML_ATT_NAME, + IXMLSyntaxConstants.XML_ATT_VALUE, IXMLSyntaxConstants.XML_ENTITY, + IXMLSyntaxConstants.XML_PI, IXMLSyntaxConstants.XML_CDATA, + IXMLSyntaxConstants.XML_COMMENT, IXMLSyntaxConstants.XML_SMARTY, + IXMLSyntaxConstants.XML_DECL, }; /** Content types for XML editors */ - public static final String[] TYPES = { - XMLPartitionScanner.XML_PI, - XMLPartitionScanner.XML_COMMENT, - XMLPartitionScanner.XML_DECL, - XMLPartitionScanner.XML_TAG, - XMLPartitionScanner.XML_ATTRIBUTE, - XMLPartitionScanner.XML_CDATA, - XMLPartitionScanner.DTD_INTERNAL, - XMLPartitionScanner.DTD_INTERNAL_PI, - XMLPartitionScanner.DTD_INTERNAL_COMMENT, - XMLPartitionScanner.DTD_INTERNAL_DECL, - }; + public static final String[] TYPES = { XMLPartitionScanner.XML_PI, + XMLPartitionScanner.XML_COMMENT, XMLPartitionScanner.XML_DECL, + XMLPartitionScanner.XML_TAG, XMLPartitionScanner.XML_ATTRIBUTE, + XMLPartitionScanner.XML_CDATA, XMLPartitionScanner.DTD_INTERNAL, + XMLPartitionScanner.DTD_INTERNAL_PI, + XMLPartitionScanner.DTD_INTERNAL_COMMENT, + XMLPartitionScanner.DTD_INTERNAL_DECL, }; /** The XML partitions scanner */ - private XMLPartitionScanner xmlPartitionScanner; - + private XMLPartitionScanner xmlPartitionScanner; + private PHPXMLPartitionScanner phpXMLPartitionScanner; + /** The XML text scanner */ private TextScanner xmlTextScanner; @@ -87,68 +76,69 @@ public class XMLTextTools extends AbstractTextTools { /** The XML processing instructions scanner */ private SingleTokenScanner xmlPIScanner; - /** The XML comments scanner */ + /** The XML comments scanner */ private SingleTokenScanner xmlCommentScanner; /** The XML declarations scanner */ private DeclScanner xmlDeclScanner; - public XMLTextTools( IPreferenceStore store ) { - this( store, TOKENS ); + + public XMLTextTools(IPreferenceStore store) { + this(store, TOKENS); } + /** * Creates a new XML text tools collection. */ - public XMLTextTools( IPreferenceStore store, String[] strTokens ) { - super( store, strTokens ); + public XMLTextTools(IPreferenceStore store, String[] strTokens) { + super(store, strTokens); - xmlPartitionScanner = new XMLPartitionScanner( false ); - phpXMLPartitionScanner = new PHPXMLPartitionScanner( false ); + xmlPartitionScanner = new XMLPartitionScanner(false); + phpXMLPartitionScanner = new PHPXMLPartitionScanner(false); Map tokens = getTokens(); - xmlTextScanner = new TextScanner( - tokens, '&', IXMLSyntaxConstants.XML_DEFAULT ); + xmlTextScanner = new TextScanner(tokens, '&', + IXMLSyntaxConstants.XML_DEFAULT); - dtdTextScanner = new TextScanner( - tokens, '%', IXMLSyntaxConstants.XML_DEFAULT ); + dtdTextScanner = new TextScanner(tokens, '%', + IXMLSyntaxConstants.XML_DEFAULT); - xmlPIScanner = new SingleTokenScanner( - tokens, IXMLSyntaxConstants.XML_PI ); + xmlPIScanner = new SingleTokenScanner(tokens, + IXMLSyntaxConstants.XML_PI); - xmlCommentScanner = new SingleTokenScanner( - tokens, IXMLSyntaxConstants.XML_COMMENT ); + xmlCommentScanner = new SingleTokenScanner(tokens, + IXMLSyntaxConstants.XML_COMMENT); - xmlDeclScanner = new DeclScanner( tokens ); + xmlDeclScanner = new DeclScanner(tokens); - xmlTagScanner = new XMLTagScanner( tokens ); + xmlTagScanner = new XMLTagScanner(tokens); - xmlAttributeScanner = new TextScanner( - tokens, '&', IXMLSyntaxConstants.XML_ATT_VALUE ); + xmlAttributeScanner = new TextScanner(tokens, '&', + IXMLSyntaxConstants.XML_ATT_VALUE); - xmlCDATAScanner = new XMLCDATAScanner( tokens ); + xmlCDATAScanner = new XMLCDATAScanner(tokens); } /** * */ public IDocumentPartitioner createXMLPartitioner() { - return new DefaultPartitioner( xmlPartitionScanner, TYPES ); + return new DefaultPartitioner(xmlPartitionScanner, TYPES); } public IDocumentPartitioner createPHPXMLPartitioner() { - return new DefaultPartitioner( phpXMLPartitionScanner, TYPES ); + return new DefaultPartitioner(phpXMLPartitionScanner, TYPES); } - + /** * */ -// public IPartitionTokenScanner getXMLPartitionScanner() { -// return xmlPartitionScanner; -// } - + // public IPartitionTokenScanner getXMLPartitionScanner() { + // return xmlPartitionScanner; + // } /** * Returns a scanner which is configured to scan XML text. * - * @return an XML text scanner + * @return an XML text scanner */ public RuleBasedScanner getXMLTextScanner() { return xmlTextScanner; @@ -157,7 +147,7 @@ public class XMLTextTools extends AbstractTextTools { /** * Returns a scanner which is configured to scan DTD text. * - * @return an DTD text scanner + * @return an DTD text scanner */ public RuleBasedScanner getDTDTextScanner() { return dtdTextScanner; @@ -166,7 +156,7 @@ public class XMLTextTools extends AbstractTextTools { /** * Returns a scanner which is configured to scan XML tags. * - * @return an XML tag scanner + * @return an XML tag scanner */ public RuleBasedScanner getXMLTagScanner() { return xmlTagScanner; @@ -175,7 +165,7 @@ public class XMLTextTools extends AbstractTextTools { /** * Returns a scanner which is configured to scan XML tag attributes. * - * @return an XML tag attribute scanner + * @return an XML tag attribute scanner */ public RuleBasedScanner getXMLAttributeScanner() { return xmlAttributeScanner; @@ -184,17 +174,17 @@ public class XMLTextTools extends AbstractTextTools { /** * Returns a scanner which is configured to scan XML CDATA sections. * - * @return an XML CDATA section scanner + * @return an XML CDATA section scanner */ public ITokenScanner getXMLCDATAScanner() { return xmlCDATAScanner; } /** - * Returns a scanner which is configured to scan XML - * processing instructions. + * Returns a scanner which is configured to scan XML processing + * instructions. * - * @return an XML processing instruction scanner + * @return an XML processing instruction scanner */ public RuleBasedScanner getXMLPIScanner() { return xmlPIScanner; @@ -203,7 +193,7 @@ public class XMLTextTools extends AbstractTextTools { /** * Returns a scanner which is configured to scan XML comments. * - * @return an XML comment scanner + * @return an XML comment scanner */ public RuleBasedScanner getXMLCommentScanner() { return xmlCommentScanner; @@ -212,7 +202,7 @@ public class XMLTextTools extends AbstractTextTools { /** * Returns a scanner which is configured to scan XML declarations. * - * @return an XML declaration scanner + * @return an XML declaration scanner */ public RuleBasedScanner getXMLDeclScanner() { return xmlDeclScanner; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/BufferChangedEvent.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/BufferChangedEvent.java index 2b030b5..b178c4c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/BufferChangedEvent.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/BufferChangedEvent.java @@ -16,31 +16,31 @@ import java.util.EventObject; * A buffer changed event describes how a buffer has changed. These events are * used in IBufferChangedListener notifications. *

    - * For text insertions, getOffset is the offset - * of the first inserted character, getText is the - * inserted text, and getLength is 0. + * For text insertions, getOffset is the offset of the first + * inserted character, getText is the inserted text, and + * getLength is 0. *

    *

    - * For text removals, getOffset is the offset - * of the first removed character, getText is null, - * and getLength is the length of the text that was removed. + * For text removals, getOffset is the offset of the first + * removed character, getText is null, and + * getLength is the length of the text that was removed. *

    *

    - * For replacements (including IBuffer.setContents), - * getOffset is the offset - * of the first replaced character, getText is the replacement - * text, and getLength is the length of the original text - * that was replaced. + * For replacements (including IBuffer.setContents), + * getOffset is the offset of the first replaced character, + * getText is the replacement text, and getLength + * is the length of the original text that was replaced. *

    *

    - * When a buffer is closed, getOffset is 0, getLength - * is 0, and getText is null. + * When a buffer is closed, getOffset is 0, + * getLength is 0, and getText is + * null. *

    *

    * This class is not intended to be instantiated or subclassed by clients. * Instances of this class are automatically created by the Java model. *

    - * + * * @see IBuffer */ public class BufferChangedEvent extends EventObject { @@ -60,55 +60,65 @@ public class BufferChangedEvent extends EventObject { */ private String text; -/** - * Creates a new buffer changed event indicating that the given buffer has changed. - * - * @param buffer the given buffer - * @param offset the given offset - * @param length the given length - * @param text the given text - */ -public BufferChangedEvent(IBuffer buffer, int offset, int length, String text) { - super(buffer); - this.offset = offset; - this.length = length; - this.text = text; -} -/** - * Returns the buffer which has changed. - * - * @return the buffer affected by the change - */ -public IBuffer getBuffer() { - return (IBuffer) source; -} -/** - * Returns the length of text removed or replaced in the buffer, or - * 0 if text has been inserted into the buffer. - * - * @return the length of the original text fragment modified by the - * buffer change ( 0 in case of insertion). - */ -public int getLength() { - return this.length; -} -/** - * Returns the index of the first character inserted, removed, or replaced - * in the buffer. - * - * @return the source offset of the textual manipulation in the buffer - */ -public int getOffset() { - return this.offset; -} -/** - * Returns the text that was inserted, the replacement text, - * or null if text has been removed. - * - * @return the text corresponding to the buffer change ( null - * in case of deletion). - */ -public String getText() { - return this.text; -} + /** + * Creates a new buffer changed event indicating that the given buffer has + * changed. + * + * @param buffer + * the given buffer + * @param offset + * the given offset + * @param length + * the given length + * @param text + * the given text + */ + public BufferChangedEvent(IBuffer buffer, int offset, int length, + String text) { + super(buffer); + this.offset = offset; + this.length = length; + this.text = text; + } + + /** + * Returns the buffer which has changed. + * + * @return the buffer affected by the change + */ + public IBuffer getBuffer() { + return (IBuffer) source; + } + + /** + * Returns the length of text removed or replaced in the buffer, or 0 if + * text has been inserted into the buffer. + * + * @return the length of the original text fragment modified by the buffer + * change ( 0 in case of insertion). + */ + public int getLength() { + return this.length; + } + + /** + * Returns the index of the first character inserted, removed, or replaced + * in the buffer. + * + * @return the source offset of the textual manipulation in the buffer + */ + public int getOffset() { + return this.offset; + } + + /** + * Returns the text that was inserted, the replacement text, or + * null if text has been removed. + * + * @return the text corresponding to the buffer change ( null + * in case of deletion). + */ + public String getText() { + return this.text; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ClasspathVariableInitializer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ClasspathVariableInitializer.java index 38a8934..a8fd2f2 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ClasspathVariableInitializer.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ClasspathVariableInitializer.java @@ -19,36 +19,37 @@ import org.eclipse.core.runtime.IProgressMonitor; * Classpath variable initializers are used in conjunction with the * "net.sourceforge.phpdt.core.classpathVariableInitializer" extension point. *

    - * Clients should subclass this class to implement a specific classpath - * variable initializer. The subclass must have a public 0-argument - * constructor and a concrete implementation of initialize. + * Clients should subclass this class to implement a specific classpath variable + * initializer. The subclass must have a public 0-argument constructor and a + * concrete implementation of initialize. * * @see IClasspathEntry * @since 2.0 */ public abstract class ClasspathVariableInitializer { - /** - * Creates a new classpath variable initializer. - */ - public ClasspathVariableInitializer() { - } + /** + * Creates a new classpath variable initializer. + */ + public ClasspathVariableInitializer() { + } - /** - * Binds a value to the workspace classpath variable with the given name, - * or fails silently if this cannot be done. - *

    - * A variable initializer is automatically activated whenever a variable value - * is needed and none has been recorded so far. The implementation of - * the initializer can set the corresponding variable using - * JavaCore#setClasspathVariable. - * - * @param variable the name of the workspace classpath variable - * that requires a binding - * - * @see JavaCore#getClasspathVariable(String) - * @see JavaCore#setClasspathVariable(String, IPath, IProgressMonitor) - * @see JavaCore#setClasspathVariables(String[], IPath[], IProgressMonitor) - */ - public abstract void initialize(String variable); + /** + * Binds a value to the workspace classpath variable with the given name, or + * fails silently if this cannot be done. + *

    + * A variable initializer is automatically activated whenever a variable + * value is needed and none has been recorded so far. The implementation of + * the initializer can set the corresponding variable using + * JavaCore#setClasspathVariable. + * + * @param variable + * the name of the workspace classpath variable that requires a + * binding + * + * @see JavaCore#getClasspathVariable(String) + * @see JavaCore#setClasspathVariable(String, IPath, IProgressMonitor) + * @see JavaCore#setClasspathVariables(String[], IPath[], IProgressMonitor) + */ + public abstract void initialize(String variable); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/CompletionProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/CompletionProposal.java index 400dae5..0e3e548 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/CompletionProposal.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/CompletionProposal.java @@ -17,34 +17,31 @@ import org.eclipse.core.runtime.IProgressMonitor; /** * Completion proposal. *

    - * In typical usage, the user working in a Java code editor issues - * a code assist command. This command results in a call to + * In typical usage, the user working in a Java code editor issues a code assist + * command. This command results in a call to * ICodeAssist.codeComplete(position, completionRequestor) - * passing the current position in the source code. The code assist - * engine analyzes the code in the buffer, determines what kind of - * Java language construct is at that position, and proposes ways - * to complete that construct. These proposals are instances of - * subclasses of CompletionProposal. These proposals, - * perhaps after sorting and filtering, are presented to the user - * to make a choice. + * passing the current position in the source code. The code assist engine + * analyzes the code in the buffer, determines what kind of Java language + * construct is at that position, and proposes ways to complete that construct. + * These proposals are instances of subclasses of + * CompletionProposal. These proposals, perhaps after sorting + * and filtering, are presented to the user to make a choice. *

    *

    - * The proposal is as follows: insert - * the {@linkplain #getCompletion() completion string} into the - * source file buffer, replacing the characters between - * {@linkplain #getReplaceStart() the start} - * and {@linkplain #getReplaceEnd() end}. The string - * can be arbitrary; for example, it might include not only the - * name of a method but a set of parentheses. Moreover, the source - * range may include source positions before or after the source - * position where ICodeAssist.codeComplete was invoked. - * The rest of the information associated with the proposal is - * to provide context that may help a user to choose from among - * competing proposals. + * The proposal is as follows: insert the + * {@linkplain #getCompletion() completion string} into the source file buffer, + * replacing the characters between {@linkplain #getReplaceStart() the start} + * and {@linkplain #getReplaceEnd() end}. The string can be arbitrary; for + * example, it might include not only the name of a method but a set of + * parentheses. Moreover, the source range may include source positions before + * or after the source position where ICodeAssist.codeComplete + * was invoked. The rest of the information associated with the proposal is to + * provide context that may help a user to choose from among competing + * proposals. *

    *

    - * The completion engine creates instances of this class; it is not - * intended to be used by other clients. + * The completion engine creates instances of this class; it is not intended to + * be used by other clients. *

    * * @see ICodeAssist#codeComplete(int, CompletionRequestor) @@ -53,24 +50,20 @@ import org.eclipse.core.runtime.IProgressMonitor; public final class CompletionProposal { /** - * Completion is a declaration of an anonymous class. - * This kind of completion might occur in a context like - * "new List^;" and complete it to - * "new List() {}". + * Completion is a declaration of an anonymous class. This kind of + * completion might occur in a context like "new List^;" and + * complete it to "new List() {}". *

    - * The following additional context information is available - * for this kind of completion proposal at little extra cost: + * The following additional context information is available for this kind + * of completion proposal at little extra cost: *

      - *
    • {@link #getDeclarationSignature()} - - * the type signature of the type being implemented or subclassed - *
    • - * - *
    • {@link #getSignature()} - - * the method signature of the constructor that is referenced - *
    • - *
    • {@link #getFlags()} - - * the modifiers flags of the constructor that is referenced + *
    • {@link #getDeclarationSignature()} - the type signature of the type + * being implemented or subclassed
    • * + *
    • {@link #getSignature()} - the method signature of the constructor + * that is referenced
    • + *
    • {@link #getFlags()} - the modifiers flags of the constructor that is + * referenced
    • *
    *

    * @@ -79,28 +72,22 @@ public final class CompletionProposal { public static final int ANONYMOUS_CLASS_DECLARATION = 1; /** - * Completion is a reference to a field. - * This kind of completion might occur in a context like - * "this.ref^ = 0;" and complete it to + * Completion is a reference to a field. This kind of completion might occur + * in a context like "this.ref^ = 0;" and complete it to * "this.refcount = 0;". *

    - * The following additional context information is available - * for this kind of completion proposal at little extra cost: + * The following additional context information is available for this kind + * of completion proposal at little extra cost: *

      - *
    • {@link #getDeclarationSignature()} - - * the type signature of the type that declares the field that is referenced - *
    • - *
    • {@link #getFlags()} - - * the modifiers flags (including ACC_ENUM) of the field that is referenced - *
    • - *
    • {@link #getName()} - - * the simple name of the field that is referenced - *
    • - *
    • {@link #getSignature()} - - * the type signature of the field's type (as opposed to the - * signature of the type in which the referenced field - * is declared) - *
    • + *
    • {@link #getDeclarationSignature()} - the type signature of the type + * that declares the field that is referenced
    • + *
    • {@link #getFlags()} - the modifiers flags (including ACC_ENUM) of + * the field that is referenced
    • + *
    • {@link #getName()} - the simple name of the field that is referenced + *
    • + *
    • {@link #getSignature()} - the type signature of the field's type (as + * opposed to the signature of the type in which the referenced field is + * declared)
    • *
    *

    * @@ -109,20 +96,16 @@ public final class CompletionProposal { public static final int FIELD_REF = 2; /** - * Completion is a keyword. - * This kind of completion might occur in a context like - * "public cl^ Foo {}" and complete it to + * Completion is a keyword. This kind of completion might occur in a context + * like "public cl^ Foo {}" and complete it to * "public class Foo {}". *

    - * The following additional context information is available - * for this kind of completion proposal at little extra cost: + * The following additional context information is available for this kind + * of completion proposal at little extra cost: *

      - *
    • {@link #getName()} - - * the keyword token - *
    • - *
    • {@link #getFlags()} - - * the corresponding modifier flags if the keyword is a modifier - *
    • + *
    • {@link #getName()} - the keyword token
    • + *
    • {@link #getFlags()} - the corresponding modifier flags if the + * keyword is a modifier
    • *
    *

    * @@ -131,16 +114,14 @@ public final class CompletionProposal { public static final int KEYWORD = 3; /** - * Completion is a reference to a label. - * This kind of completion might occur in a context like - * "break lo^;" and complete it to + * Completion is a reference to a label. This kind of completion might occur + * in a context like "break lo^;" and complete it to * "break loop;". *

    - * The following additional context information is available - * for this kind of completion proposal at little extra cost: + * The following additional context information is available for this kind + * of completion proposal at little extra cost: *

      - *
    • {@link #getName()} - - * the simple name of the label that is referenced + *
    • {@link #getName()} - the simple name of the label that is referenced *
    • *
    *

    @@ -150,23 +131,19 @@ public final class CompletionProposal { public static final int LABEL_REF = 4; /** - * Completion is a reference to a local variable. - * This kind of completion might occur in a context like - * "ke^ = 4;" and complete it to - * "keys = 4;". + * Completion is a reference to a local variable. This kind of completion + * might occur in a context like "ke^ = 4;" and complete it + * to "keys = 4;". *

    - * The following additional context information is available - * for this kind of completion proposal at little extra cost: + * The following additional context information is available for this kind + * of completion proposal at little extra cost: *

      - *
    • {@link #getFlags()} - - * the modifiers flags of the local variable that is referenced - *
    • - *
    • {@link #getName()} - - * the simple name of the local variable that is referenced - *
    • - *
    • {@link #getSignature()} - - * the type signature of the local variable's type - *
    • + *
    • {@link #getFlags()} - the modifiers flags of the local variable that + * is referenced
    • + *
    • {@link #getName()} - the simple name of the local variable that is + * referenced
    • + *
    • {@link #getSignature()} - the type signature of the local variable's + * type
    • *
    *

    * @@ -175,26 +152,21 @@ public final class CompletionProposal { public static final int LOCAL_VARIABLE_REF = 5; /** - * Completion is a reference to a method. - * This kind of completion might occur in a context like - * "System.out.pr^();" and complete it to - * ""System.out.println();". + * Completion is a reference to a method. This kind of completion might + * occur in a context like "System.out.pr^();" and complete + * it to ""System.out.println();". *

    - * The following additional context information is available - * for this kind of completion proposal at little extra cost: + * The following additional context information is available for this kind + * of completion proposal at little extra cost: *

      - *
    • {@link #getDeclarationSignature()} - - * the type signature of the type that declares the method that is referenced - *
    • - *
    • {@link #getFlags()} - - * the modifiers flags of the method that is referenced - *
    • - *
    • {@link #getName()} - - * the simple name of the method that is referenced - *
    • - *
    • {@link #getSignature()} - - * the method signature of the method that is referenced - *
    • + *
    • {@link #getDeclarationSignature()} - the type signature of the type + * that declares the method that is referenced
    • + *
    • {@link #getFlags()} - the modifiers flags of the method that is + * referenced
    • + *
    • {@link #getName()} - the simple name of the method that is + * referenced
    • + *
    • {@link #getSignature()} - the method signature of the method that is + * referenced
    • *
    *

    * @@ -203,30 +175,21 @@ public final class CompletionProposal { public static final int METHOD_REF = 6; /** - * Completion is a declaration of a method. - * This kind of completion might occur in a context like - * "new List() {si^};" and complete it to - * "new List() {public int size() {} };". + * Completion is a declaration of a method. This kind of completion might + * occur in a context like "new List() {si^};" and complete + * it to "new List() {public int size() {} };". *

    - * The following additional context information is available - * for this kind of completion proposal at little extra cost: + * The following additional context information is available for this kind + * of completion proposal at little extra cost: *

      - *
    • {@link #getDeclarationSignature()} - - * the type signature of the type that declares the - * method that is being overridden or implemented - *
    • - *
    • {@link #getName()} - - * the simple name of the method that is being overridden - * or implemented - *
    • - *
    • {@link #getSignature()} - - * the method signature of the method that is being - * overridden or implemented - *
    • - *
    • {@link #getFlags()} - - * the modifiers flags of the method that is being - * overridden or implemented - *
    • + *
    • {@link #getDeclarationSignature()} - the type signature of the type + * that declares the method that is being overridden or implemented
    • + *
    • {@link #getName()} - the simple name of the method that is being + * overridden or implemented
    • + *
    • {@link #getSignature()} - the method signature of the method that is + * being overridden or implemented
    • + *
    • {@link #getFlags()} - the modifiers flags of the method that is + * being overridden or implemented
    • *
    *

    * @@ -235,17 +198,15 @@ public final class CompletionProposal { public static final int METHOD_DECLARATION = 7; /** - * Completion is a reference to a package. - * This kind of completion might occur in a context like - * "import java.u^.*;" and complete it to - * "import java.util.*;". + * Completion is a reference to a package. This kind of completion might + * occur in a context like "import java.u^.*;" and complete + * it to "import java.util.*;". *

    - * The following additional context information is available - * for this kind of completion proposal at little extra cost: + * The following additional context information is available for this kind + * of completion proposal at little extra cost: *

      - *
    • {@link #getDeclarationSignature()} - - * the dot-based package signature of the package that is referenced - *
    • + *
    • {@link #getDeclarationSignature()} - the dot-based package signature + * of the package that is referenced
    • *
    *

    * @@ -254,27 +215,22 @@ public final class CompletionProposal { public static final int PACKAGE_REF = 8; /** - * Completion is a reference to a type. Any kind of type - * is allowed, including primitive types, reference types, - * array types, parameterized types, and type variables. - * This kind of completion might occur in a context like - * "public static Str^ key;" and complete it to + * Completion is a reference to a type. Any kind of type is allowed, + * including primitive types, reference types, array types, parameterized + * types, and type variables. This kind of completion might occur in a + * context like "public static Str^ key;" and complete it to * "public static String key;". *

    - * The following additional context information is available - * for this kind of completion proposal at little extra cost: + * The following additional context information is available for this kind + * of completion proposal at little extra cost: *

      - *
    • {@link #getDeclarationSignature()} - - * the dot-based package signature of the package that contains - * the type that is referenced - *
    • - *
    • {@link #getSignature()} - - * the type signature of the type that is referenced - *
    • - *
    • {@link #getFlags()} - - * the modifiers flags (including Flags.AccInterface, AccEnum, - * and AccAnnotation) of the type that is referenced - *
    • + *
    • {@link #getDeclarationSignature()} - the dot-based package signature + * of the package that contains the type that is referenced
    • + *
    • {@link #getSignature()} - the type signature of the type that is + * referenced
    • + *
    • {@link #getFlags()} - the modifiers flags (including + * Flags.AccInterface, AccEnum, and AccAnnotation) of the type that is + * referenced
    • *
    *

    * @@ -283,147 +239,137 @@ public final class CompletionProposal { public static final int TYPE_REF = 9; /** - * Completion is a declaration of a variable (locals, parameters, - * fields, etc.). + * Completion is a declaration of a variable (locals, parameters, fields, + * etc.). *

    - * The following additional context information is available - * for this kind of completion proposal at little extra cost: + * The following additional context information is available for this kind + * of completion proposal at little extra cost: *

      - *
    • {@link #getName()} - - * the simple name of the variable being declared - *
    • - *
    • {@link #getSignature()} - - * the type signature of the type of the variable - * being declared - *
    • - *
    • {@link #getFlags()} - - * the modifiers flags of the variable being declared + *
    • {@link #getName()} - the simple name of the variable being declared *
    • + *
    • {@link #getSignature()} - the type signature of the type of the + * variable being declared
    • + *
    • {@link #getFlags()} - the modifiers flags of the variable being + * declared
    • *
    *

    + * * @see #getKind() */ public static final int VARIABLE_DECLARATION = 10; - + /** * Kind of completion request. */ private int completionKind; - + /** - * Offset in original buffer where ICodeAssist.codeComplete() was - * requested. + * Offset in original buffer where ICodeAssist.codeComplete() was requested. */ private int completionLocation; - + /** - * Start position (inclusive) of source range in original buffer - * containing the relevant token - * defaults to empty subrange at [0,0). + * Start position (inclusive) of source range in original buffer containing + * the relevant token defaults to empty subrange at [0,0). */ private int tokenStart = 0; - + /** - * End position (exclusive) of source range in original buffer - * containing the relevant token; - * defaults to empty subrange at [0,0). + * End position (exclusive) of source range in original buffer containing + * the relevant token; defaults to empty subrange at [0,0). */ private int tokenEnd = 0; - + /** * Completion string; defaults to empty string. */ private char[] completion = CharOperation.NO_CHAR; - + /** - * Start position (inclusive) of source range in original buffer - * to be replaced by completion string; - * defaults to empty subrange at [0,0). + * Start position (inclusive) of source range in original buffer to be + * replaced by completion string; defaults to empty subrange at [0,0). */ private int replaceStart = 0; - + /** - * End position (exclusive) of source range in original buffer - * to be replaced by completion string; - * defaults to empty subrange at [0,0). + * End position (exclusive) of source range in original buffer to be + * replaced by completion string; defaults to empty subrange at [0,0). */ private int replaceEnd = 0; - + /** - * Relevance rating; positive; higher means better; - * defaults to minimum rating. + * Relevance rating; positive; higher means better; defaults to minimum + * rating. */ private int relevance = 1; - + /** - * Signature of the relevant package or type declaration - * in the context, or null if none. - * Defaults to null. + * Signature of the relevant package or type declaration in the context, or + * null if none. Defaults to null. */ private char[] declarationSignature = null; - + /** - * Simple name of the method, field, - * member, or variable relevant in the context, or - * null if none. - * Defaults to null. + * Simple name of the method, field, member, or variable relevant in the + * context, or null if none. Defaults to null. */ private char[] name = null; - + /** - * Signature of the method, field type, member type, - * relevant in the context, or null if none. - * Defaults to null. + * Signature of the method, field type, member type, relevant in the + * context, or null if none. Defaults to null. */ private char[] signature = null; - + /** - * Modifier flags relevant in the context, or - * Flags.AccDefault if none. - * Defaults to Flags.AccDefault. + * Modifier flags relevant in the context, or Flags.AccDefault + * if none. Defaults to Flags.AccDefault. */ private int flags = Flags.AccDefault; - + /** - * Parameter names (for method completions), or - * null if none. Lazily computed. - * Defaults to null. + * Parameter names (for method completions), or null if none. + * Lazily computed. Defaults to null. */ private char[][] parameterNames = null; - + /** * Indicates whether parameter names have been computed. */ private boolean parameterNamesComputed = false; - + /** - * Creates a basic completion proposal. All instance - * field have plausible default values unless otherwise noted. + * Creates a basic completion proposal. All instance field have plausible + * default values unless otherwise noted. *

    - * Note that the constructors for this class are internal to the - * Java model implementation. Clients cannot directly create - * CompletionProposal objects. + * Note that the constructors for this class are internal to the Java model + * implementation. Clients cannot directly create CompletionProposal + * objects. *

    * - * @param kind one of the kind constants declared on this class - * @param completionOffset original offset of code completion request + * @param kind + * one of the kind constants declared on this class + * @param completionOffset + * original offset of code completion request * @return a new completion proposal */ public static CompletionProposal create(int kind, int completionOffset) { return new CompletionProposal(kind, completionOffset); } - + /** - * Creates a basic completion proposal. All instance - * field have plausible default values unless otherwise noted. + * Creates a basic completion proposal. All instance field have plausible + * default values unless otherwise noted. *

    - * Note that the constructors for this class are internal to the - * Java model implementation. Clients cannot directly create - * CompletionProposal objects. + * Note that the constructors for this class are internal to the Java model + * implementation. Clients cannot directly create CompletionProposal + * objects. *

    * - * @param kind one of the kind constants declared on this class - * @param completionLocation original offset of code completion request + * @param kind + * one of the kind constants declared on this class + * @param completionLocation + * original offset of code completion request */ CompletionProposal(int kind, int completionLocation) { if ((kind < CompletionProposal.ANONYMOUS_CLASS_DECLARATION) @@ -436,29 +382,26 @@ public final class CompletionProposal { this.completionKind = kind; this.completionLocation = completionLocation; } - + /** * Returns the kind of completion being proposed. *

    - * The set of different kinds of completion proposals is - * expected to change over time. It is strongly recommended - * that clients do not assume that the kind is one of the - * ones they know about, and code defensively for the - * possibility of unexpected future growth. + * The set of different kinds of completion proposals is expected to change + * over time. It is strongly recommended that clients do not assume + * that the kind is one of the ones they know about, and code defensively + * for the possibility of unexpected future growth. *

    * - * @return the kind; one of the kind constants - * declared on this class, or possibly a kind unknown - * to the caller + * @return the kind; one of the kind constants declared on this class, or + * possibly a kind unknown to the caller */ public int getKind() { return this.completionKind; } - + /** - * Returns the character index in the source file buffer - * where source completion was requested (the - * offsetparameter to + * Returns the character index in the source file buffer where source + * completion was requested (the offsetparameter to * ICodeAssist.codeComplete. * * @return character index in source file buffer @@ -467,52 +410,48 @@ public final class CompletionProposal { public int getCompletionLocation() { return this.completionLocation; } - - /** - * Returns the character index of the start of the - * subrange in the source file buffer containing the - * relevant token being completed. This - * token is either the identifier or Java language keyword - * under, or immediately preceding, the original request - * offset. If the original request offset is not within - * or immediately after an identifier or keyword, then the - * position returned is original request offset and the - * token range is empty. + + /** + * Returns the character index of the start of the subrange in the source + * file buffer containing the relevant token being completed. This token is + * either the identifier or Java language keyword under, or immediately + * preceding, the original request offset. If the original request offset is + * not within or immediately after an identifier or keyword, then the + * position returned is original request offset and the token range is + * empty. * * @return character index of token start position (inclusive) */ public int getTokenStart() { return this.tokenStart; } - + /** - * Returns the character index of the end (exclusive) of the subrange - * in the source file buffer containing the - * relevant token. When there is no relevant token, the - * range is empty - * (getEndToken() == getStartToken()). + * Returns the character index of the end (exclusive) of the subrange in the + * source file buffer containing the relevant token. When there is no + * relevant token, the range is empty (getEndToken() == getStartToken()). * * @return character index of token end position (exclusive) */ public int getTokenEnd() { return this.tokenEnd; } - + /** - * Sets the character indices of the subrange in the - * source file buffer containing the relevant token being - * completed. This token is either the identifier or - * Java language keyword under, or immediately preceding, - * the original request offset. If the original request - * offset is not within or immediately after an identifier - * or keyword, then the source range begins at original - * request offset and is empty. + * Sets the character indices of the subrange in the source file buffer + * containing the relevant token being completed. This token is either the + * identifier or Java language keyword under, or immediately preceding, the + * original request offset. If the original request offset is not within or + * immediately after an identifier or keyword, then the source range begins + * at original request offset and is empty. *

    * If not set, defaults to empty subrange at [0,0). *

    * - * @param startIndex character index of token start position (inclusive) - * @param endIndex character index of token end position (exclusive) + * @param startIndex + * character index of token start position (inclusive) + * @param endIndex + * character index of token end position (exclusive) */ public void setTokenRange(int startIndex, int endIndex) { if (startIndex < 0 || endIndex < startIndex) { @@ -521,12 +460,12 @@ public final class CompletionProposal { this.tokenStart = startIndex; this.tokenEnd = endIndex; } - + /** - * Returns the proposed sequence of characters to insert into the - * source file buffer, replacing the characters at the specified - * source range. The string can be arbitrary; for example, it might - * include not only the name of a method but a set of parentheses. + * Returns the proposed sequence of characters to insert into the source + * file buffer, replacing the characters at the specified source range. The + * string can be arbitrary; for example, it might include not only the name + * of a method but a set of parentheses. *

    * The client must not modify the array returned. *

    @@ -536,43 +475,39 @@ public final class CompletionProposal { public char[] getCompletion() { return this.completion; } - + /** - * Sets the proposed sequence of characters to insert into the - * source file buffer, replacing the characters at the specified - * source range. The string can be arbitrary; for example, it might - * include not only the name of a method but a set of parentheses. + * Sets the proposed sequence of characters to insert into the source file + * buffer, replacing the characters at the specified source range. The + * string can be arbitrary; for example, it might include not only the name + * of a method but a set of parentheses. *

    * If not set, defaults to an empty character array. *

    *

    - * The completion engine creates instances of this class and sets - * its properties; this method is not intended to be used by other clients. + * The completion engine creates instances of this class and sets its + * properties; this method is not intended to be used by other clients. *

    * - * @param completion the completion string + * @param completion + * the completion string */ public void setCompletion(char[] completion) { this.completion = completion; } - - /** - * Returns the character index of the start of the - * subrange in the source file buffer to be replaced - * by the completion string. If the subrange is empty - * (getReplaceEnd() == getReplaceStart()), - * the completion string is to be inserted at this - * index. - *

    - * Note that while the token subrange is precisely - * specified, the replacement range is loosely - * constrained and may not bear any direct relation - * to the original request offset. For example, a - * it would be possible for a type completion to - * propose inserting an import declaration at the - * top of the compilation unit; or the completion - * might include trailing parentheses and - * punctuation for a method completion. + + /** + * Returns the character index of the start of the subrange in the source + * file buffer to be replaced by the completion string. If the subrange is + * empty (getReplaceEnd() == getReplaceStart()), the + * completion string is to be inserted at this index. + *

    + * Note that while the token subrange is precisely specified, the + * replacement range is loosely constrained and may not bear any direct + * relation to the original request offset. For example, a it would be + * possible for a type completion to propose inserting an import declaration + * at the top of the compilation unit; or the completion might include + * trailing parentheses and punctuation for a method completion. *

    * * @return replacement start position (inclusive) @@ -580,38 +515,34 @@ public final class CompletionProposal { public int getReplaceStart() { return this.replaceStart; } - + /** - * Returns the character index of the end of the - * subrange in the source file buffer to be replaced - * by the completion string. If the subrange is empty - * (getReplaceEnd() == getReplaceStart()), - * the completion string is to be inserted at this - * index. + * Returns the character index of the end of the subrange in the source file + * buffer to be replaced by the completion string. If the subrange is empty (getReplaceEnd() == getReplaceStart()), + * the completion string is to be inserted at this index. * * @return replacement end position (exclusive) */ public int getReplaceEnd() { return this.replaceEnd; } - + /** - * Sets the character indices of the subrange in the - * source file buffer to be replaced by the completion - * string. If the subrange is empty - * (startIndex == endIndex), - * the completion string is to be inserted at this - * index. + * Sets the character indices of the subrange in the source file buffer to + * be replaced by the completion string. If the subrange is empty (startIndex == endIndex), + * the completion string is to be inserted at this index. *

    * If not set, defaults to empty subrange at [0,0). *

    *

    - * The completion engine creates instances of this class and sets - * its properties; this method is not intended to be used by other clients. + * The completion engine creates instances of this class and sets its + * properties; this method is not intended to be used by other clients. *

    * - * @param startIndex character index of replacement start position (inclusive) - * @param endIndex character index of replacement end position (exclusive) + * @param startIndex + * character index of replacement start position (inclusive) + * @param endIndex + * character index of replacement end position (exclusive) */ public void setReplaceRange(int startIndex, int endIndex) { if (startIndex < 0 || endIndex < startIndex) { @@ -620,27 +551,30 @@ public final class CompletionProposal { this.replaceStart = startIndex; this.replaceEnd = endIndex; } - + /** * Returns the relative relevance rating of this proposal. * - * @return relevance rating of this proposal; ratings are positive; higher means better + * @return relevance rating of this proposal; ratings are positive; higher + * means better */ public int getRelevance() { return this.relevance; } - + /** * Sets the relative relevance rating of this proposal. *

    * If not set, defaults to the lowest possible rating (1). *

    *

    - * The completion engine creates instances of this class and sets - * its properties; this method is not intended to be used by other clients. + * The completion engine creates instances of this class and sets its + * properties; this method is not intended to be used by other clients. *

    * - * @param rating relevance rating of this proposal; ratings are positive; higher means better + * @param rating + * relevance rating of this proposal; ratings are positive; + * higher means better */ public void setRelevance(int rating) { if (rating <= 0) { @@ -648,132 +582,122 @@ public final class CompletionProposal { } this.relevance = rating; } - + /** - * Returns the type or package signature of the relevant - * declaration in the context, or null if none. + * Returns the type or package signature of the relevant declaration in the + * context, or null if none. *

    - * This field is available for the following kinds of - * completion proposals: + * This field is available for the following kinds of completion proposals: *

      - *
    • ANONYMOUS_CLASS_DECLARATION - type signature - * of the type that is being subclassed or implemented
    • - *
    • FIELD_REF - type signature - * of the type that declares the field that is referenced
    • - *
    • METHOD_REF - type signature - * of the type that declares the method that is referenced
    • - *
    • METHOD_DECLARATION - type signature - * of the type that declares the method that is being - * implemented or overridden
    • - *
    • PACKAGE_REF - dot-based package - * signature of the package that is referenced
    • - *
    • TYPE_REF - dot-based package - * signature of the package containing the type that is referenced
    • + *
    • ANONYMOUS_CLASS_DECLARATION - type signature of the + * type that is being subclassed or implemented
    • + *
    • FIELD_REF - type signature of the type that declares + * the field that is referenced
    • + *
    • METHOD_REF - type signature of the type that declares + * the method that is referenced
    • + *
    • METHOD_DECLARATION - type signature of the type that + * declares the method that is being implemented or overridden
    • + *
    • PACKAGE_REF - dot-based package signature of the + * package that is referenced
    • + *
    • TYPE_REF - dot-based package signature of the package + * containing the type that is referenced
    • *
    - * For kinds of completion proposals, this method returns - * null. Clients must not modify the array - * returned. + * For kinds of completion proposals, this method returns null. + * Clients must not modify the array returned. *

    * - * @return the declaration signature, or - * null if none + * @return the declaration signature, or null if none * @see Signature */ public char[] getDeclarationSignature() { return this.declarationSignature; } - + /** - * Sets the type or package signature of the relevant - * declaration in the context, or null if none. + * Sets the type or package signature of the relevant declaration in the + * context, or null if none. *

    * If not set, defaults to none. *

    *

    - * The completion engine creates instances of this class and sets - * its properties; this method is not intended to be used by other clients. + * The completion engine creates instances of this class and sets its + * properties; this method is not intended to be used by other clients. *

    * - * @param signature the type or package signature, or - * null if none + * @param signature + * the type or package signature, or null if none */ public void setDeclarationSignature(char[] signature) { this.declarationSignature = signature; } - + /** - * Returns the simple name of the method, field, - * member, or variable relevant in the context, or - * null if none. + * Returns the simple name of the method, field, member, or variable + * relevant in the context, or null if none. *

    - * This field is available for the following kinds of - * completion proposals: + * This field is available for the following kinds of completion proposals: *

      - *
    • FIELD_REF - the name of the field
    • - *
    • KEYWORD - the keyword
    • - *
    • LABEL_REF - the name of the label
    • - *
    • LOCAL_VARIABLE_REF - the name of the local variable
    • - *
    • METHOD_REF - the name of the method
    • - *
    • METHOD_DECLARATION - the name of the method
    • - *
    • VARIABLE_DECLARATION - the name of the variable
    • + *
    • FIELD_REF - the name of the field
    • + *
    • KEYWORD - the keyword
    • + *
    • LABEL_REF - the name of the label
    • + *
    • LOCAL_VARIABLE_REF - the name of the local variable
    • + *
    • METHOD_REF - the name of the method
    • + *
    • METHOD_DECLARATION - the name of the method
    • + *
    • VARIABLE_DECLARATION - the name of the variable
    • *
    - * For kinds of completion proposals, this method returns - * null. Clients must not modify the array - * returned. + * For kinds of completion proposals, this method returns null. + * Clients must not modify the array returned. *

    * - * @return the keyword, field, method, local variable, or member - * name, or null if none + * @return the keyword, field, method, local variable, or member name, or + * null if none */ public char[] getName() { return this.name; } - - + /** - * Sets the simple name of the method, field, - * member, or variable relevant in the context, or - * null if none. + * Sets the simple name of the method, field, member, or variable relevant + * in the context, or null if none. *

    * If not set, defaults to none. *

    *

    - * The completion engine creates instances of this class and sets - * its properties; this method is not intended to be used by other clients. + * The completion engine creates instances of this class and sets its + * properties; this method is not intended to be used by other clients. *

    * - * @param name the keyword, field, method, local variable, - * or member name, or null if none + * @param name + * the keyword, field, method, local variable, or member name, or + * null if none */ public void setName(char[] name) { this.name = name; } - + /** - * Returns the signature of the method or type - * relevant in the context, or null if none. + * Returns the signature of the method or type relevant in the context, or + * null if none. *

    - * This field is available for the following kinds of - * completion proposals: + * This field is available for the following kinds of completion proposals: *

      - *
    • ANONYMOUS_CLASS_DECLARATION - method signature - * of the constructor that is being invoked
    • - *
    • FIELD_REF - the type signature - * of the referenced field's type
    • - *
    • LOCAL_VARIABLE_REF - the type signature - * of the referenced local variable's type
    • - *
    • METHOD_REF - method signature - * of the method that is referenced
    • - *
    • METHOD_DECLARATION - method signature - * of the method that is being implemented or overridden
    • - *
    • TYPE_REF - type signature - * of the type that is referenced
    • - *
    • VARIABLE_DECLARATION - the type signature - * of the type of the variable being declared
    • + *
    • ANONYMOUS_CLASS_DECLARATION - method signature of the + * constructor that is being invoked
    • + *
    • FIELD_REF - the type signature of the referenced + * field's type
    • + *
    • LOCAL_VARIABLE_REF - the type signature of the + * referenced local variable's type
    • + *
    • METHOD_REF - method signature of the method that is + * referenced
    • + *
    • METHOD_DECLARATION - method signature of the method + * that is being implemented or overridden
    • + *
    • TYPE_REF - type signature of the type that is + * referenced
    • + *
    • VARIABLE_DECLARATION - the type signature of the type + * of the variable being declared
    • *
    - * For kinds of completion proposals, this method returns - * null. Clients must not modify the array - * returned. + * For kinds of completion proposals, this method returns null. + * Clients must not modify the array returned. *

    * * @return the signature, or null if none @@ -782,91 +706,83 @@ public final class CompletionProposal { public char[] getSignature() { return this.signature; } - + /** - * Sets the signature of the method, field type, member type, - * relevant in the context, or null if none. + * Sets the signature of the method, field type, member type, relevant in + * the context, or null if none. *

    * If not set, defaults to none. *

    *

    - * The completion engine creates instances of this class and sets - * its properties; this method is not intended to be used by other clients. + * The completion engine creates instances of this class and sets its + * properties; this method is not intended to be used by other clients. *

    * - * @param signature the signature, or null if none + * @param signature + * the signature, or null if none */ public void setSignature(char[] signature) { this.signature = signature; } - + /** * Returns the modifier flags relevant in the context, or * Flags.AccDefault if none. *

    - * This field is available for the following kinds of - * completion proposals: + * This field is available for the following kinds of completion proposals: *

      - *
    • ANONYMOUS_CLASS_DECLARATION - modifier flags - * of the constructor that is referenced
    • - *
    • FIELD_REF - modifier flags - * of the field that is referenced; - * Flags.AccEnum can be used to recognize - * references to enum constants - *
    • - *
    • KEYWORD - modifier flag - * corrresponding to the modifier keyword
    • - *
    • LOCAL_VARIABLE_REF - modifier flags - * of the local variable that is referenced
    • - *
    • METHOD_REF - modifier flags - * of the method that is referenced; - * Flags.AccAnnotation can be used to recognize - * references to annotation type members - *
    • - *
    • METHOD_DECLARATION - modifier flags - * for the method that is being implemented or overridden
    • - *
    • TYPE_REF - modifier flags - * of the type that is referenced; Flags.AccInterface - * can be used to recognize references to interfaces, - * Flags.AccEnum enum types, - * and Flags.AccAnnotation annotation types - *
    • - *
    • VARIABLE_DECLARATION - modifier flags - * for the variable being declared
    • + *
    • ANONYMOUS_CLASS_DECLARATION - modifier flags of the + * constructor that is referenced
    • + *
    • FIELD_REF - modifier flags of the field that is + * referenced; Flags.AccEnum can be used to recognize + * references to enum constants
    • + *
    • KEYWORD - modifier flag corrresponding to the + * modifier keyword
    • + *
    • LOCAL_VARIABLE_REF - modifier flags of the local + * variable that is referenced
    • + *
    • METHOD_REF - modifier flags of the method that is + * referenced; Flags.AccAnnotation can be used to recognize + * references to annotation type members
    • + *
    • METHOD_DECLARATION - modifier flags for the method + * that is being implemented or overridden
    • + *
    • TYPE_REF - modifier flags of the type that is + * referenced; Flags.AccInterface can be used to recognize + * references to interfaces, Flags.AccEnum enum types, and + * Flags.AccAnnotation annotation types
    • + *
    • VARIABLE_DECLARATION - modifier flags for the + * variable being declared
    • *
    * For kinds of completion proposals, this method returns * Flags.AccDefault. *

    * - * @return the modifier flags, or - * Flags.AccDefault if none + * @return the modifier flags, or Flags.AccDefault if none * @see Flags */ public int getFlags() { return this.flags; } - + /** * Sets the modifier flags relevant in the context. *

    * If not set, defaults to none. *

    *

    - * The completion engine creates instances of this class and sets - * its properties; this method is not intended to be used by other clients. + * The completion engine creates instances of this class and sets its + * properties; this method is not intended to be used by other clients. *

    * - * @param flags the modifier flags, or - * Flags.AccDefault if none + * @param flags + * the modifier flags, or Flags.AccDefault if none */ public void setFlags(int flags) { this.flags = flags; } - + /** - * Finds the method parameter names. - * This information is relevant to method reference (and - * method declaration proposals). Returns null + * Finds the method parameter names. This information is relevant to method + * reference (and method declaration proposals). Returns null * if not available or not relevant. *

    * The client must not modify the array returned. @@ -876,9 +792,10 @@ public final class CompletionProposal { * parsing Java source files, etc. Use sparingly. *

    * - * @param monitor the progress monitor, or null if none - * @return the parameter names, or null if none - * or not available or not relevant + * @param monitor + * the progress monitor, or null if none + * @return the parameter names, or null if none or not + * available or not relevant */ public char[][] findParameterNames(IProgressMonitor monitor) { if (!this.parameterNamesComputed) { @@ -887,17 +804,17 @@ public final class CompletionProposal { } return this.parameterNames; } - + /** - * Sets the method parameter names. - * This information is relevant to method reference (and - * method declaration proposals). + * Sets the method parameter names. This information is relevant to method + * reference (and method declaration proposals). *

    - * The completion engine creates instances of this class and sets - * its properties; this method is not intended to be used by other clients. + * The completion engine creates instances of this class and sets its + * properties; this method is not intended to be used by other clients. *

    * - * @param parameterNames the parameter names, or null if none + * @param parameterNames + * the parameter names, or null if none */ public void setParameterNames(char[][] parameterNames) { this.parameterNames = parameterNames; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/CompletionRequestor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/CompletionRequestor.java index 2195c82..735d867 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/CompletionRequestor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/CompletionRequestor.java @@ -19,30 +19,35 @@ import net.sourceforge.phpdt.core.compiler.IProblem; * This class is intended to be subclassed by clients. *

    *

    - * The code assist engine normally invokes methods on completion - * requestors in the following sequence: + * The code assist engine normally invokes methods on completion requestors in + * the following sequence: + * *

    - * requestor.beginReporting();
    - * requestor.accept(proposal_1);
    - * requestor.accept(proposal_2);
    - * ...
    - * requestor.endReporting();
    + *  requestor.beginReporting();
    + *  requestor.accept(proposal_1);
    + *  requestor.accept(proposal_2);
    + *  ...
    + *  requestor.endReporting();
      * 
    - * If, however, the engine is unable to offer completion proposals - * for whatever reason, completionFailure is called - * with a problem object describing why completions were unavailable. - * In this case, the sequence of calls is: + * + * If, however, the engine is unable to offer completion proposals for whatever + * reason, completionFailure is called with a problem object + * describing why completions were unavailable. In this case, the sequence of + * calls is: + * *
      * requestor.beginReporting();
      * requestor.completionFailure(problem);
      * requestor.endReporting();
      * 
    + * * In either case, the bracketing beginReporting - * endReporting calls are always made. + * endReporting + * calls are always made. *

    *

    - * The class was introduced in 3.0 as a more evolvable replacement - * for the ICompletionRequestor interface. + * The class was introduced in 3.0 as a more evolvable replacement for the + * ICompletionRequestor interface. *

    * * @see ICodeAssist @@ -51,16 +56,14 @@ import net.sourceforge.phpdt.core.compiler.IProblem; public abstract class CompletionRequestor { /** - * The set of CompletionProposal kinds that this requestor - * ignores; 0 means the set is empty. - * 1 << completionProposalKind + * The set of CompletionProposal kinds that this requestor ignores; + * 0 means the set is empty. 1 << completionProposalKind */ private int ignoreSet = 0; /** - * Creates a new completion requestor. - * The requestor is interested in all kinds of completion - * proposals; none will be ignored. + * Creates a new completion requestor. The requestor is interested in all + * kinds of completion proposals; none will be ignored. */ public CompletionRequestor() { // do nothing @@ -69,37 +72,40 @@ public abstract class CompletionRequestor { /** * Returns whether the given kind of completion proposal is ignored. * - * @param completionProposalKind one of the kind constants declared - * on CompletionProposal - * @return true if the given kind of completion proposal - * is ignored by this requestor, and false if it is of - * interest + * @param completionProposalKind + * one of the kind constants declared on + * CompletionProposal + * @return true if the given kind of completion proposal is + * ignored by this requestor, and false if it is of + * interest * @see #setIgnored(int, boolean) * @see CompletionProposal#getKind() */ public final boolean isIgnored(int completionProposalKind) { if (completionProposalKind < CompletionProposal.ANONYMOUS_CLASS_DECLARATION - || completionProposalKind > CompletionProposal.VARIABLE_DECLARATION) { - throw new IllegalArgumentException(); + || completionProposalKind > CompletionProposal.VARIABLE_DECLARATION) { + throw new IllegalArgumentException(); } return 0 != (this.ignoreSet & (1 << completionProposalKind)); } - + /** * Sets whether the given kind of completion proposal is ignored. * - * @param completionProposalKind one of the kind constants declared - * on CompletionProposal - * @param ignore true if the given kind of completion proposal - * is ignored by this requestor, and false if it is of - * interest + * @param completionProposalKind + * one of the kind constants declared on + * CompletionProposal + * @param ignore + * true if the given kind of completion proposal + * is ignored by this requestor, and false if it + * is of interest * @see #isIgnored(int) * @see CompletionProposal#getKind() */ public final void setIgnored(int completionProposalKind, boolean ignore) { if (completionProposalKind < CompletionProposal.ANONYMOUS_CLASS_DECLARATION - || completionProposalKind > CompletionProposal.VARIABLE_DECLARATION) { - throw new IllegalArgumentException(); + || completionProposalKind > CompletionProposal.VARIABLE_DECLARATION) { + throw new IllegalArgumentException(); } if (ignore) { this.ignoreSet |= (1 << completionProposalKind); @@ -107,13 +113,13 @@ public abstract class CompletionRequestor { this.ignoreSet &= ~(1 << completionProposalKind); } } - + /** - * Pro forma notification sent before reporting a batch of - * completion proposals. + * Pro forma notification sent before reporting a batch of completion + * proposals. *

    - * The default implementation of this method does nothing. - * Clients may override. + * The default implementation of this method does nothing. Clients may + * override. *

    */ public void beginReporting() { @@ -121,11 +127,11 @@ public abstract class CompletionRequestor { } /** - * Pro forma notification sent after reporting a batch of - * completion proposals. + * Pro forma notification sent after reporting a batch of completion + * proposals. *

    - * The default implementation of this method does nothing. - * Clients may override. + * The default implementation of this method does nothing. Clients may + * override. *

    */ public void endReporting() { @@ -133,33 +139,36 @@ public abstract class CompletionRequestor { } /** - * Notification of failure to produce any completions. - * The problem object explains what prevented completing. + * Notification of failure to produce any completions. The problem object + * explains what prevented completing. *

    - * The default implementation of this method does nothing. - * Clients may override to receive this kind of notice. + * The default implementation of this method does nothing. Clients may + * override to receive this kind of notice. *

    * - * @param problem the problem object + * @param problem + * the problem object */ public void completionFailure(IProblem problem) { // default behavior is to ignore } /** - * Proposes a completion. Has no effect if the kind of proposal - * is being ignored by this requestor. Callers should consider - * checking {@link #isIgnored(int)} before avoid creating proposal - * objects that would only be ignored. + * Proposes a completion. Has no effect if the kind of proposal is being + * ignored by this requestor. Callers should consider checking + * {@link #isIgnored(int)} before avoid creating proposal objects that would + * only be ignored. *

    - * Similarly, implementers should check - * {@link #isIgnored(int) isIgnored(proposal.getKind())} - * and ignore proposals that have been declared as uninteresting. - * The proposal object passed in only valid for the duration of - * this call; implementors must not hang on to these objects. + * Similarly, implementers should check + * {@link #isIgnored(int) isIgnored(proposal.getKind())} and ignore + * proposals that have been declared as uninteresting. The proposal object + * passed in only valid for the duration of this call; implementors must not + * hang on to these objects. * - * @param proposal the completion proposal - * @exception IllegalArgumentException if the proposal is null + * @param proposal + * the completion proposal + * @exception IllegalArgumentException + * if the proposal is null */ public abstract void accept(CompletionProposal proposal); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/CompletionRequestorAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/CompletionRequestorAdapter.java index c473feb..0a79dc5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/CompletionRequestorAdapter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/CompletionRequestorAdapter.java @@ -12,45 +12,35 @@ package net.sourceforge.phpdt.core; import net.sourceforge.phpdt.core.compiler.IProblem; - /** * Adapter of the requestor interface ICompletionRequestor. *

    * This class is intended to be instanciated and subclassed by clients. *

    - * + * * @see ICompletionRequestor * @since 2.0 */ public class CompletionRequestorAdapter implements ICompletionRequestor { /* - * @see ICompletionRequestor#acceptAnonymousType(char[], char[], char[][], char[][], char[][], char[], int, int, int) + * @see ICompletionRequestor#acceptAnonymousType(char[], char[], char[][], + * char[][], char[][], char[], int, int, int) */ - public void acceptAnonymousType( - char[] superTypePackageName, - char[] superTypeName, - char[][] parameterPackageNames, - char[][] parameterTypeNames, - char[][] parameterNames, - char[] completionName, - int modifiers, - int completionStart, - int completionEnd, - int relevance) { + public void acceptAnonymousType(char[] superTypePackageName, + char[] superTypeName, char[][] parameterPackageNames, + char[][] parameterTypeNames, char[][] parameterNames, + char[] completionName, int modifiers, int completionStart, + int completionEnd, int relevance) { } /* - * @see ICompletionRequestor#acceptClass(char[], char[], char[], int, int, int) + * @see ICompletionRequestor#acceptClass(char[], char[], char[], int, int, + * int) */ - public void acceptClass( - char[] packageName, - char[] className, - char[] completionName, - int modifiers, - int completionStart, - int completionEnd, - int relevance) { + public void acceptClass(char[] packageName, char[] className, + char[] completionName, int modifiers, int completionStart, + int completionEnd, int relevance) { } /* @@ -60,148 +50,99 @@ public class CompletionRequestorAdapter implements ICompletionRequestor { } /* - * @see ICompletionRequestor#acceptField(char[], char[], char[], char[], char[], char[], int, int, int) + * @see ICompletionRequestor#acceptField(char[], char[], char[], char[], + * char[], char[], int, int, int) */ - public void acceptField( - char[] declaringTypePackageName, - char[] declaringTypeName, - char[] name, - char[] typePackageName, - char[] typeName, - char[] completionName, - int modifiers, - int completionStart, - int completionEnd, - int relevance) { + public void acceptField(char[] declaringTypePackageName, + char[] declaringTypeName, char[] name, char[] typePackageName, + char[] typeName, char[] completionName, int modifiers, + int completionStart, int completionEnd, int relevance) { } /* - * @see ICompletionRequestor#acceptInterface(char[], char[], char[], int, int, int) + * @see ICompletionRequestor#acceptInterface(char[], char[], char[], int, + * int, int) */ - public void acceptInterface( - char[] packageName, - char[] interfaceName, - char[] completionName, - int modifiers, - int completionStart, - int completionEnd, - int relevance) { + public void acceptInterface(char[] packageName, char[] interfaceName, + char[] completionName, int modifiers, int completionStart, + int completionEnd, int relevance) { } /* * @see ICompletionRequestor#acceptKeyword(char[], int, int) */ - public void acceptKeyword( - char[] keywordName, - int completionStart, - int completionEnd, - int relevance) { + public void acceptKeyword(char[] keywordName, int completionStart, + int completionEnd, int relevance) { } /* * @see ICompletionRequestor#acceptLabel(char[], int, int) */ - public void acceptLabel( - char[] labelName, - int completionStart, - int completionEnd, - int relevance) { + public void acceptLabel(char[] labelName, int completionStart, + int completionEnd, int relevance) { } /* - * @see ICompletionRequestor#acceptLocalVariable(char[], char[], char[], int, int, int) + * @see ICompletionRequestor#acceptLocalVariable(char[], char[], char[], + * int, int, int) */ - public void acceptLocalVariable( - char[] name, - char[] typePackageName, - char[] typeName, - int modifiers, - int completionStart, - int completionEnd, - int relevance) { + public void acceptLocalVariable(char[] name, char[] typePackageName, + char[] typeName, int modifiers, int completionStart, + int completionEnd, int relevance) { } /* - * @see ICompletionRequestor#acceptMethod(char[], char[], char[], char[][], char[][], char[][], char[], char[], char[], int, int, int) + * @see ICompletionRequestor#acceptMethod(char[], char[], char[], char[][], + * char[][], char[][], char[], char[], char[], int, int, int) */ - public void acceptMethod( - char[] declaringTypePackageName, - char[] declaringTypeName, - char[] selector, - char[][] parameterPackageNames, - char[][] parameterTypeNames, - char[][] parameterNames, - char[] returnTypePackageName, - char[] returnTypeName, - char[] completionName, - int modifiers, - int completionStart, - int completionEnd, - int relevance) { + public void acceptMethod(char[] declaringTypePackageName, + char[] declaringTypeName, char[] selector, + char[][] parameterPackageNames, char[][] parameterTypeNames, + char[][] parameterNames, char[] returnTypePackageName, + char[] returnTypeName, char[] completionName, int modifiers, + int completionStart, int completionEnd, int relevance) { } /* - * @see ICompletionRequestor#acceptMethodDeclaration(char[], char[], char[], char[][], char[][], char[][], char[], char[], char[], int, int, int) + * @see ICompletionRequestor#acceptMethodDeclaration(char[], char[], char[], + * char[][], char[][], char[][], char[], char[], char[], int, int, int) */ - public void acceptMethodDeclaration( - char[] declaringTypePackageName, - char[] declaringTypeName, - char[] selector, - char[][] parameterPackageNames, - char[][] parameterTypeNames, - char[][] parameterNames, - char[] returnTypePackageName, - char[] returnTypeName, - char[] completionName, - int modifiers, - int completionStart, - int completionEnd, - int relevance) { + public void acceptMethodDeclaration(char[] declaringTypePackageName, + char[] declaringTypeName, char[] selector, + char[][] parameterPackageNames, char[][] parameterTypeNames, + char[][] parameterNames, char[] returnTypePackageName, + char[] returnTypeName, char[] completionName, int modifiers, + int completionStart, int completionEnd, int relevance) { } /* * @see ICompletionRequestor#acceptModifier(char[], int, int) */ - public void acceptModifier( - char[] modifierName, - int completionStart, - int completionEnd, - int relevance) { + public void acceptModifier(char[] modifierName, int completionStart, + int completionEnd, int relevance) { } /* * @see ICompletionRequestor#acceptPackage(char[], char[], int, int) */ - public void acceptPackage( - char[] packageName, - char[] completionName, - int completionStart, - int completionEnd, - int relevance) { + public void acceptPackage(char[] packageName, char[] completionName, + int completionStart, int completionEnd, int relevance) { } /* * @see ICompletionRequestor#acceptType(char[], char[], char[], int, int) */ - public void acceptType( - char[] packageName, - char[] typeName, - char[] completionName, - int completionStart, - int completionEnd, - int relevance) { + public void acceptType(char[] packageName, char[] typeName, + char[] completionName, int completionStart, int completionEnd, + int relevance) { } /* - * @see ICompletionRequestor#acceptVariableName(char[], char[], char[], char[], int, int) + * @see ICompletionRequestor#acceptVariableName(char[], char[], char[], + * char[], int, int) */ - public void acceptVariableName( - char[] typePackageName, - char[] typeName, - char[] name, - char[] completionName, - int completionStart, - int completionEnd, - int relevance) { + public void acceptVariableName(char[] typePackageName, char[] typeName, + char[] name, char[] completionName, int completionStart, + int completionEnd, int relevance) { } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ElementChangedEvent.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ElementChangedEvent.java index 9c16bea..ad7e315 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ElementChangedEvent.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ElementChangedEvent.java @@ -13,29 +13,29 @@ package net.sourceforge.phpdt.core; import java.util.EventObject; /** - * An element changed event describes a change to the structure or contents - * of a tree of Java elements. The changes to the elements are described by - * the associated delta object carried by this event. + * An element changed event describes a change to the structure or contents of a + * tree of Java elements. The changes to the elements are described by the + * associated delta object carried by this event. *

    * This class is not intended to be instantiated or subclassed by clients. * Instances of this class are automatically created by the Java model. *

    - * + * * @see IElementChangedListener * @see IJavaElementDelta */ public class ElementChangedEvent extends EventObject { - + /** - * Event type constant (bit mask) indicating an after-the-fact - * report of creations, deletions, and modifications - * to one or more Java element(s) expressed as a hierarchical - * java element delta as returned by getDelta(). - * + * Event type constant (bit mask) indicating an after-the-fact report of + * creations, deletions, and modifications to one or more Java element(s) + * expressed as a hierarchical java element delta as returned by + * getDelta(). + * * Note: this notification occurs during the corresponding POST_CHANGE * resource change notification, and contains a full delta accounting for - * any JavaModel operation and/or resource change. - * + * any JavaModel operation and/or resource change. + * * @see IJavaElementDelta * @see org.eclipse.core.resources.IResourceChangeEvent * @see #getDelta() @@ -44,18 +44,19 @@ public class ElementChangedEvent extends EventObject { public static final int POST_CHANGE = 1; /** - * Event type constant (bit mask) indicating an after-the-fact - * report of creations, deletions, and modifications - * to one or more Java element(s) expressed as a hierarchical - * java element delta as returned by getDelta. - * + * Event type constant (bit mask) indicating an after-the-fact report of + * creations, deletions, and modifications to one or more Java element(s) + * expressed as a hierarchical java element delta as returned by + * getDelta. + * * Note: this notification occurs during the corresponding PRE_AUTO_BUILD - * resource change notification. The delta, which is notified here, only contains - * information relative to the previous JavaModel operations (in other words, - * it ignores the possible resources which have changed outside Java operations). - * In particular, it is possible that the JavaModel be inconsistent with respect to - * resources, which got modified outside JavaModel operations (it will only be - * fully consistent once the POST_CHANGE notification has occurred). + * resource change notification. The delta, which is notified here, only + * contains information relative to the previous JavaModel operations (in + * other words, it ignores the possible resources which have changed outside + * Java operations). In particular, it is possible that the JavaModel be + * inconsistent with respect to resources, which got modified outside + * JavaModel operations (it will only be fully consistent once the + * POST_CHANGE notification has occurred). * * @see IJavaElementDelta * @see org.eclipse.core.resources.IResourceChangeEvent @@ -65,50 +66,51 @@ public class ElementChangedEvent extends EventObject { public static final int PRE_AUTO_BUILD = 2; /** - * Event type constant (bit mask) indicating an after-the-fact - * report of creations, deletions, and modifications - * to one or more Java element(s) expressed as a hierarchical - * java element delta as returned by getDelta. - * + * Event type constant (bit mask) indicating an after-the-fact report of + * creations, deletions, and modifications to one or more Java element(s) + * expressed as a hierarchical java element delta as returned by + * getDelta. + * * Note: this notification occurs as a result of a working copy reconcile * operation. - * + * * @see IJavaElementDelta * @see org.eclipse.core.resources.IResourceChangeEvent * @see #getDelta() * @since 2.0 */ - public static final int POST_RECONCILE = 4; + public static final int POST_RECONCILE = 4; + /* - * Event type indicating the nature of this event. - * It can be a combination either: - * - POST_CHANGE - * - PRE_AUTO_BUILD - * - POST_RECONCILE + * Event type indicating the nature of this event. It can be a combination + * either: - POST_CHANGE - PRE_AUTO_BUILD - POST_RECONCILE */ - private int type; - + private int type; + /** - * Creates an new element changed event (based on a IJavaElementDelta). - * - * @param delta the Java element delta. + * Creates an new element changed event (based on a + * IJavaElementDelta). + * + * @param delta + * the Java element delta. */ public ElementChangedEvent(IJavaElementDelta delta, int type) { super(delta); this.type = type; } + /** * Returns the delta describing the change. - * + * * @return the delta describing the change */ public IJavaElementDelta getDelta() { return (IJavaElementDelta) source; } - + /** * Returns the type of event being reported. - * + * * @return one of the event type constants * @see #POST_CHANGE * @see #PRE_AUTO_BUILD diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/Flags.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/Flags.java index 9182b7f..89cd25e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/Flags.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/Flags.java @@ -12,8 +12,6 @@ package net.sourceforge.phpdt.core; import net.sourceforge.phpdt.internal.compiler.env.IConstants; - - /** * Utility class for decoding modifier flags in Java elements. *

    @@ -21,254 +19,373 @@ import net.sourceforge.phpdt.internal.compiler.env.IConstants; * instantiated or subclassed by clients. *

    *

    - * Note that the numeric values of these flags match the ones for class files - * as described in the Java Virtual Machine Specification. The AST class - * Modifier provides the same functionality as this class, only in - * the net.sourceforge.phpdt.core.dom package. + * Note that the numeric values of these flags match the ones for class files as + * described in the Java Virtual Machine Specification. The AST class + * Modifier provides the same functionality as this class, only + * in the net.sourceforge.phpdt.core.dom package. *

    - * + * * @see IMember#getFlags */ public final class Flags { - /** + /** * Constant representing the absence of any flag + * * @since 3.0 */ public static final int AccDefault = 0; + /** - * Public access flag. See The Java Virtual Machine Specification for more details. + * Public access flag. See The Java Virtual Machine Specification for more + * details. + * * @since 2.0 */ public static final int AccPublic = IConstants.AccPublic; + /** - * Private access flag. See The Java Virtual Machine Specification for more details. + * Private access flag. See The Java Virtual Machine Specification for more + * details. + * * @since 2.0 */ public static final int AccPrivate = IConstants.AccPrivate; + /** - * Protected access flag. See The Java Virtual Machine Specification for more details. + * Protected access flag. See The Java Virtual Machine Specification for + * more details. + * * @since 2.0 */ public static final int AccProtected = IConstants.AccProtected; + /** - * Static access flag. See The Java Virtual Machine Specification for more details. + * Static access flag. See The Java Virtual Machine Specification for more + * details. + * * @since 2.0 */ public static final int AccStatic = IConstants.AccStatic; + /** - * Final access flag. See The Java Virtual Machine Specification for more details. + * Final access flag. See The Java Virtual Machine Specification for more + * details. + * * @since 2.0 */ public static final int AccFinal = IConstants.AccFinal; + /** - * Synchronized access flag. See The Java Virtual Machine Specification for more details. + * Synchronized access flag. See The Java Virtual Machine Specification for + * more details. + * * @since 2.0 */ -// public static final int AccSynchronized = IConstants.AccSynchronized; + // public static final int AccSynchronized = IConstants.AccSynchronized; /** - * Volatile property flag. See The Java Virtual Machine Specification for more details. + * Volatile property flag. See The Java Virtual Machine Specification for + * more details. + * * @since 2.0 */ -// public static final int AccVolatile = IConstants.AccVolatile; + // public static final int AccVolatile = IConstants.AccVolatile; /** - * Transient property flag. See The Java Virtual Machine Specification for more details. + * Transient property flag. See The Java Virtual Machine Specification for + * more details. + * * @since 2.0 */ -// public static final int AccTransient = IConstants.AccTransient; + // public static final int AccTransient = IConstants.AccTransient; /** - * Native property flag. See The Java Virtual Machine Specification for more details. + * Native property flag. See The Java Virtual Machine Specification for more + * details. + * * @since 2.0 */ -// public static final int AccNative = IConstants.AccNative; + // public static final int AccNative = IConstants.AccNative; /** - * Interface property flag. See The Java Virtual Machine Specification for more details. + * Interface property flag. See The Java Virtual Machine Specification for + * more details. + * * @since 2.0 */ public static final int AccInterface = IConstants.AccInterface; + /** - * Abstract property flag. See The Java Virtual Machine Specification for more details. + * Abstract property flag. See The Java Virtual Machine Specification for + * more details. + * * @since 2.0 */ public static final int AccAbstract = IConstants.AccAbstract; + /** - * Strictfp property flag. See The Java Virtual Machine Specification for more details. + * Strictfp property flag. See The Java Virtual Machine Specification for + * more details. + * * @since 2.0 */ -// public static final int AccStrictfp = IConstants.AccStrictfp; + // public static final int AccStrictfp = IConstants.AccStrictfp; /** - * Super property flag. See The Java Virtual Machine Specification for more details. + * Super property flag. See The Java Virtual Machine Specification for more + * details. + * * @since 2.0 */ public static final int AccSuper = IConstants.AccSuper; + /** - * Synthetic property flag. See The Java Virtual Machine Specification for more details. + * Synthetic property flag. See The Java Virtual Machine Specification for + * more details. + * * @since 2.0 */ -// public static final int AccSynthetic = IConstants.AccSynthetic; + // public static final int AccSynthetic = IConstants.AccSynthetic; /** - * Deprecated property flag. See The Java Virtual Machine Specification for more details. + * Deprecated property flag. See The Java Virtual Machine Specification for + * more details. + * * @since 2.0 */ public static final int AccDeprecated = IConstants.AccDeprecated; - + /** * Not instantiable. */ private Flags() { } + /** - * Returns whether the given integer includes the abstract modifier. - * - * @param flags the flags - * @return true if the abstract modifier is included + * Returns whether the given integer includes the abstract + * modifier. + * + * @param flags + * the flags + * @return true if the abstract modifier is + * included */ public static boolean isAbstract(int flags) { return (flags & AccAbstract) != 0; } + /** - * Returns whether the given integer includes the indication that the + * Returns whether the given integer includes the indication that the * element is deprecated (@deprecated tag in Javadoc comment). - * - * @param flags the flags + * + * @param flags + * the flags * @return true if the element is marked as deprecated */ public static boolean isDeprecated(int flags) { return (flags & AccDeprecated) != 0; } + /** - * Returns whether the given integer includes the final modifier. - * - * @param flags the flags - * @return true if the final modifier is included + * Returns whether the given integer includes the final + * modifier. + * + * @param flags + * the flags + * @return true if the final modifier is + * included */ public static boolean isFinal(int flags) { return (flags & AccFinal) != 0; } + /** - * Returns whether the given integer includes the interface modifier. - * - * @param flags the flags - * @return true if the interface modifier is included + * Returns whether the given integer includes the interface + * modifier. + * + * @param flags + * the flags + * @return true if the interface modifier is + * included * @since 2.0 */ public static boolean isInterface(int flags) { return (flags & AccInterface) != 0; } + /** - * Returns whether the given integer includes the native modifier. - * - * @param flags the flags - * @return true if the native modifier is included - */ -// public static boolean isNative(int flags) { -// return (flags & AccNative) != 0; -// } + * Returns whether the given integer includes the native + * modifier. + * + * @param flags + * the flags + * @return true if the native modifier is + * included + */ + // public static boolean isNative(int flags) { + // return (flags & AccNative) != 0; + // } /** - * Returns whether the given integer includes the private modifier. - * - * @param flags the flags - * @return true if the private modifier is included + * Returns whether the given integer includes the private + * modifier. + * + * @param flags + * the flags + * @return true if the private modifier is + * included */ public static boolean isPrivate(int flags) { return (flags & AccPrivate) != 0; } + /** - * Returns whether the given integer includes the protected modifier. - * - * @param flags the flags - * @return true if the protected modifier is included + * Returns whether the given integer includes the protected + * modifier. + * + * @param flags + * the flags + * @return true if the protected modifier is + * included */ public static boolean isProtected(int flags) { return (flags & AccProtected) != 0; } + /** - * Returns whether the given integer includes the public modifier. - * - * @param flags the flags - * @return true if the public modifier is included + * Returns whether the given integer includes the public + * modifier. + * + * @param flags + * the flags + * @return true if the public modifier is + * included */ public static boolean isPublic(int flags) { return (flags & AccPublic) != 0; } + /** - * Returns whether the given integer includes the static modifier. - * - * @param flags the flags - * @return true if the static modifier is included + * Returns whether the given integer includes the static + * modifier. + * + * @param flags + * the flags + * @return true if the static modifier is + * included */ public static boolean isStatic(int flags) { return (flags & AccStatic) != 0; } + /** - * Returns whether the given integer includes the strictfp modifier. - * - * @param flags the flags - * @return true if the strictfp modifier is included - */ -// public static boolean isStrictfp(int flags) { -// return (flags & AccStrictfp) != 0; -// } + * Returns whether the given integer includes the strictfp + * modifier. + * + * @param flags + * the flags + * @return true if the strictfp modifier is + * included + */ + // public static boolean isStrictfp(int flags) { + // return (flags & AccStrictfp) != 0; + // } /** - * Returns whether the given integer includes the synchronized modifier. - * - * @param flags the flags - * @return true if the synchronized modifier is included - */ -// public static boolean isSynchronized(int flags) { -// return (flags & AccSynchronized) != 0; -// } + * Returns whether the given integer includes the synchronized + * modifier. + * + * @param flags + * the flags + * @return true if the synchronized modifier + * is included + */ + // public static boolean isSynchronized(int flags) { + // return (flags & AccSynchronized) != 0; + // } /** - * Returns whether the given integer includes the indication that the + * Returns whether the given integer includes the indication that the * element is synthetic. - * - * @param flags the flags + * + * @param flags + * the flags * @return true if the element is marked synthetic */ -// public static boolean isSynthetic(int flags) { -// return (flags & AccSynthetic) != 0; -// } + // public static boolean isSynthetic(int flags) { + // return (flags & AccSynthetic) != 0; + // } /** - * Returns whether the given integer includes the transient modifier. - * - * @param flags the flags - * @return true if the transient modifier is included - */ -// public static boolean isTransient(int flags) { -// return (flags & AccTransient) != 0; -// } + * Returns whether the given integer includes the transient + * modifier. + * + * @param flags + * the flags + * @return true if the transient modifier is + * included + */ + // public static boolean isTransient(int flags) { + // return (flags & AccTransient) != 0; + // } /** - * Returns whether the given integer includes the volatile modifier. - * - * @param flags the flags - * @return true if the volatile modifier is included - */ -// public static boolean isVolatile(int flags) { -// return (flags & AccVolatile) != 0; -// } + * Returns whether the given integer includes the volatile + * modifier. + * + * @param flags + * the flags + * @return true if the volatile modifier is + * included + */ + // public static boolean isVolatile(int flags) { + // return (flags & AccVolatile) != 0; + // } /** - * Returns a standard string describing the given modifier flags. - * Only modifier flags are included in the output; the deprecated and - * synthetic flags are ignored if set. + * Returns a standard string describing the given modifier flags. Only + * modifier flags are included in the output; the deprecated and synthetic + * flags are ignored if set. *

    * The flags are output in the following order: + * *

    -	 *   public protected private 
    -	 *   static 
    -	 *   abstract final native synchronized transient volatile strictfp
    +	 *   
    +	 * public
    +	 *  
    +	 * protected
    +	 *  
    +	 * private
    +	 *  
    +	 *   
    +	 * static
    +	 *  
    +	 *   
    +	 * abstract
    +	 *  
    +	 * final
    +	 *  
    +	 * native
    +	 *  
    +	 * synchronized
    +	 *  
    +	 * transient
    +	 *  
    +	 * volatile
    +	 *  
    +	 * strictfp
    +	 * 
     	 * 
    + * * This is a compromise between the orders specified in sections 8.1.1, * 8.3.1, 8.4.3, 8.8.3, 9.1.1, and 9.3 of The Java Language - * Specification, Second Edition (JLS2). - *

    + * Specification, Second Edition + * (JLS2). + *

    *

    * Examples results: + * *

    -	 *	  "public static final"
    -	 *	  "private native"
    +	 *	  
    +	 * "public static final"
    +	 * 
    +	 *	  
    +	 * "private native"
    +	 * 
     	 * 
    + * *

    - * - * @param flags the flags + * + * @param flags + * the flags * @return the standard string representation of the given flags */ public static String toString(int flags) { @@ -282,20 +399,20 @@ public final class Flags { sb.append("private "); //$NON-NLS-1$ if (isStatic(flags)) sb.append("static "); //$NON-NLS-1$ -// if (isAbstract(flags)) -// sb.append("abstract "); //$NON-NLS-1$ + // if (isAbstract(flags)) + // sb.append("abstract "); //$NON-NLS-1$ if (isFinal(flags)) sb.append("final "); //$NON-NLS-1$ -// if (isNative(flags)) -// sb.append("native "); //$NON-NLS-1$ -// if (isSynchronized(flags)) -// sb.append("synchronized "); //$NON-NLS-1$ -// if (isTransient(flags)) -// sb.append("transient "); //$NON-NLS-1$ -// if (isVolatile(flags)) -// sb.append("volatile "); //$NON-NLS-1$ -// if (isStrictfp(flags)) -// sb.append("strictfp "); //$NON-NLS-1$ + // if (isNative(flags)) + // sb.append("native "); //$NON-NLS-1$ + // if (isSynchronized(flags)) + // sb.append("synchronized "); //$NON-NLS-1$ + // if (isTransient(flags)) + // sb.append("transient "); //$NON-NLS-1$ + // if (isVolatile(flags)) + // sb.append("volatile "); //$NON-NLS-1$ + // if (isStrictfp(flags)) + // sb.append("strictfp "); //$NON-NLS-1$ int len = sb.length(); if (len == 0) diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBuffer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBuffer.java index 0a84671..819eb7e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBuffer.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBuffer.java @@ -14,250 +14,307 @@ import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IProgressMonitor; /** - * A buffer contains the text contents of a resource. It is not language-specific. - * The contents may be in the process of being edited, differing from the actual contents of the - * underlying resource. A buffer has an owner, which is an IOpenable. - * If a buffer does not have an underlying resource, saving the buffer has no effect. - * Buffers can be read-only. + * A buffer contains the text contents of a resource. It is not + * language-specific. The contents may be in the process of being edited, + * differing from the actual contents of the underlying resource. A buffer has + * an owner, which is an IOpenable. If a buffer does not have an + * underlying resource, saving the buffer has no effect. Buffers can be + * read-only. *

    - * Note that java model operations that manipulate an IBuffer (for example, - * IType.createMethod(...)) ensures that the same line delimiter - * (either "\n" or "\r" or "\r\n") is - * used across the whole buffer. Thus these operations may change the line delimiter(s) - * included in the string to be append, or replaced. - * However implementers of this interface should be aware that other clients of IBuffer - * might not do such transformations beforehand. + * Note that java model operations that manipulate an IBuffer + * (for example, IType.createMethod(...)) ensures that the same + * line delimiter (either "\n" or "\r" or + * "\r\n") is used across the whole buffer. Thus these + * operations may change the line delimiter(s) included in the string to be + * append, or replaced. However implementers of this interface should be aware + * that other clients of IBuffer might not do such + * transformations beforehand. *

    * This interface may be implemented by clients. *

    */ public interface IBuffer { - -/** - * Adds the given listener for changes to this buffer. - * Has no effect if an identical listener is already registered or if the buffer - * is closed. - * - * @param listener the listener of buffer changes - */ -public void addBufferChangedListener(IBufferChangedListener listener); -/** - * Appends the given character array to the contents of the buffer. - * This buffer will now have unsaved changes. - * Any client can append to the contents of the buffer, not just the owner of the buffer. - * Reports a buffer changed event. - *

    - * Has no effect if this buffer is read-only. - *

    - * A RuntimeException might be thrown if the buffer is closed. - * - * @param text the given character array to append to contents of the buffer - */ -public void append(char[] text); -/** - * Appends the given string to the contents of the buffer. - * This buffer will now have unsaved changes. - * Any client can append to the contents of the buffer, not just the owner of the buffer. - * Reports a buffer changed event. - *

    - * Has no effect if this buffer is read-only. - *

    - * A RuntimeException might be thrown if the buffer is closed. - * - * @param text the String to append to the contents of the buffer - */ -public void append(String text); -/** - * Closes the buffer. Any unsaved changes are lost. Reports a buffer changed event - * with a 0 offset and a 0 length. When this event is fired, the buffer should already - * be closed. - *

    - * Further operations on the buffer are not allowed, except for close. If an - * attempt is made to close an already closed buffer, the second attempt has no effect. - */ -public void close(); -/** - * Returns the character at the given position in this buffer. - *

    - * A RuntimeException might be thrown if the buffer is closed. - * - * @param position a zero-based source offset in this buffer - * @return the character at the given position in this buffer - */ -public char getChar(int position); -/** - * Returns the contents of this buffer as a character array, or null if - * the buffer has not been initialized. - *

    - * Callers should make no assumption about whether the returned character array - * is or is not the genuine article or a copy. In other words, if the client - * wishes to change this array, they should make a copy. Likewise, if the - * client wishes to hang on to the array in its current state, they should - * make a copy. - *

    - *

    - * A RuntimeException might be thrown if the buffer is closed. - * - * @return the characters contained in this buffer - */ -public char[] getCharacters(); -/** - * Returns the contents of this buffer as a String. Like all strings, - * the result is an immutable value object., It can also answer null if - * the buffer has not been initialized. - *

    - * A RuntimeException might be thrown if the buffer is closed. - * - * @return the contents of this buffer as a String - */ -public String getContents(); -/** - * Returns number of characters stored in this buffer. - *

    - * A RuntimeException might be thrown if the buffer is closed. - * - * @return the number of characters in this buffer - */ -public int getLength(); -/** - * Returns the Java openable element owning of this buffer. - * - * @return the openable element owning this buffer - */ -public IOpenable getOwner(); -/** - * Returns the given range of text in this buffer. - *

    - * A RuntimeException might be thrown if the buffer is closed. - * - * @param offset the zero-based starting offset - * @param length the number of characters to retrieve - * @return the given range of text in this buffer - */ -public String getText(int offset, int length); -/** - * Returns the underlying resource for which this buffer was opened, - * or null if this buffer was not opened on a resource. - * - * @return the underlying resource for this buffer, or null - * if none. - */ -public IResource getUnderlyingResource(); -/** - * Returns whether this buffer has been modified since it - * was opened or since it was last saved. - * If a buffer does not have an underlying resource, this method always - * returns true. - * - * @return a boolean indicating presence of unsaved changes (in - * the absence of any underlying resource, it will always return true). - */ -public boolean hasUnsavedChanges(); -/** - * Returns whether this buffer has been closed. - * - * @return a boolean indicating whether this buffer is closed. - */ -public boolean isClosed(); -/** - * Returns whether this buffer is read-only. - * - * @return a boolean indicating whether this buffer is read-only - */ -public boolean isReadOnly(); -/** - * Removes the given listener from this buffer. - * Has no affect if an identical listener is not registered or if the buffer is closed. - * - * @param listener the listener - */ -public void removeBufferChangedListener(IBufferChangedListener listener); -/** - * Replaces the given range of characters in this buffer with the given text. - * position and position + length must be in the range [0, getLength()]. - * length must not be negative. - *

    - * A RuntimeException might be thrown if the buffer is closed. - * - * @param position the zero-based starting position of the affected text range in this buffer - * @param length the length of the affected text range in this buffer - * @param text the replacing text as a character array - */ -public void replace(int position, int length, char[] text); -/** - * Replaces the given range of characters in this buffer with the given text. - * position and position + length must be in the range [0, getLength()]. - * length must not be negative. - *

    - * A RuntimeException might be thrown if the buffer is closed. - * - * @param position the zero-based starting position of the affected text range in this buffer - * @param length the length of the affected text range in this buffer - * @param text the replacing text as a String - */ -public void replace(int position, int length, String text); -/** - * Saves the contents of this buffer to its underlying resource. If - * successful, this buffer will have no unsaved changes. - * The buffer is left open. Saving a buffer with no unsaved - * changes has no effect - the underlying resource is not changed. - * If the buffer does not have an underlying resource or is read-only, this - * has no effect. - *

    - * The force parameter controls how this method deals with - * cases where the workbench is not completely in sync with the local file system. - * If false is specified, this method will only attempt - * to overwrite a corresponding file in the local file system provided - * it is in sync with the workbench. This option ensures there is no - * unintended data loss; it is the recommended setting. - * However, if true is specified, an attempt will be made - * to write a corresponding file in the local file system, - * overwriting any existing one if need be. - * In either case, if this method succeeds, the resource will be marked - * as being local (even if it wasn't before). - *

    - * A RuntimeException might be thrown if the buffer is closed. - * - * @param progress the progress monitor to notify - * @param force a boolean flag indicating how to deal with resource - * inconsistencies. - * - * @exception JavaModelException if an error occurs writing the buffer - * to the underlying resource - * - * @see org.eclipse.core.resources.IFile#setContents(java.io.InputStream, boolean, boolean, org.eclipse.core.runtime.IProgressMonitor) - */ -public void save(IProgressMonitor progress, boolean force) throws JavaModelException; -/** - * Sets the contents of this buffer to the given character array. - * This buffer will now have unsaved changes. - * Any client can set the contents of the buffer, not just the owner of the buffer. - * Reports a buffer changed event. - *

    - * Equivalent to replace(0,getLength(),contents). - *

    - *

    - * Has no effect if this buffer is read-only. - *

    - * A RuntimeException might be thrown if the buffer is closed. - * - * @param contents the new contents of this buffer as a character array - */ -public void setContents(char[] contents); -/** - * Sets the contents of this buffer to the given String. - * This buffer will now have unsaved changes. - * Any client can set the contents of the buffer, not just the owner of the buffer. - * Reports a buffer changed event. - *

    - * Equivalent to replace(0,getLength(),contents). - *

    - *

    - * Has no effect if this buffer is read-only. - *

    - * A RuntimeException might be thrown if the buffer is closed. - * - * @param contents the new contents of this buffer as a String - */ -public void setContents(String contents); + + /** + * Adds the given listener for changes to this buffer. Has no effect if an + * identical listener is already registered or if the buffer is closed. + * + * @param listener + * the listener of buffer changes + */ + public void addBufferChangedListener(IBufferChangedListener listener); + + /** + * Appends the given character array to the contents of the buffer. This + * buffer will now have unsaved changes. Any client can append to the + * contents of the buffer, not just the owner of the buffer. Reports a + * buffer changed event. + *

    + * Has no effect if this buffer is read-only. + *

    + * A RuntimeException might be thrown if the buffer is + * closed. + * + * @param text + * the given character array to append to contents of the buffer + */ + public void append(char[] text); + + /** + * Appends the given string to the contents of the buffer. This buffer will + * now have unsaved changes. Any client can append to the contents of the + * buffer, not just the owner of the buffer. Reports a buffer changed event. + *

    + * Has no effect if this buffer is read-only. + *

    + * A RuntimeException might be thrown if the buffer is + * closed. + * + * @param text + * the String to append to the contents of the + * buffer + */ + public void append(String text); + + /** + * Closes the buffer. Any unsaved changes are lost. Reports a buffer changed + * event with a 0 offset and a 0 length. When this event is fired, the + * buffer should already be closed. + *

    + * Further operations on the buffer are not allowed, except for close. If an + * attempt is made to close an already closed buffer, the second attempt has + * no effect. + */ + public void close(); + + /** + * Returns the character at the given position in this buffer. + *

    + * A RuntimeException might be thrown if the buffer is + * closed. + * + * @param position + * a zero-based source offset in this buffer + * @return the character at the given position in this buffer + */ + public char getChar(int position); + + /** + * Returns the contents of this buffer as a character array, or + * null if the buffer has not been initialized. + *

    + * Callers should make no assumption about whether the returned character + * array is or is not the genuine article or a copy. In other words, if the + * client wishes to change this array, they should make a copy. Likewise, if + * the client wishes to hang on to the array in its current state, they + * should make a copy. + *

    + *

    + * A RuntimeException might be thrown if the buffer is + * closed. + * + * @return the characters contained in this buffer + */ + public char[] getCharacters(); + + /** + * Returns the contents of this buffer as a String. Like all + * strings, the result is an immutable value object., It can also answer + * null if the buffer has not been initialized. + *

    + * A RuntimeException might be thrown if the buffer is + * closed. + * + * @return the contents of this buffer as a String + */ + public String getContents(); + + /** + * Returns number of characters stored in this buffer. + *

    + * A RuntimeException might be thrown if the buffer is + * closed. + * + * @return the number of characters in this buffer + */ + public int getLength(); + + /** + * Returns the Java openable element owning of this buffer. + * + * @return the openable element owning this buffer + */ + public IOpenable getOwner(); + + /** + * Returns the given range of text in this buffer. + *

    + * A RuntimeException might be thrown if the buffer is + * closed. + * + * @param offset + * the zero-based starting offset + * @param length + * the number of characters to retrieve + * @return the given range of text in this buffer + */ + public String getText(int offset, int length); + + /** + * Returns the underlying resource for which this buffer was opened, or + * null if this buffer was not opened on a resource. + * + * @return the underlying resource for this buffer, or null + * if none. + */ + public IResource getUnderlyingResource(); + + /** + * Returns whether this buffer has been modified since it was opened or + * since it was last saved. If a buffer does not have an underlying + * resource, this method always returns true. + * + * @return a boolean indicating presence of unsaved changes + * (in the absence of any underlying resource, it will always return + * true). + */ + public boolean hasUnsavedChanges(); + + /** + * Returns whether this buffer has been closed. + * + * @return a boolean indicating whether this buffer is + * closed. + */ + public boolean isClosed(); + + /** + * Returns whether this buffer is read-only. + * + * @return a boolean indicating whether this buffer is + * read-only + */ + public boolean isReadOnly(); + + /** + * Removes the given listener from this buffer. Has no affect if an + * identical listener is not registered or if the buffer is closed. + * + * @param listener + * the listener + */ + public void removeBufferChangedListener(IBufferChangedListener listener); + + /** + * Replaces the given range of characters in this buffer with the given + * text. position and position + length must + * be in the range [0, getLength()]. length must not be + * negative. + *

    + * A RuntimeException might be thrown if the buffer is + * closed. + * + * @param position + * the zero-based starting position of the affected text range in + * this buffer + * @param length + * the length of the affected text range in this buffer + * @param text + * the replacing text as a character array + */ + public void replace(int position, int length, char[] text); + + /** + * Replaces the given range of characters in this buffer with the given + * text. position and position + length must + * be in the range [0, getLength()]. length must not be + * negative. + *

    + * A RuntimeException might be thrown if the buffer is + * closed. + * + * @param position + * the zero-based starting position of the affected text range in + * this buffer + * @param length + * the length of the affected text range in this buffer + * @param text + * the replacing text as a String + */ + public void replace(int position, int length, String text); + + /** + * Saves the contents of this buffer to its underlying resource. If + * successful, this buffer will have no unsaved changes. The buffer is left + * open. Saving a buffer with no unsaved changes has no effect - the + * underlying resource is not changed. If the buffer does not have an + * underlying resource or is read-only, this has no effect. + *

    + * The force parameter controls how this method deals with + * cases where the workbench is not completely in sync with the local file + * system. If false is specified, this method will only + * attempt to overwrite a corresponding file in the local file system + * provided it is in sync with the workbench. This option ensures there is + * no unintended data loss; it is the recommended setting. However, if + * true is specified, an attempt will be made to write a + * corresponding file in the local file system, overwriting any existing one + * if need be. In either case, if this method succeeds, the resource will be + * marked as being local (even if it wasn't before). + *

    + * A RuntimeException might be thrown if the buffer is + * closed. + * + * @param progress + * the progress monitor to notify + * @param force + * a boolean flag indicating how to deal with + * resource inconsistencies. + * + * @exception JavaModelException + * if an error occurs writing the buffer to the underlying + * resource + * + * @see org.eclipse.core.resources.IFile#setContents(java.io.InputStream, + * boolean, boolean, org.eclipse.core.runtime.IProgressMonitor) + */ + public void save(IProgressMonitor progress, boolean force) + throws JavaModelException; + + /** + * Sets the contents of this buffer to the given character array. This + * buffer will now have unsaved changes. Any client can set the contents of + * the buffer, not just the owner of the buffer. Reports a buffer changed + * event. + *

    + * Equivalent to replace(0,getLength(),contents). + *

    + *

    + * Has no effect if this buffer is read-only. + *

    + * A RuntimeException might be thrown if the buffer is + * closed. + * + * @param contents + * the new contents of this buffer as a character array + */ + public void setContents(char[] contents); + + /** + * Sets the contents of this buffer to the given String. + * This buffer will now have unsaved changes. Any client can set the + * contents of the buffer, not just the owner of the buffer. Reports a + * buffer changed event. + *

    + * Equivalent to replace(0,getLength(),contents). + *

    + *

    + * Has no effect if this buffer is read-only. + *

    + * A RuntimeException might be thrown if the buffer is + * closed. + * + * @param contents + * the new contents of this buffer as a String + */ + public void setContents(String contents); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBufferChangedListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBufferChangedListener.java index 791fcc9..87faf43 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBufferChangedListener.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBufferChangedListener.java @@ -11,20 +11,21 @@ package net.sourceforge.phpdt.core; /** - * A listener, which gets notified when the contents of a specific buffer - * have changed, or when the buffer is closed. - * When a buffer is closed, the listener is notified after the buffer has been closed. - * A listener is not notified when a buffer is saved. + * A listener, which gets notified when the contents of a specific buffer have + * changed, or when the buffer is closed. When a buffer is closed, the listener + * is notified after the buffer has been closed. A listener is not + * notified when a buffer is saved. *

    * This interface may be implemented by clients. *

    */ public interface IBufferChangedListener { - /** + /** * Notifies that the given event has occurred. - * - * @param event the change event + * + * @param event + * the change event */ public void bufferChanged(BufferChangedEvent event); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBufferFactory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBufferFactory.java index 15b61e6..d5fcc17 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBufferFactory.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBufferFactory.java @@ -15,19 +15,20 @@ package net.sourceforge.phpdt.core; *

    * This interface may be implemented by clients. *

    + * * @since 2.0 */ public interface IBufferFactory { /** - * Creates a buffer for the given owner. - * The new buffer will be initialized with the contents of the owner - * if and only if it was not already initialized by the factory (a buffer is uninitialized if - * its content is null). + * Creates a buffer for the given owner. The new buffer will be initialized + * with the contents of the owner if and only if it was not already + * initialized by the factory (a buffer is uninitialized if its content is + * null). * - * @param owner the owner of the buffer + * @param owner + * the owner of the buffer * @see IBuffer */ IBuffer createBuffer(IOpenable owner); } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IClasspathEntry.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IClasspathEntry.java index 8d6e929..a9648aa 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IClasspathEntry.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IClasspathEntry.java @@ -12,97 +12,108 @@ package net.sourceforge.phpdt.core; import org.eclipse.core.runtime.IPath; -/** +/** * An entry on a Java project classpath identifying one or more package fragment - * roots. A classpath entry has a content kind (either source, - * K_SOURCE, or binary, K_BINARY), which is inherited - * by each package fragment root and package fragment associated with the entry. + * roots. A classpath entry has a content kind (either source, + * K_SOURCE, or binary, K_BINARY), which is + * inherited by each package fragment root and package fragment associated with + * the entry. *

    - * A classpath entry can refer to any of the following:

      + * A classpath entry can refer to any of the following: + *
        * - *
      • Source code in the current project. In this case, the entry identifies a - * root folder in the current project containing package fragments and - * .java source files. The root folder itself represents a default - * package, subfolders represent package fragments, and .java files - * represent compilation units. All compilation units will be compiled when - * the project is built. The classpath entry must specify the - * absolute path to the root folder. Entries of this kind are - * associated with the CPE_SOURCE constant. - * Source classpath entries can carry patterns to exclude selected files. - * Excluded .java source files do not appear as compilation - * units and are not compiled when the project is built. - *
      • + *
      • Source code in the current project. In this case, the entry identifies a + * root folder in the current project containing package fragments and + * .java source files. The root folder itself represents a + * default package, subfolders represent package fragments, and + * .java files represent compilation units. All compilation units + * will be compiled when the project is built. The classpath entry must specify + * the absolute path to the root folder. Entries of this kind are associated + * with the CPE_SOURCE constant. Source classpath entries can + * carry patterns to exclude selected files. Excluded .java + * source files do not appear as compilation units and are not compiled when the + * project is built.
      • * - *
      • A binary library in the current project, in another project, or in the external - * file system. In this case the entry identifies a JAR (or root folder) containing - * package fragments and .class files. The classpath entry - * must specify the absolute path to the JAR (or root folder), and in case it refers - * to an external JAR, then there is no associated resource in the workbench. Entries - * of this kind are associated with the CPE_LIBRARY constant.
      • + *
      • A binary library in the current project, in another project, or in the + * external file system. In this case the entry identifies a JAR (or root + * folder) containing package fragments and .class files. The + * classpath entry must specify the absolute path to the JAR (or root folder), + * and in case it refers to an external JAR, then there is no associated + * resource in the workbench. Entries of this kind are associated with the + * CPE_LIBRARY constant.
      • * - *
      • A required project. In this case the entry identifies another project in - * the workspace. The required project is used as a binary library when compiling - * (that is, the builder looks in the output location of the required project - * for required .class files when building). When performing other - * "development" operations - such as code assist, code resolve, type hierarchy - * creation, etc. - the source code of the project is referred to. Thus, development - * is performed against a required project's source code, and compilation is - * performed against a required project's last built state. The - * classpath entry must specify the absolute path to the - * project. Entries of this kind are associated with the CPE_PROJECT - * constant. - * Note: referencing a required project with a classpath entry refers to the source - * code or associated .class files located in its output location. - * It will also automatically include any other libraries or projects that the required project's classpath - * refers to, iff the corresponding classpath entries are tagged as being exported - * (IClasspathEntry#isExported). - * Unless exporting some classpath entries, classpaths are not chained by default - - * each project must specify its own classpath in its entirety.
      • + *
      • A required project. In this case the entry identifies another project in + * the workspace. The required project is used as a binary library when + * compiling (that is, the builder looks in the output location of the required + * project for required .class files when building). When + * performing other "development" operations - such as code assist, code + * resolve, type hierarchy creation, etc. - the source code of the project is + * referred to. Thus, development is performed against a required project's + * source code, and compilation is performed against a required project's last + * built state. The classpath entry must specify the absolute path to the + * project. Entries of this kind are associated with the + * CPE_PROJECT constant. Note: referencing a required project + * with a classpath entry refers to the source code or associated + * .class files located in its output location. It will also + * automatically include any other libraries or projects that the required + * project's classpath refers to, iff the corresponding classpath entries are + * tagged as being exported (IClasspathEntry#isExported). + * Unless exporting some classpath entries, classpaths are not chained by + * default - each project must specify its own classpath in its entirety.
      • * - *
      • A path beginning in a classpath variable defined globally to the workspace. - * Entries of this kind are associated with the CPE_VARIABLE constant. - * Classpath variables are created using JavaCore#setClasspathVariable, - * and gets resolved, to either a project or library entry, using - * JavaCore#getResolvedClasspathVariable. - * It is also possible to register an automatic initializer (ClasspathVariableInitializer), - * which will be invoked through the extension point "net.sourceforge.phpdt.core.classpathVariableInitializer". - * After resolution, a classpath variable entry may either correspond to a project or a library entry.
      • + *
      • A path beginning in a classpath variable defined globally to the + * workspace. Entries of this kind are associated with the + * CPE_VARIABLE constant. Classpath variables are created using + * JavaCore#setClasspathVariable, and gets resolved, to either a + * project or library entry, using + * JavaCore#getResolvedClasspathVariable. It is also possible to + * register an automatic initializer (ClasspathVariableInitializer), + * which will be invoked through the extension point + * "net.sourceforge.phpdt.core.classpathVariableInitializer". After resolution, + * a classpath variable entry may either correspond to a project or a library + * entry.
      • * - *
      • A named classpath container identified by its container path. - * A classpath container provides a way to indirectly reference a set of classpath entries through - * a classpath entry of kind CPE_CONTAINER. Typically, a classpath container can - * be used to describe a complex library composed of multiple JARs, projects or classpath variables, - * considering also that containers can be mapped differently on each project. Several projects can - * reference the same generic container path, but have each of them actually bound to a different - * container object. - * The container path is a formed by a first ID segment followed with extra segments, - * which can be used as additional hints for resolving this container reference. If no container was ever - * recorded for this container path onto this project (using setClasspathContainer, - * then a ClasspathContainerInitializer will be activated if any was registered for this - * container ID onto the extension point "net.sourceforge.phpdt.core.classpathContainerInitializer". - * A classpath container entry can be resolved explicitly using JavaCore#getClasspathContainer - * and the resulting container entries can contain any non-container entry. In particular, it may contain variable - * entries, which in turn needs to be resolved before being directly used. - *
        Also note that the container resolution APIs include an IJavaProject argument, so as to allow the same - * container path to be interpreted in different ways for different projects.
      • + *
      • A named classpath container identified by its container path. A + * classpath container provides a way to indirectly reference a set of classpath + * entries through a classpath entry of kind CPE_CONTAINER. + * Typically, a classpath container can be used to describe a complex library + * composed of multiple JARs, projects or classpath variables, considering also + * that containers can be mapped differently on each project. Several projects + * can reference the same generic container path, but have each of them actually + * bound to a different container object. The container path is a formed by a + * first ID segment followed with extra segments, which can be used as + * additional hints for resolving this container reference. If no container was + * ever recorded for this container path onto this project (using + * setClasspathContainer, then a + * ClasspathContainerInitializer will be activated if any was + * registered for this container ID onto the extension point + * "net.sourceforge.phpdt.core.classpathContainerInitializer". A classpath + * container entry can be resolved explicitly using + * JavaCore#getClasspathContainer and the resulting container + * entries can contain any non-container entry. In particular, it may contain + * variable entries, which in turn needs to be resolved before being directly + * used.
        + * Also note that the container resolution APIs include an IJavaProject + * argument, so as to allow the same container path to be interpreted in + * different ways for different projects.
      • *
      *

      - * The result of IJavaProject#getResolvedClasspath will have all entries of type - * CPE_VARIABLE and CPE_CONTAINER resolved to a set of - * CPE_SOURCE, CPE_LIBRARY or CPE_PROJECT - * classpath entries. + * The result of IJavaProject#getResolvedClasspath will have all + * entries of type CPE_VARIABLE and CPE_CONTAINER + * resolved to a set of CPE_SOURCE, CPE_LIBRARY + * or CPE_PROJECT classpath entries. *

      - * Any classpath entry other than a source folder (kind CPE_SOURCE) can - * be marked as being exported. Exported entries are automatically contributed to - * dependent projects, along with the project's default output folder, which is - * implicitly exported, and any auxiliary output folders specified on source - * classpath entries. The project's output folder(s) are always listed first, - * followed by the any exported entries. + * Any classpath entry other than a source folder (kind CPE_SOURCE) + * can be marked as being exported. Exported entries are automatically + * contributed to dependent projects, along with the project's default output + * folder, which is implicitly exported, and any auxiliary output folders + * specified on source classpath entries. The project's output folder(s) are + * always listed first, followed by the any exported entries. *

      - * This interface is not intended to be implemented by clients. - * Classpath entries can be created via methods on JavaCore. + * This interface is not intended to be implemented by clients. Classpath + * entries can be created via methods on JavaCore. *

      - * + * * @see JavaCore#newLibraryEntry * @see JavaCore#newProjectEntry * @see JavaCore#newSourceEntry @@ -114,67 +125,67 @@ import org.eclipse.core.runtime.IPath; public interface IClasspathEntry { /** - * Entry kind constant describing a classpath entry identifying a - * library. A library is a folder or JAR containing package - * fragments consisting of pre-compiled binaries. + * Entry kind constant describing a classpath entry identifying a library. A + * library is a folder or JAR containing package fragments consisting of + * pre-compiled binaries. */ int CPE_LIBRARY = 1; /** - * Entry kind constant describing a classpath entry identifying a - * required project. + * Entry kind constant describing a classpath entry identifying a required + * project. */ int CPE_PROJECT = 2; /** - * Entry kind constant describing a classpath entry identifying a - * folder containing package fragments with source code - * to be compiled. + * Entry kind constant describing a classpath entry identifying a folder + * containing package fragments with source code to be compiled. */ int CPE_SOURCE = 3; /** - * Entry kind constant describing a classpath entry defined using - * a path that begins with a classpath variable reference. + * Entry kind constant describing a classpath entry defined using a path + * that begins with a classpath variable reference. */ int CPE_VARIABLE = 4; /** - * Entry kind constant describing a classpath entry representing - * a name classpath container. + * Entry kind constant describing a classpath entry representing a name + * classpath container. * * @since 2.0 */ int CPE_CONTAINER = 5; /** - * Returns the kind of files found in the package fragments identified by this - * classpath entry. - * + * Returns the kind of files found in the package fragments identified by + * this classpath entry. + * * @return IPackageFragmentRoot.K_SOURCE for files containing - * source code, and IPackageFragmentRoot.K_BINARY for binary - * class files. - * There is no specified value for an entry denoting a variable (CPE_VARIABLE) - * or a classpath container (CPE_CONTAINER). + * source code, and IPackageFragmentRoot.K_BINARY for + * binary class files. There is no specified value for an entry + * denoting a variable (CPE_VARIABLE) or a + * classpath container (CPE_CONTAINER). */ int getContentKind(); /** * Returns the kind of this classpath entry. - * + * * @return one of: - *
        - *
      • CPE_SOURCE - this entry describes a source root in - its project - *
      • CPE_LIBRARY - this entry describes a folder or JAR - containing binaries - *
      • CPE_PROJECT - this entry describes another project - * - *
      • CPE_VARIABLE - this entry describes a project or library - * indirectly via a classpath variable in the first segment of the path - * * + *
          + *
        • CPE_SOURCE - this entry describes a source + * root in its project + *
        • CPE_LIBRARY - this entry describes a folder + * or JAR containing binaries + *
        • CPE_PROJECT - this entry describes another + * project + * + *
        • CPE_VARIABLE - this entry describes a project or + * library indirectly via a classpath variable in the first segment of the + * path * *
        • CPE_CONTAINER - this entry describes set of entries - * referenced indirectly via a classpath container + * referenced indirectly via a classpath container *
        */ int getEntryKind(); @@ -186,9 +197,9 @@ public interface IClasspathEntry { * Exclusion patterns allow specified portions of the resource tree rooted * at this source entry's path to be filtered out. If no exclusion patterns * are specified, this source entry includes all relevent files. Each path - * specified must be a relative path, and will be interpreted relative - * to this source entry's path. File patterns are case-sensitive. A file - * matched by one or more of these patterns is excluded from the + * specified must be a relative path, and will be interpreted relative to + * this source entry's path. File patterns are case-sensitive. A file + * matched by one or more of these patterns is excluded from the * corresponding package fragment root. *

        *

        @@ -197,66 +208,61 @@ public interface IClasspathEntry { *

        *

        * The pattern mechanism is similar to Ant's. Each pattern is represented as - * a relative path. The path segments can be regular file or folder names or simple patterns - * involving standard wildcard characters. + * a relative path. The path segments can be regular file or folder names or + * simple patterns involving standard wildcard characters. *

        *

        - * '*' matches 0 or more characters within a segment. So - * *.java matches .java, a.java - * and Foo.java, but not Foo.properties - * (does not end with .java). + * '*' matches 0 or more characters within a segment. So *.java + * matches .java, a.java and + * Foo.java, but not Foo.properties (does not + * end with .java). *

        *

        - * '?' matches 1 character within a segment. So ?.java - * matches a.java, A.java, - * but not .java or xyz.java (neither have - * just one character before .java). + * '?' matches 1 character within a segment. So ?.java + * matches a.java, A.java, but not + * .java or xyz.java (neither have just one + * character before .java). *

        *

        * Combinations of *'s and ?'s are allowed. *

        *

        - * The special pattern '**' matches zero or more segments. A path - * like tests/ that ends in a trailing separator is interpreted - * as tests/**, and would match all files under the - * the folder named tests. + * The special pattern '**' matches zero or more segments. A path like + * tests/ that ends in a trailing separator is interpreted as + * tests/**, and would match all files under the the + * folder named tests. *

        *

        * Examples: *

          - *
        • - * tests/** (or simply tests/) - * matches all files under a root folder - * named tests. This includes tests/Foo.java - * and tests/com/example/Foo.java, but not + *
        • tests/** (or simply tests/) + * matches all files under a root folder named tests. This + * includes tests/Foo.java and + * tests/com/example/Foo.java, but not * com/example/tests/Foo.java (not under a root folder named - * tests). - *
        • - *
        • - * tests/* matches all files directly below a root - * folder named tests. This includes tests/Foo.java - * and tests/FooHelp.java - * but not tests/com/example/Foo.java (not directly under - * a folder named tests) or - * com/Foo.java (not under a folder named tests). - *
        • - *
        • - * **/tests/** matches all files under any - * folder named tests. This includes tests/Foo.java, - * com/examples/tests/Foo.java, and - * com/examples/tests/unit/Foo.java, but not + * tests).
        • + *
        • tests/* matches all files directly below a root + * folder named tests. This includes + * tests/Foo.java and tests/FooHelp.java but + * not tests/com/example/Foo.java (not directly under a + * folder named tests) or com/Foo.java (not + * under a folder named tests).
        • + *
        • **/tests/** matches all files under + * any folder named tests. This includes + * tests/Foo.java, com/examples/tests/Foo.java, + * and com/examples/tests/unit/Foo.java, but not * com/example/Foo.java (not under a folder named - * tests). - *
        • + * tests). *
        *

        * - * @return the possibly empty list of resource exclusion patterns - * associated with this source entry, and null for other - * kinds of classpath entries + * @return the possibly empty list of resource exclusion patterns associated + * with this source entry, and null for other kinds + * of classpath entries * @since 2.1 */ IPath[] getExclusionPatterns(); + /** * Returns the set of patterns used to explicitly define resources to be * included with this source entry. @@ -282,75 +288,74 @@ public interface IClasspathEntry { *

        * Examples: *

          - *
        • - * The inclusion pattern src/** by itself includes all - * files under a root folder named src. - *
        • - *
        • - * The inclusion patterns src/** and + *
        • The inclusion pattern src/** by itself + * includes all files under a root folder named src.
        • + *
        • The inclusion patterns src/** and * tests/** includes all files under the root folders - * named src and tests. - *
        • - *
        • - * The inclusion pattern src/** together with the - * exclusion pattern src/**/Foo.java includes all - * files under a root folder named src except for ones - * named Foo.java. - *
        • + * named src and tests. + *
        • The inclusion pattern src/** together with + * the exclusion pattern src/**/Foo.java includes all + * files under a root folder named src except for ones named + * Foo.java.
        • *
        *

        * - * @return the possibly empty list of resource inclusion patterns - * associated with this source entry, and null for other - * kinds of classpath entries + * @return the possibly empty list of resource inclusion patterns associated + * with this source entry, and null for other kinds + * of classpath entries * @since 3.0 */ IPath[] getInclusionPatterns(); - + /** - * Returns the full path to the specific location where the builder writes - * .class files generated for this source entry - * (entry kind CPE_SOURCE). + * Returns the full path to the specific location where the builder writes + * .class files generated for this source entry (entry kind + * CPE_SOURCE). + *

        + * Source entries can optionally be associated with a specific output + * location. If none is provided, the source entry will be implicitly + * associated with its project default output location (see + * IJavaProject#getOutputLocation). + *

        *

        - * Source entries can optionally be associated with a specific output location. - * If none is provided, the source entry will be implicitly associated with its project - * default output location (see IJavaProject#getOutputLocation). - *

        - * NOTE: A specific output location cannot coincidate with another source/library entry. + * NOTE: A specific output location cannot coincidate with another + * source/library entry. *

        * - * @return the full path to the specific location where the builder writes - * .class files for this source entry, or null - * if using default output folder + * @return the full path to the specific location where the builder writes + * .class files for this source entry, or + * null if using default output folder * @since 2.1 */ IPath getOutputLocation(); - + /** * Returns the path of this classpath entry. - * - * The meaning of the path of a classpath entry depends on its entry kind:
          - *
        • Source code in the current project (CPE_SOURCE) - - * The path associated with this entry is the absolute path to the root folder.
        • - *
        • A binary library in the current project (CPE_LIBRARY) - the path - * associated with this entry is the absolute path to the JAR (or root folder), and - * in case it refers to an external JAR, then there is no associated resource in - * the workbench. - *
        • A required project (CPE_PROJECT) - the path of the entry denotes the - * path to the corresponding project resource.
        • - *
        • A variable entry (CPE_VARIABLE) - the first segment of the path - * is the name of a classpath variable. If this classpath variable - * is bound to the path P, the path of the corresponding classpath entry - * is computed by appending to P the segments of the returned - * path without the variable.
        • - *
        • A container entry (CPE_CONTAINER) - the path of the entry - * is the name of the classpath container, which can be bound indirectly to a set of classpath - * entries after resolution. The containerPath is a formed by a first ID segment followed with - * extra segments that can be used as additional hints for resolving this container - * reference (also see IClasspathContainer). - *
        • + * + * The meaning of the path of a classpath entry depends on its entry kind: + *
            + *
          • Source code in the current project (CPE_SOURCE) - + * The path associated with this entry is the absolute path to the root + * folder.
          • + *
          • A binary library in the current project (CPE_LIBRARY) - + * the path associated with this entry is the absolute path to the JAR (or + * root folder), and in case it refers to an external JAR, then there is no + * associated resource in the workbench. + *
          • A required project (CPE_PROJECT) - the path of the + * entry denotes the path to the corresponding project resource.
          • + *
          • A variable entry (CPE_VARIABLE) - the first segment + * of the path is the name of a classpath variable. If this classpath + * variable is bound to the path P, the path of the corresponding + * classpath entry is computed by appending to P the segments of + * the returned path without the variable.
          • + *
          • A container entry (CPE_CONTAINER) - the path of the + * entry is the name of the classpath container, which can be bound + * indirectly to a set of classpath entries after resolution. The + * containerPath is a formed by a first ID segment followed with extra + * segments that can be used as additional hints for resolving this + * container reference (also see IClasspathContainer).
          • *
          - * + * * @return the path of this classpath entry */ IPath getPath(); @@ -361,59 +366,67 @@ public interface IClasspathEntry { * source attachment. *

          * Only library and variable classpath entries may have source attachments. - * For library classpath entries, the result path (if present) locates a source - * archive or folder. This archive or folder can be located in a project of the - * workspace or outside thr workspace. For variable classpath entries, the - * result path (if present) has an analogous form and meaning as the - * variable path, namely the first segment is the name of a classpath variable. + * For library classpath entries, the result path (if present) locates a + * source archive or folder. This archive or folder can be located in a + * project of the workspace or outside thr workspace. For variable classpath + * entries, the result path (if present) has an analogous form and meaning + * as the variable path, namely the first segment is the name of a classpath + * variable. *

          - * - * @return the path to the source archive or folder, or null if none + * + * @return the path to the source archive or folder, or null + * if none */ IPath getSourceAttachmentPath(); /** - * Returns the path within the source archive or folder where package fragments - * are located. An empty path indicates that packages are located at - * the root of the source archive or folder. Returns a non-null value - * if and only if getSourceAttachmentPath returns - * a non-null value. - * - * @return the path within the source archive or folder, or null if - * not applicable + * Returns the path within the source archive or folder where package + * fragments are located. An empty path indicates that packages are located + * at the root of the source archive or folder. Returns a non-null + * value if and only if getSourceAttachmentPath returns a + * non-null value. + * + * @return the path within the source archive or folder, or + * null if not applicable */ IPath getSourceAttachmentRootPath(); - + /** - * Returns whether this entry is exported to dependent projects. - * Always returns false for source entries (kind + * Returns whether this entry is exported to dependent projects. Always + * returns false for source entries (kind * CPE_SOURCE), which cannot be exported. * - * @return true if exported, and false otherwise + * @return true if exported, and false + * otherwise * @since 2.0 */ boolean isExported(); - + /** - * This is a helper method, which returns the resolved classpath entry denoted - * by an entry (if it is a variable entry). It is obtained by resolving the variable - * reference in the first segment. Returns null if unable to resolve using - * the following algorithm: + * This is a helper method, which returns the resolved classpath entry + * denoted by an entry (if it is a variable entry). It is obtained by + * resolving the variable reference in the first segment. Returns null + * if unable to resolve using the following algorithm: *
            *
          • if variable segment cannot be resolved, returns null
          • - *
          • finds a project, JAR or binary folder in the workspace at the resolved path location
          • - *
          • if none finds an external JAR file or folder outside the workspace at the resolved path location
          • + *
          • finds a project, JAR or binary folder in the workspace at the + * resolved path location
          • + *
          • if none finds an external JAR file or folder outside the workspace + * at the resolved path location
          • *
          • if none returns null
          • *
          *

          - * Variable source attachment is also resolved and recorded in the resulting classpath entry. + * Variable source attachment is also resolved and recorded in the resulting + * classpath entry. *

          + * * @return the resolved library or project classpath entry, or null - * if the given path could not be resolved to a classpath entry - *

          - * Note that this deprecated API doesn't handle CPE_CONTAINER entries. + * if the given path could not be resolved to a classpath entry + *

          + * Note that this deprecated API doesn't handle CPE_CONTAINER + * entries. * * @deprecated - use JavaCore.getResolvedClasspathEntry(...) */ - IClasspathEntry getResolvedEntry(); + IClasspathEntry getResolvedEntry(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICodeAssist.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICodeAssist.java index a0d7654..624ad4d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICodeAssist.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICodeAssist.java @@ -20,104 +20,138 @@ package net.sourceforge.phpdt.core; public interface ICodeAssist { /** - * Performs code completion at the given offset position in this compilation unit, - * reporting results to the given completion requestor. The offset - * is the 0-based index of the character, after which code assist is desired. - * An offset of -1 indicates to code assist at the beginning of this - * compilation unit. - * - * @param offset the given offset position - * @param requestor the given completion requestor - * - * @exception JavaModelException if code assist could not be performed. Reasons include:

            - *
          • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
          • - *
          • The position specified is < -1 or is greater than this compilation unit's - * source length (INDEX_OUT_OF_BOUNDS) - *
          - * - * @exception IllegalArgumentException if requestor is null + * Performs code completion at the given offset position in this compilation + * unit, reporting results to the given completion requestor. The + * offset is the 0-based index of the character, after which + * code assist is desired. An offset of -1 indicates to code + * assist at the beginning of this compilation unit. + * + * @param offset + * the given offset position + * @param requestor + * the given completion requestor + * + * @exception JavaModelException + * if code assist could not be performed. Reasons include: + *
            + *
          • This Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
          • + *
          • The position specified is < -1 or is greater than + * this compilation unit's source length + * (INDEX_OUT_OF_BOUNDS) + *
          + * + * @exception IllegalArgumentException + * if requestor is null * @deprecated Use {@link #codeComplete(int, ICompletionRequestor)} instead. */ void codeComplete(int offset, ICodeCompletionRequestor requestor) - throws JavaModelException; + throws JavaModelException; + /** - * Performs code completion at the given offset position in this compilation unit, - * reporting results to the given completion requestor. The offset - * is the 0-based index of the character, after which code assist is desired. - * An offset of -1 indicates to code assist at the beginning of this - * compilation unit. - * - * @param offset the given offset position - * @param requestor the given completion requestor - * @exception JavaModelException if code assist could not be performed. Reasons include:
            - *
          • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
          • - *
          • The position specified is < -1 or is greater than this compilation unit's - * source length (INDEX_OUT_OF_BOUNDS) - *
          - * - * @exception IllegalArgumentException if requestor is null + * Performs code completion at the given offset position in this compilation + * unit, reporting results to the given completion requestor. The + * offset is the 0-based index of the character, after which + * code assist is desired. An offset of -1 indicates to code + * assist at the beginning of this compilation unit. + * + * @param offset + * the given offset position + * @param requestor + * the given completion requestor + * @exception JavaModelException + * if code assist could not be performed. Reasons include: + *
            + *
          • This Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
          • + *
          • The position specified is < -1 or is greater than + * this compilation unit's source length + * (INDEX_OUT_OF_BOUNDS) + *
          + * + * @exception IllegalArgumentException + * if requestor is null * @since 2.0 - */ - // TODO (jerome - once CompletionRequestor is working) @ deprecated Use {@link #codeComplete(int, CompletionRequestor)} instead. + */ + // TODO (jerome - once CompletionRequestor is working) @ deprecated Use + // {@link #codeComplete(int, CompletionRequestor)} instead. void codeComplete(int offset, ICompletionRequestor requestor) - throws JavaModelException; - + throws JavaModelException; + /** * DO NOT USE: This API element was added in anticipation of J2SE * 1.5 support, which is planned for the next release of Eclipse after 3.0. * It is currently unimplemented, and the API may change slightly before * reaching its final form. *

          - * Performs code completion at the given offset position in this compilation unit, - * reporting results to the given completion requestor. The offset - * is the 0-based index of the character, after which code assist is desired. - * An offset of -1 indicates to code assist at the beginning of this - * compilation unit. + * Performs code completion at the given offset position in this compilation + * unit, reporting results to the given completion requestor. The + * offset is the 0-based index of the character, after which + * code assist is desired. An offset of -1 indicates to code + * assist at the beginning of this compilation unit. *

          - * - * @param offset the given offset position - * @param requestor the given completion requestor - * @exception JavaModelException if code assist could not be performed. Reasons include:

            - *
          • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
          • - *
          • The position specified is < -1 or is greater than this compilation unit's - * source length (INDEX_OUT_OF_BOUNDS) - *
          - * - * @exception IllegalArgumentException if requestor is null + * + * @param offset + * the given offset position + * @param requestor + * the given completion requestor + * @exception JavaModelException + * if code assist could not be performed. Reasons include: + *
            + *
          • This Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
          • + *
          • The position specified is < -1 or is greater than + * this compilation unit's source length + * (INDEX_OUT_OF_BOUNDS) + *
          + * + * @exception IllegalArgumentException + * if requestor is null * @since 3.0 - */ + */ void codeComplete(int offset, CompletionRequestor requestor) - throws JavaModelException; - + throws JavaModelException; + /** - * Performs code completion at the given offset position in this compilation unit, - * reporting results to the given completion requestor. The offset - * is the 0-based index of the character, after which code assist is desired. - * An offset of -1 indicates to code assist at the beginning of this - * compilation unit. - * It considers types in the working copies with the given owner first. In other words, - * the owner's working copies will take precedence over their original compilation units - * in the workspace. + * Performs code completion at the given offset position in this compilation + * unit, reporting results to the given completion requestor. The + * offset is the 0-based index of the character, after which + * code assist is desired. An offset of -1 indicates to code + * assist at the beginning of this compilation unit. It considers types in + * the working copies with the given owner first. In other words, the + * owner's working copies will take precedence over their original + * compilation units in the workspace. *

          - * Note that if a working copy is empty, it will be as if the original compilation - * unit had been deleted. + * Note that if a working copy is empty, it will be as if the original + * compilation unit had been deleted. *

          - * - * @param offset the given offset position - * @param requestor the given completion requestor - * @param owner the owner of working copies that take precedence over their original compilation units - * @exception JavaModelException if code assist could not be performed. Reasons include:
            - *
          • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
          • - *
          • The position specified is < -1 or is greater than this compilation unit's - * source length (INDEX_OUT_OF_BOUNDS) - *
          - * - * @exception IllegalArgumentException if requestor is null + * + * @param offset + * the given offset position + * @param requestor + * the given completion requestor + * @param owner + * the owner of working copies that take precedence over their + * original compilation units + * @exception JavaModelException + * if code assist could not be performed. Reasons include: + *
            + *
          • This Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
          • + *
          • The position specified is < -1 or is greater than + * this compilation unit's source length + * (INDEX_OUT_OF_BOUNDS) + *
          + * + * @exception IllegalArgumentException + * if requestor is null * @since 3.0 */ - // TODO (jerome - once CompletionRequestor is working) @ deprecated Use {@link #codeComplete(int, CompletionRequestor, WorkingCopyOwner)} instead. - void codeComplete(int offset, ICompletionRequestor requestor, WorkingCopyOwner owner) - throws JavaModelException; + // TODO (jerome - once CompletionRequestor is working) @ deprecated Use + // {@link #codeComplete(int, CompletionRequestor, WorkingCopyOwner)} + // instead. + void codeComplete(int offset, ICompletionRequestor requestor, + WorkingCopyOwner owner) throws JavaModelException; /** * DO NOT USE: This API element was added in anticipation of J2SE @@ -125,74 +159,96 @@ public interface ICodeAssist { * It is currently unimplemented, and the API may change slightly before * reaching its final form. *

          - * Performs code completion at the given offset position in this compilation unit, - * reporting results to the given completion requestor. The offset - * is the 0-based index of the character, after which code assist is desired. - * An offset of -1 indicates to code assist at the beginning of this - * compilation unit. - * It considers types in the working copies with the given owner first. In other words, - * the owner's working copies will take precedence over their original compilation units - * in the workspace. + * Performs code completion at the given offset position in this compilation + * unit, reporting results to the given completion requestor. The + * offset is the 0-based index of the character, after which + * code assist is desired. An offset of -1 indicates to code + * assist at the beginning of this compilation unit. It considers types in + * the working copies with the given owner first. In other words, the + * owner's working copies will take precedence over their original + * compilation units in the workspace. *

          - * Note that if a working copy is empty, it will be as if the original compilation - * unit had been deleted. + * Note that if a working copy is empty, it will be as if the original + * compilation unit had been deleted. *

          - * - * @param offset the given offset position - * @param requestor the given completion requestor - * @param owner the owner of working copies that take precedence over their original compilation units - * @exception JavaModelException if code assist could not be performed. Reasons include:
            - *
          • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
          • - *
          • The position specified is < -1 or is greater than this compilation unit's - * source length (INDEX_OUT_OF_BOUNDS) - *
          - * - * @exception IllegalArgumentException if requestor is null + * + * @param offset + * the given offset position + * @param requestor + * the given completion requestor + * @param owner + * the owner of working copies that take precedence over their + * original compilation units + * @exception JavaModelException + * if code assist could not be performed. Reasons include: + *
            + *
          • This Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
          • + *
          • The position specified is < -1 or is greater than + * this compilation unit's source length + * (INDEX_OUT_OF_BOUNDS) + *
          + * + * @exception IllegalArgumentException + * if requestor is null * @since 3.0 */ - void codeComplete(int offset, CompletionRequestor requestor, WorkingCopyOwner owner) - throws JavaModelException; + void codeComplete(int offset, CompletionRequestor requestor, + WorkingCopyOwner owner) throws JavaModelException; /** - * Returns the Java elements correspondiing to the given selected text in this compilation unit. - * The offset is the 0-based index of the first selected character. - * The length is the number of selected characters. + * Returns the Java elements correspondiing to the given selected text in + * this compilation unit. The offset is the 0-based index of + * the first selected character. The length is the number of + * selected characters. * - * @param offset the given offset position - * @param length the number of selected characters + * @param offset + * the given offset position + * @param length + * the number of selected characters * @return the Java elements correspondiing to the given selected text - * - * @exception JavaModelException if code resolve could not be performed. Reasons include: - *
        • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
        • - *
        • The range specified is not within this element's - * source range (INDEX_OUT_OF_BOUNDS) - *
        - * + * + * @exception JavaModelException + * if code resolve could not be performed. Reasons include: + *
      • This Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
      • + *
      • The range specified is not within this element's + * source range (INDEX_OUT_OF_BOUNDS) + *
      + * */ IJavaElement[] codeSelect(int offset, int length) throws JavaModelException; + /** - * Returns the Java elements correspondiing to the given selected text in this compilation unit. - * The offset is the 0-based index of the first selected character. - * The length is the number of selected characters. - * It considers types in the working copies with the given owner first. In other words, - * the owner's working copies will take precedence over their original compilation units - * in the workspace. + * Returns the Java elements correspondiing to the given selected text in + * this compilation unit. The offset is the 0-based index of + * the first selected character. The length is the number of + * selected characters. It considers types in the working copies with the + * given owner first. In other words, the owner's working copies will take + * precedence over their original compilation units in the workspace. *

      - * Note that if a working copy is empty, it will be as if the original compilation - * unit had been deleted. + * Note that if a working copy is empty, it will be as if the original + * compilation unit had been deleted. *

      * - * @param offset the given offset position - * @param length the number of selected characters - * @param owner the owner of working copies that take precedence over their original compilation units + * @param offset + * the given offset position + * @param length + * the number of selected characters + * @param owner + * the owner of working copies that take precedence over their + * original compilation units * @return the Java elements correspondiing to the given selected text - * - * @exception JavaModelException if code resolve could not be performed. Reasons include: - *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    • The range specified is not within this element's - * source range (INDEX_OUT_OF_BOUNDS) - *
    + * + * @exception JavaModelException + * if code resolve could not be performed. Reasons include: + *
  • This Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
  • + *
  • The range specified is not within this element's + * source range (INDEX_OUT_OF_BOUNDS) + * * @since 3.0 */ - IJavaElement[] codeSelect(int offset, int length, WorkingCopyOwner owner) throws JavaModelException; + IJavaElement[] codeSelect(int offset, int length, WorkingCopyOwner owner) + throws JavaModelException; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICodeCompletionRequestor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICodeCompletionRequestor.java index 26a923f..ba7d375 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICodeCompletionRequestor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICodeCompletionRequestor.java @@ -13,251 +13,301 @@ package net.sourceforge.phpdt.core; import org.eclipse.core.resources.IMarker; /** - * A completion requestor accepts results as they are computed and is aware - * of source positions to complete the various different results. + * A completion requestor accepts results as they are computed and is aware of + * source positions to complete the various different results. *

    * This interface may be implemented by clients. *

    - * + * * @see ICodeAssist * @deprecated Use {@link CompletionRequestor} instead. */ public interface ICodeCompletionRequestor { -/** - * Code assist notification of a class completion. - * - * @param packageName Declaring package name of the class. - * @param className Name of the class. - * @param completionName The completion for the class. - * Can include ';' for imported classes. - * @param modifiers The modifiers of the class. - * @param completionStart The start position of insertion of the name of the class. - * @param completionEnd The end position of insertion of the name of the class. - * - * NOTE - All package and type names are presented in their readable form: - * Package names are in the form "a.b.c". - * Nested type names are in the qualified form "A.M". - * The default package is represented by an empty array. - */ -void acceptClass( - char[] packageName, - char[] className, - char[] completionName, - int modifiers, - int completionStart, - int completionEnd); -/** - * Code assist notification of a compilation error detected during completion. - * @param marker Only problems which are categorized as errors are notified to the requestor, - * warnings are silently ignored. - * In case an error got signaled, no other completions might be available, - * therefore the problem message should be presented to the user. - * The source positions of the problem are related to the source where it was - * detected (might be in another compilation unit, if it was indirectly requested - * during the code assist process). - * Note: the problem knows its originating file name. - */ -void acceptError(IMarker marker); -/** - * Code assist notification of a field completion. - * - * @param declaringTypePackageName Name of the package in which the type that contains this field is declared. - * - * @param declaringTypeName Name of the type declaring this new field. - * - * @param name Name of the field. - * - * @param typePackageName Name of the package in which the type of this field is declared. - * - * @param typeName Name of the type of this field. - * - * @param completionName The completion for the field. - * - * @param modifiers The modifiers of this field. - * - * @param completionStart The start position of insertion of the name of this field. - * - * @param completionEnd The end position of insertion of the name of this field. - * - * NOTE - All package and type names are presented in their readable form: - * Package names are in the form "a.b.c". - * Base types are in the form "int" or "boolean". - * Array types are in the qualified form "M[]" or "int[]". - * Nested type names are in the qualified form "A.M". - * The default package is represented by an empty array. - */ -void acceptField( - char[] declaringTypePackageName, - char[] declaringTypeName, - char[] name, - char[] typePackageName, - char[] typeName, - char[] completionName, - int modifiers, - int completionStart, - int completionEnd); -/** - * Code assist notification of an interface completion. - * - * @param packageName Declaring package name of the interface. - * @param interfaceName Name of the interface. - * @param completionName The completion for the interface. - * Can include ';' for imported interfaces. - * @param modifiers The modifiers of the interface. - * @param completionStart The start position of insertion of the name of the interface. - * @param completionEnd The end position of insertion of the name of the interface. - * - * NOTE - All package and type names are presented in their readable form: - * Package names are in the form "a.b.c". - * Nested type names are in the qualified form "A.M". - * The default package is represented by an empty array. - */ -void acceptInterface( - char[] packageName, - char[] interfaceName, - char[] completionName, - int modifiers, - int completionStart, - int completionEnd); -/** - * Code assist notification of a keyword completion. - * - * @param keywordName The keyword source. - * @param completionStart The start position of insertion of the name of this keyword. - * @param completionEnd The end position of insertion of the name of this keyword. - */ -void acceptKeyword(char[] keywordName, int completionStart, int completionEnd); -/** - * Code assist notification of a label completion. - * - * @param labelName The label source. - * @param completionStart The start position of insertion of the name of this label. - * @param completionEnd The end position of insertion of the name of this label. - */ -void acceptLabel(char[] labelName, int completionStart, int completionEnd); -/** - * Code assist notification of a local variable completion. - * - * @param name Name of the new local variable. - * - * @param typePackageName Name of the package in which the type of this new local variable is declared. - * - * @param typeName Name of the type of this new local variable. - * - * @param modifiers The modifiers of this new local variable. - * - * @param completionStart The start position of insertion of the name of this new local variable. - * - * @param completionEnd The end position of insertion of the name of this new local variable. - * - * NOTE - All package and type names are presented in their readable form: - * Package names are in the form "a.b.c". - * Base types are in the form "int" or "boolean". - * Array types are in the qualified form "M[]" or "int[]". - * Nested type names are in the qualified form "A.M". - * The default package is represented by an empty array. - */ -void acceptLocalVariable( - char[] name, - char[] typePackageName, - char[] typeName, - int modifiers, - int completionStart, - int completionEnd); -/** - * Code assist notification of a method completion. - * - * @param declaringTypePackageName Name of the package in which the type that contains this new method is declared. - * - * @param declaringTypeName Name of the type declaring this new method. - * - * @param selector Name of the new method. - * - * @param parameterPackageNames Names of the packages in which the parameter types are declared. - * Should contain as many elements as parameterTypeNames. - * - * @param parameterTypeNames Names of the parameters types. - * Should contain as many elements as parameterPackageNames. - * - * @param returnTypePackageName Name of the package in which the return type is declared. - * - * @param returnTypeName Name of the return type of this new method, should be null for a constructor. - * - * @param completionName The completion for the method. - * Can include zero, one or two brackets. If the closing bracket is included, then the cursor should be placed before it. - * - * @param modifiers The modifiers of this new method. - * - * @param completionStart The start position of insertion of the name of this new method. - * - * @param completionEnd The end position of insertion of the name of this new method. - * - * NOTE - All package and type names are presented in their readable form: - * Package names are in the form "a.b.c". - * Base types are in the form "int" or "boolean". - * Array types are in the qualified form "M[]" or "int[]". - * Nested type names are in the qualified form "A.M". - * The default package is represented by an empty array. - * - * NOTE: parameter names can be retrieved from the source model after the user selects a specific method. - */ -void acceptMethod( - char[] declaringTypePackageName, - char[] declaringTypeName, - char[] selector, - char[][] parameterPackageNames, - char[][] parameterTypeNames, - char[] returnTypePackageName, - char[] returnTypeName, - char[] completionName, - int modifiers, - int completionStart, - int completionEnd); -/** - * Code assist notification of a modifier completion. - * - * @param modifierName The new modifier. - * @param completionStart The start position of insertion of the name of this new modifier. - * @param completionEnd The end position of insertion of the name of this new modifier. - */ -void acceptModifier(char[] modifierName, int completionStart, int completionEnd); -/** - * Code assist notification of a package completion. - * - * @param packageName The package name. - * @param completionName The completion for the package. - * Can include '.*;' for imports. - * @param completionStart The start position of insertion of the name of this new package. - * @param completionEnd The end position of insertion of the name of this new package. - * - * NOTE - All package names are presented in their readable form: - * Package names are in the form "a.b.c". - * The default package is represented by an empty array. - */ -void acceptPackage( - char[] packageName, - char[] completionName, - int completionStart, - int completionEnd); -/** - * Code assist notification of a type completion. - * - * @param packageName Declaring package name of the type. - * @param typeName Name of the type. - * @param completionName The completion for the type. - * Can include ';' for imported types. - * @param completionStart The start position of insertion of the name of the type. - * @param completionEnd The end position of insertion of the name of the type. - * - * NOTE - All package and type names are presented in their readable form: - * Package names are in the form "a.b.c". - * Nested type names are in the qualified form "A.M". - * The default package is represented by an empty array. - */ -void acceptType( - char[] packageName, - char[] typeName, - char[] completionName, - int completionStart, - int completionEnd); + /** + * Code assist notification of a class completion. + * + * @param packageName + * Declaring package name of the class. + * @param className + * Name of the class. + * @param completionName + * The completion for the class. Can include ';' for imported + * classes. + * @param modifiers + * The modifiers of the class. + * @param completionStart + * The start position of insertion of the name of the class. + * @param completionEnd + * The end position of insertion of the name of the class. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". Nested type names are in the + * qualified form "A.M". The default package is represented by an empty + * array. + */ + void acceptClass(char[] packageName, char[] className, + char[] completionName, int modifiers, int completionStart, + int completionEnd); + + /** + * Code assist notification of a compilation error detected during + * completion. + * + * @param marker + * Only problems which are categorized as errors are notified to + * the requestor, warnings are silently ignored. In case an error + * got signaled, no other completions might be available, + * therefore the problem message should be presented to the user. + * The source positions of the problem are related to the source + * where it was detected (might be in another compilation unit, + * if it was indirectly requested during the code assist + * process). Note: the problem knows its originating file name. + */ + void acceptError(IMarker marker); + + /** + * Code assist notification of a field completion. + * + * @param declaringTypePackageName + * Name of the package in which the type that contains this field + * is declared. + * + * @param declaringTypeName + * Name of the type declaring this new field. + * + * @param name + * Name of the field. + * + * @param typePackageName + * Name of the package in which the type of this field is + * declared. + * + * @param typeName + * Name of the type of this field. + * + * @param completionName + * The completion for the field. + * + * @param modifiers + * The modifiers of this field. + * + * @param completionStart + * The start position of insertion of the name of this field. + * + * @param completionEnd + * The end position of insertion of the name of this field. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". Base types are in the form "int" + * or "boolean". Array types are in the qualified form "M[]" or "int[]". + * Nested type names are in the qualified form "A.M". The default package is + * represented by an empty array. + */ + void acceptField(char[] declaringTypePackageName, char[] declaringTypeName, + char[] name, char[] typePackageName, char[] typeName, + char[] completionName, int modifiers, int completionStart, + int completionEnd); + + /** + * Code assist notification of an interface completion. + * + * @param packageName + * Declaring package name of the interface. + * @param interfaceName + * Name of the interface. + * @param completionName + * The completion for the interface. Can include ';' for imported + * interfaces. + * @param modifiers + * The modifiers of the interface. + * @param completionStart + * The start position of insertion of the name of the interface. + * @param completionEnd + * The end position of insertion of the name of the interface. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". Nested type names are in the + * qualified form "A.M". The default package is represented by an empty + * array. + */ + void acceptInterface(char[] packageName, char[] interfaceName, + char[] completionName, int modifiers, int completionStart, + int completionEnd); + + /** + * Code assist notification of a keyword completion. + * + * @param keywordName + * The keyword source. + * @param completionStart + * The start position of insertion of the name of this keyword. + * @param completionEnd + * The end position of insertion of the name of this keyword. + */ + void acceptKeyword(char[] keywordName, int completionStart, + int completionEnd); + + /** + * Code assist notification of a label completion. + * + * @param labelName + * The label source. + * @param completionStart + * The start position of insertion of the name of this label. + * @param completionEnd + * The end position of insertion of the name of this label. + */ + void acceptLabel(char[] labelName, int completionStart, int completionEnd); + + /** + * Code assist notification of a local variable completion. + * + * @param name + * Name of the new local variable. + * + * @param typePackageName + * Name of the package in which the type of this new local + * variable is declared. + * + * @param typeName + * Name of the type of this new local variable. + * + * @param modifiers + * The modifiers of this new local variable. + * + * @param completionStart + * The start position of insertion of the name of this new local + * variable. + * + * @param completionEnd + * The end position of insertion of the name of this new local + * variable. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". Base types are in the form "int" + * or "boolean". Array types are in the qualified form "M[]" or "int[]". + * Nested type names are in the qualified form "A.M". The default package is + * represented by an empty array. + */ + void acceptLocalVariable(char[] name, char[] typePackageName, + char[] typeName, int modifiers, int completionStart, + int completionEnd); + + /** + * Code assist notification of a method completion. + * + * @param declaringTypePackageName + * Name of the package in which the type that contains this new + * method is declared. + * + * @param declaringTypeName + * Name of the type declaring this new method. + * + * @param selector + * Name of the new method. + * + * @param parameterPackageNames + * Names of the packages in which the parameter types are + * declared. Should contain as many elements as + * parameterTypeNames. + * + * @param parameterTypeNames + * Names of the parameters types. Should contain as many elements + * as parameterPackageNames. + * + * @param returnTypePackageName + * Name of the package in which the return type is declared. + * + * @param returnTypeName + * Name of the return type of this new method, should be + * null for a constructor. + * + * @param completionName + * The completion for the method. Can include zero, one or two + * brackets. If the closing bracket is included, then the cursor + * should be placed before it. + * + * @param modifiers + * The modifiers of this new method. + * + * @param completionStart + * The start position of insertion of the name of this new + * method. + * + * @param completionEnd + * The end position of insertion of the name of this new method. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". Base types are in the form "int" + * or "boolean". Array types are in the qualified form "M[]" or "int[]". + * Nested type names are in the qualified form "A.M". The default package is + * represented by an empty array. + * + * NOTE: parameter names can be retrieved from the source model after the + * user selects a specific method. + */ + void acceptMethod(char[] declaringTypePackageName, + char[] declaringTypeName, char[] selector, + char[][] parameterPackageNames, char[][] parameterTypeNames, + char[] returnTypePackageName, char[] returnTypeName, + char[] completionName, int modifiers, int completionStart, + int completionEnd); + + /** + * Code assist notification of a modifier completion. + * + * @param modifierName + * The new modifier. + * @param completionStart + * The start position of insertion of the name of this new + * modifier. + * @param completionEnd + * The end position of insertion of the name of this new + * modifier. + */ + void acceptModifier(char[] modifierName, int completionStart, + int completionEnd); + + /** + * Code assist notification of a package completion. + * + * @param packageName + * The package name. + * @param completionName + * The completion for the package. Can include '.*;' for imports. + * @param completionStart + * The start position of insertion of the name of this new + * package. + * @param completionEnd + * The end position of insertion of the name of this new package. + * + * NOTE - All package names are presented in their readable form: Package + * names are in the form "a.b.c". The default package is represented by an + * empty array. + */ + void acceptPackage(char[] packageName, char[] completionName, + int completionStart, int completionEnd); + + /** + * Code assist notification of a type completion. + * + * @param packageName + * Declaring package name of the type. + * @param typeName + * Name of the type. + * @param completionName + * The completion for the type. Can include ';' for imported + * types. + * @param completionStart + * The start position of insertion of the name of the type. + * @param completionEnd + * The end position of insertion of the name of the type. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". Nested type names are in the + * qualified form "A.M". The default package is represented by an empty + * array. + */ + void acceptType(char[] packageName, char[] typeName, char[] completionName, + int completionStart, int completionEnd); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICodeFormatter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICodeFormatter.java index d960dc3..f9c08f9 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICodeFormatter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICodeFormatter.java @@ -13,9 +13,10 @@ package net.sourceforge.phpdt.core; import java.util.Map; /** - * Specification for a generic source code formatter. Client plug-ins can contribute - * an implementation for an ICodeFormatter, through the extension point "org.phpeclipse.phpdt.core.codeFormatter". - * In case none is found, a default formatter can be provided through the ToolFactory. + * Specification for a generic source code formatter. Client plug-ins can + * contribute an implementation for an ICodeFormatter, through the extension + * point "org.phpeclipse.phpdt.core.codeFormatter". In case none is found, a + * default formatter can be provided through the ToolFactory. * * @see ToolFactory#createCodeFormatter() * @see ToolFactory#createDefaultCodeFormatter(Map options) @@ -23,23 +24,29 @@ import java.util.Map; */ public interface ICodeFormatter { - /** - * Formats the String sourceString, - * and returns a string containing the formatted version. + /** + * Formats the String sourceString, and returns a string + * containing the formatted version. * - * @param string the string to format - * @param indentationLevel the initial indentation level, used - * to shift left/right the entire source fragment. An initial indentation - * level of zero has no effect. - * @param positions an array of positions to map. These are - * character-based source positions inside the original source, - * for which corresponding positions in the formatted source will - * be computed (so as to relocate elements associated with the original - * source). It updates the positions array with updated positions. - * If set to null, then no positions are mapped. - * @param lineSeparator the line separator to use in formatted source, - * if set to null, then the platform default one will be used. + * @param string + * the string to format + * @param indentationLevel + * the initial indentation level, used to shift left/right the + * entire source fragment. An initial indentation level of zero + * has no effect. + * @param positions + * an array of positions to map. These are character-based source + * positions inside the original source, for which corresponding + * positions in the formatted source will be computed (so as to + * relocate elements associated with the original source). It + * updates the positions array with updated positions. If set to + * null, then no positions are mapped. + * @param lineSeparator + * the line separator to use in formatted source, if set to + * null, then the platform default one will be + * used. * @return the formatted output string. */ - String format(String string, int indentationLevel, int[] positions, String lineSeparator); + String format(String string, int indentationLevel, int[] positions, + String lineSeparator); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICompilationUnit.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICompilationUnit.java index df9ee27..52a777c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICompilationUnit.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICompilationUnit.java @@ -12,306 +12,394 @@ package net.sourceforge.phpdt.core; import org.eclipse.core.runtime.IProgressMonitor; - - /** - * Represents an entire Java compilation unit (.java source file). - * Compilation unit elements need to be opened before they can be navigated or manipulated. - * The children are of type IPackageDeclaration, - * IImportContainer, and IType, - * and appear in the order in which they are declared in the source. - * If a .java file cannot be parsed, its structure remains unknown. - * Use IJavaElement.isStructureKnown to determine whether this is - * the case. + * Represents an entire Java compilation unit (.java source + * file). Compilation unit elements need to be opened before they can be + * navigated or manipulated. The children are of type + * IPackageDeclaration, IImportContainer, and + * IType, and appear in the order in which they are declared in + * the source. If a .java file cannot be parsed, its structure + * remains unknown. Use IJavaElement.isStructureKnown to + * determine whether this is the case. *

    * This interface is not intended to be implemented by clients. *

    - */ -public interface ICompilationUnit extends IJavaElement, ISourceReference, IParent, IOpenable, IWorkingCopy, ISourceManipulation { -//extends IJavaElement, ISourceReference, IParent, IOpenable, IWorkingCopy, ISourceManipulation, ICodeAssist { + */ +public interface ICompilationUnit extends IJavaElement, ISourceReference, + IParent, IOpenable, IWorkingCopy, ISourceManipulation { + // extends IJavaElement, ISourceReference, IParent, IOpenable, IWorkingCopy, + // ISourceManipulation, ICodeAssist { /** * Constant indicating that a reconcile operation should not return an AST. + * * @since 3.0 */ public static final int NO_AST = 0; /** - * Changes this compilation unit handle into a working copy. A new IBuffer is - * created using this compilation unit handle's owner. Uses the primary owner is none was - * specified when this compilation unit handle was created. + * Changes this compilation unit handle into a working copy. A new + * IBuffer is created using this compilation unit handle's + * owner. Uses the primary owner is none was specified when this compilation + * unit handle was created. *

    - * When switching to working copy mode, problems are reported to given + * When switching to working copy mode, problems are reported to given * IProblemRequestor. *

    *

    - * Once in working copy mode, changes to this compilation unit or its children are done in memory. - * Only the new buffer is affected. Using commitWorkingCopy(boolean, IProgressMonitor) - * will bring the underlying resource in sync with this compilation unit. + * Once in working copy mode, changes to this compilation unit or its + * children are done in memory. Only the new buffer is affected. Using + * commitWorkingCopy(boolean, IProgressMonitor) will bring + * the underlying resource in sync with this compilation unit. *

    *

    - * If this compilation unit was already in working copy mode, an internal counter is incremented and no - * other action is taken on this compilation unit. To bring this compilation unit back into the original mode - * (where it reflects the underlying resource), discardWorkingCopy must be call as many - * times as becomeWorkingCopy. + * If this compilation unit was already in working copy mode, an internal + * counter is incremented and no other action is taken on this compilation + * unit. To bring this compilation unit back into the original mode (where + * it reflects the underlying resource), discardWorkingCopy + * must be call as many times as becomeWorkingCopy. *

    * - * @param problemRequestor a requestor which will get notified of problems detected during - * reconciling as they are discovered. The requestor can be set to null indicating - * that the client is not interested in problems. - * @param monitor a progress monitor used to report progress while opening this compilation unit - * or null if no progress should be reported - * @throws JavaModelException if this compilation unit could not become a working copy. + * @param problemRequestor + * a requestor which will get notified of problems detected + * during reconciling as they are discovered. The requestor can + * be set to null indicating that the client is + * not interested in problems. + * @param monitor + * a progress monitor used to report progress while opening this + * compilation unit or null if no progress should + * be reported + * @throws JavaModelException + * if this compilation unit could not become a working copy. * @see #discardWorkingCopy() * @since 3.0 */ - void becomeWorkingCopy(IProblemRequestor problemRequestor, IProgressMonitor monitor) throws JavaModelException; + void becomeWorkingCopy(IProblemRequestor problemRequestor, + IProgressMonitor monitor) throws JavaModelException; + /** * Commits the contents of this working copy to its underlying resource. - * - *

    It is possible that the contents of the original resource have changed - * since this working copy was created, in which case there is an update conflict. - * The value of the force parameter effects the resolution of - * such a conflict:

      - *
    • true - in this case the contents of this working copy are applied to - * the underlying resource even though this working copy was created before - * a subsequent change in the resource
    • - *
    • false - in this case a JavaModelException is thrown
    • - *
    + * *

    - * Since 2.1, a working copy can be created on a not-yet existing compilation - * unit. In particular, such a working copy can then be committed in order to create - * the corresponding compilation unit. - *

    - * @param force a flag to handle the cases when the contents of the original resource have changed - * since this working copy was created - * @param monitor the given progress monitor - * @throws JavaModelException if this working copy could not commit. Reasons include: + * It is possible that the contents of the original resource have changed + * since this working copy was created, in which case there is an update + * conflict. The value of the force parameter effects the + * resolution of such a conflict: *
      - *
    • A CoreException occurred while updating an underlying resource - *
    • This element is not a working copy (INVALID_ELEMENT_TYPES) - *
    • A update conflict (described above) (UPDATE_CONFLICT) + *
    • true - in this case the contents of this working copy + * are applied to the underlying resource even though this working copy was + * created before a subsequent change in the resource
    • + *
    • false - in this case a + * JavaModelException is thrown
    • *
    + *

    + * Since 2.1, a working copy can be created on a not-yet existing + * compilation unit. In particular, such a working copy can then be + * committed in order to create the corresponding compilation unit. + *

    + * + * @param force + * a flag to handle the cases when the contents of the original + * resource have changed since this working copy was created + * @param monitor + * the given progress monitor + * @throws JavaModelException + * if this working copy could not commit. Reasons include: + *
      + *
    • A CoreException occurred while updating + * an underlying resource + *
    • This element is not a working copy + * (INVALID_ELEMENT_TYPES) + *
    • A update conflict (described above) (UPDATE_CONFLICT) + *
    * @since 3.0 */ - void commitWorkingCopy(boolean force, IProgressMonitor monitor) throws JavaModelException; + void commitWorkingCopy(boolean force, IProgressMonitor monitor) + throws JavaModelException; + /** - * Changes this compilation unit in working copy mode back to its original mode. + * Changes this compilation unit in working copy mode back to its original + * mode. *

    * This has no effect if this compilation unit was not in working copy mode. *

    *

    * If becomeWorkingCopy was called several times on this - * compilation unit, discardWorkingCopy must be called as + * compilation unit, discardWorkingCopy must be called as * many times before it switches back to the original mode. *

    * - * @throws JavaModelException if this working copy could not return in its original mode. + * @throws JavaModelException + * if this working copy could not return in its original mode. * @see #becomeWorkingCopy(IProblemRequestor, IProgressMonitor) * @since 3.0 */ void discardWorkingCopy() throws JavaModelException; -/** - * Creates and returns an import declaration in this compilation unit - * with the given name. - *

    - * Optionally, the new element can be positioned before the specified - * sibling. If no sibling is specified, the element will be inserted - * as the last import declaration in this compilation unit. - *

    - * If the compilation unit already includes the specified import declaration, - * the import is not generated (it does not generate duplicates). - * Note that it is valid to specify both a single-type import and an on-demand import - * for the same package, for example "java.io.File" and - * "java.io.*", in which case both are preserved since the semantics - * of this are not the same as just importing "java.io.*". - * Importing "java.lang.*", or the package in which the compilation unit - * is defined, are not treated as special cases. If they are specified, they are - * included in the result. - * - * @param name the name of the import declaration to add as defined by JLS2 7.5. (For example: "java.io.File" or - * "java.awt.*") - * @param sibling the existing element which the import declaration will be inserted immediately before (if - * null , then this import will be inserted as the last import declaration. - * @param monitor the progress monitor to notify - * @return the newly inserted import declaration (or the previously existing one in case attempting to create a duplicate) - * - * @exception JavaModelException if the element could not be created. Reasons include: - *

      - *
    • This Java element does not exist or the specified sibling does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    • A CoreException occurred while updating an underlying resource - *
    • The specified sibling is not a child of this compilation unit (INVALID_SIBLING) - *
    • The name is not a valid import name (INVALID_NAME) - *
    - */ -//IImportDeclaration createImport(String name, IJavaElement sibling, IProgressMonitor monitor) throws JavaModelException; -/** - * Creates and returns a package declaration in this compilation unit - * with the given package name. - * - *

    If the compilation unit already includes the specified package declaration, - * it is not generated (it does not generate duplicates). - * - * @param name the name of the package declaration to add as defined by JLS2 7.4. (For example, "java.lang") - * @param monitor the progress monitor to notify - * @return the newly inserted package declaration (or the previously existing one in case attempting to create a duplicate) - * - * @exception JavaModelException if the element could not be created. Reasons include: - *

      - *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    • A CoreException occurred while updating an underlying resource - *
    • The name is not a valid package name (INVALID_NAME) - *
    - */ -// IPackageDeclaration createPackageDeclaration(String name, IProgressMonitor monitor) throws JavaModelException; -/** - * Creates and returns a type in this compilation unit with the - * given contents. If this compilation unit does not exist, one - * will be created with an appropriate package declaration. - *

    - * Optionally, the new type can be positioned before the specified - * sibling. If sibling is null, the type will be appended - * to the end of this compilation unit. - * - *

    It is possible that a type with the same name already exists in this compilation unit. - * The value of the force parameter effects the resolution of - * such a conflict:

      - *
    • true - in this case the type is created with the new contents
    • - *
    • false - in this case a JavaModelException is thrown
    • - *
    - * - * @param contents the source contents of the type declaration to add. - * @param sibling the existing element which the type will be inserted immediately before (if - * null , then this type will be inserted as the last type declaration. - * @param force a boolean flag indicating how to deal with duplicates - * @param monitor the progress monitor to notify - * @return the newly inserted type - * - * @exception JavaModelException if the element could not be created. Reasons include: - *
      - *
    • The specified sibling element does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    • A CoreException occurred while updating an underlying resource - *
    • The specified sibling is not a child of this compilation unit (INVALID_SIBLING) - *
    • The contents could not be recognized as a type declaration (INVALID_CONTENTS) - *
    • There was a naming collision with an existing type (NAME_COLLISION) - *
    - */ -//IType createType(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) throws JavaModelException; -/** - * Returns all types declared in this compilation unit in the order - * in which they appear in the source. - * This includes all top-level types and nested member types. - * It does NOT include local types (types defined in methods). - * - * @return the array of top-level and member types defined in a compilation unit, in declaration order. - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource - */ -IType[] getAllTypes() throws JavaModelException; -/** - * Returns the smallest element within this compilation unit that - * includes the given source position (that is, a method, field, etc.), or - * null if there is no element other than the compilation - * unit itself at the given position, or if the given position is not - * within the source range of this compilation unit. - * - * @param position a source position inside the compilation unit - * @return the innermost Java element enclosing a given source position or null - * if none (excluding the compilation unit). - * @exception JavaModelException if the compilation unit does not exist or if an - * exception occurs while accessing its corresponding resource - */ -IJavaElement getElementAt(int position) throws JavaModelException; -/** - * Returns the first import declaration in this compilation unit with the given name. - * This is a handle-only method. The import declaration may or may not exist. This - * is a convenience method - imports can also be accessed from a compilation unit's - * import container. - * - * @param name the name of the import to find as defined by JLS2 7.5. (For example: "java.io.File" - * or "java.awt.*") - * @return a handle onto the corresponding import declaration. The import declaration may or may not exist. - */ -IImportDeclaration getImport(String name) ; -/** - * Returns the import declarations in this compilation unit - * in the order in which they appear in the source. This is - * a convenience method - import declarations can also be - * accessed from a compilation unit's import container. - * - * @return the import declarations in this compilation unit - * @throws JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource - */ -IImportDeclaration[] getImports() throws JavaModelException; -/** - * Returns the import container for this compilation unit. - * This is a handle-only method. The import container may or - * may not exist. The import container can used to access the - * imports. - * @return a handle onto the corresponding import container. The - * import contain may or may not exist. - */ -IImportContainer getImportContainer(); -/** - * Returns the import declarations in this compilation unit - * in the order in which they appear in the source. This is - * a convenience method - import declarations can also be - * accessed from a compilation unit's import container. - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource - */ -//IImportDeclaration[] getImports() throws JavaModelException; -/** - * Returns the first package declaration in this compilation unit with the given package name - * (there normally is at most one package declaration). - * This is a handle-only method. The package declaration may or may not exist. - * - * @param name the name of the package declaration as defined by JLS2 7.4. (For example, "java.lang") - */ -IPackageDeclaration getPackageDeclaration(String name); -/** - * Returns the package declarations in this compilation unit - * in the order in which they appear in the source. - * There normally is at most one package declaration. - * - * @return an array of package declaration (normally of size one) - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource - */ -IPackageDeclaration[] getPackageDeclarations() throws JavaModelException; -/** - * Returns the primary compilation unit (whose owner is the primary owner) - * this working copy was created from, or this compilation unit if this a primary - * compilation unit. - *

    - * Note that the returned primary compilation unit can be in working copy mode. - *

    - * - * @return the primary compilation unit this working copy was created from, - * or this compilation unit if it is primary - * @since 3.0 - */ -ICompilationUnit getPrimary(); -/** - * Returns the top-level type declared in this compilation unit with the given simple type name. - * The type name has to be a valid compilation unit name. - * This is a handle-only method. The type may or may not exist. - * - * @param name the simple name of the requested type in the compilation unit - * @return a handle onto the corresponding type. The type may or may not exist. - * @see JavaConventions#validateCompilationUnitName(String name) - */ -IType getType(String name); -/** - * Returns the top-level types declared in this compilation unit - * in the order in which they appear in the source. - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource - */ -IType[] getTypes() throws JavaModelException; + + /** + * Creates and returns an import declaration in this compilation unit with + * the given name. + *

    + * Optionally, the new element can be positioned before the specified + * sibling. If no sibling is specified, the element will be inserted as the + * last import declaration in this compilation unit. + *

    + * If the compilation unit already includes the specified import + * declaration, the import is not generated (it does not generate + * duplicates). Note that it is valid to specify both a single-type import + * and an on-demand import for the same package, for example + * "java.io.File" and "java.io.*", in which + * case both are preserved since the semantics of this are not the same as + * just importing "java.io.*". Importing + * "java.lang.*", or the package in which the compilation + * unit is defined, are not treated as special cases. If they are specified, + * they are included in the result. + * + * @param name + * the name of the import declaration to add as defined by JLS2 + * 7.5. (For example: "java.io.File" or + * "java.awt.*") + * @param sibling + * the existing element which the import declaration will be + * inserted immediately before (if null , then + * this import will be inserted as the last import declaration. + * @param monitor + * the progress monitor to notify + * @return the newly inserted import declaration (or the previously existing + * one in case attempting to create a duplicate) + * + * @exception JavaModelException + * if the element could not be created. Reasons include: + *

      + *
    • This Java element does not exist or the specified + * sibling does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while + * updating an underlying resource + *
    • The specified sibling is not a child of this + * compilation unit (INVALID_SIBLING) + *
    • The name is not a valid import name (INVALID_NAME) + *
    + */ + // IImportDeclaration createImport(String name, IJavaElement sibling, + // IProgressMonitor monitor) throws JavaModelException; + /** + * Creates and returns a package declaration in this compilation unit with + * the given package name. + * + *

    + * If the compilation unit already includes the specified package + * declaration, it is not generated (it does not generate duplicates). + * + * @param name + * the name of the package declaration to add as defined by JLS2 + * 7.4. (For example, "java.lang") + * @param monitor + * the progress monitor to notify + * @return the newly inserted package declaration (or the previously + * existing one in case attempting to create a duplicate) + * + * @exception JavaModelException + * if the element could not be created. Reasons include: + *

      + *
    • This Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while + * updating an underlying resource + *
    • The name is not a valid package name (INVALID_NAME) + *
    + */ + // IPackageDeclaration createPackageDeclaration(String name, + // IProgressMonitor monitor) throws JavaModelException; + /** + * Creates and returns a type in this compilation unit with the given + * contents. If this compilation unit does not exist, one will be created + * with an appropriate package declaration. + *

    + * Optionally, the new type can be positioned before the specified sibling. + * If sibling is null, the type will be + * appended to the end of this compilation unit. + * + *

    + * It is possible that a type with the same name already exists in this + * compilation unit. The value of the force parameter effects + * the resolution of such a conflict: + *

      + *
    • true - in this case the type is created with the new + * contents
    • + *
    • false - in this case a + * JavaModelException is thrown
    • + *
    + * + * @param contents + * the source contents of the type declaration to add. + * @param sibling + * the existing element which the type will be inserted + * immediately before (if null , then this type + * will be inserted as the last type declaration. + * @param force + * a boolean flag indicating how to deal with + * duplicates + * @param monitor + * the progress monitor to notify + * @return the newly inserted type + * + * @exception JavaModelException + * if the element could not be created. Reasons include: + *
      + *
    • The specified sibling element does not exist + * (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while + * updating an underlying resource + *
    • The specified sibling is not a child of this + * compilation unit (INVALID_SIBLING) + *
    • The contents could not be recognized as a type + * declaration (INVALID_CONTENTS) + *
    • There was a naming collision with an existing type + * (NAME_COLLISION) + *
    + */ + // IType createType(String contents, IJavaElement sibling, boolean force, + // IProgressMonitor monitor) throws JavaModelException; + /** + * Returns all types declared in this compilation unit in the order in which + * they appear in the source. This includes all top-level types and nested + * member types. It does NOT include local types (types defined in methods). + * + * @return the array of top-level and member types defined in a compilation + * unit, in declaration order. + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource + */ + IType[] getAllTypes() throws JavaModelException; + + /** + * Returns the smallest element within this compilation unit that includes + * the given source position (that is, a method, field, etc.), or + * null if there is no element other than the compilation + * unit itself at the given position, or if the given position is not within + * the source range of this compilation unit. + * + * @param position + * a source position inside the compilation unit + * @return the innermost Java element enclosing a given source position or + * null if none (excluding the compilation unit). + * @exception JavaModelException + * if the compilation unit does not exist or if an exception + * occurs while accessing its corresponding resource + */ + IJavaElement getElementAt(int position) throws JavaModelException; + + /** + * Returns the first import declaration in this compilation unit with the + * given name. This is a handle-only method. The import declaration may or + * may not exist. This is a convenience method - imports can also be + * accessed from a compilation unit's import container. + * + * @param name + * the name of the import to find as defined by JLS2 7.5. (For + * example: "java.io.File" or + * "java.awt.*") + * @return a handle onto the corresponding import declaration. The import + * declaration may or may not exist. + */ + IImportDeclaration getImport(String name); + + /** + * Returns the import declarations in this compilation unit in the order in + * which they appear in the source. This is a convenience method - import + * declarations can also be accessed from a compilation unit's import + * container. + * + * @return the import declarations in this compilation unit + * @throws JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource + */ + IImportDeclaration[] getImports() throws JavaModelException; + + /** + * Returns the import container for this compilation unit. This is a + * handle-only method. The import container may or may not exist. The import + * container can used to access the imports. + * + * @return a handle onto the corresponding import container. The import + * contain may or may not exist. + */ + IImportContainer getImportContainer(); + + /** + * Returns the import declarations in this compilation unit in the order in + * which they appear in the source. This is a convenience method - import + * declarations can also be accessed from a compilation unit's import + * container. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource + */ + // IImportDeclaration[] getImports() throws JavaModelException; + /** + * Returns the first package declaration in this compilation unit with the + * given package name (there normally is at most one package declaration). + * This is a handle-only method. The package declaration may or may not + * exist. + * + * @param name + * the name of the package declaration as defined by JLS2 7.4. + * (For example, "java.lang") + */ + IPackageDeclaration getPackageDeclaration(String name); + + /** + * Returns the package declarations in this compilation unit in the order in + * which they appear in the source. There normally is at most one package + * declaration. + * + * @return an array of package declaration (normally of size one) + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource + */ + IPackageDeclaration[] getPackageDeclarations() throws JavaModelException; + + /** + * Returns the primary compilation unit (whose owner is the primary owner) + * this working copy was created from, or this compilation unit if this a + * primary compilation unit. + *

    + * Note that the returned primary compilation unit can be in working copy + * mode. + *

    + * + * @return the primary compilation unit this working copy was created from, + * or this compilation unit if it is primary + * @since 3.0 + */ + ICompilationUnit getPrimary(); + + /** + * Returns the top-level type declared in this compilation unit with the + * given simple type name. The type name has to be a valid compilation unit + * name. This is a handle-only method. The type may or may not exist. + * + * @param name + * the simple name of the requested type in the compilation unit + * @return a handle onto the corresponding type. The type may or may not + * exist. + * @see JavaConventions#validateCompilationUnitName(String name) + */ + IType getType(String name); + + /** + * Returns the top-level types declared in this compilation unit in the + * order in which they appear in the source. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource + */ + IType[] getTypes() throws JavaModelException; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICompletionRequestor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICompletionRequestor.java index acbb1c9..62602d6 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICompletionRequestor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICompletionRequestor.java @@ -13,393 +13,485 @@ package net.sourceforge.phpdt.core; import net.sourceforge.phpdt.core.compiler.IProblem; /** - * A completion requestor accepts results as they are computed and is aware - * of source positions to complete the various different results. + * A completion requestor accepts results as they are computed and is aware of + * source positions to complete the various different results. *

    * This interface may be implemented by clients. *

    - * + * * @see ICodeAssist * @since 2.0 */ public interface ICompletionRequestor { -/** - * Code assist notification of an anonymous type declaration completion. - * @param superTypePackageName Name of the package that contains the super type of this - * new anonymous type declaration . - * - * @param superTypeName Name of the super type of this new anonymous type declaration. - * - * @param parameterPackageNames Names of the packages in which the parameter types are declared. - * Should contain as many elements as parameterTypeNames. - * - * @param parameterTypeNames Names of the parameters types. - * Should contain as many elements as parameterPackageNames. - * - * @param completionName The completion for the anonymous type declaration. - * Can include zero, one or two brackets. If the closing bracket is included, - * then the cursor should be placed before it. - * - * @param modifiers The modifiers of the constructor. - * - * @param completionStart The start position of insertion of the name of this new anonymous type declaration. - * - * @param completionEnd The end position of insertion of the name of this new anonymous type declaration. - * - * @param relevance The relevance of the completion proposal - * It is a positive integer which are used for determine if this proposal is more relevant than another proposal. - * This value can only be used for compare relevance. A proposal is more relevant than another if his relevance - * value is higher. - * - * NOTE - All package and type names are presented in their readable form: - * Package names are in the form "a.b.c". - * Base types are in the form "int" or "boolean". - * Array types are in the qualified form "M[]" or "int[]". - * Nested type names are in the qualified form "A.M". - * The default package is represented by an empty array. - * - * NOTE: parameter names can be retrieved from the source model after the user selects a specific method. - */ -void acceptAnonymousType( - char[] superTypePackageName, - char[] superTypeName, - char[][] parameterPackageNames, - char[][] parameterTypeNames, - char[][] parameterNames, - char[] completionName, - int modifiers, - int completionStart, - int completionEnd, - int relevance); -/** - * Code assist notification of a class completion. - * - * @param packageName Declaring package name of the class. - * @param className Name of the class. - * @param completionName The completion for the class. Can include ';' for imported classes. - * @param modifiers The modifiers of the class. - * @param completionStart The start position of insertion of the name of the class. - * @param completionEnd The end position of insertion of the name of the class. - * @param relevance The relevance of the completion proposal - * It is a positive integer which are used for determine if this proposal is more relevant than another proposal. - * This value can only be used for compare relevance. A proposal is more relevant than another if his relevance - * value is higher. - * - * NOTE - All package and type names are presented in their readable form: - * Package names are in the form "a.b.c". - * Nested type names are in the qualified form "A.M". - * The default package is represented by an empty array. - */ -void acceptClass( - char[] packageName, - char[] className, - char[] completionName, - int modifiers, - int completionStart, - int completionEnd, - int relevance); -/** - * Code assist notification of a compilation error detected during completion. - * @param error Only problems which are categorized as non-syntax errors are notified to the - * requestor, warnings are silently ignored. - * In case an error got signalled, no other completions might be available, - * therefore the problem message should be presented to the user. - * The source positions of the problem are related to the source where it was - * detected (might be in another compilation unit, if it was indirectly requested - * during the code assist process). - * Note: the problem knows its originating file name. - */ -void acceptError(IProblem error); -/** - * Code assist notification of a field completion. - * - * @param declaringTypePackageName Name of the package in which the type that contains this field is declared. - * @param declaringTypeName Name of the type declaring this new field. - * @param name Name of the field. - * @param typePackageName Name of the package in which the type of this field is declared. - * @param typeName Name of the type of this field. - * @param completionName The completion for the field. - * @param modifiers The modifiers of this field. - * @param completionStart The start position of insertion of the name of this field. - * @param completionEnd The end position of insertion of the name of this field. - * @param relevance The relevance of the completion proposal - * It is a positive integer which are used for determine if this proposal is more relevant than another proposal. - * This value can only be used for compare relevance. A proposal is more relevant than another if his relevance - * value is higher. - * - * NOTE - All package and type names are presented in their readable form: - * Package names are in the form "a.b.c". - * Base types are in the form "int" or "boolean". - * Array types are in the qualified form "M[]" or "int[]". - * Nested type names are in the qualified form "A.M". - * The default package is represented by an empty array. - */ -void acceptField( - char[] declaringTypePackageName, - char[] declaringTypeName, - char[] name, - char[] typePackageName, - char[] typeName, - char[] completionName, - int modifiers, - int completionStart, - int completionEnd, - int relevance); -/** - * Code assist notification of an interface completion. - * - * @param packageName Declaring package name of the interface. - * @param className Name of the interface. - * @param completionName The completion for the interface. Can include ';' for imported interfaces. - * @param modifiers The modifiers of the interface. - * @param completionStart The start position of insertion of the name of the interface. - * @param completionEnd The end position of insertion of the name of the interface. - * @param relevance The relevance of the completion proposal - * It is a positive integer which are used for determine if this proposal is more relevant than another proposal. - * This value can only be used for compare relevance. A proposal is more relevant than another if his relevance - * value is higher. - * - * NOTE - All package and type names are presented in their readable form: - * Package names are in the form "a.b.c". - * Nested type names are in the qualified form "A.M". - * The default package is represented by an empty array. - */ -void acceptInterface( - char[] packageName, - char[] interfaceName, - char[] completionName, - int modifiers, - int completionStart, - int completionEnd, - int relevance); -/** - * Code assist notification of a keyword completion. - * @param keywordName The keyword source. - * @param completionStart The start position of insertion of the name of this keyword. - * @param completionEnd The end position of insertion of the name of this keyword. - * @param relevance The relevance of the completion proposal - * It is a positive integer which are used for determine if this proposal is more relevant than another proposal. - * This value can only be used for compare relevance. A proposal is more relevant than another if his relevance - * value is higher. - */ -void acceptKeyword(char[] keywordName, int completionStart, int completionEnd, int relevance); -/** - * Code assist notification of a label completion. - * - * @param labelName The label source. - * @param completionStart The start position of insertion of the name of this label. - * @param completionEnd The end position of insertion of the name of this label. - * @param relevance The relevance of the completion proposal - * It is a positive integer which are used for determine if this proposal is more relevant than another proposal. - * This value can only be used for compare relevance. A proposal is more relevant than another if his relevance - * value is higher. - */ -void acceptLabel(char[] labelName, int completionStart, int completionEnd, int relevance); -/** - * Code assist notification of a local variable completion. - * - * @param name Name of the new local variable. - * @param typePackageName Name of the package in which the type of this new local variable is declared. - * @param typeName Name of the type of this new local variable. - * @param modifiers The modifiers of this new local variable. - * @param completionStart The start position of insertion of the name of this new local variable. - * @param completionEnd The end position of insertion of the name of this new local variable. - * @param relevance The relevance of the completion proposal - * It is a positive integer which are used for determine if this proposal is more relevant than another proposal. - * This value can only be used for compare relevance. A proposal is more relevant than another if his relevance - * value is higher. - * - * NOTE - All package and type names are presented in their readable form: - * Package names are in the form "a.b.c". - * Base types are in the form "int" or "boolean". - * Array types are in the qualified form "M[]" or "int[]". - * Nested type names are in the qualified form "A.M". - * The default package is represented by an empty array. - */ -void acceptLocalVariable( - char[] name, - char[] typePackageName, - char[] typeName, - int modifiers, - int completionStart, - int completionEnd, - int relevance); -/** - * Code assist notification of a method completion. - * - * @param declaringTypePackageName Name of the package in which the type that contains this new method is declared. - * @param declaringTypeName Name of the type declaring this new method. - * @param selector Name of the new method. - * @param parameterPackageNames Names of the packages in which the parameter types are declared. - * Should contain as many elements as parameterTypeNames. - * @param parameterTypeNames Names of the parameters types. - * Should contain as many elements as parameterPackageNames. - * @param returnTypePackageName Name of the package in which the return type is declared. - * @param returnTypeName Name of the return type of this new method, should be null for a constructor. - * @param completionName The completion for the method. Can include zero, one or two brackets. If the closing bracket is included, then the cursor should be placed before it. - * @param modifiers The modifiers of this new method. - * @param completionStart The start position of insertion of the name of this new method. - * @param completionEnd The end position of insertion of the name of this new method. - * @param relevance The relevance of the completion proposal - * It is a positive integer which are used for determine if this proposal is more relevant than another proposal. - * This value can only be used for compare relevance. A proposal is more relevant than another if his relevance - * value is higher. - * - * NOTE - All package and type names are presented in their readable form: - * Package names are in the form "a.b.c". - * Base types are in the form "int" or "boolean". - * Array types are in the qualified form "M[]" or "int[]". - * Nested type names are in the qualified form "A.M". - * The default package is represented by an empty array. - * - * NOTE: parameter names can be retrieved from the source model after the user selects a specific method. - */ -void acceptMethod( - char[] declaringTypePackageName, - char[] declaringTypeName, - char[] selector, - char[][] parameterPackageNames, - char[][] parameterTypeNames, - char[][] parameterNames, - char[] returnTypePackageName, - char[] returnTypeName, - char[] completionName, - int modifiers, - int completionStart, - int completionEnd, - int relevance); + /** + * Code assist notification of an anonymous type declaration completion. + * + * @param superTypePackageName + * Name of the package that contains the super type of this new + * anonymous type declaration . + * + * @param superTypeName + * Name of the super type of this new anonymous type declaration. + * + * @param parameterPackageNames + * Names of the packages in which the parameter types are + * declared. Should contain as many elements as + * parameterTypeNames. + * + * @param parameterTypeNames + * Names of the parameters types. Should contain as many elements + * as parameterPackageNames. + * + * @param completionName + * The completion for the anonymous type declaration. Can include + * zero, one or two brackets. If the closing bracket is included, + * then the cursor should be placed before it. + * + * @param modifiers + * The modifiers of the constructor. + * + * @param completionStart + * The start position of insertion of the name of this new + * anonymous type declaration. + * + * @param completionEnd + * The end position of insertion of the name of this new + * anonymous type declaration. + * + * @param relevance + * The relevance of the completion proposal It is a positive + * integer which are used for determine if this proposal is more + * relevant than another proposal. This value can only be used + * for compare relevance. A proposal is more relevant than + * another if his relevance value is higher. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". Base types are in the form "int" + * or "boolean". Array types are in the qualified form "M[]" or "int[]". + * Nested type names are in the qualified form "A.M". The default package is + * represented by an empty array. + * + * NOTE: parameter names can be retrieved from the source model after the + * user selects a specific method. + */ + void acceptAnonymousType(char[] superTypePackageName, char[] superTypeName, + char[][] parameterPackageNames, char[][] parameterTypeNames, + char[][] parameterNames, char[] completionName, int modifiers, + int completionStart, int completionEnd, int relevance); -/** - * Code assist notification of a method completion. - * - * @param declaringTypePackageName Name of the package in which the type that contains this new method is declared. - * @param declaringTypeName Name of the type declaring this new method. - * @param selector Name of the new method. - * @param parameterPackageNames Names of the packages in which the parameter types are declared. - * Should contain as many elements as parameterTypeNames. - * @param parameterTypeNames Names of the parameters types. - * Should contain as many elements as parameterPackageNames. - * @param returnTypePackageName Name of the package in which the return type is declared. - * @param returnTypeName Name of the return type of this new method, should be null for a constructor. - * @param completionName The completion for the method. Can include zero, one or two brackets. If the closing bracket is included, then the cursor should be placed before it. - * @param modifiers The modifiers of this new method. - * @param completionStart The start position of insertion of the name of this new method. - * @param completionEnd The end position of insertion of the name of this new method. - * @param relevance The relevance of the completion proposal - * It is a positive integer which are used for determine if this proposal is more relevant than another proposal. - * This value can only be used for compare relevance. A proposal is more relevant than another if his relevance - * value is higher. - * - * NOTE - All package and type names are presented in their readable form: - * Package names are in the form "a.b.c". - * Base types are in the form "int" or "boolean". - * Array types are in the qualified form "M[]" or "int[]". - * Nested type names are in the qualified form "A.M". - * The default package is represented by an empty array. - * - * NOTE: parameter names can be retrieved from the source model after the user selects a specific method. - */ -void acceptMethodDeclaration( - char[] declaringTypePackageName, - char[] declaringTypeName, - char[] selector, - char[][] parameterPackageNames, - char[][] parameterTypeNames, - char[][] parameterNames, - char[] returnTypePackageName, - char[] returnTypeName, - char[] completionName, - int modifiers, - int completionStart, - int completionEnd, - int relevance); -/** - * Code assist notification of a modifier completion. - * - * @param modifierName The new modifier. - * @param completionStart The start position of insertion of the name of this new modifier. - * @param completionEnd The end position of insertion of the name of this new modifier. - * @param relevance The relevance of the completion proposal - * It is a positive integer which are used for determine if this proposal is more relevant than another proposal. - * This value can only be used for compare relevance. A proposal is more relevant than another if his relevance - * value is higher. - */ -void acceptModifier(char[] modifierName, int completionStart, int completionEnd, int relevance); -/** - * Code assist notification of a package completion. - * - * @param packageName The package name. - * @param completionName The completion for the package. Can include '.*;' for imports. - * @param completionStart The start position of insertion of the name of this new package. - * @param completionEnd The end position of insertion of the name of this new package. - * @param relevance The relevance of the completion proposal - * It is a positive integer which are used for determine if this proposal is more relevant than another proposal. - * This value can only be used for compare relevance. A proposal is more relevant than another if his relevance - * value is higher. - * - * NOTE - All package names are presented in their readable form: - * Package names are in the form "a.b.c". - * The default package is represented by an empty array. - */ -void acceptPackage( - char[] packageName, - char[] completionName, - int completionStart, - int completionEnd, - int relevance); -/** - * Code assist notification of a type completion. - * - * @param packageName Declaring package name of the type. - * @param typeName Name of the type. - * @param completionName The completion for the type. Can include ';' for imported types. - * @param completionStart The start position of insertion of the name of the type. - * @param completionEnd The end position of insertion of the name of the type. - * @param relevance The relevance of the completion proposal - * It is a positive integer which are used for determine if this proposal is more relevant than another proposal. - * This value can only be used for compare relevance. A proposal is more relevant than another if his relevance - * value is higher. - * - * NOTE - All package and type names are presented in their readable form: - * Package names are in the form "a.b.c". - * Nested type names are in the qualified form "A.M". - * The default package is represented by an empty array. - */ -void acceptType( - char[] packageName, - char[] typeName, - char[] completionName, - int completionStart, - int completionEnd, - int relevance); - -/** - * Code assist notification of a variable name completion. - * - * @param typePackageName Name of the package in which the type of this variable is declared. - * @param typeName Name of the type of this variable. - * @param name Name of the variable. - * @param completionName The completion for the variable. - * @param completionStart The start position of insertion of the name of this variable. - * @param completionEnd The end position of insertion of the name of this variable. - * @param relevance The relevance of the completion proposal - * It is a positive integer which are used for determine if this proposal is more relevant than another proposal. - * This value can only be used for compare relevance. A proposal is more relevant than another if his relevance - * value is higher. - * - * NOTE - All package and type names are presented in their readable form: - * Package names are in the form "a.b.c". - * Base types are in the form "int" or "boolean". - * Array types are in the qualified form "M[]" or "int[]". - * Nested type names are in the qualified form "A.M". - * The default package is represented by an empty array. - */ -void acceptVariableName( - char[] typePackageName, - char[] typeName, - char[] name, - char[] completionName, - int completionStart, - int completionEnd, - int relevance); + /** + * Code assist notification of a class completion. + * + * @param packageName + * Declaring package name of the class. + * @param className + * Name of the class. + * @param completionName + * The completion for the class. Can include ';' for imported + * classes. + * @param modifiers + * The modifiers of the class. + * @param completionStart + * The start position of insertion of the name of the class. + * @param completionEnd + * The end position of insertion of the name of the class. + * @param relevance + * The relevance of the completion proposal It is a positive + * integer which are used for determine if this proposal is more + * relevant than another proposal. This value can only be used + * for compare relevance. A proposal is more relevant than + * another if his relevance value is higher. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". Nested type names are in the + * qualified form "A.M". The default package is represented by an empty + * array. + */ + void acceptClass(char[] packageName, char[] className, + char[] completionName, int modifiers, int completionStart, + int completionEnd, int relevance); + + /** + * Code assist notification of a compilation error detected during + * completion. + * + * @param error + * Only problems which are categorized as non-syntax errors are + * notified to the requestor, warnings are silently ignored. In + * case an error got signalled, no other completions might be + * available, therefore the problem message should be presented + * to the user. The source positions of the problem are related + * to the source where it was detected (might be in another + * compilation unit, if it was indirectly requested during the + * code assist process). Note: the problem knows its originating + * file name. + */ + void acceptError(IProblem error); + + /** + * Code assist notification of a field completion. + * + * @param declaringTypePackageName + * Name of the package in which the type that contains this field + * is declared. + * @param declaringTypeName + * Name of the type declaring this new field. + * @param name + * Name of the field. + * @param typePackageName + * Name of the package in which the type of this field is + * declared. + * @param typeName + * Name of the type of this field. + * @param completionName + * The completion for the field. + * @param modifiers + * The modifiers of this field. + * @param completionStart + * The start position of insertion of the name of this field. + * @param completionEnd + * The end position of insertion of the name of this field. + * @param relevance + * The relevance of the completion proposal It is a positive + * integer which are used for determine if this proposal is more + * relevant than another proposal. This value can only be used + * for compare relevance. A proposal is more relevant than + * another if his relevance value is higher. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". Base types are in the form "int" + * or "boolean". Array types are in the qualified form "M[]" or "int[]". + * Nested type names are in the qualified form "A.M". The default package is + * represented by an empty array. + */ + void acceptField(char[] declaringTypePackageName, char[] declaringTypeName, + char[] name, char[] typePackageName, char[] typeName, + char[] completionName, int modifiers, int completionStart, + int completionEnd, int relevance); + + /** + * Code assist notification of an interface completion. + * + * @param packageName + * Declaring package name of the interface. + * @param className + * Name of the interface. + * @param completionName + * The completion for the interface. Can include ';' for imported + * interfaces. + * @param modifiers + * The modifiers of the interface. + * @param completionStart + * The start position of insertion of the name of the interface. + * @param completionEnd + * The end position of insertion of the name of the interface. + * @param relevance + * The relevance of the completion proposal It is a positive + * integer which are used for determine if this proposal is more + * relevant than another proposal. This value can only be used + * for compare relevance. A proposal is more relevant than + * another if his relevance value is higher. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". Nested type names are in the + * qualified form "A.M". The default package is represented by an empty + * array. + */ + void acceptInterface(char[] packageName, char[] interfaceName, + char[] completionName, int modifiers, int completionStart, + int completionEnd, int relevance); + + /** + * Code assist notification of a keyword completion. + * + * @param keywordName + * The keyword source. + * @param completionStart + * The start position of insertion of the name of this keyword. + * @param completionEnd + * The end position of insertion of the name of this keyword. + * @param relevance + * The relevance of the completion proposal It is a positive + * integer which are used for determine if this proposal is more + * relevant than another proposal. This value can only be used + * for compare relevance. A proposal is more relevant than + * another if his relevance value is higher. + */ + void acceptKeyword(char[] keywordName, int completionStart, + int completionEnd, int relevance); + + /** + * Code assist notification of a label completion. + * + * @param labelName + * The label source. + * @param completionStart + * The start position of insertion of the name of this label. + * @param completionEnd + * The end position of insertion of the name of this label. + * @param relevance + * The relevance of the completion proposal It is a positive + * integer which are used for determine if this proposal is more + * relevant than another proposal. This value can only be used + * for compare relevance. A proposal is more relevant than + * another if his relevance value is higher. + */ + void acceptLabel(char[] labelName, int completionStart, int completionEnd, + int relevance); + + /** + * Code assist notification of a local variable completion. + * + * @param name + * Name of the new local variable. + * @param typePackageName + * Name of the package in which the type of this new local + * variable is declared. + * @param typeName + * Name of the type of this new local variable. + * @param modifiers + * The modifiers of this new local variable. + * @param completionStart + * The start position of insertion of the name of this new local + * variable. + * @param completionEnd + * The end position of insertion of the name of this new local + * variable. + * @param relevance + * The relevance of the completion proposal It is a positive + * integer which are used for determine if this proposal is more + * relevant than another proposal. This value can only be used + * for compare relevance. A proposal is more relevant than + * another if his relevance value is higher. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". Base types are in the form "int" + * or "boolean". Array types are in the qualified form "M[]" or "int[]". + * Nested type names are in the qualified form "A.M". The default package is + * represented by an empty array. + */ + void acceptLocalVariable(char[] name, char[] typePackageName, + char[] typeName, int modifiers, int completionStart, + int completionEnd, int relevance); + + /** + * Code assist notification of a method completion. + * + * @param declaringTypePackageName + * Name of the package in which the type that contains this new + * method is declared. + * @param declaringTypeName + * Name of the type declaring this new method. + * @param selector + * Name of the new method. + * @param parameterPackageNames + * Names of the packages in which the parameter types are + * declared. Should contain as many elements as + * parameterTypeNames. + * @param parameterTypeNames + * Names of the parameters types. Should contain as many elements + * as parameterPackageNames. + * @param returnTypePackageName + * Name of the package in which the return type is declared. + * @param returnTypeName + * Name of the return type of this new method, should be + * null for a constructor. + * @param completionName + * The completion for the method. Can include zero, one or two + * brackets. If the closing bracket is included, then the cursor + * should be placed before it. + * @param modifiers + * The modifiers of this new method. + * @param completionStart + * The start position of insertion of the name of this new + * method. + * @param completionEnd + * The end position of insertion of the name of this new method. + * @param relevance + * The relevance of the completion proposal It is a positive + * integer which are used for determine if this proposal is more + * relevant than another proposal. This value can only be used + * for compare relevance. A proposal is more relevant than + * another if his relevance value is higher. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". Base types are in the form "int" + * or "boolean". Array types are in the qualified form "M[]" or "int[]". + * Nested type names are in the qualified form "A.M". The default package is + * represented by an empty array. + * + * NOTE: parameter names can be retrieved from the source model after the + * user selects a specific method. + */ + void acceptMethod(char[] declaringTypePackageName, + char[] declaringTypeName, char[] selector, + char[][] parameterPackageNames, char[][] parameterTypeNames, + char[][] parameterNames, char[] returnTypePackageName, + char[] returnTypeName, char[] completionName, int modifiers, + int completionStart, int completionEnd, int relevance); + + /** + * Code assist notification of a method completion. + * + * @param declaringTypePackageName + * Name of the package in which the type that contains this new + * method is declared. + * @param declaringTypeName + * Name of the type declaring this new method. + * @param selector + * Name of the new method. + * @param parameterPackageNames + * Names of the packages in which the parameter types are + * declared. Should contain as many elements as + * parameterTypeNames. + * @param parameterTypeNames + * Names of the parameters types. Should contain as many elements + * as parameterPackageNames. + * @param returnTypePackageName + * Name of the package in which the return type is declared. + * @param returnTypeName + * Name of the return type of this new method, should be + * null for a constructor. + * @param completionName + * The completion for the method. Can include zero, one or two + * brackets. If the closing bracket is included, then the cursor + * should be placed before it. + * @param modifiers + * The modifiers of this new method. + * @param completionStart + * The start position of insertion of the name of this new + * method. + * @param completionEnd + * The end position of insertion of the name of this new method. + * @param relevance + * The relevance of the completion proposal It is a positive + * integer which are used for determine if this proposal is more + * relevant than another proposal. This value can only be used + * for compare relevance. A proposal is more relevant than + * another if his relevance value is higher. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". Base types are in the form "int" + * or "boolean". Array types are in the qualified form "M[]" or "int[]". + * Nested type names are in the qualified form "A.M". The default package is + * represented by an empty array. + * + * NOTE: parameter names can be retrieved from the source model after the + * user selects a specific method. + */ + void acceptMethodDeclaration(char[] declaringTypePackageName, + char[] declaringTypeName, char[] selector, + char[][] parameterPackageNames, char[][] parameterTypeNames, + char[][] parameterNames, char[] returnTypePackageName, + char[] returnTypeName, char[] completionName, int modifiers, + int completionStart, int completionEnd, int relevance); + + /** + * Code assist notification of a modifier completion. + * + * @param modifierName + * The new modifier. + * @param completionStart + * The start position of insertion of the name of this new + * modifier. + * @param completionEnd + * The end position of insertion of the name of this new + * modifier. + * @param relevance + * The relevance of the completion proposal It is a positive + * integer which are used for determine if this proposal is more + * relevant than another proposal. This value can only be used + * for compare relevance. A proposal is more relevant than + * another if his relevance value is higher. + */ + void acceptModifier(char[] modifierName, int completionStart, + int completionEnd, int relevance); + + /** + * Code assist notification of a package completion. + * + * @param packageName + * The package name. + * @param completionName + * The completion for the package. Can include '.*;' for imports. + * @param completionStart + * The start position of insertion of the name of this new + * package. + * @param completionEnd + * The end position of insertion of the name of this new package. + * @param relevance + * The relevance of the completion proposal It is a positive + * integer which are used for determine if this proposal is more + * relevant than another proposal. This value can only be used + * for compare relevance. A proposal is more relevant than + * another if his relevance value is higher. + * + * NOTE - All package names are presented in their readable form: Package + * names are in the form "a.b.c". The default package is represented by an + * empty array. + */ + void acceptPackage(char[] packageName, char[] completionName, + int completionStart, int completionEnd, int relevance); + + /** + * Code assist notification of a type completion. + * + * @param packageName + * Declaring package name of the type. + * @param typeName + * Name of the type. + * @param completionName + * The completion for the type. Can include ';' for imported + * types. + * @param completionStart + * The start position of insertion of the name of the type. + * @param completionEnd + * The end position of insertion of the name of the type. + * @param relevance + * The relevance of the completion proposal It is a positive + * integer which are used for determine if this proposal is more + * relevant than another proposal. This value can only be used + * for compare relevance. A proposal is more relevant than + * another if his relevance value is higher. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". Nested type names are in the + * qualified form "A.M". The default package is represented by an empty + * array. + */ + void acceptType(char[] packageName, char[] typeName, char[] completionName, + int completionStart, int completionEnd, int relevance); + + /** + * Code assist notification of a variable name completion. + * + * @param typePackageName + * Name of the package in which the type of this variable is + * declared. + * @param typeName + * Name of the type of this variable. + * @param name + * Name of the variable. + * @param completionName + * The completion for the variable. + * @param completionStart + * The start position of insertion of the name of this variable. + * @param completionEnd + * The end position of insertion of the name of this variable. + * @param relevance + * The relevance of the completion proposal It is a positive + * integer which are used for determine if this proposal is more + * relevant than another proposal. This value can only be used + * for compare relevance. A proposal is more relevant than + * another if his relevance value is higher. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". Base types are in the form "int" + * or "boolean". Array types are in the qualified form "M[]" or "int[]". + * Nested type names are in the qualified form "A.M". The default package is + * represented by an empty array. + */ + void acceptVariableName(char[] typePackageName, char[] typeName, + char[] name, char[] completionName, int completionStart, + int completionEnd, int relevance); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IElementChangedListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IElementChangedListener.java index 19a3ab8..2778128 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IElementChangedListener.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IElementChangedListener.java @@ -18,12 +18,14 @@ package net.sourceforge.phpdt.core; *

    */ public interface IElementChangedListener { - -/** - * Notifies that one or more attributes of one or more Java elements have changed. - * The specific details of the change are described by the given event. - * - * @param event the change event - */ -public void elementChanged(ElementChangedEvent event); + + /** + * Notifies that one or more attributes of one or more Java elements have + * changed. The specific details of the change are described by the given + * event. + * + * @param event + * the change event + */ + public void elementChanged(ElementChangedEvent event); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IField.java index 10aba92..ebfaf25 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IField.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IField.java @@ -17,31 +17,36 @@ package net.sourceforge.phpdt.core; *

    */ public interface IField extends IMember { -/** - * Returns the constant value associated with this field - * or null if this field has none. - * Returns either a subclass of Number, or a String, - * depending on the type of the field. - * For example, if the field is of type short, this returns - * a Short. - * - * @return the constant value associated with this field or null if this field has none. - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource - */ -public Object getConstant() throws JavaModelException; -/** - * Returns the simple name of this field. - * @return the simple name of this field. - */ -String getElementName(); -/** - * Returns the type signature of this field. - * - * @see Signature - * @return the type signature of this field. - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource - */ -String getTypeSignature() throws JavaModelException; + /** + * Returns the constant value associated with this field or + * null if this field has none. Returns either a subclass of + * Number, or a String, depending on the + * type of the field. For example, if the field is of type + * short, this returns a Short. + * + * @return the constant value associated with this field or + * null if this field has none. + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource + */ + public Object getConstant() throws JavaModelException; + + /** + * Returns the simple name of this field. + * + * @return the simple name of this field. + */ + String getElementName(); + + /** + * Returns the type signature of this field. + * + * @see Signature + * @return the type signature of this field. + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource + */ + String getTypeSignature() throws JavaModelException; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IImportContainer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IImportContainer.java index f7e3095..956af01 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IImportContainer.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IImportContainer.java @@ -11,21 +11,25 @@ package net.sourceforge.phpdt.core; /** - * Represents an import container is a child of a Java compilation unit that contains - * all (and only) the import declarations. If a compilation unit has no import - * declarations, no import container will be present. + * Represents an import container is a child of a Java compilation unit that + * contains all (and only) the import declarations. If a compilation unit has no + * import declarations, no import container will be present. *

    * This interface is not intended to be implemented by clients. *

    */ -public interface IImportContainer extends IJavaElement, IParent, ISourceReference { -/** - * Returns the first import declaration in this import container with the given name. - * This is a handle-only method. The import declaration may or may not exist. - * - * @param name the given name - * - * @return the first import declaration in this import container with the given name - */ -IImportDeclaration getImport(String name); +public interface IImportContainer extends IJavaElement, IParent, + ISourceReference { + /** + * Returns the first import declaration in this import container with the + * given name. This is a handle-only method. The import declaration may or + * may not exist. + * + * @param name + * the given name + * + * @return the first import declaration in this import container with the + * given name + */ + IImportDeclaration getImport(String name); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IImportDeclaration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IImportDeclaration.java index 812bc64..90e8150 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IImportDeclaration.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IImportDeclaration.java @@ -11,42 +11,46 @@ *******************************************************************************/ package net.sourceforge.phpdt.core; - /** * Represents an import declaration in Java compilation unit. *

    * This interface is not intended to be implemented by clients. *

    */ -public interface IImportDeclaration extends IJavaElement, ISourceReference, ISourceManipulation { -/** - * Returns the name that has been imported. - * For an on-demand import, this includes the trailing ".*". - * For example, for the statement "import java.util.*", - * this returns "java.util.*". - * For the statement "import java.util.Hashtable", - * this returns "java.util.Hashtable". - * - * @return the name that has been imported - */ -String getElementName(); -/** - * Returns the modifier flags for this import. The flags can be examined using class - * Flags. Only the static flag is meaningful for import declarations. - * - * @return the modifier flags for this import - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. - * @see Flags - * @since 3.0 - */ -int getFlags() throws JavaModelException; +public interface IImportDeclaration extends IJavaElement, ISourceReference, + ISourceManipulation { + /** + * Returns the name that has been imported. For an on-demand import, this + * includes the trailing ".*". For example, for the + * statement "import java.util.*", this returns + * "java.util.*". For the statement + * "import java.util.Hashtable", this returns + * "java.util.Hashtable". + * + * @return the name that has been imported + */ + String getElementName(); -/** - * Returns whether the import is on-demand. An import is on-demand if it ends - * with ".*". - * @return true if the import is on-demand, false otherwise - */ -boolean isOnDemand(); + /** + * Returns the modifier flags for this import. The flags can be examined + * using class Flags. Only the static flag is meaningful for + * import declarations. + * + * @return the modifier flags for this import + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. + * @see Flags + * @since 3.0 + */ + int getFlags() throws JavaModelException; + + /** + * Returns whether the import is on-demand. An import is on-demand if it + * ends with ".*". + * + * @return true if the import is on-demand, false otherwise + */ + boolean isOnDemand(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaElement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaElement.java index cea7b63..679a580 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaElement.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaElement.java @@ -16,14 +16,15 @@ import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.jobs.ISchedulingRule; /** - * Common protocol for all elements provided by the Java model. - * Java model elements are exposed to clients as handles to the actual underlying element. + * Common protocol for all elements provided by the Java model. Java model + * elements are exposed to clients as handles to the actual underlying element. * The Java model may hand out any number of handles for each element. Handles - * that refer to the same element are guaranteed to be equal, but not necessarily identical. + * that refer to the same element are guaranteed to be equal, but not + * necessarily identical. *

    - * Methods annotated as "handle-only" do not require underlying elements to exist. - * Methods that require underlying elements to exist throw - * a JavaModelException when an underlying element is missing. + * Methods annotated as "handle-only" do not require underlying elements to + * exist. Methods that require underlying elements to exist throw a + * JavaModelException when an underlying element is missing. * JavaModelException.isDoesNotExist can be used to recognize * this common special case. *

    @@ -34,89 +35,94 @@ import org.eclipse.core.runtime.jobs.ISchedulingRule; public interface IJavaElement extends IAdaptable { /** - * Constant representing a Java model (workspace level object). - * A Java element with this type can be safely cast to IJavaModel. + * Constant representing a Java model (workspace level object). A Java + * element with this type can be safely cast to IJavaModel. */ int JAVA_MODEL = 1; /** - * Constant representing a Java project. - * A Java element with this type can be safely cast to IJavaProject. + * Constant representing a Java project. A Java element with this type can + * be safely cast to IJavaProject. */ int JAVA_PROJECT = 2; /** - * Constant representing a package fragment root. - * A Java element with this type can be safely cast to IPackageFragmentRoot. + * Constant representing a package fragment root. A Java element with this + * type can be safely cast to IPackageFragmentRoot. */ int PACKAGE_FRAGMENT_ROOT = 3; /** - * Constant representing a package fragment. - * A Java element with this type can be safely cast to IPackageFragment. + * Constant representing a package fragment. A Java element with this type + * can be safely cast to IPackageFragment. */ int PACKAGE_FRAGMENT = 4; /** - * Constant representing a Java compilation unit. - * A Java element with this type can be safely cast to ICompilationUnit. + * Constant representing a Java compilation unit. A Java element with this + * type can be safely cast to ICompilationUnit. */ int COMPILATION_UNIT = 5; /** - * Constant representing a class file. - * A Java element with this type can be safely cast to IClassFile. + * Constant representing a class file. A Java element with this type can be + * safely cast to IClassFile. */ int CLASS_FILE = 6; /** - * Constant representing a type (a class or interface). - * A Java element with this type can be safely cast to IType. + * Constant representing a type (a class or interface). A Java element with + * this type can be safely cast to IType. */ int TYPE = 7; /** - * Constant representing a field. - * A Java element with this type can be safely cast to IField. + * Constant representing a field. A Java element with this type can be + * safely cast to IField. */ int FIELD = 8; /** - * Constant representing a method or constructor. - * A Java element with this type can be safely cast to IMethod. + * Constant representing a method or constructor. A Java element with this + * type can be safely cast to IMethod. */ int METHOD = 9; /** - * Constant representing a stand-alone instance or class initializer. - * A Java element with this type can be safely cast to IInitializer. + * Constant representing a stand-alone instance or class initializer. A Java + * element with this type can be safely cast to IInitializer. */ int INITIALIZER = 10; /** - * Constant representing a package declaration within a compilation unit. - * A Java element with this type can be safely cast to IPackageDeclaration. + * Constant representing a package declaration within a compilation unit. A + * Java element with this type can be safely cast to + * IPackageDeclaration. */ int PACKAGE_DECLARATION = 11; /** * Constant representing all import declarations within a compilation unit. - * A Java element with this type can be safely cast to IImportContainer. + * A Java element with this type can be safely cast to + * IImportContainer. */ int IMPORT_CONTAINER = 12; /** - * Constant representing an import declaration within a compilation unit. - * A Java element with this type can be safely cast to IImportDeclaration. + * Constant representing an import declaration within a compilation unit. A + * Java element with this type can be safely cast to + * IImportDeclaration. */ int IMPORT_DECLARATION = 13; /** - * Constant representing a local variable declaration. - * A Java element with this type can be safely cast to ILocalVariable. + * Constant representing a local variable declaration. A Java element with + * this type can be safely cast to ILocalVariable. + * * @since 3.0 */ int LOCAL_VARIABLE = 14; + /** * Returns whether this Java element exists in the model. *

    @@ -125,205 +131,211 @@ public interface IJavaElement extends IAdaptable { * said to "exist", and this method returns true. For Java * elements that are not working copies, it is always the case that if the * element exists, then its parent also exists (provided it has one) and - * includes the element as one of its children. It is therefore possible - * to navigated to any existing Java element from the root of the Java model + * includes the element as one of its children. It is therefore possible to + * navigated to any existing Java element from the root of the Java model * along a chain of existing Java elements. On the other hand, working * copies are said to exist until they are destroyed (with * IWorkingCopy.destroy). Unlike regular Java elements, a * working copy never shows up among the children of its parent element * (which may or may not exist). *

    - * + * * @return true if this element exists in the Java model, and - * false if this element does not exist + * false if this element does not exist */ boolean exists(); - + /** * Returns the first ancestor of this Java element that has the given type. - * Returns null if no such an ancestor can be found. - * This is a handle-only method. + * Returns null if no such an ancestor can be found. This is + * a handle-only method. * - * @param ancestorType the given type - * @return the first ancestor of this Java element that has the given type, null if no such an ancestor can be found + * @param ancestorType + * the given type + * @return the first ancestor of this Java element that has the given type, + * null if no such an ancestor can be found * @since 2.0 */ IJavaElement getAncestor(int ancestorType); /** - * Returns the resource that corresponds directly to this element, - * or null if there is no resource that corresponds to - * this element. + * Returns the resource that corresponds directly to this element, or + * null if there is no resource that corresponds to this + * element. *

    - * For example, the corresponding resource for an ICompilationUnit - * is its underlying IFile. The corresponding resource for - * an IPackageFragment that is not contained in an archive - * is its underlying IFolder. An IPackageFragment - * contained in an archive has no corresponding resource. Similarly, there - * are no corresponding resources for IMethods, - * IFields, etc. + * For example, the corresponding resource for an + * ICompilationUnit is its underlying IFile. + * The corresponding resource for an IPackageFragment that is + * not contained in an archive is its underlying IFolder. An + * IPackageFragment contained in an archive has no + * corresponding resource. Similarly, there are no corresponding resources + * for IMethods, IFields, etc. *

    - * + * * @return the corresponding resource, or null if none - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource */ IResource getCorrespondingResource() throws JavaModelException; /** * Returns the name of this element. This is a handle-only method. - * + * * @return the element name */ String getElementName(); /** - * Returns this element's kind encoded as an integer. - * This is a handle-only method. - * + * Returns this element's kind encoded as an integer. This is a handle-only + * method. + * * @return the kind of element; one of the constants declared in - * IJavaElement + * IJavaElement * @see IJavaElement */ int getElementType(); /** - * Returns a string representation of this element handle. The format of - * the string is not specified; however, the identifier is stable across - * workspace sessions, and can be used to recreate this handle via the + * Returns a string representation of this element handle. The format of the + * string is not specified; however, the identifier is stable across + * workspace sessions, and can be used to recreate this handle via the * JavaCore.create(String) method. - * + * * @return the string handle identifier * @see JavaCore#create(java.lang.String) */ String getHandleIdentifier(); /** - * Returns the Java model. - * This is a handle-only method. - * + * Returns the Java model. This is a handle-only method. + * * @return the Java model */ - IJavaModel getJavaModel(); + IJavaModel getJavaModel(); /** - * Returns the Java project this element is contained in, - * or null if this element is not contained in any Java project - * (for instance, the IJavaModel is not contained in any Java - * project). - * This is a handle-only method. - * - * @return the containing Java project, or null if this element is - * not contained in a Java project + * Returns the Java project this element is contained in, or + * null if this element is not contained in any Java project + * (for instance, the IJavaModel is not contained in any Java + * project). This is a handle-only method. + * + * @return the containing Java project, or null if this + * element is not contained in a Java project */ IJavaProject getJavaProject(); /** - * Returns the first openable parent. If this element is openable, the element - * itself is returned. Returns null if this element doesn't have - * an openable parent. - * This is a handle-only method. + * Returns the first openable parent. If this element is openable, the + * element itself is returned. Returns null if this element + * doesn't have an openable parent. This is a handle-only method. * - * @return the first openable parent or null if this element doesn't have - * an openable parent. + * @return the first openable parent or null if this element + * doesn't have an openable parent. * @since 2.0 */ IOpenable getOpenable(); /** - * Returns the element directly containing this element, - * or null if this element has no parent. - * This is a handle-only method. - * - * @return the parent element, or null if this element has no parent + * Returns the element directly containing this element, or + * null if this element has no parent. This is a handle-only + * method. + * + * @return the parent element, or null if this element has no + * parent */ IJavaElement getParent(); /** - * Returns the path to the innermost resource enclosing this element. - * If this element is not included in an external archive, - * the path returned is the full, absolute path to the underlying resource, - * relative to the workbench. - * If this element is included in an external archive, - * the path returned is the absolute path to the archive in the file system. - * This is a handle-only method. + * Returns the path to the innermost resource enclosing this element. If + * this element is not included in an external archive, the path returned is + * the full, absolute path to the underlying resource, relative to the + * workbench. If this element is included in an external archive, the path + * returned is the absolute path to the archive in the file system. This is + * a handle-only method. * * @return the path to the innermost resource enclosing this element * @since 2.0 */ IPath getPath(); + /** - * Returns the primary element (whose compilation unit is the primary compilation unit) - * this working copy element was created from, or this element if it is a descendant of a - * primary compilation unit or if it is not a descendant of a working copy (e.g. it is a - * binary member). - * The returned element may or may not exist. + * Returns the primary element (whose compilation unit is the primary + * compilation unit) this working copy element was created from, or this + * element if it is a descendant of a primary compilation unit or if it is + * not a descendant of a working copy (e.g. it is a binary member). The + * returned element may or may not exist. * - * @return the primary element this working copy element was created from, or this - * element. + * @return the primary element this working copy element was created from, + * or this element. * @since 3.0 */ IJavaElement getPrimaryElement(); + /** - * Returns the innermost resource enclosing this element. - * If this element is included in an archive and this archive is not external, - * this is the underlying resource corresponding to the archive. - * If this element is included in an external archive, null - * is returned. - * If this element is a working copy, null is returned. - * This is a handle-only method. + * Returns the innermost resource enclosing this element. If this element is + * included in an archive and this archive is not external, this is the + * underlying resource corresponding to the archive. If this element is + * included in an external archive, null is returned. If this + * element is a working copy, null is returned. This is a + * handle-only method. * - * @return the innermost resource enclosing this element, null if this - * element is a working copy or is included in an external archive + * @return the innermost resource enclosing this element, null + * if this element is a working copy or is included in an external + * archive * @since 2.0 */ IResource getResource(); + /** - * Returns the scheduling rule associated with this Java element. - * This is a handle-only method. + * Returns the scheduling rule associated with this Java element. This is a + * handle-only method. * * @return the scheduling rule associated with this Java element * @since 3.0 */ ISchedulingRule getSchedulingRule(); + /** - * Returns the smallest underlying resource that contains - * this element, or null if this element is not contained - * in a resource. - * + * Returns the smallest underlying resource that contains this element, or + * null if this element is not contained in a resource. + * * @return the underlying resource, or null if none - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its underlying resource + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its underlying resource */ IResource getUnderlyingResource() throws JavaModelException; /** * Returns whether this Java element is read-only. An element is read-only - * if its structure cannot be modified by the java model. + * if its structure cannot be modified by the java model. *

    * Note this is different from IResource.isReadOnly(). For example, .jar - * files are read-only as the java model doesn't know how to add/remove + * files are read-only as the java model doesn't know how to add/remove * elements in this file, but the underlying IFile can be writable. *

    * This is a handle-only method. - * + * * @return true if this element is read-only */ boolean isReadOnly(); /** - * Returns whether the structure of this element is known. For example, for a - * compilation unit that could not be parsed, false is returned. - * If the structure of an element is unknown, navigations will return reasonable - * defaults. For example, getChildren will return an empty collection. + * Returns whether the structure of this element is known. For example, for + * a compilation unit that could not be parsed, false is + * returned. If the structure of an element is unknown, navigations will + * return reasonable defaults. For example, getChildren will + * return an empty collection. *

    - * Note: This does not imply anything about consistency with the - * underlying resource/buffer contents. + * Note: This does not imply anything about consistency with the underlying + * resource/buffer contents. *

    - * + * * @return true if the structure of this element is known - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource */ boolean isStructureKnown() throws JavaModelException; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaElementDelta.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaElementDelta.java index 61f2ce9..c506cd8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaElementDelta.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaElementDelta.java @@ -14,89 +14,107 @@ import org.eclipse.core.resources.IResourceDelta; /** * A Java element delta describes changes in Java element between two discrete - * points in time. Given a delta, clients can access the element that has + * points in time. Given a delta, clients can access the element that has * changed, and any children that have changed. *

    - * Deltas have a different status depending on the kind of change they represent. - * The list below summarizes each status (as returned by getKind) - * and its meaning (see individual constants for a more detailled description): + * Deltas have a different status depending on the kind of change they + * represent. The list below summarizes each status (as returned by + * getKind) and its meaning (see individual constants for a more + * detailled description): *

      - *
    • ADDED - The element described by the delta has been added.
    • - *
    • REMOVED - The element described by the delta has been removed.
    • - *
    • CHANGED - The element described by the delta has been changed in some way. - * Specification of the type of change is provided by getFlags which returns the following values: + *
    • ADDED - The element described by the delta has been + * added.
    • + *
    • REMOVED - The element described by the delta has been + * removed.
    • + *
    • CHANGED - The element described by the delta has been + * changed in some way. Specification of the type of change is provided by + * getFlags which returns the following values: *
        - *
      • F_ADDED_TO_CLASSPATH - A classpath entry corresponding to the element - * has been added to the project's classpath. This flag is only valid if the element is an - * IPackageFragmentRoot.
      • + *
      • F_ADDED_TO_CLASSPATH - A classpath entry corresponding to + * the element has been added to the project's classpath. This flag is only + * valid if the element is an IPackageFragmentRoot.
      • *
      • F_ARCHIVE_CONTENT_CHANGED - The contents of an archive - * has changed in some way. This flag is only valid if the element is an IPackageFragmentRoot - * which is an archive.
      • - *
      • F_CHILDREN - A child of the element has changed in some way. This flag - * is only valid if the element is an IParent.
      • - *
      • F_CLASSPATH_REORDER - A classpath entry corresponding to the element - * has changed position in the project's classpath. This flag is only valid if the element is an - * IPackageFragmentRoot.
      • - *
      • F_CLOSED - The underlying IProject - * has been closed. This flag is only valid if the element is an IJavaProject.
      • - *
      • F_CONTENT - The contents of the element have been altered. This flag - * is only valid for elements which correspond to files.
      • - *
      • F_FINE_GRAINED - The delta is a fine-grained delta, that is, an analysis down - * to the members level was done to determine if there were structural changes to members of the element.
      • - *
      • F_MODIFIERS - The modifiers on the element have changed in some way. - * This flag is only valid if the element is an IMember.
      • - *
      • F_OPENED - The underlying IProject - * has been opened. This flag is only valid if the element is an IJavaProject.
      • - *
      • F_REMOVED_FROM_CLASSPATH - A classpath entry corresponding to the element - * has been removed from the project's classpath. This flag is only valid if the element is an + * has changed in some way. This flag is only valid if the element is an + * IPackageFragmentRoot which is an archive.
      • + *
      • F_CHILDREN - A child of the element has changed in some + * way. This flag is only valid if the element is an IParent.
      • + *
      • F_CLASSPATH_REORDER - A classpath entry corresponding to + * the element has changed position in the project's classpath. This flag is + * only valid if the element is an IPackageFragmentRoot.
      • + *
      • F_CLOSED - The underlying IProject has + * been closed. This flag is only valid if the element is an + * IJavaProject.
      • + *
      • F_CONTENT - The contents of the element have been + * altered. This flag is only valid for elements which correspond to files.
      • + *
      • F_FINE_GRAINED - The delta is a fine-grained delta, that + * is, an analysis down to the members level was done to determine if there were + * structural changes to members of the element.
      • + *
      • F_MODIFIERS - The modifiers on the element have changed + * in some way. This flag is only valid if the element is an + * IMember.
      • + *
      • F_OPENED - The underlying IProject has + * been opened. This flag is only valid if the element is an + * IJavaProject.
      • + *
      • F_REMOVED_FROM_CLASSPATH - A classpath entry + * corresponding to the element has been removed from the project's classpath. + * This flag is only valid if the element is an * IPackageFragmentRoot.
      • - *
      • F_SOURCEATTACHED - The source attachment path or the source attachment root path - * of a classpath entry corresponding to the element was added. This flag is only valid if the element is an + *
      • F_SOURCEATTACHED - The source attachment path or the + * source attachment root path of a classpath entry corresponding to the element + * was added. This flag is only valid if the element is an * IPackageFragmentRoot.
      • - *
      • F_SOURCEDETACHED - The source attachment path or the source attachment root path - * of a classpath entry corresponding to the element was removed. This flag is only valid if the element is an + *
      • F_SOURCEDETACHED - The source attachment path or the + * source attachment root path of a classpath entry corresponding to the element + * was removed. This flag is only valid if the element is an * IPackageFragmentRoot.
      • - *
      • F_SUPER_TYPES - One of the supertypes of an IType has changed
      • . + *
      • F_SUPER_TYPES - One of the supertypes of an + * IType has changed
      • . *
      *
    • *
    *

    *

    - * Move operations are indicated by other change flags, layered on top - * of the change flags described above. If element A is moved to become B, - * the delta for the change in A will have status REMOVED, - * with change flag F_MOVED_TO. In this case, - * getMovedToElement on delta A will return the handle for B. - * The delta for B will have status ADDED, with change flag - * F_MOVED_FROM, and getMovedFromElement on delta - * B will return the handle for A. (Note, the handle to A in this case represents - * an element that no longer exists). + * Move operations are indicated by other change flags, layered on top of the + * change flags described above. If element A is moved to become B, the delta + * for the change in A will have status REMOVED, with change + * flag F_MOVED_TO. In this case, getMovedToElement + * on delta A will return the handle for B. The delta for B will have status + * ADDED, with change flag F_MOVED_FROM, and + * getMovedFromElement on delta B will return the handle for A. + * (Note, the handle to A in this case represents an element that no longer + * exists). *

    *

    - * Note that the move change flags only describe the changes to a single element, they - * do not imply anything about the parent or children of the element. + * Note that the move change flags only describe the changes to a single + * element, they do not imply anything about the parent or children of the + * element. *

    *

    - * The F_ADDED_TO_CLASSPATH, F_REMOVED_FROM_CLASSPATH and - * F_CLASSPATH_REORDER flags are triggered by changes to a project's classpath. They do not mean that - * the underlying resource was added, removed or changed. For example, if a project P already contains a folder src, then - * adding a classpath entry with the 'P/src' path to the project's classpath will result in an IJavaElementDelta - * with the F_ADDED_TO_CLASSPATH flag for the IPackageFragmentRoot P/src. - * On the contrary, if a resource is physically added, removed or changed and this resource corresponds to a classpath - * entry of the project, then an IJavaElementDelta with the ADDED, + * The F_ADDED_TO_CLASSPATH, + * F_REMOVED_FROM_CLASSPATH and F_CLASSPATH_REORDER + * flags are triggered by changes to a project's classpath. They do not mean + * that the underlying resource was added, removed or changed. For example, if a + * project P already contains a folder src, then adding a classpath entry with + * the 'P/src' path to the project's classpath will result in an + * IJavaElementDelta with the F_ADDED_TO_CLASSPATH + * flag for the IPackageFragmentRoot P/src. On the contrary, if a + * resource is physically added, removed or changed and this resource + * corresponds to a classpath entry of the project, then an + * IJavaElementDelta with the ADDED, * REMOVED, or CHANGED kind will be fired. *

    *

    - * Note that when a source attachment path or a source attachment root path is changed, then the flags of the delta contain - * both F_SOURCEATTACHED and F_SOURCEDETTACHED. + * Note that when a source attachment path or a source attachment root path is + * changed, then the flags of the delta contain both + * F_SOURCEATTACHED and F_SOURCEDETTACHED. *

    *

    - * No assumptions should be made on whether the java element delta tree is rooted at the IJavaModel - * level or not. + * No assumptions should be made on whether the java element delta tree is + * rooted at the IJavaModel level or not. *

    *

    - * IJavaElementDelta object are not valid outside the dynamic scope - * of the notification. + * IJavaElementDelta object are not valid outside the dynamic + * scope of the notification. *

    *

    * This interface is not intended to be implemented by clients. @@ -105,226 +123,251 @@ import org.eclipse.core.resources.IResourceDelta; public interface IJavaElementDelta { /** - * Status constant indicating that the element has been added. - * Note that an added java element delta has no children, as they are all implicitely added. + * Status constant indicating that the element has been added. Note that an + * added java element delta has no children, as they are all implicitely + * added. */ public int ADDED = 1; /** - * Status constant indicating that the element has been removed. - * Note that a removed java element delta has no children, as they are all implicitely removed. + * Status constant indicating that the element has been removed. Note that a + * removed java element delta has no children, as they are all implicitely + * removed. */ public int REMOVED = 2; /** - * Status constant indicating that the element has been changed, - * as described by the change flags. + * Status constant indicating that the element has been changed, as + * described by the change flags. * * @see #getFlags */ public int CHANGED = 4; /** - * Change flag indicating that the content of the element has changed. - * This flag is only valid for elements which correspond to files. + * Change flag indicating that the content of the element has changed. This + * flag is only valid for elements which correspond to files. */ public int F_CONTENT = 0x0001; /** * Change flag indicating that the modifiers of the element have changed. - * This flag is only valid if the element is an IMember. + * This flag is only valid if the element is an IMember. */ public int F_MODIFIERS = 0x0002; /** - * Change flag indicating that there are changes to the children of the element. - * This flag is only valid if the element is an IParent. + * Change flag indicating that there are changes to the children of the + * element. This flag is only valid if the element is an + * IParent. */ public int F_CHILDREN = 0x0008; /** * Change flag indicating that the element was moved from another location. - * The location of the old element can be retrieved using getMovedFromElement. + * The location of the old element can be retrieved using + * getMovedFromElement. */ public int F_MOVED_FROM = 0x0010; /** * Change flag indicating that the element was moved to another location. - * The location of the new element can be retrieved using getMovedToElement. + * The location of the new element can be retrieved using + * getMovedToElement. */ public int F_MOVED_TO = 0x0020; /** - * Change flag indicating that a classpath entry corresponding to the element has been added to the project's classpath. - * This flag is only valid if the element is an IPackageFragmentRoot. + * Change flag indicating that a classpath entry corresponding to the + * element has been added to the project's classpath. This flag is only + * valid if the element is an IPackageFragmentRoot. */ public int F_ADDED_TO_CLASSPATH = 0x0040; /** - * Change flag indicating that a classpath entry corresponding to the element has been removed from the project's - * classpath. This flag is only valid if the element is an IPackageFragmentRoot. + * Change flag indicating that a classpath entry corresponding to the + * element has been removed from the project's classpath. This flag is only + * valid if the element is an IPackageFragmentRoot. */ public int F_REMOVED_FROM_CLASSPATH = 0x0080; /** - * Change flag indicating that a classpath entry corresponding to the element has changed position in the project's - * classpath. This flag is only valid if the element is an IPackageFragmentRoot. + * Change flag indicating that a classpath entry corresponding to the + * element has changed position in the project's classpath. This flag is + * only valid if the element is an IPackageFragmentRoot. + * * @deprecated Use F_REORDER instead. */ public int F_CLASSPATH_REORDER = 0x0100; + /** - * Change flag indicating that the element has changed position relatively to its siblings. - * If the element is an IPackageFragmentRoot, a classpath entry corresponding - * to the element has changed position in the project's classpath. + * Change flag indicating that the element has changed position relatively + * to its siblings. If the element is an IPackageFragmentRoot, + * a classpath entry corresponding to the element has changed position in + * the project's classpath. * * @since 2.1 */ public int F_REORDER = 0x0100; /** - * Change flag indicating that the underlying IProject has been - * opened. This flag is only valid if the element is an IJavaProject. + * Change flag indicating that the underlying IProject has + * been opened. This flag is only valid if the element is an + * IJavaProject. */ public int F_OPENED = 0x0200; /** - * Change flag indicating that the underlying IProject has been - * closed. This flag is only valid if the element is an IJavaProject. + * Change flag indicating that the underlying IProject has + * been closed. This flag is only valid if the element is an + * IJavaProject. */ public int F_CLOSED = 0x0400; /** - * Change flag indicating that one of the supertypes of an IType - * has changed. + * Change flag indicating that one of the supertypes of an + * IType has changed. */ public int F_SUPER_TYPES = 0x0800; /** - * Change flag indicating that the source attachment path or the source attachment root path of a classpath entry - * corresponding to the element was added. This flag is only valid if the element is an + * Change flag indicating that the source attachment path or the source + * attachment root path of a classpath entry corresponding to the element + * was added. This flag is only valid if the element is an * IPackageFragmentRoot. */ - public int F_SOURCEATTACHED = 0x1000; + public int F_SOURCEATTACHED = 0x1000; /** - * Change flag indicating that the source attachment path or the source attachment root path of a classpath entry - * corresponding to the element was removed. This flag is only valid if the element is an + * Change flag indicating that the source attachment path or the source + * attachment root path of a classpath entry corresponding to the element + * was removed. This flag is only valid if the element is an * IPackageFragmentRoot. */ - public int F_SOURCEDETACHED = 0x2000; - + public int F_SOURCEDETACHED = 0x2000; + /** - * Change flag indicating that this is a fine-grained delta, that is, an analysis down - * to the members level was done to determine if there were structural changes to - * members. + * Change flag indicating that this is a fine-grained delta, that is, an + * analysis down to the members level was done to determine if there were + * structural changes to members. *

    - * Clients can use this flag to find out if a compilation unit - * that have a F_CONTENT change should assume that there are - * no finer grained changes (F_FINE_GRAINED is set) or if - * finer grained changes were not considered (F_FINE_GRAINED - * is not set). - * - * @since 2.0 + * Clients can use this flag to find out if a compilation unit that have a + * F_CONTENT change should assume that there are no finer + * grained changes (F_FINE_GRAINED is set) or if finer + * grained changes were not considered (F_FINE_GRAINED is + * not set). + * + * @since 2.0 */ public int F_FINE_GRAINED = 0x4000; /** - * Change flag indicating that the element's archive content on the classpath has changed. - * This flag is only valid if the element is an IPackageFragmentRoot - * which is an archive. + * Change flag indicating that the element's archive content on the + * classpath has changed. This flag is only valid if the element is an + * IPackageFragmentRoot which is an archive. * * @see IPackageFragmentRoot#isArchive * @since 2.0 */ public int F_ARCHIVE_CONTENT_CHANGED = 0x8000; + /** - * Change flag indicating that a compilation unit has become a primary working copy, or that a - * primary working copy has reverted to a compilation unit. - * This flag is only valid if the element is an ICompilationUnit. + * Change flag indicating that a compilation unit has become a primary + * working copy, or that a primary working copy has reverted to a + * compilation unit. This flag is only valid if the element is an + * ICompilationUnit. * * @since 3.0 */ public int F_PRIMARY_WORKING_COPY = 0x10000; - + /** - * Change flag indicating that the raw classpath (or the output folder) of a project has changed. - * This flag is only valid if the element is an IJavaProject. - * + * Change flag indicating that the raw classpath (or the output folder) of a + * project has changed. This flag is only valid if the element is an + * IJavaProject. + * * @since 3.0 */ public int F_CLASSPATH_CHANGED = 0x20000; /** - * Change flag indicating that the resource of a primary compilation unit has changed. - * This flag is only valid if the element is a primary ICompilationUnit. + * Change flag indicating that the resource of a primary compilation unit + * has changed. This flag is only valid if the element is a primary + * ICompilationUnit. * * @since 3.0 */ public int F_PRIMARY_RESOURCE = 0x40000; + /** * Returns deltas for the children that have been added. + * * @return deltas for the children that have been added */ public IJavaElementDelta[] getAddedChildren(); /** * Returns deltas for the affected (added, removed, or changed) children. + * * @return deltas for the affected (added, removed, or changed) children */ public IJavaElementDelta[] getAffectedChildren(); /** * Returns deltas for the children which have changed. + * * @return deltas for the children which have changed */ public IJavaElementDelta[] getChangedChildren(); /** * Returns the element that this delta describes a change to. + * * @return the element that this delta describes a change to */ public IJavaElement getElement(); /** - * Returns flags that describe how an element has changed. - * Such flags should be tested using the & operand. For example: + * Returns flags that describe how an element has changed. Such flags should + * be tested using the & operand. For example: + * *

    -	 * if ((delta.getFlags() & IJavaElementDelta.F_CONTENT) != 0) {
    +	 * if ((delta.getFlags() & IJavaElementDelta.F_CONTENT) != 0) {
     	 * 	// the delta indicates a content change
     	 * }
     	 * 
    - * + * * @return flags that describe how an element has changed */ public int getFlags(); /** - * Returns the kind of this delta - one of ADDED, REMOVED, - * or CHANGED. + * Returns the kind of this delta - one of ADDED, + * REMOVED, or CHANGED. * * @return the kind of this delta */ public int getKind(); /** - * Returns an element describing this element before it was moved - * to its current location, or null if the - * F_MOVED_FROM change flag is not set. + * Returns an element describing this element before it was moved to its + * current location, or null if the F_MOVED_FROM + * change flag is not set. * - * @return an element describing this element before it was moved - * to its current location, or null if the - * F_MOVED_FROM change flag is not set + * @return an element describing this element before it was moved to its + * current location, or null if the + * F_MOVED_FROM change flag is not set */ public IJavaElement getMovedFromElement(); /** - * Returns an element describing this element in its new location, - * or null if the F_MOVED_TO change - * flag is not set. + * Returns an element describing this element in its new location, or + * null if the F_MOVED_TO change flag is not + * set. * - * @return an element describing this element in its new location, - * or null if the F_MOVED_TO change - * flag is not set + * @return an element describing this element in its new location, or + * null if the F_MOVED_TO change flag + * is not set */ public IJavaElement getMovedToElement(); @@ -338,11 +381,11 @@ public interface IJavaElementDelta { /** * Returns the collection of resource deltas. *

    - * Note that resource deltas, like Java element deltas, are generally only valid - * for the dynamic scope of an event notification. Clients must not hang on to - * these objects. + * Note that resource deltas, like Java element deltas, are generally only + * valid for the dynamic scope of an event notification. Clients must not + * hang on to these objects. *

    - * + * * @return the underlying resource deltas, or null if none */ public IResourceDelta[] getResourceDeltas(); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModel.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModel.java index f8cf1d8..b19805f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModel.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModel.java @@ -15,242 +15,318 @@ import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.runtime.IProgressMonitor; /** - * Represent the root Java element corresponding to the workspace. - * Since there is only one such root element, it is commonly referred to as - * the Java model element. - * The Java model element needs to be opened before it can be navigated or manipulated. - * The Java model element has no parent (it is the root of the Java element - * hierarchy). Its children are IJavaProjects. + * Represent the root Java element corresponding to the workspace. Since there + * is only one such root element, it is commonly referred to as the + * Java model element. The Java model element needs to be opened before it can + * be navigated or manipulated. The Java model element has no parent (it is the + * root of the Java element hierarchy). Its children are + * IJavaProjects. *

    - * This interface provides methods for performing copy, move, rename, and - * delete operations on multiple Java elements. + * This interface provides methods for performing copy, move, rename, and delete + * operations on multiple Java elements. *

    *

    - * This interface is not intended to be implemented by clients. An instance - * of one of these handles can be created via + * This interface is not intended to be implemented by clients. An instance of + * one of these handles can be created via * JavaCore.create(workspace.getRoot()). *

    - * + * * @see JavaCore#create(org.eclipse.core.resources.IWorkspaceRoot) */ public interface IJavaModel extends IJavaElement, IOpenable, IParent { -/** - * Returns whether this Java model contains an IJavaElement whose - * resource is the given resource or a non-Java resource which is the given resource. - *

    - * Note: no existency check is performed on the argument resource. If it is not accessible - * (see IResource.isAccessible()) yet but would be located in Java model - * range, then it will return true. - *

    - * If the resource is accessible, it can be reached by navigating the Java model down using the - * getChildren() and/or getNonJavaResources() methods. - *

    - * @param resource the resource to check - * @return true if the resource is accessible through the Java model - * @since 2.1 - */ -boolean contains(IResource resource); -/** - * Copies the given elements to the specified container(s). - * If one container is specified, all elements are copied to that - * container. If more than one container is specified, the number of - * elements and containers must match, and each element is copied to - * its associated container. - *

    - * Optionally, each copy can positioned before a sibling - * element. If null is specified for a given sibling, the copy - * is inserted as the last child of its associated container. - *

    - *

    - * Optionally, each copy can be renamed. If - * null is specified for the new name, the copy - * is not renamed. - *

    - *

    - * Optionally, any existing child in the destination container with - * the same name can be replaced by specifying true for - * force. Otherwise an exception is thrown in the event that a name - * collision occurs. - *

    - * - * @param elements the elements to copy - * @param containers the container, or list of containers - * @param siblings the list of siblings element any of which may be - * null; or null - * @param renamings the list of new names any of which may be - * null; or null - * @param replace true if any existing child in a target container - * with the target name should be replaced, and false to throw an - * exception in the event of a name collision - * @param monitor a progress monitor - * @exception JavaModelException if an element could not be copied. Reasons include: - *
      - *
    • There is no element to process (NO_ELEMENTS_TO_PROCESS). The given elements is null or empty
    • - *
    • A specified element, container, or sibling does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    • A CoreException occurred while updating an underlying resource
    • - *
    • A container is of an incompatible type (INVALID_DESTINATION)
    • - *
    • A sibling is not a child of it associated container (INVALID_SIBLING)
    • - *
    • A new name is invalid (INVALID_NAME)
    • - *
    • A child in its associated container already exists with the same - * name and replace has been specified as false (NAME_COLLISION)
    • - *
    • A container or element is read-only (READ_ONLY)
    • - *
    - */ -void copy(IJavaElement[] elements, IJavaElement[] containers, IJavaElement[] siblings, String[] renamings, boolean replace, IProgressMonitor monitor) throws JavaModelException; -/** - * Deletes the given elements, forcing the operation if necessary and specified. - * - * @param elements the elements to delete - * @param force a flag controlling whether underlying resources that are not - * in sync with the local file system will be tolerated - * @param monitor a progress monitor - * @exception JavaModelException if an element could not be deleted. Reasons include: - *
      - *
    • There is no element to process (NO_ELEMENTS_TO_PROCESS). The given elements is null or empty
    • - *
    • A specified element does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    • A CoreException occurred while updating an underlying resource
    • - *
    • An element is read-only (READ_ONLY)
    • - *
    - */ -void delete(IJavaElement[] elements, boolean force, IProgressMonitor monitor) throws JavaModelException; -/** - * Returns the Java project with the given name. This is a handle-only method. - * The project may or may not exist. - * - * @return the Java project with the given name - */ - IJavaProject getJavaProject(String name); -/** - * Returns the Java projects in this Java model, or an empty array if there - * are none. - * - * @return the Java projects in this Java model, or an empty array if there - * are none - * @exception JavaModelException if this request fails. - */ - IJavaProject[] getJavaProjects() throws JavaModelException; -/** - * Returns an array of non-Java resources (that is, non-Java projects) in - * the workspace. - *

    - * Non-Java projects include all projects that are closed (even if they have the - * Java nature). - *

    - * - * @return an array of non-Java projects contained in the workspace. - * @throws JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource - * @since 2.1 - */ -//Object[] getNonJavaResources() throws JavaModelException; -/** - * Returns the workspace associated with this Java model. - * - * @return the workspace associated with this Java model - */ -IWorkspace getWorkspace(); -/** - * Moves the given elements to the specified container(s). - * If one container is specified, all elements are moved to that - * container. If more than one container is specified, the number of - * elements and containers must match, and each element is moved to - * its associated container. - *

    - * Optionally, each element can positioned before a sibling - * element. If null is specified for sibling, the element - * is inserted as the last child of its associated container. - *

    - *

    - * Optionally, each element can be renamed. If - * null is specified for the new name, the element - * is not renamed. - *

    - *

    - * Optionally, any existing child in the destination container with - * the same name can be replaced by specifying true for - * force. Otherwise an exception is thrown in the event that a name - * collision occurs. - *

    - * - * @param elements the elements to move - * @param containers the container, or list of containers - * @param siblings the list of siblings element any of which may be - * null; or null - * @param renamings the list of new names any of which may be - * null; or null - * @param replace true if any existing child in a target container - * with the target name should be replaced, and false to throw an - * exception in the event of a name collision - * @param monitor a progress monitor - * @exception JavaModelException if an element could not be moved. Reasons include: - *
      - *
    • There is no element to process (NO_ELEMENTS_TO_PROCESS). The given elements is null or empty
    • - *
    • A specified element, container, or sibling does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    • A CoreException occurred while updating an underlying resource
    • - *
    • A container is of an incompatible type (INVALID_DESTINATION)
    • - *
    • A sibling is not a child of it associated container (INVALID_SIBLING)
    • - *
    • A new name is invalid (INVALID_NAME)
    • - *
    • A child in its associated container already exists with the same - * name and replace has been specified as false (NAME_COLLISION)
    • - *
    • A container or element is read-only (READ_ONLY)
    • - *
    - * - * @exception IllegalArgumentException any element or container is null - */ -void move(IJavaElement[] elements, IJavaElement[] containers, IJavaElement[] siblings, String[] renamings, boolean replace, IProgressMonitor monitor) throws JavaModelException; + /** + * Returns whether this Java model contains an IJavaElement + * whose resource is the given resource or a non-Java resource which is the + * given resource. + *

    + * Note: no existency check is performed on the argument resource. If it is + * not accessible (see IResource.isAccessible()) yet but + * would be located in Java model range, then it will return + * true. + *

    + *

    + * If the resource is accessible, it can be reached by navigating the Java + * model down using the getChildren() and/or + * getNonJavaResources() methods. + *

    + * + * @param resource + * the resource to check + * @return true if the resource is accessible through the Java model + * @since 2.1 + */ + boolean contains(IResource resource); -/** - * Triggers an update of the JavaModel with respect to the referenced external archives. - * This operation will issue a JavaModel delta describing the discovered changes, in term - * of Java element package fragment roots added, removed or changed. - * Note that a collection of elements can be passed so as to narrow the set of archives - * to refresh (passing null along is equivalent to refreshing the entire mode). - * The elements can be: - *
      - *
    • package fragment roots corresponding to external archives - *
    • Java projects, which referenced external archives will be refreshed - *
    • Java model, all referenced external archives will be refreshed. - *
    - *

    In case an archive is used by multiple projects, the delta issued will account for - * all of them. This means that even if a project was not part of the elements scope, it - * may still be notified of changes if it is referencing a library comprised in the scope. - *

    - * @param elementsScope - a collection of elements defining the scope of the refresh - * @param monitor - a progress monitor used to report progress - * @exception JavaModelException in one of the corresponding situation: - *

      - *
    • an exception occurs while accessing project resources
    • - *
    - * - * @see IJavaElementDelta - * @since 2.0 - */ -//void refreshExternalArchives(IJavaElement[] elementsScope, IProgressMonitor monitor) throws JavaModelException; + /** + * Copies the given elements to the specified container(s). If one container + * is specified, all elements are copied to that container. If more than one + * container is specified, the number of elements and containers must match, + * and each element is copied to its associated container. + *

    + * Optionally, each copy can positioned before a sibling element. If + * null is specified for a given sibling, the copy is + * inserted as the last child of its associated container. + *

    + *

    + * Optionally, each copy can be renamed. If null is specified + * for the new name, the copy is not renamed. + *

    + *

    + * Optionally, any existing child in the destination container with the same + * name can be replaced by specifying true for force. + * Otherwise an exception is thrown in the event that a name collision + * occurs. + *

    + * + * @param elements + * the elements to copy + * @param containers + * the container, or list of containers + * @param siblings + * the list of siblings element any of which may be + * null; or null + * @param renamings + * the list of new names any of which may be null; + * or null + * @param replace + * true if any existing child in a target + * container with the target name should be replaced, and + * false to throw an exception in the event of a + * name collision + * @param monitor + * a progress monitor + * @exception JavaModelException + * if an element could not be copied. Reasons include: + *
      + *
    • There is no element to process + * (NO_ELEMENTS_TO_PROCESS). The given elements is null or + * empty
    • + *
    • A specified element, container, or sibling does not + * exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while + * updating an underlying resource
    • + *
    • A container is of an incompatible type (INVALID_DESTINATION)
    • + *
    • A sibling is not a child of it associated container (INVALID_SIBLING)
    • + *
    • A new name is invalid (INVALID_NAME)
    • + *
    • A child in its associated container already exists + * with the same name and replace has been + * specified as false (NAME_COLLISION)
    • + *
    • A container or element is read-only (READ_ONLY) + *
    • + *
    + */ + void copy(IJavaElement[] elements, IJavaElement[] containers, + IJavaElement[] siblings, String[] renamings, boolean replace, + IProgressMonitor monitor) throws JavaModelException; -/** - * Renames the given elements as specified. - * If one container is specified, all elements are renamed within that - * container. If more than one container is specified, the number of - * elements and containers must match, and each element is renamed within - * its associated container. - * - * @param elements the elements to rename - * @param destinations the container, or list of containers - * @param names the list of new names - * @param replace true if an existing child in a target container - * with the target name should be replaced, and false to throw an - * exception in the event of a name collision - * @param monitor a progress monitor - * @exception JavaModelException if an element could not be renamed. Reasons include: - *
      - *
    • There is no element to process (NO_ELEMENTS_TO_PROCESS). The given elements is null or empty
    • - *
    • A specified element does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    • A CoreException occurred while updating an underlying resource - *
    • A new name is invalid (INVALID_NAME) - *
    • A child already exists with the same name and replace has been specified as false (NAME_COLLISION) - *
    • An element is read-only (READ_ONLY) - *
    - */ -void rename(IJavaElement[] elements, IJavaElement[] destinations, String[] names, boolean replace, IProgressMonitor monitor) throws JavaModelException; + /** + * Deletes the given elements, forcing the operation if necessary and + * specified. + * + * @param elements + * the elements to delete + * @param force + * a flag controlling whether underlying resources that are not + * in sync with the local file system will be tolerated + * @param monitor + * a progress monitor + * @exception JavaModelException + * if an element could not be deleted. Reasons include: + *
      + *
    • There is no element to process + * (NO_ELEMENTS_TO_PROCESS). The given elements is null or + * empty
    • + *
    • A specified element does not exist + * (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while + * updating an underlying resource
    • + *
    • An element is read-only (READ_ONLY) + *
    • + *
    + */ + void delete(IJavaElement[] elements, boolean force, IProgressMonitor monitor) + throws JavaModelException; + + /** + * Returns the Java project with the given name. This is a handle-only + * method. The project may or may not exist. + * + * @return the Java project with the given name + */ + IJavaProject getJavaProject(String name); + + /** + * Returns the Java projects in this Java model, or an empty array if there + * are none. + * + * @return the Java projects in this Java model, or an empty array if there + * are none + * @exception JavaModelException + * if this request fails. + */ + IJavaProject[] getJavaProjects() throws JavaModelException; + + /** + * Returns an array of non-Java resources (that is, non-Java projects) in + * the workspace. + *

    + * Non-Java projects include all projects that are closed (even if they have + * the Java nature). + *

    + * + * @return an array of non-Java projects contained in the workspace. + * @throws JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource + * @since 2.1 + */ + // Object[] getNonJavaResources() throws JavaModelException; + /** + * Returns the workspace associated with this Java model. + * + * @return the workspace associated with this Java model + */ + IWorkspace getWorkspace(); + + /** + * Moves the given elements to the specified container(s). If one container + * is specified, all elements are moved to that container. If more than one + * container is specified, the number of elements and containers must match, + * and each element is moved to its associated container. + *

    + * Optionally, each element can positioned before a sibling element. If + * null is specified for sibling, the element is inserted as + * the last child of its associated container. + *

    + *

    + * Optionally, each element can be renamed. If null is + * specified for the new name, the element is not renamed. + *

    + *

    + * Optionally, any existing child in the destination container with the same + * name can be replaced by specifying true for force. + * Otherwise an exception is thrown in the event that a name collision + * occurs. + *

    + * + * @param elements + * the elements to move + * @param containers + * the container, or list of containers + * @param siblings + * the list of siblings element any of which may be + * null; or null + * @param renamings + * the list of new names any of which may be null; + * or null + * @param replace + * true if any existing child in a target + * container with the target name should be replaced, and + * false to throw an exception in the event of a + * name collision + * @param monitor + * a progress monitor + * @exception JavaModelException + * if an element could not be moved. Reasons include: + *
      + *
    • There is no element to process + * (NO_ELEMENTS_TO_PROCESS). The given elements is null or + * empty
    • + *
    • A specified element, container, or sibling does not + * exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while + * updating an underlying resource
    • + *
    • A container is of an incompatible type (INVALID_DESTINATION)
    • + *
    • A sibling is not a child of it associated container (INVALID_SIBLING)
    • + *
    • A new name is invalid (INVALID_NAME)
    • + *
    • A child in its associated container already exists + * with the same name and replace has been + * specified as false (NAME_COLLISION)
    • + *
    • A container or element is read-only (READ_ONLY) + *
    • + *
    + * + * @exception IllegalArgumentException + * any element or container is null + */ + void move(IJavaElement[] elements, IJavaElement[] containers, + IJavaElement[] siblings, String[] renamings, boolean replace, + IProgressMonitor monitor) throws JavaModelException; + + /** + * Triggers an update of the JavaModel with respect to the referenced + * external archives. This operation will issue a JavaModel delta describing + * the discovered changes, in term of Java element package fragment roots + * added, removed or changed. Note that a collection of elements can be + * passed so as to narrow the set of archives to refresh (passing + * null along is equivalent to refreshing the entire mode). + * The elements can be: + *
      + *
    • package fragment roots corresponding to external archives + *
    • Java projects, which referenced external archives will be refreshed + *
    • Java model, all referenced external archives will be refreshed. + *
    + *

    + * In case an archive is used by multiple projects, the delta issued will + * account for all of them. This means that even if a project was not part + * of the elements scope, it may still be notified of changes if it is + * referencing a library comprised in the scope. + *

    + * + * @param elementsScope - + * a collection of elements defining the scope of the refresh + * @param monitor - + * a progress monitor used to report progress + * @exception JavaModelException + * in one of the corresponding situation: + *

      + *
    • an exception occurs while accessing project resources + *
    • + *
    + * + * @see IJavaElementDelta + * @since 2.0 + */ + // void refreshExternalArchives(IJavaElement[] elementsScope, + // IProgressMonitor monitor) throws JavaModelException; + /** + * Renames the given elements as specified. If one container is specified, + * all elements are renamed within that container. If more than one + * container is specified, the number of elements and containers must match, + * and each element is renamed within its associated container. + * + * @param elements + * the elements to rename + * @param destinations + * the container, or list of containers + * @param names + * the list of new names + * @param replace + * true if an existing child in a target container + * with the target name should be replaced, and + * false to throw an exception in the event of a + * name collision + * @param monitor + * a progress monitor + * @exception JavaModelException + * if an element could not be renamed. Reasons include: + *
      + *
    • There is no element to process + * (NO_ELEMENTS_TO_PROCESS). The given elements is null or + * empty
    • + *
    • A specified element does not exist + * (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while + * updating an underlying resource + *
    • A new name is invalid (INVALID_NAME) + *
    • A child already exists with the same name and + * replace has been specified as + * false (NAME_COLLISION) + *
    • An element is read-only (READ_ONLY) + *
    + */ + void rename(IJavaElement[] elements, IJavaElement[] destinations, + String[] names, boolean replace, IProgressMonitor monitor) + throws JavaModelException; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModelMarker.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModelMarker.java index 9c5dd12..f2f983f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModelMarker.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModelMarker.java @@ -10,7 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpdt.core; - /** * Markers used by the Java model. *

    @@ -21,74 +20,81 @@ package net.sourceforge.phpdt.core; public interface IJavaModelMarker { /** - * Java model problem marker type (value "net.sourceforge.phpdt.core.problem"). - * This can be used to recognize those markers in the workspace that flag problems - * detected by the Java tooling during compilation. + * Java model problem marker type (value + * "net.sourceforge.phpdt.core.problem"). This can be used + * to recognize those markers in the workspace that flag problems detected + * by the Java tooling during compilation. */ - public static final String JAVA_MODEL_PROBLEM_MARKER = JavaCore.PLUGIN_ID + ".problem"; //$NON-NLS-1$ - + public static final String JAVA_MODEL_PROBLEM_MARKER = JavaCore.PLUGIN_ID + + ".problem"; //$NON-NLS-1$ /** - * Java model transient problem marker type (value "net.sourceforge.phpdt.core.transient_problem"). - * This can be used to recognize those markers in the workspace that flag transient - * problems detected by the Java tooling (such as a problem - * detected by the outliner, or a problem detected during a code completion) + * Java model transient problem marker type (value + * "net.sourceforge.phpdt.core.transient_problem"). This can + * be used to recognize those markers in the workspace that flag transient + * problems detected by the Java tooling (such as a problem detected by the + * outliner, or a problem detected during a code completion) */ - public static final String TRANSIENT_PROBLEM = JavaCore.PLUGIN_ID + ".transient_problem"; //$NON-NLS-1$ + public static final String TRANSIENT_PROBLEM = JavaCore.PLUGIN_ID + + ".transient_problem"; //$NON-NLS-1$ /** - * Java model task marker type (value "net.sourceforge.phpdt.core.task"). - * This can be used to recognize task markers in the workspace that correspond to tasks - * specified in Java source comments and detected during compilation (for example, 'TO-DO: ...'). - * Tasks are identified by a task tag, which can be customized through PHPCore - * option "net.sourceforge.phpdt.core.compiler.taskTag". + * Java model task marker type (value + * "net.sourceforge.phpdt.core.task"). This can be used to + * recognize task markers in the workspace that correspond to tasks + * specified in Java source comments and detected during compilation (for + * example, 'TO-DO: ...'). Tasks are identified by a task tag, which can be + * customized through PHPCore option + * "net.sourceforge.phpdt.core.compiler.taskTag". + * * @since 2.1 */ public static final String TASK_MARKER = JavaCore.PLUGIN_ID + ".task"; //$NON-NLS-1$ - - /** - * Id marker attribute (value "arguments"). - * Arguments are concatenated into one String, prefixed with an argument count (followed with colon - * separator) and separated with '#' characters. For example: - * { "foo", "bar" } is encoded as "2:foo#bar", - * { } is encoded as "0: " + /** + * Id marker attribute (value "arguments"). Arguments are + * concatenated into one String, prefixed with an argument count (followed + * with colon separator) and separated with '#' characters. For example: { + * "foo", "bar" } is encoded as "2:foo#bar", { } is encoded as "0: " + * * @since 2.0 */ - public static final String ARGUMENTS = "arguments"; //$NON-NLS-1$ - - /** + public static final String ARGUMENTS = "arguments"; //$NON-NLS-1$ + + /** * Id marker attribute (value "id"). */ - public static final String ID = "id"; //$NON-NLS-1$ + public static final String ID = "id"; //$NON-NLS-1$ - /** - * Flags marker attribute (value "flags"). - * Reserved for future use. + /** + * Flags marker attribute (value "flags"). Reserved for + * future use. */ - public static final String FLAGS = "flags"; //$NON-NLS-1$ + public static final String FLAGS = "flags"; //$NON-NLS-1$ - /** + /** * Cycle detected marker attribute (value "cycleDetected"). - * Used only on buildpath problem markers. - * The value of this attribute is either "true" or "false". + * Used only on buildpath problem markers. The value of this attribute is + * either "true" or "false". */ - public static final String CYCLE_DETECTED = "cycleDetected"; //$NON-NLS-1$ + public static final String CYCLE_DETECTED = "cycleDetected"; //$NON-NLS-1$ /** - * Build path problem marker type (value "net.sourceforge.phpdt.core.buildpath_problem"). - * This can be used to recognize those markers in the workspace that flag problems + * Build path problem marker type (value + * "net.sourceforge.phpdt.core.buildpath_problem"). This can + * be used to recognize those markers in the workspace that flag problems * detected by the Java tooling during classpath setting. */ - public static final String BUILDPATH_PROBLEM_MARKER = JavaCore.PLUGIN_ID + ".buildpath_problem"; //$NON-NLS-1$ - - /** - * Classpath file format marker attribute (value "classpathFileFormat"). - * Used only on buildpath problem markers. - * The value of this attribute is either "true" or "false". + public static final String BUILDPATH_PROBLEM_MARKER = JavaCore.PLUGIN_ID + + ".buildpath_problem"; //$NON-NLS-1$ + + /** + * Classpath file format marker attribute (value + * "classpathFileFormat"). Used only on buildpath problem + * markers. The value of this attribute is either "true" or "false". * * @since 2.0 */ - public static final String CLASSPATH_FILE_FORMAT = "classpathFileFormat"; //$NON-NLS-1$ - + public static final String CLASSPATH_FILE_FORMAT = "classpathFileFormat"; //$NON-NLS-1$ + } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModelStatus.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModelStatus.java index 6f55b0c..2df29b4 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModelStatus.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModelStatus.java @@ -14,9 +14,8 @@ import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; /** - * Represents the outcome of an Java model operation. Status objects are - * used inside JavaModelException objects to indicate what went - * wrong. + * Represents the outcome of an Java model operation. Status objects are used + * inside JavaModelException objects to indicate what went wrong. *

    * Java model status object are distinguished by their plug-in id: * getPlugin returns "net.sourceforge.phpdt.core". @@ -24,61 +23,63 @@ import org.eclipse.core.runtime.IStatus; * IJavaModelStatusConstants. *

    *

    - * A Java model status may also carry additional information (that is, in + * A Java model status may also carry additional information (that is, in * addition to the information defined in IStatus): *

      - *
    • elements - optional handles to Java elements associated with the failure
    • - *
    • string - optional string associated with the failure
    • + *
    • elements - optional handles to Java elements associated with the failure
    • + *
    • string - optional string associated with the failure
    • *
    *

    * This interface is not intended to be implemented by clients. *

    - * + * * @see org.eclipse.core.runtime.IStatus * @see IJavaModelStatusConstants */ public interface IJavaModelStatus extends IStatus { -/** - * Returns any Java elements associated with the failure (see specification - * of the status code), or an empty array if no elements are related to this - * particular status code. - * - * @return the list of Java element culprits - * @see IJavaModelStatusConstants - */ -public IJavaElement[] getElements(); + /** + * Returns any Java elements associated with the failure (see specification + * of the status code), or an empty array if no elements are related to this + * particular status code. + * + * @return the list of Java element culprits + * @see IJavaModelStatusConstants + */ + public IJavaElement[] getElements(); -/** - * Returns the path associated with the failure (see specification - * of the status code), or null if the failure is not - * one of DEVICE_PATH, INVALID_PATH, - * PATH_OUTSIDE_PROJECT, or RELATIVE_PATH. - * - * @return the path that caused the failure, or null if none - * @see IJavaModelStatusConstants#DEVICE_PATH - * @see IJavaModelStatusConstants#INVALID_PATH - * @see IJavaModelStatusConstants#PATH_OUTSIDE_PROJECT - * @see IJavaModelStatusConstants#RELATIVE_PATH - */ -IPath getPath(); -/** - * Returns the string associated with the failure (see specification - * of the status code), or null if no string is related to this - * particular status code. - * - * @return the string culprit, or null if none - * @see IJavaModelStatusConstants - * @deprecated Use IStatus#getMessage instead - */ -String getString(); -/** - * Returns whether this status indicates that a Java model element does not exist. - * This convenience method is equivalent to - * getCode() == IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST. - * - * @return true if the status code indicates that a Java model - * element does not exist - * @see IJavaModelStatusConstants#ELEMENT_DOES_NOT_EXIST - */ -boolean isDoesNotExist(); + /** + * Returns the path associated with the failure (see specification of the + * status code), or null if the failure is not one of + * DEVICE_PATH, INVALID_PATH, + * PATH_OUTSIDE_PROJECT, or RELATIVE_PATH. + * + * @return the path that caused the failure, or null if none + * @see IJavaModelStatusConstants#DEVICE_PATH + * @see IJavaModelStatusConstants#INVALID_PATH + * @see IJavaModelStatusConstants#PATH_OUTSIDE_PROJECT + * @see IJavaModelStatusConstants#RELATIVE_PATH + */ + IPath getPath(); + + /** + * Returns the string associated with the failure (see specification of the + * status code), or null if no string is related to this + * particular status code. + * + * @return the string culprit, or null if none + * @see IJavaModelStatusConstants + * @deprecated Use IStatus#getMessage instead + */ + String getString(); + + /** + * Returns whether this status indicates that a Java model element does not + * exist. This convenience method is equivalent to + * getCode() == IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST. + * + * @return true if the status code indicates that a Java + * model element does not exist + * @see IJavaModelStatusConstants#ELEMENT_DOES_NOT_EXIST + */ + boolean isDoesNotExist(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModelStatusConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModelStatusConstants.java index f31517d..d4b11a0 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModelStatusConstants.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModelStatusConstants.java @@ -16,15 +16,15 @@ package net.sourceforge.phpdt.core; * This interface declares constants only; it is not intended to be implemented * or extended. *

    - * + * * @see IJavaModelStatus * @see org.eclipse.core.runtime.IStatus#getCode() */ public interface IJavaModelStatusConstants { /** - * Status constant indicating that a container path was resolved - * to invalid entries (null or container). + * Status constant indicating that a container path was resolved to invalid + * entries (null or container). * * @since 2.0 */ @@ -45,166 +45,160 @@ public interface IJavaModelStatusConstants { /** * Status constant indicating that a variable path was not resolvable - * indicating either the referred variable is undefined, unbound or the resolved - * variable path does not correspond to an existing file or folder. + * indicating either the referred variable is undefined, unbound or the + * resolved variable path does not correspond to an existing file or folder. */ public static final int CP_VARIABLE_PATH_UNBOUND = 965; /** - * Status constant indicating a core exception occurred. - * Use getException to retrieve a CoreException. + * Status constant indicating a core exception occurred. Use + * getException to retrieve a CoreException. */ public static final int CORE_EXCEPTION = 966; - + /** - * Status constant indicating one or more of the elements - * supplied are not of a valid type for the operation to - * process. - * The element(s) can be retrieved using getElements on the status object. + * Status constant indicating one or more of the elements supplied are not + * of a valid type for the operation to process. The element(s) can be + * retrieved using getElements on the status object. */ public static final int INVALID_ELEMENT_TYPES = 967; /** - * Status constant indicating that no elements were - * provided to the operation for processing. + * Status constant indicating that no elements were provided to the + * operation for processing. */ public static final int NO_ELEMENTS_TO_PROCESS = 968; /** - * Status constant indicating that one or more elements - * supplied do not exist. - * The element(s) can be retrieved using getElements on the status object. - * + * Status constant indicating that one or more elements supplied do not + * exist. The element(s) can be retrieved using getElements + * on the status object. + * * @see IJavaModelStatus#isDoesNotExist */ public static final int ELEMENT_DOES_NOT_EXIST = 969; /** - * Status constant indicating that a null path was - * supplied to the operation. + * Status constant indicating that a null path was supplied + * to the operation. */ public static final int NULL_PATH = 970; - + /** - * Status constant indicating that a path outside of the - * project was supplied to the operation. The path can be retrieved using + * Status constant indicating that a path outside of the project was + * supplied to the operation. The path can be retrieved using * getPath on the status object. */ public static final int PATH_OUTSIDE_PROJECT = 971; - + /** - * Status constant indicating that a relative path - * was supplied to the operation when an absolute path is - * required. The path can be retrieved using getPath on the - * status object. + * Status constant indicating that a relative path was supplied to the + * operation when an absolute path is required. The path can be retrieved + * using getPath on the status object. */ public static final int RELATIVE_PATH = 972; - + /** - * Status constant indicating that a path specifying a device - * was supplied to the operation when a path with no device is - * required. The path can be retrieved using getPath on the - * status object. + * Status constant indicating that a path specifying a device was supplied + * to the operation when a path with no device is required. The path can be + * retrieved using getPath on the status object. */ public static final int DEVICE_PATH = 973; - + /** - * Status constant indicating that a string - * was supplied to the operation that was null. + * Status constant indicating that a string was supplied to the operation + * that was null. */ public static final int NULL_STRING = 974; - + /** - * Status constant indicating that the operation encountered - * a read-only element. - * The element(s) can be retrieved using getElements on the status object. + * Status constant indicating that the operation encountered a read-only + * element. The element(s) can be retrieved using getElements + * on the status object. */ public static final int READ_ONLY = 976; - + /** - * Status constant indicating that a naming collision would occur - * if the operation proceeded. + * Status constant indicating that a naming collision would occur if the + * operation proceeded. */ public static final int NAME_COLLISION = 977; - + /** - * Status constant indicating that a destination provided for a copy/move/rename operation - * is invalid. - * The destination element can be retrieved using getElements on the status object. + * Status constant indicating that a destination provided for a + * copy/move/rename operation is invalid. The destination element can be + * retrieved using getElements on the status object. */ public static final int INVALID_DESTINATION = 978; - + /** - * Status constant indicating that a path provided to an operation - * is invalid. The path can be retrieved using getPath on the + * Status constant indicating that a path provided to an operation is + * invalid. The path can be retrieved using getPath on the * status object. */ public static final int INVALID_PATH = 979; - + /** * Status constant indicating the given source position is out of bounds. */ public static final int INDEX_OUT_OF_BOUNDS = 980; - + /** - * Status constant indicating there is an update conflict - * for a working copy. The compilation unit on which the - * working copy is based has changed since the working copy - * was created. + * Status constant indicating there is an update conflict for a working + * copy. The compilation unit on which the working copy is based has changed + * since the working copy was created. */ public static final int UPDATE_CONFLICT = 981; /** - * Status constant indicating that null was specified - * as a name argument. + * Status constant indicating that null was specified as a + * name argument. */ public static final int NULL_NAME = 982; /** - * Status constant indicating that a name provided is not syntactically correct. - * The name can be retrieved from getString. + * Status constant indicating that a name provided is not syntactically + * correct. The name can be retrieved from getString. */ public static final int INVALID_NAME = 983; /** - * Status constant indicating that the specified contents - * are not valid. + * Status constant indicating that the specified contents are not valid. */ public static final int INVALID_CONTENTS = 984; /** * Status constant indicating that an java.io.IOException - * occurred. + * occurred. */ public static final int IO_EXCEPTION = 985; /** - * Status constant indicating that a DOMException - * occurred. + * Status constant indicating that a DOMException occurred. */ public static final int DOM_EXCEPTION = 986; /** * Status constant indicating that a TargetException - * occurred. + * occurred. */ public static final int TARGET_EXCEPTION = 987; /** - * Status constant indicating that the Java builder - * could not be initialized. + * Status constant indicating that the Java builder could not be + * initialized. */ public static final int BUILDER_INITIALIZATION_ERROR = 990; /** - * Status constant indicating that the Java builder's last built state - * could not be serialized or deserialized. + * Status constant indicating that the Java builder's last built state could + * not be serialized or deserialized. */ public static final int BUILDER_SERIALIZATION_ERROR = 991; /** - * Status constant indicating that an error was encountered while - * trying to evaluate a code snippet, or other item. + * Status constant indicating that an error was encountered while trying to + * evaluate a code snippet, or other item. */ public static final int EVALUATION_ERROR = 992; @@ -214,59 +208,65 @@ public interface IJavaModelStatusConstants { public static final int INVALID_SIBLING = 993; /** - * Status indicating that a Java element could not be created because - * the underlying resource is invalid. + * Status indicating that a Java element could not be created because the + * underlying resource is invalid. + * * @see JavaCore */ - public static final int INVALID_RESOURCE = 995; + public static final int INVALID_RESOURCE = 995; /** - * Status indicating that a Java element could not be created because - * the underlying resource is not of an appropriate type. + * Status indicating that a Java element could not be created because the + * underlying resource is not of an appropriate type. + * * @see JavaCore */ - public static final int INVALID_RESOURCE_TYPE = 996; + public static final int INVALID_RESOURCE_TYPE = 996; /** - * Status indicating that a Java element could not be created because - * the project owning underlying resource does not have the Java nature. + * Status indicating that a Java element could not be created because the + * project owning underlying resource does not have the Java nature. + * * @see JavaCore */ - public static final int INVALID_PROJECT = 997; + public static final int INVALID_PROJECT = 997; + + /** + * Status indicating that the package declaration in a + * ICompilationUnit does not correspond to the + * IPackageFragment it belongs to. The getString + * method of the associated status object gives the name of the package in + * which the ICompilationUnit is declared. + */ + public static final int INVALID_PACKAGE = 998; + + /** + * Status indicating that the corresponding resource has no local contents + * yet. This might happen when attempting to use a resource before its + * contents has been made locally available. + */ + public static final int NO_LOCAL_CONTENTS = 999; /** - * Status indicating that the package declaration in a ICompilationUnit - * does not correspond to the IPackageFragment it belongs to. - * The getString method of the associated status object - * gives the name of the package in which the ICompilationUnit is - * declared. + * Status indicating that a .classpath file is ill-formed, and thus cannot + * be read/written successfully. + * + * @since 2.1 */ - public static final int INVALID_PACKAGE = 998; + public static final int INVALID_CLASSPATH_FILE_FORMAT = 1000; /** - * Status indicating that the corresponding resource has no local contents yet. - * This might happen when attempting to use a resource before its contents - * has been made locally available. + * Status indicating that a project is involved in a build path cycle. + * + * @since 2.1 */ - public static final int NO_LOCAL_CONTENTS = 999; - - /** - * Status indicating that a .classpath file is ill-formed, and thus cannot - * be read/written successfully. - * @since 2.1 - */ - public static final int INVALID_CLASSPATH_FILE_FORMAT = 1000; + public static final int CLASSPATH_CYCLE = 1001; - /** - * Status indicating that a project is involved in a build path cycle. - * @since 2.1 - */ - public static final int CLASSPATH_CYCLE = 1001; - /** - * Status constant indicating that an exclusion pattern got specified - * on a classpath source entry, though it was explicitely disabled - * according to its project preference settings. + * Status constant indicating that an exclusion pattern got specified on a + * classpath source entry, though it was explicitely disabled according to + * its project preference settings. + * * @see net.sourceforge.phpdt.core.IJavaProject#getOptions(boolean) * @since 2.1 */ @@ -274,16 +274,18 @@ public interface IJavaModelStatusConstants { /** * Status constant indicating that a specific output location got associated - * with a source entry, though it was explicitely disabled according to its project - * preference settings. + * with a source entry, though it was explicitely disabled according to its + * project preference settings. + * * @see net.sourceforge.phpdt.core.IJavaProject#getOptions(boolean) * @since 2.1 */ public static final int DISABLED_CP_MULTIPLE_OUTPUT_LOCATIONS = 1003; - + /** * Status constant indicating that a compiler failure occurred. + * * @since 3.0 */ - public static final int COMPILER_FAILURE = 1005; + public static final int COMPILER_FAILURE = 1005; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaProject.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaProject.java index 31ef9a2..4819bc7 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaProject.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaProject.java @@ -21,34 +21,33 @@ import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; - /** - * A Java project represents a view of a project resource in terms of Java - * elements such as package fragments, types, methods and fields. - * A project may contain several package roots, which contain package fragments. - * A package root corresponds to an underlying folder or JAR. + * A Java project represents a view of a project resource in terms of Java + * elements such as package fragments, types, methods and fields. A project may + * contain several package roots, which contain package fragments. A package + * root corresponds to an underlying folder or JAR. *

    - * Each Java project has a classpath, defining which folders contain source code and - * where required libraries are located. Each Java project also has an output location, - * defining where the builder writes .class files. A project that - * references packages in another project can access the packages by including - * the required project in a classpath entry. The Java model will present the - * source elements in the required project; when building, the compiler will use - * the corresponding generated class files from the required project's output - * location(s)). The classpath format is a sequence of classpath entries - * describing the location and contents of package fragment roots. + * Each Java project has a classpath, defining which folders contain source code + * and where required libraries are located. Each Java project also has an + * output location, defining where the builder writes .class + * files. A project that references packages in another project can access the + * packages by including the required project in a classpath entry. The Java + * model will present the source elements in the required project; when + * building, the compiler will use the corresponding generated class files from + * the required project's output location(s)). The classpath format is a + * sequence of classpath entries describing the location and contents of package + * fragment roots. *

    - * Java project elements need to be opened before they can be navigated or manipulated. - * The children of a Java project are the package fragment roots that are - * defined by the classpath and contained in this project (in other words, it - * does not include package fragment roots for other projects). + * Java project elements need to be opened before they can be navigated or + * manipulated. The children of a Java project are the package fragment roots + * that are defined by the classpath and contained in this project (in other + * words, it does not include package fragment roots for other projects). *

    *

    - * This interface is not intended to be implemented by clients. An instance - * of one of these handles can be created via - * JavaCore.create(project). + * This interface is not intended to be implemented by clients. An instance of + * one of these handles can be created via JavaCore.create(project). *

    - * + * * @see JavaCore#create(org.eclipse.core.resources.IProject) * @see IClasspathEntry */ @@ -56,188 +55,214 @@ public interface IJavaProject extends IParent, IJavaElement, IOpenable { /** * Returns the IJavaElement corresponding to the given - * classpath-relative path, or null if no such + * classpath-relative path, or null if no such * IJavaElement is found. The result is one of an * ICompilationUnit, IClassFile, or - * IPackageFragment. + * IPackageFragment. *

    * When looking for a package fragment, there might be several potential * matches; only one of them is returned. - * - *

    For example, the path "java/lang/Object.java", would result in the - * ICompilationUnit or IClassFile corresponding to - * "java.lang.Object". The path "java/lang" would result in the - * IPackageFragment for "java.lang". - * @param path the given classpath-relative path - * @exception JavaModelException if the given path is null - * or absolute + * + *

    + * For example, the path "java/lang/Object.java", would result in the + * ICompilationUnit or IClassFile + * corresponding to "java.lang.Object". The path "java/lang" would result in + * the IPackageFragment for "java.lang". + * + * @param path + * the given classpath-relative path + * @exception JavaModelException + * if the given path is null or absolute * @return the IJavaElement corresponding to the given - * classpath-relative path, or null if no such - * IJavaElement is found + * classpath-relative path, or null if no such + * IJavaElement is found */ IJavaElement findElement(IPath path) throws JavaModelException; /** * Returns the first existing package fragment on this project's classpath - * whose path matches the given (absolute) path, or null if none - * exist. - * The path can be: - * - internal to the workbench: "/Project/src" - * - external to the workbench: "c:/jdk/classes.zip/java/lang" - * @param path the given absolute path - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource + * whose path matches the given (absolute) path, or null if + * none exist. The path can be: - internal to the workbench: "/Project/src" - + * external to the workbench: "c:/jdk/classes.zip/java/lang" + * + * @param path + * the given absolute path + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource * @return the first existing package fragment on this project's classpath - * whose path matches the given (absolute) path, or null if none - * exist + * whose path matches the given (absolute) path, or + * null if none exist */ -// IPackageFragment findPackageFragment(IPath path) throws JavaModelException; - + // IPackageFragment findPackageFragment(IPath path) throws + // JavaModelException; /** * Returns the existing package fragment root on this project's classpath * whose path matches the given (absolute) path, or null if - * one does not exist. - * The path can be: - * - internal to the workbench: "/Compiler/src" - * - external to the workbench: "c:/jdk/classes.zip" - * @param path the given absolute path - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource + * one does not exist. The path can be: - internal to the workbench: + * "/Compiler/src" - external to the workbench: "c:/jdk/classes.zip" + * + * @param path + * the given absolute path + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource * @return the existing package fragment root on this project's classpath - * whose path matches the given (absolute) path, or null if - * one does not exist + * whose path matches the given (absolute) path, or + * null if one does not exist */ IPackageFragmentRoot findPackageFragmentRoot(IPath path) - throws JavaModelException; + throws JavaModelException; + /** - * Returns the existing package fragment roots identified by the given entry. - * Note that a classpath entry that refers to another project may - * have more than one root (if that project has more than on root - * containing source), and classpath entries within the current - * project identify a single root. + * Returns the existing package fragment roots identified by the given + * entry. Note that a classpath entry that refers to another project may + * have more than one root (if that project has more than on root containing + * source), and classpath entries within the current project identify a + * single root. *

    * If the classpath entry denotes a variable, it will be resolved and return * the roots of the target entry (empty if not resolvable). *

    - * If the classpath entry denotes a container, it will be resolved and return - * the roots corresponding to the set of container entries (empty if not resolvable). + * If the classpath entry denotes a container, it will be resolved and + * return the roots corresponding to the set of container entries (empty if + * not resolvable). * - * @param entry the given entry + * @param entry + * the given entry * @return the existing package fragment roots identified by the given entry * @see IClasspathContainer * @since 2.1 */ IPackageFragmentRoot[] findPackageFragmentRoots(IClasspathEntry entry); + /** - * Returns the first type found following this project's classpath - * with the given fully qualified name or null if none is found. - * The fully qualified name is a dot-separated name. For example, - * a class B defined as a member type of a class A in package x.y should have a - * the fully qualified name "x.y.A.B". + * Returns the first type found following this project's classpath with the + * given fully qualified name or null if none is found. The + * fully qualified name is a dot-separated name. For example, a class B + * defined as a member type of a class A in package x.y should have a the + * fully qualified name "x.y.A.B". * * Note that in order to be found, a type name (or its toplevel enclosing - * type name) must match its corresponding compilation unit name. As a + * type name) must match its corresponding compilation unit name. As a * consequence, secondary types cannot be found using this functionality. - * Secondary types can however be explicitely accessed through their enclosing - * unit or found by the SearchEngine. - * - * @param fullyQualifiedName the given fully qualified name - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource - * @return the first type found following this project's classpath - * with the given fully qualified name or null if none is found + * Secondary types can however be explicitely accessed through their + * enclosing unit or found by the SearchEngine. + * + * @param fullyQualifiedName + * the given fully qualified name + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource + * @return the first type found following this project's classpath with the + * given fully qualified name or null if none is + * found * @see IType#getFullyQualifiedName(char) * @since 2.0 */ -// IType findType(String fullyQualifiedName) throws JavaModelException; + // IType findType(String fullyQualifiedName) throws JavaModelException; /** - * Returns the first type found following this project's classpath - * with the given package name and type qualified name - * or null if none is found. - * The package name is a dot-separated name. - * The type qualified name is also a dot-separated name. For example, - * a class B defined as a member type of a class A should have the - * type qualified name "A.B". + * Returns the first type found following this project's classpath with the + * given package name and type qualified name or null if none + * is found. The package name is a dot-separated name. The type qualified + * name is also a dot-separated name. For example, a class B defined as a + * member type of a class A should have the type qualified name "A.B". * * Note that in order to be found, a type name (or its toplevel enclosing - * type name) must match its corresponding compilation unit name. As a + * type name) must match its corresponding compilation unit name. As a * consequence, secondary types cannot be found using this functionality. - * Secondary types can however be explicitely accessed through their enclosing - * unit or found by the SearchEngine. - * - * @param packageName the given package name - * @param typeQualifiedName the given type qualified name - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource - * @return the first type found following this project's classpath - * with the given package name and type qualified name - * or null if none is found + * Secondary types can however be explicitely accessed through their + * enclosing unit or found by the SearchEngine. + * + * @param packageName + * the given package name + * @param typeQualifiedName + * the given type qualified name + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource + * @return the first type found following this project's classpath with the + * given package name and type qualified name or null + * if none is found * @see IType#getTypeQualifiedName(char) - + * * @since 2.0 */ -// IType findType(String packageName, String typeQualifiedName) throws JavaModelException; - + // IType findType(String packageName, String typeQualifiedName) throws + // JavaModelException; /** - * Returns all of the existing package fragment roots that exist - * on the classpath, in the order they are defined by the classpath. - * - * @return all of the existing package fragment roots that exist - * on the classpath - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource + * Returns all of the existing package fragment roots that exist on the + * classpath, in the order they are defined by the classpath. + * + * @return all of the existing package fragment roots that exist on the + * classpath + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource */ - IPackageFragmentRoot[] getAllPackageFragmentRoots() throws JavaModelException; + IPackageFragmentRoot[] getAllPackageFragmentRoots() + throws JavaModelException; /** - * Returns an array of non-Java resources directly contained in this project. - * It does not transitively answer non-Java resources contained in folders; - * these would have to be explicitly iterated over. + * Returns an array of non-Java resources directly contained in this + * project. It does not transitively answer non-Java resources contained in + * folders; these would have to be explicitly iterated over. *

    * Non-Java resources includes other files and folders located in the * project not accounted for by any of it source or binary package fragment - * roots. If the project is a source folder itself, resources excluded from the - * corresponding source classpath entry by one or more exclusion patterns - * are considered non-Java resources and will appear in the result + * roots. If the project is a source folder itself, resources excluded from + * the corresponding source classpath entry by one or more exclusion + * patterns are considered non-Java resources and will appear in the result * (possibly in a folder) *

    * * @return an array of non-Java resources directly contained in this project - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource */ -// Object[] getNonJavaResources() throws JavaModelException; - + // Object[] getNonJavaResources() throws JavaModelException; /** - * Helper method for returning one option value only. Equivalent to (String)this.getOptions(inheritJavaCoreOptions).get(optionName) - * Note that it may answer null if this option does not exist, or if there is no custom value for it. + * Helper method for returning one option value only. Equivalent to + * (String)this.getOptions(inheritJavaCoreOptions).get(optionName) + * Note that it may answer null if this option does not + * exist, or if there is no custom value for it. *

    - * For a complete description of the configurable options, see JavaCore#getDefaultOptions. + * For a complete description of the configurable options, see + * JavaCore#getDefaultOptions. *

    * - * @param optionName the name of an option - * @param inheritJavaCoreOptions - boolean indicating whether JavaCore options should be inherited as well + * @param optionName + * the name of an option + * @param inheritJavaCoreOptions - + * boolean indicating whether JavaCore options should be + * inherited as well * @return the String value of a given option * @see JavaCore#getDefaultOptions * @since 2.1 */ - String getOption(String optionName, boolean inheritJavaCoreOptions); - + String getOption(String optionName, boolean inheritJavaCoreOptions); + /** - * Returns the table of the current custom options for this project. Projects remember their custom options, - * in other words, only the options different from the the JavaCore global options for the workspace. - * A boolean argument allows to directly merge the project options with global ones from JavaCore. + * Returns the table of the current custom options for this project. + * Projects remember their custom options, in other words, only the options + * different from the the JavaCore global options for the workspace. A + * boolean argument allows to directly merge the project options with global + * ones from JavaCore. *

    - * For a complete description of the configurable options, see JavaCore#getDefaultOptions. + * For a complete description of the configurable options, see + * JavaCore#getDefaultOptions. *

    * - * @param inheritJavaCoreOptions - boolean indicating whether JavaCore options should be inherited as well - * @return table of current settings of all options - * (key type: String; value type: String) + * @param inheritJavaCoreOptions - + * boolean indicating whether JavaCore options should be + * inherited as well + * @return table of current settings of all options (key type: + * String; value type: String) * @see JavaCore#getDefaultOptions * @since 2.1 */ - Map getOptions(boolean inheritJavaCoreOptions); + Map getOptions(boolean inheritJavaCoreOptions); /** * Returns the default output location for this project as a workspace- @@ -248,72 +273,79 @@ public interface IJavaProject extends IParent, IJavaElement, IOpenable { * specify an output location for the generated class files (and copied * resource files) corresponding to compilation units under that source * folder. This makes it possible to arrange generated class files for - * different source folders in different output folders, and not - * necessarily the default output folder. This means that the generated - * class files for the project may end up scattered across several folders, - * rather than all in the default output folder (which is more standard). + * different source folders in different output folders, and not necessarily + * the default output folder. This means that the generated class files for + * the project may end up scattered across several folders, rather than all + * in the default output folder (which is more standard). *

    * * @return the workspace-relative absolute path of the default output folder - * @exception JavaModelException if this element does not exist + * @exception JavaModelException + * if this element does not exist * @see #setOutputLocation * @see IClasspathEntry#getOutputLocation */ IPath getOutputLocation() throws JavaModelException; /** - * Returns a package fragment root for the JAR at the specified file system path. - * This is a handle-only method. The underlying java.io.File - * may or may not exist. No resource is associated with this local JAR - * package fragment root. + * Returns a package fragment root for the JAR at the specified file system + * path. This is a handle-only method. The underlying + * java.io.File may or may not exist. No resource is + * associated with this local JAR package fragment root. * - * @param jarPath the jars's file system path - * @return a package fragment root for the JAR at the specified file system path + * @param jarPath + * the jars's file system path + * @return a package fragment root for the JAR at the specified file system + * path */ -// IPackageFragmentRoot getPackageFragmentRoot(String jarPath); - + // IPackageFragmentRoot getPackageFragmentRoot(String jarPath); /** - * Returns a package fragment root for the given resource, which - * must either be a folder representing the top of a package hierarchy, - * or a .jar or .zip file. - * This is a handle-only method. The underlying resource may or may not exist. - * - * @param resource the given resource - * @return a package fragment root for the given resource, which - * must either be a folder representing the top of a package hierarchy, - * or a .jar or .zip file + * Returns a package fragment root for the given resource, which must either + * be a folder representing the top of a package hierarchy, or a + * .jar or .zip file. This is a handle-only + * method. The underlying resource may or may not exist. + * + * @param resource + * the given resource + * @return a package fragment root for the given resource, which must either + * be a folder representing the top of a package hierarchy, or a + * .jar or .zip file */ IPackageFragmentRoot getPackageFragmentRoot(IResource resource); /** - * Returns all of the package fragment roots contained in this - * project, identified on this project's resolved classpath. The result - * does not include package fragment roots in other projects referenced - * on this project's classpath. - * - *

    NOTE: This is equivalent to getChildren(). - * - * @return all of the package fragment roots contained in this - * project, identified on this project's resolved classpath - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource + * Returns all of the package fragment roots contained in this project, + * identified on this project's resolved classpath. The result does not + * include package fragment roots in other projects referenced on this + * project's classpath. + * + *

    + * NOTE: This is equivalent to getChildren(). + * + * @return all of the package fragment roots contained in this project, + * identified on this project's resolved classpath + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource */ IPackageFragmentRoot[] getPackageFragmentRoots() throws JavaModelException; /** - * Returns the existing package fragment roots identified by the given entry. - * Note that a classpath entry that refers to another project may - * have more than one root (if that project has more than on root - * containing source), and classpath entries within the current - * project identify a single root. + * Returns the existing package fragment roots identified by the given + * entry. Note that a classpath entry that refers to another project may + * have more than one root (if that project has more than on root containing + * source), and classpath entries within the current project identify a + * single root. *

    * If the classpath entry denotes a variable, it will be resolved and return * the roots of the target entry (empty if not resolvable). *

    - * If the classpath entry denotes a container, it will be resolved and return - * the roots corresponding to the set of container entries (empty if not resolvable). + * If the classpath entry denotes a container, it will be resolved and + * return the roots corresponding to the set of container entries (empty if + * not resolvable). * - * @param entry the given entry + * @param entry + * the given entry * @return the existing package fragment roots identified by the given entry * @see IClasspathContainer * @deprecated Use IJavaProject#findPackageFragmentRoots instead @@ -321,44 +353,52 @@ public interface IJavaProject extends IParent, IJavaElement, IOpenable { IPackageFragmentRoot[] getPackageFragmentRoots(IClasspathEntry entry); /** - * Returns all package fragments in all package fragment roots contained - * in this project. This is a convenience method. - * + * Returns all package fragments in all package fragment roots contained in + * this project. This is a convenience method. + * * Note that the package fragment roots corresponds to the resolved * classpath of the project. - * - * @return all package fragments in all package fragment roots contained - * in this project - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource + * + * @return all package fragments in all package fragment roots contained in + * this project + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource */ IPackageFragment[] getPackageFragments() throws JavaModelException; /** - * Returns the IProject on which this IJavaProject - * was created. This is handle-only method. + * Returns the IProject on which this + * IJavaProject was created. This is handle-only method. * - * @return the IProject on which this IJavaProject - * was created + * @return the IProject on which this + * IJavaProject was created */ IProject getProject(); /** - * Returns the raw classpath for the project, as a list of classpath entries. This corresponds to the exact set - * of entries which were assigned using setRawClasspath, in particular such a classpath may contain - * classpath variable entries. Classpath variable entries can be resolved individually (see JavaCore#getClasspathVariable), - * or the full classpath can be resolved at once using the helper method getResolvedClasspath. + * Returns the raw classpath for the project, as a list of classpath + * entries. This corresponds to the exact set of entries which were assigned + * using setRawClasspath, in particular such a classpath may + * contain classpath variable entries. Classpath variable entries can be + * resolved individually (see JavaCore#getClasspathVariable), + * or the full classpath can be resolved at once using the helper method + * getResolvedClasspath. *

    - * A classpath variable provides an indirection level for better sharing a classpath. As an example, it allows - * a classpath to no longer refer directly to external JARs located in some user specific location. The classpath - * can simply refer to some variables defining the proper locations of these external JARs. - *

    - * Note that in case the project isn't yet opened, the classpath will directly be read from the associated .classpath file. + * A classpath variable provides an indirection level for better sharing a + * classpath. As an example, it allows a classpath to no longer refer + * directly to external JARs located in some user specific location. The + * classpath can simply refer to some variables defining the proper + * locations of these external JARs. + *

    + * Note that in case the project isn't yet opened, the classpath will + * directly be read from the associated .classpath file. *

    * * @return the raw classpath for the project, as a list of classpath entries - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource * @see IClasspathEntry */ IClasspathEntry[] getRawClasspath() throws JavaModelException; @@ -368,20 +408,21 @@ public interface IJavaProject extends IParent, IJavaElement, IOpenable { * project. A project is required if it is in its classpath. *

    * The project names are returned in the order they appear on the classpath. - * + * * @return the names of the projects that are directly required by this - * project in classpath order - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource + * project in classpath order + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource */ String[] getRequiredProjectNames() throws JavaModelException; /** * This is a helper method returning the resolved classpath for the project - * as a list of simple (non-variable, non-container) classpath entries. - * All classpath variable and classpath container entries in the project's - * raw classpath will be replaced by the simple classpath entries they - * resolve to. + * as a list of simple (non-variable, non-container) classpath entries. All + * classpath variable and classpath container entries in the project's raw + * classpath will be replaced by the simple classpath entries they resolve + * to. *

    * The resulting resolved classpath is accurate for the given point in time. * If the project's raw classpath is later modified, or if classpath @@ -389,122 +430,145 @@ public interface IJavaProject extends IParent, IJavaElement, IOpenable { * Because of this, hanging on resolved classpath is not recommended. *

    * - * @param ignoreUnresolvedEntry indicates how to handle unresolvable - * variables and containers; true indicates that missing - * variables and unresolvable classpath containers should be silently - * ignored, and that the resulting list should consist only of the - * entries that could be successfully resolved; false indicates - * that a JavaModelException should be thrown for the first - * unresolved variable or container - * @return the resolved classpath for the project as a list of simple - * classpath entries, where all classpath variable and container entries - * have been resolved and substituted with their final target entries - * @exception JavaModelException in one of the corresponding situation: - *
      - *
    • this element does not exist
    • - *
    • an exception occurs while accessing its corresponding resource
    • - *
    • a classpath variable or classpath container was not resolvable - * and ignoreUnresolvedEntry is false.
    • - *
    + * @param ignoreUnresolvedEntry + * indicates how to handle unresolvable variables and containers; + * true indicates that missing variables and + * unresolvable classpath containers should be silently ignored, + * and that the resulting list should consist only of the entries + * that could be successfully resolved; false + * indicates that a JavaModelException should be + * thrown for the first unresolved variable or container + * @return the resolved classpath for the project as a list of simple + * classpath entries, where all classpath variable and container + * entries have been resolved and substituted with their final + * target entries + * @exception JavaModelException + * in one of the corresponding situation: + *
      + *
    • this element does not exist
    • + *
    • an exception occurs while accessing its corresponding + * resource
    • + *
    • a classpath variable or classpath container was not + * resolvable and ignoreUnresolvedEntry is + * false.
    • + *
    * @see IClasspathEntry */ IClasspathEntry[] getResolvedClasspath(boolean ignoreUnresolvedEntry) - throws JavaModelException; + throws JavaModelException; /** - * Returns whether this project has been built at least once and thus whether it has a build state. - * @return true if this project has been built at least once, false otherwise + * Returns whether this project has been built at least once and thus + * whether it has a build state. + * + * @return true if this project has been built at least once, false + * otherwise */ boolean hasBuildState(); /** - * Returns whether setting this project's classpath to the given classpath entries - * would result in a cycle. - * - * If the set of entries contains some variables, those are resolved in order to determine - * cycles. - * - * @param entries the given classpath entries - * @return true if the given classpath entries would result in a cycle, false otherwise + * Returns whether setting this project's classpath to the given classpath + * entries would result in a cycle. + * + * If the set of entries contains some variables, those are resolved in + * order to determine cycles. + * + * @param entries + * the given classpath entries + * @return true if the given classpath entries would result in a cycle, + * false otherwise */ boolean hasClasspathCycle(IClasspathEntry[] entries); + /** - * Returns whether the given element is on the classpath of this project, + * Returns whether the given element is on the classpath of this project, * that is, referenced from a classpath entry and not explicitly excluded - * using an exclusion pattern. + * using an exclusion pattern. * - * @param element the given element + * @param element + * the given element * @return true if the given element is on the classpath of - * this project, false otherwise + * this project, false otherwise * @see IClasspathEntry#getExclusionPatterns * @since 2.0 */ -// boolean isOnClasspath(IJavaElement element); + // boolean isOnClasspath(IJavaElement element); /** * Returns whether the given resource is on the classpath of this project, * that is, referenced from a classpath entry and not explicitly excluded * using an exclusion pattern. * - * @param element the given element + * @param element + * the given element * @return true if the given resource is on the classpath of - * this project, false otherwise + * this project, false otherwise * @see IClasspathEntry#getExclusionPatterns * @since 2.1 */ -// boolean isOnClasspath(IResource resource); - + // boolean isOnClasspath(IResource resource); /** * Creates a new evaluation context. + * * @return a new evaluation context. */ -// IEvaluationContext newEvaluationContext(); - + // IEvaluationContext newEvaluationContext(); /** - * Creates and returns a type hierarchy for all types in the given - * region, considering subtypes within that region. - * - * @param monitor the given progress monitor - * @param region the given region - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource - * @exception IllegalArgumentException if region is null - * @return a type hierarchy for all types in the given - * region, considering subtypes within that region + * Creates and returns a type hierarchy for all types in the given region, + * considering subtypes within that region. + * + * @param monitor + * the given progress monitor + * @param region + * the given region + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource + * @exception IllegalArgumentException + * if region is null + * @return a type hierarchy for all types in the given region, considering + * subtypes within that region */ -// ITypeHierarchy newTypeHierarchy(IRegion region, IProgressMonitor monitor) -// throws JavaModelException; - + // ITypeHierarchy newTypeHierarchy(IRegion region, IProgressMonitor monitor) + // throws JavaModelException; /** * Creates and returns a type hierarchy for the given type considering * subtypes in the specified region. * - * @param monitor the given monitor - * @param region the given region - * @param type the given type + * @param monitor + * the given monitor + * @param region + * the given region + * @param type + * the given type + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource - * - * @exception IllegalArgumentException if type or region is null - * @return a type hierarchy for the given type considering - * subtypes in the specified region + * @exception IllegalArgumentException + * if type or region is null + * @return a type hierarchy for the given type considering subtypes in the + * specified region */ -// ITypeHierarchy newTypeHierarchy( -// IType type, -// IRegion region, -// IProgressMonitor monitor) -// throws JavaModelException; - + // ITypeHierarchy newTypeHierarchy( + // IType type, + // IRegion region, + // IProgressMonitor monitor) + // throws JavaModelException; /** - * Sets the project custom options. All and only the options explicitly included in the given table - * are remembered; all previous option settings are forgotten, including ones not explicitly - * mentioned. + * Sets the project custom options. All and only the options explicitly + * included in the given table are remembered; all previous option settings + * are forgotten, including ones not explicitly mentioned. *

    - * For a complete description of the configurable options, see JavaCore#getDefaultOptions. + * For a complete description of the configurable options, see + * JavaCore#getDefaultOptions. *

    * - * @param newOptions the new options (key type: String; value type: String), - * or null to flush all custom options (clients will automatically get the global JavaCore options). + * @param newOptions + * the new options (key type: String; value type: + * String), or null to flush all + * custom options (clients will automatically get the global + * JavaCore options). * @see JavaCore#getDefaultOptions * @since 2.1 */ @@ -525,62 +589,80 @@ public interface IJavaProject extends IParent, IJavaElement, IOpenable { * rather than all in the default output folder (which is more standard). *

    * - * @param path the workspace-relative absolute path of the default output - * folder - * @param monitor the progress monitor - * - * @exception JavaModelException if the classpath could not be set. Reasons include: - *
      - *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    • The path refers to a location not contained in this project (PATH_OUTSIDE_PROJECT) - *
    • The path is not an absolute path (RELATIVE_PATH) - *
    • The path is nested inside a package fragment root of this project (INVALID_PATH) - *
    • The output location is being modified during resource change event notification (CORE_EXCEPTION) - *
    + * @param path + * the workspace-relative absolute path of the default output + * folder + * @param monitor + * the progress monitor + * + * @exception JavaModelException + * if the classpath could not be set. Reasons include: + *
      + *
    • This Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
    • + *
    • The path refers to a location not contained in this + * project (PATH_OUTSIDE_PROJECT) + *
    • The path is not an absolute path (RELATIVE_PATH) + *
    • The path is nested inside a package fragment root of + * this project (INVALID_PATH) + *
    • The output location is being modified during resource + * change event notification (CORE_EXCEPTION) + *
    * @see #getOutputLocation - * @see IClasspathEntry#getOutputLocation + * @see IClasspathEntry#getOutputLocation */ void setOutputLocation(IPath path, IProgressMonitor monitor) - throws JavaModelException; + throws JavaModelException; /** - * Sets the classpath of this project using a list of classpath entries. In particular such a classpath may contain - * classpath variable entries. Classpath variable entries can be resolved individually (see JavaCore#getClasspathVariable), - * or the full classpath can be resolved at once using the helper method getResolvedClasspath. + * Sets the classpath of this project using a list of classpath entries. In + * particular such a classpath may contain classpath variable entries. + * Classpath variable entries can be resolved individually (see + * JavaCore#getClasspathVariable), or the full classpath can + * be resolved at once using the helper method + * getResolvedClasspath. *

    - * A classpath variable provides an indirection level for better sharing a classpath. As an example, it allows - * a classpath to no longer refer directly to external JARs located in some user specific location. The classpath - * can simply refer to some variables defining the proper locations of these external JARs. + * A classpath variable provides an indirection level for better sharing a + * classpath. As an example, it allows a classpath to no longer refer + * directly to external JARs located in some user specific location. The + * classpath can simply refer to some variables defining the proper + * locations of these external JARs. *

    - * Setting the classpath to null specifies a default classpath - * (the project root). Setting the classpath to an empty array specifies an - * empty classpath. + * Setting the classpath to null specifies a default + * classpath (the project root). Setting the classpath to an empty array + * specifies an empty classpath. *

    - * If a cycle is detected while setting this classpath, an error marker will be added - * to the project closing the cycle. - * To avoid this problem, use hasClasspathCycle(IClasspathEntry[] entries) - * before setting the classpath. - * - * @param entries a list of classpath entries - * @param monitor the given progress monitor - * @exception JavaModelException if the classpath could not be set. Reasons include: - *

      - *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    • The classpath is being modified during resource change event notification (CORE_EXCEPTION) - *
    • The classpath failed the validation check as defined by JavaConventions#validateClasspath - *
    + * If a cycle is detected while setting this classpath, an error marker will + * be added to the project closing the cycle. To avoid this problem, use + * hasClasspathCycle(IClasspathEntry[] entries) before + * setting the classpath. + * + * @param entries + * a list of classpath entries + * @param monitor + * the given progress monitor + * @exception JavaModelException + * if the classpath could not be set. Reasons include: + *
      + *
    • This Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
    • + *
    • The classpath is being modified during resource + * change event notification (CORE_EXCEPTION) + *
    • The classpath failed the validation check as defined + * by JavaConventions#validateClasspath + *
    * @see IClasspathEntry */ void setRawClasspath(IClasspathEntry[] entries, IProgressMonitor monitor) - throws JavaModelException; - + throws JavaModelException; + /** * Sets the both the classpath of this project and its default output * location at once. The classpath is defined using a list of classpath * entries. In particular, such a classpath may contain classpath variable * entries. Classpath variable entries can be resolved individually (see - * JavaCore#getClasspathVariable), or the full classpath can be - * resolved at once using the helper method + * JavaCore#getClasspathVariable), or the full classpath can + * be resolved at once using the helper method * getResolvedClasspath. *

    * A classpath variable provides an indirection level for better sharing a @@ -590,35 +672,45 @@ public interface IJavaProject extends IParent, IJavaElement, IOpenable { * locations of these external JARs. *

    *

    - * Setting the classpath to null specifies a default classpath - * (the project root). Setting the classpath to an empty array specifies an - * empty classpath. + * Setting the classpath to null specifies a default + * classpath (the project root). Setting the classpath to an empty array + * specifies an empty classpath. *

    *

    * If a cycle is detected while setting this classpath, an error marker will * be added to the project closing the cycle. To avoid this problem, use - * hasClasspathCycle(IClasspathEntry[] entries) before setting - * the classpath. + * hasClasspathCycle(IClasspathEntry[] entries) before + * setting the classpath. *

    * - * @param entries a list of classpath entries - * @param monitor the progress monitor - * @param outputLocation the default output location - * @exception JavaModelException if the classpath could not be set. Reasons - * include: - *
      - *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    • Two or more entries specify source roots with the same or overlapping paths (NAME_COLLISION) - *
    • A entry of kind CPE_PROJECT refers to this project (INVALID_PATH) - *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    • The output location path refers to a location not contained in this project (PATH_OUTSIDE_PROJECT) - *
    • The output location path is not an absolute path (RELATIVE_PATH) - *
    • The output location path is nested inside a package fragment root of this project (INVALID_PATH) - *
    • The classpath is being modified during resource change event notification (CORE_EXCEPTION) - *
    + * @param entries + * a list of classpath entries + * @param monitor + * the progress monitor + * @param outputLocation + * the default output location + * @exception JavaModelException + * if the classpath could not be set. Reasons include: + *
      + *
    • This Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
    • + *
    • Two or more entries specify source roots with the + * same or overlapping paths (NAME_COLLISION) + *
    • A entry of kind CPE_PROJECT refers to + * this project (INVALID_PATH) + *
    • This Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
    • + *
    • The output location path refers to a location not + * contained in this project (PATH_OUTSIDE_PROJECT) + *
    • The output location path is not an absolute path (RELATIVE_PATH) + *
    • The output location path is nested inside a package + * fragment root of this project (INVALID_PATH) + *
    • The classpath is being modified during resource + * change event notification (CORE_EXCEPTION) + *
    * @see IClasspathEntry * @since 2.0 */ - void setRawClasspath(IClasspathEntry[] entries, IPath outputLocation, IProgressMonitor monitor) - throws JavaModelException; + void setRawClasspath(IClasspathEntry[] entries, IPath outputLocation, + IProgressMonitor monitor) throws JavaModelException; } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ILocalVariable.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ILocalVariable.java index 1c9f549..c652b41 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ILocalVariable.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ILocalVariable.java @@ -12,16 +12,20 @@ package net.sourceforge.phpdt.core; /** * Represents a local variable declared in a method or an initializer. - * ILocalVariable are pseudo-elements created as the result of a ICodeAssist.codeSelect(...) - * operation. They are not part of the Java model (exists() returns whether the parent exists rather than - * whether the local variable exists in the parent) and they are not included in the children of an IMethod - * or an IInitializer. + * ILocalVariable are pseudo-elements created as the result of a + * ICodeAssist.codeSelect(...) operation. They are not part of + * the Java model (exists() returns whether the parent exists + * rather than whether the local variable exists in the parent) and they are not + * included in the children of an IMethod or an + * IInitializer. + *

    + * In particular such a pseudo-element should not be used as a handle. For + * example its name range won't be updated if the underlying source changes. + *

    *

    - * In particular such a pseudo-element should not be used as a handle. For example its name range won't be updated - * if the underlying source changes. - *

    * This interface is not intended to be implemented by clients. *

    + * * @since 3.0 */ public interface ILocalVariable extends IJavaElement, ISourceReference { @@ -32,22 +36,22 @@ public interface ILocalVariable extends IJavaElement, ISourceReference { * @return the name of this local variable. */ String getElementName(); - + /** * Returns the source range of this local variable's name. - * + * * @return the source range of this local variable's name */ ISourceRange getNameRange(); - + /** * Returns the type signature of this local variable. *

    - * The type signature may be either unresolved (for source types) - * or resolved (for binary types), and either basic (for basic types) - * or rich (for parameterized types). See {@link Signature} for details. + * The type signature may be either unresolved (for source types) or + * resolved (for binary types), and either basic (for basic types) or rich + * (for parameterized types). See {@link Signature} for details. *

    - * + * * @return the type signature of this local variable. * @see Signature */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IMember.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IMember.java index f1d5d47..034a789 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IMember.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IMember.java @@ -10,91 +10,105 @@ *******************************************************************************/ package net.sourceforge.phpdt.core; - /** - * Common protocol for Java elements that can be members of types. - * This set consists of IType, IMethod, + * Common protocol for Java elements that can be members of types. This set + * consists of IType, IMethod, * IField, and IInitializer. *

    * This interface is not intended to be implemented by clients. *

    */ -public interface IMember extends IJavaElement , ISourceReference, ISourceManipulation, IParent { -/** - * Returns the class file in which this member is declared, or null - * if this member is not declared in a class file (for example, a source type). - * This is a handle-only method. - * - * @return the class file in which this member is declared, or null - * if this member is not declared in a class file (for example, a source type) - */ -//IClassFile getClassFile(); -/** - * Returns the compilation unit in which this member is declared, or null - * if this member is not declared in a compilation unit (for example, a binary type). - * This is a handle-only method. - * - * @return the compilation unit in which this member is declared, or null - * if this member is not declared in a compilation unit (for example, a binary type) - */ -ICompilationUnit getCompilationUnit(); -/** - * Returns the type in which this member is declared, or null - * if this member is not declared in a type (for example, a top-level type). - * This is a handle-only method. - * - * @return the type in which this member is declared, or null - * if this member is not declared in a type (for example, a top-level type) - */ - IType getDeclaringType(); -/** - * Returns the modifier flags for this member. The flags can be examined using class - * Flags. - *

    - * Note that only flags as indicated in the source are returned. Thus if an interface - * defines a method void myMethod(); the flags don't include the - * 'public' flag. - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. - * @return the modifier flags for this member - * @see Flags - */ -int getFlags() throws JavaModelException; -/** - * Returns the source range of this member's simple name, - * or null if this member does not have a name - * (for example, an initializer), or if this member does not have - * associated source code (for example, a binary type). - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. - * @return the source range of this member's simple name, - * or null if this member does not have a name - * (for example, an initializer), or if this member does not have - * associated source code (for example, a binary type) - */ -ISourceRange getNameRange() throws JavaModelException; -/** - * Returns the local or anonymous type declared in this source member with the given simple name and/or - * with the specified position relative to the order they are defined in the source. - * The name is empty if it is an anonymous type. - * Numbering starts at 1 (thus the first occurrence is occurrence 1, not occurrence 0). - * This is a handle-only method. The type may or may not exist. - * Throws a RuntimeException if this member is not a source member. - * - * @param name the given simple name - * @param occurrenceCount the specified position - * @return the type with the given name and/or with the specified position relative to the order they are defined in the source - * @since 3.0 - */ -IType getType(String name, int occurrenceCount); -/** - * Returns whether this member is from a class file. - * This is a handle-only method. - * - * @return true if from a class file, and false if - * from a compilation unit - */ -boolean isBinary(); +public interface IMember extends IJavaElement, ISourceReference, + ISourceManipulation, IParent { + /** + * Returns the class file in which this member is declared, or + * null if this member is not declared in a class file (for + * example, a source type). This is a handle-only method. + * + * @return the class file in which this member is declared, or + * null if this member is not declared in a class + * file (for example, a source type) + */ + // IClassFile getClassFile(); + /** + * Returns the compilation unit in which this member is declared, or + * null if this member is not declared in a compilation unit + * (for example, a binary type). This is a handle-only method. + * + * @return the compilation unit in which this member is declared, or + * null if this member is not declared in a + * compilation unit (for example, a binary type) + */ + ICompilationUnit getCompilationUnit(); + + /** + * Returns the type in which this member is declared, or null + * if this member is not declared in a type (for example, a top-level type). + * This is a handle-only method. + * + * @return the type in which this member is declared, or null + * if this member is not declared in a type (for example, a + * top-level type) + */ + IType getDeclaringType(); + + /** + * Returns the modifier flags for this member. The flags can be examined + * using class Flags. + *

    + * Note that only flags as indicated in the source are returned. Thus if an + * interface defines a method void myMethod(); the flags + * don't include the 'public' flag. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. + * @return the modifier flags for this member + * @see Flags + */ + int getFlags() throws JavaModelException; + + /** + * Returns the source range of this member's simple name, or + * null if this member does not have a name (for example, an + * initializer), or if this member does not have associated source code (for + * example, a binary type). + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. + * @return the source range of this member's simple name, or + * null if this member does not have a name (for + * example, an initializer), or if this member does not have + * associated source code (for example, a binary type) + */ + ISourceRange getNameRange() throws JavaModelException; + + /** + * Returns the local or anonymous type declared in this source member with + * the given simple name and/or with the specified position relative to the + * order they are defined in the source. The name is empty if it is an + * anonymous type. Numbering starts at 1 (thus the first occurrence is + * occurrence 1, not occurrence 0). This is a handle-only method. The type + * may or may not exist. Throws a RuntimeException if this + * member is not a source member. + * + * @param name + * the given simple name + * @param occurrenceCount + * the specified position + * @return the type with the given name and/or with the specified position + * relative to the order they are defined in the source + * @since 3.0 + */ + IType getType(String name, int occurrenceCount); + + /** + * Returns whether this member is from a class file. This is a handle-only + * method. + * + * @return true if from a class file, and false + * if from a compilation unit + */ + boolean isBinary(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IMethod.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IMethod.java index 651789a..e4d5800 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IMethod.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IMethod.java @@ -17,129 +17,158 @@ package net.sourceforge.phpdt.core; *

    */ public interface IMethod extends IMember { -/** - * Returns the simple name of this method. - * For a constructor, this returns the simple name of the declaring type. - * Note: This holds whether the constructor appears in a source or binary type - * (even though class files internally define constructor names to be "<init>"). - * For the class initialization methods in binary types, this returns - * the special name "<clinit>". - * This is a handle-only method. - */ -String getElementName(); -/** - * Returns the type signatures of the exceptions this method throws, - * in the order declared in the source. Returns an empty array - * if this method throws no exceptions. - * - *

    For example, a source method declaring "throws IOException", - * would return the array {"QIOException;"}. - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. - * @return the type signatures of the exceptions this method throws, - * in the order declared in the source, an empty array if this method throws no exceptions - * @see Signature - */ -String[] getExceptionTypes() throws JavaModelException; -/** - * Returns the number of parameters of this method. - * This is a handle-only method. - * - * @return the number of parameters of this method - */ -int getNumberOfParameters(); -/** - * Returns the names of parameters in this method. - * For binary types, these names are invented as "arg"+i, where i starts at 1 - * (even if source is associated with the binary). - * Returns an empty array if this method has no parameters. - * - *

    For example, a method declared as public void foo(String text, int length) - * would return the array {"text","length"}. - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. - * @return the names of parameters in this method, an empty array if this method has no parameters - */ -String[] getParameterNames() throws JavaModelException; -/** - * Returns the type signatures for the parameters of this method. - * Returns an empty array if this method has no parameters. - * This is a handle-only method. - * - *

    For example, a source method declared as public void foo(String text, int length) - * would return the array {"QString;","I"}. - * - * @return the type signatures for the parameters of this method, an empty array if this method has no parameters - * @see Signature - */ -String[] getParameterTypes(); -/** - * Returns the type signature of the return value of this method. - * For constructors, this returns the signature for void. - * - *

    For example, a source method declared as public String getName() - * would return "QString;". - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. - * @return the type signature of the return value of this method, void for constructors - * @see Signature - */ -String getReturnType() throws JavaModelException; -/** - * Returns the signature of the method. This includes the signatures for the parameter - * types and return type, but does not include the method name or exception types. - * - *

    For example, a source method declared as public void foo(String text, int length) - * would return "(QString;I)V". - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. - * - * @see Signature - */ -String getSignature() throws JavaModelException; -/** - * Returns whether this method is a constructor. - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. - * - * @return true if this method is a constructor, false otherwise - */ -boolean isConstructor() throws JavaModelException; -/** - * Returns whether this method is a main method. - * It is a main method if: - *

      - *
    • its name is equal to "main"
    • - *
    • its return type is void
    • - *
    • it is static and public
    • - *
    • it defines one parameter whose type's simple name is String[]
    • - *
    - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. - * @since 2.0 - * @return true if this method is a main method, false otherwise - */ -boolean isMainMethod() throws JavaModelException; -/** - * Returns whether this method is similar to the given method. - * Two methods are similar if: - *
      - *
    • their element names are equal
    • - *
    • they have the same number of parameters
    • - *
    • the simple names of their parameter types are equal
    • - *
    - * This is a handle-only method. - * - * @param method the given method - * @return true if this method is similar to the given method. - * @see Signature#getSimpleName - * @since 2.0 - */ -boolean isSimilar(IMethod method); + /** + * Returns the simple name of this method. For a constructor, this returns + * the simple name of the declaring type. Note: This holds whether the + * constructor appears in a source or binary type (even though class files + * internally define constructor names to be "<init>"). + * For the class initialization methods in binary types, this returns the + * special name "<clinit>". This is a handle-only + * method. + */ + String getElementName(); + + /** + * Returns the type signatures of the exceptions this method throws, in the + * order declared in the source. Returns an empty array if this method + * throws no exceptions. + * + *

    + * For example, a source method declaring "throws IOException", + * would return the array {"QIOException;"}. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. + * @return the type signatures of the exceptions this method throws, in the + * order declared in the source, an empty array if this method + * throws no exceptions + * @see Signature + */ + String[] getExceptionTypes() throws JavaModelException; + + /** + * Returns the number of parameters of this method. This is a handle-only + * method. + * + * @return the number of parameters of this method + */ + int getNumberOfParameters(); + + /** + * Returns the names of parameters in this method. For binary types, these + * names are invented as "arg"+i, where i starts at 1 (even if source is + * associated with the binary). Returns an empty array if this method has no + * parameters. + * + *

    + * For example, a method declared as + * public void foo(String text, int length) would return the + * array {"text","length"}. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. + * @return the names of parameters in this method, an empty array if this + * method has no parameters + */ + String[] getParameterNames() throws JavaModelException; + + /** + * Returns the type signatures for the parameters of this method. Returns an + * empty array if this method has no parameters. This is a handle-only + * method. + * + *

    + * For example, a source method declared as + * public void foo(String text, int length) would return the + * array {"QString;","I"}. + * + * @return the type signatures for the parameters of this method, an empty + * array if this method has no parameters + * @see Signature + */ + String[] getParameterTypes(); + + /** + * Returns the type signature of the return value of this method. For + * constructors, this returns the signature for void. + * + *

    + * For example, a source method declared as + * public String getName() would return + * "QString;". + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. + * @return the type signature of the return value of this method, void for + * constructors + * @see Signature + */ + String getReturnType() throws JavaModelException; + + /** + * Returns the signature of the method. This includes the signatures for the + * parameter types and return type, but does not include the method name or + * exception types. + * + *

    + * For example, a source method declared as + * public void foo(String text, int length) would return + * "(QString;I)V". + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. + * + * @see Signature + */ + String getSignature() throws JavaModelException; + + /** + * Returns whether this method is a constructor. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. + * + * @return true if this method is a constructor, false otherwise + */ + boolean isConstructor() throws JavaModelException; + + /** + * Returns whether this method is a main method. It is a main method if: + *

      + *
    • its name is equal to "main"
    • + *
    • its return type is void
    • + *
    • it is static and public
    • + *
    • it defines one parameter whose type's simple name is String[]
    • + *
    + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. + * @since 2.0 + * @return true if this method is a main method, false otherwise + */ + boolean isMainMethod() throws JavaModelException; + + /** + * Returns whether this method is similar to the given method. Two methods + * are similar if: + *
      + *
    • their element names are equal
    • + *
    • they have the same number of parameters
    • + *
    • the simple names of their parameter types are equal
    • + *
    + * This is a handle-only method. + * + * @param method + * the given method + * @return true if this method is similar to the given method. + * @see Signature#getSimpleName + * @since 2.0 + */ + boolean isSimilar(IMethod method); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IOpenable.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IOpenable.java index 9424f3a..aead99c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IOpenable.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IOpenable.java @@ -12,31 +12,30 @@ package net.sourceforge.phpdt.core; import org.eclipse.core.runtime.IProgressMonitor; - /** - * Common protocol for Java elements that must be opened before they can be + * Common protocol for Java elements that must be opened before they can be * navigated or modified. Opening a textual element (such as a compilation unit) - * involves opening a buffer on its contents. While open, any changes to the buffer - * can be reflected in the element's structure; - * see isConsistent and makeConsistent(IProgressMonitor). + * involves opening a buffer on its contents. While open, any changes to the + * buffer can be reflected in the element's structure; see + * isConsistent and makeConsistent(IProgressMonitor). *

    - * To reduce complexity in clients, elements are automatically opened - * by the Java model as element properties are accessed. The Java model maintains - * an LRU cache of open elements, and automatically closes elements as they - * are swapped out of the cache to make room for other elements. Elements with + * To reduce complexity in clients, elements are automatically opened by the + * Java model as element properties are accessed. The Java model maintains an + * LRU cache of open elements, and automatically closes elements as they are + * swapped out of the cache to make room for other elements. Elements with * unsaved changes are never removed from the cache, and thus, if the client - * maintains many open elements with unsaved - * changes, the LRU cache can grow in size (in this case the cache is not - * bounded). However, as elements are saved, the cache will shrink back to its - * original bounded size. + * maintains many open elements with unsaved changes, the LRU cache can grow in + * size (in this case the cache is not bounded). However, as elements are saved, + * the cache will shrink back to its original bounded size. *

    *

    - * To open an element, all openable parent elements must be open. - * The Java model automatically opens parent elements, as it automatically opens elements. - * Opening an element may provide access to direct children and other descendants, - * but does not automatically open any descendents which are themselves IOpenable. - * For example, opening a compilation unit provides access to all its constituent elements, - * but opening a package fragment does not open all compilation units in the package fragment. + * To open an element, all openable parent elements must be open. The Java model + * automatically opens parent elements, as it automatically opens elements. + * Opening an element may provide access to direct children and other + * descendants, but does not automatically open any descendents which are + * themselves IOpenable. For example, opening a compilation unit + * provides access to all its constituent elements, but opening a package + * fragment does not open all compilation units in the package fragment. *

    *

    * This interface is not intended to be implemented by clients. @@ -44,143 +43,176 @@ import org.eclipse.core.runtime.IProgressMonitor; */ public interface IOpenable { -/** - * Closes this element and its buffer (if any). - * Closing an element which is not open has no effect. - * - *

    Note: although close is exposed in the API, clients are - * not expected to open and close elements - the Java model does this automatically - * as elements are accessed. - * - * @exception JavaModelException if an error occurs closing this element - */ -public void close() throws JavaModelException; -/** - * Returns the buffer opened for this element, or null - * if this element does not have a buffer. - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. - * @return the buffer opened for this element, or null - * if this element does not have a buffer - */ -public IBuffer getBuffer() throws JavaModelException; -/** - * Returns true if this element is open and: - *

      - *
    • its buffer has unsaved changes, or - *
    • one of its descendants has unsaved changes, or - *
    • a working copy has been created on one of this - * element's children and has not yet destroyed - *
    - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. - * @return true if this element is open and: - *
      - *
    • its buffer has unsaved changes, or - *
    • one of its descendants has unsaved changes, or - *
    • a working copy has been created on one of this - * element's children and has not yet destroyed - *
    - */ -boolean hasUnsavedChanges() throws JavaModelException; -/** - * Returns whether the element is consistent with its underlying resource or buffer. - * The element is consistent when opened, and is consistent if the underlying resource - * or buffer has not been modified since it was last consistent. - * - *

    NOTE: Child consistency is not considered. For example, a package fragment - * responds true when it knows about all of its - * compilation units present in its underlying folder. However, one or more of - * the compilation units could be inconsistent. - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. - * @return true if the element is consistent with its underlying resource or buffer, false otherwise. - * @see IOpenable#makeConsistent - */ -boolean isConsistent() throws JavaModelException; -/** - * Returns whether this openable is open. This is a handle-only method. - * @return true if this openable is open, false otherwise - */ -boolean isOpen(); -/** - * Opens this element and all parent elements that are not already open. - * For compilation units, a buffer is opened on the contents of the underlying resource. - * - *

    Note: although open is exposed in the API, clients are - * not expected to open and close elements - the Java model does this automatically - * as elements are accessed. - * - * @param progress the given progress monitor - * @exception JavaModelException if an error occurs accessing the contents - * of its underlying resource. Reasons include: - *

      - *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    - */ -public void open(IProgressMonitor progress) throws JavaModelException; -/** - * Makes this element consistent with its underlying resource or buffer - * by updating the element's structure and properties as necessary. - * - * @param progress the given progress monitor - * @exception JavaModelException if the element is unable to access the contents - * of its underlying resource. Reasons include: - *
      - *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    - * @see IOpenable#isConsistent - */ -void makeConsistent(IProgressMonitor progress) throws JavaModelException; -/** - * Opens this element and all parent elements that are not already open. - * For compilation units, a buffer is opened on the contents of the underlying resource. - * - *

    Note: although open is exposed in the API, clients are - * not expected to open and close elements - the Java model does this automatically - * as elements are accessed. - * - * @param progress the given progress monitor - * @exception JavaModelException if an error occurs accessing the contents - * of its underlying resource. Reasons include: - *

      - *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    - */ -//public void open(IProgressMonitor progress) throws JavaModelException; -/** - * Saves any changes in this element's buffer to its underlying resource - * via a workspace resource operation. This has no effect if the element has no underlying - * buffer, or if there are no unsaved changed in the buffer. - *

    - * The force parameter controls how this method deals with - * cases where the workbench is not completely in sync with the local file system. - * If false is specified, this method will only attempt - * to overwrite a corresponding file in the local file system provided - * it is in sync with the workbench. This option ensures there is no - * unintended data loss; it is the recommended setting. - * However, if true is specified, an attempt will be made - * to write a corresponding file in the local file system, - * overwriting any existing one if need be. - * In either case, if this method succeeds, the resource will be marked - * as being local (even if it wasn't before). - *

    - * As a result of this operation, the element is consistent with its underlying - * resource or buffer. - * - * @param progress the given progress monitor - * @param force it controls how this method deals with - * cases where the workbench is not completely in sync with the local file system - * @exception JavaModelException if an error occurs accessing the contents - * of its underlying resource. Reasons include: - *

      - *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    • This Java element is read-only (READ_ONLY)
    • - *
    - */ -public void save(IProgressMonitor progress, boolean force) throws JavaModelException; + /** + * Closes this element and its buffer (if any). Closing an element which is + * not open has no effect. + * + *

    + * Note: although close is exposed in the API, clients are + * not expected to open and close elements - the Java model does this + * automatically as elements are accessed. + * + * @exception JavaModelException + * if an error occurs closing this element + */ + public void close() throws JavaModelException; + + /** + * Returns the buffer opened for this element, or null if + * this element does not have a buffer. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. + * @return the buffer opened for this element, or null if + * this element does not have a buffer + */ + public IBuffer getBuffer() throws JavaModelException; + + /** + * Returns true if this element is open and: + *

      + *
    • its buffer has unsaved changes, or + *
    • one of its descendants has unsaved changes, or + *
    • a working copy has been created on one of this element's children + * and has not yet destroyed + *
    + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. + * @return true if this element is open and: + *
      + *
    • its buffer has unsaved changes, or + *
    • one of its descendants has unsaved changes, or + *
    • a working copy has been created on one of this element's + * children and has not yet destroyed + *
    + */ + boolean hasUnsavedChanges() throws JavaModelException; + + /** + * Returns whether the element is consistent with its underlying resource or + * buffer. The element is consistent when opened, and is consistent if the + * underlying resource or buffer has not been modified since it was last + * consistent. + * + *

    + * NOTE: Child consistency is not considered. For example, a package + * fragment responds true when it knows about all of its + * compilation units present in its underlying folder. However, one or more + * of the compilation units could be inconsistent. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. + * @return true if the element is consistent with its underlying resource or + * buffer, false otherwise. + * @see IOpenable#makeConsistent + */ + boolean isConsistent() throws JavaModelException; + + /** + * Returns whether this openable is open. This is a handle-only method. + * + * @return true if this openable is open, false otherwise + */ + boolean isOpen(); + + /** + * Opens this element and all parent elements that are not already open. For + * compilation units, a buffer is opened on the contents of the underlying + * resource. + * + *

    + * Note: although open is exposed in the API, clients are not + * expected to open and close elements - the Java model does this + * automatically as elements are accessed. + * + * @param progress + * the given progress monitor + * @exception JavaModelException + * if an error occurs accessing the contents of its + * underlying resource. Reasons include: + *

      + *
    • This Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
    • + *
    + */ + public void open(IProgressMonitor progress) throws JavaModelException; + + /** + * Makes this element consistent with its underlying resource or buffer by + * updating the element's structure and properties as necessary. + * + * @param progress + * the given progress monitor + * @exception JavaModelException + * if the element is unable to access the contents of its + * underlying resource. Reasons include: + *
      + *
    • This Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
    • + *
    + * @see IOpenable#isConsistent + */ + void makeConsistent(IProgressMonitor progress) throws JavaModelException; + + /** + * Opens this element and all parent elements that are not already open. For + * compilation units, a buffer is opened on the contents of the underlying + * resource. + * + *

    + * Note: although open is exposed in the API, clients are not + * expected to open and close elements - the Java model does this + * automatically as elements are accessed. + * + * @param progress + * the given progress monitor + * @exception JavaModelException + * if an error occurs accessing the contents of its + * underlying resource. Reasons include: + *

      + *
    • This Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
    • + *
    + */ + // public void open(IProgressMonitor progress) throws JavaModelException; + /** + * Saves any changes in this element's buffer to its underlying resource via + * a workspace resource operation. This has no effect if the element has no + * underlying buffer, or if there are no unsaved changed in the buffer. + *

    + * The force parameter controls how this method deals with + * cases where the workbench is not completely in sync with the local file + * system. If false is specified, this method will only + * attempt to overwrite a corresponding file in the local file system + * provided it is in sync with the workbench. This option ensures there is + * no unintended data loss; it is the recommended setting. However, if + * true is specified, an attempt will be made to write a + * corresponding file in the local file system, overwriting any existing one + * if need be. In either case, if this method succeeds, the resource will be + * marked as being local (even if it wasn't before). + *

    + * As a result of this operation, the element is consistent with its + * underlying resource or buffer. + * + * @param progress + * the given progress monitor + * @param force + * it controls how this method deals with cases where the + * workbench is not completely in sync with the local file system + * @exception JavaModelException + * if an error occurs accessing the contents of its + * underlying resource. Reasons include: + *

      + *
    • This Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
    • + *
    • This Java element is read-only (READ_ONLY)
    • + *
    + */ + public void save(IProgressMonitor progress, boolean force) + throws JavaModelException; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IPackageDeclaration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IPackageDeclaration.java index d96737b..292a59d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IPackageDeclaration.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IPackageDeclaration.java @@ -10,7 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpdt.core; - /** * Represents a package declaration in Java compilation unit. *

    @@ -18,9 +17,9 @@ package net.sourceforge.phpdt.core; *

    */ public interface IPackageDeclaration extends IJavaElement, ISourceReference { -/** - * Returns the name of the package the statement refers to. - * This is a handle-only method. - */ -String getElementName(); + /** + * Returns the name of the package the statement refers to. This is a + * handle-only method. + */ + String getElementName(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IPackageFragment.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IPackageFragment.java index 117ee26..73bf9b8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IPackageFragment.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IPackageFragment.java @@ -13,155 +13,187 @@ package net.sourceforge.phpdt.core; import org.eclipse.core.runtime.IProgressMonitor; /** - * A package fragment is a portion of the workspace corresponding to an entire package, - * or to a portion thereof. The distinction between a package fragment and a package - * is that a package with some name is the union of all package fragments in the class path - * which have the same name. + * A package fragment is a portion of the workspace corresponding to an entire + * package, or to a portion thereof. The distinction between a package fragment + * and a package is that a package with some name is the union of all package + * fragments in the class path which have the same name. *

    - * Package fragments elements need to be opened before they can be navigated or manipulated. - * The children are of type ICompilationUnit (representing a source file) or - * IClassFile (representing a binary class file). - * The children are listed in no particular order. + * Package fragments elements need to be opened before they can be navigated or + * manipulated. The children are of type ICompilationUnit + * (representing a source file) or IClassFile (representing a + * binary class file). The children are listed in no particular order. *

    *

    * This interface is not intended to be implemented by clients. *

    */ -public interface IPackageFragment extends IParent, IJavaElement, IOpenable { -//ISourceManipulation { +public interface IPackageFragment extends IParent, IJavaElement, IOpenable { + // ISourceManipulation { - /** + /** *

    - * The name of package fragment for the default package (value: the empty + * The name of package fragment for the default package (value: the empty * string, ""). *

    - */ + */ public static final String DEFAULT_PACKAGE_NAME = ""; //$NON-NLS-1$ + /** * Returns whether this fragment contains at least one Java resource. - * @return true if this fragment contains at least one Java resource, false otherwise + * + * @return true if this fragment contains at least one Java resource, false + * otherwise */ -// boolean containsJavaResources() throws JavaModelException; + // boolean containsJavaResources() throws JavaModelException; /** - * Creates and returns a compilation unit in this package fragment - * with the specified name and contents. No verification is performed - * on the contents. - * - *

    It is possible that a compilation unit with the same name already exists in this - * package fragment. - * The value of the force parameter effects the resolution of - * such a conflict:

      - *
    • true - in this case the compilation is created with the new contents
    • - *
    • false - in this case a JavaModelException is thrown
    • - *
    - * - * @param contents the given contents - * @param force specify how to handle conflict is the same name already exists - * @param monitor the given progress monitor - * @param name the given name - * @exception JavaModelException if the element could not be created. Reasons include: + * Creates and returns a compilation unit in this package fragment with the + * specified name and contents. No verification is performed on the + * contents. + * + *

    + * It is possible that a compilation unit with the same name already exists + * in this package fragment. The value of the force parameter + * effects the resolution of such a conflict: *

      - *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    • A CoreException occurred while creating an underlying resource - *
    • The name is not a valid compilation unit name (INVALID_NAME) - *
    • The contents are null (INVALID_CONTENTS) + *
    • true - in this case the compilation is created with + * the new contents
    • + *
    • false - in this case a + * JavaModelException is thrown
    • *
    - * @return a compilation unit in this package fragment - * with the specified name and contents + * + * @param contents + * the given contents + * @param force + * specify how to handle conflict is the same name already exists + * @param monitor + * the given progress monitor + * @param name + * the given name + * @exception JavaModelException + * if the element could not be created. Reasons include: + *
      + *
    • This Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while + * creating an underlying resource + *
    • The name is not a valid compilation unit name + * (INVALID_NAME) + *
    • The contents are null + * (INVALID_CONTENTS) + *
    + * @return a compilation unit in this package fragment with the specified + * name and contents */ - ICompilationUnit createCompilationUnit(String name, String contents, boolean force, IProgressMonitor monitor) throws JavaModelException; + ICompilationUnit createCompilationUnit(String name, String contents, + boolean force, IProgressMonitor monitor) throws JavaModelException; + /** - * Returns the class file with the specified name - * in this package (for example, "Object.class"). - * The ".class" suffix is required. - * This is a handle-only method. The class file may or may not be present. - * @param name the given name + * Returns the class file with the specified name in this package (for + * example, "Object.class"). The ".class" suffix is + * required. This is a handle-only method. The class file may or may not be + * present. + * + * @param name + * the given name * @return the class file with the specified name in this package */ -// IClassFile getClassFile(String name); + // IClassFile getClassFile(String name); /** * Returns all of the class files in this package fragment. - * - *

    Note: it is possible that a package fragment contains only - * compilation units (in other words, its kind is K_SOURCE), in - * which case this method returns an empty collection. - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. + * + *

    + * Note: it is possible that a package fragment contains only compilation + * units (in other words, its kind is K_SOURCE), in which + * case this method returns an empty collection. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. * @return all of the class files in this package fragment */ -// IClassFile[] getClassFiles() throws JavaModelException; + // IClassFile[] getClassFiles() throws JavaModelException; /** - * Returns the compilation unit with the specified name - * in this package (for example, "Object.java"). - * The name has to be a valid compilation unit name. - * This is a handle-only method. The compilation unit may or may not be present. + * Returns the compilation unit with the specified name in this package (for + * example, "Object.java"). The name has to be a valid + * compilation unit name. This is a handle-only method. The compilation unit + * may or may not be present. + * * @see JavaConventions#validateCompilationUnitName - * @param name the given name + * @param name + * the given name * @return the compilation unit with the specified name in this package */ ICompilationUnit getCompilationUnit(String name); + /** * Returns all of the compilation units in this package fragment. - * - *

    Note: it is possible that a package fragment contains only - * class files (in other words, its kind is K_BINARY), in which - * case this method returns an empty collection. - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. + * + *

    + * Note: it is possible that a package fragment contains only class files + * (in other words, its kind is K_BINARY), in which case + * this method returns an empty collection. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. * @return all of the compilation units in this package fragment */ ICompilationUnit[] getCompilationUnits() throws JavaModelException; + /** * Returns the dot-separated package name of this fragment, for example - * "java.lang", or "" (the empty string), - * for the default package. + * "java.lang", or "" (the empty string), for + * the default package. * * @return the dot-separated package name of this fragment */ String getElementName(); + /** - * Returns this package fragment's root kind encoded as an integer. - * A package fragment can contain .java source files, - * or .class files. This is a convenience method. - * + * Returns this package fragment's root kind encoded as an integer. A + * package fragment can contain .java source files, or + * .class files. This is a convenience method. + * * @see IPackageFragmentRoot#K_SOURCE * @see IPackageFragmentRoot#K_BINARY - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. * @return this package fragment's root kind encoded as an integer */ int getKind() throws JavaModelException; + /** - * Returns an array of non-Java resources contained in this package fragment. + * Returns an array of non-Java resources contained in this package + * fragment. *

    * Non-Java resources includes other files and folders located in the same - * directory as the compilation units or class files for this package + * directory as the compilation units or class files for this package * fragment. Source files excluded from this package by one or more * exclusion patterns on the corresponding source classpath entry are - * considered non-Java resources and will appear in the result - * (possibly in a folder). + * considered non-Java resources and will appear in the result (possibly in + * a folder). *

    * * @return an array of non-Java resources contained in this package fragment * @see IClasspathEntry#getExclusionPatterns */ -// Object[] getNonJavaResources() throws JavaModelException; + // Object[] getNonJavaResources() throws JavaModelException; /** - * Returns whether this package fragment's name is - * a prefix of other package fragments in this package fragment's - * root. - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. - * @return true if this package fragment's name is a prefix of other package fragments in this package fragment's root, false otherwise + * Returns whether this package fragment's name is a prefix of other package + * fragments in this package fragment's root. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. + * @return true if this package fragment's name is a prefix of other package + * fragments in this package fragment's root, false otherwise */ -// boolean hasSubpackages() throws JavaModelException; + // boolean hasSubpackages() throws JavaModelException; /** - * Returns whether this package fragment is a default package. - * This is a handle-only method. + * Returns whether this package fragment is a default package. This is a + * handle-only method. * * @return true if this package fragment is a default package */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IPackageFragmentRoot.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IPackageFragmentRoot.java index 9e9fb02..f96a997 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IPackageFragmentRoot.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IPackageFragmentRoot.java @@ -18,401 +18,462 @@ *******************************************************************************/ package net.sourceforge.phpdt.core; - /** - * A package fragment root contains a set of package fragments. - * It corresponds to an underlying resource which is either a folder, - * JAR, or zip. In the case of a folder, all descendant folders represent - * package fragments. For a given child folder representing a package fragment, - * the corresponding package name is composed of the folder names between the folder - * for this root and the child folder representing the package, separated by '.'. - * In the case of a JAR or zip, the contents of the archive dictates - * the set of package fragments in an analogous manner. - * Package fragment roots need to be opened before they can be navigated or manipulated. - * The children are of type IPackageFragment, and are in no particular order. + * A package fragment root contains a set of package fragments. It corresponds + * to an underlying resource which is either a folder, JAR, or zip. In the case + * of a folder, all descendant folders represent package fragments. For a given + * child folder representing a package fragment, the corresponding package name + * is composed of the folder names between the folder for this root and the + * child folder representing the package, separated by '.'. In the case of a JAR + * or zip, the contents of the archive dictates the set of package fragments in + * an analogous manner. Package fragment roots need to be opened before they can + * be navigated or manipulated. The children are of type + * IPackageFragment, and are in no particular order. *

    * This interface is not intended to be implemented by clients. *

    */ -public interface IPackageFragmentRoot - extends IParent, IJavaElement, IOpenable { +public interface IPackageFragmentRoot extends IParent, IJavaElement, IOpenable { /** - * Kind constant for a source path root. Indicates this root - * only contains source files. + * Kind constant for a source path root. Indicates this root only contains + * source files. */ int K_SOURCE = 1; + /** - * Kind constant for a binary path root. Indicates this - * root only contains binary files. + * Kind constant for a binary path root. Indicates this root only contains + * binary files. */ int K_BINARY = 2; + /** * Empty root path */ String DEFAULT_PACKAGEROOT_PATH = ""; //$NON-NLS-1$ + /** - * Update model flag constant (bit mask value 1) indicating that the operation - * is to not copy/move/delete the package fragment root resource. + * Update model flag constant (bit mask value 1) indicating that the + * operation is to not copy/move/delete the package fragment root resource. + * * @since 2.1 */ int NO_RESOURCE_MODIFICATION = 1; + /** - * Update model flag constant (bit mask value 2) indicating that the operation - * is to update the classpath of the originating project. + * Update model flag constant (bit mask value 2) indicating that the + * operation is to update the classpath of the originating project. + * * @since 2.1 */ int ORIGINATING_PROJECT_CLASSPATH = 2; + /** - * Update model flag constant (bit mask value 4) indicating that the operation - * is to update the classpath of all referring projects except the originating project. + * Update model flag constant (bit mask value 4) indicating that the + * operation is to update the classpath of all referring projects except the + * originating project. + * * @since 2.1 */ int OTHER_REFERRING_PROJECTS_CLASSPATH = 4; + /** - * Update model flag constant (bit mask value 8) indicating that the operation - * is to update the classpath of the destination project. + * Update model flag constant (bit mask value 8) indicating that the + * operation is to update the classpath of the destination project. + * * @since 2.1 */ - int DESTINATION_PROJECT_CLASSPATH = 8; + int DESTINATION_PROJECT_CLASSPATH = 8; + /** - * Update model flag constant (bit mask value 16) indicating that the operation - * is to replace the resource and the destination project's classpath entry. + * Update model flag constant (bit mask value 16) indicating that the + * operation is to replace the resource and the destination project's + * classpath entry. + * * @since 2.1 */ - int REPLACE = 16; + int REPLACE = 16; + /** * Attaches the source archive identified by the given absolute path to this - * binary package fragment root. rootPath specifies the location - * of the root within the archive or folder (empty specifies the default root - * and null specifies the root path should be detected). - * Once a source archive or folder is attached to the package fragment root, - * the getSource and getSourceRange - * methods become operational for binary types/members. - * To detach a source archive or folder from a package fragment root, specify - * null as the source path. - * - * @param sourcePath the given absolute path to the source archive or folder - * @param rootPath specifies the location of the root within the archive - * (empty specifies the default root and null specifies - * automatic detection of the root path) - * @param monitor the given progress monitor - * @exception JavaModelException if this operation fails. Reasons include: - *
      - *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    • A CoreException occurred while updating a server property - *
    • This package fragment root is not of kind binary (INVALID_ELEMENT_TYPES) - *
    • The path provided is not absolute (RELATIVE_PATH) - *
    + * binary package fragment root. rootPath specifies the + * location of the root within the archive or folder (empty specifies the + * default root and null specifies the root path should be + * detected). Once a source archive or folder is attached to the package + * fragment root, the getSource and + * getSourceRange methods become operational for binary + * types/members. To detach a source archive or folder from a package + * fragment root, specify null as the source path. + * + * @param sourcePath + * the given absolute path to the source archive or folder + * @param rootPath + * specifies the location of the root within the archive (empty + * specifies the default root and null specifies + * automatic detection of the root path) + * @param monitor + * the given progress monitor + * @exception JavaModelException + * if this operation fails. Reasons include: + *
      + *
    • This Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while + * updating a server property + *
    • This package fragment root is not of kind binary + * (INVALID_ELEMENT_TYPES) + *
    • The path provided is not absolute (RELATIVE_PATH) + *
    */ -// void attachSource(IPath sourcePath, IPath rootPath, IProgressMonitor monitor) -// throws JavaModelException; - + // void attachSource(IPath sourcePath, IPath rootPath, IProgressMonitor + // monitor) + // throws JavaModelException; /** * Copies the resource of this package fragment root to the destination path * as specified by IResource.copy(IPath, int, IProgressMonitor) * but excluding nested source folders. *

    - * If NO_RESOURCE_MODIFICATION is specified in - * updateModelFlags or if this package fragment root is external, - * this operation doesn't copy the resource. updateResourceFlags - * is then ignored. - *

    - * If DESTINATION_PROJECT_CLASSPATH is specified in - * updateModelFlags, updates the classpath of the - * destination's project (if it is a Java project). If a non-null - * sibling is specified, a copy of this root's classpath entry is inserted before the - * sibling on the destination project's raw classpath. If null is - * specified, the classpath entry is added at the end of the raw classpath. - *

    + * If NO_RESOURCE_MODIFICATION is specified in + * updateModelFlags or if this package fragment root is + * external, this operation doesn't copy the resource. + * updateResourceFlags is then ignored. + *

    + *

    + * If DESTINATION_PROJECT_CLASSPATH is specified in + * updateModelFlags, updates the classpath of the + * destination's project (if it is a Java project). If a non-null + * sibling is specified, a copy of this root's classpath entry is inserted + * before the sibling on the destination project's raw classpath. If + * null is specified, the classpath entry is added at the end + * of the raw classpath. + *

    + *

    * If REPLACE is specified in updateModelFlags, - * overwrites the resource at the destination path if any. - * If the same classpath entry already exists on the destination project's raw - * classpath, then the sibling is ignored and the new classpath entry replaces the - * existing one. - *

    - * If no flags is specified in updateModelFlags (using + * overwrites the resource at the destination path if any. If the same + * classpath entry already exists on the destination project's raw + * classpath, then the sibling is ignored and the new classpath entry + * replaces the existing one. + *

    + *

    + * If no flags is specified in updateModelFlags (using * IResource.NONE), the default behavior applies: the - * resource is copied (if this package fragment root is not external) and the - * classpath is not updated. + * resource is copied (if this package fragment root is not external) and + * the classpath is not updated. *

    * - * @param destination the destination path - * @param updateResourceFlags bit-wise or of update resource flag constants - * (IResource.FORCE and IResource.SHALLOW) - * @param updateModelFlags bit-wise or of update resource flag constants - * (DESTINATION_PROJECT_CLASSPATH and - * NO_RESOURCE_MODIFICATION) - * @param sibling the classpath entry before which a copy of the classpath - * entry should be inserted or null if the classpath entry should - * be inserted at the end - * @param monitor a progress monitor + * @param destination + * the destination path + * @param updateResourceFlags + * bit-wise or of update resource flag constants (IResource.FORCE + * and IResource.SHALLOW) + * @param updateModelFlags + * bit-wise or of update resource flag constants (DESTINATION_PROJECT_CLASSPATH + * and NO_RESOURCE_MODIFICATION) + * @param sibling + * the classpath entry before which a copy of the classpath entry + * should be inserted or null if the classpath + * entry should be inserted at the end + * @param monitor + * a progress monitor * - * @exception JavaModelException if this root could not be copied. Reasons - * include: - *
      - *
    • This root does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    • A CoreException occurred while copying the - * resource or updating a classpath
    • - *
    • - * The destination is not inside an existing project and updateModelFlags - * has been specified as DESTINATION_PROJECT_CLASSPATH - * (INVALID_DESTINATION)
    • - *
    • The sibling is not a classpath entry on the destination project's - * raw classpath (INVALID_SIBLING)
    • - *
    • The same classpath entry already exists on the destination project's - * classpath (NAME_COLLISION) and updateModelFlags - * has not been specified as REPLACE
    • - *
    + * @exception JavaModelException + * if this root could not be copied. Reasons include: + *
      + *
    • This root does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while copying + * the resource or updating a classpath
    • + *
    • The destination is not inside an existing project and + * updateModelFlags has been specified as + * DESTINATION_PROJECT_CLASSPATH + * (INVALID_DESTINATION)
    • + *
    • The sibling is not a classpath entry on the + * destination project's raw classpath (INVALID_SIBLING)
    • + *
    • The same classpath entry already exists on the + * destination project's classpath (NAME_COLLISION) and + * updateModelFlags has not been specified as + * REPLACE
    • + *
    * @see org.eclipse.core.resources.IResource#copy * @since 2.1 */ -// void copy(IPath destination, int updateResourceFlags, int updateModelFlags, IClasspathEntry sibling, IProgressMonitor monitor) throws JavaModelException; + // void copy(IPath destination, int updateResourceFlags, int + // updateModelFlags, IClasspathEntry sibling, IProgressMonitor monitor) + // throws JavaModelException; /** - * Creates and returns a package fragment in this root with the - * given dot-separated package name. An empty string specifies the default package. - * This has the side effect of creating all package - * fragments that are a prefix of the new package fragment which - * do not exist yet. If the package fragment already exists, this - * has no effect. - * - * For a description of the force flag, see IFolder.create. - * - * @param name the given dot-separated package name - * @param force a flag controlling how to deal with resources that - * are not in sync with the local file system - * @param monitor the given progress monitor - * @exception JavaModelException if the element could not be created. Reasons include: - *
      - *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    • A CoreException occurred while creating an underlying resource - *
    • This package fragment root is read only (READ_ONLY) - *
    • The name is not a valid package name (INVALID_NAME) - *
    - * @return a package fragment in this root with the given dot-separated package name + * Creates and returns a package fragment in this root with the given + * dot-separated package name. An empty string specifies the default + * package. This has the side effect of creating all package fragments that + * are a prefix of the new package fragment which do not exist yet. If the + * package fragment already exists, this has no effect. + * + * For a description of the force flag, see + * IFolder.create. + * + * @param name + * the given dot-separated package name + * @param force + * a flag controlling how to deal with resources that are not in + * sync with the local file system + * @param monitor + * the given progress monitor + * @exception JavaModelException + * if the element could not be created. Reasons include: + *
      + *
    • This Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while + * creating an underlying resource + *
    • This package fragment root is read only (READ_ONLY) + *
    • The name is not a valid package name (INVALID_NAME) + *
    + * @return a package fragment in this root with the given dot-separated + * package name * @see org.eclipse.core.resources.IFolder#create */ -// IPackageFragment createPackageFragment( -// String name, -// boolean force, -// IProgressMonitor monitor) -// throws JavaModelException; + // IPackageFragment createPackageFragment( + // String name, + // boolean force, + // IProgressMonitor monitor) + // throws JavaModelException; /** * Deletes the resource of this package fragment root as specified by - * IResource.delete(int, IProgressMonitor) but excluding nested - * source folders. + * IResource.delete(int, IProgressMonitor) but excluding + * nested source folders. + *

    + * If NO_RESOURCE_MODIFICATION is specified in + * updateModelFlags or if this package fragment root is + * external, this operation doesn't delete the resource. + * updateResourceFlags is then ignored. + *

    *

    - * If NO_RESOURCE_MODIFICATION is specified in - * updateModelFlags or if this package fragment root is external, - * this operation doesn't delete the resource. updateResourceFlags - * is then ignored. - *

    - * If ORIGINATING_PROJECT_CLASSPATH is specified in - * updateModelFlags, update the raw classpath of this package - * fragment root's project by removing the corresponding classpath entry. - *

    - * If OTHER_REFERRING_PROJECTS_CLASSPATH is specified in - * updateModelFlags, update the raw classpaths of all other Java - * projects referring to this root's resource by removing the corresponding classpath - * entries. - *

    - * If no flags is specified in updateModelFlags (using + * If ORIGINATING_PROJECT_CLASSPATH is specified in + * updateModelFlags, update the raw classpath of this + * package fragment root's project by removing the corresponding classpath + * entry. + *

    + *

    + * If OTHER_REFERRING_PROJECTS_CLASSPATH is specified in + * updateModelFlags, update the raw classpaths of all other + * Java projects referring to this root's resource by removing the + * corresponding classpath entries. + *

    + *

    + * If no flags is specified in updateModelFlags (using * IResource.NONE), the default behavior applies: the - * resource is deleted (if this package fragment root is not external) and no - * classpaths are updated. + * resource is deleted (if this package fragment root is not external) and + * no classpaths are updated. *

    * - * @param updateResourceFlags bit-wise or of update resource flag constants - * (IResource.FORCE and IResource.KEEP_HISTORY) - * @param updateModelFlags bit-wise or of update resource flag constants - * (ORIGINATING_PROJECT_CLASSPATH, - * OTHER_REFERRING_PROJECTS_CLASSPATH and - * NO_RESOURCE_MODIFICATION) - * @param monitor a progress monitor + * @param updateResourceFlags + * bit-wise or of update resource flag constants (IResource.FORCE + * and IResource.KEEP_HISTORY) + * @param updateModelFlags + * bit-wise or of update resource flag constants (ORIGINATING_PROJECT_CLASSPATH, + * OTHER_REFERRING_PROJECTS_CLASSPATH and + * NO_RESOURCE_MODIFICATION) + * @param monitor + * a progress monitor * - * @exception JavaModelException if this root could not be deleted. Reasons - * include: - *
      - *
    • This root does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    • A CoreException occurred while deleting the resource - * or updating a classpath - *
    • - *
    + * @exception JavaModelException + * if this root could not be deleted. Reasons include: + *
      + *
    • This root does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while + * deleting the resource or updating a classpath
    • + *
    * @see org.eclipse.core.resources.IResource#delete * @since 2.1 */ -// void delete(int updateResourceFlags, int updateModelFlags, IProgressMonitor monitor) throws JavaModelException; + // void delete(int updateResourceFlags, int updateModelFlags, + // IProgressMonitor monitor) throws JavaModelException; /** - * Returns this package fragment root's kind encoded as an integer. - * A package fragment root can contain .java source files, - * or .class files, but not both. - * If the underlying folder or archive contains other kinds of files, they are ignored. - * In particular, .class files are ignored under a source package fragment root, - * and .java files are ignored under a binary package fragment root. - * + * Returns this package fragment root's kind encoded as an integer. A + * package fragment root can contain .java source files, or + * .class files, but not both. If the underlying folder or + * archive contains other kinds of files, they are ignored. In particular, + * .class files are ignored under a source package fragment + * root, and .java files are ignored under a binary package + * fragment root. + * * @see IPackageFragmentRoot#K_SOURCE * @see IPackageFragmentRoot#K_BINARY - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. * @return this package fragment root's kind encoded as an integer */ int getKind() throws JavaModelException; - + /** - * Returns an array of non-Java resources contained in this package fragment root. + * Returns an array of non-Java resources contained in this package fragment + * root. *

    * Non-Java resources includes other files and folders located in the same * directories as the compilation units or class files under this package - * fragment root. Resources excluded from this package fragment root - * by one or more exclusion patterns on the corresponding source classpath - * entry are considered non-Java resources and will appear in the result - * (possibly in a folder). Thus when a nested source folder is excluded, it will appear - * in the non-Java resources of the outer folder. + * fragment root. Resources excluded from this package fragment root by one + * or more exclusion patterns on the corresponding source classpath entry + * are considered non-Java resources and will appear in the result (possibly + * in a folder). Thus when a nested source folder is excluded, it will + * appear in the non-Java resources of the outer folder. *

    - * @return an array of non-Java resources contained in this package fragment root + * + * @return an array of non-Java resources contained in this package fragment + * root * @see IClasspathEntry#getExclusionPatterns */ -// Object[] getNonJavaResources() throws JavaModelException; - + // Object[] getNonJavaResources() throws JavaModelException; /** - * Returns the package fragment with the given package name. - * An empty string indicates the default package. - * This is a handle-only operation. The package fragment - * may or may not exist. + * Returns the package fragment with the given package name. An empty string + * indicates the default package. This is a handle-only operation. The + * package fragment may or may not exist. * - * @param packageName the given package name + * @param packageName + * the given package name * @return the package fragment with the given package name */ IPackageFragment getPackageFragment(String packageName); - /** * Returns the first raw classpath entry that corresponds to this package - * fragment root. - * A raw classpath entry corresponds to a package fragment root if once resolved - * this entry's path is equal to the root's path. + * fragment root. A raw classpath entry corresponds to a package fragment + * root if once resolved this entry's path is equal to the root's path. * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. - * @return the first raw classpath entry that corresponds to this package fragment root + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. + * @return the first raw classpath entry that corresponds to this package + * fragment root * @since 2.0 */ -// IClasspathEntry getRawClasspathEntry() throws JavaModelException; - + // IClasspathEntry getRawClasspathEntry() throws JavaModelException; /** - * Returns the absolute path to the source archive attached to - * this package fragment root's binary archive. - * - * @return the absolute path to the corresponding source archive, - * or null if this package fragment root's binary archive - * has no corresponding source archive, or if this package fragment root - * is not a binary archive - * @exception JavaModelException if this operation fails + * Returns the absolute path to the source archive attached to this package + * fragment root's binary archive. + * + * @return the absolute path to the corresponding source archive, or + * null if this package fragment root's binary + * archive has no corresponding source archive, or if this package + * fragment root is not a binary archive + * @exception JavaModelException + * if this operation fails */ -// IPath getSourceAttachmentPath() throws JavaModelException; - + // IPath getSourceAttachmentPath() throws JavaModelException; /** - * Returns the path within this package fragment root's source archive. - * An empty path indicates that packages are located at the root of the - * source archive. - * - * @return the path within the corresponding source archive, - * or null if this package fragment root's binary archive - * has no corresponding source archive, or if this package fragment root - * is not a binary archive - * @exception JavaModelException if this operation fails + * Returns the path within this package fragment root's source archive. An + * empty path indicates that packages are located at the root of the source + * archive. + * + * @return the path within the corresponding source archive, or + * null if this package fragment root's binary + * archive has no corresponding source archive, or if this package + * fragment root is not a binary archive + * @exception JavaModelException + * if this operation fails */ -// IPath getSourceAttachmentRootPath() throws JavaModelException; - + // IPath getSourceAttachmentRootPath() throws JavaModelException; /** - * Returns whether this package fragment root's underlying - * resource is a binary archive (a JAR or zip file). + * Returns whether this package fragment root's underlying resource is a + * binary archive (a JAR or zip file). * - * @return true if this package fragment root's underlying resource is a binary archive, false otherwise + * @return true if this package fragment root's underlying resource is a + * binary archive, false otherwise */ public boolean isArchive(); - + /** - * Returns whether this package fragment root is external - * to the workbench (that is, a local file), and has no - * underlying resource. + * Returns whether this package fragment root is external to the workbench + * (that is, a local file), and has no underlying resource. * - * @return true if this package fragment root is external - * to the workbench (that is, a local file), and has no - * underlying resource, false otherwise + * @return true if this package fragment root is external to the workbench + * (that is, a local file), and has no underlying resource, false + * otherwise */ boolean isExternal(); - + /** * Moves the resource of this package fragment root to the destination path * as specified by IResource.move(IPath,int,IProgressMonitor) * but excluding nested source folders. *

    - * If NO_RESOURCE_MODIFICATION is specified in - * updateModelFlags or if this package fragment root is external, - * this operation doesn't move the resource. updateResourceFlags - * is then ignored. - *

    - * If DESTINATION_PROJECT_CLASSPATH is specified in - * updateModelFlags, updates the classpath of the - * destination's project (if it is a Java project). If a non-null - * sibling is specified, a copy of this root's classpath entry is inserted before the - * sibling on the destination project's raw classpath. If null is - * specified, the classpath entry is added at the end of the raw classpath. - *

    - * If ORIGINATING_PROJECT_CLASSPATH is specified in - * updateModelFlags, update the raw classpath of this package - * fragment root's project by removing the corresponding classpath entry. - *

    - * If OTHER_REFERRING_PROJECTS_CLASSPATH is specified in - * updateModelFlags, update the raw classpaths of all other Java - * projects referring to this root's resource by removing the corresponding classpath - * entries. - *

    + * If NO_RESOURCE_MODIFICATION is specified in + * updateModelFlags or if this package fragment root is + * external, this operation doesn't move the resource. + * updateResourceFlags is then ignored. + *

    + *

    + * If DESTINATION_PROJECT_CLASSPATH is specified in + * updateModelFlags, updates the classpath of the + * destination's project (if it is a Java project). If a non-null + * sibling is specified, a copy of this root's classpath entry is inserted + * before the sibling on the destination project's raw classpath. If + * null is specified, the classpath entry is added at the end + * of the raw classpath. + *

    + *

    + * If ORIGINATING_PROJECT_CLASSPATH is specified in + * updateModelFlags, update the raw classpath of this + * package fragment root's project by removing the corresponding classpath + * entry. + *

    + *

    + * If OTHER_REFERRING_PROJECTS_CLASSPATH is specified in + * updateModelFlags, update the raw classpaths of all other + * Java projects referring to this root's resource by removing the + * corresponding classpath entries. + *

    + *

    * If REPLACE is specified in updateModelFlags, - * overwrites the resource at the destination path if any. - * If the same classpath entry already exists on the destination project's raw - * classpath, then the sibling is ignored and the new classpath entry replaces the - * existing one. - *

    - * If no flags is specified in updateModelFlags (using + * overwrites the resource at the destination path if any. If the same + * classpath entry already exists on the destination project's raw + * classpath, then the sibling is ignored and the new classpath entry + * replaces the existing one. + *

    + *

    + * If no flags is specified in updateModelFlags (using * IResource.NONE), the default behavior applies: the * resource is moved (if this package fragment root is not external) and no * classpaths are updated. *

    * - * @param destination the destination path - * @param updateFlags bit-wise or of update flag constants - * (IResource.FORCE, IResource.KEEP_HISTORY - * and IResource.SHALLOW) - * @param updateModelFlags bit-wise or of update resource flag constants - * (DESTINATION_PROJECT_CLASSPATH, - * ORIGINATING_PROJECT_CLASSPATH, - * OTHER_REFERRING_PROJECTS_CLASSPATH and - * NO_RESOURCE_MODIFICATION) - * @param sibling the classpath entry before which a copy of the classpath - * entry should be inserted or null if the classpath entry should - * be inserted at the end - * @param monitor a progress monitor + * @param destination + * the destination path + * @param updateFlags + * bit-wise or of update flag constants (IResource.FORCE, + * IResource.KEEP_HISTORY and + * IResource.SHALLOW) + * @param updateModelFlags + * bit-wise or of update resource flag constants (DESTINATION_PROJECT_CLASSPATH, + * ORIGINATING_PROJECT_CLASSPATH, + * OTHER_REFERRING_PROJECTS_CLASSPATH and + * NO_RESOURCE_MODIFICATION) + * @param sibling + * the classpath entry before which a copy of the classpath entry + * should be inserted or null if the classpath + * entry should be inserted at the end + * @param monitor + * a progress monitor * - * @exception JavaModelException if this root could not be moved. Reasons - * include: - *
      - *
    • This root does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    • A CoreException occurred while copying the - * resource or updating a classpath
    • - *
    • - * The destination is not inside an existing project and updateModelFlags - * has been specified as DESTINATION_PROJECT_CLASSPATH - * (INVALID_DESTINATION)
    • - *
    • The sibling is not a classpath entry on the destination project's - * raw classpath (INVALID_SIBLING)
    • - *
    • The same classpath entry already exists on the destination project's - * classpath (NAME_COLLISION) and updateModelFlags - * has not been specified as REPLACE
    • - *
    + * @exception JavaModelException + * if this root could not be moved. Reasons include: + *
      + *
    • This root does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while copying + * the resource or updating a classpath
    • + *
    • The destination is not inside an existing project and + * updateModelFlags has been specified as + * DESTINATION_PROJECT_CLASSPATH + * (INVALID_DESTINATION)
    • + *
    • The sibling is not a classpath entry on the + * destination project's raw classpath (INVALID_SIBLING)
    • + *
    • The same classpath entry already exists on the + * destination project's classpath (NAME_COLLISION) and + * updateModelFlags has not been specified as + * REPLACE
    • + *
    * @see org.eclipse.core.resources.IResource#move * @since 2.1 */ -// void move(IPath destination, int updateResourceFlags, int updateModelFlags, IClasspathEntry sibling, IProgressMonitor monitor) throws JavaModelException; + // void move(IPath destination, int updateResourceFlags, int + // updateModelFlags, IClasspathEntry sibling, IProgressMonitor monitor) + // throws JavaModelException; } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IParent.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IParent.java index f1571c5..6ee4aa3 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IParent.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IParent.java @@ -17,24 +17,27 @@ package net.sourceforge.phpdt.core; *

    */ public interface IParent { -/** - * Returns the immediate children of this element. - * Unless otherwise specified by the implementing element, - * the children are in no particular order. - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource - * @return the immediate children of this element - */ -IJavaElement[] getChildren() throws JavaModelException; -/** - * Returns whether this element has one or more immediate children. - * This is a convenience method, and may be more efficient than - * testing whether getChildren is an empty array. - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource - * @return true if the immediate children of this element, false otherwise - */ -boolean hasChildren() throws JavaModelException; + /** + * Returns the immediate children of this element. Unless otherwise + * specified by the implementing element, the children are in no particular + * order. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource + * @return the immediate children of this element + */ + IJavaElement[] getChildren() throws JavaModelException; + + /** + * Returns whether this element has one or more immediate children. This is + * a convenience method, and may be more efficient than testing whether + * getChildren is an empty array. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource + * @return true if the immediate children of this element, false otherwise + */ + boolean hasChildren() throws JavaModelException; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IProblemRequestor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IProblemRequestor.java index 5f2e487..c77d5eb 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IProblemRequestor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IProblemRequestor.java @@ -12,39 +12,41 @@ package net.sourceforge.phpdt.core; import net.sourceforge.phpdt.core.compiler.IProblem; - /** - * A callback interface for receiving java problem as they are discovered - * by some Java operation. + * A callback interface for receiving java problem as they are discovered by + * some Java operation. * * @see IProblem * @since 2.0 */ public interface IProblemRequestor { - + /** * Notification of a Java problem. * - * @param problem IProblem - The discovered Java problem. - */ + * @param problem + * IProblem - The discovered Java problem. + */ void acceptProblem(IProblem problem); /** * Notification sent before starting the problem detection process. - * Typically, this would tell a problem collector to clear previously recorded problems. + * Typically, this would tell a problem collector to clear previously + * recorded problems. */ void beginReporting(); /** * Notification sent after having completed problem detection process. - * Typically, this would tell a problem collector that no more problems should be expected in this - * iteration. + * Typically, this would tell a problem collector that no more problems + * should be expected in this iteration. */ void endReporting(); /** - * Predicate allowing the problem requestor to signal whether or not it is currently - * interested by problem reports. When answering false, problem will + * Predicate allowing the problem requestor to signal whether or not it is + * currently interested by problem reports. When answering + * false, problem will * not be discovered any more until the next iteration. * * This predicate will be invoked once prior to each problem detection iteration. diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IRegion.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IRegion.java index 6733054..b08700a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IRegion.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IRegion.java @@ -11,57 +11,64 @@ package net.sourceforge.phpdt.core; /** - * A Java model region describes a hierarchical set of elements. - * Regions are often used to describe a set of elements to be considered - * when performing operations; for example, the set of elements to be - * considered during a search. A region may include elements from different - * projects. + * A Java model region describes a hierarchical set of elements. Regions are + * often used to describe a set of elements to be considered when performing + * operations; for example, the set of elements to be considered during a + * search. A region may include elements from different projects. *

    - * When an element is included in a region, all of its children - * are considered to be included. Children of an included element - * cannot be selectively excluded. + * When an element is included in a region, all of its children are considered + * to be included. Children of an included element cannot be selectively + * excluded. *

    *

    - * This interface is not intended to be implemented by clients. - * Instances can be created via the JavaCore.newRegion. + * This interface is not intended to be implemented by clients. Instances can be + * created via the JavaCore.newRegion. *

    - * + * * @see JavaCore#newRegion */ public interface IRegion { /** - * Adds the given element and all of its descendents to this region. - * If the specified element is already included, or one of its - * ancestors is already included, this has no effect. If the element - * being added is an ancestor of an element already contained in this - * region, the ancestor subsumes the descendent. + * Adds the given element and all of its descendents to this region. If the + * specified element is already included, or one of its ancestors is already + * included, this has no effect. If the element being added is an ancestor + * of an element already contained in this region, the ancestor subsumes the + * descendent. * - * @param element the given element + * @param element + * the given element */ void add(IJavaElement element); + /** * Returns whether the given element is contained in this region. * - * @param element the given element - * @return true if the given element is contained in this region, false otherwise + * @param element + * the given element + * @return true if the given element is contained in this region, false + * otherwise */ boolean contains(IJavaElement element); + /** - * Returns the top level elements in this region. - * All descendents of these elements are also included in this region. + * Returns the top level elements in this region. All descendents of these + * elements are also included in this region. * * @return the top level elements in this region */ IJavaElement[] getElements(); + /** * Removes the specified element from the region and returns * true if successful, false if the remove - * fails. If an ancestor of the given element is included, the - * remove fails (in other words, it is not possible to selectively - * exclude descendants of included ancestors). + * fails. If an ancestor of the given element is included, the remove fails + * (in other words, it is not possible to selectively exclude descendants of + * included ancestors). * - * @param element the given element - * @return true if successful, false if the remove fails + * @param element + * the given element + * @return true if successful, false if the + * remove fails */ boolean remove(IJavaElement element); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceManipulation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceManipulation.java index 554bbf9..2a7ebe6 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceManipulation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceManipulation.java @@ -10,7 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpdt.core; - /** * Common protocol for Java elements that support source code manipulations such * as copy, move, rename, and delete. @@ -19,94 +18,138 @@ package net.sourceforge.phpdt.core; *

    */ public interface ISourceManipulation { -/** - * Copies this element to the given container. - * - * @param container the container - * @param sibling the sibling element before which the copy should be inserted, - * or null if the copy should be inserted as the last child of - * the container - * @param rename the new name for the element, or null if the copy - * retains the name of this element - * @param replace true if any existing child in the container with - * the target name should be replaced, and false to throw an - * exception in the event of a name collision - * @param monitor a progress monitor - * @exception JavaModelException if this element could not be copied. Reasons include: - *
      - *
    • This Java element, container element, or sibling does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    • A CoreException occurred while updating an underlying resource - *
    • The container is of an incompatible type (INVALID_DESTINATION) - *
    • The sibling is not a child of the given container (INVALID_SIBLING) - *
    • The new name is invalid (INVALID_NAME) - *
    • A child in the container already exists with the same name (NAME_COLLISION) - * and replace has been specified as false - *
    • The container or this element is read-only (READ_ONLY) - *
    - * - * @exception IllegalArgumentException if container is null - */ -//void copy(IJavaElement container, IJavaElement sibling, String rename, boolean replace, IProgressMonitor monitor) throws JavaModelException; -/** - * Deletes this element, forcing if specified and necessary. - * - * @param force a flag controlling whether underlying resources that are not - * in sync with the local file system will be tolerated (same as the force flag - * in IResource operations). - * @param monitor a progress monitor - * @exception JavaModelException if this element could not be deleted. Reasons include: - *
      - *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    • A CoreException occurred while updating an underlying resource (CORE_EXCEPTION)
    • - *
    • This element is read-only (READ_ONLY)
    • - *
    - */ -//void delete(boolean force, IProgressMonitor monitor) throws JavaModelException; -/** - * Moves this element to the given container. - * - * @param container the container - * @param sibling the sibling element before which the element should be inserted, - * or null if the element should be inserted as the last child of - * the container - * @param rename the new name for the element, or null if the - * element retains its name - * @param replace true if any existing child in the container with - * the target name should be replaced, and false to throw an - * exception in the event of a name collision - * @param monitor a progress monitor - * @exception JavaModelException if this element could not be moved. Reasons include: - *
      - *
    • This Java element, container element, or sibling does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    • A CoreException occurred while updating an underlying resource - *
    • The container is of an incompatible type (INVALID_DESTINATION) - *
    • The sibling is not a child of the given container (INVALID_SIBLING) - *
    • The new name is invalid (INVALID_NAME) - *
    • A child in the container already exists with the same name (NAME_COLLISION) - * and replace has been specified as false - *
    • The container or this element is read-only (READ_ONLY) - *
    - * - * @exception IllegalArgumentException if container is null - */ -//void move(IJavaElement container, IJavaElement sibling, String rename, boolean replace, IProgressMonitor monitor) throws JavaModelException; -/** - * Renames this element to the given name. - * - * @param name the new name for the element - * @param replace true if any existing element with the target name - * should be replaced, and false to throw an exception in the - * event of a name collision - * @param monitor a progress monitor - * @exception JavaModelException if this element could not be renamed. Reasons include: - *
      - *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    • A CoreException occurred while updating an underlying resource - *
    • The new name is invalid (INVALID_NAME) - *
    • A child in the container already exists with the same name (NAME_COLLISION) - * and replace has been specified as false - *
    • This element is read-only (READ_ONLY) - *
    - */ -//void rename(String name, boolean replace, IProgressMonitor monitor) throws JavaModelException; + /** + * Copies this element to the given container. + * + * @param container + * the container + * @param sibling + * the sibling element before which the copy should be inserted, + * or null if the copy should be inserted as the + * last child of the container + * @param rename + * the new name for the element, or null if the + * copy retains the name of this element + * @param replace + * true if any existing child in the container + * with the target name should be replaced, and + * false to throw an exception in the event of a + * name collision + * @param monitor + * a progress monitor + * @exception JavaModelException + * if this element could not be copied. Reasons include: + *
      + *
    • This Java element, container element, or sibling does + * not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while + * updating an underlying resource + *
    • The container is of an incompatible type + * (INVALID_DESTINATION) + *
    • The sibling is not a child of the given container + * (INVALID_SIBLING) + *
    • The new name is invalid (INVALID_NAME) + *
    • A child in the container already exists with the same + * name (NAME_COLLISION) and replace has been + * specified as false + *
    • The container or this element is read-only + * (READ_ONLY) + *
    + * + * @exception IllegalArgumentException + * if container is null + */ + // void copy(IJavaElement container, IJavaElement sibling, String rename, + // boolean replace, IProgressMonitor monitor) throws JavaModelException; + /** + * Deletes this element, forcing if specified and necessary. + * + * @param force + * a flag controlling whether underlying resources that are not + * in sync with the local file system will be tolerated (same as + * the force flag in IResource operations). + * @param monitor + * a progress monitor + * @exception JavaModelException + * if this element could not be deleted. Reasons include: + *
      + *
    • This Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while + * updating an underlying resource (CORE_EXCEPTION)
    • + *
    • This element is read-only (READ_ONLY)
    • + *
    + */ + // void delete(boolean force, IProgressMonitor monitor) throws + // JavaModelException; + /** + * Moves this element to the given container. + * + * @param container + * the container + * @param sibling + * the sibling element before which the element should be + * inserted, or null if the element should be + * inserted as the last child of the container + * @param rename + * the new name for the element, or null if the + * element retains its name + * @param replace + * true if any existing child in the container + * with the target name should be replaced, and + * false to throw an exception in the event of a + * name collision + * @param monitor + * a progress monitor + * @exception JavaModelException + * if this element could not be moved. Reasons include: + *
      + *
    • This Java element, container element, or sibling does + * not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while + * updating an underlying resource + *
    • The container is of an incompatible type + * (INVALID_DESTINATION) + *
    • The sibling is not a child of the given container + * (INVALID_SIBLING) + *
    • The new name is invalid (INVALID_NAME) + *
    • A child in the container already exists with the same + * name (NAME_COLLISION) and replace has been + * specified as false + *
    • The container or this element is read-only + * (READ_ONLY) + *
    + * + * @exception IllegalArgumentException + * if container is null + */ + // void move(IJavaElement container, IJavaElement sibling, String rename, + // boolean replace, IProgressMonitor monitor) throws JavaModelException; + /** + * Renames this element to the given name. + * + * @param name + * the new name for the element + * @param replace + * true if any existing element with the target + * name should be replaced, and false to throw an + * exception in the event of a name collision + * @param monitor + * a progress monitor + * @exception JavaModelException + * if this element could not be renamed. Reasons include: + *
      + *
    • This Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while + * updating an underlying resource + *
    • The new name is invalid (INVALID_NAME) + *
    • A child in the container already exists with the same + * name (NAME_COLLISION) and replace has been + * specified as false + *
    • This element is read-only (READ_ONLY) + *
    + */ + // void rename(String name, boolean replace, IProgressMonitor monitor) + // throws JavaModelException; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceRange.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceRange.java index 46ab0f6..302e6da 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceRange.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceRange.java @@ -11,28 +11,31 @@ package net.sourceforge.phpdt.core; /** - * A source range defines an element's source coordinates relative to - * its source buffer. + * A source range defines an element's source coordinates relative to its source + * buffer. *

    * This interface is not intended to be implemented by clients. *

    */ public interface ISourceRange { -/** - * Returns the number of characters of the source code for this element, - * relative to the source buffer in which this element is contained. - * - * @return the number of characters of the source code for this element, - * relative to the source buffer in which this element is contained - */ -int getLength(); -/** - * Returns the 0-based index of the first character of the source code for this element, - * relative to the source buffer in which this element is contained. - * - * @return the 0-based index of the first character of the source code for this element, - * relative to the source buffer in which this element is contained - */ -int getOffset(); + /** + * Returns the number of characters of the source code for this element, + * relative to the source buffer in which this element is contained. + * + * @return the number of characters of the source code for this element, + * relative to the source buffer in which this element is contained + */ + int getLength(); + + /** + * Returns the 0-based index of the first character of the source code for + * this element, relative to the source buffer in which this element is + * contained. + * + * @return the 0-based index of the first character of the source code for + * this element, relative to the source buffer in which this element + * is contained + */ + int getOffset(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceReference.java index 6497066..d864a05 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceReference.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceReference.java @@ -11,63 +11,66 @@ package net.sourceforge.phpdt.core; /** - * Common protocol for Java elements that have associated source code. - * This set consists of IClassFile, ICompilationUnit, + * Common protocol for Java elements that have associated source code. This set + * consists of IClassFile, ICompilationUnit, * IPackageDeclaration, IImportDeclaration, * IImportContainer, IType, IField, * IMethod, and IInitializer. * *

    * Note: For IClassFile, IType and other members - * derived from a binary type, the implementation returns source iff the - * element has attached source code. + * derived from a binary type, the implementation returns source iff the element + * has attached source code. *

    *

    - * Source reference elements may be working copies if they were created from - * a compilation unit that is a working copy. + * Source reference elements may be working copies if they were created from a + * compilation unit that is a working copy. *

    *

    * This interface is not intended to be implemented by clients. *

    - * + * * @see IPackageFragmentRoot#attachSource */ public interface ISourceReference { -/** - * Returns whether this element exists in the model. - * - * @return true if this element exists in the Java model - * @since 2.0 - */ -boolean exists(); - -/** - * Returns the source code associated with this element. - * This extracts the substring from the source buffer containing this source - * element. This corresponds to the source range that would be returned by - * getSourceRange. - *

    - * For class files, this returns the source of the entire compilation unit - * associated with the class file (if there is one). - *

    - * - * @return the source code, or null if this element has no - * associated source code - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource - */ -String getSource() throws JavaModelException; -/** - * Returns the source range associated with this element. - *

    - * For class files, this returns the range of the entire compilation unit - * associated with the class file (if there is one). - *

    - * - * @return the source range, or null if this element has no - * associated source code - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource - */ -ISourceRange getSourceRange() throws JavaModelException; + /** + * Returns whether this element exists in the model. + * + * @return true if this element exists in the Java model + * @since 2.0 + */ + boolean exists(); + + /** + * Returns the source code associated with this element. This extracts the + * substring from the source buffer containing this source element. This + * corresponds to the source range that would be returned by + * getSourceRange. + *

    + * For class files, this returns the source of the entire compilation unit + * associated with the class file (if there is one). + *

    + * + * @return the source code, or null if this element has no + * associated source code + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource + */ + String getSource() throws JavaModelException; + + /** + * Returns the source range associated with this element. + *

    + * For class files, this returns the range of the entire compilation unit + * associated with the class file (if there is one). + *

    + * + * @return the source range, or null if this element has no + * associated source code + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource + */ + ISourceRange getSourceRange() throws JavaModelException; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IType.java index ee57a1f..ddb4160 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IType.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IType.java @@ -10,20 +10,19 @@ *******************************************************************************/ package net.sourceforge.phpdt.core; - - /** * Represents either a source type in a compilation unit (either a top-level * type or a member type) or a binary type in a class file. *

    - * If a binary type cannot be parsed, its structure remains unknown. - * Use IJavaElement.isStructureKnown to determine whether this - * is the case. + * If a binary type cannot be parsed, its structure remains unknown. Use + * IJavaElement.isStructureKnown to determine whether this is the + * case. *

    *

    - * The children are of type IMember, which includes IField, - * IMethod, IInitializer and IType. - * The children are listed in the order in which they appear in the source or class file. + * The children are of type IMember, which includes + * IField, IMethod, IInitializer + * and IType. The children are listed in the order in which they + * appear in the source or class file. *

    *

    * This interface is not intended to be implemented by clients. @@ -31,406 +30,480 @@ package net.sourceforge.phpdt.core; */ public interface IType extends IMember, IParent { /** - * Do code completion inside a code snippet in the context of the current type. - * - * If the type can access to his source code and the insertion position is valid, - * then completion is performed against source. Otherwise the completion is performed - * against type structure and given locals variables. - * - * @param snippet the code snippet - * @param insertion the position with in source where the snippet - * is inserted. This position must not be in comments. - * A possible value is -1, if the position is not known. - * @param position the position with in snippet where the user - * is performing code assist. - * @param localVariableTypesNames an array (possibly empty) of fully qualified - * type names of local variables visible at the current scope - * @param localVariableNames an array (possibly empty) of local variable names - * that are visible at the current scope - * @param localVariableModifiers an array (possible empty) of modifiers for - * local variables - * @param isStatic whether the current scope is in a static context - * @param requestor the completion requestor + * Do code completion inside a code snippet in the context of the current + * type. + * + * If the type can access to his source code and the insertion position is + * valid, then completion is performed against source. Otherwise the + * completion is performed against type structure and given locals + * variables. + * + * @param snippet + * the code snippet + * @param insertion + * the position with in source where the snippet is inserted. + * This position must not be in comments. A possible value is -1, + * if the position is not known. + * @param position + * the position with in snippet where the user is performing code + * assist. + * @param localVariableTypesNames + * an array (possibly empty) of fully qualified type names of + * local variables visible at the current scope + * @param localVariableNames + * an array (possibly empty) of local variable names that are + * visible at the current scope + * @param localVariableModifiers + * an array (possible empty) of modifiers for local variables + * @param isStatic + * whether the current scope is in a static context + * @param requestor + * the completion requestor * @since 2.0 */ -// void codeComplete( -// char[] snippet, -// int insertion, -// int position, -// char[][] localVariableTypeNames, -// char[][] localVariableNames, -// int[] localVariableModifiers, -// boolean isStatic, -// ICompletionRequestor requestor) -// throws JavaModelException; - - /** - * Creates and returns a field in this type with the - * given contents. + // void codeComplete( + // char[] snippet, + // int insertion, + // int position, + // char[][] localVariableTypeNames, + // char[][] localVariableNames, + // int[] localVariableModifiers, + // boolean isStatic, + // ICompletionRequestor requestor) + // throws JavaModelException; + /** + * Creates and returns a field in this type with the given contents. *

    * Optionally, the new element can be positioned before the specified - * sibling. If no sibling is specified, the element will be inserted - * as the last field declaration in this type.

    - * - *

    It is possible that a field with the same name already exists in this type. - * The value of the force parameter effects the resolution of - * such a conflict:

      - *
    • true - in this case the field is created with the new contents
    • - *
    • false - in this case a JavaModelException is thrown
    • - *

    - * - * @param contents the given contents - * @param sibling the given sibling - * @param force a flag in case the same name already exists in this type - * @param monitor the given progress monitor - * @exception JavaModelException if the element could not be created. Reasons include: + * sibling. If no sibling is specified, the element will be inserted as the + * last field declaration in this type. + *

    + * + *

    + * It is possible that a field with the same name already exists in this + * type. The value of the force parameter effects the + * resolution of such a conflict: *

      - *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    • A CoreException occurred while updating an underlying resource - *
    • The specified sibling is not a child of this type (INVALID_SIBLING) - *
    • The contents could not be recognized as a field declaration (INVALID_CONTENTS) - *
    • This type is read-only (binary) (READ_ONLY) - *
    • There was a naming collision with an existing field (NAME_COLLISION) + *
    • true - in this case the field is created with the new + * contents
    • + *
    • false - in this case a + * JavaModelException is thrown
    • *
    + *

    + * + * @param contents + * the given contents + * @param sibling + * the given sibling + * @param force + * a flag in case the same name already exists in this type + * @param monitor + * the given progress monitor + * @exception JavaModelException + * if the element could not be created. Reasons include: + *
      + *
    • This Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while + * updating an underlying resource + *
    • The specified sibling is not a child of this type + * (INVALID_SIBLING) + *
    • The contents could not be recognized as a field + * declaration (INVALID_CONTENTS) + *
    • This type is read-only (binary) (READ_ONLY) + *
    • There was a naming collision with an existing field + * (NAME_COLLISION) + *
    * @return a field in this type with the given contents */ -// IField createField(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) -// throws JavaModelException; - + // IField createField(String contents, IJavaElement sibling, boolean force, + // IProgressMonitor monitor) + // throws JavaModelException; /** - * Creates and returns a static initializer in this type with the - * given contents. + * Creates and returns a static initializer in this type with the given + * contents. *

    * Optionally, the new element can be positioned before the specified * sibling. If no sibling is specified, the new initializer is positioned * after the last existing initializer declaration, or as the first member - * in the type if there are no initializers.

    - * - * @param contents the given contents - * @param sibling the given sibling - * @param monitor the given progress monitor - * @exception JavaModelException if the element could not be created. Reasons include: - *
      - *
    • This element does not exist - *
    • A CoreException occurred while updating an underlying resource - *
    • The specified sibling is not a child of this type (INVALID_SIBLING) - *
    • The contents could not be recognized as an initializer declaration (INVALID_CONTENTS) - *
    • This type is read-only (binary) (READ_ONLY) - *
    + * in the type if there are no initializers. + *

    + * + * @param contents + * the given contents + * @param sibling + * the given sibling + * @param monitor + * the given progress monitor + * @exception JavaModelException + * if the element could not be created. Reasons include: + *
      + *
    • This element does not exist + *
    • A CoreException occurred while + * updating an underlying resource + *
    • The specified sibling is not a child of this type + * (INVALID_SIBLING) + *
    • The contents could not be recognized as an + * initializer declaration (INVALID_CONTENTS) + *
    • This type is read-only (binary) (READ_ONLY) + *
    * @return a static initializer in this type with the given contents */ -// IInitializer createInitializer(String contents, IJavaElement sibling, IProgressMonitor monitor) -// throws JavaModelException; - + // IInitializer createInitializer(String contents, IJavaElement sibling, + // IProgressMonitor monitor) + // throws JavaModelException; /** - * Creates and returns a method or constructor in this type with the - * given contents. + * Creates and returns a method or constructor in this type with the given + * contents. *

    * Optionally, the new element can be positioned before the specified - * sibling. If no sibling is specified, the element will be appended - * to this type. - * - *

    It is possible that a method with the same signature already exists in this type. - * The value of the force parameter effects the resolution of - * such a conflict:

      - *
    • true - in this case the method is created with the new contents
    • - *
    • false - in this case a JavaModelException is thrown
    • - *

    - * - * @param contents the given contents - * @param sibling the given sibling - * @param force a flag in case the same name already exists in this type - * @param monitor the given progress monitor - * @exception JavaModelException if the element could not be created. Reasons include: + * sibling. If no sibling is specified, the element will be appended to this + * type. + * + *

    + * It is possible that a method with the same signature already exists in + * this type. The value of the force parameter effects the + * resolution of such a conflict: *

      - *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    • A CoreException occurred while updating an underlying resource - *
    • The specified sibling is not a child of this type (INVALID_SIBLING) - *
    • The contents could not be recognized as a method or constructor - * declaration (INVALID_CONTENTS) - *
    • This type is read-only (binary) (READ_ONLY) - *
    • There was a naming collision with an existing method (NAME_COLLISION) + *
    • true - in this case the method is created with the + * new contents
    • + *
    • false - in this case a + * JavaModelException is thrown
    • *
    + *

    + * + * @param contents + * the given contents + * @param sibling + * the given sibling + * @param force + * a flag in case the same name already exists in this type + * @param monitor + * the given progress monitor + * @exception JavaModelException + * if the element could not be created. Reasons include: + *
      + *
    • This Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while + * updating an underlying resource + *
    • The specified sibling is not a child of this type + * (INVALID_SIBLING) + *
    • The contents could not be recognized as a method or + * constructor declaration (INVALID_CONTENTS) + *
    • This type is read-only (binary) (READ_ONLY) + *
    • There was a naming collision with an existing method + * (NAME_COLLISION) + *
    * @return a method or constructor in this type with the given contents */ -// IMethod createMethod(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) -// throws JavaModelException; - + // IMethod createMethod(String contents, IJavaElement sibling, boolean + // force, IProgressMonitor monitor) + // throws JavaModelException; /** - * Creates and returns a type in this type with the - * given contents. + * Creates and returns a type in this type with the given contents. *

    - * Optionally, the new type can be positioned before the specified - * sibling. If no sibling is specified, the type will be appended - * to this type. - * - *

    It is possible that a type with the same name already exists in this type. - * The value of the force parameter effects the resolution of - * such a conflict:

      - *
    • true - in this case the type is created with the new contents
    • - *
    • false - in this case a JavaModelException is thrown
    • - *

    - * - * @param contents the given contents - * @param sibling the given sibling - * @param force a flag in case the same name already exists in this type - * @param monitor the given progress monitor - * @exception JavaModelException if the element could not be created. Reasons include: + * Optionally, the new type can be positioned before the specified sibling. + * If no sibling is specified, the type will be appended to this type. + * + *

    + * It is possible that a type with the same name already exists in this + * type. The value of the force parameter effects the + * resolution of such a conflict: *

      - *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • - *
    • A CoreException occurred while updating an underlying resource - *
    • The specified sibling is not a child of this type (INVALID_SIBLING) - *
    • The contents could not be recognized as a type declaration (INVALID_CONTENTS) - *
    • This type is read-only (binary) (READ_ONLY) - *
    • There was a naming collision with an existing field (NAME_COLLISION) + *
    • true - in this case the type is created with the new + * contents
    • + *
    • false - in this case a + * JavaModelException is thrown
    • *
    + *

    + * + * @param contents + * the given contents + * @param sibling + * the given sibling + * @param force + * a flag in case the same name already exists in this type + * @param monitor + * the given progress monitor + * @exception JavaModelException + * if the element could not be created. Reasons include: + *
      + *
    • This Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while + * updating an underlying resource + *
    • The specified sibling is not a child of this type + * (INVALID_SIBLING) + *
    • The contents could not be recognized as a type + * declaration (INVALID_CONTENTS) + *
    • This type is read-only (binary) (READ_ONLY) + *
    • There was a naming collision with an existing field + * (NAME_COLLISION) + *
    * @return a type in this type with the given contents */ -// IType createType(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) -// throws JavaModelException; - - /** - * Finds the methods in this type that correspond to - * the given method. - * A method m1 corresponds to another method m2 if: + // IType createType(String contents, IJavaElement sibling, boolean force, + // IProgressMonitor monitor) + // throws JavaModelException; + /** + * Finds the methods in this type that correspond to the given method. A + * method m1 corresponds to another method m2 if: *
      *
    • m1 has the same element name as m2. - *
    • m1 has the same number of arguments as m2 and - * the simple names of the argument types must be equals. + *
    • m1 has the same number of arguments as m2 and the simple names of + * the argument types must be equals. *
    • m1 exists. *
    - * @param method the given method - * @return the found method or null if no such methods can be found. * - * @since 2.0 + * @param method + * the given method + * @return the found method or null if no such methods can be + * found. + * + * @since 2.0 */ IMethod[] findMethods(IMethod method); - + /** - * Returns the simple name of this type, unqualified by package or enclosing type. - * This is a handle-only method. + * Returns the simple name of this type, unqualified by package or enclosing + * type. This is a handle-only method. * * @return the simple name of this type */ String getElementName(); - + /** - * Returns the field with the specified name - * in this type (for example, "bar"). - * This is a handle-only method. The field may or may not exist. + * Returns the field with the specified name in this type (for example, + * "bar"). This is a handle-only method. The field may or + * may not exist. * - * @param name the given name + * @param name + * the given name * @return the field with the specified name in this type */ IField getField(String name); - - /** - * Returns the fields declared by this type. - * If this is a source type, the results are listed in the order - * in which they appear in the source, otherwise, the results are - * in no particular order. For binary types, this includes synthetic fields. - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. + + /** + * Returns the fields declared by this type. If this is a source type, the + * results are listed in the order in which they appear in the source, + * otherwise, the results are in no particular order. For binary types, this + * includes synthetic fields. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. * @return the fields declared by this type */ IField[] getFields() throws JavaModelException; - + /** - * Returns the fully qualified name of this type, - * including qualification for any containing types and packages. - * This is the name of the package, followed by '.', - * followed by the type-qualified name. + * Returns the fully qualified name of this type, including qualification + * for any containing types and packages. This is the name of the package, + * followed by '.', followed by the type-qualified name. * This is a handle-only method. - * + * * @see IType#getTypeQualifiedName() * @return the fully qualified name of this type */ String getFullyQualifiedName(); - + /** - * Returns the fully qualified name of this type, - * including qualification for any containing types and packages. - * This is the name of the package, followed by '.', - * followed by the type-qualified name using the enclosingTypeSeparator. + * Returns the fully qualified name of this type, including qualification + * for any containing types and packages. This is the name of the package, + * followed by '.', followed by the type-qualified name + * using the enclosingTypeSeparator. * * For example: *
      - *
    • the fully qualified name of a class B defined as a member of a class A in a compilation unit A.java - * in a package x.y using the '.' separator is "x.y.A.B"
    • - *
    • the fully qualified name of a class B defined as a member of a class A in a compilation unit A.java - * in a package x.y using the '$' separator is "x.y.A$B"
    • - *
    • the fully qualified name of a binary type whose class file is x/y/A$B.class - * using the '.' separator is "x.y.A.B"
    • - *
    • the fully qualified name of a binary type whose class file is x/y/A$B.class - * using the '$' separator is "x.y.A$B"
    • - *
    • the fully qualified name of an anonymous binary type whose class file is x/y/A$1.class - * using the '.' separator is "x.y.A$1"
    • + *
    • the fully qualified name of a class B defined as a member of a class + * A in a compilation unit A.java in a package x.y using the '.' separator + * is "x.y.A.B"
    • + *
    • the fully qualified name of a class B defined as a member of a class + * A in a compilation unit A.java in a package x.y using the '$' separator + * is "x.y.A$B"
    • + *
    • the fully qualified name of a binary type whose class file is + * x/y/A$B.class using the '.' separator is "x.y.A.B"
    • + *
    • the fully qualified name of a binary type whose class file is + * x/y/A$B.class using the '$' separator is "x.y.A$B"
    • + *
    • the fully qualified name of an anonymous binary type whose class + * file is x/y/A$1.class using the '.' separator is "x.y.A$1"
    • *
    * * This is a handle-only method. - * - * @param enclosingTypeSeparator the given enclosing type separator - * @return the fully qualified name of this type, including qualification for any containing types and packages + * + * @param enclosingTypeSeparator + * the given enclosing type separator + * @return the fully qualified name of this type, including qualification + * for any containing types and packages * @see IType#getTypeQualifiedName(char) * @since 2.0 */ String getFullyQualifiedName(char enclosingTypeSeparator); - - /** - * Returns the initializer with the specified position relative to - * the order they are defined in the source. - * Numbering starts at 1 (thus the first occurrence is occurrence 1, not occurrence 0). - * This is a handle-only method. The initializer may or may not be present. - * - * @param occurrenceCount the specified position - * @return the initializer with the specified position relative to the order they are defined in the source - */ -// IInitializer getInitializer(int occurrenceCount); - - /** - * Returns the initializers declared by this type. - * For binary types this is an empty collection. - * If this is a source type, the results are listed in the order - * in which they appear in the source. - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. + + /** + * Returns the initializer with the specified position relative to the order + * they are defined in the source. Numbering starts at 1 (thus the first + * occurrence is occurrence 1, not occurrence 0). This is a handle-only + * method. The initializer may or may not be present. + * + * @param occurrenceCount + * the specified position + * @return the initializer with the specified position relative to the order + * they are defined in the source + */ + // IInitializer getInitializer(int occurrenceCount); + /** + * Returns the initializers declared by this type. For binary types this is + * an empty collection. If this is a source type, the results are listed in + * the order in which they appear in the source. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. * @return the initializers declared by this type */ -// IInitializer[] getInitializers() throws JavaModelException; - + // IInitializer[] getInitializers() throws JavaModelException; /** - * Returns the method with the specified name and parameter types - * in this type (for example, "foo", {"I", "QString;"}). To get the - * handle for a constructor, the name specified must be the simple - * name of the enclosing type. - * This is a handle-only method. The method may or may not be present. + * Returns the method with the specified name and parameter types in this + * type (for example, "foo", {"I", "QString;"}). To get the + * handle for a constructor, the name specified must be the simple name of + * the enclosing type. This is a handle-only method. The method may or may + * not be present. * - * @param name the given name - * @param parameterTypeSignatures the given parameter types - * @return the method with the specified name and parameter types in this type + * @param name + * the given name + * @param parameterTypeSignatures + * the given parameter types + * @return the method with the specified name and parameter types in this + * type */ IMethod getMethod(String name, String[] parameterTypeSignatures); - - /** - * Returns the methods and constructors declared by this type. - * For binary types, this may include the special <clinit>; method - * and synthetic methods. - * If this is a source type, the results are listed in the order - * in which they appear in the source, otherwise, the results are - * in no particular order. - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. + + /** + * Returns the methods and constructors declared by this type. For binary + * types, this may include the special <clinit>; method + * and synthetic methods. If this is a source type, the results are listed + * in the order in which they appear in the source, otherwise, the results + * are in no particular order. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. * @return the methods and constructors declared by this type */ IMethod[] getMethods() throws JavaModelException; - + /** - * Returns the package fragment in which this element is defined. - * This is a handle-only method. + * Returns the package fragment in which this element is defined. This is a + * handle-only method. * * @return the package fragment in which this element is defined */ IPackageFragment getPackageFragment(); - - /** - * Returns the name of this type's superclass, or null - * for source types that do not specify a superclass. - * For interfaces, the superclass name is always "java.lang.Object". - * For source types, the name as declared is returned, for binary types, - * the resolved, qualified name is returned. - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. - * @return the name of this type's superclass, or null for source types that do not specify a superclass + + /** + * Returns the name of this type's superclass, or null for + * source types that do not specify a superclass. For interfaces, the + * superclass name is always "java.lang.Object". For source + * types, the name as declared is returned, for binary types, the resolved, + * qualified name is returned. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. + * @return the name of this type's superclass, or null for + * source types that do not specify a superclass */ String getSuperclassName() throws JavaModelException; - - /** - * Returns the names of interfaces that this type implements or extends, - * in the order in which they are listed in the source. - * For classes, this gives the interfaces that this class implements. - * For interfaces, this gives the interfaces that this interface extends. - * An empty collection is returned if this type does not implement or - * extend any interfaces. For source types, simple names are returned, - * for binary types, qualified names are returned. - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. - * @return the names of interfaces that this type implements or extends, in the order in which they are listed in the source, - * an empty collection if none + + /** + * Returns the names of interfaces that this type implements or extends, in + * the order in which they are listed in the source. For classes, this gives + * the interfaces that this class implements. For interfaces, this gives the + * interfaces that this interface extends. An empty collection is returned + * if this type does not implement or extend any interfaces. For source + * types, simple names are returned, for binary types, qualified names are + * returned. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. + * @return the names of interfaces that this type implements or extends, in + * the order in which they are listed in the source, an empty + * collection if none */ String[] getSuperInterfaceNames() throws JavaModelException; - + /** * Returns the member type declared in this type with the given simple name. * This is a handle-only method. The type may or may not exist. * - * @param the given simple name + * @param the + * given simple name * @return the member type declared in this type with the given simple name */ IType getType(String name); - - /** - * Returns the type-qualified name of this type, - * including qualification for any enclosing types, - * but not including package qualification. - * For source types, this consists of the simple names of - * any enclosing types, separated by "$", followed by the simple name of this type. - * For binary types, this is the name of the class file without the ".class" suffix. - * This is a handle-only method. + + /** + * Returns the type-qualified name of this type, including qualification for + * any enclosing types, but not including package qualification. For source + * types, this consists of the simple names of any enclosing types, + * separated by "$", followed by the simple name of this + * type. For binary types, this is the name of the class file without the + * ".class" suffix. This is a handle-only method. * * @return the type-qualified name of this type */ String getTypeQualifiedName(); - + /** - * Returns the type-qualified name of this type, - * including qualification for any enclosing types, - * but not including package qualification. - * This consists of the simple names of any enclosing types, - * separated by the enclosingTypeSeparator, - * followed by the simple name of this type. + * Returns the type-qualified name of this type, including qualification for + * any enclosing types, but not including package qualification. This + * consists of the simple names of any enclosing types, separated by the + * enclosingTypeSeparator, followed by the simple name of + * this type. * * For example: *
      - *
    • the type qualified name of a class B defined as a member of a class A - * using the '.' separator is "A.B"
    • - *
    • the type qualified name of a class B defined as a member of a class A - * using the '$' separator is "A$B"
    • - *
    • the type qualified name of a binary type whose class file is A$B.class - * using the '.' separator is "A.B"
    • - *
    • the type qualified name of a binary type whose class file is A$B.class - * using the '$' separator is "A$B"
    • - *
    • the type qualified name of an anonymous binary type whose class file is A$1.class - * using the '.' separator is "A$1"
    • + *
    • the type qualified name of a class B defined as a member of a class + * A using the '.' separator is "A.B"
    • + *
    • the type qualified name of a class B defined as a member of a class + * A using the '$' separator is "A$B"
    • + *
    • the type qualified name of a binary type whose class file is + * A$B.class using the '.' separator is "A.B"
    • + *
    • the type qualified name of a binary type whose class file is + * A$B.class using the '$' separator is "A$B"
    • + *
    • the type qualified name of an anonymous binary type whose class file + * is A$1.class using the '.' separator is "A$1"
    • *
    - * + * * This is a handle-only method. * - * @param enclosingTypeSeparator the specified enclosing type separator + * @param enclosingTypeSeparator + * the specified enclosing type separator * @return the type-qualified name of this type * @since 2.0 */ String getTypeQualifiedName(char enclosingTypeSeparator); - + /** - * Returns the immediate member types declared by this type. - * The results are listed in the order in which they appear in the source or class file. - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. + * Returns the immediate member types declared by this type. The results are + * listed in the order in which they appear in the source or class file. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. * @return the immediate member types declared by this type */ IType[] getTypes() throws JavaModelException; - + /** * Returns whether this type represents an anonymous type. - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. * @return true if this type represents an anonymous type, false otherwise * @since 2.0 */ @@ -438,27 +511,30 @@ public interface IType extends IMember, IParent { /** * Returns whether this type represents a class. - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. * @return true if this type represents a class, false otherwise */ boolean isClass() throws JavaModelException; - + /** * Returns whether this type represents an interface. - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. * @return true if this type represents an interface, false otherwise */ boolean isInterface() throws JavaModelException; - + /** * Returns whether this type represents a local type. - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. * @return true if this type represents a local type, false otherwise * @since 2.0 */ @@ -466,16 +542,17 @@ public interface IType extends IMember, IParent { /** * Returns whether this type represents a member type. - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. * @return true if this type represents a member type, false otherwise * @since 2.0 */ boolean isMember() throws JavaModelException; /** - * Loads a previously saved ITypeHierarchy from an input stream. A type hierarchy can - * be stored using ITypeHierachy#store(OutputStream). + * Loads a previously saved ITypeHierarchy from an input stream. A type + * hierarchy can be stored using ITypeHierachy#store(OutputStream). * * Only hierarchies originally created by the following methods can be load: *
      @@ -484,126 +561,159 @@ public interface IType extends IMember, IParent { *
    • IType#newTypeHierarchy(IProgressMonitor)
    • * * - * @param input stream where hierarchy will be read - * @param monitor the given progress monitor + * @param input + * stream where hierarchy will be read + * @param monitor + * the given progress monitor * @return the stored hierarchy - * @exception JavaModelException if the hierarchy could not be restored, reasons include: - * - type is not the focus of the hierarchy or - * - unable to read the input stream (wrong format, IOException during reading, ...) + * @exception JavaModelException + * if the hierarchy could not be restored, reasons include: - + * type is not the focus of the hierarchy or - unable to read + * the input stream (wrong format, IOException during + * reading, ...) * @see ITypeHierarchy#store(OutputStream, IProgressMonitor) * @since 2.1 */ -// ITypeHierarchy loadTypeHierachy(InputStream input, IProgressMonitor monitor) throws JavaModelException; - /** - * Creates and returns a type hierarchy for this type containing - * this type and all of its supertypes. - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. - * @param monitor the given progress monitor - * @return a type hierarchy for this type containing this type and all of its supertypes - */ -// ITypeHierarchy newSupertypeHierarchy(IProgressMonitor monitor) throws JavaModelException; - + // ITypeHierarchy loadTypeHierachy(InputStream input, IProgressMonitor + // monitor) throws JavaModelException; /** - * Creates and returns a type hierarchy for this type containing - * this type and all of its supertypes, considering types in the given - * working copies. In other words, the list of working copies will take - * precedence over their original compilation units in the workspace. + * Creates and returns a type hierarchy for this type containing this type + * and all of its supertypes. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. + * @param monitor + * the given progress monitor + * @return a type hierarchy for this type containing this type and all of + * its supertypes + */ + // ITypeHierarchy newSupertypeHierarchy(IProgressMonitor monitor) throws + // JavaModelException; + /** + * Creates and returns a type hierarchy for this type containing this type + * and all of its supertypes, considering types in the given working copies. + * In other words, the list of working copies will take precedence over + * their original compilation units in the workspace. *

      - * Note that passing an empty working copy will be as if the original compilation - * unit had been deleted. - * - * @param workingCopies the working copies that take precedence over their original compilation units - * @param monitor the given progress monitor - * @return a type hierarchy for this type containing this type and all of its supertypes - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. + * Note that passing an empty working copy will be as if the original + * compilation unit had been deleted. + * + * @param workingCopies + * the working copies that take precedence over their original + * compilation units + * @param monitor + * the given progress monitor + * @return a type hierarchy for this type containing this type and all of + * its supertypes + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. * @since 2.0 */ -// ITypeHierarchy newSupertypeHierarchy(IWorkingCopy[] workingCopies, IProgressMonitor monitor) -// throws JavaModelException; - - /** - * Creates and returns a type hierarchy for this type containing - * this type, all of its supertypes, and all its subtypes in the workspace. - * - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. - * @param monitor the given progress monitor - * @return a type hierarchy for this type containing - * this type, all of its supertypes, and all its subtypes in the workspace - */ -// ITypeHierarchy newTypeHierarchy(IProgressMonitor monitor) throws JavaModelException; - - /** - * Creates and returns a type hierarchy for this type containing - * this type, all of its supertypes, and all its subtypes in the workspace, - * considering types in the given working copies. In other words, the list of working - * copies that will take precedence over their original compilation units in the workspace. + // ITypeHierarchy newSupertypeHierarchy(IWorkingCopy[] workingCopies, + // IProgressMonitor monitor) + // throws JavaModelException; + /** + * Creates and returns a type hierarchy for this type containing this type, + * all of its supertypes, and all its subtypes in the workspace. + * + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. + * @param monitor + * the given progress monitor + * @return a type hierarchy for this type containing this type, all of its + * supertypes, and all its subtypes in the workspace + */ + // ITypeHierarchy newTypeHierarchy(IProgressMonitor monitor) throws + // JavaModelException; + /** + * Creates and returns a type hierarchy for this type containing this type, + * all of its supertypes, and all its subtypes in the workspace, considering + * types in the given working copies. In other words, the list of working + * copies that will take precedence over their original compilation units in + * the workspace. *

      - * Note that passing an empty working copy will be as if the original compilation - * unit had been deleted. - * - * @param workingCopies the working copies that take precedence over their original compilation units - * @param monitor the given progress monitor - * @return a type hierarchy for this type containing - * this type, all of its supertypes, and all its subtypes in the workspace - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. + * Note that passing an empty working copy will be as if the original + * compilation unit had been deleted. + * + * @param workingCopies + * the working copies that take precedence over their original + * compilation units + * @param monitor + * the given progress monitor + * @return a type hierarchy for this type containing this type, all of its + * supertypes, and all its subtypes in the workspace + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. * @since 2.0 */ -// ITypeHierarchy newTypeHierarchy(IWorkingCopy[] workingCopies, IProgressMonitor monitor) throws JavaModelException; + // ITypeHierarchy newTypeHierarchy(IWorkingCopy[] workingCopies, + // IProgressMonitor monitor) throws JavaModelException; /** - * Creates and returns a type hierarchy for this type containing - * this type, all of its supertypes, and all its subtypes in the workspace, - * considering types in the working copies with the given owner. - * In other words, the owner's working copies will take - * precedence over their original compilation units in the workspace. + * Creates and returns a type hierarchy for this type containing this type, + * all of its supertypes, and all its subtypes in the workspace, considering + * types in the working copies with the given owner. In other words, the + * owner's working copies will take precedence over their original + * compilation units in the workspace. *

      - * Note that if a working copy is empty, it will be as if the original compilation - * unit had been deleted. + * Note that if a working copy is empty, it will be as if the original + * compilation unit had been deleted. *

      - * - * @param owner the owner of working copies that take precedence over their original compilation units - * @param monitor the given progress monitor - * @return a type hierarchy for this type containing - * this type, all of its supertypes, and all its subtypes in the workspace - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. + * + * @param owner + * the owner of working copies that take precedence over their + * original compilation units + * @param monitor + * the given progress monitor + * @return a type hierarchy for this type containing this type, all of its + * supertypes, and all its subtypes in the workspace + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. * @since 3.0 */ -// ITypeHierarchy newTypeHierarchy(WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaModelException; - - /** - * Creates and returns a type hierarchy for this type containing - * this type, all of its supertypes, and all its subtypes - * in the context of the given project. - * - * @param project the given project - * @param monitor the given progress monitor - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. - * @return a type hierarchy for this type containing - * this type, all of its supertypes, and all its subtypes - * in the context of the given project - */ -// ITypeHierarchy newTypeHierarchy(IJavaProject project, IProgressMonitor monitor) throws JavaModelException; - - /** - * Resolves the given type name within the context of this type (depending on the type hierarchy - * and its imports). Multiple answers might be found in case there are ambiguous matches. - * - * Each matching type name is decomposed as an array of two strings, the first denoting the package - * name (dot-separated) and the second being the type name. - * Returns null if unable to find any matching type. - * + // ITypeHierarchy newTypeHierarchy(WorkingCopyOwner owner, IProgressMonitor + // monitor) throws JavaModelException; + /** + * Creates and returns a type hierarchy for this type containing this type, + * all of its supertypes, and all its subtypes in the context of the given + * project. + * + * @param project + * the given project + * @param monitor + * the given progress monitor + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. + * @return a type hierarchy for this type containing this type, all of its + * supertypes, and all its subtypes in the context of the given + * project + */ + // ITypeHierarchy newTypeHierarchy(IJavaProject project, IProgressMonitor + // monitor) throws JavaModelException; + /** + * Resolves the given type name within the context of this type (depending + * on the type hierarchy and its imports). Multiple answers might be found + * in case there are ambiguous matches. + * + * Each matching type name is decomposed as an array of two strings, the + * first denoting the package name (dot-separated) and the second being the + * type name. Returns null if unable to find any matching + * type. + * * For example, resolution of "Object" would typically return * {{"java.lang", "Object"}}. * - * @param typeName the given type name - * @exception JavaModelException if code resolve could not be performed. - * @return the resolved type names or null if unable to find any matching type - */ -// String[][] resolveType(String typeName) throws JavaModelException; + * @param typeName + * the given type name + * @exception JavaModelException + * if code resolve could not be performed. + * @return the resolved type names or null if unable to find + * any matching type + */ + // String[][] resolveType(String typeName) throws JavaModelException; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ITypeHierarchy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ITypeHierarchy.java index 339fba1..60fcc76 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ITypeHierarchy.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ITypeHierarchy.java @@ -18,286 +18,332 @@ import org.eclipse.core.runtime.IProgressMonitor; * A type hierarchy provides navigations between a type and its resolved * supertypes and subtypes for a specific type or for all types within a region. * Supertypes may extend outside of the type hierarchy's region in which it was - * created such that the root of the hierarchy is always included. For example, if a type - * hierarchy is created for a java.io.File, and the region the hierarchy was - * created in is the package fragment java.io, the supertype - * java.lang.Object will still be included. + * created such that the root of the hierarchy is always included. For example, + * if a type hierarchy is created for a java.io.File, and the + * region the hierarchy was created in is the package fragment + * java.io, the supertype java.lang.Object will + * still be included. *

      - * A type hierarchy is static and can become stale. Although consistent when - * created, it does not automatically track changes in the model. - * As changes in the model potentially invalidate the hierarchy, change notifications - * are sent to registered ITypeHierarchyChangedListeners. Listeners should - * use the exists method to determine if the hierarchy has become completely - * invalid (for example, when the type or project the hierarchy was created on - * has been removed). To refresh a hierarchy, use the refresh method. + * A type hierarchy is static and can become stale. Although consistent when + * created, it does not automatically track changes in the model. As changes in + * the model potentially invalidate the hierarchy, change notifications are sent + * to registered ITypeHierarchyChangedListeners. Listeners + * should use the exists method to determine if the hierarchy has + * become completely invalid (for example, when the type or project the + * hierarchy was created on has been removed). To refresh a hierarchy, use the + * refresh method. *

      *

      - * The type hierarchy may contain cycles due to malformed supertype declarations. - * Most type hierarchy queries are oblivious to cycles; the getAll* - * methods are implemented such that they are unaffected by cycles. + * The type hierarchy may contain cycles due to malformed supertype + * declarations. Most type hierarchy queries are oblivious to cycles; the + * getAll* methods are implemented such that they are unaffected + * by cycles. *

      *

      * This interface is not intended to be implemented by clients. *

      */ public interface ITypeHierarchy { -/** - * Adds the given listener for changes to this type hierarchy. Listeners are - * notified when this type hierarchy changes and needs to be refreshed. - * Has no effect if an identical listener is already registered. - * - * @param listener the listener - */ -void addTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener); -/** - * Returns whether the given type is part of this hierarchy. - * - * @param type the given type - * @return true if the given type is part of this hierarchy, false otherwise - */ -boolean contains(IType type); -/** - * Returns whether the type and project this hierarchy was created on exist. - * @return true if the type and project this hierarchy was created on exist, false otherwise - */ -boolean exists(); -/** - * Returns all classes in this type hierarchy's graph, in no particular - * order. Any classes in the creation region which were not resolved to - * have any subtypes or supertypes are not included in the result. - * - * @return all classes in this type hierarchy's graph - */ -IType[] getAllClasses(); -/** - * Returns all interfaces in this type hierarchy's graph, in no particular - * order. Any interfaces in the creation region which were not resolved to - * have any subtypes or supertypes are not included in the result. - * - * @return all interfaces in this type hierarchy's graph - */ -IType[] getAllInterfaces(); -/** - * Returns all resolved subtypes (direct and indirect) of the - * given type, in no particular order, limited to the - * types in this type hierarchy's graph. An empty array - * is returned if there are no resolved subtypes for the - * given type. - * - * @param type the given type - * @return all resolved subtypes (direct and indirect) of the given type - */ -IType[] getAllSubtypes(IType type); -/** - * Returns all resolved superclasses of the - * given class, in bottom-up order. An empty array - * is returned if there are no resolved superclasses for the - * given class. - * - *

      NOTE: once a type hierarchy has been created, it is more efficient to - * query the hierarchy for superclasses than to query a class recursively up - * the superclass chain. Querying an element performs a dynamic resolution, - * whereas the hierarchy returns a pre-computed result. - * - * @param type the given type - * @return all resolved superclasses of the given class, in bottom-up order, an empty - * array if none. - */ -IType[] getAllSuperclasses(IType type); -/** - * Returns all resolved superinterfaces (direct and indirect) of the given type. - * If the given type is a class, this includes all superinterfaces of all superclasses. - * An empty array is returned if there are no resolved superinterfaces for the - * given type. - * - *

      NOTE: once a type hierarchy has been created, it is more efficient to - * query the hierarchy for superinterfaces than to query a type recursively. - * Querying an element performs a dynamic resolution, - * whereas the hierarchy returns a pre-computed result. - * - * @param type the given type - * @return all resolved superinterfaces (direct and indirect) of the given type, an empty array if none - */ -IType[] getAllSuperInterfaces(IType type); -/** - * Returns all resolved supertypes of the - * given type, in bottom-up order. An empty array - * is returned if there are no resolved supertypes for the - * given type. - *

      - * Note that java.lang.Object is NOT considered to be a supertype - * of any interface type. - *

      NOTE: once a type hierarchy has been created, it is more efficient to - * query the hierarchy for supertypes than to query a type recursively up - * the supertype chain. Querying an element performs a dynamic resolution, - * whereas the hierarchy returns a pre-computed result. - * - * @param type the given type - * @return all resolved supertypes of the given class, in bottom-up order, an empty array - * if none - */ -IType[] getAllSupertypes(IType type); -/** - * Returns all types in this type hierarchy's graph, in no particular - * order. Any types in the creation region which were not resolved to - * have any subtypes or supertypes are not included in the result. - * - * @return all types in this type hierarchy's grap - */ -IType[] getAllTypes(); + /** + * Adds the given listener for changes to this type hierarchy. Listeners are + * notified when this type hierarchy changes and needs to be refreshed. Has + * no effect if an identical listener is already registered. + * + * @param listener + * the listener + */ + void addTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener); -/** - * Return the flags associated with the given type (would be equivalent to IMember.getFlags()), - * or -1 if this information wasn't cached on the hierarchy during its computation. - * - * @param type the given type - * @return the modifier flags for this member - * @see Flags - * @since 2.0 - */ -int getCachedFlags(IType type); + /** + * Returns whether the given type is part of this hierarchy. + * + * @param type + * the given type + * @return true if the given type is part of this hierarchy, false otherwise + */ + boolean contains(IType type); -/** - * Returns all interfaces resolved to extend the given interface, - * in no particular order, limited to the interfaces in this - * hierarchy's graph. - * Returns an empty collection if the given type is a class, or - * if no interfaces were resolved to extend the given interface. - * - * @param type the given type - * @return all interfaces resolved to extend the given interface limited to the interfaces in this - * hierarchy's graph, an empty array if none. - */ -IType[] getExtendingInterfaces(IType type); -/** - * Returns all classes resolved to implement the given interface, - * in no particular order, limited to the classes in this type - * hierarchy's graph. Returns an empty collection if the given type is a - * class, or if no classes were resolved to implement the given - * interface. - * - * @param type the given type - * @return all classes resolved to implement the given interface limited to the classes in this type - * hierarchy's graph, an empty array if none - */ -IType[] getImplementingClasses(IType type); -/** - * Returns all classes in the graph which have no resolved superclass, - * in no particular order. - * - * @return all classes in the graph which have no resolved superclass - */ -IType[] getRootClasses(); -/** - * Returns all interfaces in the graph which have no resolved superinterfaces, - * in no particular order. - * - * @return all interfaces in the graph which have no resolved superinterfaces - */ -IType[] getRootInterfaces(); -/** - * Returns the direct resolved subclasses of the given class, - * in no particular order, limited to the classes in this - * type hierarchy's graph. - * Returns an empty collection if the given type is an interface, - * or if no classes were resolved to be subclasses of the given - * class. - * - * @param type the given type - * @return the direct resolved subclasses of the given class limited to the classes in this - * type hierarchy's graph, an empty collection if none. - */ -IType[] getSubclasses(IType type); -/** - * Returns the direct resolved subtypes of the given type, - * in no particular order, limited to the types in this - * type hierarchy's graph. - * If the type is a class, this returns the resolved subclasses. - * If the type is an interface, this returns both the classes which implement - * the interface and the interfaces which extend it. - * - * @param type the given type - * @return the direct resolved subtypes of the given type limited to the types in this - * type hierarchy's graph - */ -IType[] getSubtypes(IType type); -/** - * Returns the resolved superclass of the given class, - * or null if the given class has no superclass, - * the superclass could not be resolved, or if the given - * type is an interface. - * - * @param type the given type - * @return the resolved superclass of the given class, - * or null if the given class has no superclass, - * the superclass could not be resolved, or if the given - * type is an interface - */ -IType getSuperclass(IType type); -/** - * Returns the direct resolved interfaces that the given type implements or extends, - * in no particular order, limited to the interfaces in this type - * hierarchy's graph. - * For classes, this gives the interfaces that the class implements. - * For interfaces, this gives the interfaces that the interface extends. - * - * @param type the given type - * @return the direct resolved interfaces that the given type implements or extends limited to the interfaces in this type - * hierarchy's graph - */ -IType[] getSuperInterfaces(IType type); -/** - * Returns the resolved supertypes of the given type, - * in no particular order, limited to the types in this - * type hierarchy's graph. - * For classes, this returns its superclass and the interfaces that the class implements. - * For interfaces, this returns the interfaces that the interface extends. As a consequence - * java.lang.Object is NOT considered to be a supertype of any interface - * type. - * - * @param type the given type - * @return the resolved supertypes of the given type limited to the types in this - * type hierarchy's graph - */ -IType[] getSupertypes(IType type); -/** - * Returns the type this hierarchy was computed for. - * Returns null if this hierarchy was computed for a region. - * - * @return the type this hierarchy was computed for - */ -IType getType(); -/** - * Re-computes the type hierarchy reporting progress. - * - * @param monitor the given progress monitor - * @exception JavaModelException if unable to refresh the hierarchy - */ -void refresh(IProgressMonitor monitor) throws JavaModelException; -/** - * Removes the given listener from this type hierarchy. - * Has no affect if an identical listener is not registered. - * - * @param listener the listener - */ -void removeTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener); -/** - * Stores the type hierarchy in an output stream. This stored hierarchy can be load by - * IType#loadTypeHierachy(IJavaProject, InputStream, IProgressMonitor). - * Listeners of this hierarchy are not stored. - * - * Only hierarchies created by the following methods can be store: - *

        - *
      • IType#newSupertypeHierarchy(IProgressMonitor)
      • - *
      • IType#newTypeHierarchy(IJavaProject, IProgressMonitor)
      • - *
      • IType#newTypeHierarchy(IProgressMonitor)
      • - * - * - * @param outputStream output stream where the hierarchy will be stored - * @param monitor the given progress monitor - * @exception JavaModelException if unable to store the hierarchy in the ouput stream - * @see IType#loadTypeHierachy(java.io.InputStream, IProgressMonitor) - * @since 2.1 - */ -void store(OutputStream outputStream, IProgressMonitor monitor) throws JavaModelException; + /** + * Returns whether the type and project this hierarchy was created on exist. + * + * @return true if the type and project this hierarchy was created on exist, + * false otherwise + */ + boolean exists(); + + /** + * Returns all classes in this type hierarchy's graph, in no particular + * order. Any classes in the creation region which were not resolved to have + * any subtypes or supertypes are not included in the result. + * + * @return all classes in this type hierarchy's graph + */ + IType[] getAllClasses(); + + /** + * Returns all interfaces in this type hierarchy's graph, in no particular + * order. Any interfaces in the creation region which were not resolved to + * have any subtypes or supertypes are not included in the result. + * + * @return all interfaces in this type hierarchy's graph + */ + IType[] getAllInterfaces(); + + /** + * Returns all resolved subtypes (direct and indirect) of the given type, in + * no particular order, limited to the types in this type hierarchy's graph. + * An empty array is returned if there are no resolved subtypes for the + * given type. + * + * @param type + * the given type + * @return all resolved subtypes (direct and indirect) of the given type + */ + IType[] getAllSubtypes(IType type); + + /** + * Returns all resolved superclasses of the given class, in bottom-up order. + * An empty array is returned if there are no resolved superclasses for the + * given class. + * + *

        + * NOTE: once a type hierarchy has been created, it is more efficient to + * query the hierarchy for superclasses than to query a class recursively up + * the superclass chain. Querying an element performs a dynamic resolution, + * whereas the hierarchy returns a pre-computed result. + * + * @param type + * the given type + * @return all resolved superclasses of the given class, in bottom-up order, + * an empty array if none. + */ + IType[] getAllSuperclasses(IType type); + + /** + * Returns all resolved superinterfaces (direct and indirect) of the given + * type. If the given type is a class, this includes all superinterfaces of + * all superclasses. An empty array is returned if there are no resolved + * superinterfaces for the given type. + * + *

        + * NOTE: once a type hierarchy has been created, it is more efficient to + * query the hierarchy for superinterfaces than to query a type recursively. + * Querying an element performs a dynamic resolution, whereas the hierarchy + * returns a pre-computed result. + * + * @param type + * the given type + * @return all resolved superinterfaces (direct and indirect) of the given + * type, an empty array if none + */ + IType[] getAllSuperInterfaces(IType type); + + /** + * Returns all resolved supertypes of the given type, in bottom-up order. An + * empty array is returned if there are no resolved supertypes for the given + * type. + *

        + * Note that java.lang.Object is NOT considered to be a + * supertype of any interface type. + *

        + *

        + * NOTE: once a type hierarchy has been created, it is more efficient to + * query the hierarchy for supertypes than to query a type recursively up + * the supertype chain. Querying an element performs a dynamic resolution, + * whereas the hierarchy returns a pre-computed result. + * + * @param type + * the given type + * @return all resolved supertypes of the given class, in bottom-up order, + * an empty array if none + */ + IType[] getAllSupertypes(IType type); + + /** + * Returns all types in this type hierarchy's graph, in no particular order. + * Any types in the creation region which were not resolved to have any + * subtypes or supertypes are not included in the result. + * + * @return all types in this type hierarchy's grap + */ + IType[] getAllTypes(); + + /** + * Return the flags associated with the given type (would be equivalent to + * IMember.getFlags()), or -1 if this + * information wasn't cached on the hierarchy during its computation. + * + * @param type + * the given type + * @return the modifier flags for this member + * @see Flags + * @since 2.0 + */ + int getCachedFlags(IType type); + + /** + * Returns all interfaces resolved to extend the given interface, in no + * particular order, limited to the interfaces in this hierarchy's graph. + * Returns an empty collection if the given type is a class, or if no + * interfaces were resolved to extend the given interface. + * + * @param type + * the given type + * @return all interfaces resolved to extend the given interface limited to + * the interfaces in this hierarchy's graph, an empty array if none. + */ + IType[] getExtendingInterfaces(IType type); + + /** + * Returns all classes resolved to implement the given interface, in no + * particular order, limited to the classes in this type hierarchy's graph. + * Returns an empty collection if the given type is a class, or if no + * classes were resolved to implement the given interface. + * + * @param type + * the given type + * @return all classes resolved to implement the given interface limited to + * the classes in this type hierarchy's graph, an empty array if + * none + */ + IType[] getImplementingClasses(IType type); + + /** + * Returns all classes in the graph which have no resolved superclass, in no + * particular order. + * + * @return all classes in the graph which have no resolved superclass + */ + IType[] getRootClasses(); + + /** + * Returns all interfaces in the graph which have no resolved + * superinterfaces, in no particular order. + * + * @return all interfaces in the graph which have no resolved + * superinterfaces + */ + IType[] getRootInterfaces(); + + /** + * Returns the direct resolved subclasses of the given class, in no + * particular order, limited to the classes in this type hierarchy's graph. + * Returns an empty collection if the given type is an interface, or if no + * classes were resolved to be subclasses of the given class. + * + * @param type + * the given type + * @return the direct resolved subclasses of the given class limited to the + * classes in this type hierarchy's graph, an empty collection if + * none. + */ + IType[] getSubclasses(IType type); + + /** + * Returns the direct resolved subtypes of the given type, in no particular + * order, limited to the types in this type hierarchy's graph. If the type + * is a class, this returns the resolved subclasses. If the type is an + * interface, this returns both the classes which implement the interface + * and the interfaces which extend it. + * + * @param type + * the given type + * @return the direct resolved subtypes of the given type limited to the + * types in this type hierarchy's graph + */ + IType[] getSubtypes(IType type); + + /** + * Returns the resolved superclass of the given class, or null + * if the given class has no superclass, the superclass could not be + * resolved, or if the given type is an interface. + * + * @param type + * the given type + * @return the resolved superclass of the given class, or null + * if the given class has no superclass, the superclass could not be + * resolved, or if the given type is an interface + */ + IType getSuperclass(IType type); + + /** + * Returns the direct resolved interfaces that the given type implements or + * extends, in no particular order, limited to the interfaces in this type + * hierarchy's graph. For classes, this gives the interfaces that the class + * implements. For interfaces, this gives the interfaces that the interface + * extends. + * + * @param type + * the given type + * @return the direct resolved interfaces that the given type implements or + * extends limited to the interfaces in this type hierarchy's graph + */ + IType[] getSuperInterfaces(IType type); + + /** + * Returns the resolved supertypes of the given type, in no particular + * order, limited to the types in this type hierarchy's graph. For classes, + * this returns its superclass and the interfaces that the class implements. + * For interfaces, this returns the interfaces that the interface extends. + * As a consequence java.lang.Object is NOT considered to be + * a supertype of any interface type. + * + * @param type + * the given type + * @return the resolved supertypes of the given type limited to the types in + * this type hierarchy's graph + */ + IType[] getSupertypes(IType type); + + /** + * Returns the type this hierarchy was computed for. Returns + * null if this hierarchy was computed for a region. + * + * @return the type this hierarchy was computed for + */ + IType getType(); + + /** + * Re-computes the type hierarchy reporting progress. + * + * @param monitor + * the given progress monitor + * @exception JavaModelException + * if unable to refresh the hierarchy + */ + void refresh(IProgressMonitor monitor) throws JavaModelException; + + /** + * Removes the given listener from this type hierarchy. Has no affect if an + * identical listener is not registered. + * + * @param listener + * the listener + */ + void removeTypeHierarchyChangedListener( + ITypeHierarchyChangedListener listener); + + /** + * Stores the type hierarchy in an output stream. This stored hierarchy can + * be load by IType#loadTypeHierachy(IJavaProject, InputStream, + * IProgressMonitor). Listeners of this hierarchy are not stored. + * + * Only hierarchies created by the following methods can be store: + *

          + *
        • IType#newSupertypeHierarchy(IProgressMonitor)
        • + *
        • IType#newTypeHierarchy(IJavaProject, IProgressMonitor)
        • + *
        • IType#newTypeHierarchy(IProgressMonitor)
        • + * + * + * @param outputStream + * output stream where the hierarchy will be stored + * @param monitor + * the given progress monitor + * @exception JavaModelException + * if unable to store the hierarchy in the ouput stream + * @see IType#loadTypeHierachy(java.io.InputStream, IProgressMonitor) + * @since 2.1 + */ + void store(OutputStream outputStream, IProgressMonitor monitor) + throws JavaModelException; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ITypeHierarchyChangedListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ITypeHierarchyChangedListener.java index bb09b10..ace3148 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ITypeHierarchyChangedListener.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ITypeHierarchyChangedListener.java @@ -20,10 +20,11 @@ package net.sourceforge.phpdt.core; public interface ITypeHierarchyChangedListener { /** * Notifies that the given type hierarchy has changed in some way and should - * be refreshed at some point to make it consistent with the current state of - * the Java model. + * be refreshed at some point to make it consistent with the current state + * of the Java model. * - * @param typeHierarchy the given type hierarchy + * @param typeHierarchy + * the given type hierarchy */ void typeHierarchyChanged(ITypeHierarchy typeHierarchy); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IWorkingCopy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IWorkingCopy.java index 72f4a48..e30ec1d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IWorkingCopy.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IWorkingCopy.java @@ -19,340 +19,385 @@ import org.eclipse.core.runtime.IProgressMonitor; *

          * A working copy of a Java element acts just like a regular element (handle), * except it is not attached to an underlying resource. A working copy is not - * visible to the rest of the Java model. Changes in a working copy's - * buffer are not realized in a resource. To bring the Java model up-to-date with a working - * copy's contents, an explicit commit must be performed on the working copy. - * Other operations performed on a working copy update the - * contents of the working copy's buffer but do not commit the contents - * of the working copy. + * visible to the rest of the Java model. Changes in a working copy's buffer are + * not realized in a resource. To bring the Java model up-to-date with a working + * copy's contents, an explicit commit must be performed on the working copy. + * Other operations performed on a working copy update the contents of the + * working copy's buffer but do not commit the contents of the working copy. *

          *

          - * Note: The contents of a working copy is determined when a working - * copy is created, based on the current content of the element the working - * copy is created from. If a working copy is an IOpenable and is explicitly - * closed, the working copy's buffer will be thrown away. However, clients should not - * explicitly open and close working copies. + * Note: The contents of a working copy is determined when a working copy is + * created, based on the current content of the element the working copy is + * created from. If a working copy is an IOpenable and is + * explicitly closed, the working copy's buffer will be thrown away. However, + * clients should not explicitly open and close working copies. *

          *

          - * The client that creates a working copy is responsible for - * destroying the working copy. The Java model will never automatically - * destroy or close a working copy. (Note that destroying a working copy - * does not commit it to the model, it only frees up the memory occupied by - * the element). After a working copy is destroyed, the working copy cannot - * be accessed again. Non-handle methods will throw a - * JavaModelException indicating the Java element does not exist. + * The client that creates a working copy is responsible for destroying the + * working copy. The Java model will never automatically destroy or close a + * working copy. (Note that destroying a working copy does not commit it to the + * model, it only frees up the memory occupied by the element). After a working + * copy is destroyed, the working copy cannot be accessed again. Non-handle + * methods will throw a JavaModelException indicating the Java + * element does not exist. *

          *

          - * A working copy cannot be created from another working copy. - * Calling getWorkingCopy on a working copy returns the receiver. + * A working copy cannot be created from another working copy. Calling + * getWorkingCopy on a working copy returns the receiver. *

          *

          * This interface is not intended to be implemented by clients. *

          */ public interface IWorkingCopy { - + /** - * Commits the contents of this working copy to its original element - * and underlying resource, bringing the Java model up-to-date with - * the current contents of the working copy. - * - *

          It is possible that the contents of the original resource have changed - * since this working copy was created, in which case there is an update conflict. - * The value of the force parameter effects the resolution of - * such a conflict:

            - *
          • true - in this case the contents of this working copy are applied to - * the underlying resource even though this working copy was created before - * a subsequent change in the resource
          • - *
          • false - in this case a JavaModelException is thrown
          • - *
          + * Commits the contents of this working copy to its original element and + * underlying resource, bringing the Java model up-to-date with the current + * contents of the working copy. + * *

          - * Since 2.1, a working copy can be created on a not-yet existing compilation - * unit. In particular, such a working copy can then be committed in order to create - * the corresponding compilation unit. - *

          - * @param force a flag to handle the cases when the contents of the original resource have changed - * since this working copy was created - * @param monitor the given progress monitor - * @exception JavaModelException if this working copy could not commit. Reasons include: + * It is possible that the contents of the original resource have changed + * since this working copy was created, in which case there is an update + * conflict. The value of the force parameter effects the + * resolution of such a conflict: *
            - *
          • A CoreException occurred while updating an underlying resource - *
          • This element is not a working copy (INVALID_ELEMENT_TYPES) - *
          • A update conflict (described above) (UPDATE_CONFLICT) + *
          • true - in this case the contents of this working copy + * are applied to the underlying resource even though this working copy was + * created before a subsequent change in the resource
          • + *
          • false - in this case a + * JavaModelException is thrown
          • *
          + *

          + * Since 2.1, a working copy can be created on a not-yet existing + * compilation unit. In particular, such a working copy can then be + * committed in order to create the corresponding compilation unit. + *

          + * + * @param force + * a flag to handle the cases when the contents of the original + * resource have changed since this working copy was created + * @param monitor + * the given progress monitor + * @exception JavaModelException + * if this working copy could not commit. Reasons include: + *
            + *
          • A CoreException occurred while + * updating an underlying resource + *
          • This element is not a working copy + * (INVALID_ELEMENT_TYPES) + *
          • A update conflict (described above) (UPDATE_CONFLICT) + *
          */ - void commit(boolean force, IProgressMonitor monitor) throws JavaModelException; - + void commit(boolean force, IProgressMonitor monitor) + throws JavaModelException; + /** - * Destroys this working copy, closing its buffer and discarding - * its structure. Subsequent attempts to access non-handle information - * for this working copy will result in IJavaModelExceptions. Has - * no effect if this element is not a working copy. + * Destroys this working copy, closing its buffer and discarding its + * structure. Subsequent attempts to access non-handle information for this + * working copy will result in IJavaModelExceptions. Has no + * effect if this element is not a working copy. + *

          + * If this working copy is shared, it is destroyed only when the number of + * calls to destroy() is the same as the number of calls to + * + * getSharedWorkingCopy(IProgressMonitor, IBufferFactory). + *

          *

          - * If this working copy is shared, it is destroyed only when the number of calls to - * destroy() is the same as the number of calls to - * getSharedWorkingCopy(IProgressMonitor, IBufferFactory). - *

          - * When it is destroyed, a REMOVED IJavaElementDelta is reported on this + * When it is destroyed, a REMOVED IJavaElementDelta is reported on this * working copy. *

          */ void destroy(); - + /** - * Finds the shared working copy for this element, given a IBuffer factory. - * If no working copy has been created for this element associated with this - * buffer factory, returns null. + * Finds the shared working copy for this element, given a + * IBuffer factory. If no working copy has been created for + * this element associated with this buffer factory, returns + * null. *

          - * Users of this method must not destroy the resulting working copy. + * Users of this method must not destroy the resulting working copy. * - * @param bufferFactory the given IBuffer factory - * @return the found shared working copy for this element, null if none + * @param bufferFactory + * the given IBuffer factory + * @return the found shared working copy for this element, null + * if none * @see IBufferFactory * @since 2.0 */ IJavaElement findSharedWorkingCopy(IBufferFactory bufferFactory); /** - * Returns the original element the specified working copy element was created from, - * or null if this is not a working copy element. This is a handle - * only method, the returned element may or may not exist. + * Returns the original element the specified working copy element was + * created from, or null if this is not a working copy + * element. This is a handle only method, the returned element may or may + * not exist. * - * @return the original element the specified working copy element was created from, - * or null if this is not a working copy element + * @return the original element the specified working copy element was + * created from, or null if this is not a working + * copy element */ IJavaElement getOriginal(IJavaElement workingCopyElement); - + /** - * Returns the original element this working copy was created from, - * or null if this is not a working copy. + * Returns the original element this working copy was created from, or + * null if this is not a working copy. * - * @return the original element this working copy was created from, - * or null if this is not a working copy + * @return the original element this working copy was created from, or + * null if this is not a working copy */ IJavaElement getOriginalElement(); - - /** - * Finds the elements in this compilation unit that correspond to - * the given element. - * An element A corresponds to an element B if: + + /** + * Finds the elements in this compilation unit that correspond to the given + * element. An element A corresponds to an element B if: *

            *
          • A has the same element name as B. - *
          • If A is a method, A must have the same number of arguments as - * B and the simple names of the argument types must be equals. + *
          • If A is a method, A must have the same number of arguments as B and + * the simple names of the argument types must be equals. *
          • The parent of A corresponds to the parent of B recursively up to - * their respective compilation units. + * their respective compilation units. *
          • A exists. *
          - * Returns null if no such java elements can be found - * or if the given element is not included in a compilation unit. + * Returns null if no such java elements can be found or if + * the given element is not included in a compilation unit. * - * @param element the given element - * @return the found elements in this compilation unit that correspond to the given element - * @since 2.0 + * @param element + * the given element + * @return the found elements in this compilation unit that correspond to + * the given element + * @since 2.0 */ IJavaElement[] findElements(IJavaElement element); - + /** - * Finds the primary type of this compilation unit (that is, the type with the same name as the - * compilation unit), or null if no such a type exists. + * Finds the primary type of this compilation unit (that is, the type with + * the same name as the compilation unit), or null if no such + * a type exists. * - * @return the found primary type of this compilation unit, or null if no such a type exists + * @return the found primary type of this compilation unit, or + * null if no such a type exists * @since 2.0 */ IType findPrimaryType(); - + /** - * Returns a shared working copy on this element using the given factory to create - * the buffer, or this element if this element is already a working copy. - * This API can only answer an already existing working copy if it is based on the same - * original compilation unit AND was using the same buffer factory (that is, as defined by Object.equals). + * Returns a shared working copy on this element using the given factory to + * create the buffer, or this element if this element is already a working + * copy. This API can only answer an already existing working copy if it is + * based on the same original compilation unit AND was using the same buffer + * factory (that is, as defined by Object.equals). *

          * The life time of a shared working copy is as follows: *

            - *
          • The first call to getSharedWorkingCopy(...) creates a new working copy for this - * element
          • + *
          • The first call to getSharedWorkingCopy(...) creates a + * new working copy for this element
          • *
          • Subsequent calls increment an internal counter.
          • *
          • A call to destroy() decrements the internal counter.
          • *
          • When this counter is 0, the working copy is destroyed. *
          * So users of this method must destroy exactly once the working copy. *

          - * Note that the buffer factory will be used for the life time of this working copy, that is if the - * working copy is closed then reopened, this factory will be used. - * The buffer will be automatically initialized with the original's compilation unit content - * upon creation. + * Note that the buffer factory will be used for the life time of this + * working copy, that is if the working copy is closed then reopened, this + * factory will be used. The buffer will be automatically initialized with + * the original's compilation unit content upon creation. *

          - * When the shared working copy instance is created, an ADDED IJavaElementDelta is reported on this - * working copy. - * - * @param monitor a progress monitor used to report progress while opening this compilation unit - * or null if no progress should be reported - * @param factory the factory that creates a buffer that is used to get the content of the working copy - * or null if the internal factory should be used - * @param problemRequestor a requestor which will get notified of problems detected during - * reconciling as they are discovered. The requestor can be set to null indicating - * that the client is not interested in problems. - * @exception JavaModelException if the contents of this element can - * not be determined. - * @return a shared working copy on this element using the given factory to create - * the buffer, or this element if this element is already a working copy + * When the shared working copy instance is created, an ADDED + * IJavaElementDelta is reported on this working copy. + * + * @param monitor + * a progress monitor used to report progress while opening this + * compilation unit or null if no progress should + * be reported + * @param factory + * the factory that creates a buffer that is used to get the + * content of the working copy or null if the + * internal factory should be used + * @param problemRequestor + * a requestor which will get notified of problems detected + * during reconciling as they are discovered. The requestor can + * be set to null indicating that the client is + * not interested in problems. + * @exception JavaModelException + * if the contents of this element can not be determined. + * @return a shared working copy on this element using the given factory to + * create the buffer, or this element if this element is already a + * working copy * @see IBufferFactory * @see IProblemRequestor * @since 2.0 */ - IJavaElement getSharedWorkingCopy( - IProgressMonitor monitor, - IBufferFactory factory, - IProblemRequestor problemRequestor) - throws JavaModelException; - + IJavaElement getSharedWorkingCopy(IProgressMonitor monitor, + IBufferFactory factory, IProblemRequestor problemRequestor) + throws JavaModelException; + /** - * Returns a new working copy of this element if this element is not - * a working copy, or this element if this element is already a working copy. + * Returns a new working copy of this element if this element is not a + * working copy, or this element if this element is already a working copy. *

          - * Note: if intending to share a working copy amongst several clients, then + * Note: if intending to share a working copy amongst several clients, then * #getSharedWorkingCopy should be used instead. - *

          - * When the working copy instance is created, an ADDED IJavaElementDelta is + *

          + *

          + * When the working copy instance is created, an ADDED IJavaElementDelta is * reported on this working copy. - *

          - * Since 2.1, a working copy can be created on a not-yet existing compilation - * unit. In particular, such a working copy can then be committed in order to create - * the corresponding compilation unit. *

          - * @exception JavaModelException if the contents of this element can - * not be determined. - * @return a new working copy of this element if this element is not - * a working copy, or this element if this element is already a working copy + *

          + * Since 2.1, a working copy can be created on a not-yet existing + * compilation unit. In particular, such a working copy can then be + * committed in order to create the corresponding compilation unit. + *

          + * + * @exception JavaModelException + * if the contents of this element can not be determined. + * @return a new working copy of this element if this element is not a + * working copy, or this element if this element is already a + * working copy */ IJavaElement getWorkingCopy() throws JavaModelException; - + /** - * Returns a new working copy of this element using the given factory to create - * the buffer, or this element if this element is already a working copy. - * Note that this factory will be used for the life time of this working copy, that is if the - * working copy is closed then reopened, this factory will be reused. - * The buffer will be automatically initialized with the original's compilation unit content - * upon creation. + * Returns a new working copy of this element using the given factory to + * create the buffer, or this element if this element is already a working + * copy. Note that this factory will be used for the life time of this + * working copy, that is if the working copy is closed then reopened, this + * factory will be reused. The buffer will be automatically initialized with + * the original's compilation unit content upon creation. *

          - * Note: if intending to share a working copy amongst several clients, then + * Note: if intending to share a working copy amongst several clients, then * #getSharedWorkingCopy should be used instead. - *

          - * When the working copy instance is created, an ADDED IJavaElementDelta is + *

          + *

          + * When the working copy instance is created, an ADDED IJavaElementDelta is * reported on this working copy. - *

          - * Since 2.1, a working copy can be created on a not-yet existing compilation - * unit. In particular, such a working copy can then be committed in order to create - * the corresponding compilation unit. *

          - * @param monitor a progress monitor used to report progress while opening this compilation unit - * or null if no progress should be reported - * @param factory the factory that creates a buffer that is used to get the content of the working copy - * or null if the internal factory should be used - * @param problemRequestor a requestor which will get notified of problems detected during - * reconciling as they are discovered. The requestor can be set to null indicating - * that the client is not interested in problems. - * @exception JavaModelException if the contents of this element can - * not be determined. - * @return a new working copy of this element using the given factory to create - * the buffer, or this element if this element is already a working copy + *

          + * Since 2.1, a working copy can be created on a not-yet existing + * compilation unit. In particular, such a working copy can then be + * committed in order to create the corresponding compilation unit. + *

          + * + * @param monitor + * a progress monitor used to report progress while opening this + * compilation unit or null if no progress should + * be reported + * @param factory + * the factory that creates a buffer that is used to get the + * content of the working copy or null if the + * internal factory should be used + * @param problemRequestor + * a requestor which will get notified of problems detected + * during reconciling as they are discovered. The requestor can + * be set to null indicating that the client is + * not interested in problems. + * @exception JavaModelException + * if the contents of this element can not be determined. + * @return a new working copy of this element using the given factory to + * create the buffer, or this element if this element is already a + * working copy * @since 2.0 */ - IJavaElement getWorkingCopy( - IProgressMonitor monitor, - IBufferFactory factory, - IProblemRequestor problemRequestor) - throws JavaModelException; - + IJavaElement getWorkingCopy(IProgressMonitor monitor, + IBufferFactory factory, IProblemRequestor problemRequestor) + throws JavaModelException; + /** - * Returns whether this working copy's original element's content - * has not changed since the inception of this working copy. + * Returns whether this working copy's original element's content has not + * changed since the inception of this working copy. * - * @return true if this working copy's original element's content - * has not changed since the inception of this working copy, false otherwise + * @return true if this working copy's original element's content has not + * changed since the inception of this working copy, false otherwise */ boolean isBasedOn(IResource resource); - + /** * Returns whether this element is a working copy. * * @return true if this element is a working copy, false otherwise */ boolean isWorkingCopy(); - + /** - * Reconciles the contents of this working copy. - * It performs the reconciliation by locally caching the contents of - * the working copy, updating the contents, then creating a delta - * over the cached contents and the new contents, and finally firing - * this delta. + * Reconciles the contents of this working copy. It performs the + * reconciliation by locally caching the contents of the working copy, + * updating the contents, then creating a delta over the cached contents and + * the new contents, and finally firing this delta. *

          * If the working copy hasn't changed, then no problem will be detected, * this is equivalent to IWorkingCopy#reconcile(false, null). *

          * Compilation problems found in the new contents are notified through the - * IProblemRequestor interface which was passed at - * creation, and no longer as transient markers. Therefore this API will - * return null. + * IProblemRequestor interface which was passed at creation, + * and no longer as transient markers. Therefore this API will return + * null. *

          - * Note: It has been assumed that added inner types should - * not generate change deltas. The implementation has been - * modified to reflect this assumption. - * - * @exception JavaModelException if the contents of the original element - * cannot be accessed. Reasons include: - *

            - *
          • The original Java element does not exist (ELEMENT_DOES_NOT_EXIST)
          • - *
          + * Note: It has been assumed that added inner types should not generate + * change deltas. The implementation has been modified to reflect this + * assumption. + * + * @exception JavaModelException + * if the contents of the original element cannot be + * accessed. Reasons include: + *
            + *
          • The original Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
          • + *
          * @return null */ IMarker[] reconcile() throws JavaModelException; - + /** - * Reconciles the contents of this working copy. - * It performs the reconciliation by locally caching the contents of - * the working copy, updating the contents, then creating a delta - * over the cached contents and the new contents, and finally firing - * this delta. + * Reconciles the contents of this working copy. It performs the + * reconciliation by locally caching the contents of the working copy, + * updating the contents, then creating a delta over the cached contents and + * the new contents, and finally firing this delta. *

          * The boolean argument allows to force problem detection even if the * working copy is already consistent. *

          * Compilation problems found in the new contents are notified through the - * IProblemRequestor interface which was passed at - * creation, and no longer as transient markers. Therefore this API answers - * nothing. + * IProblemRequestor interface which was passed at creation, + * and no longer as transient markers. Therefore this API answers nothing. *

          - * Note: It has been assumed that added inner types should - * not generate change deltas. The implementation has been - * modified to reflect this assumption. - * - * @param forceProblemDetection boolean indicating whether problem should be recomputed - * even if the source hasn't changed. - * @param monitor a progress monitor - * @exception JavaModelException if the contents of the original element - * cannot be accessed. Reasons include: - *

            - *
          • The original Java element does not exist (ELEMENT_DOES_NOT_EXIST)
          • - *
          + * Note: It has been assumed that added inner types should not generate + * change deltas. The implementation has been modified to reflect this + * assumption. + * + * @param forceProblemDetection + * boolean indicating whether problem should be recomputed even + * if the source hasn't changed. + * @param monitor + * a progress monitor + * @exception JavaModelException + * if the contents of the original element cannot be + * accessed. Reasons include: + *
            + *
          • The original Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
          • + *
          * @since 2.0 */ - void reconcile(boolean forceProblemDetection, IProgressMonitor monitor) throws JavaModelException; + void reconcile(boolean forceProblemDetection, IProgressMonitor monitor) + throws JavaModelException; /** * Restores the contents of this working copy to the current contents of - * this working copy's original element. Has no effect if this element - * is not a working copy. - * - *

          Note: This is the inverse of committing the content of the - * working copy to the original element with commit(boolean, IProgressMonitor). - * - * @exception JavaModelException if the contents of the original element - * cannot be accessed. Reasons include: - *

            - *
          • The original Java element does not exist (ELEMENT_DOES_NOT_EXIST)
          • - *
          + * this working copy's original element. Has no effect if this element is + * not a working copy. + * + *

          + * Note: This is the inverse of committing the content of the working copy + * to the original element with + * commit(boolean, IProgressMonitor). + * + * @exception JavaModelException + * if the contents of the original element cannot be + * accessed. Reasons include: + *

            + *
          • The original Java element does not exist + * (ELEMENT_DOES_NOT_EXIST)
          • + *
          */ void restore() throws JavaModelException; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaConventions.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaConventions.java index 603da89..a8c48f2 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaConventions.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaConventions.java @@ -30,13 +30,14 @@ import org.eclipse.core.runtime.Status; /** * Provides methods for checking Java-specific conventions such as name syntax. *

          - * This class provides static methods and constants only; it is not intended to be - * instantiated or subclassed by clients. + * This class provides static methods and constants only; it is not intended to + * be instantiated or subclassed by clients. *

          */ public final class JavaConventions { - private final static char DOT= '.'; + private final static char DOT = '.'; + private final static Scanner SCANNER = new Scanner(); private JavaConventions() { @@ -44,36 +45,44 @@ public final class JavaConventions { } /** - * Returns whether the given package fragment root paths are considered - * to overlap. + * Returns whether the given package fragment root paths are considered to + * overlap. *

          * Two root paths overlap if one is a prefix of the other, or they point to * the same location. However, a JAR is allowed to be nested in a root. - * - * @param rootPath1 the first root path - * @param rootPath2 the second root path - * @return true if the given package fragment root paths are considered to overlap, false otherwise + * + * @param rootPath1 + * the first root path + * @param rootPath2 + * the second root path + * @return true if the given package fragment root paths are considered to + * overlap, false otherwise * @deprecated Overlapping roots are allowed in 2.1 */ public static boolean isOverlappingRoots(IPath rootPath1, IPath rootPath2) { if (rootPath1 == null || rootPath2 == null) { return false; } -// String extension1 = rootPath1.getFileExtension(); -// String extension2 = rootPath2.getFileExtension(); -// if (extension1 != null && (extension1.equalsIgnoreCase(SuffixConstants.EXTENSION_JAR) || extension1.equalsIgnoreCase(SuffixConstants.EXTENSION_ZIP))) { -// return false; -// } -// if (extension2 != null && (extension2.equalsIgnoreCase(SuffixConstants.EXTENSION_JAR) || extension2.equalsIgnoreCase(SuffixConstants.EXTENSION_ZIP))) { -// return false; -// } - return rootPath1.isPrefixOf(rootPath2) || rootPath2.isPrefixOf(rootPath1); + // String extension1 = rootPath1.getFileExtension(); + // String extension2 = rootPath2.getFileExtension(); + // if (extension1 != null && + // (extension1.equalsIgnoreCase(SuffixConstants.EXTENSION_JAR) || + // extension1.equalsIgnoreCase(SuffixConstants.EXTENSION_ZIP))) { + // return false; + // } + // if (extension2 != null && + // (extension2.equalsIgnoreCase(SuffixConstants.EXTENSION_JAR) || + // extension2.equalsIgnoreCase(SuffixConstants.EXTENSION_ZIP))) { + // return false; + // } + return rootPath1.isPrefixOf(rootPath2) + || rootPath2.isPrefixOf(rootPath1); } /* * Returns the current identifier extracted by the scanner (without unicode - * escapes) from the given id. - * Returns null if the id was not valid + * escapes) from the given id. Returns null if the id was not + * valid */ private static synchronized char[] scannedIdentifier(String id) { if (id == null) { @@ -92,49 +101,61 @@ public final class JavaConventions { } catch (ArrayIndexOutOfBoundsException e) { return null; } - int nextToken= SCANNER.getNextToken(); - if (token == ITerminalSymbols.TokenNameIdentifier - && nextToken == ITerminalSymbols.TokenNameEOF - && SCANNER.startPosition == SCANNER.source.length) { // to handle case where we had an ArrayIndexOutOfBoundsException - // while reading the last token + int nextToken = SCANNER.getNextToken(); + if (token == ITerminalSymbols.TokenNameIdentifier + && nextToken == ITerminalSymbols.TokenNameEOF + && SCANNER.startPosition == SCANNER.source.length) { // to + // handle + // case + // where + // we + // had + // an + // ArrayIndexOutOfBoundsException + // while reading the last token return currentIdentifier; } else { return null; } - } - catch (InvalidInputException e) { + } catch (InvalidInputException e) { return null; } } /** - * Validate the given compilation unit name. - * A compilation unit name must obey the following rules: + * Validate the given compilation unit name. A compilation unit name must + * obey the following rules: *

            *
          • it must not be null *
          • it must include the ".java" suffix *
          • its prefix must be a valid identifier - *
          • it must not contain any characters or substrings that are not valid - * on the file system on which workspace root is located. + *
          • it must not contain any characters or substrings that are not valid + * on the file system on which workspace root is located. *
          *

          - * @param name the name of a compilation unit - * @return a status object with code IStatus.OK if - * the given name is valid as a compilation unit name, otherwise a status - * object indicating what is wrong with the name + * + * @param name + * the name of a compilation unit + * @return a status object with code IStatus.OK if the given + * name is valid as a compilation unit name, otherwise a status + * object indicating what is wrong with the name */ public static IStatus validateCompilationUnitName(String name) { if (name == null) { - return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("convention.unit.nullName"), null); //$NON-NLS-1$ + return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util + .bind("convention.unit.nullName"), null); //$NON-NLS-1$ } - if (!net.sourceforge.phpdt.internal.compiler.util.Util.isJavaFileName(name)) { - return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("convention.unit.notJavaName"), null); //$NON-NLS-1$ + if (!net.sourceforge.phpdt.internal.compiler.util.Util + .isJavaFileName(name)) { + return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util + .bind("convention.unit.notJavaName"), null); //$NON-NLS-1$ } String identifier; int index; index = name.lastIndexOf('.'); if (index == -1) { - return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("convention.unit.notJavaName"), null); //$NON-NLS-1$ + return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util + .bind("convention.unit.notJavaName"), null); //$NON-NLS-1$ } identifier = name.substring(0, index); // JSR-175 metadata strongly recommends "package-info.java" as the @@ -146,7 +167,8 @@ public final class JavaConventions { return status; } } - IStatus status = ResourcesPlugin.getWorkspace().validateName(name, IResource.FILE); + IStatus status = ResourcesPlugin.getWorkspace().validateName(name, + IResource.FILE); if (!status.isOK()) { return status; } @@ -154,128 +176,145 @@ public final class JavaConventions { } /** - * Validate the given .class file name. - * A .class file name must obey the following rules: + * Validate the given .class file name. A .class file name must obey the + * following rules: *
            *
          • it must not be null *
          • it must include the ".class" suffix *
          • its prefix must be a valid identifier - *
          • it must not contain any characters or substrings that are not valid - * on the file system on which workspace root is located. + *
          • it must not contain any characters or substrings that are not valid + * on the file system on which workspace root is located. *
          *

          - * @param name the name of a .class file - * @return a status object with code IStatus.OK if - * the given name is valid as a .class file name, otherwise a status - * object indicating what is wrong with the name + * + * @param name + * the name of a .class file + * @return a status object with code IStatus.OK if the given + * name is valid as a .class file name, otherwise a status object + * indicating what is wrong with the name * @since 2.0 */ -// public static IStatus validateClassFileName(String name) { -// if (name == null) { -// return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("convention.classFile.nullName"), null); //$NON-NLS-1$ -// } -// if (!net.sourceforge.phpdt.internal.compiler.util.Util.isClassFileName(name)) { -// return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("convention.classFile.notClassFileName"), null); //$NON-NLS-1$ -// } -// String identifier; -// int index; -// index = name.lastIndexOf('.'); -// if (index == -1) { -// return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("convention.classFile.notClassFileName"), null); //$NON-NLS-1$ -// } -// identifier = name.substring(0, index); -// IStatus status = validateIdentifier(identifier); -// if (!status.isOK()) { -// return status; -// } -// status = ResourcesPlugin.getWorkspace().validateName(name, IResource.FILE); -// if (!status.isOK()) { -// return status; -// } -// return JavaModelStatus.VERIFIED_OK; -// } - + // public static IStatus validateClassFileName(String name) { + // if (name == null) { + // return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, + // Util.bind("convention.classFile.nullName"), null); //$NON-NLS-1$ + // } + // if + // (!net.sourceforge.phpdt.internal.compiler.util.Util.isClassFileName(name)) + // { + // return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, + // Util.bind("convention.classFile.notClassFileName"), null); //$NON-NLS-1$ + // } + // String identifier; + // int index; + // index = name.lastIndexOf('.'); + // if (index == -1) { + // return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, + // Util.bind("convention.classFile.notClassFileName"), null); //$NON-NLS-1$ + // } + // identifier = name.substring(0, index); + // IStatus status = validateIdentifier(identifier); + // if (!status.isOK()) { + // return status; + // } + // status = ResourcesPlugin.getWorkspace().validateName(name, + // IResource.FILE); + // if (!status.isOK()) { + // return status; + // } + // return JavaModelStatus.VERIFIED_OK; + // } /** * Validate the given field name. *

          * Syntax of a field name corresponds to VariableDeclaratorId (JLS2 8.3). * For example, "x". - * - * @param name the name of a field - * @return a status object with code IStatus.OK if - * the given name is valid as a field name, otherwise a status - * object indicating what is wrong with the name + * + * @param name + * the name of a field + * @return a status object with code IStatus.OK if the given + * name is valid as a field name, otherwise a status object + * indicating what is wrong with the name */ public static IStatus validateFieldName(String name) { return validateIdentifier(name); } /** - * Validate the given Java identifier. - * The identifier must not have the same spelling as a Java keyword, - * boolean literal ("true", "false"), or null literal ("null"). - * See section 3.8 of the Java Language Specification, Second Edition (JLS2). - * A valid identifier can act as a simple type name, method name or field name. - * - * @param id the Java identifier - * @return a status object with code IStatus.OK if - * the given identifier is a valid Java identifier, otherwise a status - * object indicating what is wrong with the identifier + * Validate the given Java identifier. The identifier must not have the same + * spelling as a Java keyword, boolean literal ("true", + * "false"), or null literal ("null"). See + * section 3.8 of the Java Language Specification, Second Edition + * (JLS2). A valid identifier can act as a simple type name, method name or + * field name. + * + * @param id + * the Java identifier + * @return a status object with code IStatus.OK if the given + * identifier is a valid Java identifier, otherwise a status object + * indicating what is wrong with the identifier */ public static IStatus validateIdentifier(String id) { if (scannedIdentifier(id) != null) { return JavaModelStatus.VERIFIED_OK; } else { - return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("convention.illegalIdentifier", id), null); //$NON-NLS-1$ + return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind( + "convention.illegalIdentifier", id), null); //$NON-NLS-1$ } } /** * Validate the given import declaration name. *

          - * The name of an import corresponds to a fully qualified type name - * or an on-demand package name as defined by ImportDeclaration (JLS2 7.5). - * For example, "java.util.*" or "java.util.Hashtable". - * - * @param name the import declaration - * @return a status object with code IStatus.OK if - * the given name is valid as an import declaration, otherwise a status - * object indicating what is wrong with the name + * The name of an import corresponds to a fully qualified type name or an + * on-demand package name as defined by ImportDeclaration (JLS2 7.5). For + * example, "java.util.*" or + * "java.util.Hashtable". + * + * @param name + * the import declaration + * @return a status object with code IStatus.OK if the given + * name is valid as an import declaration, otherwise a status object + * indicating what is wrong with the name */ public static IStatus validateImportDeclaration(String name) { if (name == null || name.length() == 0) { - return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("convention.import.nullImport"), null); //$NON-NLS-1$ - } + return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util + .bind("convention.import.nullImport"), null); //$NON-NLS-1$ + } if (name.charAt(name.length() - 1) == '*') { if (name.charAt(name.length() - 2) == '.') { return validatePackageName(name.substring(0, name.length() - 2)); } else { - return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("convention.import.unqualifiedImport"), null); //$NON-NLS-1$ + return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util + .bind("convention.import.unqualifiedImport"), null); //$NON-NLS-1$ } } return validatePackageName(name); } /** - * Validate the given Java type name, either simple or qualified. - * For example, "java.lang.Object", or "Object". + * Validate the given Java type name, either simple or qualified. For + * example, "java.lang.Object", or "Object". *

          - * - * @param name the name of a type - * @return a status object with code IStatus.OK if - * the given name is valid as a Java type name, - * a status with code IStatus.WARNING - * indicating why the given name is discouraged, - * otherwise a status object indicating what is wrong with - * the name + * + * @param name + * the name of a type + * @return a status object with code IStatus.OK if the given + * name is valid as a Java type name, a status with code + * IStatus.WARNING indicating why the given name is + * discouraged, otherwise a status object indicating what is wrong + * with the name */ public static IStatus validateJavaTypeName(String name) { if (name == null) { - return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("convention.type.nullName"), null); //$NON-NLS-1$ + return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util + .bind("convention.type.nullName"), null); //$NON-NLS-1$ } String trimmed = name.trim(); if (!name.equals(trimmed)) { - return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("convention.type.nameWithBlanks"), null); //$NON-NLS-1$ + return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util + .bind("convention.type.nameWithBlanks"), null); //$NON-NLS-1$ } int index = name.lastIndexOf('.'); char[] scannedID; @@ -292,35 +331,40 @@ public final class JavaConventions { String type = name.substring(index + 1).trim(); scannedID = scannedIdentifier(type); } - + if (scannedID != null) { - IStatus status = ResourcesPlugin.getWorkspace().validateName(new String(scannedID), IResource.FILE); + IStatus status = ResourcesPlugin.getWorkspace().validateName( + new String(scannedID), IResource.FILE); if (!status.isOK()) { return status; } if (CharOperation.contains('$', scannedID)) { - return new Status(IStatus.WARNING, JavaCore.PLUGIN_ID, -1, Util.bind("convention.type.dollarName"), null); //$NON-NLS-1$ + return new Status(IStatus.WARNING, JavaCore.PLUGIN_ID, -1, Util + .bind("convention.type.dollarName"), null); //$NON-NLS-1$ } if ((scannedID.length > 0 && Character.isLowerCase(scannedID[0]))) { - return new Status(IStatus.WARNING, JavaCore.PLUGIN_ID, -1, Util.bind("convention.type.lowercaseName"), null); //$NON-NLS-1$ + return new Status(IStatus.WARNING, JavaCore.PLUGIN_ID, -1, Util + .bind("convention.type.lowercaseName"), null); //$NON-NLS-1$ } return JavaModelStatus.VERIFIED_OK; } else { - return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("convention.type.invalidName", name), null); //$NON-NLS-1$ + return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind( + "convention.type.invalidName", name), null); //$NON-NLS-1$ } } /** - * Validate the given method name. - * The special names "<init>" and "<clinit>" are not valid. + * Validate the given method name. The special names "<init>" and + * "<clinit>" are not valid. *

          - * The syntax for a method name is defined by Identifier - * of MethodDeclarator (JLS2 8.4). For example "println". - * - * @param name the name of a method - * @return a status object with code IStatus.OK if - * the given name is valid as a method name, otherwise a status - * object indicating what is wrong with the name + * The syntax for a method name is defined by Identifier of MethodDeclarator + * (JLS2 8.4). For example "println". + * + * @param name + * the name of a method + * @return a status object with code IStatus.OK if the given + * name is valid as a method name, otherwise a status object + * indicating what is wrong with the name */ public static IStatus validateMethodName(String name) { @@ -330,42 +374,51 @@ public final class JavaConventions { /** * Validate the given package name. *

          - * The syntax of a package name corresponds to PackageName as - * defined by PackageDeclaration (JLS2 7.4). For example, "java.lang". + * The syntax of a package name corresponds to PackageName as defined by + * PackageDeclaration (JLS2 7.4). For example, "java.lang". *

          - * Note that the given name must be a non-empty package name (that is, attempting to - * validate the default package will return an error status.) - * Also it must not contain any characters or substrings that are not valid + * Note that the given name must be a non-empty package name (that is, + * attempting to validate the default package will return an error status.) + * Also it must not contain any characters or substrings that are not valid * on the file system on which workspace root is located. - * - * @param name the name of a package - * @return a status object with code IStatus.OK if - * the given name is valid as a package name, otherwise a status - * object indicating what is wrong with the name + * + * @param name + * the name of a package + * @return a status object with code IStatus.OK if the given + * name is valid as a package name, otherwise a status object + * indicating what is wrong with the name */ public static IStatus validatePackageName(String name) { if (name == null) { - return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("convention.package.nullName"), null); //$NON-NLS-1$ + return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util + .bind("convention.package.nullName"), null); //$NON-NLS-1$ } int length; if ((length = name.length()) == 0) { - return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("convention.package.emptyName"), null); //$NON-NLS-1$ + return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util + .bind("convention.package.emptyName"), null); //$NON-NLS-1$ } - if (name.charAt(0) == DOT || name.charAt(length-1) == DOT) { - return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("convention.package.dotName"), null); //$NON-NLS-1$ + if (name.charAt(0) == DOT || name.charAt(length - 1) == DOT) { + return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util + .bind("convention.package.dotName"), null); //$NON-NLS-1$ } - if (CharOperation.isWhitespace(name.charAt(0)) || CharOperation.isWhitespace(name.charAt(name.length() - 1))) { - return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("convention.package.nameWithBlanks"), null); //$NON-NLS-1$ + if (CharOperation.isWhitespace(name.charAt(0)) + || CharOperation.isWhitespace(name.charAt(name.length() - 1))) { + return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util + .bind("convention.package.nameWithBlanks"), null); //$NON-NLS-1$ } int dot = 0; - while (dot != -1 && dot < length-1) { - if ((dot = name.indexOf(DOT, dot+1)) != -1 && dot < length-1 && name.charAt(dot+1) == DOT) { - return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("convention.package.consecutiveDotsName"), null); //$NON-NLS-1$ - } + while (dot != -1 && dot < length - 1) { + if ((dot = name.indexOf(DOT, dot + 1)) != -1 && dot < length - 1 + && name.charAt(dot + 1) == DOT) { + return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util + .bind("convention.package.consecutiveDotsName"), null); //$NON-NLS-1$ + } } IWorkspace workspace = ResourcesPlugin.getWorkspace(); - StringTokenizer st = new StringTokenizer(name, new String(new char[] {DOT})); + StringTokenizer st = new StringTokenizer(name, new String( + new char[] { DOT })); boolean firstToken = true; IStatus warningStatus = null; while (st.hasMoreTokens()) { @@ -373,15 +426,20 @@ public final class JavaConventions { typeName = typeName.trim(); // grammar allows spaces char[] scannedID = scannedIdentifier(typeName); if (scannedID == null) { - return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("convention.illegalIdentifier", typeName), null); //$NON-NLS-1$ + return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util + .bind("convention.illegalIdentifier", typeName), null); //$NON-NLS-1$ } - IStatus status = workspace.validateName(new String(scannedID), IResource.FOLDER); + IStatus status = workspace.validateName(new String(scannedID), + IResource.FOLDER); if (!status.isOK()) { return status; } - if (firstToken && scannedID.length > 0 && Character.isUpperCase(scannedID[0])) { + if (firstToken && scannedID.length > 0 + && Character.isUpperCase(scannedID[0])) { if (warningStatus == null) { - warningStatus = new Status(IStatus.WARNING, JavaCore.PLUGIN_ID, -1, Util.bind("convention.package.uppercaseName"), null); //$NON-NLS-1$ + warningStatus = new Status(IStatus.WARNING, + JavaCore.PLUGIN_ID, -1, + Util.bind("convention.package.uppercaseName"), null); //$NON-NLS-1$ } } firstToken = false; @@ -391,55 +449,84 @@ public final class JavaConventions { } return JavaModelStatus.VERIFIED_OK; } - + /** - * Validate a given classpath and output location for a project, using the following rules: + * Validate a given classpath and output location for a project, using the + * following rules: *

            - *
          • Classpath entries cannot collide with each other; that is, all entry paths must be unique. - *
          • The project output location path cannot be null, must be absolute and located inside the project. - *
          • Specific output locations (specified on source entries) can be null, if not they must be located inside the project, - *
          • A project entry cannot refer to itself directly (that is, a project cannot prerequisite itself). - *
          • Classpath entries or output locations cannot coincidate or be nested in each other, except for the following scenarii listed below: - *
            • A source folder can coincidate with its own output location, in which case this output can then contain library archives. - * However, a specific output location cannot coincidate with any library or a distinct source folder than the one referring to it.
            • - *
            • A source/library folder can be nested in any source folder as long as the nested folder is excluded from the enclosing one.
            • - *
            • An output location can be nested in a source folder, if the source folder coincidates with the project itself, or if the output - * location is excluded from the source folder. - *
            + *
          • Classpath entries cannot collide with each other; that is, all entry + * paths must be unique. + *
          • The project output location path cannot be null, must be absolute + * and located inside the project. + *
          • Specific output locations (specified on source entries) can be null, + * if not they must be located inside the project, + *
          • A project entry cannot refer to itself directly (that is, a project + * cannot prerequisite itself). + *
          • Classpath entries or output locations cannot coincidate or be nested + * in each other, except for the following scenarii listed below: + *
              + *
            • A source folder can coincidate with its own output location, in + * which case this output can then contain library archives. However, a + * specific output location cannot coincidate with any library or a distinct + * source folder than the one referring to it.
            • + *
            • A source/library folder can be nested in any source folder as long + * as the nested folder is excluded from the enclosing one.
            • + *
            • An output location can be nested in a source folder, if the source + * folder coincidates with the project itself, or if the output location is + * excluded from the source folder. + *
            *
          * - * Note that the classpath entries are not validated automatically. Only bound variables or containers are considered - * in the checking process (this allows to perform a consistency check on a classpath which has references to - * yet non existing projects, folders, ...). - *

          - * This validation is intended to anticipate classpath issues prior to assigning it to a project. In particular, it will automatically - * be performed during the classpath setting operation (if validation fails, the classpath setting will not complete). - *

          - * @param javaProject the given java project - * @param rawClasspath the given classpath - * @param projectOutputLocation the given output location - * @return a status object with code IStatus.OK if - * the given classpath and output location are compatible, otherwise a status - * object indicating what is wrong with the classpath or output location + * Note that the classpath entries are not validated automatically. Only + * bound variables or containers are considered in the checking process + * (this allows to perform a consistency check on a classpath which has + * references to yet non existing projects, folders, ...). + *

          + * This validation is intended to anticipate classpath issues prior to + * assigning it to a project. In particular, it will automatically be + * performed during the classpath setting operation (if validation fails, + * the classpath setting will not complete). + *

          + * + * @param javaProject + * the given java project + * @param rawClasspath + * the given classpath + * @param projectOutputLocation + * the given output location + * @return a status object with code IStatus.OK if the given + * classpath and output location are compatible, otherwise a status + * object indicating what is wrong with the classpath or output + * location * @since 2.0 */ - public static IJavaModelStatus validateClasspath(IJavaProject javaProject, IClasspathEntry[] rawClasspath, IPath projectOutputLocation) { + public static IJavaModelStatus validateClasspath(IJavaProject javaProject, + IClasspathEntry[] rawClasspath, IPath projectOutputLocation) { - return ClasspathEntry.validateClasspath(javaProject, rawClasspath, projectOutputLocation); + return ClasspathEntry.validateClasspath(javaProject, rawClasspath, + projectOutputLocation); } - + /** - * Returns a Java model status describing the problem related to this classpath entry if any, - * a status object with code IStatus.OK if the entry is fine (that is, if the - * given classpath entry denotes a valid element to be referenced onto a classpath). + * Returns a Java model status describing the problem related to this + * classpath entry if any, a status object with code IStatus.OK + * if the entry is fine (that is, if the given classpath entry denotes a + * valid element to be referenced onto a classpath). * - * @param project the given java project - * @param entry the given classpath entry - * @param checkSourceAttachment a flag to determine if source attachement should be checked - * @return a java model status describing the problem related to this classpath entry if any, a status object with code IStatus.OK if the entry is fine + * @param project + * the given java project + * @param entry + * the given classpath entry + * @param checkSourceAttachment + * a flag to determine if source attachement should be checked + * @return a java model status describing the problem related to this + * classpath entry if any, a status object with code + * IStatus.OK if the entry is fine * @since 2.0 */ - public static IJavaModelStatus validateClasspathEntry(IJavaProject project, IClasspathEntry entry, boolean checkSourceAttachment){ - return ClasspathEntry.validateClasspathEntry(project, entry, checkSourceAttachment, true/*recurse in container*/); + public static IJavaModelStatus validateClasspathEntry(IJavaProject project, + IClasspathEntry entry, boolean checkSourceAttachment) { + return ClasspathEntry.validateClasspathEntry(project, entry, + checkSourceAttachment, true/* recurse in container */); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaCore.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaCore.java index 3797518..47e6e39 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaCore.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaCore.java @@ -38,12 +38,12 @@ import org.eclipse.core.runtime.Preferences; public class JavaCore { - // public static HashSet OptionNames = new HashSet(20); + // public static HashSet OptionNames = new HashSet(20); /** * The plug-in identifier of the Java core support (value * "net.sourceforge.phpeclipse") */ - // public static final String PLUGIN_ID = "net.sourceforge.phpeclipse.core"; + // public static final String PLUGIN_ID = "net.sourceforge.phpeclipse.core"; // //$NON-NLS-1$ public static final String PLUGIN_ID = PHPeclipsePlugin.PLUGIN_ID; @@ -287,25 +287,24 @@ public class JavaCore { * @see #getDefaultOptions */ public static final String COMPILER_PB_PHP_VAR_DEPRECATED = CompilerOptions.OPTION_PHPVarDeprecatedWarning; //$NON-NLS-1$ - + public static final String COMPILER_PB_PHP_KEYWORD = CompilerOptions.OPTION_PHPBadStyleKeywordWarning; //$NON-NLS-1$ - + public static final String COMPILER_PB_PHP_UPPERCASE_IDENTIFIER = CompilerOptions.OPTION_PHPBadStyleUppercaseIdentifierWarning; //$NON-NLS-1$ - + public static final String COMPILER_PB_PHP_FILE_NOT_EXIST = CompilerOptions.OPTION_PHPIncludeNotExistWarning; //$NON-NLS-1$ - + public static final String COMPILER_PB_UNINITIALIZED_LOCAL_VARIABLE = CompilerOptions.OPTION_UninitializedLocalVariableWarning; //$NON-NLS-1$ - + public static final String COMPILER_PB_UNREACHABLE_CODE = CompilerOptions.OPTION_CodeCannotBeReachedWarning; //$NON-NLS-1$ - + /** * Possible configurable option ID. * * @see #getDefaultOptions */ -// public static final String COMPILER_PB_UNREACHABLE_CODE = PLUGIN_ID -// + ".compiler.problem.unreachableCode"; //$NON-NLS-1$ - + // public static final String COMPILER_PB_UNREACHABLE_CODE = PLUGIN_ID + // + ".compiler.problem.unreachableCode"; //$NON-NLS-1$ /** * Possible configurable option ID. * @@ -837,417 +836,417 @@ public class JavaCore { * Note: more options might be added in further releases. * *

          -	 * 
          -	 *  RECOGNIZED OPTIONS:
          -	 *  COMPILER / Generating Local Variable Debug Attribute
          -	 *     When generated, this attribute will enable local variable names 
          -	 *     to be displayed in debugger, only in place where variables are 
          -	 *     definitely assigned (.class file is then bigger)
          -	 *      - option id:         "org.phpeclipse.phpdt.core.compiler.debug.localVariable"
          -	 *      - possible values:   { "generate", "do not generate" }
          -	 *      - default:           "generate"
          -	 * 
          -	 *  COMPILER / Generating Line Number Debug Attribute 
          -	 *     When generated, this attribute will enable source code highlighting in debugger 
          -	 *     (.class file is then bigger).
          -	 *      - option id:         "org.phpeclipse.phpdt.core.compiler.debug.lineNumber"
          -	 *      - possible values:   { "generate", "do not generate" }
          -	 *      - default:           "generate"
          -	 *     
          -	 *  COMPILER / Generating Source Debug Attribute 
          -	 *     When generated, this attribute will enable the debugger to present the 
          -	 *     corresponding source code.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.compiler.debug.sourceFile"
          -	 *      - possible values:   { "generate", "do not generate" }
          -	 *      - default:           "generate"
          -	 *     
          -	 *  COMPILER / Preserving Unused Local Variables
          -	 *     Unless requested to preserve unused local variables (i.e. never read), the 
          -	 *     compiler will optimize them out, potentially altering debugging
          -	 *      - option id:         "org.phpeclipse.phpdt.core.compiler.codegen.unusedLocal"
          -	 *      - possible values:   { "preserve", "optimize out" }
          -	 *      - default:           "preserve"
          -	 *  
          -	 *  COMPILER / Defining Target Java Platform
          -	 *     For binary compatibility reason, .class files can be tagged to with certain VM versions and later.
          -	 *     Note that "1.4" target require to toggle compliance mode to "1.4" too.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.compiler.codegen.targetPlatform"
          -	 *      - possible values:   { "1.1", "1.2", "1.3", "1.4" }
          -	 *      - default:           "1.1"
          -	 * 
          -	 *  COMPILER / Reporting Unreachable Code
          -	 *     Unreachable code can optionally be reported as an error, warning or simply 
          -	 *     ignored. The bytecode generation will always optimized it out.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.compiler.problem.unreachableCode"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "error"
          -	 * 
          -	 *  COMPILER / Reporting Invalid Import
          -	 *     An import statement that cannot be resolved might optionally be reported 
          -	 *     as an error, as a warning or ignored.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.compiler.problem.invalidImport"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "error"
          -	 * 
          -	 *  COMPILER / Reporting Attempt to Override Package-Default Method
          -	 *     A package default method is not visible in a different package, and thus 
          -	 *     cannot be overridden. When enabling this option, the compiler will signal 
          -	 *     such scenarii either as an error or a warning.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.compiler.problem.overridingPackageDefaultMethod"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "warning"
          -	 * 
          -	 *  COMPILER / Reporting Method With Constructor Name
          -	 *     Naming a method with a constructor name is generally considered poor 
          -	 *     style programming. When enabling this option, the compiler will signal such 
          -	 *     scenarii either as an error or a warning.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.compiler.problem.methodWithConstructorName"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "warning"
          -	 * 
          -	 *  COMPILER / Reporting Deprecation
          -	 *     When enabled, the compiler will signal use of deprecated API either as an 
          -	 *     error or a warning.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.compiler.problem.deprecation"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "warning"
          -	 * 
          -	 *  COMPILER / Reporting Deprecation Inside Deprecated Code
          -	 *     When enabled, the compiler will signal use of deprecated API inside deprecated code.
          -	 *     The severity of the problem is controlled with option "org.phpeclipse.phpdt.core.compiler.problem.deprecation".
          -	 *      - option id:         "org.phpeclipse.phpdt.core.compiler.problem.deprecationInDeprecatedCode"
          -	 *      - possible values:   { "enabled", "disabled" }
          -	 *      - default:           "disabled"
          -	 * 
          -	 *  COMPILER / Reporting Hidden Catch Block
          -	 *     Locally to a try statement, some catch blocks may hide others , e.g.
          -	 *       try {  throw new java.io.CharConversionException();
          -	 *       } catch (java.io.CharConversionException e) {
          -	 *       } catch (java.io.IOException e) {}. 
          -	 *     When enabling this option, the compiler will issue an error or a warning for hidden 
          -	 *     catch blocks corresponding to checked exceptions
          -	 *      - option id:         "org.phpeclipse.phpdt.core.compiler.problem.hiddenCatchBlock"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "warning"
          -	 * 
          -	 *  COMPILER / Reporting Unused Local
          -	 *     When enabled, the compiler will issue an error or a warning for unused local 
          -	 *     variables (i.e. variables never read from)
          -	 *      - option id:         "org.phpeclipse.phpdt.core.compiler.problem.unusedLocal"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "ignore"
          -	 * 
          -	 *  COMPILER / Reporting Unused Parameter
          -	 *     When enabled, the compiler will issue an error or a warning for unused method 
          -	 *     parameters (i.e. parameters never read from)
          -	 *      - option id:         "org.phpeclipse.phpdt.core.compiler.problem.unusedParameter"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "ignore"
          -	 * 
          -	 *  COMPILER / Reporting Unused Import
          -	 *     When enabled, the compiler will issue an error or a warning for unused import 
          -	 *     reference 
          -	 *      - option id:         "org.phpeclipse.phpdt.core.compiler.problem.unusedImport"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "warning"
          -	 * 
          -	 *  COMPILER / Reporting Synthetic Access Emulation
          -	 *     When enabled, the compiler will issue an error or a warning whenever it emulates 
          -	 *     access to a non-accessible member of an enclosing type. Such access can have
          -	 *     performance implications.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.compiler.problem.syntheticAccessEmulation"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "ignore"
          -	 * 
          -	 *  COMPILER / Reporting Non-Externalized String Literal
          -	 *     When enabled, the compiler will issue an error or a warning for non externalized 
          -	 *     String literal (i.e. non tagged with //$NON-NLS-<n>$). 
          -	 *      - option id:         "org.phpeclipse.phpdt.core.compiler.problem.nonExternalizedStringLiteral"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "ignore"
          -	 *  
          -	 *  COMPILER / Reporting Usage of 'assert' Identifier
          -	 *     When enabled, the compiler will issue an error or a warning whenever 'assert' is 
          -	 *     used as an identifier (reserved keyword in 1.4)
          -	 *      - option id:         "org.phpeclipse.phpdt.core.compiler.problem.assertIdentifier"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "ignore"
          -	 *  
          -	 *  COMPILER / Reporting Usage of expression receiver on static invocation/field access
          -	 *     When enabled, the compiler will issue an error or a warning whenever a static field
          -	 *     or method is accessed with an expression receiver.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.compiler.problem.staticAccessReceiver"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "warning"
          -	 *  
          -	 *  COMPILER / Reporting Assignment with no effect
          -	 *     When enabled, the compiler will issue an error or a warning whenever an assignment
          -	 *     has no effect (e.g 'x = x').
          -	 *      - option id:         "org.phpeclipse.phpdt.core.compiler.problem.noEffectAssignment"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "warning"
          -	 *  
          -	 *  COMPILER / Setting Source Compatibility Mode
          -	 *     Specify whether source is 1.3 or 1.4 compatible. From 1.4 on, 'assert' is a keyword
          -	 *     reserved for assertion support. Also note, than when toggling to 1.4 mode, the target VM
          -	 *    level should be set to "1.4" and the compliance mode should be "1.4".
          -	 *      - option id:         "org.phpeclipse.phpdt.core.compiler.source"
          -	 *      - possible values:   { "1.3", "1.4" }
          -	 *      - default:           "1.3"
          -	 *  
          -	 *  COMPILER / Setting Compliance Level
          -	 *     Select the compliance level for the compiler. In "1.3" mode, source and target settings
          -	 *     should not go beyond "1.3" level.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.compiler.compliance"
          -	 *      - possible values:   { "1.3", "1.4" }
          -	 *      - default:           "1.3"
          -	 *  
          -	 *  COMPILER / Maximum number of problems reported per compilation unit
          -	 *     Specify the maximum number of problems reported on each compilation unit.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.compiler.maxProblemPerUnit"
          -	 *      - possible values:	"<n>" where <n> is zero or a positive integer (if zero then all problems are reported).
          -	 *      - default:           "100"
          -	 *  
          -	 *  COMPILER / Define the Automatic Task Tags
          -	 *     When the tag is non empty, the compiler will issue a task marker whenever it encounters
          -	 *     one of the corresponding tag inside any comment in Java source code.
          -	 *     Generated task messages will include the tag, and range until the next line separator or comment ending, and will be trimmed.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.compiler.taskTags"
          -	 *      - possible values:   { "<tag>[,<tag>]*" } where <tag> is a String without any wild-card 
          -	 *      - default:           ""
          -	 *  COMPILER / Define the Automatic Task Priorities
          -	 *     In parallel with the Automatic Task Tags, this list defines the priorities (high, normal or low)
          -	 *     of the task markers issued by the compiler.
          -	 *     If the default is specified, the priority of each task marker is "NORMAL".
          -	 *      - option id:         "org.phpeclipse.phpdt.core.compiler.taskPriorities"
          -	 *      - possible values:   { "<priority>[,<priority>]*" } where <priority> is one of "HIGH", "NORMAL" or "LOW"
          -	 *      - default:           ""
          -	 *  
          -	 *  BUILDER / Specifying Filters for Resource Copying Control
          -	 *     Allow to specify some filters to control the resource copy process.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.builder.resourceCopyExclusionFilter"
          -	 *      - possible values:   { "<name>[,<name>]* } where <name> is a file name pattern (* and ? wild-cards allowed)
          -	 *        or the name of a folder which ends with '/'
          -	 *      - default:           ""
          -	 *  
          -	 *  BUILDER / Abort if Invalid Classpath
          -	 *     Allow to toggle the builder to abort if the classpath is invalid
          -	 *      - option id:         "org.phpeclipse.phpdt.core.builder.invalidClasspath"
          -	 *      - possible values:   { "abort", "ignore" }
          -	 *      - default:           "ignore"
          -	 *  
          -	 *  BUILDER / Cleaning Output Folder(s)
          -	 *     Indicate whether the JavaBuilder is allowed to clean the output folders
          -	 *     when performing full build operations.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.builder.cleanOutputFolder"
          -	 *      - possible values:   { "clean", "ignore" }
          -	 *      - default:           "clean"
          -	 *  
          -	 *  JAVACORE / Computing Project Build Order
          -	 *     Indicate whether JavaCore should enforce the project build order to be based on
          -	 *     the classpath prerequisite chain. When requesting to compute, this takes over
          -	 *     the platform default order (based on project references).
          -	 *      - option id:         "org.phpeclipse.phpdt.core.computeJavaBuildOrder"
          -	 *      - possible values:   { "compute", "ignore" }
          -	 *      - default:           "ignore"	 
          -	 *  
          -	 *  JAVACORE / Specify Default Source Encoding Format
          -	 *     Get the encoding format for compiled sources. This setting is read-only, it is equivalent
          -	 *     to 'ResourcesPlugin.getEncoding()'.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.encoding"
          -	 *      - possible values:   { any of the supported encoding name}.
          -	 *      - default:           <platform default>
          -	 *  
          -	 *  JAVACORE / Reporting Incomplete Classpath
          -	 *     An entry on the classpath doesn't exist or is not visible (e.g. a referenced project is closed).
          -	 *      - option id:         "org.phpeclipse.phpdt.core.incompleteClasspath"
          -	 *      - possible values:   { "error", "warning"}
          -	 *      - default:           "error"
          -	 *  
          -	 *  JAVACORE / Reporting Classpath Cycle
          -	 *     A project is involved in a cycle.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.circularClasspath"
          -	 *      - possible values:   { "error", "warning" }
          -	 *      - default:           "error"
          -	 *  
          -	 * 	FORMATTER / Inserting New Line Before Opening Brace
          -	 *     When Insert, a new line is inserted before an opening brace, otherwise nothing
          -	 *     is inserted
          -	 *      - option id:         "org.phpeclipse.phpdt.core.formatter.newline.openingBrace"
          -	 *      - possible values:   { "insert", "do not insert" }
          -	 *      - default:           "do not insert"
           	 *  
          -	 * 	FORMATTER / Inserting New Line Inside Control Statement
          -	 *     When Insert, a new line is inserted between } and following else, catch, finally
          -	 *      - option id:         "org.phpeclipse.phpdt.core.formatter.newline.controlStatement"
          -	 *      - possible values:   { "insert", "do not insert" }
          -	 *      - default:           "do not insert"
          +	 *   RECOGNIZED OPTIONS:
          +	 *   COMPILER / Generating Local Variable Debug Attribute
          +	 *      When generated, this attribute will enable local variable names 
          +	 *      to be displayed in debugger, only in place where variables are 
          +	 *      definitely assigned (.class file is then bigger)
          +	 *       - option id:         "org.phpeclipse.phpdt.core.compiler.debug.localVariable"
          +	 *       - possible values:   { "generate", "do not generate" }
          +	 *       - default:           "generate"
           	 *  
          -	 * 	FORMATTER / Clearing Blank Lines
          -	 *     When Clear all, all blank lines are removed. When Preserve one, only one is kept
          -	 *     and all others removed.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.formatter.newline.clearAll"
          -	 *      - possible values:   { "clear all", "preserve one" }
          -	 *      - default:           "preserve one"
          +	 *   COMPILER / Generating Line Number Debug Attribute 
          +	 *      When generated, this attribute will enable source code highlighting in debugger 
          +	 *      (.class file is then bigger).
          +	 *       - option id:         "org.phpeclipse.phpdt.core.compiler.debug.lineNumber"
          +	 *       - possible values:   { "generate", "do not generate" }
          +	 *       - default:           "generate"
          +	 *      
          +	 *   COMPILER / Generating Source Debug Attribute 
          +	 *      When generated, this attribute will enable the debugger to present the 
          +	 *      corresponding source code.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.compiler.debug.sourceFile"
          +	 *       - possible values:   { "generate", "do not generate" }
          +	 *       - default:           "generate"
          +	 *      
          +	 *   COMPILER / Preserving Unused Local Variables
          +	 *      Unless requested to preserve unused local variables (i.e. never read), the 
          +	 *      compiler will optimize them out, potentially altering debugging
          +	 *       - option id:         "org.phpeclipse.phpdt.core.compiler.codegen.unusedLocal"
          +	 *       - possible values:   { "preserve", "optimize out" }
          +	 *       - default:           "preserve"
          +	 *   
          +	 *   COMPILER / Defining Target Java Platform
          +	 *      For binary compatibility reason, .class files can be tagged to with certain VM versions and later.
          +	 *      Note that "1.4" target require to toggle compliance mode to "1.4" too.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.compiler.codegen.targetPlatform"
          +	 *       - possible values:   { "1.1", "1.2", "1.3", "1.4" }
          +	 *       - default:           "1.1"
           	 *  
          -	 * 	FORMATTER / Inserting New Line Between Else/If 
          -	 *     When Insert, a blank line is inserted between an else and an if when they are 
          -	 *     contiguous. When choosing to not insert, else-if will be kept on the same
          -	 *     line when possible.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.formatter.newline.elseIf"
          -	 *      - possible values:   { "insert", "do not insert" }
          -	 *      - default:           "do not insert"
          +	 *   COMPILER / Reporting Unreachable Code
          +	 *      Unreachable code can optionally be reported as an error, warning or simply 
          +	 *      ignored. The bytecode generation will always optimized it out.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.compiler.problem.unreachableCode"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "error"
           	 *  
          -	 * 	FORMATTER / Inserting New Line In Empty Block
          -	 *     When insert, a line break is inserted between contiguous { and }, if } is not followed
          -	 *     by a keyword.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.formatter.newline.emptyBlock"
          -	 *      - possible values:   { "insert", "do not insert" }
          -	 *      - default:           "insert"
          +	 *   COMPILER / Reporting Invalid Import
          +	 *      An import statement that cannot be resolved might optionally be reported 
          +	 *      as an error, as a warning or ignored.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.compiler.problem.invalidImport"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "error"
           	 *  
          -	 * 	FORMATTER / Splitting Lines Exceeding Length
          -	 *     Enable splitting of long lines (exceeding the configurable length). Length of 0 will
          -	 *     disable line splitting
          -	 *      - option id:         "org.phpeclipse.phpdt.core.formatter.lineSplit"
          -	 *      - possible values:	"<n>", where n is zero or a positive integer
          -	 *      - default:           "80"
          +	 *   COMPILER / Reporting Attempt to Override Package-Default Method
          +	 *      A package default method is not visible in a different package, and thus 
          +	 *      cannot be overridden. When enabling this option, the compiler will signal 
          +	 *      such scenarii either as an error or a warning.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.compiler.problem.overridingPackageDefaultMethod"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "warning"
           	 *  
          -	 * 	FORMATTER / Compacting Assignment
          -	 *     Assignments can be formatted asymmetrically, e.g. 'int x= 2;', when Normal, a space
          -	 *     is inserted before the assignment operator
          -	 *      - option id:         "org.phpeclipse.phpdt.core.formatter.style.assignment"
          -	 *      - possible values:   { "compact", "normal" }
          -	 *      - default:           "normal"
          +	 *   COMPILER / Reporting Method With Constructor Name
          +	 *      Naming a method with a constructor name is generally considered poor 
          +	 *      style programming. When enabling this option, the compiler will signal such 
          +	 *      scenarii either as an error or a warning.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.compiler.problem.methodWithConstructorName"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "warning"
           	 *  
          -	 * 	FORMATTER / Defining Indentation Character
          -	 *     Either choose to indent with tab characters or spaces
          -	 *      - option id:         "org.phpeclipse.phpdt.core.formatter.tabulation.char"
          -	 *      - possible values:   { "tab", "space" }
          -	 *      - default:           "tab"
          +	 *   COMPILER / Reporting Deprecation
          +	 *      When enabled, the compiler will signal use of deprecated API either as an 
          +	 *      error or a warning.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.compiler.problem.deprecation"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "warning"
           	 *  
          -	 * 	FORMATTER / Defining Space Indentation Length
          -	 *     When using spaces, set the amount of space characters to use for each 
          -	 *     indentation mark.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.formatter.tabulation.size"
          -	 *      - possible values:	"<n>", where n is a positive integer
          -	 *      - default:           "4"
          +	 *   COMPILER / Reporting Deprecation Inside Deprecated Code
          +	 *      When enabled, the compiler will signal use of deprecated API inside deprecated code.
          +	 *      The severity of the problem is controlled with option "org.phpeclipse.phpdt.core.compiler.problem.deprecation".
          +	 *       - option id:         "org.phpeclipse.phpdt.core.compiler.problem.deprecationInDeprecatedCode"
          +	 *       - possible values:   { "enabled", "disabled" }
          +	 *       - default:           "disabled"
           	 *  
          -	 * 	CODEASSIST / Activate Visibility Sensitive Completion
          -	 *     When active, completion doesn't show that you can not see
          -	 *     (e.g. you can not see private methods of a super class).
          -	 *      - option id:         "org.phpeclipse.phpdt.core.codeComplete.visibilityCheck"
          -	 *      - possible values:   { "enabled", "disabled" }
          -	 *      - default:           "disabled"
          +	 *   COMPILER / Reporting Hidden Catch Block
          +	 *      Locally to a try statement, some catch blocks may hide others , e.g.
          +	 *        try {  throw new java.io.CharConversionException();
          +	 *        } catch (java.io.CharConversionException e) {
          +	 *        } catch (java.io.IOException e) {}. 
          +	 *      When enabling this option, the compiler will issue an error or a warning for hidden 
          +	 *      catch blocks corresponding to checked exceptions
          +	 *       - option id:         "org.phpeclipse.phpdt.core.compiler.problem.hiddenCatchBlock"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "warning"
           	 *  
          -	 * 	CODEASSIST / Automatic Qualification of Implicit Members
          -	 *     When active, completion automatically qualifies completion on implicit
          -	 *     field references and message expressions.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.codeComplete.forceImplicitQualification"
          -	 *      - possible values:   { "enabled", "disabled" }
          -	 *      - default:           "disabled"
          +	 *   COMPILER / Reporting Unused Local
          +	 *      When enabled, the compiler will issue an error or a warning for unused local 
          +	 *      variables (i.e. variables never read from)
          +	 *       - option id:         "org.phpeclipse.phpdt.core.compiler.problem.unusedLocal"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "ignore"
           	 *  
          -	 *   CODEASSIST / Define the Prefixes for Field Name
          -	 *     When the prefixes is non empty, completion for field name will begin with
          -	 *     one of the proposed prefixes.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.codeComplete.fieldPrefixes"
          -	 *      - possible values:   { "<prefix>[,<prefix>]*" } where <prefix> is a String without any wild-card 
          -	 *      - default:           ""
          +	 *   COMPILER / Reporting Unused Parameter
          +	 *      When enabled, the compiler will issue an error or a warning for unused method 
          +	 *      parameters (i.e. parameters never read from)
          +	 *       - option id:         "org.phpeclipse.phpdt.core.compiler.problem.unusedParameter"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "ignore"
           	 *  
          -	 *   CODEASSIST / Define the Prefixes for Static Field Name
          -	 *     When the prefixes is non empty, completion for static field name will begin with
          -	 *     one of the proposed prefixes.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.codeComplete.staticFieldPrefixes"
          -	 *      - possible values:   { "<prefix>[,<prefix>]*" } where <prefix> is a String without any wild-card 
          -	 *      - default:           ""
          +	 *   COMPILER / Reporting Unused Import
          +	 *      When enabled, the compiler will issue an error or a warning for unused import 
          +	 *      reference 
          +	 *       - option id:         "org.phpeclipse.phpdt.core.compiler.problem.unusedImport"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "warning"
           	 *  
          -	 *   CODEASSIST / Define the Prefixes for Local Variable Name
          -	 *     When the prefixes is non empty, completion for local variable name will begin with
          -	 *     one of the proposed prefixes.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.codeComplete.localPrefixes"
          -	 *      - possible values:   { "<prefix>[,<prefix>]*" } where <prefix> is a String without any wild-card 
          -	 *      - default:           ""
          +	 *   COMPILER / Reporting Synthetic Access Emulation
          +	 *      When enabled, the compiler will issue an error or a warning whenever it emulates 
          +	 *      access to a non-accessible member of an enclosing type. Such access can have
          +	 *      performance implications.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.compiler.problem.syntheticAccessEmulation"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "ignore"
           	 *  
          -	 *   CODEASSIST / Define the Prefixes for Argument Name
          -	 *     When the prefixes is non empty, completion for argument name will begin with
          -	 *     one of the proposed prefixes.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.codeComplete.argumentPrefixes"
          -	 *      - possible values:   { "<prefix>[,<prefix>]*" } where <prefix> is a String without any wild-card 
          -	 *      - default:           ""
          -	 *  
          -	 *   CODEASSIST / Define the Suffixes for Field Name
          -	 *     When the suffixes is non empty, completion for field name will end with
          -	 *     one of the proposed suffixes.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.codeComplete.fieldSuffixes"
          -	 *      - possible values:   { "<suffix>[,<suffix>]*" } where <suffix> is a String without any wild-card 
          -	 *      - default:           ""
          -	 *  
          -	 *   CODEASSIST / Define the Suffixes for Static Field Name
          -	 *     When the suffixes is non empty, completion for static field name will end with
          -	 *     one of the proposed suffixes.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.codeComplete.staticFieldSuffixes"
          -	 *      - possible values:   { "<suffix>[,<suffix>]*" } where <suffix> is a String without any wild-card 
          -	 *      - default:           ""
          -	 *  
          -	 *   CODEASSIST / Define the Suffixes for Local Variable Name
          -	 *     When the suffixes is non empty, completion for local variable name will end with
          -	 *     one of the proposed suffixes.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.codeComplete.localSuffixes"
          -	 *      - possible values:   { "<suffix>[,<suffix>]*" } where <suffix> is a String without any wild-card 
          -	 *      - default:           ""
          -	 *  
          -	 *   CODEASSIST / Define the Suffixes for Argument Name
          -	 *     When the suffixes is non empty, completion for argument name will end with
          -	 *     one of the proposed suffixes.
          -	 *      - option id:         "org.phpeclipse.phpdt.core.codeComplete.argumentSuffixes"
          -	 *      - possible values:   { "<suffix>[,<suffix>]*" } where <prefix> is a String without any wild-card 
          -	 *      - default:           ""
          -	 *  </pre>
          -	 *  
          -	 *  @return a mutable table containing the default settings of all known options
          -	 *    (key type: 
          +	 *   COMPILER / Reporting Non-Externalized String Literal
          +	 *      When enabled, the compiler will issue an error or a warning for non externalized 
          +	 *      String literal (i.e. non tagged with //$NON-NLS-<n>$). 
          +	 *       - option id:         "org.phpeclipse.phpdt.core.compiler.problem.nonExternalizedStringLiteral"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "ignore"
          +	 *   
          +	 *   COMPILER / Reporting Usage of 'assert' Identifier
          +	 *      When enabled, the compiler will issue an error or a warning whenever 'assert' is 
          +	 *      used as an identifier (reserved keyword in 1.4)
          +	 *       - option id:         "org.phpeclipse.phpdt.core.compiler.problem.assertIdentifier"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "ignore"
          +	 *   
          +	 *   COMPILER / Reporting Usage of expression receiver on static invocation/field access
          +	 *      When enabled, the compiler will issue an error or a warning whenever a static field
          +	 *      or method is accessed with an expression receiver.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.compiler.problem.staticAccessReceiver"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "warning"
          +	 *   
          +	 *   COMPILER / Reporting Assignment with no effect
          +	 *      When enabled, the compiler will issue an error or a warning whenever an assignment
          +	 *      has no effect (e.g 'x = x').
          +	 *       - option id:         "org.phpeclipse.phpdt.core.compiler.problem.noEffectAssignment"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "warning"
          +	 *   
          +	 *   COMPILER / Setting Source Compatibility Mode
          +	 *      Specify whether source is 1.3 or 1.4 compatible. From 1.4 on, 'assert' is a keyword
          +	 *      reserved for assertion support. Also note, than when toggling to 1.4 mode, the target VM
          +	 *     level should be set to "1.4" and the compliance mode should be "1.4".
          +	 *       - option id:         "org.phpeclipse.phpdt.core.compiler.source"
          +	 *       - possible values:   { "1.3", "1.4" }
          +	 *       - default:           "1.3"
          +	 *   
          +	 *   COMPILER / Setting Compliance Level
          +	 *      Select the compliance level for the compiler. In "1.3" mode, source and target settings
          +	 *      should not go beyond "1.3" level.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.compiler.compliance"
          +	 *       - possible values:   { "1.3", "1.4" }
          +	 *       - default:           "1.3"
          +	 *   
          +	 *   COMPILER / Maximum number of problems reported per compilation unit
          +	 *      Specify the maximum number of problems reported on each compilation unit.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.compiler.maxProblemPerUnit"
          +	 *       - possible values:	"<n>" where <n> is zero or a positive integer (if zero then all problems are reported).
          +	 *       - default:           "100"
          +	 *   
          +	 *   COMPILER / Define the Automatic Task Tags
          +	 *      When the tag is non empty, the compiler will issue a task marker whenever it encounters
          +	 *      one of the corresponding tag inside any comment in Java source code.
          +	 *      Generated task messages will include the tag, and range until the next line separator or comment ending, and will be trimmed.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.compiler.taskTags"
          +	 *       - possible values:   { "<tag>[,<tag>]*" } where <tag> is a String without any wild-card 
          +	 *       - default:           ""
          +	 *   COMPILER / Define the Automatic Task Priorities
          +	 *      In parallel with the Automatic Task Tags, this list defines the priorities (high, normal or low)
          +	 *      of the task markers issued by the compiler.
          +	 *      If the default is specified, the priority of each task marker is "NORMAL".
          +	 *       - option id:         "org.phpeclipse.phpdt.core.compiler.taskPriorities"
          +	 *       - possible values:   { "<priority>[,<priority>]*" } where <priority> is one of "HIGH", "NORMAL" or "LOW"
          +	 *       - default:           ""
          +	 *   
          +	 *   BUILDER / Specifying Filters for Resource Copying Control
          +	 *      Allow to specify some filters to control the resource copy process.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.builder.resourceCopyExclusionFilter"
          +	 *       - possible values:   { "<name>[,<name>]* } where <name> is a file name pattern (* and ? wild-cards allowed)
          +	 *         or the name of a folder which ends with '/'
          +	 *       - default:           ""
          +	 *   
          +	 *   BUILDER / Abort if Invalid Classpath
          +	 *      Allow to toggle the builder to abort if the classpath is invalid
          +	 *       - option id:         "org.phpeclipse.phpdt.core.builder.invalidClasspath"
          +	 *       - possible values:   { "abort", "ignore" }
          +	 *       - default:           "ignore"
          +	 *   
          +	 *   BUILDER / Cleaning Output Folder(s)
          +	 *      Indicate whether the JavaBuilder is allowed to clean the output folders
          +	 *      when performing full build operations.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.builder.cleanOutputFolder"
          +	 *       - possible values:   { "clean", "ignore" }
          +	 *       - default:           "clean"
          +	 *   
          +	 *   JAVACORE / Computing Project Build Order
          +	 *      Indicate whether JavaCore should enforce the project build order to be based on
          +	 *      the classpath prerequisite chain. When requesting to compute, this takes over
          +	 *      the platform default order (based on project references).
          +	 *       - option id:         "org.phpeclipse.phpdt.core.computeJavaBuildOrder"
          +	 *       - possible values:   { "compute", "ignore" }
          +	 *       - default:           "ignore"	 
          +	 *   
          +	 *   JAVACORE / Specify Default Source Encoding Format
          +	 *      Get the encoding format for compiled sources. This setting is read-only, it is equivalent
          +	 *      to 'ResourcesPlugin.getEncoding()'.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.encoding"
          +	 *       - possible values:   { any of the supported encoding name}.
          +	 *       - default:           <platform default>
          +	 *   
          +	 *   JAVACORE / Reporting Incomplete Classpath
          +	 *      An entry on the classpath doesn't exist or is not visible (e.g. a referenced project is closed).
          +	 *       - option id:         "org.phpeclipse.phpdt.core.incompleteClasspath"
          +	 *       - possible values:   { "error", "warning"}
          +	 *       - default:           "error"
          +	 *   
          +	 *   JAVACORE / Reporting Classpath Cycle
          +	 *      A project is involved in a cycle.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.circularClasspath"
          +	 *       - possible values:   { "error", "warning" }
          +	 *       - default:           "error"
          +	 *   
          +	 *  	FORMATTER / Inserting New Line Before Opening Brace
          +	 *      When Insert, a new line is inserted before an opening brace, otherwise nothing
          +	 *      is inserted
          +	 *       - option id:         "org.phpeclipse.phpdt.core.formatter.newline.openingBrace"
          +	 *       - possible values:   { "insert", "do not insert" }
          +	 *       - default:           "do not insert"
          +	 *   
          +	 *  	FORMATTER / Inserting New Line Inside Control Statement
          +	 *      When Insert, a new line is inserted between } and following else, catch, finally
          +	 *       - option id:         "org.phpeclipse.phpdt.core.formatter.newline.controlStatement"
          +	 *       - possible values:   { "insert", "do not insert" }
          +	 *       - default:           "do not insert"
          +	 *   
          +	 *  	FORMATTER / Clearing Blank Lines
          +	 *      When Clear all, all blank lines are removed. When Preserve one, only one is kept
          +	 *      and all others removed.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.formatter.newline.clearAll"
          +	 *       - possible values:   { "clear all", "preserve one" }
          +	 *       - default:           "preserve one"
          +	 *   
          +	 *  	FORMATTER / Inserting New Line Between Else/If 
          +	 *      When Insert, a blank line is inserted between an else and an if when they are 
          +	 *      contiguous. When choosing to not insert, else-if will be kept on the same
          +	 *      line when possible.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.formatter.newline.elseIf"
          +	 *       - possible values:   { "insert", "do not insert" }
          +	 *       - default:           "do not insert"
          +	 *   
          +	 *  	FORMATTER / Inserting New Line In Empty Block
          +	 *      When insert, a line break is inserted between contiguous { and }, if } is not followed
          +	 *      by a keyword.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.formatter.newline.emptyBlock"
          +	 *       - possible values:   { "insert", "do not insert" }
          +	 *       - default:           "insert"
          +	 *   
          +	 *  	FORMATTER / Splitting Lines Exceeding Length
          +	 *      Enable splitting of long lines (exceeding the configurable length). Length of 0 will
          +	 *      disable line splitting
          +	 *       - option id:         "org.phpeclipse.phpdt.core.formatter.lineSplit"
          +	 *       - possible values:	"<n>", where n is zero or a positive integer
          +	 *       - default:           "80"
          +	 *   
          +	 *  	FORMATTER / Compacting Assignment
          +	 *      Assignments can be formatted asymmetrically, e.g. 'int x= 2;', when Normal, a space
          +	 *      is inserted before the assignment operator
          +	 *       - option id:         "org.phpeclipse.phpdt.core.formatter.style.assignment"
          +	 *       - possible values:   { "compact", "normal" }
          +	 *       - default:           "normal"
          +	 *   
          +	 *  	FORMATTER / Defining Indentation Character
          +	 *      Either choose to indent with tab characters or spaces
          +	 *       - option id:         "org.phpeclipse.phpdt.core.formatter.tabulation.char"
          +	 *       - possible values:   { "tab", "space" }
          +	 *       - default:           "tab"
          +	 *   
          +	 *  	FORMATTER / Defining Space Indentation Length
          +	 *      When using spaces, set the amount of space characters to use for each 
          +	 *      indentation mark.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.formatter.tabulation.size"
          +	 *       - possible values:	"<n>", where n is a positive integer
          +	 *       - default:           "4"
          +	 *   
          +	 *  	CODEASSIST / Activate Visibility Sensitive Completion
          +	 *      When active, completion doesn't show that you can not see
          +	 *      (e.g. you can not see private methods of a super class).
          +	 *       - option id:         "org.phpeclipse.phpdt.core.codeComplete.visibilityCheck"
          +	 *       - possible values:   { "enabled", "disabled" }
          +	 *       - default:           "disabled"
          +	 *   
          +	 *  	CODEASSIST / Automatic Qualification of Implicit Members
          +	 *      When active, completion automatically qualifies completion on implicit
          +	 *      field references and message expressions.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.codeComplete.forceImplicitQualification"
          +	 *       - possible values:   { "enabled", "disabled" }
          +	 *       - default:           "disabled"
          +	 *   
          +	 *    CODEASSIST / Define the Prefixes for Field Name
          +	 *      When the prefixes is non empty, completion for field name will begin with
          +	 *      one of the proposed prefixes.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.codeComplete.fieldPrefixes"
          +	 *       - possible values:   { "<prefix>[,<prefix>]*" } where <prefix> is a String without any wild-card 
          +	 *       - default:           ""
          +	 *   
          +	 *    CODEASSIST / Define the Prefixes for Static Field Name
          +	 *      When the prefixes is non empty, completion for static field name will begin with
          +	 *      one of the proposed prefixes.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.codeComplete.staticFieldPrefixes"
          +	 *       - possible values:   { "<prefix>[,<prefix>]*" } where <prefix> is a String without any wild-card 
          +	 *       - default:           ""
          +	 *   
          +	 *    CODEASSIST / Define the Prefixes for Local Variable Name
          +	 *      When the prefixes is non empty, completion for local variable name will begin with
          +	 *      one of the proposed prefixes.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.codeComplete.localPrefixes"
          +	 *       - possible values:   { "<prefix>[,<prefix>]*" } where <prefix> is a String without any wild-card 
          +	 *       - default:           ""
          +	 *   
          +	 *    CODEASSIST / Define the Prefixes for Argument Name
          +	 *      When the prefixes is non empty, completion for argument name will begin with
          +	 *      one of the proposed prefixes.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.codeComplete.argumentPrefixes"
          +	 *       - possible values:   { "<prefix>[,<prefix>]*" } where <prefix> is a String without any wild-card 
          +	 *       - default:           ""
          +	 *   
          +	 *    CODEASSIST / Define the Suffixes for Field Name
          +	 *      When the suffixes is non empty, completion for field name will end with
          +	 *      one of the proposed suffixes.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.codeComplete.fieldSuffixes"
          +	 *       - possible values:   { "<suffix>[,<suffix>]*" } where <suffix> is a String without any wild-card 
          +	 *       - default:           ""
          +	 *   
          +	 *    CODEASSIST / Define the Suffixes for Static Field Name
          +	 *      When the suffixes is non empty, completion for static field name will end with
          +	 *      one of the proposed suffixes.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.codeComplete.staticFieldSuffixes"
          +	 *       - possible values:   { "<suffix>[,<suffix>]*" } where <suffix> is a String without any wild-card 
          +	 *       - default:           ""
          +	 *   
          +	 *    CODEASSIST / Define the Suffixes for Local Variable Name
          +	 *      When the suffixes is non empty, completion for local variable name will end with
          +	 *      one of the proposed suffixes.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.codeComplete.localSuffixes"
          +	 *       - possible values:   { "<suffix>[,<suffix>]*" } where <suffix> is a String without any wild-card 
          +	 *       - default:           ""
          +	 *   
          +	 *    CODEASSIST / Define the Suffixes for Argument Name
          +	 *      When the suffixes is non empty, completion for argument name will end with
          +	 *      one of the proposed suffixes.
          +	 *       - option id:         "org.phpeclipse.phpdt.core.codeComplete.argumentSuffixes"
          +	 *       - possible values:   { "<suffix>[,<suffix>]*" } where <prefix> is a String without any wild-card 
          +	 *       - default:           ""
          +	 *   </pre>
          +	 *   
          +	 *   @return a mutable table containing the default settings of all known options
          +	 *     (key type: 
           	 * 
           	 * String
           	 * 
          -	 * ; value type: 
          +	 *  ; value type: 
           	 * 
           	 * String
           	 * 
          -	 * )
          -	 *  @see #setOptions
          +	 *  )
          +	 *   @see #setOptions
           	 * 
           	 */
          -	//  public static Hashtable getDefaultOptions() {
          +	// public static Hashtable getDefaultOptions() {
           	//
          -	//    Hashtable defaultOptions = new Hashtable(10);
          +	// Hashtable defaultOptions = new Hashtable(10);
           	//
          -	//    // see #initializeDefaultPluginPreferences() for changing default
          +	// // see #initializeDefaultPluginPreferences() for changing default
           	// settings
          -	//    Preferences preferences = getPlugin().getPluginPreferences();
          -	//    HashSet optionNames = OptionNames;
          +	// Preferences preferences = getPlugin().getPluginPreferences();
          +	// HashSet optionNames = OptionNames;
           	//
          -	//    // get preferences set to their default
          -	//    String[] defaultPropertyNames = preferences.defaultPropertyNames();
          -	//    for (int i = 0; i < defaultPropertyNames.length; i++) {
          -	//      String propertyName = defaultPropertyNames[i];
          -	//      if (optionNames.contains(propertyName)) {
          -	//        defaultOptions.put(propertyName,
          +	// // get preferences set to their default
          +	// String[] defaultPropertyNames = preferences.defaultPropertyNames();
          +	// for (int i = 0; i < defaultPropertyNames.length; i++) {
          +	// String propertyName = defaultPropertyNames[i];
          +	// if (optionNames.contains(propertyName)) {
          +	// defaultOptions.put(propertyName,
           	// preferences.getDefaultString(propertyName));
          -	//      }
          -	//    }
          -	//    // get preferences not set to their default
          -	//    String[] propertyNames = preferences.propertyNames();
          -	//    for (int i = 0; i < propertyNames.length; i++) {
          -	//      String propertyName = propertyNames[i];
          -	//      if (optionNames.contains(propertyName)) {
          -	//        defaultOptions.put(propertyName,
          +	// }
          +	// }
          +	// // get preferences not set to their default
          +	// String[] propertyNames = preferences.propertyNames();
          +	// for (int i = 0; i < propertyNames.length; i++) {
          +	// String propertyName = propertyNames[i];
          +	// if (optionNames.contains(propertyName)) {
          +	// defaultOptions.put(propertyName,
           	// preferences.getDefaultString(propertyName));
          -	//      }
          -	//    }
          -	//    // get encoding through resource plugin
          -	//    defaultOptions.put(CORE_ENCODING, ResourcesPlugin.getEncoding());
          +	// }
          +	// }
          +	// // get encoding through resource plugin
          +	// defaultOptions.put(CORE_ENCODING, ResourcesPlugin.getEncoding());
           	//
          -	//    return defaultOptions;
          -	//  }
          +	// return defaultOptions;
          +	// }
           	/**
           	 * Helper method for returning one option value only. Equivalent to
           	 * (String)JavaCore.getOptions().get(optionName) Note that it
          @@ -1263,17 +1262,17 @@ public class JavaCore {
           	 * @see JavaCore#getDefaultOptions
           	 * @since 2.0
           	 */
          -	//  public static String getOption(String optionName) {
          +	// public static String getOption(String optionName) {
           	//
          -	//    if (CORE_ENCODING.equals(optionName)) {
          -	//      return ResourcesPlugin.getEncoding();
          -	//    }
          -	//    if (OptionNames.contains(optionName)) {
          -	//      Preferences preferences = getPlugin().getPluginPreferences();
          -	//      return preferences.getString(optionName).trim();
          -	//    }
          -	//    return null;
          -	//  }
          +	// if (CORE_ENCODING.equals(optionName)) {
          +	// return ResourcesPlugin.getEncoding();
          +	// }
          +	// if (OptionNames.contains(optionName)) {
          +	// Preferences preferences = getPlugin().getPluginPreferences();
          +	// return preferences.getString(optionName).trim();
          +	// }
          +	// return null;
          +	// }
           	/**
           	 * Returns the table of the current options. Initially, all options have
           	 * their default values, and this method returns a table that includes all
          @@ -1287,38 +1286,38 @@ public class JavaCore {
           	 *         String; value type: String)
           	 * @see JavaCore#getDefaultOptions
           	 */
          -	//  public static Hashtable getOptions() {
          +	// public static Hashtable getOptions() {
           	//
          -	//    Hashtable options = new Hashtable(10);
          +	// Hashtable options = new Hashtable(10);
           	//
          -	//    // see #initializeDefaultPluginPreferences() for changing default
          +	// // see #initializeDefaultPluginPreferences() for changing default
           	// settings
          -	//    Plugin plugin = getPlugin();
          -	//    if (plugin != null) {
          -	//      Preferences preferences = getPlugin().getPluginPreferences();
          -	//      HashSet optionNames = OptionNames;
          +	// Plugin plugin = getPlugin();
          +	// if (plugin != null) {
          +	// Preferences preferences = getPlugin().getPluginPreferences();
          +	// HashSet optionNames = OptionNames;
           	//
          -	//      // get preferences set to their default
          -	//      String[] defaultPropertyNames = preferences.defaultPropertyNames();
          -	//      for (int i = 0; i < defaultPropertyNames.length; i++) {
          -	//        String propertyName = defaultPropertyNames[i];
          -	//        if (optionNames.contains(propertyName)) {
          -	//          options.put(propertyName, preferences.getDefaultString(propertyName));
          -	//        }
          -	//      }
          -	//      // get preferences not set to their default
          -	//      String[] propertyNames = preferences.propertyNames();
          -	//      for (int i = 0; i < propertyNames.length; i++) {
          -	//        String propertyName = propertyNames[i];
          -	//        if (optionNames.contains(propertyName)) {
          -	//          options.put(propertyName, preferences.getString(propertyName).trim());
          -	//        }
          -	//      }
          -	//      // get encoding through resource plugin
          -	//      options.put(CORE_ENCODING, ResourcesPlugin.getEncoding());
          -	//    }
          -	//    return options;
          -	//  }
          +	// // get preferences set to their default
          +	// String[] defaultPropertyNames = preferences.defaultPropertyNames();
          +	// for (int i = 0; i < defaultPropertyNames.length; i++) {
          +	// String propertyName = defaultPropertyNames[i];
          +	// if (optionNames.contains(propertyName)) {
          +	// options.put(propertyName, preferences.getDefaultString(propertyName));
          +	// }
          +	// }
          +	// // get preferences not set to their default
          +	// String[] propertyNames = preferences.propertyNames();
          +	// for (int i = 0; i < propertyNames.length; i++) {
          +	// String propertyName = propertyNames[i];
          +	// if (optionNames.contains(propertyName)) {
          +	// options.put(propertyName, preferences.getString(propertyName).trim());
          +	// }
          +	// }
          +	// // get encoding through resource plugin
          +	// options.put(CORE_ENCODING, ResourcesPlugin.getEncoding());
          +	// }
          +	// return options;
          +	// }
           	/**
           	 * Sets the current table of options. All and only the options explicitly
           	 * included in the given table are remembered; all previous option settings
          @@ -1334,29 +1333,29 @@ public class JavaCore {
           	 *            options to their default values
           	 * @see JavaCore#getDefaultOptions
           	 */
          -	//  public static void setOptions(Hashtable newOptions) {
          +	// public static void setOptions(Hashtable newOptions) {
           	//
          -	//    // see #initializeDefaultPluginPreferences() for changing default
          +	// // see #initializeDefaultPluginPreferences() for changing default
           	// settings
          -	//    Preferences preferences = getPlugin().getPluginPreferences();
          +	// Preferences preferences = getPlugin().getPluginPreferences();
           	//
          -	//    if (newOptions == null) {
          -	//      newOptions = getDefaultOptions();
          -	//    }
          -	//    Enumeration keys = newOptions.keys();
          -	//    while (keys.hasMoreElements()) {
          -	//      String key = (String) keys.nextElement();
          -	//      if (!OptionNames.contains(key))
          -	//        continue; // unrecognized option
          -	//      if (key.equals(CORE_ENCODING))
          -	//        continue; // skipped, contributed by resource prefs
          -	//      String value = (String) newOptions.get(key);
          -	//      preferences.setValue(key, value);
          -	//    }
          +	// if (newOptions == null) {
          +	// newOptions = getDefaultOptions();
          +	// }
          +	// Enumeration keys = newOptions.keys();
          +	// while (keys.hasMoreElements()) {
          +	// String key = (String) keys.nextElement();
          +	// if (!OptionNames.contains(key))
          +	// continue; // unrecognized option
          +	// if (key.equals(CORE_ENCODING))
          +	// continue; // skipped, contributed by resource prefs
          +	// String value = (String) newOptions.get(key);
          +	// preferences.setValue(key, value);
          +	// }
           	//
          -	//    // persist options
          -	//    getPlugin().savePluginPreferences();
          -	//  }
          +	// // persist options
          +	// getPlugin().savePluginPreferences();
          +	// }
           	public static IProject[] getPHPProjects() {
           		List phpProjectsList = new ArrayList();
           		IProject[] workspaceProjects = PHPeclipsePlugin.getWorkspace()
          @@ -1372,16 +1371,16 @@ public class JavaCore {
           		return (IProject[]) phpProjectsList.toArray(phpProjects);
           	}
           
          -	//  public static PHPProject getPHPProject(String name) {
          -	//    IProject aProject =
          +	// public static PHPProject getPHPProject(String name) {
          +	// IProject aProject =
           	// PHPeclipsePlugin.getWorkspace().getRoot().getProject(name);
          -	//    if (isPHPProject(aProject)) {
          -	//      PHPProject thePHPProject = new PHPProject();
          -	//      thePHPProject.setProject(aProject);
          -	//      return thePHPProject;
          -	//    }
          -	//    return null;
          -	//  }
          +	// if (isPHPProject(aProject)) {
          +	// PHPProject thePHPProject = new PHPProject();
          +	// thePHPProject.setProject(aProject);
          +	// return thePHPProject;
          +	// }
          +	// return null;
          +	// }
           
           	public static boolean isPHPProject(IProject aProject) {
           		try {
          @@ -1392,38 +1391,38 @@ public class JavaCore {
           		return false;
           	}
           
          -	//  public static PHPFile create(IFile aFile) {
          -	//    if (PHPFile.EXTENSION.equalsIgnoreCase(aFile.getFileExtension()))
          -	//      return new PHPFile(aFile);
          -	//    if (PHPFile.EXTENSION1.equalsIgnoreCase(aFile.getFileExtension()))
          -	//      return new PHPFile(aFile);
          -	//    if (PHPFile.EXTENSION2.equalsIgnoreCase(aFile.getFileExtension()))
          -	//      return new PHPFile(aFile);
          -	//    if (PHPFile.EXTENSION3.equalsIgnoreCase(aFile.getFileExtension()))
          -	//      return new PHPFile(aFile);
          -	//    if (PHPFile.EXTENSION4.equalsIgnoreCase(aFile.getFileExtension()))
          -	//      return new PHPFile(aFile);
          -	//    if (PHPFile.EXTENSION5.equalsIgnoreCase(aFile.getFileExtension()))
          -	//      return new PHPFile(aFile);
          +	// public static PHPFile create(IFile aFile) {
          +	// if (PHPFile.EXTENSION.equalsIgnoreCase(aFile.getFileExtension()))
          +	// return new PHPFile(aFile);
          +	// if (PHPFile.EXTENSION1.equalsIgnoreCase(aFile.getFileExtension()))
          +	// return new PHPFile(aFile);
          +	// if (PHPFile.EXTENSION2.equalsIgnoreCase(aFile.getFileExtension()))
          +	// return new PHPFile(aFile);
          +	// if (PHPFile.EXTENSION3.equalsIgnoreCase(aFile.getFileExtension()))
          +	// return new PHPFile(aFile);
          +	// if (PHPFile.EXTENSION4.equalsIgnoreCase(aFile.getFileExtension()))
          +	// return new PHPFile(aFile);
          +	// if (PHPFile.EXTENSION5.equalsIgnoreCase(aFile.getFileExtension()))
          +	// return new PHPFile(aFile);
           	//
          -	//    return null;
          -	//  }
          +	// return null;
          +	// }
           
          -	//  public static PHPProject create(IProject aProject) {
          +	// public static PHPProject create(IProject aProject) {
           	//	
          -	//    try {
          -	//      if (aProject.hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) {
          -	//        PHPProject project = new PHPProject();
          -	//        project.setProject(aProject);
          -	//        return project;
          -	//      }
          -	//    } catch (CoreException e) {
          -	//      System.err.println("Exception occurred in PHPCore#create(IProject): " +
          +	// try {
          +	// if (aProject.hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) {
          +	// PHPProject project = new PHPProject();
          +	// project.setProject(aProject);
          +	// return project;
          +	// }
          +	// } catch (CoreException e) {
          +	// System.err.println("Exception occurred in PHPCore#create(IProject): " +
           	// e.toString());
          -	//    }
          +	// }
           	//
          -	//    return null;
          -	//  }
          +	// return null;
          +	// }
           
           	public static void addPHPNature(IProject project, IProgressMonitor monitor)
           			throws CoreException {
          @@ -1476,10 +1475,10 @@ public class JavaCore {
           	 *                if the operation failed.
           	 * @since 2.1
           	 */
          -	//	public static void run(IWorkspaceRunnable action, IProgressMonitor
          +	// public static void run(IWorkspaceRunnable action, IProgressMonitor
           	// monitor) throws CoreException {
          -	//		run(action, ResourcesPlugin.getWorkspace().getRoot(), monitor);
          -	//	}
          +	// run(action, ResourcesPlugin.getWorkspace().getRoot(), monitor);
          +	// }
           	/**
           	 * Runs the given action as an atomic Java model operation.
           	 * 

          @@ -1518,19 +1517,18 @@ public class JavaCore { * if the operation failed. * @since 3.0 */ - // public static void run(IWorkspaceRunnable action, ISchedulingRule rule, + // public static void run(IWorkspaceRunnable action, ISchedulingRule rule, // IProgressMonitor monitor) throws CoreException { - // IWorkspace workspace = ResourcesPlugin.getWorkspace(); - // if (workspace.isTreeLocked()) { - // new BatchOperation(action).run(monitor); - // } else { - // // use IWorkspace.run(...) to ensure that a build will be done in + // IWorkspace workspace = ResourcesPlugin.getWorkspace(); + // if (workspace.isTreeLocked()) { + // new BatchOperation(action).run(monitor); + // } else { + // // use IWorkspace.run(...) to ensure that a build will be done in // autobuild mode - // workspace.run(new BatchOperation(action), rule, IWorkspace.AVOID_UPDATE, + // workspace.run(new BatchOperation(action), rule, IWorkspace.AVOID_UPDATE, // monitor); - // } - // } - + // } + // } /** * Adds the given listener for changes to Java elements. Has no effect if an * identical listener is already registered. @@ -1598,27 +1596,32 @@ public class JavaCore { */ public static void addJavaElementMarkerAttributes(Map attributes, IJavaElement element) { - // if (element instanceof IMember) - // element = ((IMember) element).getClassFile(); + // if (element instanceof IMember) + // element = ((IMember) element).getClassFile(); if (attributes != null && element != null) attributes.put(ATT_HANDLE_ID, element.getHandleIdentifier()); } /** - * Adds the given listener for POST_CHANGE resource change events to the Java core. - * The listener is guarantied to be notified of the POST_CHANGE resource change event before - * the Java core starts processing the resource change event itself. + * Adds the given listener for POST_CHANGE resource change events to the + * Java core. The listener is guarantied to be notified of the POST_CHANGE + * resource change event before the Java core starts processing the resource + * change event itself. *

          * Has no effect if an identical listener is already registered. *

          * - * @param listener the listener + * @param listener + * the listener * @see #removePreProcessingResourceChangedListener(IResourceChangeListener) * @since 3.0 */ - public static void addPreProcessingResourceChangedListener(IResourceChangeListener listener) { - JavaModelManager.getJavaModelManager().deltaState.addPreResourceChangedListener(listener); + public static void addPreProcessingResourceChangedListener( + IResourceChangeListener listener) { + JavaModelManager.getJavaModelManager().deltaState + .addPreResourceChangedListener(listener); } + /** * Configures the given marker for the given Java element. Used for markers, * which denote a Java element rather than a resource. @@ -1633,8 +1636,8 @@ public class JavaCore { */ public void configureJavaElementMarker(IMarker marker, IJavaElement element) throws CoreException { - // if (element instanceof IMember) - // element = ((IMember) element).getClassFile(); + // if (element instanceof IMember) + // element = ((IMember) element).getClassFile(); if (marker != null && element != null) marker.setAttribute(ATT_HANDLE_ID, element.getHandleIdentifier()); } @@ -1657,28 +1660,31 @@ public class JavaCore { } /** - * Returns the Java model element corresponding to the given handle identifier - * generated by IJavaElement.getHandleIdentifier(), or - * null if unable to create the associated element. - * If the returned Java element is an ICompilationUnit, its owner - * is the given owner if such a working copy exists, otherwise the compilation unit - * is a primary compilation unit. - * - * @param handleIdentifier the given handle identifier - * @param owner the owner of the returned compilation unit, ignored if the returned - * element is not a compilation unit + * Returns the Java model element corresponding to the given handle + * identifier generated by IJavaElement.getHandleIdentifier(), + * or null if unable to create the associated element. If the + * returned Java element is an ICompilationUnit, its owner + * is the given owner if such a working copy exists, otherwise the + * compilation unit is a primary compilation unit. + * + * @param handleIdentifier + * the given handle identifier + * @param owner + * the owner of the returned compilation unit, ignored if the + * returned element is not a compilation unit * @return the Java element corresponding to the handle identifier * @since 3.0 */ - public static IJavaElement create(String handleIdentifier, WorkingCopyOwner owner) { + public static IJavaElement create(String handleIdentifier, + WorkingCopyOwner owner) { if (handleIdentifier == null) { return null; } MementoTokenizer memento = new MementoTokenizer(handleIdentifier); JavaModel model = JavaModelManager.getJavaModelManager().getJavaModel(); return model.getHandleFromMemento(memento, owner); - } - + } + /** * Returns the Java element corresponding to the given file, or * null if unable to associate the given file with a Java @@ -1811,9 +1817,9 @@ public class JavaCore { * @return a class file element for the given .class file, or * null if unable to recognize the class file */ - //public static IClassFile createClassFileFrom(IFile file) { - // return JavaModelManager.createClassFileFrom(file, null); - //} + // public static IClassFile createClassFileFrom(IFile file) { + // return JavaModelManager.createClassFileFrom(file, null); + // } /** * Creates and returns a compilation unit element for the given * .java file. Returns null if unable to @@ -1839,10 +1845,10 @@ public class JavaCore { * to create a JAR package fragment root. (for example, if the JAR * file represents a non-Java resource) */ - //public static IPackageFragmentRoot createJarPackageFragmentRootFrom(IFile + // public static IPackageFragmentRoot createJarPackageFragmentRootFrom(IFile // file) { - // return JavaModelManager.createJarPackageFragmentRootFrom(file, null); - //} + // return JavaModelManager.createJarPackageFragmentRootFrom(file, null); + // } /** * Answers the project specific value for a given classpath container. In * case this container path could not be resolved, then will answer @@ -1887,86 +1893,87 @@ public class JavaCore { * IProgressMonitor) * @since 2.0 */ - //public static IClasspathContainer getClasspathContainer(final IPath + // public static IClasspathContainer getClasspathContainer(final IPath // containerPath, final IJavaProject project) throws JavaModelException { // - // IClasspathContainer container = JavaModelManager.containerGet(project, + // IClasspathContainer container = JavaModelManager.containerGet(project, // containerPath); - // if (container == JavaModelManager.ContainerInitializationInProgress) + // if (container == JavaModelManager.ContainerInitializationInProgress) // return null; // break cycle // - // if (container == null){ - // final ClasspathContainerInitializer initializer = + // if (container == null){ + // final ClasspathContainerInitializer initializer = // JavaCore.getClasspathContainerInitializer(containerPath.segment(0)); - // if (initializer != null){ - // if (JavaModelManager.CP_RESOLVE_VERBOSE){ - // System.out.println("CPContainer INIT - triggering initialization of: + // if (initializer != null){ + // if (JavaModelManager.CP_RESOLVE_VERBOSE){ + // System.out.println("CPContainer INIT - triggering initialization of: // ["+project.getElementName()+"] " + containerPath + " using initializer: // "+ initializer); //$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$ - // new Exception("FAKE exception for dumping current CPContainer + // new Exception("FAKE exception for dumping current CPContainer // (["+project.getElementName()+"] "+ containerPath+ ")INIT invocation stack // trace").printStackTrace(); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ - // } - // JavaModelManager.containerPut(project, containerPath, + // } + // JavaModelManager.containerPut(project, containerPath, // JavaModelManager.ContainerInitializationInProgress); // avoid // initialization cycles - // boolean ok = false; - // try { - // // wrap initializer call with Safe runnable in case initializer would be + // boolean ok = false; + // try { + // // wrap initializer call with Safe runnable in case initializer would be // causing some grief - // Platform.run(new ISafeRunnable() { - // public void handleException(Throwable exception) { - // ProjectPrefUtil.log(exception, "Exception occurred in classpath container + // Platform.run(new ISafeRunnable() { + // public void handleException(Throwable exception) { + // ProjectPrefUtil.log(exception, "Exception occurred in classpath container // initializer: "+initializer); //$NON-NLS-1$ - // } - // public void run() throws Exception { - // initializer.initialize(containerPath, project); - // } - // }); + // } + // public void run() throws Exception { + // initializer.initialize(containerPath, project); + // } + // }); // - // // retrieve value (if initialization was successful) - // container = JavaModelManager.containerGet(project, containerPath); - // if (container == JavaModelManager.ContainerInitializationInProgress) + // // retrieve value (if initialization was successful) + // container = JavaModelManager.containerGet(project, containerPath); + // if (container == JavaModelManager.ContainerInitializationInProgress) // return null; // break cycle - // ok = true; - // } finally { - // if (!ok) JavaModelManager.containerPut(project, containerPath, null); // + // ok = true; + // } finally { + // if (!ok) JavaModelManager.containerPut(project, containerPath, null); // // flush cache - // } - // if (JavaModelManager.CP_RESOLVE_VERBOSE){ - // System.out.print("CPContainer INIT - after resolution: + // } + // if (JavaModelManager.CP_RESOLVE_VERBOSE){ + // System.out.print("CPContainer INIT - after resolution: // ["+project.getElementName()+"] " + containerPath + " --> "); // //$NON-NLS-2$//$NON-NLS-1$//$NON-NLS-3$ - // if (container != null){ - // System.out.print("container: "+container.getDescription()+" {"); + // if (container != null){ + // System.out.print("container: "+container.getDescription()+" {"); // //$NON-NLS-2$//$NON-NLS-1$ - // IClasspathEntry[] entries = container.getClasspathEntries(); - // if (entries != null){ - // for (int i = 0; i < entries.length; i++){ - // if (i > 0) System.out.println(", ");//$NON-NLS-1$ - // System.out.println(entries[i]); - // } - // } - // System.out.println("}");//$NON-NLS-1$ - // } else { - // System.out.println("{unbound}");//$NON-NLS-1$ - // } - // } - // } else { - // if (JavaModelManager.CP_RESOLVE_VERBOSE){ - // System.out.println("CPContainer INIT - no initializer found for: + // IClasspathEntry[] entries = container.getClasspathEntries(); + // if (entries != null){ + // for (int i = 0; i < entries.length; i++){ + // if (i > 0) System.out.println(", ");//$NON-NLS-1$ + // System.out.println(entries[i]); + // } + // } + // System.out.println("}");//$NON-NLS-1$ + // } else { + // System.out.println("{unbound}");//$NON-NLS-1$ + // } + // } + // } else { + // if (JavaModelManager.CP_RESOLVE_VERBOSE){ + // System.out.println("CPContainer INIT - no initializer found for: // "+project.getElementName()+"] " + containerPath); //$NON-NLS-1$ // //$NON-NLS-2$ - // } - // } - // } - // return container; - //} + // } + // } + // } + // return container; + // } /** * Helper method finding the classpath container initializer registered for * a given classpath container ID or null if none was found * while iterating over the contributions to extension point to the - * extension point "net.sourceforge.phpdt.core.classpathContainerInitializer". + * extension point + * "net.sourceforge.phpdt.core.classpathContainerInitializer". *

          * A containerID is the first segment of any container path, used to * identify the registered container initializer. @@ -1978,42 +1985,42 @@ public class JavaCore { * container initializer or null if none was found. * @since 2.1 */ - //public static ClasspathContainerInitializer + // public static ClasspathContainerInitializer // getClasspathContainerInitializer(String containerID){ // - // Plugin jdtCorePlugin = JavaCore.getPlugin(); - // if (jdtCorePlugin == null) return null; + // Plugin jdtCorePlugin = JavaCore.getPlugin(); + // if (jdtCorePlugin == null) return null; // - // IExtensionPoint extension = + // IExtensionPoint extension = // jdtCorePlugin.getDescriptor().getExtensionPoint(JavaModelManager.CPCONTAINER_INITIALIZER_EXTPOINT_ID); - // if (extension != null) { - // IExtension[] extensions = extension.getExtensions(); - // for(int i = 0; i < extensions.length; i++){ - // IConfigurationElement [] configElements = + // if (extension != null) { + // IExtension[] extensions = extension.getExtensions(); + // for(int i = 0; i < extensions.length; i++){ + // IConfigurationElement [] configElements = // extensions[i].getConfigurationElements(); - // for(int j = 0; j < configElements.length; j++){ - // String initializerID = configElements[j].getAttribute("id"); + // for(int j = 0; j < configElements.length; j++){ + // String initializerID = configElements[j].getAttribute("id"); // //$NON-NLS-1$ - // if (initializerID != null && initializerID.equals(containerID)){ - // if (JavaModelManager.CP_RESOLVE_VERBOSE) { - // System.out.println("CPContainer INIT - found initializer: "+containerID + // if (initializerID != null && initializerID.equals(containerID)){ + // if (JavaModelManager.CP_RESOLVE_VERBOSE) { + // System.out.println("CPContainer INIT - found initializer: "+containerID // +" --> " + // configElements[j].getAttribute("class"));//$NON-NLS-3$//$NON-NLS-2$//$NON-NLS-1$ - // } - // try { - // Object execExt = configElements[j].createExecutableExtension("class"); + // } + // try { + // Object execExt = configElements[j].createExecutableExtension("class"); // //$NON-NLS-1$ - // if (execExt instanceof ClasspathContainerInitializer){ - // return (ClasspathContainerInitializer)execExt; - // } - // } catch(CoreException e) { - // } - // } - // } - // } - // } - // return null; - //} + // if (execExt instanceof ClasspathContainerInitializer){ + // return (ClasspathContainerInitializer)execExt; + // } + // } catch(CoreException e) { + // } + // } + // } + // } + // } + // return null; + // } /** * Returns the path held in the given classpath variable. Returns null * if unable to bind. @@ -2023,10 +2030,10 @@ public class JavaCore { *

          * Note that classpath variables can be contributed registered initializers * for, using the extension point - * "net.sourceforge.phpdt.core.classpathVariableInitializer". If an initializer is - * registered for a variable, its persisted value will be ignored: its - * initializer will thus get the opportunity to rebind the variable - * differently on each session. + * "net.sourceforge.phpdt.core.classpathVariableInitializer". If an + * initializer is registered for a variable, its persisted value will be + * ignored: its initializer will thus get the opportunity to rebind the + * variable differently on each session. * * @param variableName * the name of the classpath variable @@ -2045,54 +2052,55 @@ public class JavaCore { // even if persisted value exists, initializer is given priority, only // if no initializer is found the persisted value is reused - // final ClasspathVariableInitializer initializer = + // final ClasspathVariableInitializer initializer = // PHPCore.getClasspathVariableInitializer(variableName); - // if (initializer != null){ - // if (JavaModelManager.CP_RESOLVE_VERBOSE){ - // System.out.println("CPVariable INIT - triggering initialization of: " + // if (initializer != null){ + // if (JavaModelManager.CP_RESOLVE_VERBOSE){ + // System.out.println("CPVariable INIT - triggering initialization of: " // + variableName+ " using initializer: "+ initializer); //$NON-NLS-1$ // //$NON-NLS-2$ - // new Exception("FAKE exception for dumping current CPVariable + // new Exception("FAKE exception for dumping current CPVariable // ("+variableName+ ")INIT invocation stack trace").printStackTrace(); // //$NON-NLS-1$//$NON-NLS-2$ - // } - // JavaModelManager.variablePut(variableName, + // } + // JavaModelManager.variablePut(variableName, // JavaModelManager.VariableInitializationInProgress); // avoid // initialization cycles - // boolean ok = false; - // try { - // // wrap initializer call with Safe runnable in case initializer would + // boolean ok = false; + // try { + // // wrap initializer call with Safe runnable in case initializer would // be causing some grief - // Platform.run(new ISafeRunnable() { - // public void handleException(Throwable exception) { - // ProjectPrefUtil.log(exception, "Exception occurred in classpath variable + // Platform.run(new ISafeRunnable() { + // public void handleException(Throwable exception) { + // ProjectPrefUtil.log(exception, "Exception occurred in classpath + // variable // initializer: "+initializer+" while initializing variable: // "+variableName); //$NON-NLS-1$ //$NON-NLS-2$ - // } - // public void run() throws Exception { - // initializer.initialize(variableName); - // } - // }); - // variablePath = (IPath) JavaModelManager.variableGet(variableName); // + // } + // public void run() throws Exception { + // initializer.initialize(variableName); + // } + // }); + // variablePath = (IPath) JavaModelManager.variableGet(variableName); // // initializer should have performed side-effect - // if (variablePath == + // if (variablePath == // JavaModelManager.VariableInitializationInProgress) return null; // // break cycle (initializer did not init or reentering call) - // if (JavaModelManager.CP_RESOLVE_VERBOSE){ - // System.out.println("CPVariable INIT - after initialization: " + + // if (JavaModelManager.CP_RESOLVE_VERBOSE){ + // System.out.println("CPVariable INIT - after initialization: " + // variableName + " --> " + variablePath); //$NON-NLS-2$//$NON-NLS-1$ - // } - // ok = true; - // } finally { - // if (!ok) JavaModelManager.variablePut(variableName, null); // flush + // } + // ok = true; + // } finally { + // if (!ok) JavaModelManager.variablePut(variableName, null); // flush // cache - // } - // } else { - // if (JavaModelManager.CP_RESOLVE_VERBOSE){ - // System.out.println("CPVariable INIT - no initializer found for: " + + // } + // } else { + // if (JavaModelManager.CP_RESOLVE_VERBOSE){ + // System.out.println("CPVariable INIT - no initializer found for: " + // variableName); //$NON-NLS-1$ - // } - // } + // } + // } return variablePath; } @@ -2100,7 +2108,8 @@ public class JavaCore { * Helper method finding the classpath variable initializer registered for a * given classpath variable name or null if none was found * while iterating over the contributions to extension point to the - * extension point "net.sourceforge.phpdt.core.classpathVariableInitializer". + * extension point + * "net.sourceforge.phpdt.core.classpathVariableInitializer". *

          * * @param the @@ -2116,34 +2125,34 @@ public class JavaCore { if (jdtCorePlugin == null) return null; - // IExtensionPoint extension = + // IExtensionPoint extension = // jdtCorePlugin.getDescriptor().getExtensionPoint(JavaModelManager.CPVARIABLE_INITIALIZER_EXTPOINT_ID); - // if (extension != null) { - // IExtension[] extensions = extension.getExtensions(); - // for(int i = 0; i < extensions.length; i++){ - // IConfigurationElement [] configElements = + // if (extension != null) { + // IExtension[] extensions = extension.getExtensions(); + // for(int i = 0; i < extensions.length; i++){ + // IConfigurationElement [] configElements = // extensions[i].getConfigurationElements(); - // for(int j = 0; j < configElements.length; j++){ - // try { - // String varAttribute = configElements[j].getAttribute("variable"); + // for(int j = 0; j < configElements.length; j++){ + // try { + // String varAttribute = configElements[j].getAttribute("variable"); // //$NON-NLS-1$ - // if (variable.equals(varAttribute)) { - // if (JavaModelManager.CP_RESOLVE_VERBOSE) { - // System.out.println("CPVariable INIT - found initializer: "+variable+" + // if (variable.equals(varAttribute)) { + // if (JavaModelManager.CP_RESOLVE_VERBOSE) { + // System.out.println("CPVariable INIT - found initializer: "+variable+" // --> " + // configElements[j].getAttribute("class"));//$NON-NLS-3$//$NON-NLS-2$//$NON-NLS-1$ - // } - // Object execExt = + // } + // Object execExt = // configElements[j].createExecutableExtension("class"); //$NON-NLS-1$ - // if (execExt instanceof ClasspathVariableInitializer){ - // return (ClasspathVariableInitializer)execExt; - // } - // } - // } catch(CoreException e){ - // } - // } - // } - // } + // if (execExt instanceof ClasspathVariableInitializer){ + // return (ClasspathVariableInitializer)execExt; + // } + // } + // } catch(CoreException e){ + // } + // } + // } + // } return null; } @@ -2157,9 +2166,9 @@ public class JavaCore { * @return the list of classpath variable names * @see #setClasspathVariable */ - //public static String[] getClasspathVariableNames() { - // return JavaModelManager.variableNames(); - //} + // public static String[] getClasspathVariableNames() { + // return JavaModelManager.variableNames(); + // } /** * Returns a table of all known configurable options with their default * values. These options allow to configure the behaviour of the underlying @@ -2172,453 +2181,453 @@ public class JavaCore { * Note: more options might be added in further releases. * *

          -	 * 
          -	 *  RECOGNIZED OPTIONS:
          -	 *  COMPILER / Generating Local Variable Debug Attribute
          -	 *     When generated, this attribute will enable local variable names 
          -	 *     to be displayed in debugger, only in place where variables are 
          -	 *     definitely assigned (.class file is then bigger)
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.debug.localVariable"
          -	 *      - possible values:   { "generate", "do not generate" }
          -	 *      - default:           "generate"
          -	 * 
          -	 *  COMPILER / Generating Line Number Debug Attribute 
          -	 *     When generated, this attribute will enable source code highlighting in debugger 
          -	 *     (.class file is then bigger).
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.debug.lineNumber"
          -	 *      - possible values:   { "generate", "do not generate" }
          -	 *      - default:           "generate"
          -	 *     
          -	 *  COMPILER / Generating Source Debug Attribute 
          -	 *     When generated, this attribute will enable the debugger to present the 
          -	 *     corresponding source code.
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.debug.sourceFile"
          -	 *      - possible values:   { "generate", "do not generate" }
          -	 *      - default:           "generate"
          -	 *     
          -	 *  COMPILER / Preserving Unused Local Variables
          -	 *     Unless requested to preserve unused local variables (that is, never read), the 
          -	 *     compiler will optimize them out, potentially altering debugging
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.codegen.unusedLocal"
          -	 *      - possible values:   { "preserve", "optimize out" }
          -	 *      - default:           "preserve"
          -	 *  
          -	 *  COMPILER / Defining Target Java Platform
          -	 *     For binary compatibility reason, .class files can be tagged to with certain VM versions and later.
          -	 *     Note that "1.4" target require to toggle compliance mode to "1.4" too.
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.codegen.targetPlatform"
          -	 *      - possible values:   { "1.1", "1.2", "1.3", "1.4" }
          -	 *      - default:           "1.1"
          -	 * 
          -	 *  COMPILER / Reporting Unreachable Code
          -	 *     Unreachable code can optionally be reported as an error, warning or simply 
          -	 *     ignored. The bytecode generation will always optimized it out.
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.problem.unreachableCode"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "error"
          -	 * 
          -	 *  COMPILER / Reporting Invalid Import
          -	 *     An import statement that cannot be resolved might optionally be reported 
          -	 *     as an error, as a warning or ignored.
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.problem.invalidImport"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "error"
          -	 * 
          -	 *  COMPILER / Reporting Attempt to Override Package-Default Method
          -	 *     A package default method is not visible in a different package, and thus 
          -	 *     cannot be overridden. When enabling this option, the compiler will signal 
          -	 *     such scenarii either as an error or a warning.
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.problem.overridingPackageDefaultMethod"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "warning"
          -	 * 
          -	 *  COMPILER / Reporting Method With Constructor Name
          -	 *     Naming a method with a constructor name is generally considered poor 
          -	 *     style programming. When enabling this option, the compiler will signal such 
          -	 *     scenarii either as an error or a warning.
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.problem.methodWithConstructorName"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "warning"
          -	 * 
          -	 *  COMPILER / Reporting Deprecation
          -	 *     When enabled, the compiler will signal use of deprecated API either as an 
          -	 *     error or a warning.
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.problem.deprecation"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "warning"
          -	 * 
          -	 *  COMPILER / Reporting Deprecation Inside Deprecated Code
          -	 *     When enabled, the compiler will signal use of deprecated API inside deprecated code.
          -	 *     The severity of the problem is controlled with option "net.sourceforge.phpdt.core.compiler.problem.deprecation".
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.problem.deprecationInDeprecatedCode"
          -	 *      - possible values:   { "enabled", "disabled" }
          -	 *      - default:           "disabled"
          -	 * 
          -	 *  COMPILER / Reporting Hidden Catch Block
          -	 *     Locally to a try statement, some catch blocks may hide others . For example,
          -	 *       try {  throw new java.io.CharConversionException();
          -	 *       } catch (java.io.CharConversionException e) {
          -	 *       } catch (java.io.IOException e) {}. 
          -	 *     When enabling this option, the compiler will issue an error or a warning for hidden 
          -	 *     catch blocks corresponding to checked exceptions
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.problem.hiddenCatchBlock"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "warning"
          -	 * 
          -	 *  COMPILER / Reporting Unused Local
          -	 *     When enabled, the compiler will issue an error or a warning for unused local 
          -	 *     variables (that is, variables never read from)
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.problem.unusedLocal"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "ignore"
          -	 * 
          -	 *  COMPILER / Reporting Unused Parameter
          -	 *     When enabled, the compiler will issue an error or a warning for unused method 
          -	 *     parameters (that is, parameters never read from)
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.problem.unusedParameter"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "ignore"
          -	 * 
          -	 *  COMPILER / Reporting Unused Parameter if Implementing Abstract Method
          -	 *     When enabled, the compiler will signal unused parameters in abstract method implementations.
          -	 *     The severity of the problem is controlled with option "net.sourceforge.phpdt.core.compiler.problem.unusedParameter".
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.problem.unusedParameterWhenImplementingAbstract"
          -	 *      - possible values:   { "enabled", "disabled" }
          -	 *      - default:           "disabled"
          -	 * 
          -	 *  COMPILER / Reporting Unused Parameter if Overriding Concrete Method
          -	 *     When enabled, the compiler will signal unused parameters in methods overriding concrete ones.
          -	 *     The severity of the problem is controlled with option "net.sourceforge.phpdt.core.compiler.problem.unusedParameter".
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.problem.unusedParameterWhenOverridingConcrete"
          -	 *      - possible values:   { "enabled", "disabled" }
          -	 *      - default:           "disabled"
          -	 * 
          -	 *  COMPILER / Reporting Unused Import
          -	 *     When enabled, the compiler will issue an error or a warning for unused import 
          -	 *     reference 
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.problem.unusedImport"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "warning"
          -	 * 
          -	 *  COMPILER / Reporting Unused Private Members
          -	 *     When enabled, the compiler will issue an error or a warning whenever a private 
          -	 *     method or field is declared but never used within the same unit.
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.problem.unusedPrivateMember"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "ignore"
          -	 * 
          -	 *  COMPILER / Reporting Synthetic Access Emulation
          -	 *     When enabled, the compiler will issue an error or a warning whenever it emulates 
          -	 *     access to a non-accessible member of an enclosing type. Such access can have
          -	 *     performance implications.
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.problem.syntheticAccessEmulation"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "ignore"
          -	 * 
          -	 *  COMPILER / Reporting Non-Externalized String Literal
          -	 *     When enabled, the compiler will issue an error or a warning for non externalized 
          -	 *     String literal (that is, not tagged with //$NON-NLS-<n>$). 
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.problem.nonExternalizedStringLiteral"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "ignore"
          -	 *  
          -	 *  COMPILER / Reporting Usage of 'assert' Identifier
          -	 *     When enabled, the compiler will issue an error or a warning whenever 'assert' is 
          -	 *     used as an identifier (reserved keyword in 1.4)
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.problem.assertIdentifier"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "ignore"
          -	 *  
          -	 *  COMPILER / Reporting Non-Static Reference to a Static Member
          -	 *     When enabled, the compiler will issue an error or a warning whenever a static field
          -	 *     or method is accessed with an expression receiver. A reference to a static member should
          -	 *     be qualified with a type name.
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.problem.staticAccessReceiver"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "warning"
          -	 *  
          -	 *  COMPILER / Reporting Assignment with no Effect
          -	 *     When enabled, the compiler will issue an error or a warning whenever an assignment
          -	 *     has no effect (e.g 'x = x').
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.problem.noEffectAssignment"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "warning"
          -	 *  
          -	 *  COMPILER / Reporting Interface Method not Compatible with non-Inherited Methods
          -	 *     When enabled, the compiler will issue an error or a warning whenever an interface
          -	 *     defines a method incompatible with a non-inherited Object method. Until this conflict
          -	 *     is resolved, such an interface cannot be implemented, For example, 
          -	 *       interface I { 
          -	 *          int clone();
          -	 *       } 
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "warning"
          -	 *  
          -	 *  COMPILER / Reporting Usage of char[] Expressions in String Concatenations
          -	 *     When enabled, the compiler will issue an error or a warning whenever a char[] expression
          -	 *     is used in String concatenations (for example, "hello" + new char[]{'w','o','r','l','d'}).
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.problem.noImplicitStringConversion"
          -	 *      - possible values:   { "error", "warning", "ignore" }
          -	 *      - default:           "warning"
          -	 * 
          -	 *  COMPILER / Setting Source Compatibility Mode
          -	 *     Specify whether source is 1.3 or 1.4 compatible. From 1.4 on, 'assert' is a keyword
          -	 *     reserved for assertion support. Also note, than when toggling to 1.4 mode, the target VM
          -	 *    level should be set to "1.4" and the compliance mode should be "1.4".
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.source"
          -	 *      - possible values:   { "1.3", "1.4" }
          -	 *      - default:           "1.3"
          -	 *  
          -	 *  COMPILER / Setting Compliance Level
          -	 *     Select the compliance level for the compiler. In "1.3" mode, source and target settings
          -	 *     should not go beyond "1.3" level.
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.compliance"
          -	 *      - possible values:   { "1.3", "1.4" }
          -	 *      - default:           "1.3"
          -	 *  
          -	 *  COMPILER / Maximum number of problems reported per compilation unit
          -	 *     Specify the maximum number of problems reported on each compilation unit.
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.maxProblemPerUnit"
          -	 *      - possible values:	"<n>" where <n> is zero or a positive integer (if zero then all problems are reported).
          -	 *      - default:           "100"
           	 *  
          -	 *  COMPILER / Define the Automatic Task Tags
          -	 *     When the tag list is not empty, the compiler will issue a task marker whenever it encounters
          -	 *     one of the corresponding tag inside any comment in Java source code.
          -	 *     Generated task messages will include the tag, and range until the next line separator or comment ending.
          -	 *     Note that tasks messages are trimmed.
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.taskTags"
          -	 *      - possible values:   { "<tag>[,<tag>]*" } where <tag> is a String without any wild-card or leading/trailing spaces 
          -	 *      - default:           ""
          +	 *   RECOGNIZED OPTIONS:
          +	 *   COMPILER / Generating Local Variable Debug Attribute
          +	 *      When generated, this attribute will enable local variable names 
          +	 *      to be displayed in debugger, only in place where variables are 
          +	 *      definitely assigned (.class file is then bigger)
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.debug.localVariable"
          +	 *       - possible values:   { "generate", "do not generate" }
          +	 *       - default:           "generate"
           	 *  
          -	 *  COMPILER / Define the Automatic Task Priorities
          -	 *     In parallel with the Automatic Task Tags, this list defines the priorities (high, normal or low)
          -	 *     of the task markers issued by the compiler.
          -	 *     If the default is specified, the priority of each task marker is "NORMAL".
          -	 *      - option id:         "net.sourceforge.phpdt.core.compiler.taskPriorities"
          -	 *      - possible values:   { "<priority>[,<priority>]*" } where <priority> is one of "HIGH", "NORMAL" or "LOW"
          -	 *      - default:           ""
          -	 * 
          -	 *  BUILDER / Specifying Filters for Resource Copying Control
          -	 *     Allow to specify some filters to control the resource copy process.
          -	 *      - option id:         "net.sourceforge.phpdt.core.builder.resourceCopyExclusionFilter"
          -	 *      - possible values:   { "<name>[,<name>]* } where <name> is a file name pattern (* and ? wild-cards allowed)
          -	 *        or the name of a folder which ends with '/'
          -	 *      - default:           ""
          +	 *   COMPILER / Generating Line Number Debug Attribute 
          +	 *      When generated, this attribute will enable source code highlighting in debugger 
          +	 *      (.class file is then bigger).
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.debug.lineNumber"
          +	 *       - possible values:   { "generate", "do not generate" }
          +	 *       - default:           "generate"
          +	 *      
          +	 *   COMPILER / Generating Source Debug Attribute 
          +	 *      When generated, this attribute will enable the debugger to present the 
          +	 *      corresponding source code.
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.debug.sourceFile"
          +	 *       - possible values:   { "generate", "do not generate" }
          +	 *       - default:           "generate"
          +	 *      
          +	 *   COMPILER / Preserving Unused Local Variables
          +	 *      Unless requested to preserve unused local variables (that is, never read), the 
          +	 *      compiler will optimize them out, potentially altering debugging
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.codegen.unusedLocal"
          +	 *       - possible values:   { "preserve", "optimize out" }
          +	 *       - default:           "preserve"
          +	 *   
          +	 *   COMPILER / Defining Target Java Platform
          +	 *      For binary compatibility reason, .class files can be tagged to with certain VM versions and later.
          +	 *      Note that "1.4" target require to toggle compliance mode to "1.4" too.
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.codegen.targetPlatform"
          +	 *       - possible values:   { "1.1", "1.2", "1.3", "1.4" }
          +	 *       - default:           "1.1"
           	 *  
          -	 *  BUILDER / Abort if Invalid Classpath
          -	 *     Allow to toggle the builder to abort if the classpath is invalid
          -	 *      - option id:         "net.sourceforge.phpdt.core.builder.invalidClasspath"
          -	 *      - possible values:   { "abort", "ignore" }
          -	 *      - default:           "abort"
          +	 *   COMPILER / Reporting Unreachable Code
          +	 *      Unreachable code can optionally be reported as an error, warning or simply 
          +	 *      ignored. The bytecode generation will always optimized it out.
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.problem.unreachableCode"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "error"
           	 *  
          -	 *  BUILDER / Cleaning Output Folder(s)
          -	 *     Indicate whether the JavaBuilder is allowed to clean the output folders
          -	 *     when performing full build operations.
          -	 *      - option id:         "net.sourceforge.phpdt.core.builder.cleanOutputFolder"
          -	 *      - possible values:   { "clean", "ignore" }
          -	 *      - default:           "clean"
          +	 *   COMPILER / Reporting Invalid Import
          +	 *      An import statement that cannot be resolved might optionally be reported 
          +	 *      as an error, as a warning or ignored.
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.problem.invalidImport"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "error"
           	 *  
          -	 *  BUILDER / Reporting Duplicate Resources
          -	 *     Indicate the severity of the problem reported when more than one occurrence
          -	 *     of a resource is to be copied into the output location.
          -	 *      - option id:         "net.sourceforge.phpdt.core.builder.duplicateResourceTask"
          -	 *      - possible values:   { "error", "warning" }
          -	 *      - default:           "warning"
          +	 *   COMPILER / Reporting Attempt to Override Package-Default Method
          +	 *      A package default method is not visible in a different package, and thus 
          +	 *      cannot be overridden. When enabling this option, the compiler will signal 
          +	 *      such scenarii either as an error or a warning.
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.problem.overridingPackageDefaultMethod"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "warning"
           	 *  
          -	 *  JAVACORE / Computing Project Build Order
          -	 *     Indicate whether JavaCore should enforce the project build order to be based on
          -	 *     the classpath prerequisite chain. When requesting to compute, this takes over
          -	 *     the platform default order (based on project references).
          -	 *      - option id:         "net.sourceforge.phpdt.core.computeJavaBuildOrder"
          -	 *      - possible values:   { "compute", "ignore" }
          -	 *      - default:           "ignore"	 
          +	 *   COMPILER / Reporting Method With Constructor Name
          +	 *      Naming a method with a constructor name is generally considered poor 
          +	 *      style programming. When enabling this option, the compiler will signal such 
          +	 *      scenarii either as an error or a warning.
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.problem.methodWithConstructorName"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "warning"
           	 *  
          -	 *  JAVACORE / Specify Default Source Encoding Format
          -	 *     Get the encoding format for compiled sources. This setting is read-only, it is equivalent
          -	 *     to 'ResourcesPlugin.getEncoding()'.
          -	 *      - option id:         "net.sourceforge.phpdt.core.encoding"
          -	 *      - possible values:   { any of the supported encoding name}.
          -	 *      - default:           <platform default>
          +	 *   COMPILER / Reporting Deprecation
          +	 *      When enabled, the compiler will signal use of deprecated API either as an 
          +	 *      error or a warning.
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.problem.deprecation"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "warning"
           	 *  
          -	 *  JAVACORE / Reporting Incomplete Classpath
          -	 *     Indicate the severity of the problem reported when an entry on the classpath does not exist, 
          -	 *     is not legite or is not visible (for example, a referenced project is closed).
          -	 *      - option id:         "net.sourceforge.phpdt.core.incompleteClasspath"
          -	 *      - possible values:   { "error", "warning"}
          -	 *      - default:           "error"
          +	 *   COMPILER / Reporting Deprecation Inside Deprecated Code
          +	 *      When enabled, the compiler will signal use of deprecated API inside deprecated code.
          +	 *      The severity of the problem is controlled with option "net.sourceforge.phpdt.core.compiler.problem.deprecation".
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.problem.deprecationInDeprecatedCode"
          +	 *       - possible values:   { "enabled", "disabled" }
          +	 *       - default:           "disabled"
           	 *  
          -	 *  JAVACORE / Reporting Classpath Cycle
          -	 *     Indicate the severity of the problem reported when a project is involved in a cycle.
          -	 *      - option id:         "net.sourceforge.phpdt.core.circularClasspath"
          -	 *      - possible values:   { "error", "warning" }
          -	 *      - default:           "error"
          +	 *   COMPILER / Reporting Hidden Catch Block
          +	 *      Locally to a try statement, some catch blocks may hide others . For example,
          +	 *        try {  throw new java.io.CharConversionException();
          +	 *        } catch (java.io.CharConversionException e) {
          +	 *        } catch (java.io.IOException e) {}. 
          +	 *      When enabling this option, the compiler will issue an error or a warning for hidden 
          +	 *      catch blocks corresponding to checked exceptions
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.problem.hiddenCatchBlock"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "warning"
           	 *  
          -	 *  JAVACORE / Enabling Usage of Classpath Exclusion Patterns
          -	 *     When disabled, no entry on a project classpath can be associated with
          -	 *     an exclusion pattern.
          -	 *      - option id:         "net.sourceforge.phpdt.core.classpath.exclusionPatterns"
          -	 *      - possible values:   { "enabled", "disabled" }
          -	 *      - default:           "enabled"
          +	 *   COMPILER / Reporting Unused Local
          +	 *      When enabled, the compiler will issue an error or a warning for unused local 
          +	 *      variables (that is, variables never read from)
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.problem.unusedLocal"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "ignore"
           	 *  
          -	 *  JAVACORE / Enabling Usage of Classpath Multiple Output Locations
          -	 *     When disabled, no entry on a project classpath can be associated with
          -	 *     a specific output location, preventing thus usage of multiple output locations.
          -	 *      - option id:         "net.sourceforge.phpdt.core.classpath.multipleOutputLocations"
          -	 *      - possible values:   { "enabled", "disabled" }
          -	 *      - default:           "enabled"
          +	 *   COMPILER / Reporting Unused Parameter
          +	 *      When enabled, the compiler will issue an error or a warning for unused method 
          +	 *      parameters (that is, parameters never read from)
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.problem.unusedParameter"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "ignore"
           	 *  
          -	 * 	FORMATTER / Inserting New Line Before Opening Brace
          -	 *     When Insert, a new line is inserted before an opening brace, otherwise nothing
          -	 *     is inserted
          -	 *      - option id:         "net.sourceforge.phpdt.core.formatter.newline.openingBrace"
          -	 *      - possible values:   { "insert", "do not insert" }
          -	 *      - default:           "do not insert"
          +	 *   COMPILER / Reporting Unused Parameter if Implementing Abstract Method
          +	 *      When enabled, the compiler will signal unused parameters in abstract method implementations.
          +	 *      The severity of the problem is controlled with option "net.sourceforge.phpdt.core.compiler.problem.unusedParameter".
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.problem.unusedParameterWhenImplementingAbstract"
          +	 *       - possible values:   { "enabled", "disabled" }
          +	 *       - default:           "disabled"
           	 *  
          -	 * 	FORMATTER / Inserting New Line Inside Control Statement
          -	 *     When Insert, a new line is inserted between } and following else, catch, finally
          -	 *      - option id:         "net.sourceforge.phpdt.core.formatter.newline.controlStatement"
          -	 *      - possible values:   { "insert", "do not insert" }
          -	 *      - default:           "do not insert"
          +	 *   COMPILER / Reporting Unused Parameter if Overriding Concrete Method
          +	 *      When enabled, the compiler will signal unused parameters in methods overriding concrete ones.
          +	 *      The severity of the problem is controlled with option "net.sourceforge.phpdt.core.compiler.problem.unusedParameter".
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.problem.unusedParameterWhenOverridingConcrete"
          +	 *       - possible values:   { "enabled", "disabled" }
          +	 *       - default:           "disabled"
           	 *  
          -	 * 	FORMATTER / Clearing Blank Lines
          -	 *     When Clear all, all blank lines are removed. When Preserve one, only one is kept
          -	 *     and all others removed.
          -	 *      - option id:         "net.sourceforge.phpdt.core.formatter.newline.clearAll"
          -	 *      - possible values:   { "clear all", "preserve one" }
          -	 *      - default:           "preserve one"
          +	 *   COMPILER / Reporting Unused Import
          +	 *      When enabled, the compiler will issue an error or a warning for unused import 
          +	 *      reference 
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.problem.unusedImport"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "warning"
           	 *  
          -	 * 	FORMATTER / Inserting New Line Between Else/If 
          -	 *     When Insert, a blank line is inserted between an else and an if when they are 
          -	 *     contiguous. When choosing to not insert, else-if will be kept on the same
          -	 *     line when possible.
          -	 *      - option id:         "net.sourceforge.phpdt.core.formatter.newline.elseIf"
          -	 *      - possible values:   { "insert", "do not insert" }
          -	 *      - default:           "do not insert"
          +	 *   COMPILER / Reporting Unused Private Members
          +	 *      When enabled, the compiler will issue an error or a warning whenever a private 
          +	 *      method or field is declared but never used within the same unit.
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.problem.unusedPrivateMember"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "ignore"
           	 *  
          -	 * 	FORMATTER / Inserting New Line In Empty Block
          -	 *     When insert, a line break is inserted between contiguous { and }, if } is not followed
          -	 *     by a keyword.
          -	 *      - option id:         "net.sourceforge.phpdt.core.formatter.newline.emptyBlock"
          -	 *      - possible values:   { "insert", "do not insert" }
          -	 *      - default:           "insert"
          +	 *   COMPILER / Reporting Synthetic Access Emulation
          +	 *      When enabled, the compiler will issue an error or a warning whenever it emulates 
          +	 *      access to a non-accessible member of an enclosing type. Such access can have
          +	 *      performance implications.
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.problem.syntheticAccessEmulation"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "ignore"
           	 *  
          -	 * 	FORMATTER / Splitting Lines Exceeding Length
          -	 *     Enable splitting of long lines (exceeding the configurable length). Length of 0 will
          -	 *     disable line splitting
          -	 *      - option id:         "net.sourceforge.phpdt.core.formatter.lineSplit"
          -	 *      - possible values:	"<n>", where n is zero or a positive integer
          -	 *      - default:           "80"
          +	 *   COMPILER / Reporting Non-Externalized String Literal
          +	 *      When enabled, the compiler will issue an error or a warning for non externalized 
          +	 *      String literal (that is, not tagged with //$NON-NLS-<n>$). 
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.problem.nonExternalizedStringLiteral"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "ignore"
          +	 *   
          +	 *   COMPILER / Reporting Usage of 'assert' Identifier
          +	 *      When enabled, the compiler will issue an error or a warning whenever 'assert' is 
          +	 *      used as an identifier (reserved keyword in 1.4)
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.problem.assertIdentifier"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "ignore"
          +	 *   
          +	 *   COMPILER / Reporting Non-Static Reference to a Static Member
          +	 *      When enabled, the compiler will issue an error or a warning whenever a static field
          +	 *      or method is accessed with an expression receiver. A reference to a static member should
          +	 *      be qualified with a type name.
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.problem.staticAccessReceiver"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "warning"
          +	 *   
          +	 *   COMPILER / Reporting Assignment with no Effect
          +	 *      When enabled, the compiler will issue an error or a warning whenever an assignment
          +	 *      has no effect (e.g 'x = x').
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.problem.noEffectAssignment"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "warning"
          +	 *   
          +	 *   COMPILER / Reporting Interface Method not Compatible with non-Inherited Methods
          +	 *      When enabled, the compiler will issue an error or a warning whenever an interface
          +	 *      defines a method incompatible with a non-inherited Object method. Until this conflict
          +	 *      is resolved, such an interface cannot be implemented, For example, 
          +	 *        interface I { 
          +	 *           int clone();
          +	 *        } 
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "warning"
          +	 *   
          +	 *   COMPILER / Reporting Usage of char[] Expressions in String Concatenations
          +	 *      When enabled, the compiler will issue an error or a warning whenever a char[] expression
          +	 *      is used in String concatenations (for example, "hello" + new char[]{'w','o','r','l','d'}).
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.problem.noImplicitStringConversion"
          +	 *       - possible values:   { "error", "warning", "ignore" }
          +	 *       - default:           "warning"
           	 *  
          -	 * 	FORMATTER / Compacting Assignment
          -	 *     Assignments can be formatted asymmetrically, for example 'int x= 2;', when Normal, a space
          -	 *     is inserted before the assignment operator
          -	 *      - option id:         "net.sourceforge.phpdt.core.formatter.style.assignment"
          -	 *      - possible values:   { "compact", "normal" }
          -	 *      - default:           "normal"
          +	 *   COMPILER / Setting Source Compatibility Mode
          +	 *      Specify whether source is 1.3 or 1.4 compatible. From 1.4 on, 'assert' is a keyword
          +	 *      reserved for assertion support. Also note, than when toggling to 1.4 mode, the target VM
          +	 *     level should be set to "1.4" and the compliance mode should be "1.4".
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.source"
          +	 *       - possible values:   { "1.3", "1.4" }
          +	 *       - default:           "1.3"
          +	 *   
          +	 *   COMPILER / Setting Compliance Level
          +	 *      Select the compliance level for the compiler. In "1.3" mode, source and target settings
          +	 *      should not go beyond "1.3" level.
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.compliance"
          +	 *       - possible values:   { "1.3", "1.4" }
          +	 *       - default:           "1.3"
          +	 *   
          +	 *   COMPILER / Maximum number of problems reported per compilation unit
          +	 *      Specify the maximum number of problems reported on each compilation unit.
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.maxProblemPerUnit"
          +	 *       - possible values:	"<n>" where <n> is zero or a positive integer (if zero then all problems are reported).
          +	 *       - default:           "100"
          +	 *   
          +	 *   COMPILER / Define the Automatic Task Tags
          +	 *      When the tag list is not empty, the compiler will issue a task marker whenever it encounters
          +	 *      one of the corresponding tag inside any comment in Java source code.
          +	 *      Generated task messages will include the tag, and range until the next line separator or comment ending.
          +	 *      Note that tasks messages are trimmed.
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.taskTags"
          +	 *       - possible values:   { "<tag>[,<tag>]*" } where <tag> is a String without any wild-card or leading/trailing spaces 
          +	 *       - default:           ""
          +	 *   
          +	 *   COMPILER / Define the Automatic Task Priorities
          +	 *      In parallel with the Automatic Task Tags, this list defines the priorities (high, normal or low)
          +	 *      of the task markers issued by the compiler.
          +	 *      If the default is specified, the priority of each task marker is "NORMAL".
          +	 *       - option id:         "net.sourceforge.phpdt.core.compiler.taskPriorities"
          +	 *       - possible values:   { "<priority>[,<priority>]*" } where <priority> is one of "HIGH", "NORMAL" or "LOW"
          +	 *       - default:           ""
           	 *  
          -	 * 	FORMATTER / Defining Indentation Character
          -	 *     Either choose to indent with tab characters or spaces
          -	 *      - option id:         "net.sourceforge.phpdt.core.formatter.tabulation.char"
          -	 *      - possible values:   { "tab", "space" }
          -	 *      - default:           "tab"
          -	 *  
          -	 * 	FORMATTER / Defining Space Indentation Length
          -	 *     When using spaces, set the amount of space characters to use for each 
          -	 *     indentation mark.
          -	 *      - option id:         "net.sourceforge.phpdt.core.formatter.tabulation.size"
          -	 *      - possible values:	"<n>", where n is a positive integer
          -	 *      - default:           "4"
          -	 *  
          -	 * 	FORMATTER / Inserting space in cast expression
          -	 *     When Insert, a space is added between the type and the expression in a cast expression.
          -	 *      - option id:         "net.sourceforge.phpdt.core.formatter.space.castexpression"
          -	 *      - possible values:   { "insert", "do not insert" }
          -	 *      - default:           "insert"
          -	 *  
          -	 * 	CODEASSIST / Activate Visibility Sensitive Completion
          -	 *     When active, completion doesn't show that you can not see
          -	 *     (for example, you can not see private methods of a super class).
          -	 *      - option id:         "net.sourceforge.phpdt.core.codeComplete.visibilityCheck"
          -	 *      - possible values:   { "enabled", "disabled" }
          -	 *      - default:           "disabled"
          -	 *  
          -	 * 	CODEASSIST / Automatic Qualification of Implicit Members
          -	 *     When active, completion automatically qualifies completion on implicit
          -	 *     field references and message expressions.
          -	 *      - option id:         "net.sourceforge.phpdt.core.codeComplete.forceImplicitQualification"
          -	 *      - possible values:   { "enabled", "disabled" }
          -	 *      - default:           "disabled"
          -	 *  
          -	 *   CODEASSIST / Define the Prefixes for Field Name
          -	 *     When the prefixes is non empty, completion for field name will begin with
          -	 *     one of the proposed prefixes.
          -	 *      - option id:         "net.sourceforge.phpdt.core.codeComplete.fieldPrefixes"
          -	 *      - possible values:   { "<prefix>[,<prefix>]*" } where <prefix> is a String without any wild-card 
          -	 *      - default:           ""
          -	 *  
          -	 *   CODEASSIST / Define the Prefixes for Static Field Name
          -	 *     When the prefixes is non empty, completion for static field name will begin with
          -	 *     one of the proposed prefixes.
          -	 *      - option id:         "net.sourceforge.phpdt.core.codeComplete.staticFieldPrefixes"
          -	 *      - possible values:   { "<prefix>[,<prefix>]*" } where <prefix> is a String without any wild-card 
          -	 *      - default:           ""
          -	 *  
          -	 *   CODEASSIST / Define the Prefixes for Local Variable Name
          -	 *     When the prefixes is non empty, completion for local variable name will begin with
          -	 *     one of the proposed prefixes.
          -	 *      - option id:         "net.sourceforge.phpdt.core.codeComplete.localPrefixes"
          -	 *      - possible values:   { "<prefix>[,<prefix>]*" } where <prefix> is a String without any wild-card 
          -	 *      - default:           ""
          -	 *  
          -	 *   CODEASSIST / Define the Prefixes for Argument Name
          -	 *     When the prefixes is non empty, completion for argument name will begin with
          -	 *     one of the proposed prefixes.
          -	 *      - option id:         "net.sourceforge.phpdt.core.codeComplete.argumentPrefixes"
          -	 *      - possible values:   { "<prefix>[,<prefix>]*" } where <prefix> is a String without any wild-card 
          -	 *      - default:           ""
          -	 *  
          -	 *   CODEASSIST / Define the Suffixes for Field Name
          -	 *     When the suffixes is non empty, completion for field name will end with
          -	 *     one of the proposed suffixes.
          -	 *      - option id:         "net.sourceforge.phpdt.core.codeComplete.fieldSuffixes"
          -	 *      - possible values:   { "<suffix>[,<suffix>]*" } where <suffix> is a String without any wild-card 
          -	 *      - default:           ""
          -	 *  
          -	 *   CODEASSIST / Define the Suffixes for Static Field Name
          -	 *     When the suffixes is non empty, completion for static field name will end with
          -	 *     one of the proposed suffixes.
          -	 *      - option id:         "net.sourceforge.phpdt.core.codeComplete.staticFieldSuffixes"
          -	 *      - possible values:   { "<suffix>[,<suffix>]*" } where <suffix> is a String without any wild-card 
          -	 *      - default:           ""
          -	 *  
          -	 *   CODEASSIST / Define the Suffixes for Local Variable Name
          -	 *     When the suffixes is non empty, completion for local variable name will end with
          -	 *     one of the proposed suffixes.
          -	 *      - option id:         "net.sourceforge.phpdt.core.codeComplete.localSuffixes"
          -	 *      - possible values:   { "<suffix>[,<suffix>]*" } where <suffix> is a String without any wild-card 
          -	 *      - default:           ""
          -	 *  
          -	 *   CODEASSIST / Define the Suffixes for Argument Name
          -	 *     When the suffixes is non empty, completion for argument name will end with
          -	 *     one of the proposed suffixes.
          -	 *      - option id:         "net.sourceforge.phpdt.core.codeComplete.argumentSuffixes"
          -	 *      - possible values:   { "<suffix>[,<suffix>]*" } where <prefix> is a String without any wild-card 
          -	 *      - default:           ""
          -	 *  </pre>
          -	 *  
          -	 *  @return a mutable table containing the default settings of all known options
          -	 *    (key type: 
          +	 *   BUILDER / Specifying Filters for Resource Copying Control
          +	 *      Allow to specify some filters to control the resource copy process.
          +	 *       - option id:         "net.sourceforge.phpdt.core.builder.resourceCopyExclusionFilter"
          +	 *       - possible values:   { "<name>[,<name>]* } where <name> is a file name pattern (* and ? wild-cards allowed)
          +	 *         or the name of a folder which ends with '/'
          +	 *       - default:           ""
          +	 *   
          +	 *   BUILDER / Abort if Invalid Classpath
          +	 *      Allow to toggle the builder to abort if the classpath is invalid
          +	 *       - option id:         "net.sourceforge.phpdt.core.builder.invalidClasspath"
          +	 *       - possible values:   { "abort", "ignore" }
          +	 *       - default:           "abort"
          +	 *   
          +	 *   BUILDER / Cleaning Output Folder(s)
          +	 *      Indicate whether the JavaBuilder is allowed to clean the output folders
          +	 *      when performing full build operations.
          +	 *       - option id:         "net.sourceforge.phpdt.core.builder.cleanOutputFolder"
          +	 *       - possible values:   { "clean", "ignore" }
          +	 *       - default:           "clean"
          +	 *   
          +	 *   BUILDER / Reporting Duplicate Resources
          +	 *      Indicate the severity of the problem reported when more than one occurrence
          +	 *      of a resource is to be copied into the output location.
          +	 *       - option id:         "net.sourceforge.phpdt.core.builder.duplicateResourceTask"
          +	 *       - possible values:   { "error", "warning" }
          +	 *       - default:           "warning"
          +	 *   
          +	 *   JAVACORE / Computing Project Build Order
          +	 *      Indicate whether JavaCore should enforce the project build order to be based on
          +	 *      the classpath prerequisite chain. When requesting to compute, this takes over
          +	 *      the platform default order (based on project references).
          +	 *       - option id:         "net.sourceforge.phpdt.core.computeJavaBuildOrder"
          +	 *       - possible values:   { "compute", "ignore" }
          +	 *       - default:           "ignore"	 
          +	 *   
          +	 *   JAVACORE / Specify Default Source Encoding Format
          +	 *      Get the encoding format for compiled sources. This setting is read-only, it is equivalent
          +	 *      to 'ResourcesPlugin.getEncoding()'.
          +	 *       - option id:         "net.sourceforge.phpdt.core.encoding"
          +	 *       - possible values:   { any of the supported encoding name}.
          +	 *       - default:           <platform default>
          +	 *   
          +	 *   JAVACORE / Reporting Incomplete Classpath
          +	 *      Indicate the severity of the problem reported when an entry on the classpath does not exist, 
          +	 *      is not legite or is not visible (for example, a referenced project is closed).
          +	 *       - option id:         "net.sourceforge.phpdt.core.incompleteClasspath"
          +	 *       - possible values:   { "error", "warning"}
          +	 *       - default:           "error"
          +	 *   
          +	 *   JAVACORE / Reporting Classpath Cycle
          +	 *      Indicate the severity of the problem reported when a project is involved in a cycle.
          +	 *       - option id:         "net.sourceforge.phpdt.core.circularClasspath"
          +	 *       - possible values:   { "error", "warning" }
          +	 *       - default:           "error"
          +	 *   
          +	 *   JAVACORE / Enabling Usage of Classpath Exclusion Patterns
          +	 *      When disabled, no entry on a project classpath can be associated with
          +	 *      an exclusion pattern.
          +	 *       - option id:         "net.sourceforge.phpdt.core.classpath.exclusionPatterns"
          +	 *       - possible values:   { "enabled", "disabled" }
          +	 *       - default:           "enabled"
          +	 *   
          +	 *   JAVACORE / Enabling Usage of Classpath Multiple Output Locations
          +	 *      When disabled, no entry on a project classpath can be associated with
          +	 *      a specific output location, preventing thus usage of multiple output locations.
          +	 *       - option id:         "net.sourceforge.phpdt.core.classpath.multipleOutputLocations"
          +	 *       - possible values:   { "enabled", "disabled" }
          +	 *       - default:           "enabled"
          +	 *   
          +	 *  	FORMATTER / Inserting New Line Before Opening Brace
          +	 *      When Insert, a new line is inserted before an opening brace, otherwise nothing
          +	 *      is inserted
          +	 *       - option id:         "net.sourceforge.phpdt.core.formatter.newline.openingBrace"
          +	 *       - possible values:   { "insert", "do not insert" }
          +	 *       - default:           "do not insert"
          +	 *   
          +	 *  	FORMATTER / Inserting New Line Inside Control Statement
          +	 *      When Insert, a new line is inserted between } and following else, catch, finally
          +	 *       - option id:         "net.sourceforge.phpdt.core.formatter.newline.controlStatement"
          +	 *       - possible values:   { "insert", "do not insert" }
          +	 *       - default:           "do not insert"
          +	 *   
          +	 *  	FORMATTER / Clearing Blank Lines
          +	 *      When Clear all, all blank lines are removed. When Preserve one, only one is kept
          +	 *      and all others removed.
          +	 *       - option id:         "net.sourceforge.phpdt.core.formatter.newline.clearAll"
          +	 *       - possible values:   { "clear all", "preserve one" }
          +	 *       - default:           "preserve one"
          +	 *   
          +	 *  	FORMATTER / Inserting New Line Between Else/If 
          +	 *      When Insert, a blank line is inserted between an else and an if when they are 
          +	 *      contiguous. When choosing to not insert, else-if will be kept on the same
          +	 *      line when possible.
          +	 *       - option id:         "net.sourceforge.phpdt.core.formatter.newline.elseIf"
          +	 *       - possible values:   { "insert", "do not insert" }
          +	 *       - default:           "do not insert"
          +	 *   
          +	 *  	FORMATTER / Inserting New Line In Empty Block
          +	 *      When insert, a line break is inserted between contiguous { and }, if } is not followed
          +	 *      by a keyword.
          +	 *       - option id:         "net.sourceforge.phpdt.core.formatter.newline.emptyBlock"
          +	 *       - possible values:   { "insert", "do not insert" }
          +	 *       - default:           "insert"
          +	 *   
          +	 *  	FORMATTER / Splitting Lines Exceeding Length
          +	 *      Enable splitting of long lines (exceeding the configurable length). Length of 0 will
          +	 *      disable line splitting
          +	 *       - option id:         "net.sourceforge.phpdt.core.formatter.lineSplit"
          +	 *       - possible values:	"<n>", where n is zero or a positive integer
          +	 *       - default:           "80"
          +	 *   
          +	 *  	FORMATTER / Compacting Assignment
          +	 *      Assignments can be formatted asymmetrically, for example 'int x= 2;', when Normal, a space
          +	 *      is inserted before the assignment operator
          +	 *       - option id:         "net.sourceforge.phpdt.core.formatter.style.assignment"
          +	 *       - possible values:   { "compact", "normal" }
          +	 *       - default:           "normal"
          +	 *   
          +	 *  	FORMATTER / Defining Indentation Character
          +	 *      Either choose to indent with tab characters or spaces
          +	 *       - option id:         "net.sourceforge.phpdt.core.formatter.tabulation.char"
          +	 *       - possible values:   { "tab", "space" }
          +	 *       - default:           "tab"
          +	 *   
          +	 *  	FORMATTER / Defining Space Indentation Length
          +	 *      When using spaces, set the amount of space characters to use for each 
          +	 *      indentation mark.
          +	 *       - option id:         "net.sourceforge.phpdt.core.formatter.tabulation.size"
          +	 *       - possible values:	"<n>", where n is a positive integer
          +	 *       - default:           "4"
          +	 *   
          +	 *  	FORMATTER / Inserting space in cast expression
          +	 *      When Insert, a space is added between the type and the expression in a cast expression.
          +	 *       - option id:         "net.sourceforge.phpdt.core.formatter.space.castexpression"
          +	 *       - possible values:   { "insert", "do not insert" }
          +	 *       - default:           "insert"
          +	 *   
          +	 *  	CODEASSIST / Activate Visibility Sensitive Completion
          +	 *      When active, completion doesn't show that you can not see
          +	 *      (for example, you can not see private methods of a super class).
          +	 *       - option id:         "net.sourceforge.phpdt.core.codeComplete.visibilityCheck"
          +	 *       - possible values:   { "enabled", "disabled" }
          +	 *       - default:           "disabled"
          +	 *   
          +	 *  	CODEASSIST / Automatic Qualification of Implicit Members
          +	 *      When active, completion automatically qualifies completion on implicit
          +	 *      field references and message expressions.
          +	 *       - option id:         "net.sourceforge.phpdt.core.codeComplete.forceImplicitQualification"
          +	 *       - possible values:   { "enabled", "disabled" }
          +	 *       - default:           "disabled"
          +	 *   
          +	 *    CODEASSIST / Define the Prefixes for Field Name
          +	 *      When the prefixes is non empty, completion for field name will begin with
          +	 *      one of the proposed prefixes.
          +	 *       - option id:         "net.sourceforge.phpdt.core.codeComplete.fieldPrefixes"
          +	 *       - possible values:   { "<prefix>[,<prefix>]*" } where <prefix> is a String without any wild-card 
          +	 *       - default:           ""
          +	 *   
          +	 *    CODEASSIST / Define the Prefixes for Static Field Name
          +	 *      When the prefixes is non empty, completion for static field name will begin with
          +	 *      one of the proposed prefixes.
          +	 *       - option id:         "net.sourceforge.phpdt.core.codeComplete.staticFieldPrefixes"
          +	 *       - possible values:   { "<prefix>[,<prefix>]*" } where <prefix> is a String without any wild-card 
          +	 *       - default:           ""
          +	 *   
          +	 *    CODEASSIST / Define the Prefixes for Local Variable Name
          +	 *      When the prefixes is non empty, completion for local variable name will begin with
          +	 *      one of the proposed prefixes.
          +	 *       - option id:         "net.sourceforge.phpdt.core.codeComplete.localPrefixes"
          +	 *       - possible values:   { "<prefix>[,<prefix>]*" } where <prefix> is a String without any wild-card 
          +	 *       - default:           ""
          +	 *   
          +	 *    CODEASSIST / Define the Prefixes for Argument Name
          +	 *      When the prefixes is non empty, completion for argument name will begin with
          +	 *      one of the proposed prefixes.
          +	 *       - option id:         "net.sourceforge.phpdt.core.codeComplete.argumentPrefixes"
          +	 *       - possible values:   { "<prefix>[,<prefix>]*" } where <prefix> is a String without any wild-card 
          +	 *       - default:           ""
          +	 *   
          +	 *    CODEASSIST / Define the Suffixes for Field Name
          +	 *      When the suffixes is non empty, completion for field name will end with
          +	 *      one of the proposed suffixes.
          +	 *       - option id:         "net.sourceforge.phpdt.core.codeComplete.fieldSuffixes"
          +	 *       - possible values:   { "<suffix>[,<suffix>]*" } where <suffix> is a String without any wild-card 
          +	 *       - default:           ""
          +	 *   
          +	 *    CODEASSIST / Define the Suffixes for Static Field Name
          +	 *      When the suffixes is non empty, completion for static field name will end with
          +	 *      one of the proposed suffixes.
          +	 *       - option id:         "net.sourceforge.phpdt.core.codeComplete.staticFieldSuffixes"
          +	 *       - possible values:   { "<suffix>[,<suffix>]*" } where <suffix> is a String without any wild-card 
          +	 *       - default:           ""
          +	 *   
          +	 *    CODEASSIST / Define the Suffixes for Local Variable Name
          +	 *      When the suffixes is non empty, completion for local variable name will end with
          +	 *      one of the proposed suffixes.
          +	 *       - option id:         "net.sourceforge.phpdt.core.codeComplete.localSuffixes"
          +	 *       - possible values:   { "<suffix>[,<suffix>]*" } where <suffix> is a String without any wild-card 
          +	 *       - default:           ""
          +	 *   
          +	 *    CODEASSIST / Define the Suffixes for Argument Name
          +	 *      When the suffixes is non empty, completion for argument name will end with
          +	 *      one of the proposed suffixes.
          +	 *       - option id:         "net.sourceforge.phpdt.core.codeComplete.argumentSuffixes"
          +	 *       - possible values:   { "<suffix>[,<suffix>]*" } where <prefix> is a String without any wild-card 
          +	 *       - default:           ""
          +	 *   </pre>
          +	 *   
          +	 *   @return a mutable table containing the default settings of all known options
          +	 *     (key type: 
           	 * 
           	 * String
           	 * 
          -	 * ; value type: 
          +	 *  ; value type: 
           	 * 
           	 * String
           	 * 
          -	 * )
          -	 *  @see #setOptions
          +	 *  )
          +	 *   @see #setOptions
           	 * 
           	 */
           	public static Hashtable getDefaultOptions() {
          @@ -2795,23 +2804,25 @@ public class JavaCore {
           							.isExported());
           
           				case IResource.FILE:
          -					//					if (ProjectPrefUtil.isArchiveFileName(resolvedResource.getName())) {
          -					//						// internal binary archive
          -					//						return JavaCore.newLibraryEntry(
          -					//								resolvedPath,
          -					//								getResolvedVariablePath(entry.getSourceAttachmentPath()),
          -					//								getResolvedVariablePath(entry.getSourceAttachmentRootPath()),
          -					//								entry.isExported());
          -					//					}
          +					// if
          +					// (ProjectPrefUtil.isArchiveFileName(resolvedResource.getName()))
          +					// {
          +					// // internal binary archive
          +					// return JavaCore.newLibraryEntry(
          +					// resolvedPath,
          +					// getResolvedVariablePath(entry.getSourceAttachmentPath()),
          +					// getResolvedVariablePath(entry.getSourceAttachmentRootPath()),
          +					// entry.isExported());
          +					// }
           					break;
           
           				case IResource.FOLDER:
           					// internal binary folder
          -					//					return JavaCore.newLibraryEntry(
          -					//							resolvedPath,
          -					//							getResolvedVariablePath(entry.getSourceAttachmentPath()),
          -					//							getResolvedVariablePath(entry.getSourceAttachmentRootPath()),
          -					//							entry.isExported());
          +					// return JavaCore.newLibraryEntry(
          +					// resolvedPath,
          +					// getResolvedVariablePath(entry.getSourceAttachmentPath()),
          +					// getResolvedVariablePath(entry.getSourceAttachmentRootPath()),
          +					// entry.isExported());
           					break;
           				}
           			}
          @@ -2821,22 +2832,22 @@ public class JavaCore {
           			File externalFile = (File) target;
           			if (externalFile.isFile()) {
           				String fileName = externalFile.getName().toLowerCase();
          -				//			if (fileName.endsWith(".jar" //$NON-NLS-1$
          -				//				) || fileName.endsWith(".zip" //$NON-NLS-1$
          -				//				)) { // external binary archive
          -				//				return JavaCore.newLibraryEntry(
          -				//						resolvedPath,
          -				//						getResolvedVariablePath(entry.getSourceAttachmentPath()),
          -				//						getResolvedVariablePath(entry.getSourceAttachmentRootPath()),
          -				//						entry.isExported());
          -				//			}
          +				// if (fileName.endsWith(".jar" //$NON-NLS-1$
          +				// ) || fileName.endsWith(".zip" //$NON-NLS-1$
          +				// )) { // external binary archive
          +				// return JavaCore.newLibraryEntry(
          +				// resolvedPath,
          +				// getResolvedVariablePath(entry.getSourceAttachmentPath()),
          +				// getResolvedVariablePath(entry.getSourceAttachmentRootPath()),
          +				// entry.isExported());
          +				// }
           			} else { // external binary folder
           				if (resolvedPath.isAbsolute()) {
          -					//				return JavaCore.newLibraryEntry(
          -					//						resolvedPath,
          -					//						getResolvedVariablePath(entry.getSourceAttachmentPath()),
          -					//						getResolvedVariablePath(entry.getSourceAttachmentRootPath()),
          -					//						entry.isExported());
          +					// return JavaCore.newLibraryEntry(
          +					// resolvedPath,
          +					// getResolvedVariablePath(entry.getSourceAttachmentPath()),
          +					// getResolvedVariablePath(entry.getSourceAttachmentRootPath()),
          +					// entry.isExported());
           				}
           			}
           		}
          @@ -2923,7 +2934,7 @@ public class JavaCore {
           		optionNames.add(COMPILER_CODEGEN_UNUSED_LOCAL);
           
           		preferences.setDefault(COMPILER_CODEGEN_TARGET_PLATFORM, VERSION_1_1);
          -		optionNames.add(COMPILER_CODEGEN_TARGET_PLATFORM); 
          +		optionNames.add(COMPILER_CODEGEN_TARGET_PLATFORM);
           
           		preferences.setDefault(COMPILER_PB_PHP_VAR_DEPRECATED, IGNORE);
           		optionNames.add(COMPILER_PB_PHP_VAR_DEPRECATED);
          @@ -2935,9 +2946,10 @@ public class JavaCore {
           		optionNames.add(COMPILER_PB_PHP_FILE_NOT_EXIST);
           		preferences.setDefault(COMPILER_PB_UNREACHABLE_CODE, WARNING);
           		optionNames.add(COMPILER_PB_UNREACHABLE_CODE);
          -		preferences.setDefault(COMPILER_PB_UNINITIALIZED_LOCAL_VARIABLE, WARNING);
          +		preferences.setDefault(COMPILER_PB_UNINITIALIZED_LOCAL_VARIABLE,
          +				WARNING);
           		optionNames.add(COMPILER_PB_UNINITIALIZED_LOCAL_VARIABLE);
          -		
          +
           		preferences.setDefault(COMPILER_PB_INVALID_IMPORT, ERROR);
           		optionNames.add(COMPILER_PB_INVALID_IMPORT);
           
          @@ -3141,7 +3153,7 @@ public class JavaCore {
           		if (element instanceof IMember) {
           			IMember member = (IMember) element;
           			if (member.isBinary()) {
          -				element = null; //member.getClassFile();
          +				element = null; // member.getClassFile();
           			} else {
           				element = member.getCompilationUnit();
           			}
          @@ -3156,24 +3168,25 @@ public class JavaCore {
           			return false;
           
           		IJavaElement markerElement = JavaCore.create(markerHandleId);
          -		//	while (true){
          +		// while (true){
           		if (element.equals(markerElement))
          -			return true; // external elements may still be equal with different
          -						 // handleIDs.
          +			return true; // external elements may still be equal with
          +							// different
          +		// handleIDs.
           
           		// cycle through enclosing types in case marker is associated with a
           		// classfile (15568)
          -		//		if (markerElement instanceof IClassFile){
          -		//			IType enclosingType =
          +		// if (markerElement instanceof IClassFile){
          +		// IType enclosingType =
           		// ((IClassFile)markerElement).getType().getDeclaringType();
          -		//			if (enclosingType != null){
          -		//				markerElement = enclosingType.getClassFile(); // retry with immediate
          +		// if (enclosingType != null){
          +		// markerElement = enclosingType.getClassFile(); // retry with immediate
           		// enclosing classfile
          -		//				continue;
          -		//			}
          -		//		}
          -		//		break;
          -		//	}
          +		// continue;
          +		// }
          +		// }
          +		// break;
          +		// }
           		return false;
           	}
           
          @@ -3198,7 +3211,7 @@ public class JavaCore {
           		if (element instanceof IMember) {
           			IMember member = (IMember) element;
           			if (member.isBinary()) {
          -				element = null; //member.getClassFile();
          +				element = null; // member.getClassFile();
           			} else {
           				element = member.getCompilationUnit();
           			}
          @@ -3214,24 +3227,25 @@ public class JavaCore {
           			return false;
           
           		IJavaElement markerElement = JavaCore.create(markerDeltarHandleId);
          -		//	while (true){
          +		// while (true){
           		if (element.equals(markerElement))
          -			return true; // external elements may still be equal with different
          -						 // handleIDs.
          +			return true; // external elements may still be equal with
          +							// different
          +		// handleIDs.
           
           		// cycle through enclosing types in case marker is associated with a
           		// classfile (15568)
          -		//		if (markerElement instanceof IClassFile){
          -		//			IType enclosingType =
          +		// if (markerElement instanceof IClassFile){
          +		// IType enclosingType =
           		// ((IClassFile)markerElement).getType().getDeclaringType();
          -		//			if (enclosingType != null){
          -		//				markerElement = enclosingType.getClassFile(); // retry with immediate
          +		// if (enclosingType != null){
          +		// markerElement = enclosingType.getClassFile(); // retry with immediate
           		// enclosing classfile
          -		//				continue;
          -		//			}
          -		//		}
          -		//		break;
          -		//	}
          +		// continue;
          +		// }
          +		// }
          +		// break;
          +		// }
           		return false;
           	}
           
          @@ -3250,14 +3264,15 @@ public class JavaCore {
           	 * 

          * A container is exclusively resolved by a * ClasspathContainerInitializer registered onto the - * extension point "net.sourceforge.phpdt.core.classpathContainerInitializer". + * extension point + * "net.sourceforge.phpdt.core.classpathContainerInitializer". *

          * A container path must be formed of at least one segment, where: *

            *
          • the first segment is a unique ID identifying the target container, * there must be a container initializer registered onto this ID through the - * extension point "net.sourceforge.phpdt.core.classpathContainerInitializer". - *
          • + * extension point + * "net.sourceforge.phpdt.core.classpathContainerInitializer". *
          • the remaining segments will be passed onto the initializer, and can * be used as additional hints during the initialization phase.
          • *
          @@ -3268,7 +3283,8 @@ public class JavaCore { * containerEntry = JavaCore.newContainerEntry(new * Path("MyProvidedJDK/default")); * - * + * * *

          @@ -3290,354 +3306,371 @@ public class JavaCore { */ public static IClasspathEntry newContainerEntry(IPath containerPath) { - return newContainerEntry(containerPath, false); - } - - /** - * Creates and returns a new classpath entry of kind - * CPE_CONTAINER for the given path. The path of the - * container will be used during resolution so as to map this container - * entry to a set of other classpath entries the container is acting for. - *

          - * A container entry allows to express indirect references to a set of - * libraries, projects and variable entries, which can be interpreted - * differently for each Java project where it is used. A classpath container - * entry can be resolved using - * JavaCore.getResolvedClasspathContainer, and updated with - * JavaCore.classpathContainerChanged - *

          - * A container is exclusively resolved by a - * ClasspathContainerInitializer registered onto the - * extension point "net.sourceforge.phpdt.core.classpathContainerInitializer". - *

          - * A container path must be formed of at least one segment, where: - *

            - *
          • the first segment is a unique ID identifying the target container, - * there must be a container initializer registered onto this ID through the - * extension point "net.sourceforge.phpdt.core.classpathContainerInitializer". - *
          • - *
          • the remaining segments will be passed onto the initializer, and can - * be used as additional hints during the initialization phase.
          • - *
          - *

          - * Example of an ClasspathContainerInitializer for a classpath container - * denoting a default JDK container: - * - * containerEntry = JavaCore.newContainerEntry(new - * Path("MyProvidedJDK/default")); - * - * - * - *

          - * Note that this operation does not attempt to validate classpath - * containers or access the resources at the given paths. - *

          - * - * @param containerPath - * the path identifying the container, it must be formed of at - * least one segment (ID+hints) - * @param isExported - * a boolean indicating whether this entry is contributed to - * dependent projects in addition to the output location - * @return a new container classpath entry - * - * @see JavaCore#getClasspathContainer(IPath, IJavaProject) - * @see JavaCore#setClasspathContainer(IPath, IJavaProject[], - * IClasspathContainer[], IProgressMonitor) - * @see JavaCore#newContainerEntry(IPath, boolean) - * @since 2.0 - */ - - public static IClasspathEntry newContainerEntry(IPath containerPath, boolean isExported) { - - if (containerPath == null) Assert.isTrue(false, "Container path cannot be null"); //$NON-NLS-1$ - if (containerPath.segmentCount() < 1) { - Assert.isTrue( - false, - "Illegal classpath container path: \'" + containerPath.makeRelative().toString() + "\', must have at least one segment (containerID+hints)"); //$NON-NLS-1$//$NON-NLS-2$ + return newContainerEntry(containerPath, false); } - return new ClasspathEntry( - IPackageFragmentRoot.K_SOURCE, - IClasspathEntry.CPE_CONTAINER, - containerPath, - ClasspathEntry.INCLUDE_ALL, - ClasspathEntry.EXCLUDE_NONE, - null, // source attachment - null, // source attachment root - null, // specific output folder - isExported); -} - - /** - * Creates and returns a new non-exported classpath entry of kind - * CPE_LIBRARY for the JAR or folder identified by the given - * absolute path. This specifies that all package fragments within the root - * will have children of type IClassFile. - *

          - * A library entry is used to denote a prerequisite JAR or root folder - * containing binaries. The target JAR or folder can either be defined - * internally to the workspace (absolute path relative to the workspace - * root) or externally to the workspace (absolute path in the file system). - *

          - * e.g. Here are some examples of binary path usage - *

            - *
          • "c:/jdk1.2.2/jre/lib/rt.jar" - reference to an - * external JAR
          • - *
          • "/Project/someLib.jar" - reference to an internal JAR - *
          • - *
          • "c:/classes/" - reference to an external binary - * folder
          • - *
          - * Note that this operation does not attempt to validate or access the - * resources at the given paths. - *

          - * The resulting entry is not exported to dependent projects. This method is - * equivalent to newLibraryEntry(-,-,-,false). - *

          - * - * @param path - * the absolute path of the binary archive - * @param sourceAttachmentPath - * the absolute path of the corresponding source archive or - * folder, or null if none - * @param sourceAttachmentRootPath - * the location of the root within the source archive or folder - * or null if this location should be - * automatically detected. - * @return a new library classpath entry - * - * @see #newLibraryEntry(IPath, IPath, IPath, boolean) - */ - //public static IClasspathEntry newLibraryEntry( - // IPath path, - // IPath sourceAttachmentPath, - // IPath sourceAttachmentRootPath) { - // - // return newLibraryEntry(path, sourceAttachmentPath, - // sourceAttachmentRootPath, false); - //} - /** - * Creates and returns a new classpath entry of kind - * CPE_LIBRARY for the JAR or folder identified by the given - * absolute path. This specifies that all package fragments within the root - * will have children of type IClassFile. - *

          - * A library entry is used to denote a prerequisite JAR or root folder - * containing binaries. The target JAR or folder can either be defined - * internally to the workspace (absolute path relative to the workspace - * root) or externally to the workspace (absolute path in the file system). - *

          - * e.g. Here are some examples of binary path usage - *

            - *
          • "c:/jdk1.2.2/jre/lib/rt.jar" - reference to an - * external JAR
          • - *
          • "/Project/someLib.jar" - reference to an internal JAR - *
          • - *
          • "c:/classes/" - reference to an external binary - * folder
          • - *
          - * Note that this operation does not attempt to validate or access the - * resources at the given paths. - *

          - * - * @param path - * the absolute path of the binary archive - * @param sourceAttachmentPath - * the absolute path of the corresponding source archive or - * folder, or null if none - * @param sourceAttachmentRootPath - * the location of the root within the source archive or folder - * or null if this location should be - * automatically detected. - * @param isExported - * indicates whether this entry is contributed to dependent - * projects in addition to the output location - * @return a new library classpath entry - * @since 2.0 - */ - //public static IClasspathEntry newLibraryEntry( - // IPath path, - // IPath sourceAttachmentPath, - // IPath sourceAttachmentRootPath, - // boolean isExported) { - // - // if (!path.isAbsolute()) Assert.isTrue(false, "Path for IClasspathEntry - // must be absolute"); //$NON-NLS-1$ - // - // return new ClasspathEntry( - // IPackageFragmentRoot.K_BINARY, - // IClasspathEntry.CPE_LIBRARY, - // JavaProject.canonicalizedPath(path), - // ClasspathEntry.NO_EXCLUSION_PATTERNS, - // sourceAttachmentPath, - // sourceAttachmentRootPath, - // null, // specific output folder - // isExported); - //} - /** - * Creates and returns a new non-exported classpath entry of kind - * CPE_PROJECT for the project identified by the given - * absolute path. - *

          - * A project entry is used to denote a prerequisite project on a classpath. - * The referenced project will be contributed as a whole, either as sources - * (in the Java Model, it contributes all its package fragment roots) or as - * binaries (when building, it contributes its whole output location). - *

          - * A project reference allows to indirect through another project, - * independently from its internal layout. - *

          - * The prerequisite project is referred to using an absolute path relative - * to the workspace root. - *

          - * The resulting entry is not exported to dependent projects. This method is - * equivalent to newProjectEntry(_,false). - *

          - * - * @param path - * the absolute path of the binary archive - * @return a new project classpath entry - * - * @see JavaCore#newProjectEntry(IPath, boolean) - */ - public static IClasspathEntry newProjectEntry(IPath path) { - return newProjectEntry(path, false); - } - - /** - * Creates and returns a new classpath entry of kind - * CPE_PROJECT for the project identified by the given - * absolute path. - *

          - * A project entry is used to denote a prerequisite project on a classpath. - * The referenced project will be contributed as a whole, either as sources - * (in the Java Model, it contributes all its package fragment roots) or as - * binaries (when building, it contributes its whole output location). - *

          - * A project reference allows to indirect through another project, - * independently from its internal layout. - *

          - * The prerequisite project is referred to using an absolute path relative - * to the workspace root. - *

          - * - * @param path - * the absolute path of the prerequisite project - * @param isExported - * indicates whether this entry is contributed to dependent - * projects in addition to the output location - * @return a new project classpath entry - * @since 2.0 - */ - public static IClasspathEntry newProjectEntry(IPath path, boolean isExported) { - - if (!path.isAbsolute()) Assert.isTrue(false, "Path for IClasspathEntry must be absolute"); //$NON-NLS-1$ - - return new ClasspathEntry( - IPackageFragmentRoot.K_SOURCE, - IClasspathEntry.CPE_PROJECT, - path, - ClasspathEntry.INCLUDE_ALL, - ClasspathEntry.EXCLUDE_NONE, - null, // source attachment - null, // source attachment root - null, // specific output folder - isExported); -} - - - /** - * Returns a new empty region. - * - * @return a new empty region - */ - public static IRegion newRegion() { - return new Region(); - } - - /** + + /** + * Creates and returns a new classpath entry of kind + * CPE_CONTAINER for the given path. The path of the + * container will be used during resolution so as to map this container + * entry to a set of other classpath entries the container is acting for. + *

          + * A container entry allows to express indirect references to a set of + * libraries, projects and variable entries, which can be interpreted + * differently for each Java project where it is used. A classpath container + * entry can be resolved using + * JavaCore.getResolvedClasspathContainer, and updated with + * JavaCore.classpathContainerChanged + *

          + * A container is exclusively resolved by a + * ClasspathContainerInitializer registered onto the + * extension point + * "net.sourceforge.phpdt.core.classpathContainerInitializer". + *

          + * A container path must be formed of at least one segment, where: + *

            + *
          • the first segment is a unique ID identifying the target container, + * there must be a container initializer registered onto this ID through the + * extension point + * "net.sourceforge.phpdt.core.classpathContainerInitializer".
          • + *
          • the remaining segments will be passed onto the initializer, and can + * be used as additional hints during the initialization phase.
          • + *
          + *

          + * Example of an ClasspathContainerInitializer for a classpath container + * denoting a default JDK container: + * + * containerEntry = JavaCore.newContainerEntry(new + * Path("MyProvidedJDK/default")); + * + * + * + *

          + * Note that this operation does not attempt to validate classpath + * containers or access the resources at the given paths. + *

          + * + * @param containerPath + * the path identifying the container, it must be formed of at + * least one segment (ID+hints) + * @param isExported + * a boolean indicating whether this entry is contributed to + * dependent projects in addition to the output location + * @return a new container classpath entry + * + * @see JavaCore#getClasspathContainer(IPath, IJavaProject) + * @see JavaCore#setClasspathContainer(IPath, IJavaProject[], + * IClasspathContainer[], IProgressMonitor) + * @see JavaCore#newContainerEntry(IPath, boolean) + * @since 2.0 + */ + + public static IClasspathEntry newContainerEntry(IPath containerPath, + boolean isExported) { + + if (containerPath == null) + Assert.isTrue(false, "Container path cannot be null"); //$NON-NLS-1$ + if (containerPath.segmentCount() < 1) { + Assert + .isTrue( + false, + "Illegal classpath container path: \'" + containerPath.makeRelative().toString() + "\', must have at least one segment (containerID+hints)"); //$NON-NLS-1$//$NON-NLS-2$ + } + return new ClasspathEntry(IPackageFragmentRoot.K_SOURCE, + IClasspathEntry.CPE_CONTAINER, containerPath, + ClasspathEntry.INCLUDE_ALL, ClasspathEntry.EXCLUDE_NONE, null, // source + // attachment + null, // source attachment root + null, // specific output folder + isExported); + } + + /** + * Creates and returns a new non-exported classpath entry of kind + * CPE_LIBRARY for the JAR or folder identified by the given + * absolute path. This specifies that all package fragments within the root + * will have children of type IClassFile. + *

          + * A library entry is used to denote a prerequisite JAR or root folder + * containing binaries. The target JAR or folder can either be defined + * internally to the workspace (absolute path relative to the workspace + * root) or externally to the workspace (absolute path in the file system). + *

          + * e.g. Here are some examples of binary path usage + *

            + *
          • "c:/jdk1.2.2/jre/lib/rt.jar" - reference to an + * external JAR
          • + *
          • "/Project/someLib.jar" - reference to an internal JAR + *
          • + *
          • "c:/classes/" - reference to an external binary + * folder
          • + *
          + * Note that this operation does not attempt to validate or access the + * resources at the given paths. + *

          + * The resulting entry is not exported to dependent projects. This method is + * equivalent to newLibraryEntry(-,-,-,false). + *

          + * + * @param path + * the absolute path of the binary archive + * @param sourceAttachmentPath + * the absolute path of the corresponding source archive or + * folder, or null if none + * @param sourceAttachmentRootPath + * the location of the root within the source archive or folder + * or null if this location should be + * automatically detected. + * @return a new library classpath entry + * + * @see #newLibraryEntry(IPath, IPath, IPath, boolean) + */ + // public static IClasspathEntry newLibraryEntry( + // IPath path, + // IPath sourceAttachmentPath, + // IPath sourceAttachmentRootPath) { + // + // return newLibraryEntry(path, sourceAttachmentPath, + // sourceAttachmentRootPath, false); + // } + /** + * Creates and returns a new classpath entry of kind + * CPE_LIBRARY for the JAR or folder identified by the given + * absolute path. This specifies that all package fragments within the root + * will have children of type IClassFile. + *

          + * A library entry is used to denote a prerequisite JAR or root folder + * containing binaries. The target JAR or folder can either be defined + * internally to the workspace (absolute path relative to the workspace + * root) or externally to the workspace (absolute path in the file system). + *

          + * e.g. Here are some examples of binary path usage + *

            + *
          • "c:/jdk1.2.2/jre/lib/rt.jar" - reference to an + * external JAR
          • + *
          • "/Project/someLib.jar" - reference to an internal JAR + *
          • + *
          • "c:/classes/" - reference to an external binary + * folder
          • + *
          + * Note that this operation does not attempt to validate or access the + * resources at the given paths. + *

          + * + * @param path + * the absolute path of the binary archive + * @param sourceAttachmentPath + * the absolute path of the corresponding source archive or + * folder, or null if none + * @param sourceAttachmentRootPath + * the location of the root within the source archive or folder + * or null if this location should be + * automatically detected. + * @param isExported + * indicates whether this entry is contributed to dependent + * projects in addition to the output location + * @return a new library classpath entry + * @since 2.0 + */ + // public static IClasspathEntry newLibraryEntry( + // IPath path, + // IPath sourceAttachmentPath, + // IPath sourceAttachmentRootPath, + // boolean isExported) { + // + // if (!path.isAbsolute()) Assert.isTrue(false, "Path for IClasspathEntry + // must be absolute"); //$NON-NLS-1$ + // + // return new ClasspathEntry( + // IPackageFragmentRoot.K_BINARY, + // IClasspathEntry.CPE_LIBRARY, + // JavaProject.canonicalizedPath(path), + // ClasspathEntry.NO_EXCLUSION_PATTERNS, + // sourceAttachmentPath, + // sourceAttachmentRootPath, + // null, // specific output folder + // isExported); + // } + /** + * Creates and returns a new non-exported classpath entry of kind + * CPE_PROJECT for the project identified by the given + * absolute path. + *

          + * A project entry is used to denote a prerequisite project on a classpath. + * The referenced project will be contributed as a whole, either as sources + * (in the Java Model, it contributes all its package fragment roots) or as + * binaries (when building, it contributes its whole output location). + *

          + * A project reference allows to indirect through another project, + * independently from its internal layout. + *

          + * The prerequisite project is referred to using an absolute path relative + * to the workspace root. + *

          + * The resulting entry is not exported to dependent projects. This method is + * equivalent to newProjectEntry(_,false). + *

          + * + * @param path + * the absolute path of the binary archive + * @return a new project classpath entry + * + * @see JavaCore#newProjectEntry(IPath, boolean) + */ + public static IClasspathEntry newProjectEntry(IPath path) { + return newProjectEntry(path, false); + } + + /** + * Creates and returns a new classpath entry of kind + * CPE_PROJECT for the project identified by the given + * absolute path. + *

          + * A project entry is used to denote a prerequisite project on a classpath. + * The referenced project will be contributed as a whole, either as sources + * (in the Java Model, it contributes all its package fragment roots) or as + * binaries (when building, it contributes its whole output location). + *

          + * A project reference allows to indirect through another project, + * independently from its internal layout. + *

          + * The prerequisite project is referred to using an absolute path relative + * to the workspace root. + *

          + * + * @param path + * the absolute path of the prerequisite project + * @param isExported + * indicates whether this entry is contributed to dependent + * projects in addition to the output location + * @return a new project classpath entry + * @since 2.0 + */ + public static IClasspathEntry newProjectEntry(IPath path, boolean isExported) { + + if (!path.isAbsolute()) + Assert.isTrue(false, "Path for IClasspathEntry must be absolute"); //$NON-NLS-1$ + + return new ClasspathEntry(IPackageFragmentRoot.K_SOURCE, + IClasspathEntry.CPE_PROJECT, path, ClasspathEntry.INCLUDE_ALL, + ClasspathEntry.EXCLUDE_NONE, null, // source attachment + null, // source attachment root + null, // specific output folder + isExported); + } + + /** + * Returns a new empty region. + * + * @return a new empty region + */ + public static IRegion newRegion() { + return new Region(); + } + + /** * Creates and returns a new classpath entry of kind CPE_SOURCE * for all files in the project's source folder identified by the given * absolute workspace-relative path. *

          * The convenience method is fully equivalent to: + * *

           	 * newSourceEntry(path, new IPath[] {}, new IPath[] {}, null);
           	 * 
          + * *

          * - * @param path the absolute workspace-relative path of a source folder + * @param path + * the absolute workspace-relative path of a source folder * @return a new source classpath entry * @see #newSourceEntry(IPath, IPath[], IPath[], IPath) */ public static IClasspathEntry newSourceEntry(IPath path) { - return newSourceEntry(path, ClasspathEntry.INCLUDE_ALL, ClasspathEntry.EXCLUDE_NONE, null /*output location*/); + return newSourceEntry(path, ClasspathEntry.INCLUDE_ALL, + ClasspathEntry.EXCLUDE_NONE, null /* output location */); } - + /** * Creates and returns a new classpath entry of kind CPE_SOURCE - * for the project's source folder identified by the given absolute + * for the project's source folder identified by the given absolute * workspace-relative path but excluding all source files with paths * matching any of the given patterns. *

          * The convenience method is fully equivalent to: + * *

           	 * newSourceEntry(path, new IPath[] {}, exclusionPatterns, null);
           	 * 
          + * *

          - * - * @param path the absolute workspace-relative path of a source folder - * @param exclusionPatterns the possibly empty list of exclusion patterns - * represented as relative paths + * + * @param path + * the absolute workspace-relative path of a source folder + * @param exclusionPatterns + * the possibly empty list of exclusion patterns represented as + * relative paths * @return a new source classpath entry * @see #newSourceEntry(IPath, IPath[], IPath[], IPath) * @since 2.1 */ - public static IClasspathEntry newSourceEntry(IPath path, IPath[] exclusionPatterns) { + public static IClasspathEntry newSourceEntry(IPath path, + IPath[] exclusionPatterns) { - return newSourceEntry(path, ClasspathEntry.INCLUDE_ALL, exclusionPatterns, null /*output location*/); + return newSourceEntry(path, ClasspathEntry.INCLUDE_ALL, + exclusionPatterns, null /* output location */); } /** * Creates and returns a new classpath entry of kind CPE_SOURCE - * for the project's source folder identified by the given absolute + * for the project's source folder identified by the given absolute * workspace-relative path but excluding all source files with paths - * matching any of the given patterns, and associated with a specific output location - * (that is, ".class" files are not going to the project default output location). + * matching any of the given patterns, and associated with a specific output + * location (that is, ".class" files are not going to the project default + * output location). *

          * The convenience method is fully equivalent to: + * *

           	 * newSourceEntry(path, new IPath[] {}, exclusionPatterns, specificOutputLocation);
           	 * 
          + * *

          - * - * @param path the absolute workspace-relative path of a source folder - * @param exclusionPatterns the possibly empty list of exclusion patterns - * represented as relative paths - * @param specificOutputLocation the specific output location for this source entry (null if using project default ouput location) + * + * @param path + * the absolute workspace-relative path of a source folder + * @param exclusionPatterns + * the possibly empty list of exclusion patterns represented as + * relative paths + * @param specificOutputLocation + * the specific output location for this source entry (null + * if using project default ouput location) * @return a new source classpath entry * @see #newSourceEntry(IPath, IPath[], IPath[], IPath) * @since 2.1 */ - public static IClasspathEntry newSourceEntry(IPath path, IPath[] exclusionPatterns, IPath specificOutputLocation) { + public static IClasspathEntry newSourceEntry(IPath path, + IPath[] exclusionPatterns, IPath specificOutputLocation) { - return newSourceEntry(path, ClasspathEntry.INCLUDE_ALL, exclusionPatterns, specificOutputLocation); + return newSourceEntry(path, ClasspathEntry.INCLUDE_ALL, + exclusionPatterns, specificOutputLocation); } - + /** * Creates and returns a new classpath entry of kind CPE_SOURCE - * for the project's source folder identified by the given absolute + * for the project's source folder identified by the given absolute * workspace-relative path using the given inclusion and exclusion patterns * to determine which source files are included, and the given output path * to control the output location of generated files. *

          * The source folder is referred to using an absolute path relative to the - * workspace root, e.g. /Project/src. A project's source - * folders are located with that project. That is, a source classpath - * entry specifying the path /P1/src is only usable for - * project P1. + * workspace root, e.g. /Project/src. A project's source + * folders are located with that project. That is, a source classpath entry + * specifying the path /P1/src is only usable for project + * P1. *

          *

          * The inclusion patterns determines the initial set of source files that @@ -3646,11 +3679,11 @@ public class JavaCore { * includes all relevent files in the resource tree rooted at the source * entry's path. On the other hand, specifying one or more inclusion * patterns means that all and only files matching at least one of - * the specified patterns are to be included. If exclusion patterns are + * the specified patterns are to be included. If exclusion patterns are * specified, the initial set of files is then reduced by eliminating files * matched by at least one of the exclusion patterns. Inclusion and * exclusion patterns look like relative file paths with wildcards and are - * interpreted relative to the source entry's path. File patterns are + * interpreted relative to the source entry's path. File patterns are * case-sensitive can contain '**', '*' or '?' wildcards (see * {@link IClasspathEntry#getExclusionPatterns()} for the full description * of their syntax and semantics). The resulting set of files are included @@ -3658,925 +3691,934 @@ public class JavaCore { * the root will have children of type ICompilationUnit. *

          *

          - * For example, if the source folder path is - * /Project/src, there are no inclusion filters, and the - * exclusion pattern is - * com/xyz/tests/**, then source files - * like /Project/src/com/xyz/Foo.java - * and /Project/src/com/xyz/utils/Bar.java would be included, - * whereas /Project/src/com/xyz/tests/T1.java - * and /Project/src/com/xyz/tests/quick/T2.java would be - * excluded. + * For example, if the source folder path is /Project/src, + * there are no inclusion filters, and the exclusion pattern is + * com/xyz/tests/**, then source files like + * /Project/src/com/xyz/Foo.java and + * /Project/src/com/xyz/utils/Bar.java would be included, + * whereas /Project/src/com/xyz/tests/T1.java and + * /Project/src/com/xyz/tests/quick/T2.java would be + * excluded. *

          *

          - * Additionally, a source entry can be associated with a specific output location. - * By doing so, the Java builder will ensure that the generated ".class" files will - * be issued inside this output location, as opposed to be generated into the - * project default output location (when output location is null). - * Note that multiple source entries may target the same output location. - * The output location is referred to using an absolute path relative to the - * workspace root, e.g. "/Project/bin", it must be located inside - * the same project as the source folder. + * Additionally, a source entry can be associated with a specific output + * location. By doing so, the Java builder will ensure that the generated + * ".class" files will be issued inside this output location, as opposed to + * be generated into the project default output location (when output + * location is null). Note that multiple source entries may + * target the same output location. The output location is referred to using + * an absolute path relative to the workspace root, e.g. + * "/Project/bin", it must be located inside the same + * project as the source folder. *

          *

          - * Also note that all sources/binaries inside a project are contributed as - * a whole through a project entry - * (see JavaCore.newProjectEntry). Particular source entries - * cannot be selectively exported. + * Also note that all sources/binaries inside a project are contributed as a + * whole through a project entry (see JavaCore.newProjectEntry). + * Particular source entries cannot be selectively exported. *

          - * - * @param path the absolute workspace-relative path of a source folder - * @param inclusionPatterns the possibly empty list of inclusion patterns - * represented as relative paths - * @param exclusionPatterns the possibly empty list of exclusion patterns - * represented as relative paths - * @param specificOutputLocation the specific output location for this source entry (null if using project default ouput location) + * + * @param path + * the absolute workspace-relative path of a source folder + * @param inclusionPatterns + * the possibly empty list of inclusion patterns represented as + * relative paths + * @param exclusionPatterns + * the possibly empty list of exclusion patterns represented as + * relative paths + * @param specificOutputLocation + * the specific output location for this source entry (null + * if using project default ouput location) * @return a new source classpath entry with the given exclusion patterns * @see IClasspathEntry#getInclusionPatterns() * @see IClasspathEntry#getExclusionPatterns() * @see IClasspathEntry#getOutputLocation() * @since 3.0 */ - public static IClasspathEntry newSourceEntry(IPath path, IPath[] inclusionPatterns, IPath[] exclusionPatterns, IPath specificOutputLocation) { - - if (path == null) Assert.isTrue(false, "Source path cannot be null"); //$NON-NLS-1$ - if (!path.isAbsolute()) Assert.isTrue(false, "Path for IClasspathEntry must be absolute"); //$NON-NLS-1$ - if (exclusionPatterns == null) Assert.isTrue(false, "Exclusion pattern set cannot be null"); //$NON-NLS-1$ - if (inclusionPatterns == null) Assert.isTrue(false, "Inclusion pattern set cannot be null"); //$NON-NLS-1$ - - return new ClasspathEntry( - IPackageFragmentRoot.K_SOURCE, - IClasspathEntry.CPE_SOURCE, - path, - inclusionPatterns, - exclusionPatterns, - null, // source attachment - null, // source attachment root - specificOutputLocation, // custom output location - false); + public static IClasspathEntry newSourceEntry(IPath path, + IPath[] inclusionPatterns, IPath[] exclusionPatterns, + IPath specificOutputLocation) { + + if (path == null) + Assert.isTrue(false, "Source path cannot be null"); //$NON-NLS-1$ + if (!path.isAbsolute()) + Assert.isTrue(false, "Path for IClasspathEntry must be absolute"); //$NON-NLS-1$ + if (exclusionPatterns == null) + Assert.isTrue(false, "Exclusion pattern set cannot be null"); //$NON-NLS-1$ + if (inclusionPatterns == null) + Assert.isTrue(false, "Inclusion pattern set cannot be null"); //$NON-NLS-1$ + + return new ClasspathEntry(IPackageFragmentRoot.K_SOURCE, + IClasspathEntry.CPE_SOURCE, path, inclusionPatterns, + exclusionPatterns, null, // source attachment + null, // source attachment root + specificOutputLocation, // custom output location + false); } - /** - * Creates and returns a new non-exported classpath entry of kind - * CPE_VARIABLE for the given path. The first segment of the - * path is the name of a classpath variable. The trailing segments of the - * path will be appended to resolved variable path. - *

          - * A variable entry allows to express indirect references on a classpath to - * other projects or libraries, depending on what the classpath variable is - * referring. - *

          - * It is possible to register an automatic initializer ( - * ClasspathVariableInitializer), which will be invoked - * through the extension point - * "net.sourceforge.phpdt.core.classpathVariableInitializer". After resolution, a - * classpath variable entry may either correspond to a project or a library - * entry. - *

          - * e.g. Here are some examples of variable path usage - *

            - *
          • "JDTCORE" where variable JDTCORE is bound to - * "c:/jars/jdtcore.jar". The resolved classpath entry is denoting the - * library "c:\jars\jdtcore.jar"
          • - *
          • "JDTCORE" where variable JDTCORE is bound to - * "/Project_JDTCORE". The resolved classpath entry is denoting the project - * "/Project_JDTCORE"
          • - *
          • "PLUGINS/com.example/example.jar" where variable - * PLUGINS is bound to "c:/eclipse/plugins". The resolved - * classpath entry is denoting the library - * "c:/eclipse/plugins/com.example/example.jar"
          • - *
          - * Note that this operation does not attempt to validate classpath variables - * or access the resources at the given paths. - *

          - * The resulting entry is not exported to dependent projects. This method is - * equivalent to newVariableEntry(-,-,-,false). - *

          - * - * @param variablePath - * the path of the binary archive; first segment is the name of a - * classpath variable - * @param variableSourceAttachmentPath - * the path of the corresponding source archive, or - * null if none; if present, the first segment is - * the name of a classpath variable (not necessarily the same - * variable as the one that begins variablePath) - * @param sourceAttachmentRootPath - * the location of the root within the source archive or - * null if archivePath is also - * null - * @return a new library classpath entry - * - * @see JavaCore#newVariableEntry(IPath, IPath, IPath, boolean) - */ - //public static IClasspathEntry newVariableEntry( - // IPath variablePath, - // IPath variableSourceAttachmentPath, - // IPath sourceAttachmentRootPath) { - // - // return newVariableEntry(variablePath, variableSourceAttachmentPath, - // sourceAttachmentRootPath, false); - //} - /** - * Creates and returns a new non-exported classpath entry of kind - * CPE_VARIABLE for the given path. The first segment of the - * path is the name of a classpath variable. The trailing segments of the - * path will be appended to resolved variable path. - *

          - * A variable entry allows to express indirect references on a classpath to - * other projects or libraries, depending on what the classpath variable is - * referring. - *

          - * It is possible to register an automatic initializer ( - * ClasspathVariableInitializer), which will be invoked - * through the extension point - * "net.sourceforge.phpdt.core.classpathVariableInitializer". After resolution, a - * classpath variable entry may either correspond to a project or a library - * entry. - *

          - * e.g. Here are some examples of variable path usage - *

            - *
          • "JDTCORE" where variable JDTCORE is bound to - * "c:/jars/jdtcore.jar". The resolved classpath entry is denoting the - * library "c:\jars\jdtcore.jar"
          • - *
          • "JDTCORE" where variable JDTCORE is bound to - * "/Project_JDTCORE". The resolved classpath entry is denoting the project - * "/Project_JDTCORE"
          • - *
          • "PLUGINS/com.example/example.jar" where variable - * PLUGINS is bound to "c:/eclipse/plugins". The resolved - * classpath entry is denoting the library - * "c:/eclipse/plugins/com.example/example.jar"
          • - *
          - * Note that this operation does not attempt to validate classpath variables - * or access the resources at the given paths. - *

          - * - * @param variablePath - * the path of the binary archive; first segment is the name of a - * classpath variable - * @param variableSourceAttachmentPath - * the path of the corresponding source archive, or - * null if none; if present, the first segment is - * the name of a classpath variable (not necessarily the same - * variable as the one that begins variablePath) - * @param sourceAttachmentRootPath - * the location of the root within the source archive or - * null if archivePath is also - * null - * @param isExported - * indicates whether this entry is contributed to dependent - * projects in addition to the output location - * @return a new variable classpath entry - * @since 2.0 - */ - //public static IClasspathEntry newVariableEntry( - // IPath variablePath, - // IPath variableSourceAttachmentPath, - // IPath variableSourceAttachmentRootPath, - // boolean isExported) { - // - // if (variablePath == null || variablePath.segmentCount() < 1) { - // Assert.isTrue( - // false, - // "Illegal classpath variable path: \'" + - // variablePath.makeRelative().toString() + "\', must have at least one - // segment"); //$NON-NLS-1$//$NON-NLS-2$ - // } - // - // return new ClasspathEntry( - // IPackageFragmentRoot.K_SOURCE, - // IClasspathEntry.CPE_VARIABLE, - // variablePath, - // ClasspathEntry.NO_EXCLUSION_PATTERNS, - // variableSourceAttachmentPath, // source attachment - // variableSourceAttachmentRootPath, // source attachment root - // null, // specific output folder - // isExported); - //} - /** - * Removed the given classpath variable. Does nothing if no value was set - * for this classpath variable. - *

          - * This functionality cannot be used while the resource tree is locked. - *

          - * Classpath variable values are persisted locally to the workspace, and are - * preserved from session to session. - *

          - * - * @param variableName - * the name of the classpath variable - * @see #setClasspathVariable - * - * @deprecated - use version with extra IProgressMonitor - */ - //public static void removeClasspathVariable(String variableName) { - // removeClasspathVariable(variableName, null); - //} - /** - * Removed the given classpath variable. Does nothing if no value was set - * for this classpath variable. - *

          - * This functionality cannot be used while the resource tree is locked. - *

          - * Classpath variable values are persisted locally to the workspace, and are - * preserved from session to session. - *

          - * - * @param variableName - * the name of the classpath variable - * @param monitor - * the progress monitor to report progress - * @see #setClasspathVariable - */ - //public static void removeClasspathVariable( - // String variableName, - // IProgressMonitor monitor) { - // - // try { - // updateVariableValues(new String[]{ variableName}, new IPath[]{ null }, - // monitor); - // } catch (JavaModelException e) { - // } - //} - /** - * Removes the given element changed listener. Has no affect if an identical - * listener is not registered. - * - * @param listener - * the listener - */ - public static void removeElementChangedListener( - IElementChangedListener listener) { - JavaModelManager.getJavaModelManager().removeElementChangedListener( - listener); - } - - /** - * Bind a container reference path to some actual containers ( - * IClasspathContainer). This API must be invoked whenever - * changes in container need to be reflected onto the JavaModel. Containers - * can have distinct values in different projects, therefore this API - * considers a set of projects with their respective containers. - *

          - * containerPath is the path under which these values can be - * referenced through container classpath entries ( - * IClasspathEntry#CPE_CONTAINER). A container path is - * formed by a first ID segment followed with extra segments, which can be - * used as additional hints for the resolution. The container ID is used to - * identify a ClasspathContainerInitializer registered on the - * extension point "net.sourceforge.phpdt.core.classpathContainerInitializer". - *

          - * There is no assumption that each individual container value passed in - * argument (respectiveContainers) must answer the exact - * same path when requested IClasspathContainer#getPath. - * Indeed, the containerPath is just an indication for resolving it to an - * actual container object. It can be delegated to a - * ClasspathContainerInitializer, which can be activated - * through the extension point - * "net.sourceforge.phpdt.core.ClasspathContainerInitializer"). - *

          - * In reaction to changing container values, the JavaModel will be updated - * to reflect the new state of the updated container. - *

          - * This functionality cannot be used while the resource tree is locked. - *

          - * Classpath container values are persisted locally to the workspace, but - * are not preserved from a session to another. It is thus highly - * recommended to register a ClasspathContainerInitializer - * for each referenced container (through the extension point - * "net.sourceforge.phpdt.core.ClasspathContainerInitializer"). - *

          - * Note: setting a container to null will cause it to be - * lazily resolved again whenever its value is required. In particular, this - * will cause a registered initializer to be invoked again. - *

          - * - * @param containerPath - - * the name of the container reference, which is being updated - * @param affectedProjects - - * the set of projects for which this container is being bound - * @param respectiveContainers - - * the set of respective containers for the affected projects - * @param monitor - * a monitor to report progress - * - * @see ClasspathContainerInitializer - * @see #getClasspathContainer(IPath, IJavaProject) - * @see IClasspathContainer - * @since 2.0 - */ - //public static void setClasspathContainer(final IPath containerPath, - // IJavaProject[] affectedProjects, IClasspathContainer[] - // respectiveContainers, IProgressMonitor monitor) throws JavaModelException - // { - // - // if (affectedProjects.length != respectiveContainers.length) - // Assert.isTrue(false, "Projects and containers collections should have the - // same size"); //$NON-NLS-1$ - // - // if (monitor != null && monitor.isCanceled()) return; - // - // if (JavaModelManager.CP_RESOLVE_VERBOSE){ - // System.out.println("CPContainer SET - setting container: - // ["+containerPath+"] for projects: {" //$NON-NLS-1$ //$NON-NLS-2$ - // + (ProjectPrefUtil.toString(affectedProjects, - // new ProjectPrefUtil.Displayable(){ - // public String displayString(Object o) { return ((IJavaProject) - // o).getElementName(); } - // })) - // + "} with values: " //$NON-NLS-1$ - // + (ProjectPrefUtil.toString(respectiveContainers, - // new ProjectPrefUtil.Displayable(){ - // public String displayString(Object o) { return ((IClasspathContainer) - // o).getDescription(); } - // })) - // ); - // } - // - // final int projectLength = affectedProjects.length; - // final IJavaProject[] modifiedProjects; - // System.arraycopy(affectedProjects, 0, modifiedProjects = new - // IJavaProject[projectLength], 0, projectLength); - // final IClasspathEntry[][] oldResolvedPaths = new - // IClasspathEntry[projectLength][]; - // - // // filter out unmodified project containers - // int remaining = 0; - // for (int i = 0; i < projectLength; i++){ - // - // if (monitor != null && monitor.isCanceled()) return; - // - // IJavaProject affectedProject = affectedProjects[i]; - // IClasspathContainer newContainer = respectiveContainers[i]; - // if (newContainer == null) newContainer = - // JavaModelManager.ContainerInitializationInProgress; // 30920 - prevent - // infinite loop - // boolean found = false; - // if (JavaProject.hasJavaNature(affectedProject.getProject())){ - // IClasspathEntry[] rawClasspath = affectedProject.getRawClasspath(); - // for (int j = 0, cpLength = rawClasspath.length; j - * This functionality cannot be used while the resource tree is locked. - *

          - * Classpath variable values are persisted locally to the workspace, and are - * preserved from session to session. - *

          - * - * @param variableName - * the name of the classpath variable - * @param path - * the path - * @see #getClasspathVariable - * - * @deprecated - use API with IProgressMonitor - */ - //public static void setClasspathVariable(String variableName, IPath path) - // throws JavaModelException { - // - // setClasspathVariable(variableName, path, null); - //} - /** - * Sets the value of the given classpath variable. The path must not be - * null. - *

          - * This functionality cannot be used while the resource tree is locked. - *

          - * Classpath variable values are persisted locally to the workspace, and are - * preserved from session to session. - *

          - * Updating a variable with the same value has no effect. - * - * @param variableName - * the name of the classpath variable - * @param path - * the path - * @param monitor - * a monitor to report progress - * @see #getClasspathVariable - */ - //public static void setClasspathVariable( - // String variableName, - // IPath path, - // IProgressMonitor monitor) - // throws JavaModelException { - // - // if (path == null) Assert.isTrue(false, "Variable path cannot be null"); - // //$NON-NLS-1$ - // setClasspathVariables(new String[]{variableName}, new IPath[]{ path }, - // monitor); - //} - /** - * Sets the values of all the given classpath variables at once. Null paths - * can be used to request corresponding variable removal. - *

          - * This functionality cannot be used while the resource tree is locked. - *

          - * Classpath variable values are persisted locally to the workspace, and are - * preserved from session to session. - *

          - * Updating a variable with the same value has no effect. - * - * @param variableNames - * an array of names for the updated classpath variables - * @param paths - * an array of path updates for the modified classpath variables - * (null meaning that the corresponding value will be removed - * @param monitor - * a monitor to report progress - * @see #getClasspathVariable - * @since 2.0 - */ - //public static void setClasspathVariables( - // String[] variableNames, - // IPath[] paths, - // IProgressMonitor monitor) - // throws JavaModelException { - // - // if (variableNames.length != paths.length) Assert.isTrue(false, "Variable - // names and paths collections should have the same size"); //$NON-NLS-1$ - // //TODO: should check that null cannot be used as variable paths - // updateVariableValues(variableNames, paths, monitor); - //} - /* - * (non-Javadoc) Method declared on IExecutableExtension. Record any - * necessary initialization data from the plugin. - */ - public void setInitializationData(IConfigurationElement cfig, - String propertyName, Object data) throws CoreException { - } - - /** - * Sets the current table of options. All and only the options explicitly - * included in the given table are remembered; all previous option settings - * are forgotten, including ones not explicitly mentioned. - *

          - * For a complete description of the configurable options, see - * getDefaultOptions. - *

          - * - * @param newOptions - * the new options (key type: String; value type: - * String), or null to reset all - * options to their default values - * @see JavaCore#getDefaultOptions - */ - public static void setOptions(Hashtable newOptions) { - - // see #initializeDefaultPluginPreferences() for changing default - // settings - Preferences preferences = getPlugin().getPluginPreferences(); - - if (newOptions == null) { - newOptions = JavaCore.getDefaultOptions(); - } - Enumeration keys = newOptions.keys(); - while (keys.hasMoreElements()) { - String key = (String) keys.nextElement(); - if (!JavaModelManager.OptionNames.contains(key)) - continue; // unrecognized option - if (key.equals(CORE_ENCODING)) - continue; // skipped, contributed by resource prefs - String value = (String) newOptions.get(key); - preferences.setValue(key, value); - } - - // persist options - getPlugin().savePluginPreferences(); - } - - /** - * Shutdown the JavaCore plug-in. - *

          - * De-registers the JavaModelManager as a resource changed listener and save - * participant. - *

          - * - * @see org.eclipse.core.runtime.Plugin#shutdown() - */ - // moved to PHPeclipsePlugin#shutdown() - //public void shutdown() { - // - // //savePluginPreferences(); - // getPlugin().savePluginPreferences(); - // IWorkspace workspace = ResourcesPlugin.getWorkspace(); - // workspace.removeResourceChangeListener(JavaModelManager.getJavaModelManager().deltaProcessor); - // workspace.removeSaveParticipant(PHPeclipsePlugin.getDefault()); - // - // ((JavaModelManager) JavaModelManager.getJavaModelManager()).shutdown(); - //} - /** - * Initiate the background indexing process. This should be deferred after - * the plugin activation. - */ - //private void startIndexing() { - // - // JavaModelManager.getJavaModelManager().getIndexManager().reset(); - //} - /** - * Startup of the JavaCore plug-in. - *

          - * Registers the JavaModelManager as a resource changed listener and save - * participant. Starts the background indexing, and restore saved classpath - * variable values. - *

          - * - * @see org.eclipse.core.runtime.Plugin#startup() - */ - - // moved to PHPeclipsePlugin#startup() - //public void startup() { - // - // JavaModelManager manager = JavaModelManager.getJavaModelManager(); - // try { - // manager.configurePluginDebugOptions(); - // - // // request state folder creation (workaround 19885) - // JavaCore.getPlugin().getStateLocation(); - // - // // retrieve variable values - // JavaCore.getPlugin().getPluginPreferences().addPropertyChangeListener(new - // JavaModelManager.PluginPreferencesListener()); - //// TODO : jsurfer temp-del - //// manager.loadVariablesAndContainers(); - // - // IWorkspace workspace = ResourcesPlugin.getWorkspace(); - // workspace.addResourceChangeListener( - // manager.deltaProcessor, - // IResourceChangeEvent.PRE_AUTO_BUILD - // | IResourceChangeEvent.POST_AUTO_BUILD - // | IResourceChangeEvent.POST_CHANGE - // | IResourceChangeEvent.PRE_DELETE - // | IResourceChangeEvent.PRE_CLOSE); - // - //// startIndexing(); - // workspace.addSaveParticipant(PHPeclipsePlugin.getDefault(), manager); - // - // } catch (CoreException e) { - // } catch (RuntimeException e) { - // manager.shutdown(); - // throw e; - // } - //} - /** - * Internal updating of a variable values (null path meaning removal), - * allowing to change multiple variable values at once. - */ - //private static void updateVariableValues( - // String[] variableNames, - // IPath[] variablePaths, - // IProgressMonitor monitor) throws JavaModelException { - // - // if (monitor != null && monitor.isCanceled()) return; - // - // if (JavaModelManager.CP_RESOLVE_VERBOSE){ - // System.out.println("CPVariable SET - setting variables: {" + - // ProjectPrefUtil.toString(variableNames) //$NON-NLS-1$ - // + "} with values: " + ProjectPrefUtil.toString(variablePaths)); //$NON-NLS-1$ - // } - // - // int varLength = variableNames.length; - // - // // gather classpath information for updating - // final HashMap affectedProjects = new HashMap(5); - // JavaModelManager manager = JavaModelManager.getJavaModelManager(); - // IJavaModel model = manager.getJavaModel(); - // - // // filter out unmodified variables - // int discardCount = 0; - // for (int i = 0; i < varLength; i++){ - // String variableName = variableNames[i]; - // IPath oldPath = (IPath)JavaModelManager.variableGet(variableName); // if - // reentering will provide previous session value - // if (oldPath == JavaModelManager.VariableInitializationInProgress){ - // IPath previousPath = - // (IPath)JavaModelManager.PreviousSessionVariables.get(variableName); - // if (previousPath != null){ - // if (JavaModelManager.CP_RESOLVE_VERBOSE){ - // System.out.println("CPVariable INIT - reentering access to variable: " + - // variableName+ " during its initialization, will see previous value: "+ - // previousPath); //$NON-NLS-1$ //$NON-NLS-2$ - // } - // JavaModelManager.variablePut(variableName, previousPath); // replace - // value so reentering calls are seeing old value - // } - // oldPath = null; //33695 - cannot filter out restored variable, must - // update affected project to reset cached CP - // } - // if (oldPath != null && oldPath.equals(variablePaths[i])){ - // variableNames[i] = null; - // discardCount++; - // } - // } - // if (discardCount > 0){ - // if (discardCount == varLength) return; - // int changedLength = varLength - discardCount; - // String[] changedVariableNames = new String[changedLength]; - // IPath[] changedVariablePaths = new IPath[changedLength]; - // for (int i = 0, index = 0; i < varLength; i++){ - // if (variableNames[i] != null){ - // changedVariableNames[index] = variableNames[i]; - // changedVariablePaths[index] = variablePaths[i]; - // index++; - // } - // } - // variableNames = changedVariableNames; - // variablePaths = changedVariablePaths; - // varLength = changedLength; - // } - // - // if (monitor != null && monitor.isCanceled()) return; - // - // if (model != null) { - // IJavaProject[] projects = model.getJavaProjects(); - // nextProject : for (int i = 0, projectLength = projects.length; i < - // projectLength; i++){ - // IJavaProject project = projects[i]; - // - // // check to see if any of the modified variables is present on the - // classpath - // IClasspathEntry[] classpath = project.getRawClasspath(); - // for (int j = 0, cpLength = classpath.length; j < cpLength; j++){ - // - // IClasspathEntry entry = classpath[j]; - // for (int k = 0; k < varLength; k++){ - // - // String variableName = variableNames[k]; - // if (entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE){ - // - // if (variableName.equals(entry.getPath().segment(0))){ - // affectedProjects.put(project, project.getResolvedClasspath(true)); - // continue nextProject; - // } - // IPath sourcePath, sourceRootPath; - // if (((sourcePath = entry.getSourceAttachmentPath()) != null && - // variableName.equals(sourcePath.segment(0))) - // || ((sourceRootPath = entry.getSourceAttachmentRootPath()) != null && - // variableName.equals(sourceRootPath.segment(0)))) { - // - // affectedProjects.put(project, project.getResolvedClasspath(true)); - // continue nextProject; - // } - // } - // } - // } - // } - // } - // // update variables - // for (int i = 0; i < varLength; i++){ - // JavaModelManager.variablePut(variableNames[i], variablePaths[i]); - // } - // final String[] dbgVariableNames = variableNames; - // - // // update affected project classpaths - // if (!affectedProjects.isEmpty()) { - // try { - // JavaCore_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt.run( - // new IWorkspaceRunnable() { - // public void run(IProgressMonitor monitor) throws CoreException { - // // propagate classpath change - // Iterator projectsToUpdate = affectedProjects.keySet().iterator(); - // while (projectsToUpdate.hasNext()) { - // - // if (monitor != null && monitor.isCanceled()) return; - // - // JavaProject project = (JavaProject) projectsToUpdate.next(); - // - // if (JavaModelManager.CP_RESOLVE_VERBOSE){ - // System.out.println("CPVariable SET - updating affected project: - // ["+project.getElementName()+"] due to setting variables: "+ - // ProjectPrefUtil.toString(dbgVariableNames)); //$NON-NLS-1$ //$NON-NLS-2$ - // } - // - // project - // .setRawClasspath( - // project.getRawClasspath(), - // SetClasspathOperation.ReuseOutputLocation, - // null, // don't call beginTask on the monitor (see - // http://bugs.eclipse.org/bugs/show_bug.cgi?id=3717) - // !ResourcesPlugin.getWorkspace().isTreeLocked(), // can change resources - // (IClasspathEntry[]) affectedProjects.get(project), - // false, // updating - no validation - // false); // updating - no need to save - // } - // } - // }, - // monitor); - // } catch (CoreException e) { - // if (JavaModelManager.CP_RESOLVE_VERBOSE){ - // System.out.println("CPVariable SET - FAILED DUE TO EXCEPTION: - // "+ProjectPrefUtil.toString(dbgVariableNames)); //$NON-NLS-1$ - // e.printStackTrace(); - // } - // if (e instanceof JavaModelException) { - // throw (JavaModelException)e; - // } else { - // throw new JavaModelException(e); - // } - // } - // } - //} - /* - * (non-Javadoc) Startup the JavaCore plug-in.

          Registers the - * JavaModelManager as a resource changed listener and save participant. - * Starts the background indexing, and restore saved classpath variable - * values.

          @throws Exception - * - * @see org.eclipse.core.runtime.Plugin#start(BundleContext) - */ - //public static void start(final Plugin plugin, BundleContext context) - // throws Exception { - //// super.start(context); - // - // final JavaModelManager manager = JavaModelManager.getJavaModelManager(); - // try { - // manager.configurePluginDebugOptions(); - // - // // request state folder creation (workaround 19885) - // JavaCore.getPlugin().getStateLocation(); - // - // // retrieve variable values - // //JavaCore.getPlugin().getPluginPreferences().addPropertyChangeListener(new - // JavaModelManager.PluginPreferencesListener()); - //// manager.loadVariablesAndContainers(); - // - // final IWorkspace workspace = ResourcesPlugin.getWorkspace(); - // workspace.addResourceChangeListener( - // manager.deltaState, - // IResourceChangeEvent.PRE_BUILD - // | IResourceChangeEvent.POST_BUILD - // | IResourceChangeEvent.POST_CHANGE - // | IResourceChangeEvent.PRE_DELETE - // | IResourceChangeEvent.PRE_CLOSE); - // - //// startIndexing(); - // - // // process deltas since last activated in indexer thread so that indexes - // are up-to-date. - // // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38658 - // Job processSavedState = new Job(ProjectPrefUtil.bind("savedState.jobName")) { - // //$NON-NLS-1$ - // protected IStatus run(IProgressMonitor monitor) { - // try { - // // add save participant and process delta atomically - // // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=59937 - // workspace.run( - // new IWorkspaceRunnable() { - // public void run(IProgressMonitor progress) throws CoreException { - //// ISavedState savedState = workspace.addSaveParticipant(JavaCore.this, - // manager); - // ISavedState savedState = workspace.addSaveParticipant(plugin, manager); - // if (savedState != null) { - // // the event type coming from the saved state is always POST_AUTO_BUILD - // // force it to be POST_CHANGE so that the delta processor can handle it - // manager.deltaState.getDeltaProcessor().overridenEventType = - // IResourceChangeEvent.POST_CHANGE; - // savedState.processResourceChangeEvents(manager.deltaState); - // } - // } - // }, - // monitor); - // } catch (CoreException e) { - // return e.getStatus(); - // } - // return Status.OK_STATUS; - // } - // }; - // processSavedState.setSystem(true); - // processSavedState.setPriority(Job.SHORT); // process asap - // processSavedState.schedule(); - // } catch (RuntimeException e) { - // manager.shutdown(); - // throw e; - // } - //} - /* - * (non-Javadoc) Shutdown the JavaCore plug-in.

          De-registers the - * JavaModelManager as a resource changed listener and save participant.

          - * - * @see org.eclipse.core.runtime.Plugin#stop(BundleContext) - */ -// public static void stop(Plugin plugin, BundleContext context) -// throws Exception { -// try { -// plugin.savePluginPreferences(); -// IWorkspace workspace = ResourcesPlugin.getWorkspace(); -// workspace.removeResourceChangeListener(JavaModelManager -// .getJavaModelManager().deltaState); -// workspace.removeSaveParticipant(plugin); -// -// JavaModelManager.getJavaModelManager().shutdown(); -// } finally { -// // ensure we call super.stop as the last thing -// // super.stop(context); -// } -// } + /** + * Creates and returns a new non-exported classpath entry of kind + * CPE_VARIABLE for the given path. The first segment of the + * path is the name of a classpath variable. The trailing segments of the + * path will be appended to resolved variable path. + *

          + * A variable entry allows to express indirect references on a classpath to + * other projects or libraries, depending on what the classpath variable is + * referring. + *

          + * It is possible to register an automatic initializer ( + * ClasspathVariableInitializer), which will be invoked + * through the extension point + * "net.sourceforge.phpdt.core.classpathVariableInitializer". After + * resolution, a classpath variable entry may either correspond to a project + * or a library entry. + *

          + * e.g. Here are some examples of variable path usage + *

            + *
          • "JDTCORE" where variable JDTCORE is bound to + * "c:/jars/jdtcore.jar". The resolved classpath entry is denoting the + * library "c:\jars\jdtcore.jar"
          • + *
          • "JDTCORE" where variable JDTCORE is bound to + * "/Project_JDTCORE". The resolved classpath entry is denoting the project + * "/Project_JDTCORE"
          • + *
          • "PLUGINS/com.example/example.jar" where variable + * PLUGINS is bound to "c:/eclipse/plugins". The resolved + * classpath entry is denoting the library + * "c:/eclipse/plugins/com.example/example.jar"
          • + *
          + * Note that this operation does not attempt to validate classpath variables + * or access the resources at the given paths. + *

          + * The resulting entry is not exported to dependent projects. This method is + * equivalent to newVariableEntry(-,-,-,false). + *

          + * + * @param variablePath + * the path of the binary archive; first segment is the name of a + * classpath variable + * @param variableSourceAttachmentPath + * the path of the corresponding source archive, or + * null if none; if present, the first segment is + * the name of a classpath variable (not necessarily the same + * variable as the one that begins variablePath) + * @param sourceAttachmentRootPath + * the location of the root within the source archive or + * null if archivePath is also + * null + * @return a new library classpath entry + * + * @see JavaCore#newVariableEntry(IPath, IPath, IPath, boolean) + */ + // public static IClasspathEntry newVariableEntry( + // IPath variablePath, + // IPath variableSourceAttachmentPath, + // IPath sourceAttachmentRootPath) { + // + // return newVariableEntry(variablePath, variableSourceAttachmentPath, + // sourceAttachmentRootPath, false); + // } + /** + * Creates and returns a new non-exported classpath entry of kind + * CPE_VARIABLE for the given path. The first segment of the + * path is the name of a classpath variable. The trailing segments of the + * path will be appended to resolved variable path. + *

          + * A variable entry allows to express indirect references on a classpath to + * other projects or libraries, depending on what the classpath variable is + * referring. + *

          + * It is possible to register an automatic initializer ( + * ClasspathVariableInitializer), which will be invoked + * through the extension point + * "net.sourceforge.phpdt.core.classpathVariableInitializer". After + * resolution, a classpath variable entry may either correspond to a project + * or a library entry. + *

          + * e.g. Here are some examples of variable path usage + *

            + *
          • "JDTCORE" where variable JDTCORE is bound to + * "c:/jars/jdtcore.jar". The resolved classpath entry is denoting the + * library "c:\jars\jdtcore.jar"
          • + *
          • "JDTCORE" where variable JDTCORE is bound to + * "/Project_JDTCORE". The resolved classpath entry is denoting the project + * "/Project_JDTCORE"
          • + *
          • "PLUGINS/com.example/example.jar" where variable + * PLUGINS is bound to "c:/eclipse/plugins". The resolved + * classpath entry is denoting the library + * "c:/eclipse/plugins/com.example/example.jar"
          • + *
          + * Note that this operation does not attempt to validate classpath variables + * or access the resources at the given paths. + *

          + * + * @param variablePath + * the path of the binary archive; first segment is the name of a + * classpath variable + * @param variableSourceAttachmentPath + * the path of the corresponding source archive, or + * null if none; if present, the first segment is + * the name of a classpath variable (not necessarily the same + * variable as the one that begins variablePath) + * @param sourceAttachmentRootPath + * the location of the root within the source archive or + * null if archivePath is also + * null + * @param isExported + * indicates whether this entry is contributed to dependent + * projects in addition to the output location + * @return a new variable classpath entry + * @since 2.0 + */ + // public static IClasspathEntry newVariableEntry( + // IPath variablePath, + // IPath variableSourceAttachmentPath, + // IPath variableSourceAttachmentRootPath, + // boolean isExported) { + // + // if (variablePath == null || variablePath.segmentCount() < 1) { + // Assert.isTrue( + // false, + // "Illegal classpath variable path: \'" + + // variablePath.makeRelative().toString() + "\', must have at least one + // segment"); //$NON-NLS-1$//$NON-NLS-2$ + // } + // + // return new ClasspathEntry( + // IPackageFragmentRoot.K_SOURCE, + // IClasspathEntry.CPE_VARIABLE, + // variablePath, + // ClasspathEntry.NO_EXCLUSION_PATTERNS, + // variableSourceAttachmentPath, // source attachment + // variableSourceAttachmentRootPath, // source attachment root + // null, // specific output folder + // isExported); + // } + /** + * Removed the given classpath variable. Does nothing if no value was set + * for this classpath variable. + *

          + * This functionality cannot be used while the resource tree is locked. + *

          + * Classpath variable values are persisted locally to the workspace, and are + * preserved from session to session. + *

          + * + * @param variableName + * the name of the classpath variable + * @see #setClasspathVariable + * + * @deprecated - use version with extra IProgressMonitor + */ + // public static void removeClasspathVariable(String variableName) { + // removeClasspathVariable(variableName, null); + // } + /** + * Removed the given classpath variable. Does nothing if no value was set + * for this classpath variable. + *

          + * This functionality cannot be used while the resource tree is locked. + *

          + * Classpath variable values are persisted locally to the workspace, and are + * preserved from session to session. + *

          + * + * @param variableName + * the name of the classpath variable + * @param monitor + * the progress monitor to report progress + * @see #setClasspathVariable + */ + // public static void removeClasspathVariable( + // String variableName, + // IProgressMonitor monitor) { + // + // try { + // updateVariableValues(new String[]{ variableName}, new IPath[]{ null }, + // monitor); + // } catch (JavaModelException e) { + // } + // } + /** + * Removes the given element changed listener. Has no affect if an identical + * listener is not registered. + * + * @param listener + * the listener + */ + public static void removeElementChangedListener( + IElementChangedListener listener) { + JavaModelManager.getJavaModelManager().removeElementChangedListener( + listener); + } + + /** + * Bind a container reference path to some actual containers ( + * IClasspathContainer). This API must be invoked whenever + * changes in container need to be reflected onto the JavaModel. Containers + * can have distinct values in different projects, therefore this API + * considers a set of projects with their respective containers. + *

          + * containerPath is the path under which these values can be + * referenced through container classpath entries ( + * IClasspathEntry#CPE_CONTAINER). A container path is + * formed by a first ID segment followed with extra segments, which can be + * used as additional hints for the resolution. The container ID is used to + * identify a ClasspathContainerInitializer registered on the + * extension point + * "net.sourceforge.phpdt.core.classpathContainerInitializer". + *

          + * There is no assumption that each individual container value passed in + * argument (respectiveContainers) must answer the exact + * same path when requested IClasspathContainer#getPath. + * Indeed, the containerPath is just an indication for resolving it to an + * actual container object. It can be delegated to a + * ClasspathContainerInitializer, which can be activated + * through the extension point + * "net.sourceforge.phpdt.core.ClasspathContainerInitializer"). + *

          + * In reaction to changing container values, the JavaModel will be updated + * to reflect the new state of the updated container. + *

          + * This functionality cannot be used while the resource tree is locked. + *

          + * Classpath container values are persisted locally to the workspace, but + * are not preserved from a session to another. It is thus highly + * recommended to register a ClasspathContainerInitializer + * for each referenced container (through the extension point + * "net.sourceforge.phpdt.core.ClasspathContainerInitializer"). + *

          + * Note: setting a container to null will cause it to be + * lazily resolved again whenever its value is required. In particular, this + * will cause a registered initializer to be invoked again. + *

          + * + * @param containerPath - + * the name of the container reference, which is being updated + * @param affectedProjects - + * the set of projects for which this container is being bound + * @param respectiveContainers - + * the set of respective containers for the affected projects + * @param monitor + * a monitor to report progress + * + * @see ClasspathContainerInitializer + * @see #getClasspathContainer(IPath, IJavaProject) + * @see IClasspathContainer + * @since 2.0 + */ + // public static void setClasspathContainer(final IPath containerPath, + // IJavaProject[] affectedProjects, IClasspathContainer[] + // respectiveContainers, IProgressMonitor monitor) throws JavaModelException + // { + // + // if (affectedProjects.length != respectiveContainers.length) + // Assert.isTrue(false, "Projects and containers collections should have the + // same size"); //$NON-NLS-1$ + // + // if (monitor != null && monitor.isCanceled()) return; + // + // if (JavaModelManager.CP_RESOLVE_VERBOSE){ + // System.out.println("CPContainer SET - setting container: + // ["+containerPath+"] for projects: {" //$NON-NLS-1$ //$NON-NLS-2$ + // + (ProjectPrefUtil.toString(affectedProjects, + // new ProjectPrefUtil.Displayable(){ + // public String displayString(Object o) { return ((IJavaProject) + // o).getElementName(); } + // })) + // + "} with values: " //$NON-NLS-1$ + // + (ProjectPrefUtil.toString(respectiveContainers, + // new ProjectPrefUtil.Displayable(){ + // public String displayString(Object o) { return ((IClasspathContainer) + // o).getDescription(); } + // })) + // ); + // } + // + // final int projectLength = affectedProjects.length; + // final IJavaProject[] modifiedProjects; + // System.arraycopy(affectedProjects, 0, modifiedProjects = new + // IJavaProject[projectLength], 0, projectLength); + // final IClasspathEntry[][] oldResolvedPaths = new + // IClasspathEntry[projectLength][]; + // + // // filter out unmodified project containers + // int remaining = 0; + // for (int i = 0; i < projectLength; i++){ + // + // if (monitor != null && monitor.isCanceled()) return; + // + // IJavaProject affectedProject = affectedProjects[i]; + // IClasspathContainer newContainer = respectiveContainers[i]; + // if (newContainer == null) newContainer = + // JavaModelManager.ContainerInitializationInProgress; // 30920 - prevent + // infinite loop + // boolean found = false; + // if (JavaProject.hasJavaNature(affectedProject.getProject())){ + // IClasspathEntry[] rawClasspath = affectedProject.getRawClasspath(); + // for (int j = 0, cpLength = rawClasspath.length; j + * This functionality cannot be used while the resource tree is locked. + *

          + * Classpath variable values are persisted locally to the workspace, and are + * preserved from session to session. + *

          + * + * @param variableName + * the name of the classpath variable + * @param path + * the path + * @see #getClasspathVariable + * + * @deprecated - use API with IProgressMonitor + */ + // public static void setClasspathVariable(String variableName, IPath path) + // throws JavaModelException { + // + // setClasspathVariable(variableName, path, null); + // } + /** + * Sets the value of the given classpath variable. The path must not be + * null. + *

          + * This functionality cannot be used while the resource tree is locked. + *

          + * Classpath variable values are persisted locally to the workspace, and are + * preserved from session to session. + *

          + * Updating a variable with the same value has no effect. + * + * @param variableName + * the name of the classpath variable + * @param path + * the path + * @param monitor + * a monitor to report progress + * @see #getClasspathVariable + */ + // public static void setClasspathVariable( + // String variableName, + // IPath path, + // IProgressMonitor monitor) + // throws JavaModelException { + // + // if (path == null) Assert.isTrue(false, "Variable path cannot be null"); + // //$NON-NLS-1$ + // setClasspathVariables(new String[]{variableName}, new IPath[]{ path }, + // monitor); + // } + /** + * Sets the values of all the given classpath variables at once. Null paths + * can be used to request corresponding variable removal. + *

          + * This functionality cannot be used while the resource tree is locked. + *

          + * Classpath variable values are persisted locally to the workspace, and are + * preserved from session to session. + *

          + * Updating a variable with the same value has no effect. + * + * @param variableNames + * an array of names for the updated classpath variables + * @param paths + * an array of path updates for the modified classpath variables + * (null meaning that the corresponding value will be removed + * @param monitor + * a monitor to report progress + * @see #getClasspathVariable + * @since 2.0 + */ + // public static void setClasspathVariables( + // String[] variableNames, + // IPath[] paths, + // IProgressMonitor monitor) + // throws JavaModelException { + // + // if (variableNames.length != paths.length) Assert.isTrue(false, "Variable + // names and paths collections should have the same size"); //$NON-NLS-1$ + // //TODO: should check that null cannot be used as variable paths + // updateVariableValues(variableNames, paths, monitor); + // } + /* + * (non-Javadoc) Method declared on IExecutableExtension. Record any + * necessary initialization data from the plugin. + */ + public void setInitializationData(IConfigurationElement cfig, + String propertyName, Object data) throws CoreException { + } + + /** + * Sets the current table of options. All and only the options explicitly + * included in the given table are remembered; all previous option settings + * are forgotten, including ones not explicitly mentioned. + *

          + * For a complete description of the configurable options, see + * getDefaultOptions. + *

          + * + * @param newOptions + * the new options (key type: String; value type: + * String), or null to reset all + * options to their default values + * @see JavaCore#getDefaultOptions + */ + public static void setOptions(Hashtable newOptions) { + + // see #initializeDefaultPluginPreferences() for changing default + // settings + Preferences preferences = getPlugin().getPluginPreferences(); + + if (newOptions == null) { + newOptions = JavaCore.getDefaultOptions(); + } + Enumeration keys = newOptions.keys(); + while (keys.hasMoreElements()) { + String key = (String) keys.nextElement(); + if (!JavaModelManager.OptionNames.contains(key)) + continue; // unrecognized option + if (key.equals(CORE_ENCODING)) + continue; // skipped, contributed by resource prefs + String value = (String) newOptions.get(key); + preferences.setValue(key, value); + } + + // persist options + getPlugin().savePluginPreferences(); + } + + /** + * Shutdown the JavaCore plug-in. + *

          + * De-registers the JavaModelManager as a resource changed listener and save + * participant. + *

          + * + * @see org.eclipse.core.runtime.Plugin#shutdown() + */ + // moved to PHPeclipsePlugin#shutdown() + // public void shutdown() { + // + // //savePluginPreferences(); + // getPlugin().savePluginPreferences(); + // IWorkspace workspace = ResourcesPlugin.getWorkspace(); + // workspace.removeResourceChangeListener(JavaModelManager.getJavaModelManager().deltaProcessor); + // workspace.removeSaveParticipant(PHPeclipsePlugin.getDefault()); + // + // ((JavaModelManager) JavaModelManager.getJavaModelManager()).shutdown(); + // } + /** + * Initiate the background indexing process. This should be deferred after + * the plugin activation. + */ + // private void startIndexing() { + // + // JavaModelManager.getJavaModelManager().getIndexManager().reset(); + // } + /** + * Startup of the JavaCore plug-in. + *

          + * Registers the JavaModelManager as a resource changed listener and save + * participant. Starts the background indexing, and restore saved classpath + * variable values. + *

          + * + * @see org.eclipse.core.runtime.Plugin#startup() + */ + + // moved to PHPeclipsePlugin#startup() + // public void startup() { + // + // JavaModelManager manager = JavaModelManager.getJavaModelManager(); + // try { + // manager.configurePluginDebugOptions(); + // + // // request state folder creation (workaround 19885) + // JavaCore.getPlugin().getStateLocation(); + // + // // retrieve variable values + // JavaCore.getPlugin().getPluginPreferences().addPropertyChangeListener(new + // JavaModelManager.PluginPreferencesListener()); + // // TODO : jsurfer temp-del + // // manager.loadVariablesAndContainers(); + // + // IWorkspace workspace = ResourcesPlugin.getWorkspace(); + // workspace.addResourceChangeListener( + // manager.deltaProcessor, + // IResourceChangeEvent.PRE_AUTO_BUILD + // | IResourceChangeEvent.POST_AUTO_BUILD + // | IResourceChangeEvent.POST_CHANGE + // | IResourceChangeEvent.PRE_DELETE + // | IResourceChangeEvent.PRE_CLOSE); + // + // // startIndexing(); + // workspace.addSaveParticipant(PHPeclipsePlugin.getDefault(), manager); + // + // } catch (CoreException e) { + // } catch (RuntimeException e) { + // manager.shutdown(); + // throw e; + // } + // } + /** + * Internal updating of a variable values (null path meaning removal), + * allowing to change multiple variable values at once. + */ + // private static void updateVariableValues( + // String[] variableNames, + // IPath[] variablePaths, + // IProgressMonitor monitor) throws JavaModelException { + // + // if (monitor != null && monitor.isCanceled()) return; + // + // if (JavaModelManager.CP_RESOLVE_VERBOSE){ + // System.out.println("CPVariable SET - setting variables: {" + + // ProjectPrefUtil.toString(variableNames) //$NON-NLS-1$ + // + "} with values: " + ProjectPrefUtil.toString(variablePaths)); + // //$NON-NLS-1$ + // } + // + // int varLength = variableNames.length; + // + // // gather classpath information for updating + // final HashMap affectedProjects = new HashMap(5); + // JavaModelManager manager = JavaModelManager.getJavaModelManager(); + // IJavaModel model = manager.getJavaModel(); + // + // // filter out unmodified variables + // int discardCount = 0; + // for (int i = 0; i < varLength; i++){ + // String variableName = variableNames[i]; + // IPath oldPath = (IPath)JavaModelManager.variableGet(variableName); // if + // reentering will provide previous session value + // if (oldPath == JavaModelManager.VariableInitializationInProgress){ + // IPath previousPath = + // (IPath)JavaModelManager.PreviousSessionVariables.get(variableName); + // if (previousPath != null){ + // if (JavaModelManager.CP_RESOLVE_VERBOSE){ + // System.out.println("CPVariable INIT - reentering access to variable: " + + // variableName+ " during its initialization, will see previous value: "+ + // previousPath); //$NON-NLS-1$ //$NON-NLS-2$ + // } + // JavaModelManager.variablePut(variableName, previousPath); // replace + // value so reentering calls are seeing old value + // } + // oldPath = null; //33695 - cannot filter out restored variable, must + // update affected project to reset cached CP + // } + // if (oldPath != null && oldPath.equals(variablePaths[i])){ + // variableNames[i] = null; + // discardCount++; + // } + // } + // if (discardCount > 0){ + // if (discardCount == varLength) return; + // int changedLength = varLength - discardCount; + // String[] changedVariableNames = new String[changedLength]; + // IPath[] changedVariablePaths = new IPath[changedLength]; + // for (int i = 0, index = 0; i < varLength; i++){ + // if (variableNames[i] != null){ + // changedVariableNames[index] = variableNames[i]; + // changedVariablePaths[index] = variablePaths[i]; + // index++; + // } + // } + // variableNames = changedVariableNames; + // variablePaths = changedVariablePaths; + // varLength = changedLength; + // } + // + // if (monitor != null && monitor.isCanceled()) return; + // + // if (model != null) { + // IJavaProject[] projects = model.getJavaProjects(); + // nextProject : for (int i = 0, projectLength = projects.length; i < + // projectLength; i++){ + // IJavaProject project = projects[i]; + // + // // check to see if any of the modified variables is present on the + // classpath + // IClasspathEntry[] classpath = project.getRawClasspath(); + // for (int j = 0, cpLength = classpath.length; j < cpLength; j++){ + // + // IClasspathEntry entry = classpath[j]; + // for (int k = 0; k < varLength; k++){ + // + // String variableName = variableNames[k]; + // if (entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE){ + // + // if (variableName.equals(entry.getPath().segment(0))){ + // affectedProjects.put(project, project.getResolvedClasspath(true)); + // continue nextProject; + // } + // IPath sourcePath, sourceRootPath; + // if (((sourcePath = entry.getSourceAttachmentPath()) != null && + // variableName.equals(sourcePath.segment(0))) + // || ((sourceRootPath = entry.getSourceAttachmentRootPath()) != null && + // variableName.equals(sourceRootPath.segment(0)))) { + // + // affectedProjects.put(project, project.getResolvedClasspath(true)); + // continue nextProject; + // } + // } + // } + // } + // } + // } + // // update variables + // for (int i = 0; i < varLength; i++){ + // JavaModelManager.variablePut(variableNames[i], variablePaths[i]); + // } + // final String[] dbgVariableNames = variableNames; + // + // // update affected project classpaths + // if (!affectedProjects.isEmpty()) { + // try { + // JavaCore_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt.run( + // new IWorkspaceRunnable() { + // public void run(IProgressMonitor monitor) throws CoreException { + // // propagate classpath change + // Iterator projectsToUpdate = affectedProjects.keySet().iterator(); + // while (projectsToUpdate.hasNext()) { + // + // if (monitor != null && monitor.isCanceled()) return; + // + // JavaProject project = (JavaProject) projectsToUpdate.next(); + // + // if (JavaModelManager.CP_RESOLVE_VERBOSE){ + // System.out.println("CPVariable SET - updating affected project: + // ["+project.getElementName()+"] due to setting variables: "+ + // ProjectPrefUtil.toString(dbgVariableNames)); //$NON-NLS-1$ //$NON-NLS-2$ + // } + // + // project + // .setRawClasspath( + // project.getRawClasspath(), + // SetClasspathOperation.ReuseOutputLocation, + // null, // don't call beginTask on the monitor (see + // http://bugs.eclipse.org/bugs/show_bug.cgi?id=3717) + // !ResourcesPlugin.getWorkspace().isTreeLocked(), // can change resources + // (IClasspathEntry[]) affectedProjects.get(project), + // false, // updating - no validation + // false); // updating - no need to save + // } + // } + // }, + // monitor); + // } catch (CoreException e) { + // if (JavaModelManager.CP_RESOLVE_VERBOSE){ + // System.out.println("CPVariable SET - FAILED DUE TO EXCEPTION: + // "+ProjectPrefUtil.toString(dbgVariableNames)); //$NON-NLS-1$ + // e.printStackTrace(); + // } + // if (e instanceof JavaModelException) { + // throw (JavaModelException)e; + // } else { + // throw new JavaModelException(e); + // } + // } + // } + // } + /* + * (non-Javadoc) Startup the JavaCore plug-in.

          Registers the + * JavaModelManager as a resource changed listener and save participant. + * Starts the background indexing, and restore saved classpath variable + * values.

          @throws Exception + * + * @see org.eclipse.core.runtime.Plugin#start(BundleContext) + */ + // public static void start(final Plugin plugin, BundleContext context) + // throws Exception { + // // super.start(context); + // + // final JavaModelManager manager = JavaModelManager.getJavaModelManager(); + // try { + // manager.configurePluginDebugOptions(); + // + // // request state folder creation (workaround 19885) + // JavaCore.getPlugin().getStateLocation(); + // + // // retrieve variable values + // //JavaCore.getPlugin().getPluginPreferences().addPropertyChangeListener(new + // JavaModelManager.PluginPreferencesListener()); + // // manager.loadVariablesAndContainers(); + // + // final IWorkspace workspace = ResourcesPlugin.getWorkspace(); + // workspace.addResourceChangeListener( + // manager.deltaState, + // IResourceChangeEvent.PRE_BUILD + // | IResourceChangeEvent.POST_BUILD + // | IResourceChangeEvent.POST_CHANGE + // | IResourceChangeEvent.PRE_DELETE + // | IResourceChangeEvent.PRE_CLOSE); + // + // // startIndexing(); + // + // // process deltas since last activated in indexer thread so that indexes + // are up-to-date. + // // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38658 + // Job processSavedState = new + // Job(ProjectPrefUtil.bind("savedState.jobName")) { + // //$NON-NLS-1$ + // protected IStatus run(IProgressMonitor monitor) { + // try { + // // add save participant and process delta atomically + // // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=59937 + // workspace.run( + // new IWorkspaceRunnable() { + // public void run(IProgressMonitor progress) throws CoreException { + // // ISavedState savedState = workspace.addSaveParticipant(JavaCore.this, + // manager); + // ISavedState savedState = workspace.addSaveParticipant(plugin, manager); + // if (savedState != null) { + // // the event type coming from the saved state is always POST_AUTO_BUILD + // // force it to be POST_CHANGE so that the delta processor can handle it + // manager.deltaState.getDeltaProcessor().overridenEventType = + // IResourceChangeEvent.POST_CHANGE; + // savedState.processResourceChangeEvents(manager.deltaState); + // } + // } + // }, + // monitor); + // } catch (CoreException e) { + // return e.getStatus(); + // } + // return Status.OK_STATUS; + // } + // }; + // processSavedState.setSystem(true); + // processSavedState.setPriority(Job.SHORT); // process asap + // processSavedState.schedule(); + // } catch (RuntimeException e) { + // manager.shutdown(); + // throw e; + // } + // } + /* + * (non-Javadoc) Shutdown the JavaCore plug-in.

          De-registers the + * JavaModelManager as a resource changed listener and save participant.

          + * + * @see org.eclipse.core.runtime.Plugin#stop(BundleContext) + */ + // public static void stop(Plugin plugin, BundleContext context) + // throws Exception { + // try { + // plugin.savePluginPreferences(); + // IWorkspace workspace = ResourcesPlugin.getWorkspace(); + // workspace.removeResourceChangeListener(JavaModelManager + // .getJavaModelManager().deltaState); + // workspace.removeSaveParticipant(plugin); + // + // JavaModelManager.getJavaModelManager().shutdown(); + // } finally { + // // ensure we call super.stop as the last thing + // // super.stop(context); + // } + // } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaModelException.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaModelException.java index 2f77107..935b219 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaModelException.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaModelException.java @@ -15,120 +15,133 @@ import net.sourceforge.phpdt.internal.core.JavaModelStatus; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; -//import net.sourceforge.phpdt.internal.core.JavaModelStatus; +// import net.sourceforge.phpdt.internal.core.JavaModelStatus; /** - * A checked exception representing a failure in the Java model. - * Java model exceptions contain a Java-specific status object describing the - * cause of the exception. + * A checked exception representing a failure in the Java model. Java model + * exceptions contain a Java-specific status object describing the cause of the + * exception. *

          * This class is not intended to be subclassed by clients. Instances of this * class are automatically created by the Java model when problems arise, so * there is generally no need for clients to create instances. *

          - * + * * @see IJavaModelStatus * @see IJavaModelStatusConstants */ public class JavaModelException extends CoreException { CoreException nestedCoreException; -/** - * Creates a Java model exception that wrappers the given Throwable. - * The exception contains a Java-specific status object with severity - * IStatus.ERROR and the given status code. - * - * @param exception the Throwable - * @param code one of the Java-specific status codes declared in - * IJavaModelStatusConstants - * @see IJavaModelStatusConstants - * @see org.eclipse.core.runtime.IStatus#ERROR - */ -public JavaModelException(Throwable e, int code) { - this(new JavaModelStatus(code, e)); -} -/** - * Creates a Java model exception for the given CoreException. - * Equivalent to - * JavaModelException(exception,IJavaModelStatusConstants.CORE_EXCEPTION. - * - * @param exception the CoreException - */ -public JavaModelException(CoreException exception) { - super(exception.getStatus()); - this.nestedCoreException = exception; -} -/** - * Creates a Java model exception for the given Java-specific status object. - * - * @param status the Java-specific status object - */ -public JavaModelException(IJavaModelStatus status) { - super(status); -} -/** - * Returns the underlying Throwable that caused the failure. - * - * @return the wrappered Throwable, or null if the - * direct case of the failure was at the Java model layer - */ -public Throwable getException() { - if (this.nestedCoreException == null) { - return getStatus().getException(); - } else { - return this.nestedCoreException; + + /** + * Creates a Java model exception that wrappers the given + * Throwable. The exception contains a Java-specific status + * object with severity IStatus.ERROR and the given status + * code. + * + * @param exception + * the Throwable + * @param code + * one of the Java-specific status codes declared in + * IJavaModelStatusConstants + * @see IJavaModelStatusConstants + * @see org.eclipse.core.runtime.IStatus#ERROR + */ + public JavaModelException(Throwable e, int code) { + this(new JavaModelStatus(code, e)); } -} -/** - * Returns the Java model status object for this exception. - * Equivalent to (IJavaModelStatus) getStatus(). - * - * @return a status object - */ -public IJavaModelStatus getJavaModelStatus() { - IStatus status = this.getStatus(); - if (status instanceof IJavaModelStatus) { - return (IJavaModelStatus)status; - } else { - // A regular IStatus is created only in the case of a CoreException. - // See bug 13492 Should handle JavaModelExceptions that contains CoreException more gracefully - return new JavaModelStatus(this.nestedCoreException); + + /** + * Creates a Java model exception for the given CoreException. + * Equivalent to + * JavaModelException(exception,IJavaModelStatusConstants.CORE_EXCEPTION. + * + * @param exception + * the CoreException + */ + public JavaModelException(CoreException exception) { + super(exception.getStatus()); + this.nestedCoreException = exception; } -} -/** - * Returns whether this exception indicates that a Java model element does not - * exist. Such exceptions have a status with a code of - * IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST. - * This is a convenience method. - * - * @return true if this exception indicates that a Java model - * element does not exist - * @see IJavaModelStatus#isDoesNotExist - * @see IJavaModelStatusConstants#ELEMENT_DOES_NOT_EXIST - */ -public boolean isDoesNotExist() { - IJavaModelStatus javaModelStatus = getJavaModelStatus(); - return javaModelStatus != null && javaModelStatus.isDoesNotExist(); -} -/** - * Returns a printable representation of this exception suitable for debugging - * purposes only. - */ -public String toString() { - StringBuffer buffer= new StringBuffer(); - buffer.append("Java Model Exception: "); //$NON-NLS-1$ - if (getException() != null) { - if (getException() instanceof CoreException) { - CoreException c= (CoreException)getException(); - buffer.append("Core Exception [code "); //$NON-NLS-1$ - buffer.append(c.getStatus().getCode()); - buffer.append("] "); //$NON-NLS-1$ - buffer.append(c.getStatus().getMessage()); + + /** + * Creates a Java model exception for the given Java-specific status object. + * + * @param status + * the Java-specific status object + */ + public JavaModelException(IJavaModelStatus status) { + super(status); + } + + /** + * Returns the underlying Throwable that caused the failure. + * + * @return the wrappered Throwable, or null + * if the direct case of the failure was at the Java model layer + */ + public Throwable getException() { + if (this.nestedCoreException == null) { + return getStatus().getException(); } else { - buffer.append(getException().toString()); + return this.nestedCoreException; } - } else { - buffer.append(getStatus().toString()); } - return buffer.toString(); -} + + /** + * Returns the Java model status object for this exception. Equivalent to + * (IJavaModelStatus) getStatus(). + * + * @return a status object + */ + public IJavaModelStatus getJavaModelStatus() { + IStatus status = this.getStatus(); + if (status instanceof IJavaModelStatus) { + return (IJavaModelStatus) status; + } else { + // A regular IStatus is created only in the case of a CoreException. + // See bug 13492 Should handle JavaModelExceptions that contains + // CoreException more gracefully + return new JavaModelStatus(this.nestedCoreException); + } + } + + /** + * Returns whether this exception indicates that a Java model element does + * not exist. Such exceptions have a status with a code of + * IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST. This is + * a convenience method. + * + * @return true if this exception indicates that a Java model + * element does not exist + * @see IJavaModelStatus#isDoesNotExist + * @see IJavaModelStatusConstants#ELEMENT_DOES_NOT_EXIST + */ + public boolean isDoesNotExist() { + IJavaModelStatus javaModelStatus = getJavaModelStatus(); + return javaModelStatus != null && javaModelStatus.isDoesNotExist(); + } + + /** + * Returns a printable representation of this exception suitable for + * debugging purposes only. + */ + public String toString() { + StringBuffer buffer = new StringBuffer(); + buffer.append("Java Model Exception: "); //$NON-NLS-1$ + if (getException() != null) { + if (getException() instanceof CoreException) { + CoreException c = (CoreException) getException(); + buffer.append("Core Exception [code "); //$NON-NLS-1$ + buffer.append(c.getStatus().getCode()); + buffer.append("] "); //$NON-NLS-1$ + buffer.append(c.getStatus().getMessage()); + } else { + buffer.append(getException().toString()); + } + } else { + buffer.append(getStatus().toString()); + } + return buffer.toString(); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/NamingConventions.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/NamingConventions.java index 532ee06..a0c8d3e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/NamingConventions.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/NamingConventions.java @@ -15,7 +15,6 @@ import net.sourceforge.phpdt.internal.codeassist.impl.AssistOptions; import net.sourceforge.phpdt.internal.core.INamingRequestor; import net.sourceforge.phpdt.internal.core.InternalNamingConventions; - /** * Provides methods for computing Java-specific names. *

          @@ -24,22 +23,25 @@ import net.sourceforge.phpdt.internal.core.InternalNamingConventions; * The possible options are : *

            *
          • CODEASSIST_FIELD_PREFIXES : Define the Prefixes for Field Name.
          • - *
          • CODEASSIST_STATIC_FIELD_PREFIXES : Define the Prefixes for Static Field Name.
          • + *
          • CODEASSIST_STATIC_FIELD_PREFIXES : Define the Prefixes for Static Field + * Name.
          • *
          • CODEASSIST_LOCAL_PREFIXES : Define the Prefixes for Local Variable Name.
          • *
          • CODEASSIST_ARGUMENT_PREFIXES : Define the Prefixes for Argument Name.
          • *
          • CODEASSIST_FIELD_SUFFIXES : Define the Suffixes for Field Name.
          • - *
          • CODEASSIST_STATIC_FIELD_SUFFIXES : Define the Suffixes for Static Field Name.
          • + *
          • CODEASSIST_STATIC_FIELD_SUFFIXES : Define the Suffixes for Static Field + * Name.
          • *
          • CODEASSIST_LOCAL_SUFFIXES : Define the Suffixes for Local Variable Name.
          • *
          • CODEASSIST_ARGUMENT_SUFFIXES : Define the Suffixes for Argument Name.
          • *
          *

          *

          - * For a complete description of the configurable options, see getDefaultOptions. - * For programmaticaly change these options, see JavaCore#setOptions(). + * For a complete description of the configurable options, see + * getDefaultOptions. For programmaticaly change these options, + * see JavaCore#setOptions(). *

          *

          - * This class provides static methods and constants only; it is not intended to be - * instantiated or subclassed by clients. + * This class provides static methods and constants only; it is not intended to + * be instantiated or subclassed by clients. *

          * * @see JavaCore#setOptions(java.util.Hashtable) @@ -48,132 +50,138 @@ import net.sourceforge.phpdt.internal.core.InternalNamingConventions; */ public final class NamingConventions { private static final char[] GETTER_BOOL_NAME = "is".toCharArray(); //$NON-NLS-1$ + private static final char[] GETTER_NAME = "get".toCharArray(); //$NON-NLS-1$ + private static final char[] SETTER_NAME = "set".toCharArray(); //$NON-NLS-1$ - + private static class NamingRequestor implements INamingRequestor { private final static int SIZE = 10; - + // for acceptNameWithPrefixAndSuffix private char[][] firstPrefixAndFirstSuffixResults = new char[SIZE][]; + private int firstPrefixAndFirstSuffixResultsCount = 0; + private char[][] firstPrefixAndSuffixResults = new char[SIZE][]; + private int firstPrefixAndSuffixResultsCount = 0; + private char[][] prefixAndFirstSuffixResults = new char[SIZE][]; + private int prefixAndFirstSuffixResultsCount = 0; + private char[][] prefixAndSuffixResults = new char[SIZE][]; + private int prefixAndSuffixResultsCount = 0; - + // for acceptNameWithPrefix private char[][] firstPrefixResults = new char[SIZE][]; + private int firstPrefixResultsCount = 0; + private char[][] prefixResults = new char[SIZE][]; + private int prefixResultsCount = 0; - + // for acceptNameWithSuffix private char[][] firstSuffixResults = new char[SIZE][]; + private int firstSuffixResultsCount = 0; + private char[][] suffixResults = new char[SIZE][]; + private int suffixResultsCount = 0; - + // for acceptNameWithoutPrefixAndSuffix private char[][] otherResults = new char[SIZE][]; + private int otherResultsCount = 0; - public void acceptNameWithPrefixAndSuffix(char[] name, boolean isFirstPrefix, boolean isFirstSuffix) { - if(isFirstPrefix && isFirstSuffix) { + + public void acceptNameWithPrefixAndSuffix(char[] name, + boolean isFirstPrefix, boolean isFirstSuffix) { + if (isFirstPrefix && isFirstSuffix) { int length = this.firstPrefixAndFirstSuffixResults.length; - if(length == this.firstPrefixAndFirstSuffixResultsCount) { - System.arraycopy( - this.firstPrefixAndFirstSuffixResults, - 0, - this.firstPrefixAndFirstSuffixResults = new char[length * 2][], - 0, - length); + if (length == this.firstPrefixAndFirstSuffixResultsCount) { + System + .arraycopy( + this.firstPrefixAndFirstSuffixResults, + 0, + this.firstPrefixAndFirstSuffixResults = new char[length * 2][], + 0, length); } - this.firstPrefixAndFirstSuffixResults[this.firstPrefixAndFirstSuffixResultsCount++] = name; + this.firstPrefixAndFirstSuffixResults[this.firstPrefixAndFirstSuffixResultsCount++] = name; } else if (isFirstPrefix) { int length = this.firstPrefixAndSuffixResults.length; - if(length == this.firstPrefixAndSuffixResultsCount) { - System.arraycopy( - this.firstPrefixAndSuffixResults, - 0, - this.firstPrefixAndSuffixResults = new char[length * 2][], - 0, - length); + if (length == this.firstPrefixAndSuffixResultsCount) { + System + .arraycopy( + this.firstPrefixAndSuffixResults, + 0, + this.firstPrefixAndSuffixResults = new char[length * 2][], + 0, length); } this.firstPrefixAndSuffixResults[this.firstPrefixAndSuffixResultsCount++] = name; - } else if(isFirstSuffix) { + } else if (isFirstSuffix) { int length = this.prefixAndFirstSuffixResults.length; - if(length == this.prefixAndFirstSuffixResultsCount) { - System.arraycopy( - this.prefixAndFirstSuffixResults, - 0, - this.prefixAndFirstSuffixResults = new char[length * 2][], - 0, - length); + if (length == this.prefixAndFirstSuffixResultsCount) { + System + .arraycopy( + this.prefixAndFirstSuffixResults, + 0, + this.prefixAndFirstSuffixResults = new char[length * 2][], + 0, length); } this.prefixAndFirstSuffixResults[this.prefixAndFirstSuffixResultsCount++] = name; } else { int length = this.prefixAndSuffixResults.length; - if(length == this.prefixAndSuffixResultsCount) { - System.arraycopy( - this.prefixAndSuffixResults, - 0, - this.prefixAndSuffixResults = new char[length * 2][], - 0, - length); + if (length == this.prefixAndSuffixResultsCount) { + System + .arraycopy( + this.prefixAndSuffixResults, + 0, + this.prefixAndSuffixResults = new char[length * 2][], + 0, length); } this.prefixAndSuffixResults[this.prefixAndSuffixResultsCount++] = name; } } public void acceptNameWithPrefix(char[] name, boolean isFirstPrefix) { - if(isFirstPrefix) { + if (isFirstPrefix) { int length = this.firstPrefixResults.length; - if(length == this.firstPrefixResultsCount) { - System.arraycopy( - this.firstPrefixResults, - 0, - this.firstPrefixResults = new char[length * 2][], - 0, - length); + if (length == this.firstPrefixResultsCount) { + System.arraycopy(this.firstPrefixResults, 0, + this.firstPrefixResults = new char[length * 2][], + 0, length); } this.firstPrefixResults[this.firstPrefixResultsCount++] = name; - } else{ + } else { int length = this.prefixResults.length; - if(length == this.prefixResultsCount) { - System.arraycopy( - this.prefixResults, - 0, - this.prefixResults = new char[length * 2][], - 0, - length); + if (length == this.prefixResultsCount) { + System.arraycopy(this.prefixResults, 0, + this.prefixResults = new char[length * 2][], 0, + length); } this.prefixResults[this.prefixResultsCount++] = name; } } public void acceptNameWithSuffix(char[] name, boolean isFirstSuffix) { - if(isFirstSuffix) { + if (isFirstSuffix) { int length = this.firstSuffixResults.length; - if(length == this.firstSuffixResultsCount) { - System.arraycopy( - this.firstSuffixResults, - 0, - this.firstSuffixResults = new char[length * 2][], - 0, - length); + if (length == this.firstSuffixResultsCount) { + System.arraycopy(this.firstSuffixResults, 0, + this.firstSuffixResults = new char[length * 2][], + 0, length); } this.firstSuffixResults[this.firstSuffixResultsCount++] = name; } else { int length = this.suffixResults.length; - if(length == this.suffixResultsCount) { - System.arraycopy( - this.suffixResults, - 0, - this.suffixResults = new char[length * 2][], - 0, - length); + if (length == this.suffixResultsCount) { + System.arraycopy(this.suffixResults, 0, + this.suffixResults = new char[length * 2][], 0, + length); } this.suffixResults[this.suffixResultsCount++] = name; } @@ -181,94 +189,104 @@ public final class NamingConventions { public void acceptNameWithoutPrefixAndSuffix(char[] name) { int length = this.otherResults.length; - if(length == this.otherResultsCount) { - System.arraycopy( - this.otherResults, - 0, - this.otherResults = new char[length * 2][], - 0, - length); + if (length == this.otherResultsCount) { + System.arraycopy(this.otherResults, 0, + this.otherResults = new char[length * 2][], 0, length); } this.otherResults[this.otherResultsCount++] = name; } - public char[][] getResults(){ - int count = - this.firstPrefixAndFirstSuffixResultsCount - + this.firstPrefixAndSuffixResultsCount - + this.prefixAndFirstSuffixResultsCount - + this.prefixAndSuffixResultsCount - + this.firstPrefixResultsCount - + this.prefixResultsCount - + this.firstSuffixResultsCount - + this.suffixResultsCount - + this.otherResultsCount; - + + public char[][] getResults() { + int count = this.firstPrefixAndFirstSuffixResultsCount + + this.firstPrefixAndSuffixResultsCount + + this.prefixAndFirstSuffixResultsCount + + this.prefixAndSuffixResultsCount + + this.firstPrefixResultsCount + this.prefixResultsCount + + this.firstSuffixResultsCount + this.suffixResultsCount + + this.otherResultsCount; + char[][] results = new char[count][]; - + int index = 0; - System.arraycopy(this.firstPrefixAndFirstSuffixResults, 0, results, index, this.firstPrefixAndFirstSuffixResultsCount); + System.arraycopy(this.firstPrefixAndFirstSuffixResults, 0, results, + index, this.firstPrefixAndFirstSuffixResultsCount); index += this.firstPrefixAndFirstSuffixResultsCount; - System.arraycopy(this.firstPrefixAndSuffixResults, 0, results, index, this.firstPrefixAndSuffixResultsCount); + System.arraycopy(this.firstPrefixAndSuffixResults, 0, results, + index, this.firstPrefixAndSuffixResultsCount); index += this.firstPrefixAndSuffixResultsCount; - System.arraycopy(this.prefixAndFirstSuffixResults, 0, results, index, this.prefixAndFirstSuffixResultsCount); - index += this.prefixAndFirstSuffixResultsCount; - System.arraycopy(this.prefixAndSuffixResults, 0, results, index, this.prefixAndSuffixResultsCount); + System.arraycopy(this.prefixAndFirstSuffixResults, 0, results, + index, this.prefixAndFirstSuffixResultsCount); + index += this.prefixAndFirstSuffixResultsCount; + System.arraycopy(this.prefixAndSuffixResults, 0, results, index, + this.prefixAndSuffixResultsCount); index += this.prefixAndSuffixResultsCount; - System.arraycopy(this.firstPrefixResults, 0, results, index, this.firstPrefixResultsCount); + System.arraycopy(this.firstPrefixResults, 0, results, index, + this.firstPrefixResultsCount); index += this.firstPrefixResultsCount; - System.arraycopy(this.prefixResults, 0, results, index, this.prefixResultsCount); + System.arraycopy(this.prefixResults, 0, results, index, + this.prefixResultsCount); index += this.prefixResultsCount; - System.arraycopy(this.firstSuffixResults, 0, results, index, this.firstSuffixResultsCount); + System.arraycopy(this.firstSuffixResults, 0, results, index, + this.firstSuffixResultsCount); index += this.firstSuffixResultsCount; - System.arraycopy(this.suffixResults, 0, results, index, this.suffixResultsCount); + System.arraycopy(this.suffixResults, 0, results, index, + this.suffixResultsCount); index += this.suffixResultsCount; - System.arraycopy(this.otherResults, 0, results, index, this.otherResultsCount); - + System.arraycopy(this.otherResults, 0, results, index, + this.otherResultsCount); + return results; } } - private NamingConventions() { // Not instantiable } - private static char[] removePrefixAndSuffix(char[] name, char[][] prefixes, char[][] suffixes) { + private static char[] removePrefixAndSuffix(char[] name, char[][] prefixes, + char[][] suffixes) { // remove longer prefix char[] withoutPrefixName = name; if (prefixes != null) { int bestLength = 0; - for (int i= 0; i < prefixes.length; i++) { + for (int i = 0; i < prefixes.length; i++) { char[] prefix = prefixes[i]; if (CharOperation.prefixEquals(prefix, name)) { int currLen = prefix.length; - boolean lastCharIsLetter = Character.isLetter(prefix[currLen - 1]); - if(!lastCharIsLetter || (lastCharIsLetter && name.length > currLen && Character.isUpperCase(name[currLen]))) { + boolean lastCharIsLetter = Character + .isLetter(prefix[currLen - 1]); + if (!lastCharIsLetter + || (lastCharIsLetter && name.length > currLen && Character + .isUpperCase(name[currLen]))) { if (bestLength < currLen && name.length != currLen) { - withoutPrefixName = CharOperation.subarray(name, currLen, name.length); + withoutPrefixName = CharOperation.subarray(name, + currLen, name.length); bestLength = currLen; } } } } } - + // remove longer suffix char[] withoutSuffixName = withoutPrefixName; - if(suffixes != null) { + if (suffixes != null) { int bestLength = 0; for (int i = 0; i < suffixes.length; i++) { char[] suffix = suffixes[i]; - if(CharOperation.endsWith(withoutPrefixName, suffix)) { + if (CharOperation.endsWith(withoutPrefixName, suffix)) { int currLen = suffix.length; - if(bestLength < currLen && withoutPrefixName.length != currLen) { - withoutSuffixName = CharOperation.subarray(withoutPrefixName, 0, withoutPrefixName.length - currLen); + if (bestLength < currLen + && withoutPrefixName.length != currLen) { + withoutSuffixName = CharOperation.subarray( + withoutPrefixName, 0, withoutPrefixName.length + - currLen); bestLength = currLen; } } } } - + withoutSuffixName[0] = Character.toLowerCase(withoutSuffixName[0]); return withoutSuffixName; } @@ -276,521 +294,615 @@ public final class NamingConventions { /** * Remove prefix and suffix from an argument name. *

          - * If argument name prefix is pre and argument name suffix is suf - * then for an argument named preArgsuf the result of this method is arg. - * If there is no prefix or suffix defined in JavaCore options the result is the unchanged - * name preArgsuf. + * If argument name prefix is pre and argument name suffix is + * suf then for an argument named preArgsuf + * the result of this method is arg. If there is no prefix + * or suffix defined in JavaCore options the result is the unchanged name + * preArgsuf. *

          *

          - * This method is affected by the following JavaCore options : CODEASSIST_ARGUMENT_PREFIXES and - * CODEASSIST_ARGUMENT_SUFFIXES. + * This method is affected by the following JavaCore options : + * CODEASSIST_ARGUMENT_PREFIXES and CODEASSIST_ARGUMENT_SUFFIXES. *

          *

          - * For a complete description of these configurable options, see getDefaultOptions. - * For programmaticaly change these options, see JavaCore#setOptions(). + * For a complete description of these configurable options, see + * getDefaultOptions. For programmaticaly change these + * options, see JavaCore#setOptions(). *

          - * - * @param javaProject project which contains the argument. - * @param argumentName argument's name. + * + * @param javaProject + * project which contains the argument. + * @param argumentName + * argument's name. * @return char[] the name without prefix and suffix. * @see JavaCore#setOptions(java.util.Hashtable) * @see JavaCore#getDefaultOptions() */ - public static char[] removePrefixAndSuffixForArgumentName(IJavaProject javaProject, char[] argumentName) { - AssistOptions assistOptions = new AssistOptions(javaProject.getOptions(true)); - return removePrefixAndSuffix( - argumentName, - assistOptions.argumentPrefixes, - assistOptions.argumentSuffixes); + public static char[] removePrefixAndSuffixForArgumentName( + IJavaProject javaProject, char[] argumentName) { + AssistOptions assistOptions = new AssistOptions(javaProject + .getOptions(true)); + return removePrefixAndSuffix(argumentName, + assistOptions.argumentPrefixes, assistOptions.argumentSuffixes); } - + /** * Remove prefix and suffix from an argument name. *

          - * If argument name prefix is pre and argument name suffix is suf - * then for an argument named preArgsuf the result of this method is arg. - * If there is no prefix or suffix defined in JavaCore options the result is the unchanged - * name preArgsuf. + * If argument name prefix is pre and argument name suffix is + * suf then for an argument named preArgsuf + * the result of this method is arg. If there is no prefix + * or suffix defined in JavaCore options the result is the unchanged name + * preArgsuf. *

          *

          - * This method is affected by the following JavaCore options : CODEASSIST_ARGUMENT_PREFIXES and - * CODEASSIST_ARGUMENT_SUFFIXES. + * This method is affected by the following JavaCore options : + * CODEASSIST_ARGUMENT_PREFIXES and CODEASSIST_ARGUMENT_SUFFIXES. *

          *

          - * For a complete description of these configurable options, see getDefaultOptions. - * For programmaticaly change these options, see JavaCore#setOptions(). + * For a complete description of these configurable options, see + * getDefaultOptions. For programmaticaly change these + * options, see JavaCore#setOptions(). *

          - * - * @param javaProject project which contains the argument. - * @param argumentName argument's name. + * + * @param javaProject + * project which contains the argument. + * @param argumentName + * argument's name. * @return char[] the name without prefix and suffix. * @see JavaCore#setOptions(java.util.Hashtable) * @see JavaCore#getDefaultOptions() */ - public static String removePrefixAndSuffixForArgumentName(IJavaProject javaProject, String argumentName) { - return String.valueOf(removePrefixAndSuffixForArgumentName(javaProject, argumentName.toCharArray())); + public static String removePrefixAndSuffixForArgumentName( + IJavaProject javaProject, String argumentName) { + return String.valueOf(removePrefixAndSuffixForArgumentName(javaProject, + argumentName.toCharArray())); } /** * Remove prefix and suffix from a field name. *

          - * If field name prefix is pre and field name suffix is suf - * then for a field named preFieldsuf the result of this method is field. - * If there is no prefix or suffix defined in JavaCore options the result is the unchanged - * name preFieldsuf. + * If field name prefix is pre and field name suffix is + * suf then for a field named preFieldsuf the + * result of this method is field. If there is no prefix or + * suffix defined in JavaCore options the result is the unchanged name + * preFieldsuf. *

          *

          - * This method is affected by the following JavaCore options : CODEASSIST_FIELD_PREFIXES, - * CODEASSIST_FIELD_SUFFIXES for instance field and CODEASSIST_STATIC_FIELD_PREFIXES, - * CODEASSIST_STATIC_FIELD_SUFFIXES for static field. + * This method is affected by the following JavaCore options : + * CODEASSIST_FIELD_PREFIXES, CODEASSIST_FIELD_SUFFIXES for instance field + * and CODEASSIST_STATIC_FIELD_PREFIXES, CODEASSIST_STATIC_FIELD_SUFFIXES + * for static field. *

          *

          - * For a complete description of these configurable options, see getDefaultOptions. - * For programmaticaly change these options, see JavaCore#setOptions(). + * For a complete description of these configurable options, see + * getDefaultOptions. For programmaticaly change these + * options, see JavaCore#setOptions(). *

          * - * @param javaProject project which contains the field. - * @param fieldName field's name. - * @param modifiers field's modifiers as defined by the class - * Flags. + * @param javaProject + * project which contains the field. + * @param fieldName + * field's name. + * @param modifiers + * field's modifiers as defined by the class Flags. * @return char[] the name without prefix and suffix. * @see Flags * @see JavaCore#setOptions(java.util.Hashtable) * @see JavaCore#getDefaultOptions() */ - public static char[] removePrefixAndSuffixForFieldName(IJavaProject javaProject, char[] fieldName, int modifiers) { + public static char[] removePrefixAndSuffixForFieldName( + IJavaProject javaProject, char[] fieldName, int modifiers) { boolean isStatic = Flags.isStatic(modifiers); - AssistOptions assistOptions = new AssistOptions(javaProject.getOptions(true)); - return removePrefixAndSuffix( - fieldName, - isStatic ? assistOptions.staticFieldPrefixes : assistOptions.fieldPrefixes, - isStatic ? assistOptions.staticFieldSuffixes : assistOptions.fieldSuffixes); + AssistOptions assistOptions = new AssistOptions(javaProject + .getOptions(true)); + return removePrefixAndSuffix(fieldName, + isStatic ? assistOptions.staticFieldPrefixes + : assistOptions.fieldPrefixes, + isStatic ? assistOptions.staticFieldSuffixes + : assistOptions.fieldSuffixes); } /** * Remove prefix and suffix from a field name. *

          - * If field name prefix is pre and field name suffix is suf - * then for a field named preFieldsuf the result of this method is field. - * If there is no prefix or suffix defined in JavaCore options the result is the unchanged - * name preFieldsuf. + * If field name prefix is pre and field name suffix is + * suf then for a field named preFieldsuf the + * result of this method is field. If there is no prefix or + * suffix defined in JavaCore options the result is the unchanged name + * preFieldsuf. *

          *

          - * This method is affected by the following JavaCore options : CODEASSIST_FIELD_PREFIXES, - * CODEASSIST_FIELD_SUFFIXES for instance field and CODEASSIST_STATIC_FIELD_PREFIXES, - * CODEASSIST_STATIC_FIELD_SUFFIXES for static field. + * This method is affected by the following JavaCore options : + * CODEASSIST_FIELD_PREFIXES, CODEASSIST_FIELD_SUFFIXES for instance field + * and CODEASSIST_STATIC_FIELD_PREFIXES, CODEASSIST_STATIC_FIELD_SUFFIXES + * for static field. *

          *

          - * For a complete description of these configurable options, see getDefaultOptions. - * For programmaticaly change these options, see JavaCore#setOptions(). + * For a complete description of these configurable options, see + * getDefaultOptions. For programmaticaly change these + * options, see JavaCore#setOptions(). *

          * - * @param javaProject project which contains the field. - * @param fieldName field's name. - * @param modifiers field's modifiers as defined by the class - * Flags. + * @param javaProject + * project which contains the field. + * @param fieldName + * field's name. + * @param modifiers + * field's modifiers as defined by the class Flags. * @return char[] the name without prefix and suffix. * @see Flags * @see JavaCore#setOptions(java.util.Hashtable) * @see JavaCore#getDefaultOptions() */ - public static String removePrefixAndSuffixForFieldName(IJavaProject javaProject, String fieldName, int modifiers) { - return String.valueOf(removePrefixAndSuffixForFieldName(javaProject, fieldName.toCharArray(), modifiers)); + public static String removePrefixAndSuffixForFieldName( + IJavaProject javaProject, String fieldName, int modifiers) { + return String.valueOf(removePrefixAndSuffixForFieldName(javaProject, + fieldName.toCharArray(), modifiers)); } + /** * Remove prefix and suffix from a local variable name. *

          - * If local variable name prefix is pre and local variable name suffix is suf - * then for a local variable named preLocalsuf the result of this method is local. - * If there is no prefix or suffix defined in JavaCore options the result is the unchanged - * name preLocalsuf. + * If local variable name prefix is pre and local variable + * name suffix is suf then for a local variable named + * preLocalsuf the result of this method is + * local. If there is no prefix or suffix defined in + * JavaCore options the result is the unchanged name + * preLocalsuf. *

          *

          - * This method is affected by the following JavaCore options : CODEASSIST_LOCAL_PREFIXES and - * CODEASSIST_LOCAL_SUFFIXES. + * This method is affected by the following JavaCore options : + * CODEASSIST_LOCAL_PREFIXES and CODEASSIST_LOCAL_SUFFIXES. *

          *

          - * For a complete description of these configurable options, see getDefaultOptions. - * For programmaticaly change these options, see JavaCore#setOptions(). + * For a complete description of these configurable options, see + * getDefaultOptions. For programmaticaly change these + * options, see JavaCore#setOptions(). *

          * - * @param javaProject project which contains the variable. - * @param localName variable's name. + * @param javaProject + * project which contains the variable. + * @param localName + * variable's name. * @return char[] the name without prefix and suffix. * @see JavaCore#setOptions(java.util.Hashtable) * @see JavaCore#getDefaultOptions() */ - public static char[] removePrefixAndSuffixForLocalVariableName(IJavaProject javaProject, char[] localName) { - AssistOptions assistOptions = new AssistOptions(javaProject.getOptions(true)); - return removePrefixAndSuffix( - localName, - assistOptions.argumentPrefixes, - assistOptions.argumentSuffixes); + public static char[] removePrefixAndSuffixForLocalVariableName( + IJavaProject javaProject, char[] localName) { + AssistOptions assistOptions = new AssistOptions(javaProject + .getOptions(true)); + return removePrefixAndSuffix(localName, assistOptions.argumentPrefixes, + assistOptions.argumentSuffixes); } - + /** * Remove prefix and suffix from a local variable name. *

          - * If local variable name prefix is pre and local variable name suffix is suf - * then for a local variable named preLocalsuf the result of this method is local. - * If there is no prefix or suffix defined in JavaCore options the result is the unchanged - * name preLocalsuf. + * If local variable name prefix is pre and local variable + * name suffix is suf then for a local variable named + * preLocalsuf the result of this method is + * local. If there is no prefix or suffix defined in + * JavaCore options the result is the unchanged name + * preLocalsuf. *

          *

          - * This method is affected by the following JavaCore options : CODEASSIST_LOCAL_PREFIXES and - * CODEASSIST_LOCAL_SUFFIXES. + * This method is affected by the following JavaCore options : + * CODEASSIST_LOCAL_PREFIXES and CODEASSIST_LOCAL_SUFFIXES. *

          *

          - * For a complete description of these configurable options, see getDefaultOptions. - * For programmaticaly change these options, see JavaCore#setOptions(). + * For a complete description of these configurable options, see + * getDefaultOptions. For programmaticaly change these + * options, see JavaCore#setOptions(). *

          * - * @param javaProject project which contains the variable. - * @param localName variable's name. + * @param javaProject + * project which contains the variable. + * @param localName + * variable's name. * @return char[] the name without prefix and suffix. * @see JavaCore#setOptions(java.util.Hashtable) * @see JavaCore#getDefaultOptions() */ - public static String removePrefixAndSuffixForLocalVariableName(IJavaProject javaProject, String localName) { - return String.valueOf(removePrefixAndSuffixForLocalVariableName(javaProject, localName.toCharArray())); + public static String removePrefixAndSuffixForLocalVariableName( + IJavaProject javaProject, String localName) { + return String.valueOf(removePrefixAndSuffixForLocalVariableName( + javaProject, localName.toCharArray())); } /** * Suggest names for an argument. The name is computed from argument's type * and possible prefixes or suffixes are added. *

          - * If the type of the argument is TypeName, the prefix for argument is pre - * and the suffix for argument is suf then the proposed names are preTypeNamesuf - * and preNamesuf. If there is no prefix or suffix the proposals are typeName - * and name. + * If the type of the argument is TypeName, the prefix for + * argument is pre and the suffix for argument is + * suf then the proposed names are + * preTypeNamesuf and preNamesuf. If there is + * no prefix or suffix the proposals are typeName and + * name. *

          *

          - * This method is affected by the following JavaCore options : CODEASSIST_ARGUMENT_PREFIXES and - * CODEASSIST_ARGUMENT_SUFFIXES. + * This method is affected by the following JavaCore options : + * CODEASSIST_ARGUMENT_PREFIXES and CODEASSIST_ARGUMENT_SUFFIXES. *

          *

          - * For a complete description of these configurable options, see getDefaultOptions. - * For programmaticaly change these options, see JavaCore#setOptions(). + * For a complete description of these configurable options, see + * getDefaultOptions. For programmaticaly change these + * options, see JavaCore#setOptions(). *

          * - * @param javaProject project which contains the argument. - * @param packageName package of the argument's type. - * @param qualifiedTypeName argument's type. - * @param dim argument's dimension (0 if the argument is not an array). - * @param excludedNames a list of names which cannot be suggested (already used names). - * Can be null if there is no excluded names. + * @param javaProject + * project which contains the argument. + * @param packageName + * package of the argument's type. + * @param qualifiedTypeName + * argument's type. + * @param dim + * argument's dimension (0 if the argument is not an array). + * @param excludedNames + * a list of names which cannot be suggested (already used + * names). Can be null if there is no excluded + * names. * @return char[][] an array of names. * @see JavaCore#setOptions(java.util.Hashtable) * @see JavaCore#getDefaultOptions() */ - public static char[][] suggestArgumentNames(IJavaProject javaProject, char[] packageName, char[] qualifiedTypeName, int dim, char[][] excludedNames) { + public static char[][] suggestArgumentNames(IJavaProject javaProject, + char[] packageName, char[] qualifiedTypeName, int dim, + char[][] excludedNames) { NamingRequestor requestor = new NamingRequestor(); - InternalNamingConventions.suggestArgumentNames( - javaProject, - packageName, - qualifiedTypeName, - dim, - excludedNames, - requestor); + InternalNamingConventions.suggestArgumentNames(javaProject, + packageName, qualifiedTypeName, dim, excludedNames, requestor); return requestor.getResults(); } - + /** * Suggest names for an argument. The name is computed from argument's type * and possible prefixes or suffixes are added. *

          - * If the type of the argument is TypeName, the prefix for argument is pre - * and the suffix for argument is suf then the proposed names are preTypeNamesuf - * and preNamesuf. If there is no prefix or suffix the proposals are typeName - * and name. + * If the type of the argument is TypeName, the prefix for + * argument is pre and the suffix for argument is + * suf then the proposed names are + * preTypeNamesuf and preNamesuf. If there is + * no prefix or suffix the proposals are typeName and + * name. *

          *

          - * This method is affected by the following JavaCore options : CODEASSIST_ARGUMENT_PREFIXES and - * CODEASSIST_ARGUMENT_SUFFIXES. + * This method is affected by the following JavaCore options : + * CODEASSIST_ARGUMENT_PREFIXES and CODEASSIST_ARGUMENT_SUFFIXES. *

          *

          - * For a complete description of these configurable options, see getDefaultOptions. - * For programmaticaly change these options, see JavaCore#setOptions(). + * For a complete description of these configurable options, see + * getDefaultOptions. For programmaticaly change these + * options, see JavaCore#setOptions(). *

          * - * @param javaProject project which contains the argument. - * @param packageName package of the argument's type. - * @param qualifiedTypeName argument's type. - * @param dim argument's dimension (0 if the argument is not an array). - * @param excludedNames a list of names which cannot be suggested (already used names). - * Can be null if there is no excluded names. + * @param javaProject + * project which contains the argument. + * @param packageName + * package of the argument's type. + * @param qualifiedTypeName + * argument's type. + * @param dim + * argument's dimension (0 if the argument is not an array). + * @param excludedNames + * a list of names which cannot be suggested (already used + * names). Can be null if there is no excluded + * names. * @return char[][] an array of names. * @see JavaCore#setOptions(java.util.Hashtable) * @see JavaCore#getDefaultOptions() */ - public static String[] suggestArgumentNames(IJavaProject javaProject, String packageName, String qualifiedTypeName, int dim, String[] excludedNames) { - return convertCharsToString( - suggestArgumentNames( - javaProject, - packageName.toCharArray(), - qualifiedTypeName.toCharArray(), - dim, - convertStringToChars(excludedNames))); + public static String[] suggestArgumentNames(IJavaProject javaProject, + String packageName, String qualifiedTypeName, int dim, + String[] excludedNames) { + return convertCharsToString(suggestArgumentNames(javaProject, + packageName.toCharArray(), qualifiedTypeName.toCharArray(), + dim, convertStringToChars(excludedNames))); } + /** - * Suggest names for a field. The name is computed from field's type - * and possible prefixes or suffixes are added. + * Suggest names for a field. The name is computed from field's type and + * possible prefixes or suffixes are added. *

          - * If the type of the field is TypeName, the prefix for field is pre - * and the suffix for field is suf then the proposed names are preTypeNamesuf - * and preNamesuf. If there is no prefix or suffix the proposals are typeName - * and name. + * If the type of the field is TypeName, the prefix for + * field is pre and the suffix for field is suf + * then the proposed names are preTypeNamesuf and + * preNamesuf. If there is no prefix or suffix the proposals + * are typeName and name. *

          *

          - * This method is affected by the following JavaCore options : CODEASSIST_FIELD_PREFIXES, - * CODEASSIST_FIELD_SUFFIXES and for instance field and CODEASSIST_STATIC_FIELD_PREFIXES, + * This method is affected by the following JavaCore options : + * CODEASSIST_FIELD_PREFIXES, CODEASSIST_FIELD_SUFFIXES and for instance + * field and CODEASSIST_STATIC_FIELD_PREFIXES, * CODEASSIST_STATIC_FIELD_SUFFIXES for static field. *

          *

          - * For a complete description of these configurable options, see getDefaultOptions. - * For programmaticaly change these options, see JavaCore#setOptions(). + * For a complete description of these configurable options, see + * getDefaultOptions. For programmaticaly change these + * options, see JavaCore#setOptions(). *

          * - * @param javaProject project which contains the field. - * @param packageName package of the field's type. - * @param qualifiedTypeName field's type. - * @param dim field's dimension (0 if the field is not an array). - * @param modifiers field's modifiers as defined by the class - * Flags. - * @param excludedNames a list of names which cannot be suggested (already used names). - * Can be null if there is no excluded names. + * @param javaProject + * project which contains the field. + * @param packageName + * package of the field's type. + * @param qualifiedTypeName + * field's type. + * @param dim + * field's dimension (0 if the field is not an array). + * @param modifiers + * field's modifiers as defined by the class Flags. + * @param excludedNames + * a list of names which cannot be suggested (already used + * names). Can be null if there is no excluded + * names. * @return char[][] an array of names. * @see Flags * @see JavaCore#setOptions(java.util.Hashtable) * @see JavaCore#getDefaultOptions() */ - public static char[][] suggestFieldNames(IJavaProject javaProject, char[] packageName, char[] qualifiedTypeName, int dim, int modifiers, char[][] excludedNames) { + public static char[][] suggestFieldNames(IJavaProject javaProject, + char[] packageName, char[] qualifiedTypeName, int dim, + int modifiers, char[][] excludedNames) { NamingRequestor requestor = new NamingRequestor(); - InternalNamingConventions.suggestFieldNames( - javaProject, - packageName, - qualifiedTypeName, - dim, - modifiers, - excludedNames, - requestor); + InternalNamingConventions.suggestFieldNames(javaProject, packageName, + qualifiedTypeName, dim, modifiers, excludedNames, requestor); return requestor.getResults(); } - + /** - * Suggest names for a field. The name is computed from field's type - * and possible prefixes or suffixes are added. + * Suggest names for a field. The name is computed from field's type and + * possible prefixes or suffixes are added. *

          - * If the type of the field is TypeName, the prefix for field is pre - * and the suffix for field is suf then the proposed names are preTypeNamesuf - * and preNamesuf. If there is no prefix or suffix the proposals are typeName - * and name. + * If the type of the field is TypeName, the prefix for + * field is pre and the suffix for field is suf + * then the proposed names are preTypeNamesuf and + * preNamesuf. If there is no prefix or suffix the proposals + * are typeName and name. *

          *

          - * This method is affected by the following JavaCore options : CODEASSIST_FIELD_PREFIXES, - * CODEASSIST_FIELD_SUFFIXES and for instance field and CODEASSIST_STATIC_FIELD_PREFIXES, + * This method is affected by the following JavaCore options : + * CODEASSIST_FIELD_PREFIXES, CODEASSIST_FIELD_SUFFIXES and for instance + * field and CODEASSIST_STATIC_FIELD_PREFIXES, * CODEASSIST_STATIC_FIELD_SUFFIXES for static field. *

          *

          - * For a complete description of these configurable options, see getDefaultOptions. - * For programmaticaly change these options, see JavaCore#setOptions(). + * For a complete description of these configurable options, see + * getDefaultOptions. For programmaticaly change these + * options, see JavaCore#setOptions(). *

          * - * @param javaProject project which contains the field. - * @param packageName package of the field's type. - * @param qualifiedTypeName field's type. - * @param dim field's dimension (0 if the field is not an array). - * @param modifiers field's modifiers as defined by the class - * Flags. - * @param excludedNames a list of names which cannot be suggested (already used names). - * Can be null if there is no excluded names. + * @param javaProject + * project which contains the field. + * @param packageName + * package of the field's type. + * @param qualifiedTypeName + * field's type. + * @param dim + * field's dimension (0 if the field is not an array). + * @param modifiers + * field's modifiers as defined by the class Flags. + * @param excludedNames + * a list of names which cannot be suggested (already used + * names). Can be null if there is no excluded + * names. * @return char[][] an array of names. * @see Flags * @see JavaCore#setOptions(java.util.Hashtable) * @see JavaCore#getDefaultOptions() */ - public static String[] suggestFieldNames(IJavaProject javaProject, String packageName, String qualifiedTypeName, int dim, int modifiers, String[] excludedNames) { - return convertCharsToString( - suggestFieldNames( - javaProject, - packageName.toCharArray(), - qualifiedTypeName.toCharArray(), - dim, - modifiers, - convertStringToChars(excludedNames))); + public static String[] suggestFieldNames(IJavaProject javaProject, + String packageName, String qualifiedTypeName, int dim, + int modifiers, String[] excludedNames) { + return convertCharsToString(suggestFieldNames(javaProject, packageName + .toCharArray(), qualifiedTypeName.toCharArray(), dim, + modifiers, convertStringToChars(excludedNames))); } - + /** - * Suggest names for a local variable. The name is computed from variable's type - * and possible prefixes or suffixes are added. + * Suggest names for a local variable. The name is computed from variable's + * type and possible prefixes or suffixes are added. *

          - * If the type of the local variable is TypeName, the prefix for local variable is pre - * and the suffix for local variable is suf then the proposed names are preTypeNamesuf - * and preNamesuf. If there is no prefix or suffix the proposals are typeName - * and name. + * If the type of the local variable is TypeName, the prefix + * for local variable is pre and the suffix for local + * variable is suf then the proposed names are + * preTypeNamesuf and preNamesuf. If there is + * no prefix or suffix the proposals are typeName and + * name. *

          *

          - * This method is affected by the following JavaCore options : CODEASSIST_LOCAL_PREFIXES and - * CODEASSIST_LOCAL_SUFFIXES. + * This method is affected by the following JavaCore options : + * CODEASSIST_LOCAL_PREFIXES and CODEASSIST_LOCAL_SUFFIXES. *

          *

          - * For a complete description of these configurable options, see getDefaultOptions. - * For programmaticaly change these options, see JavaCore#setOptions(). + * For a complete description of these configurable options, see + * getDefaultOptions. For programmaticaly change these + * options, see JavaCore#setOptions(). *

          * - * @param javaProject project which contains the variable. - * @param packageName package of the variable's type. - * @param qualifiedTypeName variable's type. - * @param dim variable's dimension (0 if the variable is not an array). - * @param excludedNames a list of names which cannot be suggested (already used names). - * Can be null if there is no excluded names. + * @param javaProject + * project which contains the variable. + * @param packageName + * package of the variable's type. + * @param qualifiedTypeName + * variable's type. + * @param dim + * variable's dimension (0 if the variable is not an array). + * @param excludedNames + * a list of names which cannot be suggested (already used + * names). Can be null if there is no excluded + * names. * @return char[][] an array of names. * @see JavaCore#setOptions(java.util.Hashtable) * @see JavaCore#getDefaultOptions() */ - public static char[][] suggestLocalVariableNames(IJavaProject javaProject, char[] packageName, char[] qualifiedTypeName, int dim, char[][] excludedNames) { + public static char[][] suggestLocalVariableNames(IJavaProject javaProject, + char[] packageName, char[] qualifiedTypeName, int dim, + char[][] excludedNames) { NamingRequestor requestor = new NamingRequestor(); - InternalNamingConventions.suggestLocalVariableNames( - javaProject, - packageName, - qualifiedTypeName, - dim, - excludedNames, - requestor); + InternalNamingConventions.suggestLocalVariableNames(javaProject, + packageName, qualifiedTypeName, dim, excludedNames, requestor); return requestor.getResults(); } - + /** - * Suggest names for a local variable. The name is computed from variable's type - * and possible prefixes or suffixes are added. + * Suggest names for a local variable. The name is computed from variable's + * type and possible prefixes or suffixes are added. *

          - * If the type of the local variable is TypeName, the prefix for local variable is pre - * and the suffix for local variable is suf then the proposed names are preTypeNamesuf - * and preNamesuf. If there is no prefix or suffix the proposals are typeName - * and name. + * If the type of the local variable is TypeName, the prefix + * for local variable is pre and the suffix for local + * variable is suf then the proposed names are + * preTypeNamesuf and preNamesuf. If there is + * no prefix or suffix the proposals are typeName and + * name. *

          *

          - * This method is affected by the following JavaCore options : CODEASSIST_LOCAL_PREFIXES and - * CODEASSIST_LOCAL_SUFFIXES. + * This method is affected by the following JavaCore options : + * CODEASSIST_LOCAL_PREFIXES and CODEASSIST_LOCAL_SUFFIXES. *

          *

          - * For a complete description of these configurable options, see getDefaultOptions. - * For programmaticaly change these options, see JavaCore#setOptions(). + * For a complete description of these configurable options, see + * getDefaultOptions. For programmaticaly change these + * options, see JavaCore#setOptions(). *

          * - * @param javaProject project which contains the variable. - * @param packageName package of the variable's type. - * @param qualifiedTypeName variable's type. - * @param dim variable's dimension (0 if the variable is not an array). - * @param excludedNames a list of names which cannot be suggested (already used names). - * Can be null if there is no excluded names. + * @param javaProject + * project which contains the variable. + * @param packageName + * package of the variable's type. + * @param qualifiedTypeName + * variable's type. + * @param dim + * variable's dimension (0 if the variable is not an array). + * @param excludedNames + * a list of names which cannot be suggested (already used + * names). Can be null if there is no excluded + * names. * @return char[][] an array of names. * @see JavaCore#setOptions(java.util.Hashtable) * @see JavaCore#getDefaultOptions() */ - public static String[] suggestLocalVariableNames(IJavaProject javaProject, String packageName, String qualifiedTypeName, int dim, String[] excludedNames) { - return convertCharsToString( - suggestLocalVariableNames( - javaProject, - packageName.toCharArray(), - qualifiedTypeName.toCharArray(), - dim, - convertStringToChars(excludedNames))); + public static String[] suggestLocalVariableNames(IJavaProject javaProject, + String packageName, String qualifiedTypeName, int dim, + String[] excludedNames) { + return convertCharsToString(suggestLocalVariableNames(javaProject, + packageName.toCharArray(), qualifiedTypeName.toCharArray(), + dim, convertStringToChars(excludedNames))); } - + /** * Suggest name for a getter method. The name is computed from field's name * and possible prefixes or suffixes are removed. *

          - * If the field name is preFieldNamesuf and the prefix for field is pre and - * the suffix for field is suf then the prosposed name is isFieldName for boolean field or - * getFieldName for others. If there is no prefix and suffix the proposal is isPreFieldNamesuf - * for boolean field or getPreFieldNamesuf for others. + * If the field name is preFieldNamesuf and the prefix for + * field is pre and the suffix for field is suf + * then the prosposed name is isFieldName for boolean field + * or getFieldName for others. If there is no prefix and + * suffix the proposal is isPreFieldNamesuf for boolean field + * or getPreFieldNamesuf for others. *

          *

          - * This method is affected by the following JavaCore options : CODEASSIST_FIELD_PREFIXES, - * CODEASSIST_FIELD_SUFFIXES for instance field and CODEASSIST_STATIC_FIELD_PREFIXES, - * CODEASSIST_STATIC_FIELD_SUFFIXES for static field. + * This method is affected by the following JavaCore options : + * CODEASSIST_FIELD_PREFIXES, CODEASSIST_FIELD_SUFFIXES for instance field + * and CODEASSIST_STATIC_FIELD_PREFIXES, CODEASSIST_STATIC_FIELD_SUFFIXES + * for static field. *

          *

          - * For a complete description of these configurable options, see getDefaultOptions. - * For programmaticaly change these options, see JavaCore#setOptions(). + * For a complete description of these configurable options, see + * getDefaultOptions. For programmaticaly change these + * options, see JavaCore#setOptions(). *

          * - * @param project project which contains the field. - * @param fieldName field's name's. - * @param modifiers field's modifiers as defined by the class - * Flags. - * @param isBoolean true if the field's type is boolean - * @param excludedNames a list of names which cannot be suggested (already used names). - * Can be null if there is no excluded names. + * @param project + * project which contains the field. + * @param fieldName + * field's name's. + * @param modifiers + * field's modifiers as defined by the class Flags. + * @param isBoolean + * true if the field's type is boolean + * @param excludedNames + * a list of names which cannot be suggested (already used + * names). Can be null if there is no excluded + * names. * @return char[] a name. * @see Flags * @see JavaCore#setOptions(java.util.Hashtable) * @see JavaCore#getDefaultOptions() */ - public static char[] suggestGetterName(IJavaProject project, char[] fieldName, int modifiers, boolean isBoolean, char[][] excludedNames) { + public static char[] suggestGetterName(IJavaProject project, + char[] fieldName, int modifiers, boolean isBoolean, + char[][] excludedNames) { if (isBoolean) { - char[] name = removePrefixAndSuffixForFieldName(project, fieldName, modifiers); - int prefixLen = GETTER_BOOL_NAME.length; - if (CharOperation.prefixEquals(GETTER_BOOL_NAME, name) - && name.length > prefixLen && Character.isUpperCase(name[prefixLen])) { + char[] name = removePrefixAndSuffixForFieldName(project, fieldName, + modifiers); + int prefixLen = GETTER_BOOL_NAME.length; + if (CharOperation.prefixEquals(GETTER_BOOL_NAME, name) + && name.length > prefixLen + && Character.isUpperCase(name[prefixLen])) { return suggestNewName(name, excludedNames); } else { - return suggestNewName( - CharOperation.concat(GETTER_BOOL_NAME, suggestAccessorName(project, fieldName, modifiers)), - excludedNames - ); + return suggestNewName(CharOperation.concat(GETTER_BOOL_NAME, + suggestAccessorName(project, fieldName, modifiers)), + excludedNames); } } else { - return suggestNewName( - CharOperation.concat(GETTER_NAME, suggestAccessorName(project, fieldName, modifiers)), - excludedNames - ); + return suggestNewName(CharOperation.concat(GETTER_NAME, + suggestAccessorName(project, fieldName, modifiers)), + excludedNames); } } - + /** * Suggest name for a getter method. The name is computed from field's name * and possible prefixes or suffixes are removed. *

          - * If the field name is preFieldNamesuf and the prefix for field is pre and - * the suffix for field is suf then the prosposed name is isFieldName for boolean field or - * getFieldName for others. If there is no prefix and suffix the proposal is isPreFieldNamesuf - * for boolean field or getPreFieldNamesuf for others. + * If the field name is preFieldNamesuf and the prefix for + * field is pre and the suffix for field is suf + * then the prosposed name is isFieldName for boolean field + * or getFieldName for others. If there is no prefix and + * suffix the proposal is isPreFieldNamesuf for boolean field + * or getPreFieldNamesuf for others. *

          *

          - * This method is affected by the following JavaCore options : CODEASSIST_FIELD_PREFIXES, - * CODEASSIST_FIELD_SUFFIXES for instance field and CODEASSIST_STATIC_FIELD_PREFIXES, - * CODEASSIST_STATIC_FIELD_SUFFIXES for static field. + * This method is affected by the following JavaCore options : + * CODEASSIST_FIELD_PREFIXES, CODEASSIST_FIELD_SUFFIXES for instance field + * and CODEASSIST_STATIC_FIELD_PREFIXES, CODEASSIST_STATIC_FIELD_SUFFIXES + * for static field. *

          *

          - * For a complete description of these configurable options, see getDefaultOptions. - * For programmaticaly change these options, see JavaCore#setOptions(). + * For a complete description of these configurable options, see + * getDefaultOptions. For programmaticaly change these + * options, see JavaCore#setOptions(). *

          * - * @param project project which contains the field. - * @param fieldName field's name's. - * @param modifiers field's modifiers as defined by the class - * Flags. - * @param isBoolean true if the field's type is boolean - * @param excludedNames a list of names which cannot be suggested (already used names). - * Can be null if there is no excluded names. + * @param project + * project which contains the field. + * @param fieldName + * field's name's. + * @param modifiers + * field's modifiers as defined by the class Flags. + * @param isBoolean + * true if the field's type is boolean + * @param excludedNames + * a list of names which cannot be suggested (already used + * names). Can be null if there is no excluded + * names. * @return char[] a name. * @see Flags * @see JavaCore#setOptions(java.util.Hashtable) * @see JavaCore#getDefaultOptions() */ - public static String suggestGetterName(IJavaProject project, String fieldName, int modifiers, boolean isBoolean, String[] excludedNames) { - return String.valueOf( - suggestGetterName( - project, - fieldName.toCharArray(), - modifiers, - isBoolean, + public static String suggestGetterName(IJavaProject project, + String fieldName, int modifiers, boolean isBoolean, + String[] excludedNames) { + return String.valueOf(suggestGetterName(project, fieldName + .toCharArray(), modifiers, isBoolean, convertStringToChars(excludedNames))); } @@ -798,117 +910,135 @@ public final class NamingConventions { * Suggest name for a setter method. The name is computed from field's name * and possible prefixes or suffixes are removed. *

          - * If the field name is preFieldNamesuf and the prefix for field is pre and - * the suffix for field is suf then the proposed name is setFieldName. - * If there is no prefix and suffix the proposal is setPreFieldNamesuf. + * If the field name is preFieldNamesuf and the prefix for + * field is pre and the suffix for field is suf + * then the proposed name is setFieldName. If there is no + * prefix and suffix the proposal is setPreFieldNamesuf. *

          *

          - * This method is affected by the following JavaCore options : CODEASSIST_FIELD_PREFIXES, - * CODEASSIST_FIELD_SUFFIXES for instance field and CODEASSIST_STATIC_FIELD_PREFIXES, - * CODEASSIST_STATIC_FIELD_SUFFIXES for static field. + * This method is affected by the following JavaCore options : + * CODEASSIST_FIELD_PREFIXES, CODEASSIST_FIELD_SUFFIXES for instance field + * and CODEASSIST_STATIC_FIELD_PREFIXES, CODEASSIST_STATIC_FIELD_SUFFIXES + * for static field. *

          *

          - * For a complete description of these configurable options, see getDefaultOptions. - * For programmaticaly change these options, see JavaCore#setOptions(). + * For a complete description of these configurable options, see + * getDefaultOptions. For programmaticaly change these + * options, see JavaCore#setOptions(). *

          * - * @param project project which contains the field. - * @param fieldName field's name's. - * @param modifiers field's modifiers as defined by the class - * Flags. - * @param isBoolean true if the field's type is boolean - * @param excludedNames a list of names which cannot be suggested (already used names). - * Can be null if there is no excluded names. + * @param project + * project which contains the field. + * @param fieldName + * field's name's. + * @param modifiers + * field's modifiers as defined by the class Flags. + * @param isBoolean + * true if the field's type is boolean + * @param excludedNames + * a list of names which cannot be suggested (already used + * names). Can be null if there is no excluded + * names. * @return char[] a name. * @see Flags * @see JavaCore#setOptions(java.util.Hashtable) * @see JavaCore#getDefaultOptions() */ - public static char[] suggestSetterName(IJavaProject project, char[] fieldName, int modifiers, boolean isBoolean, char[][] excludedNames) { + public static char[] suggestSetterName(IJavaProject project, + char[] fieldName, int modifiers, boolean isBoolean, + char[][] excludedNames) { if (isBoolean) { - char[] name = removePrefixAndSuffixForFieldName(project, fieldName, modifiers); - int prefixLen = GETTER_BOOL_NAME.length; - if (CharOperation.prefixEquals(GETTER_BOOL_NAME, name) - && name.length > prefixLen && Character.isUpperCase(name[prefixLen])) { + char[] name = removePrefixAndSuffixForFieldName(project, fieldName, + modifiers); + int prefixLen = GETTER_BOOL_NAME.length; + if (CharOperation.prefixEquals(GETTER_BOOL_NAME, name) + && name.length > prefixLen + && Character.isUpperCase(name[prefixLen])) { name = CharOperation.subarray(name, prefixLen, name.length); - return suggestNewName( - CharOperation.concat(SETTER_NAME, suggestAccessorName(project, name, modifiers)), - excludedNames - ); + return suggestNewName(CharOperation.concat(SETTER_NAME, + suggestAccessorName(project, name, modifiers)), + excludedNames); } else { - return suggestNewName( - CharOperation.concat(SETTER_NAME, suggestAccessorName(project, fieldName, modifiers)), - excludedNames - ); + return suggestNewName(CharOperation.concat(SETTER_NAME, + suggestAccessorName(project, fieldName, modifiers)), + excludedNames); } } else { - return suggestNewName( - CharOperation.concat(SETTER_NAME, suggestAccessorName(project, fieldName, modifiers)), - excludedNames - ); + return suggestNewName(CharOperation.concat(SETTER_NAME, + suggestAccessorName(project, fieldName, modifiers)), + excludedNames); } } - + /** * Suggest name for a setter method. The name is computed from field's name * and possible prefixes or suffixes are removed. *

          - * If the field name is preFieldNamesuf and the prefix for field is pre and - * the suffix for field is suf then the proposed name is setFieldName. - * If there is no prefix and suffix the proposal is setPreFieldNamesuf. + * If the field name is preFieldNamesuf and the prefix for + * field is pre and the suffix for field is suf + * then the proposed name is setFieldName. If there is no + * prefix and suffix the proposal is setPreFieldNamesuf. *

          *

          - * This method is affected by the following JavaCore options : CODEASSIST_FIELD_PREFIXES, - * CODEASSIST_FIELD_SUFFIXES for instance field and CODEASSIST_STATIC_FIELD_PREFIXES, - * CODEASSIST_STATIC_FIELD_SUFFIXES for static field. + * This method is affected by the following JavaCore options : + * CODEASSIST_FIELD_PREFIXES, CODEASSIST_FIELD_SUFFIXES for instance field + * and CODEASSIST_STATIC_FIELD_PREFIXES, CODEASSIST_STATIC_FIELD_SUFFIXES + * for static field. *

          *

          - * For a complete description of these configurable options, see getDefaultOptions. - * For programmaticaly change these options, see JavaCore#setOptions(). + * For a complete description of these configurable options, see + * getDefaultOptions. For programmaticaly change these + * options, see JavaCore#setOptions(). *

          * - * @param project project which contains the field. - * @param fieldName field's name's. - * @param modifiers field's modifiers as defined by the class - * Flags. - * @param isBoolean true if the field's type is boolean - * @param excludedNames a list of names which cannot be suggested (already used names). - * Can be null if there is no excluded names. + * @param project + * project which contains the field. + * @param fieldName + * field's name's. + * @param modifiers + * field's modifiers as defined by the class Flags. + * @param isBoolean + * true if the field's type is boolean + * @param excludedNames + * a list of names which cannot be suggested (already used + * names). Can be null if there is no excluded + * names. * @return char[] a name. * @see Flags * @see JavaCore#setOptions(java.util.Hashtable) * @see JavaCore#getDefaultOptions() */ - public static String suggestSetterName(IJavaProject project, String fieldName, int modifiers, boolean isBoolean, String[] excludedNames) { - return String.valueOf( - suggestSetterName( - project, - fieldName.toCharArray(), - modifiers, - isBoolean, + public static String suggestSetterName(IJavaProject project, + String fieldName, int modifiers, boolean isBoolean, + String[] excludedNames) { + return String.valueOf(suggestSetterName(project, fieldName + .toCharArray(), modifiers, isBoolean, convertStringToChars(excludedNames))); } - - private static char[] suggestAccessorName(IJavaProject project, char[] fieldName, int modifiers) { - char[] name = removePrefixAndSuffixForFieldName(project, fieldName, modifiers); + + private static char[] suggestAccessorName(IJavaProject project, + char[] fieldName, int modifiers) { + char[] name = removePrefixAndSuffixForFieldName(project, fieldName, + modifiers); if (name.length > 0 && Character.isLowerCase(name[0])) { name[0] = Character.toUpperCase(name[0]); } return name; } - - private static char[] suggestNewName(char[] name, char[][] excludedNames){ - if(excludedNames == null) { + + private static char[] suggestNewName(char[] name, char[][] excludedNames) { + if (excludedNames == null) { return name; } - + char[] newName = name; int count = 2; int i = 0; while (i < excludedNames.length) { - if(CharOperation.equals(newName, excludedNames[i], false)) { - newName = CharOperation.concat(name, String.valueOf(count++).toCharArray()); + if (CharOperation.equals(newName, excludedNames[i], false)) { + newName = CharOperation.concat(name, String.valueOf(count++) + .toCharArray()); i = 0; } else { i++; @@ -916,7 +1046,7 @@ public final class NamingConventions { } return newName; } - + private static String[] convertCharsToString(char[][] c) { int length = c == null ? 0 : c.length; String[] s = new String[length]; @@ -925,12 +1055,12 @@ public final class NamingConventions { } return s; } - + private static char[][] convertStringToChars(String[] s) { int length = s == null ? 0 : s.length; char[][] c = new char[length][]; for (int i = 0; i < length; i++) { - if(s[i] == null) { + if (s[i] == null) { c[i] = CharOperation.NO_CHAR; } else { c[i] = s[i].toCharArray(); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/Signature.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/Signature.java index de4c360..c9f8da2 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/Signature.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/Signature.java @@ -16,50 +16,58 @@ import net.sourceforge.phpdt.core.compiler.CharOperation; * Provides methods for encoding and decoding type and method signature strings. *

          * The syntax for a type signature is: + * *

          - * typeSignature ::=
          - *     "B"  // byte
          - *   | "C"  // char
          - *   | "D"  // double
          - *   | "F"  // float
          - *   | "I"  // int
          - *   | "J"  // long
          - *   | "S"  // short
          - *   | "V"  // void
          - *   | "Z"  // boolean
          - *   | "L" + binaryTypeName + ";"  // resolved named type (in compiled code)
          - *   | "Q" + sourceTypeName + ";"  // unresolved named type (in source code)
          - *   | "[" + typeSignature  // array of type denoted by typeSignature
          + *  typeSignature ::=
          + *      "B"  // byte
          + *    | "C"  // char
          + *    | "D"  // double
          + *    | "F"  // float
          + *    | "I"  // int
          + *    | "J"  // long
          + *    | "S"  // short
          + *    | "V"  // void
          + *    | "Z"  // boolean
          + *    | "L" + binaryTypeName + ";"  // resolved named type (in compiled code)
          + *    | "Q" + sourceTypeName + ";"  // unresolved named type (in source code)
          + *    | "[" + typeSignature  // array of type denoted by typeSignature
            * 
          + * *

          *

          * Examples: *

            - *
          • "[[I" denotes int[][]
          • - *
          • "Ljava.lang.String;" denotes java.lang.String in compiled code
          • - *
          • "QString" denotes String in source code
          • - *
          • "Qjava.lang.String" denotes java.lang.String in source code
          • - *
          • "[QString" denotes String[] in source code
          • + *
          • "[[I" denotes int[][]
          • + *
          • "Ljava.lang.String;" denotes + * java.lang.String in compiled code
          • + *
          • "QString" denotes String in source code
          • + *
          • "Qjava.lang.String" denotes java.lang.String + * in source code
          • + *
          • "[QString" denotes String[] in source code
          • *
          *

          *

          * The syntax for a method signature is: + * *

          - * methodSignature ::= "(" + paramTypeSignature* + ")" + returnTypeSignature
          - * paramTypeSignature ::= typeSignature
          - * returnTypeSignature ::= typeSignature
          + *  methodSignature ::= "(" + paramTypeSignature* + ")" + returnTypeSignature
          + *  paramTypeSignature ::= typeSignature
          + *  returnTypeSignature ::= typeSignature
            * 
          + * *

          * Examples: *

            - *
          • "()I" denotes int foo()
          • - *
          • "([Ljava.lang.String;)V" denotes void foo(java.lang.String[]) in compiled code
          • - *
          • "(QString;)QObject;" denotes Object foo(String) in source code
          • + *
          • "()I" denotes int foo()
          • + *
          • "([Ljava.lang.String;)V" denotes + * void foo(java.lang.String[]) in compiled code
          • + *
          • "(QString;)QObject;" denotes + * Object foo(String) in source code
          • *
          *

          *

          - * This class provides static methods and constants only; it is not intended to be - * instantiated or subclassed by clients. + * This class provides static methods and constants only; it is not intended to + * be instantiated or subclassed by clients. *

          */ public final class Signature { @@ -68,1069 +76,1221 @@ public final class Signature { * Character constant indicating the primitive type boolean in a signature. * Value is 'Z'. */ - public static final char C_BOOLEAN = 'Z'; + public static final char C_BOOLEAN = 'Z'; /** * Character constant indicating the primitive type byte in a signature. * Value is 'B'. */ - public static final char C_BYTE = 'B'; + public static final char C_BYTE = 'B'; /** * Character constant indicating the primitive type char in a signature. * Value is 'C'. */ - public static final char C_CHAR = 'C'; + public static final char C_CHAR = 'C'; /** * Character constant indicating the primitive type double in a signature. * Value is 'D'. */ - public static final char C_DOUBLE = 'D'; + public static final char C_DOUBLE = 'D'; /** * Character constant indicating the primitive type float in a signature. * Value is 'F'. */ - public static final char C_FLOAT = 'F'; + public static final char C_FLOAT = 'F'; /** * Character constant indicating the primitive type int in a signature. * Value is 'I'. */ - public static final char C_INT = 'I'; - + public static final char C_INT = 'I'; + /** - * Character constant indicating the semicolon in a signature. - * Value is ';'. + * Character constant indicating the semicolon in a signature. Value is + * ';'. */ - public static final char C_SEMICOLON = ';'; + public static final char C_SEMICOLON = ';'; /** * Character constant indicating the primitive type long in a signature. * Value is 'J'. */ - public static final char C_LONG = 'J'; - + public static final char C_LONG = 'J'; + /** * Character constant indicating the primitive type short in a signature. * Value is 'S'. */ - public static final char C_SHORT = 'S'; - + public static final char C_SHORT = 'S'; + /** - * Character constant indicating result type void in a signature. - * Value is 'V'. + * Character constant indicating result type void in a signature. Value is + * 'V'. */ - public static final char C_VOID = 'V'; - - /** - * Character constant indicating the dot in a signature. - * Value is '.'. + public static final char C_VOID = 'V'; + + /** + * Character constant indicating the dot in a signature. Value is + * '.'. */ - public static final char C_DOT = '.'; - - /** - * Character constant indicating the dollar in a signature. - * Value is '$'. + public static final char C_DOT = '.'; + + /** + * Character constant indicating the dollar in a signature. Value is + * '$'. */ - public static final char C_DOLLAR = '$'; + public static final char C_DOLLAR = '$'; - /** - * Character constant indicating an array type in a signature. - * Value is '['. + /** + * Character constant indicating an array type in a signature. Value is + * '['. */ - public static final char C_ARRAY = '['; + public static final char C_ARRAY = '['; - /** - * Character constant indicating the start of a resolved, named type in a + /** + * Character constant indicating the start of a resolved, named type in a * signature. Value is 'L'. */ - public static final char C_RESOLVED = 'L'; + public static final char C_RESOLVED = 'L'; - /** + /** * Character constant indicating the start of an unresolved, named type in a * signature. Value is 'Q'. */ - public static final char C_UNRESOLVED = 'Q'; + public static final char C_UNRESOLVED = 'Q'; /** - * Character constant indicating the end of a named type in a signature. + * Character constant indicating the end of a named type in a signature. * Value is ';'. */ - public static final char C_NAME_END = ';'; + public static final char C_NAME_END = ';'; /** * Character constant indicating the start of a parameter type list in a * signature. Value is '('. */ - public static final char C_PARAM_START = '('; + public static final char C_PARAM_START = '('; /** - * Character constant indicating the end of a parameter type list in a + * Character constant indicating the end of a parameter type list in a * signature. Value is ')'. */ - public static final char C_PARAM_END = ')'; + public static final char C_PARAM_END = ')'; /** - * String constant for the signature of the primitive type boolean. - * Value is "Z". + * String constant for the signature of the primitive type boolean. Value is + * "Z". */ - public static final String SIG_BOOLEAN = "Z"; //$NON-NLS-1$ + public static final String SIG_BOOLEAN = "Z"; //$NON-NLS-1$ /** - * String constant for the signature of the primitive type byte. - * Value is "B". + * String constant for the signature of the primitive type byte. Value is + * "B". */ - public static final String SIG_BYTE = "B"; //$NON-NLS-1$ + public static final String SIG_BYTE = "B"; //$NON-NLS-1$ /** - * String constant for the signature of the primitive type char. - * Value is "C". + * String constant for the signature of the primitive type char. Value is + * "C". */ - public static final String SIG_CHAR = "C"; //$NON-NLS-1$ + public static final String SIG_CHAR = "C"; //$NON-NLS-1$ /** - * String constant for the signature of the primitive type double. - * Value is "D". + * String constant for the signature of the primitive type double. Value is + * "D". */ - public static final String SIG_DOUBLE = "D"; //$NON-NLS-1$ + public static final String SIG_DOUBLE = "D"; //$NON-NLS-1$ /** - * String constant for the signature of the primitive type float. - * Value is "F". + * String constant for the signature of the primitive type float. Value is + * "F". */ - public static final String SIG_FLOAT = "F"; //$NON-NLS-1$ + public static final String SIG_FLOAT = "F"; //$NON-NLS-1$ /** - * String constant for the signature of the primitive type int. - * Value is "I". + * String constant for the signature of the primitive type int. Value is + * "I". */ - public static final String SIG_INT = "I"; //$NON-NLS-1$ + public static final String SIG_INT = "I"; //$NON-NLS-1$ /** - * String constant for the signature of the primitive type long. - * Value is "J". + * String constant for the signature of the primitive type long. Value is + * "J". */ - public static final String SIG_LONG = "J"; //$NON-NLS-1$ + public static final String SIG_LONG = "J"; //$NON-NLS-1$ /** - * String constant for the signature of the primitive type short. - * Value is "S". + * String constant for the signature of the primitive type short. Value is + * "S". */ - public static final String SIG_SHORT = "S"; //$NON-NLS-1$ + public static final String SIG_SHORT = "S"; //$NON-NLS-1$ - /** String constant for the signature of result type void. - * Value is "V". + /** + * String constant for the signature of result type void. Value is + * "V". */ - public static final String SIG_VOID = "V"; //$NON-NLS-1$ - - private static final char[] BOOLEAN = {'b', 'o', 'o', 'l', 'e', 'a', 'n'}; - private static final char[] BYTE = {'b', 'y', 't', 'e'}; - private static final char[] CHAR = {'c', 'h', 'a', 'r'}; - private static final char[] DOUBLE = {'d', 'o', 'u', 'b', 'l', 'e'}; - private static final char[] FLOAT = {'f', 'l', 'o', 'a', 't'}; - private static final char[] INT = {'i', 'n', 't'}; - private static final char[] LONG = {'l', 'o', 'n', 'g'}; - private static final char[] SHORT = {'s', 'h', 'o', 'r', 't'}; - private static final char[] VOID = {'v', 'o', 'i', 'd'}; - + public static final String SIG_VOID = "V"; //$NON-NLS-1$ + + private static final char[] BOOLEAN = { 'b', 'o', 'o', 'l', 'e', 'a', 'n' }; + + private static final char[] BYTE = { 'b', 'y', 't', 'e' }; + + private static final char[] CHAR = { 'c', 'h', 'a', 'r' }; + + private static final char[] DOUBLE = { 'd', 'o', 'u', 'b', 'l', 'e' }; + + private static final char[] FLOAT = { 'f', 'l', 'o', 'a', 't' }; + + private static final char[] INT = { 'i', 'n', 't' }; + + private static final char[] LONG = { 'l', 'o', 'n', 'g' }; + + private static final char[] SHORT = { 's', 'h', 'o', 'r', 't' }; + + private static final char[] VOID = { 'v', 'o', 'i', 'd' }; + private static final String EMPTY = new String(CharOperation.NO_CHAR); - -/** - * Not instantiable. - */ -private Signature() {} -private static long copyType(char[] signature, int sigPos, char[] dest, int index, boolean fullyQualifyTypeNames) { - int arrayCount = 0; - loop: while (true) { - switch (signature[sigPos++]) { - case C_ARRAY : + /** + * Not instantiable. + */ + private Signature() { + } + + private static long copyType(char[] signature, int sigPos, char[] dest, + int index, boolean fullyQualifyTypeNames) { + int arrayCount = 0; + loop: while (true) { + switch (signature[sigPos++]) { + case C_ARRAY: arrayCount++; break; - case C_BOOLEAN : + case C_BOOLEAN: int length = BOOLEAN.length; System.arraycopy(BOOLEAN, 0, dest, index, length); index += length; break loop; - case C_BYTE : + case C_BYTE: length = BYTE.length; System.arraycopy(BYTE, 0, dest, index, length); index += length; break loop; - case C_CHAR : + case C_CHAR: length = CHAR.length; System.arraycopy(CHAR, 0, dest, index, length); index += length; break loop; - case C_DOUBLE : + case C_DOUBLE: length = DOUBLE.length; System.arraycopy(DOUBLE, 0, dest, index, length); index += length; break loop; - case C_FLOAT : + case C_FLOAT: length = FLOAT.length; System.arraycopy(FLOAT, 0, dest, index, length); index += length; break loop; - case C_INT : + case C_INT: length = INT.length; System.arraycopy(INT, 0, dest, index, length); index += length; break loop; - case C_LONG : + case C_LONG: length = LONG.length; System.arraycopy(LONG, 0, dest, index, length); index += length; break loop; - case C_SHORT : + case C_SHORT: length = SHORT.length; System.arraycopy(SHORT, 0, dest, index, length); index += length; break loop; - case C_VOID : + case C_VOID: length = VOID.length; System.arraycopy(VOID, 0, dest, index, length); index += length; break loop; - case C_RESOLVED : - case C_UNRESOLVED : + case C_RESOLVED: + case C_UNRESOLVED: int end = CharOperation.indexOf(C_SEMICOLON, signature, sigPos); - if (end == -1) throw new IllegalArgumentException(); + if (end == -1) + throw new IllegalArgumentException(); int start; if (fullyQualifyTypeNames) { start = sigPos; } else { - start = CharOperation.lastIndexOf(C_DOT, signature, sigPos, end)+1; - if (start == 0) start = sigPos; - } - length = end-start; + start = CharOperation.lastIndexOf(C_DOT, signature, sigPos, + end) + 1; + if (start == 0) + start = sigPos; + } + length = end - start; System.arraycopy(signature, start, dest, index, length); - sigPos = end+1; + sigPos = end + 1; index += length; break loop; + } } + while (arrayCount-- > 0) { + dest[index++] = '['; + dest[index++] = ']'; + } + return (((long) index) << 32) + sigPos; } - while (arrayCount-- > 0) { - dest[index++] = '['; - dest[index++] = ']'; + + /** + * Creates a new type signature with the given amount of array nesting added + * to the given type signature. + * + * @param typeSignature + * the type signature + * @param arrayCount + * the desired number of levels of array nesting + * @return the encoded array type signature + * + * @since 2.0 + */ + public static char[] createArraySignature(char[] typeSignature, + int arrayCount) { + if (arrayCount == 0) + return typeSignature; + int sigLength = typeSignature.length; + char[] result = new char[arrayCount + sigLength]; + for (int i = 0; i < arrayCount; i++) { + result[i] = C_ARRAY; + } + System.arraycopy(typeSignature, 0, result, arrayCount, sigLength); + return result; } - return (((long) index) << 32) + sigPos; -} -/** - * Creates a new type signature with the given amount of array nesting added - * to the given type signature. - * - * @param typeSignature the type signature - * @param arrayCount the desired number of levels of array nesting - * @return the encoded array type signature - * - * @since 2.0 - */ -public static char[] createArraySignature(char[] typeSignature, int arrayCount) { - if (arrayCount == 0) return typeSignature; - int sigLength = typeSignature.length; - char[] result = new char[arrayCount + sigLength]; - for (int i = 0; i < arrayCount; i++) { - result[i] = C_ARRAY; + + /** + * Creates a new type signature with the given amount of array nesting added + * to the given type signature. + * + * @param typeSignature + * the type signature + * @param arrayCount + * the desired number of levels of array nesting + * @return the encoded array type signature + */ + public static String createArraySignature(String typeSignature, + int arrayCount) { + return new String(createArraySignature(typeSignature.toCharArray(), + arrayCount)); } - System.arraycopy(typeSignature, 0, result, arrayCount, sigLength); - return result; -} -/** - * Creates a new type signature with the given amount of array nesting added - * to the given type signature. - * - * @param typeSignature the type signature - * @param arrayCount the desired number of levels of array nesting - * @return the encoded array type signature - */ -public static String createArraySignature(String typeSignature, int arrayCount) { - return new String(createArraySignature(typeSignature.toCharArray(), arrayCount)); -} -/** - * Creates a method signature from the given parameter and return type - * signatures. The encoded method signature is dot-based. - * - * @param parameterTypes the list of parameter type signatures - * @param returnType the return type signature - * @return the encoded method signature - * - * @since 2.0 - */ -public static char[] createMethodSignature(char[][] parameterTypes, char[] returnType) { - int parameterTypesLength = parameterTypes.length; - int parameterLength = 0; - for (int i = 0; i < parameterTypesLength; i++) { - parameterLength += parameterTypes[i].length; - + + /** + * Creates a method signature from the given parameter and return type + * signatures. The encoded method signature is dot-based. + * + * @param parameterTypes + * the list of parameter type signatures + * @param returnType + * the return type signature + * @return the encoded method signature + * + * @since 2.0 + */ + public static char[] createMethodSignature(char[][] parameterTypes, + char[] returnType) { + int parameterTypesLength = parameterTypes.length; + int parameterLength = 0; + for (int i = 0; i < parameterTypesLength; i++) { + parameterLength += parameterTypes[i].length; + + } + int returnTypeLength = returnType.length; + char[] result = new char[1 + parameterLength + 1 + returnTypeLength]; + result[0] = C_PARAM_START; + int index = 1; + for (int i = 0; i < parameterTypesLength; i++) { + char[] parameterType = parameterTypes[i]; + int length = parameterType.length; + System.arraycopy(parameterType, 0, result, index, length); + index += length; + } + result[index] = C_PARAM_END; + System.arraycopy(returnType, 0, result, index + 1, returnTypeLength); + return result; } - int returnTypeLength = returnType.length; - char[] result = new char[1 + parameterLength + 1 + returnTypeLength]; - result[0] = C_PARAM_START; - int index = 1; - for (int i = 0; i < parameterTypesLength; i++) { - char[] parameterType = parameterTypes[i]; - int length = parameterType.length; - System.arraycopy(parameterType, 0, result, index, length); - index += length; + + /** + * Creates a method signature from the given parameter and return type + * signatures. The encoded method signature is dot-based. + * + * @param parameterTypes + * the list of parameter type signatures + * @param returnType + * the return type signature + * @return the encoded method signature + */ + public static String createMethodSignature(String[] parameterTypes, + String returnType) { + int parameterTypesLenth = parameterTypes.length; + char[][] parameters = new char[parameterTypesLenth][]; + for (int i = 0; i < parameterTypesLenth; i++) { + parameters[i] = parameterTypes[i].toCharArray(); + } + return new String(createMethodSignature(parameters, returnType + .toCharArray())); } - result[index] = C_PARAM_END; - System.arraycopy(returnType, 0, result, index+1, returnTypeLength); - return result; -} -/** - * Creates a method signature from the given parameter and return type - * signatures. The encoded method signature is dot-based. - * - * @param parameterTypes the list of parameter type signatures - * @param returnType the return type signature - * @return the encoded method signature - */ -public static String createMethodSignature(String[] parameterTypes, String returnType) { - int parameterTypesLenth = parameterTypes.length; - char[][] parameters = new char[parameterTypesLenth][]; - for (int i = 0; i < parameterTypesLenth; i++) { - parameters[i] = parameterTypes[i].toCharArray(); + + /** + * Creates a new type signature from the given type name encoded as a + * character array. This method is equivalent to + * createTypeSignature(new String(typeName),isResolved), + * although more efficient for callers with character arrays rather than + * strings. If the type name is qualified, then it is expected to be + * dot-based. + * + * @param typeName + * the possibly qualified type name + * @param isResolved + * true if the type name is to be considered + * resolved (for example, a type name from a binary class file), + * and false if the type name is to be considered + * unresolved (for example, a type name found in source code) + * @return the encoded type signature + * @see #createTypeSignature(java.lang.String,boolean) + */ + public static String createTypeSignature(char[] typeName, boolean isResolved) { + return new String(createCharArrayTypeSignature(typeName, isResolved)); } - return new String(createMethodSignature(parameters, returnType.toCharArray())); -} -/** - * Creates a new type signature from the given type name encoded as a character - * array. This method is equivalent to - * createTypeSignature(new String(typeName),isResolved), although - * more efficient for callers with character arrays rather than strings. If the - * type name is qualified, then it is expected to be dot-based. - * - * @param typeName the possibly qualified type name - * @param isResolved true if the type name is to be considered - * resolved (for example, a type name from a binary class file), and - * false if the type name is to be considered unresolved - * (for example, a type name found in source code) - * @return the encoded type signature - * @see #createTypeSignature(java.lang.String,boolean) - */ -public static String createTypeSignature(char[] typeName, boolean isResolved) { - return new String(createCharArrayTypeSignature(typeName, isResolved)); -} -/** - * Creates a new type signature from the given type name encoded as a character - * array. This method is equivalent to - * createTypeSignature(new String(typeName),isResolved).toCharArray(), although - * more efficient for callers with character arrays rather than strings. If the - * type name is qualified, then it is expected to be dot-based. - * - * @param typeName the possibly qualified type name - * @param isResolved true if the type name is to be considered - * resolved (for example, a type name from a binary class file), and - * false if the type name is to be considered unresolved - * (for example, a type name found in source code) - * @return the encoded type signature - * @see #createTypeSignature(java.lang.String,boolean) - * - * @since 2.0 - */ -public static char[] createCharArrayTypeSignature(char[] typeName, boolean isResolved) { - if (typeName == null) throw new IllegalArgumentException("null"); //$NON-NLS-1$ - int length = typeName.length; - if (length == 0) throw new IllegalArgumentException(new String(typeName)); + /** + * Creates a new type signature from the given type name encoded as a + * character array. This method is equivalent to + * createTypeSignature(new String(typeName),isResolved).toCharArray(), + * although more efficient for callers with character arrays rather than + * strings. If the type name is qualified, then it is expected to be + * dot-based. + * + * @param typeName + * the possibly qualified type name + * @param isResolved + * true if the type name is to be considered + * resolved (for example, a type name from a binary class file), + * and false if the type name is to be considered + * unresolved (for example, a type name found in source code) + * @return the encoded type signature + * @see #createTypeSignature(java.lang.String,boolean) + * + * @since 2.0 + */ + public static char[] createCharArrayTypeSignature(char[] typeName, + boolean isResolved) { + + if (typeName == null) + throw new IllegalArgumentException("null"); //$NON-NLS-1$ + int length = typeName.length; + if (length == 0) + throw new IllegalArgumentException(new String(typeName)); - int arrayCount = CharOperation.occurencesOf('[', typeName); - char[] sig; - - switch (typeName[0]) { + int arrayCount = CharOperation.occurencesOf('[', typeName); + char[] sig; + + switch (typeName[0]) { // primitive type? - case 'b' : + case 'b': if (CharOperation.fragmentEquals(BOOLEAN, typeName, 0, true)) { - sig = new char[arrayCount+1]; + sig = new char[arrayCount + 1]; sig[arrayCount] = C_BOOLEAN; break; } else if (CharOperation.fragmentEquals(BYTE, typeName, 0, true)) { - sig = new char[arrayCount+1]; + sig = new char[arrayCount + 1]; sig[arrayCount] = C_BYTE; break; } case 'c': if (CharOperation.fragmentEquals(CHAR, typeName, 0, true)) { - sig = new char[arrayCount+1]; + sig = new char[arrayCount + 1]; sig[arrayCount] = C_CHAR; break; } case 'd': if (CharOperation.fragmentEquals(DOUBLE, typeName, 0, true)) { - sig = new char[arrayCount+1]; + sig = new char[arrayCount + 1]; sig[arrayCount] = C_DOUBLE; break; } case 'f': if (CharOperation.fragmentEquals(FLOAT, typeName, 0, true)) { - sig = new char[arrayCount+1]; + sig = new char[arrayCount + 1]; sig[arrayCount] = C_FLOAT; break; } case 'i': if (CharOperation.fragmentEquals(INT, typeName, 0, true)) { - sig = new char[arrayCount+1]; + sig = new char[arrayCount + 1]; sig[arrayCount] = C_INT; break; } case 'l': if (CharOperation.fragmentEquals(LONG, typeName, 0, true)) { - sig = new char[arrayCount+1]; + sig = new char[arrayCount + 1]; sig[arrayCount] = C_LONG; break; } case 's': if (CharOperation.fragmentEquals(SHORT, typeName, 0, true)) { - sig = new char[arrayCount+1]; + sig = new char[arrayCount + 1]; sig[arrayCount] = C_SHORT; break; } case 'v': if (CharOperation.fragmentEquals(VOID, typeName, 0, true)) { - sig = new char[arrayCount+1]; + sig = new char[arrayCount + 1]; sig[arrayCount] = C_VOID; break; } default: // non primitive type - int sigLength = arrayCount + 1 + length + 1; // for example '[[[Ljava.lang.String;' + int sigLength = arrayCount + 1 + length + 1; // for example + // '[[[Ljava.lang.String;' sig = new char[sigLength]; - int sigIndex = arrayCount+1; // index in sig + int sigIndex = arrayCount + 1; // index in sig int startID = 0; // start of current ID in typeName int index = 0; // index in typeName while (index < length) { char currentChar = typeName[index]; switch (currentChar) { - case '.': - if (startID == -1) throw new IllegalArgumentException(new String(typeName)); + case '.': + if (startID == -1) + throw new IllegalArgumentException(new String(typeName)); + if (startID < index) { + sig = CharOperation.append(sig, sigIndex, typeName, + startID, index); + sigIndex += index - startID; + } + sig[sigIndex++] = C_DOT; + index++; + startID = index; + break; + case '[': + if (startID != -1) { if (startID < index) { - sig = CharOperation.append(sig, sigIndex, typeName, startID, index); - sigIndex += index-startID; + sig = CharOperation.append(sig, sigIndex, typeName, + startID, index); + sigIndex += index - startID; } - sig[sigIndex++] = C_DOT; - index++; - startID = index; - break; - case '[': - if (startID != -1) { - if (startID < index) { - sig = CharOperation.append(sig, sigIndex, typeName, startID, index); - sigIndex += index-startID; - } - startID = -1; // no more id after [] - } - index++; - break; - default : - if (startID != -1 && CharOperation.isWhitespace(currentChar)) { - if (startID < index) { - sig = CharOperation.append(sig, sigIndex, typeName, startID, index); - sigIndex += index-startID; - } - startID = index+1; + startID = -1; // no more id after [] + } + index++; + break; + default: + if (startID != -1 + && CharOperation.isWhitespace(currentChar)) { + if (startID < index) { + sig = CharOperation.append(sig, sigIndex, typeName, + startID, index); + sigIndex += index - startID; } - index++; - break; + startID = index + 1; + } + index++; + break; } } // last id if (startID != -1 && startID < index) { - sig = CharOperation.append(sig, sigIndex, typeName, startID, index); - sigIndex += index-startID; + sig = CharOperation.append(sig, sigIndex, typeName, startID, + index); + sigIndex += index - startID; } - + // add L (or Q) at the beigininig and ; at the end sig[arrayCount] = isResolved ? C_RESOLVED : C_UNRESOLVED; sig[sigIndex++] = C_NAME_END; - + // resize if needed if (sigLength > sigIndex) { System.arraycopy(sig, 0, sig = new char[sigIndex], 0, sigIndex); } + } + + // add array info + for (int i = 0; i < arrayCount; i++) { + sig[i] = C_ARRAY; + } + + return sig; } - // add array info - for (int i = 0; i < arrayCount; i++) { - sig[i] = C_ARRAY; + /** + * Creates a new type signature from the given type name. If the type name + * is qualified, then it is expected to be dot-based. + *

          + * For example: + * + *

          +	 * 
          +	 *  createTypeSignature("int", hucairz) -> "I"
          +	 *  createTypeSignature("java.lang.String", true) -> "Ljava.lang.String;"
          +	 *  createTypeSignature("String", false) -> "QString;"
          +	 *  createTypeSignature("java.lang.String", false) -> "Qjava.lang.String;"
          +	 *  createTypeSignature("int []", false) -> "[I"
          +	 * 
          +	 * 
          + * + *

          + * + * @param typeName + * the possibly qualified type name + * @param isResolved + * true if the type name is to be considered + * resolved (for example, a type name from a binary class file), + * and false if the type name is to be considered + * unresolved (for example, a type name found in source code) + * @return the encoded type signature + */ + public static String createTypeSignature(String typeName, boolean isResolved) { + return createTypeSignature(typeName == null ? null : typeName + .toCharArray(), isResolved); } - - return sig; -} -/** - * Creates a new type signature from the given type name. If the type name is qualified, - * then it is expected to be dot-based. - *

          - * For example: - *

          - * 
          - * createTypeSignature("int", hucairz) -> "I"
          - * createTypeSignature("java.lang.String", true) -> "Ljava.lang.String;"
          - * createTypeSignature("String", false) -> "QString;"
          - * createTypeSignature("java.lang.String", false) -> "Qjava.lang.String;"
          - * createTypeSignature("int []", false) -> "[I"
          - * 
          - * 
          - *

          - * - * @param typeName the possibly qualified type name - * @param isResolved true if the type name is to be considered - * resolved (for example, a type name from a binary class file), and - * false if the type name is to be considered unresolved - * (for example, a type name found in source code) - * @return the encoded type signature - */ -public static String createTypeSignature(String typeName, boolean isResolved) { - return createTypeSignature(typeName == null ? null : typeName.toCharArray(), isResolved); -} -/** - * Returns the array count (array nesting depth) of the given type signature. - * - * @param typeSignature the type signature - * @return the array nesting depth, or 0 if not an array - * @exception IllegalArgumentException if the signature is not syntactically - * correct - * - * @since 2.0 - */ -public static int getArrayCount(char[] typeSignature) throws IllegalArgumentException { - try { - int count = 0; - while (typeSignature[count] == C_ARRAY) { - ++count; + + /** + * Returns the array count (array nesting depth) of the given type + * signature. + * + * @param typeSignature + * the type signature + * @return the array nesting depth, or 0 if not an array + * @exception IllegalArgumentException + * if the signature is not syntactically correct + * + * @since 2.0 + */ + public static int getArrayCount(char[] typeSignature) + throws IllegalArgumentException { + try { + int count = 0; + while (typeSignature[count] == C_ARRAY) { + ++count; + } + return count; + } catch (ArrayIndexOutOfBoundsException e) { // signature is + // syntactically + // incorrect if last + // character is C_ARRAY + throw new IllegalArgumentException(); } - return count; - } catch (ArrayIndexOutOfBoundsException e) { // signature is syntactically incorrect if last character is C_ARRAY - throw new IllegalArgumentException(); } -} -/** - * Returns the array count (array nesting depth) of the given type signature. - * - * @param typeSignature the type signature - * @return the array nesting depth, or 0 if not an array - * @exception IllegalArgumentException if the signature is not syntactically - * correct - */ -public static int getArrayCount(String typeSignature) throws IllegalArgumentException { - return getArrayCount(typeSignature.toCharArray()); -} -/** - * Returns the type signature without any array nesting. - *

          - * For example: - *

          - * 
          - * getElementType({'[', '[', 'I'}) --> {'I'}.
          - * 
          - * 
          - *

          - * - * @param typeSignature the type signature - * @return the type signature without arrays - * @exception IllegalArgumentException if the signature is not syntactically - * correct - * - * @since 2.0 - */ -public static char[] getElementType(char[] typeSignature) throws IllegalArgumentException { - int count = getArrayCount(typeSignature); - if (count == 0) return typeSignature; - int length = typeSignature.length; - char[] result = new char[length-count]; - System.arraycopy(typeSignature, count, result, 0, length-count); - return result; -} -/** - * Returns the type signature without any array nesting. - *

          - * For example: - *

          - * 
          - * getElementType("[[I") --> "I".
          - * 
          - * 
          - *

          - * - * @param typeSignature the type signature - * @return the type signature without arrays - * @exception IllegalArgumentException if the signature is not syntactically - * correct - */ -public static String getElementType(String typeSignature) throws IllegalArgumentException { - return new String(getElementType(typeSignature.toCharArray())); -} -/** - * Returns the number of parameter types in the given method signature. - * - * @param methodSignature the method signature - * @return the number of parameters - * @exception IllegalArgumentException if the signature is not syntactically - * correct - * @since 2.0 - */ -public static int getParameterCount(char[] methodSignature) throws IllegalArgumentException { - try { - int count = 0; - int i = CharOperation.indexOf(C_PARAM_START, methodSignature) + 1; - if (i == 0) - throw new IllegalArgumentException(); - for (;;) { - char c = methodSignature[i++]; - switch (c) { - case C_ARRAY : + + /** + * Returns the array count (array nesting depth) of the given type + * signature. + * + * @param typeSignature + * the type signature + * @return the array nesting depth, or 0 if not an array + * @exception IllegalArgumentException + * if the signature is not syntactically correct + */ + public static int getArrayCount(String typeSignature) + throws IllegalArgumentException { + return getArrayCount(typeSignature.toCharArray()); + } + + /** + * Returns the type signature without any array nesting. + *

          + * For example: + * + *

          +	 * 
          +	 *  getElementType({'[', '[', 'I'}) --> {'I'}.
          +	 * 
          +	 * 
          + * + *

          + * + * @param typeSignature + * the type signature + * @return the type signature without arrays + * @exception IllegalArgumentException + * if the signature is not syntactically correct + * + * @since 2.0 + */ + public static char[] getElementType(char[] typeSignature) + throws IllegalArgumentException { + int count = getArrayCount(typeSignature); + if (count == 0) + return typeSignature; + int length = typeSignature.length; + char[] result = new char[length - count]; + System.arraycopy(typeSignature, count, result, 0, length - count); + return result; + } + + /** + * Returns the type signature without any array nesting. + *

          + * For example: + * + *

          +	 * 
          +	 *  getElementType("[[I") --> "I".
          +	 * 
          +	 * 
          + * + *

          + * + * @param typeSignature + * the type signature + * @return the type signature without arrays + * @exception IllegalArgumentException + * if the signature is not syntactically correct + */ + public static String getElementType(String typeSignature) + throws IllegalArgumentException { + return new String(getElementType(typeSignature.toCharArray())); + } + + /** + * Returns the number of parameter types in the given method signature. + * + * @param methodSignature + * the method signature + * @return the number of parameters + * @exception IllegalArgumentException + * if the signature is not syntactically correct + * @since 2.0 + */ + public static int getParameterCount(char[] methodSignature) + throws IllegalArgumentException { + try { + int count = 0; + int i = CharOperation.indexOf(C_PARAM_START, methodSignature) + 1; + if (i == 0) + throw new IllegalArgumentException(); + for (;;) { + char c = methodSignature[i++]; + switch (c) { + case C_ARRAY: break; - case C_BOOLEAN : - case C_BYTE : - case C_CHAR : - case C_DOUBLE : - case C_FLOAT : - case C_INT : - case C_LONG : - case C_SHORT : - case C_VOID : + case C_BOOLEAN: + case C_BYTE: + case C_CHAR: + case C_DOUBLE: + case C_FLOAT: + case C_INT: + case C_LONG: + case C_SHORT: + case C_VOID: ++count; break; - case C_RESOLVED : - case C_UNRESOLVED : + case C_RESOLVED: + case C_UNRESOLVED: i = CharOperation.indexOf(C_SEMICOLON, methodSignature, i) + 1; if (i == 0) throw new IllegalArgumentException(); ++count; break; - case C_PARAM_END : + case C_PARAM_END: return count; - default : + default: throw new IllegalArgumentException(); + } } + } catch (ArrayIndexOutOfBoundsException e) { + throw new IllegalArgumentException(); } - } catch (ArrayIndexOutOfBoundsException e) { - throw new IllegalArgumentException(); } -} -/** - * Returns the number of parameter types in the given method signature. - * - * @param methodSignature the method signature - * @return the number of parameters - * @exception IllegalArgumentException if the signature is not syntactically - * correct - */ -public static int getParameterCount(String methodSignature) throws IllegalArgumentException { - return getParameterCount(methodSignature.toCharArray()); -} -/** - * Extracts the parameter type signatures from the given method signature. - * The method signature is expected to be dot-based. - * - * @param methodSignature the method signature - * @return the list of parameter type signatures - * @exception IllegalArgumentException if the signature is syntactically - * incorrect - * - * @since 2.0 - */ -public static char[][] getParameterTypes(char[] methodSignature) throws IllegalArgumentException { - try { - int count = getParameterCount(methodSignature); - char[][] result = new char[count][]; - if (count == 0) - return result; - int i = CharOperation.indexOf(C_PARAM_START, methodSignature) + 1; - count = 0; - int start = i; - for (;;) { - char c = methodSignature[i++]; - switch (c) { - case C_ARRAY : + + /** + * Returns the number of parameter types in the given method signature. + * + * @param methodSignature + * the method signature + * @return the number of parameters + * @exception IllegalArgumentException + * if the signature is not syntactically correct + */ + public static int getParameterCount(String methodSignature) + throws IllegalArgumentException { + return getParameterCount(methodSignature.toCharArray()); + } + + /** + * Extracts the parameter type signatures from the given method signature. + * The method signature is expected to be dot-based. + * + * @param methodSignature + * the method signature + * @return the list of parameter type signatures + * @exception IllegalArgumentException + * if the signature is syntactically incorrect + * + * @since 2.0 + */ + public static char[][] getParameterTypes(char[] methodSignature) + throws IllegalArgumentException { + try { + int count = getParameterCount(methodSignature); + char[][] result = new char[count][]; + if (count == 0) + return result; + int i = CharOperation.indexOf(C_PARAM_START, methodSignature) + 1; + count = 0; + int start = i; + for (;;) { + char c = methodSignature[i++]; + switch (c) { + case C_ARRAY: // array depth is i - start; break; - case C_BOOLEAN : - case C_BYTE : - case C_CHAR : - case C_DOUBLE : - case C_FLOAT : - case C_INT : - case C_LONG : - case C_SHORT : - case C_VOID : + case C_BOOLEAN: + case C_BYTE: + case C_CHAR: + case C_DOUBLE: + case C_FLOAT: + case C_INT: + case C_LONG: + case C_SHORT: + case C_VOID: // common case of base types if (i - start == 1) { switch (c) { - case C_BOOLEAN : - result[count++] = new char[] {C_BOOLEAN}; - break; - case C_BYTE : - result[count++] = new char[] {C_BYTE}; - break; - case C_CHAR : - result[count++] = new char[] {C_CHAR}; - break; - case C_DOUBLE : - result[count++] = new char[] {C_DOUBLE}; - break; - case C_FLOAT : - result[count++] = new char[] {C_FLOAT}; - break; - case C_INT : - result[count++] = new char[] {C_INT}; - break; - case C_LONG : - result[count++] = new char[] {C_LONG}; - break; - case C_SHORT : - result[count++] = new char[] {C_SHORT}; - break; - case C_VOID : - result[count++] = new char[] {C_VOID}; - break; + case C_BOOLEAN: + result[count++] = new char[] { C_BOOLEAN }; + break; + case C_BYTE: + result[count++] = new char[] { C_BYTE }; + break; + case C_CHAR: + result[count++] = new char[] { C_CHAR }; + break; + case C_DOUBLE: + result[count++] = new char[] { C_DOUBLE }; + break; + case C_FLOAT: + result[count++] = new char[] { C_FLOAT }; + break; + case C_INT: + result[count++] = new char[] { C_INT }; + break; + case C_LONG: + result[count++] = new char[] { C_LONG }; + break; + case C_SHORT: + result[count++] = new char[] { C_SHORT }; + break; + case C_VOID: + result[count++] = new char[] { C_VOID }; + break; } } else { - result[count++] = CharOperation.subarray(methodSignature, start, i); + result[count++] = CharOperation.subarray( + methodSignature, start, i); } start = i; break; - case C_RESOLVED : - case C_UNRESOLVED : + case C_RESOLVED: + case C_UNRESOLVED: i = CharOperation.indexOf(C_SEMICOLON, methodSignature, i) + 1; if (i == 0) throw new IllegalArgumentException(); - result[count++] = CharOperation.subarray(methodSignature, start, i); + result[count++] = CharOperation.subarray(methodSignature, + start, i); start = i; break; case C_PARAM_END: return result; - default : + default: throw new IllegalArgumentException(); + } } + } catch (ArrayIndexOutOfBoundsException e) { + throw new IllegalArgumentException(); } - } catch (ArrayIndexOutOfBoundsException e) { - throw new IllegalArgumentException(); - } -} -/** - * Extracts the parameter type signatures from the given method signature. - * The method signature is expected to be dot-based. - * - * @param methodSignature the method signature - * @return the list of parameter type signatures - * @exception IllegalArgumentException if the signature is syntactically - * incorrect - */ -public static String[] getParameterTypes(String methodSignature) throws IllegalArgumentException { - char[][] parameterTypes = getParameterTypes(methodSignature.toCharArray()); - int length = parameterTypes.length; - String[] result = new String[length]; - for (int i = 0; i < length; i++) { - result[i] = new String(parameterTypes[i]); } - return result; -} -/** - * Returns a char array containing all but the last segment of the given - * dot-separated qualified name. Returns the empty char array if it is not qualified. - *

          - * For example: - *

          - * 
          - * getQualifier({'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'O', 'b', 'j', 'e', 'c', 't'}) -> {'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g'}
          - * getQualifier({'O', 'u', 't', 'e', 'r', '.', 'I', 'n', 'n', 'e', 'r'}) -> {'O', 'u', 't', 'e', 'r'}
          - * 
          - * 
          - *

          - * - * @param name the name - * @return the qualifier prefix, or the empty char array if the name contains no - * dots - * @exception NullPointerException if name is null - * @since 2.0 - */ -public static char[] getQualifier(char[] name) { - int lastDot = CharOperation.lastIndexOf(C_DOT, name); - if (lastDot == -1) { - return CharOperation.NO_CHAR; - } - return CharOperation.subarray(name, 0, lastDot); -} -/** - * Returns a string containing all but the last segment of the given - * dot-separated qualified name. Returns the empty string if it is not qualified. - *

          - * For example: - *

          - * 
          - * getQualifier("java.lang.Object") -> "java.lang"
          - * getQualifier("Outer.Inner") -> "Outer"
          - * 
          - * 
          - *

          - * - * @param name the name - * @return the qualifier prefix, or the empty string if the name contains no - * dots - * @exception NullPointerException if name is null - */ -public static String getQualifier(String name) { - int lastDot = name.lastIndexOf(C_DOT); - if (lastDot == -1) { - return EMPTY; + + /** + * Extracts the parameter type signatures from the given method signature. + * The method signature is expected to be dot-based. + * + * @param methodSignature + * the method signature + * @return the list of parameter type signatures + * @exception IllegalArgumentException + * if the signature is syntactically incorrect + */ + public static String[] getParameterTypes(String methodSignature) + throws IllegalArgumentException { + char[][] parameterTypes = getParameterTypes(methodSignature + .toCharArray()); + int length = parameterTypes.length; + String[] result = new String[length]; + for (int i = 0; i < length; i++) { + result[i] = new String(parameterTypes[i]); + } + return result; } - return name.substring(0, lastDot); -} -/** - * Extracts the return type from the given method signature. The method signature is - * expected to be dot-based. - * - * @param methodSignature the method signature - * @return the type signature of the return type - * @exception IllegalArgumentException if the signature is syntactically - * incorrect - * - * @since 2.0 - */ -public static char[] getReturnType(char[] methodSignature) throws IllegalArgumentException { - int i = CharOperation.lastIndexOf(C_PARAM_END, methodSignature); - if (i == -1) { - throw new IllegalArgumentException(); + + /** + * Returns a char array containing all but the last segment of the given + * dot-separated qualified name. Returns the empty char array if it is not + * qualified. + *

          + * For example: + * + *

          +	 * 
          +	 *  getQualifier({'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'O', 'b', 'j', 'e', 'c', 't'}) -> {'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g'}
          +	 *  getQualifier({'O', 'u', 't', 'e', 'r', '.', 'I', 'n', 'n', 'e', 'r'}) -> {'O', 'u', 't', 'e', 'r'}
          +	 * 
          +	 * 
          + * + *

          + * + * @param name + * the name + * @return the qualifier prefix, or the empty char array if the name + * contains no dots + * @exception NullPointerException + * if name is null + * @since 2.0 + */ + public static char[] getQualifier(char[] name) { + int lastDot = CharOperation.lastIndexOf(C_DOT, name); + if (lastDot == -1) { + return CharOperation.NO_CHAR; + } + return CharOperation.subarray(name, 0, lastDot); } - return CharOperation.subarray(methodSignature, i + 1, methodSignature.length); -} -/** - * Extracts the return type from the given method signature. The method signature is - * expected to be dot-based. - * - * @param methodSignature the method signature - * @return the type signature of the return type - * @exception IllegalArgumentException if the signature is syntactically - * incorrect - */ -public static String getReturnType(String methodSignature) throws IllegalArgumentException { - return new String(getReturnType(methodSignature.toCharArray())); -} -/** - * Returns the last segment of the given dot-separated qualified name. - * Returns the given name if it is not qualified. - *

          - * For example: - *

          - * 
          - * getSimpleName({'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'O', 'b', 'j', 'e', 'c', 't'}) -> {'O', 'b', 'j', 'e', 'c', 't'}
          - * 
          - * 
          - *

          - * - * @param name the name - * @return the last segment of the qualified name - * @exception NullPointerException if name is null - * @since 2.0 - */ -public static char[] getSimpleName(char[] name) { - int lastDot = CharOperation.lastIndexOf(C_DOT, name); - if (lastDot == -1) { - return name; + + /** + * Returns a string containing all but the last segment of the given + * dot-separated qualified name. Returns the empty string if it is not + * qualified. + *

          + * For example: + * + *

          +	 * 
          +	 *  getQualifier("java.lang.Object") -> "java.lang"
          +	 *  getQualifier("Outer.Inner") -> "Outer"
          +	 * 
          +	 * 
          + * + *

          + * + * @param name + * the name + * @return the qualifier prefix, or the empty string if the name contains no + * dots + * @exception NullPointerException + * if name is null + */ + public static String getQualifier(String name) { + int lastDot = name.lastIndexOf(C_DOT); + if (lastDot == -1) { + return EMPTY; + } + return name.substring(0, lastDot); } - return CharOperation.subarray(name, lastDot + 1, name.length); -} -/** - * Returns the last segment of the given dot-separated qualified name. - * Returns the given name if it is not qualified. - *

          - * For example: - *

          - * 
          - * getSimpleName("java.lang.Object") -> "Object"
          - * 
          - * 
          - *

          - * - * @param name the name - * @return the last segment of the qualified name - * @exception NullPointerException if name is null - */ -public static String getSimpleName(String name) { - int lastDot = name.lastIndexOf(C_DOT); - if (lastDot == -1) { - return name; + + /** + * Extracts the return type from the given method signature. The method + * signature is expected to be dot-based. + * + * @param methodSignature + * the method signature + * @return the type signature of the return type + * @exception IllegalArgumentException + * if the signature is syntactically incorrect + * + * @since 2.0 + */ + public static char[] getReturnType(char[] methodSignature) + throws IllegalArgumentException { + int i = CharOperation.lastIndexOf(C_PARAM_END, methodSignature); + if (i == -1) { + throw new IllegalArgumentException(); + } + return CharOperation.subarray(methodSignature, i + 1, + methodSignature.length); } - return name.substring(lastDot + 1, name.length()); -} -/** - * Returns all segments of the given dot-separated qualified name. - * Returns an array with only the given name if it is not qualified. - * Returns an empty array if the name is empty. - *

          - * For example: - *

          - * 
          - * getSimpleNames({'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'O', 'b', 'j', 'e', 'c', 't'}) -> {{'j', 'a', 'v', 'a'}, {'l', 'a', 'n', 'g'}, {'O', 'b', 'j', 'e', 'c', 't'}}
          - * getSimpleNames({'O', 'b', 'j', 'e', 'c', 't'}) -> {{'O', 'b', 'j', 'e', 'c', 't'}}
          - * getSimpleNames("") -> {}
          - * 
          - * 
          - * - * @param name the name - * @return the list of simple names, possibly empty - * @exception NullPointerException if name is null - * @since 2.0 - */ -public static char[][] getSimpleNames(char[] name) { - if (name.length == 0) { - return CharOperation.NO_CHAR_CHAR; + + /** + * Extracts the return type from the given method signature. The method + * signature is expected to be dot-based. + * + * @param methodSignature + * the method signature + * @return the type signature of the return type + * @exception IllegalArgumentException + * if the signature is syntactically incorrect + */ + public static String getReturnType(String methodSignature) + throws IllegalArgumentException { + return new String(getReturnType(methodSignature.toCharArray())); } - int dot = CharOperation.indexOf(C_DOT, name); - if (dot == -1) { - return new char[][] {name}; + + /** + * Returns the last segment of the given dot-separated qualified name. + * Returns the given name if it is not qualified. + *

          + * For example: + * + *

          +	 * 
          +	 *  getSimpleName({'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'O', 'b', 'j', 'e', 'c', 't'}) -> {'O', 'b', 'j', 'e', 'c', 't'}
          +	 * 
          +	 * 
          + * + *

          + * + * @param name + * the name + * @return the last segment of the qualified name + * @exception NullPointerException + * if name is null + * @since 2.0 + */ + public static char[] getSimpleName(char[] name) { + int lastDot = CharOperation.lastIndexOf(C_DOT, name); + if (lastDot == -1) { + return name; + } + return CharOperation.subarray(name, lastDot + 1, name.length); } - int n = 1; - while ((dot = CharOperation.indexOf(C_DOT, name, dot + 1)) != -1) { - ++n; + + /** + * Returns the last segment of the given dot-separated qualified name. + * Returns the given name if it is not qualified. + *

          + * For example: + * + *

          +	 * 
          +	 *  getSimpleName("java.lang.Object") -> "Object"
          +	 * 
          +	 * 
          + * + *

          + * + * @param name + * the name + * @return the last segment of the qualified name + * @exception NullPointerException + * if name is null + */ + public static String getSimpleName(String name) { + int lastDot = name.lastIndexOf(C_DOT); + if (lastDot == -1) { + return name; + } + return name.substring(lastDot + 1, name.length()); } - char[][] result = new char[n + 1][]; - int segStart = 0; - for (int i = 0; i < n; ++i) { - dot = CharOperation.indexOf(C_DOT, name, segStart); - result[i] = CharOperation.subarray(name, segStart, dot); - segStart = dot + 1; + + /** + * Returns all segments of the given dot-separated qualified name. Returns + * an array with only the given name if it is not qualified. Returns an + * empty array if the name is empty. + *

          + * For example: + * + *

          +	 * 
          +	 *  getSimpleNames({'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'O', 'b', 'j', 'e', 'c', 't'}) -> {{'j', 'a', 'v', 'a'}, {'l', 'a', 'n', 'g'}, {'O', 'b', 'j', 'e', 'c', 't'}}
          +	 *  getSimpleNames({'O', 'b', 'j', 'e', 'c', 't'}) -> {{'O', 'b', 'j', 'e', 'c', 't'}}
          +	 *  getSimpleNames("") -> {}
          +	 * 
          +	 * 
          + * + * @param name + * the name + * @return the list of simple names, possibly empty + * @exception NullPointerException + * if name is null + * @since 2.0 + */ + public static char[][] getSimpleNames(char[] name) { + if (name.length == 0) { + return CharOperation.NO_CHAR_CHAR; + } + int dot = CharOperation.indexOf(C_DOT, name); + if (dot == -1) { + return new char[][] { name }; + } + int n = 1; + while ((dot = CharOperation.indexOf(C_DOT, name, dot + 1)) != -1) { + ++n; + } + char[][] result = new char[n + 1][]; + int segStart = 0; + for (int i = 0; i < n; ++i) { + dot = CharOperation.indexOf(C_DOT, name, segStart); + result[i] = CharOperation.subarray(name, segStart, dot); + segStart = dot + 1; + } + result[n] = CharOperation.subarray(name, segStart, name.length); + return result; } - result[n] = CharOperation.subarray(name, segStart, name.length); - return result; -} -/** - * Returns all segments of the given dot-separated qualified name. - * Returns an array with only the given name if it is not qualified. - * Returns an empty array if the name is empty. - *

          - * For example: - *

          - * 
          - * getSimpleNames("java.lang.Object") -> {"java", "lang", "Object"}
          - * getSimpleNames("Object") -> {"Object"}
          - * getSimpleNames("") -> {}
          - * 
          - * 
          - * - * @param name the name - * @return the list of simple names, possibly empty - * @exception NullPointerException if name is null - */ -public static String[] getSimpleNames(String name) { - char[][] simpleNames = getSimpleNames(name.toCharArray()); - int length = simpleNames.length; - String[] result = new String[length]; - for (int i = 0; i < length; i++) { - result[i] = new String(simpleNames[i]); + + /** + * Returns all segments of the given dot-separated qualified name. Returns + * an array with only the given name if it is not qualified. Returns an + * empty array if the name is empty. + *

          + * For example: + * + *

          +	 * 
          +	 *  getSimpleNames("java.lang.Object") -> {"java", "lang", "Object"}
          +	 *  getSimpleNames("Object") -> {"Object"}
          +	 *  getSimpleNames("") -> {}
          +	 * 
          +	 * 
          + * + * @param name + * the name + * @return the list of simple names, possibly empty + * @exception NullPointerException + * if name is null + */ + public static String[] getSimpleNames(String name) { + char[][] simpleNames = getSimpleNames(name.toCharArray()); + int length = simpleNames.length; + String[] result = new String[length]; + for (int i = 0; i < length; i++) { + result[i] = new String(simpleNames[i]); + } + return result; } - return result; -} -/** - * Converts the given method signature to a readable form. The method signature is expected to - * be dot-based. - *

          - * For example: - *

          - * 
          - * toString("([Ljava.lang.String;)V", "main", new String[] {"args"}, false, true) -> "void main(String[] args)"
          - * 
          - * 
          - *

          - * - * @param methodSignature the method signature to convert - * @param methodName the name of the method to insert in the result, or - * null if no method name is to be included - * @param parameterNames the parameter names to insert in the result, or - * null if no parameter names are to be included; if supplied, - * the number of parameter names must match that of the method signature - * @param fullyQualifyTypeNames true if type names should be fully - * qualified, and false to use only simple names - * @param includeReturnType true if the return type is to be - * included - * @return the char array representation of the method signature - * - * @since 2.0 - */ -public static char[] toCharArray(char[] methodSignature, char[] methodName, char[][] parameterNames, boolean fullyQualifyTypeNames, boolean includeReturnType) { - try { - int firstParen = CharOperation.indexOf(C_PARAM_START, methodSignature); - if (firstParen == -1) throw new IllegalArgumentException(); - - int sigLength = methodSignature.length; - - // compute result length - - // method signature - int paramCount = 0; - int lastParen = -1; - int resultLength = 0; - signature: for (int i = firstParen; i < sigLength; i++) { - switch (methodSignature[i]) { - case C_ARRAY : + + /** + * Converts the given method signature to a readable form. The method + * signature is expected to be dot-based. + *

          + * For example: + * + *

          +	 * 
          +	 *  toString("([Ljava.lang.String;)V", "main", new String[] {"args"}, false, true) -> "void main(String[] args)"
          +	 * 
          +	 * 
          + * + *

          + * + * @param methodSignature + * the method signature to convert + * @param methodName + * the name of the method to insert in the result, or + * null if no method name is to be included + * @param parameterNames + * the parameter names to insert in the result, or + * null if no parameter names are to be included; + * if supplied, the number of parameter names must match that of + * the method signature + * @param fullyQualifyTypeNames + * true if type names should be fully qualified, + * and false to use only simple names + * @param includeReturnType + * true if the return type is to be included + * @return the char array representation of the method signature + * + * @since 2.0 + */ + public static char[] toCharArray(char[] methodSignature, char[] methodName, + char[][] parameterNames, boolean fullyQualifyTypeNames, + boolean includeReturnType) { + try { + int firstParen = CharOperation.indexOf(C_PARAM_START, + methodSignature); + if (firstParen == -1) + throw new IllegalArgumentException(); + + int sigLength = methodSignature.length; + + // compute result length + + // method signature + int paramCount = 0; + int lastParen = -1; + int resultLength = 0; + signature: for (int i = firstParen; i < sigLength; i++) { + switch (methodSignature[i]) { + case C_ARRAY: resultLength += 2; // [] continue signature; - case C_BOOLEAN : + case C_BOOLEAN: resultLength += BOOLEAN.length; break; - case C_BYTE : + case C_BYTE: resultLength += BYTE.length; break; - case C_CHAR : + case C_CHAR: resultLength += CHAR.length; break; - case C_DOUBLE : + case C_DOUBLE: resultLength += DOUBLE.length; break; - case C_FLOAT : + case C_FLOAT: resultLength += FLOAT.length; break; - case C_INT : + case C_INT: resultLength += INT.length; break; - case C_LONG : + case C_LONG: resultLength += LONG.length; break; - case C_SHORT : + case C_SHORT: resultLength += SHORT.length; break; - case C_VOID : + case C_VOID: resultLength += VOID.length; break; - case C_RESOLVED : - case C_UNRESOLVED : - int end = CharOperation.indexOf(C_SEMICOLON, methodSignature, i); - if (end == -1) throw new IllegalArgumentException(); + case C_RESOLVED: + case C_UNRESOLVED: + int end = CharOperation.indexOf(C_SEMICOLON, + methodSignature, i); + if (end == -1) + throw new IllegalArgumentException(); int start; if (fullyQualifyTypeNames) { - start = i+1; + start = i + 1; } else { - start = CharOperation.lastIndexOf(C_DOT, methodSignature, i, end) + 1; - if (start == 0) start = i+1; - } - resultLength += end-start; + start = CharOperation.lastIndexOf(C_DOT, + methodSignature, i, end) + 1; + if (start == 0) + start = i + 1; + } + resultLength += end - start; i = end; break; - case C_PARAM_START : + case C_PARAM_START: // add space for "(" resultLength++; continue signature; - case C_PARAM_END : + case C_PARAM_END: lastParen = i; if (includeReturnType) { if (paramCount > 0) { - // remove space for ", " that was added with last parameter and remove space that is going to be added for ", " after return type + // remove space for ", " that was added with last + // parameter and remove space that is going to be + // added for ", " after return type // and add space for ") " resultLength -= 2; - } //else - // remove space that is going to be added for ", " after return type - // and add space for ") " - // -> noop - - // decrement param count because it is going to be added for return type + } // else + // remove space that is going to be added for ", " after + // return type + // and add space for ") " + // -> noop + + // decrement param count because it is going to be added + // for return type paramCount--; continue signature; } else { if (paramCount > 0) { - // remove space for ", " that was added with last parameter and add space for ")" + // remove space for ", " that was added with last + // parameter and add space for ")" resultLength--; } else { // add space for ")" @@ -1138,297 +1298,338 @@ public static char[] toCharArray(char[] methodSignature, char[] methodName, char } break signature; } - default : + default: throw new IllegalArgumentException(); + } + resultLength += 2; // add space for ", " + paramCount++; } - resultLength += 2; // add space for ", " - paramCount++; - } - - // parameter names - int parameterNamesLength = parameterNames == null ? 0 : parameterNames.length; - for (int i = 0; i >> 32); - result[index++] = ' '; - } - - // selector - if (methodName != null) { - System.arraycopy(methodName, 0, result, index, selectorLength); - index += selectorLength; - } - - // parameters - result[index++] = C_PARAM_START; - int sigPos = firstParen+1; - for (int i = 0; i < paramCount; i++) { - long pos = copyType(methodSignature, sigPos, result, index, fullyQualifyTypeNames); - index = (int) (pos >>> 32); - sigPos = (int)pos; - if (parameterNames != null) { - result[index++] = ' '; - char[] parameterName = parameterNames[i]; - int paramLength = parameterName.length; - System.arraycopy(parameterName, 0, result, index, paramLength); - index += paramLength; + + // parameter names + int parameterNamesLength = parameterNames == null ? 0 + : parameterNames.length; + for (int i = 0; i < parameterNamesLength; i++) { + resultLength += parameterNames[i].length + 1; // parameter + // name + space } - if (i != paramCount-1) { - result[index++] = ','; + + // selector + int selectorLength = methodName == null ? 0 : methodName.length; + resultLength += selectorLength; + + // create resulting char array + char[] result = new char[resultLength]; + + // returned type + int index = 0; + if (includeReturnType) { + long pos = copyType(methodSignature, lastParen + 1, result, + index, fullyQualifyTypeNames); + index = (int) (pos >>> 32); result[index++] = ' '; } - } - if (sigPos >= sigLength) { - throw new IllegalArgumentException(); // should be on last paren - } - result[index++] = C_PARAM_END; - - return result; - } catch (ArrayIndexOutOfBoundsException e) { - throw new IllegalArgumentException(); - } -} -/** - * Converts the given type signature to a readable string. The signature is expected to - * be dot-based. - * - *

          - * For example: - *

          - * 
          - * toString({'[', 'L', 'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'S', 't', 'r', 'i', 'n', 'g', ';'}) -> {'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'S', 't', 'r', 'i', 'n', 'g', '[', ']'}
          - * toString({'I'}) -> {'i', 'n', 't'}
          - * 
          - * 
          - *

          - *

          - * Note: This method assumes that a type signature containing a '$' - * is an inner type signature. While this is correct in most cases, someone could - * define a non-inner type name containing a '$'. Handling this - * correctly in all cases would have required resolving the signature, which - * generally not feasible. - *

          - * - * @param signature the type signature - * @return the string representation of the type - * @exception IllegalArgumentException if the signature is not syntactically - * correct - * - * @since 2.0 - */ -public static char[] toCharArray(char[] signature) throws IllegalArgumentException { - try { - int sigLength = signature.length; - if (sigLength == 0 || signature[0] == C_PARAM_START) { - return toCharArray(signature, CharOperation.NO_CHAR, null, true, true); - } - - // compute result length - int resultLength = 0; - int index = -1; - while (signature[++index] == C_ARRAY) { - resultLength += 2; // [] + // selector + if (methodName != null) { + System.arraycopy(methodName, 0, result, index, selectorLength); + index += selectorLength; + } + + // parameters + result[index++] = C_PARAM_START; + int sigPos = firstParen + 1; + for (int i = 0; i < paramCount; i++) { + long pos = copyType(methodSignature, sigPos, result, index, + fullyQualifyTypeNames); + index = (int) (pos >>> 32); + sigPos = (int) pos; + if (parameterNames != null) { + result[index++] = ' '; + char[] parameterName = parameterNames[i]; + int paramLength = parameterName.length; + System.arraycopy(parameterName, 0, result, index, + paramLength); + index += paramLength; + } + if (i != paramCount - 1) { + result[index++] = ','; + result[index++] = ' '; + } + } + if (sigPos >= sigLength) { + throw new IllegalArgumentException(); // should be on last + // paren + } + result[index++] = C_PARAM_END; + + return result; + } catch (ArrayIndexOutOfBoundsException e) { + throw new IllegalArgumentException(); } - switch (signature[index]) { - case C_BOOLEAN : + } + + /** + * Converts the given type signature to a readable string. The signature is + * expected to be dot-based. + * + *

          + * For example: + * + *

          +	 * 
          +	 *  toString({'[', 'L', 'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'S', 't', 'r', 'i', 'n', 'g', ';'}) -> {'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'S', 't', 'r', 'i', 'n', 'g', '[', ']'}
          +	 *  toString({'I'}) -> {'i', 'n', 't'}
          +	 * 
          +	 * 
          + * + *

          + *

          + * Note: This method assumes that a type signature containing a + * '$' is an inner type signature. While this is correct in + * most cases, someone could define a non-inner type name containing a + * '$'. Handling this correctly in all cases would have + * required resolving the signature, which generally not feasible. + *

          + * + * @param signature + * the type signature + * @return the string representation of the type + * @exception IllegalArgumentException + * if the signature is not syntactically correct + * + * @since 2.0 + */ + public static char[] toCharArray(char[] signature) + throws IllegalArgumentException { + try { + int sigLength = signature.length; + + if (sigLength == 0 || signature[0] == C_PARAM_START) { + return toCharArray(signature, CharOperation.NO_CHAR, null, + true, true); + } + + // compute result length + int resultLength = 0; + int index = -1; + while (signature[++index] == C_ARRAY) { + resultLength += 2; // [] + } + switch (signature[index]) { + case C_BOOLEAN: resultLength += BOOLEAN.length; break; - case C_BYTE : + case C_BYTE: resultLength += BYTE.length; break; - case C_CHAR : + case C_CHAR: resultLength += CHAR.length; break; - case C_DOUBLE : + case C_DOUBLE: resultLength += DOUBLE.length; break; - case C_FLOAT : + case C_FLOAT: resultLength += FLOAT.length; break; - case C_INT : + case C_INT: resultLength += INT.length; break; - case C_LONG : + case C_LONG: resultLength += LONG.length; break; - case C_SHORT : + case C_SHORT: resultLength += SHORT.length; break; - case C_VOID : + case C_VOID: resultLength += VOID.length; break; - case C_RESOLVED : - case C_UNRESOLVED : + case C_RESOLVED: + case C_UNRESOLVED: int end = CharOperation.indexOf(C_SEMICOLON, signature, index); - if (end == -1) throw new IllegalArgumentException(); + if (end == -1) + throw new IllegalArgumentException(); int start = index + 1; - resultLength += end-start; + resultLength += end - start; break; - default : + default: throw new IllegalArgumentException(); + } + + char[] result = new char[resultLength]; + copyType(signature, 0, result, 0, true); + + /** + * Converts '$' separated type signatures into '.' separated type + * signature. NOTE: This assumes that the type signature is an inner + * type signature. This is true in most cases, but someone can + * define a non-inner type name containing a '$'. However to tell + * the difference, we would have to resolve the signature, which + * cannot be done at this point. + */ + CharOperation.replace(result, C_DOLLAR, C_DOT); + + return result; + } catch (ArrayIndexOutOfBoundsException e) { + throw new IllegalArgumentException(); } - - char[] result = new char[resultLength]; - copyType(signature, 0, result, 0, true); + } - /** - * Converts '$' separated type signatures into '.' separated type signature. - * NOTE: This assumes that the type signature is an inner type signature. - * This is true in most cases, but someone can define a non-inner type - * name containing a '$'. However to tell the difference, we would have - * to resolve the signature, which cannot be done at this point. - */ - CharOperation.replace(result, C_DOLLAR, C_DOT); + /** + * Converts the given array of qualified name segments to a qualified name. + *

          + * For example: + * + *

          +	 * 
          +	 *  toQualifiedName({{'j', 'a', 'v', 'a'}, {'l', 'a', 'n', 'g'}, {'O', 'b', 'j', 'e', 'c', 't'}}) -> {'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'O', 'b', 'j', 'e', 'c', 't'}
          +	 *  toQualifiedName({{'O', 'b', 'j', 'e', 'c', 't'}}) -> {'O', 'b', 'j', 'e', 'c', 't'}
          +	 *  toQualifiedName({{}}) -> {}
          +	 * 
          +	 * 
          + * + *

          + * + * @param segments + * the list of name segments, possibly empty + * @return the dot-separated qualified name, or the empty string + * + * @since 2.0 + */ + public static char[] toQualifiedName(char[][] segments) { + int length = segments.length; + if (length == 0) + return CharOperation.NO_CHAR; + if (length == 1) + return segments[0]; + int resultLength = 0; + for (int i = 0; i < length; i++) { + resultLength += segments[i].length + 1; + } + resultLength--; + char[] result = new char[resultLength]; + int index = 0; + for (int i = 0; i < length; i++) { + char[] segment = segments[i]; + int segmentLength = segment.length; + System.arraycopy(segment, 0, result, index, segmentLength); + index += segmentLength; + if (i != length - 1) { + result[index++] = C_DOT; + } + } return result; - } catch (ArrayIndexOutOfBoundsException e) { - throw new IllegalArgumentException(); - } -} -/** - * Converts the given array of qualified name segments to a qualified name. - *

          - * For example: - *

          - * 
          - * toQualifiedName({{'j', 'a', 'v', 'a'}, {'l', 'a', 'n', 'g'}, {'O', 'b', 'j', 'e', 'c', 't'}}) -> {'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'O', 'b', 'j', 'e', 'c', 't'}
          - * toQualifiedName({{'O', 'b', 'j', 'e', 'c', 't'}}) -> {'O', 'b', 'j', 'e', 'c', 't'}
          - * toQualifiedName({{}}) -> {}
          - * 
          - * 
          - *

          - * - * @param segments the list of name segments, possibly empty - * @return the dot-separated qualified name, or the empty string - * - * @since 2.0 - */ -public static char[] toQualifiedName(char[][] segments) { - int length = segments.length; - if (length == 0) return CharOperation.NO_CHAR; - if (length == 1) return segments[0]; - - int resultLength = 0; - for (int i = 0; i < length; i++) { - resultLength += segments[i].length+1; } - resultLength--; - char[] result = new char[resultLength]; - int index = 0; - for (int i = 0; i < length; i++) { - char[] segment = segments[i]; - int segmentLength = segment.length; - System.arraycopy(segment, 0, result, index, segmentLength); - index += segmentLength; - if (i != length-1) { - result[index++] = C_DOT; + + /** + * Converts the given array of qualified name segments to a qualified name. + *

          + * For example: + * + *

          +	 * 
          +	 *  toQualifiedName(new String[] {"java", "lang", "Object"}) -> "java.lang.Object"
          +	 *  toQualifiedName(new String[] {"Object"}) -> "Object"
          +	 *  toQualifiedName(new String[0]) -> ""
          +	 * 
          +	 * 
          + * + *

          + * + * @param segments + * the list of name segments, possibly empty + * @return the dot-separated qualified name, or the empty string + */ + public static String toQualifiedName(String[] segments) { + int length = segments.length; + char[][] charArrays = new char[length][]; + for (int i = 0; i < length; i++) { + charArrays[i] = segments[i].toCharArray(); } + return new String(toQualifiedName(charArrays)); } - return result; -} -/** - * Converts the given array of qualified name segments to a qualified name. - *

          - * For example: - *

          - * 
          - * toQualifiedName(new String[] {"java", "lang", "Object"}) -> "java.lang.Object"
          - * toQualifiedName(new String[] {"Object"}) -> "Object"
          - * toQualifiedName(new String[0]) -> ""
          - * 
          - * 
          - *

          - * - * @param segments the list of name segments, possibly empty - * @return the dot-separated qualified name, or the empty string - */ -public static String toQualifiedName(String[] segments) { - int length = segments.length; - char[][] charArrays = new char[length][]; - for (int i = 0; i < length; i++) { - charArrays[i] = segments[i].toCharArray(); + + /** + * Converts the given type signature to a readable string. The signature is + * expected to be dot-based. + * + *

          + * For example: + * + *

          +	 * 
          +	 *  toString("[Ljava.lang.String;") -> "java.lang.String[]"
          +	 *  toString("I") -> "int"
          +	 * 
          +	 * 
          + * + *

          + *

          + * Note: This method assumes that a type signature containing a + * '$' is an inner type signature. While this is correct in + * most cases, someone could define a non-inner type name containing a + * '$'. Handling this correctly in all cases would have + * required resolving the signature, which generally not feasible. + *

          + * + * @param signature + * the type signature + * @return the string representation of the type + * @exception IllegalArgumentException + * if the signature is not syntactically correct + */ + public static String toString(String signature) + throws IllegalArgumentException { + // return new String(toCharArray(signature.toCharArray())); + return ""; } - return new String(toQualifiedName(charArrays)); -} -/** - * Converts the given type signature to a readable string. The signature is expected to - * be dot-based. - * - *

          - * For example: - *

          - * 
          - * toString("[Ljava.lang.String;") -> "java.lang.String[]"
          - * toString("I") -> "int"
          - * 
          - * 
          - *

          - *

          - * Note: This method assumes that a type signature containing a '$' - * is an inner type signature. While this is correct in most cases, someone could - * define a non-inner type name containing a '$'. Handling this - * correctly in all cases would have required resolving the signature, which - * generally not feasible. - *

          - * - * @param signature the type signature - * @return the string representation of the type - * @exception IllegalArgumentException if the signature is not syntactically - * correct - */ -public static String toString(String signature) throws IllegalArgumentException { -// return new String(toCharArray(signature.toCharArray())); - return ""; -} -/** - * Converts the given method signature to a readable string. The method signature is expected to - * be dot-based. - *

          - * For example: - *

          - * 
          - * toString("([Ljava.lang.String;)V", "main", new String[] {"args"}, false, true) -> "void main(String[] args)"
          - * 
          - * 
          - *

          - * - * @param methodSignature the method signature to convert - * @param methodName the name of the method to insert in the result, or - * null if no method name is to be included - * @param parameterNames the parameter names to insert in the result, or - * null if no parameter names are to be included; if supplied, - * the number of parameter names must match that of the method signature - * @param fullyQualifyTypeNames true if type names should be fully - * qualified, and false to use only simple names - * @param includeReturnType true if the return type is to be - * included - * @return the string representation of the method signature - */ -public static String toString(String methodSignature, String methodName, String[] parameterNames, boolean fullyQualifyTypeNames, boolean includeReturnType) { - char[][] params; - if (parameterNames == null) { - params = null; - } else { - int paramLength = parameterNames.length; - params = new char[paramLength][]; - for (int i = 0; i < paramLength; i++) { - params[i] = parameterNames[i].toCharArray(); + + /** + * Converts the given method signature to a readable string. The method + * signature is expected to be dot-based. + *

          + * For example: + * + *

          +	 * 
          +	 *  toString("([Ljava.lang.String;)V", "main", new String[] {"args"}, false, true) -> "void main(String[] args)"
          +	 * 
          +	 * 
          + * + *

          + * + * @param methodSignature + * the method signature to convert + * @param methodName + * the name of the method to insert in the result, or + * null if no method name is to be included + * @param parameterNames + * the parameter names to insert in the result, or + * null if no parameter names are to be included; + * if supplied, the number of parameter names must match that of + * the method signature + * @param fullyQualifyTypeNames + * true if type names should be fully qualified, + * and false to use only simple names + * @param includeReturnType + * true if the return type is to be included + * @return the string representation of the method signature + */ + public static String toString(String methodSignature, String methodName, + String[] parameterNames, boolean fullyQualifyTypeNames, + boolean includeReturnType) { + char[][] params; + if (parameterNames == null) { + params = null; + } else { + int paramLength = parameterNames.length; + params = new char[paramLength][]; + for (int i = 0; i < paramLength; i++) { + params[i] = parameterNames[i].toCharArray(); + } } + return new String(toCharArray(methodSignature.toCharArray(), + methodName == null ? null : methodName.toCharArray(), params, + fullyQualifyTypeNames, includeReturnType)); } - return new String(toCharArray(methodSignature.toCharArray(), methodName == null ? null : methodName.toCharArray(), params, fullyQualifyTypeNames, includeReturnType)); -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ToolFactory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ToolFactory.java index aea8d2e..34590c9 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ToolFactory.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ToolFactory.java @@ -10,7 +10,7 @@ * IBM Corporation - added #createScanner allowing to make comment check stricter ******************************************************************************/ package net.sourceforge.phpdt.core; - + import java.util.Map; import net.sourceforge.phpdt.internal.compiler.parser.Scanner; @@ -19,9 +19,11 @@ import net.sourceforge.phpdt.internal.formatter.CodeFormatter; import org.eclipse.core.runtime.Plugin; /** - * Factory for creating various compiler tools, such as scanners, parsers and compilers. + * Factory for creating various compiler tools, such as scanners, parsers and + * compilers. *

          - * This class provides static methods only; it is not intended to be instantiated or subclassed by clients. + * This class provides static methods only; it is not intended to be + * instantiated or subclassed by clients. *

          * * @since 2.0 @@ -29,142 +31,183 @@ import org.eclipse.core.runtime.Plugin; public class ToolFactory { /** - * Create an instance of a code formatter. A code formatter implementation can be contributed via the - * extension point "org.phpeclipse.phpdt.core.codeFormatter". If unable to find a registered extension, the factory - * will default to using the default code formatter. + * Create an instance of a code formatter. A code formatter implementation + * can be contributed via the extension point + * "org.phpeclipse.phpdt.core.codeFormatter". If unable to find a registered + * extension, the factory will default to using the default code formatter. * * @return an instance of a code formatter * @see ICodeFormatter * @see ToolFactory#createDefaultCodeFormatter(Map) */ - public static ICodeFormatter createCodeFormatter(){ - - Plugin jdtCorePlugin = JavaCore.getPlugin(); - if (jdtCorePlugin == null) return null; - -// IExtensionPoint extension = jdtCorePlugin.getDescriptor().getExtensionPoint(JavaModelManager.FORMATTER_EXTPOINT_ID); -// if (extension != null) { -// IExtension[] extensions = extension.getExtensions(); -// for(int i = 0; i < extensions.length; i++){ -// IConfigurationElement [] configElements = extensions[i].getConfigurationElements(); -// for(int j = 0; j < configElements.length; j++){ -// try { -// Object execExt = configElements[j].createExecutableExtension("class"); //$NON-NLS-1$ -// if (execExt instanceof ICodeFormatter){ -// // use first contribution found -// return (ICodeFormatter)execExt; -// } -// } catch(CoreException e){ -// } -// } -// } -// } - // no proper contribution found, use default formatter + public static ICodeFormatter createCodeFormatter() { + + Plugin jdtCorePlugin = JavaCore.getPlugin(); + if (jdtCorePlugin == null) + return null; + + // IExtensionPoint extension = + // jdtCorePlugin.getDescriptor().getExtensionPoint(JavaModelManager.FORMATTER_EXTPOINT_ID); + // if (extension != null) { + // IExtension[] extensions = extension.getExtensions(); + // for(int i = 0; i < extensions.length; i++){ + // IConfigurationElement [] configElements = + // extensions[i].getConfigurationElements(); + // for(int j = 0; j < configElements.length; j++){ + // try { + // Object execExt = + // configElements[j].createExecutableExtension("class"); //$NON-NLS-1$ + // if (execExt instanceof ICodeFormatter){ + // // use first contribution found + // return (ICodeFormatter)execExt; + // } + // } catch(CoreException e){ + // } + // } + // } + // } + // no proper contribution found, use default formatter return createDefaultCodeFormatter(null); } /** - * Create an instance of the built-in code formatter. A code formatter implementation can be contributed via the - * extension point "org.phpeclipse.phpdt.core.codeFormatter". If unable to find a registered extension, the factory will - * default to using the default code formatter. + * Create an instance of the built-in code formatter. A code formatter + * implementation can be contributed via the extension point + * "org.phpeclipse.phpdt.core.codeFormatter". If unable to find a registered + * extension, the factory will default to using the default code formatter. * - * @param options - the options map to use for formatting with the default code formatter. Recognized options - * are documented on JavaCore#getDefaultOptions(). If set to null, then use - * the current settings from JavaCore#getOptions. + * @param options - + * the options map to use for formatting with the default code + * formatter. Recognized options are documented on + * JavaCore#getDefaultOptions(). If set to + * null, then use the current settings from + * JavaCore#getOptions. * @return an instance of the built-in code formatter * @see ICodeFormatter * @see ToolFactory#createCodeFormatter() * @see JavaCore#getOptions() */ - public static ICodeFormatter createDefaultCodeFormatter(Map options){ + public static ICodeFormatter createDefaultCodeFormatter(Map options) { - if (options == null) options = JavaCore.getOptions(); + if (options == null) + options = JavaCore.getOptions(); return new CodeFormatter(options); } - + /** - * Create a scanner, indicating the level of detail requested for tokenizing. The scanner can then be - * used to tokenize some source in a Java aware way. - * Here is a typical scanning loop: + * Create a scanner, indicating the level of detail requested for + * tokenizing. The scanner can then be used to tokenize some source in a + * Java aware way. Here is a typical scanning loop: * * *
          -	 *   IScanner scanner = ToolFactory.createScanner(false, false, false, false);
          -	 *   scanner.setSource("int i = 0;".toCharArray());
          -	 *   while (true) {
          -	 *     int token = scanner.getNextToken();
          -	 *     if (token == ITerminalSymbols.TokenNameEOF) break;
          -	 *     System.out.println(token + " : " + new String(scanner.getCurrentTokenSource()));
          -	 *   }
          +	 * IScanner scanner = ToolFactory.createScanner(false, false, false, false);
          +	 * scanner.setSource("int i = 0;".toCharArray());
          +	 * while (true) {
          +	 * 	int token = scanner.getNextToken();
          +	 * 	if (token == ITerminalSymbols.TokenNameEOF)
          +	 * 		break;
          +	 * 	System.out.println(token + " : "
          +	 * 			+ new String(scanner.getCurrentTokenSource()));
          +	 * }
           	 * 
          *
          * *

          - * The returned scanner will tolerate unterminated line comments (missing line separator). It can be made stricter - * by using API with extra boolean parameter (strictCommentMode). + * The returned scanner will tolerate unterminated line comments (missing + * line separator). It can be made stricter by using API with extra boolean + * parameter (strictCommentMode). *

          - * @param tokenizeComments if set to false, comments will be silently consumed - * @param tokenizeWhiteSpace if set to false, white spaces will be silently consumed, - * @param assertKeyword if set to false, occurrences of 'assert' will be reported as identifiers - * (ITerminalSymbols#TokenNameIdentifier), whereas if set to true, it - * would report assert keywords (ITerminalSymbols#TokenNameassert). Java 1.4 has introduced - * a new 'assert' keyword. - * @param recordLineSeparator if set to true, the scanner will record positions of encountered line - * separator ends. In case of multi-character line separators, the last character position is considered. These positions - * can then be extracted using IScanner#getLineEnds. Only non-unicode escape sequences are - * considered as valid line separators. - * @return a scanner + * + * @param tokenizeComments + * if set to false, comments will be silently + * consumed + * @param tokenizeWhiteSpace + * if set to false, white spaces will be silently + * consumed, + * @param assertKeyword + * if set to false, occurrences of 'assert' will + * be reported as identifiers (ITerminalSymbols#TokenNameIdentifier), + * whereas if set to true, it would report assert + * keywords (ITerminalSymbols#TokenNameassert). + * Java 1.4 has introduced a new 'assert' keyword. + * @param recordLineSeparator + * if set to true, the scanner will record + * positions of encountered line separator ends. In case of + * multi-character line separators, the last character position + * is considered. These positions can then be extracted using + * IScanner#getLineEnds. Only non-unicode escape + * sequences are considered as valid line separators. + * @return a scanner * @see ToolFactory#createScanner(boolean,boolean,boolean,boolean, boolean) * @see org.phpeclipse.phpdt.core.compiler.IScanner */ -// public static IScanner createScanner(boolean tokenizeComments, boolean tokenizeWhiteSpace, boolean recordLineSeparator){ -// return createScanner(tokenizeComments, tokenizeWhiteSpace, recordLineSeparator); -// } - + // public static IScanner createScanner(boolean tokenizeComments, boolean + // tokenizeWhiteSpace, boolean recordLineSeparator){ + // return createScanner(tokenizeComments, tokenizeWhiteSpace, + // recordLineSeparator); + // } /** - * Create a scanner, indicating the level of detail requested for tokenizing. The scanner can then be - * used to tokenize some source in a Java aware way. - * Here is a typical scanning loop: + * Create a scanner, indicating the level of detail requested for + * tokenizing. The scanner can then be used to tokenize some source in a + * Java aware way. Here is a typical scanning loop: * * *

          -	 *   IScanner scanner = ToolFactory.createScanner(false, false, false, false);
          -	 *   scanner.setSource("int i = 0;".toCharArray());
          -	 *   while (true) {
          -	 *     int token = scanner.getNextToken();
          -	 *     if (token == ITerminalSymbols.TokenNameEOF) break;
          -	 *     System.out.println(token + " : " + new String(scanner.getCurrentTokenSource()));
          -	 *   }
          +	 * IScanner scanner = ToolFactory.createScanner(false, false, false, false);
          +	 * scanner.setSource("int i = 0;".toCharArray());
          +	 * while (true) {
          +	 * 	int token = scanner.getNextToken();
          +	 * 	if (token == ITerminalSymbols.TokenNameEOF)
          +	 * 		break;
          +	 * 	System.out.println(token + " : "
          +	 * 			+ new String(scanner.getCurrentTokenSource()));
          +	 * }
           	 * 
          * * - * @param tokenizeComments if set to false, comments will be silently consumed - * @param tokenizeWhiteSpace if set to false, white spaces will be silently consumed, - * @param assertMode if set to false, occurrences of 'assert' will be reported as identifiers - * (ITerminalSymbols#TokenNameIdentifier), whereas if set to true, it - * would report assert keywords (ITerminalSymbols#TokenNameassert). Java 1.4 has introduced - * a new 'assert' keyword. - * @param recordLineSeparator if set to true, the scanner will record positions of encountered line - * separator ends. In case of multi-character line separators, the last character position is considered. These positions - * can then be extracted using IScanner#getLineEnds. Only non-unicode escape sequences are - * considered as valid line separators. - * @param strictCommentMode if set to true, line comments with no trailing line separator will be - * treated as invalid tokens. - * @return a scanner + * @param tokenizeComments + * if set to false, comments will be silently + * consumed + * @param tokenizeWhiteSpace + * if set to false, white spaces will be silently + * consumed, + * @param assertMode + * if set to false, occurrences of 'assert' will + * be reported as identifiers (ITerminalSymbols#TokenNameIdentifier), + * whereas if set to true, it would report assert + * keywords (ITerminalSymbols#TokenNameassert). + * Java 1.4 has introduced a new 'assert' keyword. + * @param recordLineSeparator + * if set to true, the scanner will record + * positions of encountered line separator ends. In case of + * multi-character line separators, the last character position + * is considered. These positions can then be extracted using + * IScanner#getLineEnds. Only non-unicode escape + * sequences are considered as valid line separators. + * @param strictCommentMode + * if set to true, line comments with no trailing + * line separator will be treated as invalid tokens. + * @return a scanner * * @see org.phpeclipse.phpdt.core.compiler.IScanner * @since 2.1 */ - public static Scanner createScanner(boolean tokenizeComments, boolean tokenizeWhiteSpace, boolean recordLineSeparator){ + public static Scanner createScanner(boolean tokenizeComments, + boolean tokenizeWhiteSpace, boolean recordLineSeparator) { - Scanner scanner = new Scanner(tokenizeComments, tokenizeWhiteSpace, false/*nls*/); + Scanner scanner = new Scanner(tokenizeComments, tokenizeWhiteSpace, + false/* nls */); scanner.recordLineSeparator = recordLineSeparator; return scanner; } - - public static Scanner createScanner(boolean tokenizeComments, boolean tokenizeWhiteSpace, boolean recordLineSeparator, boolean phpMode){ - Scanner scanner = new Scanner(tokenizeComments, tokenizeWhiteSpace, false/*nls*/); + public static Scanner createScanner(boolean tokenizeComments, + boolean tokenizeWhiteSpace, boolean recordLineSeparator, + boolean phpMode) { + + Scanner scanner = new Scanner(tokenizeComments, tokenizeWhiteSpace, + false/* nls */); scanner.recordLineSeparator = recordLineSeparator; scanner.setPHPMode(phpMode); return scanner; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/WorkingCopyOwner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/WorkingCopyOwner.java index e1688f6..4463023 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/WorkingCopyOwner.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/WorkingCopyOwner.java @@ -14,57 +14,69 @@ import net.sourceforge.phpdt.internal.core.BufferManager; import net.sourceforge.phpdt.internal.core.DefaultWorkingCopyOwner; /** - * The owner of an ICompilationUnit handle in working copy mode. + * The owner of an ICompilationUnit handle in working copy mode. * An owner is used to identify a working copy and to create its buffer. *

          - * Clients should subclass this class to instantiate a working copy owner that is specific to their need and that - * they can pass in to various APIs (e.g. IType.resolveType(String, WorkingCopyOwner). - * Clients can also override the default implementation of createBuffer(ICompilationUnit). - *

          - * Note: even though this class has no abstract method, which means that it provides functional default behvior, - * it is still an abstract class, as clients are intended to own their owner implementation. + * Clients should subclass this class to instantiate a working copy owner that + * is specific to their need and that they can pass in to various APIs (e.g. + * IType.resolveType(String, WorkingCopyOwner). Clients can also + * override the default implementation of + * createBuffer(ICompilationUnit). *

          - * @see ICompilationUnit#becomeWorkingCopy(IProblemRequestor, org.eclipse.core.runtime.IProgressMonitor) + *

          + * Note: even though this class has no abstract method, which means that it + * provides functional default behvior, it is still an abstract class, as + * clients are intended to own their owner implementation. + *

          + * + * @see ICompilationUnit#becomeWorkingCopy(IProblemRequestor, + * org.eclipse.core.runtime.IProgressMonitor) * @see ICompilationUnit#discardWorkingCopy() * @see ICompilationUnit#getWorkingCopy(org.eclipse.core.runtime.IProgressMonitor) * @since 3.0 */ public abstract class WorkingCopyOwner { - + /** - * Sets the buffer provider of the primary working copy owner. Note that even if the - * buffer provider is a working copy owner, only its createBuffer(ICompilationUnit) - * method is used by the primary working copy owner. It doesn't replace the internal primary + * Sets the buffer provider of the primary working copy owner. Note that + * even if the buffer provider is a working copy owner, only its + * createBuffer(ICompilationUnit) method is used by the + * primary working copy owner. It doesn't replace the internal primary * working owner. - *

          - * This method is for internal use by the jdt-related plug-ins. - * Clients outside of the jdt should not reference this method. + *

          + * This method is for internal use by the jdt-related plug-ins. Clients + * outside of the jdt should not reference this method. *

          * - * @param primaryBufferProvider the primary buffer provider + * @param primaryBufferProvider + * the primary buffer provider */ - public static void setPrimaryBufferProvider(WorkingCopyOwner primaryBufferProvider) { + public static void setPrimaryBufferProvider( + WorkingCopyOwner primaryBufferProvider) { DefaultWorkingCopyOwner.PRIMARY.primaryBufferProvider = primaryBufferProvider; } - + /** - * Creates a buffer for the given working copy. - * The new buffer will be initialized with the contents of the underlying file - * if and only if it was not already initialized by the compilation owner (a buffer is + * Creates a buffer for the given working copy. The new buffer will be + * initialized with the contents of the underlying file if and only if it + * was not already initialized by the compilation owner (a buffer is * uninitialized if its content is null). *

          - * Note: This buffer will be associated to the working copy for its entire life-cycle. Another - * working copy on same unit but owned by a different owner would not share the same buffer - * unless its owner decided to implement such a sharing behaviour. + * Note: This buffer will be associated to the working copy for its entire + * life-cycle. Another working copy on same unit but owned by a different + * owner would not share the same buffer unless its owner decided to + * implement such a sharing behaviour. *

          * - * @param workingCopy the working copy of the buffer + * @param workingCopy + * the working copy of the buffer * @return IBuffer the created buffer for the given working copy * @see IBuffer */ public IBuffer createBuffer(ICompilationUnit workingCopy) { - return BufferManager.getDefaultBufferManager().createBuffer(workingCopy); + return BufferManager.getDefaultBufferManager() + .createBuffer(workingCopy); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/CharOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/CharOperation.java index ae0ed10..75fe787 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/CharOperation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/CharOperation.java @@ -26,28 +26,37 @@ public final class CharOperation { * Constant for an empty char array with two dimensions. */ public static final char[][] NO_CHAR_CHAR = new char[0][]; - + /** - * Answers a new array with appending the suffix character at the end of the array. - *
          + * Answers a new array with appending the suffix character at the end of the + * array.
          *
          * For example:
          *
            - *
          1. -	 *    array = { 'a', 'b' }
            -	 *    suffix = 'c'
            -	 *    => result = { 'a', 'b' , 'c' }
            +	 * 
          2. + * + *
            +	 *     array = { 'a', 'b' }
            +	 *     suffix = 'c'
            +	 *     => result = { 'a', 'b' , 'c' }
            +	 * 
            + * + *
          3. + *
          4. + * + *
            +	 *     array = null
            +	 *     suffix = 'c'
            +	 *     => result = { 'c' }
             	 * 
            + * *
          5. - *
          6. -	 *    array = null
            -	 *    suffix = 'c'
            -	 *    => result = { 'c' }
            -	 * 
          7. *
          * - * @param array the array that is concanated with the suffix character - * @param suffix the suffix character + * @param array + * the array that is concanated with the suffix character + * @param suffix + * the suffix character * @return the new array */ public static final char[] append(char[] array, char suffix) { @@ -58,88 +67,117 @@ public final class CharOperation { array[length] = suffix; return array; } + /** - * Append the given subarray to append to the target array starting at the given index in the target array. - * The start of the subarray is inclusive, the end is exclusive. - * Answers a new target array if it needs to grow, otherwise answers the same target array. - *
          + * Append the given subarray to append to the target array starting at the + * given index in the target array. The start of the subarray is inclusive, + * the end is exclusive. Answers a new target array if it needs to grow, + * otherwise answers the same target array.
          * For example:
          *
            - *
          1. -	 *    target = { 'a', 'b', -1 }
            -	 *    index = 0
            -	 *    array = { 'c', 'd' }
            -	 *    start = 0
            -	 *    end = 1
            -	 *    => result = { 'a', 'b' , 'c' }
            -	 * 
            - *
          2. - *
          3. -	 *    target = { 'a', 'b' }
            -	 *    index = 0
            -	 *    array = { 'c', 'd' }
            -	 *    start = 0
            -	 *    end = 1
            -	 *    => result = new { 'a', 'b' , 'c', -1 }
            -	 * 
          4. - *
          5. -	 *    target = { 'a', 'b', 'c' }
            -	 *    index = 1
            -	 *    array = { 'c', 'd', 'e', 'f' }
            -	 *    start = 1
            -	 *    end = 4
            -	 *    => result = new { 'a', 'd' , 'e', 'f', -1, -1 }
            -	 * 
          6. + *
          7. + * + *
            +	 *     target = { 'a', 'b', -1 }
            +	 *     index = 0
            +	 *     array = { 'c', 'd' }
            +	 *     start = 0
            +	 *     end = 1
            +	 *     => result = { 'a', 'b' , 'c' }
            +	 * 
            + * + *
          8. + *
          9. + * + *
            +	 *     target = { 'a', 'b' }
            +	 *     index = 0
            +	 *     array = { 'c', 'd' }
            +	 *     start = 0
            +	 *     end = 1
            +	 *     => result = new { 'a', 'b' , 'c', -1 }
            +	 * 
            + * + *
          10. + *
          11. + * + *
            +	 *     target = { 'a', 'b', 'c' }
            +	 *     index = 1
            +	 *     array = { 'c', 'd', 'e', 'f' }
            +	 *     start = 1
            +	 *     end = 4
            +	 *     => result = new { 'a', 'd' , 'e', 'f', -1, -1 }
            +	 * 
            + * + *
          12. *
          */ - public static final char[] append(char[] target, int index, char[] array, int start, int end) { + public static final char[] append(char[] target, int index, char[] array, + int start, int end) { int targetLength = target.length; - int subLength = end-start; - int newTargetLength = subLength+index; + int subLength = end - start; + int newTargetLength = subLength + index; if (newTargetLength > targetLength) { - System.arraycopy(target, 0, target = new char[newTargetLength*2], 0, index); + System.arraycopy(target, 0, target = new char[newTargetLength * 2], + 0, index); } System.arraycopy(array, start, target, index, subLength); return target; } /** - * Answers the concatenation of the two arrays. It answers null if the two arrays are null. - * If the first array is null, then the second array is returned. - * If the second array is null, then the first array is returned. + * Answers the concatenation of the two arrays. It answers null if the two + * arrays are null. If the first array is null, then the second array is + * returned. If the second array is null, then the first array is returned. *
          *
          * For example: *
            - *
          1. -	 *    first = null
            -	 *    second = null
            -	 *    => result = null
            +	 * 
          2. + * + *
            +	 *     first = null
            +	 *     second = null
            +	 *     => result = null
             	 * 
            + * *
          3. - *
          4. -	 *    first = { { ' a' } }
            -	 *    second = null
            -	 *    => result = { { ' a' } }
            +	 * 
          5. + * + *
            +	 *     first = { { ' a' } }
            +	 *     second = null
            +	 *     => result = { { ' a' } }
             	 * 
            + * *
          6. - *
          7. -	 *    first = null
            -	 *    second = { { ' a' } }
            -	 *    => result = { { ' a' } }
            +	 * 
          8. + * + *
            +	 *     first = null
            +	 *     second = { { ' a' } }
            +	 *     => result = { { ' a' } }
             	 * 
            + * *
          9. - *
          10. -	 *    first = { { ' b' } }
            -	 *    second = { { ' a' } }
            -	 *    => result = { { ' b' }, { ' a' } }
            +	 * 
          11. + * + *
            +	 *     first = { { ' b' } }
            +	 *     second = { { ' a' } }
            +	 *     => result = { { ' b' }, { ' a' } }
             	 * 
            + * *
          12. *
          * - * @param first the first array to concatenate - * @param second the second array to concatenate - * @return the concatenation of the two arrays, or null if the two arrays are null. + * @param first + * the first array to concatenate + * @param second + * the second array to concatenate + * @return the concatenation of the two arrays, or null if the two arrays + * are null. */ public static final char[][] arrayConcat(char[][] first, char[][] second) { if (first == null) @@ -156,36 +194,47 @@ public final class CharOperation { } /** - * Answers a new array adding the second array at the end of first array. - * It answers null if the first and second are null. - * If the first array is null, then a new array char[][] is created with second. - * If the second array is null, then the first array is returned. - *
          + * Answers a new array adding the second array at the end of first array. It + * answers null if the first and second are null. If the first array is + * null, then a new array char[][] is created with second. If the second + * array is null, then the first array is returned.
          *
          * For example: *
            - *
          1. -	 *    first = null
            -	 *    second = { 'a' }
            -	 *    => result = { { ' a' } }
            +	 * 
          2. + * + *
            +	 *     first = null
            +	 *     second = { 'a' }
            +	 *     => result = { { ' a' } }
             	 * 
            - *
          3. -	 *    first = { { ' a' } }
            -	 *    second = null
            -	 *    => result = { { ' a' } }
            +	 * 
            +	 * 
          4. + * + *
            +	 *     first = { { ' a' } }
            +	 *     second = null
            +	 *     => result = { { ' a' } }
             	 * 
            + * *
          5. - *
          6. -	 *    first = { { ' a' } }
            -	 *    second = { ' b' }
            -	 *    => result = { { ' a' } , { ' b' } }
            +	 * 
          7. + * + *
            +	 *     first = { { ' a' } }
            +	 *     second = { ' b' }
            +	 *     => result = { { ' a' } , { ' b' } }
             	 * 
            + * *
          8. *
          * - * @param first the first array to concatenate - * @param second the array to add at the end of the first array - * @return a new array adding the second array at the end of first array, or null if the two arrays are null. + * @param first + * the first array to concatenate + * @param second + * the array to add at the end of the first array + * @return a new array adding the second array at the end of first array, or + * null if the two arrays are null. */ public static final char[][] arrayConcat(char[][] first, char[] second) { if (second == null) @@ -201,36 +250,48 @@ public final class CharOperation { } /** - * Answers the concatenation of the two arrays. It answers null if the two arrays are null. - * If the first array is null, then the second array is returned. - * If the second array is null, then the first array is returned. + * Answers the concatenation of the two arrays. It answers null if the two + * arrays are null. If the first array is null, then the second array is + * returned. If the second array is null, then the first array is returned. *
          *
          * For example: *
            - *
          1. -	 *    first = null
            -	 *    second = { 'a' }
            -	 *    => result = { ' a' }
            +	 * 
          2. + * + *
            +	 *     first = null
            +	 *     second = { 'a' }
            +	 *     => result = { ' a' }
             	 * 
            + * *
          3. - *
          4. -	 *    first = { ' a' }
            -	 *    second = null
            -	 *    => result = { ' a' }
            +	 * 
          5. + * + *
            +	 *     first = { ' a' }
            +	 *     second = null
            +	 *     => result = { ' a' }
             	 * 
            + * *
          6. - *
          7. -	 *    first = { ' a' }
            -	 *    second = { ' b' }
            -	 *    => result = { ' a' , ' b' }
            +	 * 
          8. + * + *
            +	 *     first = { ' a' }
            +	 *     second = { ' b' }
            +	 *     => result = { ' a' , ' b' }
             	 * 
            + * *
          9. *
          * - * @param first the first array to concatenate - * @param second the second array to concatenate - * @return the concatenation of the two arrays, or null if the two arrays are null. + * @param first + * the first array to concatenate + * @param second + * the second array to concatenate + * @return the concatenation of the two arrays, or null if the two arrays + * are null. */ public static final char[] concat(char[] first, char[] second) { if (first == null) @@ -247,61 +308,77 @@ public final class CharOperation { } /** - * Answers the concatenation of the three arrays. It answers null if the three arrays are null. - * If first is null, it answers the concatenation of second and third. - * If second is null, it answers the concatenation of first and third. - * If third is null, it answers the concatenation of first and second. - *
          + * Answers the concatenation of the three arrays. It answers null if the + * three arrays are null. If first is null, it answers the concatenation of + * second and third. If second is null, it answers the concatenation of + * first and third. If third is null, it answers the concatenation of first + * and second.
          *
          * For example: *
            - *
          1. -	 *    first = null
            -	 *    second = { 'a' }
            -	 *    third = { 'b' }
            -	 *    => result = { ' a', 'b' }
            +	 * 
          2. + * + *
            +	 *     first = null
            +	 *     second = { 'a' }
            +	 *     third = { 'b' }
            +	 *     => result = { ' a', 'b' }
             	 * 
            + * *
          3. - *
          4. -	 *    first = { 'a' }
            -	 *    second = null
            -	 *    third = { 'b' }
            -	 *    => result = { ' a', 'b' }
            +	 * 
          5. + * + *
            +	 *     first = { 'a' }
            +	 *     second = null
            +	 *     third = { 'b' }
            +	 *     => result = { ' a', 'b' }
             	 * 
            + * *
          6. - *
          7. -	 *    first = { 'a' }
            -	 *    second = { 'b' }
            -	 *    third = null
            -	 *    => result = { ' a', 'b' }
            +	 * 
          8. + * + *
            +	 *     first = { 'a' }
            +	 *     second = { 'b' }
            +	 *     third = null
            +	 *     => result = { ' a', 'b' }
             	 * 
            + * *
          9. - *
          10. -	 *    first = null
            -	 *    second = null
            -	 *    third = null
            -	 *    => result = null
            +	 * 
          11. + * + *
            +	 *     first = null
            +	 *     second = null
            +	 *     third = null
            +	 *     => result = null
             	 * 
            + * *
          12. - *
          13. -	 *    first = { 'a' }
            -	 *    second = { 'b' }
            -	 *    third = { 'c' }
            -	 *    => result = { 'a', 'b', 'c' }
            +	 * 
          14. + * + *
            +	 *     first = { 'a' }
            +	 *     second = { 'b' }
            +	 *     third = { 'c' }
            +	 *     => result = { 'a', 'b', 'c' }
             	 * 
            + * *
          15. *
          * - * @param first the first array to concatenate - * @param second the second array to concatenate - * @param third the third array to concatenate + * @param first + * the first array to concatenate + * @param second + * the second array to concatenate + * @param third + * the third array to concatenate * - * @return the concatenation of the three arrays, or null if the three arrays are null. + * @return the concatenation of the three arrays, or null if the three + * arrays are null. */ - public static final char[] concat( - char[] first, - char[] second, - char[] third) { + public static final char[] concat(char[] first, char[] second, char[] third) { if (first == null) return concat(second, third); if (second == null) @@ -320,47 +397,57 @@ public final class CharOperation { } /** - * Answers the concatenation of the two arrays inserting the separator character between the two arrays. - * It answers null if the two arrays are null. - * If the first array is null, then the second array is returned. - * If the second array is null, then the first array is returned. - *
          + * Answers the concatenation of the two arrays inserting the separator + * character between the two arrays. It answers null if the two arrays are + * null. If the first array is null, then the second array is returned. If + * the second array is null, then the first array is returned.
          *
          * For example: *
            - *
          1. -	 *    first = null
            -	 *    second = { 'a' }
            -	 *    separator = '/'
            -	 *    => result = { ' a' }
            +	 * 
          2. + * + *
            +	 *     first = null
            +	 *     second = { 'a' }
            +	 *     separator = '/'
            +	 *     => result = { ' a' }
             	 * 
            + * *
          3. - *
          4. -	 *    first = { ' a' }
            -	 *    second = null
            -	 *    separator = '/'
            -	 *    => result = { ' a' }
            +	 * 
          5. + * + *
            +	 *     first = { ' a' }
            +	 *     second = null
            +	 *     separator = '/'
            +	 *     => result = { ' a' }
             	 * 
            + * *
          6. - *
          7. -	 *    first = { ' a' }
            -	 *    second = { ' b' }
            -	 *    separator = '/'
            -	 *    => result = { ' a' , '/', 'b' }
            +	 * 
          8. + * + *
            +	 *     first = { ' a' }
            +	 *     second = { ' b' }
            +	 *     separator = '/'
            +	 *     => result = { ' a' , '/', 'b' }
             	 * 
            + * *
          9. *
          * - * @param first the first array to concatenate - * @param second the second array to concatenate - * @param separator the character to insert - * @return the concatenation of the two arrays inserting the separator character - * between the two arrays , or null if the two arrays are null. + * @param first + * the first array to concatenate + * @param second + * the second array to concatenate + * @param separator + * the character to insert + * @return the concatenation of the two arrays inserting the separator + * character between the two arrays , or null if the two arrays are + * null. */ - public static final char[] concat( - char[] first, - char[] second, - char separator) { + public static final char[] concat(char[] first, char[] second, + char separator) { if (first == null) return second; if (second == null) @@ -381,51 +468,59 @@ public final class CharOperation { } /** - * Answers the concatenation of the three arrays inserting the sep1 character between the - * two arrays and sep2 between the last two. - * It answers null if the three arrays are null. - * If the first array is null, then it answers the concatenation of second and third inserting - * the sep2 character between them. - * If the second array is null, then the first array is returned. - *
          + * Answers the concatenation of the three arrays inserting the sep1 + * character between the two arrays and sep2 between the last two. It + * answers null if the three arrays are null. If the first array is null, + * then it answers the concatenation of second and third inserting the sep2 + * character between them. If the second array is null, then the first array + * is returned.
          *
          * For example: *
            - *
          1. -	 *    first = null
            -	 *    second = { 'a' }
            -	 *    separator = '/'
            -	 *    => result = { ' a' }
            +	 * 
          2. + * + *
            +	 *     first = null
            +	 *     second = { 'a' }
            +	 *     separator = '/'
            +	 *     => result = { ' a' }
             	 * 
            + * *
          3. - *
          4. -	 *    first = { ' a' }
            -	 *    second = null
            -	 *    separator = '/'
            -	 *    => result = { ' a' }
            +	 * 
          5. + * + *
            +	 *     first = { ' a' }
            +	 *     second = null
            +	 *     separator = '/'
            +	 *     => result = { ' a' }
             	 * 
            + * *
          6. - *
          7. -	 *    first = { ' a' }
            -	 *    second = { ' b' }
            -	 *    separator = '/'
            -	 *    => result = { ' a' , '/', 'b' }
            +	 * 
          8. + * + *
            +	 *     first = { ' a' }
            +	 *     second = { ' b' }
            +	 *     separator = '/'
            +	 *     => result = { ' a' , '/', 'b' }
             	 * 
            + * *
          9. *
          * - * @param first the first array to concatenate - * @param second the second array to concatenate - * @param separator the character to insert - * @return the concatenation of the two arrays inserting the separator character - * between the two arrays , or null if the two arrays are null. + * @param first + * the first array to concatenate + * @param second + * the second array to concatenate + * @param separator + * the character to insert + * @return the concatenation of the two arrays inserting the separator + * character between the two arrays , or null if the two arrays are + * null. */ - public static final char[] concat( - char[] first, - char sep1, - char[] second, - char sep2, - char[] third) { + public static final char[] concat(char[] first, char sep1, char[] second, + char sep2, char[] third) { if (first == null) return concat(second, third, sep2); if (second == null) @@ -446,31 +541,41 @@ public final class CharOperation { } /** - * Answers a new array with prepending the prefix character and appending the suffix - * character at the end of the array. If array is null, it answers a new array containing the - * prefix and the suffix characters. - *
          + * Answers a new array with prepending the prefix character and appending + * the suffix character at the end of the array. If array is null, it + * answers a new array containing the prefix and the suffix characters.
          *
          * For example:
          *
            - *
          1. -	 *    prefix = 'a'
            -	 *    array = { 'b' }
            -	 *    suffix = 'c'
            -	 *    => result = { 'a', 'b' , 'c' }
            -	 * 
            - *
          2. - *
          3. -	 *    prefix = 'a'
            -	 *    array = null
            -	 *    suffix = 'c'
            -	 *    => result = { 'a', 'c' }
            -	 * 
          4. + *
          5. + * + *
            +	 *     prefix = 'a'
            +	 *     array = { 'b' }
            +	 *     suffix = 'c'
            +	 *     => result = { 'a', 'b' , 'c' }
            +	 * 
            + * + *
          6. + *
          7. + * + *
            +	 *     prefix = 'a'
            +	 *     array = null
            +	 *     suffix = 'c'
            +	 *     => result = { 'a', 'c' }
            +	 * 
            + * + *
          8. *
          * - * @param prefix the prefix character - * @param array the array that is concanated with the prefix and suffix characters - * @param suffix the suffix character + * @param prefix + * the prefix character + * @param array + * the array that is concanated with the prefix and suffix + * characters + * @param suffix + * the suffix character * @return the new array */ public static final char[] concat(char prefix, char[] array, char suffix) { @@ -484,45 +589,57 @@ public final class CharOperation { result[length + 1] = suffix; return result; } - + /** - * Answers the concatenation of the given array parts using the given separator between each - * part and appending the given name at the end. - *
          + * Answers the concatenation of the given array parts using the given + * separator between each part and appending the given name at the end.
          *
          * For example:
          *
            - *
          1. -	 *    name = { 'c' }
            -	 *    array = { { 'a' }, { 'b' } }
            -	 *    separator = '.'
            -	 *    => result = { 'a', '.', 'b' , '.', 'c' }
            -	 * 
            - *
          2. - *
          3. -	 *    name = null
            -	 *    array = { { 'a' }, { 'b' } }
            -	 *    separator = '.'
            -	 *    => result = { 'a', '.', 'b' }
            -	 * 
          4. - *
          5. -	 *    name = { ' c' }
            -	 *    array = null
            -	 *    separator = '.'
            -	 *    => result = { 'c' }
            -	 * 
          6. + *
          7. + * + *
            +	 *     name = { 'c' }
            +	 *     array = { { 'a' }, { 'b' } }
            +	 *     separator = '.'
            +	 *     => result = { 'a', '.', 'b' , '.', 'c' }
            +	 * 
            + * + *
          8. + *
          9. + * + *
            +	 *     name = null
            +	 *     array = { { 'a' }, { 'b' } }
            +	 *     separator = '.'
            +	 *     => result = { 'a', '.', 'b' }
            +	 * 
            + * + *
          10. + *
          11. + * + *
            +	 *     name = { ' c' }
            +	 *     array = null
            +	 *     separator = '.'
            +	 *     => result = { 'c' }
            +	 * 
            + * + *
          12. *
          * - * @param name the given name - * @param array the given array - * @param separator the given separator - * @return the concatenation of the given array parts using the given separator between each - * part and appending the given name at the end + * @param name + * the given name + * @param array + * the given array + * @param separator + * the given separator + * @return the concatenation of the given array parts using the given + * separator between each part and appending the given name at the + * end */ - public static final char[] concatWith( - char[] name, - char[][] array, - char separator) { + public static final char[] concatWith(char[] name, char[][] array, + char separator) { int nameLength = name == null ? 0 : name.length; if (nameLength == 0) return concatWith(array, separator); @@ -551,43 +668,55 @@ public final class CharOperation { } /** - * Answers the concatenation of the given array parts using the given separator between each - * part and appending the given name at the end. - *
          + * Answers the concatenation of the given array parts using the given + * separator between each part and appending the given name at the end.
          *
          * For example:
          *
            - *
          1. -	 *    name = { 'c' }
            -	 *    array = { { 'a' }, { 'b' } }
            -	 *    separator = '.'
            -	 *    => result = { 'a', '.', 'b' , '.', 'c' }
            -	 * 
            - *
          2. - *
          3. -	 *    name = null
            -	 *    array = { { 'a' }, { 'b' } }
            -	 *    separator = '.'
            -	 *    => result = { 'a', '.', 'b' }
            -	 * 
          4. - *
          5. -	 *    name = { ' c' }
            -	 *    array = null
            -	 *    separator = '.'
            -	 *    => result = { 'c' }
            -	 * 
          6. + *
          7. + * + *
            +	 *     name = { 'c' }
            +	 *     array = { { 'a' }, { 'b' } }
            +	 *     separator = '.'
            +	 *     => result = { 'a', '.', 'b' , '.', 'c' }
            +	 * 
            + * + *
          8. + *
          9. + * + *
            +	 *     name = null
            +	 *     array = { { 'a' }, { 'b' } }
            +	 *     separator = '.'
            +	 *     => result = { 'a', '.', 'b' }
            +	 * 
            + * + *
          10. + *
          11. + * + *
            +	 *     name = { ' c' }
            +	 *     array = null
            +	 *     separator = '.'
            +	 *     => result = { 'c' }
            +	 * 
            + * + *
          12. *
          * - * @param array the given array - * @param name the given name - * @param separator the given separator - * @return the concatenation of the given array parts using the given separator between each - * part and appending the given name at the end + * @param array + * the given array + * @param name + * the given name + * @param separator + * the given separator + * @return the concatenation of the given array parts using the given + * separator between each part and appending the given name at the + * end */ - public static final char[] concatWith( - char[][] array, - char[] name, - char separator) { + public static final char[] concatWith(char[][] array, char[] name, + char separator) { int nameLength = name == null ? 0 : name.length; if (nameLength == 0) return concatWith(array, separator); @@ -616,27 +745,37 @@ public final class CharOperation { } /** - * Answers the concatenation of the given array parts using the given separator between each part. - *
          + * Answers the concatenation of the given array parts using the given + * separator between each part.
          *
          * For example:
          *
            - *
          1. -	 *    array = { { 'a' }, { 'b' } }
            -	 *    separator = '.'
            -	 *    => result = { 'a', '.', 'b' }
            +	 * 
          2. + * + *
            +	 *     array = { { 'a' }, { 'b' } }
            +	 *     separator = '.'
            +	 *     => result = { 'a', '.', 'b' }
            +	 * 
            + * + *
          3. + *
          4. + * + *
            +	 *     array = null
            +	 *     separator = '.'
            +	 *     => result = { }
             	 * 
            + * *
          5. - *
          6. -	 *    array = null
            -	 *    separator = '.'
            -	 *    => result = { }
            -	 * 
          7. *
          * - * @param array the given array - * @param separator the given separator - * @return the concatenation of the given array parts using the given separator between each part + * @param array + * the given array + * @param separator + * the given separator + * @return the concatenation of the given array parts using the given + * separator between each part */ public static final char[] concatWith(char[][] array, char separator) { int length = array == null ? 0 : array.length; @@ -658,45 +797,52 @@ public final class CharOperation { while (--index >= 0) { length = array[index].length; if (length > 0) { - System.arraycopy( - array[index], - 0, - result, - (size -= length), - length); + System.arraycopy(array[index], 0, result, (size -= length), + length); if (--size >= 0) result[size] = separator; } } return result; } - + /** - * Answers true if the array contains an occurrence of character, false otherwise. + * Answers true if the array contains an occurrence of character, false + * otherwise. * *
          *
          * For example: *
            - *
          1. -	 *    character = 'c'
            -	 *    array = { { ' a' }, { ' b' } }
            -	 *    result => false
            +	 * 
          2. + * + *
            +	 *     character = 'c'
            +	 *     array = { { ' a' }, { ' b' } }
            +	 *     result => false
             	 * 
            + * *
          3. - *
          4. -	 *    character = 'a'
            -	 *    array = { { ' a' }, { ' b' } }
            -	 *    result => true
            +	 * 
          5. + * + *
            +	 *     character = 'a'
            +	 *     array = { { ' a' }, { ' b' } }
            +	 *     result => true
             	 * 
            + * *
          6. *
          * - * @param character the character to search - * @param array the array in which the search is done - * @exception NullPointerException if array is null. + * @param character + * the character to search + * @param array + * the array in which the search is done + * @exception NullPointerException + * if array is null. * - * @return true if the array contains an occurrence of character, false otherwise. + * @return true if the array contains an occurrence of character, false + * otherwise. */ public static final boolean contains(char character, char[][] array) { for (int i = array.length; --i >= 0;) { @@ -709,31 +855,42 @@ public final class CharOperation { } /** - * Answers true if the array contains an occurrence of character, false otherwise. + * Answers true if the array contains an occurrence of character, false + * otherwise. * *
          *
          * For example: *
            - *
          1. -	 *    character = 'c'
            -	 *    array = { ' b'  }
            -	 *    result => false
            +	 * 
          2. + * + *
            +	 *     character = 'c'
            +	 *     array = { ' b'  }
            +	 *     result => false
             	 * 
            + * *
          3. - *
          4. -	 *    character = 'a'
            -	 *    array = { ' a' , ' b' }
            -	 *    result => true
            +	 * 
          5. + * + *
            +	 *     character = 'a'
            +	 *     array = { ' a' , ' b' }
            +	 *     result => true
             	 * 
            + * *
          6. *
          * - * @param character the character to search - * @param array the array in which the search is done - * @exception NullPointerException if array is null. + * @param character + * the character to search + * @param array + * the array in which the search is done + * @exception NullPointerException + * if array is null. * - * @return true if the array contains an occurrence of character, false otherwise. + * @return true if the array contains an occurrence of character, false + * otherwise. */ public static final boolean contains(char character, char[] array) { for (int i = array.length; --i >= 0;) @@ -741,11 +898,12 @@ public final class CharOperation { return true; return false; } - + /** * Answers a deep copy of the toCopy array. * - * @param toCopy the array to copy + * @param toCopy + * the array to copy * @return a deep copy of the toCopy array. */ public static final char[][] deepCopy(char[][] toCopy) { @@ -762,31 +920,39 @@ public final class CharOperation { } /** - * Return true if array ends with the sequence of characters contained in toBeFound, - * otherwise false. - *
          + * Return true if array ends with the sequence of characters contained in + * toBeFound, otherwise false.
          *
          * For example: *
            - *
          1. -	 *    array = { 'a', 'b', 'c', 'd' }
            -	 *    toBeFound = { 'b', 'c' }
            -	 *    result => false
            +	 * 
          2. + * + *
            +	 *     array = { 'a', 'b', 'c', 'd' }
            +	 *     toBeFound = { 'b', 'c' }
            +	 *     result => false
             	 * 
            + * *
          3. - *
          4. -	 *    array = { 'a', 'b', 'c' }
            -	 *    toBeFound = { 'b', 'c' }
            -	 *    result => true
            +	 * 
          5. + * + *
            +	 *     array = { 'a', 'b', 'c' }
            +	 *     toBeFound = { 'b', 'c' }
            +	 *     result => true
             	 * 
            + * *
          6. *
          * - * @param array the array to check - * @param toBeFound the array to find - * @exception NullPointerException if array is null or toBeFound is null - * @return true if array ends with the sequence of characters contained in toBeFound, - * otherwise false. + * @param array + * the array to check + * @param toBeFound + * the array to find + * @exception NullPointerException + * if array is null or toBeFound is null + * @return true if array ends with the sequence of characters contained in + * toBeFound, otherwise false. */ public static final boolean endsWith(char[] array, char[] toBeFound) { int i = toBeFound.length; @@ -801,40 +967,55 @@ public final class CharOperation { } /** - * Answers true if the two arrays are identical character by character, otherwise false. - * The equality is case sensitive. - *
          + * Answers true if the two arrays are identical character by character, + * otherwise false. The equality is case sensitive.
          *
          * For example: *
            - *
          1. -	 *    first = null
            -	 *    second = null
            -	 *    result => true
            +	 * 
          2. + * + *
            +	 *     first = null
            +	 *     second = null
            +	 *     result => true
             	 * 
            + * *
          3. - *
          4. -	 *    first = { { } }
            -	 *    second = null
            -	 *    result => false
            +	 * 
          5. + * + *
            +	 *     first = { { } }
            +	 *     second = null
            +	 *     result => false
             	 * 
            + * *
          6. - *
          7. -	 *    first = { { 'a' } }
            -	 *    second = { { 'a' } }
            -	 *    result => true
            +	 * 
          8. + * + *
            +	 *     first = { { 'a' } }
            +	 *     second = { { 'a' } }
            +	 *     result => true
             	 * 
            + * *
          9. - *
          10. -	 *    first = { { 'A' } }
            -	 *    second = { { 'a' } }
            -	 *    result => false
            +	 * 
          11. + * + *
            +	 *     first = { { 'A' } }
            +	 *     second = { { 'a' } }
            +	 *     result => false
             	 * 
            + * *
          12. *
          - * @param first the first array - * @param second the second array - * @return true if the two arrays are identical character by character, otherwise false + * + * @param first + * the first array + * @param second + * the second array + * @return true if the two arrays are identical character by character, + * otherwise false */ public static final boolean equals(char[][] first, char[][] second) { if (first == second) @@ -851,54 +1032,66 @@ public final class CharOperation { } /** - * If isCaseSensite is true, answers true if the two arrays are identical character - * by character, otherwise false. - * If it is false, answers true if the two arrays are identical character by - * character without checking the case, otherwise false. - *
          + * If isCaseSensite is true, answers true if the two arrays are identical + * character by character, otherwise false. If it is false, answers true if + * the two arrays are identical character by character without checking the + * case, otherwise false.
          *
          * For example: *
            - *
          1. -	 *    first = null
            -	 *    second = null
            -	 *    isCaseSensitive = true
            -	 *    result => true
            +	 * 
          2. + * + *
            +	 *     first = null
            +	 *     second = null
            +	 *     isCaseSensitive = true
            +	 *     result => true
             	 * 
            + * *
          3. - *
          4. -	 *    first = { { } }
            -	 *    second = null
            -	 *    isCaseSensitive = true
            -	 *    result => false
            +	 * 
          5. + * + *
            +	 *     first = { { } }
            +	 *     second = null
            +	 *     isCaseSensitive = true
            +	 *     result => false
             	 * 
            + * *
          6. - *
          7. -	 *    first = { { 'A' } }
            -	 *    second = { { 'a' } }
            -	 *    isCaseSensitive = true
            -	 *    result => false
            +	 * 
          8. + * + *
            +	 *     first = { { 'A' } }
            +	 *     second = { { 'a' } }
            +	 *     isCaseSensitive = true
            +	 *     result => false
             	 * 
            + * *
          9. - *
          10. -	 *    first = { { 'A' } }
            -	 *    second = { { 'a' } }
            -	 *    isCaseSensitive = false
            -	 *    result => true
            +	 * 
          11. + * + *
            +	 *     first = { { 'A' } }
            +	 *     second = { { 'a' } }
            +	 *     isCaseSensitive = false
            +	 *     result => true
             	 * 
            + * *
          12. *
          * - * @param first the first array - * @param second the second array - * @param isCaseSensitive check whether or not the equality should be case sensitive - * @return true if the two arrays are identical character by character according to the value - * of isCaseSensitive, otherwise false + * @param first + * the first array + * @param second + * the second array + * @param isCaseSensitive + * check whether or not the equality should be case sensitive + * @return true if the two arrays are identical character by character + * according to the value of isCaseSensitive, otherwise false */ - public static final boolean equals( - char[][] first, - char[][] second, - boolean isCaseSensitive) { + public static final boolean equals(char[][] first, char[][] second, + boolean isCaseSensitive) { if (isCaseSensitive) { return equals(first, second); @@ -917,40 +1110,55 @@ public final class CharOperation { } /** - * Answers true if the two arrays are identical character by character, otherwise false. - * The equality is case sensitive. - *
          + * Answers true if the two arrays are identical character by character, + * otherwise false. The equality is case sensitive.
          *
          * For example: *
            - *
          1. -	 *    first = null
            -	 *    second = null
            -	 *    result => true
            +	 * 
          2. + * + *
            +	 *     first = null
            +	 *     second = null
            +	 *     result => true
             	 * 
            + * *
          3. - *
          4. -	 *    first = { }
            -	 *    second = null
            -	 *    result => false
            +	 * 
          5. + * + *
            +	 *     first = { }
            +	 *     second = null
            +	 *     result => false
             	 * 
            + * *
          6. - *
          7. -	 *    first = { 'a' }
            -	 *    second = { 'a' }
            -	 *    result => true
            +	 * 
          8. + * + *
            +	 *     first = { 'a' }
            +	 *     second = { 'a' }
            +	 *     result => true
             	 * 
            + * *
          9. - *
          10. -	 *    first = { 'a' }
            -	 *    second = { 'A' }
            -	 *    result => false
            +	 * 
          11. + * + *
            +	 *     first = { 'a' }
            +	 *     second = { 'A' }
            +	 *     result => false
             	 * 
            + * *
          12. *
          - * @param first the first array - * @param second the second array - * @return true if the two arrays are identical character by character, otherwise false + * + * @param first + * the first array + * @param second + * the second array + * @return true if the two arrays are identical character by character, + * otherwise false */ public static final boolean equals(char[] first, char[] second) { if (first == second) @@ -967,54 +1175,66 @@ public final class CharOperation { } /** - * If isCaseSensite is true, answers true if the two arrays are identical character - * by character, otherwise false. - * If it is false, answers true if the two arrays are identical character by - * character without checking the case, otherwise false. - *
          + * If isCaseSensite is true, answers true if the two arrays are identical + * character by character, otherwise false. If it is false, answers true if + * the two arrays are identical character by character without checking the + * case, otherwise false.
          *
          * For example: *
            - *
          1. -	 *    first = null
            -	 *    second = null
            -	 *    isCaseSensitive = true
            -	 *    result => true
            +	 * 
          2. + * + *
            +	 *     first = null
            +	 *     second = null
            +	 *     isCaseSensitive = true
            +	 *     result => true
             	 * 
            + * *
          3. - *
          4. -	 *    first = { }
            -	 *    second = null
            -	 *    isCaseSensitive = true
            -	 *    result => false
            +	 * 
          5. + * + *
            +	 *     first = { }
            +	 *     second = null
            +	 *     isCaseSensitive = true
            +	 *     result => false
             	 * 
            + * *
          6. - *
          7. -	 *    first = { 'A' }
            -	 *    second = { 'a' }
            -	 *    isCaseSensitive = true
            -	 *    result => false
            +	 * 
          8. + * + *
            +	 *     first = { 'A' }
            +	 *     second = { 'a' }
            +	 *     isCaseSensitive = true
            +	 *     result => false
             	 * 
            + * *
          9. - *
          10. -	 *    first = { 'A' }
            -	 *    second = { 'a' }
            -	 *    isCaseSensitive = false
            -	 *    result => true
            +	 * 
          11. + * + *
            +	 *     first = { 'A' }
            +	 *     second = { 'a' }
            +	 *     isCaseSensitive = false
            +	 *     result => true
             	 * 
            + * *
          12. *
          * - * @param first the first array - * @param second the second array - * @param isCaseSensitive check whether or not the equality should be case sensitive - * @return true if the two arrays are identical character by character according to the value - * of isCaseSensitive, otherwise false + * @param first + * the first array + * @param second + * the second array + * @param isCaseSensitive + * check whether or not the equality should be case sensitive + * @return true if the two arrays are identical character by character + * according to the value of isCaseSensitive, otherwise false */ - public static final boolean equals( - char[] first, - char[] second, - boolean isCaseSensitive) { + public static final boolean equals(char[] first, char[] second, + boolean isCaseSensitive) { if (isCaseSensitive) { return equals(first, second); @@ -1027,83 +1247,98 @@ public final class CharOperation { return false; for (int i = first.length; --i >= 0;) - if (Character.toLowerCase(first[i]) - != Character.toLowerCase(second[i])) + if (Character.toLowerCase(first[i]) != Character + .toLowerCase(second[i])) return false; return true; } + /** - * If isCaseSensite is true, the equality is case sensitive, otherwise it is case insensitive. + * If isCaseSensite is true, the equality is case sensitive, otherwise it is + * case insensitive. * - * Answers true if the name contains the fragment at the starting index startIndex, otherwise false. - *
          + * Answers true if the name contains the fragment at the starting index + * startIndex, otherwise false.
          *
          * For example: *
            - *
          1. -	 *    fragment = { 'b', 'c' , 'd' }
            -	 *    name = { 'a', 'b', 'c' , 'd' }
            -	 *    startIndex = 1
            -	 *    isCaseSensitive = true
            -	 *    result => true
            +	 * 
          2. + * + *
            +	 *     fragment = { 'b', 'c' , 'd' }
            +	 *     name = { 'a', 'b', 'c' , 'd' }
            +	 *     startIndex = 1
            +	 *     isCaseSensitive = true
            +	 *     result => true
             	 * 
            + * *
          3. - *
          4. -	 *    fragment = { 'b', 'c' , 'd' }
            -	 *    name = { 'a', 'b', 'C' , 'd' }
            -	 *    startIndex = 1
            -	 *    isCaseSensitive = true
            -	 *    result => false
            +	 * 
          5. + * + *
            +	 *     fragment = { 'b', 'c' , 'd' }
            +	 *     name = { 'a', 'b', 'C' , 'd' }
            +	 *     startIndex = 1
            +	 *     isCaseSensitive = true
            +	 *     result => false
             	 * 
            + * *
          6. - *
          7. -	 *    fragment = { 'b', 'c' , 'd' }
            -	 *    name = { 'a', 'b', 'C' , 'd' }
            -	 *    startIndex = 0
            -	 *    isCaseSensitive = false
            -	 *    result => false
            +	 * 
          8. + * + *
            +	 *     fragment = { 'b', 'c' , 'd' }
            +	 *     name = { 'a', 'b', 'C' , 'd' }
            +	 *     startIndex = 0
            +	 *     isCaseSensitive = false
            +	 *     result => false
             	 * 
            + * *
          9. - *
          10. -	 *    fragment = { 'b', 'c' , 'd' }
            -	 *    name = { 'a', 'b'}
            -	 *    startIndex = 0
            -	 *    isCaseSensitive = true
            -	 *    result => false
            +	 * 
          11. + * + *
            +	 *     fragment = { 'b', 'c' , 'd' }
            +	 *     name = { 'a', 'b'}
            +	 *     startIndex = 0
            +	 *     isCaseSensitive = true
            +	 *     result => false
             	 * 
            + * *
          12. *
          * - * @param fragment the fragment to check - * @param second the array to check - * @param startIndex the starting index - * @param isCaseSensitive check whether or not the equality should be case sensitive - * @return true if the name contains the fragment at the starting index startIndex according to the - * value of isCaseSensitive, otherwise false. - * @exception NullPointerException if fragment or name is null. + * @param fragment + * the fragment to check + * @param second + * the array to check + * @param startIndex + * the starting index + * @param isCaseSensitive + * check whether or not the equality should be case sensitive + * @return true if the name contains the fragment at the starting index + * startIndex according to the value of isCaseSensitive, otherwise + * false. + * @exception NullPointerException + * if fragment or name is null. */ - public static final boolean fragmentEquals( - char[] fragment, - char[] name, - int startIndex, - boolean isCaseSensitive) { + public static final boolean fragmentEquals(char[] fragment, char[] name, + int startIndex, boolean isCaseSensitive) { int max = fragment.length; if (name.length < max + startIndex) return false; if (isCaseSensitive) { - for (int i = max; - --i >= 0; - ) // assumes the prefix is not larger than the name + for (int i = max; --i >= 0;) + // assumes the prefix is not larger than the name if (fragment[i] != name[i + startIndex]) return false; return true; } - for (int i = max; - --i >= 0; - ) // assumes the prefix is not larger than the name - if (Character.toLowerCase(fragment[i]) - != Character.toLowerCase(name[i + startIndex])) + for (int i = max; --i >= 0;) + // assumes the prefix is not larger than the name + if (Character.toLowerCase(fragment[i]) != Character + .toLowerCase(name[i + startIndex])) return false; return true; } @@ -1111,9 +1346,11 @@ public final class CharOperation { /** * Answers a hashcode for the array * - * @param array the array for which a hashcode is required + * @param array + * the array for which a hashcode is required * @return the hashcode - * @exception NullPointerException if array is null + * @exception NullPointerException + * if array is null */ public static final int hashCode(char[] array) { int hash = 0; @@ -1130,66 +1367,83 @@ public final class CharOperation { } return hash & 0x7FFFFFFF; } + /** - * Answers true if c is a whitespace according to the JLS (\u000a, \u000c, \u000d, \u0009), otherwise false. - *
          + * Answers true if c is a whitespace according to the JLS (\u000a, + * \u000c, \u000d, \u0009), otherwise false.
          *
          * For example: *
            - *
          1. -	 *    c = ' '
            -	 *    result => true
            +	 * 
          2. + * + *
            +	 *     c = ' '
            +	 *     result => true
             	 * 
            + * *
          3. - *
          4. -	 *    c = '\u3000'
            -	 *    result => false
            +	 * 
          5. + * + *
            +	 *     c = ' \u3000'
            +	 *     result => false
             	 * 
            + * *
          6. *
          * - * @param c the character to check + * @param c + * the character to check * @return true if c is a whitespace according to the JLS, otherwise false. */ public static boolean isWhitespace(char c) { switch (c) { - case 10 : /* \ u000a: LINE FEED */ - case 12 : /* \ u000c: FORM FEED */ - case 13 : /* \ u000d: CARRIAGE RETURN */ - case 32 : /* \ u0020: SPACE */ - case 9 : /* \ u0009: HORIZONTAL TABULATION */ - return true; - default : - return false; + case 10: /* \ u000a: LINE FEED */ + case 12: /* \ u000c: FORM FEED */ + case 13: /* \ u000d: CARRIAGE RETURN */ + case 32: /* \ u0020: SPACE */ + case 9: /* \ u0009: HORIZONTAL TABULATION */ + return true; + default: + return false; } } - + /** - * Answers the first index in the array for which the corresponding character is - * equal to toBeFound. Answers -1 if no occurrence of this character is found. - *
          + * Answers the first index in the array for which the corresponding + * character is equal to toBeFound. Answers -1 if no occurrence of this + * character is found.
          *
          * For example: *
            - *
          1. -	 *    toBeFound = 'c'
            -	 *    array = { ' a', 'b', 'c', 'd' }
            -	 *    result => 2
            +	 * 
          2. + * + *
            +	 *     toBeFound = 'c'
            +	 *     array = { ' a', 'b', 'c', 'd' }
            +	 *     result => 2
             	 * 
            + * *
          3. - *
          4. -	 *    toBeFound = 'e'
            -	 *    array = { ' a', 'b', 'c', 'd' }
            -	 *    result => -1
            +	 * 
          5. + * + *
            +	 *     toBeFound = 'e'
            +	 *     array = { ' a', 'b', 'c', 'd' }
            +	 *     result => -1
             	 * 
            + * *
          6. *
          * - * @param toBeFound the character to search - * @param array the array to be searched - * @return the first index in the array for which the corresponding character is - * equal to toBeFound, -1 otherwise - * @exception NullPointerException if array is null + * @param toBeFound + * the character to search + * @param array + * the array to be searched + * @return the first index in the array for which the corresponding + * character is equal to toBeFound, -1 otherwise + * @exception NullPointerException + * if array is null */ public static final int indexOf(char toBeFound, char[] array) { for (int i = 0; i < array.length; i++) @@ -1199,43 +1453,56 @@ public final class CharOperation { } /** - * Answers the first index in the array for which the corresponding character is - * equal to toBeFound starting the search at index start. - * Answers -1 if no occurrence of this character is found. - *
          + * Answers the first index in the array for which the corresponding + * character is equal to toBeFound starting the search at index start. + * Answers -1 if no occurrence of this character is found.
          *
          * For example: *
            - *
          1. -	 *    toBeFound = 'c'
            -	 *    array = { ' a', 'b', 'c', 'd' }
            -	 *    start = 2
            -	 *    result => 2
            +	 * 
          2. + * + *
            +	 *     toBeFound = 'c'
            +	 *     array = { ' a', 'b', 'c', 'd' }
            +	 *     start = 2
            +	 *     result => 2
             	 * 
            + * *
          3. - *
          4. -	 *    toBeFound = 'c'
            -	 *    array = { ' a', 'b', 'c', 'd' }
            -	 *    start = 3
            -	 *    result => -1
            +	 * 
          5. + * + *
            +	 *     toBeFound = 'c'
            +	 *     array = { ' a', 'b', 'c', 'd' }
            +	 *     start = 3
            +	 *     result => -1
             	 * 
            + * *
          6. - *
          7. -	 *    toBeFound = 'e'
            -	 *    array = { ' a', 'b', 'c', 'd' }
            -	 *    start = 1
            -	 *    result => -1
            +	 * 
          8. + * + *
            +	 *     toBeFound = 'e'
            +	 *     array = { ' a', 'b', 'c', 'd' }
            +	 *     start = 1
            +	 *     result => -1
             	 * 
            + * *
          9. *
          * - * @param toBeFound the character to search - * @param array the array to be searched - * @param start the starting index - * @return the first index in the array for which the corresponding character is - * equal to toBeFound, -1 otherwise - * @exception NullPointerException if array is null - * @exception ArrayIndexOutOfBoundsException if start is lower than 0 + * @param toBeFound + * the character to search + * @param array + * the array to be searched + * @param start + * the starting index + * @return the first index in the array for which the corresponding + * character is equal to toBeFound, -1 otherwise + * @exception NullPointerException + * if array is null + * @exception ArrayIndexOutOfBoundsException + * if start is lower than 0 */ public static final int indexOf(char toBeFound, char[] array, int start) { for (int i = start; i < array.length; i++) @@ -1245,32 +1512,41 @@ public final class CharOperation { } /** - * Answers the last index in the array for which the corresponding character is - * equal to toBeFound starting from the end of the array. - * Answers -1 if no occurrence of this character is found. - *
          + * Answers the last index in the array for which the corresponding character + * is equal to toBeFound starting from the end of the array. Answers -1 if + * no occurrence of this character is found.
          *
          * For example: *
            - *
          1. -	 *    toBeFound = 'c'
            -	 *    array = { ' a', 'b', 'c', 'd' , 'c', 'e' }
            -	 *    result => 4
            +	 * 
          2. + * + *
            +	 *     toBeFound = 'c'
            +	 *     array = { ' a', 'b', 'c', 'd' , 'c', 'e' }
            +	 *     result => 4
             	 * 
            + * *
          3. - *
          4. -	 *    toBeFound = 'e'
            -	 *    array = { ' a', 'b', 'c', 'd' }
            -	 *    result => -1
            +	 * 
          5. + * + *
            +	 *     toBeFound = 'e'
            +	 *     array = { ' a', 'b', 'c', 'd' }
            +	 *     result => -1
             	 * 
            + * *
          6. *
          - * - * @param toBeFound the character to search - * @param array the array to be searched - * @return the last index in the array for which the corresponding character is - * equal to toBeFound starting from the end of the array, -1 otherwise - * @exception NullPointerException if array is null + * + * @param toBeFound + * the character to search + * @param array + * the array to be searched + * @return the last index in the array for which the corresponding character + * is equal to toBeFound starting from the end of the array, -1 + * otherwise + * @exception NullPointerException + * if array is null */ public static final int lastIndexOf(char toBeFound, char[] array) { for (int i = array.length; --i >= 0;) @@ -1280,48 +1556,60 @@ public final class CharOperation { } /** - * Answers the last index in the array for which the corresponding character is - * equal to toBeFound stopping at the index startIndex. - * Answers -1 if no occurrence of this character is found. - *
          + * Answers the last index in the array for which the corresponding character + * is equal to toBeFound stopping at the index startIndex. Answers -1 if no + * occurrence of this character is found.
          *
          * For example: *
            - *
          1. -	 *    toBeFound = 'c'
            -	 *    array = { ' a', 'b', 'c', 'd' }
            -	 *    startIndex = 2
            -	 *    result => 2
            +	 * 
          2. + * + *
            +	 *     toBeFound = 'c'
            +	 *     array = { ' a', 'b', 'c', 'd' }
            +	 *     startIndex = 2
            +	 *     result => 2
             	 * 
            + * *
          3. - *
          4. -	 *    toBeFound = 'c'
            -	 *    array = { ' a', 'b', 'c', 'd', 'e' }
            -	 *    startIndex = 3
            -	 *    result => -1
            +	 * 
          5. + * + *
            +	 *     toBeFound = 'c'
            +	 *     array = { ' a', 'b', 'c', 'd', 'e' }
            +	 *     startIndex = 3
            +	 *     result => -1
             	 * 
            + * *
          6. - *
          7. -	 *    toBeFound = 'e'
            -	 *    array = { ' a', 'b', 'c', 'd' }
            -	 *    startIndex = 0
            -	 *    result => -1
            +	 * 
          8. + * + *
            +	 *     toBeFound = 'e'
            +	 *     array = { ' a', 'b', 'c', 'd' }
            +	 *     startIndex = 0
            +	 *     result => -1
             	 * 
            + * *
          9. *
          - * - * @param toBeFound the character to search - * @param array the array to be searched - * @param startIndex the stopping index - * @return the last index in the array for which the corresponding character is - * equal to toBeFound stopping at the index startIndex, -1 otherwise - * @exception NullPointerException if array is null - * @exception ArrayIndexOutOfBoundsException if startIndex is lower than 0 + * + * @param toBeFound + * the character to search + * @param array + * the array to be searched + * @param startIndex + * the stopping index + * @return the last index in the array for which the corresponding character + * is equal to toBeFound stopping at the index startIndex, -1 + * otherwise + * @exception NullPointerException + * if array is null + * @exception ArrayIndexOutOfBoundsException + * if startIndex is lower than 0 */ - public static final int lastIndexOf( - char toBeFound, - char[] array, - int startIndex) { + public static final int lastIndexOf(char toBeFound, char[] array, + int startIndex) { for (int i = array.length; --i >= startIndex;) if (toBeFound == array[i]) return i; @@ -1329,72 +1617,88 @@ public final class CharOperation { } /** - * Answers the last index in the array for which the corresponding character is - * equal to toBeFound starting from endIndex to startIndex. - * Answers -1 if no occurrence of this character is found. - *
          + * Answers the last index in the array for which the corresponding character + * is equal to toBeFound starting from endIndex to startIndex. Answers -1 if + * no occurrence of this character is found.
          *
          * For example: *
            - *
          1. -	 *    toBeFound = 'c'
            -	 *    array = { ' a', 'b', 'c', 'd' }
            -	 *    startIndex = 2
            -	 *    endIndex = 2
            -	 *    result => 2
            +	 * 
          2. + * + *
            +	 *     toBeFound = 'c'
            +	 *     array = { ' a', 'b', 'c', 'd' }
            +	 *     startIndex = 2
            +	 *     endIndex = 2
            +	 *     result => 2
             	 * 
            + * *
          3. - *
          4. -	 *    toBeFound = 'c'
            -	 *    array = { ' a', 'b', 'c', 'd', 'e' }
            -	 *    startIndex = 3
            -	 *    endIndex = 4
            -	 *    result => -1
            +	 * 
          5. + * + *
            +	 *     toBeFound = 'c'
            +	 *     array = { ' a', 'b', 'c', 'd', 'e' }
            +	 *     startIndex = 3
            +	 *     endIndex = 4
            +	 *     result => -1
             	 * 
            + * *
          6. - *
          7. -	 *    toBeFound = 'e'
            -	 *    array = { ' a', 'b', 'c', 'd' }
            -	 *    startIndex = 0
            -	 *    endIndex = 3
            -	 *    result => -1
            +	 * 
          8. + * + *
            +	 *     toBeFound = 'e'
            +	 *     array = { ' a', 'b', 'c', 'd' }
            +	 *     startIndex = 0
            +	 *     endIndex = 3
            +	 *     result => -1
             	 * 
            + * *
          9. *
          * - * @param toBeFound the character to search - * @param array the array to be searched - * @param startIndex the stopping index - * @param endIndex the starting index - * @return the last index in the array for which the corresponding character is - * equal to toBeFound starting from endIndex to startIndex, -1 otherwise - * @exception NullPointerException if array is null - * @exception ArrayIndexOutOfBoundsException if endIndex is greater or equals to array length or starting is lower than 0 + * @param toBeFound + * the character to search + * @param array + * the array to be searched + * @param startIndex + * the stopping index + * @param endIndex + * the starting index + * @return the last index in the array for which the corresponding character + * is equal to toBeFound starting from endIndex to startIndex, -1 + * otherwise + * @exception NullPointerException + * if array is null + * @exception ArrayIndexOutOfBoundsException + * if endIndex is greater or equals to array length or + * starting is lower than 0 */ - public static final int lastIndexOf( - char toBeFound, - char[] array, - int startIndex, - int endIndex) { + public static final int lastIndexOf(char toBeFound, char[] array, + int startIndex, int endIndex) { for (int i = endIndex; --i >= startIndex;) if (toBeFound == array[i]) return i; return -1; } - + /** - * Answers the last portion of a name given a separator. - *
          + * Answers the last portion of a name given a separator.
          *
          * For example, + * *
          -	 * 	lastSegment("java.lang.Object".toCharArray(),'.') --> Object
          +	 *  	lastSegment("java.lang.Object".toCharArray(),'.') --> Object
           	 * 
          * - * @param array the array - * @param separator the given separator + * @param array + * the array + * @param separator + * the given separator * @return the last portion of a name given a separator - * @exception NullPointerException if array is null + * @exception NullPointerException + * if array is null */ final static public char[] lastSegment(char[] array, char separator) { int pos = lastIndexOf(separator, array); @@ -1404,117 +1708,130 @@ public final class CharOperation { } /** - * Answers true if the pattern matches the given name, false otherwise. This char[] pattern matching - * accepts wild-cards '*' and '?'. - * - * When not case sensitive, the pattern is assumed to already be lowercased, the - * name will be lowercased character per character as comparing. - * If name is null, the answer is false. - * If pattern is null, the answer is true if name is not null. - *
          + * Answers true if the pattern matches the given name, false otherwise. This + * char[] pattern matching accepts wild-cards '*' and '?'. + * + * When not case sensitive, the pattern is assumed to already be lowercased, + * the name will be lowercased character per character as comparing. If name + * is null, the answer is false. If pattern is null, the answer is true if + * name is not null.
          *
          * For example: *
            - *
          1. -	 *    pattern = { '?', 'b', '*' }
            -	 *    name = { 'a', 'b', 'c' , 'd' }
            -	 *    isCaseSensitive = true
            -	 *    result => true
            +	 * 
          2. + * + *
            +	 *     pattern = { '?', 'b', '*' }
            +	 *     name = { 'a', 'b', 'c' , 'd' }
            +	 *     isCaseSensitive = true
            +	 *     result => true
             	 * 
            + * *
          3. - *
          4. -	 *    pattern = { '?', 'b', '?' }
            -	 *    name = { 'a', 'b', 'c' , 'd' }
            -	 *    isCaseSensitive = true
            -	 *    result => false
            +	 * 
          5. + * + *
            +	 *     pattern = { '?', 'b', '?' }
            +	 *     name = { 'a', 'b', 'c' , 'd' }
            +	 *     isCaseSensitive = true
            +	 *     result => false
             	 * 
            + * *
          6. - *
          7. -	 *    pattern = { 'b', '*' }
            -	 *    name = { 'a', 'b', 'c' , 'd' }
            -	 *    isCaseSensitive = true
            -	 *    result => false
            +	 * 
          8. + * + *
            +	 *     pattern = { 'b', '*' }
            +	 *     name = { 'a', 'b', 'c' , 'd' }
            +	 *     isCaseSensitive = true
            +	 *     result => false
             	 * 
            + * *
          9. *
          * - * @param pattern the given pattern - * @param name the given name - * @param isCaseSensitive flag to know whether or not the matching should be case sensitive + * @param pattern + * the given pattern + * @param name + * the given name + * @param isCaseSensitive + * flag to know whether or not the matching should be case + * sensitive * @return true if the pattern matches the given name, false otherwise */ - public static final boolean match( - char[] pattern, - char[] name, - boolean isCaseSensitive) { + public static final boolean match(char[] pattern, char[] name, + boolean isCaseSensitive) { if (name == null) return false; // null name cannot match if (pattern == null) return true; // null pattern is equivalent to '*' - return match( - pattern, - 0, - pattern.length, - name, - 0, - name.length, - isCaseSensitive); + return match(pattern, 0, pattern.length, name, 0, name.length, + isCaseSensitive); } /** - * Answers true if the a sub-pattern matches the subpart of the given name, false otherwise. - * char[] pattern matching, accepting wild-cards '*' and '?'. Can match only subset of name/pattern. - * end positions are non-inclusive. - * The subpattern is defined by the patternStart and pattternEnd positions. - * When not case sensitive, the pattern is assumed to already be lowercased, the - * name will be lowercased character per character as comparing. - *
          + * Answers true if the a sub-pattern matches the subpart of the given name, + * false otherwise. char[] pattern matching, accepting wild-cards '*' and + * '?'. Can match only subset of name/pattern. end positions are + * non-inclusive. The subpattern is defined by the patternStart and + * pattternEnd positions. When not case sensitive, the pattern is assumed to + * already be lowercased, the name will be lowercased character per + * character as comparing.
          *
          * For example: *
            - *
          1. -	 *    pattern = { '?', 'b', '*' }
            -	 *    patternStart = 1
            -	 *    patternEnd = 3
            -	 *    name = { 'a', 'b', 'c' , 'd' }
            -	 *    nameStart = 1
            -	 *    nameEnd = 4
            -	 *    isCaseSensitive = true
            -	 *    result => true
            -	 * 
            - *
          2. - *
          3. -	 *    pattern = { '?', 'b', '*' }
            -	 *    patternStart = 1
            -	 *    patternEnd = 2
            -	 *    name = { 'a', 'b', 'c' , 'd' }
            -	 *    nameStart = 1
            -	 *    nameEnd = 2
            -	 *    isCaseSensitive = true
            -	 *    result => false
            +	 * 
          4. + * + *
            +	 *     pattern = { '?', 'b', '*' }
            +	 *     patternStart = 1
            +	 *     patternEnd = 3
            +	 *     name = { 'a', 'b', 'c' , 'd' }
            +	 *     nameStart = 1
            +	 *     nameEnd = 4
            +	 *     isCaseSensitive = true
            +	 *     result => true
             	 * 
            + * + *
          5. + *
          6. + * + *
            +	 *     pattern = { '?', 'b', '*' }
            +	 *     patternStart = 1
            +	 *     patternEnd = 2
            +	 *     name = { 'a', 'b', 'c' , 'd' }
            +	 *     nameStart = 1
            +	 *     nameEnd = 2
            +	 *     isCaseSensitive = true
            +	 *     result => false
            +	 * 
            + * *
          7. *
          * - * @param pattern the given pattern - * @param patternStart the given pattern start - * @param patternEnd the given pattern end - * @param name the given name - * @param nameStart the given name start - * @param nameEnd the given name end - * @param isCaseSensitive flag to know if the matching should be case sensitive - * @return true if the a sub-pattern matches the subpart of the given name, false otherwise + * @param pattern + * the given pattern + * @param patternStart + * the given pattern start + * @param patternEnd + * the given pattern end + * @param name + * the given name + * @param nameStart + * the given name start + * @param nameEnd + * the given name end + * @param isCaseSensitive + * flag to know if the matching should be case sensitive + * @return true if the a sub-pattern matches the subpart of the given name, + * false otherwise */ - public static final boolean match( - char[] pattern, - int patternStart, - int patternEnd, - char[] name, - int nameStart, - int nameEnd, - boolean isCaseSensitive) { + public static final boolean match(char[] pattern, int patternStart, + int patternEnd, char[] name, int nameStart, int nameEnd, + boolean isCaseSensitive) { if (name == null) return false; // null name cannot match @@ -1531,14 +1848,12 @@ public final class CharOperation { /* check first segment */ char patternChar = 0; while ((iPattern < patternEnd) - && (patternChar = pattern[iPattern]) != '*') { + && (patternChar = pattern[iPattern]) != '*') { if (iName == nameEnd) return false; - if (patternChar - != (isCaseSensitive - ? name[iName] - : Character.toLowerCase(name[iName])) - && patternChar != '?') { + if (patternChar != (isCaseSensitive ? name[iName] : Character + .toLowerCase(name[iName])) + && patternChar != '?') { return false; } iName++; @@ -1552,9 +1867,10 @@ public final class CharOperation { segmentStart = 0; // force iName check } int prefixStart = iName; - checkSegment : while (iName < nameEnd) { + checkSegment: while (iName < nameEnd) { if (iPattern == patternEnd) { - iPattern = segmentStart; // mismatch - restart current segment + iPattern = segmentStart; // mismatch - restart current + // segment iName = ++prefixStart; continue checkSegment; } @@ -1568,10 +1884,11 @@ public final class CharOperation { continue checkSegment; } /* check current name character */ - if ((isCaseSensitive ? name[iName] : Character.toLowerCase(name[iName])) - != patternChar + if ((isCaseSensitive ? name[iName] : Character + .toLowerCase(name[iName])) != patternChar && patternChar != '?') { - iPattern = segmentStart; // mismatch - restart current segment + iPattern = segmentStart; // mismatch - restart current + // segment iName = ++prefixStart; continue checkSegment; } @@ -1580,34 +1897,37 @@ public final class CharOperation { } return (segmentStart == patternEnd) - || (iName == nameEnd && iPattern == patternEnd) - || (iPattern == patternEnd - 1 && pattern[iPattern] == '*'); + || (iName == nameEnd && iPattern == patternEnd) + || (iPattern == patternEnd - 1 && pattern[iPattern] == '*'); } /** - * Answers true if the pattern matches the filepath using the pathSepatator, false otherwise. - * - * Path char[] pattern matching, accepting wild-cards '**', '*' and '?' (using Ant directory tasks - * conventions, also see "http://jakarta.apache.org/ant/manual/dirtasks.html#defaultexcludes"). - * Path pattern matching is enhancing regular pattern matching in supporting extra rule where '**' represent - * any folder combination. - * Special rules: - * - foo\ is equivalent to foo\** - * - *.php is equivalent to **\*.php - * When not case sensitive, the pattern is assumed to already be lowercased, the - * name will be lowercased character per character as comparing. - * - * @param pattern the given pattern - * @param filepath the given path - * @param isCaseSensitive to find out whether or not the matching should be case sensitive - * @param pathSeparator the given path separator - * @return true if the pattern matches the filepath using the pathSepatator, false otherwise + * Answers true if the pattern matches the filepath using the pathSepatator, + * false otherwise. + * + * Path char[] pattern matching, accepting wild-cards '**', '*' and '?' + * (using Ant directory tasks conventions, also see + * "http://jakarta.apache.org/ant/manual/dirtasks.html#defaultexcludes"). + * Path pattern matching is enhancing regular pattern matching in supporting + * extra rule where '**' represent any folder combination. Special rules: - + * foo\ is equivalent to foo\** - *.php is equivalent to **\*.php When not + * case sensitive, the pattern is assumed to already be lowercased, the name + * will be lowercased character per character as comparing. + * + * @param pattern + * the given pattern + * @param filepath + * the given path + * @param isCaseSensitive + * to find out whether or not the matching should be case + * sensitive + * @param pathSeparator + * the given path separator + * @return true if the pattern matches the filepath using the pathSepatator, + * false otherwise */ - public static final boolean pathMatch( - char[] pattern, - char[] filepath, - boolean isCaseSensitive, - char pathSeparator) { + public static final boolean pathMatch(char[] pattern, char[] filepath, + boolean isCaseSensitive, char pathSeparator) { if (filepath == null) return false; // null name cannot match @@ -1620,20 +1940,22 @@ public final class CharOperation { // offsets inside pattern int pSegmentStart, pLength = pattern.length; - if (freeLeadingDoubleStar = pattern[0] != pathSeparator){ + if (freeLeadingDoubleStar = pattern[0] != pathSeparator) { pSegmentStart = 0; } else { pSegmentStart = 1; } - int pSegmentEnd = CharOperation.indexOf(pathSeparator, pattern, pSegmentStart+1); - if (pSegmentEnd < 0) pSegmentEnd = pLength; + int pSegmentEnd = CharOperation.indexOf(pathSeparator, pattern, + pSegmentStart + 1); + if (pSegmentEnd < 0) + pSegmentEnd = pLength; // special case: pattern foo\ is equivalent to foo\** boolean freeTrailingDoubleStar = pattern[pLength - 1] == pathSeparator; // offsets inside filepath int fSegmentStart, fLength = filepath.length; - if (filepath[0] != pathSeparator){ + if (filepath[0] != pathSeparator) { fSegmentStart = 0; } else { fSegmentStart = 1; @@ -1641,145 +1963,125 @@ public final class CharOperation { if (fSegmentStart != pSegmentStart) { return false; // both must start with a separator or none. } - int fSegmentEnd = CharOperation.indexOf(pathSeparator, filepath, fSegmentStart+1); - if (fSegmentEnd < 0) fSegmentEnd = fLength; + int fSegmentEnd = CharOperation.indexOf(pathSeparator, filepath, + fSegmentStart + 1); + if (fSegmentEnd < 0) + fSegmentEnd = fLength; // first segments while (pSegmentStart < pLength - && !freeLeadingDoubleStar - && !(pSegmentEnd == pLength && freeTrailingDoubleStar - || (pSegmentEnd == pSegmentStart + 2 - && pattern[pSegmentStart] == '*' - && pattern[pSegmentStart + 1] == '*'))) { + && !freeLeadingDoubleStar + && !(pSegmentEnd == pLength && freeTrailingDoubleStar || (pSegmentEnd == pSegmentStart + 2 + && pattern[pSegmentStart] == '*' && pattern[pSegmentStart + 1] == '*'))) { if (fSegmentStart >= fLength) return false; - if (!CharOperation - .match( - pattern, - pSegmentStart, - pSegmentEnd, - filepath, - fSegmentStart, - fSegmentEnd, - isCaseSensitive)) { + if (!CharOperation.match(pattern, pSegmentStart, pSegmentEnd, + filepath, fSegmentStart, fSegmentEnd, isCaseSensitive)) { return false; } - // jump to next segment - pSegmentEnd = - CharOperation.indexOf( - pathSeparator, - pattern, + // jump to next segment + pSegmentEnd = CharOperation.indexOf(pathSeparator, pattern, pSegmentStart = pSegmentEnd + 1); // skip separator if (pSegmentEnd < 0) pSegmentEnd = pLength; - fSegmentEnd = - CharOperation.indexOf( - pathSeparator, - filepath, + fSegmentEnd = CharOperation.indexOf(pathSeparator, filepath, fSegmentStart = fSegmentEnd + 1); // skip separator - if (fSegmentEnd < 0) fSegmentEnd = fLength; + if (fSegmentEnd < 0) + fSegmentEnd = fLength; } /* check sequence of doubleStar+segment */ int pSegmentRestart; if ((pSegmentStart >= pLength && freeTrailingDoubleStar) || (pSegmentEnd == pSegmentStart + 2 - && pattern[pSegmentStart] == '*' - && pattern[pSegmentStart + 1] == '*')) { - pSegmentEnd = - CharOperation.indexOf( - pathSeparator, - pattern, + && pattern[pSegmentStart] == '*' && pattern[pSegmentStart + 1] == '*')) { + pSegmentEnd = CharOperation.indexOf(pathSeparator, pattern, pSegmentStart = pSegmentEnd + 1); // skip separator - if (pSegmentEnd < 0) pSegmentEnd = pLength; + if (pSegmentEnd < 0) + pSegmentEnd = pLength; pSegmentRestart = pSegmentStart; } else { pSegmentRestart = 0; // force fSegmentStart check } int fSegmentRestart = fSegmentStart; - checkSegment : while (fSegmentStart < fLength) { - + checkSegment: while (fSegmentStart < fLength) { + if (pSegmentStart >= pLength) { - if (freeTrailingDoubleStar) return true; + if (freeTrailingDoubleStar) + return true; // mismatch - restart current path segment - pSegmentEnd = - CharOperation.indexOf(pathSeparator, pattern, pSegmentStart = pSegmentRestart); - if (pSegmentEnd < 0) pSegmentEnd = pLength; + pSegmentEnd = CharOperation.indexOf(pathSeparator, pattern, + pSegmentStart = pSegmentRestart); + if (pSegmentEnd < 0) + pSegmentEnd = pLength; - fSegmentRestart = - CharOperation.indexOf(pathSeparator, filepath, fSegmentRestart + 1); + fSegmentRestart = CharOperation.indexOf(pathSeparator, + filepath, fSegmentRestart + 1); // skip separator if (fSegmentRestart < 0) { fSegmentRestart = fLength; } else { fSegmentRestart++; } - fSegmentEnd = - CharOperation.indexOf(pathSeparator, filepath, fSegmentStart = fSegmentRestart); - if (fSegmentEnd < 0) fSegmentEnd = fLength; + fSegmentEnd = CharOperation.indexOf(pathSeparator, filepath, + fSegmentStart = fSegmentRestart); + if (fSegmentEnd < 0) + fSegmentEnd = fLength; continue checkSegment; } - + /* path segment is ending */ if (pSegmentEnd == pSegmentStart + 2 - && pattern[pSegmentStart] == '*' - && pattern[pSegmentStart + 1] == '*') { - pSegmentEnd = - CharOperation.indexOf(pathSeparator, pattern, pSegmentStart = pSegmentEnd + 1); + && pattern[pSegmentStart] == '*' + && pattern[pSegmentStart + 1] == '*') { + pSegmentEnd = CharOperation.indexOf(pathSeparator, pattern, + pSegmentStart = pSegmentEnd + 1); // skip separator - if (pSegmentEnd < 0) pSegmentEnd = pLength; + if (pSegmentEnd < 0) + pSegmentEnd = pLength; pSegmentRestart = pSegmentStart; fSegmentRestart = fSegmentStart; - if (pSegmentStart >= pLength) return true; + if (pSegmentStart >= pLength) + return true; continue checkSegment; } /* chech current path segment */ - if (!CharOperation.match( - pattern, - pSegmentStart, - pSegmentEnd, - filepath, - fSegmentStart, - fSegmentEnd, - isCaseSensitive)) { + if (!CharOperation.match(pattern, pSegmentStart, pSegmentEnd, + filepath, fSegmentStart, fSegmentEnd, isCaseSensitive)) { // mismatch - restart current path segment - pSegmentEnd = - CharOperation.indexOf(pathSeparator, pattern, pSegmentStart = pSegmentRestart); - if (pSegmentEnd < 0) pSegmentEnd = pLength; + pSegmentEnd = CharOperation.indexOf(pathSeparator, pattern, + pSegmentStart = pSegmentRestart); + if (pSegmentEnd < 0) + pSegmentEnd = pLength; - fSegmentRestart = - CharOperation.indexOf(pathSeparator, filepath, fSegmentRestart + 1); + fSegmentRestart = CharOperation.indexOf(pathSeparator, + filepath, fSegmentRestart + 1); // skip separator if (fSegmentRestart < 0) { fSegmentRestart = fLength; } else { fSegmentRestart++; } - fSegmentEnd = - CharOperation.indexOf(pathSeparator, filepath, fSegmentStart = fSegmentRestart); - if (fSegmentEnd < 0) fSegmentEnd = fLength; + fSegmentEnd = CharOperation.indexOf(pathSeparator, filepath, + fSegmentStart = fSegmentRestart); + if (fSegmentEnd < 0) + fSegmentEnd = fLength; continue checkSegment; } - // jump to next segment - pSegmentEnd = - CharOperation.indexOf( - pathSeparator, - pattern, + // jump to next segment + pSegmentEnd = CharOperation.indexOf(pathSeparator, pattern, pSegmentStart = pSegmentEnd + 1); // skip separator if (pSegmentEnd < 0) pSegmentEnd = pLength; - fSegmentEnd = - CharOperation.indexOf( - pathSeparator, - filepath, + fSegmentEnd = CharOperation.indexOf(pathSeparator, filepath, fSegmentStart = fSegmentEnd + 1); // skip separator if (fSegmentEnd < 0) @@ -1787,38 +2089,48 @@ public final class CharOperation { } return (pSegmentRestart >= pSegmentEnd) - || (fSegmentStart >= fLength && pSegmentStart >= pLength) - || (pSegmentStart == pLength - 2 - && pattern[pSegmentStart] == '*' - && pattern[pSegmentStart + 1] == '*') - || (pSegmentStart == pLength && freeTrailingDoubleStar); + || (fSegmentStart >= fLength && pSegmentStart >= pLength) + || (pSegmentStart == pLength - 2 + && pattern[pSegmentStart] == '*' && pattern[pSegmentStart + 1] == '*') + || (pSegmentStart == pLength && freeTrailingDoubleStar); } /** - * Answers the number of occurrences of the given character in the given array, 0 if any. + * Answers the number of occurrences of the given character in the given + * array, 0 if any. * *
          *
          * For example: *
            - *
          1. -	 *    toBeFound = 'b'
            -	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            -	 *    result => 3
            +	 * 
          2. + * + *
            +	 *     toBeFound = 'b'
            +	 *     array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            +	 *     result => 3
             	 * 
            + * *
          3. - *
          4. -	 *    toBeFound = 'c'
            -	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            -	 *    result => 0
            +	 * 
          5. + * + *
            +	 *     toBeFound = 'c'
            +	 *     array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            +	 *     result => 0
             	 * 
            + * *
          6. *
          * - * @param toBeFound the given character - * @param array the given array - * @return the number of occurrences of the given character in the given array, 0 if any - * @exception NullPointerException if array is null + * @param toBeFound + * the given character + * @param array + * the given array + * @return the number of occurrences of the given character in the given + * array, 0 if any + * @exception NullPointerException + * if array is null */ public static final int occurencesOf(char toBeFound, char[] array) { int count = 0; @@ -1829,39 +2141,47 @@ public final class CharOperation { } /** - * Answers the number of occurrences of the given character in the given array starting - * at the given index, 0 if any. + * Answers the number of occurrences of the given character in the given + * array starting at the given index, 0 if any. * *
          *
          * For example: *
            - *
          1. -	 *    toBeFound = 'b'
            -	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            -	 *    start = 2
            -	 *    result => 2
            +	 * 
          2. + * + *
            +	 *     toBeFound = 'b'
            +	 *     array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            +	 *     start = 2
            +	 *     result => 2
             	 * 
            + * *
          3. - *
          4. -	 *    toBeFound = 'c'
            -	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            -	 *    start = 0
            -	 *    result => 0
            +	 * 
          5. + * + *
            +	 *     toBeFound = 'c'
            +	 *     array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            +	 *     start = 0
            +	 *     result => 0
             	 * 
            + * *
          6. *
          * - * @param toBeFound the given character - * @param array the given array - * @return the number of occurrences of the given character in the given array, 0 if any - * @exception NullPointerException if array is null - * @exception ArrayIndexOutOfBoundsException if start is lower than 0 + * @param toBeFound + * the given character + * @param array + * the given array + * @return the number of occurrences of the given character in the given + * array, 0 if any + * @exception NullPointerException + * if array is null + * @exception ArrayIndexOutOfBoundsException + * if start is lower than 0 */ - public static final int occurencesOf( - char toBeFound, - char[] array, - int start) { + public static final int occurencesOf(char toBeFound, char[] array, int start) { int count = 0; for (int i = start; i < array.length; i++) if (toBeFound == array[i]) @@ -1870,131 +2190,154 @@ public final class CharOperation { } /** - * Answers true if the given name starts with the given prefix, false otherwise. - * The comparison is case sensitive. - *
          + * Answers true if the given name starts with the given prefix, false + * otherwise. The comparison is case sensitive.
          *
          * For example: *
            - *
          1. -	 *    prefix = { 'a' , 'b' }
            -	 *    name = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            -	 *    result => true
            +	 * 
          2. + * + *
            +	 *     prefix = { 'a' , 'b' }
            +	 *     name = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            +	 *     result => true
             	 * 
            + * *
          3. - *
          4. -	 *    prefix = { 'a' , 'c' }
            -	 *    name = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            -	 *    result => false
            +	 * 
          5. + * + *
            +	 *     prefix = { 'a' , 'c' }
            +	 *     name = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            +	 *     result => false
             	 * 
            + * *
          6. *
          * - * @param prefix the given prefix - * @param name the given name - * @return true if the given name starts with the given prefix, false otherwise - * @exception NullPointerException if the given name is null or if the given prefix is null + * @param prefix + * the given prefix + * @param name + * the given name + * @return true if the given name starts with the given prefix, false + * otherwise + * @exception NullPointerException + * if the given name is null or if the given prefix is null */ public static final boolean prefixEquals(char[] prefix, char[] name) { int max = prefix.length; if (name.length < max) return false; - for (int i = max; - --i >= 0; - ) // assumes the prefix is not larger than the name + for (int i = max; --i >= 0;) + // assumes the prefix is not larger than the name if (prefix[i] != name[i]) return false; return true; } /** - * Answers true if the given name starts with the given prefix, false otherwise. - * isCaseSensitive is used to find out whether or not the comparison should be case sensitive. - *
          + * Answers true if the given name starts with the given prefix, false + * otherwise. isCaseSensitive is used to find out whether or not the + * comparison should be case sensitive.
          *
          * For example: *
            - *
          1. -	 *    prefix = { 'a' , 'B' }
            -	 *    name = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            -	 *    isCaseSensitive = false
            -	 *    result => true
            +	 * 
          2. + * + *
            +	 *     prefix = { 'a' , 'B' }
            +	 *     name = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            +	 *     isCaseSensitive = false
            +	 *     result => true
             	 * 
            + * *
          3. - *
          4. -	 *    prefix = { 'a' , 'B' }
            -	 *    name = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            -	 *    isCaseSensitive = true
            -	 *    result => false
            +	 * 
          5. + * + *
            +	 *     prefix = { 'a' , 'B' }
            +	 *     name = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            +	 *     isCaseSensitive = true
            +	 *     result => false
             	 * 
            + * *
          6. *
          * - * @param prefix the given prefix - * @param name the given name - * @param isCaseSensitive to find out whether or not the comparison should be case sensitive - * @return true if the given name starts with the given prefix, false otherwise - * @exception NullPointerException if the given name is null or if the given prefix is null + * @param prefix + * the given prefix + * @param name + * the given name + * @param isCaseSensitive + * to find out whether or not the comparison should be case + * sensitive + * @return true if the given name starts with the given prefix, false + * otherwise + * @exception NullPointerException + * if the given name is null or if the given prefix is null */ - public static final boolean prefixEquals( - char[] prefix, - char[] name, - boolean isCaseSensitive) { + public static final boolean prefixEquals(char[] prefix, char[] name, + boolean isCaseSensitive) { int max = prefix.length; if (name.length < max) return false; if (isCaseSensitive) { - for (int i = max; - --i >= 0; - ) // assumes the prefix is not larger than the name + for (int i = max; --i >= 0;) + // assumes the prefix is not larger than the name if (prefix[i] != name[i]) return false; return true; } - for (int i = max; - --i >= 0; - ) // assumes the prefix is not larger than the name - if (Character.toLowerCase(prefix[i]) - != Character.toLowerCase(name[i])) + for (int i = max; --i >= 0;) + // assumes the prefix is not larger than the name + if (Character.toLowerCase(prefix[i]) != Character + .toLowerCase(name[i])) return false; return true; } /** - * Replace all occurrence of the character to be replaced with the remplacement character in the - * given array. - *
          + * Replace all occurrence of the character to be replaced with the + * remplacement character in the given array.
          *
          * For example: *
            - *
          1. -	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            -	 *    toBeReplaced = 'b'
            -	 *    replacementChar = 'a'
            -	 *    result => No returned value, but array is now equals to { 'a' , 'a', 'a', 'a', 'a', 'a' }
            +	 * 
          2. + * + *
            +	 *     array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            +	 *     toBeReplaced = 'b'
            +	 *     replacementChar = 'a'
            +	 *     result => No returned value, but array is now equals to { 'a' , 'a', 'a', 'a', 'a', 'a' }
             	 * 
            + * *
          3. - *
          4. -	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            -	 *    toBeReplaced = 'c'
            -	 *    replacementChar = 'a'
            -	 *    result => No returned value, but array is now equals to { 'a' , 'b', 'b', 'a', 'b', 'a' }
            +	 * 
          5. + * + *
            +	 *     array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            +	 *     toBeReplaced = 'c'
            +	 *     replacementChar = 'a'
            +	 *     result => No returned value, but array is now equals to { 'a' , 'b', 'b', 'a', 'b', 'a' }
             	 * 
            + * *
          6. *
          * - * @param array the given array - * @param toBeReplaced the character to be replaced - * @param replacementChar the replacement character - * @exception NullPointerException if the given array is null + * @param array + * the given array + * @param toBeReplaced + * the character to be replaced + * @param replacementChar + * the replacement character + * @exception NullPointerException + * if the given array is null */ - public static final void replace( - char[] array, - char toBeReplaced, - char replacementChar) { + public static final void replace(char[] array, char toBeReplaced, + char replacementChar) { if (toBeReplaced != replacementChar) { for (int i = 0, max = array.length; i < max; i++) { if (array[i] == toBeReplaced) @@ -2004,39 +2347,47 @@ public final class CharOperation { } /** - * Answers a new array of characters with substitutions. No side-effect is operated on the original - * array, in case no substitution happened, then the result is the same as the - * original one. - *
          + * Answers a new array of characters with substitutions. No side-effect is + * operated on the original array, in case no substitution happened, then + * the result is the same as the original one.
          *
          * For example: *
            - *
          1. -	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            -	 *    toBeReplaced = { 'b' }
            -	 *    replacementChar = { 'a', 'a' }
            -	 *    result => { 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a' }
            +	 * 
          2. + * + *
            +	 *     array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            +	 *     toBeReplaced = { 'b' }
            +	 *     replacementChar = { 'a', 'a' }
            +	 *     result => { 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a' }
             	 * 
            + * *
          3. - *
          4. -	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            -	 *    toBeReplaced = { 'c' }
            -	 *    replacementChar = { 'a' }
            -	 *    result => { 'a' , 'b', 'b', 'a', 'b', 'a' }
            +	 * 
          5. + * + *
            +	 *     array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            +	 *     toBeReplaced = { 'c' }
            +	 *     replacementChar = { 'a' }
            +	 *     result => { 'a' , 'b', 'b', 'a', 'b', 'a' }
             	 * 
            + * *
          6. *
          * - * @param the given array - * @param toBeReplaced characters to be replaced - * @param the replacement characters - * @return a new array of characters with substitutions or the given array if none - * @exception NullPointerException if the given array is null + * @param the + * given array + * @param toBeReplaced + * characters to be replaced + * @param the + * replacement characters + * @return a new array of characters with substitutions or the given array + * if none + * @exception NullPointerException + * if the given array is null */ - public static final char[] replace( - char[] array, - char[] toBeReplaced, - char[] replacementChars) { + public static final char[] replace(char[] array, char[] toBeReplaced, + char[] replacementChars) { int max = array.length; int replacedLength = toBeReplaced.length; @@ -2047,7 +2398,7 @@ public final class CharOperation { if (!equals(toBeReplaced, replacementChars)) { - next : for (int i = 0; i < max; i++) { + next: for (int i = 0; i < max; i++) { int j = 0; while (j < replacedLength) { if (i + j == max) @@ -2056,33 +2407,25 @@ public final class CharOperation { continue next; } if (occurrenceCount == starts.length) { - System.arraycopy( - starts, - 0, - starts = new int[occurrenceCount * 2], - 0, - occurrenceCount); + System.arraycopy(starts, 0, + starts = new int[occurrenceCount * 2], 0, + occurrenceCount); } starts[occurrenceCount++] = i; } } if (occurrenceCount == 0) return array; - char[] result = - new char[max - + occurrenceCount * (replacementLength - replacedLength)]; + char[] result = new char[max + occurrenceCount + * (replacementLength - replacedLength)]; int inStart = 0, outStart = 0; for (int i = 0; i < occurrenceCount; i++) { int offset = starts[i] - inStart; System.arraycopy(array, inStart, result, outStart, offset); inStart += offset; outStart += offset; - System.arraycopy( - replacementChars, - 0, - result, - outStart, - replacementLength); + System.arraycopy(replacementChars, 0, result, outStart, + replacementLength); inStart += replacedLength; outStart += replacementLength; } @@ -2091,42 +2434,56 @@ public final class CharOperation { } /** - * Return a new array which is the split of the given array using the given divider and triming each subarray to remove - * whitespaces equals to ' '. + * Return a new array which is the split of the given array using the given + * divider and triming each subarray to remove whitespaces equals to ' '. *
          *
          * For example: *
            - *
          1. -	 *    divider = 'b'
            -	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            -	 *    result => { { 'a' }, {  }, { 'a' }, { 'a' } }
            +	 * 
          2. + * + *
            +	 *     divider = 'b'
            +	 *     array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            +	 *     result => { { 'a' }, {  }, { 'a' }, { 'a' } }
             	 * 
            + * *
          3. - *
          4. -	 *    divider = 'c'
            -	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            -	 *    result => { { 'a', 'b', 'b', 'a', 'b', 'a' } }
            +	 * 
          5. + * + *
            +	 *     divider = 'c'
            +	 *     array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            +	 *     result => { { 'a', 'b', 'b', 'a', 'b', 'a' } }
             	 * 
            + * *
          6. - *
          7. -	 *    divider = 'b'
            -	 *    array = { 'a' , ' ', 'b', 'b', 'a', 'b', 'a' }
            -	 *    result => { { 'a' }, {  }, { 'a' }, { 'a' } }
            +	 * 
          8. + * + *
            +	 *     divider = 'b'
            +	 *     array = { 'a' , ' ', 'b', 'b', 'a', 'b', 'a' }
            +	 *     result => { { 'a' }, {  }, { 'a' }, { 'a' } }
             	 * 
            + * *
          9. - *
          10. -	 *    divider = 'c'
            -	 *    array = { ' ', ' ', 'a' , 'b', 'b', 'a', 'b', 'a', ' ' }
            -	 *    result => { { 'a', 'b', 'b', 'a', 'b', 'a' } }
            +	 * 
          11. + * + *
            +	 *     divider = 'c'
            +	 *     array = { ' ', ' ', 'a' , 'b', 'b', 'a', 'b', 'a', ' ' }
            +	 *     result => { { 'a', 'b', 'b', 'a', 'b', 'a' } }
             	 * 
            + * *
          12. *
          * - * @param divider the given divider - * @param array the given array - * @return a new array which is the split of the given array using the given divider and triming each subarray to remove - * whitespaces equals to ' ' + * @param divider + * the given divider + * @param array + * the given array + * @return a new array which is the split of the given array using the given + * divider and triming each subarray to remove whitespaces equals to ' ' */ public static final char[][] splitAndTrimOn(char divider, char[] array) { int length = array == null ? 0 : array.length; @@ -2147,12 +2504,8 @@ public final class CharOperation { while (end > start && array[end] == ' ') end--; split[currentWord] = new char[end - start + 1]; - System.arraycopy( - array, - start, - split[currentWord++], - 0, - end - start + 1); + System.arraycopy(array, start, split[currentWord++], 0, end + - start + 1); last = i + 1; } } @@ -2162,44 +2515,53 @@ public final class CharOperation { while (end > start && array[end] == ' ') end--; split[currentWord] = new char[end - start + 1]; - System.arraycopy( - array, - start, - split[currentWord++], - 0, - end - start + 1); + System + .arraycopy(array, start, split[currentWord++], 0, end - start + + 1); return split; } /** - * Return a new array which is the split of the given array using the given divider. - *
          + * Return a new array which is the split of the given array using the given + * divider.
          *
          * For example: *
            - *
          1. -	 *    divider = 'b'
            -	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            -	 *    result => { { 'a' }, {  }, { 'a' }, { 'a' } }
            +	 * 
          2. + * + *
            +	 *     divider = 'b'
            +	 *     array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            +	 *     result => { { 'a' }, {  }, { 'a' }, { 'a' } }
             	 * 
            + * *
          3. - *
          4. -	 *    divider = 'c'
            -	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            -	 *    result => { { 'a', 'b', 'b', 'a', 'b', 'a' } }
            +	 * 
          5. + * + *
            +	 *     divider = 'c'
            +	 *     array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            +	 *     result => { { 'a', 'b', 'b', 'a', 'b', 'a' } }
             	 * 
            + * *
          6. - *
          7. -	 *    divider = 'c'
            -	 *    array = { ' ', ' ', 'a' , 'b', 'b', 'a', 'b', 'a', ' ' }
            -	 *    result => { { ' ', 'a', 'b', 'b', 'a', 'b', 'a', ' ' } }
            +	 * 
          8. + * + *
            +	 *     divider = 'c'
            +	 *     array = { ' ', ' ', 'a' , 'b', 'b', 'a', 'b', 'a', ' ' }
            +	 *     result => { { ' ', 'a', 'b', 'b', 'a', 'b', 'a', ' ' } }
             	 * 
            + * *
          9. *
          * - * @param divider the given divider - * @param array the given array - * @return a new array which is the split of the given array using the given divider + * @param divider + * the given divider + * @param array + * the given array + * @return a new array which is the split of the given array using the given + * divider */ public static final char[][] splitOn(char divider, char[] array) { int length = array == null ? 0 : array.length; @@ -2215,12 +2577,9 @@ public final class CharOperation { for (int i = 0; i < length; i++) { if (array[i] == divider) { split[currentWord] = new char[i - last]; - System.arraycopy( - array, - last, - split[currentWord++], - 0, - i - last); + System + .arraycopy(array, last, split[currentWord++], 0, i + - last); last = i + 1; } } @@ -2230,34 +2589,41 @@ public final class CharOperation { } /** - * Return a new array which is the split of the given array using the given divider. The given end - * is exclusive and the given start is inclusive. + * Return a new array which is the split of the given array using the given + * divider. The given end is exclusive and the given start is inclusive. *
          *
          * For example: *
            - *
          1. -	 *    divider = 'b'
            -	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            -	 *    start = 2
            -	 *    end = 5
            -	 *    result => { {  }, {  }, { 'a' } }
            +	 * 
          2. + * + *
            +	 *     divider = 'b'
            +	 *     array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            +	 *     start = 2
            +	 *     end = 5
            +	 *     result => { {  }, {  }, { 'a' } }
             	 * 
            + * *
          3. *
          * - * @param divider the given divider - * @param array the given array - * @param start the given starting index - * @param end the given ending index - * @return a new array which is the split of the given array using the given divider - * @exception ArrayIndexOutOfBoundsException if start is lower than 0 or end is greater than the array length + * @param divider + * the given divider + * @param array + * the given array + * @param start + * the given starting index + * @param end + * the given ending index + * @return a new array which is the split of the given array using the given + * divider + * @exception ArrayIndexOutOfBoundsException + * if start is lower than 0 or end is greater than the array + * length */ - public static final char[][] splitOn( - char divider, - char[] array, - int start, - int end) { + public static final char[][] splitOn(char divider, char[] array, int start, + int end) { int length = array == null ? 0 : array.length; if (length == 0 || start > end) return NO_CHAR_CHAR; @@ -2271,12 +2637,9 @@ public final class CharOperation { for (int i = start; i < end; i++) { if (array[i] == divider) { split[currentWord] = new char[i - last]; - System.arraycopy( - array, - last, - split[currentWord++], - 0, - i - last); + System + .arraycopy(array, last, split[currentWord++], 0, i + - last); last = i + 1; } } @@ -2286,30 +2649,40 @@ public final class CharOperation { } /** - * Answers true if the given array starts with the given characters, false otherwise. - * The comparison is case sensitive. - *
          + * Answers true if the given array starts with the given characters, false + * otherwise. The comparison is case sensitive.
          *
          * For example: *
            - *
          1. -	 *    toBeFound = { 'a' , 'b' }
            -	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            -	 *    result => true
            +	 * 
          2. + * + *
            +	 *     toBeFound = { 'a' , 'b' }
            +	 *     array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            +	 *     result => true
             	 * 
            + * *
          3. - *
          4. -	 *    toBeFound = { 'a' , 'c' }
            -	 *    array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            -	 *    result => false
            +	 * 
          5. + * + *
            +	 *     toBeFound = { 'a' , 'c' }
            +	 *     array = { 'a' , 'b', 'b', 'a', 'b', 'a' }
            +	 *     result => false
             	 * 
            + * *
          6. *
          * - * @param array the given array - * @param toBeFound the given character to search - * @return true if the given array starts with the given characters, false otherwise - * @exception NullPointerException if the given array is null or if the given characters array to be found is null + * @param array + * the given array + * @param toBeFound + * the given character to search + * @return true if the given array starts with the given characters, false + * otherwise + * @exception NullPointerException + * if the given array is null or if the given characters + * array to be found is null */ public static final boolean startsWith(char[] array, char[] toBeFound) { int i = toBeFound.length; @@ -2320,38 +2693,48 @@ public final class CharOperation { return false; return true; } - + /** - * Answers a new array which is a copy of the given array starting at the given start and - * ending at the given end. The given start is inclusive and the given end is exclusive. - * Answers null if start is greater than end, if start is lower than 0 or if end is greater - * than the length of the given array. If end equals -1, it is converted to the array length. - *
          + * Answers a new array which is a copy of the given array starting at the + * given start and ending at the given end. The given start is inclusive and + * the given end is exclusive. Answers null if start is greater than end, if + * start is lower than 0 or if end is greater than the length of the given + * array. If end equals -1, it is converted to the array length.
          *
          * For example: *
            - *
          1. -	 *    array = { { 'a' } , { 'b' } }
            -	 *    start = 0
            -	 *    end = 1
            -	 *    result => { { 'a' } }
            +	 * 
          2. + * + *
            +	 *     array = { { 'a' } , { 'b' } }
            +	 *     start = 0
            +	 *     end = 1
            +	 *     result => { { 'a' } }
             	 * 
            + * *
          3. - *
          4. -	 *    array = { { 'a' } , { 'b' } }
            -	 *    start = 0
            -	 *    end = -1
            -	 *    result => { { 'a' }, { 'b' } }
            +	 * 
          5. + * + *
            +	 *     array = { { 'a' } , { 'b' } }
            +	 *     start = 0
            +	 *     end = -1
            +	 *     result => { { 'a' }, { 'b' } }
             	 * 
            + * *
          6. *
          - * - * @param array the given array - * @param start the given starting index - * @param end the given ending index - * @return a new array which is a copy of the given array starting at the given start and - * ending at the given end - * @exception NullPointerException if the given array is null + * + * @param array + * the given array + * @param start + * the given starting index + * @param end + * the given ending index + * @return a new array which is a copy of the given array starting at the + * given start and ending at the given end + * @exception NullPointerException + * if the given array is null */ public static final char[][] subarray(char[][] array, int start, int end) { if (end == -1) @@ -2369,36 +2752,46 @@ public final class CharOperation { } /** - * Answers a new array which is a copy of the given array starting at the given start and - * ending at the given end. The given start is inclusive and the given end is exclusive. - * Answers null if start is greater than end, if start is lower than 0 or if end is greater - * than the length of the given array. If end equals -1, it is converted to the array length. - *
          + * Answers a new array which is a copy of the given array starting at the + * given start and ending at the given end. The given start is inclusive and + * the given end is exclusive. Answers null if start is greater than end, if + * start is lower than 0 or if end is greater than the length of the given + * array. If end equals -1, it is converted to the array length.
          *
          * For example: *
            - *
          1. -	 *    array = { 'a' , 'b' }
            -	 *    start = 0
            -	 *    end = 1
            -	 *    result => { 'a' }
            +	 * 
          2. + * + *
            +	 *     array = { 'a' , 'b' }
            +	 *     start = 0
            +	 *     end = 1
            +	 *     result => { 'a' }
             	 * 
            + * *
          3. - *
          4. -	 *    array = { 'a', 'b' }
            -	 *    start = 0
            -	 *    end = -1
            -	 *    result => { 'a' , 'b' }
            +	 * 
          5. + * + *
            +	 *     array = { 'a', 'b' }
            +	 *     start = 0
            +	 *     end = -1
            +	 *     result => { 'a' , 'b' }
             	 * 
            + * *
          6. *
          - * - * @param array the given array - * @param start the given starting index - * @param end the given ending index - * @return a new array which is a copy of the given array starting at the given start and - * ending at the given end - * @exception NullPointerException if the given array is null + * + * @param array + * the given array + * @param start + * the given starting index + * @param end + * the given ending index + * @return a new array which is a copy of the given array starting at the + * given start and ending at the given end + * @exception NullPointerException + * if the given array is null */ public static final char[] subarray(char[] array, int start, int end) { if (end == -1) @@ -2414,27 +2807,35 @@ public final class CharOperation { System.arraycopy(array, start, result, 0, end - start); return result; } + /** - * Answers the result of a char[] conversion to lowercase. Answers null if the given chars array is null. - *
          + * Answers the result of a char[] conversion to lowercase. Answers null if + * the given chars array is null.
          * NOTE: if no conversion was necessary, then answers back the argument one. *
          *
          * For example: *
            - *
          1. -	 *    chars = { 'a' , 'b' }
            -	 *    result => { 'a' , 'b' }
            +	 * 
          2. + * + *
            +	 *     chars = { 'a' , 'b' }
            +	 *     result => { 'a' , 'b' }
             	 * 
            + * *
          3. - *
          4. -	 *    array = { 'A', 'b' }
            -	 *    result => { 'a' , 'b' }
            +	 * 
          5. + * + *
            +	 *     array = { 'A', 'b' }
            +	 *     result => { 'a' , 'b' }
             	 * 
            + * *
          6. *
          * - * @param chars the chars to convert + * @param chars + * the chars to convert * @return the result of a char[] conversion to lowercase */ final static public char[] toLowerCase(char[] chars) { @@ -2447,12 +2848,8 @@ public final class CharOperation { char lc = Character.toLowerCase(c); if ((c != lc) || (lowerChars != null)) { if (lowerChars == null) { - System.arraycopy( - chars, - 0, - lowerChars = new char[length], - 0, - i); + System.arraycopy(chars, 0, lowerChars = new char[length], + 0, i); } lowerChars[i] = lc; } @@ -2461,25 +2858,31 @@ public final class CharOperation { } /** - * Answers a new array removing leading and trailing spaces (' '). Answers the given array if there is no - * space characters to remove. - *
          + * Answers a new array removing leading and trailing spaces (' '). Answers + * the given array if there is no space characters to remove.
          *
          * For example: *
            - *
          1. -	 *    chars = { ' ', 'a' , 'b', ' ',  ' ' }
            -	 *    result => { 'a' , 'b' }
            +	 * 
          2. + * + *
            +	 *     chars = { ' ', 'a' , 'b', ' ',  ' ' }
            +	 *     result => { 'a' , 'b' }
             	 * 
            + * *
          3. - *
          4. -	 *    array = { 'A', 'b' }
            -	 *    result => { 'A' , 'b' }
            +	 * 
          5. + * + *
            +	 *     array = { 'A', 'b' }
            +	 *     result => { 'A' , 'b' }
             	 * 
            + * *
          6. *
          * - * @param chars the given array + * @param chars + * the given array * @return a new array removing leading and trailing spaces (' ') */ final static public char[] trim(char[] chars) { @@ -2501,25 +2904,33 @@ public final class CharOperation { } /** - * Answers a string which is the concatenation of the given array using the '.' as a separator. - *
          + * Answers a string which is the concatenation of the given array using the + * '.' as a separator.
          *
          * For example: *
            - *
          1. -	 *    array = { { 'a' } , { 'b' } }
            -	 *    result => "a.b"
            +	 * 
          2. + * + *
            +	 *     array = { { 'a' } , { 'b' } }
            +	 *     result => "a.b"
             	 * 
            + * *
          3. - *
          4. -	 *    array = { { ' ',  'a' } , { 'b' } }
            -	 *    result => " a.b"
            +	 * 
          5. + * + *
            +	 *     array = { { ' ',  'a' } , { 'b' } }
            +	 *     result => " a.b"
             	 * 
            + * *
          6. *
          * - * @param chars the given array - * @return a string which is the concatenation of the given array using the '.' as a separator + * @param chars + * the given array + * @return a string which is the concatenation of the given array using the + * '.' as a separator */ final static public String toString(char[][] array) { char[] result = concatWith(array, '.'); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/IProblem.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/IProblem.java index 24cd371..85b68a2 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/IProblem.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/IProblem.java @@ -33,31 +33,35 @@ * IncompatibleExceptionInThrowsClauseForNonInheritedInterfaceMethod *******************************************************************************/ package net.sourceforge.phpdt.core.compiler; - + import net.sourceforge.phpdt.internal.compiler.lookup.ProblemReasons; /** - * Description of a Java problem, as detected by the compiler or some of the underlying - * technology reusing the compiler. - * A problem provides access to: + * Description of a Java problem, as detected by the compiler or some of the + * underlying technology reusing the compiler. A problem provides access to: *
            - *
          • its location (originating source file name, source position, line number),
          • - *
          • its message description and a predicate to check its severity (warning or error).
          • - *
          • its ID : an number identifying the very nature of this problem. All possible IDs are listed - * as constants on this interface.
          • + *
          • its location (originating source file name, source position, line + * number),
          • + *
          • its message description and a predicate to check its severity (warning + * or error).
          • + *
          • its ID : an number identifying the very nature of this problem. All + * possible IDs are listed as constants on this interface.
          • *
          * - * Note: the compiler produces IProblems internally, which are turned into markers by the JavaBuilder - * so as to persist problem descriptions. This explains why there is no API allowing to reach IProblem detected - * when compiling. However, the Java problem markers carry equivalent information to IProblem, in particular - * their ID (attribute "id") is set to one of the IDs defined on this interface. + * Note: the compiler produces IProblems internally, which are turned into + * markers by the JavaBuilder so as to persist problem descriptions. This + * explains why there is no API allowing to reach IProblem detected when + * compiling. However, the Java problem markers carry equivalent information to + * IProblem, in particular their ID (attribute "id") is set to one of the IDs + * defined on this interface. * * @since 2.0 */ -public interface IProblem { - +public interface IProblem { + /** * Answer back the original arguments recorded into the problem. + * * @return the original arguments recorded into the problem */ String[] getArguments(); @@ -70,9 +74,11 @@ public interface IProblem { int getID(); /** - * Answer a localized, human-readable message string which describes the problem. + * Answer a localized, human-readable message string which describes the + * problem. * - * @return a localized, human-readable message string which describes the problem + * @return a localized, human-readable message string which describes the + * problem */ String getMessage(); @@ -82,7 +88,7 @@ public interface IProblem { * @return the file name in which the problem was found */ char[] getOriginatingFileName(); - + /** * Answer the end position of the problem (inclusive), or -1 if unknown. * @@ -114,68 +120,84 @@ public interface IProblem { /** * Checks the severity to see if the Error bit is not set. * - * @return true if the Error bit is not set for the severity, false otherwise + * @return true if the Error bit is not set for the severity, false + * otherwise */ boolean isWarning(); /** - * Set the end position of the problem (inclusive), or -1 if unknown. - * Used for shifting problem positions. + * Set the end position of the problem (inclusive), or -1 if unknown. Used + * for shifting problem positions. * - * @param sourceEnd the given end position + * @param sourceEnd + * the given end position */ void setSourceEnd(int sourceEnd); /** * Set the line number in source where the problem begins. * - * @param lineNumber the given line number + * @param lineNumber + * the given line number */ void setSourceLineNumber(int lineNumber); /** - * Set the start position of the problem (inclusive), or -1 if unknown. - * Used for shifting problem positions. + * Set the start position of the problem (inclusive), or -1 if unknown. Used + * for shifting problem positions. * - * @param the given start position + * @param the + * given start position */ void setSourceStart(int sourceStart); - + /** - * Problem Categories - * The high bits of a problem ID contains information about the category of a problem. - * For example, (problemID & TypeRelated) != 0, indicates that this problem is type related. + * Problem Categories The high bits of a problem ID contains information + * about the category of a problem. For example, (problemID & TypeRelated) != + * 0, indicates that this problem is type related. * - * A problem category can help to implement custom problem filters. Indeed, when numerous problems - * are listed, focusing on import related problems first might be relevant. + * A problem category can help to implement custom problem filters. Indeed, + * when numerous problems are listed, focusing on import related problems + * first might be relevant. * - * When a problem is tagged as Internal, it means that no change other than a local source code change - * can fix the corresponding problem. + * When a problem is tagged as Internal, it means that no change other than + * a local source code change can fix the corresponding problem. */ int TypeRelated = 0x01000000; + int FieldRelated = 0x02000000; + int MethodRelated = 0x04000000; + int ConstructorRelated = 0x08000000; + int ImportRelated = 0x10000000; + int Internal = 0x20000000; - int Syntax = 0x40000000; + + int Syntax = 0x40000000; + /** * @since 3.0 */ int Javadoc = 0x80000000; + /** - * Mask to use in order to filter out the category portion of the problem ID. + * Mask to use in order to filter out the category portion of the problem + * ID. */ int IgnoreCategoriesMask = 0xFFFFFF; /** - * Below are listed all available problem IDs. Note that this list could be augmented in the future, - * as new features are added to the Java core implementation. + * Below are listed all available problem IDs. Note that this list could be + * augmented in the future, as new features are added to the Java core + * implementation. */ /** - * ID reserved for referencing an internal error inside the JavaCore implementation which - * may be surfaced as a problem associated with the compilation unit which caused it to occur. + * ID reserved for referencing an internal error inside the JavaCore + * implementation which may be surfaced as a problem associated with the + * compilation unit which caused it to occur. */ int Unclassified = 0; @@ -183,489 +205,830 @@ public interface IProblem { * Generic type related problems */ int ObjectHasNoSuperclass = TypeRelated + 1; + int UndefinedType = TypeRelated + 2; + int NotVisibleType = TypeRelated + 3; + int AmbiguousType = TypeRelated + 4; + int UsingDeprecatedType = TypeRelated + 5; + int InternalTypeNameProvided = TypeRelated + 6; + /** @since 2.1 */ int UnusedPrivateType = Internal + TypeRelated + 7; - + int IncompatibleTypesInEqualityOperator = TypeRelated + 15; + int IncompatibleTypesInConditionalOperator = TypeRelated + 16; + int TypeMismatch = TypeRelated + 17; /** * Inner types related problems */ int MissingEnclosingInstanceForConstructorCall = TypeRelated + 20; + int MissingEnclosingInstance = TypeRelated + 21; + int IncorrectEnclosingInstanceReference = TypeRelated + 22; - int IllegalEnclosingInstanceSpecification = TypeRelated + 23; + + int IllegalEnclosingInstanceSpecification = TypeRelated + 23; + int CannotDefineStaticInitializerInLocalType = Internal + 24; + int OuterLocalMustBeFinal = Internal + 25; + int CannotDefineInterfaceInLocalType = Internal + 26; + int IllegalPrimitiveOrArrayTypeForEnclosingInstance = TypeRelated + 27; + /** @since 2.1 */ int EnclosingInstanceInConstructorCall = Internal + 28; + int AnonymousClassCannotExtendFinalClass = TypeRelated + 29; // variables int UndefinedName = 50; + int UninitializedLocalVariable = Internal + 51; + int VariableTypeCannotBeVoid = Internal + 52; + int VariableTypeCannotBeVoidArray = Internal + 53; + int CannotAllocateVoidArray = Internal + 54; + // local variables int RedefinedLocal = Internal + 55; + int RedefinedArgument = Internal + 56; + // final local variables int DuplicateFinalLocalInitialization = Internal + 57; + /** @since 2.1 */ int NonBlankFinalLocalAssignment = Internal + 58; + int FinalOuterLocalAssignment = Internal + 60; + int LocalVariableIsNeverUsed = Internal + 61; + int ArgumentIsNeverUsed = Internal + 62; + int BytecodeExceeds64KLimit = Internal + 63; + int BytecodeExceeds64KLimitForClinit = Internal + 64; + int TooManyArgumentSlots = Internal + 65; + int TooManyLocalVariableSlots = Internal + 66; + /** @since 2.1 */ int TooManySyntheticArgumentSlots = Internal + 67; + /** @since 2.1 */ int TooManyArrayDimensions = Internal + 68; + /** @since 2.1 */ int BytecodeExceeds64KLimitForConstructor = Internal + 69; // fields int UndefinedField = FieldRelated + 70; + int NotVisibleField = FieldRelated + 71; + int AmbiguousField = FieldRelated + 72; + int UsingDeprecatedField = FieldRelated + 73; + int NonStaticFieldFromStaticInvocation = FieldRelated + 74; + int ReferenceToForwardField = FieldRelated + Internal + 75; + /** @since 2.1 */ int NonStaticAccessToStaticField = Internal + FieldRelated + 76; + /** @since 2.1 */ int UnusedPrivateField = Internal + FieldRelated + 77; - + // blank final fields int FinalFieldAssignment = FieldRelated + 80; + int UninitializedBlankFinalField = FieldRelated + 81; + int DuplicateBlankFinalFieldInitialization = FieldRelated + 82; // methods int UndefinedMethod = MethodRelated + 100; + int NotVisibleMethod = MethodRelated + 101; + int AmbiguousMethod = MethodRelated + 102; + int UsingDeprecatedMethod = MethodRelated + 103; + int DirectInvocationOfAbstractMethod = MethodRelated + 104; + int VoidMethodReturnsValue = MethodRelated + 105; + int MethodReturnsVoid = MethodRelated + 106; + int MethodRequiresBody = Internal + MethodRelated + 107; + int ShouldReturnValue = Internal + MethodRelated + 108; + int MethodButWithConstructorName = MethodRelated + 110; + int MissingReturnType = TypeRelated + 111; + int BodyForNativeMethod = Internal + MethodRelated + 112; + int BodyForAbstractMethod = Internal + MethodRelated + 113; + int NoMessageSendOnBaseType = MethodRelated + 114; + int ParameterMismatch = MethodRelated + 115; + int NoMessageSendOnArrayType = MethodRelated + 116; + /** @since 2.1 */ - int NonStaticAccessToStaticMethod = Internal + MethodRelated + 117; + int NonStaticAccessToStaticMethod = Internal + MethodRelated + 117; + /** @since 2.1 */ int UnusedPrivateMethod = Internal + MethodRelated + 118; - + // constructors int UndefinedConstructor = ConstructorRelated + 130; + int NotVisibleConstructor = ConstructorRelated + 131; + int AmbiguousConstructor = ConstructorRelated + 132; + int UsingDeprecatedConstructor = ConstructorRelated + 133; + /** @since 2.1 */ int UnusedPrivateConstructor = Internal + MethodRelated + 134; + // explicit constructor calls int InstanceFieldDuringConstructorInvocation = ConstructorRelated + 135; + int InstanceMethodDuringConstructorInvocation = ConstructorRelated + 136; + int RecursiveConstructorInvocation = ConstructorRelated + 137; + int ThisSuperDuringConstructorInvocation = ConstructorRelated + 138; + // implicit constructor calls int UndefinedConstructorInDefaultConstructor = ConstructorRelated + 140; + int NotVisibleConstructorInDefaultConstructor = ConstructorRelated + 141; + int AmbiguousConstructorInDefaultConstructor = ConstructorRelated + 142; + int UndefinedConstructorInImplicitConstructorCall = ConstructorRelated + 143; + int NotVisibleConstructorInImplicitConstructorCall = ConstructorRelated + 144; + int AmbiguousConstructorInImplicitConstructorCall = ConstructorRelated + 145; + int UnhandledExceptionInDefaultConstructor = TypeRelated + 146; + int UnhandledExceptionInImplicitConstructorCall = TypeRelated + 147; - + // expressions int ArrayReferenceRequired = Internal + 150; + int NoImplicitStringConversionForCharArrayExpression = Internal + 151; + // constant expressions int StringConstantIsExceedingUtf8Limit = Internal + 152; + int NonConstantExpression = 153; + int NumericValueOutOfRange = Internal + 154; + // cast expressions int IllegalCast = TypeRelated + 156; + // allocations int InvalidClassInstantiation = TypeRelated + 157; + int CannotDefineDimensionExpressionsWithInit = Internal + 158; + int MustDefineEitherDimensionExpressionsOrInitializer = Internal + 159; + // operators int InvalidOperator = Internal + 160; + // statements int CodeCannotBeReached = Internal + 161; + int CannotReturnInInitializer = Internal + 162; + int InitializerMustCompleteNormally = Internal + 163; - + // assert int InvalidVoidExpression = Internal + 164; + // try int MaskedCatch = TypeRelated + 165; + int DuplicateDefaultCase = 166; + int UnreachableCatch = TypeRelated + MethodRelated + 167; + int UnhandledException = TypeRelated + 168; - // switch + + // switch int IncorrectSwitchType = TypeRelated + 169; + int DuplicateCase = FieldRelated + 170; + // labelled int DuplicateLabel = Internal + 171; + int InvalidBreak = Internal + 172; + int InvalidContinue = Internal + 173; + int UndefinedLabel = Internal + 174; - //synchronized + + // synchronized int InvalidTypeToSynchronized = Internal + 175; + int InvalidNullToSynchronized = Internal + 176; + // throw int CannotThrowNull = Internal + 177; + // assignment /** @since 2.1 */ int AssignmentHasNoEffect = Internal + 178; - + // inner emulation int NeedToEmulateFieldReadAccess = FieldRelated + 190; + int NeedToEmulateFieldWriteAccess = FieldRelated + 191; + int NeedToEmulateMethodAccess = MethodRelated + 192; + int NeedToEmulateConstructorAccess = MethodRelated + 193; - //inherited name hides enclosing name (sort of ambiguous) + // inherited name hides enclosing name (sort of ambiguous) int InheritedMethodHidesEnclosingName = MethodRelated + 195; + int InheritedFieldHidesEnclosingName = FieldRelated + 196; + int InheritedTypeHidesEnclosingName = TypeRelated + 197; // miscellaneous int ThisInStaticContext = Internal + 200; + int StaticMethodRequested = Internal + MethodRelated + 201; + int IllegalDimension = Internal + 202; + int InvalidTypeExpression = Internal + 203; + int ParsingError = Syntax + Internal + 204; + int ParsingErrorNoSuggestion = Syntax + Internal + 205; + int InvalidUnaryExpression = Syntax + Internal + 206; // syntax errors int InterfaceCannotHaveConstructors = Syntax + Internal + 207; + int ArrayConstantsOnlyInArrayInitializers = Syntax + Internal + 208; - int ParsingErrorOnKeyword = Syntax + Internal + 209; + + int ParsingErrorOnKeyword = Syntax + Internal + 209; + int ParsingErrorOnKeywordNoSuggestion = Syntax + Internal + 210; + int PHPParsingError = Syntax + Internal + 211; + int PHPParsingWarning = Syntax + Internal + 212; + int PHPVarDeprecatedWarning = Syntax + Internal + 213; + int PHPBadStyleKeywordWarning = Syntax + Internal + 214; + int PHPBadStyleUppercaseIdentifierWarning = Syntax + Internal + 215; + int PHPIncludeNotExistWarning = Syntax + Internal + 216; - + int UnmatchedBracket = Syntax + Internal + 220; + int NoFieldOnBaseType = FieldRelated + 221; + int InvalidExpressionAsStatement = Syntax + Internal + 222; + /** @since 2.1 */ int ExpressionShouldBeAVariable = Syntax + Internal + 223; + /** @since 2.1 */ int MissingSemiColon = Syntax + Internal + 224; + /** @since 2.1 */ int InvalidParenthesizedExpression = Syntax + Internal + 225; - + // scanner errors int EndOfSource = Syntax + Internal + 250; + int InvalidHexa = Syntax + Internal + 251; + int InvalidOctal = Syntax + Internal + 252; + int InvalidCharacterConstant = Syntax + Internal + 253; + int InvalidEscape = Syntax + Internal + 254; + int InvalidInput = Syntax + Internal + 255; + int InvalidUnicodeEscape = Syntax + Internal + 256; + int InvalidFloat = Syntax + Internal + 257; + int NullSourceString = Syntax + Internal + 258; + int UnterminatedString = Syntax + Internal + 259; + int UnterminatedComment = Syntax + Internal + 260; // type related problems int InterfaceCannotHaveInitializers = TypeRelated + 300; + int DuplicateModifierForType = TypeRelated + 301; + int IllegalModifierForClass = TypeRelated + 302; + int IllegalModifierForInterface = TypeRelated + 303; + int IllegalModifierForMemberClass = TypeRelated + 304; + int IllegalModifierForMemberInterface = TypeRelated + 305; + int IllegalModifierForLocalClass = TypeRelated + 306; int IllegalModifierCombinationFinalAbstractForClass = TypeRelated + 308; + int IllegalVisibilityModifierForInterfaceMemberType = TypeRelated + 309; + int IllegalVisibilityModifierCombinationForMemberType = TypeRelated + 310; + int IllegalStaticModifierForMemberType = TypeRelated + 311; + int SuperclassMustBeAClass = TypeRelated + 312; + int ClassExtendFinalClass = TypeRelated + 313; + int DuplicateSuperInterface = TypeRelated + 314; + int SuperInterfaceMustBeAnInterface = TypeRelated + 315; + int HierarchyCircularitySelfReference = TypeRelated + 316; + int HierarchyCircularity = TypeRelated + 317; + int HidingEnclosingType = TypeRelated + 318; + int DuplicateNestedType = TypeRelated + 319; + int CannotThrowType = TypeRelated + 320; + int PackageCollidesWithType = TypeRelated + 321; + int TypeCollidesWithPackage = TypeRelated + 322; + int DuplicateTypes = TypeRelated + 323; + int IsClassPathCorrect = TypeRelated + 324; + int PublicClassMustMatchFileName = TypeRelated + 325; + int MustSpecifyPackage = 326; + int HierarchyHasProblems = TypeRelated + 327; + int PackageIsNotExpectedPackage = 328; + /** @since 2.1 */ int ObjectCannotHaveSuperTypes = 329; - // int InvalidSuperclassBase = TypeRelated + 329; // reserved to 334 included - int SuperclassNotFound = TypeRelated + 329 + ProblemReasons.NotFound; // TypeRelated + 330 - int SuperclassNotVisible = TypeRelated + 329 + ProblemReasons.NotVisible; // TypeRelated + 331 - int SuperclassAmbiguous = TypeRelated + 329 + ProblemReasons.Ambiguous; // TypeRelated + 332 - int SuperclassInternalNameProvided = TypeRelated + 329 + ProblemReasons.InternalNameProvided; // TypeRelated + 333 - int SuperclassInheritedNameHidesEnclosingName = TypeRelated + 329 + ProblemReasons.InheritedNameHidesEnclosingName; // TypeRelated + 334 + // int InvalidSuperclassBase = TypeRelated + 329; // reserved to 334 + // included + int SuperclassNotFound = TypeRelated + 329 + ProblemReasons.NotFound; // TypeRelated + // + + // 330 + + int SuperclassNotVisible = TypeRelated + 329 + ProblemReasons.NotVisible; // TypeRelated + // + + // 331 + + int SuperclassAmbiguous = TypeRelated + 329 + ProblemReasons.Ambiguous; // TypeRelated + // + + // 332 + + int SuperclassInternalNameProvided = TypeRelated + 329 + + ProblemReasons.InternalNameProvided; // TypeRelated + 333 + + int SuperclassInheritedNameHidesEnclosingName = TypeRelated + 329 + + ProblemReasons.InheritedNameHidesEnclosingName; // TypeRelated + + // 334 // int InvalidInterfaceBase = TypeRelated + 334; // reserved to 339 included - int InterfaceNotFound = TypeRelated + 334 + ProblemReasons.NotFound; // TypeRelated + 335 - int InterfaceNotVisible = TypeRelated + 334 + ProblemReasons.NotVisible; // TypeRelated + 336 - int InterfaceAmbiguous = TypeRelated + 334 + ProblemReasons.Ambiguous; // TypeRelated + 337 - int InterfaceInternalNameProvided = TypeRelated + 334 + ProblemReasons.InternalNameProvided; // TypeRelated + 338 - int InterfaceInheritedNameHidesEnclosingName = TypeRelated + 334 + ProblemReasons.InheritedNameHidesEnclosingName; // TypeRelated + 339 + int InterfaceNotFound = TypeRelated + 334 + ProblemReasons.NotFound; // TypeRelated + // + + // 335 + + int InterfaceNotVisible = TypeRelated + 334 + ProblemReasons.NotVisible; // TypeRelated + // + + // 336 + + int InterfaceAmbiguous = TypeRelated + 334 + ProblemReasons.Ambiguous; // TypeRelated + // + + // 337 + + int InterfaceInternalNameProvided = TypeRelated + 334 + + ProblemReasons.InternalNameProvided; // TypeRelated + 338 + + int InterfaceInheritedNameHidesEnclosingName = TypeRelated + 334 + + ProblemReasons.InheritedNameHidesEnclosingName; // TypeRelated + + // 339 // field related problems int DuplicateField = FieldRelated + 340; + int DuplicateModifierForField = FieldRelated + 341; + int IllegalModifierForField = FieldRelated + 342; + int IllegalModifierForInterfaceField = FieldRelated + 343; + int IllegalVisibilityModifierCombinationForField = FieldRelated + 344; + int IllegalModifierCombinationFinalVolatileForField = FieldRelated + 345; + int UnexpectedStaticModifierForField = FieldRelated + 346; // int FieldTypeProblemBase = FieldRelated + 349; //reserved to 354 - int FieldTypeNotFound = FieldRelated + 349 + ProblemReasons.NotFound; // FieldRelated + 350 - int FieldTypeNotVisible = FieldRelated + 349 + ProblemReasons.NotVisible; // FieldRelated + 351 - int FieldTypeAmbiguous = FieldRelated + 349 + ProblemReasons.Ambiguous; // FieldRelated + 352 - int FieldTypeInternalNameProvided = FieldRelated + 349 + ProblemReasons.InternalNameProvided; // FieldRelated + 353 - int FieldTypeInheritedNameHidesEnclosingName = FieldRelated + 349 + ProblemReasons.InheritedNameHidesEnclosingName; // FieldRelated + 354 - + int FieldTypeNotFound = FieldRelated + 349 + ProblemReasons.NotFound; // FieldRelated + // + + // 350 + + int FieldTypeNotVisible = FieldRelated + 349 + ProblemReasons.NotVisible; // FieldRelated + // + + // 351 + + int FieldTypeAmbiguous = FieldRelated + 349 + ProblemReasons.Ambiguous; // FieldRelated + // + + // 352 + + int FieldTypeInternalNameProvided = FieldRelated + 349 + + ProblemReasons.InternalNameProvided; // FieldRelated + 353 + + int FieldTypeInheritedNameHidesEnclosingName = FieldRelated + 349 + + ProblemReasons.InheritedNameHidesEnclosingName; // FieldRelated + // + 354 + // method related problems int DuplicateMethod = MethodRelated + 355; + int IllegalModifierForArgument = MethodRelated + 356; + int DuplicateModifierForMethod = MethodRelated + 357; + int IllegalModifierForMethod = MethodRelated + 358; + int IllegalModifierForInterfaceMethod = MethodRelated + 359; + int IllegalVisibilityModifierCombinationForMethod = MethodRelated + 360; + int UnexpectedStaticModifierForMethod = MethodRelated + 361; + int IllegalAbstractModifierCombinationForMethod = MethodRelated + 362; + int AbstractMethodInAbstractClass = MethodRelated + 363; + int ArgumentTypeCannotBeVoid = MethodRelated + 364; + int ArgumentTypeCannotBeVoidArray = MethodRelated + 365; + int ReturnTypeCannotBeVoidArray = MethodRelated + 366; + int NativeMethodsCannotBeStrictfp = MethodRelated + 367; + int DuplicateModifierForArgument = MethodRelated + 368; - // int ArgumentProblemBase = MethodRelated + 369; // reserved to 374 included. - int ArgumentTypeNotFound = MethodRelated + 369 + ProblemReasons.NotFound; // MethodRelated + 370 - int ArgumentTypeNotVisible = MethodRelated + 369 + ProblemReasons.NotVisible; // MethodRelated + 371 - int ArgumentTypeAmbiguous = MethodRelated + 369 + ProblemReasons.Ambiguous; // MethodRelated + 372 - int ArgumentTypeInternalNameProvided = MethodRelated + 369 + ProblemReasons.InternalNameProvided; // MethodRelated + 373 - int ArgumentTypeInheritedNameHidesEnclosingName = MethodRelated + 369 + ProblemReasons.InheritedNameHidesEnclosingName; // MethodRelated + 374 - - // int ExceptionTypeProblemBase = MethodRelated + 374; // reserved to 379 included. - int ExceptionTypeNotFound = MethodRelated + 374 + ProblemReasons.NotFound; // MethodRelated + 375 - int ExceptionTypeNotVisible = MethodRelated + 374 + ProblemReasons.NotVisible; // MethodRelated + 376 - int ExceptionTypeAmbiguous = MethodRelated + 374 + ProblemReasons.Ambiguous; // MethodRelated + 377 - int ExceptionTypeInternalNameProvided = MethodRelated + 374 + ProblemReasons.InternalNameProvided; // MethodRelated + 378 - int ExceptionTypeInheritedNameHidesEnclosingName = MethodRelated + 374 + ProblemReasons.InheritedNameHidesEnclosingName; // MethodRelated + 379 - - // int ReturnTypeProblemBase = MethodRelated + 379; - int ReturnTypeNotFound = MethodRelated + 379 + ProblemReasons.NotFound; // MethodRelated + 380 - int ReturnTypeNotVisible = MethodRelated + 379 + ProblemReasons.NotVisible; // MethodRelated + 381 - int ReturnTypeAmbiguous = MethodRelated + 379 + ProblemReasons.Ambiguous; // MethodRelated + 382 - int ReturnTypeInternalNameProvided = MethodRelated + 379 + ProblemReasons.InternalNameProvided; // MethodRelated + 383 - int ReturnTypeInheritedNameHidesEnclosingName = MethodRelated + 379 + ProblemReasons.InheritedNameHidesEnclosingName; // MethodRelated + 384 + // int ArgumentProblemBase = MethodRelated + 369; // reserved to 374 + // included. + int ArgumentTypeNotFound = MethodRelated + 369 + ProblemReasons.NotFound; // MethodRelated + // + + // 370 + + int ArgumentTypeNotVisible = MethodRelated + 369 + + ProblemReasons.NotVisible; // MethodRelated + 371 + + int ArgumentTypeAmbiguous = MethodRelated + 369 + ProblemReasons.Ambiguous; // MethodRelated + // + + // 372 + + int ArgumentTypeInternalNameProvided = MethodRelated + 369 + + ProblemReasons.InternalNameProvided; // MethodRelated + 373 + + int ArgumentTypeInheritedNameHidesEnclosingName = MethodRelated + 369 + + ProblemReasons.InheritedNameHidesEnclosingName; // MethodRelated + // + 374 + + // int ExceptionTypeProblemBase = MethodRelated + 374; // reserved to 379 + // included. + int ExceptionTypeNotFound = MethodRelated + 374 + ProblemReasons.NotFound; // MethodRelated + // + + // 375 + + int ExceptionTypeNotVisible = MethodRelated + 374 + + ProblemReasons.NotVisible; // MethodRelated + 376 + + int ExceptionTypeAmbiguous = MethodRelated + 374 + ProblemReasons.Ambiguous; // MethodRelated + // + + // 377 + + int ExceptionTypeInternalNameProvided = MethodRelated + 374 + + ProblemReasons.InternalNameProvided; // MethodRelated + 378 + + int ExceptionTypeInheritedNameHidesEnclosingName = MethodRelated + 374 + + ProblemReasons.InheritedNameHidesEnclosingName; // MethodRelated + // + 379 + + // int ReturnTypeProblemBase = MethodRelated + 379; + int ReturnTypeNotFound = MethodRelated + 379 + ProblemReasons.NotFound; // MethodRelated + // + + // 380 + + int ReturnTypeNotVisible = MethodRelated + 379 + ProblemReasons.NotVisible; // MethodRelated + // + + // 381 + + int ReturnTypeAmbiguous = MethodRelated + 379 + ProblemReasons.Ambiguous; // MethodRelated + // + + // 382 + + int ReturnTypeInternalNameProvided = MethodRelated + 379 + + ProblemReasons.InternalNameProvided; // MethodRelated + 383 + + int ReturnTypeInheritedNameHidesEnclosingName = MethodRelated + 379 + + ProblemReasons.InheritedNameHidesEnclosingName; // MethodRelated + // + 384 // import related problems int ConflictingImport = ImportRelated + 385; + int DuplicateImport = ImportRelated + 386; + int CannotImportPackage = ImportRelated + 387; + int UnusedImport = ImportRelated + 388; - // int ImportProblemBase = ImportRelated + 389; - int ImportNotFound = ImportRelated + 389 + ProblemReasons.NotFound; // ImportRelated + 390 - int ImportNotVisible = ImportRelated + 389 + ProblemReasons.NotVisible; // ImportRelated + 391 - int ImportAmbiguous = ImportRelated + 389 + ProblemReasons.Ambiguous; // ImportRelated + 392 - int ImportInternalNameProvided = ImportRelated + 389 + ProblemReasons.InternalNameProvided; // ImportRelated + 393 - int ImportInheritedNameHidesEnclosingName = ImportRelated + 389 + ProblemReasons.InheritedNameHidesEnclosingName; // ImportRelated + 394 + // int ImportProblemBase = ImportRelated + 389; + int ImportNotFound = ImportRelated + 389 + ProblemReasons.NotFound; // ImportRelated + // + 390 + + int ImportNotVisible = ImportRelated + 389 + ProblemReasons.NotVisible; // ImportRelated + // + + // 391 + + int ImportAmbiguous = ImportRelated + 389 + ProblemReasons.Ambiguous; // ImportRelated + // + + // 392 + + int ImportInternalNameProvided = ImportRelated + 389 + + ProblemReasons.InternalNameProvided; // ImportRelated + 393 + + int ImportInheritedNameHidesEnclosingName = ImportRelated + 389 + + ProblemReasons.InheritedNameHidesEnclosingName; // ImportRelated + // + 394 - // local variable related problems int DuplicateModifierForVariable = MethodRelated + 395; + int IllegalModifierForVariable = MethodRelated + 396; // method verifier problems int AbstractMethodMustBeImplemented = MethodRelated + 400; + int FinalMethodCannotBeOverridden = MethodRelated + 401; + int IncompatibleExceptionInThrowsClause = MethodRelated + 402; + int IncompatibleExceptionInInheritedMethodThrowsClause = MethodRelated + 403; + int IncompatibleReturnType = MethodRelated + 404; + int InheritedMethodReducesVisibility = MethodRelated + 405; + int CannotOverrideAStaticMethodWithAnInstanceMethod = MethodRelated + 406; + int CannotHideAnInstanceMethodWithAStaticMethod = MethodRelated + 407; + int StaticInheritedMethodConflicts = MethodRelated + 408; + int MethodReducesVisibility = MethodRelated + 409; + int OverridingNonVisibleMethod = MethodRelated + 410; + int AbstractMethodCannotBeOverridden = MethodRelated + 411; + int OverridingDeprecatedMethod = MethodRelated + 412; + /** @since 2.1 */ int IncompatibleReturnTypeForNonInheritedInterfaceMethod = MethodRelated + 413; + /** @since 2.1 */ int IncompatibleExceptionInThrowsClauseForNonInheritedInterfaceMethod = MethodRelated + 414; - + // code snippet support int CodeSnippetMissingClass = Internal + 420; + int CodeSnippetMissingMethod = Internal + 421; + int NonExternalizedStringLiteral = Internal + 261; + int CannotUseSuperInCodeSnippet = Internal + 422; - - //constant pool + + // constant pool int TooManyConstantsInConstantPool = Internal + 430; + /** @since 2.1 */ int TooManyBytesForStringConstant = Internal + 431; // static constraints /** @since 2.1 */ int TooManyFields = Internal + 432; + /** @since 2.1 */ - int TooManyMethods = Internal + 433; - + int TooManyMethods = Internal + 433; + // 1.4 features // assertion warning int UseAssertAsAnIdentifier = Internal + 440; - + // detected task /** @since 2.1 */ int Task = Internal + 450; - -// block + + // block /** @since 3.0 */ int UndocumentedEmptyBlock = Internal + 460; - + /* * Javadoc comments */ /** @since 3.0 */ int JavadocUnexpectedTag = Javadoc + Internal + 470; + /** @since 3.0 */ int JavadocMissingParamTag = Javadoc + Internal + 471; + /** @since 3.0 */ int JavadocMissingParamName = Javadoc + Internal + 472; + /** @since 3.0 */ int JavadocDuplicateParamName = Javadoc + Internal + 473; + /** @since 3.0 */ int JavadocInvalidParamName = Javadoc + Internal + 474; + /** @since 3.0 */ int JavadocMissingReturnTag = Javadoc + Internal + 475; + /** @since 3.0 */ int JavadocDuplicateReturnTag = Javadoc + Internal + 476; + /** @since 3.0 */ int JavadocMissingThrowsTag = Javadoc + Internal + 477; + /** @since 3.0 */ int JavadocMissingThrowsClassName = Javadoc + Internal + 478; + /** @since 3.0 */ int JavadocInvalidThrowsClass = Javadoc + Internal + 479; + /** @since 3.0 */ int JavadocDuplicateThrowsClassName = Javadoc + Internal + 480; + /** @since 3.0 */ int JavadocInvalidThrowsClassName = Javadoc + Internal + 481; + /** @since 3.0 */ int JavadocMissingSeeReference = Javadoc + Internal + 482; + /** @since 3.0 */ int JavadocInvalidSeeReference = Javadoc + Internal + 483; + /** @since 3.0 */ int JavadocInvalidSeeHref = Javadoc + Internal + 484; + /** @since 3.0 */ int JavadocInvalidSeeArgs = Javadoc + Internal + 485; + /** @since 3.0 */ int JavadocMissing = Javadoc + Internal + 486; + /** @since 3.0 */ int JavadocInvalidTag = Javadoc + Internal + 487; + /* * ID for field errors in Javadoc */ /** @since 3.0 */ int JavadocUndefinedField = Javadoc + Internal + 488; + /** @since 3.0 */ int JavadocNotVisibleField = Javadoc + Internal + 489; + /** @since 3.0 */ int JavadocAmbiguousField = Javadoc + Internal + 490; + /** @since 3.0 */ int JavadocUsingDeprecatedField = Javadoc + Internal + 491; + /* * IDs for constructor errors in Javadoc */ /** @since 3.0 */ int JavadocUndefinedConstructor = Javadoc + Internal + 492; + /** @since 3.0 */ int JavadocNotVisibleConstructor = Javadoc + Internal + 493; + /** @since 3.0 */ int JavadocAmbiguousConstructor = Javadoc + Internal + 494; + /** @since 3.0 */ int JavadocUsingDeprecatedConstructor = Javadoc + Internal + 495; + /* * IDs for method errors in Javadoc */ /** @since 3.0 */ int JavadocUndefinedMethod = Javadoc + Internal + 496; + /** @since 3.0 */ int JavadocNotVisibleMethod = Javadoc + Internal + 497; + /** @since 3.0 */ int JavadocAmbiguousMethod = Javadoc + Internal + 498; + /** @since 3.0 */ int JavadocUsingDeprecatedMethod = Javadoc + Internal + 499; + /** @since 3.0 */ int JavadocNoMessageSendOnBaseType = Javadoc + Internal + 500; + /** @since 3.0 */ int JavadocParameterMismatch = Javadoc + Internal + 501; + /** @since 3.0 */ int JavadocNoMessageSendOnArrayType = Javadoc + Internal + 502; + /* * IDs for type errors in Javadoc */ /** @since 3.0 */ int JavadocUndefinedType = Javadoc + Internal + 503; + /** @since 3.0 */ int JavadocNotVisibleType = Javadoc + Internal + 504; + /** @since 3.0 */ int JavadocAmbiguousType = Javadoc + Internal + 505; + /** @since 3.0 */ int JavadocUsingDeprecatedType = Javadoc + Internal + 506; + /** @since 3.0 */ int JavadocInternalTypeNameProvided = Javadoc + Internal + 507; + /** @since 3.0 */ int JavadocInheritedMethodHidesEnclosingName = Javadoc + Internal + 508; + /** @since 3.0 */ int JavadocInheritedFieldHidesEnclosingName = Javadoc + Internal + 509; + /** @since 3.0 */ int JavadocInheritedNameHidesEnclosingTypeName = Javadoc + Internal + 510; + /** @since 3.0 */ int JavadocAmbiguousMethodReference = Javadoc + Internal + 511; + /** @since 3.0 */ int JavadocUnterminatedInlineTag = Javadoc + Internal + 512; + /** @since 3.0 */ int JavadocMalformedSeeReference = Javadoc + Internal + 513; + /** @since 3.0 */ int JavadocMessagePrefix = Internal + 515; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/IScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/IScanner.java index 3207a73..f3c6ff6 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/IScanner.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/IScanner.java @@ -1,134 +1,154 @@ /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. -All rights reserved. � This program and the accompanying materials -are made available under the terms of the Common Public License v0.5 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v05.html -� -Contributors: - IBM Corporation - initial API and implementation -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. + All rights reserved. � This program and the accompanying materials + are made available under the terms of the Common Public License v0.5 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v05.html + � + Contributors: + IBM Corporation - initial API and implementation + **********************************************************************/ package net.sourceforge.phpdt.core.compiler; - - /** - * Definition of a Java scanner, as returned by the ToolFactory. - * The scanner is responsible for tokenizing a given source, providing information about - * the nature of the token read, its positions and source equivalent. - * - * When the scanner has finished tokenizing, it answers an EOF token ( - * ITerminalSymbols#TokenNameEOF. - * - * When encountering lexical errors, an InvalidInputException is thrown. - * - * @see net.sourceforge.phpdt.core.ToolFactory - * @see ITerminalSymbols - * @since 2.0 - */ +/** + * Definition of a Java scanner, as returned by the ToolFactory. + * The scanner is responsible for tokenizing a given source, providing + * information about the nature of the token read, its positions and source + * equivalent. + * + * When the scanner has finished tokenizing, it answers an EOF token ( + * ITerminalSymbols#TokenNameEOF. + * + * When encountering lexical errors, an InvalidInputException is + * thrown. + * + * @see net.sourceforge.phpdt.core.ToolFactory + * @see ITerminalSymbols + * @since 2.0 + */ public interface IScanner { /** - * Answers the current identifier source, after unicode escape sequences have - * been translated into unicode characters. - * e.g. if original source was \\u0061bc then it will answer abc. + * Answers the current identifier source, after unicode escape sequences + * have been translated into unicode characters. e.g. if original source was + * \\u0061bc then it will answer abc. * - * @return the current identifier source, after unicode escape sequences have - * been translated into unicode characters + * @return the current identifier source, after unicode escape sequences + * have been translated into unicode characters */ char[] getCurrentTokenSource(); /** - * Answers the starting position of the current token inside the original source. - * This position is zero-based and inclusive. It corresponds to the position of the first character - * which is part of this token. If this character was a unicode escape sequence, it points at the first - * character of this sequence. + * Answers the starting position of the current token inside the original + * source. This position is zero-based and inclusive. It corresponds to the + * position of the first character which is part of this token. If this + * character was a unicode escape sequence, it points at the first character + * of this sequence. * - * @return the starting position of the current token inside the original source + * @return the starting position of the current token inside the original + * source */ int getCurrentTokenStartPosition(); /** - * Answers the ending position of the current token inside the original source. - * This position is zero-based and inclusive. It corresponds to the position of the last character - * which is part of this token. If this character was a unicode escape sequence, it points at the last - * character of this sequence. + * Answers the ending position of the current token inside the original + * source. This position is zero-based and inclusive. It corresponds to the + * position of the last character which is part of this token. If this + * character was a unicode escape sequence, it points at the last character + * of this sequence. * - * @return the ending position of the current token inside the original source + * @return the ending position of the current token inside the original + * source */ int getCurrentTokenEndPosition(); /** - * Answers the starting position of a given line number. This line has to have been encountered - * already in the tokenization process (i.e. it cannot be used to compute positions of lines beyond - * current token). Once the entire source has been processed, it can be used without any limit. - * Line starting positions are zero-based, and start immediately after the previous line separator (if any). + * Answers the starting position of a given line number. This line has to + * have been encountered already in the tokenization process (i.e. it cannot + * be used to compute positions of lines beyond current token). Once the + * entire source has been processed, it can be used without any limit. Line + * starting positions are zero-based, and start immediately after the + * previous line separator (if any). * - * @param lineNumber the given line number + * @param lineNumber + * the given line number * @return the starting position of a given line number */ int getLineStart(int lineNumber); /** - * Answers the ending position of a given line number. This line has to have been encountered - * already in the tokenization process (i.e. it cannot be used to compute positions of lines beyond - * current token). Once the entire source has been processed, it can be used without any limit. - * Line ending positions are zero-based, and correspond to the last character of the line separator - * (in case multi-character line separators). + * Answers the ending position of a given line number. This line has to have + * been encountered already in the tokenization process (i.e. it cannot be + * used to compute positions of lines beyond current token). Once the entire + * source has been processed, it can be used without any limit. Line ending + * positions are zero-based, and correspond to the last character of the + * line separator (in case multi-character line separators). * - * @param lineNumber the given line number + * @param lineNumber + * the given line number * @return the ending position of a given line number - **/ + */ int getLineEnd(int lineNumber); /** - * Answers an array of the ending positions of the lines encountered so far. Line ending positions - * are zero-based, and correspond to the last character of the line separator (in case multi-character - * line separators). + * Answers an array of the ending positions of the lines encountered so far. + * Line ending positions are zero-based, and correspond to the last + * character of the line separator (in case multi-character line + * separators). * * @return an array of the ending positions of the lines encountered so far */ int[] getLineEnds(); /** - * Answers a 1-based line number using the lines which have been encountered so far. If the position - * is located beyond the current scanned line, then the last line number will be answered. + * Answers a 1-based line number using the lines which have been encountered + * so far. If the position is located beyond the current scanned line, then + * the last line number will be answered. * - * @param charPosition the given character position - * @return a 1-based line number using the lines which have been encountered so far + * @param charPosition + * the given character position + * @return a 1-based line number using the lines which have been encountered + * so far */ int getLineNumber(int charPosition); /** - * Read the next token in the source, and answers its ID as specified by ITerminalSymbols. - * Note that the actual token ID values are subject to change if new keywords were added to the language - * (i.e. 'assert' keyword in 1.4). + * Read the next token in the source, and answers its ID as specified by + * ITerminalSymbols. Note that the actual token ID values + * are subject to change if new keywords were added to the language (i.e. + * 'assert' keyword in 1.4). * - * @throws InvalidInputException - in case a lexical error was detected while reading the current token + * @throws InvalidInputException - + * in case a lexical error was detected while reading the + * current token */ int getNextToken() throws InvalidInputException; /** - * Answers the original source being processed (not a copy of it). + * Answers the original source being processed (not a copy of it). * * @return the original source being processed */ char[] getSource(); /** - * Reposition the scanner on some portion of the original source. Once reaching the given endPosition - * it will answer EOF tokens (ITerminalSymbols.TokenNameEOF). + * Reposition the scanner on some portion of the original source. Once + * reaching the given endPosition it will answer EOF tokens (ITerminalSymbols.TokenNameEOF). * - * @param startPosition the given start position - * @param endPosition the given end position + * @param startPosition + * the given start position + * @param endPosition + * the given end position */ void resetTo(int startPosition, int endPosition); /** - * Set the scanner source to process. By default, the scanner will consider starting at the beginning of the - * source until it reaches its end. + * Set the scanner source to process. By default, the scanner will consider + * starting at the beginning of the source until it reaches its end. * - * @param source the given source + * @param source + * the given source */ void setSource(char[] source); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/ITerminalSymbols.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/ITerminalSymbols.java index 6440ffd..ae1db34 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/ITerminalSymbols.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/ITerminalSymbols.java @@ -9,201 +9,350 @@ IBM Corporation - initial API and implementation **********************************************************************/ package net.sourceforge.phpdt.core.compiler; + /** * Maps each terminal symbol in the php-grammar into a unique integer. This * integer is used to represent the terminal when computing a parsing action. - * + * * @see IScanner * @since 2.0 */ public interface ITerminalSymbols { - public final static String[] PHP_TYPES = {"array", "string", "object", - "bool", "boolean", "real", "double", "float", "int", "integer",}; - //"array", - public final static int TokenNameWHITESPACE = 900, - TokenNameCOMMENT_LINE = 901, TokenNameCOMMENT_BLOCK = 902, - TokenNameCOMMENT_PHPDOC = 903; - // TokenNameHTML = 904; - final static int TokenNameEOF = 0; - final static int TokenNameERROR = 1; - final static int TokenNameINLINE_HTML = 2; - final static int TokenNameREMAINDER = 30; - final static int TokenNameNOT = 31; - final static int TokenNameDOT = 32; - final static int TokenNameXOR = 33; - final static int TokenNameDIVIDE = 34; - final static int TokenNameMULTIPLY = 35; - final static int TokenNameMINUS = 36; - final static int TokenNamePLUS = 37; - final static int TokenNameEQUAL_EQUAL = 38; - final static int TokenNameNOT_EQUAL = 39; - final static int TokenNameGREATER = 40; - final static int TokenNameGREATER_EQUAL = 41; - final static int TokenNameLESS = 42; - final static int TokenNameLESS_EQUAL = 43; - final static int TokenNameAND_AND = 44; - final static int TokenNameOR_OR = 45; - final static int TokenNameCOLON = 47; - final static int TokenNameDOT_EQUAL = 48; - final static int TokenNameEQUAL = 49; - final static int TokenNameMINUS_GREATER = 50; // -> - final static int TokenNameEQUAL_GREATER = 51; // => (for each operator) - final static int TokenNameAND = 52; - final static int TokenNameTWIDDLE = 54; - final static int TokenNameTWIDDLE_EQUAL = 55; - final static int TokenNameREMAINDER_EQUAL = 56; - final static int TokenNameXOR_EQUAL = 57; - final static int TokenNameRIGHT_SHIFT_EQUAL = 58; - final static int TokenNameLEFT_SHIFT_EQUAL = 59; - final static int TokenNameAND_EQUAL = 60; - final static int TokenNameOR_EQUAL = 61; - final static int TokenNameQUESTION = 62; - final static int TokenNamePAAMAYIM_NEKUDOTAYIM = 63; - final static int TokenNameAT = 64; - final static int TokenNameand = 65; - final static int TokenNameor = 66; - final static int TokenNamexor = 67; - final static int TokenNameDOLLAR = 126; - final static int TokenNameDOLLAR_LBRACE = 127; - final static int TokenNameLPAREN = 128; - final static int TokenNameRPAREN = 129; - final static int TokenNameLBRACE = 130; - final static int TokenNameRBRACE = 131; - final static int TokenNameLBRACKET = 132; - final static int TokenNameRBRACKET = 133; - final static int TokenNameCOMMA = 134; - final static int TokenNameStringDoubleQuote = 136; - final static int TokenNameIdentifier = 138; - final static int TokenNameSEMICOLON = 140; - final static int TokenNameMINUS_MINUS = 144; - final static int TokenNamePLUS_PLUS = 145; - final static int TokenNamePLUS_EQUAL = 146; - final static int TokenNameDIVIDE_EQUAL = 147; - final static int TokenNameMINUS_EQUAL = 148; - final static int TokenNameMULTIPLY_EQUAL = 149; - final static int TokenNameVariable = 150; - final static int TokenNameIntegerLiteral = 151; - final static int TokenNameDoubleLiteral = 152; - final static int TokenNameStringInterpolated = 153; - final static int TokenNameStringSingleQuote = 154; - final static int TokenNameLEFT_SHIFT = 155; - final static int TokenNameRIGHT_SHIFT = 156; - final static int TokenNameEQUAL_EQUAL_EQUAL = 157; - final static int TokenNameNOT_EQUAL_EQUAL = 158; - final static int TokenNameOR = 160; - final static int TokenNameHEREDOC = 161; - final static int TokenNameintCAST = 174; - final static int TokenNameboolCAST = 175; - final static int TokenNamedoubleCAST = 176; - final static int TokenNamestringCAST = 177; - final static int TokenNamearrayCAST = 178; - final static int TokenNameobjectCAST = 179; - final static int TokenNameunsetCAST = 180; - - // � - final static int TokenNameEncapsedString0 = 190; - // ' -// final static int TokenNameEncapsedString1 = 191; - // " -// final static int TokenNameEncapsedString2 = 192; - - final static int TokenNameSTRING = 193; - - final static int TokenNameLBRACE_DOLLAR = 194; - - // start SQL token - the SQL tokens are only used in the - // PHPCompletionprocessor: - public final static int TokenNameSQLselect = 901; - public final static int TokenNameSQLupdate = 902; - public final static int TokenNameSQLinsert = 903; - public final static int TokenNameSQLwhere = 904; - public final static int TokenNameSQLfrom = 905; - public final static int TokenNameSQLinto = 906; - public final static int TokenNameSQLset = 907; - public final static int TokenNameSQLvalues = 908; - // stop SQL token - - /** - * Special 0-length token for php short tag syntax; - * Detected directly after <?= - */ - public final static int TokenNameECHO_INVISIBLE = 990; - - public final static int TokenNameKEYWORD = 1000; - public final static int TokenNameif = 1001; - public final static int TokenNameelseif = 1002; - public final static int TokenNameelse = 1003; - public final static int TokenNameendif = 1004; - public final static int TokenNamefor = 1005; - public final static int TokenNameendfor = 1006; - public final static int TokenNamewhile = 1007; - public final static int TokenNameendwhile = 1008; - public final static int TokenNameswitch = 1009; - public final static int TokenNamecase = 10010; - public final static int TokenNameendswitch = 1011; - public final static int TokenNamebreak = 1012; - public final static int TokenNamecontinue = 1013; - public final static int TokenNamereturn = 1014; - // public final static int TokenNamedefine = 1015; - public final static int TokenNameinclude = 1016; - public final static int TokenNameinclude_once = 1017; - public final static int TokenNamerequire = 1018; - public final static int TokenNamerequire_once = 1019; - public final static int TokenNamefunction = 1020; - public final static int TokenNameclass = 1021; - public final static int TokenNamenew = 1022; - public final static int TokenNamedo = 1023; - public final static int TokenNameold_function = 1024; - public final static int TokenNamedefault = 1025; - public final static int TokenNameglobal = 1026; - public final static int TokenNamestatic = 1027; - public final static int TokenNameforeach = 1028; - public final static int TokenNameendforeach = 1029; - public final static int TokenNameextends = 1030; - public final static int TokenNameempty = 1031; - public final static int TokenNamearray = 1032; - public final static int TokenNameecho = 1033; - public final static int TokenNamevar = 1034; - public final static int TokenNameas = 1035; - public final static int TokenNameprint = 1036; - public final static int TokenNameunset = 1037; - public final static int TokenNameexit = 1038; - // public final static int TokenNamedie = 1039; - // public final static int TokenNameand = 1040; - // public final static int TokenNameor = 1041; - // public final static int TokenNamexor = 1042; - public final static int TokenNamelist = 1043; - // public final static int TokenNamenull = 1044; - // public final static int TokenNamefalse = 1045; - // public final static int TokenNametrue = 1046; - // public final static int TokenNamethis = 1047; - // - public final static int TokenNameabstract = 1050; - public final static int TokenNamecatch = 1051; - public final static int TokenNamefinally = 1052; - public final static int TokenNametry = 1053; - public final static int TokenNameprivate = 1054; - public final static int TokenNameprotected = 1055; - public final static int TokenNamepublic = 1056; - public final static int TokenNameinterface = 1057; - public final static int TokenNameimplements = 1058; - public final static int TokenNameinstanceof = 1059; - public final static int TokenNamesuper = 1060; - public final static int TokenNamethrow = 1061; - public final static int TokenNameconst = 1062; - public final static int TokenNameclone = 1063; - public final static int TokenNamedeclare = 1064; - public final static int TokenNameenddeclare = 1065; - public final static int TokenNameeval = 1066; - public final static int TokenNameuse = 1067; - public final static int TokenNameisset = 1068; - public final static int TokenNamefinal = 1069; - public final static int TokenNameLINE = 1070; - public final static int TokenNameFILE = 1071; - public final static int TokenNameCLASS_C = 1072; - public final static int TokenNameMETHOD_C = 1073; - public final static int TokenNameFUNC_C = 1074; - - // special tokens not normally used in the parser - public final static int TokenNamethis_PHP_COMPLETION = 2000; + public final static String[] PHP_TYPES = { "array", "string", "object", + "bool", "boolean", "real", "double", "float", "int", "integer", }; + + // "array", + public final static int TokenNameWHITESPACE = 900, + TokenNameCOMMENT_LINE = 901, TokenNameCOMMENT_BLOCK = 902, + TokenNameCOMMENT_PHPDOC = 903; + + // TokenNameHTML = 904; + final static int TokenNameEOF = 0; + + final static int TokenNameERROR = 1; + + final static int TokenNameINLINE_HTML = 2; + + final static int TokenNameREMAINDER = 30; + + final static int TokenNameNOT = 31; + + final static int TokenNameDOT = 32; + + final static int TokenNameXOR = 33; + + final static int TokenNameDIVIDE = 34; + + final static int TokenNameMULTIPLY = 35; + + final static int TokenNameMINUS = 36; + + final static int TokenNamePLUS = 37; + + final static int TokenNameEQUAL_EQUAL = 38; + + final static int TokenNameNOT_EQUAL = 39; + + final static int TokenNameGREATER = 40; + + final static int TokenNameGREATER_EQUAL = 41; + + final static int TokenNameLESS = 42; + + final static int TokenNameLESS_EQUAL = 43; + + final static int TokenNameAND_AND = 44; + + final static int TokenNameOR_OR = 45; + + final static int TokenNameCOLON = 47; + + final static int TokenNameDOT_EQUAL = 48; + + final static int TokenNameEQUAL = 49; + + final static int TokenNameMINUS_GREATER = 50; // -> + + final static int TokenNameEQUAL_GREATER = 51; // => (for each operator) + + final static int TokenNameAND = 52; + + final static int TokenNameTWIDDLE = 54; + + final static int TokenNameTWIDDLE_EQUAL = 55; + + final static int TokenNameREMAINDER_EQUAL = 56; + + final static int TokenNameXOR_EQUAL = 57; + + final static int TokenNameRIGHT_SHIFT_EQUAL = 58; + + final static int TokenNameLEFT_SHIFT_EQUAL = 59; + + final static int TokenNameAND_EQUAL = 60; + + final static int TokenNameOR_EQUAL = 61; + + final static int TokenNameQUESTION = 62; + + final static int TokenNamePAAMAYIM_NEKUDOTAYIM = 63; + + final static int TokenNameAT = 64; + + final static int TokenNameand = 65; + + final static int TokenNameor = 66; + + final static int TokenNamexor = 67; + + final static int TokenNameDOLLAR = 126; + + final static int TokenNameDOLLAR_LBRACE = 127; + + final static int TokenNameLPAREN = 128; + + final static int TokenNameRPAREN = 129; + + final static int TokenNameLBRACE = 130; + + final static int TokenNameRBRACE = 131; + + final static int TokenNameLBRACKET = 132; + + final static int TokenNameRBRACKET = 133; + + final static int TokenNameCOMMA = 134; + + final static int TokenNameStringDoubleQuote = 136; + + final static int TokenNameIdentifier = 138; + + final static int TokenNameSEMICOLON = 140; + + final static int TokenNameMINUS_MINUS = 144; + + final static int TokenNamePLUS_PLUS = 145; + + final static int TokenNamePLUS_EQUAL = 146; + + final static int TokenNameDIVIDE_EQUAL = 147; + + final static int TokenNameMINUS_EQUAL = 148; + + final static int TokenNameMULTIPLY_EQUAL = 149; + + final static int TokenNameVariable = 150; + + final static int TokenNameIntegerLiteral = 151; + + final static int TokenNameDoubleLiteral = 152; + + final static int TokenNameStringInterpolated = 153; + + final static int TokenNameStringSingleQuote = 154; + + final static int TokenNameLEFT_SHIFT = 155; + + final static int TokenNameRIGHT_SHIFT = 156; + + final static int TokenNameEQUAL_EQUAL_EQUAL = 157; + + final static int TokenNameNOT_EQUAL_EQUAL = 158; + + final static int TokenNameOR = 160; + + final static int TokenNameHEREDOC = 161; + + final static int TokenNameintCAST = 174; + + final static int TokenNameboolCAST = 175; + + final static int TokenNamedoubleCAST = 176; + + final static int TokenNamestringCAST = 177; + + final static int TokenNamearrayCAST = 178; + + final static int TokenNameobjectCAST = 179; + + final static int TokenNameunsetCAST = 180; + + // � + final static int TokenNameEncapsedString0 = 190; + + // ' + // final static int TokenNameEncapsedString1 = 191; + // " + // final static int TokenNameEncapsedString2 = 192; + + final static int TokenNameSTRING = 193; + + final static int TokenNameLBRACE_DOLLAR = 194; + + // start SQL token - the SQL tokens are only used in the + // PHPCompletionprocessor: + public final static int TokenNameSQLselect = 901; + + public final static int TokenNameSQLupdate = 902; + + public final static int TokenNameSQLinsert = 903; + + public final static int TokenNameSQLwhere = 904; + + public final static int TokenNameSQLfrom = 905; + + public final static int TokenNameSQLinto = 906; + + public final static int TokenNameSQLset = 907; + + public final static int TokenNameSQLvalues = 908; + + // stop SQL token + + /** + * Special 0-length token for php short tag syntax; Detected directly after + * <?= + */ + public final static int TokenNameECHO_INVISIBLE = 990; + + public final static int TokenNameKEYWORD = 1000; + + public final static int TokenNameif = 1001; + + public final static int TokenNameelseif = 1002; + + public final static int TokenNameelse = 1003; + + public final static int TokenNameendif = 1004; + + public final static int TokenNamefor = 1005; + + public final static int TokenNameendfor = 1006; + + public final static int TokenNamewhile = 1007; + + public final static int TokenNameendwhile = 1008; + + public final static int TokenNameswitch = 1009; + + public final static int TokenNamecase = 10010; + + public final static int TokenNameendswitch = 1011; + + public final static int TokenNamebreak = 1012; + + public final static int TokenNamecontinue = 1013; + + public final static int TokenNamereturn = 1014; + + // public final static int TokenNamedefine = 1015; + public final static int TokenNameinclude = 1016; + + public final static int TokenNameinclude_once = 1017; + + public final static int TokenNamerequire = 1018; + + public final static int TokenNamerequire_once = 1019; + + public final static int TokenNamefunction = 1020; + + public final static int TokenNameclass = 1021; + + public final static int TokenNamenew = 1022; + + public final static int TokenNamedo = 1023; + + public final static int TokenNameold_function = 1024; + + public final static int TokenNamedefault = 1025; + + public final static int TokenNameglobal = 1026; + + public final static int TokenNamestatic = 1027; + + public final static int TokenNameforeach = 1028; + + public final static int TokenNameendforeach = 1029; + + public final static int TokenNameextends = 1030; + + public final static int TokenNameempty = 1031; + + public final static int TokenNamearray = 1032; + + public final static int TokenNameecho = 1033; + + public final static int TokenNamevar = 1034; + + public final static int TokenNameas = 1035; + + public final static int TokenNameprint = 1036; + + public final static int TokenNameunset = 1037; + + public final static int TokenNameexit = 1038; + + // public final static int TokenNamedie = 1039; + // public final static int TokenNameand = 1040; + // public final static int TokenNameor = 1041; + // public final static int TokenNamexor = 1042; + public final static int TokenNamelist = 1043; + + // public final static int TokenNamenull = 1044; + // public final static int TokenNamefalse = 1045; + // public final static int TokenNametrue = 1046; + // public final static int TokenNamethis = 1047; + // + public final static int TokenNameabstract = 1050; + + public final static int TokenNamecatch = 1051; + + public final static int TokenNamefinally = 1052; + + public final static int TokenNametry = 1053; + + public final static int TokenNameprivate = 1054; + + public final static int TokenNameprotected = 1055; + + public final static int TokenNamepublic = 1056; + + public final static int TokenNameinterface = 1057; + + public final static int TokenNameimplements = 1058; + + public final static int TokenNameinstanceof = 1059; + + public final static int TokenNamesuper = 1060; + + public final static int TokenNamethrow = 1061; + + public final static int TokenNameconst = 1062; + + public final static int TokenNameclone = 1063; + + public final static int TokenNamedeclare = 1064; + + public final static int TokenNameenddeclare = 1065; + + public final static int TokenNameeval = 1066; + + public final static int TokenNameuse = 1067; + + public final static int TokenNameisset = 1068; + + public final static int TokenNamefinal = 1069; + + public final static int TokenNameLINE = 1070; + + public final static int TokenNameFILE = 1071; + + public final static int TokenNameCLASS_C = 1072; + + public final static int TokenNameMETHOD_C = 1073; + + public final static int TokenNameFUNC_C = 1074; + + // special tokens not normally used in the parser + public final static int TokenNamethis_PHP_COMPLETION = 2000; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/InvalidInputException.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/InvalidInputException.java index a4367a7..5a3767b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/InvalidInputException.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/InvalidInputException.java @@ -1,13 +1,13 @@ /********************************************************************** -Copyright (c) 2002 IBM Corp. and others. -All rights reserved.   This program and the accompanying materials -are made available under the terms of the Common Public License v0.5 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v05.html -  -Contributors: - IBM Corporation - initial API and implementation -**********************************************************************/ + Copyright (c) 2002 IBM Corp. and others. + All rights reserved. � This program and the accompanying materials + are made available under the terms of the Common Public License v0.5 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v05.html + � + Contributors: + IBM Corporation - initial API and implementation + **********************************************************************/ package net.sourceforge.phpdt.core.compiler; @@ -22,9 +22,12 @@ public class InvalidInputException extends Exception { public InvalidInputException() { super(); } + /** * InvalidInputException constructor comment. - * @param s java.lang.String + * + * @param s + * java.lang.String */ public InvalidInputException(String s) { super(s); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/dom/CompilationUnit.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/dom/CompilationUnit.java index 5570ff9..1b3e452 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/dom/CompilationUnit.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/dom/CompilationUnit.java @@ -1,4 +1,5 @@ package net.sourceforge.phpdt.core.dom; + /******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials @@ -10,7 +11,6 @@ package net.sourceforge.phpdt.core.dom; * IBM Corporation - initial API and implementation *******************************************************************************/ - /** * Java compilation unit AST node type. This is the type of the root of an AST. *

          @@ -18,826 +18,851 @@ package net.sourceforge.phpdt.core.dom; * including leading and trailing whitespace and comments. *

          * For JLS2: + * *
          - * CompilationUnit:
          - *    [ PackageDeclaration ]
          - *        { ImportDeclaration }
          - *        { TypeDeclaration | ; }
          + *  CompilationUnit:
          + *     [ PackageDeclaration ]
          + *         { ImportDeclaration }
          + *         { TypeDeclaration | <b>;</b> }
            * 
          - * For JLS3, the kinds of type declarations - * grew to include enum and annotation type declarations: + * + * For JLS3, the kinds of type declarations grew to include enum and annotation + * type declarations: + * *
          - * CompilationUnit:
          - *    [ PackageDeclaration ]
          - *        { ImportDeclaration }
          - *        { TypeDeclaration | EnumDeclaration | AnnotationTypeDeclaration | ; }
          + *  CompilationUnit:
          + *     [ PackageDeclaration ]
          + *         { ImportDeclaration }
          + *         { TypeDeclaration | EnumDeclaration | AnnotationTypeDeclaration | <b>;</b> }
            * 
          - * + * * @since 2.0 */ public class CompilationUnit { -// /** -// * The "package" structural property of this node type. -// * -// * @since 3.0 -// */ -// public static final ChildPropertyDescriptor PACKAGE_PROPERTY = -// new ChildPropertyDescriptor(CompilationUnit.class, "package", PackageDeclaration.class, OPTIONAL, NO_CYCLE_RISK); //$NON-NLS-1$ -// -// /** -// * The "imports" structural property of this node type. -// * -// * @since 3.0 -// */ -// public static final ChildListPropertyDescriptor IMPORTS_PROPERTY = -// new ChildListPropertyDescriptor(CompilationUnit.class, "imports", ImportDeclaration.class, NO_CYCLE_RISK); //$NON-NLS-1$ -// -// /** -// * The "types" structural property of this node type. -// * -// * @since 3.0 -// */ -// public static final ChildListPropertyDescriptor TYPES_PROPERTY = -// new ChildListPropertyDescriptor(CompilationUnit.class, "types", AbstractTypeDeclaration.class, CYCLE_RISK); //$NON-NLS-1$ -// -// /** -// * A list of property descriptors (element type: -// * {@link StructuralPropertyDescriptor}), -// * or null if uninitialized. -// * @since 3.0 -// */ -// private static final List PROPERTY_DESCRIPTORS; -// -// static { -// createPropertyList(CompilationUnit.class); -// addProperty(PACKAGE_PROPERTY); -// addProperty(IMPORTS_PROPERTY); -// addProperty(TYPES_PROPERTY); -// PROPERTY_DESCRIPTORS = reapPropertyList(); -// } -// -// /** -// * Returns a list of structural property descriptors for this node type. -// * Clients must not modify the result. -// * -// * @param apiLevel the API level; one of the -// * AST.JLS* constants -// -// * @return a list of property descriptors (element type: -// * {@link StructuralPropertyDescriptor}) -// * @since 3.0 -// */ -// public static List propertyDescriptors(int apiLevel) { -// return PROPERTY_DESCRIPTORS; -// } -// -// /** -// * The comment table, or null if none; initially -// * null. This array is the storage underlying -// * the optionalCommentList ArrayList. -// * @since 3.0 -// */ -// Comment[] optionalCommentTable = null; -// -// /** -// * The comment list (element type: Comment, -// * or null if none; initially null. -// * @since 3.0 -// */ -// private List optionalCommentList = null; -// -// /** -// * The package declaration, or null if none; initially -// * null. -// */ -// private PackageDeclaration optionalPackageDeclaration = null; -// -// /** -// * The list of import declarations in textual order order; -// * initially none (elementType: ImportDeclaration). -// */ -// private ASTNode.NodeList imports = -// new ASTNode.NodeList(IMPORTS_PROPERTY); -// -// /** -// * The list of type declarations in textual order order; -// * initially none (elementType: AbstractTypeDeclaration) -// */ -// private ASTNode.NodeList types = -// new ASTNode.NodeList(TYPES_PROPERTY); -// -// /** -// * Line end table. If lineEndTable[i] == p then the -// * line number i+1 ends at character position -// * p. Except for the last line, the positions are that -// * of the last character of the line delimiter. -// * For example, the source string A\nB\nC has -// * line end table {1, 3} (if \n is one character). -// */ -// private int[] lineEndTable = new int[0]; -// -// /** -// * Canonical empty list of messages. -// */ -// private static final Message[] EMPTY_MESSAGES = new Message[0]; -// -// /** -// * Canonical empty list of problems. -// */ -// private static final IProblem[] EMPTY_PROBLEMS = new IProblem[0]; -// -// /** -// * Messages reported by the compiler during parsing or name resolution. -// */ -// private Message[] messages; -// -// /** -// * Problems reported by the compiler during parsing or name resolution. -// */ -// private IProblem[] problems = EMPTY_PROBLEMS; -// -// /** -// * The comment mapper, or null in none; -// * initially null. -// * @since 3.0 -// */ -// private DefaultCommentMapper commentMapper = null; -// -// /** -// * Sets the line end table for this compilation unit. -// * If lineEndTable[i] == p then line number i+1 -// * ends at character position p. Except for the last line, the -// * positions are that of (the last character of) the line delimiter. -// * For example, the source string A\nB\nC has -// * line end table {1, 3, 4}. -// * -// * @param lineEndtable the line end table -// */ -// void setLineEndTable(int[] lineEndTable) { -// if (lineEndTable == null) { -// throw new NullPointerException(); -// } -// // alternate root is *not* considered a structural property -// // but we protect them nevertheless -// checkModifiable(); -// this.lineEndTable = lineEndTable; -// } -// -// /** -// * Creates a new AST node for a compilation owned by the given AST. -// * The compilation unit initially has no package declaration, no -// * import declarations, and no type declarations. -// *

          -// * N.B. This constructor is package-private; all subclasses must be -// * declared in the same package; clients are unable to declare -// * additional subclasses. -// *

          -// * -// * @param ast the AST that is to own this node -// */ -// CompilationUnit(AST ast) { -// super(ast); -// } -// -// /* (omit javadoc for this method) -// * Method declared on ASTNode. -// * @since 3.0 -// */ -// final List internalStructuralPropertiesForType(int apiLevel) { -// return propertyDescriptors(apiLevel); -// } -// -// /* (omit javadoc for this method) -// * Method declared on ASTNode. -// */ -// final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) { -// if (property == PACKAGE_PROPERTY) { -// if (get) { -// return getPackage(); -// } else { -// setPackage((PackageDeclaration) child); -// return null; -// } -// } -// // allow default implementation to flag the error -// return super.internalGetSetChildProperty(property, get, child); -// } -// -// /* (omit javadoc for this method) -// * Method declared on ASTNode. -// */ -// final List internalGetChildListProperty(ChildListPropertyDescriptor property) { -// if (property == IMPORTS_PROPERTY) { -// return imports(); -// } -// if (property == TYPES_PROPERTY) { -// return types(); -// } -// // allow default implementation to flag the error -// return super.internalGetChildListProperty(property); -// } -// -// /* (omit javadoc for this method) -// * Method declared on ASTNode. -// */ -// final int getNodeType0() { -// return COMPILATION_UNIT; -// } -// -// /* (omit javadoc for this method) -// * Method declared on ASTNode. -// */ -// ASTNode clone0(AST target) { -// CompilationUnit result = new CompilationUnit(target); -// // n.b do not copy line number table or messages -// result.setSourceRange(this.getStartPosition(), this.getLength()); -// result.setPackage( -// (PackageDeclaration) ASTNode.copySubtree(target, getPackage())); -// result.imports().addAll(ASTNode.copySubtrees(target, imports())); -// result.types().addAll(ASTNode.copySubtrees(target, types())); -// return result; -// } -// -// /* (omit javadoc for this method) -// * Method declared on ASTNode. -// */ -// final boolean subtreeMatch0(ASTMatcher matcher, Object other) { -// // dispatch to correct overloaded match method -// return matcher.match(this, other); -// } -// -// /* (omit javadoc for this method) -// * Method declared on ASTNode. -// */ -// void accept0(ASTVisitor visitor) { -// boolean visitChildren = visitor.visit(this); -// if (visitChildren) { -// // visit children in normal left to right reading order -// acceptChild(visitor, getPackage()); -// acceptChildren(visitor, this.imports); -// acceptChildren(visitor, this.types); -// } -// visitor.endVisit(this); -// } -// -// /** -// * Returns the node for the package declaration of this compilation -// * unit, or null if this compilation unit is in the -// * default package. -// * -// * @return the package declaration node, or null if none -// */ -// public PackageDeclaration getPackage() { -// return this.optionalPackageDeclaration; -// } -// -// /** -// * Sets or clears the package declaration of this compilation unit -// * node to the given package declaration node. -// * -// * @param pkgDecl the new package declaration node, or -// * null if this compilation unit does not have a package -// * declaration (that is in the default package) -// * @exception IllegalArgumentException if: -// *
            -// *
          • the node belongs to a different AST
          • -// *
          • the node already has a parent
          • -// *
          -// */ -// public void setPackage(PackageDeclaration pkgDecl) { -// ASTNode oldChild = this.optionalPackageDeclaration; -// preReplaceChild(oldChild, pkgDecl, PACKAGE_PROPERTY); -// this.optionalPackageDeclaration = pkgDecl; -// postReplaceChild(oldChild, pkgDecl, PACKAGE_PROPERTY); -// } -// -// /** -// * Returns the live list of nodes for the import declarations of this -// * compilation unit, in order of appearance. -// * -// * @return the live list of import declaration nodes -// * (elementType: ImportDeclaration) -// */ -// public List imports() { -// return this.imports; -// } -// -// /** -// * Returns the live list of nodes for the top-level type declarations of this -// * compilation unit, in order of appearance. -// *

          -// * Note that in JLS3, the types may include both enum declarations -// * and annotation type declarations introduced in J2SE 1.5. -// * For JLS2, the elements are always TypeDeclaration. -// *

          -// * -// * @return the live list of top-level type declaration -// * nodes (elementType: AbstractTypeDeclaration) -// */ -// public List types() { -// return this.types; -// } -// -// /** -// * Finds the corresponding AST node in the given compilation unit from -// * which the given binding originated. Returns null if the -// * binding does not correspond to any node in this compilation unit. -// * This method always returns null if bindings were not requested -// * when this AST was built. -// *

          -// * The following table indicates the expected node type for the various -// * different kinds of bindings: -// *

            -// *
          • -// *
          • package - a PackageDeclaration
          • -// *
          • class or interface - a TypeDeclaration or a -// * AnonymousClassDeclaration (for anonymous classes)
          • -// *
          • primitive type - none
          • -// *
          • array type - none
          • -// *
          • field - a VariableDeclarationFragment in a -// * FieldDeclaration
          • -// *
          • local variable - a SingleVariableDeclaration, or -// * a VariableDeclarationFragment in a -// * VariableDeclarationStatement or -// * VariableDeclarationExpression
          • -// *
          • method - a MethodDeclaration
          • -// *
          • constructor - a MethodDeclaration
          • -// *
          • annotation type - an AnnotationTypeDeclaration
          • -// *
          • annotation type member - an AnnotationTypeMemberDeclaration
          • -// *
          • enum type - an EnumDeclaration
          • -// *
          • enum constant - an EnumConstantDeclaration
          • -// *
          -// *

          -// *

          -// * Each call to {@link ASTParser#createAST(IProgressMonitor)} with a request for bindings -// * gives rise to separate universe of binding objects. This method always returns -// * null when the binding object comes from a different AST. -// * Use findDeclaringNode(binding.getKey()) when the binding comes -// * from a different AST. -// *

          -// * -// * @param binding the binding -// * @return the corresponding node where the given binding is declared, -// * or null if the binding does not correspond to a node in this -// * compilation unit or if bindings were not requested when this AST was built -// * @see #findDeclaringNode(String) -// */ -// public ASTNode findDeclaringNode(IBinding binding) { -// return this.ast.getBindingResolver().findDeclaringNode(binding); -// } -// -// /** -// * Finds the corresponding AST node in the given compilation unit from -// * which the binding with the given key originated. Returns -// * null if the corresponding node cannot be determined. -// * This method always returns null if bindings were not requested -// * when this AST was built. -// *

          -// * The following table indicates the expected node type for the various -// * different kinds of binding keys: -// *

            -// *
          • -// *
          • package - a PackageDeclaration
          • -// *
          • class or interface - a TypeDeclaration or a -// * AnonymousClassDeclaration (for anonymous classes)
          • -// *
          • primitive type - none
          • -// *
          • array type - none
          • -// *
          • field - a VariableDeclarationFragment in a -// * FieldDeclaration
          • -// *
          • local variable - a SingleVariableDeclaration, or -// * a VariableDeclarationFragment in a -// * VariableDeclarationStatement or -// * VariableDeclarationExpression
          • -// *
          • method - a MethodDeclaration
          • -// *
          • constructor - a MethodDeclaration
          • -// *
          • annotation type - an AnnotationTypeDeclaration
          • -// *
          • annotation type member - an AnnotationTypeMemberDeclaration
          • -// *
          • enum type - an EnumDeclaration
          • -// *
          • enum constant - an EnumConstantDeclaration
          • -// *
          -// *

          -// *

          -// * Note that as explained in {@link IBinding#getKey() IBinding.getkey} -// * there may be no keys for finding the declaring node for local variables, -// * local or anonymous classes, etc. -// *

          -// * -// * @param key the binding key, or null -// * @return the corresponding node where a binding with the given -// * key is declared, or null if the key is null -// * or if the key does not correspond to a node in this compilation unit -// * or if bindings were not requested when this AST was built -// * @see IBinding#getKey() -// * @since 2.1 -// */ -// public ASTNode findDeclaringNode(String key) { -// return this.ast.getBindingResolver().findDeclaringNode(key); -// } -// -// /** -// * Returns the internal comment mapper. -// * -// * @return the comment mapper, or null if none. -// * @since 3.0 -// */ -// DefaultCommentMapper getCommentMapper() { -// return this.commentMapper; -// } -// -// /** -// * Initializes the internal comment mapper with the given -// * scanner. -// * -// * @param scanner the scanner -// * @since 3.0 -// */ -// void initCommentMapper(Scanner scanner) { -// this.commentMapper = new DefaultCommentMapper(this.optionalCommentTable); -// this.commentMapper.initialize(this, scanner); -// } -// -// /** -// * Returns the extended start position of the given node. Unlike -// * {@link ASTNode#getStartPosition()} and {@link ASTNode#getLength()()}, -// * the extended source range may include comments and whitespace -// * immediately before or after the normal source range for the node. -// * -// * @param node the node -// * @return the 0-based character index, or -1 -// * if no source position information is recorded for this node -// * @see #getExtendedLength(ASTNode) -// * @since 3.0 -// */ -// public int getExtendedStartPosition(ASTNode node) { -// if (this.commentMapper == null) { -// return -1; -// } else { -// return this.commentMapper.getExtendedStartPosition(node); -// } -// } -// -// /** -// * Returns the extended source length of the given node. Unlike -// * {@link ASTNode#getStartPosition()} and {@link ASTNode#getLength()()}, -// * the extended source range may include comments and whitespace -// * immediately before or after the normal source range for the node. -// * -// * @param node the node -// * @return a (possibly 0) length, or 0 -// * if no source position information is recorded for this node -// * @see #getExtendedStartPosition(ASTNode) -// * @since 3.0 -// */ -// public int getExtendedLength(ASTNode node) { -// if (this.commentMapper == null) { -// return 0; -// } else { -// return this.commentMapper.getExtendedLength(node); -// } -// } -// -// /** -// * Returns the line number corresponding to the given source character -// * position in the original source string. The initial line of the -// * compilation unit is numbered 1, and each line extends through the -// * last character of the end-of-line delimiter. The very last line extends -// * through the end of the source string and has no line delimiter. -// * For example, the source string class A\n{\n} has 3 lines -// * corresponding to inclusive character ranges [0,7], [8,9], and [10,10]. -// * Returns 1 for a character position that does not correspond to any -// * source line, or if no line number information is available for this -// * compilation unit. -// * -// * @param position a 0-based character position, possibly -// * negative or out of range -// * @return the 1-based line number, or 1 if the character -// * position does not correspond to a source line in the original -// * source file or if line number information is not known for this -// * compilation unit -// * @see ASTParser -// */ -// public int lineNumber(int position) { -// int length = lineEndTable.length; -// if (length == 0) { -// // no line number info -// return 1; -// } -// int low = 0; -// if (position <= lineEndTable[low]) { -// // position illegal or before the first line delimiter -// return 1; -// } -// // assert position > lineEndTable[low+1] && low == 0 -// int hi = length - 1; -// if (position > lineEndTable[hi]) { -// // position beyond the last line separator -// if (position >= getStartPosition() + getLength()) { -// // this is beyond the end of the source length -// return 1; -// } else { -// return length + 1; -// } -// } -// // assert lineEndTable[low] < position <= lineEndTable[hi] -// // && low == 0 && hi == length - 1 && low < hi -// -// // binary search line end table -// while (true) { -// // invariant lineEndTable[low] < position <= lineEndTable[hi] -// // && 0 <= low < hi <= length - 1 -// // reducing measure hi - low -// if (low + 1 == hi) { -// // assert lineEndTable[low] < position <= lineEndTable[low+1] -// // position is on line low+1 (line number is low+2) -// return low + 2; -// } -// // assert hi - low >= 2, so average is truly in between -// int mid = (low + hi) / 2; -// // assert 0 <= low < mid < hi <= length - 1 -// if (position <= lineEndTable[mid]) { -// // assert lineEndTable[low] < position <= lineEndTable[mid] -// // && 0 <= low < mid < hi <= length - 1 -// hi = mid; -// } else { -// // position > lineEndTable[mid] -// // assert lineEndTable[mid] < position <= lineEndTable[hi] -// // && 0 <= low < mid < hi <= length - 1 -// low = mid; -// } -// // in both cases, invariant reachieved with reduced measure -// } -// } -// -// /** -// * Returns the list of messages reported by the compiler during the parsing -// * or the type checking of this compilation unit. This list might be a subset of -// * errors detected and reported by a Java compiler. -// *

          -// * This list of messages is suitable for simple clients that do little -// * more than log the messages or display them to the user. Clients that -// * need further details should call getProblems to get -// * compiler problem objects. -// *

          -// * -// * @return the list of messages, possibly empty -// * @see #getProblems() -// * @see ASTParser -// */ -// public Message[] getMessages() { -// if (this.messages == null) { -// int problemLength = this.problems.length; -// if (problemLength == 0) { -// this.messages = EMPTY_MESSAGES; -// } else { -// this.messages = new Message[problemLength]; -// for (int i = 0; i < problemLength; i++) { -// IProblem problem = this.problems[i]; -// int start = problem.getSourceStart(); -// int end = problem.getSourceEnd(); -// messages[i] = new Message(problem.getMessage(), start, end - start + 1); -// } -// } -// } -// return this.messages; -// } -// -// /** -// * Returns the list of detailed problem reports noted by the compiler -// * during the parsing or the type checking of this compilation unit. This -// * list might be a subset of errors detected and reported by a Java -// * compiler. -// *

          -// * Simple clients that do little more than log the messages or display -// * them to the user should probably call getMessages instead. -// *

          -// * -// * @return the list of detailed problem objects, possibly empty -// * @see #getMessages() -// * @see ASTParser -// * @since 2.1 -// */ -// public IProblem[] getProblems() { -// return this.problems; -// } -// -// /** -// * Sets the array of problems reported by the compiler during the parsing or -// * name resolution of this compilation unit. -// * -// * @param problems the list of problems -// */ -// void setProblems(IProblem[] problems) { -// if (problems == null) { -// throw new IllegalArgumentException(); -// } -// this.problems = problems; -// } -// -// /** -// * Returns a list of the comments encountered while parsing -// * this compilation unit. -// *

          -// * Since the Java language allows comments to appear most anywhere -// * in the source text, it is problematic to locate comments in relation -// * to the structure of an AST. The one exception is doc comments -// * which, by convention, immediately precede type, field, and -// * method declarations; these comments are located in the AST -// * by {@link BodyDeclaration#getJavadoc BodyDeclaration.getJavadoc}. -// * Other comments do not show up in the AST. The table of comments -// * is provided for clients that need to find the source ranges of -// * all comments in the original source string. It includes entries -// * for comments of all kinds (line, block, and doc), arranged in order -// * of increasing source position. -// *

          -// * Note on comment parenting: The {@link ASTNode#getParent() getParent()} -// * of a doc comment associated with a body declaration is the body -// * declaration node; for these comment nodes -// * {@link ASTNode#getRoot() getRoot()} will return the compilation unit -// * (assuming an unmodified AST) reflecting the fact that these nodes -// * are property located in the AST for the compilation unit. -// * However, for other comment nodes, {@link ASTNode#getParent() getParent()} -// * will return null, and {@link ASTNode#getRoot() getRoot()} -// * will return the comment node itself, indicating that these comment nodes -// * are not directly connected to the AST for the compilation unit. The -// * {@link Comment#getAlternateRoot Comment.getAlternateRoot} -// * method provides a way to navigate from a comment to its compilation -// * unit. -// *

          -// *

          -// * A note on visitors: The only comment nodes that will be visited when -// * visiting a compilation unit are the doc comments parented by body -// * declarations. To visit all comments in normal reading order, iterate -// * over the comment table and call {@link ASTNode#accept(ASTVisitor) accept} -// * on each element. -// *

          -// *

          -// * Clients cannot modify the resulting list. -// *

          -// * -// * @return an unmodifiable list of comments in increasing order of source -// * start position, or null if comment information -// * for this compilation unit is not available -// * @see ASTParser -// * @since 3.0 -// */ -// public List getCommentList() { -// return this.optionalCommentList; -// } -// -// /** -// * Sets the list of the comments encountered while parsing -// * this compilation unit. -// * -// * @param commentTable a list of comments in increasing order -// * of source start position, or null if comment -// * information for this compilation unit is not available -// * @exception IllegalArgumentException if the comment table is -// * not in increasing order of source position -// * @see #getCommentList() -// * @see ASTParser -// * @since 3.0 -// */ -// void setCommentTable(Comment[] commentTable) { -// // double check table to ensure that all comments have -// // source positions and are in strictly increasing order -// if (commentTable == null) { -// this.optionalCommentList = null; -// this.optionalCommentTable = null; -// } else { -// int nextAvailablePosition = 0; -// for (int i = 0; i < commentTable.length; i++) { -// Comment comment = commentTable[i]; -// if (comment == null) { -// throw new IllegalArgumentException(); -// } -// int start = comment.getStartPosition(); -// int length = comment.getLength(); -// if (start < 0 || length < 0 || start < nextAvailablePosition) { -// throw new IllegalArgumentException(); -// } -// nextAvailablePosition = comment.getStartPosition() + comment.getLength(); -// } -// this.optionalCommentTable = commentTable; -// List commentList = Arrays.asList(commentTable); -// // protect the list from further modification -// this.optionalCommentList = Collections.unmodifiableList(commentList); -// } -// } -// -// -// /* (omit javadoc for this method) -// * Method declared on ASTNode. -// */ -// void appendDebugString(StringBuffer buffer) { -// buffer.append("CompilationUnit"); //$NON-NLS-1$ -// // include the type names -// buffer.append("["); //$NON-NLS-1$ -// for (Iterator it = types().iterator(); it.hasNext(); ) { -// AbstractTypeDeclaration d = (AbstractTypeDeclaration) it.next(); -// buffer.append(d.getName().getIdentifier()); -// if (it.hasNext()) { -// buffer.append(","); //$NON-NLS-1$ -// } -// } -// buffer.append("]"); //$NON-NLS-1$ -// } -// -// /* (omit javadoc for this method) -// * Method declared on ASTNode. -// */ -// int memSize() { -// int size = BASE_NODE_SIZE + 8 * 4; -// if (this.lineEndTable != null) { -// size += HEADERS + 4 * this.lineEndTable.length; -// } -// if (this.optionalCommentTable != null) { -// size += HEADERS + 4 * this.optionalCommentTable.length; -// } -// // ignore the space taken up by optionalCommentList -// return size; -// } -// -// /* (omit javadoc for this method) -// * Method declared on ASTNode. -// */ -// int treeSize() { -// int size = memSize(); -// if (this.optionalPackageDeclaration != null) { -// size += getPackage().treeSize(); -// } -// size += this.imports.listSize(); -// size += this.types.listSize(); -// // include disconnected comments -// if (this.optionalCommentList != null) { -// for (int i = 0; i < this.optionalCommentList.size(); i++) { -// Comment comment = (Comment) this.optionalCommentList.get(i); -// if (comment != null && comment.getParent() == null) { -// size += comment.treeSize(); -// } -// } -// } -// return size; -// } -// -// /** -// * Enables the recording of changes to this compilation -// * unit and its descendents. The compilation unit must have -// * been created by ASTParser and still be in -// * its original state. Once recording is on, -// * arbitrary changes to the subtree rooted at this compilation -// * unit are recorded internally. Once the modification has -// * been completed, call rewrite to get an object -// * representing the corresponding edits to the original -// * source code string. -// * -// * @exception IllegalArgumentException if this compilation unit is -// * marked as unmodifiable, or if this compilation unit has already -// * been tampered with, or recording has already been enabled -// * @since 3.0 -// */ -// public void recordModifications() { -// getAST().recordModifications(this); -// } -// -// /** -// * Converts all modifications recorded for this compilation -// * unit into an object representing the corresponding text -// * edits to the given document containing the original source -// * code for this compilation unit. -// *

          -// * The compilation unit must have been created by -// * ASTParser from the source code string in the -// * given document, and recording must have been turned -// * on with a prior call to recordModifications -// * while the AST was still in its original state. -// *

          -// *

          -// * Calling this methods does not discard the modifications -// * on record. Subsequence modifications made to the AST -// * are added to the ones already on record. If this method -// * is called again later, the resulting text edit object will -// * accurately reflect the net cumulative affect of all those -// * changes. -// *

          -// * -// * @param document original document containing source code -// * for this compilation unit -// * @param options the table of formatter options -// * (key type: String; value type: String); -// * or null to use the standard global options -// * {@link JavaCore#getOptions() JavaCore.getOptions()}. -// * @return text edit object describing the changes to the -// * document corresponding to the recorded AST modifications -// * @exception IllegalArgumentException if the document passed is -// * null or does not correspond to this AST -// * @exception IllegalStateException if recordModifications -// * was not called to enable recording -// * @see #recordModifications() -// * @since 3.0 -// */ -// public TextEdit rewrite(IDocument document, Map options) { -// return getAST().rewrite(document, options); -// } + // /** + // * The "package" structural property of this node type. + // * + // * @since 3.0 + // */ + // public static final ChildPropertyDescriptor PACKAGE_PROPERTY = + // new ChildPropertyDescriptor(CompilationUnit.class, "package", + // PackageDeclaration.class, OPTIONAL, NO_CYCLE_RISK); //$NON-NLS-1$ + // + // /** + // * The "imports" structural property of this node type. + // * + // * @since 3.0 + // */ + // public static final ChildListPropertyDescriptor IMPORTS_PROPERTY = + // new ChildListPropertyDescriptor(CompilationUnit.class, "imports", + // ImportDeclaration.class, NO_CYCLE_RISK); //$NON-NLS-1$ + // + // /** + // * The "types" structural property of this node type. + // * + // * @since 3.0 + // */ + // public static final ChildListPropertyDescriptor TYPES_PROPERTY = + // new ChildListPropertyDescriptor(CompilationUnit.class, "types", + // AbstractTypeDeclaration.class, CYCLE_RISK); //$NON-NLS-1$ + // + // /** + // * A list of property descriptors (element type: + // * {@link StructuralPropertyDescriptor}), + // * or null if uninitialized. + // * @since 3.0 + // */ + // private static final List PROPERTY_DESCRIPTORS; + // + // static { + // createPropertyList(CompilationUnit.class); + // addProperty(PACKAGE_PROPERTY); + // addProperty(IMPORTS_PROPERTY); + // addProperty(TYPES_PROPERTY); + // PROPERTY_DESCRIPTORS = reapPropertyList(); + // } + // + // /** + // * Returns a list of structural property descriptors for this node type. + // * Clients must not modify the result. + // * + // * @param apiLevel the API level; one of the + // * AST.JLS* constants + // + // * @return a list of property descriptors (element type: + // * {@link StructuralPropertyDescriptor}) + // * @since 3.0 + // */ + // public static List propertyDescriptors(int apiLevel) { + // return PROPERTY_DESCRIPTORS; + // } + // + // /** + // * The comment table, or null if none; initially + // * null. This array is the storage underlying + // * the optionalCommentList ArrayList. + // * @since 3.0 + // */ + // Comment[] optionalCommentTable = null; + // + // /** + // * The comment list (element type: Comment, + // * or null if none; initially null. + // * @since 3.0 + // */ + // private List optionalCommentList = null; + // + // /** + // * The package declaration, or null if none; initially + // * null. + // */ + // private PackageDeclaration optionalPackageDeclaration = null; + // + // /** + // * The list of import declarations in textual order order; + // * initially none (elementType: ImportDeclaration). + // */ + // private ASTNode.NodeList imports = + // new ASTNode.NodeList(IMPORTS_PROPERTY); + // + // /** + // * The list of type declarations in textual order order; + // * initially none (elementType: AbstractTypeDeclaration) + // */ + // private ASTNode.NodeList types = + // new ASTNode.NodeList(TYPES_PROPERTY); + // + // /** + // * Line end table. If lineEndTable[i] == p then the + // * line number i+1 ends at character position + // * p. Except for the last line, the positions are that + // * of the last character of the line delimiter. + // * For example, the source string A\nB\nC has + // * line end table {1, 3} (if \n is one character). + // */ + // private int[] lineEndTable = new int[0]; + // + // /** + // * Canonical empty list of messages. + // */ + // private static final Message[] EMPTY_MESSAGES = new Message[0]; + // + // /** + // * Canonical empty list of problems. + // */ + // private static final IProblem[] EMPTY_PROBLEMS = new IProblem[0]; + // + // /** + // * Messages reported by the compiler during parsing or name resolution. + // */ + // private Message[] messages; + // + // /** + // * Problems reported by the compiler during parsing or name resolution. + // */ + // private IProblem[] problems = EMPTY_PROBLEMS; + // + // /** + // * The comment mapper, or null in none; + // * initially null. + // * @since 3.0 + // */ + // private DefaultCommentMapper commentMapper = null; + // + // /** + // * Sets the line end table for this compilation unit. + // * If lineEndTable[i] == p then line number i+1 + // * ends at character position p. Except for the last line, + // the + // * positions are that of (the last character of) the line delimiter. + // * For example, the source string A\nB\nC has + // * line end table {1, 3, 4}. + // * + // * @param lineEndtable the line end table + // */ + // void setLineEndTable(int[] lineEndTable) { + // if (lineEndTable == null) { + // throw new NullPointerException(); + // } + // // alternate root is *not* considered a structural property + // // but we protect them nevertheless + // checkModifiable(); + // this.lineEndTable = lineEndTable; + // } + // + // /** + // * Creates a new AST node for a compilation owned by the given AST. + // * The compilation unit initially has no package declaration, no + // * import declarations, and no type declarations. + // *

          + // * N.B. This constructor is package-private; all subclasses must be + // * declared in the same package; clients are unable to declare + // * additional subclasses. + // *

          + // * + // * @param ast the AST that is to own this node + // */ + // CompilationUnit(AST ast) { + // super(ast); + // } + // + // /* (omit javadoc for this method) + // * Method declared on ASTNode. + // * @since 3.0 + // */ + // final List internalStructuralPropertiesForType(int apiLevel) { + // return propertyDescriptors(apiLevel); + // } + // + // /* (omit javadoc for this method) + // * Method declared on ASTNode. + // */ + // final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor + // property, boolean get, ASTNode child) { + // if (property == PACKAGE_PROPERTY) { + // if (get) { + // return getPackage(); + // } else { + // setPackage((PackageDeclaration) child); + // return null; + // } + // } + // // allow default implementation to flag the error + // return super.internalGetSetChildProperty(property, get, child); + // } + // + // /* (omit javadoc for this method) + // * Method declared on ASTNode. + // */ + // final List internalGetChildListProperty(ChildListPropertyDescriptor + // property) { + // if (property == IMPORTS_PROPERTY) { + // return imports(); + // } + // if (property == TYPES_PROPERTY) { + // return types(); + // } + // // allow default implementation to flag the error + // return super.internalGetChildListProperty(property); + // } + // + // /* (omit javadoc for this method) + // * Method declared on ASTNode. + // */ + // final int getNodeType0() { + // return COMPILATION_UNIT; + // } + // + // /* (omit javadoc for this method) + // * Method declared on ASTNode. + // */ + // ASTNode clone0(AST target) { + // CompilationUnit result = new CompilationUnit(target); + // // n.b do not copy line number table or messages + // result.setSourceRange(this.getStartPosition(), this.getLength()); + // result.setPackage( + // (PackageDeclaration) ASTNode.copySubtree(target, getPackage())); + // result.imports().addAll(ASTNode.copySubtrees(target, imports())); + // result.types().addAll(ASTNode.copySubtrees(target, types())); + // return result; + // } + // + // /* (omit javadoc for this method) + // * Method declared on ASTNode. + // */ + // final boolean subtreeMatch0(ASTMatcher matcher, Object other) { + // // dispatch to correct overloaded match method + // return matcher.match(this, other); + // } + // + // /* (omit javadoc for this method) + // * Method declared on ASTNode. + // */ + // void accept0(ASTVisitor visitor) { + // boolean visitChildren = visitor.visit(this); + // if (visitChildren) { + // // visit children in normal left to right reading order + // acceptChild(visitor, getPackage()); + // acceptChildren(visitor, this.imports); + // acceptChildren(visitor, this.types); + // } + // visitor.endVisit(this); + // } + // + // /** + // * Returns the node for the package declaration of this compilation + // * unit, or null if this compilation unit is in the + // * default package. + // * + // * @return the package declaration node, or null if none + // */ + // public PackageDeclaration getPackage() { + // return this.optionalPackageDeclaration; + // } + // + // /** + // * Sets or clears the package declaration of this compilation unit + // * node to the given package declaration node. + // * + // * @param pkgDecl the new package declaration node, or + // * null if this compilation unit does not have a package + // * declaration (that is in the default package) + // * @exception IllegalArgumentException if: + // *
            + // *
          • the node belongs to a different AST
          • + // *
          • the node already has a parent
          • + // *
          + // */ + // public void setPackage(PackageDeclaration pkgDecl) { + // ASTNode oldChild = this.optionalPackageDeclaration; + // preReplaceChild(oldChild, pkgDecl, PACKAGE_PROPERTY); + // this.optionalPackageDeclaration = pkgDecl; + // postReplaceChild(oldChild, pkgDecl, PACKAGE_PROPERTY); + // } + // + // /** + // * Returns the live list of nodes for the import declarations of this + // * compilation unit, in order of appearance. + // * + // * @return the live list of import declaration nodes + // * (elementType: ImportDeclaration) + // */ + // public List imports() { + // return this.imports; + // } + // + // /** + // * Returns the live list of nodes for the top-level type declarations of + // this + // * compilation unit, in order of appearance. + // *

          + // * Note that in JLS3, the types may include both enum declarations + // * and annotation type declarations introduced in J2SE 1.5. + // * For JLS2, the elements are always TypeDeclaration. + // *

          + // * + // * @return the live list of top-level type declaration + // * nodes (elementType: AbstractTypeDeclaration) + // */ + // public List types() { + // return this.types; + // } + // + // /** + // * Finds the corresponding AST node in the given compilation unit from + // * which the given binding originated. Returns null if the + // * binding does not correspond to any node in this compilation unit. + // * This method always returns null if bindings were not + // requested + // * when this AST was built. + // *

          + // * The following table indicates the expected node type for the various + // * different kinds of bindings: + // *

            + // *
          • + // *
          • package - a PackageDeclaration
          • + // *
          • class or interface - a TypeDeclaration or a + // * AnonymousClassDeclaration (for anonymous classes)
          • + // *
          • primitive type - none
          • + // *
          • array type - none
          • + // *
          • field - a VariableDeclarationFragment in a + // * FieldDeclaration
          • + // *
          • local variable - a SingleVariableDeclaration, or + // * a VariableDeclarationFragment in a + // * VariableDeclarationStatement or + // * VariableDeclarationExpression
          • + // *
          • method - a MethodDeclaration
          • + // *
          • constructor - a MethodDeclaration
          • + // *
          • annotation type - an AnnotationTypeDeclaration
          • + // *
          • annotation type member - an + // AnnotationTypeMemberDeclaration
          • + // *
          • enum type - an EnumDeclaration
          • + // *
          • enum constant - an EnumConstantDeclaration
          • + // *
          + // *

          + // *

          + // * Each call to {@link ASTParser#createAST(IProgressMonitor)} with a + // request for bindings + // * gives rise to separate universe of binding objects. This method always + // returns + // * null when the binding object comes from a different AST. + // * Use findDeclaringNode(binding.getKey()) when the binding + // comes + // * from a different AST. + // *

          + // * + // * @param binding the binding + // * @return the corresponding node where the given binding is declared, + // * or null if the binding does not correspond to a node in + // this + // * compilation unit or if bindings were not requested when this AST was + // built + // * @see #findDeclaringNode(String) + // */ + // public ASTNode findDeclaringNode(IBinding binding) { + // return this.ast.getBindingResolver().findDeclaringNode(binding); + // } + // + // /** + // * Finds the corresponding AST node in the given compilation unit from + // * which the binding with the given key originated. Returns + // * null if the corresponding node cannot be determined. + // * This method always returns null if bindings were not + // requested + // * when this AST was built. + // *

          + // * The following table indicates the expected node type for the various + // * different kinds of binding keys: + // *

            + // *
          • + // *
          • package - a PackageDeclaration
          • + // *
          • class or interface - a TypeDeclaration or a + // * AnonymousClassDeclaration (for anonymous classes)
          • + // *
          • primitive type - none
          • + // *
          • array type - none
          • + // *
          • field - a VariableDeclarationFragment in a + // * FieldDeclaration
          • + // *
          • local variable - a SingleVariableDeclaration, or + // * a VariableDeclarationFragment in a + // * VariableDeclarationStatement or + // * VariableDeclarationExpression
          • + // *
          • method - a MethodDeclaration
          • + // *
          • constructor - a MethodDeclaration
          • + // *
          • annotation type - an AnnotationTypeDeclaration
          • + // *
          • annotation type member - an + // AnnotationTypeMemberDeclaration
          • + // *
          • enum type - an EnumDeclaration
          • + // *
          • enum constant - an EnumConstantDeclaration
          • + // *
          + // *

          + // *

          + // * Note that as explained in {@link IBinding#getKey() IBinding.getkey} + // * there may be no keys for finding the declaring node for local + // variables, + // * local or anonymous classes, etc. + // *

          + // * + // * @param key the binding key, or null + // * @return the corresponding node where a binding with the given + // * key is declared, or null if the key is null + // * or if the key does not correspond to a node in this compilation unit + // * or if bindings were not requested when this AST was built + // * @see IBinding#getKey() + // * @since 2.1 + // */ + // public ASTNode findDeclaringNode(String key) { + // return this.ast.getBindingResolver().findDeclaringNode(key); + // } + // + // /** + // * Returns the internal comment mapper. + // * + // * @return the comment mapper, or null if none. + // * @since 3.0 + // */ + // DefaultCommentMapper getCommentMapper() { + // return this.commentMapper; + // } + // + // /** + // * Initializes the internal comment mapper with the given + // * scanner. + // * + // * @param scanner the scanner + // * @since 3.0 + // */ + // void initCommentMapper(Scanner scanner) { + // this.commentMapper = new DefaultCommentMapper(this.optionalCommentTable); + // this.commentMapper.initialize(this, scanner); + // } + // + // /** + // * Returns the extended start position of the given node. Unlike + // * {@link ASTNode#getStartPosition()} and {@link ASTNode#getLength()()}, + // * the extended source range may include comments and whitespace + // * immediately before or after the normal source range for the node. + // * + // * @param node the node + // * @return the 0-based character index, or -1 + // * if no source position information is recorded for this node + // * @see #getExtendedLength(ASTNode) + // * @since 3.0 + // */ + // public int getExtendedStartPosition(ASTNode node) { + // if (this.commentMapper == null) { + // return -1; + // } else { + // return this.commentMapper.getExtendedStartPosition(node); + // } + // } + // + // /** + // * Returns the extended source length of the given node. Unlike + // * {@link ASTNode#getStartPosition()} and {@link ASTNode#getLength()()}, + // * the extended source range may include comments and whitespace + // * immediately before or after the normal source range for the node. + // * + // * @param node the node + // * @return a (possibly 0) length, or 0 + // * if no source position information is recorded for this node + // * @see #getExtendedStartPosition(ASTNode) + // * @since 3.0 + // */ + // public int getExtendedLength(ASTNode node) { + // if (this.commentMapper == null) { + // return 0; + // } else { + // return this.commentMapper.getExtendedLength(node); + // } + // } + // + // /** + // * Returns the line number corresponding to the given source character + // * position in the original source string. The initial line of the + // * compilation unit is numbered 1, and each line extends through the + // * last character of the end-of-line delimiter. The very last line extends + // * through the end of the source string and has no line delimiter. + // * For example, the source string class A\n{\n} has 3 lines + // * corresponding to inclusive character ranges [0,7], [8,9], and [10,10]. + // * Returns 1 for a character position that does not correspond to any + // * source line, or if no line number information is available for this + // * compilation unit. + // * + // * @param position a 0-based character position, possibly + // * negative or out of range + // * @return the 1-based line number, or 1 if the character + // * position does not correspond to a source line in the original + // * source file or if line number information is not known for this + // * compilation unit + // * @see ASTParser + // */ + // public int lineNumber(int position) { + // int length = lineEndTable.length; + // if (length == 0) { + // // no line number info + // return 1; + // } + // int low = 0; + // if (position <= lineEndTable[low]) { + // // position illegal or before the first line delimiter + // return 1; + // } + // // assert position > lineEndTable[low+1] && low == 0 + // int hi = length - 1; + // if (position > lineEndTable[hi]) { + // // position beyond the last line separator + // if (position >= getStartPosition() + getLength()) { + // // this is beyond the end of the source length + // return 1; + // } else { + // return length + 1; + // } + // } + // // assert lineEndTable[low] < position <= lineEndTable[hi] + // // && low == 0 && hi == length - 1 && low < hi + // + // // binary search line end table + // while (true) { + // // invariant lineEndTable[low] < position <= lineEndTable[hi] + // // && 0 <= low < hi <= length - 1 + // // reducing measure hi - low + // if (low + 1 == hi) { + // // assert lineEndTable[low] < position <= lineEndTable[low+1] + // // position is on line low+1 (line number is low+2) + // return low + 2; + // } + // // assert hi - low >= 2, so average is truly in between + // int mid = (low + hi) / 2; + // // assert 0 <= low < mid < hi <= length - 1 + // if (position <= lineEndTable[mid]) { + // // assert lineEndTable[low] < position <= lineEndTable[mid] + // // && 0 <= low < mid < hi <= length - 1 + // hi = mid; + // } else { + // // position > lineEndTable[mid] + // // assert lineEndTable[mid] < position <= lineEndTable[hi] + // // && 0 <= low < mid < hi <= length - 1 + // low = mid; + // } + // // in both cases, invariant reachieved with reduced measure + // } + // } + // + // /** + // * Returns the list of messages reported by the compiler during the + // parsing + // * or the type checking of this compilation unit. This list might be a + // subset of + // * errors detected and reported by a Java compiler. + // *

          + // * This list of messages is suitable for simple clients that do little + // * more than log the messages or display them to the user. Clients that + // * need further details should call getProblems to get + // * compiler problem objects. + // *

          + // * + // * @return the list of messages, possibly empty + // * @see #getProblems() + // * @see ASTParser + // */ + // public Message[] getMessages() { + // if (this.messages == null) { + // int problemLength = this.problems.length; + // if (problemLength == 0) { + // this.messages = EMPTY_MESSAGES; + // } else { + // this.messages = new Message[problemLength]; + // for (int i = 0; i < problemLength; i++) { + // IProblem problem = this.problems[i]; + // int start = problem.getSourceStart(); + // int end = problem.getSourceEnd(); + // messages[i] = new Message(problem.getMessage(), start, end - start + 1); + // } + // } + // } + // return this.messages; + // } + // + // /** + // * Returns the list of detailed problem reports noted by the compiler + // * during the parsing or the type checking of this compilation unit. This + // * list might be a subset of errors detected and reported by a Java + // * compiler. + // *

          + // * Simple clients that do little more than log the messages or display + // * them to the user should probably call getMessages instead. + // *

          + // * + // * @return the list of detailed problem objects, possibly empty + // * @see #getMessages() + // * @see ASTParser + // * @since 2.1 + // */ + // public IProblem[] getProblems() { + // return this.problems; + // } + // + // /** + // * Sets the array of problems reported by the compiler during the parsing + // or + // * name resolution of this compilation unit. + // * + // * @param problems the list of problems + // */ + // void setProblems(IProblem[] problems) { + // if (problems == null) { + // throw new IllegalArgumentException(); + // } + // this.problems = problems; + // } + // + // /** + // * Returns a list of the comments encountered while parsing + // * this compilation unit. + // *

          + // * Since the Java language allows comments to appear most anywhere + // * in the source text, it is problematic to locate comments in relation + // * to the structure of an AST. The one exception is doc comments + // * which, by convention, immediately precede type, field, and + // * method declarations; these comments are located in the AST + // * by {@link BodyDeclaration#getJavadoc BodyDeclaration.getJavadoc}. + // * Other comments do not show up in the AST. The table of comments + // * is provided for clients that need to find the source ranges of + // * all comments in the original source string. It includes entries + // * for comments of all kinds (line, block, and doc), arranged in order + // * of increasing source position. + // *

          + // * Note on comment parenting: The {@link ASTNode#getParent() getParent()} + // * of a doc comment associated with a body declaration is the body + // * declaration node; for these comment nodes + // * {@link ASTNode#getRoot() getRoot()} will return the compilation unit + // * (assuming an unmodified AST) reflecting the fact that these nodes + // * are property located in the AST for the compilation unit. + // * However, for other comment nodes, {@link ASTNode#getParent() + // getParent()} + // * will return null, and {@link ASTNode#getRoot() getRoot()} + // * will return the comment node itself, indicating that these comment + // nodes + // * are not directly connected to the AST for the compilation unit. The + // * {@link Comment#getAlternateRoot Comment.getAlternateRoot} + // * method provides a way to navigate from a comment to its compilation + // * unit. + // *

          + // *

          + // * A note on visitors: The only comment nodes that will be visited when + // * visiting a compilation unit are the doc comments parented by body + // * declarations. To visit all comments in normal reading order, iterate + // * over the comment table and call {@link ASTNode#accept(ASTVisitor) + // accept} + // * on each element. + // *

          + // *

          + // * Clients cannot modify the resulting list. + // *

          + // * + // * @return an unmodifiable list of comments in increasing order of source + // * start position, or null if comment information + // * for this compilation unit is not available + // * @see ASTParser + // * @since 3.0 + // */ + // public List getCommentList() { + // return this.optionalCommentList; + // } + // + // /** + // * Sets the list of the comments encountered while parsing + // * this compilation unit. + // * + // * @param commentTable a list of comments in increasing order + // * of source start position, or null if comment + // * information for this compilation unit is not available + // * @exception IllegalArgumentException if the comment table is + // * not in increasing order of source position + // * @see #getCommentList() + // * @see ASTParser + // * @since 3.0 + // */ + // void setCommentTable(Comment[] commentTable) { + // // double check table to ensure that all comments have + // // source positions and are in strictly increasing order + // if (commentTable == null) { + // this.optionalCommentList = null; + // this.optionalCommentTable = null; + // } else { + // int nextAvailablePosition = 0; + // for (int i = 0; i < commentTable.length; i++) { + // Comment comment = commentTable[i]; + // if (comment == null) { + // throw new IllegalArgumentException(); + // } + // int start = comment.getStartPosition(); + // int length = comment.getLength(); + // if (start < 0 || length < 0 || start < nextAvailablePosition) { + // throw new IllegalArgumentException(); + // } + // nextAvailablePosition = comment.getStartPosition() + comment.getLength(); + // } + // this.optionalCommentTable = commentTable; + // List commentList = Arrays.asList(commentTable); + // // protect the list from further modification + // this.optionalCommentList = Collections.unmodifiableList(commentList); + // } + // } + // + // + // /* (omit javadoc for this method) + // * Method declared on ASTNode. + // */ + // void appendDebugString(StringBuffer buffer) { + // buffer.append("CompilationUnit"); //$NON-NLS-1$ + // // include the type names + // buffer.append("["); //$NON-NLS-1$ + // for (Iterator it = types().iterator(); it.hasNext(); ) { + // AbstractTypeDeclaration d = (AbstractTypeDeclaration) it.next(); + // buffer.append(d.getName().getIdentifier()); + // if (it.hasNext()) { + // buffer.append(","); //$NON-NLS-1$ + // } + // } + // buffer.append("]"); //$NON-NLS-1$ + // } + // + // /* (omit javadoc for this method) + // * Method declared on ASTNode. + // */ + // int memSize() { + // int size = BASE_NODE_SIZE + 8 * 4; + // if (this.lineEndTable != null) { + // size += HEADERS + 4 * this.lineEndTable.length; + // } + // if (this.optionalCommentTable != null) { + // size += HEADERS + 4 * this.optionalCommentTable.length; + // } + // // ignore the space taken up by optionalCommentList + // return size; + // } + // + // /* (omit javadoc for this method) + // * Method declared on ASTNode. + // */ + // int treeSize() { + // int size = memSize(); + // if (this.optionalPackageDeclaration != null) { + // size += getPackage().treeSize(); + // } + // size += this.imports.listSize(); + // size += this.types.listSize(); + // // include disconnected comments + // if (this.optionalCommentList != null) { + // for (int i = 0; i < this.optionalCommentList.size(); i++) { + // Comment comment = (Comment) this.optionalCommentList.get(i); + // if (comment != null && comment.getParent() == null) { + // size += comment.treeSize(); + // } + // } + // } + // return size; + // } + // + // /** + // * Enables the recording of changes to this compilation + // * unit and its descendents. The compilation unit must have + // * been created by ASTParser and still be in + // * its original state. Once recording is on, + // * arbitrary changes to the subtree rooted at this compilation + // * unit are recorded internally. Once the modification has + // * been completed, call rewrite to get an object + // * representing the corresponding edits to the original + // * source code string. + // * + // * @exception IllegalArgumentException if this compilation unit is + // * marked as unmodifiable, or if this compilation unit has already + // * been tampered with, or recording has already been enabled + // * @since 3.0 + // */ + // public void recordModifications() { + // getAST().recordModifications(this); + // } + // + // /** + // * Converts all modifications recorded for this compilation + // * unit into an object representing the corresponding text + // * edits to the given document containing the original source + // * code for this compilation unit. + // *

          + // * The compilation unit must have been created by + // * ASTParser from the source code string in the + // * given document, and recording must have been turned + // * on with a prior call to recordModifications + // * while the AST was still in its original state. + // *

          + // *

          + // * Calling this methods does not discard the modifications + // * on record. Subsequence modifications made to the AST + // * are added to the ones already on record. If this method + // * is called again later, the resulting text edit object will + // * accurately reflect the net cumulative affect of all those + // * changes. + // *

          + // * + // * @param document original document containing source code + // * for this compilation unit + // * @param options the table of formatter options + // * (key type: String; value type: String); + // * or null to use the standard global options + // * {@link JavaCore#getOptions() JavaCore.getOptions()}. + // * @return text edit object describing the changes to the + // * document corresponding to the recorded AST modifications + // * @exception IllegalArgumentException if the document passed is + // * null or does not correspond to this AST + // * @exception IllegalStateException if recordModifications + // * was not called to enable recording + // * @see #recordModifications() + // * @since 3.0 + // */ + // public TextEdit rewrite(IDocument document, Map options) { + // return getAST().rewrite(document, options); + // } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/formatter/CodeFormatter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/formatter/CodeFormatter.java index d977c00..4e20db0 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/formatter/CodeFormatter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/formatter/CodeFormatter.java @@ -28,43 +28,54 @@ public abstract class CodeFormatter { * Kind used to format an expression */ public static final int K_EXPRESSION = 0x01; - + /** * Kind used to format a set of statements */ public static final int K_STATEMENTS = 0x02; - + /** * Kind used to format a set of class body declarations */ public static final int K_CLASS_BODY_DECLARATIONS = 0x04; - + /** * Kind used to format a compilation unit */ public static final int K_COMPILATION_UNIT = 0x08; - /** - * Format source, - * and returns a text edit that correspond to the difference between the given string and the formatted string. - * It returns null if the given string cannot be formatted. + /** + * Format source, and returns a text edit that correspond to + * the difference between the given string and the formatted string. It + * returns null if the given string cannot be formatted. * - * If the offset position is matching a whitespace, the result can include whitespaces. It would be up to the - * caller to get rid of preceeding whitespaces. + * If the offset position is matching a whitespace, the result can include + * whitespaces. It would be up to the caller to get rid of preceeding + * whitespaces. * - * @param kind Use to specify the kind of the code snippet to format. It can be any of these: - * K_EXPRESSION, K_STATEMENTS, K_CLASS_BODY_DECLARATIONS, K_COMPILATION_UNIT, K_UNKNOWN - * @param source the source to format - * @param offset the given offset to start recording the edits (inclusive). - * @param length the given length to stop recording the edits (exclusive). - * @param indentationLevel the initial indentation level, used - * to shift left/right the entire source fragment. An initial indentation - * level of zero or below has no effect. - * @param lineSeparator the line separator to use in formatted source, - * if set to null, then the platform default one will be used. + * @param kind + * Use to specify the kind of the code snippet to format. It can + * be any of these: K_EXPRESSION, K_STATEMENTS, + * K_CLASS_BODY_DECLARATIONS, K_COMPILATION_UNIT, K_UNKNOWN + * @param source + * the source to format + * @param offset + * the given offset to start recording the edits (inclusive). + * @param length + * the given length to stop recording the edits (exclusive). + * @param indentationLevel + * the initial indentation level, used to shift left/right the + * entire source fragment. An initial indentation level of zero + * or below has no effect. + * @param lineSeparator + * the line separator to use in formatted source, if set to + * null, then the platform default one will be + * used. * @return the text edit - * @throws IllegalArgumentException if offset is lower than 0, length is lower than 0 or - * length is greater than source length. + * @throws IllegalArgumentException + * if offset is lower than 0, length is lower than 0 or length + * is greater than source length. */ - public abstract TextEdit format(int kind, String source, int offset, int length, int indentationLevel, String lineSeparator); + public abstract TextEdit format(int kind, String source, int offset, + int length, int indentationLevel, String lineSeparator); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/formatter/DefaultCodeFormatterConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/formatter/DefaultCodeFormatterConstants.java index fcdd29c..6ab235d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/formatter/DefaultCodeFormatterConstants.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/formatter/DefaultCodeFormatterConstants.java @@ -10,11 +10,9 @@ *******************************************************************************/ package net.sourceforge.phpdt.core.formatter; -//import java.util.Map; +// import java.util.Map; import net.sourceforge.phpdt.core.JavaCore; -//import net.sourceforge.phpdt.internal.formatter.DefaultCodeFormatterOptions; -//import net.sourceforge.phpdt.internal.formatter.align.Alignment; /** * Constants used to set up the options of the code formatter. @@ -30,2235 +28,2833 @@ public class DefaultCodeFormatterConstants { /** *
          -	 * FORMATTER / Value to set a brace location at the end of a line.
          +	 *  FORMATTER / Value to set a brace location at the end of a line.
           	 * 
          + * * @see #FORMATTER_BRACE_POSITION_FOR_ANONYMOUS_TYPE_DECLARATION * @see #FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER * @see #FORMATTER_BRACE_POSITION_FOR_BLOCK * @see #FORMATTER_BRACE_POSITION_FOR_CONSTRUCTOR_DECLARATION - * @see #FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION - * @see #FORMATTER_BRACE_POSITION_FOR_SWITCH + * @see #FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION + * @see #FORMATTER_BRACE_POSITION_FOR_SWITCH * @see #FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION * @since 3.0 */ - public static final String END_OF_LINE = "end_of_line"; //$NON-NLS-1$ + public static final String END_OF_LINE = "end_of_line"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Value to set a brace location at the start of the next line with
          -	 *             the right indentation.
          +	 *  FORMATTER / Value to set a brace location at the start of the next line with
          +	 *              the right indentation.
           	 * 
          + * * @see #FORMATTER_BRACE_POSITION_FOR_ANONYMOUS_TYPE_DECLARATION * @see #FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER * @see #FORMATTER_BRACE_POSITION_FOR_BLOCK * @see #FORMATTER_BRACE_POSITION_FOR_CONSTRUCTOR_DECLARATION - * @see #FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION - * @see #FORMATTER_BRACE_POSITION_FOR_SWITCH + * @see #FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION + * @see #FORMATTER_BRACE_POSITION_FOR_SWITCH * @see #FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION * @since 3.0 */ public static final String NEXT_LINE = "next_line"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Value to set a brace location at the start of the next line with
          -	 *             an extra indentation.
          +	 *  FORMATTER / Value to set a brace location at the start of the next line with
          +	 *              an extra indentation.
           	 * 
          + * * @see #FORMATTER_BRACE_POSITION_FOR_ANONYMOUS_TYPE_DECLARATION * @see #FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER * @see #FORMATTER_BRACE_POSITION_FOR_BLOCK * @see #FORMATTER_BRACE_POSITION_FOR_CONSTRUCTOR_DECLARATION - * @see #FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION - * @see #FORMATTER_BRACE_POSITION_FOR_SWITCH + * @see #FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION + * @see #FORMATTER_BRACE_POSITION_FOR_SWITCH * @see #FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION * @since 3.0 */ - public static final String NEXT_LINE_SHIFTED = "next_line_shifted"; //$NON-NLS-1$ + public static final String NEXT_LINE_SHIFTED = "next_line_shifted"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Value to set a brace location at the start of the next line if a wrapping
          -	 *             occured.
          +	 *  FORMATTER / Value to set a brace location at the start of the next line if a wrapping
          +	 *              occured.
           	 * 
          + * * @see #FORMATTER_BRACE_POSITION_FOR_ANONYMOUS_TYPE_DECLARATION * @see #FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER * @see #FORMATTER_BRACE_POSITION_FOR_BLOCK * @see #FORMATTER_BRACE_POSITION_FOR_CONSTRUCTOR_DECLARATION - * @see #FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION - * @see #FORMATTER_BRACE_POSITION_FOR_SWITCH + * @see #FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION + * @see #FORMATTER_BRACE_POSITION_FOR_SWITCH * @see #FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION * @since 3.0 */ - public static final String NEXT_LINE_ON_WRAP = "next_line_on_wrap"; //$NON-NLS-1$ + public static final String NEXT_LINE_ON_WRAP = "next_line_on_wrap"; //$NON-NLS-1$ /** *
          -	 * FORMATTER / Value to set an option to true.
          +	 *  FORMATTER / Value to set an option to true.
           	 * 
          + * * @since 3.0 */ - public static final String FALSE = "false"; //$NON-NLS-1$ + public static final String FALSE = "false"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Value to set an option to false.
          +	 *  FORMATTER / Value to set an option to false.
           	 * 
          + * * @since 3.0 */ public static final String TRUE = "true"; //$NON-NLS-1$ /** *
          -	 * FORMATTER / Value to disable alignment.
          +	 *  FORMATTER / Value to disable alignment.
           	 * 
          + * * @since 3.0 */ - public static final int WRAP_NO_SPLIT= 0; + public static final int WRAP_NO_SPLIT = 0; + /** *
          -	 * FORMATTER / The wrapping is done using as few lines as possible.
          +	 *  FORMATTER / The wrapping is done using as few lines as possible.
           	 * 
          + * * @since 3.0 */ - public static final int WRAP_COMPACT= 1; + public static final int WRAP_COMPACT = 1; + /** *
          -	 * FORMATTER / The wrapping is done putting the first element on a new
          -	 *             line and then wrapping next elements using as few lines as possible.
          +	 *  FORMATTER / The wrapping is done putting the first element on a new
          +	 *              line and then wrapping next elements using as few lines as possible.
           	 * 
          + * * @since 3.0 */ - public static final int WRAP_COMPACT_FIRST_BREAK= 2; + public static final int WRAP_COMPACT_FIRST_BREAK = 2; + /** *
          -	 * FORMATTER / The wrapping is done by putting each element on its own line.
          +	 *  FORMATTER / The wrapping is done by putting each element on its own line.
           	 * 
          + * * @since 3.0 */ - public static final int WRAP_ONE_PER_LINE= 3; + public static final int WRAP_ONE_PER_LINE = 3; + /** *
          -	 * FORMATTER / The wrapping is done by putting each element on its own line.
          -	 *             All elements are indented by one except the first element.
          +	 *  FORMATTER / The wrapping is done by putting each element on its own line.
          +	 *              All elements are indented by one except the first element.
           	 * 
          + * * @since 3.0 */ - public static final int WRAP_NEXT_SHIFTED= 4; + public static final int WRAP_NEXT_SHIFTED = 4; + /** *
          -	 * FORMATTER / The wrapping is done by putting each element on its own line
          -	 *             except the first element.
          +	 *  FORMATTER / The wrapping is done by putting each element on its own line
          +	 *              except the first element.
           	 * 
          + * * @since 3.0 */ - public static final int WRAP_NEXT_PER_LINE= 5; - + public static final int WRAP_NEXT_PER_LINE = 5; + /** *
          -	 * FORMATTER / The wrapping is done by using the current indentation.
          +	 *  FORMATTER / The wrapping is done by using the current indentation.
           	 * 
          + * * @since 3.0 */ - public static final int INDENT_DEFAULT= 0; + public static final int INDENT_DEFAULT = 0; + /** *
          -	 * FORMATTER / The wrapping is done by indenting on column under the splitting location.
          +	 *  FORMATTER / The wrapping is done by indenting on column under the splitting location.
           	 * 
          + * * @since 3.0 */ public static final int INDENT_ON_COLUMN = 1; + /** *
          -	 * FORMATTER / The wrapping is done by indenting by one compare to the current indentation.
          +	 *  FORMATTER / The wrapping is done by indenting by one compare to the current indentation.
           	 * 
          + * * @since 3.0 */ - public static final int INDENT_BY_ONE= 2; - + public static final int INDENT_BY_ONE = 2; + /** *
          -	 * FORMATTER / Option for alignment of arguments in allocation expression
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_arguments_in_allocation_expression"
          -	 *     - possible values:   values returned by createAlignmentValue(boolean, int, int) call
          -	 *     - default:           createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
          +	 *  FORMATTER / Option for alignment of arguments in allocation expression
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_arguments_in_allocation_expression"
          +	 *      - possible values:   values returned by
          +	 * 
          +	 * createAlignmentValue(boolean, int, int)
          +	 * 
          +	 *  call
          +	 *      - default:           createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
           	 * 
          + * * @see #createAlignmentValue(boolean, int, int) * @since 3.0 */ - public static final String FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_ALLOCATION_EXPRESSION = JavaCore.PLUGIN_ID + ".formatter.alignment_for_arguments_in_allocation_expression"; //$NON-NLS-1$ + public static final String FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_ALLOCATION_EXPRESSION = JavaCore.PLUGIN_ID + + ".formatter.alignment_for_arguments_in_allocation_expression"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option for alignment of arguments in explicit constructor call
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call"
          -	 *     - possible values:   values returned by createAlignmentValue(boolean, int, int) call
          -	 *     - default:           createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
          +	 *  FORMATTER / Option for alignment of arguments in explicit constructor call
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call"
          +	 *      - possible values:   values returned by
          +	 * 
          +	 * createAlignmentValue(boolean, int, int)
          +	 * 
          +	 *  call
          +	 *      - default:           createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
           	 * 
          + * * @see #createAlignmentValue(boolean, int, int) * @since 3.0 */ - public static final String FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_EXPLICIT_CONSTRUCTOR_CALL = JavaCore.PLUGIN_ID + ".formatter.alignment_for_arguments_in_explicit_constructor_call"; //$NON-NLS-1$ + public static final String FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_EXPLICIT_CONSTRUCTOR_CALL = JavaCore.PLUGIN_ID + + ".formatter.alignment_for_arguments_in_explicit_constructor_call"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option for alignment of arguments in method invocation
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_arguments_in_method_invocation"
          -	 *     - possible values:   values returned by createAlignmentValue(boolean, int, int) call
          -	 *     - default:           createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
          +	 *  FORMATTER / Option for alignment of arguments in method invocation
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_arguments_in_method_invocation"
          +	 *      - possible values:   values returned by
          +	 * 
          +	 * createAlignmentValue(boolean, int, int)
          +	 * 
          +	 *  call
          +	 *      - default:           createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
           	 * 
          + * * @see #createAlignmentValue(boolean, int, int) * @since 3.0 */ - public static final String FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION = JavaCore.PLUGIN_ID + ".formatter.alignment_for_arguments_in_method_invocation"; //$NON-NLS-1$ + public static final String FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION = JavaCore.PLUGIN_ID + + ".formatter.alignment_for_arguments_in_method_invocation"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option for alignment of arguments in qualified allocation expression
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression"
          -	 *     - possible values:   values returned by createAlignmentValue(boolean, int, int) call
          -	 *     - default:           createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
          +	 *  FORMATTER / Option for alignment of arguments in qualified allocation expression
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression"
          +	 *      - possible values:   values returned by
          +	 * 
          +	 * createAlignmentValue(boolean, int, int)
          +	 * 
          +	 *  call
          +	 *      - default:           createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
           	 * 
          + * * @see #createAlignmentValue(boolean, int, int) * @since 3.0 */ - public static final String FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_QUALIFIED_ALLOCATION_EXPRESSION = JavaCore.PLUGIN_ID + ".formatter.alignment_for_arguments_in_qualified_allocation_expression"; //$NON-NLS-1$ + public static final String FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_QUALIFIED_ALLOCATION_EXPRESSION = JavaCore.PLUGIN_ID + + ".formatter.alignment_for_arguments_in_qualified_allocation_expression"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option for alignment of binary expression
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_binary_expression"
          -	 *     - possible values:   values returned by createAlignmentValue(boolean, int, int) call
          -	 *     - default:           createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
          +	 *  FORMATTER / Option for alignment of binary expression
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_binary_expression"
          +	 *      - possible values:   values returned by
          +	 * 
          +	 * createAlignmentValue(boolean, int, int)
          +	 * 
          +	 *  call
          +	 *      - default:           createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
           	 * 
          + * * @see #createAlignmentValue(boolean, int, int) * @since 3.0 */ - public static final String FORMATTER_ALIGNMENT_FOR_BINARY_EXPRESSION = JavaCore.PLUGIN_ID + ".formatter.alignment_for_binary_expression"; //$NON-NLS-1$ + public static final String FORMATTER_ALIGNMENT_FOR_BINARY_EXPRESSION = JavaCore.PLUGIN_ID + + ".formatter.alignment_for_binary_expression"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option for alignment of compact if
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_compact_if"
          -	 *     - possible values:   values returned by createAlignmentValue(boolean, int, int) call
          -	 *     - default:           createAlignmentValue(false, WRAP_ONE_PER_LINE, INDENT_BY_ONE)
          +	 *  FORMATTER / Option for alignment of compact if
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_compact_if"
          +	 *      - possible values:   values returned by
          +	 * 
          +	 * createAlignmentValue(boolean, int, int)
          +	 * 
          +	 *  call
          +	 *      - default:           createAlignmentValue(false, WRAP_ONE_PER_LINE, INDENT_BY_ONE)
           	 * 
          + * * @see #createAlignmentValue(boolean, int, int) * @since 3.0 */ - public static final String FORMATTER_ALIGNMENT_FOR_COMPACT_IF = JavaCore.PLUGIN_ID + ".formatter.alignment_for_compact_if"; //$NON-NLS-1$ + public static final String FORMATTER_ALIGNMENT_FOR_COMPACT_IF = JavaCore.PLUGIN_ID + + ".formatter.alignment_for_compact_if"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option for alignment of conditional expression
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_conditional_expression"
          -	 *     - possible values:   values returned by createAlignmentValue(boolean, int, int) call
          -	 *     - default:           createAlignmentValue(false, WRAP_ONE_PER_LINE, INDENT_DEFAULT)
          +	 *  FORMATTER / Option for alignment of conditional expression
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_conditional_expression"
          +	 *      - possible values:   values returned by
          +	 * 
          +	 * createAlignmentValue(boolean, int, int)
          +	 * 
          +	 *  call
          +	 *      - default:           createAlignmentValue(false, WRAP_ONE_PER_LINE, INDENT_DEFAULT)
           	 * 
          + * * @see #createAlignmentValue(boolean, int, int) * @since 3.0 */ - public static final String FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION = JavaCore.PLUGIN_ID + ".formatter.alignment_for_conditional_expression"; //$NON-NLS-1$ + public static final String FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION = JavaCore.PLUGIN_ID + + ".formatter.alignment_for_conditional_expression"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option for alignment of expressions in array initializer
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_expressions_in_array_initializer"
          -	 *     - possible values:   values returned by createAlignmentValue(boolean, int, int) call
          -	 *     - default:           createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
          +	 *  FORMATTER / Option for alignment of expressions in array initializer
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_expressions_in_array_initializer"
          +	 *      - possible values:   values returned by
          +	 * 
          +	 * createAlignmentValue(boolean, int, int)
          +	 * 
          +	 *  call
          +	 *      - default:           createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
           	 * 
          + * * @see #createAlignmentValue(boolean, int, int) * @since 3.0 */ - public static final String FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER = JavaCore.PLUGIN_ID + ".formatter.alignment_for_expressions_in_array_initializer"; //$NON-NLS-1$ + public static final String FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER = JavaCore.PLUGIN_ID + + ".formatter.alignment_for_expressions_in_array_initializer"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option for alignment of multiple fields
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_multiple_fields"
          -	 *     - possible values:   values returned by createAlignmentValue(boolean, int, int) call
          -	 *     - default:           createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
          +	 *  FORMATTER / Option for alignment of multiple fields
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_multiple_fields"
          +	 *      - possible values:   values returned by
          +	 * 
          +	 * createAlignmentValue(boolean, int, int)
          +	 * 
          +	 *  call
          +	 *      - default:           createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
           	 * 
          + * * @see #createAlignmentValue(boolean, int, int) * @since 3.0 */ - public static final String FORMATTER_ALIGNMENT_FOR_MULTIPLE_FIELDS = JavaCore.PLUGIN_ID + ".formatter.alignment_for_multiple_fields";//$NON-NLS-1$ + public static final String FORMATTER_ALIGNMENT_FOR_MULTIPLE_FIELDS = JavaCore.PLUGIN_ID + + ".formatter.alignment_for_multiple_fields";//$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option for alignment of parameters in constructor declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_parameters_in_constructor_declaration"
          -	 *     - possible values:   values returned by createAlignmentValue(boolean, int, int) call
          -	 *     - default:           createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
          +	 *  FORMATTER / Option for alignment of parameters in constructor declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_parameters_in_constructor_declaration"
          +	 *      - possible values:   values returned by
          +	 * 
          +	 * createAlignmentValue(boolean, int, int)
          +	 * 
          +	 *  call
          +	 *      - default:           createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
           	 * 
          + * * @see #createAlignmentValue(boolean, int, int) * @since 3.0 */ - public static final String FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_CONSTRUCTOR_DECLARATION = JavaCore.PLUGIN_ID + ".formatter.alignment_for_parameters_in_constructor_declaration"; //$NON-NLS-1$ + public static final String FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_CONSTRUCTOR_DECLARATION = JavaCore.PLUGIN_ID + + ".formatter.alignment_for_parameters_in_constructor_declaration"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option for alignment of parameters in method declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_parameters_in_method_declaration"
          -	 *     - possible values:   values returned by createAlignmentValue(boolean, int, int) call
          -	 *     - default:           createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
          +	 *  FORMATTER / Option for alignment of parameters in method declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_parameters_in_method_declaration"
          +	 *      - possible values:   values returned by
          +	 * 
          +	 * createAlignmentValue(boolean, int, int)
          +	 * 
          +	 *  call
          +	 *      - default:           createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
           	 * 
          + * * @see #createAlignmentValue(boolean, int, int) * @since 3.0 */ - public static final String FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION = JavaCore.PLUGIN_ID + ".formatter.alignment_for_parameters_in_method_declaration"; //$NON-NLS-1$ + public static final String FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION = JavaCore.PLUGIN_ID + + ".formatter.alignment_for_parameters_in_method_declaration"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option for alignment of selector in method invocation
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_selector_in_method_invocation"
          -	 *     - possible values:   values returned by createAlignmentValue(boolean, int, int) call
          -	 *     - default:           createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
          +	 *  FORMATTER / Option for alignment of selector in method invocation
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_selector_in_method_invocation"
          +	 *      - possible values:   values returned by
          +	 * 
          +	 * createAlignmentValue(boolean, int, int)
          +	 * 
          +	 *  call
          +	 *      - default:           createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
           	 * 
          + * * @see #createAlignmentValue(boolean, int, int) * @since 3.0 */ - public static final String FORMATTER_ALIGNMENT_FOR_SELECTOR_IN_METHOD_INVOCATION = JavaCore.PLUGIN_ID + ".formatter.alignment_for_selector_in_method_invocation"; //$NON-NLS-1$ + public static final String FORMATTER_ALIGNMENT_FOR_SELECTOR_IN_METHOD_INVOCATION = JavaCore.PLUGIN_ID + + ".formatter.alignment_for_selector_in_method_invocation"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option for alignment of superclass in type declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_superclass_in_type_declaration"
          -	 *     - possible values:   values returned by createAlignmentValue(boolean, int, int) call
          -	 *     - default:           createAlignmentValue(false, WRAP_NEXT_SHIFTED, INDENT_DEFAULT)
          +	 *  FORMATTER / Option for alignment of superclass in type declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_superclass_in_type_declaration"
          +	 *      - possible values:   values returned by
          +	 * 
          +	 * createAlignmentValue(boolean, int, int)
          +	 * 
          +	 *  call
          +	 *      - default:           createAlignmentValue(false, WRAP_NEXT_SHIFTED, INDENT_DEFAULT)
           	 * 
          + * * @see #createAlignmentValue(boolean, int, int) * @since 3.0 */ - public static final String FORMATTER_ALIGNMENT_FOR_SUPERCLASS_IN_TYPE_DECLARATION = JavaCore.PLUGIN_ID + ".formatter.alignment_for_superclass_in_type_declaration"; //$NON-NLS-1$ + public static final String FORMATTER_ALIGNMENT_FOR_SUPERCLASS_IN_TYPE_DECLARATION = JavaCore.PLUGIN_ID + + ".formatter.alignment_for_superclass_in_type_declaration"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option for alignment of superinterfaces in type declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_superinterfaces_in_type_declaration"
          -	 *     - possible values:   values returned by createAlignmentValue(boolean, int, int) call
          -	 *     - default:           createAlignmentValue(false, WRAP_NEXT_SHIFTED, INDENT_DEFAULT)
          +	 *  FORMATTER / Option for alignment of superinterfaces in type declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_superinterfaces_in_type_declaration"
          +	 *      - possible values:   values returned by
          +	 * 
          +	 * createAlignmentValue(boolean, int, int)
          +	 * 
          +	 *  call
          +	 *      - default:           createAlignmentValue(false, WRAP_NEXT_SHIFTED, INDENT_DEFAULT)
           	 * 
          + * * @see #createAlignmentValue(boolean, int, int) * @since 3.0 */ - public static final String FORMATTER_ALIGNMENT_FOR_SUPERINTERFACES_IN_TYPE_DECLARATION = JavaCore.PLUGIN_ID + ".formatter.alignment_for_superinterfaces_in_type_declaration"; //$NON-NLS-1$ + public static final String FORMATTER_ALIGNMENT_FOR_SUPERINTERFACES_IN_TYPE_DECLARATION = JavaCore.PLUGIN_ID + + ".formatter.alignment_for_superinterfaces_in_type_declaration"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option for alignment of throws clause in constructor declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration"
          -	 *     - possible values:   values returned by createAlignmentValue(boolean, int, int) call
          -	 *     - default:           createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
          +	 *  FORMATTER / Option for alignment of throws clause in constructor declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration"
          +	 *      - possible values:   values returned by
          +	 * 
          +	 * createAlignmentValue(boolean, int, int)
          +	 * 
          +	 *  call
          +	 *      - default:           createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
           	 * 
          + * * @see #createAlignmentValue(boolean, int, int) * @since 3.0 */ - public static final String FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_CONSTRUCTOR_DECLARATION = JavaCore.PLUGIN_ID + ".formatter.alignment_for_throws_clause_in_constructor_declaration"; //$NON-NLS-1$ + public static final String FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_CONSTRUCTOR_DECLARATION = JavaCore.PLUGIN_ID + + ".formatter.alignment_for_throws_clause_in_constructor_declaration"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option for alignment of throws clause in method declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_throws_clause_in_method_declaration"
          -	 *     - possible values:   values returned by createAlignmentValue(boolean, int, int) call
          -	 *     - default:           createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
          +	 *  FORMATTER / Option for alignment of throws clause in method declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_throws_clause_in_method_declaration"
          +	 *      - possible values:   values returned by
          +	 * 
          +	 * createAlignmentValue(boolean, int, int)
          +	 * 
          +	 *  call
          +	 *      - default:           createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
           	 * 
          + * * @see #createAlignmentValue(boolean, int, int) * @since 3.0 */ - public static final String FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_METHOD_DECLARATION = JavaCore.PLUGIN_ID + ".formatter.alignment_for_throws_clause_in_method_declaration"; //$NON-NLS-1$ - + public static final String FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_METHOD_DECLARATION = JavaCore.PLUGIN_ID + + ".formatter.alignment_for_throws_clause_in_method_declaration"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to align type members of a type declaration on column
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_throws_clause_in_method_declaration"
          -	 *     - possible values:   values returned by createAlignmentValue(boolean, int, int) call
          -	 *     - default:           createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
          +	 *  FORMATTER / Option to align type members of a type declaration on column
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.alignment_for_throws_clause_in_method_declaration"
          +	 *      - possible values:   values returned by
          +	 * 
          +	 * createAlignmentValue(boolean, int, int)
          +	 * 
          +	 *  call
          +	 *      - default:           createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
           	 * 
          + * * @see #createAlignmentValue(boolean, int, int) * @since 3.0 */ - public static final String FORMATTER_ALIGN_TYPE_MEMBERS_ON_COLUMNS = JavaCore.PLUGIN_ID + ".formatter.align_type_members_on_columns"; //$NON-NLS-1$ - + public static final String FORMATTER_ALIGN_TYPE_MEMBERS_ON_COLUMNS = JavaCore.PLUGIN_ID + + ".formatter.align_type_members_on_columns"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to position the braces of a anonymous type declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.brace_position_for_anonymous_type_declaration"
          -	 *     - possible values:   { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
          -	 *     - default:           END_OF_LINE
          +	 *  FORMATTER / Option to position the braces of a anonymous type declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.brace_position_for_anonymous_type_declaration"
          +	 *      - possible values:   { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
          +	 *      - default:           END_OF_LINE
           	 * 
          + * * @see #END_OF_LINE * @see #NEXT_LINE * @see #NEXT_LINE_SHIFTED * @see #NEXT_LINE_ON_WRAP * @since 3.0 */ - public static final String FORMATTER_BRACE_POSITION_FOR_ANONYMOUS_TYPE_DECLARATION = JavaCore.PLUGIN_ID + ".formatter.brace_position_for_anonymous_type_declaration"; //$NON-NLS-1$ + public static final String FORMATTER_BRACE_POSITION_FOR_ANONYMOUS_TYPE_DECLARATION = JavaCore.PLUGIN_ID + + ".formatter.brace_position_for_anonymous_type_declaration"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to position the braces of an array initializer
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.brace_position_for_array_initializer"
          -	 *     - possible values:   { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
          -	 *     - default:           END_OF_LINE
          +	 *  FORMATTER / Option to position the braces of an array initializer
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.brace_position_for_array_initializer"
          +	 *      - possible values:   { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
          +	 *      - default:           END_OF_LINE
           	 * 
          + * * @see #END_OF_LINE * @see #NEXT_LINE * @see #NEXT_LINE_SHIFTED * @see #NEXT_LINE_ON_WRAP * @since 3.0 */ - public static final String FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER = JavaCore.PLUGIN_ID + ".formatter.brace_position_for_array_initializer"; //$NON-NLS-1$ + public static final String FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER = JavaCore.PLUGIN_ID + + ".formatter.brace_position_for_array_initializer"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to position the braces of a block
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.brace_position_for_block"
          -	 *     - possible values:   { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
          -	 *     - default:           END_OF_LINE
          +	 *  FORMATTER / Option to position the braces of a block
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.brace_position_for_block"
          +	 *      - possible values:   { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
          +	 *      - default:           END_OF_LINE
           	 * 
          + * * @see #END_OF_LINE * @see #NEXT_LINE * @see #NEXT_LINE_SHIFTED * @see #NEXT_LINE_ON_WRAP * @since 3.0 */ - public static final String FORMATTER_BRACE_POSITION_FOR_BLOCK = JavaCore.PLUGIN_ID + ".formatter.brace_position_for_block"; //$NON-NLS-1$ + public static final String FORMATTER_BRACE_POSITION_FOR_BLOCK = JavaCore.PLUGIN_ID + + ".formatter.brace_position_for_block"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to position the braces of a block in a case statement when the block is the first statement following
          -	 *             the case
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.brace_position_for_block_in_case"
          -	 *     - possible values:   { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
          -	 *     - default:           END_OF_LINE
          +	 *  FORMATTER / Option to position the braces of a block in a case statement when the block is the first statement following
          +	 *              the case
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.brace_position_for_block_in_case"
          +	 *      - possible values:   { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
          +	 *      - default:           END_OF_LINE
           	 * 
          + * * @see #END_OF_LINE * @see #NEXT_LINE * @see #NEXT_LINE_SHIFTED * @see #NEXT_LINE_ON_WRAP * @since 3.0 */ - public static final String FORMATTER_BRACE_POSITION_FOR_BLOCK_IN_CASE = JavaCore.PLUGIN_ID + ".formatter.brace_position_for_block_in_case"; //$NON-NLS-1$ + public static final String FORMATTER_BRACE_POSITION_FOR_BLOCK_IN_CASE = JavaCore.PLUGIN_ID + + ".formatter.brace_position_for_block_in_case"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to position the braces of a constructor declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.brace_position_for_constructor_declaration"
          -	 *     - possible values:   { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
          -	 *     - default:           END_OF_LINE
          +	 *  FORMATTER / Option to position the braces of a constructor declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.brace_position_for_constructor_declaration"
          +	 *      - possible values:   { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
          +	 *      - default:           END_OF_LINE
           	 * 
          + * * @see #END_OF_LINE * @see #NEXT_LINE * @see #NEXT_LINE_SHIFTED * @see #NEXT_LINE_ON_WRAP * @since 3.0 */ - public static final String FORMATTER_BRACE_POSITION_FOR_CONSTRUCTOR_DECLARATION = JavaCore.PLUGIN_ID + ".formatter.brace_position_for_constructor_declaration"; //$NON-NLS-1$ + public static final String FORMATTER_BRACE_POSITION_FOR_CONSTRUCTOR_DECLARATION = JavaCore.PLUGIN_ID + + ".formatter.brace_position_for_constructor_declaration"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to position the braces of a method declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.brace_position_for_method_declaration"
          -	 *     - possible values:   { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
          -	 *     - default:           END_OF_LINE
          +	 *  FORMATTER / Option to position the braces of a method declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.brace_position_for_method_declaration"
          +	 *      - possible values:   { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
          +	 *      - default:           END_OF_LINE
           	 * 
          + * * @see #END_OF_LINE * @see #NEXT_LINE * @see #NEXT_LINE_SHIFTED * @see #NEXT_LINE_ON_WRAP * @since 3.0 */ - public static final String FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION = JavaCore.PLUGIN_ID + ".formatter.brace_position_for_method_declaration"; //$NON-NLS-1$ + public static final String FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION = JavaCore.PLUGIN_ID + + ".formatter.brace_position_for_method_declaration"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to position the braces of a type declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.brace_position_for_type_declaration"
          -	 *     - possible values:   { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
          -	 *     - default:           END_OF_LINE
          +	 *  FORMATTER / Option to position the braces of a type declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.brace_position_for_type_declaration"
          +	 *      - possible values:   { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
          +	 *      - default:           END_OF_LINE
           	 * 
          + * * @see #END_OF_LINE * @see #NEXT_LINE * @see #NEXT_LINE_SHIFTED * @see #NEXT_LINE_ON_WRAP * @since 3.0 */ - public static final String FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION = JavaCore.PLUGIN_ID + ".formatter.brace_position_for_type_declaration"; //$NON-NLS-1$ + public static final String FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION = JavaCore.PLUGIN_ID + + ".formatter.brace_position_for_type_declaration"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to position the braces of a switch statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.brace_position_for_switch"
          -	 *     - possible values:   { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
          -	 *     - default:           END_OF_LINE
          +	 *  FORMATTER / Option to position the braces of a switch statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.brace_position_for_switch"
          +	 *      - possible values:   { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
          +	 *      - default:           END_OF_LINE
           	 * 
          + * * @see #END_OF_LINE * @see #NEXT_LINE * @see #NEXT_LINE_SHIFTED * @see #NEXT_LINE_ON_WRAP * @since 3.0 */ - public static final String FORMATTER_BRACE_POSITION_FOR_SWITCH = JavaCore.PLUGIN_ID + ".formatter.brace_position_for_switch"; //$NON-NLS-1$ + public static final String FORMATTER_BRACE_POSITION_FOR_SWITCH = JavaCore.PLUGIN_ID + + ".formatter.brace_position_for_switch"; //$NON-NLS-1$ /** *
          -	 * FORMATTER / Option to set the continuation indentation
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.continuation_indentation"
          -	 *     - possible values:   "<n>", where n is zero or a positive integer
          -	 *     - default:           "2"
          +	 *  FORMATTER / Option to set the continuation indentation
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.continuation_indentation"
          +	 *      - possible values:   "<n>", where n is zero or a positive integer
          +	 *      - default:           "2"
           	 * 
          + * * @since 3.0 */ - public static final String FORMATTER_CONTINUATION_INDENTATION = JavaCore.PLUGIN_ID + ".formatter.continuation_indentation"; //$NON-NLS-1$ + public static final String FORMATTER_CONTINUATION_INDENTATION = JavaCore.PLUGIN_ID + + ".formatter.continuation_indentation"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to set the continuation indentation inside array initializer
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.continuation_indentation_for_array_initializer"
          -	 *     - possible values:   "<n>", where n is zero or a positive integer
          -	 *     - default:           "2"
          +	 *  FORMATTER / Option to set the continuation indentation inside array initializer
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.continuation_indentation_for_array_initializer"
          +	 *      - possible values:   "<n>", where n is zero or a positive integer
          +	 *      - default:           "2"
           	 * 
          + * * @since 3.0 */ - public static final String FORMATTER_CONTINUATION_INDENTATION_FOR_ARRAY_INITIALIZER = JavaCore.PLUGIN_ID + ".formatter.continuation_indentation_for_array_initializer"; //$NON-NLS-1$ + public static final String FORMATTER_CONTINUATION_INDENTATION_FOR_ARRAY_INITIALIZER = JavaCore.PLUGIN_ID + + ".formatter.continuation_indentation_for_array_initializer"; //$NON-NLS-1$ /** *
          -	 * FORMATTER / Option to add blank lines after the imports declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.blank_lines_after_imports"
          -	 *     - possible values:   "<n>", where n is zero or a positive integer
          -	 *     - default:           "0"
          +	 *  FORMATTER / Option to add blank lines after the imports declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.blank_lines_after_imports"
          +	 *      - possible values:   "<n>", where n is zero or a positive integer
          +	 *      - default:           "0"
           	 * 
          + * * @since 3.0 */ - public static final String FORMATTER_BLANK_LINES_AFTER_IMPORTS = JavaCore.PLUGIN_ID + ".formatter.blank_lines_after_imports"; //$NON-NLS-1$ + public static final String FORMATTER_BLANK_LINES_AFTER_IMPORTS = JavaCore.PLUGIN_ID + + ".formatter.blank_lines_after_imports"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to add blank lines after the package declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.blank_lines_after_package"
          -	 *     - possible values:   "<n>", where n is zero or a positive integer
          -	 *     - default:           "0"
          +	 *  FORMATTER / Option to add blank lines after the package declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.blank_lines_after_package"
          +	 *      - possible values:   "<n>", where n is zero or a positive integer
          +	 *      - default:           "0"
           	 * 
          + * * @since 3.0 */ - public static final String FORMATTER_BLANK_LINES_AFTER_PACKAGE = JavaCore.PLUGIN_ID + ".formatter.blank_lines_after_package"; //$NON-NLS-1$ + public static final String FORMATTER_BLANK_LINES_AFTER_PACKAGE = JavaCore.PLUGIN_ID + + ".formatter.blank_lines_after_package"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to add blank lines before a field declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.blank_lines_before_field"
          -	 *     - possible values:   "<n>", where n is zero or a positive integer
          -	 *     - default:           "0"
          +	 *  FORMATTER / Option to add blank lines before a field declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.blank_lines_before_field"
          +	 *      - possible values:   "<n>", where n is zero or a positive integer
          +	 *      - default:           "0"
           	 * 
          + * * @since 3.0 */ - public static final String FORMATTER_BLANK_LINES_BEFORE_FIELD = JavaCore.PLUGIN_ID + ".formatter.blank_lines_before_field"; //$NON-NLS-1$ + public static final String FORMATTER_BLANK_LINES_BEFORE_FIELD = JavaCore.PLUGIN_ID + + ".formatter.blank_lines_before_field"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to add blank lines before the first class body declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.blank_lines_before_first_class_body_declaration"
          -	 *     - possible values:   "<n>", where n is zero or a positive integer
          -	 *     - default:           "0"
          +	 *  FORMATTER / Option to add blank lines before the first class body declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.blank_lines_before_first_class_body_declaration"
          +	 *      - possible values:   "<n>", where n is zero or a positive integer
          +	 *      - default:           "0"
           	 * 
          + * * @since 3.0 */ - public static final String FORMATTER_BLANK_LINES_BEFORE_FIRST_CLASS_BODY_DECLARATION = JavaCore.PLUGIN_ID + ".formatter.blank_lines_before_first_class_body_declaration"; //$NON-NLS-1$ + public static final String FORMATTER_BLANK_LINES_BEFORE_FIRST_CLASS_BODY_DECLARATION = JavaCore.PLUGIN_ID + + ".formatter.blank_lines_before_first_class_body_declaration"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to add blank lines before the imports declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.blank_lines_before_imports"
          -	 *     - possible values:   "<n>", where n is zero or a positive integer
          -	 *     - default:           "0"
          +	 *  FORMATTER / Option to add blank lines before the imports declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.blank_lines_before_imports"
          +	 *      - possible values:   "<n>", where n is zero or a positive integer
          +	 *      - default:           "0"
           	 * 
          + * * @since 3.0 */ - public static final String FORMATTER_BLANK_LINES_BEFORE_IMPORTS = JavaCore.PLUGIN_ID + ".formatter.blank_lines_before_imports"; //$NON-NLS-1$ + public static final String FORMATTER_BLANK_LINES_BEFORE_IMPORTS = JavaCore.PLUGIN_ID + + ".formatter.blank_lines_before_imports"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to add blank lines before a member type declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.blank_lines_before_member_type"
          -	 *     - possible values:   "<n>", where n is zero or a positive integer
          -	 *     - default:           "0"
          +	 *  FORMATTER / Option to add blank lines before a member type declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.blank_lines_before_member_type"
          +	 *      - possible values:   "<n>", where n is zero or a positive integer
          +	 *      - default:           "0"
           	 * 
          + * * @since 3.0 */ - public static final String FORMATTER_BLANK_LINES_BEFORE_MEMBER_TYPE = JavaCore.PLUGIN_ID + ".formatter.blank_lines_before_member_type"; //$NON-NLS-1$ + public static final String FORMATTER_BLANK_LINES_BEFORE_MEMBER_TYPE = JavaCore.PLUGIN_ID + + ".formatter.blank_lines_before_member_type"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to add blank lines before a method declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.blank_lines_before_method"
          -	 *     - possible values:   "<n>", where n is zero or a positive integer
          -	 *     - default:           "0"
          +	 *  FORMATTER / Option to add blank lines before a method declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.blank_lines_before_method"
          +	 *      - possible values:   "<n>", where n is zero or a positive integer
          +	 *      - default:           "0"
           	 * 
          + * * @since 3.0 */ - public static final String FORMATTER_BLANK_LINES_BEFORE_METHOD = JavaCore.PLUGIN_ID + ".formatter.blank_lines_before_method"; //$NON-NLS-1$ + public static final String FORMATTER_BLANK_LINES_BEFORE_METHOD = JavaCore.PLUGIN_ID + + ".formatter.blank_lines_before_method"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to add blank lines before a new chunk
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.blank_lines_before_new_chunk"
          -	 *     - possible values:   "<n>", where n is zero or a positive integer
          -	 *     - default:           "0"
          +	 *  FORMATTER / Option to add blank lines before a new chunk
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.blank_lines_before_new_chunk"
          +	 *      - possible values:   "<n>", where n is zero or a positive integer
          +	 *      - default:           "0"
           	 * 
          + * * @since 3.0 */ - public static final String FORMATTER_BLANK_LINES_BEFORE_NEW_CHUNK = JavaCore.PLUGIN_ID + ".formatter.blank_lines_before_new_chunk"; //$NON-NLS-1$ + public static final String FORMATTER_BLANK_LINES_BEFORE_NEW_CHUNK = JavaCore.PLUGIN_ID + + ".formatter.blank_lines_before_new_chunk"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to add blank lines before the package declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.blank_lines_before_package"
          -	 *     - possible values:   "<n>", where n is zero or a positive integer
          -	 *     - default:           "0"
          +	 *  FORMATTER / Option to add blank lines before the package declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.blank_lines_before_package"
          +	 *      - possible values:   "<n>", where n is zero or a positive integer
          +	 *      - default:           "0"
           	 * 
          + * * @since 3.0 */ - public static final String FORMATTER_BLANK_LINES_BEFORE_PACKAGE = JavaCore.PLUGIN_ID + ".formatter.blank_lines_before_package"; //$NON-NLS-1$ + public static final String FORMATTER_BLANK_LINES_BEFORE_PACKAGE = JavaCore.PLUGIN_ID + + ".formatter.blank_lines_before_package"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to add blank lines between type declarations
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.blank_lines_between_type_declarations"
          -	 *     - possible values:   "<n>", where n is zero or a positive integer
          -	 *     - default:           "0"
          +	 *  FORMATTER / Option to add blank lines between type declarations
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.blank_lines_between_type_declarations"
          +	 *      - possible values:   "<n>", where n is zero or a positive integer
          +	 *      - default:           "0"
           	 * 
          + * * @since 3.0 */ - public static final String FORMATTER_BLANK_LINES_BETWEEN_TYPE_DECLARATIONS = JavaCore.PLUGIN_ID + ".formatter.blank_lines_between_type_declarations"; //$NON-NLS-1$ + public static final String FORMATTER_BLANK_LINES_BETWEEN_TYPE_DECLARATIONS = JavaCore.PLUGIN_ID + + ".formatter.blank_lines_between_type_declarations"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to add blank lines at the beginning of the method body
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body"
          -	 *     - possible values:   "<n>", where n is zero or a positive integer
          -	 *     - default:           "0"
          +	 *  FORMATTER / Option to add blank lines at the beginning of the method body
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body"
          +	 *      - possible values:   "<n>", where n is zero or a positive integer
          +	 *      - default:           "0"
           	 * 
          + * * @since 3.0 */ - public static final String FORMATTER_BLANK_LINES_AT_BEGINNING_OF_METHOD_BODY = JavaCore.PLUGIN_ID + ".formatter.number_of_blank_lines_at_beginning_of_method_body"; //$NON-NLS-1$ + public static final String FORMATTER_BLANK_LINES_AT_BEGINNING_OF_METHOD_BODY = JavaCore.PLUGIN_ID + + ".formatter.number_of_blank_lines_at_beginning_of_method_body"; //$NON-NLS-1$ /** *
          -	 * FORMATTER / Option to indent body declarations compare to its enclosing type header
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.indent_body_declarations_compare_to_type_header"
          -	 *     - possible values:   { TRUE, FALSE }
          -	 *     - default:           TRUE
          +	 *  FORMATTER / Option to indent body declarations compare to its enclosing type header
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.indent_body_declarations_compare_to_type_header"
          +	 *      - possible values:   { TRUE, FALSE }
          +	 *      - default:           TRUE
           	 * 
          + * * @see #TRUE * @see #FALSE * @since 3.0 */ - public static final String FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_TYPE_HEADER = JavaCore.PLUGIN_ID + ".formatter.indent_body_declarations_compare_to_type_header"; //$NON-NLS-1$ + public static final String FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_TYPE_HEADER = JavaCore.PLUGIN_ID + + ".formatter.indent_body_declarations_compare_to_type_header"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to indent breaks compare to cases
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.indent_breaks_compare_to_cases"
          -	 *     - possible values:   { TRUE, FALSE }
          -	 *     - default:           TRUE
          +	 *  FORMATTER / Option to indent breaks compare to cases
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.indent_breaks_compare_to_cases"
          +	 *      - possible values:   { TRUE, FALSE }
          +	 *      - default:           TRUE
           	 * 
          + * * @see #TRUE * @see #FALSE * @since 3.0 */ - public static final String FORMATTER_INDENT_BREAKS_COMPARE_TO_CASES = JavaCore.PLUGIN_ID + ".formatter.indent_breaks_compare_to_cases"; //$NON-NLS-1$ + public static final String FORMATTER_INDENT_BREAKS_COMPARE_TO_CASES = JavaCore.PLUGIN_ID + + ".formatter.indent_breaks_compare_to_cases"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to indent statements inside a block
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.indent_statements_compare_to_block"
          -	 *     - possible values:   { TRUE, FALSE }
          -	 *     - default:           TRUE
          +	 *  FORMATTER / Option to indent statements inside a block
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.indent_statements_compare_to_block"
          +	 *      - possible values:   { TRUE, FALSE }
          +	 *      - default:           TRUE
           	 * 
          + * * @see #TRUE * @see #FALSE * @since 3.0 */ - public static final String FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BLOCK = JavaCore.PLUGIN_ID + ".formatter.indent_statements_compare_to_block"; //$NON-NLS-1$ + public static final String FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BLOCK = JavaCore.PLUGIN_ID + + ".formatter.indent_statements_compare_to_block"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to indent statements inside the body of a method or a constructor
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.indent_statements_compare_to_body"
          -	 *     - possible values:   { TRUE, FALSE }
          -	 *     - default:           TRUE
          +	 *  FORMATTER / Option to indent statements inside the body of a method or a constructor
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.indent_statements_compare_to_body"
          +	 *      - possible values:   { TRUE, FALSE }
          +	 *      - default:           TRUE
           	 * 
          + * * @see #TRUE * @see #FALSE * @since 3.0 */ - public static final String FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BODY = JavaCore.PLUGIN_ID + ".formatter.indent_statements_compare_to_body"; //$NON-NLS-1$ + public static final String FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BODY = JavaCore.PLUGIN_ID + + ".formatter.indent_statements_compare_to_body"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to indent switch statements compare to cases
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.indent_switchstatements_compare_to_cases"
          -	 *     - possible values:   { TRUE, FALSE }
          -	 *     - default:           TRUE
          +	 *  FORMATTER / Option to indent switch statements compare to cases
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.indent_switchstatements_compare_to_cases"
          +	 *      - possible values:   { TRUE, FALSE }
          +	 *      - default:           TRUE
           	 * 
          + * * @see #TRUE * @see #FALSE * @since 3.0 */ - public static final String FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES = JavaCore.PLUGIN_ID + ".formatter.indent_switchstatements_compare_to_cases"; //$NON-NLS-1$ + public static final String FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES = JavaCore.PLUGIN_ID + + ".formatter.indent_switchstatements_compare_to_cases"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to indent switch statements compare to switch
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.indent_switchstatements_compare_to_switch"
          -	 *     - possible values:   { TRUE, FALSE }
          -	 *     - default:           TRUE
          +	 *  FORMATTER / Option to indent switch statements compare to switch
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.indent_switchstatements_compare_to_switch"
          +	 *      - possible values:   { TRUE, FALSE }
          +	 *      - default:           TRUE
           	 * 
          + * * @see #TRUE * @see #FALSE * @since 3.0 */ - public static final String FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH = JavaCore.PLUGIN_ID + ".formatter.indent_switchstatements_compare_to_switch"; //$NON-NLS-1$ + public static final String FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH = JavaCore.PLUGIN_ID + + ".formatter.indent_switchstatements_compare_to_switch"; //$NON-NLS-1$ /** *
          -	 * FORMATTER / Option to insert a new line after the opening brace in an array initializer
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a new line after the opening brace in an array initializer
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_NEW_LINE_AFTER_OPENING_BRACE_IN_ARRAY_INITIALIZER = JavaCore.PLUGIN_ID + ".formatter.insert_new_line_after_opening_brace_in_array_initializer";//$NON-NLS-1$ + public static final String FORMATTER_INSERT_NEW_LINE_AFTER_OPENING_BRACE_IN_ARRAY_INITIALIZER = JavaCore.PLUGIN_ID + + ".formatter.insert_new_line_after_opening_brace_in_array_initializer";//$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a new line before the catch keyword in try statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_new_line_before_catch_in_try_statement"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a new line before the catch keyword in try statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_new_line_before_catch_in_try_statement"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_NEW_LINE_BEFORE_CATCH_IN_TRY_STATEMENT = JavaCore.PLUGIN_ID + ".formatter.insert_new_line_before_catch_in_try_statement"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_NEW_LINE_BEFORE_CATCH_IN_TRY_STATEMENT = JavaCore.PLUGIN_ID + + ".formatter.insert_new_line_before_catch_in_try_statement"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a new line before the closing brace in an array initializer
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a new line before the closing brace in an array initializer
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_NEW_LINE_BEFORE_CLOSING_BRACE_IN_ARRAY_INITIALIZER = JavaCore.PLUGIN_ID + ".formatter.insert_new_line_before_closing_brace_in_array_initializer";//$NON-NLS-1$ + public static final String FORMATTER_INSERT_NEW_LINE_BEFORE_CLOSING_BRACE_IN_ARRAY_INITIALIZER = JavaCore.PLUGIN_ID + + ".formatter.insert_new_line_before_closing_brace_in_array_initializer";//$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a new line before the else keyword in if statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_new_line_before_else_in_if_statement"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a new line before the else keyword in if statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_new_line_before_else_in_if_statement"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_NEW_LINE_BEFORE_ELSE_IN_IF_STATEMENT = JavaCore.PLUGIN_ID + ".formatter.insert_new_line_before_else_in_if_statement"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_NEW_LINE_BEFORE_ELSE_IN_IF_STATEMENT = JavaCore.PLUGIN_ID + + ".formatter.insert_new_line_before_else_in_if_statement"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a new line before the finally keyword in try statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_new_line_before_finally_in_try_statement"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a new line before the finally keyword in try statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_new_line_before_finally_in_try_statement"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_NEW_LINE_BEFORE_FINALLY_IN_TRY_STATEMENT = JavaCore.PLUGIN_ID + ".formatter.insert_new_line_before_finally_in_try_statement"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_NEW_LINE_BEFORE_FINALLY_IN_TRY_STATEMENT = JavaCore.PLUGIN_ID + + ".formatter.insert_new_line_before_finally_in_try_statement"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a new line before while in do statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_new_line_before_while_in_do_statement"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a new line before while in do statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_new_line_before_while_in_do_statement"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_NEW_LINE_BEFORE_WHILE_IN_DO_STATEMENT = JavaCore.PLUGIN_ID + ".formatter.insert_new_line_before_while_in_do_statement"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_NEW_LINE_BEFORE_WHILE_IN_DO_STATEMENT = JavaCore.PLUGIN_ID + + ".formatter.insert_new_line_before_while_in_do_statement"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a new line in an empty anonymous type declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a new line in an empty anonymous type declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_NEW_LINE_IN_EMPTY_ANONYMOUS_TYPE_DECLARATION = JavaCore.PLUGIN_ID + ".formatter.insert_new_line_in_empty_anonymous_type_declaration"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_NEW_LINE_IN_EMPTY_ANONYMOUS_TYPE_DECLARATION = JavaCore.PLUGIN_ID + + ".formatter.insert_new_line_in_empty_anonymous_type_declaration"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a new line in an empty block
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_new_line_in_empty_block"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a new line in an empty block
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_new_line_in_empty_block"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_NEW_LINE_IN_EMPTY_BLOCK = JavaCore.PLUGIN_ID + ".formatter.insert_new_line_in_empty_block"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_NEW_LINE_IN_EMPTY_BLOCK = JavaCore.PLUGIN_ID + + ".formatter.insert_new_line_in_empty_block"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a new line in an empty method body
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_new_line_in_empty_method_body"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a new line in an empty method body
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_new_line_in_empty_method_body"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_NEW_LINE_IN_EMPTY_METHOD_BODY = JavaCore.PLUGIN_ID + ".formatter.insert_new_line_in_empty_method_body"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_NEW_LINE_IN_EMPTY_METHOD_BODY = JavaCore.PLUGIN_ID + + ".formatter.insert_new_line_in_empty_method_body"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a new line in an empty type declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_new_line_in_empty_type_declaration"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a new line in an empty type declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_new_line_in_empty_type_declaration"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_NEW_LINE_IN_EMPTY_TYPE_DECLARATION = JavaCore.PLUGIN_ID + ".formatter.insert_new_line_in_empty_type_declaration"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_NEW_LINE_IN_EMPTY_TYPE_DECLARATION = JavaCore.PLUGIN_ID + + ".formatter.insert_new_line_in_empty_type_declaration"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after an assignment operator
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_assignment_operator"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space after an assignment operator
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_assignment_operator"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_ASSIGNMENT_OPERATOR = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_assignment_operator"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_ASSIGNMENT_OPERATOR = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_assignment_operator"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after a binary operator
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_binary_operator"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space after a binary operator
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_binary_operator"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_BINARY_OPERATOR = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_binary_operator"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_BINARY_OPERATOR = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_binary_operator"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the closing parenthesis of a cast expression
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_closing_paren_in_cast"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space after the closing parenthesis of a cast expression
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_closing_paren_in_cast"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_CLOSING_PAREN_IN_CAST = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_closing_paren_in_cast"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_CLOSING_PAREN_IN_CAST = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_closing_paren_in_cast"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the closing brace of a block
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_closing_brace_in_block"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space after the closing brace of a block
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_closing_brace_in_block"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_CLOSING_BRACE_IN_BLOCK = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_closing_brace_in_block"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_CLOSING_BRACE_IN_BLOCK = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_closing_brace_in_block"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the colon in an assert statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_colon_in_assert"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space after the colon in an assert statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_colon_in_assert"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_COLON_IN_ASSERT = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_colon_in_assert"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_COLON_IN_ASSERT = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_colon_in_assert"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after colon in a case statement when a opening brace follows the colon
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_colon_in_case"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space after colon in a case statement when a opening brace follows the colon
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_colon_in_case"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_COLON_IN_CASE = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_colon_in_case"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_COLON_IN_CASE = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_colon_in_case"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the colon in a conditional expression
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_colon_in_conditional"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space after the colon in a conditional expression
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_colon_in_conditional"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_COLON_IN_CONDITIONAL = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_colon_in_conditional"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_COLON_IN_CONDITIONAL = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_colon_in_conditional"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the colon in a labeled statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_colon_in_labeled_statement"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space after the colon in a labeled statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_colon_in_labeled_statement"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_COLON_IN_LABELED_STATEMENT = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_colon_in_labeled_statement"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_COLON_IN_LABELED_STATEMENT = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_colon_in_labeled_statement"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the comma in an allocation expression
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_comma_in_allocation_expression"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space after the comma in an allocation expression
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_comma_in_allocation_expression"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ALLOCATION_EXPRESSION = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_allocation_expression"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ALLOCATION_EXPRESSION = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_comma_in_allocation_expression"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the comma in an array initializer
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_comma_in_array_initializer"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space after the comma in an array initializer
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_comma_in_array_initializer"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ARRAY_INITIALIZER = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_array_initializer"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_ARRAY_INITIALIZER = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_comma_in_array_initializer"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the comma in the parameters of a constructor declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space after the comma in the parameters of a constructor declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_CONSTRUCTOR_DECLARATION_PARAMETERS = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_constructor_declaration_parameters"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_CONSTRUCTOR_DECLARATION_PARAMETERS = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_comma_in_constructor_declaration_parameters"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the comma in the exception names in a throws clause of a constructor declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space after the comma in the exception names in a throws clause of a constructor declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_CONSTRUCTOR_DECLARATION_THROWS = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_constructor_declaration_throws"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_CONSTRUCTOR_DECLARATION_THROWS = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_comma_in_constructor_declaration_throws"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the comma in the arguments of an explicit constructor call
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space after the comma in the arguments of an explicit constructor call
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_EXPLICIT_CONSTRUCTOR_CALL_ARGUMENTS = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_explicitconstructorcall_arguments"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_EXPLICIT_CONSTRUCTOR_CALL_ARGUMENTS = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_comma_in_explicitconstructorcall_arguments"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the comma in the increments of a for statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_comma_in_for_increments"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space after the comma in the increments of a for statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_comma_in_for_increments"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_FOR_INCREMENTS = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_for_increments"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_FOR_INCREMENTS = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_comma_in_for_increments"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the comma in the initializations of a for statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_comma_in_for_inits"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space after the comma in the initializations of a for statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_comma_in_for_inits"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_FOR_INITS = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_for_inits"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_FOR_INITS = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_comma_in_for_inits"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the comma in the arguments of a method invocation
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space after the comma in the arguments of a method invocation
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_INVOCATION_ARGUMENTS = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_method_invocation_arguments"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_INVOCATION_ARGUMENTS = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_comma_in_method_invocation_arguments"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the comma in the parameters of a method declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space after the comma in the parameters of a method declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_DECLARATION_PARAMETERS = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_method_declaration_parameters"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_DECLARATION_PARAMETERS = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_comma_in_method_declaration_parameters"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the comma in the exception names in a throws clause of a method declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_comma_in_method_declaration_throws"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space after the comma in the exception names in a throws clause of a method declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_comma_in_method_declaration_throws"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_DECLARATION_THROWS = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_method_declaration_throws"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_METHOD_DECLARATION_THROWS = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_comma_in_method_declaration_throws"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the comma in multiple field declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space after the comma in multiple field declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_MULTIPLE_FIELD_DECLARATIONS = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_multiple_field_declarations"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_MULTIPLE_FIELD_DECLARATIONS = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_comma_in_multiple_field_declarations"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the comma in multiple local declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space after the comma in multiple local declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_MULTIPLE_LOCAL_DECLARATIONS = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_multiple_local_declarations"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_MULTIPLE_LOCAL_DECLARATIONS = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_comma_in_multiple_local_declarations"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the comma in superinterfaces names of a type header
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_comma_in_superinterfaces"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space after the comma in superinterfaces names of a type header
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_comma_in_superinterfaces"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_SUPERINTERFACES = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_comma_in_superinterfaces"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_COMMA_IN_SUPERINTERFACES = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_comma_in_superinterfaces"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the opening bracket inside an array allocation expression
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space after the opening bracket inside an array allocation expression
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_BRACKET_IN_ARRAY_ALLOCATION_EXPRESSION = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_opening_bracket_in_array_allocation_expression";//$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_BRACKET_IN_ARRAY_ALLOCATION_EXPRESSION = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_opening_bracket_in_array_allocation_expression";//$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the opening bracket inside an array reference
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_bracket_in_array_reference"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space after the opening bracket inside an array reference
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_bracket_in_array_reference"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_BRACKET_IN_ARRAY_REFERENCE = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_opening_bracket_in_array_reference";//$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_BRACKET_IN_ARRAY_REFERENCE = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_opening_bracket_in_array_reference";//$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the opening brace in an array initializer
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_brace_in_array_initializer"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space after the opening brace in an array initializer
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_brace_in_array_initializer"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_BRACE_IN_ARRAY_INITIALIZER = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_opening_brace_in_array_initializer"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_BRACE_IN_ARRAY_INITIALIZER = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_opening_brace_in_array_initializer"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the opening parenthesis in a cast expression
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_paren_in_cast"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space after the opening parenthesis in a cast expression
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_paren_in_cast"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_CAST = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_opening_paren_in_cast"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_CAST = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_opening_paren_in_cast"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the opening parenthesis in a catch
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_paren_in_catch"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space after the opening parenthesis in a catch
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_paren_in_catch"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_CATCH = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_opening_paren_in_catch"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_CATCH = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_opening_paren_in_catch"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the opening parenthesis in a constructor declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space after the opening parenthesis in a constructor declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_CONSTRUCTOR_DECLARATION = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_opening_paren_in_constructor_declaration"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_CONSTRUCTOR_DECLARATION = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_opening_paren_in_constructor_declaration"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the opening parenthesis in a for statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_paren_in_for"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space after the opening parenthesis in a for statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_paren_in_for"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_FOR = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_opening_paren_in_for"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_FOR = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_opening_paren_in_for"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the opening parenthesis in an if statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_paren_in_if"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space after the opening parenthesis in an if statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_paren_in_if"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_IF = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_opening_paren_in_if"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_IF = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_opening_paren_in_if"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the opening parenthesis in a method declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_paren_in_method_declaration"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space after the opening parenthesis in a method declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_paren_in_method_declaration"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_METHOD_DECLARATION = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_opening_paren_in_method_declaration"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_METHOD_DECLARATION = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_opening_paren_in_method_declaration"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the opening parenthesis in a method invocation
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_paren_in_method_invocation"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space after the opening parenthesis in a method invocation
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_paren_in_method_invocation"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_METHOD_INVOCATION = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_opening_paren_in_method_invocation"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_METHOD_INVOCATION = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_opening_paren_in_method_invocation"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the opening parenthesis in a parenthesized expression
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space after the opening parenthesis in a parenthesized expression
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_PARENTHESIZED_EXPRESSION = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_opening_paren_in_parenthesized_expression"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_PARENTHESIZED_EXPRESSION = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_opening_paren_in_parenthesized_expression"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the opening parenthesis in a switch statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_paren_in_switch"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space after the opening parenthesis in a switch statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_paren_in_switch"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_SWITCH = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_opening_paren_in_switch"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_SWITCH = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_opening_paren_in_switch"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the opening parenthesis in a synchronized statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_paren_in_synchronized"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space after the opening parenthesis in a synchronized statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_paren_in_synchronized"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_SYNCHRONIZED = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_opening_paren_in_synchronized"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_SYNCHRONIZED = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_opening_paren_in_synchronized"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after the opening parenthesis in a while statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_paren_in_while"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space after the opening parenthesis in a while statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_opening_paren_in_while"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_WHILE = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_opening_paren_in_while"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_OPENING_PAREN_IN_WHILE = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_opening_paren_in_while"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after a postfix operator
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_postfix_operator"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space after a postfix operator
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_postfix_operator"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_POSTFIX_OPERATOR = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_postfix_operator"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_POSTFIX_OPERATOR = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_postfix_operator"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after a prefix operator
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_prefix_operator"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space after a prefix operator
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_prefix_operator"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_PREFIX_OPERATOR = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_prefix_operator"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_PREFIX_OPERATOR = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_prefix_operator"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after question mark in a conditional expression
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_question_in_conditional"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space after question mark in a conditional expression
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_question_in_conditional"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_QUESTION_IN_CONDITIONAL = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_question_in_conditional"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_QUESTION_IN_CONDITIONAL = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_question_in_conditional"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after semicolon in a for statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_semicolon_in_for"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space after semicolon in a for statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_semicolon_in_for"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_SEMICOLON_IN_FOR = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_semicolon_in_for"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_AFTER_SEMICOLON_IN_FOR = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_semicolon_in_for"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space after an unary operator
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_unary_operator"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space after an unary operator
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_after_unary_operator"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_AFTER_UNARY_OPERATOR = JavaCore.PLUGIN_ID + ".formatter.insert_space_after_unary_operator"; //$NON-NLS-1$ - + public static final String FORMATTER_INSERT_SPACE_AFTER_UNARY_OPERATOR = JavaCore.PLUGIN_ID + + ".formatter.insert_space_after_unary_operator"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before an assignment operator
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_assignment_operator"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space before an assignment operator
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_assignment_operator"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATOR = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_assignment_operator"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATOR = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_assignment_operator"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before an binary operator
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_binary_operator"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before an binary operator
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_binary_operator"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_BINARY_OPERATOR = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_binary_operator"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_BINARY_OPERATOR = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_binary_operator"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the closing brace in an array initializer
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_brace_in_array_initializer"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before the closing brace in an array initializer
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_brace_in_array_initializer"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_BRACE_IN_ARRAY_INITIALIZER = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_closing_brace_in_array_initializer"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_BRACE_IN_ARRAY_INITIALIZER = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_closing_brace_in_array_initializer"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the closing bracket in an array allocation expression
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before the closing bracket in an array allocation expression
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_BRACKET_IN_ARRAY_ALLOCATION_EXPRESSION = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_closing_bracket_in_array_allocation_expression";//$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_BRACKET_IN_ARRAY_ALLOCATION_EXPRESSION = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_closing_bracket_in_array_allocation_expression";//$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the closing bracket in an array reference
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_bracket_in_array_reference"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before the closing bracket in an array reference
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_bracket_in_array_reference"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_BRACKET_IN_ARRAY_REFERENCE = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_closing_bracket_in_array_reference";//$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_BRACKET_IN_ARRAY_REFERENCE = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_closing_bracket_in_array_reference";//$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the closing parenthesis in a cast expression
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_paren_in_cast"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before the closing parenthesis in a cast expression
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_paren_in_cast"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_CAST = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_closing_paren_in_cast"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_CAST = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_closing_paren_in_cast"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the closing parenthesis in a catch
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_paren_in_catch"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before the closing parenthesis in a catch
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_paren_in_catch"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_CATCH = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_closing_paren_in_catch"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_CATCH = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_closing_paren_in_catch"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the closing parenthesis in a constructor declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before the closing parenthesis in a constructor declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_CONSTRUCTOR_DECLARATION = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_closing_paren_in_constructor_declaration"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_CONSTRUCTOR_DECLARATION = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_closing_paren_in_constructor_declaration"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the closing parenthesis in a for statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_paren_in_for"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before the closing parenthesis in a for statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_paren_in_for"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_FOR = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_closing_paren_in_for"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_FOR = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_closing_paren_in_for"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the closing parenthesis in an if statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_paren_in_if"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before the closing parenthesis in an if statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_paren_in_if"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_IF = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_closing_paren_in_if"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_IF = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_closing_paren_in_if"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the closing parenthesis in a method declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_paren_in_method_declaration"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before the closing parenthesis in a method declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_paren_in_method_declaration"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_METHOD_DECLARATION = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_closing_paren_in_method_declaration"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_METHOD_DECLARATION = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_closing_paren_in_method_declaration"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the closing parenthesis in a method invocation
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_paren_in_method_invocation"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before the closing parenthesis in a method invocation
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_paren_in_method_invocation"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_METHOD_INVOCATION = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_closing_paren_in_method_invocation"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_METHOD_INVOCATION = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_closing_paren_in_method_invocation"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the closing parenthesis in a parenthesized expression
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before the closing parenthesis in a parenthesized expression
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_PARENTHESIZED_EXPRESSION = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_closing_paren_in_parenthesized_expression"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_PARENTHESIZED_EXPRESSION = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_closing_paren_in_parenthesized_expression"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the closing parenthesis in a switch statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_paren_in_switch"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before the closing parenthesis in a switch statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_paren_in_switch"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_SWITCH = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_closing_paren_in_switch"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_SWITCH = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_closing_paren_in_switch"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the closing parenthesis in a synchronized statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_paren_in_synchronized"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before the closing parenthesis in a synchronized statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_paren_in_synchronized"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_SYNCHRONIZED = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_closing_paren_in_synchronized"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_SYNCHRONIZED = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_closing_paren_in_synchronized"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the closing parenthesis in a while statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_paren_in_while"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before the closing parenthesis in a while statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_closing_paren_in_while"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_WHILE = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_closing_paren_in_while"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_CLOSING_PAREN_IN_WHILE = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_closing_paren_in_while"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before colon in an assert statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_colon_in_assert"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space before colon in an assert statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_colon_in_assert"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_ASSERT = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_colon_in_assert"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_ASSERT = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_colon_in_assert"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before colon in a case statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_colon_in_case"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space before colon in a case statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_colon_in_case"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_CASE = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_colon_in_case"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_CASE = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_colon_in_case"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before colon in a conditional expression
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_colon_in_conditional"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space before colon in a conditional expression
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_colon_in_conditional"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_CONDITIONAL = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_colon_in_conditional"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_CONDITIONAL = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_colon_in_conditional"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before colon in a default statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_colon_in_default"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space before colon in a default statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_colon_in_default"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_DEFAULT = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_colon_in_default"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_DEFAULT = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_colon_in_default"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before colon in a labeled statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_colon_in_labeled_statement"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space before colon in a labeled statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_colon_in_labeled_statement"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_LABELED_STATEMENT = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_colon_in_labeled_statement"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_COLON_IN_LABELED_STATEMENT = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_colon_in_labeled_statement"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before comma in an allocation expression
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_comma_in_allocation_expression"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before comma in an allocation expression
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_comma_in_allocation_expression"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ALLOCATION_EXPRESSION = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_allocation_expression"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ALLOCATION_EXPRESSION = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_comma_in_allocation_expression"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before comma in an array initializer
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_comma_in_array_initializer"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before comma in an array initializer
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_comma_in_array_initializer"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ARRAY_INITIALIZER = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_array_initializer"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_ARRAY_INITIALIZER = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_comma_in_array_initializer"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before comma in the parameters of a constructor declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before comma in the parameters of a constructor declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_CONSTRUCTOR_DECLARATION_PARAMETERS = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_constructor_declaration_parameters"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_CONSTRUCTOR_DECLARATION_PARAMETERS = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_comma_in_constructor_declaration_parameters"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before comma in the exception names of the throws clause of a constructor declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before comma in the exception names of the throws clause of a constructor declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_CONSTRUCTOR_DECLARATION_THROWS = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_constructor_declaration_throws"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_CONSTRUCTOR_DECLARATION_THROWS = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_comma_in_constructor_declaration_throws"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before comma in the arguments of an explicit constructor call
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before comma in the arguments of an explicit constructor call
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_EXPLICIT_CONSTRUCTOR_CALL_ARGUMENTS = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_explicitconstructorcall_arguments"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_EXPLICIT_CONSTRUCTOR_CALL_ARGUMENTS = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_comma_in_explicitconstructorcall_arguments"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before comma in the increments of a for statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_comma_in_for_increments"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before comma in the increments of a for statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_comma_in_for_increments"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_FOR_INCREMENTS = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_for_increments"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_FOR_INCREMENTS = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_comma_in_for_increments"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before comma in the initializations of a for statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_comma_in_for_inits"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before comma in the initializations of a for statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_comma_in_for_inits"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_FOR_INITS = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_for_inits"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_FOR_INITS = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_comma_in_for_inits"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before comma in the arguments of a method invocation
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before comma in the arguments of a method invocation
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_INVOCATION_ARGUMENTS = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_method_invocation_arguments"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_INVOCATION_ARGUMENTS = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_comma_in_method_invocation_arguments"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before comma in the parameters of a method declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before comma in the parameters of a method declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_DECLARATION_PARAMETERS = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_method_declaration_parameters"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_DECLARATION_PARAMETERS = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_comma_in_method_declaration_parameters"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before comma in the exception names of the throws clause of a method declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_comma_in_method_declaration_throws"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before comma in the exception names of the throws clause of a method declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_comma_in_method_declaration_throws"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_DECLARATION_THROWS = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_method_declaration_throws"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_METHOD_DECLARATION_THROWS = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_comma_in_method_declaration_throws"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before comma in a multiple field declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before comma in a multiple field declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_MULTIPLE_FIELD_DECLARATIONS = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_multiple_field_declarations"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_MULTIPLE_FIELD_DECLARATIONS = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_comma_in_multiple_field_declarations"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before comma in a multiple local declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before comma in a multiple local declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_MULTIPLE_LOCAL_DECLARATIONS = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_multiple_local_declarations"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_MULTIPLE_LOCAL_DECLARATIONS = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_comma_in_multiple_local_declarations"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before comma in the superinterfaces names in a type header
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_comma_in_superinterfaces"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before comma in the superinterfaces names in a type header
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_comma_in_superinterfaces"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_SUPERINTERFACES = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_comma_in_superinterfaces"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_COMMA_IN_SUPERINTERFACES = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_comma_in_superinterfaces"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the opening brace in an anonymous type declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space before the opening brace in an anonymous type declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_ANONYMOUS_TYPE_DECLARATION = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_opening_brace_in_anonymous_type_declaration"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_ANONYMOUS_TYPE_DECLARATION = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_opening_brace_in_anonymous_type_declaration"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the opening brace in an array initializer
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_brace_in_array_initializer"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before the opening brace in an array initializer
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_brace_in_array_initializer"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_ARRAY_INITIALIZER = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_opening_brace_in_array_initializer"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_ARRAY_INITIALIZER = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_opening_brace_in_array_initializer"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the opening brace in a block
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_brace_in_block"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space before the opening brace in a block
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_brace_in_block"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_BLOCK = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_opening_brace_in_block"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_BLOCK = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_opening_brace_in_block"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the opening brace in a constructor declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space before the opening brace in a constructor declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_CONSTRUCTOR_DECLARATION = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_opening_brace_in_constructor_declaration"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_CONSTRUCTOR_DECLARATION = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_opening_brace_in_constructor_declaration"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the opening brace in a method declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_brace_in_method_declaration"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space before the opening brace in a method declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_brace_in_method_declaration"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_METHOD_DECLARATION = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_opening_brace_in_method_declaration"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_METHOD_DECLARATION = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_opening_brace_in_method_declaration"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the opening brace in a switch statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_brace_in_switch"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space before the opening brace in a switch statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_brace_in_switch"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_SWITCH = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_opening_brace_in_switch"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_SWITCH = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_opening_brace_in_switch"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the opening brace in a type declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_brace_in_type_declaration"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space before the opening brace in a type declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_brace_in_type_declaration"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_TYPE_DECLARATION = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_opening_brace_in_type_declaration"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACE_IN_TYPE_DECLARATION = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_opening_brace_in_type_declaration"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the opening bracket in an array allocation expression
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before the opening bracket in an array allocation expression
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACKET_IN_ARRAY_ALLOCATION_EXPRESSION = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_opening_bracket_in_array_allocation_expression";//$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACKET_IN_ARRAY_ALLOCATION_EXPRESSION = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_opening_bracket_in_array_allocation_expression";//$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the opening bracket in an array reference
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_bracket_in_array_reference"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before the opening bracket in an array reference
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_bracket_in_array_reference"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACKET_IN_ARRAY_REFERENCE = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_opening_bracket_in_array_reference";//$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACKET_IN_ARRAY_REFERENCE = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_opening_bracket_in_array_reference";//$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the opening bracket in an array type reference
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before the opening bracket in an array type reference
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACKET_IN_ARRAY_TYPE_REFERENCE = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_opening_bracket_in_array_type_reference"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_BRACKET_IN_ARRAY_TYPE_REFERENCE = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_opening_bracket_in_array_type_reference"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the opening parenthesis in a catch
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_paren_in_catch"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space before the opening parenthesis in a catch
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_paren_in_catch"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_CATCH = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_opening_paren_in_catch"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_CATCH = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_opening_paren_in_catch"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the opening parenthesis in a constructor declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before the opening parenthesis in a constructor declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_CONSTRUCTOR_DECLARATION = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_opening_paren_in_constructor_declaration"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_CONSTRUCTOR_DECLARATION = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_opening_paren_in_constructor_declaration"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the opening parenthesis in a for statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_paren_in_for"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space before the opening parenthesis in a for statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_paren_in_for"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_FOR = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_opening_paren_in_for"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_FOR = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_opening_paren_in_for"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the opening parenthesis in an if statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_paren_in_if"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space before the opening parenthesis in an if statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_paren_in_if"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_IF = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_opening_paren_in_if"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_IF = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_opening_paren_in_if"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the opening parenthesis in a method invocation
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_paren_in_method_invocation"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before the opening parenthesis in a method invocation
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_paren_in_method_invocation"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_METHOD_INVOCATION = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_opening_paren_in_method_invocation"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_METHOD_INVOCATION = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_opening_paren_in_method_invocation"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the opening parenthesis in a method declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_paren_in_method_declaration"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before the opening parenthesis in a method declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_paren_in_method_declaration"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_METHOD_DECLARATION = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_opening_paren_in_method_declaration"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_METHOD_DECLARATION = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_opening_paren_in_method_declaration"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the opening parenthesis in a switch statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_paren_in_switch"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space before the opening parenthesis in a switch statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_paren_in_switch"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_SWITCH = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_opening_paren_in_switch"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_SWITCH = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_opening_paren_in_switch"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the opening parenthesis in a synchronized statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_paren_in_synchronized"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space before the opening parenthesis in a synchronized statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_paren_in_synchronized"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_SYNCHRONIZED = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_opening_paren_in_synchronized"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_SYNCHRONIZED = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_opening_paren_in_synchronized"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the opening parenthesis in a parenthesized expression
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before the opening parenthesis in a parenthesized expression
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_PARENTHESIZED_EXPRESSION = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_opening_paren_in_parenthesized_expression"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_PARENTHESIZED_EXPRESSION = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_opening_paren_in_parenthesized_expression"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before the opening parenthesis in a while statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_paren_in_while"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space before the opening parenthesis in a while statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_opening_paren_in_while"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_WHILE = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_opening_paren_in_while"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_OPENING_PAREN_IN_WHILE = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_opening_paren_in_while"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before a postfix operator
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_postfix_operator"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before a postfix operator
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_postfix_operator"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_POSTFIX_OPERATOR = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_postfix_operator"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_POSTFIX_OPERATOR = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_postfix_operator"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before a prefix operator
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_prefix_operator"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before a prefix operator
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_prefix_operator"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_PREFIX_OPERATOR = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_prefix_operator"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_PREFIX_OPERATOR = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_prefix_operator"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before question mark in a conditional expression
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_question_in_conditional"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           INSERT
          +	 *  FORMATTER / Option to insert a space before question mark in a conditional expression
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_question_in_conditional"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_QUESTION_IN_CONDITIONAL = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_question_in_conditional"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_QUESTION_IN_CONDITIONAL = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_question_in_conditional"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before semicolon
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_semicolon"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before semicolon
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_semicolon"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_SEMICOLON = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_semicolon"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_SEMICOLON = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_semicolon"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before semicolon in for statement
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_semicolon_in_for"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before semicolon in for statement
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_semicolon_in_for"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_SEMICOLON_IN_FOR = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_semicolon_in_for"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_SEMICOLON_IN_FOR = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_semicolon_in_for"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space before unary operator
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_unary_operator"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space before unary operator
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_before_unary_operator"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BEFORE_UNARY_OPERATOR = JavaCore.PLUGIN_ID + ".formatter.insert_space_before_unary_operator"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BEFORE_UNARY_OPERATOR = JavaCore.PLUGIN_ID + + ".formatter.insert_space_before_unary_operator"; //$NON-NLS-1$ /** *
          -	 * FORMATTER / Option to insert a space between brackets in an array type reference
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_between_brackets_in_array_type_reference"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space between brackets in an array type reference
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_between_brackets_in_array_type_reference"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BETWEEN_BRACKETS_IN_ARRAY_TYPE_REFERENCE = JavaCore.PLUGIN_ID + ".formatter.insert_space_between_brackets_in_array_type_reference"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BETWEEN_BRACKETS_IN_ARRAY_TYPE_REFERENCE = JavaCore.PLUGIN_ID + + ".formatter.insert_space_between_brackets_in_array_type_reference"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space between empty braces in an array initializer
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_between_empty_braces_in_array_initializer"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space between empty braces in an array initializer
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_between_empty_braces_in_array_initializer"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_BRACES_IN_ARRAY_INITIALIZER = JavaCore.PLUGIN_ID + ".formatter.insert_space_between_empty_braces_in_array_initializer"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_BRACES_IN_ARRAY_INITIALIZER = JavaCore.PLUGIN_ID + + ".formatter.insert_space_between_empty_braces_in_array_initializer"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space between empty brackets in an array allocation expression
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space between empty brackets in an array allocation expression
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_BRACKETS_IN_ARRAY_ALLOCATION_EXPRESSION = JavaCore.PLUGIN_ID + ".formatter.insert_space_between_empty_brackets_in_array_allocation_expression"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_BRACKETS_IN_ARRAY_ALLOCATION_EXPRESSION = JavaCore.PLUGIN_ID + + ".formatter.insert_space_between_empty_brackets_in_array_allocation_expression"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space between empty parenthesis in a constructor declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space between empty parenthesis in a constructor declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_CONSTRUCTOR_DECLARATION = JavaCore.PLUGIN_ID + ".formatter.insert_space_between_empty_parens_in_constructor_declaration"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_CONSTRUCTOR_DECLARATION = JavaCore.PLUGIN_ID + + ".formatter.insert_space_between_empty_parens_in_constructor_declaration"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space between empty parenthesis in a method declaration
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_between_empty_parens_in_method_declaration"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space between empty parenthesis in a method declaration
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_between_empty_parens_in_method_declaration"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_METHOD_DECLARATION = JavaCore.PLUGIN_ID + ".formatter.insert_space_between_empty_parens_in_method_declaration"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_METHOD_DECLARATION = JavaCore.PLUGIN_ID + + ".formatter.insert_space_between_empty_parens_in_method_declaration"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to insert a space between empty parenthesis in a method invocation
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_between_empty_parens_in_method_invocation"
          -	 *     - possible values:   { INSERT, DO_NOT_INSERT }
          -	 *     - default:           DO_NOT_INSERT
          +	 *  FORMATTER / Option to insert a space between empty parenthesis in a method invocation
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.insert_space_between_empty_parens_in_method_invocation"
          +	 *      - possible values:   { INSERT, DO_NOT_INSERT }
          +	 *      - default:           DO_NOT_INSERT
           	 * 
          + * * @see JavaCore#INSERT * @see JavaCore#DO_NOT_INSERT * @since 3.0 */ - public static final String FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_METHOD_INVOCATION = JavaCore.PLUGIN_ID + ".formatter.insert_space_between_empty_parens_in_method_invocation"; //$NON-NLS-1$ + public static final String FORMATTER_INSERT_SPACE_BETWEEN_EMPTY_PARENS_IN_METHOD_INVOCATION = JavaCore.PLUGIN_ID + + ".formatter.insert_space_between_empty_parens_in_method_invocation"; //$NON-NLS-1$ /** *
          -	 * FORMATTER / Option to compact else/if
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.compact_else_if"
          -	 *     - possible values:   { TRUE, FALSE }
          -	 *     - default:           TRUE
          +	 *  FORMATTER / Option to compact else/if
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.compact_else_if"
          +	 *      - possible values:   { TRUE, FALSE }
          +	 *      - default:           TRUE
           	 * 
          + * * @see #TRUE * @see #FALSE * @since 3.0 */ - public static final String FORMATTER_COMPACT_ELSE_IF = JavaCore.PLUGIN_ID + ".formatter.compact_else_if"; //$NON-NLS-1$ + public static final String FORMATTER_COMPACT_ELSE_IF = JavaCore.PLUGIN_ID + + ".formatter.compact_else_if"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to keep guardian clause on one line
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.format_guardian_clause_on_one_line"
          -	 *     - possible values:   { TRUE, FALSE }
          -	 *     - default:           FALSE
          +	 *  FORMATTER / Option to keep guardian clause on one line
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.format_guardian_clause_on_one_line"
          +	 *      - possible values:   { TRUE, FALSE }
          +	 *      - default:           FALSE
           	 * 
          + * * @see #TRUE * @see #FALSE * @since 3.0 */ - public static final String FORMATTER_KEEP_GUARDIAN_CLAUSE_ON_ONE_LINE = JavaCore.PLUGIN_ID + ".formatter.format_guardian_clause_on_one_line"; //$NON-NLS-1$ + public static final String FORMATTER_KEEP_GUARDIAN_CLAUSE_ON_ONE_LINE = JavaCore.PLUGIN_ID + + ".formatter.format_guardian_clause_on_one_line"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to keep else statement on the same line
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.keep_else_statement_on_same_line"
          -	 *     - possible values:   { TRUE, FALSE }
          -	 *     - default:           FALSE
          +	 *  FORMATTER / Option to keep else statement on the same line
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.keep_else_statement_on_same_line"
          +	 *      - possible values:   { TRUE, FALSE }
          +	 *      - default:           FALSE
           	 * 
          + * * @see #TRUE * @see #FALSE * @since 3.0 */ - public static final String FORMATTER_KEEP_ELSE_STATEMENT_ON_SAME_LINE = JavaCore.PLUGIN_ID + ".formatter.keep_else_statement_on_same_line"; //$NON-NLS-1$ + public static final String FORMATTER_KEEP_ELSE_STATEMENT_ON_SAME_LINE = JavaCore.PLUGIN_ID + + ".formatter.keep_else_statement_on_same_line"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to keep empty array initializer one one line
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.keep_empty_array_initializer_on_one_line"
          -	 *     - possible values:   { TRUE, FALSE }
          -	 *     - default:           FALSE
          +	 *  FORMATTER / Option to keep empty array initializer one one line
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.keep_empty_array_initializer_on_one_line"
          +	 *      - possible values:   { TRUE, FALSE }
          +	 *      - default:           FALSE
           	 * 
          + * * @see #TRUE * @see #FALSE * @since 3.0 */ - public static final String FORMATTER_KEEP_EMPTY_ARRAY_INITIALIZER_ON_ONE_LINE = JavaCore.PLUGIN_ID + ".formatter.keep_empty_array_initializer_on_one_line"; //$NON-NLS-1$ + public static final String FORMATTER_KEEP_EMPTY_ARRAY_INITIALIZER_ON_ONE_LINE = JavaCore.PLUGIN_ID + + ".formatter.keep_empty_array_initializer_on_one_line"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to keep simple if statement on the one line
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.keep_imple_if_on_one_line"
          -	 *     - possible values:   { TRUE, FALSE }
          -	 *     - default:           FALSE
          +	 *  FORMATTER / Option to keep simple if statement on the one line
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.keep_imple_if_on_one_line"
          +	 *      - possible values:   { TRUE, FALSE }
          +	 *      - default:           FALSE
           	 * 
          + * * @see #TRUE * @see #FALSE * @since 3.0 */ - public static final String FORMATTER_KEEP_SIMPLE_IF_ON_ONE_LINE = JavaCore.PLUGIN_ID + ".formatter.keep_imple_if_on_one_line"; //$NON-NLS-1$ + public static final String FORMATTER_KEEP_SIMPLE_IF_ON_ONE_LINE = JavaCore.PLUGIN_ID + + ".formatter.keep_imple_if_on_one_line"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to keep then statement on the same line
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.keep_then_statement_on_same_line"
          -	 *     - possible values:   { TRUE, FALSE }
          -	 *     - default:           FALSE
          +	 *  FORMATTER / Option to keep then statement on the same line
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.keep_then_statement_on_same_line"
          +	 *      - possible values:   { TRUE, FALSE }
          +	 *      - default:           FALSE
           	 * 
          + * * @see #TRUE * @see #FALSE * @since 3.0 */ - public static final String FORMATTER_KEEP_THEN_STATEMENT_ON_SAME_LINE = JavaCore.PLUGIN_ID + ".formatter.keep_then_statement_on_same_line";//$NON-NLS-1$ + public static final String FORMATTER_KEEP_THEN_STATEMENT_ON_SAME_LINE = JavaCore.PLUGIN_ID + + ".formatter.keep_then_statement_on_same_line";//$NON-NLS-1$ /** *
          -	 * FORMATTER / Option to specify the number of empty lines to preserve
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.number_of_empty_lines_to_preserve"
          -	 *     - possible values:   "<n>", where n is zero or a positive integer
          -	 *     - default:           "0"
          +	 *  FORMATTER / Option to specify the number of empty lines to preserve
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.number_of_empty_lines_to_preserve"
          +	 *      - possible values:   "<n>", where n is zero or a positive integer
          +	 *      - default:           "0"
           	 * 
          + * * @since 3.0 */ - public static final String FORMATTER_NUMBER_OF_EMPTY_LINES_TO_PRESERVE = JavaCore.PLUGIN_ID + ".formatter.number_of_empty_lines_to_preserve"; //$NON-NLS-1$ + public static final String FORMATTER_NUMBER_OF_EMPTY_LINES_TO_PRESERVE = JavaCore.PLUGIN_ID + + ".formatter.number_of_empty_lines_to_preserve"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to specify whether or not empty statement should be on a new line
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.put_empty_statement_on_new_line"
          -	 *     - possible values:   { TRUE, FALSE }
          -	 *     - default:           FALSE
          +	 *  FORMATTER / Option to specify whether or not empty statement should be on a new line
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.put_empty_statement_on_new_line"
          +	 *      - possible values:   { TRUE, FALSE }
          +	 *      - default:           FALSE
           	 * 
          + * * @see #TRUE * @see #FALSE * @since 3.0 */ - public static final String FORMATTER_PUT_EMPTY_STATEMENT_ON_NEW_LINE = JavaCore.PLUGIN_ID + ".formatter.put_empty_statement_on_new_line"; //$NON-NLS-1$ + public static final String FORMATTER_PUT_EMPTY_STATEMENT_ON_NEW_LINE = JavaCore.PLUGIN_ID + + ".formatter.put_empty_statement_on_new_line"; //$NON-NLS-1$ /** *
          -	 * FORMATTER / Option to specify the length of the page. Beyond this length, the formatter will try to split the code
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.lineSplit"
          -	 *     - possible values:   "<n>", where n is zero or a positive integer
          -	 *     - default:           "80"
          +	 *  FORMATTER / Option to specify the length of the page. Beyond this length, the formatter will try to split the code
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.lineSplit"
          +	 *      - possible values:   "<n>", where n is zero or a positive integer
          +	 *      - default:           "80"
           	 * 
          + * * @since 3.0 */ - public static final String FORMATTER_LINE_SPLIT = JavaCore.PLUGIN_ID + ".formatter.lineSplit"; //$NON-NLS-1$ + public static final String FORMATTER_LINE_SPLIT = JavaCore.PLUGIN_ID + + ".formatter.lineSplit"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to specify the tabulation size
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.tabulation.size"
          -	 *     - possible values:   { TAB, SPACE }
          -	 *     - default:           TAB
          +	 *  FORMATTER / Option to specify the tabulation size
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.tabulation.size"
          +	 *      - possible values:   { TAB, SPACE }
          +	 *      - default:           TAB
           	 * 
          + * * @see JavaCore#TAB * @see JavaCore#SPACE * @since 3.0 */ - public static final String FORMATTER_TAB_CHAR = JavaCore.PLUGIN_ID + ".formatter.tabulation.char"; //$NON-NLS-1$ + public static final String FORMATTER_TAB_CHAR = JavaCore.PLUGIN_ID + + ".formatter.tabulation.char"; //$NON-NLS-1$ + /** *
          -	 * FORMATTER / Option to specify the tabulation size
          -	 *     - option id:         "net.sourceforge.phpdt.core.formatter.tabulation.size"
          -	 *     - possible values:   "<n>", where n is zero or a positive integer
          -	 *     - default:           "4"
          +	 *  FORMATTER / Option to specify the tabulation size
          +	 *      - option id:         "net.sourceforge.phpdt.core.formatter.tabulation.size"
          +	 *      - possible values:   "<n>", where n is zero or a positive integer
          +	 *      - default:           "4"
           	 * 
          + * * @since 3.0 */ - public static final String FORMATTER_TAB_SIZE = JavaCore.PLUGIN_ID + ".formatter.tabulation.size"; //$NON-NLS-1$ + public static final String FORMATTER_TAB_SIZE = JavaCore.PLUGIN_ID + + ".formatter.tabulation.size"; //$NON-NLS-1$ /** - * Returns the formatter settings that most closely approximate - * the default formatter settings of Eclipse version 2.1. + * Returns the formatter settings that most closely approximate the default + * formatter settings of Eclipse version 2.1. * * @return the Eclipse 2.1 settings * @since 3.0 */ -// public static Map getEclipse21Settings() { -// return DefaultCodeFormatterOptions.getDefaultSettings().getMap(); -// } - + // public static Map getEclipse21Settings() { + // return DefaultCodeFormatterOptions.getDefaultSettings().getMap(); + // } /** * Returns the settings according to the Java conventions. * * @return the settings according to the Java conventions * @since 3.0 */ -// public static Map getJavaConventionsSettings() { -// return DefaultCodeFormatterOptions.getJavaConventionsSettings().getMap(); -// } - + // public static Map getJavaConventionsSettings() { + // return DefaultCodeFormatterOptions.getJavaConventionsSettings().getMap(); + // } /** - *

          Return the force value of the given alignment value. - * The given alignment value should be created using the createAlignmentValue(boolean, int, int) - * API. + *

          + * Return the force value of the given alignment value. The given alignment + * value should be created using the + * createAlignmentValue(boolean, int, int) API. *

          - * - * @param value the given alignment value + * + * @param value + * the given alignment value * @return the force value of the given alignment value * @see #createAlignmentValue(boolean, int, int) - * @exception IllegalArgumentException if the given alignment value is null, or if it - * doesn't have a valid format. - */ -// public static boolean getForceWrapping(String value) { -// if (value == null) { -// throw WRONG_ARGUMENT; -// } -// try { -// int existingValue = Integer.parseInt(value); -// return (existingValue & Alignment.M_FORCE) != 0; -// } catch (NumberFormatException e) { -// throw WRONG_ARGUMENT; -// } -// } - - /** - *

          Return the indentation style of the given alignment value. - * The given alignment value should be created using the createAlignmentValue(boolean, int, int) - * API. + * @exception IllegalArgumentException + * if the given alignment value is null, or if it doesn't + * have a valid format. + */ + // public static boolean getForceWrapping(String value) { + // if (value == null) { + // throw WRONG_ARGUMENT; + // } + // try { + // int existingValue = Integer.parseInt(value); + // return (existingValue & Alignment.M_FORCE) != 0; + // } catch (NumberFormatException e) { + // throw WRONG_ARGUMENT; + // } + // } + /** + *

          + * Return the indentation style of the given alignment value. The given + * alignment value should be created using the + * createAlignmentValue(boolean, int, int) API. *

          - * - * @param value the given alignment value + * + * @param value + * the given alignment value * @return the indentation style of the given alignment value * @see #createAlignmentValue(boolean, int, int) - * @exception IllegalArgumentException if the given alignment value is null, or if it - * doesn't have a valid format. + * @exception IllegalArgumentException + * if the given alignment value is null, or if it doesn't + * have a valid format. */ public static int getIndentStyle(String value) { if (value == null) { @@ -2266,136 +2862,151 @@ public class DefaultCodeFormatterConstants { } try { int existingValue = Integer.parseInt(value); -// if ((existingValue & Alignment.M_INDENT_BY_ONE) != 0) { -// return INDENT_BY_ONE; -// } else if ((existingValue & Alignment.M_INDENT_ON_COLUMN) != 0) { -// return INDENT_ON_COLUMN; -// } else { - return INDENT_DEFAULT; -// } + // if ((existingValue & Alignment.M_INDENT_BY_ONE) != 0) { + // return INDENT_BY_ONE; + // } else if ((existingValue & Alignment.M_INDENT_ON_COLUMN) != 0) { + // return INDENT_ON_COLUMN; + // } else { + return INDENT_DEFAULT; + // } } catch (NumberFormatException e) { throw WRONG_ARGUMENT; } } /** - *

          Return the wrapping style of the given alignment value. - * The given alignment value should be created using the createAlignmentValue(boolean, int, int) - * API. + *

          + * Return the wrapping style of the given alignment value. The given + * alignment value should be created using the + * createAlignmentValue(boolean, int, int) API. *

          - * - * @param value the given alignment value + * + * @param value + * the given alignment value * @return the wrapping style of the given alignment value * @see #createAlignmentValue(boolean, int, int) - * @exception IllegalArgumentException if the given alignment value is null, or if it - * doesn't have a valid format. - */ -// public static int getWrappingStyle(String value) { -// if (value == null) { -// throw WRONG_ARGUMENT; -// } -// try { -// int existingValue = Integer.parseInt(value) & Alignment.SPLIT_MASK; -// switch(existingValue) { -// case Alignment.M_COMPACT_SPLIT : -// return WRAP_COMPACT; -// case Alignment.M_COMPACT_FIRST_BREAK_SPLIT : -// return WRAP_COMPACT_FIRST_BREAK; -// case Alignment.M_NEXT_PER_LINE_SPLIT : -// return WRAP_NEXT_PER_LINE; -// case Alignment.M_NEXT_SHIFTED_SPLIT : -// return WRAP_NEXT_SHIFTED; -// case Alignment.M_ONE_PER_LINE_SPLIT : -// return WRAP_ONE_PER_LINE; -// default: -// return WRAP_NO_SPLIT; -// } -// } catch (NumberFormatException e) { -// throw WRONG_ARGUMENT; -// } -// } - - /** - *

          Set the indentation style of the given alignment value and return the new value. - * The given value should be created using the createAlignmentValue(boolean, int, int) - * API. + * @exception IllegalArgumentException + * if the given alignment value is null, or if it doesn't + * have a valid format. + */ + // public static int getWrappingStyle(String value) { + // if (value == null) { + // throw WRONG_ARGUMENT; + // } + // try { + // int existingValue = Integer.parseInt(value) & Alignment.SPLIT_MASK; + // switch(existingValue) { + // case Alignment.M_COMPACT_SPLIT : + // return WRAP_COMPACT; + // case Alignment.M_COMPACT_FIRST_BREAK_SPLIT : + // return WRAP_COMPACT_FIRST_BREAK; + // case Alignment.M_NEXT_PER_LINE_SPLIT : + // return WRAP_NEXT_PER_LINE; + // case Alignment.M_NEXT_SHIFTED_SPLIT : + // return WRAP_NEXT_SHIFTED; + // case Alignment.M_ONE_PER_LINE_SPLIT : + // return WRAP_ONE_PER_LINE; + // default: + // return WRAP_NO_SPLIT; + // } + // } catch (NumberFormatException e) { + // throw WRONG_ARGUMENT; + // } + // } + /** + *

          + * Set the indentation style of the given alignment value and return the new + * value. The given value should be created using the + * createAlignmentValue(boolean, int, int) API. *

          - * - * @param value the given alignment value - * @param indentStyle the given indentation style + * + * @param value + * the given alignment value + * @param indentStyle + * the given indentation style * @return the new alignment value * @see #INDENT_BY_ONE * @see #INDENT_DEFAULT * @see #INDENT_ON_COLUMN * @see #createAlignmentValue(boolean, int, int) - * @exception IllegalArgumentException if the given alignment value is null, if the given - * indentation style is not one of the possible indentation styles, or if the given - * alignment value doesn't have a valid format. - */ -// public static String setIndentStyle(String value, int indentStyle) { -// if (value == null) { -// throw WRONG_ARGUMENT; -// } -// switch(indentStyle) { -// case INDENT_BY_ONE : -// case INDENT_DEFAULT : -// case INDENT_ON_COLUMN : -// break; -// default : -// throw WRONG_ARGUMENT; -// } -// try { -// int existingValue = Integer.parseInt(value); -// // clear existing indent bits -// existingValue &= ~(Alignment.M_INDENT_BY_ONE | Alignment.M_INDENT_ON_COLUMN); -// switch(indentStyle) { -// case INDENT_BY_ONE : -// existingValue |= Alignment.M_INDENT_BY_ONE; -// break; -// case INDENT_ON_COLUMN : -// existingValue |= Alignment.M_INDENT_ON_COLUMN; -// } -// return String.valueOf(existingValue); -// } catch (NumberFormatException e) { -// throw WRONG_ARGUMENT; -// } -// } - /** - *

          Set the force value of the given alignment value and return the new value. - * The given alignment value should be created using the createAlignmentValue(boolean, int, int) - * API. + * @exception IllegalArgumentException + * if the given alignment value is null, if the given + * indentation style is not one of the possible indentation + * styles, or if the given alignment value doesn't have a + * valid format. + */ + // public static String setIndentStyle(String value, int indentStyle) { + // if (value == null) { + // throw WRONG_ARGUMENT; + // } + // switch(indentStyle) { + // case INDENT_BY_ONE : + // case INDENT_DEFAULT : + // case INDENT_ON_COLUMN : + // break; + // default : + // throw WRONG_ARGUMENT; + // } + // try { + // int existingValue = Integer.parseInt(value); + // // clear existing indent bits + // existingValue &= ~(Alignment.M_INDENT_BY_ONE | + // Alignment.M_INDENT_ON_COLUMN); + // switch(indentStyle) { + // case INDENT_BY_ONE : + // existingValue |= Alignment.M_INDENT_BY_ONE; + // break; + // case INDENT_ON_COLUMN : + // existingValue |= Alignment.M_INDENT_ON_COLUMN; + // } + // return String.valueOf(existingValue); + // } catch (NumberFormatException e) { + // throw WRONG_ARGUMENT; + // } + // } + /** + *

          + * Set the force value of the given alignment value and return the new + * value. The given alignment value should be created using the + * createAlignmentValue(boolean, int, int) API. *

          - * - * @param value the given alignment value - * @param force the given force value + * + * @param value + * the given alignment value + * @param force + * the given force value * @return the new alignment value * @see #createAlignmentValue(boolean, int, int) - * @exception IllegalArgumentException if the given alignment value is null, or if it - * doesn't have a valid format. - */ -// public static String setForceWrapping(String value, boolean force) { -// if (value == null) { -// throw WRONG_ARGUMENT; -// } -// try { -// int existingValue = Integer.parseInt(value); -// // clear existing force bit -// existingValue &= ~Alignment.M_FORCE; -// if (force) { -// existingValue |= Alignment.M_FORCE; -// } -// return String.valueOf(existingValue); -// } catch (NumberFormatException e) { -// throw WRONG_ARGUMENT; -// } -// } - /** - *

          Set the wrapping style of the given alignment value and return the new value. - * The given value should be created using the createAlignmentValue(boolean, int, int) - * API. + * @exception IllegalArgumentException + * if the given alignment value is null, or if it doesn't + * have a valid format. + */ + // public static String setForceWrapping(String value, boolean force) { + // if (value == null) { + // throw WRONG_ARGUMENT; + // } + // try { + // int existingValue = Integer.parseInt(value); + // // clear existing force bit + // existingValue &= ~Alignment.M_FORCE; + // if (force) { + // existingValue |= Alignment.M_FORCE; + // } + // return String.valueOf(existingValue); + // } catch (NumberFormatException e) { + // throw WRONG_ARGUMENT; + // } + // } + /** + *

          + * Set the wrapping style of the given alignment value and return the new + * value. The given value should be created using the + * createAlignmentValue(boolean, int, int) API. *

          - * - * @param value the given alignment value - * @param wrappingStyle the given wrapping style + * + * @param value + * the given alignment value + * @param wrappingStyle + * the given wrapping style * @return the new alignment value * @see #WRAP_COMPACT * @see #WRAP_COMPACT_FIRST_BREAK @@ -2404,90 +3015,96 @@ public class DefaultCodeFormatterConstants { * @see #WRAP_NO_SPLIT * @see #WRAP_ONE_PER_LINE * @see #createAlignmentValue(boolean, int, int) - * @exception IllegalArgumentException if the given alignment value is null, if the given - * wrapping style is not one of the possible wrapping styles, or if the given - * alignment value doesn't have a valid format. - */ -// public static String setWrappingStyle(String value, int wrappingStyle) { -// if (value == null) { -// throw WRONG_ARGUMENT; -// } -// switch(wrappingStyle) { -// case WRAP_COMPACT : -// case WRAP_COMPACT_FIRST_BREAK : -// case WRAP_NEXT_PER_LINE : -// case WRAP_NEXT_SHIFTED : -// case WRAP_NO_SPLIT : -// case WRAP_ONE_PER_LINE : -// break; -// default: -// throw WRONG_ARGUMENT; -// } -// try { -// int existingValue = Integer.parseInt(value); -// // clear existing split bits -// existingValue &= ~(Alignment.SPLIT_MASK); -// switch(wrappingStyle) { -// case WRAP_COMPACT : -// existingValue |= Alignment.M_COMPACT_SPLIT; -// break; -// case WRAP_COMPACT_FIRST_BREAK : -// existingValue |= Alignment.M_COMPACT_FIRST_BREAK_SPLIT; -// break; -// case WRAP_NEXT_PER_LINE : -// existingValue |= Alignment.M_NEXT_PER_LINE_SPLIT; -// break; -// case WRAP_NEXT_SHIFTED : -// existingValue |= Alignment.M_NEXT_SHIFTED_SPLIT; -// break; -// case WRAP_ONE_PER_LINE : -// existingValue |= Alignment.M_ONE_PER_LINE_SPLIT; -// break; -// } -// return String.valueOf(existingValue); -// } catch (NumberFormatException e) { -// throw WRONG_ARGUMENT; -// } -// } - /** - * Create a new alignment value according to the given values. This must be used to set up - * the alignment options. - * - * @param forceSplit the given force value - * @param wrapStyle the given wrapping style - * @param indentStyle the given indent style + * @exception IllegalArgumentException + * if the given alignment value is null, if the given + * wrapping style is not one of the possible wrapping styles, + * or if the given alignment value doesn't have a valid + * format. + */ + // public static String setWrappingStyle(String value, int wrappingStyle) { + // if (value == null) { + // throw WRONG_ARGUMENT; + // } + // switch(wrappingStyle) { + // case WRAP_COMPACT : + // case WRAP_COMPACT_FIRST_BREAK : + // case WRAP_NEXT_PER_LINE : + // case WRAP_NEXT_SHIFTED : + // case WRAP_NO_SPLIT : + // case WRAP_ONE_PER_LINE : + // break; + // default: + // throw WRONG_ARGUMENT; + // } + // try { + // int existingValue = Integer.parseInt(value); + // // clear existing split bits + // existingValue &= ~(Alignment.SPLIT_MASK); + // switch(wrappingStyle) { + // case WRAP_COMPACT : + // existingValue |= Alignment.M_COMPACT_SPLIT; + // break; + // case WRAP_COMPACT_FIRST_BREAK : + // existingValue |= Alignment.M_COMPACT_FIRST_BREAK_SPLIT; + // break; + // case WRAP_NEXT_PER_LINE : + // existingValue |= Alignment.M_NEXT_PER_LINE_SPLIT; + // break; + // case WRAP_NEXT_SHIFTED : + // existingValue |= Alignment.M_NEXT_SHIFTED_SPLIT; + // break; + // case WRAP_ONE_PER_LINE : + // existingValue |= Alignment.M_ONE_PER_LINE_SPLIT; + // break; + // } + // return String.valueOf(existingValue); + // } catch (NumberFormatException e) { + // throw WRONG_ARGUMENT; + // } + // } + /** + * Create a new alignment value according to the given values. This must be + * used to set up the alignment options. + * + * @param forceSplit + * the given force value + * @param wrapStyle + * the given wrapping style + * @param indentStyle + * the given indent style * * @return the new alignement value */ -// public static String createAlignmentValue(boolean forceSplit, int wrapStyle, int indentStyle) { -// int alignmentValue = 0; -// switch(wrapStyle) { -// case WRAP_COMPACT : -// alignmentValue |= Alignment.M_COMPACT_SPLIT; -// break; -// case WRAP_COMPACT_FIRST_BREAK : -// alignmentValue |= Alignment.M_COMPACT_FIRST_BREAK_SPLIT; -// break; -// case WRAP_NEXT_PER_LINE : -// alignmentValue |= Alignment.M_NEXT_PER_LINE_SPLIT; -// break; -// case WRAP_NEXT_SHIFTED : -// alignmentValue |= Alignment.M_NEXT_SHIFTED_SPLIT; -// break; -// case WRAP_ONE_PER_LINE : -// alignmentValue |= Alignment.M_ONE_PER_LINE_SPLIT; -// break; -// } -// if (forceSplit) { -// alignmentValue |= Alignment.M_FORCE; -// } -// switch(indentStyle) { -// case INDENT_BY_ONE : -// alignmentValue |= Alignment.M_INDENT_BY_ONE; -// break; -// case INDENT_ON_COLUMN : -// alignmentValue |= Alignment.M_INDENT_ON_COLUMN; -// } -// return String.valueOf(alignmentValue); -// } + // public static String createAlignmentValue(boolean forceSplit, int + // wrapStyle, int indentStyle) { + // int alignmentValue = 0; + // switch(wrapStyle) { + // case WRAP_COMPACT : + // alignmentValue |= Alignment.M_COMPACT_SPLIT; + // break; + // case WRAP_COMPACT_FIRST_BREAK : + // alignmentValue |= Alignment.M_COMPACT_FIRST_BREAK_SPLIT; + // break; + // case WRAP_NEXT_PER_LINE : + // alignmentValue |= Alignment.M_NEXT_PER_LINE_SPLIT; + // break; + // case WRAP_NEXT_SHIFTED : + // alignmentValue |= Alignment.M_NEXT_SHIFTED_SPLIT; + // break; + // case WRAP_ONE_PER_LINE : + // alignmentValue |= Alignment.M_ONE_PER_LINE_SPLIT; + // break; + // } + // if (forceSplit) { + // alignmentValue |= Alignment.M_FORCE; + // } + // switch(indentStyle) { + // case INDENT_BY_ONE : + // alignmentValue |= Alignment.M_INDENT_BY_ONE; + // break; + // case INDENT_ON_COLUMN : + // alignmentValue |= Alignment.M_INDENT_ON_COLUMN; + // } + // return String.valueOf(alignmentValue); + // } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/DOMException.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/DOMException.java index 79b002a..815016e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/DOMException.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/DOMException.java @@ -11,22 +11,25 @@ package net.sourceforge.phpdt.core.jdom; /** - * Unchecked exception thrown when an illegal manipulation of the JDOM is - * performed, or when an attempt is made to access/set an attribute of a - * JDOM node that source indexes cannot be determined for (in case the source - * was syntactically incorrect). + * Unchecked exception thrown when an illegal manipulation of the JDOM is + * performed, or when an attempt is made to access/set an attribute of a JDOM + * node that source indexes cannot be determined for (in case the source was + * syntactically incorrect). */ public class DOMException extends RuntimeException { -/** - * Creates a new exception with no detail message. - */ -public DOMException() {} -/** - * Creates a new exception with the given detail message. - * - * @param message the detail message - */ -public DOMException(String message) { - super(message); -} + /** + * Creates a new exception with no detail message. + */ + public DOMException() { + } + + /** + * Creates a new exception with the given detail message. + * + * @param message + * the detail message + */ + public DOMException(String message) { + super(message); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/DOMFactory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/DOMFactory.java index a803c26..179b6a6 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/DOMFactory.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/DOMFactory.java @@ -13,144 +13,159 @@ package net.sourceforge.phpdt.core.jdom; import net.sourceforge.phpdt.internal.core.jdom.DOMBuilder; import net.sourceforge.phpdt.internal.core.jdom.SimpleDOMBuilder; - - /** - * Standard implementation of IDOMFactory, and the only means - * of creating JDOMs and document fragments. + * Standard implementation of IDOMFactory, and the only means of + * creating JDOMs and document fragments. *

          * This class may be instantiated; it is not intended to be subclassed. *

          */ public class DOMFactory implements IDOMFactory { -/** - * Creates a new DOM factory. - */ -public DOMFactory() {} -/* (non-Javadoc) - * Method declared on IDOMFactory. - */ -public IDOMCompilationUnit createCompilationUnit() { - return (new DOMBuilder()).createCompilationUnit(); -} -/* (non-Javadoc) - * Method declared on IDOMFactory. - */ -public IDOMCompilationUnit createCompilationUnit(char[] sourceCode, String name) { - if(sourceCode == null) { - return null; - } - return (new SimpleDOMBuilder()).createCompilationUnit(sourceCode, name.toCharArray()); -} -/* (non-Javadoc) - * Method declared on IDOMFactory. - */ -public IDOMCompilationUnit createCompilationUnit(String sourceCode, String name) { - if(sourceCode == null) { - return null; - } - return (new SimpleDOMBuilder()).createCompilationUnit(sourceCode.toCharArray(), name.toCharArray()); -} -/* (non-Javadoc) - * Method declared on IDOMFactory. - */ -//public IDOMField createField() { -// return createField("Object aField;"+ ProjectPrefUtil.LINE_SEPARATOR); //$NON-NLS-1$ -//} -///* (non-Javadoc) -// * Method declared on IDOMFactory. -// */ -//public IDOMField createField(String sourceCode) { -// if(sourceCode == null) { -// return null; -// } -// return (new DOMBuilder()).createField(sourceCode.toCharArray()); -//} -/* (non-Javadoc) - * Method declared on IDOMFactory. - */ -//public IDOMImport createImport() { -// return (new DOMBuilder()).createImport(); -//} -///* (non-Javadoc) -// * Method declared on IDOMFactory. -// */ -//public IDOMImport createImport(String sourceCode) { -// if(sourceCode == null) { -// return null; -// } -// return (new DOMBuilder()).createImport(sourceCode.toCharArray()); -//} -/* (non-Javadoc) - * Method declared on IDOMFactory. - */ -//public IDOMInitializer createInitializer() { -// return createInitializer("static {}"+ ProjectPrefUtil.LINE_SEPARATOR); //$NON-NLS-1$ -//} -///* (non-Javadoc) -// * Method declared on IDOMFactory. -// */ -//public IDOMInitializer createInitializer(String sourceCode) { -// if(sourceCode == null) { -// return null; -// } -// return (new DOMBuilder()).createInitializer(sourceCode.toCharArray()); -//} -/* (non-Javadoc) - * Method declared on IDOMFactory. - */ -//public IDOMMethod createMethod() { -// return createMethod("public void newMethod() {"+ ProjectPrefUtil.LINE_SEPARATOR+"}"+ ProjectPrefUtil.LINE_SEPARATOR); //$NON-NLS-2$ //$NON-NLS-1$ -//} -///* (non-Javadoc) -// * Method declared on IDOMFactory. -// */ -//public IDOMMethod createMethod(String sourceCode) { -// if(sourceCode == null) { -// return null; -// } -// return (new DOMBuilder()).createMethod(sourceCode.toCharArray()); -//} -/* (non-Javadoc) - * Method declared on IDOMFactory. - */ -public IDOMPackage createPackage() { - return (new DOMBuilder()).createPackage(); -} -/* (non-Javadoc) - * Method declared on IDOMFactory. - */ -//public IDOMPackage createPackage(String sourceCode) { -// if(sourceCode == null) { -// return null; -// } -// return (new DOMBuilder()).createPackage(sourceCode.toCharArray()); -//} -///* (non-Javadoc) -// * Method declared on IDOMFactory. -// */ -//public IDOMType createType() { -// return createType("public class AClass {"+ ProjectPrefUtil.LINE_SEPARATOR +"}"+ ProjectPrefUtil.LINE_SEPARATOR); //$NON-NLS-2$ //$NON-NLS-1$ -//} -/* (non-Javadoc) - * Method declared on IDOMFactory. - */ -//public IDOMType createClass() { -// return createType("public class AClass {"+ ProjectPrefUtil.LINE_SEPARATOR +"}"+ ProjectPrefUtil.LINE_SEPARATOR); //$NON-NLS-2$ //$NON-NLS-1$ -//} -///* (non-Javadoc) -// * Method declared on IDOMFactory. -// */ -//public IDOMType createInterface() { -// return createType("public interface AnInterface {"+ ProjectPrefUtil.LINE_SEPARATOR +"}"+ ProjectPrefUtil.LINE_SEPARATOR); //$NON-NLS-2$ //$NON-NLS-1$ -//} -/* (non-Javadoc) - * Method declared on IDOMFactory. - */ -//public IDOMType createType(String sourceCode) { -// if(sourceCode == null) { -// return null; -// } -// return (new DOMBuilder()).createType(sourceCode.toCharArray()); -//} + /** + * Creates a new DOM factory. + */ + public DOMFactory() { + } + + /* + * (non-Javadoc) Method declared on IDOMFactory. + */ + public IDOMCompilationUnit createCompilationUnit() { + return (new DOMBuilder()).createCompilationUnit(); + } + + /* + * (non-Javadoc) Method declared on IDOMFactory. + */ + public IDOMCompilationUnit createCompilationUnit(char[] sourceCode, + String name) { + if (sourceCode == null) { + return null; + } + return (new SimpleDOMBuilder()).createCompilationUnit(sourceCode, name + .toCharArray()); + } + + /* + * (non-Javadoc) Method declared on IDOMFactory. + */ + public IDOMCompilationUnit createCompilationUnit(String sourceCode, + String name) { + if (sourceCode == null) { + return null; + } + return (new SimpleDOMBuilder()).createCompilationUnit(sourceCode + .toCharArray(), name.toCharArray()); + } + + /* + * (non-Javadoc) Method declared on IDOMFactory. + */ + // public IDOMField createField() { + // return createField("Object aField;"+ ProjectPrefUtil.LINE_SEPARATOR); + // //$NON-NLS-1$ + // } + // /* (non-Javadoc) + // * Method declared on IDOMFactory. + // */ + // public IDOMField createField(String sourceCode) { + // if(sourceCode == null) { + // return null; + // } + // return (new DOMBuilder()).createField(sourceCode.toCharArray()); + // } + /* + * (non-Javadoc) Method declared on IDOMFactory. + */ + // public IDOMImport createImport() { + // return (new DOMBuilder()).createImport(); + // } + // /* (non-Javadoc) + // * Method declared on IDOMFactory. + // */ + // public IDOMImport createImport(String sourceCode) { + // if(sourceCode == null) { + // return null; + // } + // return (new DOMBuilder()).createImport(sourceCode.toCharArray()); + // } + /* + * (non-Javadoc) Method declared on IDOMFactory. + */ + // public IDOMInitializer createInitializer() { + // return createInitializer("static {}"+ ProjectPrefUtil.LINE_SEPARATOR); + // //$NON-NLS-1$ + // } + // /* (non-Javadoc) + // * Method declared on IDOMFactory. + // */ + // public IDOMInitializer createInitializer(String sourceCode) { + // if(sourceCode == null) { + // return null; + // } + // return (new DOMBuilder()).createInitializer(sourceCode.toCharArray()); + // } + /* + * (non-Javadoc) Method declared on IDOMFactory. + */ + // public IDOMMethod createMethod() { + // return createMethod("public void newMethod() {"+ + // ProjectPrefUtil.LINE_SEPARATOR+"}"+ ProjectPrefUtil.LINE_SEPARATOR); + // //$NON-NLS-2$ //$NON-NLS-1$ + // } + // /* (non-Javadoc) + // * Method declared on IDOMFactory. + // */ + // public IDOMMethod createMethod(String sourceCode) { + // if(sourceCode == null) { + // return null; + // } + // return (new DOMBuilder()).createMethod(sourceCode.toCharArray()); + // } + /* + * (non-Javadoc) Method declared on IDOMFactory. + */ + public IDOMPackage createPackage() { + return (new DOMBuilder()).createPackage(); + } + /* + * (non-Javadoc) Method declared on IDOMFactory. + */ + // public IDOMPackage createPackage(String sourceCode) { + // if(sourceCode == null) { + // return null; + // } + // return (new DOMBuilder()).createPackage(sourceCode.toCharArray()); + // } + // /* (non-Javadoc) + // * Method declared on IDOMFactory. + // */ + // public IDOMType createType() { + // return createType("public class AClass {"+ ProjectPrefUtil.LINE_SEPARATOR + // +"}"+ ProjectPrefUtil.LINE_SEPARATOR); //$NON-NLS-2$ //$NON-NLS-1$ + // } + /* + * (non-Javadoc) Method declared on IDOMFactory. + */ + // public IDOMType createClass() { + // return createType("public class AClass {"+ ProjectPrefUtil.LINE_SEPARATOR + // +"}"+ ProjectPrefUtil.LINE_SEPARATOR); //$NON-NLS-2$ //$NON-NLS-1$ + // } + // /* (non-Javadoc) + // * Method declared on IDOMFactory. + // */ + // public IDOMType createInterface() { + // return createType("public interface AnInterface {"+ + // ProjectPrefUtil.LINE_SEPARATOR +"}"+ ProjectPrefUtil.LINE_SEPARATOR); + // //$NON-NLS-2$ //$NON-NLS-1$ + // } + /* + * (non-Javadoc) Method declared on IDOMFactory. + */ + // public IDOMType createType(String sourceCode) { + // if(sourceCode == null) { + // return null; + // } + // return (new DOMBuilder()).createType(sourceCode.toCharArray()); + // } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMCompilationUnit.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMCompilationUnit.java index 37f0537..1504b23 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMCompilationUnit.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMCompilationUnit.java @@ -11,54 +11,63 @@ package net.sourceforge.phpdt.core.jdom; /** - * Represents a Java compilation unit (.java source file). - * The corresponding syntactic unit is CompilationUnit (JLS2 7.3). - * Allowable child types for a compilation unit are IDOMPackage, IDOMImport, - * and IDOMType. + * Represents a Java compilation unit (.java source file). The + * corresponding syntactic unit is CompilationUnit (JLS2 7.3). Allowable child + * types for a compilation unit are IDOMPackage, + * IDOMImport, and IDOMType. *

          * This interface is not intended to be implemented by clients. *

          */ public interface IDOMCompilationUnit extends IDOMNode { -/** - * Returns the header comment for this compilation unit. The header comment - * appears before the first declaration in a compilation unit. - * The syntax for a comment corresponds to Comments (JLS2 3.7), including - * comment delimiters. - * - * @return the header comment for this compilation unit, or null if - * no header comment is present - */ -public String getHeader(); -/** - * The IDOMCompilationNode refinement of this IDOMNode - * method returns the name of this compilation unit. - * - *

          The name of a compilation unit is the name of the first top-level public type - * defined in the compilation unit, suffixed with ".java". For example, if the first - * top-level public type defined in this compilation unit has the name "Hanoi", - * then name of this compilation unit is "Hanoi.java".

          - * - *

          In the absence of a public top-level type, the name of the first top-level - * type is used. In the absence of any type, the name of the compilation unit - * is null.

          - * - * @return the name of this compilation unit, or null if none - */ -public String getName(); -/** - * Sets the header comment for this compilation unit. The header comment - * appears before the first declaration in a compilation unit. - * The syntax for a comment corresponds to Comments (JLS2 3.7), including - * comment delimiters. - * - * @param comment the header comment for this compilation unit, or null if - * indicating no header comment - */ -public void setHeader(String comment); -/** - * The IDOMCompilationNode refinement of this IDOMNode - * method has no effect (the name is computed from the types declared within it). - */ -public void setName(String name); + /** + * Returns the header comment for this compilation unit. The header comment + * appears before the first declaration in a compilation unit. The syntax + * for a comment corresponds to Comments (JLS2 3.7), including + * comment delimiters. + * + * @return the header comment for this compilation unit, or + * null if no header comment is present + */ + public String getHeader(); + + /** + * The IDOMCompilationNode refinement of this + * IDOMNode method returns the name of this compilation unit. + * + *

          + * The name of a compilation unit is the name of the first top-level public + * type defined in the compilation unit, suffixed with ".java". For example, + * if the first top-level public type defined in this compilation unit has + * the name "Hanoi", then name of this compilation unit is "Hanoi.java". + *

          + * + *

          + * In the absence of a public top-level type, the name of the first + * top-level type is used. In the absence of any type, the name of the + * compilation unit is null. + *

          + * + * @return the name of this compilation unit, or null if none + */ + public String getName(); + + /** + * Sets the header comment for this compilation unit. The header comment + * appears before the first declaration in a compilation unit. The syntax + * for a comment corresponds to Comments (JLS2 3.7), including + * comment delimiters. + * + * @param comment + * the header comment for this compilation unit, or + * null if indicating no header comment + */ + public void setHeader(String comment); + + /** + * The IDOMCompilationNode refinement of this + * IDOMNode method has no effect (the name is computed from + * the types declared within it). + */ + public void setName(String name); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMFactory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMFactory.java index eea0df1..19c58b2 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMFactory.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMFactory.java @@ -11,32 +11,32 @@ package net.sourceforge.phpdt.core.jdom; /** - * A factory used to create document fragment (DF) nodes. An - * IDOMCompilationUnit represents the root of a complete JDOM (that - * is, a ".java" file). Other node types represent fragments of a compilation - * unit. + * A factory used to create document fragment (DF) nodes. An + * IDOMCompilationUnit represents the root of a complete JDOM + * (that is, a ".java" file). Other node types represent fragments of a + * compilation unit. *

          * The factory can be used to create empty DFs or it can create DFs from source * strings. All DFs created empty are assigned default values as required, such - * that a call to IDOMNode.getContents will generate a valid source - * string. See individual create methods for details on the default - * values supplied. The factory does its best to recognize Java structures in - * the source provided. If the factory is completely unable to recognize source - * constructs, the factory method returns null. + * that a call to IDOMNode.getContents will generate a valid + * source string. See individual create methods for details on + * the default values supplied. The factory does its best to recognize Java + * structures in the source provided. If the factory is completely unable to + * recognize source constructs, the factory method returns null. *

          *

          * Even if a DF is created successfully from source code, it does not guarantee * that the source code will compile error free. Similarly, the contents of a DF - * are not guaranteed to compile error free. However, syntactically correct + * are not guaranteed to compile error free. However, syntactically correct * source code is guaranteed to be recognized and successfully generate a DF. * Similarly, if all of the fragments of a JDOM are syntactically correct, the * contents of the entire document will be correct too. *

          *

          - * The factory does not perform or provide any code formatting. Document + * The factory does not perform or provide any code formatting. Document * fragments created on source strings must be pre-formatted. The JDOM attempts * to maintain the formatting of documents as best as possible. For this reason, - * document fragments created for nodes that are to be strung together should + * document fragments created for nodes that are to be strung together should * end with a new-line character. Failing to do so will result in a document * that has elements strung together on the same line. This is especially * important if a source string ends with a // comment. In this case, it would @@ -45,153 +45,174 @@ package net.sourceforge.phpdt.core.jdom; *

          * This interface is not intended to be implemented by clients. *

          - * + * * @see IDOMNode */ public interface IDOMFactory { -/** - * Creates and return an empty JDOM. The initial content is an empty string. - * - * @return the new compilation unit - */ -public IDOMCompilationUnit createCompilationUnit(); -/** - * Creates a JDOM on the given source code. The syntax for the given source - * code corresponds to CompilationUnit (JLS2 7.3). - * - * @param sourceCode the source code character array, or null - * @param name the name of the compilation unit - * @return the new compilation unit, or null if unable to recognize - * the source code, or if the source code is null - */ -public IDOMCompilationUnit createCompilationUnit(char[] sourceCode, String name); -/** - * Creates a JDOM on the given source code. The syntax for the given source - * code corresponds to CompilationUnit (JLS2 7.3). - * - * @param sourceCode the source code string, or null - * @param name the name of the compilation unit - * @return the new compilation unit, or null if unable to recognize - * the source code, or if the source code is null - */ -public IDOMCompilationUnit createCompilationUnit(String sourceCode, String name); -/** - * Creates a default field document fragment. Initially the field will have - * default protection, type "Object", name "aField", - * no comment, and no initializer. - * - * @return the new field - */ -//public IDOMField createField(); -/** - * Creates a field document fragment on the given source code. The given source - * string corresponds to FieldDeclaration (JLS2 8.3) and ConstantDeclaration - * (JLS2 9.3) restricted to a single VariableDeclarator clause. - * - * @param sourceCode the source code - * @return the new field, or null if unable to recognize - * the source code, if the source code is null, or when the source - * contains more than one VariableDeclarator clause - */ -//public IDOMField createField(String sourceCode); -/** - * Creates an empty import document fragment. Initially the import will have - * name "java.lang.*". - * - * @return the new import - */ -//public IDOMImport createImport(); -/** - * Creates an import document fragment on the given source code. The syntax for - * the given source string corresponds to ImportDeclaration (JLS2 7.5). - * - * @param sourceCode the source code - * @return the new import, or null if unable to recognize - * the source code, or if the source code is null - */ -//public IDOMImport createImport(String sourceCode); -/** - * Creates an empty initializer document fragment. Initially the initializer - * will be static and have no body or comment. - * - * @return the new initializer - */ -//public IDOMInitializer createInitializer(); -/** - * Creates an initializer document fragment from the given source code. The - * syntax for the given source string corresponds to InstanceInitializer - * (JLS2 8.6) and StaticDeclaration (JLS2 8.7). - * - * @param sourceCode the source code - * @return the new initializer, or null if unable to recognize - * the source code, or if the source code is null - */ -//public IDOMInitializer createInitializer(String sourceCode); -/** - * Creates a default method document fragment. Initially the method - * will have public visibility, return type "void", be named - * "newMethod", have no parameters, no comment, and an empty body. - * - * @return the new method - */ -//public IDOMMethod createMethod(); -/** - * Creates a method document fragment on the given source code. The syntax for - * the given source string corresponds to MethodDeclaration (JLS2 8.4), - * ConstructorDeclaration (JLS2 8.8), and AbstractMethodDeclaration (JLS2 9.4). - * - * @param sourceCode the source code - * @return the new method, or null if unable to recognize - * the source code, or if the source code is null - */ -//public IDOMMethod createMethod(String sourceCode); -/** - * Creates an empty package document fragment. Initially the package - * declaration will have no name. - * - * @return the new package - */ -//public IDOMPackage createPackage(); -/** - * Creates a package document fragment on the given source code. The syntax for - * the given source string corresponds to PackageDeclaration (JLS2 7.4). - * - * @param sourceCode the source code - * @return the new package, or null if unable to recognize - * the source code, or if the source code is null - */ -//public IDOMPackage createPackage(String sourceCode); -/** - * Creates a default type document fragment. Initially the type will be - * a public class named "AClass", with no members or comment. - * - * @return the new type - */ -//public IDOMType createType(); -/** - * Creates a default type document fragment. Initially the type will be - * a public class named "AClass", with no members or comment. - * - * @return the new class - * @since 2.0 - */ -//public IDOMType createClass(); -/** - * Creates a default type document fragment. Initially the type will be - * a public interface named "AnInterface", with no members or comment. - * - * @return the new interface - * @since 2.0 - */ -//public IDOMType createInterface(); -/** - * Creates a type document fragment on the given source code. The syntax for the - * given source string corresponds to ClassDeclaration (JLS2 8.1) and - * InterfaceDeclaration (JLS2 9.1). - * - * @param sourceCode the source code - * @return the new type, or null if unable to recognize - * the source code, or if the source code is null - */ -//public IDOMType createType(String sourceCode); + /** + * Creates and return an empty JDOM. The initial content is an empty string. + * + * @return the new compilation unit + */ + public IDOMCompilationUnit createCompilationUnit(); + + /** + * Creates a JDOM on the given source code. The syntax for the given source + * code corresponds to CompilationUnit (JLS2 7.3). + * + * @param sourceCode + * the source code character array, or null + * @param name + * the name of the compilation unit + * @return the new compilation unit, or null if unable to + * recognize the source code, or if the source code is + * null + */ + public IDOMCompilationUnit createCompilationUnit(char[] sourceCode, + String name); + + /** + * Creates a JDOM on the given source code. The syntax for the given source + * code corresponds to CompilationUnit (JLS2 7.3). + * + * @param sourceCode + * the source code string, or null + * @param name + * the name of the compilation unit + * @return the new compilation unit, or null if unable to + * recognize the source code, or if the source code is + * null + */ + public IDOMCompilationUnit createCompilationUnit(String sourceCode, + String name); + /** + * Creates a default field document fragment. Initially the field will have + * default protection, type "Object", name + * "aField", no comment, and no initializer. + * + * @return the new field + */ + // public IDOMField createField(); + /** + * Creates a field document fragment on the given source code. The given + * source string corresponds to FieldDeclaration (JLS2 8.3) and + * ConstantDeclaration (JLS2 9.3) restricted to a single VariableDeclarator + * clause. + * + * @param sourceCode + * the source code + * @return the new field, or null if unable to recognize the + * source code, if the source code is null, or when + * the source contains more than one VariableDeclarator clause + */ + // public IDOMField createField(String sourceCode); + /** + * Creates an empty import document fragment. Initially the import will have + * name "java.lang.*". + * + * @return the new import + */ + // public IDOMImport createImport(); + /** + * Creates an import document fragment on the given source code. The syntax + * for the given source string corresponds to ImportDeclaration (JLS2 7.5). + * + * @param sourceCode + * the source code + * @return the new import, or null if unable to recognize the + * source code, or if the source code is null + */ + // public IDOMImport createImport(String sourceCode); + /** + * Creates an empty initializer document fragment. Initially the initializer + * will be static and have no body or comment. + * + * @return the new initializer + */ + // public IDOMInitializer createInitializer(); + /** + * Creates an initializer document fragment from the given source code. The + * syntax for the given source string corresponds to InstanceInitializer + * (JLS2 8.6) and StaticDeclaration (JLS2 8.7). + * + * @param sourceCode + * the source code + * @return the new initializer, or null if unable to + * recognize the source code, or if the source code is + * null + */ + // public IDOMInitializer createInitializer(String sourceCode); + /** + * Creates a default method document fragment. Initially the method will + * have public visibility, return type "void", be named + * "newMethod", have no parameters, no comment, and an empty + * body. + * + * @return the new method + */ + // public IDOMMethod createMethod(); + /** + * Creates a method document fragment on the given source code. The syntax + * for the given source string corresponds to MethodDeclaration (JLS2 8.4), + * ConstructorDeclaration (JLS2 8.8), and AbstractMethodDeclaration (JLS2 + * 9.4). + * + * @param sourceCode + * the source code + * @return the new method, or null if unable to recognize the + * source code, or if the source code is null + */ + // public IDOMMethod createMethod(String sourceCode); + /** + * Creates an empty package document fragment. Initially the package + * declaration will have no name. + * + * @return the new package + */ + // public IDOMPackage createPackage(); + /** + * Creates a package document fragment on the given source code. The syntax + * for the given source string corresponds to PackageDeclaration (JLS2 7.4). + * + * @param sourceCode + * the source code + * @return the new package, or null if unable to recognize + * the source code, or if the source code is null + */ + // public IDOMPackage createPackage(String sourceCode); + /** + * Creates a default type document fragment. Initially the type will be a + * public class named "AClass", with no members or comment. + * + * @return the new type + */ + // public IDOMType createType(); + /** + * Creates a default type document fragment. Initially the type will be a + * public class named "AClass", with no members or comment. + * + * @return the new class + * @since 2.0 + */ + // public IDOMType createClass(); + /** + * Creates a default type document fragment. Initially the type will be a + * public interface named "AnInterface", with no members or + * comment. + * + * @return the new interface + * @since 2.0 + */ + // public IDOMType createInterface(); + /** + * Creates a type document fragment on the given source code. The syntax for + * the given source string corresponds to ClassDeclaration (JLS2 8.1) and + * InterfaceDeclaration (JLS2 9.1). + * + * @param sourceCode + * the source code + * @return the new type, or null if unable to recognize the + * source code, or if the source code is null + */ + // public IDOMType createType(String sourceCode); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMField.java index 72de2a6..2c59e19 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMField.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMField.java @@ -11,66 +11,76 @@ package net.sourceforge.phpdt.core.jdom; /** - * Represents a field declaration. The corresponding - * syntactic units are FieldDeclaration (JLS2 8.3) and ConstantDeclaration - * (JLS2 9.3) restricted to a single VariableDeclarator clause. - * A field has no children. The parent of a field is a type. + * Represents a field declaration. The corresponding syntactic units are + * FieldDeclaration (JLS2 8.3) and ConstantDeclaration (JLS2 9.3) restricted to + * a single VariableDeclarator clause. A field has no children. The parent of a + * field is a type. *

          * This interface is not intended to be implemented by clients. *

          */ public interface IDOMField extends IDOMMember { -/** - * Returns the initializer expression for this field. - * The syntax for an initializer corresponds to VariableInitializer (JLS2 8.3). - *

          - * Note: The expression does not include a "=". - *

          - * - * @return the initializer expression, or null if this field does - * not have an initializer - */ -public String getInitializer(); -/** - * The IDOMField refinement of this IDOMNode - * method returns the name of this field. The syntax for the name of a field - * corresponds to VariableDeclaratorId (JLS2 8.3). - */ -public String getName(); -/** - * Returns the type name of this field. The syntax for a type name of a field - * corresponds to Type in Field Declaration (JLS2 8.3). - * - * @return the type name - */ -public String getType(); -/** - * Sets the initializer expression for this field. - * The syntax for an initializer corresponds to VariableInitializer (JLS2 8.3). - *

          - * Note: The expression does not include a "=". - *

          - * - * @param initializer the initializer expression, or null indicating - * the field does not have an initializer - */ -public void setInitializer(String initializer); -/** - * The IDOMField refinement of this IDOMNode - * method sets the name of this field. The syntax for the name of a field - * corresponds to VariableDeclaratorId (JLS2 8.3). - * - * @exception IllegalArgumentException if null is specified - */ -public void setName(String name) throws IllegalArgumentException; -/** - * Sets the type name of this field. The syntax for a type name of a field - * corresponds to Type in Field Declaration (JLS2 8.3). Type names must be - * specified as they should appear in source code. For example: - * "String", "int[]", or "java.io.File". - * - * @param typeName the type name - * @exception IllegalArgumentException if null is specified - */ -public void setType(String typeName) throws IllegalArgumentException; + /** + * Returns the initializer expression for this field. The syntax for an + * initializer corresponds to VariableInitializer (JLS2 8.3). + *

          + * Note: The expression does not include a "=". + *

          + * + * @return the initializer expression, or null if this field + * does not have an initializer + */ + public String getInitializer(); + + /** + * The IDOMField refinement of this IDOMNode + * method returns the name of this field. The syntax for the name of a field + * corresponds to VariableDeclaratorId (JLS2 8.3). + */ + public String getName(); + + /** + * Returns the type name of this field. The syntax for a type name of a + * field corresponds to Type in Field Declaration (JLS2 8.3). + * + * @return the type name + */ + public String getType(); + + /** + * Sets the initializer expression for this field. The syntax for an + * initializer corresponds to VariableInitializer (JLS2 8.3). + *

          + * Note: The expression does not include a "=". + *

          + * + * @param initializer + * the initializer expression, or null indicating + * the field does not have an initializer + */ + public void setInitializer(String initializer); + + /** + * The IDOMField refinement of this IDOMNode + * method sets the name of this field. The syntax for the name of a field + * corresponds to VariableDeclaratorId (JLS2 8.3). + * + * @exception IllegalArgumentException + * if null is specified + */ + public void setName(String name) throws IllegalArgumentException; + + /** + * Sets the type name of this field. The syntax for a type name of a field + * corresponds to Type in Field Declaration (JLS2 8.3). Type names must be + * specified as they should appear in source code. For example: + * "String", "int[]", or + * "java.io.File". + * + * @param typeName + * the type name + * @exception IllegalArgumentException + * if null is specified + */ + public void setType(String typeName) throws IllegalArgumentException; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMImport.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMImport.java index 47a6ffa..67c64c3 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMImport.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMImport.java @@ -11,34 +11,37 @@ package net.sourceforge.phpdt.core.jdom; /** - * Represents an import declaration. - * The corresponding syntactic unit is ImportDeclaration (JLS2 7.5). - * An import has no children and its parent is a compilation unit. + * Represents an import declaration. The corresponding syntactic unit is + * ImportDeclaration (JLS2 7.5). An import has no children and its parent is a + * compilation unit. *

          * This interface is not intended to be implemented by clients. *

          */ public interface IDOMImport extends IDOMNode { -/** - * The IDOMImport refinement of this IDOMNode - * method returns the name of this import. The syntax for an import name - * corresponds to a fully qualified type name, or to an on-demand package name - * as defined by ImportDeclaration (JLS2 7.5). - */ -public String getName(); -/** - * Returns whether this import declaration ends with ".*". - * - * @return true if this in an on-demand import - */ -public boolean isOnDemand(); -/** - * The IDOMImport refinement of this IDOMNode - * method sets the name of this import. The syntax for an import name - * corresponds to a fully qualified type name, or to an on-demand package name - * as defined by ImportDeclaration (JLS2 7.5). - * - * @exception IllegalArgumentException if null is specified - */ -public void setName(String name); + /** + * The IDOMImport refinement of this IDOMNode + * method returns the name of this import. The syntax for an import name + * corresponds to a fully qualified type name, or to an on-demand package + * name as defined by ImportDeclaration (JLS2 7.5). + */ + public String getName(); + + /** + * Returns whether this import declaration ends with ".*". + * + * @return true if this in an on-demand import + */ + public boolean isOnDemand(); + + /** + * The IDOMImport refinement of this IDOMNode + * method sets the name of this import. The syntax for an import name + * corresponds to a fully qualified type name, or to an on-demand package + * name as defined by ImportDeclaration (JLS2 7.5). + * + * @exception IllegalArgumentException + * if null is specified + */ + public void setName(String name); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMInitializer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMInitializer.java index 96c612e..d021d03 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMInitializer.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMInitializer.java @@ -11,39 +11,45 @@ package net.sourceforge.phpdt.core.jdom; /** - * Represents an initializer. The corresponding syntactic - * units are InstanceInitializer (JLS2 8.6) and StaticDeclaration (JLS2 8.7). - * An initializer has no children and its parent is a type. + * Represents an initializer. The corresponding syntactic units are + * InstanceInitializer (JLS2 8.6) and StaticDeclaration (JLS2 8.7). An + * initializer has no children and its parent is a type. *

          * This interface is not intended to be implemented by clients. *

          */ public interface IDOMInitializer extends IDOMMember { -/** - * Returns the body of this initializer. The syntax for a body corresponds to - * InstanceInitializer (JLS2 8.6) and StaticDeclaration (JLS2 8.7). - * - * @return an initializer body, including braces, or null if - * no body is present - */ -public String getBody(); -/** - * The IDOMInitializer refinement of this IDOMNode - * method returns null. An initializer does not have a name. - */ -public String getName(); -/** - * Sets the body of this initializer. The syntax for a body corresponds to - * InstanceInitializer (JLS2 8.6) and StaticDeclaration (JLS2 8.7). No formatting - * or syntax checking is performed on the body. Braces must be included. - * - * @param body an initializer body, including braces, or null - * indicating no body - */ -public void setBody(String body); -/** - * The IDOMInitializer refinement of this IDOMNode - * method does nothing. - */ -public void setName(String name); + /** + * Returns the body of this initializer. The syntax for a body corresponds + * to InstanceInitializer (JLS2 8.6) and StaticDeclaration (JLS2 8.7). + * + * @return an initializer body, including braces, or null if + * no body is present + */ + public String getBody(); + + /** + * The IDOMInitializer refinement of this + * IDOMNode method returns null. An + * initializer does not have a name. + */ + public String getName(); + + /** + * Sets the body of this initializer. The syntax for a body corresponds to + * InstanceInitializer (JLS2 8.6) and StaticDeclaration (JLS2 8.7). No + * formatting or syntax checking is performed on the body. Braces must + * be included. + * + * @param body + * an initializer body, including braces, or null + * indicating no body + */ + public void setBody(String body); + + /** + * The IDOMInitializer refinement of this + * IDOMNode method does nothing. + */ + public void setName(String name); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMMember.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMMember.java index cd4d327..ff16067 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMMember.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMMember.java @@ -11,51 +11,58 @@ package net.sourceforge.phpdt.core.jdom; /** - * An IDOMMember defines functionality common to nodes, which - * can be members of types. + * An IDOMMember defines functionality common to nodes, which can + * be members of types. *

          * This interface is not intended to be implemented by clients. *

          - * + * * @see IDOMType * @see IDOMMethod * @see IDOMField * @see IDOMInitializer */ public interface IDOMMember extends IDOMNode { -/** - * Returns the comment associated with this member (including comment delimiters). - * - * @return the comment, or null if this member has no associated - * comment - */ -public String getComment(); -/** - * Returns the flags for this member. The flags can be examined using the - * Flags class. - * - * @return the flags - * @see net.sourceforge.phpdt.core.Flags - */ -public int getFlags(); -/** - * Sets the comment associated with this member. The comment will appear - * before the member in the source. The comment must be properly formatted, including - * delimiters. A null comment indicates no comment. This member's - * deprecated flag is automatically set to reflect the deprecated tag in the - * comment. - * - * @param comment the comment, including comment delimiters, or - * null indicating this member should have no associated comment - * @see #setFlags - */ -public void setComment(String comment); -/** - * Sets the flags for this member. The flags can be examined using the - * Flags class. The deprecated flag passed in is ignored. - * - * @param flags the flags - * @see net.sourceforge.phpdt.core.Flags - */ -public void setFlags(int flags); + /** + * Returns the comment associated with this member (including comment + * delimiters). + * + * @return the comment, or null if this member has no + * associated comment + */ + public String getComment(); + + /** + * Returns the flags for this member. The flags can be examined using the + * Flags class. + * + * @return the flags + * @see net.sourceforge.phpdt.core.Flags + */ + public int getFlags(); + + /** + * Sets the comment associated with this member. The comment will appear + * before the member in the source. The comment must be properly formatted, + * including delimiters. A null comment indicates no comment. + * This member's deprecated flag is automatically set to reflect the + * deprecated tag in the comment. + * + * @param comment + * the comment, including comment delimiters, or + * null indicating this member should have no + * associated comment + * @see #setFlags + */ + public void setComment(String comment); + + /** + * Sets the flags for this member. The flags can be examined using the + * Flags class. The deprecated flag passed in is ignored. + * + * @param flags + * the flags + * @see net.sourceforge.phpdt.core.Flags + */ + public void setFlags(int flags); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMMethod.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMMethod.java index 4845a80..d2b3419 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMMethod.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMMethod.java @@ -11,172 +11,204 @@ package net.sourceforge.phpdt.core.jdom; /** - * Represents a method declaration. - * The corresponding syntactic units are MethodDeclaration (JLS2 8.4), - * ConstructorDeclaration (JLS2 8.8), and AbstractMethodDeclaration (JLS2 9.4). - * A method has no children and its parent is a type. - * Local classes are considered to be part of the body of a method, not a child. + * Represents a method declaration. The corresponding syntactic units are + * MethodDeclaration (JLS2 8.4), ConstructorDeclaration (JLS2 8.8), and + * AbstractMethodDeclaration (JLS2 9.4). A method has no children and its parent + * is a type. Local classes are considered to be part of the body of a method, + * not a child. *

          * This interface is not intended to be implemented by clients. *

          */ public interface IDOMMethod extends IDOMMember { -/** - * Adds the given exception to the end of the list of exceptions this method - * is declared to throw. - * The syntax for an exception type name is defined by Method Throws (JLS2 8.4.4). - * Type names must be specified as they would appear in source code. For - * example: "IOException" or "java.io.IOException". - * This is a convenience method for setExceptions. - * - * @param exceptionType the exception type - * @exception IllegalArgumentException if null is specified - * @see #setExceptions - */ -public void addException(String exceptionType) throws IllegalArgumentException; -/** - * Adds the given parameter to the end of the parameter list. - * This is a convenience method for setParameters. - * The syntax for parameter names is defined by Formal Parameters (JLS2 8.4.1). - * The syntax for type names is defined by Formal Parameters (JLS2 8.4.1). - * Type names must be specified as they would appear in source code. For - * example: "File", "java.io.File", or - * "int[]". - * - * @param type the type name - * @param name the parameter name - * @exception IllegalArgumentException if null is specified for - * either the type or the name - * @see #setParameters - */ -public void addParameter(String type, String name) throws IllegalArgumentException; -/** - * Returns the body of this method. The method body includes all code following - * the method declaration, including the enclosing braces. - * - * @return the body, or null if the method has no body (for - * example, for an abstract or native method) - */ -public String getBody(); -/** - * Returns the names of the exception types this method throws - * in the order in which they are declared in the source, or an empty array - * if this method declares no exception types. - * The syntax for an exception type name is defined by Method Throws (JLS2 8.4.4). - * Type names appear as they would in source code. For example: - * "IOException" or "java.io.IOException". - * - * @return the list of exception types - */ -public String[] getExceptions(); -/** - * The IDOMMethod refinement of this IDOMNode - * method returns the name of this method. Returns null for - * constructors. The syntax for a method name is defined by Identifier - * of MethodDeclarator (JLS2 8.4). - */ -public String getName(); -/** - * Returns the names of parameters in this method in the order they are declared, - * or null if no parameters are declared. - * The syntax for parameter names is defined by Formal Parameters (JLS2 8.4.1). - * - * @return the list of parameter names, or null if no parameters - * are declared - */ -public String[] getParameterNames(); -/** - * Returns the type names for the parameters of this method in the order they are declared, - * or null if no parameters are declared. - * The syntax for type names is defined by Formal Parameters (JLS2 8.4.1). - * Type names must be specified as they would appear in source code. For - * example: "File", "java.io.File", or - * "int[]". - * - * @return the list of parameter types, or null if no parameters - * are declared - */ -public String[] getParameterTypes(); -/** - * Returns the return type name, or null. - * Returns null for constructors. - * The syntax for return type name corresponds to ReturnType in - * MethodDeclaration (JLS2 8.4). Names are returned as they appear in the source - * code; for example: "File", "java.io.File", - * "int[]", or "void". - * - * @return the return type - */ -public String getReturnType(); -/** - * Returns whether this method is a constructor. - * - * @return true for constructors, and false for methods - */ -public boolean isConstructor(); -/** - * Sets the body of this method. The method body includes all code following - * the method declaration, including the enclosing braces. No formatting or - * syntax checking is performed on the body. - * - * @return the body, or null indicating the method has no body (for - * example, for an abstract or native method) - */ -public void setBody(String body); -/** - * Sets whether this method represents a constructor. - * - * @param b true for constructors, and false for methods - */ -public void setConstructor(boolean b); -/** - * Sets the names of the exception types this method throws, - * in the order in which they are declared in the source. An empty array - * indicates this method declares no exception types. - * The syntax for an exception type name is defined by Method Throws (JLS2 8.4.4). - * Type names must be specified as they would appear in source code. For - * example: "IOException" or "java.io.IOException". - * - * @param exceptionTypes the list of exception types - */ -public void setExceptions(String[] exceptionTypes); -/** - * The IDOMMethod refinement of this IDOMNode - * method sets the name of this method. The syntax for a method - * name is defined by Identifer of MethodDeclarator (JLS2 8.4). - *

          - * The name of a constructor is always null and thus it - * must not be set. - *

          - * - * @exception IllegalArgumentException if null is specified - */ -public void setName(String name) throws IllegalArgumentException; -/** - * Sets the types and names of parameters in this method in the order they are - * to be declared. If both types and names are null - * this indicates that this method has no parameters. - * The syntax for parameter names is defined by Formal Parameters (JLS2 8.4.1). - * The syntax for type names is defined by Formal Parameters (JLS2 8.4.1). - * Type names must be specified as they would appear in source code. For - * example: "File", "java.io.File", or - * "int[]". - * - * @param types the list of type names - * @param names the list of parameter name - * @exception IllegalArgumentException if the number of types and names do not - * match, or if either argument is null - */ -public void setParameters(String[] types, String[] names) throws IllegalArgumentException; -/** - * Sets the return type name. This has no effect on constructors. - * The syntax for return type name corresponds to ReturnType in - * MethodDeclaration (JLS2 8.4). Type names are specified as they appear in the - * source code; for example: "File", "java.io.File", - * "int[]", or "void". - * - * @param type the return type - * @exception IllegalArgumentException if null is specified - */ -public void setReturnType(String type) throws IllegalArgumentException; + /** + * Adds the given exception to the end of the list of exceptions this method + * is declared to throw. The syntax for an exception type name is defined by + * Method Throws (JLS2 8.4.4). Type names must be specified as they would + * appear in source code. For example: "IOException" or + * "java.io.IOException". This is a convenience method for + * setExceptions. + * + * @param exceptionType + * the exception type + * @exception IllegalArgumentException + * if null is specified + * @see #setExceptions + */ + public void addException(String exceptionType) + throws IllegalArgumentException; + + /** + * Adds the given parameter to the end of the parameter list. This is a + * convenience method for setParameters. The syntax for + * parameter names is defined by Formal Parameters (JLS2 8.4.1). The syntax + * for type names is defined by Formal Parameters (JLS2 8.4.1). Type names + * must be specified as they would appear in source code. For example: + * "File", "java.io.File", or + * "int[]". + * + * @param type + * the type name + * @param name + * the parameter name + * @exception IllegalArgumentException + * if null is specified for either the type or + * the name + * @see #setParameters + */ + public void addParameter(String type, String name) + throws IllegalArgumentException; + + /** + * Returns the body of this method. The method body includes all code + * following the method declaration, including the enclosing braces. + * + * @return the body, or null if the method has no body (for + * example, for an abstract or native method) + */ + public String getBody(); + + /** + * Returns the names of the exception types this method throws in the order + * in which they are declared in the source, or an empty array if this + * method declares no exception types. The syntax for an exception type name + * is defined by Method Throws (JLS2 8.4.4). Type names appear as they would + * in source code. For example: "IOException" or + * "java.io.IOException". + * + * @return the list of exception types + */ + public String[] getExceptions(); + + /** + * The IDOMMethod refinement of this IDOMNode + * method returns the name of this method. Returns null for + * constructors. The syntax for a method name is defined by Identifier of + * MethodDeclarator (JLS2 8.4). + */ + public String getName(); + + /** + * Returns the names of parameters in this method in the order they are + * declared, or null if no parameters are declared. The + * syntax for parameter names is defined by Formal Parameters (JLS2 8.4.1). + * + * @return the list of parameter names, or null if no + * parameters are declared + */ + public String[] getParameterNames(); + + /** + * Returns the type names for the parameters of this method in the order + * they are declared, or null if no parameters are declared. + * The syntax for type names is defined by Formal Parameters (JLS2 8.4.1). + * Type names must be specified as they would appear in source code. For + * example: "File", "java.io.File", or + * "int[]". + * + * @return the list of parameter types, or null if no + * parameters are declared + */ + public String[] getParameterTypes(); + + /** + * Returns the return type name, or null. Returns + * null for constructors. The syntax for return type name + * corresponds to ReturnType in MethodDeclaration (JLS2 8.4). Names are + * returned as they appear in the source code; for example: + * "File", "java.io.File", + * "int[]", or "void". + * + * @return the return type + */ + public String getReturnType(); + + /** + * Returns whether this method is a constructor. + * + * @return true for constructors, and false + * for methods + */ + public boolean isConstructor(); + + /** + * Sets the body of this method. The method body includes all code following + * the method declaration, including the enclosing braces. No formatting or + * syntax checking is performed on the body. + * + * @return the body, or null indicating the method has no + * body (for example, for an abstract or native method) + */ + public void setBody(String body); + + /** + * Sets whether this method represents a constructor. + * + * @param b + * true for constructors, and false + * for methods + */ + public void setConstructor(boolean b); + + /** + * Sets the names of the exception types this method throws, in the order in + * which they are declared in the source. An empty array indicates this + * method declares no exception types. The syntax for an exception type name + * is defined by Method Throws (JLS2 8.4.4). Type names must be specified as + * they would appear in source code. For example: "IOException" + * or "java.io.IOException". + * + * @param exceptionTypes + * the list of exception types + */ + public void setExceptions(String[] exceptionTypes); + + /** + * The IDOMMethod refinement of this IDOMNode + * method sets the name of this method. The syntax for a method name is + * defined by Identifer of MethodDeclarator (JLS2 8.4). + *

          + * The name of a constructor is always null and thus it must + * not be set. + *

          + * + * @exception IllegalArgumentException + * if null is specified + */ + public void setName(String name) throws IllegalArgumentException; + + /** + * Sets the types and names of parameters in this method in the order they + * are to be declared. If both types and names + * are null this indicates that this method has no + * parameters. The syntax for parameter names is defined by Formal + * Parameters (JLS2 8.4.1). The syntax for type names is defined by Formal + * Parameters (JLS2 8.4.1). Type names must be specified as they would + * appear in source code. For example: "File", + * "java.io.File", or "int[]". + * + * @param types + * the list of type names + * @param names + * the list of parameter name + * @exception IllegalArgumentException + * if the number of types and names do not match, or if + * either argument is null + */ + public void setParameters(String[] types, String[] names) + throws IllegalArgumentException; + + /** + * Sets the return type name. This has no effect on constructors. The syntax + * for return type name corresponds to ReturnType in MethodDeclaration (JLS2 + * 8.4). Type names are specified as they appear in the source code; for + * example: "File", "java.io.File", + * "int[]", or "void". + * + * @param type + * the return type + * @exception IllegalArgumentException + * if null is specified + */ + public void setReturnType(String type) throws IllegalArgumentException; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMNode.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMNode.java index 9c61412..10a162b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMNode.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMNode.java @@ -14,265 +14,321 @@ import java.util.Enumeration; import net.sourceforge.phpdt.core.IJavaElement; - /** - * Nodes represent structural fragments of a Java source file, also known as document fragments. Their implementation - * is known as a DOM (Document Object Model) - in this case a JDOM (Java DOM). A root node (node - * with no parent or siblings) represents the root of a document fragment (DF). A complete Java document is - * represented by a compilation unit node (IDOMCompilationUnit). In this way, a DF is - * comprised of DFs, and a document itself (compilation unit) is also a DF. + * Nodes represent structural fragments of a Java source file, also known as + * document fragments. Their implementation is known as a DOM (Document Object + * Model) - in this case a JDOM (Java DOM). A root node (node with no parent or + * siblings) represents the root of a document fragment (DF). A complete Java + * document is represented by a compilation unit node (IDOMCompilationUnit). + * In this way, a DF is comprised of DFs, and a document itself (compilation + * unit) is also a DF. *

          - * A DF may be created empty and programmatically filled, or it may be created from - * a source code string. The IDOMFactory allows the creation of all kinds - * of nodes from source code strings. Manipulations performed on a DF are immediately - * reflected in the DF's contents. + * A DF may be created empty and programmatically filled, or it may be created + * from a source code string. The IDOMFactory allows the creation + * of all kinds of nodes from source code strings. Manipulations performed on a + * DF are immediately reflected in the DF's contents. *

          *

          - * Children fragments are represented as a linked list of nodes. Children are inserted via their parent node, and - * are automatically linked up with previous and next nodes. + * Children fragments are represented as a linked list of nodes. Children are + * inserted via their parent node, and are automatically linked up with previous + * and next nodes. *

          *

          - * The contents of any node (DF) may be retrieved at any time. In this way it is possible to retrieve - * source code representing fragments of the compilation unit (for example, a type or a method), since - * the contents of any node (not just the root node) may be obtained. + * The contents of any node (DF) may be retrieved at any time. In this way it is + * possible to retrieve source code representing fragments of the compilation + * unit (for example, a type or a method), since the contents of any node (not + * just the root node) may be obtained. *

          *

          * The following manipulations on DFs are distinct: *

            - *
          • clone - this creates a stand-alone copy of the DF that is in no way dependent on the DF that it was cloned from
          • - *
          • remove - this orphans a DF from its host DF. The removed DF may still be dependent on its previous host - * (perhaps to generate its contents), and hanging onto the fragment means that its previous host is also - * retained in memory.
          • - *
          • add/insert - this splices an un-parented DF (one that has been cloned, removed, or created stand-alone), - * into an existing DF such that the newly inserted DF is only dependent on its new host.
          • + *
          • clone - this creates a stand-alone copy of the DF that is in no way + * dependent on the DF that it was cloned from
          • + *
          • remove - this orphans a DF from its host DF. The removed DF may still be + * dependent on its previous host (perhaps to generate its contents), and + * hanging onto the fragment means that its previous host is also retained in + * memory.
          • + *
          • add/insert - this splices an un-parented DF (one that has been cloned, + * removed, or created stand-alone), into an existing DF such that the newly + * inserted DF is only dependent on its new host.
          • *
          *

          *

          - * Wherever types are specified in DOM APIs, type names must be specified as they would appear - * in source code. The DOM does not have a notion of type signatures, only raw text. Example type - * names are "Object", "java.io.File", and "int[]". + * Wherever types are specified in DOM APIs, type names must be specified as + * they would appear in source code. The DOM does not have a notion of type + * signatures, only raw text. Example type names are "Object", + * "java.io.File", and "int[]". *

          *

          * This interface is not intended to be implemented by clients. *

          */ -public interface IDOMNode extends Cloneable { +public interface IDOMNode extends Cloneable { /** - * Node type constant indicating a compilation unit. - * Nodes of this type maybe by safely cast to IDOMCompilationUnit. + * Node type constant indicating a compilation unit. Nodes of this type + * maybe by safely cast to IDOMCompilationUnit. + * * @see #getNodeType */ - public static int COMPILATION_UNIT= 1; - + public static int COMPILATION_UNIT = 1; + /** - * Node type constant indicating a package declaration. - * Nodes of this type maybe by safely cast to IDOMPackage. - * @see #getNodeType + * Node type constant indicating a package declaration. Nodes of this type + * maybe by safely cast to IDOMPackage. + * + * @see #getNodeType */ - public static int PACKAGE= 2; - + public static int PACKAGE = 2; + /** - * Node type constant indicating an import declaration. - * Nodes of this type maybe by safely cast to IDOMImport. + * Node type constant indicating an import declaration. Nodes of this type + * maybe by safely cast to IDOMImport. + * * @see #getNodeType */ - public static int IMPORT= 3; - + public static int IMPORT = 3; + /** - * Node type constant indicating a type declaration. - * Nodes of this type maybe by safely cast to IDOMType. + * Node type constant indicating a type declaration. Nodes of this type + * maybe by safely cast to IDOMType. + * * @see #getNodeType */ - public static int TYPE= 4; - + public static int TYPE = 4; + /** - * Node type constant indicating a field declaration. - * Nodes of this type maybe by safely cast to IDOMField. + * Node type constant indicating a field declaration. Nodes of this type + * maybe by safely cast to IDOMField. + * * @see #getNodeType */ - public static int FIELD= 5; - + public static int FIELD = 5; + /** * Node type constant indicating a method (or constructor) declaration. * Nodes of this type maybe by safely cast to IDOMMethod. + * * @see #getNodeType */ - public static int METHOD= 6; - + public static int METHOD = 6; + /** - * Node type constant indicating an initializer declaration. - * Nodes of this type maybe by safely cast to IDOMInitializer. + * Node type constant indicating an initializer declaration. Nodes of this + * type maybe by safely cast to IDOMInitializer. + * * @see #getNodeType */ - public static int INITIALIZER= 7; - -/** - * Adds the given un-parented node (document fragment) as the last child of this node. - * - * @param child the new child node - * @exception DOMException if any of the following conditions hold:
            - *
          • this node is not allowed to have children,
          • - *
          • the child is not of an allowable type
          • - *
          • the child already has a parent
          • - *
          • the child is an ancestor of this node
          • - *
          - * @exception IllegalArgumentException if the child is null - * - * @see #insertSibling - * @see #remove - */ -public void addChild(IDOMNode child) throws DOMException, IllegalArgumentException; -/** - * Returns whether this node is allowed to have children. - * - * @return true if this node can have children - */ -public boolean canHaveChildren(); -/** - * Returns a stand-alone copy of the document fragment represented by this node that - * is in no way dependent on the document this node is part of. - * - * @return a copy of type IDOMNode - * @see #addChild - * @see #insertSibling - * @see #remove - */ -public Object clone(); -/** - * Returns the current contents of this document fragment as a character array. - *

          - * Note: To obtain complete source for the ".java" file, ask a compilation unit - * node for its contents. - *

          - * - * @return the contents, or null if this node has no contents - */ -public char[] getCharacters(); -/** - * Returns the first named child of this node with the given name. - * - * @param name the name - * @return the child node, or null if no such child exists - */ -public IDOMNode getChild(String name); -/** - * Returns an enumeration of children of this node. Returns an empty enumeration - * if this node has no children (including nodes that cannot have children). - * Children appear in the order in which they are declared in the source code. - * - * @return an enumeration of the children - */ -public Enumeration getChildren(); -/** - * Returns the current contents of this document fragment. - *

          - * Note: To obtain complete source for the ".java" file, ask a compilation unit - * node for its contents. - *

          - * - * @return the contents, or null if this node has no contents - */ -public String getContents(); -/** - * Returns the first child of this node. - * Children appear in the order in which they exist in the source code. - * - * @return the first child, or null if this node has no children - * @see #getChildren - */ -public IDOMNode getFirstChild(); -/** - * Returns a handle for the Java element associated with this - * document fragment, based on the parent Java element. - * - * @param parent the parent Java element - * @exception IllegalArgumentException if the parent element is not - * of a valid parent type for this node - */ -public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException; -/** - * Returns the name of this node. - * More details are provided in each of the subtypes. - * - * @return the name, or null if it has no name - */ -public String getName(); -/** - * Returns the sibling node immediately following this node. - * - * @return the next node, or null if there is no following node - */ -public IDOMNode getNextNode(); -/** - * Returns the type of this node. - * - * @return one of the node type constants defined in IDOMNode - */ -public int getNodeType(); -/** - * Returns the parent of this node. - * - * @return the parent node, or null if this node does not have a - * parent - */ -public IDOMNode getParent(); -/** - * Returns the sibling node immediately preceding this node. - * - * @return the previous node, or null if there is no preceding node - */ -public IDOMNode getPreviousNode(); -/** - * Inserts the given un-parented node as a sibling of this node, immediately before - * this node. - * - * @param sibling the new sibling node - * @exception DOMException if any of the following conditions hold:
            - *
          • this node is a document fragment root
          • - *
          • the sibling is not of the correct type
          • - *
          • the sibling already has a parent
          • - *
          • this sibling is an ancestor of this node
          • - *
          - * @exception IllegalArgumentException if the sibling is null - * - * @see #addChild - * @see #clone - * @see #remove - */ -public void insertSibling(IDOMNode sibling) throws DOMException, IllegalArgumentException; -/** - * Returns whether the given node is an allowable child for this node. - * - * @param node the potential child node - * @return true if the given node is an allowable child - */ -public boolean isAllowableChild(IDOMNode node); -/** - * Returns whether this node's signature is equivalent to the given - * node's signature. In other words, if the nodes were siblings, - * would the declarations collide because they represent the same declaration. - * - * @param node the other node - * @return true if the nodes have equivalent signatures - */ -public boolean isSignatureEqual(IDOMNode node); -/** - * Separates this node from its parent and siblings, maintaining any ties that this node - * has to the underlying document fragment. A document fragment that is removed - * from its host document may still be dependent on that host document until it is - * inserted into a different document. Removing a root node has no effect. - * - * @see #addChild - * @see #clone - * @see #insertSibling - */ -public void remove(); -/** - * Sets the name of this node. Name format depends on node type. - * More details are provided in each of the subtypes. - * - * @param name the name, or null to clear the name - */ -public void setName(String name); + public static int INITIALIZER = 7; + + /** + * Adds the given un-parented node (document fragment) as the last child of + * this node. + * + * @param child + * the new child node + * @exception DOMException + * if any of the following conditions hold: + *
            + *
          • this node is not allowed to have children,
          • + *
          • the child is not of an allowable type
          • + *
          • the child already has a parent
          • + *
          • the child is an ancestor of this node
          • + *
          + * @exception IllegalArgumentException + * if the child is null + * + * @see #insertSibling + * @see #remove + */ + public void addChild(IDOMNode child) throws DOMException, + IllegalArgumentException; + + /** + * Returns whether this node is allowed to have children. + * + * @return true if this node can have children + */ + public boolean canHaveChildren(); + + /** + * Returns a stand-alone copy of the document fragment represented by this + * node that is in no way dependent on the document this node is part of. + * + * @return a copy of type IDOMNode + * @see #addChild + * @see #insertSibling + * @see #remove + */ + public Object clone(); + + /** + * Returns the current contents of this document fragment as a character + * array. + *

          + * Note: To obtain complete source for the ".java" file, ask a compilation + * unit node for its contents. + *

          + * + * @return the contents, or null if this node has no contents + */ + public char[] getCharacters(); + + /** + * Returns the first named child of this node with the given name. + * + * @param name + * the name + * @return the child node, or null if no such child exists + */ + public IDOMNode getChild(String name); + + /** + * Returns an enumeration of children of this node. Returns an empty + * enumeration if this node has no children (including nodes that cannot + * have children). Children appear in the order in which they are declared + * in the source code. + * + * @return an enumeration of the children + */ + public Enumeration getChildren(); + + /** + * Returns the current contents of this document fragment. + *

          + * Note: To obtain complete source for the ".java" file, ask a compilation + * unit node for its contents. + *

          + * + * @return the contents, or null if this node has no contents + */ + public String getContents(); + + /** + * Returns the first child of this node. Children appear in the order in + * which they exist in the source code. + * + * @return the first child, or null if this node has no + * children + * @see #getChildren + */ + public IDOMNode getFirstChild(); + + /** + * Returns a handle for the Java element associated with this document + * fragment, based on the parent Java element. + * + * @param parent + * the parent Java element + * @exception IllegalArgumentException + * if the parent element is not of a valid parent type for + * this node + */ + public IJavaElement getJavaElement(IJavaElement parent) + throws IllegalArgumentException; + + /** + * Returns the name of this node. More details are provided in each of the + * subtypes. + * + * @return the name, or null if it has no name + */ + public String getName(); + + /** + * Returns the sibling node immediately following this node. + * + * @return the next node, or null if there is no following + * node + */ + public IDOMNode getNextNode(); + + /** + * Returns the type of this node. + * + * @return one of the node type constants defined in IDOMNode + */ + public int getNodeType(); + + /** + * Returns the parent of this node. + * + * @return the parent node, or null if this node does not + * have a parent + */ + public IDOMNode getParent(); + + /** + * Returns the sibling node immediately preceding this node. + * + * @return the previous node, or null if there is no + * preceding node + */ + public IDOMNode getPreviousNode(); + + /** + * Inserts the given un-parented node as a sibling of this node, immediately + * before this node. + * + * @param sibling + * the new sibling node + * @exception DOMException + * if any of the following conditions hold: + *
            + *
          • this node is a document fragment root
          • + *
          • the sibling is not of the correct type
          • + *
          • the sibling already has a parent
          • + *
          • this sibling is an ancestor of this node
          • + *
          + * @exception IllegalArgumentException + * if the sibling is null + * + * @see #addChild + * @see #clone + * @see #remove + */ + public void insertSibling(IDOMNode sibling) throws DOMException, + IllegalArgumentException; + + /** + * Returns whether the given node is an allowable child for this node. + * + * @param node + * the potential child node + * @return true if the given node is an allowable child + */ + public boolean isAllowableChild(IDOMNode node); + + /** + * Returns whether this node's signature is equivalent to the given node's + * signature. In other words, if the nodes were siblings, would the + * declarations collide because they represent the same declaration. + * + * @param node + * the other node + * @return true if the nodes have equivalent signatures + */ + public boolean isSignatureEqual(IDOMNode node); + + /** + * Separates this node from its parent and siblings, maintaining any ties + * that this node has to the underlying document fragment. A document + * fragment that is removed from its host document may still be dependent on + * that host document until it is inserted into a different document. + * Removing a root node has no effect. + * + * @see #addChild + * @see #clone + * @see #insertSibling + */ + public void remove(); + + /** + * Sets the name of this node. Name format depends on node type. More + * details are provided in each of the subtypes. + * + * @param name + * the name, or null to clear the name + */ + public void setName(String name); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMPackage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMPackage.java index 49333c8..c085d3a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMPackage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMPackage.java @@ -9,28 +9,31 @@ * IBM Corporation - initial API and implementation *******************************************************************************/ package net.sourceforge.phpdt.core.jdom; + /** - * Represents a package declaration. - * The corresponding syntactic unit is PackageDeclaration (JLS2 7.4). - * A Package has no children, and its parent is a compilation unit. + * Represents a package declaration. The corresponding syntactic unit is + * PackageDeclaration (JLS2 7.4). A Package has no children, and its parent is a + * compilation unit. *

          * This interface is not intended to be implemented by clients. *

          */ public interface IDOMPackage extends IDOMNode { -/** - * The IDOMPackage refinement of this IDOMNode - * method returns the name of this package declaration, or null - * if it has none. The syntax for a package name corresponds to PackageName - * as defined by PackageDeclaration (JLS2 7.4). - */ -public String getName(); -/** - * The IDOMPackage refinement of this IDOMNode - * method sets the name of this package declaration. The syntax for a package - * name corresponds to PackageName as defined by PackageDeclaration (JLS2 7.4). - * A null name indicates an empty package declaration; that is, - * getContents returns the empty string. - */ -public void setName(String name); + /** + * The IDOMPackage refinement of this IDOMNode + * method returns the name of this package declaration, or null + * if it has none. The syntax for a package name corresponds to PackageName + * as defined by PackageDeclaration (JLS2 7.4). + */ + public String getName(); + + /** + * The IDOMPackage refinement of this IDOMNode + * method sets the name of this package declaration. The syntax for a + * package name corresponds to PackageName as defined by PackageDeclaration + * (JLS2 7.4). A null name indicates an empty package + * declaration; that is, getContents returns the empty + * string. + */ + public void setName(String name); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMType.java index 5a4c62e..ef4c0ed 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMType.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMType.java @@ -11,117 +11,142 @@ package net.sourceforge.phpdt.core.jdom; /** - * Represents a source type in a compilation unit, either as a top-level type or a member type. - * The corresponding syntactic units are ClassDeclaration (JLS2 8.1) and InterfaceDeclaration (JLS2 9.1). + * Represents a source type in a compilation unit, either as a top-level type or + * a member type. The corresponding syntactic units are ClassDeclaration (JLS2 + * 8.1) and InterfaceDeclaration (JLS2 9.1). *

          - * Allowable child types for a type are IDOMType, IDOMField, - * IDOMMethod, and IDOMInitializer. - * Children are listed in the order in which they appear in the source. The parent of a type - * is a type (in the case of a member type) or a compilation unit (in the case of a top-level type). + * Allowable child types for a type are IDOMType, + * IDOMField, IDOMMethod, and + * IDOMInitializer. Children are listed in the order in which + * they appear in the source. The parent of a type is a type (in the case of a + * member type) or a compilation unit (in the case of a top-level type). *

          *

          * This interface is not intended to be implemented by clients. *

          */ public interface IDOMType extends IDOMMember { -/** - * Adds the given interface name to the names of interfaces that this type implements or extends - * (the name will be added after the existing interface names). This is a convenience method. - * - * For classes, this represents the interfaces that this class implements. - * For interfaces, this represents the interfaces that this interface extends. - * The name may or may not be fully qualified. - * - * @param interfaceName the syntax for an interface name is defined by - * Interfaces in ClassDeclaration (JLS2 8.1). Type names must be specified as they would - * appear in source code. For example: "Cloneable", "java.io.Serializable". - * - * @exception IllegalArgumentException if null is specified - */ -public void addSuperInterface(String interfaceName) throws IllegalArgumentException; -/** - * The IDOMType refinement of this IDOMNode - * method returns the name of this type. The name of a class is defined by - * ClassDeclaration (JLS2 8.1); the name of an interface is defined by - * InterfaceDeclaration (JLS2 9.1). - */ -public String getName(); -/** - * Returns the name of this type's superclass. The syntax for a superclass name - * is specified by Super in ClassDeclaration (JLS2 8.1). Type names must be - * specified as they would appear in source code. For example: - * "Object", or "java.io.File". - * - * @return the superclass name, or null if this type represents - * an interface or if no superclass has been assigned to this class - */ -public String getSuperclass(); -/** - * Returns the names of interfaces that this type implements or extends, - * in the order in which they are listed in the source, or an empty array - * if no superinterfaces are present. The syntax for interface names is - * defined by Interfaces in ClassDeclaration (JLS2 8.1). Type names appear - * as they would in source code. For example: "Cloneable", - * or "java.io.Serializable". - *

          - * For classes, this method returns the interfaces that this class implements. - * For interfaces, this method returns the interfaces that this interface extends. - *

          - * - * @return the list of interface names - */ -public String[] getSuperInterfaces(); -/** - * Returns whether this type is a class. - * - * @return true for classes, and false for interfaces - */ -public boolean isClass(); -/** - * Sets whether this type is a class or an interface. If this type is - * a class, and is changed to an interface, this type's superclass - * becomes null. When a class becomes an interface or an - * interface becomes a class, superinterfaces remain (as part of an - * implements clause for classes, or an extends - * clause for interfaces). - * - * @param b true for classes, and false for interfaces - */ -public void setClass(boolean b); -/** - * The IDOMType refinement of this IDOMNode - * method sets the name of this type. The name of a class is defined by - * ClassDeclaration (JLS2 8.1); the name of an interface is defined by - * InterfaceDeclaration (JLS2 9.1). - * - * @exception IllegalArgumentException if null is specified - */ -public void setName(String name) throws IllegalArgumentException; -/** - * Sets the name of this type's superclass. Has no effect if this type - * represents an interface. A null name indicates that no - * superclass name (extends clause) should appear in the source code. - * The syntax for a superclass name is specified by Super in ClassDeclaration - * (JLS2 8.1). Type names must be specified as they would appear in source code. - * For example: "Object", or "java.io.File". - * - * @param superclassName the superclass name, or null if this type - * should have to no explicitly specified superclass - */ -public void setSuperclass(String superclassName); -/** - * Sets the names of interfaces that this type implements or extends, - * in the order in which they are to be listed in the source. An empty array - * parameter indicates that no superinterfaces are present. The syntax for - * interface names is defined by Interfaces in ClassDeclaration (JLS2 8.1). - * Type names appear as they would in source code. For example: - * "Cloneable", or "java.io.Serializable". - *

          - * For classes, this method sets the interfaces that this class implements. - * For interfaces, this method sets the interfaces that this interface extends. - *

          - * - * @param interfaceNames the list of interface names - */ -public void setSuperInterfaces(String[] interfaceNames); + /** + * Adds the given interface name to the names of interfaces that this type + * implements or extends (the name will be added after the existing + * interface names). This is a convenience method. + * + * For classes, this represents the interfaces that this class implements. + * For interfaces, this represents the interfaces that this interface + * extends. The name may or may not be fully qualified. + * + * @param interfaceName + * the syntax for an interface name is defined by Interfaces in + * ClassDeclaration (JLS2 8.1). Type names must be specified as + * they would appear in source code. For example: "Cloneable", + * "java.io.Serializable". + * + * @exception IllegalArgumentException + * if null is specified + */ + public void addSuperInterface(String interfaceName) + throws IllegalArgumentException; + + /** + * The IDOMType refinement of this IDOMNode + * method returns the name of this type. The name of a class is defined by + * ClassDeclaration (JLS2 8.1); the name of an interface is defined by + * InterfaceDeclaration (JLS2 9.1). + */ + public String getName(); + + /** + * Returns the name of this type's superclass. The syntax for a superclass + * name is specified by Super in ClassDeclaration (JLS2 8.1). Type names + * must be specified as they would appear in source code. For example: + * "Object", or "java.io.File". + * + * @return the superclass name, or null if this type + * represents an interface or if no superclass has been assigned to + * this class + */ + public String getSuperclass(); + + /** + * Returns the names of interfaces that this type implements or extends, in + * the order in which they are listed in the source, or an empty array if no + * superinterfaces are present. The syntax for interface names is defined by + * Interfaces in ClassDeclaration (JLS2 8.1). Type names appear as they + * would in source code. For example: "Cloneable", or + * "java.io.Serializable". + *

          + * For classes, this method returns the interfaces that this class + * implements. For interfaces, this method returns the interfaces that this + * interface extends. + *

          + * + * @return the list of interface names + */ + public String[] getSuperInterfaces(); + + /** + * Returns whether this type is a class. + * + * @return true for classes, and false for + * interfaces + */ + public boolean isClass(); + + /** + * Sets whether this type is a class or an interface. If this type is a + * class, and is changed to an interface, this type's superclass becomes + * null. When a class becomes an interface or an interface + * becomes a class, superinterfaces remain (as part of an + * implements clause for classes, or an extends + * clause for interfaces). + * + * @param b + * true for classes, and false for + * interfaces + */ + public void setClass(boolean b); + + /** + * The IDOMType refinement of this IDOMNode + * method sets the name of this type. The name of a class is defined by + * ClassDeclaration (JLS2 8.1); the name of an interface is defined by + * InterfaceDeclaration (JLS2 9.1). + * + * @exception IllegalArgumentException + * if null is specified + */ + public void setName(String name) throws IllegalArgumentException; + + /** + * Sets the name of this type's superclass. Has no effect if this type + * represents an interface. A null name indicates that no + * superclass name (extends clause) should appear in the source code. The + * syntax for a superclass name is specified by Super in ClassDeclaration + * (JLS2 8.1). Type names must be specified as they would appear in source + * code. For example: "Object", or + * "java.io.File". + * + * @param superclassName + * the superclass name, or null if this type + * should have to no explicitly specified superclass + */ + public void setSuperclass(String superclassName); + + /** + * Sets the names of interfaces that this type implements or extends, in the + * order in which they are to be listed in the source. An empty array + * parameter indicates that no superinterfaces are present. The syntax for + * interface names is defined by Interfaces in ClassDeclaration (JLS2 8.1). + * Type names appear as they would in source code. For example: + * "Cloneable", or "java.io.Serializable". + *

          + * For classes, this method sets the interfaces that this class implements. + * For interfaces, this method sets the interfaces that this interface + * extends. + *

          + * + * @param interfaceNames + * the list of interface names + */ + public void setSuperInterfaces(String[] interfaceNames); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/search/IJavaSearchConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/search/IJavaSearchConstants.java index 6c3a8ea..edf7402 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/search/IJavaSearchConstants.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/search/IJavaSearchConstants.java @@ -10,7 +10,7 @@ *******************************************************************************/ package net.sourceforge.phpdt.core.search; -//import net.sourceforge.phpdt.internal.core.search.processing.*; +// import net.sourceforge.phpdt.internal.core.search.processing.*; /** *

          @@ -19,164 +19,167 @@ package net.sourceforge.phpdt.core.search; *

          * This interface declares constants only; it is not intended to be implemented. *

          + * * @see org.eclipse.jdt.core.search.SearchEngine */ public interface IJavaSearchConstants { /** - * The nature of searched element or the nature - * of match in unknown. + * The nature of searched element or the nature of match in unknown. */ int UNKNOWN = -1; - + /* Nature of searched element */ - + /** * The searched element is a type. */ - int TYPE= 0; + int TYPE = 0; /** * The searched element is a method. */ - int METHOD= 1; + int METHOD = 1; /** * The searched element is a package. */ - int PACKAGE= 2; + int PACKAGE = 2; /** * The searched element is a constructor. */ - int CONSTRUCTOR= 3; + int CONSTRUCTOR = 3; /** * The searched element is a field. */ - int FIELD= 4; + int FIELD = 4; /** - * The searched element is a class. - * More selective than using TYPE + * The searched element is a class. More selective than using TYPE */ - int CLASS= 5; + int CLASS = 5; /** - * The searched element is an interface. - * More selective than using TYPE + * The searched element is an interface. More selective than using TYPE */ - int INTERFACE= 6; + int INTERFACE = 6; /* Nature of match */ - + /** - * The search result is a declaration. - * Can be used in conjunction with any of the nature of searched elements - * so as to better narrow down the search. + * The search result is a declaration. Can be used in conjunction with any + * of the nature of searched elements so as to better narrow down the + * search. */ - int DECLARATIONS= 0; + int DECLARATIONS = 0; /** - * The search result is a type that implements an interface. - * Used in conjunction with either TYPE or CLASS or INTERFACE, it will - * respectively search for any type implementing/extending an interface, or - * rather exclusively search for classes implementing an interface, or interfaces + * The search result is a type that implements an interface. Used in + * conjunction with either TYPE or CLASS or INTERFACE, it will respectively + * search for any type implementing/extending an interface, or rather + * exclusively search for classes implementing an interface, or interfaces * extending an interface. */ - int IMPLEMENTORS= 1; + int IMPLEMENTORS = 1; /** - * The search result is a reference. - * Can be used in conjunction with any of the nature of searched elements - * so as to better narrow down the search. - * References can contain implementers since they are more generic kind - * of matches. + * The search result is a reference. Can be used in conjunction with any of + * the nature of searched elements so as to better narrow down the search. + * References can contain implementers since they are more generic kind of + * matches. */ - int REFERENCES= 2; + int REFERENCES = 2; /** - * The search result is a declaration, a reference, or an implementer - * of an interface. - * Can be used in conjunction with any of the nature of searched elements - * so as to better narrow down the search. + * The search result is a declaration, a reference, or an implementer of an + * interface. Can be used in conjunction with any of the nature of searched + * elements so as to better narrow down the search. */ - int ALL_OCCURRENCES= 3; + int ALL_OCCURRENCES = 3; /** - * When searching for field matches, it will exclusively find read accesses, as - * opposed to write accesses. Note that some expressions are considered both - * as field read/write accesses: for example, x++; x+= 1; + * When searching for field matches, it will exclusively find read accesses, + * as opposed to write accesses. Note that some expressions are considered + * both as field read/write accesses: for example, x++; x+= 1; * * @since 2.0 */ int READ_ACCESSES = 4; - + /** - * When searching for field matches, it will exclusively find write accesses, as - * opposed to read accesses. Note that some expressions are considered both - * as field read/write accesses: for example, x++; x+= 1; + * When searching for field matches, it will exclusively find write + * accesses, as opposed to read accesses. Note that some expressions are + * considered both as field read/write accesses: for example, x++; x+= 1; * * @since 2.0 */ int WRITE_ACCESSES = 5; - + /* Syntactic match modes */ - + /** - * The search pattern matches exactly the search result, - * that is, the source of the search result equals the search pattern. + * The search pattern matches exactly the search result, that is, the source + * of the search result equals the search pattern. + * * @deprecated Use {@link SearchPattern#R_EXACT_MATCH} instead. */ int EXACT_MATCH = 0; + /** * The search pattern is a prefix of the search result. + * * @deprecated Use {@link SearchPattern#R_PREFIX_MATCH} instead. */ int PREFIX_MATCH = 1; + /** - * The search pattern contains one or more wild cards ('*') where a + * The search pattern contains one or more wild cards ('*') where a * wild-card can replace 0 or more characters in the search result. + * * @deprecated Use {@link SearchPattern#R_PATTERN_MATCH} instead. */ int PATTERN_MATCH = 2; - /* Case sensitivity */ - + /** - * The search pattern matches the search result only - * if cases are the same. - * @deprecated Use the methods that take the matchMode - * with {@link SearchPattern#R_CASE_SENSITIVE} as a matchRule instead. + * The search pattern matches the search result only if cases are the same. + * + * @deprecated Use the methods that take the matchMode with + * {@link SearchPattern#R_CASE_SENSITIVE} as a matchRule + * instead. */ boolean CASE_SENSITIVE = true; + /** * The search pattern ignores cases in the search result. - * @deprecated Use the methods that take the matchMode - * without {@link SearchPattern#R_CASE_SENSITIVE} as a matchRule instead. + * + * @deprecated Use the methods that take the matchMode without + * {@link SearchPattern#R_CASE_SENSITIVE} as a matchRule + * instead. */ boolean CASE_INSENSITIVE = false; - /* Waiting policies */ - + /** * The search operation starts immediately, even if the underlying indexer - * has not finished indexing the workspace. Results will more likely - * not contain all the matches. + * has not finished indexing the workspace. Results will more likely not + * contain all the matches. */ -// int FORCE_IMMEDIATE_SEARCH = IJob.ForceImmediate; + // int FORCE_IMMEDIATE_SEARCH = IJob.ForceImmediate; /** - * The search operation throws an org.eclipse.core.runtime.OperationCanceledException - * if the underlying indexer has not finished indexing the workspace. + * The search operation throws an + * org.eclipse.core.runtime.OperationCanceledException if the + * underlying indexer has not finished indexing the workspace. */ -// int CANCEL_IF_NOT_READY_TO_SEARCH = IJob.CancelIfNotReady; + // int CANCEL_IF_NOT_READY_TO_SEARCH = IJob.CancelIfNotReady; /** - * The search operation waits for the underlying indexer to finish indexing + * The search operation waits for the underlying indexer to finish indexing * the workspace before starting the search. */ -// int WAIT_UNTIL_READY_TO_SEARCH = IJob.WaitUntilReady; - - + // int WAIT_UNTIL_READY_TO_SEARCH = IJob.WaitUntilReady; + } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/search/ITypeNameRequestor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/search/ITypeNameRequestor.java index 776560a..28da0ca 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/search/ITypeNameRequestor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/search/ITypeNameRequestor.java @@ -11,51 +11,71 @@ package net.sourceforge.phpdt.core.search; /** - * A ITypeNameRequestor collects search results from a searchAllTypeNames - * query to a SearchEngine. Clients must implement this interface and pass - * an instance to the searchAllTypeNames(...) method. Only top-level and - * member types are reported. Local types are not reported. + * A ITypeNameRequestor collects search results from a + * searchAllTypeNames query to a SearchEngine. + * Clients must implement this interface and pass an instance to the + * searchAllTypeNames(...) method. Only top-level and member + * types are reported. Local types are not reported. *

          * This interface may be implemented by clients. *

          */ public interface ITypeNameRequestor { -/** - * Accepts a top-level or a member class. - * - * @param packageName the dot-separated name of the package of the class - * @param simpleTypeName the simple name of the class - * @param enclosingTypeNames if the class is a member type, - * the simple names of the enclosing types from the outer-most to the - * direct parent of the class (for example, if the class is x.y.A$B$C then - * the enclosing types are [A, B]. This is an empty array if the class - * is a top-level type. - * @param path the full path to the resource containing the class. If the resource is a .class file - * or a .java file, this is the full path in the workspace to this resource. If the - * resource is an archive (that is, a .zip or .jar file), the path is composed of 2 paths separated - * by IJavaSearchScope.JAR_FILE_ENTRY_SEPARATOR: - * the first path is the full OS path to the archive (if it is an external archive), - * or the workspace relative IPath to the archive (if it is an internal archive), - * the second path is the path to the resource inside the archive. - */ -void acceptClass(char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path); -/** - * Accepts a top-level or a member interface. - * - * @param packageName the dot-separated name of the package of the interface - * @param simpleTypeName the simple name of the interface - * @param enclosingTypeNames if the interface is a member type, - * the simple names of the enclosing types from the outer-most to the - * direct parent of the interface (for example, if the interface is x.y.A$B$I then - * the enclosing types are [A, B]. This is an empty array if the interface - * is a top-level type. - * @param path the full path to the resource containing the interface. If the resource is a .class file - * or a .java file, this is the full path in the workspace to this resource. If the - * resource is an archive (that is, a .zip or .jar file), the path is composed of 2 paths separated - * by IJavaSearchScope.JAR_FILE_ENTRY_SEPARATOR: - * the first path is the full OS path to the archive (if it is an external archive), - * or the workspace relative IPath to the archive (if it is an internal archive), - * the second path is the path to the resource inside the archive. - * */ -void acceptInterface(char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path); + /** + * Accepts a top-level or a member class. + * + * @param packageName + * the dot-separated name of the package of the class + * @param simpleTypeName + * the simple name of the class + * @param enclosingTypeNames + * if the class is a member type, the simple names of the + * enclosing types from the outer-most to the direct parent of + * the class (for example, if the class is x.y.A$B$C then the + * enclosing types are [A, B]. This is an empty array if the + * class is a top-level type. + * @param path + * the full path to the resource containing the class. If the + * resource is a .class file or a .java file, this is the full + * path in the workspace to this resource. If the resource is an + * archive (that is, a .zip or .jar file), the path is composed + * of 2 paths separated by + * IJavaSearchScope.JAR_FILE_ENTRY_SEPARATOR: the + * first path is the full OS path to the archive (if it is an + * external archive), or the workspace relative + * IPath to the archive (if it is an internal + * archive), the second path is the path to the resource inside + * the archive. + */ + void acceptClass(char[] packageName, char[] simpleTypeName, + char[][] enclosingTypeNames, String path); + + /** + * Accepts a top-level or a member interface. + * + * @param packageName + * the dot-separated name of the package of the interface + * @param simpleTypeName + * the simple name of the interface + * @param enclosingTypeNames + * if the interface is a member type, the simple names of the + * enclosing types from the outer-most to the direct parent of + * the interface (for example, if the interface is x.y.A$B$I then + * the enclosing types are [A, B]. This is an empty array if the + * interface is a top-level type. + * @param path + * the full path to the resource containing the interface. If the + * resource is a .class file or a .java file, this is the full + * path in the workspace to this resource. If the resource is an + * archive (that is, a .zip or .jar file), the path is composed + * of 2 paths separated by + * IJavaSearchScope.JAR_FILE_ENTRY_SEPARATOR: the + * first path is the full OS path to the archive (if it is an + * external archive), or the workspace relative + * IPath to the archive (if it is an internal + * archive), the second path is the path to the resource inside + * the archive. + */ + void acceptInterface(char[] packageName, char[] simpleTypeName, + char[][] enclosingTypeNames, String path); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/corext/refactoring/nls/NLSElement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/corext/refactoring/nls/NLSElement.java index 11bbf94..992ce02 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/corext/refactoring/nls/NLSElement.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/corext/refactoring/nls/NLSElement.java @@ -15,13 +15,17 @@ import org.eclipse.jface.util.Assert; public class NLSElement { - public static final String TAG_PREFIX= "//$NON-NLS-"; //$NON-NLS-1$ - public static final int TAG_PREFIX_LENGTH= TAG_PREFIX.length(); - public static final String TAG_POSTFIX= "$"; //$NON-NLS-1$ - public static final int TAG_POSTFIX_LENGTH= TAG_POSTFIX.length(); + public static final String TAG_PREFIX = "//$NON-NLS-"; //$NON-NLS-1$ + + public static final int TAG_PREFIX_LENGTH = TAG_PREFIX.length(); + + public static final String TAG_POSTFIX = "$"; //$NON-NLS-1$ + + public static final int TAG_POSTFIX_LENGTH = TAG_POSTFIX.length(); /** The original string denoted by the position */ private String fValue; + /** The position of the original string */ private Region fPosition; @@ -35,14 +39,15 @@ public class NLSElement { * Creates a new NLS element for the given string and position. */ public NLSElement(String value, int start, int length, int index) { - fValue= value; - fIndex= index; + fValue = value; + fIndex = index; Assert.isNotNull(fValue); - fPosition= new Region(start, length); + fPosition = new Region(start, length); } /** * Returns the position of the string to be NLSed. + * * @return Returns the position of the string to be NLSed */ public Region getPosition() { @@ -51,6 +56,7 @@ public class NLSElement { /** * Returns the actual string value. + * * @return the actual string value */ public String getValue() { @@ -61,27 +67,28 @@ public class NLSElement { * Sets the actual string value. */ public void setValue(String value) { - fValue= value; + fValue = value; } /** * Sets the tag position if one is associated with the NLS element. */ public void setTagPosition(int start, int length) { - fTagPosition= new Region(start, length); + fTagPosition = new Region(start, length); } /** - * Returns the tag position for this element. The method can return null. - * In this case no tag has been found for this NLS element. + * Returns the tag position for this element. The method can return + * null. In this case no tag has been found for this NLS + * element. */ public Region getTagPosition() { return fTagPosition; } /** - * Returns true if the NLS element has an assicated $NON-NLS-*$ tag. - * Otherwise false is returned. + * Returns true if the NLS element has an assicated + * $NON-NLS-*$ tag. Otherwise false is returned. */ public boolean hasTag() { return fTagPosition != null && fTagPosition.getLength() > 0; @@ -95,13 +102,11 @@ public class NLSElement { return TAG_PREFIX + (fIndex + 1) + TAG_POSTFIX; } - /* (Non-Javadoc) - * Method declared in Object. - * only for debugging + /* + * (Non-Javadoc) Method declared in Object. only for debugging */ public String toString() { return fPosition + ": " + fValue + " Tag position: " + //$NON-NLS-2$ //$NON-NLS-1$ (hasTag() ? fTagPosition.toString() : "no tag found"); //$NON-NLS-1$ } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/corext/refactoring/nls/NLSLine.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/corext/refactoring/nls/NLSLine.java index 92e1df2..0dc8095 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/corext/refactoring/nls/NLSLine.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/corext/refactoring/nls/NLSLine.java @@ -19,18 +19,19 @@ import org.eclipse.jface.util.Assert; public class NLSLine { private int fLineNumber; + private List fElements; public NLSLine(int lineNumber) { - fLineNumber= lineNumber; + fLineNumber = lineNumber; Assert.isTrue(fLineNumber >= 0); - fElements= new ArrayList(); + fElements = new ArrayList(); } - + public int getLineNumber() { return fLineNumber; } - + /** * Adds a NLS element to this line. */ @@ -38,31 +39,33 @@ public class NLSLine { Assert.isNotNull(element); fElements.add(element); } - + public NLSElement[] getElements() { - return (NLSElement[]) fElements.toArray(new NLSElement[fElements.size()]); + return (NLSElement[]) fElements + .toArray(new NLSElement[fElements.size()]); } - + public NLSElement get(int index) { - return (NLSElement)fElements.get(index); + return (NLSElement) fElements.get(index); } - + public boolean exists(int index) { return index >= 0 && index < fElements.size(); } - - public int size(){ + + public int size() { return fElements.size(); } - - /* non javaDoc - * only for debugging + + /* + * non javaDoc only for debugging + * * @see Object#toString() */ public String toString() { - StringBuffer result= new StringBuffer(); + StringBuffer result = new StringBuffer(); result.append("Line: " + fLineNumber + "\n"); //$NON-NLS-2$ //$NON-NLS-1$ - for (Iterator iter= fElements.iterator(); iter.hasNext(); ) { + for (Iterator iter = fElements.iterator(); iter.hasNext();) { result.append("\t"); //$NON-NLS-1$ result.append(iter.next().toString()); result.append("\n"); //$NON-NLS-1$ @@ -70,4 +73,3 @@ public class NLSLine { return result.toString(); } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/ISearchRequestor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/ISearchRequestor.java index e430c5b..c2ae18c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/ISearchRequestor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/ISearchRequestor.java @@ -11,50 +11,51 @@ package net.sourceforge.phpdt.internal.codeassist; /** - * This is the internal requestor passed to the searchable name environment - * so as to process the multiple search results as they are discovered. - * - * It is used to allow the code assist engine to add some more information - * to the raw name environment results before answering them to the UI. + * This is the internal requestor passed to the searchable name environment so + * as to process the multiple search results as they are discovered. + * + * It is used to allow the code assist engine to add some more information to + * the raw name environment results before answering them to the UI. */ public interface ISearchRequestor { - + /** * One result of the search consists of a new class. - * + * * NOTE - All package and type names are presented in their readable form: - * Package names are in the form "a.b.c". - * Nested type names are in the qualified form "A.M". - * The default package is represented by an empty array. + * Package names are in the form "a.b.c". Nested type names are in the + * qualified form "A.M". The default package is represented by an empty + * array. */ public void acceptClass(char[] packageName, char[] typeName, int modifiers); /** * One result of the search consists of a new interface. - * + * * NOTE - All package and type names are presented in their readable form: - * Package names are in the form "a.b.c". - * Nested type names are in the qualified form "A.I". - * The default package is represented by an empty array. + * Package names are in the form "a.b.c". Nested type names are in the + * qualified form "A.I". The default package is represented by an empty + * array. */ - public void acceptInterface(char[] packageName, char[] typeName, int modifiers); + public void acceptInterface(char[] packageName, char[] typeName, + int modifiers); /** * One result of the search consists of a new package. - * - * NOTE - All package names are presented in their readable form: - * Package names are in the form "a.b.c". - * The default package is represented by an empty array. + * + * NOTE - All package names are presented in their readable form: Package + * names are in the form "a.b.c". The default package is represented by an + * empty array. */ public void acceptPackage(char[] packageName); /** * One result of the search consists of a new type. - * + * * NOTE - All package and type names are presented in their readable form: - * Package names are in the form "a.b.c". - * Nested type names are in the qualified form "A.M". - * The default package is represented by an empty array. + * Package names are in the form "a.b.c". Nested type names are in the + * qualified form "A.M". The default package is represented by an empty + * array. */ public void acceptType(char[] packageName, char[] typeName); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/ISearchableNameEnvironment.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/ISearchableNameEnvironment.java index 57cfbd5..e981f01 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/ISearchableNameEnvironment.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/ISearchableNameEnvironment.java @@ -13,36 +13,35 @@ package net.sourceforge.phpdt.internal.codeassist; import net.sourceforge.phpdt.internal.compiler.env.INameEnvironment; /** - * This interface defines the API that may be used to implement any - * search-based tool (such as a CodeAssist, a Finder, ...). - * It is mainly used to hide from the search tool the implementation - * of the underlying environment and its constructions. + * This interface defines the API that may be used to implement any search-based + * tool (such as a CodeAssist, a Finder, ...). It is mainly used to hide from + * the search tool the implementation of the underlying environment and its + * constructions. */ public interface ISearchableNameEnvironment extends INameEnvironment { /** - * Find the packages that start with the given prefix. - * A valid prefix is a qualified name separated by periods - * (ex. java.util). - * The packages found are passed to: - * ISearchRequestor.acceptPackage(char[][] packageName) + * Find the packages that start with the given prefix. A valid prefix is a + * qualified name separated by periods (ex. java.util). The packages found + * are passed to: ISearchRequestor.acceptPackage(char[][] packageName) */ void findPackages(char[] prefix, ISearchRequestor requestor); /** - * Find the top-level types (classes and interfaces) that are defined - * in the current environment and whose name starts with the - * given prefix. The prefix is a qualified name separated by periods - * or a simple name (ex. java.util.V or V). - * + * Find the top-level types (classes and interfaces) that are defined in the + * current environment and whose name starts with the given prefix. The + * prefix is a qualified name separated by periods or a simple name (ex. + * java.util.V or V). + * * The types found are passed to one of the following methods (if additional * information is known about the types): - * ISearchRequestor.acceptType(char[][] packageName, char[] typeName) - * ISearchRequestor.acceptClass(char[][] packageName, char[] typeName, int modifiers) - * ISearchRequestor.acceptInterface(char[][] packageName, char[] typeName, int modifiers) - * - * This method can not be used to find member types... member - * types are found relative to their enclosing type. + * ISearchRequestor.acceptType(char[][] packageName, char[] typeName) + * ISearchRequestor.acceptClass(char[][] packageName, char[] typeName, int + * modifiers) ISearchRequestor.acceptInterface(char[][] packageName, char[] + * typeName, int modifiers) + * + * This method can not be used to find member types... member types are + * found relative to their enclosing type. */ void findTypes(char[] prefix, ISearchRequestor requestor); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/impl/AssistOptions.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/impl/AssistOptions.java index 3244c02..46d07d4 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/impl/AssistOptions.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/impl/AssistOptions.java @@ -18,48 +18,58 @@ public class AssistOptions { /** * Option IDs */ - public static final String OPTION_PerformVisibilityCheck = - "net.sourceforge.phpdt.core.codeComplete.visibilityCheck"; //$NON-NLS-1$ - public static final String OPTION_ForceImplicitQualification = - "net.sourceforge.phpdt.core.codeComplete.forceImplicitQualification"; //$NON-NLS-1$ - public static final String OPTION_FieldPrefixes = - "net.sourceforge.phpdt.core.codeComplete.fieldPrefixes"; //$NON-NLS-1$ - public static final String OPTION_StaticFieldPrefixes = - "net.sourceforge.phpdt.core.codeComplete.staticFieldPrefixes"; //$NON-NLS-1$ - public static final String OPTION_LocalPrefixes = - "net.sourceforge.phpdt.core.codeComplete.localPrefixes"; //$NON-NLS-1$ - public static final String OPTION_ArgumentPrefixes = - "net.sourceforge.phpdt.core.codeComplete.argumentPrefixes"; //$NON-NLS-1$ - public static final String OPTION_FieldSuffixes = - "net.sourceforge.phpdt.core.codeComplete.fieldSuffixes"; //$NON-NLS-1$ - public static final String OPTION_StaticFieldSuffixes = - "net.sourceforge.phpdt.core.codeComplete.staticFieldSuffixes"; //$NON-NLS-1$ - public static final String OPTION_LocalSuffixes = - "net.sourceforge.phpdt.core.codeComplete.localSuffixes"; //$NON-NLS-1$ - public static final String OPTION_ArgumentSuffixes = - "net.sourceforge.phpdt.core.codeComplete.argumentSuffixes"; //$NON-NLS-1$ + public static final String OPTION_PerformVisibilityCheck = "net.sourceforge.phpdt.core.codeComplete.visibilityCheck"; //$NON-NLS-1$ + + public static final String OPTION_ForceImplicitQualification = "net.sourceforge.phpdt.core.codeComplete.forceImplicitQualification"; //$NON-NLS-1$ + + public static final String OPTION_FieldPrefixes = "net.sourceforge.phpdt.core.codeComplete.fieldPrefixes"; //$NON-NLS-1$ + + public static final String OPTION_StaticFieldPrefixes = "net.sourceforge.phpdt.core.codeComplete.staticFieldPrefixes"; //$NON-NLS-1$ + + public static final String OPTION_LocalPrefixes = "net.sourceforge.phpdt.core.codeComplete.localPrefixes"; //$NON-NLS-1$ + + public static final String OPTION_ArgumentPrefixes = "net.sourceforge.phpdt.core.codeComplete.argumentPrefixes"; //$NON-NLS-1$ + + public static final String OPTION_FieldSuffixes = "net.sourceforge.phpdt.core.codeComplete.fieldSuffixes"; //$NON-NLS-1$ + + public static final String OPTION_StaticFieldSuffixes = "net.sourceforge.phpdt.core.codeComplete.staticFieldSuffixes"; //$NON-NLS-1$ + + public static final String OPTION_LocalSuffixes = "net.sourceforge.phpdt.core.codeComplete.localSuffixes"; //$NON-NLS-1$ + + public static final String OPTION_ArgumentSuffixes = "net.sourceforge.phpdt.core.codeComplete.argumentSuffixes"; //$NON-NLS-1$ + public static final String ENABLED = "enabled"; //$NON-NLS-1$ + public static final String DISABLED = "disabled"; //$NON-NLS-1$ public boolean checkVisibility = false; + public boolean forceImplicitQualification = false; + public char[][] fieldPrefixes = null; + public char[][] staticFieldPrefixes = null; + public char[][] localPrefixes = null; + public char[][] argumentPrefixes = null; + public char[][] fieldSuffixes = null; + public char[][] staticFieldSuffixes = null; + public char[][] localSuffixes = null; + public char[][] argumentSuffixes = null; - /** + /** * Initializing the assist options with default settings */ public AssistOptions() { // Initializing the assist options with default settings } - /** + /** * Initializing the assist options with external settings */ public AssistOptions(Map settings) { @@ -68,6 +78,7 @@ public class AssistOptions { set(settings); } + public void set(Map optionsMap) { Object optionValue; @@ -88,8 +99,9 @@ public class AssistOptions { if ((optionValue = optionsMap.get(OPTION_FieldPrefixes)) != null) { if (optionValue instanceof String) { String stringValue = (String) optionValue; - if (stringValue.length() > 0){ - this.fieldPrefixes = CharOperation.splitAndTrimOn(',', stringValue.toCharArray()); + if (stringValue.length() > 0) { + this.fieldPrefixes = CharOperation.splitAndTrimOn(',', + stringValue.toCharArray()); } else { this.fieldPrefixes = null; } @@ -98,8 +110,9 @@ public class AssistOptions { if ((optionValue = optionsMap.get(OPTION_StaticFieldPrefixes)) != null) { if (optionValue instanceof String) { String stringValue = (String) optionValue; - if (stringValue.length() > 0){ - this.staticFieldPrefixes = CharOperation.splitAndTrimOn(',', stringValue.toCharArray()); + if (stringValue.length() > 0) { + this.staticFieldPrefixes = CharOperation.splitAndTrimOn( + ',', stringValue.toCharArray()); } else { this.staticFieldPrefixes = null; } @@ -108,8 +121,9 @@ public class AssistOptions { if ((optionValue = optionsMap.get(OPTION_LocalPrefixes)) != null) { if (optionValue instanceof String) { String stringValue = (String) optionValue; - if (stringValue.length() > 0){ - this.localPrefixes = CharOperation.splitAndTrimOn(',', stringValue.toCharArray()); + if (stringValue.length() > 0) { + this.localPrefixes = CharOperation.splitAndTrimOn(',', + stringValue.toCharArray()); } else { this.localPrefixes = null; } @@ -118,8 +132,9 @@ public class AssistOptions { if ((optionValue = optionsMap.get(OPTION_ArgumentPrefixes)) != null) { if (optionValue instanceof String) { String stringValue = (String) optionValue; - if (stringValue.length() > 0){ - this.argumentPrefixes = CharOperation.splitAndTrimOn(',', stringValue.toCharArray()); + if (stringValue.length() > 0) { + this.argumentPrefixes = CharOperation.splitAndTrimOn(',', + stringValue.toCharArray()); } else { this.argumentPrefixes = null; } @@ -128,8 +143,9 @@ public class AssistOptions { if ((optionValue = optionsMap.get(OPTION_FieldSuffixes)) != null) { if (optionValue instanceof String) { String stringValue = (String) optionValue; - if (stringValue.length() > 0){ - this.fieldSuffixes = CharOperation.splitAndTrimOn(',', stringValue.toCharArray()); + if (stringValue.length() > 0) { + this.fieldSuffixes = CharOperation.splitAndTrimOn(',', + stringValue.toCharArray()); } else { this.fieldSuffixes = null; } @@ -138,8 +154,9 @@ public class AssistOptions { if ((optionValue = optionsMap.get(OPTION_StaticFieldSuffixes)) != null) { if (optionValue instanceof String) { String stringValue = (String) optionValue; - if (stringValue.length() > 0){ - this.staticFieldSuffixes = CharOperation.splitAndTrimOn(',', stringValue.toCharArray()); + if (stringValue.length() > 0) { + this.staticFieldSuffixes = CharOperation.splitAndTrimOn( + ',', stringValue.toCharArray()); } else { this.staticFieldSuffixes = null; } @@ -148,8 +165,9 @@ public class AssistOptions { if ((optionValue = optionsMap.get(OPTION_LocalSuffixes)) != null) { if (optionValue instanceof String) { String stringValue = (String) optionValue; - if (stringValue.length() > 0){ - this.localSuffixes = CharOperation.splitAndTrimOn(',', stringValue.toCharArray()); + if (stringValue.length() > 0) { + this.localSuffixes = CharOperation.splitAndTrimOn(',', + stringValue.toCharArray()); } else { this.localSuffixes = null; } @@ -158,8 +176,9 @@ public class AssistOptions { if ((optionValue = optionsMap.get(OPTION_ArgumentSuffixes)) != null) { if (optionValue instanceof String) { String stringValue = (String) optionValue; - if (stringValue.length() > 0){ - this.argumentSuffixes = CharOperation.splitAndTrimOn(',', stringValue.toCharArray()); + if (stringValue.length() > 0) { + this.argumentSuffixes = CharOperation.splitAndTrimOn(',', + stringValue.toCharArray()); } else { this.argumentSuffixes = null; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ASTVisitor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ASTVisitor.java index cdf1f49..ed54e23 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ASTVisitor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ASTVisitor.java @@ -80,7 +80,7 @@ import net.sourceforge.phpdt.internal.compiler.lookup.ClassScope; import net.sourceforge.phpdt.internal.compiler.lookup.CompilationUnitScope; import net.sourceforge.phpdt.internal.compiler.lookup.MethodScope; -/** +/** * A visitor for iterating through the parse tree. */ public abstract class ASTVisitor { @@ -88,578 +88,687 @@ public abstract class ASTVisitor { public void acceptProblem(IProblem problem) { // do nothing by default } - public void endVisit( - AllocationExpression allocationExpression, - BlockScope scope) { + + public void endVisit(AllocationExpression allocationExpression, + BlockScope scope) { // do nothing by default } + public void endVisit(AND_AND_Expression and_and_Expression, BlockScope scope) { // do nothing by default } -// public void endVisit(JavadocArrayQualifiedTypeReference typeRef, BlockScope scope) { -// // do nothing by default -// } -// public void endVisit(JavadocArraySingleTypeReference typeRef, BlockScope scope) { -// // do nothing by default -// } -// public void endVisit(JavadocArgumentExpression expression, BlockScope scope) { -// // do nothing by default -// } -// public void endVisit(JavadocFieldReference fieldRef, BlockScope scope) { -// // do nothing by default -// } -// public void endVisit(JavadocMessageSend messageSend, BlockScope scope) { -// // do nothing by default -// } -// public void endVisit(JavadocQualifiedTypeReference typeRef, BlockScope scope) { -// // do nothing by default -// } -// public void endVisit(JavadocReturnStatement statement, BlockScope scope) { -// // do nothing by default -// } -// public void endVisit(JavadocSingleNameReference argument, BlockScope scope) { -// // do nothing by default -// } -// public void endVisit(JavadocSingleTypeReference typeRef, BlockScope scope) { -// // do nothing by default -// } + + // public void endVisit(JavadocArrayQualifiedTypeReference typeRef, + // BlockScope scope) { + // // do nothing by default + // } + // public void endVisit(JavadocArraySingleTypeReference typeRef, BlockScope + // scope) { + // // do nothing by default + // } + // public void endVisit(JavadocArgumentExpression expression, BlockScope + // scope) { + // // do nothing by default + // } + // public void endVisit(JavadocFieldReference fieldRef, BlockScope scope) { + // // do nothing by default + // } + // public void endVisit(JavadocMessageSend messageSend, BlockScope scope) { + // // do nothing by default + // } + // public void endVisit(JavadocQualifiedTypeReference typeRef, BlockScope + // scope) { + // // do nothing by default + // } + // public void endVisit(JavadocReturnStatement statement, BlockScope scope) + // { + // // do nothing by default + // } + // public void endVisit(JavadocSingleNameReference argument, BlockScope + // scope) { + // // do nothing by default + // } + // public void endVisit(JavadocSingleTypeReference typeRef, BlockScope + // scope) { + // // do nothing by default + // } public void endVisit(Argument argument, BlockScope scope) { // do nothing by default } - public void endVisit( - ArrayAllocationExpression arrayAllocationExpression, - BlockScope scope) { + + public void endVisit(ArrayAllocationExpression arrayAllocationExpression, + BlockScope scope) { // do nothing by default } + public void endVisit(ArrayInitializer arrayInitializer, BlockScope scope) { // do nothing by default } + public void endVisit( - ArrayQualifiedTypeReference arrayQualifiedTypeReference, - BlockScope scope) { + ArrayQualifiedTypeReference arrayQualifiedTypeReference, + BlockScope scope) { // do nothing by default } + public void endVisit( - ArrayQualifiedTypeReference arrayQualifiedTypeReference, - ClassScope scope) { + ArrayQualifiedTypeReference arrayQualifiedTypeReference, + ClassScope scope) { // do nothing by default } + public void endVisit(ArrayReference arrayReference, BlockScope scope) { // do nothing by default } + public void endVisit(ArrayTypeReference arrayTypeReference, BlockScope scope) { // do nothing by default } + public void endVisit(ArrayTypeReference arrayTypeReference, ClassScope scope) { // do nothing by default } + public void endVisit(Assignment assignment, BlockScope scope) { // do nothing by default } + public void endVisit(AssertStatement assertStatement, BlockScope scope) { // do nothing by default } + public void endVisit(BinaryExpression binaryExpression, BlockScope scope) { // do nothing by default } + public void endVisit(Block block, BlockScope scope) { // do nothing by default } + public void endVisit(BreakStatement breakStatement, BlockScope scope) { // do nothing by default } + public void endVisit(CaseStatement caseStatement, BlockScope scope) { // do nothing by default } + public void endVisit(CastExpression castExpression, BlockScope scope) { // do nothing by default } - + public void endVisit(Clinit clinit, ClassScope scope) { // do nothing by default } - public void endVisit( - CompilationUnitDeclaration compilationUnitDeclaration, - CompilationUnitScope scope) { + + public void endVisit(CompilationUnitDeclaration compilationUnitDeclaration, + CompilationUnitScope scope) { // do nothing by default } + public void endVisit(CompoundAssignment compoundAssignment, BlockScope scope) { // do nothing by default } - public void endVisit( - ConditionalExpression conditionalExpression, - BlockScope scope) { + + public void endVisit(ConditionalExpression conditionalExpression, + BlockScope scope) { // do nothing by default } - public void endVisit( - ConstructorDeclaration constructorDeclaration, - ClassScope scope) { + + public void endVisit(ConstructorDeclaration constructorDeclaration, + ClassScope scope) { // do nothing by default } + public void endVisit(ContinueStatement continueStatement, BlockScope scope) { // do nothing by default } + public void endVisit(DoStatement doStatement, BlockScope scope) { // do nothing by default } + public void endVisit(DoubleLiteral doubleLiteral, BlockScope scope) { // do nothing by default } + public void endVisit(EqualExpression equalExpression, BlockScope scope) { // do nothing by default } - public void endVisit( - ExplicitConstructorCall explicitConstructor, - BlockScope scope) { + + public void endVisit(ExplicitConstructorCall explicitConstructor, + BlockScope scope) { // do nothing by default } - public void endVisit( - ExtendedStringLiteral extendedStringLiteral, - BlockScope scope) { + + public void endVisit(ExtendedStringLiteral extendedStringLiteral, + BlockScope scope) { // do nothing by default } + public void endVisit(FalseLiteral falseLiteral, BlockScope scope) { // do nothing by default } + public void endVisit(FieldDeclaration fieldDeclaration, MethodScope scope) { // do nothing by default } + public void endVisit(FieldReference fieldReference, BlockScope scope) { // do nothing by default } + public void endVisit(FloatLiteral floatLiteral, BlockScope scope) { // do nothing by default } + public void endVisit(EmptyStatement emptyStatement, BlockScope scope) { // do nothing by default } + public void endVisit(ForStatement forStatement, BlockScope scope) { // do nothing by default } + public void endVisit(IfStatement ifStatement, BlockScope scope) { // do nothing by default } + public void endVisit(ImportReference importRef, CompilationUnitScope scope) { // do nothing by default } + public void endVisit(Initializer initializer, MethodScope scope) { // do nothing by default } - public void endVisit( - InstanceOfExpression instanceOfExpression, - BlockScope scope) { + + public void endVisit(InstanceOfExpression instanceOfExpression, + BlockScope scope) { // do nothing by default } + public void endVisit(IntLiteral intLiteral, BlockScope scope) { // do nothing by default } + public void endVisit(LabeledStatement labeledStatement, BlockScope scope) { // do nothing by default } + public void endVisit(LocalDeclaration localDeclaration, BlockScope scope) { // do nothing by default } + public void endVisit(LongLiteral longLiteral, BlockScope scope) { // do nothing by default } + public void endVisit(MessageSend messageSend, BlockScope scope) { // do nothing by default } + public void endVisit(MethodDeclaration methodDeclaration, ClassScope scope) { // do nothing by default } -// public void endVisit(StringLiteralConcatenation literal, BlockScope scope) { -// // do nothing by default -// } + + // public void endVisit(StringLiteralConcatenation literal, BlockScope + // scope) { + // // do nothing by default + // } public void endVisit(NullLiteral nullLiteral, BlockScope scope) { // do nothing by default } + public void endVisit(OR_OR_Expression or_or_Expression, BlockScope scope) { // do nothing by default } + public void endVisit(PostfixExpression postfixExpression, BlockScope scope) { // do nothing by default } + public void endVisit(PrefixExpression prefixExpression, BlockScope scope) { // do nothing by default } + public void endVisit( - QualifiedAllocationExpression qualifiedAllocationExpression, - BlockScope scope) { + QualifiedAllocationExpression qualifiedAllocationExpression, + BlockScope scope) { // do nothing by default } - public void endVisit( - QualifiedNameReference qualifiedNameReference, - BlockScope scope) { + + public void endVisit(QualifiedNameReference qualifiedNameReference, + BlockScope scope) { // do nothing by default } - public void endVisit( - QualifiedSuperReference qualifiedSuperReference, - BlockScope scope) { + + public void endVisit(QualifiedSuperReference qualifiedSuperReference, + BlockScope scope) { // do nothing by default } - public void endVisit( - QualifiedThisReference qualifiedThisReference, - BlockScope scope) { + + public void endVisit(QualifiedThisReference qualifiedThisReference, + BlockScope scope) { // do nothing by default } - public void endVisit( - QualifiedTypeReference qualifiedTypeReference, - BlockScope scope) { + + public void endVisit(QualifiedTypeReference qualifiedTypeReference, + BlockScope scope) { // do nothing by default } - public void endVisit( - QualifiedTypeReference qualifiedTypeReference, - ClassScope scope) { + + public void endVisit(QualifiedTypeReference qualifiedTypeReference, + ClassScope scope) { // do nothing by default } + public void endVisit(ReturnStatement returnStatement, BlockScope scope) { // do nothing by default } - public void endVisit( - SingleNameReference singleNameReference, - BlockScope scope) { + + public void endVisit(SingleNameReference singleNameReference, + BlockScope scope) { // do nothing by default } - public void endVisit( - SingleTypeReference singleTypeReference, - BlockScope scope) { + + public void endVisit(SingleTypeReference singleTypeReference, + BlockScope scope) { // do nothing by default } - public void endVisit( - SingleTypeReference singleTypeReference, - ClassScope scope) { + + public void endVisit(SingleTypeReference singleTypeReference, + ClassScope scope) { // do nothing by default } + public void endVisit(StringLiteral stringLiteral, BlockScope scope) { // do nothing by default } + public void endVisit(SuperReference superReference, BlockScope scope) { // do nothing by default } + public void endVisit(SwitchStatement switchStatement, BlockScope scope) { // do nothing by default } - + public void endVisit(ThisReference thisReference, BlockScope scope) { // do nothing by default } + public void endVisit(ThrowStatement throwStatement, BlockScope scope) { // do nothing by default } + public void endVisit(TrueLiteral trueLiteral, BlockScope scope) { // do nothing by default } + public void endVisit(TryStatement tryStatement, BlockScope scope) { // do nothing by default } - public void endVisit( - TypeDeclaration localTypeDeclaration, - BlockScope scope) { + + public void endVisit(TypeDeclaration localTypeDeclaration, BlockScope scope) { // do nothing by default - } - public void endVisit( - TypeDeclaration memberTypeDeclaration, - ClassScope scope) { + } + + public void endVisit(TypeDeclaration memberTypeDeclaration, ClassScope scope) { // do nothing by default } - public void endVisit( - TypeDeclaration typeDeclaration, - CompilationUnitScope scope) { + + public void endVisit(TypeDeclaration typeDeclaration, + CompilationUnitScope scope) { // do nothing by default - } + } + public void endVisit(UnaryExpression unaryExpression, BlockScope scope) { // do nothing by default } + public void endVisit(WhileStatement whileStatement, BlockScope scope) { // do nothing by default } - public boolean visit( - AllocationExpression allocationExpression, - BlockScope scope) { + + public boolean visit(AllocationExpression allocationExpression, + BlockScope scope) { return true; // do nothing by default, keep traversing // do nothing by default } + public boolean visit(AND_AND_Expression and_and_Expression, BlockScope scope) { return true; // do nothing by default, keep traversing } -// public boolean visit(JavadocArrayQualifiedTypeReference typeRef, BlockScope scope) { -// return true; // do nothing by default, keep traversing -// } -// public boolean visit(JavadocArraySingleTypeReference typeRef, BlockScope scope) { -// return true; // do nothing by default, keep traversing -// } -// public boolean visit(JavadocArgumentExpression expression, BlockScope scope) { -// return true; // do nothing by default, keep traversing -// } -// public boolean visit(JavadocFieldReference fieldRef, BlockScope scope) { -// return true; // do nothing by default, keep traversing -// } -// public boolean visit(JavadocMessageSend messageSend, BlockScope scope) { -// return true; // do nothing by default, keep traversing -// } -// public boolean visit(JavadocQualifiedTypeReference typeRef, BlockScope scope) { -// return true; // do nothing by default, keep traversing -// } -// public boolean visit(JavadocReturnStatement statement, BlockScope scope) { -// return true; // do nothing by default, keep traversing -// } -// public boolean visit(JavadocSingleNameReference argument, BlockScope scope) { -// return true; // do nothing by default, keep traversing -// } -// public boolean visit(JavadocSingleTypeReference typeRef, BlockScope scope) { -// return true; // do nothing by default, keep traversing -// } + + // public boolean visit(JavadocArrayQualifiedTypeReference typeRef, + // BlockScope scope) { + // return true; // do nothing by default, keep traversing + // } + // public boolean visit(JavadocArraySingleTypeReference typeRef, BlockScope + // scope) { + // return true; // do nothing by default, keep traversing + // } + // public boolean visit(JavadocArgumentExpression expression, BlockScope + // scope) { + // return true; // do nothing by default, keep traversing + // } + // public boolean visit(JavadocFieldReference fieldRef, BlockScope scope) { + // return true; // do nothing by default, keep traversing + // } + // public boolean visit(JavadocMessageSend messageSend, BlockScope scope) { + // return true; // do nothing by default, keep traversing + // } + // public boolean visit(JavadocQualifiedTypeReference typeRef, BlockScope + // scope) { + // return true; // do nothing by default, keep traversing + // } + // public boolean visit(JavadocReturnStatement statement, BlockScope scope) + // { + // return true; // do nothing by default, keep traversing + // } + // public boolean visit(JavadocSingleNameReference argument, BlockScope + // scope) { + // return true; // do nothing by default, keep traversing + // } + // public boolean visit(JavadocSingleTypeReference typeRef, BlockScope + // scope) { + // return true; // do nothing by default, keep traversing + // } public boolean visit(Argument argument, BlockScope scope) { return true; // do nothing by default, keep traversing } - public boolean visit( - ArrayAllocationExpression arrayAllocationExpression, - BlockScope scope) { + + public boolean visit(ArrayAllocationExpression arrayAllocationExpression, + BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(ArrayInitializer arrayInitializer, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit( - ArrayQualifiedTypeReference arrayQualifiedTypeReference, - BlockScope scope) { + ArrayQualifiedTypeReference arrayQualifiedTypeReference, + BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit( - ArrayQualifiedTypeReference arrayQualifiedTypeReference, - ClassScope scope) { + ArrayQualifiedTypeReference arrayQualifiedTypeReference, + ClassScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(ArrayReference arrayReference, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(ArrayTypeReference arrayTypeReference, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(ArrayTypeReference arrayTypeReference, ClassScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(Assignment assignment, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(AssertStatement assertStatement, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(BinaryExpression binaryExpression, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(Block block, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(BreakStatement breakStatement, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(CaseStatement caseStatement, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(CastExpression castExpression, BlockScope scope) { return true; // do nothing by default, keep traversing } - + public boolean visit(Clinit clinit, ClassScope scope) { return true; // do nothing by default, keep traversing } - public boolean visit( - CompilationUnitDeclaration compilationUnitDeclaration, - CompilationUnitScope scope) { + + public boolean visit(CompilationUnitDeclaration compilationUnitDeclaration, + CompilationUnitScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(CompoundAssignment compoundAssignment, BlockScope scope) { return true; // do nothing by default, keep traversing } - public boolean visit( - ConditionalExpression conditionalExpression, - BlockScope scope) { + + public boolean visit(ConditionalExpression conditionalExpression, + BlockScope scope) { return true; // do nothing by default, keep traversing } - public boolean visit( - ConstructorDeclaration constructorDeclaration, - ClassScope scope) { + + public boolean visit(ConstructorDeclaration constructorDeclaration, + ClassScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(ContinueStatement continueStatement, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(DoStatement doStatement, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(DoubleLiteral doubleLiteral, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(EqualExpression equalExpression, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(EmptyStatement emptyStatement, BlockScope scope) { return true; // do nothing by default, keep traversing } - public boolean visit( - ExplicitConstructorCall explicitConstructor, - BlockScope scope) { + + public boolean visit(ExplicitConstructorCall explicitConstructor, + BlockScope scope) { return true; // do nothing by default, keep traversing } - public boolean visit( - ExtendedStringLiteral extendedStringLiteral, - BlockScope scope) { + + public boolean visit(ExtendedStringLiteral extendedStringLiteral, + BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(FalseLiteral falseLiteral, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(FieldReference fieldReference, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(FloatLiteral floatLiteral, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(ForStatement forStatement, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(IfStatement ifStatement, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(ImportReference importRef, CompilationUnitScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(Initializer initializer, MethodScope scope) { return true; // do nothing by default, keep traversing } - public boolean visit( - InstanceOfExpression instanceOfExpression, - BlockScope scope) { + + public boolean visit(InstanceOfExpression instanceOfExpression, + BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(IntLiteral intLiteral, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(LabeledStatement labeledStatement, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(LocalDeclaration localDeclaration, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(LongLiteral longLiteral, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(MessageSend messageSend, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) { return true; // do nothing by default, keep traversing } -// public boolean visit( -// StringLiteralConcatenation literal, -// BlockScope scope) { -// return true; // do nothing by default, keep traversing -// } + + // public boolean visit( + // StringLiteralConcatenation literal, + // BlockScope scope) { + // return true; // do nothing by default, keep traversing + // } public boolean visit(NullLiteral nullLiteral, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(OR_OR_Expression or_or_Expression, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(PostfixExpression postfixExpression, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(PrefixExpression prefixExpression, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit( - QualifiedAllocationExpression qualifiedAllocationExpression, - BlockScope scope) { + QualifiedAllocationExpression qualifiedAllocationExpression, + BlockScope scope) { return true; // do nothing by default, keep traversing } - public boolean visit( - QualifiedNameReference qualifiedNameReference, - BlockScope scope) { + + public boolean visit(QualifiedNameReference qualifiedNameReference, + BlockScope scope) { return true; // do nothing by default, keep traversing } - public boolean visit( - QualifiedSuperReference qualifiedSuperReference, - BlockScope scope) { + + public boolean visit(QualifiedSuperReference qualifiedSuperReference, + BlockScope scope) { return true; // do nothing by default, keep traversing } - public boolean visit( - QualifiedThisReference qualifiedThisReference, - BlockScope scope) { + + public boolean visit(QualifiedThisReference qualifiedThisReference, + BlockScope scope) { return true; // do nothing by default, keep traversing } - public boolean visit( - QualifiedTypeReference qualifiedTypeReference, - BlockScope scope) { + + public boolean visit(QualifiedTypeReference qualifiedTypeReference, + BlockScope scope) { return true; // do nothing by default, keep traversing } - public boolean visit( - QualifiedTypeReference qualifiedTypeReference, - ClassScope scope) { + + public boolean visit(QualifiedTypeReference qualifiedTypeReference, + ClassScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(ReturnStatement returnStatement, BlockScope scope) { return true; // do nothing by default, keep traversing } - public boolean visit( - SingleNameReference singleNameReference, - BlockScope scope) { + + public boolean visit(SingleNameReference singleNameReference, + BlockScope scope) { return true; // do nothing by default, keep traversing } - public boolean visit( - SingleTypeReference singleTypeReference, - BlockScope scope) { + + public boolean visit(SingleTypeReference singleTypeReference, + BlockScope scope) { return true; // do nothing by default, keep traversing } - public boolean visit( - SingleTypeReference singleTypeReference, - ClassScope scope) { + + public boolean visit(SingleTypeReference singleTypeReference, + ClassScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(StringLiteral stringLiteral, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(SuperReference superReference, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(SwitchStatement switchStatement, BlockScope scope) { return true; // do nothing by default, keep traversing } - + public boolean visit(ThisReference thisReference, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(ThrowStatement throwStatement, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(TrueLiteral trueLiteral, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(TryStatement tryStatement, BlockScope scope) { return true; // do nothing by default, keep traversing } - public boolean visit( - TypeDeclaration localTypeDeclaration, - BlockScope scope) { + + public boolean visit(TypeDeclaration localTypeDeclaration, BlockScope scope) { return true; // do nothing by default, keep traversing } - public boolean visit( - TypeDeclaration memberTypeDeclaration, - ClassScope scope) { + + public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope scope) { return true; // do nothing by default, keep traversing - } - public boolean visit( - TypeDeclaration typeDeclaration, - CompilationUnitScope scope) { + } + + public boolean visit(TypeDeclaration typeDeclaration, + CompilationUnitScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(UnaryExpression unaryExpression, BlockScope scope) { return true; // do nothing by default, keep traversing } + public boolean visit(WhileStatement whileStatement, BlockScope scope) { return true; // do nothing by default, keep traversing } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/AbstractSyntaxTreeVisitorAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/AbstractSyntaxTreeVisitorAdapter.java index 8be0b3f..b5cf9d2 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/AbstractSyntaxTreeVisitorAdapter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/AbstractSyntaxTreeVisitorAdapter.java @@ -84,467 +84,571 @@ import net.sourceforge.phpdt.internal.compiler.lookup.ClassScope; import net.sourceforge.phpdt.internal.compiler.lookup.CompilationUnitScope; import net.sourceforge.phpdt.internal.compiler.lookup.MethodScope; - /** * An adapter class for interating through the parse tree. */ -public class AbstractSyntaxTreeVisitorAdapter implements IAbstractSyntaxTreeVisitor { +public class AbstractSyntaxTreeVisitorAdapter implements + IAbstractSyntaxTreeVisitor { - public void acceptProblem(IProblem problem) {} - public void endVisit( - AllocationExpression allocationExpression, - BlockScope scope) { + public void acceptProblem(IProblem problem) { + } + + public void endVisit(AllocationExpression allocationExpression, + BlockScope scope) { } + public void endVisit(AND_AND_Expression and_and_Expression, BlockScope scope) { } + public void endVisit( - AnonymousLocalTypeDeclaration anonymousTypeDeclaration, - BlockScope scope) { + AnonymousLocalTypeDeclaration anonymousTypeDeclaration, + BlockScope scope) { } + public void endVisit(Argument argument, BlockScope scope) { } - public void endVisit( - ArrayAllocationExpression arrayAllocationExpression, - BlockScope scope) { + + public void endVisit(ArrayAllocationExpression arrayAllocationExpression, + BlockScope scope) { } + public void endVisit(ArrayInitializer arrayInitializer, BlockScope scope) { } + public void endVisit( - ArrayQualifiedTypeReference arrayQualifiedTypeReference, - BlockScope scope) { + ArrayQualifiedTypeReference arrayQualifiedTypeReference, + BlockScope scope) { } + public void endVisit( - ArrayQualifiedTypeReference arrayQualifiedTypeReference, - ClassScope scope) { + ArrayQualifiedTypeReference arrayQualifiedTypeReference, + ClassScope scope) { } + public void endVisit(ArrayReference arrayReference, BlockScope scope) { } + public void endVisit(ArrayTypeReference arrayTypeReference, BlockScope scope) { } + public void endVisit(ArrayTypeReference arrayTypeReference, ClassScope scope) { } + public void endVisit(Assignment assignment, BlockScope scope) { } + public void endVisit(AssertStatement assertStatement, BlockScope scope) { } + public void endVisit(BinaryExpression binaryExpression, BlockScope scope) { } + public void endVisit(Block block, BlockScope scope) { } + public void endVisit(BreakStatement breakStatement, BlockScope scope) { } + public void endVisit(CaseStatement caseStatement, BlockScope scope) { } + public void endVisit(CastExpression castExpression, BlockScope scope) { } + public void endVisit(Clinit clinit, ClassScope scope) { } - public void endVisit( - CompilationUnitDeclaration compilationUnitDeclaration, - CompilationUnitScope scope) { + + public void endVisit(CompilationUnitDeclaration compilationUnitDeclaration, + CompilationUnitScope scope) { } + public void endVisit(CompoundAssignment compoundAssignment, BlockScope scope) { } - public void endVisit( - ConditionalExpression conditionalExpression, - BlockScope scope) { + + public void endVisit(ConditionalExpression conditionalExpression, + BlockScope scope) { } - public void endVisit( - ConstructorDeclaration constructorDeclaration, - ClassScope scope) { + + public void endVisit(ConstructorDeclaration constructorDeclaration, + ClassScope scope) { } + public void endVisit(ContinueStatement continueStatement, BlockScope scope) { } + public void endVisit(DefaultCase defaultCaseStatement, BlockScope scope) { } + public void endVisit(DoStatement doStatement, BlockScope scope) { } + public void endVisit(DoubleLiteral doubleLiteral, BlockScope scope) { } + public void endVisit(EqualExpression equalExpression, BlockScope scope) { } - public void endVisit( - ExplicitConstructorCall explicitConstructor, - BlockScope scope) { + + public void endVisit(ExplicitConstructorCall explicitConstructor, + BlockScope scope) { } - public void endVisit( - ExtendedStringLiteral extendedStringLiteral, - BlockScope scope) { + + public void endVisit(ExtendedStringLiteral extendedStringLiteral, + BlockScope scope) { } + public void endVisit(FalseLiteral falseLiteral, BlockScope scope) { } + public void endVisit(FieldDeclaration fieldDeclaration, MethodScope scope) { } + public void endVisit(FieldReference fieldReference, BlockScope scope) { } + public void endVisit(FloatLiteral floatLiteral, BlockScope scope) { } + public void endVisit(EmptyStatement emptyStatement, BlockScope scope) { } + public void endVisit(ForStatement forStatement, BlockScope scope) { } + public void endVisit(IfStatement ifStatement, BlockScope scope) { } + public void endVisit(ImportReference importRef, CompilationUnitScope scope) { } + public void endVisit(Initializer initializer, MethodScope scope) { } - public void endVisit( - InstanceOfExpression instanceOfExpression, - BlockScope scope) { + + public void endVisit(InstanceOfExpression instanceOfExpression, + BlockScope scope) { } + public void endVisit(IntLiteral intLiteral, BlockScope scope) { } + public void endVisit(LabeledStatement labeledStatement, BlockScope scope) { } + public void endVisit(LocalDeclaration localDeclaration, BlockScope scope) { } + public void endVisit(LongLiteral longLiteral, BlockScope scope) { } - public void endVisit( - MemberTypeDeclaration memberTypeDeclaration, - ClassScope scope) { + + public void endVisit(MemberTypeDeclaration memberTypeDeclaration, + ClassScope scope) { } + public void endVisit(MessageSend messageSend, BlockScope scope) { } + public void endVisit(MethodDeclaration methodDeclaration, ClassScope scope) { } + public void endVisit(NullLiteral nullLiteral, BlockScope scope) { } + public void endVisit(OR_OR_Expression or_or_Expression, BlockScope scope) { } + public void endVisit(PostfixExpression postfixExpression, BlockScope scope) { } + public void endVisit(PrefixExpression prefixExpression, BlockScope scope) { } + public void endVisit( - QualifiedAllocationExpression qualifiedAllocationExpression, - BlockScope scope) { + QualifiedAllocationExpression qualifiedAllocationExpression, + BlockScope scope) { } - public void endVisit( - QualifiedNameReference qualifiedNameReference, - BlockScope scope) { + + public void endVisit(QualifiedNameReference qualifiedNameReference, + BlockScope scope) { } - public void endVisit( - QualifiedSuperReference qualifiedSuperReference, - BlockScope scope) { + + public void endVisit(QualifiedSuperReference qualifiedSuperReference, + BlockScope scope) { } - public void endVisit( - QualifiedThisReference qualifiedThisReference, - BlockScope scope) { + + public void endVisit(QualifiedThisReference qualifiedThisReference, + BlockScope scope) { } - public void endVisit( - QualifiedTypeReference qualifiedTypeReference, - BlockScope scope) { + + public void endVisit(QualifiedTypeReference qualifiedTypeReference, + BlockScope scope) { } - public void endVisit( - QualifiedTypeReference qualifiedTypeReference, - ClassScope scope) { + + public void endVisit(QualifiedTypeReference qualifiedTypeReference, + ClassScope scope) { } + public void endVisit(ReturnStatement returnStatement, BlockScope scope) { } - public void endVisit( - SingleNameReference singleNameReference, - BlockScope scope) { + + public void endVisit(SingleNameReference singleNameReference, + BlockScope scope) { } - public void endVisit( - SingleTypeReference singleTypeReference, - BlockScope scope) { + + public void endVisit(SingleTypeReference singleTypeReference, + BlockScope scope) { } - public void endVisit( - SingleTypeReference singleTypeReference, - ClassScope scope) { + + public void endVisit(SingleTypeReference singleTypeReference, + ClassScope scope) { } + public void endVisit(StringLiteral stringLiteral, BlockScope scope) { } + public void endVisit(SuperReference superReference, BlockScope scope) { } + public void endVisit(SwitchStatement switchStatement, BlockScope scope) { } - + public void endVisit(ThisReference thisReference, BlockScope scope) { } + public void endVisit(ThrowStatement throwStatement, BlockScope scope) { } + public void endVisit(TrueLiteral trueLiteral, BlockScope scope) { } + public void endVisit(TryStatement tryStatement, BlockScope scope) { } - public void endVisit( - TypeDeclaration typeDeclaration, - CompilationUnitScope scope) { + + public void endVisit(TypeDeclaration typeDeclaration, + CompilationUnitScope scope) { } + public void endVisit(UnaryExpression unaryExpression, BlockScope scope) { } + public void endVisit(WhileStatement whileStatement, BlockScope scope) { } - public boolean visit( - AllocationExpression allocationExpression, - BlockScope scope) { + + public boolean visit(AllocationExpression allocationExpression, + BlockScope scope) { return true; } + public boolean visit(AND_AND_Expression and_and_Expression, BlockScope scope) { return true; } + public boolean visit( - AnonymousLocalTypeDeclaration anonymousTypeDeclaration, - BlockScope scope) { + AnonymousLocalTypeDeclaration anonymousTypeDeclaration, + BlockScope scope) { return true; } + public boolean visit(Argument argument, BlockScope scope) { return true; } - public boolean visit( - ArrayAllocationExpression arrayAllocationExpression, - BlockScope scope) { + + public boolean visit(ArrayAllocationExpression arrayAllocationExpression, + BlockScope scope) { return true; } + public boolean visit(ArrayInitializer arrayInitializer, BlockScope scope) { return true; } + public boolean visit( - ArrayQualifiedTypeReference arrayQualifiedTypeReference, - BlockScope scope) { + ArrayQualifiedTypeReference arrayQualifiedTypeReference, + BlockScope scope) { return true; } + public boolean visit( - ArrayQualifiedTypeReference arrayQualifiedTypeReference, - ClassScope scope) { + ArrayQualifiedTypeReference arrayQualifiedTypeReference, + ClassScope scope) { return true; } + public boolean visit(ArrayReference arrayReference, BlockScope scope) { return true; } + public boolean visit(ArrayTypeReference arrayTypeReference, BlockScope scope) { return true; } + public boolean visit(ArrayTypeReference arrayTypeReference, ClassScope scope) { return true; } + public boolean visit(Assignment assignment, BlockScope scope) { return true; } + public boolean visit(AssertStatement assertStatement, BlockScope scope) { return true; } + public boolean visit(BinaryExpression binaryExpression, BlockScope scope) { return true; } + public boolean visit(Block block, BlockScope scope) { return true; } + public boolean visit(BreakStatement breakStatement, BlockScope scope) { return true; } + public boolean visit(CaseStatement caseStatement, BlockScope scope) { return true; } + public boolean visit(CastExpression castExpression, BlockScope scope) { return true; } - + public boolean visit(Clinit clinit, ClassScope scope) { return true; } - public boolean visit( - CompilationUnitDeclaration compilationUnitDeclaration, - CompilationUnitScope scope) { + + public boolean visit(CompilationUnitDeclaration compilationUnitDeclaration, + CompilationUnitScope scope) { return true; } + public boolean visit(CompoundAssignment compoundAssignment, BlockScope scope) { return true; } - public boolean visit( - ConditionalExpression conditionalExpression, - BlockScope scope) { + + public boolean visit(ConditionalExpression conditionalExpression, + BlockScope scope) { return true; } - public boolean visit( - ConstructorDeclaration constructorDeclaration, - ClassScope scope) { + + public boolean visit(ConstructorDeclaration constructorDeclaration, + ClassScope scope) { return true; } + public boolean visit(ContinueStatement continueStatement, BlockScope scope) { return true; } + public boolean visit(DefaultCase defaultCaseStatement, BlockScope scope) { return true; } + public boolean visit(DoStatement doStatement, BlockScope scope) { return true; } + public boolean visit(DoubleLiteral doubleLiteral, BlockScope scope) { return true; } + public boolean visit(EqualExpression equalExpression, BlockScope scope) { return true; } + public boolean visit(EmptyStatement emptyStatement, BlockScope scope) { return true; } - public boolean visit( - ExplicitConstructorCall explicitConstructor, - BlockScope scope) { + + public boolean visit(ExplicitConstructorCall explicitConstructor, + BlockScope scope) { return true; } - public boolean visit( - ExtendedStringLiteral extendedStringLiteral, - BlockScope scope) { + + public boolean visit(ExtendedStringLiteral extendedStringLiteral, + BlockScope scope) { return true; } + public boolean visit(FalseLiteral falseLiteral, BlockScope scope) { return true; } + public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) { return true; } + public boolean visit(FieldReference fieldReference, BlockScope scope) { return true; } + public boolean visit(FloatLiteral floatLiteral, BlockScope scope) { return true; } + public boolean visit(ForStatement forStatement, BlockScope scope) { return true; } + public boolean visit(IfStatement ifStatement, BlockScope scope) { return true; } + public boolean visit(ImportReference importRef, CompilationUnitScope scope) { return true; } + public boolean visit(Initializer initializer, MethodScope scope) { return true; } - public boolean visit( - InstanceOfExpression instanceOfExpression, - BlockScope scope) { + + public boolean visit(InstanceOfExpression instanceOfExpression, + BlockScope scope) { return true; } + public boolean visit(IntLiteral intLiteral, BlockScope scope) { return true; } + public boolean visit(LabeledStatement labeledStatement, BlockScope scope) { return true; } + public boolean visit(LocalDeclaration localDeclaration, BlockScope scope) { return true; } + public boolean visit(LongLiteral longLiteral, BlockScope scope) { return true; } - public boolean visit( - MemberTypeDeclaration memberTypeDeclaration, - ClassScope scope) { + + public boolean visit(MemberTypeDeclaration memberTypeDeclaration, + ClassScope scope) { return true; } + public boolean visit(MessageSend messageSend, BlockScope scope) { return true; } + public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) { return true; } + public boolean visit(NullLiteral nullLiteral, BlockScope scope) { return true; } + public boolean visit(OR_OR_Expression or_or_Expression, BlockScope scope) { return true; } + public boolean visit(PostfixExpression postfixExpression, BlockScope scope) { return true; } + public boolean visit(PrefixExpression prefixExpression, BlockScope scope) { return true; } + public boolean visit( - QualifiedAllocationExpression qualifiedAllocationExpression, - BlockScope scope) { + QualifiedAllocationExpression qualifiedAllocationExpression, + BlockScope scope) { return true; } - public boolean visit( - QualifiedNameReference qualifiedNameReference, - BlockScope scope) { + + public boolean visit(QualifiedNameReference qualifiedNameReference, + BlockScope scope) { return true; } - public boolean visit( - QualifiedSuperReference qualifiedSuperReference, - BlockScope scope) { + + public boolean visit(QualifiedSuperReference qualifiedSuperReference, + BlockScope scope) { return true; } - public boolean visit( - QualifiedThisReference qualifiedThisReference, - BlockScope scope) { + + public boolean visit(QualifiedThisReference qualifiedThisReference, + BlockScope scope) { return true; } - public boolean visit( - QualifiedTypeReference qualifiedTypeReference, - BlockScope scope) { + + public boolean visit(QualifiedTypeReference qualifiedTypeReference, + BlockScope scope) { return true; } - public boolean visit( - QualifiedTypeReference qualifiedTypeReference, - ClassScope scope) { + + public boolean visit(QualifiedTypeReference qualifiedTypeReference, + ClassScope scope) { return true; } + public boolean visit(ReturnStatement returnStatement, BlockScope scope) { return true; } - public boolean visit( - SingleNameReference singleNameReference, - BlockScope scope) { + + public boolean visit(SingleNameReference singleNameReference, + BlockScope scope) { return true; } - public boolean visit( - SingleTypeReference singleTypeReference, - BlockScope scope) { + + public boolean visit(SingleTypeReference singleTypeReference, + BlockScope scope) { return true; } - public boolean visit( - SingleTypeReference singleTypeReference, - ClassScope scope) { + + public boolean visit(SingleTypeReference singleTypeReference, + ClassScope scope) { return true; } + public boolean visit(StringLiteral stringLiteral, BlockScope scope) { return true; } + public boolean visit(SuperReference superReference, BlockScope scope) { return true; } + public boolean visit(SwitchStatement switchStatement, BlockScope scope) { return true; } - + public boolean visit(ThisReference thisReference, BlockScope scope) { return true; } + public boolean visit(ThrowStatement throwStatement, BlockScope scope) { return true; } + public boolean visit(TrueLiteral trueLiteral, BlockScope scope) { return true; } + public boolean visit(TryStatement tryStatement, BlockScope scope) { return true; } - public boolean visit( - TypeDeclaration typeDeclaration, - CompilationUnitScope scope) { + + public boolean visit(TypeDeclaration typeDeclaration, + CompilationUnitScope scope) { return true; } + public boolean visit(UnaryExpression unaryExpression, BlockScope scope) { return true; } + public boolean visit(WhileStatement whileStatement, BlockScope scope) { return true; } - public boolean visit( - LocalTypeDeclaration localTypeDeclaration, - BlockScope scope) { + + public boolean visit(LocalTypeDeclaration localTypeDeclaration, + BlockScope scope) { return true; } - public void endVisit( - LocalTypeDeclaration localTypeDeclaration, - BlockScope scope) { + + public void endVisit(LocalTypeDeclaration localTypeDeclaration, + BlockScope scope) { } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/CompilationResult.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/CompilationResult.java index 90d5434..4d0704c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/CompilationResult.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/CompilationResult.java @@ -11,29 +11,30 @@ package net.sourceforge.phpdt.internal.compiler; /** - * A compilation result consists of all information returned by the compiler for - * a single compiled compilation source unit. This includes: + * A compilation result consists of all information returned by the compiler for + * a single compiled compilation source unit. This includes: *
            *
          • the compilation unit that was compiled - *
          • for each type produced by compiling the compilation unit, its binary and optionally its principal structure + *
          • for each type produced by compiling the compilation unit, its binary and + * optionally its principal structure *
          • any problems (errors or warnings) produced *
          • dependency info *
          - * - * The principle structure and binary may be null if the compiler could not produce them. - * If neither could be produced, there is no corresponding entry for the type. - * - * The dependency info includes type references such as supertypes, field types, method - * parameter and return types, local variable types, types of intermediate expressions, etc. - * It also includes the namespaces (packages) in which names were looked up. - * It does not include finer grained dependencies such as information about - * specific fields and methods which were referenced, but does contain their - * declaring types and any other types used to locate such fields or methods. + * + * The principle structure and binary may be null if the compiler could not + * produce them. If neither could be produced, there is no corresponding entry + * for the type. + * + * The dependency info includes type references such as supertypes, field types, + * method parameter and return types, local variable types, types of + * intermediate expressions, etc. It also includes the namespaces (packages) in + * which names were looked up. It does not include finer grained + * dependencies such as information about specific fields and methods which were + * referenced, but does contain their declaring types and any other types used + * to locate such fields or methods. */ - - -//import java.util.Enumeration; +// import java.util.Enumeration; import java.util.Hashtable; import java.util.Map; @@ -42,42 +43,48 @@ import net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit; import net.sourceforge.phpdt.internal.compiler.impl.ReferenceContext; public class CompilationResult { - + public IProblem problems[]; + public IProblem tasks[]; + public int problemCount; + public int taskCount; + public ICompilationUnit compilationUnit; + private Map problemsMap; + private Map firstErrorsMap; + private int maxProblemPerUnit; + public char[][][] qualifiedReferences; + public char[][] simpleNameReferences; public int lineSeparatorPositions[]; -// public Hashtable compiledTypes = new Hashtable(11); + + // public Hashtable compiledTypes = new Hashtable(11); public int unitIndex, totalUnitsKnown; + public boolean hasBeenAccepted = false; + public char[] fileName; - - public CompilationResult( - char[] fileName, - int unitIndex, - int totalUnitsKnown, - int maxProblemPerUnit){ - + + public CompilationResult(char[] fileName, int unitIndex, + int totalUnitsKnown, int maxProblemPerUnit) { + this.fileName = fileName; this.unitIndex = unitIndex; this.totalUnitsKnown = totalUnitsKnown; this.maxProblemPerUnit = maxProblemPerUnit; } - - public CompilationResult( - ICompilationUnit compilationUnit, - int unitIndex, - int totalUnitsKnown, - int maxProblemPerUnit){ - + + public CompilationResult(ICompilationUnit compilationUnit, int unitIndex, + int totalUnitsKnown, int maxProblemPerUnit) { + this.fileName = compilationUnit.getFileName(); this.compilationUnit = compilationUnit; this.unitIndex = unitIndex; @@ -85,38 +92,42 @@ public class CompilationResult { this.maxProblemPerUnit = maxProblemPerUnit; } - private int computePriority(IProblem problem){ - + private int computePriority(IProblem problem) { + final int P_STATIC = 1000; final int P_OUTSIDE_METHOD = 4000; final int P_FIRST_ERROR = 2000; final int P_ERROR = 10000; - - int priority = 1000 - problem.getSourceLineNumber(); // early problems first - if (priority < 0) priority = 0; - if (problem.isError()){ + + int priority = 1000 - problem.getSourceLineNumber(); // early + // problems + // first + if (priority < 0) + priority = 0; + if (problem.isError()) { priority += P_ERROR; } - ReferenceContext context = problemsMap == null ? null : (ReferenceContext) problemsMap.get(problem); - if (context != null){ -// if (context instanceof AbstractMethodDeclaration){ -// AbstractMethodDeclaration method = (AbstractMethodDeclaration) context; -// if (method.isStatic()) { -// priority += P_STATIC; -// } -// } else { + ReferenceContext context = problemsMap == null ? null + : (ReferenceContext) problemsMap.get(problem); + if (context != null) { + // if (context instanceof AbstractMethodDeclaration){ + // AbstractMethodDeclaration method = (AbstractMethodDeclaration) + // context; + // if (method.isStatic()) { + // priority += P_STATIC; + // } + // } else { priority += P_OUTSIDE_METHOD; -// } + // } } else { priority += P_OUTSIDE_METHOD; } - if (firstErrorsMap.containsKey(problem)){ + if (firstErrorsMap.containsKey(problem)) { priority += P_FIRST_ERROR; } return priority; } - public IProblem[] getAllProblems() { IProblem[] problems = this.getProblems(); int problemCount = problems != null ? problems.length : 0; @@ -147,7 +158,8 @@ public class CompilationResult { IProblem currentProblem = null; if (nextProblem != null) { if (nextTask != null) { - if (nextProblem.getSourceStart() < nextTask.getSourceStart()) { + if (nextProblem.getSourceStart() < nextTask + .getSourceStart()) { currentProblem = nextProblem; problemIndex++; } else { @@ -168,100 +180,109 @@ public class CompilationResult { } return allProblems; } - -// public ClassFile[] getClassFiles() { -// Enumeration enum = compiledTypes.elements(); -// ClassFile[] classFiles = new ClassFile[compiledTypes.size()]; -// int index = 0; -// while (enum.hasMoreElements()){ -// classFiles[index++] = (ClassFile)enum.nextElement(); -// } -// return classFiles; -// } + + // public ClassFile[] getClassFiles() { + // Enumeration enum = compiledTypes.elements(); + // ClassFile[] classFiles = new ClassFile[compiledTypes.size()]; + // int index = 0; + // while (enum.hasMoreElements()){ + // classFiles[index++] = (ClassFile)enum.nextElement(); + // } + // return classFiles; + // } /** - * Answer the initial compilation unit corresponding to the present compilation result + * Answer the initial compilation unit corresponding to the present + * compilation result */ - public ICompilationUnit getCompilationUnit(){ + public ICompilationUnit getCompilationUnit() { return compilationUnit; } /** * Answer the initial file name */ - public char[] getFileName(){ + public char[] getFileName() { return fileName; } - + /** * Answer the errors encountered during compilation. */ public IProblem[] getErrors() { - + IProblem[] problems = getProblems(); int errorCount = 0; for (int i = 0; i < this.problemCount; i++) { - if (problems[i].isError()) errorCount++; + if (problems[i].isError()) + errorCount++; } - if (errorCount == this.problemCount) return problems; + if (errorCount == this.problemCount) + return problems; IProblem[] errors = new IProblem[errorCount]; int index = 0; for (int i = 0; i < this.problemCount; i++) { - if (problems[i].isError()) errors[index++] = problems[i]; + if (problems[i].isError()) + errors[index++] = problems[i]; } return errors; } - + /** * Answer the problems (errors and warnings) encountered during compilation. - * - * This is not a compiler internal API - it has side-effects ! - * It is intended to be used only once all problems have been detected, - * and makes sure the problems slot as the exact size of the number of - * problems. + * + * This is not a compiler internal API - it has side-effects ! It is + * intended to be used only once all problems have been detected, and makes + * sure the problems slot as the exact size of the number of problems. */ public IProblem[] getProblems() { - + // Re-adjust the size of the problems if necessary. if (problems != null) { - + if (this.problemCount != problems.length) { - System.arraycopy(problems, 0, (problems = new IProblem[problemCount]), 0, problemCount); + System.arraycopy(problems, 0, + (problems = new IProblem[problemCount]), 0, + problemCount); } - - if (this.maxProblemPerUnit > 0 && this.problemCount > this.maxProblemPerUnit){ + + if (this.maxProblemPerUnit > 0 + && this.problemCount > this.maxProblemPerUnit) { quickPrioritize(problems, 0, problemCount - 1); this.problemCount = this.maxProblemPerUnit; - System.arraycopy(problems, 0, (problems = new IProblem[problemCount]), 0, problemCount); + System.arraycopy(problems, 0, + (problems = new IProblem[problemCount]), 0, + problemCount); } - + // Sort problems per source positions. - quickSort(problems, 0, problems.length-1); + quickSort(problems, 0, problems.length - 1); } return problems; } /** * Answer the tasks (TO-DO, ...) encountered during compilation. - * - * This is not a compiler internal API - it has side-effects ! - * It is intended to be used only once all problems have been detected, - * and makes sure the problems slot as the exact size of the number of - * problems. + * + * This is not a compiler internal API - it has side-effects ! It is + * intended to be used only once all problems have been detected, and makes + * sure the problems slot as the exact size of the number of problems. */ public IProblem[] getTasks() { - + // Re-adjust the size of the tasks if necessary. if (this.tasks != null) { - + if (this.taskCount != this.tasks.length) { - System.arraycopy(this.tasks, 0, (this.tasks = new IProblem[this.taskCount]), 0, this.taskCount); + System.arraycopy(this.tasks, 0, + (this.tasks = new IProblem[this.taskCount]), 0, + this.taskCount); } - quickSort(tasks, 0, tasks.length-1); + quickSort(tasks, 0, tasks.length - 1); } return this.tasks; } - + public boolean hasErrors() { if (problems != null) @@ -277,12 +298,13 @@ public class CompilationResult { return problemCount != 0; } - public boolean hasSyntaxError(){ + public boolean hasSyntaxError() { if (problems != null) for (int i = 0; i < problemCount; i++) { IProblem problem = problems[i]; - if ((problem.getID() & IProblem.Syntax) != 0 && problem.isError()) + if ((problem.getID() & IProblem.Syntax) != 0 + && problem.isError()) return true; } return false; @@ -291,7 +313,7 @@ public class CompilationResult { public boolean hasTasks() { return this.taskCount != 0; } - + public boolean hasWarnings() { if (problems != null) @@ -301,11 +323,12 @@ public class CompilationResult { } return false; } - + private static void quickSort(IProblem[] list, int left, int right) { - if (left >= right) return; - + if (left >= right) + return; + // sort the problems by their source start position... starting with 0 int original_left = left; int original_right = right; @@ -328,12 +351,14 @@ public class CompilationResult { if (left < original_right) quickSort(list, left, original_right); } - + private void quickPrioritize(IProblem[] list, int left, int right) { - - if (left >= right) return; - - // sort the problems by their priority... starting with the highest priority + + if (left >= right) + return; + + // sort the problems by their priority... starting with the highest + // priority int original_left = left; int original_right = right; int mid = computePriority(list[(left + right) / 2]); @@ -355,15 +380,14 @@ public class CompilationResult { if (left < original_right) quickPrioritize(list, left, original_right); } - + /** * For now, remember the compiled type using its compound name. */ -// public void record(char[] typeName, ClassFile classFile) { -// -// compiledTypes.put(typeName, classFile); -// } - + // public void record(char[] typeName, ClassFile classFile) { + // + // compiledTypes.put(typeName, classFile); + // } public void record(IProblem newProblem, ReferenceContext referenceContext) { if (newProblem.getID() == IProblem.Task) { @@ -373,13 +397,18 @@ public class CompilationResult { if (problemCount == 0) { problems = new IProblem[5]; } else if (problemCount == problems.length) { - System.arraycopy(problems, 0, (problems = new IProblem[problemCount * 2]), 0, problemCount); + System.arraycopy(problems, 0, + (problems = new IProblem[problemCount * 2]), 0, + problemCount); } problems[problemCount++] = newProblem; - if (referenceContext != null){ - if (problemsMap == null) problemsMap = new Hashtable(5); - if (firstErrorsMap == null) firstErrorsMap = new Hashtable(5); - if (newProblem.isError() && !referenceContext.hasErrors()) firstErrorsMap.put(newProblem, newProblem); + if (referenceContext != null) { + if (problemsMap == null) + problemsMap = new Hashtable(5); + if (firstErrorsMap == null) + firstErrorsMap = new Hashtable(5); + if (newProblem.isError() && !referenceContext.hasErrors()) + firstErrorsMap.put(newProblem, newProblem); problemsMap.put(newProblem, referenceContext); } } @@ -388,43 +417,45 @@ public class CompilationResult { if (this.taskCount == 0) { this.tasks = new IProblem[5]; } else if (this.taskCount == this.tasks.length) { - System.arraycopy(this.tasks, 0, (this.tasks = new IProblem[this.taskCount * 2]), 0, this.taskCount); + System.arraycopy(this.tasks, 0, + (this.tasks = new IProblem[this.taskCount * 2]), 0, + this.taskCount); } this.tasks[this.taskCount++] = newProblem; } - - public CompilationResult tagAsAccepted(){ + + public CompilationResult tagAsAccepted() { this.hasBeenAccepted = true; this.problemsMap = null; // flush return this; } - - public String toString(){ + + public String toString() { StringBuffer buffer = new StringBuffer(); - if (this.fileName != null){ + if (this.fileName != null) { buffer.append("Filename : ").append(this.fileName).append('\n'); //$NON-NLS-1$ } -// if (this.compiledTypes != null){ -// buffer.append("COMPILED type(s) \n"); //$NON-NLS-1$ -// Enumeration typeNames = this.compiledTypes.keys(); -// while (typeNames.hasMoreElements()) { -// char[] typeName = (char[]) typeNames.nextElement(); -// buffer.append("\t - ").append(typeName).append('\n'); //$NON-NLS-1$ -// -// } -// } else { -// buffer.append("No COMPILED type\n"); //$NON-NLS-1$ -// } - if (problems != null){ + // if (this.compiledTypes != null){ + // buffer.append("COMPILED type(s) \n"); //$NON-NLS-1$ + // Enumeration typeNames = this.compiledTypes.keys(); + // while (typeNames.hasMoreElements()) { + // char[] typeName = (char[]) typeNames.nextElement(); + // buffer.append("\t - ").append(typeName).append('\n'); //$NON-NLS-1$ + // + // } + // } else { + // buffer.append("No COMPILED type\n"); //$NON-NLS-1$ + // } + if (problems != null) { buffer.append(this.problemCount).append(" PROBLEM(s) detected \n"); //$NON-NLS-1$//$NON-NLS-2$ - for (int i = 0; i < this.problemCount; i++){ + for (int i = 0; i < this.problemCount; i++) { buffer.append("\t - ").append(this.problems[i]).append('\n'); //$NON-NLS-1$ } } else { buffer.append("No PROBLEM\n"); //$NON-NLS-1$ - } + } return buffer.toString(); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/Compiler.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/Compiler.java index a360dae..76286a7 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/Compiler.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/Compiler.java @@ -9,6 +9,7 @@ * IBM Corporation - initial API and implementation *******************************************************************************/ package net.sourceforge.phpdt.internal.compiler; + import java.io.PrintWriter; import java.io.StringWriter; import java.util.Map; @@ -32,481 +33,534 @@ import net.sourceforge.phpdt.internal.compiler.problem.ProblemSeverities; import net.sourceforge.phpdt.internal.compiler.util.Util; public class Compiler implements ITypeRequestor, ProblemSeverities { - public UnitParser parser; - public ICompilerRequestor requestor; - public CompilerOptions options; - public ProblemReporter problemReporter; - // management of unit to be processed - //public CompilationUnitResult currentCompilationUnitResult; - public CompilationUnitDeclaration[] unitsToProcess; - public int totalUnits; // (totalUnits-1) gives the last unit in unitToProcess - // name lookup - public LookupEnvironment lookupEnvironment; - // ONCE STABILIZED, THESE SHOULD RETURN TO A FINAL FIELD - public static boolean DEBUG = false; - public int parseThreshold = -1; - // number of initial units parsed at once (-1: none) - /* - * Static requestor reserved to listening compilation results in debug mode, - * so as for example to monitor compiler activity independantly from a - * particular builder implementation. It is reset at the end of compilation, - * and should not persist any information after having been reset. - */ - // public static IDebugRequestor DebugRequestor = null; - /** - * Answer a new compiler using the given name environment and compiler - * options. The environment and options will be in effect for the lifetime of - * the compiler. When the compiler is run, compilation results are sent to - * the given requestor. - * - * @param environment - * org.eclipse.jdt.internal.compiler.api.env.INameEnvironment - * Environment used by the compiler in order to resolve type and - * package names. The name environment implements the actual - * connection of the compiler to the outside world (e.g. in batch - * mode the name environment is performing pure file accesses, - * reuse previous build state or connection to repositories). - * Note: the name environment is responsible for implementing the - * actual classpath rules. - * - * @param policy - * org.eclipse.jdt.internal.compiler.api.problem.IErrorHandlingPolicy - * Configurable part for problem handling, allowing the compiler - * client to specify the rules for handling problems (stop on - * first error or accumulate them all) and at the same time - * perform some actions such as opening a dialog in UI when - * compiling interactively. - * @see org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies - * - * @param requestor - * org.eclipse.jdt.internal.compiler.api.ICompilerRequestor - * Component which will receive and persist all compilation - * results and is intended to consume them as they are produced. - * Typically, in a batch compiler, it is responsible for writing - * out the actual .class files to the file system. - * @see org.eclipse.jdt.internal.compiler.CompilationResult - * - * @param problemFactory - * org.eclipse.jdt.internal.compiler.api.problem.IProblemFactory - * Factory used inside the compiler to create problem descriptors. - * It allows the compiler client to supply its own representation - * of compilation problems in order to avoid object conversions. - * Note that the factory is not supposed to accumulate the created - * problems, the compiler will gather them all and hand them back - * as part of the compilation unit result. - */ - public Compiler(INameEnvironment environment, IErrorHandlingPolicy policy, - Map settings, final ICompilerRequestor requestor, - IProblemFactory problemFactory) { - // create a problem handler given a handling policy - this.options = new CompilerOptions(settings); - // wrap requestor in DebugRequestor if one is specified - // if(DebugRequestor == null) { - this.requestor = requestor; - // } else { - // this.requestor = new ICompilerRequestor(){ - // public void acceptResult(CompilationResult result){ - // if (DebugRequestor.isActive()){ - // DebugRequestor.acceptDebugResult(result); - // } - // requestor.acceptResult(result); - // } - // }; - // } - this.problemReporter = new ProblemReporter(policy, this.options, - problemFactory); - this.lookupEnvironment = new LookupEnvironment(this, problemReporter, - environment); //options, problemReporter, environment); - this.parser = new UnitParser(problemReporter); - // this.options.parseLiteralExpressionsAsConstants, - // options.sourceLevel >= CompilerOptions.JDK1_4); - } - /** - * Answer a new compiler using the given name environment and compiler - * options. The environment and options will be in effect for the lifetime of - * the compiler. When the compiler is run, compilation results are sent to - * the given requestor. - * - * @param environment - * org.eclipse.jdt.internal.compiler.api.env.INameEnvironment - * Environment used by the compiler in order to resolve type and - * package names. The name environment implements the actual - * connection of the compiler to the outside world (e.g. in batch - * mode the name environment is performing pure file accesses, - * reuse previous build state or connection to repositories). - * Note: the name environment is responsible for implementing the - * actual classpath rules. - * - * @param policy - * org.eclipse.jdt.internal.compiler.api.problem.IErrorHandlingPolicy - * Configurable part for problem handling, allowing the compiler - * client to specify the rules for handling problems (stop on - * first error or accumulate them all) and at the same time - * perform some actions such as opening a dialog in UI when - * compiling interactively. - * @see org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies - * - * @param requestor - * org.eclipse.jdt.internal.compiler.api.ICompilerRequestor - * Component which will receive and persist all compilation - * results and is intended to consume them as they are produced. - * Typically, in a batch compiler, it is responsible for writing - * out the actual .class files to the file system. - * @see org.eclipse.jdt.internal.compiler.CompilationResult - * - * @param problemFactory - * org.eclipse.jdt.internal.compiler.api.problem.IProblemFactory - * Factory used inside the compiler to create problem descriptors. - * It allows the compiler client to supply its own representation - * of compilation problems in order to avoid object conversions. - * Note that the factory is not supposed to accumulate the created - * problems, the compiler will gather them all and hand them back - * as part of the compilation unit result. - * @param parseLiteralExpressionsAsConstants - * boolean This parameter is used to optimize the - * literals or leave them as they are in the source. If you put - * true, "Hello" . " world" will be converted to "Hello world". - */ - public Compiler(INameEnvironment environment, IErrorHandlingPolicy policy, - Map settings, final ICompilerRequestor requestor, - IProblemFactory problemFactory, boolean parseLiteralExpressionsAsConstants) { - // create a problem handler given a handling policy - this.options = new CompilerOptions(settings); - // wrap requestor in DebugRequestor if one is specified - // if(DebugRequestor == null) { - this.requestor = requestor; - // } else { - // this.requestor = new ICompilerRequestor(){ - // public void acceptResult(CompilationResult result){ - // if (DebugRequestor.isActive()){ - // DebugRequestor.acceptDebugResult(result); - // } - // requestor.acceptResult(result); - // } - // }; - // } - this.problemReporter = new ProblemReporter(policy, this.options, - problemFactory); - this.lookupEnvironment = new LookupEnvironment(this, problemReporter, - environment);//options, problemReporter, environment); - this.parser = new UnitParser(problemReporter); - // parseLiteralExpressionsAsConstants, - // this.options.sourceLevel >= CompilerOptions.JDK1_4); - } - /** - * Add an additional binary type - */ - public void accept(IBinaryType binaryType, PackageBinding packageBinding) { - lookupEnvironment.createBinaryTypeFrom(binaryType, packageBinding); - } - /** - * Add an additional compilation unit into the loop -> build compilation unit - * declarations, their bindings and record their results. - */ - public void accept(ICompilationUnit sourceUnit) { - // Switch the current policy and compilation result for this unit to the - // requested one. - CompilationResult unitResult = new CompilationResult(sourceUnit, - totalUnits, totalUnits, this.options.maxProblemsPerUnit); - try { - // diet parsing for large collection of unit - CompilationUnitDeclaration parsedUnit; - if (totalUnits < parseThreshold) { - parsedUnit = parser.parse(sourceUnit, unitResult, false); - } else { - parsedUnit = parser.dietParse(sourceUnit, unitResult); - } - if (options.verbose) { - String count = String.valueOf(totalUnits + 1); - System.out.println(Util.bind("compilation.request", //$NON-NLS-1$ - new String[]{count, count, new String(sourceUnit.getFileName())})); - } - // initial type binding creation - lookupEnvironment.buildTypeBindings(parsedUnit); - this.addCompilationUnit(sourceUnit, parsedUnit); - // binding resolution - lookupEnvironment.completeTypeBindings(parsedUnit); - } catch (AbortCompilationUnit e) { - // at this point, currentCompilationUnitResult may not be sourceUnit, but - // some other - // one requested further along to resolve sourceUnit. - if (unitResult.compilationUnit == sourceUnit) { // only report once - requestor.acceptResult(unitResult.tagAsAccepted()); - } else { - throw e; // want to abort enclosing request to compile - } - } - } - /** - * Add additional source types - */ - public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding) { - problemReporter.abortDueToInternalError(Util.bind( - "abort.againstSourceModel ", //$NON-NLS-1$ - String.valueOf(sourceTypes[0].getName()), String.valueOf(sourceTypes[0] - .getFileName()))); - } - protected void addCompilationUnit(ICompilationUnit sourceUnit, - CompilationUnitDeclaration parsedUnit) { - // append the unit to the list of ones to process later on - int size = unitsToProcess.length; - if (totalUnits == size) - // when growing reposition units starting at position 0 - System.arraycopy(unitsToProcess, 0, - (unitsToProcess = new CompilationUnitDeclaration[size * 2]), 0, - totalUnits); - unitsToProcess[totalUnits++] = parsedUnit; - } - /** - * Add the initial set of compilation units into the loop -> build - * compilation unit declarations, their bindings and record their results. - */ - protected void beginToCompile(ICompilationUnit[] sourceUnits) { - int maxUnits = sourceUnits.length; - totalUnits = 0; - unitsToProcess = new CompilationUnitDeclaration[maxUnits]; - // Switch the current policy and compilation result for this unit to the - // requested one. - for (int i = 0; i < maxUnits; i++) { - CompilationUnitDeclaration parsedUnit; - CompilationResult unitResult = new CompilationResult(sourceUnits[i], i, - maxUnits, this.options.maxProblemsPerUnit); - try { - // diet parsing for large collection of units - if (totalUnits < parseThreshold) { - parsedUnit = parser.parse(sourceUnits[i], unitResult, false); - } else { - parsedUnit = parser.dietParse(sourceUnits[i], unitResult); - } - if (options.verbose) { - System.out.println(Util.bind("compilation.request", //$NON-NLS-1$ - new String[]{String.valueOf(i + 1), String.valueOf(maxUnits), - new String(sourceUnits[i].getFileName())})); - } - // initial type binding creation - // lookupEnvironment.buildTypeBindings(parsedUnit); - this.addCompilationUnit(sourceUnits[i], parsedUnit); - //} catch (AbortCompilationUnit e) { - //requestor.acceptResult(unitResult.tagAsAccepted()); - } finally { - sourceUnits[i] = null; // no longer hold onto the unit - } - } - // binding resolution - lookupEnvironment.completeTypeBindings(); - } - /** - * General API -> compile each of supplied files -> recompile any required - * types for which we have an incomplete principle structure - */ - public void compile(ICompilationUnit[] sourceUnits) { - CompilationUnitDeclaration unit = null; - int i = 0; - try { - // build and record parsed units - beginToCompile(sourceUnits); - // process all units (some more could be injected in the loop by the - // lookup environment) - for (; i < totalUnits; i++) { - unit = unitsToProcess[i]; - try { - if (options.verbose) - System.out.println(Util.bind("compilation.process", //$NON-NLS-1$ - new String[]{String.valueOf(i + 1), String.valueOf(totalUnits), - new String(unitsToProcess[i].getFileName())})); - process(unit, i); - } finally { - // cleanup compilation unit result - unit.cleanUp(); - if (options.verbose) - System.out.println(Util.bind("compilation.done", //$NON-NLS-1$ - new String[]{String.valueOf(i + 1), String.valueOf(totalUnits), - new String(unitsToProcess[i].getFileName())})); - } - unitsToProcess[i] = null; // release reference to processed unit - // declaration - requestor.acceptResult(unit.compilationResult.tagAsAccepted()); - } - } catch (AbortCompilation e) { - this.handleInternalException(e, unit); - } catch (Error e) { - this.handleInternalException(e, unit, null); - throw e; // rethrow - } catch (RuntimeException e) { - this.handleInternalException(e, unit, null); - throw e; // rethrow - } finally { - this.reset(); - } - // if (options.verbose) { - // if (totalUnits > 1) { - // System.out.println( - // ProjectPrefUtil.bind("compilation.units" , String.valueOf(totalUnits))); - // //$NON-NLS-1$ - // } else { - // System.out.println( - // ProjectPrefUtil.bind("compilation.unit" , String.valueOf(totalUnits))); - // //$NON-NLS-1$ - // } - // } - } - protected void getMethodBodies(CompilationUnitDeclaration unit, int place) { - //fill the methods bodies in order for the code to be generated - if (unit.ignoreMethodBodies) { - unit.ignoreFurtherInvestigation = true; - return; - // if initial diet parse did not work, no need to dig into method bodies. - } - if (place < parseThreshold) - return; //work already done ... - //real parse of the method.... - parser.scanner.setSource(unit.compilationResult.compilationUnit - .getContents()); - if (unit.types != null) { - for (int i = unit.types.size(); --i >= 0;) - if (unit.types.get(i) instanceof TypeDeclaration) { - ((TypeDeclaration) unit.types.get(i)).parseMethod(parser, unit); - } - } - } - /* - * Compiler crash recovery in case of unexpected runtime exceptions - */ - protected void handleInternalException(Throwable internalException, - CompilationUnitDeclaration unit, CompilationResult result) { - /* dump a stack trace to the console */ - internalException.printStackTrace(); - /* find a compilation result */ - if ((unit != null)) // basing result upon the current unit if available - result = unit.compilationResult; // current unit being processed ? - if ((result == null) && (unitsToProcess != null) && (totalUnits > 0)) - result = unitsToProcess[totalUnits - 1].compilationResult; - // last unit in beginToCompile ? - if (result != null) { - /* create and record a compilation problem */ - StringWriter stringWriter = new StringWriter(); - PrintWriter writer = new PrintWriter(stringWriter); - internalException.printStackTrace(writer); - StringBuffer buffer = stringWriter.getBuffer(); - String[] pbArguments = new String[]{Util - .bind("compilation.internalError") - //$NON-NLS-1$ - + "\n" //$NON-NLS-1$ - + buffer.toString()}; - result.record(problemReporter.createProblem(result.getFileName(), - IProblem.Unclassified, pbArguments, pbArguments, Error, // severity - 0, // source start - 0, // source end - 0, // line number - unit, result), unit); - /* hand back the compilation result */ - if (!result.hasBeenAccepted) { - requestor.acceptResult(result.tagAsAccepted()); - } - } - } - /* - * Compiler recovery in case of internal AbortCompilation event - */ - protected void handleInternalException(AbortCompilation abortException, - CompilationUnitDeclaration unit) { - /* - * special treatment for SilentAbort: silently cancelling the compilation - * process - */ - if (abortException.isSilent) { - if (abortException.silentException == null) { - return; - } else { - throw abortException.silentException; - } - } - /* uncomment following line to see where the abort came from */ - // abortException.printStackTrace(); - // Exception may tell which compilation result it is related, and which - // problem caused it - CompilationResult result = abortException.compilationResult; - if ((result == null) && (unit != null)) - result = unit.compilationResult; // current unit being processed ? - if ((result == null) && (unitsToProcess != null) && (totalUnits > 0)) - result = unitsToProcess[totalUnits - 1].compilationResult; - // last unit in beginToCompile ? - if (result != null && !result.hasBeenAccepted) { - /* distant problem which could not be reported back there */ - if (abortException.problemId != 0) { - result.record(problemReporter.createProblem(result.getFileName(), - abortException.problemId, abortException.problemArguments, - abortException.messageArguments, Error, // severity - 0, // source start - 0, // source end - 0, // line number - unit, result), unit); - } else { - /* distant internal exception which could not be reported back there */ - if (abortException.exception != null) { - this.handleInternalException(abortException.exception, null, result); - return; - } - } - /* hand back the compilation result */ - if (!result.hasBeenAccepted) { - requestor.acceptResult(result.tagAsAccepted()); - } - } else { - /* - * if (abortException.problemId != 0){ IProblem problem = - * problemReporter.createProblem( "???".toCharArray(), - * abortException.problemId, abortException.problemArguments, Error, // - * severity 0, // source start 0, // source end 0); // line number - * System.out.println(problem.getMessage()); } - */ - abortException.printStackTrace(); - } - } - /** - * Process a compilation unit already parsed and build. - */ - public void process(CompilationUnitDeclaration unit, int i) { - getMethodBodies(unit, i); - // fault in fields & methods - if (unit.scope != null) - unit.scope.faultInTypes(); - // verify inherited methods - // if (unit.scope != null) - // unit.scope.verifyMethods(lookupEnvironment.methodVerifier()); - // type checking - unit.resolve(); - // flow analysis - unit.analyseCode(); - // code generation - // unit.generateCode(); - // reference info - // if (options.produceReferenceInfo && unit.scope != null) - // unit.scope.storeDependencyInfo(); - // refresh the total number of units known at this stage - unit.compilationResult.totalUnitsKnown = totalUnits; - } - public void reset() { - lookupEnvironment.reset(); - parser.scanner.source = null; - unitsToProcess = null; - // if (DebugRequestor != null) DebugRequestor.reset(); - } - /** - * Internal API used to resolve a given compilation unit. Can run a subset of the compilation process + public UnitParser parser; + + public ICompilerRequestor requestor; + + public CompilerOptions options; + + public ProblemReporter problemReporter; + + // management of unit to be processed + // public CompilationUnitResult currentCompilationUnitResult; + public CompilationUnitDeclaration[] unitsToProcess; + + public int totalUnits; // (totalUnits-1) gives the last unit in + // unitToProcess + + // name lookup + public LookupEnvironment lookupEnvironment; + + // ONCE STABILIZED, THESE SHOULD RETURN TO A FINAL FIELD + public static boolean DEBUG = false; + + public int parseThreshold = -1; + + // number of initial units parsed at once (-1: none) + /* + * Static requestor reserved to listening compilation results in debug mode, + * so as for example to monitor compiler activity independantly from a + * particular builder implementation. It is reset at the end of compilation, + * and should not persist any information after having been reset. + */ + // public static IDebugRequestor DebugRequestor = null; + /** + * Answer a new compiler using the given name environment and compiler + * options. The environment and options will be in effect for the lifetime + * of the compiler. When the compiler is run, compilation results are sent + * to the given requestor. + * + * @param environment + * org.eclipse.jdt.internal.compiler.api.env.INameEnvironment + * Environment used by the compiler in order to resolve type and + * package names. The name environment implements the actual + * connection of the compiler to the outside world (e.g. in batch + * mode the name environment is performing pure file accesses, + * reuse previous build state or connection to repositories). + * Note: the name environment is responsible for implementing the + * actual classpath rules. + * + * @param policy + * org.eclipse.jdt.internal.compiler.api.problem.IErrorHandlingPolicy + * Configurable part for problem handling, allowing the compiler + * client to specify the rules for handling problems (stop on + * first error or accumulate them all) and at the same time + * perform some actions such as opening a dialog in UI when + * compiling interactively. + * @see org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies + * + * @param requestor + * org.eclipse.jdt.internal.compiler.api.ICompilerRequestor + * Component which will receive and persist all compilation + * results and is intended to consume them as they are produced. + * Typically, in a batch compiler, it is responsible for writing + * out the actual .class files to the file system. + * @see org.eclipse.jdt.internal.compiler.CompilationResult + * + * @param problemFactory + * org.eclipse.jdt.internal.compiler.api.problem.IProblemFactory + * Factory used inside the compiler to create problem + * descriptors. It allows the compiler client to supply its own + * representation of compilation problems in order to avoid + * object conversions. Note that the factory is not supposed to + * accumulate the created problems, the compiler will gather them + * all and hand them back as part of the compilation unit result. + */ + public Compiler(INameEnvironment environment, IErrorHandlingPolicy policy, + Map settings, final ICompilerRequestor requestor, + IProblemFactory problemFactory) { + // create a problem handler given a handling policy + this.options = new CompilerOptions(settings); + // wrap requestor in DebugRequestor if one is specified + // if(DebugRequestor == null) { + this.requestor = requestor; + // } else { + // this.requestor = new ICompilerRequestor(){ + // public void acceptResult(CompilationResult result){ + // if (DebugRequestor.isActive()){ + // DebugRequestor.acceptDebugResult(result); + // } + // requestor.acceptResult(result); + // } + // }; + // } + this.problemReporter = new ProblemReporter(policy, this.options, + problemFactory); + this.lookupEnvironment = new LookupEnvironment(this, problemReporter, + environment); // options, problemReporter, environment); + this.parser = new UnitParser(problemReporter); + // this.options.parseLiteralExpressionsAsConstants, + // options.sourceLevel >= CompilerOptions.JDK1_4); + } + + /** + * Answer a new compiler using the given name environment and compiler + * options. The environment and options will be in effect for the lifetime + * of the compiler. When the compiler is run, compilation results are sent + * to the given requestor. + * + * @param environment + * org.eclipse.jdt.internal.compiler.api.env.INameEnvironment + * Environment used by the compiler in order to resolve type and + * package names. The name environment implements the actual + * connection of the compiler to the outside world (e.g. in batch + * mode the name environment is performing pure file accesses, + * reuse previous build state or connection to repositories). + * Note: the name environment is responsible for implementing the + * actual classpath rules. + * + * @param policy + * org.eclipse.jdt.internal.compiler.api.problem.IErrorHandlingPolicy + * Configurable part for problem handling, allowing the compiler + * client to specify the rules for handling problems (stop on + * first error or accumulate them all) and at the same time + * perform some actions such as opening a dialog in UI when + * compiling interactively. + * @see org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies + * + * @param requestor + * org.eclipse.jdt.internal.compiler.api.ICompilerRequestor + * Component which will receive and persist all compilation + * results and is intended to consume them as they are produced. + * Typically, in a batch compiler, it is responsible for writing + * out the actual .class files to the file system. + * @see org.eclipse.jdt.internal.compiler.CompilationResult + * + * @param problemFactory + * org.eclipse.jdt.internal.compiler.api.problem.IProblemFactory + * Factory used inside the compiler to create problem + * descriptors. It allows the compiler client to supply its own + * representation of compilation problems in order to avoid + * object conversions. Note that the factory is not supposed to + * accumulate the created problems, the compiler will gather them + * all and hand them back as part of the compilation unit result. + * @param parseLiteralExpressionsAsConstants + * boolean This parameter is used to optimize the + * literals or leave them as they are in the source. If you put + * true, "Hello" . " world" will be converted to "Hello world". + */ + public Compiler(INameEnvironment environment, IErrorHandlingPolicy policy, + Map settings, final ICompilerRequestor requestor, + IProblemFactory problemFactory, + boolean parseLiteralExpressionsAsConstants) { + // create a problem handler given a handling policy + this.options = new CompilerOptions(settings); + // wrap requestor in DebugRequestor if one is specified + // if(DebugRequestor == null) { + this.requestor = requestor; + // } else { + // this.requestor = new ICompilerRequestor(){ + // public void acceptResult(CompilationResult result){ + // if (DebugRequestor.isActive()){ + // DebugRequestor.acceptDebugResult(result); + // } + // requestor.acceptResult(result); + // } + // }; + // } + this.problemReporter = new ProblemReporter(policy, this.options, + problemFactory); + this.lookupEnvironment = new LookupEnvironment(this, problemReporter, + environment);// options, problemReporter, environment); + this.parser = new UnitParser(problemReporter); + // parseLiteralExpressionsAsConstants, + // this.options.sourceLevel >= CompilerOptions.JDK1_4); + } + + /** + * Add an additional binary type + */ + public void accept(IBinaryType binaryType, PackageBinding packageBinding) { + lookupEnvironment.createBinaryTypeFrom(binaryType, packageBinding); + } + + /** + * Add an additional compilation unit into the loop -> build compilation + * unit declarations, their bindings and record their results. + */ + public void accept(ICompilationUnit sourceUnit) { + // Switch the current policy and compilation result for this unit to the + // requested one. + CompilationResult unitResult = new CompilationResult(sourceUnit, + totalUnits, totalUnits, this.options.maxProblemsPerUnit); + try { + // diet parsing for large collection of unit + CompilationUnitDeclaration parsedUnit; + if (totalUnits < parseThreshold) { + parsedUnit = parser.parse(sourceUnit, unitResult, false); + } else { + parsedUnit = parser.dietParse(sourceUnit, unitResult); + } + if (options.verbose) { + String count = String.valueOf(totalUnits + 1); + System.out.println(Util.bind("compilation.request", //$NON-NLS-1$ + new String[] { count, count, + new String(sourceUnit.getFileName()) })); + } + // initial type binding creation + lookupEnvironment.buildTypeBindings(parsedUnit); + this.addCompilationUnit(sourceUnit, parsedUnit); + // binding resolution + lookupEnvironment.completeTypeBindings(parsedUnit); + } catch (AbortCompilationUnit e) { + // at this point, currentCompilationUnitResult may not be + // sourceUnit, but + // some other + // one requested further along to resolve sourceUnit. + if (unitResult.compilationUnit == sourceUnit) { // only report once + requestor.acceptResult(unitResult.tagAsAccepted()); + } else { + throw e; // want to abort enclosing request to compile + } + } + } + + /** + * Add additional source types */ - public CompilationUnitDeclaration resolve( - CompilationUnitDeclaration unit, - ICompilationUnit sourceUnit, - boolean verifyMethods, + public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding) { + problemReporter.abortDueToInternalError(Util.bind( + "abort.againstSourceModel ", //$NON-NLS-1$ + String.valueOf(sourceTypes[0].getName()), String + .valueOf(sourceTypes[0].getFileName()))); + } + + protected void addCompilationUnit(ICompilationUnit sourceUnit, + CompilationUnitDeclaration parsedUnit) { + // append the unit to the list of ones to process later on + int size = unitsToProcess.length; + if (totalUnits == size) + // when growing reposition units starting at position 0 + System + .arraycopy( + unitsToProcess, + 0, + (unitsToProcess = new CompilationUnitDeclaration[size * 2]), + 0, totalUnits); + unitsToProcess[totalUnits++] = parsedUnit; + } + + /** + * Add the initial set of compilation units into the loop -> build + * compilation unit declarations, their bindings and record their results. + */ + protected void beginToCompile(ICompilationUnit[] sourceUnits) { + int maxUnits = sourceUnits.length; + totalUnits = 0; + unitsToProcess = new CompilationUnitDeclaration[maxUnits]; + // Switch the current policy and compilation result for this unit to the + // requested one. + for (int i = 0; i < maxUnits; i++) { + CompilationUnitDeclaration parsedUnit; + CompilationResult unitResult = new CompilationResult( + sourceUnits[i], i, maxUnits, + this.options.maxProblemsPerUnit); + try { + // diet parsing for large collection of units + if (totalUnits < parseThreshold) { + parsedUnit = parser + .parse(sourceUnits[i], unitResult, false); + } else { + parsedUnit = parser.dietParse(sourceUnits[i], unitResult); + } + if (options.verbose) { + System.out + .println(Util.bind("compilation.request", //$NON-NLS-1$ + new String[] { + String.valueOf(i + 1), + String.valueOf(maxUnits), + new String(sourceUnits[i] + .getFileName()) })); + } + // initial type binding creation + // lookupEnvironment.buildTypeBindings(parsedUnit); + this.addCompilationUnit(sourceUnits[i], parsedUnit); + // } catch (AbortCompilationUnit e) { + // requestor.acceptResult(unitResult.tagAsAccepted()); + } finally { + sourceUnits[i] = null; // no longer hold onto the unit + } + } + // binding resolution + lookupEnvironment.completeTypeBindings(); + } + + /** + * General API -> compile each of supplied files -> recompile any required + * types for which we have an incomplete principle structure + */ + public void compile(ICompilationUnit[] sourceUnits) { + CompilationUnitDeclaration unit = null; + int i = 0; + try { + // build and record parsed units + beginToCompile(sourceUnits); + // process all units (some more could be injected in the loop by the + // lookup environment) + for (; i < totalUnits; i++) { + unit = unitsToProcess[i]; + try { + if (options.verbose) + System.out.println(Util.bind("compilation.process", //$NON-NLS-1$ + new String[] { + String.valueOf(i + 1), + String.valueOf(totalUnits), + new String(unitsToProcess[i] + .getFileName()) })); + process(unit, i); + } finally { + // cleanup compilation unit result + unit.cleanUp(); + if (options.verbose) + System.out.println(Util.bind("compilation.done", //$NON-NLS-1$ + new String[] { + String.valueOf(i + 1), + String.valueOf(totalUnits), + new String(unitsToProcess[i] + .getFileName()) })); + } + unitsToProcess[i] = null; // release reference to processed + // unit + // declaration + requestor.acceptResult(unit.compilationResult.tagAsAccepted()); + } + } catch (AbortCompilation e) { + this.handleInternalException(e, unit); + } catch (Error e) { + this.handleInternalException(e, unit, null); + throw e; // rethrow + } catch (RuntimeException e) { + this.handleInternalException(e, unit, null); + throw e; // rethrow + } finally { + this.reset(); + } + // if (options.verbose) { + // if (totalUnits > 1) { + // System.out.println( + // ProjectPrefUtil.bind("compilation.units" , + // String.valueOf(totalUnits))); + // //$NON-NLS-1$ + // } else { + // System.out.println( + // ProjectPrefUtil.bind("compilation.unit" , + // String.valueOf(totalUnits))); + // //$NON-NLS-1$ + // } + // } + } + + protected void getMethodBodies(CompilationUnitDeclaration unit, int place) { + // fill the methods bodies in order for the code to be generated + if (unit.ignoreMethodBodies) { + unit.ignoreFurtherInvestigation = true; + return; + // if initial diet parse did not work, no need to dig into method + // bodies. + } + if (place < parseThreshold) + return; // work already done ... + // real parse of the method.... + parser.scanner.setSource(unit.compilationResult.compilationUnit + .getContents()); + if (unit.types != null) { + for (int i = unit.types.size(); --i >= 0;) + if (unit.types.get(i) instanceof TypeDeclaration) { + ((TypeDeclaration) unit.types.get(i)).parseMethod(parser, + unit); + } + } + } + + /* + * Compiler crash recovery in case of unexpected runtime exceptions + */ + protected void handleInternalException(Throwable internalException, + CompilationUnitDeclaration unit, CompilationResult result) { + /* dump a stack trace to the console */ + internalException.printStackTrace(); + /* find a compilation result */ + if ((unit != null)) // basing result upon the current unit if available + result = unit.compilationResult; // current unit being processed + // ? + if ((result == null) && (unitsToProcess != null) && (totalUnits > 0)) + result = unitsToProcess[totalUnits - 1].compilationResult; + // last unit in beginToCompile ? + if (result != null) { + /* create and record a compilation problem */ + StringWriter stringWriter = new StringWriter(); + PrintWriter writer = new PrintWriter(stringWriter); + internalException.printStackTrace(writer); + StringBuffer buffer = stringWriter.getBuffer(); + String[] pbArguments = new String[] { Util + .bind("compilation.internalError") + //$NON-NLS-1$ + + "\n" //$NON-NLS-1$ + + buffer.toString() }; + result.record(problemReporter.createProblem(result.getFileName(), + IProblem.Unclassified, pbArguments, pbArguments, Error, // severity + 0, // source start + 0, // source end + 0, // line number + unit, result), unit); + /* hand back the compilation result */ + if (!result.hasBeenAccepted) { + requestor.acceptResult(result.tagAsAccepted()); + } + } + } + + /* + * Compiler recovery in case of internal AbortCompilation event + */ + protected void handleInternalException(AbortCompilation abortException, + CompilationUnitDeclaration unit) { + /* + * special treatment for SilentAbort: silently cancelling the + * compilation process + */ + if (abortException.isSilent) { + if (abortException.silentException == null) { + return; + } else { + throw abortException.silentException; + } + } + /* uncomment following line to see where the abort came from */ + // abortException.printStackTrace(); + // Exception may tell which compilation result it is related, and which + // problem caused it + CompilationResult result = abortException.compilationResult; + if ((result == null) && (unit != null)) + result = unit.compilationResult; // current unit being processed + // ? + if ((result == null) && (unitsToProcess != null) && (totalUnits > 0)) + result = unitsToProcess[totalUnits - 1].compilationResult; + // last unit in beginToCompile ? + if (result != null && !result.hasBeenAccepted) { + /* distant problem which could not be reported back there */ + if (abortException.problemId != 0) { + result.record(problemReporter.createProblem(result + .getFileName(), abortException.problemId, + abortException.problemArguments, + abortException.messageArguments, Error, // severity + 0, // source start + 0, // source end + 0, // line number + unit, result), unit); + } else { + /* + * distant internal exception which could not be reported back + * there + */ + if (abortException.exception != null) { + this.handleInternalException(abortException.exception, + null, result); + return; + } + } + /* hand back the compilation result */ + if (!result.hasBeenAccepted) { + requestor.acceptResult(result.tagAsAccepted()); + } + } else { + /* + * if (abortException.problemId != 0){ IProblem problem = + * problemReporter.createProblem( "???".toCharArray(), + * abortException.problemId, abortException.problemArguments, Error, // + * severity 0, // source start 0, // source end 0); // line number + * System.out.println(problem.getMessage()); } + */ + abortException.printStackTrace(); + } + } + + /** + * Process a compilation unit already parsed and build. + */ + public void process(CompilationUnitDeclaration unit, int i) { + getMethodBodies(unit, i); + // fault in fields & methods + if (unit.scope != null) + unit.scope.faultInTypes(); + // verify inherited methods + // if (unit.scope != null) + // unit.scope.verifyMethods(lookupEnvironment.methodVerifier()); + // type checking + unit.resolve(); + // flow analysis + unit.analyseCode(); + // code generation + // unit.generateCode(); + // reference info + // if (options.produceReferenceInfo && unit.scope != null) + // unit.scope.storeDependencyInfo(); + // refresh the total number of units known at this stage + unit.compilationResult.totalUnitsKnown = totalUnits; + } + + public void reset() { + lookupEnvironment.reset(); + parser.scanner.source = null; + unitsToProcess = null; + // if (DebugRequestor != null) DebugRequestor.reset(); + } + + /** + * Internal API used to resolve a given compilation unit. Can run a subset + * of the compilation process + */ + public CompilationUnitDeclaration resolve(CompilationUnitDeclaration unit, + ICompilationUnit sourceUnit, boolean verifyMethods, boolean analyzeCode) { - + try { if (unit == null) { // build and record parsed units parseThreshold = 0; // will request a full parse beginToCompile(new ICompilationUnit[] { sourceUnit }); - // process all units (some more could be injected in the loop by the lookup environment) + // process all units (some more could be injected in the loop by + // the lookup environment) unit = unitsToProcess[0]; } else { // initial type binding creation @@ -516,27 +570,85 @@ public class Compiler implements ITypeRequestor, ProblemSeverities { lookupEnvironment.completeTypeBindings(); } // TODO : jsurfer check this -// this.parser.getMethodBodies(unit); + // this.parser.getMethodBodies(unit); getMethodBodies(unit, 0); - + if (unit.scope != null) { // fault in fields & methods unit.scope.faultInTypes(); if (unit.scope != null && verifyMethods) { // http://dev.eclipse.org/bugs/show_bug.cgi?id=23117 // verify inherited methods - unit.scope.verifyMethods(lookupEnvironment.methodVerifier()); + unit.scope + .verifyMethods(lookupEnvironment.methodVerifier()); } // type checking - unit.resolve(); + unit.resolve(); + + // flow analysis + // if (analyzeCode) unit.analyseCode(); + // code generation + // if (generateCode) unit.generateCode(); + } + if (unitsToProcess != null) + unitsToProcess[0] = null; // release reference to processed + // unit declaration + requestor.acceptResult(unit.compilationResult.tagAsAccepted()); + return unit; + } catch (AbortCompilation e) { + this.handleInternalException(e, unit); + return unit == null ? unitsToProcess[0] : unit; + } catch (Error e) { + this.handleInternalException(e, unit, null); + throw e; // rethrow + } catch (RuntimeException e) { + this.handleInternalException(e, unit, null); + throw e; // rethrow + } finally { + // No reset is performed there anymore since, + // within the CodeAssist (or related tools), + // the compiler may be called *after* a call + // to this resolve(...) method. And such a call + // needs to have a compiler with a non-empty + // environment. + // this.reset(); + } + } + + /** + * Internal API used to resolve a given compilation unit. Can run a subset + * of the compilation process + */ + public CompilationUnitDeclaration resolve(ICompilationUnit sourceUnit, + boolean verifyMethods, boolean analyzeCode) { + // boolean generateCode) { + CompilationUnitDeclaration unit = null; + try { + // build and record parsed units + parseThreshold = 0; // will request a full parse + beginToCompile(new ICompilationUnit[] { sourceUnit }); + // process all units (some more could be injected in the loop by the + // lookup environment) + unit = unitsToProcess[0]; + getMethodBodies(unit, 0); + if (unit.scope != null) { + // // fault in fields & methods + // unit.scope.faultInTypes(); + // if (unit.scope != null && verifyMethods) { + // // http://dev.eclipse.org/bugs/show_bug.cgi?id=23117 + // // verify inherited methods + // unit.scope.verifyMethods(lookupEnvironment.methodVerifier()); + // } + // // type checking + // unit.resolve(); // flow analysis -// if (analyzeCode) unit.analyseCode(); - + // if (analyzeCode) unit.analyseCode(); // code generation -// if (generateCode) unit.generateCode(); + // if (generateCode) unit.generateCode(); } - if (unitsToProcess != null) unitsToProcess[0] = null; // release reference to processed unit declaration + unitsToProcess[0] = null; // release reference to processed unit + // declaration requestor.acceptResult(unit.compilationResult.tagAsAccepted()); return unit; } catch (AbortCompilation e) { @@ -558,59 +670,5 @@ public class Compiler implements ITypeRequestor, ProblemSeverities { // this.reset(); } } - /** - * Internal API used to resolve a given compilation unit. Can run a subset of - * the compilation process - */ - public CompilationUnitDeclaration resolve(ICompilationUnit sourceUnit, - boolean verifyMethods, boolean analyzeCode) { - // boolean generateCode) { - CompilationUnitDeclaration unit = null; - try { - // build and record parsed units - parseThreshold = 0; // will request a full parse - beginToCompile(new ICompilationUnit[]{sourceUnit}); - // process all units (some more could be injected in the loop by the - // lookup environment) - unit = unitsToProcess[0]; - getMethodBodies(unit, 0); - if (unit.scope != null) { - // // fault in fields & methods - // unit.scope.faultInTypes(); - // if (unit.scope != null && verifyMethods) { - // // http://dev.eclipse.org/bugs/show_bug.cgi?id=23117 - // // verify inherited methods - // unit.scope.verifyMethods(lookupEnvironment.methodVerifier()); - // } - // // type checking - // unit.resolve(); - // flow analysis - // if (analyzeCode) unit.analyseCode(); - // code generation - // if (generateCode) unit.generateCode(); - } - unitsToProcess[0] = null; // release reference to processed unit - // declaration - requestor.acceptResult(unit.compilationResult.tagAsAccepted()); - return unit; - } catch (AbortCompilation e) { - this.handleInternalException(e, unit); - return unit == null ? unitsToProcess[0] : unit; - } catch (Error e) { - this.handleInternalException(e, unit, null); - throw e; // rethrow - } catch (RuntimeException e) { - this.handleInternalException(e, unit, null); - throw e; // rethrow - } finally { - // No reset is performed there anymore since, - // within the CodeAssist (or related tools), - // the compiler may be called *after* a call - // to this resolve(...) method. And such a call - // needs to have a compiler with a non-empty - // environment. - // this.reset(); - } - } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ConfigurableOption.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ConfigurableOption.java index 624ed03..e9b77f2 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ConfigurableOption.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ConfigurableOption.java @@ -25,206 +25,234 @@ import java.util.StringTokenizer; public class ConfigurableOption { private String componentName; + private String optionName; + private int id; private String category; + private String name; + private String description; + private int currentValueIndex; + private int defaultValueIndex; + private String[] possibleValues; - // special value for indicating that + // special value for indicating that // the is the actual value - public final static String[] NoDiscreteValue = {}; -/** - * INTERNAL USE ONLY - * - * Initialize an instance of this class according to a specific locale - * - * @param loc java.util.Locale - */ -public ConfigurableOption( - String componentName, - String optionName, - Locale loc, - int currentValueIndex) { - - this.componentName = componentName; - this.optionName = optionName; - this.currentValueIndex = currentValueIndex; - - ResourceBundle resource = null; - try { - String location = componentName.substring(0, componentName.lastIndexOf('.')); - resource = ResourceBundle.getBundle(location + ".Options", loc); //$NON-NLS-1$ - } catch (MissingResourceException e) { - category = "Missing ressources entries for" + componentName + " options"; //$NON-NLS-1$ //$NON-NLS-2$ - name = "Missing ressources entries for"+ componentName + " options"; //$NON-NLS-1$ //$NON-NLS-2$ - description = "Missing ressources entries for" + componentName + " options"; //$NON-NLS-1$ //$NON-NLS-2$ - possibleValues = new String[0]; - id = -1; + public final static String[] NoDiscreteValue = {}; + + /** + * INTERNAL USE ONLY + * + * Initialize an instance of this class according to a specific locale + * + * @param loc + * java.util.Locale + */ + public ConfigurableOption(String componentName, String optionName, + Locale loc, int currentValueIndex) { + + this.componentName = componentName; + this.optionName = optionName; + this.currentValueIndex = currentValueIndex; + + ResourceBundle resource = null; + try { + String location = componentName.substring(0, componentName + .lastIndexOf('.')); + resource = ResourceBundle.getBundle(location + ".Options", loc); //$NON-NLS-1$ + } catch (MissingResourceException e) { + category = "Missing ressources entries for" + componentName + " options"; //$NON-NLS-1$ //$NON-NLS-2$ + name = "Missing ressources entries for" + componentName + " options"; //$NON-NLS-1$ //$NON-NLS-2$ + description = "Missing ressources entries for" + componentName + " options"; //$NON-NLS-1$ //$NON-NLS-2$ + possibleValues = new String[0]; + id = -1; + } + if (resource == null) + return; + try { + id = Integer.parseInt(resource.getString(optionName + ".number")); //$NON-NLS-1$ + } catch (MissingResourceException e) { + id = -1; + } catch (NumberFormatException e) { + id = -1; + } + try { + category = resource.getString(optionName + ".category"); //$NON-NLS-1$ + } catch (MissingResourceException e) { + category = "Missing ressources entries for" + componentName + " options"; //$NON-NLS-1$ //$NON-NLS-2$ + } + try { + name = resource.getString(optionName + ".name"); //$NON-NLS-1$ + } catch (MissingResourceException e) { + name = "Missing ressources entries for" + componentName + " options"; //$NON-NLS-1$ //$NON-NLS-2$ + } + try { + StringTokenizer tokenizer = new StringTokenizer(resource + .getString(optionName + ".possibleValues"), "|"); //$NON-NLS-1$ //$NON-NLS-2$ + int numberOfValues = Integer.parseInt(tokenizer.nextToken()); + if (numberOfValues == -1) { + possibleValues = NoDiscreteValue; + } else { + possibleValues = new String[numberOfValues]; + int index = 0; + while (tokenizer.hasMoreTokens()) { + possibleValues[index] = tokenizer.nextToken(); + index++; + } + } + } catch (MissingResourceException e) { + possibleValues = new String[0]; + } catch (NoSuchElementException e) { + possibleValues = new String[0]; + } catch (NumberFormatException e) { + possibleValues = new String[0]; + } + try { + description = resource.getString(optionName + ".description"); //$NON-NLS-1$ + } catch (MissingResourceException e) { + description = "Missing ressources entries for" + componentName + " options"; //$NON-NLS-1$ //$NON-NLS-2$ + } } - if (resource == null) return; - try { - id = Integer.parseInt(resource.getString(optionName + ".number")); //$NON-NLS-1$ - } catch (MissingResourceException e) { - id = -1; - } catch (NumberFormatException e) { - id = -1; + + /** + * Return a String that represents the localized category of the receiver. + * + * @return java.lang.String + */ + public String getCategory() { + return category; } - try { - category = resource.getString(optionName + ".category"); //$NON-NLS-1$ - } catch (MissingResourceException e) { - category = "Missing ressources entries for" + componentName + " options"; //$NON-NLS-1$ //$NON-NLS-2$ + + /** + * Return a String that identifies the component owner (typically the + * qualified type name of the class which it corresponds to). + * + * e.g. "org.phpeclipse.phpdt.internal.compiler.api.Compiler" + * + * @return java.lang.String + */ + public String getComponentName() { + return componentName; } - try { - name = resource.getString(optionName + ".name"); //$NON-NLS-1$ - } catch (MissingResourceException e) { - name = "Missing ressources entries for"+ componentName + " options"; //$NON-NLS-1$ //$NON-NLS-2$ + + /** + * Answer the index (in possibleValues array) of the current setting for + * this particular option. + * + * In case the set of possibleValues is NoDiscreteValue, then this index is + * the actual value (e.g. max line lenght set to 80). + * + * @return int + */ + public int getCurrentValueIndex() { + return currentValueIndex; } - try { - StringTokenizer tokenizer = new StringTokenizer(resource.getString(optionName + ".possibleValues"), "|"); //$NON-NLS-1$ //$NON-NLS-2$ - int numberOfValues = Integer.parseInt(tokenizer.nextToken()); - if(numberOfValues == -1){ - possibleValues = NoDiscreteValue; - } else { - possibleValues = new String[numberOfValues]; - int index = 0; - while (tokenizer.hasMoreTokens()) { - possibleValues[index] = tokenizer.nextToken(); - index++; - } - } - } catch (MissingResourceException e) { - possibleValues = new String[0]; - } catch (NoSuchElementException e) { - possibleValues = new String[0]; - } catch (NumberFormatException e) { - possibleValues = new String[0]; + + /** + * Answer the index (in possibleValues array) of the default setting for + * this particular option. + * + * In case the set of possibleValues is NoDiscreteValue, then this index is + * the actual value (e.g. max line lenght set to 80). + * + * @return int + */ + public int getDefaultValueIndex() { + return defaultValueIndex; } - try { - description = resource.getString(optionName + ".description"); //$NON-NLS-1$ - } catch (MissingResourceException e) { - description = "Missing ressources entries for"+ componentName + " options"; //$NON-NLS-1$ //$NON-NLS-2$ + + /** + * Return an String that represents the localized description of the + * receiver. + * + * @return java.lang.String + */ + public String getDescription() { + return description; } -} -/** - * Return a String that represents the localized category of the receiver. - * @return java.lang.String - */ -public String getCategory() { - return category; -} -/** - * Return a String that identifies the component owner (typically the qualified - * type name of the class which it corresponds to). - * - * e.g. "org.phpeclipse.phpdt.internal.compiler.api.Compiler" - * - * @return java.lang.String - */ -public String getComponentName() { - return componentName; -} -/** - * Answer the index (in possibleValues array) of the current setting for this - * particular option. - * - * In case the set of possibleValues is NoDiscreteValue, then this index is the - * actual value (e.g. max line lenght set to 80). - * - * @return int - */ -public int getCurrentValueIndex() { - return currentValueIndex; -} -/** - * Answer the index (in possibleValues array) of the default setting for this - * particular option. - * - * In case the set of possibleValues is NoDiscreteValue, then this index is the - * actual value (e.g. max line lenght set to 80). - * - * @return int - */ -public int getDefaultValueIndex() { - return defaultValueIndex; -} -/** - * Return an String that represents the localized description of the receiver. - * - * @return java.lang.String - */ -public String getDescription() { - return description; -} -/** - * Internal ID which allows the configurable component to identify this particular option. - * - * @return int - */ -public int getID() { - return id; -} -/** - * Return a String that represents the localized name of the receiver. - * @return java.lang.String - */ -public String getName() { - return name; -} -/** - * Return an array of String that represents the localized possible values of the receiver. - * @return java.lang.String[] - */ -public String[] getPossibleValues() { - return possibleValues; -} -/** - * Change the index (in possibleValues array) of the current setting for this - * particular option. - * - * In case the set of possibleValues is NoDiscreteValue, then this index is the - * actual value (e.g. max line lenght set to 80). - * - * @return int - */ -public void setValueIndex(int newIndex) { - currentValueIndex = newIndex; -} -public String toString() { - StringBuffer buffer = new StringBuffer(); - buffer.append("Configurable option for "); //$NON-NLS-1$ - buffer.append(this.componentName).append("\n"); //$NON-NLS-1$ - buffer.append("- category: ").append(this.category).append("\n"); //$NON-NLS-1$ //$NON-NLS-2$ - buffer.append("- name: ").append(this.name).append("\n"); //$NON-NLS-1$ //$NON-NLS-2$ - /* display current value */ - buffer.append("- current value: "); //$NON-NLS-1$ - if (possibleValues == NoDiscreteValue){ - buffer.append(this.currentValueIndex); - } else { - buffer.append(this.possibleValues[this.currentValueIndex]); + + /** + * Internal ID which allows the configurable component to identify this + * particular option. + * + * @return int + */ + public int getID() { + return id; + } + + /** + * Return a String that represents the localized name of the receiver. + * + * @return java.lang.String + */ + public String getName() { + return name; + } + + /** + * Return an array of String that represents the localized possible values + * of the receiver. + * + * @return java.lang.String[] + */ + public String[] getPossibleValues() { + return possibleValues; } - buffer.append("\n"); //$NON-NLS-1$ - - /* display possible values */ - if (possibleValues != NoDiscreteValue){ - buffer.append("- possible values: ["); //$NON-NLS-1$ - for (int i = 0, max = possibleValues.length; i < max; i++) { - if (i != 0) - buffer.append(", "); //$NON-NLS-1$ - buffer.append(possibleValues[i]); + + /** + * Change the index (in possibleValues array) of the current setting for + * this particular option. + * + * In case the set of possibleValues is NoDiscreteValue, then this index is + * the actual value (e.g. max line lenght set to 80). + * + * @return int + */ + public void setValueIndex(int newIndex) { + currentValueIndex = newIndex; + } + + public String toString() { + StringBuffer buffer = new StringBuffer(); + buffer.append("Configurable option for "); //$NON-NLS-1$ + buffer.append(this.componentName).append("\n"); //$NON-NLS-1$ + buffer.append("- category: ").append(this.category).append("\n"); //$NON-NLS-1$ //$NON-NLS-2$ + buffer.append("- name: ").append(this.name).append("\n"); //$NON-NLS-1$ //$NON-NLS-2$ + /* display current value */ + buffer.append("- current value: "); //$NON-NLS-1$ + if (possibleValues == NoDiscreteValue) { + buffer.append(this.currentValueIndex); + } else { + buffer.append(this.possibleValues[this.currentValueIndex]); } - buffer.append("]\n"); //$NON-NLS-1$ - buffer.append("- curr. val. index: ").append(currentValueIndex).append("\n"); //$NON-NLS-1$ //$NON-NLS-2$ + buffer.append("\n"); //$NON-NLS-1$ + + /* display possible values */ + if (possibleValues != NoDiscreteValue) { + buffer.append("- possible values: ["); //$NON-NLS-1$ + for (int i = 0, max = possibleValues.length; i < max; i++) { + if (i != 0) + buffer.append(", "); //$NON-NLS-1$ + buffer.append(possibleValues[i]); + } + buffer.append("]\n"); //$NON-NLS-1$ + buffer + .append("- curr. val. index: ").append(currentValueIndex).append("\n"); //$NON-NLS-1$ //$NON-NLS-2$ + } + buffer.append("- description: ").append(description).append("\n"); //$NON-NLS-1$ //$NON-NLS-2$ + return buffer.toString(); } - buffer.append("- description: ").append(description).append("\n"); //$NON-NLS-1$ //$NON-NLS-2$ - return buffer.toString(); -} + /** * Gets the optionName. + * * @return Returns a String */ public String getOptionName() { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/DefaultErrorHandlingPolicies.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/DefaultErrorHandlingPolicies.java index 19152b4..034dcec 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/DefaultErrorHandlingPolicies.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/DefaultErrorHandlingPolicies.java @@ -11,65 +11,70 @@ package net.sourceforge.phpdt.internal.compiler; public class DefaultErrorHandlingPolicies { - -/* - * Accumulate all problems, then exit without proceeding. - * - * Typically, the #proceedWithProblems(Problem[]) should - * show the problems. - * - */ -public static IErrorHandlingPolicy exitAfterAllProblems() { - return new IErrorHandlingPolicy() { - public boolean stopOnFirstError() { - return false; - } - public boolean proceedOnErrors(){ - return false; - } - }; -} -/* - * Exit without proceeding on the first problem wich appears - * to be an error. - * - */ -public static IErrorHandlingPolicy exitOnFirstError() { - return new IErrorHandlingPolicy() { - public boolean stopOnFirstError() { - return true; - } - public boolean proceedOnErrors(){ - return false; - } - }; -} -/* - * Proceed on the first error met. - * - */ -public static IErrorHandlingPolicy proceedOnFirstError() { - return new IErrorHandlingPolicy() { - public boolean stopOnFirstError() { - return true; - } - public boolean proceedOnErrors(){ - return true; - } - }; -} -/* - * Accumulate all problems, then proceed with them. - * - */ -public static IErrorHandlingPolicy proceedWithAllProblems() { - return new IErrorHandlingPolicy() { - public boolean stopOnFirstError() { - return false; - } - public boolean proceedOnErrors(){ - return true; - } - }; -} + + /* + * Accumulate all problems, then exit without proceeding. + * + * Typically, the #proceedWithProblems(Problem[]) should show the problems. + * + */ + public static IErrorHandlingPolicy exitAfterAllProblems() { + return new IErrorHandlingPolicy() { + public boolean stopOnFirstError() { + return false; + } + + public boolean proceedOnErrors() { + return false; + } + }; + } + + /* + * Exit without proceeding on the first problem wich appears to be an error. + * + */ + public static IErrorHandlingPolicy exitOnFirstError() { + return new IErrorHandlingPolicy() { + public boolean stopOnFirstError() { + return true; + } + + public boolean proceedOnErrors() { + return false; + } + }; + } + + /* + * Proceed on the first error met. + * + */ + public static IErrorHandlingPolicy proceedOnFirstError() { + return new IErrorHandlingPolicy() { + public boolean stopOnFirstError() { + return true; + } + + public boolean proceedOnErrors() { + return true; + } + }; + } + + /* + * Accumulate all problems, then proceed with them. + * + */ + public static IErrorHandlingPolicy proceedWithAllProblems() { + return new IErrorHandlingPolicy() { + public boolean stopOnFirstError() { + return false; + } + + public boolean proceedOnErrors() { + return true; + } + }; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/DocumentElementParser.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/DocumentElementParser.java index 80da79e..d68c7a2 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/DocumentElementParser.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/DocumentElementParser.java @@ -16,1287 +16,1340 @@ import net.sourceforge.phpdt.internal.compiler.problem.AbortCompilation; import net.sourceforge.phpdt.internal.compiler.problem.ProblemReporter; /* - * A document element parser extracts structural information from a piece of source, providing detailed source positions info. + * A document element parser extracts structural information from a piece of + * source, providing detailed source positions info. * * also see @IDocumentElementRequestor * - * The structural investigation includes: - the package statement - import statements - top-level types: package member, member - * types (member types of member types...) - fields - methods + * The structural investigation includes: - the package statement - import + * statements - top-level types: package member, member types (member types of + * member types...) - fields - methods * * Any (parsing) problem encountered is also provided. */ public class DocumentElementParser extends UnitParser { - IDocumentElementRequestor requestor; + IDocumentElementRequestor requestor; - private int localIntPtr; + private int localIntPtr; - private int lastFieldEndPosition; + private int lastFieldEndPosition; - private int lastFieldBodyEndPosition; + private int lastFieldBodyEndPosition; - private int typeStartPosition; + private int typeStartPosition; - private long selectorSourcePositions; + private long selectorSourcePositions; - private int typeDims; + private int typeDims; - private int extendsDim; + private int extendsDim; - private int declarationSourceStart; + private int declarationSourceStart; - /* int[] stack for storing javadoc positions */ - int[][] intArrayStack; + /* int[] stack for storing javadoc positions */ + int[][] intArrayStack; - int intArrayPtr; + int intArrayPtr; - // CompilerOptions options; + // CompilerOptions options; - public DocumentElementParser(final IDocumentElementRequestor requestor, IProblemFactory problemFactory, - CompilerOptions options) { - super(new ProblemReporter(DefaultErrorHandlingPolicies.exitAfterAllProblems(), options, problemFactory) { - public void record(IProblem problem, CompilationResult unitResult) { - requestor.acceptProblem(problem); - } - }); - // false, - // options.sourceLevel >= CompilerOptions.JDK1_4); - this.requestor = requestor; - intArrayStack = new int[30][]; - this.options = options; - } + public DocumentElementParser(final IDocumentElementRequestor requestor, + IProblemFactory problemFactory, CompilerOptions options) { + super(new ProblemReporter(DefaultErrorHandlingPolicies + .exitAfterAllProblems(), options, problemFactory) { + public void record(IProblem problem, CompilationResult unitResult) { + requestor.acceptProblem(problem); + } + }); + // false, + // options.sourceLevel >= CompilerOptions.JDK1_4); + this.requestor = requestor; + intArrayStack = new int[30][]; + this.options = options; + } - /** - * - * INTERNAL USE-ONLY - */ - //protected void adjustInterfaceModifiers() { - // intStack[intPtr - 2] |= AccInterface; - //} - /* - * Will clear the comment stack when looking for a potential JavaDoc which might contain @deprecated. - * - * Additionally, before investigating for @deprecated, retrieve the positions of the JavaDoc comments so as to notify requestor - * with them. - */ - //public void checkAnnotation() { - // - // /* persisting javadoc positions */ - // pushOnIntArrayStack(this.getJavaDocPositions()); - // boolean deprecated = false; - // int lastAnnotationIndex = -1; - // int commentPtr = scanner.commentPtr; - // - // //since jdk1.2 look only in the last java doc comment... - // nextComment : for (lastAnnotationIndex = scanner.commentPtr; lastAnnotationIndex >= 0; lastAnnotationIndex--){ - // //look for @deprecated into the first javadoc comment preceeding the declaration - // int commentSourceStart = scanner.commentStarts[lastAnnotationIndex]; - // // javadoc only (non javadoc comment have negative end positions.) - // if (modifiersSourceStart != -1 && modifiersSourceStart < commentSourceStart) { - // continue nextComment; - // } - // if (scanner.commentStops[lastAnnotationIndex] < 0) { - // continue nextComment; - // } - // int commentSourceEnd = scanner.commentStops[lastAnnotationIndex] - 1; //stop is one over - // char[] comment = scanner.source; - // - // deprecated = - // checkDeprecation( - // commentSourceStart, - // commentSourceEnd, - // comment); - // break nextComment; - // } - // if (deprecated) { - // checkAndSetModifiers(AccDeprecated); - // } - // // modify the modifier source start to point at the first comment - // if (commentPtr >= 0) { - // declarationSourceStart = scanner.commentStarts[0]; - // } - //} - /** - * - * INTERNAL USE-ONLY - */ - //protected void consumeClassBodyDeclaration() { - // // ClassBodyDeclaration ::= Diet Block - // //push an Initializer - // //optimize the push/pop - // - // super.consumeClassBodyDeclaration(); - // Initializer initializer = (Initializer) astStack[astPtr]; - // requestor.acceptInitializer( - // initializer.declarationSourceStart, - // initializer.declarationSourceEnd, - // intArrayStack[intArrayPtr--], - // 0, - // modifiersSourceStart, - // initializer.block.sourceStart, - // initializer.block.sourceEnd); - //} - ///** - // * - // * INTERNAL USE-ONLY - // */ - //protected void consumeClassDeclaration() { - // super.consumeClassDeclaration(); - // // we know that we have a TypeDeclaration on the top of the astStack - // if (isLocalDeclaration()) { - // // we ignore the local variable declarations - // return; - // } - // requestor.exitClass(endStatementPosition, // '}' is the end of the body - // ((TypeDeclaration) astStack[astPtr]).declarationSourceEnd); - //} - ///** - // * - // * INTERNAL USE-ONLY - // */ - //protected void consumeClassHeader() { - // //ClassHeader ::= $empty - // super.consumeClassHeader(); - // if (isLocalDeclaration()) { - // // we ignore the local variable declarations - // intArrayPtr--; - // return; - // } - // TypeDeclaration typeDecl = (TypeDeclaration) astStack[astPtr]; - // TypeReference[] superInterfaces = typeDecl.superInterfaces; - // char[][] interfaceNames = null; - // int[] interfaceNameStarts = null; - // int[] interfaceNameEnds = null; - // if (superInterfaces != null) { - // int superInterfacesLength = superInterfaces.length; - // interfaceNames = new char[superInterfacesLength][]; - // interfaceNameStarts = new int[superInterfacesLength]; - // interfaceNameEnds = new int[superInterfacesLength]; - // for (int i = 0; i < superInterfacesLength; i++) { - // TypeReference superInterface = superInterfaces[i]; - // interfaceNames[i] = CharOperation.concatWith(superInterface.getTypeName(), '.'); - // interfaceNameStarts[i] = superInterface.sourceStart; - // interfaceNameEnds[i] = superInterface.sourceEnd; - // } - // } - // // flush the comments related to the class header - // scanner.commentPtr = -1; - // TypeReference superclass = typeDecl.superclass; - // if (superclass == null) { - // requestor.enterClass( - // typeDecl.declarationSourceStart, - // intArrayStack[intArrayPtr--], - // typeDecl.modifiers, - // typeDecl.modifiersSourceStart, - // typeStartPosition, - // typeDecl.name, - // typeDecl.sourceStart, - // typeDecl.sourceEnd, - // null, - // -1, - // -1, - // interfaceNames, - // interfaceNameStarts, - // interfaceNameEnds, - // scanner.currentPosition - 1); - // } else { - // requestor.enterClass( - // typeDecl.declarationSourceStart, - // intArrayStack[intArrayPtr--], - // typeDecl.modifiers, - // typeDecl.modifiersSourceStart, - // typeStartPosition, - // typeDecl.name, - // typeDecl.sourceStart, - // typeDecl.sourceEnd, - // CharOperation.concatWith(superclass.getTypeName(), '.'), - // superclass.sourceStart, - // superclass.sourceEnd, - // interfaceNames, - // interfaceNameStarts, - // interfaceNameEnds, - // scanner.currentPosition - 1); - // - // } - //} - //protected void consumeClassHeaderName() { - // // ClassHeaderName ::= Modifiersopt 'class' 'Identifier' - // TypeDeclaration typeDecl; - // if (nestedMethod[nestedType] == 0) { - // if (nestedType != 0) { - // typeDecl = new MemberTypeDeclaration(this.compilationUnit.compilationResult); - // } else { - // typeDecl = new TypeDeclaration(this.compilationUnit.compilationResult); - // } - // } else { - // // Record that the block has a declaration for local types - // typeDecl = new LocalTypeDeclaration(this.compilationUnit.compilationResult); - // markEnclosingMemberWithLocalType(); - // blockReal(); - // } - // - // //highlight the name of the type - // long pos = identifierPositionStack[identifierPtr]; - // typeDecl.sourceEnd = (int) pos; - // typeDecl.sourceStart = (int) (pos >>> 32); - // typeDecl.name = identifierStack[identifierPtr--]; - // identifierLengthPtr--; - // - // //compute the declaration source too - // // 'class' and 'interface' push an int position - // typeStartPosition = typeDecl.declarationSourceStart = intStack[intPtr--]; - // intPtr--; - // int declarationSourceStart = intStack[intPtr--]; - // typeDecl.modifiersSourceStart = intStack[intPtr--]; - // typeDecl.modifiers = intStack[intPtr--]; - // if (typeDecl.declarationSourceStart > declarationSourceStart) { - // typeDecl.declarationSourceStart = declarationSourceStart; - // } - // typeDecl.bodyStart = typeDecl.sourceEnd + 1; - // pushOnAstStack(typeDecl); - //} - ///** - // * - // * INTERNAL USE-ONLY - // */ - //protected void consumeCompilationUnit() { - // // CompilationUnit ::= EnterCompilationUnit PackageDeclarationopt ImportDeclarationsopt - // requestor.exitCompilationUnit(scanner.source.length - 1); - //} - /** - * - * INTERNAL USE-ONLY - */ - //protected void consumeConstructorDeclaration() { - // // ConstructorDeclaration ::= ConstructorHeader ConstructorBody - // super.consumeConstructorDeclaration(); - // if (isLocalDeclaration()) { - // // we ignore the local variable declarations - // return; - // } - // ConstructorDeclaration cd = (ConstructorDeclaration) astStack[astPtr]; - // requestor.exitConstructor(endStatementPosition, cd.declarationSourceEnd); - //} - ///** - // * - // * INTERNAL USE-ONLY - // */ - //protected void consumeConstructorHeader() { - // // ConstructorHeader ::= ConstructorHeaderName MethodHeaderParameters MethodHeaderThrowsClauseopt - // super.consumeConstructorHeader(); - // if (isLocalDeclaration()) { - // // we ignore the local variable declarations - // intArrayPtr--; - // return; - // } - // ConstructorDeclaration cd = (ConstructorDeclaration) astStack[astPtr]; - // Argument[] arguments = cd.arguments; - // char[][] argumentTypes = null; - // char[][] argumentNames = null; - // int[] argumentTypeStarts = null; - // int[] argumentTypeEnds = null; - // int[] argumentNameStarts = null; - // int[] argumentNameEnds = null; - // if (arguments != null) { - // int argumentLength = arguments.length; - // argumentTypes = new char[argumentLength][]; - // argumentNames = new char[argumentLength][]; - // argumentNameStarts = new int[argumentLength]; - // argumentNameEnds = new int[argumentLength]; - // argumentTypeStarts = new int[argumentLength]; - // argumentTypeEnds = new int[argumentLength]; - // for (int i = 0; i < argumentLength; i++) { - // Argument argument = arguments[i]; - // TypeReference argumentType = argument.type; - // argumentTypes[i] = returnTypeName(argumentType); - // argumentNames[i] = argument.name; - // argumentNameStarts[i] = argument.sourceStart; - // argumentNameEnds[i] = argument.sourceEnd; - // argumentTypeStarts[i] = argumentType.sourceStart; - // argumentTypeEnds[i] = argumentType.sourceEnd; - // } - // } - // TypeReference[] thrownExceptions = cd.thrownExceptions; - // char[][] exceptionTypes = null; - // int[] exceptionTypeStarts = null; - // int[] exceptionTypeEnds = null; - // if (thrownExceptions != null) { - // int thrownExceptionLength = thrownExceptions.length; - // exceptionTypes = new char[thrownExceptionLength][]; - // exceptionTypeStarts = new int[thrownExceptionLength]; - // exceptionTypeEnds = new int[thrownExceptionLength]; - // for (int i = 0; i < thrownExceptionLength; i++) { - // TypeReference exception = thrownExceptions[i]; - // exceptionTypes[i] = CharOperation.concatWith(exception.getTypeName(), '.'); - // exceptionTypeStarts[i] = exception.sourceStart; - // exceptionTypeEnds[i] = exception.sourceEnd; - // } - // } - // requestor - // .enterConstructor( - // cd.declarationSourceStart, - // intArrayStack[intArrayPtr--], - // cd.modifiers, - // cd.modifiersSourceStart, - // cd.selector, - // cd.sourceStart, - // (int) (selectorSourcePositions & 0xFFFFFFFFL), - // // retrieve the source end of the name - // argumentTypes, - // argumentTypeStarts, - // argumentTypeEnds, - // argumentNames, - // argumentNameStarts, - // argumentNameEnds, - // rParenPos, - // // right parenthesis - // exceptionTypes, - // exceptionTypeStarts, - // exceptionTypeEnds, - // scanner.currentPosition - 1); - //} - //protected void consumeConstructorHeaderName() { - // // ConstructorHeaderName ::= Modifiersopt 'Identifier' '(' - // ConstructorDeclaration cd = new ConstructorDeclaration(this.compilationUnit.compilationResult); - // - // //name -- this is not really revelant but we do ..... - // cd.selector = identifierStack[identifierPtr]; - // selectorSourcePositions = identifierPositionStack[identifierPtr--]; - // identifierLengthPtr--; - // - // //modifiers - // cd.declarationSourceStart = intStack[intPtr--]; - // cd.modifiersSourceStart = intStack[intPtr--]; - // cd.modifiers = intStack[intPtr--]; - // - // //highlight starts at the selector starts - // cd.sourceStart = (int) (selectorSourcePositions >>> 32); - // pushOnAstStack(cd); - // - // cd.sourceEnd = lParenPos; - // cd.bodyStart = lParenPos + 1; - //} - //protected void consumeDefaultModifiers() { - // checkAnnotation(); // might update modifiers with AccDeprecated - // pushOnIntStack(modifiers); // modifiers - // pushOnIntStack(-1); - // pushOnIntStack( - // declarationSourceStart >= 0 ? declarationSourceStart : scanner.startPosition); - // resetModifiers(); - //} - //protected void consumeDiet() { - // // Diet ::= $empty - // super.consumeDiet(); - // /* persisting javadoc positions - // * Will be consume in consumeClassBodyDeclaration - // */ - // pushOnIntArrayStack(this.getJavaDocPositions()); - //} - ///** - // * - // * INTERNAL USE-ONLY - // */ - //protected void consumeEnterCompilationUnit() { - // // EnterCompilationUnit ::= $empty - // requestor.enterCompilationUnit(); - //} - ///** - // * - // * INTERNAL USE-ONLY - // */ - //protected void consumeEnterVariable() { - // // EnterVariable ::= $empty - // boolean isLocalDeclaration = isLocalDeclaration(); - // if (!isLocalDeclaration && (variablesCounter[nestedType] != 0)) { - // requestor.exitField(lastFieldBodyEndPosition, lastFieldEndPosition); - // } - // char[] name = identifierStack[identifierPtr]; - // long namePosition = identifierPositionStack[identifierPtr--]; - // int extendedTypeDimension = intStack[intPtr--]; - // - // AbstractVariableDeclaration declaration; - // if (nestedMethod[nestedType] != 0) { - // // create the local variable declarations - // declaration = - // new LocalDeclaration(null, name, (int) (namePosition >>> 32), (int) namePosition); - // } else { - // // create the field declaration - // declaration = - // new FieldDeclaration(null, name, (int) (namePosition >>> 32), (int) namePosition); - // } - // identifierLengthPtr--; - // TypeReference type; - // int variableIndex = variablesCounter[nestedType]; - // int typeDim = 0; - // if (variableIndex == 0) { - // // first variable of the declaration (FieldDeclaration or LocalDeclaration) - // if (nestedMethod[nestedType] != 0) { - // // local declaration - // declaration.declarationSourceStart = intStack[intPtr--]; - // declaration.modifiersSourceStart = intStack[intPtr--]; - // declaration.modifiers = intStack[intPtr--]; - // type = getTypeReference(typeDim = intStack[intPtr--]); // type dimension - // pushOnAstStack(type); - // } else { - // // field declaration - // type = getTypeReference(typeDim = intStack[intPtr--]); // type dimension - // pushOnAstStack(type); - // declaration.declarationSourceStart = intStack[intPtr--]; - // declaration.modifiersSourceStart = intStack[intPtr--]; - // declaration.modifiers = intStack[intPtr--]; - // } - // } else { - // type = (TypeReference) astStack[astPtr - variableIndex]; - // typeDim = type.dimensions(); - // AbstractVariableDeclaration previousVariable = - // (AbstractVariableDeclaration) astStack[astPtr]; - // declaration.declarationSourceStart = previousVariable.declarationSourceStart; - // declaration.modifiers = previousVariable.modifiers; - // declaration.modifiersSourceStart = previousVariable.modifiersSourceStart; - // } - // - // localIntPtr = intPtr; - // - // if (extendedTypeDimension == 0) { - // declaration.type = type; - // } else { - // int dimension = typeDim + extendedTypeDimension; - // //on the identifierLengthStack there is the information about the type.... - // int baseType; - // if ((baseType = identifierLengthStack[identifierLengthPtr + 1]) < 0) { - // //it was a baseType - // declaration.type = TypeReference.baseTypeReference(-baseType, dimension); - // declaration.type.sourceStart = type.sourceStart; - // declaration.type.sourceEnd = type.sourceEnd; - // } else { - // declaration.type = this.copyDims(type, dimension); - // } - // } - // variablesCounter[nestedType]++; - // nestedMethod[nestedType]++; - // pushOnAstStack(declaration); - // - // int[] javadocPositions = intArrayStack[intArrayPtr]; - // if (!isLocalDeclaration) { - // requestor - // .enterField( - // declaration.declarationSourceStart, - // javadocPositions, - // declaration.modifiers, - // declaration.modifiersSourceStart, - // returnTypeName(declaration.type), - // type.sourceStart, - // type.sourceEnd, - // typeDims, - // name, - // (int) (namePosition >>> 32), - // (int) namePosition, - // extendedTypeDimension, - // extendedTypeDimension == 0 ? -1 : endPosition); - // } - //} - ///** - // * - // * INTERNAL USE-ONLY - // */ - //protected void consumeExitVariableWithInitialization() { - // // ExitVariableWithInitialization ::= $empty - // // the scanner is located after the comma or the semi-colon. - // // we want to include the comma or the semi-colon - // super.consumeExitVariableWithInitialization(); - // nestedMethod[nestedType]--; - // lastFieldEndPosition = scanner.currentPosition - 1; - // lastFieldBodyEndPosition = ((AbstractVariableDeclaration) astStack[astPtr]).initialization.sourceEnd; - //} - //protected void consumeExitVariableWithoutInitialization() { - // // ExitVariableWithoutInitialization ::= $empty - // // do nothing by default - // super.consumeExitVariableWithoutInitialization(); - // nestedMethod[nestedType]--; - // lastFieldEndPosition = scanner.currentPosition - 1; - // lastFieldBodyEndPosition = scanner.startPosition - 1; - //} - ///** - // * - // * INTERNAL USE-ONLY - // */ - //protected void consumeFieldDeclaration() { - // // See consumeLocalVariableDeclarationDefaultModifier() in case of change: duplicated code - // // FieldDeclaration ::= Modifiersopt Type VariableDeclarators ';' - // // the super.consumeFieldDeclaration will reinitialize the variableCounter[nestedType] - // int variableIndex = variablesCounter[nestedType]; - // super.consumeFieldDeclaration(); - // intArrayPtr--; - // if (isLocalDeclaration()) - // return; - // if (variableIndex != 0) { - // requestor.exitField(lastFieldBodyEndPosition, lastFieldEndPosition); - // } - //} - //protected void consumeFormalParameter() { - // // FormalParameter ::= Type VariableDeclaratorId ==> false - // // FormalParameter ::= Modifiers Type VariableDeclaratorId ==> true - // /* - // astStack : - // identifierStack : type identifier - // intStack : dim dim - // ==> - // astStack : Argument - // identifierStack : - // intStack : - // */ - // - // identifierLengthPtr--; - // char[] name = identifierStack[identifierPtr]; - // long namePositions = identifierPositionStack[identifierPtr--]; - // TypeReference type = getTypeReference(intStack[intPtr--] + intStack[intPtr--]); - // intPtr -= 3; - // Argument arg = - // new Argument( - // name, - // namePositions, - // type, - // intStack[intPtr + 1]); // modifiers - // pushOnAstStack(arg); - // intArrayPtr--; - //} - ///** - // * - // * INTERNAL USE-ONLY - // */ - //protected void consumeInterfaceDeclaration() { - // super.consumeInterfaceDeclaration(); - // // we know that we have a TypeDeclaration on the top of the astStack - // if (isLocalDeclaration()) { - // // we ignore the local variable declarations - // return; - // } - // requestor.exitInterface(endStatementPosition, // the '}' is the end of the body - // ((TypeDeclaration) astStack[astPtr]).declarationSourceEnd); - //} - ///** - // * - // * INTERNAL USE-ONLY - // */ - //protected void consumeInterfaceHeader() { - // //InterfaceHeader ::= $empty - // super.consumeInterfaceHeader(); - // if (isLocalDeclaration()) { - // // we ignore the local variable declarations - // intArrayPtr--; - // return; - // } - // TypeDeclaration typeDecl = (TypeDeclaration) astStack[astPtr]; - // TypeReference[] superInterfaces = typeDecl.superInterfaces; - // char[][] interfaceNames = null; - // int[] interfaceNameStarts = null; - // int[] interfacenameEnds = null; - // int superInterfacesLength = 0; - // if (superInterfaces != null) { - // superInterfacesLength = superInterfaces.length; - // interfaceNames = new char[superInterfacesLength][]; - // interfaceNameStarts = new int[superInterfacesLength]; - // interfacenameEnds = new int[superInterfacesLength]; - // } - // if (superInterfaces != null) { - // for (int i = 0; i < superInterfacesLength; i++) { - // TypeReference superInterface = superInterfaces[i]; - // interfaceNames[i] = CharOperation.concatWith(superInterface.getTypeName(), '.'); - // interfaceNameStarts[i] = superInterface.sourceStart; - // interfacenameEnds[i] = superInterface.sourceEnd; - // } - // } - // // flush the comments related to the interface header - // scanner.commentPtr = -1; - // requestor.enterInterface( - // typeDecl.declarationSourceStart, - // intArrayStack[intArrayPtr--], - // typeDecl.modifiers, - // typeDecl.modifiersSourceStart, - // typeStartPosition, - // typeDecl.name, - // typeDecl.sourceStart, - // typeDecl.sourceEnd, - // interfaceNames, - // interfaceNameStarts, - // interfacenameEnds, - // scanner.currentPosition - 1); - //} - //protected void consumeInterfaceHeaderName() { - // // InterfaceHeaderName ::= Modifiersopt 'interface' 'Identifier' - // TypeDeclaration typeDecl; - // if (nestedMethod[nestedType] == 0) { - // if (nestedType != 0) { - // typeDecl = new MemberTypeDeclaration(this.compilationUnit.compilationResult); - // } else { - // typeDecl = new TypeDeclaration(this.compilationUnit.compilationResult); - // } - // } else { - // // Record that the block has a declaration for local types - // typeDecl = new LocalTypeDeclaration(this.compilationUnit.compilationResult); - // markEnclosingMemberWithLocalType(); - // blockReal(); - // } - // - // //highlight the name of the type - // long pos = identifierPositionStack[identifierPtr]; - // typeDecl.sourceEnd = (int) pos; - // typeDecl.sourceStart = (int) (pos >>> 32); - // typeDecl.name = identifierStack[identifierPtr--]; - // identifierLengthPtr--; - // - // //compute the declaration source too - // // 'class' and 'interface' push an int position - // typeStartPosition = typeDecl.declarationSourceStart = intStack[intPtr--]; - // intPtr--; - // int declarationSourceStart = intStack[intPtr--]; - // typeDecl.modifiersSourceStart = intStack[intPtr--]; - // typeDecl.modifiers = intStack[intPtr--]; - // if (typeDecl.declarationSourceStart > declarationSourceStart) { - // typeDecl.declarationSourceStart = declarationSourceStart; - // } - // typeDecl.bodyStart = typeDecl.sourceEnd + 1; - // pushOnAstStack(typeDecl); - //} - ///** - // * - // * INTERNAL USE-ONLY - // */ - //protected void consumeLocalVariableDeclaration() { - // // See consumeLocalVariableDeclarationDefaultModifier() in case of change: duplicated code - // // FieldDeclaration ::= Modifiersopt Type VariableDeclarators ';' - // - // super.consumeLocalVariableDeclaration(); - // intArrayPtr--; - //} - ///** - // * - // * INTERNAL USE-ONLY - // */ - //protected void consumeMethodDeclaration(boolean isNotAbstract) { - // // MethodDeclaration ::= MethodHeader MethodBody - // // AbstractMethodDeclaration ::= MethodHeader ';' - // super.consumeMethodDeclaration(isNotAbstract); - // if (isLocalDeclaration()) { - // // we ignore the local variable declarations - // return; - // } - // MethodDeclaration md = (MethodDeclaration) astStack[astPtr]; - // requestor.exitMethod(endStatementPosition, md.declarationSourceEnd); - //} - ///** - // * - // * INTERNAL USE-ONLY - // */ - //protected void consumeMethodHeader() { - // // MethodHeader ::= MethodHeaderName MethodHeaderParameters MethodHeaderExtendedDims ThrowsClauseopt - // super.consumeMethodHeader(); - // if (isLocalDeclaration()) { - // // we ignore the local variable declarations - // intArrayPtr--; - // return; - // } - // MethodDeclaration md = (MethodDeclaration) astStack[astPtr]; - // - // TypeReference returnType = md.returnType; - // char[] returnTypeName = returnTypeName(returnType); - // Argument[] arguments = md.arguments; - // char[][] argumentTypes = null; - // char[][] argumentNames = null; - // int[] argumentTypeStarts = null; - // int[] argumentTypeEnds = null; - // int[] argumentNameStarts = null; - // int[] argumentNameEnds = null; - // if (arguments != null) { - // int argumentLength = arguments.length; - // argumentTypes = new char[argumentLength][]; - // argumentNames = new char[argumentLength][]; - // argumentNameStarts = new int[argumentLength]; - // argumentNameEnds = new int[argumentLength]; - // argumentTypeStarts = new int[argumentLength]; - // argumentTypeEnds = new int[argumentLength]; - // for (int i = 0; i < argumentLength; i++) { - // Argument argument = arguments[i]; - // TypeReference argumentType = argument.type; - // argumentTypes[i] = returnTypeName(argumentType); - // argumentNames[i] = argument.name; - // argumentNameStarts[i] = argument.sourceStart; - // argumentNameEnds[i] = argument.sourceEnd; - // argumentTypeStarts[i] = argumentType.sourceStart; - // argumentTypeEnds[i] = argumentType.sourceEnd; - // } - // } - // TypeReference[] thrownExceptions = md.thrownExceptions; - // char[][] exceptionTypes = null; - // int[] exceptionTypeStarts = null; - // int[] exceptionTypeEnds = null; - // if (thrownExceptions != null) { - // int thrownExceptionLength = thrownExceptions.length; - // exceptionTypeStarts = new int[thrownExceptionLength]; - // exceptionTypeEnds = new int[thrownExceptionLength]; - // exceptionTypes = new char[thrownExceptionLength][]; - // for (int i = 0; i < thrownExceptionLength; i++) { - // TypeReference exception = thrownExceptions[i]; - // exceptionTypes[i] = CharOperation.concatWith(exception.getTypeName(), '.'); - // exceptionTypeStarts[i] = exception.sourceStart; - // exceptionTypeEnds[i] = exception.sourceEnd; - // } - // } - // requestor - // .enterMethod( - // md.declarationSourceStart, - // intArrayStack[intArrayPtr--], - // md.modifiers, - // md.modifiersSourceStart, - // returnTypeName, - // returnType.sourceStart, - // returnType.sourceEnd, - // typeDims, - // md.selector, - // md.sourceStart, - // (int) (selectorSourcePositions & 0xFFFFFFFFL), - // argumentTypes, - // argumentTypeStarts, - // argumentTypeEnds, - // argumentNames, - // argumentNameStarts, - // argumentNameEnds, - // rParenPos, - // extendsDim, - // extendsDim == 0 ? -1 : endPosition, - // exceptionTypes, - // exceptionTypeStarts, - // exceptionTypeEnds, - // scanner.currentPosition - 1); - //} - //protected void consumeMethodHeaderExtendedDims() { - // // MethodHeaderExtendedDims ::= Dimsopt - // // now we update the returnType of the method - // MethodDeclaration md = (MethodDeclaration) astStack[astPtr]; - // int extendedDims = intStack[intPtr--]; - // extendsDim = extendedDims; - // if (extendedDims != 0) { - // TypeReference returnType = md.returnType; - // md.sourceEnd = endPosition; - // int dims = returnType.dimensions() + extendedDims; - // int baseType; - // if ((baseType = identifierLengthStack[identifierLengthPtr + 1]) < 0) { - // //it was a baseType - // int sourceStart = returnType.sourceStart; - // int sourceEnd = returnType.sourceEnd; - // returnType = TypeReference.baseTypeReference(-baseType, dims); - // returnType.sourceStart = sourceStart; - // returnType.sourceEnd = sourceEnd; - // md.returnType = returnType; - // } else { - // md.returnType = this.copyDims(md.returnType, dims); - // } - // if (currentToken == TokenNameLBRACE) { - // md.bodyStart = endPosition + 1; - // } - // } - //} - //protected void consumeMethodHeaderName() { - // // MethodHeaderName ::= Modifiersopt Type 'Identifier' '(' - // MethodDeclaration md = new MethodDeclaration(this.compilationUnit.compilationResult); - // - // //name - // md.selector = identifierStack[identifierPtr]; - // selectorSourcePositions = identifierPositionStack[identifierPtr--]; - // identifierLengthPtr--; - // //type - // md.returnType = getTypeReference(typeDims = intStack[intPtr--]); - // //modifiers - // md.declarationSourceStart = intStack[intPtr--]; - // md.modifiersSourceStart = intStack[intPtr--]; - // md.modifiers = intStack[intPtr--]; - // - // //highlight starts at selector start - // md.sourceStart = (int) (selectorSourcePositions >>> 32); - // pushOnAstStack(md); - // md.bodyStart = scanner.currentPosition-1; - //} - //protected void consumeModifiers() { - // checkAnnotation(); // might update modifiers with AccDeprecated - // pushOnIntStack(modifiers); // modifiers - // pushOnIntStack(modifiersSourceStart); - // pushOnIntStack( - // declarationSourceStart >= 0 ? declarationSourceStart : modifiersSourceStart); - // resetModifiers(); - //} - /** - * - * INTERNAL USE-ONLY - */ - //protected void consumePackageDeclarationName() { - // /* persisting javadoc positions */ - // pushOnIntArrayStack(this.getJavaDocPositions()); - // - // super.consumePackageDeclarationName(); - // ImportReference importReference = compilationUnit.currentPackage; - // - // requestor.acceptPackage( - // importReference.declarationSourceStart, - // importReference.declarationSourceEnd, - // intArrayStack[intArrayPtr--], - // CharOperation.concatWith(importReference.getImportName(), '.'), - // importReference.sourceStart); - //} - //protected void consumePushModifiers() { - // checkAnnotation(); // might update modifiers with AccDeprecated - // pushOnIntStack(modifiers); // modifiers - // if (modifiersSourceStart < 0) { - // pushOnIntStack(-1); - // pushOnIntStack( - // declarationSourceStart >= 0 ? declarationSourceStart : scanner.startPosition); - // } else { - // pushOnIntStack(modifiersSourceStart); - // pushOnIntStack( - // declarationSourceStart >= 0 ? declarationSourceStart : modifiersSourceStart); - // } - // resetModifiers(); - //} - ///** - // * - // * INTERNAL USE-ONLY - // */ - //protected void consumeSingleTypeImportDeclarationName() { - // // SingleTypeImportDeclarationName ::= 'import' Name - // - // /* persisting javadoc positions */ - // pushOnIntArrayStack(this.getJavaDocPositions()); - // - // super.consumeSingleTypeImportDeclarationName(); - // ImportReference importReference = (ImportReference) astStack[astPtr]; - // requestor.acceptImport( - // importReference.declarationSourceStart, - // importReference.declarationSourceEnd, - // intArrayStack[intArrayPtr--], - // CharOperation.concatWith(importReference.getImportName(), '.'), - // importReference.sourceStart, - // false); - //} - ///** - // * - // * INTERNAL USE-ONLY - // */ - //protected void consumeStaticInitializer() { - // // StaticInitializer ::= StaticOnly Block - // //push an Initializer - // //optimize the push/pop - // super.consumeStaticInitializer(); - // Initializer initializer = (Initializer) astStack[astPtr]; - // requestor.acceptInitializer( - // initializer.declarationSourceStart, - // initializer.declarationSourceEnd, - // intArrayStack[intArrayPtr--], - // AccStatic, - // intStack[intPtr--], - // initializer.block.sourceStart, - // initializer.declarationSourceEnd); - //} - //protected void consumeStaticOnly() { - // // StaticOnly ::= 'static' - // checkAnnotation(); // might update declaration source start - // pushOnIntStack(modifiersSourceStart); - // pushOnIntStack( - // declarationSourceStart >= 0 ? declarationSourceStart : modifiersSourceStart); - // jumpOverMethodBody(); - // nestedMethod[nestedType]++; - // resetModifiers(); - //} - ///** - // * - // * INTERNAL USE-ONLY - // */ - //protected void consumeTypeImportOnDemandDeclarationName() { - // // TypeImportOnDemandDeclarationName ::= 'import' Name '.' '*' - // - // /* persisting javadoc positions */ - // pushOnIntArrayStack(this.getJavaDocPositions()); - // - // super.consumeTypeImportOnDemandDeclarationName(); - // ImportReference importReference = (ImportReference) astStack[astPtr]; - // requestor.acceptImport( - // importReference.declarationSourceStart, - // importReference.declarationSourceEnd, - // intArrayStack[intArrayPtr--], - // CharOperation.concatWith(importReference.getImportName(), '.'), - // importReference.sourceStart, - // true); - //} - public CompilationUnitDeclaration endParse(int act) { - if (scanner.recordLineSeparator) { - requestor.acceptLineSeparatorPositions(scanner.getLineEnds()); - } - return super.endParse(act); - } + /** + * + * INTERNAL USE-ONLY + */ + // protected void adjustInterfaceModifiers() { + // intStack[intPtr - 2] |= AccInterface; + // } + /* + * Will clear the comment stack when looking for a potential JavaDoc which + * might contain @deprecated. + * + * Additionally, before investigating for @deprecated, retrieve the + * positions of the JavaDoc comments so as to notify requestor with them. + */ + // public void checkAnnotation() { + // + // /* persisting javadoc positions */ + // pushOnIntArrayStack(this.getJavaDocPositions()); + // boolean deprecated = false; + // int lastAnnotationIndex = -1; + // int commentPtr = scanner.commentPtr; + // + // //since jdk1.2 look only in the last java doc comment... + // nextComment : for (lastAnnotationIndex = scanner.commentPtr; + // lastAnnotationIndex >= 0; lastAnnotationIndex--){ + // //look for @deprecated into the first javadoc comment preceeding the + // declaration + // int commentSourceStart = scanner.commentStarts[lastAnnotationIndex]; + // // javadoc only (non javadoc comment have negative end positions.) + // if (modifiersSourceStart != -1 && modifiersSourceStart < + // commentSourceStart) { + // continue nextComment; + // } + // if (scanner.commentStops[lastAnnotationIndex] < 0) { + // continue nextComment; + // } + // int commentSourceEnd = scanner.commentStops[lastAnnotationIndex] - 1; + // //stop is one over + // char[] comment = scanner.source; + // + // deprecated = + // checkDeprecation( + // commentSourceStart, + // commentSourceEnd, + // comment); + // break nextComment; + // } + // if (deprecated) { + // checkAndSetModifiers(AccDeprecated); + // } + // // modify the modifier source start to point at the first comment + // if (commentPtr >= 0) { + // declarationSourceStart = scanner.commentStarts[0]; + // } + // } + /** + * + * INTERNAL USE-ONLY + */ + // protected void consumeClassBodyDeclaration() { + // // ClassBodyDeclaration ::= Diet Block + // //push an Initializer + // //optimize the push/pop + // + // super.consumeClassBodyDeclaration(); + // Initializer initializer = (Initializer) astStack[astPtr]; + // requestor.acceptInitializer( + // initializer.declarationSourceStart, + // initializer.declarationSourceEnd, + // intArrayStack[intArrayPtr--], + // 0, + // modifiersSourceStart, + // initializer.block.sourceStart, + // initializer.block.sourceEnd); + // } + // /** + // * + // * INTERNAL USE-ONLY + // */ + // protected void consumeClassDeclaration() { + // super.consumeClassDeclaration(); + // // we know that we have a TypeDeclaration on the top of the astStack + // if (isLocalDeclaration()) { + // // we ignore the local variable declarations + // return; + // } + // requestor.exitClass(endStatementPosition, // '}' is the end of the body + // ((TypeDeclaration) astStack[astPtr]).declarationSourceEnd); + // } + // /** + // * + // * INTERNAL USE-ONLY + // */ + // protected void consumeClassHeader() { + // //ClassHeader ::= $empty + // super.consumeClassHeader(); + // if (isLocalDeclaration()) { + // // we ignore the local variable declarations + // intArrayPtr--; + // return; + // } + // TypeDeclaration typeDecl = (TypeDeclaration) astStack[astPtr]; + // TypeReference[] superInterfaces = typeDecl.superInterfaces; + // char[][] interfaceNames = null; + // int[] interfaceNameStarts = null; + // int[] interfaceNameEnds = null; + // if (superInterfaces != null) { + // int superInterfacesLength = superInterfaces.length; + // interfaceNames = new char[superInterfacesLength][]; + // interfaceNameStarts = new int[superInterfacesLength]; + // interfaceNameEnds = new int[superInterfacesLength]; + // for (int i = 0; i < superInterfacesLength; i++) { + // TypeReference superInterface = superInterfaces[i]; + // interfaceNames[i] = + // CharOperation.concatWith(superInterface.getTypeName(), '.'); + // interfaceNameStarts[i] = superInterface.sourceStart; + // interfaceNameEnds[i] = superInterface.sourceEnd; + // } + // } + // // flush the comments related to the class header + // scanner.commentPtr = -1; + // TypeReference superclass = typeDecl.superclass; + // if (superclass == null) { + // requestor.enterClass( + // typeDecl.declarationSourceStart, + // intArrayStack[intArrayPtr--], + // typeDecl.modifiers, + // typeDecl.modifiersSourceStart, + // typeStartPosition, + // typeDecl.name, + // typeDecl.sourceStart, + // typeDecl.sourceEnd, + // null, + // -1, + // -1, + // interfaceNames, + // interfaceNameStarts, + // interfaceNameEnds, + // scanner.currentPosition - 1); + // } else { + // requestor.enterClass( + // typeDecl.declarationSourceStart, + // intArrayStack[intArrayPtr--], + // typeDecl.modifiers, + // typeDecl.modifiersSourceStart, + // typeStartPosition, + // typeDecl.name, + // typeDecl.sourceStart, + // typeDecl.sourceEnd, + // CharOperation.concatWith(superclass.getTypeName(), '.'), + // superclass.sourceStart, + // superclass.sourceEnd, + // interfaceNames, + // interfaceNameStarts, + // interfaceNameEnds, + // scanner.currentPosition - 1); + // + // } + // } + // protected void consumeClassHeaderName() { + // // ClassHeaderName ::= Modifiersopt 'class' 'Identifier' + // TypeDeclaration typeDecl; + // if (nestedMethod[nestedType] == 0) { + // if (nestedType != 0) { + // typeDecl = new + // MemberTypeDeclaration(this.compilationUnit.compilationResult); + // } else { + // typeDecl = new TypeDeclaration(this.compilationUnit.compilationResult); + // } + // } else { + // // Record that the block has a declaration for local types + // typeDecl = new + // LocalTypeDeclaration(this.compilationUnit.compilationResult); + // markEnclosingMemberWithLocalType(); + // blockReal(); + // } + // + // //highlight the name of the type + // long pos = identifierPositionStack[identifierPtr]; + // typeDecl.sourceEnd = (int) pos; + // typeDecl.sourceStart = (int) (pos >>> 32); + // typeDecl.name = identifierStack[identifierPtr--]; + // identifierLengthPtr--; + // + // //compute the declaration source too + // // 'class' and 'interface' push an int position + // typeStartPosition = typeDecl.declarationSourceStart = intStack[intPtr--]; + // intPtr--; + // int declarationSourceStart = intStack[intPtr--]; + // typeDecl.modifiersSourceStart = intStack[intPtr--]; + // typeDecl.modifiers = intStack[intPtr--]; + // if (typeDecl.declarationSourceStart > declarationSourceStart) { + // typeDecl.declarationSourceStart = declarationSourceStart; + // } + // typeDecl.bodyStart = typeDecl.sourceEnd + 1; + // pushOnAstStack(typeDecl); + // } + // /** + // * + // * INTERNAL USE-ONLY + // */ + // protected void consumeCompilationUnit() { + // // CompilationUnit ::= EnterCompilationUnit PackageDeclarationopt + // ImportDeclarationsopt + // requestor.exitCompilationUnit(scanner.source.length - 1); + // } + /** + * + * INTERNAL USE-ONLY + */ + // protected void consumeConstructorDeclaration() { + // // ConstructorDeclaration ::= ConstructorHeader ConstructorBody + // super.consumeConstructorDeclaration(); + // if (isLocalDeclaration()) { + // // we ignore the local variable declarations + // return; + // } + // ConstructorDeclaration cd = (ConstructorDeclaration) astStack[astPtr]; + // requestor.exitConstructor(endStatementPosition, cd.declarationSourceEnd); + // } + // /** + // * + // * INTERNAL USE-ONLY + // */ + // protected void consumeConstructorHeader() { + // // ConstructorHeader ::= ConstructorHeaderName MethodHeaderParameters + // MethodHeaderThrowsClauseopt + // super.consumeConstructorHeader(); + // if (isLocalDeclaration()) { + // // we ignore the local variable declarations + // intArrayPtr--; + // return; + // } + // ConstructorDeclaration cd = (ConstructorDeclaration) astStack[astPtr]; + // Argument[] arguments = cd.arguments; + // char[][] argumentTypes = null; + // char[][] argumentNames = null; + // int[] argumentTypeStarts = null; + // int[] argumentTypeEnds = null; + // int[] argumentNameStarts = null; + // int[] argumentNameEnds = null; + // if (arguments != null) { + // int argumentLength = arguments.length; + // argumentTypes = new char[argumentLength][]; + // argumentNames = new char[argumentLength][]; + // argumentNameStarts = new int[argumentLength]; + // argumentNameEnds = new int[argumentLength]; + // argumentTypeStarts = new int[argumentLength]; + // argumentTypeEnds = new int[argumentLength]; + // for (int i = 0; i < argumentLength; i++) { + // Argument argument = arguments[i]; + // TypeReference argumentType = argument.type; + // argumentTypes[i] = returnTypeName(argumentType); + // argumentNames[i] = argument.name; + // argumentNameStarts[i] = argument.sourceStart; + // argumentNameEnds[i] = argument.sourceEnd; + // argumentTypeStarts[i] = argumentType.sourceStart; + // argumentTypeEnds[i] = argumentType.sourceEnd; + // } + // } + // TypeReference[] thrownExceptions = cd.thrownExceptions; + // char[][] exceptionTypes = null; + // int[] exceptionTypeStarts = null; + // int[] exceptionTypeEnds = null; + // if (thrownExceptions != null) { + // int thrownExceptionLength = thrownExceptions.length; + // exceptionTypes = new char[thrownExceptionLength][]; + // exceptionTypeStarts = new int[thrownExceptionLength]; + // exceptionTypeEnds = new int[thrownExceptionLength]; + // for (int i = 0; i < thrownExceptionLength; i++) { + // TypeReference exception = thrownExceptions[i]; + // exceptionTypes[i] = CharOperation.concatWith(exception.getTypeName(), + // '.'); + // exceptionTypeStarts[i] = exception.sourceStart; + // exceptionTypeEnds[i] = exception.sourceEnd; + // } + // } + // requestor + // .enterConstructor( + // cd.declarationSourceStart, + // intArrayStack[intArrayPtr--], + // cd.modifiers, + // cd.modifiersSourceStart, + // cd.selector, + // cd.sourceStart, + // (int) (selectorSourcePositions & 0xFFFFFFFFL), + // // retrieve the source end of the name + // argumentTypes, + // argumentTypeStarts, + // argumentTypeEnds, + // argumentNames, + // argumentNameStarts, + // argumentNameEnds, + // rParenPos, + // // right parenthesis + // exceptionTypes, + // exceptionTypeStarts, + // exceptionTypeEnds, + // scanner.currentPosition - 1); + // } + // protected void consumeConstructorHeaderName() { + // // ConstructorHeaderName ::= Modifiersopt 'Identifier' '(' + // ConstructorDeclaration cd = new + // ConstructorDeclaration(this.compilationUnit.compilationResult); + // + // //name -- this is not really revelant but we do ..... + // cd.selector = identifierStack[identifierPtr]; + // selectorSourcePositions = identifierPositionStack[identifierPtr--]; + // identifierLengthPtr--; + // + // //modifiers + // cd.declarationSourceStart = intStack[intPtr--]; + // cd.modifiersSourceStart = intStack[intPtr--]; + // cd.modifiers = intStack[intPtr--]; + // + // //highlight starts at the selector starts + // cd.sourceStart = (int) (selectorSourcePositions >>> 32); + // pushOnAstStack(cd); + // + // cd.sourceEnd = lParenPos; + // cd.bodyStart = lParenPos + 1; + // } + // protected void consumeDefaultModifiers() { + // checkAnnotation(); // might update modifiers with AccDeprecated + // pushOnIntStack(modifiers); // modifiers + // pushOnIntStack(-1); + // pushOnIntStack( + // declarationSourceStart >= 0 ? declarationSourceStart : + // scanner.startPosition); + // resetModifiers(); + // } + // protected void consumeDiet() { + // // Diet ::= $empty + // super.consumeDiet(); + // /* persisting javadoc positions + // * Will be consume in consumeClassBodyDeclaration + // */ + // pushOnIntArrayStack(this.getJavaDocPositions()); + // } + // /** + // * + // * INTERNAL USE-ONLY + // */ + // protected void consumeEnterCompilationUnit() { + // // EnterCompilationUnit ::= $empty + // requestor.enterCompilationUnit(); + // } + // /** + // * + // * INTERNAL USE-ONLY + // */ + // protected void consumeEnterVariable() { + // // EnterVariable ::= $empty + // boolean isLocalDeclaration = isLocalDeclaration(); + // if (!isLocalDeclaration && (variablesCounter[nestedType] != 0)) { + // requestor.exitField(lastFieldBodyEndPosition, lastFieldEndPosition); + // } + // char[] name = identifierStack[identifierPtr]; + // long namePosition = identifierPositionStack[identifierPtr--]; + // int extendedTypeDimension = intStack[intPtr--]; + // + // AbstractVariableDeclaration declaration; + // if (nestedMethod[nestedType] != 0) { + // // create the local variable declarations + // declaration = + // new LocalDeclaration(null, name, (int) (namePosition >>> 32), (int) + // namePosition); + // } else { + // // create the field declaration + // declaration = + // new FieldDeclaration(null, name, (int) (namePosition >>> 32), (int) + // namePosition); + // } + // identifierLengthPtr--; + // TypeReference type; + // int variableIndex = variablesCounter[nestedType]; + // int typeDim = 0; + // if (variableIndex == 0) { + // // first variable of the declaration (FieldDeclaration or + // LocalDeclaration) + // if (nestedMethod[nestedType] != 0) { + // // local declaration + // declaration.declarationSourceStart = intStack[intPtr--]; + // declaration.modifiersSourceStart = intStack[intPtr--]; + // declaration.modifiers = intStack[intPtr--]; + // type = getTypeReference(typeDim = intStack[intPtr--]); // type dimension + // pushOnAstStack(type); + // } else { + // // field declaration + // type = getTypeReference(typeDim = intStack[intPtr--]); // type dimension + // pushOnAstStack(type); + // declaration.declarationSourceStart = intStack[intPtr--]; + // declaration.modifiersSourceStart = intStack[intPtr--]; + // declaration.modifiers = intStack[intPtr--]; + // } + // } else { + // type = (TypeReference) astStack[astPtr - variableIndex]; + // typeDim = type.dimensions(); + // AbstractVariableDeclaration previousVariable = + // (AbstractVariableDeclaration) astStack[astPtr]; + // declaration.declarationSourceStart = + // previousVariable.declarationSourceStart; + // declaration.modifiers = previousVariable.modifiers; + // declaration.modifiersSourceStart = previousVariable.modifiersSourceStart; + // } + // + // localIntPtr = intPtr; + // + // if (extendedTypeDimension == 0) { + // declaration.type = type; + // } else { + // int dimension = typeDim + extendedTypeDimension; + // //on the identifierLengthStack there is the information about the + // type.... + // int baseType; + // if ((baseType = identifierLengthStack[identifierLengthPtr + 1]) < 0) { + // //it was a baseType + // declaration.type = TypeReference.baseTypeReference(-baseType, dimension); + // declaration.type.sourceStart = type.sourceStart; + // declaration.type.sourceEnd = type.sourceEnd; + // } else { + // declaration.type = this.copyDims(type, dimension); + // } + // } + // variablesCounter[nestedType]++; + // nestedMethod[nestedType]++; + // pushOnAstStack(declaration); + // + // int[] javadocPositions = intArrayStack[intArrayPtr]; + // if (!isLocalDeclaration) { + // requestor + // .enterField( + // declaration.declarationSourceStart, + // javadocPositions, + // declaration.modifiers, + // declaration.modifiersSourceStart, + // returnTypeName(declaration.type), + // type.sourceStart, + // type.sourceEnd, + // typeDims, + // name, + // (int) (namePosition >>> 32), + // (int) namePosition, + // extendedTypeDimension, + // extendedTypeDimension == 0 ? -1 : endPosition); + // } + // } + // /** + // * + // * INTERNAL USE-ONLY + // */ + // protected void consumeExitVariableWithInitialization() { + // // ExitVariableWithInitialization ::= $empty + // // the scanner is located after the comma or the semi-colon. + // // we want to include the comma or the semi-colon + // super.consumeExitVariableWithInitialization(); + // nestedMethod[nestedType]--; + // lastFieldEndPosition = scanner.currentPosition - 1; + // lastFieldBodyEndPosition = ((AbstractVariableDeclaration) + // astStack[astPtr]).initialization.sourceEnd; + // } + // protected void consumeExitVariableWithoutInitialization() { + // // ExitVariableWithoutInitialization ::= $empty + // // do nothing by default + // super.consumeExitVariableWithoutInitialization(); + // nestedMethod[nestedType]--; + // lastFieldEndPosition = scanner.currentPosition - 1; + // lastFieldBodyEndPosition = scanner.startPosition - 1; + // } + // /** + // * + // * INTERNAL USE-ONLY + // */ + // protected void consumeFieldDeclaration() { + // // See consumeLocalVariableDeclarationDefaultModifier() in case of + // change: duplicated code + // // FieldDeclaration ::= Modifiersopt Type VariableDeclarators ';' + // // the super.consumeFieldDeclaration will reinitialize the + // variableCounter[nestedType] + // int variableIndex = variablesCounter[nestedType]; + // super.consumeFieldDeclaration(); + // intArrayPtr--; + // if (isLocalDeclaration()) + // return; + // if (variableIndex != 0) { + // requestor.exitField(lastFieldBodyEndPosition, lastFieldEndPosition); + // } + // } + // protected void consumeFormalParameter() { + // // FormalParameter ::= Type VariableDeclaratorId ==> false + // // FormalParameter ::= Modifiers Type VariableDeclaratorId ==> true + // /* + // astStack : + // identifierStack : type identifier + // intStack : dim dim + // ==> + // astStack : Argument + // identifierStack : + // intStack : + // */ + // + // identifierLengthPtr--; + // char[] name = identifierStack[identifierPtr]; + // long namePositions = identifierPositionStack[identifierPtr--]; + // TypeReference type = getTypeReference(intStack[intPtr--] + + // intStack[intPtr--]); + // intPtr -= 3; + // Argument arg = + // new Argument( + // name, + // namePositions, + // type, + // intStack[intPtr + 1]); // modifiers + // pushOnAstStack(arg); + // intArrayPtr--; + // } + // /** + // * + // * INTERNAL USE-ONLY + // */ + // protected void consumeInterfaceDeclaration() { + // super.consumeInterfaceDeclaration(); + // // we know that we have a TypeDeclaration on the top of the astStack + // if (isLocalDeclaration()) { + // // we ignore the local variable declarations + // return; + // } + // requestor.exitInterface(endStatementPosition, // the '}' is the end of + // the body + // ((TypeDeclaration) astStack[astPtr]).declarationSourceEnd); + // } + // /** + // * + // * INTERNAL USE-ONLY + // */ + // protected void consumeInterfaceHeader() { + // //InterfaceHeader ::= $empty + // super.consumeInterfaceHeader(); + // if (isLocalDeclaration()) { + // // we ignore the local variable declarations + // intArrayPtr--; + // return; + // } + // TypeDeclaration typeDecl = (TypeDeclaration) astStack[astPtr]; + // TypeReference[] superInterfaces = typeDecl.superInterfaces; + // char[][] interfaceNames = null; + // int[] interfaceNameStarts = null; + // int[] interfacenameEnds = null; + // int superInterfacesLength = 0; + // if (superInterfaces != null) { + // superInterfacesLength = superInterfaces.length; + // interfaceNames = new char[superInterfacesLength][]; + // interfaceNameStarts = new int[superInterfacesLength]; + // interfacenameEnds = new int[superInterfacesLength]; + // } + // if (superInterfaces != null) { + // for (int i = 0; i < superInterfacesLength; i++) { + // TypeReference superInterface = superInterfaces[i]; + // interfaceNames[i] = + // CharOperation.concatWith(superInterface.getTypeName(), '.'); + // interfaceNameStarts[i] = superInterface.sourceStart; + // interfacenameEnds[i] = superInterface.sourceEnd; + // } + // } + // // flush the comments related to the interface header + // scanner.commentPtr = -1; + // requestor.enterInterface( + // typeDecl.declarationSourceStart, + // intArrayStack[intArrayPtr--], + // typeDecl.modifiers, + // typeDecl.modifiersSourceStart, + // typeStartPosition, + // typeDecl.name, + // typeDecl.sourceStart, + // typeDecl.sourceEnd, + // interfaceNames, + // interfaceNameStarts, + // interfacenameEnds, + // scanner.currentPosition - 1); + // } + // protected void consumeInterfaceHeaderName() { + // // InterfaceHeaderName ::= Modifiersopt 'interface' 'Identifier' + // TypeDeclaration typeDecl; + // if (nestedMethod[nestedType] == 0) { + // if (nestedType != 0) { + // typeDecl = new + // MemberTypeDeclaration(this.compilationUnit.compilationResult); + // } else { + // typeDecl = new TypeDeclaration(this.compilationUnit.compilationResult); + // } + // } else { + // // Record that the block has a declaration for local types + // typeDecl = new + // LocalTypeDeclaration(this.compilationUnit.compilationResult); + // markEnclosingMemberWithLocalType(); + // blockReal(); + // } + // + // //highlight the name of the type + // long pos = identifierPositionStack[identifierPtr]; + // typeDecl.sourceEnd = (int) pos; + // typeDecl.sourceStart = (int) (pos >>> 32); + // typeDecl.name = identifierStack[identifierPtr--]; + // identifierLengthPtr--; + // + // //compute the declaration source too + // // 'class' and 'interface' push an int position + // typeStartPosition = typeDecl.declarationSourceStart = intStack[intPtr--]; + // intPtr--; + // int declarationSourceStart = intStack[intPtr--]; + // typeDecl.modifiersSourceStart = intStack[intPtr--]; + // typeDecl.modifiers = intStack[intPtr--]; + // if (typeDecl.declarationSourceStart > declarationSourceStart) { + // typeDecl.declarationSourceStart = declarationSourceStart; + // } + // typeDecl.bodyStart = typeDecl.sourceEnd + 1; + // pushOnAstStack(typeDecl); + // } + // /** + // * + // * INTERNAL USE-ONLY + // */ + // protected void consumeLocalVariableDeclaration() { + // // See consumeLocalVariableDeclarationDefaultModifier() in case of + // change: duplicated code + // // FieldDeclaration ::= Modifiersopt Type VariableDeclarators ';' + // + // super.consumeLocalVariableDeclaration(); + // intArrayPtr--; + // } + // /** + // * + // * INTERNAL USE-ONLY + // */ + // protected void consumeMethodDeclaration(boolean isNotAbstract) { + // // MethodDeclaration ::= MethodHeader MethodBody + // // AbstractMethodDeclaration ::= MethodHeader ';' + // super.consumeMethodDeclaration(isNotAbstract); + // if (isLocalDeclaration()) { + // // we ignore the local variable declarations + // return; + // } + // MethodDeclaration md = (MethodDeclaration) astStack[astPtr]; + // requestor.exitMethod(endStatementPosition, md.declarationSourceEnd); + // } + // /** + // * + // * INTERNAL USE-ONLY + // */ + // protected void consumeMethodHeader() { + // // MethodHeader ::= MethodHeaderName MethodHeaderParameters + // MethodHeaderExtendedDims ThrowsClauseopt + // super.consumeMethodHeader(); + // if (isLocalDeclaration()) { + // // we ignore the local variable declarations + // intArrayPtr--; + // return; + // } + // MethodDeclaration md = (MethodDeclaration) astStack[astPtr]; + // + // TypeReference returnType = md.returnType; + // char[] returnTypeName = returnTypeName(returnType); + // Argument[] arguments = md.arguments; + // char[][] argumentTypes = null; + // char[][] argumentNames = null; + // int[] argumentTypeStarts = null; + // int[] argumentTypeEnds = null; + // int[] argumentNameStarts = null; + // int[] argumentNameEnds = null; + // if (arguments != null) { + // int argumentLength = arguments.length; + // argumentTypes = new char[argumentLength][]; + // argumentNames = new char[argumentLength][]; + // argumentNameStarts = new int[argumentLength]; + // argumentNameEnds = new int[argumentLength]; + // argumentTypeStarts = new int[argumentLength]; + // argumentTypeEnds = new int[argumentLength]; + // for (int i = 0; i < argumentLength; i++) { + // Argument argument = arguments[i]; + // TypeReference argumentType = argument.type; + // argumentTypes[i] = returnTypeName(argumentType); + // argumentNames[i] = argument.name; + // argumentNameStarts[i] = argument.sourceStart; + // argumentNameEnds[i] = argument.sourceEnd; + // argumentTypeStarts[i] = argumentType.sourceStart; + // argumentTypeEnds[i] = argumentType.sourceEnd; + // } + // } + // TypeReference[] thrownExceptions = md.thrownExceptions; + // char[][] exceptionTypes = null; + // int[] exceptionTypeStarts = null; + // int[] exceptionTypeEnds = null; + // if (thrownExceptions != null) { + // int thrownExceptionLength = thrownExceptions.length; + // exceptionTypeStarts = new int[thrownExceptionLength]; + // exceptionTypeEnds = new int[thrownExceptionLength]; + // exceptionTypes = new char[thrownExceptionLength][]; + // for (int i = 0; i < thrownExceptionLength; i++) { + // TypeReference exception = thrownExceptions[i]; + // exceptionTypes[i] = CharOperation.concatWith(exception.getTypeName(), + // '.'); + // exceptionTypeStarts[i] = exception.sourceStart; + // exceptionTypeEnds[i] = exception.sourceEnd; + // } + // } + // requestor + // .enterMethod( + // md.declarationSourceStart, + // intArrayStack[intArrayPtr--], + // md.modifiers, + // md.modifiersSourceStart, + // returnTypeName, + // returnType.sourceStart, + // returnType.sourceEnd, + // typeDims, + // md.selector, + // md.sourceStart, + // (int) (selectorSourcePositions & 0xFFFFFFFFL), + // argumentTypes, + // argumentTypeStarts, + // argumentTypeEnds, + // argumentNames, + // argumentNameStarts, + // argumentNameEnds, + // rParenPos, + // extendsDim, + // extendsDim == 0 ? -1 : endPosition, + // exceptionTypes, + // exceptionTypeStarts, + // exceptionTypeEnds, + // scanner.currentPosition - 1); + // } + // protected void consumeMethodHeaderExtendedDims() { + // // MethodHeaderExtendedDims ::= Dimsopt + // // now we update the returnType of the method + // MethodDeclaration md = (MethodDeclaration) astStack[astPtr]; + // int extendedDims = intStack[intPtr--]; + // extendsDim = extendedDims; + // if (extendedDims != 0) { + // TypeReference returnType = md.returnType; + // md.sourceEnd = endPosition; + // int dims = returnType.dimensions() + extendedDims; + // int baseType; + // if ((baseType = identifierLengthStack[identifierLengthPtr + 1]) < 0) { + // //it was a baseType + // int sourceStart = returnType.sourceStart; + // int sourceEnd = returnType.sourceEnd; + // returnType = TypeReference.baseTypeReference(-baseType, dims); + // returnType.sourceStart = sourceStart; + // returnType.sourceEnd = sourceEnd; + // md.returnType = returnType; + // } else { + // md.returnType = this.copyDims(md.returnType, dims); + // } + // if (currentToken == TokenNameLBRACE) { + // md.bodyStart = endPosition + 1; + // } + // } + // } + // protected void consumeMethodHeaderName() { + // // MethodHeaderName ::= Modifiersopt Type 'Identifier' '(' + // MethodDeclaration md = new + // MethodDeclaration(this.compilationUnit.compilationResult); + // + // //name + // md.selector = identifierStack[identifierPtr]; + // selectorSourcePositions = identifierPositionStack[identifierPtr--]; + // identifierLengthPtr--; + // //type + // md.returnType = getTypeReference(typeDims = intStack[intPtr--]); + // //modifiers + // md.declarationSourceStart = intStack[intPtr--]; + // md.modifiersSourceStart = intStack[intPtr--]; + // md.modifiers = intStack[intPtr--]; + // + // //highlight starts at selector start + // md.sourceStart = (int) (selectorSourcePositions >>> 32); + // pushOnAstStack(md); + // md.bodyStart = scanner.currentPosition-1; + // } + // protected void consumeModifiers() { + // checkAnnotation(); // might update modifiers with AccDeprecated + // pushOnIntStack(modifiers); // modifiers + // pushOnIntStack(modifiersSourceStart); + // pushOnIntStack( + // declarationSourceStart >= 0 ? declarationSourceStart : + // modifiersSourceStart); + // resetModifiers(); + // } + /** + * + * INTERNAL USE-ONLY + */ + // protected void consumePackageDeclarationName() { + // /* persisting javadoc positions */ + // pushOnIntArrayStack(this.getJavaDocPositions()); + // + // super.consumePackageDeclarationName(); + // ImportReference importReference = compilationUnit.currentPackage; + // + // requestor.acceptPackage( + // importReference.declarationSourceStart, + // importReference.declarationSourceEnd, + // intArrayStack[intArrayPtr--], + // CharOperation.concatWith(importReference.getImportName(), '.'), + // importReference.sourceStart); + // } + // protected void consumePushModifiers() { + // checkAnnotation(); // might update modifiers with AccDeprecated + // pushOnIntStack(modifiers); // modifiers + // if (modifiersSourceStart < 0) { + // pushOnIntStack(-1); + // pushOnIntStack( + // declarationSourceStart >= 0 ? declarationSourceStart : + // scanner.startPosition); + // } else { + // pushOnIntStack(modifiersSourceStart); + // pushOnIntStack( + // declarationSourceStart >= 0 ? declarationSourceStart : + // modifiersSourceStart); + // } + // resetModifiers(); + // } + // /** + // * + // * INTERNAL USE-ONLY + // */ + // protected void consumeSingleTypeImportDeclarationName() { + // // SingleTypeImportDeclarationName ::= 'import' Name + // + // /* persisting javadoc positions */ + // pushOnIntArrayStack(this.getJavaDocPositions()); + // + // super.consumeSingleTypeImportDeclarationName(); + // ImportReference importReference = (ImportReference) astStack[astPtr]; + // requestor.acceptImport( + // importReference.declarationSourceStart, + // importReference.declarationSourceEnd, + // intArrayStack[intArrayPtr--], + // CharOperation.concatWith(importReference.getImportName(), '.'), + // importReference.sourceStart, + // false); + // } + // /** + // * + // * INTERNAL USE-ONLY + // */ + // protected void consumeStaticInitializer() { + // // StaticInitializer ::= StaticOnly Block + // //push an Initializer + // //optimize the push/pop + // super.consumeStaticInitializer(); + // Initializer initializer = (Initializer) astStack[astPtr]; + // requestor.acceptInitializer( + // initializer.declarationSourceStart, + // initializer.declarationSourceEnd, + // intArrayStack[intArrayPtr--], + // AccStatic, + // intStack[intPtr--], + // initializer.block.sourceStart, + // initializer.declarationSourceEnd); + // } + // protected void consumeStaticOnly() { + // // StaticOnly ::= 'static' + // checkAnnotation(); // might update declaration source start + // pushOnIntStack(modifiersSourceStart); + // pushOnIntStack( + // declarationSourceStart >= 0 ? declarationSourceStart : + // modifiersSourceStart); + // jumpOverMethodBody(); + // nestedMethod[nestedType]++; + // resetModifiers(); + // } + // /** + // * + // * INTERNAL USE-ONLY + // */ + // protected void consumeTypeImportOnDemandDeclarationName() { + // // TypeImportOnDemandDeclarationName ::= 'import' Name '.' '*' + // + // /* persisting javadoc positions */ + // pushOnIntArrayStack(this.getJavaDocPositions()); + // + // super.consumeTypeImportOnDemandDeclarationName(); + // ImportReference importReference = (ImportReference) astStack[astPtr]; + // requestor.acceptImport( + // importReference.declarationSourceStart, + // importReference.declarationSourceEnd, + // intArrayStack[intArrayPtr--], + // CharOperation.concatWith(importReference.getImportName(), '.'), + // importReference.sourceStart, + // true); + // } + public CompilationUnitDeclaration endParse(int act) { + if (scanner.recordLineSeparator) { + requestor.acceptLineSeparatorPositions(scanner.getLineEnds()); + } + return super.endParse(act); + } - /* - * Flush annotations defined prior to a given positions. - * - * Note: annotations are stacked in syntactical order - * - * Either answer given , or the end position of a comment line immediately following the (same line) - * - * e.g. void foo(){ } // end of method foo - */ + /* + * Flush annotations defined prior to a given positions. + * + * Note: annotations are stacked in syntactical order + * + * Either answer given , or the end position of a comment line + * immediately following the (same line) + * + * e.g. void foo(){ } // end of method foo + */ - //public int flushAnnotationsDefinedPriorTo(int position) { - // - // return lastFieldEndPosition = super.flushAnnotationsDefinedPriorTo(position); - //} - //protected TypeReference getTypeReference(int dim) { /* build a Reference on a variable that may be qualified or not - //This variable is a type reference and dim will be its dimensions*/ - // - // int length; - // TypeReference ref; - // if ((length = identifierLengthStack[identifierLengthPtr--]) == 1) { - // // single variable reference - // if (dim == 0) { - // ref = - // new SingleTypeReference( - // identifierStack[identifierPtr], - // identifierPositionStack[identifierPtr--]); - // } else { - // ref = - // new ArrayTypeReference( - // identifierStack[identifierPtr], - // dim, - // identifierPositionStack[identifierPtr--]); - // ref.sourceEnd = endPosition; - // } - // } else { - // if (length < 0) { //flag for precompiled type reference on base types - // ref = TypeReference.baseTypeReference(-length, dim); - // ref.sourceStart = intStack[intPtr--]; - // if (dim == 0) { - // ref.sourceEnd = intStack[intPtr--]; - // } else { - // intPtr--; - // ref.sourceEnd = endPosition; - // } - // } else { //Qualified variable reference - // char[][] tokens = new char[length][]; - // identifierPtr -= length; - // long[] positions = new long[length]; - // System.arraycopy(identifierStack, identifierPtr + 1, tokens, 0, length); - // System.arraycopy( - // identifierPositionStack, - // identifierPtr + 1, - // positions, - // 0, - // length); - // if (dim == 0) { - // ref = new QualifiedTypeReference(tokens, positions); - // } else { - // ref = new ArrayQualifiedTypeReference(tokens, dim, positions); - // ref.sourceEnd = endPosition; - // } - // } - // }; - // return ref; - //} - public void initialize() { - //positionning the parser for a new compilation unit - //avoiding stack reallocation and all that.... - super.initialize(false); - intArrayPtr = -1; - } + // public int flushAnnotationsDefinedPriorTo(int position) { + // + // return lastFieldEndPosition = + // super.flushAnnotationsDefinedPriorTo(position); + // } + // protected TypeReference getTypeReference(int dim) { /* build a Reference + // on a variable that may be qualified or not + // This variable is a type reference and dim will be its dimensions*/ + // + // int length; + // TypeReference ref; + // if ((length = identifierLengthStack[identifierLengthPtr--]) == 1) { + // // single variable reference + // if (dim == 0) { + // ref = + // new SingleTypeReference( + // identifierStack[identifierPtr], + // identifierPositionStack[identifierPtr--]); + // } else { + // ref = + // new ArrayTypeReference( + // identifierStack[identifierPtr], + // dim, + // identifierPositionStack[identifierPtr--]); + // ref.sourceEnd = endPosition; + // } + // } else { + // if (length < 0) { //flag for precompiled type reference on base types + // ref = TypeReference.baseTypeReference(-length, dim); + // ref.sourceStart = intStack[intPtr--]; + // if (dim == 0) { + // ref.sourceEnd = intStack[intPtr--]; + // } else { + // intPtr--; + // ref.sourceEnd = endPosition; + // } + // } else { //Qualified variable reference + // char[][] tokens = new char[length][]; + // identifierPtr -= length; + // long[] positions = new long[length]; + // System.arraycopy(identifierStack, identifierPtr + 1, tokens, 0, length); + // System.arraycopy( + // identifierPositionStack, + // identifierPtr + 1, + // positions, + // 0, + // length); + // if (dim == 0) { + // ref = new QualifiedTypeReference(tokens, positions); + // } else { + // ref = new ArrayQualifiedTypeReference(tokens, dim, positions); + // ref.sourceEnd = endPosition; + // } + // } + // }; + // return ref; + // } + public void initialize() { + // positionning the parser for a new compilation unit + // avoiding stack reallocation and all that.... + super.initialize(false); + intArrayPtr = -1; + } - /** - * - * INTERNAL USE-ONLY - */ - //private boolean isLocalDeclaration() { - // int nestedDepth = nestedType; - // while (nestedDepth >= 0) { - // if (nestedMethod[nestedDepth] != 0) { - // return true; - // } - // nestedDepth--; - // } - // return false; - //} - /* - * Investigate one entire unit. - */ - public void parseCompilationUnit(ICompilationUnit unit) { - char[] regionSource = unit.getContents(); - try { - initialize(); - goForCompilationUnit(); - referenceContext = compilationUnit = new CompilationUnitDeclaration(problemReporter(), - new CompilationResult(unit, 0, 0, 10), //this.options.maxProblemsPerUnit), - regionSource.length); - scanner.resetTo(0, regionSource.length); - scanner.setSource(regionSource); - parse(); - } catch (AbortCompilation ex) { - } - } + /** + * + * INTERNAL USE-ONLY + */ + // private boolean isLocalDeclaration() { + // int nestedDepth = nestedType; + // while (nestedDepth >= 0) { + // if (nestedMethod[nestedDepth] != 0) { + // return true; + // } + // nestedDepth--; + // } + // return false; + // } + /* + * Investigate one entire unit. + */ + public void parseCompilationUnit(ICompilationUnit unit) { + char[] regionSource = unit.getContents(); + try { + initialize(); + goForCompilationUnit(); + referenceContext = compilationUnit = new CompilationUnitDeclaration( + problemReporter(), new CompilationResult(unit, 0, 0, 10), // this.options.maxProblemsPerUnit), + regionSource.length); + scanner.resetTo(0, regionSource.length); + scanner.setSource(regionSource); + parse(); + } catch (AbortCompilation ex) { + } + } - /* - * Investigate one constructor declaration. - */ - //public void parseConstructor(char[] regionSource) { - // try { - // initialize(); - // goForClassBodyDeclarations(); - // referenceContext = - // compilationUnit = - // compilationUnit = - // new CompilationUnitDeclaration( - // problemReporter(), - // new CompilationResult(regionSource, 0, 0, 10), //this.options.maxProblemsPerUnit), - // regionSource.length); - // scanner.resetTo(0, regionSource.length); - // scanner.setSource(regionSource); - // parse(); - // } catch (AbortCompilation ex) { - // } - //} - /* - * Investigate one field declaration statement (might have multiple declarations in it). - */ - //public void parseField(char[] regionSource) { - // try { - // initialize(); - // goForFieldDeclaration(); - // referenceContext = - // compilationUnit = - // compilationUnit = - // new CompilationUnitDeclaration( - // problemReporter(), - // new CompilationResult(regionSource, 0, 0, this.options.maxProblemsPerUnit), - // regionSource.length); - // scanner.resetTo(0, regionSource.length); - // scanner.setSource(regionSource); - // parse(); - // } catch (AbortCompilation ex) { - // } - // - //} - ///* - // * Investigate one import statement declaration. - // */ - //public void parseImport(char[] regionSource) { - // try { - // initialize(); - // goForImportDeclaration(); - // referenceContext = - // compilationUnit = - // compilationUnit = - // new CompilationUnitDeclaration( - // problemReporter(), - // new CompilationResult(regionSource, 0, 0, this.options.maxProblemsPerUnit), - // regionSource.length); - // scanner.resetTo(0, regionSource.length); - // scanner.setSource(regionSource); - // parse(); - // } catch (AbortCompilation ex) { - // } - // - //} - ///* - // * Investigate one initializer declaration. - // * regionSource need to content exactly an initializer declaration. - // * e.g: static { i = 4; } - // * { name = "test"; } - // */ - //public void parseInitializer(char[] regionSource) { - // try { - // initialize(); - // goForInitializer(); - // referenceContext = - // compilationUnit = - // compilationUnit = - // new CompilationUnitDeclaration( - // problemReporter(), - // new CompilationResult(regionSource, 0, 0, this.options.maxProblemsPerUnit), - // regionSource.length); - // scanner.resetTo(0, regionSource.length); - // scanner.setSource(regionSource); - // parse(); - // } catch (AbortCompilation ex) { - // } - // - //} - ///* - // * Investigate one method declaration. - // */ - //public void parseMethod(char[] regionSource) { - // try { - // initialize(); - // goForGenericMethodDeclaration(); - // referenceContext = - // compilationUnit = - // compilationUnit = - // new CompilationUnitDeclaration( - // problemReporter(), - // new CompilationResult(regionSource, 0, 0, this.options.maxProblemsPerUnit), - // regionSource.length); - // scanner.resetTo(0, regionSource.length); - // scanner.setSource(regionSource); - // parse(); - // } catch (AbortCompilation ex) { - // } - // - //} - ///* - // * Investigate one package statement declaration. - // */ - //public void parsePackage(char[] regionSource) { - // try { - // initialize(); - // goForPackageDeclaration(); - // referenceContext = - // compilationUnit = - // compilationUnit = - // new CompilationUnitDeclaration( - // problemReporter(), - // new CompilationResult(regionSource, 0, 0, this.options.maxProblemsPerUnit), - // regionSource.length); - // scanner.resetTo(0, regionSource.length); - // scanner.setSource(regionSource); - // parse(); - // } catch (AbortCompilation ex) { - // } - // - //} - ///* - // * Investigate one type declaration, its fields, methods and member types. - // */ - //public void parseType(char[] regionSource) { - // try { - // initialize(); - // goForTypeDeclaration(); - // referenceContext = - // compilationUnit = - // compilationUnit = - // new CompilationUnitDeclaration( - // problemReporter(), - // new CompilationResult(regionSource, 0, 0, this.options.maxProblemsPerUnit), - // regionSource.length); - // scanner.resetTo(0, regionSource.length); - // scanner.setSource(regionSource); - // parse(); - // } catch (AbortCompilation ex) { - // } - // - //} - /** - * Returns this parser's problem reporter initialized with its reference context. Also it is assumed that a problem is going to be - * reported, so initializes the compilation result's line positions. - */ - public ProblemReporter problemReporter() { - problemReporter.referenceContext = referenceContext; - return problemReporter; - } + /* + * Investigate one constructor declaration. + */ + // public void parseConstructor(char[] regionSource) { + // try { + // initialize(); + // goForClassBodyDeclarations(); + // referenceContext = + // compilationUnit = + // compilationUnit = + // new CompilationUnitDeclaration( + // problemReporter(), + // new CompilationResult(regionSource, 0, 0, 10), + // //this.options.maxProblemsPerUnit), + // regionSource.length); + // scanner.resetTo(0, regionSource.length); + // scanner.setSource(regionSource); + // parse(); + // } catch (AbortCompilation ex) { + // } + // } + /* + * Investigate one field declaration statement (might have multiple + * declarations in it). + */ + // public void parseField(char[] regionSource) { + // try { + // initialize(); + // goForFieldDeclaration(); + // referenceContext = + // compilationUnit = + // compilationUnit = + // new CompilationUnitDeclaration( + // problemReporter(), + // new CompilationResult(regionSource, 0, 0, + // this.options.maxProblemsPerUnit), + // regionSource.length); + // scanner.resetTo(0, regionSource.length); + // scanner.setSource(regionSource); + // parse(); + // } catch (AbortCompilation ex) { + // } + // + // } + // /* + // * Investigate one import statement declaration. + // */ + // public void parseImport(char[] regionSource) { + // try { + // initialize(); + // goForImportDeclaration(); + // referenceContext = + // compilationUnit = + // compilationUnit = + // new CompilationUnitDeclaration( + // problemReporter(), + // new CompilationResult(regionSource, 0, 0, + // this.options.maxProblemsPerUnit), + // regionSource.length); + // scanner.resetTo(0, regionSource.length); + // scanner.setSource(regionSource); + // parse(); + // } catch (AbortCompilation ex) { + // } + // + // } + // /* + // * Investigate one initializer declaration. + // * regionSource need to content exactly an initializer declaration. + // * e.g: static { i = 4; } + // * { name = "test"; } + // */ + // public void parseInitializer(char[] regionSource) { + // try { + // initialize(); + // goForInitializer(); + // referenceContext = + // compilationUnit = + // compilationUnit = + // new CompilationUnitDeclaration( + // problemReporter(), + // new CompilationResult(regionSource, 0, 0, + // this.options.maxProblemsPerUnit), + // regionSource.length); + // scanner.resetTo(0, regionSource.length); + // scanner.setSource(regionSource); + // parse(); + // } catch (AbortCompilation ex) { + // } + // + // } + // /* + // * Investigate one method declaration. + // */ + // public void parseMethod(char[] regionSource) { + // try { + // initialize(); + // goForGenericMethodDeclaration(); + // referenceContext = + // compilationUnit = + // compilationUnit = + // new CompilationUnitDeclaration( + // problemReporter(), + // new CompilationResult(regionSource, 0, 0, + // this.options.maxProblemsPerUnit), + // regionSource.length); + // scanner.resetTo(0, regionSource.length); + // scanner.setSource(regionSource); + // parse(); + // } catch (AbortCompilation ex) { + // } + // + // } + // /* + // * Investigate one package statement declaration. + // */ + // public void parsePackage(char[] regionSource) { + // try { + // initialize(); + // goForPackageDeclaration(); + // referenceContext = + // compilationUnit = + // compilationUnit = + // new CompilationUnitDeclaration( + // problemReporter(), + // new CompilationResult(regionSource, 0, 0, + // this.options.maxProblemsPerUnit), + // regionSource.length); + // scanner.resetTo(0, regionSource.length); + // scanner.setSource(regionSource); + // parse(); + // } catch (AbortCompilation ex) { + // } + // + // } + // /* + // * Investigate one type declaration, its fields, methods and member types. + // */ + // public void parseType(char[] regionSource) { + // try { + // initialize(); + // goForTypeDeclaration(); + // referenceContext = + // compilationUnit = + // compilationUnit = + // new CompilationUnitDeclaration( + // problemReporter(), + // new CompilationResult(regionSource, 0, 0, + // this.options.maxProblemsPerUnit), + // regionSource.length); + // scanner.resetTo(0, regionSource.length); + // scanner.setSource(regionSource); + // parse(); + // } catch (AbortCompilation ex) { + // } + // + // } + /** + * Returns this parser's problem reporter initialized with its reference + * context. Also it is assumed that a problem is going to be reported, so + * initializes the compilation result's line positions. + */ + public ProblemReporter problemReporter() { + problemReporter.referenceContext = referenceContext; + return problemReporter; + } - protected void pushOnIntArrayStack(int[] positions) { + protected void pushOnIntArrayStack(int[] positions) { - try { - intArrayStack[++intArrayPtr] = positions; - } catch (IndexOutOfBoundsException e) { - //intPtr is correct - int oldStackLength = intArrayStack.length; - int oldStack[][] = intArrayStack; - intArrayStack = new int[oldStackLength + StackIncrement][]; - System.arraycopy(oldStack, 0, intArrayStack, 0, oldStackLength); - intArrayStack[intArrayPtr] = positions; - } - } + try { + intArrayStack[++intArrayPtr] = positions; + } catch (IndexOutOfBoundsException e) { + // intPtr is correct + int oldStackLength = intArrayStack.length; + int oldStack[][] = intArrayStack; + intArrayStack = new int[oldStackLength + StackIncrement][]; + System.arraycopy(oldStack, 0, intArrayStack, 0, oldStackLength); + intArrayStack[intArrayPtr] = positions; + } + } - //protected void resetModifiers() { - // super.resetModifiers(); - // declarationSourceStart = -1; - //} - /* - * Syntax error was detected. Will attempt to perform some recovery action in order to resume to the regular parse loop. - */ - protected boolean resumeOnSyntaxError() { - return false; - } - /* - * Answer a char array representation of the type name formatted like: - type name + dimensions Example: "A[][]".toCharArray() - * "java.lang.String".toCharArray() - */ - //private char[] returnTypeName(TypeReference type) { - // int dimension = type.dimensions(); - // if (dimension != 0) { - // char[] dimensionsArray = new char[dimension * 2]; - // for (int i = 0; i < dimension; i++) { - // dimensionsArray[i*2] = '['; - // dimensionsArray[(i*2) + 1] = ']'; - // } - // return CharOperation.concat( - // CharOperation.concatWith(type.getTypeName(), '.'), - // dimensionsArray); - // } - // return CharOperation.concatWith(type.getTypeName(), '.'); - //} - //public String toString() { - // StringBuffer buffer = new StringBuffer(); - // buffer.append("intArrayPtr = " + intArrayPtr + "\n"); //$NON-NLS-1$ //$NON-NLS-2$ - // buffer.append(super.toString()); - // return buffer.toString(); - //} - ///** - // * INTERNAL USE ONLY - // */ - //protected TypeReference typeReference( - // int dim, - // int localIdentifierPtr, - // int localIdentifierLengthPtr) { - // /* build a Reference on a variable that may be qualified or not - // * This variable is a type reference and dim will be its dimensions. - // * We don't have any side effect on the stacks' pointers. - // */ - // - // int length; - // TypeReference ref; - // if ((length = identifierLengthStack[localIdentifierLengthPtr]) == 1) { - // // single variable reference - // if (dim == 0) { - // ref = - // new SingleTypeReference( - // identifierStack[localIdentifierPtr], - // identifierPositionStack[localIdentifierPtr--]); - // } else { - // ref = - // new ArrayTypeReference( - // identifierStack[localIdentifierPtr], - // dim, - // identifierPositionStack[localIdentifierPtr--]); - // ref.sourceEnd = endPosition; - // } - // } else { - // if (length < 0) { //flag for precompiled type reference on base types - // ref = TypeReference.baseTypeReference(-length, dim); - // ref.sourceStart = intStack[localIntPtr--]; - // if (dim == 0) { - // ref.sourceEnd = intStack[localIntPtr--]; - // } else { - // localIntPtr--; - // ref.sourceEnd = endPosition; - // } - // } else { //Qualified variable reference - // char[][] tokens = new char[length][]; - // localIdentifierPtr -= length; - // long[] positions = new long[length]; - // System.arraycopy(identifierStack, localIdentifierPtr + 1, tokens, 0, length); - // System.arraycopy( - // identifierPositionStack, - // localIdentifierPtr + 1, - // positions, - // 0, - // length); - // if (dim == 0) - // ref = new QualifiedTypeReference(tokens, positions); - // else - // ref = new ArrayQualifiedTypeReference(tokens, dim, positions); - // } - // }; - // return ref; - //} + // protected void resetModifiers() { + // super.resetModifiers(); + // declarationSourceStart = -1; + // } + /* + * Syntax error was detected. Will attempt to perform some recovery action + * in order to resume to the regular parse loop. + */ + protected boolean resumeOnSyntaxError() { + return false; + } + /* + * Answer a char array representation of the type name formatted like: - + * type name + dimensions Example: "A[][]".toCharArray() + * "java.lang.String".toCharArray() + */ + // private char[] returnTypeName(TypeReference type) { + // int dimension = type.dimensions(); + // if (dimension != 0) { + // char[] dimensionsArray = new char[dimension * 2]; + // for (int i = 0; i < dimension; i++) { + // dimensionsArray[i*2] = '['; + // dimensionsArray[(i*2) + 1] = ']'; + // } + // return CharOperation.concat( + // CharOperation.concatWith(type.getTypeName(), '.'), + // dimensionsArray); + // } + // return CharOperation.concatWith(type.getTypeName(), '.'); + // } + // public String toString() { + // StringBuffer buffer = new StringBuffer(); + // buffer.append("intArrayPtr = " + intArrayPtr + "\n"); //$NON-NLS-1$ + // //$NON-NLS-2$ + // buffer.append(super.toString()); + // return buffer.toString(); + // } + // /** + // * INTERNAL USE ONLY + // */ + // protected TypeReference typeReference( + // int dim, + // int localIdentifierPtr, + // int localIdentifierLengthPtr) { + // /* build a Reference on a variable that may be qualified or not + // * This variable is a type reference and dim will be its dimensions. + // * We don't have any side effect on the stacks' pointers. + // */ + // + // int length; + // TypeReference ref; + // if ((length = identifierLengthStack[localIdentifierLengthPtr]) == 1) { + // // single variable reference + // if (dim == 0) { + // ref = + // new SingleTypeReference( + // identifierStack[localIdentifierPtr], + // identifierPositionStack[localIdentifierPtr--]); + // } else { + // ref = + // new ArrayTypeReference( + // identifierStack[localIdentifierPtr], + // dim, + // identifierPositionStack[localIdentifierPtr--]); + // ref.sourceEnd = endPosition; + // } + // } else { + // if (length < 0) { //flag for precompiled type reference on base types + // ref = TypeReference.baseTypeReference(-length, dim); + // ref.sourceStart = intStack[localIntPtr--]; + // if (dim == 0) { + // ref.sourceEnd = intStack[localIntPtr--]; + // } else { + // localIntPtr--; + // ref.sourceEnd = endPosition; + // } + // } else { //Qualified variable reference + // char[][] tokens = new char[length][]; + // localIdentifierPtr -= length; + // long[] positions = new long[length]; + // System.arraycopy(identifierStack, localIdentifierPtr + 1, tokens, 0, + // length); + // System.arraycopy( + // identifierPositionStack, + // localIdentifierPtr + 1, + // positions, + // 0, + // length); + // if (dim == 0) + // ref = new QualifiedTypeReference(tokens, positions); + // else + // ref = new ArrayQualifiedTypeReference(tokens, dim, positions); + // } + // }; + // return ref; + // } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/IAbstractSyntaxTreeVisitor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/IAbstractSyntaxTreeVisitor.java index be48825..f29b43b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/IAbstractSyntaxTreeVisitor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/IAbstractSyntaxTreeVisitor.java @@ -89,154 +89,324 @@ import net.sourceforge.phpdt.internal.compiler.lookup.MethodScope; */ public interface IAbstractSyntaxTreeVisitor { void acceptProblem(IProblem problem); + void endVisit(AllocationExpression allocationExpression, BlockScope scope); + void endVisit(AND_AND_Expression and_and_Expression, BlockScope scope); - void endVisit(AnonymousLocalTypeDeclaration anonymousTypeDeclaration, BlockScope scope); + + void endVisit(AnonymousLocalTypeDeclaration anonymousTypeDeclaration, + BlockScope scope); + void endVisit(Argument argument, BlockScope scope); - void endVisit(ArrayAllocationExpression arrayAllocationExpression, BlockScope scope); + + void endVisit(ArrayAllocationExpression arrayAllocationExpression, + BlockScope scope); + void endVisit(ArrayInitializer arrayInitializer, BlockScope scope); - void endVisit(ArrayQualifiedTypeReference arrayQualifiedTypeReference, BlockScope scope); - void endVisit(ArrayQualifiedTypeReference arrayQualifiedTypeReference, ClassScope scope); + + void endVisit(ArrayQualifiedTypeReference arrayQualifiedTypeReference, + BlockScope scope); + + void endVisit(ArrayQualifiedTypeReference arrayQualifiedTypeReference, + ClassScope scope); + void endVisit(ArrayReference arrayReference, BlockScope scope); + void endVisit(ArrayTypeReference arrayTypeReference, BlockScope scope); + void endVisit(ArrayTypeReference arrayTypeReference, ClassScope scope); + void endVisit(AssertStatement assertStatement, BlockScope scope); + void endVisit(Assignment assignment, BlockScope scope); + void endVisit(BinaryExpression binaryExpression, BlockScope scope); + void endVisit(Block block, BlockScope scope); + void endVisit(BreakStatement breakStatement, BlockScope scope); + void endVisit(CaseStatement caseStatement, BlockScope scope); + void endVisit(CastExpression castExpression, BlockScope scope); -// void endVisit(CharLiteral charLiteral, BlockScope scope); -// void endVisit(ClassLiteralAccess classLiteral, BlockScope scope); + + // void endVisit(CharLiteral charLiteral, BlockScope scope); + // void endVisit(ClassLiteralAccess classLiteral, BlockScope scope); void endVisit(Clinit clinit, ClassScope scope); - void endVisit(CompilationUnitDeclaration compilationUnitDeclaration, CompilationUnitScope scope); + + void endVisit(CompilationUnitDeclaration compilationUnitDeclaration, + CompilationUnitScope scope); + void endVisit(CompoundAssignment compoundAssignment, BlockScope scope); + void endVisit(ConditionalExpression conditionalExpression, BlockScope scope); - void endVisit(ConstructorDeclaration constructorDeclaration, ClassScope scope); + + void endVisit(ConstructorDeclaration constructorDeclaration, + ClassScope scope); + void endVisit(ContinueStatement continueStatement, BlockScope scope); + void endVisit(DefaultCase defaultCaseStatement, BlockScope scope); + void endVisit(DoStatement doStatement, BlockScope scope); + void endVisit(DoubleLiteral doubleLiteral, BlockScope scope); + void endVisit(EqualExpression equalExpression, BlockScope scope); + void endVisit(EmptyStatement statement, BlockScope scope); + void endVisit(ExplicitConstructorCall explicitConstructor, BlockScope scope); + void endVisit(ExtendedStringLiteral extendedStringLiteral, BlockScope scope); + void endVisit(FalseLiteral falseLiteral, BlockScope scope); + void endVisit(FieldDeclaration fieldDeclaration, MethodScope scope); + void endVisit(FieldReference fieldReference, BlockScope scope); + void endVisit(FloatLiteral floatLiteral, BlockScope scope); + void endVisit(ForStatement forStatement, BlockScope scope); + void endVisit(IfStatement ifStatement, BlockScope scope); + void endVisit(ImportReference importRef, CompilationUnitScope scope); + void endVisit(Initializer initializer, MethodScope scope); + void endVisit(InstanceOfExpression instanceOfExpression, BlockScope scope); + void endVisit(IntLiteral intLiteral, BlockScope scope); + void endVisit(LabeledStatement labeledStatement, BlockScope scope); + void endVisit(LocalDeclaration localDeclaration, BlockScope scope); + void endVisit(LocalTypeDeclaration localTypeDeclaration, BlockScope scope); + void endVisit(LongLiteral longLiteral, BlockScope scope); + void endVisit(MemberTypeDeclaration memberTypeDeclaration, ClassScope scope); + void endVisit(MessageSend messageSend, BlockScope scope); + void endVisit(MethodDeclaration methodDeclaration, ClassScope scope); + void endVisit(NullLiteral nullLiteral, BlockScope scope); + void endVisit(OR_OR_Expression or_or_Expression, BlockScope scope); + void endVisit(PostfixExpression postfixExpression, BlockScope scope); + void endVisit(PrefixExpression prefixExpression, BlockScope scope); - void endVisit(QualifiedAllocationExpression qualifiedAllocationExpression, BlockScope scope); - void endVisit(QualifiedNameReference qualifiedNameReference, BlockScope scope); - void endVisit(QualifiedSuperReference qualifiedSuperReference, BlockScope scope); - void endVisit(QualifiedThisReference qualifiedThisReference, BlockScope scope); - void endVisit(QualifiedTypeReference qualifiedTypeReference, BlockScope scope); - void endVisit(QualifiedTypeReference qualifiedTypeReference, ClassScope scope); + + void endVisit(QualifiedAllocationExpression qualifiedAllocationExpression, + BlockScope scope); + + void endVisit(QualifiedNameReference qualifiedNameReference, + BlockScope scope); + + void endVisit(QualifiedSuperReference qualifiedSuperReference, + BlockScope scope); + + void endVisit(QualifiedThisReference qualifiedThisReference, + BlockScope scope); + + void endVisit(QualifiedTypeReference qualifiedTypeReference, + BlockScope scope); + + void endVisit(QualifiedTypeReference qualifiedTypeReference, + ClassScope scope); + void endVisit(ReturnStatement returnStatement, BlockScope scope); + void endVisit(SingleNameReference singleNameReference, BlockScope scope); + void endVisit(SingleTypeReference singleTypeReference, BlockScope scope); + void endVisit(SingleTypeReference singleTypeReference, ClassScope scope); + void endVisit(StringLiteral stringLiteral, BlockScope scope); + void endVisit(SuperReference superReference, BlockScope scope); + void endVisit(SwitchStatement switchStatement, BlockScope scope); -// void endVisit(SynchronizedStatement synchronizedStatement, BlockScope scope); + + // void endVisit(SynchronizedStatement synchronizedStatement, BlockScope + // scope); void endVisit(ThisReference thisReference, BlockScope scope); + void endVisit(ThrowStatement throwStatement, BlockScope scope); + void endVisit(TrueLiteral trueLiteral, BlockScope scope); + void endVisit(TryStatement tryStatement, BlockScope scope); + void endVisit(TypeDeclaration typeDeclaration, CompilationUnitScope scope); + void endVisit(UnaryExpression unaryExpression, BlockScope scope); + void endVisit(WhileStatement whileStatement, BlockScope scope); + boolean visit(AllocationExpression allocationExpression, BlockScope scope); + boolean visit(AND_AND_Expression and_and_Expression, BlockScope scope); - boolean visit(AnonymousLocalTypeDeclaration anonymousTypeDeclaration, BlockScope scope); + + boolean visit(AnonymousLocalTypeDeclaration anonymousTypeDeclaration, + BlockScope scope); + boolean visit(Argument argument, BlockScope scope); - boolean visit(ArrayAllocationExpression arrayAllocationExpression, BlockScope scope); + + boolean visit(ArrayAllocationExpression arrayAllocationExpression, + BlockScope scope); + boolean visit(ArrayInitializer arrayInitializer, BlockScope scope); - boolean visit(ArrayQualifiedTypeReference arrayQualifiedTypeReference, BlockScope scope); - boolean visit(ArrayQualifiedTypeReference arrayQualifiedTypeReference, ClassScope scope); + + boolean visit(ArrayQualifiedTypeReference arrayQualifiedTypeReference, + BlockScope scope); + + boolean visit(ArrayQualifiedTypeReference arrayQualifiedTypeReference, + ClassScope scope); + boolean visit(ArrayReference arrayReference, BlockScope scope); + boolean visit(ArrayTypeReference arrayTypeReference, BlockScope scope); + boolean visit(ArrayTypeReference arrayTypeReference, ClassScope scope); + boolean visit(AssertStatement assertStatement, BlockScope scope); + boolean visit(Assignment assignment, BlockScope scope); + boolean visit(BinaryExpression binaryExpression, BlockScope scope); + boolean visit(Block block, BlockScope scope); + boolean visit(BreakStatement breakStatement, BlockScope scope); + boolean visit(CaseStatement caseStatement, BlockScope scope); + boolean visit(CastExpression castExpression, BlockScope scope); -// boolean visit(CharLiteral charLiteral, BlockScope scope); -// boolean visit(ClassLiteralAccess classLiteral, BlockScope scope); + + // boolean visit(CharLiteral charLiteral, BlockScope scope); + // boolean visit(ClassLiteralAccess classLiteral, BlockScope scope); boolean visit(Clinit clinit, ClassScope scope); - boolean visit(CompilationUnitDeclaration compilationUnitDeclaration, CompilationUnitScope scope); + + boolean visit(CompilationUnitDeclaration compilationUnitDeclaration, + CompilationUnitScope scope); + boolean visit(CompoundAssignment compoundAssignment, BlockScope scope); + boolean visit(ConditionalExpression conditionalExpression, BlockScope scope); - boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope); + + boolean visit(ConstructorDeclaration constructorDeclaration, + ClassScope scope); + boolean visit(ContinueStatement continueStatement, BlockScope scope); + boolean visit(DefaultCase defaultCaseStatement, BlockScope scope); + boolean visit(DoStatement doStatement, BlockScope scope); + boolean visit(DoubleLiteral doubleLiteral, BlockScope scope); + boolean visit(EqualExpression equalExpression, BlockScope scope); + boolean visit(EmptyStatement statement, BlockScope scope); + boolean visit(ExplicitConstructorCall explicitConstructor, BlockScope scope); + boolean visit(ExtendedStringLiteral extendedStringLiteral, BlockScope scope); + boolean visit(FalseLiteral falseLiteral, BlockScope scope); + boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope); + boolean visit(FieldReference fieldReference, BlockScope scope); + boolean visit(FloatLiteral floatLiteral, BlockScope scope); + boolean visit(ForStatement forStatement, BlockScope scope); + boolean visit(IfStatement ifStatement, BlockScope scope); + boolean visit(ImportReference importRef, CompilationUnitScope scope); + boolean visit(Initializer initializer, MethodScope scope); + boolean visit(InstanceOfExpression instanceOfExpression, BlockScope scope); + boolean visit(IntLiteral intLiteral, BlockScope scope); + boolean visit(LabeledStatement labeledStatement, BlockScope scope); + boolean visit(LocalDeclaration localDeclaration, BlockScope scope); + boolean visit(LocalTypeDeclaration localTypeDeclaration, BlockScope scope); + boolean visit(LongLiteral longLiteral, BlockScope scope); + boolean visit(MemberTypeDeclaration memberTypeDeclaration, ClassScope scope); + boolean visit(MessageSend messageSend, BlockScope scope); + boolean visit(MethodDeclaration methodDeclaration, ClassScope scope); + boolean visit(NullLiteral nullLiteral, BlockScope scope); + boolean visit(OR_OR_Expression or_or_Expression, BlockScope scope); + boolean visit(PostfixExpression postfixExpression, BlockScope scope); + boolean visit(PrefixExpression prefixExpression, BlockScope scope); - boolean visit(QualifiedAllocationExpression qualifiedAllocationExpression, BlockScope scope); - boolean visit(QualifiedNameReference qualifiedNameReference, BlockScope scope); - boolean visit(QualifiedSuperReference qualifiedSuperReference, BlockScope scope); - boolean visit(QualifiedThisReference qualifiedThisReference, BlockScope scope); - boolean visit(QualifiedTypeReference qualifiedTypeReference, BlockScope scope); - boolean visit(QualifiedTypeReference qualifiedTypeReference, ClassScope scope); + + boolean visit(QualifiedAllocationExpression qualifiedAllocationExpression, + BlockScope scope); + + boolean visit(QualifiedNameReference qualifiedNameReference, + BlockScope scope); + + boolean visit(QualifiedSuperReference qualifiedSuperReference, + BlockScope scope); + + boolean visit(QualifiedThisReference qualifiedThisReference, + BlockScope scope); + + boolean visit(QualifiedTypeReference qualifiedTypeReference, + BlockScope scope); + + boolean visit(QualifiedTypeReference qualifiedTypeReference, + ClassScope scope); + boolean visit(ReturnStatement returnStatement, BlockScope scope); + boolean visit(SingleNameReference singleNameReference, BlockScope scope); + boolean visit(SingleTypeReference singleTypeReference, BlockScope scope); + boolean visit(SingleTypeReference singleTypeReference, ClassScope scope); + boolean visit(StringLiteral stringLiteral, BlockScope scope); + boolean visit(SuperReference superReference, BlockScope scope); + boolean visit(SwitchStatement switchStatement, BlockScope scope); -// boolean visit(SynchronizedStatement synchronizedStatement, BlockScope scope); + + // boolean visit(SynchronizedStatement synchronizedStatement, BlockScope + // scope); boolean visit(ThisReference thisReference, BlockScope scope); + boolean visit(ThrowStatement throwStatement, BlockScope scope); + boolean visit(TrueLiteral trueLiteral, BlockScope scope); + boolean visit(TryStatement tryStatement, BlockScope scope); + boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope); + boolean visit(UnaryExpression unaryExpression, BlockScope scope); + boolean visit(WhileStatement whileStatement, BlockScope scope); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ICompilerRequestor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ICompilerRequestor.java index b41a9b1..9450525 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ICompilerRequestor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ICompilerRequestor.java @@ -14,7 +14,7 @@ package net.sourceforge.phpdt.internal.compiler; * A callback interface for receiving compilation results. */ public interface ICompilerRequestor { - + /** * Accept a compilation result. */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/IDocumentElementRequestor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/IDocumentElementRequestor.java index 3308ae1..3c6e134 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/IDocumentElementRequestor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/IDocumentElementRequestor.java @@ -13,399 +13,462 @@ package net.sourceforge.phpdt.internal.compiler; import net.sourceforge.phpdt.core.compiler.IProblem; /** - * Part of the source element parser responsible for building the output. - * It gets notified of structural information as they are detected, relying - * on the requestor to assemble them together, based on the notifications it got. - * - * The structural investigation includes: - * - package statement - * - import statements - * - top-level types: package member, member types (member types of member types...) - * - fields - * - methods - * + * Part of the source element parser responsible for building the output. It + * gets notified of structural information as they are detected, relying on the + * requestor to assemble them together, based on the notifications it got. + * + * The structural investigation includes: - package statement - import + * statements - top-level types: package member, member types (member types of + * member types...) - fields - methods + * * If reference information is requested, then all source constructs are * investigated and type, field & method references are provided as well. - * + * * Any (parsing) problem encountered is also provided. - * + * * All positions are relative to the exact source fed to the parser. - * - * Elements which are complex are notified in two steps: - * - enter : once the element header has been identified - * - exit : once the element has been fully consumed - * - * other simpler elements (package, import) are read all at once: - * - accept - */ - -public interface IDocumentElementRequestor { -/** - * @param declarationStart - a source position corresponding to the start of the package - * declaration - * @param declarationEnd - a source position corresponding to the end of the package - * declaration - * @param javaDocPositions - answer back an array of sourceStart/sourceEnd - * positions of the available JavaDoc comments. The array is a flattened - * structure: 2*n entries with consecutives start and end positions. - * If no JavaDoc is available, then null is answered instead of an empty array. - * e.g. { 10, 20, 25, 45 } --> javadoc1 from 10 to 20, javadoc2 from 25 to 45 - * The array is equals to null if there are no javadoc comments - * @param name - the name of the package - * @param nameStartPosition - a source position corresponding to the first character of the - * name - * @param onDemand - a boolean equals to true if the import is an import on demand - */ -void acceptImport( - int declarationStart, - int declarationEnd, - int[] javaDocPositions, - char[] name, - int nameStartPosition, - boolean onDemand); -/** - * @param declarationStart - a source position corresponding to the start of the package - * declaration - * @param declarationEnd - a source position corresponding to the end of the package - * declaration - * @param javaDocPositions - answer back an array of sourceStart/sourceEnd - * positions of the available JavaDoc comments. The array is a flattened - * structure: 2*n entries with consecutives start and end positions. - * If no JavaDoc is available, then null is answered instead of an empty array. - * e.g. { 10, 20, 25, 45 } --> javadoc1 from 10 to 20, javadoc2 from 25 to 45 - * The array is equals to null if there are no javadoc comments - * @param modifiers - the modifiers for this initializer - * @param modifiersStart - a source position corresponding to the start - * of the textual modifiers, is < 0 if there are no textual modifiers - * @param bodyStart - the position of the '{' - * @param bodyEnd - the position of the '}' - */ -void acceptInitializer( - int declarationStart, - int declarationEnd, - int[] javaDocPositions, - int modifiers, - int modifiersStart, - int bodyStart, - int bodyEnd); -/* - * Table of line separator position. This table is passed once at the end - * of the parse action, so as to allow computation of normalized ranges. - * - * A line separator might corresponds to several characters in the source, * + * Elements which are complex are notified in two steps: - enter : + * once the element header has been identified - exit : once the + * element has been fully consumed + * + * other simpler elements (package, import) are read all at once: - accept */ -void acceptLineSeparatorPositions(int[] positions); -/** - * @param declarationStart - a source position corresponding to the start of the package - * declaration - * @param declarationEnd - a source position corresponding to the end of the package - * declaration - * @param javaDocPositions - answer back an array of sourceStart/sourceEnd - * positions of the available JavaDoc comments. The array is a flattened - * structure: 2*n entries with consecutives start and end positions. - * If no JavaDoc is available, then null is answered instead of an empty array. - * e.g. { 10, 20, 25, 45 } --> javadoc1 from 10 to 20, javadoc2 from 25 to 45 - * The array is equals to null if there are no javadoc comments - * @param name - the name of the package - * @param nameStartPosition - a source position corresponding to the first character of the - * name - */ -void acceptPackage( - int declarationStart, - int declarationEnd, - int[] javaDocPositions, - char[] name, - int nameStartPosition); -/** - * @param problem - Used to report a problem while running the JDOM - */ -void acceptProblem(IProblem problem); -/** - * @param declarationStart - a source position corresponding to the start - * of this class. - * @param javaDocPositions - answer back an array of sourceStart/sourceEnd - * positions of the available JavaDoc comments. The array is a flattened - * structure: 2*n entries with consecutives start and end positions. - * If no JavaDoc is available, then null is answered instead of an empty array. - * e.g. { 10, 20, 25, 45 } --> javadoc1 from 10 to 20, javadoc2 from 25 to 45 - * The array is equals to null if there are no javadoc comments - * @param modifiers - the modifiers for this class - * @param modifiersStart - a source position corresponding to the start - * of the textual modifiers, is < 0 if there are no textual modifiers - * @param classStart - a source position corresponding to the start - * of the keyword 'class' - * @param name - the name of the class - * @param nameStart - a source position corresponding to the start of the name - * @param nameEnd - a source position corresponding to the end of the name - * @param superclass - the name of the superclass - * @param superclassStart - a source position corresponding to the start - * of the superclass name - * @param superclassEnd - a source position corresponding to the end of the - * superclass name - * @param superinterfaces - the name of the superinterfaces - * @param superinterfaceStarts - an array of source positions corresponding - * to the start of their respective superinterface names - * @param superinterfaceEnds - an array of source positions corresponding - * to the end of their respective superinterface names - * @param bodyStart - a source position corresponding to the open bracket - * of the class body - */ -void enterClass( - int declarationStart, - int[] javaDocPositions, - int modifiers, - int modifiersStart, - int classStart, - char[] name, - int nameStart, - int nameEnd, - char[] superclass, - int superclassStart, - int superclassEnd, - char[][] superinterfaces, - int[] superinterfaceStarts, - int[] superinterfaceEnds, - int bodyStart); -void enterCompilationUnit(); -/** - * @param declarationStart - a source position corresponding to the first character - * of this constructor declaration - * @param javaDocPositions - answer back an array of sourceStart/sourceEnd - * positions of the available JavaDoc comments. The array is a flattened - * structure: 2*n entries with consecutives start and end positions. - * If no JavaDoc is available, then null is answered instead of an empty array. - * e.g. { 10, 20, 25, 45 } --> javadoc1 from 10 to 20, javadoc2 from 25 to 45 - * The array is equals to null if there are no javadoc comments - * @param modifiers - the modifiers for this constructor converted to a flag - * @param modifiersStart - a source position corresponding to the first character of the - * textual modifiers - * @param name - the name of this constructor - * @param nameStart - a source position corresponding to the first character of the name - * @param nameEnd - a source position corresponding to the last character of the name - * @param parameterTypes - a list of parameter type names - * @param parameterTypeStarts - a list of source positions corresponding to the - * first character of each parameter type name - * @param parameterTypeEnds - a list of source positions corresponding to the - * last character of each parameter type name - * @param parameterNames - a list of the names of the parameters - * @param parametersEnd - a source position corresponding to the last character of the - * parameter list - * @param exceptionTypes - a list of the exception types - * @param exceptionTypeStarts - a list of source positions corresponding to the first - * character of the respective exception types - * @param exceptionTypeEnds - a list of source positions corresponding to the last - * character of the respective exception types - * @param bodyStart - a source position corresponding to the start of this - * constructor's body - */ -void enterConstructor( - int declarationStart, - int[] javaDocPositions, - int modifiers, - int modifiersStart, - char[] name, - int nameStart, - int nameEnd, - char[][] parameterTypes, - int [] parameterTypeStarts, - int [] parameterTypeEnds, - char[][] parameterNames, - int [] parameterNameStarts, - int [] parameterNameEnds, - int parametersEnd, - char[][] exceptionTypes, - int [] exceptionTypeStarts, - int [] exceptionTypeEnds, - int bodyStart); -/** - * @param declarationStart - a source position corresponding to the first character - * of this field - * @param javaDocPositions - answer back an array of sourceStart/sourceEnd - * positions of the available JavaDoc comments. The array is a flattened - * structure: 2*n entries with consecutives start and end positions. - * If no JavaDoc is available, then null is answered instead of an empty array. - * e.g. { 10, 20, 25, 45 } --> javadoc1 from 10 to 20, javadoc2 from 25 to 45 - * The array is equals to null if there are no javadoc comments - * @param modifiers - the modifiers for this field converted to a flag - * @param modifiersStart - a source position corresponding to the first character of the - * textual modifiers - * @param type - the name of the field type - * @param typeStart - a source position corresponding to the start of the fields type - * @param typeEnd - a source position corresponding to the end of the fields type - * @param typeDimensionCount - the array dimension indicated on the type (for example, 'int[] v') - * @param name - the name of this constructor - * @param nameStart - a source position corresponding to the first character of the name - * @param nameEnd - a source position corresponding to the last character of the name - * @param extendedTypeDimensionCount - the array dimension indicated on the variable, - * (for example, 'int v[]') - * @param extendedTypeDimnesionEnd - a source position corresponding to the end of - * the extened type dimension. This position should be -1 in case there is no extended - * dimension for the type. - */ -void enterField( - int declarationStart, - int[] javaDocPositions, - int modifiers, - int modifiersStart, - char[] type, - int typeStart, - int typeEnd, - int typeDimensionCount, - char[] name, - int nameStart, - int nameEnd, - int extendedTypeDimensionCount, - int extendedTypeDimensionEnd); -/** - * @param declarationStart - a source position corresponding to the start - * of this class. - * @param javaDocPositions - answer back an array of sourceStart/sourceEnd - * positions of the available JavaDoc comments. The array is a flattened - * structure: 2*n entries with consecutives start and end positions. - * If no JavaDoc is available, then null is answered instead of an empty array. - * e.g. { 10, 20, 25, 45 } --> javadoc1 from 10 to 20, javadoc2 from 25 to 45 - * The array is equals to null if there are no javadoc comments - * @param modifiers - the modifiers for this class - * @param modifiersStart - a source position corresponding to the start - * of the textual modifiers, is < 0 if there are no textual modifiers - * @param interfaceStart - a source position corresponding to the start - * of the keyword 'interface' - * @param name - the name of the class - * @param nameStart - a source position corresponding to the start of the name - * @param nameEnd - a source position corresponding to the end of the name - * @param superinterfaces - the name of the superinterfaces - * @param superinterfaceStarts - an array of source positions corresponding - * to the start of their respective superinterface names - * @param superinterfaceEnds - an array of source positions corresponding - * to the end of their respective superinterface names - * @param bodyStart - a source position corresponding to the open bracket - * of the class body - */ -void enterInterface( - int declarationStart, - int[] javaDocPositions, - int modifiers, - int modifiersStart, - int interfaceStart, - char[] name, - int nameStart, - int nameEnd, - char[][] superinterfaces, - int[] superinterfaceStarts, - int[] superinterfaceEnds, - int bodyStart); -/** - * @param declarationStart - a source position corresponding to the first character - * of this constructor declaration - * @param javaDocPositions - answer back an array of sourceStart/sourceEnd - * positions of the available JavaDoc comments. The array is a flattened - * structure: 2*n entries with consecutives start and end positions. - * If no JavaDoc is available, then null is answered instead of an empty array. - * e.g. { 10, 20, 25, 45 } --> javadoc1 from 10 to 20, javadoc2 from 25 to 45 - * The array is equals to null if there are no javadoc comments - * @param modifiers - the modifiers for this constructor converted to a flag - * @param modifiersStart - a source position corresponding to the first character of the - * textual modifiers - * @param returnType - the name of the return type - * @param returnTypeStart - a source position corresponding to the first character - * of the return type - * @param returnTypeEnd - a source position corresponding to the last character - * of the return type - * @param returnTypeDimensionCount - the array dimension count as supplied on the - * return type (for example, 'public int[] foo() {}') - * @param name - the name of this constructor - * @param nameStart - a source position corresponding to the first character of the name - * @param nameEnd - a source position corresponding to the last character of the name - * @param parameterTypes - a list of parameter type names - * @param parameterTypeStarts - a list of source positions corresponding to the - * first character of each parameter type name - * @param parameterTypeEnds - a list of source positions corresponding to the - * last character of each parameter type name - * @param parameterNames - a list of the names of the parameters - * @param parametersEnd - a source position corresponding to the last character of the - * parameter list - * @param extendedReturnTypeDimensionCount - the array dimension count as supplied on the - * end of the parameter list (for example, 'public int foo()[] {}') - * @param extendedReturnTypeDimensionEnd - a source position corresponding to the last character - * of the extended return type dimension. This position should be -1 in case there is no extended - * dimension for the type. - * @param exceptionTypes - a list of the exception types - * @param exceptionTypeStarts - a list of source positions corresponding to the first - * character of the respective exception types - * @param exceptionTypeEnds - a list of source positions corresponding to the last - * character of the respective exception types - * @param bodyStart - a source position corresponding to the start of this - * method's body - */ -void enterMethod( - int declarationStart, - int[] javaDocPositions, - int modifiers, - int modifiersStart, - char[] returnType, - int returnTypeStart, - int returnTypeEnd, - int returnTypeDimensionCount, - char[] name, - int nameStart, - int nameEnd, - char[][] parameterTypes, - int [] parameterTypeStarts, - int [] parameterTypeEnds, - char[][] parameterNames, - int [] parameterNameStarts, - int [] parameterNameEnds, - int parametersEnd, - int extendedReturnTypeDimensionCount, - int extendedReturnTypeDimensionEnd, - char[][] exceptionTypes, - int [] exceptionTypeStarts, - int [] exceptionTypeEnds, - int bodyStart); -/** - * @param bodyEnd - a source position corresponding to the closing bracket of the class - * @param declarationEnd - a source position corresponding to the end of the class - * declaration. This can include whitespace and comments following the closing bracket. - */ -void exitClass( - int bodyEnd, - int declarationEnd); -/** - * @param declarationEnd - a source position corresponding to the end of the compilation unit - */ -void exitCompilationUnit( - int declarationEnd); -/** - * @param bodyEnd - a source position corresponding to the closing bracket of the method - * @param declarationEnd - a source position corresponding to the end of the method - * declaration. This can include whitespace and comments following the closing bracket. - */ -void exitConstructor( - int bodyEnd, - int declarationEnd); -/** - * @param bodyEnd - a source position corresponding to the end of the field. - * @param declarationEnd - a source position corresponding to the end of the field. - * This can include whitespace and comments following the semi-colon. - */ -void exitField( - int bodyEnd, - int declarationEnd); -/** - * @param bodyEnd - a source position corresponding to the closing bracket of the interface - * @param declarationEnd - a source position corresponding to the end of the interface - * declaration. This can include whitespace and comments following the closing bracket. - */ -void exitInterface( - int bodyEnd, - int declarationEnd); -/** - * @param bodyEnd - a source position corresponding to the closing bracket of the method - * @param declarationEnd - a source position corresponding to the end of the method - * declaration. This can include whitespace and comments following the closing bracket. - */ -void exitMethod( - int bodyEnd, - int declarationEnd); + +public interface IDocumentElementRequestor { + /** + * @param declarationStart - + * a source position corresponding to the start of the package + * declaration + * @param declarationEnd - + * a source position corresponding to the end of the package + * declaration + * @param javaDocPositions - + * answer back an array of sourceStart/sourceEnd positions of the + * available JavaDoc comments. The array is a flattened + * structure: 2*n entries with consecutives start and end + * positions. If no JavaDoc is available, then null is answered + * instead of an empty array. e.g. { 10, 20, 25, 45 } --> + * javadoc1 from 10 to 20, javadoc2 from 25 to 45 The array is + * equals to null if there are no javadoc comments + * @param name - + * the name of the package + * @param nameStartPosition - + * a source position corresponding to the first character of the + * name + * @param onDemand - + * a boolean equals to true if the import is an import on demand + */ + void acceptImport(int declarationStart, int declarationEnd, + int[] javaDocPositions, char[] name, int nameStartPosition, + boolean onDemand); + + /** + * @param declarationStart - + * a source position corresponding to the start of the package + * declaration + * @param declarationEnd - + * a source position corresponding to the end of the package + * declaration + * @param javaDocPositions - + * answer back an array of sourceStart/sourceEnd positions of the + * available JavaDoc comments. The array is a flattened + * structure: 2*n entries with consecutives start and end + * positions. If no JavaDoc is available, then null is answered + * instead of an empty array. e.g. { 10, 20, 25, 45 } --> + * javadoc1 from 10 to 20, javadoc2 from 25 to 45 The array is + * equals to null if there are no javadoc comments + * @param modifiers - + * the modifiers for this initializer + * @param modifiersStart - + * a source position corresponding to the start of the textual + * modifiers, is < 0 if there are no textual modifiers + * @param bodyStart - + * the position of the '{' + * @param bodyEnd - + * the position of the '}' + */ + void acceptInitializer(int declarationStart, int declarationEnd, + int[] javaDocPositions, int modifiers, int modifiersStart, + int bodyStart, int bodyEnd); + + /* + * Table of line separator position. This table is passed once at the end of + * the parse action, so as to allow computation of normalized ranges. + * + * A line separator might corresponds to several characters in the source, + * + */ + void acceptLineSeparatorPositions(int[] positions); + + /** + * @param declarationStart - + * a source position corresponding to the start of the package + * declaration + * @param declarationEnd - + * a source position corresponding to the end of the package + * declaration + * @param javaDocPositions - + * answer back an array of sourceStart/sourceEnd positions of the + * available JavaDoc comments. The array is a flattened + * structure: 2*n entries with consecutives start and end + * positions. If no JavaDoc is available, then null is answered + * instead of an empty array. e.g. { 10, 20, 25, 45 } --> + * javadoc1 from 10 to 20, javadoc2 from 25 to 45 The array is + * equals to null if there are no javadoc comments + * @param name - + * the name of the package + * @param nameStartPosition - + * a source position corresponding to the first character of the + * name + */ + void acceptPackage(int declarationStart, int declarationEnd, + int[] javaDocPositions, char[] name, int nameStartPosition); + + /** + * @param problem - + * Used to report a problem while running the JDOM + */ + void acceptProblem(IProblem problem); + + /** + * @param declarationStart - + * a source position corresponding to the start of this class. + * @param javaDocPositions - + * answer back an array of sourceStart/sourceEnd positions of the + * available JavaDoc comments. The array is a flattened + * structure: 2*n entries with consecutives start and end + * positions. If no JavaDoc is available, then null is answered + * instead of an empty array. e.g. { 10, 20, 25, 45 } --> + * javadoc1 from 10 to 20, javadoc2 from 25 to 45 The array is + * equals to null if there are no javadoc comments + * @param modifiers - + * the modifiers for this class + * @param modifiersStart - + * a source position corresponding to the start of the textual + * modifiers, is < 0 if there are no textual modifiers + * @param classStart - + * a source position corresponding to the start of the keyword + * 'class' + * @param name - + * the name of the class + * @param nameStart - + * a source position corresponding to the start of the name + * @param nameEnd - + * a source position corresponding to the end of the name + * @param superclass - + * the name of the superclass + * @param superclassStart - + * a source position corresponding to the start of the superclass + * name + * @param superclassEnd - + * a source position corresponding to the end of the superclass + * name + * @param superinterfaces - + * the name of the superinterfaces + * @param superinterfaceStarts - + * an array of source positions corresponding to the start of + * their respective superinterface names + * @param superinterfaceEnds - + * an array of source positions corresponding to the end of their + * respective superinterface names + * @param bodyStart - + * a source position corresponding to the open bracket of the + * class body + */ + void enterClass(int declarationStart, int[] javaDocPositions, + int modifiers, int modifiersStart, int classStart, char[] name, + int nameStart, int nameEnd, char[] superclass, int superclassStart, + int superclassEnd, char[][] superinterfaces, + int[] superinterfaceStarts, int[] superinterfaceEnds, int bodyStart); + + void enterCompilationUnit(); + + /** + * @param declarationStart - + * a source position corresponding to the first character of this + * constructor declaration + * @param javaDocPositions - + * answer back an array of sourceStart/sourceEnd positions of the + * available JavaDoc comments. The array is a flattened + * structure: 2*n entries with consecutives start and end + * positions. If no JavaDoc is available, then null is answered + * instead of an empty array. e.g. { 10, 20, 25, 45 } --> + * javadoc1 from 10 to 20, javadoc2 from 25 to 45 The array is + * equals to null if there are no javadoc comments + * @param modifiers - + * the modifiers for this constructor converted to a flag + * @param modifiersStart - + * a source position corresponding to the first character of the + * textual modifiers + * @param name - + * the name of this constructor + * @param nameStart - + * a source position corresponding to the first character of the + * name + * @param nameEnd - + * a source position corresponding to the last character of the + * name + * @param parameterTypes - + * a list of parameter type names + * @param parameterTypeStarts - + * a list of source positions corresponding to the first + * character of each parameter type name + * @param parameterTypeEnds - + * a list of source positions corresponding to the last character + * of each parameter type name + * @param parameterNames - + * a list of the names of the parameters + * @param parametersEnd - + * a source position corresponding to the last character of the + * parameter list + * @param exceptionTypes - + * a list of the exception types + * @param exceptionTypeStarts - + * a list of source positions corresponding to the first + * character of the respective exception types + * @param exceptionTypeEnds - + * a list of source positions corresponding to the last character + * of the respective exception types + * @param bodyStart - + * a source position corresponding to the start of this + * constructor's body + */ + void enterConstructor(int declarationStart, int[] javaDocPositions, + int modifiers, int modifiersStart, char[] name, int nameStart, + int nameEnd, char[][] parameterTypes, int[] parameterTypeStarts, + int[] parameterTypeEnds, char[][] parameterNames, + int[] parameterNameStarts, int[] parameterNameEnds, + int parametersEnd, char[][] exceptionTypes, + int[] exceptionTypeStarts, int[] exceptionTypeEnds, int bodyStart); + + /** + * @param declarationStart - + * a source position corresponding to the first character of this + * field + * @param javaDocPositions - + * answer back an array of sourceStart/sourceEnd positions of the + * available JavaDoc comments. The array is a flattened + * structure: 2*n entries with consecutives start and end + * positions. If no JavaDoc is available, then null is answered + * instead of an empty array. e.g. { 10, 20, 25, 45 } --> + * javadoc1 from 10 to 20, javadoc2 from 25 to 45 The array is + * equals to null if there are no javadoc comments + * @param modifiers - + * the modifiers for this field converted to a flag + * @param modifiersStart - + * a source position corresponding to the first character of the + * textual modifiers + * @param type - + * the name of the field type + * @param typeStart - + * a source position corresponding to the start of the fields + * type + * @param typeEnd - + * a source position corresponding to the end of the fields type + * @param typeDimensionCount - + * the array dimension indicated on the type (for example, 'int[] + * v') + * @param name - + * the name of this constructor + * @param nameStart - + * a source position corresponding to the first character of the + * name + * @param nameEnd - + * a source position corresponding to the last character of the + * name + * @param extendedTypeDimensionCount - + * the array dimension indicated on the variable, (for example, + * 'int v[]') + * @param extendedTypeDimnesionEnd - + * a source position corresponding to the end of the extened type + * dimension. This position should be -1 in case there is no + * extended dimension for the type. + */ + void enterField(int declarationStart, int[] javaDocPositions, + int modifiers, int modifiersStart, char[] type, int typeStart, + int typeEnd, int typeDimensionCount, char[] name, int nameStart, + int nameEnd, int extendedTypeDimensionCount, + int extendedTypeDimensionEnd); + + /** + * @param declarationStart - + * a source position corresponding to the start of this class. + * @param javaDocPositions - + * answer back an array of sourceStart/sourceEnd positions of the + * available JavaDoc comments. The array is a flattened + * structure: 2*n entries with consecutives start and end + * positions. If no JavaDoc is available, then null is answered + * instead of an empty array. e.g. { 10, 20, 25, 45 } --> + * javadoc1 from 10 to 20, javadoc2 from 25 to 45 The array is + * equals to null if there are no javadoc comments + * @param modifiers - + * the modifiers for this class + * @param modifiersStart - + * a source position corresponding to the start of the textual + * modifiers, is < 0 if there are no textual modifiers + * @param interfaceStart - + * a source position corresponding to the start of the keyword + * 'interface' + * @param name - + * the name of the class + * @param nameStart - + * a source position corresponding to the start of the name + * @param nameEnd - + * a source position corresponding to the end of the name + * @param superinterfaces - + * the name of the superinterfaces + * @param superinterfaceStarts - + * an array of source positions corresponding to the start of + * their respective superinterface names + * @param superinterfaceEnds - + * an array of source positions corresponding to the end of their + * respective superinterface names + * @param bodyStart - + * a source position corresponding to the open bracket of the + * class body + */ + void enterInterface(int declarationStart, int[] javaDocPositions, + int modifiers, int modifiersStart, int interfaceStart, char[] name, + int nameStart, int nameEnd, char[][] superinterfaces, + int[] superinterfaceStarts, int[] superinterfaceEnds, int bodyStart); + + /** + * @param declarationStart - + * a source position corresponding to the first character of this + * constructor declaration + * @param javaDocPositions - + * answer back an array of sourceStart/sourceEnd positions of the + * available JavaDoc comments. The array is a flattened + * structure: 2*n entries with consecutives start and end + * positions. If no JavaDoc is available, then null is answered + * instead of an empty array. e.g. { 10, 20, 25, 45 } --> + * javadoc1 from 10 to 20, javadoc2 from 25 to 45 The array is + * equals to null if there are no javadoc comments + * @param modifiers - + * the modifiers for this constructor converted to a flag + * @param modifiersStart - + * a source position corresponding to the first character of the + * textual modifiers + * @param returnType - + * the name of the return type + * @param returnTypeStart - + * a source position corresponding to the first character of the + * return type + * @param returnTypeEnd - + * a source position corresponding to the last character of the + * return type + * @param returnTypeDimensionCount - + * the array dimension count as supplied on the return type (for + * example, 'public int[] foo() {}') + * @param name - + * the name of this constructor + * @param nameStart - + * a source position corresponding to the first character of the + * name + * @param nameEnd - + * a source position corresponding to the last character of the + * name + * @param parameterTypes - + * a list of parameter type names + * @param parameterTypeStarts - + * a list of source positions corresponding to the first + * character of each parameter type name + * @param parameterTypeEnds - + * a list of source positions corresponding to the last character + * of each parameter type name + * @param parameterNames - + * a list of the names of the parameters + * @param parametersEnd - + * a source position corresponding to the last character of the + * parameter list + * @param extendedReturnTypeDimensionCount - + * the array dimension count as supplied on the end of the + * parameter list (for example, 'public int foo()[] {}') + * @param extendedReturnTypeDimensionEnd - + * a source position corresponding to the last character of the + * extended return type dimension. This position should be -1 in + * case there is no extended dimension for the type. + * @param exceptionTypes - + * a list of the exception types + * @param exceptionTypeStarts - + * a list of source positions corresponding to the first + * character of the respective exception types + * @param exceptionTypeEnds - + * a list of source positions corresponding to the last character + * of the respective exception types + * @param bodyStart - + * a source position corresponding to the start of this method's + * body + */ + void enterMethod(int declarationStart, int[] javaDocPositions, + int modifiers, int modifiersStart, char[] returnType, + int returnTypeStart, int returnTypeEnd, + int returnTypeDimensionCount, char[] name, int nameStart, + int nameEnd, char[][] parameterTypes, int[] parameterTypeStarts, + int[] parameterTypeEnds, char[][] parameterNames, + int[] parameterNameStarts, int[] parameterNameEnds, + int parametersEnd, int extendedReturnTypeDimensionCount, + int extendedReturnTypeDimensionEnd, char[][] exceptionTypes, + int[] exceptionTypeStarts, int[] exceptionTypeEnds, int bodyStart); + + /** + * @param bodyEnd - + * a source position corresponding to the closing bracket of the + * class + * @param declarationEnd - + * a source position corresponding to the end of the class + * declaration. This can include whitespace and comments + * following the closing bracket. + */ + void exitClass(int bodyEnd, int declarationEnd); + + /** + * @param declarationEnd - + * a source position corresponding to the end of the compilation + * unit + */ + void exitCompilationUnit(int declarationEnd); + + /** + * @param bodyEnd - + * a source position corresponding to the closing bracket of the + * method + * @param declarationEnd - + * a source position corresponding to the end of the method + * declaration. This can include whitespace and comments + * following the closing bracket. + */ + void exitConstructor(int bodyEnd, int declarationEnd); + + /** + * @param bodyEnd - + * a source position corresponding to the end of the field. + * @param declarationEnd - + * a source position corresponding to the end of the field. This + * can include whitespace and comments following the semi-colon. + */ + void exitField(int bodyEnd, int declarationEnd); + + /** + * @param bodyEnd - + * a source position corresponding to the closing bracket of the + * interface + * @param declarationEnd - + * a source position corresponding to the end of the interface + * declaration. This can include whitespace and comments + * following the closing bracket. + */ + void exitInterface(int bodyEnd, int declarationEnd); + + /** + * @param bodyEnd - + * a source position corresponding to the closing bracket of the + * method + * @param declarationEnd - + * a source position corresponding to the end of the method + * declaration. This can include whitespace and comments + * following the closing bracket. + */ + void exitMethod(int bodyEnd, int declarationEnd); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/IErrorHandlingPolicy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/IErrorHandlingPolicy.java index 48d74b8..6e39789 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/IErrorHandlingPolicy.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/IErrorHandlingPolicy.java @@ -11,18 +11,17 @@ package net.sourceforge.phpdt.internal.compiler; /* - * Handler policy is responsible to answer the 2 following - * questions: - * 1. should the handler stop on first problem which appears - * to be a real error (that is, not a warning), - * 2. should it proceed once it has gathered all problems - * - * The intent is that one can supply its own policy to implement - * some interactive error handling strategy where some UI would - * display problems and ask user if he wants to proceed or not. + * Handler policy is responsible to answer the 2 following questions: 1. should + * the handler stop on first problem which appears to be a real error (that is, + * not a warning), 2. should it proceed once it has gathered all problems + * + * The intent is that one can supply its own policy to implement some + * interactive error handling strategy where some UI would display problems and + * ask user if he wants to proceed or not. */ public interface IErrorHandlingPolicy { boolean proceedOnErrors(); + boolean stopOnFirstError(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/IProblemFactory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/IProblemFactory.java index bc424f7..e6d3a69 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/IProblemFactory.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/IProblemFactory.java @@ -14,30 +14,26 @@ import java.util.Locale; import net.sourceforge.phpdt.core.compiler.IProblem; - - /* - * Factory used from inside the compiler to build the actual problems - * which are handed back in the compilation result. - * + * Factory used from inside the compiler to build the actual problems which are + * handed back in the compilation result. + * * This allows sharing the internal problem representation with the environment. - * - * Note: The factory is responsible for computing and storing a localized error message. + * + * Note: The factory is responsible for computing and storing a localized error + * message. */ public interface IProblemFactory { - IProblem createProblem( - char[] originatingFileName, - int problemId, - String[] problemArguments, - String[] messageArguments, // shorter versions of the problemArguments - int severity, - int startPosition, - int endPosition, - int lineNumber); - + IProblem createProblem(char[] originatingFileName, int problemId, + String[] problemArguments, String[] messageArguments, // shorter + // versions + // of the + // problemArguments + int severity, int startPosition, int endPosition, int lineNumber); + Locale getLocale(); - + String getLocalizedMessage(int problemId, String[] messageArguments); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ISourceElementRequestor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ISourceElementRequestor.java index 58c2541..2d1e256 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ISourceElementRequestor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ISourceElementRequestor.java @@ -13,115 +13,116 @@ package net.sourceforge.phpdt.internal.compiler; import net.sourceforge.phpdt.core.compiler.IProblem; /* - * Part of the source element parser responsible for building the output. - * It gets notified of structural information as they are detected, relying - * on the requestor to assemble them together, based on the notifications it got. - * - * The structural investigation includes: - * - package statement - * - import statements - * - top-level types: package member, member types (member types of member types...) - * - fields - * - methods - * + * Part of the source element parser responsible for building the output. It + * gets notified of structural information as they are detected, relying on the + * requestor to assemble them together, based on the notifications it got. + * + * The structural investigation includes: - package statement - import + * statements - top-level types: package member, member types (member types of + * member types...) - fields - methods + * * If reference information is requested, then all source constructs are * investigated and type, field & method references are provided as well. - * + * * Any (parsing) problem encountered is also provided. - * + * * All positions are relative to the exact source fed to the parser. - * - * Elements which are complex are notified in two steps: - * - enter : once the element header has been identified - * - exit : once the element has been fully consumed - * - * other simpler elements (package, import) are read all at once: - * - accept + * + * Elements which are complex are notified in two steps: - enter : + * once the element header has been identified - exit : once the + * element has been fully consumed + * + * other simpler elements (package, import) are read all at once: - accept */ public interface ISourceElementRequestor { - void acceptConstructorReference(char[] typeName, int argCount, int sourcePosition); - //void acceptFieldReference(char[] fieldName, int sourcePosition); - /** - * @param declarationStart This is the position of the first character of the - * import keyword. - * @param declarationEnd This is the position of the ';' ending the import statement - * or the end of the comment following the import. - * @param name This is the name of the import like specified in the source including the dots. The '.*' - * is never included in the name. - * @param onDemand set to true if the import is an import on demand (e.g. import java.io.*). False otherwise. - */ - void acceptImport( - int declarationStart, - int declarationEnd, - char[] name, - boolean onDemand); - /* - * Table of line separator position. This table is passed once at the end - * of the parse action, so as to allow computation of normalized ranges. - * - * A line separator might corresponds to several characters in the source, - * - */ - void acceptLineSeparatorPositions(int[] positions); - void acceptMethodReference(char[] methodName, int argCount, int sourcePosition); - //void acceptPackage( - // int declarationStart, - // int declarationEnd, - // char[] name); - void acceptProblem(IProblem problem); - void acceptTypeReference(char[][] typeName, int sourceStart, int sourceEnd); - void acceptTypeReference(char[] typeName, int sourcePosition); - void acceptUnknownReference(char[][] name, int sourceStart, int sourceEnd); - void acceptUnknownReference(char[] name, int sourcePosition); - void enterClass( - int declarationStart, - int modifiers, - char[] name, - int nameSourceStart, - int nameSourceEnd, - char[] superclass, - char[][] superinterfaces); - void enterCompilationUnit(); - void enterConstructor( - int declarationStart, - int modifiers, - char[] name, - int nameSourceStart, - int nameSourceEnd, - char[][] parameterTypes, - char[][] parameterNames, - char[][] exceptionTypes); - void enterField(int declarationStart, int modifiers, char[] type, char[] name, int nameSourceStart, int nameSourceEnd); - //void enterInitializer( - // int declarationStart, - // int modifiers); - void enterInterface( - int declarationStart, - int modifiers, - char[] name, - int nameSourceStart, - int nameSourceEnd, - char[][] superinterfaces); - void enterMethod( - int declarationStart, - int modifiers, - char[] returnType, - char[] name, - int nameSourceStart, - int nameSourceEnd, - char[][] parameterTypes, - char[][] parameterNames, - char[][] exceptionTypes); - void exitClass(int declarationEnd); - void exitCompilationUnit(int declarationEnd); - void exitConstructor(int declarationEnd); - /* - * initializationStart denotes the source start of the expression used for initializing - * the field if any (-1 if no initialization). - */ - void exitField(int initializationStart, int declarationEnd, int declarationSourceEnd); - void exitInitializer(int declarationEnd); - void exitInterface(int declarationEnd); - void exitMethod(int declarationEnd); + void acceptConstructorReference(char[] typeName, int argCount, + int sourcePosition); + + // void acceptFieldReference(char[] fieldName, int sourcePosition); + /** + * @param declarationStart + * This is the position of the first character of the import + * keyword. + * @param declarationEnd + * This is the position of the ';' ending the import statement or + * the end of the comment following the import. + * @param name + * This is the name of the import like specified in the source + * including the dots. The '.*' is never included in the name. + * @param onDemand + * set to true if the import is an import on demand (e.g. import + * java.io.*). False otherwise. + */ + void acceptImport(int declarationStart, int declarationEnd, char[] name, + boolean onDemand); + + /* + * Table of line separator position. This table is passed once at the end of + * the parse action, so as to allow computation of normalized ranges. + * + * A line separator might corresponds to several characters in the source, + * + */ + void acceptLineSeparatorPositions(int[] positions); + + void acceptMethodReference(char[] methodName, int argCount, + int sourcePosition); + + // void acceptPackage( + // int declarationStart, + // int declarationEnd, + // char[] name); + void acceptProblem(IProblem problem); + + void acceptTypeReference(char[][] typeName, int sourceStart, int sourceEnd); + + void acceptTypeReference(char[] typeName, int sourcePosition); + + void acceptUnknownReference(char[][] name, int sourceStart, int sourceEnd); + + void acceptUnknownReference(char[] name, int sourcePosition); + + void enterClass(int declarationStart, int modifiers, char[] name, + int nameSourceStart, int nameSourceEnd, char[] superclass, + char[][] superinterfaces); + + void enterCompilationUnit(); + + void enterConstructor(int declarationStart, int modifiers, char[] name, + int nameSourceStart, int nameSourceEnd, char[][] parameterTypes, + char[][] parameterNames, char[][] exceptionTypes); + + void enterField(int declarationStart, int modifiers, char[] type, + char[] name, int nameSourceStart, int nameSourceEnd); + + // void enterInitializer( + // int declarationStart, + // int modifiers); + void enterInterface(int declarationStart, int modifiers, char[] name, + int nameSourceStart, int nameSourceEnd, char[][] superinterfaces); + + void enterMethod(int declarationStart, int modifiers, char[] returnType, + char[] name, int nameSourceStart, int nameSourceEnd, + char[][] parameterTypes, char[][] parameterNames, + char[][] exceptionTypes); + + void exitClass(int declarationEnd); + + void exitCompilationUnit(int declarationEnd); + + void exitConstructor(int declarationEnd); + + /* + * initializationStart denotes the source start of the expression used for + * initializing the field if any (-1 if no initialization). + */ + void exitField(int initializationStart, int declarationEnd, + int declarationSourceEnd); + + void exitInitializer(int declarationEnd); + + void exitInterface(int declarationEnd); + + void exitMethod(int declarationEnd); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/SourceElementParser.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/SourceElementParser.java index b7dda3f..c120843 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/SourceElementParser.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/SourceElementParser.java @@ -39,1297 +39,1404 @@ import net.sourceforge.phpdt.internal.compiler.problem.ProblemReporter; import net.sourceforge.phpdt.internal.core.util.CommentRecorderParser; /** - * A source element parser extracts structural and reference information - * from a piece of source. - * - * also see @ISourceElementRequestor - * - * The structural investigation includes: - * - the package statement - * - import statements - * - top-level types: package member, member types (member types of member types...) - * - fields - * - methods - * + * A source element parser extracts structural and reference information from a + * piece of source. + * + * also see + * + * @ISourceElementRequestor + * + * The structural investigation includes: - the package statement - import + * statements - top-level types: package member, member types (member types of + * member types...) - fields - methods + * * If reference information is requested, then all source constructs are * investigated and type, field & method references are provided as well. - * + * * Any (parsing) problem encountered is also provided. */ -public class SourceElementParser extends CommentRecorderParser {//extends - // UnitParser { +public class SourceElementParser extends CommentRecorderParser {// extends + // UnitParser { + + ISourceElementRequestor requestor; + + int fieldCount; + + int localIntPtr; + + int lastFieldEndPosition; + + ISourceType sourceType; + + boolean reportReferenceInfo; + + char[][] typeNames; + + char[][] superTypeNames; + + int nestedTypeIndex; + + static final char[] JAVA_LANG_OBJECT = "java.lang.Object".toCharArray(); //$NON-NLS-1$ + + NameReference[] unknownRefs; + + int unknownRefsCounter; + + LocalDeclarationVisitor localDeclarationVisitor = null; + + // CompilerOptions options; + + /** + * An ast visitor that visits local type declarations. + */ + public class LocalDeclarationVisitor extends ASTVisitor { + public boolean visit(TypeDeclaration typeDeclaration, BlockScope scope) { + notifySourceElementRequestor(typeDeclaration, sourceType == null); + return false; // don't visit members as this was done during + // notifySourceElementRequestor(...) + } + + public boolean visit(TypeDeclaration typeDeclaration, ClassScope scope) { + notifySourceElementRequestor(typeDeclaration, sourceType == null); + return false; // don't visit members as this was done during + // notifySourceElementRequestor(...) + } + + } + + public SourceElementParser(final ISourceElementRequestor requestor, + IProblemFactory problemFactory, CompilerOptions options) { + // we want to notify all syntax error with the acceptProblem API + // To do so, we define the record method of the ProblemReporter + super(new ProblemReporter(DefaultErrorHandlingPolicies + .exitAfterAllProblems(), options, problemFactory) { + public void record(IProblem problem, CompilationResult unitResult, + ReferenceContext referenceContext) { + unitResult.record(problem, referenceContext); + if (requestor != null) { + requestor.acceptProblem(problem); + } + } + }); + // true); + // options.sourceLevel >= CompilerOptions.JDK1_4); + this.requestor = requestor; + typeNames = new char[4][]; + superTypeNames = new char[4][]; + nestedTypeIndex = 0; + this.options = options; + } + + /** + * @deprecated use SourceElementParser(ISourceElementRequestor, + * IProblemFactory, CompilerOptions) + */ + public SourceElementParser(final ISourceElementRequestor requestor, + IProblemFactory problemFactory) { + this(requestor, problemFactory, new CompilerOptions()); + } + + public SourceElementParser(final ISourceElementRequestor requestor, + IProblemFactory problemFactory, CompilerOptions options, + boolean reportLocalDeclarations) { + this(requestor, problemFactory, options); + if (reportLocalDeclarations) { + this.localDeclarationVisitor = new LocalDeclarationVisitor(); + } + } + + // public void checkAnnotation() { + // int firstCommentIndex = scanner.commentPtr; + // + // super.checkAnnotation(); + // + // // modify the modifier source start to point at the first comment + // if (firstCommentIndex >= 0) { + // modifiersSourceStart = scanner.commentStarts[0]; + // } + // } + // protected void classInstanceCreation(boolean alwaysQualified) { + // + // boolean previousFlag = reportReferenceInfo; + // reportReferenceInfo = false; // not to see the type reference reported in + // super call to getTypeReference(...) + // super.classInstanceCreation(alwaysQualified); + // reportReferenceInfo = previousFlag; + // if (reportReferenceInfo){ + // AllocationExpression alloc = + // (AllocationExpression)expressionStack[expressionPtr]; + // TypeReference typeRef = alloc.type; + // requestor.acceptConstructorReference( + // typeRef instanceof SingleTypeReference + // ? ((SingleTypeReference) typeRef).token + // : CharOperation.concatWith(alloc.type.getTypeName(), '.'), + // alloc.arguments == null ? 0 : alloc.arguments.length, + // alloc.sourceStart); + // } + // } + // protected void consumeConstructorHeaderName() { + // // ConstructorHeaderName ::= Modifiersopt 'Identifier' '(' + // + // /* recovering - might be an empty message send */ + // if (currentElement != null){ + // if (lastIgnoredToken == TokenNamenew){ // was an allocation expression + // lastCheckPoint = scanner.startPosition; // force to restart at this exact + // position + // restartRecovery = true; + // return; + // } + // } + // SourceConstructorDeclaration cd = new + // SourceConstructorDeclaration(this.compilationUnit.compilationResult); + // + // //name -- this is not really revelant but we do ..... + // cd.selector = identifierStack[identifierPtr]; + // long selectorSourcePositions = identifierPositionStack[identifierPtr--]; + // identifierLengthPtr--; + // + // //modifiers + // cd.declarationSourceStart = intStack[intPtr--]; + // cd.modifiers = intStack[intPtr--]; + // + // //highlight starts at the selector starts + // cd.sourceStart = (int) (selectorSourcePositions >>> 32); + // cd.selectorSourceEnd = (int) selectorSourcePositions; + // pushOnAstStack(cd); + // + // cd.sourceEnd = lParenPos; + // cd.bodyStart = lParenPos+1; + // listLength = 0; // initialize listLength before reading parameters/throws + // + // // recovery + // if (currentElement != null){ + // lastCheckPoint = cd.bodyStart; + // if ((currentElement instanceof RecoveredType && lastIgnoredToken != + // TokenNameDOT) + // || cd.modifiers != 0){ + // currentElement = currentElement.add(cd, 0); + // lastIgnoredToken = -1; + // } + // } + // } + // /** + // * + // * INTERNAL USE-ONLY + // */ + // protected void consumeExitVariableWithInitialization() { + // // ExitVariableWithInitialization ::= $empty + // // the scanner is located after the comma or the semi-colon. + // // we want to include the comma or the semi-colon + // super.consumeExitVariableWithInitialization(); + // if (isLocalDeclaration() || ((currentToken != TokenNameCOMMA) && + // (currentToken != TokenNameSEMICOLON))) + // return; + // ((SourceFieldDeclaration) astStack[astPtr]).fieldEndPosition = + // scanner.currentPosition - 1; + // } + // protected void consumeExitVariableWithoutInitialization() { + // // ExitVariableWithoutInitialization ::= $empty + // // do nothing by default + // super.consumeExitVariableWithoutInitialization(); + // if (isLocalDeclaration() || ((currentToken != TokenNameCOMMA) && + // (currentToken != TokenNameSEMICOLON))) + // return; + // ((SourceFieldDeclaration) astStack[astPtr]).fieldEndPosition = + // scanner.currentPosition - 1; + // } + // /** + // * + // * INTERNAL USE-ONLY + // */ + // protected void consumeFieldAccess(boolean isSuperAccess) { + // // FieldAccess ::= Primary '.' 'Identifier' + // // FieldAccess ::= 'super' '.' 'Identifier' + // super.consumeFieldAccess(isSuperAccess); + // FieldReference fr = (FieldReference) expressionStack[expressionPtr]; + // if (reportReferenceInfo) { + // requestor.acceptFieldReference(fr.token, fr.sourceStart); + // } + // } + // protected void consumeMethodHeaderName() { + // // MethodHeaderName ::= Modifiersopt Type 'Identifier' '(' + // SourceMethodDeclaration md = new + // SourceMethodDeclaration(this.compilationUnit.compilationResult); + // + // //name + // md.selector = identifierStack[identifierPtr]; + // long selectorSourcePositions = identifierPositionStack[identifierPtr--]; + // identifierLengthPtr--; + // //type + // md.returnType = getTypeReference(intStack[intPtr--]); + // //modifiers + // md.declarationSourceStart = intStack[intPtr--]; + // md.modifiers = intStack[intPtr--]; + // + // //highlight starts at selector start + // md.sourceStart = (int) (selectorSourcePositions >>> 32); + // md.selectorSourceEnd = (int) selectorSourcePositions; + // pushOnAstStack(md); + // md.sourceEnd = lParenPos; + // md.bodyStart = lParenPos+1; + // listLength = 0; // initialize listLength before reading parameters/throws + // + // // recovery + // if (currentElement != null){ + // if (currentElement instanceof RecoveredType + // //|| md.modifiers != 0 + // || (scanner.getLineNumber(md.returnType.sourceStart) + // == scanner.getLineNumber(md.sourceStart))){ + // lastCheckPoint = md.bodyStart; + // currentElement = currentElement.add(md, 0); + // lastIgnoredToken = -1; + // } else { + // lastCheckPoint = md.sourceStart; + // restartRecovery = true; + // } + // } + // } + // /** + // * + // * INTERNAL USE-ONLY + // */ + // protected void consumeMethodInvocationName() { + // // MethodInvocation ::= Name '(' ArgumentListopt ')' + // + // // when the name is only an identifier...we have a message send to "this" + // (implicit) + // super.consumeMethodInvocationName(); + // MessageSend messageSend = (MessageSend) expressionStack[expressionPtr]; + // Expression[] args = messageSend.arguments; + // if (reportReferenceInfo) { + // requestor.acceptMethodReference( + // messageSend.selector, + // args == null ? 0 : args.length, + // (int)(messageSend.nameSourcePosition >>> 32)); + // } + // } + // /** + // * + // * INTERNAL USE-ONLY + // */ + // protected void consumeMethodInvocationPrimary() { + // super.consumeMethodInvocationPrimary(); + // MessageSend messageSend = (MessageSend) expressionStack[expressionPtr]; + // Expression[] args = messageSend.arguments; + // if (reportReferenceInfo) { + // requestor.acceptMethodReference( + // messageSend.selector, + // args == null ? 0 : args.length, + // (int)(messageSend.nameSourcePosition >>> 32)); + // } + // } + // /** + // * + // * INTERNAL USE-ONLY + // */ + // protected void consumeMethodInvocationSuper() { + // // MethodInvocation ::= 'super' '.' 'Identifier' '(' ArgumentListopt ')' + // super.consumeMethodInvocationSuper(); + // MessageSend messageSend = (MessageSend) expressionStack[expressionPtr]; + // Expression[] args = messageSend.arguments; + // if (reportReferenceInfo) { + // requestor.acceptMethodReference( + // messageSend.selector, + // args == null ? 0 : args.length, + // (int)(messageSend.nameSourcePosition >>> 32)); + // } + // } + // protected void consumeSingleTypeImportDeclarationName() { + // // SingleTypeImportDeclarationName ::= 'import' Name + // /* push an ImportRef build from the last name + // stored in the identifier stack. */ + // + // super.consumeSingleTypeImportDeclarationName(); + // ImportReference impt = (ImportReference)astStack[astPtr]; + // if (reportReferenceInfo) { + // requestor.acceptTypeReference(impt.tokens, impt.sourceStart, + // impt.sourceEnd); + // } + // } + // protected void consumeTypeImportOnDemandDeclarationName() { + // // TypeImportOnDemandDeclarationName ::= 'import' Name '.' '*' + // /* push an ImportRef build from the last name + // stored in the identifier stack. */ + // + // super.consumeTypeImportOnDemandDeclarationName(); + // ImportReference impt = (ImportReference)astStack[astPtr]; + // if (reportReferenceInfo) { + // requestor.acceptUnknownReference(impt.tokens, impt.sourceStart, + // impt.sourceEnd); + // } + // } + // protected FieldDeclaration createFieldDeclaration(Expression + // initialization, char[] name, int sourceStart, int sourceEnd) { + // return new SourceFieldDeclaration(null, name, sourceStart, sourceEnd); + // } + // protected CompilationUnitDeclaration endParse(int act) { + // if (sourceType != null) { + // if (sourceType.isInterface()) { + // consumeInterfaceDeclaration(); + // } else { + // consumeClassDeclaration(); + // } + // } + // if (compilationUnit != null) { + // CompilationUnitDeclaration result = super.endParse(act); + // return result; + // } else { + // return null; + // } + // } + /* + * Flush annotations defined prior to a given positions. + * + * Note: annotations are stacked in syntactical order + * + * Either answer given , or the end position of a comment line + * immediately following the (same line) + * + * e.g. void foo(){ } // end of method foo + */ + // + // public int flushAnnotationsDefinedPriorTo(int position) { + // + // return lastFieldEndPosition = + // super.flushAnnotationsDefinedPriorTo(position); + // } + // public TypeReference getTypeReference(int dim) { + // /* build a Reference on a variable that may be qualified or not + // * This variable is a type reference and dim will be its dimensions + // */ + // int length; + // if ((length = identifierLengthStack[identifierLengthPtr--]) == 1) { + // // single variable reference + // if (dim == 0) { + // SingleTypeReference ref = + // new SingleTypeReference( + // identifierStack[identifierPtr], + // identifierPositionStack[identifierPtr--]); + // if (reportReferenceInfo) { + // requestor.acceptTypeReference(ref.token, ref.sourceStart); + // } + // return ref; + // } else { + // ArrayTypeReference ref = + // new ArrayTypeReference( + // identifierStack[identifierPtr], + // dim, + // identifierPositionStack[identifierPtr--]); + // ref.sourceEnd = endPosition; + // if (reportReferenceInfo) { + // requestor.acceptTypeReference(ref.token, ref.sourceStart); + // } + // return ref; + // } + // } else { + // if (length < 0) { //flag for precompiled type reference on base types + // TypeReference ref = TypeReference.baseTypeReference(-length, dim); + // ref.sourceStart = intStack[intPtr--]; + // if (dim == 0) { + // ref.sourceEnd = intStack[intPtr--]; + // } else { + // intPtr--; // no need to use this position as it is an array + // ref.sourceEnd = endPosition; + // } + // if (reportReferenceInfo){ + // requestor.acceptTypeReference(ref.getTypeName(), ref.sourceStart, + // ref.sourceEnd); + // } + // return ref; + // } else { //Qualified variable reference + // char[][] tokens = new char[length][]; + // identifierPtr -= length; + // long[] positions = new long[length]; + // System.arraycopy(identifierStack, identifierPtr + 1, tokens, 0, length); + // System.arraycopy( + // identifierPositionStack, + // identifierPtr + 1, + // positions, + // 0, + // length); + // if (dim == 0) { + // QualifiedTypeReference ref = new QualifiedTypeReference(tokens, + // positions); + // if (reportReferenceInfo) { + // requestor.acceptTypeReference(ref.tokens, ref.sourceStart, + // ref.sourceEnd); + // } + // return ref; + // } else { + // ArrayQualifiedTypeReference ref = + // new ArrayQualifiedTypeReference(tokens, dim, positions); + // ref.sourceEnd = endPosition; + // if (reportReferenceInfo) { + // requestor.acceptTypeReference(ref.tokens, ref.sourceStart, + // ref.sourceEnd); + // } + // return ref; + // } + // } + // } + // } + // public NameReference getUnspecifiedReference() { + // /* build a (unspecified) NameReference which may be qualified*/ + // + // int length; + // if ((length = identifierLengthStack[identifierLengthPtr--]) == 1) { + // // single variable reference + // SingleNameReference ref = + // new SingleNameReference( + // identifierStack[identifierPtr], + // identifierPositionStack[identifierPtr--]); + // if (reportReferenceInfo) { + // this.addUnknownRef(ref); + // } + // return ref; + // } else { + // //Qualified variable reference + // char[][] tokens = new char[length][]; + // identifierPtr -= length; + // System.arraycopy(identifierStack, identifierPtr + 1, tokens, 0, length); + // QualifiedNameReference ref = + // new QualifiedNameReference( + // tokens, + // (int) (identifierPositionStack[identifierPtr + 1] >> 32), // sourceStart + // (int) identifierPositionStack[identifierPtr + length]); // sourceEnd + // if (reportReferenceInfo) { + // this.addUnknownRef(ref); + // } + // return ref; + // } + // } + // public NameReference getUnspecifiedReferenceOptimized() { + // /* build a (unspecified) NameReference which may be qualified + // The optimization occurs for qualified reference while we are + // certain in this case the last item of the qualified name is + // a field access. This optimization is IMPORTANT while it results + // that when a NameReference is build, the type checker should always + // look for that it is not a type reference */ + // + // int length; + // if ((length = identifierLengthStack[identifierLengthPtr--]) == 1) { + // // single variable reference + // SingleNameReference ref = + // new SingleNameReference( + // identifierStack[identifierPtr], + // identifierPositionStack[identifierPtr--]); + // ref.bits &= ~ASTNode.RestrictiveFlagMASK; + // ref.bits |= LOCAL | FIELD; + // if (reportReferenceInfo) { + // this.addUnknownRef(ref); + // } + // return ref; + // } + // + // //Qualified-variable-reference + // //In fact it is variable-reference DOT field-ref , but it would result in + // a + // type + // //conflict tha can be only reduce by making a superclass (or inetrface ) + // between + // //nameReference and FiledReference or putting FieldReference under + // NameReference + // //or else..........This optimisation is not really relevant so just leave + // as it is + // + // char[][] tokens = new char[length][]; + // identifierPtr -= length; + // System.arraycopy(identifierStack, identifierPtr + 1, tokens, 0, length); + // QualifiedNameReference ref = + // new QualifiedNameReference( + // tokens, + // (int) (identifierPositionStack[identifierPtr + 1] >> 32), + // // sourceStart + // (int) identifierPositionStack[identifierPtr + length]); // sourceEnd + // ref.bits &= ~ASTNode.RestrictiveFlagMASK; + // ref.bits |= LOCAL | FIELD; + // if (reportReferenceInfo) { + // this.addUnknownRef(ref); + // } + // return ref; + // } + // /** + // * + // * INTERNAL USE-ONLY + // */ + // private boolean isLocalDeclaration() { + // int nestedDepth = nestedType; + // while (nestedDepth >= 0) { + // if (nestedMethod[nestedDepth] != 0) { + // return true; + // } + // nestedDepth--; + // } + // return false; + // } + /* + * Update the bodyStart of the corresponding parse node + */ + public void notifySourceElementRequestor( + CompilationUnitDeclaration parsedUnit) { + if (parsedUnit == null) { + // when we parse a single type member declaration the compilation + // unit is + // null, but we still + // want to be able to notify the requestor on the created ast node + if (astStack[0] instanceof AbstractMethodDeclaration) { + notifySourceElementRequestor((AbstractMethodDeclaration) astStack[0]); + return; + } + return; + } + // range check + boolean isInRange = scanner.initialPosition <= parsedUnit.sourceStart + && scanner.eofPosition >= parsedUnit.sourceEnd; + + // if (reportReferenceInfo) { + // notifyAllUnknownReferences(); + // } + // collect the top level ast nodes + int length = 0; + ASTNode[] nodes = null; + if (sourceType == null) { + if (isInRange) { + requestor.enterCompilationUnit(); + } + // ImportReference currentPackage = parsedUnit.currentPackage; + ImportReference[] imports = parsedUnit.imports; + // TypeDeclaration[] types = parsedUnit.types; + ArrayList types = parsedUnit.types; + if (types != null) { + // length = + // (currentPackage == null ? 0 : 1) + // + (imports == null ? 0 : imports.length) + // + (types == null ? 0 : types.length); + // nodes = new ASTNode[length]; + length = (imports == null ? 0 : imports.length) + types.size(); + nodes = new ASTNode[length]; + int index = 0; + // if (currentPackage != null) { + // nodes[index++] = currentPackage; + // } + if (imports != null) { + for (int i = 0, max = imports.length; i < max; i++) { + nodes[index++] = imports[i]; + } + } + + for (int i = 0, max = types.size(); i < max; i++) { + nodes[index++] = (ASTNode) types.get(i); + } + } + } else { + // TypeDeclaration[] types = parsedUnit.types; + ArrayList types = parsedUnit.types; + if (types != null) { + length = types.size(); + nodes = new ASTNode[length]; + for (int i = 0, max = types.size(); i < max; i++) { + nodes[i] = (ASTNode) types.get(i); + } + } + } + + // notify the nodes in the syntactical order + if (nodes != null && length > 0) { + quickSort(nodes, 0, length - 1); + for (int i = 0; i < length; i++) { + ASTNode node = nodes[i]; + if (node instanceof ImportReference) { + ImportReference importRef = (ImportReference) node; + // if (node == parsedUnit.currentPackage) { + // notifySourceElementRequestor(importRef, true); + // } else { + notifySourceElementRequestor(importRef, false); + // } + } // else { instanceof TypeDeclaration + if (node instanceof TypeDeclaration) { + notifySourceElementRequestor((TypeDeclaration) node, + sourceType == null); + // notifySourceElementRequestor((CompilationUnitDeclaration)node, + // sourceType == null); + } + // jsurfer - INSERT start + if (node instanceof AbstractMethodDeclaration) { + notifySourceElementRequestor((AbstractMethodDeclaration) node); + } + // jsurfer - INSERT end + } + } - ISourceElementRequestor requestor; - int fieldCount; - int localIntPtr; - int lastFieldEndPosition; - ISourceType sourceType; - boolean reportReferenceInfo; - char[][] typeNames; - char[][] superTypeNames; - int nestedTypeIndex; - static final char[] JAVA_LANG_OBJECT = "java.lang.Object".toCharArray(); //$NON-NLS-1$ - NameReference[] unknownRefs; - int unknownRefsCounter; - LocalDeclarationVisitor localDeclarationVisitor = null; - // CompilerOptions options; + if (sourceType == null) { + if (isInRange) { + requestor.exitCompilationUnit(parsedUnit.sourceEnd); + } + } + } - /** - * An ast visitor that visits local type declarations. - */ - public class LocalDeclarationVisitor extends ASTVisitor { - public boolean visit(TypeDeclaration typeDeclaration, BlockScope scope) { - notifySourceElementRequestor(typeDeclaration, sourceType == null); - return false; // don't visit members as this was done during notifySourceElementRequestor(...) - } - public boolean visit(TypeDeclaration typeDeclaration, ClassScope scope) { - notifySourceElementRequestor(typeDeclaration, sourceType == null); - return false; // don't visit members as this was done during notifySourceElementRequestor(...) - } - - } + // private void notifyAllUnknownReferences() { + // for (int i = 0, max = this.unknownRefsCounter; i < max; i++) { + // NameReference nameRef = this.unknownRefs[i]; + // if ((nameRef.bits & BindingIds.VARIABLE) != 0) { + // if ((nameRef.bits & BindingIds.TYPE) == 0) { + // // variable but not type + // if (nameRef instanceof SingleNameReference) { + // // local var or field + // requestor.acceptUnknownReference(((SingleNameReference) nameRef).token, + // nameRef.sourceStart); + // } else { + // // QualifiedNameReference + // // The last token is a field reference and the previous tokens are a + // type/variable references + // char[][] tokens = ((QualifiedNameReference) nameRef).tokens; + // int tokensLength = tokens.length; + // requestor.acceptFieldReference(tokens[tokensLength - 1], + // nameRef.sourceEnd + // - tokens[tokensLength - 1].length + 1); + // char[][] typeRef = new char[tokensLength - 1][]; + // System.arraycopy(tokens, 0, typeRef, 0, tokensLength - 1); + // requestor.acceptUnknownReference(typeRef, nameRef.sourceStart, + // nameRef.sourceEnd - tokens[tokensLength - 1].length); + // } + // } else { + // // variable or type + // if (nameRef instanceof SingleNameReference) { + // requestor.acceptUnknownReference(((SingleNameReference) nameRef).token, + // nameRef.sourceStart); + // } else { + // //QualifiedNameReference + // requestor.acceptUnknownReference(((QualifiedNameReference) + // nameRef).tokens, + // nameRef.sourceStart, nameRef.sourceEnd); + // } + // } + // } else if ((nameRef.bits & BindingIds.TYPE) != 0) { + // if (nameRef instanceof SingleNameReference) { + // requestor.acceptTypeReference(((SingleNameReference) nameRef).token, + // nameRef.sourceStart); + // } else { + // // it is a QualifiedNameReference + // requestor.acceptTypeReference(((QualifiedNameReference) nameRef).tokens, + // nameRef.sourceStart, nameRef.sourceEnd); + // } + // } + // } + // } + /* + * Update the bodyStart of the corresponding parse node + */ + public void notifySourceElementRequestor( + AbstractMethodDeclaration methodDeclaration) { - public SourceElementParser(final ISourceElementRequestor requestor, IProblemFactory problemFactory, CompilerOptions options) { - // we want to notify all syntax error with the acceptProblem API - // To do so, we define the record method of the ProblemReporter - super( new ProblemReporter(DefaultErrorHandlingPolicies.exitAfterAllProblems(), options, problemFactory) { - public void record(IProblem problem, CompilationResult unitResult, ReferenceContext referenceContext) { - unitResult.record(problem, referenceContext); - if (requestor!=null) { - requestor.acceptProblem(problem); - } - } - }); - // true); - // options.sourceLevel >= CompilerOptions.JDK1_4); - this.requestor = requestor; - typeNames = new char[4][]; - superTypeNames = new char[4][]; - nestedTypeIndex = 0; - this.options = options; - } + // range check + boolean isInRange = scanner.initialPosition <= methodDeclaration.declarationSourceStart + && scanner.eofPosition >= methodDeclaration.declarationSourceEnd; - /** - * @deprecated use SourceElementParser(ISourceElementRequestor, - * IProblemFactory, CompilerOptions) - */ - public SourceElementParser( - final ISourceElementRequestor requestor, - IProblemFactory problemFactory) { - this(requestor, problemFactory, new CompilerOptions()); - } - public SourceElementParser( - final ISourceElementRequestor requestor, - IProblemFactory problemFactory, - CompilerOptions options, - boolean reportLocalDeclarations) { - this(requestor, problemFactory, options); - if (reportLocalDeclarations) { - this.localDeclarationVisitor = new LocalDeclarationVisitor(); - } - } - //public void checkAnnotation() { - // int firstCommentIndex = scanner.commentPtr; - // - // super.checkAnnotation(); - // - // // modify the modifier source start to point at the first comment - // if (firstCommentIndex >= 0) { - // modifiersSourceStart = scanner.commentStarts[0]; - // } - //} - //protected void classInstanceCreation(boolean alwaysQualified) { - // - // boolean previousFlag = reportReferenceInfo; - // reportReferenceInfo = false; // not to see the type reference reported in - // super call to getTypeReference(...) - // super.classInstanceCreation(alwaysQualified); - // reportReferenceInfo = previousFlag; - // if (reportReferenceInfo){ - // AllocationExpression alloc = - // (AllocationExpression)expressionStack[expressionPtr]; - // TypeReference typeRef = alloc.type; - // requestor.acceptConstructorReference( - // typeRef instanceof SingleTypeReference - // ? ((SingleTypeReference) typeRef).token - // : CharOperation.concatWith(alloc.type.getTypeName(), '.'), - // alloc.arguments == null ? 0 : alloc.arguments.length, - // alloc.sourceStart); - // } - //} - //protected void consumeConstructorHeaderName() { - // // ConstructorHeaderName ::= Modifiersopt 'Identifier' '(' - // - // /* recovering - might be an empty message send */ - // if (currentElement != null){ - // if (lastIgnoredToken == TokenNamenew){ // was an allocation expression - // lastCheckPoint = scanner.startPosition; // force to restart at this exact - // position - // restartRecovery = true; - // return; - // } - // } - // SourceConstructorDeclaration cd = new - // SourceConstructorDeclaration(this.compilationUnit.compilationResult); - // - // //name -- this is not really revelant but we do ..... - // cd.selector = identifierStack[identifierPtr]; - // long selectorSourcePositions = identifierPositionStack[identifierPtr--]; - // identifierLengthPtr--; - // - // //modifiers - // cd.declarationSourceStart = intStack[intPtr--]; - // cd.modifiers = intStack[intPtr--]; - // - // //highlight starts at the selector starts - // cd.sourceStart = (int) (selectorSourcePositions >>> 32); - // cd.selectorSourceEnd = (int) selectorSourcePositions; - // pushOnAstStack(cd); - // - // cd.sourceEnd = lParenPos; - // cd.bodyStart = lParenPos+1; - // listLength = 0; // initialize listLength before reading parameters/throws - // - // // recovery - // if (currentElement != null){ - // lastCheckPoint = cd.bodyStart; - // if ((currentElement instanceof RecoveredType && lastIgnoredToken != - // TokenNameDOT) - // || cd.modifiers != 0){ - // currentElement = currentElement.add(cd, 0); - // lastIgnoredToken = -1; - // } - // } - //} - ///** - // * - // * INTERNAL USE-ONLY - // */ - //protected void consumeExitVariableWithInitialization() { - // // ExitVariableWithInitialization ::= $empty - // // the scanner is located after the comma or the semi-colon. - // // we want to include the comma or the semi-colon - // super.consumeExitVariableWithInitialization(); - // if (isLocalDeclaration() || ((currentToken != TokenNameCOMMA) && - // (currentToken != TokenNameSEMICOLON))) - // return; - // ((SourceFieldDeclaration) astStack[astPtr]).fieldEndPosition = - // scanner.currentPosition - 1; - //} - //protected void consumeExitVariableWithoutInitialization() { - // // ExitVariableWithoutInitialization ::= $empty - // // do nothing by default - // super.consumeExitVariableWithoutInitialization(); - // if (isLocalDeclaration() || ((currentToken != TokenNameCOMMA) && - // (currentToken != TokenNameSEMICOLON))) - // return; - // ((SourceFieldDeclaration) astStack[astPtr]).fieldEndPosition = - // scanner.currentPosition - 1; - //} - ///** - // * - // * INTERNAL USE-ONLY - // */ - //protected void consumeFieldAccess(boolean isSuperAccess) { - // // FieldAccess ::= Primary '.' 'Identifier' - // // FieldAccess ::= 'super' '.' 'Identifier' - // super.consumeFieldAccess(isSuperAccess); - // FieldReference fr = (FieldReference) expressionStack[expressionPtr]; - // if (reportReferenceInfo) { - // requestor.acceptFieldReference(fr.token, fr.sourceStart); - // } - //} - //protected void consumeMethodHeaderName() { - // // MethodHeaderName ::= Modifiersopt Type 'Identifier' '(' - // SourceMethodDeclaration md = new - // SourceMethodDeclaration(this.compilationUnit.compilationResult); - // - // //name - // md.selector = identifierStack[identifierPtr]; - // long selectorSourcePositions = identifierPositionStack[identifierPtr--]; - // identifierLengthPtr--; - // //type - // md.returnType = getTypeReference(intStack[intPtr--]); - // //modifiers - // md.declarationSourceStart = intStack[intPtr--]; - // md.modifiers = intStack[intPtr--]; - // - // //highlight starts at selector start - // md.sourceStart = (int) (selectorSourcePositions >>> 32); - // md.selectorSourceEnd = (int) selectorSourcePositions; - // pushOnAstStack(md); - // md.sourceEnd = lParenPos; - // md.bodyStart = lParenPos+1; - // listLength = 0; // initialize listLength before reading parameters/throws - // - // // recovery - // if (currentElement != null){ - // if (currentElement instanceof RecoveredType - // //|| md.modifiers != 0 - // || (scanner.getLineNumber(md.returnType.sourceStart) - // == scanner.getLineNumber(md.sourceStart))){ - // lastCheckPoint = md.bodyStart; - // currentElement = currentElement.add(md, 0); - // lastIgnoredToken = -1; - // } else { - // lastCheckPoint = md.sourceStart; - // restartRecovery = true; - // } - // } - //} - ///** - // * - // * INTERNAL USE-ONLY - // */ - //protected void consumeMethodInvocationName() { - // // MethodInvocation ::= Name '(' ArgumentListopt ')' - // - // // when the name is only an identifier...we have a message send to "this" - // (implicit) - // super.consumeMethodInvocationName(); - // MessageSend messageSend = (MessageSend) expressionStack[expressionPtr]; - // Expression[] args = messageSend.arguments; - // if (reportReferenceInfo) { - // requestor.acceptMethodReference( - // messageSend.selector, - // args == null ? 0 : args.length, - // (int)(messageSend.nameSourcePosition >>> 32)); - // } - //} - ///** - // * - // * INTERNAL USE-ONLY - // */ - //protected void consumeMethodInvocationPrimary() { - // super.consumeMethodInvocationPrimary(); - // MessageSend messageSend = (MessageSend) expressionStack[expressionPtr]; - // Expression[] args = messageSend.arguments; - // if (reportReferenceInfo) { - // requestor.acceptMethodReference( - // messageSend.selector, - // args == null ? 0 : args.length, - // (int)(messageSend.nameSourcePosition >>> 32)); - // } - //} - ///** - // * - // * INTERNAL USE-ONLY - // */ - //protected void consumeMethodInvocationSuper() { - // // MethodInvocation ::= 'super' '.' 'Identifier' '(' ArgumentListopt ')' - // super.consumeMethodInvocationSuper(); - // MessageSend messageSend = (MessageSend) expressionStack[expressionPtr]; - // Expression[] args = messageSend.arguments; - // if (reportReferenceInfo) { - // requestor.acceptMethodReference( - // messageSend.selector, - // args == null ? 0 : args.length, - // (int)(messageSend.nameSourcePosition >>> 32)); - // } - //} - //protected void consumeSingleTypeImportDeclarationName() { - // // SingleTypeImportDeclarationName ::= 'import' Name - // /* push an ImportRef build from the last name - // stored in the identifier stack. */ - // - // super.consumeSingleTypeImportDeclarationName(); - // ImportReference impt = (ImportReference)astStack[astPtr]; - // if (reportReferenceInfo) { - // requestor.acceptTypeReference(impt.tokens, impt.sourceStart, - // impt.sourceEnd); - // } - //} - //protected void consumeTypeImportOnDemandDeclarationName() { - // // TypeImportOnDemandDeclarationName ::= 'import' Name '.' '*' - // /* push an ImportRef build from the last name - // stored in the identifier stack. */ - // - // super.consumeTypeImportOnDemandDeclarationName(); - // ImportReference impt = (ImportReference)astStack[astPtr]; - // if (reportReferenceInfo) { - // requestor.acceptUnknownReference(impt.tokens, impt.sourceStart, - // impt.sourceEnd); - // } - //} - //protected FieldDeclaration createFieldDeclaration(Expression - // initialization, char[] name, int sourceStart, int sourceEnd) { - // return new SourceFieldDeclaration(null, name, sourceStart, sourceEnd); - //} - //protected CompilationUnitDeclaration endParse(int act) { - // if (sourceType != null) { - // if (sourceType.isInterface()) { - // consumeInterfaceDeclaration(); - // } else { - // consumeClassDeclaration(); - // } - // } - // if (compilationUnit != null) { - // CompilationUnitDeclaration result = super.endParse(act); - // return result; - // } else { - // return null; - // } - //} - /* - * Flush annotations defined prior to a given positions. - * - * Note: annotations are stacked in syntactical order - * - * Either answer given , or the end position of a comment line - * immediately following the (same line) - * - * e.g. void foo(){ } // end of method foo - */ - // - //public int flushAnnotationsDefinedPriorTo(int position) { - // - // return lastFieldEndPosition = - // super.flushAnnotationsDefinedPriorTo(position); - //} - //public TypeReference getTypeReference(int dim) { - // /* build a Reference on a variable that may be qualified or not - // * This variable is a type reference and dim will be its dimensions - // */ - // int length; - // if ((length = identifierLengthStack[identifierLengthPtr--]) == 1) { - // // single variable reference - // if (dim == 0) { - // SingleTypeReference ref = - // new SingleTypeReference( - // identifierStack[identifierPtr], - // identifierPositionStack[identifierPtr--]); - // if (reportReferenceInfo) { - // requestor.acceptTypeReference(ref.token, ref.sourceStart); - // } - // return ref; - // } else { - // ArrayTypeReference ref = - // new ArrayTypeReference( - // identifierStack[identifierPtr], - // dim, - // identifierPositionStack[identifierPtr--]); - // ref.sourceEnd = endPosition; - // if (reportReferenceInfo) { - // requestor.acceptTypeReference(ref.token, ref.sourceStart); - // } - // return ref; - // } - // } else { - // if (length < 0) { //flag for precompiled type reference on base types - // TypeReference ref = TypeReference.baseTypeReference(-length, dim); - // ref.sourceStart = intStack[intPtr--]; - // if (dim == 0) { - // ref.sourceEnd = intStack[intPtr--]; - // } else { - // intPtr--; // no need to use this position as it is an array - // ref.sourceEnd = endPosition; - // } - // if (reportReferenceInfo){ - // requestor.acceptTypeReference(ref.getTypeName(), ref.sourceStart, - // ref.sourceEnd); - // } - // return ref; - // } else { //Qualified variable reference - // char[][] tokens = new char[length][]; - // identifierPtr -= length; - // long[] positions = new long[length]; - // System.arraycopy(identifierStack, identifierPtr + 1, tokens, 0, length); - // System.arraycopy( - // identifierPositionStack, - // identifierPtr + 1, - // positions, - // 0, - // length); - // if (dim == 0) { - // QualifiedTypeReference ref = new QualifiedTypeReference(tokens, positions); - // if (reportReferenceInfo) { - // requestor.acceptTypeReference(ref.tokens, ref.sourceStart, ref.sourceEnd); - // } - // return ref; - // } else { - // ArrayQualifiedTypeReference ref = - // new ArrayQualifiedTypeReference(tokens, dim, positions); - // ref.sourceEnd = endPosition; - // if (reportReferenceInfo) { - // requestor.acceptTypeReference(ref.tokens, ref.sourceStart, ref.sourceEnd); - // } - // return ref; - // } - // } - // } - //} - //public NameReference getUnspecifiedReference() { - // /* build a (unspecified) NameReference which may be qualified*/ - // - // int length; - // if ((length = identifierLengthStack[identifierLengthPtr--]) == 1) { - // // single variable reference - // SingleNameReference ref = - // new SingleNameReference( - // identifierStack[identifierPtr], - // identifierPositionStack[identifierPtr--]); - // if (reportReferenceInfo) { - // this.addUnknownRef(ref); - // } - // return ref; - // } else { - // //Qualified variable reference - // char[][] tokens = new char[length][]; - // identifierPtr -= length; - // System.arraycopy(identifierStack, identifierPtr + 1, tokens, 0, length); - // QualifiedNameReference ref = - // new QualifiedNameReference( - // tokens, - // (int) (identifierPositionStack[identifierPtr + 1] >> 32), // sourceStart - // (int) identifierPositionStack[identifierPtr + length]); // sourceEnd - // if (reportReferenceInfo) { - // this.addUnknownRef(ref); - // } - // return ref; - // } - //} - //public NameReference getUnspecifiedReferenceOptimized() { - // /* build a (unspecified) NameReference which may be qualified - // The optimization occurs for qualified reference while we are - // certain in this case the last item of the qualified name is - // a field access. This optimization is IMPORTANT while it results - // that when a NameReference is build, the type checker should always - // look for that it is not a type reference */ - // - // int length; - // if ((length = identifierLengthStack[identifierLengthPtr--]) == 1) { - // // single variable reference - // SingleNameReference ref = - // new SingleNameReference( - // identifierStack[identifierPtr], - // identifierPositionStack[identifierPtr--]); - // ref.bits &= ~ASTNode.RestrictiveFlagMASK; - // ref.bits |= LOCAL | FIELD; - // if (reportReferenceInfo) { - // this.addUnknownRef(ref); - // } - // return ref; - // } - // - // //Qualified-variable-reference - // //In fact it is variable-reference DOT field-ref , but it would result in a - // type - // //conflict tha can be only reduce by making a superclass (or inetrface ) - // between - // //nameReference and FiledReference or putting FieldReference under - // NameReference - // //or else..........This optimisation is not really relevant so just leave - // as it is - // - // char[][] tokens = new char[length][]; - // identifierPtr -= length; - // System.arraycopy(identifierStack, identifierPtr + 1, tokens, 0, length); - // QualifiedNameReference ref = - // new QualifiedNameReference( - // tokens, - // (int) (identifierPositionStack[identifierPtr + 1] >> 32), - // // sourceStart - // (int) identifierPositionStack[identifierPtr + length]); // sourceEnd - // ref.bits &= ~ASTNode.RestrictiveFlagMASK; - // ref.bits |= LOCAL | FIELD; - // if (reportReferenceInfo) { - // this.addUnknownRef(ref); - // } - // return ref; - //} - ///** - // * - // * INTERNAL USE-ONLY - // */ - //private boolean isLocalDeclaration() { - // int nestedDepth = nestedType; - // while (nestedDepth >= 0) { - // if (nestedMethod[nestedDepth] != 0) { - // return true; - // } - // nestedDepth--; - // } - // return false; - //} - /* - * Update the bodyStart of the corresponding parse node - */ - public void notifySourceElementRequestor(CompilationUnitDeclaration parsedUnit) { - if (parsedUnit == null) { - // when we parse a single type member declaration the compilation unit is - // null, but we still - // want to be able to notify the requestor on the created ast node - if (astStack[0] instanceof AbstractMethodDeclaration) { - notifySourceElementRequestor((AbstractMethodDeclaration) astStack[0]); - return; - } - return; - } - // range check - boolean isInRange = scanner.initialPosition <= parsedUnit.sourceStart && scanner.eofPosition >= parsedUnit.sourceEnd; + if (methodDeclaration.isClinit()) { + this.visitIfNeeded(methodDeclaration); + return; + } - // if (reportReferenceInfo) { - // notifyAllUnknownReferences(); - // } - // collect the top level ast nodes - int length = 0; - ASTNode[] nodes = null; - if (sourceType == null) { - if (isInRange) { - requestor.enterCompilationUnit(); - } - // ImportReference currentPackage = parsedUnit.currentPackage; - ImportReference[] imports = parsedUnit.imports; - // TypeDeclaration[] types = parsedUnit.types; - ArrayList types = parsedUnit.types; - if (types != null) { - // length = - // (currentPackage == null ? 0 : 1) - // + (imports == null ? 0 : imports.length) - // + (types == null ? 0 : types.length); - // nodes = new ASTNode[length]; - length = (imports == null ? 0 : imports.length) + types.size(); - nodes = new ASTNode[length]; - int index = 0; - // if (currentPackage != null) { - // nodes[index++] = currentPackage; - // } - if (imports != null) { - for (int i = 0, max = imports.length; i < max; i++) { - nodes[index++] = imports[i]; - } - } + if (methodDeclaration.isDefaultConstructor()) { + if (reportReferenceInfo) { + ConstructorDeclaration constructorDeclaration = (ConstructorDeclaration) methodDeclaration; + ExplicitConstructorCall constructorCall = constructorDeclaration.constructorCall; + if (constructorCall != null) { + switch (constructorCall.accessMode) { + case ExplicitConstructorCall.This: + requestor.acceptConstructorReference( + typeNames[nestedTypeIndex - 1], + constructorCall.arguments == null ? 0 + : constructorCall.arguments.length, + constructorCall.sourceStart); + break; + case ExplicitConstructorCall.Super: + case ExplicitConstructorCall.ImplicitSuper: + requestor.acceptConstructorReference( + superTypeNames[nestedTypeIndex - 1], + constructorCall.arguments == null ? 0 + : constructorCall.arguments.length, + constructorCall.sourceStart); + break; + } + } + } + return; + } + char[][] argumentTypes = null; + char[][] argumentNames = null; + Argument[] arguments = methodDeclaration.arguments; + if (arguments != null) { + int argumentLength = arguments.length; + argumentTypes = new char[argumentLength][]; + argumentNames = new char[argumentLength][]; + for (int i = 0; i < argumentLength; i++) { + argumentTypes[i] = returnTypeName(arguments[i].type); + argumentNames[i] = arguments[i].name; + } + } + char[][] thrownExceptionTypes = null; + TypeReference[] thrownExceptions = methodDeclaration.thrownExceptions; + if (thrownExceptions != null) { + int thrownExceptionLength = thrownExceptions.length; + thrownExceptionTypes = new char[thrownExceptionLength][]; + for (int i = 0; i < thrownExceptionLength; i++) { + thrownExceptionTypes[i] = CharOperation.concatWith( + thrownExceptions[i].getTypeName(), '.'); + } + } + // by default no selector end position + int selectorSourceEnd = -1; + if (methodDeclaration.isConstructor()) { + // if (methodDeclaration instanceof SourceConstructorDeclaration) { + // selectorSourceEnd = + // ((SourceConstructorDeclaration) + // methodDeclaration).selectorSourceEnd; + // } + if (isInRange) { + requestor.enterConstructor( + methodDeclaration.declarationSourceStart, + methodDeclaration.modifiers, + methodDeclaration.selector, + methodDeclaration.sourceStart, selectorSourceEnd, + argumentTypes, argumentNames, thrownExceptionTypes); + } + if (reportReferenceInfo) { + ConstructorDeclaration constructorDeclaration = (ConstructorDeclaration) methodDeclaration; + ExplicitConstructorCall constructorCall = constructorDeclaration.constructorCall; + if (constructorCall != null) { + switch (constructorCall.accessMode) { + case ExplicitConstructorCall.This: + requestor.acceptConstructorReference( + typeNames[nestedTypeIndex - 1], + constructorCall.arguments == null ? 0 + : constructorCall.arguments.length, + constructorCall.sourceStart); + break; + case ExplicitConstructorCall.Super: + case ExplicitConstructorCall.ImplicitSuper: + requestor.acceptConstructorReference( + superTypeNames[nestedTypeIndex - 1], + constructorCall.arguments == null ? 0 + : constructorCall.arguments.length, + constructorCall.sourceStart); + break; + } + } + } + this.visitIfNeeded(methodDeclaration); + if (isInRange) { + requestor + .exitConstructor(methodDeclaration.declarationSourceEnd); + } + return; + } + // if (methodDeclaration instanceof SourceMethodDeclaration) { + // selectorSourceEnd = + // ((SourceMethodDeclaration) methodDeclaration).selectorSourceEnd; + // } + if (isInRange) { + int modifiers = methodDeclaration.modifiers; + // boolean deprecated = (modifiers & AccDeprecated) != 0; // + // remember + // deprecation so as to not lose it below + requestor + .enterMethod( + methodDeclaration.declarationSourceStart, + modifiers, // deprecated + // ? + // (modifiers + // & + // AccJustFlag) + // | + // AccDeprecated + // : + // modifiers + // & + // AccJustFlag, + returnTypeName(((MethodDeclaration) methodDeclaration).returnType), + methodDeclaration.selector, + methodDeclaration.sourceStart, selectorSourceEnd, + argumentTypes, argumentNames, thrownExceptionTypes); + } + this.visitIfNeeded(methodDeclaration); - for (int i = 0, max = types.size(); i < max; i++) { - nodes[index++] = (ASTNode) types.get(i); - } - } - } else { - // TypeDeclaration[] types = parsedUnit.types; - ArrayList types = parsedUnit.types; - if (types != null) { - length = types.size(); - nodes = new ASTNode[length]; - for (int i = 0, max = types.size(); i < max; i++) { - nodes[i] = (ASTNode) types.get(i); - } - } - } + if (isInRange) { + requestor.exitMethod(methodDeclaration.declarationSourceEnd); + } + } - // notify the nodes in the syntactical order - if (nodes != null && length > 0) { - quickSort(nodes, 0, length - 1); - for (int i = 0; i < length; i++) { - ASTNode node = nodes[i]; - if (node instanceof ImportReference) { - ImportReference importRef = (ImportReference)node; -// if (node == parsedUnit.currentPackage) { -// notifySourceElementRequestor(importRef, true); -// } else { - notifySourceElementRequestor(importRef, false); -// } - } //else { instanceof TypeDeclaration - if (node instanceof TypeDeclaration) { - notifySourceElementRequestor((TypeDeclaration) node, sourceType == null); - // notifySourceElementRequestor((CompilationUnitDeclaration)node, - // sourceType == null); - } - // jsurfer - INSERT start - if (node instanceof AbstractMethodDeclaration) { - notifySourceElementRequestor((AbstractMethodDeclaration) node); - } - // jsurfer - INSERT end - } - } + /* + * Update the bodyStart of the corresponding parse node + */ + public void notifySourceElementRequestor(FieldDeclaration fieldDeclaration) { - if (sourceType == null) { - if (isInRange) { - requestor.exitCompilationUnit(parsedUnit.sourceEnd); - } - } - } + // range check + boolean isInRange = scanner.initialPosition <= fieldDeclaration.declarationSourceStart + && scanner.eofPosition >= fieldDeclaration.declarationSourceEnd; - //private void notifyAllUnknownReferences() { - // for (int i = 0, max = this.unknownRefsCounter; i < max; i++) { - // NameReference nameRef = this.unknownRefs[i]; - // if ((nameRef.bits & BindingIds.VARIABLE) != 0) { - // if ((nameRef.bits & BindingIds.TYPE) == 0) { - // // variable but not type - // if (nameRef instanceof SingleNameReference) { - // // local var or field - // requestor.acceptUnknownReference(((SingleNameReference) nameRef).token, - // nameRef.sourceStart); - // } else { - // // QualifiedNameReference - // // The last token is a field reference and the previous tokens are a - // type/variable references - // char[][] tokens = ((QualifiedNameReference) nameRef).tokens; - // int tokensLength = tokens.length; - // requestor.acceptFieldReference(tokens[tokensLength - 1], nameRef.sourceEnd - // - tokens[tokensLength - 1].length + 1); - // char[][] typeRef = new char[tokensLength - 1][]; - // System.arraycopy(tokens, 0, typeRef, 0, tokensLength - 1); - // requestor.acceptUnknownReference(typeRef, nameRef.sourceStart, - // nameRef.sourceEnd - tokens[tokensLength - 1].length); - // } - // } else { - // // variable or type - // if (nameRef instanceof SingleNameReference) { - // requestor.acceptUnknownReference(((SingleNameReference) nameRef).token, - // nameRef.sourceStart); - // } else { - // //QualifiedNameReference - // requestor.acceptUnknownReference(((QualifiedNameReference) nameRef).tokens, - // nameRef.sourceStart, nameRef.sourceEnd); - // } - // } - // } else if ((nameRef.bits & BindingIds.TYPE) != 0) { - // if (nameRef instanceof SingleNameReference) { - // requestor.acceptTypeReference(((SingleNameReference) nameRef).token, - // nameRef.sourceStart); - // } else { - // // it is a QualifiedNameReference - // requestor.acceptTypeReference(((QualifiedNameReference) nameRef).tokens, - // nameRef.sourceStart, nameRef.sourceEnd); - // } - // } - // } - //} - /* - * Update the bodyStart of the corresponding parse node - */ - public void notifySourceElementRequestor(AbstractMethodDeclaration methodDeclaration) { + if (fieldDeclaration.isField()) { + int fieldEndPosition = fieldDeclaration.declarationSourceEnd; + // if (fieldDeclaration instanceof SourceFieldDeclaration) { + // fieldEndPosition = ((SourceFieldDeclaration) + // fieldDeclaration).fieldEndPosition; + // if (fieldEndPosition == 0) { + // // use the declaration source end by default + // fieldEndPosition = fieldDeclaration.declarationSourceEnd; + // } + // } + if (isInRange) { + int modifiers = fieldDeclaration.modifiers; + boolean deprecated = (modifiers & AccDeprecated) != 0; // remember + // deprecation so + // as to not lose + // it below + requestor.enterField(fieldDeclaration.declarationSourceStart, + deprecated ? (modifiers & AccJustFlag) | AccDeprecated + : modifiers & AccJustFlag, + returnTypeName(fieldDeclaration.type), + fieldDeclaration.name, fieldDeclaration.sourceStart, + fieldDeclaration.sourceEnd); + } + // this.visitIfNeeded(fieldDeclaration); + if (isInRange) { + // requestor.exitField( + // // filter out initializations that are not a constant (simple + // check) + // (fieldDeclaration.initialization == null + // || fieldDeclaration.initialization instanceof + // ArrayInitializer + // || fieldDeclaration.initialization instanceof + // AllocationExpression + // || fieldDeclaration.initialization instanceof + // ArrayAllocationExpression + // || fieldDeclaration.initialization instanceof Assignment + // || fieldDeclaration.initialization instanceof + // ClassLiteralAccess + // || fieldDeclaration.initialization instanceof MessageSend + // || fieldDeclaration.initialization instanceof ArrayReference + // || fieldDeclaration.initialization instanceof ThisReference) + // ? + // -1 : + // fieldDeclaration.initialization.sourceStart, + // fieldEndPosition, + // fieldDeclaration.declarationSourceEnd); + requestor.exitField( + // filter out initializations that are not a constant + // (simple check) + -1, fieldEndPosition, + fieldDeclaration.declarationSourceEnd); + } - // range check - boolean isInRange = scanner.initialPosition <= methodDeclaration.declarationSourceStart - && scanner.eofPosition >= methodDeclaration.declarationSourceEnd; + } else { + // if (isInRange){ + // requestor.enterInitializer( + // fieldDeclaration.declarationSourceStart, + // fieldDeclaration.modifiers); + // } + // this.visitIfNeeded((Initializer)fieldDeclaration); + // if (isInRange){ + // requestor.exitInitializer(fieldDeclaration.declarationSourceEnd); + // } + } + } - if (methodDeclaration.isClinit()) { - this.visitIfNeeded(methodDeclaration); - return; - } + public void notifySourceElementRequestor(ImportReference importReference, + boolean isPackage) { + // if (isPackage) { + // requestor.acceptPackage( + // importReference.declarationSourceStart, + // importReference.declarationSourceEnd, + // CharOperation.concatWith(importReference.getImportName(), '.')); + // } else { + requestor.acceptImport(importReference.declarationSourceStart, + importReference.declarationSourceEnd, importReference + .getIncludeName(), // CharOperation.concatWith(importReference.getImportName(), + // '.'), + importReference.onDemand); + // } + } - if (methodDeclaration.isDefaultConstructor()) { - if (reportReferenceInfo) { - ConstructorDeclaration constructorDeclaration = (ConstructorDeclaration) methodDeclaration; - ExplicitConstructorCall constructorCall = constructorDeclaration.constructorCall; - if (constructorCall != null) { - switch (constructorCall.accessMode) { - case ExplicitConstructorCall.This : - requestor.acceptConstructorReference(typeNames[nestedTypeIndex - 1], constructorCall.arguments == null - ? 0 - : constructorCall.arguments.length, constructorCall.sourceStart); - break; - case ExplicitConstructorCall.Super : - case ExplicitConstructorCall.ImplicitSuper : - requestor.acceptConstructorReference(superTypeNames[nestedTypeIndex - 1], constructorCall.arguments == null - ? 0 - : constructorCall.arguments.length, constructorCall.sourceStart); - break; - } - } - } - return; - } - char[][] argumentTypes = null; - char[][] argumentNames = null; - Argument[] arguments = methodDeclaration.arguments; - if (arguments != null) { - int argumentLength = arguments.length; - argumentTypes = new char[argumentLength][]; - argumentNames = new char[argumentLength][]; - for (int i = 0; i < argumentLength; i++) { - argumentTypes[i] = returnTypeName(arguments[i].type); - argumentNames[i] = arguments[i].name; - } - } - char[][] thrownExceptionTypes = null; - TypeReference[] thrownExceptions = methodDeclaration.thrownExceptions; - if (thrownExceptions != null) { - int thrownExceptionLength = thrownExceptions.length; - thrownExceptionTypes = new char[thrownExceptionLength][]; - for (int i = 0; i < thrownExceptionLength; i++) { - thrownExceptionTypes[i] = CharOperation.concatWith(thrownExceptions[i].getTypeName(), '.'); - } - } - // by default no selector end position - int selectorSourceEnd = -1; - if (methodDeclaration.isConstructor()) { - // if (methodDeclaration instanceof SourceConstructorDeclaration) { - // selectorSourceEnd = - // ((SourceConstructorDeclaration) methodDeclaration).selectorSourceEnd; - // } - if (isInRange) { - requestor.enterConstructor(methodDeclaration.declarationSourceStart, methodDeclaration.modifiers, - methodDeclaration.selector, methodDeclaration.sourceStart, selectorSourceEnd, argumentTypes, argumentNames, - thrownExceptionTypes); - } - if (reportReferenceInfo) { - ConstructorDeclaration constructorDeclaration = (ConstructorDeclaration) methodDeclaration; - ExplicitConstructorCall constructorCall = constructorDeclaration.constructorCall; - if (constructorCall != null) { - switch (constructorCall.accessMode) { - case ExplicitConstructorCall.This : - requestor.acceptConstructorReference(typeNames[nestedTypeIndex - 1], constructorCall.arguments == null - ? 0 - : constructorCall.arguments.length, constructorCall.sourceStart); - break; - case ExplicitConstructorCall.Super : - case ExplicitConstructorCall.ImplicitSuper : - requestor.acceptConstructorReference(superTypeNames[nestedTypeIndex - 1], constructorCall.arguments == null - ? 0 - : constructorCall.arguments.length, constructorCall.sourceStart); - break; - } - } - } - this.visitIfNeeded(methodDeclaration); - if (isInRange) { - requestor.exitConstructor(methodDeclaration.declarationSourceEnd); - } - return; - } - // if (methodDeclaration instanceof SourceMethodDeclaration) { - // selectorSourceEnd = - // ((SourceMethodDeclaration) methodDeclaration).selectorSourceEnd; - // } - if (isInRange) { - int modifiers = methodDeclaration.modifiers; - // boolean deprecated = (modifiers & AccDeprecated) != 0; // remember - // deprecation so as to not lose it below - requestor.enterMethod(methodDeclaration.declarationSourceStart, modifiers, // deprecated - // ? - // (modifiers - // & - // AccJustFlag) - // | - // AccDeprecated - // : - // modifiers - // & - // AccJustFlag, - returnTypeName(((MethodDeclaration) methodDeclaration).returnType), methodDeclaration.selector, - methodDeclaration.sourceStart, selectorSourceEnd, argumentTypes, argumentNames, thrownExceptionTypes); - } - this.visitIfNeeded(methodDeclaration); + public void notifySourceElementRequestor(TypeDeclaration typeDeclaration, + boolean notifyTypePresence) { + // // public void notifySourceElementRequestor(ASTNode typeDeclaration, + // boolean notifyTypePresence) { - if (isInRange) { - requestor.exitMethod(methodDeclaration.declarationSourceEnd); - } - } - /* - * Update the bodyStart of the corresponding parse node - */ - public void notifySourceElementRequestor(FieldDeclaration fieldDeclaration) { + // range check + boolean isInRange = scanner.initialPosition <= typeDeclaration.declarationSourceStart + && scanner.eofPosition >= typeDeclaration.declarationSourceEnd; - // range check - boolean isInRange = scanner.initialPosition <= fieldDeclaration.declarationSourceStart - && scanner.eofPosition >= fieldDeclaration.declarationSourceEnd; + FieldDeclaration[] fields = typeDeclaration.fields; + AbstractMethodDeclaration[] methods = typeDeclaration.methods; + TypeDeclaration[] memberTypes = typeDeclaration.memberTypes; + int fieldCount = fields == null ? 0 : fields.length; + int methodCount = methods == null ? 0 : methods.length; + int memberTypeCount = memberTypes == null ? 0 : memberTypes.length; + int fieldIndex = 0; + int methodIndex = 0; + int memberTypeIndex = 0; + boolean isInterface = typeDeclaration.isInterface(); - if (fieldDeclaration.isField()) { - int fieldEndPosition = fieldDeclaration.declarationSourceEnd; - // if (fieldDeclaration instanceof SourceFieldDeclaration) { - // fieldEndPosition = ((SourceFieldDeclaration) - // fieldDeclaration).fieldEndPosition; - // if (fieldEndPosition == 0) { - // // use the declaration source end by default - // fieldEndPosition = fieldDeclaration.declarationSourceEnd; - // } - // } - if (isInRange) { - int modifiers = fieldDeclaration.modifiers; - boolean deprecated = (modifiers & AccDeprecated) != 0; // remember - // deprecation so - // as to not lose - // it below - requestor.enterField(fieldDeclaration.declarationSourceStart, deprecated - ? (modifiers & AccJustFlag) | AccDeprecated - : modifiers & AccJustFlag, returnTypeName(fieldDeclaration.type), fieldDeclaration.name, fieldDeclaration.sourceStart, - fieldDeclaration.sourceEnd); - } - // this.visitIfNeeded(fieldDeclaration); - if (isInRange) { - // requestor.exitField( - // // filter out initializations that are not a constant (simple check) - // (fieldDeclaration.initialization == null - // || fieldDeclaration.initialization instanceof ArrayInitializer - // || fieldDeclaration.initialization instanceof AllocationExpression - // || fieldDeclaration.initialization instanceof - // ArrayAllocationExpression - // || fieldDeclaration.initialization instanceof Assignment - // || fieldDeclaration.initialization instanceof ClassLiteralAccess - // || fieldDeclaration.initialization instanceof MessageSend - // || fieldDeclaration.initialization instanceof ArrayReference - // || fieldDeclaration.initialization instanceof ThisReference) ? - // -1 : - // fieldDeclaration.initialization.sourceStart, - // fieldEndPosition, - // fieldDeclaration.declarationSourceEnd); - requestor.exitField( - // filter out initializations that are not a constant (simple check) - -1, fieldEndPosition, fieldDeclaration.declarationSourceEnd); - } + if (notifyTypePresence) { + char[][] interfaceNames = null; + int superInterfacesLength = 0; + TypeReference[] superInterfaces = typeDeclaration.superInterfaces; + if (superInterfaces != null) { + superInterfacesLength = superInterfaces.length; + interfaceNames = new char[superInterfacesLength][]; + } else { + if (typeDeclaration instanceof AnonymousLocalTypeDeclaration) { + // see PR 3442 + QualifiedAllocationExpression alloc = ((AnonymousLocalTypeDeclaration) typeDeclaration).allocation; + if (alloc != null && alloc.type != null) { + superInterfaces = new TypeReference[] { ((AnonymousLocalTypeDeclaration) typeDeclaration).allocation.type }; + superInterfacesLength = 1; + interfaceNames = new char[1][]; + } + } + } + if (superInterfaces != null) { + for (int i = 0; i < superInterfacesLength; i++) { + interfaceNames[i] = CharOperation.concatWith( + superInterfaces[i].getTypeName(), '.'); + } + } + if (isInterface) { + if (isInRange) { + int modifiers = typeDeclaration.modifiers; + boolean deprecated = false; // (modifiers & AccDeprecated) + // != 0; // + // remember deprecation so as to not lose + // it below + requestor.enterInterface( + typeDeclaration.declarationSourceStart, + modifiers, // deprecated + // ? + // (modifiers + // & + // AccJustFlag) + // | + // AccDeprecated + // : + // modifiers + // & + // AccJustFlag, + typeDeclaration.name, typeDeclaration.sourceStart, + typeDeclaration.sourceEnd, interfaceNames); + } + if (nestedTypeIndex == typeNames.length) { + // need a resize + System.arraycopy(typeNames, 0, + (typeNames = new char[nestedTypeIndex * 2][]), 0, + nestedTypeIndex); + System.arraycopy(superTypeNames, 0, + (superTypeNames = new char[nestedTypeIndex * 2][]), + 0, nestedTypeIndex); + } + typeNames[nestedTypeIndex] = typeDeclaration.name; + superTypeNames[nestedTypeIndex++] = JAVA_LANG_OBJECT; + } else { + TypeReference superclass = typeDeclaration.superclass; + if (superclass == null) { + if (isInRange) { + requestor + .enterClass( + typeDeclaration.declarationSourceStart, + typeDeclaration.modifiers, + typeDeclaration.name, + typeDeclaration.sourceStart, + typeDeclaration.sourceEnd, null, + interfaceNames); + } + } else { + if (isInRange) { + requestor.enterClass( + typeDeclaration.declarationSourceStart, + typeDeclaration.modifiers, + typeDeclaration.name, + typeDeclaration.sourceStart, + typeDeclaration.sourceEnd, CharOperation + .concatWith(superclass.getTypeName(), + '.'), interfaceNames); + } + } + if (nestedTypeIndex == typeNames.length) { + // need a resize + System.arraycopy(typeNames, 0, + (typeNames = new char[nestedTypeIndex * 2][]), 0, + nestedTypeIndex); + System.arraycopy(superTypeNames, 0, + (superTypeNames = new char[nestedTypeIndex * 2][]), + 0, nestedTypeIndex); + } + typeNames[nestedTypeIndex] = typeDeclaration.name; + superTypeNames[nestedTypeIndex++] = superclass == null ? JAVA_LANG_OBJECT + : CharOperation.concatWith(superclass.getTypeName(), + '.'); + } + } + while ((fieldIndex < fieldCount) || (memberTypeIndex < memberTypeCount) + || (methodIndex < methodCount)) { + FieldDeclaration nextFieldDeclaration = null; + AbstractMethodDeclaration nextMethodDeclaration = null; + TypeDeclaration nextMemberDeclaration = null; - } else { - // if (isInRange){ - // requestor.enterInitializer( - // fieldDeclaration.declarationSourceStart, - // fieldDeclaration.modifiers); - // } - // this.visitIfNeeded((Initializer)fieldDeclaration); - // if (isInRange){ - // requestor.exitInitializer(fieldDeclaration.declarationSourceEnd); - // } - } - } - public void notifySourceElementRequestor( - ImportReference importReference, - boolean isPackage) { -// if (isPackage) { -// requestor.acceptPackage( -// importReference.declarationSourceStart, -// importReference.declarationSourceEnd, -// CharOperation.concatWith(importReference.getImportName(), '.')); -// } else { - requestor.acceptImport( - importReference.declarationSourceStart, - importReference.declarationSourceEnd, - importReference.getIncludeName(), //CharOperation.concatWith(importReference.getImportName(), '.'), - importReference.onDemand); -// } - } - public void notifySourceElementRequestor(TypeDeclaration typeDeclaration, boolean notifyTypePresence) { - //// public void notifySourceElementRequestor(ASTNode typeDeclaration, - // boolean notifyTypePresence) { + int position = Integer.MAX_VALUE; + int nextDeclarationType = -1; + if (fieldIndex < fieldCount) { + nextFieldDeclaration = fields[fieldIndex]; + if (nextFieldDeclaration.declarationSourceStart < position) { + position = nextFieldDeclaration.declarationSourceStart; + nextDeclarationType = 0; // FIELD + } + } + if (methodIndex < methodCount) { + nextMethodDeclaration = methods[methodIndex]; + if (nextMethodDeclaration.declarationSourceStart < position) { + position = nextMethodDeclaration.declarationSourceStart; + nextDeclarationType = 1; // METHOD + } + } + if (memberTypeIndex < memberTypeCount) { + nextMemberDeclaration = memberTypes[memberTypeIndex]; + if (nextMemberDeclaration.declarationSourceStart < position) { + position = nextMemberDeclaration.declarationSourceStart; + nextDeclarationType = 2; // MEMBER + } + } + switch (nextDeclarationType) { + case 0: + fieldIndex++; + notifySourceElementRequestor(nextFieldDeclaration); + break; + case 1: + methodIndex++; + notifySourceElementRequestor(nextMethodDeclaration); + break; + case 2: + memberTypeIndex++; + notifySourceElementRequestor(nextMemberDeclaration, true); + } + } + if (notifyTypePresence) { + if (isInRange) { + if (isInterface) { + requestor + .exitInterface(typeDeclaration.declarationSourceEnd); + } else { + requestor.exitClass(typeDeclaration.declarationSourceEnd); + } + } + nestedTypeIndex--; + } + } - // range check - boolean isInRange = scanner.initialPosition <= typeDeclaration.declarationSourceStart - && scanner.eofPosition >= typeDeclaration.declarationSourceEnd; + public void parseCompilationUnit(ICompilationUnit unit, int start, int end) { + // boolean needReferenceInfo) { - FieldDeclaration[] fields = typeDeclaration.fields; - AbstractMethodDeclaration[] methods = typeDeclaration.methods; - TypeDeclaration[] memberTypes = typeDeclaration.memberTypes; - int fieldCount = fields == null ? 0 : fields.length; - int methodCount = methods == null ? 0 : methods.length; - int memberTypeCount = memberTypes == null ? 0 : memberTypes.length; - int fieldIndex = 0; - int methodIndex = 0; - int memberTypeIndex = 0; - boolean isInterface = typeDeclaration.isInterface(); + // reportReferenceInfo = needReferenceInfo; + // boolean old = diet; + // if (needReferenceInfo) { + // unknownRefs = new NameReference[10]; + // unknownRefsCounter = 0; + // } - if (notifyTypePresence) { - char[][] interfaceNames = null; - int superInterfacesLength = 0; - TypeReference[] superInterfaces = typeDeclaration.superInterfaces; - if (superInterfaces != null) { - superInterfacesLength = superInterfaces.length; - interfaceNames = new char[superInterfacesLength][]; - } else { - if (typeDeclaration instanceof AnonymousLocalTypeDeclaration) { - // see PR 3442 - QualifiedAllocationExpression alloc = ((AnonymousLocalTypeDeclaration) typeDeclaration).allocation; - if (alloc != null && alloc.type != null) { - superInterfaces = new TypeReference[]{((AnonymousLocalTypeDeclaration) typeDeclaration).allocation.type}; - superInterfacesLength = 1; - interfaceNames = new char[1][]; - } - } - } - if (superInterfaces != null) { - for (int i = 0; i < superInterfacesLength; i++) { - interfaceNames[i] = CharOperation.concatWith(superInterfaces[i].getTypeName(), '.'); - } - } - if (isInterface) { - if (isInRange) { - int modifiers = typeDeclaration.modifiers; - boolean deprecated = false; //(modifiers & AccDeprecated) != 0; // - // remember deprecation so as to not lose - // it below - requestor.enterInterface(typeDeclaration.declarationSourceStart, modifiers, //deprecated - // ? - // (modifiers - // & - // AccJustFlag) - // | - // AccDeprecated - // : - // modifiers - // & - // AccJustFlag, - typeDeclaration.name, typeDeclaration.sourceStart, typeDeclaration.sourceEnd, interfaceNames); - } - if (nestedTypeIndex == typeNames.length) { - // need a resize - System.arraycopy(typeNames, 0, (typeNames = new char[nestedTypeIndex * 2][]), 0, nestedTypeIndex); - System.arraycopy(superTypeNames, 0, (superTypeNames = new char[nestedTypeIndex * 2][]), 0, nestedTypeIndex); - } - typeNames[nestedTypeIndex] = typeDeclaration.name; - superTypeNames[nestedTypeIndex++] = JAVA_LANG_OBJECT; - } else { - TypeReference superclass = typeDeclaration.superclass; - if (superclass == null) { - if (isInRange) { - requestor.enterClass(typeDeclaration.declarationSourceStart, typeDeclaration.modifiers, typeDeclaration.name, - typeDeclaration.sourceStart, typeDeclaration.sourceEnd, null, interfaceNames); - } - } else { - if (isInRange) { - requestor.enterClass(typeDeclaration.declarationSourceStart, typeDeclaration.modifiers, typeDeclaration.name, - typeDeclaration.sourceStart, typeDeclaration.sourceEnd, CharOperation.concatWith(superclass.getTypeName(), '.'), - interfaceNames); - } - } - if (nestedTypeIndex == typeNames.length) { - // need a resize - System.arraycopy(typeNames, 0, (typeNames = new char[nestedTypeIndex * 2][]), 0, nestedTypeIndex); - System.arraycopy(superTypeNames, 0, (superTypeNames = new char[nestedTypeIndex * 2][]), 0, nestedTypeIndex); - } - typeNames[nestedTypeIndex] = typeDeclaration.name; - superTypeNames[nestedTypeIndex++] = superclass == null ? JAVA_LANG_OBJECT : CharOperation.concatWith(superclass - .getTypeName(), '.'); - } - } - while ((fieldIndex < fieldCount) || (memberTypeIndex < memberTypeCount) || (methodIndex < methodCount)) { - FieldDeclaration nextFieldDeclaration = null; - AbstractMethodDeclaration nextMethodDeclaration = null; - TypeDeclaration nextMemberDeclaration = null; + try { + // diet = true; + CompilationResult compilationUnitResult = new CompilationResult( + unit, 0, 0, 10); // this.options.maxProblemsPerUnit); + CompilationUnitDeclaration parsedUnit = parse(unit, + compilationUnitResult, start, end); + // if (scanner.recordLineSeparator) { + // requestor.acceptLineSeparatorPositions(scanner.getLineEnds()); + // } + // if (this.localDeclarationVisitor != null || needReferenceInfo){ + // diet = false; + // this.getMethodBodies(parsedUnit); + // } + // this.scanner.resetTo(start, end); + // notifySourceElementRequestor(parsedUnit); + } catch (AbortCompilation e) { + } finally { + // diet = old; + } + } - int position = Integer.MAX_VALUE; - int nextDeclarationType = -1; - if (fieldIndex < fieldCount) { - nextFieldDeclaration = fields[fieldIndex]; - if (nextFieldDeclaration.declarationSourceStart < position) { - position = nextFieldDeclaration.declarationSourceStart; - nextDeclarationType = 0; // FIELD - } - } - if (methodIndex < methodCount) { - nextMethodDeclaration = methods[methodIndex]; - if (nextMethodDeclaration.declarationSourceStart < position) { - position = nextMethodDeclaration.declarationSourceStart; - nextDeclarationType = 1; // METHOD - } - } - if (memberTypeIndex < memberTypeCount) { - nextMemberDeclaration = memberTypes[memberTypeIndex]; - if (nextMemberDeclaration.declarationSourceStart < position) { - position = nextMemberDeclaration.declarationSourceStart; - nextDeclarationType = 2; // MEMBER - } - } - switch (nextDeclarationType) { - case 0 : - fieldIndex++; - notifySourceElementRequestor(nextFieldDeclaration); - break; - case 1 : - methodIndex++; - notifySourceElementRequestor(nextMethodDeclaration); - break; - case 2 : - memberTypeIndex++; - notifySourceElementRequestor(nextMemberDeclaration, true); - } - } - if (notifyTypePresence) { - if (isInRange) { - if (isInterface) { - requestor.exitInterface(typeDeclaration.declarationSourceEnd); - } else { - requestor.exitClass(typeDeclaration.declarationSourceEnd); - } - } - nestedTypeIndex--; - } - } - public void parseCompilationUnit(ICompilationUnit unit, int start, int end) { - // boolean needReferenceInfo) { + public CompilationUnitDeclaration parseCompilationUnit( + ICompilationUnit unit, boolean fullParse) { - // reportReferenceInfo = needReferenceInfo; - // boolean old = diet; - // if (needReferenceInfo) { - // unknownRefs = new NameReference[10]; - // unknownRefsCounter = 0; - // } + // boolean old = diet; + // if (fullParse) { + // unknownRefs = new NameReference[10]; + // unknownRefsCounter = 0; + // } - try { - // diet = true; - CompilationResult compilationUnitResult = new CompilationResult(unit, 0, 0, 10); //this.options.maxProblemsPerUnit); - CompilationUnitDeclaration parsedUnit = parse(unit, compilationUnitResult, start, end); - // if (scanner.recordLineSeparator) { - // requestor.acceptLineSeparatorPositions(scanner.getLineEnds()); - // } - // if (this.localDeclarationVisitor != null || needReferenceInfo){ - // diet = false; - // this.getMethodBodies(parsedUnit); - // } - // this.scanner.resetTo(start, end); - // notifySourceElementRequestor(parsedUnit); - } catch (AbortCompilation e) { - } finally { - // diet = old; - } - } - public CompilationUnitDeclaration parseCompilationUnit(ICompilationUnit unit, boolean fullParse) { + try { + // diet = true; + this.reportReferenceInfo = fullParse; + CompilationResult compilationUnitResult = new CompilationResult( + unit, 0, 0, this.options.maxProblemsPerUnit); + CompilationUnitDeclaration parsedUnit = parse(unit, + compilationUnitResult, false); + if (scanner.recordLineSeparator) { + requestor.acceptLineSeparatorPositions(scanner.getLineEnds()); + } + int initialStart = this.scanner.initialPosition; + int initialEnd = this.scanner.eofPosition; + // if (this.localDeclarationVisitor != null || fullParse){ + // diet = false; + // this.getMethodBodies(parsedUnit); + // } + this.scanner.resetTo(initialStart, initialEnd); + notifySourceElementRequestor(parsedUnit); + return parsedUnit; + } catch (AbortCompilation e) { + // ignore this exception + } finally { + // diet = old; + } + return null; + } - // boolean old = diet; - // if (fullParse) { - // unknownRefs = new NameReference[10]; - // unknownRefsCounter = 0; - // } + public CompilationUnitDeclaration parseCompletionUnit( + ICompilationUnit unit, boolean fullParse) { - try { - // diet = true; - this.reportReferenceInfo = fullParse; - CompilationResult compilationUnitResult = new CompilationResult(unit, 0, 0, this.options.maxProblemsPerUnit); - CompilationUnitDeclaration parsedUnit = parse(unit, compilationUnitResult, false); - if (scanner.recordLineSeparator) { - requestor.acceptLineSeparatorPositions(scanner.getLineEnds()); - } - int initialStart = this.scanner.initialPosition; - int initialEnd = this.scanner.eofPosition; - // if (this.localDeclarationVisitor != null || fullParse){ - // diet = false; - // this.getMethodBodies(parsedUnit); - // } - this.scanner.resetTo(initialStart, initialEnd); - notifySourceElementRequestor(parsedUnit); - return parsedUnit; - } catch (AbortCompilation e) { - // ignore this exception - } finally { - // diet = old; - } - return null; - } + // boolean old = diet; + // if (fullParse) { + // unknownRefs = new NameReference[10]; + // unknownRefsCounter = 0; + // } - public CompilationUnitDeclaration parseCompletionUnit(ICompilationUnit unit, boolean fullParse) { + try { + // diet = true; + this.reportReferenceInfo = fullParse; + CompilationResult compilationUnitResult = new CompilationResult( + unit, 0, 0, this.options.maxProblemsPerUnit); + CompilationUnitDeclaration parsedUnit = parse(unit, + compilationUnitResult, false); + // if (scanner.recordLineSeparator) { + // requestor.acceptLineSeparatorPositions(scanner.getLineEnds()); + // } + // int initialStart = this.scanner.initialPosition; + // int initialEnd = this.scanner.eofPosition; + // // if (this.localDeclarationVisitor != null || fullParse){ + // // diet = false; + // // this.getMethodBodies(parsedUnit); + // // } + // this.scanner.resetTo(initialStart, initialEnd); + // notifySourceElementRequestor(parsedUnit); + return parsedUnit; + } catch (AbortCompilation e) { + // ignore this exception + } finally { + // diet = old; + } + return null; + } - // boolean old = diet; - // if (fullParse) { - // unknownRefs = new NameReference[10]; - // unknownRefsCounter = 0; - // } + // public void parseTypeMemberDeclarations( + // ISourceType sourceType, + // ICompilationUnit sourceUnit, + // int start, + // int end, + // boolean needReferenceInfo) { + // boolean old = diet; + // if (needReferenceInfo) { + // unknownRefs = new NameReference[10]; + // unknownRefsCounter = 0; + // } + // + // try { + // diet = !needReferenceInfo; + // reportReferenceInfo = needReferenceInfo; + // CompilationResult compilationUnitResult = + // new CompilationResult(sourceUnit, 0, 0, this.options.maxProblemsPerUnit); + // CompilationUnitDeclaration unit = + // SourceTypeConverter.buildCompilationUnit( + // new ISourceType[]{sourceType}, + // false, // no need for field and methods + // false, // no need for member types + // false, // no need for field initialization + // problemReporter(), + // compilationUnitResult); + // if ((unit == null) || (unit.types == null) || (unit.types.length != 1)) + // return; + // this.sourceType = sourceType; + // try { + // /* automaton initialization */ + // initialize(); + // goForClassBodyDeclarations(); + // /* scanner initialization */ + // scanner.setSource(sourceUnit.getContents()); + // scanner.resetTo(start, end); + // /* unit creation */ + // referenceContext = compilationUnit = unit; + // /* initialize the astStacl */ + // // the compilationUnitDeclaration should contain exactly one type + // pushOnAstStack(unit.types[0]); + // /* run automaton */ + // parse(); + // notifySourceElementRequestor(unit); + // } finally { + // unit = compilationUnit; + // compilationUnit = null; // reset parser + // } + // } catch (AbortCompilation e) { + // } finally { + // if (scanner.recordLineSeparator) { + // requestor.acceptLineSeparatorPositions(scanner.getLineEnds()); + // } + // diet = old; + // } + // } + // + // public void parseTypeMemberDeclarations( + // char[] contents, + // int start, + // int end) { + // + // boolean old = diet; + // + // try { + // diet = true; + // + // /* automaton initialization */ + // initialize(); + // goForClassBodyDeclarations(); + // /* scanner initialization */ + // scanner.setSource(contents); + // scanner.recordLineSeparator = false; + // scanner.taskTags = null; + // scanner.taskPriorities = null; + // scanner.resetTo(start, end); + // + // /* unit creation */ + // referenceContext = null; + // + // /* initialize the astStacl */ + // // the compilationUnitDeclaration should contain exactly one type + // /* run automaton */ + // parse(); + // notifySourceElementRequestor((CompilationUnitDeclaration)null); + // } catch (AbortCompilation e) { + // } finally { + // diet = old; + // } + // } + /** + * Sort the given ast nodes by their positions. + */ + private static void quickSort(ASTNode[] sortedCollection, int left, + int right) { + int original_left = left; + int original_right = right; + ASTNode mid = sortedCollection[(left + right) / 2]; + do { + while (sortedCollection[left].sourceStart < mid.sourceStart) { + left++; + } + while (mid.sourceStart < sortedCollection[right].sourceStart) { + right--; + } + if (left <= right) { + ASTNode tmp = sortedCollection[left]; + sortedCollection[left] = sortedCollection[right]; + sortedCollection[right] = tmp; + left++; + right--; + } + } while (left <= right); + if (original_left < right) { + quickSort(sortedCollection, original_left, right); + } + if (left < original_right) { + quickSort(sortedCollection, left, original_right); + } + } - try { - // diet = true; - this.reportReferenceInfo = fullParse; - CompilationResult compilationUnitResult = new CompilationResult(unit, 0, 0, this.options.maxProblemsPerUnit); - CompilationUnitDeclaration parsedUnit = parse(unit, compilationUnitResult, false); -// if (scanner.recordLineSeparator) { -// requestor.acceptLineSeparatorPositions(scanner.getLineEnds()); -// } -// int initialStart = this.scanner.initialPosition; -// int initialEnd = this.scanner.eofPosition; -// // if (this.localDeclarationVisitor != null || fullParse){ -// // diet = false; -// // this.getMethodBodies(parsedUnit); -// // } -// this.scanner.resetTo(initialStart, initialEnd); -// notifySourceElementRequestor(parsedUnit); - return parsedUnit; - } catch (AbortCompilation e) { - // ignore this exception - } finally { - // diet = old; - } - return null; - } - //public void parseTypeMemberDeclarations( - // ISourceType sourceType, - // ICompilationUnit sourceUnit, - // int start, - // int end, - // boolean needReferenceInfo) { - // boolean old = diet; - // if (needReferenceInfo) { - // unknownRefs = new NameReference[10]; - // unknownRefsCounter = 0; - // } - // - // try { - // diet = !needReferenceInfo; - // reportReferenceInfo = needReferenceInfo; - // CompilationResult compilationUnitResult = - // new CompilationResult(sourceUnit, 0, 0, this.options.maxProblemsPerUnit); - // CompilationUnitDeclaration unit = - // SourceTypeConverter.buildCompilationUnit( - // new ISourceType[]{sourceType}, - // false, // no need for field and methods - // false, // no need for member types - // false, // no need for field initialization - // problemReporter(), - // compilationUnitResult); - // if ((unit == null) || (unit.types == null) || (unit.types.length != 1)) - // return; - // this.sourceType = sourceType; - // try { - // /* automaton initialization */ - // initialize(); - // goForClassBodyDeclarations(); - // /* scanner initialization */ - // scanner.setSource(sourceUnit.getContents()); - // scanner.resetTo(start, end); - // /* unit creation */ - // referenceContext = compilationUnit = unit; - // /* initialize the astStacl */ - // // the compilationUnitDeclaration should contain exactly one type - // pushOnAstStack(unit.types[0]); - // /* run automaton */ - // parse(); - // notifySourceElementRequestor(unit); - // } finally { - // unit = compilationUnit; - // compilationUnit = null; // reset parser - // } - // } catch (AbortCompilation e) { - // } finally { - // if (scanner.recordLineSeparator) { - // requestor.acceptLineSeparatorPositions(scanner.getLineEnds()); - // } - // diet = old; - // } - //} - // - //public void parseTypeMemberDeclarations( - // char[] contents, - // int start, - // int end) { - // - // boolean old = diet; - // - // try { - // diet = true; - // - // /* automaton initialization */ - // initialize(); - // goForClassBodyDeclarations(); - // /* scanner initialization */ - // scanner.setSource(contents); - // scanner.recordLineSeparator = false; - // scanner.taskTags = null; - // scanner.taskPriorities = null; - // scanner.resetTo(start, end); - // - // /* unit creation */ - // referenceContext = null; - // - // /* initialize the astStacl */ - // // the compilationUnitDeclaration should contain exactly one type - // /* run automaton */ - // parse(); - // notifySourceElementRequestor((CompilationUnitDeclaration)null); - // } catch (AbortCompilation e) { - // } finally { - // diet = old; - // } - //} - /** - * Sort the given ast nodes by their positions. - */ - private static void quickSort(ASTNode[] sortedCollection, int left, int right) { - int original_left = left; - int original_right = right; - ASTNode mid = sortedCollection[(left + right) / 2]; - do { - while (sortedCollection[left].sourceStart < mid.sourceStart) { - left++; - } - while (mid.sourceStart < sortedCollection[right].sourceStart) { - right--; - } - if (left <= right) { - ASTNode tmp = sortedCollection[left]; - sortedCollection[left] = sortedCollection[right]; - sortedCollection[right] = tmp; - left++; - right--; - } - } while (left <= right); - if (original_left < right) { - quickSort(sortedCollection, original_left, right); - } - if (left < original_right) { - quickSort(sortedCollection, left, original_right); - } - } - /* - * Answer a char array representation of the type name formatted like: - type - * name + dimensions Example: "A[][]".toCharArray() - * "java.lang.String".toCharArray() - */ - private char[] returnTypeName(TypeReference type) { - if (type == null) - return null; - int dimension = type.dimensions(); - if (dimension != 0) { - char[] dimensionsArray = new char[dimension * 2]; - for (int i = 0; i < dimension; i++) { - dimensionsArray[i * 2] = '['; - dimensionsArray[(i * 2) + 1] = ']'; - } - return CharOperation.concat(CharOperation.concatWith(type.getTypeName(), '.'), dimensionsArray); - } - return CharOperation.concatWith(type.getTypeName(), '.'); - } + /* + * Answer a char array representation of the type name formatted like: - + * type name + dimensions Example: "A[][]".toCharArray() + * "java.lang.String".toCharArray() + */ + private char[] returnTypeName(TypeReference type) { + if (type == null) + return null; + int dimension = type.dimensions(); + if (dimension != 0) { + char[] dimensionsArray = new char[dimension * 2]; + for (int i = 0; i < dimension; i++) { + dimensionsArray[i * 2] = '['; + dimensionsArray[(i * 2) + 1] = ']'; + } + return CharOperation.concat(CharOperation.concatWith(type + .getTypeName(), '.'), dimensionsArray); + } + return CharOperation.concatWith(type.getTypeName(), '.'); + } - public void addUnknownRef(NameReference nameRef) { - if (this.unknownRefs.length == this.unknownRefsCounter) { - // resize - System.arraycopy(this.unknownRefs, 0, (this.unknownRefs = new NameReference[this.unknownRefsCounter * 2]), 0, - this.unknownRefsCounter); - } - this.unknownRefs[this.unknownRefsCounter++] = nameRef; - } + public void addUnknownRef(NameReference nameRef) { + if (this.unknownRefs.length == this.unknownRefsCounter) { + // resize + System + .arraycopy( + this.unknownRefs, + 0, + (this.unknownRefs = new NameReference[this.unknownRefsCounter * 2]), + 0, this.unknownRefsCounter); + } + this.unknownRefs[this.unknownRefsCounter++] = nameRef; + } - private void visitIfNeeded(AbstractMethodDeclaration method) { - if (this.localDeclarationVisitor != null && (method.bits & ASTNode.HasLocalTypeMASK) != 0) { - if (method.statements != null) { - int statementsLength = method.statements.length; - for (int i = 0; i < statementsLength; i++) - method.statements[i].traverse(this.localDeclarationVisitor, method.scope); - } - } - } + private void visitIfNeeded(AbstractMethodDeclaration method) { + if (this.localDeclarationVisitor != null + && (method.bits & ASTNode.HasLocalTypeMASK) != 0) { + if (method.statements != null) { + int statementsLength = method.statements.length; + for (int i = 0; i < statementsLength; i++) + method.statements[i].traverse(this.localDeclarationVisitor, + method.scope); + } + } + } - //private void visitIfNeeded(FieldDeclaration field) { - // if (this.localDeclarationVisitor != null - // && (field.bits & ASTNode.HasLocalTypeMASK) != 0) { - // if (field.initialization != null) { - // field.initialization.traverse(this.localDeclarationVisitor, null); - // } - // } - //} - // - //private void visitIfNeeded(Initializer initializer) { - // if (this.localDeclarationVisitor != null - // && (initializer.bits & ASTNode.HasLocalTypeMASK) != 0) { - // if (initializer.block != null) { - // initializer.block.traverse(this.localDeclarationVisitor, null); - // } - // } - //} - // - //protected void reportSyntaxError(int act, int currentKind, int - // stateStackTop) { - // if (compilationUnit == null) return; - // super.reportSyntaxError(act, currentKind,stateStackTop); - //} - protected CompilationUnitDeclaration endParse(int act) { - // if (sourceType != null) { - // if (sourceType.isInterface()) { - // consumeInterfaceDeclaration(); - // } else { - // consumeClassDeclaration(); - // } - // } - if (compilationUnit != null) { - CompilationUnitDeclaration result = super.endParse(act); - return result; - } else { - return null; - } - } + // private void visitIfNeeded(FieldDeclaration field) { + // if (this.localDeclarationVisitor != null + // && (field.bits & ASTNode.HasLocalTypeMASK) != 0) { + // if (field.initialization != null) { + // field.initialization.traverse(this.localDeclarationVisitor, null); + // } + // } + // } + // + // private void visitIfNeeded(Initializer initializer) { + // if (this.localDeclarationVisitor != null + // && (initializer.bits & ASTNode.HasLocalTypeMASK) != 0) { + // if (initializer.block != null) { + // initializer.block.traverse(this.localDeclarationVisitor, null); + // } + // } + // } + // + // protected void reportSyntaxError(int act, int currentKind, int + // stateStackTop) { + // if (compilationUnit == null) return; + // super.reportSyntaxError(act, currentKind,stateStackTop); + // } + protected CompilationUnitDeclaration endParse(int act) { + // if (sourceType != null) { + // if (sourceType.isInterface()) { + // consumeInterfaceDeclaration(); + // } else { + // consumeClassDeclaration(); + // } + // } + if (compilationUnit != null) { + CompilationUnitDeclaration result = super.endParse(act); + return result; + } else { + return null; + } + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AND_AND_Expression.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AND_AND_Expression.java index ea4128a..4efd729 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AND_AND_Expression.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AND_AND_Expression.java @@ -16,285 +16,298 @@ import net.sourceforge.phpdt.internal.compiler.flow.FlowInfo; import net.sourceforge.phpdt.internal.compiler.impl.Constant; import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; -//dedicated treatment for the && +// dedicated treatment for the && public class AND_AND_Expression extends BinaryExpression { int rightInitStateIndex = -1; + int mergedInitStateIndex = -1; public AND_AND_Expression(Expression left, Expression right, int operator) { super(left, right, operator); } - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { Constant cst = this.left.optimizedBooleanConstant(); - boolean isLeftOptimizedTrue = cst != NotAConstant && cst.booleanValue() == true; - boolean isLeftOptimizedFalse = cst != NotAConstant && cst.booleanValue() == false; + boolean isLeftOptimizedTrue = cst != NotAConstant + && cst.booleanValue() == true; + boolean isLeftOptimizedFalse = cst != NotAConstant + && cst.booleanValue() == false; if (isLeftOptimizedTrue) { // TRUE && anything - // need to be careful of scenario: - // (x && y) && !z, if passing the left info to the right, it would be swapped by the ! - FlowInfo mergedInfo = left.analyseCode(currentScope, flowContext, flowInfo).unconditionalInits(); - mergedInfo = right.analyseCode(currentScope, flowContext, mergedInfo); - mergedInitStateIndex = - currentScope.methodScope().recordInitializationStates(mergedInfo); + // need to be careful of scenario: + // (x && y) && !z, if passing the left info to the right, it would + // be swapped by the ! + FlowInfo mergedInfo = left.analyseCode(currentScope, flowContext, + flowInfo).unconditionalInits(); + mergedInfo = right.analyseCode(currentScope, flowContext, + mergedInfo); + mergedInitStateIndex = currentScope.methodScope() + .recordInitializationStates(mergedInfo); return mergedInfo; } - - FlowInfo leftInfo = left.analyseCode(currentScope, flowContext, flowInfo); - // need to be careful of scenario: - // (x && y) && !z, if passing the left info to the right, it would be swapped by the ! - FlowInfo rightInfo = leftInfo.initsWhenTrue().unconditionalInits().copy(); - rightInitStateIndex = - currentScope.methodScope().recordInitializationStates(rightInfo); + + FlowInfo leftInfo = left.analyseCode(currentScope, flowContext, + flowInfo); + // need to be careful of scenario: + // (x && y) && !z, if passing the left info to the right, it would be + // swapped by the ! + FlowInfo rightInfo = leftInfo.initsWhenTrue().unconditionalInits() + .copy(); + rightInitStateIndex = currentScope.methodScope() + .recordInitializationStates(rightInfo); int previousMode = rightInfo.reachMode(); - if (isLeftOptimizedFalse){ - rightInfo.setReachMode(FlowInfo.UNREACHABLE); + if (isLeftOptimizedFalse) { + rightInfo.setReachMode(FlowInfo.UNREACHABLE); } rightInfo = right.analyseCode(currentScope, flowContext, rightInfo); FlowInfo trueMergedInfo = rightInfo.initsWhenTrue().copy(); - rightInfo.setReachMode(previousMode); // reset after trueMergedInfo got extracted - - FlowInfo mergedInfo = - FlowInfo.conditional( - trueMergedInfo, - leftInfo.initsWhenFalse().copy().unconditionalInits().mergedWith( - rightInfo.initsWhenFalse().copy().unconditionalInits())); - mergedInitStateIndex = - currentScope.methodScope().recordInitializationStates(mergedInfo); + rightInfo.setReachMode(previousMode); // reset after trueMergedInfo + // got extracted + + FlowInfo mergedInfo = FlowInfo + .conditional(trueMergedInfo, leftInfo.initsWhenFalse().copy() + .unconditionalInits().mergedWith( + rightInfo.initsWhenFalse().copy() + .unconditionalInits())); + mergedInitStateIndex = currentScope.methodScope() + .recordInitializationStates(mergedInfo); return mergedInfo; } /** * Code generation for a binary operation */ -// public void generateCode( -// BlockScope currentScope, -// CodeStream codeStream, -// boolean valueRequired) { -// -// int pc = codeStream.position; -// Label falseLabel, endLabel; -// if (constant != Constant.NotAConstant) { -// // inlined value -// if (valueRequired) -// codeStream.generateConstant(constant, implicitConversion); -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// return; -// } -// bits |= OnlyValueRequiredMASK; -// generateOptimizedBoolean( -// currentScope, -// codeStream, -// null, -// (falseLabel = new Label(codeStream)), -// valueRequired); -// /* improving code gen for such a case: boolean b = i < 0 && false -// * since the label has never been used, we have the inlined value on the stack. */ -// if (falseLabel.hasForwardReferences()) { -// if (valueRequired) { -// codeStream.iconst_1(); -// if ((bits & ValueForReturnMASK) != 0) { -// codeStream.ireturn(); -// falseLabel.place(); -// codeStream.iconst_0(); -// } else { -// codeStream.goto_(endLabel = new Label(codeStream)); -// codeStream.decrStackSize(1); -// falseLabel.place(); -// codeStream.iconst_0(); -// endLabel.place(); -// } -// } else { -// falseLabel.place(); -// } -// } -// if (valueRequired) { -// codeStream.generateImplicitConversion(implicitConversion); -// } -// // reposition the endPC -// codeStream.updateLastRecordedEndPC(codeStream.position); -// } - + // public void generateCode( + // BlockScope currentScope, + // CodeStream codeStream, + // boolean valueRequired) { + // + // int pc = codeStream.position; + // Label falseLabel, endLabel; + // if (constant != Constant.NotAConstant) { + // // inlined value + // if (valueRequired) + // codeStream.generateConstant(constant, implicitConversion); + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // return; + // } + // bits |= OnlyValueRequiredMASK; + // generateOptimizedBoolean( + // currentScope, + // codeStream, + // null, + // (falseLabel = new Label(codeStream)), + // valueRequired); + // /* improving code gen for such a case: boolean b = i < 0 && false + // * since the label has never been used, we have the inlined value on the + // stack. */ + // if (falseLabel.hasForwardReferences()) { + // if (valueRequired) { + // codeStream.iconst_1(); + // if ((bits & ValueForReturnMASK) != 0) { + // codeStream.ireturn(); + // falseLabel.place(); + // codeStream.iconst_0(); + // } else { + // codeStream.goto_(endLabel = new Label(codeStream)); + // codeStream.decrStackSize(1); + // falseLabel.place(); + // codeStream.iconst_0(); + // endLabel.place(); + // } + // } else { + // falseLabel.place(); + // } + // } + // if (valueRequired) { + // codeStream.generateImplicitConversion(implicitConversion); + // } + // // reposition the endPC + // codeStream.updateLastRecordedEndPC(codeStream.position); + // } /** - * Boolean operator code generation - * Optimized operations are: && + * Boolean operator code generation Optimized operations are: && */ -// public void generateOptimizedBoolean( -// BlockScope currentScope, -// CodeStream codeStream, -// Label trueLabel, -// Label falseLabel, -// boolean valueRequired) { -// -// if (constant != Constant.NotAConstant) { -// super.generateOptimizedBoolean(currentScope, codeStream, trueLabel, falseLabel, valueRequired); -// return; -// } -// Constant condConst; -// if ((condConst = left.optimizedBooleanConstant()) != NotAConstant) { -// if (condConst.booleanValue() == true) { -// // && x -// left.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// false); -// if (rightInitStateIndex != -1) { -// codeStream.addDefinitelyAssignedVariables(currentScope, rightInitStateIndex); -// } -// if ((bits & OnlyValueRequiredMASK) != 0) { -// right.generateCode(currentScope, codeStream, valueRequired); -// } else { -// right.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// valueRequired); -// } -// } else { -// // && x -// left.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// false); -// if (valueRequired) { -// if ((bits & OnlyValueRequiredMASK) != 0) { -// codeStream.iconst_0(); -// } else { -// if (falseLabel != null) { -// // implicit falling through the TRUE case -// codeStream.goto_(falseLabel); -// } -// } -// } -// // reposition the endPC -// codeStream.updateLastRecordedEndPC(codeStream.position); -// } -// if (mergedInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// mergedInitStateIndex); -// } -// return; -// } -// if ((condConst = right.optimizedBooleanConstant()) != NotAConstant) { -// if (condConst.booleanValue() == true) { -// // x && -// if ((bits & OnlyValueRequiredMASK) != 0) { -// left.generateCode(currentScope, codeStream, valueRequired); -// } else { -// left.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// valueRequired); -// } -// if (rightInitStateIndex != -1) { -// codeStream.addDefinitelyAssignedVariables(currentScope, rightInitStateIndex); -// } -// right.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// false); -// } else { -// // x && -// Label internalTrueLabel = new Label(codeStream); -// left.generateOptimizedBoolean( -// currentScope, -// codeStream, -// internalTrueLabel, // will be false in the end -// null, -// false); -// if (rightInitStateIndex != -1) { -// codeStream.addDefinitelyAssignedVariables(currentScope, rightInitStateIndex); -// } -// internalTrueLabel.place(); -// right.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// false); -// if (valueRequired) { -// if ((bits & OnlyValueRequiredMASK) != 0) { -// codeStream.iconst_0(); -// } else { -// if (falseLabel != null) { -// // implicit falling through the TRUE case -// codeStream.goto_(falseLabel); -// } -// } -// } -// // reposition the endPC -// codeStream.updateLastRecordedEndPC(codeStream.position); -// } -// if (mergedInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// mergedInitStateIndex); -// } -// return; -// } -// // default case -// if (falseLabel == null) { -// if (trueLabel != null) { -// // implicit falling through the FALSE case -// Label internalFalseLabel = new Label(codeStream); -// left.generateOptimizedBoolean( -// currentScope, -// codeStream, -// null, -// internalFalseLabel, -// true); -// if (rightInitStateIndex != -1) { -// codeStream.addDefinitelyAssignedVariables(currentScope, rightInitStateIndex); -// } -// right.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// null, -// valueRequired); -// internalFalseLabel.place(); -// } -// } else { -// // implicit falling through the TRUE case -// if (trueLabel == null) { -// left.generateOptimizedBoolean(currentScope, codeStream, null, falseLabel, true); -// if (rightInitStateIndex != -1) { -// codeStream.addDefinitelyAssignedVariables(currentScope, rightInitStateIndex); -// } -// right.generateOptimizedBoolean( -// currentScope, -// codeStream, -// null, -// falseLabel, -// valueRequired); -// } else { -// // no implicit fall through TRUE/FALSE --> should never occur -// } -// } -// if (mergedInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// mergedInitStateIndex); -// } -// } - + // public void generateOptimizedBoolean( + // BlockScope currentScope, + // CodeStream codeStream, + // Label trueLabel, + // Label falseLabel, + // boolean valueRequired) { + // + // if (constant != Constant.NotAConstant) { + // super.generateOptimizedBoolean(currentScope, codeStream, trueLabel, + // falseLabel, valueRequired); + // return; + // } + // Constant condConst; + // if ((condConst = left.optimizedBooleanConstant()) != NotAConstant) { + // if (condConst.booleanValue() == true) { + // // && x + // left.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // false); + // if (rightInitStateIndex != -1) { + // codeStream.addDefinitelyAssignedVariables(currentScope, + // rightInitStateIndex); + // } + // if ((bits & OnlyValueRequiredMASK) != 0) { + // right.generateCode(currentScope, codeStream, valueRequired); + // } else { + // right.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // valueRequired); + // } + // } else { + // // && x + // left.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // false); + // if (valueRequired) { + // if ((bits & OnlyValueRequiredMASK) != 0) { + // codeStream.iconst_0(); + // } else { + // if (falseLabel != null) { + // // implicit falling through the TRUE case + // codeStream.goto_(falseLabel); + // } + // } + // } + // // reposition the endPC + // codeStream.updateLastRecordedEndPC(codeStream.position); + // } + // if (mergedInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // mergedInitStateIndex); + // } + // return; + // } + // if ((condConst = right.optimizedBooleanConstant()) != NotAConstant) { + // if (condConst.booleanValue() == true) { + // // x && + // if ((bits & OnlyValueRequiredMASK) != 0) { + // left.generateCode(currentScope, codeStream, valueRequired); + // } else { + // left.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // valueRequired); + // } + // if (rightInitStateIndex != -1) { + // codeStream.addDefinitelyAssignedVariables(currentScope, + // rightInitStateIndex); + // } + // right.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // false); + // } else { + // // x && + // Label internalTrueLabel = new Label(codeStream); + // left.generateOptimizedBoolean( + // currentScope, + // codeStream, + // internalTrueLabel, // will be false in the end + // null, + // false); + // if (rightInitStateIndex != -1) { + // codeStream.addDefinitelyAssignedVariables(currentScope, + // rightInitStateIndex); + // } + // internalTrueLabel.place(); + // right.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // false); + // if (valueRequired) { + // if ((bits & OnlyValueRequiredMASK) != 0) { + // codeStream.iconst_0(); + // } else { + // if (falseLabel != null) { + // // implicit falling through the TRUE case + // codeStream.goto_(falseLabel); + // } + // } + // } + // // reposition the endPC + // codeStream.updateLastRecordedEndPC(codeStream.position); + // } + // if (mergedInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // mergedInitStateIndex); + // } + // return; + // } + // // default case + // if (falseLabel == null) { + // if (trueLabel != null) { + // // implicit falling through the FALSE case + // Label internalFalseLabel = new Label(codeStream); + // left.generateOptimizedBoolean( + // currentScope, + // codeStream, + // null, + // internalFalseLabel, + // true); + // if (rightInitStateIndex != -1) { + // codeStream.addDefinitelyAssignedVariables(currentScope, + // rightInitStateIndex); + // } + // right.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // null, + // valueRequired); + // internalFalseLabel.place(); + // } + // } else { + // // implicit falling through the TRUE case + // if (trueLabel == null) { + // left.generateOptimizedBoolean(currentScope, codeStream, null, falseLabel, + // true); + // if (rightInitStateIndex != -1) { + // codeStream.addDefinitelyAssignedVariables(currentScope, + // rightInitStateIndex); + // } + // right.generateOptimizedBoolean( + // currentScope, + // codeStream, + // null, + // falseLabel, + // valueRequired); + // } else { + // // no implicit fall through TRUE/FALSE --> should never occur + // } + // } + // if (mergedInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // mergedInitStateIndex); + // } + // } public boolean isCompactableOperation() { return false; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ASTNode.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ASTNode.java index 7c429a6..a575451 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ASTNode.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ASTNode.java @@ -24,91 +24,171 @@ import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; import net.sourceforge.phpdt.internal.compiler.lookup.TypeConstants; import net.sourceforge.phpdt.internal.compiler.lookup.TypeIds; +public abstract class ASTNode implements BaseTypes, CompilerModifiers, + TypeConstants, TypeIds { -public abstract class ASTNode implements BaseTypes, CompilerModifiers, TypeConstants, TypeIds { - public int sourceStart, sourceEnd; - //some global provision for the hierarchy + // some global provision for the hierarchy public final static Constant NotAConstant = Constant.NotAConstant; - // storage for internal flags (32 bits) BIT USAGE - public final static int Bit1 = 0x1; // return type (operators) | name reference kind (name ref) | add assertion (type decl) - public final static int Bit2 = 0x2; // return type (operators) | name reference kind (name ref) | has local type (type, method, field decl) - public final static int Bit3 = 0x4; // return type (operators) | name reference kind (name ref) | implicit this (this ref) - public final static int Bit4 = 0x8; // return type (operators) | first assignment to local (local decl) - public final static int Bit5 = 0x10; // value for return (binary expression) | - public final static int Bit6 = 0x20; // depth (name ref, msg) | only value required (binary expression) - public final static int Bit7 = 0x40; // depth (name ref, msg) | operator (operators) - public final static int Bit8 = 0x80; // depth (name ref, msg) | operator (operators) - public final static int Bit9 = 0x100; // depth (name ref, msg) | operator (operators) - public final static int Bit10= 0x200; // depth (name ref, msg) | operator (operators) - public final static int Bit11 = 0x400; // depth (name ref, msg) | operator (operators) - public final static int Bit12 = 0x800; // depth (name ref, msg) | operator (operators) - public final static int Bit13 = 0x1000; // depth (name ref, msg) - public final static int Bit14 = 0x2000; // assigned (reference lhs) - public final static int Bit15 = 0x4000; - public final static int Bit16 = 0x8000; - public final static int Bit17 = 0x10000; - public final static int Bit18 = 0x20000; - public final static int Bit19 = 0x40000; - public final static int Bit20 = 0x80000; - public final static int Bit21 = 0x100000; - public final static int Bit22 = 0x200000; // parenthesis count (expression) - public final static int Bit23 = 0x400000; // parenthesis count (expression) - public final static int Bit24 = 0x800000; // parenthesis count (expression) - public final static int Bit25 = 0x1000000; // parenthesis count (expression) - public final static int Bit26 = 0x2000000; // parenthesis count (expression) - public final static int Bit27 = 0x4000000; // parenthesis count (expression) - public final static int Bit28 = 0x8000000; // parenthesis count (expression) - public final static int Bit29 = 0x10000000; // parenthesis count (expression) - public final static int Bit30 = 0x20000000; // assignment with no effect (assignment) - public final static int Bit31 = 0x40000000; // local declaration reachable (local decl) - public final static int Bit32 = 0x80000000; // reachable (statement) - - public int bits = IsReachableMASK; // reachable by default - - // for operators - public static final int ReturnTypeIDMASK = Bit1|Bit2|Bit3|Bit4; - public static final int OperatorSHIFT = 6; // Bit7 -> Bit12 - public static final int OperatorMASK = Bit7|Bit8|Bit9|Bit10|Bit11|Bit12; // 6 bits for operator ID + // storage for internal flags (32 bits) BIT USAGE + public final static int Bit1 = 0x1; // return type (operators) | name + // reference kind (name ref) | add + // assertion (type decl) + + public final static int Bit2 = 0x2; // return type (operators) | name + // reference kind (name ref) | has local + // type (type, method, field decl) + + public final static int Bit3 = 0x4; // return type (operators) | name + // reference kind (name ref) | implicit + // this (this ref) + + public final static int Bit4 = 0x8; // return type (operators) | first + // assignment to local (local decl) + + public final static int Bit5 = 0x10; // value for return (binary + // expression) | + + public final static int Bit6 = 0x20; // depth (name ref, msg) | only + // value required (binary + // expression) + + public final static int Bit7 = 0x40; // depth (name ref, msg) | operator + // (operators) + + public final static int Bit8 = 0x80; // depth (name ref, msg) | operator + // (operators) + + public final static int Bit9 = 0x100; // depth (name ref, msg) | operator + // (operators) + + public final static int Bit10 = 0x200; // depth (name ref, msg) | operator + // (operators) + + public final static int Bit11 = 0x400; // depth (name ref, msg) | operator + // (operators) + + public final static int Bit12 = 0x800; // depth (name ref, msg) | operator + // (operators) + + public final static int Bit13 = 0x1000; // depth (name ref, msg) + + public final static int Bit14 = 0x2000; // assigned (reference lhs) + + public final static int Bit15 = 0x4000; + + public final static int Bit16 = 0x8000; + + public final static int Bit17 = 0x10000; + + public final static int Bit18 = 0x20000; + + public final static int Bit19 = 0x40000; + + public final static int Bit20 = 0x80000; + + public final static int Bit21 = 0x100000; + + public final static int Bit22 = 0x200000; // parenthesis count + // (expression) + + public final static int Bit23 = 0x400000; // parenthesis count + // (expression) + + public final static int Bit24 = 0x800000; // parenthesis count + // (expression) + + public final static int Bit25 = 0x1000000; // parenthesis count + // (expression) + + public final static int Bit26 = 0x2000000; // parenthesis count + // (expression) + + public final static int Bit27 = 0x4000000; // parenthesis count + // (expression) + + public final static int Bit28 = 0x8000000; // parenthesis count + // (expression) + + public final static int Bit29 = 0x10000000; // parenthesis count + // (expression) + + public final static int Bit30 = 0x20000000; // assignment with no effect + // (assignment) + + public final static int Bit31 = 0x40000000; // local declaration reachable + // (local decl) + + public final static int Bit32 = 0x80000000; // reachable (statement) + + public int bits = IsReachableMASK; // reachable by default + + // for operators + public static final int ReturnTypeIDMASK = Bit1 | Bit2 | Bit3 | Bit4; + + public static final int OperatorSHIFT = 6; // Bit7 -> Bit12 + + public static final int OperatorMASK = Bit7 | Bit8 | Bit9 | Bit10 | Bit11 + | Bit12; // 6 bits for operator ID // for binary expressions - public static final int ValueForReturnMASK = Bit5; - public static final int OnlyValueRequiredMASK = Bit6; + public static final int ValueForReturnMASK = Bit5; + + public static final int OnlyValueRequiredMASK = Bit6; + + // for name references + public static final int RestrictiveFlagMASK = Bit1 | Bit2 | Bit3; - // for name references - public static final int RestrictiveFlagMASK = Bit1|Bit2|Bit3; public static final int FirstAssignmentToLocalMASK = Bit4; - + // for this reference - public static final int IsImplicitThisMask = Bit3; + public static final int IsImplicitThisMask = Bit3; // for single name references - public static final int DepthSHIFT = 5; // Bit6 -> Bit13 - public static final int DepthMASK = Bit6|Bit7|Bit8|Bit9|Bit10|Bit11|Bit12|Bit13; // 8 bits for actual depth value (max. 255) + public static final int DepthSHIFT = 5; // Bit6 -> Bit13 + + public static final int DepthMASK = Bit6 | Bit7 | Bit8 | Bit9 | Bit10 + | Bit11 | Bit12 | Bit13; // 8 bits for actual depth value (max. + // 255) + + // for statements + public static final int IsReachableMASK = Bit32; - // for statements - public static final int IsReachableMASK = Bit32; - public static final int IsLocalDeclarationReachableMASK = Bit31; + public static final int IsLocalDeclarationReachableMASK = Bit31; // for type declaration public static final int AddAssertionMASK = Bit1; - public static final int IsMemberTypeMASK = Bit11; // local member do not know it is local at parse time (need to look at binding) - - // for type, method and field declarations - public static final int HasLocalTypeMASK = Bit2; // cannot conflict with AddAssertionMASK - // for expression + public static final int IsMemberTypeMASK = Bit11; // local member do not + // know it is local at + // parse time (need to + // look at binding) + + // for type, method and field declarations + public static final int HasLocalTypeMASK = Bit2; // cannot conflict with + // AddAssertionMASK + + // for expression public static final int ParenthesizedSHIFT = 21; // Bit22 -> Bit29 - public static final int ParenthesizedMASK = Bit22|Bit23|Bit24|Bit25|Bit26|Bit27|Bit28|Bit29; // 8 bits for parenthesis count value (max. 255) + + public static final int ParenthesizedMASK = Bit22 | Bit23 | Bit24 | Bit25 + | Bit26 | Bit27 | Bit28 | Bit29; // 8 bits for parenthesis count + // value (max. 255) // for assignment - public static final int IsAssignmentWithNoEffectMASK = Bit30; - - // for references on lhs of assignment (set only for true assignments, as opposed to compound ones) + public static final int IsAssignmentWithNoEffectMASK = Bit30; + + // for references on lhs of assignment (set only for true assignments, as + // opposed to compound ones) public static final int IsStrictlyAssignedMASK = Bit14; - public static final int IsCompoundAssignedMASK = Bit17; // set only for compound assignments, as opposed to other ones + + public static final int IsCompoundAssignedMASK = Bit17; // set only for + // compound + // assignments, as + // opposed to other + // ones // for empty statement public static final int IsUsefulEmptyStatementMASK = Bit1; @@ -118,13 +198,13 @@ public abstract class ASTNode implements BaseTypes, CompilerModifiers, TypeConst // for compilation unit public static final int HasAllMethodBodies = Bit5; - + // for references in Javadoc comments public static final int InsideJavadoc = Bit16; - + // for if statement public static final int IsElseIfStatement = Bit30; - + public ASTNode() { super(); @@ -138,48 +218,59 @@ public abstract class ASTNode implements BaseTypes, CompilerModifiers, TypeConst return this; } - /* Answer true if the field use is considered deprecated. - * An access in the same compilation unit is allowed. - */ + /* + * Answer true if the field use is considered deprecated. An access in the + * same compilation unit is allowed. + */ public final boolean isFieldUseDeprecated(FieldBinding field, Scope scope) { if (field.isPrivate() && !scope.isDefinedInField(field)) { - // ignore cases where field is used from within inside itself + // ignore cases where field is used from within inside itself field.modifiers |= AccPrivateUsed; } - if (!field.isViewedAsDeprecated()) return false; + if (!field.isViewedAsDeprecated()) + return false; // inside same unit - no report - if (scope.isDefinedInSameUnit(field.declaringClass)) return false; - + if (scope.isDefinedInSameUnit(field.declaringClass)) + return false; + // if context is deprecated, may avoid reporting -// if (!scope.environment().options.reportDeprecationInsideDeprecatedCode && scope.isInsideDeprecatedCode()) return false; + // if + // (!scope.environment().options.reportDeprecationInsideDeprecatedCode + // && scope.isInsideDeprecatedCode()) return false; return true; } public boolean isImplicitThis() { - + return false; } - - /* Answer true if the method use is considered deprecated. - * An access in the same compilation unit is allowed. - */ + + /* + * Answer true if the method use is considered deprecated. An access in the + * same compilation unit is allowed. + */ public final boolean isMethodUseDeprecated(MethodBinding method, Scope scope) { if (method.isPrivate() && !scope.isDefinedInMethod(method)) { - // ignore cases where method is used from within inside itself (e.g. direct recursions) + // ignore cases where method is used from within inside itself (e.g. + // direct recursions) method.modifiers |= AccPrivateUsed; } - - if (!method.isViewedAsDeprecated()) return false; + + if (!method.isViewedAsDeprecated()) + return false; // inside same unit - no report - if (scope.isDefinedInSameUnit(method.declaringClass)) return false; - + if (scope.isDefinedInSameUnit(method.declaringClass)) + return false; + // if context is deprecated, may avoid reporting -// if (!scope.environment().options.reportDeprecationInsideDeprecatedCode && scope.isInsideDeprecatedCode()) return false; + // if + // (!scope.environment().options.reportDeprecationInsideDeprecatedCode + // && scope.isInsideDeprecatedCode()) return false; return true; } @@ -193,9 +284,10 @@ public abstract class ASTNode implements BaseTypes, CompilerModifiers, TypeConst return false; } - /* Answer true if the type use is considered deprecated. - * An access in the same compilation unit is allowed. - */ + /* + * Answer true if the type use is considered deprecated. An access in the + * same compilation unit is allowed. + */ public final boolean isTypeUseDeprecated(TypeBinding type, Scope scope) { if (type.isArrayType()) @@ -206,17 +298,21 @@ public abstract class ASTNode implements BaseTypes, CompilerModifiers, TypeConst ReferenceBinding refType = (ReferenceBinding) type; if (refType.isPrivate() && !scope.isDefinedInType(refType)) { - // ignore cases where type is used from within inside itself + // ignore cases where type is used from within inside itself refType.modifiers |= AccPrivateUsed; } - if (!refType.isViewedAsDeprecated()) return false; - + if (!refType.isViewedAsDeprecated()) + return false; + // inside same unit - no report - if (scope.isDefinedInSameUnit(refType)) return false; - + if (scope.isDefinedInSameUnit(refType)) + return false; + // if context is deprecated, may avoid reporting -// if (!scope.environment().options.reportDeprecationInsideDeprecatedCode && scope.isInsideDeprecatedCode()) return false; + // if + // (!scope.environment().options.reportDeprecationInsideDeprecatedCode + // && scope.isInsideDeprecatedCode()) return false; return true; } @@ -233,14 +329,14 @@ public abstract class ASTNode implements BaseTypes, CompilerModifiers, TypeConst s = s + "static "; //$NON-NLS-1$ if ((modifiers & AccFinal) != 0) s = s + "final "; //$NON-NLS-1$ -// if ((modifiers & AccSynchronized) != 0) -// s = s + "synchronized "; //$NON-NLS-1$ -// if ((modifiers & AccVolatile) != 0) -// s = s + "volatile "; //$NON-NLS-1$ -// if ((modifiers & AccTransient) != 0) -// s = s + "transient "; //$NON-NLS-1$ -// if ((modifiers & AccNative) != 0) -// s = s + "native "; //$NON-NLS-1$ + // if ((modifiers & AccSynchronized) != 0) + // s = s + "synchronized "; //$NON-NLS-1$ + // if ((modifiers & AccVolatile) != 0) + // s = s + "volatile "; //$NON-NLS-1$ + // if ((modifiers & AccTransient) != 0) + // s = s + "transient "; //$NON-NLS-1$ + // if ((modifiers & AccNative) != 0) + // s = s + "native "; //$NON-NLS-1$ if ((modifiers & AccAbstract) != 0) s = s + "abstract "; //$NON-NLS-1$ return s; @@ -250,7 +346,8 @@ public abstract class ASTNode implements BaseTypes, CompilerModifiers, TypeConst public static StringBuffer printIndent(int indent, StringBuffer output) { - for (int i = indent; i > 0; i--) output.append(" "); //$NON-NLS-1$ + for (int i = indent; i > 0; i--) + output.append(" "); //$NON-NLS-1$ return output; } @@ -266,28 +363,29 @@ public abstract class ASTNode implements BaseTypes, CompilerModifiers, TypeConst output.append("static "); //$NON-NLS-1$ if ((modifiers & AccFinal) != 0) output.append("final "); //$NON-NLS-1$ -// if ((modifiers & AccSynchronized) != 0) -// output.append("synchronized "); //$NON-NLS-1$ -// if ((modifiers & AccVolatile) != 0) -// output.append("volatile "); //$NON-NLS-1$ -// if ((modifiers & AccTransient) != 0) -// output.append("transient "); //$NON-NLS-1$ -// if ((modifiers & AccNative) != 0) -// output.append("native "); //$NON-NLS-1$ + // if ((modifiers & AccSynchronized) != 0) + // output.append("synchronized "); //$NON-NLS-1$ + // if ((modifiers & AccVolatile) != 0) + // output.append("volatile "); //$NON-NLS-1$ + // if ((modifiers & AccTransient) != 0) + // output.append("transient "); //$NON-NLS-1$ + // if ((modifiers & AccNative) != 0) + // output.append("native "); //$NON-NLS-1$ if ((modifiers & AccAbstract) != 0) output.append("abstract "); //$NON-NLS-1$ return output; } - /** + + /** * @deprecated - use field instead - */ + */ public int sourceEnd() { return sourceEnd; } - - /** + + /** * @deprecated - use field instead - */ + */ public int sourceStart() { return sourceStart; } @@ -307,9 +405,9 @@ public abstract class ASTNode implements BaseTypes, CompilerModifiers, TypeConst public String toString(int tab) { - return "****" + super.toString() + "****"; //$NON-NLS-2$ //$NON-NLS-1$ + return "****" + super.toString() + "****"; //$NON-NLS-2$ //$NON-NLS-1$ } - + public void traverse(ASTVisitor visitor, BlockScope scope) { } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AbstractMethodDeclaration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AbstractMethodDeclaration.java index 9c001cc..004039f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AbstractMethodDeclaration.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AbstractMethodDeclaration.java @@ -28,37 +28,51 @@ import net.sourceforge.phpdt.internal.compiler.problem.AbortMethod; import net.sourceforge.phpdt.internal.compiler.problem.AbortType; import net.sourceforge.phpdt.internal.compiler.problem.ProblemSeverities; +public abstract class AbstractMethodDeclaration extends ASTNode implements + ProblemSeverities, ReferenceContext { -public abstract class AbstractMethodDeclaration - extends ASTNode - implements ProblemSeverities, ReferenceContext { - public MethodScope scope; - //it is not relevent for constructor but it helps to have the name of the constructor here - //which is always the name of the class.....parsing do extra work to fill it up while it do not have to.... + + // it is not relevent for constructor but it helps to have the name of the + // constructor here + // which is always the name of the class.....parsing do extra work to fill + // it up while it do not have to.... public char[] selector; + public int declarationSourceStart; + public int declarationSourceEnd; + public int modifiers; + public int modifiersSourceStart; + public Argument[] arguments; + public TypeReference[] thrownExceptions; + public Statement[] statements; + public int explicitDeclarations; + public MethodBinding binding; + public boolean ignoreFurtherInvestigation = false; + public boolean needFreeReturn = false; - + public int bodyStart; + public int bodyEnd = -1; + public CompilationResult compilationResult; - - AbstractMethodDeclaration(CompilationResult compilationResult){ + + AbstractMethodDeclaration(CompilationResult compilationResult) { this.compilationResult = compilationResult; } - + /* - * We cause the compilation task to abort to a given extent. + * We cause the compilation task to abort to a given extent. */ public void abort(int abortLevel) { @@ -66,48 +80,51 @@ public abstract class AbstractMethodDeclaration throw new AbortCompilation(); // cannot do better } - CompilationResult compilationResult = - scope.referenceCompilationUnit().compilationResult; + CompilationResult compilationResult = scope.referenceCompilationUnit().compilationResult; switch (abortLevel) { - case AbortCompilation : - throw new AbortCompilation(compilationResult); - case AbortCompilationUnit : - throw new AbortCompilationUnit(compilationResult); - case AbortType : - throw new AbortType(compilationResult); - default : - throw new AbortMethod(compilationResult); + case AbortCompilation: + throw new AbortCompilation(compilationResult); + case AbortCompilationUnit: + throw new AbortCompilationUnit(compilationResult); + case AbortType: + throw new AbortType(compilationResult); + default: + throw new AbortMethod(compilationResult); } } - public abstract void analyseCode(ClassScope scope, InitializationFlowContext initializationContext, FlowInfo info); + public abstract void analyseCode(ClassScope scope, + InitializationFlowContext initializationContext, FlowInfo info); - /** + /** * Bind and add argument's binding into the scope of the method */ public void bindArguments() { if (arguments != null) { - // by default arguments in abstract/native methods are considered to be used (no complaint is expected) - boolean used = binding == null || binding.isAbstract();// || binding.isNative(); + // by default arguments in abstract/native methods are considered to + // be used (no complaint is expected) + boolean used = binding == null || binding.isAbstract();// || + // binding.isNative(); int length = arguments.length; for (int i = 0; i < length; i++) { - TypeBinding argType = binding == null ? null : binding.parameters[i]; + TypeBinding argType = binding == null ? null + : binding.parameters[i]; arguments[i].bind(scope, argType, used); } } } /** - * Record the thrown exception type bindings in the corresponding type references. + * Record the thrown exception type bindings in the corresponding type + * references. */ public void bindThrownExceptions() { - if (this.thrownExceptions != null - && this.binding != null - && this.binding.thrownExceptions != null) { + if (this.thrownExceptions != null && this.binding != null + && this.binding.thrownExceptions != null) { int thrownExceptionLength = this.thrownExceptions.length; int length = this.binding.thrownExceptions.length; if (length == thrownExceptionLength) { @@ -116,24 +133,28 @@ public abstract class AbstractMethodDeclaration } } else { int bindingIndex = 0; - for (int i = 0; i < thrownExceptionLength && bindingIndex < length; i++) { + for (int i = 0; i < thrownExceptionLength + && bindingIndex < length; i++) { TypeReference thrownException = this.thrownExceptions[i]; ReferenceBinding thrownExceptionBinding = this.binding.thrownExceptions[bindingIndex]; char[][] bindingCompoundName = thrownExceptionBinding.compoundName; if (thrownException instanceof SingleTypeReference) { // single type reference int lengthName = bindingCompoundName.length; - char[] thrownExceptionTypeName = thrownException.getTypeName()[0]; - if (CharOperation.equals(thrownExceptionTypeName, bindingCompoundName[lengthName - 1])) { + char[] thrownExceptionTypeName = thrownException + .getTypeName()[0]; + if (CharOperation.equals(thrownExceptionTypeName, + bindingCompoundName[lengthName - 1])) { thrownException.resolvedType = thrownExceptionBinding; bindingIndex++; } } else { // qualified type reference - if (CharOperation.equals(thrownException.getTypeName(), bindingCompoundName)) { + if (CharOperation.equals(thrownException.getTypeName(), + bindingCompoundName)) { thrownException.resolvedType = thrownExceptionBinding; bindingIndex++; - } + } } } } @@ -141,123 +162,126 @@ public abstract class AbstractMethodDeclaration } public CompilationResult compilationResult() { - + return this.compilationResult; } - + /** * Bytecode generation for a method */ -// public void generateCode(ClassScope classScope, ClassFile classFile) { -// -// int problemResetPC = 0; -// classFile.codeStream.wideMode = false; // reset wideMode to false -// if (ignoreFurtherInvestigation) { -// // method is known to have errors, dump a problem method -// if (this.binding == null) -// return; // handle methods with invalid signature or duplicates -// int problemsLength; -// IProblem[] problems = -// scope.referenceCompilationUnit().compilationResult.getProblems(); -// IProblem[] problemsCopy = new IProblem[problemsLength = problems.length]; -// System.arraycopy(problems, 0, problemsCopy, 0, problemsLength); -// classFile.addProblemMethod(this, binding, problemsCopy); -// return; -// } -// // regular code generation -// try { -// problemResetPC = classFile.contentsOffset; -// this.generateCode(classFile); -// } catch (AbortMethod e) { -// // a fatal error was detected during code generation, need to restart code gen if possible -// if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) { -// // a branch target required a goto_w, restart code gen in wide mode. -// try { -// this.traverse(new ResetStateForCodeGenerationVisitor(), classScope); -// classFile.contentsOffset = problemResetPC; -// classFile.methodCount--; -// classFile.codeStream.wideMode = true; // request wide mode -// this.generateCode(classFile); // restart method generation -// } catch (AbortMethod e2) { -// int problemsLength; -// IProblem[] problems = -// scope.referenceCompilationUnit().compilationResult.getAllProblems(); -// IProblem[] problemsCopy = new IProblem[problemsLength = problems.length]; -// System.arraycopy(problems, 0, problemsCopy, 0, problemsLength); -// classFile.addProblemMethod(this, binding, problemsCopy, problemResetPC); -// } -// } else { -// // produce a problem method accounting for this fatal error -// int problemsLength; -// IProblem[] problems = -// scope.referenceCompilationUnit().compilationResult.getAllProblems(); -// IProblem[] problemsCopy = new IProblem[problemsLength = problems.length]; -// System.arraycopy(problems, 0, problemsCopy, 0, problemsLength); -// classFile.addProblemMethod(this, binding, problemsCopy, problemResetPC); -// } -// } -// } -// -// private void generateCode(ClassFile classFile) { -// -// classFile.generateMethodInfoHeader(binding); -// int methodAttributeOffset = classFile.contentsOffset; -// int attributeNumber = classFile.generateMethodInfoAttribute(binding); -// if ((!binding.isNative()) && (!binding.isAbstract())) { -// int codeAttributeOffset = classFile.contentsOffset; -// classFile.generateCodeAttributeHeader(); -// CodeStream codeStream = classFile.codeStream; -// codeStream.reset(this, classFile); -// // initialize local positions -// this.scope.computeLocalVariablePositions(binding.isStatic() ? 0 : 1, codeStream); -// -// // arguments initialization for local variable debug attributes -// if (arguments != null) { -// for (int i = 0, max = arguments.length; i < max; i++) { -// LocalVariableBinding argBinding; -// codeStream.addVisibleLocalVariable(argBinding = arguments[i].binding); -// argBinding.recordInitializationStartPC(0); -// } -// } -// if (statements != null) { -// for (int i = 0, max = statements.length; i < max; i++) -// statements[i].generateCode(scope, codeStream); -// } -// if (this.needFreeReturn) { -// codeStream.return_(); -// } -// // local variable attributes -// codeStream.exitUserScope(scope); -// codeStream.recordPositionsFrom(0, this.declarationSourceEnd); -// classFile.completeCodeAttribute(codeAttributeOffset); -// attributeNumber++; -// } else { -// checkArgumentsSize(); -// } -// classFile.completeMethodInfo(methodAttributeOffset, attributeNumber); -// -// // if a problem got reported during code gen, then trigger problem method creation -// if (ignoreFurtherInvestigation) { -// throw new AbortMethod(scope.referenceCompilationUnit().compilationResult); -// } -// } - -// private void checkArgumentsSize() { -// TypeBinding[] parameters = binding.parameters; -// int size = 1; // an abstact method or a native method cannot be static -// for (int i = 0, max = parameters.length; i < max; i++) { -// TypeBinding parameter = parameters[i]; -// if (parameter == LongBinding || parameter == DoubleBinding) { -// size += 2; -// } else { -// size++; -// } -// if (size > 0xFF) { -// scope.problemReporter().noMoreAvailableSpaceForArgument(scope.locals[i], scope.locals[i].declaration); -// } -// } -// } - + // public void generateCode(ClassScope classScope, ClassFile classFile) { + // + // int problemResetPC = 0; + // classFile.codeStream.wideMode = false; // reset wideMode to false + // if (ignoreFurtherInvestigation) { + // // method is known to have errors, dump a problem method + // if (this.binding == null) + // return; // handle methods with invalid signature or duplicates + // int problemsLength; + // IProblem[] problems = + // scope.referenceCompilationUnit().compilationResult.getProblems(); + // IProblem[] problemsCopy = new IProblem[problemsLength = problems.length]; + // System.arraycopy(problems, 0, problemsCopy, 0, problemsLength); + // classFile.addProblemMethod(this, binding, problemsCopy); + // return; + // } + // // regular code generation + // try { + // problemResetPC = classFile.contentsOffset; + // this.generateCode(classFile); + // } catch (AbortMethod e) { + // // a fatal error was detected during code generation, need to restart + // code gen if possible + // if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) { + // // a branch target required a goto_w, restart code gen in wide mode. + // try { + // this.traverse(new ResetStateForCodeGenerationVisitor(), classScope); + // classFile.contentsOffset = problemResetPC; + // classFile.methodCount--; + // classFile.codeStream.wideMode = true; // request wide mode + // this.generateCode(classFile); // restart method generation + // } catch (AbortMethod e2) { + // int problemsLength; + // IProblem[] problems = + // scope.referenceCompilationUnit().compilationResult.getAllProblems(); + // IProblem[] problemsCopy = new IProblem[problemsLength = problems.length]; + // System.arraycopy(problems, 0, problemsCopy, 0, problemsLength); + // classFile.addProblemMethod(this, binding, problemsCopy, problemResetPC); + // } + // } else { + // // produce a problem method accounting for this fatal error + // int problemsLength; + // IProblem[] problems = + // scope.referenceCompilationUnit().compilationResult.getAllProblems(); + // IProblem[] problemsCopy = new IProblem[problemsLength = problems.length]; + // System.arraycopy(problems, 0, problemsCopy, 0, problemsLength); + // classFile.addProblemMethod(this, binding, problemsCopy, problemResetPC); + // } + // } + // } + // + // private void generateCode(ClassFile classFile) { + // + // classFile.generateMethodInfoHeader(binding); + // int methodAttributeOffset = classFile.contentsOffset; + // int attributeNumber = classFile.generateMethodInfoAttribute(binding); + // if ((!binding.isNative()) && (!binding.isAbstract())) { + // int codeAttributeOffset = classFile.contentsOffset; + // classFile.generateCodeAttributeHeader(); + // CodeStream codeStream = classFile.codeStream; + // codeStream.reset(this, classFile); + // // initialize local positions + // this.scope.computeLocalVariablePositions(binding.isStatic() ? 0 : 1, + // codeStream); + // + // // arguments initialization for local variable debug attributes + // if (arguments != null) { + // for (int i = 0, max = arguments.length; i < max; i++) { + // LocalVariableBinding argBinding; + // codeStream.addVisibleLocalVariable(argBinding = arguments[i].binding); + // argBinding.recordInitializationStartPC(0); + // } + // } + // if (statements != null) { + // for (int i = 0, max = statements.length; i < max; i++) + // statements[i].generateCode(scope, codeStream); + // } + // if (this.needFreeReturn) { + // codeStream.return_(); + // } + // // local variable attributes + // codeStream.exitUserScope(scope); + // codeStream.recordPositionsFrom(0, this.declarationSourceEnd); + // classFile.completeCodeAttribute(codeAttributeOffset); + // attributeNumber++; + // } else { + // checkArgumentsSize(); + // } + // classFile.completeMethodInfo(methodAttributeOffset, attributeNumber); + // + // // if a problem got reported during code gen, then trigger problem method + // creation + // if (ignoreFurtherInvestigation) { + // throw new + // AbortMethod(scope.referenceCompilationUnit().compilationResult); + // } + // } + // private void checkArgumentsSize() { + // TypeBinding[] parameters = binding.parameters; + // int size = 1; // an abstact method or a native method cannot be static + // for (int i = 0, max = parameters.length; i < max; i++) { + // TypeBinding parameter = parameters[i]; + // if (parameter == LongBinding || parameter == DoubleBinding) { + // size += 2; + // } else { + // size++; + // } + // if (size > 0xFF) { + // scope.problemReporter().noMoreAvailableSpaceForArgument(scope.locals[i], + // scope.locals[i].declaration); + // } + // } + // } public boolean hasErrors() { return this.ignoreFurtherInvestigation; } @@ -289,12 +313,12 @@ public abstract class AbstractMethodDeclaration return false; } -// public boolean isNative() { -// -// if (binding != null) -// return binding.isNative(); -// return (modifiers & AccNative) != 0; -// } + // public boolean isNative() { + // + // if (binding != null) + // return binding.isNative(); + // return (modifiers & AccNative) != 0; + // } public boolean isStatic() { @@ -306,9 +330,9 @@ public abstract class AbstractMethodDeclaration /** * Fill up the method body with statement */ - public abstract void parseStatements( - UnitParser parser, - CompilationUnitDeclaration unit); + public abstract void parseStatements(UnitParser parser, + CompilationUnitDeclaration unit); + public StringBuffer print(int tab, StringBuffer output) { printIndent(tab, output); @@ -316,7 +340,8 @@ public abstract class AbstractMethodDeclaration printReturnType(0, output).append(this.selector).append('('); if (this.arguments != null) { for (int i = 0; i < this.arguments.length; i++) { - if (i > 0) output.append(", "); //$NON-NLS-1$ + if (i > 0) + output.append(", "); //$NON-NLS-1$ this.arguments[i].print(0, output); } } @@ -324,7 +349,8 @@ public abstract class AbstractMethodDeclaration if (this.thrownExceptions != null) { output.append(" throws "); //$NON-NLS-1$ for (int i = 0; i < this.thrownExceptions.length; i++) { - if (i > 0) output.append(", "); //$NON-NLS-1$ + if (i > 0) + output.append(", "); //$NON-NLS-1$ this.thrownExceptions[i].print(0, output); } } @@ -334,14 +360,14 @@ public abstract class AbstractMethodDeclaration public StringBuffer printBody(int indent, StringBuffer output) { - if (isAbstract() || (this.modifiers & AccSemicolonBody) != 0) + if (isAbstract() || (this.modifiers & AccSemicolonBody) != 0) return output.append(';'); output.append(" {"); //$NON-NLS-1$ if (this.statements != null) { for (int i = 0; i < this.statements.length; i++) { output.append('\n'); - this.statements[i].printStatement(indent, output); + this.statements[i].printStatement(indent, output); } } output.append('\n'); //$NON-NLS-1$ @@ -350,9 +376,10 @@ public abstract class AbstractMethodDeclaration } public StringBuffer printReturnType(int indent, StringBuffer output) { - + return output; } + public void resolve(ClassScope upperScope) { if (binding == null) { @@ -360,12 +387,13 @@ public abstract class AbstractMethodDeclaration } try { - bindArguments(); + bindArguments(); bindThrownExceptions(); resolveStatements(); - } catch (AbortMethod e) { // ========= abort on fatal error ============= + } catch (AbortMethod e) { // ========= abort on fatal error + // ============= this.ignoreFurtherInvestigation = true; - } + } } public void resolveStatements() { @@ -401,8 +429,10 @@ public abstract class AbstractMethodDeclaration s += arguments[i].toString(0); if (i != (arguments.length - 1)) s = s + ", "; //$NON-NLS-1$ - }; - }; + } + ; + } + ; s += ")"; //$NON-NLS-1$ if (thrownExceptions != null) { s += " throws "; //$NON-NLS-1$ @@ -410,8 +440,10 @@ public abstract class AbstractMethodDeclaration s += thrownExceptions[i].toString(0); if (i != (thrownExceptions.length - 1)) s = s + ", "; //$NON-NLS-1$ - }; - }; + } + ; + } + ; s += toStringStatements(tab + 1); return s; @@ -435,8 +467,6 @@ public abstract class AbstractMethodDeclaration return s; } - public void traverse( - ASTVisitor visitor, - ClassScope classScope) { + public void traverse(ASTVisitor visitor, ClassScope classScope) { } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AbstractVariableDeclaration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AbstractVariableDeclaration.java index 84319d5..5ca4e4d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AbstractVariableDeclaration.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AbstractVariableDeclaration.java @@ -18,26 +18,34 @@ public abstract class AbstractVariableDeclaration extends Statement { public int modifiers; public TypeReference type; + public Expression initialization; public char[] name; + public int declarationEnd; + public int declarationSourceStart; + public int declarationSourceEnd; + public int modifiersSourceStart; - - public AbstractVariableDeclaration() {} - public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { + public AbstractVariableDeclaration() { + } + + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { return flowInfo; } public abstract String name(); + public StringBuffer printStatement(int indent, StringBuffer output) { printIndent(indent, output); printModifiers(this.modifiers, output); - type.print(0, output).append(' ').append(this.name); + type.print(0, output).append(' ').append(this.name); if (initialization != null) { output.append(" = "); //$NON-NLS-1$ initialization.printExpression(indent, output); @@ -45,8 +53,9 @@ public abstract class AbstractVariableDeclaration extends Statement { return output.append(';'); } - public void resolve(BlockScope scope) {} - + public void resolve(BlockScope scope) { + } + public String toString(int tab) { String s = tabString(tab); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AllocationExpression.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AllocationExpression.java index 7eb480b..c164bcb 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AllocationExpression.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AllocationExpression.java @@ -24,12 +24,12 @@ import net.sourceforge.phpdt.internal.compiler.lookup.SourceTypeBinding; import net.sourceforge.phpdt.internal.compiler.lookup.SyntheticArgumentBinding; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; -public class AllocationExpression - extends Expression - implements InvocationSite { - +public class AllocationExpression extends Expression implements InvocationSite { + public TypeReference type; + public Expression[] arguments; + public MethodBinding binding; MethodBinding syntheticAccessor; @@ -37,114 +37,117 @@ public class AllocationExpression public AllocationExpression() { } - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { // check captured variables are initialized in current context (26134) - checkCapturedLocalInitializationIfNecessary(this.binding.declaringClass, currentScope, flowInfo); + checkCapturedLocalInitializationIfNecessary( + this.binding.declaringClass, currentScope, flowInfo); // process arguments if (arguments != null) { for (int i = 0, count = arguments.length; i < count; i++) { - flowInfo = - arguments[i] - .analyseCode(currentScope, flowContext, flowInfo) - .unconditionalInits(); + flowInfo = arguments[i].analyseCode(currentScope, flowContext, + flowInfo).unconditionalInits(); } } // record some dependency information for exception types ReferenceBinding[] thrownExceptions; if (((thrownExceptions = this.binding.thrownExceptions).length) != 0) { // check exception handling - flowContext.checkExceptionHandlers( - thrownExceptions, - this, - flowInfo, - currentScope); + flowContext.checkExceptionHandlers(thrownExceptions, this, + flowInfo, currentScope); } manageEnclosingInstanceAccessIfNecessary(currentScope); manageSyntheticAccessIfNecessary(currentScope); - + return flowInfo; } - public void checkCapturedLocalInitializationIfNecessary(ReferenceBinding checkedType, BlockScope currentScope, FlowInfo flowInfo) { + public void checkCapturedLocalInitializationIfNecessary( + ReferenceBinding checkedType, BlockScope currentScope, + FlowInfo flowInfo) { - if (checkedType.isLocalType() - && !checkedType.isAnonymousType() - && !currentScope.isDefinedInType(checkedType)) { // only check external allocations + if (checkedType.isLocalType() && !checkedType.isAnonymousType() + && !currentScope.isDefinedInType(checkedType)) { // only + // check + // external + // allocations NestedTypeBinding nestedType = (NestedTypeBinding) checkedType; - SyntheticArgumentBinding[] syntheticArguments = nestedType.syntheticOuterLocalVariables(); - if (syntheticArguments != null) - for (int i = 0, count = syntheticArguments.length; i < count; i++){ + SyntheticArgumentBinding[] syntheticArguments = nestedType + .syntheticOuterLocalVariables(); + if (syntheticArguments != null) + for (int i = 0, count = syntheticArguments.length; i < count; i++) { SyntheticArgumentBinding syntheticArgument = syntheticArguments[i]; LocalVariableBinding targetLocal; - if ((targetLocal = syntheticArgument.actualOuterLocalVariable) == null) continue; -// if (targetLocal.declaration != null && !flowInfo.isDefinitelyAssigned(targetLocal)){ -// currentScope.problemReporter().uninitializedLocalVariable(targetLocal, this); -// } + if ((targetLocal = syntheticArgument.actualOuterLocalVariable) == null) + continue; + // if (targetLocal.declaration != null && + // !flowInfo.isDefinitelyAssigned(targetLocal)){ + // currentScope.problemReporter().uninitializedLocalVariable(targetLocal, + // this); + // } } - + } } - + public Expression enclosingInstance() { return null; } -// public void generateCode( -// BlockScope currentScope, -// CodeStream codeStream, -// boolean valueRequired) { -// -// int pc = codeStream.position; -// ReferenceBinding allocatedType = binding.declaringClass; -// -// codeStream.new_(allocatedType); -// if (valueRequired) { -// codeStream.dup(); -// } -// // better highlight for allocation: display the type individually -// codeStream.recordPositionsFrom(pc, type.sourceStart); -// -// // handling innerclass instance allocation - enclosing instance arguments -// if (allocatedType.isNestedType()) { -// codeStream.generateSyntheticEnclosingInstanceValues( -// currentScope, -// allocatedType, -// enclosingInstance(), -// this); -// } -// // generate the arguments for constructor -// if (arguments != null) { -// for (int i = 0, count = arguments.length; i < count; i++) { -// arguments[i].generateCode(currentScope, codeStream, true); -// } -// } -// // handling innerclass instance allocation - outer local arguments -// if (allocatedType.isNestedType()) { -// codeStream.generateSyntheticOuterArgumentValues( -// currentScope, -// allocatedType, -// this); -// } -// // invoke constructor -// if (syntheticAccessor == null) { -// codeStream.invokespecial(binding); -// } else { -// // synthetic accessor got some extra arguments appended to its signature, which need values -// for (int i = 0, -// max = syntheticAccessor.parameters.length - binding.parameters.length; -// i < max; -// i++) { -// codeStream.aconst_null(); -// } -// codeStream.invokespecial(syntheticAccessor); -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } + // public void generateCode( + // BlockScope currentScope, + // CodeStream codeStream, + // boolean valueRequired) { + // + // int pc = codeStream.position; + // ReferenceBinding allocatedType = binding.declaringClass; + // + // codeStream.new_(allocatedType); + // if (valueRequired) { + // codeStream.dup(); + // } + // // better highlight for allocation: display the type individually + // codeStream.recordPositionsFrom(pc, type.sourceStart); + // + // // handling innerclass instance allocation - enclosing instance arguments + // if (allocatedType.isNestedType()) { + // codeStream.generateSyntheticEnclosingInstanceValues( + // currentScope, + // allocatedType, + // enclosingInstance(), + // this); + // } + // // generate the arguments for constructor + // if (arguments != null) { + // for (int i = 0, count = arguments.length; i < count; i++) { + // arguments[i].generateCode(currentScope, codeStream, true); + // } + // } + // // handling innerclass instance allocation - outer local arguments + // if (allocatedType.isNestedType()) { + // codeStream.generateSyntheticOuterArgumentValues( + // currentScope, + // allocatedType, + // this); + // } + // // invoke constructor + // if (syntheticAccessor == null) { + // codeStream.invokespecial(binding); + // } else { + // // synthetic accessor got some extra arguments appended to its signature, + // which need values + // for (int i = 0, + // max = syntheticAccessor.parameters.length - binding.parameters.length; + // i < max; + // i++) { + // codeStream.aconst_null(); + // } + // codeStream.invokespecial(syntheticAccessor); + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } public boolean isSuperAccess() { @@ -156,26 +159,29 @@ public class AllocationExpression return true; } - /* Inner emulation consists in either recording a dependency - * link only, or performing one level of propagation. - * - * Dependency mechanism is used whenever dealing with source target - * types, since by the time we reach them, we might not yet know their - * exact need. + /* + * Inner emulation consists in either recording a dependency link only, or + * performing one level of propagation. + * + * Dependency mechanism is used whenever dealing with source target types, + * since by the time we reach them, we might not yet know their exact need. */ public void manageEnclosingInstanceAccessIfNecessary(BlockScope currentScope) { ReferenceBinding allocatedType; - // perform some emulation work in case there is some and we are inside a local type only + // perform some emulation work in case there is some and we are inside a + // local type only if ((allocatedType = binding.declaringClass).isNestedType() - && currentScope.enclosingSourceType().isLocalType()) { + && currentScope.enclosingSourceType().isLocalType()) { if (allocatedType.isLocalType()) { - ((LocalTypeBinding) allocatedType).addInnerEmulationDependent(currentScope, false); + ((LocalTypeBinding) allocatedType).addInnerEmulationDependent( + currentScope, false); // request cascade of accesses } else { - // locally propagate, since we already now the desired shape for sure + // locally propagate, since we already now the desired shape for + // sure currentScope.propagateInnerEmulation(allocatedType, false); // request cascade of accesses } @@ -185,37 +191,43 @@ public class AllocationExpression public void manageSyntheticAccessIfNecessary(BlockScope currentScope) { if (binding.isPrivate() - && (currentScope.enclosingSourceType() != binding.declaringClass)) { - -// if (currentScope -// .environment() -// .options -// .isPrivateConstructorAccessChangingVisibility) { -// binding.tagForClearingPrivateModifier(); -// // constructor will not be dumped as private, no emulation required thus -// } else { - syntheticAccessor = - ((SourceTypeBinding) binding.declaringClass).addSyntheticMethod(binding, isSuperAccess()); - currentScope.problemReporter().needToEmulateMethodAccess(binding, this); -// } + && (currentScope.enclosingSourceType() != binding.declaringClass)) { + + // if (currentScope + // .environment() + // .options + // .isPrivateConstructorAccessChangingVisibility) { + // binding.tagForClearingPrivateModifier(); + // // constructor will not be dumped as private, no emulation + // required thus + // } else { + syntheticAccessor = ((SourceTypeBinding) binding.declaringClass) + .addSyntheticMethod(binding, isSuperAccess()); + currentScope.problemReporter().needToEmulateMethodAccess(binding, + this); + // } } } + public StringBuffer printExpression(int indent, StringBuffer output) { output.append("new "); //$NON-NLS-1$ - type.printExpression(0, output); + type.printExpression(0, output); output.append('('); if (arguments != null) { for (int i = 0; i < arguments.length; i++) { - if (i > 0) output.append(", "); //$NON-NLS-1$ + if (i > 0) + output.append(", "); //$NON-NLS-1$ arguments[i].printExpression(0, output); } } return output.append(')'); } + public TypeBinding resolveType(BlockScope scope) { - // Propagate the type checking to the arguments, and check if the constructor is defined. + // Propagate the type checking to the arguments, and check if the + // constructor is defined. constant = NotAConstant; this.resolvedType = type.resolveType(scope); // will check for null after args are resolved @@ -240,8 +252,9 @@ public class AllocationExpression return this.resolvedType; } ReferenceBinding allocatedType = (ReferenceBinding) this.resolvedType; - if (!(binding = scope.getConstructor(allocatedType, argumentTypes, this)) - .isValidBinding()) { + if (!(binding = scope + .getConstructor(allocatedType, argumentTypes, this)) + .isValidBinding()) { if (binding.declaringClass == null) binding.declaringClass = allocatedType; scope.problemReporter().invalidConstructor(this, binding); @@ -252,7 +265,8 @@ public class AllocationExpression if (arguments != null) for (int i = 0; i < arguments.length; i++) - arguments[i].implicitWidening(binding.parameters[i], argumentTypes[i]); + arguments[i].implicitWidening(binding.parameters[i], + argumentTypes[i]); return allocatedType; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AnonymousLocalTypeDeclaration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AnonymousLocalTypeDeclaration.java index 73b3689..841196d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AnonymousLocalTypeDeclaration.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AnonymousLocalTypeDeclaration.java @@ -22,27 +22,30 @@ import net.sourceforge.phpdt.internal.compiler.problem.AbortType; public class AnonymousLocalTypeDeclaration extends LocalTypeDeclaration { public static final char[] ANONYMOUS_EMPTY_NAME = new char[] {}; + public QualifiedAllocationExpression allocation; public AnonymousLocalTypeDeclaration(CompilationResult compilationResult) { super(compilationResult); modifiers = AccDefault; name = ANONYMOUS_EMPTY_NAME; - } - - // use a default name in order to th name lookup + } + + // use a default name in order to th name lookup // to operate just like a regular type (which has a name) - //without checking systematically if the naem is null .... - public MethodBinding createsInternalConstructorWithBinding(MethodBinding inheritedConstructorBinding) { + // without checking systematically if the naem is null .... + public MethodBinding createsInternalConstructorWithBinding( + MethodBinding inheritedConstructorBinding) { - //Add to method'set, the default constuctor that just recall the - //super constructor with the same arguments + // Add to method'set, the default constuctor that just recall the + // super constructor with the same arguments String baseName = "$anonymous"; //$NON-NLS-1$ TypeBinding[] argumentTypes = inheritedConstructorBinding.parameters; int argumentsLength = argumentTypes.length; - //the constructor - ConstructorDeclaration cd = new ConstructorDeclaration(this.compilationResult); - cd.selector = new char[] { 'x' }; //no maining + // the constructor + ConstructorDeclaration cd = new ConstructorDeclaration( + this.compilationResult); + cd.selector = new char[] { 'x' }; // no maining cd.sourceStart = sourceStart; cd.sourceEnd = sourceEnd; cd.modifiers = modifiers & AccVisibilityMASK; @@ -51,11 +54,12 @@ public class AnonymousLocalTypeDeclaration extends LocalTypeDeclaration { if (argumentsLength > 0) { Argument[] arguments = (cd.arguments = new Argument[argumentsLength]); for (int i = argumentsLength; --i >= 0;) { - arguments[i] = new Argument((baseName + i).toCharArray(), 0L, null /*type ref*/, AccDefault); + arguments[i] = new Argument((baseName + i).toCharArray(), 0L, + null /* type ref */, AccDefault); } } - //the super call inside the constructor + // the super call inside the constructor cd.constructorCall = SuperReference.implicitSuperConstructorCall(); cd.constructorCall.sourceStart = sourceStart; cd.constructorCall.sourceEnd = sourceEnd; @@ -64,32 +68,33 @@ public class AnonymousLocalTypeDeclaration extends LocalTypeDeclaration { Expression[] args; args = cd.constructorCall.arguments = new Expression[argumentsLength]; for (int i = argumentsLength; --i >= 0;) { - args[i] = new SingleNameReference((baseName + i).toCharArray(), 0L); + args[i] = new SingleNameReference((baseName + i).toCharArray(), + 0L); } } - //adding the constructor in the methods list + // adding the constructor in the methods list if (methods == null) { methods = new AbstractMethodDeclaration[] { cd }; } else { AbstractMethodDeclaration[] newMethods; - System.arraycopy( - methods, - 0, - newMethods = new AbstractMethodDeclaration[methods.length + 1], - 1, - methods.length); + System + .arraycopy( + methods, + 0, + newMethods = new AbstractMethodDeclaration[methods.length + 1], + 1, methods.length); newMethods[0] = cd; methods = newMethods; } - //============BINDING UPDATE========================== - cd.binding = new MethodBinding( - cd.modifiers, //methodDeclaration - argumentsLength == 0 ? NoParameters : argumentTypes, //arguments bindings - inheritedConstructorBinding.thrownExceptions, //exceptions - binding); //declaringClass - + // ============BINDING UPDATE========================== + cd.binding = new MethodBinding(cd.modifiers, // methodDeclaration + argumentsLength == 0 ? NoParameters : argumentTypes, // arguments + // bindings + inheritedConstructorBinding.thrownExceptions, // exceptions + binding); // declaringClass + cd.scope = new MethodScope(scope, cd, true); cd.bindArguments(); cd.constructorCall.resolve(cd.scope); @@ -98,27 +103,25 @@ public class AnonymousLocalTypeDeclaration extends LocalTypeDeclaration { binding.methods = new MethodBinding[] { cd.binding }; } else { MethodBinding[] newMethods; - System.arraycopy( - binding.methods, - 0, - newMethods = new MethodBinding[binding.methods.length + 1], - 1, - binding.methods.length); + System.arraycopy(binding.methods, 0, + newMethods = new MethodBinding[binding.methods.length + 1], + 1, binding.methods.length); newMethods[0] = cd.binding; binding.methods = newMethods; } - //=================================================== + // =================================================== return cd.binding; } + public void resolve(BlockScope scope) { if (binding != null) { // remember local types binding for innerclass emulation propagation - scope.referenceCompilationUnit().record((LocalTypeBinding)binding); + scope.referenceCompilationUnit().record((LocalTypeBinding) binding); } - // scope and binding are provided in updateBindingSuperclass + // scope and binding are provided in updateBindingSuperclass resolve(); updateMaxFieldCount(); } @@ -129,12 +132,10 @@ public class AnonymousLocalTypeDeclaration extends LocalTypeDeclaration { } /** - * Iteration for a local anonymous innertype - * + * Iteration for a local anonymous innertype + * */ - public void traverse( - ASTVisitor visitor, - BlockScope blockScope) { + public void traverse(ASTVisitor visitor, BlockScope blockScope) { if (ignoreFurtherInvestigation) return; @@ -145,7 +146,8 @@ public class AnonymousLocalTypeDeclaration extends LocalTypeDeclaration { int methodsLength; int memberTypesLength; - // is bound to the actual type from the allocation expression + // is bound to the actual type from the allocation + // expression // therefore it has already been iterated at this point. if (memberTypes != null) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Argument.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Argument.java index 27da26c..aa0bd08 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Argument.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Argument.java @@ -17,7 +17,7 @@ import net.sourceforge.phpdt.internal.compiler.lookup.MethodScope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class Argument extends LocalDeclaration { - + public Argument(char[] name, long posNom, TypeReference tr, int modifiers) { super(null, name, (int) (posNom >>> 32), (int) posNom); @@ -34,17 +34,18 @@ public class Argument extends LocalDeclaration { // record the resolved type into the type reference int modifierFlag = this.modifiers; if ((this.binding = scope.duplicateName(this.name)) != null) { - //the name already exist....may carry on with the first binding .... + // the name already exist....may carry on with the first binding + // .... scope.problemReporter().redefineArgument(this); } else { - scope.addLocalVariable( - this.binding = - new LocalVariableBinding(this, typeBinding, modifierFlag, true)); - //true stand for argument instead of just local + scope.addLocalVariable(this.binding = new LocalVariableBinding( + this, typeBinding, modifierFlag, true)); + // true stand for argument instead of just local if (typeBinding != null && isTypeUseDeprecated(typeBinding, scope)) scope.problemReporter().deprecatedType(typeBinding, this.type); this.binding.declaration = this; - this.binding.useFlag = used ? LocalVariableBinding.USED : LocalVariableBinding.UNUSED; + this.binding.useFlag = used ? LocalVariableBinding.USED + : LocalVariableBinding.UNUSED; } } @@ -54,15 +55,25 @@ public class Argument extends LocalDeclaration { // provide the scope with a side effect : insertion of a LOCAL // that represents the argument. The type must be from JavaThrowable - TypeBinding tb = type.resolveTypeExpecting(scope, scope.getJavaLangThrowable()); + TypeBinding tb = type.resolveTypeExpecting(scope, scope + .getJavaLangThrowable()); if (tb == null) return null; if ((binding = scope.duplicateName(name)) != null) { - // the name already exists....may carry on with the first binding .... + // the name already exists....may carry on with the first binding + // .... scope.problemReporter().redefineArgument(this); return null; } - binding = new LocalVariableBinding(this, tb, modifiers, false); // argument decl, but local var (where isArgument = false) + binding = new LocalVariableBinding(this, tb, modifiers, false); // argument + // decl, + // but + // local + // var + // (where + // isArgument + // = + // false) scope.addLocalVariable(binding); binding.constant = NotAConstant; return tb; @@ -84,7 +95,7 @@ public class Argument extends LocalDeclaration { } public void traverse(ASTVisitor visitor, BlockScope scope) { - + if (visitor.visit(this, scope)) { if (type != null) type.traverse(visitor, scope); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ArrayAllocationExpression.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ArrayAllocationExpression.java index 9adf04f..3d8c880 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ArrayAllocationExpression.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ArrayAllocationExpression.java @@ -18,14 +18,14 @@ import net.sourceforge.phpdt.internal.compiler.lookup.ArrayBinding; import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; - public class ArrayAllocationExpression extends Expression { public TypeReference type; - //dimensions.length gives the number of dimensions, but the + // dimensions.length gives the number of dimensions, but the // last ones may be nulled as in new int[4][5][][] public Expression[] dimensions; + public ArrayInitializer initializer; /** @@ -35,10 +35,8 @@ public class ArrayAllocationExpression extends Expression { super(); } - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { for (int i = 0, max = dimensions.length; i < max; i++) { Expression dim; if ((dim = dimensions[i]) != null) { @@ -55,46 +53,46 @@ public class ArrayAllocationExpression extends Expression { /** * Code generation for a array allocation expression */ -// public void generateCode( -// BlockScope currentScope, -// CodeStream codeStream, -// boolean valueRequired) { -// -// int pc = codeStream.position; -// -// if (initializer != null) { -// initializer.generateCode(currentScope, codeStream, valueRequired); -// return; -// } -// -// int nonNullDimensionsLength = 0; -// for (int i = 0, max = dimensions.length; i < max; i++) -// if (dimensions[i] != null) { -// dimensions[i].generateCode(currentScope, codeStream, true); -// nonNullDimensionsLength++; -// } -// -// // Generate a sequence of bytecodes corresponding to an array allocation -// if (this.resolvedType.dimensions() == 1) { -// // Mono-dimensional array -// codeStream.newArray(currentScope, (ArrayBinding)this.resolvedType); -// } else { -// // Multi-dimensional array -// codeStream.multianewarray(this.resolvedType, nonNullDimensionsLength); -// } -// -// if (valueRequired) { -// codeStream.generateImplicitConversion(implicitConversion); -// } else { -// codeStream.pop(); -// } -// -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } + // public void generateCode( + // BlockScope currentScope, + // CodeStream codeStream, + // boolean valueRequired) { + // + // int pc = codeStream.position; + // + // if (initializer != null) { + // initializer.generateCode(currentScope, codeStream, valueRequired); + // return; + // } + // + // int nonNullDimensionsLength = 0; + // for (int i = 0, max = dimensions.length; i < max; i++) + // if (dimensions[i] != null) { + // dimensions[i].generateCode(currentScope, codeStream, true); + // nonNullDimensionsLength++; + // } + // + // // Generate a sequence of bytecodes corresponding to an array allocation + // if (this.resolvedType.dimensions() == 1) { + // // Mono-dimensional array + // codeStream.newArray(currentScope, (ArrayBinding)this.resolvedType); + // } else { + // // Multi-dimensional array + // codeStream.multianewarray(this.resolvedType, nonNullDimensionsLength); + // } + // + // if (valueRequired) { + // codeStream.generateImplicitConversion(implicitConversion); + // } else { + // codeStream.pop(); + // } + // + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } public StringBuffer printExpression(int indent, StringBuffer output) { output.append("new "); //$NON-NLS-1$ - type.print(0, output); + type.print(0, output); for (int i = 0; i < dimensions.length; i++) { if (dimensions[i] == null) output.append("[]"); //$NON-NLS-1$ @@ -103,19 +101,23 @@ public class ArrayAllocationExpression extends Expression { dimensions[i].printExpression(0, output); output.append(']'); } - } - if (initializer != null) initializer.printExpression(0, output); + } + if (initializer != null) + initializer.printExpression(0, output); return output; } + public TypeBinding resolveType(BlockScope scope) { // Build an array type reference using the current dimensions // The parser does not check for the fact that dimension may be null - // only at the -end- like new int [4][][]. The parser allows new int[][4][] - // so this must be checked here......(this comes from a reduction to LL1 grammar) + // only at the -end- like new int [4][][]. The parser allows new + // int[][4][] + // so this must be checked here......(this comes from a reduction to LL1 + // grammar) TypeBinding referenceType = type.resolveType(scope); - + // will check for null after dimensions are checked constant = Constant.NotAConstant; if (referenceType == VoidBinding) { @@ -123,14 +125,17 @@ public class ArrayAllocationExpression extends Expression { referenceType = null; } - // check the validity of the dimension syntax (and test for all null dimensions) + // check the validity of the dimension syntax (and test for all null + // dimensions) int explicitDimIndex = -1; for (int i = dimensions.length; --i >= 0;) { if (dimensions[i] != null) { - if (explicitDimIndex < 0) explicitDimIndex = i; - } else if (explicitDimIndex> 0) { + if (explicitDimIndex < 0) + explicitDimIndex = i; + } else if (explicitDimIndex > 0) { // should not have an empty dimension before an non-empty one - scope.problemReporter().incorrectLocationForEmptyDimension(this, i); + scope.problemReporter().incorrectLocationForEmptyDimension( + this, i); } } @@ -144,10 +149,11 @@ public class ArrayAllocationExpression extends Expression { scope.problemReporter().cannotDefineDimensionsAndInitializer(this); } - // dimensions resolution + // dimensions resolution for (int i = 0; i <= explicitDimIndex; i++) { if (dimensions[i] != null) { - TypeBinding dimensionType = dimensions[i].resolveTypeExpecting(scope, IntBinding); + TypeBinding dimensionType = dimensions[i].resolveTypeExpecting( + scope, IntBinding); if (dimensionType != null) { dimensions[i].implicitWidening(IntBinding, dimensionType); } @@ -159,12 +165,13 @@ public class ArrayAllocationExpression extends Expression { if (dimensions.length > 255) { scope.problemReporter().tooManyDimensions(this); } - this.resolvedType = scope.createArray(referenceType, dimensions.length); + this.resolvedType = scope.createArray(referenceType, + dimensions.length); // check the initializer if (initializer != null) { if ((initializer.resolveTypeExpecting(scope, this.resolvedType)) != null) - initializer.binding = (ArrayBinding)this.resolvedType; + initializer.binding = (ArrayBinding) this.resolvedType; } } return this.resolvedType; @@ -178,7 +185,7 @@ public class ArrayAllocationExpression extends Expression { s = s + "[]"; //$NON-NLS-1$ else s = s + "[" + dimensions[i].toStringExpression() + "]"; //$NON-NLS-2$ //$NON-NLS-1$ - } + } if (initializer != null) s = s + initializer.toStringExpression(); return s; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ArrayInitializer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ArrayInitializer.java index 1e16c28..b184c17 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ArrayInitializer.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ArrayInitializer.java @@ -16,203 +16,224 @@ import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class ArrayInitializer extends Expression { - public Expression[] expressions; + public Expression[] expressions; - public ArrayBinding binding; //the type of the { , , , } + public ArrayBinding binding; // the type of the { , , , } - /** - * ArrayInitializer constructor comment. - */ - public ArrayInitializer() { - super(); - } + /** + * ArrayInitializer constructor comment. + */ + public ArrayInitializer() { + super(); + } - public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { - if (expressions != null) { - for (int i = 0, max = expressions.length; i < max; i++) { - flowInfo = expressions[i].analyseCode(currentScope, flowContext, flowInfo).unconditionalInits(); - } - } - return flowInfo; - } + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { + if (expressions != null) { + for (int i = 0, max = expressions.length; i < max; i++) { + flowInfo = expressions[i].analyseCode(currentScope, + flowContext, flowInfo).unconditionalInits(); + } + } + return flowInfo; + } - /** - * Code generation for a array initializer - */ - //public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) { - // // Flatten the values and compute the dimensions, by iterating in depth into nested array initializers - // - // int pc = codeStream.position; - // int expressionLength = (expressions == null) ? 0: expressions.length; - // codeStream.generateInlinedValue(expressionLength); - // codeStream.newArray(currentScope, binding); - // if (expressions != null) { - // // binding is an ArrayType, so I can just deal with the dimension - // int elementsTypeID = binding.dimensions > 1 ? -1 : binding.leafComponentType.id; - // for (int i = 0; i < expressionLength; i++) { - // Expression expr; - // if ((expr = expressions[i]).constant != NotAConstant) { - // switch (elementsTypeID) { // filter out initializations to default values - // case T_int : - // case T_short : - // case T_byte : - // case T_char : - // case T_long : - // if (expr.constant.longValue() != 0) { - // codeStream.dup(); - // codeStream.generateInlinedValue(i); - // expr.generateCode(currentScope, codeStream, true); - // codeStream.arrayAtPut(elementsTypeID, false); - // } - // break; - // case T_float : - // case T_double : - // double constantValue = expr.constant.doubleValue(); - // if (constantValue == -0.0 || constantValue != 0) { - // codeStream.dup(); - // codeStream.generateInlinedValue(i); - // expr.generateCode(currentScope, codeStream, true); - // codeStream.arrayAtPut(elementsTypeID, false); - // } - // break; - // case T_boolean : - // if (expr.constant.booleanValue() != false) { - // codeStream.dup(); - // codeStream.generateInlinedValue(i); - // expr.generateCode(currentScope, codeStream, true); - // codeStream.arrayAtPut(elementsTypeID, false); - // } - // break; - // default : - // if (!(expr instanceof NullLiteral)) { - // codeStream.dup(); - // codeStream.generateInlinedValue(i); - // expr.generateCode(currentScope, codeStream, true); - // codeStream.arrayAtPut(elementsTypeID, false); - // } - // } - // } else if (!(expr instanceof NullLiteral)) { - // codeStream.dup(); - // codeStream.generateInlinedValue(i); - // expr.generateCode(currentScope, codeStream, true); - // codeStream.arrayAtPut(elementsTypeID, false); - // } - // } - // } - // if (!valueRequired) { - // codeStream.pop(); - // } - // codeStream.recordPositionsFrom(pc, this.sourceStart); - //} - public StringBuffer printExpression(int indent, StringBuffer output) { + /** + * Code generation for a array initializer + */ + // public void generateCode(BlockScope currentScope, CodeStream codeStream, + // boolean valueRequired) { + // // Flatten the values and compute the dimensions, by iterating in depth + // into nested array initializers + // + // int pc = codeStream.position; + // int expressionLength = (expressions == null) ? 0: expressions.length; + // codeStream.generateInlinedValue(expressionLength); + // codeStream.newArray(currentScope, binding); + // if (expressions != null) { + // // binding is an ArrayType, so I can just deal with the dimension + // int elementsTypeID = binding.dimensions > 1 ? -1 : + // binding.leafComponentType.id; + // for (int i = 0; i < expressionLength; i++) { + // Expression expr; + // if ((expr = expressions[i]).constant != NotAConstant) { + // switch (elementsTypeID) { // filter out initializations to default values + // case T_int : + // case T_short : + // case T_byte : + // case T_char : + // case T_long : + // if (expr.constant.longValue() != 0) { + // codeStream.dup(); + // codeStream.generateInlinedValue(i); + // expr.generateCode(currentScope, codeStream, true); + // codeStream.arrayAtPut(elementsTypeID, false); + // } + // break; + // case T_float : + // case T_double : + // double constantValue = expr.constant.doubleValue(); + // if (constantValue == -0.0 || constantValue != 0) { + // codeStream.dup(); + // codeStream.generateInlinedValue(i); + // expr.generateCode(currentScope, codeStream, true); + // codeStream.arrayAtPut(elementsTypeID, false); + // } + // break; + // case T_boolean : + // if (expr.constant.booleanValue() != false) { + // codeStream.dup(); + // codeStream.generateInlinedValue(i); + // expr.generateCode(currentScope, codeStream, true); + // codeStream.arrayAtPut(elementsTypeID, false); + // } + // break; + // default : + // if (!(expr instanceof NullLiteral)) { + // codeStream.dup(); + // codeStream.generateInlinedValue(i); + // expr.generateCode(currentScope, codeStream, true); + // codeStream.arrayAtPut(elementsTypeID, false); + // } + // } + // } else if (!(expr instanceof NullLiteral)) { + // codeStream.dup(); + // codeStream.generateInlinedValue(i); + // expr.generateCode(currentScope, codeStream, true); + // codeStream.arrayAtPut(elementsTypeID, false); + // } + // } + // } + // if (!valueRequired) { + // codeStream.pop(); + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } + public StringBuffer printExpression(int indent, StringBuffer output) { - output.append('{'); - if (expressions != null) { - int j = 20; - for (int i = 0; i < expressions.length; i++) { - if (i > 0) - output.append(", "); //$NON-NLS-1$ - expressions[i].printExpression(0, output); - j--; - if (j == 0) { - output.append('\n'); - printIndent(indent + 1, output); - j = 20; - } - } - } - return output.append('}'); - } + output.append('{'); + if (expressions != null) { + int j = 20; + for (int i = 0; i < expressions.length; i++) { + if (i > 0) + output.append(", "); //$NON-NLS-1$ + expressions[i].printExpression(0, output); + j--; + if (j == 0) { + output.append('\n'); + printIndent(indent + 1, output); + j = 20; + } + } + } + return output.append('}'); + } - public TypeBinding resolveTypeExpecting(BlockScope scope, TypeBinding expectedTb) { - // Array initializers can only occur on the right hand side of an assignment - // expression, therefore the expected type contains the valid information - // concerning the type that must be enforced by the elements of the array initializer. + public TypeBinding resolveTypeExpecting(BlockScope scope, + TypeBinding expectedTb) { + // Array initializers can only occur on the right hand side of an + // assignment + // expression, therefore the expected type contains the valid + // information + // concerning the type that must be enforced by the elements of the + // array initializer. - // this method is recursive... (the test on isArrayType is the stop case) + // this method is recursive... (the test on isArrayType is the stop + // case) - constant = NotAConstant; - if (expectedTb.isArrayType()) { - binding = (ArrayBinding) expectedTb; - if (expressions == null) - return binding; - TypeBinding expectedElementsTb = binding.elementsType(scope); - if (expectedElementsTb.isBaseType()) { - for (int i = 0, length = expressions.length; i < length; i++) { - Expression expression = expressions[i]; - TypeBinding expressionTb = (expression instanceof ArrayInitializer) ? expression.resolveTypeExpecting(scope, - expectedElementsTb) : expression.resolveType(scope); - if (expressionTb == null) - return null; + constant = NotAConstant; + if (expectedTb.isArrayType()) { + binding = (ArrayBinding) expectedTb; + if (expressions == null) + return binding; + TypeBinding expectedElementsTb = binding.elementsType(scope); + if (expectedElementsTb.isBaseType()) { + for (int i = 0, length = expressions.length; i < length; i++) { + Expression expression = expressions[i]; + TypeBinding expressionTb = (expression instanceof ArrayInitializer) ? expression + .resolveTypeExpecting(scope, expectedElementsTb) + : expression.resolveType(scope); + if (expressionTb == null) + return null; - // Compile-time conversion required? - if (expression.isConstantValueOfTypeAssignableToType(expressionTb, expectedElementsTb)) { - expression.implicitWidening(expectedElementsTb, expressionTb); - } else if (BaseTypeBinding.isWidening(expectedElementsTb.id, expressionTb.id)) { - expression.implicitWidening(expectedElementsTb, expressionTb); - } else { - scope.problemReporter().typeMismatchErrorActualTypeExpectedType(expression, expressionTb, expectedElementsTb); - return null; - } - } - } else { - for (int i = 0, length = expressions.length; i < length; i++) - if (expressions[i].resolveTypeExpecting(scope, expectedElementsTb) == null) - return null; - } - return binding; - } + // Compile-time conversion required? + if (expression.isConstantValueOfTypeAssignableToType( + expressionTb, expectedElementsTb)) { + expression.implicitWidening(expectedElementsTb, + expressionTb); + } else if (BaseTypeBinding.isWidening( + expectedElementsTb.id, expressionTb.id)) { + expression.implicitWidening(expectedElementsTb, + expressionTb); + } else { + scope.problemReporter() + .typeMismatchErrorActualTypeExpectedType( + expression, expressionTb, + expectedElementsTb); + return null; + } + } + } else { + for (int i = 0, length = expressions.length; i < length; i++) + if (expressions[i].resolveTypeExpecting(scope, + expectedElementsTb) == null) + return null; + } + return binding; + } - // infer initializer type for error reporting based on first element - TypeBinding leafElementType = null; - int dim = 1; - if (expressions == null) { - leafElementType = scope.getJavaLangObject(); - } else { - Expression currentExpression = expressions[0]; - while (currentExpression != null && currentExpression instanceof ArrayInitializer) { - dim++; - Expression[] subExprs = ((ArrayInitializer) currentExpression).expressions; - if (subExprs == null) { - leafElementType = scope.getJavaLangObject(); - currentExpression = null; - break; - } - currentExpression = ((ArrayInitializer) currentExpression).expressions[0]; - } - if (currentExpression != null) { - leafElementType = currentExpression.resolveType(scope); - } - } - if (leafElementType != null) { - TypeBinding probableTb = scope.createArray(leafElementType, dim); - scope.problemReporter().typeMismatchErrorActualTypeExpectedType(this, probableTb, expectedTb); - } - return null; - } + // infer initializer type for error reporting based on first element + TypeBinding leafElementType = null; + int dim = 1; + if (expressions == null) { + leafElementType = scope.getJavaLangObject(); + } else { + Expression currentExpression = expressions[0]; + while (currentExpression != null + && currentExpression instanceof ArrayInitializer) { + dim++; + Expression[] subExprs = ((ArrayInitializer) currentExpression).expressions; + if (subExprs == null) { + leafElementType = scope.getJavaLangObject(); + currentExpression = null; + break; + } + currentExpression = ((ArrayInitializer) currentExpression).expressions[0]; + } + if (currentExpression != null) { + leafElementType = currentExpression.resolveType(scope); + } + } + if (leafElementType != null) { + TypeBinding probableTb = scope.createArray(leafElementType, dim); + scope.problemReporter().typeMismatchErrorActualTypeExpectedType( + this, probableTb, expectedTb); + } + return null; + } - public String toStringExpression() { + public String toStringExpression() { - String s = "{"; //$NON-NLS-1$ - if (expressions != null) { - int j = 20; - for (int i = 0; i < expressions.length; i++) { - s = s + expressions[i].toStringExpression() + ","; //$NON-NLS-1$ - j--; - if (j == 0) { - s = s + "\n ";j = 20;}}}; //$NON-NLS-1$ - s = s + "}"; //$NON-NLS-1$ - return s; - } + String s = "{"; //$NON-NLS-1$ + if (expressions != null) { + int j = 20; + for (int i = 0; i < expressions.length; i++) { + s = s + expressions[i].toStringExpression() + ","; //$NON-NLS-1$ + j--; + if (j == 0) { + s = s + "\n ";j = 20;}}}; //$NON-NLS-1$ + s = s + "}"; //$NON-NLS-1$ + return s; + } - public void traverse(ASTVisitor visitor, BlockScope scope) { - if (visitor.visit(this, scope)) { - if (expressions != null) { - int expressionsLength = expressions.length; - for (int i = 0; i < expressionsLength; i++) - expressions[i].traverse(visitor, scope); - } - } - visitor.endVisit(this, scope); - } + public void traverse(ASTVisitor visitor, BlockScope scope) { + if (visitor.visit(this, scope)) { + if (expressions != null) { + int expressionsLength = expressions.length; + for (int i = 0; i < expressionsLength; i++) + expressions[i].traverse(visitor, scope); + } + } + visitor.endVisit(this, scope); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ArrayQualifiedTypeReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ArrayQualifiedTypeReference.java index 26e133c..b8f27aa 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ArrayQualifiedTypeReference.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ArrayQualifiedTypeReference.java @@ -18,40 +18,49 @@ import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class ArrayQualifiedTypeReference extends QualifiedTypeReference { int dimensions; -public ArrayQualifiedTypeReference(char[][] sources , int dim, long[] poss) { - super( sources , poss); - dimensions = dim ; -} -public ArrayQualifiedTypeReference(char[][] sources , TypeBinding tb, int dim, long[] poss) { - super( sources , tb, poss); - dimensions = dim ; -} -public int dimensions() { - return dimensions; -} -public TypeBinding getTypeBinding(Scope scope) { - if (this.resolvedType != null) - return this.resolvedType; - if (dimensions > 255) { - scope.problemReporter().tooManyDimensions(this); + + public ArrayQualifiedTypeReference(char[][] sources, int dim, long[] poss) { + super(sources, poss); + dimensions = dim; + } + + public ArrayQualifiedTypeReference(char[][] sources, TypeBinding tb, + int dim, long[] poss) { + super(sources, tb, poss); + dimensions = dim; + } + + public int dimensions() { + return dimensions; + } + + public TypeBinding getTypeBinding(Scope scope) { + if (this.resolvedType != null) + return this.resolvedType; + if (dimensions > 255) { + scope.problemReporter().tooManyDimensions(this); + } + return scope.createArray(scope.getType(tokens), dimensions); + } + + public String toStringExpression(int tab) { + /* slow speed */ + + String s = super.toStringExpression(tab); + if (dimensions == 1) + return s + "[]"; //$NON-NLS-1$ + for (int i = 1; i <= dimensions; i++) + s = s + "[]"; //$NON-NLS-1$ + return s; + } + + public void traverse(IAbstractSyntaxTreeVisitor visitor, BlockScope scope) { + visitor.visit(this, scope); + visitor.endVisit(this, scope); + } + + public void traverse(IAbstractSyntaxTreeVisitor visitor, ClassScope scope) { + visitor.visit(this, scope); + visitor.endVisit(this, scope); } - return scope.createArray(scope.getType(tokens), dimensions); -} -public String toStringExpression(int tab){ - /* slow speed */ - - String s = super.toStringExpression(tab) ; - if (dimensions == 1 ) return s + "[]" ; //$NON-NLS-1$ - for (int i=1 ; i <= dimensions ; i++) - s = s + "[]" ; //$NON-NLS-1$ - return s ; -} -public void traverse(IAbstractSyntaxTreeVisitor visitor, BlockScope scope) { - visitor.visit(this, scope); - visitor.endVisit(this, scope); -} -public void traverse(IAbstractSyntaxTreeVisitor visitor, ClassScope scope) { - visitor.visit(this, scope); - visitor.endVisit(this, scope); -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ArrayReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ArrayReference.java index 5d49323..1f1a810 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ArrayReference.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ArrayReference.java @@ -19,8 +19,9 @@ import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class ArrayReference extends Reference { - + public Expression receiver; + public Expression position; public ArrayReference(Expression rec, Expression pos) { @@ -29,154 +30,150 @@ public class ArrayReference extends Reference { sourceStart = rec.sourceStart; } - public FlowInfo analyseAssignment( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo, - Assignment assignment, - boolean compoundAssignment) { + public FlowInfo analyseAssignment(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo, Assignment assignment, + boolean compoundAssignment) { if (assignment.expression == null) { - return analyseCode(currentScope, flowContext, flowInfo).unconditionalInits(); + return analyseCode(currentScope, flowContext, flowInfo) + .unconditionalInits(); } else { - return assignment - .expression - .analyseCode( + return assignment.expression.analyseCode( currentScope, flowContext, - analyseCode(currentScope, flowContext, flowInfo).unconditionalInits()) - .unconditionalInits(); + analyseCode(currentScope, flowContext, flowInfo) + .unconditionalInits()).unconditionalInits(); } } - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { - return position.analyseCode( - currentScope, - flowContext, - receiver.analyseCode(currentScope, flowContext, flowInfo)); + return position.analyseCode(currentScope, flowContext, receiver + .analyseCode(currentScope, flowContext, flowInfo)); } -// public void generateAssignment( -// BlockScope currentScope, -// CodeStream codeStream, -// Assignment assignment, -// boolean valueRequired) { -// -// receiver.generateCode(currentScope, codeStream, true); -// position.generateCode(currentScope, codeStream, true); -// assignment.expression.generateCode(currentScope, codeStream, true); -// codeStream.arrayAtPut(this.resolvedType.id, valueRequired); -// if (valueRequired) { -// codeStream.generateImplicitConversion(assignment.implicitConversion); -// } -// } + // public void generateAssignment( + // BlockScope currentScope, + // CodeStream codeStream, + // Assignment assignment, + // boolean valueRequired) { + // + // receiver.generateCode(currentScope, codeStream, true); + // position.generateCode(currentScope, codeStream, true); + // assignment.expression.generateCode(currentScope, codeStream, true); + // codeStream.arrayAtPut(this.resolvedType.id, valueRequired); + // if (valueRequired) { + // codeStream.generateImplicitConversion(assignment.implicitConversion); + // } + // } /** * Code generation for a array reference */ -// public void generateCode( -// BlockScope currentScope, -// CodeStream codeStream, -// boolean valueRequired) { -// -// int pc = codeStream.position; -// receiver.generateCode(currentScope, codeStream, true); -// position.generateCode(currentScope, codeStream, true); -// codeStream.arrayAt(this.resolvedType.id); -// // Generating code for the potential runtime type checking -// if (valueRequired) { -// codeStream.generateImplicitConversion(implicitConversion); -// } else { -// if (this.resolvedType == LongBinding -// || this.resolvedType == DoubleBinding) { -// codeStream.pop2(); -// } else { -// codeStream.pop(); -// } -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } -// -// public void generateCompoundAssignment( -// BlockScope currentScope, -// CodeStream codeStream, -// Expression expression, -// int operator, -// int assignmentImplicitConversion, -// boolean valueRequired) { -// -// receiver.generateCode(currentScope, codeStream, true); -// position.generateCode(currentScope, codeStream, true); -// codeStream.dup2(); -// codeStream.arrayAt(this.resolvedType.id); -// int operationTypeID; -// if ((operationTypeID = implicitConversion >> 4) == T_String) { -// codeStream.generateStringAppend(currentScope, null, expression); -// } else { -// // promote the array reference to the suitable operation type -// codeStream.generateImplicitConversion(implicitConversion); -// // generate the increment value (will by itself be promoted to the operation value) -// if (expression == IntLiteral.One) { // prefix operation -// codeStream.generateConstant(expression.constant, implicitConversion); -// } else { -// expression.generateCode(currentScope, codeStream, true); -// } -// // perform the operation -// codeStream.sendOperator(operator, operationTypeID); -// // cast the value back to the array reference type -// codeStream.generateImplicitConversion(assignmentImplicitConversion); -// } -// codeStream.arrayAtPut(this.resolvedType.id, valueRequired); -// } -// -// public void generatePostIncrement( -// BlockScope currentScope, -// CodeStream codeStream, -// CompoundAssignment postIncrement, -// boolean valueRequired) { -// -// receiver.generateCode(currentScope, codeStream, true); -// position.generateCode(currentScope, codeStream, true); -// codeStream.dup2(); -// codeStream.arrayAt(this.resolvedType.id); -// if (valueRequired) { -// if ((this.resolvedType == LongBinding) -// || (this.resolvedType == DoubleBinding)) { -// codeStream.dup2_x2(); -// } else { -// codeStream.dup_x2(); -// } -// } -// codeStream.generateConstant( -// postIncrement.expression.constant, -// implicitConversion); -// codeStream.sendOperator(postIncrement.operator, this.resolvedType.id); -// codeStream.generateImplicitConversion( -// postIncrement.assignmentImplicitConversion); -// codeStream.arrayAtPut(this.resolvedType.id, false); -// } + // public void generateCode( + // BlockScope currentScope, + // CodeStream codeStream, + // boolean valueRequired) { + // + // int pc = codeStream.position; + // receiver.generateCode(currentScope, codeStream, true); + // position.generateCode(currentScope, codeStream, true); + // codeStream.arrayAt(this.resolvedType.id); + // // Generating code for the potential runtime type checking + // if (valueRequired) { + // codeStream.generateImplicitConversion(implicitConversion); + // } else { + // if (this.resolvedType == LongBinding + // || this.resolvedType == DoubleBinding) { + // codeStream.pop2(); + // } else { + // codeStream.pop(); + // } + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } + // + // public void generateCompoundAssignment( + // BlockScope currentScope, + // CodeStream codeStream, + // Expression expression, + // int operator, + // int assignmentImplicitConversion, + // boolean valueRequired) { + // + // receiver.generateCode(currentScope, codeStream, true); + // position.generateCode(currentScope, codeStream, true); + // codeStream.dup2(); + // codeStream.arrayAt(this.resolvedType.id); + // int operationTypeID; + // if ((operationTypeID = implicitConversion >> 4) == T_String) { + // codeStream.generateStringAppend(currentScope, null, expression); + // } else { + // // promote the array reference to the suitable operation type + // codeStream.generateImplicitConversion(implicitConversion); + // // generate the increment value (will by itself be promoted to the + // operation value) + // if (expression == IntLiteral.One) { // prefix operation + // codeStream.generateConstant(expression.constant, implicitConversion); + // } else { + // expression.generateCode(currentScope, codeStream, true); + // } + // // perform the operation + // codeStream.sendOperator(operator, operationTypeID); + // // cast the value back to the array reference type + // codeStream.generateImplicitConversion(assignmentImplicitConversion); + // } + // codeStream.arrayAtPut(this.resolvedType.id, valueRequired); + // } + // + // public void generatePostIncrement( + // BlockScope currentScope, + // CodeStream codeStream, + // CompoundAssignment postIncrement, + // boolean valueRequired) { + // + // receiver.generateCode(currentScope, codeStream, true); + // position.generateCode(currentScope, codeStream, true); + // codeStream.dup2(); + // codeStream.arrayAt(this.resolvedType.id); + // if (valueRequired) { + // if ((this.resolvedType == LongBinding) + // || (this.resolvedType == DoubleBinding)) { + // codeStream.dup2_x2(); + // } else { + // codeStream.dup_x2(); + // } + // } + // codeStream.generateConstant( + // postIncrement.expression.constant, + // implicitConversion); + // codeStream.sendOperator(postIncrement.operator, this.resolvedType.id); + // codeStream.generateImplicitConversion( + // postIncrement.assignmentImplicitConversion); + // codeStream.arrayAtPut(this.resolvedType.id, false); + // } public StringBuffer printExpression(int indent, StringBuffer output) { receiver.printExpression(0, output).append('['); return position.printExpression(0, output).append(']'); } - + public TypeBinding resolveType(BlockScope scope) { constant = Constant.NotAConstant; TypeBinding arrayType = receiver.resolveType(scope); if (arrayType != null) { if (arrayType.isArrayType()) { - this.resolvedType = ((ArrayBinding) arrayType).elementsType(scope); + this.resolvedType = ((ArrayBinding) arrayType) + .elementsType(scope); } else { - scope.problemReporter().referenceMustBeArrayTypeAt(arrayType, this); + scope.problemReporter().referenceMustBeArrayTypeAt(arrayType, + this); } } - TypeBinding positionType = position.resolveTypeExpecting(scope, IntBinding); + TypeBinding positionType = position.resolveTypeExpecting(scope, + IntBinding); if (positionType != null) { position.implicitWidening(IntBinding, positionType); } @@ -186,11 +183,11 @@ public class ArrayReference extends Reference { public String toStringExpression() { return receiver.toStringExpression() + "[" //$NON-NLS-1$ - +position.toStringExpression() + "]"; //$NON-NLS-1$ - } + + position.toStringExpression() + "]"; //$NON-NLS-1$ + } public void traverse(ASTVisitor visitor, BlockScope scope) { - + if (visitor.visit(this, scope)) { receiver.traverse(visitor, scope); position.traverse(visitor, scope); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ArrayTypeReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ArrayTypeReference.java index fb4d932..f7edabc 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ArrayTypeReference.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ArrayTypeReference.java @@ -17,41 +17,53 @@ import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class ArrayTypeReference extends SingleTypeReference { public int dimensions; -/** - * ArrayTypeReference constructor comment. - * @param source char[] - * @param dim int - * @param pos int - */ -public ArrayTypeReference(char[] source, int dim, long pos) { - super(source, pos); - dimensions = dim ; -} -public ArrayTypeReference(char[] source, TypeBinding tb, int dim, long pos) { - super(source, tb, pos); - dimensions = dim ;} -public int dimensions() { - return dimensions; -} -public TypeBinding getTypeBinding(Scope scope) { - if (this.resolvedType != null) - return this.resolvedType; - if (dimensions > 255) { - scope.problemReporter().tooManyDimensions(this); + + /** + * ArrayTypeReference constructor comment. + * + * @param source + * char[] + * @param dim + * int + * @param pos + * int + */ + public ArrayTypeReference(char[] source, int dim, long pos) { + super(source, pos); + dimensions = dim; } - return scope.createArray(scope.getType(token), dimensions); -} -public String toStringExpression(int tab){ + public ArrayTypeReference(char[] source, TypeBinding tb, int dim, long pos) { + super(source, tb, pos); + dimensions = dim; + } - String s = super.toStringExpression(tab) ; - if (dimensions == 1 ) return s + "[]" ; //$NON-NLS-1$ - for (int i=1 ; i <= dimensions ; i++) - s = s + "[]" ; //$NON-NLS-1$ - return s ; -} -public void traverse(IAbstractSyntaxTreeVisitor visitor, BlockScope scope) { - visitor.visit(this, scope); - visitor.endVisit(this, scope); -} + public int dimensions() { + return dimensions; + } + + public TypeBinding getTypeBinding(Scope scope) { + if (this.resolvedType != null) + return this.resolvedType; + if (dimensions > 255) { + scope.problemReporter().tooManyDimensions(this); + } + return scope.createArray(scope.getType(token), dimensions); + + } + + public String toStringExpression(int tab) { + + String s = super.toStringExpression(tab); + if (dimensions == 1) + return s + "[]"; //$NON-NLS-1$ + for (int i = 1; i <= dimensions; i++) + s = s + "[]"; //$NON-NLS-1$ + return s; + } + + public void traverse(IAbstractSyntaxTreeVisitor visitor, BlockScope scope) { + visitor.visit(this, scope); + visitor.endVisit(this, scope); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AssertStatement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AssertStatement.java index 87f61e8..64705dc 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AssertStatement.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AssertStatement.java @@ -21,18 +21,17 @@ import net.sourceforge.phpdt.internal.compiler.lookup.SourceTypeBinding; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class AssertStatement extends Statement { - + public Expression assertExpression, exceptionArgument; // for local variable attribute int preAssertInitStateIndex = -1; + private FieldBinding assertionSyntheticFieldBinding; - - public AssertStatement( - Expression exceptionArgument, - Expression assertExpression, - int startPosition) { - + + public AssertStatement(Expression exceptionArgument, + Expression assertExpression, int startPosition) { + this.assertExpression = assertExpression; this.exceptionArgument = exceptionArgument; sourceStart = startPosition; @@ -46,77 +45,85 @@ public class AssertStatement extends Statement { sourceEnd = assertExpression.sourceEnd; } - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { - - preAssertInitStateIndex = currentScope.methodScope().recordInitializationStates(flowInfo); + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { - Constant cst = this.assertExpression.optimizedBooleanConstant(); - boolean isOptimizedTrueAssertion = cst != NotAConstant && cst.booleanValue() == true; - boolean isOptimizedFalseAssertion = cst != NotAConstant && cst.booleanValue() == false; + preAssertInitStateIndex = currentScope.methodScope() + .recordInitializationStates(flowInfo); + + Constant cst = this.assertExpression.optimizedBooleanConstant(); + boolean isOptimizedTrueAssertion = cst != NotAConstant + && cst.booleanValue() == true; + boolean isOptimizedFalseAssertion = cst != NotAConstant + && cst.booleanValue() == false; FlowInfo assertInfo = flowInfo.copy(); if (isOptimizedTrueAssertion) { assertInfo.setReachMode(FlowInfo.UNREACHABLE); } - assertInfo = assertExpression.analyseCode(currentScope, flowContext, assertInfo).unconditionalInits(); - + assertInfo = assertExpression.analyseCode(currentScope, flowContext, + assertInfo).unconditionalInits(); + if (exceptionArgument != null) { - // only gets evaluated when escaping - results are not taken into account - FlowInfo exceptionInfo = exceptionArgument.analyseCode(currentScope, flowContext, assertInfo.copy()); - - if (!isOptimizedTrueAssertion){ - flowContext.checkExceptionHandlers( - currentScope.getJavaLangAssertionError(), - this, - exceptionInfo, - currentScope); + // only gets evaluated when escaping - results are not taken into + // account + FlowInfo exceptionInfo = exceptionArgument.analyseCode( + currentScope, flowContext, assertInfo.copy()); + + if (!isOptimizedTrueAssertion) { + flowContext.checkExceptionHandlers(currentScope + .getJavaLangAssertionError(), this, exceptionInfo, + currentScope); } } - + // add the assert support in the clinit manageSyntheticAccessIfNecessary(currentScope); if (isOptimizedFalseAssertion) { - return flowInfo; // if assertions are enabled, the following code will be unreachable + return flowInfo; // if assertions are enabled, the following code + // will be unreachable } else { - return flowInfo.mergedWith(assertInfo.unconditionalInits()); + return flowInfo.mergedWith(assertInfo.unconditionalInits()); } } -// public void generateCode(BlockScope currentScope, CodeStream codeStream) { -// -// if ((bits & IsReachableMASK) == 0) { -// return; -// } -// int pc = codeStream.position; -// -// if (this.assertionSyntheticFieldBinding != null) { -// Label assertionActivationLabel = new Label(codeStream); -// codeStream.getstatic(this.assertionSyntheticFieldBinding); -// codeStream.ifne(assertionActivationLabel); -// Label falseLabel = new Label(codeStream); -// assertExpression.generateOptimizedBoolean(currentScope, codeStream, (falseLabel = new Label(codeStream)), null , true); -// codeStream.newJavaLangAssertionError(); -// codeStream.dup(); -// if (exceptionArgument != null) { -// exceptionArgument.generateCode(currentScope, codeStream, true); -// codeStream.invokeJavaLangAssertionErrorConstructor(exceptionArgument.implicitConversion & 0xF); -// } else { -// codeStream.invokeJavaLangAssertionErrorDefaultConstructor(); -// } -// codeStream.athrow(); -// falseLabel.place(); -// assertionActivationLabel.place(); -// } -// -// // May loose some local variable initializations : affecting the local variable attributes -// if (preAssertInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables(currentScope, preAssertInitStateIndex); -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } + // public void generateCode(BlockScope currentScope, CodeStream codeStream) + // { + // + // if ((bits & IsReachableMASK) == 0) { + // return; + // } + // int pc = codeStream.position; + // + // if (this.assertionSyntheticFieldBinding != null) { + // Label assertionActivationLabel = new Label(codeStream); + // codeStream.getstatic(this.assertionSyntheticFieldBinding); + // codeStream.ifne(assertionActivationLabel); + // Label falseLabel = new Label(codeStream); + // assertExpression.generateOptimizedBoolean(currentScope, codeStream, + // (falseLabel = new Label(codeStream)), null , true); + // codeStream.newJavaLangAssertionError(); + // codeStream.dup(); + // if (exceptionArgument != null) { + // exceptionArgument.generateCode(currentScope, codeStream, true); + // codeStream.invokeJavaLangAssertionErrorConstructor(exceptionArgument.implicitConversion + // & 0xF); + // } else { + // codeStream.invokeJavaLangAssertionErrorDefaultConstructor(); + // } + // codeStream.athrow(); + // falseLabel.place(); + // assertionActivationLabel.place(); + // } + // + // // May loose some local variable initializations : affecting the local + // variable attributes + // if (preAssertInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables(currentScope, + // preAssertInitStateIndex); + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } public StringBuffer printStatement(int tab, StringBuffer output) { printIndent(tab, output); @@ -128,20 +135,24 @@ public class AssertStatement extends Statement { } return output.append(';'); } + public void resolve(BlockScope scope) { assertExpression.resolveTypeExpecting(scope, BooleanBinding); if (exceptionArgument != null) { - TypeBinding exceptionArgumentType = exceptionArgument.resolveType(scope); - if (exceptionArgumentType != null){ - if (exceptionArgumentType.id == T_void){ - scope.problemReporter().illegalVoidExpression(exceptionArgument); + TypeBinding exceptionArgumentType = exceptionArgument + .resolveType(scope); + if (exceptionArgumentType != null) { + if (exceptionArgumentType.id == T_void) { + scope.problemReporter().illegalVoidExpression( + exceptionArgument); } - exceptionArgument.implicitConversion = (exceptionArgumentType.id << 4) + exceptionArgumentType.id; + exceptionArgument.implicitConversion = (exceptionArgumentType.id << 4) + + exceptionArgumentType.id; } } } - + public void traverse(ASTVisitor visitor, BlockScope scope) { if (visitor.visit(this, scope)) { @@ -151,20 +162,23 @@ public class AssertStatement extends Statement { } } visitor.endVisit(this, scope); - } - + } + public void manageSyntheticAccessIfNecessary(BlockScope currentScope) { // need assertion flag: $assertionsDisabled on outer most source clas - // (in case of static member of interface, will use the outermost static member - bug 22334) + // (in case of static member of interface, will use the outermost static + // member - bug 22334) SourceTypeBinding outerMostClass = currentScope.enclosingSourceType(); - while (outerMostClass.isLocalType()){ + while (outerMostClass.isLocalType()) { ReferenceBinding enclosing = outerMostClass.enclosingType(); - if (enclosing == null || enclosing.isInterface()) break; + if (enclosing == null || enclosing.isInterface()) + break; outerMostClass = (SourceTypeBinding) enclosing; } - this.assertionSyntheticFieldBinding = outerMostClass.addSyntheticField(this, currentScope); + this.assertionSyntheticFieldBinding = outerMostClass.addSyntheticField( + this, currentScope); // find and enable assertion support TypeDeclaration typeDeclaration = outerMostClass.scope.referenceType(); @@ -172,7 +186,8 @@ public class AssertStatement extends Statement { for (int i = 0, max = methods.length; i < max; i++) { AbstractMethodDeclaration method = methods[i]; if (method.isClinit()) { - ((Clinit) method).addSupportForAssertion(assertionSyntheticFieldBinding); + ((Clinit) method) + .addSupportForAssertion(assertionSyntheticFieldBinding); break; } } @@ -190,5 +205,5 @@ public class AssertStatement extends Statement { } return buffer.toString(); } - + } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Assignment.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Assignment.java index 90a58c8..297f4a0 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Assignment.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Assignment.java @@ -22,152 +22,167 @@ import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class Assignment extends Expression { public Expression lhs; + public Expression expression; - + public Assignment(Expression lhs, Expression expression, int sourceEnd) { - //lhs is always a reference by construction , - //but is build as an expression ==> the checkcast cannot fail + // lhs is always a reference by construction , + // but is build as an expression ==> the checkcast cannot fail this.lhs = lhs; lhs.bits |= IsStrictlyAssignedMASK; // tag lhs as assigned - + this.expression = expression; this.sourceStart = lhs.sourceStart; this.sourceEnd = sourceEnd; } - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { - // record setting a variable: various scenarii are possible, setting an array reference, - // a field reference, a blank final field reference, a field of an enclosing instance or + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { + // record setting a variable: various scenarii are possible, setting an + // array reference, + // a field reference, a blank final field reference, a field of an + // enclosing instance or // just a local variable. - return ((Reference) lhs) - .analyseAssignment(currentScope, flowContext, flowInfo, this, false) - .unconditionalInits(); + return ((Reference) lhs).analyseAssignment(currentScope, flowContext, + flowInfo, this, false).unconditionalInits(); } void checkAssignmentEffect(BlockScope scope) { - + Binding left = getDirectBinding(this.lhs); if (left != null && left == getDirectBinding(this.expression)) { - scope.problemReporter().assignmentHasNoEffect(this, left.shortReadableName()); - this.bits |= IsAssignmentWithNoEffectMASK; // record assignment has no effect + scope.problemReporter().assignmentHasNoEffect(this, + left.shortReadableName()); + this.bits |= IsAssignmentWithNoEffectMASK; // record assignment has + // no effect } } -// public void generateCode( -// BlockScope currentScope, -// CodeStream codeStream, -// boolean valueRequired) { -// -// // various scenarii are possible, setting an array reference, -// // a field reference, a blank final field reference, a field of an enclosing instance or -// // just a local variable. -// -// int pc = codeStream.position; -// if ((this.bits & IsAssignmentWithNoEffectMASK) != 0) { -// if (valueRequired) { -// this.expression.generateCode(currentScope, codeStream, true); -// } -// } else { -// ((Reference) lhs).generateAssignment(currentScope, codeStream, this, valueRequired); -// // variable may have been optimized out -// // the lhs is responsible to perform the implicitConversion generation for the assignment since optimized for unused local assignment. -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } + // public void generateCode( + // BlockScope currentScope, + // CodeStream codeStream, + // boolean valueRequired) { + // + // // various scenarii are possible, setting an array reference, + // // a field reference, a blank final field reference, a field of an + // enclosing instance or + // // just a local variable. + // + // int pc = codeStream.position; + // if ((this.bits & IsAssignmentWithNoEffectMASK) != 0) { + // if (valueRequired) { + // this.expression.generateCode(currentScope, codeStream, true); + // } + // } else { + // ((Reference) lhs).generateAssignment(currentScope, codeStream, this, + // valueRequired); + // // variable may have been optimized out + // // the lhs is responsible to perform the implicitConversion generation + // for the assignment since optimized for unused local assignment. + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } Binding getDirectBinding(Expression someExpression) { if (someExpression instanceof SingleNameReference) { - return ((SingleNameReference)someExpression).binding; + return ((SingleNameReference) someExpression).binding; } else if (someExpression instanceof FieldReference) { - FieldReference fieldRef = (FieldReference)someExpression; - if (fieldRef.receiver.isThis() && !(fieldRef.receiver instanceof QualifiedThisReference)) { + FieldReference fieldRef = (FieldReference) someExpression; + if (fieldRef.receiver.isThis() + && !(fieldRef.receiver instanceof QualifiedThisReference)) { return fieldRef.binding; - } + } } return null; } + public StringBuffer print(int indent, StringBuffer output) { - //no () when used as a statement + // no () when used as a statement printIndent(indent, output); return printExpressionNoParenthesis(indent, output); } + public StringBuffer printExpression(int indent, StringBuffer output) { - //subclass redefine printExpressionNoParenthesis() + // subclass redefine printExpressionNoParenthesis() output.append('('); return printExpressionNoParenthesis(0, output).append(')'); - } + } - public StringBuffer printExpressionNoParenthesis(int indent, StringBuffer output) { + public StringBuffer printExpressionNoParenthesis(int indent, + StringBuffer output) { lhs.printExpression(indent, output).append(" = "); //$NON-NLS-1$ return expression.printExpression(0, output); } - + public StringBuffer printStatement(int indent, StringBuffer output) { - //no () when used as a statement + // no () when used as a statement return print(indent, output).append(';'); } + public TypeBinding resolveType(BlockScope scope) { - // due to syntax lhs may be only a NameReference, a FieldReference or an ArrayReference + // due to syntax lhs may be only a NameReference, a FieldReference or an + // ArrayReference constant = NotAConstant; if (!(this.lhs instanceof Reference)) { scope.problemReporter().expressionShouldBeAVariable(this.lhs); } - this.resolvedType = lhs.resolveType(scope); // expressionType contains the assignment type (lhs Type) + this.resolvedType = lhs.resolveType(scope); // expressionType contains + // the assignment type (lhs + // Type) TypeBinding rhsType = expression.resolveType(scope); if (this.resolvedType == null || rhsType == null) { return null; } checkAssignmentEffect(scope); - - // Compile-time conversion of base-types : implicit narrowing integer into byte/short/character + + // Compile-time conversion of base-types : implicit narrowing integer + // into byte/short/character // may require to widen the rhs expression at runtime - if ((expression.isConstantValueOfTypeAssignableToType(rhsType, this.resolvedType) - || (this.resolvedType.isBaseType() && BaseTypeBinding.isWidening(this.resolvedType.id, rhsType.id))) + if ((expression.isConstantValueOfTypeAssignableToType(rhsType, + this.resolvedType) || (this.resolvedType.isBaseType() && BaseTypeBinding + .isWidening(this.resolvedType.id, rhsType.id))) || rhsType.isCompatibleWith(this.resolvedType)) { expression.implicitWidening(this.resolvedType, rhsType); return this.resolvedType; } scope.problemReporter().typeMismatchErrorActualTypeExpectedType( - expression, - rhsType, - this.resolvedType); + expression, rhsType, this.resolvedType); return this.resolvedType; } public String toString(int tab) { - //no () when used as a statement + // no () when used as a statement return tabString(tab) + toStringExpressionNoParenthesis(); } public String toStringExpression() { - //subclass redefine toStringExpressionNoParenthesis() + // subclass redefine toStringExpressionNoParenthesis() return "(" + toStringExpressionNoParenthesis() + ")"; //$NON-NLS-2$ //$NON-NLS-1$ - } - + } + public String toStringExpressionNoParenthesis() { - return lhs.toStringExpression() + " " //$NON-NLS-1$ - + "=" //$NON-NLS-1$ - + ((expression.constant != null) && (expression.constant != NotAConstant) - ? " /*cst:" + expression.constant.toString() + "*/ " //$NON-NLS-1$ //$NON-NLS-2$ - : " ") //$NON-NLS-1$ - + expression.toStringExpression(); + return lhs.toStringExpression() + + " " //$NON-NLS-1$ + + "=" //$NON-NLS-1$ + + ((expression.constant != null) + && (expression.constant != NotAConstant) ? " /*cst:" + expression.constant.toString() + "*/ " //$NON-NLS-1$ //$NON-NLS-2$ + : " ") //$NON-NLS-1$ + + expression.toStringExpression(); } + public void traverse(ASTVisitor visitor, BlockScope scope) { - + if (visitor.visit(this, scope)) { lhs.traverse(visitor, scope); expression.traverse(visitor, scope); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/BinaryExpression.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/BinaryExpression.java index ce506cb..8a264bc 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/BinaryExpression.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/BinaryExpression.java @@ -21,6 +21,7 @@ import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class BinaryExpression extends OperatorExpression { public Expression left, right; + public Constant optimizedBooleanConstant; public BinaryExpression(Expression left, Expression right, int operator) { @@ -32,1622 +33,1631 @@ public class BinaryExpression extends OperatorExpression { this.sourceEnd = right.sourceEnd; } - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { - return right - .analyseCode( + return right.analyseCode( currentScope, flowContext, - left.analyseCode(currentScope, flowContext, flowInfo).unconditionalInits()) - .unconditionalInits(); + left.analyseCode(currentScope, flowContext, flowInfo) + .unconditionalInits()).unconditionalInits(); } public void computeConstant(BlockScope scope, int leftId, int rightId) { - //compute the constant when valid + // compute the constant when valid if ((this.left.constant != Constant.NotAConstant) - && (this.right.constant != Constant.NotAConstant)) { + && (this.right.constant != Constant.NotAConstant)) { try { - this.constant = - Constant.computeConstantOperation( - this.left.constant, - leftId, + this.constant = Constant.computeConstantOperation( + this.left.constant, leftId, (this.bits & OperatorMASK) >> OperatorSHIFT, - this.right.constant, - rightId); + this.right.constant, rightId); } catch (ArithmeticException e) { this.constant = Constant.NotAConstant; // 1.2 no longer throws an exception at compile-time - //scope.problemReporter().compileTimeConstantThrowsArithmeticException(this); + // scope.problemReporter().compileTimeConstantThrowsArithmeticException(this); } } else { this.constant = Constant.NotAConstant; - //add some work for the boolean operators & | -// this.optimizedBooleanConstant( -// leftId, -// (this.bits & OperatorMASK) >> OperatorSHIFT, -// rightId); + // add some work for the boolean operators & | + // this.optimizedBooleanConstant( + // leftId, + // (this.bits & OperatorMASK) >> OperatorSHIFT, + // rightId); } } public Constant optimizedBooleanConstant() { - return this.optimizedBooleanConstant == null ? this.constant : this.optimizedBooleanConstant; + return this.optimizedBooleanConstant == null ? this.constant + : this.optimizedBooleanConstant; } /** * Code generation for a binary operation */ -// public void generateCode( -// BlockScope currentScope, -// CodeStream codeStream, -// boolean valueRequired) { -// -// int pc = codeStream.position; -// Label falseLabel, endLabel; -// if (constant != Constant.NotAConstant) { -// if (valueRequired) -// codeStream.generateConstant(constant, implicitConversion); -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// return; -// } -// bits |= OnlyValueRequiredMASK; -// switch ((bits & OperatorMASK) >> OperatorSHIFT) { -// case PLUS : -// switch (bits & ReturnTypeIDMASK) { -// case T_String : -// codeStream.generateStringAppend(currentScope, left, right); -// if (!valueRequired) -// codeStream.pop(); -// break; -// case T_int : -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.iadd(); -// break; -// case T_long : -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.ladd(); -// break; -// case T_double : -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.dadd(); -// break; -// case T_float : -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.fadd(); -// break; -// } -// break; -// case MINUS : -// switch (bits & ReturnTypeIDMASK) { -// case T_int : -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.isub(); -// break; -// case T_long : -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.lsub(); -// break; -// case T_double : -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.dsub(); -// break; -// case T_float : -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.fsub(); -// break; -// } -// break; -// case MULTIPLY : -// switch (bits & ReturnTypeIDMASK) { -// case T_int : -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.imul(); -// break; -// case T_long : -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.lmul(); -// break; -// case T_double : -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.dmul(); -// break; -// case T_float : -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.fmul(); -// break; -// } -// break; -// case DIVIDE : -// switch (bits & ReturnTypeIDMASK) { -// case T_int : -// left.generateCode(currentScope, codeStream, true); -// right.generateCode(currentScope, codeStream, true); -// codeStream.idiv(); -// if (!valueRequired) -// codeStream.pop(); -// break; -// case T_long : -// left.generateCode(currentScope, codeStream, true); -// right.generateCode(currentScope, codeStream, true); -// codeStream.ldiv(); -// if (!valueRequired) -// codeStream.pop2(); -// break; -// case T_double : -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.ddiv(); -// break; -// case T_float : -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.fdiv(); -// break; -// } -// break; -// case REMAINDER : -// switch (bits & ReturnTypeIDMASK) { -// case T_int : -// left.generateCode(currentScope, codeStream, true); -// right.generateCode(currentScope, codeStream, true); -// codeStream.irem(); -// if (!valueRequired) -// codeStream.pop(); -// break; -// case T_long : -// left.generateCode(currentScope, codeStream, true); -// right.generateCode(currentScope, codeStream, true); -// codeStream.lrem(); -// if (!valueRequired) -// codeStream.pop2(); -// break; -// case T_double : -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.drem(); -// break; -// case T_float : -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.frem(); -// break; -// } -// break; -// case AND : -// switch (bits & ReturnTypeIDMASK) { -// case T_int : -// // 0 & x -// if ((left.constant != Constant.NotAConstant) -// && (left.constant.typeID() == T_int) -// && (left.constant.intValue() == 0)) { -// right.generateCode(currentScope, codeStream, false); -// if (valueRequired) -// codeStream.iconst_0(); -// } else { -// // x & 0 -// if ((right.constant != Constant.NotAConstant) -// && (right.constant.typeID() == T_int) -// && (right.constant.intValue() == 0)) { -// left.generateCode(currentScope, codeStream, false); -// if (valueRequired) -// codeStream.iconst_0(); -// } else { -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.iand(); -// } -// } -// break; -// case T_long : -// // 0 & x -// if ((left.constant != Constant.NotAConstant) -// && (left.constant.typeID() == T_long) -// && (left.constant.longValue() == 0L)) { -// right.generateCode(currentScope, codeStream, false); -// if (valueRequired) -// codeStream.lconst_0(); -// } else { -// // x & 0 -// if ((right.constant != Constant.NotAConstant) -// && (right.constant.typeID() == T_long) -// && (right.constant.longValue() == 0L)) { -// left.generateCode(currentScope, codeStream, false); -// if (valueRequired) -// codeStream.lconst_0(); -// } else { -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.land(); -// } -// } -// break; -// case T_boolean : // logical and -// generateOptimizedLogicalAnd( -// currentScope, -// codeStream, -// null, -// (falseLabel = new Label(codeStream)), -// valueRequired); -// /* improving code gen for such a case: boolean b = i < 0 && false; -// * since the label has never been used, we have the inlined value on the stack. */ -// if (falseLabel.hasForwardReferences()) { -// if (valueRequired) { -// codeStream.iconst_1(); -// if ((bits & ValueForReturnMASK) != 0) { -// codeStream.ireturn(); -// falseLabel.place(); -// codeStream.iconst_0(); -// } else { -// codeStream.goto_(endLabel = new Label(codeStream)); -// codeStream.decrStackSize(1); -// falseLabel.place(); -// codeStream.iconst_0(); -// endLabel.place(); -// } -// } else { -// falseLabel.place(); -// } -// } -// } -// break; -// case OR : -// switch (bits & ReturnTypeIDMASK) { -// case T_int : -// // 0 | x -// if ((left.constant != Constant.NotAConstant) -// && (left.constant.typeID() == T_int) -// && (left.constant.intValue() == 0)) { -// right.generateCode(currentScope, codeStream, valueRequired); -// } else { -// // x | 0 -// if ((right.constant != Constant.NotAConstant) -// && (right.constant.typeID() == T_int) -// && (right.constant.intValue() == 0)) { -// left.generateCode(currentScope, codeStream, valueRequired); -// } else { -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.ior(); -// } -// } -// break; -// case T_long : -// // 0 | x -// if ((left.constant != Constant.NotAConstant) -// && (left.constant.typeID() == T_long) -// && (left.constant.longValue() == 0L)) { -// right.generateCode(currentScope, codeStream, valueRequired); -// } else { -// // x | 0 -// if ((right.constant != Constant.NotAConstant) -// && (right.constant.typeID() == T_long) -// && (right.constant.longValue() == 0L)) { -// left.generateCode(currentScope, codeStream, valueRequired); -// } else { -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.lor(); -// } -// } -// break; -// case T_boolean : // logical or -// generateOptimizedLogicalOr( -// currentScope, -// codeStream, -// null, -// (falseLabel = new Label(codeStream)), -// valueRequired); -// /* improving code gen for such a case: boolean b = i < 0 || true; -// * since the label has never been used, we have the inlined value on the stack. */ -// if (falseLabel.hasForwardReferences()) { -// if (valueRequired) { -// codeStream.iconst_1(); -// if ((bits & ValueForReturnMASK) != 0) { -// codeStream.ireturn(); -// falseLabel.place(); -// codeStream.iconst_0(); -// } else { -// codeStream.goto_(endLabel = new Label(codeStream)); -// codeStream.decrStackSize(1); -// falseLabel.place(); -// codeStream.iconst_0(); -// endLabel.place(); -// } -// } else { -// falseLabel.place(); -// } -// } -// } -// break; -// case XOR : -// switch (bits & ReturnTypeIDMASK) { -// case T_int : -// // 0 ^ x -// if ((left.constant != Constant.NotAConstant) -// && (left.constant.typeID() == T_int) -// && (left.constant.intValue() == 0)) { -// right.generateCode(currentScope, codeStream, valueRequired); -// } else { -// // x ^ 0 -// if ((right.constant != Constant.NotAConstant) -// && (right.constant.typeID() == T_int) -// && (right.constant.intValue() == 0)) { -// left.generateCode(currentScope, codeStream, valueRequired); -// } else { -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.ixor(); -// } -// } -// break; -// case T_long : -// // 0 ^ x -// if ((left.constant != Constant.NotAConstant) -// && (left.constant.typeID() == T_long) -// && (left.constant.longValue() == 0L)) { -// right.generateCode(currentScope, codeStream, valueRequired); -// } else { -// // x ^ 0 -// if ((right.constant != Constant.NotAConstant) -// && (right.constant.typeID() == T_long) -// && (right.constant.longValue() == 0L)) { -// left.generateCode(currentScope, codeStream, valueRequired); -// } else { -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.lxor(); -// } -// } -// break; -// case T_boolean : -// generateOptimizedLogicalXor( -// currentScope, -// codeStream, -// null, -// (falseLabel = new Label(codeStream)), -// valueRequired); -// /* improving code gen for such a case: boolean b = i < 0 ^ bool; -// * since the label has never been used, we have the inlined value on the stack. */ -// if (falseLabel.hasForwardReferences()) { -// if (valueRequired) { -// codeStream.iconst_1(); -// if ((bits & ValueForReturnMASK) != 0) { -// codeStream.ireturn(); -// falseLabel.place(); -// codeStream.iconst_0(); -// } else { -// codeStream.goto_(endLabel = new Label(codeStream)); -// codeStream.decrStackSize(1); -// falseLabel.place(); -// codeStream.iconst_0(); -// endLabel.place(); -// } -// } else { -// falseLabel.place(); -// } -// } -// } -// break; -// case LEFT_SHIFT : -// switch (bits & ReturnTypeIDMASK) { -// case T_int : -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.ishl(); -// break; -// case T_long : -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.lshl(); -// } -// break; -// case RIGHT_SHIFT : -// switch (bits & ReturnTypeIDMASK) { -// case T_int : -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.ishr(); -// break; -// case T_long : -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.lshr(); -// } -// break; -// case UNSIGNED_RIGHT_SHIFT : -// switch (bits & ReturnTypeIDMASK) { -// case T_int : -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.iushr(); -// break; -// case T_long : -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) -// codeStream.lushr(); -// } -// break; -// case GREATER : -// generateOptimizedGreaterThan( -// currentScope, -// codeStream, -// null, -// (falseLabel = new Label(codeStream)), -// valueRequired); -// if (valueRequired) { -// codeStream.iconst_1(); -// if ((bits & ValueForReturnMASK) != 0) { -// codeStream.ireturn(); -// falseLabel.place(); -// codeStream.iconst_0(); -// } else { -// codeStream.goto_(endLabel = new Label(codeStream)); -// codeStream.decrStackSize(1); -// falseLabel.place(); -// codeStream.iconst_0(); -// endLabel.place(); -// } -// } -// break; -// case GREATER_EQUAL : -// generateOptimizedGreaterThanOrEqual( -// currentScope, -// codeStream, -// null, -// (falseLabel = new Label(codeStream)), -// valueRequired); -// if (valueRequired) { -// codeStream.iconst_1(); -// if ((bits & ValueForReturnMASK) != 0) { -// codeStream.ireturn(); -// falseLabel.place(); -// codeStream.iconst_0(); -// } else { -// codeStream.goto_(endLabel = new Label(codeStream)); -// codeStream.decrStackSize(1); -// falseLabel.place(); -// codeStream.iconst_0(); -// endLabel.place(); -// } -// } -// break; -// case LESS : -// generateOptimizedLessThan( -// currentScope, -// codeStream, -// null, -// (falseLabel = new Label(codeStream)), -// valueRequired); -// if (valueRequired) { -// codeStream.iconst_1(); -// if ((bits & ValueForReturnMASK) != 0) { -// codeStream.ireturn(); -// falseLabel.place(); -// codeStream.iconst_0(); -// } else { -// codeStream.goto_(endLabel = new Label(codeStream)); -// codeStream.decrStackSize(1); -// falseLabel.place(); -// codeStream.iconst_0(); -// endLabel.place(); -// } -// } -// break; -// case LESS_EQUAL : -// generateOptimizedLessThanOrEqual( -// currentScope, -// codeStream, -// null, -// (falseLabel = new Label(codeStream)), -// valueRequired); -// if (valueRequired) { -// codeStream.iconst_1(); -// if ((bits & ValueForReturnMASK) != 0) { -// codeStream.ireturn(); -// falseLabel.place(); -// codeStream.iconst_0(); -// } else { -// codeStream.goto_(endLabel = new Label(codeStream)); -// codeStream.decrStackSize(1); -// falseLabel.place(); -// codeStream.iconst_0(); -// endLabel.place(); -// } -// } -// } -// if (valueRequired) { -// codeStream.generateImplicitConversion(implicitConversion); -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } - + // public void generateCode( + // BlockScope currentScope, + // CodeStream codeStream, + // boolean valueRequired) { + // + // int pc = codeStream.position; + // Label falseLabel, endLabel; + // if (constant != Constant.NotAConstant) { + // if (valueRequired) + // codeStream.generateConstant(constant, implicitConversion); + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // return; + // } + // bits |= OnlyValueRequiredMASK; + // switch ((bits & OperatorMASK) >> OperatorSHIFT) { + // case PLUS : + // switch (bits & ReturnTypeIDMASK) { + // case T_String : + // codeStream.generateStringAppend(currentScope, left, right); + // if (!valueRequired) + // codeStream.pop(); + // break; + // case T_int : + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.iadd(); + // break; + // case T_long : + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.ladd(); + // break; + // case T_double : + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.dadd(); + // break; + // case T_float : + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.fadd(); + // break; + // } + // break; + // case MINUS : + // switch (bits & ReturnTypeIDMASK) { + // case T_int : + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.isub(); + // break; + // case T_long : + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.lsub(); + // break; + // case T_double : + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.dsub(); + // break; + // case T_float : + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.fsub(); + // break; + // } + // break; + // case MULTIPLY : + // switch (bits & ReturnTypeIDMASK) { + // case T_int : + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.imul(); + // break; + // case T_long : + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.lmul(); + // break; + // case T_double : + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.dmul(); + // break; + // case T_float : + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.fmul(); + // break; + // } + // break; + // case DIVIDE : + // switch (bits & ReturnTypeIDMASK) { + // case T_int : + // left.generateCode(currentScope, codeStream, true); + // right.generateCode(currentScope, codeStream, true); + // codeStream.idiv(); + // if (!valueRequired) + // codeStream.pop(); + // break; + // case T_long : + // left.generateCode(currentScope, codeStream, true); + // right.generateCode(currentScope, codeStream, true); + // codeStream.ldiv(); + // if (!valueRequired) + // codeStream.pop2(); + // break; + // case T_double : + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.ddiv(); + // break; + // case T_float : + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.fdiv(); + // break; + // } + // break; + // case REMAINDER : + // switch (bits & ReturnTypeIDMASK) { + // case T_int : + // left.generateCode(currentScope, codeStream, true); + // right.generateCode(currentScope, codeStream, true); + // codeStream.irem(); + // if (!valueRequired) + // codeStream.pop(); + // break; + // case T_long : + // left.generateCode(currentScope, codeStream, true); + // right.generateCode(currentScope, codeStream, true); + // codeStream.lrem(); + // if (!valueRequired) + // codeStream.pop2(); + // break; + // case T_double : + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.drem(); + // break; + // case T_float : + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.frem(); + // break; + // } + // break; + // case AND : + // switch (bits & ReturnTypeIDMASK) { + // case T_int : + // // 0 & x + // if ((left.constant != Constant.NotAConstant) + // && (left.constant.typeID() == T_int) + // && (left.constant.intValue() == 0)) { + // right.generateCode(currentScope, codeStream, false); + // if (valueRequired) + // codeStream.iconst_0(); + // } else { + // // x & 0 + // if ((right.constant != Constant.NotAConstant) + // && (right.constant.typeID() == T_int) + // && (right.constant.intValue() == 0)) { + // left.generateCode(currentScope, codeStream, false); + // if (valueRequired) + // codeStream.iconst_0(); + // } else { + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.iand(); + // } + // } + // break; + // case T_long : + // // 0 & x + // if ((left.constant != Constant.NotAConstant) + // && (left.constant.typeID() == T_long) + // && (left.constant.longValue() == 0L)) { + // right.generateCode(currentScope, codeStream, false); + // if (valueRequired) + // codeStream.lconst_0(); + // } else { + // // x & 0 + // if ((right.constant != Constant.NotAConstant) + // && (right.constant.typeID() == T_long) + // && (right.constant.longValue() == 0L)) { + // left.generateCode(currentScope, codeStream, false); + // if (valueRequired) + // codeStream.lconst_0(); + // } else { + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.land(); + // } + // } + // break; + // case T_boolean : // logical and + // generateOptimizedLogicalAnd( + // currentScope, + // codeStream, + // null, + // (falseLabel = new Label(codeStream)), + // valueRequired); + // /* improving code gen for such a case: boolean b = i < 0 && false; + // * since the label has never been used, we have the inlined value on the + // stack. */ + // if (falseLabel.hasForwardReferences()) { + // if (valueRequired) { + // codeStream.iconst_1(); + // if ((bits & ValueForReturnMASK) != 0) { + // codeStream.ireturn(); + // falseLabel.place(); + // codeStream.iconst_0(); + // } else { + // codeStream.goto_(endLabel = new Label(codeStream)); + // codeStream.decrStackSize(1); + // falseLabel.place(); + // codeStream.iconst_0(); + // endLabel.place(); + // } + // } else { + // falseLabel.place(); + // } + // } + // } + // break; + // case OR : + // switch (bits & ReturnTypeIDMASK) { + // case T_int : + // // 0 | x + // if ((left.constant != Constant.NotAConstant) + // && (left.constant.typeID() == T_int) + // && (left.constant.intValue() == 0)) { + // right.generateCode(currentScope, codeStream, valueRequired); + // } else { + // // x | 0 + // if ((right.constant != Constant.NotAConstant) + // && (right.constant.typeID() == T_int) + // && (right.constant.intValue() == 0)) { + // left.generateCode(currentScope, codeStream, valueRequired); + // } else { + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.ior(); + // } + // } + // break; + // case T_long : + // // 0 | x + // if ((left.constant != Constant.NotAConstant) + // && (left.constant.typeID() == T_long) + // && (left.constant.longValue() == 0L)) { + // right.generateCode(currentScope, codeStream, valueRequired); + // } else { + // // x | 0 + // if ((right.constant != Constant.NotAConstant) + // && (right.constant.typeID() == T_long) + // && (right.constant.longValue() == 0L)) { + // left.generateCode(currentScope, codeStream, valueRequired); + // } else { + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.lor(); + // } + // } + // break; + // case T_boolean : // logical or + // generateOptimizedLogicalOr( + // currentScope, + // codeStream, + // null, + // (falseLabel = new Label(codeStream)), + // valueRequired); + // /* improving code gen for such a case: boolean b = i < 0 || true; + // * since the label has never been used, we have the inlined value on the + // stack. */ + // if (falseLabel.hasForwardReferences()) { + // if (valueRequired) { + // codeStream.iconst_1(); + // if ((bits & ValueForReturnMASK) != 0) { + // codeStream.ireturn(); + // falseLabel.place(); + // codeStream.iconst_0(); + // } else { + // codeStream.goto_(endLabel = new Label(codeStream)); + // codeStream.decrStackSize(1); + // falseLabel.place(); + // codeStream.iconst_0(); + // endLabel.place(); + // } + // } else { + // falseLabel.place(); + // } + // } + // } + // break; + // case XOR : + // switch (bits & ReturnTypeIDMASK) { + // case T_int : + // // 0 ^ x + // if ((left.constant != Constant.NotAConstant) + // && (left.constant.typeID() == T_int) + // && (left.constant.intValue() == 0)) { + // right.generateCode(currentScope, codeStream, valueRequired); + // } else { + // // x ^ 0 + // if ((right.constant != Constant.NotAConstant) + // && (right.constant.typeID() == T_int) + // && (right.constant.intValue() == 0)) { + // left.generateCode(currentScope, codeStream, valueRequired); + // } else { + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.ixor(); + // } + // } + // break; + // case T_long : + // // 0 ^ x + // if ((left.constant != Constant.NotAConstant) + // && (left.constant.typeID() == T_long) + // && (left.constant.longValue() == 0L)) { + // right.generateCode(currentScope, codeStream, valueRequired); + // } else { + // // x ^ 0 + // if ((right.constant != Constant.NotAConstant) + // && (right.constant.typeID() == T_long) + // && (right.constant.longValue() == 0L)) { + // left.generateCode(currentScope, codeStream, valueRequired); + // } else { + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.lxor(); + // } + // } + // break; + // case T_boolean : + // generateOptimizedLogicalXor( + // currentScope, + // codeStream, + // null, + // (falseLabel = new Label(codeStream)), + // valueRequired); + // /* improving code gen for such a case: boolean b = i < 0 ^ bool; + // * since the label has never been used, we have the inlined value on the + // stack. */ + // if (falseLabel.hasForwardReferences()) { + // if (valueRequired) { + // codeStream.iconst_1(); + // if ((bits & ValueForReturnMASK) != 0) { + // codeStream.ireturn(); + // falseLabel.place(); + // codeStream.iconst_0(); + // } else { + // codeStream.goto_(endLabel = new Label(codeStream)); + // codeStream.decrStackSize(1); + // falseLabel.place(); + // codeStream.iconst_0(); + // endLabel.place(); + // } + // } else { + // falseLabel.place(); + // } + // } + // } + // break; + // case LEFT_SHIFT : + // switch (bits & ReturnTypeIDMASK) { + // case T_int : + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.ishl(); + // break; + // case T_long : + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.lshl(); + // } + // break; + // case RIGHT_SHIFT : + // switch (bits & ReturnTypeIDMASK) { + // case T_int : + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.ishr(); + // break; + // case T_long : + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.lshr(); + // } + // break; + // case UNSIGNED_RIGHT_SHIFT : + // switch (bits & ReturnTypeIDMASK) { + // case T_int : + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.iushr(); + // break; + // case T_long : + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) + // codeStream.lushr(); + // } + // break; + // case GREATER : + // generateOptimizedGreaterThan( + // currentScope, + // codeStream, + // null, + // (falseLabel = new Label(codeStream)), + // valueRequired); + // if (valueRequired) { + // codeStream.iconst_1(); + // if ((bits & ValueForReturnMASK) != 0) { + // codeStream.ireturn(); + // falseLabel.place(); + // codeStream.iconst_0(); + // } else { + // codeStream.goto_(endLabel = new Label(codeStream)); + // codeStream.decrStackSize(1); + // falseLabel.place(); + // codeStream.iconst_0(); + // endLabel.place(); + // } + // } + // break; + // case GREATER_EQUAL : + // generateOptimizedGreaterThanOrEqual( + // currentScope, + // codeStream, + // null, + // (falseLabel = new Label(codeStream)), + // valueRequired); + // if (valueRequired) { + // codeStream.iconst_1(); + // if ((bits & ValueForReturnMASK) != 0) { + // codeStream.ireturn(); + // falseLabel.place(); + // codeStream.iconst_0(); + // } else { + // codeStream.goto_(endLabel = new Label(codeStream)); + // codeStream.decrStackSize(1); + // falseLabel.place(); + // codeStream.iconst_0(); + // endLabel.place(); + // } + // } + // break; + // case LESS : + // generateOptimizedLessThan( + // currentScope, + // codeStream, + // null, + // (falseLabel = new Label(codeStream)), + // valueRequired); + // if (valueRequired) { + // codeStream.iconst_1(); + // if ((bits & ValueForReturnMASK) != 0) { + // codeStream.ireturn(); + // falseLabel.place(); + // codeStream.iconst_0(); + // } else { + // codeStream.goto_(endLabel = new Label(codeStream)); + // codeStream.decrStackSize(1); + // falseLabel.place(); + // codeStream.iconst_0(); + // endLabel.place(); + // } + // } + // break; + // case LESS_EQUAL : + // generateOptimizedLessThanOrEqual( + // currentScope, + // codeStream, + // null, + // (falseLabel = new Label(codeStream)), + // valueRequired); + // if (valueRequired) { + // codeStream.iconst_1(); + // if ((bits & ValueForReturnMASK) != 0) { + // codeStream.ireturn(); + // falseLabel.place(); + // codeStream.iconst_0(); + // } else { + // codeStream.goto_(endLabel = new Label(codeStream)); + // codeStream.decrStackSize(1); + // falseLabel.place(); + // codeStream.iconst_0(); + // endLabel.place(); + // } + // } + // } + // if (valueRequired) { + // codeStream.generateImplicitConversion(implicitConversion); + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } /** - * Boolean operator code generation - * Optimized operations are: <, <=, >, >=, &, |, ^ + * Boolean operator code generation Optimized operations are: <, <=, >, >=, &, |, ^ */ -// public void generateOptimizedBoolean( -// BlockScope currentScope, -// CodeStream codeStream, -// Label trueLabel, -// Label falseLabel, -// boolean valueRequired) { -// -// if ((constant != Constant.NotAConstant) && (constant.typeID() == T_boolean)) { -// super.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// valueRequired); -// return; -// } -// switch ((bits & OperatorMASK) >> OperatorSHIFT) { -// case LESS : -// generateOptimizedLessThan( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// valueRequired); -// return; -// case LESS_EQUAL : -// generateOptimizedLessThanOrEqual( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// valueRequired); -// return; -// case GREATER : -// generateOptimizedGreaterThan( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// valueRequired); -// return; -// case GREATER_EQUAL : -// generateOptimizedGreaterThanOrEqual( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// valueRequired); -// return; -// case AND : -// generateOptimizedLogicalAnd( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// valueRequired); -// return; -// case OR : -// generateOptimizedLogicalOr( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// valueRequired); -// return; -// case XOR : -// generateOptimizedLogicalXor( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// valueRequired); -// return; -// } -// super.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// valueRequired); -// } -// -// /** -// * Boolean generation for > -// */ -// public void generateOptimizedGreaterThan( -// BlockScope currentScope, -// CodeStream codeStream, -// Label trueLabel, -// Label falseLabel, -// boolean valueRequired) { -// -// int promotedTypeID = left.implicitConversion >> 4; -// // both sides got promoted in the same way -// if (promotedTypeID == T_int) { -// // 0 > x -// if ((left.constant != NotAConstant) && (left.constant.intValue() == 0)) { -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) { -// if (falseLabel == null) { -// if (trueLabel != null) { -// // implicitly falling through the FALSE case -// codeStream.iflt(trueLabel); -// } -// } else { -// if (trueLabel == null) { -// // implicitly falling through the TRUE case -// codeStream.ifge(falseLabel); -// } else { -// // no implicit fall through TRUE/FALSE --> should never occur -// } -// } -// } -// // reposition the endPC -// codeStream.updateLastRecordedEndPC(codeStream.position); -// return; -// } -// // x > 0 -// if ((right.constant != NotAConstant) && (right.constant.intValue() == 0)) { -// left.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) { -// if (falseLabel == null) { -// if (trueLabel != null) { -// // implicitly falling through the FALSE case -// codeStream.ifgt(trueLabel); -// } -// } else { -// if (trueLabel == null) { -// // implicitly falling through the TRUE case -// codeStream.ifle(falseLabel); -// } else { -// // no implicit fall through TRUE/FALSE --> should never occur -// } -// } -// } -// // reposition the endPC -// codeStream.updateLastRecordedEndPC(codeStream.position); -// return; -// } -// } -// // default comparison -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) { -// if (falseLabel == null) { -// if (trueLabel != null) { -// // implicit falling through the FALSE case -// switch (promotedTypeID) { -// case T_int : -// codeStream.if_icmpgt(trueLabel); -// break; -// case T_float : -// codeStream.fcmpl(); -// codeStream.ifgt(trueLabel); -// break; -// case T_long : -// codeStream.lcmp(); -// codeStream.ifgt(trueLabel); -// break; -// case T_double : -// codeStream.dcmpl(); -// codeStream.ifgt(trueLabel); -// } -// // reposition the endPC -// codeStream.updateLastRecordedEndPC(codeStream.position); -// return; -// } -// } else { -// if (trueLabel == null) { -// // implicit falling through the TRUE case -// switch (promotedTypeID) { -// case T_int : -// codeStream.if_icmple(falseLabel); -// break; -// case T_float : -// codeStream.fcmpl(); -// codeStream.ifle(falseLabel); -// break; -// case T_long : -// codeStream.lcmp(); -// codeStream.ifle(falseLabel); -// break; -// case T_double : -// codeStream.dcmpl(); -// codeStream.ifle(falseLabel); -// } -// // reposition the endPC -// codeStream.updateLastRecordedEndPC(codeStream.position); -// return; -// } else { -// // no implicit fall through TRUE/FALSE --> should never occur -// } -// } -// } -// } - + // public void generateOptimizedBoolean( + // BlockScope currentScope, + // CodeStream codeStream, + // Label trueLabel, + // Label falseLabel, + // boolean valueRequired) { + // + // if ((constant != Constant.NotAConstant) && (constant.typeID() == + // T_boolean)) { + // super.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // valueRequired); + // return; + // } + // switch ((bits & OperatorMASK) >> OperatorSHIFT) { + // case LESS : + // generateOptimizedLessThan( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // valueRequired); + // return; + // case LESS_EQUAL : + // generateOptimizedLessThanOrEqual( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // valueRequired); + // return; + // case GREATER : + // generateOptimizedGreaterThan( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // valueRequired); + // return; + // case GREATER_EQUAL : + // generateOptimizedGreaterThanOrEqual( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // valueRequired); + // return; + // case AND : + // generateOptimizedLogicalAnd( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // valueRequired); + // return; + // case OR : + // generateOptimizedLogicalOr( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // valueRequired); + // return; + // case XOR : + // generateOptimizedLogicalXor( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // valueRequired); + // return; + // } + // super.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // valueRequired); + // } + // + // /** + // * Boolean generation for > + // */ + // public void generateOptimizedGreaterThan( + // BlockScope currentScope, + // CodeStream codeStream, + // Label trueLabel, + // Label falseLabel, + // boolean valueRequired) { + // + // int promotedTypeID = left.implicitConversion >> 4; + // // both sides got promoted in the same way + // if (promotedTypeID == T_int) { + // // 0 > x + // if ((left.constant != NotAConstant) && (left.constant.intValue() == 0)) { + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) { + // if (falseLabel == null) { + // if (trueLabel != null) { + // // implicitly falling through the FALSE case + // codeStream.iflt(trueLabel); + // } + // } else { + // if (trueLabel == null) { + // // implicitly falling through the TRUE case + // codeStream.ifge(falseLabel); + // } else { + // // no implicit fall through TRUE/FALSE --> should never occur + // } + // } + // } + // // reposition the endPC + // codeStream.updateLastRecordedEndPC(codeStream.position); + // return; + // } + // // x > 0 + // if ((right.constant != NotAConstant) && (right.constant.intValue() == 0)) + // { + // left.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) { + // if (falseLabel == null) { + // if (trueLabel != null) { + // // implicitly falling through the FALSE case + // codeStream.ifgt(trueLabel); + // } + // } else { + // if (trueLabel == null) { + // // implicitly falling through the TRUE case + // codeStream.ifle(falseLabel); + // } else { + // // no implicit fall through TRUE/FALSE --> should never occur + // } + // } + // } + // // reposition the endPC + // codeStream.updateLastRecordedEndPC(codeStream.position); + // return; + // } + // } + // // default comparison + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) { + // if (falseLabel == null) { + // if (trueLabel != null) { + // // implicit falling through the FALSE case + // switch (promotedTypeID) { + // case T_int : + // codeStream.if_icmpgt(trueLabel); + // break; + // case T_float : + // codeStream.fcmpl(); + // codeStream.ifgt(trueLabel); + // break; + // case T_long : + // codeStream.lcmp(); + // codeStream.ifgt(trueLabel); + // break; + // case T_double : + // codeStream.dcmpl(); + // codeStream.ifgt(trueLabel); + // } + // // reposition the endPC + // codeStream.updateLastRecordedEndPC(codeStream.position); + // return; + // } + // } else { + // if (trueLabel == null) { + // // implicit falling through the TRUE case + // switch (promotedTypeID) { + // case T_int : + // codeStream.if_icmple(falseLabel); + // break; + // case T_float : + // codeStream.fcmpl(); + // codeStream.ifle(falseLabel); + // break; + // case T_long : + // codeStream.lcmp(); + // codeStream.ifle(falseLabel); + // break; + // case T_double : + // codeStream.dcmpl(); + // codeStream.ifle(falseLabel); + // } + // // reposition the endPC + // codeStream.updateLastRecordedEndPC(codeStream.position); + // return; + // } else { + // // no implicit fall through TRUE/FALSE --> should never occur + // } + // } + // } + // } /** * Boolean generation for >= */ -// public void generateOptimizedGreaterThanOrEqual( -// BlockScope currentScope, -// CodeStream codeStream, -// Label trueLabel, -// Label falseLabel, -// boolean valueRequired) { -// -// int promotedTypeID = left.implicitConversion >> 4; -// // both sides got promoted in the same way -// if (promotedTypeID == T_int) { -// // 0 >= x -// if ((left.constant != NotAConstant) && (left.constant.intValue() == 0)) { -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) { -// if (falseLabel == null) { -// if (trueLabel != null) { -// // implicitly falling through the FALSE case -// codeStream.ifle(trueLabel); -// } -// } else { -// if (trueLabel == null) { -// // implicitly falling through the TRUE case -// codeStream.ifgt(falseLabel); -// } else { -// // no implicit fall through TRUE/FALSE --> should never occur -// } -// } -// } -// // reposition the endPC -// codeStream.updateLastRecordedEndPC(codeStream.position); -// return; -// } -// // x >= 0 -// if ((right.constant != NotAConstant) && (right.constant.intValue() == 0)) { -// left.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) { -// if (falseLabel == null) { -// if (trueLabel != null) { -// // implicitly falling through the FALSE case -// codeStream.ifge(trueLabel); -// } -// } else { -// if (trueLabel == null) { -// // implicitly falling through the TRUE case -// codeStream.iflt(falseLabel); -// } else { -// // no implicit fall through TRUE/FALSE --> should never occur -// } -// } -// } -// // reposition the endPC -// codeStream.updateLastRecordedEndPC(codeStream.position); -// return; -// } -// } -// // default comparison -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) { -// if (falseLabel == null) { -// if (trueLabel != null) { -// // implicit falling through the FALSE case -// switch (promotedTypeID) { -// case T_int : -// codeStream.if_icmpge(trueLabel); -// break; -// case T_float : -// codeStream.fcmpl(); -// codeStream.ifge(trueLabel); -// break; -// case T_long : -// codeStream.lcmp(); -// codeStream.ifge(trueLabel); -// break; -// case T_double : -// codeStream.dcmpl(); -// codeStream.ifge(trueLabel); -// } -// // reposition the endPC -// codeStream.updateLastRecordedEndPC(codeStream.position); -// return; -// } -// } else { -// if (trueLabel == null) { -// // implicit falling through the TRUE case -// switch (promotedTypeID) { -// case T_int : -// codeStream.if_icmplt(falseLabel); -// break; -// case T_float : -// codeStream.fcmpl(); -// codeStream.iflt(falseLabel); -// break; -// case T_long : -// codeStream.lcmp(); -// codeStream.iflt(falseLabel); -// break; -// case T_double : -// codeStream.dcmpl(); -// codeStream.iflt(falseLabel); -// } -// // reposition the endPC -// codeStream.updateLastRecordedEndPC(codeStream.position); -// return; -// } else { -// // no implicit fall through TRUE/FALSE --> should never occur -// } -// } -// } -// } -// -// /** -// * Boolean generation for < -// */ -// public void generateOptimizedLessThan( -// BlockScope currentScope, -// CodeStream codeStream, -// Label trueLabel, -// Label falseLabel, -// boolean valueRequired) { -// -// int promotedTypeID = left.implicitConversion >> 4; -// // both sides got promoted in the same way -// if (promotedTypeID == T_int) { -// // 0 < x -// if ((left.constant != NotAConstant) && (left.constant.intValue() == 0)) { -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) { -// if (falseLabel == null) { -// if (trueLabel != null) { -// // implicitly falling through the FALSE case -// codeStream.ifgt(trueLabel); -// } -// } else { -// if (trueLabel == null) { -// // implicitly falling through the TRUE case -// codeStream.ifle(falseLabel); -// } else { -// // no implicit fall through TRUE/FALSE --> should never occur -// } -// } -// } -// codeStream.updateLastRecordedEndPC(codeStream.position); -// return; -// } -// // x < 0 -// if ((right.constant != NotAConstant) && (right.constant.intValue() == 0)) { -// left.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) { -// if (falseLabel == null) { -// if (trueLabel != null) { -// // implicitly falling through the FALSE case -// codeStream.iflt(trueLabel); -// } -// } else { -// if (trueLabel == null) { -// // implicitly falling through the TRUE case -// codeStream.ifge(falseLabel); -// } else { -// // no implicit fall through TRUE/FALSE --> should never occur -// } -// } -// } -// codeStream.updateLastRecordedEndPC(codeStream.position); -// return; -// } -// } -// // default comparison -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) { -// if (falseLabel == null) { -// if (trueLabel != null) { -// // implicit falling through the FALSE case -// switch (promotedTypeID) { -// case T_int : -// codeStream.if_icmplt(trueLabel); -// break; -// case T_float : -// codeStream.fcmpg(); -// codeStream.iflt(trueLabel); -// break; -// case T_long : -// codeStream.lcmp(); -// codeStream.iflt(trueLabel); -// break; -// case T_double : -// codeStream.dcmpg(); -// codeStream.iflt(trueLabel); -// } -// codeStream.updateLastRecordedEndPC(codeStream.position); -// return; -// } -// } else { -// if (trueLabel == null) { -// // implicit falling through the TRUE case -// switch (promotedTypeID) { -// case T_int : -// codeStream.if_icmpge(falseLabel); -// break; -// case T_float : -// codeStream.fcmpg(); -// codeStream.ifge(falseLabel); -// break; -// case T_long : -// codeStream.lcmp(); -// codeStream.ifge(falseLabel); -// break; -// case T_double : -// codeStream.dcmpg(); -// codeStream.ifge(falseLabel); -// } -// codeStream.updateLastRecordedEndPC(codeStream.position); -// return; -// } else { -// // no implicit fall through TRUE/FALSE --> should never occur -// } -// } -// } -// } -// -// /** -// * Boolean generation for <= -// */ -// public void generateOptimizedLessThanOrEqual( -// BlockScope currentScope, -// CodeStream codeStream, -// Label trueLabel, -// Label falseLabel, -// boolean valueRequired) { -// -// int promotedTypeID = left.implicitConversion >> 4; -// // both sides got promoted in the same way -// if (promotedTypeID == T_int) { -// // 0 <= x -// if ((left.constant != NotAConstant) && (left.constant.intValue() == 0)) { -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) { -// if (falseLabel == null) { -// if (trueLabel != null) { -// // implicitly falling through the FALSE case -// codeStream.ifge(trueLabel); -// } -// } else { -// if (trueLabel == null) { -// // implicitly falling through the TRUE case -// codeStream.iflt(falseLabel); -// } else { -// // no implicit fall through TRUE/FALSE --> should never occur -// } -// } -// } -// // reposition the endPC -// codeStream.updateLastRecordedEndPC(codeStream.position); -// return; -// } -// // x <= 0 -// if ((right.constant != NotAConstant) && (right.constant.intValue() == 0)) { -// left.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) { -// if (falseLabel == null) { -// if (trueLabel != null) { -// // implicitly falling through the FALSE case -// codeStream.ifle(trueLabel); -// } -// } else { -// if (trueLabel == null) { -// // implicitly falling through the TRUE case -// codeStream.ifgt(falseLabel); -// } else { -// // no implicit fall through TRUE/FALSE --> should never occur -// } -// } -// } -// // reposition the endPC -// codeStream.updateLastRecordedEndPC(codeStream.position); -// return; -// } -// } -// // default comparison -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) { -// if (falseLabel == null) { -// if (trueLabel != null) { -// // implicit falling through the FALSE case -// switch (promotedTypeID) { -// case T_int : -// codeStream.if_icmple(trueLabel); -// break; -// case T_float : -// codeStream.fcmpg(); -// codeStream.ifle(trueLabel); -// break; -// case T_long : -// codeStream.lcmp(); -// codeStream.ifle(trueLabel); -// break; -// case T_double : -// codeStream.dcmpg(); -// codeStream.ifle(trueLabel); -// } -// // reposition the endPC -// codeStream.updateLastRecordedEndPC(codeStream.position); -// return; -// } -// } else { -// if (trueLabel == null) { -// // implicit falling through the TRUE case -// switch (promotedTypeID) { -// case T_int : -// codeStream.if_icmpgt(falseLabel); -// break; -// case T_float : -// codeStream.fcmpg(); -// codeStream.ifgt(falseLabel); -// break; -// case T_long : -// codeStream.lcmp(); -// codeStream.ifgt(falseLabel); -// break; -// case T_double : -// codeStream.dcmpg(); -// codeStream.ifgt(falseLabel); -// } -// // reposition the endPC -// codeStream.updateLastRecordedEndPC(codeStream.position); -// return; -// } else { -// // no implicit fall through TRUE/FALSE --> should never occur -// } -// } -// } -// } -// -// /** -// * Boolean generation for & -// */ -// public void generateOptimizedLogicalAnd( -// BlockScope currentScope, -// CodeStream codeStream, -// Label trueLabel, -// Label falseLabel, -// boolean valueRequired) { -// -// Constant condConst; -// if ((left.implicitConversion & 0xF) == T_boolean) { -// if ((condConst = left.optimizedBooleanConstant()) != NotAConstant) { -// if (condConst.booleanValue() == true) { -// // & x -// left.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// false); -// if ((bits & OnlyValueRequiredMASK) != 0) { -// right.generateCode(currentScope, codeStream, valueRequired); -// } else { -// right.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// valueRequired); -// } -// } else { -// // & x -// left.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// false); -// right.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// false); -// if (valueRequired) { -// if ((bits & OnlyValueRequiredMASK) != 0) { -// codeStream.iconst_0(); -// } else { -// if (falseLabel != null) { -// // implicit falling through the TRUE case -// codeStream.goto_(falseLabel); -// } -// } -// } -// // reposition the endPC -// codeStream.updateLastRecordedEndPC(codeStream.position); -// } -// return; -// } -// if ((condConst = right.optimizedBooleanConstant()) != NotAConstant) { -// if (condConst.booleanValue() == true) { -// // x & -// if ((bits & OnlyValueRequiredMASK) != 0) { -// left.generateCode(currentScope, codeStream, valueRequired); -// } else { -// left.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// valueRequired); -// } -// right.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// false); -// } else { -// // x & -// left.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// false); -// right.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// false); -// if (valueRequired) { -// if ((bits & OnlyValueRequiredMASK) != 0) { -// codeStream.iconst_0(); -// } else { -// if (falseLabel != null) { -// // implicit falling through the TRUE case -// codeStream.goto_(falseLabel); -// } -// } -// } -// // reposition the endPC -// codeStream.updateLastRecordedEndPC(codeStream.position); -// } -// return; -// } -// } -// // default case -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) { -// codeStream.iand(); -// if ((bits & OnlyValueRequiredMASK) == 0) { -// if (falseLabel == null) { -// if (trueLabel != null) { -// // implicit falling through the FALSE case -// codeStream.ifne(trueLabel); -// } -// } else { -// // implicit falling through the TRUE case -// if (trueLabel == null) { -// codeStream.ifeq(falseLabel); -// } else { -// // no implicit fall through TRUE/FALSE --> should never occur -// } -// } -// } -// } -// // reposition the endPC -// codeStream.updateLastRecordedEndPC(codeStream.position); -// } -// -// /** -// * Boolean generation for | -// */ -// public void generateOptimizedLogicalOr( -// BlockScope currentScope, -// CodeStream codeStream, -// Label trueLabel, -// Label falseLabel, -// boolean valueRequired) { -// -// Constant condConst; -// if ((left.implicitConversion & 0xF) == T_boolean) { -// if ((condConst = left.optimizedBooleanConstant()) != NotAConstant) { -// if (condConst.booleanValue() == true) { -// // | x -// left.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// false); -// right.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// false); -// if (valueRequired) { -// if ((bits & OnlyValueRequiredMASK) != 0) { -// codeStream.iconst_1(); -// } else { -// if (trueLabel != null) { -// codeStream.goto_(trueLabel); -// } -// } -// } -// // reposition the endPC -// codeStream.updateLastRecordedEndPC(codeStream.position); -// } else { -// // | x -// left.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// false); -// if ((bits & OnlyValueRequiredMASK) != 0) { -// right.generateCode(currentScope, codeStream, valueRequired); -// } else { -// right.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// valueRequired); -// } -// } -// return; -// } -// if ((condConst = right.optimizedBooleanConstant()) != NotAConstant) { -// if (condConst.booleanValue() == true) { -// // x | -// left.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// false); -// right.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// false); -// if (valueRequired) { -// if ((bits & OnlyValueRequiredMASK) != 0) { -// codeStream.iconst_1(); -// } else { -// if (trueLabel != null) { -// codeStream.goto_(trueLabel); -// } -// } -// } -// // reposition the endPC -// codeStream.updateLastRecordedEndPC(codeStream.position); -// } else { -// // x | -// if ((bits & OnlyValueRequiredMASK) != 0) { -// left.generateCode(currentScope, codeStream, valueRequired); -// } else { -// left.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// valueRequired); -// } -// right.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// false); -// } -// return; -// } -// } -// // default case -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) { -// codeStream.ior(); -// if ((bits & OnlyValueRequiredMASK) == 0) { -// if (falseLabel == null) { -// if (trueLabel != null) { -// // implicit falling through the FALSE case -// codeStream.ifne(trueLabel); -// } -// } else { -// // implicit falling through the TRUE case -// if (trueLabel == null) { -// codeStream.ifeq(falseLabel); -// } else { -// // no implicit fall through TRUE/FALSE --> should never occur -// } -// } -// } -// } -// // reposition the endPC -// codeStream.updateLastRecordedEndPC(codeStream.position); -// } -// -// /** -// * Boolean generation for ^ -// */ -// public void generateOptimizedLogicalXor( -// BlockScope currentScope, -// CodeStream codeStream, -// Label trueLabel, -// Label falseLabel, -// boolean valueRequired) { -// -// Constant condConst; -// if ((left.implicitConversion & 0xF) == T_boolean) { -// if ((condConst = left.optimizedBooleanConstant()) != NotAConstant) { -// if (condConst.booleanValue() == true) { -// // ^ x -// left.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// false); -// right.generateOptimizedBoolean( -// currentScope, -// codeStream, -// falseLabel, -// trueLabel, -// valueRequired); -// } else { -// // ^ x -// left.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// false); -// if ((bits & OnlyValueRequiredMASK) != 0) { -// right.generateCode(currentScope, codeStream, valueRequired); -// } else { -// right.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// valueRequired); -// } -// } -// return; -// } -// if ((condConst = right.optimizedBooleanConstant()) != NotAConstant) { -// if (condConst.booleanValue() == true) { -// // x ^ -// left.generateOptimizedBoolean( -// currentScope, -// codeStream, -// falseLabel, -// trueLabel, -// valueRequired); -// right.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// false); -// } else { -// // x ^ -// if ((bits & OnlyValueRequiredMASK) != 0) { -// left.generateCode(currentScope, codeStream, valueRequired); -// } else { -// left.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// valueRequired); -// } -// right.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// false); -// } -// return; -// } -// } -// // default case -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) { -// codeStream.ixor(); -// if ((bits & OnlyValueRequiredMASK) == 0) { -// if (falseLabel == null) { -// if (trueLabel != null) { -// // implicit falling through the FALSE case -// codeStream.ifne(trueLabel); -// } -// } else { -// // implicit falling through the TRUE case -// if (trueLabel == null) { -// codeStream.ifeq(falseLabel); -// } else { -// // no implicit fall through TRUE/FALSE --> should never occur -// } -// } -// } -// } -// // reposition the endPC -// codeStream.updateLastRecordedEndPC(codeStream.position); -// } -// -// public void generateOptimizedStringBuffer( -// BlockScope blockScope, -// CodeStream codeStream, -// int typeID) { -// -// /* In the case trying to make a string concatenation, there is no need to create a new -// * string buffer, thus use a lower-level API for code generation involving only the -// * appending of arguments to the existing StringBuffer -// */ -// -// if ((((bits & OperatorMASK) >> OperatorSHIFT) == PLUS) -// && ((bits & ReturnTypeIDMASK) == T_String)) { -// if (constant != NotAConstant) { -// codeStream.generateConstant(constant, implicitConversion); -// codeStream.invokeStringBufferAppendForType(implicitConversion & 0xF); -// } else { -// int pc = codeStream.position; -// left.generateOptimizedStringBuffer( -// blockScope, -// codeStream, -// left.implicitConversion & 0xF); -// codeStream.recordPositionsFrom(pc, left.sourceStart); -// pc = codeStream.position; -// right.generateOptimizedStringBuffer( -// blockScope, -// codeStream, -// right.implicitConversion & 0xF); -// codeStream.recordPositionsFrom(pc, right.sourceStart); -// } -// } else { -// super.generateOptimizedStringBuffer(blockScope, codeStream, typeID); -// } -// } -// -// public void generateOptimizedStringBufferCreation( -// BlockScope blockScope, -// CodeStream codeStream, -// int typeID) { -// -// /* In the case trying to make a string concatenation, there is no need to create a new -// * string buffer, thus use a lower-level API for code generation involving only the -// * appending of arguments to the existing StringBuffer -// */ -// -// if ((((bits & OperatorMASK) >> OperatorSHIFT) == PLUS) -// && ((bits & ReturnTypeIDMASK) == T_String)) { -// if (constant != NotAConstant) { -// codeStream.newStringBuffer(); // new: java.lang.StringBuffer -// codeStream.dup(); -// codeStream.ldc(constant.stringValue()); -// codeStream.invokeStringBufferStringConstructor(); -// // invokespecial: java.lang.StringBuffer.(Ljava.lang.String;)V -// } else { -// int pc = codeStream.position; -// left.generateOptimizedStringBufferCreation( -// blockScope, -// codeStream, -// left.implicitConversion & 0xF); -// codeStream.recordPositionsFrom(pc, left.sourceStart); -// pc = codeStream.position; -// right.generateOptimizedStringBuffer( -// blockScope, -// codeStream, -// right.implicitConversion & 0xF); -// codeStream.recordPositionsFrom(pc, right.sourceStart); -// } -// } else { -// super.generateOptimizedStringBufferCreation(blockScope, codeStream, typeID); -// } -// } -// -// public boolean isCompactableOperation() { -// -// return true; -// } -// -// public void optimizedBooleanConstant(int leftId, int operator, int rightId) { -// -// switch (operator) { -// case AND : -// if ((leftId != T_boolean) || (rightId != T_boolean)) -// return; -// case AND_AND : -// Constant cst; -// if ((cst = left.optimizedBooleanConstant()) != NotAConstant) { -// if (cst.booleanValue() == false) { // left is equivalent to false -// optimizedBooleanConstant = cst; // constant(false) -// return; -// } else { //left is equivalent to true -// if ((cst = right.optimizedBooleanConstant()) != NotAConstant) { -// optimizedBooleanConstant = cst; -// // the conditional result is equivalent to the right conditional value -// } -// return; -// } -// } -// if ((cst = right.optimizedBooleanConstant()) != NotAConstant) { -// if (cst.booleanValue() == false) { // right is equivalent to false -// optimizedBooleanConstant = cst; // constant(false) -// } -// } -// return; -// case OR : -// if ((leftId != T_boolean) || (rightId != T_boolean)) -// return; -// case OR_OR : -// if ((cst = left.optimizedBooleanConstant()) != NotAConstant) { -// if (cst.booleanValue() == true) { // left is equivalent to true -// optimizedBooleanConstant = cst; // constant(true) -// return; -// } else { //left is equivalent to false -// if ((cst = right.optimizedBooleanConstant()) != NotAConstant) { -// optimizedBooleanConstant = cst; -// } -// return; -// } -// } -// if ((cst = right.optimizedBooleanConstant()) != NotAConstant) { -// if (cst.booleanValue() == true) { // right is equivalent to true -// optimizedBooleanConstant = cst; // constant(true) -// } -// } -// } -// } - public StringBuffer printExpressionNoParenthesis(int indent, StringBuffer output) { + // public void generateOptimizedGreaterThanOrEqual( + // BlockScope currentScope, + // CodeStream codeStream, + // Label trueLabel, + // Label falseLabel, + // boolean valueRequired) { + // + // int promotedTypeID = left.implicitConversion >> 4; + // // both sides got promoted in the same way + // if (promotedTypeID == T_int) { + // // 0 >= x + // if ((left.constant != NotAConstant) && (left.constant.intValue() == 0)) { + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) { + // if (falseLabel == null) { + // if (trueLabel != null) { + // // implicitly falling through the FALSE case + // codeStream.ifle(trueLabel); + // } + // } else { + // if (trueLabel == null) { + // // implicitly falling through the TRUE case + // codeStream.ifgt(falseLabel); + // } else { + // // no implicit fall through TRUE/FALSE --> should never occur + // } + // } + // } + // // reposition the endPC + // codeStream.updateLastRecordedEndPC(codeStream.position); + // return; + // } + // // x >= 0 + // if ((right.constant != NotAConstant) && (right.constant.intValue() == 0)) + // { + // left.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) { + // if (falseLabel == null) { + // if (trueLabel != null) { + // // implicitly falling through the FALSE case + // codeStream.ifge(trueLabel); + // } + // } else { + // if (trueLabel == null) { + // // implicitly falling through the TRUE case + // codeStream.iflt(falseLabel); + // } else { + // // no implicit fall through TRUE/FALSE --> should never occur + // } + // } + // } + // // reposition the endPC + // codeStream.updateLastRecordedEndPC(codeStream.position); + // return; + // } + // } + // // default comparison + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) { + // if (falseLabel == null) { + // if (trueLabel != null) { + // // implicit falling through the FALSE case + // switch (promotedTypeID) { + // case T_int : + // codeStream.if_icmpge(trueLabel); + // break; + // case T_float : + // codeStream.fcmpl(); + // codeStream.ifge(trueLabel); + // break; + // case T_long : + // codeStream.lcmp(); + // codeStream.ifge(trueLabel); + // break; + // case T_double : + // codeStream.dcmpl(); + // codeStream.ifge(trueLabel); + // } + // // reposition the endPC + // codeStream.updateLastRecordedEndPC(codeStream.position); + // return; + // } + // } else { + // if (trueLabel == null) { + // // implicit falling through the TRUE case + // switch (promotedTypeID) { + // case T_int : + // codeStream.if_icmplt(falseLabel); + // break; + // case T_float : + // codeStream.fcmpl(); + // codeStream.iflt(falseLabel); + // break; + // case T_long : + // codeStream.lcmp(); + // codeStream.iflt(falseLabel); + // break; + // case T_double : + // codeStream.dcmpl(); + // codeStream.iflt(falseLabel); + // } + // // reposition the endPC + // codeStream.updateLastRecordedEndPC(codeStream.position); + // return; + // } else { + // // no implicit fall through TRUE/FALSE --> should never occur + // } + // } + // } + // } + // + // /** + // * Boolean generation for < + // */ + // public void generateOptimizedLessThan( + // BlockScope currentScope, + // CodeStream codeStream, + // Label trueLabel, + // Label falseLabel, + // boolean valueRequired) { + // + // int promotedTypeID = left.implicitConversion >> 4; + // // both sides got promoted in the same way + // if (promotedTypeID == T_int) { + // // 0 < x + // if ((left.constant != NotAConstant) && (left.constant.intValue() == 0)) { + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) { + // if (falseLabel == null) { + // if (trueLabel != null) { + // // implicitly falling through the FALSE case + // codeStream.ifgt(trueLabel); + // } + // } else { + // if (trueLabel == null) { + // // implicitly falling through the TRUE case + // codeStream.ifle(falseLabel); + // } else { + // // no implicit fall through TRUE/FALSE --> should never occur + // } + // } + // } + // codeStream.updateLastRecordedEndPC(codeStream.position); + // return; + // } + // // x < 0 + // if ((right.constant != NotAConstant) && (right.constant.intValue() == 0)) + // { + // left.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) { + // if (falseLabel == null) { + // if (trueLabel != null) { + // // implicitly falling through the FALSE case + // codeStream.iflt(trueLabel); + // } + // } else { + // if (trueLabel == null) { + // // implicitly falling through the TRUE case + // codeStream.ifge(falseLabel); + // } else { + // // no implicit fall through TRUE/FALSE --> should never occur + // } + // } + // } + // codeStream.updateLastRecordedEndPC(codeStream.position); + // return; + // } + // } + // // default comparison + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) { + // if (falseLabel == null) { + // if (trueLabel != null) { + // // implicit falling through the FALSE case + // switch (promotedTypeID) { + // case T_int : + // codeStream.if_icmplt(trueLabel); + // break; + // case T_float : + // codeStream.fcmpg(); + // codeStream.iflt(trueLabel); + // break; + // case T_long : + // codeStream.lcmp(); + // codeStream.iflt(trueLabel); + // break; + // case T_double : + // codeStream.dcmpg(); + // codeStream.iflt(trueLabel); + // } + // codeStream.updateLastRecordedEndPC(codeStream.position); + // return; + // } + // } else { + // if (trueLabel == null) { + // // implicit falling through the TRUE case + // switch (promotedTypeID) { + // case T_int : + // codeStream.if_icmpge(falseLabel); + // break; + // case T_float : + // codeStream.fcmpg(); + // codeStream.ifge(falseLabel); + // break; + // case T_long : + // codeStream.lcmp(); + // codeStream.ifge(falseLabel); + // break; + // case T_double : + // codeStream.dcmpg(); + // codeStream.ifge(falseLabel); + // } + // codeStream.updateLastRecordedEndPC(codeStream.position); + // return; + // } else { + // // no implicit fall through TRUE/FALSE --> should never occur + // } + // } + // } + // } + // + // /** + // * Boolean generation for <= + // */ + // public void generateOptimizedLessThanOrEqual( + // BlockScope currentScope, + // CodeStream codeStream, + // Label trueLabel, + // Label falseLabel, + // boolean valueRequired) { + // + // int promotedTypeID = left.implicitConversion >> 4; + // // both sides got promoted in the same way + // if (promotedTypeID == T_int) { + // // 0 <= x + // if ((left.constant != NotAConstant) && (left.constant.intValue() == 0)) { + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) { + // if (falseLabel == null) { + // if (trueLabel != null) { + // // implicitly falling through the FALSE case + // codeStream.ifge(trueLabel); + // } + // } else { + // if (trueLabel == null) { + // // implicitly falling through the TRUE case + // codeStream.iflt(falseLabel); + // } else { + // // no implicit fall through TRUE/FALSE --> should never occur + // } + // } + // } + // // reposition the endPC + // codeStream.updateLastRecordedEndPC(codeStream.position); + // return; + // } + // // x <= 0 + // if ((right.constant != NotAConstant) && (right.constant.intValue() == 0)) + // { + // left.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) { + // if (falseLabel == null) { + // if (trueLabel != null) { + // // implicitly falling through the FALSE case + // codeStream.ifle(trueLabel); + // } + // } else { + // if (trueLabel == null) { + // // implicitly falling through the TRUE case + // codeStream.ifgt(falseLabel); + // } else { + // // no implicit fall through TRUE/FALSE --> should never occur + // } + // } + // } + // // reposition the endPC + // codeStream.updateLastRecordedEndPC(codeStream.position); + // return; + // } + // } + // // default comparison + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) { + // if (falseLabel == null) { + // if (trueLabel != null) { + // // implicit falling through the FALSE case + // switch (promotedTypeID) { + // case T_int : + // codeStream.if_icmple(trueLabel); + // break; + // case T_float : + // codeStream.fcmpg(); + // codeStream.ifle(trueLabel); + // break; + // case T_long : + // codeStream.lcmp(); + // codeStream.ifle(trueLabel); + // break; + // case T_double : + // codeStream.dcmpg(); + // codeStream.ifle(trueLabel); + // } + // // reposition the endPC + // codeStream.updateLastRecordedEndPC(codeStream.position); + // return; + // } + // } else { + // if (trueLabel == null) { + // // implicit falling through the TRUE case + // switch (promotedTypeID) { + // case T_int : + // codeStream.if_icmpgt(falseLabel); + // break; + // case T_float : + // codeStream.fcmpg(); + // codeStream.ifgt(falseLabel); + // break; + // case T_long : + // codeStream.lcmp(); + // codeStream.ifgt(falseLabel); + // break; + // case T_double : + // codeStream.dcmpg(); + // codeStream.ifgt(falseLabel); + // } + // // reposition the endPC + // codeStream.updateLastRecordedEndPC(codeStream.position); + // return; + // } else { + // // no implicit fall through TRUE/FALSE --> should never occur + // } + // } + // } + // } + // + // /** + // * Boolean generation for & + // */ + // public void generateOptimizedLogicalAnd( + // BlockScope currentScope, + // CodeStream codeStream, + // Label trueLabel, + // Label falseLabel, + // boolean valueRequired) { + // + // Constant condConst; + // if ((left.implicitConversion & 0xF) == T_boolean) { + // if ((condConst = left.optimizedBooleanConstant()) != NotAConstant) { + // if (condConst.booleanValue() == true) { + // // & x + // left.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // false); + // if ((bits & OnlyValueRequiredMASK) != 0) { + // right.generateCode(currentScope, codeStream, valueRequired); + // } else { + // right.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // valueRequired); + // } + // } else { + // // & x + // left.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // false); + // right.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // false); + // if (valueRequired) { + // if ((bits & OnlyValueRequiredMASK) != 0) { + // codeStream.iconst_0(); + // } else { + // if (falseLabel != null) { + // // implicit falling through the TRUE case + // codeStream.goto_(falseLabel); + // } + // } + // } + // // reposition the endPC + // codeStream.updateLastRecordedEndPC(codeStream.position); + // } + // return; + // } + // if ((condConst = right.optimizedBooleanConstant()) != NotAConstant) { + // if (condConst.booleanValue() == true) { + // // x & + // if ((bits & OnlyValueRequiredMASK) != 0) { + // left.generateCode(currentScope, codeStream, valueRequired); + // } else { + // left.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // valueRequired); + // } + // right.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // false); + // } else { + // // x & + // left.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // false); + // right.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // false); + // if (valueRequired) { + // if ((bits & OnlyValueRequiredMASK) != 0) { + // codeStream.iconst_0(); + // } else { + // if (falseLabel != null) { + // // implicit falling through the TRUE case + // codeStream.goto_(falseLabel); + // } + // } + // } + // // reposition the endPC + // codeStream.updateLastRecordedEndPC(codeStream.position); + // } + // return; + // } + // } + // // default case + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) { + // codeStream.iand(); + // if ((bits & OnlyValueRequiredMASK) == 0) { + // if (falseLabel == null) { + // if (trueLabel != null) { + // // implicit falling through the FALSE case + // codeStream.ifne(trueLabel); + // } + // } else { + // // implicit falling through the TRUE case + // if (trueLabel == null) { + // codeStream.ifeq(falseLabel); + // } else { + // // no implicit fall through TRUE/FALSE --> should never occur + // } + // } + // } + // } + // // reposition the endPC + // codeStream.updateLastRecordedEndPC(codeStream.position); + // } + // + // /** + // * Boolean generation for | + // */ + // public void generateOptimizedLogicalOr( + // BlockScope currentScope, + // CodeStream codeStream, + // Label trueLabel, + // Label falseLabel, + // boolean valueRequired) { + // + // Constant condConst; + // if ((left.implicitConversion & 0xF) == T_boolean) { + // if ((condConst = left.optimizedBooleanConstant()) != NotAConstant) { + // if (condConst.booleanValue() == true) { + // // | x + // left.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // false); + // right.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // false); + // if (valueRequired) { + // if ((bits & OnlyValueRequiredMASK) != 0) { + // codeStream.iconst_1(); + // } else { + // if (trueLabel != null) { + // codeStream.goto_(trueLabel); + // } + // } + // } + // // reposition the endPC + // codeStream.updateLastRecordedEndPC(codeStream.position); + // } else { + // // | x + // left.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // false); + // if ((bits & OnlyValueRequiredMASK) != 0) { + // right.generateCode(currentScope, codeStream, valueRequired); + // } else { + // right.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // valueRequired); + // } + // } + // return; + // } + // if ((condConst = right.optimizedBooleanConstant()) != NotAConstant) { + // if (condConst.booleanValue() == true) { + // // x | + // left.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // false); + // right.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // false); + // if (valueRequired) { + // if ((bits & OnlyValueRequiredMASK) != 0) { + // codeStream.iconst_1(); + // } else { + // if (trueLabel != null) { + // codeStream.goto_(trueLabel); + // } + // } + // } + // // reposition the endPC + // codeStream.updateLastRecordedEndPC(codeStream.position); + // } else { + // // x | + // if ((bits & OnlyValueRequiredMASK) != 0) { + // left.generateCode(currentScope, codeStream, valueRequired); + // } else { + // left.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // valueRequired); + // } + // right.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // false); + // } + // return; + // } + // } + // // default case + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) { + // codeStream.ior(); + // if ((bits & OnlyValueRequiredMASK) == 0) { + // if (falseLabel == null) { + // if (trueLabel != null) { + // // implicit falling through the FALSE case + // codeStream.ifne(trueLabel); + // } + // } else { + // // implicit falling through the TRUE case + // if (trueLabel == null) { + // codeStream.ifeq(falseLabel); + // } else { + // // no implicit fall through TRUE/FALSE --> should never occur + // } + // } + // } + // } + // // reposition the endPC + // codeStream.updateLastRecordedEndPC(codeStream.position); + // } + // + // /** + // * Boolean generation for ^ + // */ + // public void generateOptimizedLogicalXor( + // BlockScope currentScope, + // CodeStream codeStream, + // Label trueLabel, + // Label falseLabel, + // boolean valueRequired) { + // + // Constant condConst; + // if ((left.implicitConversion & 0xF) == T_boolean) { + // if ((condConst = left.optimizedBooleanConstant()) != NotAConstant) { + // if (condConst.booleanValue() == true) { + // // ^ x + // left.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // false); + // right.generateOptimizedBoolean( + // currentScope, + // codeStream, + // falseLabel, + // trueLabel, + // valueRequired); + // } else { + // // ^ x + // left.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // false); + // if ((bits & OnlyValueRequiredMASK) != 0) { + // right.generateCode(currentScope, codeStream, valueRequired); + // } else { + // right.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // valueRequired); + // } + // } + // return; + // } + // if ((condConst = right.optimizedBooleanConstant()) != NotAConstant) { + // if (condConst.booleanValue() == true) { + // // x ^ + // left.generateOptimizedBoolean( + // currentScope, + // codeStream, + // falseLabel, + // trueLabel, + // valueRequired); + // right.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // false); + // } else { + // // x ^ + // if ((bits & OnlyValueRequiredMASK) != 0) { + // left.generateCode(currentScope, codeStream, valueRequired); + // } else { + // left.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // valueRequired); + // } + // right.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // false); + // } + // return; + // } + // } + // // default case + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) { + // codeStream.ixor(); + // if ((bits & OnlyValueRequiredMASK) == 0) { + // if (falseLabel == null) { + // if (trueLabel != null) { + // // implicit falling through the FALSE case + // codeStream.ifne(trueLabel); + // } + // } else { + // // implicit falling through the TRUE case + // if (trueLabel == null) { + // codeStream.ifeq(falseLabel); + // } else { + // // no implicit fall through TRUE/FALSE --> should never occur + // } + // } + // } + // } + // // reposition the endPC + // codeStream.updateLastRecordedEndPC(codeStream.position); + // } + // + // public void generateOptimizedStringBuffer( + // BlockScope blockScope, + // CodeStream codeStream, + // int typeID) { + // + // /* In the case trying to make a string concatenation, there is no need to + // create a new + // * string buffer, thus use a lower-level API for code generation involving + // only the + // * appending of arguments to the existing StringBuffer + // */ + // + // if ((((bits & OperatorMASK) >> OperatorSHIFT) == PLUS) + // && ((bits & ReturnTypeIDMASK) == T_String)) { + // if (constant != NotAConstant) { + // codeStream.generateConstant(constant, implicitConversion); + // codeStream.invokeStringBufferAppendForType(implicitConversion & 0xF); + // } else { + // int pc = codeStream.position; + // left.generateOptimizedStringBuffer( + // blockScope, + // codeStream, + // left.implicitConversion & 0xF); + // codeStream.recordPositionsFrom(pc, left.sourceStart); + // pc = codeStream.position; + // right.generateOptimizedStringBuffer( + // blockScope, + // codeStream, + // right.implicitConversion & 0xF); + // codeStream.recordPositionsFrom(pc, right.sourceStart); + // } + // } else { + // super.generateOptimizedStringBuffer(blockScope, codeStream, typeID); + // } + // } + // + // public void generateOptimizedStringBufferCreation( + // BlockScope blockScope, + // CodeStream codeStream, + // int typeID) { + // + // /* In the case trying to make a string concatenation, there is no need to + // create a new + // * string buffer, thus use a lower-level API for code generation involving + // only the + // * appending of arguments to the existing StringBuffer + // */ + // + // if ((((bits & OperatorMASK) >> OperatorSHIFT) == PLUS) + // && ((bits & ReturnTypeIDMASK) == T_String)) { + // if (constant != NotAConstant) { + // codeStream.newStringBuffer(); // new: java.lang.StringBuffer + // codeStream.dup(); + // codeStream.ldc(constant.stringValue()); + // codeStream.invokeStringBufferStringConstructor(); + // // invokespecial: java.lang.StringBuffer.(Ljava.lang.String;)V + // } else { + // int pc = codeStream.position; + // left.generateOptimizedStringBufferCreation( + // blockScope, + // codeStream, + // left.implicitConversion & 0xF); + // codeStream.recordPositionsFrom(pc, left.sourceStart); + // pc = codeStream.position; + // right.generateOptimizedStringBuffer( + // blockScope, + // codeStream, + // right.implicitConversion & 0xF); + // codeStream.recordPositionsFrom(pc, right.sourceStart); + // } + // } else { + // super.generateOptimizedStringBufferCreation(blockScope, codeStream, + // typeID); + // } + // } + // + // public boolean isCompactableOperation() { + // + // return true; + // } + // + // public void optimizedBooleanConstant(int leftId, int operator, int + // rightId) { + // + // switch (operator) { + // case AND : + // if ((leftId != T_boolean) || (rightId != T_boolean)) + // return; + // case AND_AND : + // Constant cst; + // if ((cst = left.optimizedBooleanConstant()) != NotAConstant) { + // if (cst.booleanValue() == false) { // left is equivalent to false + // optimizedBooleanConstant = cst; // constant(false) + // return; + // } else { //left is equivalent to true + // if ((cst = right.optimizedBooleanConstant()) != NotAConstant) { + // optimizedBooleanConstant = cst; + // // the conditional result is equivalent to the right conditional value + // } + // return; + // } + // } + // if ((cst = right.optimizedBooleanConstant()) != NotAConstant) { + // if (cst.booleanValue() == false) { // right is equivalent to false + // optimizedBooleanConstant = cst; // constant(false) + // } + // } + // return; + // case OR : + // if ((leftId != T_boolean) || (rightId != T_boolean)) + // return; + // case OR_OR : + // if ((cst = left.optimizedBooleanConstant()) != NotAConstant) { + // if (cst.booleanValue() == true) { // left is equivalent to true + // optimizedBooleanConstant = cst; // constant(true) + // return; + // } else { //left is equivalent to false + // if ((cst = right.optimizedBooleanConstant()) != NotAConstant) { + // optimizedBooleanConstant = cst; + // } + // return; + // } + // } + // if ((cst = right.optimizedBooleanConstant()) != NotAConstant) { + // if (cst.booleanValue() == true) { // right is equivalent to true + // optimizedBooleanConstant = cst; // constant(true) + // } + // } + // } + // } + public StringBuffer printExpressionNoParenthesis(int indent, + StringBuffer output) { - left.printExpression(indent, output).append(' ').append(operatorToString()).append(' '); + left.printExpression(indent, output).append(' ').append( + operatorToString()).append(' '); return right.printExpression(0, output); } + public TypeBinding resolveType(BlockScope scope) { // use the id of the type to navigate into the table @@ -1659,8 +1669,8 @@ public class BinaryExpression extends OperatorExpression { } int leftId = leftTb.id; int rightId = rightTb.id; - if (leftId > 15 - || rightId > 15) { // must convert String + Object || Object + String + if (leftId > 15 || rightId > 15) { // must convert String + Object || + // Object + String if (leftId == T_String) { rightId = T_Object; } else if (rightId == T_String) { @@ -1673,78 +1683,81 @@ public class BinaryExpression extends OperatorExpression { } if (((bits & OperatorMASK) >> OperatorSHIFT) == PLUS) { if (leftId == T_String - && rightTb.isArrayType() - && ((ArrayBinding) rightTb).elementsType(scope) == CharBinding) - scope.problemReporter().signalNoImplicitStringConversionForCharArrayExpression( - right); - else if ( - rightId == T_String + && rightTb.isArrayType() + && ((ArrayBinding) rightTb).elementsType(scope) == CharBinding) + scope + .problemReporter() + .signalNoImplicitStringConversionForCharArrayExpression( + right); + else if (rightId == T_String && leftTb.isArrayType() && ((ArrayBinding) leftTb).elementsType(scope) == CharBinding) - scope.problemReporter().signalNoImplicitStringConversionForCharArrayExpression( - left); + scope + .problemReporter() + .signalNoImplicitStringConversionForCharArrayExpression( + left); } // the code is an int - // (cast) left Op (cast) rigth --> result - // 0000 0000 0000 0000 0000 - // <<16 <<12 <<8 <<4 <<0 + // (cast) left Op (cast) rigth --> result + // 0000 0000 0000 0000 0000 + // <<16 <<12 <<8 <<4 <<0 // Don't test for result = 0. If it is zero, some more work is done. - // On the one hand when it is not zero (correct code) we avoid doing the test - int result = - ResolveTypeTables[(bits & OperatorMASK) >> OperatorSHIFT][(leftId << 4) + // On the one hand when it is not zero (correct code) we avoid doing the + // test + int result = ResolveTypeTables[(bits & OperatorMASK) >> OperatorSHIFT][(leftId << 4) + rightId]; left.implicitConversion = result >>> 12; right.implicitConversion = (result >>> 4) & 0x000FF; bits |= result & 0xF; switch (result & 0xF) { // record the current ReturnTypeID - // only switch on possible result type..... - case T_boolean : - this.resolvedType = BooleanBinding; - break; - case T_byte : - this.resolvedType = ByteBinding; - break; - case T_char : - this.resolvedType = CharBinding; - break; - case T_double : - this.resolvedType = DoubleBinding; - break; - case T_float : - this.resolvedType = FloatBinding; - break; - case T_int : - this.resolvedType = IntBinding; - break; - case T_long : - this.resolvedType = LongBinding; - break; - case T_String : - this.resolvedType = scope.getJavaLangString(); - break; - default : //error........ - constant = Constant.NotAConstant; - scope.problemReporter().invalidOperator(this, leftTb, rightTb); - return null; + // only switch on possible result type..... + case T_boolean: + this.resolvedType = BooleanBinding; + break; + case T_byte: + this.resolvedType = ByteBinding; + break; + case T_char: + this.resolvedType = CharBinding; + break; + case T_double: + this.resolvedType = DoubleBinding; + break; + case T_float: + this.resolvedType = FloatBinding; + break; + case T_int: + this.resolvedType = IntBinding; + break; + case T_long: + this.resolvedType = LongBinding; + break; + case T_String: + this.resolvedType = scope.getJavaLangString(); + break; + default: // error........ + constant = Constant.NotAConstant; + scope.problemReporter().invalidOperator(this, leftTb, rightTb); + return null; } // compute the constant when valid computeConstant(scope, leftId, rightId); return this.resolvedType; } - + public String toStringExpressionNoParenthesis() { return left.toStringExpression() + " " + //$NON-NLS-1$ - operatorToString() + " " + //$NON-NLS-1$ - right.toStringExpression(); + operatorToString() + " " + //$NON-NLS-1$ + right.toStringExpression(); } public void traverse(ASTVisitor visitor, BlockScope scope) { - + if (visitor.visit(this, scope)) { left.traverse(visitor, scope); right.traverse(visitor, scope); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Block.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Block.java index 30a2c2b..df31b10 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Block.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Block.java @@ -17,28 +17,31 @@ import net.sourceforge.phpdt.internal.compiler.flow.FlowInfo; import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; public class Block extends Statement { - + public Statement[] statements; + public int explicitDeclarations; + // the number of explicit declaration , used to create scope public BlockScope scope; + public static final Block None = new Block(0); - + public Block(int explicitDeclarations) { this.explicitDeclarations = explicitDeclarations; } - - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { + + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { // empty block - if (statements == null) return flowInfo; + if (statements == null) + return flowInfo; boolean didAlreadyComplain = false; for (int i = 0, max = statements.length; i < max; i++) { Statement stat; - if (!flowInfo.complainIfUnreachable(stat = statements[i], scope, didAlreadyComplain)) { + if (!flowInfo.complainIfUnreachable(stat = statements[i], scope, + didAlreadyComplain)) { flowInfo = stat.analyseCode(scope, flowContext, flowInfo); } else { didAlreadyComplain = true; @@ -49,7 +52,7 @@ public class Block extends Statement { public static final Block EmptyWith(int sourceStart, int sourceEnd) { - //return an empty block which position is s and e + // return an empty block which position is s and e Block bk = new Block(0); bk.sourceStart = sourceStart; bk.sourceEnd = sourceEnd; @@ -59,33 +62,35 @@ public class Block extends Statement { /** * Code generation for a block */ -// public void generateCode(BlockScope currentScope, CodeStream codeStream) { -// -// if ((bits & IsReachableMASK) == 0) { -// return; -// } -// int pc = codeStream.position; -// if (statements != null) { -// for (int i = 0, max = statements.length; i < max; i++) { -// statements[i].generateCode(scope, codeStream); -// } -// } // for local variable debug attributes -// if (scope != currentScope) { // was really associated with its own scope -// codeStream.exitUserScope(scope); -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } - + // public void generateCode(BlockScope currentScope, CodeStream codeStream) + // { + // + // if ((bits & IsReachableMASK) == 0) { + // return; + // } + // int pc = codeStream.position; + // if (statements != null) { + // for (int i = 0, max = statements.length; i < max; i++) { + // statements[i].generateCode(scope, codeStream); + // } + // } // for local variable debug attributes + // if (scope != currentScope) { // was really associated with its own scope + // codeStream.exitUserScope(scope); + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } public boolean isEmptyBlock() { return statements == null; } + public StringBuffer printBody(int indent, StringBuffer output) { - if (this.statements == null) return output; + if (this.statements == null) + return output; for (int i = 0; i < statements.length; i++) { statements[i].printStatement(indent + 1, output); - output.append('\n'); + output.append('\n'); } return output; } @@ -97,13 +102,12 @@ public class Block extends Statement { printBody(indent, output); return printIndent(indent, output).append('}'); } + public void resolve(BlockScope upperScope) { if (statements != null) { - scope = - explicitDeclarations == 0 - ? upperScope - : new BlockScope(upperScope, explicitDeclarations); + scope = explicitDeclarations == 0 ? upperScope : new BlockScope( + upperScope, explicitDeclarations); int i = 0, length = statements.length; while (i < length) statements[i++].resolve(scope); @@ -149,13 +153,12 @@ public class Block extends Statement { } else { buffer.append(";\n"); //$NON-NLS-1$ } - }; + } + ; return buffer.toString(); } - public void traverse( - ASTVisitor visitor, - BlockScope blockScope) { + public void traverse(ASTVisitor visitor, BlockScope blockScope) { if (visitor.visit(this, blockScope)) { if (statements != null) { @@ -166,14 +169,14 @@ public class Block extends Statement { } visitor.endVisit(this, blockScope); } - + /** * Dispatch the call on its last statement. */ public void branchChainTo(Label label) { - if (this.statements != null) { - this.statements[statements.length - 1].branchChainTo(label); - } + if (this.statements != null) { + this.statements[statements.length - 1].branchChainTo(label); + } } - + } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/BranchStatement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/BranchStatement.java index 245a491..4b17645 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/BranchStatement.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/BranchStatement.java @@ -14,59 +14,64 @@ import net.sourceforge.phpdt.internal.compiler.codegen.Label; import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; public abstract class BranchStatement extends Statement { - public Expression expression; + public Expression expression; + public Label targetLabel; + public ASTNode[] subroutines; -/** - * BranchStatement constructor comment. - */ -public BranchStatement(Expression expr, int s,int e) { - expression = expr ; - sourceStart = s; - sourceEnd = e; -} -/** - * Branch code generation - * - * generate the finallyInvocationSequence. - */ -//public void generateCode(BlockScope currentScope, CodeStream codeStream) { -// -// if ((bits & IsReachableMASK) == 0) { -// return; -// } -// int pc = codeStream.position; -// -// // generation of code responsible for invoking the finally -// // blocks in sequence -// if (subroutines != null){ -// for (int i = 0, max = subroutines.length; i < max; i++){ -// ASTNode sub; -// if ((sub = subroutines[i]) instanceof SynchronizedStatement){ -// codeStream.load(((SynchronizedStatement)sub).synchroVariable); -// codeStream.monitorexit(); -// } else { -// TryStatement trySub = (TryStatement) sub; -// if (trySub.subRoutineCannotReturn) { -// codeStream.goto_(trySub.subRoutineStartLabel); -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// return; -// } else { -// codeStream.jsr(trySub.subRoutineStartLabel); -// } -// } -// } -// } -// codeStream.goto_(targetLabel); -// codeStream.recordPositionsFrom(pc, this.sourceStart); -//} -public void resetStateForCodeGeneration() { - if (this.targetLabel != null) { - this.targetLabel.resetStateForCodeGeneration(); + + /** + * BranchStatement constructor comment. + */ + public BranchStatement(Expression expr, int s, int e) { + expression = expr; + sourceStart = s; + sourceEnd = e; } -} -public void resolve(BlockScope scope) { -} + /** + * Branch code generation + * + * generate the finallyInvocationSequence. + */ + // public void generateCode(BlockScope currentScope, CodeStream codeStream) + // { + // + // if ((bits & IsReachableMASK) == 0) { + // return; + // } + // int pc = codeStream.position; + // + // // generation of code responsible for invoking the finally + // // blocks in sequence + // if (subroutines != null){ + // for (int i = 0, max = subroutines.length; i < max; i++){ + // ASTNode sub; + // if ((sub = subroutines[i]) instanceof SynchronizedStatement){ + // codeStream.load(((SynchronizedStatement)sub).synchroVariable); + // codeStream.monitorexit(); + // } else { + // TryStatement trySub = (TryStatement) sub; + // if (trySub.subRoutineCannotReturn) { + // codeStream.goto_(trySub.subRoutineStartLabel); + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // return; + // } else { + // codeStream.jsr(trySub.subRoutineStartLabel); + // } + // } + // } + // } + // codeStream.goto_(targetLabel); + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } + public void resetStateForCodeGeneration() { + if (this.targetLabel != null) { + this.targetLabel.resetStateForCodeGeneration(); + } + } + + public void resolve(BlockScope scope) { + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/BreakStatement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/BreakStatement.java index a033e1e..0acbc7d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/BreakStatement.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/BreakStatement.java @@ -16,69 +16,74 @@ import net.sourceforge.phpdt.internal.compiler.flow.FlowInfo; import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; public class BreakStatement extends BranchStatement { - + public BreakStatement(Expression expr, int sourceStart, int e) { super(expr, sourceStart, e); } - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { - // here requires to generate a sequence of finally blocks invocations depending corresponding - // to each of the traversed try statements, so that execution will terminate properly. + // here requires to generate a sequence of finally blocks invocations + // depending corresponding + // to each of the traversed try statements, so that execution will + // terminate properly. // lookup the label, this should answer the returnContext -// FlowContext targetContext = (label == null) -// ? flowContext.getTargetContextForDefaultBreak() -// : flowContext.getTargetContextForBreakLabel(label); -// -// if (targetContext == null) { -// if (label == null) { -// currentScope.problemReporter().invalidBreak(this); -// } else { -// currentScope.problemReporter().undefinedLabel(this); -// } -// return flowInfo; // pretend it did not break since no actual target -// } -// -// targetLabel = targetContext.breakLabel(); -// FlowContext traversedContext = flowContext; -// int subIndex = 0, maxSub = 5; -// subroutines = new ASTNode[maxSub]; -// -// do { -// ASTNode sub; -// if ((sub = traversedContext.subRoutine()) != null) { -// if (subIndex == maxSub) { -// System.arraycopy(subroutines, 0, (subroutines = new ASTNode[maxSub*=2]), 0, subIndex); // grow -// } -// subroutines[subIndex++] = sub; -// if (sub.cannotReturn()) { -// break; -// } -// } -// traversedContext.recordReturnFrom(flowInfo.unconditionalInits()); -// -// ASTNode node; -// if ((node = traversedContext.associatedNode) instanceof TryStatement) { -// TryStatement tryStatement = (TryStatement) node; -// flowInfo.addInitializationsFrom(tryStatement.subRoutineInits); // collect inits -// } else if (traversedContext == targetContext) { -// // only record break info once accumulated through subroutines, and only against target context -// targetContext.recordBreakFrom(flowInfo); -// break; -// } -// } while ((traversedContext = traversedContext.parent) != null); -// -// // resize subroutines -// if (subIndex != maxSub) { -// System.arraycopy(subroutines, 0, (subroutines = new ASTNode[subIndex]), 0, subIndex); -// } + // FlowContext targetContext = (label == null) + // ? flowContext.getTargetContextForDefaultBreak() + // : flowContext.getTargetContextForBreakLabel(label); + // + // if (targetContext == null) { + // if (label == null) { + // currentScope.problemReporter().invalidBreak(this); + // } else { + // currentScope.problemReporter().undefinedLabel(this); + // } + // return flowInfo; // pretend it did not break since no actual target + // } + // + // targetLabel = targetContext.breakLabel(); + // FlowContext traversedContext = flowContext; + // int subIndex = 0, maxSub = 5; + // subroutines = new ASTNode[maxSub]; + // + // do { + // ASTNode sub; + // if ((sub = traversedContext.subRoutine()) != null) { + // if (subIndex == maxSub) { + // System.arraycopy(subroutines, 0, (subroutines = new + // ASTNode[maxSub*=2]), 0, subIndex); // grow + // } + // subroutines[subIndex++] = sub; + // if (sub.cannotReturn()) { + // break; + // } + // } + // traversedContext.recordReturnFrom(flowInfo.unconditionalInits()); + // + // ASTNode node; + // if ((node = traversedContext.associatedNode) instanceof TryStatement) + // { + // TryStatement tryStatement = (TryStatement) node; + // flowInfo.addInitializationsFrom(tryStatement.subRoutineInits); // + // collect inits + // } else if (traversedContext == targetContext) { + // // only record break info once accumulated through subroutines, and + // only against target context + // targetContext.recordBreakFrom(flowInfo); + // break; + // } + // } while ((traversedContext = traversedContext.parent) != null); + // + // // resize subroutines + // if (subIndex != maxSub) { + // System.arraycopy(subroutines, 0, (subroutines = new + // ASTNode[subIndex]), 0, subIndex); + // } return FlowInfo.DEAD_END; } - + public String toString(int tab) { String s = tabString(tab); @@ -87,15 +92,17 @@ public class BreakStatement extends BranchStatement { s += expression.toString(); return s; } + public StringBuffer printStatement(int tab, StringBuffer output) { printIndent(tab, output).append("break "); //$NON-NLS-1$ - if (expression != null) output.append(expression); + if (expression != null) + output.append(expression); return output.append(';'); } - public void traverse( - IAbstractSyntaxTreeVisitor visitor, - BlockScope blockscope) { + + public void traverse(IAbstractSyntaxTreeVisitor visitor, + BlockScope blockscope) { visitor.visit(this, blockscope); visitor.endVisit(this, blockscope); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/CaseStatement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/CaseStatement.java index 976bc66..c0fef15 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/CaseStatement.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/CaseStatement.java @@ -18,42 +18,44 @@ import net.sourceforge.phpdt.internal.compiler.impl.Constant; import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; - public class CaseStatement extends Statement { - + public Expression constantExpression; + public CaseLabel targetLabel; + public CaseStatement(int sourceStart, Expression constantExpression) { this.constantExpression = constantExpression; this.sourceEnd = constantExpression.sourceEnd; this.sourceStart = sourceStart; } - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { if (constantExpression.constant == NotAConstant) - currentScope.problemReporter().caseExpressionMustBeConstant(constantExpression); + currentScope.problemReporter().caseExpressionMustBeConstant( + constantExpression); - this.constantExpression.analyseCode(currentScope, flowContext, flowInfo); + this.constantExpression + .analyseCode(currentScope, flowContext, flowInfo); return flowInfo; } /** * Case code generation - * + * */ -// public void generateCode(BlockScope currentScope, CodeStream codeStream) { -// -// if ((bits & IsReachableMASK) == 0) { -// return; -// } -// int pc = codeStream.position; -// targetLabel.place(); -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } + // public void generateCode(BlockScope currentScope, CodeStream codeStream) + // { + // + // if ((bits & IsReachableMASK) == 0) { + // return; + // } + // int pc = codeStream.position; + // targetLabel.place(); + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } public StringBuffer printStatement(int tab, StringBuffer output) { printIndent(tab, output); @@ -65,30 +67,28 @@ public class CaseStatement extends Statement { } return output.append(';'); } + /** * No-op : should use resolveCase(...) instead. */ public void resolve(BlockScope scope) { } - public Constant resolveCase( - BlockScope scope, - TypeBinding switchType, - SwitchStatement switchStatement) { + public Constant resolveCase(BlockScope scope, TypeBinding switchType, + SwitchStatement switchStatement) { // add into the collection of cases of the associated switch statement switchStatement.cases[switchStatement.caseCount++] = this; TypeBinding caseType = constantExpression.resolveType(scope); if (caseType == null || switchType == null) return null; - if (constantExpression.isConstantValueOfTypeAssignableToType(caseType, switchType)) + if (constantExpression.isConstantValueOfTypeAssignableToType(caseType, + switchType)) return constantExpression.constant; if (caseType.isCompatibleWith(switchType)) return constantExpression.constant; scope.problemReporter().typeMismatchErrorActualTypeExpectedType( - constantExpression, - caseType, - switchType); + constantExpression, caseType, switchType); return null; } @@ -99,9 +99,7 @@ public class CaseStatement extends Statement { return s; } - public void traverse( - ASTVisitor visitor, - BlockScope blockScope) { + public void traverse(ASTVisitor visitor, BlockScope blockScope) { if (visitor.visit(this, blockScope)) { constantExpression.traverse(visitor, blockScope); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/CastExpression.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/CastExpression.java index 950716d..ad9c88a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/CastExpression.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/CastExpression.java @@ -25,44 +25,43 @@ import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class CastExpression extends Expression { public Expression expression; + public Expression type; + public boolean needRuntimeCheckcast; - //expression.implicitConversion holds the cast for baseType casting + // expression.implicitConversion holds the cast for baseType casting public CastExpression(Expression e, Expression t) { expression = e; type = t; - //due to the fact an expression may start with ( and that a cast also start with ( - //the field is an expression....it can be a TypeReference OR a NameReference Or - //an expression <--this last one is invalid....... + // due to the fact an expression may start with ( and that a cast also + // start with ( + // the field is an expression....it can be a TypeReference OR a + // NameReference Or + // an expression <--this last one is invalid....... // :-( ............. - //if (type instanceof TypeReference ) - // flag = IsTypeReference ; - //else - // if (type instanceof NameReference) - // flag = IsNameReference ; - // else - // flag = IsExpression ; + // if (type instanceof TypeReference ) + // flag = IsTypeReference ; + // else + // if (type instanceof NameReference) + // flag = IsNameReference ; + // else + // flag = IsExpression ; } - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { - return expression - .analyseCode(currentScope, flowContext, flowInfo) - .unconditionalInits(); + return expression.analyseCode(currentScope, flowContext, flowInfo) + .unconditionalInits(); } - public final void areTypesCastCompatible( - BlockScope scope, - TypeBinding castType, - TypeBinding expressionType) { + public final void areTypesCastCompatible(BlockScope scope, + TypeBinding castType, TypeBinding expressionType) { // see specifications 5.5 // handle errors and process constant when needed @@ -72,141 +71,174 @@ public class CastExpression extends Expression { // we then do not report an obvious-cascade-error. needRuntimeCheckcast = false; - if (castType == null || expressionType == null) return; + if (castType == null || expressionType == null) + return; // identity conversion cannot be performed upfront, due to side-effects // like constant propagation - + if (castType.isBaseType()) { if (expressionType.isBaseType()) { if (expressionType == castType) { expression.implicitWidening(castType, expressionType); - constant = expression.constant; //use the same constant + constant = expression.constant; // use the same constant return; } if (expressionType.isCompatibleWith(castType) - || BaseTypeBinding.isNarrowing(castType.id, expressionType.id)) { - expression.implicitConversion = (castType.id << 4) + expressionType.id; + || BaseTypeBinding.isNarrowing(castType.id, + expressionType.id)) { + expression.implicitConversion = (castType.id << 4) + + expressionType.id; if (expression.constant != Constant.NotAConstant) - constant = expression.constant.castTo(expression.implicitConversion); + constant = expression.constant + .castTo(expression.implicitConversion); return; } } - scope.problemReporter().typeCastError(this, castType, expressionType); + scope.problemReporter().typeCastError(this, castType, + expressionType); return; } - //-----------cast to something which is NOT a base type-------------------------- + // -----------cast to something which is NOT a base + // type-------------------------- if (expressionType == NullBinding) { - // if (castType.isArrayType()){ // 26903 - need checkcast when casting null to array type - // needRuntimeCheckcast = true; - // } - return; //null is compatible with every thing + // if (castType.isArrayType()){ // 26903 - need checkcast when + // casting null to array type + // needRuntimeCheckcast = true; + // } + return; // null is compatible with every thing } if (expressionType.isBaseType()) { - scope.problemReporter().typeCastError(this, castType, expressionType); + scope.problemReporter().typeCastError(this, castType, + expressionType); return; } if (expressionType.isArrayType()) { - if (castType == expressionType) return; // identity conversion + if (castType == expressionType) + return; // identity conversion if (castType.isArrayType()) { - //------- (castType.isArray) expressionType.isArray ----------- - TypeBinding exprElementType = ((ArrayBinding) expressionType).elementsType(scope); + // ------- (castType.isArray) expressionType.isArray ----------- + TypeBinding exprElementType = ((ArrayBinding) expressionType) + .elementsType(scope); if (exprElementType.isBaseType()) { - // <---stop the recursion------- + // <---stop the recursion------- if (((ArrayBinding) castType).elementsType(scope) == exprElementType) needRuntimeCheckcast = true; else - scope.problemReporter().typeCastError(this, castType, expressionType); + scope.problemReporter().typeCastError(this, castType, + expressionType); return; } // recursively on the elements... - areTypesCastCompatible( - scope, - ((ArrayBinding) castType).elementsType(scope), - exprElementType); + areTypesCastCompatible(scope, ((ArrayBinding) castType) + .elementsType(scope), exprElementType); return; - } else if ( - castType.isClass()) { - //------(castType.isClass) expressionType.isArray --------------- + } else if (castType.isClass()) { + // ------(castType.isClass) expressionType.isArray + // --------------- if (scope.isJavaLangObject(castType)) return; - } else { //------- (castType.isInterface) expressionType.isArray ----------- - if (scope.isJavaLangCloneable(castType) || scope.isJavaIoSerializable(castType)) { + } else { // ------- (castType.isInterface) expressionType.isArray + // ----------- + if (scope.isJavaLangCloneable(castType) + || scope.isJavaIoSerializable(castType)) { needRuntimeCheckcast = true; return; } } - scope.problemReporter().typeCastError(this, castType, expressionType); + scope.problemReporter().typeCastError(this, castType, + expressionType); return; } if (expressionType.isClass()) { if (castType.isArrayType()) { // ---- (castType.isArray) expressionType.isClass ------- - if (scope.isJavaLangObject(expressionType)) { // potential runtime error + if (scope.isJavaLangObject(expressionType)) { // potential + // runtime error needRuntimeCheckcast = true; return; } - } else if (castType.isClass()) { // ----- (castType.isClass) expressionType.isClass ------ - if (expressionType.isCompatibleWith(castType)){ // no runtime error - if (castType.id == T_String) constant = expression.constant; // (String) cst is still a constant + } else if (castType.isClass()) { // ----- (castType.isClass) + // expressionType.isClass ------ + if (expressionType.isCompatibleWith(castType)) { // no + // runtime + // error + if (castType.id == T_String) + constant = expression.constant; // (String) cst is still + // a constant return; } if (castType.isCompatibleWith(expressionType)) { - // potential runtime error + // potential runtime error needRuntimeCheckcast = true; return; } - } else { // ----- (castType.isInterface) expressionType.isClass ------- + } else { // ----- (castType.isInterface) expressionType.isClass + // ------- if (((ReferenceBinding) expressionType).isFinal()) { - // no subclass for expressionType, thus compile-time check is valid - if (expressionType.isCompatibleWith(castType)) + // no subclass for expressionType, thus compile-time check + // is valid + if (expressionType.isCompatibleWith(castType)) return; - } else { // a subclass may implement the interface ==> no check at compile time + } else { // a subclass may implement the interface ==> no + // check at compile time needRuntimeCheckcast = true; return; } } - scope.problemReporter().typeCastError(this, castType, expressionType); + scope.problemReporter().typeCastError(this, castType, + expressionType); return; } - // if (expressionType.isInterface()) { cannot be anything else + // if (expressionType.isInterface()) { cannot be anything else if (castType.isArrayType()) { // ----- (castType.isArray) expressionType.isInterface ------ if (scope.isJavaLangCloneable(expressionType) - || scope.isJavaIoSerializable(expressionType)) // potential runtime error + || scope.isJavaIoSerializable(expressionType)) // potential + // runtime + // error needRuntimeCheckcast = true; else - scope.problemReporter().typeCastError(this, castType, expressionType); + scope.problemReporter().typeCastError(this, castType, + expressionType); return; - } else if (castType.isClass()) { // ----- (castType.isClass) expressionType.isInterface -------- + } else if (castType.isClass()) { // ----- (castType.isClass) + // expressionType.isInterface + // -------- if (scope.isJavaLangObject(castType)) // no runtime error return; if (((ReferenceBinding) castType).isFinal()) { // no subclass for castType, thus compile-time check is valid if (!castType.isCompatibleWith(expressionType)) { // potential runtime error - scope.problemReporter().typeCastError(this, castType, expressionType); + scope.problemReporter().typeCastError(this, castType, + expressionType); return; } } - } else { // ----- (castType.isInterface) expressionType.isInterface ------- - if (castType == expressionType) return; // identity conversion + } else { // ----- (castType.isInterface) expressionType.isInterface + // ------- + if (castType == expressionType) + return; // identity conversion if (Scope.compareTypes(castType, expressionType) == NotRelated) { - MethodBinding[] castTypeMethods = ((ReferenceBinding) castType).methods(); - MethodBinding[] expressionTypeMethods = - ((ReferenceBinding) expressionType).methods(); + MethodBinding[] castTypeMethods = ((ReferenceBinding) castType) + .methods(); + MethodBinding[] expressionTypeMethods = ((ReferenceBinding) expressionType) + .methods(); int exprMethodsLength = expressionTypeMethods.length; for (int i = 0, castMethodsLength = castTypeMethods.length; i < castMethodsLength; i++) for (int j = 0; j < exprMethodsLength; j++) { if ((castTypeMethods[i].returnType != expressionTypeMethods[j].returnType) && (castTypeMethods[i].selector == expressionTypeMethods[j].selector) - && castTypeMethods[i].areParametersEqual(expressionTypeMethods[j])) { - scope.problemReporter().typeCastError(this, castType, expressionType); + && castTypeMethods[i] + .areParametersEqual(expressionTypeMethods[j])) { + scope.problemReporter().typeCastError(this, + castType, expressionType); } } } @@ -217,52 +249,56 @@ public class CastExpression extends Expression { /** * Cast expression code generation - * - * @param currentScope net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream - * @param valueRequired boolean + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * @param valueRequired + * boolean */ -// public void generateCode( -// BlockScope currentScope, -// CodeStream codeStream, -// boolean valueRequired) { -// -// int pc = codeStream.position; -// if (constant != NotAConstant) { -// if (valueRequired -// || needRuntimeCheckcast) { // Added for: 1F1W9IG: IVJCOM:WINNT - Compiler omits casting check -// codeStream.generateConstant(constant, implicitConversion); -// if (needRuntimeCheckcast) { -// codeStream.checkcast(this.resolvedType); -// if (!valueRequired) -// codeStream.pop(); -// } -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// return; -// } -// expression.generateCode( -// currentScope, -// codeStream, -// valueRequired || needRuntimeCheckcast); -// if (needRuntimeCheckcast) { -// codeStream.checkcast(this.resolvedType); -// if (!valueRequired) -// codeStream.pop(); -// } else { -// if (valueRequired) -// codeStream.generateImplicitConversion(implicitConversion); -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } - - public Expression innermostCastedExpression(){ + // public void generateCode( + // BlockScope currentScope, + // CodeStream codeStream, + // boolean valueRequired) { + // + // int pc = codeStream.position; + // if (constant != NotAConstant) { + // if (valueRequired + // || needRuntimeCheckcast) { // Added for: 1F1W9IG: IVJCOM:WINNT - Compiler + // omits casting check + // codeStream.generateConstant(constant, implicitConversion); + // if (needRuntimeCheckcast) { + // codeStream.checkcast(this.resolvedType); + // if (!valueRequired) + // codeStream.pop(); + // } + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // return; + // } + // expression.generateCode( + // currentScope, + // codeStream, + // valueRequired || needRuntimeCheckcast); + // if (needRuntimeCheckcast) { + // codeStream.checkcast(this.resolvedType); + // if (!valueRequired) + // codeStream.pop(); + // } else { + // if (valueRequired) + // codeStream.generateImplicitConversion(implicitConversion); + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } + public Expression innermostCastedExpression() { Expression current = this.expression; while (current instanceof CastExpression) { current = ((CastExpression) current).expression; } return current; } + public StringBuffer printExpression(int indent, StringBuffer output) { output.append('('); @@ -273,8 +309,10 @@ public class CastExpression extends Expression { public TypeBinding resolveType(BlockScope scope) { // compute a new constant if the cast is effective - // due to the fact an expression may start with ( and that a cast can also start with ( - // the field is an expression....it can be a TypeReference OR a NameReference Or + // due to the fact an expression may start with ( and that a cast can + // also start with ( + // the field is an expression....it can be a TypeReference OR a + // NameReference Or // any kind of Expression <-- this last one is invalid....... constant = Constant.NotAConstant; @@ -283,12 +321,14 @@ public class CastExpression extends Expression { this.resolvedType = type.resolveType(scope); TypeBinding castedExpressionType = expression.resolveType(scope); if (this.resolvedType != null && castedExpressionType != null) { - areTypesCastCompatible(scope, this.resolvedType, castedExpressionType); + areTypesCastCompatible(scope, this.resolvedType, + castedExpressionType); } return this.resolvedType; } else { // expression as a cast !!!!!!!! TypeBinding castedExpressionType = expression.resolveType(scope); - if (castedExpressionType == null) return null; + if (castedExpressionType == null) + return null; scope.problemReporter().invalidTypeReference(type); return null; } @@ -297,12 +337,10 @@ public class CastExpression extends Expression { public String toStringExpression() { return "(" + type.toString(0) + ") " + //$NON-NLS-2$ //$NON-NLS-1$ - expression.toStringExpression(); + expression.toStringExpression(); } - public void traverse( - ASTVisitor visitor, - BlockScope blockScope) { + public void traverse(ASTVisitor visitor, BlockScope blockScope) { if (visitor.visit(this, blockScope)) { type.traverse(visitor, blockScope); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Clinit.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Clinit.java index bbd37e2..d04f112 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Clinit.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Clinit.java @@ -23,10 +23,11 @@ import net.sourceforge.phpdt.internal.compiler.parser.UnitParser; import net.sourceforge.phpdt.internal.compiler.problem.AbortMethod; public class Clinit extends AbstractMethodDeclaration { - + public final static char[] ConstantPoolName = "".toCharArray(); //$NON-NLS-1$ private FieldBinding assertionSyntheticFieldBinding = null; + private FieldBinding classLiteralSyntheticField = null; public Clinit(CompilationResult compilationResult) { @@ -35,44 +36,37 @@ public class Clinit extends AbstractMethodDeclaration { selector = ConstantPoolName; } - public void analyseCode( - ClassScope classScope, - InitializationFlowContext staticInitializerFlowContext, - FlowInfo flowInfo) { + public void analyseCode(ClassScope classScope, + InitializationFlowContext staticInitializerFlowContext, + FlowInfo flowInfo) { if (ignoreFurtherInvestigation) return; try { - ExceptionHandlingFlowContext clinitContext = - new ExceptionHandlingFlowContext( - staticInitializerFlowContext.parent, - this, - NoExceptions, - scope, - FlowInfo.DEAD_END); + ExceptionHandlingFlowContext clinitContext = new ExceptionHandlingFlowContext( + staticInitializerFlowContext.parent, this, NoExceptions, + scope, FlowInfo.DEAD_END); // check for missing returning path this.needFreeReturn = flowInfo.isReachable(); // check missing blank final field initializations - flowInfo = flowInfo.mergedWith(staticInitializerFlowContext.initsOnReturn); + flowInfo = flowInfo + .mergedWith(staticInitializerFlowContext.initsOnReturn); FieldBinding[] fields = scope.enclosingSourceType().fields(); for (int i = 0, count = fields.length; i < count; i++) { FieldBinding field; - if ((field = fields[i]).isStatic() - && field.isFinal() - && (!flowInfo.isDefinitelyAssigned(fields[i]))) { - scope.problemReporter().uninitializedBlankFinalField( - field, - scope.referenceType().declarationOf(field)); - // can complain against the field decl, since only one + if ((field = fields[i]).isStatic() && field.isFinal() + && (!flowInfo.isDefinitelyAssigned(fields[i]))) { + scope.problemReporter().uninitializedBlankFinalField(field, + scope.referenceType().declarationOf(field)); + // can complain against the field decl, since only one + // } } // check static initializers thrown exceptions - staticInitializerFlowContext.checkInitializerExceptions( - scope, - clinitContext, - flowInfo); + staticInitializerFlowContext.checkInitializerExceptions(scope, + clinitContext, flowInfo); } catch (AbortMethod e) { this.ignoreFurtherInvestigation = true; } @@ -80,126 +74,133 @@ public class Clinit extends AbstractMethodDeclaration { /** * Bytecode generation for a method - * - * @param classScope net.sourceforge.phpdt.internal.compiler.lookup.ClassScope - * @param classFile net.sourceforge.phpdt.internal.compiler.codegen.ClassFile + * + * @param classScope + * net.sourceforge.phpdt.internal.compiler.lookup.ClassScope + * @param classFile + * net.sourceforge.phpdt.internal.compiler.codegen.ClassFile */ -// public void generateCode(ClassScope classScope, ClassFile classFile) { -// -// int clinitOffset = 0; -// if (ignoreFurtherInvestigation) { -// // should never have to add any problem method -// return; -// } -// try { -// clinitOffset = classFile.contentsOffset; -// this.generateCode(classScope, classFile, clinitOffset); -// } catch (AbortMethod e) { -// // should never occur -// // the clinit referenceContext is the type declaration -// // All clinit problems will be reported against the type: AbortType instead of AbortMethod -// // reset the contentsOffset to the value before generating the clinit code -// // decrement the number of method info as well. -// // This is done in the addProblemMethod and addProblemConstructor for other -// // cases. -// if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) { -// // a branch target required a goto_w, restart code gen in wide mode. -// try { -// if (statements != null) { -// for (int i = 0, max = statements.length; i < max; i++) -// statements[i].resetStateForCodeGeneration(); -// } -// classFile.contentsOffset = clinitOffset; -// classFile.methodCount--; -// classFile.codeStream.wideMode = true; // request wide mode -// this.generateCode(classScope, classFile, clinitOffset); -// // restart method generation -// } catch (AbortMethod e2) { -// classFile.contentsOffset = clinitOffset; -// classFile.methodCount--; -// } -// } else { -// // produce a problem method accounting for this fatal error -// classFile.contentsOffset = clinitOffset; -// classFile.methodCount--; -// } -// } -// } - + // public void generateCode(ClassScope classScope, ClassFile classFile) { + // + // int clinitOffset = 0; + // if (ignoreFurtherInvestigation) { + // // should never have to add any problem method + // return; + // } + // try { + // clinitOffset = classFile.contentsOffset; + // this.generateCode(classScope, classFile, clinitOffset); + // } catch (AbortMethod e) { + // // should never occur + // // the clinit referenceContext is the type declaration + // // All clinit problems will be reported against the type: AbortType + // instead of AbortMethod + // // reset the contentsOffset to the value before generating the clinit + // code + // // decrement the number of method info as well. + // // This is done in the addProblemMethod and addProblemConstructor for + // other + // // cases. + // if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) { + // // a branch target required a goto_w, restart code gen in wide mode. + // try { + // if (statements != null) { + // for (int i = 0, max = statements.length; i < max; i++) + // statements[i].resetStateForCodeGeneration(); + // } + // classFile.contentsOffset = clinitOffset; + // classFile.methodCount--; + // classFile.codeStream.wideMode = true; // request wide mode + // this.generateCode(classScope, classFile, clinitOffset); + // // restart method generation + // } catch (AbortMethod e2) { + // classFile.contentsOffset = clinitOffset; + // classFile.methodCount--; + // } + // } else { + // // produce a problem method accounting for this fatal error + // classFile.contentsOffset = clinitOffset; + // classFile.methodCount--; + // } + // } + // } /** * Bytecode generation for a method - * - * @param classScope net.sourceforge.phpdt.internal.compiler.lookup.ClassScope - * @param classFile net.sourceforge.phpdt.internal.compiler.codegen.ClassFile + * + * @param classScope + * net.sourceforge.phpdt.internal.compiler.lookup.ClassScope + * @param classFile + * net.sourceforge.phpdt.internal.compiler.codegen.ClassFile */ -// private void generateCode( -// ClassScope classScope, -// ClassFile classFile, -// int clinitOffset) { -// -// ConstantPool constantPool = classFile.constantPool; -// int constantPoolOffset = constantPool.currentOffset; -// int constantPoolIndex = constantPool.currentIndex; -// classFile.generateMethodInfoHeaderForClinit(); -// int codeAttributeOffset = classFile.contentsOffset; -// classFile.generateCodeAttributeHeader(); -// CodeStream codeStream = classFile.codeStream; -// this.resolve(classScope); -// -// codeStream.reset(this, classFile); -// TypeDeclaration declaringType = classScope.referenceContext; -// -// // initialize local positions - including initializer scope. -// MethodScope staticInitializerScope = declaringType.staticInitializerScope; -// staticInitializerScope.computeLocalVariablePositions(0, codeStream); -// -// // 1.4 feature -// // This has to be done before any other initialization -// if (this.assertionSyntheticFieldBinding != null) { -// // generate code related to the activation of assertion for this class -// codeStream.generateClassLiteralAccessForType( -// classScope.enclosingSourceType(), -// classLiteralSyntheticField); -// codeStream.invokeJavaLangClassDesiredAssertionStatus(); -// Label falseLabel = new Label(codeStream); -// codeStream.ifne(falseLabel); -// codeStream.iconst_1(); -// Label jumpLabel = new Label(codeStream); -// codeStream.goto_(jumpLabel); -// falseLabel.place(); -// codeStream.iconst_0(); -// jumpLabel.place(); -// codeStream.putstatic(this.assertionSyntheticFieldBinding); -// } -// // generate initializers -// if (declaringType.fields != null) { -// for (int i = 0, max = declaringType.fields.length; i < max; i++) { -// FieldDeclaration fieldDecl; -// if ((fieldDecl = declaringType.fields[i]).isStatic()) { -// fieldDecl.generateCode(staticInitializerScope, codeStream); -// } -// } -// } -// if (codeStream.position == 0) { -// // do not need to output a Clinit if no bytecodes -// // so we reset the offset inside the byte array contents. -// classFile.contentsOffset = clinitOffset; -// // like we don't addd a method we need to undo the increment on the method count -// classFile.methodCount--; -// // reset the constant pool to its state before the clinit -// constantPool.resetForClinit(constantPoolIndex, constantPoolOffset); -// } else { -// if (this.needFreeReturn) { -// int oldPosition = codeStream.position; -// codeStream.return_(); -// codeStream.updateLocalVariablesAttribute(oldPosition); -// } -// // Record the end of the clinit: point to the declaration of the class -// codeStream.recordPositionsFrom(0, declaringType.sourceStart); -// classFile.completeCodeAttributeForClinit(codeAttributeOffset); -// } -// } - + // private void generateCode( + // ClassScope classScope, + // ClassFile classFile, + // int clinitOffset) { + // + // ConstantPool constantPool = classFile.constantPool; + // int constantPoolOffset = constantPool.currentOffset; + // int constantPoolIndex = constantPool.currentIndex; + // classFile.generateMethodInfoHeaderForClinit(); + // int codeAttributeOffset = classFile.contentsOffset; + // classFile.generateCodeAttributeHeader(); + // CodeStream codeStream = classFile.codeStream; + // this.resolve(classScope); + // + // codeStream.reset(this, classFile); + // TypeDeclaration declaringType = classScope.referenceContext; + // + // // initialize local positions - including initializer scope. + // MethodScope staticInitializerScope = + // declaringType.staticInitializerScope; + // staticInitializerScope.computeLocalVariablePositions(0, codeStream); + // + // // 1.4 feature + // // This has to be done before any other initialization + // if (this.assertionSyntheticFieldBinding != null) { + // // generate code related to the activation of assertion for this class + // codeStream.generateClassLiteralAccessForType( + // classScope.enclosingSourceType(), + // classLiteralSyntheticField); + // codeStream.invokeJavaLangClassDesiredAssertionStatus(); + // Label falseLabel = new Label(codeStream); + // codeStream.ifne(falseLabel); + // codeStream.iconst_1(); + // Label jumpLabel = new Label(codeStream); + // codeStream.goto_(jumpLabel); + // falseLabel.place(); + // codeStream.iconst_0(); + // jumpLabel.place(); + // codeStream.putstatic(this.assertionSyntheticFieldBinding); + // } + // // generate initializers + // if (declaringType.fields != null) { + // for (int i = 0, max = declaringType.fields.length; i < max; i++) { + // FieldDeclaration fieldDecl; + // if ((fieldDecl = declaringType.fields[i]).isStatic()) { + // fieldDecl.generateCode(staticInitializerScope, codeStream); + // } + // } + // } + // if (codeStream.position == 0) { + // // do not need to output a Clinit if no bytecodes + // // so we reset the offset inside the byte array contents. + // classFile.contentsOffset = clinitOffset; + // // like we don't addd a method we need to undo the increment on the + // method count + // classFile.methodCount--; + // // reset the constant pool to its state before the clinit + // constantPool.resetForClinit(constantPoolIndex, constantPoolOffset); + // } else { + // if (this.needFreeReturn) { + // int oldPosition = codeStream.position; + // codeStream.return_(); + // codeStream.updateLocalVariablesAttribute(oldPosition); + // } + // // Record the end of the clinit: point to the declaration of the class + // codeStream.recordPositionsFrom(0, declaringType.sourceStart); + // classFile.completeCodeAttributeForClinit(codeAttributeOffset); + // } + // } public boolean isClinit() { return true; @@ -215,15 +216,18 @@ public class Clinit extends AbstractMethodDeclaration { return true; } - public void parseStatements(UnitParser parser, CompilationUnitDeclaration unit) { - //the clinit is filled by hand .... + public void parseStatements(UnitParser parser, + CompilationUnitDeclaration unit) { + // the clinit is filled by hand .... } + public StringBuffer print(int tab, StringBuffer output) { printIndent(tab, output).append("()"); //$NON-NLS-1$ printBody(tab + 1, output); return output; } + public void resolve(ClassScope scope) { this.scope = new MethodScope(scope, scope.referenceContext, true); @@ -238,24 +242,25 @@ public class Clinit extends AbstractMethodDeclaration { return s; } - public void traverse( - IAbstractSyntaxTreeVisitor visitor, - ClassScope classScope) { + public void traverse(IAbstractSyntaxTreeVisitor visitor, + ClassScope classScope) { visitor.visit(this, classScope); visitor.endVisit(this, classScope); } // 1.4 feature - public void addSupportForAssertion(FieldBinding assertionSyntheticFieldBinding) { + public void addSupportForAssertion( + FieldBinding assertionSyntheticFieldBinding) { this.assertionSyntheticFieldBinding = assertionSyntheticFieldBinding; - // we need to add the field right now, because the field infos are generated before the methods - SourceTypeBinding sourceType = - this.scope.outerMostMethodScope().enclosingSourceType(); - this.classLiteralSyntheticField = - sourceType.addSyntheticField(sourceType, scope); + // we need to add the field right now, because the field infos are + // generated before the methods + SourceTypeBinding sourceType = this.scope.outerMostMethodScope() + .enclosingSourceType(); + this.classLiteralSyntheticField = sourceType.addSyntheticField( + sourceType, scope); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/CompilationUnitDeclaration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/CompilationUnitDeclaration.java index 583b11a..3ea6e05 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/CompilationUnitDeclaration.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/CompilationUnitDeclaration.java @@ -9,6 +9,7 @@ * IBM Corporation - initial API and implementation *******************************************************************************/ package net.sourceforge.phpdt.internal.compiler.ast; + import java.util.ArrayList; import net.sourceforge.phpdt.core.compiler.CharOperation; @@ -23,204 +24,217 @@ import net.sourceforge.phpdt.internal.compiler.problem.AbortType; import net.sourceforge.phpdt.internal.compiler.problem.ProblemReporter; import net.sourceforge.phpdt.internal.compiler.problem.ProblemSeverities; -public class CompilationUnitDeclaration extends ASTNode implements ProblemSeverities, ReferenceContext { - - public ImportReference currentPackage; - public ImportReference[] imports; - // public TypeDeclaration[] types; - public ArrayList types; - - //public char[][] name; - public int[][] comments; - - public boolean ignoreFurtherInvestigation = false; // once pointless to investigate due to errors - public boolean ignoreMethodBodies = false; - public CompilationUnitScope scope; - public ProblemReporter problemReporter; - public CompilationResult compilationResult; - - private LocalTypeBinding[] localTypes; - int localTypeCount = 0; - - public boolean isPropagatingInnerClassEmulation; - - public CompilationUnitDeclaration(ProblemReporter problemReporter, CompilationResult compilationResult, int sourceLength) { - - this.problemReporter = problemReporter; - this.compilationResult = compilationResult; - this.types = new ArrayList(); - //by definition of a compilation unit.... - sourceStart = 0; - sourceEnd = sourceLength - 1; - } - - /* - * We cause the compilation task to abort to a given extent. - */ - public void abort(int abortLevel) { - - switch (abortLevel) { - case AbortType : - throw new AbortType(compilationResult); - case AbortMethod : - throw new AbortMethod(compilationResult); - default : - throw new AbortCompilationUnit(compilationResult); - } - } - - /* - * Dispatch code analysis AND request saturation of inner emulation - */ - public void analyseCode() { - - if (ignoreFurtherInvestigation) - return; - try { - if (types != null) { - for (int i = 0, count = types.size(); i < count; i++) { - if (types.get(i) instanceof TypeDeclaration) - ((TypeDeclaration) types.get(i)).analyseCode(scope); - } - } - // request inner emulation propagation - propagateInnerEmulationForAllLocalTypes(); - } catch (AbortCompilationUnit e) { - this.ignoreFurtherInvestigation = true; - return; - } - } - - /* - * When unit result is about to be accepted, removed back pointers - * to compiler structures. - */ - public void cleanUp() { - if (this.types != null) { - for (int i = 0, max = this.types.size(); i < max; i++) { - if (this.types.get(i) instanceof TypeDeclaration) { - cleanUp((TypeDeclaration) this.types.get(i)); - } - } - for (int i = 0, max = this.localTypeCount; i < max; i++) { - // null out the type's scope backpointers - localTypes[i].scope = null; // local members are already in the list - } - } - // ClassFile[] classFiles = compilationResult.getClassFiles(); - // for (int i = 0, max = classFiles.length; i < max; i++) { - // // clear the classFile back pointer to the bindings - // ClassFile classFile = classFiles[i]; - // // null out the classfile backpointer to a type binding - // classFile.referenceBinding = null; - // classFile.codeStream = null; // codeStream holds onto ast and scopes - // classFile.innerClassesBindings = null; - // } - } - private void cleanUp(TypeDeclaration type) { - if (type.memberTypes != null) { - for (int i = 0, max = type.memberTypes.length; i < max; i++) { - cleanUp(type.memberTypes[i]); - } - } - if (type.binding != null) { - // null out the type's scope backpointers - type.binding.scope = null; - } - } - -// public void checkUnusedImports() { -// -// if (this.scope.imports != null) { -// for (int i = 0, max = this.scope.imports.length; i < max; i++) { -// ImportBinding importBinding = this.scope.imports[i]; -// ImportReference importReference = importBinding.reference; -// if (importReference != null && !importReference.used) { -// scope.problemReporter().unusedImport(importReference); -// } -// } -// } -// } - - public CompilationResult compilationResult() { - return compilationResult; - } - - /* - * Finds the matching type amoung this compilation unit types. - * Returns null if no type with this name is found. - * The type name is a compound name - * eg. if we're looking for X.A.B then a type name would be {X, A, B} - */ - public TypeDeclaration declarationOfType(char[][] typeName) { - - for (int i = 0; i < this.types.size(); i++) { - if (this.types.get(i) instanceof TypeDeclaration) { - TypeDeclaration typeDecl = ((TypeDeclaration) this.types.get(i)).declarationOfType(typeName); - if (typeDecl != null) { - return typeDecl; - } - } - } - return null; - } - - /** - * Bytecode generation - */ - // public void generateCode() { - // - // if (ignoreFurtherInvestigation) { - // if (types != null) { - // for (int i = 0, count = types.length; i < count; i++) { - // types[i].ignoreFurtherInvestigation = true; - // // propagate the flag to request problem type creation - // types[i].generateCode(scope); - // } - // } - // return; - // } - // try { - // if (types != null) { - // for (int i = 0, count = types.length; i < count; i++) - // types[i].generateCode(scope); - // } - // } catch (AbortCompilationUnit e) { - // } - // } - - public char[] getFileName() { - - return compilationResult.getFileName(); - } - - public char[] getMainTypeName() { - - if (compilationResult.compilationUnit == null) { - char[] fileName = compilationResult.getFileName(); - - int start = CharOperation.lastIndexOf('/', fileName) + 1; - if (start == 0 || start < CharOperation.lastIndexOf('\\', fileName)) - start = CharOperation.lastIndexOf('\\', fileName) + 1; - - int end = CharOperation.lastIndexOf('.', fileName); - if (end == -1) - end = fileName.length; - - return CharOperation.subarray(fileName, start, end); - } else { - return compilationResult.compilationUnit.getMainTypeName(); - } - } - - public boolean isEmpty() { - - return (currentPackage == null) && (imports == null) && (types == null); - } - - public boolean hasErrors() { - return this.ignoreFurtherInvestigation; - } +public class CompilationUnitDeclaration extends ASTNode implements + ProblemSeverities, ReferenceContext { + + public ImportReference currentPackage; + + public ImportReference[] imports; + + // public TypeDeclaration[] types; + public ArrayList types; + + // public char[][] name; + public int[][] comments; + + public boolean ignoreFurtherInvestigation = false; // once pointless to + // investigate due to + // errors + + public boolean ignoreMethodBodies = false; + + public CompilationUnitScope scope; + + public ProblemReporter problemReporter; + + public CompilationResult compilationResult; + + private LocalTypeBinding[] localTypes; + + int localTypeCount = 0; + + public boolean isPropagatingInnerClassEmulation; + + public CompilationUnitDeclaration(ProblemReporter problemReporter, + CompilationResult compilationResult, int sourceLength) { + + this.problemReporter = problemReporter; + this.compilationResult = compilationResult; + this.types = new ArrayList(); + // by definition of a compilation unit.... + sourceStart = 0; + sourceEnd = sourceLength - 1; + } + + /* + * We cause the compilation task to abort to a given extent. + */ + public void abort(int abortLevel) { + + switch (abortLevel) { + case AbortType: + throw new AbortType(compilationResult); + case AbortMethod: + throw new AbortMethod(compilationResult); + default: + throw new AbortCompilationUnit(compilationResult); + } + } + + /* + * Dispatch code analysis AND request saturation of inner emulation + */ + public void analyseCode() { + + if (ignoreFurtherInvestigation) + return; + try { + if (types != null) { + for (int i = 0, count = types.size(); i < count; i++) { + if (types.get(i) instanceof TypeDeclaration) + ((TypeDeclaration) types.get(i)).analyseCode(scope); + } + } + // request inner emulation propagation + propagateInnerEmulationForAllLocalTypes(); + } catch (AbortCompilationUnit e) { + this.ignoreFurtherInvestigation = true; + return; + } + } + + /* + * When unit result is about to be accepted, removed back pointers to + * compiler structures. + */ + public void cleanUp() { + if (this.types != null) { + for (int i = 0, max = this.types.size(); i < max; i++) { + if (this.types.get(i) instanceof TypeDeclaration) { + cleanUp((TypeDeclaration) this.types.get(i)); + } + } + for (int i = 0, max = this.localTypeCount; i < max; i++) { + // null out the type's scope backpointers + localTypes[i].scope = null; // local members are already in the + // list + } + } + // ClassFile[] classFiles = compilationResult.getClassFiles(); + // for (int i = 0, max = classFiles.length; i < max; i++) { + // // clear the classFile back pointer to the bindings + // ClassFile classFile = classFiles[i]; + // // null out the classfile backpointer to a type binding + // classFile.referenceBinding = null; + // classFile.codeStream = null; // codeStream holds onto ast and scopes + // classFile.innerClassesBindings = null; + // } + } + + private void cleanUp(TypeDeclaration type) { + if (type.memberTypes != null) { + for (int i = 0, max = type.memberTypes.length; i < max; i++) { + cleanUp(type.memberTypes[i]); + } + } + if (type.binding != null) { + // null out the type's scope backpointers + type.binding.scope = null; + } + } + + // public void checkUnusedImports() { + // + // if (this.scope.imports != null) { + // for (int i = 0, max = this.scope.imports.length; i < max; i++) { + // ImportBinding importBinding = this.scope.imports[i]; + // ImportReference importReference = importBinding.reference; + // if (importReference != null && !importReference.used) { + // scope.problemReporter().unusedImport(importReference); + // } + // } + // } + // } + + public CompilationResult compilationResult() { + return compilationResult; + } + + /* + * Finds the matching type amoung this compilation unit types. Returns null + * if no type with this name is found. The type name is a compound name eg. + * if we're looking for X.A.B then a type name would be {X, A, B} + */ + public TypeDeclaration declarationOfType(char[][] typeName) { + + for (int i = 0; i < this.types.size(); i++) { + if (this.types.get(i) instanceof TypeDeclaration) { + TypeDeclaration typeDecl = ((TypeDeclaration) this.types.get(i)) + .declarationOfType(typeName); + if (typeDecl != null) { + return typeDecl; + } + } + } + return null; + } + + /** + * Bytecode generation + */ + // public void generateCode() { + // + // if (ignoreFurtherInvestigation) { + // if (types != null) { + // for (int i = 0, count = types.length; i < count; i++) { + // types[i].ignoreFurtherInvestigation = true; + // // propagate the flag to request problem type creation + // types[i].generateCode(scope); + // } + // } + // return; + // } + // try { + // if (types != null) { + // for (int i = 0, count = types.length; i < count; i++) + // types[i].generateCode(scope); + // } + // } catch (AbortCompilationUnit e) { + // } + // } + public char[] getFileName() { + + return compilationResult.getFileName(); + } + + public char[] getMainTypeName() { + + if (compilationResult.compilationUnit == null) { + char[] fileName = compilationResult.getFileName(); + + int start = CharOperation.lastIndexOf('/', fileName) + 1; + if (start == 0 || start < CharOperation.lastIndexOf('\\', fileName)) + start = CharOperation.lastIndexOf('\\', fileName) + 1; + + int end = CharOperation.lastIndexOf('.', fileName); + if (end == -1) + end = fileName.length; + + return CharOperation.subarray(fileName, start, end); + } else { + return compilationResult.compilationUnit.getMainTypeName(); + } + } + + public boolean isEmpty() { + + return (currentPackage == null) && (imports == null) && (types == null); + } + + public boolean hasErrors() { + return this.ignoreFurtherInvestigation; + } + public StringBuffer print(int indent, StringBuffer output) { if (currentPackage != null) { @@ -235,113 +249,117 @@ public class CompilationUnitDeclaration extends ASTNode implements ProblemSeveri if (types != null) { for (int i = 0; i < types.size(); i++) { - ((ASTNode)types.get(i)).print(indent, output).append("\n"); //$NON-NLS-1$ + ((ASTNode) types.get(i)).print(indent, output).append("\n"); //$NON-NLS-1$ } } return output; } - - /* - * Force inner local types to update their innerclass emulation - */ - public void propagateInnerEmulationForAllLocalTypes() { - - isPropagatingInnerClassEmulation = true; - for (int i = 0, max = this.localTypeCount; i < max; i++) { - - LocalTypeBinding localType = localTypes[i]; - // only propagate for reachable local types - if ((localType.scope.referenceType().bits & IsReachableMASK) != 0) { - localType.updateInnerEmulationDependents(); - } - } - } - - /* - * Keep track of all local types, so as to update their innerclass - * emulation later on. - */ - public void record(LocalTypeBinding localType) { - - if (this.localTypeCount == 0) { - this.localTypes = new LocalTypeBinding[5]; - } else if (this.localTypeCount == this.localTypes.length) { - System.arraycopy( - this.localTypes, - 0, - (this.localTypes = new LocalTypeBinding[this.localTypeCount * 2]), - 0, - this.localTypeCount); - } - this.localTypes[this.localTypeCount++] = localType; - } - - public void resolve() { - - try { - if (types != null) { - for (int i = 0, count = types.size(); i < count; i++) { - if (types.get(i) instanceof TypeDeclaration) { - ((TypeDeclaration) types.get(i)).resolve(scope); - } - } - } -// if (!this.compilationResult.hasSyntaxError()) -// checkUnusedImports(); - } catch (AbortCompilationUnit e) { - this.ignoreFurtherInvestigation = true; - return; - } - } - - public void tagAsHavingErrors() { - ignoreFurtherInvestigation = true; - } - - public String toString(int tab) { - - String s = ""; //$NON-NLS-1$ - if (currentPackage != null) - s = tabString(tab) + "package " + currentPackage.toString(0, false) + ";\n"; //$NON-NLS-1$ //$NON-NLS-2$ - - if (imports != null) - for (int i = 0; i < imports.length; i++) { - s += tabString(tab) + "include " + imports[i].toString() + ";\n"; //$NON-NLS-1$ //$NON-NLS-2$ - }; - - if (types != null) - for (int i = 0; i < types.size(); i++) { - s += ((ASTNode) types.get(i)).toString(tab) + "\n"; //$NON-NLS-1$ - } - return s; - } - - public void traverse(ASTVisitor visitor, CompilationUnitScope scope) { - - if (ignoreFurtherInvestigation) - return; - try { - if (visitor.visit(this, scope)) { - if (currentPackage != null) { - currentPackage.traverse(visitor, scope); - } - if (imports != null) { - int importLength = imports.length; - for (int i = 0; i < importLength; i++) { - imports[i].traverse(visitor, scope); - } - } - if (types != null) { - int typesLength = types.size(); - for (int i = 0; i < typesLength; i++) { - if (types.get(i) instanceof TypeDeclaration) { - ((TypeDeclaration) types.get(i)).traverse(visitor, scope); - } - } - } - } - visitor.endVisit(this, scope); - } catch (AbortCompilationUnit e) { - } - } + + /* + * Force inner local types to update their innerclass emulation + */ + public void propagateInnerEmulationForAllLocalTypes() { + + isPropagatingInnerClassEmulation = true; + for (int i = 0, max = this.localTypeCount; i < max; i++) { + + LocalTypeBinding localType = localTypes[i]; + // only propagate for reachable local types + if ((localType.scope.referenceType().bits & IsReachableMASK) != 0) { + localType.updateInnerEmulationDependents(); + } + } + } + + /* + * Keep track of all local types, so as to update their innerclass emulation + * later on. + */ + public void record(LocalTypeBinding localType) { + + if (this.localTypeCount == 0) { + this.localTypes = new LocalTypeBinding[5]; + } else if (this.localTypeCount == this.localTypes.length) { + System + .arraycopy( + this.localTypes, + 0, + (this.localTypes = new LocalTypeBinding[this.localTypeCount * 2]), + 0, this.localTypeCount); + } + this.localTypes[this.localTypeCount++] = localType; + } + + public void resolve() { + + try { + if (types != null) { + for (int i = 0, count = types.size(); i < count; i++) { + if (types.get(i) instanceof TypeDeclaration) { + ((TypeDeclaration) types.get(i)).resolve(scope); + } + } + } + // if (!this.compilationResult.hasSyntaxError()) + // checkUnusedImports(); + } catch (AbortCompilationUnit e) { + this.ignoreFurtherInvestigation = true; + return; + } + } + + public void tagAsHavingErrors() { + ignoreFurtherInvestigation = true; + } + + public String toString(int tab) { + + String s = ""; //$NON-NLS-1$ + if (currentPackage != null) + s = tabString(tab) + + "package " + currentPackage.toString(0, false) + ";\n"; //$NON-NLS-1$ //$NON-NLS-2$ + + if (imports != null) + for (int i = 0; i < imports.length; i++) { + s += tabString(tab) + + "include " + imports[i].toString() + ";\n"; //$NON-NLS-1$ //$NON-NLS-2$ + } + ; + + if (types != null) + for (int i = 0; i < types.size(); i++) { + s += ((ASTNode) types.get(i)).toString(tab) + "\n"; //$NON-NLS-1$ + } + return s; + } + + public void traverse(ASTVisitor visitor, CompilationUnitScope scope) { + + if (ignoreFurtherInvestigation) + return; + try { + if (visitor.visit(this, scope)) { + if (currentPackage != null) { + currentPackage.traverse(visitor, scope); + } + if (imports != null) { + int importLength = imports.length; + for (int i = 0; i < importLength; i++) { + imports[i].traverse(visitor, scope); + } + } + if (types != null) { + int typesLength = types.size(); + for (int i = 0; i < typesLength; i++) { + if (types.get(i) instanceof TypeDeclaration) { + ((TypeDeclaration) types.get(i)).traverse(visitor, + scope); + } + } + } + } + visitor.endVisit(this, scope); + } catch (AbortCompilationUnit e) { + } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/CompoundAssignment.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/CompoundAssignment.java index 5912979..5f6649e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/CompoundAssignment.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/CompoundAssignment.java @@ -18,129 +18,157 @@ import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class CompoundAssignment extends Assignment implements OperatorIds { public int operator; + public int assignmentImplicitConversion; - // var op exp is equivalent to var = (varType) var op exp + // var op exp is equivalent to var = (varType) var op exp // assignmentImplicitConversion stores the cast needed for the assignment -public CompoundAssignment(Expression lhs, Expression expression,int operator, int sourceEnd) { - //lhs is always a reference by construction , - //but is build as an expression ==> the checkcast cannot fail + public CompoundAssignment(Expression lhs, Expression expression, + int operator, int sourceEnd) { + // lhs is always a reference by construction , + // but is build as an expression ==> the checkcast cannot fail - super(lhs, expression, sourceEnd); - lhs.bits &= ~IsStrictlyAssignedMASK; // tag lhs as NON assigned - it is also a read access - this.operator = operator ; -} -public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { - // record setting a variable: various scenarii are possible, setting an array reference, - // a field reference, a blank final field reference, a field of an enclosing instance or - // just a local variable. + super(lhs, expression, sourceEnd); + lhs.bits &= ~IsStrictlyAssignedMASK; // tag lhs as NON assigned - it + // is also a read access + this.operator = operator; + } - return ((Reference) lhs).analyseAssignment(currentScope, flowContext, flowInfo, this, true).unconditionalInits(); -} -//public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) { -// -// // various scenarii are possible, setting an array reference, -// // a field reference, a blank final field reference, a field of an enclosing instance or -// // just a local variable. -// -// int pc = codeStream.position; -// ((Reference) lhs).generateCompoundAssignment(currentScope, codeStream, expression, operator, assignmentImplicitConversion, valueRequired); -// if (valueRequired) { -// codeStream.generateImplicitConversion(implicitConversion); -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -//} -public String operatorToString() { - switch (operator) { - case PLUS : + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { + // record setting a variable: various scenarii are possible, setting an + // array reference, + // a field reference, a blank final field reference, a field of an + // enclosing instance or + // just a local variable. + + return ((Reference) lhs).analyseAssignment(currentScope, flowContext, + flowInfo, this, true).unconditionalInits(); + } + + // public void generateCode(BlockScope currentScope, CodeStream codeStream, + // boolean valueRequired) { + // + // // various scenarii are possible, setting an array reference, + // // a field reference, a blank final field reference, a field of an + // enclosing instance or + // // just a local variable. + // + // int pc = codeStream.position; + // ((Reference) lhs).generateCompoundAssignment(currentScope, codeStream, + // expression, operator, assignmentImplicitConversion, valueRequired); + // if (valueRequired) { + // codeStream.generateImplicitConversion(implicitConversion); + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } + public String operatorToString() { + switch (operator) { + case PLUS: return "+="; //$NON-NLS-1$ - case MINUS : + case MINUS: return "-="; //$NON-NLS-1$ - case MULTIPLY : + case MULTIPLY: return "*="; //$NON-NLS-1$ - case DIVIDE : + case DIVIDE: return "/="; //$NON-NLS-1$ - case AND : + case AND: return "&="; //$NON-NLS-1$ - case OR : + case OR: return "|="; //$NON-NLS-1$ - case XOR : + case XOR: return "^="; //$NON-NLS-1$ - case REMAINDER : + case REMAINDER: return "%="; //$NON-NLS-1$ - case LEFT_SHIFT : + case LEFT_SHIFT: return "<<="; //$NON-NLS-1$ - case RIGHT_SHIFT : + case RIGHT_SHIFT: return ">>="; //$NON-NLS-1$ - case UNSIGNED_RIGHT_SHIFT : + case UNSIGNED_RIGHT_SHIFT: return ">>>="; //$NON-NLS-1$ - }; - return "unknown operator"; //$NON-NLS-1$ -} -public TypeBinding resolveType(BlockScope scope) { - constant = NotAConstant; - if (!(this.lhs instanceof Reference)) { - scope.problemReporter().expressionShouldBeAVariable(this.lhs); - } - TypeBinding lhsType = lhs.resolveType(scope); - TypeBinding expressionType = expression.resolveType(scope); - if (lhsType == null || expressionType == null) - return null; - - int lhsId = lhsType.id; - int expressionId = expressionType.id; - if (restrainUsageToNumericTypes() && !lhsType.isNumericType()) { - scope.problemReporter().operatorOnlyValidOnNumericType(this, lhsType, expressionType); - return null; - } - if (lhsId > 15 || expressionId > 15) { - if (lhsId != T_String) { // String += Object is valid wheraas Object -= String is not - scope.problemReporter().invalidOperator(this, lhsType, expressionType); - return null; } - expressionId = T_Object; // use the Object has tag table + ; + return "unknown operator"; //$NON-NLS-1$ } - // the code is an int - // (cast) left Op (cast) rigth --> result - // 0000 0000 0000 0000 0000 - // <<16 <<12 <<8 <<4 <<0 + public TypeBinding resolveType(BlockScope scope) { + constant = NotAConstant; + if (!(this.lhs instanceof Reference)) { + scope.problemReporter().expressionShouldBeAVariable(this.lhs); + } + TypeBinding lhsType = lhs.resolveType(scope); + TypeBinding expressionType = expression.resolveType(scope); + if (lhsType == null || expressionType == null) + return null; - // the conversion is stored INTO the reference (info needed for the code gen) - int result = OperatorExpression.ResolveTypeTables[operator][ (lhsId << 4) + expressionId]; - if (result == T_undefined) { - scope.problemReporter().invalidOperator(this, lhsType, expressionType); - return null; - } - if (operator == PLUS){ - if(scope.isJavaLangObject(lhsType)) { - // += is illegal - scope.problemReporter().invalidOperator(this, lhsType, expressionType); + int lhsId = lhsType.id; + int expressionId = expressionType.id; + if (restrainUsageToNumericTypes() && !lhsType.isNumericType()) { + scope.problemReporter().operatorOnlyValidOnNumericType(this, + lhsType, expressionType); return null; - } else if ((lhsType.isNumericType() || lhsId == T_boolean) && !expressionType.isNumericType()){ - // += is illegal - scope.problemReporter().invalidOperator(this, lhsType, expressionType); + } + if (lhsId > 15 || expressionId > 15) { + if (lhsId != T_String) { // String += Object is valid wheraas + // Object -= String is not + scope.problemReporter().invalidOperator(this, lhsType, + expressionType); + return null; + } + expressionId = T_Object; // use the Object has tag table + } + + // the code is an int + // (cast) left Op (cast) rigth --> result + // 0000 0000 0000 0000 0000 + // <<16 <<12 <<8 <<4 <<0 + + // the conversion is stored INTO the reference (info needed for the code + // gen) + int result = OperatorExpression.ResolveTypeTables[operator][(lhsId << 4) + + expressionId]; + if (result == T_undefined) { + scope.problemReporter().invalidOperator(this, lhsType, + expressionType); return null; } + if (operator == PLUS) { + if (scope.isJavaLangObject(lhsType)) { + // += is illegal + scope.problemReporter().invalidOperator(this, lhsType, + expressionType); + return null; + } else if ((lhsType.isNumericType() || lhsId == T_boolean) + && !expressionType.isNumericType()) { + // += is illegal + scope.problemReporter().invalidOperator(this, lhsType, + expressionType); + return null; + } + } + lhs.implicitConversion = result >>> 12; + expression.implicitConversion = (result >>> 4) & 0x000FF; + assignmentImplicitConversion = (lhsId << 4) + (result & 0x0000F); + return this.resolvedType = lhsType; } - lhs.implicitConversion = result >>> 12; - expression.implicitConversion = (result >>> 4) & 0x000FF; - assignmentImplicitConversion = (lhsId << 4) + (result & 0x0000F); - return this.resolvedType = lhsType; -} -public boolean restrainUsageToNumericTypes(){ - return false ;} -public String toStringExpressionNoParenthesis() { - - return lhs.toStringExpression() + " " + //$NON-NLS-1$ - operatorToString() + " " + //$NON-NLS-1$ - expression.toStringExpression() ; } -public void traverse(ASTVisitor visitor, BlockScope scope) { - if (visitor.visit(this, scope)) { - lhs.traverse(visitor, scope); - expression.traverse(visitor, scope); + + public boolean restrainUsageToNumericTypes() { + return false; + } + + public String toStringExpressionNoParenthesis() { + + return lhs.toStringExpression() + " " + //$NON-NLS-1$ + operatorToString() + " " + //$NON-NLS-1$ + expression.toStringExpression(); + } + + public void traverse(ASTVisitor visitor, BlockScope scope) { + if (visitor.visit(this, scope)) { + lhs.traverse(visitor, scope); + expression.traverse(visitor, scope); + } + visitor.endVisit(this, scope); } - visitor.endVisit(this, scope); -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ConditionalExpression.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ConditionalExpression.java index 9bd4807..6a3b606 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ConditionalExpression.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ConditionalExpression.java @@ -20,21 +20,24 @@ import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; public class ConditionalExpression extends OperatorExpression { public Expression condition, valueIfTrue, valueIfFalse; + public Constant optimizedBooleanConstant; + public Constant optimizedIfTrueConstant; + public Constant optimizedIfFalseConstant; - + private int returnTypeSlotSize = 1; // for local variables table attributes int trueInitStateIndex = -1; + int falseInitStateIndex = -1; + int mergedInitStateIndex = -1; - - public ConditionalExpression( - Expression condition, - Expression valueIfTrue, - Expression valueIfFalse) { + + public ConditionalExpression(Expression condition, Expression valueIfTrue, + Expression valueIfFalse) { this.condition = condition; this.valueIfTrue = valueIfTrue; this.valueIfFalse = valueIfFalse; @@ -42,378 +45,426 @@ public class ConditionalExpression extends OperatorExpression { sourceEnd = valueIfFalse.sourceEnd; } - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { Constant cst = this.condition.optimizedBooleanConstant(); - boolean isConditionOptimizedTrue = cst != NotAConstant && cst.booleanValue() == true; - boolean isConditionOptimizedFalse = cst != NotAConstant && cst.booleanValue() == false; + boolean isConditionOptimizedTrue = cst != NotAConstant + && cst.booleanValue() == true; + boolean isConditionOptimizedFalse = cst != NotAConstant + && cst.booleanValue() == false; int mode = flowInfo.reachMode(); - flowInfo = condition.analyseCode(currentScope, flowContext, flowInfo, cst == NotAConstant); - + flowInfo = condition.analyseCode(currentScope, flowContext, flowInfo, + cst == NotAConstant); + // process the if-true part FlowInfo trueFlowInfo = flowInfo.initsWhenTrue().copy(); if (isConditionOptimizedFalse) { - trueFlowInfo.setReachMode(FlowInfo.UNREACHABLE); + trueFlowInfo.setReachMode(FlowInfo.UNREACHABLE); } - trueInitStateIndex = currentScope.methodScope().recordInitializationStates(trueFlowInfo); - trueFlowInfo = valueIfTrue.analyseCode(currentScope, flowContext, trueFlowInfo); + trueInitStateIndex = currentScope.methodScope() + .recordInitializationStates(trueFlowInfo); + trueFlowInfo = valueIfTrue.analyseCode(currentScope, flowContext, + trueFlowInfo); // process the if-false part FlowInfo falseFlowInfo = flowInfo.initsWhenFalse().copy(); if (isConditionOptimizedTrue) { - falseFlowInfo.setReachMode(FlowInfo.UNREACHABLE); + falseFlowInfo.setReachMode(FlowInfo.UNREACHABLE); } - falseInitStateIndex = currentScope.methodScope().recordInitializationStates(falseFlowInfo); - falseFlowInfo = valueIfFalse.analyseCode(currentScope, flowContext, falseFlowInfo); + falseInitStateIndex = currentScope.methodScope() + .recordInitializationStates(falseFlowInfo); + falseFlowInfo = valueIfFalse.analyseCode(currentScope, flowContext, + falseFlowInfo); // merge if-true & if-false initializations FlowInfo mergedInfo; - if (isConditionOptimizedTrue){ - mergedInfo = trueFlowInfo.addPotentialInitializationsFrom(falseFlowInfo); + if (isConditionOptimizedTrue) { + mergedInfo = trueFlowInfo + .addPotentialInitializationsFrom(falseFlowInfo); } else if (isConditionOptimizedFalse) { - mergedInfo = falseFlowInfo.addPotentialInitializationsFrom(trueFlowInfo); + mergedInfo = falseFlowInfo + .addPotentialInitializationsFrom(trueFlowInfo); } else { - // merge using a conditional info - 1GK2BLM - // if ((t && (v = t)) ? t : t && (v = f)) r = v; -- ok + // merge using a conditional info - 1GK2BLM + // if ((t && (v = t)) ? t : t && (v = f)) r = v; -- ok cst = this.optimizedIfTrueConstant; - boolean isValueIfTrueOptimizedTrue = cst != null && cst != NotAConstant && cst.booleanValue() == true; - boolean isValueIfTrueOptimizedFalse = cst != null && cst != NotAConstant && cst.booleanValue() == false; - + boolean isValueIfTrueOptimizedTrue = cst != null + && cst != NotAConstant && cst.booleanValue() == true; + boolean isValueIfTrueOptimizedFalse = cst != null + && cst != NotAConstant && cst.booleanValue() == false; + cst = this.optimizedIfFalseConstant; - boolean isValueIfFalseOptimizedTrue = cst != null && cst != NotAConstant && cst.booleanValue() == true; - boolean isValueIfFalseOptimizedFalse = cst != null && cst != NotAConstant && cst.booleanValue() == false; + boolean isValueIfFalseOptimizedTrue = cst != null + && cst != NotAConstant && cst.booleanValue() == true; + boolean isValueIfFalseOptimizedFalse = cst != null + && cst != NotAConstant && cst.booleanValue() == false; - UnconditionalFlowInfo trueInfoWhenTrue = trueFlowInfo.initsWhenTrue().copy().unconditionalInits(); - if (isValueIfTrueOptimizedFalse) trueInfoWhenTrue.setReachMode(FlowInfo.UNREACHABLE); + UnconditionalFlowInfo trueInfoWhenTrue = trueFlowInfo + .initsWhenTrue().copy().unconditionalInits(); + if (isValueIfTrueOptimizedFalse) + trueInfoWhenTrue.setReachMode(FlowInfo.UNREACHABLE); - UnconditionalFlowInfo falseInfoWhenTrue = falseFlowInfo.initsWhenTrue().copy().unconditionalInits(); - if (isValueIfFalseOptimizedFalse) falseInfoWhenTrue.setReachMode(FlowInfo.UNREACHABLE); - - UnconditionalFlowInfo trueInfoWhenFalse = trueFlowInfo.initsWhenFalse().copy().unconditionalInits(); - if (isValueIfTrueOptimizedTrue) trueInfoWhenFalse.setReachMode(FlowInfo.UNREACHABLE); + UnconditionalFlowInfo falseInfoWhenTrue = falseFlowInfo + .initsWhenTrue().copy().unconditionalInits(); + if (isValueIfFalseOptimizedFalse) + falseInfoWhenTrue.setReachMode(FlowInfo.UNREACHABLE); - UnconditionalFlowInfo falseInfoWhenFalse = falseFlowInfo.initsWhenFalse().copy().unconditionalInits(); - if (isValueIfFalseOptimizedTrue) falseInfoWhenFalse.setReachMode(FlowInfo.UNREACHABLE); + UnconditionalFlowInfo trueInfoWhenFalse = trueFlowInfo + .initsWhenFalse().copy().unconditionalInits(); + if (isValueIfTrueOptimizedTrue) + trueInfoWhenFalse.setReachMode(FlowInfo.UNREACHABLE); - mergedInfo = - FlowInfo.conditional( - trueInfoWhenTrue.mergedWith(falseInfoWhenTrue), - trueInfoWhenFalse.mergedWith(falseInfoWhenFalse)); + UnconditionalFlowInfo falseInfoWhenFalse = falseFlowInfo + .initsWhenFalse().copy().unconditionalInits(); + if (isValueIfFalseOptimizedTrue) + falseInfoWhenFalse.setReachMode(FlowInfo.UNREACHABLE); + + mergedInfo = FlowInfo.conditional(trueInfoWhenTrue + .mergedWith(falseInfoWhenTrue), trueInfoWhenFalse + .mergedWith(falseInfoWhenFalse)); } - mergedInitStateIndex = - currentScope.methodScope().recordInitializationStates(mergedInfo); + mergedInitStateIndex = currentScope.methodScope() + .recordInitializationStates(mergedInfo); mergedInfo.setReachMode(mode); return mergedInfo; } /** * Code generation for the conditional operator ?: - * - * @param currentScope net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream - * @param valueRequired boolean - */ -// public void generateCode( -// BlockScope currentScope, -// CodeStream codeStream, -// boolean valueRequired) { -// -// int pc = codeStream.position; -// Label endifLabel, falseLabel; -// if (constant != NotAConstant) { -// if (valueRequired) -// codeStream.generateConstant(constant, implicitConversion); -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// return; -// } -// Constant cst = condition.constant; -// Constant condCst = condition.optimizedBooleanConstant(); -// boolean needTruePart = -// !(((cst != NotAConstant) && (cst.booleanValue() == false)) -// || ((condCst != NotAConstant) && (condCst.booleanValue() == false))); -// boolean needFalsePart = -// !(((cst != NotAConstant) && (cst.booleanValue() == true)) -// || ((condCst != NotAConstant) && (condCst.booleanValue() == true))); -// endifLabel = new Label(codeStream); -// -// // Generate code for the condition -// boolean needConditionValue = (cst == NotAConstant) && (condCst == NotAConstant); -// condition.generateOptimizedBoolean( -// currentScope, -// codeStream, -// null, -// (falseLabel = new Label(codeStream)), -// needConditionValue); -// -// if (trueInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// trueInitStateIndex); -// codeStream.addDefinitelyAssignedVariables(currentScope, trueInitStateIndex); -// } -// // Then code generation -// if (needTruePart) { -// valueIfTrue.generateCode(currentScope, codeStream, valueRequired); -// if (needFalsePart) { -// // Jump over the else part -// int position = codeStream.position; -// codeStream.goto_(endifLabel); -// codeStream.updateLastRecordedEndPC(position); -// // Tune codestream stack size -// if (valueRequired) { -// codeStream.decrStackSize(returnTypeSlotSize); -// } -// } -// } -// if (needFalsePart) { -// falseLabel.place(); -// if (falseInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// falseInitStateIndex); -// codeStream.addDefinitelyAssignedVariables(currentScope, falseInitStateIndex); -// } -// valueIfFalse.generateCode(currentScope, codeStream, valueRequired); -// // End of if statement -// endifLabel.place(); -// } -// // May loose some local variable initializations : affecting the local variable attributes -// if (mergedInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// mergedInitStateIndex); -// } -// // implicit conversion -// if (valueRequired) -// codeStream.generateImplicitConversion(implicitConversion); -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } -// -// /** -// * Optimized boolean code generation for the conditional operator ?: -// */ -// public void generateOptimizedBoolean( -// BlockScope currentScope, -// CodeStream codeStream, -// Label trueLabel, -// Label falseLabel, -// boolean valueRequired) { -// -// if ((constant != Constant.NotAConstant) && (constant.typeID() == T_boolean) // constant -// || (valueIfTrue.implicitConversion >> 4) != T_boolean) { // non boolean values -// super.generateOptimizedBoolean(currentScope, codeStream, trueLabel, falseLabel, valueRequired); -// return; -// } -// Constant cst = condition.constant; -// Constant condCst = condition.optimizedBooleanConstant(); -// boolean needTruePart = -// !(((cst != NotAConstant) && (cst.booleanValue() == false)) -// || ((condCst != NotAConstant) && (condCst.booleanValue() == false))); -// boolean needFalsePart = -// !(((cst != NotAConstant) && (cst.booleanValue() == true)) -// || ((condCst != NotAConstant) && (condCst.booleanValue() == true))); -// -// Label internalFalseLabel, endifLabel = new Label(codeStream); -// -// // Generate code for the condition -// boolean needConditionValue = (cst == NotAConstant) && (condCst == NotAConstant); -// condition.generateOptimizedBoolean( -// currentScope, -// codeStream, -// null, -// internalFalseLabel = new Label(codeStream), -// needConditionValue); -// -// if (trueInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// trueInitStateIndex); -// codeStream.addDefinitelyAssignedVariables(currentScope, trueInitStateIndex); -// } -// // Then code generation -// if (needTruePart) { -// valueIfTrue.generateOptimizedBoolean(currentScope, codeStream, trueLabel, falseLabel, valueRequired); -// -// if (needFalsePart) { -// // Jump over the else part -// int position = codeStream.position; -// codeStream.goto_(endifLabel); -// codeStream.updateLastRecordedEndPC(position); -// // No need to decrement codestream stack size -// // since valueIfTrue was already consumed by branch bytecode -// } -// } -// if (needFalsePart) { -// internalFalseLabel.place(); -// if (falseInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// falseInitStateIndex); -// codeStream.addDefinitelyAssignedVariables(currentScope, falseInitStateIndex); -// } -// valueIfFalse.generateOptimizedBoolean(currentScope, codeStream, trueLabel, falseLabel, valueRequired); -// -// // End of if statement -// endifLabel.place(); -// } -// // May loose some local variable initializations : affecting the local variable attributes -// if (mergedInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// mergedInitStateIndex); -// } -// // no implicit conversion for boolean values -// codeStream.updateLastRecordedEndPC(codeStream.position); -// } -// -// public Constant optimizedBooleanConstant() { -// -// return this.optimizedBooleanConstant == null ? this.constant : this.optimizedBooleanConstant; -// } -// -// public TypeBinding resolveType(BlockScope scope) { -// // specs p.368 -// constant = NotAConstant; -// TypeBinding conditionType = condition.resolveTypeExpecting(scope, BooleanBinding); -// TypeBinding valueIfTrueType = valueIfTrue.resolveType(scope); -// TypeBinding valueIfFalseType = valueIfFalse.resolveType(scope); -// if (conditionType == null || valueIfTrueType == null || valueIfFalseType == null) -// return null; -// -// // Propagate the constant value from the valueIfTrue and valueIFFalse expression if it is possible -// Constant condConstant, trueConstant, falseConstant; -// if ((condConstant = condition.constant) != NotAConstant -// && (trueConstant = valueIfTrue.constant) != NotAConstant -// && (falseConstant = valueIfFalse.constant) != NotAConstant) { -// // all terms are constant expression so we can propagate the constant -// // from valueIFTrue or valueIfFalse to teh receiver constant -// constant = condConstant.booleanValue() ? trueConstant : falseConstant; -// } -// if (valueIfTrueType == valueIfFalseType) { // harmed the implicit conversion -// valueIfTrue.implicitWidening(valueIfTrueType, valueIfTrueType); -// valueIfFalse.implicitConversion = valueIfTrue.implicitConversion; -// if (valueIfTrueType == LongBinding || valueIfTrueType == DoubleBinding) { -// returnTypeSlotSize = 2; -// } -// -// if (valueIfTrueType == BooleanBinding) { -// this.optimizedIfTrueConstant = valueIfTrue.optimizedBooleanConstant(); -// this.optimizedIfFalseConstant = valueIfFalse.optimizedBooleanConstant(); -// -// // Propagate the optimized boolean constant if possible -// if ((condConstant = condition.optimizedBooleanConstant()) != NotAConstant) { -// -// this.optimizedBooleanConstant = condConstant.booleanValue() -// ? optimizedIfTrueConstant -// : optimizedIfFalseConstant; -// } -// } -// return this.resolvedType = valueIfTrueType; -// } -// // Determine the return type depending on argument types -// // Numeric types -// if (valueIfTrueType.isNumericType() && valueIfFalseType.isNumericType()) { -// // (Short x Byte) or (Byte x Short)" -// if ((valueIfTrueType == ByteBinding && valueIfFalseType == ShortBinding) -// || (valueIfTrueType == ShortBinding && valueIfFalseType == ByteBinding)) { -// valueIfTrue.implicitWidening(ShortBinding, valueIfTrueType); -// valueIfFalse.implicitWidening(ShortBinding, valueIfFalseType); -// this.resolvedType = ShortBinding; -// return ShortBinding; -// } -// // x constant(Int) ---> and reciprocally -// if ((valueIfTrueType == ByteBinding || valueIfTrueType == ShortBinding || valueIfTrueType == CharBinding) -// && (valueIfFalseType == IntBinding -// && valueIfFalse.isConstantValueOfTypeAssignableToType(valueIfFalseType, valueIfTrueType))) { -// valueIfTrue.implicitWidening(valueIfTrueType, valueIfTrueType); -// valueIfFalse.implicitWidening(valueIfTrueType, valueIfFalseType); -// this.resolvedType = valueIfTrueType; -// return valueIfTrueType; -// } -// if ((valueIfFalseType == ByteBinding -// || valueIfFalseType == ShortBinding -// || valueIfFalseType == CharBinding) -// && (valueIfTrueType == IntBinding -// && valueIfTrue.isConstantValueOfTypeAssignableToType(valueIfTrueType, valueIfFalseType))) { -// valueIfTrue.implicitWidening(valueIfFalseType, valueIfTrueType); -// valueIfFalse.implicitWidening(valueIfFalseType, valueIfFalseType); -// this.resolvedType = valueIfFalseType; -// return valueIfFalseType; -// } -// // Manual binary numeric promotion -// // int -// if (BaseTypeBinding.isNarrowing(valueIfTrueType.id, T_int) -// && BaseTypeBinding.isNarrowing(valueIfFalseType.id, T_int)) { -// valueIfTrue.implicitWidening(IntBinding, valueIfTrueType); -// valueIfFalse.implicitWidening(IntBinding, valueIfFalseType); -// this.resolvedType = IntBinding; -// return IntBinding; -// } -// // long -// if (BaseTypeBinding.isNarrowing(valueIfTrueType.id, T_long) -// && BaseTypeBinding.isNarrowing(valueIfFalseType.id, T_long)) { -// valueIfTrue.implicitWidening(LongBinding, valueIfTrueType); -// valueIfFalse.implicitWidening(LongBinding, valueIfFalseType); -// returnTypeSlotSize = 2; -// this.resolvedType = LongBinding; -// return LongBinding; -// } -// // float -// if (BaseTypeBinding.isNarrowing(valueIfTrueType.id, T_float) -// && BaseTypeBinding.isNarrowing(valueIfFalseType.id, T_float)) { -// valueIfTrue.implicitWidening(FloatBinding, valueIfTrueType); -// valueIfFalse.implicitWidening(FloatBinding, valueIfFalseType); -// this.resolvedType = FloatBinding; -// return FloatBinding; -// } -// // double -// valueIfTrue.implicitWidening(DoubleBinding, valueIfTrueType); -// valueIfFalse.implicitWidening(DoubleBinding, valueIfFalseType); -// returnTypeSlotSize = 2; -// this.resolvedType = DoubleBinding; -// return DoubleBinding; -// } -// // Type references (null null is already tested) -// if ((valueIfTrueType.isBaseType() && valueIfTrueType != NullBinding) -// || (valueIfFalseType.isBaseType() && valueIfFalseType != NullBinding)) { -// scope.problemReporter().conditionalArgumentsIncompatibleTypes( -// this, -// valueIfTrueType, -// valueIfFalseType); -// return null; -// } -// if (valueIfFalseType.isCompatibleWith(valueIfTrueType)) { -// valueIfTrue.implicitWidening(valueIfTrueType, valueIfTrueType); -// valueIfFalse.implicitWidening(valueIfTrueType, valueIfFalseType); -// this.resolvedType = valueIfTrueType; -// return valueIfTrueType; -// } -// if (valueIfTrueType.isCompatibleWith(valueIfFalseType)) { -// valueIfTrue.implicitWidening(valueIfFalseType, valueIfTrueType); -// valueIfFalse.implicitWidening(valueIfFalseType, valueIfFalseType); -// this.resolvedType = valueIfFalseType; -// return valueIfFalseType; -// } -// scope.problemReporter().conditionalArgumentsIncompatibleTypes( -// this, -// valueIfTrueType, -// valueIfFalseType); -// return null; -// } - public StringBuffer printExpressionNoParenthesis(int indent, StringBuffer output) { - + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * @param valueRequired + * boolean + */ + // public void generateCode( + // BlockScope currentScope, + // CodeStream codeStream, + // boolean valueRequired) { + // + // int pc = codeStream.position; + // Label endifLabel, falseLabel; + // if (constant != NotAConstant) { + // if (valueRequired) + // codeStream.generateConstant(constant, implicitConversion); + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // return; + // } + // Constant cst = condition.constant; + // Constant condCst = condition.optimizedBooleanConstant(); + // boolean needTruePart = + // !(((cst != NotAConstant) && (cst.booleanValue() == false)) + // || ((condCst != NotAConstant) && (condCst.booleanValue() == false))); + // boolean needFalsePart = + // !(((cst != NotAConstant) && (cst.booleanValue() == true)) + // || ((condCst != NotAConstant) && (condCst.booleanValue() == true))); + // endifLabel = new Label(codeStream); + // + // // Generate code for the condition + // boolean needConditionValue = (cst == NotAConstant) && (condCst == + // NotAConstant); + // condition.generateOptimizedBoolean( + // currentScope, + // codeStream, + // null, + // (falseLabel = new Label(codeStream)), + // needConditionValue); + // + // if (trueInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // trueInitStateIndex); + // codeStream.addDefinitelyAssignedVariables(currentScope, + // trueInitStateIndex); + // } + // // Then code generation + // if (needTruePart) { + // valueIfTrue.generateCode(currentScope, codeStream, valueRequired); + // if (needFalsePart) { + // // Jump over the else part + // int position = codeStream.position; + // codeStream.goto_(endifLabel); + // codeStream.updateLastRecordedEndPC(position); + // // Tune codestream stack size + // if (valueRequired) { + // codeStream.decrStackSize(returnTypeSlotSize); + // } + // } + // } + // if (needFalsePart) { + // falseLabel.place(); + // if (falseInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // falseInitStateIndex); + // codeStream.addDefinitelyAssignedVariables(currentScope, + // falseInitStateIndex); + // } + // valueIfFalse.generateCode(currentScope, codeStream, valueRequired); + // // End of if statement + // endifLabel.place(); + // } + // // May loose some local variable initializations : affecting the local + // variable attributes + // if (mergedInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // mergedInitStateIndex); + // } + // // implicit conversion + // if (valueRequired) + // codeStream.generateImplicitConversion(implicitConversion); + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } + // + // /** + // * Optimized boolean code generation for the conditional operator ?: + // */ + // public void generateOptimizedBoolean( + // BlockScope currentScope, + // CodeStream codeStream, + // Label trueLabel, + // Label falseLabel, + // boolean valueRequired) { + // + // if ((constant != Constant.NotAConstant) && (constant.typeID() == + // T_boolean) // constant + // || (valueIfTrue.implicitConversion >> 4) != T_boolean) { // non boolean + // values + // super.generateOptimizedBoolean(currentScope, codeStream, trueLabel, + // falseLabel, valueRequired); + // return; + // } + // Constant cst = condition.constant; + // Constant condCst = condition.optimizedBooleanConstant(); + // boolean needTruePart = + // !(((cst != NotAConstant) && (cst.booleanValue() == false)) + // || ((condCst != NotAConstant) && (condCst.booleanValue() == false))); + // boolean needFalsePart = + // !(((cst != NotAConstant) && (cst.booleanValue() == true)) + // || ((condCst != NotAConstant) && (condCst.booleanValue() == true))); + // + // Label internalFalseLabel, endifLabel = new Label(codeStream); + // + // // Generate code for the condition + // boolean needConditionValue = (cst == NotAConstant) && (condCst == + // NotAConstant); + // condition.generateOptimizedBoolean( + // currentScope, + // codeStream, + // null, + // internalFalseLabel = new Label(codeStream), + // needConditionValue); + // + // if (trueInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // trueInitStateIndex); + // codeStream.addDefinitelyAssignedVariables(currentScope, + // trueInitStateIndex); + // } + // // Then code generation + // if (needTruePart) { + // valueIfTrue.generateOptimizedBoolean(currentScope, codeStream, trueLabel, + // falseLabel, valueRequired); + // + // if (needFalsePart) { + // // Jump over the else part + // int position = codeStream.position; + // codeStream.goto_(endifLabel); + // codeStream.updateLastRecordedEndPC(position); + // // No need to decrement codestream stack size + // // since valueIfTrue was already consumed by branch bytecode + // } + // } + // if (needFalsePart) { + // internalFalseLabel.place(); + // if (falseInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // falseInitStateIndex); + // codeStream.addDefinitelyAssignedVariables(currentScope, + // falseInitStateIndex); + // } + // valueIfFalse.generateOptimizedBoolean(currentScope, codeStream, + // trueLabel, falseLabel, valueRequired); + // + // // End of if statement + // endifLabel.place(); + // } + // // May loose some local variable initializations : affecting the local + // variable attributes + // if (mergedInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // mergedInitStateIndex); + // } + // // no implicit conversion for boolean values + // codeStream.updateLastRecordedEndPC(codeStream.position); + // } + // + // public Constant optimizedBooleanConstant() { + // + // return this.optimizedBooleanConstant == null ? this.constant : + // this.optimizedBooleanConstant; + // } + // + // public TypeBinding resolveType(BlockScope scope) { + // // specs p.368 + // constant = NotAConstant; + // TypeBinding conditionType = condition.resolveTypeExpecting(scope, + // BooleanBinding); + // TypeBinding valueIfTrueType = valueIfTrue.resolveType(scope); + // TypeBinding valueIfFalseType = valueIfFalse.resolveType(scope); + // if (conditionType == null || valueIfTrueType == null || valueIfFalseType + // == null) + // return null; + // + // // Propagate the constant value from the valueIfTrue and valueIFFalse + // expression if it is possible + // Constant condConstant, trueConstant, falseConstant; + // if ((condConstant = condition.constant) != NotAConstant + // && (trueConstant = valueIfTrue.constant) != NotAConstant + // && (falseConstant = valueIfFalse.constant) != NotAConstant) { + // // all terms are constant expression so we can propagate the constant + // // from valueIFTrue or valueIfFalse to teh receiver constant + // constant = condConstant.booleanValue() ? trueConstant : falseConstant; + // } + // if (valueIfTrueType == valueIfFalseType) { // harmed the implicit + // conversion + // valueIfTrue.implicitWidening(valueIfTrueType, valueIfTrueType); + // valueIfFalse.implicitConversion = valueIfTrue.implicitConversion; + // if (valueIfTrueType == LongBinding || valueIfTrueType == DoubleBinding) { + // returnTypeSlotSize = 2; + // } + // + // if (valueIfTrueType == BooleanBinding) { + // this.optimizedIfTrueConstant = valueIfTrue.optimizedBooleanConstant(); + // this.optimizedIfFalseConstant = valueIfFalse.optimizedBooleanConstant(); + // + // // Propagate the optimized boolean constant if possible + // if ((condConstant = condition.optimizedBooleanConstant()) != + // NotAConstant) { + // + // this.optimizedBooleanConstant = condConstant.booleanValue() + // ? optimizedIfTrueConstant + // : optimizedIfFalseConstant; + // } + // } + // return this.resolvedType = valueIfTrueType; + // } + // // Determine the return type depending on argument types + // // Numeric types + // if (valueIfTrueType.isNumericType() && valueIfFalseType.isNumericType()) + // { + // // (Short x Byte) or (Byte x Short)" + // if ((valueIfTrueType == ByteBinding && valueIfFalseType == ShortBinding) + // || (valueIfTrueType == ShortBinding && valueIfFalseType == ByteBinding)) + // { + // valueIfTrue.implicitWidening(ShortBinding, valueIfTrueType); + // valueIfFalse.implicitWidening(ShortBinding, valueIfFalseType); + // this.resolvedType = ShortBinding; + // return ShortBinding; + // } + // // x constant(Int) ---> and + // reciprocally + // if ((valueIfTrueType == ByteBinding || valueIfTrueType == ShortBinding || + // valueIfTrueType == CharBinding) + // && (valueIfFalseType == IntBinding + // && valueIfFalse.isConstantValueOfTypeAssignableToType(valueIfFalseType, + // valueIfTrueType))) { + // valueIfTrue.implicitWidening(valueIfTrueType, valueIfTrueType); + // valueIfFalse.implicitWidening(valueIfTrueType, valueIfFalseType); + // this.resolvedType = valueIfTrueType; + // return valueIfTrueType; + // } + // if ((valueIfFalseType == ByteBinding + // || valueIfFalseType == ShortBinding + // || valueIfFalseType == CharBinding) + // && (valueIfTrueType == IntBinding + // && valueIfTrue.isConstantValueOfTypeAssignableToType(valueIfTrueType, + // valueIfFalseType))) { + // valueIfTrue.implicitWidening(valueIfFalseType, valueIfTrueType); + // valueIfFalse.implicitWidening(valueIfFalseType, valueIfFalseType); + // this.resolvedType = valueIfFalseType; + // return valueIfFalseType; + // } + // // Manual binary numeric promotion + // // int + // if (BaseTypeBinding.isNarrowing(valueIfTrueType.id, T_int) + // && BaseTypeBinding.isNarrowing(valueIfFalseType.id, T_int)) { + // valueIfTrue.implicitWidening(IntBinding, valueIfTrueType); + // valueIfFalse.implicitWidening(IntBinding, valueIfFalseType); + // this.resolvedType = IntBinding; + // return IntBinding; + // } + // // long + // if (BaseTypeBinding.isNarrowing(valueIfTrueType.id, T_long) + // && BaseTypeBinding.isNarrowing(valueIfFalseType.id, T_long)) { + // valueIfTrue.implicitWidening(LongBinding, valueIfTrueType); + // valueIfFalse.implicitWidening(LongBinding, valueIfFalseType); + // returnTypeSlotSize = 2; + // this.resolvedType = LongBinding; + // return LongBinding; + // } + // // float + // if (BaseTypeBinding.isNarrowing(valueIfTrueType.id, T_float) + // && BaseTypeBinding.isNarrowing(valueIfFalseType.id, T_float)) { + // valueIfTrue.implicitWidening(FloatBinding, valueIfTrueType); + // valueIfFalse.implicitWidening(FloatBinding, valueIfFalseType); + // this.resolvedType = FloatBinding; + // return FloatBinding; + // } + // // double + // valueIfTrue.implicitWidening(DoubleBinding, valueIfTrueType); + // valueIfFalse.implicitWidening(DoubleBinding, valueIfFalseType); + // returnTypeSlotSize = 2; + // this.resolvedType = DoubleBinding; + // return DoubleBinding; + // } + // // Type references (null null is already tested) + // if ((valueIfTrueType.isBaseType() && valueIfTrueType != NullBinding) + // || (valueIfFalseType.isBaseType() && valueIfFalseType != NullBinding)) { + // scope.problemReporter().conditionalArgumentsIncompatibleTypes( + // this, + // valueIfTrueType, + // valueIfFalseType); + // return null; + // } + // if (valueIfFalseType.isCompatibleWith(valueIfTrueType)) { + // valueIfTrue.implicitWidening(valueIfTrueType, valueIfTrueType); + // valueIfFalse.implicitWidening(valueIfTrueType, valueIfFalseType); + // this.resolvedType = valueIfTrueType; + // return valueIfTrueType; + // } + // if (valueIfTrueType.isCompatibleWith(valueIfFalseType)) { + // valueIfTrue.implicitWidening(valueIfFalseType, valueIfTrueType); + // valueIfFalse.implicitWidening(valueIfFalseType, valueIfFalseType); + // this.resolvedType = valueIfFalseType; + // return valueIfFalseType; + // } + // scope.problemReporter().conditionalArgumentsIncompatibleTypes( + // this, + // valueIfTrueType, + // valueIfFalseType); + // return null; + // } + public StringBuffer printExpressionNoParenthesis(int indent, + StringBuffer output) { + condition.printExpression(indent, output).append(" ? "); //$NON-NLS-1$ valueIfTrue.printExpression(0, output).append(" : "); //$NON-NLS-1$ return valueIfFalse.printExpression(0, output); } + public String toStringExpressionNoParenthesis() { return condition.toStringExpression() + " ? " + //$NON-NLS-1$ - valueIfTrue.toStringExpression() + " : " + //$NON-NLS-1$ - valueIfFalse.toStringExpression(); + valueIfTrue.toStringExpression() + " : " + //$NON-NLS-1$ + valueIfFalse.toStringExpression(); } public void traverse(ASTVisitor visitor, BlockScope scope) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ConstructorDeclaration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ConstructorDeclaration.java index 0bf4ad0..e43ddcb 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ConstructorDeclaration.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ConstructorDeclaration.java @@ -24,66 +24,66 @@ import net.sourceforge.phpdt.internal.compiler.lookup.ReferenceBinding; import net.sourceforge.phpdt.internal.compiler.parser.UnitParser; import net.sourceforge.phpdt.internal.compiler.problem.AbortMethod; - public class ConstructorDeclaration extends AbstractMethodDeclaration { public ExplicitConstructorCall constructorCall; + public final static char[] ConstantPoolName = "".toCharArray(); //$NON-NLS-1$ + public boolean isDefaultConstructor = false; - public ConstructorDeclaration(CompilationResult compilationResult){ + public ConstructorDeclaration(CompilationResult compilationResult) { super(compilationResult); } - - public void analyseCode( - ClassScope classScope, - InitializationFlowContext initializerFlowContext, - FlowInfo flowInfo) { + + public void analyseCode(ClassScope classScope, + InitializationFlowContext initializerFlowContext, FlowInfo flowInfo) { if (ignoreFurtherInvestigation) return; - if (this.binding != null && this.binding.isPrivate() && !this.binding.isPrivateUsed()) { - if (!classScope.referenceCompilationUnit().compilationResult.hasSyntaxError()) { + if (this.binding != null && this.binding.isPrivate() + && !this.binding.isPrivateUsed()) { + if (!classScope.referenceCompilationUnit().compilationResult + .hasSyntaxError()) { scope.problemReporter().unusedPrivateConstructor(this); } } - + // check constructor recursion, once all constructor got resolved - if (isRecursive(null /*lazy initialized visited list*/)) { - this.scope.problemReporter().recursiveConstructorInvocation(this.constructorCall); + if (isRecursive(null /* lazy initialized visited list */)) { + this.scope.problemReporter().recursiveConstructorInvocation( + this.constructorCall); } - + try { - ExceptionHandlingFlowContext constructorContext = - new ExceptionHandlingFlowContext( - initializerFlowContext.parent, - this, - binding.thrownExceptions, - scope, - FlowInfo.DEAD_END); - initializerFlowContext.checkInitializerExceptions( - scope, - constructorContext, - flowInfo); - - // anonymous constructor can gain extra thrown exceptions from unhandled ones + ExceptionHandlingFlowContext constructorContext = new ExceptionHandlingFlowContext( + initializerFlowContext.parent, this, + binding.thrownExceptions, scope, FlowInfo.DEAD_END); + initializerFlowContext.checkInitializerExceptions(scope, + constructorContext, flowInfo); + + // anonymous constructor can gain extra thrown exceptions from + // unhandled ones if (binding.declaringClass.isAnonymousType()) { ArrayList computedExceptions = constructorContext.extendedExceptions; - if (computedExceptions != null){ + if (computedExceptions != null) { int size; - if ((size = computedExceptions.size()) > 0){ + if ((size = computedExceptions.size()) > 0) { ReferenceBinding[] actuallyThrownExceptions; - computedExceptions.toArray(actuallyThrownExceptions = new ReferenceBinding[size]); + computedExceptions + .toArray(actuallyThrownExceptions = new ReferenceBinding[size]); binding.thrownExceptions = actuallyThrownExceptions; } } } - + // propagate to constructor call if (constructorCall != null) { - // if calling 'this(...)', then flag all non-static fields as definitely - // set since they are supposed to be set inside other local constructor + // if calling 'this(...)', then flag all non-static fields as + // definitely + // set since they are supposed to be set inside other local + // constructor if (constructorCall.accessMode == ExplicitConstructorCall.This) { FieldBinding[] fields = binding.declaringClass.fields(); for (int i = 0, count = fields.length; i < count; i++) { @@ -93,15 +93,18 @@ public class ConstructorDeclaration extends AbstractMethodDeclaration { } } } - flowInfo = constructorCall.analyseCode(scope, constructorContext, flowInfo); + flowInfo = constructorCall.analyseCode(scope, + constructorContext, flowInfo); } // propagate to statements if (statements != null) { boolean didAlreadyComplain = false; for (int i = 0, count = statements.length; i < count; i++) { Statement stat; - if (!flowInfo.complainIfUnreachable(stat = statements[i], scope, didAlreadyComplain)) { - flowInfo = stat.analyseCode(scope, constructorContext, flowInfo); + if (!flowInfo.complainIfUnreachable(stat = statements[i], + scope, didAlreadyComplain)) { + flowInfo = stat.analyseCode(scope, constructorContext, + flowInfo); } else { didAlreadyComplain = true; } @@ -112,17 +115,18 @@ public class ConstructorDeclaration extends AbstractMethodDeclaration { // check missing blank final field initializations if ((constructorCall != null) - && (constructorCall.accessMode != ExplicitConstructorCall.This)) { - flowInfo = flowInfo.mergedWith(constructorContext.initsOnReturn); + && (constructorCall.accessMode != ExplicitConstructorCall.This)) { + flowInfo = flowInfo + .mergedWith(constructorContext.initsOnReturn); FieldBinding[] fields = binding.declaringClass.fields(); for (int i = 0, count = fields.length; i < count; i++) { FieldBinding field; - if ((!(field = fields[i]).isStatic()) - && field.isFinal() - && (!flowInfo.isDefinitelyAssigned(fields[i]))) { + if ((!(field = fields[i]).isStatic()) && field.isFinal() + && (!flowInfo.isDefinitelyAssigned(fields[i]))) { scope.problemReporter().uninitializedBlankFinalField( - field, - isDefaultConstructor ? (ASTNode) scope.referenceType() : this); + field, + isDefaultConstructor ? (ASTNode) scope + .referenceType() : this); } } } @@ -133,185 +137,205 @@ public class ConstructorDeclaration extends AbstractMethodDeclaration { /** * Bytecode generation for a constructor - * - * @param classScope net.sourceforge.phpdt.internal.compiler.lookup.ClassScope - * @param classFile net.sourceforge.phpdt.internal.compiler.codegen.ClassFile + * + * @param classScope + * net.sourceforge.phpdt.internal.compiler.lookup.ClassScope + * @param classFile + * net.sourceforge.phpdt.internal.compiler.codegen.ClassFile */ -// public void generateCode(ClassScope classScope, ClassFile classFile) { -// -// int problemResetPC = 0; -// if (ignoreFurtherInvestigation) { -// if (this.binding == null) -// return; // Handle methods with invalid signature or duplicates -// int problemsLength; -// IProblem[] problems = -// scope.referenceCompilationUnit().compilationResult.getProblems(); -// IProblem[] problemsCopy = new IProblem[problemsLength = problems.length]; -// System.arraycopy(problems, 0, problemsCopy, 0, problemsLength); -// classFile.addProblemConstructor(this, binding, problemsCopy); -// return; -// } -// try { -// problemResetPC = classFile.contentsOffset; -// this.internalGenerateCode(classScope, classFile); -// } catch (AbortMethod e) { -// if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) { -// // a branch target required a goto_w, restart code gen in wide mode. -// try { -// if (statements != null) { -// for (int i = 0, max = statements.length; i < max; i++) -// statements[i].resetStateForCodeGeneration(); -// } -// classFile.contentsOffset = problemResetPC; -// classFile.methodCount--; -// classFile.codeStream.wideMode = true; // request wide mode -// this.internalGenerateCode(classScope, classFile); // restart method generation -// } catch (AbortMethod e2) { -// int problemsLength; -// IProblem[] problems = -// scope.referenceCompilationUnit().compilationResult.getAllProblems(); -// IProblem[] problemsCopy = new IProblem[problemsLength = problems.length]; -// System.arraycopy(problems, 0, problemsCopy, 0, problemsLength); -// classFile.addProblemConstructor(this, binding, problemsCopy, problemResetPC); -// } -// } else { -// int problemsLength; -// IProblem[] problems = -// scope.referenceCompilationUnit().compilationResult.getAllProblems(); -// IProblem[] problemsCopy = new IProblem[problemsLength = problems.length]; -// System.arraycopy(problems, 0, problemsCopy, 0, problemsLength); -// classFile.addProblemConstructor(this, binding, problemsCopy, problemResetPC); -// } -// } -// } -// -// public void generateSyntheticFieldInitializationsIfNecessary( -// MethodScope scope, -// CodeStream codeStream, -// ReferenceBinding declaringClass) { -// -// if (!declaringClass.isNestedType()) return; -// -// NestedTypeBinding nestedType = (NestedTypeBinding) declaringClass; -// -// SyntheticArgumentBinding[] syntheticArgs = nestedType.syntheticEnclosingInstances(); -// for (int i = 0, max = syntheticArgs == null ? 0 : syntheticArgs.length; i < max; i++) { -// SyntheticArgumentBinding syntheticArg; -// if ((syntheticArg = syntheticArgs[i]).matchingField != null) { -// codeStream.aload_0(); -// codeStream.load(syntheticArg); -// codeStream.putfield(syntheticArg.matchingField); -// } -// } -// syntheticArgs = nestedType.syntheticOuterLocalVariables(); -// for (int i = 0, max = syntheticArgs == null ? 0 : syntheticArgs.length; i < max; i++) { -// SyntheticArgumentBinding syntheticArg; -// if ((syntheticArg = syntheticArgs[i]).matchingField != null) { -// codeStream.aload_0(); -// codeStream.load(syntheticArg); -// codeStream.putfield(syntheticArg.matchingField); -// } -// } -// } -// -// private void internalGenerateCode(ClassScope classScope, ClassFile classFile) { -// -// classFile.generateMethodInfoHeader(binding); -// int methodAttributeOffset = classFile.contentsOffset; -// int attributeNumber = classFile.generateMethodInfoAttribute(binding); -// if ((!binding.isNative()) && (!binding.isAbstract())) { -// -// TypeDeclaration declaringType = classScope.referenceContext; -// int codeAttributeOffset = classFile.contentsOffset; -// classFile.generateCodeAttributeHeader(); -// CodeStream codeStream = classFile.codeStream; -// codeStream.reset(this, classFile); -// -// // initialize local positions - including initializer scope. -// ReferenceBinding declaringClass = binding.declaringClass; -// -// int argSlotSize = 1; // this==aload0 -// -// if (declaringClass.isNestedType()){ -// NestedTypeBinding nestedType = (NestedTypeBinding) declaringClass; -// this.scope.extraSyntheticArguments = nestedType.syntheticOuterLocalVariables(); -// scope.computeLocalVariablePositions(// consider synthetic arguments if any -// nestedType.enclosingInstancesSlotSize + 1, -// codeStream); -// argSlotSize += nestedType.enclosingInstancesSlotSize; -// argSlotSize += nestedType.outerLocalVariablesSlotSize; -// } else { -// scope.computeLocalVariablePositions(1, codeStream); -// } -// -// if (arguments != null) { -// for (int i = 0, max = arguments.length; i < max; i++) { -// // arguments initialization for local variable debug attributes -// LocalVariableBinding argBinding; -// codeStream.addVisibleLocalVariable(argBinding = arguments[i].binding); -// argBinding.recordInitializationStartPC(0); -// TypeBinding argType; -// if ((argType = argBinding.type) == LongBinding || (argType == DoubleBinding)) { -// argSlotSize += 2; -// } else { -// argSlotSize++; -// } -// } -// } -// -// MethodScope initializerScope = declaringType.initializerScope; -// initializerScope.computeLocalVariablePositions(argSlotSize, codeStream); // offset by the argument size (since not linked to method scope) -// -// boolean needFieldInitializations = constructorCall == null || constructorCall.accessMode != ExplicitConstructorCall.This; -// -// // post 1.4 source level, synthetic initializations occur prior to explicit constructor call -// boolean preInitSyntheticFields = scope.environment().options.targetJDK >= CompilerOptions.JDK1_4; -// -// if (needFieldInitializations && preInitSyntheticFields){ -// generateSyntheticFieldInitializationsIfNecessary(scope, codeStream, declaringClass); -// } -// // generate constructor call -// if (constructorCall != null) { -// constructorCall.generateCode(scope, codeStream); -// } -// // generate field initialization - only if not invoking another constructor call of the same class -// if (needFieldInitializations) { -// if (!preInitSyntheticFields){ -// generateSyntheticFieldInitializationsIfNecessary(scope, codeStream, declaringClass); -// } -// // generate user field initialization -// if (declaringType.fields != null) { -// for (int i = 0, max = declaringType.fields.length; i < max; i++) { -// FieldDeclaration fieldDecl; -// if (!(fieldDecl = declaringType.fields[i]).isStatic()) { -// fieldDecl.generateCode(initializerScope, codeStream); -// } -// } -// } -// } -// // generate statements -// if (statements != null) { -// for (int i = 0, max = statements.length; i < max; i++) { -// statements[i].generateCode(scope, codeStream); -// } -// } -// if (this.needFreeReturn) { -// codeStream.return_(); -// } -// // local variable attributes -// codeStream.exitUserScope(scope); -// codeStream.recordPositionsFrom(0, this.bodyEnd); -// classFile.completeCodeAttribute(codeAttributeOffset); -// attributeNumber++; -// } -// classFile.completeMethodInfo(methodAttributeOffset, attributeNumber); -// -// // if a problem got reported during code gen, then trigger problem method creation -// if (ignoreFurtherInvestigation) { -// throw new AbortMethod(scope.referenceCompilationUnit().compilationResult); -// } -// } - + // public void generateCode(ClassScope classScope, ClassFile classFile) { + // + // int problemResetPC = 0; + // if (ignoreFurtherInvestigation) { + // if (this.binding == null) + // return; // Handle methods with invalid signature or duplicates + // int problemsLength; + // IProblem[] problems = + // scope.referenceCompilationUnit().compilationResult.getProblems(); + // IProblem[] problemsCopy = new IProblem[problemsLength = problems.length]; + // System.arraycopy(problems, 0, problemsCopy, 0, problemsLength); + // classFile.addProblemConstructor(this, binding, problemsCopy); + // return; + // } + // try { + // problemResetPC = classFile.contentsOffset; + // this.internalGenerateCode(classScope, classFile); + // } catch (AbortMethod e) { + // if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) { + // // a branch target required a goto_w, restart code gen in wide mode. + // try { + // if (statements != null) { + // for (int i = 0, max = statements.length; i < max; i++) + // statements[i].resetStateForCodeGeneration(); + // } + // classFile.contentsOffset = problemResetPC; + // classFile.methodCount--; + // classFile.codeStream.wideMode = true; // request wide mode + // this.internalGenerateCode(classScope, classFile); // restart method + // generation + // } catch (AbortMethod e2) { + // int problemsLength; + // IProblem[] problems = + // scope.referenceCompilationUnit().compilationResult.getAllProblems(); + // IProblem[] problemsCopy = new IProblem[problemsLength = problems.length]; + // System.arraycopy(problems, 0, problemsCopy, 0, problemsLength); + // classFile.addProblemConstructor(this, binding, problemsCopy, + // problemResetPC); + // } + // } else { + // int problemsLength; + // IProblem[] problems = + // scope.referenceCompilationUnit().compilationResult.getAllProblems(); + // IProblem[] problemsCopy = new IProblem[problemsLength = problems.length]; + // System.arraycopy(problems, 0, problemsCopy, 0, problemsLength); + // classFile.addProblemConstructor(this, binding, problemsCopy, + // problemResetPC); + // } + // } + // } + // + // public void generateSyntheticFieldInitializationsIfNecessary( + // MethodScope scope, + // CodeStream codeStream, + // ReferenceBinding declaringClass) { + // + // if (!declaringClass.isNestedType()) return; + // + // NestedTypeBinding nestedType = (NestedTypeBinding) declaringClass; + // + // SyntheticArgumentBinding[] syntheticArgs = + // nestedType.syntheticEnclosingInstances(); + // for (int i = 0, max = syntheticArgs == null ? 0 : syntheticArgs.length; i + // < max; i++) { + // SyntheticArgumentBinding syntheticArg; + // if ((syntheticArg = syntheticArgs[i]).matchingField != null) { + // codeStream.aload_0(); + // codeStream.load(syntheticArg); + // codeStream.putfield(syntheticArg.matchingField); + // } + // } + // syntheticArgs = nestedType.syntheticOuterLocalVariables(); + // for (int i = 0, max = syntheticArgs == null ? 0 : syntheticArgs.length; i + // < max; i++) { + // SyntheticArgumentBinding syntheticArg; + // if ((syntheticArg = syntheticArgs[i]).matchingField != null) { + // codeStream.aload_0(); + // codeStream.load(syntheticArg); + // codeStream.putfield(syntheticArg.matchingField); + // } + // } + // } + // + // private void internalGenerateCode(ClassScope classScope, ClassFile + // classFile) { + // + // classFile.generateMethodInfoHeader(binding); + // int methodAttributeOffset = classFile.contentsOffset; + // int attributeNumber = classFile.generateMethodInfoAttribute(binding); + // if ((!binding.isNative()) && (!binding.isAbstract())) { + // + // TypeDeclaration declaringType = classScope.referenceContext; + // int codeAttributeOffset = classFile.contentsOffset; + // classFile.generateCodeAttributeHeader(); + // CodeStream codeStream = classFile.codeStream; + // codeStream.reset(this, classFile); + // + // // initialize local positions - including initializer scope. + // ReferenceBinding declaringClass = binding.declaringClass; + // + // int argSlotSize = 1; // this==aload0 + // + // if (declaringClass.isNestedType()){ + // NestedTypeBinding nestedType = (NestedTypeBinding) declaringClass; + // this.scope.extraSyntheticArguments = + // nestedType.syntheticOuterLocalVariables(); + // scope.computeLocalVariablePositions(// consider synthetic arguments if + // any + // nestedType.enclosingInstancesSlotSize + 1, + // codeStream); + // argSlotSize += nestedType.enclosingInstancesSlotSize; + // argSlotSize += nestedType.outerLocalVariablesSlotSize; + // } else { + // scope.computeLocalVariablePositions(1, codeStream); + // } + // + // if (arguments != null) { + // for (int i = 0, max = arguments.length; i < max; i++) { + // // arguments initialization for local variable debug attributes + // LocalVariableBinding argBinding; + // codeStream.addVisibleLocalVariable(argBinding = arguments[i].binding); + // argBinding.recordInitializationStartPC(0); + // TypeBinding argType; + // if ((argType = argBinding.type) == LongBinding || (argType == + // DoubleBinding)) { + // argSlotSize += 2; + // } else { + // argSlotSize++; + // } + // } + // } + // + // MethodScope initializerScope = declaringType.initializerScope; + // initializerScope.computeLocalVariablePositions(argSlotSize, codeStream); + // // offset by the argument size (since not linked to method scope) + // + // boolean needFieldInitializations = constructorCall == null || + // constructorCall.accessMode != ExplicitConstructorCall.This; + // + // // post 1.4 source level, synthetic initializations occur prior to + // explicit constructor call + // boolean preInitSyntheticFields = scope.environment().options.targetJDK >= + // CompilerOptions.JDK1_4; + // + // if (needFieldInitializations && preInitSyntheticFields){ + // generateSyntheticFieldInitializationsIfNecessary(scope, codeStream, + // declaringClass); + // } + // // generate constructor call + // if (constructorCall != null) { + // constructorCall.generateCode(scope, codeStream); + // } + // // generate field initialization - only if not invoking another + // constructor call of the same class + // if (needFieldInitializations) { + // if (!preInitSyntheticFields){ + // generateSyntheticFieldInitializationsIfNecessary(scope, codeStream, + // declaringClass); + // } + // // generate user field initialization + // if (declaringType.fields != null) { + // for (int i = 0, max = declaringType.fields.length; i < max; i++) { + // FieldDeclaration fieldDecl; + // if (!(fieldDecl = declaringType.fields[i]).isStatic()) { + // fieldDecl.generateCode(initializerScope, codeStream); + // } + // } + // } + // } + // // generate statements + // if (statements != null) { + // for (int i = 0, max = statements.length; i < max; i++) { + // statements[i].generateCode(scope, codeStream); + // } + // } + // if (this.needFreeReturn) { + // codeStream.return_(); + // } + // // local variable attributes + // codeStream.exitUserScope(scope); + // codeStream.recordPositionsFrom(0, this.bodyEnd); + // classFile.completeCodeAttribute(codeAttributeOffset); + // attributeNumber++; + // } + // classFile.completeMethodInfo(methodAttributeOffset, attributeNumber); + // + // // if a problem got reported during code gen, then trigger problem method + // creation + // if (ignoreFurtherInvestigation) { + // throw new + // AbortMethod(scope.referenceCompilationUnit().compilationResult); + // } + // } public boolean isConstructor() { return true; @@ -328,44 +352,45 @@ public class ConstructorDeclaration extends AbstractMethodDeclaration { } /** - * Returns true if the constructor is directly involved in a cycle. - * Given most constructors aren't, we only allocate the visited list - * lazily. + * Returns true if the constructor is directly involved in a cycle. Given + * most constructors aren't, we only allocate the visited list lazily. */ public boolean isRecursive(ArrayList visited) { - if (this.binding == null - || this.constructorCall == null + if (this.binding == null || this.constructorCall == null || this.constructorCall.binding == null || this.constructorCall.isSuperAccess() || !this.constructorCall.binding.isValidBinding()) { return false; } - - ConstructorDeclaration targetConstructor = - ((ConstructorDeclaration)this.scope.referenceType().declarationOf(constructorCall.binding)); - if (this == targetConstructor) return true; // direct case + + ConstructorDeclaration targetConstructor = ((ConstructorDeclaration) this.scope + .referenceType().declarationOf(constructorCall.binding)); + if (this == targetConstructor) + return true; // direct case if (visited == null) { // lazy allocation visited = new ArrayList(1); } else { int index = visited.indexOf(this); - if (index >= 0) return index == 0; // only blame if directly part of the cycle + if (index >= 0) + return index == 0; // only blame if directly part of the cycle } visited.add(this); return targetConstructor.isRecursive(visited); } - - public void parseStatements(UnitParser parser, CompilationUnitDeclaration unit) { - //fill up the constructor body with its statements + public void parseStatements(UnitParser parser, + CompilationUnitDeclaration unit) { + + // fill up the constructor body with its statements if (ignoreFurtherInvestigation) return; - if (isDefaultConstructor){ + if (isDefaultConstructor) { constructorCall = SuperReference.implicitSuperConstructorCall(); constructorCall.sourceStart = sourceStart; - constructorCall.sourceEnd = sourceEnd; + constructorCall.sourceEnd = sourceEnd; return; } parser.parse(this, unit); @@ -373,12 +398,13 @@ public class ConstructorDeclaration extends AbstractMethodDeclaration { } /* - * Type checking for constructor, just another method, except for special check - * for recursive constructor invocations. + * Type checking for constructor, just another method, except for special + * check for recursive constructor invocations. */ public void resolveStatements() { - if (!CharOperation.equals(scope.enclosingSourceType().sourceName, selector)){ + if (!CharOperation.equals(scope.enclosingSourceType().sourceName, + selector)) { scope.problemReporter().missingReturnType(this); } @@ -386,17 +412,18 @@ public class ConstructorDeclaration extends AbstractMethodDeclaration { if (this.constructorCall != null) { // e.g. using super() in java.lang.Object if (this.binding != null - && this.binding.declaringClass.id == T_Object - && this.constructorCall.accessMode != ExplicitConstructorCall.This) { - if (this.constructorCall.accessMode == ExplicitConstructorCall.Super) { - scope.problemReporter().cannotUseSuperInJavaLangObject(this.constructorCall); - } - this.constructorCall = null; + && this.binding.declaringClass.id == T_Object + && this.constructorCall.accessMode != ExplicitConstructorCall.This) { + if (this.constructorCall.accessMode == ExplicitConstructorCall.Super) { + scope.problemReporter().cannotUseSuperInJavaLangObject( + this.constructorCall); + } + this.constructorCall = null; } else { this.constructorCall.resolve(this.scope); } } - + super.resolveStatements(); } @@ -419,9 +446,7 @@ public class ConstructorDeclaration extends AbstractMethodDeclaration { return s; } - public void traverse( - ASTVisitor visitor, - ClassScope classScope) { + public void traverse(ASTVisitor visitor, ClassScope classScope) { if (visitor.visit(this, classScope)) { if (arguments != null) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ContinueStatement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ContinueStatement.java index 7498fd8..9628874 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ContinueStatement.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ContinueStatement.java @@ -18,77 +18,87 @@ import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; public class ContinueStatement extends BranchStatement { public ContinueStatement(Expression expr, int s, int e) { - + super(expr, s, e); } - - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { - // here requires to generate a sequence of finally blocks invocations depending corresponding - // to each of the traversed try statements, so that execution will terminate properly. + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { + + // here requires to generate a sequence of finally blocks invocations + // depending corresponding + // to each of the traversed try statements, so that execution will + // terminate properly. // lookup the label, this should answer the returnContext -// FlowContext targetContext = (expression == null) -// ? flowContext.getTargetContextForDefaultContinue() -// : flowContext.getTargetContextForContinueLabel(label); + // FlowContext targetContext = (expression == null) + // ? flowContext.getTargetContextForDefaultContinue() + // : flowContext.getTargetContextForContinueLabel(label); -// if (targetContext == null) { -// if (expression == null) { -// currentScope.problemReporter().invalidContinue(this); -// } else { -// currentScope.problemReporter().undefinedLabel(this); -// } -// return flowInfo; // pretend it did not continue since no actual target -// } + // if (targetContext == null) { + // if (expression == null) { + // currentScope.problemReporter().invalidContinue(this); + // } else { + // currentScope.problemReporter().undefinedLabel(this); + // } + // return flowInfo; // pretend it did not continue since no actual + // target + // } -// if (targetContext == FlowContext.NotContinuableContext) { -// currentScope.problemReporter().invalidContinue(this); -// return flowInfo; // pretend it did not continue since no actual target -// } -// targetLabel = targetContext.continueLabel(); -// FlowContext traversedContext = flowContext; -// int subIndex = 0, maxSub = 5; -// subroutines = new ASTNode[maxSub]; -// -// do { -// ASTNode sub; -// if ((sub = traversedContext.subRoutine()) != null) { -// if (subIndex == maxSub) { -// System.arraycopy(subroutines, 0, (subroutines = new ASTNode[maxSub*=2]), 0, subIndex); // grow -// } -// subroutines[subIndex++] = sub; -// if (sub.cannotReturn()) { -// break; -// } -// } -// traversedContext.recordReturnFrom(flowInfo.unconditionalInits()); -// -// ASTNode node; -// if ((node = traversedContext.associatedNode) instanceof TryStatement) { -// TryStatement tryStatement = (TryStatement) node; -// flowInfo.addInitializationsFrom(tryStatement.subRoutineInits); // collect inits -// } else if (traversedContext == targetContext) { -// // only record continue info once accumulated through subroutines, and only against target context -// targetContext.recordContinueFrom(flowInfo); -// break; -// } -// } while ((traversedContext = traversedContext.parent) != null); -// -// // resize subroutines -// if (subIndex != maxSub) { -// System.arraycopy(subroutines, 0, (subroutines = new ASTNode[subIndex]), 0, subIndex); -// } + // if (targetContext == FlowContext.NotContinuableContext) { + // currentScope.problemReporter().invalidContinue(this); + // return flowInfo; // pretend it did not continue since no actual + // target + // } + // targetLabel = targetContext.continueLabel(); + // FlowContext traversedContext = flowContext; + // int subIndex = 0, maxSub = 5; + // subroutines = new ASTNode[maxSub]; + // + // do { + // ASTNode sub; + // if ((sub = traversedContext.subRoutine()) != null) { + // if (subIndex == maxSub) { + // System.arraycopy(subroutines, 0, (subroutines = new + // ASTNode[maxSub*=2]), 0, subIndex); // grow + // } + // subroutines[subIndex++] = sub; + // if (sub.cannotReturn()) { + // break; + // } + // } + // traversedContext.recordReturnFrom(flowInfo.unconditionalInits()); + // + // ASTNode node; + // if ((node = traversedContext.associatedNode) instanceof TryStatement) + // { + // TryStatement tryStatement = (TryStatement) node; + // flowInfo.addInitializationsFrom(tryStatement.subRoutineInits); // + // collect inits + // } else if (traversedContext == targetContext) { + // // only record continue info once accumulated through subroutines, + // and only against target context + // targetContext.recordContinueFrom(flowInfo); + // break; + // } + // } while ((traversedContext = traversedContext.parent) != null); + // + // // resize subroutines + // if (subIndex != maxSub) { + // System.arraycopy(subroutines, 0, (subroutines = new + // ASTNode[subIndex]), 0, subIndex); + // } return FlowInfo.DEAD_END; } + public StringBuffer printStatement(int tab, StringBuffer output) { printIndent(tab, output).append("continue "); //$NON-NLS-1$ - if (expression != null) output.append(expression); + if (expression != null) + output.append(expression); return output.append(';'); } + public String toString(int tab) { String s = tabString(tab); @@ -98,9 +108,8 @@ public class ContinueStatement extends BranchStatement { return s; } - public void traverse( - IAbstractSyntaxTreeVisitor visitor, - BlockScope blockScope) { + public void traverse(IAbstractSyntaxTreeVisitor visitor, + BlockScope blockScope) { visitor.visit(this, blockScope); visitor.endVisit(this, blockScope); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/DefaultCase.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/DefaultCase.java index 587f248..601562d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/DefaultCase.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/DefaultCase.java @@ -17,75 +17,80 @@ import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class DefaultCase extends Statement { - public CaseLabel targetLabel; - - /** - * DefautCase constructor comment. - */ - public DefaultCase(int sourceEnd, int sourceStart) { - - this.sourceStart = sourceStart; - this.sourceEnd = sourceEnd; - } - - public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { - - return flowInfo; - } - - /** - * Default case code generation - * - * @param currentScope - * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream - * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream - */ - // public void generateCode(BlockScope currentScope, CodeStream codeStream) { - // - // if ((bits & IsReachableMASK) == 0) { - // return; - // } - // int pc = codeStream.position; - // targetLabel.place(); - // codeStream.recordPositionsFrom(pc, this.sourceStart); - // - // } - /** - * No-op : should use resolveCase(...) instead. - */ - public void resolve(BlockScope scope) { - } - - public Constant resolveCase(BlockScope scope, TypeBinding testType, SwitchStatement switchStatement) { - - // remember the default case into the associated switch statement - if (switchStatement.defaultCase != null) - scope.problemReporter().duplicateDefaultCase(this); - - // on error the last default will be the selected one .... (why not) .... - switchStatement.defaultCase = this; - resolve(scope); - return null; - } - - public StringBuffer printStatement(int tab, StringBuffer output) { - - printIndent(tab, output); - output.append("default : "); //$NON-NLS-1$ - return output.append(';'); - } - - public String toString(int tab) { - - String s = tabString(tab); - s = s + "default : "; //$NON-NLS-1$ - return s; - } - - public void traverse(IAbstractSyntaxTreeVisitor visitor, BlockScope blockScope) { - - visitor.visit(this, blockScope); - visitor.endVisit(this, blockScope); - } + public CaseLabel targetLabel; + + /** + * DefautCase constructor comment. + */ + public DefaultCase(int sourceEnd, int sourceStart) { + + this.sourceStart = sourceStart; + this.sourceEnd = sourceEnd; + } + + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { + + return flowInfo; + } + + /** + * Default case code generation + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + */ + // public void generateCode(BlockScope currentScope, CodeStream codeStream) + // { + // + // if ((bits & IsReachableMASK) == 0) { + // return; + // } + // int pc = codeStream.position; + // targetLabel.place(); + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // + // } + /** + * No-op : should use resolveCase(...) instead. + */ + public void resolve(BlockScope scope) { + } + + public Constant resolveCase(BlockScope scope, TypeBinding testType, + SwitchStatement switchStatement) { + + // remember the default case into the associated switch statement + if (switchStatement.defaultCase != null) + scope.problemReporter().duplicateDefaultCase(this); + + // on error the last default will be the selected one .... (why not) + // .... + switchStatement.defaultCase = this; + resolve(scope); + return null; + } + + public StringBuffer printStatement(int tab, StringBuffer output) { + + printIndent(tab, output); + output.append("default : "); //$NON-NLS-1$ + return output.append(';'); + } + + public String toString(int tab) { + + String s = tabString(tab); + s = s + "default : "; //$NON-NLS-1$ + return s; + } + + public void traverse(IAbstractSyntaxTreeVisitor visitor, + BlockScope blockScope) { + + visitor.visit(this, blockScope); + visitor.endVisit(this, blockScope); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/DoStatement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/DoStatement.java index 32dfabd..fa656a7 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/DoStatement.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/DoStatement.java @@ -22,6 +22,7 @@ import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class DoStatement extends Statement { public Expression condition; + public Statement action; private Label breakLabel, continueLabel; @@ -37,119 +38,118 @@ public class DoStatement extends Statement { this.action = action; } - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { breakLabel = new Label(); continueLabel = new Label(); - LoopingFlowContext loopingContext = - new LoopingFlowContext( - flowContext, - this, - breakLabel, - continueLabel, - currentScope); + LoopingFlowContext loopingContext = new LoopingFlowContext(flowContext, + this, breakLabel, continueLabel, currentScope); Constant cst = condition.constant; - boolean isConditionTrue = cst != NotAConstant && cst.booleanValue() == true; + boolean isConditionTrue = cst != NotAConstant + && cst.booleanValue() == true; cst = condition.optimizedBooleanConstant(); - boolean isConditionOptimizedTrue = cst != NotAConstant && cst.booleanValue() == true; - boolean isConditionOptimizedFalse = cst != NotAConstant && cst.booleanValue() == false; + boolean isConditionOptimizedTrue = cst != NotAConstant + && cst.booleanValue() == true; + boolean isConditionOptimizedFalse = cst != NotAConstant + && cst.booleanValue() == false; int previousMode = flowInfo.reachMode(); - + if ((action != null) && !action.isEmptyBlock()) { - flowInfo = action.analyseCode(currentScope, loopingContext, flowInfo); + flowInfo = action.analyseCode(currentScope, loopingContext, + flowInfo); - // code generation can be optimized when no need to continue in the loop - if (!flowInfo.isReachable() && !loopingContext.initsOnContinue.isReachable()) { + // code generation can be optimized when no need to continue in the + // loop + if (!flowInfo.isReachable() + && !loopingContext.initsOnContinue.isReachable()) { continueLabel = null; } } - /* Reset reach mode, to address following scenario. - * final blank; - * do { if (true) break; else blank = 0; } while(false); - * blank = 1; // may be initialized already + /* + * Reset reach mode, to address following scenario. final blank; do { if + * (true) break; else blank = 0; } while(false); blank = 1; // may be + * initialized already */ flowInfo.setReachMode(previousMode); - - flowInfo = - condition.analyseCode( - currentScope, - loopingContext, - (action == null - ? flowInfo - : (flowInfo.mergedWith(loopingContext.initsOnContinue)))); + + flowInfo = condition.analyseCode(currentScope, loopingContext, + (action == null ? flowInfo : (flowInfo + .mergedWith(loopingContext.initsOnContinue)))); if (!isConditionOptimizedFalse && continueLabel != null) { - loopingContext.complainOnFinalAssignmentsInLoop(currentScope, flowInfo); + loopingContext.complainOnFinalAssignmentsInLoop(currentScope, + flowInfo); } // infinite loop FlowInfo mergedInfo; if (isConditionTrue) { mergedInfo = loopingContext.initsOnBreak; - if (!mergedInfo.isReachable()) mergedInfo.addPotentialInitializationsFrom(flowInfo.initsWhenFalse()); + if (!mergedInfo.isReachable()) + mergedInfo.addPotentialInitializationsFrom(flowInfo + .initsWhenFalse()); } else { // end of loop: either condition false or break - mergedInfo = - flowInfo.initsWhenFalse().unconditionalInits().mergedWith( - loopingContext.initsOnBreak); - if (isConditionOptimizedTrue && !loopingContext.initsOnBreak.isReachable()) { + mergedInfo = flowInfo.initsWhenFalse().unconditionalInits() + .mergedWith(loopingContext.initsOnBreak); + if (isConditionOptimizedTrue + && !loopingContext.initsOnBreak.isReachable()) { mergedInfo.setReachMode(FlowInfo.UNREACHABLE); } } - mergedInitStateIndex = - currentScope.methodScope().recordInitializationStates(mergedInfo); + mergedInitStateIndex = currentScope.methodScope() + .recordInitializationStates(mergedInfo); return mergedInfo; } /** * Do statement code generation - * + * */ -// public void generateCode(BlockScope currentScope, CodeStream codeStream) { -// -// if ((bits & IsReachableMASK) == 0) { -// return; -// } -// int pc = codeStream.position; -// -// // labels management -// Label actionLabel = new Label(codeStream); -// actionLabel.place(); -// breakLabel.codeStream = codeStream; -// if (continueLabel != null) { -// continueLabel.codeStream = codeStream; -// } -// -// // generate action -// if (action != null) { -// action.generateCode(currentScope, codeStream); -// } -// // generate condition -// if (continueLabel != null) { -// continueLabel.place(); -// condition.generateOptimizedBoolean( -// currentScope, -// codeStream, -// actionLabel, -// null, -// true); -// } -// breakLabel.place(); -// -// // May loose some local variable initializations : affecting the local variable attributes -// if (mergedInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// mergedInitStateIndex); -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// -// } - + // public void generateCode(BlockScope currentScope, CodeStream codeStream) + // { + // + // if ((bits & IsReachableMASK) == 0) { + // return; + // } + // int pc = codeStream.position; + // + // // labels management + // Label actionLabel = new Label(codeStream); + // actionLabel.place(); + // breakLabel.codeStream = codeStream; + // if (continueLabel != null) { + // continueLabel.codeStream = codeStream; + // } + // + // // generate action + // if (action != null) { + // action.generateCode(currentScope, codeStream); + // } + // // generate condition + // if (continueLabel != null) { + // continueLabel.place(); + // condition.generateOptimizedBoolean( + // currentScope, + // codeStream, + // actionLabel, + // null, + // true); + // } + // breakLabel.place(); + // + // // May loose some local variable initializations : affecting the local + // variable attributes + // if (mergedInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // mergedInitStateIndex); + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // + // } public void resetStateForCodeGeneration() { if (this.breakLabel != null) { this.breakLabel.resetStateForCodeGeneration(); @@ -161,11 +161,13 @@ public class DoStatement extends Statement { public void resolve(BlockScope scope) { - TypeBinding type = condition.resolveTypeExpecting(scope, BooleanBinding); + TypeBinding type = condition + .resolveTypeExpecting(scope, BooleanBinding); condition.implicitWidening(type, type); if (action != null) action.resolve(scope); } + public StringBuffer printStatement(int indent, StringBuffer output) { printIndent(indent, output).append("do"); //$NON-NLS-1$ @@ -178,6 +180,7 @@ public class DoStatement extends Statement { output.append("while ("); //$NON-NLS-1$ return condition.printExpression(0, output).append(");"); //$NON-NLS-1$ } + public String toString(int tab) { String inFront, s = tabString(tab); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/DoubleLiteral.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/DoubleLiteral.java index 7095049..6cb5a24 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/DoubleLiteral.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/DoubleLiteral.java @@ -15,58 +15,81 @@ import net.sourceforge.phpdt.internal.compiler.impl.Constant; import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; - public class DoubleLiteral extends NumberLiteral { double value; -public DoubleLiteral(char[] token, int s, int e) { - super(token, s,e); -} -public void computeConstant() { - //the source is correctly formated so the exception should never occurs + public DoubleLiteral(char[] token, int s, int e) { + super(token, s, e); + } - Double computedValue; - try { computedValue = Double.valueOf(String.valueOf(source));} - catch(NumberFormatException e){return ;} //how can it happen ???? + public void computeConstant() { - if (computedValue.doubleValue() > Double.MAX_VALUE) return ; //may be Infinity - if (computedValue.doubleValue() < Double.MIN_VALUE) - { //only a true 0 can be made of zeros - //2.00000000000000000e-324 is illegal .... - label : - for (int i=0;i> 4) == T_double) -// codeStream.generateInlinedValue(value); -// else -// codeStream.generateConstant(constant, implicitConversion); -// codeStream.recordPositionsFrom(pc, this.sourceStart); -//} -public TypeBinding literalType(BlockScope scope) { - return DoubleBinding; -} -public void traverse(IAbstractSyntaxTreeVisitor visitor, BlockScope blockScope) { - visitor.visit(this, blockScope); - visitor.endVisit(this, blockScope); -} + Double computedValue; + try { + computedValue = Double.valueOf(String.valueOf(source)); + } catch (NumberFormatException e) { + return; + } // how can it happen ???? + + if (computedValue.doubleValue() > Double.MAX_VALUE) + return; // may be Infinity + if (computedValue.doubleValue() < Double.MIN_VALUE) { // only a true 0 + // can be made + // of zeros + // 2.00000000000000000e-324 is illegal .... + label: for (int i = 0; i < source.length; i++) { // it is welled + // formated so + // just test + // against '0' + // and potential + // . D d + switch (source[i]) { + case '0': + case '.': + case 'd': + case 'D': + break; + case 'e': + case 'E': + break label; // exposant are valid....! + default: + return; + } + } + } // error + + constant = Constant.fromValue(value = computedValue.doubleValue()); + } + + /** + * Code generation for the double literak + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * @param valueRequired + * boolean + */ + // public void generateCode(BlockScope currentScope, CodeStream codeStream, + // boolean valueRequired) { + // int pc = codeStream.position; + // if (valueRequired) + // if ((implicitConversion >> 4) == T_double) + // codeStream.generateInlinedValue(value); + // else + // codeStream.generateConstant(constant, implicitConversion); + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } + public TypeBinding literalType(BlockScope scope) { + return DoubleBinding; + } + + public void traverse(IAbstractSyntaxTreeVisitor visitor, + BlockScope blockScope) { + visitor.visit(this, blockScope); + visitor.endVisit(this, blockScope); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/EmptyStatement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/EmptyStatement.java index 1fb6260..e498674 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/EmptyStatement.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/EmptyStatement.java @@ -22,26 +22,28 @@ public class EmptyStatement extends Statement { this.sourceEnd = endPosition; } - public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { return flowInfo; } -// public void generateCode(BlockScope currentScope, CodeStream codeStream){ -// // no bytecode, no need to check for reachability or recording source positions -// } + // public void generateCode(BlockScope currentScope, CodeStream codeStream){ + // // no bytecode, no need to check for reachability or recording source + // positions + // } public StringBuffer printStatement(int tab, StringBuffer output) { return printIndent(tab, output).append(';'); } + public void resolve(BlockScope scope) { } - + public void traverse(IAbstractSyntaxTreeVisitor visitor, BlockScope scope) { visitor.visit(this, scope); visitor.endVisit(this, scope); } - + public String toString(int tab) { return tabString(tab) + ";"; //$NON-NLS-1$ } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/EqualExpression.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/EqualExpression.java index 3788b65..7109c76 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/EqualExpression.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/EqualExpression.java @@ -23,538 +23,614 @@ import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class EqualExpression extends BinaryExpression { -public EqualExpression(Expression left, Expression right,int operator) { - super(left,right,operator); -} -public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { - if (((bits & OperatorMASK) >> OperatorSHIFT) == EQUAL_EQUAL) { - if ((left.constant != NotAConstant) && (left.constant.typeID() == T_boolean)) { - if (left.constant.booleanValue()) { // true == anything - // this is equivalent to the right argument inits - return right.analyseCode(currentScope, flowContext, flowInfo); - } else { // false == anything - // this is equivalent to the right argument inits negated - return right.analyseCode(currentScope, flowContext, flowInfo).asNegatedCondition(); + public EqualExpression(Expression left, Expression right, int operator) { + super(left, right, operator); + } + + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { + if (((bits & OperatorMASK) >> OperatorSHIFT) == EQUAL_EQUAL) { + if ((left.constant != NotAConstant) + && (left.constant.typeID() == T_boolean)) { + if (left.constant.booleanValue()) { // true == anything + // this is equivalent to the right argument inits + return right.analyseCode(currentScope, flowContext, + flowInfo); + } else { // false == anything + // this is equivalent to the right argument inits negated + return right.analyseCode(currentScope, flowContext, + flowInfo).asNegatedCondition(); + } } - } - if ((right.constant != NotAConstant) && (right.constant.typeID() == T_boolean)) { - if (right.constant.booleanValue()) { // anything == true - // this is equivalent to the right argument inits - return left.analyseCode(currentScope, flowContext, flowInfo); - } else { // anything == false - // this is equivalent to the right argument inits negated - return left.analyseCode(currentScope, flowContext, flowInfo).asNegatedCondition(); + if ((right.constant != NotAConstant) + && (right.constant.typeID() == T_boolean)) { + if (right.constant.booleanValue()) { // anything == true + // this is equivalent to the right argument inits + return left + .analyseCode(currentScope, flowContext, flowInfo); + } else { // anything == false + // this is equivalent to the right argument inits negated + return left + .analyseCode(currentScope, flowContext, flowInfo) + .asNegatedCondition(); + } } - } - return right.analyseCode( - currentScope, flowContext, - left.analyseCode(currentScope, flowContext, flowInfo).unconditionalInits()).unconditionalInits(); - } else { //NOT_EQUAL : - if ((left.constant != NotAConstant) && (left.constant.typeID() == T_boolean)) { - if (!left.constant.booleanValue()) { // false != anything - // this is equivalent to the right argument inits - return right.analyseCode(currentScope, flowContext, flowInfo); - } else { // true != anything - // this is equivalent to the right argument inits negated - return right.analyseCode(currentScope, flowContext, flowInfo).asNegatedCondition(); + return right.analyseCode( + currentScope, + flowContext, + left.analyseCode(currentScope, flowContext, flowInfo) + .unconditionalInits()).unconditionalInits(); + } else { // NOT_EQUAL : + if ((left.constant != NotAConstant) + && (left.constant.typeID() == T_boolean)) { + if (!left.constant.booleanValue()) { // false != anything + // this is equivalent to the right argument inits + return right.analyseCode(currentScope, flowContext, + flowInfo); + } else { // true != anything + // this is equivalent to the right argument inits negated + return right.analyseCode(currentScope, flowContext, + flowInfo).asNegatedCondition(); + } } - } - if ((right.constant != NotAConstant) && (right.constant.typeID() == T_boolean)) { - if (!right.constant.booleanValue()) { // anything != false - // this is equivalent to the right argument inits - return left.analyseCode(currentScope, flowContext, flowInfo); - } else { // anything != true - // this is equivalent to the right argument inits negated - return left.analyseCode(currentScope, flowContext, flowInfo).asNegatedCondition(); + if ((right.constant != NotAConstant) + && (right.constant.typeID() == T_boolean)) { + if (!right.constant.booleanValue()) { // anything != false + // this is equivalent to the right argument inits + return left + .analyseCode(currentScope, flowContext, flowInfo); + } else { // anything != true + // this is equivalent to the right argument inits negated + return left + .analyseCode(currentScope, flowContext, flowInfo) + .asNegatedCondition(); + } } + return right.analyseCode( + currentScope, + flowContext, + left.analyseCode(currentScope, flowContext, flowInfo) + .unconditionalInits()).asNegatedCondition() + .unconditionalInits(); } - return right.analyseCode( - currentScope, flowContext, - left.analyseCode(currentScope, flowContext, flowInfo).unconditionalInits()).asNegatedCondition().unconditionalInits(); } -} -public final boolean areTypesCastCompatible(BlockScope scope, TypeBinding castType, TypeBinding expressionType) { - //see specifications 5.5 - //A more complete version of this method is provided on - //CastExpression (it deals with constant and need runtime checkcast) - if (castType == expressionType) return true; + public final boolean areTypesCastCompatible(BlockScope scope, + TypeBinding castType, TypeBinding expressionType) { + // see specifications 5.5 + // A more complete version of this method is provided on + // CastExpression (it deals with constant and need runtime checkcast) - //========ARRAY=============== - if (expressionType.isArrayType()) { - if (castType.isArrayType()) { //------- (castTb.isArray) expressionTb.isArray ----------- - TypeBinding expressionEltType = ((ArrayBinding) expressionType).elementsType(scope); - if (expressionEltType.isBaseType()) - // <---stop the recursion------- - return ((ArrayBinding) castType).elementsType(scope) == expressionEltType; - //recursivly on the elts... - return areTypesCastCompatible(scope, ((ArrayBinding) castType).elementsType(scope), expressionEltType); - } - if (castType.isBaseType()) { - return false; - } - if (castType.isClass()) { //------(castTb.isClass) expressionTb.isArray --------------- - if (scope.isJavaLangObject(castType)) - return true; - return false; - } - if (castType.isInterface()) { //------- (castTb.isInterface) expressionTb.isArray ----------- - if (scope.isJavaLangCloneable(castType) || scope.isJavaIoSerializable(castType)) { - return true; + if (castType == expressionType) + return true; + + // ========ARRAY=============== + if (expressionType.isArrayType()) { + if (castType.isArrayType()) { // ------- (castTb.isArray) + // expressionTb.isArray ----------- + TypeBinding expressionEltType = ((ArrayBinding) expressionType) + .elementsType(scope); + if (expressionEltType.isBaseType()) + // <---stop the recursion------- + return ((ArrayBinding) castType).elementsType(scope) == expressionEltType; + // recursivly on the elts... + return areTypesCastCompatible(scope, ((ArrayBinding) castType) + .elementsType(scope), expressionEltType); + } + if (castType.isBaseType()) { + return false; + } + if (castType.isClass()) { // ------(castTb.isClass) + // expressionTb.isArray --------------- + if (scope.isJavaLangObject(castType)) + return true; + return false; } + if (castType.isInterface()) { // ------- (castTb.isInterface) + // expressionTb.isArray ----------- + if (scope.isJavaLangCloneable(castType) + || scope.isJavaIoSerializable(castType)) { + return true; + } + return false; + } + return false; } - return false; - } - - //------------(castType) null-------------- - if (expressionType == NullBinding) { - return !castType.isBaseType(); - } - - //========BASETYPE============== - if (expressionType.isBaseType()) { - return false; - } - - - //========REFERENCE TYPE=================== - - if (expressionType.isClass()) { - if (castType.isArrayType()) { // ---- (castTb.isArray) expressionTb.isClass ------- - if (scope.isJavaLangObject(expressionType)) - return true; + // ------------(castType) null-------------- + if (expressionType == NullBinding) { + return !castType.isBaseType(); } - if (castType.isBaseType()) { + + // ========BASETYPE============== + if (expressionType.isBaseType()) { return false; } - if (castType.isClass()) { // ----- (castTb.isClass) expressionTb.isClass ------ - if (expressionType.isCompatibleWith(castType)) - return true; - else { - if (castType.isCompatibleWith(expressionType)) { + + // ========REFERENCE TYPE=================== + + if (expressionType.isClass()) { + if (castType.isArrayType()) { // ---- (castTb.isArray) + // expressionTb.isClass ------- + if (scope.isJavaLangObject(expressionType)) return true; - } + } + if (castType.isBaseType()) { return false; } - } - if (castType.isInterface()) { // ----- (castTb.isInterface) expressionTb.isClass ------- - if (((ReferenceBinding) expressionType).isFinal()) { //no subclass for expressionTb, thus compile-time check is valid + if (castType.isClass()) { // ----- (castTb.isClass) + // expressionTb.isClass ------ if (expressionType.isCompatibleWith(castType)) return true; - return false; - } else { - return true; + else { + if (castType.isCompatibleWith(expressionType)) { + return true; + } + return false; + } } - } - - return false; - } - if (expressionType.isInterface()) { - if (castType.isArrayType()) { // ----- (castTb.isArray) expressionTb.isInterface ------ - if (scope.isJavaLangCloneable(expressionType) || scope.isJavaIoSerializable(expressionType)) - //potential runtime error - { - return true; + if (castType.isInterface()) { // ----- (castTb.isInterface) + // expressionTb.isClass ------- + if (((ReferenceBinding) expressionType).isFinal()) { // no + // subclass + // for + // expressionTb, + // thus + // compile-time + // check + // is + // valid + if (expressionType.isCompatibleWith(castType)) + return true; + return false; + } else { + return true; + } } + return false; } - if (castType.isBaseType()) { - return false; - } - if (castType.isClass()) { // ----- (castTb.isClass) expressionTb.isInterface -------- - if (scope.isJavaLangObject(castType)) - return true; - if (((ReferenceBinding) castType).isFinal()) { //no subclass for castTb, thus compile-time check is valid - if (castType.isCompatibleWith(expressionType)) { + if (expressionType.isInterface()) { + if (castType.isArrayType()) { // ----- (castTb.isArray) + // expressionTb.isInterface ------ + if (scope.isJavaLangCloneable(expressionType) + || scope.isJavaIoSerializable(expressionType)) + // potential runtime error + { return true; } return false; } - return true; - } - if (castType.isInterface()) { // ----- (castTb.isInterface) expressionTb.isInterface ------- - if (Scope.compareTypes(castType, expressionType) == NotRelated) { - MethodBinding[] castTbMethods = ((ReferenceBinding) castType).methods(); - int castTbMethodsLength = castTbMethods.length; - MethodBinding[] expressionTbMethods = ((ReferenceBinding) expressionType).methods(); - int expressionTbMethodsLength = expressionTbMethods.length; - for (int i = 0; i < castTbMethodsLength; i++) { - for (int j = 0; j < expressionTbMethodsLength; j++) { - if (castTbMethods[i].selector == expressionTbMethods[j].selector) { - if (castTbMethods[i].returnType != expressionTbMethods[j].returnType) { - if (castTbMethods[i].areParametersEqual(expressionTbMethods[j])) { - return false; + if (castType.isBaseType()) { + return false; + } + if (castType.isClass()) { // ----- (castTb.isClass) + // expressionTb.isInterface -------- + if (scope.isJavaLangObject(castType)) + return true; + if (((ReferenceBinding) castType).isFinal()) { // no subclass + // for castTb, + // thus + // compile-time + // check is + // valid + if (castType.isCompatibleWith(expressionType)) { + return true; + } + return false; + } + return true; + } + if (castType.isInterface()) { // ----- (castTb.isInterface) + // expressionTb.isInterface ------- + if (Scope.compareTypes(castType, expressionType) == NotRelated) { + MethodBinding[] castTbMethods = ((ReferenceBinding) castType) + .methods(); + int castTbMethodsLength = castTbMethods.length; + MethodBinding[] expressionTbMethods = ((ReferenceBinding) expressionType) + .methods(); + int expressionTbMethodsLength = expressionTbMethods.length; + for (int i = 0; i < castTbMethodsLength; i++) { + for (int j = 0; j < expressionTbMethodsLength; j++) { + if (castTbMethods[i].selector == expressionTbMethods[j].selector) { + if (castTbMethods[i].returnType != expressionTbMethods[j].returnType) { + if (castTbMethods[i] + .areParametersEqual(expressionTbMethods[j])) { + return false; + } } } } } } + return true; } - return true; + + return false; } return false; } - return false; -} -public final void computeConstant(TypeBinding leftType, TypeBinding rightType) { - if ((this.left.constant != NotAConstant) && (this.right.constant != NotAConstant)) { - this.constant = - Constant.computeConstantOperationEQUAL_EQUAL( - left.constant, - leftType.id, - EQUAL_EQUAL, - right.constant, - rightType.id); - if (((this.bits & OperatorMASK) >> OperatorSHIFT) == NOT_EQUAL) - constant = Constant.fromValue(!constant.booleanValue()); - } else { - this.constant = NotAConstant; - // no optimization for null == null + public final void computeConstant(TypeBinding leftType, + TypeBinding rightType) { + if ((this.left.constant != NotAConstant) + && (this.right.constant != NotAConstant)) { + this.constant = Constant.computeConstantOperationEQUAL_EQUAL( + left.constant, leftType.id, EQUAL_EQUAL, right.constant, + rightType.id); + if (((this.bits & OperatorMASK) >> OperatorSHIFT) == NOT_EQUAL) + constant = Constant.fromValue(!constant.booleanValue()); + } else { + this.constant = NotAConstant; + // no optimization for null == null + } } -} -/** - * Normal == or != code generation. - * - * @param currentScope net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream - * @param valueRequired boolean - */ -//public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) { -// -// if (constant != NotAConstant) { -// int pc = codeStream.position; -// if (valueRequired) -// codeStream.generateConstant(constant, implicitConversion); -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// return; -// } -// Label falseLabel; -// bits |= OnlyValueRequiredMASK; -// generateOptimizedBoolean( -// currentScope, -// codeStream, -// null, -// falseLabel = new Label(codeStream), -// valueRequired); -// if (falseLabel.hasForwardReferences()) { -// if (valueRequired){ -// // comparison is TRUE -// codeStream.iconst_1(); -// if ((bits & ValueForReturnMASK) != 0){ -// codeStream.ireturn(); -// // comparison is FALSE -// falseLabel.place(); -// codeStream.iconst_0(); -// } else { -// Label endLabel = new Label(codeStream); -// codeStream.goto_(endLabel); -// codeStream.decrStackSize(1); -// // comparison is FALSE -// falseLabel.place(); -// codeStream.iconst_0(); -// endLabel.place(); -// } -// } else { -// falseLabel.place(); -// } -// } -//} -/** - * Boolean operator code generation - * Optimized operations are: == and != - */ -//public void generateOptimizedBoolean(BlockScope currentScope, CodeStream codeStream, Label trueLabel, Label falseLabel, boolean valueRequired) { -// -// if (constant != Constant.NotAConstant) { -// super.generateOptimizedBoolean(currentScope, codeStream, trueLabel, falseLabel, valueRequired); -// return; -// } -// if (((bits & OperatorMASK) >> OperatorSHIFT) == EQUAL_EQUAL) { -// if ((left.implicitConversion & 0xF) /*compile-time*/ == T_boolean) { -// generateOptimizedBooleanEqual(currentScope, codeStream, trueLabel, falseLabel, valueRequired); -// } else { -// generateOptimizedNonBooleanEqual(currentScope, codeStream, trueLabel, falseLabel, valueRequired); -// } -// } else { -// if ((left.implicitConversion & 0xF) /*compile-time*/ == T_boolean) { -// generateOptimizedBooleanEqual(currentScope, codeStream, falseLabel, trueLabel, valueRequired); -// } else { -// generateOptimizedNonBooleanEqual(currentScope, codeStream, falseLabel, trueLabel, valueRequired); -// } -// } -//} -/** - * Boolean generation for == with boolean operands - * - * Note this code does not optimize conditional constants !!!! - */ -//public void generateOptimizedBooleanEqual(BlockScope currentScope, CodeStream codeStream, Label trueLabel, Label falseLabel, boolean valueRequired) { -// -// // optimized cases: true == x, false == x -// if (left.constant != NotAConstant) { -// boolean inline = left.constant.booleanValue(); -// right.generateOptimizedBoolean(currentScope, codeStream, (inline ? trueLabel : falseLabel), (inline ? falseLabel : trueLabel), valueRequired); -// return; -// } // optimized cases: x == true, x == false -// if (right.constant != NotAConstant) { -// boolean inline = right.constant.booleanValue(); -// left.generateOptimizedBoolean(currentScope, codeStream, (inline ? trueLabel : falseLabel), (inline ? falseLabel : trueLabel), valueRequired); -// return; -// } -// // default case -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) { -// if (falseLabel == null) { -// if (trueLabel != null) { -// // implicit falling through the FALSE case -// codeStream.if_icmpeq(trueLabel); -// } -// } else { -// // implicit falling through the TRUE case -// if (trueLabel == null) { -// codeStream.if_icmpne(falseLabel); -// } else { -// // no implicit fall through TRUE/FALSE --> should never occur -// } -// } -// } -// // reposition the endPC -// codeStream.updateLastRecordedEndPC(codeStream.position); -//} -///** -// * Boolean generation for == with non-boolean operands -// * -// */ -//public void generateOptimizedNonBooleanEqual(BlockScope currentScope, CodeStream codeStream, Label trueLabel, Label falseLabel, boolean valueRequired) { -// -// int pc = codeStream.position; -// Constant inline; -// if ((inline = right.constant) != NotAConstant) { -// // optimized case: x == 0 -// if (((left.implicitConversion >> 4) == T_int) && (inline.intValue() == 0)) { -// left.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) { -// if (falseLabel == null) { -// if (trueLabel != null) { -// // implicit falling through the FALSE case -// codeStream.ifeq(trueLabel); -// } -// } else { -// // implicit falling through the TRUE case -// if (trueLabel == null) { -// codeStream.ifne(falseLabel); -// } else { -// // no implicit fall through TRUE/FALSE --> should never occur -// } -// } -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// return; -// } -// } -// if ((inline = left.constant) != NotAConstant) { -// // optimized case: 0 == x -// if (((left.implicitConversion >> 4) == T_int) -// && (inline.intValue() == 0)) { -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) { -// if (falseLabel == null) { -// if (trueLabel != null) { -// // implicit falling through the FALSE case -// codeStream.ifeq(trueLabel); -// } -// } else { -// // implicit falling through the TRUE case -// if (trueLabel == null) { -// codeStream.ifne(falseLabel); -// } else { -// // no implicit fall through TRUE/FALSE --> should never occur -// } -// } -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// return; -// } -// } -// // null cases -// // optimized case: x == null -// if (right instanceof NullLiteral) { -// if (left instanceof NullLiteral) { -// // null == null -// if (valueRequired) { -// if ((bits & OnlyValueRequiredMASK) != 0) { -// if (((bits & OperatorMASK) >> OperatorSHIFT) == EQUAL_EQUAL) { -// codeStream.iconst_1(); -// } else { -// codeStream.iconst_0(); -// } -// } else { -// if (falseLabel == null) { -// // implicit falling through the FALSE case -// if (trueLabel != null) { -// codeStream.goto_(trueLabel); -// } -// } -// } -// } -// } else { -// left.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) { -// if (falseLabel == null) { -// if (trueLabel != null) { -// // implicit falling through the FALSE case -// codeStream.ifnull(trueLabel); -// } -// } else { -// // implicit falling through the TRUE case -// if (trueLabel == null) { -// codeStream.ifnonnull(falseLabel); -// } else { -// // no implicit fall through TRUE/FALSE --> should never occur -// } -// } -// } -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// return; -// } else if (left instanceof NullLiteral) { // optimized case: null == x -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) { -// if (falseLabel == null) { -// if (trueLabel != null) { -// // implicit falling through the FALSE case -// codeStream.ifnull(trueLabel); -// } -// } else { -// // implicit falling through the TRUE case -// if (trueLabel == null) { -// codeStream.ifnonnull(falseLabel); -// } else { -// // no implicit fall through TRUE/FALSE --> should never occur -// } -// } -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// return; -// } -// -// // default case -// left.generateCode(currentScope, codeStream, valueRequired); -// right.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) { -// if (falseLabel == null) { -// if (trueLabel != null) { -// // implicit falling through the FALSE case -// switch (left.implicitConversion >> 4) { // operand runtime type -// case T_int : -// codeStream.if_icmpeq(trueLabel); -// break; -// case T_float : -// codeStream.fcmpl(); -// codeStream.ifeq(trueLabel); -// break; -// case T_long : -// codeStream.lcmp(); -// codeStream.ifeq(trueLabel); -// break; -// case T_double : -// codeStream.dcmpl(); -// codeStream.ifeq(trueLabel); -// break; -// default : -// codeStream.if_acmpeq(trueLabel); -// } -// } -// } else { -// // implicit falling through the TRUE case -// if (trueLabel == null) { -// switch (left.implicitConversion >> 4) { // operand runtime type -// case T_int : -// codeStream.if_icmpne(falseLabel); -// break; -// case T_float : -// codeStream.fcmpl(); -// codeStream.ifne(falseLabel); -// break; -// case T_long : -// codeStream.lcmp(); -// codeStream.ifne(falseLabel); -// break; -// case T_double : -// codeStream.dcmpl(); -// codeStream.ifne(falseLabel); -// break; -// default : -// codeStream.if_acmpne(falseLabel); -// } -// } else { -// // no implicit fall through TRUE/FALSE --> should never occur -// } -// } -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -//} -public boolean isCompactableOperation() { - return false; -} -public TypeBinding resolveType(BlockScope scope) { - // always return BooleanBinding - TypeBinding leftType = left.resolveType(scope); - TypeBinding rightType = right.resolveType(scope); - if (leftType == null || rightType == null){ - constant = NotAConstant; - return null; + + /** + * Normal == or != code generation. + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * @param valueRequired + * boolean + */ + // public void generateCode(BlockScope currentScope, CodeStream codeStream, + // boolean valueRequired) { + // + // if (constant != NotAConstant) { + // int pc = codeStream.position; + // if (valueRequired) + // codeStream.generateConstant(constant, implicitConversion); + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // return; + // } + // Label falseLabel; + // bits |= OnlyValueRequiredMASK; + // generateOptimizedBoolean( + // currentScope, + // codeStream, + // null, + // falseLabel = new Label(codeStream), + // valueRequired); + // if (falseLabel.hasForwardReferences()) { + // if (valueRequired){ + // // comparison is TRUE + // codeStream.iconst_1(); + // if ((bits & ValueForReturnMASK) != 0){ + // codeStream.ireturn(); + // // comparison is FALSE + // falseLabel.place(); + // codeStream.iconst_0(); + // } else { + // Label endLabel = new Label(codeStream); + // codeStream.goto_(endLabel); + // codeStream.decrStackSize(1); + // // comparison is FALSE + // falseLabel.place(); + // codeStream.iconst_0(); + // endLabel.place(); + // } + // } else { + // falseLabel.place(); + // } + // } + // } + /** + * Boolean operator code generation Optimized operations are: == and != + */ + // public void generateOptimizedBoolean(BlockScope currentScope, CodeStream + // codeStream, Label trueLabel, Label falseLabel, boolean valueRequired) { + // + // if (constant != Constant.NotAConstant) { + // super.generateOptimizedBoolean(currentScope, codeStream, trueLabel, + // falseLabel, valueRequired); + // return; + // } + // if (((bits & OperatorMASK) >> OperatorSHIFT) == EQUAL_EQUAL) { + // if ((left.implicitConversion & 0xF) /*compile-time*/ == T_boolean) { + // generateOptimizedBooleanEqual(currentScope, codeStream, trueLabel, + // falseLabel, valueRequired); + // } else { + // generateOptimizedNonBooleanEqual(currentScope, codeStream, trueLabel, + // falseLabel, valueRequired); + // } + // } else { + // if ((left.implicitConversion & 0xF) /*compile-time*/ == T_boolean) { + // generateOptimizedBooleanEqual(currentScope, codeStream, falseLabel, + // trueLabel, valueRequired); + // } else { + // generateOptimizedNonBooleanEqual(currentScope, codeStream, falseLabel, + // trueLabel, valueRequired); + // } + // } + // } + /** + * Boolean generation for == with boolean operands + * + * Note this code does not optimize conditional constants !!!! + */ + // public void generateOptimizedBooleanEqual(BlockScope currentScope, + // CodeStream codeStream, Label trueLabel, Label falseLabel, boolean + // valueRequired) { + // + // // optimized cases: true == x, false == x + // if (left.constant != NotAConstant) { + // boolean inline = left.constant.booleanValue(); + // right.generateOptimizedBoolean(currentScope, codeStream, (inline ? + // trueLabel : falseLabel), (inline ? falseLabel : trueLabel), + // valueRequired); + // return; + // } // optimized cases: x == true, x == false + // if (right.constant != NotAConstant) { + // boolean inline = right.constant.booleanValue(); + // left.generateOptimizedBoolean(currentScope, codeStream, (inline ? + // trueLabel : falseLabel), (inline ? falseLabel : trueLabel), + // valueRequired); + // return; + // } + // // default case + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) { + // if (falseLabel == null) { + // if (trueLabel != null) { + // // implicit falling through the FALSE case + // codeStream.if_icmpeq(trueLabel); + // } + // } else { + // // implicit falling through the TRUE case + // if (trueLabel == null) { + // codeStream.if_icmpne(falseLabel); + // } else { + // // no implicit fall through TRUE/FALSE --> should never occur + // } + // } + // } + // // reposition the endPC + // codeStream.updateLastRecordedEndPC(codeStream.position); + // } + // /** + // * Boolean generation for == with non-boolean operands + // * + // */ + // public void generateOptimizedNonBooleanEqual(BlockScope currentScope, + // CodeStream codeStream, Label trueLabel, Label falseLabel, boolean + // valueRequired) { + // + // int pc = codeStream.position; + // Constant inline; + // if ((inline = right.constant) != NotAConstant) { + // // optimized case: x == 0 + // if (((left.implicitConversion >> 4) == T_int) && (inline.intValue() == + // 0)) { + // left.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) { + // if (falseLabel == null) { + // if (trueLabel != null) { + // // implicit falling through the FALSE case + // codeStream.ifeq(trueLabel); + // } + // } else { + // // implicit falling through the TRUE case + // if (trueLabel == null) { + // codeStream.ifne(falseLabel); + // } else { + // // no implicit fall through TRUE/FALSE --> should never occur + // } + // } + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // return; + // } + // } + // if ((inline = left.constant) != NotAConstant) { + // // optimized case: 0 == x + // if (((left.implicitConversion >> 4) == T_int) + // && (inline.intValue() == 0)) { + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) { + // if (falseLabel == null) { + // if (trueLabel != null) { + // // implicit falling through the FALSE case + // codeStream.ifeq(trueLabel); + // } + // } else { + // // implicit falling through the TRUE case + // if (trueLabel == null) { + // codeStream.ifne(falseLabel); + // } else { + // // no implicit fall through TRUE/FALSE --> should never occur + // } + // } + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // return; + // } + // } + // // null cases + // // optimized case: x == null + // if (right instanceof NullLiteral) { + // if (left instanceof NullLiteral) { + // // null == null + // if (valueRequired) { + // if ((bits & OnlyValueRequiredMASK) != 0) { + // if (((bits & OperatorMASK) >> OperatorSHIFT) == EQUAL_EQUAL) { + // codeStream.iconst_1(); + // } else { + // codeStream.iconst_0(); + // } + // } else { + // if (falseLabel == null) { + // // implicit falling through the FALSE case + // if (trueLabel != null) { + // codeStream.goto_(trueLabel); + // } + // } + // } + // } + // } else { + // left.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) { + // if (falseLabel == null) { + // if (trueLabel != null) { + // // implicit falling through the FALSE case + // codeStream.ifnull(trueLabel); + // } + // } else { + // // implicit falling through the TRUE case + // if (trueLabel == null) { + // codeStream.ifnonnull(falseLabel); + // } else { + // // no implicit fall through TRUE/FALSE --> should never occur + // } + // } + // } + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // return; + // } else if (left instanceof NullLiteral) { // optimized case: null == x + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) { + // if (falseLabel == null) { + // if (trueLabel != null) { + // // implicit falling through the FALSE case + // codeStream.ifnull(trueLabel); + // } + // } else { + // // implicit falling through the TRUE case + // if (trueLabel == null) { + // codeStream.ifnonnull(falseLabel); + // } else { + // // no implicit fall through TRUE/FALSE --> should never occur + // } + // } + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // return; + // } + // + // // default case + // left.generateCode(currentScope, codeStream, valueRequired); + // right.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) { + // if (falseLabel == null) { + // if (trueLabel != null) { + // // implicit falling through the FALSE case + // switch (left.implicitConversion >> 4) { // operand runtime type + // case T_int : + // codeStream.if_icmpeq(trueLabel); + // break; + // case T_float : + // codeStream.fcmpl(); + // codeStream.ifeq(trueLabel); + // break; + // case T_long : + // codeStream.lcmp(); + // codeStream.ifeq(trueLabel); + // break; + // case T_double : + // codeStream.dcmpl(); + // codeStream.ifeq(trueLabel); + // break; + // default : + // codeStream.if_acmpeq(trueLabel); + // } + // } + // } else { + // // implicit falling through the TRUE case + // if (trueLabel == null) { + // switch (left.implicitConversion >> 4) { // operand runtime type + // case T_int : + // codeStream.if_icmpne(falseLabel); + // break; + // case T_float : + // codeStream.fcmpl(); + // codeStream.ifne(falseLabel); + // break; + // case T_long : + // codeStream.lcmp(); + // codeStream.ifne(falseLabel); + // break; + // case T_double : + // codeStream.dcmpl(); + // codeStream.ifne(falseLabel); + // break; + // default : + // codeStream.if_acmpne(falseLabel); + // } + // } else { + // // no implicit fall through TRUE/FALSE --> should never occur + // } + // } + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } + public boolean isCompactableOperation() { + return false; } - // both base type - if (leftType.isBaseType() && rightType.isBaseType()) { - // the code is an int - // (cast) left == (cast) rigth --> result - // 0000 0000 0000 0000 0000 - // <<16 <<12 <<8 <<4 <<0 - int result = ResolveTypeTables[EQUAL_EQUAL][ (leftType.id << 4) + rightType.id]; - left.implicitConversion = result >>> 12; - right.implicitConversion = (result >>> 4) & 0x000FF; - bits |= result & 0xF; - if ((result & 0x0000F) == T_undefined) { - constant = Constant.NotAConstant; - scope.problemReporter().invalidOperator(this, leftType, rightType); + public TypeBinding resolveType(BlockScope scope) { + // always return BooleanBinding + TypeBinding leftType = left.resolveType(scope); + TypeBinding rightType = right.resolveType(scope); + if (leftType == null || rightType == null) { + constant = NotAConstant; return null; } - computeConstant(leftType, rightType); - this.resolvedType = BooleanBinding; - return BooleanBinding; - } - // Object references - // spec 15.20.3 - if (areTypesCastCompatible(scope, rightType, leftType) || areTypesCastCompatible(scope, leftType, rightType)) { - // (special case for String) - if ((rightType.id == T_String) && (leftType.id == T_String)) + // both base type + if (leftType.isBaseType() && rightType.isBaseType()) { + // the code is an int + // (cast) left == (cast) rigth --> result + // 0000 0000 0000 0000 0000 + // <<16 <<12 <<8 <<4 <<0 + int result = ResolveTypeTables[EQUAL_EQUAL][(leftType.id << 4) + + rightType.id]; + left.implicitConversion = result >>> 12; + right.implicitConversion = (result >>> 4) & 0x000FF; + bits |= result & 0xF; + if ((result & 0x0000F) == T_undefined) { + constant = Constant.NotAConstant; + scope.problemReporter().invalidOperator(this, leftType, + rightType); + return null; + } computeConstant(leftType, rightType); - else - constant = NotAConstant; - if (rightType.id == T_String) - right.implicitConversion = String2String; - if (leftType.id == T_String) - left.implicitConversion = String2String; - this.resolvedType = BooleanBinding; - return BooleanBinding; + this.resolvedType = BooleanBinding; + return BooleanBinding; + } + + // Object references + // spec 15.20.3 + if (areTypesCastCompatible(scope, rightType, leftType) + || areTypesCastCompatible(scope, leftType, rightType)) { + // (special case for String) + if ((rightType.id == T_String) && (leftType.id == T_String)) + computeConstant(leftType, rightType); + else + constant = NotAConstant; + if (rightType.id == T_String) + right.implicitConversion = String2String; + if (leftType.id == T_String) + left.implicitConversion = String2String; + this.resolvedType = BooleanBinding; + return BooleanBinding; + } + constant = NotAConstant; + scope.problemReporter().notCompatibleTypesError(this, leftType, + rightType); + return null; } - constant = NotAConstant; - scope.problemReporter().notCompatibleTypesError(this, leftType, rightType); - return null; -} -public void traverse(ASTVisitor visitor, BlockScope scope) { - if (visitor.visit(this, scope)) { - left.traverse(visitor, scope); - right.traverse(visitor, scope); + + public void traverse(ASTVisitor visitor, BlockScope scope) { + if (visitor.visit(this, scope)) { + left.traverse(visitor, scope); + right.traverse(visitor, scope); + } + visitor.endVisit(this, scope); } - visitor.endVisit(this, scope); -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ExplicitConstructorCall.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ExplicitConstructorCall.java index acd983f..ecf0b95 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ExplicitConstructorCall.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ExplicitConstructorCall.java @@ -23,21 +23,25 @@ import net.sourceforge.phpdt.internal.compiler.lookup.SourceTypeBinding; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; import net.sourceforge.phpdt.internal.compiler.lookup.VariableBinding; -public class ExplicitConstructorCall - extends Statement - implements InvocationSite { - +public class ExplicitConstructorCall extends Statement implements + InvocationSite { + public Expression[] arguments; + public Expression qualification; + public MethodBinding binding; public int accessMode; public final static int ImplicitSuper = 1; + public final static int Super = 2; + public final static int This = 3; public VariableBinding[][] implicitArguments; + boolean discardEnclosingInstance; MethodBinding syntheticAccessor; @@ -46,43 +50,35 @@ public class ExplicitConstructorCall this.accessMode = accessMode; } - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { - // must verify that exceptions potentially thrown by this expression are caught in the method. + // must verify that exceptions potentially thrown by this expression are + // caught in the method. try { ((MethodScope) currentScope).isConstructorCall = true; // process enclosing instance if (qualification != null) { - flowInfo = - qualification - .analyseCode(currentScope, flowContext, flowInfo) - .unconditionalInits(); + flowInfo = qualification.analyseCode(currentScope, flowContext, + flowInfo).unconditionalInits(); } // process arguments if (arguments != null) { for (int i = 0, max = arguments.length; i < max; i++) { - flowInfo = - arguments[i] - .analyseCode(currentScope, flowContext, flowInfo) - .unconditionalInits(); + flowInfo = arguments[i].analyseCode(currentScope, + flowContext, flowInfo).unconditionalInits(); } } ReferenceBinding[] thrownExceptions; if ((thrownExceptions = binding.thrownExceptions) != NoExceptions) { // check exceptions - flowContext.checkExceptionHandlers( - thrownExceptions, - (accessMode == ImplicitSuper) - ? (ASTNode) currentScope.methodScope().referenceContext - : (ASTNode) this, - flowInfo, - currentScope); + flowContext.checkExceptionHandlers(thrownExceptions, + (accessMode == ImplicitSuper) ? (ASTNode) currentScope + .methodScope().referenceContext + : (ASTNode) this, flowInfo, currentScope); } manageEnclosingInstanceAccessIfNecessary(currentScope); manageSyntheticAccessIfNecessary(currentScope); @@ -94,64 +90,67 @@ public class ExplicitConstructorCall /** * Constructor call code generation - * - * @param currentScope net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream */ -// public void generateCode(BlockScope currentScope, CodeStream codeStream) { -// -// if ((bits & IsReachableMASK) == 0) { -// return; -// } -// try { -// ((MethodScope) currentScope).isConstructorCall = true; -// -// int pc = codeStream.position; -// codeStream.aload_0(); -// -// // handling innerclass constructor invocation -// ReferenceBinding targetType = binding.declaringClass; -// // handling innerclass instance allocation - enclosing instance arguments -// if (targetType.isNestedType()) { -// codeStream.generateSyntheticEnclosingInstanceValues( -// currentScope, -// targetType, -// discardEnclosingInstance ? null : qualification, -// this); -// } -// // regular code gen -// if (arguments != null) { -// for (int i = 0, max = arguments.length; i < max; i++) { -// arguments[i].generateCode(currentScope, codeStream, true); -// } -// } -// // handling innerclass instance allocation - outer local arguments -// if (targetType.isNestedType()) { -// codeStream.generateSyntheticOuterArgumentValues( -// currentScope, -// targetType, -// this); -// } -// if (syntheticAccessor != null) { -// // synthetic accessor got some extra arguments appended to its signature, which need values -// for (int i = 0, -// max = syntheticAccessor.parameters.length - binding.parameters.length; -// i < max; -// i++) { -// codeStream.aconst_null(); -// } -// codeStream.invokespecial(syntheticAccessor); -// } else { -// codeStream.invokespecial(binding); -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } finally { -// ((MethodScope) currentScope).isConstructorCall = false; -// } -// } - + // public void generateCode(BlockScope currentScope, CodeStream codeStream) + // { + // + // if ((bits & IsReachableMASK) == 0) { + // return; + // } + // try { + // ((MethodScope) currentScope).isConstructorCall = true; + // + // int pc = codeStream.position; + // codeStream.aload_0(); + // + // // handling innerclass constructor invocation + // ReferenceBinding targetType = binding.declaringClass; + // // handling innerclass instance allocation - enclosing instance arguments + // if (targetType.isNestedType()) { + // codeStream.generateSyntheticEnclosingInstanceValues( + // currentScope, + // targetType, + // discardEnclosingInstance ? null : qualification, + // this); + // } + // // regular code gen + // if (arguments != null) { + // for (int i = 0, max = arguments.length; i < max; i++) { + // arguments[i].generateCode(currentScope, codeStream, true); + // } + // } + // // handling innerclass instance allocation - outer local arguments + // if (targetType.isNestedType()) { + // codeStream.generateSyntheticOuterArgumentValues( + // currentScope, + // targetType, + // this); + // } + // if (syntheticAccessor != null) { + // // synthetic accessor got some extra arguments appended to its signature, + // which need values + // for (int i = 0, + // max = syntheticAccessor.parameters.length - binding.parameters.length; + // i < max; + // i++) { + // codeStream.aconst_null(); + // } + // codeStream.invokespecial(syntheticAccessor); + // } else { + // codeStream.invokespecial(binding); + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } finally { + // ((MethodScope) currentScope).isConstructorCall = false; + // } + // } public boolean isImplicitSuper() { - //return true if I'm of these compiler added statement super(); + // return true if I'm of these compiler added statement super(); return (accessMode == ImplicitSuper); } @@ -166,45 +165,52 @@ public class ExplicitConstructorCall return true; } - /* Inner emulation consists in either recording a dependency - * link only, or performing one level of propagation. - * - * Dependency mechanism is used whenever dealing with source target - * types, since by the time we reach them, we might not yet know their - * exact need. + /* + * Inner emulation consists in either recording a dependency link only, or + * performing one level of propagation. + * + * Dependency mechanism is used whenever dealing with source target types, + * since by the time we reach them, we might not yet know their exact need. */ void manageEnclosingInstanceAccessIfNecessary(BlockScope currentScope) { ReferenceBinding superType; - // perform some emulation work in case there is some and we are inside a local type only + // perform some emulation work in case there is some and we are inside a + // local type only if ((superType = binding.declaringClass).isNestedType() - && currentScope.enclosingSourceType().isLocalType()) { + && currentScope.enclosingSourceType().isLocalType()) { if (superType.isLocalType()) { - ((LocalTypeBinding) superType).addInnerEmulationDependent(currentScope, qualification != null); + ((LocalTypeBinding) superType).addInnerEmulationDependent( + currentScope, qualification != null); } else { - // locally propagate, since we already now the desired shape for sure - currentScope.propagateInnerEmulation(superType, qualification != null); + // locally propagate, since we already now the desired shape for + // sure + currentScope.propagateInnerEmulation(superType, + qualification != null); } } } public void manageSyntheticAccessIfNecessary(BlockScope currentScope) { - // perform some emulation work in case there is some and we are inside a local type only + // perform some emulation work in case there is some and we are inside a + // local type only if (binding.isPrivate() && (accessMode != This)) { -// if (currentScope -// .environment() -// .options -// .isPrivateConstructorAccessChangingVisibility) { -// binding.tagForClearingPrivateModifier(); -// // constructor will not be dumped as private, no emulation required thus -// } else { - syntheticAccessor = - ((SourceTypeBinding) binding.declaringClass).addSyntheticMethod(binding, isSuperAccess()); - currentScope.problemReporter().needToEmulateMethodAccess(binding, this); -// } + // if (currentScope + // .environment() + // .options + // .isPrivateConstructorAccessChangingVisibility) { + // binding.tagForClearingPrivateModifier(); + // // constructor will not be dumped as private, no emulation + // required thus + // } else { + syntheticAccessor = ((SourceTypeBinding) binding.declaringClass) + .addSyntheticMethod(binding, isSuperAccess()); + currentScope.problemReporter().needToEmulateMethodAccess(binding, + this); + // } } } @@ -227,18 +233,19 @@ public class ExplicitConstructorCall // qualification should be from the type of the enclosingType if (qualification != null) { if (accessMode != Super) { - scope.problemReporter().unnecessaryEnclosingInstanceSpecification( - qualification, - receiverType); + scope.problemReporter() + .unnecessaryEnclosingInstanceSpecification( + qualification, receiverType); } ReferenceBinding enclosingType = receiverType.enclosingType(); if (enclosingType == null) { - scope.problemReporter().unnecessaryEnclosingInstanceSpecification( - qualification, - receiverType); + scope.problemReporter() + .unnecessaryEnclosingInstanceSpecification( + qualification, receiverType); discardEnclosingInstance = true; } else { - TypeBinding qTb = qualification.resolveTypeExpecting(scope, enclosingType); + TypeBinding qTb = qualification.resolveTypeExpecting(scope, + enclosingType); qualification.implicitWidening(qTb, qTb); } } @@ -256,20 +263,21 @@ public class ExplicitConstructorCall return; } if ((binding = scope.getConstructor(receiverType, argTypes, this)) - .isValidBinding()) { + .isValidBinding()) { if (isMethodUseDeprecated(binding, scope)) scope.problemReporter().deprecatedMethod(binding, this); - // see for user-implicit widening conversion + // see for user-implicit widening conversion if (arguments != null) { int length = arguments.length; TypeBinding[] paramTypes = binding.parameters; for (int i = 0; i < length; i++) - arguments[i].implicitWidening(paramTypes[i], argTypes[i]); + arguments[i].implicitWidening(paramTypes[i], + argTypes[i]); } if (binding.isPrivate()) { binding.modifiers |= AccPrivateUsed; - } + } } else { if (binding.declaringClass == null) binding.declaringClass = receiverType; @@ -291,10 +299,12 @@ public class ExplicitConstructorCall public void setFieldIndex(int depth) { // ignore for here } + public StringBuffer printStatement(int indent, StringBuffer output) { printIndent(indent, output); - if (qualification != null) qualification.printExpression(0, output).append('.'); + if (qualification != null) + qualification.printExpression(0, output).append('.'); if (accessMode == This) { output.append("this("); //$NON-NLS-1$ } else { @@ -302,12 +312,14 @@ public class ExplicitConstructorCall } if (arguments != null) { for (int i = 0; i < arguments.length; i++) { - if (i > 0) output.append(", "); //$NON-NLS-1$ + if (i > 0) + output.append(", "); //$NON-NLS-1$ arguments[i].printExpression(0, output); } } return output.append(");"); //$NON-NLS-1$ } + public String toString(int tab) { String s = tabString(tab); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Expression.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Expression.java index 69bd341..0b6c568 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Expression.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Expression.java @@ -18,379 +18,393 @@ import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class Expression extends Statement { - - //some expression may not be used - from a java semantic point - //of view only - as statements. Other may. In order to avoid the creation - //of wrappers around expression in order to tune them as expression - //Expression is a subclass of Statement. See the message isValidJavaStatement() + + // some expression may not be used - from a java semantic point + // of view only - as statements. Other may. In order to avoid the creation + // of wrappers around expression in order to tune them as expression + // Expression is a subclass of Statement. See the message + // isValidJavaStatement() public int implicitConversion; + public TypeBinding resolvedType; - + public Constant constant; public Expression() { super(); } - public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { return flowInfo; } - public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo, boolean valueRequired) { + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo, boolean valueRequired) { return analyseCode(currentScope, flowContext, flowInfo); } /** * Constant usable for bytecode pattern optimizations, but cannot be inlined - * since it is not strictly equivalent to the definition of constant expressions. - * In particular, some side-effects may be required to occur (only the end value - * is known). - * Constant is known to be of boolean type - */ + * since it is not strictly equivalent to the definition of constant + * expressions. In particular, some side-effects may be required to occur + * (only the end value is known). Constant is known to be of boolean type + */ public Constant optimizedBooleanConstant() { return this.constant; } - public static final boolean isConstantValueRepresentable( - Constant constant, - int constantTypeID, - int targetTypeID) { + public static final boolean isConstantValueRepresentable(Constant constant, + int constantTypeID, int targetTypeID) { - //true if there is no loss of precision while casting. + // true if there is no loss of precision while casting. // constantTypeID == constant.typeID if (targetTypeID == constantTypeID) return true; switch (targetTypeID) { - case T_char : - switch (constantTypeID) { - case T_char : - return true; - case T_double : - return constant.doubleValue() == constant.charValue(); - case T_float : - return constant.floatValue() == constant.charValue(); - case T_int : - return constant.intValue() == constant.charValue(); - case T_short : - return constant.shortValue() == constant.charValue(); - case T_byte : - return constant.byteValue() == constant.charValue(); - case T_long : - return constant.longValue() == constant.charValue(); - default : - return false;//boolean - } - - case T_float : - switch (constantTypeID) { - case T_char : - return constant.charValue() == constant.floatValue(); - case T_double : - return constant.doubleValue() == constant.floatValue(); - case T_float : - return true; - case T_int : - return constant.intValue() == constant.floatValue(); - case T_short : - return constant.shortValue() == constant.floatValue(); - case T_byte : - return constant.byteValue() == constant.floatValue(); - case T_long : - return constant.longValue() == constant.floatValue(); - default : - return false;//boolean - } - - case T_double : - switch (constantTypeID) { - case T_char : - return constant.charValue() == constant.doubleValue(); - case T_double : - return true; - case T_float : - return constant.floatValue() == constant.doubleValue(); - case T_int : - return constant.intValue() == constant.doubleValue(); - case T_short : - return constant.shortValue() == constant.doubleValue(); - case T_byte : - return constant.byteValue() == constant.doubleValue(); - case T_long : - return constant.longValue() == constant.doubleValue(); - default : - return false; //boolean - } - - case T_byte : - switch (constantTypeID) { - case T_char : - return constant.charValue() == constant.byteValue(); - case T_double : - return constant.doubleValue() == constant.byteValue(); - case T_float : - return constant.floatValue() == constant.byteValue(); - case T_int : - return constant.intValue() == constant.byteValue(); - case T_short : - return constant.shortValue() == constant.byteValue(); - case T_byte : - return true; - case T_long : - return constant.longValue() == constant.byteValue(); - default : - return false; //boolean - } - - case T_short : - switch (constantTypeID) { - case T_char : - return constant.charValue() == constant.shortValue(); - case T_double : - return constant.doubleValue() == constant.shortValue(); - case T_float : - return constant.floatValue() == constant.shortValue(); - case T_int : - return constant.intValue() == constant.shortValue(); - case T_short : - return true; - case T_byte : - return constant.byteValue() == constant.shortValue(); - case T_long : - return constant.longValue() == constant.shortValue(); - default : - return false; //boolean - } - - case T_int : - switch (constantTypeID) { - case T_char : - return constant.charValue() == constant.intValue(); - case T_double : - return constant.doubleValue() == constant.intValue(); - case T_float : - return constant.floatValue() == constant.intValue(); - case T_int : - return true; - case T_short : - return constant.shortValue() == constant.intValue(); - case T_byte : - return constant.byteValue() == constant.intValue(); - case T_long : - return constant.longValue() == constant.intValue(); - default : - return false; //boolean - } - - case T_long : - switch (constantTypeID) { - case T_char : - return constant.charValue() == constant.longValue(); - case T_double : - return constant.doubleValue() == constant.longValue(); - case T_float : - return constant.floatValue() == constant.longValue(); - case T_int : - return constant.intValue() == constant.longValue(); - case T_short : - return constant.shortValue() == constant.longValue(); - case T_byte : - return constant.byteValue() == constant.longValue(); - case T_long : - return true; - default : - return false; //boolean - } - - default : - return false; //boolean - } + case T_char: + switch (constantTypeID) { + case T_char: + return true; + case T_double: + return constant.doubleValue() == constant.charValue(); + case T_float: + return constant.floatValue() == constant.charValue(); + case T_int: + return constant.intValue() == constant.charValue(); + case T_short: + return constant.shortValue() == constant.charValue(); + case T_byte: + return constant.byteValue() == constant.charValue(); + case T_long: + return constant.longValue() == constant.charValue(); + default: + return false;// boolean + } + + case T_float: + switch (constantTypeID) { + case T_char: + return constant.charValue() == constant.floatValue(); + case T_double: + return constant.doubleValue() == constant.floatValue(); + case T_float: + return true; + case T_int: + return constant.intValue() == constant.floatValue(); + case T_short: + return constant.shortValue() == constant.floatValue(); + case T_byte: + return constant.byteValue() == constant.floatValue(); + case T_long: + return constant.longValue() == constant.floatValue(); + default: + return false;// boolean + } + + case T_double: + switch (constantTypeID) { + case T_char: + return constant.charValue() == constant.doubleValue(); + case T_double: + return true; + case T_float: + return constant.floatValue() == constant.doubleValue(); + case T_int: + return constant.intValue() == constant.doubleValue(); + case T_short: + return constant.shortValue() == constant.doubleValue(); + case T_byte: + return constant.byteValue() == constant.doubleValue(); + case T_long: + return constant.longValue() == constant.doubleValue(); + default: + return false; // boolean + } + + case T_byte: + switch (constantTypeID) { + case T_char: + return constant.charValue() == constant.byteValue(); + case T_double: + return constant.doubleValue() == constant.byteValue(); + case T_float: + return constant.floatValue() == constant.byteValue(); + case T_int: + return constant.intValue() == constant.byteValue(); + case T_short: + return constant.shortValue() == constant.byteValue(); + case T_byte: + return true; + case T_long: + return constant.longValue() == constant.byteValue(); + default: + return false; // boolean + } + + case T_short: + switch (constantTypeID) { + case T_char: + return constant.charValue() == constant.shortValue(); + case T_double: + return constant.doubleValue() == constant.shortValue(); + case T_float: + return constant.floatValue() == constant.shortValue(); + case T_int: + return constant.intValue() == constant.shortValue(); + case T_short: + return true; + case T_byte: + return constant.byteValue() == constant.shortValue(); + case T_long: + return constant.longValue() == constant.shortValue(); + default: + return false; // boolean + } + + case T_int: + switch (constantTypeID) { + case T_char: + return constant.charValue() == constant.intValue(); + case T_double: + return constant.doubleValue() == constant.intValue(); + case T_float: + return constant.floatValue() == constant.intValue(); + case T_int: + return true; + case T_short: + return constant.shortValue() == constant.intValue(); + case T_byte: + return constant.byteValue() == constant.intValue(); + case T_long: + return constant.longValue() == constant.intValue(); + default: + return false; // boolean + } + + case T_long: + switch (constantTypeID) { + case T_char: + return constant.charValue() == constant.longValue(); + case T_double: + return constant.doubleValue() == constant.longValue(); + case T_float: + return constant.floatValue() == constant.longValue(); + case T_int: + return constant.intValue() == constant.longValue(); + case T_short: + return constant.shortValue() == constant.longValue(); + case T_byte: + return constant.byteValue() == constant.longValue(); + case T_long: + return true; + default: + return false; // boolean + } + + default: + return false; // boolean + } } /** * Expression statements are plain expressions, however they generate like * normal expressions with no value required. - * - * @param currentScope net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream */ -// public void generateCode(BlockScope currentScope, CodeStream codeStream) { -// -// if ((bits & IsReachableMASK) == 0) { -// return; -// } -// generateCode(currentScope, codeStream, false); -// } - + // public void generateCode(BlockScope currentScope, CodeStream codeStream) + // { + // + // if ((bits & IsReachableMASK) == 0) { + // return; + // } + // generateCode(currentScope, codeStream, false); + // } /** - * Every expression is responsible for generating its implicit conversion when necessary. - * - * @param currentScope net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream - * @param valueRequired boolean + * Every expression is responsible for generating its implicit conversion + * when necessary. + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * @param valueRequired + * boolean */ -// public void generateCode( -// BlockScope currentScope, -// CodeStream codeStream, -// boolean valueRequired) { -// -// if (constant != NotAConstant) { -// // generate a constant expression -// int pc = codeStream.position; -// codeStream.generateConstant(constant, implicitConversion); -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } else { -// // actual non-constant code generation -// throw new ShouldNotImplement(ProjectPrefUtil.bind("ast.missingCode")); //$NON-NLS-1$ -// } -// } - + // public void generateCode( + // BlockScope currentScope, + // CodeStream codeStream, + // boolean valueRequired) { + // + // if (constant != NotAConstant) { + // // generate a constant expression + // int pc = codeStream.position; + // codeStream.generateConstant(constant, implicitConversion); + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } else { + // // actual non-constant code generation + // throw new ShouldNotImplement(ProjectPrefUtil.bind("ast.missingCode")); + // //$NON-NLS-1$ + // } + // } /** * Default generation of a boolean value */ -// public void generateOptimizedBoolean( -// BlockScope currentScope, -// CodeStream codeStream, -// Label trueLabel, -// Label falseLabel, -// boolean valueRequired) { -// -// // a label valued to nil means: by default we fall through the case... -// // both nil means we leave the value on the stack -// -// if ((constant != Constant.NotAConstant) && (constant.typeID() == T_boolean)) { -// int pc = codeStream.position; -// if (constant.booleanValue() == true) { -// // constant == true -// if (valueRequired) { -// if (falseLabel == null) { -// // implicit falling through the FALSE case -// if (trueLabel != null) { -// codeStream.goto_(trueLabel); -// } -// } -// } -// } else { -// if (valueRequired) { -// if (falseLabel != null) { -// // implicit falling through the TRUE case -// if (trueLabel == null) { -// codeStream.goto_(falseLabel); -// } -// } -// } -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// return; -// } -// generateCode(currentScope, codeStream, valueRequired); -// // branching -// int position = codeStream.position; -// if (valueRequired) { -// if (falseLabel == null) { -// if (trueLabel != null) { -// // Implicit falling through the FALSE case -// codeStream.ifne(trueLabel); -// } -// } else { -// if (trueLabel == null) { -// // Implicit falling through the TRUE case -// codeStream.ifeq(falseLabel); -// } else { -// // No implicit fall through TRUE/FALSE --> should never occur -// } -// } -// } -// // reposition the endPC -// codeStream.updateLastRecordedEndPC(position); -// } -// -// /* Optimized (java) code generation for string concatenations that involve StringBuffer -// * creation: going through this path means that there is no need for a new StringBuffer -// * creation, further operands should rather be only appended to the current one. -// * By default: no optimization. -// */ -// public void generateOptimizedStringBuffer( -// BlockScope blockScope, -// net.sourceforge.phpdt.internal.compiler.codegen.CodeStream codeStream, -// int typeID) { -// -// generateCode(blockScope, codeStream, true); -// codeStream.invokeStringBufferAppendForType(typeID); -// } - - /* Optimized (java) code generation for string concatenations that involve StringBuffer - * creation: going through this path means that there is no need for a new StringBuffer - * creation, further operands should rather be only appended to the current one. + // public void generateOptimizedBoolean( + // BlockScope currentScope, + // CodeStream codeStream, + // Label trueLabel, + // Label falseLabel, + // boolean valueRequired) { + // + // // a label valued to nil means: by default we fall through the case... + // // both nil means we leave the value on the stack + // + // if ((constant != Constant.NotAConstant) && (constant.typeID() == + // T_boolean)) { + // int pc = codeStream.position; + // if (constant.booleanValue() == true) { + // // constant == true + // if (valueRequired) { + // if (falseLabel == null) { + // // implicit falling through the FALSE case + // if (trueLabel != null) { + // codeStream.goto_(trueLabel); + // } + // } + // } + // } else { + // if (valueRequired) { + // if (falseLabel != null) { + // // implicit falling through the TRUE case + // if (trueLabel == null) { + // codeStream.goto_(falseLabel); + // } + // } + // } + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // return; + // } + // generateCode(currentScope, codeStream, valueRequired); + // // branching + // int position = codeStream.position; + // if (valueRequired) { + // if (falseLabel == null) { + // if (trueLabel != null) { + // // Implicit falling through the FALSE case + // codeStream.ifne(trueLabel); + // } + // } else { + // if (trueLabel == null) { + // // Implicit falling through the TRUE case + // codeStream.ifeq(falseLabel); + // } else { + // // No implicit fall through TRUE/FALSE --> should never occur + // } + // } + // } + // // reposition the endPC + // codeStream.updateLastRecordedEndPC(position); + // } + // + // /* Optimized (java) code generation for string concatenations that + // involve StringBuffer + // * creation: going through this path means that there is no need for a new + // StringBuffer + // * creation, further operands should rather be only appended to the + // current one. + // * By default: no optimization. + // */ + // public void generateOptimizedStringBuffer( + // BlockScope blockScope, + // net.sourceforge.phpdt.internal.compiler.codegen.CodeStream codeStream, + // int typeID) { + // + // generateCode(blockScope, codeStream, true); + // codeStream.invokeStringBufferAppendForType(typeID); + // } + /* + * Optimized (java) code generation for string concatenations that involve + * StringBuffer creation: going through this path means that there is no + * need for a new StringBuffer creation, further operands should rather be + * only appended to the current one. */ -// public void generateOptimizedStringBufferCreation( -// BlockScope blockScope, -// CodeStream codeStream, -// int typeID) { -// -// // Optimization only for integers and strings -// if (typeID == T_Object) { -// // in the case the runtime value of valueOf(Object) returns null, we have to use append(Object) instead of directly valueOf(Object) -// // append(Object) returns append(valueOf(Object)), which means that the null case is handled by append(String). -// codeStream.newStringBuffer(); -// codeStream.dup(); -// codeStream.invokeStringBufferDefaultConstructor(); -// generateCode(blockScope, codeStream, true); -// codeStream.invokeStringBufferAppendForType(T_Object); -// return; -// } -// codeStream.newStringBuffer(); -// codeStream.dup(); -// if (typeID == T_String || typeID == T_null) { -// if (constant != NotAConstant) { -// codeStream.ldc(constant.stringValue()); -// } else { -// generateCode(blockScope, codeStream, true); -// codeStream.invokeStringValueOf(T_Object); -// } -// } else { -// generateCode(blockScope, codeStream, true); -// codeStream.invokeStringValueOf(typeID); -// } -// codeStream.invokeStringBufferStringConstructor(); -// } - - // Base types need that the widening is explicitly done by the compiler using some bytecode like i2f - public void implicitWidening( - TypeBinding runtimeTimeType, - TypeBinding compileTimeType) { + // public void generateOptimizedStringBufferCreation( + // BlockScope blockScope, + // CodeStream codeStream, + // int typeID) { + // + // // Optimization only for integers and strings + // if (typeID == T_Object) { + // // in the case the runtime value of valueOf(Object) returns null, we have + // to use append(Object) instead of directly valueOf(Object) + // // append(Object) returns append(valueOf(Object)), which means that the + // null case is handled by append(String). + // codeStream.newStringBuffer(); + // codeStream.dup(); + // codeStream.invokeStringBufferDefaultConstructor(); + // generateCode(blockScope, codeStream, true); + // codeStream.invokeStringBufferAppendForType(T_Object); + // return; + // } + // codeStream.newStringBuffer(); + // codeStream.dup(); + // if (typeID == T_String || typeID == T_null) { + // if (constant != NotAConstant) { + // codeStream.ldc(constant.stringValue()); + // } else { + // generateCode(blockScope, codeStream, true); + // codeStream.invokeStringValueOf(T_Object); + // } + // } else { + // generateCode(blockScope, codeStream, true); + // codeStream.invokeStringValueOf(typeID); + // } + // codeStream.invokeStringBufferStringConstructor(); + // } + // Base types need that the widening is explicitly done by the compiler + // using some bytecode like i2f + public void implicitWidening(TypeBinding runtimeTimeType, + TypeBinding compileTimeType) { if (runtimeTimeType == null || compileTimeType == null) return; -// if (compileTimeType.id == T_null) { -// // this case is possible only for constant null -// // The type of runtime is a reference type -// // The code gen use the constant id thus any value -// // for the runtime id (akak the <<4) could be used. -// // T_Object is used as some general T_reference -// implicitConversion = (T_Object << 4) + T_null; -// return; -// } + // if (compileTimeType.id == T_null) { + // // this case is possible only for constant null + // // The type of runtime is a reference type + // // The code gen use the constant id thus any value + // // for the runtime id (akak the <<4) could be used. + // // T_Object is used as some general T_reference + // implicitConversion = (T_Object << 4) + T_null; + // return; + // } switch (runtimeTimeType.id) { - case T_byte : - case T_short : - case T_char : - implicitConversion = (T_int << 4) + compileTimeType.id; - break; - case T_String : - case T_float : - case T_boolean : - case T_double : - case T_int : //implicitConversion may result in i2i which will result in NO code gen - case T_long : - implicitConversion = (runtimeTimeType.id << 4) + compileTimeType.id; - break; - default : //nothing on regular object ref + case T_byte: + case T_short: + case T_char: + implicitConversion = (T_int << 4) + compileTimeType.id; + break; + case T_String: + case T_float: + case T_boolean: + case T_double: + case T_int: // implicitConversion may result in i2i which will result in + // NO code gen + case T_long: + implicitConversion = (runtimeTimeType.id << 4) + compileTimeType.id; + break; + default: // nothing on regular object ref } } @@ -399,25 +413,26 @@ public class Expression extends Statement { return false; } - //Return true if the conversion is done AUTOMATICALLY by the vm - //while the javaVM is an int based-machine, thus for example pushing - //a byte onto the stack , will automatically creates a int on the stack - //(this request some work d be done by the VM on signed numbers) + // Return true if the conversion is done AUTOMATICALLY by the vm + // while the javaVM is an int based-machine, thus for example pushing + // a byte onto the stack , will automatically creates a int on the stack + // (this request some work d be done by the VM on signed numbers) public boolean isConstantValueOfTypeAssignableToType( - TypeBinding constantType, - TypeBinding targetType) { + TypeBinding constantType, TypeBinding targetType) { if (constant == Constant.NotAConstant) return false; if (constantType == targetType) return true; if (constantType.isBaseType() && targetType.isBaseType()) { - //No free assignment conversion from anything but to integral ones. - if ((constantType == IntBinding - || BaseTypeBinding.isWidening(T_int, constantType.id)) - && (BaseTypeBinding.isNarrowing(targetType.id, T_int))) { - //use current explicit conversion in order to get some new value to compare with current one - return isConstantValueRepresentable(constant, constantType.id, targetType.id); + // No free assignment conversion from anything but to integral ones. + if ((constantType == IntBinding || BaseTypeBinding.isWidening( + T_int, constantType.id)) + && (BaseTypeBinding.isNarrowing(targetType.id, T_int))) { + // use current explicit conversion in order to get some new + // value to compare with current one + return isConstantValueRepresentable(constant, constantType.id, + targetType.id); } } return false; @@ -426,19 +441,21 @@ public class Expression extends Statement { public boolean isTypeReference() { return false; } + public StringBuffer print(int indent, StringBuffer output) { printIndent(indent, output); return printExpression(indent, output); } public StringBuffer printExpression(int indent, StringBuffer output) { - output.append(super.toString(0)); - return output; + output.append(super.toString(0)); + return output; } - + public StringBuffer printStatement(int indent, StringBuffer output) { return print(indent, output).append(";"); //$NON-NLS-1$ } + public void resolve(BlockScope scope) { // drops the returning expression's type whatever the type is. @@ -452,16 +469,18 @@ public class Expression extends Statement { return null; } - public TypeBinding resolveTypeExpecting( - BlockScope scope, - TypeBinding expectedType) { + public TypeBinding resolveTypeExpecting(BlockScope scope, + TypeBinding expectedType) { TypeBinding expressionType = this.resolveType(scope); - if (expressionType == null) return null; - if (expressionType == expectedType) return expressionType; - + if (expressionType == null) + return null; + if (expressionType == expectedType) + return expressionType; + if (!expressionType.isCompatibleWith(expectedType)) { - scope.problemReporter().typeMismatchError(expressionType, expectedType, this); + scope.problemReporter().typeMismatchError(expressionType, + expectedType, this); return null; } return expressionType; @@ -469,37 +488,39 @@ public class Expression extends Statement { public String toString(int tab) { - //Subclass re-define toStringExpression + // Subclass re-define toStringExpression String s = tabString(tab); if (constant != null) - //before TC has runned + // before TC has runned if (constant != NotAConstant) - //after the TC has runned + // after the TC has runned s += " /*cst:" + constant.toString() + "*/ "; //$NON-NLS-1$ //$NON-NLS-2$ return s + toStringExpression(tab); } - //Subclass re-define toStringExpression - //This method is abstract and should never be called - //but we provide some code that is running.....just in case - //of developpement time (while every thing is not built) + // Subclass re-define toStringExpression + // This method is abstract and should never be called + // but we provide some code that is running.....just in case + // of developpement time (while every thing is not built) public String toStringExpression() { return super.toString(0); } public String toStringExpression(int tab) { - // default is regular toString expression (qualified allocation expressions redifine this method) + // default is regular toString expression (qualified allocation + // expressions redifine this method) return this.toStringExpression(); } public Expression toTypeReference() { - //by default undefined + // by default undefined - //this method is meanly used by the parser in order to transform - //an expression that is used as a type reference in a cast .... - //--appreciate the fact that castExpression and ExpressionWithParenthesis - //--starts with the same pattern..... + // this method is meanly used by the parser in order to transform + // an expression that is used as a type reference in a cast .... + // --appreciate the fact that castExpression and + // ExpressionWithParenthesis + // --starts with the same pattern..... return this; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ExtendedStringLiteral.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ExtendedStringLiteral.java index 6427535..4376e3d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ExtendedStringLiteral.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ExtendedStringLiteral.java @@ -15,18 +15,17 @@ import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; public class ExtendedStringLiteral extends StringLiteral { - /** - * Build a string+char literal + /** + * Build a string+char literal */ -// public ExtendedStringLiteral(StringLiteral str, CharLiteral character) { -// -// super(str.source, str.sourceStart, str.sourceEnd); -// extendWith(character); -// } - - /** + // public ExtendedStringLiteral(StringLiteral str, CharLiteral character) { + // + // super(str.source, str.sourceStart, str.sourceEnd); + // extendWith(character); + // } + /** * Build a two-strings literal - * */ + */ public ExtendedStringLiteral(StringLiteral str1, StringLiteral str2) { super(str1.source, str1.sourceStart, str1.sourceEnd); @@ -36,42 +35,40 @@ public class ExtendedStringLiteral extends StringLiteral { /** * Add the lit source to mine, just as if it was mine */ -// public ExtendedStringLiteral extendWith(CharLiteral lit) { -// -// //update the source -// int length = source.length; -// System.arraycopy(source, 0, (source = new char[length + 1]), 0, length); -// source[length] = lit.value; -// //position at the end of all literals -// sourceEnd = lit.sourceEnd; -// return this; -// } - + // public ExtendedStringLiteral extendWith(CharLiteral lit) { + // + // //update the source + // int length = source.length; + // System.arraycopy(source, 0, (source = new char[length + 1]), 0, length); + // source[length] = lit.value; + // //position at the end of all literals + // sourceEnd = lit.sourceEnd; + // return this; + // } /** - * Add the lit source to mine, just as if it was mine + * Add the lit source to mine, just as if it was mine */ public ExtendedStringLiteral extendWith(StringLiteral lit) { - //uddate the source + // uddate the source int length = source.length; - System.arraycopy( - source, - 0, - source = new char[length + lit.source.length], - 0, - length); + System.arraycopy(source, 0, source = new char[length + + lit.source.length], 0, length); System.arraycopy(lit.source, 0, source, length, lit.source.length); - //position at the end of all literals + // position at the end of all literals sourceEnd = lit.sourceEnd; return this; } + public StringBuffer printExpression(int indent, StringBuffer output) { - return output.append("ExtendedStringLiteral{").append(source).append('}'); //$NON-NLS-1$ + return output + .append("ExtendedStringLiteral{").append(source).append('}'); //$NON-NLS-1$ } + public String toStringExpression() { - String str = "ExtendedStringLiteral{" + new String(source) + "}"; //$NON-NLS-2$ //$NON-NLS-1$ + String str = "ExtendedStringLiteral{" + new String(source) + "}"; //$NON-NLS-2$ //$NON-NLS-1$ return str; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/FalseLiteral.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/FalseLiteral.java index f9d289e..613b3ef 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/FalseLiteral.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/FalseLiteral.java @@ -16,52 +16,64 @@ import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class FalseLiteral extends MagicLiteral { - static final char[] source = {'f', 'a', 'l', 's', 'e'}; -public FalseLiteral(int s , int e) { - super(s,e); -} -public void computeConstant() { + static final char[] source = { 'f', 'a', 'l', 's', 'e' }; - constant = Constant.fromValue(false);} -/** - * Code generation for false literal - * - * @param currentScope net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream - * @param valueRequired boolean - */ -//public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) { -// int pc = codeStream.position; -// if (valueRequired) -// codeStream.iconst_0(); -// codeStream.recordPositionsFrom(pc, this.sourceStart); -//} -//public void generateOptimizedBoolean(BlockScope currentScope, CodeStream codeStream, Label trueLabel, Label falseLabel, boolean valueRequired) { -// -// // falseLabel being not nil means that we will not fall through into the FALSE case -// -// int pc = codeStream.position; -// if (valueRequired) { -// if (falseLabel != null) { -// // implicit falling through the TRUE case -// if (trueLabel == null) { -// codeStream.goto_(falseLabel); -// } -// } -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -//} -public TypeBinding literalType(BlockScope scope) { - return BooleanBinding; -} -/** - * - */ -public char[] source() { - return source; -} -public void traverse(IAbstractSyntaxTreeVisitor visitor, BlockScope scope) { - visitor.visit(this, scope); - visitor.endVisit(this, scope); -} + public FalseLiteral(int s, int e) { + super(s, e); + } + + public void computeConstant() { + + constant = Constant.fromValue(false); + } + + /** + * Code generation for false literal + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * @param valueRequired + * boolean + */ + // public void generateCode(BlockScope currentScope, CodeStream codeStream, + // boolean valueRequired) { + // int pc = codeStream.position; + // if (valueRequired) + // codeStream.iconst_0(); + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } + // public void generateOptimizedBoolean(BlockScope currentScope, CodeStream + // codeStream, Label trueLabel, Label falseLabel, boolean valueRequired) { + // + // // falseLabel being not nil means that we will not fall through into the + // FALSE case + // + // int pc = codeStream.position; + // if (valueRequired) { + // if (falseLabel != null) { + // // implicit falling through the TRUE case + // if (trueLabel == null) { + // codeStream.goto_(falseLabel); + // } + // } + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } + public TypeBinding literalType(BlockScope scope) { + return BooleanBinding; + } + + /** + * + */ + public char[] source() { + return source; + } + + public void traverse(IAbstractSyntaxTreeVisitor visitor, BlockScope scope) { + visitor.visit(this, scope); + visitor.endVisit(this, scope); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/FieldDeclaration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/FieldDeclaration.java index d561986..7268571 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/FieldDeclaration.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/FieldDeclaration.java @@ -20,216 +20,252 @@ import net.sourceforge.phpdt.internal.compiler.lookup.SourceTypeBinding; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class FieldDeclaration extends AbstractVariableDeclaration { - public FieldBinding binding; - - boolean hasBeenResolved = false; - - //allows to retrieve both the "type" part of the declaration (part1) - //and also the part that decribe the name and the init and optionally - //some other dimension ! .... - //public int[] a, b[] = X, c ; - //for b that would give for - // - part1 : public int[] - // - part2 : b[] = X, - - public int endPart1Position; - - public int endPart2Position; - - public FieldDeclaration() { - } - - public FieldDeclaration(char[] name, int sourceStart, int sourceEnd) { - - this.name = name; - - //due to some declaration like - // int x, y = 3, z , x ; - //the sourceStart and the sourceEnd is ONLY on the name - this.sourceStart = sourceStart; - this.sourceEnd = sourceEnd; - } - - public FieldDeclaration(Expression initialization, char[] name, int sourceStart, int sourceEnd) { - - this.initialization = initialization; - this.name = name; - - //due to some declaration like - // int x, y = 3, z , x ; - //the sourceStart and the sourceEnd is ONLY on the name - this.sourceStart = sourceStart; - this.sourceEnd = sourceEnd; - } - - public FlowInfo analyseCode(MethodScope initializationScope, FlowContext flowContext, FlowInfo flowInfo) { - - if (this.binding != null && this.binding.isPrivate() && !this.binding.isPrivateUsed()) { - if (!initializationScope.referenceCompilationUnit().compilationResult.hasSyntaxError()) { - initializationScope.problemReporter().unusedPrivateField(this); - } - } - // cannot define static non-constant field inside nested class - if (binding != null && binding.isValidBinding() && binding.isStatic() && binding.constant == NotAConstant - && binding.declaringClass.isNestedType() && binding.declaringClass.isClass() && !binding.declaringClass.isStatic()) { - initializationScope.problemReporter().unexpectedStaticModifierForField((SourceTypeBinding) binding.declaringClass, this); - } - - if (initialization != null) { - flowInfo = initialization.analyseCode(initializationScope, flowContext, flowInfo).unconditionalInits(); - flowInfo.markAsDefinitelyAssigned(binding); - } - return flowInfo; - } - - /** - * Code generation for a field declaration: standard assignment to a field - * - * @param currentScope - * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream - * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream - */ - // public void generateCode(BlockScope currentScope, CodeStream codeStream) { - // - // if ((bits & IsReachableMASK) == 0) { - // return; - // } - // // do not generate initialization code if final and static (constant is then - // // recorded inside the field itself). - // int pc = codeStream.position; - // boolean isStatic; - // if (initialization != null - // && !((isStatic = binding.isStatic()) && binding.constant != NotAConstant)) { - // // non-static field, need receiver - // if (!isStatic) - // codeStream.aload_0(); - // // generate initialization value - // initialization.generateCode(currentScope, codeStream, true); - // // store into field - // if (isStatic) { - // codeStream.putstatic(binding); - // } else { - // codeStream.putfield(binding); - // } - // } - // codeStream.recordPositionsFrom(pc, this.sourceStart); - // } - public TypeBinding getTypeBinding(Scope scope) { - - return type.getTypeBinding(scope); - } - - public boolean isField() { - - return true; - } - - public boolean isStatic() { - - if (binding != null) - return binding.isStatic(); - return (modifiers & AccStatic) != 0; - } - - public String name() { - - return String.valueOf(name); - } - - public void resolve(MethodScope initializationScope) { - - // the two could be regrouped into - // a single line but it is clearer to have two lines while the reason of their - // existence is not at all the same. See comment for the second one. - - //-------------------------------------------------------- - if (!this.hasBeenResolved && binding != null && this.binding.isValidBinding()) { - - this.hasBeenResolved = true; - - if (isTypeUseDeprecated(this.binding.type, initializationScope)) - initializationScope.problemReporter().deprecatedType(this.binding.type, this.type); - - this.type.resolvedType = this.binding.type; // update binding for type reference - - // the resolution of the initialization hasn't been done - if (this.initialization == null) { - this.binding.constant = Constant.NotAConstant; - } else { - int previous = initializationScope.fieldDeclarationIndex; - try { - initializationScope.fieldDeclarationIndex = this.binding.id; - - // break dead-lock cycles by forcing constant to NotAConstant - this.binding.constant = Constant.NotAConstant; - - TypeBinding typeBinding = this.binding.type; - TypeBinding initializationTypeBinding; - - if (initialization instanceof ArrayInitializer) { - - if ((initializationTypeBinding = this.initialization.resolveTypeExpecting(initializationScope, typeBinding)) != null) { - ((ArrayInitializer) this.initialization).binding = (ArrayBinding) initializationTypeBinding; - this.initialization.implicitWidening(typeBinding, initializationTypeBinding); - } - } else if ((initializationTypeBinding = initialization.resolveType(initializationScope)) != null) { - - if (this.initialization.isConstantValueOfTypeAssignableToType(initializationTypeBinding, typeBinding) - || (typeBinding.isBaseType() && BaseTypeBinding.isWidening(typeBinding.id, initializationTypeBinding.id))) { - - this.initialization.implicitWidening(typeBinding, initializationTypeBinding); - - } else if (initializationTypeBinding.isCompatibleWith(typeBinding)) { - this.initialization.implicitWidening(typeBinding, initializationTypeBinding); - - } else { - initializationScope.problemReporter().typeMismatchError(initializationTypeBinding, typeBinding, this); - } - if (this.binding.isFinal()) { // cast from constant actual type to variable type - this.binding.constant = this.initialization.constant.castTo((this.binding.type.id << 4) - + this.initialization.constant.typeID()); - } - } else { - this.binding.constant = NotAConstant; - } - } finally { - initializationScope.fieldDeclarationIndex = previous; - if (this.binding.constant == null) - this.binding.constant = Constant.NotAConstant; - } - } - } - } - - public void traverse(ASTVisitor visitor, MethodScope scope) { - - if (visitor.visit(this, scope)) { - type.traverse(visitor, scope); - if (initialization != null) - initialization.traverse(visitor, scope); - } - visitor.endVisit(this, scope); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object obj) { - if (obj instanceof FieldDeclaration) { - char[] objName = ((FieldDeclaration) obj).name; - if (name.length != objName.length) { - return false; - } - for (int i = 0; i < objName.length; i++) { - if (name[i] != objName[i]) { - return false; - } - } - return true; - } - return super.equals(obj); - } + public FieldBinding binding; + + boolean hasBeenResolved = false; + + // allows to retrieve both the "type" part of the declaration (part1) + // and also the part that decribe the name and the init and optionally + // some other dimension ! .... + // public int[] a, b[] = X, c ; + // for b that would give for + // - part1 : public int[] + // - part2 : b[] = X, + + public int endPart1Position; + + public int endPart2Position; + + public FieldDeclaration() { + } + + public FieldDeclaration(char[] name, int sourceStart, int sourceEnd) { + + this.name = name; + + // due to some declaration like + // int x, y = 3, z , x ; + // the sourceStart and the sourceEnd is ONLY on the name + this.sourceStart = sourceStart; + this.sourceEnd = sourceEnd; + } + + public FieldDeclaration(Expression initialization, char[] name, + int sourceStart, int sourceEnd) { + + this.initialization = initialization; + this.name = name; + + // due to some declaration like + // int x, y = 3, z , x ; + // the sourceStart and the sourceEnd is ONLY on the name + this.sourceStart = sourceStart; + this.sourceEnd = sourceEnd; + } + + public FlowInfo analyseCode(MethodScope initializationScope, + FlowContext flowContext, FlowInfo flowInfo) { + + if (this.binding != null && this.binding.isPrivate() + && !this.binding.isPrivateUsed()) { + if (!initializationScope.referenceCompilationUnit().compilationResult + .hasSyntaxError()) { + initializationScope.problemReporter().unusedPrivateField(this); + } + } + // cannot define static non-constant field inside nested class + if (binding != null && binding.isValidBinding() && binding.isStatic() + && binding.constant == NotAConstant + && binding.declaringClass.isNestedType() + && binding.declaringClass.isClass() + && !binding.declaringClass.isStatic()) { + initializationScope.problemReporter() + .unexpectedStaticModifierForField( + (SourceTypeBinding) binding.declaringClass, this); + } + + if (initialization != null) { + flowInfo = initialization.analyseCode(initializationScope, + flowContext, flowInfo).unconditionalInits(); + flowInfo.markAsDefinitelyAssigned(binding); + } + return flowInfo; + } + + /** + * Code generation for a field declaration: standard assignment to a field + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + */ + // public void generateCode(BlockScope currentScope, CodeStream codeStream) + // { + // + // if ((bits & IsReachableMASK) == 0) { + // return; + // } + // // do not generate initialization code if final and static (constant is + // then + // // recorded inside the field itself). + // int pc = codeStream.position; + // boolean isStatic; + // if (initialization != null + // && !((isStatic = binding.isStatic()) && binding.constant != + // NotAConstant)) { + // // non-static field, need receiver + // if (!isStatic) + // codeStream.aload_0(); + // // generate initialization value + // initialization.generateCode(currentScope, codeStream, true); + // // store into field + // if (isStatic) { + // codeStream.putstatic(binding); + // } else { + // codeStream.putfield(binding); + // } + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } + public TypeBinding getTypeBinding(Scope scope) { + + return type.getTypeBinding(scope); + } + + public boolean isField() { + + return true; + } + + public boolean isStatic() { + + if (binding != null) + return binding.isStatic(); + return (modifiers & AccStatic) != 0; + } + + public String name() { + + return String.valueOf(name); + } + + public void resolve(MethodScope initializationScope) { + + // the two could be regrouped into + // a single line but it is clearer to have two lines while the reason of + // their + // existence is not at all the same. See comment for the second one. + + // -------------------------------------------------------- + if (!this.hasBeenResolved && binding != null + && this.binding.isValidBinding()) { + + this.hasBeenResolved = true; + + if (isTypeUseDeprecated(this.binding.type, initializationScope)) + initializationScope.problemReporter().deprecatedType( + this.binding.type, this.type); + + this.type.resolvedType = this.binding.type; // update binding for + // type reference + + // the resolution of the initialization hasn't been done + if (this.initialization == null) { + this.binding.constant = Constant.NotAConstant; + } else { + int previous = initializationScope.fieldDeclarationIndex; + try { + initializationScope.fieldDeclarationIndex = this.binding.id; + + // break dead-lock cycles by forcing constant to + // NotAConstant + this.binding.constant = Constant.NotAConstant; + + TypeBinding typeBinding = this.binding.type; + TypeBinding initializationTypeBinding; + + if (initialization instanceof ArrayInitializer) { + + if ((initializationTypeBinding = this.initialization + .resolveTypeExpecting(initializationScope, + typeBinding)) != null) { + ((ArrayInitializer) this.initialization).binding = (ArrayBinding) initializationTypeBinding; + this.initialization.implicitWidening(typeBinding, + initializationTypeBinding); + } + } else if ((initializationTypeBinding = initialization + .resolveType(initializationScope)) != null) { + + if (this.initialization + .isConstantValueOfTypeAssignableToType( + initializationTypeBinding, typeBinding) + || (typeBinding.isBaseType() && BaseTypeBinding + .isWidening(typeBinding.id, + initializationTypeBinding.id))) { + + this.initialization.implicitWidening(typeBinding, + initializationTypeBinding); + + } else if (initializationTypeBinding + .isCompatibleWith(typeBinding)) { + this.initialization.implicitWidening(typeBinding, + initializationTypeBinding); + + } else { + initializationScope.problemReporter() + .typeMismatchError( + initializationTypeBinding, + typeBinding, this); + } + if (this.binding.isFinal()) { // cast from constant + // actual type to + // variable type + this.binding.constant = this.initialization.constant + .castTo((this.binding.type.id << 4) + + this.initialization.constant + .typeID()); + } + } else { + this.binding.constant = NotAConstant; + } + } finally { + initializationScope.fieldDeclarationIndex = previous; + if (this.binding.constant == null) + this.binding.constant = Constant.NotAConstant; + } + } + } + } + + public void traverse(ASTVisitor visitor, MethodScope scope) { + + if (visitor.visit(this, scope)) { + type.traverse(visitor, scope); + if (initialization != null) + initialization.traverse(visitor, scope); + } + visitor.endVisit(this, scope); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + public boolean equals(Object obj) { + if (obj instanceof FieldDeclaration) { + char[] objName = ((FieldDeclaration) obj).name; + if (name.length != objName.length) { + return false; + } + for (int i = 0; i < objName.length; i++) { + if (name[i] != objName[i]) { + return false; + } + } + return true; + } + return super.equals(obj); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/FieldReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/FieldReference.java index 22d3e6c..9fdf367 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/FieldReference.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/FieldReference.java @@ -27,96 +27,94 @@ import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class FieldReference extends Reference implements InvocationSite { public Expression receiver; + public char[] token; + public FieldBinding binding, codegenBinding; - public long nameSourcePosition; //(start<<32)+end + + public long nameSourcePosition; // (start<<32)+end + MethodBinding syntheticReadAccessor, syntheticWriteAccessor; + public TypeBinding receiverType; public FieldReference(char[] source, long pos) { token = source; nameSourcePosition = pos; - //by default the position are the one of the field (not true for super access) -// sourceStart = (int) (pos >>> 32); -// sourceEnd = (int) (pos & 0x00000000FFFFFFFFL); + // by default the position are the one of the field (not true for super + // access) + // sourceStart = (int) (pos >>> 32); + // sourceEnd = (int) (pos & 0x00000000FFFFFFFFL); sourceStart = (int) pos; sourceEnd = sourceStart + source.length; bits |= BindingIds.FIELD; } - public FlowInfo analyseAssignment( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo, - Assignment assignment, - boolean isCompound) { + public FlowInfo analyseAssignment(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo, Assignment assignment, + boolean isCompound) { // compound assignment extra work - if (isCompound) { // check the variable part is initialized if blank final - if (binding.isBlankFinal() - && receiver.isThis() - && currentScope.allowBlankFinalFieldAssignment(binding) - && (!flowInfo.isDefinitelyAssigned(binding))) { - currentScope.problemReporter().uninitializedBlankFinalField(binding, this); - // we could improve error msg here telling "cannot use compound assignment on final blank field" + if (isCompound) { // check the variable part is initialized if blank + // final + if (binding.isBlankFinal() && receiver.isThis() + && currentScope.allowBlankFinalFieldAssignment(binding) + && (!flowInfo.isDefinitelyAssigned(binding))) { + currentScope.problemReporter().uninitializedBlankFinalField( + binding, this); + // we could improve error msg here telling "cannot use compound + // assignment on final blank field" } manageSyntheticReadAccessIfNecessary(currentScope); } - flowInfo = - receiver - .analyseCode(currentScope, flowContext, flowInfo, !binding.isStatic()) - .unconditionalInits(); + flowInfo = receiver.analyseCode(currentScope, flowContext, flowInfo, + !binding.isStatic()).unconditionalInits(); if (assignment.expression != null) { - flowInfo = - assignment - .expression - .analyseCode(currentScope, flowContext, flowInfo) - .unconditionalInits(); + flowInfo = assignment.expression.analyseCode(currentScope, + flowContext, flowInfo).unconditionalInits(); } manageSyntheticWriteAccessIfNecessary(currentScope); - // check if assigning a final field + // check if assigning a final field if (binding.isFinal()) { // in a context where it can be assigned? - if (binding.isBlankFinal() - && !isCompound - && receiver.isThis() - && !(receiver instanceof QualifiedThisReference) - && ((receiver.bits & ParenthesizedMASK) == 0) // (this).x is forbidden - && currentScope.allowBlankFinalFieldAssignment(binding)) { + if (binding.isBlankFinal() && !isCompound && receiver.isThis() + && !(receiver instanceof QualifiedThisReference) + && ((receiver.bits & ParenthesizedMASK) == 0) // (this).x + // is + // forbidden + && currentScope.allowBlankFinalFieldAssignment(binding)) { if (flowInfo.isPotentiallyAssigned(binding)) { - currentScope.problemReporter().duplicateInitializationOfBlankFinalField( - binding, - this); + currentScope.problemReporter() + .duplicateInitializationOfBlankFinalField(binding, + this); } else { flowContext.recordSettingFinal(binding, this); } flowInfo.markAsDefinitelyAssigned(binding); } else { - // assigning a final field outside an initializer or constructor or wrong reference - currentScope.problemReporter().cannotAssignToFinalField(binding, this); + // assigning a final field outside an initializer or constructor + // or wrong reference + currentScope.problemReporter().cannotAssignToFinalField( + binding, this); } } return flowInfo; } - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { return analyseCode(currentScope, flowContext, flowInfo, true); } - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo, - boolean valueRequired) { + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo, boolean valueRequired) { - receiver.analyseCode(currentScope, flowContext, flowInfo, !binding.isStatic()); + receiver.analyseCode(currentScope, flowContext, flowInfo, !binding + .isStatic()); if (valueRequired) { manageSyntheticReadAccessIfNecessary(currentScope); } @@ -128,230 +126,242 @@ public class FieldReference extends Reference implements InvocationSite { return binding; } -// public void generateAssignment( -// BlockScope currentScope, -// CodeStream codeStream, -// Assignment assignment, -// boolean valueRequired) { -// -// receiver.generateCode( -// currentScope, -// codeStream, -// !this.codegenBinding.isStatic()); -// assignment.expression.generateCode(currentScope, codeStream, true); -// fieldStore( -// codeStream, -// this.codegenBinding, -// syntheticWriteAccessor, -// valueRequired); -// if (valueRequired) { -// codeStream.generateImplicitConversion(assignment.implicitConversion); -// } -// } + // public void generateAssignment( + // BlockScope currentScope, + // CodeStream codeStream, + // Assignment assignment, + // boolean valueRequired) { + // + // receiver.generateCode( + // currentScope, + // codeStream, + // !this.codegenBinding.isStatic()); + // assignment.expression.generateCode(currentScope, codeStream, true); + // fieldStore( + // codeStream, + // this.codegenBinding, + // syntheticWriteAccessor, + // valueRequired); + // if (valueRequired) { + // codeStream.generateImplicitConversion(assignment.implicitConversion); + // } + // } /** * Field reference code generation - * - * @param currentScope net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream - * @param valueRequired boolean + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * @param valueRequired + * boolean */ -// public void generateCode( -// BlockScope currentScope, -// CodeStream codeStream, -// boolean valueRequired) { -// -// int pc = codeStream.position; -// if (constant != NotAConstant) { -// if (valueRequired) { -// codeStream.generateConstant(constant, implicitConversion); -// } -// } else { -// boolean isStatic = this.codegenBinding.isStatic(); -// receiver.generateCode(currentScope, codeStream, !isStatic); -// if (valueRequired) { -// if (this.codegenBinding.constant == NotAConstant) { -// if (this.codegenBinding.declaringClass == null) { // array length -// codeStream.arraylength(); -// } else { -// if (syntheticReadAccessor == null) { -// if (isStatic) { -// codeStream.getstatic(this.codegenBinding); -// } else { -// codeStream.getfield(this.codegenBinding); -// } -// } else { -// codeStream.invokestatic(syntheticReadAccessor); -// } -// } -// codeStream.generateImplicitConversion(implicitConversion); -// } else { -// if (!isStatic) { -// codeStream.invokeObjectGetClass(); // perform null check -// codeStream.pop(); -// } -// codeStream.generateConstant(this.codegenBinding.constant, implicitConversion); -// } -// } else { -// if (!isStatic){ -// codeStream.invokeObjectGetClass(); // perform null check -// codeStream.pop(); -// } -// } -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } -// -// public void generateCompoundAssignment( -// BlockScope currentScope, -// CodeStream codeStream, -// Expression expression, -// int operator, -// int assignmentImplicitConversion, -// boolean valueRequired) { -// -// boolean isStatic; -// receiver.generateCode( -// currentScope, -// codeStream, -// !(isStatic = this.codegenBinding.isStatic())); -// if (isStatic) { -// if (syntheticReadAccessor == null) { -// codeStream.getstatic(this.codegenBinding); -// } else { -// codeStream.invokestatic(syntheticReadAccessor); -// } -// } else { -// codeStream.dup(); -// if (syntheticReadAccessor == null) { -// codeStream.getfield(this.codegenBinding); -// } else { -// codeStream.invokestatic(syntheticReadAccessor); -// } -// } -// int operationTypeID; -// if ((operationTypeID = implicitConversion >> 4) == T_String) { -// codeStream.generateStringAppend(currentScope, null, expression); -// } else { -// // promote the array reference to the suitable operation type -// codeStream.generateImplicitConversion(implicitConversion); -// // generate the increment value (will by itself be promoted to the operation value) -// if (expression == IntLiteral.One) { // prefix operation -// codeStream.generateConstant(expression.constant, implicitConversion); -// } else { -// expression.generateCode(currentScope, codeStream, true); -// } -// // perform the operation -// codeStream.sendOperator(operator, operationTypeID); -// // cast the value back to the array reference type -// codeStream.generateImplicitConversion(assignmentImplicitConversion); -// } -// fieldStore( -// codeStream, -// this.codegenBinding, -// syntheticWriteAccessor, -// valueRequired); -// } -// -// public void generatePostIncrement( -// BlockScope currentScope, -// CodeStream codeStream, -// CompoundAssignment postIncrement, -// boolean valueRequired) { -// -// boolean isStatic; -// receiver.generateCode( -// currentScope, -// codeStream, -// !(isStatic = this.codegenBinding.isStatic())); -// if (isStatic) { -// if (syntheticReadAccessor == null) { -// codeStream.getstatic(this.codegenBinding); -// } else { -// codeStream.invokestatic(syntheticReadAccessor); -// } -// } else { -// codeStream.dup(); -// if (syntheticReadAccessor == null) { -// codeStream.getfield(this.codegenBinding); -// } else { -// codeStream.invokestatic(syntheticReadAccessor); -// } -// } -// if (valueRequired) { -// if (isStatic) { -// if ((this.codegenBinding.type == LongBinding) -// || (this.codegenBinding.type == DoubleBinding)) { -// codeStream.dup2(); -// } else { -// codeStream.dup(); -// } -// } else { // Stack: [owner][old field value] ---> [old field value][owner][old field value] -// if ((this.codegenBinding.type == LongBinding) -// || (this.codegenBinding.type == DoubleBinding)) { -// codeStream.dup2_x1(); -// } else { -// codeStream.dup_x1(); -// } -// } -// } -// codeStream.generateConstant( -// postIncrement.expression.constant, -// implicitConversion); -// codeStream.sendOperator(postIncrement.operator, this.codegenBinding.type.id); -// codeStream.generateImplicitConversion( -// postIncrement.assignmentImplicitConversion); -// fieldStore(codeStream, this.codegenBinding, syntheticWriteAccessor, false); -// } - - public static final Constant getConstantFor( - FieldBinding binding, - Reference reference, - boolean isImplicit, - Scope referenceScope) { - - //propagation of the constant. - - //ref can be a FieldReference, a SingleNameReference or a QualifiedNameReference - //indexInQualification may have a value greater than zero only for QualifiednameReference - //if ref==null then indexInQualification==0 AND implicitReceiver == false. This case is a - //degenerated case where a fake reference field (null) - //is associted to a real FieldBinding in order - //to allow its constant computation using the regular path (in other words, find the fieldDeclaration - //and proceed to its type resolution). As implicitReceiver is false, no error reporting - //against ref will be used ==> no nullPointerException risk .... - - //special treatment for langage-built-in field (their declaring class is null) + // public void generateCode( + // BlockScope currentScope, + // CodeStream codeStream, + // boolean valueRequired) { + // + // int pc = codeStream.position; + // if (constant != NotAConstant) { + // if (valueRequired) { + // codeStream.generateConstant(constant, implicitConversion); + // } + // } else { + // boolean isStatic = this.codegenBinding.isStatic(); + // receiver.generateCode(currentScope, codeStream, !isStatic); + // if (valueRequired) { + // if (this.codegenBinding.constant == NotAConstant) { + // if (this.codegenBinding.declaringClass == null) { // array length + // codeStream.arraylength(); + // } else { + // if (syntheticReadAccessor == null) { + // if (isStatic) { + // codeStream.getstatic(this.codegenBinding); + // } else { + // codeStream.getfield(this.codegenBinding); + // } + // } else { + // codeStream.invokestatic(syntheticReadAccessor); + // } + // } + // codeStream.generateImplicitConversion(implicitConversion); + // } else { + // if (!isStatic) { + // codeStream.invokeObjectGetClass(); // perform null check + // codeStream.pop(); + // } + // codeStream.generateConstant(this.codegenBinding.constant, + // implicitConversion); + // } + // } else { + // if (!isStatic){ + // codeStream.invokeObjectGetClass(); // perform null check + // codeStream.pop(); + // } + // } + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } + // + // public void generateCompoundAssignment( + // BlockScope currentScope, + // CodeStream codeStream, + // Expression expression, + // int operator, + // int assignmentImplicitConversion, + // boolean valueRequired) { + // + // boolean isStatic; + // receiver.generateCode( + // currentScope, + // codeStream, + // !(isStatic = this.codegenBinding.isStatic())); + // if (isStatic) { + // if (syntheticReadAccessor == null) { + // codeStream.getstatic(this.codegenBinding); + // } else { + // codeStream.invokestatic(syntheticReadAccessor); + // } + // } else { + // codeStream.dup(); + // if (syntheticReadAccessor == null) { + // codeStream.getfield(this.codegenBinding); + // } else { + // codeStream.invokestatic(syntheticReadAccessor); + // } + // } + // int operationTypeID; + // if ((operationTypeID = implicitConversion >> 4) == T_String) { + // codeStream.generateStringAppend(currentScope, null, expression); + // } else { + // // promote the array reference to the suitable operation type + // codeStream.generateImplicitConversion(implicitConversion); + // // generate the increment value (will by itself be promoted to the + // operation value) + // if (expression == IntLiteral.One) { // prefix operation + // codeStream.generateConstant(expression.constant, implicitConversion); + // } else { + // expression.generateCode(currentScope, codeStream, true); + // } + // // perform the operation + // codeStream.sendOperator(operator, operationTypeID); + // // cast the value back to the array reference type + // codeStream.generateImplicitConversion(assignmentImplicitConversion); + // } + // fieldStore( + // codeStream, + // this.codegenBinding, + // syntheticWriteAccessor, + // valueRequired); + // } + // + // public void generatePostIncrement( + // BlockScope currentScope, + // CodeStream codeStream, + // CompoundAssignment postIncrement, + // boolean valueRequired) { + // + // boolean isStatic; + // receiver.generateCode( + // currentScope, + // codeStream, + // !(isStatic = this.codegenBinding.isStatic())); + // if (isStatic) { + // if (syntheticReadAccessor == null) { + // codeStream.getstatic(this.codegenBinding); + // } else { + // codeStream.invokestatic(syntheticReadAccessor); + // } + // } else { + // codeStream.dup(); + // if (syntheticReadAccessor == null) { + // codeStream.getfield(this.codegenBinding); + // } else { + // codeStream.invokestatic(syntheticReadAccessor); + // } + // } + // if (valueRequired) { + // if (isStatic) { + // if ((this.codegenBinding.type == LongBinding) + // || (this.codegenBinding.type == DoubleBinding)) { + // codeStream.dup2(); + // } else { + // codeStream.dup(); + // } + // } else { // Stack: [owner][old field value] ---> [old field + // value][owner][old field value] + // if ((this.codegenBinding.type == LongBinding) + // || (this.codegenBinding.type == DoubleBinding)) { + // codeStream.dup2_x1(); + // } else { + // codeStream.dup_x1(); + // } + // } + // } + // codeStream.generateConstant( + // postIncrement.expression.constant, + // implicitConversion); + // codeStream.sendOperator(postIncrement.operator, + // this.codegenBinding.type.id); + // codeStream.generateImplicitConversion( + // postIncrement.assignmentImplicitConversion); + // fieldStore(codeStream, this.codegenBinding, syntheticWriteAccessor, + // false); + // } + public static final Constant getConstantFor(FieldBinding binding, + Reference reference, boolean isImplicit, Scope referenceScope) { + + // propagation of the constant. + + // ref can be a FieldReference, a SingleNameReference or a + // QualifiedNameReference + // indexInQualification may have a value greater than zero only for + // QualifiednameReference + // if ref==null then indexInQualification==0 AND implicitReceiver == + // false. This case is a + // degenerated case where a fake reference field (null) + // is associted to a real FieldBinding in order + // to allow its constant computation using the regular path (in other + // words, find the fieldDeclaration + // and proceed to its type resolution). As implicitReceiver is false, no + // error reporting + // against ref will be used ==> no nullPointerException risk .... + + // special treatment for langage-built-in field (their declaring class + // is null) if (binding.declaringClass == null) { - //currently only one field "length" : the constant computation is never done + // currently only one field "length" : the constant computation is + // never done return NotAConstant; } if (!binding.isFinal()) { return binding.constant = NotAConstant; } if (binding.constant != null) { - if (isImplicit || (reference instanceof QualifiedNameReference - && binding == ((QualifiedNameReference)reference).binding)) { + if (isImplicit + || (reference instanceof QualifiedNameReference && binding == ((QualifiedNameReference) reference).binding)) { return binding.constant; } return NotAConstant; } - //The field has not been yet type checked. - //It also means that the field is not coming from a class that - //has already been compiled. It can only be from a class within - //compilation units to process. Thus the field is NOT from a BinaryTypeBinbing + // The field has not been yet type checked. + // It also means that the field is not coming from a class that + // has already been compiled. It can only be from a class within + // compilation units to process. Thus the field is NOT from a + // BinaryTypeBinbing SourceTypeBinding typeBinding = (SourceTypeBinding) binding.declaringClass; TypeDeclaration typeDecl = typeBinding.scope.referenceContext; FieldDeclaration fieldDecl = typeDecl.declarationOf(binding); - fieldDecl.resolve(binding.isStatic() //side effect on binding - ? typeDecl.staticInitializerScope - : typeDecl.initializerScope); + fieldDecl.resolve(binding.isStatic() // side effect on binding + ? typeDecl.staticInitializerScope + : typeDecl.initializerScope); - if (isImplicit || (reference instanceof QualifiedNameReference - && binding == ((QualifiedNameReference)reference).binding)) { + if (isImplicit + || (reference instanceof QualifiedNameReference && binding == ((QualifiedNameReference) reference).binding)) { return binding.constant; } return NotAConstant; @@ -368,134 +378,148 @@ public class FieldReference extends Reference implements InvocationSite { } /* - * No need to emulate access to protected fields since not implicitly accessed + * No need to emulate access to protected fields since not implicitly + * accessed */ public void manageSyntheticReadAccessIfNecessary(BlockScope currentScope) { if (binding.isPrivate()) { if ((currentScope.enclosingSourceType() != binding.declaringClass) - && (binding.constant == NotAConstant)) { - syntheticReadAccessor = - ((SourceTypeBinding) binding.declaringClass).addSyntheticMethod(binding, true); - currentScope.problemReporter().needToEmulateFieldReadAccess(binding, this); + && (binding.constant == NotAConstant)) { + syntheticReadAccessor = ((SourceTypeBinding) binding.declaringClass) + .addSyntheticMethod(binding, true); + currentScope.problemReporter().needToEmulateFieldReadAccess( + binding, this); return; } - } else if (receiver instanceof QualifiedSuperReference) { // qualified super + } else if (receiver instanceof QualifiedSuperReference) { // qualified + // super // qualified super need emulation always - SourceTypeBinding destinationType = - (SourceTypeBinding) (((QualifiedSuperReference) receiver) - .currentCompatibleType); - syntheticReadAccessor = destinationType.addSyntheticMethod(binding, true); - currentScope.problemReporter().needToEmulateFieldReadAccess(binding, this); + SourceTypeBinding destinationType = (SourceTypeBinding) (((QualifiedSuperReference) receiver).currentCompatibleType); + syntheticReadAccessor = destinationType.addSyntheticMethod(binding, + true); + currentScope.problemReporter().needToEmulateFieldReadAccess( + binding, this); return; } else if (binding.isProtected()) { SourceTypeBinding enclosingSourceType; if (((bits & DepthMASK) != 0) - && binding.declaringClass.getPackage() - != (enclosingSourceType = currentScope.enclosingSourceType()).getPackage()) { - - SourceTypeBinding currentCompatibleType = - (SourceTypeBinding) enclosingSourceType.enclosingTypeAt( - (bits & DepthMASK) >> DepthSHIFT); - syntheticReadAccessor = currentCompatibleType.addSyntheticMethod(binding, true); - currentScope.problemReporter().needToEmulateFieldReadAccess(binding, this); + && binding.declaringClass.getPackage() != (enclosingSourceType = currentScope + .enclosingSourceType()).getPackage()) { + + SourceTypeBinding currentCompatibleType = (SourceTypeBinding) enclosingSourceType + .enclosingTypeAt((bits & DepthMASK) >> DepthSHIFT); + syntheticReadAccessor = currentCompatibleType + .addSyntheticMethod(binding, true); + currentScope.problemReporter().needToEmulateFieldReadAccess( + binding, this); return; } } // if the binding declaring class is not visible, need special action - // for runtime compatibility on 1.2 VMs : change the declaring class of the binding - // NOTE: from target 1.2 on, field's declaring class is touched if any different from receiver type -// if (binding.declaringClass != this.receiverType -// && !this.receiverType.isArrayType() -// && binding.declaringClass != null // array.length -// && binding.constant == NotAConstant -// && ((currentScope.environment().options.targetJDK >= CompilerOptions.JDK1_2 -// && binding.declaringClass.id != T_Object) -// //no change for Object fields (in case there was) -// || !binding.declaringClass.canBeSeenBy(currentScope))) { -// this.codegenBinding = -// currentScope.enclosingSourceType().getUpdatedFieldBinding( -// binding, -// (ReferenceBinding) this.receiverType); -// } + // for runtime compatibility on 1.2 VMs : change the declaring class of + // the binding + // NOTE: from target 1.2 on, field's declaring class is touched if any + // different from receiver type + // if (binding.declaringClass != this.receiverType + // && !this.receiverType.isArrayType() + // && binding.declaringClass != null // array.length + // && binding.constant == NotAConstant + // && ((currentScope.environment().options.targetJDK >= + // CompilerOptions.JDK1_2 + // && binding.declaringClass.id != T_Object) + // //no change for Object fields (in case there was) + // || !binding.declaringClass.canBeSeenBy(currentScope))) { + // this.codegenBinding = + // currentScope.enclosingSourceType().getUpdatedFieldBinding( + // binding, + // (ReferenceBinding) this.receiverType); + // } } /* - * No need to emulate access to protected fields since not implicitly accessed + * No need to emulate access to protected fields since not implicitly + * accessed */ public void manageSyntheticWriteAccessIfNecessary(BlockScope currentScope) { if (binding.isPrivate()) { if (currentScope.enclosingSourceType() != binding.declaringClass) { - syntheticWriteAccessor = - ((SourceTypeBinding) binding.declaringClass).addSyntheticMethod(binding, false); - currentScope.problemReporter().needToEmulateFieldWriteAccess(binding, this); + syntheticWriteAccessor = ((SourceTypeBinding) binding.declaringClass) + .addSyntheticMethod(binding, false); + currentScope.problemReporter().needToEmulateFieldWriteAccess( + binding, this); return; } - } else if (receiver instanceof QualifiedSuperReference) { // qualified super + } else if (receiver instanceof QualifiedSuperReference) { // qualified + // super // qualified super need emulation always - SourceTypeBinding destinationType = - (SourceTypeBinding) (((QualifiedSuperReference) receiver) - .currentCompatibleType); - syntheticWriteAccessor = destinationType.addSyntheticMethod(binding, false); - currentScope.problemReporter().needToEmulateFieldWriteAccess(binding, this); + SourceTypeBinding destinationType = (SourceTypeBinding) (((QualifiedSuperReference) receiver).currentCompatibleType); + syntheticWriteAccessor = destinationType.addSyntheticMethod( + binding, false); + currentScope.problemReporter().needToEmulateFieldWriteAccess( + binding, this); return; } else if (binding.isProtected()) { SourceTypeBinding enclosingSourceType; if (((bits & DepthMASK) != 0) - && binding.declaringClass.getPackage() - != (enclosingSourceType = currentScope.enclosingSourceType()).getPackage()) { - - SourceTypeBinding currentCompatibleType = - (SourceTypeBinding) enclosingSourceType.enclosingTypeAt( - (bits & DepthMASK) >> DepthSHIFT); - syntheticWriteAccessor = - currentCompatibleType.addSyntheticMethod(binding, false); - currentScope.problemReporter().needToEmulateFieldWriteAccess(binding, this); + && binding.declaringClass.getPackage() != (enclosingSourceType = currentScope + .enclosingSourceType()).getPackage()) { + + SourceTypeBinding currentCompatibleType = (SourceTypeBinding) enclosingSourceType + .enclosingTypeAt((bits & DepthMASK) >> DepthSHIFT); + syntheticWriteAccessor = currentCompatibleType + .addSyntheticMethod(binding, false); + currentScope.problemReporter().needToEmulateFieldWriteAccess( + binding, this); return; } } // if the binding declaring class is not visible, need special action - // for runtime compatibility on 1.2 VMs : change the declaring class of the binding - // NOTE: from target 1.2 on, field's declaring class is touched if any different from receiver type -// if (binding.declaringClass != this.receiverType -// && !this.receiverType.isArrayType() -// && binding.declaringClass != null // array.length -// && binding.constant == NotAConstant -// && ((currentScope.environment().options.targetJDK >= CompilerOptions.JDK1_2 -// && binding.declaringClass.id != T_Object) -// //no change for Object fields (in case there was) -// || !binding.declaringClass.canBeSeenBy(currentScope))) { -// this.codegenBinding = -// currentScope.enclosingSourceType().getUpdatedFieldBinding( -// binding, -// (ReferenceBinding) this.receiverType); -// } + // for runtime compatibility on 1.2 VMs : change the declaring class of + // the binding + // NOTE: from target 1.2 on, field's declaring class is touched if any + // different from receiver type + // if (binding.declaringClass != this.receiverType + // && !this.receiverType.isArrayType() + // && binding.declaringClass != null // array.length + // && binding.constant == NotAConstant + // && ((currentScope.environment().options.targetJDK >= + // CompilerOptions.JDK1_2 + // && binding.declaringClass.id != T_Object) + // //no change for Object fields (in case there was) + // || !binding.declaringClass.canBeSeenBy(currentScope))) { + // this.codegenBinding = + // currentScope.enclosingSourceType().getUpdatedFieldBinding( + // binding, + // (ReferenceBinding) this.receiverType); + // } } public TypeBinding resolveType(BlockScope scope) { // Answer the signature type of the field. // constants are propaged when the field is final - // and initialized with a (compile time) constant + // and initialized with a (compile time) constant - // regular receiver reference + // regular receiver reference this.receiverType = receiver.resolveType(scope); if (this.receiverType == null) { constant = NotAConstant; return null; } - // the case receiverType.isArrayType and token = 'length' is handled by the scope API - this.codegenBinding = - this.binding = scope.getField(this.receiverType, token, this); + // the case receiverType.isArrayType and token = 'length' is handled by + // the scope API + this.codegenBinding = this.binding = scope.getField(this.receiverType, + token, this); if (!binding.isValidBinding()) { constant = NotAConstant; scope.problemReporter().invalidField(this, this.receiverType); @@ -506,17 +530,17 @@ public class FieldReference extends Reference implements InvocationSite { scope.problemReporter().deprecatedField(binding, this); boolean isImplicitThisRcv = receiver.isImplicitThis(); - constant = FieldReference.getConstantFor(binding, this, isImplicitThisRcv, scope); + constant = FieldReference.getConstantFor(binding, this, + isImplicitThisRcv, scope); if (!isImplicitThisRcv) { constant = NotAConstant; } if (binding.isStatic()) { - // static field accessed through receiver? legal but unoptimal (optional warning) - if (!(isImplicitThisRcv - || receiver.isSuper() - || (receiver instanceof NameReference - && (((NameReference) receiver).bits & BindingIds.TYPE) != 0))) { - scope.problemReporter().unnecessaryReceiverForStaticField(this, binding); + // static field accessed through receiver? legal but unoptimal + // (optional warning) + if (!(isImplicitThisRcv || receiver.isSuper() || (receiver instanceof NameReference && (((NameReference) receiver).bits & BindingIds.TYPE) != 0))) { + scope.problemReporter().unnecessaryReceiverForStaticField(this, + binding); } } return this.resolvedType = binding.type; @@ -528,7 +552,7 @@ public class FieldReference extends Reference implements InvocationSite { public void setDepth(int depth) { - bits &= ~DepthMASK; // flush previous depth if any + bits &= ~DepthMASK; // flush previous depth if any if (depth > 0) { bits |= (depth & 0xFF) << DepthSHIFT; // encoded on 8 bits } @@ -537,14 +561,16 @@ public class FieldReference extends Reference implements InvocationSite { public void setFieldIndex(int index) { // ignored } + public StringBuffer printExpression(int indent, StringBuffer output) { return receiver.printExpression(0, output).append('.').append(token); } + public String toStringExpression() { return receiver.toString() + "." //$NON-NLS-1$ - + new String(token); + + new String(token); } public void traverse(ASTVisitor visitor, BlockScope scope) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/FloatLiteral.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/FloatLiteral.java index 64035d5..cbffad5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/FloatLiteral.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/FloatLiteral.java @@ -15,71 +15,82 @@ import net.sourceforge.phpdt.internal.compiler.impl.Constant; import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; - public class FloatLiteral extends NumberLiteral { float value; - final static float Float_MIN_VALUE = Float.intBitsToFloat(1); // work-around VAJ problem 1F6IGUU -public FloatLiteral(char[] token, int s, int e) { - super(token, s,e); -} -public void computeConstant() { - - //the source is correctly formated so the exception should never occurs - Float computedValue; - try { - computedValue = Float.valueOf(String.valueOf(source)); - } catch (NumberFormatException e) { - return; - } + final static float Float_MIN_VALUE = Float.intBitsToFloat(1); // work-around + // VAJ + // problem + // 1F6IGUU - if (computedValue.doubleValue() > Float.MAX_VALUE){ - return; //may be Infinity + public FloatLiteral(char[] token, int s, int e) { + super(token, s, e); } - if (computedValue.floatValue() < Float_MIN_VALUE){ - // see 1F6IGUU - //only a true 0 can be made of zeros - //1.00000000e-46f is illegal .... - label : for (int i = 0; i < source.length; i++) { - switch (source[i]) { - case '.' : - case 'f' : - case 'F' : - case '0' : - break; - case 'e' : - case 'E' : - break label; //exposant are valid !.... - default : - return; //error + public void computeConstant() { + + // the source is correctly formated so the exception should never occurs + Float computedValue; + try { + computedValue = Float.valueOf(String.valueOf(source)); + } catch (NumberFormatException e) { + return; + } + + if (computedValue.doubleValue() > Float.MAX_VALUE) { + return; // may be Infinity + } + if (computedValue.floatValue() < Float_MIN_VALUE) { + // see 1F6IGUU + // only a true 0 can be made of zeros + // 1.00000000e-46f is illegal .... + label: for (int i = 0; i < source.length; i++) { + switch (source[i]) { + case '.': + case 'f': + case 'F': + case '0': + break; + case 'e': + case 'E': + break label; // exposant are valid !.... + default: + return; // error + + } } } + constant = Constant.fromValue(value = computedValue.floatValue()); + } + + /** + * Code generation for float literal + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * @param valueRequired + * boolean + */ + // public void generateCode(BlockScope currentScope, CodeStream codeStream, + // boolean valueRequired) { + // int pc = codeStream.position; + // if (valueRequired) + // if ((implicitConversion >> 4) == T_float) + // codeStream.generateInlinedValue(value); + // else + // codeStream.generateConstant(constant, implicitConversion); + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } + public TypeBinding literalType(BlockScope scope) { + return FloatBinding; + } + + public void traverse(IAbstractSyntaxTreeVisitor visitor, + BlockScope blockScope) { + visitor.visit(this, blockScope); + visitor.endVisit(this, blockScope); } - constant = Constant.fromValue(value = computedValue.floatValue()); -} -/** - * Code generation for float literal - * - * @param currentScope net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream - * @param valueRequired boolean - */ -//public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) { -// int pc = codeStream.position; -// if (valueRequired) -// if ((implicitConversion >> 4) == T_float) -// codeStream.generateInlinedValue(value); -// else -// codeStream.generateConstant(constant, implicitConversion); -// codeStream.recordPositionsFrom(pc, this.sourceStart); -//} -public TypeBinding literalType(BlockScope scope) { - return FloatBinding; -} -public void traverse(IAbstractSyntaxTreeVisitor visitor, BlockScope blockScope) { - visitor.visit(this, blockScope); - visitor.endVisit(this, blockScope); -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ForStatement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ForStatement.java index 7d0f14c..bfef122 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ForStatement.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ForStatement.java @@ -20,32 +20,34 @@ import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class ForStatement extends Statement { - + public Statement[] initializations; + public Expression condition; + public Statement[] increments; + public Statement action; - //when there is no local declaration, there is no need of a new scope - //scope is positionned either to a new scope, or to the "upper"scope (see resolveType) + // when there is no local declaration, there is no need of a new scope + // scope is positionned either to a new scope, or to the "upper"scope (see + // resolveType) public boolean neededScope; + public BlockScope scope; private Label breakLabel, continueLabel; // for local variables table attributes int preCondInitStateIndex = -1; + int condIfTrueInitStateIndex = -1; + int mergedInitStateIndex = -1; - public ForStatement( - Statement[] initializations, - Expression condition, - Statement[] increments, - Statement action, - boolean neededScope, - int s, - int e) { + public ForStatement(Statement[] initializations, Expression condition, + Statement[] increments, Statement action, boolean neededScope, + int s, int e) { this.sourceStart = s; this.sourceEnd = e; @@ -56,11 +58,9 @@ public class ForStatement extends Statement { this.neededScope = neededScope; } - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { - + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { + breakLabel = new Label(); continueLabel = new Label(); @@ -68,199 +68,219 @@ public class ForStatement extends Statement { if (initializations != null) { int count = initializations.length, i = 0; while (i < count) { - flowInfo = initializations[i++].analyseCode(scope, flowContext, flowInfo); + flowInfo = initializations[i++].analyseCode(scope, flowContext, + flowInfo); } } - preCondInitStateIndex = - currentScope.methodScope().recordInitializationStates(flowInfo); + preCondInitStateIndex = currentScope.methodScope() + .recordInitializationStates(flowInfo); Constant cst = this.condition == null ? null : this.condition.constant; - boolean isConditionTrue = cst == null || (cst != NotAConstant && cst.booleanValue() == true); - boolean isConditionFalse = cst != null && (cst != NotAConstant && cst.booleanValue() == false); + boolean isConditionTrue = cst == null + || (cst != NotAConstant && cst.booleanValue() == true); + boolean isConditionFalse = cst != null + && (cst != NotAConstant && cst.booleanValue() == false); + + cst = this.condition == null ? null : this.condition + .optimizedBooleanConstant(); + boolean isConditionOptimizedTrue = cst == null + || (cst != NotAConstant && cst.booleanValue() == true); + boolean isConditionOptimizedFalse = cst != null + && (cst != NotAConstant && cst.booleanValue() == false); - cst = this.condition == null ? null : this.condition.optimizedBooleanConstant(); - boolean isConditionOptimizedTrue = cst == null || (cst != NotAConstant && cst.booleanValue() == true); - boolean isConditionOptimizedFalse = cst != null && (cst != NotAConstant && cst.booleanValue() == false); - // process the condition LoopingFlowContext condLoopContext = null; if (condition != null) { if (!isConditionTrue) { - flowInfo = - condition.analyseCode( - scope, - (condLoopContext = - new LoopingFlowContext(flowContext, this, null, null, scope)), - flowInfo); + flowInfo = condition.analyseCode(scope, + (condLoopContext = new LoopingFlowContext(flowContext, + this, null, null, scope)), flowInfo); } } // process the action LoopingFlowContext loopingContext; FlowInfo actionInfo; - if (action == null ){ -// || (action.isEmptyBlock() && currentScope.environment().options.complianceLevel <= CompilerOptions.JDK1_3)) { + if (action == null) { + // || (action.isEmptyBlock() && + // currentScope.environment().options.complianceLevel <= + // CompilerOptions.JDK1_3)) { if (condLoopContext != null) - condLoopContext.complainOnFinalAssignmentsInLoop(scope, flowInfo); + condLoopContext.complainOnFinalAssignmentsInLoop(scope, + flowInfo); if (isConditionTrue) { return FlowInfo.DEAD_END; } else { - if (isConditionFalse){ + if (isConditionFalse) { continueLabel = null; // for(;false;p()); } actionInfo = flowInfo.initsWhenTrue().copy(); - loopingContext = - new LoopingFlowContext(flowContext, this, breakLabel, continueLabel, scope); + loopingContext = new LoopingFlowContext(flowContext, this, + breakLabel, continueLabel, scope); } } else { - loopingContext = - new LoopingFlowContext(flowContext, this, breakLabel, continueLabel, scope); + loopingContext = new LoopingFlowContext(flowContext, this, + breakLabel, continueLabel, scope); FlowInfo initsWhenTrue = flowInfo.initsWhenTrue(); - condIfTrueInitStateIndex = - currentScope.methodScope().recordInitializationStates(initsWhenTrue); + condIfTrueInitStateIndex = currentScope.methodScope() + .recordInitializationStates(initsWhenTrue); - if (isConditionFalse) { - actionInfo = FlowInfo.DEAD_END; - } else { - actionInfo = initsWhenTrue.copy(); - if (isConditionOptimizedFalse){ - actionInfo.setReachMode(FlowInfo.UNREACHABLE); - } + if (isConditionFalse) { + actionInfo = FlowInfo.DEAD_END; + } else { + actionInfo = initsWhenTrue.copy(); + if (isConditionOptimizedFalse) { + actionInfo.setReachMode(FlowInfo.UNREACHABLE); } + } if (!actionInfo.complainIfUnreachable(action, scope, false)) { - actionInfo = action.analyseCode(scope, loopingContext, actionInfo); + actionInfo = action.analyseCode(scope, loopingContext, + actionInfo); } - // code generation can be optimized when no need to continue in the loop - if (!actionInfo.isReachable() && !loopingContext.initsOnContinue.isReachable()) { + // code generation can be optimized when no need to continue in the + // loop + if (!actionInfo.isReachable() + && !loopingContext.initsOnContinue.isReachable()) { continueLabel = null; } else { if (condLoopContext != null) - condLoopContext.complainOnFinalAssignmentsInLoop(scope, flowInfo); - loopingContext.complainOnFinalAssignmentsInLoop(scope, actionInfo); - actionInfo = - actionInfo.mergedWith(loopingContext.initsOnContinue.unconditionalInits()); + condLoopContext.complainOnFinalAssignmentsInLoop(scope, + flowInfo); + loopingContext.complainOnFinalAssignmentsInLoop(scope, + actionInfo); + actionInfo = actionInfo + .mergedWith(loopingContext.initsOnContinue + .unconditionalInits()); // for increments } } if ((continueLabel != null) && (increments != null)) { - LoopingFlowContext loopContext = - new LoopingFlowContext(flowContext, this, null, null, scope); + LoopingFlowContext loopContext = new LoopingFlowContext( + flowContext, this, null, null, scope); int i = 0, count = increments.length; while (i < count) - actionInfo = increments[i++].analyseCode(scope, loopContext, actionInfo); + actionInfo = increments[i++].analyseCode(scope, loopContext, + actionInfo); loopContext.complainOnFinalAssignmentsInLoop(scope, actionInfo); } // infinite loop FlowInfo mergedInfo; if (isConditionOptimizedTrue) { - mergedInitStateIndex = - currentScope.methodScope().recordInitializationStates( - mergedInfo = loopingContext.initsOnBreak); + mergedInitStateIndex = currentScope.methodScope() + .recordInitializationStates( + mergedInfo = loopingContext.initsOnBreak); return mergedInfo; } - //end of loop: either condition false or break - mergedInfo = - flowInfo.initsWhenFalse().unconditionalInits().mergedWith( + // end of loop: either condition false or break + mergedInfo = flowInfo.initsWhenFalse().unconditionalInits().mergedWith( loopingContext.initsOnBreak.unconditionalInits()); - if (isConditionOptimizedTrue && continueLabel == null){ + if (isConditionOptimizedTrue && continueLabel == null) { mergedInfo.setReachMode(FlowInfo.UNREACHABLE); } - mergedInitStateIndex = - currentScope.methodScope().recordInitializationStates(mergedInfo); + mergedInitStateIndex = currentScope.methodScope() + .recordInitializationStates(mergedInfo); return mergedInfo; } /** * For statement code generation - * - * @param currentScope net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream */ -// public void generateCode(BlockScope currentScope, CodeStream codeStream) { -// -// if ((bits & IsReachableMASK) == 0) { -// return; -// } -// int pc = codeStream.position; -// -// // generate the initializations -// if (initializations != null) { -// for (int i = 0, max = initializations.length; i < max; i++) { -// initializations[i].generateCode(scope, codeStream); -// } -// } -// -// // label management -// Label actionLabel = new Label(codeStream); -// Label conditionLabel = new Label(codeStream); -// breakLabel.codeStream = codeStream; -// if (continueLabel != null) { -// continueLabel.codeStream = codeStream; -// } -// // jump over the actionBlock -// if ((condition != null) -// && (condition.constant == NotAConstant) -// && !((action == null || action.isEmptyBlock()) && (increments == null))) { -// int jumpPC = codeStream.position; -// codeStream.goto_(conditionLabel); -// codeStream.recordPositionsFrom(jumpPC, condition.sourceStart); -// } -// // generate the loop action -// actionLabel.place(); -// if (action != null) { -// // Required to fix 1PR0XVS: LFRE:WINNT - Compiler: variable table for method appears incorrect -// if (condIfTrueInitStateIndex != -1) { -// // insert all locals initialized inside the condition into the action generated prior to the condition -// codeStream.addDefinitelyAssignedVariables( -// currentScope, -// condIfTrueInitStateIndex); -// } -// action.generateCode(scope, codeStream); -// } -// // continuation point -// if (continueLabel != null) { -// continueLabel.place(); -// // generate the increments for next iteration -// if (increments != null) { -// for (int i = 0, max = increments.length; i < max; i++) { -// increments[i].generateCode(scope, codeStream); -// } -// } -// } -// -// // May loose some local variable initializations : affecting the local variable attributes -// if (preCondInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// preCondInitStateIndex); -// } -// -// // generate the condition -// conditionLabel.place(); -// if ((condition != null) && (condition.constant == NotAConstant)) { -// condition.generateOptimizedBoolean(scope, codeStream, actionLabel, null, true); -// } else { -// if (continueLabel != null) { -// codeStream.goto_(actionLabel); -// } -// } -// breakLabel.place(); -// -// // May loose some local variable initializations : affecting the local variable attributes -// if (neededScope) { -// codeStream.exitUserScope(scope); -// } -// if (mergedInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// mergedInitStateIndex); -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } - + // public void generateCode(BlockScope currentScope, CodeStream codeStream) + // { + // + // if ((bits & IsReachableMASK) == 0) { + // return; + // } + // int pc = codeStream.position; + // + // // generate the initializations + // if (initializations != null) { + // for (int i = 0, max = initializations.length; i < max; i++) { + // initializations[i].generateCode(scope, codeStream); + // } + // } + // + // // label management + // Label actionLabel = new Label(codeStream); + // Label conditionLabel = new Label(codeStream); + // breakLabel.codeStream = codeStream; + // if (continueLabel != null) { + // continueLabel.codeStream = codeStream; + // } + // // jump over the actionBlock + // if ((condition != null) + // && (condition.constant == NotAConstant) + // && !((action == null || action.isEmptyBlock()) && (increments == null))) + // { + // int jumpPC = codeStream.position; + // codeStream.goto_(conditionLabel); + // codeStream.recordPositionsFrom(jumpPC, condition.sourceStart); + // } + // // generate the loop action + // actionLabel.place(); + // if (action != null) { + // // Required to fix 1PR0XVS: LFRE:WINNT - Compiler: variable table for + // method appears incorrect + // if (condIfTrueInitStateIndex != -1) { + // // insert all locals initialized inside the condition into the action + // generated prior to the condition + // codeStream.addDefinitelyAssignedVariables( + // currentScope, + // condIfTrueInitStateIndex); + // } + // action.generateCode(scope, codeStream); + // } + // // continuation point + // if (continueLabel != null) { + // continueLabel.place(); + // // generate the increments for next iteration + // if (increments != null) { + // for (int i = 0, max = increments.length; i < max; i++) { + // increments[i].generateCode(scope, codeStream); + // } + // } + // } + // + // // May loose some local variable initializations : affecting the local + // variable attributes + // if (preCondInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // preCondInitStateIndex); + // } + // + // // generate the condition + // conditionLabel.place(); + // if ((condition != null) && (condition.constant == NotAConstant)) { + // condition.generateOptimizedBoolean(scope, codeStream, actionLabel, null, + // true); + // } else { + // if (continueLabel != null) { + // codeStream.goto_(actionLabel); + // } + // } + // breakLabel.place(); + // + // // May loose some local variable initializations : affecting the local + // variable attributes + // if (neededScope) { + // codeStream.exitUserScope(scope); + // } + // if (mergedInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // mergedInitStateIndex); + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } public void resetStateForCodeGeneration() { if (this.breakLabel != null) { this.breakLabel.resetStateForCodeGeneration(); @@ -269,30 +289,34 @@ public class ForStatement extends Statement { this.continueLabel.resetStateForCodeGeneration(); } } + public StringBuffer printStatement(int tab, StringBuffer output) { printIndent(tab, output).append("for ("); //$NON-NLS-1$ - //inits + // inits if (initializations != null) { for (int i = 0; i < initializations.length; i++) { - //nice only with expressions - if (i > 0) output.append(", "); //$NON-NLS-1$ + // nice only with expressions + if (i > 0) + output.append(", "); //$NON-NLS-1$ initializations[i].print(0, output); } } output.append("; "); //$NON-NLS-1$ - //cond - if (condition != null) condition.printExpression(0, output); + // cond + if (condition != null) + condition.printExpression(0, output); output.append("; "); //$NON-NLS-1$ - //updates + // updates if (increments != null) { for (int i = 0; i < increments.length; i++) { - if (i > 0) output.append(", "); //$NON-NLS-1$ + if (i > 0) + output.append(", "); //$NON-NLS-1$ increments[i].print(0, output); } } output.append(") "); //$NON-NLS-1$ - //block + // block if (action == null) output.append(';'); else { @@ -301,6 +325,7 @@ public class ForStatement extends Statement { } return output.append(';'); } + public void resolve(BlockScope upperScope) { // use the scope that will hold the init declarations @@ -309,7 +334,8 @@ public class ForStatement extends Statement { for (int i = 0, length = initializations.length; i < length; i++) initializations[i].resolve(scope); if (condition != null) { - TypeBinding type = condition.resolveTypeExpecting(scope, BooleanBinding); + TypeBinding type = condition.resolveTypeExpecting(scope, + BooleanBinding); condition.implicitWidening(type, type); } if (increments != null) @@ -323,42 +349,43 @@ public class ForStatement extends Statement { String s = tabString(tab) + "for ("; //$NON-NLS-1$ if (!neededScope) - s = s + " //--NO upperscope scope needed\n" + tabString(tab) + " "; //$NON-NLS-2$ //$NON-NLS-1$ - //inits + s = s + + " //--NO upperscope scope needed\n" + tabString(tab) + " "; //$NON-NLS-2$ //$NON-NLS-1$ + // inits if (initializations != null) { for (int i = 0; i < initializations.length; i++) { - //nice only with expressions + // nice only with expressions s = s + initializations[i].toString(0); if (i != (initializations.length - 1)) s = s + " , "; //$NON-NLS-1$ } - }; + } + ; s = s + "; "; //$NON-NLS-1$ - //cond + // cond if (condition != null) s = s + condition.toStringExpression(); s = s + "; "; //$NON-NLS-1$ - //updates + // updates if (increments != null) { for (int i = 0; i < increments.length; i++) { - //nice only with expressions + // nice only with expressions s = s + increments[i].toString(0); if (i != (increments.length - 1)) s = s + " , "; //$NON-NLS-1$ } - }; + } + ; s = s + ") "; //$NON-NLS-1$ - //block + // block if (action == null) s = s + "{}"; //$NON-NLS-1$ else s = s + "\n" + action.toString(tab + 1); //$NON-NLS-1$ return s; } - - public void traverse( - ASTVisitor visitor, - BlockScope blockScope) { + + public void traverse(ASTVisitor visitor, BlockScope blockScope) { if (visitor.visit(this, blockScope)) { if (initializations != null) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/IfStatement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/IfStatement.java index 7959ba7..39d5ae0 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/IfStatement.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/IfStatement.java @@ -18,29 +18,33 @@ import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class IfStatement extends Statement { - - //this class represents the case of only one statement in - //either else and/or then branches. + + // this class represents the case of only one statement in + // either else and/or then branches. public Expression condition; + public Statement thenStatement; + public Statement elseStatement; + public Expression[] elseifConditions; + public Statement[] elseifStatements; + public boolean checkUnreachable; + boolean thenExit; - // for local variables table attributes int thenInitStateIndex = -1; + int elseInitStateIndex = -1; + int mergedInitStateIndex = -1; - public IfStatement( - Expression condition, - Statement thenStatement, - int s, - int e) { + public IfStatement(Expression condition, Statement thenStatement, int s, + int e) { this.condition = condition; this.thenStatement = thenStatement; @@ -49,12 +53,8 @@ public class IfStatement extends Statement { checkUnreachable = true; } - public IfStatement( - Expression condition, - Statement thenStatement, - Statement elseStatement, - int s, - int e) { + public IfStatement(Expression condition, Statement thenStatement, + Statement elseStatement, int s, int e) { this.condition = condition; this.thenStatement = thenStatement; @@ -64,186 +64,201 @@ public class IfStatement extends Statement { checkUnreachable = true; } - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { // process the condition flowInfo = condition.analyseCode(currentScope, flowContext, flowInfo); Constant cst = this.condition.optimizedBooleanConstant(); - boolean isConditionOptimizedTrue = cst != NotAConstant && cst.booleanValue() == true; - boolean isConditionOptimizedFalse = cst != NotAConstant && cst.booleanValue() == false; - + boolean isConditionOptimizedTrue = cst != NotAConstant + && cst.booleanValue() == true; + boolean isConditionOptimizedFalse = cst != NotAConstant + && cst.booleanValue() == false; + // process the THEN part FlowInfo thenFlowInfo = flowInfo.initsWhenTrue().copy(); if (isConditionOptimizedFalse) { - thenFlowInfo.setReachMode(FlowInfo.UNREACHABLE); + thenFlowInfo.setReachMode(FlowInfo.UNREACHABLE); } if (this.thenStatement != null) { // Save info for code gen - thenInitStateIndex = - currentScope.methodScope().recordInitializationStates(thenFlowInfo); - if (!thenFlowInfo.complainIfUnreachable(thenStatement, currentScope, false)) { - thenFlowInfo = - thenStatement.analyseCode(currentScope, flowContext, thenFlowInfo); + thenInitStateIndex = currentScope.methodScope() + .recordInitializationStates(thenFlowInfo); + if (!thenFlowInfo.complainIfUnreachable(thenStatement, + currentScope, false)) { + thenFlowInfo = thenStatement.analyseCode(currentScope, + flowContext, thenFlowInfo); } - }; + } + ; // optimizing the jump around the ELSE part this.thenExit = !thenFlowInfo.isReachable(); // process the ELSE part FlowInfo elseFlowInfo = flowInfo.initsWhenFalse().copy(); if (isConditionOptimizedTrue) { - elseFlowInfo.setReachMode(FlowInfo.UNREACHABLE); + elseFlowInfo.setReachMode(FlowInfo.UNREACHABLE); } if (this.elseStatement != null) { // Save info for code gen - elseInitStateIndex = - currentScope.methodScope().recordInitializationStates(elseFlowInfo); - if (!elseFlowInfo.complainIfUnreachable(elseStatement, currentScope, false)) { - elseFlowInfo = - elseStatement.analyseCode(currentScope, flowContext, elseFlowInfo); + elseInitStateIndex = currentScope.methodScope() + .recordInitializationStates(elseFlowInfo); + if (!elseFlowInfo.complainIfUnreachable(elseStatement, + currentScope, false)) { + elseFlowInfo = elseStatement.analyseCode(currentScope, + flowContext, elseFlowInfo); } } boolean elseExit = !elseFlowInfo.isReachable(); - + // merge THEN & ELSE initializations FlowInfo mergedInfo; -// if (isConditionOptimizedTrue){ -// if (!this.thenExit) { -// mergedInfo = thenFlowInfo; -// } else { -// mergedInfo = elseFlowInfo.setReachMode(FlowInfo.UNREACHABLE); -// } -// -// } else if (isConditionOptimizedFalse) { -// if (!elseExit) { -// mergedInfo = elseFlowInfo; -// } else { -// mergedInfo = thenFlowInfo.setReachMode(FlowInfo.UNREACHABLE); -// } -// -// } else { -// mergedInfo = thenFlowInfo.mergedWith(elseFlowInfo.unconditionalInits()); -// } - if (isConditionOptimizedTrue){ + // if (isConditionOptimizedTrue){ + // if (!this.thenExit) { + // mergedInfo = thenFlowInfo; + // } else { + // mergedInfo = elseFlowInfo.setReachMode(FlowInfo.UNREACHABLE); + // } + // + // } else if (isConditionOptimizedFalse) { + // if (!elseExit) { + // mergedInfo = elseFlowInfo; + // } else { + // mergedInfo = thenFlowInfo.setReachMode(FlowInfo.UNREACHABLE); + // } + // + // } else { + // mergedInfo = + // thenFlowInfo.mergedWith(elseFlowInfo.unconditionalInits()); + // } + if (isConditionOptimizedTrue) { if (!this.thenExit) { - mergedInfo = thenFlowInfo.addPotentialInitializationsFrom(elseFlowInfo); + mergedInfo = thenFlowInfo + .addPotentialInitializationsFrom(elseFlowInfo); } else { mergedInfo = elseFlowInfo.setReachMode(FlowInfo.UNREACHABLE); } } else if (isConditionOptimizedFalse) { if (!elseExit) { - mergedInfo = elseFlowInfo.addPotentialInitializationsFrom(thenFlowInfo); + mergedInfo = elseFlowInfo + .addPotentialInitializationsFrom(thenFlowInfo); } else { mergedInfo = thenFlowInfo.setReachMode(FlowInfo.UNREACHABLE); } } else { - mergedInfo = thenFlowInfo.mergedWith(elseFlowInfo.unconditionalInits()); + mergedInfo = thenFlowInfo.mergedWith(elseFlowInfo + .unconditionalInits()); } - mergedInitStateIndex = - currentScope.methodScope().recordInitializationStates(mergedInfo); + mergedInitStateIndex = currentScope.methodScope() + .recordInitializationStates(mergedInfo); return mergedInfo; } /** * If code generation - * - * @param currentScope net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream */ -// public void generateCode(BlockScope currentScope, CodeStream codeStream) { -// -// if ((this.bits & IsReachableMASK) == 0) { -// return; -// } -// int pc = codeStream.position; -// Label endifLabel = new Label(codeStream); -// -// // optimizing the then/else part code gen -// Constant cst; -// boolean hasThenPart = -// !(((cst = this.condition.optimizedBooleanConstant()) != NotAConstant -// && cst.booleanValue() == false) -// || this.thenStatement == null -// || this.thenStatement.isEmptyBlock()); -// boolean hasElsePart = -// !((cst != NotAConstant && cst.booleanValue() == true) -// || this.elseStatement == null -// || this.elseStatement.isEmptyBlock()); -// -// if (hasThenPart) { -// Label falseLabel; -// // generate boolean condition -// this.condition.generateOptimizedBoolean( -// currentScope, -// codeStream, -// null, -// (falseLabel = new Label(codeStream)), -// true); -// // May loose some local variable initializations : affecting the local variable attributes -// if (thenInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// thenInitStateIndex); -// codeStream.addDefinitelyAssignedVariables(currentScope, thenInitStateIndex); -// } -// // generate then statement -// this.thenStatement.generateCode(currentScope, codeStream); -// // jump around the else statement -// if (hasElsePart && !thenExit) { -// this.thenStatement.branchChainTo(endifLabel); -// int position = codeStream.position; -// codeStream.goto_(endifLabel); -// codeStream.updateLastRecordedEndPC(position); -// //goto is tagged as part of the thenAction block -// } -// falseLabel.place(); -// } else { -// if (hasElsePart) { -// // generate boolean condition -// this.condition.generateOptimizedBoolean( -// currentScope, -// codeStream, -// endifLabel, -// null, -// true); -// } else { -// // generate condition side-effects -// this.condition.generateCode(currentScope, codeStream, false); -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } -// } -// // generate else statement -// if (hasElsePart) { -// // May loose some local variable initializations : affecting the local variable attributes -// if (elseInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// elseInitStateIndex); -// codeStream.addDefinitelyAssignedVariables(currentScope, elseInitStateIndex); -// } -// this.elseStatement.generateCode(currentScope, codeStream); -// } -// endifLabel.place(); -// // May loose some local variable initializations : affecting the local variable attributes -// if (mergedInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// mergedInitStateIndex); -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } + // public void generateCode(BlockScope currentScope, CodeStream codeStream) + // { + // + // if ((this.bits & IsReachableMASK) == 0) { + // return; + // } + // int pc = codeStream.position; + // Label endifLabel = new Label(codeStream); + // + // // optimizing the then/else part code gen + // Constant cst; + // boolean hasThenPart = + // !(((cst = this.condition.optimizedBooleanConstant()) != NotAConstant + // && cst.booleanValue() == false) + // || this.thenStatement == null + // || this.thenStatement.isEmptyBlock()); + // boolean hasElsePart = + // !((cst != NotAConstant && cst.booleanValue() == true) + // || this.elseStatement == null + // || this.elseStatement.isEmptyBlock()); + // + // if (hasThenPart) { + // Label falseLabel; + // // generate boolean condition + // this.condition.generateOptimizedBoolean( + // currentScope, + // codeStream, + // null, + // (falseLabel = new Label(codeStream)), + // true); + // // May loose some local variable initializations : affecting the local + // variable attributes + // if (thenInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // thenInitStateIndex); + // codeStream.addDefinitelyAssignedVariables(currentScope, + // thenInitStateIndex); + // } + // // generate then statement + // this.thenStatement.generateCode(currentScope, codeStream); + // // jump around the else statement + // if (hasElsePart && !thenExit) { + // this.thenStatement.branchChainTo(endifLabel); + // int position = codeStream.position; + // codeStream.goto_(endifLabel); + // codeStream.updateLastRecordedEndPC(position); + // //goto is tagged as part of the thenAction block + // } + // falseLabel.place(); + // } else { + // if (hasElsePart) { + // // generate boolean condition + // this.condition.generateOptimizedBoolean( + // currentScope, + // codeStream, + // endifLabel, + // null, + // true); + // } else { + // // generate condition side-effects + // this.condition.generateCode(currentScope, codeStream, false); + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } + // } + // // generate else statement + // if (hasElsePart) { + // // May loose some local variable initializations : affecting the local + // variable attributes + // if (elseInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // elseInitStateIndex); + // codeStream.addDefinitelyAssignedVariables(currentScope, + // elseInitStateIndex); + // } + // this.elseStatement.generateCode(currentScope, codeStream); + // } + // endifLabel.place(); + // // May loose some local variable initializations : affecting the local + // variable attributes + // if (mergedInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // mergedInitStateIndex); + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } public StringBuffer printStatement(int indent, StringBuffer output) { printIndent(indent, output).append("if ("); //$NON-NLS-1$ - condition.printExpression(0, output).append(")\n"); //$NON-NLS-1$ + condition.printExpression(0, output).append(")\n"); //$NON-NLS-1$ thenStatement.printStatement(indent + 2, output); if (elseStatement != null) { output.append('\n'); @@ -253,9 +268,11 @@ public class IfStatement extends Statement { } return output; } + public void resolve(BlockScope scope) { - TypeBinding type = condition.resolveTypeExpecting(scope, BooleanBinding); + TypeBinding type = condition + .resolveTypeExpecting(scope, BooleanBinding); condition.implicitWidening(type, type); if (thenStatement != null) thenStatement.resolve(scope); @@ -267,16 +284,15 @@ public class IfStatement extends Statement { String inFront, s = tabString(tab); inFront = s; - s = s + "if (" + condition.toStringExpression() + ") \n"; //$NON-NLS-1$ //$NON-NLS-2$ + s = s + "if (" + condition.toStringExpression() + ") \n"; //$NON-NLS-1$ //$NON-NLS-2$ s = s + thenStatement.toString(tab + 2) + ";"; //$NON-NLS-1$ if (elseStatement != null) - s = s + "\n" + inFront + "else\n" + elseStatement.toString(tab + 2) + ";"; //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-3$ + s = s + + "\n" + inFront + "else\n" + elseStatement.toString(tab + 2) + ";"; //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-3$ return s; } - public void traverse( - ASTVisitor visitor, - BlockScope blockScope) { + public void traverse(ASTVisitor visitor, BlockScope blockScope) { if (visitor.visit(this, blockScope)) { condition.traverse(visitor, blockScope); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ImplicitDocTypeReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ImplicitDocTypeReference.java index c6287f0..bfe2bd6 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ImplicitDocTypeReference.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ImplicitDocTypeReference.java @@ -16,7 +16,7 @@ import net.sourceforge.phpdt.internal.compiler.lookup.Scope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class ImplicitDocTypeReference extends TypeReference { - + public char[] token; public ImplicitDocTypeReference(char[] name, int pos) { @@ -25,20 +25,29 @@ public class ImplicitDocTypeReference extends TypeReference { this.sourceStart = pos; this.sourceEnd = pos; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.jdt.internal.compiler.ast.TypeReference#copyDims(int) */ public TypeReference copyDims(int dim) { return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.jdt.internal.compiler.ast.TypeReference#getTypeBinding(org.eclipse.jdt.internal.compiler.lookup.Scope) */ public TypeBinding getTypeBinding(Scope scope) { this.constant = NotAConstant; return this.resolvedType = scope.enclosingSourceType(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.jdt.internal.compiler.ast.TypeReference#getTypeName() */ public char[][] getTypeName() { @@ -48,17 +57,26 @@ public class ImplicitDocTypeReference extends TypeReference { } return null; } + public boolean isThis() { return true; } - /* (non-Javadoc) - * @see org.eclipse.jdt.internal.compiler.ast.TypeReference#traverse(org.eclipse.jdt.internal.compiler.ASTVisitor, org.eclipse.jdt.internal.compiler.lookup.ClassScope) + + /* + * (non-Javadoc) + * + * @see org.eclipse.jdt.internal.compiler.ast.TypeReference#traverse(org.eclipse.jdt.internal.compiler.ASTVisitor, + * org.eclipse.jdt.internal.compiler.lookup.ClassScope) */ public void traverse(ASTVisitor visitor, ClassScope classScope) { // Do nothing } - /* (non-Javadoc) - * @see org.eclipse.jdt.internal.compiler.ast.Expression#printExpression(int, java.lang.StringBuffer) + + /* + * (non-Javadoc) + * + * @see org.eclipse.jdt.internal.compiler.ast.Expression#printExpression(int, + * java.lang.StringBuffer) */ public StringBuffer printExpression(int indent, StringBuffer output) { return new StringBuffer(); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ImportReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ImportReference.java index 4f45275..7c5b2d4 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ImportReference.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ImportReference.java @@ -14,104 +14,107 @@ import org.eclipse.core.resources.IFile; public class ImportReference extends ASTNode { - public char[][] tokens; - - // public long[] sourcePositions; //each entry is using the code : (start<<32) + end - public boolean onDemand = true; //most of the time - - public final char[] includeSource; - - public int declarationEnd;// doesn't include an potential trailing comment - - public int declarationSourceStart; - - public int declarationSourceEnd; - - public boolean used; - - private IFile fFile; - - public ImportReference(char[][] sources, char[] sourceString, int start, int end, boolean d) { // char[][] sources , long[] poss , - // boolean d) { - tokens = sources; - // sourcePositions = poss ; - includeSource = sourceString; - onDemand = d; - sourceEnd = end;//(int)(sourcePositions[sourcePositions.length-1] & 0x00000000FFFFFFFF); - sourceStart = start;//(int)(sourcePositions[0]>>>32) ; - fFile = null; - } - - /** - * @return char[][] - */ - public char[][] getImportName() { - return tokens; - } - - public char[] getIncludeName() { - return includeSource; - } - - public StringBuffer print(int indent, StringBuffer output) { - - return print(indent, output, true); - } - - public StringBuffer print(int tab, StringBuffer output, boolean withOnDemand) { - - /* when withOnDemand is false, only the name is printed */ - for (int i = 0; i < tokens.length; i++) { - if (i > 0) - output.append('.'); - output.append(tokens[i]); - } - if (withOnDemand && onDemand) { - output.append(".*"); //$NON-NLS-1$ - } - return output; - } - - public String toString(int tab) { - - return toString(tab, true); - } - - public String toString(int tab, boolean withOnDemand) { - /* when withOnDemand is false, only the name is printed */ - StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < tokens.length; i++) { - buffer.append(tokens[i]); - if (i < (tokens.length - 1)) { - buffer.append("."); //$NON-NLS-1$ - } - } - if (withOnDemand && onDemand) { - buffer.append(".*"); //$NON-NLS-1$ - } - buffer.append(" - "); - buffer.append(includeSource); - return buffer.toString(); - // return new String(includeSource); - } - - public void traverse(ASTVisitor visitor, CompilationUnitScope scope) { - visitor.visit(this, scope); - visitor.endVisit(this, scope); - } - - /** - * @return Returns the filePath. - */ - public IFile getFile() { - return fFile; - } - - /** - * @param filePath - * The filePath to set. - */ - public void setFile(IFile filePath) { - fFile = filePath; - } + public char[][] tokens; + + // public long[] sourcePositions; //each entry is using the code : + // (start<<32) + end + public boolean onDemand = true; // most of the time + + public final char[] includeSource; + + public int declarationEnd;// doesn't include an potential trailing comment + + public int declarationSourceStart; + + public int declarationSourceEnd; + + public boolean used; + + private IFile fFile; + + public ImportReference(char[][] sources, char[] sourceString, int start, + int end, boolean d) { // char[][] sources , long[] poss , + // boolean d) { + tokens = sources; + // sourcePositions = poss ; + includeSource = sourceString; + onDemand = d; + sourceEnd = end;// (int)(sourcePositions[sourcePositions.length-1] & + // 0x00000000FFFFFFFF); + sourceStart = start;// (int)(sourcePositions[0]>>>32) ; + fFile = null; + } + + /** + * @return char[][] + */ + public char[][] getImportName() { + return tokens; + } + + public char[] getIncludeName() { + return includeSource; + } + + public StringBuffer print(int indent, StringBuffer output) { + + return print(indent, output, true); + } + + public StringBuffer print(int tab, StringBuffer output, boolean withOnDemand) { + + /* when withOnDemand is false, only the name is printed */ + for (int i = 0; i < tokens.length; i++) { + if (i > 0) + output.append('.'); + output.append(tokens[i]); + } + if (withOnDemand && onDemand) { + output.append(".*"); //$NON-NLS-1$ + } + return output; + } + + public String toString(int tab) { + + return toString(tab, true); + } + + public String toString(int tab, boolean withOnDemand) { + /* when withOnDemand is false, only the name is printed */ + StringBuffer buffer = new StringBuffer(); + for (int i = 0; i < tokens.length; i++) { + buffer.append(tokens[i]); + if (i < (tokens.length - 1)) { + buffer.append("."); //$NON-NLS-1$ + } + } + if (withOnDemand && onDemand) { + buffer.append(".*"); //$NON-NLS-1$ + } + buffer.append(" - "); + buffer.append(includeSource); + return buffer.toString(); + // return new String(includeSource); + } + + public void traverse(ASTVisitor visitor, CompilationUnitScope scope) { + visitor.visit(this, scope); + visitor.endVisit(this, scope); + } + + /** + * @return Returns the filePath. + */ + public IFile getFile() { + return fFile; + } + + /** + * @param filePath + * The filePath to set. + */ + public void setFile(IFile filePath) { + fFile = filePath; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Initializer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Initializer.java index 4c5f8d6..16bc51a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Initializer.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Initializer.java @@ -18,10 +18,13 @@ import net.sourceforge.phpdt.internal.compiler.lookup.ReferenceBinding; import net.sourceforge.phpdt.internal.compiler.parser.UnitParser; public class Initializer extends FieldDeclaration { - + public Block block; + public int lastFieldID; + public int bodyStart; + public Initializer(Block block, int modifiers) { this.block = block; this.modifiers = modifiers; @@ -29,31 +32,30 @@ public class Initializer extends FieldDeclaration { declarationSourceStart = sourceStart = bodyStart = block.sourceStart; } - public FlowInfo analyseCode( - MethodScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { + public FlowInfo analyseCode(MethodScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { return block.analyseCode(currentScope, flowContext, flowInfo); } /** - * Code generation for a non-static initializer: - * standard block code gen - * - * @param currentScope net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * Code generation for a non-static initializer: standard block code gen + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream */ -// public void generateCode(BlockScope currentScope, CodeStream codeStream) { -// -// if ((bits & IsReachableMASK) == 0) { -// return; -// } -// int pc = codeStream.position; -// block.generateCode(currentScope, codeStream); -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } - + // public void generateCode(BlockScope currentScope, CodeStream codeStream) + // { + // + // if ((bits & IsReachableMASK) == 0) { + // return; + // } + // int pc = codeStream.position; + // block.generateCode(currentScope, codeStream); + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } public boolean isField() { return false; @@ -64,12 +66,10 @@ public class Initializer extends FieldDeclaration { return (modifiers & AccStatic) != 0; } - public void parseStatements( - UnitParser parser, - TypeDeclaration type, - CompilationUnitDeclaration unit) { + public void parseStatements(UnitParser parser, TypeDeclaration type, + CompilationUnitDeclaration unit) { - //fill up the method body with statement + // fill up the method body with statement parser.parse(this, type, unit); } @@ -81,9 +81,9 @@ public class Initializer extends FieldDeclaration { if (isStatic()) { ReferenceBinding declaringType = scope.enclosingSourceType(); if (declaringType.isNestedType() && !declaringType.isStatic()) - scope.problemReporter().innerTypesCannotDeclareStaticInitializers( - declaringType, - this); + scope.problemReporter() + .innerTypesCannotDeclareStaticInitializers( + declaringType, this); } block.resolve(scope); } finally { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/InnerTypeDeclaration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/InnerTypeDeclaration.java index cd375b7..c3ed7c9 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/InnerTypeDeclaration.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/InnerTypeDeclaration.java @@ -13,8 +13,8 @@ package net.sourceforge.phpdt.internal.compiler.ast; import net.sourceforge.phpdt.internal.compiler.CompilationResult; public class InnerTypeDeclaration extends TypeDeclaration { - - public InnerTypeDeclaration(CompilationResult compilationResult){ + + public InnerTypeDeclaration(CompilationResult compilationResult) { super(compilationResult); - } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/InstanceOfExpression.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/InstanceOfExpression.java index 22e3e57..05ee78d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/InstanceOfExpression.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/InstanceOfExpression.java @@ -20,16 +20,14 @@ import net.sourceforge.phpdt.internal.compiler.lookup.ReferenceBinding; import net.sourceforge.phpdt.internal.compiler.lookup.Scope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; - public class InstanceOfExpression extends OperatorExpression { public Expression expression; + public TypeReference type; - public InstanceOfExpression( - Expression expression, - TypeReference type, - int operator) { + public InstanceOfExpression(Expression expression, TypeReference type, + int operator) { this.expression = expression; this.type = type; @@ -38,73 +36,74 @@ public class InstanceOfExpression extends OperatorExpression { this.sourceEnd = type.sourceEnd; } - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { - return expression - .analyseCode(currentScope, flowContext, flowInfo) - .unconditionalInits(); + return expression.analyseCode(currentScope, flowContext, flowInfo) + .unconditionalInits(); } - public final boolean areTypesCastCompatible( - BlockScope scope, - TypeBinding castType, - TypeBinding expressionType) { + public final boolean areTypesCastCompatible(BlockScope scope, + TypeBinding castType, TypeBinding expressionType) { - // see specifications p.68 - //A more cpmplete version of this method is provided on - //CastExpression (it deals with constant and need runtime checkcast) + // see specifications p.68 + // A more cpmplete version of this method is provided on + // CastExpression (it deals with constant and need runtime checkcast) - if (castType == expressionType) return true; - - //by grammatical construction, the first test is ALWAYS false - //if (castTb.isBaseType()) - //{ if (expressionTb.isBaseType()) - // { if (expression.isConstantValueOfTypeAssignableToType(expressionTb,castTb)) - // { return true;} - // else - // { if (expressionTb==castTb) - // { return true;} - // else - // { if (scope.areTypesCompatible(expressionTb,castTb)) - // { return true; } + if (castType == expressionType) + return true; + + // by grammatical construction, the first test is ALWAYS false + // if (castTb.isBaseType()) + // { if (expressionTb.isBaseType()) + // { if + // (expression.isConstantValueOfTypeAssignableToType(expressionTb,castTb)) + // { return true;} + // else + // { if (expressionTb==castTb) + // { return true;} + // else + // { if (scope.areTypesCompatible(expressionTb,castTb)) + // { return true; } // - // if (BaseTypeBinding.isNarrowing(castTb.id,expressionTb.id)) - // { return true;} - // return false;}}} - // else - // { return false; }} - //else - { //-------------checkcast to something which is NOT a basetype---------------------------------- + // if (BaseTypeBinding.isNarrowing(castTb.id,expressionTb.id)) + // { return true;} + // return false;}}} + // else + // { return false; }} + // else + { // -------------checkcast to something which is NOT a + // basetype---------------------------------- - //null is compatible with every thing .... + // null is compatible with every thing .... if (NullBinding == expressionType) { return true; } if (expressionType.isArrayType()) { if (castType.isArrayType()) { - //------- (castTb.isArray) expressionTb.isArray ----------- - TypeBinding expressionEltTb = ((ArrayBinding) expressionType).elementsType(scope); + // ------- (castTb.isArray) expressionTb.isArray ----------- + TypeBinding expressionEltTb = ((ArrayBinding) expressionType) + .elementsType(scope); if (expressionEltTb.isBaseType()) - // <---stop the recursion------- + // <---stop the recursion------- return ((ArrayBinding) castType).elementsType(scope) == expressionEltTb; - //recursivly on the elts... - return areTypesCastCompatible( - scope, - ((ArrayBinding) castType).elementsType(scope), - expressionEltTb); + // recursivly on the elts... + return areTypesCastCompatible(scope, + ((ArrayBinding) castType).elementsType(scope), + expressionEltTb); } if (castType.isClass()) { - //------(castTb.isClass) expressionTb.isArray --------------- + // ------(castTb.isClass) expressionTb.isArray + // --------------- if (scope.isJavaLangObject(castType)) return true; return false; } if (castType.isInterface()) { - //------- (castTb.isInterface) expressionTb.isArray ----------- - if (scope.isJavaLangCloneable(castType) || scope.isJavaIoSerializable(castType)) { + // ------- (castTb.isInterface) expressionTb.isArray + // ----------- + if (scope.isJavaLangCloneable(castType) + || scope.isJavaIoSerializable(castType)) { return true; } return false; @@ -124,7 +123,8 @@ public class InstanceOfExpression extends OperatorExpression { return false; } } - if (castType.isClass()) { // ----- (castTb.isClass) expressionTb.isClass ------ + if (castType.isClass()) { // ----- (castTb.isClass) + // expressionTb.isClass ------ if (expressionType.isCompatibleWith(castType)) return true; else { @@ -135,9 +135,10 @@ public class InstanceOfExpression extends OperatorExpression { } } if (castType.isInterface()) { - // ----- (castTb.isInterface) expressionTb.isClass ------- + // ----- (castTb.isInterface) expressionTb.isClass ------- if (((ReferenceBinding) expressionType).isFinal()) { - //no subclass for expressionTb, thus compile-time check is valid + // no subclass for expressionTb, thus compile-time check + // is valid if (expressionType.isCompatibleWith(castType)) return true; return false; @@ -152,9 +153,9 @@ public class InstanceOfExpression extends OperatorExpression { if (castType.isArrayType()) { // ----- (castTb.isArray) expressionTb.isInterface ------ if (scope.isJavaLangCloneable(expressionType) - || scope.isJavaIoSerializable(expressionType)) - //potential runtime error - { + || scope.isJavaIoSerializable(expressionType)) + // potential runtime error + { return true; } return false; @@ -164,7 +165,8 @@ public class InstanceOfExpression extends OperatorExpression { if (scope.isJavaLangObject(castType)) return true; if (((ReferenceBinding) castType).isFinal()) { - //no subclass for castTb, thus compile-time check is valid + // no subclass for castTb, thus compile-time check is + // valid if (castType.isCompatibleWith(expressionType)) { return true; } @@ -173,18 +175,21 @@ public class InstanceOfExpression extends OperatorExpression { return true; } if (castType.isInterface()) { - // ----- (castTb.isInterface) expressionTb.isInterface ------- + // ----- (castTb.isInterface) expressionTb.isInterface + // ------- if ((Scope.compareTypes(castType, expressionType) == NotRelated)) { - MethodBinding[] castTbMethods = ((ReferenceBinding) castType).methods(); + MethodBinding[] castTbMethods = ((ReferenceBinding) castType) + .methods(); int castTbMethodsLength = castTbMethods.length; - MethodBinding[] expressionTbMethods = - ((ReferenceBinding) expressionType).methods(); + MethodBinding[] expressionTbMethods = ((ReferenceBinding) expressionType) + .methods(); int expressionTbMethodsLength = expressionTbMethods.length; for (int i = 0; i < castTbMethodsLength; i++) { for (int j = 0; j < expressionTbMethodsLength; j++) { if (castTbMethods[i].selector == expressionTbMethods[j].selector) { if (castTbMethods[i].returnType != expressionTbMethods[j].returnType) { - if (castTbMethods[i].areParametersEqual(expressionTbMethods[j])) { + if (castTbMethods[i] + .areParametersEqual(expressionTbMethods[j])) { return false; } } @@ -196,31 +201,34 @@ public class InstanceOfExpression extends OperatorExpression { } return false; - } + } return false; } } + /** * Code generation for instanceOfExpression - * - * @param currentScope net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream - * @param valueRequired boolean - */ -// public void generateCode( -// BlockScope currentScope, -// CodeStream codeStream, -// boolean valueRequired) { -// -// int pc = codeStream.position; -// expression.generateCode(currentScope, codeStream, true); -// codeStream.instance_of(type.resolvedType); -// if (!valueRequired) -// codeStream.pop(); -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } - + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * @param valueRequired + * boolean + */ + // public void generateCode( + // BlockScope currentScope, + // CodeStream codeStream, + // boolean valueRequired) { + // + // int pc = codeStream.position; + // expression.generateCode(currentScope, codeStream, true); + // codeStream.instance_of(type.resolvedType); + // if (!valueRequired) + // codeStream.pop(); + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } public TypeBinding resolveType(BlockScope scope) { constant = NotAConstant; @@ -230,21 +238,25 @@ public class InstanceOfExpression extends OperatorExpression { return null; if (!areTypesCastCompatible(scope, checkType, expressionType)) { - scope.problemReporter().notCompatibleTypesError(this, expressionType, checkType); + scope.problemReporter().notCompatibleTypesError(this, + expressionType, checkType); return null; } this.resolvedType = BooleanBinding; return BooleanBinding; } - public StringBuffer printExpressionNoParenthesis(int indent, StringBuffer output) { + + public StringBuffer printExpressionNoParenthesis(int indent, + StringBuffer output) { expression.printExpression(indent, output).append(" instanceof "); //$NON-NLS-1$ return type.print(0, output); } + public String toStringExpressionNoParenthesis() { return expression.toStringExpression() + " instanceof " + //$NON-NLS-1$ - type.toString(0); + type.toString(0); } public void traverse(ASTVisitor visitor, BlockScope scope) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/IntLiteral.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/IntLiteral.java index d78e934..42b7b22 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/IntLiteral.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/IntLiteral.java @@ -16,135 +16,163 @@ import net.sourceforge.phpdt.internal.compiler.impl.DoubleConstant; import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; - public class IntLiteral extends NumberLiteral { public int value; - - public static final IntLiteral - One = new IntLiteral(new char[]{'1'},0,0,1);//used for ++ and -- - static final Constant FORMAT_ERROR = new DoubleConstant(1.0/0.0); // NaN; -public IntLiteral(char[] token, int s, int e) { - super(token, s,e); -} -public IntLiteral(char[] token, int s,int e, int value) { - this(token, s,e); - this.value = value; -} -public IntLiteral(int intValue) { - //special optimized constructor : the cst is the argument - - //value that should not be used - // tokens = null ; - // sourceStart = 0; - // sourceEnd = 0; - super(null,0,0); - constant = Constant.fromValue(intValue); - value = intValue; - -} -public void computeConstant() { - //a special constant is use for the potential Integer.MAX_VALUE+1 - //which is legal if used with a - as prefix....cool.... - //notice that Integer.MIN_VALUE == -2147483648 - - long MAX = Integer.MAX_VALUE; - if (this == One) { constant = Constant.One; return ;} - - int length = source.length; - long computedValue = 0L; - if (source[0] == '0') - { MAX = 0xFFFFFFFFL ; //a long in order to be positive ! - if (length == 1) { constant = Constant.fromValue(0); return ;} - final int shift,radix; - int j ; - if ( (source[1] == 'x') | (source[1] == 'X') ) - { shift = 4 ; j = 2; radix = 16;} - else - { shift = 3 ; j = 1; radix = 8;} - while (source[j]=='0') - { j++; //jump over redondant zero - if (j == length) - { //watch for 000000000000000000 :-( - constant = Constant.fromValue(value = (int)computedValue); - return ;}} - - while (j MAX) return /*constant stays null*/ ;}} - else - { //-----------regular case : radix = 10----------- - for (int i = 0 ; i < length;i++) - { int digitValue ; - if ((digitValue = Character.digit(source[i],10)) < 0 ) - { constant = FORMAT_ERROR; return ;} - computedValue = 10*computedValue + digitValue; - if (computedValue > MAX) return /*constant stays null*/ ; }} - - constant = Constant.fromValue(value = (int)computedValue); - -} -/** - * Code generation for int literal - * - * @param currentScope net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream - * @param valueRequired boolean - */ -//public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) { -// int pc = codeStream.position; -// if (valueRequired) -// if ((implicitConversion >> 4) == T_int) -// codeStream.generateInlinedValue(value); -// else -// codeStream.generateConstant(constant, implicitConversion); -// codeStream.recordPositionsFrom(pc, this.sourceStart); -//} -public TypeBinding literalType(BlockScope scope) { - return IntBinding; -} -public final boolean mayRepresentMIN_VALUE(){ - //a special autorized int literral is 2147483648 - //which is ONE over the limit. This special case - //only is used in combinaison with - to denote - //the minimal value of int -2147483648 - - return ((source.length == 10) && - (source[0] == '2') && - (source[1] == '1') && - (source[2] == '4') && - (source[3] == '7') && - (source[4] == '4') && - (source[5] == '8') && - (source[6] == '3') && - (source[7] == '6') && - (source[8] == '4') && - (source[9] == '8'));} -public TypeBinding resolveType(BlockScope scope) { - // the format may be incorrect while the scanner could detect - // such an error only on painfull tests...easier and faster here - - TypeBinding tb = super.resolveType(scope); - if (constant == FORMAT_ERROR) { - constant = NotAConstant; - scope.problemReporter().constantOutOfFormat(this); - this.resolvedType = null; - return null; + public static final IntLiteral One = new IntLiteral(new char[] { '1' }, 0, + 0, 1);// used for ++ and -- + + static final Constant FORMAT_ERROR = new DoubleConstant(1.0 / 0.0); // NaN; + + public IntLiteral(char[] token, int s, int e) { + super(token, s, e); + } + + public IntLiteral(char[] token, int s, int e, int value) { + this(token, s, e); + this.value = value; + } + + public IntLiteral(int intValue) { + // special optimized constructor : the cst is the argument + + // value that should not be used + // tokens = null ; + // sourceStart = 0; + // sourceEnd = 0; + super(null, 0, 0); + constant = Constant.fromValue(intValue); + value = intValue; + + } + + public void computeConstant() { + // a special constant is use for the potential Integer.MAX_VALUE+1 + // which is legal if used with a - as prefix....cool.... + // notice that Integer.MIN_VALUE == -2147483648 + + long MAX = Integer.MAX_VALUE; + if (this == One) { + constant = Constant.One; + return; + } + + int length = source.length; + long computedValue = 0L; + if (source[0] == '0') { + MAX = 0xFFFFFFFFL; // a long in order to be positive ! + if (length == 1) { + constant = Constant.fromValue(0); + return; + } + final int shift, radix; + int j; + if ((source[1] == 'x') | (source[1] == 'X')) { + shift = 4; + j = 2; + radix = 16; + } else { + shift = 3; + j = 1; + radix = 8; + } + while (source[j] == '0') { + j++; // jump over redondant zero + if (j == length) { // watch for 000000000000000000 :-( + constant = Constant.fromValue(value = (int) computedValue); + return; + } + } + + while (j < length) { + int digitValue; + if ((digitValue = Character.digit(source[j++], radix)) < 0) { + constant = FORMAT_ERROR; + return; + } + computedValue = (computedValue << shift) | digitValue; + if (computedValue > MAX) + return /* constant stays null */; + } + } else { // -----------regular case : radix = 10----------- + for (int i = 0; i < length; i++) { + int digitValue; + if ((digitValue = Character.digit(source[i], 10)) < 0) { + constant = FORMAT_ERROR; + return; + } + computedValue = 10 * computedValue + digitValue; + if (computedValue > MAX) + return /* constant stays null */; + } + } + + constant = Constant.fromValue(value = (int) computedValue); + + } + + /** + * Code generation for int literal + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * @param valueRequired + * boolean + */ + // public void generateCode(BlockScope currentScope, CodeStream codeStream, + // boolean valueRequired) { + // int pc = codeStream.position; + // if (valueRequired) + // if ((implicitConversion >> 4) == T_int) + // codeStream.generateInlinedValue(value); + // else + // codeStream.generateConstant(constant, implicitConversion); + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } + public TypeBinding literalType(BlockScope scope) { + return IntBinding; + } + + public final boolean mayRepresentMIN_VALUE() { + // a special autorized int literral is 2147483648 + // which is ONE over the limit. This special case + // only is used in combinaison with - to denote + // the minimal value of int -2147483648 + + return ((source.length == 10) && (source[0] == '2') + && (source[1] == '1') && (source[2] == '4') + && (source[3] == '7') && (source[4] == '4') + && (source[5] == '8') && (source[6] == '3') + && (source[7] == '6') && (source[8] == '4') && (source[9] == '8')); + } + + public TypeBinding resolveType(BlockScope scope) { + // the format may be incorrect while the scanner could detect + // such an error only on painfull tests...easier and faster here + + TypeBinding tb = super.resolveType(scope); + if (constant == FORMAT_ERROR) { + constant = NotAConstant; + scope.problemReporter().constantOutOfFormat(this); + this.resolvedType = null; + return null; + } + return tb; + } + + public String toStringExpression() { + + if (source == null) + /* special optimized IntLiteral that are created by the compiler */ + return String.valueOf(value); + + return super.toStringExpression(); + } + + public void traverse(IAbstractSyntaxTreeVisitor visitor, BlockScope scope) { + visitor.visit(this, scope); + visitor.endVisit(this, scope); } - return tb; -} -public String toStringExpression(){ - - if (source == null) - /* special optimized IntLiteral that are created by the compiler */ - return String.valueOf(value); - - return super.toStringExpression();} -public void traverse(IAbstractSyntaxTreeVisitor visitor, BlockScope scope) { - visitor.visit(this, scope); - visitor.endVisit(this, scope); -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/IntLiteralMinValue.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/IntLiteralMinValue.java index 7f82c7f..e932aaa 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/IntLiteralMinValue.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/IntLiteralMinValue.java @@ -12,17 +12,19 @@ package net.sourceforge.phpdt.internal.compiler.ast; import net.sourceforge.phpdt.internal.compiler.impl.Constant; - public class IntLiteralMinValue extends IntLiteral { - final static char[] CharValue = new char[]{'-','2','1','4','7','4','8','3','6','4','8'}; - final static Constant MIN_VALUE = Constant.fromValue(Integer.MIN_VALUE) ; + final static char[] CharValue = new char[] { '-', '2', '1', '4', '7', '4', + '8', '3', '6', '4', '8' }; -public IntLiteralMinValue() { - super(CharValue,0,0,Integer.MIN_VALUE); - constant = MIN_VALUE; -} -public void computeConstant(){ - - /*precomputed at creation time*/ } + final static Constant MIN_VALUE = Constant.fromValue(Integer.MIN_VALUE); + + public IntLiteralMinValue() { + super(CharValue, 0, 0, Integer.MIN_VALUE); + constant = MIN_VALUE; + } + + public void computeConstant() { + + /* precomputed at creation time */} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/JavadocArrayQualifiedTypeReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/JavadocArrayQualifiedTypeReference.java index b4b9dfd..8b19337 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/JavadocArrayQualifiedTypeReference.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/JavadocArrayQualifiedTypeReference.java @@ -14,26 +14,31 @@ import net.sourceforge.phpdt.internal.compiler.ASTVisitor; import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; import net.sourceforge.phpdt.internal.compiler.lookup.Scope; - - -public class JavadocArrayQualifiedTypeReference extends ArrayQualifiedTypeReference { +public class JavadocArrayQualifiedTypeReference extends + ArrayQualifiedTypeReference { public int tagSourceStart, tagSourceEnd; - public JavadocArrayQualifiedTypeReference(JavadocQualifiedTypeReference typeRef, int dim) { + public JavadocArrayQualifiedTypeReference( + JavadocQualifiedTypeReference typeRef, int dim) { super(typeRef.tokens, dim, typeRef.sourcePositions); } protected void reportInvalidType(Scope scope) { - scope.problemReporter().javadocInvalidType(this, this.resolvedType, scope.getDeclarationModifiers()); + scope.problemReporter().javadocInvalidType(this, this.resolvedType, + scope.getDeclarationModifiers()); } + protected void reportDeprecatedType(Scope scope) { - scope.problemReporter().javadocDeprecatedType(this.resolvedType, this, scope.getDeclarationModifiers()); + scope.problemReporter().javadocDeprecatedType(this.resolvedType, this, + scope.getDeclarationModifiers()); } - /* (non-Javadoc) - * Redefine to capture javadoc specific signatures - * @see net.sourceforge.phpdt.internal.compiler.ast.ASTNode#traverse(net.sourceforge.phpdt.internal.compiler.ASTVisitor, net.sourceforge.phpdt.internal.compiler.lookup.BlockScope) + /* + * (non-Javadoc) Redefine to capture javadoc specific signatures + * + * @see net.sourceforge.phpdt.internal.compiler.ast.ASTNode#traverse(net.sourceforge.phpdt.internal.compiler.ASTVisitor, + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope) */ public void traverse(ASTVisitor visitor, BlockScope scope) { visitor.visit(this, scope); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/JavadocArraySingleTypeReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/JavadocArraySingleTypeReference.java index 2b7a99c..dafbf9f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/JavadocArraySingleTypeReference.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/JavadocArraySingleTypeReference.java @@ -14,7 +14,6 @@ import net.sourceforge.phpdt.internal.compiler.ASTVisitor; import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; import net.sourceforge.phpdt.internal.compiler.lookup.Scope; - public class JavadocArraySingleTypeReference extends ArrayTypeReference { public JavadocArraySingleTypeReference(char[] name, int dim, long pos) { @@ -23,15 +22,20 @@ public class JavadocArraySingleTypeReference extends ArrayTypeReference { } protected void reportInvalidType(Scope scope) { - scope.problemReporter().javadocInvalidType(this, this.resolvedType, scope.getDeclarationModifiers()); + scope.problemReporter().javadocInvalidType(this, this.resolvedType, + scope.getDeclarationModifiers()); } + protected void reportDeprecatedType(Scope scope) { - scope.problemReporter().javadocDeprecatedType(this.resolvedType, this, scope.getDeclarationModifiers()); + scope.problemReporter().javadocDeprecatedType(this.resolvedType, this, + scope.getDeclarationModifiers()); } - /* (non-Javadoc) - * Redefine to capture javadoc specific signatures - * @see net.sourceforge.phpdt.internal.compiler.ast.ASTNode#traverse(net.sourceforge.phpdt.internal.compiler.ASTVisitor, net.sourceforge.phpdt.internal.compiler.lookup.BlockScope) + /* + * (non-Javadoc) Redefine to capture javadoc specific signatures + * + * @see net.sourceforge.phpdt.internal.compiler.ast.ASTNode#traverse(net.sourceforge.phpdt.internal.compiler.ASTVisitor, + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope) */ public void traverse(ASTVisitor visitor, BlockScope scope) { visitor.visit(this, scope); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/JavadocQualifiedTypeReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/JavadocQualifiedTypeReference.java index a68f5a7..dd50179 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/JavadocQualifiedTypeReference.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/JavadocQualifiedTypeReference.java @@ -18,14 +18,14 @@ import net.sourceforge.phpdt.internal.compiler.lookup.PackageBinding; import net.sourceforge.phpdt.internal.compiler.lookup.Scope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; - - public class JavadocQualifiedTypeReference extends QualifiedTypeReference { public int tagSourceStart, tagSourceEnd; + public PackageBinding packageBinding; - public JavadocQualifiedTypeReference(char[][] sources, long[] pos, int tagStart, int tagEnd) { + public JavadocQualifiedTypeReference(char[][] sources, long[] pos, + int tagStart, int tagEnd) { super(sources, pos); this.tagSourceStart = tagStart; this.tagSourceEnd = tagEnd; @@ -33,15 +33,20 @@ public class JavadocQualifiedTypeReference extends QualifiedTypeReference { } protected void reportInvalidType(Scope scope) { - scope.problemReporter().javadocInvalidType(this, this.resolvedType, scope.getDeclarationModifiers()); + scope.problemReporter().javadocInvalidType(this, this.resolvedType, + scope.getDeclarationModifiers()); } + protected void reportDeprecatedType(Scope scope) { - scope.problemReporter().javadocDeprecatedType(this.resolvedType, this, scope.getDeclarationModifiers()); + scope.problemReporter().javadocDeprecatedType(this.resolvedType, this, + scope.getDeclarationModifiers()); } - /* (non-Javadoc) - * Redefine to capture javadoc specific signatures - * @see net.sourceforge.phpdt.internal.compiler.ast.ASTNode#traverse(net.sourceforge.phpdt.internal.compiler.ASTVisitor, net.sourceforge.phpdt.internal.compiler.lookup.BlockScope) + /* + * (non-Javadoc) Redefine to capture javadoc specific signatures + * + * @see net.sourceforge.phpdt.internal.compiler.ast.ASTNode#traverse(net.sourceforge.phpdt.internal.compiler.ASTVisitor, + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope) */ public void traverse(ASTVisitor visitor, BlockScope scope) { visitor.visit(this, scope); @@ -54,7 +59,8 @@ public class JavadocQualifiedTypeReference extends QualifiedTypeReference { private TypeBinding internalResolveType(Scope scope) { // handle the error here this.constant = NotAConstant; - if (this.resolvedType != null) { // is a shared type reference which was already resolved + if (this.resolvedType != null) { // is a shared type reference which + // was already resolved if (!this.resolvedType.isValidBinding()) return null; // already reported error } else { @@ -75,17 +81,21 @@ public class JavadocQualifiedTypeReference extends QualifiedTypeReference { return this.resolvedType; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpdt.internal.compiler.ast.Expression#resolveType(net.sourceforge.phpdt.internal.compiler.lookup.BlockScope) - * We need to override to handle package references + * We need to override to handle package references */ public TypeBinding resolveType(BlockScope blockScope) { return internalResolveType(blockScope); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpdt.internal.compiler.ast.Expression#resolveType(net.sourceforge.phpdt.internal.compiler.lookup.ClassScope) - * We need to override to handle package references + * We need to override to handle package references */ public TypeBinding resolveType(ClassScope classScope) { return internalResolveType(classScope); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/JavadocReturnStatement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/JavadocReturnStatement.java index 9465de8..423c03f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/JavadocReturnStatement.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/JavadocReturnStatement.java @@ -16,7 +16,6 @@ import net.sourceforge.phpdt.internal.compiler.lookup.MethodBinding; import net.sourceforge.phpdt.internal.compiler.lookup.MethodScope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; - public class JavadocReturnStatement extends ReturnStatement { public char[] description; @@ -29,20 +28,20 @@ public class JavadocReturnStatement extends ReturnStatement { public void resolve(BlockScope scope) { MethodScope methodScope = scope.methodScope(); MethodBinding methodBinding; - TypeBinding methodType = - (methodScope.referenceContext instanceof AbstractMethodDeclaration) - ? ((methodBinding = ((AbstractMethodDeclaration) methodScope.referenceContext).binding) == null - ? null - : methodBinding.returnType) + TypeBinding methodType = (methodScope.referenceContext instanceof AbstractMethodDeclaration) ? ((methodBinding = ((AbstractMethodDeclaration) methodScope.referenceContext).binding) == null ? null + : methodBinding.returnType) : VoidBinding; if (methodType == null || methodType == VoidBinding) { - scope.problemReporter().javadocUnexpectedTag(this.sourceStart, this.sourceEnd); + scope.problemReporter().javadocUnexpectedTag(this.sourceStart, + this.sourceEnd); } } - /* (non-Javadoc) - * Redefine to capture javadoc specific signatures - * @see net.sourceforge.phpdt.internal.compiler.ast.ASTNode#traverse(net.sourceforge.phpdt.internal.compiler.ASTVisitor, net.sourceforge.phpdt.internal.compiler.lookup.BlockScope) + /* + * (non-Javadoc) Redefine to capture javadoc specific signatures + * + * @see net.sourceforge.phpdt.internal.compiler.ast.ASTNode#traverse(net.sourceforge.phpdt.internal.compiler.ASTVisitor, + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope) */ public void traverse(ASTVisitor visitor, BlockScope scope) { visitor.visit(this, scope); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/JavadocSingleTypeReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/JavadocSingleTypeReference.java index 4c93535..a1d9ee4 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/JavadocSingleTypeReference.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/JavadocSingleTypeReference.java @@ -18,13 +18,14 @@ import net.sourceforge.phpdt.internal.compiler.lookup.PackageBinding; import net.sourceforge.phpdt.internal.compiler.lookup.Scope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; - public class JavadocSingleTypeReference extends SingleTypeReference { - + public int tagSourceStart, tagSourceEnd; + public PackageBinding packageBinding; - public JavadocSingleTypeReference(char[] source, long pos, int tagStart, int tagEnd) { + public JavadocSingleTypeReference(char[] source, long pos, int tagStart, + int tagEnd) { super(source, pos); this.tagSourceStart = tagStart; this.tagSourceEnd = tagEnd; @@ -32,15 +33,20 @@ public class JavadocSingleTypeReference extends SingleTypeReference { } protected void reportInvalidType(Scope scope) { - scope.problemReporter().javadocInvalidType(this, this.resolvedType, scope.getDeclarationModifiers()); + scope.problemReporter().javadocInvalidType(this, this.resolvedType, + scope.getDeclarationModifiers()); } + protected void reportDeprecatedType(Scope scope) { - scope.problemReporter().javadocDeprecatedType(this.resolvedType, this, scope.getDeclarationModifiers()); + scope.problemReporter().javadocDeprecatedType(this.resolvedType, this, + scope.getDeclarationModifiers()); } - /* (non-Javadoc) - * Redefine to capture javadoc specific signatures - * @see net.sourceforge.phpdt.internal.compiler.ast.ASTNode#traverse(net.sourceforge.phpdt.internal.compiler.ASTVisitor, net.sourceforge.phpdt.internal.compiler.lookup.BlockScope) + /* + * (non-Javadoc) Redefine to capture javadoc specific signatures + * + * @see net.sourceforge.phpdt.internal.compiler.ast.ASTNode#traverse(net.sourceforge.phpdt.internal.compiler.ASTVisitor, + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope) */ public void traverse(ASTVisitor visitor, BlockScope scope) { visitor.visit(this, scope); @@ -53,7 +59,8 @@ public class JavadocSingleTypeReference extends SingleTypeReference { private TypeBinding internalResolveType(Scope scope) { // handle the error here this.constant = NotAConstant; - if (this.resolvedType != null) { // is a shared type reference which was already resolved + if (this.resolvedType != null) { // is a shared type reference which + // was already resolved if (!this.resolvedType.isValidBinding()) return null; // already reported error } else { @@ -75,17 +82,21 @@ public class JavadocSingleTypeReference extends SingleTypeReference { return this.resolvedType; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpdt.internal.compiler.ast.Expression#resolveType(net.sourceforge.phpdt.internal.compiler.lookup.BlockScope) - * We need to override to handle package references + * We need to override to handle package references */ public TypeBinding resolveType(BlockScope blockScope) { return internalResolveType(blockScope); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpdt.internal.compiler.ast.Expression#resolveType(net.sourceforge.phpdt.internal.compiler.lookup.ClassScope) - * We need to override to handle package references + * We need to override to handle package references */ public TypeBinding resolveType(ClassScope classScope) { return internalResolveType(classScope); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/LabeledStatement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/LabeledStatement.java index 7070de7..e7fe6a0 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/LabeledStatement.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/LabeledStatement.java @@ -17,103 +17,102 @@ import net.sourceforge.phpdt.internal.compiler.flow.FlowInfo; import net.sourceforge.phpdt.internal.compiler.flow.LabelFlowContext; import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; - public class LabeledStatement extends Statement { - + public Statement statement; + public char[] label; + public Label targetLabel; // for local variables table attributes int mergedInitStateIndex = -1; - + /** * LabeledStatement constructor comment. */ public LabeledStatement(char[] l, Statement st, int s, int e) { - + this.statement = st; this.label = l; this.sourceStart = s; this.sourceEnd = e; } - - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { - - // need to stack a context to store explicit label, answer inits in case of normal completion merged - // with those relative to the exit path from break statement occurring inside the labeled statement. + + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { + + // need to stack a context to store explicit label, answer inits in case + // of normal completion merged + // with those relative to the exit path from break statement occurring + // inside the labeled statement. if (statement == null) { return flowInfo; } else { LabelFlowContext labelContext; - FlowInfo mergedInfo = - statement - .analyseCode( - currentScope, - (labelContext = - new LabelFlowContext( - flowContext, - this, - label, - (targetLabel = new Label()), - currentScope)), - flowInfo) - .mergedWith(labelContext.initsOnBreak); - mergedInitStateIndex = - currentScope.methodScope().recordInitializationStates(mergedInfo); + FlowInfo mergedInfo = statement.analyseCode( + currentScope, + (labelContext = new LabelFlowContext(flowContext, this, + label, (targetLabel = new Label()), currentScope)), + flowInfo).mergedWith(labelContext.initsOnBreak); + mergedInitStateIndex = currentScope.methodScope() + .recordInitializationStates(mergedInfo); return mergedInfo; } } - + public ASTNode concreteStatement() { - - // return statement.concreteStatement(); // for supporting nested labels: a:b:c: someStatement (see 21912) + + // return statement.concreteStatement(); // for supporting nested + // labels: a:b:c: someStatement (see 21912) return statement; } - + /** * Code generation for labeled statement - * + * * may not need actual source positions recording - * - * @param currentScope net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream */ -// public void generateCode(BlockScope currentScope, CodeStream codeStream) { -// -// int pc = codeStream.position; -// if (targetLabel != null) { -// targetLabel.codeStream = codeStream; -// if (statement != null) { -// statement.generateCode(currentScope, codeStream); -// } -// targetLabel.place(); -// } -// // May loose some local variable initializations : affecting the local variable attributes -// if (mergedInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// mergedInitStateIndex); -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } + // public void generateCode(BlockScope currentScope, CodeStream codeStream) + // { + // + // int pc = codeStream.position; + // if (targetLabel != null) { + // targetLabel.codeStream = codeStream; + // if (statement != null) { + // statement.generateCode(currentScope, codeStream); + // } + // targetLabel.place(); + // } + // // May loose some local variable initializations : affecting the local + // variable attributes + // if (mergedInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // mergedInitStateIndex); + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } public StringBuffer printStatement(int tab, StringBuffer output) { printIndent(tab, output).append(label).append(": "); //$NON-NLS-1$ - if (this.statement == null) + if (this.statement == null) output.append(';'); - else - this.statement.printStatement(0, output); + else + this.statement.printStatement(0, output); return output; } + public void resolve(BlockScope scope) { - + statement.resolve(scope); } - + public String toString(int tab) { String s = tabString(tab); @@ -121,9 +120,7 @@ public class LabeledStatement extends Statement { return s; } - public void traverse( - ASTVisitor visitor, - BlockScope blockScope) { + public void traverse(ASTVisitor visitor, BlockScope blockScope) { if (visitor.visit(this, blockScope)) { statement.traverse(visitor, blockScope); @@ -132,7 +129,7 @@ public class LabeledStatement extends Statement { } public void resetStateForCodeGeneration() { - if (this.targetLabel != null) { + if (this.targetLabel != null) { this.targetLabel.resetStateForCodeGeneration(); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Literal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Literal.java index 3c4fcbf..e643884 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Literal.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Literal.java @@ -16,36 +16,40 @@ import net.sourceforge.phpdt.internal.compiler.impl.Constant; import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; - public abstract class Literal extends Expression { - -public Literal(int s,int e) { - sourceStart = s ; - sourceEnd= e; -} -public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { - return flowInfo; -} + public Literal(int s, int e) { + sourceStart = s; + sourceEnd = e; + } + + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { + return flowInfo; + } + + public abstract void computeConstant(); + + // ON ERROR constant STAYS NULL + public abstract TypeBinding literalType(BlockScope scope); + + public StringBuffer printExpression(int indent, StringBuffer output) { -public abstract void computeConstant() ; - //ON ERROR constant STAYS NULL -public abstract TypeBinding literalType(BlockScope scope); -public StringBuffer printExpression(int indent, StringBuffer output){ - return output.append(source()); - } -public TypeBinding resolveType(BlockScope scope) { - // compute the real value, which must range its type's range - - computeConstant(); - if (constant == null) { - scope.problemReporter().constantOutOfRange(this); - constant = Constant.NotAConstant; - return null; } - this.resolvedType = literalType(scope); - return this.resolvedType; -} -public abstract char[] source() ; + + public TypeBinding resolveType(BlockScope scope) { + // compute the real value, which must range its type's range + + computeConstant(); + if (constant == null) { + scope.problemReporter().constantOutOfRange(this); + constant = Constant.NotAConstant; + return null; + } + this.resolvedType = literalType(scope); + return this.resolvedType; + } + + public abstract char[] source(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/LocalDeclaration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/LocalDeclaration.java index a094fc4..59073c2 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/LocalDeclaration.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/LocalDeclaration.java @@ -19,16 +19,12 @@ import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; import net.sourceforge.phpdt.internal.compiler.lookup.LocalVariableBinding; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; - public class LocalDeclaration extends AbstractVariableDeclaration { public LocalVariableBinding binding; - public LocalDeclaration( - Expression expr, - char[] name, - int sourceStart, - int sourceEnd) { + public LocalDeclaration(Expression expr, char[] name, int sourceStart, + int sourceEnd) { initialization = expr; this.name = name; @@ -42,106 +38,115 @@ public class LocalDeclaration extends AbstractVariableDeclaration { } } - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { // record variable initialization if any if (flowInfo.isReachable()) { - bits |= IsLocalDeclarationReachableMASK; // only set if actually reached + bits |= IsLocalDeclarationReachableMASK; // only set if actually + // reached } - if (initialization == null) + if (initialization == null) return flowInfo; - - flowInfo = - initialization - .analyseCode(currentScope, flowContext, flowInfo) - .unconditionalInits(); + + flowInfo = initialization.analyseCode(currentScope, flowContext, + flowInfo).unconditionalInits(); // final int i = (i = 0); // no need to complain since (i = 0) part will get the blame - //if (binding.isFinal() && flowInfo.isPotentiallyAssigned(binding)) { - // currentScope.problemReporter().duplicateInitializationOfFinalLocal(binding, this); - //} - + // if (binding.isFinal() && flowInfo.isPotentiallyAssigned(binding)) { + // currentScope.problemReporter().duplicateInitializationOfFinalLocal(binding, + // this); + // } + flowInfo.markAsDefinitelyAssigned(binding); return flowInfo; } public void checkModifiers() { - //only potential valid modifier is <> + // only potential valid modifier is <> if (((modifiers & AccJustFlag) & ~AccFinal) != 0) - //AccModifierProblem -> other (non-visibility problem) - //AccAlternateModifierProblem -> duplicate modifier - //AccModifierProblem | AccAlternateModifierProblem -> visibility problem" + // AccModifierProblem -> other (non-visibility problem) + // AccAlternateModifierProblem -> duplicate modifier + // AccModifierProblem | AccAlternateModifierProblem -> visibility + // problem" - modifiers = (modifiers & ~AccAlternateModifierProblem) | AccModifierProblem; + modifiers = (modifiers & ~AccAlternateModifierProblem) + | AccModifierProblem; } /** - * Code generation for a local declaration: - * normal assignment to a local variable + unused variable handling + * Code generation for a local declaration: normal assignment to a local + * variable + unused variable handling */ -// public void generateCode(BlockScope currentScope, CodeStream codeStream) { -// -// // even if not reachable, variable must be added to visible if allocated (28298) -// if (binding.resolvedPosition != -1) { -// codeStream.addVisibleLocalVariable(binding); -// } -// if ((bits & IsReachableMASK) == 0) { -// return; -// } -// int pc = codeStream.position; -// Constant inlinedValue; -// -// // something to initialize? -// if (initialization != null) { -// // initialize to constant value? -// if ((inlinedValue = initialization.constant) != NotAConstant) { -// // forget initializing unused or final locals set to constant value (final ones are inlined) -// if (binding.resolvedPosition != -1) { // may need to preserve variable -// int initPC = codeStream.position; -// codeStream.generateConstant(inlinedValue, initialization.implicitConversion); -// codeStream.recordPositionsFrom(initPC, initialization.sourceStart); -// codeStream.store(binding, false); -// binding.recordInitializationStartPC(codeStream.position); -// // codeStream.lastInitStateIndexWhenRemovingInits = -2; // reinitialize remove index -// // codeStream.lastInitStateIndexWhenAddingInits = -2; // reinitialize add index -// } -// } else { // initializing to non-constant value -// initialization.generateCode(currentScope, codeStream, true); -// // if binding unused generate then discard the value -// if (binding.resolvedPosition != -1) { -// // 26903, need extra cast to store null in array local var -// if (binding.type.isArrayType() -// && (initialization.resolvedType == NullBinding // arrayLoc = null -// || ((initialization instanceof CastExpression) // arrayLoc = (type[])null -// && (((CastExpression)initialization).innermostCastedExpression().resolvedType == NullBinding)))){ -// codeStream.checkcast(binding.type); -// } -// codeStream.store(binding, false); -// if (binding.initializationCount == 0) { -// /* Variable may have been initialized during the code initializing it -// e.g. int i = (i = 1); -// */ -// binding.recordInitializationStartPC(codeStream.position); -// // codeStream.lastInitStateIndexWhenRemovingInits = -2; // reinitialize remove index -// // codeStream.lastInitStateIndexWhenAddingInits = -2; // reinitialize add index -// } -// } else { -// if ((binding.type == LongBinding) || (binding.type == DoubleBinding)) { -// codeStream.pop2(); -// } else { -// codeStream.pop(); -// } -// } -// } -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } - + // public void generateCode(BlockScope currentScope, CodeStream codeStream) + // { + // + // // even if not reachable, variable must be added to visible if allocated + // (28298) + // if (binding.resolvedPosition != -1) { + // codeStream.addVisibleLocalVariable(binding); + // } + // if ((bits & IsReachableMASK) == 0) { + // return; + // } + // int pc = codeStream.position; + // Constant inlinedValue; + // + // // something to initialize? + // if (initialization != null) { + // // initialize to constant value? + // if ((inlinedValue = initialization.constant) != NotAConstant) { + // // forget initializing unused or final locals set to constant value + // (final ones are inlined) + // if (binding.resolvedPosition != -1) { // may need to preserve variable + // int initPC = codeStream.position; + // codeStream.generateConstant(inlinedValue, + // initialization.implicitConversion); + // codeStream.recordPositionsFrom(initPC, initialization.sourceStart); + // codeStream.store(binding, false); + // binding.recordInitializationStartPC(codeStream.position); + // // codeStream.lastInitStateIndexWhenRemovingInits = -2; // reinitialize + // remove index + // // codeStream.lastInitStateIndexWhenAddingInits = -2; // reinitialize add + // index + // } + // } else { // initializing to non-constant value + // initialization.generateCode(currentScope, codeStream, true); + // // if binding unused generate then discard the value + // if (binding.resolvedPosition != -1) { + // // 26903, need extra cast to store null in array local var + // if (binding.type.isArrayType() + // && (initialization.resolvedType == NullBinding // arrayLoc = null + // || ((initialization instanceof CastExpression) // arrayLoc = (type[])null + // && + // (((CastExpression)initialization).innermostCastedExpression().resolvedType + // == NullBinding)))){ + // codeStream.checkcast(binding.type); + // } + // codeStream.store(binding, false); + // if (binding.initializationCount == 0) { + // /* Variable may have been initialized during the code initializing it + // e.g. int i = (i = 1); + // */ + // binding.recordInitializationStartPC(codeStream.position); + // // codeStream.lastInitStateIndexWhenRemovingInits = -2; // reinitialize + // remove index + // // codeStream.lastInitStateIndexWhenAddingInits = -2; // reinitialize add + // index + // } + // } else { + // if ((binding.type == LongBinding) || (binding.type == DoubleBinding)) { + // codeStream.pop2(); + // } else { + // codeStream.pop(); + // } + // } + // } + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } public String name() { return String.valueOf(name); @@ -159,7 +164,8 @@ public class LocalDeclaration extends AbstractVariableDeclaration { scope.problemReporter().variableTypeCannotBeVoid(this); return; } - if (tb.isArrayType() && ((ArrayBinding) tb).leafComponentType == VoidBinding) { + if (tb.isArrayType() + && ((ArrayBinding) tb).leafComponentType == VoidBinding) { scope.problemReporter().variableTypeCannotBeVoidArray(this); return; } @@ -170,26 +176,29 @@ public class LocalDeclaration extends AbstractVariableDeclaration { // the name already exists... may carry on with the first binding... scope.problemReporter().redefineLocal(this); } else { - if ((modifiers & AccFinal)!= 0 && this.initialization == null) { + if ((modifiers & AccFinal) != 0 && this.initialization == null) { modifiers |= AccBlankFinal; } binding = new LocalVariableBinding(this, tb, modifiers, false); scope.addLocalVariable(binding); binding.constant = NotAConstant; // allow to recursivelly target the binding.... - // the correct constant is harmed if correctly computed at the end of this method + // the correct constant is harmed if correctly computed at the end + // of this method } if (tb == null) { if (initialization != null) - initialization.resolveType(scope); // want to report all possible errors + initialization.resolveType(scope); // want to report all + // possible errors return; } - // store the constant for final locals + // store the constant for final locals if (initialization != null) { if (initialization instanceof ArrayInitializer) { - TypeBinding initTb = initialization.resolveTypeExpecting(scope, tb); + TypeBinding initTb = initialization.resolveTypeExpecting(scope, + tb); if (initTb != null) { ((ArrayInitializer) initialization).binding = (ArrayBinding) initTb; initialization.implicitWidening(tb, initTb); @@ -197,21 +206,24 @@ public class LocalDeclaration extends AbstractVariableDeclaration { } else { TypeBinding initTb = initialization.resolveType(scope); if (initTb != null) { - if (initialization.isConstantValueOfTypeAssignableToType(initTb, tb) - || (tb.isBaseType() && BaseTypeBinding.isWidening(tb.id, initTb.id)) - || initTb.isCompatibleWith(tb)) + if (initialization.isConstantValueOfTypeAssignableToType( + initTb, tb) + || (tb.isBaseType() && BaseTypeBinding.isWidening( + tb.id, initTb.id)) + || initTb.isCompatibleWith(tb)) initialization.implicitWidening(tb, initTb); else - scope.problemReporter().typeMismatchError(initTb, tb, this); + scope.problemReporter().typeMismatchError(initTb, tb, + this); } } // change the constant in the binding when it is final - // (the optimization of the constant propagation will be done later on) + // (the optimization of the constant propagation will be done later + // on) // cast from constant actual type to variable type - binding.constant = - binding.isFinal() - ? initialization.constant.castTo((tb.id << 4) + initialization.constant.typeID()) + binding.constant = binding.isFinal() ? initialization.constant + .castTo((tb.id << 4) + initialization.constant.typeID()) : NotAConstant; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/LocalTypeDeclaration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/LocalTypeDeclaration.java index a75f126..0a123ce 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/LocalTypeDeclaration.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/LocalTypeDeclaration.java @@ -18,50 +18,50 @@ import net.sourceforge.phpdt.internal.compiler.problem.AbortType; public class LocalTypeDeclaration extends InnerTypeDeclaration { public AbstractMethodDeclaration enclosingMethod; -public LocalTypeDeclaration(CompilationResult compilationResult){ - super(compilationResult); -} + public LocalTypeDeclaration(CompilationResult compilationResult) { + super(compilationResult); + } -/** - * Iteration for a local innertype - * - */ -public void traverse(ASTVisitor visitor, BlockScope blockScope) { - if (ignoreFurtherInvestigation) - return; - try { - if (visitor.visit(this, blockScope)) { - if (superclass != null) - superclass.traverse(visitor, scope); - if (superInterfaces != null) { - int superInterfaceLength = superInterfaces.length; - for (int i = 0; i < superInterfaceLength; i++) - superInterfaces[i].traverse(visitor, scope); - } - if (memberTypes != null) { - int memberTypesLength = memberTypes.length; - for (int i = 0; i < memberTypesLength; i++) - memberTypes[i].traverse(visitor, scope); - } - if (fields != null) { - int fieldsLength = fields.length; - for (int i = 0; i < fieldsLength; i++) { - FieldDeclaration field; - if ((field = fields[i]).isStatic()) { - // local type cannot have static fields - } else { - field.traverse(visitor, initializerScope); + /** + * Iteration for a local innertype + * + */ + public void traverse(ASTVisitor visitor, BlockScope blockScope) { + if (ignoreFurtherInvestigation) + return; + try { + if (visitor.visit(this, blockScope)) { + if (superclass != null) + superclass.traverse(visitor, scope); + if (superInterfaces != null) { + int superInterfaceLength = superInterfaces.length; + for (int i = 0; i < superInterfaceLength; i++) + superInterfaces[i].traverse(visitor, scope); + } + if (memberTypes != null) { + int memberTypesLength = memberTypes.length; + for (int i = 0; i < memberTypesLength; i++) + memberTypes[i].traverse(visitor, scope); + } + if (fields != null) { + int fieldsLength = fields.length; + for (int i = 0; i < fieldsLength; i++) { + FieldDeclaration field; + if ((field = fields[i]).isStatic()) { + // local type cannot have static fields + } else { + field.traverse(visitor, initializerScope); + } } } + if (methods != null) { + int methodsLength = methods.length; + for (int i = 0; i < methodsLength; i++) + methods[i].traverse(visitor, scope); + } } - if (methods != null) { - int methodsLength = methods.length; - for (int i = 0; i < methodsLength; i++) - methods[i].traverse(visitor, scope); - } + visitor.endVisit(this, blockScope); + } catch (AbortType e) { } - visitor.endVisit(this, blockScope); - } catch (AbortType e) { } } -} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/LongLiteral.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/LongLiteral.java index e09a01d..7ee1423 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/LongLiteral.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/LongLiteral.java @@ -16,128 +16,152 @@ import net.sourceforge.phpdt.internal.compiler.impl.DoubleConstant; import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; - public class LongLiteral extends NumberLiteral { long value; - - static final Constant FORMAT_ERROR = new DoubleConstant(1.0/0.0); // NaN; - -public LongLiteral(char[] token, int s,int e) { - super(token, s,e); -} -public LongLiteral(char[] token, int s,int e, long value) { - this(token, s,e); - this.value = value; -} -public void computeConstant() { - //the overflow (when radix=10) is tested using the fact that - //the value should always grow during its computation - - int length = source.length - 1; //minus one because the last char is 'l' or 'L' - - long computedValue ; - if (source[0] == '0') - { if (length == 1) { constant = Constant.fromValue(0L); return; } - final int shift,radix; - int j ; - if ( (source[1] == 'x') | (source[1] == 'X') ) - { shift = 4 ; j = 2; radix = 16;} - else - { shift = 3 ; j = 1; radix = 8;} - int nbDigit = 0; - while (source[j]=='0') - { j++; //jump over redondant zero - if ( j == length) - { //watch for 0000000000000L - constant = Constant.fromValue(value = 0L); - return ;}} - - int digitValue ; - if ((digitValue = Character.digit(source[j++],radix)) < 0 ) - { constant = FORMAT_ERROR; return ;} - if (digitValue >= 8) nbDigit = 4; - else if (digitValue >= 4) nbDigit = 3; - else if (digitValue >= 2) nbDigit = 2; - else nbDigit = 1; //digitValue is not 0 - computedValue = digitValue ; - while (j 64) return /*constant stays null*/ ; - computedValue = (computedValue< computedValue) return /*constant stays null*/;}} - - constant = Constant.fromValue(value = computedValue); -} -/** - * Code generation for long literal - * - * @param currentScope net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream - * @param valueRequired boolean - */ -//public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) { -// int pc = codeStream.position; -// if (valueRequired) -// if ((implicitConversion >> 4) == T_long) -// codeStream.generateInlinedValue(value); -// else -// codeStream.generateConstant(constant, implicitConversion); -// codeStream.recordPositionsFrom(pc, this.sourceStart); -//} -public TypeBinding literalType(BlockScope scope) { - return LongBinding; -} -public final boolean mayRepresentMIN_VALUE(){ - //a special autorized int literral is 9223372036854775808L - //which is ONE over the limit. This special case - //only is used in combinaison with - to denote - //the minimal value of int -9223372036854775808L - - return ((source.length == 20) && - (source[0] == '9') && - (source[1] == '2') && - (source[2] == '2') && - (source[3] == '3') && - (source[4] == '3') && - (source[5] == '7') && - (source[6] == '2') && - (source[7] == '0') && - (source[8] == '3') && - (source[9] == '6') && - (source[10] == '8') && - (source[11] == '5') && - (source[12] == '4') && - (source[13] == '7') && - (source[14] == '7') && - (source[15] == '5') && - (source[16] == '8') && - (source[17] == '0') && - (source[18] == '8'));} -public TypeBinding resolveType(BlockScope scope) { - // the format may be incorrect while the scanner could detect - // such error only on painfull tests...easier and faster here - - TypeBinding tb = super.resolveType(scope); - if (constant == FORMAT_ERROR) { - constant = NotAConstant; - scope.problemReporter().constantOutOfFormat(this); - this.resolvedType = null; - return null; + + static final Constant FORMAT_ERROR = new DoubleConstant(1.0 / 0.0); // NaN; + + public LongLiteral(char[] token, int s, int e) { + super(token, s, e); + } + + public LongLiteral(char[] token, int s, int e, long value) { + this(token, s, e); + this.value = value; + } + + public void computeConstant() { + // the overflow (when radix=10) is tested using the fact that + // the value should always grow during its computation + + int length = source.length - 1; // minus one because the last char is + // 'l' or 'L' + + long computedValue; + if (source[0] == '0') { + if (length == 1) { + constant = Constant.fromValue(0L); + return; + } + final int shift, radix; + int j; + if ((source[1] == 'x') | (source[1] == 'X')) { + shift = 4; + j = 2; + radix = 16; + } else { + shift = 3; + j = 1; + radix = 8; + } + int nbDigit = 0; + while (source[j] == '0') { + j++; // jump over redondant zero + if (j == length) { // watch for 0000000000000L + constant = Constant.fromValue(value = 0L); + return; + } + } + + int digitValue; + if ((digitValue = Character.digit(source[j++], radix)) < 0) { + constant = FORMAT_ERROR; + return; + } + if (digitValue >= 8) + nbDigit = 4; + else if (digitValue >= 4) + nbDigit = 3; + else if (digitValue >= 2) + nbDigit = 2; + else + nbDigit = 1; // digitValue is not 0 + computedValue = digitValue; + while (j < length) { + if ((digitValue = Character.digit(source[j++], radix)) < 0) { + constant = FORMAT_ERROR; + return; + } + if ((nbDigit += shift) > 64) + return /* constant stays null */; + computedValue = (computedValue << shift) | digitValue; + } + } + + else { // -----------case radix=10----------------- + long previous = computedValue = 0; + for (int i = 0; i < length; i++) { + int digitValue; + if ((digitValue = Character.digit(source[i], 10)) < 0) + return /* constant stays null */; + previous = computedValue; + computedValue = 10 * computedValue + digitValue; + if (previous > computedValue) + return /* constant stays null */; + } + } + + constant = Constant.fromValue(value = computedValue); + } + + /** + * Code generation for long literal + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * @param valueRequired + * boolean + */ + // public void generateCode(BlockScope currentScope, CodeStream codeStream, + // boolean valueRequired) { + // int pc = codeStream.position; + // if (valueRequired) + // if ((implicitConversion >> 4) == T_long) + // codeStream.generateInlinedValue(value); + // else + // codeStream.generateConstant(constant, implicitConversion); + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } + public TypeBinding literalType(BlockScope scope) { + return LongBinding; + } + + public final boolean mayRepresentMIN_VALUE() { + // a special autorized int literral is 9223372036854775808L + // which is ONE over the limit. This special case + // only is used in combinaison with - to denote + // the minimal value of int -9223372036854775808L + + return ((source.length == 20) && (source[0] == '9') + && (source[1] == '2') && (source[2] == '2') + && (source[3] == '3') && (source[4] == '3') + && (source[5] == '7') && (source[6] == '2') + && (source[7] == '0') && (source[8] == '3') + && (source[9] == '6') && (source[10] == '8') + && (source[11] == '5') && (source[12] == '4') + && (source[13] == '7') && (source[14] == '7') + && (source[15] == '5') && (source[16] == '8') + && (source[17] == '0') && (source[18] == '8')); + } + + public TypeBinding resolveType(BlockScope scope) { + // the format may be incorrect while the scanner could detect + // such error only on painfull tests...easier and faster here + + TypeBinding tb = super.resolveType(scope); + if (constant == FORMAT_ERROR) { + constant = NotAConstant; + scope.problemReporter().constantOutOfFormat(this); + this.resolvedType = null; + return null; + } + return tb; + } + + public void traverse(IAbstractSyntaxTreeVisitor visitor, BlockScope scope) { + visitor.visit(this, scope); + visitor.endVisit(this, scope); } - return tb; -} -public void traverse(IAbstractSyntaxTreeVisitor visitor, BlockScope scope) { - visitor.visit(this, scope); - visitor.endVisit(this, scope); -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/LongLiteralMinValue.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/LongLiteralMinValue.java index eb4d900..c6de42d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/LongLiteralMinValue.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/LongLiteralMinValue.java @@ -12,17 +12,20 @@ package net.sourceforge.phpdt.internal.compiler.ast; import net.sourceforge.phpdt.internal.compiler.impl.Constant; - public class LongLiteralMinValue extends LongLiteral { - final static char[] CharValue = new char[]{'-', '9','2','2','3','3','7','2','0','3','6','8','5','4','7','7','5','8','0','8','L'}; - final static Constant MIN_VALUE = Constant.fromValue(Long.MIN_VALUE) ; + final static char[] CharValue = new char[] { '-', '9', '2', '2', '3', '3', + '7', '2', '0', '3', '6', '8', '5', '4', '7', '7', '5', '8', '0', + '8', 'L' }; -public LongLiteralMinValue(){ - super(CharValue,0,0,Long.MIN_VALUE); - constant = MIN_VALUE; -} -public void computeConstant() { + final static Constant MIN_VALUE = Constant.fromValue(Long.MIN_VALUE); + + public LongLiteralMinValue() { + super(CharValue, 0, 0, Long.MIN_VALUE); + constant = MIN_VALUE; + } + + public void computeConstant() { - /*precomputed at creation time*/} + /* precomputed at creation time */} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/MagicLiteral.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/MagicLiteral.java index 52faae0..6aa9856 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/MagicLiteral.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/MagicLiteral.java @@ -10,22 +10,27 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.compiler.ast; -public abstract class MagicLiteral extends Literal { -public MagicLiteral(int s , int e) { - super(s,e); -} -public boolean isValidJavaStatement(){ - //should never be reach, but with a bug in the ast tree.... - //see comment on the Statement class - - return false ;} -/** - * source method comment. - */ -public char[] source() { - return null; -} -public String toStringExpression(){ +public abstract class MagicLiteral extends Literal { + public MagicLiteral(int s, int e) { + super(s, e); + } + + public boolean isValidJavaStatement() { + // should never be reach, but with a bug in the ast tree.... + // see comment on the Statement class + + return false; + } + + /** + * source method comment. + */ + public char[] source() { + return null; + } + + public String toStringExpression() { - return new String(source()) ; } + return new String(source()); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/MemberTypeDeclaration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/MemberTypeDeclaration.java index 7320bbd..ea576bd 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/MemberTypeDeclaration.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/MemberTypeDeclaration.java @@ -17,50 +17,51 @@ import net.sourceforge.phpdt.internal.compiler.problem.AbortType; public class MemberTypeDeclaration extends InnerTypeDeclaration { public TypeDeclaration enclosingType; - -public MemberTypeDeclaration(CompilationResult compilationResult){ - super(compilationResult); -} -/** - * Iteration for a member innertype - * - */ -public void traverse(ASTVisitor visitor, ClassScope classScope) { - if (ignoreFurtherInvestigation) - return; - try { - if (visitor.visit(this, classScope)) { - if (superclass != null) - superclass.traverse(visitor, scope); - if (superInterfaces != null) { - int superInterfaceLength = superInterfaces.length; - for (int i = 0; i < superInterfaceLength; i++) - superInterfaces[i].traverse(visitor, scope); - } - if (memberTypes != null) { - int memberTypesLength = memberTypes.length; - for (int i = 0; i < memberTypesLength; i++) - memberTypes[i].traverse(visitor, scope); - } - if (fields != null) { - int fieldsLength = fields.length; - for (int i = 0; i < fieldsLength; i++) { - FieldDeclaration field; - if ((field = fields[i]).isStatic()) { - field.traverse(visitor, staticInitializerScope); - } else { - field.traverse(visitor, initializerScope); + + public MemberTypeDeclaration(CompilationResult compilationResult) { + super(compilationResult); + } + + /** + * Iteration for a member innertype + * + */ + public void traverse(ASTVisitor visitor, ClassScope classScope) { + if (ignoreFurtherInvestigation) + return; + try { + if (visitor.visit(this, classScope)) { + if (superclass != null) + superclass.traverse(visitor, scope); + if (superInterfaces != null) { + int superInterfaceLength = superInterfaces.length; + for (int i = 0; i < superInterfaceLength; i++) + superInterfaces[i].traverse(visitor, scope); + } + if (memberTypes != null) { + int memberTypesLength = memberTypes.length; + for (int i = 0; i < memberTypesLength; i++) + memberTypes[i].traverse(visitor, scope); + } + if (fields != null) { + int fieldsLength = fields.length; + for (int i = 0; i < fieldsLength; i++) { + FieldDeclaration field; + if ((field = fields[i]).isStatic()) { + field.traverse(visitor, staticInitializerScope); + } else { + field.traverse(visitor, initializerScope); + } } } + if (methods != null) { + int methodsLength = methods.length; + for (int i = 0; i < methodsLength; i++) + methods[i].traverse(visitor, scope); + } } - if (methods != null) { - int methodsLength = methods.length; - for (int i = 0; i < methodsLength; i++) - methods[i].traverse(visitor, scope); - } + visitor.endVisit(this, classScope); + } catch (AbortType e) { } - visitor.endVisit(this, classScope); - } catch (AbortType e) { } } -} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/MessageSend.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/MessageSend.java index cdb2f4b..0295099 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/MessageSend.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/MessageSend.java @@ -23,290 +23,342 @@ import net.sourceforge.phpdt.internal.compiler.lookup.SourceTypeBinding; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class MessageSend extends Expression implements InvocationSite { - public Expression receiver ; - public char[] selector ; - public Expression[] arguments ; + public Expression receiver; + + public char[] selector; + + public Expression[] arguments; + public MethodBinding binding, codegenBinding; - public long nameSourcePosition ; //(start<<32)+end + public long nameSourcePosition; // (start<<32)+end MethodBinding syntheticAccessor; public TypeBinding receiverType, qualifyingType; - -public MessageSend() { - -} -public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { - flowInfo = receiver.analyseCode(currentScope, flowContext, flowInfo, !binding.isStatic()).unconditionalInits(); - if (arguments != null) { - int length = arguments.length; - for (int i = 0; i < length; i++) { - flowInfo = arguments[i].analyseCode(currentScope, flowContext, flowInfo).unconditionalInits(); + public MessageSend() { + + } + + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { + + flowInfo = receiver.analyseCode(currentScope, flowContext, flowInfo, + !binding.isStatic()).unconditionalInits(); + if (arguments != null) { + int length = arguments.length; + for (int i = 0; i < length; i++) { + flowInfo = arguments[i].analyseCode(currentScope, flowContext, + flowInfo).unconditionalInits(); + } } + ReferenceBinding[] thrownExceptions; + if ((thrownExceptions = binding.thrownExceptions) != NoExceptions) { + // must verify that exceptions potentially thrown by this expression + // are caught in the method + flowContext.checkExceptionHandlers(thrownExceptions, this, + flowInfo, currentScope); + } + manageSyntheticAccessIfNecessary(currentScope); + return flowInfo; } - ReferenceBinding[] thrownExceptions; - if ((thrownExceptions = binding.thrownExceptions) != NoExceptions) { - // must verify that exceptions potentially thrown by this expression are caught in the method - flowContext.checkExceptionHandlers(thrownExceptions, this, flowInfo, currentScope); + + /** + * MessageSend code generation + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * @param valueRequired + * boolean + */ + // public void generateCode(BlockScope currentScope, CodeStream codeStream, + // boolean valueRequired) { + // + // int pc = codeStream.position; + // + // // generate receiver/enclosing instance access + // boolean isStatic = codegenBinding.isStatic(); + // // outer access ? + // if (!isStatic && ((bits & DepthMASK) != 0) && receiver.isImplicitThis()){ + // // outer method can be reached through emulation if implicit access + // ReferenceBinding targetType = + // currentScope.enclosingSourceType().enclosingTypeAt((bits & DepthMASK) >> + // DepthSHIFT); + // Object[] path = currentScope.getEmulationPath(targetType, true /*only + // exact match*/, false/*consider enclosing arg*/); + // codeStream.generateOuterAccess(path, this, targetType, currentScope); + // } else { + // receiver.generateCode(currentScope, codeStream, !isStatic); + // } + // // generate arguments + // if (arguments != null){ + // for (int i = 0, max = arguments.length; i < max; i++){ + // arguments[i].generateCode(currentScope, codeStream, true); + // } + // } + // // actual message invocation + // if (syntheticAccessor == null){ + // if (isStatic){ + // codeStream.invokestatic(codegenBinding); + // } else { + // if( (receiver.isSuper()) || codegenBinding.isPrivate()){ + // codeStream.invokespecial(codegenBinding); + // } else { + // if (codegenBinding.declaringClass.isInterface()){ + // codeStream.invokeinterface(codegenBinding); + // } else { + // codeStream.invokevirtual(codegenBinding); + // } + // } + // } + // } else { + // codeStream.invokestatic(syntheticAccessor); + // } + // // operation on the returned value + // if (valueRequired){ + // // implicit conversion if necessary + // codeStream.generateImplicitConversion(implicitConversion); + // } else { + // // pop return value if any + // switch(binding.returnType.id){ + // case T_long : + // case T_double : + // codeStream.pop2(); + // break; + // case T_void : + // break; + // default: + // codeStream.pop(); + // } + // } + // codeStream.recordPositionsFrom(pc, (int)(this.nameSourcePosition >>> + // 32)); // highlight selector + // } + public boolean isSuperAccess() { + return receiver.isSuper(); } - manageSyntheticAccessIfNecessary(currentScope); - return flowInfo; -} -/** - * MessageSend code generation - * - * @param currentScope net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream - * @param valueRequired boolean - */ -//public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) { -// -// int pc = codeStream.position; -// -// // generate receiver/enclosing instance access -// boolean isStatic = codegenBinding.isStatic(); -// // outer access ? -// if (!isStatic && ((bits & DepthMASK) != 0) && receiver.isImplicitThis()){ -// // outer method can be reached through emulation if implicit access -// ReferenceBinding targetType = currentScope.enclosingSourceType().enclosingTypeAt((bits & DepthMASK) >> DepthSHIFT); -// Object[] path = currentScope.getEmulationPath(targetType, true /*only exact match*/, false/*consider enclosing arg*/); -// codeStream.generateOuterAccess(path, this, targetType, currentScope); -// } else { -// receiver.generateCode(currentScope, codeStream, !isStatic); -// } -// // generate arguments -// if (arguments != null){ -// for (int i = 0, max = arguments.length; i < max; i++){ -// arguments[i].generateCode(currentScope, codeStream, true); -// } -// } -// // actual message invocation -// if (syntheticAccessor == null){ -// if (isStatic){ -// codeStream.invokestatic(codegenBinding); -// } else { -// if( (receiver.isSuper()) || codegenBinding.isPrivate()){ -// codeStream.invokespecial(codegenBinding); -// } else { -// if (codegenBinding.declaringClass.isInterface()){ -// codeStream.invokeinterface(codegenBinding); -// } else { -// codeStream.invokevirtual(codegenBinding); -// } -// } -// } -// } else { -// codeStream.invokestatic(syntheticAccessor); -// } -// // operation on the returned value -// if (valueRequired){ -// // implicit conversion if necessary -// codeStream.generateImplicitConversion(implicitConversion); -// } else { -// // pop return value if any -// switch(binding.returnType.id){ -// case T_long : -// case T_double : -// codeStream.pop2(); -// break; -// case T_void : -// break; -// default: -// codeStream.pop(); -// } -// } -// codeStream.recordPositionsFrom(pc, (int)(this.nameSourcePosition >>> 32)); // highlight selector -//} -public boolean isSuperAccess() { - return receiver.isSuper(); -} -public boolean isTypeAccess() { - return receiver != null && receiver.isTypeReference(); -} -public void manageSyntheticAccessIfNecessary(BlockScope currentScope){ - if (binding.isPrivate()){ + public boolean isTypeAccess() { + return receiver != null && receiver.isTypeReference(); + } - // depth is set for both implicit and explicit access (see MethodBinding#canBeSeenBy) - if (currentScope.enclosingSourceType() != binding.declaringClass){ - - syntheticAccessor = ((SourceTypeBinding)binding.declaringClass).addSyntheticMethod(binding, isSuperAccess()); - currentScope.problemReporter().needToEmulateMethodAccess(binding, this); - return; - } + public void manageSyntheticAccessIfNecessary(BlockScope currentScope) { - } else if (receiver instanceof QualifiedSuperReference){ // qualified super + if (binding.isPrivate()) { - // qualified super need emulation always - SourceTypeBinding destinationType = (SourceTypeBinding)(((QualifiedSuperReference)receiver).currentCompatibleType); - syntheticAccessor = destinationType.addSyntheticMethod(binding, isSuperAccess()); - currentScope.problemReporter().needToEmulateMethodAccess(binding, this); - return; + // depth is set for both implicit and explicit access (see + // MethodBinding#canBeSeenBy) + if (currentScope.enclosingSourceType() != binding.declaringClass) { - } else if (binding.isProtected()){ + syntheticAccessor = ((SourceTypeBinding) binding.declaringClass) + .addSyntheticMethod(binding, isSuperAccess()); + currentScope.problemReporter().needToEmulateMethodAccess( + binding, this); + return; + } - SourceTypeBinding enclosingSourceType; - if (((bits & DepthMASK) != 0) - && binding.declaringClass.getPackage() - != (enclosingSourceType = currentScope.enclosingSourceType()).getPackage()){ + } else if (receiver instanceof QualifiedSuperReference) { // qualified + // super - SourceTypeBinding currentCompatibleType = (SourceTypeBinding)enclosingSourceType.enclosingTypeAt((bits & DepthMASK) >> DepthSHIFT); - syntheticAccessor = currentCompatibleType.addSyntheticMethod(binding, isSuperAccess()); - currentScope.problemReporter().needToEmulateMethodAccess(binding, this); + // qualified super need emulation always + SourceTypeBinding destinationType = (SourceTypeBinding) (((QualifiedSuperReference) receiver).currentCompatibleType); + syntheticAccessor = destinationType.addSyntheticMethod(binding, + isSuperAccess()); + currentScope.problemReporter().needToEmulateMethodAccess(binding, + this); return; + + } else if (binding.isProtected()) { + + SourceTypeBinding enclosingSourceType; + if (((bits & DepthMASK) != 0) + && binding.declaringClass.getPackage() != (enclosingSourceType = currentScope + .enclosingSourceType()).getPackage()) { + + SourceTypeBinding currentCompatibleType = (SourceTypeBinding) enclosingSourceType + .enclosingTypeAt((bits & DepthMASK) >> DepthSHIFT); + syntheticAccessor = currentCompatibleType.addSyntheticMethod( + binding, isSuperAccess()); + currentScope.problemReporter().needToEmulateMethodAccess( + binding, this); + return; + } } + // if the binding declaring class is not visible, need special action + // for runtime compatibility on 1.2 VMs : change the declaring class of + // the binding + // NOTE: from target 1.2 on, method's declaring class is touched if any + // different from receiver type + // and not from Object or implicit static method call. + // if (binding.declaringClass != this.qualifyingType + // && !this.qualifyingType.isArrayType() + // && ((currentScope.environment().options.targetJDK >= + // CompilerOptions.JDK1_2 + // && (!receiver.isImplicitThis() || !binding.isStatic()) + // && binding.declaringClass.id != T_Object) // no change for Object + // methods + // || !binding.declaringClass.canBeSeenBy(currentScope))) { + // + // this.codegenBinding = + // currentScope.enclosingSourceType().getUpdatedMethodBinding(binding, + // (ReferenceBinding) this.qualifyingType); + // } } - // if the binding declaring class is not visible, need special action - // for runtime compatibility on 1.2 VMs : change the declaring class of the binding - // NOTE: from target 1.2 on, method's declaring class is touched if any different from receiver type - // and not from Object or implicit static method call. -// if (binding.declaringClass != this.qualifyingType -// && !this.qualifyingType.isArrayType() -// && ((currentScope.environment().options.targetJDK >= CompilerOptions.JDK1_2 -// && (!receiver.isImplicitThis() || !binding.isStatic()) -// && binding.declaringClass.id != T_Object) // no change for Object methods -// || !binding.declaringClass.canBeSeenBy(currentScope))) { -// -// this.codegenBinding = currentScope.enclosingSourceType().getUpdatedMethodBinding(binding, (ReferenceBinding) this.qualifyingType); -// } -} -public StringBuffer printExpression(int indent, StringBuffer output){ - - if (!receiver.isImplicitThis()) receiver.printExpression(0, output).append('.'); - output.append(selector).append('(') ; //$NON-NLS-1$ - if (arguments != null) { - for (int i = 0; i < arguments.length ; i ++) { - if (i > 0) output.append(", "); //$NON-NLS-1$ - arguments[i].printExpression(0, output); - } - } - return output.append(')'); -} -public TypeBinding resolveType(BlockScope scope) { - // Answer the signature return type - // Base type promotion - - constant = NotAConstant; - this.qualifyingType = this.receiverType = receiver.resolveType(scope); - - // will check for null after args are resolved - TypeBinding[] argumentTypes = NoParameters; - if (arguments != null) { - boolean argHasError = false; // typeChecks all arguments - int length = arguments.length; - argumentTypes = new TypeBinding[length]; - for (int i = 0; i < length; i++){ - if ((argumentTypes[i] = arguments[i].resolveType(scope)) == null){ - argHasError = true; + + public StringBuffer printExpression(int indent, StringBuffer output) { + + if (!receiver.isImplicitThis()) + receiver.printExpression(0, output).append('.'); + output.append(selector).append('('); //$NON-NLS-1$ + if (arguments != null) { + for (int i = 0; i < arguments.length; i++) { + if (i > 0) + output.append(", "); //$NON-NLS-1$ + arguments[i].printExpression(0, output); } } - if (argHasError){ - if(receiverType instanceof ReferenceBinding) { - // record any selector match, for clients who may still need hint about possible method match - this.codegenBinding = this.binding = scope.findMethod((ReferenceBinding)receiverType, selector, new TypeBinding[]{}, this); - } - return null; - } + return output.append(')'); } - if (this.receiverType == null) - return null; - // base type cannot receive any message - if (this.receiverType.isBaseType()) { - scope.problemReporter().errorNoMethodFor(this, this.receiverType, argumentTypes); - return null; - } + public TypeBinding resolveType(BlockScope scope) { + // Answer the signature return type + // Base type promotion - this.codegenBinding = this.binding = - receiver.isImplicitThis() - ? scope.getImplicitMethod(selector, argumentTypes, this) - : scope.getMethod(this.receiverType, selector, argumentTypes, this); - if (!binding.isValidBinding()) { - if (binding.declaringClass == null) { - if (this.receiverType instanceof ReferenceBinding) { - binding.declaringClass = (ReferenceBinding) this.receiverType; - } else { - scope.problemReporter().errorNoMethodFor(this, this.receiverType, argumentTypes); + constant = NotAConstant; + this.qualifyingType = this.receiverType = receiver.resolveType(scope); + + // will check for null after args are resolved + TypeBinding[] argumentTypes = NoParameters; + if (arguments != null) { + boolean argHasError = false; // typeChecks all arguments + int length = arguments.length; + argumentTypes = new TypeBinding[length]; + for (int i = 0; i < length; i++) { + if ((argumentTypes[i] = arguments[i].resolveType(scope)) == null) { + argHasError = true; + } + } + if (argHasError) { + if (receiverType instanceof ReferenceBinding) { + // record any selector match, for clients who may still need + // hint about possible method match + this.codegenBinding = this.binding = scope.findMethod( + (ReferenceBinding) receiverType, selector, + new TypeBinding[] {}, this); + } return null; } } - scope.problemReporter().invalidMethod(this, binding); - // record the closest match, for clients who may still need hint about possible method match - if (binding instanceof ProblemMethodBinding){ - MethodBinding closestMatch = ((ProblemMethodBinding)binding).closestMatch; - if (closestMatch != null) this.codegenBinding = this.binding = closestMatch; + if (this.receiverType == null) + return null; + + // base type cannot receive any message + if (this.receiverType.isBaseType()) { + scope.problemReporter().errorNoMethodFor(this, this.receiverType, + argumentTypes); + return null; } - return binding == null ? null : binding.returnType; - } - if (!binding.isStatic()) { - // the "receiver" must not be a type, in other words, a NameReference that the TC has bound to a Type - if (receiver instanceof NameReference - && (((NameReference) receiver).bits & BindingIds.TYPE) != 0) { - scope.problemReporter().mustUseAStaticMethod(this, binding); + + this.codegenBinding = this.binding = receiver.isImplicitThis() ? scope + .getImplicitMethod(selector, argumentTypes, this) : scope + .getMethod(this.receiverType, selector, argumentTypes, this); + if (!binding.isValidBinding()) { + if (binding.declaringClass == null) { + if (this.receiverType instanceof ReferenceBinding) { + binding.declaringClass = (ReferenceBinding) this.receiverType; + } else { + scope.problemReporter().errorNoMethodFor(this, + this.receiverType, argumentTypes); + return null; + } + } + scope.problemReporter().invalidMethod(this, binding); + // record the closest match, for clients who may still need hint + // about possible method match + if (binding instanceof ProblemMethodBinding) { + MethodBinding closestMatch = ((ProblemMethodBinding) binding).closestMatch; + if (closestMatch != null) + this.codegenBinding = this.binding = closestMatch; + } + return binding == null ? null : binding.returnType; } - } else { - // static message invoked through receiver? legal but unoptimal (optional warning). - if (!(receiver.isImplicitThis() - || receiver.isSuper() - || (receiver instanceof NameReference - && (((NameReference) receiver).bits & BindingIds.TYPE) != 0))) { - scope.problemReporter().unnecessaryReceiverForStaticMethod(this, binding); + if (!binding.isStatic()) { + // the "receiver" must not be a type, in other words, a + // NameReference that the TC has bound to a Type + if (receiver instanceof NameReference + && (((NameReference) receiver).bits & BindingIds.TYPE) != 0) { + scope.problemReporter().mustUseAStaticMethod(this, binding); + } + } else { + // static message invoked through receiver? legal but unoptimal + // (optional warning). + if (!(receiver.isImplicitThis() || receiver.isSuper() || (receiver instanceof NameReference && (((NameReference) receiver).bits & BindingIds.TYPE) != 0))) { + scope.problemReporter().unnecessaryReceiverForStaticMethod( + this, binding); + } } + if (arguments != null) + for (int i = 0; i < arguments.length; i++) + arguments[i].implicitWidening(binding.parameters[i], + argumentTypes[i]); + + // -------message send that are known to fail at compile time----------- + if (binding.isAbstract()) { + if (receiver.isSuper()) { + scope.problemReporter().cannotDireclyInvokeAbstractMethod(this, + binding); + } + // abstract private methods cannot occur nor abstract + // static............ + } + if (isMethodUseDeprecated(binding, scope)) + scope.problemReporter().deprecatedMethod(binding, this); + + return this.resolvedType = binding.returnType; + } + + public void setActualReceiverType(ReferenceBinding receiverType) { + this.qualifyingType = receiverType; } - if (arguments != null) - for (int i = 0; i < arguments.length; i++) - arguments[i].implicitWidening(binding.parameters[i], argumentTypes[i]); - - //-------message send that are known to fail at compile time----------- - if (binding.isAbstract()) { - if (receiver.isSuper()) { - scope.problemReporter().cannotDireclyInvokeAbstractMethod(this, binding); + + public void setDepth(int depth) { + bits &= ~DepthMASK; // flush previous depth if any + if (depth > 0) { + bits |= (depth & 0xFF) << DepthSHIFT; // encoded on 8 bits } - // abstract private methods cannot occur nor abstract static............ } - if (isMethodUseDeprecated(binding, scope)) - scope.problemReporter().deprecatedMethod(binding, this); - return this.resolvedType = binding.returnType; -} -public void setActualReceiverType(ReferenceBinding receiverType) { - this.qualifyingType = receiverType; -} -public void setDepth(int depth) { - bits &= ~DepthMASK; // flush previous depth if any - if (depth > 0) { - bits |= (depth & 0xFF) << DepthSHIFT; // encoded on 8 bits + public void setFieldIndex(int depth) { + // ignore for here } -} -public void setFieldIndex(int depth) { - // ignore for here -} -public String toStringExpression(){ - - String s = ""; //$NON-NLS-1$ - if (!receiver.isImplicitThis()) - s = s + receiver.toStringExpression()+"."; //$NON-NLS-1$ - s = s + new String(selector) + "(" ; //$NON-NLS-1$ - if (arguments != null) - for (int i = 0; i < arguments.length ; i ++) - { s = s + arguments[i].toStringExpression(); - if ( i != arguments.length -1 ) s = s + " , " ;};; //$NON-NLS-1$ - s =s + ")" ; //$NON-NLS-1$ - return s; -} + public String toStringExpression() { -public void traverse(ASTVisitor visitor, BlockScope blockScope) { - if (visitor.visit(this, blockScope)) { - receiver.traverse(visitor, blockScope); - if (arguments != null) { - int argumentsLength = arguments.length; - for (int i = 0; i < argumentsLength; i++) - arguments[i].traverse(visitor, blockScope); + String s = ""; //$NON-NLS-1$ + if (!receiver.isImplicitThis()) + s = s + receiver.toStringExpression() + "."; //$NON-NLS-1$ + s = s + new String(selector) + "("; //$NON-NLS-1$ + if (arguments != null) + for (int i = 0; i < arguments.length; i++) { + s = s + arguments[i].toStringExpression(); + if (i != arguments.length - 1) + s = s + " , ";};; //$NON-NLS-1$ + s = s + ")"; //$NON-NLS-1$ + return s; + } + + public void traverse(ASTVisitor visitor, BlockScope blockScope) { + if (visitor.visit(this, blockScope)) { + receiver.traverse(visitor, blockScope); + if (arguments != null) { + int argumentsLength = arguments.length; + for (int i = 0; i < argumentsLength; i++) + arguments[i].traverse(visitor, blockScope); + } } + visitor.endVisit(this, blockScope); } - visitor.endVisit(this, blockScope); -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/MethodDeclaration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/MethodDeclaration.java index 0e23833..d41b0e8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/MethodDeclaration.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/MethodDeclaration.java @@ -23,136 +23,152 @@ import net.sourceforge.phpdt.internal.compiler.problem.AbortMethod; public class MethodDeclaration extends AbstractMethodDeclaration { - public TypeReference returnType; - public static final int FUNCTION_DEFINITION = 1; - public static final int METHOD_DEFINITION = 2; - public int type; - - /** - * MethodDeclaration constructor comment. - */ - public MethodDeclaration(CompilationResult compilationResult) { - super(compilationResult); - } - - public void analyseCode(ClassScope classScope, InitializationFlowContext initializationContext, FlowInfo flowInfo) { - - // starting of the code analysis for methods - if (ignoreFurtherInvestigation) - return; - try { - if (binding == null) - return; - - if (this.binding.isPrivate() && !this.binding.isPrivateUsed()) { - if (!classScope.referenceCompilationUnit().compilationResult.hasSyntaxError()) { - scope.problemReporter().unusedPrivateMethod(this); - } - } - - // may be in a non necessary for innerclass with static final constant fields - if (binding.isAbstract()) // || binding.isNative()) - return; - - ExceptionHandlingFlowContext methodContext = - new ExceptionHandlingFlowContext(initializationContext, this, binding.thrownExceptions, scope, FlowInfo.DEAD_END); - - // propagate to statements - if (statements != null) { - boolean didAlreadyComplain = false; - for (int i = 0, count = statements.length; i < count; i++) { - Statement stat; - if (!flowInfo.complainIfUnreachable((stat = statements[i]), scope, didAlreadyComplain)) { - flowInfo = stat.analyseCode(scope, methodContext, flowInfo); - } else { - didAlreadyComplain = true; - } - } - } - // check for missing returning path - TypeBinding returnType = binding.returnType; - if ((returnType == VoidBinding) || isAbstract()) { - this.needFreeReturn = flowInfo.isReachable(); - } else { - if (flowInfo != FlowInfo.DEAD_END) { - scope.problemReporter().shouldReturn(returnType, this); - } - } - } catch (AbortMethod e) { - this.ignoreFurtherInvestigation = true; - } - } - - public void parseStatements(UnitParser parser, CompilationUnitDeclaration unit) { - - //fill up the method body with statement - if (ignoreFurtherInvestigation) - return; - parser.parse(this, unit); - } - - public void resolveStatements() { - - // ========= abort on fatal error ============= - if (this.returnType != null && this.binding != null) { - this.returnType.resolvedType = this.binding.returnType; - // record the return type binding - } - // look if the name of the method is correct - if (binding != null && isTypeUseDeprecated(binding.returnType, scope)) - scope.problemReporter().deprecatedType(binding.returnType, returnType); - - if (scope != null) { - if (CharOperation.equals(scope.enclosingSourceType().sourceName, selector)) - scope.problemReporter().methodWithConstructorName(this); - - // by grammatical construction, interface methods are always abstract - if (!scope.enclosingSourceType().isInterface()) { - - // if a method has an semicolon body and is not declared as abstract==>error - // native methods may have a semicolon body - // if ((modifiers & AccSemicolonBody) != 0) { - // if ((modifiers & AccNative) == 0) - // if ((modifiers & AccAbstract) == 0) - // scope.problemReporter().methodNeedingAbstractModifier(this); - // } else { - // // the method HAS a body --> abstract native modifiers are forbiden - // if (((modifiers & AccNative) != 0) || ((modifiers & AccAbstract) != 0)) - // scope.problemReporter().methodNeedingNoBody(this); - // } - } - } - super.resolveStatements(); - } - - public String returnTypeToString(int tab) { - - if (returnType == null) - return ""; //$NON-NLS-1$ - return returnType.toString(tab) + " "; //$NON-NLS-1$ - } - - public void traverse(ASTVisitor visitor, ClassScope classScope) { - - if (visitor.visit(this, classScope)) { - if (returnType != null) - returnType.traverse(visitor, scope); - if (arguments != null) { - int argumentLength = arguments.length; - for (int i = 0; i < argumentLength; i++) - arguments[i].traverse(visitor, scope); - } - if (thrownExceptions != null) { - int thrownExceptionsLength = thrownExceptions.length; - for (int i = 0; i < thrownExceptionsLength; i++) - thrownExceptions[i].traverse(visitor, scope); - } - if (statements != null) { - int statementsLength = statements.length; - for (int i = 0; i < statementsLength; i++) - statements[i].traverse(visitor, scope); - } - } - visitor.endVisit(this, classScope); - } + public TypeReference returnType; + + public static final int FUNCTION_DEFINITION = 1; + + public static final int METHOD_DEFINITION = 2; + + public int type; + + /** + * MethodDeclaration constructor comment. + */ + public MethodDeclaration(CompilationResult compilationResult) { + super(compilationResult); + } + + public void analyseCode(ClassScope classScope, + InitializationFlowContext initializationContext, FlowInfo flowInfo) { + + // starting of the code analysis for methods + if (ignoreFurtherInvestigation) + return; + try { + if (binding == null) + return; + + if (this.binding.isPrivate() && !this.binding.isPrivateUsed()) { + if (!classScope.referenceCompilationUnit().compilationResult + .hasSyntaxError()) { + scope.problemReporter().unusedPrivateMethod(this); + } + } + + // may be in a non necessary for innerclass with static + // final constant fields + if (binding.isAbstract()) // || binding.isNative()) + return; + + ExceptionHandlingFlowContext methodContext = new ExceptionHandlingFlowContext( + initializationContext, this, binding.thrownExceptions, + scope, FlowInfo.DEAD_END); + + // propagate to statements + if (statements != null) { + boolean didAlreadyComplain = false; + for (int i = 0, count = statements.length; i < count; i++) { + Statement stat; + if (!flowInfo.complainIfUnreachable((stat = statements[i]), + scope, didAlreadyComplain)) { + flowInfo = stat.analyseCode(scope, methodContext, + flowInfo); + } else { + didAlreadyComplain = true; + } + } + } + // check for missing returning path + TypeBinding returnType = binding.returnType; + if ((returnType == VoidBinding) || isAbstract()) { + this.needFreeReturn = flowInfo.isReachable(); + } else { + if (flowInfo != FlowInfo.DEAD_END) { + scope.problemReporter().shouldReturn(returnType, this); + } + } + } catch (AbortMethod e) { + this.ignoreFurtherInvestigation = true; + } + } + + public void parseStatements(UnitParser parser, + CompilationUnitDeclaration unit) { + + // fill up the method body with statement + if (ignoreFurtherInvestigation) + return; + parser.parse(this, unit); + } + + public void resolveStatements() { + + // ========= abort on fatal error ============= + if (this.returnType != null && this.binding != null) { + this.returnType.resolvedType = this.binding.returnType; + // record the return type binding + } + // look if the name of the method is correct + if (binding != null && isTypeUseDeprecated(binding.returnType, scope)) + scope.problemReporter().deprecatedType(binding.returnType, + returnType); + + if (scope != null) { + if (CharOperation.equals(scope.enclosingSourceType().sourceName, + selector)) + scope.problemReporter().methodWithConstructorName(this); + + // by grammatical construction, interface methods are always + // abstract + if (!scope.enclosingSourceType().isInterface()) { + + // if a method has an semicolon body and is not declared as + // abstract==>error + // native methods may have a semicolon body + // if ((modifiers & AccSemicolonBody) != 0) { + // if ((modifiers & AccNative) == 0) + // if ((modifiers & AccAbstract) == 0) + // scope.problemReporter().methodNeedingAbstractModifier(this); + // } else { + // // the method HAS a body --> abstract native modifiers are + // forbiden + // if (((modifiers & AccNative) != 0) || ((modifiers & + // AccAbstract) != 0)) + // scope.problemReporter().methodNeedingNoBody(this); + // } + } + } + super.resolveStatements(); + } + + public String returnTypeToString(int tab) { + + if (returnType == null) + return ""; //$NON-NLS-1$ + return returnType.toString(tab) + " "; //$NON-NLS-1$ + } + + public void traverse(ASTVisitor visitor, ClassScope classScope) { + + if (visitor.visit(this, classScope)) { + if (returnType != null) + returnType.traverse(visitor, scope); + if (arguments != null) { + int argumentLength = arguments.length; + for (int i = 0; i < argumentLength; i++) + arguments[i].traverse(visitor, scope); + } + if (thrownExceptions != null) { + int thrownExceptionsLength = thrownExceptions.length; + for (int i = 0; i < thrownExceptionsLength; i++) + thrownExceptions[i].traverse(visitor, scope); + } + if (statements != null) { + int statementsLength = statements.length; + for (int i = 0; i < statementsLength; i++) + statements[i].traverse(visitor, scope); + } + } + visitor.endVisit(this, classScope); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/NameReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/NameReference.java index 3dbaaa9..626e4dd 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/NameReference.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/NameReference.java @@ -17,53 +17,66 @@ import net.sourceforge.phpdt.internal.compiler.lookup.InvocationSite; import net.sourceforge.phpdt.internal.compiler.lookup.ReferenceBinding; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; -public abstract class NameReference extends Reference implements InvocationSite, BindingIds { - - public Binding binding, codegenBinding; //may be aTypeBinding-aFieldBinding-aLocalVariableBinding - - public TypeBinding receiverType; // raw receiver type - public TypeBinding actualReceiverType; // modified receiver type - actual one according to namelookup - - //the error printing - //some name reference are build as name reference but - //only used as type reference. When it happens, instead of - //creating a new objet (aTypeReference) we just flag a boolean - //This concesion is valuable while their are cases when the NameReference - //will be a TypeReference (static message sends.....) and there is - //no changeClass in java. -public NameReference() { - super(); - bits |= TYPE | VARIABLE; // restrictiveFlag - -} -public FieldBinding fieldBinding() { - //this method should be sent ONLY after a check against isFieldReference() - //check its use doing senders......... +public abstract class NameReference extends Reference implements + InvocationSite, BindingIds { + + public Binding binding, codegenBinding; // may be + // aTypeBinding-aFieldBinding-aLocalVariableBinding + + public TypeBinding receiverType; // raw receiver type + + public TypeBinding actualReceiverType; // modified receiver type - actual + // one according to namelookup + + // the error printing + // some name reference are build as name reference but + // only used as type reference. When it happens, instead of + // creating a new objet (aTypeReference) we just flag a boolean + // This concesion is valuable while their are cases when the NameReference + // will be a TypeReference (static message sends.....) and there is + // no changeClass in java. + public NameReference() { + super(); + bits |= TYPE | VARIABLE; // restrictiveFlag - return (FieldBinding) binding ; -} -public boolean isSuperAccess() { - return false; -} -public boolean isTypeAccess() { - // null is acceptable when we are resolving the first part of a reference - return binding == null || binding instanceof ReferenceBinding; -} -public boolean isTypeReference() { - return binding instanceof ReferenceBinding; -} -public void setActualReceiverType(ReferenceBinding receiverType) { - this.actualReceiverType = receiverType; -} -public void setDepth(int depth) { - bits &= ~DepthMASK; // flush previous depth if any - if (depth > 0) { - bits |= (depth & 0xFF) << DepthSHIFT; // encoded on 8 bits } -} -public void setFieldIndex(int index){ - // ignored -} -public abstract String unboundReferenceErrorName(); + public FieldBinding fieldBinding() { + // this method should be sent ONLY after a check against + // isFieldReference() + // check its use doing senders......... + + return (FieldBinding) binding; + } + + public boolean isSuperAccess() { + return false; + } + + public boolean isTypeAccess() { + // null is acceptable when we are resolving the first part of a + // reference + return binding == null || binding instanceof ReferenceBinding; + } + + public boolean isTypeReference() { + return binding instanceof ReferenceBinding; + } + + public void setActualReceiverType(ReferenceBinding receiverType) { + this.actualReceiverType = receiverType; + } + + public void setDepth(int depth) { + bits &= ~DepthMASK; // flush previous depth if any + if (depth > 0) { + bits |= (depth & 0xFF) << DepthSHIFT; // encoded on 8 bits + } + } + + public void setFieldIndex(int index) { + // ignored + } + + public abstract String unboundReferenceErrorName(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/NullLiteral.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/NullLiteral.java index 791b6a0..d158440 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/NullLiteral.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/NullLiteral.java @@ -16,31 +16,35 @@ import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class NullLiteral extends MagicLiteral { - static final char[] source = {'n' , 'u' , 'l' , 'l'}; + static final char[] source = { 'n', 'u', 'l', 'l' }; - public NullLiteral(int s , int e) { + public NullLiteral(int s, int e) { - super(s,e); + super(s, e); } public void computeConstant() { - - constant = NotAConstant; + + constant = NotAConstant; } /** * Code generation for the null literal - * - * @param currentScope net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream - * @param valueRequired boolean - */ -// public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) { -// int pc = codeStream.position; -// if (valueRequired) -// codeStream.aconst_null(); -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * @param valueRequired + * boolean + */ + // public void generateCode(BlockScope currentScope, CodeStream codeStream, + // boolean valueRequired) { + // int pc = codeStream.position; + // if (valueRequired) + // codeStream.aconst_null(); + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } public TypeBinding literalType(BlockScope scope) { return NullBinding; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/NumberLiteral.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/NumberLiteral.java index a80651d..0ce2098 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/NumberLiteral.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/NumberLiteral.java @@ -12,21 +12,29 @@ package net.sourceforge.phpdt.internal.compiler.ast; public abstract class NumberLiteral extends Literal { char[] source; -public NumberLiteral(char[] token, int s, int e) { - this(s,e) ; - source = token ; -} -public NumberLiteral(int s, int e) { - super (s,e) ; -} -public boolean isValidJavaStatement(){ - //should never be reach, but with a bug in the ast tree.... - //see comment on the Statement class - - return false ;} -public char[] source(){ - return source;} -public String toStringExpression(){ - - return new String(source);} + + public NumberLiteral(char[] token, int s, int e) { + this(s, e); + source = token; + } + + public NumberLiteral(int s, int e) { + super(s, e); + } + + public boolean isValidJavaStatement() { + // should never be reach, but with a bug in the ast tree.... + // see comment on the Statement class + + return false; + } + + public char[] source() { + return source; + } + + public String toStringExpression() { + + return new String(source); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/OR_OR_Expression.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/OR_OR_Expression.java index 67b76e7..9dee180 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/OR_OR_Expression.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/OR_OR_Expression.java @@ -16,281 +16,303 @@ import net.sourceforge.phpdt.internal.compiler.flow.FlowInfo; import net.sourceforge.phpdt.internal.compiler.impl.Constant; import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; -//dedicated treatment for the || +// dedicated treatment for the || public class OR_OR_Expression extends BinaryExpression { int rightInitStateIndex = -1; + int mergedInitStateIndex = -1; public OR_OR_Expression(Expression left, Expression right, int operator) { super(left, right, operator); } - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { Constant cst = this.left.optimizedBooleanConstant(); - boolean isLeftOptimizedTrue = cst != NotAConstant && cst.booleanValue() == true; - boolean isLeftOptimizedFalse = cst != NotAConstant && cst.booleanValue() == false; + boolean isLeftOptimizedTrue = cst != NotAConstant + && cst.booleanValue() == true; + boolean isLeftOptimizedFalse = cst != NotAConstant + && cst.booleanValue() == false; if (isLeftOptimizedFalse) { // FALSE || anything - // need to be careful of scenario: - // (x || y) || !z, if passing the left info to the right, it would be swapped by the ! - FlowInfo mergedInfo = left.analyseCode(currentScope, flowContext, flowInfo).unconditionalInits(); - mergedInfo = right.analyseCode(currentScope, flowContext, mergedInfo); - mergedInitStateIndex = - currentScope.methodScope().recordInitializationStates(mergedInfo); + // need to be careful of scenario: + // (x || y) || !z, if passing the left info to the right, it would + // be swapped by the ! + FlowInfo mergedInfo = left.analyseCode(currentScope, flowContext, + flowInfo).unconditionalInits(); + mergedInfo = right.analyseCode(currentScope, flowContext, + mergedInfo); + mergedInitStateIndex = currentScope.methodScope() + .recordInitializationStates(mergedInfo); return mergedInfo; } - FlowInfo leftInfo = left.analyseCode(currentScope, flowContext, flowInfo); - - // need to be careful of scenario: - // (x || y) || !z, if passing the left info to the right, it would be swapped by the ! - FlowInfo rightInfo = leftInfo.initsWhenFalse().unconditionalInits().copy(); - rightInitStateIndex = - currentScope.methodScope().recordInitializationStates(rightInfo); + FlowInfo leftInfo = left.analyseCode(currentScope, flowContext, + flowInfo); + + // need to be careful of scenario: + // (x || y) || !z, if passing the left info to the right, it would be + // swapped by the ! + FlowInfo rightInfo = leftInfo.initsWhenFalse().unconditionalInits() + .copy(); + rightInitStateIndex = currentScope.methodScope() + .recordInitializationStates(rightInfo); int previousMode = rightInfo.reachMode(); - if (isLeftOptimizedTrue){ - rightInfo.setReachMode(FlowInfo.UNREACHABLE); + if (isLeftOptimizedTrue) { + rightInfo.setReachMode(FlowInfo.UNREACHABLE); } rightInfo = right.analyseCode(currentScope, flowContext, rightInfo); FlowInfo falseMergedInfo = rightInfo.initsWhenFalse().copy(); - rightInfo.setReachMode(previousMode); // reset after falseMergedInfo got extracted + rightInfo.setReachMode(previousMode); // reset after falseMergedInfo + // got extracted - FlowInfo mergedInfo = FlowInfo.conditional( - // merging two true initInfos for such a negative case: if ((t && (b = t)) || f) r = b; // b may not have been initialized - leftInfo.initsWhenTrue().copy().unconditionalInits().mergedWith( - rightInfo.initsWhenTrue().copy().unconditionalInits()), - falseMergedInfo); - mergedInitStateIndex = - currentScope.methodScope().recordInitializationStates(mergedInfo); + FlowInfo mergedInfo = FlowInfo + .conditional( + // merging two true initInfos for such a negative case: + // if ((t && (b = t)) || f) r = b; // b may not have + // been initialized + leftInfo.initsWhenTrue().copy().unconditionalInits() + .mergedWith( + rightInfo.initsWhenTrue().copy() + .unconditionalInits()), + falseMergedInfo); + mergedInitStateIndex = currentScope.methodScope() + .recordInitializationStates(mergedInfo); return mergedInfo; } /** * Code generation for a binary operation - * - * @param currentScope net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream - * @param valueRequired boolean + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * @param valueRequired + * boolean */ -// public void generateCode( -// BlockScope currentScope, -// CodeStream codeStream, -// boolean valueRequired) { -// int pc = codeStream.position; -// Label falseLabel, endLabel; -// if (constant != Constant.NotAConstant) { -// if (valueRequired) -// codeStream.generateConstant(constant, implicitConversion); -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// return; -// } -// bits |= OnlyValueRequiredMASK; -// generateOptimizedBoolean( -// currentScope, -// codeStream, -// null, -// (falseLabel = new Label(codeStream)), -// valueRequired); -// /* improving code gen for such a case: boolean b = i < 0 || true; -// * since the label has never been used, we have the inlined value on the stack. */ -// if (falseLabel.hasForwardReferences()) { -// if (valueRequired) { -// codeStream.iconst_1(); -// if ((bits & ValueForReturnMASK) != 0) { -// codeStream.ireturn(); -// falseLabel.place(); -// codeStream.iconst_0(); -// } else { -// codeStream.goto_(endLabel = new Label(codeStream)); -// codeStream.decrStackSize(1); -// falseLabel.place(); -// codeStream.iconst_0(); -// endLabel.place(); -// } -// } else { -// falseLabel.place(); -// } -// } -// if (valueRequired) { -// codeStream.generateImplicitConversion(implicitConversion); -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } -// -// /** -// * Boolean operator code generation -// * Optimized operations are: || -// */ -// public void generateOptimizedBoolean( -// BlockScope currentScope, -// CodeStream codeStream, -// Label trueLabel, -// Label falseLabel, -// boolean valueRequired) { -// if (constant != Constant.NotAConstant) { -// super.generateOptimizedBoolean(currentScope, codeStream, trueLabel, falseLabel, valueRequired); -// return; -// } -// Constant condConst; -// if ((condConst = left.optimizedBooleanConstant()) != NotAConstant) { -// if (condConst.booleanValue() == true) { -// // || x -// left.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// false); -// if (valueRequired) { -// if ((bits & OnlyValueRequiredMASK) != 0) { -// codeStream.iconst_1(); -// } else { -// if (trueLabel != null) { -// codeStream.goto_(trueLabel); -// } -// } -// } -// // reposition the endPC -// codeStream.updateLastRecordedEndPC(codeStream.position); -// } else { -// // || x -// left.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// false); -// if (rightInitStateIndex != -1) { -// codeStream.addDefinitelyAssignedVariables(currentScope, rightInitStateIndex); -// } -// if ((bits & OnlyValueRequiredMASK) != 0) { -// right.generateCode(currentScope, codeStream, valueRequired); -// } else { -// right.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// valueRequired); -// } -// } -// if (mergedInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// mergedInitStateIndex); -// } -// return; -// } -// if ((condConst = right.optimizedBooleanConstant()) != NotAConstant) { -// if (condConst.booleanValue() == true) { -// // x || -// Label internalFalseLabel = new Label(codeStream); -// left.generateOptimizedBoolean( -// currentScope, -// codeStream, -// null, -// internalFalseLabel, // will be true in the end -// false); -// if (rightInitStateIndex != -1) { -// codeStream.addDefinitelyAssignedVariables(currentScope, rightInitStateIndex); -// } -// internalFalseLabel.place(); -// right.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// false); -// if (valueRequired) { -// if ((bits & OnlyValueRequiredMASK) != 0) { -// codeStream.iconst_1(); -// } else { -// if (trueLabel != null) { -// codeStream.goto_(trueLabel); -// } -// } -// } -// // reposition the endPC -// codeStream.updateLastRecordedEndPC(codeStream.position); -// } else { -// // x || -// if ((bits & OnlyValueRequiredMASK) != 0) { -// left.generateCode(currentScope, codeStream, valueRequired); -// } else { -// left.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// valueRequired); -// } -// if (rightInitStateIndex != -1) { -// codeStream.addDefinitelyAssignedVariables(currentScope, rightInitStateIndex); -// } -// right.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// false); -// } -// if (mergedInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// mergedInitStateIndex); -// } -// return; -// } -// // default case -// if (falseLabel == null) { -// if (trueLabel != null) { -// // implicit falling through the FALSE case -// left.generateOptimizedBoolean(currentScope, codeStream, trueLabel, null, true); -// right.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// null, -// valueRequired); -// } -// } else { -// // implicit falling through the TRUE case -// if (trueLabel == null) { -// Label internalTrueLabel = new Label(codeStream); -// left.generateOptimizedBoolean( -// currentScope, -// codeStream, -// internalTrueLabel, -// null, -// true); -// if (rightInitStateIndex != -1) { -// codeStream.addDefinitelyAssignedVariables(currentScope, rightInitStateIndex); -// } -// right.generateOptimizedBoolean( -// currentScope, -// codeStream, -// null, -// falseLabel, -// valueRequired); -// internalTrueLabel.place(); -// } else { -// // no implicit fall through TRUE/FALSE --> should never occur -// } -// } -// if (mergedInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// mergedInitStateIndex); -// } -// } - + // public void generateCode( + // BlockScope currentScope, + // CodeStream codeStream, + // boolean valueRequired) { + // int pc = codeStream.position; + // Label falseLabel, endLabel; + // if (constant != Constant.NotAConstant) { + // if (valueRequired) + // codeStream.generateConstant(constant, implicitConversion); + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // return; + // } + // bits |= OnlyValueRequiredMASK; + // generateOptimizedBoolean( + // currentScope, + // codeStream, + // null, + // (falseLabel = new Label(codeStream)), + // valueRequired); + // /* improving code gen for such a case: boolean b = i < 0 || true; + // * since the label has never been used, we have the inlined value on the + // stack. */ + // if (falseLabel.hasForwardReferences()) { + // if (valueRequired) { + // codeStream.iconst_1(); + // if ((bits & ValueForReturnMASK) != 0) { + // codeStream.ireturn(); + // falseLabel.place(); + // codeStream.iconst_0(); + // } else { + // codeStream.goto_(endLabel = new Label(codeStream)); + // codeStream.decrStackSize(1); + // falseLabel.place(); + // codeStream.iconst_0(); + // endLabel.place(); + // } + // } else { + // falseLabel.place(); + // } + // } + // if (valueRequired) { + // codeStream.generateImplicitConversion(implicitConversion); + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } + // + // /** + // * Boolean operator code generation + // * Optimized operations are: || + // */ + // public void generateOptimizedBoolean( + // BlockScope currentScope, + // CodeStream codeStream, + // Label trueLabel, + // Label falseLabel, + // boolean valueRequired) { + // if (constant != Constant.NotAConstant) { + // super.generateOptimizedBoolean(currentScope, codeStream, trueLabel, + // falseLabel, valueRequired); + // return; + // } + // Constant condConst; + // if ((condConst = left.optimizedBooleanConstant()) != NotAConstant) { + // if (condConst.booleanValue() == true) { + // // || x + // left.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // false); + // if (valueRequired) { + // if ((bits & OnlyValueRequiredMASK) != 0) { + // codeStream.iconst_1(); + // } else { + // if (trueLabel != null) { + // codeStream.goto_(trueLabel); + // } + // } + // } + // // reposition the endPC + // codeStream.updateLastRecordedEndPC(codeStream.position); + // } else { + // // || x + // left.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // false); + // if (rightInitStateIndex != -1) { + // codeStream.addDefinitelyAssignedVariables(currentScope, + // rightInitStateIndex); + // } + // if ((bits & OnlyValueRequiredMASK) != 0) { + // right.generateCode(currentScope, codeStream, valueRequired); + // } else { + // right.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // valueRequired); + // } + // } + // if (mergedInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // mergedInitStateIndex); + // } + // return; + // } + // if ((condConst = right.optimizedBooleanConstant()) != NotAConstant) { + // if (condConst.booleanValue() == true) { + // // x || + // Label internalFalseLabel = new Label(codeStream); + // left.generateOptimizedBoolean( + // currentScope, + // codeStream, + // null, + // internalFalseLabel, // will be true in the end + // false); + // if (rightInitStateIndex != -1) { + // codeStream.addDefinitelyAssignedVariables(currentScope, + // rightInitStateIndex); + // } + // internalFalseLabel.place(); + // right.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // false); + // if (valueRequired) { + // if ((bits & OnlyValueRequiredMASK) != 0) { + // codeStream.iconst_1(); + // } else { + // if (trueLabel != null) { + // codeStream.goto_(trueLabel); + // } + // } + // } + // // reposition the endPC + // codeStream.updateLastRecordedEndPC(codeStream.position); + // } else { + // // x || + // if ((bits & OnlyValueRequiredMASK) != 0) { + // left.generateCode(currentScope, codeStream, valueRequired); + // } else { + // left.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // valueRequired); + // } + // if (rightInitStateIndex != -1) { + // codeStream.addDefinitelyAssignedVariables(currentScope, + // rightInitStateIndex); + // } + // right.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // false); + // } + // if (mergedInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // mergedInitStateIndex); + // } + // return; + // } + // // default case + // if (falseLabel == null) { + // if (trueLabel != null) { + // // implicit falling through the FALSE case + // left.generateOptimizedBoolean(currentScope, codeStream, trueLabel, null, + // true); + // right.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // null, + // valueRequired); + // } + // } else { + // // implicit falling through the TRUE case + // if (trueLabel == null) { + // Label internalTrueLabel = new Label(codeStream); + // left.generateOptimizedBoolean( + // currentScope, + // codeStream, + // internalTrueLabel, + // null, + // true); + // if (rightInitStateIndex != -1) { + // codeStream.addDefinitelyAssignedVariables(currentScope, + // rightInitStateIndex); + // } + // right.generateOptimizedBoolean( + // currentScope, + // codeStream, + // null, + // falseLabel, + // valueRequired); + // internalTrueLabel.place(); + // } else { + // // no implicit fall through TRUE/FALSE --> should never occur + // } + // } + // if (mergedInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // mergedInitStateIndex); + // } + // } public boolean isCompactableOperation() { return false; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/OperatorExpression.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/OperatorExpression.java index f4eb5db..4330cc6 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/OperatorExpression.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/OperatorExpression.java @@ -10,11 +10,14 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.compiler.ast; -public abstract class OperatorExpression extends Expression implements OperatorIds { +public abstract class OperatorExpression extends Expression implements + OperatorIds { public static int[][] ResolveTypeTables = new int[NumberOfTables][]; - static {classInitialize();} + static { + classInitialize(); + } /** * OperatorExpression constructor comment. @@ -22,6 +25,7 @@ public abstract class OperatorExpression extends Expression implements OperatorI public OperatorExpression() { super(); } + public static final void classInitialize() { ResolveTypeTables[AND] = get_AND(); ResolveTypeTables[AND_AND] = get_AND_AND(); @@ -43,1529 +47,1832 @@ public abstract class OperatorExpression extends Expression implements OperatorI ResolveTypeTables[XOR] = get_XOR(); } - public static final String generateTableTestCase(){ - //return a String which is a java method allowing to test - //the non zero entries of all tables - + public static final String generateTableTestCase() { + // return a String which is a java method allowing to test + // the non zero entries of all tables + /* - net.sourceforge.phpdt.internal.compiler.ast. - OperatorExpression.generateTableTestCase(); - */ - - int[] operators = new int[]{AND,AND_AND,DIVIDE,GREATER,GREATER_EQUAL, - LEFT_SHIFT,LESS,LESS_EQUAL,MINUS,MULTIPLY,OR,OR_OR,PLUS,REMAINDER, - RIGHT_SHIFT,UNSIGNED_RIGHT_SHIFT,XOR}; - + * net.sourceforge.phpdt.internal.compiler.ast. + * OperatorExpression.generateTableTestCase(); + */ + + int[] operators = new int[] { AND, AND_AND, DIVIDE, GREATER, + GREATER_EQUAL, LEFT_SHIFT, LESS, LESS_EQUAL, MINUS, MULTIPLY, + OR, OR_OR, PLUS, REMAINDER, RIGHT_SHIFT, UNSIGNED_RIGHT_SHIFT, + XOR }; + class Decode { - public final String constant(int code){ - switch(code){ - case T_boolean : return "true" ; //$NON-NLS-1$ - case T_byte : return "((byte) 3)" ; //$NON-NLS-1$ - case T_char : return "'A'" ; //$NON-NLS-1$ - case T_double : return "300.0d" ; //$NON-NLS-1$ - case T_float : return "100.0f" ; //$NON-NLS-1$ - case T_int : return "1" ; //$NON-NLS-1$ - case T_long : return "7L" ; //$NON-NLS-1$ - case T_String : return "\"hello-world\"" ; //$NON-NLS-1$ - case T_null : return "null"; //$NON-NLS-1$ - case T_short : return "((short) 5)"; //$NON-NLS-1$ - case T_Object : return "null";} //$NON-NLS-1$ + public final String constant(int code) { + switch (code) { + case T_boolean: + return "true"; //$NON-NLS-1$ + case T_byte: + return "((byte) 3)"; //$NON-NLS-1$ + case T_char: + return "'A'"; //$NON-NLS-1$ + case T_double: + return "300.0d"; //$NON-NLS-1$ + case T_float: + return "100.0f"; //$NON-NLS-1$ + case T_int: + return "1"; //$NON-NLS-1$ + case T_long: + return "7L"; //$NON-NLS-1$ + case T_String: + return "\"hello-world\""; //$NON-NLS-1$ + case T_null: + return "null"; //$NON-NLS-1$ + case T_short: + return "((short) 5)"; //$NON-NLS-1$ + case T_Object: + return "null";} //$NON-NLS-1$ return "";} //$NON-NLS-1$ - - public final String type(int code){ - switch(code){ - case T_boolean : return "z" ; //$NON-NLS-1$ - case T_byte : return "b" ; //$NON-NLS-1$ - case T_char : return "c" ; //$NON-NLS-1$ - case T_double : return "d" ; //$NON-NLS-1$ - case T_float : return "f" ; //$NON-NLS-1$ - case T_int : return "i" ; //$NON-NLS-1$ - case T_long : return "l" ; //$NON-NLS-1$ - case T_String : return "str" ; //$NON-NLS-1$ - case T_null : return "null"; //$NON-NLS-1$ - case T_short : return "s"; //$NON-NLS-1$ - case T_Object : return "obj";} //$NON-NLS-1$ + + public final String type(int code) { + switch (code) { + case T_boolean: + return "z"; //$NON-NLS-1$ + case T_byte: + return "b"; //$NON-NLS-1$ + case T_char: + return "c"; //$NON-NLS-1$ + case T_double: + return "d"; //$NON-NLS-1$ + case T_float: + return "f"; //$NON-NLS-1$ + case T_int: + return "i"; //$NON-NLS-1$ + case T_long: + return "l"; //$NON-NLS-1$ + case T_String: + return "str"; //$NON-NLS-1$ + case T_null: + return "null"; //$NON-NLS-1$ + case T_short: + return "s"; //$NON-NLS-1$ + case T_Object: + return "obj";} //$NON-NLS-1$ return "xxx";} //$NON-NLS-1$ - - public final String operator(int operator){ - switch (operator) { - case EQUAL_EQUAL : return "=="; //$NON-NLS-1$ - case LESS_EQUAL : return "<="; //$NON-NLS-1$ - case GREATER_EQUAL :return ">="; //$NON-NLS-1$ - case LEFT_SHIFT : return "<<"; //$NON-NLS-1$ - case RIGHT_SHIFT : return ">>"; //$NON-NLS-1$ - case UNSIGNED_RIGHT_SHIFT : return ">>>"; //$NON-NLS-1$ - case OR_OR :return "||"; //$NON-NLS-1$ - case AND_AND : return "&&"; //$NON-NLS-1$ - case PLUS : return "+"; //$NON-NLS-1$ - case MINUS : return "-"; //$NON-NLS-1$ - case NOT : return "!"; //$NON-NLS-1$ - case REMAINDER : return "%"; //$NON-NLS-1$ - case XOR : return "^"; //$NON-NLS-1$ - case AND : return "&"; //$NON-NLS-1$ - case MULTIPLY : return "*"; //$NON-NLS-1$ - case OR : return "|"; //$NON-NLS-1$ - case TWIDDLE : return "~"; //$NON-NLS-1$ - case DIVIDE : return "/"; //$NON-NLS-1$ - case GREATER : return ">"; //$NON-NLS-1$ - case LESS : return "<"; }; //$NON-NLS-1$ + + public final String operator(int operator) { + switch (operator) { + case EQUAL_EQUAL: + return "=="; //$NON-NLS-1$ + case LESS_EQUAL: + return "<="; //$NON-NLS-1$ + case GREATER_EQUAL: + return ">="; //$NON-NLS-1$ + case LEFT_SHIFT: + return "<<"; //$NON-NLS-1$ + case RIGHT_SHIFT: + return ">>"; //$NON-NLS-1$ + case UNSIGNED_RIGHT_SHIFT: + return ">>>"; //$NON-NLS-1$ + case OR_OR: + return "||"; //$NON-NLS-1$ + case AND_AND: + return "&&"; //$NON-NLS-1$ + case PLUS: + return "+"; //$NON-NLS-1$ + case MINUS: + return "-"; //$NON-NLS-1$ + case NOT: + return "!"; //$NON-NLS-1$ + case REMAINDER: + return "%"; //$NON-NLS-1$ + case XOR: + return "^"; //$NON-NLS-1$ + case AND: + return "&"; //$NON-NLS-1$ + case MULTIPLY: + return "*"; //$NON-NLS-1$ + case OR: + return "|"; //$NON-NLS-1$ + case TWIDDLE: + return "~"; //$NON-NLS-1$ + case DIVIDE: + return "/"; //$NON-NLS-1$ + case GREATER: + return ">"; //$NON-NLS-1$ + case LESS: + return "<";}; //$NON-NLS-1$ return "????";} //$NON-NLS-1$ } - - + Decode decode = new Decode(); - String s ; - + String s; + s = "\tpublic static void binaryOperationTablesTestCase(){\n" + //$NON-NLS-1$ - - "\t\t//TC test : all binary operation (described in tables)\n"+ //$NON-NLS-1$ - "\t\t//method automatically generated by\n"+ //$NON-NLS-1$ - "\t\t//net.sourceforge.phpdt.internal.compiler.ast.OperatorExpression.generateTableTestCase();\n"+ //$NON-NLS-1$ - - "\t\tString str0 ;\t String str\t= "+decode.constant(T_String)+";\n"+ //$NON-NLS-1$ //$NON-NLS-2$ - "\t\tint i0 ;\t int i\t= "+decode.constant(T_int)+" ;\n"+ //$NON-NLS-1$ //$NON-NLS-2$ - "\t\tboolean z0;\t boolean z\t= "+decode.constant(T_boolean)+";\n"+ //$NON-NLS-1$ //$NON-NLS-2$ - "\t\tchar c0; \t char c\t= "+decode.constant(T_char)+" ;\n"+ //$NON-NLS-1$ //$NON-NLS-2$ - "\t\tfloat f0; \t float f\t= "+decode.constant(T_float)+" ;\n"+ //$NON-NLS-1$ //$NON-NLS-2$ - "\t\tdouble d0;\t double d\t= "+decode.constant(T_double)+" ;\n"+ //$NON-NLS-1$ //$NON-NLS-2$ - "\t\tbyte b0; \t byte b\t= "+decode.constant(T_byte)+";\n"+ //$NON-NLS-1$ //$NON-NLS-2$ - "\t\tshort s0; \t short s\t= "+decode.constant(T_short)+";\n"+ //$NON-NLS-1$ //$NON-NLS-2$ - "\t\tlong l0; \t long l\t= "+decode.constant(T_long)+" ;\n"+ //$NON-NLS-1$ //$NON-NLS-2$ - "\t\tObject obj0; \t Object obj\t= "+decode.constant(T_Object)+" ;\n"+ //$NON-NLS-1$ //$NON-NLS-2$ - "\n"; //$NON-NLS-1$ - - int error = 0; - for (int i=0; i < operators.length ; i++) - { int operator = operators[i]; - for (int left=0; left<16;left++) - for (int right=0; right<16;right++) - { int result = (ResolveTypeTables[operator][(left<<4)+right]) & 0x0000F; - if (result != T_undefined) - - //1/ First regular computation then 2/ comparaison - //with a compile time constant (generated by the compiler) - // z0 = s >= s; - // if ( z0 != (((short) 5) >= ((short) 5))) - // System.out.println(155); - - { s += "\t\t"+decode.type(result)+"0"+" = "+decode.type(left); //$NON-NLS-1$ //$NON-NLS-3$ //$NON-NLS-2$ - s += " "+decode.operator(operator)+" "+decode.type(right)+";\n"; //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-3$ - String begin = result == T_String ? "\t\tif (! " : "\t\tif ( "; //$NON-NLS-2$ //$NON-NLS-1$ - String test = result == T_String ? ".equals(" : " != (" ; //$NON-NLS-2$ //$NON-NLS-1$ - s += begin +decode.type(result)+"0"+test //$NON-NLS-1$ - +decode.constant(left)+" " //$NON-NLS-1$ - +decode.operator(operator)+" " //$NON-NLS-1$ - +decode.constant(right)+"))\n"; //$NON-NLS-1$ - s += "\t\t\tSystem.out.println("+ (++error) +");\n"; //$NON-NLS-1$ //$NON-NLS-2$ - + + "\t\t//TC test : all binary operation (described in tables)\n" + + //$NON-NLS-1$ + "\t\t//method automatically generated by\n" + + //$NON-NLS-1$ + "\t\t//net.sourceforge.phpdt.internal.compiler.ast.OperatorExpression.generateTableTestCase();\n" + + //$NON-NLS-1$ + + "\t\tString str0 ;\t String str\t= " + + decode.constant(T_String) + + ";\n" + //$NON-NLS-1$ //$NON-NLS-2$ + "\t\tint i0 ;\t int i\t= " + + decode.constant(T_int) + + " ;\n" + //$NON-NLS-1$ //$NON-NLS-2$ + "\t\tboolean z0;\t boolean z\t= " + + decode.constant(T_boolean) + + ";\n" + //$NON-NLS-1$ //$NON-NLS-2$ + "\t\tchar c0; \t char c\t= " + + decode.constant(T_char) + + " ;\n" + //$NON-NLS-1$ //$NON-NLS-2$ + "\t\tfloat f0; \t float f\t= " + + decode.constant(T_float) + + " ;\n" + //$NON-NLS-1$ //$NON-NLS-2$ + "\t\tdouble d0;\t double d\t= " + + decode.constant(T_double) + + " ;\n" + //$NON-NLS-1$ //$NON-NLS-2$ + "\t\tbyte b0; \t byte b\t= " + + decode.constant(T_byte) + + ";\n" + //$NON-NLS-1$ //$NON-NLS-2$ + "\t\tshort s0; \t short s\t= " + + decode.constant(T_short) + + ";\n" + //$NON-NLS-1$ //$NON-NLS-2$ + "\t\tlong l0; \t long l\t= " + + decode.constant(T_long) + + " ;\n" + //$NON-NLS-1$ //$NON-NLS-2$ + "\t\tObject obj0; \t Object obj\t= " + + decode.constant(T_Object) + " ;\n" + //$NON-NLS-1$ //$NON-NLS-2$ + "\n"; //$NON-NLS-1$ + + int error = 0; + for (int i = 0; i < operators.length; i++) { + int operator = operators[i]; + for (int left = 0; left < 16; left++) + for (int right = 0; right < 16; right++) { + int result = (ResolveTypeTables[operator][(left << 4) + + right]) & 0x0000F; + if (result != T_undefined) + + // 1/ First regular computation then 2/ comparaison + // with a compile time constant (generated by the compiler) + // z0 = s >= s; + // if ( z0 != (((short) 5) >= ((short) 5))) + // System.out.println(155); + + { + s += "\t\t" + decode.type(result) + "0" + " = " + decode.type(left); //$NON-NLS-1$ //$NON-NLS-3$ //$NON-NLS-2$ + s += " " + decode.operator(operator) + " " + decode.type(right) + ";\n"; //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-3$ + String begin = result == T_String ? "\t\tif (! " : "\t\tif ( "; //$NON-NLS-2$ //$NON-NLS-1$ + String test = result == T_String ? ".equals(" : " != ("; //$NON-NLS-2$ //$NON-NLS-1$ + s += begin + decode.type(result) + "0" + test //$NON-NLS-1$ + + decode.constant(left) + " " //$NON-NLS-1$ + + decode.operator(operator) + " " //$NON-NLS-1$ + + decode.constant(right) + "))\n"; //$NON-NLS-1$ + s += "\t\t\tSystem.out.println(" + (++error) + ");\n"; //$NON-NLS-1$ //$NON-NLS-2$ + } } - } - - return s += "\n\t\tSystem.out.println(\"binary tables test : done\");}" ; //$NON-NLS-1$ + } + + return s += "\n\t\tSystem.out.println(\"binary tables test : done\");}"; //$NON-NLS-1$ } - public static final int[] get_AND(){ - - //the code is an int - // (cast) left Op (cast) rigth --> result - // 0000 0000 0000 0000 0000 - // <<16 <<12 <<8 <<4 - - int[] table = new int[16*16] ; - - // table[(T_undefined<<4)+T_undefined] = T_undefined ; - // table[(T_undefined<<4)+T_byte] = T_undefined ; - // table[(T_undefined<<4)+T_long] = T_undefined ; - // table[(T_undefined<<4)+T_short] = T_undefined ; - // table[(T_undefined<<4)+T_void] = T_undefined ; - // table[(T_undefined<<4)+T_String] = T_undefined ; - // table[(T_undefined<<4)+T_Object] = T_undefined ; - // table[(T_undefined<<4)+T_double] = T_undefined ; - // table[(T_undefined<<4)+T_float] = T_undefined ; - // table[(T_undefined<<4)+T_boolean] = T_undefined ; - // table[(T_undefined<<4)+T_char] = T_undefined ; - // table[(T_undefined<<4)+T_int] = T_undefined ; - // table[(T_undefined<<4)+T_null] = T_undefined ; - - // table[(T_byte<<4)+T_undefined] = T_undefined ; - table[(T_byte<<4)+T_byte] = (Byte2Int<<12) +(Byte2Int<<4) +T_int ; - table[(T_byte<<4)+T_long] = (Byte2Long<<12)+(Long2Long<<4)+T_long ; - table[(T_byte<<4)+T_short] = (Byte2Int<<12) +(Short2Int<<4)+T_int; - // table[(T_byte<<4)+T_void] = T_undefined ; - // table[(T_byte<<4)+T_String] = T_undefined ; - // table[(T_byte<<4)+T_Object] = T_undefined ; - // table[(T_byte<<4)+T_double] = T_undefined ; - // table[(T_byte<<4)+T_float] = T_undefined ; - // table[(T_byte<<4)+T_boolean] = T_undefined ; - table[(T_byte<<4)+T_char] = (Byte2Int<<12) +(Char2Int<<4) +T_int ; - table[(T_byte<<4)+T_int] = (Byte2Int<<12) +(Int2Int<<4) +T_int ; - // table[(T_byte<<4)+T_null] = T_undefined ; - - // table[(T_long<<4)+T_undefined] = T_undefined ; - table[(T_long<<4)+T_byte] = (Long2Long<<12)+(Byte2Long<<4)+T_long; - table[(T_long<<4)+T_long] = (Long2Long<<12)+(Long2Long<<4)+T_long ; - table[(T_long<<4)+T_short] = (Long2Long<<12)+(Short2Long<<4)+T_long; ; - // table[(T_long<<4)+T_void] = T_undefined ; - // table[(T_long<<4)+T_String] = T_undefined ; - // table[(T_long<<4)+T_Object] = T_undefined ; - // table[(T_long<<4)+T_double] = T_undefined ; - // table[(T_long<<4)+T_float] = T_undefined ; - // table[(T_long<<4)+T_boolean] = T_undefined ; - table[(T_long<<4)+T_char] = (Long2Long<<12)+(Char2Long<<4)+T_long ; - table[(T_long<<4)+T_int] = (Long2Long<<12)+(Int2Long<<4)+T_long ; - // table[(T_long<<4)+T_null] = T_undefined ; - - // table[(T_short<<4)+T_undefined] = T_undefined ; - table[(T_short<<4)+T_byte] = (Short2Int<<12)+(Byte2Int<<4)+T_int ; - table[(T_short<<4)+T_long] = (Short2Long<<12)+(Long2Long<<4)+T_long ; - table[(T_short<<4)+T_short] = (Short2Int<<12)+(Short2Int<<4)+T_int ; - // table[(T_short<<4)+T_void] = T_undefined ; - // table[(T_short<<4)+T_String] = T_undefined ; - // table[(T_short<<4)+T_Object] = T_undefined ; - // table[(T_short<<4)+T_double] = T_undefined ; - // table[(T_short<<4)+T_float] = T_undefined ; - // table[(T_short<<4)+T_boolean] = T_undefined ; - table[(T_short<<4)+T_char] = (Short2Int<<12)+(Char2Int<<4)+T_int ; - table[(T_short<<4)+T_int] = (Short2Int<<12)+(Int2Int<<4)+T_int ; - // table[(T_short<<4)+T_null] = T_undefined ; - - // table[(T_void<<4)+T_undefined] = T_undefined ; - // table[(T_void<<4)+T_byte] = T_undefined ; - // table[(T_void<<4)+T_long] = T_undefined ; - // table[(T_void<<4)+T_short] = T_undefined ; - // table[(T_void<<4)+T_void] = T_undefined ; - // table[(T_void<<4)+T_String] = T_undefined ; - // table[(T_void<<4)+T_Object] = T_undefined ; - // table[(T_void<<4)+T_double] = T_undefined ; - // table[(T_void<<4)+T_float] = T_undefined ; - // table[(T_void<<4)+T_boolean] = T_undefined ; - // table[(T_void<<4)+T_char] = T_undefined ; - // table[(T_void<<4)+T_int] = T_undefined ; - // table[(T_void<<4)+T_null] = T_undefined ; - - // table[(T_String<<4)+T_undefined] = T_undefined ; - // table[(T_String<<4)+T_byte] = T_undefined ; - // table[(T_String<<4)+T_long] = T_undefined ; - // table[(T_String<<4)+T_short] = T_undefined ; - // table[(T_String<<4)+T_void] = T_undefined ; - // table[(T_String<<4)+T_String] = T_undefined ; - // table[(T_String<<4)+T_Object] = T_undefined ; - // table[(T_String<<4)+T_double] = T_undefined ; - // table[(T_String<<4)+T_float] = T_undefined ; - // table[(T_String<<4)+T_boolean] = T_undefined ; - // table[(T_String<<4)+T_char] = T_undefined ; - // table[(T_String<<4)+T_int] = T_undefined ; - // table[(T_String<<4)+T_null] = T_undefined ; - - // table[(T_Object<<4)+T_undefined] = T_undefined ; - // table[(T_Object<<4)+T_byte] = T_undefined ; - // table[(T_Object<<4)+T_long] = T_undefined ; - // table[(T_Object<<4)+T_short] = T_undefined ; - // table[(T_Object<<4)+T_void] = T_undefined ; - // table[(T_Object<<4)+T_String] = T_undefined ; - // table[(T_Object<<4)+T_Object] = T_undefined ; - // table[(T_Object<<4)+T_double] = T_undefined ; - // table[(T_Object<<4)+T_float] = T_undefined ; - // table[(T_Object<<4)+T_boolean] = T_undefined ; - // table[(T_Object<<4)+T_char] = T_undefined ; - // table[(T_Object<<4)+T_int] = T_undefined ; - // table[(T_Object<<4)+T_null] = T_undefined ; - - // table[(T_double<<4)+T_undefined] = T_undefined ; - // table[(T_double<<4)+T_byte] = T_undefined ; - // table[(T_double<<4)+T_long] = T_undefined ; - // table[(T_double<<4)+T_short] = T_undefined ; - // table[(T_double<<4)+T_void] = T_undefined ; - // table[(T_double<<4)+T_String] = T_undefined ; - // table[(T_double<<4)+T_Object] = T_undefined ; - // table[(T_double<<4)+T_double] = T_undefined ; - // table[(T_double<<4)+T_float] = T_undefined ; - // table[(T_double<<4)+T_boolean] = T_undefined ; - // table[(T_double<<4)+T_char] = T_undefined ; - // table[(T_double<<4)+T_int] = T_undefined; - // table[(T_double<<4)+T_null] = T_undefined ; - - // table[(T_float<<4)+T_undefined] = T_undefined ; - // table[(T_float<<4)+T_byte] = T_undefined ; - // table[(T_float<<4)+T_long] = T_undefined ; - // table[(T_float<<4)+T_short] = T_undefined ; - // table[(T_float<<4)+T_void] = T_undefined ; - // table[(T_float<<4)+T_String] = T_undefined ; - // table[(T_float<<4)+T_Object] = T_undefined ; - // table[(T_float<<4)+T_double] = T_undefined ; - // table[(T_float<<4)+T_float] = T_undefined ; - // table[(T_float<<4)+T_boolean] = T_undefined ; - // table[(T_float<<4)+T_char] = T_undefined ; - // table[(T_float<<4)+T_int] = T_undefined ; - // table[(T_float<<4)+T_null] = T_undefined ; - - // table[(T_boolean<<4)+T_undefined] = T_undefined ; - // table[(T_boolean<<4)+T_byte] = T_undefined ; - // table[(T_boolean<<4)+T_long] = T_undefined ; - // table[(T_boolean<<4)+T_short] = T_undefined ; - // table[(T_boolean<<4)+T_void] = T_undefined ; - // table[(T_boolean<<4)+T_String] = T_undefined ; - // table[(T_boolean<<4)+T_Object] = T_undefined ; - // table[(T_boolean<<4)+T_double] = T_undefined ; - // table[(T_boolean<<4)+T_float] = T_undefined ; - table[(T_boolean<<4)+T_boolean] = (Boolean2Boolean << 12)+(Boolean2Boolean << 4)+T_boolean ; - // table[(T_boolean<<4)+T_char] = T_undefined ; - // table[(T_boolean<<4)+T_int] = T_undefined ; - // table[(T_boolean<<4)+T_null] = T_undefined ; - - // table[(T_char<<4)+T_undefined] = T_undefined ; - table[(T_char<<4)+T_byte] = (Char2Int<<12)+(Byte2Int<<4)+T_int ; - table[(T_char<<4)+T_long] = (Char2Long<<12)+(Long2Long<<4)+T_long; - table[(T_char<<4)+T_short] = (Char2Int<<12)+(Short2Int<<4)+T_int ; - // table[(T_char<<4)+T_void] = T_undefined ; - // table[(T_char<<4)+T_String] = T_undefined ; - // table[(T_char<<4)+T_Object] = T_undefined ; - // table[(T_char<<4)+T_double] = T_undefined ; - // table[(T_char<<4)+T_float] = T_undefined ; - // table[(T_char<<4)+T_boolean] = T_undefined ; - table[(T_char<<4)+T_char] = (Char2Int<<12)+(Char2Int<<4)+T_int ; - table[(T_char<<4)+T_int] = (Char2Int<<12)+(Int2Int<<4)+T_int ; - // table[(T_char<<4)+T_null] = T_undefined ; - - // table[(T_int<<4)+T_undefined] = T_undefined ; - table[(T_int<<4)+T_byte] = (Int2Int<<12)+(Byte2Int<<4)+T_int ; - table[(T_int<<4)+T_long] = (Int2Long<<12)+(Long2Long<<4)+T_long ; - table[(T_int<<4)+T_short] = (Int2Int<<12)+(Short2Int<<4)+T_int ; - // table[(T_int<<4)+T_void] = T_undefined ; - // table[(T_int<<4)+T_String] = T_undefined ; - // table[(T_int<<4)+T_Object] = T_undefined ; - // table[(T_int<<4)+T_double] = T_undefined ; - // table[(T_int<<4)+T_float] = T_undefined ; - // table[(T_int<<4)+T_boolean] = T_undefined ; - table[(T_int<<4)+T_char] = (Int2Int<<12)+(Char2Int<<4)+T_int ; - table[(T_int<<4)+T_int] = (Int2Int<<12)+(Int2Int<<4)+T_int ; - // table[(T_int<<4)+T_null] = T_undefined ; - - // table[(T_null<<4)+T_undefined] = T_undefined ; - // table[(T_null<<4)+T_byte] = T_undefined ; - // table[(T_null<<4)+T_long] = T_undefined ; - // table[(T_null<<4)+T_short] = T_undefined ; - // table[(T_null<<4)+T_void] = T_undefined ; - // table[(T_null<<4)+T_String] = T_undefined ; - // table[(T_null<<4)+T_Object] = T_undefined ; - // table[(T_null<<4)+T_double] = T_undefined ; - // table[(T_null<<4)+T_float] = T_undefined ; - // table[(T_null<<4)+T_boolean] = T_undefined ; - // table[(T_null<<4)+T_char] = T_undefined ; - // table[(T_null<<4)+T_int] = T_undefined ; - // table[(T_null<<4)+T_null] = T_undefined ; - - return table ; + public static final int[] get_AND() { + + // the code is an int + // (cast) left Op (cast) rigth --> result + // 0000 0000 0000 0000 0000 + // <<16 <<12 <<8 <<4 + + int[] table = new int[16 * 16]; + + // table[(T_undefined<<4)+T_undefined] = T_undefined ; + // table[(T_undefined<<4)+T_byte] = T_undefined ; + // table[(T_undefined<<4)+T_long] = T_undefined ; + // table[(T_undefined<<4)+T_short] = T_undefined ; + // table[(T_undefined<<4)+T_void] = T_undefined ; + // table[(T_undefined<<4)+T_String] = T_undefined ; + // table[(T_undefined<<4)+T_Object] = T_undefined ; + // table[(T_undefined<<4)+T_double] = T_undefined ; + // table[(T_undefined<<4)+T_float] = T_undefined ; + // table[(T_undefined<<4)+T_boolean] = T_undefined ; + // table[(T_undefined<<4)+T_char] = T_undefined ; + // table[(T_undefined<<4)+T_int] = T_undefined ; + // table[(T_undefined<<4)+T_null] = T_undefined ; + + // table[(T_byte<<4)+T_undefined] = T_undefined ; + table[(T_byte << 4) + T_byte] = (Byte2Int << 12) + (Byte2Int << 4) + + T_int; + table[(T_byte << 4) + T_long] = (Byte2Long << 12) + (Long2Long << 4) + + T_long; + table[(T_byte << 4) + T_short] = (Byte2Int << 12) + (Short2Int << 4) + + T_int; + // table[(T_byte<<4)+T_void] = T_undefined ; + // table[(T_byte<<4)+T_String] = T_undefined ; + // table[(T_byte<<4)+T_Object] = T_undefined ; + // table[(T_byte<<4)+T_double] = T_undefined ; + // table[(T_byte<<4)+T_float] = T_undefined ; + // table[(T_byte<<4)+T_boolean] = T_undefined ; + table[(T_byte << 4) + T_char] = (Byte2Int << 12) + (Char2Int << 4) + + T_int; + table[(T_byte << 4) + T_int] = (Byte2Int << 12) + (Int2Int << 4) + + T_int; + // table[(T_byte<<4)+T_null] = T_undefined ; + + // table[(T_long<<4)+T_undefined] = T_undefined ; + table[(T_long << 4) + T_byte] = (Long2Long << 12) + (Byte2Long << 4) + + T_long; + table[(T_long << 4) + T_long] = (Long2Long << 12) + (Long2Long << 4) + + T_long; + table[(T_long << 4) + T_short] = (Long2Long << 12) + (Short2Long << 4) + + T_long; + ; + // table[(T_long<<4)+T_void] = T_undefined ; + // table[(T_long<<4)+T_String] = T_undefined ; + // table[(T_long<<4)+T_Object] = T_undefined ; + // table[(T_long<<4)+T_double] = T_undefined ; + // table[(T_long<<4)+T_float] = T_undefined ; + // table[(T_long<<4)+T_boolean] = T_undefined ; + table[(T_long << 4) + T_char] = (Long2Long << 12) + (Char2Long << 4) + + T_long; + table[(T_long << 4) + T_int] = (Long2Long << 12) + (Int2Long << 4) + + T_long; + // table[(T_long<<4)+T_null] = T_undefined ; + + // table[(T_short<<4)+T_undefined] = T_undefined ; + table[(T_short << 4) + T_byte] = (Short2Int << 12) + (Byte2Int << 4) + + T_int; + table[(T_short << 4) + T_long] = (Short2Long << 12) + (Long2Long << 4) + + T_long; + table[(T_short << 4) + T_short] = (Short2Int << 12) + (Short2Int << 4) + + T_int; + // table[(T_short<<4)+T_void] = T_undefined ; + // table[(T_short<<4)+T_String] = T_undefined ; + // table[(T_short<<4)+T_Object] = T_undefined ; + // table[(T_short<<4)+T_double] = T_undefined ; + // table[(T_short<<4)+T_float] = T_undefined ; + // table[(T_short<<4)+T_boolean] = T_undefined ; + table[(T_short << 4) + T_char] = (Short2Int << 12) + (Char2Int << 4) + + T_int; + table[(T_short << 4) + T_int] = (Short2Int << 12) + (Int2Int << 4) + + T_int; + // table[(T_short<<4)+T_null] = T_undefined ; + + // table[(T_void<<4)+T_undefined] = T_undefined ; + // table[(T_void<<4)+T_byte] = T_undefined ; + // table[(T_void<<4)+T_long] = T_undefined ; + // table[(T_void<<4)+T_short] = T_undefined ; + // table[(T_void<<4)+T_void] = T_undefined ; + // table[(T_void<<4)+T_String] = T_undefined ; + // table[(T_void<<4)+T_Object] = T_undefined ; + // table[(T_void<<4)+T_double] = T_undefined ; + // table[(T_void<<4)+T_float] = T_undefined ; + // table[(T_void<<4)+T_boolean] = T_undefined ; + // table[(T_void<<4)+T_char] = T_undefined ; + // table[(T_void<<4)+T_int] = T_undefined ; + // table[(T_void<<4)+T_null] = T_undefined ; + + // table[(T_String<<4)+T_undefined] = T_undefined ; + // table[(T_String<<4)+T_byte] = T_undefined ; + // table[(T_String<<4)+T_long] = T_undefined ; + // table[(T_String<<4)+T_short] = T_undefined ; + // table[(T_String<<4)+T_void] = T_undefined ; + // table[(T_String<<4)+T_String] = T_undefined ; + // table[(T_String<<4)+T_Object] = T_undefined ; + // table[(T_String<<4)+T_double] = T_undefined ; + // table[(T_String<<4)+T_float] = T_undefined ; + // table[(T_String<<4)+T_boolean] = T_undefined ; + // table[(T_String<<4)+T_char] = T_undefined ; + // table[(T_String<<4)+T_int] = T_undefined ; + // table[(T_String<<4)+T_null] = T_undefined ; + + // table[(T_Object<<4)+T_undefined] = T_undefined ; + // table[(T_Object<<4)+T_byte] = T_undefined ; + // table[(T_Object<<4)+T_long] = T_undefined ; + // table[(T_Object<<4)+T_short] = T_undefined ; + // table[(T_Object<<4)+T_void] = T_undefined ; + // table[(T_Object<<4)+T_String] = T_undefined ; + // table[(T_Object<<4)+T_Object] = T_undefined ; + // table[(T_Object<<4)+T_double] = T_undefined ; + // table[(T_Object<<4)+T_float] = T_undefined ; + // table[(T_Object<<4)+T_boolean] = T_undefined ; + // table[(T_Object<<4)+T_char] = T_undefined ; + // table[(T_Object<<4)+T_int] = T_undefined ; + // table[(T_Object<<4)+T_null] = T_undefined ; + + // table[(T_double<<4)+T_undefined] = T_undefined ; + // table[(T_double<<4)+T_byte] = T_undefined ; + // table[(T_double<<4)+T_long] = T_undefined ; + // table[(T_double<<4)+T_short] = T_undefined ; + // table[(T_double<<4)+T_void] = T_undefined ; + // table[(T_double<<4)+T_String] = T_undefined ; + // table[(T_double<<4)+T_Object] = T_undefined ; + // table[(T_double<<4)+T_double] = T_undefined ; + // table[(T_double<<4)+T_float] = T_undefined ; + // table[(T_double<<4)+T_boolean] = T_undefined ; + // table[(T_double<<4)+T_char] = T_undefined ; + // table[(T_double<<4)+T_int] = T_undefined; + // table[(T_double<<4)+T_null] = T_undefined ; + + // table[(T_float<<4)+T_undefined] = T_undefined ; + // table[(T_float<<4)+T_byte] = T_undefined ; + // table[(T_float<<4)+T_long] = T_undefined ; + // table[(T_float<<4)+T_short] = T_undefined ; + // table[(T_float<<4)+T_void] = T_undefined ; + // table[(T_float<<4)+T_String] = T_undefined ; + // table[(T_float<<4)+T_Object] = T_undefined ; + // table[(T_float<<4)+T_double] = T_undefined ; + // table[(T_float<<4)+T_float] = T_undefined ; + // table[(T_float<<4)+T_boolean] = T_undefined ; + // table[(T_float<<4)+T_char] = T_undefined ; + // table[(T_float<<4)+T_int] = T_undefined ; + // table[(T_float<<4)+T_null] = T_undefined ; + + // table[(T_boolean<<4)+T_undefined] = T_undefined ; + // table[(T_boolean<<4)+T_byte] = T_undefined ; + // table[(T_boolean<<4)+T_long] = T_undefined ; + // table[(T_boolean<<4)+T_short] = T_undefined ; + // table[(T_boolean<<4)+T_void] = T_undefined ; + // table[(T_boolean<<4)+T_String] = T_undefined ; + // table[(T_boolean<<4)+T_Object] = T_undefined ; + // table[(T_boolean<<4)+T_double] = T_undefined ; + // table[(T_boolean<<4)+T_float] = T_undefined ; + table[(T_boolean << 4) + T_boolean] = (Boolean2Boolean << 12) + + (Boolean2Boolean << 4) + T_boolean; + // table[(T_boolean<<4)+T_char] = T_undefined ; + // table[(T_boolean<<4)+T_int] = T_undefined ; + // table[(T_boolean<<4)+T_null] = T_undefined ; + + // table[(T_char<<4)+T_undefined] = T_undefined ; + table[(T_char << 4) + T_byte] = (Char2Int << 12) + (Byte2Int << 4) + + T_int; + table[(T_char << 4) + T_long] = (Char2Long << 12) + (Long2Long << 4) + + T_long; + table[(T_char << 4) + T_short] = (Char2Int << 12) + (Short2Int << 4) + + T_int; + // table[(T_char<<4)+T_void] = T_undefined ; + // table[(T_char<<4)+T_String] = T_undefined ; + // table[(T_char<<4)+T_Object] = T_undefined ; + // table[(T_char<<4)+T_double] = T_undefined ; + // table[(T_char<<4)+T_float] = T_undefined ; + // table[(T_char<<4)+T_boolean] = T_undefined ; + table[(T_char << 4) + T_char] = (Char2Int << 12) + (Char2Int << 4) + + T_int; + table[(T_char << 4) + T_int] = (Char2Int << 12) + (Int2Int << 4) + + T_int; + // table[(T_char<<4)+T_null] = T_undefined ; + + // table[(T_int<<4)+T_undefined] = T_undefined ; + table[(T_int << 4) + T_byte] = (Int2Int << 12) + (Byte2Int << 4) + + T_int; + table[(T_int << 4) + T_long] = (Int2Long << 12) + (Long2Long << 4) + + T_long; + table[(T_int << 4) + T_short] = (Int2Int << 12) + (Short2Int << 4) + + T_int; + // table[(T_int<<4)+T_void] = T_undefined ; + // table[(T_int<<4)+T_String] = T_undefined ; + // table[(T_int<<4)+T_Object] = T_undefined ; + // table[(T_int<<4)+T_double] = T_undefined ; + // table[(T_int<<4)+T_float] = T_undefined ; + // table[(T_int<<4)+T_boolean] = T_undefined ; + table[(T_int << 4) + T_char] = (Int2Int << 12) + (Char2Int << 4) + + T_int; + table[(T_int << 4) + T_int] = (Int2Int << 12) + (Int2Int << 4) + T_int; + // table[(T_int<<4)+T_null] = T_undefined ; + + // table[(T_null<<4)+T_undefined] = T_undefined ; + // table[(T_null<<4)+T_byte] = T_undefined ; + // table[(T_null<<4)+T_long] = T_undefined ; + // table[(T_null<<4)+T_short] = T_undefined ; + // table[(T_null<<4)+T_void] = T_undefined ; + // table[(T_null<<4)+T_String] = T_undefined ; + // table[(T_null<<4)+T_Object] = T_undefined ; + // table[(T_null<<4)+T_double] = T_undefined ; + // table[(T_null<<4)+T_float] = T_undefined ; + // table[(T_null<<4)+T_boolean] = T_undefined ; + // table[(T_null<<4)+T_char] = T_undefined ; + // table[(T_null<<4)+T_int] = T_undefined ; + // table[(T_null<<4)+T_null] = T_undefined ; + + return table; } - public static final int[] get_AND_AND(){ - - //the code is an int - // (cast) left Op (cast) rigth --> result - // 0000 0000 0000 0000 0000 - // <<16 <<12 <<8 <<4 - - int[] table = new int[16*16] ; - - // table[(T_undefined<<4)+T_undefined] = T_undefined ; - // table[(T_undefined<<4)+T_byte] = T_undefined ; - // table[(T_undefined<<4)+T_long] = T_undefined ; - // table[(T_undefined<<4)+T_short] = T_undefined ; - // table[(T_undefined<<4)+T_void] = T_undefined ; - // table[(T_undefined<<4)+T_String] = T_undefined ; - // table[(T_undefined<<4)+T_Object] = T_undefined ; - // table[(T_undefined<<4)+T_double] = T_undefined ; - // table[(T_undefined<<4)+T_float] = T_undefined ; - // table[(T_undefined<<4)+T_boolean] = T_undefined ; - // table[(T_undefined<<4)+T_char] = T_undefined ; - // table[(T_undefined<<4)+T_int] = T_undefined ; - // table[(T_undefined<<4)+T_null] = T_undefined ; - - // table[(T_byte<<4)+T_undefined] = T_undefined ; - // table[(T_byte<<4)+T_byte] = T_undefined ; - // table[(T_byte<<4)+T_long] = T_undefined ; - // table[(T_byte<<4)+T_short] = T_undefined ; - // table[(T_byte<<4)+T_void] = T_undefined ; - // table[(T_byte<<4)+T_String] = T_undefined ; - // table[(T_byte<<4)+T_Object] = T_undefined ; - // table[(T_byte<<4)+T_double] = T_undefined ; - // table[(T_byte<<4)+T_float] = T_undefined ; - // table[(T_byte<<4)+T_boolean] = T_undefined ; - // table[(T_byte<<4)+T_char] = T_undefined ; - // table[(T_byte<<4)+T_int] = T_undefined ; - // table[(T_byte<<4)+T_null] = T_undefined ; - - // table[(T_long<<4)+T_undefined] = T_undefined ; - // table[(T_long<<4)+T_byte] = T_undefined; - // table[(T_long<<4)+T_long] = T_undefined ; - // table[(T_long<<4)+T_short] = T_undefined ; - // table[(T_long<<4)+T_void] = T_undefined ; - // table[(T_long<<4)+T_String] = T_undefined ; - // table[(T_long<<4)+T_Object] = T_undefined ; - // table[(T_long<<4)+T_double] = T_undefined ; - // table[(T_long<<4)+T_float] = T_undefined ; - // table[(T_long<<4)+T_boolean] = T_undefined ; - // table[(T_long<<4)+T_char] = T_undefined ; - // table[(T_long<<4)+T_int] = T_undefined ; - // table[(T_long<<4)+T_null] = T_undefined ; - - // table[(T_short<<4)+T_undefined] = T_undefined ; - // table[(T_short<<4)+T_byte] = T_undefined ; - // table[(T_short<<4)+T_long] = T_undefined ; - // table[(T_short<<4)+T_short] = T_undefined ; - // table[(T_short<<4)+T_void] = T_undefined ; - // table[(T_short<<4)+T_String] = T_undefined ; - // table[(T_short<<4)+T_Object] = T_undefined ; - // table[(T_short<<4)+T_double] = T_undefined ; - // table[(T_short<<4)+T_float] = T_undefined ; - // table[(T_short<<4)+T_boolean] = T_undefined ; - // table[(T_short<<4)+T_char] = T_undefined ; - // table[(T_short<<4)+T_int] = T_undefined ; - // table[(T_short<<4)+T_null] = T_undefined ; - - // table[(T_void<<4)+T_undefined] = T_undefined ; - // table[(T_void<<4)+T_byte] = T_undefined ; - // table[(T_void<<4)+T_long] = T_undefined ; - // table[(T_void<<4)+T_short] = T_undefined ; - // table[(T_void<<4)+T_void] = T_undefined ; - // table[(T_void<<4)+T_String] = T_undefined ; - // table[(T_void<<4)+T_Object] = T_undefined ; - // table[(T_void<<4)+T_double] = T_undefined ; - // table[(T_void<<4)+T_float] = T_undefined ; - // table[(T_void<<4)+T_boolean] = T_undefined ; - // table[(T_void<<4)+T_char] = T_undefined ; - // table[(T_void<<4)+T_int] = T_undefined ; - // table[(T_void<<4)+T_null] = T_undefined ; - - // table[(T_String<<4)+T_undefined] = T_undefined ; - // table[(T_String<<4)+T_byte] = T_undefined ; - // table[(T_String<<4)+T_long] = T_undefined ; - // table[(T_String<<4)+T_short] = T_undefined ; - // table[(T_String<<4)+T_void] = T_undefined ; - // table[(T_String<<4)+T_String] = T_undefined ; - // table[(T_String<<4)+T_Object] = T_undefined ; - // table[(T_String<<4)+T_double] = T_undefined ; - // table[(T_String<<4)+T_float] = T_undefined ; - // table[(T_String<<4)+T_boolean] = T_undefined ; - // table[(T_String<<4)+T_char] = T_undefined ; - // table[(T_String<<4)+T_int] = T_undefined ; - // table[(T_String<<4)+T_null] = T_undefined ; - - // table[(T_Object<<4)+T_undefined] = T_undefined ; - // table[(T_Object<<4)+T_byte] = T_undefined ; - // table[(T_Object<<4)+T_long] = T_undefined ; - // table[(T_Object<<4)+T_short] = T_undefined ; - // table[(T_Object<<4)+T_void] = T_undefined ; - // table[(T_Object<<4)+T_String] = T_undefined ; - // table[(T_Object<<4)+T_Object] = T_undefined ; - // table[(T_Object<<4)+T_double] = T_undefined ; - // table[(T_Object<<4)+T_float] = T_undefined ; - // table[(T_Object<<4)+T_boolean] = T_undefined ; - // table[(T_Object<<4)+T_char] = T_undefined ; - // table[(T_Object<<4)+T_int] = T_undefined ; - // table[(T_Object<<4)+T_null] = T_undefined ; - - // table[(T_double<<4)+T_undefined] = T_undefined ; - // table[(T_double<<4)+T_byte] = T_undefined ; - // table[(T_double<<4)+T_long] = T_undefined ; - // table[(T_double<<4)+T_short] = T_undefined ; - // table[(T_double<<4)+T_void] = T_undefined ; - // table[(T_double<<4)+T_String] = T_undefined ; - // table[(T_double<<4)+T_Object] = T_undefined ; - // table[(T_double<<4)+T_double] = T_undefined ; - // table[(T_double<<4)+T_float] = T_undefined ; - // table[(T_double<<4)+T_boolean] = T_undefined ; - // table[(T_double<<4)+T_char] = T_undefined ; - // table[(T_double<<4)+T_int] = T_undefined; - // table[(T_double<<4)+T_null] = T_undefined ; - - // table[(T_float<<4)+T_undefined] = T_undefined ; - // table[(T_float<<4)+T_byte] = T_undefined ; - // table[(T_float<<4)+T_long] = T_undefined ; - // table[(T_float<<4)+T_short] = T_undefined ; - // table[(T_float<<4)+T_void] = T_undefined ; - // table[(T_float<<4)+T_String] = T_undefined ; - // table[(T_float<<4)+T_Object] = T_undefined ; - // table[(T_float<<4)+T_double] = T_undefined ; - // table[(T_float<<4)+T_float] = T_undefined ; - // table[(T_float<<4)+T_boolean] = T_undefined ; - // table[(T_float<<4)+T_char] = T_undefined ; - // table[(T_float<<4)+T_int] = T_undefined ; - // table[(T_float<<4)+T_null] = T_undefined ; - - // table[(T_boolean<<4)+T_undefined] = T_undefined ; - // table[(T_boolean<<4)+T_byte] = T_undefined ; - // table[(T_boolean<<4)+T_long] = T_undefined ; - // table[(T_boolean<<4)+T_short] = T_undefined ; - // table[(T_boolean<<4)+T_void] = T_undefined ; - // table[(T_boolean<<4)+T_String] = T_undefined ; - // table[(T_boolean<<4)+T_Object] = T_undefined ; - // table[(T_boolean<<4)+T_double] = T_undefined ; - // table[(T_boolean<<4)+T_float] = T_undefined ; - table[(T_boolean<<4)+T_boolean] = (Boolean2Boolean<<12)+(Boolean2Boolean<<4)+T_boolean ; - // table[(T_boolean<<4)+T_char] = T_undefined ; - // table[(T_boolean<<4)+T_int] = T_undefined ; - // table[(T_boolean<<4)+T_null] = T_undefined ; - - // table[(T_char<<4)+T_undefined] = T_undefined ; - // table[(T_char<<4)+T_byte] = T_undefined ; - // table[(T_char<<4)+T_long] = T_undefined; - // table[(T_char<<4)+T_short] = T_undefined ; - // table[(T_char<<4)+T_void] = T_undefined ; - // table[(T_char<<4)+T_String] = T_undefined ; - // table[(T_char<<4)+T_Object] = T_undefined ; - // table[(T_char<<4)+T_double] = T_undefined ; - // table[(T_char<<4)+T_float] = T_undefined ; - // table[(T_char<<4)+T_boolean] = T_undefined ; - // table[(T_char<<4)+T_char] = T_undefined ; - // table[(T_char<<4)+T_int] = T_undefined ; - // table[(T_char<<4)+T_null] = T_undefined ; - - // table[(T_int<<4)+T_undefined] = T_undefined ; - // table[(T_int<<4)+T_byte] = T_undefined ; - // table[(T_int<<4)+T_long] = T_undefined ; - // table[(T_int<<4)+T_short] = T_undefined ; - // table[(T_int<<4)+T_void] = T_undefined ; - // table[(T_int<<4)+T_String] = T_undefined ; - // table[(T_int<<4)+T_Object] = T_undefined ; - // table[(T_int<<4)+T_double] = T_undefined ; - // table[(T_int<<4)+T_float] = T_undefined ; - // table[(T_int<<4)+T_boolean] = T_undefined ; - // table[(T_int<<4)+T_char] = T_undefined ; - // table[(T_int<<4)+T_int] = T_undefined ; - // table[(T_int<<4)+T_null] = T_undefined ; - - // table[(T_null<<4)+T_undefined] = T_undefined ; - // table[(T_null<<4)+T_byte] = T_undefined ; - // table[(T_null<<4)+T_long] = T_undefined ; - // table[(T_null<<4)+T_short] = T_undefined ; - // table[(T_null<<4)+T_void] = T_undefined ; - // table[(T_null<<4)+T_String] = T_undefined ; - // table[(T_null<<4)+T_Object] = T_undefined ; - // table[(T_null<<4)+T_double] = T_undefined ; - // table[(T_null<<4)+T_float] = T_undefined ; - // table[(T_null<<4)+T_boolean] = T_undefined ; - // table[(T_null<<4)+T_char] = T_undefined ; - // table[(T_null<<4)+T_int] = T_undefined ; - // table[(T_null<<4)+T_null] = T_undefined ; - return table ; + public static final int[] get_AND_AND() { + + // the code is an int + // (cast) left Op (cast) rigth --> result + // 0000 0000 0000 0000 0000 + // <<16 <<12 <<8 <<4 + + int[] table = new int[16 * 16]; + + // table[(T_undefined<<4)+T_undefined] = T_undefined ; + // table[(T_undefined<<4)+T_byte] = T_undefined ; + // table[(T_undefined<<4)+T_long] = T_undefined ; + // table[(T_undefined<<4)+T_short] = T_undefined ; + // table[(T_undefined<<4)+T_void] = T_undefined ; + // table[(T_undefined<<4)+T_String] = T_undefined ; + // table[(T_undefined<<4)+T_Object] = T_undefined ; + // table[(T_undefined<<4)+T_double] = T_undefined ; + // table[(T_undefined<<4)+T_float] = T_undefined ; + // table[(T_undefined<<4)+T_boolean] = T_undefined ; + // table[(T_undefined<<4)+T_char] = T_undefined ; + // table[(T_undefined<<4)+T_int] = T_undefined ; + // table[(T_undefined<<4)+T_null] = T_undefined ; + + // table[(T_byte<<4)+T_undefined] = T_undefined ; + // table[(T_byte<<4)+T_byte] = T_undefined ; + // table[(T_byte<<4)+T_long] = T_undefined ; + // table[(T_byte<<4)+T_short] = T_undefined ; + // table[(T_byte<<4)+T_void] = T_undefined ; + // table[(T_byte<<4)+T_String] = T_undefined ; + // table[(T_byte<<4)+T_Object] = T_undefined ; + // table[(T_byte<<4)+T_double] = T_undefined ; + // table[(T_byte<<4)+T_float] = T_undefined ; + // table[(T_byte<<4)+T_boolean] = T_undefined ; + // table[(T_byte<<4)+T_char] = T_undefined ; + // table[(T_byte<<4)+T_int] = T_undefined ; + // table[(T_byte<<4)+T_null] = T_undefined ; + + // table[(T_long<<4)+T_undefined] = T_undefined ; + // table[(T_long<<4)+T_byte] = T_undefined; + // table[(T_long<<4)+T_long] = T_undefined ; + // table[(T_long<<4)+T_short] = T_undefined ; + // table[(T_long<<4)+T_void] = T_undefined ; + // table[(T_long<<4)+T_String] = T_undefined ; + // table[(T_long<<4)+T_Object] = T_undefined ; + // table[(T_long<<4)+T_double] = T_undefined ; + // table[(T_long<<4)+T_float] = T_undefined ; + // table[(T_long<<4)+T_boolean] = T_undefined ; + // table[(T_long<<4)+T_char] = T_undefined ; + // table[(T_long<<4)+T_int] = T_undefined ; + // table[(T_long<<4)+T_null] = T_undefined ; + + // table[(T_short<<4)+T_undefined] = T_undefined ; + // table[(T_short<<4)+T_byte] = T_undefined ; + // table[(T_short<<4)+T_long] = T_undefined ; + // table[(T_short<<4)+T_short] = T_undefined ; + // table[(T_short<<4)+T_void] = T_undefined ; + // table[(T_short<<4)+T_String] = T_undefined ; + // table[(T_short<<4)+T_Object] = T_undefined ; + // table[(T_short<<4)+T_double] = T_undefined ; + // table[(T_short<<4)+T_float] = T_undefined ; + // table[(T_short<<4)+T_boolean] = T_undefined ; + // table[(T_short<<4)+T_char] = T_undefined ; + // table[(T_short<<4)+T_int] = T_undefined ; + // table[(T_short<<4)+T_null] = T_undefined ; + + // table[(T_void<<4)+T_undefined] = T_undefined ; + // table[(T_void<<4)+T_byte] = T_undefined ; + // table[(T_void<<4)+T_long] = T_undefined ; + // table[(T_void<<4)+T_short] = T_undefined ; + // table[(T_void<<4)+T_void] = T_undefined ; + // table[(T_void<<4)+T_String] = T_undefined ; + // table[(T_void<<4)+T_Object] = T_undefined ; + // table[(T_void<<4)+T_double] = T_undefined ; + // table[(T_void<<4)+T_float] = T_undefined ; + // table[(T_void<<4)+T_boolean] = T_undefined ; + // table[(T_void<<4)+T_char] = T_undefined ; + // table[(T_void<<4)+T_int] = T_undefined ; + // table[(T_void<<4)+T_null] = T_undefined ; + + // table[(T_String<<4)+T_undefined] = T_undefined ; + // table[(T_String<<4)+T_byte] = T_undefined ; + // table[(T_String<<4)+T_long] = T_undefined ; + // table[(T_String<<4)+T_short] = T_undefined ; + // table[(T_String<<4)+T_void] = T_undefined ; + // table[(T_String<<4)+T_String] = T_undefined ; + // table[(T_String<<4)+T_Object] = T_undefined ; + // table[(T_String<<4)+T_double] = T_undefined ; + // table[(T_String<<4)+T_float] = T_undefined ; + // table[(T_String<<4)+T_boolean] = T_undefined ; + // table[(T_String<<4)+T_char] = T_undefined ; + // table[(T_String<<4)+T_int] = T_undefined ; + // table[(T_String<<4)+T_null] = T_undefined ; + + // table[(T_Object<<4)+T_undefined] = T_undefined ; + // table[(T_Object<<4)+T_byte] = T_undefined ; + // table[(T_Object<<4)+T_long] = T_undefined ; + // table[(T_Object<<4)+T_short] = T_undefined ; + // table[(T_Object<<4)+T_void] = T_undefined ; + // table[(T_Object<<4)+T_String] = T_undefined ; + // table[(T_Object<<4)+T_Object] = T_undefined ; + // table[(T_Object<<4)+T_double] = T_undefined ; + // table[(T_Object<<4)+T_float] = T_undefined ; + // table[(T_Object<<4)+T_boolean] = T_undefined ; + // table[(T_Object<<4)+T_char] = T_undefined ; + // table[(T_Object<<4)+T_int] = T_undefined ; + // table[(T_Object<<4)+T_null] = T_undefined ; + + // table[(T_double<<4)+T_undefined] = T_undefined ; + // table[(T_double<<4)+T_byte] = T_undefined ; + // table[(T_double<<4)+T_long] = T_undefined ; + // table[(T_double<<4)+T_short] = T_undefined ; + // table[(T_double<<4)+T_void] = T_undefined ; + // table[(T_double<<4)+T_String] = T_undefined ; + // table[(T_double<<4)+T_Object] = T_undefined ; + // table[(T_double<<4)+T_double] = T_undefined ; + // table[(T_double<<4)+T_float] = T_undefined ; + // table[(T_double<<4)+T_boolean] = T_undefined ; + // table[(T_double<<4)+T_char] = T_undefined ; + // table[(T_double<<4)+T_int] = T_undefined; + // table[(T_double<<4)+T_null] = T_undefined ; + + // table[(T_float<<4)+T_undefined] = T_undefined ; + // table[(T_float<<4)+T_byte] = T_undefined ; + // table[(T_float<<4)+T_long] = T_undefined ; + // table[(T_float<<4)+T_short] = T_undefined ; + // table[(T_float<<4)+T_void] = T_undefined ; + // table[(T_float<<4)+T_String] = T_undefined ; + // table[(T_float<<4)+T_Object] = T_undefined ; + // table[(T_float<<4)+T_double] = T_undefined ; + // table[(T_float<<4)+T_float] = T_undefined ; + // table[(T_float<<4)+T_boolean] = T_undefined ; + // table[(T_float<<4)+T_char] = T_undefined ; + // table[(T_float<<4)+T_int] = T_undefined ; + // table[(T_float<<4)+T_null] = T_undefined ; + + // table[(T_boolean<<4)+T_undefined] = T_undefined ; + // table[(T_boolean<<4)+T_byte] = T_undefined ; + // table[(T_boolean<<4)+T_long] = T_undefined ; + // table[(T_boolean<<4)+T_short] = T_undefined ; + // table[(T_boolean<<4)+T_void] = T_undefined ; + // table[(T_boolean<<4)+T_String] = T_undefined ; + // table[(T_boolean<<4)+T_Object] = T_undefined ; + // table[(T_boolean<<4)+T_double] = T_undefined ; + // table[(T_boolean<<4)+T_float] = T_undefined ; + table[(T_boolean << 4) + T_boolean] = (Boolean2Boolean << 12) + + (Boolean2Boolean << 4) + T_boolean; + // table[(T_boolean<<4)+T_char] = T_undefined ; + // table[(T_boolean<<4)+T_int] = T_undefined ; + // table[(T_boolean<<4)+T_null] = T_undefined ; + + // table[(T_char<<4)+T_undefined] = T_undefined ; + // table[(T_char<<4)+T_byte] = T_undefined ; + // table[(T_char<<4)+T_long] = T_undefined; + // table[(T_char<<4)+T_short] = T_undefined ; + // table[(T_char<<4)+T_void] = T_undefined ; + // table[(T_char<<4)+T_String] = T_undefined ; + // table[(T_char<<4)+T_Object] = T_undefined ; + // table[(T_char<<4)+T_double] = T_undefined ; + // table[(T_char<<4)+T_float] = T_undefined ; + // table[(T_char<<4)+T_boolean] = T_undefined ; + // table[(T_char<<4)+T_char] = T_undefined ; + // table[(T_char<<4)+T_int] = T_undefined ; + // table[(T_char<<4)+T_null] = T_undefined ; + + // table[(T_int<<4)+T_undefined] = T_undefined ; + // table[(T_int<<4)+T_byte] = T_undefined ; + // table[(T_int<<4)+T_long] = T_undefined ; + // table[(T_int<<4)+T_short] = T_undefined ; + // table[(T_int<<4)+T_void] = T_undefined ; + // table[(T_int<<4)+T_String] = T_undefined ; + // table[(T_int<<4)+T_Object] = T_undefined ; + // table[(T_int<<4)+T_double] = T_undefined ; + // table[(T_int<<4)+T_float] = T_undefined ; + // table[(T_int<<4)+T_boolean] = T_undefined ; + // table[(T_int<<4)+T_char] = T_undefined ; + // table[(T_int<<4)+T_int] = T_undefined ; + // table[(T_int<<4)+T_null] = T_undefined ; + + // table[(T_null<<4)+T_undefined] = T_undefined ; + // table[(T_null<<4)+T_byte] = T_undefined ; + // table[(T_null<<4)+T_long] = T_undefined ; + // table[(T_null<<4)+T_short] = T_undefined ; + // table[(T_null<<4)+T_void] = T_undefined ; + // table[(T_null<<4)+T_String] = T_undefined ; + // table[(T_null<<4)+T_Object] = T_undefined ; + // table[(T_null<<4)+T_double] = T_undefined ; + // table[(T_null<<4)+T_float] = T_undefined ; + // table[(T_null<<4)+T_boolean] = T_undefined ; + // table[(T_null<<4)+T_char] = T_undefined ; + // table[(T_null<<4)+T_int] = T_undefined ; + // table[(T_null<<4)+T_null] = T_undefined ; + return table; } - public static final int[] get_DIVIDE(){ - - //the code is an int - // (cast) left Op (cast) rigth --> result - // 0000 0000 0000 0000 0000 - // <<16 <<12 <<8 <<4 - - - // int[] table = new int[16*16] ; - + public static final int[] get_DIVIDE() { + + // the code is an int + // (cast) left Op (cast) rigth --> result + // 0000 0000 0000 0000 0000 + // <<16 <<12 <<8 <<4 + + // int[] table = new int[16*16] ; + return get_MINUS(); } - public static final int[] get_EQUAL_EQUAL(){ - - //the code is an int - // (cast) left Op (cast) rigth --> result - // 0000 0000 0000 0000 0000 - // <<16 <<12 <<8 <<4 - - int[] table = new int[16*16] ; - - // table[(T_undefined<<4)+T_undefined] = T_undefined ; - // table[(T_undefined<<4)+T_byte] = T_undefined ; - // table[(T_undefined<<4)+T_long] = T_undefined ; - // table[(T_undefined<<4)+T_short] = T_undefined ; - // table[(T_undefined<<4)+T_void] = T_undefined ; - // table[(T_undefined<<4)+T_String] = T_undefined ; - // table[(T_undefined<<4)+T_Object] = T_undefined ; - // table[(T_undefined<<4)+T_double] = T_undefined ; - // table[(T_undefined<<4)+T_float] = T_undefined ; - // table[(T_undefined<<4)+T_boolean] = T_undefined ; - // table[(T_undefined<<4)+T_char] = T_undefined ; - // table[(T_undefined<<4)+T_int] = T_undefined ; - // table[(T_undefined<<4)+T_null] = T_undefined ; - - // table[(T_byte<<4)+T_undefined] = T_undefined ; - table[(T_byte<<4)+T_byte] = (Byte2Int<<12)+(Byte2Int<<4)+T_boolean ; - table[(T_byte<<4)+T_long] = (Byte2Long<<12)+(Long2Long<<4)+T_boolean ; - table[(T_byte<<4)+T_short] = (Byte2Int<<12)+(Short2Int<<4)+T_boolean ; - // table[(T_byte<<4)+T_void] = T_undefined ; - // table[(T_byte<<4)+T_String] = T_undefined ; - // table[(T_byte<<4)+T_Object] = T_undefined ; - table[(T_byte<<4)+T_double] = (Byte2Double<<12)+(Double2Double<<4)+T_boolean ; - table[(T_byte<<4)+T_float] = (Byte2Float<<12)+(Float2Float<<4)+T_boolean; - // table[(T_byte<<4)+T_boolean] = T_undefined ; - table[(T_byte<<4)+T_char] = (Byte2Int<<12)+(Char2Int<<4)+T_boolean ; - table[(T_byte<<4)+T_int] = (Byte2Int<<12)+(Int2Int<<4)+T_boolean; - // table[(T_byte<<4)+T_null] = T_undefined ; - - // table[(T_long<<4)+T_undefined] = T_undefined ; - table[(T_long<<4)+T_byte] = (Long2Long<<12)+(Byte2Long<<4)+T_boolean; - table[(T_long<<4)+T_long] = (Long2Long<<12)+(Long2Long<<4)+T_boolean ; - table[(T_long<<4)+T_short] = (Long2Long<<12)+(Short2Long<<4)+T_boolean ; - // table[(T_long<<4)+T_void] = T_undefined ; - // table[(T_long<<4)+T_String] = T_undefined ; - // table[(T_long<<4)+T_Object] = T_undefined ; - table[(T_long<<4)+T_double] = (Long2Double<<12)+(Double2Double<<4)+T_boolean ; - table[(T_long<<4)+T_float] = (Long2Float<<12)+(Float2Float<<4)+T_boolean ; - // table[(T_long<<4)+T_boolean] = T_undefined ; - table[(T_long<<4)+T_char] = (Long2Long<<12)+(Char2Long<<4)+T_boolean ; - table[(T_long<<4)+T_int] = (Long2Long<<12)+(Int2Long<<4)+T_boolean ; - // table[(T_long<<4)+T_null] = T_undefined ; - - // table[(T_short<<4)+T_undefined] = T_undefined ; - table[(T_short<<4)+T_byte] = (Short2Int<<12)+(Byte2Int<<4)+T_boolean ; - table[(T_short<<4)+T_long] = (Short2Long<<12)+(Long2Long<<4)+T_boolean ; - table[(T_short<<4)+T_short] = (Short2Int<<12)+(Short2Int<<4)+T_boolean ; - // table[(T_short<<4)+T_void] = T_undefined ; - // table[(T_short<<4)+T_String] = T_undefined ; - // table[(T_short<<4)+T_Object] = T_undefined ; - table[(T_short<<4)+T_double] = (Short2Double<<12)+(Double2Double<<4)+T_boolean ; - table[(T_short<<4)+T_float] = (Short2Float<<12)+(Float2Float<<4)+T_boolean ; - // table[(T_short<<4)+T_boolean] = T_undefined ; - table[(T_short<<4)+T_char] = (Short2Int<<12)+(Char2Int<<4)+T_boolean ; - table[(T_short<<4)+T_int] = (Short2Int<<12)+(Int2Int<<4)+T_boolean ; - // table[(T_short<<4)+T_null] = T_undefined ; - - // table[(T_void<<4)+T_undefined] = T_undefined ; - // table[(T_void<<4)+T_byte] = T_undefined ; - // table[(T_void<<4)+T_long] = T_undefined ; - // table[(T_void<<4)+T_short] = T_undefined ; - // table[(T_void<<4)+T_void] = T_undefined ; - // table[(T_void<<4)+T_String] = T_undefined ; - // table[(T_void<<4)+T_Object] = T_undefined ; - // table[(T_void<<4)+T_double] = T_undefined ; - // table[(T_void<<4)+T_float] = T_undefined ; - // table[(T_void<<4)+T_boolean] = T_undefined ; - // table[(T_void<<4)+T_char] = T_undefined ; - // table[(T_void<<4)+T_int] = T_undefined ; - // table[(T_void<<4)+T_null] = T_undefined ; - - // table[(T_String<<4)+T_undefined] = T_undefined ; - // table[(T_String<<4)+T_byte] = T_undefined ; - // table[(T_String<<4)+T_long] = T_undefined ; - // table[(T_String<<4)+T_short] = T_undefined ; - // table[(T_String<<4)+T_void] = T_undefined ; - table[(T_String<<4)+T_String] = /*String2Object String2Object*/ - (T_Object<<16)+(T_String<<12)+(T_Object<<8)+(T_String<<4)+T_boolean ; - table[(T_String<<4)+T_Object] = /*String2Object Object2Object*/ - (T_Object<<16)+(T_String<<12)+(T_Object<<8)+(T_Object<<4)+T_boolean ; - // table[(T_String<<4)+T_double] = T_undefined ; - // table[(T_String<<4)+T_float] = T_undefined ; - // table[(T_String<<4)+T_boolean] = T_undefined ; - // table[(T_String<<4)+T_char] = T_undefined ; - // table[(T_String<<4)+T_int] = T_undefined ; - table[(T_String<<4)+T_null] = /*Object2String null2Object */ - (T_Object<<16)+(T_String<<12)+(T_Object<<8)+(T_null<<4)+T_boolean ; - - // table[(T_Object<<4)+T_undefined] = T_undefined ; - // table[(T_Object<<4)+T_byte] = T_undefined ; - // table[(T_Object<<4)+T_long] = T_undefined ; - // table[(T_Object<<4)+T_short] = T_undefined ; - // table[(T_Object<<4)+T_void] = T_undefined ; - table[(T_Object<<4)+T_String] = /*Object2Object String2Object*/ - (T_Object<<16)+(T_Object<<12)+(T_Object<<8)+(T_String<<4)+T_boolean ; - table[(T_Object<<4)+T_Object] = /*Object2Object Object2Object*/ - (T_Object<<16)+(T_Object<<12)+(T_Object<<8)+(T_Object<<4)+T_boolean ; - // table[(T_Object<<4)+T_double] = T_undefined ; - // table[(T_Object<<4)+T_float] = T_undefined ; - // table[(T_Object<<4)+T_boolean] = T_undefined ; - // table[(T_Object<<4)+T_char] = T_undefined ; - // table[(T_Object<<4)+T_int] = T_undefined ; - table[(T_Object<<4)+T_null] = /*Object2Object null2Object*/ - (T_Object<<16)+(T_Object<<12)+(T_Object<<8)+(T_null<<4)+T_boolean ; - - // table[(T_double<<4)+T_undefined] = T_undefined ; - table[(T_double<<4)+T_byte] = (Double2Double<<12)+(Byte2Double<<4)+T_boolean ; - table[(T_double<<4)+T_long] = (Double2Double<<12)+(Long2Double<<4)+T_boolean ; - table[(T_double<<4)+T_short] = (Double2Double<<12)+(Short2Double<<4)+T_boolean ; - // table[(T_double<<4)+T_void] = T_undefined ; - // table[(T_double<<4)+T_String] = T_undefined ; - // table[(T_double<<4)+T_Object] = T_undefined ; - table[(T_double<<4)+T_double] = (Double2Double<<12)+(Double2Double<<4)+T_boolean ; - table[(T_double<<4)+T_float] = (Double2Double<<12)+(Float2Double<<4)+T_boolean; - // table[(T_double<<4)+T_boolean] = T_undefined ; - table[(T_double<<4)+T_char] = (Double2Double<<12)+(Char2Double<<4)+T_boolean ; - table[(T_double<<4)+T_int] = (Double2Double<<12)+(Int2Double<<4)+T_boolean ; - // table[(T_double<<4)+T_null] = T_undefined ; - - // table[(T_float<<4)+T_undefined] = T_undefined ; - table[(T_float<<4)+T_byte] = (Float2Float<<12)+(Byte2Float<<4)+T_boolean ; - table[(T_float<<4)+T_long] = (Float2Float<<12)+(Long2Float<<4)+T_boolean ; - table[(T_float<<4)+T_short] = (Float2Float<<12)+(Short2Float<<4)+T_boolean ; - // table[(T_float<<4)+T_void] = T_undefined ; - // table[(T_float<<4)+T_String] = T_undefined ; - // table[(T_float<<4)+T_Object] = T_undefined ; - table[(T_float<<4)+T_double] = (Float2Double<<12)+(Double2Double<<4)+T_boolean ; - table[(T_float<<4)+T_float] = (Float2Float<<12)+(Float2Float<<4)+T_boolean ; - // table[(T_float<<4)+T_boolean] = T_undefined ; - table[(T_float<<4)+T_char] = (Float2Float<<12)+(Char2Float<<4)+T_boolean ; - table[(T_float<<4)+T_int] = (Float2Float<<12)+(Int2Float<<4)+T_boolean ; - // table[(T_float<<4)+T_null] = T_undefined ; - - // table[(T_boolean<<4)+T_undefined] = T_undefined ; - // table[(T_boolean<<4)+T_byte] = T_undefined ; - // table[(T_boolean<<4)+T_long] = T_undefined ; - // table[(T_boolean<<4)+T_short] = T_undefined ; - // table[(T_boolean<<4)+T_void] = T_undefined ; - // table[(T_boolean<<4)+T_String] = T_undefined ; - // table[(T_boolean<<4)+T_Object] = T_undefined ; - // table[(T_boolean<<4)+T_double] = T_undefined ; - // table[(T_boolean<<4)+T_float] = T_undefined ; - table[(T_boolean<<4)+T_boolean] = (Boolean2Boolean<<12)+(Boolean2Boolean<<4)+T_boolean ; - // table[(T_boolean<<4)+T_char] = T_undefined ; - // table[(T_boolean<<4)+T_int] = T_undefined ; - // table[(T_boolean<<4)+T_null] = T_undefined ; - - // table[(T_char<<4)+T_undefined] = T_undefined ; - table[(T_char<<4)+T_byte] = (Char2Int<<12)+(Byte2Int<<4)+T_boolean ; - table[(T_char<<4)+T_long] = (Char2Long<<12)+(Long2Long<<4)+T_boolean ; - table[(T_char<<4)+T_short] = (Char2Int<<12)+(Short2Int<<4)+T_boolean ; - // table[(T_char<<4)+T_void] = T_undefined ; - // table[(T_char<<4)+T_String] = T_undefined ; - // table[(T_char<<4)+T_Object] = T_undefined ; - table[(T_char<<4)+T_double] = (Char2Double<<12)+(Double2Double<<4)+T_boolean ; - table[(T_char<<4)+T_float] = (Char2Float<<12)+(Float2Float<<4)+T_boolean ; - // table[(T_char<<4)+T_boolean] = T_undefined ; - table[(T_char<<4)+T_char] = (Char2Int<<12)+(Char2Int<<4)+T_boolean ; - table[(T_char<<4)+T_int] = (Char2Int<<12)+(Int2Int<<4)+T_boolean ; - // table[(T_char<<4)+T_null] = T_undefined ; - - // table[(T_int<<4)+T_undefined] = T_undefined ; - table[(T_int<<4)+T_byte] = (Int2Int<<12)+(Byte2Int<<4)+T_boolean ; - table[(T_int<<4)+T_long] = (Int2Long<<12)+(Long2Long<<4)+T_boolean ; - table[(T_int<<4)+T_short] = (Int2Int<<12)+(Short2Int<<4)+T_boolean ; - // table[(T_int<<4)+T_void] = T_undefined ; - // table[(T_int<<4)+T_String] = T_undefined ; - // table[(T_int<<4)+T_Object] = T_undefined ; - table[(T_int<<4)+T_double] = (Int2Double<<12)+(Double2Double<<4)+T_boolean ; - table[(T_int<<4)+T_float] = (Int2Float<<12)+(Float2Float<<4)+T_boolean; - // table[(T_int<<4)+T_boolean] = T_undefined ; - table[(T_int<<4)+T_char] = (Int2Int<<12)+(Char2Int<<4)+T_boolean ; - table[(T_int<<4)+T_int] = (Int2Int<<12)+(Int2Int<<4)+T_boolean ; - // table[(T_int<<4)+T_null] = T_undefined ; - - // table[(T_null<<4)+T_undefined] = T_undefined ; - // table[(T_null<<4)+T_byte] = T_undefined ; - // table[(T_null<<4)+T_long] = T_undefined ; - // table[(T_null<<4)+T_short] = T_undefined ; - // table[(T_null<<4)+T_void] = T_undefined ; - table[(T_null<<4)+T_String] = /*null2Object String2Object*/ - (T_Object<<16)+(T_null<<12)+(T_Object<<8)+(T_String<<4)+T_boolean ; - table[(T_null<<4)+T_Object] = /*null2Object Object2Object*/ - (T_Object<<16)+(T_null<<12)+(T_Object<<8)+(T_Object<<4)+T_boolean ; ; - // table[(T_null<<4)+T_double] = T_undefined ; - // table[(T_null<<4)+T_float] = T_undefined ; - // table[(T_null<<4)+T_boolean] = T_undefined ; - // table[(T_null<<4)+T_char] = T_undefined ; - // table[(T_null<<4)+T_int] = T_undefined ; - table[(T_null<<4)+T_null] = /*null2Object null2Object*/ - (T_Object<<16)+(T_null<<12)+(T_Object<<8)+(T_null<<4)+T_boolean ; - return table ; + public static final int[] get_EQUAL_EQUAL() { + + // the code is an int + // (cast) left Op (cast) rigth --> result + // 0000 0000 0000 0000 0000 + // <<16 <<12 <<8 <<4 + + int[] table = new int[16 * 16]; + + // table[(T_undefined<<4)+T_undefined] = T_undefined ; + // table[(T_undefined<<4)+T_byte] = T_undefined ; + // table[(T_undefined<<4)+T_long] = T_undefined ; + // table[(T_undefined<<4)+T_short] = T_undefined ; + // table[(T_undefined<<4)+T_void] = T_undefined ; + // table[(T_undefined<<4)+T_String] = T_undefined ; + // table[(T_undefined<<4)+T_Object] = T_undefined ; + // table[(T_undefined<<4)+T_double] = T_undefined ; + // table[(T_undefined<<4)+T_float] = T_undefined ; + // table[(T_undefined<<4)+T_boolean] = T_undefined ; + // table[(T_undefined<<4)+T_char] = T_undefined ; + // table[(T_undefined<<4)+T_int] = T_undefined ; + // table[(T_undefined<<4)+T_null] = T_undefined ; + + // table[(T_byte<<4)+T_undefined] = T_undefined ; + table[(T_byte << 4) + T_byte] = (Byte2Int << 12) + (Byte2Int << 4) + + T_boolean; + table[(T_byte << 4) + T_long] = (Byte2Long << 12) + (Long2Long << 4) + + T_boolean; + table[(T_byte << 4) + T_short] = (Byte2Int << 12) + (Short2Int << 4) + + T_boolean; + // table[(T_byte<<4)+T_void] = T_undefined ; + // table[(T_byte<<4)+T_String] = T_undefined ; + // table[(T_byte<<4)+T_Object] = T_undefined ; + table[(T_byte << 4) + T_double] = (Byte2Double << 12) + + (Double2Double << 4) + T_boolean; + table[(T_byte << 4) + T_float] = (Byte2Float << 12) + + (Float2Float << 4) + T_boolean; + // table[(T_byte<<4)+T_boolean] = T_undefined ; + table[(T_byte << 4) + T_char] = (Byte2Int << 12) + (Char2Int << 4) + + T_boolean; + table[(T_byte << 4) + T_int] = (Byte2Int << 12) + (Int2Int << 4) + + T_boolean; + // table[(T_byte<<4)+T_null] = T_undefined ; + + // table[(T_long<<4)+T_undefined] = T_undefined ; + table[(T_long << 4) + T_byte] = (Long2Long << 12) + (Byte2Long << 4) + + T_boolean; + table[(T_long << 4) + T_long] = (Long2Long << 12) + (Long2Long << 4) + + T_boolean; + table[(T_long << 4) + T_short] = (Long2Long << 12) + (Short2Long << 4) + + T_boolean; + // table[(T_long<<4)+T_void] = T_undefined ; + // table[(T_long<<4)+T_String] = T_undefined ; + // table[(T_long<<4)+T_Object] = T_undefined ; + table[(T_long << 4) + T_double] = (Long2Double << 12) + + (Double2Double << 4) + T_boolean; + table[(T_long << 4) + T_float] = (Long2Float << 12) + + (Float2Float << 4) + T_boolean; + // table[(T_long<<4)+T_boolean] = T_undefined ; + table[(T_long << 4) + T_char] = (Long2Long << 12) + (Char2Long << 4) + + T_boolean; + table[(T_long << 4) + T_int] = (Long2Long << 12) + (Int2Long << 4) + + T_boolean; + // table[(T_long<<4)+T_null] = T_undefined ; + + // table[(T_short<<4)+T_undefined] = T_undefined ; + table[(T_short << 4) + T_byte] = (Short2Int << 12) + (Byte2Int << 4) + + T_boolean; + table[(T_short << 4) + T_long] = (Short2Long << 12) + (Long2Long << 4) + + T_boolean; + table[(T_short << 4) + T_short] = (Short2Int << 12) + (Short2Int << 4) + + T_boolean; + // table[(T_short<<4)+T_void] = T_undefined ; + // table[(T_short<<4)+T_String] = T_undefined ; + // table[(T_short<<4)+T_Object] = T_undefined ; + table[(T_short << 4) + T_double] = (Short2Double << 12) + + (Double2Double << 4) + T_boolean; + table[(T_short << 4) + T_float] = (Short2Float << 12) + + (Float2Float << 4) + T_boolean; + // table[(T_short<<4)+T_boolean] = T_undefined ; + table[(T_short << 4) + T_char] = (Short2Int << 12) + (Char2Int << 4) + + T_boolean; + table[(T_short << 4) + T_int] = (Short2Int << 12) + (Int2Int << 4) + + T_boolean; + // table[(T_short<<4)+T_null] = T_undefined ; + + // table[(T_void<<4)+T_undefined] = T_undefined ; + // table[(T_void<<4)+T_byte] = T_undefined ; + // table[(T_void<<4)+T_long] = T_undefined ; + // table[(T_void<<4)+T_short] = T_undefined ; + // table[(T_void<<4)+T_void] = T_undefined ; + // table[(T_void<<4)+T_String] = T_undefined ; + // table[(T_void<<4)+T_Object] = T_undefined ; + // table[(T_void<<4)+T_double] = T_undefined ; + // table[(T_void<<4)+T_float] = T_undefined ; + // table[(T_void<<4)+T_boolean] = T_undefined ; + // table[(T_void<<4)+T_char] = T_undefined ; + // table[(T_void<<4)+T_int] = T_undefined ; + // table[(T_void<<4)+T_null] = T_undefined ; + + // table[(T_String<<4)+T_undefined] = T_undefined ; + // table[(T_String<<4)+T_byte] = T_undefined ; + // table[(T_String<<4)+T_long] = T_undefined ; + // table[(T_String<<4)+T_short] = T_undefined ; + // table[(T_String<<4)+T_void] = T_undefined ; + table[(T_String << 4) + T_String] = /* String2Object String2Object */ + (T_Object << 16) + (T_String << 12) + (T_Object << 8) + (T_String << 4) + + T_boolean; + table[(T_String << 4) + T_Object] = /* String2Object Object2Object */ + (T_Object << 16) + (T_String << 12) + (T_Object << 8) + (T_Object << 4) + + T_boolean; + // table[(T_String<<4)+T_double] = T_undefined ; + // table[(T_String<<4)+T_float] = T_undefined ; + // table[(T_String<<4)+T_boolean] = T_undefined ; + // table[(T_String<<4)+T_char] = T_undefined ; + // table[(T_String<<4)+T_int] = T_undefined ; + table[(T_String << 4) + T_null] = /* Object2String null2Object */ + (T_Object << 16) + (T_String << 12) + (T_Object << 8) + (T_null << 4) + + T_boolean; + + // table[(T_Object<<4)+T_undefined] = T_undefined ; + // table[(T_Object<<4)+T_byte] = T_undefined ; + // table[(T_Object<<4)+T_long] = T_undefined ; + // table[(T_Object<<4)+T_short] = T_undefined ; + // table[(T_Object<<4)+T_void] = T_undefined ; + table[(T_Object << 4) + T_String] = /* Object2Object String2Object */ + (T_Object << 16) + (T_Object << 12) + (T_Object << 8) + (T_String << 4) + + T_boolean; + table[(T_Object << 4) + T_Object] = /* Object2Object Object2Object */ + (T_Object << 16) + (T_Object << 12) + (T_Object << 8) + (T_Object << 4) + + T_boolean; + // table[(T_Object<<4)+T_double] = T_undefined ; + // table[(T_Object<<4)+T_float] = T_undefined ; + // table[(T_Object<<4)+T_boolean] = T_undefined ; + // table[(T_Object<<4)+T_char] = T_undefined ; + // table[(T_Object<<4)+T_int] = T_undefined ; + table[(T_Object << 4) + T_null] = /* Object2Object null2Object */ + (T_Object << 16) + (T_Object << 12) + (T_Object << 8) + (T_null << 4) + + T_boolean; + + // table[(T_double<<4)+T_undefined] = T_undefined ; + table[(T_double << 4) + T_byte] = (Double2Double << 12) + + (Byte2Double << 4) + T_boolean; + table[(T_double << 4) + T_long] = (Double2Double << 12) + + (Long2Double << 4) + T_boolean; + table[(T_double << 4) + T_short] = (Double2Double << 12) + + (Short2Double << 4) + T_boolean; + // table[(T_double<<4)+T_void] = T_undefined ; + // table[(T_double<<4)+T_String] = T_undefined ; + // table[(T_double<<4)+T_Object] = T_undefined ; + table[(T_double << 4) + T_double] = (Double2Double << 12) + + (Double2Double << 4) + T_boolean; + table[(T_double << 4) + T_float] = (Double2Double << 12) + + (Float2Double << 4) + T_boolean; + // table[(T_double<<4)+T_boolean] = T_undefined ; + table[(T_double << 4) + T_char] = (Double2Double << 12) + + (Char2Double << 4) + T_boolean; + table[(T_double << 4) + T_int] = (Double2Double << 12) + + (Int2Double << 4) + T_boolean; + // table[(T_double<<4)+T_null] = T_undefined ; + + // table[(T_float<<4)+T_undefined] = T_undefined ; + table[(T_float << 4) + T_byte] = (Float2Float << 12) + + (Byte2Float << 4) + T_boolean; + table[(T_float << 4) + T_long] = (Float2Float << 12) + + (Long2Float << 4) + T_boolean; + table[(T_float << 4) + T_short] = (Float2Float << 12) + + (Short2Float << 4) + T_boolean; + // table[(T_float<<4)+T_void] = T_undefined ; + // table[(T_float<<4)+T_String] = T_undefined ; + // table[(T_float<<4)+T_Object] = T_undefined ; + table[(T_float << 4) + T_double] = (Float2Double << 12) + + (Double2Double << 4) + T_boolean; + table[(T_float << 4) + T_float] = (Float2Float << 12) + + (Float2Float << 4) + T_boolean; + // table[(T_float<<4)+T_boolean] = T_undefined ; + table[(T_float << 4) + T_char] = (Float2Float << 12) + + (Char2Float << 4) + T_boolean; + table[(T_float << 4) + T_int] = (Float2Float << 12) + (Int2Float << 4) + + T_boolean; + // table[(T_float<<4)+T_null] = T_undefined ; + + // table[(T_boolean<<4)+T_undefined] = T_undefined ; + // table[(T_boolean<<4)+T_byte] = T_undefined ; + // table[(T_boolean<<4)+T_long] = T_undefined ; + // table[(T_boolean<<4)+T_short] = T_undefined ; + // table[(T_boolean<<4)+T_void] = T_undefined ; + // table[(T_boolean<<4)+T_String] = T_undefined ; + // table[(T_boolean<<4)+T_Object] = T_undefined ; + // table[(T_boolean<<4)+T_double] = T_undefined ; + // table[(T_boolean<<4)+T_float] = T_undefined ; + table[(T_boolean << 4) + T_boolean] = (Boolean2Boolean << 12) + + (Boolean2Boolean << 4) + T_boolean; + // table[(T_boolean<<4)+T_char] = T_undefined ; + // table[(T_boolean<<4)+T_int] = T_undefined ; + // table[(T_boolean<<4)+T_null] = T_undefined ; + + // table[(T_char<<4)+T_undefined] = T_undefined ; + table[(T_char << 4) + T_byte] = (Char2Int << 12) + (Byte2Int << 4) + + T_boolean; + table[(T_char << 4) + T_long] = (Char2Long << 12) + (Long2Long << 4) + + T_boolean; + table[(T_char << 4) + T_short] = (Char2Int << 12) + (Short2Int << 4) + + T_boolean; + // table[(T_char<<4)+T_void] = T_undefined ; + // table[(T_char<<4)+T_String] = T_undefined ; + // table[(T_char<<4)+T_Object] = T_undefined ; + table[(T_char << 4) + T_double] = (Char2Double << 12) + + (Double2Double << 4) + T_boolean; + table[(T_char << 4) + T_float] = (Char2Float << 12) + + (Float2Float << 4) + T_boolean; + // table[(T_char<<4)+T_boolean] = T_undefined ; + table[(T_char << 4) + T_char] = (Char2Int << 12) + (Char2Int << 4) + + T_boolean; + table[(T_char << 4) + T_int] = (Char2Int << 12) + (Int2Int << 4) + + T_boolean; + // table[(T_char<<4)+T_null] = T_undefined ; + + // table[(T_int<<4)+T_undefined] = T_undefined ; + table[(T_int << 4) + T_byte] = (Int2Int << 12) + (Byte2Int << 4) + + T_boolean; + table[(T_int << 4) + T_long] = (Int2Long << 12) + (Long2Long << 4) + + T_boolean; + table[(T_int << 4) + T_short] = (Int2Int << 12) + (Short2Int << 4) + + T_boolean; + // table[(T_int<<4)+T_void] = T_undefined ; + // table[(T_int<<4)+T_String] = T_undefined ; + // table[(T_int<<4)+T_Object] = T_undefined ; + table[(T_int << 4) + T_double] = (Int2Double << 12) + + (Double2Double << 4) + T_boolean; + table[(T_int << 4) + T_float] = (Int2Float << 12) + (Float2Float << 4) + + T_boolean; + // table[(T_int<<4)+T_boolean] = T_undefined ; + table[(T_int << 4) + T_char] = (Int2Int << 12) + (Char2Int << 4) + + T_boolean; + table[(T_int << 4) + T_int] = (Int2Int << 12) + (Int2Int << 4) + + T_boolean; + // table[(T_int<<4)+T_null] = T_undefined ; + + // table[(T_null<<4)+T_undefined] = T_undefined ; + // table[(T_null<<4)+T_byte] = T_undefined ; + // table[(T_null<<4)+T_long] = T_undefined ; + // table[(T_null<<4)+T_short] = T_undefined ; + // table[(T_null<<4)+T_void] = T_undefined ; + table[(T_null << 4) + T_String] = /* null2Object String2Object */ + (T_Object << 16) + (T_null << 12) + (T_Object << 8) + (T_String << 4) + + T_boolean; + table[(T_null << 4) + T_Object] = /* null2Object Object2Object */ + (T_Object << 16) + (T_null << 12) + (T_Object << 8) + (T_Object << 4) + + T_boolean; + ; + // table[(T_null<<4)+T_double] = T_undefined ; + // table[(T_null<<4)+T_float] = T_undefined ; + // table[(T_null<<4)+T_boolean] = T_undefined ; + // table[(T_null<<4)+T_char] = T_undefined ; + // table[(T_null<<4)+T_int] = T_undefined ; + table[(T_null << 4) + T_null] = /* null2Object null2Object */ + (T_Object << 16) + (T_null << 12) + (T_Object << 8) + (T_null << 4) + + T_boolean; + return table; } - public static final int[] get_GREATER(){ - - //the code is an int - // (cast) left Op (cast) rigth --> result - // 0000 0000 0000 0000 0000 - // <<16 <<12 <<8 <<4 - - // int[] table = new int[16*16] ; + public static final int[] get_GREATER() { + + // the code is an int + // (cast) left Op (cast) rigth --> result + // 0000 0000 0000 0000 0000 + // <<16 <<12 <<8 <<4 + + // int[] table = new int[16*16] ; return get_LESS(); } - public static final int[] get_GREATER_EQUAL(){ - - //the code is an int - // (cast) left Op (cast) rigth --> result - // 0000 0000 0000 0000 0000 - // <<16 <<12 <<8 <<4 - - // int[] table = new int[16*16] ; + public static final int[] get_GREATER_EQUAL() { + + // the code is an int + // (cast) left Op (cast) rigth --> result + // 0000 0000 0000 0000 0000 + // <<16 <<12 <<8 <<4 + + // int[] table = new int[16*16] ; return get_LESS(); } - public static final int[] get_LEFT_SHIFT(){ - - //the code is an int - // (cast) left Op (cast) rigth --> result - // 0000 0000 0000 0000 0000 - // <<16 <<12 <<8 <<4 - - int[] table = new int[16*16] ; - - // table[(T_undefined<<4)+T_undefined] = T_undefined ; - // table[(T_undefined<<4)+T_byte] = T_undefined ; - // table[(T_undefined<<4)+T_long] = T_undefined ; - // table[(T_undefined<<4)+T_short] = T_undefined ; - // table[(T_undefined<<4)+T_void] = T_undefined ; - // table[(T_undefined<<4)+T_String] = T_undefined ; - // table[(T_undefined<<4)+T_Object] = T_undefined ; - // table[(T_undefined<<4)+T_double] = T_undefined ; - // table[(T_undefined<<4)+T_float] = T_undefined ; - // table[(T_undefined<<4)+T_boolean] = T_undefined ; - // table[(T_undefined<<4)+T_char] = T_undefined ; - // table[(T_undefined<<4)+T_int] = T_undefined ; - // table[(T_undefined<<4)+T_null] = T_undefined ; - - // table[(T_byte<<4)+T_undefined] = T_undefined ; - table[(T_byte<<4)+T_byte] = (Byte2Int<<12)+(Byte2Int<<4)+T_int ; - table[(T_byte<<4)+T_long] = (Byte2Int<<12)+(Long2Int<<4)+T_int ; - table[(T_byte<<4)+T_short] = (Byte2Int<<12)+(Short2Int<<4)+T_int ; - // table[(T_byte<<4)+T_void] = T_undefined ; - // table[(T_byte<<4)+T_String] = T_undefined ; - // table[(T_byte<<4)+T_Object] = T_undefined ; - // table[(T_byte<<4)+T_double] = T_undefined ; - // table[(T_byte<<4)+T_float] = T_undefined ; - // table[(T_byte<<4)+T_boolean] = T_undefined ; - table[(T_byte<<4)+T_char] = (Byte2Int<<12)+(Char2Int<<4)+T_int ; - table[(T_byte<<4)+T_int] = (Byte2Int<<12)+(Int2Int<<4)+T_int ; - // table[(T_byte<<4)+T_null] = T_undefined ; - - // table[(T_long<<4)+T_undefined] = T_undefined ; - table[(T_long<<4)+T_byte] = (Long2Long<<12)+(Byte2Int<<4)+T_long; - table[(T_long<<4)+T_long] = (Long2Long<<12)+(Long2Int<<4)+T_long ; - table[(T_long<<4)+T_short] = (Long2Long<<12)+(Short2Int<<4)+T_long ; - // table[(T_long<<4)+T_void] = T_undefined ; - // table[(T_long<<4)+T_String] = T_undefined ; - // table[(T_long<<4)+T_Object] = T_undefined ; - // table[(T_long<<4)+T_double] = T_undefined ; - // table[(T_long<<4)+T_float] = T_undefined ; - // table[(T_long<<4)+T_boolean] = T_undefined ; - table[(T_long<<4)+T_char] = (Long2Long<<12)+(Char2Int<<4)+T_long ; - table[(T_long<<4)+T_int] = (Long2Long<<12)+(Int2Int<<4)+T_long ; - // table[(T_long<<4)+T_null] = T_undefined ; - - // table[(T_short<<4)+T_undefined] = T_undefined ; - table[(T_short<<4)+T_byte] = (Short2Int<<12)+(Byte2Int<<4)+T_int ; - table[(T_short<<4)+T_long] = (Short2Int<<12)+(Long2Int<<4)+T_int ; - table[(T_short<<4)+T_short] = (Short2Int<<12)+(Short2Int<<4)+T_int ; - // table[(T_short<<4)+T_void] = T_undefined ; - // table[(T_short<<4)+T_String] = T_undefined ; - // table[(T_short<<4)+T_Object] = T_undefined ; - // table[(T_short<<4)+T_double] = T_undefined ; - // table[(T_short<<4)+T_float] = T_undefined ; - // table[(T_short<<4)+T_boolean] = T_undefined ; - table[(T_short<<4)+T_char] = (Short2Int<<12)+(Char2Int<<4)+T_int ; - table[(T_short<<4)+T_int] = (Short2Int<<12)+(Int2Int<<4)+T_int ; - // table[(T_short<<4)+T_null] = T_undefined ; - - // table[(T_void<<4)+T_undefined] = T_undefined ; - // table[(T_void<<4)+T_byte] = T_undefined ; - // table[(T_void<<4)+T_long] = T_undefined ; - // table[(T_void<<4)+T_short] = T_undefined ; - // table[(T_void<<4)+T_void] = T_undefined ; - // table[(T_void<<4)+T_String] = T_undefined ; - // table[(T_void<<4)+T_Object] = T_undefined ; - // table[(T_void<<4)+T_double] = T_undefined ; - // table[(T_void<<4)+T_float] = T_undefined ; - // table[(T_void<<4)+T_boolean] = T_undefined ; - // table[(T_void<<4)+T_char] = T_undefined ; - // table[(T_void<<4)+T_int] = T_undefined ; - // table[(T_void<<4)+T_null] = T_undefined ; - - // table[(T_String<<4)+T_undefined] = T_undefined ; - // table[(T_String<<4)+T_byte] = T_undefined ; - // table[(T_String<<4)+T_long] = T_undefined ; - // table[(T_String<<4)+T_short] = T_undefined ; - // table[(T_String<<4)+T_void] = T_undefined ; - // table[(T_String<<4)+T_String] = T_undefined ; - // table[(T_String<<4)+T_Object] = T_undefined ; - // table[(T_String<<4)+T_double] = T_undefined ; - // table[(T_String<<4)+T_float] = T_undefined ; - // table[(T_String<<4)+T_boolean] = T_undefined ; - // table[(T_String<<4)+T_char] = T_undefined ; - // table[(T_String<<4)+T_int] = T_undefined ; - // table[(T_String<<4)+T_null] = T_undefined ; - - // table[(T_Object<<4)+T_undefined] = T_undefined ; - // table[(T_Object<<4)+T_byte] = T_undefined ; - // table[(T_Object<<4)+T_long] = T_undefined ; - // table[(T_Object<<4)+T_short] = T_undefined ; - // table[(T_Object<<4)+T_void] = T_undefined ; - // table[(T_Object<<4)+T_String] = T_undefined ; - // table[(T_Object<<4)+T_Object] = T_undefined ; - // table[(T_Object<<4)+T_double] = T_undefined ; - // table[(T_Object<<4)+T_float] = T_undefined ; - // table[(T_Object<<4)+T_boolean] = T_undefined ; - // table[(T_Object<<4)+T_char] = T_undefined ; - // table[(T_Object<<4)+T_int] = T_undefined ; - // table[(T_Object<<4)+T_null] = T_undefined ; - - // table[(T_double<<4)+T_undefined] = T_undefined ; - // table[(T_double<<4)+T_byte] = T_undefined ; - // table[(T_double<<4)+T_long] = T_undefined ; - // table[(T_double<<4)+T_short] = T_undefined ; - // table[(T_double<<4)+T_void] = T_undefined ; - // table[(T_double<<4)+T_String] = T_undefined ; - // table[(T_double<<4)+T_Object] = T_undefined ; - // table[(T_double<<4)+T_double] = T_undefined ; - // table[(T_double<<4)+T_float] = T_undefined ; - // table[(T_double<<4)+T_boolean] = T_undefined ; - // table[(T_double<<4)+T_char] = T_undefined ; - // table[(T_double<<4)+T_int] = T_undefined; - // table[(T_double<<4)+T_null] = T_undefined ; - - // table[(T_float<<4)+T_undefined] = T_undefined ; - // table[(T_float<<4)+T_byte] = T_undefined ; - // table[(T_float<<4)+T_long] = T_undefined ; - // table[(T_float<<4)+T_short] = T_undefined ; - // table[(T_float<<4)+T_void] = T_undefined ; - // table[(T_float<<4)+T_String] = T_undefined ; - // table[(T_float<<4)+T_Object] = T_undefined ; - // table[(T_float<<4)+T_double] = T_undefined ; - // table[(T_float<<4)+T_float] = T_undefined ; - // table[(T_float<<4)+T_boolean] = T_undefined ; - // table[(T_float<<4)+T_char] = T_undefined ; - // table[(T_float<<4)+T_int] = T_undefined ; - // table[(T_float<<4)+T_null] = T_undefined ; - - // table[(T_boolean<<4)+T_undefined] = T_undefined ; - // table[(T_boolean<<4)+T_byte] = T_undefined ; - // table[(T_boolean<<4)+T_long] = T_undefined ; - // table[(T_boolean<<4)+T_short] = T_undefined ; - // table[(T_boolean<<4)+T_void] = T_undefined ; - // table[(T_boolean<<4)+T_String] = T_undefined ; - // table[(T_boolean<<4)+T_Object] = T_undefined ; - // table[(T_boolean<<4)+T_double] = T_undefined ; - // table[(T_boolean<<4)+T_float] = T_undefined ; - // table[(T_boolean<<4)+T_boolean] = T_undefined ; - // table[(T_boolean<<4)+T_char] = T_undefined ; - // table[(T_boolean<<4)+T_int] = T_undefined ; - // table[(T_boolean<<4)+T_null] = T_undefined ; - - // table[(T_char<<4)+T_undefined] = T_undefined ; - table[(T_char<<4)+T_byte] = (Char2Int<<12)+(Byte2Int<<4)+T_int ; - table[(T_char<<4)+T_long] = (Char2Int<<12)+(Long2Int<<4)+T_int ; - table[(T_char<<4)+T_short] = (Char2Int<<12)+(Short2Int<<4)+T_int ; - // table[(T_char<<4)+T_void] = T_undefined ; - // table[(T_char<<4)+T_String] = T_undefined ; - // table[(T_char<<4)+T_Object] = T_undefined ; - // table[(T_char<<4)+T_double] = T_undefined ; - // table[(T_char<<4)+T_float] = T_undefined ; - // table[(T_char<<4)+T_boolean] = T_undefined ; - table[(T_char<<4)+T_char] = (Char2Int<<12)+(Char2Int<<4)+T_int ; - table[(T_char<<4)+T_int] = (Char2Int<<12)+(Int2Int<<4)+T_int ; - // table[(T_char<<4)+T_null] = T_undefined ; - - // table[(T_int<<4)+T_undefined] = T_undefined ; - table[(T_int<<4)+T_byte] = (Int2Int<<12)+(Byte2Int<<4)+T_int ; - table[(T_int<<4)+T_long] = (Int2Int<<12)+(Long2Int<<4)+T_int ; - table[(T_int<<4)+T_short] = (Int2Int<<12)+(Short2Int<<4)+T_int ; - // table[(T_int<<4)+T_void] = T_undefined ; - // table[(T_int<<4)+T_String] = T_undefined ; - // table[(T_int<<4)+T_Object] = T_undefined ; - // table[(T_int<<4)+T_double] = T_undefined ; - // table[(T_int<<4)+T_float] = T_undefined ; - // table[(T_int<<4)+T_boolean] = T_undefined ; - table[(T_int<<4)+T_char] = (Int2Int<<12)+(Char2Int<<4)+T_int ; - table[(T_int<<4)+T_int] = (Int2Int<<12)+(Int2Int<<4)+T_int ; - // table[(T_int<<4)+T_null] = T_undefined ; - - // table[(T_null<<4)+T_undefined] = T_undefined ; - // table[(T_null<<4)+T_byte] = T_undefined ; - // table[(T_null<<4)+T_long] = T_undefined ; - // table[(T_null<<4)+T_short] = T_undefined ; - // table[(T_null<<4)+T_void] = T_undefined ; - // table[(T_null<<4)+T_String] = T_undefined ; - // table[(T_null<<4)+T_Object] = T_undefined ; - // table[(T_null<<4)+T_double] = T_undefined ; - // table[(T_null<<4)+T_float] = T_undefined ; - // table[(T_null<<4)+T_boolean] = T_undefined ; - // table[(T_null<<4)+T_char] = T_undefined ; - // table[(T_null<<4)+T_int] = T_undefined ; - // table[(T_null<<4)+T_null] = T_undefined ; - - return table ; + public static final int[] get_LEFT_SHIFT() { + + // the code is an int + // (cast) left Op (cast) rigth --> result + // 0000 0000 0000 0000 0000 + // <<16 <<12 <<8 <<4 + + int[] table = new int[16 * 16]; + + // table[(T_undefined<<4)+T_undefined] = T_undefined ; + // table[(T_undefined<<4)+T_byte] = T_undefined ; + // table[(T_undefined<<4)+T_long] = T_undefined ; + // table[(T_undefined<<4)+T_short] = T_undefined ; + // table[(T_undefined<<4)+T_void] = T_undefined ; + // table[(T_undefined<<4)+T_String] = T_undefined ; + // table[(T_undefined<<4)+T_Object] = T_undefined ; + // table[(T_undefined<<4)+T_double] = T_undefined ; + // table[(T_undefined<<4)+T_float] = T_undefined ; + // table[(T_undefined<<4)+T_boolean] = T_undefined ; + // table[(T_undefined<<4)+T_char] = T_undefined ; + // table[(T_undefined<<4)+T_int] = T_undefined ; + // table[(T_undefined<<4)+T_null] = T_undefined ; + + // table[(T_byte<<4)+T_undefined] = T_undefined ; + table[(T_byte << 4) + T_byte] = (Byte2Int << 12) + (Byte2Int << 4) + + T_int; + table[(T_byte << 4) + T_long] = (Byte2Int << 12) + (Long2Int << 4) + + T_int; + table[(T_byte << 4) + T_short] = (Byte2Int << 12) + (Short2Int << 4) + + T_int; + // table[(T_byte<<4)+T_void] = T_undefined ; + // table[(T_byte<<4)+T_String] = T_undefined ; + // table[(T_byte<<4)+T_Object] = T_undefined ; + // table[(T_byte<<4)+T_double] = T_undefined ; + // table[(T_byte<<4)+T_float] = T_undefined ; + // table[(T_byte<<4)+T_boolean] = T_undefined ; + table[(T_byte << 4) + T_char] = (Byte2Int << 12) + (Char2Int << 4) + + T_int; + table[(T_byte << 4) + T_int] = (Byte2Int << 12) + (Int2Int << 4) + + T_int; + // table[(T_byte<<4)+T_null] = T_undefined ; + + // table[(T_long<<4)+T_undefined] = T_undefined ; + table[(T_long << 4) + T_byte] = (Long2Long << 12) + (Byte2Int << 4) + + T_long; + table[(T_long << 4) + T_long] = (Long2Long << 12) + (Long2Int << 4) + + T_long; + table[(T_long << 4) + T_short] = (Long2Long << 12) + (Short2Int << 4) + + T_long; + // table[(T_long<<4)+T_void] = T_undefined ; + // table[(T_long<<4)+T_String] = T_undefined ; + // table[(T_long<<4)+T_Object] = T_undefined ; + // table[(T_long<<4)+T_double] = T_undefined ; + // table[(T_long<<4)+T_float] = T_undefined ; + // table[(T_long<<4)+T_boolean] = T_undefined ; + table[(T_long << 4) + T_char] = (Long2Long << 12) + (Char2Int << 4) + + T_long; + table[(T_long << 4) + T_int] = (Long2Long << 12) + (Int2Int << 4) + + T_long; + // table[(T_long<<4)+T_null] = T_undefined ; + + // table[(T_short<<4)+T_undefined] = T_undefined ; + table[(T_short << 4) + T_byte] = (Short2Int << 12) + (Byte2Int << 4) + + T_int; + table[(T_short << 4) + T_long] = (Short2Int << 12) + (Long2Int << 4) + + T_int; + table[(T_short << 4) + T_short] = (Short2Int << 12) + (Short2Int << 4) + + T_int; + // table[(T_short<<4)+T_void] = T_undefined ; + // table[(T_short<<4)+T_String] = T_undefined ; + // table[(T_short<<4)+T_Object] = T_undefined ; + // table[(T_short<<4)+T_double] = T_undefined ; + // table[(T_short<<4)+T_float] = T_undefined ; + // table[(T_short<<4)+T_boolean] = T_undefined ; + table[(T_short << 4) + T_char] = (Short2Int << 12) + (Char2Int << 4) + + T_int; + table[(T_short << 4) + T_int] = (Short2Int << 12) + (Int2Int << 4) + + T_int; + // table[(T_short<<4)+T_null] = T_undefined ; + + // table[(T_void<<4)+T_undefined] = T_undefined ; + // table[(T_void<<4)+T_byte] = T_undefined ; + // table[(T_void<<4)+T_long] = T_undefined ; + // table[(T_void<<4)+T_short] = T_undefined ; + // table[(T_void<<4)+T_void] = T_undefined ; + // table[(T_void<<4)+T_String] = T_undefined ; + // table[(T_void<<4)+T_Object] = T_undefined ; + // table[(T_void<<4)+T_double] = T_undefined ; + // table[(T_void<<4)+T_float] = T_undefined ; + // table[(T_void<<4)+T_boolean] = T_undefined ; + // table[(T_void<<4)+T_char] = T_undefined ; + // table[(T_void<<4)+T_int] = T_undefined ; + // table[(T_void<<4)+T_null] = T_undefined ; + + // table[(T_String<<4)+T_undefined] = T_undefined ; + // table[(T_String<<4)+T_byte] = T_undefined ; + // table[(T_String<<4)+T_long] = T_undefined ; + // table[(T_String<<4)+T_short] = T_undefined ; + // table[(T_String<<4)+T_void] = T_undefined ; + // table[(T_String<<4)+T_String] = T_undefined ; + // table[(T_String<<4)+T_Object] = T_undefined ; + // table[(T_String<<4)+T_double] = T_undefined ; + // table[(T_String<<4)+T_float] = T_undefined ; + // table[(T_String<<4)+T_boolean] = T_undefined ; + // table[(T_String<<4)+T_char] = T_undefined ; + // table[(T_String<<4)+T_int] = T_undefined ; + // table[(T_String<<4)+T_null] = T_undefined ; + + // table[(T_Object<<4)+T_undefined] = T_undefined ; + // table[(T_Object<<4)+T_byte] = T_undefined ; + // table[(T_Object<<4)+T_long] = T_undefined ; + // table[(T_Object<<4)+T_short] = T_undefined ; + // table[(T_Object<<4)+T_void] = T_undefined ; + // table[(T_Object<<4)+T_String] = T_undefined ; + // table[(T_Object<<4)+T_Object] = T_undefined ; + // table[(T_Object<<4)+T_double] = T_undefined ; + // table[(T_Object<<4)+T_float] = T_undefined ; + // table[(T_Object<<4)+T_boolean] = T_undefined ; + // table[(T_Object<<4)+T_char] = T_undefined ; + // table[(T_Object<<4)+T_int] = T_undefined ; + // table[(T_Object<<4)+T_null] = T_undefined ; + + // table[(T_double<<4)+T_undefined] = T_undefined ; + // table[(T_double<<4)+T_byte] = T_undefined ; + // table[(T_double<<4)+T_long] = T_undefined ; + // table[(T_double<<4)+T_short] = T_undefined ; + // table[(T_double<<4)+T_void] = T_undefined ; + // table[(T_double<<4)+T_String] = T_undefined ; + // table[(T_double<<4)+T_Object] = T_undefined ; + // table[(T_double<<4)+T_double] = T_undefined ; + // table[(T_double<<4)+T_float] = T_undefined ; + // table[(T_double<<4)+T_boolean] = T_undefined ; + // table[(T_double<<4)+T_char] = T_undefined ; + // table[(T_double<<4)+T_int] = T_undefined; + // table[(T_double<<4)+T_null] = T_undefined ; + + // table[(T_float<<4)+T_undefined] = T_undefined ; + // table[(T_float<<4)+T_byte] = T_undefined ; + // table[(T_float<<4)+T_long] = T_undefined ; + // table[(T_float<<4)+T_short] = T_undefined ; + // table[(T_float<<4)+T_void] = T_undefined ; + // table[(T_float<<4)+T_String] = T_undefined ; + // table[(T_float<<4)+T_Object] = T_undefined ; + // table[(T_float<<4)+T_double] = T_undefined ; + // table[(T_float<<4)+T_float] = T_undefined ; + // table[(T_float<<4)+T_boolean] = T_undefined ; + // table[(T_float<<4)+T_char] = T_undefined ; + // table[(T_float<<4)+T_int] = T_undefined ; + // table[(T_float<<4)+T_null] = T_undefined ; + + // table[(T_boolean<<4)+T_undefined] = T_undefined ; + // table[(T_boolean<<4)+T_byte] = T_undefined ; + // table[(T_boolean<<4)+T_long] = T_undefined ; + // table[(T_boolean<<4)+T_short] = T_undefined ; + // table[(T_boolean<<4)+T_void] = T_undefined ; + // table[(T_boolean<<4)+T_String] = T_undefined ; + // table[(T_boolean<<4)+T_Object] = T_undefined ; + // table[(T_boolean<<4)+T_double] = T_undefined ; + // table[(T_boolean<<4)+T_float] = T_undefined ; + // table[(T_boolean<<4)+T_boolean] = T_undefined ; + // table[(T_boolean<<4)+T_char] = T_undefined ; + // table[(T_boolean<<4)+T_int] = T_undefined ; + // table[(T_boolean<<4)+T_null] = T_undefined ; + + // table[(T_char<<4)+T_undefined] = T_undefined ; + table[(T_char << 4) + T_byte] = (Char2Int << 12) + (Byte2Int << 4) + + T_int; + table[(T_char << 4) + T_long] = (Char2Int << 12) + (Long2Int << 4) + + T_int; + table[(T_char << 4) + T_short] = (Char2Int << 12) + (Short2Int << 4) + + T_int; + // table[(T_char<<4)+T_void] = T_undefined ; + // table[(T_char<<4)+T_String] = T_undefined ; + // table[(T_char<<4)+T_Object] = T_undefined ; + // table[(T_char<<4)+T_double] = T_undefined ; + // table[(T_char<<4)+T_float] = T_undefined ; + // table[(T_char<<4)+T_boolean] = T_undefined ; + table[(T_char << 4) + T_char] = (Char2Int << 12) + (Char2Int << 4) + + T_int; + table[(T_char << 4) + T_int] = (Char2Int << 12) + (Int2Int << 4) + + T_int; + // table[(T_char<<4)+T_null] = T_undefined ; + + // table[(T_int<<4)+T_undefined] = T_undefined ; + table[(T_int << 4) + T_byte] = (Int2Int << 12) + (Byte2Int << 4) + + T_int; + table[(T_int << 4) + T_long] = (Int2Int << 12) + (Long2Int << 4) + + T_int; + table[(T_int << 4) + T_short] = (Int2Int << 12) + (Short2Int << 4) + + T_int; + // table[(T_int<<4)+T_void] = T_undefined ; + // table[(T_int<<4)+T_String] = T_undefined ; + // table[(T_int<<4)+T_Object] = T_undefined ; + // table[(T_int<<4)+T_double] = T_undefined ; + // table[(T_int<<4)+T_float] = T_undefined ; + // table[(T_int<<4)+T_boolean] = T_undefined ; + table[(T_int << 4) + T_char] = (Int2Int << 12) + (Char2Int << 4) + + T_int; + table[(T_int << 4) + T_int] = (Int2Int << 12) + (Int2Int << 4) + T_int; + // table[(T_int<<4)+T_null] = T_undefined ; + + // table[(T_null<<4)+T_undefined] = T_undefined ; + // table[(T_null<<4)+T_byte] = T_undefined ; + // table[(T_null<<4)+T_long] = T_undefined ; + // table[(T_null<<4)+T_short] = T_undefined ; + // table[(T_null<<4)+T_void] = T_undefined ; + // table[(T_null<<4)+T_String] = T_undefined ; + // table[(T_null<<4)+T_Object] = T_undefined ; + // table[(T_null<<4)+T_double] = T_undefined ; + // table[(T_null<<4)+T_float] = T_undefined ; + // table[(T_null<<4)+T_boolean] = T_undefined ; + // table[(T_null<<4)+T_char] = T_undefined ; + // table[(T_null<<4)+T_int] = T_undefined ; + // table[(T_null<<4)+T_null] = T_undefined ; + + return table; } - public static final int[] get_LESS(){ - - //the code is an int - // (cast) left Op (cast) rigth --> result - // 0000 0000 0000 0000 0000 - // <<16 <<12 <<8 <<4 - - int[] table = new int[16*16] ; - - // table[(T_undefined<<4)+T_undefined] = T_undefined ; - // table[(T_undefined<<4)+T_byte] = T_undefined ; - // table[(T_undefined<<4)+T_long] = T_undefined ; - // table[(T_undefined<<4)+T_short] = T_undefined ; - // table[(T_undefined<<4)+T_void] = T_undefined ; - // table[(T_undefined<<4)+T_String] = T_undefined ; - // table[(T_undefined<<4)+T_Object] = T_undefined ; - // table[(T_undefined<<4)+T_double] = T_undefined ; - // table[(T_undefined<<4)+T_float] = T_undefined ; - // table[(T_undefined<<4)+T_boolean] = T_undefined ; - // table[(T_undefined<<4)+T_char] = T_undefined ; - // table[(T_undefined<<4)+T_int] = T_undefined ; - // table[(T_undefined<<4)+T_null] = T_undefined ; - - // table[(T_byte<<4)+T_undefined] = T_undefined ; - table[(T_byte<<4)+T_byte] = (Byte2Int<<12)+(Byte2Int<<4)+T_boolean ; - table[(T_byte<<4)+T_long] = (Byte2Long<<12)+(Long2Long<<4)+T_boolean ; - table[(T_byte<<4)+T_short] = (Byte2Int<<12)+(Short2Int<<4)+T_boolean ; - // table[(T_byte<<4)+T_void] = T_undefined ; - // table[(T_byte<<4)+T_String] = T_undefined ; - // table[(T_byte<<4)+T_Object] = T_undefined ; - table[(T_byte<<4)+T_double] = (Byte2Double<<12)+(Double2Double<<4)+T_boolean ; - table[(T_byte<<4)+T_float] = (Byte2Float<<12)+(Float2Float<<4)+T_boolean; - // table[(T_byte<<4)+T_boolean] = T_undefined ; - table[(T_byte<<4)+T_char] = (Byte2Int<<12)+(Char2Int<<4)+T_boolean ; - table[(T_byte<<4)+T_int] = (Byte2Int<<12)+(Int2Int<<4)+T_boolean ; - // table[(T_byte<<4)+T_null] = T_undefined ; - - // table[(T_long<<4)+T_undefined] = T_undefined ; - table[(T_long<<4)+T_byte] = (Long2Long<<12)+(Byte2Long<<4)+T_boolean; - table[(T_long<<4)+T_long] = (Long2Long<<12)+(Long2Long<<4)+T_boolean ; - table[(T_long<<4)+T_short] = (Long2Long<<12)+(Short2Long<<4)+T_boolean ; - // table[(T_long<<4)+T_void] = T_undefined ; - // table[(T_long<<4)+T_String] = T_undefined ; - // table[(T_long<<4)+T_Object] = T_undefined ; - table[(T_long<<4)+T_double] = (Long2Double<<12)+(Double2Double<<4)+T_boolean ; - table[(T_long<<4)+T_float] = (Long2Float<<12)+(Float2Float<<4)+T_boolean ; - // table[(T_long<<4)+T_boolean] = T_undefined ; - table[(T_long<<4)+T_char] = (Long2Long<<12)+(Char2Long<<4)+T_boolean ; - table[(T_long<<4)+T_int] = (Long2Long<<12)+(Int2Long<<4)+T_boolean ; - // table[(T_long<<4)+T_null] = T_undefined ; - - // table[(T_short<<4)+T_undefined] = T_undefined ; - table[(T_short<<4)+T_byte] = (Short2Int<<12)+(Byte2Int<<4)+T_boolean ; - table[(T_short<<4)+T_long] = (Short2Long<<12)+(Long2Long<<4)+T_boolean ; - table[(T_short<<4)+T_short] = (Short2Int<<12)+(Short2Int<<4)+T_boolean ; - // table[(T_short<<4)+T_void] = T_undefined ; - // table[(T_short<<4)+T_String] = T_undefined ; - // table[(T_short<<4)+T_Object] = T_undefined ; - table[(T_short<<4)+T_double] = (Short2Double<<12)+(Double2Double<<4)+T_boolean ; - table[(T_short<<4)+T_float] = (Short2Float<<12)+(Float2Float<<4)+T_boolean ; - // table[(T_short<<4)+T_boolean] = T_undefined ; - table[(T_short<<4)+T_char] = (Short2Int<<12)+(Char2Int<<4)+T_boolean ; - table[(T_short<<4)+T_int] = (Short2Int<<12)+(Int2Int<<4)+T_boolean ; - // table[(T_short<<4)+T_null] = T_undefined ; - - // table[(T_void<<4)+T_undefined] = T_undefined ; - // table[(T_void<<4)+T_byte] = T_undefined ; - // table[(T_void<<4)+T_long] = T_undefined ; - // table[(T_void<<4)+T_short] = T_undefined ; - // table[(T_void<<4)+T_void] = T_undefined ; - // table[(T_void<<4)+T_String] = T_undefined ; - // table[(T_void<<4)+T_Object] = T_undefined ; - // table[(T_void<<4)+T_double] = T_undefined ; - // table[(T_void<<4)+T_float] = T_undefined ; - // table[(T_void<<4)+T_boolean] = T_undefined ; - // table[(T_void<<4)+T_char] = T_undefined ; - // table[(T_void<<4)+T_int] = T_undefined ; - // table[(T_void<<4)+T_null] = T_undefined ; - - // table[(T_String<<4)+T_undefined] = T_undefined ; - // table[(T_String<<4)+T_byte] = T_undefined ; - // table[(T_String<<4)+T_long] = T_undefined ; - // table[(T_String<<4)+T_short] = T_undefined ; - // table[(T_String<<4)+T_void] = T_undefined ; - // table[(T_String<<4)+T_String] = T_undefined ; - // table[(T_String<<4)+T_Object] = T_undefined ; - // table[(T_String<<4)+T_double] = T_undefined ; - // table[(T_String<<4)+T_float] = T_undefined ; - // table[(T_String<<4)+T_boolean] = T_undefined ; - // table[(T_String<<4)+T_char] = T_undefined ; - // table[(T_String<<4)+T_int] = T_undefined ; - // table[(T_String<<4)+T_null] = T_undefined ; - - // table[(T_Object<<4)+T_undefined] = T_undefined ; - // table[(T_Object<<4)+T_byte] = T_undefined ; - // table[(T_Object<<4)+T_long] = T_undefined ; - // table[(T_Object<<4)+T_short] = T_undefined ; - // table[(T_Object<<4)+T_void] = T_undefined ; - // table[(T_Object<<4)+T_String] = T_undefined ; - // table[(T_Object<<4)+T_Object] = T_undefined ; - // table[(T_Object<<4)+T_double] = T_undefined ; - // table[(T_Object<<4)+T_float] = T_undefined ; - // table[(T_Object<<4)+T_boolean] = T_undefined ; - // table[(T_Object<<4)+T_char] = T_undefined ; - // table[(T_Object<<4)+T_int] = T_undefined ; - // table[(T_Object<<4)+T_null] = T_undefined ; - - // table[(T_double<<4)+T_undefined] = T_undefined ; - table[(T_double<<4)+T_byte] = (Double2Double<<12)+(Byte2Double<<4)+T_boolean ; - table[(T_double<<4)+T_long] = (Double2Double<<12)+(Long2Double<<4)+T_boolean; - table[(T_double<<4)+T_short] = (Double2Double<<12)+(Short2Double<<4)+T_boolean ; - // table[(T_double<<4)+T_void] = T_undefined ; - // table[(T_double<<4)+T_String] = T_undefined ; - // table[(T_double<<4)+T_Object] = T_undefined ; - table[(T_double<<4)+T_double] = (Double2Double<<12)+(Double2Double<<4)+T_boolean ; - table[(T_double<<4)+T_float] = (Double2Double<<12)+(Float2Double<<4)+T_boolean ; - // table[(T_double<<4)+T_boolean] = T_undefined ; - table[(T_double<<4)+T_char] = (Double2Double<<12)+(Char2Double<<4)+T_boolean ; - table[(T_double<<4)+T_int] = (Double2Double<<12)+(Int2Double<<4)+T_boolean; - // table[(T_double<<4)+T_null] = T_undefined ; - - // table[(T_float<<4)+T_undefined] = T_undefined ; - table[(T_float<<4)+T_byte] = (Float2Float<<12)+(Byte2Float<<4)+T_boolean ; - table[(T_float<<4)+T_long] = (Float2Float<<12)+(Long2Float<<4)+T_boolean ; - table[(T_float<<4)+T_short] = (Float2Float<<12)+(Short2Float<<4)+T_boolean ; - // table[(T_float<<4)+T_void] = T_undefined ; - // table[(T_float<<4)+T_String] = T_undefined ; - // table[(T_float<<4)+T_Object] = T_undefined ; - table[(T_float<<4)+T_double] = (Float2Double<<12)+(Double2Double<<4)+T_boolean ; - table[(T_float<<4)+T_float] = (Float2Float<<12)+(Float2Float<<4)+T_boolean ; - // table[(T_float<<4)+T_boolean] = T_undefined ; - table[(T_float<<4)+T_char] = (Float2Float<<12)+(Char2Float<<4)+T_boolean ; - table[(T_float<<4)+T_int] = (Float2Float<<12)+(Int2Float<<4)+T_boolean ; - // table[(T_float<<4)+T_null] = T_undefined ; - - // table[(T_boolean<<4)+T_undefined] = T_undefined ; - // table[(T_boolean<<4)+T_byte] = T_undefined ; - // table[(T_boolean<<4)+T_long] = T_undefined ; - // table[(T_boolean<<4)+T_short] = T_undefined ; - // table[(T_boolean<<4)+T_void] = T_undefined ; - // table[(T_boolean<<4)+T_String] = T_undefined ; - // table[(T_boolean<<4)+T_Object] = T_undefined ; - // table[(T_boolean<<4)+T_double] = T_undefined ; - // table[(T_boolean<<4)+T_float] = T_undefined ; - // table[(T_boolean<<4)+T_boolean] = T_undefined ; - // table[(T_boolean<<4)+T_char] = T_undefined ; - // table[(T_boolean<<4)+T_int] = T_undefined ; - // table[(T_boolean<<4)+T_null] = T_undefined ; - - // table[(T_char<<4)+T_undefined] = T_undefined ; - table[(T_char<<4)+T_byte] = (Char2Int<<12)+(Byte2Int<<4)+T_boolean ; - table[(T_char<<4)+T_long] = (Char2Long<<12)+(Long2Long<<4)+T_boolean ; - table[(T_char<<4)+T_short] = (Char2Int<<12)+(Short2Int<<4)+T_boolean ; - // table[(T_char<<4)+T_void] = T_undefined ; - // table[(T_char<<4)+T_String] = T_undefined ; - // table[(T_char<<4)+T_Object] = T_undefined ; - table[(T_char<<4)+T_double] = (Char2Double<<12)+(Double2Double<<4)+T_boolean ; - table[(T_char<<4)+T_float] = (Char2Float<<12)+(Float2Float<<4)+T_boolean ; - // table[(T_char<<4)+T_boolean] = T_undefined ; - table[(T_char<<4)+T_char] = (Char2Int<<12)+(Char2Int<<4)+T_boolean ; - table[(T_char<<4)+T_int] = (Char2Int<<12)+(Int2Int<<4)+T_boolean ; - // table[(T_char<<4)+T_null] = T_undefined ; - - // table[(T_int<<4)+T_undefined] = T_undefined ; - table[(T_int<<4)+T_byte] = (Int2Int<<12)+(Byte2Int<<4)+T_boolean ; - table[(T_int<<4)+T_long] = (Int2Long<<12)+(Long2Long<<4)+T_boolean; - table[(T_int<<4)+T_short] = (Int2Int<<12)+(Short2Int<<4)+T_boolean ; - // table[(T_int<<4)+T_void] = T_undefined ; - // table[(T_int<<4)+T_String] = T_undefined ; - // table[(T_int<<4)+T_Object] = T_undefined ; - table[(T_int<<4)+T_double] = (Int2Double<<12)+(Double2Double<<4)+T_boolean ; - table[(T_int<<4)+T_float] = (Int2Float<<12)+(Float2Float<<4)+T_boolean ; - // table[(T_int<<4)+T_boolean] = T_undefined ; - table[(T_int<<4)+T_char] = (Int2Int<<12)+(Char2Int<<4)+T_boolean ; - table[(T_int<<4)+T_int] = (Int2Int<<12)+(Int2Int<<4)+T_boolean; - // table[(T_int<<4)+T_null] = T_undefined ; - - // table[(T_null<<4)+T_undefined] = T_undefined ; - // table[(T_null<<4)+T_byte] = T_undefined ; - // table[(T_null<<4)+T_long] = T_undefined ; - // table[(T_null<<4)+T_short] = T_undefined ; - // table[(T_null<<4)+T_void] = T_undefined ; - // table[(T_null<<4)+T_String] = T_undefined ; - // table[(T_null<<4)+T_Object] = T_undefined ; - // table[(T_null<<4)+T_double] = T_undefined ; - // table[(T_null<<4)+T_float] = T_undefined ; - // table[(T_null<<4)+T_boolean] = T_undefined ; - // table[(T_null<<4)+T_char] = T_undefined ; - // table[(T_null<<4)+T_int] = T_undefined ; - // table[(T_null<<4)+T_null] = T_undefined ; - - return table ; + public static final int[] get_LESS() { + + // the code is an int + // (cast) left Op (cast) rigth --> result + // 0000 0000 0000 0000 0000 + // <<16 <<12 <<8 <<4 + + int[] table = new int[16 * 16]; + + // table[(T_undefined<<4)+T_undefined] = T_undefined ; + // table[(T_undefined<<4)+T_byte] = T_undefined ; + // table[(T_undefined<<4)+T_long] = T_undefined ; + // table[(T_undefined<<4)+T_short] = T_undefined ; + // table[(T_undefined<<4)+T_void] = T_undefined ; + // table[(T_undefined<<4)+T_String] = T_undefined ; + // table[(T_undefined<<4)+T_Object] = T_undefined ; + // table[(T_undefined<<4)+T_double] = T_undefined ; + // table[(T_undefined<<4)+T_float] = T_undefined ; + // table[(T_undefined<<4)+T_boolean] = T_undefined ; + // table[(T_undefined<<4)+T_char] = T_undefined ; + // table[(T_undefined<<4)+T_int] = T_undefined ; + // table[(T_undefined<<4)+T_null] = T_undefined ; + + // table[(T_byte<<4)+T_undefined] = T_undefined ; + table[(T_byte << 4) + T_byte] = (Byte2Int << 12) + (Byte2Int << 4) + + T_boolean; + table[(T_byte << 4) + T_long] = (Byte2Long << 12) + (Long2Long << 4) + + T_boolean; + table[(T_byte << 4) + T_short] = (Byte2Int << 12) + (Short2Int << 4) + + T_boolean; + // table[(T_byte<<4)+T_void] = T_undefined ; + // table[(T_byte<<4)+T_String] = T_undefined ; + // table[(T_byte<<4)+T_Object] = T_undefined ; + table[(T_byte << 4) + T_double] = (Byte2Double << 12) + + (Double2Double << 4) + T_boolean; + table[(T_byte << 4) + T_float] = (Byte2Float << 12) + + (Float2Float << 4) + T_boolean; + // table[(T_byte<<4)+T_boolean] = T_undefined ; + table[(T_byte << 4) + T_char] = (Byte2Int << 12) + (Char2Int << 4) + + T_boolean; + table[(T_byte << 4) + T_int] = (Byte2Int << 12) + (Int2Int << 4) + + T_boolean; + // table[(T_byte<<4)+T_null] = T_undefined ; + + // table[(T_long<<4)+T_undefined] = T_undefined ; + table[(T_long << 4) + T_byte] = (Long2Long << 12) + (Byte2Long << 4) + + T_boolean; + table[(T_long << 4) + T_long] = (Long2Long << 12) + (Long2Long << 4) + + T_boolean; + table[(T_long << 4) + T_short] = (Long2Long << 12) + (Short2Long << 4) + + T_boolean; + // table[(T_long<<4)+T_void] = T_undefined ; + // table[(T_long<<4)+T_String] = T_undefined ; + // table[(T_long<<4)+T_Object] = T_undefined ; + table[(T_long << 4) + T_double] = (Long2Double << 12) + + (Double2Double << 4) + T_boolean; + table[(T_long << 4) + T_float] = (Long2Float << 12) + + (Float2Float << 4) + T_boolean; + // table[(T_long<<4)+T_boolean] = T_undefined ; + table[(T_long << 4) + T_char] = (Long2Long << 12) + (Char2Long << 4) + + T_boolean; + table[(T_long << 4) + T_int] = (Long2Long << 12) + (Int2Long << 4) + + T_boolean; + // table[(T_long<<4)+T_null] = T_undefined ; + + // table[(T_short<<4)+T_undefined] = T_undefined ; + table[(T_short << 4) + T_byte] = (Short2Int << 12) + (Byte2Int << 4) + + T_boolean; + table[(T_short << 4) + T_long] = (Short2Long << 12) + (Long2Long << 4) + + T_boolean; + table[(T_short << 4) + T_short] = (Short2Int << 12) + (Short2Int << 4) + + T_boolean; + // table[(T_short<<4)+T_void] = T_undefined ; + // table[(T_short<<4)+T_String] = T_undefined ; + // table[(T_short<<4)+T_Object] = T_undefined ; + table[(T_short << 4) + T_double] = (Short2Double << 12) + + (Double2Double << 4) + T_boolean; + table[(T_short << 4) + T_float] = (Short2Float << 12) + + (Float2Float << 4) + T_boolean; + // table[(T_short<<4)+T_boolean] = T_undefined ; + table[(T_short << 4) + T_char] = (Short2Int << 12) + (Char2Int << 4) + + T_boolean; + table[(T_short << 4) + T_int] = (Short2Int << 12) + (Int2Int << 4) + + T_boolean; + // table[(T_short<<4)+T_null] = T_undefined ; + + // table[(T_void<<4)+T_undefined] = T_undefined ; + // table[(T_void<<4)+T_byte] = T_undefined ; + // table[(T_void<<4)+T_long] = T_undefined ; + // table[(T_void<<4)+T_short] = T_undefined ; + // table[(T_void<<4)+T_void] = T_undefined ; + // table[(T_void<<4)+T_String] = T_undefined ; + // table[(T_void<<4)+T_Object] = T_undefined ; + // table[(T_void<<4)+T_double] = T_undefined ; + // table[(T_void<<4)+T_float] = T_undefined ; + // table[(T_void<<4)+T_boolean] = T_undefined ; + // table[(T_void<<4)+T_char] = T_undefined ; + // table[(T_void<<4)+T_int] = T_undefined ; + // table[(T_void<<4)+T_null] = T_undefined ; + + // table[(T_String<<4)+T_undefined] = T_undefined ; + // table[(T_String<<4)+T_byte] = T_undefined ; + // table[(T_String<<4)+T_long] = T_undefined ; + // table[(T_String<<4)+T_short] = T_undefined ; + // table[(T_String<<4)+T_void] = T_undefined ; + // table[(T_String<<4)+T_String] = T_undefined ; + // table[(T_String<<4)+T_Object] = T_undefined ; + // table[(T_String<<4)+T_double] = T_undefined ; + // table[(T_String<<4)+T_float] = T_undefined ; + // table[(T_String<<4)+T_boolean] = T_undefined ; + // table[(T_String<<4)+T_char] = T_undefined ; + // table[(T_String<<4)+T_int] = T_undefined ; + // table[(T_String<<4)+T_null] = T_undefined ; + + // table[(T_Object<<4)+T_undefined] = T_undefined ; + // table[(T_Object<<4)+T_byte] = T_undefined ; + // table[(T_Object<<4)+T_long] = T_undefined ; + // table[(T_Object<<4)+T_short] = T_undefined ; + // table[(T_Object<<4)+T_void] = T_undefined ; + // table[(T_Object<<4)+T_String] = T_undefined ; + // table[(T_Object<<4)+T_Object] = T_undefined ; + // table[(T_Object<<4)+T_double] = T_undefined ; + // table[(T_Object<<4)+T_float] = T_undefined ; + // table[(T_Object<<4)+T_boolean] = T_undefined ; + // table[(T_Object<<4)+T_char] = T_undefined ; + // table[(T_Object<<4)+T_int] = T_undefined ; + // table[(T_Object<<4)+T_null] = T_undefined ; + + // table[(T_double<<4)+T_undefined] = T_undefined ; + table[(T_double << 4) + T_byte] = (Double2Double << 12) + + (Byte2Double << 4) + T_boolean; + table[(T_double << 4) + T_long] = (Double2Double << 12) + + (Long2Double << 4) + T_boolean; + table[(T_double << 4) + T_short] = (Double2Double << 12) + + (Short2Double << 4) + T_boolean; + // table[(T_double<<4)+T_void] = T_undefined ; + // table[(T_double<<4)+T_String] = T_undefined ; + // table[(T_double<<4)+T_Object] = T_undefined ; + table[(T_double << 4) + T_double] = (Double2Double << 12) + + (Double2Double << 4) + T_boolean; + table[(T_double << 4) + T_float] = (Double2Double << 12) + + (Float2Double << 4) + T_boolean; + // table[(T_double<<4)+T_boolean] = T_undefined ; + table[(T_double << 4) + T_char] = (Double2Double << 12) + + (Char2Double << 4) + T_boolean; + table[(T_double << 4) + T_int] = (Double2Double << 12) + + (Int2Double << 4) + T_boolean; + // table[(T_double<<4)+T_null] = T_undefined ; + + // table[(T_float<<4)+T_undefined] = T_undefined ; + table[(T_float << 4) + T_byte] = (Float2Float << 12) + + (Byte2Float << 4) + T_boolean; + table[(T_float << 4) + T_long] = (Float2Float << 12) + + (Long2Float << 4) + T_boolean; + table[(T_float << 4) + T_short] = (Float2Float << 12) + + (Short2Float << 4) + T_boolean; + // table[(T_float<<4)+T_void] = T_undefined ; + // table[(T_float<<4)+T_String] = T_undefined ; + // table[(T_float<<4)+T_Object] = T_undefined ; + table[(T_float << 4) + T_double] = (Float2Double << 12) + + (Double2Double << 4) + T_boolean; + table[(T_float << 4) + T_float] = (Float2Float << 12) + + (Float2Float << 4) + T_boolean; + // table[(T_float<<4)+T_boolean] = T_undefined ; + table[(T_float << 4) + T_char] = (Float2Float << 12) + + (Char2Float << 4) + T_boolean; + table[(T_float << 4) + T_int] = (Float2Float << 12) + (Int2Float << 4) + + T_boolean; + // table[(T_float<<4)+T_null] = T_undefined ; + + // table[(T_boolean<<4)+T_undefined] = T_undefined ; + // table[(T_boolean<<4)+T_byte] = T_undefined ; + // table[(T_boolean<<4)+T_long] = T_undefined ; + // table[(T_boolean<<4)+T_short] = T_undefined ; + // table[(T_boolean<<4)+T_void] = T_undefined ; + // table[(T_boolean<<4)+T_String] = T_undefined ; + // table[(T_boolean<<4)+T_Object] = T_undefined ; + // table[(T_boolean<<4)+T_double] = T_undefined ; + // table[(T_boolean<<4)+T_float] = T_undefined ; + // table[(T_boolean<<4)+T_boolean] = T_undefined ; + // table[(T_boolean<<4)+T_char] = T_undefined ; + // table[(T_boolean<<4)+T_int] = T_undefined ; + // table[(T_boolean<<4)+T_null] = T_undefined ; + + // table[(T_char<<4)+T_undefined] = T_undefined ; + table[(T_char << 4) + T_byte] = (Char2Int << 12) + (Byte2Int << 4) + + T_boolean; + table[(T_char << 4) + T_long] = (Char2Long << 12) + (Long2Long << 4) + + T_boolean; + table[(T_char << 4) + T_short] = (Char2Int << 12) + (Short2Int << 4) + + T_boolean; + // table[(T_char<<4)+T_void] = T_undefined ; + // table[(T_char<<4)+T_String] = T_undefined ; + // table[(T_char<<4)+T_Object] = T_undefined ; + table[(T_char << 4) + T_double] = (Char2Double << 12) + + (Double2Double << 4) + T_boolean; + table[(T_char << 4) + T_float] = (Char2Float << 12) + + (Float2Float << 4) + T_boolean; + // table[(T_char<<4)+T_boolean] = T_undefined ; + table[(T_char << 4) + T_char] = (Char2Int << 12) + (Char2Int << 4) + + T_boolean; + table[(T_char << 4) + T_int] = (Char2Int << 12) + (Int2Int << 4) + + T_boolean; + // table[(T_char<<4)+T_null] = T_undefined ; + + // table[(T_int<<4)+T_undefined] = T_undefined ; + table[(T_int << 4) + T_byte] = (Int2Int << 12) + (Byte2Int << 4) + + T_boolean; + table[(T_int << 4) + T_long] = (Int2Long << 12) + (Long2Long << 4) + + T_boolean; + table[(T_int << 4) + T_short] = (Int2Int << 12) + (Short2Int << 4) + + T_boolean; + // table[(T_int<<4)+T_void] = T_undefined ; + // table[(T_int<<4)+T_String] = T_undefined ; + // table[(T_int<<4)+T_Object] = T_undefined ; + table[(T_int << 4) + T_double] = (Int2Double << 12) + + (Double2Double << 4) + T_boolean; + table[(T_int << 4) + T_float] = (Int2Float << 12) + (Float2Float << 4) + + T_boolean; + // table[(T_int<<4)+T_boolean] = T_undefined ; + table[(T_int << 4) + T_char] = (Int2Int << 12) + (Char2Int << 4) + + T_boolean; + table[(T_int << 4) + T_int] = (Int2Int << 12) + (Int2Int << 4) + + T_boolean; + // table[(T_int<<4)+T_null] = T_undefined ; + + // table[(T_null<<4)+T_undefined] = T_undefined ; + // table[(T_null<<4)+T_byte] = T_undefined ; + // table[(T_null<<4)+T_long] = T_undefined ; + // table[(T_null<<4)+T_short] = T_undefined ; + // table[(T_null<<4)+T_void] = T_undefined ; + // table[(T_null<<4)+T_String] = T_undefined ; + // table[(T_null<<4)+T_Object] = T_undefined ; + // table[(T_null<<4)+T_double] = T_undefined ; + // table[(T_null<<4)+T_float] = T_undefined ; + // table[(T_null<<4)+T_boolean] = T_undefined ; + // table[(T_null<<4)+T_char] = T_undefined ; + // table[(T_null<<4)+T_int] = T_undefined ; + // table[(T_null<<4)+T_null] = T_undefined ; + + return table; } - public static final int[] get_LESS_EQUAL(){ - - //the code is an int - // (cast) left Op (cast) rigth --> result - // 0000 0000 0000 0000 0000 - // <<16 <<12 <<8 <<4 - - // int[] table = new int[16*16] ; + public static final int[] get_LESS_EQUAL() { + + // the code is an int + // (cast) left Op (cast) rigth --> result + // 0000 0000 0000 0000 0000 + // <<16 <<12 <<8 <<4 + + // int[] table = new int[16*16] ; return get_LESS(); } - public static final int[] get_MINUS(){ - - //the code is an int - // (cast) left Op (cast) rigth --> result - // 0000 0000 0000 0000 0000 - // <<16 <<12 <<8 <<4 - - int[] table = new int[16*16] ; - + public static final int[] get_MINUS() { + + // the code is an int + // (cast) left Op (cast) rigth --> result + // 0000 0000 0000 0000 0000 + // <<16 <<12 <<8 <<4 + + int[] table = new int[16 * 16]; + table = (int[]) get_PLUS().clone(); - // customization - table[(T_String<<4)+T_byte] = T_undefined ; - table[(T_String<<4)+T_long] = T_undefined ; - table[(T_String<<4)+T_short] = T_undefined ; - table[(T_String<<4)+T_void] = T_undefined ; - table[(T_String<<4)+T_String] = T_undefined ; - table[(T_String<<4)+T_Object] = T_undefined ; - table[(T_String<<4)+T_double] = T_undefined ; - table[(T_String<<4)+T_float] = T_undefined ; - table[(T_String<<4)+T_boolean] = T_undefined ; - table[(T_String<<4)+T_char] = T_undefined ; - table[(T_String<<4)+T_int] = T_undefined ; - table[(T_String<<4)+T_null] = T_undefined ; - - table[(T_byte<<4) +T_String] = T_undefined ; - table[(T_long<<4) +T_String] = T_undefined ; - table[(T_short<<4) +T_String] = T_undefined ; - table[(T_void<<4) +T_String] = T_undefined ; - table[(T_Object<<4) +T_String] = T_undefined ; - table[(T_double<<4) +T_String] = T_undefined ; - table[(T_float<<4) +T_String] = T_undefined ; - table[(T_boolean<<4)+T_String] = T_undefined ; - table[(T_char<<4) +T_String] = T_undefined ; - table[(T_int<<4) +T_String] = T_undefined ; - table[(T_null<<4) +T_String] = T_undefined ; - - table[(T_null<<4) +T_null] = T_undefined ; - - return table ; + // customization + table[(T_String << 4) + T_byte] = T_undefined; + table[(T_String << 4) + T_long] = T_undefined; + table[(T_String << 4) + T_short] = T_undefined; + table[(T_String << 4) + T_void] = T_undefined; + table[(T_String << 4) + T_String] = T_undefined; + table[(T_String << 4) + T_Object] = T_undefined; + table[(T_String << 4) + T_double] = T_undefined; + table[(T_String << 4) + T_float] = T_undefined; + table[(T_String << 4) + T_boolean] = T_undefined; + table[(T_String << 4) + T_char] = T_undefined; + table[(T_String << 4) + T_int] = T_undefined; + table[(T_String << 4) + T_null] = T_undefined; + + table[(T_byte << 4) + T_String] = T_undefined; + table[(T_long << 4) + T_String] = T_undefined; + table[(T_short << 4) + T_String] = T_undefined; + table[(T_void << 4) + T_String] = T_undefined; + table[(T_Object << 4) + T_String] = T_undefined; + table[(T_double << 4) + T_String] = T_undefined; + table[(T_float << 4) + T_String] = T_undefined; + table[(T_boolean << 4) + T_String] = T_undefined; + table[(T_char << 4) + T_String] = T_undefined; + table[(T_int << 4) + T_String] = T_undefined; + table[(T_null << 4) + T_String] = T_undefined; + + table[(T_null << 4) + T_null] = T_undefined; + + return table; } - public static final int[] get_MULTIPLY(){ - - //the code is an int - // (cast) left Op (cast) rigth --> result - // 0000 0000 0000 0000 0000 - // <<16 <<12 <<8 <<4 - - // int[] table = new int[16*16] ; + public static final int[] get_MULTIPLY() { + + // the code is an int + // (cast) left Op (cast) rigth --> result + // 0000 0000 0000 0000 0000 + // <<16 <<12 <<8 <<4 + + // int[] table = new int[16*16] ; return get_MINUS(); } - public static final int[] get_OR(){ - - //the code is an int - // (cast) left Op (cast) rigth --> result - // 0000 0000 0000 0000 0000 - // <<16 <<12 <<8 <<4 - - - // int[] table = new int[16*16] ; - return get_AND() ; + public static final int[] get_OR() { + + // the code is an int + // (cast) left Op (cast) rigth --> result + // 0000 0000 0000 0000 0000 + // <<16 <<12 <<8 <<4 + + // int[] table = new int[16*16] ; + return get_AND(); } - public static final int[] get_OR_OR(){ - - //the code is an int - // (cast) left Op (cast) rigth --> result - // 0000 0000 0000 0000 0000 - // <<16 <<12 <<8 <<4 - - // int[] table = new int[16*16] ; - return get_AND_AND() ; + public static final int[] get_OR_OR() { + + // the code is an int + // (cast) left Op (cast) rigth --> result + // 0000 0000 0000 0000 0000 + // <<16 <<12 <<8 <<4 + + // int[] table = new int[16*16] ; + return get_AND_AND(); } - public static final int[] get_PLUS(){ - - //the code is an int - // (cast) left Op (cast) rigth --> result - // 0000 0000 0000 0000 0000 - // <<16 <<12 <<8 <<4 - - int[] table = new int[16*16] ; - - // table[(T_undefined<<4)+T_undefined] = T_undefined ; - // table[(T_undefined<<4)+T_byte] = T_undefined ; - // table[(T_undefined<<4)+T_long] = T_undefined ; - // table[(T_undefined<<4)+T_short] = T_undefined ; - // table[(T_undefined<<4)+T_void] = T_undefined ; - // table[(T_undefined<<4)+T_String] = T_undefined ; - // table[(T_undefined<<4)+T_Object] = T_undefined ; - // table[(T_undefined<<4)+T_double] = T_undefined ; - // table[(T_undefined<<4)+T_float] = T_undefined ; - // table[(T_undefined<<4)+T_boolean] = T_undefined ; - // table[(T_undefined<<4)+T_char] = T_undefined ; - // table[(T_undefined<<4)+T_int] = T_undefined ; - // table[(T_undefined<<4)+T_null] = T_undefined ; - - // table[(T_byte<<4)+T_undefined] = T_undefined ; - table[(T_byte<<4)+T_byte] = (Byte2Int<<12)+(Byte2Int<<4)+T_int ; - table[(T_byte<<4)+T_long] = (Byte2Long<<12)+(Long2Long<<4)+T_long ; - table[(T_byte<<4)+T_short] = (Byte2Int<<12)+(Short2Int<<4)+T_int ; - // table[(T_byte<<4)+T_void] = T_undefined ; - table[(T_byte<<4)+T_String] = (Byte2Byte<<12)+(String2String<<4)+T_String ; - // table[(T_byte<<4)+T_Object] = T_undefined ; - table[(T_byte<<4)+T_double] = (Byte2Double<<12)+(Double2Double<<4)+T_double ; - table[(T_byte<<4)+T_float] = (Byte2Float<<12)+(Float2Float<<4)+T_float; - // table[(T_byte<<4)+T_boolean] = T_undefined ; - table[(T_byte<<4)+T_char] = (Byte2Int<<12)+(Char2Int<<4)+T_int ; - table[(T_byte<<4)+T_int] = (Byte2Int<<12)+(Int2Int<<4)+T_int ; - // table[(T_byte<<4)+T_null] = T_undefined ; - - // table[(T_long<<4)+T_undefined] = T_undefined ; - table[(T_long<<4)+T_byte] = (Long2Long<<12)+(Byte2Long<<4)+T_long; - table[(T_long<<4)+T_long] = (Long2Long<<12)+(Long2Long<<4)+T_long ; - table[(T_long<<4)+T_short] = (Long2Long<<12)+(Short2Long<<4)+T_long ; - // table[(T_long<<4)+T_void] = T_undefined ; - table[(T_long<<4)+T_String] = (Long2Long<<12)+(String2String<<4)+T_String ; - // table[(T_long<<4)+T_Object] = T_undefined ; - table[(T_long<<4)+T_double] = (Long2Double<<12)+(Double2Double<<4)+T_double ; - table[(T_long<<4)+T_float] = (Long2Float<<12)+(Float2Float<<4)+T_float ; - // table[(T_long<<4)+T_boolean] = T_undefined ; - table[(T_long<<4)+T_char] = (Long2Long<<12)+(Char2Long<<4)+T_long ; - table[(T_long<<4)+T_int] = (Long2Long<<12)+(Int2Long<<4)+T_long ; ; - // table[(T_long<<4)+T_null] = T_undefined ; - - // table[(T_short<<4)+T_undefined] = T_undefined ; - table[(T_short<<4)+T_byte] = (Short2Int<<12)+(Byte2Int<<4)+T_int ; - table[(T_short<<4)+T_long] = (Short2Long<<12)+(Long2Long<<4)+T_long ; - table[(T_short<<4)+T_short] = (Short2Int<<12)+(Short2Int<<4)+T_int ; - // table[(T_short<<4)+T_void] = T_undefined ; - table[(T_short<<4)+T_String] = (Short2Short<<12)+(String2String<<4)+T_String ; - // table[(T_short<<4)+T_Object] = T_undefined ; - table[(T_short<<4)+T_double] = (Short2Double<<12)+(Double2Double<<4)+T_double ; - table[(T_short<<4)+T_float] = (Short2Float<<12)+(Float2Float<<4)+T_float ; - // table[(T_short<<4)+T_boolean] = T_undefined ; - table[(T_short<<4)+T_char] = (Short2Int<<12)+(Char2Int<<4)+T_int ; - table[(T_short<<4)+T_int] = (Short2Int<<12)+(Int2Int<<4)+T_int ; - // table[(T_short<<4)+T_null] = T_undefined ; - - // table[(T_void<<4)+T_undefined] = T_undefined ; - // table[(T_void<<4)+T_byte] = T_undefined ; - // table[(T_void<<4)+T_long] = T_undefined ; - // table[(T_void<<4)+T_short] = T_undefined ; - // table[(T_void<<4)+T_void] = T_undefined ; - // table[(T_void<<4)+T_String] = T_undefined ; - // table[(T_void<<4)+T_Object] = T_undefined ; - // table[(T_void<<4)+T_double] = T_undefined ; - // table[(T_void<<4)+T_float] = T_undefined ; - // table[(T_void<<4)+T_boolean] = T_undefined ; - // table[(T_void<<4)+T_char] = T_undefined ; - // table[(T_void<<4)+T_int] = T_undefined ; - // table[(T_void<<4)+T_null] = T_undefined ; - - // table[(T_String<<4)+T_undefined] = T_undefined ; - table[(T_String<<4)+T_byte] = (String2String<<12)+(Byte2Byte<<4)+T_String ; - table[(T_String<<4)+T_long] = (String2String<<12)+(Long2Long<<4)+T_String ; - table[(T_String<<4)+T_short] = (String2String<<12)+(Short2Short<<4)+T_String ; - // table[(T_String<<4)+T_void] = T_undefined ; - table[(T_String<<4)+T_String] = (String2String<<12)+(String2String<<4)+T_String ; - table[(T_String<<4)+T_Object] = (String2String<<12)+(Object2Object<<4)+T_String ; - table[(T_String<<4)+T_double] = (String2String<<12)+(Double2Double<<4)+T_String ; - table[(T_String<<4)+T_float] = (String2String<<12)+(Float2Float<<4)+T_String ; - table[(T_String<<4)+T_boolean] = (String2String<<12)+(Boolean2Boolean<<4)+T_String ; - table[(T_String<<4)+T_char] = (String2String<<12)+(Char2Char<<4)+T_String ; - table[(T_String<<4)+T_int] = (String2String<<12)+(Int2Int<<4)+T_String ; - table[(T_String<<4)+T_null] = (String2String<<12)+(T_null<<8)+(T_null<<4)+T_String ; - - // table[(T_Object<<4)+T_undefined] = T_undefined ; - // table[(T_Object<<4)+T_byte] = T_undefined ; - // table[(T_Object<<4)+T_long] = T_undefined ; - // table[(T_Object<<4)+T_short] = T_undefined ; - // table[(T_Object<<4)+T_void] = T_undefined ; - table[(T_Object<<4)+T_String] = (Object2Object<<12)+(String2String<<4)+T_String ; - // table[(T_Object<<4)+T_Object] = T_undefined ; - // table[(T_Object<<4)+T_double] = T_undefined ; - // table[(T_Object<<4)+T_float] = T_undefined ; - // table[(T_Object<<4)+T_boolean] = T_undefined ; - // table[(T_Object<<4)+T_char] = T_undefined ; - // table[(T_Object<<4)+T_int] = T_undefined ; - // table[(T_Object<<4)+T_null] = T_undefined ; - - // table[(T_double<<4)+T_undefined] = T_undefined ; - table[(T_double<<4)+T_byte] = (Double2Double<<12)+(Byte2Double<<4)+T_double ; - table[(T_double<<4)+T_long] = (Double2Double<<12)+(Long2Double<<4)+T_double ; - table[(T_double<<4)+T_short] = (Double2Double<<12)+(Short2Double<<4)+T_double ; ; - // table[(T_double<<4)+T_void] = T_undefined ; - table[(T_double<<4)+T_String] = (Double2Double<<12)+(String2String<<4)+T_String ; - // table[(T_double<<4)+T_Object] = T_undefined ; - table[(T_double<<4)+T_double] = (Double2Double<<12)+(Double2Double<<4)+T_double ; - table[(T_double<<4)+T_float] = (Double2Double<<12)+(Float2Double<<4)+T_double ; ; - // table[(T_double<<4)+T_boolean] = T_undefined ; - table[(T_double<<4)+T_char] = (Double2Double<<12)+(Char2Double<<4)+T_double ; ; - table[(T_double<<4)+T_int] = (Double2Double<<12)+(Int2Double<<4)+T_double ; ; - // table[(T_double<<4)+T_null] = T_undefined ; - - // table[(T_float<<4)+T_undefined] = T_undefined ; - table[(T_float<<4)+T_byte] = (Float2Float<<12)+(Byte2Float<<4)+T_float ; - table[(T_float<<4)+T_long] = (Float2Float<<12)+(Long2Float<<4)+T_float ; - table[(T_float<<4)+T_short] = (Float2Float<<12)+(Short2Float<<4)+T_float ; - // table[(T_float<<4)+T_void] = T_undefined ; - table[(T_float<<4)+T_String] = (Float2Float<<12)+(String2String<<4)+T_String ; - // table[(T_float<<4)+T_Object] = T_undefined ; - table[(T_float<<4)+T_double] = (Float2Double<<12)+(Double2Double<<4)+T_double ; - table[(T_float<<4)+T_float] = (Float2Float<<12)+(Float2Float<<4)+T_float ; - // table[(T_float<<4)+T_boolean] = T_undefined ; - table[(T_float<<4)+T_char] = (Float2Float<<12)+(Char2Float<<4)+T_float ; - table[(T_float<<4)+T_int] = (Float2Float<<12)+(Int2Float<<4)+T_float ; - // table[(T_float<<4)+T_null] = T_undefined ; - - // table[(T_boolean<<4)+T_undefined] = T_undefined ; - // table[(T_boolean<<4)+T_byte] = T_undefined ; - // table[(T_boolean<<4)+T_long] = T_undefined ; - // table[(T_boolean<<4)+T_short] = T_undefined ; - // table[(T_boolean<<4)+T_void] = T_undefined ; - table[(T_boolean<<4)+T_String] = (Boolean2Boolean<<12)+(String2String<<4)+T_String ; - // table[(T_boolean<<4)+T_Object] = T_undefined ; - // table[(T_boolean<<4)+T_double] = T_undefined ; - // table[(T_boolean<<4)+T_float] = T_undefined ; - // table[(T_boolean<<4)+T_boolean] = T_undefined ; - // table[(T_boolean<<4)+T_char] = T_undefined ; - // table[(T_boolean<<4)+T_int] = T_undefined ; - // table[(T_boolean<<4)+T_null] = T_undefined ; - - // table[(T_char<<4)+T_undefined] = T_undefined ; - table[(T_char<<4)+T_byte] = (Char2Int<<12)+(Byte2Int<<4)+T_int ; - table[(T_char<<4)+T_long] = (Char2Long<<12)+(Long2Long<<4)+T_long ; - table[(T_char<<4)+T_short] = (Char2Int<<12)+(Short2Int<<4)+T_int ; - // table[(T_char<<4)+T_void] = T_undefined ; - table[(T_char<<4)+T_String] = (Char2Char<<12)+(String2String<<4)+T_String ; - // table[(T_char<<4)+T_Object] = T_undefined ; - table[(T_char<<4)+T_double] = (Char2Double<<12)+(Double2Double<<4)+T_double ; - table[(T_char<<4)+T_float] = (Char2Float<<12)+(Float2Float<<4)+T_float ; - // table[(T_char<<4)+T_boolean] = T_undefined ; - table[(T_char<<4)+T_char] = (Char2Int<<12)+(Char2Int<<4)+T_int ; ; - table[(T_char<<4)+T_int] = (Char2Int<<12)+(Int2Int<<4)+T_int ; - // table[(T_char<<4)+T_null] = T_undefined ; - - // table[(T_int<<4)+T_undefined] = T_undefined ; - table[(T_int<<4)+T_byte] = (Int2Int<<12)+(Byte2Int<<4)+T_int ; - table[(T_int<<4)+T_long] = (Int2Long<<12)+(Long2Long<<4)+T_long ; - table[(T_int<<4)+T_short] = (Int2Int<<12)+(Short2Int<<4)+T_int ; - // table[(T_int<<4)+T_void] = T_undefined ; - table[(T_int<<4)+T_String] = (Int2Int<<12)+(String2String<<4)+T_String ; - // table[(T_int<<4)+T_Object] = T_undefined ; - table[(T_int<<4)+T_double] = (Int2Double<<12)+(Double2Double<<4)+T_double ; - table[(T_int<<4)+T_float] = (Int2Float<<12)+(Float2Float<<4)+T_float ; - // table[(T_int<<4)+T_boolean] = T_undefined ; - table[(T_int<<4)+T_char] = (Int2Int<<12)+(Char2Int<<4)+T_int ; - table[(T_int<<4)+T_int] = (Int2Int<<12)+(Int2Int<<4)+T_int ; - // table[(T_int<<4)+T_null] = T_undefined ; - - // table[(T_null<<4)+T_undefined] = T_undefined ; - // table[(T_null<<4)+T_byte] = T_undefined ; - // table[(T_null<<4)+T_long] = T_undefined ; - // table[(T_null<<4)+T_short] = T_undefined ; - // table[(T_null<<4)+T_void] = T_undefined ; - table[(T_null<<4)+T_String] = (T_null<<16)+(T_null<<12)+(String2String<<4)+T_String ; - // table[(T_null<<4)+T_Object] = T_undefined ; - // table[(T_null<<4)+T_double] = T_undefined ; - // table[(T_null<<4)+T_float] = T_undefined ; - // table[(T_null<<4)+T_boolean] = T_undefined ; - // table[(T_null<<4)+T_char] = T_undefined ; - // table[(T_null<<4)+T_int] = T_undefined ; - // table[(T_null<<4)+T_null] = (Null2String<<12)+(Null2String<<4)+T_String ;; - - return table ; + public static final int[] get_PLUS() { + + // the code is an int + // (cast) left Op (cast) rigth --> result + // 0000 0000 0000 0000 0000 + // <<16 <<12 <<8 <<4 + + int[] table = new int[16 * 16]; + + // table[(T_undefined<<4)+T_undefined] = T_undefined ; + // table[(T_undefined<<4)+T_byte] = T_undefined ; + // table[(T_undefined<<4)+T_long] = T_undefined ; + // table[(T_undefined<<4)+T_short] = T_undefined ; + // table[(T_undefined<<4)+T_void] = T_undefined ; + // table[(T_undefined<<4)+T_String] = T_undefined ; + // table[(T_undefined<<4)+T_Object] = T_undefined ; + // table[(T_undefined<<4)+T_double] = T_undefined ; + // table[(T_undefined<<4)+T_float] = T_undefined ; + // table[(T_undefined<<4)+T_boolean] = T_undefined ; + // table[(T_undefined<<4)+T_char] = T_undefined ; + // table[(T_undefined<<4)+T_int] = T_undefined ; + // table[(T_undefined<<4)+T_null] = T_undefined ; + + // table[(T_byte<<4)+T_undefined] = T_undefined ; + table[(T_byte << 4) + T_byte] = (Byte2Int << 12) + (Byte2Int << 4) + + T_int; + table[(T_byte << 4) + T_long] = (Byte2Long << 12) + (Long2Long << 4) + + T_long; + table[(T_byte << 4) + T_short] = (Byte2Int << 12) + (Short2Int << 4) + + T_int; + // table[(T_byte<<4)+T_void] = T_undefined ; + table[(T_byte << 4) + T_String] = (Byte2Byte << 12) + + (String2String << 4) + T_String; + // table[(T_byte<<4)+T_Object] = T_undefined ; + table[(T_byte << 4) + T_double] = (Byte2Double << 12) + + (Double2Double << 4) + T_double; + table[(T_byte << 4) + T_float] = (Byte2Float << 12) + + (Float2Float << 4) + T_float; + // table[(T_byte<<4)+T_boolean] = T_undefined ; + table[(T_byte << 4) + T_char] = (Byte2Int << 12) + (Char2Int << 4) + + T_int; + table[(T_byte << 4) + T_int] = (Byte2Int << 12) + (Int2Int << 4) + + T_int; + // table[(T_byte<<4)+T_null] = T_undefined ; + + // table[(T_long<<4)+T_undefined] = T_undefined ; + table[(T_long << 4) + T_byte] = (Long2Long << 12) + (Byte2Long << 4) + + T_long; + table[(T_long << 4) + T_long] = (Long2Long << 12) + (Long2Long << 4) + + T_long; + table[(T_long << 4) + T_short] = (Long2Long << 12) + (Short2Long << 4) + + T_long; + // table[(T_long<<4)+T_void] = T_undefined ; + table[(T_long << 4) + T_String] = (Long2Long << 12) + + (String2String << 4) + T_String; + // table[(T_long<<4)+T_Object] = T_undefined ; + table[(T_long << 4) + T_double] = (Long2Double << 12) + + (Double2Double << 4) + T_double; + table[(T_long << 4) + T_float] = (Long2Float << 12) + + (Float2Float << 4) + T_float; + // table[(T_long<<4)+T_boolean] = T_undefined ; + table[(T_long << 4) + T_char] = (Long2Long << 12) + (Char2Long << 4) + + T_long; + table[(T_long << 4) + T_int] = (Long2Long << 12) + (Int2Long << 4) + + T_long; + ; + // table[(T_long<<4)+T_null] = T_undefined ; + + // table[(T_short<<4)+T_undefined] = T_undefined ; + table[(T_short << 4) + T_byte] = (Short2Int << 12) + (Byte2Int << 4) + + T_int; + table[(T_short << 4) + T_long] = (Short2Long << 12) + (Long2Long << 4) + + T_long; + table[(T_short << 4) + T_short] = (Short2Int << 12) + (Short2Int << 4) + + T_int; + // table[(T_short<<4)+T_void] = T_undefined ; + table[(T_short << 4) + T_String] = (Short2Short << 12) + + (String2String << 4) + T_String; + // table[(T_short<<4)+T_Object] = T_undefined ; + table[(T_short << 4) + T_double] = (Short2Double << 12) + + (Double2Double << 4) + T_double; + table[(T_short << 4) + T_float] = (Short2Float << 12) + + (Float2Float << 4) + T_float; + // table[(T_short<<4)+T_boolean] = T_undefined ; + table[(T_short << 4) + T_char] = (Short2Int << 12) + (Char2Int << 4) + + T_int; + table[(T_short << 4) + T_int] = (Short2Int << 12) + (Int2Int << 4) + + T_int; + // table[(T_short<<4)+T_null] = T_undefined ; + + // table[(T_void<<4)+T_undefined] = T_undefined ; + // table[(T_void<<4)+T_byte] = T_undefined ; + // table[(T_void<<4)+T_long] = T_undefined ; + // table[(T_void<<4)+T_short] = T_undefined ; + // table[(T_void<<4)+T_void] = T_undefined ; + // table[(T_void<<4)+T_String] = T_undefined ; + // table[(T_void<<4)+T_Object] = T_undefined ; + // table[(T_void<<4)+T_double] = T_undefined ; + // table[(T_void<<4)+T_float] = T_undefined ; + // table[(T_void<<4)+T_boolean] = T_undefined ; + // table[(T_void<<4)+T_char] = T_undefined ; + // table[(T_void<<4)+T_int] = T_undefined ; + // table[(T_void<<4)+T_null] = T_undefined ; + + // table[(T_String<<4)+T_undefined] = T_undefined ; + table[(T_String << 4) + T_byte] = (String2String << 12) + + (Byte2Byte << 4) + T_String; + table[(T_String << 4) + T_long] = (String2String << 12) + + (Long2Long << 4) + T_String; + table[(T_String << 4) + T_short] = (String2String << 12) + + (Short2Short << 4) + T_String; + // table[(T_String<<4)+T_void] = T_undefined ; + table[(T_String << 4) + T_String] = (String2String << 12) + + (String2String << 4) + T_String; + table[(T_String << 4) + T_Object] = (String2String << 12) + + (Object2Object << 4) + T_String; + table[(T_String << 4) + T_double] = (String2String << 12) + + (Double2Double << 4) + T_String; + table[(T_String << 4) + T_float] = (String2String << 12) + + (Float2Float << 4) + T_String; + table[(T_String << 4) + T_boolean] = (String2String << 12) + + (Boolean2Boolean << 4) + T_String; + table[(T_String << 4) + T_char] = (String2String << 12) + + (Char2Char << 4) + T_String; + table[(T_String << 4) + T_int] = (String2String << 12) + (Int2Int << 4) + + T_String; + table[(T_String << 4) + T_null] = (String2String << 12) + (T_null << 8) + + (T_null << 4) + T_String; + + // table[(T_Object<<4)+T_undefined] = T_undefined ; + // table[(T_Object<<4)+T_byte] = T_undefined ; + // table[(T_Object<<4)+T_long] = T_undefined ; + // table[(T_Object<<4)+T_short] = T_undefined ; + // table[(T_Object<<4)+T_void] = T_undefined ; + table[(T_Object << 4) + T_String] = (Object2Object << 12) + + (String2String << 4) + T_String; + // table[(T_Object<<4)+T_Object] = T_undefined ; + // table[(T_Object<<4)+T_double] = T_undefined ; + // table[(T_Object<<4)+T_float] = T_undefined ; + // table[(T_Object<<4)+T_boolean] = T_undefined ; + // table[(T_Object<<4)+T_char] = T_undefined ; + // table[(T_Object<<4)+T_int] = T_undefined ; + // table[(T_Object<<4)+T_null] = T_undefined ; + + // table[(T_double<<4)+T_undefined] = T_undefined ; + table[(T_double << 4) + T_byte] = (Double2Double << 12) + + (Byte2Double << 4) + T_double; + table[(T_double << 4) + T_long] = (Double2Double << 12) + + (Long2Double << 4) + T_double; + table[(T_double << 4) + T_short] = (Double2Double << 12) + + (Short2Double << 4) + T_double; + ; + // table[(T_double<<4)+T_void] = T_undefined ; + table[(T_double << 4) + T_String] = (Double2Double << 12) + + (String2String << 4) + T_String; + // table[(T_double<<4)+T_Object] = T_undefined ; + table[(T_double << 4) + T_double] = (Double2Double << 12) + + (Double2Double << 4) + T_double; + table[(T_double << 4) + T_float] = (Double2Double << 12) + + (Float2Double << 4) + T_double; + ; + // table[(T_double<<4)+T_boolean] = T_undefined ; + table[(T_double << 4) + T_char] = (Double2Double << 12) + + (Char2Double << 4) + T_double; + ; + table[(T_double << 4) + T_int] = (Double2Double << 12) + + (Int2Double << 4) + T_double; + ; + // table[(T_double<<4)+T_null] = T_undefined ; + + // table[(T_float<<4)+T_undefined] = T_undefined ; + table[(T_float << 4) + T_byte] = (Float2Float << 12) + + (Byte2Float << 4) + T_float; + table[(T_float << 4) + T_long] = (Float2Float << 12) + + (Long2Float << 4) + T_float; + table[(T_float << 4) + T_short] = (Float2Float << 12) + + (Short2Float << 4) + T_float; + // table[(T_float<<4)+T_void] = T_undefined ; + table[(T_float << 4) + T_String] = (Float2Float << 12) + + (String2String << 4) + T_String; + // table[(T_float<<4)+T_Object] = T_undefined ; + table[(T_float << 4) + T_double] = (Float2Double << 12) + + (Double2Double << 4) + T_double; + table[(T_float << 4) + T_float] = (Float2Float << 12) + + (Float2Float << 4) + T_float; + // table[(T_float<<4)+T_boolean] = T_undefined ; + table[(T_float << 4) + T_char] = (Float2Float << 12) + + (Char2Float << 4) + T_float; + table[(T_float << 4) + T_int] = (Float2Float << 12) + (Int2Float << 4) + + T_float; + // table[(T_float<<4)+T_null] = T_undefined ; + + // table[(T_boolean<<4)+T_undefined] = T_undefined ; + // table[(T_boolean<<4)+T_byte] = T_undefined ; + // table[(T_boolean<<4)+T_long] = T_undefined ; + // table[(T_boolean<<4)+T_short] = T_undefined ; + // table[(T_boolean<<4)+T_void] = T_undefined ; + table[(T_boolean << 4) + T_String] = (Boolean2Boolean << 12) + + (String2String << 4) + T_String; + // table[(T_boolean<<4)+T_Object] = T_undefined ; + // table[(T_boolean<<4)+T_double] = T_undefined ; + // table[(T_boolean<<4)+T_float] = T_undefined ; + // table[(T_boolean<<4)+T_boolean] = T_undefined ; + // table[(T_boolean<<4)+T_char] = T_undefined ; + // table[(T_boolean<<4)+T_int] = T_undefined ; + // table[(T_boolean<<4)+T_null] = T_undefined ; + + // table[(T_char<<4)+T_undefined] = T_undefined ; + table[(T_char << 4) + T_byte] = (Char2Int << 12) + (Byte2Int << 4) + + T_int; + table[(T_char << 4) + T_long] = (Char2Long << 12) + (Long2Long << 4) + + T_long; + table[(T_char << 4) + T_short] = (Char2Int << 12) + (Short2Int << 4) + + T_int; + // table[(T_char<<4)+T_void] = T_undefined ; + table[(T_char << 4) + T_String] = (Char2Char << 12) + + (String2String << 4) + T_String; + // table[(T_char<<4)+T_Object] = T_undefined ; + table[(T_char << 4) + T_double] = (Char2Double << 12) + + (Double2Double << 4) + T_double; + table[(T_char << 4) + T_float] = (Char2Float << 12) + + (Float2Float << 4) + T_float; + // table[(T_char<<4)+T_boolean] = T_undefined ; + table[(T_char << 4) + T_char] = (Char2Int << 12) + (Char2Int << 4) + + T_int; + ; + table[(T_char << 4) + T_int] = (Char2Int << 12) + (Int2Int << 4) + + T_int; + // table[(T_char<<4)+T_null] = T_undefined ; + + // table[(T_int<<4)+T_undefined] = T_undefined ; + table[(T_int << 4) + T_byte] = (Int2Int << 12) + (Byte2Int << 4) + + T_int; + table[(T_int << 4) + T_long] = (Int2Long << 12) + (Long2Long << 4) + + T_long; + table[(T_int << 4) + T_short] = (Int2Int << 12) + (Short2Int << 4) + + T_int; + // table[(T_int<<4)+T_void] = T_undefined ; + table[(T_int << 4) + T_String] = (Int2Int << 12) + (String2String << 4) + + T_String; + // table[(T_int<<4)+T_Object] = T_undefined ; + table[(T_int << 4) + T_double] = (Int2Double << 12) + + (Double2Double << 4) + T_double; + table[(T_int << 4) + T_float] = (Int2Float << 12) + (Float2Float << 4) + + T_float; + // table[(T_int<<4)+T_boolean] = T_undefined ; + table[(T_int << 4) + T_char] = (Int2Int << 12) + (Char2Int << 4) + + T_int; + table[(T_int << 4) + T_int] = (Int2Int << 12) + (Int2Int << 4) + T_int; + // table[(T_int<<4)+T_null] = T_undefined ; + + // table[(T_null<<4)+T_undefined] = T_undefined ; + // table[(T_null<<4)+T_byte] = T_undefined ; + // table[(T_null<<4)+T_long] = T_undefined ; + // table[(T_null<<4)+T_short] = T_undefined ; + // table[(T_null<<4)+T_void] = T_undefined ; + table[(T_null << 4) + T_String] = (T_null << 16) + (T_null << 12) + + (String2String << 4) + T_String; + // table[(T_null<<4)+T_Object] = T_undefined ; + // table[(T_null<<4)+T_double] = T_undefined ; + // table[(T_null<<4)+T_float] = T_undefined ; + // table[(T_null<<4)+T_boolean] = T_undefined ; + // table[(T_null<<4)+T_char] = T_undefined ; + // table[(T_null<<4)+T_int] = T_undefined ; + // table[(T_null<<4)+T_null] = + // (Null2String<<12)+(Null2String<<4)+T_String ;; + + return table; } - public static final int[] get_REMAINDER(){ - - //the code is an int - // (cast) left Op (cast) rigth --> result - // 0000 0000 0000 0000 0000 - // <<16 <<12 <<8 <<4 - - // int[] table = new int[16*16] ; + public static final int[] get_REMAINDER() { + + // the code is an int + // (cast) left Op (cast) rigth --> result + // 0000 0000 0000 0000 0000 + // <<16 <<12 <<8 <<4 + + // int[] table = new int[16*16] ; return get_MINUS(); } - public static final int[] get_RIGHT_SHIFT(){ - - //the code is an int - // (cast) left Op (cast) rigth --> result - // 0000 0000 0000 0000 0000 - // <<16 <<12 <<8 <<4 - - // int[] table = new int[16*16] ; + public static final int[] get_RIGHT_SHIFT() { + + // the code is an int + // (cast) left Op (cast) rigth --> result + // 0000 0000 0000 0000 0000 + // <<16 <<12 <<8 <<4 + + // int[] table = new int[16*16] ; return get_LEFT_SHIFT(); } - public static final int[] get_UNSIGNED_RIGHT_SHIFT(){ - - //the code is an int - // (cast) left Op (cast) rigth --> result - // 0000 0000 0000 0000 0000 - // <<16 <<12 <<8 <<4 - - // int[] table = new int[16*16] ; + public static final int[] get_UNSIGNED_RIGHT_SHIFT() { + + // the code is an int + // (cast) left Op (cast) rigth --> result + // 0000 0000 0000 0000 0000 + // <<16 <<12 <<8 <<4 + + // int[] table = new int[16*16] ; return get_LEFT_SHIFT(); } - public static final int[] get_XOR(){ - - //the code is an int - // (cast) left Op (cast) rigth --> result - // 0000 0000 0000 0000 0000 - // <<16 <<12 <<8 <<4 + public static final int[] get_XOR() { - // int[] table = new int[16*16] ; - return get_AND() ; + // the code is an int + // (cast) left Op (cast) rigth --> result + // 0000 0000 0000 0000 0000 + // <<16 <<12 <<8 <<4 + + // int[] table = new int[16*16] ; + return get_AND(); } - + public String operatorToString() { switch ((bits & OperatorMASK) >> OperatorSHIFT) { - case EQUAL_EQUAL : - return "=="; //$NON-NLS-1$ - case LESS_EQUAL : - return "<="; //$NON-NLS-1$ - case GREATER_EQUAL : - return ">="; //$NON-NLS-1$ - case NOT_EQUAL : - return "!="; //$NON-NLS-1$ - case LEFT_SHIFT : - return "<<"; //$NON-NLS-1$ - case RIGHT_SHIFT : - return ">>"; //$NON-NLS-1$ - case UNSIGNED_RIGHT_SHIFT : - return ">>>"; //$NON-NLS-1$ - case OR_OR : - return "||"; //$NON-NLS-1$ - case AND_AND : - return "&&"; //$NON-NLS-1$ - case PLUS : - return "+"; //$NON-NLS-1$ - case MINUS : - return "-"; //$NON-NLS-1$ - case NOT : - return "!"; //$NON-NLS-1$ - case REMAINDER : - return "%"; //$NON-NLS-1$ - case XOR : - return "^"; //$NON-NLS-1$ - case AND : - return "&"; //$NON-NLS-1$ - case MULTIPLY : - return "*"; //$NON-NLS-1$ - case OR : - return "|"; //$NON-NLS-1$ - case TWIDDLE : - return "~"; //$NON-NLS-1$ - case DIVIDE : - return "/"; //$NON-NLS-1$ - case GREATER : - return ">"; //$NON-NLS-1$ - case LESS : - return "<"; //$NON-NLS-1$ - case QUESTIONCOLON : - return "?:"; //$NON-NLS-1$ - case EQUAL : - return "="; //$NON-NLS-1$ - }; + case EQUAL_EQUAL: + return "=="; //$NON-NLS-1$ + case LESS_EQUAL: + return "<="; //$NON-NLS-1$ + case GREATER_EQUAL: + return ">="; //$NON-NLS-1$ + case NOT_EQUAL: + return "!="; //$NON-NLS-1$ + case LEFT_SHIFT: + return "<<"; //$NON-NLS-1$ + case RIGHT_SHIFT: + return ">>"; //$NON-NLS-1$ + case UNSIGNED_RIGHT_SHIFT: + return ">>>"; //$NON-NLS-1$ + case OR_OR: + return "||"; //$NON-NLS-1$ + case AND_AND: + return "&&"; //$NON-NLS-1$ + case PLUS: + return "+"; //$NON-NLS-1$ + case MINUS: + return "-"; //$NON-NLS-1$ + case NOT: + return "!"; //$NON-NLS-1$ + case REMAINDER: + return "%"; //$NON-NLS-1$ + case XOR: + return "^"; //$NON-NLS-1$ + case AND: + return "&"; //$NON-NLS-1$ + case MULTIPLY: + return "*"; //$NON-NLS-1$ + case OR: + return "|"; //$NON-NLS-1$ + case TWIDDLE: + return "~"; //$NON-NLS-1$ + case DIVIDE: + return "/"; //$NON-NLS-1$ + case GREATER: + return ">"; //$NON-NLS-1$ + case LESS: + return "<"; //$NON-NLS-1$ + case QUESTIONCOLON: + return "?:"; //$NON-NLS-1$ + case EQUAL: + return "="; //$NON-NLS-1$ + } + ; return "unknown operator"; //$NON-NLS-1$ } - public StringBuffer printExpression(int indent, StringBuffer output){ + + public StringBuffer printExpression(int indent, StringBuffer output) { output.append('('); return printExpressionNoParenthesis(0, output).append(')'); } - - public abstract StringBuffer printExpressionNoParenthesis(int indent, StringBuffer output); - public String toStringExpression(){ + public abstract StringBuffer printExpressionNoParenthesis(int indent, + StringBuffer output); - //subclass redefine toStringExpressionNoParenthesis() - return "(" + toStringExpressionNoParenthesis() + ")"; //$NON-NLS-2$ //$NON-NLS-1$ + public String toStringExpression() { + + // subclass redefine toStringExpressionNoParenthesis() + return "(" + toStringExpressionNoParenthesis() + ")"; //$NON-NLS-2$ //$NON-NLS-1$ } - + public abstract String toStringExpressionNoParenthesis(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/OperatorIds.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/OperatorIds.java index 8f9ffa3..879e101 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/OperatorIds.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/OperatorIds.java @@ -12,32 +12,56 @@ package net.sourceforge.phpdt.internal.compiler.ast; public interface OperatorIds { public static final int AND_AND = 0; + public static final int OR_OR = 1; - public static final int AND = 2; - public static final int OR = 3; + + public static final int AND = 2; + + public static final int OR = 3; + public static final int LESS = 4; + public static final int LESS_EQUAL = 5; + public static final int GREATER = 6; + public static final int GREATER_EQUAL = 7; + public static final int XOR = 8; - public static final int DIVIDE = 9; + + public static final int DIVIDE = 9; + public static final int LEFT_SHIFT = 10; - public static final int NOT = 11; - public static final int TWIDDLE = 12; - public static final int MINUS = 13; - public static final int PLUS = 14; - public static final int MULTIPLY = 15; + + public static final int NOT = 11; + + public static final int TWIDDLE = 12; + + public static final int MINUS = 13; + + public static final int PLUS = 14; + + public static final int MULTIPLY = 15; + public static final int REMAINDER = 16; + public static final int RIGHT_SHIFT = 17; + public static final int EQUAL_EQUAL = 18; - public static final int UNSIGNED_RIGHT_SHIFT= 19; + + public static final int UNSIGNED_RIGHT_SHIFT = 19; + public static final int NumberOfTables = 20; public static final int QUESTIONCOLON = 23; public static final int NOT_EQUAL = 29; + public static final int EQUAL = 30; + public static final int INSTANCEOF = 31; + public static final int PLUS_PLUS = 32; + public static final int MINUS_MINUS = 33; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/PostfixExpression.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/PostfixExpression.java index 1f62325..a724020 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/PostfixExpression.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/PostfixExpression.java @@ -16,55 +16,59 @@ import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; public class PostfixExpression extends CompoundAssignment { public PostfixExpression(Expression l, Expression e, int op, int pos) { - + super(l, e, op, pos); this.sourceStart = l.sourceStart; this.sourceEnd = pos; } - + /** * Code generation for PostfixExpression - * - * @param currentScope net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream - * @param valueRequired boolean + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * @param valueRequired + * boolean */ -// public void generateCode( -// BlockScope currentScope, -// CodeStream codeStream, -// boolean valueRequired) { -// -// // various scenarii are possible, setting an array reference, -// // a field reference, a blank final field reference, a field of an enclosing instance or -// // just a local variable. -// -// int pc = codeStream.position; -// ((Reference) lhs).generatePostIncrement(currentScope, codeStream, this, valueRequired); -// if (valueRequired) { -// codeStream.generateImplicitConversion(implicitConversion); -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } - + // public void generateCode( + // BlockScope currentScope, + // CodeStream codeStream, + // boolean valueRequired) { + // + // // various scenarii are possible, setting an array reference, + // // a field reference, a blank final field reference, a field of an + // enclosing instance or + // // just a local variable. + // + // int pc = codeStream.position; + // ((Reference) lhs).generatePostIncrement(currentScope, codeStream, this, + // valueRequired); + // if (valueRequired) { + // codeStream.generateImplicitConversion(implicitConversion); + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } public String operatorToString() { switch (operator) { - case PLUS : - return "++"; //$NON-NLS-1$ - case MINUS : - return "--"; //$NON-NLS-1$ - } + case PLUS: + return "++"; //$NON-NLS-1$ + case MINUS: + return "--"; //$NON-NLS-1$ + } return "unknown operator"; //$NON-NLS-1$ } - + public boolean restrainUsageToNumericTypes() { return true; } - + public String toStringExpressionNoParenthesis() { return lhs.toStringExpression() + " " + operatorToString(); //$NON-NLS-1$ - } + } public void traverse(ASTVisitor visitor, BlockScope scope) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/PrefixExpression.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/PrefixExpression.java index f978601..71baa1f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/PrefixExpression.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/PrefixExpression.java @@ -17,9 +17,13 @@ public class PrefixExpression extends CompoundAssignment { /** * PrefixExpression constructor comment. - * @param l net.sourceforge.phpdt.internal.compiler.ast.Expression - * @param r net.sourceforge.phpdt.internal.compiler.ast.Expression - * @param op int + * + * @param l + * net.sourceforge.phpdt.internal.compiler.ast.Expression + * @param r + * net.sourceforge.phpdt.internal.compiler.ast.Expression + * @param op + * int */ public PrefixExpression(Expression l, Expression e, int op, int pos) { @@ -31,11 +35,11 @@ public class PrefixExpression extends CompoundAssignment { public String operatorToString() { switch (operator) { - case PLUS : - return "++"; //$NON-NLS-1$ - case MINUS : - return "--"; //$NON-NLS-1$ - } + case PLUS: + return "++"; //$NON-NLS-1$ + case MINUS: + return "--"; //$NON-NLS-1$ + } return "unknown operator"; //$NON-NLS-1$ } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/QualifiedAllocationExpression.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/QualifiedAllocationExpression.java index 8cc98e7..fe67cc9 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/QualifiedAllocationExpression.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/QualifiedAllocationExpression.java @@ -20,59 +20,60 @@ import net.sourceforge.phpdt.internal.compiler.lookup.ReferenceBinding; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; /** - * Variation on allocation, where can be specified an enclosing instance and an anonymous type + * Variation on allocation, where can be specified an enclosing instance and an + * anonymous type */ public class QualifiedAllocationExpression extends AllocationExpression { - - //qualification may be on both side + + // qualification may be on both side public Expression enclosingInstance; + public AnonymousLocalTypeDeclaration anonymousType; + public ReferenceBinding superTypeBinding; - + public QualifiedAllocationExpression() { } - public QualifiedAllocationExpression(AnonymousLocalTypeDeclaration anonymousType) { + public QualifiedAllocationExpression( + AnonymousLocalTypeDeclaration anonymousType) { this.anonymousType = anonymousType; } - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { // analyse the enclosing instance if (enclosingInstance != null) { - flowInfo = enclosingInstance.analyseCode(currentScope, flowContext, flowInfo); + flowInfo = enclosingInstance.analyseCode(currentScope, flowContext, + flowInfo); } - + // check captured variables are initialized in current context (26134) checkCapturedLocalInitializationIfNecessary( - this.superTypeBinding == null ? this.binding.declaringClass : this.superTypeBinding, - currentScope, - flowInfo); - + this.superTypeBinding == null ? this.binding.declaringClass + : this.superTypeBinding, currentScope, flowInfo); + // process arguments if (arguments != null) { for (int i = 0, count = arguments.length; i < count; i++) { - flowInfo = arguments[i].analyseCode(currentScope, flowContext, flowInfo); + flowInfo = arguments[i].analyseCode(currentScope, flowContext, + flowInfo); } } // analyse the anonymous nested type if (anonymousType != null) { - flowInfo = anonymousType.analyseCode(currentScope, flowContext, flowInfo); + flowInfo = anonymousType.analyseCode(currentScope, flowContext, + flowInfo); } // record some dependency information for exception types ReferenceBinding[] thrownExceptions; if (((thrownExceptions = binding.thrownExceptions).length) != 0) { // check exception handling - flowContext.checkExceptionHandlers( - thrownExceptions, - this, - flowInfo, - currentScope); + flowContext.checkExceptionHandlers(thrownExceptions, this, + flowInfo, currentScope); } manageEnclosingInstanceAccessIfNecessary(currentScope); manageSyntheticAccessIfNecessary(currentScope); @@ -84,88 +85,93 @@ public class QualifiedAllocationExpression extends AllocationExpression { return enclosingInstance; } -// public void generateCode( -// BlockScope currentScope, -// CodeStream codeStream, -// boolean valueRequired) { -// -// int pc = codeStream.position; -// ReferenceBinding allocatedType = binding.declaringClass; -// codeStream.new_(allocatedType); -// if (valueRequired) { -// codeStream.dup(); -// } -// // better highlight for allocation: display the type individually -// codeStream.recordPositionsFrom(pc, type.sourceStart); -// -// // handling innerclass instance allocation - enclosing instance arguments -// if (allocatedType.isNestedType()) { -// codeStream.generateSyntheticEnclosingInstanceValues( -// currentScope, -// allocatedType, -// enclosingInstance(), -// this); -// } -// // generate the arguments for constructor -// if (arguments != null) { -// for (int i = 0, count = arguments.length; i < count; i++) { -// arguments[i].generateCode(currentScope, codeStream, true); -// } -// } -// // handling innerclass instance allocation - outer local arguments -// if (allocatedType.isNestedType()) { -// codeStream.generateSyntheticOuterArgumentValues( -// currentScope, -// allocatedType, -// this); -// } -// -// // invoke constructor -// if (syntheticAccessor == null) { -// codeStream.invokespecial(binding); -// } else { -// // synthetic accessor got some extra arguments appended to its signature, which need values -// for (int i = 0, -// max = syntheticAccessor.parameters.length - binding.parameters.length; -// i < max; -// i++) { -// codeStream.aconst_null(); -// } -// codeStream.invokespecial(syntheticAccessor); -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// -// if (anonymousType != null) { -// anonymousType.generateCode(currentScope, codeStream); -// } -// } - + // public void generateCode( + // BlockScope currentScope, + // CodeStream codeStream, + // boolean valueRequired) { + // + // int pc = codeStream.position; + // ReferenceBinding allocatedType = binding.declaringClass; + // codeStream.new_(allocatedType); + // if (valueRequired) { + // codeStream.dup(); + // } + // // better highlight for allocation: display the type individually + // codeStream.recordPositionsFrom(pc, type.sourceStart); + // + // // handling innerclass instance allocation - enclosing instance arguments + // if (allocatedType.isNestedType()) { + // codeStream.generateSyntheticEnclosingInstanceValues( + // currentScope, + // allocatedType, + // enclosingInstance(), + // this); + // } + // // generate the arguments for constructor + // if (arguments != null) { + // for (int i = 0, count = arguments.length; i < count; i++) { + // arguments[i].generateCode(currentScope, codeStream, true); + // } + // } + // // handling innerclass instance allocation - outer local arguments + // if (allocatedType.isNestedType()) { + // codeStream.generateSyntheticOuterArgumentValues( + // currentScope, + // allocatedType, + // this); + // } + // + // // invoke constructor + // if (syntheticAccessor == null) { + // codeStream.invokespecial(binding); + // } else { + // // synthetic accessor got some extra arguments appended to its signature, + // which need values + // for (int i = 0, + // max = syntheticAccessor.parameters.length - binding.parameters.length; + // i < max; + // i++) { + // codeStream.aconst_null(); + // } + // codeStream.invokespecial(syntheticAccessor); + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // + // if (anonymousType != null) { + // anonymousType.generateCode(currentScope, codeStream); + // } + // } + public boolean isSuperAccess() { // necessary to lookup super constructor of anonymous type return anonymousType != null; } - - /* Inner emulation consists in either recording a dependency - * link only, or performing one level of propagation. - * - * Dependency mechanism is used whenever dealing with source target - * types, since by the time we reach them, we might not yet know their - * exact need. + + /* + * Inner emulation consists in either recording a dependency link only, or + * performing one level of propagation. + * + * Dependency mechanism is used whenever dealing with source target types, + * since by the time we reach them, we might not yet know their exact need. */ public void manageEnclosingInstanceAccessIfNecessary(BlockScope currentScope) { ReferenceBinding allocatedType; - // perform some emulation work in case there is some and we are inside a local type only + // perform some emulation work in case there is some and we are inside a + // local type only if ((allocatedType = binding.declaringClass).isNestedType() - && currentScope.enclosingSourceType().isLocalType()) { + && currentScope.enclosingSourceType().isLocalType()) { if (allocatedType.isLocalType()) { - ((LocalTypeBinding) allocatedType).addInnerEmulationDependent(currentScope, enclosingInstance != null); + ((LocalTypeBinding) allocatedType).addInnerEmulationDependent( + currentScope, enclosingInstance != null); } else { - // locally propagate, since we already now the desired shape for sure - currentScope.propagateInnerEmulation(allocatedType, enclosingInstance != null); + // locally propagate, since we already now the desired shape for + // sure + currentScope.propagateInnerEmulation(allocatedType, + enclosingInstance != null); } } } @@ -177,27 +183,34 @@ public class QualifiedAllocationExpression extends AllocationExpression { return super.resolveType(scope); } - // Propagate the type checking to the arguments, and checks if the constructor is defined. - // ClassInstanceCreationExpression ::= Primary '.' 'new' SimpleName '(' ArgumentListopt ')' ClassBodyopt - // ClassInstanceCreationExpression ::= Name '.' 'new' SimpleName '(' ArgumentListopt ')' ClassBodyopt - // ==> by construction, when there is an enclosing instance the typename may NOT be qualified - // ==> therefore by construction the type is always a SingleTypeReferenceType instead of being either + // Propagate the type checking to the arguments, and checks if the + // constructor is defined. + // ClassInstanceCreationExpression ::= Primary '.' 'new' SimpleName '(' + // ArgumentListopt ')' ClassBodyopt + // ClassInstanceCreationExpression ::= Name '.' 'new' SimpleName '(' + // ArgumentListopt ')' ClassBodyopt + // ==> by construction, when there is an enclosing instance the typename + // may NOT be qualified + // ==> therefore by construction the type is always a + // SingleTypeReferenceType instead of being either // sometime a SingleTypeReference and sometime a QualifedTypeReference constant = NotAConstant; TypeBinding enclosingInstanceType = null; TypeBinding receiverType = null; boolean hasError = false; - if (anonymousType == null) { //----------------no anonymous class------------------------ - if ((enclosingInstanceType = enclosingInstance.resolveType(scope)) == null){ + if (anonymousType == null) { // ----------------no anonymous + // class------------------------ + if ((enclosingInstanceType = enclosingInstance.resolveType(scope)) == null) { hasError = true; - } else if (enclosingInstanceType.isBaseType() || enclosingInstanceType.isArrayType()) { - scope.problemReporter().illegalPrimitiveOrArrayTypeForEnclosingInstance( - enclosingInstanceType, - enclosingInstance); + } else if (enclosingInstanceType.isBaseType() + || enclosingInstanceType.isArrayType()) { + scope.problemReporter() + .illegalPrimitiveOrArrayTypeForEnclosingInstance( + enclosingInstanceType, enclosingInstance); hasError = true; - } else if ((this.resolvedType = receiverType = ((SingleTypeReference) type).resolveTypeEnclosing( - scope, + } else if ((this.resolvedType = receiverType = ((SingleTypeReference) type) + .resolveTypeEnclosing(scope, (ReferenceBinding) enclosingInstanceType)) == null) { hasError = true; } @@ -207,25 +220,29 @@ public class QualifiedAllocationExpression extends AllocationExpression { int length = arguments.length; argumentTypes = new TypeBinding[length]; for (int i = 0; i < length; i++) - if ((argumentTypes[i] = arguments[i].resolveType(scope)) == null){ + if ((argumentTypes[i] = arguments[i].resolveType(scope)) == null) { hasError = true; } } // limit of fault-tolerance - if (hasError) return receiverType; + if (hasError) + return receiverType; if (!receiverType.canBeInstantiated()) { scope.problemReporter().cannotInstantiate(type, receiverType); return receiverType; } - if ((this.binding = scope.getConstructor((ReferenceBinding) receiverType, argumentTypes, this)) + if ((this.binding = scope.getConstructor( + (ReferenceBinding) receiverType, argumentTypes, this)) .isValidBinding()) { if (isMethodUseDeprecated(binding, scope)) - scope.problemReporter().deprecatedMethod(this.binding, this); + scope.problemReporter() + .deprecatedMethod(this.binding, this); if (arguments != null) for (int i = 0; i < arguments.length; i++) - arguments[i].implicitWidening(this.binding.parameters[i], argumentTypes[i]); + arguments[i].implicitWidening( + this.binding.parameters[i], argumentTypes[i]); } else { if (this.binding.declaringClass == null) this.binding.declaringClass = (ReferenceBinding) receiverType; @@ -233,30 +250,34 @@ public class QualifiedAllocationExpression extends AllocationExpression { return receiverType; } - // The enclosing instance must be compatible with the innermost enclosing type - ReferenceBinding expectedType = this.binding.declaringClass.enclosingType(); + // The enclosing instance must be compatible with the innermost + // enclosing type + ReferenceBinding expectedType = this.binding.declaringClass + .enclosingType(); if (enclosingInstanceType.isCompatibleWith(expectedType)) return receiverType; - scope.problemReporter().typeMismatchErrorActualTypeExpectedType( - this.enclosingInstance, - enclosingInstanceType, - expectedType); + scope.problemReporter() + .typeMismatchErrorActualTypeExpectedType( + this.enclosingInstance, enclosingInstanceType, + expectedType); return receiverType; } - //--------------there is an anonymous type declaration----------------- + // --------------there is an anonymous type declaration----------------- if (this.enclosingInstance != null) { - if ((enclosingInstanceType = this.enclosingInstance.resolveType(scope)) == null) { + if ((enclosingInstanceType = this.enclosingInstance + .resolveType(scope)) == null) { hasError = true; - } else if (enclosingInstanceType.isBaseType() || enclosingInstanceType.isArrayType()) { - scope.problemReporter().illegalPrimitiveOrArrayTypeForEnclosingInstance( - enclosingInstanceType, - this.enclosingInstance); + } else if (enclosingInstanceType.isBaseType() + || enclosingInstanceType.isArrayType()) { + scope.problemReporter() + .illegalPrimitiveOrArrayTypeForEnclosingInstance( + enclosingInstanceType, this.enclosingInstance); hasError = true; } else { - receiverType = ((SingleTypeReference) type).resolveTypeEnclosing( - scope, - (ReferenceBinding) enclosingInstanceType); + receiverType = ((SingleTypeReference) type) + .resolveTypeEnclosing(scope, + (ReferenceBinding) enclosingInstanceType); } } else { receiverType = type.resolveType(scope); @@ -264,7 +285,8 @@ public class QualifiedAllocationExpression extends AllocationExpression { if (receiverType == null) { hasError = true; } else if (((ReferenceBinding) receiverType).isFinal()) { - scope.problemReporter().anonymousClassCannotExtendFinalClass(type, receiverType); + scope.problemReporter().anonymousClassCannotExtendFinalClass(type, + receiverType); hasError = true; } TypeBinding[] argumentTypes = NoParameters; @@ -278,14 +300,15 @@ public class QualifiedAllocationExpression extends AllocationExpression { } // limit of fault-tolerance if (hasError) { - return receiverType; + return receiverType; } - // an anonymous class inherits from java.lang.Object when declared "after" an interface - this.superTypeBinding = - receiverType.isInterface() ? scope.getJavaLangObject() : (ReferenceBinding) receiverType; - MethodBinding inheritedBinding = - scope.getConstructor(this.superTypeBinding, argumentTypes, this); + // an anonymous class inherits from java.lang.Object when declared + // "after" an interface + this.superTypeBinding = receiverType.isInterface() ? scope + .getJavaLangObject() : (ReferenceBinding) receiverType; + MethodBinding inheritedBinding = scope.getConstructor( + this.superTypeBinding, argumentTypes, this); if (!inheritedBinding.isValidBinding()) { if (inheritedBinding.declaringClass == null) inheritedBinding.declaringClass = this.superTypeBinding; @@ -293,28 +316,35 @@ public class QualifiedAllocationExpression extends AllocationExpression { return null; } if (enclosingInstance != null) { - if (!enclosingInstanceType.isCompatibleWith(inheritedBinding.declaringClass.enclosingType())) { - scope.problemReporter().typeMismatchErrorActualTypeExpectedType( - enclosingInstance, - enclosingInstanceType, - inheritedBinding.declaringClass.enclosingType()); + if (!enclosingInstanceType + .isCompatibleWith(inheritedBinding.declaringClass + .enclosingType())) { + scope + .problemReporter() + .typeMismatchErrorActualTypeExpectedType( + enclosingInstance, enclosingInstanceType, + inheritedBinding.declaringClass.enclosingType()); return null; } } - // this promotion has to be done somewhere: here or inside the constructor of the - // anonymous class. We do it here while the constructor of the inner is then easier. + // this promotion has to be done somewhere: here or inside the + // constructor of the + // anonymous class. We do it here while the constructor of the inner is + // then easier. if (arguments != null) for (int i = 0; i < arguments.length; i++) - arguments[i].implicitWidening(inheritedBinding.parameters[i], argumentTypes[i]); + arguments[i].implicitWidening(inheritedBinding.parameters[i], + argumentTypes[i]); - // Update the anonymous inner class : superclass, interface + // Update the anonymous inner class : superclass, interface scope.addAnonymousType(anonymousType, (ReferenceBinding) receiverType); anonymousType.resolve(scope); - binding = anonymousType.createsInternalConstructorWithBinding(inheritedBinding); + binding = anonymousType + .createsInternalConstructorWithBinding(inheritedBinding); return anonymousType.binding; // 1.2 change } - + public String toStringExpression() { return this.toStringExpression(0); } @@ -327,7 +357,7 @@ public class QualifiedAllocationExpression extends AllocationExpression { s += super.toStringExpression(); if (anonymousType != null) { s += anonymousType.toString(tab); - } //allows to restart just after the } one line under .... + } // allows to restart just after the } one line under .... return s; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/QualifiedNameReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/QualifiedNameReference.java index 26d4107..4e74dc3 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/QualifiedNameReference.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/QualifiedNameReference.java @@ -25,199 +25,213 @@ import net.sourceforge.phpdt.internal.compiler.lookup.SyntheticAccessMethodBindi import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; import net.sourceforge.phpdt.internal.compiler.lookup.VariableBinding; - public class QualifiedNameReference extends NameReference { - + public char[][] tokens; + public FieldBinding[] otherBindings, otherCodegenBindings; + int[] otherDepths; - public int indexOfFirstFieldBinding;//points (into tokens) for the first token that corresponds to first FieldBinding + + public int indexOfFirstFieldBinding;// points (into tokens) for the first + // token that corresponds to first + // FieldBinding + SyntheticAccessMethodBinding syntheticWriteAccessor; + SyntheticAccessMethodBinding[] syntheticReadAccessors; + protected FieldBinding lastFieldBinding; - public QualifiedNameReference( - char[][] sources, - int sourceStart, - int sourceEnd) { + + public QualifiedNameReference(char[][] sources, int sourceStart, + int sourceEnd) { super(); tokens = sources; this.sourceStart = sourceStart; this.sourceEnd = sourceEnd; } - public FlowInfo analyseAssignment( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo, - Assignment assignment, - boolean isCompound) { - - // determine the rank until which we now we do not need any actual value for the field access - int otherBindingsCount = otherBindings == null ? 0 : otherBindings.length; - boolean needValue = otherBindingsCount == 0 || !this.otherBindings[0].isStatic(); + + public FlowInfo analyseAssignment(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo, Assignment assignment, + boolean isCompound) { + + // determine the rank until which we now we do not need any actual value + // for the field access + int otherBindingsCount = otherBindings == null ? 0 + : otherBindings.length; + boolean needValue = otherBindingsCount == 0 + || !this.otherBindings[0].isStatic(); switch (bits & RestrictiveFlagMASK) { - case FIELD : // reading a field - lastFieldBinding = (FieldBinding) binding; - if (needValue) { - manageSyntheticReadAccessIfNecessary(currentScope, lastFieldBinding, this.actualReceiverType, 0); - } // check if final blank field - if (lastFieldBinding.isBlankFinal() - && this.otherBindings != null // the last field binding is only assigned - && currentScope.allowBlankFinalFieldAssignment(lastFieldBinding)) { - if (!flowInfo.isDefinitelyAssigned(lastFieldBinding)) { - currentScope.problemReporter().uninitializedBlankFinalField( - lastFieldBinding, - this); - } + case FIELD: // reading a field + lastFieldBinding = (FieldBinding) binding; + if (needValue) { + manageSyntheticReadAccessIfNecessary(currentScope, + lastFieldBinding, this.actualReceiverType, 0); + } // check if final blank field + if (lastFieldBinding.isBlankFinal() + && this.otherBindings != null // the last field binding is + // only assigned + && currentScope + .allowBlankFinalFieldAssignment(lastFieldBinding)) { + if (!flowInfo.isDefinitelyAssigned(lastFieldBinding)) { + currentScope.problemReporter() + .uninitializedBlankFinalField(lastFieldBinding, + this); } - break; -// case LOCAL : -// // first binding is a local variable -// LocalVariableBinding localBinding; -// if (!flowInfo -// .isDefinitelyAssigned(localBinding = (LocalVariableBinding) binding)) { -// currentScope.problemReporter().uninitializedLocalVariable(localBinding, this); -// } -// if (flowInfo.isReachable()) { -// localBinding.useFlag = LocalVariableBinding.USED; -// } else if (localBinding.useFlag == LocalVariableBinding.UNUSED) { -// localBinding.useFlag = LocalVariableBinding.FAKE_USED; -// } + } + break; + // case LOCAL : + // // first binding is a local variable + // LocalVariableBinding localBinding; + // if (!flowInfo + // .isDefinitelyAssigned(localBinding = (LocalVariableBinding) binding)) + // { + // currentScope.problemReporter().uninitializedLocalVariable(localBinding, + // this); + // } + // if (flowInfo.isReachable()) { + // localBinding.useFlag = LocalVariableBinding.USED; + // } else if (localBinding.useFlag == LocalVariableBinding.UNUSED) { + // localBinding.useFlag = LocalVariableBinding.FAKE_USED; + // } } - + if (needValue) { manageEnclosingInstanceAccessIfNecessary(currentScope); // only for first binding } // all intermediate field accesses are read accesses if (otherBindings != null) { - for (int i = 0; i < otherBindingsCount-1; i++) { + for (int i = 0; i < otherBindingsCount - 1; i++) { lastFieldBinding = otherBindings[i]; - needValue = !otherBindings[i+1].isStatic(); + needValue = !otherBindings[i + 1].isStatic(); if (needValue) { - manageSyntheticReadAccessIfNecessary( - currentScope, - lastFieldBinding, - i == 0 - ? ((VariableBinding)binding).type - : otherBindings[i-1].type, - i + 1); + manageSyntheticReadAccessIfNecessary(currentScope, + lastFieldBinding, + i == 0 ? ((VariableBinding) binding).type + : otherBindings[i - 1].type, i + 1); } } - lastFieldBinding = otherBindings[otherBindingsCount-1]; + lastFieldBinding = otherBindings[otherBindingsCount - 1]; } if (isCompound) { if (binding == lastFieldBinding - && lastFieldBinding.isBlankFinal() - && currentScope.allowBlankFinalFieldAssignment(lastFieldBinding) - && (!flowInfo.isDefinitelyAssigned(lastFieldBinding))) { + && lastFieldBinding.isBlankFinal() + && currentScope + .allowBlankFinalFieldAssignment(lastFieldBinding) + && (!flowInfo.isDefinitelyAssigned(lastFieldBinding))) { currentScope.problemReporter().uninitializedBlankFinalField( - lastFieldBinding, - this); + lastFieldBinding, this); } TypeBinding lastReceiverType; - if (lastFieldBinding == binding){ + if (lastFieldBinding == binding) { lastReceiverType = this.actualReceiverType; - } else if (otherBindingsCount == 1){ - lastReceiverType = ((VariableBinding)this.binding).type; + } else if (otherBindingsCount == 1) { + lastReceiverType = ((VariableBinding) this.binding).type; } else { - lastReceiverType = this.otherBindings[otherBindingsCount-2].type; + lastReceiverType = this.otherBindings[otherBindingsCount - 2].type; } - manageSyntheticReadAccessIfNecessary( - currentScope, - lastFieldBinding, - lastReceiverType, - lastFieldBinding == binding - ? 0 - : otherBindingsCount); + manageSyntheticReadAccessIfNecessary(currentScope, + lastFieldBinding, lastReceiverType, + lastFieldBinding == binding ? 0 : otherBindingsCount); } - + if (assignment.expression != null) { - flowInfo = - assignment - .expression - .analyseCode(currentScope, flowContext, flowInfo) - .unconditionalInits(); + flowInfo = assignment.expression.analyseCode(currentScope, + flowContext, flowInfo).unconditionalInits(); } - + // the last field access is a write access if (lastFieldBinding.isFinal()) { // in a context where it can be assigned? if (lastFieldBinding.isBlankFinal() && !isCompound - && currentScope.allowBlankFinalFieldAssignment(lastFieldBinding) + && currentScope + .allowBlankFinalFieldAssignment(lastFieldBinding) && indexOfFirstFieldBinding == 1) { if (flowInfo.isPotentiallyAssigned(lastFieldBinding)) { - currentScope.problemReporter().duplicateInitializationOfBlankFinalField(lastFieldBinding, this); + currentScope.problemReporter() + .duplicateInitializationOfBlankFinalField( + lastFieldBinding, this); } else { flowContext.recordSettingFinal(lastFieldBinding, this); } flowInfo.markAsDefinitelyAssigned(lastFieldBinding); } else { - currentScope.problemReporter().cannotAssignToFinalField(lastFieldBinding, this); - if (currentScope.allowBlankFinalFieldAssignment(lastFieldBinding)) { // pretend it got assigned + currentScope.problemReporter().cannotAssignToFinalField( + lastFieldBinding, this); + if (currentScope + .allowBlankFinalFieldAssignment(lastFieldBinding)) { // pretend + // it + // got + // assigned flowInfo.markAsDefinitelyAssigned(lastFieldBinding); } } } // equivalent to valuesRequired[maxOtherBindings] TypeBinding lastReceiverType; - if (lastFieldBinding == binding){ + if (lastFieldBinding == binding) { lastReceiverType = this.actualReceiverType; - } else if (otherBindingsCount == 1){ - lastReceiverType = ((VariableBinding)this.binding).type; + } else if (otherBindingsCount == 1) { + lastReceiverType = ((VariableBinding) this.binding).type; } else { - lastReceiverType = this.otherBindings[otherBindingsCount-2].type; + lastReceiverType = this.otherBindings[otherBindingsCount - 2].type; } - manageSyntheticWriteAccessIfNecessary(currentScope, lastFieldBinding, lastReceiverType); + manageSyntheticWriteAccessIfNecessary(currentScope, lastFieldBinding, + lastReceiverType); return flowInfo; } - - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { + + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { return analyseCode(currentScope, flowContext, flowInfo, true); } - - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo, - boolean valueRequired) { - - // determine the rank until which we now we do not need any actual value for the field access - int otherBindingsCount = otherBindings == null ? 0 : otherBindings.length; - - boolean needValue = otherBindingsCount == 0 ? valueRequired : !this.otherBindings[0].isStatic(); + + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo, boolean valueRequired) { + + // determine the rank until which we now we do not need any actual value + // for the field access + int otherBindingsCount = otherBindings == null ? 0 + : otherBindings.length; + + boolean needValue = otherBindingsCount == 0 ? valueRequired + : !this.otherBindings[0].isStatic(); switch (bits & RestrictiveFlagMASK) { - case FIELD : // reading a field - if (needValue) { - manageSyntheticReadAccessIfNecessary(currentScope, (FieldBinding) binding, this.actualReceiverType, 0); - } - // check if reading a final blank field - FieldBinding fieldBinding; - if ((fieldBinding = (FieldBinding) binding).isBlankFinal() - && (indexOfFirstFieldBinding == 1) + case FIELD: // reading a field + if (needValue) { + manageSyntheticReadAccessIfNecessary(currentScope, + (FieldBinding) binding, this.actualReceiverType, 0); + } + // check if reading a final blank field + FieldBinding fieldBinding; + if ((fieldBinding = (FieldBinding) binding).isBlankFinal() + && (indexOfFirstFieldBinding == 1) // was an implicit reference to the first field binding - && currentScope.allowBlankFinalFieldAssignment(fieldBinding) - && (!flowInfo.isDefinitelyAssigned(fieldBinding))) { - currentScope.problemReporter().uninitializedBlankFinalField(fieldBinding, this); - } - break; -// case LOCAL : // reading a local variable -// LocalVariableBinding localBinding; -// if (!flowInfo -// .isDefinitelyAssigned(localBinding = (LocalVariableBinding) binding)) { -// currentScope.problemReporter().uninitializedLocalVariable(localBinding, this); -// } -// if (flowInfo.isReachable()) { -// localBinding.useFlag = LocalVariableBinding.USED; -// } else if (localBinding.useFlag == LocalVariableBinding.UNUSED) { -// localBinding.useFlag = LocalVariableBinding.FAKE_USED; -// } + && currentScope + .allowBlankFinalFieldAssignment(fieldBinding) + && (!flowInfo.isDefinitelyAssigned(fieldBinding))) { + currentScope.problemReporter().uninitializedBlankFinalField( + fieldBinding, this); + } + break; + // case LOCAL : // reading a local variable + // LocalVariableBinding localBinding; + // if (!flowInfo + // .isDefinitelyAssigned(localBinding = (LocalVariableBinding) binding)) + // { + // currentScope.problemReporter().uninitializedLocalVariable(localBinding, + // this); + // } + // if (flowInfo.isReachable()) { + // localBinding.useFlag = LocalVariableBinding.USED; + // } else if (localBinding.useFlag == LocalVariableBinding.UNUSED) { + // localBinding.useFlag = LocalVariableBinding.FAKE_USED; + // } } if (needValue) { manageEnclosingInstanceAccessIfNecessary(currentScope); @@ -225,20 +239,19 @@ public class QualifiedNameReference extends NameReference { } if (otherBindings != null) { for (int i = 0; i < otherBindingsCount; i++) { - needValue = i < otherBindingsCount-1 ? !otherBindings[i+1].isStatic() : valueRequired; + needValue = i < otherBindingsCount - 1 ? !otherBindings[i + 1] + .isStatic() : valueRequired; if (needValue) { - manageSyntheticReadAccessIfNecessary( - currentScope, - otherBindings[i], - i == 0 - ? ((VariableBinding)binding).type - : otherBindings[i-1].type, - i + 1); + manageSyntheticReadAccessIfNecessary(currentScope, + otherBindings[i], + i == 0 ? ((VariableBinding) binding).type + : otherBindings[i - 1].type, i + 1); } } } return flowInfo; } + /** * Check and/or redirect the field access to the delegate receiver if any */ @@ -247,318 +260,343 @@ public class QualifiedNameReference extends NameReference { FieldBinding fieldBinding = (FieldBinding) binding; MethodScope methodScope = scope.methodScope(); if (methodScope.enclosingSourceType() == fieldBinding.declaringClass - && methodScope.fieldDeclarationIndex != MethodScope.NotInFieldDecl - && fieldBinding.id >= methodScope.fieldDeclarationIndex) { + && methodScope.fieldDeclarationIndex != MethodScope.NotInFieldDecl + && fieldBinding.id >= methodScope.fieldDeclarationIndex) { if ((!fieldBinding.isStatic() || methodScope.isStatic) - && this.indexOfFirstFieldBinding == 1) - scope.problemReporter().forwardReference(this, 0, scope.enclosingSourceType()); + && this.indexOfFirstFieldBinding == 1) + scope.problemReporter().forwardReference(this, 0, + scope.enclosingSourceType()); } bits &= ~RestrictiveFlagMASK; // clear bits bits |= FIELD; return getOtherFieldBindings(scope); } -// public void generateAssignment( -// BlockScope currentScope, -// CodeStream codeStream, -// Assignment assignment, -// boolean valueRequired) { -// -// generateReadSequence(currentScope, codeStream); -// assignment.expression.generateCode(currentScope, codeStream, true); -// fieldStore(codeStream, lastFieldBinding, syntheticWriteAccessor, valueRequired); -// // equivalent to valuesRequired[maxOtherBindings] -// if (valueRequired) { -// codeStream.generateImplicitConversion(assignment.implicitConversion); -// } -// } -// public void generateCode( -// BlockScope currentScope, -// CodeStream codeStream, -// boolean valueRequired) { -// -// int pc = codeStream.position; -// if (constant != NotAConstant) { -// if (valueRequired) { -// codeStream.generateConstant(constant, implicitConversion); -// } -// } else { -// generateReadSequence(currentScope, codeStream); -// if (valueRequired) { -// if (lastFieldBinding.declaringClass == null) { // array length -// codeStream.arraylength(); -// codeStream.generateImplicitConversion(implicitConversion); -// } else { -// if (lastFieldBinding.constant != NotAConstant) { -// if (!lastFieldBinding.isStatic()){ -// codeStream.invokeObjectGetClass(); -// codeStream.pop(); -// } -// // inline the last field constant -// codeStream.generateConstant(lastFieldBinding.constant, implicitConversion); -// } else { -// SyntheticAccessMethodBinding accessor = -// syntheticReadAccessors == null -// ? null -// : syntheticReadAccessors[syntheticReadAccessors.length - 1]; -// if (accessor == null) { -// if (lastFieldBinding.isStatic()) { -// codeStream.getstatic(lastFieldBinding); -// } else { -// codeStream.getfield(lastFieldBinding); -// } -// } else { -// codeStream.invokestatic(accessor); -// } -// codeStream.generateImplicitConversion(implicitConversion); -// } -// } -// } else { -// if (lastFieldBinding != null && !lastFieldBinding.isStatic()){ -// codeStream.invokeObjectGetClass(); // perform null check -// codeStream.pop(); -// } -// -// } -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } -// public void generateCompoundAssignment( -// BlockScope currentScope, -// CodeStream codeStream, -// Expression expression, -// int operator, -// int assignmentImplicitConversion, -// boolean valueRequired) { -// -// generateReadSequence(currentScope, codeStream); -// SyntheticAccessMethodBinding accessor = -// syntheticReadAccessors == null -// ? null -// : syntheticReadAccessors[syntheticReadAccessors.length - 1]; -// if (lastFieldBinding.isStatic()) { -// if (accessor == null) { -// codeStream.getstatic(lastFieldBinding); -// } else { -// codeStream.invokestatic(accessor); -// } -// } else { -// codeStream.dup(); -// if (accessor == null) { -// codeStream.getfield(lastFieldBinding); -// } else { -// codeStream.invokestatic(accessor); -// } -// } -// // the last field access is a write access -// // perform the actual compound operation -// int operationTypeID; -// if ((operationTypeID = implicitConversion >> 4) == T_String) { -// codeStream.generateStringAppend(currentScope, null, expression); -// } else { -// // promote the array reference to the suitable operation type -// codeStream.generateImplicitConversion(implicitConversion); -// // generate the increment value (will by itself be promoted to the operation value) -// if (expression == IntLiteral.One) { // prefix operation -// codeStream.generateConstant(expression.constant, implicitConversion); -// } else { -// expression.generateCode(currentScope, codeStream, true); -// } -// // perform the operation -// codeStream.sendOperator(operator, operationTypeID); -// // cast the value back to the array reference type -// codeStream.generateImplicitConversion(assignmentImplicitConversion); -// } -// // actual assignment -// fieldStore(codeStream, lastFieldBinding, syntheticWriteAccessor, valueRequired); -// // equivalent to valuesRequired[maxOtherBindings] -// } -// public void generatePostIncrement( -// BlockScope currentScope, -// CodeStream codeStream, -// CompoundAssignment postIncrement, -// boolean valueRequired) { -// generateReadSequence(currentScope, codeStream); -// SyntheticAccessMethodBinding accessor = -// syntheticReadAccessors == null -// ? null -// : syntheticReadAccessors[syntheticReadAccessors.length - 1]; -// if (lastFieldBinding.isStatic()) { -// if (accessor == null) { -// codeStream.getstatic(lastFieldBinding); -// } else { -// codeStream.invokestatic(accessor); -// } -// } else { -// codeStream.dup(); -// if (accessor == null) { -// codeStream.getfield(lastFieldBinding); -// } else { -// codeStream.invokestatic(accessor); -// } -// } -// // duplicate the old field value -// if (valueRequired) { -// if (lastFieldBinding.isStatic()) { -// if ((lastFieldBinding.type == LongBinding) -// || (lastFieldBinding.type == DoubleBinding)) { -// codeStream.dup2(); -// } else { -// codeStream.dup(); -// } -// } else { // Stack: [owner][old field value] ---> [old field value][owner][old field value] -// if ((lastFieldBinding.type == LongBinding) -// || (lastFieldBinding.type == DoubleBinding)) { -// codeStream.dup2_x1(); -// } else { -// codeStream.dup_x1(); -// } -// } -// } -// codeStream.generateConstant( -// postIncrement.expression.constant, -// implicitConversion); -// codeStream.sendOperator(postIncrement.operator, lastFieldBinding.type.id); -// codeStream.generateImplicitConversion( -// postIncrement.assignmentImplicitConversion); -// fieldStore(codeStream, lastFieldBinding, syntheticWriteAccessor, false); -// } -// /* -// * Generate code for all bindings (local and fields) excluding the last one, which may then be generated code -// * for a read or write access. -// */ -// public void generateReadSequence( -// BlockScope currentScope, -// CodeStream codeStream) { -// -// // determine the rank until which we now we do not need any actual value for the field access -// int otherBindingsCount = this.otherCodegenBindings == null ? 0 : otherCodegenBindings.length; -// -// boolean needValue = otherBindingsCount == 0 || !this.otherBindings[0].isStatic(); -// switch (bits & RestrictiveFlagMASK) { -// case FIELD : -// lastFieldBinding = (FieldBinding) this.codegenBinding; -// // if first field is actually constant, we can inline it -// if (lastFieldBinding.constant != NotAConstant) { -// break; -// } -// if (needValue && !lastFieldBinding.isStatic()) { -// if ((bits & DepthMASK) != 0) { -// ReferenceBinding targetType = currentScope.enclosingSourceType().enclosingTypeAt((bits & DepthMASK) >> DepthSHIFT); -// Object[] emulationPath = currentScope.getEmulationPath(targetType, true /*only exact match*/, false/*consider enclosing arg*/); -// codeStream.generateOuterAccess(emulationPath, this, targetType, currentScope); -// } else { -// generateReceiver(codeStream); -// } -// } -// break; -// case LOCAL : // reading the first local variable -// if (!needValue) break; // no value needed -// lastFieldBinding = null; -// LocalVariableBinding localBinding = (LocalVariableBinding) this.codegenBinding; -// // regular local variable read -// if (localBinding.constant != NotAConstant) { -// codeStream.generateConstant(localBinding.constant, 0); -// // no implicit conversion -// } else { -// // outer local? -// if ((bits & DepthMASK) != 0) { -// // outer local can be reached either through a synthetic arg or a synthetic field -// VariableBinding[] path = currentScope.getEmulationPath(localBinding); -// codeStream.generateOuterAccess(path, this, localBinding, currentScope); -// } else { -// codeStream.load(localBinding); -// } -// } -// } -// -// // all intermediate field accesses are read accesses -// // only the last field binding is a write access -// if (this.otherCodegenBindings != null) { -// for (int i = 0; i < otherBindingsCount; i++) { -// FieldBinding nextField = this.otherCodegenBindings[i]; -// if (lastFieldBinding != null) { -// needValue = !nextField.isStatic(); -// if (needValue) { -// MethodBinding accessor = -// syntheticReadAccessors == null ? null : syntheticReadAccessors[i]; -// if (accessor == null) { -// if (lastFieldBinding.constant != NotAConstant) { -// if (this.lastFieldBinding != this.codegenBinding && !this.lastFieldBinding.isStatic()) { -// codeStream.invokeObjectGetClass(); // perform null check -// codeStream.pop(); -// } -// codeStream.generateConstant(lastFieldBinding.constant, 0); -// } else if (lastFieldBinding.isStatic()) { -// codeStream.getstatic(lastFieldBinding); -// } else { -// codeStream.getfield(lastFieldBinding); -// } -// } else { -// codeStream.invokestatic(accessor); -// } -// } else { -// if (this.codegenBinding != this.lastFieldBinding && !this.lastFieldBinding.isStatic()){ -// codeStream.invokeObjectGetClass(); // perform null check -// codeStream.pop(); -// } -// } -// } -// this.lastFieldBinding = nextField; -// } -// } -// } -// public void generateReceiver(CodeStream codeStream) { -// codeStream.aload_0(); -// } + + // public void generateAssignment( + // BlockScope currentScope, + // CodeStream codeStream, + // Assignment assignment, + // boolean valueRequired) { + // + // generateReadSequence(currentScope, codeStream); + // assignment.expression.generateCode(currentScope, codeStream, true); + // fieldStore(codeStream, lastFieldBinding, syntheticWriteAccessor, + // valueRequired); + // // equivalent to valuesRequired[maxOtherBindings] + // if (valueRequired) { + // codeStream.generateImplicitConversion(assignment.implicitConversion); + // } + // } + // public void generateCode( + // BlockScope currentScope, + // CodeStream codeStream, + // boolean valueRequired) { + // + // int pc = codeStream.position; + // if (constant != NotAConstant) { + // if (valueRequired) { + // codeStream.generateConstant(constant, implicitConversion); + // } + // } else { + // generateReadSequence(currentScope, codeStream); + // if (valueRequired) { + // if (lastFieldBinding.declaringClass == null) { // array length + // codeStream.arraylength(); + // codeStream.generateImplicitConversion(implicitConversion); + // } else { + // if (lastFieldBinding.constant != NotAConstant) { + // if (!lastFieldBinding.isStatic()){ + // codeStream.invokeObjectGetClass(); + // codeStream.pop(); + // } + // // inline the last field constant + // codeStream.generateConstant(lastFieldBinding.constant, + // implicitConversion); + // } else { + // SyntheticAccessMethodBinding accessor = + // syntheticReadAccessors == null + // ? null + // : syntheticReadAccessors[syntheticReadAccessors.length - 1]; + // if (accessor == null) { + // if (lastFieldBinding.isStatic()) { + // codeStream.getstatic(lastFieldBinding); + // } else { + // codeStream.getfield(lastFieldBinding); + // } + // } else { + // codeStream.invokestatic(accessor); + // } + // codeStream.generateImplicitConversion(implicitConversion); + // } + // } + // } else { + // if (lastFieldBinding != null && !lastFieldBinding.isStatic()){ + // codeStream.invokeObjectGetClass(); // perform null check + // codeStream.pop(); + // } + // + // } + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } + // public void generateCompoundAssignment( + // BlockScope currentScope, + // CodeStream codeStream, + // Expression expression, + // int operator, + // int assignmentImplicitConversion, + // boolean valueRequired) { + // + // generateReadSequence(currentScope, codeStream); + // SyntheticAccessMethodBinding accessor = + // syntheticReadAccessors == null + // ? null + // : syntheticReadAccessors[syntheticReadAccessors.length - 1]; + // if (lastFieldBinding.isStatic()) { + // if (accessor == null) { + // codeStream.getstatic(lastFieldBinding); + // } else { + // codeStream.invokestatic(accessor); + // } + // } else { + // codeStream.dup(); + // if (accessor == null) { + // codeStream.getfield(lastFieldBinding); + // } else { + // codeStream.invokestatic(accessor); + // } + // } + // // the last field access is a write access + // // perform the actual compound operation + // int operationTypeID; + // if ((operationTypeID = implicitConversion >> 4) == T_String) { + // codeStream.generateStringAppend(currentScope, null, expression); + // } else { + // // promote the array reference to the suitable operation type + // codeStream.generateImplicitConversion(implicitConversion); + // // generate the increment value (will by itself be promoted to the + // operation value) + // if (expression == IntLiteral.One) { // prefix operation + // codeStream.generateConstant(expression.constant, implicitConversion); + // } else { + // expression.generateCode(currentScope, codeStream, true); + // } + // // perform the operation + // codeStream.sendOperator(operator, operationTypeID); + // // cast the value back to the array reference type + // codeStream.generateImplicitConversion(assignmentImplicitConversion); + // } + // // actual assignment + // fieldStore(codeStream, lastFieldBinding, syntheticWriteAccessor, + // valueRequired); + // // equivalent to valuesRequired[maxOtherBindings] + // } + // public void generatePostIncrement( + // BlockScope currentScope, + // CodeStream codeStream, + // CompoundAssignment postIncrement, + // boolean valueRequired) { + // generateReadSequence(currentScope, codeStream); + // SyntheticAccessMethodBinding accessor = + // syntheticReadAccessors == null + // ? null + // : syntheticReadAccessors[syntheticReadAccessors.length - 1]; + // if (lastFieldBinding.isStatic()) { + // if (accessor == null) { + // codeStream.getstatic(lastFieldBinding); + // } else { + // codeStream.invokestatic(accessor); + // } + // } else { + // codeStream.dup(); + // if (accessor == null) { + // codeStream.getfield(lastFieldBinding); + // } else { + // codeStream.invokestatic(accessor); + // } + // } + // // duplicate the old field value + // if (valueRequired) { + // if (lastFieldBinding.isStatic()) { + // if ((lastFieldBinding.type == LongBinding) + // || (lastFieldBinding.type == DoubleBinding)) { + // codeStream.dup2(); + // } else { + // codeStream.dup(); + // } + // } else { // Stack: [owner][old field value] ---> [old field + // value][owner][old field value] + // if ((lastFieldBinding.type == LongBinding) + // || (lastFieldBinding.type == DoubleBinding)) { + // codeStream.dup2_x1(); + // } else { + // codeStream.dup_x1(); + // } + // } + // } + // codeStream.generateConstant( + // postIncrement.expression.constant, + // implicitConversion); + // codeStream.sendOperator(postIncrement.operator, + // lastFieldBinding.type.id); + // codeStream.generateImplicitConversion( + // postIncrement.assignmentImplicitConversion); + // fieldStore(codeStream, lastFieldBinding, syntheticWriteAccessor, false); + // } + // /* + // * Generate code for all bindings (local and fields) excluding the last + // one, which may then be generated code + // * for a read or write access. + // */ + // public void generateReadSequence( + // BlockScope currentScope, + // CodeStream codeStream) { + // + // // determine the rank until which we now we do not need any actual value + // for the field access + // int otherBindingsCount = this.otherCodegenBindings == null ? 0 : + // otherCodegenBindings.length; + // + // boolean needValue = otherBindingsCount == 0 || + // !this.otherBindings[0].isStatic(); + // switch (bits & RestrictiveFlagMASK) { + // case FIELD : + // lastFieldBinding = (FieldBinding) this.codegenBinding; + // // if first field is actually constant, we can inline it + // if (lastFieldBinding.constant != NotAConstant) { + // break; + // } + // if (needValue && !lastFieldBinding.isStatic()) { + // if ((bits & DepthMASK) != 0) { + // ReferenceBinding targetType = + // currentScope.enclosingSourceType().enclosingTypeAt((bits & DepthMASK) >> + // DepthSHIFT); + // Object[] emulationPath = currentScope.getEmulationPath(targetType, true + // /*only exact match*/, false/*consider enclosing arg*/); + // codeStream.generateOuterAccess(emulationPath, this, targetType, + // currentScope); + // } else { + // generateReceiver(codeStream); + // } + // } + // break; + // case LOCAL : // reading the first local variable + // if (!needValue) break; // no value needed + // lastFieldBinding = null; + // LocalVariableBinding localBinding = (LocalVariableBinding) + // this.codegenBinding; + // // regular local variable read + // if (localBinding.constant != NotAConstant) { + // codeStream.generateConstant(localBinding.constant, 0); + // // no implicit conversion + // } else { + // // outer local? + // if ((bits & DepthMASK) != 0) { + // // outer local can be reached either through a synthetic arg or a + // synthetic field + // VariableBinding[] path = currentScope.getEmulationPath(localBinding); + // codeStream.generateOuterAccess(path, this, localBinding, currentScope); + // } else { + // codeStream.load(localBinding); + // } + // } + // } + // + // // all intermediate field accesses are read accesses + // // only the last field binding is a write access + // if (this.otherCodegenBindings != null) { + // for (int i = 0; i < otherBindingsCount; i++) { + // FieldBinding nextField = this.otherCodegenBindings[i]; + // if (lastFieldBinding != null) { + // needValue = !nextField.isStatic(); + // if (needValue) { + // MethodBinding accessor = + // syntheticReadAccessors == null ? null : syntheticReadAccessors[i]; + // if (accessor == null) { + // if (lastFieldBinding.constant != NotAConstant) { + // if (this.lastFieldBinding != this.codegenBinding && + // !this.lastFieldBinding.isStatic()) { + // codeStream.invokeObjectGetClass(); // perform null check + // codeStream.pop(); + // } + // codeStream.generateConstant(lastFieldBinding.constant, 0); + // } else if (lastFieldBinding.isStatic()) { + // codeStream.getstatic(lastFieldBinding); + // } else { + // codeStream.getfield(lastFieldBinding); + // } + // } else { + // codeStream.invokestatic(accessor); + // } + // } else { + // if (this.codegenBinding != this.lastFieldBinding && + // !this.lastFieldBinding.isStatic()){ + // codeStream.invokeObjectGetClass(); // perform null check + // codeStream.pop(); + // } + // } + // } + // this.lastFieldBinding = nextField; + // } + // } + // } + // public void generateReceiver(CodeStream codeStream) { + // codeStream.aload_0(); + // } public TypeBinding getOtherFieldBindings(BlockScope scope) { - // At this point restrictiveFlag may ONLY have two potential value : FIELD LOCAL (i.e cast <<(VariableBinding) binding>> is valid) + // At this point restrictiveFlag may ONLY have two potential value : + // FIELD LOCAL (i.e cast <<(VariableBinding) binding>> is valid) if ((bits & FIELD) != 0) { if (!((FieldBinding) binding).isStatic()) { - //must check for the static status.... + // must check for the static status.... if (indexOfFirstFieldBinding == 1) { - //the field is the first token of the qualified reference.... + // the field is the first token of the qualified + // reference.... if (scope.methodScope().isStatic) { - scope.problemReporter().staticFieldAccessToNonStaticVariable( - this, - (FieldBinding) binding); + scope.problemReporter() + .staticFieldAccessToNonStaticVariable(this, + (FieldBinding) binding); return null; } - } else { //accessing to a field using a type as "receiver" is allowed only with static field - scope.problemReporter().staticFieldAccessToNonStaticVariable( - this, - (FieldBinding) binding); + } else { // accessing to a field using a type as "receiver" + // is allowed only with static field + scope.problemReporter() + .staticFieldAccessToNonStaticVariable(this, + (FieldBinding) binding); return null; } } if (isFieldUseDeprecated((FieldBinding) binding, scope)) - scope.problemReporter().deprecatedField((FieldBinding) binding, this); + scope.problemReporter().deprecatedField((FieldBinding) binding, + this); } TypeBinding type = ((VariableBinding) binding).type; int index = indexOfFirstFieldBinding; int length = tokens.length; - if (index == length) { // restrictiveFlag == FIELD - this.constant = FieldReference.getConstantFor((FieldBinding) binding, this, false, scope); + if (index == length) { // restrictiveFlag == FIELD + this.constant = FieldReference.getConstantFor( + (FieldBinding) binding, this, false, scope); return type; } - // allocation of the fieldBindings array and its respective constants + // allocation of the fieldBindings array and its respective constants int otherBindingsLength = length - index; otherCodegenBindings = otherBindings = new FieldBinding[otherBindingsLength]; otherDepths = new int[otherBindingsLength]; - + // fill the first constant (the one of the binding) - this.constant = - ((bits & FIELD) != 0) - ? FieldReference.getConstantFor((FieldBinding) binding, this, false, scope) + this.constant = ((bits & FIELD) != 0) ? FieldReference.getConstantFor( + (FieldBinding) binding, this, false, scope) : ((VariableBinding) binding).constant; - // save first depth, since will be updated by visibility checks of other bindings + // save first depth, since will be updated by visibility checks of other + // bindings int firstDepth = (bits & DepthMASK) >> DepthSHIFT; - // iteration on each field + // iteration on each field while (index < length) { char[] token = tokens[index]; if (type == null) return null; // could not resolve type prior to this point - bits &= ~DepthMASK; // flush previous depth if any + bits &= ~DepthMASK; // flush previous depth if any FieldBinding field = scope.getField(type, token, this); int place = index - indexOfFirstFieldBinding; otherBindings[place] = field; @@ -566,22 +604,27 @@ public class QualifiedNameReference extends NameReference { if (field.isValidBinding()) { if (isFieldUseDeprecated(field, scope)) scope.problemReporter().deprecatedField(field, this); - Constant someConstant = FieldReference.getConstantFor(field, this, false, scope); - // constant propagation can only be performed as long as the previous one is a constant too. + Constant someConstant = FieldReference.getConstantFor(field, + this, false, scope); + // constant propagation can only be performed as long as the + // previous one is a constant too. if (this.constant != NotAConstant) { - this.constant = someConstant; + this.constant = someConstant; } type = field.type; index++; - + if (field.isStatic()) { - // static field accessed through receiver? legal but unoptimal (optional warning) - scope.problemReporter().unnecessaryReceiverForStaticField(this, field); + // static field accessed through receiver? legal but + // unoptimal (optional warning) + scope.problemReporter().unnecessaryReceiverForStaticField( + this, field); } - + } else { - constant = NotAConstant; //don't fill other constants slots... + constant = NotAConstant; // don't fill other constants + // slots... scope.problemReporter().invalidField(this, field, index, type); setDepth(firstDepth); return null; @@ -590,8 +633,10 @@ public class QualifiedNameReference extends NameReference { setDepth(firstDepth); return (otherBindings[otherBindingsLength - 1]).type; } + public void manageEnclosingInstanceAccessIfNecessary(BlockScope currentScope) { - //If inlinable field, forget the access emulation, the code gen will directly target it + // If inlinable field, forget the access emulation, the code gen will + // directly target it if (((bits & DepthMASK) == 0) || (constant != NotAConstant)) { return; } @@ -599,117 +644,146 @@ public class QualifiedNameReference extends NameReference { currentScope.emulateOuterAccess((LocalVariableBinding) binding); } } - public void manageSyntheticReadAccessIfNecessary( - BlockScope currentScope, - FieldBinding fieldBinding, - TypeBinding lastReceiverType, - int index) { - // index == 0 denotes the first fieldBinding, index > 0 denotes one of the 'otherBindings' + + public void manageSyntheticReadAccessIfNecessary(BlockScope currentScope, + FieldBinding fieldBinding, TypeBinding lastReceiverType, int index) { + // index == 0 denotes the first fieldBinding, index > 0 denotes one of + // the 'otherBindings' if (fieldBinding.constant != NotAConstant) return; if (fieldBinding.isPrivate()) { // private access - if (fieldBinding.declaringClass != currentScope.enclosingSourceType()) { + if (fieldBinding.declaringClass != currentScope + .enclosingSourceType()) { if (syntheticReadAccessors == null) { if (otherBindings == null) syntheticReadAccessors = new SyntheticAccessMethodBinding[1]; else - syntheticReadAccessors = - new SyntheticAccessMethodBinding[otherBindings.length + 1]; + syntheticReadAccessors = new SyntheticAccessMethodBinding[otherBindings.length + 1]; } - syntheticReadAccessors[index] = ((SourceTypeBinding) fieldBinding.declaringClass).addSyntheticMethod(fieldBinding, true); - currentScope.problemReporter().needToEmulateFieldReadAccess(fieldBinding, this); + syntheticReadAccessors[index] = ((SourceTypeBinding) fieldBinding.declaringClass) + .addSyntheticMethod(fieldBinding, true); + currentScope.problemReporter().needToEmulateFieldReadAccess( + fieldBinding, this); return; } - } else if (fieldBinding.isProtected()){ - int depth = index == 0 ? (bits & DepthMASK) >> DepthSHIFT : otherDepths[index-1]; + } else if (fieldBinding.isProtected()) { + int depth = index == 0 ? (bits & DepthMASK) >> DepthSHIFT + : otherDepths[index - 1]; // implicit protected access (only for first one) - if (depth > 0 && (fieldBinding.declaringClass.getPackage() - != currentScope.enclosingSourceType().getPackage())) { + if (depth > 0 + && (fieldBinding.declaringClass.getPackage() != currentScope + .enclosingSourceType().getPackage())) { if (syntheticReadAccessors == null) { if (otherBindings == null) syntheticReadAccessors = new SyntheticAccessMethodBinding[1]; else - syntheticReadAccessors = - new SyntheticAccessMethodBinding[otherBindings.length + 1]; + syntheticReadAccessors = new SyntheticAccessMethodBinding[otherBindings.length + 1]; } - syntheticReadAccessors[index] = - ((SourceTypeBinding) currentScope.enclosingSourceType().enclosingTypeAt(depth)) - .addSyntheticMethod(fieldBinding, true); - currentScope.problemReporter().needToEmulateFieldReadAccess(fieldBinding, this); + syntheticReadAccessors[index] = ((SourceTypeBinding) currentScope + .enclosingSourceType().enclosingTypeAt(depth)) + .addSyntheticMethod(fieldBinding, true); + currentScope.problemReporter().needToEmulateFieldReadAccess( + fieldBinding, this); return; } } // if the binding declaring class is not visible, need special action - // for runtime compatibility on 1.2 VMs : change the declaring class of the binding - // NOTE: from target 1.2 on, field's declaring class is touched if any different from receiver type -// if (fieldBinding.declaringClass != lastReceiverType -// && !lastReceiverType.isArrayType() -// && fieldBinding.declaringClass != null -// && fieldBinding.constant == NotAConstant -// && ((currentScope.environment().options.targetJDK >= CompilerOptions.JDK1_2 -// && (index > 0 || indexOfFirstFieldBinding > 1 || !fieldBinding.isStatic()) -// && fieldBinding.declaringClass.id != T_Object) -// || !fieldBinding.declaringClass.canBeSeenBy(currentScope))){ -// if (index == 0){ -// this.codegenBinding = currentScope.enclosingSourceType().getUpdatedFieldBinding(fieldBinding, (ReferenceBinding)lastReceiverType); -// } else { -// if (this.otherCodegenBindings == this.otherBindings){ -// int l = this.otherBindings.length; -// System.arraycopy(this.otherBindings, 0, this.otherCodegenBindings = new FieldBinding[l], 0, l); -// } -// this.otherCodegenBindings[index-1] = currentScope.enclosingSourceType().getUpdatedFieldBinding(fieldBinding, (ReferenceBinding)lastReceiverType); -// } -// } + // for runtime compatibility on 1.2 VMs : change the declaring class of + // the binding + // NOTE: from target 1.2 on, field's declaring class is touched if any + // different from receiver type + // if (fieldBinding.declaringClass != lastReceiverType + // && !lastReceiverType.isArrayType() + // && fieldBinding.declaringClass != null + // && fieldBinding.constant == NotAConstant + // && ((currentScope.environment().options.targetJDK >= + // CompilerOptions.JDK1_2 + // && (index > 0 || indexOfFirstFieldBinding > 1 || + // !fieldBinding.isStatic()) + // && fieldBinding.declaringClass.id != T_Object) + // || !fieldBinding.declaringClass.canBeSeenBy(currentScope))){ + // if (index == 0){ + // this.codegenBinding = + // currentScope.enclosingSourceType().getUpdatedFieldBinding(fieldBinding, + // (ReferenceBinding)lastReceiverType); + // } else { + // if (this.otherCodegenBindings == this.otherBindings){ + // int l = this.otherBindings.length; + // System.arraycopy(this.otherBindings, 0, this.otherCodegenBindings = + // new FieldBinding[l], 0, l); + // } + // this.otherCodegenBindings[index-1] = + // currentScope.enclosingSourceType().getUpdatedFieldBinding(fieldBinding, + // (ReferenceBinding)lastReceiverType); + // } + // } } + /* - * No need to emulate access to protected fields since not implicitly accessed + * No need to emulate access to protected fields since not implicitly + * accessed */ - public void manageSyntheticWriteAccessIfNecessary( - BlockScope currentScope, - FieldBinding fieldBinding, - TypeBinding lastReceiverType) { + public void manageSyntheticWriteAccessIfNecessary(BlockScope currentScope, + FieldBinding fieldBinding, TypeBinding lastReceiverType) { if (fieldBinding.isPrivate()) { - if (fieldBinding.declaringClass != currentScope.enclosingSourceType()) { + if (fieldBinding.declaringClass != currentScope + .enclosingSourceType()) { syntheticWriteAccessor = ((SourceTypeBinding) fieldBinding.declaringClass) - .addSyntheticMethod(fieldBinding, false); - currentScope.problemReporter().needToEmulateFieldWriteAccess(fieldBinding, this); + .addSyntheticMethod(fieldBinding, false); + currentScope.problemReporter().needToEmulateFieldWriteAccess( + fieldBinding, this); return; } - } else if (fieldBinding.isProtected()){ - int depth = fieldBinding == binding ? (bits & DepthMASK) >> DepthSHIFT : otherDepths[otherDepths.length-1]; - if (depth > 0 && (fieldBinding.declaringClass.getPackage() - != currentScope.enclosingSourceType().getPackage())) { - syntheticWriteAccessor = ((SourceTypeBinding) currentScope.enclosingSourceType().enclosingTypeAt(depth)) - .addSyntheticMethod(fieldBinding, false); - currentScope.problemReporter().needToEmulateFieldWriteAccess(fieldBinding, this); + } else if (fieldBinding.isProtected()) { + int depth = fieldBinding == binding ? (bits & DepthMASK) >> DepthSHIFT + : otherDepths[otherDepths.length - 1]; + if (depth > 0 + && (fieldBinding.declaringClass.getPackage() != currentScope + .enclosingSourceType().getPackage())) { + syntheticWriteAccessor = ((SourceTypeBinding) currentScope + .enclosingSourceType().enclosingTypeAt(depth)) + .addSyntheticMethod(fieldBinding, false); + currentScope.problemReporter().needToEmulateFieldWriteAccess( + fieldBinding, this); return; } } // if the binding declaring class is not visible, need special action - // for runtime compatibility on 1.2 VMs : change the declaring class of the binding - // NOTE: from target 1.2 on, field's declaring class is touched if any different from receiver type -// if (fieldBinding.declaringClass != lastReceiverType -// && !lastReceiverType.isArrayType() -// && fieldBinding.declaringClass != null -// && fieldBinding.constant == NotAConstant -// && ((currentScope.environment().options.targetJDK >= CompilerOptions.JDK1_2 -// && (fieldBinding != binding || indexOfFirstFieldBinding > 1 || !fieldBinding.isStatic()) -// && fieldBinding.declaringClass.id != T_Object) -// || !fieldBinding.declaringClass.canBeSeenBy(currentScope))){ -// if (fieldBinding == binding){ -// this.codegenBinding = currentScope.enclosingSourceType().getUpdatedFieldBinding(fieldBinding, (ReferenceBinding)lastReceiverType); -// } else { -// if (this.otherCodegenBindings == this.otherBindings){ -// int l = this.otherBindings.length; -// System.arraycopy(this.otherBindings, 0, this.otherCodegenBindings = new FieldBinding[l], 0, l); -// } -// this.otherCodegenBindings[this.otherCodegenBindings.length-1] = currentScope.enclosingSourceType().getUpdatedFieldBinding(fieldBinding, (ReferenceBinding)lastReceiverType); -// } -// } - + // for runtime compatibility on 1.2 VMs : change the declaring class of + // the binding + // NOTE: from target 1.2 on, field's declaring class is touched if any + // different from receiver type + // if (fieldBinding.declaringClass != lastReceiverType + // && !lastReceiverType.isArrayType() + // && fieldBinding.declaringClass != null + // && fieldBinding.constant == NotAConstant + // && ((currentScope.environment().options.targetJDK >= + // CompilerOptions.JDK1_2 + // && (fieldBinding != binding || indexOfFirstFieldBinding > 1 || + // !fieldBinding.isStatic()) + // && fieldBinding.declaringClass.id != T_Object) + // || !fieldBinding.declaringClass.canBeSeenBy(currentScope))){ + // if (fieldBinding == binding){ + // this.codegenBinding = + // currentScope.enclosingSourceType().getUpdatedFieldBinding(fieldBinding, + // (ReferenceBinding)lastReceiverType); + // } else { + // if (this.otherCodegenBindings == this.otherBindings){ + // int l = this.otherBindings.length; + // System.arraycopy(this.otherBindings, 0, this.otherCodegenBindings = + // new FieldBinding[l], 0, l); + // } + // this.otherCodegenBindings[this.otherCodegenBindings.length-1] = + // currentScope.enclosingSourceType().getUpdatedFieldBinding(fieldBinding, + // (ReferenceBinding)lastReceiverType); + // } + // } + } + /** - * Normal field binding did not work, try to bind to a field of the delegate receiver. + * Normal field binding did not work, try to bind to a field of the delegate + * receiver. */ public TypeBinding reportError(BlockScope scope) { if (binding instanceof ProblemFieldBinding) { @@ -721,72 +795,82 @@ public class QualifiedNameReference extends NameReference { } return null; } + public StringBuffer printExpression(int indent, StringBuffer output) { - + for (int i = 0; i < tokens.length; i++) { - if (i > 0) output.append('.'); + if (i > 0) + output.append('.'); output.append(tokens[i]); } return output; } + public TypeBinding resolveType(BlockScope scope) { // field and/or local are done before type lookups // the only available value for the restrictiveFlag BEFORE - // the TC is Flag_Type Flag_LocalField and Flag_TypeLocalField - this.actualReceiverType = this.receiverType = scope.enclosingSourceType(); + // the TC is Flag_Type Flag_LocalField and Flag_TypeLocalField + this.actualReceiverType = this.receiverType = scope + .enclosingSourceType(); constant = Constant.NotAConstant; - if ((this.codegenBinding = this.binding = scope.getBinding(tokens, bits & RestrictiveFlagMASK, this)) - .isValidBinding()) { + if ((this.codegenBinding = this.binding = scope.getBinding(tokens, bits + & RestrictiveFlagMASK, this)).isValidBinding()) { switch (bits & RestrictiveFlagMASK) { - case VARIABLE : //============only variable=========== - case TYPE | VARIABLE : - if (binding instanceof LocalVariableBinding) { - if (!((LocalVariableBinding) binding).isFinal() && ((bits & DepthMASK) != 0)) - scope.problemReporter().cannotReferToNonFinalOuterLocal( - (LocalVariableBinding) binding, - this); - bits &= ~RestrictiveFlagMASK; // clear bits - bits |= LOCAL; - return this.resolvedType = getOtherFieldBindings(scope); - } - if (binding instanceof FieldBinding) { - // check for forward references - FieldBinding fieldBinding = (FieldBinding) binding; - MethodScope methodScope = scope.methodScope(); - if (methodScope.enclosingSourceType() == fieldBinding.declaringClass + case VARIABLE: // ============only variable=========== + case TYPE | VARIABLE: + if (binding instanceof LocalVariableBinding) { + if (!((LocalVariableBinding) binding).isFinal() + && ((bits & DepthMASK) != 0)) + scope.problemReporter() + .cannotReferToNonFinalOuterLocal( + (LocalVariableBinding) binding, this); + bits &= ~RestrictiveFlagMASK; // clear bits + bits |= LOCAL; + return this.resolvedType = getOtherFieldBindings(scope); + } + if (binding instanceof FieldBinding) { + // check for forward references + FieldBinding fieldBinding = (FieldBinding) binding; + MethodScope methodScope = scope.methodScope(); + if (methodScope.enclosingSourceType() == fieldBinding.declaringClass && methodScope.fieldDeclarationIndex != MethodScope.NotInFieldDecl && fieldBinding.id >= methodScope.fieldDeclarationIndex) { - if ((!fieldBinding.isStatic() || methodScope.isStatic) + if ((!fieldBinding.isStatic() || methodScope.isStatic) && this.indexOfFirstFieldBinding == 1) - scope.problemReporter().forwardReference(this, 0, scope.enclosingSourceType()); - } - bits &= ~RestrictiveFlagMASK; // clear bits - bits |= FIELD; - - // check for deprecated receiver type - // deprecation check for receiver type if not first token - if (indexOfFirstFieldBinding > 1) { - if (isTypeUseDeprecated(this.actualReceiverType, scope)) - scope.problemReporter().deprecatedType(this.actualReceiverType, this); - } - - return this.resolvedType = getOtherFieldBindings(scope); + scope.problemReporter().forwardReference(this, 0, + scope.enclosingSourceType()); } - // thus it was a type bits &= ~RestrictiveFlagMASK; // clear bits - bits |= TYPE; - case TYPE : //=============only type ============== - if (isTypeUseDeprecated((TypeBinding) binding, scope)) - scope.problemReporter().deprecatedType((TypeBinding) binding, this); - return this.resolvedType = (TypeBinding) binding; + bits |= FIELD; + + // check for deprecated receiver type + // deprecation check for receiver type if not first token + if (indexOfFirstFieldBinding > 1) { + if (isTypeUseDeprecated(this.actualReceiverType, scope)) + scope.problemReporter().deprecatedType( + this.actualReceiverType, this); + } + + return this.resolvedType = getOtherFieldBindings(scope); + } + // thus it was a type + bits &= ~RestrictiveFlagMASK; // clear bits + bits |= TYPE; + case TYPE: // =============only type ============== + if (isTypeUseDeprecated((TypeBinding) binding, scope)) + scope.problemReporter().deprecatedType( + (TypeBinding) binding, this); + return this.resolvedType = (TypeBinding) binding; } } - //========error cases=============== + // ========error cases=============== return this.resolvedType = this.reportError(scope); } + public void setFieldIndex(int index) { this.indexOfFirstFieldBinding = index; } + public String toStringExpression() { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < tokens.length; i++) { @@ -797,10 +881,12 @@ public class QualifiedNameReference extends NameReference { } return buffer.toString(); } + public void traverse(IAbstractSyntaxTreeVisitor visitor, BlockScope scope) { visitor.visit(this, scope); visitor.endVisit(this, scope); } + public String unboundReferenceErrorName() { return new String(tokens[0]); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/QualifiedSuperReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/QualifiedSuperReference.java index c3a35aa..889dcac 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/QualifiedSuperReference.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/QualifiedSuperReference.java @@ -15,7 +15,7 @@ import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class QualifiedSuperReference extends QualifiedThisReference { - + public QualifiedSuperReference(TypeReference name, int pos, int sourceEnd) { super(name, pos, sourceEnd); } @@ -52,9 +52,7 @@ public class QualifiedSuperReference extends QualifiedThisReference { return qualification.toString(0) + ".super"; //$NON-NLS-1$ } - public void traverse( - ASTVisitor visitor, - BlockScope blockScope) { + public void traverse(ASTVisitor visitor, BlockScope blockScope) { if (visitor.visit(this, blockScope)) { qualification.traverse(visitor, blockScope); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/QualifiedThisReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/QualifiedThisReference.java index 5dd3156..0d8c060 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/QualifiedThisReference.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/QualifiedThisReference.java @@ -18,79 +18,83 @@ import net.sourceforge.phpdt.internal.compiler.lookup.ReferenceBinding; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class QualifiedThisReference extends ThisReference { - + public TypeReference qualification; + ReferenceBinding currentCompatibleType; - - public QualifiedThisReference(TypeReference name, int sourceStart, int sourceEnd) { + + public QualifiedThisReference(TypeReference name, int sourceStart, + int sourceEnd) { super(sourceStart, sourceEnd); qualification = name; this.sourceStart = name.sourceStart; } - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { return flowInfo; } - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo, - boolean valueRequired) { + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo, boolean valueRequired) { return flowInfo; } /** * Code generation for QualifiedThisReference - * - * @param currentScope net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream - * @param valueRequired boolean + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * @param valueRequired + * boolean */ -// public void generateCode( -// BlockScope currentScope, -// CodeStream codeStream, -// boolean valueRequired) { -// -// int pc = codeStream.position; -// if (valueRequired) { -// if ((bits & DepthMASK) != 0) { -// Object[] emulationPath = -// currentScope.getEmulationPath(this.currentCompatibleType, true /*only exact match*/, false/*consider enclosing arg*/); -// codeStream.generateOuterAccess(emulationPath, this, this.currentCompatibleType, currentScope); -// } else { -// // nothing particular after all -// codeStream.aload_0(); -// } -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } - + // public void generateCode( + // BlockScope currentScope, + // CodeStream codeStream, + // boolean valueRequired) { + // + // int pc = codeStream.position; + // if (valueRequired) { + // if ((bits & DepthMASK) != 0) { + // Object[] emulationPath = + // currentScope.getEmulationPath(this.currentCompatibleType, true /*only + // exact match*/, false/*consider enclosing arg*/); + // codeStream.generateOuterAccess(emulationPath, this, + // this.currentCompatibleType, currentScope); + // } else { + // // nothing particular after all + // codeStream.aload_0(); + // } + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } public TypeBinding resolveType(BlockScope scope) { constant = NotAConstant; this.resolvedType = qualification.resolveType(scope); - if (this.resolvedType == null) return null; + if (this.resolvedType == null) + return null; // the qualification MUST exactly match some enclosing type name // Its possible to qualify 'this' by the name of the current class int depth = 0; this.currentCompatibleType = scope.referenceType().binding; while (this.currentCompatibleType != null - && this.currentCompatibleType != this.resolvedType) { + && this.currentCompatibleType != this.resolvedType) { depth++; - this.currentCompatibleType = this.currentCompatibleType.isStatic() ? null : this.currentCompatibleType.enclosingType(); + this.currentCompatibleType = this.currentCompatibleType.isStatic() ? null + : this.currentCompatibleType.enclosingType(); } - bits &= ~DepthMASK; // flush previous depth if any + bits &= ~DepthMASK; // flush previous depth if any bits |= (depth & 0xFF) << DepthSHIFT; // encoded depth into 8 bits if (this.currentCompatibleType == null) { - scope.problemReporter().noSuchEnclosingInstance(this.resolvedType, this, false); + scope.problemReporter().noSuchEnclosingInstance(this.resolvedType, + this, false); return this.resolvedType; } @@ -106,9 +110,7 @@ public class QualifiedThisReference extends ThisReference { return qualification.toString(0) + ".this"; //$NON-NLS-1$ } - public void traverse( - ASTVisitor visitor, - BlockScope blockScope) { + public void traverse(ASTVisitor visitor, BlockScope blockScope) { if (visitor.visit(this, blockScope)) { qualification.traverse(visitor, blockScope); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/QualifiedTypeReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/QualifiedTypeReference.java index 102804e..1cc409c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/QualifiedTypeReference.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/QualifiedTypeReference.java @@ -18,56 +18,69 @@ import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class QualifiedTypeReference extends TypeReference { public char[][] tokens; + public long[] sourcePositions; -public QualifiedTypeReference(char[][] sources , long[] poss) { - tokens = sources ; - sourcePositions = poss ; - sourceStart = (int) (sourcePositions[0]>>>32) ; - sourceEnd = (int)(sourcePositions[sourcePositions.length-1] & 0x00000000FFFFFFFFL ) ; -} -public QualifiedTypeReference(char[][] sources , TypeBinding type , long[] poss) { - this(sources,poss); - this.resolvedType = type; -} -public TypeReference copyDims(int dim){ - //return a type reference copy of me with some dimensions - //warning : the new type ref has a null binding - - return new ArrayQualifiedTypeReference(tokens,null,dim,sourcePositions) ; -} -public TypeBinding getTypeBinding(Scope scope) { - if (this.resolvedType != null) - return this.resolvedType; - return scope.getType(tokens); -} -public char[][] getTypeName(){ - return tokens; -} -public StringBuffer printExpression(int indent, StringBuffer output) { - - for (int i = 0; i < tokens.length; i++) { - if (i > 0) output.append('.'); - output.append(tokens[i]); + public QualifiedTypeReference(char[][] sources, long[] poss) { + tokens = sources; + sourcePositions = poss; + sourceStart = (int) (sourcePositions[0] >>> 32); + sourceEnd = (int) (sourcePositions[sourcePositions.length - 1] & 0x00000000FFFFFFFFL); } - return output; -} -public String toStringExpression(int tab) { - StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < tokens.length; i++) { - buffer.append(tokens[i]); - if (i < (tokens.length - 1)) { - buffer.append("."); //$NON-NLS-1$ + + public QualifiedTypeReference(char[][] sources, TypeBinding type, + long[] poss) { + this(sources, poss); + this.resolvedType = type; + } + + public TypeReference copyDims(int dim) { + // return a type reference copy of me with some dimensions + // warning : the new type ref has a null binding + + return new ArrayQualifiedTypeReference(tokens, null, dim, + sourcePositions); + } + + public TypeBinding getTypeBinding(Scope scope) { + if (this.resolvedType != null) + return this.resolvedType; + return scope.getType(tokens); + } + + public char[][] getTypeName() { + + return tokens; + } + + public StringBuffer printExpression(int indent, StringBuffer output) { + + for (int i = 0; i < tokens.length; i++) { + if (i > 0) + output.append('.'); + output.append(tokens[i]); } + return output; + } + + public String toStringExpression(int tab) { + StringBuffer buffer = new StringBuffer(); + for (int i = 0; i < tokens.length; i++) { + buffer.append(tokens[i]); + if (i < (tokens.length - 1)) { + buffer.append("."); //$NON-NLS-1$ + } + } + return buffer.toString(); + } + + public void traverse(ASTVisitor visitor, BlockScope scope) { + visitor.visit(this, scope); + visitor.endVisit(this, scope); + } + + public void traverse(ASTVisitor visitor, ClassScope scope) { + visitor.visit(this, scope); + visitor.endVisit(this, scope); } - return buffer.toString(); -} -public void traverse(ASTVisitor visitor, BlockScope scope) { - visitor.visit(this, scope); - visitor.endVisit(this, scope); -} -public void traverse(ASTVisitor visitor, ClassScope scope) { - visitor.visit(this, scope); - visitor.endVisit(this, scope); -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Reference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Reference.java index 035cee0..e7a1519 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Reference.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Reference.java @@ -15,57 +15,71 @@ import net.sourceforge.phpdt.internal.compiler.flow.FlowInfo; import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; import net.sourceforge.phpdt.internal.compiler.lookup.FieldBinding; -public abstract class Reference extends Expression { -/** - * BaseLevelReference constructor comment. - */ -public Reference() { - super(); -} -public abstract FlowInfo analyseAssignment(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo, Assignment assignment, boolean isCompound); +public abstract class Reference extends Expression { + /** + * BaseLevelReference constructor comment. + */ + public Reference() { + super(); + } -public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { - return flowInfo; -} -public FieldBinding fieldBinding() { - //this method should be sent one FIELD-tagged references - // (ref.bits & BindingIds.FIELD != 0)() - return null ; -} -//public void fieldStore(CodeStream codeStream, FieldBinding fieldBinding, MethodBinding syntheticWriteAccessor, boolean valueRequired) { -// -// if (fieldBinding.isStatic()) { -// if (valueRequired) { -// if ((fieldBinding.type == LongBinding) || (fieldBinding.type == DoubleBinding)) { -// codeStream.dup2(); -// } else { -// codeStream.dup(); -// } -// } -// if (syntheticWriteAccessor == null) { -// codeStream.putstatic(fieldBinding); -// } else { -// codeStream.invokestatic(syntheticWriteAccessor); -// } -// } else { // Stack: [owner][new field value] ---> [new field value][owner][new field value] -// if (valueRequired) { -// if ((fieldBinding.type == LongBinding) || (fieldBinding.type == DoubleBinding)) { -// codeStream.dup2_x1(); -// } else { -// codeStream.dup_x1(); -// } -// } -// if (syntheticWriteAccessor == null) { -// codeStream.putfield(fieldBinding); -// } else { -// codeStream.invokestatic(syntheticWriteAccessor); -// } -// } -//} -//public abstract void generateAssignment(BlockScope currentScope, CodeStream codeStream, Assignment assignment, boolean valueRequired); -// -//public abstract void generateCompoundAssignment(BlockScope currentScope, CodeStream codeStream, Expression expression, int operator, int assignmentImplicitConversion, boolean valueRequired); -// -//public abstract void generatePostIncrement(BlockScope currentScope, CodeStream codeStream, CompoundAssignment postIncrement, boolean valueRequired); + public abstract FlowInfo analyseAssignment(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo, Assignment assignment, + boolean isCompound); + + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { + return flowInfo; + } + + public FieldBinding fieldBinding() { + // this method should be sent one FIELD-tagged references + // (ref.bits & BindingIds.FIELD != 0)() + return null; + } + // public void fieldStore(CodeStream codeStream, FieldBinding fieldBinding, + // MethodBinding syntheticWriteAccessor, boolean valueRequired) { + // + // if (fieldBinding.isStatic()) { + // if (valueRequired) { + // if ((fieldBinding.type == LongBinding) || (fieldBinding.type == + // DoubleBinding)) { + // codeStream.dup2(); + // } else { + // codeStream.dup(); + // } + // } + // if (syntheticWriteAccessor == null) { + // codeStream.putstatic(fieldBinding); + // } else { + // codeStream.invokestatic(syntheticWriteAccessor); + // } + // } else { // Stack: [owner][new field value] ---> [new field + // value][owner][new field value] + // if (valueRequired) { + // if ((fieldBinding.type == LongBinding) || (fieldBinding.type == + // DoubleBinding)) { + // codeStream.dup2_x1(); + // } else { + // codeStream.dup_x1(); + // } + // } + // if (syntheticWriteAccessor == null) { + // codeStream.putfield(fieldBinding); + // } else { + // codeStream.invokestatic(syntheticWriteAccessor); + // } + // } + // } + // public abstract void generateAssignment(BlockScope currentScope, + // CodeStream codeStream, Assignment assignment, boolean valueRequired); + // + // public abstract void generateCompoundAssignment(BlockScope currentScope, + // CodeStream codeStream, Expression expression, int operator, int + // assignmentImplicitConversion, boolean valueRequired); + // + // public abstract void generatePostIncrement(BlockScope currentScope, + // CodeStream codeStream, CompoundAssignment postIncrement, boolean + // valueRequired); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ReturnStatement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ReturnStatement.java index 149f034..f92c358 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ReturnStatement.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ReturnStatement.java @@ -18,248 +18,272 @@ import net.sourceforge.phpdt.internal.compiler.lookup.MethodScope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class ReturnStatement extends Statement { - public Expression expression; + public Expression expression; - public TypeBinding expressionType; + public TypeBinding expressionType; - public boolean isSynchronized; + public boolean isSynchronized; - public ASTNode[] subroutines; + public ASTNode[] subroutines; - public LocalVariableBinding saveValueVariable; + public LocalVariableBinding saveValueVariable; - public ReturnStatement(Expression expr, int s, int e) { - sourceStart = s; - sourceEnd = e; - expression = expr; - } + public ReturnStatement(Expression expr, int s, int e) { + sourceStart = s; + sourceEnd = e; + expression = expr; + } - public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { // here requires to generate a - // sequence of finally blocks - // invocations depending - // corresponding - // to each of the traversed try statements, so that execution will terminate properly. + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { // here requires to + // generate a + // sequence of finally blocks + // invocations depending + // corresponding + // to each of the traversed try statements, so that execution will + // terminate properly. - // lookup the label, this should answer the returnContext + // lookup the label, this should answer the returnContext - if (expression != null) { - flowInfo = expression.analyseCode(currentScope, flowContext, flowInfo); - } - // compute the return sequence (running the finally blocks) - FlowContext traversedContext = flowContext; - int subIndex = 0, maxSub = 5; - boolean saveValueNeeded = false; - boolean hasValueToSave = expression != null && expression.constant == NotAConstant; - do { - ASTNode sub; - if ((sub = traversedContext.subRoutine()) != null) { - if (this.subroutines == null) { - this.subroutines = new ASTNode[maxSub]; - } - if (subIndex == maxSub) { - System.arraycopy(this.subroutines, 0, (this.subroutines = new ASTNode[maxSub *= 2]), 0, subIndex); // grow - } - this.subroutines[subIndex++] = sub; - if (sub.cannotReturn()) { - saveValueNeeded = false; - break; - } - } - traversedContext.recordReturnFrom(flowInfo.unconditionalInits()); + if (expression != null) { + flowInfo = expression.analyseCode(currentScope, flowContext, + flowInfo); + } + // compute the return sequence (running the finally blocks) + FlowContext traversedContext = flowContext; + int subIndex = 0, maxSub = 5; + boolean saveValueNeeded = false; + boolean hasValueToSave = expression != null + && expression.constant == NotAConstant; + do { + ASTNode sub; + if ((sub = traversedContext.subRoutine()) != null) { + if (this.subroutines == null) { + this.subroutines = new ASTNode[maxSub]; + } + if (subIndex == maxSub) { + System.arraycopy(this.subroutines, 0, + (this.subroutines = new ASTNode[maxSub *= 2]), 0, + subIndex); // grow + } + this.subroutines[subIndex++] = sub; + if (sub.cannotReturn()) { + saveValueNeeded = false; + break; + } + } + traversedContext.recordReturnFrom(flowInfo.unconditionalInits()); - ASTNode node = traversedContext.associatedNode; -// if ((node = traversedContext.associatedNode) instanceof SynchronizedStatement) { -// isSynchronized = true; -// -// } else - if (node instanceof TryStatement) { - TryStatement tryStatement = (TryStatement) node; - flowInfo.addInitializationsFrom(tryStatement.subRoutineInits); // collect inits - if (hasValueToSave) { - if (this.saveValueVariable == null) { // closest subroutine secret variable is used - prepareSaveValueLocation(tryStatement); - } - saveValueNeeded = true; - } + ASTNode node = traversedContext.associatedNode; + // if ((node = traversedContext.associatedNode) instanceof + // SynchronizedStatement) { + // isSynchronized = true; + // + // } else + if (node instanceof TryStatement) { + TryStatement tryStatement = (TryStatement) node; + flowInfo.addInitializationsFrom(tryStatement.subRoutineInits); // collect + // inits + if (hasValueToSave) { + if (this.saveValueVariable == null) { // closest + // subroutine secret + // variable is used + prepareSaveValueLocation(tryStatement); + } + saveValueNeeded = true; + } - } else if (traversedContext instanceof InitializationFlowContext) { - currentScope.problemReporter().cannotReturnInInitializer(this); - return FlowInfo.DEAD_END; - } - } while ((traversedContext = traversedContext.parent) != null); + } else if (traversedContext instanceof InitializationFlowContext) { + currentScope.problemReporter().cannotReturnInInitializer(this); + return FlowInfo.DEAD_END; + } + } while ((traversedContext = traversedContext.parent) != null); - // resize subroutines - if ((subroutines != null) && (subIndex != maxSub)) { - System.arraycopy(subroutines, 0, (subroutines = new ASTNode[subIndex]), 0, subIndex); - } + // resize subroutines + if ((subroutines != null) && (subIndex != maxSub)) { + System.arraycopy(subroutines, 0, + (subroutines = new ASTNode[subIndex]), 0, subIndex); + } - // secret local variable for return value (note that this can only occur in a real method) - if (saveValueNeeded) { - if (this.saveValueVariable != null) { - this.saveValueVariable.useFlag = LocalVariableBinding.USED; - } - } else { - this.saveValueVariable = null; - if ((!isSynchronized) && (expressionType == BooleanBinding)) { - this.expression.bits |= ValueForReturnMASK; - } - } - return FlowInfo.DEAD_END; - } + // secret local variable for return value (note that this can only occur + // in a real method) + if (saveValueNeeded) { + if (this.saveValueVariable != null) { + this.saveValueVariable.useFlag = LocalVariableBinding.USED; + } + } else { + this.saveValueVariable = null; + if ((!isSynchronized) && (expressionType == BooleanBinding)) { + this.expression.bits |= ValueForReturnMASK; + } + } + return FlowInfo.DEAD_END; + } - /** - * Retrun statement code generation - * - * generate the finallyInvocationSequence. - * - * @param currentScope - * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream - * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream - */ - //public void generateCode(BlockScope currentScope, CodeStream codeStream) { - // if ((bits & IsReachableMASK) == 0) { - // return; - // } - // int pc = codeStream.position; - // // generate the expression - // if ((expression != null) && (expression.constant == NotAConstant)) { - // expression.generateCode(currentScope, codeStream, needValue()); // no value needed if non-returning subroutine - // generateStoreSaveValueIfNecessary(codeStream); - // } - // - // // generation of code responsible for invoking the finally blocks in sequence - // if (subroutines != null) { - // for (int i = 0, max = subroutines.length; i < max; i++) { - // ASTNode sub; - // if ((sub = subroutines[i]) instanceof SynchronizedStatement) { - // codeStream.load(((SynchronizedStatement) sub).synchroVariable); - // codeStream.monitorexit(); - // } else { - // TryStatement trySub = (TryStatement) sub; - // if (trySub.subRoutineCannotReturn) { - // codeStream.goto_(trySub.subRoutineStartLabel); - // codeStream.recordPositionsFrom(pc, this.sourceStart); - // return; - // } else { - // codeStream.jsr(trySub.subRoutineStartLabel); - // } - // } - // } - // } - // if (saveValueVariable != null) codeStream.load(saveValueVariable); - // - // if ((expression != null) && (expression.constant != NotAConstant)) { - // codeStream.generateConstant(expression.constant, expression.implicitConversion); - // generateStoreSaveValueIfNecessary(codeStream); - // } - // // output the suitable return bytecode or wrap the value inside a descriptor for doits - // this.generateReturnBytecode(codeStream); - // - // codeStream.recordPositionsFrom(pc, this.sourceStart); - //} - /** - * Dump the suitable return bytecode for a return statement - * - */ - //public void generateReturnBytecode(CodeStream codeStream) { - // - // if (expression == null) { - // codeStream.return_(); - // } else { - // switch (expression.implicitConversion >> 4) { - // case T_boolean : - // case T_int : - // codeStream.ireturn(); - // break; - // case T_float : - // codeStream.freturn(); - // break; - // case T_long : - // codeStream.lreturn(); - // break; - // case T_double : - // codeStream.dreturn(); - // break; - // default : - // codeStream.areturn(); - // } - // } - //} - //public void generateStoreSaveValueIfNecessary(CodeStream codeStream){ - // if (saveValueVariable != null) codeStream.store(saveValueVariable, false); - //} - public boolean needValue() { - return (subroutines == null) || (saveValueVariable != null) || isSynchronized; - } + /** + * Retrun statement code generation + * + * generate the finallyInvocationSequence. + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + */ + // public void generateCode(BlockScope currentScope, CodeStream codeStream) + // { + // if ((bits & IsReachableMASK) == 0) { + // return; + // } + // int pc = codeStream.position; + // // generate the expression + // if ((expression != null) && (expression.constant == NotAConstant)) { + // expression.generateCode(currentScope, codeStream, needValue()); // no + // value needed if non-returning subroutine + // generateStoreSaveValueIfNecessary(codeStream); + // } + // + // // generation of code responsible for invoking the finally blocks in + // sequence + // if (subroutines != null) { + // for (int i = 0, max = subroutines.length; i < max; i++) { + // ASTNode sub; + // if ((sub = subroutines[i]) instanceof SynchronizedStatement) { + // codeStream.load(((SynchronizedStatement) sub).synchroVariable); + // codeStream.monitorexit(); + // } else { + // TryStatement trySub = (TryStatement) sub; + // if (trySub.subRoutineCannotReturn) { + // codeStream.goto_(trySub.subRoutineStartLabel); + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // return; + // } else { + // codeStream.jsr(trySub.subRoutineStartLabel); + // } + // } + // } + // } + // if (saveValueVariable != null) codeStream.load(saveValueVariable); + // + // if ((expression != null) && (expression.constant != NotAConstant)) { + // codeStream.generateConstant(expression.constant, + // expression.implicitConversion); + // generateStoreSaveValueIfNecessary(codeStream); + // } + // // output the suitable return bytecode or wrap the value inside a + // descriptor for doits + // this.generateReturnBytecode(codeStream); + // + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } + /** + * Dump the suitable return bytecode for a return statement + * + */ + // public void generateReturnBytecode(CodeStream codeStream) { + // + // if (expression == null) { + // codeStream.return_(); + // } else { + // switch (expression.implicitConversion >> 4) { + // case T_boolean : + // case T_int : + // codeStream.ireturn(); + // break; + // case T_float : + // codeStream.freturn(); + // break; + // case T_long : + // codeStream.lreturn(); + // break; + // case T_double : + // codeStream.dreturn(); + // break; + // default : + // codeStream.areturn(); + // } + // } + // } + // public void generateStoreSaveValueIfNecessary(CodeStream codeStream){ + // if (saveValueVariable != null) codeStream.store(saveValueVariable, + // false); + // } + public boolean needValue() { + return (subroutines == null) || (saveValueVariable != null) + || isSynchronized; + } - public void prepareSaveValueLocation(TryStatement targetTryStatement) { + public void prepareSaveValueLocation(TryStatement targetTryStatement) { - this.saveValueVariable = targetTryStatement.secretReturnValue; - } + this.saveValueVariable = targetTryStatement.secretReturnValue; + } - public void resolve(BlockScope scope) { - MethodScope methodScope = scope.methodScope(); - MethodBinding methodBinding; - TypeBinding methodType = (methodScope.referenceContext instanceof AbstractMethodDeclaration) ? ((methodBinding = ((AbstractMethodDeclaration) methodScope.referenceContext).binding) == null ? null - : methodBinding.returnType) - : VoidBinding; - if (methodType == VoidBinding) { - // the expression should be null - if (expression == null) - return; - if ((expressionType = expression.resolveType(scope)) != null) - scope.problemReporter().attemptToReturnNonVoidExpression(this, expressionType); - return; - } - if (expression == null) { - if (methodType != null) - scope.problemReporter().shouldReturn(methodType, this); - return; - } - if ((expressionType = expression.resolveType(scope)) == null) - return; + public void resolve(BlockScope scope) { + MethodScope methodScope = scope.methodScope(); + MethodBinding methodBinding; + TypeBinding methodType = (methodScope.referenceContext instanceof AbstractMethodDeclaration) ? ((methodBinding = ((AbstractMethodDeclaration) methodScope.referenceContext).binding) == null ? null + : methodBinding.returnType) + : VoidBinding; + if (methodType == VoidBinding) { + // the expression should be null + if (expression == null) + return; + if ((expressionType = expression.resolveType(scope)) != null) + scope.problemReporter().attemptToReturnNonVoidExpression(this, + expressionType); + return; + } + if (expression == null) { + if (methodType != null) + scope.problemReporter().shouldReturn(methodType, this); + return; + } + if ((expressionType = expression.resolveType(scope)) == null) + return; - if (methodType != null && expression.isConstantValueOfTypeAssignableToType(expressionType, methodType)) { - // dealing with constant - expression.implicitWidening(methodType, expressionType); - return; - } - if (expressionType == VoidBinding) { - scope.problemReporter().attemptToReturnVoidValue(this); - return; - } - if (methodType != null && expressionType.isCompatibleWith(methodType)) { - expression.implicitWidening(methodType, expressionType); - return; - } - if (methodType != null) { - scope.problemReporter().typeMismatchErrorActualTypeExpectedType(expression, expressionType, methodType); - } - } + if (methodType != null + && expression.isConstantValueOfTypeAssignableToType( + expressionType, methodType)) { + // dealing with constant + expression.implicitWidening(methodType, expressionType); + return; + } + if (expressionType == VoidBinding) { + scope.problemReporter().attemptToReturnVoidValue(this); + return; + } + if (methodType != null && expressionType.isCompatibleWith(methodType)) { + expression.implicitWidening(methodType, expressionType); + return; + } + if (methodType != null) { + scope.problemReporter().typeMismatchErrorActualTypeExpectedType( + expression, expressionType, methodType); + } + } - public StringBuffer printStatement(int tab, StringBuffer output) { + public StringBuffer printStatement(int tab, StringBuffer output) { - printIndent(tab, output).append("return "); //$NON-NLS-1$ - if (expression != null) - expression.printExpression(0, output); - return output.append(';'); - } + printIndent(tab, output).append("return "); //$NON-NLS-1$ + if (expression != null) + expression.printExpression(0, output); + return output.append(';'); + } - public String toString(int tab) { + public String toString(int tab) { - String s = tabString(tab); - s = s + "return "; //$NON-NLS-1$ - if (expression != null) - s = s + expression.toStringExpression(); - return s; - } + String s = tabString(tab); + s = s + "return "; //$NON-NLS-1$ + if (expression != null) + s = s + expression.toStringExpression(); + return s; + } - public void traverse(ASTVisitor visitor, BlockScope scope) { - if (visitor.visit(this, scope)) { - if (expression != null) - expression.traverse(visitor, scope); - } - visitor.endVisit(this, scope); - } + public void traverse(ASTVisitor visitor, BlockScope scope) { + if (visitor.visit(this, scope)) { + if (expression != null) + expression.traverse(visitor, scope); + } + visitor.endVisit(this, scope); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/SingleNameReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/SingleNameReference.java index e681c4c..7271ede 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/SingleNameReference.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/SingleNameReference.java @@ -28,608 +28,751 @@ import net.sourceforge.phpdt.internal.compiler.lookup.VariableBinding; public class SingleNameReference extends NameReference implements OperatorIds { public char[] token; - public MethodBinding[] syntheticAccessors; // [0]=read accessor [1]=write accessor + public MethodBinding[] syntheticAccessors; // [0]=read accessor [1]=write + // accessor + public static final int READ = 0; + public static final int WRITE = 1; - -public SingleNameReference(char[] source, long pos) { - super(); - token = source; - sourceStart = (int) (pos >>> 32); - sourceEnd = (int) pos; -} -public FlowInfo analyseAssignment(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo, Assignment assignment, boolean isCompound) { - // compound assignment extra work - if (isCompound) { // check the variable part is initialized if blank final - switch (bits & RestrictiveFlagMASK) { - case FIELD : // reading a field + public SingleNameReference(char[] source, long pos) { + super(); + token = source; + sourceStart = (int) (pos >>> 32); + sourceEnd = (int) pos; + } + + public FlowInfo analyseAssignment(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo, Assignment assignment, + boolean isCompound) { + + // compound assignment extra work + if (isCompound) { // check the variable part is initialized if blank + // final + switch (bits & RestrictiveFlagMASK) { + case FIELD: // reading a field FieldBinding fieldBinding; - if ((fieldBinding = (FieldBinding) binding).isBlankFinal() - && currentScope.allowBlankFinalFieldAssignment(fieldBinding)) { + if ((fieldBinding = (FieldBinding) binding).isBlankFinal() + && currentScope + .allowBlankFinalFieldAssignment(fieldBinding)) { if (!flowInfo.isDefinitelyAssigned(fieldBinding)) { - currentScope.problemReporter().uninitializedBlankFinalField(fieldBinding, this); + currentScope.problemReporter() + .uninitializedBlankFinalField(fieldBinding, + this); } } manageSyntheticReadAccessIfNecessary(currentScope); break; -// case LOCAL : // reading a local variable -// // check if assigning a final blank field -// LocalVariableBinding localBinding; -// if (!flowInfo.isDefinitelyAssigned(localBinding = (LocalVariableBinding) binding)) { -// currentScope.problemReporter().uninitializedLocalVariable(localBinding, this); -// // we could improve error msg here telling "cannot use compound assignment on final local variable" -// } -// if (flowInfo.isReachable()) { -// localBinding.useFlag = LocalVariableBinding.USED; -// } else if (localBinding.useFlag == LocalVariableBinding.UNUSED) { -// localBinding.useFlag = LocalVariableBinding.FAKE_USED; -// } + // case LOCAL : // reading a local variable + // // check if assigning a final blank field + // LocalVariableBinding localBinding; + // if (!flowInfo.isDefinitelyAssigned(localBinding = + // (LocalVariableBinding) binding)) { + // currentScope.problemReporter().uninitializedLocalVariable(localBinding, + // this); + // // we could improve error msg here telling "cannot use compound + // assignment on final local variable" + // } + // if (flowInfo.isReachable()) { + // localBinding.useFlag = LocalVariableBinding.USED; + // } else if (localBinding.useFlag == LocalVariableBinding.UNUSED) { + // localBinding.useFlag = LocalVariableBinding.FAKE_USED; + // } + } } - } - if (assignment.expression != null) { - flowInfo = assignment.expression.analyseCode(currentScope, flowContext, flowInfo).unconditionalInits(); - } - switch (bits & RestrictiveFlagMASK) { - case FIELD : // assigning to a field + if (assignment.expression != null) { + flowInfo = assignment.expression.analyseCode(currentScope, + flowContext, flowInfo).unconditionalInits(); + } + switch (bits & RestrictiveFlagMASK) { + case FIELD: // assigning to a field manageSyntheticWriteAccessIfNecessary(currentScope); // check if assigning a final field FieldBinding fieldBinding; if ((fieldBinding = (FieldBinding) binding).isFinal()) { // inside a context where allowed - if (!isCompound && fieldBinding.isBlankFinal() && currentScope.allowBlankFinalFieldAssignment(fieldBinding)) { + if (!isCompound + && fieldBinding.isBlankFinal() + && currentScope + .allowBlankFinalFieldAssignment(fieldBinding)) { if (flowInfo.isPotentiallyAssigned(fieldBinding)) { - currentScope.problemReporter().duplicateInitializationOfBlankFinalField(fieldBinding, this); + currentScope.problemReporter() + .duplicateInitializationOfBlankFinalField( + fieldBinding, this); } else { - flowContext.recordSettingFinal(fieldBinding, this); + flowContext.recordSettingFinal(fieldBinding, this); } flowInfo.markAsDefinitelyAssigned(fieldBinding); } else { - currentScope.problemReporter().cannotAssignToFinalField(fieldBinding, this); + currentScope.problemReporter().cannotAssignToFinalField( + fieldBinding, this); } } break; - case LOCAL : // assigning to a local variable + case LOCAL: // assigning to a local variable LocalVariableBinding localBinding = (LocalVariableBinding) binding; - if (!flowInfo.isDefinitelyAssigned(localBinding)){// for local variable debug attributes + if (!flowInfo.isDefinitelyAssigned(localBinding)) {// for local + // variable + // debug + // attributes bits |= FirstAssignmentToLocalMASK; } else { bits &= ~FirstAssignmentToLocalMASK; } if (localBinding.isFinal()) { if ((bits & DepthMASK) == 0) { - if (isCompound || !localBinding.isBlankFinal()){ - currentScope.problemReporter().cannotAssignToFinalLocal(localBinding, this); + if (isCompound || !localBinding.isBlankFinal()) { + currentScope.problemReporter() + .cannotAssignToFinalLocal(localBinding, this); } else if (flowInfo.isPotentiallyAssigned(localBinding)) { - currentScope.problemReporter().duplicateInitializationOfFinalLocal(localBinding, this); + currentScope.problemReporter() + .duplicateInitializationOfFinalLocal( + localBinding, this); } else { - flowContext.recordSettingFinal(localBinding, this); + flowContext.recordSettingFinal(localBinding, this); } } else { - currentScope.problemReporter().cannotAssignToFinalOuterLocal(localBinding, this); + currentScope.problemReporter() + .cannotAssignToFinalOuterLocal(localBinding, this); } } flowInfo.markAsDefinitelyAssigned(localBinding); + } + manageEnclosingInstanceAccessIfNecessary(currentScope); + return flowInfo; } - manageEnclosingInstanceAccessIfNecessary(currentScope); - return flowInfo; -} -public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { - return analyseCode(currentScope, flowContext, flowInfo, true); -} -public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo, boolean valueRequired) { - switch (bits & RestrictiveFlagMASK) { - case FIELD : // reading a field + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { + return analyseCode(currentScope, flowContext, flowInfo, true); + } + + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo, boolean valueRequired) { + + switch (bits & RestrictiveFlagMASK) { + case FIELD: // reading a field if (valueRequired) { manageSyntheticReadAccessIfNecessary(currentScope); } // check if reading a final blank field FieldBinding fieldBinding; - if ((fieldBinding = (FieldBinding) binding).isBlankFinal() - && currentScope.allowBlankFinalFieldAssignment(fieldBinding)) { + if ((fieldBinding = (FieldBinding) binding).isBlankFinal() + && currentScope + .allowBlankFinalFieldAssignment(fieldBinding)) { if (!flowInfo.isDefinitelyAssigned(fieldBinding)) { - currentScope.problemReporter().uninitializedBlankFinalField(fieldBinding, this); + currentScope.problemReporter() + .uninitializedBlankFinalField(fieldBinding, this); } } break; -// case LOCAL : // reading a local variable -// LocalVariableBinding localBinding; -// if (!flowInfo.isDefinitelyAssigned(localBinding = (LocalVariableBinding) binding)) { -// currentScope.problemReporter().uninitializedLocalVariable(localBinding, this); -// } -// if (flowInfo.isReachable()) { -// localBinding.useFlag = LocalVariableBinding.USED; -// } else if (localBinding.useFlag == LocalVariableBinding.UNUSED) { -// localBinding.useFlag = LocalVariableBinding.FAKE_USED; -// } - } - if (valueRequired) { - manageEnclosingInstanceAccessIfNecessary(currentScope); - } - return flowInfo; -} -public TypeBinding checkFieldAccess(BlockScope scope) { - - FieldBinding fieldBinding = (FieldBinding) binding; - - bits &= ~RestrictiveFlagMASK; // clear bits - bits |= FIELD; - if (!((FieldBinding) binding).isStatic()) { - // must check for the static status.... - if (scope.methodScope().isStatic) { - scope.problemReporter().staticFieldAccessToNonStaticVariable(this, fieldBinding); - constant = NotAConstant; - return fieldBinding.type; + // case LOCAL : // reading a local variable + // LocalVariableBinding localBinding; + // if (!flowInfo.isDefinitelyAssigned(localBinding = + // (LocalVariableBinding) binding)) { + // currentScope.problemReporter().uninitializedLocalVariable(localBinding, + // this); + // } + // if (flowInfo.isReachable()) { + // localBinding.useFlag = LocalVariableBinding.USED; + // } else if (localBinding.useFlag == LocalVariableBinding.UNUSED) { + // localBinding.useFlag = LocalVariableBinding.FAKE_USED; + // } } + if (valueRequired) { + manageEnclosingInstanceAccessIfNecessary(currentScope); + } + return flowInfo; } - constant = FieldReference.getConstantFor(fieldBinding, this, true, scope); - - if (isFieldUseDeprecated(fieldBinding, scope)) - scope.problemReporter().deprecatedField(fieldBinding, this); - - MethodScope ms = scope.methodScope(); - if ((this.bits & IsStrictlyAssignedMASK) == 0 - && ms.enclosingSourceType() == fieldBinding.declaringClass - && ms.fieldDeclarationIndex != MethodScope.NotInFieldDecl - && fieldBinding.id >= ms.fieldDeclarationIndex) { - //if the field is static and ms is not .... then it is valid - if (!fieldBinding.isStatic() || ms.isStatic) - scope.problemReporter().forwardReference(this, 0, scope.enclosingSourceType()); - } - //==================================================== - return fieldBinding.type; + public TypeBinding checkFieldAccess(BlockScope scope) { + + FieldBinding fieldBinding = (FieldBinding) binding; + + bits &= ~RestrictiveFlagMASK; // clear bits + bits |= FIELD; + if (!((FieldBinding) binding).isStatic()) { + // must check for the static status.... + if (scope.methodScope().isStatic) { + scope.problemReporter().staticFieldAccessToNonStaticVariable( + this, fieldBinding); + constant = NotAConstant; + return fieldBinding.type; + } + } + constant = FieldReference.getConstantFor(fieldBinding, this, true, + scope); + + if (isFieldUseDeprecated(fieldBinding, scope)) + scope.problemReporter().deprecatedField(fieldBinding, this); + + MethodScope ms = scope.methodScope(); + if ((this.bits & IsStrictlyAssignedMASK) == 0 + && ms.enclosingSourceType() == fieldBinding.declaringClass + && ms.fieldDeclarationIndex != MethodScope.NotInFieldDecl + && fieldBinding.id >= ms.fieldDeclarationIndex) { + // if the field is static and ms is not .... then it is valid + if (!fieldBinding.isStatic() || ms.isStatic) + scope.problemReporter().forwardReference(this, 0, + scope.enclosingSourceType()); + } + // ==================================================== + + return fieldBinding.type; -} -//public void generateAssignment(BlockScope currentScope, CodeStream codeStream, Assignment assignment, boolean valueRequired) { -// -// // optimizing assignment like: i = i + 1 or i = 1 + i -// if (assignment.expression.isCompactableOperation()) { -// BinaryExpression operation = (BinaryExpression) assignment.expression; -// SingleNameReference variableReference; -// if ((operation.left instanceof SingleNameReference) && ((variableReference = (SingleNameReference) operation.left).binding == binding)) { -// // i = i + value, then use the variable on the right hand side, since it has the correct implicit conversion -// variableReference.generateCompoundAssignment(currentScope, codeStream, syntheticAccessors == null ? null : syntheticAccessors[WRITE], operation.right, (operation.bits & OperatorMASK) >> OperatorSHIFT, operation.left.implicitConversion /*should be equivalent to no conversion*/, valueRequired); -// return; -// } -// int operator = (operation.bits & OperatorMASK) >> OperatorSHIFT; -// if ((operation.right instanceof SingleNameReference) -// && ((operator == PLUS) || (operator == MULTIPLY)) // only commutative operations -// && ((variableReference = (SingleNameReference) operation.right).binding == binding) -// && (operation.left.constant != NotAConstant) // exclude non constant expressions, since could have side-effect -// && ((operation.left.implicitConversion >> 4) != T_String) // exclude string concatenation which would occur backwards -// && ((operation.right.implicitConversion >> 4) != T_String)) { // exclude string concatenation which would occur backwards -// // i = value + i, then use the variable on the right hand side, since it has the correct implicit conversion -// variableReference.generateCompoundAssignment(currentScope, codeStream, syntheticAccessors == null ? null : syntheticAccessors[WRITE], operation.left, operator, operation.right.implicitConversion /*should be equivalent to no conversion*/, valueRequired); -// return; -// } -// } -// switch (bits & RestrictiveFlagMASK) { -// case FIELD : // assigning to a field -// FieldBinding fieldBinding; -// if (!(fieldBinding = (FieldBinding) this.codegenBinding).isStatic()) { // need a receiver? -// if ((bits & DepthMASK) != 0) { -// ReferenceBinding targetType = currentScope.enclosingSourceType().enclosingTypeAt((bits & DepthMASK) >> DepthSHIFT); -// Object[] emulationPath = currentScope.getEmulationPath(targetType, true /*only exact match*/, false/*consider enclosing arg*/); -// codeStream.generateOuterAccess(emulationPath, this, targetType, currentScope); -// } else { -// this.generateReceiver(codeStream); -// } -// } -// assignment.expression.generateCode(currentScope, codeStream, true); -// fieldStore(codeStream, fieldBinding, syntheticAccessors == null ? null : syntheticAccessors[WRITE], valueRequired); -// if (valueRequired) { -// codeStream.generateImplicitConversion(assignment.implicitConversion); -// } -// return; -// case LOCAL : // assigning to a local variable -// LocalVariableBinding localBinding = (LocalVariableBinding) this.codegenBinding; -// if (localBinding.resolvedPosition != -1) { -// assignment.expression.generateCode(currentScope, codeStream, true); -// } else { -// if (assignment.expression.constant != NotAConstant) { -// // assigning an unused local to a constant value = no actual assignment is necessary -// if (valueRequired) { -// codeStream.generateConstant(assignment.expression.constant, assignment.implicitConversion); -// } -// } else { -// assignment.expression.generateCode(currentScope, codeStream, true); -// /* Even though the value may not be required, we force it to be produced, and discard it later -// on if it was actually not necessary, so as to provide the same behavior as JDK1.2beta3. */ -// if (valueRequired) { -// codeStream.generateImplicitConversion(assignment.implicitConversion); // implicit conversion -// } else { -// if ((localBinding.type == LongBinding) || (localBinding.type == DoubleBinding)) { -// codeStream.pop2(); -// } else { -// codeStream.pop(); -// } -// } -// } -// return; -// } -// // 26903, need extra cast to store null in array local var -// if (localBinding.type.isArrayType() -// && (assignment.expression.resolvedType == NullBinding // arrayLoc = null -// || ((assignment.expression instanceof CastExpression) // arrayLoc = (type[])null -// && (((CastExpression)assignment.expression).innermostCastedExpression().resolvedType == NullBinding)))){ -// codeStream.checkcast(localBinding.type); -// } -// -// // normal local assignment (since cannot store in outer local which are final locations) -// codeStream.store(localBinding, valueRequired); -// if ((bits & FirstAssignmentToLocalMASK) != 0) { // for local variable debug attributes -// localBinding.recordInitializationStartPC(codeStream.position); -// } -// // implicit conversion -// if (valueRequired) { -// codeStream.generateImplicitConversion(assignment.implicitConversion); -// } -// } -//} -//public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) { -// int pc = codeStream.position; -// if (constant != NotAConstant) { -// if (valueRequired) { -// codeStream.generateConstant(constant, implicitConversion); -// } -// } else { -// switch (bits & RestrictiveFlagMASK) { -// case FIELD : // reading a field -// FieldBinding fieldBinding; -// if (valueRequired) { -// if ((fieldBinding = (FieldBinding) this.codegenBinding).constant == NotAConstant) { // directly use inlined value for constant fields -// boolean isStatic; -// if (!(isStatic = fieldBinding.isStatic())) { -// if ((bits & DepthMASK) != 0) { -// ReferenceBinding targetType = currentScope.enclosingSourceType().enclosingTypeAt((bits & DepthMASK) >> DepthSHIFT); -// Object[] emulationPath = currentScope.getEmulationPath(targetType, true /*only exact match*/, false/*consider enclosing arg*/); -// codeStream.generateOuterAccess(emulationPath, this, targetType, currentScope); -// } else { -// generateReceiver(codeStream); -// } -// } -// // managing private access -// if ((syntheticAccessors == null) || (syntheticAccessors[READ] == null)) { -// if (isStatic) { -// codeStream.getstatic(fieldBinding); -// } else { -// codeStream.getfield(fieldBinding); -// } -// } else { -// codeStream.invokestatic(syntheticAccessors[READ]); -// } -// codeStream.generateImplicitConversion(implicitConversion); -// } else { // directly use the inlined value -// codeStream.generateConstant(fieldBinding.constant, implicitConversion); -// } -// } -// break; -// case LOCAL : // reading a local -// LocalVariableBinding localBinding = (LocalVariableBinding) this.codegenBinding; -// if (valueRequired) { -// // outer local? -// if ((bits & DepthMASK) != 0) { -// // outer local can be reached either through a synthetic arg or a synthetic field -// VariableBinding[] path = currentScope.getEmulationPath(localBinding); -// codeStream.generateOuterAccess(path, this, localBinding, currentScope); -// } else { -// // regular local variable read -// codeStream.load(localBinding); -// } -// codeStream.generateImplicitConversion(implicitConversion); -// } -// } -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -//} -///* -// * Regular API for compound assignment, relies on the fact that there is only one reference to the -// * variable, which carries both synthetic read/write accessors. -// * The APIs with an extra argument is used whenever there are two references to the same variable which -// * are optimized in one access: e.g "a = a + 1" optimized into "a++". -// */ -//public void generateCompoundAssignment(BlockScope currentScope, CodeStream codeStream, Expression expression, int operator, int assignmentImplicitConversion, boolean valueRequired) { -// -// this.generateCompoundAssignment( -// currentScope, -// codeStream, -// syntheticAccessors == null ? null : syntheticAccessors[WRITE], -// expression, -// operator, -// assignmentImplicitConversion, -// valueRequired); -//} -///* -// * The APIs with an extra argument is used whenever there are two references to the same variable which -// * are optimized in one access: e.g "a = a + 1" optimized into "a++". -// */ -//public void generateCompoundAssignment(BlockScope currentScope, CodeStream codeStream, MethodBinding writeAccessor, Expression expression, int operator, int assignmentImplicitConversion, boolean valueRequired) { -// switch (bits & RestrictiveFlagMASK) { -// case FIELD : // assigning to a field -// FieldBinding fieldBinding; -// if ((fieldBinding = (FieldBinding) this.codegenBinding).isStatic()) { -// if ((syntheticAccessors == null) || (syntheticAccessors[READ] == null)) { -// codeStream.getstatic(fieldBinding); -// } else { -// codeStream.invokestatic(syntheticAccessors[READ]); -// } -// } else { -// if ((bits & DepthMASK) != 0) { -// ReferenceBinding targetType = currentScope.enclosingSourceType().enclosingTypeAt((bits & DepthMASK) >> DepthSHIFT); -// Object[] emulationPath = currentScope.getEmulationPath(targetType, true /*only exact match*/, false/*consider enclosing arg*/); -// codeStream.generateOuterAccess(emulationPath, this, targetType, currentScope); -// } else { -// codeStream.aload_0(); -// } -// codeStream.dup(); -// if ((syntheticAccessors == null) || (syntheticAccessors[READ] == null)) { -// codeStream.getfield(fieldBinding); -// } else { -// codeStream.invokestatic(syntheticAccessors[READ]); -// } -// } -// break; -// case LOCAL : // assigning to a local variable (cannot assign to outer local) -// LocalVariableBinding localBinding = (LocalVariableBinding) this.codegenBinding; -// Constant assignConstant; -// int increment; -// // using incr bytecode if possible -// switch (localBinding.type.id) { -// case T_String : -// codeStream.generateStringAppend(currentScope, this, expression); -// if (valueRequired) { -// codeStream.dup(); -// } -// codeStream.store(localBinding, false); -// return; -// case T_int : -// if (((assignConstant = expression.constant) != NotAConstant) -// && (assignConstant.typeID() != T_float) // only for integral types -// && (assignConstant.typeID() != T_double) -// && ((increment = assignConstant.intValue()) == (short) increment)) { // 16 bits value -// switch (operator) { -// case PLUS : -// codeStream.iinc(localBinding.resolvedPosition, increment); -// if (valueRequired) { -// codeStream.load(localBinding); -// } -// return; -// case MINUS : -// codeStream.iinc(localBinding.resolvedPosition, -increment); -// if (valueRequired) { -// codeStream.load(localBinding); -// } -// return; -// } -// } -// default : -// codeStream.load(localBinding); -// } -// } -// // perform the actual compound operation -// int operationTypeID; -// if ((operationTypeID = implicitConversion >> 4) == T_String || operationTypeID == T_Object) { -// // we enter here if the single name reference is a field of type java.lang.String or if the type of the -// // operation is java.lang.Object -// // For example: o = o + ""; // where the compiled type of o is java.lang.Object. -// codeStream.generateStringAppend(currentScope, null, expression); -// } else { -// // promote the array reference to the suitable operation type -// codeStream.generateImplicitConversion(implicitConversion); -// // generate the increment value (will by itself be promoted to the operation value) -// if (expression == IntLiteral.One){ // prefix operation -// codeStream.generateConstant(expression.constant, implicitConversion); -// } else { -// expression.generateCode(currentScope, codeStream, true); -// } -// // perform the operation -// codeStream.sendOperator(operator, operationTypeID); -// // cast the value back to the array reference type -// codeStream.generateImplicitConversion(assignmentImplicitConversion); -// } -// // store the result back into the variable -// switch (bits & RestrictiveFlagMASK) { -// case FIELD : // assigning to a field -// fieldStore(codeStream, (FieldBinding) this.codegenBinding, writeAccessor, valueRequired); -// return; -// case LOCAL : // assigning to a local variable -// LocalVariableBinding localBinding = (LocalVariableBinding) this.codegenBinding; -// if (valueRequired) { -// if ((localBinding.type == LongBinding) || (localBinding.type == DoubleBinding)) { -// codeStream.dup2(); -// } else { -// codeStream.dup(); -// } -// } -// codeStream.store(localBinding, false); -// } -//} -//public void generatePostIncrement(BlockScope currentScope, CodeStream codeStream, CompoundAssignment postIncrement, boolean valueRequired) { -// switch (bits & RestrictiveFlagMASK) { -// case FIELD : // assigning to a field -// FieldBinding fieldBinding; -// if ((fieldBinding = (FieldBinding) this.codegenBinding).isStatic()) { -// if ((syntheticAccessors == null) || (syntheticAccessors[READ] == null)) { -// codeStream.getstatic(fieldBinding); -// } else { -// codeStream.invokestatic(syntheticAccessors[READ]); -// } -// } else { -// if ((bits & DepthMASK) != 0) { -// ReferenceBinding targetType = currentScope.enclosingSourceType().enclosingTypeAt((bits & DepthMASK) >> DepthSHIFT); -// Object[] emulationPath = currentScope.getEmulationPath(targetType, true /*only exact match*/, false/*consider enclosing arg*/); -// codeStream.generateOuterAccess(emulationPath, this, targetType, currentScope); -// } else { -// codeStream.aload_0(); -// } -// codeStream.dup(); -// if ((syntheticAccessors == null) || (syntheticAccessors[READ] == null)) { -// codeStream.getfield(fieldBinding); -// } else { -// codeStream.invokestatic(syntheticAccessors[READ]); -// } -// } -// if (valueRequired) { -// if (fieldBinding.isStatic()) { -// if ((fieldBinding.type == LongBinding) || (fieldBinding.type == DoubleBinding)) { -// codeStream.dup2(); -// } else { -// codeStream.dup(); -// } -// } else { // Stack: [owner][old field value] ---> [old field value][owner][old field value] -// if ((fieldBinding.type == LongBinding) || (fieldBinding.type == DoubleBinding)) { -// codeStream.dup2_x1(); -// } else { -// codeStream.dup_x1(); -// } -// } -// } -// codeStream.generateConstant(postIncrement.expression.constant, implicitConversion); -// codeStream.sendOperator(postIncrement.operator, fieldBinding.type.id); -// codeStream.generateImplicitConversion(postIncrement.assignmentImplicitConversion); -// fieldStore(codeStream, fieldBinding, syntheticAccessors == null ? null : syntheticAccessors[WRITE], false); -// return; -// case LOCAL : // assigning to a local variable -// LocalVariableBinding localBinding = (LocalVariableBinding) this.codegenBinding; -// // using incr bytecode if possible -// if (localBinding.type == IntBinding) { -// if (valueRequired) { -// codeStream.load(localBinding); -// } -// if (postIncrement.operator == PLUS) { -// codeStream.iinc(localBinding.resolvedPosition, 1); -// } else { -// codeStream.iinc(localBinding.resolvedPosition, -1); -// } -// } else { -// codeStream.load(localBinding); -// if (valueRequired){ -// if ((localBinding.type == LongBinding) || (localBinding.type == DoubleBinding)) { -// codeStream.dup2(); -// } else { -// codeStream.dup(); -// } -// } -// codeStream.generateConstant(postIncrement.expression.constant, implicitConversion); -// codeStream.sendOperator(postIncrement.operator, localBinding.type.id); -// codeStream.generateImplicitConversion(postIncrement.assignmentImplicitConversion); -// -// codeStream.store(localBinding, false); -// } -// } -//} -//public void generateReceiver(CodeStream codeStream) { -// codeStream.aload_0(); -//} -public void manageEnclosingInstanceAccessIfNecessary(BlockScope currentScope) { - - //If inlinable field, forget the access emulation, the code gen will directly target it - if (((bits & DepthMASK) == 0) || (constant != NotAConstant)) return; - - if ((bits & RestrictiveFlagMASK) == LOCAL) { - currentScope.emulateOuterAccess((LocalVariableBinding) binding); } -} -public void manageSyntheticReadAccessIfNecessary(BlockScope currentScope) { - //If inlinable field, forget the access emulation, the code gen will directly target it - if (constant != NotAConstant) - return; + // public void generateAssignment(BlockScope currentScope, CodeStream + // codeStream, Assignment assignment, boolean valueRequired) { + // + // // optimizing assignment like: i = i + 1 or i = 1 + i + // if (assignment.expression.isCompactableOperation()) { + // BinaryExpression operation = (BinaryExpression) assignment.expression; + // SingleNameReference variableReference; + // if ((operation.left instanceof SingleNameReference) && + // ((variableReference = (SingleNameReference) operation.left).binding == + // binding)) { + // // i = i + value, then use the variable on the right hand side, since it + // has the correct implicit conversion + // variableReference.generateCompoundAssignment(currentScope, codeStream, + // syntheticAccessors == null ? null : syntheticAccessors[WRITE], + // operation.right, (operation.bits & OperatorMASK) >> OperatorSHIFT, + // operation.left.implicitConversion /*should be equivalent to no + // conversion*/, valueRequired); + // return; + // } + // int operator = (operation.bits & OperatorMASK) >> OperatorSHIFT; + // if ((operation.right instanceof SingleNameReference) + // && ((operator == PLUS) || (operator == MULTIPLY)) // only commutative + // operations + // && ((variableReference = (SingleNameReference) operation.right).binding + // == binding) + // && (operation.left.constant != NotAConstant) // exclude non constant + // expressions, since could have side-effect + // && ((operation.left.implicitConversion >> 4) != T_String) // exclude + // string concatenation which would occur backwards + // && ((operation.right.implicitConversion >> 4) != T_String)) { // exclude + // string concatenation which would occur backwards + // // i = value + i, then use the variable on the right hand side, since it + // has the correct implicit conversion + // variableReference.generateCompoundAssignment(currentScope, codeStream, + // syntheticAccessors == null ? null : syntheticAccessors[WRITE], + // operation.left, operator, operation.right.implicitConversion /*should be + // equivalent to no conversion*/, valueRequired); + // return; + // } + // } + // switch (bits & RestrictiveFlagMASK) { + // case FIELD : // assigning to a field + // FieldBinding fieldBinding; + // if (!(fieldBinding = (FieldBinding) this.codegenBinding).isStatic()) { // + // need a receiver? + // if ((bits & DepthMASK) != 0) { + // ReferenceBinding targetType = + // currentScope.enclosingSourceType().enclosingTypeAt((bits & DepthMASK) >> + // DepthSHIFT); + // Object[] emulationPath = currentScope.getEmulationPath(targetType, true + // /*only exact match*/, false/*consider enclosing arg*/); + // codeStream.generateOuterAccess(emulationPath, this, targetType, + // currentScope); + // } else { + // this.generateReceiver(codeStream); + // } + // } + // assignment.expression.generateCode(currentScope, codeStream, true); + // fieldStore(codeStream, fieldBinding, syntheticAccessors == null ? null : + // syntheticAccessors[WRITE], valueRequired); + // if (valueRequired) { + // codeStream.generateImplicitConversion(assignment.implicitConversion); + // } + // return; + // case LOCAL : // assigning to a local variable + // LocalVariableBinding localBinding = (LocalVariableBinding) + // this.codegenBinding; + // if (localBinding.resolvedPosition != -1) { + // assignment.expression.generateCode(currentScope, codeStream, true); + // } else { + // if (assignment.expression.constant != NotAConstant) { + // // assigning an unused local to a constant value = no actual assignment + // is necessary + // if (valueRequired) { + // codeStream.generateConstant(assignment.expression.constant, + // assignment.implicitConversion); + // } + // } else { + // assignment.expression.generateCode(currentScope, codeStream, true); + // /* Even though the value may not be required, we force it to be produced, + // and discard it later + // on if it was actually not necessary, so as to provide the same behavior + // as JDK1.2beta3. */ + // if (valueRequired) { + // codeStream.generateImplicitConversion(assignment.implicitConversion); // + // implicit conversion + // } else { + // if ((localBinding.type == LongBinding) || (localBinding.type == + // DoubleBinding)) { + // codeStream.pop2(); + // } else { + // codeStream.pop(); + // } + // } + // } + // return; + // } + // // 26903, need extra cast to store null in array local var + // if (localBinding.type.isArrayType() + // && (assignment.expression.resolvedType == NullBinding // arrayLoc = null + // || ((assignment.expression instanceof CastExpression) // arrayLoc = + // (type[])null + // && + // (((CastExpression)assignment.expression).innermostCastedExpression().resolvedType + // == NullBinding)))){ + // codeStream.checkcast(localBinding.type); + // } + // + // // normal local assignment (since cannot store in outer local which are + // final locations) + // codeStream.store(localBinding, valueRequired); + // if ((bits & FirstAssignmentToLocalMASK) != 0) { // for local variable + // debug attributes + // localBinding.recordInitializationStartPC(codeStream.position); + // } + // // implicit conversion + // if (valueRequired) { + // codeStream.generateImplicitConversion(assignment.implicitConversion); + // } + // } + // } + // public void generateCode(BlockScope currentScope, CodeStream codeStream, + // boolean valueRequired) { + // int pc = codeStream.position; + // if (constant != NotAConstant) { + // if (valueRequired) { + // codeStream.generateConstant(constant, implicitConversion); + // } + // } else { + // switch (bits & RestrictiveFlagMASK) { + // case FIELD : // reading a field + // FieldBinding fieldBinding; + // if (valueRequired) { + // if ((fieldBinding = (FieldBinding) this.codegenBinding).constant == + // NotAConstant) { // directly use inlined value for constant fields + // boolean isStatic; + // if (!(isStatic = fieldBinding.isStatic())) { + // if ((bits & DepthMASK) != 0) { + // ReferenceBinding targetType = + // currentScope.enclosingSourceType().enclosingTypeAt((bits & DepthMASK) >> + // DepthSHIFT); + // Object[] emulationPath = currentScope.getEmulationPath(targetType, true + // /*only exact match*/, false/*consider enclosing arg*/); + // codeStream.generateOuterAccess(emulationPath, this, targetType, + // currentScope); + // } else { + // generateReceiver(codeStream); + // } + // } + // // managing private access + // if ((syntheticAccessors == null) || (syntheticAccessors[READ] == null)) { + // if (isStatic) { + // codeStream.getstatic(fieldBinding); + // } else { + // codeStream.getfield(fieldBinding); + // } + // } else { + // codeStream.invokestatic(syntheticAccessors[READ]); + // } + // codeStream.generateImplicitConversion(implicitConversion); + // } else { // directly use the inlined value + // codeStream.generateConstant(fieldBinding.constant, implicitConversion); + // } + // } + // break; + // case LOCAL : // reading a local + // LocalVariableBinding localBinding = (LocalVariableBinding) + // this.codegenBinding; + // if (valueRequired) { + // // outer local? + // if ((bits & DepthMASK) != 0) { + // // outer local can be reached either through a synthetic arg or a + // synthetic field + // VariableBinding[] path = currentScope.getEmulationPath(localBinding); + // codeStream.generateOuterAccess(path, this, localBinding, currentScope); + // } else { + // // regular local variable read + // codeStream.load(localBinding); + // } + // codeStream.generateImplicitConversion(implicitConversion); + // } + // } + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } + // /* + // * Regular API for compound assignment, relies on the fact that there is + // only one reference to the + // * variable, which carries both synthetic read/write accessors. + // * The APIs with an extra argument is used whenever there are two + // references to the same variable which + // * are optimized in one access: e.g "a = a + 1" optimized into "a++". + // */ + // public void generateCompoundAssignment(BlockScope currentScope, + // CodeStream codeStream, Expression expression, int operator, int + // assignmentImplicitConversion, boolean valueRequired) { + // + // this.generateCompoundAssignment( + // currentScope, + // codeStream, + // syntheticAccessors == null ? null : syntheticAccessors[WRITE], + // expression, + // operator, + // assignmentImplicitConversion, + // valueRequired); + // } + // /* + // * The APIs with an extra argument is used whenever there are two + // references to the same variable which + // * are optimized in one access: e.g "a = a + 1" optimized into "a++". + // */ + // public void generateCompoundAssignment(BlockScope currentScope, + // CodeStream codeStream, MethodBinding writeAccessor, Expression + // expression, int operator, int assignmentImplicitConversion, boolean + // valueRequired) { + // switch (bits & RestrictiveFlagMASK) { + // case FIELD : // assigning to a field + // FieldBinding fieldBinding; + // if ((fieldBinding = (FieldBinding) this.codegenBinding).isStatic()) { + // if ((syntheticAccessors == null) || (syntheticAccessors[READ] == null)) { + // codeStream.getstatic(fieldBinding); + // } else { + // codeStream.invokestatic(syntheticAccessors[READ]); + // } + // } else { + // if ((bits & DepthMASK) != 0) { + // ReferenceBinding targetType = + // currentScope.enclosingSourceType().enclosingTypeAt((bits & DepthMASK) >> + // DepthSHIFT); + // Object[] emulationPath = currentScope.getEmulationPath(targetType, true + // /*only exact match*/, false/*consider enclosing arg*/); + // codeStream.generateOuterAccess(emulationPath, this, targetType, + // currentScope); + // } else { + // codeStream.aload_0(); + // } + // codeStream.dup(); + // if ((syntheticAccessors == null) || (syntheticAccessors[READ] == null)) { + // codeStream.getfield(fieldBinding); + // } else { + // codeStream.invokestatic(syntheticAccessors[READ]); + // } + // } + // break; + // case LOCAL : // assigning to a local variable (cannot assign to outer + // local) + // LocalVariableBinding localBinding = (LocalVariableBinding) + // this.codegenBinding; + // Constant assignConstant; + // int increment; + // // using incr bytecode if possible + // switch (localBinding.type.id) { + // case T_String : + // codeStream.generateStringAppend(currentScope, this, expression); + // if (valueRequired) { + // codeStream.dup(); + // } + // codeStream.store(localBinding, false); + // return; + // case T_int : + // if (((assignConstant = expression.constant) != NotAConstant) + // && (assignConstant.typeID() != T_float) // only for integral types + // && (assignConstant.typeID() != T_double) + // && ((increment = assignConstant.intValue()) == (short) increment)) { // + // 16 bits value + // switch (operator) { + // case PLUS : + // codeStream.iinc(localBinding.resolvedPosition, increment); + // if (valueRequired) { + // codeStream.load(localBinding); + // } + // return; + // case MINUS : + // codeStream.iinc(localBinding.resolvedPosition, -increment); + // if (valueRequired) { + // codeStream.load(localBinding); + // } + // return; + // } + // } + // default : + // codeStream.load(localBinding); + // } + // } + // // perform the actual compound operation + // int operationTypeID; + // if ((operationTypeID = implicitConversion >> 4) == T_String || + // operationTypeID == T_Object) { + // // we enter here if the single name reference is a field of type + // java.lang.String or if the type of the + // // operation is java.lang.Object + // // For example: o = o + ""; // where the compiled type of o is + // java.lang.Object. + // codeStream.generateStringAppend(currentScope, null, expression); + // } else { + // // promote the array reference to the suitable operation type + // codeStream.generateImplicitConversion(implicitConversion); + // // generate the increment value (will by itself be promoted to the + // operation value) + // if (expression == IntLiteral.One){ // prefix operation + // codeStream.generateConstant(expression.constant, implicitConversion); + // } else { + // expression.generateCode(currentScope, codeStream, true); + // } + // // perform the operation + // codeStream.sendOperator(operator, operationTypeID); + // // cast the value back to the array reference type + // codeStream.generateImplicitConversion(assignmentImplicitConversion); + // } + // // store the result back into the variable + // switch (bits & RestrictiveFlagMASK) { + // case FIELD : // assigning to a field + // fieldStore(codeStream, (FieldBinding) this.codegenBinding, writeAccessor, + // valueRequired); + // return; + // case LOCAL : // assigning to a local variable + // LocalVariableBinding localBinding = (LocalVariableBinding) + // this.codegenBinding; + // if (valueRequired) { + // if ((localBinding.type == LongBinding) || (localBinding.type == + // DoubleBinding)) { + // codeStream.dup2(); + // } else { + // codeStream.dup(); + // } + // } + // codeStream.store(localBinding, false); + // } + // } + // public void generatePostIncrement(BlockScope currentScope, CodeStream + // codeStream, CompoundAssignment postIncrement, boolean valueRequired) { + // switch (bits & RestrictiveFlagMASK) { + // case FIELD : // assigning to a field + // FieldBinding fieldBinding; + // if ((fieldBinding = (FieldBinding) this.codegenBinding).isStatic()) { + // if ((syntheticAccessors == null) || (syntheticAccessors[READ] == null)) { + // codeStream.getstatic(fieldBinding); + // } else { + // codeStream.invokestatic(syntheticAccessors[READ]); + // } + // } else { + // if ((bits & DepthMASK) != 0) { + // ReferenceBinding targetType = + // currentScope.enclosingSourceType().enclosingTypeAt((bits & DepthMASK) >> + // DepthSHIFT); + // Object[] emulationPath = currentScope.getEmulationPath(targetType, true + // /*only exact match*/, false/*consider enclosing arg*/); + // codeStream.generateOuterAccess(emulationPath, this, targetType, + // currentScope); + // } else { + // codeStream.aload_0(); + // } + // codeStream.dup(); + // if ((syntheticAccessors == null) || (syntheticAccessors[READ] == null)) { + // codeStream.getfield(fieldBinding); + // } else { + // codeStream.invokestatic(syntheticAccessors[READ]); + // } + // } + // if (valueRequired) { + // if (fieldBinding.isStatic()) { + // if ((fieldBinding.type == LongBinding) || (fieldBinding.type == + // DoubleBinding)) { + // codeStream.dup2(); + // } else { + // codeStream.dup(); + // } + // } else { // Stack: [owner][old field value] ---> [old field + // value][owner][old field value] + // if ((fieldBinding.type == LongBinding) || (fieldBinding.type == + // DoubleBinding)) { + // codeStream.dup2_x1(); + // } else { + // codeStream.dup_x1(); + // } + // } + // } + // codeStream.generateConstant(postIncrement.expression.constant, + // implicitConversion); + // codeStream.sendOperator(postIncrement.operator, fieldBinding.type.id); + // codeStream.generateImplicitConversion(postIncrement.assignmentImplicitConversion); + // fieldStore(codeStream, fieldBinding, syntheticAccessors == null ? null : + // syntheticAccessors[WRITE], false); + // return; + // case LOCAL : // assigning to a local variable + // LocalVariableBinding localBinding = (LocalVariableBinding) + // this.codegenBinding; + // // using incr bytecode if possible + // if (localBinding.type == IntBinding) { + // if (valueRequired) { + // codeStream.load(localBinding); + // } + // if (postIncrement.operator == PLUS) { + // codeStream.iinc(localBinding.resolvedPosition, 1); + // } else { + // codeStream.iinc(localBinding.resolvedPosition, -1); + // } + // } else { + // codeStream.load(localBinding); + // if (valueRequired){ + // if ((localBinding.type == LongBinding) || (localBinding.type == + // DoubleBinding)) { + // codeStream.dup2(); + // } else { + // codeStream.dup(); + // } + // } + // codeStream.generateConstant(postIncrement.expression.constant, + // implicitConversion); + // codeStream.sendOperator(postIncrement.operator, localBinding.type.id); + // codeStream.generateImplicitConversion(postIncrement.assignmentImplicitConversion); + // + // codeStream.store(localBinding, false); + // } + // } + // } + // public void generateReceiver(CodeStream codeStream) { + // codeStream.aload_0(); + // } + public void manageEnclosingInstanceAccessIfNecessary(BlockScope currentScope) { - if ((bits & FIELD) != 0) { - FieldBinding fieldBinding = (FieldBinding) binding; - if (((bits & DepthMASK) != 0) - && (fieldBinding.isPrivate() // private access - || (fieldBinding.isProtected() // implicit protected access - && fieldBinding.declaringClass.getPackage() - != currentScope.enclosingSourceType().getPackage()))) { - if (syntheticAccessors == null) - syntheticAccessors = new MethodBinding[2]; - syntheticAccessors[READ] = - ((SourceTypeBinding)currentScope.enclosingSourceType(). - enclosingTypeAt((bits & DepthMASK) >> DepthSHIFT)). - addSyntheticMethod(fieldBinding, true); - currentScope.problemReporter().needToEmulateFieldReadAccess(fieldBinding, this); + // If inlinable field, forget the access emulation, the code gen will + // directly target it + if (((bits & DepthMASK) == 0) || (constant != NotAConstant)) return; + + if ((bits & RestrictiveFlagMASK) == LOCAL) { + currentScope.emulateOuterAccess((LocalVariableBinding) binding); } - // if the binding declaring class is not visible, need special action - // for runtime compatibility on 1.2 VMs : change the declaring class of the binding - // NOTE: from target 1.2 on, field's declaring class is touched if any different from receiver type - // and not from Object or implicit static field access. -// if (fieldBinding.declaringClass != this.actualReceiverType -// && !this.actualReceiverType.isArrayType() -// && fieldBinding.declaringClass != null -// && fieldBinding.constant == NotAConstant -// && ((currentScope.environment().options.targetJDK >= CompilerOptions.JDK1_2 -// && !fieldBinding.isStatic() -// && fieldBinding.declaringClass.id != T_Object) // no change for Object fields (if there was any) -// || !fieldBinding.declaringClass.canBeSeenBy(currentScope))){ -// this.codegenBinding = currentScope.enclosingSourceType().getUpdatedFieldBinding(fieldBinding, (ReferenceBinding)this.actualReceiverType); -// } } -} -public void manageSyntheticWriteAccessIfNecessary(BlockScope currentScope) { - if ((bits & FIELD) != 0) { - FieldBinding fieldBinding = (FieldBinding) binding; - if (((bits & DepthMASK) != 0) - && (fieldBinding.isPrivate() // private access - || (fieldBinding.isProtected() // implicit protected access - && fieldBinding.declaringClass.getPackage() - != currentScope.enclosingSourceType().getPackage()))) { - if (syntheticAccessors == null) - syntheticAccessors = new MethodBinding[2]; - syntheticAccessors[WRITE] = - ((SourceTypeBinding)currentScope.enclosingSourceType(). - enclosingTypeAt((bits & DepthMASK) >> DepthSHIFT)). - addSyntheticMethod(fieldBinding, false); - currentScope.problemReporter().needToEmulateFieldWriteAccess(fieldBinding, this); + public void manageSyntheticReadAccessIfNecessary(BlockScope currentScope) { + + // If inlinable field, forget the access emulation, the code gen will + // directly target it + if (constant != NotAConstant) return; + + if ((bits & FIELD) != 0) { + FieldBinding fieldBinding = (FieldBinding) binding; + if (((bits & DepthMASK) != 0) && (fieldBinding.isPrivate() // private + // access + || (fieldBinding.isProtected() // implicit protected access + && fieldBinding.declaringClass.getPackage() != currentScope + .enclosingSourceType().getPackage()))) { + if (syntheticAccessors == null) + syntheticAccessors = new MethodBinding[2]; + syntheticAccessors[READ] = ((SourceTypeBinding) currentScope + .enclosingSourceType().enclosingTypeAt( + (bits & DepthMASK) >> DepthSHIFT)) + .addSyntheticMethod(fieldBinding, true); + currentScope.problemReporter().needToEmulateFieldReadAccess( + fieldBinding, this); + return; + } + // if the binding declaring class is not visible, need special + // action + // for runtime compatibility on 1.2 VMs : change the declaring class + // of the binding + // NOTE: from target 1.2 on, field's declaring class is touched if + // any different from receiver type + // and not from Object or implicit static field access. + // if (fieldBinding.declaringClass != this.actualReceiverType + // && !this.actualReceiverType.isArrayType() + // && fieldBinding.declaringClass != null + // && fieldBinding.constant == NotAConstant + // && ((currentScope.environment().options.targetJDK >= + // CompilerOptions.JDK1_2 + // && !fieldBinding.isStatic() + // && fieldBinding.declaringClass.id != T_Object) // no change for + // Object fields (if there was any) + // || !fieldBinding.declaringClass.canBeSeenBy(currentScope))){ + // this.codegenBinding = + // currentScope.enclosingSourceType().getUpdatedFieldBinding(fieldBinding, + // (ReferenceBinding)this.actualReceiverType); + // } } - // if the binding declaring class is not visible, need special action - // for runtime compatibility on 1.2 VMs : change the declaring class of the binding - // NOTE: from target 1.2 on, field's declaring class is touched if any different from receiver type - // and not from Object or implicit static field access. -// if (fieldBinding.declaringClass != this.actualReceiverType -// && !this.actualReceiverType.isArrayType() -// && fieldBinding.declaringClass != null -// && fieldBinding.constant == NotAConstant -// && ((currentScope.environment().options.targetJDK >= CompilerOptions.JDK1_2 -// && !fieldBinding.isStatic() -// && fieldBinding.declaringClass.id != T_Object) // no change for Object fields (if there was any) -// || !fieldBinding.declaringClass.canBeSeenBy(currentScope))){ -// this.codegenBinding = currentScope.enclosingSourceType().getUpdatedFieldBinding(fieldBinding, (ReferenceBinding)this.actualReceiverType); -// } } -} -public TypeBinding reportError(BlockScope scope) { - //=====error cases======= - constant = Constant.NotAConstant; - if (binding instanceof ProblemFieldBinding) { - scope.problemReporter().invalidField(this, (FieldBinding) binding); - } else if (binding instanceof ProblemReferenceBinding) { - scope.problemReporter().invalidType(this, (TypeBinding) binding); - } else { - scope.problemReporter().unresolvableReference(this, binding); + + public void manageSyntheticWriteAccessIfNecessary(BlockScope currentScope) { + + if ((bits & FIELD) != 0) { + FieldBinding fieldBinding = (FieldBinding) binding; + if (((bits & DepthMASK) != 0) && (fieldBinding.isPrivate() // private + // access + || (fieldBinding.isProtected() // implicit protected access + && fieldBinding.declaringClass.getPackage() != currentScope + .enclosingSourceType().getPackage()))) { + if (syntheticAccessors == null) + syntheticAccessors = new MethodBinding[2]; + syntheticAccessors[WRITE] = ((SourceTypeBinding) currentScope + .enclosingSourceType().enclosingTypeAt( + (bits & DepthMASK) >> DepthSHIFT)) + .addSyntheticMethod(fieldBinding, false); + currentScope.problemReporter().needToEmulateFieldWriteAccess( + fieldBinding, this); + return; + } + // if the binding declaring class is not visible, need special + // action + // for runtime compatibility on 1.2 VMs : change the declaring class + // of the binding + // NOTE: from target 1.2 on, field's declaring class is touched if + // any different from receiver type + // and not from Object or implicit static field access. + // if (fieldBinding.declaringClass != this.actualReceiverType + // && !this.actualReceiverType.isArrayType() + // && fieldBinding.declaringClass != null + // && fieldBinding.constant == NotAConstant + // && ((currentScope.environment().options.targetJDK >= + // CompilerOptions.JDK1_2 + // && !fieldBinding.isStatic() + // && fieldBinding.declaringClass.id != T_Object) // no change for + // Object fields (if there was any) + // || !fieldBinding.declaringClass.canBeSeenBy(currentScope))){ + // this.codegenBinding = + // currentScope.enclosingSourceType().getUpdatedFieldBinding(fieldBinding, + // (ReferenceBinding)this.actualReceiverType); + // } + } } - return null; -} -public TypeBinding resolveType(BlockScope scope) { - // for code gen, harm the restrictiveFlag - this.actualReceiverType = this.receiverType = scope.enclosingSourceType(); - - if ((this.codegenBinding = this.binding = scope.getBinding(token, bits & RestrictiveFlagMASK, this)).isValidBinding()) { - switch (bits & RestrictiveFlagMASK) { - case VARIABLE : // =========only variable============ - case VARIABLE | TYPE : //====both variable and type============ + public TypeBinding reportError(BlockScope scope) { + // =====error cases======= + constant = Constant.NotAConstant; + if (binding instanceof ProblemFieldBinding) { + scope.problemReporter().invalidField(this, (FieldBinding) binding); + } else if (binding instanceof ProblemReferenceBinding) { + scope.problemReporter().invalidType(this, (TypeBinding) binding); + } else { + scope.problemReporter().unresolvableReference(this, binding); + } + return null; + } + + public TypeBinding resolveType(BlockScope scope) { + // for code gen, harm the restrictiveFlag + + this.actualReceiverType = this.receiverType = scope + .enclosingSourceType(); + + if ((this.codegenBinding = this.binding = scope.getBinding(token, bits + & RestrictiveFlagMASK, this)).isValidBinding()) { + switch (bits & RestrictiveFlagMASK) { + case VARIABLE: // =========only variable============ + case VARIABLE | TYPE: // ====both variable and type============ if (binding instanceof VariableBinding) { VariableBinding variable = (VariableBinding) binding; if (binding instanceof LocalVariableBinding) { - bits &= ~RestrictiveFlagMASK; // clear bits + bits &= ~RestrictiveFlagMASK; // clear bits bits |= LOCAL; if ((this.bits & IsStrictlyAssignedMASK) == 0) { constant = variable.constant; @@ -637,7 +780,10 @@ public TypeBinding resolveType(BlockScope scope) { constant = NotAConstant; } if ((!variable.isFinal()) && ((bits & DepthMASK) != 0)) { - scope.problemReporter().cannotReferToNonFinalOuterLocal((LocalVariableBinding)variable, this); + scope.problemReporter() + .cannotReferToNonFinalOuterLocal( + (LocalVariableBinding) variable, + this); } return this.resolvedType = variable.type; } @@ -646,32 +792,39 @@ public TypeBinding resolveType(BlockScope scope) { } // thus it was a type - bits &= ~RestrictiveFlagMASK; // clear bits + bits &= ~RestrictiveFlagMASK; // clear bits bits |= TYPE; - case TYPE : //========only type============== + case TYPE: // ========only type============== constant = Constant.NotAConstant; - //deprecated test + // deprecated test if (isTypeUseDeprecated((TypeBinding) binding, scope)) - scope.problemReporter().deprecatedType((TypeBinding) binding, this); + scope.problemReporter().deprecatedType( + (TypeBinding) binding, this); return this.resolvedType = (TypeBinding) binding; + } } + + // error scenarii + return this.resolvedType = this.reportError(scope); } - // error scenarii - return this.resolvedType = this.reportError(scope); -} -public StringBuffer printExpression(int indent, StringBuffer output){ - + public StringBuffer printExpression(int indent, StringBuffer output) { + return output.append(token); } -public String toStringExpression(){ - return new String(token);} -public void traverse(IAbstractSyntaxTreeVisitor visitor, BlockScope scope) { - visitor.visit(this, scope); - visitor.endVisit(this, scope); -} -public String unboundReferenceErrorName(){ + public String toStringExpression() { + + return new String(token); + } - return new String(token);} + public void traverse(IAbstractSyntaxTreeVisitor visitor, BlockScope scope) { + visitor.visit(this, scope); + visitor.endVisit(this, scope); + } + + public String unboundReferenceErrorName() { + + return new String(token); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/SingleTypeReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/SingleTypeReference.java index 5d3cedb..d86c411 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/SingleTypeReference.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/SingleTypeReference.java @@ -21,6 +21,7 @@ import org.eclipse.core.resources.IFile; public class SingleTypeReference extends TypeReference { public char[] token; + public IFile file; public SingleTypeReference(IFile f, char[] source, int start, int end) { @@ -29,55 +30,68 @@ public class SingleTypeReference extends TypeReference { sourceStart = start; sourceEnd = end; -} -public SingleTypeReference(char[] source, long pos) { + } + + public SingleTypeReference(char[] source, long pos) { token = source; file = null; - sourceStart = (int) (pos>>>32) ; - sourceEnd = (int) (pos & 0x00000000FFFFFFFFL) ; + sourceStart = (int) (pos >>> 32); + sourceEnd = (int) (pos & 0x00000000FFFFFFFFL); -} -public SingleTypeReference(char[] source ,TypeBinding type, long pos) { - this(source, pos) ; - this.resolvedType = type ; -} -public TypeReference copyDims(int dim){ - //return a type reference copy of me with some dimensions - //warning : the new type ref has a null binding + } - return new ArrayTypeReference(token,null,dim,(((long)sourceStart)<<32)+sourceEnd) ; -} -public TypeBinding getTypeBinding(Scope scope) { - if (this.resolvedType != null) - return this.resolvedType; - return scope.getType(token); -} -public char [][] getTypeName() { - return new char[][] { token }; -} -public TypeBinding resolveTypeEnclosing(BlockScope scope, ReferenceBinding enclosingType) { - ReferenceBinding memberTb = scope.getMemberType(token, enclosingType); - if (!memberTb.isValidBinding()) { - scope.problemReporter().invalidEnclosingType(this, memberTb, enclosingType); - return null; + public SingleTypeReference(char[] source, TypeBinding type, long pos) { + this(source, pos); + this.resolvedType = type; } - if (isTypeUseDeprecated(memberTb, scope)) - scope.problemReporter().deprecatedType(memberTb, this); - return this.resolvedType = memberTb; -} -public StringBuffer printExpression(int indent, StringBuffer output){ - return output.append(token); -} -public String toStringExpression(int tab){ - return new String(token) ; -} -public void traverse(ASTVisitor visitor, BlockScope scope) { - visitor.visit(this, scope); - visitor.endVisit(this, scope); -} -public void traverse(ASTVisitor visitor, ClassScope scope) { - visitor.visit(this, scope); - visitor.endVisit(this, scope); -} + public TypeReference copyDims(int dim) { + // return a type reference copy of me with some dimensions + // warning : the new type ref has a null binding + + return new ArrayTypeReference(token, null, dim, + (((long) sourceStart) << 32) + sourceEnd); + } + + public TypeBinding getTypeBinding(Scope scope) { + if (this.resolvedType != null) + return this.resolvedType; + return scope.getType(token); + } + + public char[][] getTypeName() { + return new char[][] { token }; + } + + public TypeBinding resolveTypeEnclosing(BlockScope scope, + ReferenceBinding enclosingType) { + ReferenceBinding memberTb = scope.getMemberType(token, enclosingType); + if (!memberTb.isValidBinding()) { + scope.problemReporter().invalidEnclosingType(this, memberTb, + enclosingType); + return null; + } + if (isTypeUseDeprecated(memberTb, scope)) + scope.problemReporter().deprecatedType(memberTb, this); + return this.resolvedType = memberTb; + } + + public StringBuffer printExpression(int indent, StringBuffer output) { + + return output.append(token); + } + + public String toStringExpression(int tab) { + return new String(token); + } + + public void traverse(ASTVisitor visitor, BlockScope scope) { + visitor.visit(this, scope); + visitor.endVisit(this, scope); + } + + public void traverse(ASTVisitor visitor, ClassScope scope) { + visitor.visit(this, scope); + visitor.endVisit(this, scope); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Statement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Statement.java index 08b01e4..12893a4 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Statement.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Statement.java @@ -17,58 +17,64 @@ import net.sourceforge.phpdt.internal.compiler.impl.Constant; import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; - public abstract class Statement extends ASTNode { - + /** * Statement constructor comment. - */ + */ public Statement() { super(); } - - public abstract FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo); - -// public abstract void generateCode(BlockScope currentScope, CodeStream codeStream); - + + public abstract FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo); + + // public abstract void generateCode(BlockScope currentScope, CodeStream + // codeStream); + public boolean isEmptyBlock() { return false; } - + public boolean isValidJavaStatement() { - //the use of this method should be avoid in most cases - //and is here mostly for documentation purpose..... - //while the parser is responsable for creating - //welled formed expression statement, which results - //in the fact that java-non-semantic-expression-used-as-statement - //should not be parsable...thus not being built. - //It sounds like the java grammar as help the compiler job in removing - //-by construction- some statement that would have no effect.... - //(for example all expression that may do side-effects are valid statement + // the use of this method should be avoid in most cases + // and is here mostly for documentation purpose..... + // while the parser is responsable for creating + // welled formed expression statement, which results + // in the fact that java-non-semantic-expression-used-as-statement + // should not be parsable...thus not being built. + // It sounds like the java grammar as help the compiler job in removing + // -by construction- some statement that would have no effect.... + // (for example all expression that may do side-effects are valid + // statement // -this is an appromative idea.....-) return true; } + public StringBuffer print(int indent, StringBuffer output) { return printStatement(indent, output); } + public abstract StringBuffer printStatement(int indent, StringBuffer output); public abstract void resolve(BlockScope scope); - - public Constant resolveCase(BlockScope scope, TypeBinding testType, SwitchStatement switchStatement) { - // statement within a switch that are not case are treated as normal statement.... + + public Constant resolveCase(BlockScope scope, TypeBinding testType, + SwitchStatement switchStatement) { + // statement within a switch that are not case are treated as normal + // statement.... resolve(scope); return null; } - + public void resetStateForCodeGeneration() { } - + /** - * INTERNAL USE ONLY. - * Do nothing by default. This is used to redirect inter-statements jumps. + * INTERNAL USE ONLY. Do nothing by default. This is used to redirect + * inter-statements jumps. */ public void branchChainTo(Label label) { } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/StringLiteral.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/StringLiteral.java index 24892a2..72b2083 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/StringLiteral.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/StringLiteral.java @@ -14,134 +14,137 @@ import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class StringLiteral extends Literal { - char[] source; - - public StringLiteral(char[] token, int s, int e) { - - this(s, e); - source = token; - } - - public StringLiteral(int s, int e) { - - super(s, e); - } - - public void computeConstant() { - - constant = Constant.fromValue(String.valueOf(source)); - } - -// public ExtendedStringLiteral extendWith(CharLiteral lit) { -// -// //add the lit source to mine, just as if it was mine -// return new ExtendedStringLiteral(this, lit); -// } - - public ExtendedStringLiteral extendWith(StringLiteral lit) { - - //add the lit source to mine, just as if it was mine - return new ExtendedStringLiteral(this, lit); - } - - /** - * Code generation for string literal - */ - // public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) { - // - // int pc = codeStream.position; - // if (valueRequired) - // codeStream.ldc(constant.stringValue()); - // codeStream.recordPositionsFrom(pc, this.sourceStart); - // } - public TypeBinding literalType(BlockScope scope) { - - return scope.getJavaLangString(); - } - - public StringBuffer printExpression(int indent, StringBuffer output) { - - // handle some special char..... - output.append('\"'); - for (int i = 0; i < source.length; i++) { - switch (source[i]) { - case '\b': - output.append("\\b"); //$NON-NLS-1$ - break; - case '\t': - output.append("\\t"); //$NON-NLS-1$ - break; - case '\n': - output.append("\\n"); //$NON-NLS-1$ - break; - case '\f': - output.append("\\f"); //$NON-NLS-1$ - break; - case '\r': - output.append("\\r"); //$NON-NLS-1$ - break; - case '\"': - output.append("\\\""); //$NON-NLS-1$ - break; - case '\'': - output.append("\\'"); //$NON-NLS-1$ - break; - case '\\': //take care not to display the escape as a potential real char - output.append("\\\\"); //$NON-NLS-1$ - break; - default: - output.append(source[i]); - } - } - output.append('\"'); - return output; - } - - public char[] source() { - - return source; - } - - public String toStringExpression() { - - // handle some special char..... - StringBuffer result = new StringBuffer("\""); //$NON-NLS-1$ - for (int i = 0; i < source.length; i++) { - switch (source[i]) { - case '\b': - result.append("\\b"); //$NON-NLS-1$ - break; - case '\t': - result.append("\\t"); //$NON-NLS-1$ - break; - case '\n': - result.append("\\n"); //$NON-NLS-1$ - break; - case '\f': - result.append("\\f"); //$NON-NLS-1$ - break; - case '\r': - result.append("\\r"); //$NON-NLS-1$ - break; - case '\"': - result.append("\\\""); //$NON-NLS-1$ - break; - case '\'': - result.append("\\'"); //$NON-NLS-1$ - break; - case '\\': //take care not to display the escape as a potential real char - result.append("\\\\"); //$NON-NLS-1$ - break; - default: - result.append(source[i]); - } - } - result.append("\""); //$NON-NLS-1$ - return result.toString(); - } - - public void traverse(IAbstractSyntaxTreeVisitor visitor, BlockScope scope) { - visitor.visit(this, scope); - visitor.endVisit(this, scope); - } + char[] source; + + public StringLiteral(char[] token, int s, int e) { + + this(s, e); + source = token; + } + + public StringLiteral(int s, int e) { + + super(s, e); + } + + public void computeConstant() { + + constant = Constant.fromValue(String.valueOf(source)); + } + + // public ExtendedStringLiteral extendWith(CharLiteral lit) { + // + // //add the lit source to mine, just as if it was mine + // return new ExtendedStringLiteral(this, lit); + // } + + public ExtendedStringLiteral extendWith(StringLiteral lit) { + + // add the lit source to mine, just as if it was mine + return new ExtendedStringLiteral(this, lit); + } + + /** + * Code generation for string literal + */ + // public void generateCode(BlockScope currentScope, CodeStream codeStream, + // boolean valueRequired) { + // + // int pc = codeStream.position; + // if (valueRequired) + // codeStream.ldc(constant.stringValue()); + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } + public TypeBinding literalType(BlockScope scope) { + + return scope.getJavaLangString(); + } + + public StringBuffer printExpression(int indent, StringBuffer output) { + + // handle some special char..... + output.append('\"'); + for (int i = 0; i < source.length; i++) { + switch (source[i]) { + case '\b': + output.append("\\b"); //$NON-NLS-1$ + break; + case '\t': + output.append("\\t"); //$NON-NLS-1$ + break; + case '\n': + output.append("\\n"); //$NON-NLS-1$ + break; + case '\f': + output.append("\\f"); //$NON-NLS-1$ + break; + case '\r': + output.append("\\r"); //$NON-NLS-1$ + break; + case '\"': + output.append("\\\""); //$NON-NLS-1$ + break; + case '\'': + output.append("\\'"); //$NON-NLS-1$ + break; + case '\\': // take care not to display the escape as a potential + // real char + output.append("\\\\"); //$NON-NLS-1$ + break; + default: + output.append(source[i]); + } + } + output.append('\"'); + return output; + } + + public char[] source() { + + return source; + } + + public String toStringExpression() { + + // handle some special char..... + StringBuffer result = new StringBuffer("\""); //$NON-NLS-1$ + for (int i = 0; i < source.length; i++) { + switch (source[i]) { + case '\b': + result.append("\\b"); //$NON-NLS-1$ + break; + case '\t': + result.append("\\t"); //$NON-NLS-1$ + break; + case '\n': + result.append("\\n"); //$NON-NLS-1$ + break; + case '\f': + result.append("\\f"); //$NON-NLS-1$ + break; + case '\r': + result.append("\\r"); //$NON-NLS-1$ + break; + case '\"': + result.append("\\\""); //$NON-NLS-1$ + break; + case '\'': + result.append("\\'"); //$NON-NLS-1$ + break; + case '\\': // take care not to display the escape as a potential + // real char + result.append("\\\\"); //$NON-NLS-1$ + break; + default: + result.append(source[i]); + } + } + result.append("\""); //$NON-NLS-1$ + return result.toString(); + } + + public void traverse(IAbstractSyntaxTreeVisitor visitor, BlockScope scope) { + visitor.visit(this, scope); + visitor.endVisit(this, scope); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/StringLiteralDQ.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/StringLiteralDQ.java index 88ce3e6..37df2b5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/StringLiteralDQ.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/StringLiteralDQ.java @@ -16,50 +16,51 @@ package net.sourceforge.phpdt.internal.compiler.ast; */ public class StringLiteralDQ extends StringLiteral { - public StringLiteralDQ(char[] token, int s, int e) { - super(token, s, e); - } + public StringLiteralDQ(char[] token, int s, int e) { + super(token, s, e); + } - public StringLiteralDQ(int s, int e) { - super(s, e); - } + public StringLiteralDQ(int s, int e) { + super(s, e); + } - public String toStringExpression() { + public String toStringExpression() { - // handle some special char..... - StringBuffer result = new StringBuffer("\""); //$NON-NLS-1$ - for (int i = 0; i < source.length; i++) { - switch (source[i]) { - case '\b': - result.append("\\b"); //$NON-NLS-1$ - break; - case '\t': - result.append("\\t"); //$NON-NLS-1$ - break; - case '\n': - result.append("\\n"); //$NON-NLS-1$ - break; - case '\f': - result.append("\\f"); //$NON-NLS-1$ - break; - case '\r': - result.append("\\r"); //$NON-NLS-1$ - break; - case '\"': - result.append("\\\""); //$NON-NLS-1$ - break; - case '\'': - result.append("\\'"); //$NON-NLS-1$ - break; - case '\\': //take care not to display the escape as a potential real char - result.append("\\\\"); //$NON-NLS-1$ - break; - default: - result.append(source[i]); - } - } - result.append("\""); //$NON-NLS-1$ - return result.toString(); - } + // handle some special char..... + StringBuffer result = new StringBuffer("\""); //$NON-NLS-1$ + for (int i = 0; i < source.length; i++) { + switch (source[i]) { + case '\b': + result.append("\\b"); //$NON-NLS-1$ + break; + case '\t': + result.append("\\t"); //$NON-NLS-1$ + break; + case '\n': + result.append("\\n"); //$NON-NLS-1$ + break; + case '\f': + result.append("\\f"); //$NON-NLS-1$ + break; + case '\r': + result.append("\\r"); //$NON-NLS-1$ + break; + case '\"': + result.append("\\\""); //$NON-NLS-1$ + break; + case '\'': + result.append("\\'"); //$NON-NLS-1$ + break; + case '\\': // take care not to display the escape as a potential + // real char + result.append("\\\\"); //$NON-NLS-1$ + break; + default: + result.append(source[i]); + } + } + result.append("\""); //$NON-NLS-1$ + return result.toString(); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/StringLiteralSQ.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/StringLiteralSQ.java index 98d3244..23609ef 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/StringLiteralSQ.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/StringLiteralSQ.java @@ -15,51 +15,52 @@ package net.sourceforge.phpdt.internal.compiler.ast; * single quoted string literal */ public class StringLiteralSQ extends StringLiteral { - public StringLiteralSQ(char[] token, int s, int e) { - super(token, s, e); - } + public StringLiteralSQ(char[] token, int s, int e) { + super(token, s, e); + } - public StringLiteralSQ(int s, int e) { + public StringLiteralSQ(int s, int e) { - super(s, e); - } + super(s, e); + } - public String toStringExpression() { + public String toStringExpression() { - // handle some special char..... - StringBuffer result = new StringBuffer("\'"); //$NON-NLS-1$ - for (int i = 0; i < source.length; i++) { - switch (source[i]) { - case '\b': - result.append("\\b"); //$NON-NLS-1$ - break; - case '\t': - result.append("\\t"); //$NON-NLS-1$ - break; - case '\n': - result.append("\\n"); //$NON-NLS-1$ - break; - case '\f': - result.append("\\f"); //$NON-NLS-1$ - break; - case '\r': - result.append("\\r"); //$NON-NLS-1$ - break; - case '\"': - result.append("\\\""); //$NON-NLS-1$ - break; - case '\'': - result.append("\\'"); //$NON-NLS-1$ - break; - case '\\': //take care not to display the escape as a potential real char - result.append("\\\\"); //$NON-NLS-1$ - break; - default: - result.append(source[i]); - } - } - result.append("\'"); //$NON-NLS-1$ - return result.toString(); - } + // handle some special char..... + StringBuffer result = new StringBuffer("\'"); //$NON-NLS-1$ + for (int i = 0; i < source.length; i++) { + switch (source[i]) { + case '\b': + result.append("\\b"); //$NON-NLS-1$ + break; + case '\t': + result.append("\\t"); //$NON-NLS-1$ + break; + case '\n': + result.append("\\n"); //$NON-NLS-1$ + break; + case '\f': + result.append("\\f"); //$NON-NLS-1$ + break; + case '\r': + result.append("\\r"); //$NON-NLS-1$ + break; + case '\"': + result.append("\\\""); //$NON-NLS-1$ + break; + case '\'': + result.append("\\'"); //$NON-NLS-1$ + break; + case '\\': // take care not to display the escape as a potential + // real char + result.append("\\\\"); //$NON-NLS-1$ + break; + default: + result.append(source[i]); + } + } + result.append("\'"); //$NON-NLS-1$ + return result.toString(); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/SuperReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/SuperReference.java index 60d2df4..5610a74 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/SuperReference.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/SuperReference.java @@ -16,43 +16,52 @@ import net.sourceforge.phpdt.internal.compiler.lookup.SourceTypeBinding; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class SuperReference extends ThisReference { - -public SuperReference(int sourceStart, int sourceEnd) { - super(sourceStart, sourceEnd); -} -public static ExplicitConstructorCall implicitSuperConstructorCall() { - return new ExplicitConstructorCall(ExplicitConstructorCall.ImplicitSuper); -} -public boolean isImplicitThis() { - - return false; -} -public boolean isSuper() { - - return true; -} -public boolean isThis() { - - return false ; -} -public TypeBinding resolveType(BlockScope scope) { - constant = NotAConstant; - if (!checkAccess(scope.methodScope())) - return null; - SourceTypeBinding enclosingTb = scope.enclosingSourceType(); - if (scope.isJavaLangObject(enclosingTb)) { - scope.problemReporter().cannotUseSuperInJavaLangObject(this); - return null; - } - return this.resolvedType = enclosingTb.superclass; -} -public String toStringExpression(){ - return "super"; //$NON-NLS-1$ - -} -public void traverse(IAbstractSyntaxTreeVisitor visitor, BlockScope blockScope) { - visitor.visit(this, blockScope); - visitor.endVisit(this, blockScope); -} + public SuperReference(int sourceStart, int sourceEnd) { + super(sourceStart, sourceEnd); + } + + public static ExplicitConstructorCall implicitSuperConstructorCall() { + return new ExplicitConstructorCall( + ExplicitConstructorCall.ImplicitSuper); + } + + public boolean isImplicitThis() { + + return false; + } + + public boolean isSuper() { + + return true; + } + + public boolean isThis() { + + return false; + } + + public TypeBinding resolveType(BlockScope scope) { + constant = NotAConstant; + if (!checkAccess(scope.methodScope())) + return null; + SourceTypeBinding enclosingTb = scope.enclosingSourceType(); + if (scope.isJavaLangObject(enclosingTb)) { + scope.problemReporter().cannotUseSuperInJavaLangObject(this); + return null; + } + return this.resolvedType = enclosingTb.superclass; + } + + public String toStringExpression() { + + return "super"; //$NON-NLS-1$ + + } + + public void traverse(IAbstractSyntaxTreeVisitor visitor, + BlockScope blockScope) { + visitor.visit(this, blockScope); + visitor.endVisit(this, blockScope); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/SwitchStatement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/SwitchStatement.java index 91984b0..55cdca7 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/SwitchStatement.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/SwitchStatement.java @@ -21,185 +21,213 @@ import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class SwitchStatement extends Statement { public Expression expression; + public Statement[] statements; + public BlockScope scope; + public int explicitDeclarations; + public Label breakLabel; + public CaseStatement[] cases; + public DefaultCase defaultCase; + public int caseCount = 0; // for local variables table attributes int preSwitchInitStateIndex = -1; + int mergedInitStateIndex = -1; + /** * SwitchStatement constructor comment. */ public SwitchStatement() { super(); } - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { + + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { flowInfo = expression.analyseCode(currentScope, flowContext, flowInfo); - SwitchFlowContext switchContext = - new SwitchFlowContext(flowContext, this, (breakLabel = new Label())); + SwitchFlowContext switchContext = new SwitchFlowContext(flowContext, + this, (breakLabel = new Label())); - // analyse the block by considering specially the case/default statements (need to bind them + // analyse the block by considering specially the case/default + // statements (need to bind them // to the entry point) FlowInfo caseInits = FlowInfo.DEAD_END; // in case of statements before the first case - preSwitchInitStateIndex = - currentScope.methodScope().recordInitializationStates(flowInfo); + preSwitchInitStateIndex = currentScope.methodScope() + .recordInitializationStates(flowInfo); int caseIndex = 0; if (statements != null) { boolean didAlreadyComplain = false; for (int i = 0, max = statements.length; i < max; i++) { Statement statement = statements[i]; - if ((caseIndex < caseCount) && (statement == cases[caseIndex])) { // statement is a case + if ((caseIndex < caseCount) && (statement == cases[caseIndex])) { // statement + // is a + // case caseIndex++; - caseInits = caseInits.mergedWith(flowInfo.copy().unconditionalInits()); + caseInits = caseInits.mergedWith(flowInfo.copy() + .unconditionalInits()); didAlreadyComplain = false; // reset complaint - } else if (statement == defaultCase) { // statement is the default case - caseInits = caseInits.mergedWith(flowInfo.copy().unconditionalInits()); + } else if (statement == defaultCase) { // statement is the + // default case + caseInits = caseInits.mergedWith(flowInfo.copy() + .unconditionalInits()); didAlreadyComplain = false; // reset complaint } - if (!caseInits.complainIfUnreachable(statement, scope, didAlreadyComplain)) { - caseInits = statement.analyseCode(scope, switchContext, caseInits); + if (!caseInits.complainIfUnreachable(statement, scope, + didAlreadyComplain)) { + caseInits = statement.analyseCode(scope, switchContext, + caseInits); } else { didAlreadyComplain = true; } } } - // if no default case, then record it may jump over the block directly to the end + // if no default case, then record it may jump over the block directly + // to the end if (defaultCase == null) { // only retain the potential initializations - flowInfo.addPotentialInitializationsFrom( - caseInits.mergedWith(switchContext.initsOnBreak)); - mergedInitStateIndex = - currentScope.methodScope().recordInitializationStates(flowInfo); + flowInfo.addPotentialInitializationsFrom(caseInits + .mergedWith(switchContext.initsOnBreak)); + mergedInitStateIndex = currentScope.methodScope() + .recordInitializationStates(flowInfo); return flowInfo; } // merge all branches inits FlowInfo mergedInfo = caseInits.mergedWith(switchContext.initsOnBreak); - mergedInitStateIndex = - currentScope.methodScope().recordInitializationStates(mergedInfo); + mergedInitStateIndex = currentScope.methodScope() + .recordInitializationStates(mergedInfo); return mergedInfo; } + /** * Switch code generation - * - * @param currentScope net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream */ -// public void generateCode(BlockScope currentScope, CodeStream codeStream) { -// int[] sortedIndexes = new int[caseCount]; -// int[] localKeysCopy; -// if ((bits & IsReachableMASK) == 0) { -// return; -// } -// int pc = codeStream.position; -// -// // prepare the labels and constants -// breakLabel.codeStream = codeStream; -// CaseLabel[] caseLabels = new CaseLabel[caseCount]; -// int[] constants = new int[caseCount]; -// boolean needSwitch = caseCount != 0; -// for (int i = 0; i < caseCount; i++) { -// constants[i] = cases[i].constantExpression.constant.intValue(); -// cases[i].targetLabel = (caseLabels[i] = new CaseLabel(codeStream)); -// } -// -// // we sort the keys to be able to generate the code for tableswitch or lookupswitch -// for (int i = 0; i < caseCount; i++) { -// sortedIndexes[i] = i; -// } -// System.arraycopy( -// constants, -// 0, -// (localKeysCopy = new int[caseCount]), -// 0, -// caseCount); -// CodeStream.sort(localKeysCopy, 0, caseCount - 1, sortedIndexes); -// CaseLabel defaultLabel = new CaseLabel(codeStream); -// if (defaultCase != null) { -// defaultCase.targetLabel = defaultLabel; -// } -// // generate expression testes -// testExpression.generateCode(currentScope, codeStream, needSwitch); -// -// // generate the appropriate switch table/lookup bytecode -// if (needSwitch) { -// int max = localKeysCopy[caseCount - 1]; -// int min = localKeysCopy[0]; -// if ((long) (caseCount * 2.5) > ((long) max - (long) min)) { -// -// // work-around 1.3 VM bug, if max>0x7FFF0000, must use lookup bytecode -// // see http://dev.eclipse.org/bugs/show_bug.cgi?id=21557 -// if (max > 0x7FFF0000 && currentScope.environment().options.complianceLevel < CompilerOptions.JDK1_4) { -// codeStream.lookupswitch(defaultLabel, constants, sortedIndexes, caseLabels); -// -// } else { -// codeStream.tableswitch( -// defaultLabel, -// min, -// max, -// constants, -// sortedIndexes, -// caseLabels); -// } -// } else { -// codeStream.lookupswitch(defaultLabel, constants, sortedIndexes, caseLabels); -// } -// codeStream.updateLastRecordedEndPC(codeStream.position); -// } -// -// // generate the switch block statements -// int caseIndex = 0; -// if (statements != null) { -// for (int i = 0, maxCases = statements.length; i < maxCases; i++) { -// Statement statement = statements[i]; -// if ((caseIndex < caseCount) -// && (statement == cases[caseIndex])) { // statements[i] is a case -// if (preSwitchInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// preSwitchInitStateIndex); -// caseIndex++; -// } -// } else { -// if (statement == defaultCase) { // statements[i] is a case or a default case -// if (preSwitchInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// preSwitchInitStateIndex); -// } -// } -// } -// statement.generateCode(scope, codeStream); -// } -// } -// // place the trailing labels (for break and default case) -// breakLabel.place(); -// if (defaultCase == null) { -// defaultLabel.place(); -// } -// // May loose some local variable initializations : affecting the local variable attributes -// if (mergedInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// mergedInitStateIndex); -// codeStream.addDefinitelyAssignedVariables(currentScope, mergedInitStateIndex); -// } -// if (scope != currentScope) { -// codeStream.exitUserScope(scope); -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } - + // public void generateCode(BlockScope currentScope, CodeStream codeStream) + // { + // int[] sortedIndexes = new int[caseCount]; + // int[] localKeysCopy; + // if ((bits & IsReachableMASK) == 0) { + // return; + // } + // int pc = codeStream.position; + // + // // prepare the labels and constants + // breakLabel.codeStream = codeStream; + // CaseLabel[] caseLabels = new CaseLabel[caseCount]; + // int[] constants = new int[caseCount]; + // boolean needSwitch = caseCount != 0; + // for (int i = 0; i < caseCount; i++) { + // constants[i] = cases[i].constantExpression.constant.intValue(); + // cases[i].targetLabel = (caseLabels[i] = new CaseLabel(codeStream)); + // } + // + // // we sort the keys to be able to generate the code for tableswitch or + // lookupswitch + // for (int i = 0; i < caseCount; i++) { + // sortedIndexes[i] = i; + // } + // System.arraycopy( + // constants, + // 0, + // (localKeysCopy = new int[caseCount]), + // 0, + // caseCount); + // CodeStream.sort(localKeysCopy, 0, caseCount - 1, sortedIndexes); + // CaseLabel defaultLabel = new CaseLabel(codeStream); + // if (defaultCase != null) { + // defaultCase.targetLabel = defaultLabel; + // } + // // generate expression testes + // testExpression.generateCode(currentScope, codeStream, needSwitch); + // + // // generate the appropriate switch table/lookup bytecode + // if (needSwitch) { + // int max = localKeysCopy[caseCount - 1]; + // int min = localKeysCopy[0]; + // if ((long) (caseCount * 2.5) > ((long) max - (long) min)) { + // + // // work-around 1.3 VM bug, if max>0x7FFF0000, must use lookup bytecode + // // see http://dev.eclipse.org/bugs/show_bug.cgi?id=21557 + // if (max > 0x7FFF0000 && + // currentScope.environment().options.complianceLevel < + // CompilerOptions.JDK1_4) { + // codeStream.lookupswitch(defaultLabel, constants, sortedIndexes, + // caseLabels); + // + // } else { + // codeStream.tableswitch( + // defaultLabel, + // min, + // max, + // constants, + // sortedIndexes, + // caseLabels); + // } + // } else { + // codeStream.lookupswitch(defaultLabel, constants, sortedIndexes, + // caseLabels); + // } + // codeStream.updateLastRecordedEndPC(codeStream.position); + // } + // + // // generate the switch block statements + // int caseIndex = 0; + // if (statements != null) { + // for (int i = 0, maxCases = statements.length; i < maxCases; i++) { + // Statement statement = statements[i]; + // if ((caseIndex < caseCount) + // && (statement == cases[caseIndex])) { // statements[i] is a case + // if (preSwitchInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // preSwitchInitStateIndex); + // caseIndex++; + // } + // } else { + // if (statement == defaultCase) { // statements[i] is a case or a default + // case + // if (preSwitchInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // preSwitchInitStateIndex); + // } + // } + // } + // statement.generateCode(scope, codeStream); + // } + // } + // // place the trailing labels (for break and default case) + // breakLabel.place(); + // if (defaultCase == null) { + // defaultLabel.place(); + // } + // // May loose some local variable initializations : affecting the local + // variable attributes + // if (mergedInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // mergedInitStateIndex); + // codeStream.addDefinitelyAssignedVariables(currentScope, + // mergedInitStateIndex); + // } + // if (scope != currentScope) { + // codeStream.exitUserScope(scope); + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } public void resetStateForCodeGeneration() { if (this.breakLabel != null) { @@ -217,41 +245,55 @@ public class SwitchStatement extends Statement { if (statements[i] instanceof CaseStatement) { statements[i].printStatement(indent, output); } else { - statements[i].printStatement(indent+2, output); + statements[i].printStatement(indent + 2, output); } } } output.append("\n"); //$NON-NLS-1$ return printIndent(indent, output).append('}'); } + public void resolve(BlockScope upperScope) { TypeBinding testType = expression.resolveType(upperScope); if (testType == null) return; expression.implicitWidening(testType, testType); - if (!(expression.isConstantValueOfTypeAssignableToType(testType, IntBinding))) { + if (!(expression.isConstantValueOfTypeAssignableToType(testType, + IntBinding))) { if (!testType.isCompatibleWith(IntBinding)) { - upperScope.problemReporter().incorrectSwitchType(expression, testType); + upperScope.problemReporter().incorrectSwitchType(expression, + testType); return; } } if (statements != null) { - scope = explicitDeclarations == 0 ? upperScope : new BlockScope(upperScope); + scope = explicitDeclarations == 0 ? upperScope : new BlockScope( + upperScope); int length; - // collection of cases is too big but we will only iterate until caseCount + // collection of cases is too big but we will only iterate until + // caseCount cases = new CaseStatement[length = statements.length]; int[] casesValues = new int[length]; int counter = 0; for (int i = 0; i < length; i++) { Constant cst; if ((cst = statements[i].resolveCase(scope, testType, this)) != null) { - //----check for duplicate case statement------------ + // ----check for duplicate case statement------------ if (cst != NotAConstant) { int key = cst.intValue(); for (int j = 0; j < counter; j++) { if (casesValues[j] == key) { - scope.problemReporter().duplicateCase((CaseStatement) statements[i], cst); //TODO: (philippe) could improve diagnosis to indicate colliding case + scope.problemReporter().duplicateCase( + (CaseStatement) statements[i], cst); // TODO: + // (philippe) + // could + // improve + // diagnosis + // to + // indicate + // colliding + // case } } casesValues[counter++] = key; @@ -260,6 +302,7 @@ public class SwitchStatement extends Statement { } } } + public String toString(int tab) { String inFront, s = tabString(tab); @@ -270,34 +313,35 @@ public class SwitchStatement extends Statement { return s; } else s = s + "{"; //$NON-NLS-1$ - s = s - + (explicitDeclarations != 0 - ? "// ---scope needed for " //$NON-NLS-1$ - + String.valueOf(explicitDeclarations) - + " locals------------ \n"//$NON-NLS-1$ - : "// ---NO scope needed------ \n"); //$NON-NLS-1$ + s = s + + (explicitDeclarations != 0 ? "// ---scope needed for " //$NON-NLS-1$ + + String.valueOf(explicitDeclarations) + + " locals------------ \n"//$NON-NLS-1$ + : "// ---NO scope needed------ \n"); //$NON-NLS-1$ int i = 0; String tabulation = " "; //$NON-NLS-1$ try { while (true) { - //use instanceof in order not to polluate classes with behavior only needed for printing purpose. + // use instanceof in order not to polluate classes with behavior + // only needed for printing purpose. if (statements[i] instanceof Expression) s = s + "\n" + inFront + tabulation; //$NON-NLS-1$ if (statements[i] instanceof BreakStatement) s = s + statements[i].toString(0); else s = s + "\n" + statements[i].toString(tab + 2); //$NON-NLS-1$ - //============= + // ============= if ((statements[i] instanceof CaseStatement) - || (statements[i] instanceof DefaultCase)) { + || (statements[i] instanceof DefaultCase)) { i++; - while (!((statements[i] instanceof CaseStatement) - || (statements[i] instanceof DefaultCase))) { - if ((statements[i] instanceof Expression) || (statements[i] instanceof BreakStatement)) + while (!((statements[i] instanceof CaseStatement) || (statements[i] instanceof DefaultCase))) { + if ((statements[i] instanceof Expression) + || (statements[i] instanceof BreakStatement)) s = s + statements[i].toString(0) + " ; "; //$NON-NLS-1$ else - s = s + "\n" + statements[i].toString(tab + 6) + " ; "; //$NON-NLS-1$ //$NON-NLS-2$ + s = s + + "\n" + statements[i].toString(tab + 6) + " ; "; //$NON-NLS-1$ //$NON-NLS-2$ i++; } } else { @@ -306,14 +350,13 @@ public class SwitchStatement extends Statement { } } } catch (IndexOutOfBoundsException e) { - }; + } + ; s = s + "}"; //$NON-NLS-1$ return s; } - public void traverse( - ASTVisitor visitor, - BlockScope blockScope) { + public void traverse(ASTVisitor visitor, BlockScope blockScope) { if (visitor.visit(this, blockScope)) { expression.traverse(visitor, scope); @@ -325,12 +368,12 @@ public class SwitchStatement extends Statement { } visitor.endVisit(this, blockScope); } - + /** * Dispatch the call on its last statement. */ public void branchChainTo(Label label) { - + // in order to improve debug attributes for stepping (11431) // we want to inline the jumps to #breakLabel which already got // generated (if any), and have them directly branch to a better diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ThisReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ThisReference.java index 38e2352..dd86d19 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ThisReference.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ThisReference.java @@ -16,112 +16,121 @@ import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class ThisReference extends Reference { - public static ThisReference implicitThis() { - - ThisReference implicitThis = new ThisReference(0, 0); - implicitThis.bits |= IsImplicitThisMask; - return implicitThis; - } - - public ThisReference(int sourceStart, int sourceEnd) { - - this.sourceStart = sourceStart; - this.sourceEnd = sourceEnd; - } - - /* - * @see Reference#analyseAssignment(...) - */ - public FlowInfo analyseAssignment(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo, Assignment assignment, - boolean isCompound) { - - return flowInfo; // this cannot be assigned - } - - public boolean checkAccess(MethodScope methodScope) { - - // this/super cannot be used in constructor call - if (methodScope.isConstructorCall) { - methodScope.problemReporter().fieldsOrThisBeforeConstructorInvocation(this); - return false; - } - - // static may not refer to this/super - if (methodScope.isStatic) { - methodScope.problemReporter().errorThisSuperInStatic(this); - return false; - } - return true; - } - - /* - * @see Reference#generateAssignment(...) - */ - // public void generateAssignment(BlockScope currentScope, CodeStream codeStream, Assignment assignment, boolean valueRequired) { - // - // // this cannot be assigned - // } - // - // public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) { - // - // int pc = codeStream.position; - // if (valueRequired) - // codeStream.aload_0(); - // if ((this.bits & IsImplicitThisMask) == 0) codeStream.recordPositionsFrom(pc, this.sourceStart); - // } - // - // /* - // * @see Reference#generateCompoundAssignment(...) - // */ - // public void generateCompoundAssignment(BlockScope currentScope, CodeStream codeStream, Expression expression, int operator, int - // assignmentImplicitConversion, boolean valueRequired) { - // - // // this cannot be assigned - // } - // - // /* - // * @see net.sourceforge.phpdt.internal.compiler.ast.Reference#generatePostIncrement() - // */ - // public void generatePostIncrement(BlockScope currentScope, CodeStream codeStream, CompoundAssignment postIncrement, boolean - // valueRequired) { - // - // // this cannot be assigned - // } - public boolean isImplicitThis() { - - return (this.bits & IsImplicitThisMask) != 0; - } - - public boolean isThis() { - - return true; - } - - public TypeBinding resolveType(BlockScope scope) { - - constant = NotAConstant; - if (!this.isImplicitThis() && !checkAccess(scope.methodScope())) - return null; - return this.resolvedType = scope.enclosingSourceType(); - } - - public StringBuffer printExpression(int indent, StringBuffer output) { - - if (this.isImplicitThis()) - return output; - return output.append("this"); //$NON-NLS-1$ - } - - public String toStringExpression() { - - if (this.isImplicitThis()) - return ""; //$NON-NLS-1$ - return "this"; //$NON-NLS-1$ - } - - public void traverse(IAbstractSyntaxTreeVisitor visitor, BlockScope blockScope) { - - visitor.visit(this, blockScope); - visitor.endVisit(this, blockScope); - } + public static ThisReference implicitThis() { + + ThisReference implicitThis = new ThisReference(0, 0); + implicitThis.bits |= IsImplicitThisMask; + return implicitThis; + } + + public ThisReference(int sourceStart, int sourceEnd) { + + this.sourceStart = sourceStart; + this.sourceEnd = sourceEnd; + } + + /* + * @see Reference#analyseAssignment(...) + */ + public FlowInfo analyseAssignment(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo, Assignment assignment, + boolean isCompound) { + + return flowInfo; // this cannot be assigned + } + + public boolean checkAccess(MethodScope methodScope) { + + // this/super cannot be used in constructor call + if (methodScope.isConstructorCall) { + methodScope.problemReporter() + .fieldsOrThisBeforeConstructorInvocation(this); + return false; + } + + // static may not refer to this/super + if (methodScope.isStatic) { + methodScope.problemReporter().errorThisSuperInStatic(this); + return false; + } + return true; + } + + /* + * @see Reference#generateAssignment(...) + */ + // public void generateAssignment(BlockScope currentScope, CodeStream + // codeStream, Assignment assignment, boolean valueRequired) { + // + // // this cannot be assigned + // } + // + // public void generateCode(BlockScope currentScope, CodeStream codeStream, + // boolean valueRequired) { + // + // int pc = codeStream.position; + // if (valueRequired) + // codeStream.aload_0(); + // if ((this.bits & IsImplicitThisMask) == 0) + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } + // + // /* + // * @see Reference#generateCompoundAssignment(...) + // */ + // public void generateCompoundAssignment(BlockScope currentScope, + // CodeStream codeStream, Expression expression, int operator, int + // assignmentImplicitConversion, boolean valueRequired) { + // + // // this cannot be assigned + // } + // + // /* + // * @see + // net.sourceforge.phpdt.internal.compiler.ast.Reference#generatePostIncrement() + // */ + // public void generatePostIncrement(BlockScope currentScope, CodeStream + // codeStream, CompoundAssignment postIncrement, boolean + // valueRequired) { + // + // // this cannot be assigned + // } + public boolean isImplicitThis() { + + return (this.bits & IsImplicitThisMask) != 0; + } + + public boolean isThis() { + + return true; + } + + public TypeBinding resolveType(BlockScope scope) { + + constant = NotAConstant; + if (!this.isImplicitThis() && !checkAccess(scope.methodScope())) + return null; + return this.resolvedType = scope.enclosingSourceType(); + } + + public StringBuffer printExpression(int indent, StringBuffer output) { + + if (this.isImplicitThis()) + return output; + return output.append("this"); //$NON-NLS-1$ + } + + public String toStringExpression() { + + if (this.isImplicitThis()) + return ""; //$NON-NLS-1$ + return "this"; //$NON-NLS-1$ + } + + public void traverse(IAbstractSyntaxTreeVisitor visitor, + BlockScope blockScope) { + + visitor.visit(this, blockScope); + visitor.endVisit(this, blockScope); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ThrowStatement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ThrowStatement.java index b6c5e29..f7b7dd8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ThrowStatement.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/ThrowStatement.java @@ -18,6 +18,7 @@ import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class ThrowStatement extends Statement { public Expression exception; + public TypeBinding exceptionType; public ThrowStatement(Expression exception, int startPosition) { @@ -26,47 +27,55 @@ public class ThrowStatement extends Statement { this.sourceEnd = exception.sourceEnd; } - public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { exception.analyseCode(currentScope, flowContext, flowInfo); // need to check that exception thrown is actually caught somewhere - flowContext.checkExceptionHandlers(exceptionType, this, flowInfo, currentScope); + flowContext.checkExceptionHandlers(exceptionType, this, flowInfo, + currentScope); return FlowInfo.DEAD_END; } /** * Throw code generation - * - * @param currentScope net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream */ -// public void generateCode(BlockScope currentScope, CodeStream codeStream) { -// -// if ((bits & IsReachableMASK) == 0) -// return; -// int pc = codeStream.position; -// exception.generateCode(currentScope, codeStream, true); -// codeStream.athrow(); -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } - + // public void generateCode(BlockScope currentScope, CodeStream codeStream) + // { + // + // if ((bits & IsReachableMASK) == 0) + // return; + // int pc = codeStream.position; + // exception.generateCode(currentScope, codeStream, true); + // codeStream.athrow(); + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } public void resolve(BlockScope scope) { - - exceptionType = exception.resolveTypeExpecting(scope, scope.getJavaLangThrowable()); - -// if (exceptionType == NullBinding -// && scope.environment().options.complianceLevel <= CompilerOptions.JDK1_3){ -// // if compliant with 1.4, this problem will not be reported -// scope.problemReporter().cannotThrowNull(this); -// } + + exceptionType = exception.resolveTypeExpecting(scope, scope + .getJavaLangThrowable()); + + // if (exceptionType == NullBinding + // && scope.environment().options.complianceLevel <= + // CompilerOptions.JDK1_3){ + // // if compliant with 1.4, this problem will not be reported + // scope.problemReporter().cannotThrowNull(this); + // } exception.implicitWidening(exceptionType, exceptionType); } + public StringBuffer printStatement(int indent, StringBuffer output) { printIndent(indent, output).append("throw "); //$NON-NLS-1$ exception.printExpression(0, output); return output.append(';'); } + public String toString(int tab) { String s = tabString(tab); s = s + "throw "; //$NON-NLS-1$ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/TrueLiteral.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/TrueLiteral.java index 181a99f..80ff4c8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/TrueLiteral.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/TrueLiteral.java @@ -15,55 +15,66 @@ import net.sourceforge.phpdt.internal.compiler.impl.Constant; import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; - public class TrueLiteral extends MagicLiteral { - static final char[] source = {'t' , 'r' , 'u' , 'e'}; -public TrueLiteral(int s , int e) { - super(s,e); -} -public void computeConstant() { + static final char[] source = { 't', 'r', 'u', 'e' }; - constant = Constant.fromValue(true);} -/** - * Code generation for the true literal - * - * @param currentScope net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream - * @param valueRequired boolean - */ -//public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) { -// int pc = codeStream.position; -// if (valueRequired) -// codeStream.iconst_1(); -// codeStream.recordPositionsFrom(pc, this.sourceStart); -//} -//public void generateOptimizedBoolean(BlockScope currentScope, CodeStream codeStream, Label trueLabel, Label falseLabel, boolean valueRequired) { -// -// // trueLabel being not nil means that we will not fall through into the TRUE case -// -// int pc = codeStream.position; -// // constant == true -// if (valueRequired) { -// if (falseLabel == null) { -// // implicit falling through the FALSE case -// if (trueLabel != null) { -// codeStream.goto_(trueLabel); -// } -// } -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -//} -public TypeBinding literalType(BlockScope scope) { - return BooleanBinding; -} -/** - * - */ -public char[] source() { - return source; -} -public void traverse(IAbstractSyntaxTreeVisitor visitor, BlockScope scope) { - visitor.visit(this, scope); - visitor.endVisit(this, scope); -} + public TrueLiteral(int s, int e) { + super(s, e); + } + + public void computeConstant() { + + constant = Constant.fromValue(true); + } + + /** + * Code generation for the true literal + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * @param valueRequired + * boolean + */ + // public void generateCode(BlockScope currentScope, CodeStream codeStream, + // boolean valueRequired) { + // int pc = codeStream.position; + // if (valueRequired) + // codeStream.iconst_1(); + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } + // public void generateOptimizedBoolean(BlockScope currentScope, CodeStream + // codeStream, Label trueLabel, Label falseLabel, boolean valueRequired) { + // + // // trueLabel being not nil means that we will not fall through into the + // TRUE case + // + // int pc = codeStream.position; + // // constant == true + // if (valueRequired) { + // if (falseLabel == null) { + // // implicit falling through the FALSE case + // if (trueLabel != null) { + // codeStream.goto_(trueLabel); + // } + // } + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } + public TypeBinding literalType(BlockScope scope) { + return BooleanBinding; + } + + /** + * + */ + public char[] source() { + return source; + } + + public void traverse(IAbstractSyntaxTreeVisitor visitor, BlockScope scope) { + visitor.visit(this, scope); + visitor.endVisit(this, scope); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/TryStatement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/TryStatement.java index 59a804d..bf4c55a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/TryStatement.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/TryStatement.java @@ -26,50 +26,63 @@ import net.sourceforge.phpdt.internal.compiler.lookup.ReferenceBinding; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class TryStatement extends Statement { - + public Block tryBlock; + public Block[] catchBlocks; + public Argument[] catchArguments; + public Block finallyBlock; + BlockScope scope; public boolean subRoutineCannotReturn = true; + public UnconditionalFlowInfo subRoutineInits; - + // should rename into subRoutineComplete to be set to false by default ReferenceBinding[] caughtExceptionTypes; + boolean tryBlockExit; + boolean[] catchExits; + public int[] preserveExceptionHandler; Label subRoutineStartLabel; - public LocalVariableBinding anyExceptionVariable, - returnAddressVariable, - secretReturnValue; + + public LocalVariableBinding anyExceptionVariable, returnAddressVariable, + secretReturnValue; public final static char[] SecretReturnName = " returnAddress".toCharArray(); //$NON-NLS-1$ + public final static char[] SecretAnyHandlerName = " anyExceptionHandler".toCharArray(); //$NON-NLS-1$ + public static final char[] SecretLocalDeclarationName = " returnValue".toCharArray(); //$NON-NLS-1$ // for local variables table attributes int preTryInitStateIndex = -1; + int mergedInitStateIndex = -1; - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { - // Consider the try block and catch block so as to compute the intersection of initializations and - // the minimum exit relative depth amongst all of them. Then consider the subroutine, and append its - // initialization to the try/catch ones, if the subroutine completes normally. If the subroutine does not + // Consider the try block and catch block so as to compute the + // intersection of initializations and + // the minimum exit relative depth amongst all of them. Then consider + // the subroutine, and append its + // initialization to the try/catch ones, if the subroutine completes + // normally. If the subroutine does not // complete, then only keep this result for the rest of the analysis - // process the finally block (subroutine) - create a context for the subroutine + // process the finally block (subroutine) - create a context for the + // subroutine - preTryInitStateIndex = - currentScope.methodScope().recordInitializationStates(flowInfo); + preTryInitStateIndex = currentScope.methodScope() + .recordInitializationStates(flowInfo); if (anyExceptionVariable != null) { anyExceptionVariable.useFlag = LocalVariableBinding.USED; @@ -87,13 +100,12 @@ public class TryStatement extends Statement { subInfo = null; } else { // analyse finally block first - insideSubContext = new InsideSubRoutineFlowContext(flowContext, this); - subInfo = - finallyBlock - .analyseCode( - currentScope, - finallyContext = new FinallyFlowContext(flowContext, finallyBlock), - flowInfo.copy()) + insideSubContext = new InsideSubRoutineFlowContext(flowContext, + this); + subInfo = finallyBlock.analyseCode( + currentScope, + finallyContext = new FinallyFlowContext(flowContext, + finallyBlock), flowInfo.copy()) .unconditionalInits(); if (subInfo.isReachable()) { subRoutineCannotReturn = false; @@ -101,86 +113,90 @@ public class TryStatement extends Statement { this.subRoutineInits = subInfo; } // process the try block in a context handling the local exceptions. - ExceptionHandlingFlowContext handlingContext = - new ExceptionHandlingFlowContext( + ExceptionHandlingFlowContext handlingContext = new ExceptionHandlingFlowContext( insideSubContext == null ? flowContext : insideSubContext, - tryBlock, - caughtExceptionTypes, - scope, - flowInfo.unconditionalInits()); + tryBlock, caughtExceptionTypes, scope, flowInfo + .unconditionalInits()); FlowInfo tryInfo; if (tryBlock.statements == null) { tryInfo = flowInfo; tryBlockExit = false; } else { - tryInfo = tryBlock.analyseCode(currentScope, handlingContext, flowInfo.copy()); + tryInfo = tryBlock.analyseCode(currentScope, handlingContext, + flowInfo.copy()); tryBlockExit = !tryInfo.isReachable(); } // check unreachable catch blocks -// handlingContext.complainIfUnusedExceptionHandlers(catchBlocks, scope, this); + // handlingContext.complainIfUnusedExceptionHandlers(catchBlocks, scope, + // this); - // process the catch blocks - computing the minimal exit depth amongst try/catch + // process the catch blocks - computing the minimal exit depth amongst + // try/catch if (catchArguments != null) { int catchCount; catchExits = new boolean[catchCount = catchBlocks.length]; for (int i = 0; i < catchCount; i++) { - // keep track of the inits that could potentially have led to this exception handler (for final assignments diagnosis) - FlowInfo catchInfo = - flowInfo - .copy() - .unconditionalInits() + // keep track of the inits that could potentially have led to + // this exception handler (for final assignments diagnosis) + FlowInfo catchInfo = flowInfo.copy().unconditionalInits() + .addPotentialInitializationsFrom( + handlingContext.initsOnException( + caughtExceptionTypes[i]) + .unconditionalInits()) .addPotentialInitializationsFrom( - handlingContext.initsOnException(caughtExceptionTypes[i]).unconditionalInits()) - .addPotentialInitializationsFrom(tryInfo.unconditionalInits()) - .addPotentialInitializationsFrom(handlingContext.initsOnReturn); + tryInfo.unconditionalInits()) + .addPotentialInitializationsFrom( + handlingContext.initsOnReturn); // catch var is always set catchInfo.markAsDefinitelyAssigned(catchArguments[i].binding); /* - "If we are about to consider an unchecked exception handler, potential inits may have occured inside - the try block that need to be detected , e.g. - try { x = 1; throwSomething();} catch(Exception e){ x = 2} " - "(uncheckedExceptionTypes notNil and: [uncheckedExceptionTypes at: index]) - ifTrue: [catchInits addPotentialInitializationsFrom: tryInits]." - */ - // TODO: should only tag as unreachable if the catchblock cannot be reached - //??? if (!handlingContext.initsOnException(caughtExceptionTypes[i]).isReachable()){ + * "If we are about to consider an unchecked exception handler, + * potential inits may have occured inside the try block that + * need to be detected , e.g. try { x = 1; throwSomething();} + * catch(Exception e){ x = 2} " "(uncheckedExceptionTypes notNil + * and: [uncheckedExceptionTypes at: index]) ifTrue: [catchInits + * addPotentialInitializationsFrom: tryInits]." + */ + // TODO: should only tag as unreachable if the catchblock cannot + // be reached + // ??? if + // (!handlingContext.initsOnException(caughtExceptionTypes[i]).isReachable()){ if (tryBlock.statements == null) { catchInfo.setReachMode(FlowInfo.UNREACHABLE); } - catchInfo = - catchBlocks[i].analyseCode( - currentScope, - insideSubContext == null ? flowContext : insideSubContext, - catchInfo); + catchInfo = catchBlocks[i].analyseCode(currentScope, + insideSubContext == null ? flowContext + : insideSubContext, catchInfo); catchExits[i] = !catchInfo.isReachable(); tryInfo = tryInfo.mergedWith(catchInfo.unconditionalInits()); } } if (subRoutineStartLabel == null) { - mergedInitStateIndex = - currentScope.methodScope().recordInitializationStates(tryInfo); + mergedInitStateIndex = currentScope.methodScope() + .recordInitializationStates(tryInfo); return tryInfo; } - - // we also need to check potential multiple assignments of final variables inside the finally block - // need to include potential inits from returns inside the try/catch parts - 1GK2AOF - finallyContext.complainOnRedundantFinalAssignments( - tryInfo.isReachable() - ? (tryInfo.addPotentialInitializationsFrom(insideSubContext.initsOnReturn)) - : insideSubContext.initsOnReturn, - currentScope); + // we also need to check potential multiple assignments of final + // variables inside the finally block + // need to include potential inits from returns inside the try/catch + // parts - 1GK2AOF + finallyContext + .complainOnRedundantFinalAssignments( + tryInfo.isReachable() ? (tryInfo + .addPotentialInitializationsFrom(insideSubContext.initsOnReturn)) + : insideSubContext.initsOnReturn, currentScope); if (subInfo == FlowInfo.DEAD_END) { - mergedInitStateIndex = - currentScope.methodScope().recordInitializationStates(subInfo); + mergedInitStateIndex = currentScope.methodScope() + .recordInitializationStates(subInfo); return subInfo; } else { FlowInfo mergedInfo = tryInfo.addInitializationsFrom(subInfo); - mergedInitStateIndex = - currentScope.methodScope().recordInitializationStates(mergedInfo); + mergedInitStateIndex = currentScope.methodScope() + .recordInitializationStates(mergedInfo); return mergedInfo; } } @@ -192,234 +208,248 @@ public class TryStatement extends Statement { /** * Try statement code generation - * + * */ -// public void generateCode(BlockScope currentScope, CodeStream codeStream) { -// -// if ((bits & IsReachableMASK) == 0) { -// return; -// } -// if (tryBlock.isEmptyBlock()) { -// if (subRoutineStartLabel != null) { -// // since not passing the finallyScope, the block generation will exitUserScope(finallyScope) -// finallyBlock.generateCode(scope, codeStream); -// } -// // May loose some local variable initializations : affecting the local variable attributes -// if (mergedInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// mergedInitStateIndex); -// } -// // no local bytecode produced so no need for position remembering -// return; -// } -// int pc = codeStream.position; -// Label endLabel = new Label(codeStream); -// boolean requiresNaturalJsr = false; -// -// // preparing exception labels -// int maxCatches; -// ExceptionLabel[] exceptionLabels = -// new ExceptionLabel[maxCatches = -// catchArguments == null ? 0 : catchArguments.length]; -// for (int i = 0; i < maxCatches; i++) { -// boolean preserveCurrentHandler = -// (preserveExceptionHandler[i -// / ExceptionHandlingFlowContext.BitCacheSize] -// & (1 << (i % ExceptionHandlingFlowContext.BitCacheSize))) -// != 0; -// if (preserveCurrentHandler) { -// exceptionLabels[i] = -// new ExceptionLabel( -// codeStream, -// (ReferenceBinding) catchArguments[i].binding.type); -// } -// } -// ExceptionLabel anyExceptionLabel = null; -// if (subRoutineStartLabel != null) { -// subRoutineStartLabel.codeStream = codeStream; -// anyExceptionLabel = new ExceptionLabel(codeStream, null); -// } -// // generate the try block -// tryBlock.generateCode(scope, codeStream); -// boolean tryBlockHasSomeCode = codeStream.position != pc; -// // flag telling if some bytecodes were issued inside the try block -// -// // natural exit: only if necessary -// boolean nonReturningSubRoutine = -// (subRoutineStartLabel != null) && subRoutineCannotReturn; -// if ((!tryBlockExit) && tryBlockHasSomeCode) { -// int position = codeStream.position; -// if (nonReturningSubRoutine) { -// codeStream.goto_(subRoutineStartLabel); -// } else { -// requiresNaturalJsr = true; -// codeStream.goto_(endLabel); -// } -// codeStream.updateLastRecordedEndPC(position); -// //goto is tagged as part of the try block -// } -// // place end positions of user-defined exception labels -// if (tryBlockHasSomeCode) { -// for (int i = 0; i < maxCatches; i++) { -// boolean preserveCurrentHandler = -// (preserveExceptionHandler[i / ExceptionHandlingFlowContext.BitCacheSize] -// & (1 << (i % ExceptionHandlingFlowContext.BitCacheSize))) -// != 0; -// if (preserveCurrentHandler) { -// exceptionLabels[i].placeEnd(); -// } -// } -// /* generate sequence of handler, all starting by storing the TOS (exception -// thrown) into their own catch variables, the one specified in the source -// that must denote the handled exception. -// */ -// if (catchArguments == null) { -// if (anyExceptionLabel != null) { -// anyExceptionLabel.placeEnd(); -// } -// } else { -// for (int i = 0; i < maxCatches; i++) { -// boolean preserveCurrentHandler = -// (preserveExceptionHandler[i / ExceptionHandlingFlowContext.BitCacheSize] -// & (1 << (i % ExceptionHandlingFlowContext.BitCacheSize))) -// != 0; -// if (preserveCurrentHandler) { -// // May loose some local variable initializations : affecting the local variable attributes -// if (preTryInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// preTryInitStateIndex); -// } -// exceptionLabels[i].place(); -// codeStream.incrStackSize(1); -// // optimizing the case where the exception variable is not actually used -// LocalVariableBinding catchVar; -// int varPC = codeStream.position; -// if ((catchVar = catchArguments[i].binding).resolvedPosition != -1) { -// codeStream.store(catchVar, false); -// catchVar.recordInitializationStartPC(codeStream.position); -// codeStream.addVisibleLocalVariable(catchVar); -// } else { -// codeStream.pop(); -// } -// codeStream.recordPositionsFrom(varPC, catchArguments[i].sourceStart); -// // Keep track of the pcs at diverging point for computing the local attribute -// // since not passing the catchScope, the block generation will exitUserScope(catchScope) -// catchBlocks[i].generateCode(scope, codeStream); -// } -// if (i == maxCatches - 1) { -// if (anyExceptionLabel != null) { -// anyExceptionLabel.placeEnd(); -// } -// if (subRoutineStartLabel != null) { -// if (!catchExits[i] && preserveCurrentHandler) { -// requiresNaturalJsr = true; -// codeStream.goto_(endLabel); -// } -// } -// } else { -// if (!catchExits[i] && preserveCurrentHandler) { -// if (nonReturningSubRoutine) { -// codeStream.goto_(subRoutineStartLabel); -// } else { -// requiresNaturalJsr = true; -// codeStream.goto_(endLabel); -// } -// } -// } -// } -// } -// // addition of a special handler so as to ensure that any uncaught exception (or exception thrown -// // inside catch blocks) will run the finally block -// int finallySequenceStartPC = codeStream.position; -// if (subRoutineStartLabel != null) { -// // the additional handler is doing: jsr finallyBlock and rethrow TOS-exception -// anyExceptionLabel.place(); -// -// if (preTryInitStateIndex != -1) { -// // reset initialization state, as for a normal catch block -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// preTryInitStateIndex); -// } -// -// codeStream.incrStackSize(1); -// if (nonReturningSubRoutine) { -// codeStream.pop(); -// // "if subroutine cannot return, no need to jsr/jump to subroutine since it will be entered in sequence -// } else { -// codeStream.store(anyExceptionVariable, false); -// codeStream.jsr(subRoutineStartLabel); -// codeStream.load(anyExceptionVariable); -// codeStream.athrow(); -// } -// } -// // end of catch sequence, place label that will correspond to the finally block beginning, or end of statement -// endLabel.place(); -// if (subRoutineStartLabel != null) { -// if (nonReturningSubRoutine) { -// requiresNaturalJsr = false; -// } -// Label veryEndLabel = new Label(codeStream); -// if (requiresNaturalJsr) { -// codeStream.jsr(subRoutineStartLabel); -// codeStream.goto_(veryEndLabel); -// } -// subRoutineStartLabel.place(); -// if (!nonReturningSubRoutine) { -// codeStream.incrStackSize(1); -// codeStream.store(returnAddressVariable, false); -// } -// codeStream.recordPositionsFrom( -// finallySequenceStartPC, -// finallyBlock.sourceStart); -// // entire sequence for finally is associated to finally block -// finallyBlock.generateCode(scope, codeStream); -// if (!nonReturningSubRoutine) { -// int position = codeStream.position; -// codeStream.ret(returnAddressVariable.resolvedPosition); -// codeStream.updateLastRecordedEndPC(position); -// // the ret bytecode is part of the subroutine -// } -// if (requiresNaturalJsr) { -// veryEndLabel.place(); -// } -// } -// } else { -// // try block had no effect, only generate the body of the finally block if any -// if (subRoutineStartLabel != null) { -// finallyBlock.generateCode(scope, codeStream); -// } -// } -// // May loose some local variable initializations : affecting the local variable attributes -// if (mergedInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// mergedInitStateIndex); -// codeStream.addDefinitelyAssignedVariables(currentScope, mergedInitStateIndex); -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } - + // public void generateCode(BlockScope currentScope, CodeStream codeStream) + // { + // + // if ((bits & IsReachableMASK) == 0) { + // return; + // } + // if (tryBlock.isEmptyBlock()) { + // if (subRoutineStartLabel != null) { + // // since not passing the finallyScope, the block generation will + // exitUserScope(finallyScope) + // finallyBlock.generateCode(scope, codeStream); + // } + // // May loose some local variable initializations : affecting the local + // variable attributes + // if (mergedInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // mergedInitStateIndex); + // } + // // no local bytecode produced so no need for position remembering + // return; + // } + // int pc = codeStream.position; + // Label endLabel = new Label(codeStream); + // boolean requiresNaturalJsr = false; + // + // // preparing exception labels + // int maxCatches; + // ExceptionLabel[] exceptionLabels = + // new ExceptionLabel[maxCatches = + // catchArguments == null ? 0 : catchArguments.length]; + // for (int i = 0; i < maxCatches; i++) { + // boolean preserveCurrentHandler = + // (preserveExceptionHandler[i + // / ExceptionHandlingFlowContext.BitCacheSize] + // & (1 << (i % ExceptionHandlingFlowContext.BitCacheSize))) + // != 0; + // if (preserveCurrentHandler) { + // exceptionLabels[i] = + // new ExceptionLabel( + // codeStream, + // (ReferenceBinding) catchArguments[i].binding.type); + // } + // } + // ExceptionLabel anyExceptionLabel = null; + // if (subRoutineStartLabel != null) { + // subRoutineStartLabel.codeStream = codeStream; + // anyExceptionLabel = new ExceptionLabel(codeStream, null); + // } + // // generate the try block + // tryBlock.generateCode(scope, codeStream); + // boolean tryBlockHasSomeCode = codeStream.position != pc; + // // flag telling if some bytecodes were issued inside the try block + // + // // natural exit: only if necessary + // boolean nonReturningSubRoutine = + // (subRoutineStartLabel != null) && subRoutineCannotReturn; + // if ((!tryBlockExit) && tryBlockHasSomeCode) { + // int position = codeStream.position; + // if (nonReturningSubRoutine) { + // codeStream.goto_(subRoutineStartLabel); + // } else { + // requiresNaturalJsr = true; + // codeStream.goto_(endLabel); + // } + // codeStream.updateLastRecordedEndPC(position); + // //goto is tagged as part of the try block + // } + // // place end positions of user-defined exception labels + // if (tryBlockHasSomeCode) { + // for (int i = 0; i < maxCatches; i++) { + // boolean preserveCurrentHandler = + // (preserveExceptionHandler[i / ExceptionHandlingFlowContext.BitCacheSize] + // & (1 << (i % ExceptionHandlingFlowContext.BitCacheSize))) + // != 0; + // if (preserveCurrentHandler) { + // exceptionLabels[i].placeEnd(); + // } + // } + // /* generate sequence of handler, all starting by storing the TOS + // (exception + // thrown) into their own catch variables, the one specified in the source + // that must denote the handled exception. + // */ + // if (catchArguments == null) { + // if (anyExceptionLabel != null) { + // anyExceptionLabel.placeEnd(); + // } + // } else { + // for (int i = 0; i < maxCatches; i++) { + // boolean preserveCurrentHandler = + // (preserveExceptionHandler[i / ExceptionHandlingFlowContext.BitCacheSize] + // & (1 << (i % ExceptionHandlingFlowContext.BitCacheSize))) + // != 0; + // if (preserveCurrentHandler) { + // // May loose some local variable initializations : affecting the local + // variable attributes + // if (preTryInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // preTryInitStateIndex); + // } + // exceptionLabels[i].place(); + // codeStream.incrStackSize(1); + // // optimizing the case where the exception variable is not actually used + // LocalVariableBinding catchVar; + // int varPC = codeStream.position; + // if ((catchVar = catchArguments[i].binding).resolvedPosition != -1) { + // codeStream.store(catchVar, false); + // catchVar.recordInitializationStartPC(codeStream.position); + // codeStream.addVisibleLocalVariable(catchVar); + // } else { + // codeStream.pop(); + // } + // codeStream.recordPositionsFrom(varPC, catchArguments[i].sourceStart); + // // Keep track of the pcs at diverging point for computing the local + // attribute + // // since not passing the catchScope, the block generation will + // exitUserScope(catchScope) + // catchBlocks[i].generateCode(scope, codeStream); + // } + // if (i == maxCatches - 1) { + // if (anyExceptionLabel != null) { + // anyExceptionLabel.placeEnd(); + // } + // if (subRoutineStartLabel != null) { + // if (!catchExits[i] && preserveCurrentHandler) { + // requiresNaturalJsr = true; + // codeStream.goto_(endLabel); + // } + // } + // } else { + // if (!catchExits[i] && preserveCurrentHandler) { + // if (nonReturningSubRoutine) { + // codeStream.goto_(subRoutineStartLabel); + // } else { + // requiresNaturalJsr = true; + // codeStream.goto_(endLabel); + // } + // } + // } + // } + // } + // // addition of a special handler so as to ensure that any uncaught + // exception (or exception thrown + // // inside catch blocks) will run the finally block + // int finallySequenceStartPC = codeStream.position; + // if (subRoutineStartLabel != null) { + // // the additional handler is doing: jsr finallyBlock and rethrow + // TOS-exception + // anyExceptionLabel.place(); + // + // if (preTryInitStateIndex != -1) { + // // reset initialization state, as for a normal catch block + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // preTryInitStateIndex); + // } + // + // codeStream.incrStackSize(1); + // if (nonReturningSubRoutine) { + // codeStream.pop(); + // // "if subroutine cannot return, no need to jsr/jump to subroutine since + // it will be entered in sequence + // } else { + // codeStream.store(anyExceptionVariable, false); + // codeStream.jsr(subRoutineStartLabel); + // codeStream.load(anyExceptionVariable); + // codeStream.athrow(); + // } + // } + // // end of catch sequence, place label that will correspond to the finally + // block beginning, or end of statement + // endLabel.place(); + // if (subRoutineStartLabel != null) { + // if (nonReturningSubRoutine) { + // requiresNaturalJsr = false; + // } + // Label veryEndLabel = new Label(codeStream); + // if (requiresNaturalJsr) { + // codeStream.jsr(subRoutineStartLabel); + // codeStream.goto_(veryEndLabel); + // } + // subRoutineStartLabel.place(); + // if (!nonReturningSubRoutine) { + // codeStream.incrStackSize(1); + // codeStream.store(returnAddressVariable, false); + // } + // codeStream.recordPositionsFrom( + // finallySequenceStartPC, + // finallyBlock.sourceStart); + // // entire sequence for finally is associated to finally block + // finallyBlock.generateCode(scope, codeStream); + // if (!nonReturningSubRoutine) { + // int position = codeStream.position; + // codeStream.ret(returnAddressVariable.resolvedPosition); + // codeStream.updateLastRecordedEndPC(position); + // // the ret bytecode is part of the subroutine + // } + // if (requiresNaturalJsr) { + // veryEndLabel.place(); + // } + // } + // } else { + // // try block had no effect, only generate the body of the finally block + // if any + // if (subRoutineStartLabel != null) { + // finallyBlock.generateCode(scope, codeStream); + // } + // } + // // May loose some local variable initializations : affecting the local + // variable attributes + // if (mergedInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // mergedInitStateIndex); + // codeStream.addDefinitelyAssignedVariables(currentScope, + // mergedInitStateIndex); + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } public void resetStateForCodeGeneration() { if (this.subRoutineStartLabel != null) { this.subRoutineStartLabel.resetStateForCodeGeneration(); } - } + } + public StringBuffer printStatement(int indent, StringBuffer output) { printIndent(indent, output).append("try \n"); //$NON-NLS-1$ tryBlock.printStatement(indent + 1, output); //$NON-NLS-1$ - //catches + // catches if (catchBlocks != null) for (int i = 0; i < catchBlocks.length; i++) { - output.append('\n'); - printIndent(indent, output).append("catch ("); //$NON-NLS-1$ - catchArguments[i].print(0, output).append(") "); //$NON-NLS-1$ - catchBlocks[i].printStatement(indent + 1, output); + output.append('\n'); + printIndent(indent, output).append("catch ("); //$NON-NLS-1$ + catchArguments[i].print(0, output).append(") "); //$NON-NLS-1$ + catchBlocks[i].printStatement(indent + 1, output); } - //finally + // finally if (finallyBlock != null) { output.append('\n'); printIndent(indent, output).append("finally\n"); //$NON-NLS-1$ @@ -428,69 +458,73 @@ public class TryStatement extends Statement { return output; } + public void resolve(BlockScope upperScope) { - // special scope for secret locals optimization. + // special scope for secret locals optimization. this.scope = new BlockScope(upperScope); BlockScope tryScope = new BlockScope(scope); BlockScope finallyScope = null; - - if (finallyBlock != null - && finallyBlock.statements != null) { - finallyScope = new BlockScope(scope, false); // don't add it yet to parent scope + if (finallyBlock != null && finallyBlock.statements != null) { + + finallyScope = new BlockScope(scope, false); // don't add it yet + // to parent scope // provision for returning and forcing the finally block to run MethodScope methodScope = scope.methodScope(); // the type does not matter as long as it is not a base type - this.returnAddressVariable = - new LocalVariableBinding(SecretReturnName, upperScope.getJavaLangObject(), AccDefault, false); + this.returnAddressVariable = new LocalVariableBinding( + SecretReturnName, upperScope.getJavaLangObject(), + AccDefault, false); finallyScope.addLocalVariable(returnAddressVariable); this.returnAddressVariable.constant = NotAConstant; // not inlinable this.subRoutineStartLabel = new Label(); - this.anyExceptionVariable = - new LocalVariableBinding(SecretAnyHandlerName, scope.getJavaLangThrowable(), AccDefault, false); + this.anyExceptionVariable = new LocalVariableBinding( + SecretAnyHandlerName, scope.getJavaLangThrowable(), + AccDefault, false); finallyScope.addLocalVariable(this.anyExceptionVariable); this.anyExceptionVariable.constant = NotAConstant; // not inlinable if (!methodScope.isInsideInitializer()) { - MethodBinding methodBinding = - ((AbstractMethodDeclaration) methodScope.referenceContext).binding; + MethodBinding methodBinding = ((AbstractMethodDeclaration) methodScope.referenceContext).binding; if (methodBinding != null) { TypeBinding methodReturnType = methodBinding.returnType; if (methodReturnType.id != T_void) { - this.secretReturnValue = - new LocalVariableBinding( - SecretLocalDeclarationName, - methodReturnType, - AccDefault, - false); + this.secretReturnValue = new LocalVariableBinding( + SecretLocalDeclarationName, methodReturnType, + AccDefault, false); finallyScope.addLocalVariable(this.secretReturnValue); - this.secretReturnValue.constant = NotAConstant; // not inlinable + this.secretReturnValue.constant = NotAConstant; // not + // inlinable } } } finallyBlock.resolveUsing(finallyScope); - // force the finally scope to have variable positions shifted after its try scope and catch ones - finallyScope.shiftScopes = new BlockScope[catchArguments == null ? 1 : catchArguments.length+1]; + // force the finally scope to have variable positions shifted after + // its try scope and catch ones + finallyScope.shiftScopes = new BlockScope[catchArguments == null ? 1 + : catchArguments.length + 1]; finallyScope.shiftScopes[0] = tryScope; } this.tryBlock.resolveUsing(tryScope); - // arguments type are checked against JavaLangThrowable in resolveForCatch(..) + // arguments type are checked against JavaLangThrowable in + // resolveForCatch(..) if (this.catchBlocks != null) { int length = this.catchArguments.length; TypeBinding[] argumentTypes = new TypeBinding[length]; for (int i = 0; i < length; i++) { BlockScope catchScope = new BlockScope(scope); - if (finallyScope != null){ - finallyScope.shiftScopes[i+1] = catchScope; + if (finallyScope != null) { + finallyScope.shiftScopes[i + 1] = catchScope; } // side effect on catchScope in resolveForCatch(..) - if ((argumentTypes[i] = catchArguments[i].resolveForCatch(catchScope)) == null) + if ((argumentTypes[i] = catchArguments[i] + .resolveForCatch(catchScope)) == null) return; catchBlocks[i].resolveUsing(catchScope); } @@ -501,19 +535,24 @@ public class TryStatement extends Statement { for (int i = 0; i < length; i++) { caughtExceptionTypes[i] = (ReferenceBinding) argumentTypes[i]; for (int j = 0; j < i; j++) { - if (caughtExceptionTypes[i].isCompatibleWith(argumentTypes[j])) { - scope.problemReporter().wrongSequenceOfExceptionTypesError(this, i, j); - // cannot return - since may still proceed if unreachable code is ignored (21203) + if (caughtExceptionTypes[i] + .isCompatibleWith(argumentTypes[j])) { + scope.problemReporter() + .wrongSequenceOfExceptionTypesError(this, i, j); + // cannot return - since may still proceed if + // unreachable code is ignored (21203) } } } } else { caughtExceptionTypes = new ReferenceBinding[0]; } - - if (finallyScope != null){ - // add finallyScope as last subscope, so it can be shifted behind try/catch subscopes. - // the shifting is necessary to achieve no overlay in between the finally scope and its + + if (finallyScope != null) { + // add finallyScope as last subscope, so it can be shifted behind + // try/catch subscopes. + // the shifting is necessary to achieve no overlay in between the + // finally scope and its // sibling in term of local variable positions. this.scope.addSubscope(finallyScope); } @@ -521,34 +560,32 @@ public class TryStatement extends Statement { public String toString(int tab) { String s = tabString(tab); - //try + // try s = s + "try "; //$NON-NLS-1$ if (tryBlock == Block.None) s = s + "{}"; //$NON-NLS-1$ else s = s + "\n" + tryBlock.toString(tab + 1); //$NON-NLS-1$ - //catches + // catches if (catchBlocks != null) for (int i = 0; i < catchBlocks.length; i++) - s = s + "\n" + tabString(tab) + "catch (" //$NON-NLS-2$ //$NON-NLS-1$ - +catchArguments[i].toString(0) + ") " //$NON-NLS-1$ - +catchBlocks[i].toString(tab + 1); - //finally + s = s + "\n" + tabString(tab) + "catch (" //$NON-NLS-2$ //$NON-NLS-1$ + + catchArguments[i].toString(0) + ") " //$NON-NLS-1$ + + catchBlocks[i].toString(tab + 1); + // finally if (finallyBlock != null) { if (finallyBlock == Block.None) s = s + "\n" + tabString(tab) + "finally {}"; //$NON-NLS-2$ //$NON-NLS-1$ else - s = s + "\n" + tabString(tab) + "finally\n" + //$NON-NLS-2$ //$NON-NLS-1$ - finallyBlock.toString(tab + 1); + s = s + "\n" + tabString(tab) + "finally\n" + //$NON-NLS-2$ //$NON-NLS-1$ + finallyBlock.toString(tab + 1); } return s; } - public void traverse( - ASTVisitor visitor, - BlockScope blockScope) { + public void traverse(ASTVisitor visitor, BlockScope blockScope) { if (visitor.visit(this, blockScope)) { tryBlock.traverse(visitor, scope); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/TypeDeclaration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/TypeDeclaration.java index ca49457..5312f66 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/TypeDeclaration.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/TypeDeclaration.java @@ -35,1055 +35,1166 @@ import net.sourceforge.phpdt.internal.compiler.problem.AbortMethod; import net.sourceforge.phpdt.internal.compiler.problem.AbortType; import net.sourceforge.phpdt.internal.compiler.problem.ProblemSeverities; -public class TypeDeclaration extends Statement implements ProblemSeverities, ReferenceContext { +public class TypeDeclaration extends Statement implements ProblemSeverities, + ReferenceContext { - public int modifiers; + public int modifiers; - public int modifiersSourceStart; + public int modifiersSourceStart; - public char[] name; + public char[] name; - public TypeReference superclass; + public TypeReference superclass; - public TypeReference[] superInterfaces; + public TypeReference[] superInterfaces; - public FieldDeclaration[] fields; + public FieldDeclaration[] fields; - public AbstractMethodDeclaration[] methods; + public AbstractMethodDeclaration[] methods; - public TypeDeclaration[] memberTypes; + public TypeDeclaration[] memberTypes; - public SourceTypeBinding binding; + public SourceTypeBinding binding; - public ClassScope scope; + public ClassScope scope; - public MethodScope initializerScope; + public MethodScope initializerScope; - public MethodScope staticInitializerScope; + public MethodScope staticInitializerScope; - public boolean ignoreFurtherInvestigation = false; + public boolean ignoreFurtherInvestigation = false; - public int maxFieldCount; + public int maxFieldCount; - public int declarationSourceStart; - - public int declarationSourceEnd; - - public int bodyStart; - - public int bodyEnd; // doesn't include the trailing comment if any. - - protected boolean hasBeenGenerated = false; - - public CompilationResult compilationResult; - - private MethodDeclaration[] missingAbstractMethods; - - public TypeDeclaration(CompilationResult compilationResult) { - this.compilationResult = compilationResult; - } - - /* - * We cause the compilation task to abort to a given extent. - */ - public void abort(int abortLevel) { - - if (scope == null) { - throw new AbortCompilation(); // cannot do better - } - - CompilationResult compilationResult = scope.referenceCompilationUnit().compilationResult; - - switch (abortLevel) { - case AbortCompilation: - throw new AbortCompilation(compilationResult); - case AbortCompilationUnit: - throw new AbortCompilationUnit(compilationResult); - case AbortMethod: - throw new AbortMethod(compilationResult); - default: - throw new AbortType(compilationResult); - } - } - - /** - * This method is responsible for adding a method declaration to the type method collections. Note that this - * implementation is inserting it in first place (as VAJ or javac), and that this impacts the behavior of the method - * ConstantPool.resetForClinit(int. int), in so far as the latter will have to reset the constant pool state accordingly (if it - * was added first, it does not need to preserve some of the method specific cached entries since this will be the first method). - * inserts the clinit method declaration in the first position. - * - * @see net.sourceforge.phpdt.internal.compiler.codegen.ConstantPool#resetForClinit(int, int) - */ - public final void addClinit() { - - //see comment on needClassInitMethod - if (needClassInitMethod()) { - int length; - AbstractMethodDeclaration[] methods; - if ((methods = this.methods) == null) { - length = 0; - methods = new AbstractMethodDeclaration[1]; - } else { - length = methods.length; - System.arraycopy(methods, 0, (methods = new AbstractMethodDeclaration[length + 1]), 1, length); - } - Clinit clinit = new Clinit(this.compilationResult); - methods[0] = clinit; - // clinit is added in first location, so as to minimize the use of ldcw (big consumer of constant inits) - clinit.declarationSourceStart = clinit.sourceStart = sourceStart; - clinit.declarationSourceEnd = clinit.sourceEnd = sourceEnd; - clinit.bodyEnd = sourceEnd; - this.methods = methods; - } - } - - /** - * Flow analysis for a local innertype - * - */ - public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { - - if (ignoreFurtherInvestigation) - return flowInfo; - try { - bits |= IsReachableMASK; - LocalTypeBinding localType = (LocalTypeBinding) binding; - - localType.setConstantPoolName(currentScope.compilationUnitScope().computeConstantPoolName(localType)); - manageEnclosingInstanceAccessIfNecessary(currentScope); - - updateMaxFieldCount(); // propagate down the max field count - internalAnalyseCode(flowContext, flowInfo); - } catch (AbortType e) { - this.ignoreFurtherInvestigation = true; - } - return flowInfo; - } - - /** - * Flow analysis for a member innertype - * - */ - public void analyseCode(ClassScope enclosingClassScope) { - - if (ignoreFurtherInvestigation) - return; - try { - // propagate down the max field count - updateMaxFieldCount(); - internalAnalyseCode(null, FlowInfo.initial(maxFieldCount)); - } catch (AbortType e) { - this.ignoreFurtherInvestigation = true; - } - } - - /** - * Flow analysis for a local member innertype - * - */ - public void analyseCode(ClassScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { - - if (ignoreFurtherInvestigation) - return; - try { - bits |= IsReachableMASK; - LocalTypeBinding localType = (LocalTypeBinding) binding; - - localType.setConstantPoolName(currentScope.compilationUnitScope().computeConstantPoolName(localType)); - manageEnclosingInstanceAccessIfNecessary(currentScope); - - updateMaxFieldCount(); // propagate down the max field count - internalAnalyseCode(flowContext, flowInfo); - } catch (AbortType e) { - this.ignoreFurtherInvestigation = true; - } - } - - /** - * Flow analysis for a package member type - * - */ - public void analyseCode(CompilationUnitScope unitScope) { - - if (ignoreFurtherInvestigation) - return; - try { - internalAnalyseCode(null, FlowInfo.initial(maxFieldCount)); - } catch (AbortType e) { - this.ignoreFurtherInvestigation = true; - } - } - - /* - * Check for constructor vs. method with no return type. Answers true if at least one constructor is defined - */ - public boolean checkConstructors(Parser parser) { - - //if a constructor has not the name of the type, - //convert it into a method with 'null' as its return type - boolean hasConstructor = false; - if (methods != null) { - for (int i = methods.length; --i >= 0;) { - AbstractMethodDeclaration am; - if ((am = methods[i]).isConstructor()) { - if (!CharOperation.equals(am.selector, name)) { - // the constructor was in fact a method with no return type - // unless an explicit constructor call was supplied - ConstructorDeclaration c = (ConstructorDeclaration) am; - if ((c.constructorCall == null) || (c.constructorCall.isImplicitSuper())) { //changed to a method - MethodDeclaration m = new MethodDeclaration(this.compilationResult); - m.sourceStart = c.sourceStart; - m.sourceEnd = c.sourceEnd; - m.bodyStart = c.bodyStart; - m.bodyEnd = c.bodyEnd; - m.declarationSourceEnd = c.declarationSourceEnd; - m.declarationSourceStart = c.declarationSourceStart; - m.selector = c.selector; - m.statements = c.statements; - m.modifiers = c.modifiers; - m.arguments = c.arguments; - m.thrownExceptions = c.thrownExceptions; - m.explicitDeclarations = c.explicitDeclarations; - m.returnType = null; - methods[i] = m; - } - } else { - if (this.isInterface()) { - // report the problem and continue the parsing - parser.problemReporter().interfaceCannotHaveConstructors((ConstructorDeclaration) am); - } - hasConstructor = true; - } - } - } - } - return hasConstructor; - } - - public CompilationResult compilationResult() { - - return this.compilationResult; - } - - public ConstructorDeclaration createsInternalConstructor(boolean needExplicitConstructorCall, boolean needToInsert) { - - //Add to method'set, the default constuctor that just recall the - //super constructor with no arguments - //The arguments' type will be positionned by the TC so just use - //the default int instead of just null (consistency purpose) - - //the constructor - ConstructorDeclaration constructor = new ConstructorDeclaration(this.compilationResult); - constructor.isDefaultConstructor = true; - constructor.selector = name; - if (modifiers != AccDefault) { - constructor.modifiers = ((this instanceof MemberTypeDeclaration) && (modifiers & AccPrivate) != 0) ? AccDefault : modifiers - & AccVisibilityMASK; - } - - //if you change this setting, please update the - //SourceIndexer2.buildTypeDeclaration(TypeDeclaration,char[]) method - constructor.declarationSourceStart = constructor.sourceStart = sourceStart; - constructor.declarationSourceEnd = constructor.sourceEnd = constructor.bodyEnd = sourceEnd; - - //the super call inside the constructor - if (needExplicitConstructorCall) { - constructor.constructorCall = SuperReference.implicitSuperConstructorCall(); - constructor.constructorCall.sourceStart = sourceStart; - constructor.constructorCall.sourceEnd = sourceEnd; - } - - //adding the constructor in the methods list - if (needToInsert) { - if (methods == null) { - methods = new AbstractMethodDeclaration[] { constructor }; - } else { - AbstractMethodDeclaration[] newMethods; - System.arraycopy(methods, 0, newMethods = new AbstractMethodDeclaration[methods.length + 1], 1, methods.length); - newMethods[0] = constructor; - methods = newMethods; - } - } - return constructor; - } - - /** - * INTERNAL USE ONLY - Creates a fake method declaration for the corresponding binding. It is used to report errors for missing - * abstract methods. - */ - public MethodDeclaration addMissingAbstractMethodFor(MethodBinding methodBinding) { - TypeBinding[] argumentTypes = methodBinding.parameters; - int argumentsLength = argumentTypes.length; - //the constructor - MethodDeclaration methodDeclaration = new MethodDeclaration(this.compilationResult); - methodDeclaration.selector = methodBinding.selector; - methodDeclaration.sourceStart = sourceStart; - methodDeclaration.sourceEnd = sourceEnd; - methodDeclaration.modifiers = methodBinding.getAccessFlags() & ~AccAbstract; - - if (argumentsLength > 0) { - String baseName = "arg";//$NON-NLS-1$ - Argument[] arguments = (methodDeclaration.arguments = new Argument[argumentsLength]); - for (int i = argumentsLength; --i >= 0;) { - arguments[i] = new Argument((baseName + i).toCharArray(), 0L, null /* type ref */, AccDefault); - } - } - - //adding the constructor in the methods list - if (this.missingAbstractMethods == null) { - this.missingAbstractMethods = new MethodDeclaration[] { methodDeclaration }; - } else { - MethodDeclaration[] newMethods; - System.arraycopy(this.missingAbstractMethods, 0, newMethods = new MethodDeclaration[this.missingAbstractMethods.length + 1], - 1, this.missingAbstractMethods.length); - newMethods[0] = methodDeclaration; - this.missingAbstractMethods = newMethods; - } - - //============BINDING UPDATE========================== - methodDeclaration.binding = new MethodBinding(methodDeclaration.modifiers, //methodDeclaration - methodBinding.selector, methodBinding.returnType, argumentsLength == 0 ? NoParameters : argumentTypes, //arguments bindings - methodBinding.thrownExceptions, //exceptions - binding); //declaringClass - - methodDeclaration.scope = new MethodScope(scope, methodDeclaration, true); - methodDeclaration.bindArguments(); - - /* - * if (binding.methods == null) { binding.methods = new MethodBinding[] { methodDeclaration.binding }; } else { MethodBinding[] - * newMethods; System.arraycopy( binding.methods, 0, newMethods = new MethodBinding[binding.methods.length + 1], 1, - * binding.methods.length); newMethods[0] = methodDeclaration.binding; binding.methods = newMethods; } - */ - //=================================================== - return methodDeclaration; - } - - /* - * Find the matching parse node, answers null if nothing found - */ - public FieldDeclaration declarationOf(FieldBinding fieldBinding) { - - if (fieldBinding != null) { - for (int i = 0, max = this.fields.length; i < max; i++) { - FieldDeclaration fieldDecl; - if ((fieldDecl = this.fields[i]).binding == fieldBinding) - return fieldDecl; - } - } - return null; - } - - /* - * Find the matching parse node, answers null if nothing found - */ - public TypeDeclaration declarationOf(MemberTypeBinding memberTypeBinding) { - - if (memberTypeBinding != null) { - for (int i = 0, max = this.memberTypes.length; i < max; i++) { - TypeDeclaration memberTypeDecl; - if ((memberTypeDecl = this.memberTypes[i]).binding == memberTypeBinding) - return memberTypeDecl; - } - } - return null; - } - - /* - * Find the matching parse node, answers null if nothing found - */ - public AbstractMethodDeclaration declarationOf(MethodBinding methodBinding) { - - if (methodBinding != null) { - for (int i = 0, max = this.methods.length; i < max; i++) { - AbstractMethodDeclaration methodDecl; - - if ((methodDecl = this.methods[i]).binding == methodBinding) - return methodDecl; - } - } - return null; - } - - /* - * Finds the matching type amoung this type's member types. Returns null if no type with this name is found. The type name is a - * compound name relative to this type eg. if this type is X and we're looking for Y.X.A.B then a type name would be {X, A, B} - */ - public TypeDeclaration declarationOfType(char[][] typeName) { - - int typeNameLength = typeName.length; - if (typeNameLength < 1 || !CharOperation.equals(typeName[0], this.name)) { - return null; - } - if (typeNameLength == 1) { - return this; - } - char[][] subTypeName = new char[typeNameLength - 1][]; - System.arraycopy(typeName, 1, subTypeName, 0, typeNameLength - 1); - for (int i = 0; i < this.memberTypes.length; i++) { - TypeDeclaration typeDecl = this.memberTypes[i].declarationOfType(subTypeName); - if (typeDecl != null) { - return typeDecl; - } - } - return null; - } - - /** - * Generic bytecode generation for type - */ - // public void generateCode(ClassFile enclosingClassFile) { - // - // if (hasBeenGenerated) - // return; - // hasBeenGenerated = true; - // if (ignoreFurtherInvestigation) { - // if (binding == null) - // return; - // ClassFile.createProblemType( - // this, - // scope.referenceCompilationUnit().compilationResult); - // return; - // } - // try { - // // create the result for a compiled type - // ClassFile classFile = new ClassFile(binding, enclosingClassFile, false); - // // generate all fiels - // classFile.addFieldInfos(); - // - // // record the inner type inside its own .class file to be able - // // to generate inner classes attributes - // if (binding.isMemberType()) - // classFile.recordEnclosingTypeAttributes(binding); - // if (binding.isLocalType()) { - // enclosingClassFile.recordNestedLocalAttribute(binding); - // classFile.recordNestedLocalAttribute(binding); - // } - // if (memberTypes != null) { - // for (int i = 0, max = memberTypes.length; i < max; i++) { - // // record the inner type inside its own .class file to be able - // // to generate inner classes attributes - // classFile.recordNestedMemberAttribute(memberTypes[i].binding); - // memberTypes[i].generateCode(scope, classFile); - // } - // } - // // generate all methods - // classFile.setForMethodInfos(); - // if (methods != null) { - // for (int i = 0, max = methods.length; i < max; i++) { - // methods[i].generateCode(scope, classFile); - // } - // } - // - // classFile.generateMissingAbstractMethods(this.missingAbstractMethods, scope.referenceCompilationUnit().compilationResult); - // - // // generate all methods - // classFile.addSpecialMethods(); - // - // if (ignoreFurtherInvestigation) { // trigger problem type generation for code gen errors - // throw new AbortType(scope.referenceCompilationUnit().compilationResult); - // } - // - // // finalize the compiled type result - // classFile.addAttributes(); - // scope.referenceCompilationUnit().compilationResult.record( - // binding.constantPoolName(), - // classFile); - // } catch (AbortType e) { - // if (binding == null) - // return; - // ClassFile.createProblemType( - // this, - // scope.referenceCompilationUnit().compilationResult); - // } - // } - /** - * Bytecode generation for a local inner type (API as a normal statement code gen) - */ - // public void generateCode(BlockScope blockScope, CodeStream codeStream) { - // - // if (hasBeenGenerated) return; - // int pc = codeStream.position; - // if (binding != null) ((NestedTypeBinding) binding).computeSyntheticArgumentSlotSizes(); - // generateCode(codeStream.classFile); - // codeStream.recordPositionsFrom(pc, this.sourceStart); - // } - /** - * Bytecode generation for a member inner type - */ - // public void generateCode(ClassScope classScope, ClassFile enclosingClassFile) { - // - // if (hasBeenGenerated) return; - // if (binding != null) ((NestedTypeBinding) binding).computeSyntheticArgumentSlotSizes(); - // generateCode(enclosingClassFile); - // } - /** - * Bytecode generation for a package member - */ - // public void generateCode(CompilationUnitScope unitScope) { - // - // generateCode((ClassFile) null); - // } - public boolean hasErrors() { - return this.ignoreFurtherInvestigation; - } - - /** - * Common flow analysis for all types - * - */ - public void internalAnalyseCode(FlowContext flowContext, FlowInfo flowInfo) { - - if (this.binding.isPrivate() && !this.binding.isPrivateUsed()) { - if (!scope.referenceCompilationUnit().compilationResult.hasSyntaxError()) { - scope.problemReporter().unusedPrivateType(this); - } - } - - ReferenceBinding[] defaultHandledExceptions = new ReferenceBinding[] { scope.getJavaLangThrowable() }; // tolerate any kind of - // exception - InitializationFlowContext initializerContext = new InitializationFlowContext(null, this, initializerScope); - InitializationFlowContext staticInitializerContext = new InitializationFlowContext(null, this, staticInitializerScope); - FlowInfo nonStaticFieldInfo = flowInfo.copy().unconditionalInits().discardFieldInitializations(); - FlowInfo staticFieldInfo = flowInfo.copy().unconditionalInits().discardFieldInitializations(); - if (fields != null) { - for (int i = 0, count = fields.length; i < count; i++) { - FieldDeclaration field = fields[i]; - if (field.isStatic()) { - /* - * if (field.isField()){ staticInitializerContext.handledExceptions = NoExceptions; // no exception is allowed jls8.3.2 } - * else { - */ - staticInitializerContext.handledExceptions = defaultHandledExceptions; // tolerate them all, and record them - /* } */ - staticFieldInfo = field.analyseCode(staticInitializerScope, staticInitializerContext, staticFieldInfo); - // in case the initializer is not reachable, use a reinitialized flowInfo and enter a fake reachable - // branch, since the previous initializer already got the blame. - if (staticFieldInfo == FlowInfo.DEAD_END) { - staticInitializerScope.problemReporter().initializerMustCompleteNormally(field); - staticFieldInfo = FlowInfo.initial(maxFieldCount).setReachMode(FlowInfo.UNREACHABLE); - } - } else { - /* - * if (field.isField()){ initializerContext.handledExceptions = NoExceptions; // no exception is allowed jls8.3.2 } else { - */ - initializerContext.handledExceptions = defaultHandledExceptions; // tolerate them all, and record them - /* } */ - nonStaticFieldInfo = field.analyseCode(initializerScope, initializerContext, nonStaticFieldInfo); - // in case the initializer is not reachable, use a reinitialized flowInfo and enter a fake reachable - // branch, since the previous initializer already got the blame. - if (nonStaticFieldInfo == FlowInfo.DEAD_END) { - initializerScope.problemReporter().initializerMustCompleteNormally(field); - nonStaticFieldInfo = FlowInfo.initial(maxFieldCount).setReachMode(FlowInfo.UNREACHABLE); - } - } - } - } - if (memberTypes != null) { - for (int i = 0, count = memberTypes.length; i < count; i++) { - if (flowContext != null) { // local type - memberTypes[i].analyseCode(scope, flowContext, nonStaticFieldInfo.copy()); - } else { - memberTypes[i].analyseCode(scope); - } - } - } - if (methods != null) { - UnconditionalFlowInfo outerInfo = flowInfo.copy().unconditionalInits().discardFieldInitializations(); - FlowInfo constructorInfo = nonStaticFieldInfo.unconditionalInits().discardNonFieldInitializations().addInitializationsFrom( - outerInfo); - for (int i = 0, count = methods.length; i < count; i++) { - AbstractMethodDeclaration method = methods[i]; - if (method.ignoreFurtherInvestigation) - continue; - if (method.isInitializationMethod()) { - if (method.isStatic()) { // - method.analyseCode(scope, staticInitializerContext, staticFieldInfo.unconditionalInits() - .discardNonFieldInitializations().addInitializationsFrom(outerInfo)); - } else { // constructor - method.analyseCode(scope, initializerContext, constructorInfo.copy()); - } - } else { // regular method - method.analyseCode(scope, null, flowInfo.copy()); - } - } - } - } - - public boolean isInterface() { - - return (modifiers & AccInterface) != 0; - } - - /* - * Access emulation for a local type force to emulation of access to direct enclosing instance. By using the initializer scope, we - * actually only request an argument emulation, the field is not added until actually used. However we will force allocations to - * be qualified with an enclosing instance. 15.9.2 - */ - public void manageEnclosingInstanceAccessIfNecessary(BlockScope currentScope) { - - NestedTypeBinding nestedType = (NestedTypeBinding) binding; - - MethodScope methodScope = currentScope.methodScope(); - if (!methodScope.isStatic && !methodScope.isConstructorCall) { - - nestedType.addSyntheticArgumentAndField(binding.enclosingType()); - } - // add superclass enclosing instance arg for anonymous types (if necessary) - if (binding.isAnonymousType()) { - ReferenceBinding superclass = binding.superclass; - if (superclass.enclosingType() != null && !superclass.isStatic()) { - if (!binding.superclass.isLocalType() - || ((NestedTypeBinding) binding.superclass).getSyntheticField(superclass.enclosingType(), true) != null) { - - nestedType.addSyntheticArgument(superclass.enclosingType()); - } - } - } - } - - /* - * Access emulation for a local member type force to emulation of access to direct enclosing instance. By using the initializer - * scope, we actually only request an argument emulation, the field is not added until actually used. However we will force - * allocations to be qualified with an enclosing instance. - * - * Local member cannot be static. - */ - public void manageEnclosingInstanceAccessIfNecessary(ClassScope currentScope) { - - NestedTypeBinding nestedType = (NestedTypeBinding) binding; - nestedType.addSyntheticArgumentAndField(binding.enclosingType()); - } - - /** - * A will be requested as soon as static fields or assertions are present. It will be eliminated during classfile creation - * if no bytecode was actually produced based on some optimizations/compiler settings. - */ - public final boolean needClassInitMethod() { - - // always need a when assertions are present - if ((this.bits & AddAssertionMASK) != 0) - return true; - if (fields == null) - return false; - if (isInterface()) - return true; // fields are implicitly statics - for (int i = fields.length; --i >= 0;) { - FieldDeclaration field = fields[i]; - //need to test the modifier directly while there is no binding yet - if ((field.modifiers & AccStatic) != 0) - return true; - } - return false; - } - - public void parseMethod(UnitParser parser, CompilationUnitDeclaration unit) { - - //connect method bodies - if (unit.ignoreMethodBodies) - return; - - // no scope were created, so cannot report further errors - // if (binding == null) - // return; - - //members - if (memberTypes != null) { - int length = memberTypes.length; - for (int i = 0; i < length; i++) - memberTypes[i].parseMethod(parser, unit); - } - - //methods - if (methods != null) { - int length = methods.length; - for (int i = 0; i < length; i++) - methods[i].parseStatements(parser, unit); - } - - //initializers - if (fields != null) { - int length = fields.length; - for (int i = 0; i < length; i++) { - if (fields[i] instanceof Initializer) { - ((Initializer) fields[i]).parseStatements(parser, this, unit); - } - } - } - } - - public void resolve() { - - if (binding == null) { - ignoreFurtherInvestigation = true; - return; - } - - try { - // check superclass & interfaces - if (binding.superclass != null) // watch out for Object ! (and other roots) - if (isTypeUseDeprecated(binding.superclass, scope)) - scope.problemReporter().deprecatedType(binding.superclass, superclass); - if (superInterfaces != null) - for (int i = superInterfaces.length; --i >= 0;) - if (superInterfaces[i].resolvedType != null) - if (isTypeUseDeprecated(superInterfaces[i].resolvedType, scope)) - scope.problemReporter().deprecatedType(superInterfaces[i].resolvedType, superInterfaces[i]); - maxFieldCount = 0; - int lastFieldID = -1; - if (fields != null) { - for (int i = 0, count = fields.length; i < count; i++) { - FieldDeclaration field = fields[i]; - if (field.isField()) { - if (field.binding == null) { - // still discover secondary errors - if (field.initialization != null) - field.initialization.resolve(field.isStatic() ? staticInitializerScope : initializerScope); - ignoreFurtherInvestigation = true; - continue; - } - maxFieldCount++; - lastFieldID = field.binding.id; - } else { // initializer - ((Initializer) field).lastFieldID = lastFieldID + 1; - } - field.resolve(field.isStatic() ? staticInitializerScope : initializerScope); - } - } - if (memberTypes != null) { - for (int i = 0, count = memberTypes.length; i < count; i++) { - memberTypes[i].resolve(scope); - } - } - int missingAbstractMethodslength = this.missingAbstractMethods == null ? 0 : this.missingAbstractMethods.length; - int methodsLength = this.methods == null ? 0 : methods.length; - if ((methodsLength + missingAbstractMethodslength) > 0xFFFF) { - scope.problemReporter().tooManyMethods(this); - } - - if (methods != null) { - for (int i = 0, count = methods.length; i < count; i++) { - methods[i].resolve(scope); - } - } - } catch (AbortType e) { - this.ignoreFurtherInvestigation = true; - return; - } - ; - } - - public void resolve(BlockScope blockScope) { - // local type declaration - - // need to build its scope first and proceed with binding's creation - blockScope.addLocalType(this); - - // and TC.... - if (binding != null) { - // remember local types binding for innerclass emulation propagation - blockScope.referenceCompilationUnit().record((LocalTypeBinding) binding); - - // binding is not set if the receiver could not be created - resolve(); - updateMaxFieldCount(); - } - } - - public void resolve(ClassScope upperScope) { - // member scopes are already created - // request the construction of a binding if local member type - - if (binding != null && binding instanceof LocalTypeBinding) { - // remember local types binding for innerclass emulation propagation - upperScope.referenceCompilationUnit().record((LocalTypeBinding) binding); - } - resolve(); - updateMaxFieldCount(); - } - - public void resolve(CompilationUnitScope upperScope) { - // top level : scope are already created - - resolve(); - updateMaxFieldCount(); - } - - public void tagAsHavingErrors() { - ignoreFurtherInvestigation = true; - } - - public StringBuffer print(int indent, StringBuffer output) { - - // if ((this.bits & IsAnonymousTypeMASK) == 0) { - printIndent(indent, output); - printHeader(0, output); - // } - return printBody(indent, output); - } - - public StringBuffer printBody(int indent, StringBuffer output) { - - output.append(" {"); //$NON-NLS-1$ - if (memberTypes != null) { - for (int i = 0; i < memberTypes.length; i++) { - if (memberTypes[i] != null) { - output.append('\n'); - memberTypes[i].print(indent + 1, output); - } - } - } - if (fields != null) { - for (int fieldI = 0; fieldI < fields.length; fieldI++) { - if (fields[fieldI] != null) { - output.append('\n'); - fields[fieldI].print(indent + 1, output); - } - } - } - if (methods != null) { - for (int i = 0; i < methods.length; i++) { - if (methods[i] != null) { - output.append('\n'); - methods[i].print(indent + 1, output); - } - } - } - output.append('\n'); - return printIndent(indent, output).append('}'); - } - - public StringBuffer printHeader(int indent, StringBuffer output) { - - printModifiers(this.modifiers, output); - output.append(isInterface() ? "interface " : "class "); //$NON-NLS-1$ //$NON-NLS-2$ - output.append(name); - if (superclass != null) { - output.append(" extends "); //$NON-NLS-1$ - superclass.print(0, output); - } - if (superInterfaces != null && superInterfaces.length > 0) { - output.append(isInterface() ? " extends " : " implements ");//$NON-NLS-2$ //$NON-NLS-1$ - for (int i = 0; i < superInterfaces.length; i++) { - if (i > 0) - output.append(", "); //$NON-NLS-1$ - superInterfaces[i].print(0, output); - } - } - return output; - } - - public StringBuffer printStatement(int tab, StringBuffer output) { - return print(tab, output); - } - - public String toString(int tab) { - - return tabString(tab) + toStringHeader() + toStringBody(tab); - } - - public String toStringBody(int tab) { - - String s = " {"; //$NON-NLS-1$ - if (memberTypes != null) { - for (int i = 0; i < memberTypes.length; i++) { - if (memberTypes[i] != null) { - s += "\n" + memberTypes[i].toString(tab + 1); //$NON-NLS-1$ - } - } - } - if (fields != null) { - for (int fieldI = 0; fieldI < fields.length; fieldI++) { - if (fields[fieldI] != null) { - s += "\n" + fields[fieldI].toString(tab + 1); //$NON-NLS-1$ - if (fields[fieldI].isField()) - s += ";"; //$NON-NLS-1$ - } - } - } - if (methods != null) { - for (int i = 0; i < methods.length; i++) { - if (methods[i] != null) { - s += "\n" + methods[i].toString(tab + 1); //$NON-NLS-1$ - } - } - } - s += "\n" + tabString(tab) + "}"; //$NON-NLS-2$ //$NON-NLS-1$ - return s; - } - - public String toStringHeader() { - - String s = ""; //$NON-NLS-1$ - if (modifiers != AccDefault) { - s += modifiersString(modifiers); - } - s += (isInterface() ? "interface " : "class ") + new String(name);//$NON-NLS-1$ //$NON-NLS-2$ - if (superclass != null) - s += " extends " + superclass.toString(0); //$NON-NLS-1$ - if (superInterfaces != null && superInterfaces.length > 0) { - s += (isInterface() ? " extends " : " implements ");//$NON-NLS-2$ //$NON-NLS-1$ - for (int i = 0; i < superInterfaces.length; i++) { - s += superInterfaces[i].toString(0); - if (i != superInterfaces.length - 1) - s += ", "; //$NON-NLS-1$ - } - ; - } - ; - return s; - } - - /** - * Iteration for a local innertype - * - */ - public void traverse(ASTVisitor visitor, BlockScope blockScope) { - if (ignoreFurtherInvestigation) - return; - try { - if (visitor.visit(this, blockScope)) { - if (superclass != null) - superclass.traverse(visitor, scope); - if (superInterfaces != null) { - int superInterfaceLength = superInterfaces.length; - for (int i = 0; i < superInterfaceLength; i++) - superInterfaces[i].traverse(visitor, scope); - } - if (memberTypes != null) { - int memberTypesLength = memberTypes.length; - for (int i = 0; i < memberTypesLength; i++) - memberTypes[i].traverse(visitor, scope); - } - if (fields != null) { - int fieldsLength = fields.length; - for (int i = 0; i < fieldsLength; i++) { - FieldDeclaration field; - if ((field = fields[i]).isStatic()) { - // local type cannot have static fields - } else { - field.traverse(visitor, initializerScope); - } - } - } - if (methods != null) { - int methodsLength = methods.length; - for (int i = 0; i < methodsLength; i++) - methods[i].traverse(visitor, scope); - } - } - visitor.endVisit(this, blockScope); - } catch (AbortType e) { - // silent abort - } - } - - /** - * Iteration for a member innertype - * - */ - public void traverse(ASTVisitor visitor, ClassScope classScope) { - if (ignoreFurtherInvestigation) - return; - try { - if (visitor.visit(this, classScope)) { - if (superclass != null) - superclass.traverse(visitor, scope); - if (superInterfaces != null) { - int superInterfaceLength = superInterfaces.length; - for (int i = 0; i < superInterfaceLength; i++) - superInterfaces[i].traverse(visitor, scope); - } - if (memberTypes != null) { - int memberTypesLength = memberTypes.length; - for (int i = 0; i < memberTypesLength; i++) - memberTypes[i].traverse(visitor, scope); - } - if (fields != null) { - int fieldsLength = fields.length; - for (int i = 0; i < fieldsLength; i++) { - FieldDeclaration field; - if ((field = fields[i]).isStatic()) { - field.traverse(visitor, staticInitializerScope); - } else { - field.traverse(visitor, initializerScope); - } - } - } - if (methods != null) { - int methodsLength = methods.length; - for (int i = 0; i < methodsLength; i++) - methods[i].traverse(visitor, scope); - } - } - visitor.endVisit(this, classScope); - } catch (AbortType e) { - // silent abort - } - } - - /** - * Iteration for a package member type - * - */ - public void traverse(ASTVisitor visitor, CompilationUnitScope unitScope) { - - if (ignoreFurtherInvestigation) - return; - try { - if (visitor.visit(this, unitScope)) { - if (superclass != null) - superclass.traverse(visitor, scope); - if (superInterfaces != null) { - int superInterfaceLength = superInterfaces.length; - for (int i = 0; i < superInterfaceLength; i++) - superInterfaces[i].traverse(visitor, scope); - } - if (memberTypes != null) { - int memberTypesLength = memberTypes.length; - for (int i = 0; i < memberTypesLength; i++) - memberTypes[i].traverse(visitor, scope); - } - if (fields != null) { - int fieldsLength = fields.length; - for (int i = 0; i < fieldsLength; i++) { - FieldDeclaration field; - if ((field = fields[i]).isStatic()) { - field.traverse(visitor, staticInitializerScope); - } else { - field.traverse(visitor, initializerScope); - } - } - } - if (methods != null) { - int methodsLength = methods.length; - for (int i = 0; i < methodsLength; i++) - methods[i].traverse(visitor, scope); - } - } - visitor.endVisit(this, unitScope); - } catch (AbortType e) { - } - } - - /** - * MaxFieldCount's computation is necessary so as to reserve space for the flow info field portions. It corresponds to the maximum - * amount of fields this class or one of its innertypes have. - * - * During name resolution, types are traversed, and the max field count is recorded on the outermost type. It is then propagated - * down during the flow analysis. - * - * This method is doing either up/down propagation. - */ - void updateMaxFieldCount() { - - if (binding == null) - return; // error scenario - TypeDeclaration outerMostType = scope.outerMostClassScope().referenceType(); - if (maxFieldCount > outerMostType.maxFieldCount) { - outerMostType.maxFieldCount = maxFieldCount; // up - } else { - maxFieldCount = outerMostType.maxFieldCount; // down - } - } + public int declarationSourceStart; + + public int declarationSourceEnd; + + public int bodyStart; + + public int bodyEnd; // doesn't include the trailing comment if any. + + protected boolean hasBeenGenerated = false; + + public CompilationResult compilationResult; + + private MethodDeclaration[] missingAbstractMethods; + + public TypeDeclaration(CompilationResult compilationResult) { + this.compilationResult = compilationResult; + } + + /* + * We cause the compilation task to abort to a given extent. + */ + public void abort(int abortLevel) { + + if (scope == null) { + throw new AbortCompilation(); // cannot do better + } + + CompilationResult compilationResult = scope.referenceCompilationUnit().compilationResult; + + switch (abortLevel) { + case AbortCompilation: + throw new AbortCompilation(compilationResult); + case AbortCompilationUnit: + throw new AbortCompilationUnit(compilationResult); + case AbortMethod: + throw new AbortMethod(compilationResult); + default: + throw new AbortType(compilationResult); + } + } + + /** + * This method is responsible for adding a method declaration to the + * type method collections. Note that this implementation is inserting it in + * first place (as VAJ or javac), and that this impacts the behavior of the + * method ConstantPool.resetForClinit(int. int), in so far as the latter + * will have to reset the constant pool state accordingly (if it was added + * first, it does not need to preserve some of the method specific cached + * entries since this will be the first method). inserts the clinit method + * declaration in the first position. + * + * @see net.sourceforge.phpdt.internal.compiler.codegen.ConstantPool#resetForClinit(int, + * int) + */ + public final void addClinit() { + + // see comment on needClassInitMethod + if (needClassInitMethod()) { + int length; + AbstractMethodDeclaration[] methods; + if ((methods = this.methods) == null) { + length = 0; + methods = new AbstractMethodDeclaration[1]; + } else { + length = methods.length; + System.arraycopy(methods, 0, + (methods = new AbstractMethodDeclaration[length + 1]), + 1, length); + } + Clinit clinit = new Clinit(this.compilationResult); + methods[0] = clinit; + // clinit is added in first location, so as to minimize the use of + // ldcw (big consumer of constant inits) + clinit.declarationSourceStart = clinit.sourceStart = sourceStart; + clinit.declarationSourceEnd = clinit.sourceEnd = sourceEnd; + clinit.bodyEnd = sourceEnd; + this.methods = methods; + } + } + + /** + * Flow analysis for a local innertype + * + */ + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { + + if (ignoreFurtherInvestigation) + return flowInfo; + try { + bits |= IsReachableMASK; + LocalTypeBinding localType = (LocalTypeBinding) binding; + + localType.setConstantPoolName(currentScope.compilationUnitScope() + .computeConstantPoolName(localType)); + manageEnclosingInstanceAccessIfNecessary(currentScope); + + updateMaxFieldCount(); // propagate down the max field count + internalAnalyseCode(flowContext, flowInfo); + } catch (AbortType e) { + this.ignoreFurtherInvestigation = true; + } + return flowInfo; + } + + /** + * Flow analysis for a member innertype + * + */ + public void analyseCode(ClassScope enclosingClassScope) { + + if (ignoreFurtherInvestigation) + return; + try { + // propagate down the max field count + updateMaxFieldCount(); + internalAnalyseCode(null, FlowInfo.initial(maxFieldCount)); + } catch (AbortType e) { + this.ignoreFurtherInvestigation = true; + } + } + + /** + * Flow analysis for a local member innertype + * + */ + public void analyseCode(ClassScope currentScope, FlowContext flowContext, + FlowInfo flowInfo) { + + if (ignoreFurtherInvestigation) + return; + try { + bits |= IsReachableMASK; + LocalTypeBinding localType = (LocalTypeBinding) binding; + + localType.setConstantPoolName(currentScope.compilationUnitScope() + .computeConstantPoolName(localType)); + manageEnclosingInstanceAccessIfNecessary(currentScope); + + updateMaxFieldCount(); // propagate down the max field count + internalAnalyseCode(flowContext, flowInfo); + } catch (AbortType e) { + this.ignoreFurtherInvestigation = true; + } + } + + /** + * Flow analysis for a package member type + * + */ + public void analyseCode(CompilationUnitScope unitScope) { + + if (ignoreFurtherInvestigation) + return; + try { + internalAnalyseCode(null, FlowInfo.initial(maxFieldCount)); + } catch (AbortType e) { + this.ignoreFurtherInvestigation = true; + } + } + + /* + * Check for constructor vs. method with no return type. Answers true if at + * least one constructor is defined + */ + public boolean checkConstructors(Parser parser) { + + // if a constructor has not the name of the type, + // convert it into a method with 'null' as its return type + boolean hasConstructor = false; + if (methods != null) { + for (int i = methods.length; --i >= 0;) { + AbstractMethodDeclaration am; + if ((am = methods[i]).isConstructor()) { + if (!CharOperation.equals(am.selector, name)) { + // the constructor was in fact a method with no return + // type + // unless an explicit constructor call was supplied + ConstructorDeclaration c = (ConstructorDeclaration) am; + if ((c.constructorCall == null) + || (c.constructorCall.isImplicitSuper())) { // changed + // to a + // method + MethodDeclaration m = new MethodDeclaration( + this.compilationResult); + m.sourceStart = c.sourceStart; + m.sourceEnd = c.sourceEnd; + m.bodyStart = c.bodyStart; + m.bodyEnd = c.bodyEnd; + m.declarationSourceEnd = c.declarationSourceEnd; + m.declarationSourceStart = c.declarationSourceStart; + m.selector = c.selector; + m.statements = c.statements; + m.modifiers = c.modifiers; + m.arguments = c.arguments; + m.thrownExceptions = c.thrownExceptions; + m.explicitDeclarations = c.explicitDeclarations; + m.returnType = null; + methods[i] = m; + } + } else { + if (this.isInterface()) { + // report the problem and continue the parsing + parser.problemReporter() + .interfaceCannotHaveConstructors( + (ConstructorDeclaration) am); + } + hasConstructor = true; + } + } + } + } + return hasConstructor; + } + + public CompilationResult compilationResult() { + + return this.compilationResult; + } + + public ConstructorDeclaration createsInternalConstructor( + boolean needExplicitConstructorCall, boolean needToInsert) { + + // Add to method'set, the default constuctor that just recall the + // super constructor with no arguments + // The arguments' type will be positionned by the TC so just use + // the default int instead of just null (consistency purpose) + + // the constructor + ConstructorDeclaration constructor = new ConstructorDeclaration( + this.compilationResult); + constructor.isDefaultConstructor = true; + constructor.selector = name; + if (modifiers != AccDefault) { + constructor.modifiers = ((this instanceof MemberTypeDeclaration) && (modifiers & AccPrivate) != 0) ? AccDefault + : modifiers & AccVisibilityMASK; + } + + // if you change this setting, please update the + // SourceIndexer2.buildTypeDeclaration(TypeDeclaration,char[]) method + constructor.declarationSourceStart = constructor.sourceStart = sourceStart; + constructor.declarationSourceEnd = constructor.sourceEnd = constructor.bodyEnd = sourceEnd; + + // the super call inside the constructor + if (needExplicitConstructorCall) { + constructor.constructorCall = SuperReference + .implicitSuperConstructorCall(); + constructor.constructorCall.sourceStart = sourceStart; + constructor.constructorCall.sourceEnd = sourceEnd; + } + + // adding the constructor in the methods list + if (needToInsert) { + if (methods == null) { + methods = new AbstractMethodDeclaration[] { constructor }; + } else { + AbstractMethodDeclaration[] newMethods; + System + .arraycopy( + methods, + 0, + newMethods = new AbstractMethodDeclaration[methods.length + 1], + 1, methods.length); + newMethods[0] = constructor; + methods = newMethods; + } + } + return constructor; + } + + /** + * INTERNAL USE ONLY - Creates a fake method declaration for the + * corresponding binding. It is used to report errors for missing abstract + * methods. + */ + public MethodDeclaration addMissingAbstractMethodFor( + MethodBinding methodBinding) { + TypeBinding[] argumentTypes = methodBinding.parameters; + int argumentsLength = argumentTypes.length; + // the constructor + MethodDeclaration methodDeclaration = new MethodDeclaration( + this.compilationResult); + methodDeclaration.selector = methodBinding.selector; + methodDeclaration.sourceStart = sourceStart; + methodDeclaration.sourceEnd = sourceEnd; + methodDeclaration.modifiers = methodBinding.getAccessFlags() + & ~AccAbstract; + + if (argumentsLength > 0) { + String baseName = "arg";//$NON-NLS-1$ + Argument[] arguments = (methodDeclaration.arguments = new Argument[argumentsLength]); + for (int i = argumentsLength; --i >= 0;) { + arguments[i] = new Argument((baseName + i).toCharArray(), 0L, + null /* type ref */, AccDefault); + } + } + + // adding the constructor in the methods list + if (this.missingAbstractMethods == null) { + this.missingAbstractMethods = new MethodDeclaration[] { methodDeclaration }; + } else { + MethodDeclaration[] newMethods; + System + .arraycopy( + this.missingAbstractMethods, + 0, + newMethods = new MethodDeclaration[this.missingAbstractMethods.length + 1], + 1, this.missingAbstractMethods.length); + newMethods[0] = methodDeclaration; + this.missingAbstractMethods = newMethods; + } + + // ============BINDING UPDATE========================== + methodDeclaration.binding = new MethodBinding( + methodDeclaration.modifiers, // methodDeclaration + methodBinding.selector, methodBinding.returnType, + argumentsLength == 0 ? NoParameters : argumentTypes, // arguments + // bindings + methodBinding.thrownExceptions, // exceptions + binding); // declaringClass + + methodDeclaration.scope = new MethodScope(scope, methodDeclaration, + true); + methodDeclaration.bindArguments(); + + /* + * if (binding.methods == null) { binding.methods = new MethodBinding[] { + * methodDeclaration.binding }; } else { MethodBinding[] newMethods; + * System.arraycopy( binding.methods, 0, newMethods = new + * MethodBinding[binding.methods.length + 1], 1, + * binding.methods.length); newMethods[0] = methodDeclaration.binding; + * binding.methods = newMethods; } + */ + // =================================================== + return methodDeclaration; + } + + /* + * Find the matching parse node, answers null if nothing found + */ + public FieldDeclaration declarationOf(FieldBinding fieldBinding) { + + if (fieldBinding != null) { + for (int i = 0, max = this.fields.length; i < max; i++) { + FieldDeclaration fieldDecl; + if ((fieldDecl = this.fields[i]).binding == fieldBinding) + return fieldDecl; + } + } + return null; + } + + /* + * Find the matching parse node, answers null if nothing found + */ + public TypeDeclaration declarationOf(MemberTypeBinding memberTypeBinding) { + + if (memberTypeBinding != null) { + for (int i = 0, max = this.memberTypes.length; i < max; i++) { + TypeDeclaration memberTypeDecl; + if ((memberTypeDecl = this.memberTypes[i]).binding == memberTypeBinding) + return memberTypeDecl; + } + } + return null; + } + + /* + * Find the matching parse node, answers null if nothing found + */ + public AbstractMethodDeclaration declarationOf(MethodBinding methodBinding) { + + if (methodBinding != null) { + for (int i = 0, max = this.methods.length; i < max; i++) { + AbstractMethodDeclaration methodDecl; + + if ((methodDecl = this.methods[i]).binding == methodBinding) + return methodDecl; + } + } + return null; + } + + /* + * Finds the matching type amoung this type's member types. Returns null if + * no type with this name is found. The type name is a compound name + * relative to this type eg. if this type is X and we're looking for Y.X.A.B + * then a type name would be {X, A, B} + */ + public TypeDeclaration declarationOfType(char[][] typeName) { + + int typeNameLength = typeName.length; + if (typeNameLength < 1 || !CharOperation.equals(typeName[0], this.name)) { + return null; + } + if (typeNameLength == 1) { + return this; + } + char[][] subTypeName = new char[typeNameLength - 1][]; + System.arraycopy(typeName, 1, subTypeName, 0, typeNameLength - 1); + for (int i = 0; i < this.memberTypes.length; i++) { + TypeDeclaration typeDecl = this.memberTypes[i] + .declarationOfType(subTypeName); + if (typeDecl != null) { + return typeDecl; + } + } + return null; + } + + /** + * Generic bytecode generation for type + */ + // public void generateCode(ClassFile enclosingClassFile) { + // + // if (hasBeenGenerated) + // return; + // hasBeenGenerated = true; + // if (ignoreFurtherInvestigation) { + // if (binding == null) + // return; + // ClassFile.createProblemType( + // this, + // scope.referenceCompilationUnit().compilationResult); + // return; + // } + // try { + // // create the result for a compiled type + // ClassFile classFile = new ClassFile(binding, enclosingClassFile, false); + // // generate all fiels + // classFile.addFieldInfos(); + // + // // record the inner type inside its own .class file to be able + // // to generate inner classes attributes + // if (binding.isMemberType()) + // classFile.recordEnclosingTypeAttributes(binding); + // if (binding.isLocalType()) { + // enclosingClassFile.recordNestedLocalAttribute(binding); + // classFile.recordNestedLocalAttribute(binding); + // } + // if (memberTypes != null) { + // for (int i = 0, max = memberTypes.length; i < max; i++) { + // // record the inner type inside its own .class file to be able + // // to generate inner classes attributes + // classFile.recordNestedMemberAttribute(memberTypes[i].binding); + // memberTypes[i].generateCode(scope, classFile); + // } + // } + // // generate all methods + // classFile.setForMethodInfos(); + // if (methods != null) { + // for (int i = 0, max = methods.length; i < max; i++) { + // methods[i].generateCode(scope, classFile); + // } + // } + // + // classFile.generateMissingAbstractMethods(this.missingAbstractMethods, + // scope.referenceCompilationUnit().compilationResult); + // + // // generate all methods + // classFile.addSpecialMethods(); + // + // if (ignoreFurtherInvestigation) { // trigger problem type generation for + // code gen errors + // throw new AbortType(scope.referenceCompilationUnit().compilationResult); + // } + // + // // finalize the compiled type result + // classFile.addAttributes(); + // scope.referenceCompilationUnit().compilationResult.record( + // binding.constantPoolName(), + // classFile); + // } catch (AbortType e) { + // if (binding == null) + // return; + // ClassFile.createProblemType( + // this, + // scope.referenceCompilationUnit().compilationResult); + // } + // } + /** + * Bytecode generation for a local inner type (API as a normal statement + * code gen) + */ + // public void generateCode(BlockScope blockScope, CodeStream codeStream) { + // + // if (hasBeenGenerated) return; + // int pc = codeStream.position; + // if (binding != null) ((NestedTypeBinding) + // binding).computeSyntheticArgumentSlotSizes(); + // generateCode(codeStream.classFile); + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } + /** + * Bytecode generation for a member inner type + */ + // public void generateCode(ClassScope classScope, ClassFile + // enclosingClassFile) { + // + // if (hasBeenGenerated) return; + // if (binding != null) ((NestedTypeBinding) + // binding).computeSyntheticArgumentSlotSizes(); + // generateCode(enclosingClassFile); + // } + /** + * Bytecode generation for a package member + */ + // public void generateCode(CompilationUnitScope unitScope) { + // + // generateCode((ClassFile) null); + // } + public boolean hasErrors() { + return this.ignoreFurtherInvestigation; + } + + /** + * Common flow analysis for all types + * + */ + public void internalAnalyseCode(FlowContext flowContext, FlowInfo flowInfo) { + + if (this.binding.isPrivate() && !this.binding.isPrivateUsed()) { + if (!scope.referenceCompilationUnit().compilationResult + .hasSyntaxError()) { + scope.problemReporter().unusedPrivateType(this); + } + } + + ReferenceBinding[] defaultHandledExceptions = new ReferenceBinding[] { scope + .getJavaLangThrowable() }; // tolerate any kind of + // exception + InitializationFlowContext initializerContext = new InitializationFlowContext( + null, this, initializerScope); + InitializationFlowContext staticInitializerContext = new InitializationFlowContext( + null, this, staticInitializerScope); + FlowInfo nonStaticFieldInfo = flowInfo.copy().unconditionalInits() + .discardFieldInitializations(); + FlowInfo staticFieldInfo = flowInfo.copy().unconditionalInits() + .discardFieldInitializations(); + if (fields != null) { + for (int i = 0, count = fields.length; i < count; i++) { + FieldDeclaration field = fields[i]; + if (field.isStatic()) { + /* + * if (field.isField()){ + * staticInitializerContext.handledExceptions = + * NoExceptions; // no exception is allowed jls8.3.2 } else { + */ + staticInitializerContext.handledExceptions = defaultHandledExceptions; // tolerate + // them + // all, + // and + // record + // them + /* } */ + staticFieldInfo = field.analyseCode(staticInitializerScope, + staticInitializerContext, staticFieldInfo); + // in case the initializer is not reachable, use a + // reinitialized flowInfo and enter a fake reachable + // branch, since the previous initializer already got the + // blame. + if (staticFieldInfo == FlowInfo.DEAD_END) { + staticInitializerScope.problemReporter() + .initializerMustCompleteNormally(field); + staticFieldInfo = FlowInfo.initial(maxFieldCount) + .setReachMode(FlowInfo.UNREACHABLE); + } + } else { + /* + * if (field.isField()){ + * initializerContext.handledExceptions = NoExceptions; // + * no exception is allowed jls8.3.2 } else { + */ + initializerContext.handledExceptions = defaultHandledExceptions; // tolerate + // them + // all, + // and + // record + // them + /* } */ + nonStaticFieldInfo = field.analyseCode(initializerScope, + initializerContext, nonStaticFieldInfo); + // in case the initializer is not reachable, use a + // reinitialized flowInfo and enter a fake reachable + // branch, since the previous initializer already got the + // blame. + if (nonStaticFieldInfo == FlowInfo.DEAD_END) { + initializerScope.problemReporter() + .initializerMustCompleteNormally(field); + nonStaticFieldInfo = FlowInfo.initial(maxFieldCount) + .setReachMode(FlowInfo.UNREACHABLE); + } + } + } + } + if (memberTypes != null) { + for (int i = 0, count = memberTypes.length; i < count; i++) { + if (flowContext != null) { // local type + memberTypes[i].analyseCode(scope, flowContext, + nonStaticFieldInfo.copy()); + } else { + memberTypes[i].analyseCode(scope); + } + } + } + if (methods != null) { + UnconditionalFlowInfo outerInfo = flowInfo.copy() + .unconditionalInits().discardFieldInitializations(); + FlowInfo constructorInfo = nonStaticFieldInfo.unconditionalInits() + .discardNonFieldInitializations().addInitializationsFrom( + outerInfo); + for (int i = 0, count = methods.length; i < count; i++) { + AbstractMethodDeclaration method = methods[i]; + if (method.ignoreFurtherInvestigation) + continue; + if (method.isInitializationMethod()) { + if (method.isStatic()) { // + method.analyseCode(scope, staticInitializerContext, + staticFieldInfo.unconditionalInits() + .discardNonFieldInitializations() + .addInitializationsFrom(outerInfo)); + } else { // constructor + method.analyseCode(scope, initializerContext, + constructorInfo.copy()); + } + } else { // regular method + method.analyseCode(scope, null, flowInfo.copy()); + } + } + } + } + + public boolean isInterface() { + + return (modifiers & AccInterface) != 0; + } + + /* + * Access emulation for a local type force to emulation of access to direct + * enclosing instance. By using the initializer scope, we actually only + * request an argument emulation, the field is not added until actually + * used. However we will force allocations to be qualified with an enclosing + * instance. 15.9.2 + */ + public void manageEnclosingInstanceAccessIfNecessary(BlockScope currentScope) { + + NestedTypeBinding nestedType = (NestedTypeBinding) binding; + + MethodScope methodScope = currentScope.methodScope(); + if (!methodScope.isStatic && !methodScope.isConstructorCall) { + + nestedType.addSyntheticArgumentAndField(binding.enclosingType()); + } + // add superclass enclosing instance arg for anonymous types (if + // necessary) + if (binding.isAnonymousType()) { + ReferenceBinding superclass = binding.superclass; + if (superclass.enclosingType() != null && !superclass.isStatic()) { + if (!binding.superclass.isLocalType() + || ((NestedTypeBinding) binding.superclass) + .getSyntheticField(superclass.enclosingType(), + true) != null) { + + nestedType.addSyntheticArgument(superclass.enclosingType()); + } + } + } + } + + /* + * Access emulation for a local member type force to emulation of access to + * direct enclosing instance. By using the initializer scope, we actually + * only request an argument emulation, the field is not added until actually + * used. However we will force allocations to be qualified with an enclosing + * instance. + * + * Local member cannot be static. + */ + public void manageEnclosingInstanceAccessIfNecessary(ClassScope currentScope) { + + NestedTypeBinding nestedType = (NestedTypeBinding) binding; + nestedType.addSyntheticArgumentAndField(binding.enclosingType()); + } + + /** + * A will be requested as soon as static fields or assertions are + * present. It will be eliminated during classfile creation if no bytecode + * was actually produced based on some optimizations/compiler settings. + */ + public final boolean needClassInitMethod() { + + // always need a when assertions are present + if ((this.bits & AddAssertionMASK) != 0) + return true; + if (fields == null) + return false; + if (isInterface()) + return true; // fields are implicitly statics + for (int i = fields.length; --i >= 0;) { + FieldDeclaration field = fields[i]; + // need to test the modifier directly while there is no binding yet + if ((field.modifiers & AccStatic) != 0) + return true; + } + return false; + } + + public void parseMethod(UnitParser parser, CompilationUnitDeclaration unit) { + + // connect method bodies + if (unit.ignoreMethodBodies) + return; + + // no scope were created, so cannot report further errors + // if (binding == null) + // return; + + // members + if (memberTypes != null) { + int length = memberTypes.length; + for (int i = 0; i < length; i++) + memberTypes[i].parseMethod(parser, unit); + } + + // methods + if (methods != null) { + int length = methods.length; + for (int i = 0; i < length; i++) + methods[i].parseStatements(parser, unit); + } + + // initializers + if (fields != null) { + int length = fields.length; + for (int i = 0; i < length; i++) { + if (fields[i] instanceof Initializer) { + ((Initializer) fields[i]).parseStatements(parser, this, + unit); + } + } + } + } + + public void resolve() { + + if (binding == null) { + ignoreFurtherInvestigation = true; + return; + } + + try { + // check superclass & interfaces + if (binding.superclass != null) // watch out for Object ! (and other + // roots) + if (isTypeUseDeprecated(binding.superclass, scope)) + scope.problemReporter().deprecatedType(binding.superclass, + superclass); + if (superInterfaces != null) + for (int i = superInterfaces.length; --i >= 0;) + if (superInterfaces[i].resolvedType != null) + if (isTypeUseDeprecated( + superInterfaces[i].resolvedType, scope)) + scope.problemReporter().deprecatedType( + superInterfaces[i].resolvedType, + superInterfaces[i]); + maxFieldCount = 0; + int lastFieldID = -1; + if (fields != null) { + for (int i = 0, count = fields.length; i < count; i++) { + FieldDeclaration field = fields[i]; + if (field.isField()) { + if (field.binding == null) { + // still discover secondary errors + if (field.initialization != null) + field.initialization + .resolve(field.isStatic() ? staticInitializerScope + : initializerScope); + ignoreFurtherInvestigation = true; + continue; + } + maxFieldCount++; + lastFieldID = field.binding.id; + } else { // initializer + ((Initializer) field).lastFieldID = lastFieldID + 1; + } + field.resolve(field.isStatic() ? staticInitializerScope + : initializerScope); + } + } + if (memberTypes != null) { + for (int i = 0, count = memberTypes.length; i < count; i++) { + memberTypes[i].resolve(scope); + } + } + int missingAbstractMethodslength = this.missingAbstractMethods == null ? 0 + : this.missingAbstractMethods.length; + int methodsLength = this.methods == null ? 0 : methods.length; + if ((methodsLength + missingAbstractMethodslength) > 0xFFFF) { + scope.problemReporter().tooManyMethods(this); + } + + if (methods != null) { + for (int i = 0, count = methods.length; i < count; i++) { + methods[i].resolve(scope); + } + } + } catch (AbortType e) { + this.ignoreFurtherInvestigation = true; + return; + } + ; + } + + public void resolve(BlockScope blockScope) { + // local type declaration + + // need to build its scope first and proceed with binding's creation + blockScope.addLocalType(this); + + // and TC.... + if (binding != null) { + // remember local types binding for innerclass emulation propagation + blockScope.referenceCompilationUnit().record( + (LocalTypeBinding) binding); + + // binding is not set if the receiver could not be created + resolve(); + updateMaxFieldCount(); + } + } + + public void resolve(ClassScope upperScope) { + // member scopes are already created + // request the construction of a binding if local member type + + if (binding != null && binding instanceof LocalTypeBinding) { + // remember local types binding for innerclass emulation propagation + upperScope.referenceCompilationUnit().record( + (LocalTypeBinding) binding); + } + resolve(); + updateMaxFieldCount(); + } + + public void resolve(CompilationUnitScope upperScope) { + // top level : scope are already created + + resolve(); + updateMaxFieldCount(); + } + + public void tagAsHavingErrors() { + ignoreFurtherInvestigation = true; + } + + public StringBuffer print(int indent, StringBuffer output) { + + // if ((this.bits & IsAnonymousTypeMASK) == 0) { + printIndent(indent, output); + printHeader(0, output); + // } + return printBody(indent, output); + } + + public StringBuffer printBody(int indent, StringBuffer output) { + + output.append(" {"); //$NON-NLS-1$ + if (memberTypes != null) { + for (int i = 0; i < memberTypes.length; i++) { + if (memberTypes[i] != null) { + output.append('\n'); + memberTypes[i].print(indent + 1, output); + } + } + } + if (fields != null) { + for (int fieldI = 0; fieldI < fields.length; fieldI++) { + if (fields[fieldI] != null) { + output.append('\n'); + fields[fieldI].print(indent + 1, output); + } + } + } + if (methods != null) { + for (int i = 0; i < methods.length; i++) { + if (methods[i] != null) { + output.append('\n'); + methods[i].print(indent + 1, output); + } + } + } + output.append('\n'); + return printIndent(indent, output).append('}'); + } + + public StringBuffer printHeader(int indent, StringBuffer output) { + + printModifiers(this.modifiers, output); + output.append(isInterface() ? "interface " : "class "); //$NON-NLS-1$ //$NON-NLS-2$ + output.append(name); + if (superclass != null) { + output.append(" extends "); //$NON-NLS-1$ + superclass.print(0, output); + } + if (superInterfaces != null && superInterfaces.length > 0) { + output.append(isInterface() ? " extends " : " implements ");//$NON-NLS-2$ //$NON-NLS-1$ + for (int i = 0; i < superInterfaces.length; i++) { + if (i > 0) + output.append(", "); //$NON-NLS-1$ + superInterfaces[i].print(0, output); + } + } + return output; + } + + public StringBuffer printStatement(int tab, StringBuffer output) { + return print(tab, output); + } + + public String toString(int tab) { + + return tabString(tab) + toStringHeader() + toStringBody(tab); + } + + public String toStringBody(int tab) { + + String s = " {"; //$NON-NLS-1$ + if (memberTypes != null) { + for (int i = 0; i < memberTypes.length; i++) { + if (memberTypes[i] != null) { + s += "\n" + memberTypes[i].toString(tab + 1); //$NON-NLS-1$ + } + } + } + if (fields != null) { + for (int fieldI = 0; fieldI < fields.length; fieldI++) { + if (fields[fieldI] != null) { + s += "\n" + fields[fieldI].toString(tab + 1); //$NON-NLS-1$ + if (fields[fieldI].isField()) + s += ";"; //$NON-NLS-1$ + } + } + } + if (methods != null) { + for (int i = 0; i < methods.length; i++) { + if (methods[i] != null) { + s += "\n" + methods[i].toString(tab + 1); //$NON-NLS-1$ + } + } + } + s += "\n" + tabString(tab) + "}"; //$NON-NLS-2$ //$NON-NLS-1$ + return s; + } + + public String toStringHeader() { + + String s = ""; //$NON-NLS-1$ + if (modifiers != AccDefault) { + s += modifiersString(modifiers); + } + s += (isInterface() ? "interface " : "class ") + new String(name);//$NON-NLS-1$ //$NON-NLS-2$ + if (superclass != null) + s += " extends " + superclass.toString(0); //$NON-NLS-1$ + if (superInterfaces != null && superInterfaces.length > 0) { + s += (isInterface() ? " extends " : " implements ");//$NON-NLS-2$ //$NON-NLS-1$ + for (int i = 0; i < superInterfaces.length; i++) { + s += superInterfaces[i].toString(0); + if (i != superInterfaces.length - 1) + s += ", "; //$NON-NLS-1$ + } + ; + } + ; + return s; + } + + /** + * Iteration for a local innertype + * + */ + public void traverse(ASTVisitor visitor, BlockScope blockScope) { + if (ignoreFurtherInvestigation) + return; + try { + if (visitor.visit(this, blockScope)) { + if (superclass != null) + superclass.traverse(visitor, scope); + if (superInterfaces != null) { + int superInterfaceLength = superInterfaces.length; + for (int i = 0; i < superInterfaceLength; i++) + superInterfaces[i].traverse(visitor, scope); + } + if (memberTypes != null) { + int memberTypesLength = memberTypes.length; + for (int i = 0; i < memberTypesLength; i++) + memberTypes[i].traverse(visitor, scope); + } + if (fields != null) { + int fieldsLength = fields.length; + for (int i = 0; i < fieldsLength; i++) { + FieldDeclaration field; + if ((field = fields[i]).isStatic()) { + // local type cannot have static fields + } else { + field.traverse(visitor, initializerScope); + } + } + } + if (methods != null) { + int methodsLength = methods.length; + for (int i = 0; i < methodsLength; i++) + methods[i].traverse(visitor, scope); + } + } + visitor.endVisit(this, blockScope); + } catch (AbortType e) { + // silent abort + } + } + + /** + * Iteration for a member innertype + * + */ + public void traverse(ASTVisitor visitor, ClassScope classScope) { + if (ignoreFurtherInvestigation) + return; + try { + if (visitor.visit(this, classScope)) { + if (superclass != null) + superclass.traverse(visitor, scope); + if (superInterfaces != null) { + int superInterfaceLength = superInterfaces.length; + for (int i = 0; i < superInterfaceLength; i++) + superInterfaces[i].traverse(visitor, scope); + } + if (memberTypes != null) { + int memberTypesLength = memberTypes.length; + for (int i = 0; i < memberTypesLength; i++) + memberTypes[i].traverse(visitor, scope); + } + if (fields != null) { + int fieldsLength = fields.length; + for (int i = 0; i < fieldsLength; i++) { + FieldDeclaration field; + if ((field = fields[i]).isStatic()) { + field.traverse(visitor, staticInitializerScope); + } else { + field.traverse(visitor, initializerScope); + } + } + } + if (methods != null) { + int methodsLength = methods.length; + for (int i = 0; i < methodsLength; i++) + methods[i].traverse(visitor, scope); + } + } + visitor.endVisit(this, classScope); + } catch (AbortType e) { + // silent abort + } + } + + /** + * Iteration for a package member type + * + */ + public void traverse(ASTVisitor visitor, CompilationUnitScope unitScope) { + + if (ignoreFurtherInvestigation) + return; + try { + if (visitor.visit(this, unitScope)) { + if (superclass != null) + superclass.traverse(visitor, scope); + if (superInterfaces != null) { + int superInterfaceLength = superInterfaces.length; + for (int i = 0; i < superInterfaceLength; i++) + superInterfaces[i].traverse(visitor, scope); + } + if (memberTypes != null) { + int memberTypesLength = memberTypes.length; + for (int i = 0; i < memberTypesLength; i++) + memberTypes[i].traverse(visitor, scope); + } + if (fields != null) { + int fieldsLength = fields.length; + for (int i = 0; i < fieldsLength; i++) { + FieldDeclaration field; + if ((field = fields[i]).isStatic()) { + field.traverse(visitor, staticInitializerScope); + } else { + field.traverse(visitor, initializerScope); + } + } + } + if (methods != null) { + int methodsLength = methods.length; + for (int i = 0; i < methodsLength; i++) + methods[i].traverse(visitor, scope); + } + } + visitor.endVisit(this, unitScope); + } catch (AbortType e) { + } + } + + /** + * MaxFieldCount's computation is necessary so as to reserve space for the + * flow info field portions. It corresponds to the maximum amount of fields + * this class or one of its innertypes have. + * + * During name resolution, types are traversed, and the max field count is + * recorded on the outermost type. It is then propagated down during the + * flow analysis. + * + * This method is doing either up/down propagation. + */ + void updateMaxFieldCount() { + + if (binding == null) + return; // error scenario + TypeDeclaration outerMostType = scope.outerMostClassScope() + .referenceType(); + if (maxFieldCount > outerMostType.maxFieldCount) { + outerMostType.maxFieldCount = maxFieldCount; // up + } else { + maxFieldCount = outerMostType.maxFieldCount; // down + } + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/TypeReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/TypeReference.java index 0450380..d4dabea 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/TypeReference.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/TypeReference.java @@ -20,92 +20,103 @@ import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public abstract class TypeReference extends Expression { -public TypeReference() { - super () ; - } + public TypeReference() { + super(); + } -public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { - return flowInfo; -} + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { + return flowInfo; + } -// allows us to trap completion & selection nodes -public void aboutToResolve(Scope scope) {} -/* - * Answer a base type reference (can be an array of base type). - */ -//public static final TypeReference baseTypeReference(int baseType, int dim) { -// -// if (dim == 0) { -// switch (baseType) { -// case (T_void) : -// return new SingleTypeReference(VoidBinding.simpleName, 0); -// case (T_boolean) : -// return new SingleTypeReference(BooleanBinding.simpleName, 0); -// case (T_char) : -// return new SingleTypeReference(CharBinding.simpleName, 0); -// case (T_float) : -// return new SingleTypeReference(FloatBinding.simpleName, 0); -// case (T_double) : -// return new SingleTypeReference(DoubleBinding.simpleName, 0); -// case (T_byte) : -// return new SingleTypeReference(ByteBinding.simpleName, 0); -// case (T_short) : -// return new SingleTypeReference(ShortBinding.simpleName, 0); -// case (T_int) : -// return new SingleTypeReference(IntBinding.simpleName, 0); -// default : //T_long -// return new SingleTypeReference(LongBinding.simpleName, 0); -// } -// } -// switch (baseType) { -// case (T_void) : -// return new ArrayTypeReference(VoidBinding.simpleName, dim, 0); -// case (T_boolean) : -// return new ArrayTypeReference(BooleanBinding.simpleName, dim, 0); -// case (T_char) : -// return new ArrayTypeReference(CharBinding.simpleName, dim, 0); -// case (T_float) : -// return new ArrayTypeReference(FloatBinding.simpleName, dim, 0); -// case (T_double) : -// return new ArrayTypeReference(DoubleBinding.simpleName, dim, 0); -// case (T_byte) : -// return new ArrayTypeReference(ByteBinding.simpleName, dim, 0); -// case (T_short) : -// return new ArrayTypeReference(ShortBinding.simpleName, dim, 0); -// case (T_int) : -// return new ArrayTypeReference(IntBinding.simpleName, dim, 0); -// default : //T_long -// return new ArrayTypeReference(LongBinding.simpleName, dim, 0); -// } -//} -public abstract TypeReference copyDims(int dim); -public int dimensions() { - return 0; -} -public abstract TypeBinding getTypeBinding(Scope scope); -/** - * @return char[][] - */ -public abstract char [][] getTypeName() ; -public boolean isTypeReference() { - return true; -} -public TypeBinding resolveType(BlockScope scope) { - // handle the error here - constant = NotAConstant; - if (this.resolvedType != null) { // is a shared type reference which was already resolved - if (!this.resolvedType.isValidBinding()) - return null; // already reported error - } else { - this.resolvedType = getTypeBinding(scope); - if (!this.resolvedType.isValidBinding()) { - scope.problemReporter().invalidType(this, this.resolvedType); - return null; + // allows us to trap completion & selection nodes + public void aboutToResolve(Scope scope) { + } + + /* + * Answer a base type reference (can be an array of base type). + */ + // public static final TypeReference baseTypeReference(int baseType, int + // dim) { + // + // if (dim == 0) { + // switch (baseType) { + // case (T_void) : + // return new SingleTypeReference(VoidBinding.simpleName, 0); + // case (T_boolean) : + // return new SingleTypeReference(BooleanBinding.simpleName, 0); + // case (T_char) : + // return new SingleTypeReference(CharBinding.simpleName, 0); + // case (T_float) : + // return new SingleTypeReference(FloatBinding.simpleName, 0); + // case (T_double) : + // return new SingleTypeReference(DoubleBinding.simpleName, 0); + // case (T_byte) : + // return new SingleTypeReference(ByteBinding.simpleName, 0); + // case (T_short) : + // return new SingleTypeReference(ShortBinding.simpleName, 0); + // case (T_int) : + // return new SingleTypeReference(IntBinding.simpleName, 0); + // default : //T_long + // return new SingleTypeReference(LongBinding.simpleName, 0); + // } + // } + // switch (baseType) { + // case (T_void) : + // return new ArrayTypeReference(VoidBinding.simpleName, dim, 0); + // case (T_boolean) : + // return new ArrayTypeReference(BooleanBinding.simpleName, dim, 0); + // case (T_char) : + // return new ArrayTypeReference(CharBinding.simpleName, dim, 0); + // case (T_float) : + // return new ArrayTypeReference(FloatBinding.simpleName, dim, 0); + // case (T_double) : + // return new ArrayTypeReference(DoubleBinding.simpleName, dim, 0); + // case (T_byte) : + // return new ArrayTypeReference(ByteBinding.simpleName, dim, 0); + // case (T_short) : + // return new ArrayTypeReference(ShortBinding.simpleName, dim, 0); + // case (T_int) : + // return new ArrayTypeReference(IntBinding.simpleName, dim, 0); + // default : //T_long + // return new ArrayTypeReference(LongBinding.simpleName, dim, 0); + // } + // } + public abstract TypeReference copyDims(int dim); + + public int dimensions() { + return 0; + } + + public abstract TypeBinding getTypeBinding(Scope scope); + + /** + * @return char[][] + */ + public abstract char[][] getTypeName(); + + public boolean isTypeReference() { + return true; + } + + public TypeBinding resolveType(BlockScope scope) { + // handle the error here + constant = NotAConstant; + if (this.resolvedType != null) { // is a shared type reference which + // was already resolved + if (!this.resolvedType.isValidBinding()) + return null; // already reported error + } else { + this.resolvedType = getTypeBinding(scope); + if (!this.resolvedType.isValidBinding()) { + scope.problemReporter().invalidType(this, this.resolvedType); + return null; + } + if (isTypeUseDeprecated(this.resolvedType, scope)) + scope.problemReporter().deprecatedType(this.resolvedType, this); } - if (isTypeUseDeprecated(this.resolvedType, scope)) - scope.problemReporter().deprecatedType(this.resolvedType, this); + return this.resolvedType; } - return this.resolvedType; -} -public abstract void traverse(ASTVisitor visitor, ClassScope classScope); + + public abstract void traverse(ASTVisitor visitor, ClassScope classScope); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/UnaryExpression.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/UnaryExpression.java index d21dc2e..81ed939 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/UnaryExpression.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/UnaryExpression.java @@ -17,10 +17,10 @@ import net.sourceforge.phpdt.internal.compiler.impl.Constant; import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; - public class UnaryExpression extends OperatorExpression { - + public Expression expression; + public Constant optimizedBooleanConstant; public UnaryExpression(Expression expression, int operator) { @@ -28,180 +28,180 @@ public class UnaryExpression extends OperatorExpression { this.bits |= operator << OperatorSHIFT; // encode operator } - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { - + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { + if (((bits & OperatorMASK) >> OperatorSHIFT) == NOT) { - return this.expression - .analyseCode(currentScope, flowContext, flowInfo) - .asNegatedCondition(); + return this.expression.analyseCode(currentScope, flowContext, + flowInfo).asNegatedCondition(); } else { - return this.expression.analyseCode(currentScope, flowContext, flowInfo); + return this.expression.analyseCode(currentScope, flowContext, + flowInfo); } } public Constant optimizedBooleanConstant() { - - return this.optimizedBooleanConstant == null - ? this.constant + + return this.optimizedBooleanConstant == null ? this.constant : this.optimizedBooleanConstant; } /** * Code generation for an unary operation - * - * @param currentScope net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream - * @param valueRequired boolean + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * @param valueRequired + * boolean */ -// public void generateCode( -// BlockScope currentScope, -// CodeStream codeStream, -// boolean valueRequired) { -// -// int pc = codeStream.position; -// Label falseLabel, endifLabel; -// if (this.constant != Constant.NotAConstant) { -// // inlined value -// if (valueRequired) { -// codeStream.generateConstant(this.constant, this.implicitConversion); -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// return; -// } -// switch ((bits & OperatorMASK) >> OperatorSHIFT) { -// case NOT : -// switch (this.expression.implicitConversion >> 4) /* runtime type */ { -// case T_boolean : -// // ! -// // Generate code for the condition -// this.expression.generateOptimizedBoolean( -// currentScope, -// codeStream, -// null, -// (falseLabel = new Label(codeStream)), -// valueRequired); -// if (valueRequired) { -// codeStream.iconst_0(); -// if (falseLabel.hasForwardReferences()) { -// codeStream.goto_(endifLabel = new Label(codeStream)); -// codeStream.decrStackSize(1); -// falseLabel.place(); -// codeStream.iconst_1(); -// endifLabel.place(); -// } -// } else { // 6596: if (!(a && b)){} - must still place falseLabel -// falseLabel.place(); -// } -// break; -// } -// break; -// case TWIDDLE : -// switch (this.expression.implicitConversion >> 4 /* runtime */ -// ) { -// case T_int : -// // ~int -// this.expression.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) { -// codeStream.iconst_m1(); -// codeStream.ixor(); -// } -// break; -// case T_long : -// this.expression.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) { -// codeStream.ldc2_w(-1L); -// codeStream.lxor(); -// } -// } -// break; -// case MINUS : -// // - -// if (this.constant != NotAConstant) { -// if (valueRequired) { -// switch (this.expression.implicitConversion >> 4){ /* runtime */ -// case T_int : -// codeStream.generateInlinedValue(this.constant.intValue() * -1); -// break; -// case T_float : -// codeStream.generateInlinedValue(this.constant.floatValue() * -1.0f); -// break; -// case T_long : -// codeStream.generateInlinedValue(this.constant.longValue() * -1L); -// break; -// case T_double : -// codeStream.generateInlinedValue(this.constant.doubleValue() * -1.0); -// } -// } -// } else { -// this.expression.generateCode(currentScope, codeStream, valueRequired); -// if (valueRequired) { -// switch (expression.implicitConversion >> 4){ /* runtime type */ -// case T_int : -// codeStream.ineg(); -// break; -// case T_float : -// codeStream.fneg(); -// break; -// case T_long : -// codeStream.lneg(); -// break; -// case T_double : -// codeStream.dneg(); -// } -// } -// } -// break; -// case PLUS : -// this.expression.generateCode(currentScope, codeStream, valueRequired); -// } -// if (valueRequired) { -// codeStream.generateImplicitConversion(this.implicitConversion); -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } -// -// /** -// * Boolean operator code generation -// * Optimized operations are: &&, ||, <, <=, >, >=, &, |, ^ -// */ -// public void generateOptimizedBoolean( -// BlockScope currentScope, -// CodeStream codeStream, -// Label trueLabel, -// Label falseLabel, -// boolean valueRequired) { -// -// if ((this.constant != Constant.NotAConstant) && (this.constant.typeID() == T_boolean)) { -// super.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// valueRequired); -// return; -// } -// if (((this.bits & OperatorMASK) >> OperatorSHIFT) == NOT) { -// this.expression.generateOptimizedBoolean( -// currentScope, -// codeStream, -// falseLabel, -// trueLabel, -// valueRequired); -// } else { -// super.generateOptimizedBoolean( -// currentScope, -// codeStream, -// trueLabel, -// falseLabel, -// valueRequired); -// } -// } - + // public void generateCode( + // BlockScope currentScope, + // CodeStream codeStream, + // boolean valueRequired) { + // + // int pc = codeStream.position; + // Label falseLabel, endifLabel; + // if (this.constant != Constant.NotAConstant) { + // // inlined value + // if (valueRequired) { + // codeStream.generateConstant(this.constant, this.implicitConversion); + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // return; + // } + // switch ((bits & OperatorMASK) >> OperatorSHIFT) { + // case NOT : + // switch (this.expression.implicitConversion >> 4) /* runtime type */ { + // case T_boolean : + // // ! + // // Generate code for the condition + // this.expression.generateOptimizedBoolean( + // currentScope, + // codeStream, + // null, + // (falseLabel = new Label(codeStream)), + // valueRequired); + // if (valueRequired) { + // codeStream.iconst_0(); + // if (falseLabel.hasForwardReferences()) { + // codeStream.goto_(endifLabel = new Label(codeStream)); + // codeStream.decrStackSize(1); + // falseLabel.place(); + // codeStream.iconst_1(); + // endifLabel.place(); + // } + // } else { // 6596: if (!(a && b)){} - must still place falseLabel + // falseLabel.place(); + // } + // break; + // } + // break; + // case TWIDDLE : + // switch (this.expression.implicitConversion >> 4 /* runtime */ + // ) { + // case T_int : + // // ~int + // this.expression.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) { + // codeStream.iconst_m1(); + // codeStream.ixor(); + // } + // break; + // case T_long : + // this.expression.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) { + // codeStream.ldc2_w(-1L); + // codeStream.lxor(); + // } + // } + // break; + // case MINUS : + // // - + // if (this.constant != NotAConstant) { + // if (valueRequired) { + // switch (this.expression.implicitConversion >> 4){ /* runtime */ + // case T_int : + // codeStream.generateInlinedValue(this.constant.intValue() * -1); + // break; + // case T_float : + // codeStream.generateInlinedValue(this.constant.floatValue() * -1.0f); + // break; + // case T_long : + // codeStream.generateInlinedValue(this.constant.longValue() * -1L); + // break; + // case T_double : + // codeStream.generateInlinedValue(this.constant.doubleValue() * -1.0); + // } + // } + // } else { + // this.expression.generateCode(currentScope, codeStream, valueRequired); + // if (valueRequired) { + // switch (expression.implicitConversion >> 4){ /* runtime type */ + // case T_int : + // codeStream.ineg(); + // break; + // case T_float : + // codeStream.fneg(); + // break; + // case T_long : + // codeStream.lneg(); + // break; + // case T_double : + // codeStream.dneg(); + // } + // } + // } + // break; + // case PLUS : + // this.expression.generateCode(currentScope, codeStream, valueRequired); + // } + // if (valueRequired) { + // codeStream.generateImplicitConversion(this.implicitConversion); + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } + // + // /** + // * Boolean operator code generation + // * Optimized operations are: &&, ||, <, <=, >, >=, &, |, ^ + // */ + // public void generateOptimizedBoolean( + // BlockScope currentScope, + // CodeStream codeStream, + // Label trueLabel, + // Label falseLabel, + // boolean valueRequired) { + // + // if ((this.constant != Constant.NotAConstant) && (this.constant.typeID() + // == T_boolean)) { + // super.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // valueRequired); + // return; + // } + // if (((this.bits & OperatorMASK) >> OperatorSHIFT) == NOT) { + // this.expression.generateOptimizedBoolean( + // currentScope, + // codeStream, + // falseLabel, + // trueLabel, + // valueRequired); + // } else { + // super.generateOptimizedBoolean( + // currentScope, + // codeStream, + // trueLabel, + // falseLabel, + // valueRequired); + // } + // } public TypeBinding resolveType(BlockScope scope) { - + TypeBinding expressionType = this.expression.resolveType(scope); if (expressionType == null) { this.constant = NotAConstant; @@ -216,82 +216,83 @@ public class UnaryExpression extends OperatorExpression { int tableId; switch ((bits & OperatorMASK) >> OperatorSHIFT) { - case NOT : - tableId = AND_AND; - break; - case TWIDDLE : - tableId = LEFT_SHIFT; - break; - default : - tableId = MINUS; - } //+ and - cases + case NOT: + tableId = AND_AND; + break; + case TWIDDLE: + tableId = LEFT_SHIFT; + break; + default: + tableId = MINUS; + } // + and - cases // the code is an int - // (cast) left Op (cast) rigth --> result - // 0000 0000 0000 0000 0000 - // <<16 <<12 <<8 <<4 <<0 - int result = ResolveTypeTables[tableId][(expressionId << 4) + expressionId]; + // (cast) left Op (cast) rigth --> result + // 0000 0000 0000 0000 0000 + // <<16 <<12 <<8 <<4 <<0 + int result = ResolveTypeTables[tableId][(expressionId << 4) + + expressionId]; this.expression.implicitConversion = result >>> 12; this.bits |= result & 0xF; switch (result & 0xF) { // only switch on possible result type..... - case T_boolean : - this.resolvedType = BooleanBinding; - break; - case T_byte : - this.resolvedType = ByteBinding; - break; - case T_char : - this.resolvedType = CharBinding; - break; - case T_double : - this.resolvedType = DoubleBinding; - break; - case T_float : - this.resolvedType = FloatBinding; - break; - case T_int : - this.resolvedType = IntBinding; - break; - case T_long : - this.resolvedType = LongBinding; - break; - default : //error........ - this.constant = Constant.NotAConstant; - if (expressionId != T_undefined) - scope.problemReporter().invalidOperator(this, expressionType); - return null; + case T_boolean: + this.resolvedType = BooleanBinding; + break; + case T_byte: + this.resolvedType = ByteBinding; + break; + case T_char: + this.resolvedType = CharBinding; + break; + case T_double: + this.resolvedType = DoubleBinding; + break; + case T_float: + this.resolvedType = FloatBinding; + break; + case T_int: + this.resolvedType = IntBinding; + break; + case T_long: + this.resolvedType = LongBinding; + break; + default: // error........ + this.constant = Constant.NotAConstant; + if (expressionId != T_undefined) + scope.problemReporter().invalidOperator(this, expressionType); + return null; } // compute the constant when valid if (this.expression.constant != Constant.NotAConstant) { - this.constant = - Constant.computeConstantOperation( - this.expression.constant, - expressionId, + this.constant = Constant.computeConstantOperation( + this.expression.constant, expressionId, (bits & OperatorMASK) >> OperatorSHIFT); } else { this.constant = Constant.NotAConstant; if (((bits & OperatorMASK) >> OperatorSHIFT) == NOT) { Constant cst = expression.optimizedBooleanConstant(); - if (cst != Constant.NotAConstant) - this.optimizedBooleanConstant = Constant.fromValue(!cst.booleanValue()); + if (cst != Constant.NotAConstant) + this.optimizedBooleanConstant = Constant.fromValue(!cst + .booleanValue()); } } return this.resolvedType; } - public StringBuffer printExpressionNoParenthesis(int indent, StringBuffer output) { - + + public StringBuffer printExpressionNoParenthesis(int indent, + StringBuffer output) { + output.append(operatorToString()).append(' '); return this.expression.printExpression(0, output); - } + } + public String toStringExpressionNoParenthesis() { - + return operatorToString() + " " + this.expression.toStringExpression(); //$NON-NLS-1$ - } - - public void traverse( - ASTVisitor visitor, - BlockScope blockScope) { - + } + + public void traverse(ASTVisitor visitor, BlockScope blockScope) { + if (visitor.visit(this, blockScope)) { this.expression.traverse(visitor, blockScope); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/WhileStatement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/WhileStatement.java index d1eb28b..d7cbf11 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/WhileStatement.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/WhileStatement.java @@ -19,14 +19,18 @@ import net.sourceforge.phpdt.internal.compiler.impl.Constant; import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; - public class WhileStatement extends Statement { - + public Expression condition; + public Statement action; + private Label breakLabel, continueLabel; + int preCondInitStateIndex = -1; + int condIfTrueInitStateIndex = -1; + int mergedInitStateIndex = -1; public WhileStatement(Expression condition, Statement action, int s, int e) { @@ -37,184 +41,192 @@ public class WhileStatement extends Statement { sourceEnd = e; } - public FlowInfo analyseCode( - BlockScope currentScope, - FlowContext flowContext, - FlowInfo flowInfo) { + public FlowInfo analyseCode(BlockScope currentScope, + FlowContext flowContext, FlowInfo flowInfo) { breakLabel = new Label(); - continueLabel = new Label(); + continueLabel = new Label(); Constant cst = this.condition.constant; - boolean isConditionTrue = cst != NotAConstant && cst.booleanValue() == true; - boolean isConditionFalse = cst != NotAConstant && cst.booleanValue() == false; + boolean isConditionTrue = cst != NotAConstant + && cst.booleanValue() == true; + boolean isConditionFalse = cst != NotAConstant + && cst.booleanValue() == false; cst = this.condition.optimizedBooleanConstant(); - boolean isConditionOptimizedTrue = cst != NotAConstant && cst.booleanValue() == true; - boolean isConditionOptimizedFalse = cst != NotAConstant && cst.booleanValue() == false; - - preCondInitStateIndex = - currentScope.methodScope().recordInitializationStates(flowInfo); + boolean isConditionOptimizedTrue = cst != NotAConstant + && cst.booleanValue() == true; + boolean isConditionOptimizedFalse = cst != NotAConstant + && cst.booleanValue() == false; + + preCondInitStateIndex = currentScope.methodScope() + .recordInitializationStates(flowInfo); LoopingFlowContext condLoopContext; - FlowInfo postCondInfo = - this.condition.analyseCode( - currentScope, - (condLoopContext = - new LoopingFlowContext(flowContext, this, null, null, currentScope)), - flowInfo); + FlowInfo postCondInfo = this.condition.analyseCode(currentScope, + (condLoopContext = new LoopingFlowContext(flowContext, this, + null, null, currentScope)), flowInfo); LoopingFlowContext loopingContext; FlowInfo actionInfo; -// if (action == null -// || (action.isEmptyBlock() && currentScope.environment().options.complianceLevel <= CompilerOptions.JDK1_3)) { -// condLoopContext.complainOnFinalAssignmentsInLoop(currentScope, postCondInfo); -// if (isConditionTrue) { -// return FlowInfo.DEAD_END; -// } else { -// FlowInfo mergedInfo = postCondInfo.initsWhenFalse().unconditionalInits(); -// if (isConditionOptimizedTrue){ -// mergedInfo.setReachMode(FlowInfo.UNREACHABLE); -// } -// mergedInitStateIndex = -// currentScope.methodScope().recordInitializationStates(mergedInfo); -// return mergedInfo; -// } -// } else { - // in case the condition was inlined to false, record the fact that there is no way to reach any - // statement inside the looping action - loopingContext = - new LoopingFlowContext( - flowContext, - this, - breakLabel, - continueLabel, - currentScope); - if (isConditionFalse) { - actionInfo = FlowInfo.DEAD_END; - } else { - actionInfo = postCondInfo.initsWhenTrue().copy(); - if (isConditionOptimizedFalse){ - actionInfo.setReachMode(FlowInfo.UNREACHABLE); - } + // if (action == null + // || (action.isEmptyBlock() && + // currentScope.environment().options.complianceLevel <= + // CompilerOptions.JDK1_3)) { + // condLoopContext.complainOnFinalAssignmentsInLoop(currentScope, + // postCondInfo); + // if (isConditionTrue) { + // return FlowInfo.DEAD_END; + // } else { + // FlowInfo mergedInfo = + // postCondInfo.initsWhenFalse().unconditionalInits(); + // if (isConditionOptimizedTrue){ + // mergedInfo.setReachMode(FlowInfo.UNREACHABLE); + // } + // mergedInitStateIndex = + // currentScope.methodScope().recordInitializationStates(mergedInfo); + // return mergedInfo; + // } + // } else { + // in case the condition was inlined to false, record the fact that + // there is no way to reach any + // statement inside the looping action + loopingContext = new LoopingFlowContext(flowContext, this, breakLabel, + continueLabel, currentScope); + if (isConditionFalse) { + actionInfo = FlowInfo.DEAD_END; + } else { + actionInfo = postCondInfo.initsWhenTrue().copy(); + if (isConditionOptimizedFalse) { + actionInfo.setReachMode(FlowInfo.UNREACHABLE); } + } - // for computing local var attributes - condIfTrueInitStateIndex = - currentScope.methodScope().recordInitializationStates( - postCondInfo.initsWhenTrue()); + // for computing local var attributes + condIfTrueInitStateIndex = currentScope.methodScope() + .recordInitializationStates(postCondInfo.initsWhenTrue()); - if (!actionInfo.complainIfUnreachable(action, currentScope, false)) { - actionInfo = action.analyseCode(currentScope, loopingContext, actionInfo); - } + if (!actionInfo.complainIfUnreachable(action, currentScope, false)) { + actionInfo = action.analyseCode(currentScope, loopingContext, + actionInfo); + } - // code generation can be optimized when no need to continue in the loop - if (!actionInfo.isReachable() && !loopingContext.initsOnContinue.isReachable()) { - continueLabel = null; - } else { - // TODO: (philippe) should simplify in one Loop context - condLoopContext.complainOnFinalAssignmentsInLoop(currentScope, postCondInfo); - loopingContext.complainOnFinalAssignmentsInLoop(currentScope, actionInfo); - } -// } + // code generation can be optimized when no need to continue in the loop + if (!actionInfo.isReachable() + && !loopingContext.initsOnContinue.isReachable()) { + continueLabel = null; + } else { + // TODO: (philippe) should simplify in one Loop context + condLoopContext.complainOnFinalAssignmentsInLoop(currentScope, + postCondInfo); + loopingContext.complainOnFinalAssignmentsInLoop(currentScope, + actionInfo); + } + // } // infinite loop FlowInfo mergedInfo; if (isConditionOptimizedTrue) { - mergedInitStateIndex = - currentScope.methodScope().recordInitializationStates( - mergedInfo = loopingContext.initsOnBreak); + mergedInitStateIndex = currentScope.methodScope() + .recordInitializationStates( + mergedInfo = loopingContext.initsOnBreak); return mergedInfo; } // end of loop: either condition false or break - mergedInfo = - postCondInfo.initsWhenFalse().unconditionalInits().mergedWith( - loopingContext.initsOnBreak); - if (isConditionOptimizedTrue && continueLabel == null){ + mergedInfo = postCondInfo.initsWhenFalse().unconditionalInits() + .mergedWith(loopingContext.initsOnBreak); + if (isConditionOptimizedTrue && continueLabel == null) { mergedInfo.setReachMode(FlowInfo.UNREACHABLE); } - mergedInitStateIndex = - currentScope.methodScope().recordInitializationStates(mergedInfo); + mergedInitStateIndex = currentScope.methodScope() + .recordInitializationStates(mergedInfo); return mergedInfo; } /** * While code generation - * - * @param currentScope net.sourceforge.phpdt.internal.compiler.lookup.BlockScope - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + * + * @param currentScope + * net.sourceforge.phpdt.internal.compiler.lookup.BlockScope + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream */ -// public void generateCode(BlockScope currentScope, CodeStream codeStream) { -// -// if ((bits & IsReachableMASK) == 0) { -// return; -// } -// int pc = codeStream.position; -// breakLabel.codeStream = codeStream; -// -// // generate condition -// if (continueLabel == null) { -// // no need to reverse condition -// if (condition.constant == NotAConstant) { -// condition.generateOptimizedBoolean( -// currentScope, -// codeStream, -// null, -// breakLabel, -// true); -// } -// } else { -// continueLabel.codeStream = codeStream; -// if (!(((condition.constant != NotAConstant) -// && (condition.constant.booleanValue() == true)) -// || (action == null) -// || action.isEmptyBlock())) { -// int jumpPC = codeStream.position; -// codeStream.goto_(continueLabel); -// codeStream.recordPositionsFrom(jumpPC, condition.sourceStart); -// } -// } -// // generate the action -// Label actionLabel; -// (actionLabel = new Label(codeStream)).place(); -// if (action != null) { -// // Required to fix 1PR0XVS: LFRE:WINNT - Compiler: variable table for method appears incorrect -// if (condIfTrueInitStateIndex != -1) { -// // insert all locals initialized inside the condition into the action generated prior to the condition -// codeStream.addDefinitelyAssignedVariables( -// currentScope, -// condIfTrueInitStateIndex); -// } -// action.generateCode(currentScope, codeStream); -// // May loose some local variable initializations : affecting the local variable attributes -// if (preCondInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// preCondInitStateIndex); -// } -// -// } -// // output condition and branch back to the beginning of the repeated action -// if (continueLabel != null) { -// continueLabel.place(); -// condition.generateOptimizedBoolean( -// currentScope, -// codeStream, -// actionLabel, -// null, -// true); -// } -// breakLabel.place(); -// -// // May loose some local variable initializations : affecting the local variable attributes -// if (mergedInitStateIndex != -1) { -// codeStream.removeNotDefinitelyAssignedVariables( -// currentScope, -// mergedInitStateIndex); -// } -// codeStream.recordPositionsFrom(pc, this.sourceStart); -// } - + // public void generateCode(BlockScope currentScope, CodeStream codeStream) + // { + // + // if ((bits & IsReachableMASK) == 0) { + // return; + // } + // int pc = codeStream.position; + // breakLabel.codeStream = codeStream; + // + // // generate condition + // if (continueLabel == null) { + // // no need to reverse condition + // if (condition.constant == NotAConstant) { + // condition.generateOptimizedBoolean( + // currentScope, + // codeStream, + // null, + // breakLabel, + // true); + // } + // } else { + // continueLabel.codeStream = codeStream; + // if (!(((condition.constant != NotAConstant) + // && (condition.constant.booleanValue() == true)) + // || (action == null) + // || action.isEmptyBlock())) { + // int jumpPC = codeStream.position; + // codeStream.goto_(continueLabel); + // codeStream.recordPositionsFrom(jumpPC, condition.sourceStart); + // } + // } + // // generate the action + // Label actionLabel; + // (actionLabel = new Label(codeStream)).place(); + // if (action != null) { + // // Required to fix 1PR0XVS: LFRE:WINNT - Compiler: variable table for + // method appears incorrect + // if (condIfTrueInitStateIndex != -1) { + // // insert all locals initialized inside the condition into the action + // generated prior to the condition + // codeStream.addDefinitelyAssignedVariables( + // currentScope, + // condIfTrueInitStateIndex); + // } + // action.generateCode(currentScope, codeStream); + // // May loose some local variable initializations : affecting the local + // variable attributes + // if (preCondInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // preCondInitStateIndex); + // } + // + // } + // // output condition and branch back to the beginning of the repeated + // action + // if (continueLabel != null) { + // continueLabel.place(); + // condition.generateOptimizedBoolean( + // currentScope, + // codeStream, + // actionLabel, + // null, + // true); + // } + // breakLabel.place(); + // + // // May loose some local variable initializations : affecting the local + // variable attributes + // if (mergedInitStateIndex != -1) { + // codeStream.removeNotDefinitelyAssignedVariables( + // currentScope, + // mergedInitStateIndex); + // } + // codeStream.recordPositionsFrom(pc, this.sourceStart); + // } public void resetStateForCodeGeneration() { if (this.breakLabel != null) { this.breakLabel.resetStateForCodeGeneration(); @@ -223,6 +235,7 @@ public class WhileStatement extends Statement { this.continueLabel.resetStateForCodeGeneration(); } } + public StringBuffer printStatement(int tab, StringBuffer output) { printIndent(tab, output).append("while ("); //$NON-NLS-1$ @@ -230,12 +243,14 @@ public class WhileStatement extends Statement { if (action == null) output.append(';'); else - action.printStatement(tab + 1, output); + action.printStatement(tab + 1, output); return output; } + public void resolve(BlockScope scope) { - TypeBinding type = condition.resolveTypeExpecting(scope, BooleanBinding); + TypeBinding type = condition + .resolveTypeExpecting(scope, BooleanBinding); condition.implicitWidening(type, type); if (action != null) action.resolve(scope); @@ -244,7 +259,7 @@ public class WhileStatement extends Statement { public String toString(int tab) { String s = tabString(tab); - s = s + "while (" + condition.toStringExpression() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ + s = s + "while (" + condition.toStringExpression() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ if (action == null) s = s + " {} ;"; //$NON-NLS-1$ else if (action instanceof Block) @@ -254,9 +269,7 @@ public class WhileStatement extends Statement { return s; } - public void traverse( - ASTVisitor visitor, - BlockScope blockScope) { + public void traverse(ASTVisitor visitor, BlockScope blockScope) { if (visitor.visit(this, blockScope)) { condition.traverse(visitor, blockScope); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/batch/ClasspathDirectory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/batch/ClasspathDirectory.java index 29069bc..ec61df9 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/batch/ClasspathDirectory.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/batch/ClasspathDirectory.java @@ -16,104 +16,140 @@ import java.util.Hashtable; import net.sourceforge.phpdt.internal.compiler.env.NameEnvironmentAnswer; import net.sourceforge.phpdt.internal.compiler.util.SuffixConstants; -public class ClasspathDirectory implements FileSystem.Classpath, SuffixConstants { - -String path; -Hashtable directoryCache; -String[] missingPackageHolder = new String[1]; -String encoding; -public int mode; // ability to only consider one kind of files (source vs. binaries), by default use both - -public static final int SOURCE = 1; -public static final int BINARY = 2; - -ClasspathDirectory(File directory, String encoding, int mode) { - this.mode = mode; - this.path = directory.getAbsolutePath(); - if (!this.path.endsWith(File.separator)) - this.path += File.separator; - this.directoryCache = new Hashtable(11); - this.encoding = encoding; -} +public class ClasspathDirectory implements FileSystem.Classpath, + SuffixConstants { -ClasspathDirectory(File directory, String encoding) { - this(directory, encoding, SOURCE | BINARY); // by default consider both sources and binaries -} + String path; + + Hashtable directoryCache; + + String[] missingPackageHolder = new String[1]; + + String encoding; -String[] directoryList(String qualifiedPackageName) { - String[] dirList = (String[]) this.directoryCache.get(qualifiedPackageName); - if (dirList == this.missingPackageHolder) return null; // package exists in another classpath directory or jar - if (dirList != null) return dirList; - - File dir = new File(this.path + qualifiedPackageName); - notFound : if (dir != null && dir.isDirectory()) { - // must protect against a case insensitive File call - // walk the qualifiedPackageName backwards looking for an uppercase character before the '/' - int index = qualifiedPackageName.length(); - int last = qualifiedPackageName.lastIndexOf(File.separatorChar); - while (--index > last && !Character.isUpperCase(qualifiedPackageName.charAt(index))){/*empty*/} - if (index > last) { - if (last == -1) { - if (!doesFileExist(qualifiedPackageName, "")) //$NON-NLS-1$ - break notFound; - } else { - String packageName = qualifiedPackageName.substring(last + 1); - String parentPackage = qualifiedPackageName.substring(0, last); - if (!doesFileExist(packageName, parentPackage)) - break notFound; + public int mode; // ability to only consider one kind of files (source + // vs. binaries), by default use both + + public static final int SOURCE = 1; + + public static final int BINARY = 2; + + ClasspathDirectory(File directory, String encoding, int mode) { + this.mode = mode; + this.path = directory.getAbsolutePath(); + if (!this.path.endsWith(File.separator)) + this.path += File.separator; + this.directoryCache = new Hashtable(11); + this.encoding = encoding; + } + + ClasspathDirectory(File directory, String encoding) { + this(directory, encoding, SOURCE | BINARY); // by default consider both + // sources and binaries + } + + String[] directoryList(String qualifiedPackageName) { + String[] dirList = (String[]) this.directoryCache + .get(qualifiedPackageName); + if (dirList == this.missingPackageHolder) + return null; // package exists in another classpath directory or + // jar + if (dirList != null) + return dirList; + + File dir = new File(this.path + qualifiedPackageName); + notFound: if (dir != null && dir.isDirectory()) { + // must protect against a case insensitive File call + // walk the qualifiedPackageName backwards looking for an uppercase + // character before the '/' + int index = qualifiedPackageName.length(); + int last = qualifiedPackageName.lastIndexOf(File.separatorChar); + while (--index > last + && !Character.isUpperCase(qualifiedPackageName + .charAt(index))) {/* empty */ } + if (index > last) { + if (last == -1) { + if (!doesFileExist(qualifiedPackageName, "")) //$NON-NLS-1$ + break notFound; + } else { + String packageName = qualifiedPackageName + .substring(last + 1); + String parentPackage = qualifiedPackageName.substring(0, + last); + if (!doesFileExist(packageName, parentPackage)) + break notFound; + } + } + if ((dirList = dir.list()) == null) + dirList = new String[0]; + this.directoryCache.put(qualifiedPackageName, dirList); + return dirList; } - if ((dirList = dir.list()) == null) - dirList = new String[0]; - this.directoryCache.put(qualifiedPackageName, dirList); - return dirList; + this.directoryCache + .put(qualifiedPackageName, this.missingPackageHolder); + return null; } - this.directoryCache.put(qualifiedPackageName, this.missingPackageHolder); - return null; -} -boolean doesFileExist(String fileName, String qualifiedPackageName) { - String[] dirList = directoryList(qualifiedPackageName); - if (dirList == null) return false; // most common case - - for (int i = dirList.length; --i >= 0;) - if (fileName.equals(dirList[i])) - return true; - return false; -} -public NameEnvironmentAnswer findClass(char[] typeName, String qualifiedPackageName, String qualifiedBinaryFileName) { - if (!isPackage(qualifiedPackageName)) return null; // most common case - - String fileName = new String(typeName); -// boolean binaryExists = ((this.mode & BINARY) != 0) && doesFileExist(fileName + SUFFIX_STRING_class, qualifiedPackageName); - boolean sourceExists = ((this.mode & SOURCE) != 0) && doesFileExist(fileName + SUFFIX_STRING_php, qualifiedPackageName); - if (sourceExists) { - String fullSourcePath = this.path + qualifiedBinaryFileName.substring(0, qualifiedBinaryFileName.length() - 6) + SUFFIX_STRING_php; -// if (!binaryExists) - return new NameEnvironmentAnswer(new CompilationUnit(null, fullSourcePath, this.encoding)); - -// String fullBinaryPath = this.path + qualifiedBinaryFileName; -// long binaryModified = new File(fullBinaryPath).lastModified(); -// long sourceModified = new File(fullSourcePath).lastModified(); -// if (sourceModified > binaryModified) -// return new NameEnvironmentAnswer(new CompilationUnit(null, fullSourcePath, this.encoding)); + + boolean doesFileExist(String fileName, String qualifiedPackageName) { + String[] dirList = directoryList(qualifiedPackageName); + if (dirList == null) + return false; // most common case + + for (int i = dirList.length; --i >= 0;) + if (fileName.equals(dirList[i])) + return true; + return false; + } + + public NameEnvironmentAnswer findClass(char[] typeName, + String qualifiedPackageName, String qualifiedBinaryFileName) { + if (!isPackage(qualifiedPackageName)) + return null; // most common case + + String fileName = new String(typeName); + // boolean binaryExists = ((this.mode & BINARY) != 0) && + // doesFileExist(fileName + SUFFIX_STRING_class, qualifiedPackageName); + boolean sourceExists = ((this.mode & SOURCE) != 0) + && doesFileExist(fileName + SUFFIX_STRING_php, + qualifiedPackageName); + if (sourceExists) { + String fullSourcePath = this.path + + qualifiedBinaryFileName.substring(0, + qualifiedBinaryFileName.length() - 6) + + SUFFIX_STRING_php; + // if (!binaryExists) + return new NameEnvironmentAnswer(new CompilationUnit(null, + fullSourcePath, this.encoding)); + + // String fullBinaryPath = this.path + qualifiedBinaryFileName; + // long binaryModified = new File(fullBinaryPath).lastModified(); + // long sourceModified = new File(fullSourcePath).lastModified(); + // if (sourceModified > binaryModified) + // return new NameEnvironmentAnswer(new CompilationUnit(null, + // fullSourcePath, this.encoding)); + } + // if (binaryExists) { + // try { + // ClassFileReader reader = ClassFileReader.read(this.path + + // qualifiedBinaryFileName); + // if (reader != null) return new NameEnvironmentAnswer(reader); + // } catch (Exception e) { + // // treat as if file is missing + // } + // } + return null; + } + + public boolean isPackage(String qualifiedPackageName) { + return directoryList(qualifiedPackageName) != null; + } + + public void reset() { + this.directoryCache = new Hashtable(11); + } + + public String toString() { + return "ClasspathDirectory " + this.path; //$NON-NLS-1$ } -// if (binaryExists) { -// try { -// ClassFileReader reader = ClassFileReader.read(this.path + qualifiedBinaryFileName); -// if (reader != null) return new NameEnvironmentAnswer(reader); -// } catch (Exception e) { -// // treat as if file is missing -// } -// } - return null; -} -public boolean isPackage(String qualifiedPackageName) { - return directoryList(qualifiedPackageName) != null; -} -public void reset() { - this.directoryCache = new Hashtable(11); -} -public String toString() { - return "ClasspathDirectory " + this.path; //$NON-NLS-1$ -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/batch/CompilationUnit.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/batch/CompilationUnit.java index c944911..98c9cce 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/batch/CompilationUnit.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/batch/CompilationUnit.java @@ -17,70 +17,71 @@ import net.sourceforge.phpdt.internal.compiler.util.Util; import org.eclipse.core.resources.IResource; public class CompilationUnit implements ICompilationUnit { - public char[] contents; - - public char[] fileName; - - public char[] mainTypeName; - - String encoding; - - public CompilationUnit(char[] contents, String fileName, String encoding) { - this.contents = contents; - if (File.separator.equals("/")) { //$NON-NLS-1$ - if (fileName.indexOf("\\") != -1) { //$NON-NLS-1$ - fileName = fileName.replace('\\', File.separatorChar); - } - } else { - // the file separator is \ - if (fileName.indexOf('/') != -1) { - fileName = fileName.replace('/', File.separatorChar); - } - } - this.fileName = fileName.toCharArray(); - - int start = fileName.lastIndexOf("/") + 1; //$NON-NLS-1$ - if (start == 0 || start < fileName.lastIndexOf("\\")) //$NON-NLS-1$ - start = fileName.lastIndexOf("\\") + 1; //$NON-NLS-1$ - - int end = fileName.lastIndexOf("."); //$NON-NLS-1$ - if (end == -1) - end = fileName.length(); - - this.mainTypeName = fileName.substring(start, end).toCharArray(); - this.encoding = encoding; - } - - public char[] getContents() { - if (this.contents != null) - return this.contents; // answer the cached source - - // otherwise retrieve it - try { - return Util.getFileCharContent(new File(new String(this.fileName)), this.encoding); - } catch (IOException e) { - // assume no content then - } - return CharOperation.NO_CHAR; - } - - public char[] getFileName() { - return this.fileName; - } - - public char[] getMainTypeName() { - return this.mainTypeName; - } - - public char[][] getPackageName() { - return null; - } - - public String toString() { - return "CompilationUnit[" + new String(this.fileName) + "]"; //$NON-NLS-2$ //$NON-NLS-1$ - } - - public IResource getResource() { - return null; - } + public char[] contents; + + public char[] fileName; + + public char[] mainTypeName; + + String encoding; + + public CompilationUnit(char[] contents, String fileName, String encoding) { + this.contents = contents; + if (File.separator.equals("/")) { //$NON-NLS-1$ + if (fileName.indexOf("\\") != -1) { //$NON-NLS-1$ + fileName = fileName.replace('\\', File.separatorChar); + } + } else { + // the file separator is \ + if (fileName.indexOf('/') != -1) { + fileName = fileName.replace('/', File.separatorChar); + } + } + this.fileName = fileName.toCharArray(); + + int start = fileName.lastIndexOf("/") + 1; //$NON-NLS-1$ + if (start == 0 || start < fileName.lastIndexOf("\\")) //$NON-NLS-1$ + start = fileName.lastIndexOf("\\") + 1; //$NON-NLS-1$ + + int end = fileName.lastIndexOf("."); //$NON-NLS-1$ + if (end == -1) + end = fileName.length(); + + this.mainTypeName = fileName.substring(start, end).toCharArray(); + this.encoding = encoding; + } + + public char[] getContents() { + if (this.contents != null) + return this.contents; // answer the cached source + + // otherwise retrieve it + try { + return Util.getFileCharContent(new File(new String(this.fileName)), + this.encoding); + } catch (IOException e) { + // assume no content then + } + return CharOperation.NO_CHAR; + } + + public char[] getFileName() { + return this.fileName; + } + + public char[] getMainTypeName() { + return this.mainTypeName; + } + + public char[][] getPackageName() { + return null; + } + + public String toString() { + return "CompilationUnit[" + new String(this.fileName) + "]"; //$NON-NLS-2$ //$NON-NLS-1$ + } + + public IResource getResource() { + return null; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/batch/FileFinder.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/batch/FileFinder.java index 61cdefe..aa8ab54 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/batch/FileFinder.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/batch/FileFinder.java @@ -14,35 +14,48 @@ import java.io.File; public class FileFinder { private static final int INITIAL_SIZE = 10; + public String[] resultFiles = new String[INITIAL_SIZE]; + public int count = 0; -public void find(File f, String pattern, boolean verbose) { - if (verbose) { -// System.out.println(Main.bind("scanning.start",f.getAbsolutePath())); //$NON-NLS-1$ + + public void find(File f, String pattern, boolean verbose) { + if (verbose) { + // System.out.println(Main.bind("scanning.start",f.getAbsolutePath())); + // //$NON-NLS-1$ + } + find0(f, pattern, verbose); + System.arraycopy(this.resultFiles, 0, + (this.resultFiles = new String[this.count]), 0, this.count); } - find0(f, pattern, verbose); - System.arraycopy(this.resultFiles, 0, (this.resultFiles = new String[this.count]), 0, this.count); -} -public void find0(File f, String pattern, boolean verbose) { - if (f.isDirectory()) { - String[] files = f.list(); - if (files == null) return; - for (int i = 0, max = files.length; i < max; i++) { - File current = new File(f, files[i]); - if (current.isDirectory()) { - find0(current, pattern, verbose); - } else { - if (current.getName().toUpperCase().endsWith(pattern)) { - int length; - if ((length = this.resultFiles.length) == this.count) { - System.arraycopy(this.resultFiles, 0, (this.resultFiles = new String[length * 2]), 0, length); + + public void find0(File f, String pattern, boolean verbose) { + if (f.isDirectory()) { + String[] files = f.list(); + if (files == null) + return; + for (int i = 0, max = files.length; i < max; i++) { + File current = new File(f, files[i]); + if (current.isDirectory()) { + find0(current, pattern, verbose); + } else { + if (current.getName().toUpperCase().endsWith(pattern)) { + int length; + if ((length = this.resultFiles.length) == this.count) { + System + .arraycopy( + this.resultFiles, + 0, + (this.resultFiles = new String[length * 2]), + 0, length); + } + this.resultFiles[this.count++] = current + .getAbsolutePath(); + if (verbose && (this.count % 100) == 0) + System.out.print('.'); } - this.resultFiles[this.count++] = current.getAbsolutePath(); - if (verbose && (this.count % 100) == 0) - System.out.print('.'); } } } } } -} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/batch/FileSystem.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/batch/FileSystem.java index a1f60ab..4ffa4a7 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/batch/FileSystem.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/batch/FileSystem.java @@ -19,155 +19,184 @@ import net.sourceforge.phpdt.internal.compiler.util.SuffixConstants; public class FileSystem implements INameEnvironment, SuffixConstants { Classpath[] classpaths; + String[] knownFileNames; interface Classpath { - NameEnvironmentAnswer findClass(char[] typeName, String qualifiedPackageName, String qualifiedBinaryFileName); - boolean isPackage(String qualifiedPackageName); + NameEnvironmentAnswer findClass(char[] typeName, + String qualifiedPackageName, String qualifiedBinaryFileName); + + boolean isPackage(String qualifiedPackageName); + /** - * This method resets the environment. The resulting state is equivalent to - * a new name environment without creating a new object. + * This method resets the environment. The resulting state is equivalent + * to a new name environment without creating a new object. */ void reset(); } -/* - classPathNames is a collection is Strings representing the full path of each class path - initialFileNames is a collection is Strings, the trailing '.java' will be removed if its not already. -*/ -public FileSystem(String[] classpathNames, String[] initialFileNames, String encoding) { - this(classpathNames, initialFileNames, encoding, null); -} -public FileSystem(String[] classpathNames, String[] initialFileNames, String encoding, int[] classpathDirectoryModes) { - int classpathSize = classpathNames.length; - this.classpaths = new Classpath[classpathSize]; - String[] pathNames = new String[classpathSize]; - int problemsOccured = 0; - for (int i = 0; i < classpathSize; i++) { -// try { + /* + * classPathNames is a collection is Strings representing the full path of + * each class path initialFileNames is a collection is Strings, the trailing + * '.java' will be removed if its not already. + */ + + public FileSystem(String[] classpathNames, String[] initialFileNames, + String encoding) { + this(classpathNames, initialFileNames, encoding, null); + } + + public FileSystem(String[] classpathNames, String[] initialFileNames, + String encoding, int[] classpathDirectoryModes) { + int classpathSize = classpathNames.length; + this.classpaths = new Classpath[classpathSize]; + String[] pathNames = new String[classpathSize]; + int problemsOccured = 0; + for (int i = 0; i < classpathSize; i++) { + // try { File file = new File(convertPathSeparators(classpathNames[i])); if (file.isDirectory()) { if (file.exists()) { - if (classpathDirectoryModes == null){ - this.classpaths[i] = new ClasspathDirectory(file, encoding); + if (classpathDirectoryModes == null) { + this.classpaths[i] = new ClasspathDirectory(file, + encoding); } else { - this.classpaths[i] = new ClasspathDirectory(file, encoding, classpathDirectoryModes[i]); + this.classpaths[i] = new ClasspathDirectory(file, + encoding, classpathDirectoryModes[i]); } pathNames[i] = ((ClasspathDirectory) this.classpaths[i]).path; } } else { String lowercaseClasspathName = classpathNames[i].toLowerCase(); -// if (lowercaseClasspathName.endsWith(SUFFIX_STRING_jar) -// || lowercaseClasspathName.endsWith(SUFFIX_STRING_zip)) { -// this.classpaths[i] = this.getClasspathJar(file); // will throw an IOException if file does not exist -// pathNames[i] = classpathNames[i].substring(0, classpathNames[i].lastIndexOf('.')); -// } + // if (lowercaseClasspathName.endsWith(SUFFIX_STRING_jar) + // || lowercaseClasspathName.endsWith(SUFFIX_STRING_zip)) { + // this.classpaths[i] = this.getClasspathJar(file); // will + // throw an IOException if file does not exist + // pathNames[i] = classpathNames[i].substring(0, + // classpathNames[i].lastIndexOf('.')); + // } } -// } catch (IOException e) { -// this.classpaths[i] = null; -// } - if (this.classpaths[i] == null) - problemsOccured++; + // } catch (IOException e) { + // this.classpaths[i] = null; + // } + if (this.classpaths[i] == null) + problemsOccured++; + } + if (problemsOccured > 0) { + Classpath[] newPaths = new Classpath[classpathSize + - problemsOccured]; + String[] newNames = new String[classpathSize - problemsOccured]; + for (int i = 0, current = 0; i < classpathSize; i++) + if (this.classpaths[i] != null) { + newPaths[current] = this.classpaths[i]; + newNames[current++] = pathNames[i]; + } + classpathSize = newPaths.length; + this.classpaths = newPaths; + pathNames = newNames; + } + + this.knownFileNames = new String[initialFileNames.length]; + for (int i = initialFileNames.length; --i >= 0;) { + String fileName = initialFileNames[i]; + String matchingPathName = null; + if (fileName.lastIndexOf(".") != -1) //$NON-NLS-1$ + fileName = fileName.substring(0, fileName.lastIndexOf('.')); // remove + // trailing + // ".java" + + fileName = convertPathSeparators(fileName); + for (int j = 0; j < classpathSize; j++) + if (fileName.startsWith(pathNames[j])) + matchingPathName = pathNames[j]; + if (matchingPathName == null) + this.knownFileNames[i] = fileName; // leave as is... + else + this.knownFileNames[i] = fileName.substring(matchingPathName + .length()); + } } - if (problemsOccured > 0) { - Classpath[] newPaths = new Classpath[classpathSize - problemsOccured]; - String[] newNames = new String[classpathSize - problemsOccured]; - for (int i = 0, current = 0; i < classpathSize; i++) - if (this.classpaths[i] != null) { - newPaths[current] = this.classpaths[i]; - newNames[current++] = pathNames[i]; - } - classpathSize = newPaths.length; - this.classpaths = newPaths; - pathNames = newNames; + + public void cleanup() { + for (int i = 0, max = this.classpaths.length; i < max; i++) + this.classpaths[i].reset(); } - this.knownFileNames = new String[initialFileNames.length]; - for (int i = initialFileNames.length; --i >= 0;) { - String fileName = initialFileNames[i]; - String matchingPathName = null; - if (fileName.lastIndexOf(".") != -1) //$NON-NLS-1$ - fileName = fileName.substring(0, fileName.lastIndexOf('.')); // remove trailing ".java" - - fileName = convertPathSeparators(fileName); - for (int j = 0; j < classpathSize; j++) - if (fileName.startsWith(pathNames[j])) - matchingPathName = pathNames[j]; - if (matchingPathName == null) - this.knownFileNames[i] = fileName; // leave as is... - else - this.knownFileNames[i] = fileName.substring(matchingPathName.length()); + private String convertPathSeparators(String path) { + return File.separatorChar == '/' ? path.replace('\\', '/') : path + .replace('/', '\\'); + } + + // private NameEnvironmentAnswer findClass(String qualifiedTypeName, char[] + // typeName){ + // for (int i = 0, length = this.knownFileNames.length; i < length; i++) + // if (qualifiedTypeName.equals(this.knownFileNames[i])) + // return null; // looking for a file which we know was provided at the + // beginning of the compilation + // + // String qualifiedBinaryFileName = qualifiedTypeName + SUFFIX_STRING_class; + // String qualifiedPackageName = + // qualifiedTypeName.length() == typeName.length + // ? "" //$NON-NLS-1$ + // : qualifiedBinaryFileName.substring(0, qualifiedTypeName.length() - + // typeName.length - 1); + // String qp2 = File.separatorChar == '/' ? qualifiedPackageName : + // qualifiedPackageName.replace('/', File.separatorChar); + // if (qualifiedPackageName == qp2) { + // for (int i = 0, length = this.classpaths.length; i < length; i++) { + // NameEnvironmentAnswer answer = this.classpaths[i].findClass(typeName, + // qualifiedPackageName, qualifiedBinaryFileName); + // if (answer != null) return answer; + // } + // } else { + // String qb2 = qualifiedBinaryFileName.replace('/', File.separatorChar); + // for (int i = 0, length = this.classpaths.length; i < length; i++) { + // Classpath p = this.classpaths[i]; + // NameEnvironmentAnswer answer = (p instanceof ClasspathJar) + // ? p.findClass(typeName, qualifiedPackageName, qualifiedBinaryFileName) + // : p.findClass(typeName, qp2, qb2); + // if (answer != null) return answer; + // } + // } + // return null; + // } + public NameEnvironmentAnswer findType(char[][] compoundName) { + // if (compoundName != null) + // return findClass( + // new String(CharOperation.concatWith(compoundName, '/')), + // compoundName[compoundName.length - 1]); + return null; + } + + public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) { + // if (typeName != null) + // return findClass( + // new String(CharOperation.concatWith(packageName, typeName, '/')), + // typeName); + return null; + } + + // public ClasspathJar getClasspathJar(File file) throws IOException { + // return new ClasspathJar(new ZipFile(file), true); + // } + public boolean isPackage(char[][] compoundName, char[] packageName) { + String qualifiedPackageName = new String(CharOperation.concatWith( + compoundName, packageName, '/')); + String qp2 = File.separatorChar == '/' ? qualifiedPackageName + : qualifiedPackageName.replace('/', File.separatorChar); + if (qualifiedPackageName == qp2) { + for (int i = 0, length = this.classpaths.length; i < length; i++) + if (this.classpaths[i].isPackage(qualifiedPackageName)) + return true; + } + // else { + // for (int i = 0, length = this.classpaths.length; i < length; i++) { + // Classpath p = this.classpaths[i]; + // if ((p instanceof ClasspathJar) ? p.isPackage(qualifiedPackageName) : + // p.isPackage(qp2)) + // return true; + // } + // } + return false; } -} -public void cleanup() { - for (int i = 0, max = this.classpaths.length; i < max; i++) - this.classpaths[i].reset(); -} -private String convertPathSeparators(String path) { - return File.separatorChar == '/' - ? path.replace('\\', '/') - : path.replace('/', '\\'); -} -//private NameEnvironmentAnswer findClass(String qualifiedTypeName, char[] typeName){ -// for (int i = 0, length = this.knownFileNames.length; i < length; i++) -// if (qualifiedTypeName.equals(this.knownFileNames[i])) -// return null; // looking for a file which we know was provided at the beginning of the compilation -// -// String qualifiedBinaryFileName = qualifiedTypeName + SUFFIX_STRING_class; -// String qualifiedPackageName = -// qualifiedTypeName.length() == typeName.length -// ? "" //$NON-NLS-1$ -// : qualifiedBinaryFileName.substring(0, qualifiedTypeName.length() - typeName.length - 1); -// String qp2 = File.separatorChar == '/' ? qualifiedPackageName : qualifiedPackageName.replace('/', File.separatorChar); -// if (qualifiedPackageName == qp2) { -// for (int i = 0, length = this.classpaths.length; i < length; i++) { -// NameEnvironmentAnswer answer = this.classpaths[i].findClass(typeName, qualifiedPackageName, qualifiedBinaryFileName); -// if (answer != null) return answer; -// } -// } else { -// String qb2 = qualifiedBinaryFileName.replace('/', File.separatorChar); -// for (int i = 0, length = this.classpaths.length; i < length; i++) { -// Classpath p = this.classpaths[i]; -// NameEnvironmentAnswer answer = (p instanceof ClasspathJar) -// ? p.findClass(typeName, qualifiedPackageName, qualifiedBinaryFileName) -// : p.findClass(typeName, qp2, qb2); -// if (answer != null) return answer; -// } -// } -// return null; -//} -public NameEnvironmentAnswer findType(char[][] compoundName) { -// if (compoundName != null) -// return findClass( -// new String(CharOperation.concatWith(compoundName, '/')), -// compoundName[compoundName.length - 1]); - return null; -} -public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) { -// if (typeName != null) -// return findClass( -// new String(CharOperation.concatWith(packageName, typeName, '/')), -// typeName); - return null; -} -//public ClasspathJar getClasspathJar(File file) throws IOException { -// return new ClasspathJar(new ZipFile(file), true); -//} -public boolean isPackage(char[][] compoundName, char[] packageName) { - String qualifiedPackageName = new String(CharOperation.concatWith(compoundName, packageName, '/')); - String qp2 = File.separatorChar == '/' ? qualifiedPackageName : qualifiedPackageName.replace('/', File.separatorChar); - if (qualifiedPackageName == qp2) { - for (int i = 0, length = this.classpaths.length; i < length; i++) - if (this.classpaths[i].isPackage(qualifiedPackageName)) - return true; - } -// else { -// for (int i = 0, length = this.classpaths.length; i < length; i++) { -// Classpath p = this.classpaths[i]; -// if ((p instanceof ClasspathJar) ? p.isPackage(qualifiedPackageName) : p.isPackage(qp2)) -// return true; -// } -// } - return false; -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/codegen/CaseLabel.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/codegen/CaseLabel.java index 18b80c7..c5d2456 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/codegen/CaseLabel.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/codegen/CaseLabel.java @@ -12,70 +12,73 @@ package net.sourceforge.phpdt.internal.compiler.codegen; public class CaseLabel extends Label { public int instructionPosition = POS_NOT_SET; + public int backwardsBranch = POS_NOT_SET; -/** - * CaseLabel constructor comment. - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream - */ -//public CaseLabel(CodeStream codeStream) { -// super(codeStream); -//} -/* -* Put down a refernece to the array at the location in the codestream. -*/ -//void branch() { -// if (position == POS_NOT_SET) { -// addForwardReference(codeStream.position); -// // Leave 4 bytes free to generate the jump offset afterwards -// codeStream.position += 4; -// codeStream.classFileOffset += 4; -// } else { //Position is set. Write it! -// codeStream.writeSignedWord(position - codeStream.position + 1); -// } -//} -///* -//* Put down a refernece to the array at the location in the codestream. -//*/ -//void branchWide() { -// if (position == POS_NOT_SET) { -// addForwardReference(codeStream.position); -// // Leave 4 bytes free to generate the jump offset afterwards -// codeStream.position += 4; -// } else { //Position is set. Write it! -// codeStream.writeSignedWord(position - codeStream.position + 1); -// } -//} -//public boolean isStandardLabel(){ -// return false; -//} -///* -//* Put down a reference to the array at the location in the codestream. -//*/ -//public void place() { -// position = codeStream.position; -// if (instructionPosition == POS_NOT_SET) -// backwardsBranch = position; -// else { -// int offset = position - instructionPosition; -// for (int i = 0; i < forwardReferenceCount; i++) { -// codeStream.writeSignedWord(forwardReferences[i], offset); -// } -// // add the label int the codeStream labels collection -// codeStream.addLabel(this); -// } -//} -/* -* Put down a refernece to the array at the location in the codestream. -*/ -//void placeInstruction() { -// if (instructionPosition == POS_NOT_SET) { -// instructionPosition = codeStream.position; -// if (backwardsBranch != POS_NOT_SET) { -// int offset = backwardsBranch - instructionPosition; -// for (int i = 0; i < forwardReferenceCount; i++) -// codeStream.writeSignedWord(forwardReferences[i], offset); -// backwardsBranch = POS_NOT_SET; -// } -// } -//} + /** + * CaseLabel constructor comment. + * + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + */ + // public CaseLabel(CodeStream codeStream) { + // super(codeStream); + // } + /* + * Put down a refernece to the array at the location in the codestream. + */ + // void branch() { + // if (position == POS_NOT_SET) { + // addForwardReference(codeStream.position); + // // Leave 4 bytes free to generate the jump offset afterwards + // codeStream.position += 4; + // codeStream.classFileOffset += 4; + // } else { //Position is set. Write it! + // codeStream.writeSignedWord(position - codeStream.position + 1); + // } + // } + // /* + // * Put down a refernece to the array at the location in the codestream. + // */ + // void branchWide() { + // if (position == POS_NOT_SET) { + // addForwardReference(codeStream.position); + // // Leave 4 bytes free to generate the jump offset afterwards + // codeStream.position += 4; + // } else { //Position is set. Write it! + // codeStream.writeSignedWord(position - codeStream.position + 1); + // } + // } + // public boolean isStandardLabel(){ + // return false; + // } + // /* + // * Put down a reference to the array at the location in the codestream. + // */ + // public void place() { + // position = codeStream.position; + // if (instructionPosition == POS_NOT_SET) + // backwardsBranch = position; + // else { + // int offset = position - instructionPosition; + // for (int i = 0; i < forwardReferenceCount; i++) { + // codeStream.writeSignedWord(forwardReferences[i], offset); + // } + // // add the label int the codeStream labels collection + // codeStream.addLabel(this); + // } + // } + /* + * Put down a refernece to the array at the location in the codestream. + */ + // void placeInstruction() { + // if (instructionPosition == POS_NOT_SET) { + // instructionPosition = codeStream.position; + // if (backwardsBranch != POS_NOT_SET) { + // int offset = backwardsBranch - instructionPosition; + // for (int i = 0; i < forwardReferenceCount; i++) + // codeStream.writeSignedWord(forwardReferences[i], offset); + // backwardsBranch = POS_NOT_SET; + // } + // } + // } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/codegen/Label.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/codegen/Label.java index f7bdd9a..21134e1 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/codegen/Label.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/codegen/Label.java @@ -10,242 +10,272 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.compiler.codegen; - /** * This type is a port of smalltalks JavaLabel */ public class Label { -// public CodeStream codeStream; + // public CodeStream codeStream; final static int POS_NOT_SET = -1; - public int position = POS_NOT_SET; // position=POS_NOT_SET Then it's pos is not set. - public int[] forwardReferences = new int[10]; // Add an overflow check here. + + public int position = POS_NOT_SET; // position=POS_NOT_SET Then it's pos is + // not set. + + public int[] forwardReferences = new int[10]; // Add an overflow check + // here. + public int forwardReferenceCount = 0; + private boolean isWide = false; -public Label() { -} -/** - * @param codeStream net.sourceforge.phpdt.internal.compiler.codegen.CodeStream - */ -//public Label(CodeStream codeStream) { -// this.codeStream = codeStream; -//} -/** - * Add a forward refrence for the array. - */ -void addForwardReference(int iPos) { - int length; - if (forwardReferenceCount >= (length = forwardReferences.length)) - System.arraycopy(forwardReferences, 0, (forwardReferences = new int[2*length]), 0, length); - forwardReferences[forwardReferenceCount++] = iPos; -} -/** - * Add a forward refrence for the array. - */ -public void appendForwardReferencesFrom(Label otherLabel) { - int otherCount = otherLabel.forwardReferenceCount; - if (otherCount == 0) return; - int length = forwardReferences.length; - int neededSpace = otherCount + forwardReferenceCount; - if (neededSpace >= length){ - System.arraycopy(forwardReferences, 0, (forwardReferences = new int[neededSpace]), 0, forwardReferenceCount); + + public Label() { } - // append other forward references at the end, so they will get updated as well - System.arraycopy(otherLabel.forwardReferences, 0, forwardReferences, forwardReferenceCount, otherCount); - forwardReferenceCount = neededSpace; -} -/* -* Put down a refernece to the array at the location in the codestream. -*/ -//void branch() { -// if (position == POS_NOT_SET) { -// addForwardReference(codeStream.position); -// // Leave two bytes free to generate the jump afterwards -// codeStream.position += 2; -// codeStream.classFileOffset += 2; -// } else { -// /* -// * Position is set. Write it if it is not a wide branch. -// */ -// int offset = position - codeStream.position + 1; -// if (Math.abs(offset) > 0x7FFF && !this.codeStream.wideMode) { -// throw new AbortMethod(CodeStream.RESTART_IN_WIDE_MODE); -// } -// codeStream.writeSignedShort((short) offset); -// } -//} -/* -* No support for wide branches yet -*/ -//void branchWide() { -// if (position == POS_NOT_SET) { -// addForwardReference(codeStream.position); -// // Leave 4 bytes free to generate the jump offset afterwards -// isWide = true; -// codeStream.position += 4; -// codeStream.classFileOffset += 4; -// } else { //Position is set. Write it! -// codeStream.writeSignedWord(position - codeStream.position + 1); -// } -//} -/** - * @return boolean - */ -public boolean hasForwardReferences() { - return forwardReferenceCount != 0; -} -/* - * Some placed labels might be branching to a goto bytecode which we can optimize better. - */ -//public void inlineForwardReferencesFromLabelsTargeting(int gotoLocation) { -///* -// Code required to optimized unreachable gotos. -// public boolean isBranchTarget(int location) { -// Label[] labels = codeStream.labels; -// for (int i = codeStream.countLabels - 1; i >= 0; i--){ -// Label label = labels[i]; -// if ((label.position == location) && label.isStandardLabel()){ -// return true; -// } -// } -// return false; -// } -// */ -// -// Label[] labels = codeStream.labels; -// for (int i = codeStream.countLabels - 1; i >= 0; i--){ -// Label label = labels[i]; -// if ((label.position == gotoLocation) && label.isStandardLabel()){ -// this.appendForwardReferencesFrom(label); -// /* -// Code required to optimized unreachable gotos. -// label.position = POS_NOT_SET; -// */ -// } else { -// break; // same target labels should be contiguous -// } -// } -//} -public boolean isStandardLabel(){ - return true; -} -/* -* Place the label. If we have forward references resolve them. -*/ -//public void place() { // Currently lacking wide support. -// if (position == POS_NOT_SET) { -// position = codeStream.position; -// codeStream.addLabel(this); -// int oldPosition = position; -// boolean optimizedBranch = false; -// // TURNED OFF since fail on 1F4IRD9 -// if (forwardReferenceCount != 0) { -// if (optimizedBranch = (forwardReferences[forwardReferenceCount - 1] + 2 == position) && (codeStream.bCodeStream[codeStream.classFileOffset - 3] == CodeStream.OPC_goto)) { -// codeStream.position = (position -= 3); -// codeStream.classFileOffset -= 3; -// forwardReferenceCount--; -// // also update the PCs in the related debug attributes -// /** OLD CODE -// int index = codeStream.pcToSourceMapSize - 1; -// while ((index >= 0) && (codeStream.pcToSourceMap[index][1] == oldPosition)) { -// codeStream.pcToSourceMap[index--][1] = position; -// } -// */ -// // Beginning of new code -// int index = codeStream.pcToSourceMapSize - 2; -// if (codeStream.lastEntryPC == oldPosition) { -// codeStream.lastEntryPC = position; -// } -// if ((index >= 0) && (codeStream.pcToSourceMap[index] == position)) { -// codeStream.pcToSourceMapSize-=2; -// } -// // end of new code -// if (codeStream.generateLocalVariableTableAttributes) { -// LocalVariableBinding locals[] = codeStream.locals; -// for (int i = 0, max = locals.length; i < max; i++) { -// LocalVariableBinding local = locals[i]; -// if ((local != null) && (local.initializationCount > 0)) { -// if (local.initializationPCs[((local.initializationCount - 1) << 1) + 1] == oldPosition) { -// // we want to prevent interval of size 0 to have a negative size. -// // see PR 1GIRQLA: ITPJCORE:ALL - ClassFormatError for local variable attribute -// local.initializationPCs[((local.initializationCount - 1) << 1) + 1] = position; -// } -// if (local.initializationPCs[(local.initializationCount - 1) << 1] == oldPosition) { -// local.initializationPCs[(local.initializationCount - 1) << 1] = position; -// } -// } -// } -// } -// } -// } -// for (int i = 0; i < forwardReferenceCount; i++) { -// int offset = position - forwardReferences[i] + 1; -// if (Math.abs(offset) > 0x7FFF && !this.codeStream.wideMode) { -// throw new AbortMethod(CodeStream.RESTART_IN_WIDE_MODE); -// } -// if (this.codeStream.wideMode) { -// if (this.isWide) { -// codeStream.writeSignedWord(forwardReferences[i], offset); -// } else { -// codeStream.writeSignedShort(forwardReferences[i], (short) offset); -// } -// } else { -// codeStream.writeSignedShort(forwardReferences[i], (short) offset); -// } -// } -// // For all labels placed at that position we check if we need to rewrite the jump -// // offset. It is the case each time a label had a forward reference to the current position. -// // Like we change the current position, we have to change the jump offset. See 1F4IRD9 for more details. -// if (optimizedBranch) { -// for (int i = 0; i < codeStream.countLabels; i++) { -// Label label = codeStream.labels[i]; -// if (oldPosition == label.position) { -// label.position = position; -// if (label instanceof CaseLabel) { -// int offset = position - ((CaseLabel) label).instructionPosition; -// for (int j = 0; j < label.forwardReferenceCount; j++) { -// int forwardPosition = label.forwardReferences[j]; -// codeStream.writeSignedWord(forwardPosition, offset); -// } -// } else { -// for (int j = 0; j < label.forwardReferenceCount; j++) { -// int forwardPosition = label.forwardReferences[j]; -// int offset = position - forwardPosition + 1; -// if (Math.abs(offset) > 0x7FFF && !this.codeStream.wideMode) { -// throw new AbortMethod(CodeStream.RESTART_IN_WIDE_MODE); -// } -// if (this.codeStream.wideMode) { -// if (this.isWide) { -// codeStream.writeSignedWord(forwardPosition, offset); -// } else { -// codeStream.writeSignedShort(forwardPosition, (short) offset); -// } -// } else { -// codeStream.writeSignedShort(forwardPosition, (short) offset); -// } -// } -// } -// } -// } -// } -// } -//} -/** - * Print out the receiver - */ -public String toString() { - StringBuffer buffer = new StringBuffer("(position="); //$NON-NLS-1$ - buffer.append(position); - buffer.append(", forwards = ["); //$NON-NLS-1$ - for (int i = 0; i < forwardReferenceCount - 1; i++) - buffer.append(forwardReferences[i] + ", "); //$NON-NLS-1$ - if (forwardReferenceCount >= 1) - buffer.append(forwardReferences[forwardReferenceCount-1]); - buffer.append("] )"); //$NON-NLS-1$ - return buffer.toString(); -} -public void resetStateForCodeGeneration() { - this.position = POS_NOT_SET; - this.forwardReferenceCount = 0; -} + /** + * @param codeStream + * net.sourceforge.phpdt.internal.compiler.codegen.CodeStream + */ + // public Label(CodeStream codeStream) { + // this.codeStream = codeStream; + // } + /** + * Add a forward refrence for the array. + */ + void addForwardReference(int iPos) { + int length; + if (forwardReferenceCount >= (length = forwardReferences.length)) + System.arraycopy(forwardReferences, 0, + (forwardReferences = new int[2 * length]), 0, length); + forwardReferences[forwardReferenceCount++] = iPos; + } + + /** + * Add a forward refrence for the array. + */ + public void appendForwardReferencesFrom(Label otherLabel) { + int otherCount = otherLabel.forwardReferenceCount; + if (otherCount == 0) + return; + int length = forwardReferences.length; + int neededSpace = otherCount + forwardReferenceCount; + if (neededSpace >= length) { + System.arraycopy(forwardReferences, 0, + (forwardReferences = new int[neededSpace]), 0, + forwardReferenceCount); + } + // append other forward references at the end, so they will get updated + // as well + System.arraycopy(otherLabel.forwardReferences, 0, forwardReferences, + forwardReferenceCount, otherCount); + forwardReferenceCount = neededSpace; + } + + /* + * Put down a refernece to the array at the location in the codestream. + */ + // void branch() { + // if (position == POS_NOT_SET) { + // addForwardReference(codeStream.position); + // // Leave two bytes free to generate the jump afterwards + // codeStream.position += 2; + // codeStream.classFileOffset += 2; + // } else { + // /* + // * Position is set. Write it if it is not a wide branch. + // */ + // int offset = position - codeStream.position + 1; + // if (Math.abs(offset) > 0x7FFF && !this.codeStream.wideMode) { + // throw new AbortMethod(CodeStream.RESTART_IN_WIDE_MODE); + // } + // codeStream.writeSignedShort((short) offset); + // } + // } + /* + * No support for wide branches yet + */ + // void branchWide() { + // if (position == POS_NOT_SET) { + // addForwardReference(codeStream.position); + // // Leave 4 bytes free to generate the jump offset afterwards + // isWide = true; + // codeStream.position += 4; + // codeStream.classFileOffset += 4; + // } else { //Position is set. Write it! + // codeStream.writeSignedWord(position - codeStream.position + 1); + // } + // } + /** + * @return boolean + */ + public boolean hasForwardReferences() { + return forwardReferenceCount != 0; + } + + /* + * Some placed labels might be branching to a goto bytecode which we can + * optimize better. + */ + // public void inlineForwardReferencesFromLabelsTargeting(int gotoLocation) + // { + // /* + // Code required to optimized unreachable gotos. + // public boolean isBranchTarget(int location) { + // Label[] labels = codeStream.labels; + // for (int i = codeStream.countLabels - 1; i >= 0; i--){ + // Label label = labels[i]; + // if ((label.position == location) && label.isStandardLabel()){ + // return true; + // } + // } + // return false; + // } + // */ + // + // Label[] labels = codeStream.labels; + // for (int i = codeStream.countLabels - 1; i >= 0; i--){ + // Label label = labels[i]; + // if ((label.position == gotoLocation) && label.isStandardLabel()){ + // this.appendForwardReferencesFrom(label); + // /* + // Code required to optimized unreachable gotos. + // label.position = POS_NOT_SET; + // */ + // } else { + // break; // same target labels should be contiguous + // } + // } + // } + public boolean isStandardLabel() { + return true; + } + + /* + * Place the label. If we have forward references resolve them. + */ + // public void place() { // Currently lacking wide support. + // if (position == POS_NOT_SET) { + // position = codeStream.position; + // codeStream.addLabel(this); + // int oldPosition = position; + // boolean optimizedBranch = false; + // // TURNED OFF since fail on 1F4IRD9 + // if (forwardReferenceCount != 0) { + // if (optimizedBranch = (forwardReferences[forwardReferenceCount - 1] + 2 + // == position) && (codeStream.bCodeStream[codeStream.classFileOffset - 3] + // == CodeStream.OPC_goto)) { + // codeStream.position = (position -= 3); + // codeStream.classFileOffset -= 3; + // forwardReferenceCount--; + // // also update the PCs in the related debug attributes + // /** OLD CODE + // int index = codeStream.pcToSourceMapSize - 1; + // while ((index >= 0) && (codeStream.pcToSourceMap[index][1] == + // oldPosition)) { + // codeStream.pcToSourceMap[index--][1] = position; + // } + // */ + // // Beginning of new code + // int index = codeStream.pcToSourceMapSize - 2; + // if (codeStream.lastEntryPC == oldPosition) { + // codeStream.lastEntryPC = position; + // } + // if ((index >= 0) && (codeStream.pcToSourceMap[index] == position)) { + // codeStream.pcToSourceMapSize-=2; + // } + // // end of new code + // if (codeStream.generateLocalVariableTableAttributes) { + // LocalVariableBinding locals[] = codeStream.locals; + // for (int i = 0, max = locals.length; i < max; i++) { + // LocalVariableBinding local = locals[i]; + // if ((local != null) && (local.initializationCount > 0)) { + // if (local.initializationPCs[((local.initializationCount - 1) << 1) + 1] + // == oldPosition) { + // // we want to prevent interval of size 0 to have a negative size. + // // see PR 1GIRQLA: ITPJCORE:ALL - ClassFormatError for local variable + // attribute + // local.initializationPCs[((local.initializationCount - 1) << 1) + 1] = + // position; + // } + // if (local.initializationPCs[(local.initializationCount - 1) << 1] == + // oldPosition) { + // local.initializationPCs[(local.initializationCount - 1) << 1] = position; + // } + // } + // } + // } + // } + // } + // for (int i = 0; i < forwardReferenceCount; i++) { + // int offset = position - forwardReferences[i] + 1; + // if (Math.abs(offset) > 0x7FFF && !this.codeStream.wideMode) { + // throw new AbortMethod(CodeStream.RESTART_IN_WIDE_MODE); + // } + // if (this.codeStream.wideMode) { + // if (this.isWide) { + // codeStream.writeSignedWord(forwardReferences[i], offset); + // } else { + // codeStream.writeSignedShort(forwardReferences[i], (short) offset); + // } + // } else { + // codeStream.writeSignedShort(forwardReferences[i], (short) offset); + // } + // } + // // For all labels placed at that position we check if we need to rewrite + // the jump + // // offset. It is the case each time a label had a forward reference to + // the current position. + // // Like we change the current position, we have to change the jump + // offset. See 1F4IRD9 for more details. + // if (optimizedBranch) { + // for (int i = 0; i < codeStream.countLabels; i++) { + // Label label = codeStream.labels[i]; + // if (oldPosition == label.position) { + // label.position = position; + // if (label instanceof CaseLabel) { + // int offset = position - ((CaseLabel) label).instructionPosition; + // for (int j = 0; j < label.forwardReferenceCount; j++) { + // int forwardPosition = label.forwardReferences[j]; + // codeStream.writeSignedWord(forwardPosition, offset); + // } + // } else { + // for (int j = 0; j < label.forwardReferenceCount; j++) { + // int forwardPosition = label.forwardReferences[j]; + // int offset = position - forwardPosition + 1; + // if (Math.abs(offset) > 0x7FFF && !this.codeStream.wideMode) { + // throw new AbortMethod(CodeStream.RESTART_IN_WIDE_MODE); + // } + // if (this.codeStream.wideMode) { + // if (this.isWide) { + // codeStream.writeSignedWord(forwardPosition, offset); + // } else { + // codeStream.writeSignedShort(forwardPosition, (short) offset); + // } + // } else { + // codeStream.writeSignedShort(forwardPosition, (short) offset); + // } + // } + // } + // } + // } + // } + // } + // } + /** + * Print out the receiver + */ + public String toString() { + StringBuffer buffer = new StringBuffer("(position="); //$NON-NLS-1$ + buffer.append(position); + buffer.append(", forwards = ["); //$NON-NLS-1$ + for (int i = 0; i < forwardReferenceCount - 1; i++) + buffer.append(forwardReferences[i] + ", "); //$NON-NLS-1$ + if (forwardReferenceCount >= 1) + buffer.append(forwardReferences[forwardReferenceCount - 1]); + buffer.append("] )"); //$NON-NLS-1$ + return buffer.toString(); + } + + public void resetStateForCodeGeneration() { + this.position = POS_NOT_SET; + this.forwardReferenceCount = 0; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/codegen/ObjectCache.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/codegen/ObjectCache.java index 9151ddb..b3a231a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/codegen/ObjectCache.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/codegen/ObjectCache.java @@ -12,141 +12,160 @@ package net.sourceforge.phpdt.internal.compiler.codegen; public class ObjectCache { public Object keyTable[]; + public int valueTable[]; + int elementSize; + int threshold; -/** - * Constructs a new, empty hashtable. A default capacity is used. - * Note that the hashtable will automatically grow when it gets full. - */ -public ObjectCache() { - this(13); -} -/** - * Constructs a new, empty hashtable with the specified initial - * capacity. - * @param initialCapacity int - * the initial number of buckets - */ -public ObjectCache(int initialCapacity) { - this.elementSize = 0; - this.threshold = (int) (initialCapacity * 0.66f); - this.keyTable = new Object[initialCapacity]; - this.valueTable = new int[initialCapacity]; -} -/** - * Clears the hash table so that it has no more elements in it. - */ -public void clear() { - for (int i = keyTable.length; --i >= 0;) { - keyTable[i] = null; - valueTable[i] = 0; + + /** + * Constructs a new, empty hashtable. A default capacity is used. Note that + * the hashtable will automatically grow when it gets full. + */ + public ObjectCache() { + this(13); } - elementSize = 0; -} -/** Returns true if the collection contains an element for the key. - * - * @param char[] key the key that we are looking for - * @return boolean - */ -public boolean containsKey(Object key) { - int index = hashCode(key); - while (keyTable[index] != null) { - if (keyTable[index] == key) - return true; - index = (index + 1) % keyTable.length; + + /** + * Constructs a new, empty hashtable with the specified initial capacity. + * + * @param initialCapacity + * int the initial number of buckets + */ + public ObjectCache(int initialCapacity) { + this.elementSize = 0; + this.threshold = (int) (initialCapacity * 0.66f); + this.keyTable = new Object[initialCapacity]; + this.valueTable = new int[initialCapacity]; } - return false; -} -/** Gets the object associated with the specified key in the - * hashtable. - * @param key char[] the specified key - * @return int the element for the key or -1 if the key is not - * defined in the hash table. - */ -public int get(Object key) { - int index = hashCode(key); - while (keyTable[index] != null) { - if (keyTable[index] == key) - return valueTable[index]; - index = (index + 1) % keyTable.length; + + /** + * Clears the hash table so that it has no more elements in it. + */ + public void clear() { + for (int i = keyTable.length; --i >= 0;) { + keyTable[i] = null; + valueTable[i] = 0; + } + elementSize = 0; } - return -1; -} -/** - * Return the hashcode for the key parameter - * - * @param key net.sourceforge.phpdt.internal.compiler.lookup.MethodBinding - * @return int - */ -public int hashCode(Object key) { - return (key.hashCode() & 0x7FFFFFFF) % keyTable.length; -} -/** - * Puts the specified element into the hashtable, using the specified - * key. The element may be retrieved by doing a get() with the same key. - * The key and the element cannot be null. - * - * @param key Object the specified key in the hashtable - * @param value int the specified element - * @return int the old value of the key, or -1 if it did not have one. - */ -public int put(Object key, int value) { - int index = hashCode(key); - while (keyTable[index] != null) { - if (keyTable[index] == key) - return valueTable[index] = value; - index = (index + 1) % keyTable.length; + + /** + * Returns true if the collection contains an element for the key. + * + * @param char[] + * key the key that we are looking for + * @return boolean + */ + public boolean containsKey(Object key) { + int index = hashCode(key); + while (keyTable[index] != null) { + if (keyTable[index] == key) + return true; + index = (index + 1) % keyTable.length; + } + return false; } - keyTable[index] = key; - valueTable[index] = value; - // assumes the threshold is never equal to the size of the table - if (++elementSize > threshold) - rehash(); - return value; -} -/** - * Rehashes the content of the table into a bigger table. - * This method is called automatically when the hashtable's - * size exceeds the threshold. - */ -private void rehash() { - ObjectCache newHashtable = new ObjectCache(keyTable.length * 2); - for (int i = keyTable.length; --i >= 0;) - if (keyTable[i] != null) - newHashtable.put(keyTable[i], valueTable[i]); - - this.keyTable = newHashtable.keyTable; - this.valueTable = newHashtable.valueTable; - this.threshold = newHashtable.threshold; -} -/** - * Returns the number of elements contained in the hashtable. - * - * @return int The size of the table - */ -public int size() { - return elementSize; -} -/** - * Converts to a rather lengthy String. - * - * @return String the ascii representation of the receiver - */ -public String toString() { - int max = size(); - StringBuffer buf = new StringBuffer(); - buf.append("{"); //$NON-NLS-1$ - for (int i = 0; i < max; ++i) { - if (keyTable[i] != null) { - buf.append(keyTable[i]).append("->").append(valueTable[i]); //$NON-NLS-1$ + /** + * Gets the object associated with the specified key in the hashtable. + * + * @param key + * char[] the specified key + * @return int the element for the key or -1 if the key is not defined in + * the hash table. + */ + public int get(Object key) { + int index = hashCode(key); + while (keyTable[index] != null) { + if (keyTable[index] == key) + return valueTable[index]; + index = (index + 1) % keyTable.length; } - if (i < max) { - buf.append(", "); //$NON-NLS-1$ + return -1; + } + + /** + * Return the hashcode for the key parameter + * + * @param key + * net.sourceforge.phpdt.internal.compiler.lookup.MethodBinding + * @return int + */ + public int hashCode(Object key) { + return (key.hashCode() & 0x7FFFFFFF) % keyTable.length; + } + + /** + * Puts the specified element into the hashtable, using the specified key. + * The element may be retrieved by doing a get() with the same key. The key + * and the element cannot be null. + * + * @param key + * Object the specified key in the hashtable + * @param value + * int the specified element + * @return int the old value of the key, or -1 if it did not have one. + */ + public int put(Object key, int value) { + int index = hashCode(key); + while (keyTable[index] != null) { + if (keyTable[index] == key) + return valueTable[index] = value; + index = (index + 1) % keyTable.length; } + keyTable[index] = key; + valueTable[index] = value; + + // assumes the threshold is never equal to the size of the table + if (++elementSize > threshold) + rehash(); + return value; + } + + /** + * Rehashes the content of the table into a bigger table. This method is + * called automatically when the hashtable's size exceeds the threshold. + */ + private void rehash() { + ObjectCache newHashtable = new ObjectCache(keyTable.length * 2); + for (int i = keyTable.length; --i >= 0;) + if (keyTable[i] != null) + newHashtable.put(keyTable[i], valueTable[i]); + + this.keyTable = newHashtable.keyTable; + this.valueTable = newHashtable.valueTable; + this.threshold = newHashtable.threshold; + } + + /** + * Returns the number of elements contained in the hashtable. + * + * @return int The size of the table + */ + public int size() { + return elementSize; + } + + /** + * Converts to a rather lengthy String. + * + * @return String the ascii representation of the receiver + */ + public String toString() { + int max = size(); + StringBuffer buf = new StringBuffer(); + buf.append("{"); //$NON-NLS-1$ + for (int i = 0; i < max; ++i) { + if (keyTable[i] != null) { + buf.append(keyTable[i]).append("->").append(valueTable[i]); //$NON-NLS-1$ + } + if (i < max) { + buf.append(", "); //$NON-NLS-1$ + } + } + buf.append("}"); //$NON-NLS-1$ + return buf.toString(); } - buf.append("}"); //$NON-NLS-1$ - return buf.toString(); -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryField.java index c36a81b..d075191 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryField.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryField.java @@ -13,21 +13,20 @@ package net.sourceforge.phpdt.internal.compiler.env; import net.sourceforge.phpdt.internal.compiler.impl.Constant; public interface IBinaryField extends IGenericField { -/** - * - * @return net.sourceforge.phpdt.internal.compiler.Constant - */ -Constant getConstant(); -/** - * Answer the resolved name of the receiver's type in the - * class file format as specified in section 4.3.2 of the Java 2 VM spec. - * - * For example: - * - java.lang.String is Ljava/lang/String; - * - an int is I - * - a 2 dimensional array of strings is [[Ljava/lang/String; - * - an array of floats is [F - */ + /** + * + * @return net.sourceforge.phpdt.internal.compiler.Constant + */ + Constant getConstant(); + + /** + * Answer the resolved name of the receiver's type in the class file format + * as specified in section 4.3.2 of the Java 2 VM spec. + * + * For example: - java.lang.String is Ljava/lang/String; - an int is I - a 2 + * dimensional array of strings is [[Ljava/lang/String; - an array of floats + * is [F + */ -char[] getTypeName(); + char[] getTypeName(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryMethod.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryMethod.java index 316c368..6d03d81 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryMethod.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryMethod.java @@ -10,35 +10,38 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.compiler.env; -// clinit methods (synthetics too?) can be returned from IBinaryType>>getMethods() -// BUT do not have to be... the compiler will ignore them when building the binding. -// The synthetic argument of a member type's constructor (ie. the first arg of a non-static -// member type) is also ignored by the compiler, BUT in this case it must be included +// clinit methods (synthetics too?) can be returned from +// IBinaryType>>getMethods() +// BUT do not have to be... the compiler will ignore them when building the +// binding. +// The synthetic argument of a member type's constructor (ie. the first arg of a +// non-static +// member type) is also ignored by the compiler, BUT in this case it must be +// included // in the constructor's signature. public interface IBinaryMethod extends IGenericMethod { -/** - * Answer the resolved names of the exception types in the - * class file format as specified in section 4.2 of the Java 2 VM spec - * or null if the array is empty. - * - * For example, java.lang.String is java/lang/String. - */ -char[][] getExceptionTypeNames(); + /** + * Answer the resolved names of the exception types in the class file format + * as specified in section 4.2 of the Java 2 VM spec or null if the array is + * empty. + * + * For example, java.lang.String is java/lang/String. + */ + char[][] getExceptionTypeNames(); -/** - * Answer the receiver's method descriptor which describes the parameter & - * return types as specified in section 4.3.3 of the Java 2 VM spec. - * - * For example: - * - int foo(String) is (Ljava/lang/String;)I - * - Object[] foo(int) is (I)[Ljava/lang/Object; - */ -char[] getMethodDescriptor(); + /** + * Answer the receiver's method descriptor which describes the parameter & + * return types as specified in section 4.3.3 of the Java 2 VM spec. + * + * For example: - int foo(String) is (Ljava/lang/String;)I - Object[] + * foo(int) is (I)[Ljava/lang/Object; + */ + char[] getMethodDescriptor(); -/** - * Answer whether the receiver represents a class initializer method. - */ -boolean isClinit(); + /** + * Answer whether the receiver represents a class initializer method. + */ + boolean isClinit(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryNestedType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryNestedType.java index a9aa1f0..45a67ec 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryNestedType.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryNestedType.java @@ -11,28 +11,29 @@ package net.sourceforge.phpdt.internal.compiler.env; public interface IBinaryNestedType { -/** - * Answer the resolved name of the enclosing type in the - * class file format as specified in section 4.2 of the Java 2 VM spec. - * - * For example, java.lang.String is java/lang/String. - */ + /** + * Answer the resolved name of the enclosing type in the class file format + * as specified in section 4.2 of the Java 2 VM spec. + * + * For example, java.lang.String is java/lang/String. + */ -char[] getEnclosingTypeName(); -/** - * Answer an int whose bits are set according the access constants - * defined by the VM spec. - */ + char[] getEnclosingTypeName(); -// We have added AccDeprecated & AccSynthetic. + /** + * Answer an int whose bits are set according the access constants defined + * by the VM spec. + */ -int getModifiers(); -/** - * Answer the resolved name of the member type in the - * class file format as specified in section 4.2 of the Java 2 VM spec. - * - * For example, p1.p2.A.M is p1/p2/A$M. - */ + // We have added AccDeprecated & AccSynthetic. + int getModifiers(); -char[] getName(); + /** + * Answer the resolved name of the member type in the class file format as + * specified in section 4.2 of the Java 2 VM spec. + * + * For example, p1.p2.A.M is p1/p2/A$M. + */ + + char[] getName(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryType.java index b9f3d19..489caae 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryType.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryType.java @@ -15,90 +15,97 @@ import net.sourceforge.phpdt.core.compiler.CharOperation; public interface IBinaryType extends IGenericType { char[][] NoInterface = CharOperation.NO_CHAR_CHAR; + IBinaryNestedType[] NoNestedType = new IBinaryNestedType[0]; + IBinaryField[] NoField = new IBinaryField[0]; + IBinaryMethod[] NoMethod = new IBinaryMethod[0]; -/** - * Answer the resolved name of the enclosing type in the - * class file format as specified in section 4.2 of the Java 2 VM spec - * or null if the receiver is a top level type. - * - * For example, java.lang.String is java/lang/String. - */ - -char[] getEnclosingTypeName(); -/** - * Answer the receiver's fields or null if the array is empty. - */ - -IBinaryField[] getFields(); -/** - * Answer the resolved names of the receiver's interfaces in the - * class file format as specified in section 4.2 of the Java 2 VM spec - * or null if the array is empty. - * - * For example, java.lang.String is java/lang/String. - */ - -char[][] getInterfaceNames(); -/** - * Answer the receiver's nested types or null if the array is empty. - * - * This nested type info is extracted from the inner class attributes. - * Ask the name environment to find a member type using its compound name. - */ - -// NOTE: The compiler examines the nested type info & ignores the local types -// so the local types do not have to be included. - -IBinaryNestedType[] getMemberTypes(); -/** - * Answer the receiver's methods or null if the array is empty. - */ - -IBinaryMethod[] getMethods(); -/** - * Answer the resolved name of the type in the - * class file format as specified in section 4.2 of the Java 2 VM spec. - * - * For example, java.lang.String is java/lang/String. - */ - -char[] getName(); -/** - * Answer the resolved name of the receiver's superclass in the - * class file format as specified in section 4.2 of the Java 2 VM spec - * or null if it does not have one. - * - * For example, java.lang.String is java/lang/String. - */ - -char[] getSuperclassName(); - -/** - * Answer true if the receiver is an anonymous class. - * false otherwise - */ -boolean isAnonymous(); - -/** - * Answer true if the receiver is a local class. - * false otherwise - */ -boolean isLocal(); - -/** - * Answer true if the receiver is a member class. - * false otherwise - */ -boolean isMember(); - -/** - * Answer the source file attribute, or null if none. - * - * For example, "String.java" - */ - -char[] sourceFileName(); + + /** + * Answer the resolved name of the enclosing type in the class file format + * as specified in section 4.2 of the Java 2 VM spec or null if the receiver + * is a top level type. + * + * For example, java.lang.String is java/lang/String. + */ + + char[] getEnclosingTypeName(); + + /** + * Answer the receiver's fields or null if the array is empty. + */ + + IBinaryField[] getFields(); + + /** + * Answer the resolved names of the receiver's interfaces in the class file + * format as specified in section 4.2 of the Java 2 VM spec or null if the + * array is empty. + * + * For example, java.lang.String is java/lang/String. + */ + + char[][] getInterfaceNames(); + + /** + * Answer the receiver's nested types or null if the array is empty. + * + * This nested type info is extracted from the inner class attributes. Ask + * the name environment to find a member type using its compound name. + */ + + // NOTE: The compiler examines the nested type info & ignores the local + // types + // so the local types do not have to be included. + IBinaryNestedType[] getMemberTypes(); + + /** + * Answer the receiver's methods or null if the array is empty. + */ + + IBinaryMethod[] getMethods(); + + /** + * Answer the resolved name of the type in the class file format as + * specified in section 4.2 of the Java 2 VM spec. + * + * For example, java.lang.String is java/lang/String. + */ + + char[] getName(); + + /** + * Answer the resolved name of the receiver's superclass in the class file + * format as specified in section 4.2 of the Java 2 VM spec or null if it + * does not have one. + * + * For example, java.lang.String is java/lang/String. + */ + + char[] getSuperclassName(); + + /** + * Answer true if the receiver is an anonymous class. false otherwise + */ + boolean isAnonymous(); + + /** + * Answer true if the receiver is a local class. false otherwise + */ + boolean isLocal(); + + /** + * Answer true if the receiver is a member class. false otherwise + */ + boolean isMember(); + + /** + * Answer the source file attribute, or null if none. + * + * For example, "String.java" + */ + + char[] sourceFileName(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/ICompilationUnit.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/ICompilationUnit.java index 7e14fc5..eefb4f2 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/ICompilationUnit.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/ICompilationUnit.java @@ -16,26 +16,26 @@ import org.eclipse.core.resources.IResource; * This interface denotes a compilation unit, providing its name and content. */ public interface ICompilationUnit extends IDependent { -/** - * Answer the contents of the compilation unit. - * - * In normal use, the contents are requested twice. - * Once during the initial lite parsing step, then again for the - * more detailed parsing step. - */ -char[] getContents(); -/** - * Answer the name of the top level public type. - * For example, {Hashtable}. - */ -char[] getMainTypeName(); -/** - * Answer the name of the package according to the directory structure - * or null if package consistency checks should be ignored. - * For example, {java, lang}. - */ -char[][] getPackageName(); + /** + * Answer the contents of the compilation unit. + * + * In normal use, the contents are requested twice. Once during the initial + * lite parsing step, then again for the more detailed parsing step. + */ + char[] getContents(); + + /** + * Answer the name of the top level public type. For example, {Hashtable}. + */ + char[] getMainTypeName(); + + /** + * Answer the name of the package according to the directory structure or + * null if package consistency checks should be ignored. For example, {java, + * lang}. + */ + char[][] getPackageName(); -IResource getResource(); + IResource getResource(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IConstants.java index a0f7338..6405487 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IConstants.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IConstants.java @@ -19,17 +19,24 @@ public interface IConstants { * Modifiers */ int AccPublic = 0x0001; + int AccPrivate = 0x0002; + int AccProtected = 0x0004; + int AccStatic = 0x0008; + int AccFinal = 0x0010; -// int AccSynchronized = 0x0020; -// int AccVolatile = 0x0040; -// int AccTransient = 0x0080; -// int AccNative = 0x0100; + + // int AccSynchronized = 0x0020; + // int AccVolatile = 0x0040; + // int AccTransient = 0x0080; + // int AccNative = 0x0100; int AccInterface = 0x0200; + int AccAbstract = 0x0400; -// int AccStrictfp = 0x0800; + + // int AccStrictfp = 0x0800; /* * Other VM flags. @@ -39,6 +46,6 @@ public interface IConstants { /** * Extra flags for types and members. */ -// int AccSynthetic = 0x20000; + // int AccSynthetic = 0x20000; int AccDeprecated = 0x100000; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IDependent.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IDependent.java index 8229ea5..7549c36 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IDependent.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IDependent.java @@ -12,22 +12,22 @@ package net.sourceforge.phpdt.internal.compiler.env; /** * This represents the target file of a type dependency. - * + * * All implementors of this interface are containers for types or types - * themselves which must be able to identify their source file name - * when file dependencies are collected. + * themselves which must be able to identify their source file name when file + * dependencies are collected. */ public interface IDependent { -/** - * Answer the file name which defines the type. - * - * The path part (optional) must be separated from the actual - * file proper name by a java.io.File.separator. - * - * The proper file name includes the suffix extension (e.g. ".java") - * - * e.g. "c:/com/ibm/compiler/java/api/Compiler.java" - */ + /** + * Answer the file name which defines the type. + * + * The path part (optional) must be separated from the actual file proper + * name by a java.io.File.separator. + * + * The proper file name includes the suffix extension (e.g. ".java") + * + * e.g. "c:/com/ibm/compiler/java/api/Compiler.java" + */ -char[] getFileName(); + char[] getFileName(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IGenericField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IGenericField.java index ac1f15e..b590260 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IGenericField.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IGenericField.java @@ -11,17 +11,17 @@ package net.sourceforge.phpdt.internal.compiler.env; public interface IGenericField { -/** - * Answer an int whose bits are set according the access constants - * defined by the VM spec. - */ + /** + * Answer an int whose bits are set according the access constants defined + * by the VM spec. + */ -// We have added AccDeprecated & AccSynthetic. + // We have added AccDeprecated & AccSynthetic. + int getModifiers(); -int getModifiers(); -/** - * Answer the name of the field. - */ + /** + * Answer the name of the field. + */ -char[] getName(); + char[] getName(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IGenericMethod.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IGenericMethod.java index 5c17762..4f915f1 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IGenericMethod.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IGenericMethod.java @@ -11,26 +11,26 @@ package net.sourceforge.phpdt.internal.compiler.env; public interface IGenericMethod { -/** - * Answer an int whose bits are set according the access constants - * defined by the VM spec. - */ -// We have added AccDeprecated & AccSynthetic. -int getModifiers(); + /** + * Answer an int whose bits are set according the access constants defined + * by the VM spec. + */ + // We have added AccDeprecated & AccSynthetic. + int getModifiers(); -/** - * Answer the name of the method. - * - * For a constructor, answer & for a clinit method. - */ -char[] getSelector(); + /** + * Answer the name of the method. + * + * For a constructor, answer & for a clinit method. + */ + char[] getSelector(); -boolean isConstructor(); + boolean isConstructor(); -/** - * Answer the names of the argument - * or null if the argument names are not available. - */ + /** + * Answer the names of the argument or null if the argument names are not + * available. + */ -char[][] getArgumentNames(); + char[][] getArgumentNames(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IGenericType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IGenericType.java index 7d1bf79..528a9ef 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IGenericType.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IGenericType.java @@ -11,22 +11,24 @@ package net.sourceforge.phpdt.internal.compiler.env; public interface IGenericType extends IDependent { -/** - * Answer an int whose bits are set according the access constants - * defined by the VM spec. - */ + /** + * Answer an int whose bits are set according the access constants defined + * by the VM spec. + */ -// We have added AccDeprecated & AccSynthetic. + // We have added AccDeprecated & AccSynthetic. + // NOTE: If the receiver represents a member type, the modifiers are + // extracted from its inner class attributes. + int getModifiers(); -// NOTE: If the receiver represents a member type, the modifiers are extracted from its inner class attributes. + /** + * Answer whether the receiver contains the resolved binary form or the + * unresolved source form of the type. + */ -int getModifiers(); -/** - * Answer whether the receiver contains the resolved binary form - * or the unresolved source form of the type. - */ + boolean isBinaryType(); -boolean isBinaryType(); -boolean isClass(); -boolean isInterface(); + boolean isClass(); + + boolean isInterface(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/INameEnvironment.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/INameEnvironment.java index 63cb9ff..45d8d96 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/INameEnvironment.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/INameEnvironment.java @@ -11,61 +11,61 @@ package net.sourceforge.phpdt.internal.compiler.env; /** - * The name environment provides a callback API that the compiler - * can use to look up types, compilation units, and packages in the - * current environment. The name environment is passed to the compiler - * on creation. + * The name environment provides a callback API that the compiler can use to + * look up types, compilation units, and packages in the current environment. + * The name environment is passed to the compiler on creation. */ public interface INameEnvironment { -/** - * Find a type with the given compound name. - * Answer the binary form of the type if it is known to be consistent. - * Otherwise, answer the compilation unit which defines the type - * or null if the type does not exist. - * Types in the default package are specified as {{typeName}}. - * - * It is unknown whether the package containing the type actually exists. - * - * NOTE: This method can be used to find a member type using its - * internal name A$B, but the source file for A is answered if the binary - * file is inconsistent. - */ + /** + * Find a type with the given compound name. Answer the binary form of the + * type if it is known to be consistent. Otherwise, answer the compilation + * unit which defines the type or null if the type does not exist. Types in + * the default package are specified as {{typeName}}. + * + * It is unknown whether the package containing the type actually exists. + * + * NOTE: This method can be used to find a member type using its internal + * name A$B, but the source file for A is answered if the binary file is + * inconsistent. + */ -NameEnvironmentAnswer findType(char[][] compoundTypeName); -/** - * Find a type named in the package . - * Answer the binary form of the type if it is known to be consistent. - * Otherwise, answer the compilation unit which defines the type - * or null if the type does not exist. - * The default package is indicated by char[0][]. - * - * It is known that the package containing the type exists. - * - * NOTE: This method can be used to find a member type using its - * internal name A$B, but the source file for A is answered if the binary - * file is inconsistent. - */ + NameEnvironmentAnswer findType(char[][] compoundTypeName); -NameEnvironmentAnswer findType(char[] typeName, char[][] packageName); -/** - * Answer whether packageName is the name of a known subpackage inside - * the package parentPackageName. A top level package is found relative to null. - * The default package is always assumed to exist. - * - * For example: - * isPackage({{java}, {awt}}, {event}); - * isPackage(null, {java}); - */ + /** + * Find a type named in the package . Answer the + * binary form of the type if it is known to be consistent. Otherwise, + * answer the compilation unit which defines the type or null if the type + * does not exist. The default package is indicated by char[0][]. + * + * It is known that the package containing the type exists. + * + * NOTE: This method can be used to find a member type using its internal + * name A$B, but the source file for A is answered if the binary file is + * inconsistent. + */ -boolean isPackage(char[][] parentPackageName, char[] packageName); + NameEnvironmentAnswer findType(char[] typeName, char[][] packageName); -/** - * This method cleans the environment uo. It is responsible for releasing the memory - * and freeing resources. Passed that point, the name environment is no longer usable. - * - * A name environment can have a long life cycle, therefore it is the responsibility of - * the code which created it to decide when it is a good time to clean it up. - */ -void cleanup(); + /** + * Answer whether packageName is the name of a known subpackage inside the + * package parentPackageName. A top level package is found relative to null. + * The default package is always assumed to exist. + * + * For example: isPackage({{java}, {awt}}, {event}); isPackage(null, + * {java}); + */ + + boolean isPackage(char[][] parentPackageName, char[] packageName); + + /** + * This method cleans the environment uo. It is responsible for releasing + * the memory and freeing resources. Passed that point, the name environment + * is no longer usable. + * + * A name environment can have a long life cycle, therefore it is the + * responsibility of the code which created it to decide when it is a good + * time to clean it up. + */ + void cleanup(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/ISourceField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/ISourceField.java index 2cb6e1d..a2f4139 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/ISourceField.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/ISourceField.java @@ -11,37 +11,37 @@ package net.sourceforge.phpdt.internal.compiler.env; public interface ISourceField extends IGenericField { -/** - * Answer the source end position of the field's declaration. - */ -int getDeclarationSourceEnd(); + /** + * Answer the source end position of the field's declaration. + */ + int getDeclarationSourceEnd(); -/** - * Answer the source start position of the field's declaration. - */ -int getDeclarationSourceStart(); + /** + * Answer the source start position of the field's declaration. + */ + int getDeclarationSourceStart(); -/** - * Answer the initialization source for this constant field. - * Answer null if the field is not a constant or if it has no initialization. - */ -char[] getInitializationSource(); + /** + * Answer the initialization source for this constant field. Answer null if + * the field is not a constant or if it has no initialization. + */ + char[] getInitializationSource(); -/** - * Answer the source end position of the field's name. - */ -int getNameSourceEnd(); + /** + * Answer the source end position of the field's name. + */ + int getNameSourceEnd(); -/** - * Answer the source start position of the field's name. - */ -int getNameSourceStart(); + /** + * Answer the source start position of the field's name. + */ + int getNameSourceStart(); -/** - * Answer the type name of the field. - * - * The name is a simple name or a qualified, dot separated name. - * For example, Hashtable or java.util.Hashtable. - */ -char[] getTypeName(); + /** + * Answer the type name of the field. + * + * The name is a simple name or a qualified, dot separated name. For + * example, Hashtable or java.util.Hashtable. + */ + char[] getTypeName(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/ISourceImport.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/ISourceImport.java index dd5932b..2dcd1ff 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/ISourceImport.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/ISourceImport.java @@ -12,34 +12,33 @@ package net.sourceforge.phpdt.internal.compiler.env; public interface ISourceImport { -/** - * Answer the source end position of the import declaration. - */ - -int getDeclarationSourceEnd(); -/** - * Answer the source start position of the import declaration. - */ - -int getDeclarationSourceStart(); - -/** - * Answer an int whose bits are set according the access constants - * defined by the VM spec. - * Since Java 1.5, static imports can be defined. - */ -int getModifiers(); - -/** - * Answer the name of the import. - * A name is a simple name or a qualified, dot separated name. - * For example, Hashtable or java.util.Hashtable. - */ -char[] getName(); - -/** - * Answer whether the import is on demand or not - * On demand import names have no trailing star - */ -boolean onDemand(); + /** + * Answer the source end position of the import declaration. + */ + + int getDeclarationSourceEnd(); + + /** + * Answer the source start position of the import declaration. + */ + + int getDeclarationSourceStart(); + + /** + * Answer an int whose bits are set according the access constants defined + * by the VM spec. Since Java 1.5, static imports can be defined. + */ + int getModifiers(); + + /** + * Answer the name of the import. A name is a simple name or a qualified, + * dot separated name. For example, Hashtable or java.util.Hashtable. + */ + char[] getName(); + + /** + * Answer whether the import is on demand or not On demand import names have + * no trailing star + */ + boolean onDemand(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/ISourceMethod.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/ISourceMethod.java index ce667c8..0410483 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/ISourceMethod.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/ISourceMethod.java @@ -12,51 +12,57 @@ package net.sourceforge.phpdt.internal.compiler.env; public interface ISourceMethod extends IGenericMethod { -/** - * Answer the unresolved names of the argument types - * or null if the array is empty. - * - * A name is a simple name or a qualified, dot separated name. - * For example, Hashtable or java.util.Hashtable. - */ - -char[][] getArgumentTypeNames(); -/** - * Answer the source end position of the method's declaration. - */ - -int getDeclarationSourceEnd(); -/** - * Answer the source start position of the method's declaration. - */ - -int getDeclarationSourceStart(); -/** - * Answer the unresolved names of the exception types - * or null if the array is empty. - * - * A name is a simple name or a qualified, dot separated name. - * For example, Hashtable or java.util.Hashtable. - */ - -char[][] getExceptionTypeNames(); -/** - * Answer the source end position of the method's selector. - */ - -int getNameSourceEnd(); -/** - * Answer the source start position of the method's selector. - */ - -int getNameSourceStart(); -/** - * Answer the unresolved name of the return type - * or null if receiver is a constructor or clinit. - * - * The name is a simple name or a qualified, dot separated name. - * For example, Hashtable or java.util.Hashtable. - */ - -char[] getReturnTypeName(); + /** + * Answer the unresolved names of the argument types or null if the array is + * empty. + * + * A name is a simple name or a qualified, dot separated name. For example, + * Hashtable or java.util.Hashtable. + */ + + char[][] getArgumentTypeNames(); + + /** + * Answer the source end position of the method's declaration. + */ + + int getDeclarationSourceEnd(); + + /** + * Answer the source start position of the method's declaration. + */ + + int getDeclarationSourceStart(); + + /** + * Answer the unresolved names of the exception types or null if the array + * is empty. + * + * A name is a simple name or a qualified, dot separated name. For example, + * Hashtable or java.util.Hashtable. + */ + + char[][] getExceptionTypeNames(); + + /** + * Answer the source end position of the method's selector. + */ + + int getNameSourceEnd(); + + /** + * Answer the source start position of the method's selector. + */ + + int getNameSourceStart(); + + /** + * Answer the unresolved name of the return type or null if receiver is a + * constructor or clinit. + * + * The name is a simple name or a qualified, dot separated name. For + * example, Hashtable or java.util.Hashtable. + */ + + char[] getReturnTypeName(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/ISourceType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/ISourceType.java index e51b731..fc47cad 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/ISourceType.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/ISourceType.java @@ -10,110 +10,119 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.compiler.env; - public interface ISourceType extends IGenericType { -/** - * Answer the source end position of the type's declaration. - */ - -int getDeclarationSourceEnd(); -/** - * Answer the source start position of the type's declaration. - */ - -int getDeclarationSourceStart(); -/** - * Answer the enclosing type - * or null if the receiver is a top level type. - */ - -ISourceType getEnclosingType(); -/** - * Answer the receiver's fields or null if the array is empty. - * - * NOTE: Multiple fields with the same name can exist in the result. - */ - -ISourceField[] getFields(); -///** -// * Answer the unresolved names of the receiver's imports -// * or null if the array is empty. -// * -// * An import is a qualified, dot separated name. -// * For example, java.util.Hashtable or java.lang.*. -// */ -// -//char[][] getImports(); -/** - * Answer the receiver's imports or null if the array is empty. - * - * An import is a qualified, dot separated name. - * For example, java.util.Hashtable or java.lang.*. - * A static import used 'static.' as its first fragment, for - * example: static.java.util.Hashtable.* - */ -char[][] getImports(); - -/** - * Answer the unresolved names of the receiver's interfaces - * or null if the array is empty. - * - * A name is a simple name or a qualified, dot separated name. - * For example, Hashtable or java.util.Hashtable. - */ - -char[][] getInterfaceNames(); -/** - * Answer the receiver's member types - * or null if the array is empty. - */ - -ISourceType[] getMemberTypes(); -/** - * Answer the receiver's methods or null if the array is empty. - * - * NOTE: Multiple methods with the same name & parameter types can exist in the result. - */ - -ISourceMethod[] getMethods(); -/** - * Answer the simple source name of the receiver. - */ - -char[] getName(); -/** - * Answer the source end position of the type's name. - */ - -int getNameSourceEnd(); -/** - * Answer the source start position of the type's name. - */ - -int getNameSourceStart(); -/** - * Answer the qualified name of the receiver's package separated by periods - * or null if its the default package. - * - * For example, {java.util.Hashtable}. - */ - -char[] getPackageName(); -/** - * Answer the qualified name of the receiver. - * - * The name is a qualified, dot separated name. - * For example, java.util.Hashtable. - */ - -char[] getQualifiedName(); -/** - * Answer the unresolved name of the receiver's superclass - * or null if it does not have one. - * - * The name is a simple name or a qualified, dot separated name. - * For example, Hashtable or java.util.Hashtable. - */ - -char[] getSuperclassName(); + /** + * Answer the source end position of the type's declaration. + */ + + int getDeclarationSourceEnd(); + + /** + * Answer the source start position of the type's declaration. + */ + + int getDeclarationSourceStart(); + + /** + * Answer the enclosing type or null if the receiver is a top level type. + */ + + ISourceType getEnclosingType(); + + /** + * Answer the receiver's fields or null if the array is empty. + * + * NOTE: Multiple fields with the same name can exist in the result. + */ + + ISourceField[] getFields(); + + // /** + // * Answer the unresolved names of the receiver's imports + // * or null if the array is empty. + // * + // * An import is a qualified, dot separated name. + // * For example, java.util.Hashtable or java.lang.*. + // */ + // + // char[][] getImports(); + /** + * Answer the receiver's imports or null if the array is empty. + * + * An import is a qualified, dot separated name. For example, + * java.util.Hashtable or java.lang.*. A static import used 'static.' as its + * first fragment, for example: static.java.util.Hashtable.* + */ + char[][] getImports(); + + /** + * Answer the unresolved names of the receiver's interfaces or null if the + * array is empty. + * + * A name is a simple name or a qualified, dot separated name. For example, + * Hashtable or java.util.Hashtable. + */ + + char[][] getInterfaceNames(); + + /** + * Answer the receiver's member types or null if the array is empty. + */ + + ISourceType[] getMemberTypes(); + + /** + * Answer the receiver's methods or null if the array is empty. + * + * NOTE: Multiple methods with the same name & parameter types can exist in + * the result. + */ + + ISourceMethod[] getMethods(); + + /** + * Answer the simple source name of the receiver. + */ + + char[] getName(); + + /** + * Answer the source end position of the type's name. + */ + + int getNameSourceEnd(); + + /** + * Answer the source start position of the type's name. + */ + + int getNameSourceStart(); + + /** + * Answer the qualified name of the receiver's package separated by periods + * or null if its the default package. + * + * For example, {java.util.Hashtable}. + */ + + char[] getPackageName(); + + /** + * Answer the qualified name of the receiver. + * + * The name is a qualified, dot separated name. For example, + * java.util.Hashtable. + */ + + char[] getQualifiedName(); + + /** + * Answer the unresolved name of the receiver's superclass or null if it + * does not have one. + * + * The name is a simple name or a qualified, dot separated name. For + * example, Hashtable or java.util.Hashtable. + */ + + char[] getSuperclassName(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/NameEnvironmentAnswer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/NameEnvironmentAnswer.java index b022209..38cecaf 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/NameEnvironmentAnswer.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/NameEnvironmentAnswer.java @@ -11,12 +11,14 @@ package net.sourceforge.phpdt.internal.compiler.env; public class NameEnvironmentAnswer { - + // only one of the three can be set IBinaryType binaryType; + ICompilationUnit compilationUnit; + ISourceType[] sourceTypes; - + public NameEnvironmentAnswer(IBinaryType binaryType) { this.binaryType = binaryType; } @@ -30,48 +32,52 @@ public class NameEnvironmentAnswer { } /** - * Answer the resolved binary form for the type or null if the - * receiver represents a compilation unit or source type. + * Answer the resolved binary form for the type or null if the receiver + * represents a compilation unit or source type. */ public IBinaryType getBinaryType() { return binaryType; } /** - * Answer the compilation unit or null if the - * receiver represents a binary or source type. + * Answer the compilation unit or null if the receiver represents a binary + * or source type. */ public ICompilationUnit getCompilationUnit() { return compilationUnit; } /** - * Answer the unresolved source forms for the type or null if the - * receiver represents a compilation unit or binary type. + * Answer the unresolved source forms for the type or null if the receiver + * represents a compilation unit or binary type. * - * Multiple source forms can be answered in case the originating compilation unit did contain - * several type at once. Then the first type is guaranteed to be the requested type. + * Multiple source forms can be answered in case the originating compilation + * unit did contain several type at once. Then the first type is guaranteed + * to be the requested type. */ public ISourceType[] getSourceTypes() { return sourceTypes; } /** - * Answer whether the receiver contains the resolved binary form of the type. + * Answer whether the receiver contains the resolved binary form of the + * type. */ public boolean isBinaryType() { return binaryType != null; } /** - * Answer whether the receiver contains the compilation unit which defines the type. + * Answer whether the receiver contains the compilation unit which defines + * the type. */ public boolean isCompilationUnit() { return compilationUnit != null; } /** - * Answer whether the receiver contains the unresolved source form of the type. + * Answer whether the receiver contains the unresolved source form of the + * type. */ public boolean isSourceType() { return sourceTypes != null; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/ConditionalFlowInfo.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/ConditionalFlowInfo.java index ceda218..8671eb6 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/ConditionalFlowInfo.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/ConditionalFlowInfo.java @@ -15,35 +15,36 @@ import net.sourceforge.phpdt.internal.compiler.lookup.LocalVariableBinding; /** * Record conditional initialization status during definite assignment analysis - * + * */ public class ConditionalFlowInfo extends FlowInfo { - + public FlowInfo initsWhenTrue; + public FlowInfo initsWhenFalse; - - ConditionalFlowInfo(FlowInfo initsWhenTrue, FlowInfo initsWhenFalse){ - + + ConditionalFlowInfo(FlowInfo initsWhenTrue, FlowInfo initsWhenFalse) { + this.initsWhenTrue = initsWhenTrue; - this.initsWhenFalse = initsWhenFalse; + this.initsWhenFalse = initsWhenFalse; } - + public FlowInfo addInitializationsFrom(FlowInfo otherInits) { - + this.initsWhenTrue.addInitializationsFrom(otherInits); this.initsWhenFalse.addInitializationsFrom(otherInits); return this; } - + public FlowInfo addPotentialInitializationsFrom(FlowInfo otherInits) { - + this.initsWhenTrue.addPotentialInitializationsFrom(otherInits); this.initsWhenFalse.addPotentialInitializationsFrom(otherInits); return this; } - + public FlowInfo asNegatedCondition() { - + FlowInfo extra = initsWhenTrue; initsWhenTrue = initsWhenFalse; initsWhenFalse = extra; @@ -51,128 +52,131 @@ public class ConditionalFlowInfo extends FlowInfo { } public FlowInfo copy() { - - return new ConditionalFlowInfo(initsWhenTrue.copy(), initsWhenFalse.copy()); + + return new ConditionalFlowInfo(initsWhenTrue.copy(), initsWhenFalse + .copy()); } - + public FlowInfo initsWhenFalse() { - + return initsWhenFalse; } - + public FlowInfo initsWhenTrue() { - + return initsWhenTrue; } - + /** * Check status of definite assignment for a field. */ public boolean isDefinitelyAssigned(FieldBinding field) { - - return initsWhenTrue.isDefinitelyAssigned(field) + + return initsWhenTrue.isDefinitelyAssigned(field) && initsWhenFalse.isDefinitelyAssigned(field); } - + /** * Check status of definite assignment for a local variable. */ public boolean isDefinitelyAssigned(LocalVariableBinding local) { - - return initsWhenTrue.isDefinitelyAssigned(local) + + return initsWhenTrue.isDefinitelyAssigned(local) && initsWhenFalse.isDefinitelyAssigned(local); } - - public int reachMode(){ + + public int reachMode() { return unconditionalInits().reachMode(); } - - public boolean isReachable(){ - - return unconditionalInits().isReachable(); - //should maybe directly be: false + + public boolean isReachable() { + + return unconditionalInits().isReachable(); + // should maybe directly be: false } - + /** * Check status of potential assignment for a field. */ public boolean isPotentiallyAssigned(FieldBinding field) { - - return initsWhenTrue.isPotentiallyAssigned(field) + + return initsWhenTrue.isPotentiallyAssigned(field) || initsWhenFalse.isPotentiallyAssigned(field); } - + /** * Check status of potential assignment for a local variable. */ public boolean isPotentiallyAssigned(LocalVariableBinding local) { - - return initsWhenTrue.isPotentiallyAssigned(local) + + return initsWhenTrue.isPotentiallyAssigned(local) || initsWhenFalse.isPotentiallyAssigned(local); } - + /** * Record a field got definitely assigned. */ public void markAsDefinitelyAssigned(FieldBinding field) { - + initsWhenTrue.markAsDefinitelyAssigned(field); - initsWhenFalse.markAsDefinitelyAssigned(field); + initsWhenFalse.markAsDefinitelyAssigned(field); } - + /** * Record a field got definitely assigned. */ public void markAsDefinitelyAssigned(LocalVariableBinding local) { - + initsWhenTrue.markAsDefinitelyAssigned(local); - initsWhenFalse.markAsDefinitelyAssigned(local); + initsWhenFalse.markAsDefinitelyAssigned(local); } - + /** * Clear the initialization info for a field */ public void markAsDefinitelyNotAssigned(FieldBinding field) { - + initsWhenTrue.markAsDefinitelyNotAssigned(field); - initsWhenFalse.markAsDefinitelyNotAssigned(field); + initsWhenFalse.markAsDefinitelyNotAssigned(field); } - + /** * Clear the initialization info for a local variable */ public void markAsDefinitelyNotAssigned(LocalVariableBinding local) { - + initsWhenTrue.markAsDefinitelyNotAssigned(local); - initsWhenFalse.markAsDefinitelyNotAssigned(local); + initsWhenFalse.markAsDefinitelyNotAssigned(local); } - + public FlowInfo setReachMode(int reachMode) { - + initsWhenTrue.setReachMode(reachMode); initsWhenFalse.setReachMode(reachMode); return this; } - + /** - * Converts conditional receiver into inconditional one, updated in the following way:
            - *
          • intersection of definitely assigned variables, + * Converts conditional receiver into inconditional one, updated in the + * following way: + *
              + *
            • intersection of definitely assigned variables, *
            • union of potentially assigned variables. *
            */ public UnconditionalFlowInfo mergedWith(UnconditionalFlowInfo otherInits) { - + return unconditionalInits().mergedWith(otherInits); } - + public String toString() { - + return "FlowInfo"; //$NON-NLS-1$ //$NON-NLS-3$ //$NON-NLS-2$ } - + public UnconditionalFlowInfo unconditionalInits() { - - return initsWhenTrue.unconditionalInits().copy() - .mergedWith(initsWhenFalse.unconditionalInits()); + + return initsWhenTrue.unconditionalInits().copy().mergedWith( + initsWhenFalse.unconditionalInits()); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/ExceptionHandlingFlowContext.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/ExceptionHandlingFlowContext.java index 0ddf6ab..4d0927b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/ExceptionHandlingFlowContext.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/ExceptionHandlingFlowContext.java @@ -20,31 +20,33 @@ import net.sourceforge.phpdt.internal.compiler.lookup.Scope; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; /** - * Reflects the context of code analysis, keeping track of enclosing - * try statements, exception handlers, etc... + * Reflects the context of code analysis, keeping track of enclosing try + * statements, exception handlers, etc... */ public class ExceptionHandlingFlowContext extends FlowContext { - + public ReferenceBinding[] handledExceptions; - + public final static int BitCacheSize = 32; // 32 bits per int + int[] isReached; + int[] isNeeded; + UnconditionalFlowInfo[] initsOnExceptions; + ObjectCache indexes = new ObjectCache(); + boolean isMethodContext; public UnconditionalFlowInfo initsOnReturn; // for dealing with anonymous constructor thrown exceptions public ArrayList extendedExceptions; - - public ExceptionHandlingFlowContext( - FlowContext parent, - ASTNode associatedNode, - ReferenceBinding[] handledExceptions, - BlockScope scope, - UnconditionalFlowInfo flowInfo) { + + public ExceptionHandlingFlowContext(FlowContext parent, + ASTNode associatedNode, ReferenceBinding[] handledExceptions, + BlockScope scope, UnconditionalFlowInfo flowInfo) { super(parent, associatedNode); isMethodContext = scope == scope.methodScope(); @@ -54,49 +56,50 @@ public class ExceptionHandlingFlowContext extends FlowContext { this.isNeeded = new int[cacheSize]; // none is needed by default this.initsOnExceptions = new UnconditionalFlowInfo[count]; for (int i = 0; i < count; i++) { - this.indexes.put(handledExceptions[i], i); // key type -> value index - boolean isUnchecked = - (scope.compareUncheckedException(handledExceptions[i]) != NotRelated); + this.indexes.put(handledExceptions[i], i); // key type -> value + // index + boolean isUnchecked = (scope + .compareUncheckedException(handledExceptions[i]) != NotRelated); int cacheIndex = i / BitCacheSize, bitMask = 1 << (i % BitCacheSize); if (isUnchecked) { isReached[cacheIndex] |= bitMask; - this.initsOnExceptions[i] = flowInfo.copy().unconditionalInits(); + this.initsOnExceptions[i] = flowInfo.copy() + .unconditionalInits(); } else { this.initsOnExceptions[i] = FlowInfo.DEAD_END; } } System.arraycopy(this.isReached, 0, this.isNeeded, 0, cacheSize); - this.initsOnReturn = FlowInfo.DEAD_END; + this.initsOnReturn = FlowInfo.DEAD_END; } - - -// public void complainIfUnusedExceptionHandlers( -// ASTNode[] exceptionHandlers, -// BlockScope scope, -// TryStatement tryStatement) { -// // report errors for unreachable exception handlers -// for (int i = 0, count = handledExceptions.length; i < count; i++) { -// int index = indexes.get(handledExceptions[i]); -// int cacheIndex = index / BitCacheSize; -// int bitMask = 1 << (index % BitCacheSize); -// if ((isReached[cacheIndex] & bitMask) == 0) { -// scope.problemReporter().unreachableExceptionHandler( -// handledExceptions[index], -// exceptionHandlers[index]); -// } else { -// if ((isNeeded[cacheIndex] & bitMask) == 0) { -// scope.problemReporter().maskedExceptionHandler( -// handledExceptions[index], -// exceptionHandlers[index]); -// } -// } -// } -// // will optimized out unnecessary catch block during code gen -// tryStatement.preserveExceptionHandler = isNeeded; -// } + + // public void complainIfUnusedExceptionHandlers( + // ASTNode[] exceptionHandlers, + // BlockScope scope, + // TryStatement tryStatement) { + // // report errors for unreachable exception handlers + // for (int i = 0, count = handledExceptions.length; i < count; i++) { + // int index = indexes.get(handledExceptions[i]); + // int cacheIndex = index / BitCacheSize; + // int bitMask = 1 << (index % BitCacheSize); + // if ((isReached[cacheIndex] & bitMask) == 0) { + // scope.problemReporter().unreachableExceptionHandler( + // handledExceptions[index], + // exceptionHandlers[index]); + // } else { + // if ((isNeeded[cacheIndex] & bitMask) == 0) { + // scope.problemReporter().maskedExceptionHandler( + // handledExceptions[index], + // exceptionHandlers[index]); + // } + // } + // } + // // will optimized out unnecessary catch block during code gen + // tryStatement.preserveExceptionHandler = isNeeded; + // } public String individualToString() { - + StringBuffer buffer = new StringBuffer("Exception flow context"); //$NON-NLS-1$ int length = handledExceptions.length; for (int i = 0; i < length; i++) { @@ -112,14 +115,16 @@ public class ExceptionHandlingFlowContext extends FlowContext { } else { buffer.append("-not reached"); //$NON-NLS-1$ } - buffer.append('-').append(initsOnExceptions[i].toString()).append(']'); + buffer.append('-').append(initsOnExceptions[i].toString()).append( + ']'); } - buffer.append("[initsOnReturn -").append(initsOnReturn.toString()).append(']'); //$NON-NLS-1$ + buffer + .append("[initsOnReturn -").append(initsOnReturn.toString()).append(']'); //$NON-NLS-1$ return buffer.toString(); } public UnconditionalFlowInfo initsOnException(ReferenceBinding exceptionType) { - + int index; if ((index = indexes.get(exceptionType)) < 0) { return FlowInfo.DEAD_END; @@ -127,17 +132,14 @@ public class ExceptionHandlingFlowContext extends FlowContext { return initsOnExceptions[index]; } - public UnconditionalFlowInfo initsOnReturn(){ + public UnconditionalFlowInfo initsOnReturn() { return this.initsOnReturn; } - - public void recordHandlingException( - ReferenceBinding exceptionType, - UnconditionalFlowInfo flowInfo, - TypeBinding raisedException, - ASTNode invocationSite, - boolean wasAlreadyDefinitelyCaught) { - + + public void recordHandlingException(ReferenceBinding exceptionType, + UnconditionalFlowInfo flowInfo, TypeBinding raisedException, + ASTNode invocationSite, boolean wasAlreadyDefinitelyCaught) { + int index = indexes.get(exceptionType); // if already flagged as being reached (unchecked exception handler) int cacheIndex = index / BitCacheSize; @@ -146,51 +148,54 @@ public class ExceptionHandlingFlowContext extends FlowContext { this.isNeeded[cacheIndex] |= bitMask; } this.isReached[cacheIndex] |= bitMask; - - initsOnExceptions[index] = - initsOnExceptions[index] == FlowInfo.DEAD_END - ? flowInfo.copy().unconditionalInits() + + initsOnExceptions[index] = initsOnExceptions[index] == FlowInfo.DEAD_END ? flowInfo + .copy().unconditionalInits() : initsOnExceptions[index].mergedWith(flowInfo); } - + public void recordReturnFrom(FlowInfo flowInfo) { - if (!flowInfo.isReachable()) return; + if (!flowInfo.isReachable()) + return; if (initsOnReturn == FlowInfo.DEAD_END) { initsOnReturn = flowInfo.copy().unconditionalInits(); } else { - initsOnReturn = initsOnReturn.mergedWith(flowInfo.unconditionalInits()); + initsOnReturn = initsOnReturn.mergedWith(flowInfo + .unconditionalInits()); } } - + /* - * Compute a merged list of unhandled exception types (keeping only the most generic ones). - * This is necessary to add synthetic thrown exceptions for anonymous type constructors (JLS 8.6). + * Compute a merged list of unhandled exception types (keeping only the most + * generic ones). This is necessary to add synthetic thrown exceptions for + * anonymous type constructors (JLS 8.6). */ - public void mergeUnhandledException(TypeBinding newException){ - - if (this.extendedExceptions == null){ + public void mergeUnhandledException(TypeBinding newException) { + + if (this.extendedExceptions == null) { this.extendedExceptions = new ArrayList(5); - for (int i = 0; i < this.handledExceptions.length; i++){ + for (int i = 0; i < this.handledExceptions.length; i++) { this.extendedExceptions.add(this.handledExceptions[i]); } } - + boolean isRedundant = false; - - for(int i = this.extendedExceptions.size()-1; i >= 0; i--){ - switch(Scope.compareTypes(newException, (TypeBinding)this.extendedExceptions.get(i))){ - case MoreGeneric : - this.extendedExceptions.remove(i); - break; - case EqualOrMoreSpecific : - isRedundant = true; - break; - case NotRelated : - break; + + for (int i = this.extendedExceptions.size() - 1; i >= 0; i--) { + switch (Scope.compareTypes(newException, + (TypeBinding) this.extendedExceptions.get(i))) { + case MoreGeneric: + this.extendedExceptions.remove(i); + break; + case EqualOrMoreSpecific: + isRedundant = true; + break; + case NotRelated: + break; } } - if (!isRedundant){ + if (!isRedundant) { this.extendedExceptions.add(newException); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/FinallyFlowContext.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/FinallyFlowContext.java index 9adb823..88200c5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/FinallyFlowContext.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/FinallyFlowContext.java @@ -18,55 +18,65 @@ import net.sourceforge.phpdt.internal.compiler.lookup.LocalVariableBinding; import net.sourceforge.phpdt.internal.compiler.lookup.VariableBinding; /** - * Reflects the context of code analysis, keeping track of enclosing - * try statements, exception handlers, etc... + * Reflects the context of code analysis, keeping track of enclosing try + * statements, exception handlers, etc... */ public class FinallyFlowContext extends FlowContext { - + Reference finalAssignments[]; + VariableBinding finalVariables[]; + int assignCount; - + public FinallyFlowContext(FlowContext parent, ASTNode associatedNode) { super(parent, associatedNode); } /** - * Given some contextual initialization info (derived from a try block or a catch block), this - * code will check that the subroutine context does not also initialize a final variable potentially set - * redundantly. + * Given some contextual initialization info (derived from a try block or a + * catch block), this code will check that the subroutine context does not + * also initialize a final variable potentially set redundantly. */ - public void complainOnRedundantFinalAssignments( - FlowInfo flowInfo, - BlockScope scope) { + public void complainOnRedundantFinalAssignments(FlowInfo flowInfo, + BlockScope scope) { for (int i = 0; i < assignCount; i++) { VariableBinding variable = finalVariables[i]; - if (variable == null) continue; - - boolean complained = false; // remember if have complained on this final assignment + if (variable == null) + continue; + + boolean complained = false; // remember if have complained on this + // final assignment if (variable instanceof FieldBinding) { // final field - if (flowInfo.isPotentiallyAssigned((FieldBinding)variable)) { + if (flowInfo.isPotentiallyAssigned((FieldBinding) variable)) { complained = true; - scope.problemReporter().duplicateInitializationOfBlankFinalField((FieldBinding)variable, finalAssignments[i]); + scope.problemReporter() + .duplicateInitializationOfBlankFinalField( + (FieldBinding) variable, + finalAssignments[i]); } } else { // final local variable - if (flowInfo.isPotentiallyAssigned((LocalVariableBinding) variable)) { + if (flowInfo + .isPotentiallyAssigned((LocalVariableBinding) variable)) { complained = true; - scope.problemReporter().duplicateInitializationOfFinalLocal( - (LocalVariableBinding) variable, - finalAssignments[i]); + scope.problemReporter() + .duplicateInitializationOfFinalLocal( + (LocalVariableBinding) variable, + finalAssignments[i]); } } - // any reference reported at this level is removed from the parent context + // any reference reported at this level is removed from the parent + // context // where it could also be reported again if (complained) { FlowContext currentContext = parent; while (currentContext != null) { - //if (currentContext.isSubRoutine()) { - currentContext.removeFinalAssignmentIfAny(finalAssignments[i]); - //} + // if (currentContext.isSubRoutine()) { + currentContext + .removeFinalAssignmentIfAny(finalAssignments[i]); + // } currentContext = currentContext.parent; } } @@ -74,37 +84,32 @@ public class FinallyFlowContext extends FlowContext { } public String individualToString() { - + StringBuffer buffer = new StringBuffer("Finally flow context"); //$NON-NLS-1$ - buffer.append("[finalAssignments count -").append(assignCount).append(']'); //$NON-NLS-1$ + buffer + .append("[finalAssignments count -").append(assignCount).append(']'); //$NON-NLS-1$ return buffer.toString(); } - + public boolean isSubRoutine() { return true; } - boolean recordFinalAssignment( - VariableBinding binding, - Reference finalAssignment) { + boolean recordFinalAssignment(VariableBinding binding, + Reference finalAssignment) { if (assignCount == 0) { finalAssignments = new Reference[5]; finalVariables = new VariableBinding[5]; } else { if (assignCount == finalAssignments.length) - System.arraycopy( - finalAssignments, - 0, - (finalAssignments = new Reference[assignCount * 2]), - 0, + System.arraycopy(finalAssignments, 0, + (finalAssignments = new Reference[assignCount * 2]), 0, + assignCount); + System.arraycopy(finalVariables, 0, + (finalVariables = new VariableBinding[assignCount * 2]), 0, assignCount); - System.arraycopy( - finalVariables, - 0, - (finalVariables = new VariableBinding[assignCount * 2]), - 0, - assignCount); - }; + } + ; finalAssignments[assignCount] = finalAssignment; finalVariables[assignCount++] = binding; return true; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/FlowContext.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/FlowContext.java index dca4536..8daeeba 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/FlowContext.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/FlowContext.java @@ -24,99 +24,100 @@ import net.sourceforge.phpdt.internal.compiler.lookup.TypeConstants; import net.sourceforge.phpdt.internal.compiler.lookup.VariableBinding; /** - * Reflects the context of code analysis, keeping track of enclosing - * try statements, exception handlers, etc... + * Reflects the context of code analysis, keeping track of enclosing try + * statements, exception handlers, etc... */ public class FlowContext implements TypeConstants { - + public ASTNode associatedNode; + public FlowContext parent; - public final static FlowContext NotContinuableContext = new FlowContext(null, null); - + public final static FlowContext NotContinuableContext = new FlowContext( + null, null); + public FlowContext(FlowContext parent, ASTNode associatedNode) { this.parent = parent; this.associatedNode = associatedNode; } - + public Label breakLabel() { return null; } - - public void checkExceptionHandlers( - TypeBinding[] raisedExceptions, - ASTNode location, - FlowInfo flowInfo, - BlockScope scope) { + + public void checkExceptionHandlers(TypeBinding[] raisedExceptions, + ASTNode location, FlowInfo flowInfo, BlockScope scope) { // check that all the argument exception types are handled - // JDK Compatible implementation - when an exception type is thrown, - // all related catch blocks are marked as reachable... instead of those only - // until the point where it is safely handled (Smarter - see comment at the end) - int remainingCount; // counting the number of remaining unhandled exceptions + // JDK Compatible implementation - when an exception type is thrown, + // all related catch blocks are marked as reachable... instead of those + // only + // until the point where it is safely handled (Smarter - see comment at + // the end) + int remainingCount; // counting the number of remaining unhandled + // exceptions int raisedCount; // total number of exceptions raised if ((raisedExceptions == null) - || ((raisedCount = raisedExceptions.length) == 0)) + || ((raisedCount = raisedExceptions.length) == 0)) return; remainingCount = raisedCount; // duplicate the array of raised exceptions since it will be updated // (null replaces any handled exception) - System.arraycopy( - raisedExceptions, - 0, - (raisedExceptions = new TypeBinding[raisedCount]), - 0, - raisedCount); + System.arraycopy(raisedExceptions, 0, + (raisedExceptions = new TypeBinding[raisedCount]), 0, + raisedCount); FlowContext traversedContext = this; while (traversedContext != null) { ASTNode sub; - if (((sub = traversedContext.subRoutine()) != null) && sub.cannotReturn()) { - // traversing a non-returning subroutine means that all unhandled + if (((sub = traversedContext.subRoutine()) != null) + && sub.cannotReturn()) { + // traversing a non-returning subroutine means that all + // unhandled // exceptions will actually never get sent... return; } - // filter exceptions that are locally caught from the innermost enclosing + // filter exceptions that are locally caught from the innermost + // enclosing // try statement to the outermost ones. if (traversedContext instanceof ExceptionHandlingFlowContext) { - ExceptionHandlingFlowContext exceptionContext = - (ExceptionHandlingFlowContext) traversedContext; + ExceptionHandlingFlowContext exceptionContext = (ExceptionHandlingFlowContext) traversedContext; ReferenceBinding[] caughtExceptions; if ((caughtExceptions = exceptionContext.handledExceptions) != NoExceptions) { int caughtCount = caughtExceptions.length; - boolean[] locallyCaught = new boolean[raisedCount]; // at most + boolean[] locallyCaught = new boolean[raisedCount]; // at + // most for (int caughtIndex = 0; caughtIndex < caughtCount; caughtIndex++) { ReferenceBinding caughtException = caughtExceptions[caughtIndex]; for (int raisedIndex = 0; raisedIndex < raisedCount; raisedIndex++) { TypeBinding raisedException; if ((raisedException = raisedExceptions[raisedIndex]) != null) { - switch (Scope.compareTypes(raisedException, caughtException)) { - case EqualOrMoreSpecific : - exceptionContext.recordHandlingException( - caughtException, - flowInfo.unconditionalInits(), - raisedException, - location, + switch (Scope.compareTypes(raisedException, + caughtException)) { + case EqualOrMoreSpecific: + exceptionContext.recordHandlingException( + caughtException, flowInfo + .unconditionalInits(), + raisedException, location, locallyCaught[raisedIndex]); - // was already definitely caught ? - if (!locallyCaught[raisedIndex]) { - locallyCaught[raisedIndex] = true; - // remember that this exception has been definitely caught - remainingCount--; - } - break; - case MoreGeneric : - exceptionContext.recordHandlingException( - caughtException, - flowInfo.unconditionalInits(), - raisedException, - location, - false); - // was not caught already per construction + // was already definitely caught ? + if (!locallyCaught[raisedIndex]) { + locallyCaught[raisedIndex] = true; + // remember that this exception has been + // definitely caught + remainingCount--; + } + break; + case MoreGeneric: + exceptionContext.recordHandlingException( + caughtException, flowInfo + .unconditionalInits(), + raisedException, location, false); + // was not caught already per construction } } } @@ -124,7 +125,8 @@ public class FlowContext implements TypeConstants { // remove locally caught exceptions from the remaining ones for (int i = 0; i < raisedCount; i++) { if (locallyCaught[i]) { - raisedExceptions[i] = null; // removed from the remaining ones. + raisedExceptions[i] = null; // removed from the + // remaining ones. } } } @@ -133,26 +135,33 @@ public class FlowContext implements TypeConstants { for (int i = 0; i < raisedCount; i++) { TypeBinding raisedException; if ((raisedException = raisedExceptions[i]) != null) { - if (raisedException.isCompatibleWith(scope.getJavaLangRuntimeException()) - || raisedException.isCompatibleWith(scope.getJavaLangError())) { + if (raisedException.isCompatibleWith(scope + .getJavaLangRuntimeException()) + || raisedException.isCompatibleWith(scope + .getJavaLangError())) { remainingCount--; raisedExceptions[i] = null; } } } - // anonymous constructors are allowed to throw any exceptions (their thrown exceptions + // anonymous constructors are allowed to throw any + // exceptions (their thrown exceptions // clause will be fixed up later as per JLS 8.6). - if (exceptionContext.associatedNode instanceof AbstractMethodDeclaration){ - AbstractMethodDeclaration method = (AbstractMethodDeclaration)exceptionContext.associatedNode; - if (method.isConstructor() && method.binding.declaringClass.isAnonymousType()){ - + if (exceptionContext.associatedNode instanceof AbstractMethodDeclaration) { + AbstractMethodDeclaration method = (AbstractMethodDeclaration) exceptionContext.associatedNode; + if (method.isConstructor() + && method.binding.declaringClass + .isAnonymousType()) { + for (int i = 0; i < raisedCount; i++) { TypeBinding raisedException; if ((raisedException = raisedExceptions[i]) != null) { - exceptionContext.mergeUnhandledException(raisedException); + exceptionContext + .mergeUnhandledException(raisedException); } } - return; // no need to complain, will fix up constructor exceptions + return; // no need to complain, will fix up + // constructor exceptions } } break; // not handled anywhere, thus jump to error handling @@ -160,77 +169,80 @@ public class FlowContext implements TypeConstants { } if (remainingCount == 0) return; - + traversedContext.recordReturnFrom(flowInfo.unconditionalInits()); - if (traversedContext.associatedNode instanceof TryStatement){ - flowInfo = flowInfo.copy().addInitializationsFrom(((TryStatement) traversedContext.associatedNode).subRoutineInits); + if (traversedContext.associatedNode instanceof TryStatement) { + flowInfo = flowInfo + .copy() + .addInitializationsFrom( + ((TryStatement) traversedContext.associatedNode).subRoutineInits); } traversedContext = traversedContext.parent; } - // if reaches this point, then there are some remaining unhandled exception types. + // if reaches this point, then there are some remaining unhandled + // exception types. nextReport: for (int i = 0; i < raisedCount; i++) { TypeBinding exception; if ((exception = raisedExceptions[i]) != null) { - // only one complaint if same exception declared to be thrown more than once + // only one complaint if same exception declared to be thrown + // more than once for (int j = 0; j < i; j++) { - if (raisedExceptions[j] == exception) continue nextReport; // already reported + if (raisedExceptions[j] == exception) + continue nextReport; // already reported } scope.problemReporter().unhandledException(exception, location); } } } - public void checkExceptionHandlers( - TypeBinding raisedException, - ASTNode location, - FlowInfo flowInfo, - BlockScope scope) { + public void checkExceptionHandlers(TypeBinding raisedException, + ASTNode location, FlowInfo flowInfo, BlockScope scope) { // LIGHT-VERSION OF THE EQUIVALENT WITH AN ARRAY OF EXCEPTIONS // check that all the argument exception types are handled - // JDK Compatible implementation - when an exception type is thrown, - // all related catch blocks are marked as reachable... instead of those only - // until the point where it is safely handled (Smarter - see comment at the end) + // JDK Compatible implementation - when an exception type is thrown, + // all related catch blocks are marked as reachable... instead of those + // only + // until the point where it is safely handled (Smarter - see comment at + // the end) FlowContext traversedContext = this; while (traversedContext != null) { ASTNode sub; - if (((sub = traversedContext.subRoutine()) != null) && sub.cannotReturn()) { - // traversing a non-returning subroutine means that all unhandled + if (((sub = traversedContext.subRoutine()) != null) + && sub.cannotReturn()) { + // traversing a non-returning subroutine means that all + // unhandled // exceptions will actually never get sent... return; } - - // filter exceptions that are locally caught from the innermost enclosing + + // filter exceptions that are locally caught from the innermost + // enclosing // try statement to the outermost ones. if (traversedContext instanceof ExceptionHandlingFlowContext) { - ExceptionHandlingFlowContext exceptionContext = - (ExceptionHandlingFlowContext) traversedContext; + ExceptionHandlingFlowContext exceptionContext = (ExceptionHandlingFlowContext) traversedContext; ReferenceBinding[] caughtExceptions; if ((caughtExceptions = exceptionContext.handledExceptions) != NoExceptions) { boolean definitelyCaught = false; - for (int caughtIndex = 0, caughtCount = caughtExceptions.length; - caughtIndex < caughtCount; - caughtIndex++) { + for (int caughtIndex = 0, caughtCount = caughtExceptions.length; caughtIndex < caughtCount; caughtIndex++) { ReferenceBinding caughtException = caughtExceptions[caughtIndex]; - switch (Scope.compareTypes(raisedException, caughtException)) { - case EqualOrMoreSpecific : - exceptionContext.recordHandlingException( - caughtException, - flowInfo.unconditionalInits(), - raisedException, - location, - definitelyCaught); - // was it already definitely caught ? - definitelyCaught = true; - break; - case MoreGeneric : - exceptionContext.recordHandlingException( - caughtException, - flowInfo.unconditionalInits(), - raisedException, - location, - false); - // was not caught already per construction + switch (Scope.compareTypes(raisedException, + caughtException)) { + case EqualOrMoreSpecific: + exceptionContext + .recordHandlingException(caughtException, + flowInfo.unconditionalInits(), + raisedException, location, + definitelyCaught); + // was it already definitely caught ? + definitelyCaught = true; + break; + case MoreGeneric: + exceptionContext.recordHandlingException( + caughtException, flowInfo + .unconditionalInits(), + raisedException, location, false); + // was not caught already per construction } } if (definitelyCaught) @@ -238,18 +250,25 @@ public class FlowContext implements TypeConstants { } // method treatment for unchecked exceptions if (exceptionContext.isMethodContext) { - if (raisedException.isCompatibleWith(scope.getJavaLangRuntimeException()) - || raisedException.isCompatibleWith(scope.getJavaLangError())) + if (raisedException.isCompatibleWith(scope + .getJavaLangRuntimeException()) + || raisedException.isCompatibleWith(scope + .getJavaLangError())) return; - - // anonymous constructors are allowed to throw any exceptions (their thrown exceptions + + // anonymous constructors are allowed to throw any + // exceptions (their thrown exceptions // clause will be fixed up later as per JLS 8.6). - if (exceptionContext.associatedNode instanceof AbstractMethodDeclaration){ - AbstractMethodDeclaration method = (AbstractMethodDeclaration)exceptionContext.associatedNode; - if (method.isConstructor() && method.binding.declaringClass.isAnonymousType()){ - - exceptionContext.mergeUnhandledException(raisedException); - return; // no need to complain, will fix up constructor exceptions + if (exceptionContext.associatedNode instanceof AbstractMethodDeclaration) { + AbstractMethodDeclaration method = (AbstractMethodDeclaration) exceptionContext.associatedNode; + if (method.isConstructor() + && method.binding.declaringClass + .isAnonymousType()) { + + exceptionContext + .mergeUnhandledException(raisedException); + return; // no need to complain, will fix up + // constructor exceptions } } break; // not handled anywhere, thus jump to error handling @@ -257,12 +276,16 @@ public class FlowContext implements TypeConstants { } traversedContext.recordReturnFrom(flowInfo.unconditionalInits()); - if (traversedContext.associatedNode instanceof TryStatement){ - flowInfo = flowInfo.copy().addInitializationsFrom(((TryStatement) traversedContext.associatedNode).subRoutineInits); + if (traversedContext.associatedNode instanceof TryStatement) { + flowInfo = flowInfo + .copy() + .addInitializationsFrom( + ((TryStatement) traversedContext.associatedNode).subRoutineInits); } traversedContext = traversedContext.parent; } - // if reaches this point, then there are some remaining unhandled exception types. + // if reaches this point, then there are some remaining unhandled + // exception types. scope.problemReporter().unhandledException(raisedException, location); } @@ -283,7 +306,7 @@ public class FlowContext implements TypeConstants { } char[] currentLabelName; if (((currentLabelName = current.labelName()) != null) - && CharOperation.equals(currentLabelName, labelName)) { + && CharOperation.equals(currentLabelName, labelName)) { if (lastNonReturningSubRoutine == null) { return current; } else { @@ -313,14 +336,15 @@ public class FlowContext implements TypeConstants { lastContinuable = current; } } - + char[] currentLabelName; - if ((currentLabelName = current.labelName()) != null && CharOperation.equals(currentLabelName, labelName)) { + if ((currentLabelName = current.labelName()) != null + && CharOperation.equals(currentLabelName, labelName)) { - // matching label found + // matching label found if ((lastContinuable != null) - && (current.associatedNode.concreteStatement() == lastContinuable.associatedNode)) { - + && (current.associatedNode.concreteStatement() == lastContinuable.associatedNode)) { + if (lastNonReturningSubRoutine == null) { return lastContinuable; } else { @@ -429,9 +453,8 @@ public class FlowContext implements TypeConstants { public void recordContinueFrom(FlowInfo flowInfo) { } - boolean recordFinalAssignment( - VariableBinding variable, - Reference finalReference) { + boolean recordFinalAssignment(VariableBinding variable, + Reference finalReference) { return true; // keep going } @@ -439,9 +462,8 @@ public class FlowContext implements TypeConstants { public void recordReturnFrom(FlowInfo flowInfo) { } - public void recordSettingFinal( - VariableBinding variable, - Reference finalReference) { + public void recordSettingFinal(VariableBinding variable, + Reference finalReference) { // for initialization inside looping statement that effectively loops FlowContext context = this; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/FlowInfo.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/FlowInfo.java index dfa74a9..141541e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/FlowInfo.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/FlowInfo.java @@ -18,13 +18,17 @@ import net.sourceforge.phpdt.internal.compiler.lookup.LocalVariableBinding; public abstract class FlowInfo { public final static int REACHABLE = 0; - public final static int UNREACHABLE = 1; - - public static final UnconditionalFlowInfo DEAD_END; // Represents a dead branch status of initialization + + public final static int UNREACHABLE = 1; + + public static final UnconditionalFlowInfo DEAD_END; // Represents a dead + // branch status of + // initialization static { DEAD_END = new UnconditionalFlowInfo(); DEAD_END.reachMode = UNREACHABLE; } + abstract public FlowInfo addInitializationsFrom(FlowInfo otherInits); abstract public FlowInfo addPotentialInitializationsFrom(FlowInfo otherInits); @@ -34,15 +38,18 @@ public abstract class FlowInfo { return this; } - public boolean complainIfUnreachable(Statement statement, BlockScope scope, boolean didAlreadyComplain) { + public boolean complainIfUnreachable(Statement statement, BlockScope scope, + boolean didAlreadyComplain) { // Report an error if necessary return false; } - public static FlowInfo conditional(FlowInfo initsWhenTrue, FlowInfo initsWhenFalse){ + public static FlowInfo conditional(FlowInfo initsWhenTrue, + FlowInfo initsWhenFalse) { - // if (initsWhenTrue.equals(initsWhenFalse)) return initsWhenTrue; -- could optimize if #equals is defined + // if (initsWhenTrue.equals(initsWhenFalse)) return initsWhenTrue; -- + // could optimize if #equals is defined return new ConditionalFlowInfo(initsWhenTrue, initsWhenFalse); } @@ -61,28 +68,28 @@ public abstract class FlowInfo { /** * Check status of definite assignment for a field. */ - abstract public boolean isDefinitelyAssigned(FieldBinding field); + abstract public boolean isDefinitelyAssigned(FieldBinding field); /** * Check status of definite assignment for a local. */ public abstract boolean isDefinitelyAssigned(LocalVariableBinding local); - //abstract public int reachMode(); + // abstract public int reachMode(); /** * Check status of potential assignment for a field. */ - abstract public boolean isPotentiallyAssigned(FieldBinding field); + abstract public boolean isPotentiallyAssigned(FieldBinding field); /** * Check status of potential assignment for a local variable. */ - abstract public boolean isPotentiallyAssigned(LocalVariableBinding field); + abstract public boolean isPotentiallyAssigned(LocalVariableBinding field); abstract public boolean isReachable(); - + /** * Record a field got definitely assigned. */ @@ -108,16 +115,18 @@ public abstract class FlowInfo { abstract public FlowInfo setReachMode(int reachMode); /** - * Returns the receiver updated in the following way:
              - *
            • intersection of definitely assigned variables, + * Returns the receiver updated in the following way: + *
                + *
              • intersection of definitely assigned variables, *
              • union of potentially assigned variables. *
              */ - abstract public UnconditionalFlowInfo mergedWith(UnconditionalFlowInfo otherInits); + abstract public UnconditionalFlowInfo mergedWith( + UnconditionalFlowInfo otherInits); - public String toString(){ + public String toString() { - if (this == DEAD_END){ + if (this == DEAD_END) { return "FlowInfo.DEAD_END"; //$NON-NLS-1$ } return super.toString(); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/InitializationFlowContext.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/InitializationFlowContext.java index 10e348e..03b3e3b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/InitializationFlowContext.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/InitializationFlowContext.java @@ -16,82 +16,64 @@ import net.sourceforge.phpdt.internal.compiler.lookup.ReferenceBinding; import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; /** - * Reflects the context of code analysis, keeping track of enclosing - * try statements, exception handlers, etc... + * Reflects the context of code analysis, keeping track of enclosing try + * statements, exception handlers, etc... */ public class InitializationFlowContext extends ExceptionHandlingFlowContext { public int exceptionCount; + public TypeBinding[] thrownExceptions = new TypeBinding[5]; + public ASTNode[] exceptionThrowers = new ASTNode[5]; + public FlowInfo[] exceptionThrowerFlowInfos = new FlowInfo[5]; - - public InitializationFlowContext( - FlowContext parent, - ASTNode associatedNode, - BlockScope scope) { - super( - parent, - associatedNode, - NoExceptions, // no exception allowed by default - scope, - FlowInfo.DEAD_END); + + public InitializationFlowContext(FlowContext parent, + ASTNode associatedNode, BlockScope scope) { + super(parent, associatedNode, NoExceptions, // no exception allowed by + // default + scope, FlowInfo.DEAD_END); } - public void checkInitializerExceptions( - BlockScope currentScope, - FlowContext initializerContext, - FlowInfo flowInfo) { + public void checkInitializerExceptions(BlockScope currentScope, + FlowContext initializerContext, FlowInfo flowInfo) { for (int i = 0; i < exceptionCount; i++) { - initializerContext.checkExceptionHandlers( - thrownExceptions[i], - exceptionThrowers[i], - exceptionThrowerFlowInfos[i], - currentScope); + initializerContext.checkExceptionHandlers(thrownExceptions[i], + exceptionThrowers[i], exceptionThrowerFlowInfos[i], + currentScope); } } public String individualToString() { - + StringBuffer buffer = new StringBuffer("Initialization flow context"); //$NON-NLS-1$ for (int i = 0; i < exceptionCount; i++) { buffer.append('[').append(thrownExceptions[i].readableName()); - buffer.append('-').append(exceptionThrowerFlowInfos[i].toString()).append(']'); + buffer.append('-').append(exceptionThrowerFlowInfos[i].toString()) + .append(']'); } return buffer.toString(); } - - public void recordHandlingException( - ReferenceBinding exceptionType, - UnconditionalFlowInfo flowInfo, - TypeBinding raisedException, - ASTNode invocationSite, - boolean wasMasked) { - - // even if unreachable code, need to perform unhandled exception diagnosis + + public void recordHandlingException(ReferenceBinding exceptionType, + UnconditionalFlowInfo flowInfo, TypeBinding raisedException, + ASTNode invocationSite, boolean wasMasked) { + + // even if unreachable code, need to perform unhandled exception + // diagnosis int size = thrownExceptions.length; if (exceptionCount == size) { - System.arraycopy( - thrownExceptions, - 0, - (thrownExceptions = new TypeBinding[size * 2]), - 0, - size); - System.arraycopy( - exceptionThrowers, - 0, - (exceptionThrowers = new ASTNode[size * 2]), - 0, - size); - System.arraycopy( - exceptionThrowerFlowInfos, - 0, - (exceptionThrowerFlowInfos = new FlowInfo[size * 2]), - 0, - size); + System.arraycopy(thrownExceptions, 0, + (thrownExceptions = new TypeBinding[size * 2]), 0, size); + System.arraycopy(exceptionThrowers, 0, + (exceptionThrowers = new ASTNode[size * 2]), 0, size); + System.arraycopy(exceptionThrowerFlowInfos, 0, + (exceptionThrowerFlowInfos = new FlowInfo[size * 2]), 0, + size); } thrownExceptions[exceptionCount] = raisedException; exceptionThrowers[exceptionCount] = invocationSite; exceptionThrowerFlowInfos[exceptionCount++] = flowInfo.copy(); - } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/InsideSubRoutineFlowContext.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/InsideSubRoutineFlowContext.java index b124402..592d957 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/InsideSubRoutineFlowContext.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/InsideSubRoutineFlowContext.java @@ -13,46 +13,48 @@ package net.sourceforge.phpdt.internal.compiler.flow; import net.sourceforge.phpdt.internal.compiler.ast.ASTNode; /** - * Reflects the context of code analysis, keeping track of enclosing - * try statements, exception handlers, etc... + * Reflects the context of code analysis, keeping track of enclosing try + * statements, exception handlers, etc... */ public class InsideSubRoutineFlowContext extends FlowContext { public UnconditionalFlowInfo initsOnReturn; - - public InsideSubRoutineFlowContext( - FlowContext parent, - ASTNode associatedNode) { + + public InsideSubRoutineFlowContext(FlowContext parent, + ASTNode associatedNode) { super(parent, associatedNode); - this.initsOnReturn = FlowInfo.DEAD_END; + this.initsOnReturn = FlowInfo.DEAD_END; } public String individualToString() { - + StringBuffer buffer = new StringBuffer("Inside SubRoutine flow context"); //$NON-NLS-1$ - buffer.append("[initsOnReturn -").append(initsOnReturn.toString()).append(']'); //$NON-NLS-1$ + buffer + .append("[initsOnReturn -").append(initsOnReturn.toString()).append(']'); //$NON-NLS-1$ return buffer.toString(); } - - public UnconditionalFlowInfo initsOnReturn(){ + + public UnconditionalFlowInfo initsOnReturn() { return this.initsOnReturn; } - + public boolean isNonReturningContext() { return associatedNode.cannotReturn(); } - + public ASTNode subRoutine() { return associatedNode; } - + public void recordReturnFrom(FlowInfo flowInfo) { - if (!flowInfo.isReachable()) return; + if (!flowInfo.isReachable()) + return; if (initsOnReturn == FlowInfo.DEAD_END) { initsOnReturn = flowInfo.copy().unconditionalInits(); } else { - initsOnReturn = initsOnReturn.mergedWith(flowInfo.unconditionalInits()); + initsOnReturn = initsOnReturn.mergedWith(flowInfo + .unconditionalInits()); } } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/LabelFlowContext.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/LabelFlowContext.java index 47ca611..2850d36 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/LabelFlowContext.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/LabelFlowContext.java @@ -16,34 +16,31 @@ import net.sourceforge.phpdt.internal.compiler.codegen.Label; import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; /** - * Reflects the context of code analysis, keeping track of enclosing - * try statements, exception handlers, etc... + * Reflects the context of code analysis, keeping track of enclosing try + * statements, exception handlers, etc... */ public class LabelFlowContext extends SwitchFlowContext { - + public char[] labelName; - - public LabelFlowContext( - FlowContext parent, - ASTNode associatedNode, - char[] labelName, - Label breakLabel, - BlockScope scope) { - + + public LabelFlowContext(FlowContext parent, ASTNode associatedNode, + char[] labelName, Label breakLabel, BlockScope scope) { + super(parent, associatedNode, breakLabel); this.labelName = labelName; checkLabelValidity(scope); } void checkLabelValidity(BlockScope scope) { - + // check if label was already defined above FlowContext current = parent; while (current != null) { char[] currentLabelName; if (((currentLabelName = current.labelName()) != null) - && CharOperation.equals(currentLabelName, labelName)) { - scope.problemReporter().alreadyDefinedLabel(labelName, associatedNode); + && CharOperation.equals(currentLabelName, labelName)) { + scope.problemReporter().alreadyDefinedLabel(labelName, + associatedNode); } current = current.parent; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/LoopingFlowContext.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/LoopingFlowContext.java index 130fd4e..c052e07 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/LoopingFlowContext.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/LoopingFlowContext.java @@ -20,52 +20,58 @@ import net.sourceforge.phpdt.internal.compiler.lookup.Scope; import net.sourceforge.phpdt.internal.compiler.lookup.VariableBinding; /** - * Reflects the context of code analysis, keeping track of enclosing - * try statements, exception handlers, etc... + * Reflects the context of code analysis, keeping track of enclosing try + * statements, exception handlers, etc... */ public class LoopingFlowContext extends SwitchFlowContext { - + public Label continueLabel; + public UnconditionalFlowInfo initsOnContinue = FlowInfo.DEAD_END; + Reference finalAssignments[]; + VariableBinding finalVariables[]; + int assignCount = 0; + Scope associatedScope; - - public LoopingFlowContext( - FlowContext parent, - ASTNode associatedNode, - Label breakLabel, - Label continueLabel, - Scope associatedScope) { + + public LoopingFlowContext(FlowContext parent, ASTNode associatedNode, + Label breakLabel, Label continueLabel, Scope associatedScope) { super(parent, associatedNode, breakLabel); this.continueLabel = continueLabel; this.associatedScope = associatedScope; } - - public void complainOnFinalAssignmentsInLoop( - BlockScope scope, - FlowInfo flowInfo) { + + public void complainOnFinalAssignmentsInLoop(BlockScope scope, + FlowInfo flowInfo) { for (int i = 0; i < assignCount; i++) { VariableBinding variable = finalVariables[i]; - if (variable == null) continue; - boolean complained = false; // remember if have complained on this final assignment + if (variable == null) + continue; + boolean complained = false; // remember if have complained on this + // final assignment if (variable instanceof FieldBinding) { if (flowInfo.isPotentiallyAssigned((FieldBinding) variable)) { complained = true; - scope.problemReporter().duplicateInitializationOfBlankFinalField( - (FieldBinding) variable, - finalAssignments[i]); + scope.problemReporter() + .duplicateInitializationOfBlankFinalField( + (FieldBinding) variable, + finalAssignments[i]); } } else { - if (flowInfo.isPotentiallyAssigned((LocalVariableBinding) variable)) { + if (flowInfo + .isPotentiallyAssigned((LocalVariableBinding) variable)) { complained = true; - scope.problemReporter().duplicateInitializationOfFinalLocal( - (LocalVariableBinding) variable, - finalAssignments[i]); + scope.problemReporter() + .duplicateInitializationOfFinalLocal( + (LocalVariableBinding) variable, + finalAssignments[i]); } } - // any reference reported at this level is removed from the parent context where it + // any reference reported at this level is removed from the parent + // context where it // could also be reported again if (complained) { FlowContext context = parent; @@ -83,8 +89,10 @@ public class LoopingFlowContext extends SwitchFlowContext { public String individualToString() { StringBuffer buffer = new StringBuffer("Looping flow context"); //$NON-NLS-1$ - buffer.append("[initsOnBreak -").append(initsOnBreak.toString()).append(']'); //$NON-NLS-1$ - buffer.append("[initsOnContinue -").append(initsOnContinue.toString()).append(']'); //$NON-NLS-1$ + buffer + .append("[initsOnBreak -").append(initsOnBreak.toString()).append(']'); //$NON-NLS-1$ + buffer + .append("[initsOnContinue -").append(initsOnContinue.toString()).append(']'); //$NON-NLS-1$ return buffer.toString(); } @@ -98,17 +106,19 @@ public class LoopingFlowContext extends SwitchFlowContext { public void recordContinueFrom(FlowInfo flowInfo) { - if (!flowInfo.isReachable()) return; + if (!flowInfo.isReachable()) + return; if (initsOnContinue == FlowInfo.DEAD_END) { initsOnContinue = flowInfo.copy().unconditionalInits(); } else { - initsOnContinue = initsOnContinue.mergedWith(flowInfo.unconditionalInits()); - }; + initsOnContinue = initsOnContinue.mergedWith(flowInfo + .unconditionalInits()); + } + ; } - boolean recordFinalAssignment( - VariableBinding binding, - Reference finalAssignment) { + boolean recordFinalAssignment(VariableBinding binding, + Reference finalAssignment) { // do not consider variables which are defined inside this loop if (binding instanceof LocalVariableBinding) { Scope scope = ((LocalVariableBinding) binding).declaringScope; @@ -122,19 +132,14 @@ public class LoopingFlowContext extends SwitchFlowContext { finalVariables = new VariableBinding[5]; } else { if (assignCount == finalAssignments.length) - System.arraycopy( - finalAssignments, - 0, - (finalAssignments = new Reference[assignCount * 2]), - 0, + System.arraycopy(finalAssignments, 0, + (finalAssignments = new Reference[assignCount * 2]), 0, + assignCount); + System.arraycopy(finalVariables, 0, + (finalVariables = new VariableBinding[assignCount * 2]), 0, assignCount); - System.arraycopy( - finalVariables, - 0, - (finalVariables = new VariableBinding[assignCount * 2]), - 0, - assignCount); - }; + } + ; finalAssignments[assignCount] = finalAssignment; finalVariables[assignCount++] = binding; return true; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/SwitchFlowContext.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/SwitchFlowContext.java index fc455c7..26a050d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/SwitchFlowContext.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/SwitchFlowContext.java @@ -14,17 +14,16 @@ import net.sourceforge.phpdt.internal.compiler.ast.ASTNode; import net.sourceforge.phpdt.internal.compiler.codegen.Label; /** - * Reflects the context of code analysis, keeping track of enclosing - * try statements, exception handlers, etc... + * Reflects the context of code analysis, keeping track of enclosing try + * statements, exception handlers, etc... */ public class SwitchFlowContext extends FlowContext { public Label breakLabel; + public UnconditionalFlowInfo initsOnBreak = FlowInfo.DEAD_END; - - public SwitchFlowContext( - FlowContext parent, - ASTNode associatedNode, - Label breakLabel) { + + public SwitchFlowContext(FlowContext parent, ASTNode associatedNode, + Label breakLabel) { super(parent, associatedNode); this.breakLabel = breakLabel; } @@ -35,7 +34,8 @@ public class SwitchFlowContext extends FlowContext { public String individualToString() { StringBuffer buffer = new StringBuffer("Switch flow context"); //$NON-NLS-1$ - buffer.append("[initsOnBreak -").append(initsOnBreak.toString()).append(']'); //$NON-NLS-1$ + buffer + .append("[initsOnBreak -").append(initsOnBreak.toString()).append(']'); //$NON-NLS-1$ return buffer.toString(); } @@ -48,7 +48,9 @@ public class SwitchFlowContext extends FlowContext { if (initsOnBreak == FlowInfo.DEAD_END) { initsOnBreak = flowInfo.copy().unconditionalInits(); } else { - initsOnBreak = initsOnBreak.mergedWith(flowInfo.unconditionalInits()); - }; + initsOnBreak = initsOnBreak.mergedWith(flowInfo + .unconditionalInits()); + } + ; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/UnconditionalFlowInfo.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/UnconditionalFlowInfo.java index 9aa6a34..6907f62 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/UnconditionalFlowInfo.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/flow/UnconditionalFlowInfo.java @@ -17,21 +17,23 @@ import net.sourceforge.phpdt.internal.compiler.lookup.ReferenceBinding; /** * Record initialization status during definite assignment analysis - * + * * No caching of pre-allocated instances. */ public class UnconditionalFlowInfo extends FlowInfo { - public long definiteInits; + public long potentialInits; + public long extraDefiniteInits[]; + public long extraPotentialInits[]; - + public int reachMode = REACHABLE; // by default public int maxFieldCount; - + // Constants public static final int BitCacheSize = 64; // 64 bits in a long. @@ -44,24 +46,29 @@ public class UnconditionalFlowInfo extends FlowInfo { if (this == DEAD_END) return this; - UnconditionalFlowInfo otherInits = inits.unconditionalInits(); + UnconditionalFlowInfo otherInits = inits.unconditionalInits(); if (otherInits == DEAD_END) return this; - - // union of definitely assigned variables, + + // union of definitely assigned variables, definiteInits |= otherInits.definiteInits; // union of potentially set ones potentialInits |= otherInits.potentialInits; - + // treating extra storage if (extraDefiniteInits != null) { if (otherInits.extraDefiniteInits != null) { // both sides have extra storage int i = 0, length, otherLength; if ((length = extraDefiniteInits.length) < (otherLength = otherInits.extraDefiniteInits.length)) { - // current storage is shorter -> grow current (could maybe reuse otherInits extra storage?) - System.arraycopy(extraDefiniteInits, 0, (extraDefiniteInits = new long[otherLength]), 0, length); - System.arraycopy(extraPotentialInits, 0, (extraPotentialInits = new long[otherLength]), 0, length); + // current storage is shorter -> grow current (could maybe + // reuse otherInits extra storage?) + System.arraycopy(extraDefiniteInits, 0, + (extraDefiniteInits = new long[otherLength]), 0, + length); + System.arraycopy(extraPotentialInits, 0, + (extraPotentialInits = new long[otherLength]), 0, + length); while (i < length) { extraDefiniteInits[i] |= otherInits.extraDefiniteInits[i]; extraPotentialInits[i] |= otherInits.extraPotentialInits[i++]; @@ -81,39 +88,50 @@ public class UnconditionalFlowInfo extends FlowInfo { } else { // no extra storage on otherInits } - } else - if (otherInits.extraDefiniteInits != null) { - // no storage here, but other has extra storage. - int otherLength; - System.arraycopy(otherInits.extraDefiniteInits, 0, (extraDefiniteInits = new long[otherLength = otherInits.extraDefiniteInits.length]), 0, otherLength); - System.arraycopy(otherInits.extraPotentialInits, 0, (extraPotentialInits = new long[otherLength]), 0, otherLength); - } + } else if (otherInits.extraDefiniteInits != null) { + // no storage here, but other has extra storage. + int otherLength; + System + .arraycopy( + otherInits.extraDefiniteInits, + 0, + (extraDefiniteInits = new long[otherLength = otherInits.extraDefiniteInits.length]), + 0, otherLength); + System.arraycopy(otherInits.extraPotentialInits, 0, + (extraPotentialInits = new long[otherLength]), 0, + otherLength); + } return this; } // unions of both sets of initialization - used for try/finally public FlowInfo addPotentialInitializationsFrom(FlowInfo inits) { - - if (this == DEAD_END){ + + if (this == DEAD_END) { return this; } UnconditionalFlowInfo otherInits = inits.unconditionalInits(); - if (otherInits == DEAD_END){ + if (otherInits == DEAD_END) { return this; } // union of potentially set ones potentialInits |= otherInits.potentialInits; - + // treating extra storage if (extraDefiniteInits != null) { if (otherInits.extraDefiniteInits != null) { // both sides have extra storage int i = 0, length, otherLength; if ((length = extraDefiniteInits.length) < (otherLength = otherInits.extraDefiniteInits.length)) { - // current storage is shorter -> grow current (could maybe reuse otherInits extra storage?) - System.arraycopy(extraDefiniteInits, 0, (extraDefiniteInits = new long[otherLength]), 0, length); - System.arraycopy(extraPotentialInits, 0, (extraPotentialInits = new long[otherLength]), 0, length); + // current storage is shorter -> grow current (could maybe + // reuse otherInits extra storage?) + System.arraycopy(extraDefiniteInits, 0, + (extraDefiniteInits = new long[otherLength]), 0, + length); + System.arraycopy(extraPotentialInits, 0, + (extraPotentialInits = new long[otherLength]), 0, + length); while (i < length) { extraPotentialInits[i] |= otherInits.extraPotentialInits[i++]; } @@ -127,66 +145,75 @@ public class UnconditionalFlowInfo extends FlowInfo { } } } - } else - if (otherInits.extraDefiniteInits != null) { - // no storage here, but other has extra storage. - int otherLength; - extraDefiniteInits = new long[otherLength = otherInits.extraDefiniteInits.length]; - System.arraycopy(otherInits.extraPotentialInits, 0, (extraPotentialInits = new long[otherLength]), 0, otherLength); - } + } else if (otherInits.extraDefiniteInits != null) { + // no storage here, but other has extra storage. + int otherLength; + extraDefiniteInits = new long[otherLength = otherInits.extraDefiniteInits.length]; + System.arraycopy(otherInits.extraPotentialInits, 0, + (extraPotentialInits = new long[otherLength]), 0, + otherLength); + } return this; } // Report an error if necessary -// public boolean complainIfUnreachable(Statement statement, BlockScope scope, boolean didAlreadyComplain) { -// -// if ((this.reachMode & UNREACHABLE) != 0) { -// statement.bits &= ~ASTNode.IsReachableMASK; -// boolean reported = this == DEAD_END; -// if (!didAlreadyComplain && reported) { -// scope.problemReporter().unreachableCode(statement); -// } -// return reported; // keep going for fake reachable -// } -// return false; -// } - + // public boolean complainIfUnreachable(Statement statement, BlockScope + // scope, boolean didAlreadyComplain) { + // + // if ((this.reachMode & UNREACHABLE) != 0) { + // statement.bits &= ~ASTNode.IsReachableMASK; + // boolean reported = this == DEAD_END; + // if (!didAlreadyComplain && reported) { + // scope.problemReporter().unreachableCode(statement); + // } + // return reported; // keep going for fake reachable + // } + // return false; + // } + /** * Answers a copy of the current instance */ public FlowInfo copy() { - + // do not clone the DeadEnd if (this == DEAD_END) return this; - + // look for an unused preallocated object UnconditionalFlowInfo copy = new UnconditionalFlowInfo(); - + // copy slots copy.definiteInits = this.definiteInits; copy.potentialInits = this.potentialInits; copy.reachMode = this.reachMode; copy.maxFieldCount = this.maxFieldCount; - + if (this.extraDefiniteInits != null) { int length; - System.arraycopy(this.extraDefiniteInits, 0, (copy.extraDefiniteInits = new long[ (length = extraDefiniteInits.length)]), 0, length); - System.arraycopy(this.extraPotentialInits, 0, (copy.extraPotentialInits = new long[length]), 0, length); - }; + System + .arraycopy( + this.extraDefiniteInits, + 0, + (copy.extraDefiniteInits = new long[(length = extraDefiniteInits.length)]), + 0, length); + System.arraycopy(this.extraPotentialInits, 0, + (copy.extraPotentialInits = new long[length]), 0, length); + } + ; return copy; } - - public UnconditionalFlowInfo discardFieldInitializations(){ - + + public UnconditionalFlowInfo discardFieldInitializations() { + int limit = this.maxFieldCount; - + if (limit < BitCacheSize) { - long mask = (1L << limit)-1; + long mask = (1L << limit) - 1; this.definiteInits &= ~mask; this.potentialInits &= ~mask; return this; - } + } this.definiteInits = 0; this.potentialInits = 0; @@ -203,22 +230,22 @@ public class UnconditionalFlowInfo extends FlowInfo { this.extraDefiniteInits[i] = 0L; this.extraPotentialInits[i] = 0L; } - long mask = (1L << (limit % BitCacheSize))-1; + long mask = (1L << (limit % BitCacheSize)) - 1; this.extraDefiniteInits[vectorIndex] &= ~mask; this.extraPotentialInits[vectorIndex] &= ~mask; return this; } - public UnconditionalFlowInfo discardNonFieldInitializations(){ - + public UnconditionalFlowInfo discardNonFieldInitializations() { + int limit = this.maxFieldCount; - + if (limit < BitCacheSize) { - long mask = (1L << limit)-1; + long mask = (1L << limit) - 1; this.definiteInits &= mask; this.potentialInits &= mask; return this; - } + } // use extra vector if (extraDefiniteInits == null) { return this; // if vector not yet allocated, then not initialized @@ -227,33 +254,33 @@ public class UnconditionalFlowInfo extends FlowInfo { if ((vectorIndex = (limit / BitCacheSize) - 1) >= length) { return this; // not enough room yet } - long mask = (1L << (limit % BitCacheSize))-1; + long mask = (1L << (limit % BitCacheSize)) - 1; this.extraDefiniteInits[vectorIndex] &= mask; this.extraPotentialInits[vectorIndex] &= mask; - for (int i = vectorIndex+1; i < length; i++) { + for (int i = vectorIndex + 1; i < length; i++) { this.extraDefiniteInits[i] = 0L; this.extraPotentialInits[i] = 0L; } return this; } - + public FlowInfo initsWhenFalse() { - + return this; } - + public FlowInfo initsWhenTrue() { - + return this; } - + /** - * Check status of definite assignment at a given position. - * It deals with the dual representation of the InitializationInfo2: - * bits for the first 64 entries, then an array of booleans. + * Check status of definite assignment at a given position. It deals with + * the dual representation of the InitializationInfo2: bits for the first 64 + * entries, then an array of booleans. */ final private boolean isDefinitelyAssigned(int position) { - + // Dependant of CodeStream.isDefinitelyAssigned(..) // id is zero-based if (position < BitCacheSize) { @@ -264,27 +291,28 @@ public class UnconditionalFlowInfo extends FlowInfo { return false; // if vector not yet allocated, then not initialized int vectorIndex; if ((vectorIndex = (position / BitCacheSize) - 1) >= extraDefiniteInits.length) - return false; // if not enough room in vector, then not initialized + return false; // if not enough room in vector, then not + // initialized return ((extraDefiniteInits[vectorIndex]) & (1L << (position % BitCacheSize))) != 0; } - + /** * Check status of definite assignment for a field. */ final public boolean isDefinitelyAssigned(FieldBinding field) { - + // Dependant of CodeStream.isDefinitelyAssigned(..) // We do not want to complain in unreachable code - if ((this.reachMode & UNREACHABLE) != 0) + if ((this.reachMode & UNREACHABLE) != 0) return true; - return isDefinitelyAssigned(field.id); + return isDefinitelyAssigned(field.id); } - + /** * Check status of definite assignment for a local. */ final public boolean isDefinitelyAssigned(LocalVariableBinding local) { - + // Dependant of CodeStream.isDefinitelyAssigned(..) // We do not want to complain in unreachable code if ((this.reachMode & UNREACHABLE) != 0) @@ -292,25 +320,26 @@ public class UnconditionalFlowInfo extends FlowInfo { if (local.isArgument) { return true; } - // final constants are inlined, and thus considered as always initialized + // final constants are inlined, and thus considered as always + // initialized if (local.constant != Constant.NotAConstant) { return true; } return isDefinitelyAssigned(local.id + maxFieldCount); } - + public boolean isReachable() { - + return this.reachMode == REACHABLE; } - + /** - * Check status of potential assignment at a given position. - * It deals with the dual representation of the InitializationInfo3: - * bits for the first 64 entries, then an array of booleans. + * Check status of potential assignment at a given position. It deals with + * the dual representation of the InitializationInfo3: bits for the first 64 + * entries, then an array of booleans. */ final private boolean isPotentiallyAssigned(int position) { - + // id is zero-based if (position < BitCacheSize) { // use bits @@ -321,42 +350,44 @@ public class UnconditionalFlowInfo extends FlowInfo { return false; // if vector not yet allocated, then not initialized int vectorIndex; if ((vectorIndex = (position / BitCacheSize) - 1) >= extraPotentialInits.length) - return false; // if not enough room in vector, then not initialized + return false; // if not enough room in vector, then not + // initialized return ((extraPotentialInits[vectorIndex]) & (1L << (position % BitCacheSize))) != 0; } - + /** * Check status of definite assignment for a field. */ final public boolean isPotentiallyAssigned(FieldBinding field) { - - return isPotentiallyAssigned(field.id); + + return isPotentiallyAssigned(field.id); } - + /** * Check status of potential assignment for a local. */ final public boolean isPotentiallyAssigned(LocalVariableBinding local) { - + if (local.isArgument) { return true; } - // final constants are inlined, and thus considered as always initialized + // final constants are inlined, and thus considered as always + // initialized if (local.constant != Constant.NotAConstant) { return true; } return isPotentiallyAssigned(local.id + maxFieldCount); } - + /** - * Record a definite assignment at a given position. - * It deals with the dual representation of the InitializationInfo2: - * bits for the first 64 entries, then an array of booleans. + * Record a definite assignment at a given position. It deals with the dual + * representation of the InitializationInfo2: bits for the first 64 entries, + * then an array of booleans. */ final private void markAsDefinitelyAssigned(int position) { - + if (this != DEAD_END) { - + // position is zero-based if (position < BitCacheSize) { // use bits @@ -373,8 +404,18 @@ public class UnconditionalFlowInfo extends FlowInfo { } else { int oldLength; // might need to grow the arrays if (vectorIndex >= (oldLength = extraDefiniteInits.length)) { - System.arraycopy(extraDefiniteInits, 0, (extraDefiniteInits = new long[vectorIndex + 1]), 0, oldLength); - System.arraycopy(extraPotentialInits, 0, (extraPotentialInits = new long[vectorIndex + 1]), 0, oldLength); + System + .arraycopy( + extraDefiniteInits, + 0, + (extraDefiniteInits = new long[vectorIndex + 1]), + 0, oldLength); + System + .arraycopy( + extraPotentialInits, + 0, + (extraPotentialInits = new long[vectorIndex + 1]), + 0, oldLength); } } long mask; @@ -383,7 +424,7 @@ public class UnconditionalFlowInfo extends FlowInfo { } } } - + /** * Record a field got definitely assigned. */ @@ -391,7 +432,7 @@ public class UnconditionalFlowInfo extends FlowInfo { if (this != DEAD_END) markAsDefinitelyAssigned(field.id); } - + /** * Record a local got definitely assigned. */ @@ -399,15 +440,15 @@ public class UnconditionalFlowInfo extends FlowInfo { if (this != DEAD_END) markAsDefinitelyAssigned(local.id + maxFieldCount); } - + /** - * Clear initialization information at a given position. - * It deals with the dual representation of the InitializationInfo2: - * bits for the first 64 entries, then an array of booleans. + * Clear initialization information at a given position. It deals with the + * dual representation of the InitializationInfo2: bits for the first 64 + * entries, then an array of booleans. */ final private void markAsDefinitelyNotAssigned(int position) { if (this != DEAD_END) { - + // position is zero-based if (position < BitCacheSize) { // use bits @@ -418,11 +459,11 @@ public class UnconditionalFlowInfo extends FlowInfo { // use extra vector int vectorIndex = (position / BitCacheSize) - 1; if (extraDefiniteInits == null) { - return; // nothing to do, it was not yet set + return; // nothing to do, it was not yet set } else { // might need to grow the arrays if (vectorIndex >= extraDefiniteInits.length) { - return; // nothing to do, it was not yet set + return; // nothing to do, it was not yet set } } long mask; @@ -431,62 +472,70 @@ public class UnconditionalFlowInfo extends FlowInfo { } } } - + /** * Clear the initialization info for a field */ public void markAsDefinitelyNotAssigned(FieldBinding field) { - + if (this != DEAD_END) markAsDefinitelyNotAssigned(field.id); } - + /** * Clear the initialization info for a local variable */ - + public void markAsDefinitelyNotAssigned(LocalVariableBinding local) { - + if (this != DEAD_END) markAsDefinitelyNotAssigned(local.id + maxFieldCount); } - + /** - * Returns the receiver updated in the following way:
                - *
              • intersection of definitely assigned variables, + * Returns the receiver updated in the following way: + *
                  + *
                • intersection of definitely assigned variables, *
                • union of potentially assigned variables. *
                */ public UnconditionalFlowInfo mergedWith(UnconditionalFlowInfo otherInits) { - - if (this == DEAD_END) return otherInits; - if (otherInits == DEAD_END) return this; - - if ((this.reachMode & UNREACHABLE) != (otherInits.reachMode & UNREACHABLE)){ - if ((this.reachMode & UNREACHABLE) != 0){ + + if (this == DEAD_END) + return otherInits; + if (otherInits == DEAD_END) + return this; + + if ((this.reachMode & UNREACHABLE) != (otherInits.reachMode & UNREACHABLE)) { + if ((this.reachMode & UNREACHABLE) != 0) { return otherInits; } else { return this; } } - + // if one branch is not fake reachable, then the merged one is reachable this.reachMode &= otherInits.reachMode; - - // intersection of definitely assigned variables, + + // intersection of definitely assigned variables, this.definiteInits &= otherInits.definiteInits; // union of potentially set ones this.potentialInits |= otherInits.potentialInits; - + // treating extra storage if (this.extraDefiniteInits != null) { if (otherInits.extraDefiniteInits != null) { // both sides have extra storage int i = 0, length, otherLength; if ((length = this.extraDefiniteInits.length) < (otherLength = otherInits.extraDefiniteInits.length)) { - // current storage is shorter -> grow current (could maybe reuse otherInits extra storage?) - System.arraycopy(this.extraDefiniteInits, 0, (this.extraDefiniteInits = new long[otherLength]), 0, length); - System.arraycopy(this.extraPotentialInits, 0, (this.extraPotentialInits = new long[otherLength]), 0, length); + // current storage is shorter -> grow current (could maybe + // reuse otherInits extra storage?) + System.arraycopy(this.extraDefiniteInits, 0, + (this.extraDefiniteInits = new long[otherLength]), + 0, length); + System.arraycopy(this.extraPotentialInits, 0, + (this.extraPotentialInits = new long[otherLength]), + 0, length); while (i < length) { this.extraDefiniteInits[i] &= otherInits.extraDefiniteInits[i]; this.extraPotentialInits[i] |= otherInits.extraPotentialInits[i++]; @@ -509,65 +558,68 @@ public class UnconditionalFlowInfo extends FlowInfo { while (i < length) this.extraDefiniteInits[i++] = 0; } - } else - if (otherInits.extraDefiniteInits != null) { - // no storage here, but other has extra storage. - int otherLength; - this.extraDefiniteInits = new long[otherLength = otherInits.extraDefiniteInits.length]; - System.arraycopy(otherInits.extraPotentialInits, 0, (this.extraPotentialInits = new long[otherLength]), 0, otherLength); - } + } else if (otherInits.extraDefiniteInits != null) { + // no storage here, but other has extra storage. + int otherLength; + this.extraDefiniteInits = new long[otherLength = otherInits.extraDefiniteInits.length]; + System.arraycopy(otherInits.extraPotentialInits, 0, + (this.extraPotentialInits = new long[otherLength]), 0, + otherLength); + } return this; } - + /* * Answer the total number of fields in enclosing types of a given type */ - static int numberOfEnclosingFields(ReferenceBinding type){ - + static int numberOfEnclosingFields(ReferenceBinding type) { + int count = 0; type = type.enclosingType(); - while(type != null) { + while (type != null) { count += type.fieldCount(); type = type.enclosingType(); } return count; } - - public int reachMode(){ + + public int reachMode() { return this.reachMode; } - + public FlowInfo setReachMode(int reachMode) { - - if (this == DEAD_END) return this; // cannot modify DEAD_END - + + if (this == DEAD_END) + return this; // cannot modify DEAD_END + // reset optional inits when becoming unreachable - if ((this.reachMode & UNREACHABLE) == 0 && (reachMode & UNREACHABLE) != 0) { + if ((this.reachMode & UNREACHABLE) == 0 + && (reachMode & UNREACHABLE) != 0) { this.potentialInits = 0; - if (this.extraPotentialInits != null){ - for (int i = 0, length = this.extraPotentialInits.length; i < length; i++){ + if (this.extraPotentialInits != null) { + for (int i = 0, length = this.extraPotentialInits.length; i < length; i++) { this.extraPotentialInits[i] = 0; } } - } + } this.reachMode = reachMode; - + return this; } - public String toString(){ - - if (this == DEAD_END){ + public String toString() { + + if (this == DEAD_END) { return "FlowInfo.DEAD_END"; //$NON-NLS-1$ } - return "FlowInfo"; //$NON-NLS-1$ + return "FlowInfo"; //$NON-NLS-1$ } - + public UnconditionalFlowInfo unconditionalInits() { - + // also see conditional inits, where it requests them to merge return this; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/BooleanConstant.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/BooleanConstant.java index 6af6c00..8e34eb4 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/BooleanConstant.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/BooleanConstant.java @@ -13,26 +13,29 @@ package net.sourceforge.phpdt.internal.compiler.impl; public class BooleanConstant extends Constant { boolean value; - -public BooleanConstant(boolean value) { - this.value = value; -} -public boolean booleanValue() { - return (boolean) value; -} -public String stringValue() { - //spec 15.17.11 - - String s = new Boolean(value).toString() ; - if (s == null) - return "null"; //$NON-NLS-1$ - else - return s; -} -public String toString(){ + public BooleanConstant(boolean value) { + this.value = value; + } - return "(boolean)" + value ; } //$NON-NLS-1$ -public int typeID() { - return T_boolean; -} + public boolean booleanValue() { + return (boolean) value; + } + + public String stringValue() { + // spec 15.17.11 + + String s = new Boolean(value).toString(); + if (s == null) + return "null"; //$NON-NLS-1$ + else + return s; + } + + public String toString() { + + return "(boolean)" + value;} //$NON-NLS-1$ + + public int typeID() { + return T_boolean; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/CompilerOptions.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/CompilerOptions.java index d09ca41..409f590 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/CompilerOptions.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/CompilerOptions.java @@ -22,101 +22,173 @@ import net.sourceforge.phpdt.internal.compiler.env.IConstants; import net.sourceforge.phpdt.internal.compiler.lookup.ProblemReasons; import net.sourceforge.phpdt.internal.compiler.problem.ProblemSeverities; -public class CompilerOptions implements ProblemReasons, ProblemSeverities, IConstants { - +public class CompilerOptions implements ProblemReasons, ProblemSeverities, + IConstants { + /** * Option IDs */ - public static final String OPTION_PHPVarDeprecatedWarning = "net.sourceforge.phpeclipse.compiler.problem.phpVarDeprecatedWarning"; //$NON-NLS-1$ - public static final String OPTION_PHPBadStyleKeywordWarning = "net.sourceforge.phpeclipse.compiler.problem.phpBadStyleKeywordWarning"; //$NON-NLS-1$ - public static final String OPTION_PHPBadStyleUppercaseIdentifierWarning = "net.sourceforge.phpeclipse.compiler.problem.phpBadStyleUppercaseIdentifierWarning"; //$NON-NLS-1$ - public static final String OPTION_PHPIncludeNotExistWarning = "net.sourceforge.phpeclipse.compiler.problem.phpIncludeNotExistWarning"; //$NON-NLS-1$ - public static final String OPTION_UninitializedLocalVariableWarning = "net.sourceforge.phpeclipse.compiler.problem.uninitializedLocalVariableWarning"; //$NON-NLS-1$ - public static final String OPTION_CodeCannotBeReachedWarning = "net.sourceforge.phpeclipse.compiler.problem.codeCannotBeReachedWarning"; //$NON-NLS-1$ - - public static final String OPTION_LocalVariableAttribute = "net.sourceforge.phpeclipse.compiler.debug.localVariable"; //$NON-NLS-1$ + public static final String OPTION_PHPVarDeprecatedWarning = "net.sourceforge.phpeclipse.compiler.problem.phpVarDeprecatedWarning"; //$NON-NLS-1$ + + public static final String OPTION_PHPBadStyleKeywordWarning = "net.sourceforge.phpeclipse.compiler.problem.phpBadStyleKeywordWarning"; //$NON-NLS-1$ + + public static final String OPTION_PHPBadStyleUppercaseIdentifierWarning = "net.sourceforge.phpeclipse.compiler.problem.phpBadStyleUppercaseIdentifierWarning"; //$NON-NLS-1$ + + public static final String OPTION_PHPIncludeNotExistWarning = "net.sourceforge.phpeclipse.compiler.problem.phpIncludeNotExistWarning"; //$NON-NLS-1$ + + public static final String OPTION_UninitializedLocalVariableWarning = "net.sourceforge.phpeclipse.compiler.problem.uninitializedLocalVariableWarning"; //$NON-NLS-1$ + + public static final String OPTION_CodeCannotBeReachedWarning = "net.sourceforge.phpeclipse.compiler.problem.codeCannotBeReachedWarning"; //$NON-NLS-1$ + + public static final String OPTION_LocalVariableAttribute = "net.sourceforge.phpeclipse.compiler.debug.localVariable"; //$NON-NLS-1$ + public static final String OPTION_LineNumberAttribute = "net.sourceforge.phpeclipse.compiler.debug.lineNumber"; //$NON-NLS-1$ + public static final String OPTION_SourceFileAttribute = "net.sourceforge.phpeclipse.compiler.debug.sourceFile"; //$NON-NLS-1$ -// public static final String OPTION_PreserveUnusedLocal = "net.sourceforge.phpeclipse.compiler.codegen.unusedLocal"; //$NON-NLS-1$ - public static final String OPTION_DocCommentSupport= "net.sourceforge.phpeclipse.compiler.doc.comment.support"; //$NON-NLS-1$ + // public static final String OPTION_PreserveUnusedLocal = + // "net.sourceforge.phpeclipse.compiler.codegen.unusedLocal"; //$NON-NLS-1$ + + public static final String OPTION_DocCommentSupport = "net.sourceforge.phpeclipse.compiler.doc.comment.support"; //$NON-NLS-1$ + public static final String OPTION_ReportMethodWithConstructorName = "net.sourceforge.phpeclipse.compiler.problem.methodWithConstructorName"; //$NON-NLS-1$ + public static final String OPTION_ReportOverridingPackageDefaultMethod = "net.sourceforge.phpeclipse.compiler.problem.overridingPackageDefaultMethod"; //$NON-NLS-1$ + public static final String OPTION_ReportDeprecation = "net.sourceforge.phpeclipse.compiler.problem.deprecation"; //$NON-NLS-1$ + public static final String OPTION_ReportDeprecationInDeprecatedCode = "net.sourceforge.phpeclipse.compiler.problem.deprecationInDeprecatedCode"; //$NON-NLS-1$ + public static final String OPTION_ReportDeprecationWhenOverridingDeprecatedMethod = "net.sourceforge.phpeclipse.compiler.problem.deprecationWhenOverridingDeprecatedMethod"; //$NON-NLS-1$ + public static final String OPTION_ReportHiddenCatchBlock = "net.sourceforge.phpeclipse.compiler.problem.hiddenCatchBlock"; //$NON-NLS-1$ + public static final String OPTION_ReportUnusedLocal = "net.sourceforge.phpeclipse.compiler.problem.unusedLocal"; //$NON-NLS-1$ + public static final String OPTION_ReportUnusedParameter = "net.sourceforge.phpeclipse.compiler.problem.unusedParameter"; //$NON-NLS-1$ + public static final String OPTION_ReportUnusedParameterWhenImplementingAbstract = "net.sourceforge.phpeclipse.compiler.problem.unusedParameterWhenImplementingAbstract"; //$NON-NLS-1$ + public static final String OPTION_ReportUnusedParameterWhenOverridingConcrete = "net.sourceforge.phpeclipse.compiler.problem.unusedParameterWhenOverridingConcrete"; //$NON-NLS-1$ + public static final String OPTION_ReportUnusedImport = "net.sourceforge.phpeclipse.compiler.problem.unusedImport"; //$NON-NLS-1$ + public static final String OPTION_ReportSyntheticAccessEmulation = "net.sourceforge.phpeclipse.compiler.problem.syntheticAccessEmulation"; //$NON-NLS-1$ + public static final String OPTION_ReportNoEffectAssignment = "net.sourceforge.phpeclipse.compiler.problem.noEffectAssignment"; //$NON-NLS-1$ + public static final String OPTION_ReportLocalVariableHiding = "net.sourceforge.phpeclipse.compiler.problem.localVariableHiding"; //$NON-NLS-1$ + public static final String OPTION_ReportSpecialParameterHidingField = "net.sourceforge.phpeclipse.compiler.problem.specialParameterHidingField"; //$NON-NLS-1$ + public static final String OPTION_ReportFieldHiding = "net.sourceforge.phpeclipse.compiler.problem.fieldHiding"; //$NON-NLS-1$ + public static final String OPTION_ReportPossibleAccidentalBooleanAssignment = "net.sourceforge.phpeclipse.compiler.problem.possibleAccidentalBooleanAssignment"; //$NON-NLS-1$ + public static final String OPTION_ReportNonExternalizedStringLiteral = "net.sourceforge.phpeclipse.compiler.problem.nonExternalizedStringLiteral"; //$NON-NLS-1$ + public static final String OPTION_ReportIncompatibleNonInheritedInterfaceMethod = "net.sourceforge.phpeclipse.compiler.problem.incompatibleNonInheritedInterfaceMethod"; //$NON-NLS-1$ + public static final String OPTION_ReportUnusedPrivateMember = "net.sourceforge.phpeclipse.compiler.problem.unusedPrivateMember"; //$NON-NLS-1$ + public static final String OPTION_ReportNoImplicitStringConversion = "net.sourceforge.phpeclipse.compiler.problem.noImplicitStringConversion"; //$NON-NLS-1$ + public static final String OPTION_ReportAssertIdentifier = "net.sourceforge.phpeclipse.compiler.problem.assertIdentifier"; //$NON-NLS-1$ + public static final String OPTION_ReportNonStaticAccessToStatic = "net.sourceforge.phpeclipse.compiler.problem.staticAccessReceiver"; //$NON-NLS-1$ + public static final String OPTION_ReportIndirectStaticAccess = "net.sourceforge.phpeclipse.compiler.problem.indirectStaticAccess"; //$NON-NLS-1$ + public static final String OPTION_ReportSuperfluousSemicolon = "net.sourceforge.phpeclipse.compiler.problem.superfluousSemicolon"; //$NON-NLS-1$ + public static final String OPTION_ReportUnnecessaryTypeCheck = "net.sourceforge.phpeclipse.compiler.problem.unnecessaryTypeCheck"; //$NON-NLS-1$ + public static final String OPTION_ReportUndocumentedEmptyBlock = "net.sourceforge.phpeclipse.compiler.problem.undocumentedEmptyBlock"; //$NON-NLS-1$ + public static final String OPTION_ReportInvalidJavadoc = "net.sourceforge.phpeclipse.compiler.problem.invalidJavadoc"; //$NON-NLS-1$ + public static final String OPTION_ReportInvalidJavadocTags = "net.sourceforge.phpeclipse.compiler.problem.invalidJavadocTags"; //$NON-NLS-1$ + public static final String OPTION_ReportInvalidJavadocTagsVisibility = "net.sourceforge.phpeclipse.compiler.problem.invalidJavadocTagsVisibility"; //$NON-NLS-1$ + public static final String OPTION_ReportMissingJavadocTags = "net.sourceforge.phpeclipse.compiler.problem.missingJavadocTags"; //$NON-NLS-1$ + public static final String OPTION_ReportMissingJavadocTagsVisibility = "net.sourceforge.phpeclipse.compiler.problem.missingJavadocTagsVisibility"; //$NON-NLS-1$ + public static final String OPTION_ReportMissingJavadocTagsOverriding = "net.sourceforge.phpeclipse.compiler.problem.missingJavadocTagsOverriding"; //$NON-NLS-1$ + public static final String OPTION_ReportMissingJavadocComments = "net.sourceforge.phpeclipse.compiler.problem.missingJavadocComments"; //$NON-NLS-1$ + public static final String OPTION_ReportMissingJavadocCommentsVisibility = "net.sourceforge.phpeclipse.compiler.problem.missingJavadocCommentsVisibility"; //$NON-NLS-1$ + public static final String OPTION_ReportMissingJavadocCommentsOverriding = "net.sourceforge.phpeclipse.compiler.problem.missingJavadocCommentsOverriding"; //$NON-NLS-1$ + public static final String OPTION_ReportFinallyBlockNotCompletingNormally = "net.sourceforge.phpeclipse.compiler.problem.finallyBlockNotCompletingNormally"; //$NON-NLS-1$ + public static final String OPTION_ReportUnusedDeclaredThrownException = "net.sourceforge.phpeclipse.compiler.problem.unusedDeclaredThrownException"; //$NON-NLS-1$ + public static final String OPTION_ReportUnusedDeclaredThrownExceptionWhenOverriding = "net.sourceforge.phpeclipse.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding"; //$NON-NLS-1$ + public static final String OPTION_ReportUnqualifiedFieldAccess = "net.sourceforge.phpeclipse.compiler.problem.unqualifiedFieldAccess"; //$NON-NLS-1$ -// public static final String OPTION_Source = "net.sourceforge.phpeclipse.compiler.source"; //$NON-NLS-1$ -// public static final String OPTION_TargetPlatform = "net.sourceforge.phpeclipse.compiler.codegen.targetPlatform"; //$NON-NLS-1$ -// public static final String OPTION_Compliance = "net.sourceforge.phpeclipse.compiler.compliance"; //$NON-NLS-1$ + // public static final String OPTION_Source = + // "net.sourceforge.phpeclipse.compiler.source"; //$NON-NLS-1$ + // public static final String OPTION_TargetPlatform = + // "net.sourceforge.phpeclipse.compiler.codegen.targetPlatform"; + // //$NON-NLS-1$ + // public static final String OPTION_Compliance = + // "net.sourceforge.phpeclipse.compiler.compliance"; //$NON-NLS-1$ + public static final String OPTION_Encoding = "net.sourceforge.phpeclipse.encoding"; //$NON-NLS-1$ + public static final String OPTION_MaxProblemPerUnit = "net.sourceforge.phpeclipse.compiler.maxProblemPerUnit"; //$NON-NLS-1$ + public static final String OPTION_TaskTags = "net.sourceforge.phpeclipse.compiler.taskTags"; //$NON-NLS-1$ + public static final String OPTION_TaskPriorities = "net.sourceforge.phpeclipse.compiler.taskPriorities"; //$NON-NLS-1$ - + // Backward compatibility public static final String OPTION_ReportInvalidAnnotation = "net.sourceforge.phpeclipse.compiler.problem.invalidAnnotation"; //$NON-NLS-1$ + public static final String OPTION_ReportMissingAnnotation = "net.sourceforge.phpeclipse.compiler.problem.missingAnnotation"; //$NON-NLS-1$ + public static final String OPTION_ReportMissingJavadoc = "net.sourceforge.phpeclipse.compiler.problem.missingJavadoc"; //$NON-NLS-1$ /* should surface ??? */ -// public static final String OPTION_PrivateConstructorAccess = "net.sourceforge.phpeclipse.compiler.codegen.constructorAccessEmulation"; //$NON-NLS-1$ - + // public static final String OPTION_PrivateConstructorAccess = + // "net.sourceforge.phpeclipse.compiler.codegen.constructorAccessEmulation"; + // //$NON-NLS-1$ /** * Possible values for configurable options */ public static final String GENERATE = "generate";//$NON-NLS-1$ + public static final String DO_NOT_GENERATE = "do not generate"; //$NON-NLS-1$ + public static final String PRESERVE = "preserve"; //$NON-NLS-1$ -// public static final String OPTIMIZE_OUT = "optimize out"; //$NON-NLS-1$ -// public static final String VERSION_1_1 = "1.1"; //$NON-NLS-1$ -// public static final String VERSION_1_2 = "1.2"; //$NON-NLS-1$ -// public static final String VERSION_1_3 = "1.3"; //$NON-NLS-1$ -// public static final String VERSION_1_4 = "1.4"; //$NON-NLS-1$ -// public static final String VERSION_1_5 = "1.5"; //$NON-NLS-1$ + // public static final String OPTIMIZE_OUT = "optimize out"; //$NON-NLS-1$ + // public static final String VERSION_1_1 = "1.1"; //$NON-NLS-1$ + // public static final String VERSION_1_2 = "1.2"; //$NON-NLS-1$ + // public static final String VERSION_1_3 = "1.3"; //$NON-NLS-1$ + // public static final String VERSION_1_4 = "1.4"; //$NON-NLS-1$ + // public static final String VERSION_1_5 = "1.5"; //$NON-NLS-1$ + public static final String ERROR = "error"; //$NON-NLS-1$ + public static final String WARNING = "warning"; //$NON-NLS-1$ + public static final String IGNORE = "ignore"; //$NON-NLS-1$ + public static final String ENABLED = "enabled"; //$NON-NLS-1$ + public static final String DISABLED = "disabled"; //$NON-NLS-1$ - public static final String PUBLIC = "public"; //$NON-NLS-1$ - public static final String PROTECTED = "protected"; //$NON-NLS-1$ - public static final String DEFAULT = "default"; //$NON-NLS-1$ - public static final String PRIVATE = "private"; //$NON-NLS-1$ - + + public static final String PUBLIC = "public"; //$NON-NLS-1$ + + public static final String PROTECTED = "protected"; //$NON-NLS-1$ + + public static final String DEFAULT = "default"; //$NON-NLS-1$ + + public static final String PRIVATE = "private"; //$NON-NLS-1$ + /** * Bit mask for configurable problems (error/warning threshold) */ @@ -125,98 +197,132 @@ public class CompilerOptions implements ProblemReasons, ProblemSeverities, ICons // 0x400L unused // 0x800L unused public static final long MethodWithConstructorName = 0x1000L; + public static final long OverriddenPackageDefaultMethod = 0x2000L; + public static final long UsingDeprecatedAPI = 0x4000L; + public static final long MaskedCatchBlock = 0x8000L; + public static final long UnusedLocalVariable = 0x10000L; + public static final long UnusedArgument = 0x20000L; + public static final long NoImplicitStringConversion = 0x40000L; + public static final long AccessEmulation = 0x80000L; + public static final long NonExternalizedString = 0x100000L; + public static final long AssertUsedAsAnIdentifier = 0x200000L; + public static final long UnusedImport = 0x400000L; + public static final long NonStaticAccessToStatic = 0x800000L; + public static final long Task = 0x1000000L; + public static final long NoEffectAssignment = 0x2000000L; + public static final long IncompatibleNonInheritedInterfaceMethod = 0x4000000L; + public static final long UnusedPrivateMember = 0x8000000L; + public static final long LocalVariableHiding = 0x10000000L; + public static final long FieldHiding = 0x20000000L; + public static final long AccidentalBooleanAssign = 0x40000000L; + public static final long SuperfluousSemicolon = 0x80000000L; + public static final long IndirectStaticAccess = 0x100000000L; + public static final long UndocumentedEmptyBlock = 0x200000000L; + public static final long UnnecessaryTypeCheck = 0x400000000L; + public static final long InvalidJavadoc = 0x800000000L; + public static final long FinallyBlockNotCompleting = 0x1000000000L; + public static final long UnusedDeclaredThrownException = 0x2000000000L; + public static final long UnqualifiedFieldAccess = 0x4000000000L; + public static final long MissingJavadocTags = 0x8000000000L; - public static final long MissingJavadocComments = 0x10000000000L; - - - public static final long PHPVarDeprecatedWarning = 0x20000000000L; + + public static final long MissingJavadocComments = 0x10000000000L; + + public static final long PHPVarDeprecatedWarning = 0x20000000000L; + public static final long PHPBadStyleKeywordWarning = 0x40000000000L; - public static final long PHPBadStyleUppercaseIdentifierWarning = 0x80000000000L; + + public static final long PHPBadStyleUppercaseIdentifierWarning = 0x80000000000L; + public static final long PHPIncludeNotExistWarning = 0x100000000000L; + public static final long UninitializedLocalVariableWarning = 0x200000000000L; + public static final long CodeCannotBeReachedWarning = 0x400000000000L; + // Default severity level for handlers public long errorThreshold = 0; - - public long warningThreshold = - MethodWithConstructorName - | UsingDeprecatedAPI - | MaskedCatchBlock - | OverriddenPackageDefaultMethod - | UnusedImport - | NonStaticAccessToStatic - | NoEffectAssignment - | IncompatibleNonInheritedInterfaceMethod - | NoImplicitStringConversion - | FinallyBlockNotCompleting - | AssertUsedAsAnIdentifier - | PHPVarDeprecatedWarning - | PHPBadStyleKeywordWarning - | PHPBadStyleUppercaseIdentifierWarning - | PHPIncludeNotExistWarning - | UninitializedLocalVariableWarning - | CodeCannotBeReachedWarning; - ; + + public long warningThreshold = MethodWithConstructorName + | UsingDeprecatedAPI | MaskedCatchBlock + | OverriddenPackageDefaultMethod | UnusedImport + | NonStaticAccessToStatic | NoEffectAssignment + | IncompatibleNonInheritedInterfaceMethod + | NoImplicitStringConversion | FinallyBlockNotCompleting + | AssertUsedAsAnIdentifier | PHPVarDeprecatedWarning + | PHPBadStyleKeywordWarning | PHPBadStyleUppercaseIdentifierWarning + | PHPIncludeNotExistWarning | UninitializedLocalVariableWarning + | CodeCannotBeReachedWarning;; // Debug attributes public static final int Source = 1; // SourceFileAttribute + public static final int Lines = 2; // LineNumberAttribute + public static final int Vars = 4; // LocalVariableTableAttribute // By default only lines and source attributes are generated. public int produceDebugAttributes = Lines | Source; -// public long complianceLevel = JDK1_4; // by default be compliant with 1.4 -// public long sourceLevel = JDK1_3; //1.3 source behavior by default -// public long targetJDK = JDK1_2; // default generates for JVM1.2 + // public long complianceLevel = JDK1_4; // by default be compliant with 1.4 + // public long sourceLevel = JDK1_3; //1.3 source behavior by default + // public long targetJDK = JDK1_2; // default generates for JVM1.2 + + // toggle private access emulation for 1.2 (constr. accessor has extra arg + // on constructor) or 1.3 (make private constructor default access when + // access needed) + public boolean isPrivateConstructorAccessChangingVisibility = false; // by + // default, + // follows + // 1.2 - // toggle private access emulation for 1.2 (constr. accessor has extra arg on constructor) or 1.3 (make private constructor default access when access needed) - public boolean isPrivateConstructorAccessChangingVisibility = false; // by default, follows 1.2 - // source encoding format - public String defaultEncoding = null; // will use the platform default encoding - + public String defaultEncoding = null; // will use the platform default + // encoding + // print what unit is being processed public boolean verbose = Compiler.DEBUG; // indicates if reference info is desired public boolean produceReferenceInfo = false; - // indicates if unused/optimizable local variables need to be preserved (debugging purpose) + // indicates if unused/optimizable local variables need to be preserved + // (debugging purpose) public boolean preserveAllLocalVariables = false; // indicates whether literal expressions are inlined at parse-time or not public boolean parseLiteralExpressionsAsConstants = true; // max problems per compilation unit - public int maxProblemsPerUnit = 100; // no more than 100 problems per default - + public int maxProblemsPerUnit = 100; // no more than 100 problems per + // default + // tags used to recognize tasks in comments public char[][] taskTags = null; @@ -225,145 +331,227 @@ public class CompilerOptions implements ProblemReasons, ProblemSeverities, ICons // deprecation report public boolean reportDeprecationInsideDeprecatedCode = false; + public boolean reportDeprecationWhenOverridingDeprecatedMethod = false; - + // unused parameters report public boolean reportUnusedParameterWhenImplementingAbstract = false; + public boolean reportUnusedParameterWhenOverridingConcrete = false; // unused declaration of thrown exception public boolean reportUnusedDeclaredThrownExceptionWhenOverriding = false; - + // constructor/setter parameter hiding public boolean reportSpecialParameterHidingField = false; // check javadoc comments - public int reportInvalidJavadocTagsVisibility = AccPrivate; - public boolean reportInvalidJavadocTags = true; + public int reportInvalidJavadocTagsVisibility = AccPrivate; + + public boolean reportInvalidJavadocTags = true; // check missing javadoc tags - public int reportMissingJavadocTagsVisibility = AccPrivate; + public int reportMissingJavadocTagsVisibility = AccPrivate; + public boolean reportMissingJavadocTagsOverriding = true; // check missing javadoc comments - public int reportMissingJavadocCommentsVisibility = AccPublic; - public boolean reportMissingJavadocCommentsOverriding = true; -// javadoc comment support + public int reportMissingJavadocCommentsVisibility = AccPublic; + + public boolean reportMissingJavadocCommentsOverriding = true; + + // javadoc comment support public boolean docCommentSupport = false; - - /** + + /** * Initializing the compiler options with defaults */ - public CompilerOptions(){ + public CompilerOptions() { // use default options } - /** + /** * Initializing the compiler options with external settings + * * @param settings */ - public CompilerOptions(Map settings){ + public CompilerOptions(Map settings) { - if (settings == null) return; - set(settings); + if (settings == null) + return; + set(settings); } public Map getMap() { Map optionsMap = new HashMap(30); - optionsMap.put(OPTION_PHPIncludeNotExistWarning, getSeverityString(PHPIncludeNotExistWarning)); - optionsMap.put(OPTION_PHPVarDeprecatedWarning, getSeverityString(PHPVarDeprecatedWarning)); - optionsMap.put(OPTION_PHPBadStyleKeywordWarning, getSeverityString(PHPBadStyleKeywordWarning)); - optionsMap.put(OPTION_PHPBadStyleUppercaseIdentifierWarning, getSeverityString(PHPBadStyleUppercaseIdentifierWarning)); - optionsMap.put(OPTION_UninitializedLocalVariableWarning, getSeverityString(UninitializedLocalVariableWarning)); - optionsMap.put(OPTION_CodeCannotBeReachedWarning, getSeverityString(CodeCannotBeReachedWarning)); - - optionsMap.put(OPTION_LocalVariableAttribute, (this.produceDebugAttributes & Vars) != 0 ? GENERATE : DO_NOT_GENERATE); - optionsMap.put(OPTION_LineNumberAttribute, (this.produceDebugAttributes & Lines) != 0 ? GENERATE : DO_NOT_GENERATE); - optionsMap.put(OPTION_SourceFileAttribute, (this.produceDebugAttributes & Source) != 0 ? GENERATE : DO_NOT_GENERATE); -// optionsMap.put(OPTION_PreserveUnusedLocal, this.preserveAllLocalVariables ? PRESERVE : OPTIMIZE_OUT); - optionsMap.put(OPTION_DocCommentSupport, this.docCommentSupport ? ENABLED : DISABLED); - optionsMap.put(OPTION_ReportMethodWithConstructorName, getSeverityString(MethodWithConstructorName)); - optionsMap.put(OPTION_ReportOverridingPackageDefaultMethod, getSeverityString(OverriddenPackageDefaultMethod)); - optionsMap.put(OPTION_ReportDeprecation, getSeverityString(UsingDeprecatedAPI)); - optionsMap.put(OPTION_ReportDeprecationInDeprecatedCode, this.reportDeprecationInsideDeprecatedCode ? ENABLED : DISABLED); - optionsMap.put(OPTION_ReportDeprecationWhenOverridingDeprecatedMethod, this.reportDeprecationWhenOverridingDeprecatedMethod ? ENABLED : DISABLED); - optionsMap.put(OPTION_ReportHiddenCatchBlock, getSeverityString(MaskedCatchBlock)); - optionsMap.put(OPTION_ReportUnusedLocal, getSeverityString(UnusedLocalVariable)); - optionsMap.put(OPTION_ReportUnusedParameter, getSeverityString(UnusedArgument)); - optionsMap.put(OPTION_ReportUnusedImport, getSeverityString(UnusedImport)); - optionsMap.put(OPTION_ReportSyntheticAccessEmulation, getSeverityString(AccessEmulation)); - optionsMap.put(OPTION_ReportNoEffectAssignment, getSeverityString(NoEffectAssignment)); - optionsMap.put(OPTION_ReportNonExternalizedStringLiteral, getSeverityString(NonExternalizedString)); - optionsMap.put(OPTION_ReportNoImplicitStringConversion, getSeverityString(NoImplicitStringConversion)); - optionsMap.put(OPTION_ReportNonStaticAccessToStatic, getSeverityString(NonStaticAccessToStatic)); - optionsMap.put(OPTION_ReportIndirectStaticAccess, getSeverityString(IndirectStaticAccess)); - optionsMap.put(OPTION_ReportIncompatibleNonInheritedInterfaceMethod, getSeverityString(IncompatibleNonInheritedInterfaceMethod)); - optionsMap.put(OPTION_ReportUnusedPrivateMember, getSeverityString(UnusedPrivateMember)); - optionsMap.put(OPTION_ReportLocalVariableHiding, getSeverityString(LocalVariableHiding)); - optionsMap.put(OPTION_ReportFieldHiding, getSeverityString(FieldHiding)); - optionsMap.put(OPTION_ReportPossibleAccidentalBooleanAssignment, getSeverityString(AccidentalBooleanAssign)); - optionsMap.put(OPTION_ReportSuperfluousSemicolon, getSeverityString(SuperfluousSemicolon)); - optionsMap.put(OPTION_ReportAssertIdentifier, getSeverityString(AssertUsedAsAnIdentifier)); - optionsMap.put(OPTION_ReportUndocumentedEmptyBlock, getSeverityString(UndocumentedEmptyBlock)); - optionsMap.put(OPTION_ReportUnnecessaryTypeCheck, getSeverityString(UnnecessaryTypeCheck)); - optionsMap.put(OPTION_ReportInvalidJavadoc, getSeverityString(InvalidJavadoc)); - optionsMap.put(OPTION_ReportInvalidJavadocTagsVisibility, getVisibilityString(this.reportInvalidJavadocTagsVisibility)); - optionsMap.put(OPTION_ReportInvalidJavadocTags, this.reportInvalidJavadocTags? ENABLED : DISABLED); - optionsMap.put(OPTION_ReportMissingJavadocTags, getSeverityString(MissingJavadocTags)); - optionsMap.put(OPTION_ReportMissingJavadocTagsVisibility, getVisibilityString(this.reportMissingJavadocTagsVisibility)); - optionsMap.put(OPTION_ReportMissingJavadocTagsOverriding, this.reportMissingJavadocTagsOverriding ? ENABLED : DISABLED); - optionsMap.put(OPTION_ReportMissingJavadocComments, getSeverityString(MissingJavadocComments)); - optionsMap.put(OPTION_ReportMissingJavadocCommentsVisibility, getVisibilityString(this.reportMissingJavadocCommentsVisibility)); - optionsMap.put(OPTION_ReportMissingJavadocCommentsOverriding, this.reportMissingJavadocCommentsOverriding ? ENABLED : DISABLED); - optionsMap.put(OPTION_ReportFinallyBlockNotCompletingNormally, getSeverityString(FinallyBlockNotCompleting)); - optionsMap.put(OPTION_ReportUnusedDeclaredThrownException, getSeverityString(UnusedDeclaredThrownException)); - optionsMap.put(OPTION_ReportUnusedDeclaredThrownExceptionWhenOverriding, this.reportUnusedDeclaredThrownExceptionWhenOverriding ? ENABLED : DISABLED); - optionsMap.put(OPTION_ReportUnqualifiedFieldAccess, getSeverityString(UnqualifiedFieldAccess)); -// optionsMap.put(OPTION_Compliance, versionFromJdkLevel(this.complianceLevel)); -// optionsMap.put(OPTION_Source, versionFromJdkLevel(this.sourceLevel)); -// optionsMap.put(OPTION_TargetPlatform, versionFromJdkLevel(this.targetJDK)); + optionsMap.put(OPTION_PHPIncludeNotExistWarning, + getSeverityString(PHPIncludeNotExistWarning)); + optionsMap.put(OPTION_PHPVarDeprecatedWarning, + getSeverityString(PHPVarDeprecatedWarning)); + optionsMap.put(OPTION_PHPBadStyleKeywordWarning, + getSeverityString(PHPBadStyleKeywordWarning)); + optionsMap.put(OPTION_PHPBadStyleUppercaseIdentifierWarning, + getSeverityString(PHPBadStyleUppercaseIdentifierWarning)); + optionsMap.put(OPTION_UninitializedLocalVariableWarning, + getSeverityString(UninitializedLocalVariableWarning)); + optionsMap.put(OPTION_CodeCannotBeReachedWarning, + getSeverityString(CodeCannotBeReachedWarning)); + + optionsMap.put(OPTION_LocalVariableAttribute, + (this.produceDebugAttributes & Vars) != 0 ? GENERATE + : DO_NOT_GENERATE); + optionsMap.put(OPTION_LineNumberAttribute, + (this.produceDebugAttributes & Lines) != 0 ? GENERATE + : DO_NOT_GENERATE); + optionsMap.put(OPTION_SourceFileAttribute, + (this.produceDebugAttributes & Source) != 0 ? GENERATE + : DO_NOT_GENERATE); + // optionsMap.put(OPTION_PreserveUnusedLocal, + // this.preserveAllLocalVariables ? PRESERVE : OPTIMIZE_OUT); + optionsMap.put(OPTION_DocCommentSupport, + this.docCommentSupport ? ENABLED : DISABLED); + optionsMap.put(OPTION_ReportMethodWithConstructorName, + getSeverityString(MethodWithConstructorName)); + optionsMap.put(OPTION_ReportOverridingPackageDefaultMethod, + getSeverityString(OverriddenPackageDefaultMethod)); + optionsMap.put(OPTION_ReportDeprecation, + getSeverityString(UsingDeprecatedAPI)); + optionsMap + .put(OPTION_ReportDeprecationInDeprecatedCode, + this.reportDeprecationInsideDeprecatedCode ? ENABLED + : DISABLED); + optionsMap.put(OPTION_ReportDeprecationWhenOverridingDeprecatedMethod, + this.reportDeprecationWhenOverridingDeprecatedMethod ? ENABLED + : DISABLED); + optionsMap.put(OPTION_ReportHiddenCatchBlock, + getSeverityString(MaskedCatchBlock)); + optionsMap.put(OPTION_ReportUnusedLocal, + getSeverityString(UnusedLocalVariable)); + optionsMap.put(OPTION_ReportUnusedParameter, + getSeverityString(UnusedArgument)); + optionsMap.put(OPTION_ReportUnusedImport, + getSeverityString(UnusedImport)); + optionsMap.put(OPTION_ReportSyntheticAccessEmulation, + getSeverityString(AccessEmulation)); + optionsMap.put(OPTION_ReportNoEffectAssignment, + getSeverityString(NoEffectAssignment)); + optionsMap.put(OPTION_ReportNonExternalizedStringLiteral, + getSeverityString(NonExternalizedString)); + optionsMap.put(OPTION_ReportNoImplicitStringConversion, + getSeverityString(NoImplicitStringConversion)); + optionsMap.put(OPTION_ReportNonStaticAccessToStatic, + getSeverityString(NonStaticAccessToStatic)); + optionsMap.put(OPTION_ReportIndirectStaticAccess, + getSeverityString(IndirectStaticAccess)); + optionsMap.put(OPTION_ReportIncompatibleNonInheritedInterfaceMethod, + getSeverityString(IncompatibleNonInheritedInterfaceMethod)); + optionsMap.put(OPTION_ReportUnusedPrivateMember, + getSeverityString(UnusedPrivateMember)); + optionsMap.put(OPTION_ReportLocalVariableHiding, + getSeverityString(LocalVariableHiding)); + optionsMap + .put(OPTION_ReportFieldHiding, getSeverityString(FieldHiding)); + optionsMap.put(OPTION_ReportPossibleAccidentalBooleanAssignment, + getSeverityString(AccidentalBooleanAssign)); + optionsMap.put(OPTION_ReportSuperfluousSemicolon, + getSeverityString(SuperfluousSemicolon)); + optionsMap.put(OPTION_ReportAssertIdentifier, + getSeverityString(AssertUsedAsAnIdentifier)); + optionsMap.put(OPTION_ReportUndocumentedEmptyBlock, + getSeverityString(UndocumentedEmptyBlock)); + optionsMap.put(OPTION_ReportUnnecessaryTypeCheck, + getSeverityString(UnnecessaryTypeCheck)); + optionsMap.put(OPTION_ReportInvalidJavadoc, + getSeverityString(InvalidJavadoc)); + optionsMap.put(OPTION_ReportInvalidJavadocTagsVisibility, + getVisibilityString(this.reportInvalidJavadocTagsVisibility)); + optionsMap.put(OPTION_ReportInvalidJavadocTags, + this.reportInvalidJavadocTags ? ENABLED : DISABLED); + optionsMap.put(OPTION_ReportMissingJavadocTags, + getSeverityString(MissingJavadocTags)); + optionsMap.put(OPTION_ReportMissingJavadocTagsVisibility, + getVisibilityString(this.reportMissingJavadocTagsVisibility)); + optionsMap.put(OPTION_ReportMissingJavadocTagsOverriding, + this.reportMissingJavadocTagsOverriding ? ENABLED : DISABLED); + optionsMap.put(OPTION_ReportMissingJavadocComments, + getSeverityString(MissingJavadocComments)); + optionsMap + .put( + OPTION_ReportMissingJavadocCommentsVisibility, + getVisibilityString(this.reportMissingJavadocCommentsVisibility)); + optionsMap.put(OPTION_ReportMissingJavadocCommentsOverriding, + this.reportMissingJavadocCommentsOverriding ? ENABLED + : DISABLED); + optionsMap.put(OPTION_ReportFinallyBlockNotCompletingNormally, + getSeverityString(FinallyBlockNotCompleting)); + optionsMap.put(OPTION_ReportUnusedDeclaredThrownException, + getSeverityString(UnusedDeclaredThrownException)); + optionsMap + .put( + OPTION_ReportUnusedDeclaredThrownExceptionWhenOverriding, + this.reportUnusedDeclaredThrownExceptionWhenOverriding ? ENABLED + : DISABLED); + optionsMap.put(OPTION_ReportUnqualifiedFieldAccess, + getSeverityString(UnqualifiedFieldAccess)); + // optionsMap.put(OPTION_Compliance, + // versionFromJdkLevel(this.complianceLevel)); + // optionsMap.put(OPTION_Source, versionFromJdkLevel(this.sourceLevel)); + // optionsMap.put(OPTION_TargetPlatform, + // versionFromJdkLevel(this.targetJDK)); if (this.defaultEncoding != null) { - optionsMap.put(OPTION_Encoding, this.defaultEncoding); + optionsMap.put(OPTION_Encoding, this.defaultEncoding); } - optionsMap.put(OPTION_TaskTags, this.taskTags == null ? "" : new String(CharOperation.concatWith(this.taskTags,','))); //$NON-NLS-1$ - optionsMap.put(OPTION_TaskPriorities, this.taskPriorites == null ? "" : new String(CharOperation.concatWith(this.taskPriorites,','))); //$NON-NLS-1$ - optionsMap.put(OPTION_ReportUnusedParameterWhenImplementingAbstract, this.reportUnusedParameterWhenImplementingAbstract ? ENABLED : DISABLED); - optionsMap.put(OPTION_ReportUnusedParameterWhenOverridingConcrete, this.reportUnusedParameterWhenOverridingConcrete ? ENABLED : DISABLED); - optionsMap.put(OPTION_ReportSpecialParameterHidingField, this.reportSpecialParameterHidingField ? ENABLED : DISABLED); - optionsMap.put(OPTION_MaxProblemPerUnit, String.valueOf(this.maxProblemsPerUnit)); - - return optionsMap; + optionsMap + .put( + OPTION_TaskTags, + this.taskTags == null ? "" : new String(CharOperation.concatWith(this.taskTags, ','))); //$NON-NLS-1$ + optionsMap + .put( + OPTION_TaskPriorities, + this.taskPriorites == null ? "" : new String(CharOperation.concatWith(this.taskPriorites, ','))); //$NON-NLS-1$ + optionsMap.put(OPTION_ReportUnusedParameterWhenImplementingAbstract, + this.reportUnusedParameterWhenImplementingAbstract ? ENABLED + : DISABLED); + optionsMap.put(OPTION_ReportUnusedParameterWhenOverridingConcrete, + this.reportUnusedParameterWhenOverridingConcrete ? ENABLED + : DISABLED); + optionsMap.put(OPTION_ReportSpecialParameterHidingField, + this.reportSpecialParameterHidingField ? ENABLED : DISABLED); + optionsMap.put(OPTION_MaxProblemPerUnit, String + .valueOf(this.maxProblemsPerUnit)); + + return optionsMap; } - + public int getSeverity(long irritant) { - if((this.warningThreshold & irritant) != 0) + if ((this.warningThreshold & irritant) != 0) return Warning; - if((this.errorThreshold & irritant) != 0) + if ((this.errorThreshold & irritant) != 0) return Error; return Ignore; } public String getSeverityString(long irritant) { - if((this.warningThreshold & irritant) != 0) + if ((this.warningThreshold & irritant) != 0) return WARNING; - if((this.errorThreshold & irritant) != 0) + if ((this.errorThreshold & irritant) != 0) return ERROR; return IGNORE; } - + public String getVisibilityString(int level) { switch (level) { - case AccPublic: - return PUBLIC; - case AccProtected: - return PROTECTED; - case AccPrivate: - return PRIVATE; - default: - return DEFAULT; + case AccPublic: + return PUBLIC; + case AccProtected: + return PROTECTED; + case AccPrivate: + return PRIVATE; + default: + return DEFAULT; } } - + public void set(Map optionsMap) { Object optionValue; @@ -388,79 +576,89 @@ public class CompilerOptions implements ProblemReasons, ProblemSeverities, ICons this.produceDebugAttributes &= ~Source; } } -// if ((optionValue = optionsMap.get(OPTION_PreserveUnusedLocal)) != null) { -// if (PRESERVE.equals(optionValue)) { -// this.preserveAllLocalVariables = true; -// } else if (OPTIMIZE_OUT.equals(optionValue)) { -// this.preserveAllLocalVariables = false; -// } -// } - if ((optionValue = optionsMap.get(OPTION_ReportDeprecationInDeprecatedCode)) != null) { + // if ((optionValue = optionsMap.get(OPTION_PreserveUnusedLocal)) != + // null) { + // if (PRESERVE.equals(optionValue)) { + // this.preserveAllLocalVariables = true; + // } else if (OPTIMIZE_OUT.equals(optionValue)) { + // this.preserveAllLocalVariables = false; + // } + // } + if ((optionValue = optionsMap + .get(OPTION_ReportDeprecationInDeprecatedCode)) != null) { if (ENABLED.equals(optionValue)) { this.reportDeprecationInsideDeprecatedCode = true; } else if (DISABLED.equals(optionValue)) { this.reportDeprecationInsideDeprecatedCode = false; } } - if ((optionValue = optionsMap.get(OPTION_ReportDeprecationWhenOverridingDeprecatedMethod)) != null) { + if ((optionValue = optionsMap + .get(OPTION_ReportDeprecationWhenOverridingDeprecatedMethod)) != null) { if (ENABLED.equals(optionValue)) { this.reportDeprecationWhenOverridingDeprecatedMethod = true; } else if (DISABLED.equals(optionValue)) { this.reportDeprecationWhenOverridingDeprecatedMethod = false; } } - if ((optionValue = optionsMap.get(OPTION_ReportUnusedDeclaredThrownExceptionWhenOverriding)) != null) { + if ((optionValue = optionsMap + .get(OPTION_ReportUnusedDeclaredThrownExceptionWhenOverriding)) != null) { if (ENABLED.equals(optionValue)) { this.reportUnusedDeclaredThrownExceptionWhenOverriding = true; } else if (DISABLED.equals(optionValue)) { this.reportUnusedDeclaredThrownExceptionWhenOverriding = false; } } -// if ((optionValue = optionsMap.get(OPTION_Compliance)) != null) { -// long level = versionToJdkLevel(optionValue); -// if (level != 0) this.complianceLevel = level; -// } -// if ((optionValue = optionsMap.get(OPTION_Source)) != null) { -// long level = versionToJdkLevel(optionValue); -// if (level != 0) this.sourceLevel = level; -// } -// if ((optionValue = optionsMap.get(OPTION_TargetPlatform)) != null) { -// long level = versionToJdkLevel(optionValue); -// if (level != 0) this.targetJDK = level; -// } + // if ((optionValue = optionsMap.get(OPTION_Compliance)) != null) { + // long level = versionToJdkLevel(optionValue); + // if (level != 0) this.complianceLevel = level; + // } + // if ((optionValue = optionsMap.get(OPTION_Source)) != null) { + // long level = versionToJdkLevel(optionValue); + // if (level != 0) this.sourceLevel = level; + // } + // if ((optionValue = optionsMap.get(OPTION_TargetPlatform)) != null) { + // long level = versionToJdkLevel(optionValue); + // if (level != 0) this.targetJDK = level; + // } if ((optionValue = optionsMap.get(OPTION_Encoding)) != null) { if (optionValue instanceof String) { this.defaultEncoding = null; String stringValue = (String) optionValue; - if (stringValue.length() > 0){ - try { - new InputStreamReader(new ByteArrayInputStream(new byte[0]), stringValue); + if (stringValue.length() > 0) { + try { + new InputStreamReader(new ByteArrayInputStream( + new byte[0]), stringValue); this.defaultEncoding = stringValue; - } catch(UnsupportedEncodingException e){ + } catch (UnsupportedEncodingException e) { // ignore unsupported encoding } } } } -// if ((optionValue = optionsMap.get(OPTION_PrivateConstructorAccess)) != null) { -// long level = versionToJdkLevel(optionValue); -// if (level >= JDK1_3) this.isPrivateConstructorAccessChangingVisibility = true; -// } - if ((optionValue = optionsMap.get(OPTION_ReportUnusedParameterWhenImplementingAbstract)) != null) { + // if ((optionValue = optionsMap.get(OPTION_PrivateConstructorAccess)) + // != null) { + // long level = versionToJdkLevel(optionValue); + // if (level >= JDK1_3) + // this.isPrivateConstructorAccessChangingVisibility = true; + // } + if ((optionValue = optionsMap + .get(OPTION_ReportUnusedParameterWhenImplementingAbstract)) != null) { if (ENABLED.equals(optionValue)) { this.reportUnusedParameterWhenImplementingAbstract = true; } else if (DISABLED.equals(optionValue)) { this.reportUnusedParameterWhenImplementingAbstract = false; } } - if ((optionValue = optionsMap.get(OPTION_ReportUnusedParameterWhenOverridingConcrete)) != null) { + if ((optionValue = optionsMap + .get(OPTION_ReportUnusedParameterWhenOverridingConcrete)) != null) { if (ENABLED.equals(optionValue)) { this.reportUnusedParameterWhenOverridingConcrete = true; } else if (DISABLED.equals(optionValue)) { this.reportUnusedParameterWhenOverridingConcrete = false; } } - if ((optionValue = optionsMap.get(OPTION_ReportSpecialParameterHidingField)) != null) { + if ((optionValue = optionsMap + .get(OPTION_ReportSpecialParameterHidingField)) != null) { if (ENABLED.equals(optionValue)) { this.reportSpecialParameterHidingField = true; } else if (DISABLED.equals(optionValue)) { @@ -472,10 +670,11 @@ public class CompilerOptions implements ProblemReasons, ProblemSeverities, ICons String stringValue = (String) optionValue; try { int val = Integer.parseInt(stringValue); - if (val >= 0) this.maxProblemsPerUnit = val; - } catch(NumberFormatException e){ + if (val >= 0) + this.maxProblemsPerUnit = val; + } catch (NumberFormatException e) { // ignore ill-formatted limit - } + } } } if ((optionValue = optionsMap.get(OPTION_TaskTags)) != null) { @@ -484,7 +683,8 @@ public class CompilerOptions implements ProblemReasons, ProblemSeverities, ICons if (stringValue.length() == 0) { this.taskTags = null; } else { - this.taskTags = CharOperation.splitAndTrimOn(',', stringValue.toCharArray()); + this.taskTags = CharOperation.splitAndTrimOn(',', + stringValue.toCharArray()); } } } @@ -494,45 +694,88 @@ public class CompilerOptions implements ProblemReasons, ProblemSeverities, ICons if (stringValue.length() == 0) { this.taskPriorites = null; } else { - this.taskPriorites = CharOperation.splitAndTrimOn(',', stringValue.toCharArray()); + this.taskPriorites = CharOperation.splitAndTrimOn(',', + stringValue.toCharArray()); } } } - if ((optionValue = optionsMap.get(OPTION_PHPVarDeprecatedWarning)) != null) updateSeverity(PHPVarDeprecatedWarning, optionValue); - if ((optionValue = optionsMap.get(OPTION_PHPBadStyleKeywordWarning)) != null) updateSeverity(PHPBadStyleKeywordWarning, optionValue); - if ((optionValue = optionsMap.get(OPTION_PHPBadStyleUppercaseIdentifierWarning)) != null) updateSeverity(PHPBadStyleUppercaseIdentifierWarning, optionValue); - if ((optionValue = optionsMap.get(OPTION_PHPIncludeNotExistWarning)) != null) updateSeverity(PHPIncludeNotExistWarning, optionValue); - if ((optionValue = optionsMap.get(OPTION_UninitializedLocalVariableWarning)) != null) updateSeverity(UninitializedLocalVariableWarning, optionValue); - if ((optionValue = optionsMap.get(OPTION_CodeCannotBeReachedWarning)) != null) updateSeverity(CodeCannotBeReachedWarning, optionValue); - - if ((optionValue = optionsMap.get(OPTION_ReportMethodWithConstructorName)) != null) updateSeverity(MethodWithConstructorName, optionValue); - if ((optionValue = optionsMap.get(OPTION_ReportOverridingPackageDefaultMethod)) != null) updateSeverity(OverriddenPackageDefaultMethod, optionValue); - if ((optionValue = optionsMap.get(OPTION_ReportDeprecation)) != null) updateSeverity(UsingDeprecatedAPI, optionValue); - if ((optionValue = optionsMap.get(OPTION_ReportHiddenCatchBlock)) != null) updateSeverity(MaskedCatchBlock, optionValue); - if ((optionValue = optionsMap.get(OPTION_ReportUnusedLocal)) != null) updateSeverity(UnusedLocalVariable, optionValue); - if ((optionValue = optionsMap.get(OPTION_ReportUnusedParameter)) != null) updateSeverity(UnusedArgument, optionValue); - if ((optionValue = optionsMap.get(OPTION_ReportUnusedImport)) != null) updateSeverity(UnusedImport, optionValue); - if ((optionValue = optionsMap.get(OPTION_ReportUnusedPrivateMember)) != null) updateSeverity(UnusedPrivateMember, optionValue); - if ((optionValue = optionsMap.get(OPTION_ReportUnusedDeclaredThrownException)) != null) updateSeverity(UnusedDeclaredThrownException, optionValue); - if ((optionValue = optionsMap.get(OPTION_ReportNoImplicitStringConversion)) != null) updateSeverity(NoImplicitStringConversion, optionValue); - if ((optionValue = optionsMap.get(OPTION_ReportSyntheticAccessEmulation)) != null) updateSeverity(AccessEmulation, optionValue); - if ((optionValue = optionsMap.get(OPTION_ReportLocalVariableHiding)) != null) updateSeverity(LocalVariableHiding, optionValue); - if ((optionValue = optionsMap.get(OPTION_ReportFieldHiding)) != null) updateSeverity(FieldHiding, optionValue); - if ((optionValue = optionsMap.get(OPTION_ReportPossibleAccidentalBooleanAssignment)) != null) updateSeverity(AccidentalBooleanAssign, optionValue); - if ((optionValue = optionsMap.get(OPTION_ReportSuperfluousSemicolon)) != null) updateSeverity(SuperfluousSemicolon, optionValue); - if ((optionValue = optionsMap.get(OPTION_ReportNonExternalizedStringLiteral)) != null) updateSeverity(NonExternalizedString, optionValue); - if ((optionValue = optionsMap.get(OPTION_ReportAssertIdentifier)) != null) updateSeverity(AssertUsedAsAnIdentifier, optionValue); - if ((optionValue = optionsMap.get(OPTION_ReportNonStaticAccessToStatic)) != null) updateSeverity(NonStaticAccessToStatic, optionValue); - if ((optionValue = optionsMap.get(OPTION_ReportIndirectStaticAccess)) != null) updateSeverity(IndirectStaticAccess, optionValue); - if ((optionValue = optionsMap.get(OPTION_ReportIncompatibleNonInheritedInterfaceMethod)) != null) updateSeverity(IncompatibleNonInheritedInterfaceMethod, optionValue); - if ((optionValue = optionsMap.get(OPTION_ReportUndocumentedEmptyBlock)) != null) updateSeverity(UndocumentedEmptyBlock, optionValue); - if ((optionValue = optionsMap.get(OPTION_ReportUnnecessaryTypeCheck)) != null) updateSeverity(UnnecessaryTypeCheck, optionValue); - if ((optionValue = optionsMap.get(OPTION_ReportFinallyBlockNotCompletingNormally)) != null) updateSeverity(FinallyBlockNotCompleting, optionValue); - if ((optionValue = optionsMap.get(OPTION_ReportUnqualifiedFieldAccess)) != null) updateSeverity(UnqualifiedFieldAccess, optionValue); - if ((optionValue = optionsMap.get(OPTION_ReportNoEffectAssignment)) != null) updateSeverity(NoEffectAssignment, optionValue); + if ((optionValue = optionsMap.get(OPTION_PHPVarDeprecatedWarning)) != null) + updateSeverity(PHPVarDeprecatedWarning, optionValue); + if ((optionValue = optionsMap.get(OPTION_PHPBadStyleKeywordWarning)) != null) + updateSeverity(PHPBadStyleKeywordWarning, optionValue); + if ((optionValue = optionsMap + .get(OPTION_PHPBadStyleUppercaseIdentifierWarning)) != null) + updateSeverity(PHPBadStyleUppercaseIdentifierWarning, optionValue); + if ((optionValue = optionsMap.get(OPTION_PHPIncludeNotExistWarning)) != null) + updateSeverity(PHPIncludeNotExistWarning, optionValue); + if ((optionValue = optionsMap + .get(OPTION_UninitializedLocalVariableWarning)) != null) + updateSeverity(UninitializedLocalVariableWarning, optionValue); + if ((optionValue = optionsMap.get(OPTION_CodeCannotBeReachedWarning)) != null) + updateSeverity(CodeCannotBeReachedWarning, optionValue); + if ((optionValue = optionsMap + .get(OPTION_ReportMethodWithConstructorName)) != null) + updateSeverity(MethodWithConstructorName, optionValue); + if ((optionValue = optionsMap + .get(OPTION_ReportOverridingPackageDefaultMethod)) != null) + updateSeverity(OverriddenPackageDefaultMethod, optionValue); + if ((optionValue = optionsMap.get(OPTION_ReportDeprecation)) != null) + updateSeverity(UsingDeprecatedAPI, optionValue); + if ((optionValue = optionsMap.get(OPTION_ReportHiddenCatchBlock)) != null) + updateSeverity(MaskedCatchBlock, optionValue); + if ((optionValue = optionsMap.get(OPTION_ReportUnusedLocal)) != null) + updateSeverity(UnusedLocalVariable, optionValue); + if ((optionValue = optionsMap.get(OPTION_ReportUnusedParameter)) != null) + updateSeverity(UnusedArgument, optionValue); + if ((optionValue = optionsMap.get(OPTION_ReportUnusedImport)) != null) + updateSeverity(UnusedImport, optionValue); + if ((optionValue = optionsMap.get(OPTION_ReportUnusedPrivateMember)) != null) + updateSeverity(UnusedPrivateMember, optionValue); + if ((optionValue = optionsMap + .get(OPTION_ReportUnusedDeclaredThrownException)) != null) + updateSeverity(UnusedDeclaredThrownException, optionValue); + if ((optionValue = optionsMap + .get(OPTION_ReportNoImplicitStringConversion)) != null) + updateSeverity(NoImplicitStringConversion, optionValue); + if ((optionValue = optionsMap + .get(OPTION_ReportSyntheticAccessEmulation)) != null) + updateSeverity(AccessEmulation, optionValue); + if ((optionValue = optionsMap.get(OPTION_ReportLocalVariableHiding)) != null) + updateSeverity(LocalVariableHiding, optionValue); + if ((optionValue = optionsMap.get(OPTION_ReportFieldHiding)) != null) + updateSeverity(FieldHiding, optionValue); + if ((optionValue = optionsMap + .get(OPTION_ReportPossibleAccidentalBooleanAssignment)) != null) + updateSeverity(AccidentalBooleanAssign, optionValue); + if ((optionValue = optionsMap.get(OPTION_ReportSuperfluousSemicolon)) != null) + updateSeverity(SuperfluousSemicolon, optionValue); + if ((optionValue = optionsMap + .get(OPTION_ReportNonExternalizedStringLiteral)) != null) + updateSeverity(NonExternalizedString, optionValue); + if ((optionValue = optionsMap.get(OPTION_ReportAssertIdentifier)) != null) + updateSeverity(AssertUsedAsAnIdentifier, optionValue); + if ((optionValue = optionsMap.get(OPTION_ReportNonStaticAccessToStatic)) != null) + updateSeverity(NonStaticAccessToStatic, optionValue); + if ((optionValue = optionsMap.get(OPTION_ReportIndirectStaticAccess)) != null) + updateSeverity(IndirectStaticAccess, optionValue); + if ((optionValue = optionsMap + .get(OPTION_ReportIncompatibleNonInheritedInterfaceMethod)) != null) + updateSeverity(IncompatibleNonInheritedInterfaceMethod, optionValue); + if ((optionValue = optionsMap.get(OPTION_ReportUndocumentedEmptyBlock)) != null) + updateSeverity(UndocumentedEmptyBlock, optionValue); + if ((optionValue = optionsMap.get(OPTION_ReportUnnecessaryTypeCheck)) != null) + updateSeverity(UnnecessaryTypeCheck, optionValue); + if ((optionValue = optionsMap + .get(OPTION_ReportFinallyBlockNotCompletingNormally)) != null) + updateSeverity(FinallyBlockNotCompleting, optionValue); + if ((optionValue = optionsMap.get(OPTION_ReportUnqualifiedFieldAccess)) != null) + updateSeverity(UnqualifiedFieldAccess, optionValue); + if ((optionValue = optionsMap.get(OPTION_ReportNoEffectAssignment)) != null) + updateSeverity(NoEffectAssignment, optionValue); + + // Javadoc options // Javadoc options -// Javadoc options if ((optionValue = optionsMap.get(OPTION_DocCommentSupport)) != null) { if (ENABLED.equals(optionValue)) { this.docCommentSupport = true; @@ -543,20 +786,21 @@ public class CompilerOptions implements ProblemReasons, ProblemSeverities, ICons if ((optionValue = optionsMap.get(OPTION_ReportInvalidJavadoc)) != null) { updateSeverity(InvalidJavadoc, optionValue); } - if ((optionValue = optionsMap.get(OPTION_ReportInvalidJavadocTagsVisibility)) != null) { + if ((optionValue = optionsMap + .get(OPTION_ReportInvalidJavadocTagsVisibility)) != null) { if (PUBLIC.equals(optionValue)) { this.reportInvalidJavadocTagsVisibility = AccPublic; } else if (PROTECTED.equals(optionValue)) { this.reportInvalidJavadocTagsVisibility = AccProtected; -// } else if (DEFAULT.equals(optionValue)) { -// this.reportInvalidJavadocTagsVisibility = AccDefault; + // } else if (DEFAULT.equals(optionValue)) { + // this.reportInvalidJavadocTagsVisibility = AccDefault; } else if (PRIVATE.equals(optionValue)) { this.reportInvalidJavadocTagsVisibility = AccPrivate; } } if ((optionValue = optionsMap.get(OPTION_ReportInvalidJavadocTags)) != null) { if (ENABLED.equals(optionValue)) { - this.reportInvalidJavadocTags= true; + this.reportInvalidJavadocTags = true; } else if (DISABLED.equals(optionValue)) { this.reportInvalidJavadocTags = false; } @@ -564,18 +808,20 @@ public class CompilerOptions implements ProblemReasons, ProblemSeverities, ICons if ((optionValue = optionsMap.get(OPTION_ReportMissingJavadocTags)) != null) { updateSeverity(MissingJavadocTags, optionValue); } - if ((optionValue = optionsMap.get(OPTION_ReportMissingJavadocTagsVisibility)) != null) { + if ((optionValue = optionsMap + .get(OPTION_ReportMissingJavadocTagsVisibility)) != null) { if (PUBLIC.equals(optionValue)) { this.reportMissingJavadocTagsVisibility = AccPublic; } else if (PROTECTED.equals(optionValue)) { this.reportMissingJavadocTagsVisibility = AccProtected; -// } else if (DEFAULT.equals(optionValue)) { -// this.reportMissingJavadocTagsVisibility = AccDefault; + // } else if (DEFAULT.equals(optionValue)) { + // this.reportMissingJavadocTagsVisibility = AccDefault; } else if (PRIVATE.equals(optionValue)) { this.reportMissingJavadocTagsVisibility = AccPrivate; } } - if ((optionValue = optionsMap.get(OPTION_ReportMissingJavadocTagsOverriding)) != null) { + if ((optionValue = optionsMap + .get(OPTION_ReportMissingJavadocTagsOverriding)) != null) { if (ENABLED.equals(optionValue)) { this.reportMissingJavadocTagsOverriding = true; } else if (DISABLED.equals(optionValue)) { @@ -585,18 +831,20 @@ public class CompilerOptions implements ProblemReasons, ProblemSeverities, ICons if ((optionValue = optionsMap.get(OPTION_ReportMissingJavadocComments)) != null) { updateSeverity(MissingJavadocComments, optionValue); } - if ((optionValue = optionsMap.get(OPTION_ReportMissingJavadocCommentsVisibility)) != null) { + if ((optionValue = optionsMap + .get(OPTION_ReportMissingJavadocCommentsVisibility)) != null) { if (PUBLIC.equals(optionValue)) { this.reportMissingJavadocCommentsVisibility = AccPublic; } else if (PROTECTED.equals(optionValue)) { this.reportMissingJavadocCommentsVisibility = AccProtected; -// } else if (DEFAULT.equals(optionValue)) { -// this.reportMissingJavadocCommentsVisibility = AccDefault; + // } else if (DEFAULT.equals(optionValue)) { + // this.reportMissingJavadocCommentsVisibility = AccDefault; } else if (PRIVATE.equals(optionValue)) { this.reportMissingJavadocCommentsVisibility = AccPrivate; } } - if ((optionValue = optionsMap.get(OPTION_ReportMissingJavadocCommentsOverriding)) != null) { + if ((optionValue = optionsMap + .get(OPTION_ReportMissingJavadocCommentsOverriding)) != null) { if (ENABLED.equals(optionValue)) { this.reportMissingJavadocCommentsOverriding = true; } else if (DISABLED.equals(optionValue)) { @@ -610,66 +858,133 @@ public class CompilerOptions implements ProblemReasons, ProblemSeverities, ICons } public String toString() { - + StringBuffer buf = new StringBuffer("CompilerOptions:"); //$NON-NLS-1$ - buf.append("\n\t- var is deprecated keyword: ").append(getSeverityString(PHPVarDeprecatedWarning)); //$NON-NLS-1$ - buf.append("\n\t- don't use keywords as identifiers: ").append(getSeverityString(PHPBadStyleKeywordWarning)); //$NON-NLS-1$ - buf.append("\n\t- non-variable idenifiers should contain only uppercase characters: ").append(getSeverityString(PHPBadStyleUppercaseIdentifierWarning)); //$NON-NLS-1$ - buf.append("\n\t- include filename doesn't exist in project: ").append(getSeverityString(PHPIncludeNotExistWarning)); //$NON-NLS-1$ - buf.append("\n\t- local variable not initialized: ").append(getSeverityString(UninitializedLocalVariableWarning)); //$NON-NLS-1$ - buf.append("\n\t- unreachable code: ").append(getSeverityString(CodeCannotBeReachedWarning)); //$NON-NLS-1$ - - buf.append("\n\t- local variables debug attributes: ").append((this.produceDebugAttributes & Vars) != 0 ? "ON" : " OFF"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - buf.append("\n\t- line number debug attributes: ").append((this.produceDebugAttributes & Lines) != 0 ? "ON" : " OFF"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - buf.append("\n\t- source debug attributes: ").append((this.produceDebugAttributes & Source) != 0 ? "ON" : " OFF"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - buf.append("\n\t- preserve all local variables: ").append(this.preserveAllLocalVariables ? "ON" : " OFF"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - buf.append("\n\t- method with constructor name: ").append(getSeverityString(MethodWithConstructorName)); //$NON-NLS-1$ - buf.append("\n\t- overridden package default method: ").append(getSeverityString(OverriddenPackageDefaultMethod)); //$NON-NLS-1$ - buf.append("\n\t- deprecation: ").append(getSeverityString(UsingDeprecatedAPI)); //$NON-NLS-1$ - buf.append("\n\t- masked catch block: ").append(getSeverityString(MaskedCatchBlock)); //$NON-NLS-1$ - buf.append("\n\t- unused local variable: ").append(getSeverityString(UnusedLocalVariable)); //$NON-NLS-1$ - buf.append("\n\t- unused parameter: ").append(getSeverityString(UnusedArgument)); //$NON-NLS-1$ - buf.append("\n\t- unused import: ").append(getSeverityString(UnusedImport)); //$NON-NLS-1$ - buf.append("\n\t- synthetic access emulation: ").append(getSeverityString(AccessEmulation)); //$NON-NLS-1$ - buf.append("\n\t- assignment with no effect: ").append(getSeverityString(NoEffectAssignment)); //$NON-NLS-1$ - buf.append("\n\t- non externalized string: ").append(getSeverityString(NonExternalizedString)); //$NON-NLS-1$ - buf.append("\n\t- static access receiver: ").append(getSeverityString(NonStaticAccessToStatic)); //$NON-NLS-1$ - buf.append("\n\t- indirect static access: ").append(getSeverityString(IndirectStaticAccess)); //$NON-NLS-1$ - buf.append("\n\t- incompatible non inherited interface method: ").append(getSeverityString(IncompatibleNonInheritedInterfaceMethod)); //$NON-NLS-1$ - buf.append("\n\t- unused private member: ").append(getSeverityString(UnusedPrivateMember)); //$NON-NLS-1$ - buf.append("\n\t- local variable hiding another variable: ").append(getSeverityString(LocalVariableHiding)); //$NON-NLS-1$ - buf.append("\n\t- field hiding another variable: ").append(getSeverityString(FieldHiding)); //$NON-NLS-1$ - buf.append("\n\t- possible accidental boolean assignment: ").append(getSeverityString(AccidentalBooleanAssign)); //$NON-NLS-1$ - buf.append("\n\t- superfluous semicolon: ").append(getSeverityString(SuperfluousSemicolon)); //$NON-NLS-1$ - buf.append("\n\t- uncommented empty block: ").append(getSeverityString(UndocumentedEmptyBlock)); //$NON-NLS-1$ - buf.append("\n\t- unnecessary type check: ").append(getSeverityString(UnnecessaryTypeCheck)); //$NON-NLS-1$ - buf.append("\n\t- invalid javadoc: ").append(getSeverityString(InvalidJavadoc)); //$NON-NLS-1$ - buf.append("\n\t- report invalid javadoc tags: ").append(this.reportInvalidJavadocTags ? ENABLED : DISABLED); //$NON-NLS-1$ - buf.append("\n\t- visibility level to report invalid javadoc tags: ").append(getVisibilityString(this.reportInvalidJavadocTagsVisibility)); //$NON-NLS-1$ - buf.append("\n\t- missing javadoc tags: ").append(getSeverityString(MissingJavadocTags)); //$NON-NLS-1$ - buf.append("\n\t- visibility level to report missing javadoc tags: ").append(getVisibilityString(this.reportMissingJavadocTagsVisibility)); //$NON-NLS-1$ - buf.append("\n\t- report missing javadoc tags in overriding methods: ").append(this.reportMissingJavadocTagsOverriding ? ENABLED : DISABLED); //$NON-NLS-1$ - buf.append("\n\t- missing javadoc comments: ").append(getSeverityString(MissingJavadocComments)); //$NON-NLS-1$ - buf.append("\n\t- visibility level to report missing javadoc comments: ").append(getVisibilityString(this.reportMissingJavadocCommentsVisibility)); //$NON-NLS-1$ - buf.append("\n\t- report missing javadoc comments in overriding methods: ").append(this.reportMissingJavadocCommentsOverriding ? ENABLED : DISABLED); //$NON-NLS-1$ - buf.append("\n\t- finally block not completing normally: ").append(getSeverityString(FinallyBlockNotCompleting)); //$NON-NLS-1$ - buf.append("\n\t- unused declared thrown exception: ").append(getSeverityString(UnusedDeclaredThrownException)); //$NON-NLS-1$ - buf.append("\n\t- unused declared thrown exception when overriding ").append(this.reportUnusedDeclaredThrownExceptionWhenOverriding ? ENABLED : DISABLED); //$NON-NLS-1$ -// buf.append("\n\t- JDK compliance level: "+ versionFromJdkLevel(this.complianceLevel)); //$NON-NLS-1$ -// buf.append("\n\t- JDK source level: "+ versionFromJdkLevel(this.sourceLevel)); //$NON-NLS-1$ -// buf.append("\n\t- JDK target level: "+ versionFromJdkLevel(this.targetJDK)); //$NON-NLS-1$ - buf.append("\n\t- private constructor access: ").append(this.isPrivateConstructorAccessChangingVisibility ? "extra argument" : "make default access"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + buf + .append("\n\t- var is deprecated keyword: ").append(getSeverityString(PHPVarDeprecatedWarning)); //$NON-NLS-1$ + buf + .append("\n\t- don't use keywords as identifiers: ").append(getSeverityString(PHPBadStyleKeywordWarning)); //$NON-NLS-1$ + buf + .append( + "\n\t- non-variable idenifiers should contain only uppercase characters: ").append(getSeverityString(PHPBadStyleUppercaseIdentifierWarning)); //$NON-NLS-1$ + buf + .append("\n\t- include filename doesn't exist in project: ").append(getSeverityString(PHPIncludeNotExistWarning)); //$NON-NLS-1$ + buf + .append("\n\t- local variable not initialized: ").append(getSeverityString(UninitializedLocalVariableWarning)); //$NON-NLS-1$ + buf + .append("\n\t- unreachable code: ").append(getSeverityString(CodeCannotBeReachedWarning)); //$NON-NLS-1$ + + buf + .append("\n\t- local variables debug attributes: ").append((this.produceDebugAttributes & Vars) != 0 ? "ON" : " OFF"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + buf + .append("\n\t- line number debug attributes: ").append((this.produceDebugAttributes & Lines) != 0 ? "ON" : " OFF"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + buf + .append("\n\t- source debug attributes: ").append((this.produceDebugAttributes & Source) != 0 ? "ON" : " OFF"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + buf + .append("\n\t- preserve all local variables: ").append(this.preserveAllLocalVariables ? "ON" : " OFF"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + buf + .append("\n\t- method with constructor name: ").append(getSeverityString(MethodWithConstructorName)); //$NON-NLS-1$ + buf + .append("\n\t- overridden package default method: ").append(getSeverityString(OverriddenPackageDefaultMethod)); //$NON-NLS-1$ + buf + .append("\n\t- deprecation: ").append(getSeverityString(UsingDeprecatedAPI)); //$NON-NLS-1$ + buf + .append("\n\t- masked catch block: ").append(getSeverityString(MaskedCatchBlock)); //$NON-NLS-1$ + buf + .append("\n\t- unused local variable: ").append(getSeverityString(UnusedLocalVariable)); //$NON-NLS-1$ + buf + .append("\n\t- unused parameter: ").append(getSeverityString(UnusedArgument)); //$NON-NLS-1$ + buf + .append("\n\t- unused import: ").append(getSeverityString(UnusedImport)); //$NON-NLS-1$ + buf + .append("\n\t- synthetic access emulation: ").append(getSeverityString(AccessEmulation)); //$NON-NLS-1$ + buf + .append("\n\t- assignment with no effect: ").append(getSeverityString(NoEffectAssignment)); //$NON-NLS-1$ + buf + .append("\n\t- non externalized string: ").append(getSeverityString(NonExternalizedString)); //$NON-NLS-1$ + buf + .append("\n\t- static access receiver: ").append(getSeverityString(NonStaticAccessToStatic)); //$NON-NLS-1$ + buf + .append("\n\t- indirect static access: ").append(getSeverityString(IndirectStaticAccess)); //$NON-NLS-1$ + buf + .append("\n\t- incompatible non inherited interface method: ").append(getSeverityString(IncompatibleNonInheritedInterfaceMethod)); //$NON-NLS-1$ + buf + .append("\n\t- unused private member: ").append(getSeverityString(UnusedPrivateMember)); //$NON-NLS-1$ + buf + .append("\n\t- local variable hiding another variable: ").append(getSeverityString(LocalVariableHiding)); //$NON-NLS-1$ + buf + .append("\n\t- field hiding another variable: ").append(getSeverityString(FieldHiding)); //$NON-NLS-1$ + buf + .append("\n\t- possible accidental boolean assignment: ").append(getSeverityString(AccidentalBooleanAssign)); //$NON-NLS-1$ + buf + .append("\n\t- superfluous semicolon: ").append(getSeverityString(SuperfluousSemicolon)); //$NON-NLS-1$ + buf + .append("\n\t- uncommented empty block: ").append(getSeverityString(UndocumentedEmptyBlock)); //$NON-NLS-1$ + buf + .append("\n\t- unnecessary type check: ").append(getSeverityString(UnnecessaryTypeCheck)); //$NON-NLS-1$ + buf + .append("\n\t- invalid javadoc: ").append(getSeverityString(InvalidJavadoc)); //$NON-NLS-1$ + buf + .append("\n\t- report invalid javadoc tags: ").append(this.reportInvalidJavadocTags ? ENABLED : DISABLED); //$NON-NLS-1$ + buf + .append( + "\n\t- visibility level to report invalid javadoc tags: ").append(getVisibilityString(this.reportInvalidJavadocTagsVisibility)); //$NON-NLS-1$ + buf + .append("\n\t- missing javadoc tags: ").append(getSeverityString(MissingJavadocTags)); //$NON-NLS-1$ + buf + .append( + "\n\t- visibility level to report missing javadoc tags: ").append(getVisibilityString(this.reportMissingJavadocTagsVisibility)); //$NON-NLS-1$ + buf + .append( + "\n\t- report missing javadoc tags in overriding methods: ").append(this.reportMissingJavadocTagsOverriding ? ENABLED : DISABLED); //$NON-NLS-1$ + buf + .append("\n\t- missing javadoc comments: ").append(getSeverityString(MissingJavadocComments)); //$NON-NLS-1$ + buf + .append( + "\n\t- visibility level to report missing javadoc comments: ").append(getVisibilityString(this.reportMissingJavadocCommentsVisibility)); //$NON-NLS-1$ + buf + .append( + "\n\t- report missing javadoc comments in overriding methods: ").append(this.reportMissingJavadocCommentsOverriding ? ENABLED : DISABLED); //$NON-NLS-1$ + buf + .append("\n\t- finally block not completing normally: ").append(getSeverityString(FinallyBlockNotCompleting)); //$NON-NLS-1$ + buf + .append("\n\t- unused declared thrown exception: ").append(getSeverityString(UnusedDeclaredThrownException)); //$NON-NLS-1$ + buf + .append( + "\n\t- unused declared thrown exception when overriding ").append(this.reportUnusedDeclaredThrownExceptionWhenOverriding ? ENABLED : DISABLED); //$NON-NLS-1$ + // buf.append("\n\t- JDK compliance level: "+ + // versionFromJdkLevel(this.complianceLevel)); //$NON-NLS-1$ + // buf.append("\n\t- JDK source level: "+ + // versionFromJdkLevel(this.sourceLevel)); //$NON-NLS-1$ + // buf.append("\n\t- JDK target level: "+ + // versionFromJdkLevel(this.targetJDK)); //$NON-NLS-1$ + buf + .append("\n\t- private constructor access: ").append(this.isPrivateConstructorAccessChangingVisibility ? "extra argument" : "make default access"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ buf.append("\n\t- verbose : ").append(this.verbose ? "ON" : "OFF"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - buf.append("\n\t- produce reference info : ").append(this.produceReferenceInfo ? "ON" : "OFF"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - buf.append("\n\t- parse literal expressions as constants : ").append(this.parseLiteralExpressionsAsConstants ? "ON" : "OFF"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - buf.append("\n\t- encoding : ").append(this.defaultEncoding == null ? "" : this.defaultEncoding); //$NON-NLS-1$ //$NON-NLS-2$ - buf.append("\n\t- task tags: ").append(this.taskTags == null ? "" : new String(CharOperation.concatWith(this.taskTags,','))); //$NON-NLS-1$ //$NON-NLS-2$ - buf.append("\n\t- task priorities : ").append(this.taskPriorites == null ? "" : new String(CharOperation.concatWith(this.taskPriorites,','))); //$NON-NLS-1$ //$NON-NLS-2$ - buf.append("\n\t- report deprecation inside deprecated code : ").append(this.reportDeprecationInsideDeprecatedCode ? "ENABLED" : "DISABLED"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - buf.append("\n\t- report deprecation when overriding deprecated method : ").append(this.reportDeprecationWhenOverridingDeprecatedMethod ? "ENABLED" : "DISABLED"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - buf.append("\n\t- report unused parameter when implementing abstract method : ").append(this.reportUnusedParameterWhenImplementingAbstract ? "ENABLED" : "DISABLED"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - buf.append("\n\t- report unused parameter when overriding concrete method : ").append(this.reportUnusedParameterWhenOverridingConcrete ? "ENABLED" : "DISABLED"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - buf.append("\n\t- report constructor/setter parameter hiding existing field : ").append(this.reportSpecialParameterHidingField ? "ENABLED" : "DISABLED"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + buf + .append("\n\t- produce reference info : ").append(this.produceReferenceInfo ? "ON" : "OFF"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + buf + .append("\n\t- parse literal expressions as constants : ").append(this.parseLiteralExpressionsAsConstants ? "ON" : "OFF"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + buf + .append("\n\t- encoding : ").append(this.defaultEncoding == null ? "" : this.defaultEncoding); //$NON-NLS-1$ //$NON-NLS-2$ + buf + .append("\n\t- task tags: ").append(this.taskTags == null ? "" : new String(CharOperation.concatWith(this.taskTags, ','))); //$NON-NLS-1$ //$NON-NLS-2$ + buf + .append("\n\t- task priorities : ").append(this.taskPriorites == null ? "" : new String(CharOperation.concatWith(this.taskPriorites, ','))); //$NON-NLS-1$ //$NON-NLS-2$ + buf + .append("\n\t- report deprecation inside deprecated code : ").append(this.reportDeprecationInsideDeprecatedCode ? "ENABLED" : "DISABLED"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + buf + .append( + "\n\t- report deprecation when overriding deprecated method : ").append(this.reportDeprecationWhenOverridingDeprecatedMethod ? "ENABLED" : "DISABLED"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + buf + .append( + "\n\t- report unused parameter when implementing abstract method : ").append(this.reportUnusedParameterWhenImplementingAbstract ? "ENABLED" : "DISABLED"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + buf + .append( + "\n\t- report unused parameter when overriding concrete method : ").append(this.reportUnusedParameterWhenOverridingConcrete ? "ENABLED" : "DISABLED"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + buf + .append( + "\n\t- report constructor/setter parameter hiding existing field : ").append(this.reportSpecialParameterHidingField ? "ENABLED" : "DISABLED"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return buf.toString(); } @@ -684,34 +999,34 @@ public class CompilerOptions implements ProblemReasons, ProblemSeverities, ICons this.errorThreshold &= ~irritant; this.warningThreshold &= ~irritant; } - } -// public static long versionToJdkLevel(Object versionID) { -// if (VERSION_1_1.equals(versionID)) { -// return JDK1_1; -// } else if (VERSION_1_2.equals(versionID)) { -// return JDK1_2; -// } else if (VERSION_1_3.equals(versionID)) { -// return JDK1_3; -// } else if (VERSION_1_4.equals(versionID)) { -// return JDK1_4; -// } else if (VERSION_1_5.equals(versionID)) { -// return JDK1_5; -// } -// return 0; // unknown -// } - -// public static String versionFromJdkLevel(long jdkLevel) { -// if (jdkLevel == JDK1_1) { -// return VERSION_1_1; -// } else if (jdkLevel == JDK1_2) { -// return VERSION_1_2; -// } else if (jdkLevel == JDK1_3) { -// return VERSION_1_3; -// } else if (jdkLevel == JDK1_4) { -// return VERSION_1_4; -// } else if (jdkLevel == JDK1_5) { -// return VERSION_1_5; -// } -// return ""; // unknown version //$NON-NLS-1$ -// } + } + // public static long versionToJdkLevel(Object versionID) { + // if (VERSION_1_1.equals(versionID)) { + // return JDK1_1; + // } else if (VERSION_1_2.equals(versionID)) { + // return JDK1_2; + // } else if (VERSION_1_3.equals(versionID)) { + // return JDK1_3; + // } else if (VERSION_1_4.equals(versionID)) { + // return JDK1_4; + // } else if (VERSION_1_5.equals(versionID)) { + // return JDK1_5; + // } + // return 0; // unknown + // } + + // public static String versionFromJdkLevel(long jdkLevel) { + // if (jdkLevel == JDK1_1) { + // return VERSION_1_1; + // } else if (jdkLevel == JDK1_2) { + // return VERSION_1_2; + // } else if (jdkLevel == JDK1_3) { + // return VERSION_1_3; + // } else if (jdkLevel == JDK1_4) { + // return VERSION_1_4; + // } else if (jdkLevel == JDK1_5) { + // return VERSION_1_5; + // } + // return ""; // unknown version //$NON-NLS-1$ + // } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/Constant.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/Constant.java index 53e0d0a..6fffe25 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/Constant.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/Constant.java @@ -16,1550 +16,2789 @@ import net.sourceforge.phpdt.internal.compiler.problem.ShouldNotImplement; import net.sourceforge.phpdt.internal.compiler.util.Util; public abstract class Constant implements TypeIds, OperatorIds { - + public static final Constant NotAConstant = new DoubleConstant(Double.NaN); public static final IntConstant Zero = new IntConstant(0); + public static final IntConstant Two = new IntConstant(2); + public static final IntConstant One = new IntConstant(1); - + public boolean booleanValue() { - throw new ShouldNotImplement(Util.bind("constant.cannotCastedInto",typeName(),"boolean")); //$NON-NLS-1$ //$NON-NLS-2$ + throw new ShouldNotImplement(Util.bind( + "constant.cannotCastedInto", typeName(), "boolean")); //$NON-NLS-1$ //$NON-NLS-2$ } public byte byteValue() { - throw new ShouldNotImplement(Util.bind("constant.cannotCastedInto",typeName(),"byte")); //$NON-NLS-1$ //$NON-NLS-2$ + throw new ShouldNotImplement(Util.bind( + "constant.cannotCastedInto", typeName(), "byte")); //$NON-NLS-1$ //$NON-NLS-2$ } - public final Constant castTo(int conversionToTargetType){ - //the cast is an int of the form + public final Constant castTo(int conversionToTargetType) { + // the cast is an int of the form // (castId<<4)+typeId (in order to follow the - //user written style (cast)expression .... - - if (this == NotAConstant) return NotAConstant; - switch(conversionToTargetType){ - case T_undefined : return this; - // TARGET TYPE <- FROM TYPE - // case (T_undefined<<4)+T_undefined : return NotAConstant; - // case (T_undefined<<4)+T_byte : return NotAConstant; - // case (T_undefined<<4)+T_long : return NotAConstant; - // case (T_undefined<<4)+T_short : return NotAConstant; - // case (T_undefined<<4)+T_void : return NotAConstant; - // case (T_undefined<<4)+T_String : return NotAConstant; - // case (T_undefined<<4)+T_Object : return NotAConstant; - // case (T_undefined<<4)+T_double : return NotAConstant; - // case (T_undefined<<4)+T_float : return NotAConstant; - // case (T_undefined<<4)+T_boolean : return NotAConstant; - // case (T_undefined<<4)+T_char : return NotAConstant; - // case (T_undefined<<4)+T_int : return NotAConstant; - - // case (T_byte<<4)+T_undefined : return NotAConstant; - case (T_byte<<4)+T_byte : return this; - case (T_byte<<4)+T_long : return Constant.fromValue((byte)this.longValue()); - case (T_byte<<4)+T_short : return Constant.fromValue((byte)this.shortValue()); - // case (T_byte<<4)+T_void : return NotAConstant; - // case (T_byte<<4)+T_String : return NotAConstant; - // case (T_byte<<4)+T_Object : return NotAConstant; - case (T_byte<<4)+T_double : return Constant.fromValue((byte)this.doubleValue()); - case (T_byte<<4)+T_float : return Constant.fromValue((byte)this.floatValue()); - // case (T_byte<<4)+T_boolean : return NotAConstant; - case (T_byte<<4)+T_char : return Constant.fromValue((byte)this.charValue()); - case (T_byte<<4)+T_int : return Constant.fromValue((byte)this.intValue()); - - // case (T_long<<4)+T_undefined : return NotAConstant; - case (T_long<<4)+T_byte : return Constant.fromValue((long)this.byteValue()); - case (T_long<<4)+T_long : return this; - case (T_long<<4)+T_short : return Constant.fromValue((long)this.shortValue()); - // case (T_long<<4)+T_void : return NotAConstant; - // case (T_long<<4)+T_String : return NotAConstant; - // case (T_long<<4)+T_Object : return NotAConstant; - case (T_long<<4)+T_double : return Constant.fromValue((long)this.doubleValue()); - case (T_long<<4)+T_float : return Constant.fromValue((long)this.floatValue()); - // case (T_long<<4)+T_boolean : return NotAConstant; - case (T_long<<4)+T_char : return Constant.fromValue((long)this.charValue()); - case (T_long<<4)+T_int : return Constant.fromValue((long)this.intValue()); - - // case (T_short<<4)+T_undefined : return NotAConstant; - case (T_short<<4)+T_byte : return Constant.fromValue((short)this.byteValue()); - case (T_short<<4)+T_long : return Constant.fromValue((short)this.longValue()); - case (T_short<<4)+T_short : return this; - // case (T_short<<4)+T_void : return NotAConstant; - // case (T_short<<4)+T_String : return NotAConstant; - // case (T_short<<4)+T_Object : return NotAConstant; - case (T_short<<4)+T_double : return Constant.fromValue((short)this.doubleValue()); - case (T_short<<4)+T_float : return Constant.fromValue((short)this.floatValue()); - // case (T_short<<4)+T_boolean : return NotAConstant; - case (T_short<<4)+T_char : return Constant.fromValue((short)this.charValue()); - case (T_short<<4)+T_int : return Constant.fromValue((short)this.intValue()); - - // case (T_void<<4)+T_undefined : return NotAConstant; - // case (T_void<<4)+T_byte : return NotAConstant; - // case (T_void<<4)+T_long : return NotAConstant; - // case (T_void<<4)+T_short : return NotAConstant; - // case (T_void<<4)+T_void : return NotAConstant; - // case (T_void<<4)+T_String : return NotAConstant; - // case (T_void<<4)+T_Object : return NotAConstant; - // case (T_void<<4)+T_double : return NotAConstant; - // case (T_void<<4)+T_float : return NotAConstant; - // case (T_void<<4)+T_boolean : return NotAConstant; - // case (T_void<<4)+T_char : return NotAConstant; - // case (T_void<<4)+T_int : return NotAConstant; - - // case (T_String<<4)+T_undefined : return NotAConstant; - // case (T_String<<4)+T_byte : return NotAConstant; - // case (T_String<<4)+T_long : return NotAConstant; - // case (T_String<<4)+T_short : return NotAConstant; - // case (T_String<<4)+T_void : return NotAConstant; - case (T_String<<4)+T_String : return this; - // case (T_String<<4)+T_Object : return NotAConstant; - // case (T_String<<4)+T_double : return NotAConstant; - // case (T_String<<4)+T_float : return NotAConstant; - // case (T_String<<4)+T_boolean : return NotAConstant; - // case (T_String<<4)+T_char : return NotAConstant; - // case (T_String<<4)+T_int : return NotAConstant; - - // case (T_Object<<4)+T_undefined : return NotAConstant; - // case (T_Object<<4)+T_byte : return NotAConstant; - // case (T_Object<<4)+T_long : return NotAConstant; - // case (T_Object<<4)+T_short : return NotAConstant; - // case (T_Object<<4)+T_void : return NotAConstant; - // case (T_Object<<4)+T_String : return NotAConstant; - // case (T_Object<<4)+T_Object : return NotAConstant; - // case (T_Object<<4)+T_double : return NotAConstant; - // case (T_Object<<4)+T_float : return NotAConstant; - // case (T_Object<<4)+T_boolean : return NotAConstant; - // case (T_Object<<4)+T_char : return NotAConstant; - // case (T_Object<<4)+T_int : return NotAConstant; - - // case (T_double<<4)+T_undefined : return NotAConstant; - case (T_double<<4)+T_byte : return Constant.fromValue((double)this.byteValue()); - case (T_double<<4)+T_long : return Constant.fromValue((double)this.longValue()); - case (T_double<<4)+T_short : return Constant.fromValue((double)this.shortValue()); - // case (T_double<<4)+T_void : return NotAConstant; - // case (T_double<<4)+T_String : return NotAConstant; - // case (T_double<<4)+T_Object : return NotAConstant; - case (T_double<<4)+T_double : return this; - case (T_double<<4)+T_float : return Constant.fromValue((double)this.floatValue()); - // case (T_double<<4)+T_boolean : return NotAConstant; - case (T_double<<4)+T_char : return Constant.fromValue((double)this.charValue()); - case (T_double<<4)+T_int : return Constant.fromValue((double)this.intValue()); - - // case (T_float<<4)+T_undefined : return NotAConstant; - case (T_float<<4)+T_byte : return Constant.fromValue((float)this.byteValue()); - case (T_float<<4)+T_long : return Constant.fromValue((float)this.longValue()); - case (T_float<<4)+T_short : return Constant.fromValue((float)this.shortValue()); - // case (T_float<<4)+T_void : return NotAConstant; - // case (T_float<<4)+T_String : return NotAConstant; - // case (T_float<<4)+T_Object : return NotAConstant; - case (T_float<<4)+T_double : return Constant.fromValue((float)this.doubleValue()); - case (T_float<<4)+T_float : return this; - // case (T_float<<4)+T_boolean : return NotAConstant; - case (T_float<<4)+T_char : return Constant.fromValue((float)this.charValue()); - case (T_float<<4)+T_int : return Constant.fromValue((float)this.intValue()); - - // case (T_boolean<<4)+T_undefined : return NotAConstant; - // case (T_boolean<<4)+T_byte : return NotAConstant; - // case (T_boolean<<4)+T_long : return NotAConstant; - // case (T_boolean<<4)+T_short : return NotAConstant; - // case (T_boolean<<4)+T_void : return NotAConstant; - // case (T_boolean<<4)+T_String : return NotAConstant; - // case (T_boolean<<4)+T_Object : return NotAConstant; - // case (T_boolean<<4)+T_double : return NotAConstant; - // case (T_boolean<<4)+T_float : return NotAConstant; - case (T_boolean<<4)+T_boolean : return this; - // case (T_boolean<<4)+T_char : return NotAConstant; - // case (T_boolean<<4)+T_int : return NotAConstant; - - // case (T_char<<4)+T_undefined : return NotAConstant; - case (T_char<<4)+T_byte : return Constant.fromValue((char)this.byteValue()); - case (T_char<<4)+T_long : return Constant.fromValue((char)this.longValue()); - case (T_char<<4)+T_short : return Constant.fromValue((char)this.shortValue()); - // case (T_char<<4)+T_void : return NotAConstant; - // case (T_char<<4)+T_String : return NotAConstant; - // case (T_char<<4)+T_Object : return NotAConstant; - case (T_char<<4)+T_double : return Constant.fromValue((char)this.doubleValue()); - case (T_char<<4)+T_float : return Constant.fromValue((char)this.floatValue()); - // case (T_char<<4)+T_boolean : return NotAConstant; - case (T_char<<4)+T_char : return this; - case (T_char<<4)+T_int : return Constant.fromValue((char)this.intValue()); - - // case (T_int<<4)+T_undefined : return NotAConstant; - case (T_int<<4)+T_byte : return Constant.fromValue((int)this.byteValue()); - case (T_int<<4)+T_long : return Constant.fromValue((int)this.longValue()); - case (T_int<<4)+T_short : return Constant.fromValue((int)this.shortValue()); - // case (T_int<<4)+T_void : return NotAConstant; - // case (T_int<<4)+T_String : return NotAConstant; - // case (T_int<<4)+T_Object : return NotAConstant; - case (T_int<<4)+T_double : return Constant.fromValue((int)this.doubleValue()); - case (T_int<<4)+T_float : return Constant.fromValue((int)this.floatValue()); - // case (T_int<<4)+T_boolean : return NotAConstant; - case (T_int<<4)+T_char : return Constant.fromValue((int)this.charValue()); - case (T_int<<4)+T_int : return this; - + // user written style (cast)expression .... + + if (this == NotAConstant) + return NotAConstant; + switch (conversionToTargetType) { + case T_undefined: + return this; + // TARGET TYPE <- FROM TYPE + // case (T_undefined<<4)+T_undefined : return NotAConstant; + // case (T_undefined<<4)+T_byte : return NotAConstant; + // case (T_undefined<<4)+T_long : return NotAConstant; + // case (T_undefined<<4)+T_short : return NotAConstant; + // case (T_undefined<<4)+T_void : return NotAConstant; + // case (T_undefined<<4)+T_String : return NotAConstant; + // case (T_undefined<<4)+T_Object : return NotAConstant; + // case (T_undefined<<4)+T_double : return NotAConstant; + // case (T_undefined<<4)+T_float : return NotAConstant; + // case (T_undefined<<4)+T_boolean : return NotAConstant; + // case (T_undefined<<4)+T_char : return NotAConstant; + // case (T_undefined<<4)+T_int : return NotAConstant; + + // case (T_byte<<4)+T_undefined : return NotAConstant; + case (T_byte << 4) + T_byte: + return this; + case (T_byte << 4) + T_long: + return Constant.fromValue((byte) this.longValue()); + case (T_byte << 4) + T_short: + return Constant.fromValue((byte) this.shortValue()); + // case (T_byte<<4)+T_void : return NotAConstant; + // case (T_byte<<4)+T_String : return NotAConstant; + // case (T_byte<<4)+T_Object : return NotAConstant; + case (T_byte << 4) + T_double: + return Constant.fromValue((byte) this.doubleValue()); + case (T_byte << 4) + T_float: + return Constant.fromValue((byte) this.floatValue()); + // case (T_byte<<4)+T_boolean : return NotAConstant; + case (T_byte << 4) + T_char: + return Constant.fromValue((byte) this.charValue()); + case (T_byte << 4) + T_int: + return Constant.fromValue((byte) this.intValue()); + + // case (T_long<<4)+T_undefined : return NotAConstant; + case (T_long << 4) + T_byte: + return Constant.fromValue((long) this.byteValue()); + case (T_long << 4) + T_long: + return this; + case (T_long << 4) + T_short: + return Constant.fromValue((long) this.shortValue()); + // case (T_long<<4)+T_void : return NotAConstant; + // case (T_long<<4)+T_String : return NotAConstant; + // case (T_long<<4)+T_Object : return NotAConstant; + case (T_long << 4) + T_double: + return Constant.fromValue((long) this.doubleValue()); + case (T_long << 4) + T_float: + return Constant.fromValue((long) this.floatValue()); + // case (T_long<<4)+T_boolean : return NotAConstant; + case (T_long << 4) + T_char: + return Constant.fromValue((long) this.charValue()); + case (T_long << 4) + T_int: + return Constant.fromValue((long) this.intValue()); + + // case (T_short<<4)+T_undefined : return NotAConstant; + case (T_short << 4) + T_byte: + return Constant.fromValue((short) this.byteValue()); + case (T_short << 4) + T_long: + return Constant.fromValue((short) this.longValue()); + case (T_short << 4) + T_short: + return this; + // case (T_short<<4)+T_void : return NotAConstant; + // case (T_short<<4)+T_String : return NotAConstant; + // case (T_short<<4)+T_Object : return NotAConstant; + case (T_short << 4) + T_double: + return Constant.fromValue((short) this.doubleValue()); + case (T_short << 4) + T_float: + return Constant.fromValue((short) this.floatValue()); + // case (T_short<<4)+T_boolean : return NotAConstant; + case (T_short << 4) + T_char: + return Constant.fromValue((short) this.charValue()); + case (T_short << 4) + T_int: + return Constant.fromValue((short) this.intValue()); + + // case (T_void<<4)+T_undefined : return NotAConstant; + // case (T_void<<4)+T_byte : return NotAConstant; + // case (T_void<<4)+T_long : return NotAConstant; + // case (T_void<<4)+T_short : return NotAConstant; + // case (T_void<<4)+T_void : return NotAConstant; + // case (T_void<<4)+T_String : return NotAConstant; + // case (T_void<<4)+T_Object : return NotAConstant; + // case (T_void<<4)+T_double : return NotAConstant; + // case (T_void<<4)+T_float : return NotAConstant; + // case (T_void<<4)+T_boolean : return NotAConstant; + // case (T_void<<4)+T_char : return NotAConstant; + // case (T_void<<4)+T_int : return NotAConstant; + + // case (T_String<<4)+T_undefined : return NotAConstant; + // case (T_String<<4)+T_byte : return NotAConstant; + // case (T_String<<4)+T_long : return NotAConstant; + // case (T_String<<4)+T_short : return NotAConstant; + // case (T_String<<4)+T_void : return NotAConstant; + case (T_String << 4) + T_String: + return this; + // case (T_String<<4)+T_Object : return NotAConstant; + // case (T_String<<4)+T_double : return NotAConstant; + // case (T_String<<4)+T_float : return NotAConstant; + // case (T_String<<4)+T_boolean : return NotAConstant; + // case (T_String<<4)+T_char : return NotAConstant; + // case (T_String<<4)+T_int : return NotAConstant; + + // case (T_Object<<4)+T_undefined : return NotAConstant; + // case (T_Object<<4)+T_byte : return NotAConstant; + // case (T_Object<<4)+T_long : return NotAConstant; + // case (T_Object<<4)+T_short : return NotAConstant; + // case (T_Object<<4)+T_void : return NotAConstant; + // case (T_Object<<4)+T_String : return NotAConstant; + // case (T_Object<<4)+T_Object : return NotAConstant; + // case (T_Object<<4)+T_double : return NotAConstant; + // case (T_Object<<4)+T_float : return NotAConstant; + // case (T_Object<<4)+T_boolean : return NotAConstant; + // case (T_Object<<4)+T_char : return NotAConstant; + // case (T_Object<<4)+T_int : return NotAConstant; + + // case (T_double<<4)+T_undefined : return NotAConstant; + case (T_double << 4) + T_byte: + return Constant.fromValue((double) this.byteValue()); + case (T_double << 4) + T_long: + return Constant.fromValue((double) this.longValue()); + case (T_double << 4) + T_short: + return Constant.fromValue((double) this.shortValue()); + // case (T_double<<4)+T_void : return NotAConstant; + // case (T_double<<4)+T_String : return NotAConstant; + // case (T_double<<4)+T_Object : return NotAConstant; + case (T_double << 4) + T_double: + return this; + case (T_double << 4) + T_float: + return Constant.fromValue((double) this.floatValue()); + // case (T_double<<4)+T_boolean : return NotAConstant; + case (T_double << 4) + T_char: + return Constant.fromValue((double) this.charValue()); + case (T_double << 4) + T_int: + return Constant.fromValue((double) this.intValue()); + + // case (T_float<<4)+T_undefined : return NotAConstant; + case (T_float << 4) + T_byte: + return Constant.fromValue((float) this.byteValue()); + case (T_float << 4) + T_long: + return Constant.fromValue((float) this.longValue()); + case (T_float << 4) + T_short: + return Constant.fromValue((float) this.shortValue()); + // case (T_float<<4)+T_void : return NotAConstant; + // case (T_float<<4)+T_String : return NotAConstant; + // case (T_float<<4)+T_Object : return NotAConstant; + case (T_float << 4) + T_double: + return Constant.fromValue((float) this.doubleValue()); + case (T_float << 4) + T_float: + return this; + // case (T_float<<4)+T_boolean : return NotAConstant; + case (T_float << 4) + T_char: + return Constant.fromValue((float) this.charValue()); + case (T_float << 4) + T_int: + return Constant.fromValue((float) this.intValue()); + + // case (T_boolean<<4)+T_undefined : return NotAConstant; + // case (T_boolean<<4)+T_byte : return NotAConstant; + // case (T_boolean<<4)+T_long : return NotAConstant; + // case (T_boolean<<4)+T_short : return NotAConstant; + // case (T_boolean<<4)+T_void : return NotAConstant; + // case (T_boolean<<4)+T_String : return NotAConstant; + // case (T_boolean<<4)+T_Object : return NotAConstant; + // case (T_boolean<<4)+T_double : return NotAConstant; + // case (T_boolean<<4)+T_float : return NotAConstant; + case (T_boolean << 4) + T_boolean: + return this; + // case (T_boolean<<4)+T_char : return NotAConstant; + // case (T_boolean<<4)+T_int : return NotAConstant; + + // case (T_char<<4)+T_undefined : return NotAConstant; + case (T_char << 4) + T_byte: + return Constant.fromValue((char) this.byteValue()); + case (T_char << 4) + T_long: + return Constant.fromValue((char) this.longValue()); + case (T_char << 4) + T_short: + return Constant.fromValue((char) this.shortValue()); + // case (T_char<<4)+T_void : return NotAConstant; + // case (T_char<<4)+T_String : return NotAConstant; + // case (T_char<<4)+T_Object : return NotAConstant; + case (T_char << 4) + T_double: + return Constant.fromValue((char) this.doubleValue()); + case (T_char << 4) + T_float: + return Constant.fromValue((char) this.floatValue()); + // case (T_char<<4)+T_boolean : return NotAConstant; + case (T_char << 4) + T_char: + return this; + case (T_char << 4) + T_int: + return Constant.fromValue((char) this.intValue()); + + // case (T_int<<4)+T_undefined : return NotAConstant; + case (T_int << 4) + T_byte: + return Constant.fromValue((int) this.byteValue()); + case (T_int << 4) + T_long: + return Constant.fromValue((int) this.longValue()); + case (T_int << 4) + T_short: + return Constant.fromValue((int) this.shortValue()); + // case (T_int<<4)+T_void : return NotAConstant; + // case (T_int<<4)+T_String : return NotAConstant; + // case (T_int<<4)+T_Object : return NotAConstant; + case (T_int << 4) + T_double: + return Constant.fromValue((int) this.doubleValue()); + case (T_int << 4) + T_float: + return Constant.fromValue((int) this.floatValue()); + // case (T_int<<4)+T_boolean : return NotAConstant; + case (T_int << 4) + T_char: + return Constant.fromValue((int) this.charValue()); + case (T_int << 4) + T_int: + return this; + } - + return NotAConstant; } - + public char charValue() { - - throw new ShouldNotImplement(Util.bind("constant.cannotCastedInto",typeName(),"char")); //$NON-NLS-1$ //$NON-NLS-2$ + + throw new ShouldNotImplement(Util.bind( + "constant.cannotCastedInto", typeName(), "char")); //$NON-NLS-1$ //$NON-NLS-2$ } - - public static final Constant computeConstantOperation(Constant cst, int id, int operator) { + + public static final Constant computeConstantOperation(Constant cst, int id, + int operator) { switch (operator) { - case NOT : - return Constant.fromValue(!cst.booleanValue()); - case PLUS : return cst; - case MINUS : //the two special -9223372036854775808L and -2147483648 are inlined at parseTime - switch (id){ - case T_float : float f; - if ( (f= cst.floatValue()) == 0.0f) - { //positive and negative 0.... - if (Float.floatToIntBits(f) == 0) - return Constant.fromValue(-0.0f); - else - return Constant.fromValue(0.0f);} - break; //default case - case T_double : double d; - if ( (d= cst.doubleValue()) == 0.0d) - { //positive and negative 0.... - if (Double.doubleToLongBits(d) == 0) - return Constant.fromValue(-0.0d); - else - return Constant.fromValue(0.0d);} - break; //default case - } - return computeConstantOperationMINUS(Zero,T_int,operator,cst,id); - case TWIDDLE: - switch (id){ - case T_char : return Constant.fromValue(~ cst.charValue()); - case T_byte: return Constant.fromValue(~ cst.byteValue()); - case T_short: return Constant.fromValue(~ cst.shortValue()); - case T_int: return Constant.fromValue(~ cst.intValue()); - case T_long: return Constant.fromValue(~ cst.longValue()); - default : return NotAConstant; - } - default : return NotAConstant; + case NOT: + return Constant.fromValue(!cst.booleanValue()); + case PLUS: + return cst; + case MINUS: // the two special -9223372036854775808L and -2147483648 are + // inlined at parseTime + switch (id) { + case T_float: + float f; + if ((f = cst.floatValue()) == 0.0f) { // positive and negative + // 0.... + if (Float.floatToIntBits(f) == 0) + return Constant.fromValue(-0.0f); + else + return Constant.fromValue(0.0f); + } + break; // default case + case T_double: + double d; + if ((d = cst.doubleValue()) == 0.0d) { // positive and negative + // 0.... + if (Double.doubleToLongBits(d) == 0) + return Constant.fromValue(-0.0d); + else + return Constant.fromValue(0.0d); + } + break; // default case + } + return computeConstantOperationMINUS(Zero, T_int, operator, cst, id); + case TWIDDLE: + switch (id) { + case T_char: + return Constant.fromValue(~cst.charValue()); + case T_byte: + return Constant.fromValue(~cst.byteValue()); + case T_short: + return Constant.fromValue(~cst.shortValue()); + case T_int: + return Constant.fromValue(~cst.intValue()); + case T_long: + return Constant.fromValue(~cst.longValue()); + default: + return NotAConstant; + } + default: + return NotAConstant; } - } + } - public static final Constant computeConstantOperation(Constant left, int leftId, int operator, Constant right, int rightId) { + public static final Constant computeConstantOperation(Constant left, + int leftId, int operator, Constant right, int rightId) { switch (operator) { - case AND : return computeConstantOperationAND (left,leftId,operator,right,rightId); - case AND_AND : return computeConstantOperationAND_AND (left,leftId,operator,right,rightId); - case DIVIDE : return computeConstantOperationDIVIDE (left,leftId,operator,right,rightId); - case GREATER : return computeConstantOperationGREATER (left,leftId,operator,right,rightId); - case GREATER_EQUAL : return computeConstantOperationGREATER_EQUAL(left,leftId,operator,right,rightId); - case LEFT_SHIFT : return computeConstantOperationLEFT_SHIFT (left,leftId,operator,right,rightId); - case LESS : return computeConstantOperationLESS (left,leftId,operator,right,rightId); - case LESS_EQUAL : return computeConstantOperationLESS_EQUAL (left,leftId,operator,right,rightId); - case MINUS : return computeConstantOperationMINUS (left,leftId,operator,right,rightId); - case MULTIPLY : return computeConstantOperationMULTIPLY (left,leftId,operator,right,rightId); - case OR : return computeConstantOperationOR (left,leftId,operator,right,rightId); - case OR_OR : return computeConstantOperationOR_OR (left,leftId,operator,right,rightId); - case PLUS : return computeConstantOperationPLUS (left,leftId,operator,right,rightId); - case REMAINDER : return computeConstantOperationREMAINDER (left,leftId,operator,right,rightId); - case RIGHT_SHIFT: return computeConstantOperationRIGHT_SHIFT(left,leftId,operator,right,rightId); - case UNSIGNED_RIGHT_SHIFT: return computeConstantOperationUNSIGNED_RIGHT_SHIFT(left,leftId,operator,right,rightId); - case XOR : return computeConstantOperationXOR (left,leftId,operator,right,rightId); - - default : return NotAConstant; + case AND: + return computeConstantOperationAND(left, leftId, operator, right, + rightId); + case AND_AND: + return computeConstantOperationAND_AND(left, leftId, operator, + right, rightId); + case DIVIDE: + return computeConstantOperationDIVIDE(left, leftId, operator, + right, rightId); + case GREATER: + return computeConstantOperationGREATER(left, leftId, operator, + right, rightId); + case GREATER_EQUAL: + return computeConstantOperationGREATER_EQUAL(left, leftId, + operator, right, rightId); + case LEFT_SHIFT: + return computeConstantOperationLEFT_SHIFT(left, leftId, operator, + right, rightId); + case LESS: + return computeConstantOperationLESS(left, leftId, operator, right, + rightId); + case LESS_EQUAL: + return computeConstantOperationLESS_EQUAL(left, leftId, operator, + right, rightId); + case MINUS: + return computeConstantOperationMINUS(left, leftId, operator, right, + rightId); + case MULTIPLY: + return computeConstantOperationMULTIPLY(left, leftId, operator, + right, rightId); + case OR: + return computeConstantOperationOR(left, leftId, operator, right, + rightId); + case OR_OR: + return computeConstantOperationOR_OR(left, leftId, operator, right, + rightId); + case PLUS: + return computeConstantOperationPLUS(left, leftId, operator, right, + rightId); + case REMAINDER: + return computeConstantOperationREMAINDER(left, leftId, operator, + right, rightId); + case RIGHT_SHIFT: + return computeConstantOperationRIGHT_SHIFT(left, leftId, operator, + right, rightId); + case UNSIGNED_RIGHT_SHIFT: + return computeConstantOperationUNSIGNED_RIGHT_SHIFT(left, leftId, + operator, right, rightId); + case XOR: + return computeConstantOperationXOR(left, leftId, operator, right, + rightId); + + default: + return NotAConstant; } } - - public static final Constant computeConstantOperationAND(Constant left, int leftId, int operator, Constant right, int rightId) { - - switch (leftId){ - case T_boolean : return Constant.fromValue(left.booleanValue() & right.booleanValue()); - case T_char : - switch (rightId){ - case T_char : return Constant.fromValue(left.charValue() & right.charValue()); - case T_byte: return Constant.fromValue(left.charValue() & right.byteValue()); - case T_short: return Constant.fromValue(left.charValue() & right.shortValue()); - case T_int: return Constant.fromValue(left.charValue() & right.intValue()); - case T_long: return Constant.fromValue(left.charValue() & right.longValue()); - } + + public static final Constant computeConstantOperationAND(Constant left, + int leftId, int operator, Constant right, int rightId) { + + switch (leftId) { + case T_boolean: + return Constant.fromValue(left.booleanValue() + & right.booleanValue()); + case T_char: + switch (rightId) { + case T_char: + return Constant.fromValue(left.charValue() & right.charValue()); + case T_byte: + return Constant.fromValue(left.charValue() & right.byteValue()); + case T_short: + return Constant + .fromValue(left.charValue() & right.shortValue()); + case T_int: + return Constant.fromValue(left.charValue() & right.intValue()); + case T_long: + return Constant.fromValue(left.charValue() & right.longValue()); + } break; - case T_byte : - switch (rightId){ - case T_char : return Constant.fromValue(left.byteValue() & right.charValue()); - case T_byte: return Constant.fromValue(left.byteValue() & right.byteValue()); - case T_short: return Constant.fromValue(left.byteValue() & right.shortValue()); - case T_int: return Constant.fromValue(left.byteValue() & right.intValue()); - case T_long: return Constant.fromValue(left.byteValue() & right.longValue()); - } + case T_byte: + switch (rightId) { + case T_char: + return Constant.fromValue(left.byteValue() & right.charValue()); + case T_byte: + return Constant.fromValue(left.byteValue() & right.byteValue()); + case T_short: + return Constant + .fromValue(left.byteValue() & right.shortValue()); + case T_int: + return Constant.fromValue(left.byteValue() & right.intValue()); + case T_long: + return Constant.fromValue(left.byteValue() & right.longValue()); + } break; - case T_short : - switch (rightId){ - case T_char : return Constant.fromValue(left.shortValue() & right.charValue()); - case T_byte: return Constant.fromValue(left.shortValue() & right.byteValue()); - case T_short: return Constant.fromValue(left.shortValue() & right.shortValue()); - case T_int: return Constant.fromValue(left.shortValue() & right.intValue()); - case T_long: return Constant.fromValue(left.shortValue() & right.longValue()); - } + case T_short: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.shortValue() & right.charValue()); + case T_byte: + return Constant + .fromValue(left.shortValue() & right.byteValue()); + case T_short: + return Constant.fromValue(left.shortValue() + & right.shortValue()); + case T_int: + return Constant.fromValue(left.shortValue() & right.intValue()); + case T_long: + return Constant + .fromValue(left.shortValue() & right.longValue()); + } break; - case T_int : - switch (rightId){ - case T_char : return Constant.fromValue(left.intValue() & right.charValue()); - case T_byte: return Constant.fromValue(left.intValue() & right.byteValue()); - case T_short: return Constant.fromValue(left.intValue() & right.shortValue()); - case T_int: return Constant.fromValue(left.intValue() & right.intValue()); - case T_long: return Constant.fromValue(left.intValue() & right.longValue()); - } + case T_int: + switch (rightId) { + case T_char: + return Constant.fromValue(left.intValue() & right.charValue()); + case T_byte: + return Constant.fromValue(left.intValue() & right.byteValue()); + case T_short: + return Constant.fromValue(left.intValue() & right.shortValue()); + case T_int: + return Constant.fromValue(left.intValue() & right.intValue()); + case T_long: + return Constant.fromValue(left.intValue() & right.longValue()); + } break; - case T_long : - switch (rightId){ - case T_char : return Constant.fromValue(left.longValue() & right.charValue()); - case T_byte: return Constant.fromValue(left.longValue() & right.byteValue()); - case T_short: return Constant.fromValue(left.longValue() & right.shortValue()); - case T_int: return Constant.fromValue(left.longValue() & right.intValue()); - case T_long: return Constant.fromValue(left.longValue() & right.longValue()); - } + case T_long: + switch (rightId) { + case T_char: + return Constant.fromValue(left.longValue() & right.charValue()); + case T_byte: + return Constant.fromValue(left.longValue() & right.byteValue()); + case T_short: + return Constant + .fromValue(left.longValue() & right.shortValue()); + case T_int: + return Constant.fromValue(left.longValue() & right.intValue()); + case T_long: + return Constant.fromValue(left.longValue() & right.longValue()); } - + } + return NotAConstant; - } - - public static final Constant computeConstantOperationAND_AND(Constant left, int leftId, int operator, Constant right, int rightId) { - + } + + public static final Constant computeConstantOperationAND_AND(Constant left, + int leftId, int operator, Constant right, int rightId) { + return Constant.fromValue(left.booleanValue() && right.booleanValue()); } - - public static final Constant computeConstantOperationDIVIDE(Constant left, int leftId, int operator, Constant right, int rightId) { - // division by zero must be handled outside this method (error reporting) - - switch (leftId){ - case T_char : - switch (rightId){ - case T_char : return Constant.fromValue(left.charValue() / right.charValue()); - case T_float: return Constant.fromValue(left.charValue() / right.floatValue()); - case T_double: return Constant.fromValue(left.charValue() / right.doubleValue()); - case T_byte: return Constant.fromValue(left.charValue() / right.byteValue()); - case T_short: return Constant.fromValue(left.charValue() / right.shortValue()); - case T_int: return Constant.fromValue(left.charValue() / right.intValue()); - case T_long: return Constant.fromValue(left.charValue() / right.longValue()); - } + + public static final Constant computeConstantOperationDIVIDE(Constant left, + int leftId, int operator, Constant right, int rightId) { + // division by zero must be handled outside this method (error + // reporting) + + switch (leftId) { + case T_char: + switch (rightId) { + case T_char: + return Constant.fromValue(left.charValue() / right.charValue()); + case T_float: + return Constant + .fromValue(left.charValue() / right.floatValue()); + case T_double: + return Constant.fromValue(left.charValue() + / right.doubleValue()); + case T_byte: + return Constant.fromValue(left.charValue() / right.byteValue()); + case T_short: + return Constant + .fromValue(left.charValue() / right.shortValue()); + case T_int: + return Constant.fromValue(left.charValue() / right.intValue()); + case T_long: + return Constant.fromValue(left.charValue() / right.longValue()); + } break; - case T_float : - switch (rightId){ - case T_char : return Constant.fromValue(left.floatValue() / right.charValue()); - case T_float: return Constant.fromValue(left.floatValue() / right.floatValue()); - case T_double: return Constant.fromValue(left.floatValue() / right.doubleValue()); - case T_byte: return Constant.fromValue(left.floatValue() / right.byteValue()); - case T_short: return Constant.fromValue(left.floatValue() / right.shortValue()); - case T_int: return Constant.fromValue(left.floatValue() / right.intValue()); - case T_long: return Constant.fromValue(left.floatValue() / right.longValue()); - } + case T_float: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.floatValue() / right.charValue()); + case T_float: + return Constant.fromValue(left.floatValue() + / right.floatValue()); + case T_double: + return Constant.fromValue(left.floatValue() + / right.doubleValue()); + case T_byte: + return Constant + .fromValue(left.floatValue() / right.byteValue()); + case T_short: + return Constant.fromValue(left.floatValue() + / right.shortValue()); + case T_int: + return Constant.fromValue(left.floatValue() / right.intValue()); + case T_long: + return Constant + .fromValue(left.floatValue() / right.longValue()); + } break; - case T_double : - switch (rightId){ - case T_char : return Constant.fromValue(left.doubleValue() / right.charValue()); - case T_float: return Constant.fromValue(left.doubleValue() / right.floatValue()); - case T_double: return Constant.fromValue(left.doubleValue() / right.doubleValue()); - case T_byte: return Constant.fromValue(left.doubleValue() / right.byteValue()); - case T_short: return Constant.fromValue(left.doubleValue() / right.shortValue()); - case T_int: return Constant.fromValue(left.doubleValue() / right.intValue()); - case T_long: return Constant.fromValue(left.doubleValue() / right.longValue()); - } + case T_double: + switch (rightId) { + case T_char: + return Constant.fromValue(left.doubleValue() + / right.charValue()); + case T_float: + return Constant.fromValue(left.doubleValue() + / right.floatValue()); + case T_double: + return Constant.fromValue(left.doubleValue() + / right.doubleValue()); + case T_byte: + return Constant.fromValue(left.doubleValue() + / right.byteValue()); + case T_short: + return Constant.fromValue(left.doubleValue() + / right.shortValue()); + case T_int: + return Constant + .fromValue(left.doubleValue() / right.intValue()); + case T_long: + return Constant.fromValue(left.doubleValue() + / right.longValue()); + } break; - case T_byte : - switch (rightId){ - case T_char : return Constant.fromValue(left.byteValue() / right.charValue()); - case T_float: return Constant.fromValue(left.byteValue() / right.floatValue()); - case T_double: return Constant.fromValue(left.byteValue() / right.doubleValue()); - case T_byte: return Constant.fromValue(left.byteValue() / right.byteValue()); - case T_short: return Constant.fromValue(left.byteValue() / right.shortValue()); - case T_int: return Constant.fromValue(left.byteValue() / right.intValue()); - case T_long: return Constant.fromValue(left.byteValue() / right.longValue()); - } + case T_byte: + switch (rightId) { + case T_char: + return Constant.fromValue(left.byteValue() / right.charValue()); + case T_float: + return Constant + .fromValue(left.byteValue() / right.floatValue()); + case T_double: + return Constant.fromValue(left.byteValue() + / right.doubleValue()); + case T_byte: + return Constant.fromValue(left.byteValue() / right.byteValue()); + case T_short: + return Constant + .fromValue(left.byteValue() / right.shortValue()); + case T_int: + return Constant.fromValue(left.byteValue() / right.intValue()); + case T_long: + return Constant.fromValue(left.byteValue() / right.longValue()); + } break; - case T_short : - switch (rightId){ - case T_char : return Constant.fromValue(left.shortValue() / right.charValue()); - case T_float: return Constant.fromValue(left.shortValue() / right.floatValue()); - case T_double: return Constant.fromValue(left.shortValue() / right.doubleValue()); - case T_byte: return Constant.fromValue(left.shortValue() / right.byteValue()); - case T_short: return Constant.fromValue(left.shortValue() / right.shortValue()); - case T_int: return Constant.fromValue(left.shortValue() / right.intValue()); - case T_long: return Constant.fromValue(left.shortValue() / right.longValue()); - } + case T_short: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.shortValue() / right.charValue()); + case T_float: + return Constant.fromValue(left.shortValue() + / right.floatValue()); + case T_double: + return Constant.fromValue(left.shortValue() + / right.doubleValue()); + case T_byte: + return Constant + .fromValue(left.shortValue() / right.byteValue()); + case T_short: + return Constant.fromValue(left.shortValue() + / right.shortValue()); + case T_int: + return Constant.fromValue(left.shortValue() / right.intValue()); + case T_long: + return Constant + .fromValue(left.shortValue() / right.longValue()); + } break; - case T_int : - switch (rightId){ - case T_char : return Constant.fromValue(left.intValue() / right.charValue()); - case T_float: return Constant.fromValue(left.intValue() / right.floatValue()); - case T_double: return Constant.fromValue(left.intValue() / right.doubleValue()); - case T_byte: return Constant.fromValue(left.intValue() / right.byteValue()); - case T_short: return Constant.fromValue(left.intValue() / right.shortValue()); - case T_int: return Constant.fromValue(left.intValue() / right.intValue()); - case T_long: return Constant.fromValue(left.intValue() / right.longValue()); - } + case T_int: + switch (rightId) { + case T_char: + return Constant.fromValue(left.intValue() / right.charValue()); + case T_float: + return Constant.fromValue(left.intValue() / right.floatValue()); + case T_double: + return Constant + .fromValue(left.intValue() / right.doubleValue()); + case T_byte: + return Constant.fromValue(left.intValue() / right.byteValue()); + case T_short: + return Constant.fromValue(left.intValue() / right.shortValue()); + case T_int: + return Constant.fromValue(left.intValue() / right.intValue()); + case T_long: + return Constant.fromValue(left.intValue() / right.longValue()); + } break; - case T_long : - switch (rightId){ - case T_char : return Constant.fromValue(left.longValue() / right.charValue()); - case T_float: return Constant.fromValue(left.longValue() / right.floatValue()); - case T_double: return Constant.fromValue(left.longValue() / right.doubleValue()); - case T_byte: return Constant.fromValue(left.longValue() / right.byteValue()); - case T_short: return Constant.fromValue(left.longValue() / right.shortValue()); - case T_int: return Constant.fromValue(left.longValue() / right.intValue()); - case T_long: return Constant.fromValue(left.longValue() / right.longValue()); - } - + case T_long: + switch (rightId) { + case T_char: + return Constant.fromValue(left.longValue() / right.charValue()); + case T_float: + return Constant + .fromValue(left.longValue() / right.floatValue()); + case T_double: + return Constant.fromValue(left.longValue() + / right.doubleValue()); + case T_byte: + return Constant.fromValue(left.longValue() / right.byteValue()); + case T_short: + return Constant + .fromValue(left.longValue() / right.shortValue()); + case T_int: + return Constant.fromValue(left.longValue() / right.intValue()); + case T_long: + return Constant.fromValue(left.longValue() / right.longValue()); } - + + } + return NotAConstant; - } - - public static final Constant computeConstantOperationEQUAL_EQUAL(Constant left, int leftId, int operator, Constant right, int rightId) { - - switch (leftId){ - case T_boolean : - if (rightId == T_boolean) { - return Constant.fromValue(left.booleanValue() == right.booleanValue()); - } + } + + public static final Constant computeConstantOperationEQUAL_EQUAL( + Constant left, int leftId, int operator, Constant right, int rightId) { + + switch (leftId) { + case T_boolean: + if (rightId == T_boolean) { + return Constant.fromValue(left.booleanValue() == right + .booleanValue()); + } break; - case T_char : - switch (rightId){ - case T_char : return Constant.fromValue(left.charValue() == right.charValue()); - case T_float: return Constant.fromValue(left.charValue() == right.floatValue()); - case T_double: return Constant.fromValue(left.charValue() == right.doubleValue()); - case T_byte: return Constant.fromValue(left.charValue() == right.byteValue()); - case T_short: return Constant.fromValue(left.charValue() == right.shortValue()); - case T_int: return Constant.fromValue(left.charValue() == right.intValue()); - case T_long: return Constant.fromValue(left.charValue() == right.longValue());} - break; - case T_float : - switch (rightId){ - case T_char : return Constant.fromValue(left.floatValue() == right.charValue()); - case T_float: return Constant.fromValue(left.floatValue() == right.floatValue()); - case T_double: return Constant.fromValue(left.floatValue() == right.doubleValue()); - case T_byte: return Constant.fromValue(left.floatValue() == right.byteValue()); - case T_short: return Constant.fromValue(left.floatValue() == right.shortValue()); - case T_int: return Constant.fromValue(left.floatValue() == right.intValue()); - case T_long: return Constant.fromValue(left.floatValue() == right.longValue()); - } + case T_char: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.charValue() == right.charValue()); + case T_float: + return Constant.fromValue(left.charValue() == right + .floatValue()); + case T_double: + return Constant.fromValue(left.charValue() == right + .doubleValue()); + case T_byte: + return Constant + .fromValue(left.charValue() == right.byteValue()); + case T_short: + return Constant.fromValue(left.charValue() == right + .shortValue()); + case T_int: + return Constant.fromValue(left.charValue() == right.intValue()); + case T_long: + return Constant + .fromValue(left.charValue() == right.longValue()); + } break; - case T_double : - switch (rightId){ - case T_char : return Constant.fromValue(left.doubleValue() == right.charValue()); - case T_float: return Constant.fromValue(left.doubleValue() == right.floatValue()); - case T_double: return Constant.fromValue(left.doubleValue() == right.doubleValue()); - case T_byte: return Constant.fromValue(left.doubleValue() == right.byteValue()); - case T_short: return Constant.fromValue(left.doubleValue() == right.shortValue()); - case T_int: return Constant.fromValue(left.doubleValue() == right.intValue()); - case T_long: return Constant.fromValue(left.doubleValue() == right.longValue()); - } + case T_float: + switch (rightId) { + case T_char: + return Constant.fromValue(left.floatValue() == right + .charValue()); + case T_float: + return Constant.fromValue(left.floatValue() == right + .floatValue()); + case T_double: + return Constant.fromValue(left.floatValue() == right + .doubleValue()); + case T_byte: + return Constant.fromValue(left.floatValue() == right + .byteValue()); + case T_short: + return Constant.fromValue(left.floatValue() == right + .shortValue()); + case T_int: + return Constant + .fromValue(left.floatValue() == right.intValue()); + case T_long: + return Constant.fromValue(left.floatValue() == right + .longValue()); + } break; - case T_byte : - switch (rightId){ - case T_char : return Constant.fromValue(left.byteValue() == right.charValue()); - case T_float: return Constant.fromValue(left.byteValue() == right.floatValue()); - case T_double: return Constant.fromValue(left.byteValue() == right.doubleValue()); - case T_byte: return Constant.fromValue(left.byteValue() == right.byteValue()); - case T_short: return Constant.fromValue(left.byteValue() == right.shortValue()); - case T_int: return Constant.fromValue(left.byteValue() == right.intValue()); - case T_long: return Constant.fromValue(left.byteValue() == right.longValue()); - } - break; - case T_short : - switch (rightId){ - case T_char : return Constant.fromValue(left.shortValue() == right.charValue()); - case T_float: return Constant.fromValue(left.shortValue() == right.floatValue()); - case T_double: return Constant.fromValue(left.shortValue() == right.doubleValue()); - case T_byte: return Constant.fromValue(left.shortValue() == right.byteValue()); - case T_short: return Constant.fromValue(left.shortValue() == right.shortValue()); - case T_int: return Constant.fromValue(left.shortValue() == right.intValue()); - case T_long: return Constant.fromValue(left.shortValue() == right.longValue()); - } + case T_double: + switch (rightId) { + case T_char: + return Constant.fromValue(left.doubleValue() == right + .charValue()); + case T_float: + return Constant.fromValue(left.doubleValue() == right + .floatValue()); + case T_double: + return Constant.fromValue(left.doubleValue() == right + .doubleValue()); + case T_byte: + return Constant.fromValue(left.doubleValue() == right + .byteValue()); + case T_short: + return Constant.fromValue(left.doubleValue() == right + .shortValue()); + case T_int: + return Constant.fromValue(left.doubleValue() == right + .intValue()); + case T_long: + return Constant.fromValue(left.doubleValue() == right + .longValue()); + } break; - case T_int : - switch (rightId){ - case T_char : return Constant.fromValue(left.intValue() == right.charValue()); - case T_float: return Constant.fromValue(left.intValue() == right.floatValue()); - case T_double: return Constant.fromValue(left.intValue() == right.doubleValue()); - case T_byte: return Constant.fromValue(left.intValue() == right.byteValue()); - case T_short: return Constant.fromValue(left.intValue() == right.shortValue()); - case T_int: return Constant.fromValue(left.intValue() == right.intValue()); - case T_long: return Constant.fromValue(left.intValue() == right.longValue()); - } - break; - case T_long : - switch (rightId){ - case T_char : return Constant.fromValue(left.longValue() == right.charValue()); - case T_float: return Constant.fromValue(left.longValue() == right.floatValue()); - case T_double: return Constant.fromValue(left.longValue() == right.doubleValue()); - case T_byte: return Constant.fromValue(left.longValue() == right.byteValue()); - case T_short: return Constant.fromValue(left.longValue() == right.shortValue()); - case T_int: return Constant.fromValue(left.longValue() == right.intValue()); - case T_long: return Constant.fromValue(left.longValue() == right.longValue()); - } + case T_byte: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.byteValue() == right.charValue()); + case T_float: + return Constant.fromValue(left.byteValue() == right + .floatValue()); + case T_double: + return Constant.fromValue(left.byteValue() == right + .doubleValue()); + case T_byte: + return Constant + .fromValue(left.byteValue() == right.byteValue()); + case T_short: + return Constant.fromValue(left.byteValue() == right + .shortValue()); + case T_int: + return Constant.fromValue(left.byteValue() == right.intValue()); + case T_long: + return Constant + .fromValue(left.byteValue() == right.longValue()); + } break; - case T_String : - if (rightId == T_String) { - //String are interned in th compiler==>thus if two string constant - //get to be compared, it is an equal on the vale which is done - return Constant.fromValue(((StringConstant)left).compileTimeEqual((StringConstant)right)); - } - break; - case T_null : - if (rightId == T_String) { - return Constant.fromValue(false); - } else { - if (rightId == T_null) { - return Constant.fromValue(true); - } + case T_short: + switch (rightId) { + case T_char: + return Constant.fromValue(left.shortValue() == right + .charValue()); + case T_float: + return Constant.fromValue(left.shortValue() == right + .floatValue()); + case T_double: + return Constant.fromValue(left.shortValue() == right + .doubleValue()); + case T_byte: + return Constant.fromValue(left.shortValue() == right + .byteValue()); + case T_short: + return Constant.fromValue(left.shortValue() == right + .shortValue()); + case T_int: + return Constant + .fromValue(left.shortValue() == right.intValue()); + case T_long: + return Constant.fromValue(left.shortValue() == right + .longValue()); + } + break; + case T_int: + switch (rightId) { + case T_char: + return Constant.fromValue(left.intValue() == right.charValue()); + case T_float: + return Constant + .fromValue(left.intValue() == right.floatValue()); + case T_double: + return Constant.fromValue(left.intValue() == right + .doubleValue()); + case T_byte: + return Constant.fromValue(left.intValue() == right.byteValue()); + case T_short: + return Constant + .fromValue(left.intValue() == right.shortValue()); + case T_int: + return Constant.fromValue(left.intValue() == right.intValue()); + case T_long: + return Constant.fromValue(left.intValue() == right.longValue()); + } + break; + case T_long: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.longValue() == right.charValue()); + case T_float: + return Constant.fromValue(left.longValue() == right + .floatValue()); + case T_double: + return Constant.fromValue(left.longValue() == right + .doubleValue()); + case T_byte: + return Constant + .fromValue(left.longValue() == right.byteValue()); + case T_short: + return Constant.fromValue(left.longValue() == right + .shortValue()); + case T_int: + return Constant.fromValue(left.longValue() == right.intValue()); + case T_long: + return Constant + .fromValue(left.longValue() == right.longValue()); + } + break; + case T_String: + if (rightId == T_String) { + // String are interned in th compiler==>thus if two string + // constant + // get to be compared, it is an equal on the vale which is done + return Constant.fromValue(((StringConstant) left) + .compileTimeEqual((StringConstant) right)); + } + break; + case T_null: + if (rightId == T_String) { + return Constant.fromValue(false); + } else { + if (rightId == T_null) { + return Constant.fromValue(true); } } - + } + return Constant.fromValue(false); } - - public static final Constant computeConstantOperationGREATER(Constant left, int leftId, int operator, Constant right, int rightId) { - - switch (leftId){ - case T_char : - switch (rightId){ - case T_char : return Constant.fromValue(left.charValue() > right.charValue()); - case T_float: return Constant.fromValue(left.charValue() > right.floatValue()); - case T_double: return Constant.fromValue(left.charValue() > right.doubleValue()); - case T_byte: return Constant.fromValue(left.charValue() > right.byteValue()); - case T_short: return Constant.fromValue(left.charValue() > right.shortValue()); - case T_int: return Constant.fromValue(left.charValue() > right.intValue()); - case T_long: return Constant.fromValue(left.charValue() > right.longValue()); - } + + public static final Constant computeConstantOperationGREATER(Constant left, + int leftId, int operator, Constant right, int rightId) { + + switch (leftId) { + case T_char: + switch (rightId) { + case T_char: + return Constant.fromValue(left.charValue() > right.charValue()); + case T_float: + return Constant + .fromValue(left.charValue() > right.floatValue()); + case T_double: + return Constant.fromValue(left.charValue() > right + .doubleValue()); + case T_byte: + return Constant.fromValue(left.charValue() > right.byteValue()); + case T_short: + return Constant + .fromValue(left.charValue() > right.shortValue()); + case T_int: + return Constant.fromValue(left.charValue() > right.intValue()); + case T_long: + return Constant.fromValue(left.charValue() > right.longValue()); + } break; - case T_float : - switch (rightId){ - case T_char : return Constant.fromValue(left.floatValue() > right.charValue()); - case T_float: return Constant.fromValue(left.floatValue() > right.floatValue()); - case T_double: return Constant.fromValue(left.floatValue() > right.doubleValue()); - case T_byte: return Constant.fromValue(left.floatValue() > right.byteValue()); - case T_short: return Constant.fromValue(left.floatValue() > right.shortValue()); - case T_int: return Constant.fromValue(left.floatValue() > right.intValue()); - case T_long: return Constant.fromValue(left.floatValue() > right.longValue()); - } + case T_float: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.floatValue() > right.charValue()); + case T_float: + return Constant.fromValue(left.floatValue() > right + .floatValue()); + case T_double: + return Constant.fromValue(left.floatValue() > right + .doubleValue()); + case T_byte: + return Constant + .fromValue(left.floatValue() > right.byteValue()); + case T_short: + return Constant.fromValue(left.floatValue() > right + .shortValue()); + case T_int: + return Constant.fromValue(left.floatValue() > right.intValue()); + case T_long: + return Constant + .fromValue(left.floatValue() > right.longValue()); + } break; - case T_double : - switch (rightId){ - case T_char : return Constant.fromValue(left.doubleValue() > right.charValue()); - case T_float: return Constant.fromValue(left.doubleValue() > right.floatValue()); - case T_double: return Constant.fromValue(left.doubleValue() > right.doubleValue()); - case T_byte: return Constant.fromValue(left.doubleValue() > right.byteValue()); - case T_short: return Constant.fromValue(left.doubleValue() > right.shortValue()); - case T_int: return Constant.fromValue(left.doubleValue() > right.intValue()); - case T_long: return Constant.fromValue(left.doubleValue() > right.longValue()); - } + case T_double: + switch (rightId) { + case T_char: + return Constant.fromValue(left.doubleValue() > right + .charValue()); + case T_float: + return Constant.fromValue(left.doubleValue() > right + .floatValue()); + case T_double: + return Constant.fromValue(left.doubleValue() > right + .doubleValue()); + case T_byte: + return Constant.fromValue(left.doubleValue() > right + .byteValue()); + case T_short: + return Constant.fromValue(left.doubleValue() > right + .shortValue()); + case T_int: + return Constant + .fromValue(left.doubleValue() > right.intValue()); + case T_long: + return Constant.fromValue(left.doubleValue() > right + .longValue()); + } break; - case T_byte : - switch (rightId){ - case T_char : return Constant.fromValue(left.byteValue() > right.charValue()); - case T_float: return Constant.fromValue(left.byteValue() > right.floatValue()); - case T_double: return Constant.fromValue(left.byteValue() > right.doubleValue()); - case T_byte: return Constant.fromValue(left.byteValue() > right.byteValue()); - case T_short: return Constant.fromValue(left.byteValue() > right.shortValue()); - case T_int: return Constant.fromValue(left.byteValue() > right.intValue()); - case T_long: return Constant.fromValue(left.byteValue() > right.longValue()); - } - break; - case T_short : - switch (rightId){ - case T_char : return Constant.fromValue(left.shortValue() > right.charValue()); - case T_float: return Constant.fromValue(left.shortValue() > right.floatValue()); - case T_double: return Constant.fromValue(left.shortValue() > right.doubleValue()); - case T_byte: return Constant.fromValue(left.shortValue() > right.byteValue()); - case T_short: return Constant.fromValue(left.shortValue() > right.shortValue()); - case T_int: return Constant.fromValue(left.shortValue() > right.intValue()); - case T_long: return Constant.fromValue(left.shortValue() > right.longValue()); - } + case T_byte: + switch (rightId) { + case T_char: + return Constant.fromValue(left.byteValue() > right.charValue()); + case T_float: + return Constant + .fromValue(left.byteValue() > right.floatValue()); + case T_double: + return Constant.fromValue(left.byteValue() > right + .doubleValue()); + case T_byte: + return Constant.fromValue(left.byteValue() > right.byteValue()); + case T_short: + return Constant + .fromValue(left.byteValue() > right.shortValue()); + case T_int: + return Constant.fromValue(left.byteValue() > right.intValue()); + case T_long: + return Constant.fromValue(left.byteValue() > right.longValue()); + } break; - case T_int : - switch (rightId){ - case T_char : return Constant.fromValue(left.intValue() > right.charValue()); - case T_float: return Constant.fromValue(left.intValue() > right.floatValue()); - case T_double: return Constant.fromValue(left.intValue() > right.doubleValue()); - case T_byte: return Constant.fromValue(left.intValue() > right.byteValue()); - case T_short: return Constant.fromValue(left.intValue() > right.shortValue()); - case T_int: return Constant.fromValue(left.intValue() > right.intValue()); - case T_long: return Constant.fromValue(left.intValue() > right.longValue()); - } - break; - case T_long : - switch (rightId){ - case T_char : return Constant.fromValue(left.longValue() > right.charValue()); - case T_float: return Constant.fromValue(left.longValue() > right.floatValue()); - case T_double: return Constant.fromValue(left.longValue() > right.doubleValue()); - case T_byte: return Constant.fromValue(left.longValue() > right.byteValue()); - case T_short: return Constant.fromValue(left.longValue() > right.shortValue()); - case T_int: return Constant.fromValue(left.longValue() > right.intValue()); - case T_long: return Constant.fromValue(left.longValue() > right.longValue()); - } - + case T_short: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.shortValue() > right.charValue()); + case T_float: + return Constant.fromValue(left.shortValue() > right + .floatValue()); + case T_double: + return Constant.fromValue(left.shortValue() > right + .doubleValue()); + case T_byte: + return Constant + .fromValue(left.shortValue() > right.byteValue()); + case T_short: + return Constant.fromValue(left.shortValue() > right + .shortValue()); + case T_int: + return Constant.fromValue(left.shortValue() > right.intValue()); + case T_long: + return Constant + .fromValue(left.shortValue() > right.longValue()); } - + break; + case T_int: + switch (rightId) { + case T_char: + return Constant.fromValue(left.intValue() > right.charValue()); + case T_float: + return Constant.fromValue(left.intValue() > right.floatValue()); + case T_double: + return Constant + .fromValue(left.intValue() > right.doubleValue()); + case T_byte: + return Constant.fromValue(left.intValue() > right.byteValue()); + case T_short: + return Constant.fromValue(left.intValue() > right.shortValue()); + case T_int: + return Constant.fromValue(left.intValue() > right.intValue()); + case T_long: + return Constant.fromValue(left.intValue() > right.longValue()); + } + break; + case T_long: + switch (rightId) { + case T_char: + return Constant.fromValue(left.longValue() > right.charValue()); + case T_float: + return Constant + .fromValue(left.longValue() > right.floatValue()); + case T_double: + return Constant.fromValue(left.longValue() > right + .doubleValue()); + case T_byte: + return Constant.fromValue(left.longValue() > right.byteValue()); + case T_short: + return Constant + .fromValue(left.longValue() > right.shortValue()); + case T_int: + return Constant.fromValue(left.longValue() > right.intValue()); + case T_long: + return Constant.fromValue(left.longValue() > right.longValue()); + } + + } + return NotAConstant; } - public static final Constant computeConstantOperationGREATER_EQUAL(Constant left, int leftId, int operator, Constant right, int rightId) { - - switch (leftId){ - case T_char : - switch (rightId){ - case T_char : return Constant.fromValue(left.charValue() >= right.charValue()); - case T_float: return Constant.fromValue(left.charValue() >= right.floatValue()); - case T_double: return Constant.fromValue(left.charValue() >= right.doubleValue()); - case T_byte: return Constant.fromValue(left.charValue() >= right.byteValue()); - case T_short: return Constant.fromValue(left.charValue() >= right.shortValue()); - case T_int: return Constant.fromValue(left.charValue() >= right.intValue()); - case T_long: return Constant.fromValue(left.charValue() >= right.longValue()); - } + public static final Constant computeConstantOperationGREATER_EQUAL( + Constant left, int leftId, int operator, Constant right, int rightId) { + + switch (leftId) { + case T_char: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.charValue() >= right.charValue()); + case T_float: + return Constant.fromValue(left.charValue() >= right + .floatValue()); + case T_double: + return Constant.fromValue(left.charValue() >= right + .doubleValue()); + case T_byte: + return Constant + .fromValue(left.charValue() >= right.byteValue()); + case T_short: + return Constant.fromValue(left.charValue() >= right + .shortValue()); + case T_int: + return Constant.fromValue(left.charValue() >= right.intValue()); + case T_long: + return Constant + .fromValue(left.charValue() >= right.longValue()); + } break; - case T_float : - switch (rightId){ - case T_char : return Constant.fromValue(left.floatValue() >= right.charValue()); - case T_float: return Constant.fromValue(left.floatValue() >= right.floatValue()); - case T_double: return Constant.fromValue(left.floatValue() >= right.doubleValue()); - case T_byte: return Constant.fromValue(left.floatValue() >= right.byteValue()); - case T_short: return Constant.fromValue(left.floatValue() >= right.shortValue()); - case T_int: return Constant.fromValue(left.floatValue() >= right.intValue()); - case T_long: return Constant.fromValue(left.floatValue() >= right.longValue()); - } + case T_float: + switch (rightId) { + case T_char: + return Constant.fromValue(left.floatValue() >= right + .charValue()); + case T_float: + return Constant.fromValue(left.floatValue() >= right + .floatValue()); + case T_double: + return Constant.fromValue(left.floatValue() >= right + .doubleValue()); + case T_byte: + return Constant.fromValue(left.floatValue() >= right + .byteValue()); + case T_short: + return Constant.fromValue(left.floatValue() >= right + .shortValue()); + case T_int: + return Constant + .fromValue(left.floatValue() >= right.intValue()); + case T_long: + return Constant.fromValue(left.floatValue() >= right + .longValue()); + } break; - case T_double : - switch (rightId){ - case T_char : return Constant.fromValue(left.doubleValue() >= right.charValue()); - case T_float: return Constant.fromValue(left.doubleValue() >= right.floatValue()); - case T_double: return Constant.fromValue(left.doubleValue() >= right.doubleValue()); - case T_byte: return Constant.fromValue(left.doubleValue() >= right.byteValue()); - case T_short: return Constant.fromValue(left.doubleValue() >= right.shortValue()); - case T_int: return Constant.fromValue(left.doubleValue() >= right.intValue()); - case T_long: return Constant.fromValue(left.doubleValue() >= right.longValue()); - } + case T_double: + switch (rightId) { + case T_char: + return Constant.fromValue(left.doubleValue() >= right + .charValue()); + case T_float: + return Constant.fromValue(left.doubleValue() >= right + .floatValue()); + case T_double: + return Constant.fromValue(left.doubleValue() >= right + .doubleValue()); + case T_byte: + return Constant.fromValue(left.doubleValue() >= right + .byteValue()); + case T_short: + return Constant.fromValue(left.doubleValue() >= right + .shortValue()); + case T_int: + return Constant.fromValue(left.doubleValue() >= right + .intValue()); + case T_long: + return Constant.fromValue(left.doubleValue() >= right + .longValue()); + } break; - case T_byte : - switch (rightId){ - case T_char : return Constant.fromValue(left.byteValue() >= right.charValue()); - case T_float: return Constant.fromValue(left.byteValue() >= right.floatValue()); - case T_double: return Constant.fromValue(left.byteValue() >= right.doubleValue()); - case T_byte: return Constant.fromValue(left.byteValue() >= right.byteValue()); - case T_short: return Constant.fromValue(left.byteValue() >= right.shortValue()); - case T_int: return Constant.fromValue(left.byteValue() >= right.intValue()); - case T_long: return Constant.fromValue(left.byteValue() >= right.longValue()); - } - break; - case T_short : - switch (rightId){ - case T_char : return Constant.fromValue(left.shortValue() >= right.charValue()); - case T_float: return Constant.fromValue(left.shortValue() >= right.floatValue()); - case T_double: return Constant.fromValue(left.shortValue() >= right.doubleValue()); - case T_byte: return Constant.fromValue(left.shortValue() >= right.byteValue()); - case T_short: return Constant.fromValue(left.shortValue() >= right.shortValue()); - case T_int: return Constant.fromValue(left.shortValue() >= right.intValue()); - case T_long: return Constant.fromValue(left.shortValue() >= right.longValue()); - } + case T_byte: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.byteValue() >= right.charValue()); + case T_float: + return Constant.fromValue(left.byteValue() >= right + .floatValue()); + case T_double: + return Constant.fromValue(left.byteValue() >= right + .doubleValue()); + case T_byte: + return Constant + .fromValue(left.byteValue() >= right.byteValue()); + case T_short: + return Constant.fromValue(left.byteValue() >= right + .shortValue()); + case T_int: + return Constant.fromValue(left.byteValue() >= right.intValue()); + case T_long: + return Constant + .fromValue(left.byteValue() >= right.longValue()); + } break; - case T_int : - switch (rightId){ - case T_char : return Constant.fromValue(left.intValue() >= right.charValue()); - case T_float: return Constant.fromValue(left.intValue() >= right.floatValue()); - case T_double: return Constant.fromValue(left.intValue() >= right.doubleValue()); - case T_byte: return Constant.fromValue(left.intValue() >= right.byteValue()); - case T_short: return Constant.fromValue(left.intValue() >= right.shortValue()); - case T_int: return Constant.fromValue(left.intValue() >= right.intValue()); - case T_long: return Constant.fromValue(left.intValue() >= right.longValue()); - } - break; - case T_long : - switch (rightId){ - case T_char : return Constant.fromValue(left.longValue() >= right.charValue()); - case T_float: return Constant.fromValue(left.longValue() >= right.floatValue()); - case T_double: return Constant.fromValue(left.longValue() >= right.doubleValue()); - case T_byte: return Constant.fromValue(left.longValue() >= right.byteValue()); - case T_short: return Constant.fromValue(left.longValue() >= right.shortValue()); - case T_int: return Constant.fromValue(left.longValue() >= right.intValue()); - case T_long: return Constant.fromValue(left.longValue() >= right.longValue()); - } - + case T_short: + switch (rightId) { + case T_char: + return Constant.fromValue(left.shortValue() >= right + .charValue()); + case T_float: + return Constant.fromValue(left.shortValue() >= right + .floatValue()); + case T_double: + return Constant.fromValue(left.shortValue() >= right + .doubleValue()); + case T_byte: + return Constant.fromValue(left.shortValue() >= right + .byteValue()); + case T_short: + return Constant.fromValue(left.shortValue() >= right + .shortValue()); + case T_int: + return Constant + .fromValue(left.shortValue() >= right.intValue()); + case T_long: + return Constant.fromValue(left.shortValue() >= right + .longValue()); + } + break; + case T_int: + switch (rightId) { + case T_char: + return Constant.fromValue(left.intValue() >= right.charValue()); + case T_float: + return Constant + .fromValue(left.intValue() >= right.floatValue()); + case T_double: + return Constant.fromValue(left.intValue() >= right + .doubleValue()); + case T_byte: + return Constant.fromValue(left.intValue() >= right.byteValue()); + case T_short: + return Constant + .fromValue(left.intValue() >= right.shortValue()); + case T_int: + return Constant.fromValue(left.intValue() >= right.intValue()); + case T_long: + return Constant.fromValue(left.intValue() >= right.longValue()); + } + break; + case T_long: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.longValue() >= right.charValue()); + case T_float: + return Constant.fromValue(left.longValue() >= right + .floatValue()); + case T_double: + return Constant.fromValue(left.longValue() >= right + .doubleValue()); + case T_byte: + return Constant + .fromValue(left.longValue() >= right.byteValue()); + case T_short: + return Constant.fromValue(left.longValue() >= right + .shortValue()); + case T_int: + return Constant.fromValue(left.longValue() >= right.intValue()); + case T_long: + return Constant + .fromValue(left.longValue() >= right.longValue()); } - + + } + return NotAConstant; - } - - public static final Constant computeConstantOperationLEFT_SHIFT(Constant left, int leftId, int operator, Constant right, int rightId) { - - switch (leftId){ - case T_char : - switch (rightId){ - case T_char : return Constant.fromValue(left.charValue() << right.charValue()); - case T_byte: return Constant.fromValue(left.charValue() << right.byteValue()); - case T_short: return Constant.fromValue(left.charValue() << right.shortValue()); - case T_int: return Constant.fromValue(left.charValue() << right.intValue()); - case T_long: return Constant.fromValue(left.charValue() << right.longValue()); - } + } + + public static final Constant computeConstantOperationLEFT_SHIFT( + Constant left, int leftId, int operator, Constant right, int rightId) { + + switch (leftId) { + case T_char: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.charValue() << right.charValue()); + case T_byte: + return Constant + .fromValue(left.charValue() << right.byteValue()); + case T_short: + return Constant.fromValue(left.charValue() << right + .shortValue()); + case T_int: + return Constant.fromValue(left.charValue() << right.intValue()); + case T_long: + return Constant + .fromValue(left.charValue() << right.longValue()); + } break; - case T_byte : - switch (rightId){ - case T_char : return Constant.fromValue(left.byteValue() << right.charValue()); - case T_byte: return Constant.fromValue(left.byteValue() << right.byteValue()); - case T_short: return Constant.fromValue(left.byteValue() << right.shortValue()); - case T_int: return Constant.fromValue(left.byteValue() << right.intValue()); - case T_long: return Constant.fromValue(left.byteValue() << right.longValue()); - } + case T_byte: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.byteValue() << right.charValue()); + case T_byte: + return Constant + .fromValue(left.byteValue() << right.byteValue()); + case T_short: + return Constant.fromValue(left.byteValue() << right + .shortValue()); + case T_int: + return Constant.fromValue(left.byteValue() << right.intValue()); + case T_long: + return Constant + .fromValue(left.byteValue() << right.longValue()); + } break; - case T_short : - switch (rightId){ - case T_char : return Constant.fromValue(left.shortValue() << right.charValue()); - case T_byte: return Constant.fromValue(left.shortValue() << right.byteValue()); - case T_short: return Constant.fromValue(left.shortValue() << right.shortValue()); - case T_int: return Constant.fromValue(left.shortValue() << right.intValue()); - case T_long: return Constant.fromValue(left.shortValue() << right.longValue()); - } + case T_short: + switch (rightId) { + case T_char: + return Constant.fromValue(left.shortValue() << right + .charValue()); + case T_byte: + return Constant.fromValue(left.shortValue() << right + .byteValue()); + case T_short: + return Constant.fromValue(left.shortValue() << right + .shortValue()); + case T_int: + return Constant + .fromValue(left.shortValue() << right.intValue()); + case T_long: + return Constant.fromValue(left.shortValue() << right + .longValue()); + } break; - case T_int : - switch (rightId){ - case T_char : return Constant.fromValue(left.intValue() << right.charValue()); - case T_byte: return Constant.fromValue(left.intValue() << right.byteValue()); - case T_short: return Constant.fromValue(left.intValue() << right.shortValue()); - case T_int: return Constant.fromValue(left.intValue() << right.intValue()); - case T_long: return Constant.fromValue(left.intValue() << right.longValue()); - } + case T_int: + switch (rightId) { + case T_char: + return Constant.fromValue(left.intValue() << right.charValue()); + case T_byte: + return Constant.fromValue(left.intValue() << right.byteValue()); + case T_short: + return Constant + .fromValue(left.intValue() << right.shortValue()); + case T_int: + return Constant.fromValue(left.intValue() << right.intValue()); + case T_long: + return Constant.fromValue(left.intValue() << right.longValue()); + } break; - case T_long : - switch (rightId){ - case T_char : return Constant.fromValue(left.longValue() << right.charValue()); - case T_byte: return Constant.fromValue(left.longValue() << right.byteValue()); - case T_short: return Constant.fromValue(left.longValue() << right.shortValue()); - case T_int: return Constant.fromValue(left.longValue() << right.intValue()); - case T_long: return Constant.fromValue(left.longValue() << right.longValue()); - } - + case T_long: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.longValue() << right.charValue()); + case T_byte: + return Constant + .fromValue(left.longValue() << right.byteValue()); + case T_short: + return Constant.fromValue(left.longValue() << right + .shortValue()); + case T_int: + return Constant.fromValue(left.longValue() << right.intValue()); + case T_long: + return Constant + .fromValue(left.longValue() << right.longValue()); } - + + } + return NotAConstant; - } - - public static final Constant computeConstantOperationLESS(Constant left, int leftId, int operator, Constant right, int rightId) { - - switch (leftId){ - case T_char : - switch (rightId){ - case T_char : return Constant.fromValue(left.charValue() < right.charValue()); - case T_float: return Constant.fromValue(left.charValue() < right.floatValue()); - case T_double: return Constant.fromValue(left.charValue() < right.doubleValue()); - case T_byte: return Constant.fromValue(left.charValue() < right.byteValue()); - case T_short: return Constant.fromValue(left.charValue() < right.shortValue()); - case T_int: return Constant.fromValue(left.charValue() < right.intValue()); - case T_long: return Constant.fromValue(left.charValue() < right.longValue()); - } + } + + public static final Constant computeConstantOperationLESS(Constant left, + int leftId, int operator, Constant right, int rightId) { + + switch (leftId) { + case T_char: + switch (rightId) { + case T_char: + return Constant.fromValue(left.charValue() < right.charValue()); + case T_float: + return Constant + .fromValue(left.charValue() < right.floatValue()); + case T_double: + return Constant.fromValue(left.charValue() < right + .doubleValue()); + case T_byte: + return Constant.fromValue(left.charValue() < right.byteValue()); + case T_short: + return Constant + .fromValue(left.charValue() < right.shortValue()); + case T_int: + return Constant.fromValue(left.charValue() < right.intValue()); + case T_long: + return Constant.fromValue(left.charValue() < right.longValue()); + } break; - case T_float : - switch (rightId){ - case T_char : return Constant.fromValue(left.floatValue() < right.charValue()); - case T_float: return Constant.fromValue(left.floatValue() < right.floatValue()); - case T_double: return Constant.fromValue(left.floatValue() < right.doubleValue()); - case T_byte: return Constant.fromValue(left.floatValue() < right.byteValue()); - case T_short: return Constant.fromValue(left.floatValue() < right.shortValue()); - case T_int: return Constant.fromValue(left.floatValue() < right.intValue()); - case T_long: return Constant.fromValue(left.floatValue() < right.longValue()); - } + case T_float: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.floatValue() < right.charValue()); + case T_float: + return Constant.fromValue(left.floatValue() < right + .floatValue()); + case T_double: + return Constant.fromValue(left.floatValue() < right + .doubleValue()); + case T_byte: + return Constant + .fromValue(left.floatValue() < right.byteValue()); + case T_short: + return Constant.fromValue(left.floatValue() < right + .shortValue()); + case T_int: + return Constant.fromValue(left.floatValue() < right.intValue()); + case T_long: + return Constant + .fromValue(left.floatValue() < right.longValue()); + } break; - case T_double : - switch (rightId){ - case T_char : return Constant.fromValue(left.doubleValue() < right.charValue()); - case T_float: return Constant.fromValue(left.doubleValue() < right.floatValue()); - case T_double: return Constant.fromValue(left.doubleValue() < right.doubleValue()); - case T_byte: return Constant.fromValue(left.doubleValue() < right.byteValue()); - case T_short: return Constant.fromValue(left.doubleValue() < right.shortValue()); - case T_int: return Constant.fromValue(left.doubleValue() < right.intValue()); - case T_long: return Constant.fromValue(left.doubleValue() < right.longValue()); - } + case T_double: + switch (rightId) { + case T_char: + return Constant.fromValue(left.doubleValue() < right + .charValue()); + case T_float: + return Constant.fromValue(left.doubleValue() < right + .floatValue()); + case T_double: + return Constant.fromValue(left.doubleValue() < right + .doubleValue()); + case T_byte: + return Constant.fromValue(left.doubleValue() < right + .byteValue()); + case T_short: + return Constant.fromValue(left.doubleValue() < right + .shortValue()); + case T_int: + return Constant + .fromValue(left.doubleValue() < right.intValue()); + case T_long: + return Constant.fromValue(left.doubleValue() < right + .longValue()); + } break; - case T_byte : - switch (rightId){ - case T_char : return Constant.fromValue(left.byteValue() < right.charValue()); - case T_float: return Constant.fromValue(left.byteValue() < right.floatValue()); - case T_double: return Constant.fromValue(left.byteValue() < right.doubleValue()); - case T_byte: return Constant.fromValue(left.byteValue() < right.byteValue()); - case T_short: return Constant.fromValue(left.byteValue() < right.shortValue()); - case T_int: return Constant.fromValue(left.byteValue() < right.intValue()); - case T_long: return Constant.fromValue(left.byteValue() < right.longValue()); - } - break; - case T_short : - switch (rightId){ - case T_char : return Constant.fromValue(left.shortValue() < right.charValue()); - case T_float: return Constant.fromValue(left.shortValue() < right.floatValue()); - case T_double: return Constant.fromValue(left.shortValue() < right.doubleValue()); - case T_byte: return Constant.fromValue(left.shortValue() < right.byteValue()); - case T_short: return Constant.fromValue(left.shortValue() < right.shortValue()); - case T_int: return Constant.fromValue(left.shortValue() < right.intValue()); - case T_long: return Constant.fromValue(left.shortValue() < right.longValue()); - } + case T_byte: + switch (rightId) { + case T_char: + return Constant.fromValue(left.byteValue() < right.charValue()); + case T_float: + return Constant + .fromValue(left.byteValue() < right.floatValue()); + case T_double: + return Constant.fromValue(left.byteValue() < right + .doubleValue()); + case T_byte: + return Constant.fromValue(left.byteValue() < right.byteValue()); + case T_short: + return Constant + .fromValue(left.byteValue() < right.shortValue()); + case T_int: + return Constant.fromValue(left.byteValue() < right.intValue()); + case T_long: + return Constant.fromValue(left.byteValue() < right.longValue()); + } break; - case T_int : - switch (rightId){ - case T_char : return Constant.fromValue(left.intValue() < right.charValue()); - case T_float: return Constant.fromValue(left.intValue() < right.floatValue()); - case T_double: return Constant.fromValue(left.intValue() < right.doubleValue()); - case T_byte: return Constant.fromValue(left.intValue() < right.byteValue()); - case T_short: return Constant.fromValue(left.intValue() < right.shortValue()); - case T_int: return Constant.fromValue(left.intValue() < right.intValue()); - case T_long: return Constant.fromValue(left.intValue() < right.longValue()); - } - break; - case T_long : - switch (rightId){ - case T_char : return Constant.fromValue(left.longValue() < right.charValue()); - case T_float: return Constant.fromValue(left.longValue() < right.floatValue()); - case T_double: return Constant.fromValue(left.longValue() < right.doubleValue()); - case T_byte: return Constant.fromValue(left.longValue() < right.byteValue()); - case T_short: return Constant.fromValue(left.longValue() < right.shortValue()); - case T_int: return Constant.fromValue(left.longValue() < right.intValue()); - case T_long: return Constant.fromValue(left.longValue() < right.longValue()); - } - + case T_short: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.shortValue() < right.charValue()); + case T_float: + return Constant.fromValue(left.shortValue() < right + .floatValue()); + case T_double: + return Constant.fromValue(left.shortValue() < right + .doubleValue()); + case T_byte: + return Constant + .fromValue(left.shortValue() < right.byteValue()); + case T_short: + return Constant.fromValue(left.shortValue() < right + .shortValue()); + case T_int: + return Constant.fromValue(left.shortValue() < right.intValue()); + case T_long: + return Constant + .fromValue(left.shortValue() < right.longValue()); + } + break; + case T_int: + switch (rightId) { + case T_char: + return Constant.fromValue(left.intValue() < right.charValue()); + case T_float: + return Constant.fromValue(left.intValue() < right.floatValue()); + case T_double: + return Constant + .fromValue(left.intValue() < right.doubleValue()); + case T_byte: + return Constant.fromValue(left.intValue() < right.byteValue()); + case T_short: + return Constant.fromValue(left.intValue() < right.shortValue()); + case T_int: + return Constant.fromValue(left.intValue() < right.intValue()); + case T_long: + return Constant.fromValue(left.intValue() < right.longValue()); + } + break; + case T_long: + switch (rightId) { + case T_char: + return Constant.fromValue(left.longValue() < right.charValue()); + case T_float: + return Constant + .fromValue(left.longValue() < right.floatValue()); + case T_double: + return Constant.fromValue(left.longValue() < right + .doubleValue()); + case T_byte: + return Constant.fromValue(left.longValue() < right.byteValue()); + case T_short: + return Constant + .fromValue(left.longValue() < right.shortValue()); + case T_int: + return Constant.fromValue(left.longValue() < right.intValue()); + case T_long: + return Constant.fromValue(left.longValue() < right.longValue()); } - + + } + return NotAConstant; } - - public static final Constant computeConstantOperationLESS_EQUAL(Constant left, int leftId, int operator, Constant right, int rightId) { - - switch (leftId){ - case T_char : - switch (rightId){ - case T_char : return Constant.fromValue(left.charValue() <= right.charValue()); - case T_float: return Constant.fromValue(left.charValue() <= right.floatValue()); - case T_double: return Constant.fromValue(left.charValue() <= right.doubleValue()); - case T_byte: return Constant.fromValue(left.charValue() <= right.byteValue()); - case T_short: return Constant.fromValue(left.charValue() <= right.shortValue()); - case T_int: return Constant.fromValue(left.charValue() <= right.intValue()); - case T_long: return Constant.fromValue(left.charValue() <= right.longValue()); - } + + public static final Constant computeConstantOperationLESS_EQUAL( + Constant left, int leftId, int operator, Constant right, int rightId) { + + switch (leftId) { + case T_char: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.charValue() <= right.charValue()); + case T_float: + return Constant.fromValue(left.charValue() <= right + .floatValue()); + case T_double: + return Constant.fromValue(left.charValue() <= right + .doubleValue()); + case T_byte: + return Constant + .fromValue(left.charValue() <= right.byteValue()); + case T_short: + return Constant.fromValue(left.charValue() <= right + .shortValue()); + case T_int: + return Constant.fromValue(left.charValue() <= right.intValue()); + case T_long: + return Constant + .fromValue(left.charValue() <= right.longValue()); + } break; - case T_float : - switch (rightId){ - case T_char : return Constant.fromValue(left.floatValue() <= right.charValue()); - case T_float: return Constant.fromValue(left.floatValue() <= right.floatValue()); - case T_double: return Constant.fromValue(left.floatValue() <= right.doubleValue()); - case T_byte: return Constant.fromValue(left.floatValue() <= right.byteValue()); - case T_short: return Constant.fromValue(left.floatValue() <= right.shortValue()); - case T_int: return Constant.fromValue(left.floatValue() <= right.intValue()); - case T_long: return Constant.fromValue(left.floatValue() <= right.longValue()); - } + case T_float: + switch (rightId) { + case T_char: + return Constant.fromValue(left.floatValue() <= right + .charValue()); + case T_float: + return Constant.fromValue(left.floatValue() <= right + .floatValue()); + case T_double: + return Constant.fromValue(left.floatValue() <= right + .doubleValue()); + case T_byte: + return Constant.fromValue(left.floatValue() <= right + .byteValue()); + case T_short: + return Constant.fromValue(left.floatValue() <= right + .shortValue()); + case T_int: + return Constant + .fromValue(left.floatValue() <= right.intValue()); + case T_long: + return Constant.fromValue(left.floatValue() <= right + .longValue()); + } break; - case T_double : - switch (rightId){ - case T_char : return Constant.fromValue(left.doubleValue() <= right.charValue()); - case T_float: return Constant.fromValue(left.doubleValue() <= right.floatValue()); - case T_double: return Constant.fromValue(left.doubleValue() <= right.doubleValue()); - case T_byte: return Constant.fromValue(left.doubleValue() <= right.byteValue()); - case T_short: return Constant.fromValue(left.doubleValue() <= right.shortValue()); - case T_int: return Constant.fromValue(left.doubleValue() <= right.intValue()); - case T_long: return Constant.fromValue(left.doubleValue() <= right.longValue()); - } + case T_double: + switch (rightId) { + case T_char: + return Constant.fromValue(left.doubleValue() <= right + .charValue()); + case T_float: + return Constant.fromValue(left.doubleValue() <= right + .floatValue()); + case T_double: + return Constant.fromValue(left.doubleValue() <= right + .doubleValue()); + case T_byte: + return Constant.fromValue(left.doubleValue() <= right + .byteValue()); + case T_short: + return Constant.fromValue(left.doubleValue() <= right + .shortValue()); + case T_int: + return Constant.fromValue(left.doubleValue() <= right + .intValue()); + case T_long: + return Constant.fromValue(left.doubleValue() <= right + .longValue()); + } break; - case T_byte : - switch (rightId){ - case T_char : return Constant.fromValue(left.byteValue() <= right.charValue()); - case T_float: return Constant.fromValue(left.byteValue() <= right.floatValue()); - case T_double: return Constant.fromValue(left.byteValue() <= right.doubleValue()); - case T_byte: return Constant.fromValue(left.byteValue() <= right.byteValue()); - case T_short: return Constant.fromValue(left.byteValue() <= right.shortValue()); - case T_int: return Constant.fromValue(left.byteValue() <= right.intValue()); - case T_long: return Constant.fromValue(left.byteValue() <= right.longValue()); - } - break; - case T_short : - switch (rightId){ - case T_char : return Constant.fromValue(left.shortValue() <= right.charValue()); - case T_float: return Constant.fromValue(left.shortValue() <= right.floatValue()); - case T_double: return Constant.fromValue(left.shortValue() <= right.doubleValue()); - case T_byte: return Constant.fromValue(left.shortValue() <= right.byteValue()); - case T_short: return Constant.fromValue(left.shortValue() <= right.shortValue()); - case T_int: return Constant.fromValue(left.shortValue() <= right.intValue()); - case T_long: return Constant.fromValue(left.shortValue() <= right.longValue()); - } + case T_byte: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.byteValue() <= right.charValue()); + case T_float: + return Constant.fromValue(left.byteValue() <= right + .floatValue()); + case T_double: + return Constant.fromValue(left.byteValue() <= right + .doubleValue()); + case T_byte: + return Constant + .fromValue(left.byteValue() <= right.byteValue()); + case T_short: + return Constant.fromValue(left.byteValue() <= right + .shortValue()); + case T_int: + return Constant.fromValue(left.byteValue() <= right.intValue()); + case T_long: + return Constant + .fromValue(left.byteValue() <= right.longValue()); + } break; - case T_int : - switch (rightId){ - case T_char : return Constant.fromValue(left.intValue() <= right.charValue()); - case T_float: return Constant.fromValue(left.intValue() <= right.floatValue()); - case T_double: return Constant.fromValue(left.intValue() <= right.doubleValue()); - case T_byte: return Constant.fromValue(left.intValue() <= right.byteValue()); - case T_short: return Constant.fromValue(left.intValue() <= right.shortValue()); - case T_int: return Constant.fromValue(left.intValue() <= right.intValue()); - case T_long: return Constant.fromValue(left.intValue() <= right.longValue()); - } - break; - case T_long : - switch (rightId){ - case T_char : return Constant.fromValue(left.longValue() <= right.charValue()); - case T_float: return Constant.fromValue(left.longValue() <= right.floatValue()); - case T_double: return Constant.fromValue(left.longValue() <= right.doubleValue()); - case T_byte: return Constant.fromValue(left.longValue() <= right.byteValue()); - case T_short: return Constant.fromValue(left.longValue() <= right.shortValue()); - case T_int: return Constant.fromValue(left.longValue() <= right.intValue()); - case T_long: return Constant.fromValue(left.longValue() <= right.longValue()); - } + case T_short: + switch (rightId) { + case T_char: + return Constant.fromValue(left.shortValue() <= right + .charValue()); + case T_float: + return Constant.fromValue(left.shortValue() <= right + .floatValue()); + case T_double: + return Constant.fromValue(left.shortValue() <= right + .doubleValue()); + case T_byte: + return Constant.fromValue(left.shortValue() <= right + .byteValue()); + case T_short: + return Constant.fromValue(left.shortValue() <= right + .shortValue()); + case T_int: + return Constant + .fromValue(left.shortValue() <= right.intValue()); + case T_long: + return Constant.fromValue(left.shortValue() <= right + .longValue()); + } + break; + case T_int: + switch (rightId) { + case T_char: + return Constant.fromValue(left.intValue() <= right.charValue()); + case T_float: + return Constant + .fromValue(left.intValue() <= right.floatValue()); + case T_double: + return Constant.fromValue(left.intValue() <= right + .doubleValue()); + case T_byte: + return Constant.fromValue(left.intValue() <= right.byteValue()); + case T_short: + return Constant + .fromValue(left.intValue() <= right.shortValue()); + case T_int: + return Constant.fromValue(left.intValue() <= right.intValue()); + case T_long: + return Constant.fromValue(left.intValue() <= right.longValue()); } - + break; + case T_long: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.longValue() <= right.charValue()); + case T_float: + return Constant.fromValue(left.longValue() <= right + .floatValue()); + case T_double: + return Constant.fromValue(left.longValue() <= right + .doubleValue()); + case T_byte: + return Constant + .fromValue(left.longValue() <= right.byteValue()); + case T_short: + return Constant.fromValue(left.longValue() <= right + .shortValue()); + case T_int: + return Constant.fromValue(left.longValue() <= right.intValue()); + case T_long: + return Constant + .fromValue(left.longValue() <= right.longValue()); + } + } + return NotAConstant; - } - - public static final Constant computeConstantOperationMINUS(Constant left, int leftId, int operator, Constant right, int rightId) { - - switch (leftId){ - case T_char : - switch (rightId){ - case T_char : return Constant.fromValue(left.charValue() - right.charValue()); - case T_float: return Constant.fromValue(left.charValue() - right.floatValue()); - case T_double: return Constant.fromValue(left.charValue() - right.doubleValue()); - case T_byte: return Constant.fromValue(left.charValue() - right.byteValue()); - case T_short: return Constant.fromValue(left.charValue() - right.shortValue()); - case T_int: return Constant.fromValue(left.charValue() - right.intValue()); - case T_long: return Constant.fromValue(left.charValue() - right.longValue()); - } + } + + public static final Constant computeConstantOperationMINUS(Constant left, + int leftId, int operator, Constant right, int rightId) { + + switch (leftId) { + case T_char: + switch (rightId) { + case T_char: + return Constant.fromValue(left.charValue() - right.charValue()); + case T_float: + return Constant + .fromValue(left.charValue() - right.floatValue()); + case T_double: + return Constant.fromValue(left.charValue() + - right.doubleValue()); + case T_byte: + return Constant.fromValue(left.charValue() - right.byteValue()); + case T_short: + return Constant + .fromValue(left.charValue() - right.shortValue()); + case T_int: + return Constant.fromValue(left.charValue() - right.intValue()); + case T_long: + return Constant.fromValue(left.charValue() - right.longValue()); + } break; - case T_float : - switch (rightId){ - case T_char : return Constant.fromValue(left.floatValue() - right.charValue()); - case T_float: return Constant.fromValue(left.floatValue() - right.floatValue()); - case T_double: return Constant.fromValue(left.floatValue() - right.doubleValue()); - case T_byte: return Constant.fromValue(left.floatValue() - right.byteValue()); - case T_short: return Constant.fromValue(left.floatValue() - right.shortValue()); - case T_int: return Constant.fromValue(left.floatValue() - right.intValue()); - case T_long: return Constant.fromValue(left.floatValue() - right.longValue()); - } + case T_float: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.floatValue() - right.charValue()); + case T_float: + return Constant.fromValue(left.floatValue() + - right.floatValue()); + case T_double: + return Constant.fromValue(left.floatValue() + - right.doubleValue()); + case T_byte: + return Constant + .fromValue(left.floatValue() - right.byteValue()); + case T_short: + return Constant.fromValue(left.floatValue() + - right.shortValue()); + case T_int: + return Constant.fromValue(left.floatValue() - right.intValue()); + case T_long: + return Constant + .fromValue(left.floatValue() - right.longValue()); + } break; - case T_double : - switch (rightId){ - case T_char : return Constant.fromValue(left.doubleValue() - right.charValue()); - case T_float: return Constant.fromValue(left.doubleValue() - right.floatValue()); - case T_double: return Constant.fromValue(left.doubleValue() - right.doubleValue()); - case T_byte: return Constant.fromValue(left.doubleValue() - right.byteValue()); - case T_short: return Constant.fromValue(left.doubleValue() - right.shortValue()); - case T_int: return Constant.fromValue(left.doubleValue() - right.intValue()); - case T_long: return Constant.fromValue(left.doubleValue() - right.longValue()); - } + case T_double: + switch (rightId) { + case T_char: + return Constant.fromValue(left.doubleValue() + - right.charValue()); + case T_float: + return Constant.fromValue(left.doubleValue() + - right.floatValue()); + case T_double: + return Constant.fromValue(left.doubleValue() + - right.doubleValue()); + case T_byte: + return Constant.fromValue(left.doubleValue() + - right.byteValue()); + case T_short: + return Constant.fromValue(left.doubleValue() + - right.shortValue()); + case T_int: + return Constant + .fromValue(left.doubleValue() - right.intValue()); + case T_long: + return Constant.fromValue(left.doubleValue() + - right.longValue()); + } break; - case T_byte : - switch (rightId){ - case T_char : return Constant.fromValue(left.byteValue() - right.charValue()); - case T_float: return Constant.fromValue(left.byteValue() - right.floatValue()); - case T_double: return Constant.fromValue(left.byteValue() - right.doubleValue()); - case T_byte: return Constant.fromValue(left.byteValue() - right.byteValue()); - case T_short: return Constant.fromValue(left.byteValue() - right.shortValue()); - case T_int: return Constant.fromValue(left.byteValue() - right.intValue()); - case T_long: return Constant.fromValue(left.byteValue() - right.longValue()); - } - break; - case T_short : - switch (rightId){ - case T_char : return Constant.fromValue(left.shortValue() - right.charValue()); - case T_float: return Constant.fromValue(left.shortValue() - right.floatValue()); - case T_double: return Constant.fromValue(left.shortValue() - right.doubleValue()); - case T_byte: return Constant.fromValue(left.shortValue() - right.byteValue()); - case T_short: return Constant.fromValue(left.shortValue() - right.shortValue()); - case T_int: return Constant.fromValue(left.shortValue() - right.intValue()); - case T_long: return Constant.fromValue(left.shortValue() - right.longValue()); - } + case T_byte: + switch (rightId) { + case T_char: + return Constant.fromValue(left.byteValue() - right.charValue()); + case T_float: + return Constant + .fromValue(left.byteValue() - right.floatValue()); + case T_double: + return Constant.fromValue(left.byteValue() + - right.doubleValue()); + case T_byte: + return Constant.fromValue(left.byteValue() - right.byteValue()); + case T_short: + return Constant + .fromValue(left.byteValue() - right.shortValue()); + case T_int: + return Constant.fromValue(left.byteValue() - right.intValue()); + case T_long: + return Constant.fromValue(left.byteValue() - right.longValue()); + } break; - case T_int : - switch (rightId){ - case T_char : return Constant.fromValue(left.intValue() - right.charValue()); - case T_float: return Constant.fromValue(left.intValue() - right.floatValue()); - case T_double: return Constant.fromValue(left.intValue() - right.doubleValue()); - case T_byte: return Constant.fromValue(left.intValue() - right.byteValue()); - case T_short: return Constant.fromValue(left.intValue() - right.shortValue()); - case T_int: return Constant.fromValue(left.intValue() - right.intValue()); - case T_long: return Constant.fromValue(left.intValue() - right.longValue()); - } - break; - case T_long : - switch (rightId){ - case T_char : return Constant.fromValue(left.longValue() - right.charValue()); - case T_float: return Constant.fromValue(left.longValue() - right.floatValue()); - case T_double: return Constant.fromValue(left.longValue() - right.doubleValue()); - case T_byte: return Constant.fromValue(left.longValue() - right.byteValue()); - case T_short: return Constant.fromValue(left.longValue() - right.shortValue()); - case T_int: return Constant.fromValue(left.longValue() - right.intValue()); - case T_long: return Constant.fromValue(left.longValue() - right.longValue()); - } - + case T_short: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.shortValue() - right.charValue()); + case T_float: + return Constant.fromValue(left.shortValue() + - right.floatValue()); + case T_double: + return Constant.fromValue(left.shortValue() + - right.doubleValue()); + case T_byte: + return Constant + .fromValue(left.shortValue() - right.byteValue()); + case T_short: + return Constant.fromValue(left.shortValue() + - right.shortValue()); + case T_int: + return Constant.fromValue(left.shortValue() - right.intValue()); + case T_long: + return Constant + .fromValue(left.shortValue() - right.longValue()); + } + break; + case T_int: + switch (rightId) { + case T_char: + return Constant.fromValue(left.intValue() - right.charValue()); + case T_float: + return Constant.fromValue(left.intValue() - right.floatValue()); + case T_double: + return Constant + .fromValue(left.intValue() - right.doubleValue()); + case T_byte: + return Constant.fromValue(left.intValue() - right.byteValue()); + case T_short: + return Constant.fromValue(left.intValue() - right.shortValue()); + case T_int: + return Constant.fromValue(left.intValue() - right.intValue()); + case T_long: + return Constant.fromValue(left.intValue() - right.longValue()); } - + break; + case T_long: + switch (rightId) { + case T_char: + return Constant.fromValue(left.longValue() - right.charValue()); + case T_float: + return Constant + .fromValue(left.longValue() - right.floatValue()); + case T_double: + return Constant.fromValue(left.longValue() + - right.doubleValue()); + case T_byte: + return Constant.fromValue(left.longValue() - right.byteValue()); + case T_short: + return Constant + .fromValue(left.longValue() - right.shortValue()); + case T_int: + return Constant.fromValue(left.longValue() - right.intValue()); + case T_long: + return Constant.fromValue(left.longValue() - right.longValue()); + } + + } + return NotAConstant; } - - public static final Constant computeConstantOperationMULTIPLY(Constant left, int leftId, int operator, Constant right, int rightId) { - - switch (leftId){ - case T_char : - switch (rightId){ - case T_char : return Constant.fromValue(left.charValue() * right.charValue()); - case T_float: return Constant.fromValue(left.charValue() * right.floatValue()); - case T_double: return Constant.fromValue(left.charValue() * right.doubleValue()); - case T_byte: return Constant.fromValue(left.charValue() * right.byteValue()); - case T_short: return Constant.fromValue(left.charValue() * right.shortValue()); - case T_int: return Constant.fromValue(left.charValue() * right.intValue()); - case T_long: return Constant.fromValue(left.charValue() * right.longValue()); - } + + public static final Constant computeConstantOperationMULTIPLY( + Constant left, int leftId, int operator, Constant right, int rightId) { + + switch (leftId) { + case T_char: + switch (rightId) { + case T_char: + return Constant.fromValue(left.charValue() * right.charValue()); + case T_float: + return Constant + .fromValue(left.charValue() * right.floatValue()); + case T_double: + return Constant.fromValue(left.charValue() + * right.doubleValue()); + case T_byte: + return Constant.fromValue(left.charValue() * right.byteValue()); + case T_short: + return Constant + .fromValue(left.charValue() * right.shortValue()); + case T_int: + return Constant.fromValue(left.charValue() * right.intValue()); + case T_long: + return Constant.fromValue(left.charValue() * right.longValue()); + } break; - case T_float : - switch (rightId){ - case T_char : return Constant.fromValue(left.floatValue() * right.charValue()); - case T_float: return Constant.fromValue(left.floatValue() * right.floatValue()); - case T_double: return Constant.fromValue(left.floatValue() * right.doubleValue()); - case T_byte: return Constant.fromValue(left.floatValue() * right.byteValue()); - case T_short: return Constant.fromValue(left.floatValue() * right.shortValue()); - case T_int: return Constant.fromValue(left.floatValue() * right.intValue()); - case T_long: return Constant.fromValue(left.floatValue() * right.longValue()); - } + case T_float: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.floatValue() * right.charValue()); + case T_float: + return Constant.fromValue(left.floatValue() + * right.floatValue()); + case T_double: + return Constant.fromValue(left.floatValue() + * right.doubleValue()); + case T_byte: + return Constant + .fromValue(left.floatValue() * right.byteValue()); + case T_short: + return Constant.fromValue(left.floatValue() + * right.shortValue()); + case T_int: + return Constant.fromValue(left.floatValue() * right.intValue()); + case T_long: + return Constant + .fromValue(left.floatValue() * right.longValue()); + } break; - case T_double : - switch (rightId){ - case T_char : return Constant.fromValue(left.doubleValue() * right.charValue()); - case T_float: return Constant.fromValue(left.doubleValue() * right.floatValue()); - case T_double: return Constant.fromValue(left.doubleValue() * right.doubleValue()); - case T_byte: return Constant.fromValue(left.doubleValue() * right.byteValue()); - case T_short: return Constant.fromValue(left.doubleValue() * right.shortValue()); - case T_int: return Constant.fromValue(left.doubleValue() * right.intValue()); - case T_long: return Constant.fromValue(left.doubleValue() * right.longValue()); - } + case T_double: + switch (rightId) { + case T_char: + return Constant.fromValue(left.doubleValue() + * right.charValue()); + case T_float: + return Constant.fromValue(left.doubleValue() + * right.floatValue()); + case T_double: + return Constant.fromValue(left.doubleValue() + * right.doubleValue()); + case T_byte: + return Constant.fromValue(left.doubleValue() + * right.byteValue()); + case T_short: + return Constant.fromValue(left.doubleValue() + * right.shortValue()); + case T_int: + return Constant + .fromValue(left.doubleValue() * right.intValue()); + case T_long: + return Constant.fromValue(left.doubleValue() + * right.longValue()); + } break; - case T_byte : - switch (rightId){ - case T_char : return Constant.fromValue(left.byteValue() * right.charValue()); - case T_float: return Constant.fromValue(left.byteValue() * right.floatValue()); - case T_double: return Constant.fromValue(left.byteValue() * right.doubleValue()); - case T_byte: return Constant.fromValue(left.byteValue() * right.byteValue()); - case T_short: return Constant.fromValue(left.byteValue() * right.shortValue()); - case T_int: return Constant.fromValue(left.byteValue() * right.intValue()); - case T_long: return Constant.fromValue(left.byteValue() * right.longValue()); - } + case T_byte: + switch (rightId) { + case T_char: + return Constant.fromValue(left.byteValue() * right.charValue()); + case T_float: + return Constant + .fromValue(left.byteValue() * right.floatValue()); + case T_double: + return Constant.fromValue(left.byteValue() + * right.doubleValue()); + case T_byte: + return Constant.fromValue(left.byteValue() * right.byteValue()); + case T_short: + return Constant + .fromValue(left.byteValue() * right.shortValue()); + case T_int: + return Constant.fromValue(left.byteValue() * right.intValue()); + case T_long: + return Constant.fromValue(left.byteValue() * right.longValue()); + } break; - case T_short : - switch (rightId){ - case T_char : return Constant.fromValue(left.shortValue() * right.charValue()); - case T_float: return Constant.fromValue(left.shortValue() * right.floatValue()); - case T_double: return Constant.fromValue(left.shortValue() * right.doubleValue()); - case T_byte: return Constant.fromValue(left.shortValue() * right.byteValue()); - case T_short: return Constant.fromValue(left.shortValue() * right.shortValue()); - case T_int: return Constant.fromValue(left.shortValue() * right.intValue()); - case T_long: return Constant.fromValue(left.shortValue() * right.longValue()); - } + case T_short: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.shortValue() * right.charValue()); + case T_float: + return Constant.fromValue(left.shortValue() + * right.floatValue()); + case T_double: + return Constant.fromValue(left.shortValue() + * right.doubleValue()); + case T_byte: + return Constant + .fromValue(left.shortValue() * right.byteValue()); + case T_short: + return Constant.fromValue(left.shortValue() + * right.shortValue()); + case T_int: + return Constant.fromValue(left.shortValue() * right.intValue()); + case T_long: + return Constant + .fromValue(left.shortValue() * right.longValue()); + } break; - case T_int : - switch (rightId){ - case T_char : return Constant.fromValue(left.intValue() * right.charValue()); - case T_float: return Constant.fromValue(left.intValue() * right.floatValue()); - case T_double: return Constant.fromValue(left.intValue() * right.doubleValue()); - case T_byte: return Constant.fromValue(left.intValue() * right.byteValue()); - case T_short: return Constant.fromValue(left.intValue() * right.shortValue()); - case T_int: return Constant.fromValue(left.intValue() * right.intValue()); - case T_long: return Constant.fromValue(left.intValue() * right.longValue()); - } + case T_int: + switch (rightId) { + case T_char: + return Constant.fromValue(left.intValue() * right.charValue()); + case T_float: + return Constant.fromValue(left.intValue() * right.floatValue()); + case T_double: + return Constant + .fromValue(left.intValue() * right.doubleValue()); + case T_byte: + return Constant.fromValue(left.intValue() * right.byteValue()); + case T_short: + return Constant.fromValue(left.intValue() * right.shortValue()); + case T_int: + return Constant.fromValue(left.intValue() * right.intValue()); + case T_long: + return Constant.fromValue(left.intValue() * right.longValue()); + } break; - case T_long : - switch (rightId){ - case T_char : return Constant.fromValue(left.longValue() * right.charValue()); - case T_float: return Constant.fromValue(left.longValue() * right.floatValue()); - case T_double: return Constant.fromValue(left.longValue() * right.doubleValue()); - case T_byte: return Constant.fromValue(left.longValue() * right.byteValue()); - case T_short: return Constant.fromValue(left.longValue() * right.shortValue()); - case T_int: return Constant.fromValue(left.longValue() * right.intValue()); - case T_long: return Constant.fromValue(left.longValue() * right.longValue()); - } + case T_long: + switch (rightId) { + case T_char: + return Constant.fromValue(left.longValue() * right.charValue()); + case T_float: + return Constant + .fromValue(left.longValue() * right.floatValue()); + case T_double: + return Constant.fromValue(left.longValue() + * right.doubleValue()); + case T_byte: + return Constant.fromValue(left.longValue() * right.byteValue()); + case T_short: + return Constant + .fromValue(left.longValue() * right.shortValue()); + case T_int: + return Constant.fromValue(left.longValue() * right.intValue()); + case T_long: + return Constant.fromValue(left.longValue() * right.longValue()); } - + } + return NotAConstant; } - - public static final Constant computeConstantOperationOR(Constant left, int leftId, int operator, Constant right, int rightId) { - - switch (leftId){ - case T_boolean : return Constant.fromValue(left.booleanValue() | right.booleanValue()); - case T_char : - switch (rightId){ - case T_char : return Constant.fromValue(left.charValue() | right.charValue()); - case T_byte: return Constant.fromValue(left.charValue() | right.byteValue()); - case T_short: return Constant.fromValue(left.charValue() | right.shortValue()); - case T_int: return Constant.fromValue(left.charValue() | right.intValue()); - case T_long: return Constant.fromValue(left.charValue() | right.longValue()); - } + + public static final Constant computeConstantOperationOR(Constant left, + int leftId, int operator, Constant right, int rightId) { + + switch (leftId) { + case T_boolean: + return Constant.fromValue(left.booleanValue() + | right.booleanValue()); + case T_char: + switch (rightId) { + case T_char: + return Constant.fromValue(left.charValue() | right.charValue()); + case T_byte: + return Constant.fromValue(left.charValue() | right.byteValue()); + case T_short: + return Constant + .fromValue(left.charValue() | right.shortValue()); + case T_int: + return Constant.fromValue(left.charValue() | right.intValue()); + case T_long: + return Constant.fromValue(left.charValue() | right.longValue()); + } break; - case T_byte : - switch (rightId){ - case T_char : return Constant.fromValue(left.byteValue() | right.charValue()); - case T_byte: return Constant.fromValue(left.byteValue() | right.byteValue()); - case T_short: return Constant.fromValue(left.byteValue() | right.shortValue()); - case T_int: return Constant.fromValue(left.byteValue() | right.intValue()); - case T_long: return Constant.fromValue(left.byteValue() | right.longValue()); - } + case T_byte: + switch (rightId) { + case T_char: + return Constant.fromValue(left.byteValue() | right.charValue()); + case T_byte: + return Constant.fromValue(left.byteValue() | right.byteValue()); + case T_short: + return Constant + .fromValue(left.byteValue() | right.shortValue()); + case T_int: + return Constant.fromValue(left.byteValue() | right.intValue()); + case T_long: + return Constant.fromValue(left.byteValue() | right.longValue()); + } break; - case T_short : - switch (rightId){ - case T_char : return Constant.fromValue(left.shortValue() | right.charValue()); - case T_byte: return Constant.fromValue(left.shortValue() | right.byteValue()); - case T_short: return Constant.fromValue(left.shortValue() | right.shortValue()); - case T_int: return Constant.fromValue(left.shortValue() | right.intValue()); - case T_long: return Constant.fromValue(left.shortValue() | right.longValue()); - } + case T_short: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.shortValue() | right.charValue()); + case T_byte: + return Constant + .fromValue(left.shortValue() | right.byteValue()); + case T_short: + return Constant.fromValue(left.shortValue() + | right.shortValue()); + case T_int: + return Constant.fromValue(left.shortValue() | right.intValue()); + case T_long: + return Constant + .fromValue(left.shortValue() | right.longValue()); + } break; - case T_int : - switch (rightId){ - case T_char : return Constant.fromValue(left.intValue() | right.charValue()); - case T_byte: return Constant.fromValue(left.intValue() | right.byteValue()); - case T_short: return Constant.fromValue(left.intValue() | right.shortValue()); - case T_int: return Constant.fromValue(left.intValue() | right.intValue()); - case T_long: return Constant.fromValue(left.intValue() | right.longValue()); - } + case T_int: + switch (rightId) { + case T_char: + return Constant.fromValue(left.intValue() | right.charValue()); + case T_byte: + return Constant.fromValue(left.intValue() | right.byteValue()); + case T_short: + return Constant.fromValue(left.intValue() | right.shortValue()); + case T_int: + return Constant.fromValue(left.intValue() | right.intValue()); + case T_long: + return Constant.fromValue(left.intValue() | right.longValue()); + } break; - case T_long : - switch (rightId){ - case T_char : return Constant.fromValue(left.longValue() | right.charValue()); - case T_byte: return Constant.fromValue(left.longValue() | right.byteValue()); - case T_short: return Constant.fromValue(left.longValue() | right.shortValue()); - case T_int: return Constant.fromValue(left.longValue() | right.intValue()); - case T_long: return Constant.fromValue(left.longValue() | right.longValue()); - } - - } - + case T_long: + switch (rightId) { + case T_char: + return Constant.fromValue(left.longValue() | right.charValue()); + case T_byte: + return Constant.fromValue(left.longValue() | right.byteValue()); + case T_short: + return Constant + .fromValue(left.longValue() | right.shortValue()); + case T_int: + return Constant.fromValue(left.longValue() | right.intValue()); + case T_long: + return Constant.fromValue(left.longValue() | right.longValue()); + } + + } + return NotAConstant; } - - public static final Constant computeConstantOperationOR_OR(Constant left, int leftId, int operator, Constant right, int rightId) { - + + public static final Constant computeConstantOperationOR_OR(Constant left, + int leftId, int operator, Constant right, int rightId) { + return Constant.fromValue(left.booleanValue() || right.booleanValue()); } - - public static final Constant computeConstantOperationPLUS(Constant left, int leftId, int operator, Constant right, int rightId) { - - switch (leftId){ - case T_Object : - if (rightId == T_String) { - return Constant.fromValue(left.stringValue() + right.stringValue()); - } - case T_boolean : - if (rightId == T_String) { - return Constant.fromValue(left.stringValue() + right.stringValue()); - } + + public static final Constant computeConstantOperationPLUS(Constant left, + int leftId, int operator, Constant right, int rightId) { + + switch (leftId) { + case T_Object: + if (rightId == T_String) { + return Constant.fromValue(left.stringValue() + + right.stringValue()); + } + case T_boolean: + if (rightId == T_String) { + return Constant.fromValue(left.stringValue() + + right.stringValue()); + } break; - case T_char : - switch (rightId){ - case T_char : return Constant.fromValue(left.charValue() + right.charValue()); - case T_float: return Constant.fromValue(left.charValue() + right.floatValue()); - case T_double: return Constant.fromValue(left.charValue() + right.doubleValue()); - case T_byte: return Constant.fromValue(left.charValue() + right.byteValue()); - case T_short: return Constant.fromValue(left.charValue() + right.shortValue()); - case T_int: return Constant.fromValue(left.charValue() + right.intValue()); - case T_long: return Constant.fromValue(left.charValue() + right.longValue()); - case T_String: return Constant.fromValue(left.stringValue() + right.stringValue()); - } + case T_char: + switch (rightId) { + case T_char: + return Constant.fromValue(left.charValue() + right.charValue()); + case T_float: + return Constant + .fromValue(left.charValue() + right.floatValue()); + case T_double: + return Constant.fromValue(left.charValue() + + right.doubleValue()); + case T_byte: + return Constant.fromValue(left.charValue() + right.byteValue()); + case T_short: + return Constant + .fromValue(left.charValue() + right.shortValue()); + case T_int: + return Constant.fromValue(left.charValue() + right.intValue()); + case T_long: + return Constant.fromValue(left.charValue() + right.longValue()); + case T_String: + return Constant.fromValue(left.stringValue() + + right.stringValue()); + } break; - case T_float : - switch (rightId){ - case T_char : return Constant.fromValue(left.floatValue() + right.charValue()); - case T_float: return Constant.fromValue(left.floatValue() + right.floatValue()); - case T_double: return Constant.fromValue(left.floatValue() + right.doubleValue()); - case T_byte: return Constant.fromValue(left.floatValue() + right.byteValue()); - case T_short: return Constant.fromValue(left.floatValue() + right.shortValue()); - case T_int: return Constant.fromValue(left.floatValue() + right.intValue()); - case T_long: return Constant.fromValue(left.floatValue() + right.longValue()); - case T_String: return Constant.fromValue(left.stringValue() + right.stringValue()); - } + case T_float: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.floatValue() + right.charValue()); + case T_float: + return Constant.fromValue(left.floatValue() + + right.floatValue()); + case T_double: + return Constant.fromValue(left.floatValue() + + right.doubleValue()); + case T_byte: + return Constant + .fromValue(left.floatValue() + right.byteValue()); + case T_short: + return Constant.fromValue(left.floatValue() + + right.shortValue()); + case T_int: + return Constant.fromValue(left.floatValue() + right.intValue()); + case T_long: + return Constant + .fromValue(left.floatValue() + right.longValue()); + case T_String: + return Constant.fromValue(left.stringValue() + + right.stringValue()); + } break; - case T_double : - switch (rightId){ - case T_char : return Constant.fromValue(left.doubleValue() + right.charValue()); - case T_float: return Constant.fromValue(left.doubleValue() + right.floatValue()); - case T_double: return Constant.fromValue(left.doubleValue() + right.doubleValue()); - case T_byte: return Constant.fromValue(left.doubleValue() + right.byteValue()); - case T_short: return Constant.fromValue(left.doubleValue() + right.shortValue()); - case T_int: return Constant.fromValue(left.doubleValue() + right.intValue()); - case T_long: return Constant.fromValue(left.doubleValue() + right.longValue()); - case T_String: return Constant.fromValue(left.stringValue() + right.stringValue()); - } + case T_double: + switch (rightId) { + case T_char: + return Constant.fromValue(left.doubleValue() + + right.charValue()); + case T_float: + return Constant.fromValue(left.doubleValue() + + right.floatValue()); + case T_double: + return Constant.fromValue(left.doubleValue() + + right.doubleValue()); + case T_byte: + return Constant.fromValue(left.doubleValue() + + right.byteValue()); + case T_short: + return Constant.fromValue(left.doubleValue() + + right.shortValue()); + case T_int: + return Constant + .fromValue(left.doubleValue() + right.intValue()); + case T_long: + return Constant.fromValue(left.doubleValue() + + right.longValue()); + case T_String: + return Constant.fromValue(left.stringValue() + + right.stringValue()); + } break; - case T_byte : - switch (rightId){ - case T_char : return Constant.fromValue(left.byteValue() + right.charValue()); - case T_float: return Constant.fromValue(left.byteValue() + right.floatValue()); - case T_double: return Constant.fromValue(left.byteValue() + right.doubleValue()); - case T_byte: return Constant.fromValue(left.byteValue() + right.byteValue()); - case T_short: return Constant.fromValue(left.byteValue() + right.shortValue()); - case T_int: return Constant.fromValue(left.byteValue() + right.intValue()); - case T_long: return Constant.fromValue(left.byteValue() + right.longValue()); - case T_String: return Constant.fromValue(left.stringValue() + right.stringValue()); - } - - break; - case T_short : - switch (rightId){ - case T_char : return Constant.fromValue(left.shortValue() + right.charValue()); - case T_float: return Constant.fromValue(left.shortValue() + right.floatValue()); - case T_double: return Constant.fromValue(left.shortValue() + right.doubleValue()); - case T_byte: return Constant.fromValue(left.shortValue() + right.byteValue()); - case T_short: return Constant.fromValue(left.shortValue() + right.shortValue()); - case T_int: return Constant.fromValue(left.shortValue() + right.intValue()); - case T_long: return Constant.fromValue(left.shortValue() + right.longValue()); - case T_String: return Constant.fromValue(left.stringValue() + right.stringValue()); - } + case T_byte: + switch (rightId) { + case T_char: + return Constant.fromValue(left.byteValue() + right.charValue()); + case T_float: + return Constant + .fromValue(left.byteValue() + right.floatValue()); + case T_double: + return Constant.fromValue(left.byteValue() + + right.doubleValue()); + case T_byte: + return Constant.fromValue(left.byteValue() + right.byteValue()); + case T_short: + return Constant + .fromValue(left.byteValue() + right.shortValue()); + case T_int: + return Constant.fromValue(left.byteValue() + right.intValue()); + case T_long: + return Constant.fromValue(left.byteValue() + right.longValue()); + case T_String: + return Constant.fromValue(left.stringValue() + + right.stringValue()); + } + break; - case T_int : - switch (rightId){ - case T_char : return Constant.fromValue(left.intValue() + right.charValue()); - case T_float: return Constant.fromValue(left.intValue() + right.floatValue()); - case T_double: return Constant.fromValue(left.intValue() + right.doubleValue()); - case T_byte: return Constant.fromValue(left.intValue() + right.byteValue()); - case T_short: return Constant.fromValue(left.intValue() + right.shortValue()); - case T_int: return Constant.fromValue(left.intValue() + right.intValue()); - case T_long: return Constant.fromValue(left.intValue() + right.longValue()); - case T_String: return Constant.fromValue(left.stringValue() + right.stringValue()); - } - break; - case T_long : - switch (rightId){ - case T_char : return Constant.fromValue(left.longValue() + right.charValue()); - case T_float: return Constant.fromValue(left.longValue() + right.floatValue()); - case T_double: return Constant.fromValue(left.longValue() + right.doubleValue()); - case T_byte: return Constant.fromValue(left.longValue() + right.byteValue()); - case T_short: return Constant.fromValue(left.longValue() + right.shortValue()); - case T_int: return Constant.fromValue(left.longValue() + right.intValue()); - case T_long: return Constant.fromValue(left.longValue() + right.longValue()); - case T_String: return Constant.fromValue(left.stringValue() + right.stringValue()); - } + case T_short: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.shortValue() + right.charValue()); + case T_float: + return Constant.fromValue(left.shortValue() + + right.floatValue()); + case T_double: + return Constant.fromValue(left.shortValue() + + right.doubleValue()); + case T_byte: + return Constant + .fromValue(left.shortValue() + right.byteValue()); + case T_short: + return Constant.fromValue(left.shortValue() + + right.shortValue()); + case T_int: + return Constant.fromValue(left.shortValue() + right.intValue()); + case T_long: + return Constant + .fromValue(left.shortValue() + right.longValue()); + case T_String: + return Constant.fromValue(left.stringValue() + + right.stringValue()); + } break; - case T_String : - switch (rightId){ - case T_char : return Constant.fromValue(left.stringValue() + right.stringValue()); - case T_float: return Constant.fromValue(left.stringValue() + right.stringValue()); - case T_double: return Constant.fromValue(left.stringValue() + right.stringValue()); - case T_byte: return Constant.fromValue(left.stringValue() + right.stringValue()); - case T_short: return Constant.fromValue(left.stringValue() + right.stringValue()); - case T_int: return Constant.fromValue(left.stringValue() + right.stringValue()); - case T_long: return Constant.fromValue(left.stringValue() + right.stringValue()); - case T_String: return Constant.fromValue(left.stringValue() + right.stringValue()); - case T_boolean: return Constant.fromValue(left.stringValue() + right.stringValue()); - } - break; - case T_null : - switch (rightId){ - case T_char : return Constant.fromValue(left.stringValue() + right.stringValue()); - case T_float: return Constant.fromValue(left.stringValue() + right.stringValue()); - case T_double: return Constant.fromValue(left.stringValue() + right.stringValue()); - case T_byte: return Constant.fromValue(left.stringValue() + right.stringValue()); - case T_short: return Constant.fromValue(left.stringValue() + right.stringValue()); - case T_int: return Constant.fromValue(left.stringValue() + right.stringValue()); - case T_long: return Constant.fromValue(left.stringValue() + right.stringValue()); - case T_String: return Constant.fromValue(left.stringValue() + right.stringValue()); - } - + case T_int: + switch (rightId) { + case T_char: + return Constant.fromValue(left.intValue() + right.charValue()); + case T_float: + return Constant.fromValue(left.intValue() + right.floatValue()); + case T_double: + return Constant + .fromValue(left.intValue() + right.doubleValue()); + case T_byte: + return Constant.fromValue(left.intValue() + right.byteValue()); + case T_short: + return Constant.fromValue(left.intValue() + right.shortValue()); + case T_int: + return Constant.fromValue(left.intValue() + right.intValue()); + case T_long: + return Constant.fromValue(left.intValue() + right.longValue()); + case T_String: + return Constant.fromValue(left.stringValue() + + right.stringValue()); + } + break; + case T_long: + switch (rightId) { + case T_char: + return Constant.fromValue(left.longValue() + right.charValue()); + case T_float: + return Constant + .fromValue(left.longValue() + right.floatValue()); + case T_double: + return Constant.fromValue(left.longValue() + + right.doubleValue()); + case T_byte: + return Constant.fromValue(left.longValue() + right.byteValue()); + case T_short: + return Constant + .fromValue(left.longValue() + right.shortValue()); + case T_int: + return Constant.fromValue(left.longValue() + right.intValue()); + case T_long: + return Constant.fromValue(left.longValue() + right.longValue()); + case T_String: + return Constant.fromValue(left.stringValue() + + right.stringValue()); } - + break; + case T_String: + switch (rightId) { + case T_char: + return Constant.fromValue(left.stringValue() + + right.stringValue()); + case T_float: + return Constant.fromValue(left.stringValue() + + right.stringValue()); + case T_double: + return Constant.fromValue(left.stringValue() + + right.stringValue()); + case T_byte: + return Constant.fromValue(left.stringValue() + + right.stringValue()); + case T_short: + return Constant.fromValue(left.stringValue() + + right.stringValue()); + case T_int: + return Constant.fromValue(left.stringValue() + + right.stringValue()); + case T_long: + return Constant.fromValue(left.stringValue() + + right.stringValue()); + case T_String: + return Constant.fromValue(left.stringValue() + + right.stringValue()); + case T_boolean: + return Constant.fromValue(left.stringValue() + + right.stringValue()); + } + break; + case T_null: + switch (rightId) { + case T_char: + return Constant.fromValue(left.stringValue() + + right.stringValue()); + case T_float: + return Constant.fromValue(left.stringValue() + + right.stringValue()); + case T_double: + return Constant.fromValue(left.stringValue() + + right.stringValue()); + case T_byte: + return Constant.fromValue(left.stringValue() + + right.stringValue()); + case T_short: + return Constant.fromValue(left.stringValue() + + right.stringValue()); + case T_int: + return Constant.fromValue(left.stringValue() + + right.stringValue()); + case T_long: + return Constant.fromValue(left.stringValue() + + right.stringValue()); + case T_String: + return Constant.fromValue(left.stringValue() + + right.stringValue()); + } + + } + return NotAConstant; } - - public static final Constant computeConstantOperationREMAINDER(Constant left, int leftId, int operator, Constant right, int rightId) { - - switch (leftId){ - case T_char : - switch (rightId){ - case T_char : return Constant.fromValue(left.charValue() % right.charValue()); - case T_float: return Constant.fromValue(left.charValue() % right.floatValue()); - case T_double: return Constant.fromValue(left.charValue() % right.doubleValue()); - case T_byte: return Constant.fromValue(left.charValue() % right.byteValue()); - case T_short: return Constant.fromValue(left.charValue() % right.shortValue()); - case T_int: return Constant.fromValue(left.charValue() % right.intValue()); - case T_long: return Constant.fromValue(left.charValue() % right.longValue()); - } + + public static final Constant computeConstantOperationREMAINDER( + Constant left, int leftId, int operator, Constant right, int rightId) { + + switch (leftId) { + case T_char: + switch (rightId) { + case T_char: + return Constant.fromValue(left.charValue() % right.charValue()); + case T_float: + return Constant + .fromValue(left.charValue() % right.floatValue()); + case T_double: + return Constant.fromValue(left.charValue() + % right.doubleValue()); + case T_byte: + return Constant.fromValue(left.charValue() % right.byteValue()); + case T_short: + return Constant + .fromValue(left.charValue() % right.shortValue()); + case T_int: + return Constant.fromValue(left.charValue() % right.intValue()); + case T_long: + return Constant.fromValue(left.charValue() % right.longValue()); + } break; - case T_float : - switch (rightId){ - case T_char : return Constant.fromValue(left.floatValue() % right.charValue()); - case T_float: return Constant.fromValue(left.floatValue() % right.floatValue()); - case T_double: return Constant.fromValue(left.floatValue() % right.doubleValue()); - case T_byte: return Constant.fromValue(left.floatValue() % right.byteValue()); - case T_short: return Constant.fromValue(left.floatValue() % right.shortValue()); - case T_int: return Constant.fromValue(left.floatValue() % right.intValue()); - case T_long: return Constant.fromValue(left.floatValue() % right.longValue()); - } + case T_float: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.floatValue() % right.charValue()); + case T_float: + return Constant.fromValue(left.floatValue() + % right.floatValue()); + case T_double: + return Constant.fromValue(left.floatValue() + % right.doubleValue()); + case T_byte: + return Constant + .fromValue(left.floatValue() % right.byteValue()); + case T_short: + return Constant.fromValue(left.floatValue() + % right.shortValue()); + case T_int: + return Constant.fromValue(left.floatValue() % right.intValue()); + case T_long: + return Constant + .fromValue(left.floatValue() % right.longValue()); + } break; - case T_double : - switch (rightId){ - case T_char : return Constant.fromValue(left.doubleValue() % right.charValue()); - case T_float: return Constant.fromValue(left.doubleValue() % right.floatValue()); - case T_double: return Constant.fromValue(left.doubleValue() % right.doubleValue()); - case T_byte: return Constant.fromValue(left.doubleValue() % right.byteValue()); - case T_short: return Constant.fromValue(left.doubleValue() % right.shortValue()); - case T_int: return Constant.fromValue(left.doubleValue() % right.intValue()); - case T_long: return Constant.fromValue(left.doubleValue() % right.longValue()); - } + case T_double: + switch (rightId) { + case T_char: + return Constant.fromValue(left.doubleValue() + % right.charValue()); + case T_float: + return Constant.fromValue(left.doubleValue() + % right.floatValue()); + case T_double: + return Constant.fromValue(left.doubleValue() + % right.doubleValue()); + case T_byte: + return Constant.fromValue(left.doubleValue() + % right.byteValue()); + case T_short: + return Constant.fromValue(left.doubleValue() + % right.shortValue()); + case T_int: + return Constant + .fromValue(left.doubleValue() % right.intValue()); + case T_long: + return Constant.fromValue(left.doubleValue() + % right.longValue()); + } break; - case T_byte : - switch (rightId){ - case T_char : return Constant.fromValue(left.byteValue() % right.charValue()); - case T_float: return Constant.fromValue(left.byteValue() % right.floatValue()); - case T_double: return Constant.fromValue(left.byteValue() % right.doubleValue()); - case T_byte: return Constant.fromValue(left.byteValue() % right.byteValue()); - case T_short: return Constant.fromValue(left.byteValue() % right.shortValue()); - case T_int: return Constant.fromValue(left.byteValue() % right.intValue()); - case T_long: return Constant.fromValue(left.byteValue() % right.longValue()); - } - break; - case T_short : - switch (rightId){ - case T_char : return Constant.fromValue(left.shortValue() % right.charValue()); - case T_float: return Constant.fromValue(left.shortValue() % right.floatValue()); - case T_double: return Constant.fromValue(left.shortValue() % right.doubleValue()); - case T_byte: return Constant.fromValue(left.shortValue() % right.byteValue()); - case T_short: return Constant.fromValue(left.shortValue() % right.shortValue()); - case T_int: return Constant.fromValue(left.shortValue() % right.intValue()); - case T_long: return Constant.fromValue(left.shortValue() % right.longValue()); - } + case T_byte: + switch (rightId) { + case T_char: + return Constant.fromValue(left.byteValue() % right.charValue()); + case T_float: + return Constant + .fromValue(left.byteValue() % right.floatValue()); + case T_double: + return Constant.fromValue(left.byteValue() + % right.doubleValue()); + case T_byte: + return Constant.fromValue(left.byteValue() % right.byteValue()); + case T_short: + return Constant + .fromValue(left.byteValue() % right.shortValue()); + case T_int: + return Constant.fromValue(left.byteValue() % right.intValue()); + case T_long: + return Constant.fromValue(left.byteValue() % right.longValue()); + } break; - case T_int : - switch (rightId){ - case T_char : return Constant.fromValue(left.intValue() % right.charValue()); - case T_float: return Constant.fromValue(left.intValue() % right.floatValue()); - case T_double: return Constant.fromValue(left.intValue() % right.doubleValue()); - case T_byte: return Constant.fromValue(left.intValue() % right.byteValue()); - case T_short: return Constant.fromValue(left.intValue() % right.shortValue()); - case T_int: return Constant.fromValue(left.intValue() % right.intValue()); - case T_long: return Constant.fromValue(left.intValue() % right.longValue()); - } - break; - case T_long : - switch (rightId){ - case T_char : return Constant.fromValue(left.longValue() % right.charValue()); - case T_float: return Constant.fromValue(left.longValue() % right.floatValue()); - case T_double: return Constant.fromValue(left.longValue() % right.doubleValue()); - case T_byte: return Constant.fromValue(left.longValue() % right.byteValue()); - case T_short: return Constant.fromValue(left.longValue() % right.shortValue()); - case T_int: return Constant.fromValue(left.longValue() % right.intValue()); - case T_long: return Constant.fromValue(left.longValue() % right.longValue()); - } - + case T_short: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.shortValue() % right.charValue()); + case T_float: + return Constant.fromValue(left.shortValue() + % right.floatValue()); + case T_double: + return Constant.fromValue(left.shortValue() + % right.doubleValue()); + case T_byte: + return Constant + .fromValue(left.shortValue() % right.byteValue()); + case T_short: + return Constant.fromValue(left.shortValue() + % right.shortValue()); + case T_int: + return Constant.fromValue(left.shortValue() % right.intValue()); + case T_long: + return Constant + .fromValue(left.shortValue() % right.longValue()); } - + break; + case T_int: + switch (rightId) { + case T_char: + return Constant.fromValue(left.intValue() % right.charValue()); + case T_float: + return Constant.fromValue(left.intValue() % right.floatValue()); + case T_double: + return Constant + .fromValue(left.intValue() % right.doubleValue()); + case T_byte: + return Constant.fromValue(left.intValue() % right.byteValue()); + case T_short: + return Constant.fromValue(left.intValue() % right.shortValue()); + case T_int: + return Constant.fromValue(left.intValue() % right.intValue()); + case T_long: + return Constant.fromValue(left.intValue() % right.longValue()); + } + break; + case T_long: + switch (rightId) { + case T_char: + return Constant.fromValue(left.longValue() % right.charValue()); + case T_float: + return Constant + .fromValue(left.longValue() % right.floatValue()); + case T_double: + return Constant.fromValue(left.longValue() + % right.doubleValue()); + case T_byte: + return Constant.fromValue(left.longValue() % right.byteValue()); + case T_short: + return Constant + .fromValue(left.longValue() % right.shortValue()); + case T_int: + return Constant.fromValue(left.longValue() % right.intValue()); + case T_long: + return Constant.fromValue(left.longValue() % right.longValue()); + } + + } + return NotAConstant; - } - - public static final Constant computeConstantOperationRIGHT_SHIFT(Constant left, int leftId, int operator, Constant right, int rightId) { - - switch (leftId){ - case T_char : - switch (rightId){ - case T_char : return Constant.fromValue(left.charValue() >> right.charValue()); - case T_byte: return Constant.fromValue(left.charValue() >> right.byteValue()); - case T_short: return Constant.fromValue(left.charValue() >> right.shortValue()); - case T_int: return Constant.fromValue(left.charValue() >> right.intValue()); - case T_long: return Constant.fromValue(left.charValue() >> right.longValue()); - } + } + + public static final Constant computeConstantOperationRIGHT_SHIFT( + Constant left, int leftId, int operator, Constant right, int rightId) { + + switch (leftId) { + case T_char: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.charValue() >> right.charValue()); + case T_byte: + return Constant + .fromValue(left.charValue() >> right.byteValue()); + case T_short: + return Constant.fromValue(left.charValue() >> right + .shortValue()); + case T_int: + return Constant.fromValue(left.charValue() >> right.intValue()); + case T_long: + return Constant + .fromValue(left.charValue() >> right.longValue()); + } break; - case T_byte : - switch (rightId){ - case T_char : return Constant.fromValue(left.byteValue() >> right.charValue()); - case T_byte: return Constant.fromValue(left.byteValue() >> right.byteValue()); - case T_short: return Constant.fromValue(left.byteValue() >> right.shortValue()); - case T_int: return Constant.fromValue(left.byteValue() >> right.intValue()); - case T_long: return Constant.fromValue(left.byteValue() >> right.longValue()); - } + case T_byte: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.byteValue() >> right.charValue()); + case T_byte: + return Constant + .fromValue(left.byteValue() >> right.byteValue()); + case T_short: + return Constant.fromValue(left.byteValue() >> right + .shortValue()); + case T_int: + return Constant.fromValue(left.byteValue() >> right.intValue()); + case T_long: + return Constant + .fromValue(left.byteValue() >> right.longValue()); + } break; - case T_short : - switch (rightId){ - case T_char : return Constant.fromValue(left.shortValue() >> right.charValue()); - case T_byte: return Constant.fromValue(left.shortValue() >> right.byteValue()); - case T_short: return Constant.fromValue(left.shortValue() >> right.shortValue()); - case T_int: return Constant.fromValue(left.shortValue() >> right.intValue()); - case T_long: return Constant.fromValue(left.shortValue() >> right.longValue()); - } + case T_short: + switch (rightId) { + case T_char: + return Constant.fromValue(left.shortValue() >> right + .charValue()); + case T_byte: + return Constant.fromValue(left.shortValue() >> right + .byteValue()); + case T_short: + return Constant.fromValue(left.shortValue() >> right + .shortValue()); + case T_int: + return Constant + .fromValue(left.shortValue() >> right.intValue()); + case T_long: + return Constant.fromValue(left.shortValue() >> right + .longValue()); + } break; - case T_int : - switch (rightId){ - case T_char : return Constant.fromValue(left.intValue() >> right.charValue()); - case T_byte: return Constant.fromValue(left.intValue() >> right.byteValue()); - case T_short: return Constant.fromValue(left.intValue() >> right.shortValue()); - case T_int: return Constant.fromValue(left.intValue() >> right.intValue()); - case T_long: return Constant.fromValue(left.intValue() >> right.longValue()); - } + case T_int: + switch (rightId) { + case T_char: + return Constant.fromValue(left.intValue() >> right.charValue()); + case T_byte: + return Constant.fromValue(left.intValue() >> right.byteValue()); + case T_short: + return Constant + .fromValue(left.intValue() >> right.shortValue()); + case T_int: + return Constant.fromValue(left.intValue() >> right.intValue()); + case T_long: + return Constant.fromValue(left.intValue() >> right.longValue()); + } break; - case T_long : - switch (rightId){ - case T_char : return Constant.fromValue(left.longValue() >> right.charValue()); - case T_byte: return Constant.fromValue(left.longValue() >> right.byteValue()); - case T_short: return Constant.fromValue(left.longValue() >> right.shortValue()); - case T_int: return Constant.fromValue(left.longValue() >> right.intValue()); - case T_long: return Constant.fromValue(left.longValue() >> right.longValue()); - } - + case T_long: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.longValue() >> right.charValue()); + case T_byte: + return Constant + .fromValue(left.longValue() >> right.byteValue()); + case T_short: + return Constant.fromValue(left.longValue() >> right + .shortValue()); + case T_int: + return Constant.fromValue(left.longValue() >> right.intValue()); + case T_long: + return Constant + .fromValue(left.longValue() >> right.longValue()); } - + + } + return NotAConstant; } - public static final Constant computeConstantOperationUNSIGNED_RIGHT_SHIFT(Constant left, int leftId, int operator, Constant right, int rightId) { - - switch (leftId){ - case T_char : - switch (rightId){ - case T_char : return Constant.fromValue(left.charValue() >>> right.charValue()); - case T_byte: return Constant.fromValue(left.charValue() >>> right.byteValue()); - case T_short: return Constant.fromValue(left.charValue() >>> right.shortValue()); - case T_int: return Constant.fromValue(left.charValue() >>> right.intValue()); - case T_long: return Constant.fromValue(left.charValue() >>> right.longValue()); - } + public static final Constant computeConstantOperationUNSIGNED_RIGHT_SHIFT( + Constant left, int leftId, int operator, Constant right, int rightId) { + + switch (leftId) { + case T_char: + switch (rightId) { + case T_char: + return Constant.fromValue(left.charValue() >>> right + .charValue()); + case T_byte: + return Constant.fromValue(left.charValue() >>> right + .byteValue()); + case T_short: + return Constant.fromValue(left.charValue() >>> right + .shortValue()); + case T_int: + return Constant + .fromValue(left.charValue() >>> right.intValue()); + case T_long: + return Constant.fromValue(left.charValue() >>> right + .longValue()); + } break; - case T_byte : - switch (rightId){ - case T_char : return Constant.fromValue(left.byteValue() >>> right.charValue()); - case T_byte: return Constant.fromValue(left.byteValue() >>> right.byteValue()); - case T_short: return Constant.fromValue(left.byteValue() >>> right.shortValue()); - case T_int: return Constant.fromValue(left.byteValue() >>> right.intValue()); - case T_long: return Constant.fromValue(left.byteValue() >>> right.longValue()); - } + case T_byte: + switch (rightId) { + case T_char: + return Constant.fromValue(left.byteValue() >>> right + .charValue()); + case T_byte: + return Constant.fromValue(left.byteValue() >>> right + .byteValue()); + case T_short: + return Constant.fromValue(left.byteValue() >>> right + .shortValue()); + case T_int: + return Constant + .fromValue(left.byteValue() >>> right.intValue()); + case T_long: + return Constant.fromValue(left.byteValue() >>> right + .longValue()); + } break; - case T_short : - switch (rightId){ - case T_char : return Constant.fromValue(left.shortValue() >>> right.charValue()); - case T_byte: return Constant.fromValue(left.shortValue() >>> right.byteValue()); - case T_short: return Constant.fromValue(left.shortValue() >>> right.shortValue()); - case T_int: return Constant.fromValue(left.shortValue() >>> right.intValue()); - case T_long: return Constant.fromValue(left.shortValue() >>> right.longValue()); - } + case T_short: + switch (rightId) { + case T_char: + return Constant.fromValue(left.shortValue() >>> right + .charValue()); + case T_byte: + return Constant.fromValue(left.shortValue() >>> right + .byteValue()); + case T_short: + return Constant.fromValue(left.shortValue() >>> right + .shortValue()); + case T_int: + return Constant.fromValue(left.shortValue() >>> right + .intValue()); + case T_long: + return Constant.fromValue(left.shortValue() >>> right + .longValue()); + } break; - case T_int : - switch (rightId){ - case T_char : return Constant.fromValue(left.intValue() >>> right.charValue()); - case T_byte: return Constant.fromValue(left.intValue() >>> right.byteValue()); - case T_short: return Constant.fromValue(left.intValue() >>> right.shortValue()); - case T_int: return Constant.fromValue(left.intValue() >>> right.intValue()); - case T_long: return Constant.fromValue(left.intValue() >>> right.longValue()); - } + case T_int: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.intValue() >>> right.charValue()); + case T_byte: + return Constant + .fromValue(left.intValue() >>> right.byteValue()); + case T_short: + return Constant.fromValue(left.intValue() >>> right + .shortValue()); + case T_int: + return Constant.fromValue(left.intValue() >>> right.intValue()); + case T_long: + return Constant + .fromValue(left.intValue() >>> right.longValue()); + } break; - case T_long : - switch (rightId){ - case T_char : return Constant.fromValue(left.longValue() >>> right.charValue()); - case T_byte: return Constant.fromValue(left.longValue() >>> right.byteValue()); - case T_short: return Constant.fromValue(left.longValue() >>> right.shortValue()); - case T_int: return Constant.fromValue(left.longValue() >>> right.intValue()); - case T_long: return Constant.fromValue(left.longValue() >>> right.longValue()); - } - + case T_long: + switch (rightId) { + case T_char: + return Constant.fromValue(left.longValue() >>> right + .charValue()); + case T_byte: + return Constant.fromValue(left.longValue() >>> right + .byteValue()); + case T_short: + return Constant.fromValue(left.longValue() >>> right + .shortValue()); + case T_int: + return Constant + .fromValue(left.longValue() >>> right.intValue()); + case T_long: + return Constant.fromValue(left.longValue() >>> right + .longValue()); } - + + } + return NotAConstant; } - - public static final Constant computeConstantOperationXOR(Constant left, int leftId, int operator, Constant right, int rightId) { - - switch (leftId){ - case T_boolean : return Constant.fromValue(left.booleanValue() ^ right.booleanValue()); - case T_char : - switch (rightId){ - case T_char : return Constant.fromValue(left.charValue() ^ right.charValue()); - case T_byte: return Constant.fromValue(left.charValue() ^ right.byteValue()); - case T_short: return Constant.fromValue(left.charValue() ^ right.shortValue()); - case T_int: return Constant.fromValue(left.charValue() ^ right.intValue()); - case T_long: return Constant.fromValue(left.charValue() ^ right.longValue()); - } + + public static final Constant computeConstantOperationXOR(Constant left, + int leftId, int operator, Constant right, int rightId) { + + switch (leftId) { + case T_boolean: + return Constant.fromValue(left.booleanValue() + ^ right.booleanValue()); + case T_char: + switch (rightId) { + case T_char: + return Constant.fromValue(left.charValue() ^ right.charValue()); + case T_byte: + return Constant.fromValue(left.charValue() ^ right.byteValue()); + case T_short: + return Constant + .fromValue(left.charValue() ^ right.shortValue()); + case T_int: + return Constant.fromValue(left.charValue() ^ right.intValue()); + case T_long: + return Constant.fromValue(left.charValue() ^ right.longValue()); + } break; - case T_byte : - switch (rightId){ - case T_char : return Constant.fromValue(left.byteValue() ^ right.charValue()); - case T_byte: return Constant.fromValue(left.byteValue() ^ right.byteValue()); - case T_short: return Constant.fromValue(left.byteValue() ^ right.shortValue()); - case T_int: return Constant.fromValue(left.byteValue() ^ right.intValue()); - case T_long: return Constant.fromValue(left.byteValue() ^ right.longValue()); - } + case T_byte: + switch (rightId) { + case T_char: + return Constant.fromValue(left.byteValue() ^ right.charValue()); + case T_byte: + return Constant.fromValue(left.byteValue() ^ right.byteValue()); + case T_short: + return Constant + .fromValue(left.byteValue() ^ right.shortValue()); + case T_int: + return Constant.fromValue(left.byteValue() ^ right.intValue()); + case T_long: + return Constant.fromValue(left.byteValue() ^ right.longValue()); + } break; - case T_short : - switch (rightId){ - case T_char : return Constant.fromValue(left.shortValue() ^ right.charValue()); - case T_byte: return Constant.fromValue(left.shortValue() ^ right.byteValue()); - case T_short: return Constant.fromValue(left.shortValue() ^ right.shortValue()); - case T_int: return Constant.fromValue(left.shortValue() ^ right.intValue()); - case T_long: return Constant.fromValue(left.shortValue() ^ right.longValue()); - } + case T_short: + switch (rightId) { + case T_char: + return Constant + .fromValue(left.shortValue() ^ right.charValue()); + case T_byte: + return Constant + .fromValue(left.shortValue() ^ right.byteValue()); + case T_short: + return Constant.fromValue(left.shortValue() + ^ right.shortValue()); + case T_int: + return Constant.fromValue(left.shortValue() ^ right.intValue()); + case T_long: + return Constant + .fromValue(left.shortValue() ^ right.longValue()); + } break; - case T_int : - switch (rightId){ - case T_char : return Constant.fromValue(left.intValue() ^ right.charValue()); - case T_byte: return Constant.fromValue(left.intValue() ^ right.byteValue()); - case T_short: return Constant.fromValue(left.intValue() ^ right.shortValue()); - case T_int: return Constant.fromValue(left.intValue() ^ right.intValue()); - case T_long: return Constant.fromValue(left.intValue() ^ right.longValue()); - } + case T_int: + switch (rightId) { + case T_char: + return Constant.fromValue(left.intValue() ^ right.charValue()); + case T_byte: + return Constant.fromValue(left.intValue() ^ right.byteValue()); + case T_short: + return Constant.fromValue(left.intValue() ^ right.shortValue()); + case T_int: + return Constant.fromValue(left.intValue() ^ right.intValue()); + case T_long: + return Constant.fromValue(left.intValue() ^ right.longValue()); + } break; - case T_long : - switch (rightId){ - case T_char : return Constant.fromValue(left.longValue() ^ right.charValue()); - case T_byte: return Constant.fromValue(left.longValue() ^ right.byteValue()); - case T_short: return Constant.fromValue(left.longValue() ^ right.shortValue()); - case T_int: return Constant.fromValue(left.longValue() ^ right.intValue()); - case T_long: return Constant.fromValue(left.longValue() ^ right.longValue()); - } + case T_long: + switch (rightId) { + case T_char: + return Constant.fromValue(left.longValue() ^ right.charValue()); + case T_byte: + return Constant.fromValue(left.longValue() ^ right.byteValue()); + case T_short: + return Constant + .fromValue(left.longValue() ^ right.shortValue()); + case T_int: + return Constant.fromValue(left.longValue() ^ right.intValue()); + case T_long: + return Constant.fromValue(left.longValue() ^ right.longValue()); } - + } + return NotAConstant; } public double doubleValue() { - throw new ShouldNotImplement(Util.bind("constant.cannotCastedInto",typeName(),"double")); //$NON-NLS-2$ //$NON-NLS-1$ + throw new ShouldNotImplement(Util.bind( + "constant.cannotCastedInto", typeName(), "double")); //$NON-NLS-2$ //$NON-NLS-1$ } public float floatValue() { - throw new ShouldNotImplement(Util.bind("constant.cannotCastedInto",typeName(),"float")); //$NON-NLS-2$ //$NON-NLS-1$ + throw new ShouldNotImplement(Util.bind( + "constant.cannotCastedInto", typeName(), "float")); //$NON-NLS-2$ //$NON-NLS-1$ } -// public static Constant fromValue(byte value) { -// -// return new ByteConstant(value); -// } + // public static Constant fromValue(byte value) { + // + // return new ByteConstant(value); + // } -// public static Constant fromValue(char value) { -// -// return new CharConstant(value); -// } + // public static Constant fromValue(char value) { + // + // return new CharConstant(value); + // } public static Constant fromValue(double value) { return new DoubleConstant(value); } -// public static Constant fromValue(float value) { -// -// return new FloatConstant(value); -// } + // public static Constant fromValue(float value) { + // + // return new FloatConstant(value); + // } public static Constant fromValue(int value) { return new IntConstant(value); } -// public static Constant fromValue(long value) { -// -// return new LongConstant(value); -// } + // public static Constant fromValue(long value) { + // + // return new LongConstant(value); + // } public static Constant fromValue(String value) { - + return new StringConstant(value); } -// public static Constant fromValue(short value) { -// -// return new ShortConstant(value); -// } + // public static Constant fromValue(short value) { + // + // return new ShortConstant(value); + // } public static Constant fromValue(boolean value) { @@ -1568,44 +2807,61 @@ public abstract class Constant implements TypeIds, OperatorIds { public int intValue() { - throw new ShouldNotImplement(Util.bind("constant.cannotCastedInto",typeName(),"int")); //$NON-NLS-2$ //$NON-NLS-1$ + throw new ShouldNotImplement(Util.bind( + "constant.cannotCastedInto", typeName(), "int")); //$NON-NLS-2$ //$NON-NLS-1$ } public long longValue() { - throw new ShouldNotImplement(Util.bind("constant.cannotCastedInto",typeName(),"long")); //$NON-NLS-2$ //$NON-NLS-1$ + throw new ShouldNotImplement(Util.bind( + "constant.cannotCastedInto", typeName(), "long")); //$NON-NLS-2$ //$NON-NLS-1$ } public short shortValue() { - throw new ShouldNotImplement(Util.bind("constant.cannotConvertedTo",typeName(),"short")); //$NON-NLS-2$ //$NON-NLS-1$ + throw new ShouldNotImplement(Util.bind( + "constant.cannotConvertedTo", typeName(), "short")); //$NON-NLS-2$ //$NON-NLS-1$ } public String stringValue() { - throw new ShouldNotImplement(Util.bind("constant.cannotConvertedTo",typeName(),"String")); //$NON-NLS-1$ //$NON-NLS-2$ + throw new ShouldNotImplement(Util.bind( + "constant.cannotConvertedTo", typeName(), "String")); //$NON-NLS-1$ //$NON-NLS-2$ } - public String toString(){ - - if (this == NotAConstant) return "(Constant) NotAConstant"; //$NON-NLS-1$ - return super.toString(); } + public String toString() { + + if (this == NotAConstant) + return "(Constant) NotAConstant"; //$NON-NLS-1$ + return super.toString(); + } public abstract int typeID(); public String typeName() { switch (typeID()) { - case T_int : return "int"; //$NON-NLS-1$ - case T_byte : return "byte"; //$NON-NLS-1$ - case T_short : return "short"; //$NON-NLS-1$ - case T_char : return "char"; //$NON-NLS-1$ - case T_float : return "float"; //$NON-NLS-1$ - case T_double : return "double"; //$NON-NLS-1$ - case T_boolean : return "boolean"; //$NON-NLS-1$ - case T_long : return "long";//$NON-NLS-1$ - case T_String : return "java.lang.String"; //$NON-NLS-1$ - case T_null : return "null"; //$NON-NLS-1$ - default: return "unknown"; //$NON-NLS-1$ + case T_int: + return "int"; //$NON-NLS-1$ + case T_byte: + return "byte"; //$NON-NLS-1$ + case T_short: + return "short"; //$NON-NLS-1$ + case T_char: + return "char"; //$NON-NLS-1$ + case T_float: + return "float"; //$NON-NLS-1$ + case T_double: + return "double"; //$NON-NLS-1$ + case T_boolean: + return "boolean"; //$NON-NLS-1$ + case T_long: + return "long";//$NON-NLS-1$ + case T_String: + return "java.lang.String"; //$NON-NLS-1$ + case T_null: + return "null"; //$NON-NLS-1$ + default: + return "unknown"; //$NON-NLS-1$ } } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/DoubleConstant.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/DoubleConstant.java index 4b23f59..3ddb5d8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/DoubleConstant.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/DoubleConstant.java @@ -11,41 +11,41 @@ package net.sourceforge.phpdt.internal.compiler.impl; public class DoubleConstant extends Constant { - + double value; - + public DoubleConstant(double value) { this.value = value; } - + public byte byteValue() { return (byte) value; } - + public char charValue() { return (char) value; } - + public double doubleValue() { return (double) value; } - + public float floatValue() { return (float) value; } - + public int intValue() { return (int) value; } - + public long longValue() { return (long) value; } - + public short shortValue() { return (short) value; } - + public String stringValue() { String s = Double.toString(value); if (s == null) @@ -53,11 +53,11 @@ public class DoubleConstant extends Constant { else return s; } - + public String toString() { if (this == NotAConstant) return "(Constant) NotAConstant"; //$NON-NLS-1$ - return "(double)" + value; //$NON-NLS-1$ + return "(double)" + value; //$NON-NLS-1$ } public int typeID() { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/ITypeRequestor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/ITypeRequestor.java index 31d0840..b11ab72 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/ITypeRequestor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/ITypeRequestor.java @@ -16,7 +16,7 @@ import net.sourceforge.phpdt.internal.compiler.env.ISourceType; import net.sourceforge.phpdt.internal.compiler.lookup.PackageBinding; public interface ITypeRequestor { - + /** * Accept the resolved binary form for the requested type. */ @@ -28,10 +28,10 @@ public interface ITypeRequestor { void accept(ICompilationUnit unit); /** - * Accept the unresolved source forms for the requested type. - * Note that the multiple source forms can be answered, in case the target compilation unit - * contains multiple types. The first one is then guaranteed to be the one corresponding to the - * requested type. + * Accept the unresolved source forms for the requested type. Note that the + * multiple source forms can be answered, in case the target compilation + * unit contains multiple types. The first one is then guaranteed to be the + * one corresponding to the requested type. */ void accept(ISourceType[] sourceType, PackageBinding packageBinding); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/IntConstant.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/IntConstant.java index 87e2e3e..c9c1837 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/IntConstant.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/IntConstant.java @@ -11,43 +11,43 @@ package net.sourceforge.phpdt.internal.compiler.impl; public class IntConstant extends Constant { - + int value; - + public IntConstant(int value) { this.value = value; } - + public byte byteValue() { return (byte) value; } - + public char charValue() { return (char) value; } - + public double doubleValue() { return (double) value; } - + public float floatValue() { return (float) value; } - + public int intValue() { return (int) value; } - + public long longValue() { return (long) value; } - + public short shortValue() { return (short) value; } - + public String stringValue() { - //spec 15.17.11 + // spec 15.17.11 String s = new Integer(value).toString(); if (s == null) return "null"; //$NON-NLS-1$ @@ -57,7 +57,7 @@ public class IntConstant extends Constant { public String toString() { return "(int)" + value; //$NON-NLS-1$ - } + } public int typeID() { return T_int; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/ReferenceContext.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/ReferenceContext.java index 7770bf7..4ebbd6e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/ReferenceContext.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/ReferenceContext.java @@ -13,13 +13,15 @@ package net.sourceforge.phpdt.internal.compiler.impl; import net.sourceforge.phpdt.internal.compiler.CompilationResult; /* - * Implementors are valid compilation contexts from which we can - * escape in case of error: - * For example: method, type or compilation unit. + * Implementors are valid compilation contexts from which we can escape in case + * of error: For example: method, type or compilation unit. */ public interface ReferenceContext { void abort(int abortLevel); + CompilationResult compilationResult(); + void tagAsHavingErrors(); + boolean hasErrors(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/StringConstant.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/StringConstant.java index d9893cf..8cd9463 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/StringConstant.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/impl/StringConstant.java @@ -12,37 +12,38 @@ package net.sourceforge.phpdt.internal.compiler.impl; public class StringConstant extends Constant { public String value; - -public StringConstant(String value) { - this.value = value ; -} -public boolean compileTimeEqual(StringConstant right){ - //String are intermed in the compiler==>thus if two string constant - //get to be compared, it is an equal on the vale which is done - if (this.value == null) { - return right.value == null; + + public StringConstant(String value) { + this.value = value; } - return this.value.equals(right.value); -} -public String stringValue() { - //spec 15.17.11 - - //the next line do not go into the toString() send....! - return value ; - - /* - String s = value.toString() ; - if (s == null) - return "null"; - else - return s; - */ - -} -public String toString(){ - return "(String)\"" + value +"\""; } //$NON-NLS-2$ //$NON-NLS-1$ -public int typeID() { - return T_String; -} + public boolean compileTimeEqual(StringConstant right) { + // String are intermed in the compiler==>thus if two string constant + // get to be compared, it is an equal on the vale which is done + if (this.value == null) { + return right.value == null; + } + return this.value.equals(right.value); + } + + public String stringValue() { + // spec 15.17.11 + + // the next line do not go into the toString() send....! + return value; + + /* + * String s = value.toString() ; if (s == null) return "null"; else + * return s; + */ + + } + + public String toString() { + + return "(String)\"" + value + "\"";} //$NON-NLS-2$ //$NON-NLS-1$ + + public int typeID() { + return T_String; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ArrayBinding.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ArrayBinding.java index 6ccc14b..360fc3d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ArrayBinding.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ArrayBinding.java @@ -15,141 +15,167 @@ import net.sourceforge.phpdt.internal.compiler.impl.Constant; public final class ArrayBinding extends TypeBinding { // creation and initialization of the length field - // the declaringClass of this field is intentionally set to null so it can be distinguished. - public static final FieldBinding LengthField = new FieldBinding(LENGTH, IntBinding, AccPublic | AccFinal, null, Constant.NotAConstant); + // the declaringClass of this field is intentionally set to null so it can + // be distinguished. + public static final FieldBinding LengthField = new FieldBinding(LENGTH, + IntBinding, AccPublic | AccFinal, null, Constant.NotAConstant); public TypeBinding leafComponentType; + public int dimensions; char[] constantPoolName; -public ArrayBinding(TypeBinding type, int dimensions) { - this.tagBits |= IsArrayType; - this.leafComponentType = type; - this.dimensions = dimensions; -} -/* Answer the receiver's constant pool name. -* -* NOTE: This method should only be used during/after code gen. -*/ - -public char[] constantPoolName() /* [Ljava/lang/Object; */ { - if (constantPoolName != null) - return constantPoolName; - - char[] brackets = new char[dimensions]; - for (int i = dimensions - 1; i >= 0; i--) - brackets[i] = '['; - return constantPoolName = CharOperation.concat(brackets, leafComponentType.signature()); -} -String debugName() { - StringBuffer brackets = new StringBuffer(dimensions * 2); - for (int i = dimensions; --i >= 0;) - brackets.append("[]"); //$NON-NLS-1$ - return leafComponentType.debugName() + brackets.toString(); -} -public int dimensions() { - return this.dimensions; -} -/* Answer an array whose dimension size is one less than the receiver. -* -* When the receiver's dimension size is one then answer the leaf component type. -*/ + public ArrayBinding(TypeBinding type, int dimensions) { + this.tagBits |= IsArrayType; + this.leafComponentType = type; + this.dimensions = dimensions; + } + + /* + * Answer the receiver's constant pool name. + * + * NOTE: This method should only be used during/after code gen. + */ + + public char[] constantPoolName() /* [Ljava/lang/Object; */{ + if (constantPoolName != null) + return constantPoolName; + + char[] brackets = new char[dimensions]; + for (int i = dimensions - 1; i >= 0; i--) + brackets[i] = '['; + return constantPoolName = CharOperation.concat(brackets, + leafComponentType.signature()); + } + + String debugName() { + StringBuffer brackets = new StringBuffer(dimensions * 2); + for (int i = dimensions; --i >= 0;) + brackets.append("[]"); //$NON-NLS-1$ + return leafComponentType.debugName() + brackets.toString(); + } + + public int dimensions() { + return this.dimensions; + } + + /* + * Answer an array whose dimension size is one less than the receiver. + * + * When the receiver's dimension size is one then answer the leaf component + * type. + */ + + public TypeBinding elementsType(Scope scope) { + if (dimensions == 1) + return leafComponentType; + else + return scope.createArray(leafComponentType, dimensions - 1); + } + + public PackageBinding getPackage() { + return leafComponentType.getPackage(); + } + + /* + * Answer true if the receiver type can be assigned to the argument type + * (right) + */ + + public boolean isCompatibleWith(TypeBinding right) { + if (this == right) + return true; -public TypeBinding elementsType(Scope scope) { - if (dimensions == 1) + char[][] rightName; + if (right.isArrayType()) { + ArrayBinding rightArray = (ArrayBinding) right; + if (rightArray.leafComponentType.isBaseType()) + return false; // relying on the fact that all equal arrays are + // identical + if (dimensions == rightArray.dimensions) + return leafComponentType + .isCompatibleWith(rightArray.leafComponentType); + if (dimensions < rightArray.dimensions) + return false; // cannot assign 'String[]' into 'Object[][]' + // but can assign 'byte[][]' into 'Object[]' + rightName = ((ReferenceBinding) rightArray.leafComponentType).compoundName; + } else { + if (right.isBaseType()) + return false; + rightName = ((ReferenceBinding) right).compoundName; + } + // Check dimensions - Java does not support explicitly sized dimensions + // for types. + // However, if it did, the type checking support would go here. + + if (CharOperation.equals(rightName, JAVA_LANG_OBJECT)) + return true; + if (CharOperation.equals(rightName, JAVA_LANG_CLONEABLE)) + return true; + if (CharOperation.equals(rightName, JAVA_IO_SERIALIZABLE)) + return true; + return false; + } + + public TypeBinding leafComponentType() { return leafComponentType; - else - return scope.createArray(leafComponentType, dimensions - 1); -} -public PackageBinding getPackage() { - return leafComponentType.getPackage(); -} -/* Answer true if the receiver type can be assigned to the argument type (right) -*/ - -public boolean isCompatibleWith(TypeBinding right) { - if (this == right) - return true; - - char[][] rightName; - if (right.isArrayType()) { - ArrayBinding rightArray = (ArrayBinding) right; - if (rightArray.leafComponentType.isBaseType()) - return false; // relying on the fact that all equal arrays are identical - if (dimensions == rightArray.dimensions) - return leafComponentType.isCompatibleWith(rightArray.leafComponentType); - if (dimensions < rightArray.dimensions) - return false; // cannot assign 'String[]' into 'Object[][]' but can assign 'byte[][]' into 'Object[]' - rightName = ((ReferenceBinding) rightArray.leafComponentType).compoundName; - } else { - if (right.isBaseType()) - return false; - rightName = ((ReferenceBinding) right).compoundName; } - //Check dimensions - Java does not support explicitly sized dimensions for types. - //However, if it did, the type checking support would go here. - - if (CharOperation.equals(rightName, JAVA_LANG_OBJECT)) - return true; - if (CharOperation.equals(rightName, JAVA_LANG_CLONEABLE)) - return true; - if (CharOperation.equals(rightName, JAVA_IO_SERIALIZABLE)) - return true; - return false; -} -public TypeBinding leafComponentType(){ - return leafComponentType; -} + /* + * API Answer the problem id associated with the receiver. NoError if the + * receiver is a valid binding. + */ -/* API -* Answer the problem id associated with the receiver. -* NoError if the receiver is a valid binding. -*/ + public int problemId() { + return leafComponentType.problemId(); + } -public int problemId() { - return leafComponentType.problemId(); -} -/** -* Answer the source name for the type. -* In the case of member types, as the qualified name from its top level type. -* For example, for a member type N defined inside M & A: "A.M.N". -*/ - -public char[] qualifiedSourceName() { - char[] brackets = new char[dimensions * 2]; - for (int i = dimensions * 2 - 1; i >= 0; i -= 2) { - brackets[i] = ']'; - brackets[i - 1] = '['; + /** + * Answer the source name for the type. In the case of member types, as the + * qualified name from its top level type. For example, for a member type N + * defined inside M & A: "A.M.N". + */ + + public char[] qualifiedSourceName() { + char[] brackets = new char[dimensions * 2]; + for (int i = dimensions * 2 - 1; i >= 0; i -= 2) { + brackets[i] = ']'; + brackets[i - 1] = '['; + } + return CharOperation.concat(leafComponentType.qualifiedSourceName(), + brackets); } - return CharOperation.concat(leafComponentType.qualifiedSourceName(), brackets); -} -public char[] readableName() /* java.lang.Object[] */ { - char[] brackets = new char[dimensions * 2]; - for (int i = dimensions * 2 - 1; i >= 0; i -= 2) { - brackets[i] = ']'; - brackets[i - 1] = '['; + + public char[] readableName() /* java.lang.Object[] */{ + char[] brackets = new char[dimensions * 2]; + for (int i = dimensions * 2 - 1; i >= 0; i -= 2) { + brackets[i] = ']'; + brackets[i - 1] = '['; + } + return CharOperation.concat(leafComponentType.readableName(), brackets); } - return CharOperation.concat(leafComponentType.readableName(), brackets); -} -public char[] shortReadableName(){ - char[] brackets = new char[dimensions * 2]; - for (int i = dimensions * 2 - 1; i >= 0; i -= 2) { - brackets[i] = ']'; - brackets[i - 1] = '['; + + public char[] shortReadableName() { + char[] brackets = new char[dimensions * 2]; + for (int i = dimensions * 2 - 1; i >= 0; i -= 2) { + brackets[i] = ']'; + brackets[i - 1] = '['; + } + return CharOperation.concat(leafComponentType.shortReadableName(), + brackets); } - return CharOperation.concat(leafComponentType.shortReadableName(), brackets); -} -public char[] sourceName() { - char[] brackets = new char[dimensions * 2]; - for (int i = dimensions * 2 - 1; i >= 0; i -= 2) { - brackets[i] = ']'; - brackets[i - 1] = '['; + + public char[] sourceName() { + char[] brackets = new char[dimensions * 2]; + for (int i = dimensions * 2 - 1; i >= 0; i -= 2) { + brackets[i] = ']'; + brackets[i - 1] = '['; + } + return CharOperation.concat(leafComponentType.sourceName(), brackets); + } + + public String toString() { + return leafComponentType != null ? debugName() : "NULL TYPE ARRAY"; //$NON-NLS-1$ } - return CharOperation.concat(leafComponentType.sourceName(), brackets); -} -public String toString() { - return leafComponentType != null ? debugName() : "NULL TYPE ARRAY"; //$NON-NLS-1$ -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/BaseTypeBinding.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/BaseTypeBinding.java index 2115b38..55cedda 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/BaseTypeBinding.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/BaseTypeBinding.java @@ -12,147 +12,176 @@ package net.sourceforge.phpdt.internal.compiler.lookup; public final class BaseTypeBinding extends TypeBinding { public char[] simpleName; - private char [] constantPoolName; -BaseTypeBinding(int id, char[] name, char[] constantPoolName) { - this.tagBits |= IsBaseType; - this.id = id; - this.simpleName = name; - this.constantPoolName = constantPoolName; -} -/* Answer the receiver's constant pool name. -*/ -public char[] constantPoolName() { - return constantPoolName; -} -public PackageBinding getPackage() { - return null; -} -/* Answer true if the receiver type can be assigned to the argument type (right) -*/ - -public final boolean isCompatibleWith(TypeBinding right) { - if (this == right) - return true; - if (!right.isBaseType()) - return this == NullBinding; - - switch (right.id) { - case T_boolean : - case T_byte : - case T_char : + private char[] constantPoolName; + + BaseTypeBinding(int id, char[] name, char[] constantPoolName) { + this.tagBits |= IsBaseType; + this.id = id; + this.simpleName = name; + this.constantPoolName = constantPoolName; + } + + /* + * Answer the receiver's constant pool name. + */ + + public char[] constantPoolName() { + return constantPoolName; + } + + public PackageBinding getPackage() { + return null; + } + + /* + * Answer true if the receiver type can be assigned to the argument type + * (right) + */ + + public final boolean isCompatibleWith(TypeBinding right) { + if (this == right) + return true; + if (!right.isBaseType()) + return this == NullBinding; + + switch (right.id) { + case T_boolean: + case T_byte: + case T_char: return false; - case T_double : + case T_double: switch (id) { - case T_byte : - case T_char : - case T_short : - case T_int : - case T_long : - case T_float : - return true; - default : - return false; + case T_byte: + case T_char: + case T_short: + case T_int: + case T_long: + case T_float: + return true; + default: + return false; } - case T_float : + case T_float: switch (id) { - case T_byte : - case T_char : - case T_short : - case T_int : - case T_long : - return true; - default : - return false; + case T_byte: + case T_char: + case T_short: + case T_int: + case T_long: + return true; + default: + return false; } - case T_long : + case T_long: switch (id) { - case T_byte : - case T_char : - case T_short : - case T_int : - return true; - default : - return false; + case T_byte: + case T_char: + case T_short: + case T_int: + return true; + default: + return false; } - case T_int : + case T_int: switch (id) { - case T_byte : - case T_char : - case T_short : - return true; - default : - return false; + case T_byte: + case T_char: + case T_short: + return true; + default: + return false; } - case T_short : + case T_short: return (id == T_byte); + } + return false; } - return false; -} -public static final boolean isNarrowing(int left, int right) { - //can "left" store a "right" using some narrowing conversion - //(is left smaller than right) - switch (left) { - case T_boolean : + public static final boolean isNarrowing(int left, int right) { + // can "left" store a "right" using some narrowing conversion + // (is left smaller than right) + + switch (left) { + case T_boolean: return right == T_boolean; - case T_char : - case T_byte : - if (right == T_byte) return true; - case T_short : - if (right == T_short) return true; - if (right == T_char) return true; - case T_int : - if (right == T_int) return true; - case T_long : - if (right == T_long) return true; - case T_float : - if (right == T_float) return true; - case T_double : - if (right == T_double) return true; - default : + case T_char: + case T_byte: + if (right == T_byte) + return true; + case T_short: + if (right == T_short) + return true; + if (right == T_char) + return true; + case T_int: + if (right == T_int) + return true; + case T_long: + if (right == T_long) + return true; + case T_float: + if (right == T_float) + return true; + case T_double: + if (right == T_double) + return true; + default: return false; + } } -} -public static final boolean isWidening(int left, int right) { - //can "left" store a "right" using some widening conversion - //(is left "bigger" than right) - switch (left) { - case T_boolean : + public static final boolean isWidening(int left, int right) { + // can "left" store a "right" using some widening conversion + // (is left "bigger" than right) + + switch (left) { + case T_boolean: return right == T_boolean; - case T_char : + case T_char: return right == T_char; - case T_double : - if (right == T_double) return true; - case T_float : - if (right == T_float) return true; - case T_long : - if (right == T_long) return true; - case T_int : - if (right == T_int) return true; - if (right == T_char) return true; - case T_short : - if (right == T_short) return true; - case T_byte : - if (right == T_byte) return true; - default : + case T_double: + if (right == T_double) + return true; + case T_float: + if (right == T_float) + return true; + case T_long: + if (right == T_long) + return true; + case T_int: + if (right == T_int) + return true; + if (right == T_char) + return true; + case T_short: + if (right == T_short) + return true; + case T_byte: + if (right == T_byte) + return true; + default: return false; + } + } + + public char[] qualifiedSourceName() { + return simpleName; + } + + public char[] readableName() { + return simpleName; + } + + public char[] shortReadableName() { + return simpleName; + } + + public char[] sourceName() { + return simpleName; + } + + public String toString() { + return new String(constantPoolName) + " (id=" + id + ")"; //$NON-NLS-1$ //$NON-NLS-2$ } -} -public char[] qualifiedSourceName() { - return simpleName; -} -public char[] readableName() { - return simpleName; -} -public char[] shortReadableName(){ - return simpleName; -} -public char[] sourceName() { - return simpleName; -} -public String toString() { - return new String(constantPoolName) + " (id=" + id + ")"; //$NON-NLS-1$ //$NON-NLS-2$ -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/BaseTypes.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/BaseTypes.java index 209ae95..c419524 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/BaseTypes.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/BaseTypes.java @@ -11,14 +11,36 @@ package net.sourceforge.phpdt.internal.compiler.lookup; public interface BaseTypes { - final BaseTypeBinding IntBinding = new BaseTypeBinding(TypeIds.T_int, "int".toCharArray(), new char[] {'I'}); //$NON-NLS-1$ - final BaseTypeBinding ByteBinding = new BaseTypeBinding(TypeIds.T_byte, "byte".toCharArray(), new char[] {'B'}); //$NON-NLS-1$ - final BaseTypeBinding ShortBinding = new BaseTypeBinding(TypeIds.T_short, "short".toCharArray(), new char[] {'S'}); //$NON-NLS-1$ - final BaseTypeBinding CharBinding = new BaseTypeBinding(TypeIds.T_char, "char".toCharArray(), new char[] {'C'}); //$NON-NLS-1$ - final BaseTypeBinding LongBinding = new BaseTypeBinding(TypeIds.T_long, "long".toCharArray(), new char[] {'J'}); //$NON-NLS-1$ - final BaseTypeBinding FloatBinding = new BaseTypeBinding(TypeIds.T_float, "float".toCharArray(), new char[] {'F'}); //$NON-NLS-1$ - final BaseTypeBinding DoubleBinding = new BaseTypeBinding(TypeIds.T_double, "double".toCharArray(), new char[] {'D'}); //$NON-NLS-1$ - final BaseTypeBinding BooleanBinding = new BaseTypeBinding(TypeIds.T_boolean, "boolean".toCharArray(), new char[] {'Z'}); //$NON-NLS-1$ - final BaseTypeBinding NullBinding = new BaseTypeBinding(TypeIds.T_null, "null".toCharArray(), new char[] {'N'}); //N stands for null even if it is never internally used //$NON-NLS-1$ - final BaseTypeBinding VoidBinding = new BaseTypeBinding(TypeIds.T_void, "void".toCharArray(), new char[] {'V'}); //$NON-NLS-1$ + final BaseTypeBinding IntBinding = new BaseTypeBinding(TypeIds.T_int, + "int".toCharArray(), new char[] { 'I' }); //$NON-NLS-1$ + + final BaseTypeBinding ByteBinding = new BaseTypeBinding(TypeIds.T_byte, + "byte".toCharArray(), new char[] { 'B' }); //$NON-NLS-1$ + + final BaseTypeBinding ShortBinding = new BaseTypeBinding(TypeIds.T_short, + "short".toCharArray(), new char[] { 'S' }); //$NON-NLS-1$ + + final BaseTypeBinding CharBinding = new BaseTypeBinding(TypeIds.T_char, + "char".toCharArray(), new char[] { 'C' }); //$NON-NLS-1$ + + final BaseTypeBinding LongBinding = new BaseTypeBinding(TypeIds.T_long, + "long".toCharArray(), new char[] { 'J' }); //$NON-NLS-1$ + + final BaseTypeBinding FloatBinding = new BaseTypeBinding(TypeIds.T_float, + "float".toCharArray(), new char[] { 'F' }); //$NON-NLS-1$ + + final BaseTypeBinding DoubleBinding = new BaseTypeBinding(TypeIds.T_double, + "double".toCharArray(), new char[] { 'D' }); //$NON-NLS-1$ + + final BaseTypeBinding BooleanBinding = new BaseTypeBinding( + TypeIds.T_boolean, "boolean".toCharArray(), new char[] { 'Z' }); //$NON-NLS-1$ + + final BaseTypeBinding NullBinding = new BaseTypeBinding(TypeIds.T_null, + "null".toCharArray(), new char[] { 'N' }); // N stands for null + // even if it is never + // internally used + // //$NON-NLS-1$ + + final BaseTypeBinding VoidBinding = new BaseTypeBinding(TypeIds.T_void, + "void".toCharArray(), new char[] { 'V' }); //$NON-NLS-1$ } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/BinaryTypeBinding.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/BinaryTypeBinding.java index 127acbe..58143ee 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/BinaryTypeBinding.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/BinaryTypeBinding.java @@ -19,297 +19,317 @@ import net.sourceforge.phpdt.internal.compiler.env.IBinaryType; import net.sourceforge.phpdt.internal.compiler.problem.AbortCompilation; /* -Not all fields defined by this type are initialized when it is created. -Some are initialized only when needed. - -Accessors have been provided for some public fields so all TypeBindings have the same API... -but access public fields directly whenever possible. -Non-public fields have accessors which should be used everywhere you expect the field to be initialized. - -null is NOT a valid value for a non-public field... it just means the field is not initialized. -*/ + * Not all fields defined by this type are initialized when it is created. Some + * are initialized only when needed. + * + * Accessors have been provided for some public fields so all TypeBindings have + * the same API... but access public fields directly whenever possible. + * Non-public fields have accessors which should be used everywhere you expect + * the field to be initialized. + * + * null is NOT a valid value for a non-public field... it just means the field + * is not initialized. + */ public final class BinaryTypeBinding extends ReferenceBinding { - // all of these fields are ONLY guaranteed to be initialized if accessed using their public accessor method + // all of these fields are ONLY guaranteed to be initialized if accessed + // using their public accessor method private ReferenceBinding superclass; + private ReferenceBinding enclosingType; + private ReferenceBinding[] superInterfaces; + private FieldBinding[] fields; + private MethodBinding[] methods; + private ReferenceBinding[] memberTypes; // For the link with the principle structure private LookupEnvironment environment; -public BinaryTypeBinding(PackageBinding packageBinding, IBinaryType binaryType, LookupEnvironment environment) { - this.compoundName = CharOperation.splitOn('/', binaryType.getName()); -// computeId(); - - this.tagBits |= IsBinaryBinding; - this.environment = environment; - this.fPackage = packageBinding; - this. fileName = binaryType.getFileName(); - - // source name must be one name without "$". - char[] possibleSourceName = this.compoundName[this.compoundName.length - 1]; - int start = CharOperation.lastIndexOf('$', possibleSourceName) + 1; - if (start == 0) { - this.sourceName = possibleSourceName; - } else { - this.sourceName = new char[possibleSourceName.length - start]; - System.arraycopy(possibleSourceName, start, this.sourceName, 0, this.sourceName.length); + + public BinaryTypeBinding(PackageBinding packageBinding, + IBinaryType binaryType, LookupEnvironment environment) { + this.compoundName = CharOperation.splitOn('/', binaryType.getName()); + // computeId(); + + this.tagBits |= IsBinaryBinding; + this.environment = environment; + this.fPackage = packageBinding; + this.fileName = binaryType.getFileName(); + + // source name must be one name without "$". + char[] possibleSourceName = this.compoundName[this.compoundName.length - 1]; + int start = CharOperation.lastIndexOf('$', possibleSourceName) + 1; + if (start == 0) { + this.sourceName = possibleSourceName; + } else { + this.sourceName = new char[possibleSourceName.length - start]; + System.arraycopy(possibleSourceName, start, this.sourceName, 0, + this.sourceName.length); + } + + this.modifiers = binaryType.getModifiers(); + if (binaryType.isInterface()) + this.modifiers |= AccInterface; } - this.modifiers = binaryType.getModifiers(); - if (binaryType.isInterface()) - this.modifiers |= AccInterface; -} + public FieldBinding[] availableFields() { + FieldBinding[] availableFields = new FieldBinding[fields.length]; + int count = 0; -public FieldBinding[] availableFields() { - FieldBinding[] availableFields = new FieldBinding[fields.length]; - int count = 0; - - for (int i = 0; i < fields.length;i++) { - try { - availableFields[count] = resolveTypeFor(fields[i]); - count++; - } catch (AbortCompilation a){ + for (int i = 0; i < fields.length; i++) { + try { + availableFields[count] = resolveTypeFor(fields[i]); + count++; + } catch (AbortCompilation a) { + } } + + System.arraycopy(availableFields, 0, + availableFields = new FieldBinding[count], 0, count); + return availableFields; } - - System.arraycopy(availableFields, 0, availableFields = new FieldBinding[count], 0, count); - return availableFields; -} -public MethodBinding[] availableMethods() { - if ((modifiers & AccUnresolved) == 0) - return methods; - - MethodBinding[] availableMethods = new MethodBinding[methods.length]; - int count = 0; - - for (int i = 0; i < methods.length;i++) { - try { - availableMethods[count] = resolveTypesFor(methods[i]); - count++; - } catch (AbortCompilation a){ + public MethodBinding[] availableMethods() { + if ((modifiers & AccUnresolved) == 0) + return methods; + + MethodBinding[] availableMethods = new MethodBinding[methods.length]; + int count = 0; + + for (int i = 0; i < methods.length; i++) { + try { + availableMethods[count] = resolveTypesFor(methods[i]); + count++; + } catch (AbortCompilation a) { + } } + System.arraycopy(availableMethods, 0, + availableMethods = new MethodBinding[count], 0, count); + return availableMethods; } - System.arraycopy(availableMethods, 0, availableMethods = new MethodBinding[count], 0, count); - return availableMethods; -} -void cachePartsFrom(IBinaryType binaryType, boolean needFieldsAndMethods) { - char[] superclassName = binaryType.getSuperclassName(); - if (superclassName != null) - // attempt to find the superclass if it exists in the cache (otherwise - resolve it when requested) - this.superclass = environment.getTypeFromConstantPoolName(superclassName, 0, -1); - - char[] enclosingTypeName = binaryType.getEnclosingTypeName(); - if (enclosingTypeName != null) { - // attempt to find the enclosing type if it exists in the cache (otherwise - resolve it when requested) - this.enclosingType = environment.getTypeFromConstantPoolName(enclosingTypeName, 0, -1); - this.tagBits |= MemberTypeMask; // must be a member type not a top-level or local type -// if (this.enclosingType().isStrictfp()) -// this.modifiers |= AccStrictfp; - if (this.enclosingType().isDeprecated()) - this.modifiers |= AccDeprecatedImplicitly; - } + void cachePartsFrom(IBinaryType binaryType, boolean needFieldsAndMethods) { + char[] superclassName = binaryType.getSuperclassName(); + if (superclassName != null) + // attempt to find the superclass if it exists in the cache + // (otherwise - resolve it when requested) + this.superclass = environment.getTypeFromConstantPoolName( + superclassName, 0, -1); + + char[] enclosingTypeName = binaryType.getEnclosingTypeName(); + if (enclosingTypeName != null) { + // attempt to find the enclosing type if it exists in the cache + // (otherwise - resolve it when requested) + this.enclosingType = environment.getTypeFromConstantPoolName( + enclosingTypeName, 0, -1); + this.tagBits |= MemberTypeMask; // must be a member type not a + // top-level or local type + // if (this.enclosingType().isStrictfp()) + // this.modifiers |= AccStrictfp; + if (this.enclosingType().isDeprecated()) + this.modifiers |= AccDeprecatedImplicitly; + } - this.memberTypes = NoMemberTypes; - IBinaryNestedType[] memberTypeStructures = binaryType.getMemberTypes(); - if (memberTypeStructures != null) { - int size = memberTypeStructures.length; - if (size > 0) { - this.memberTypes = new ReferenceBinding[size]; - for (int i = 0; i < size; i++) - // attempt to find each member type if it exists in the cache (otherwise - resolve it when requested) - this.memberTypes[i] = environment.getTypeFromConstantPoolName(memberTypeStructures[i].getName(), 0, -1); + this.memberTypes = NoMemberTypes; + IBinaryNestedType[] memberTypeStructures = binaryType.getMemberTypes(); + if (memberTypeStructures != null) { + int size = memberTypeStructures.length; + if (size > 0) { + this.memberTypes = new ReferenceBinding[size]; + for (int i = 0; i < size; i++) + // attempt to find each member type if it exists in the + // cache (otherwise - resolve it when requested) + this.memberTypes[i] = environment + .getTypeFromConstantPoolName( + memberTypeStructures[i].getName(), 0, -1); + } } - } - this.superInterfaces = NoSuperInterfaces; - char[][] interfaceNames = binaryType.getInterfaceNames(); - if (interfaceNames != null) { - int size = interfaceNames.length; - if (size > 0) { - this.superInterfaces = new ReferenceBinding[size]; - for (int i = 0; i < size; i++) - // attempt to find each superinterface if it exists in the cache (otherwise - resolve it when requested) - this.superInterfaces[i] = environment.getTypeFromConstantPoolName(interfaceNames[i], 0, -1); + this.superInterfaces = NoSuperInterfaces; + char[][] interfaceNames = binaryType.getInterfaceNames(); + if (interfaceNames != null) { + int size = interfaceNames.length; + if (size > 0) { + this.superInterfaces = new ReferenceBinding[size]; + for (int i = 0; i < size; i++) + // attempt to find each superinterface if it exists in the + // cache (otherwise - resolve it when requested) + this.superInterfaces[i] = environment + .getTypeFromConstantPoolName(interfaceNames[i], 0, + -1); + } + } + if (needFieldsAndMethods) { + createFields(binaryType.getFields()); + createMethods(binaryType.getMethods()); } } - if (needFieldsAndMethods){ - createFields(binaryType.getFields()); - createMethods(binaryType.getMethods()); - } -} -private void createFields(IBinaryField[] iFields) { - this.fields = NoFields; - if (iFields != null) { - int size = iFields.length; - if (size > 0) { - this.fields = new FieldBinding[size]; - for (int i = 0; i < size; i++) { - IBinaryField field = iFields[i]; - this.fields[i] = - new FieldBinding( - field.getName(), - environment.getTypeFromSignature(field.getTypeName(), 0, -1), - field.getModifiers(), - this, - field.getConstant()); + + private void createFields(IBinaryField[] iFields) { + this.fields = NoFields; + if (iFields != null) { + int size = iFields.length; + if (size > 0) { + this.fields = new FieldBinding[size]; + for (int i = 0; i < size; i++) { + IBinaryField field = iFields[i]; + this.fields[i] = new FieldBinding(field.getName(), + environment.getTypeFromSignature(field + .getTypeName(), 0, -1), field + .getModifiers(), this, field.getConstant()); + } } } } -} -private MethodBinding createMethod(IBinaryMethod method) { - int modifiers = method.getModifiers() | AccUnresolved; - ReferenceBinding[] exceptions = NoExceptions; - char[][] exceptionTypes = method.getExceptionTypeNames(); - if (exceptionTypes != null) { - int size = exceptionTypes.length; - if (size > 0) { - exceptions = new ReferenceBinding[size]; - for (int i = 0; i < size; i++) - exceptions[i] = environment.getTypeFromConstantPoolName(exceptionTypes[i], 0, -1); + private MethodBinding createMethod(IBinaryMethod method) { + int modifiers = method.getModifiers() | AccUnresolved; + + ReferenceBinding[] exceptions = NoExceptions; + char[][] exceptionTypes = method.getExceptionTypeNames(); + if (exceptionTypes != null) { + int size = exceptionTypes.length; + if (size > 0) { + exceptions = new ReferenceBinding[size]; + for (int i = 0; i < size; i++) + exceptions[i] = environment.getTypeFromConstantPoolName( + exceptionTypes[i], 0, -1); + } } - } - TypeBinding[] parameters = NoParameters; - char[] signature = method.getMethodDescriptor(); // of the form (I[Ljava/jang/String;)V - int numOfParams = 0; - char nextChar; - int index = 0; // first character is always '(' so skip it - while ((nextChar = signature[++index]) != ')') { - if (nextChar != '[') { - numOfParams++; - if (nextChar == 'L') - while ((nextChar = signature[++index]) != ';'); + TypeBinding[] parameters = NoParameters; + char[] signature = method.getMethodDescriptor(); // of the form + // (I[Ljava/jang/String;)V + int numOfParams = 0; + char nextChar; + int index = 0; // first character is always '(' so skip it + while ((nextChar = signature[++index]) != ')') { + if (nextChar != '[') { + numOfParams++; + if (nextChar == 'L') + while ((nextChar = signature[++index]) != ';') + ; + } } - } - // Ignore synthetic argument for member types. - int startIndex = (method.isConstructor() && isMemberType() && !isStatic()) ? 1 : 0; - int size = numOfParams - startIndex; - if (size > 0) { - parameters = new TypeBinding[size]; - index = 1; - int end = 0; // first character is always '(' so skip it - for (int i = 0; i < numOfParams; i++) { - while ((nextChar = signature[++end]) == '['); - if (nextChar == 'L') - while ((nextChar = signature[++end]) != ';'); - - if (i >= startIndex) // skip the synthetic arg if necessary - parameters[i - startIndex] = environment.getTypeFromSignature(signature, index, end); - index = end + 1; + // Ignore synthetic argument for member types. + int startIndex = (method.isConstructor() && isMemberType() && !isStatic()) ? 1 + : 0; + int size = numOfParams - startIndex; + if (size > 0) { + parameters = new TypeBinding[size]; + index = 1; + int end = 0; // first character is always '(' so skip it + for (int i = 0; i < numOfParams; i++) { + while ((nextChar = signature[++end]) == '[') + ; + if (nextChar == 'L') + while ((nextChar = signature[++end]) != ';') + ; + + if (i >= startIndex) // skip the synthetic arg if necessary + parameters[i - startIndex] = environment + .getTypeFromSignature(signature, index, end); + index = end + 1; + } } + + MethodBinding binding = null; + if (method.isConstructor()) + binding = new MethodBinding(modifiers, parameters, exceptions, this); + else + binding = new MethodBinding(modifiers, method.getSelector(), + environment.getTypeFromSignature(signature, index + 1, -1), // index + // is + // currently + // pointing + // at + // the + // ')' + parameters, exceptions, this); + return binding; } - MethodBinding binding = null; - if (method.isConstructor()) - binding = new MethodBinding(modifiers, parameters, exceptions, this); - else - binding = new MethodBinding( - modifiers, - method.getSelector(), - environment.getTypeFromSignature(signature, index + 1, -1), // index is currently pointing at the ')' - parameters, - exceptions, - this); - return binding; -} -/** - * Create method bindings for binary type, filtering out and synthetics - */ -private void createMethods(IBinaryMethod[] iMethods) { - int total = 0, initialTotal = 0, iClinit = -1; - int[] toSkip = null; - if (iMethods != null) { - total = initialTotal = iMethods.length; - for (int i = total; --i >= 0;) { - IBinaryMethod method = iMethods[i]; -// if ((method.getModifiers() & AccSynthetic) != 0) { -// // discard synthetics methods -// if (toSkip == null) toSkip = new int[iMethods.length]; -// toSkip[i] = -1; -// total--; -// } else - if (iClinit == -1) { - char[] methodName = method.getSelector(); - if (methodName.length == 8 && methodName[0] == '<') { - // discard - iClinit = i; - total--; + /** + * Create method bindings for binary type, filtering out and + * synthetics + */ + private void createMethods(IBinaryMethod[] iMethods) { + int total = 0, initialTotal = 0, iClinit = -1; + int[] toSkip = null; + if (iMethods != null) { + total = initialTotal = iMethods.length; + for (int i = total; --i >= 0;) { + IBinaryMethod method = iMethods[i]; + // if ((method.getModifiers() & AccSynthetic) != 0) { + // // discard synthetics methods + // if (toSkip == null) toSkip = new int[iMethods.length]; + // toSkip[i] = -1; + // total--; + // } else + if (iClinit == -1) { + char[] methodName = method.getSelector(); + if (methodName.length == 8 && methodName[0] == '<') { + // discard + iClinit = i; + total--; + } } } } - } - if (total == 0) { - this.methods = NoMethods; - return; + if (total == 0) { + this.methods = NoMethods; + return; + } + + this.methods = new MethodBinding[total]; + if (total == initialTotal) { + for (int i = 0; i < initialTotal; i++) + this.methods[i] = createMethod(iMethods[i]); + } else { + for (int i = 0, index = 0; i < initialTotal; i++) + if (iClinit != i && (toSkip == null || toSkip[i] != -1)) + this.methods[index++] = createMethod(iMethods[i]); + } + modifiers |= AccUnresolved; // until methods() is sent } - this.methods = new MethodBinding[total]; - if (total == initialTotal) { - for (int i = 0; i < initialTotal; i++) - this.methods[i] = createMethod(iMethods[i]); - } else { - for (int i = 0, index = 0; i < initialTotal; i++) - if (iClinit != i && (toSkip == null || toSkip[i] != -1)) - this.methods[index++] = createMethod(iMethods[i]); + /* + * Answer the receiver's enclosing type... null if the receiver is a top + * level type. + * + * NOTE: enclosingType of a binary type is resolved when needed + */ + + public ReferenceBinding enclosingType() { + if (enclosingType == null) + return null; + if (enclosingType instanceof UnresolvedReferenceBinding) + enclosingType = ((UnresolvedReferenceBinding) enclosingType) + .resolve(environment); + return enclosingType; } - modifiers |= AccUnresolved; // until methods() is sent -} -/* Answer the receiver's enclosing type... null if the receiver is a top level type. -* -* NOTE: enclosingType of a binary type is resolved when needed -*/ -public ReferenceBinding enclosingType() { - if (enclosingType == null) - return null; - if (enclosingType instanceof UnresolvedReferenceBinding) - enclosingType = ((UnresolvedReferenceBinding) enclosingType).resolve(environment); - return enclosingType; -} -// NOTE: the type of each field of a binary type is resolved when needed + // NOTE: the type of each field of a binary type is resolved when needed -public FieldBinding[] fields() { - for (int i = fields.length; --i >= 0;) - resolveTypeFor(fields[i]); - return fields; -} -// NOTE: the return type, arg & exception types of each method of a binary type are resolved when needed - -public MethodBinding getExactConstructor(TypeBinding[] argumentTypes) { - int argCount = argumentTypes.length; - nextMethod : for (int m = methods.length; --m >= 0;) { - MethodBinding method = methods[m]; - if (method.selector == ConstructorDeclaration.ConstantPoolName && method.parameters.length == argCount) { - resolveTypesFor(method); - TypeBinding[] toMatch = method.parameters; - for (int p = 0; p < argCount; p++) - if (toMatch[p] != argumentTypes[p]) - continue nextMethod; - return method; - } + public FieldBinding[] fields() { + for (int i = fields.length; --i >= 0;) + resolveTypeFor(fields[i]); + return fields; } - return null; -} -// NOTE: the return type, arg & exception types of each method of a binary type are resolved when needed -// searches up the hierarchy as long as no potential (but not exact) match was found. - -public MethodBinding getExactMethod(char[] selector, TypeBinding[] argumentTypes) { - int argCount = argumentTypes.length; - int selectorLength = selector.length; - boolean foundNothing = true; - nextMethod : for (int m = methods.length; --m >= 0;) { - MethodBinding method = methods[m]; - if (method.selector.length == selectorLength && CharOperation.prefixEquals(method.selector, selector)) { - foundNothing = false; // inner type lookups must know that a method with this name exists - if (method.parameters.length == argCount) { + + // NOTE: the return type, arg & exception types of each method of a binary + // type are resolved when needed + + public MethodBinding getExactConstructor(TypeBinding[] argumentTypes) { + int argCount = argumentTypes.length; + nextMethod: for (int m = methods.length; --m >= 0;) { + MethodBinding method = methods[m]; + if (method.selector == ConstructorDeclaration.ConstantPoolName + && method.parameters.length == argCount) { resolveTypesFor(method); TypeBinding[] toMatch = method.parameters; for (int p = 0; p < argCount; p++) @@ -318,190 +338,251 @@ public MethodBinding getExactMethod(char[] selector, TypeBinding[] argumentTypes return method; } } + return null; } - if (foundNothing) { - if (isInterface()) { - if (superInterfaces.length == 1) - return superInterfaces[0].getExactMethod(selector, argumentTypes); - } else if (superclass != null) { - return superclass.getExactMethod(selector, argumentTypes); + // NOTE: the return type, arg & exception types of each method of a binary + // type are resolved when needed + // searches up the hierarchy as long as no potential (but not exact) match + // was found. + + public MethodBinding getExactMethod(char[] selector, + TypeBinding[] argumentTypes) { + int argCount = argumentTypes.length; + int selectorLength = selector.length; + boolean foundNothing = true; + nextMethod: for (int m = methods.length; --m >= 0;) { + MethodBinding method = methods[m]; + if (method.selector.length == selectorLength + && CharOperation.prefixEquals(method.selector, selector)) { + foundNothing = false; // inner type lookups must know that a + // method with this name exists + if (method.parameters.length == argCount) { + resolveTypesFor(method); + TypeBinding[] toMatch = method.parameters; + for (int p = 0; p < argCount; p++) + if (toMatch[p] != argumentTypes[p]) + continue nextMethod; + return method; + } + } } + + if (foundNothing) { + if (isInterface()) { + if (superInterfaces.length == 1) + return superInterfaces[0].getExactMethod(selector, + argumentTypes); + } else if (superclass != null) { + return superclass.getExactMethod(selector, argumentTypes); + } + } + return null; } - return null; -} -// NOTE: the type of a field of a binary type is resolved when needed - -public FieldBinding getField(char[] fieldName) { - int fieldLength = fieldName.length; - for (int f = fields.length; --f >= 0;) { - char[] name = fields[f].name; - if (name.length == fieldLength && CharOperation.prefixEquals(name, fieldName)) - return resolveTypeFor(fields[f]); - } - return null; -} -// NOTE: the return type, arg & exception types of each method of a binary type are resolved when needed - -public MethodBinding[] getMethods(char[] selector) { - int count = 0; - int lastIndex = -1; - int selectorLength = selector.length; - for (int m = 0, length = methods.length; m < length; m++) { - MethodBinding method = methods[m]; - if (method.selector.length == selectorLength && CharOperation.prefixEquals(method.selector, selector)) { - resolveTypesFor(method); - count++; - lastIndex = m; + + // NOTE: the type of a field of a binary type is resolved when needed + + public FieldBinding getField(char[] fieldName) { + int fieldLength = fieldName.length; + for (int f = fields.length; --f >= 0;) { + char[] name = fields[f].name; + if (name.length == fieldLength + && CharOperation.prefixEquals(name, fieldName)) + return resolveTypeFor(fields[f]); } + return null; } - if (count == 1) - return new MethodBinding[] {methods[lastIndex]}; - if (count > 0) { - MethodBinding[] result = new MethodBinding[count]; - count = 0; - for (int m = 0; m <= lastIndex; m++) { + + // NOTE: the return type, arg & exception types of each method of a binary + // type are resolved when needed + + public MethodBinding[] getMethods(char[] selector) { + int count = 0; + int lastIndex = -1; + int selectorLength = selector.length; + for (int m = 0, length = methods.length; m < length; m++) { MethodBinding method = methods[m]; - if (method.selector.length == selectorLength && CharOperation.prefixEquals(method.selector, selector)) - result[count++] = method; + if (method.selector.length == selectorLength + && CharOperation.prefixEquals(method.selector, selector)) { + resolveTypesFor(method); + count++; + lastIndex = m; + } + } + if (count == 1) + return new MethodBinding[] { methods[lastIndex] }; + if (count > 0) { + MethodBinding[] result = new MethodBinding[count]; + count = 0; + for (int m = 0; m <= lastIndex; m++) { + MethodBinding method = methods[m]; + if (method.selector.length == selectorLength + && CharOperation + .prefixEquals(method.selector, selector)) + result[count++] = method; + } + return result; } - return result; + return NoMethods; } - return NoMethods; -} -// NOTE: member types of binary types are resolved when needed -public ReferenceBinding[] memberTypes() { - for (int i = memberTypes.length; --i >= 0;) - if (memberTypes[i] instanceof UnresolvedReferenceBinding) - memberTypes[i] = ((UnresolvedReferenceBinding) memberTypes[i]).resolve(environment); - return memberTypes; -} -// NOTE: the return type, arg & exception types of each method of a binary type are resolved when needed + // NOTE: member types of binary types are resolved when needed + + public ReferenceBinding[] memberTypes() { + for (int i = memberTypes.length; --i >= 0;) + if (memberTypes[i] instanceof UnresolvedReferenceBinding) + memberTypes[i] = ((UnresolvedReferenceBinding) memberTypes[i]) + .resolve(environment); + return memberTypes; + } -public MethodBinding[] methods() { - if ((modifiers & AccUnresolved) == 0) + // NOTE: the return type, arg & exception types of each method of a binary + // type are resolved when needed + + public MethodBinding[] methods() { + if ((modifiers & AccUnresolved) == 0) + return methods; + + for (int i = methods.length; --i >= 0;) + resolveTypesFor(methods[i]); + modifiers ^= AccUnresolved; return methods; + } - for (int i = methods.length; --i >= 0;) - resolveTypesFor(methods[i]); - modifiers ^= AccUnresolved; - return methods; -} -private TypeBinding resolveType(TypeBinding type) { - if (type instanceof UnresolvedReferenceBinding) - return ((UnresolvedReferenceBinding) type).resolve(environment); - if (type instanceof ArrayBinding) { - ArrayBinding array = (ArrayBinding) type; - if (array.leafComponentType instanceof UnresolvedReferenceBinding) - array.leafComponentType = ((UnresolvedReferenceBinding) array.leafComponentType).resolve(environment); + private TypeBinding resolveType(TypeBinding type) { + if (type instanceof UnresolvedReferenceBinding) + return ((UnresolvedReferenceBinding) type).resolve(environment); + if (type instanceof ArrayBinding) { + ArrayBinding array = (ArrayBinding) type; + if (array.leafComponentType instanceof UnresolvedReferenceBinding) + array.leafComponentType = ((UnresolvedReferenceBinding) array.leafComponentType) + .resolve(environment); + } + return type; } - return type; -} -private FieldBinding resolveTypeFor(FieldBinding field) { - field.type = resolveType(field.type); - return field; -} -private MethodBinding resolveTypesFor(MethodBinding method) { - if ((method.modifiers & AccUnresolved) == 0) + + private FieldBinding resolveTypeFor(FieldBinding field) { + field.type = resolveType(field.type); + return field; + } + + private MethodBinding resolveTypesFor(MethodBinding method) { + if ((method.modifiers & AccUnresolved) == 0) + return method; + + if (!method.isConstructor()) + method.returnType = resolveType(method.returnType); + for (int i = method.parameters.length; --i >= 0;) + method.parameters[i] = resolveType(method.parameters[i]); + for (int i = method.thrownExceptions.length; --i >= 0;) + if (method.thrownExceptions[i] instanceof UnresolvedReferenceBinding) + method.thrownExceptions[i] = ((UnresolvedReferenceBinding) method.thrownExceptions[i]) + .resolve(environment); + method.modifiers ^= AccUnresolved; return method; + } - if (!method.isConstructor()) - method.returnType = resolveType(method.returnType); - for (int i = method.parameters.length; --i >= 0;) - method.parameters[i] = resolveType(method.parameters[i]); - for (int i = method.thrownExceptions.length; --i >= 0;) - if (method.thrownExceptions[i] instanceof UnresolvedReferenceBinding) - method.thrownExceptions[i] = ((UnresolvedReferenceBinding) method.thrownExceptions[i]).resolve(environment); - method.modifiers ^= AccUnresolved; - return method; -} -/* Answer the receiver's superclass... null if the receiver is Object or an interface. -* -* NOTE: superclass of a binary type is resolved when needed -*/ + /* + * Answer the receiver's superclass... null if the receiver is Object or an + * interface. + * + * NOTE: superclass of a binary type is resolved when needed + */ + + public ReferenceBinding superclass() { + if (superclass == null) + return null; + if (superclass instanceof UnresolvedReferenceBinding) + superclass = ((UnresolvedReferenceBinding) superclass) + .resolve(environment); + return superclass; + } -public ReferenceBinding superclass() { - if (superclass == null) - return null; - if (superclass instanceof UnresolvedReferenceBinding) - superclass = ((UnresolvedReferenceBinding) superclass).resolve(environment); - return superclass; -} -// NOTE: superInterfaces of binary types are resolved when needed + // NOTE: superInterfaces of binary types are resolved when needed -public ReferenceBinding[] superInterfaces() { - for (int i = superInterfaces.length; --i >= 0;) - if (superInterfaces[i] instanceof UnresolvedReferenceBinding) - superInterfaces[i] = ((UnresolvedReferenceBinding) superInterfaces[i]).resolve(environment); - return superInterfaces; -} -public String toString() { - String s = ""; //$NON-NLS-1$ - - if (isDeprecated()) s += "deprecated "; //$NON-NLS-1$ - if (isPublic()) s += "public "; //$NON-NLS-1$ - if (isProtected()) s += "protected "; //$NON-NLS-1$ - if (isPrivate()) s += "private "; //$NON-NLS-1$ - if (isAbstract() && isClass()) s += "abstract "; //$NON-NLS-1$ - if (isStatic() && isNestedType()) s += "static "; //$NON-NLS-1$ - if (isFinal()) s += "final "; //$NON-NLS-1$ - - s += isInterface() ? "interface " : "class "; //$NON-NLS-1$ //$NON-NLS-2$ - s += (compoundName != null) ? CharOperation.toString(compoundName) : "UNNAMED TYPE"; //$NON-NLS-1$ - - s += "\n\textends "; //$NON-NLS-1$ - s += (superclass != null) ? superclass.debugName() : "NULL TYPE"; //$NON-NLS-1$ - - if (superInterfaces != null) { - if (superInterfaces != NoSuperInterfaces) { - s += "\n\timplements : "; //$NON-NLS-1$ - for (int i = 0, length = superInterfaces.length; i < length; i++) { - if (i > 0) - s += ", "; //$NON-NLS-1$ - s += (superInterfaces[i] != null) ? superInterfaces[i].debugName() : "NULL TYPE"; //$NON-NLS-1$ + public ReferenceBinding[] superInterfaces() { + for (int i = superInterfaces.length; --i >= 0;) + if (superInterfaces[i] instanceof UnresolvedReferenceBinding) + superInterfaces[i] = ((UnresolvedReferenceBinding) superInterfaces[i]) + .resolve(environment); + return superInterfaces; + } + + public String toString() { + String s = ""; //$NON-NLS-1$ + + if (isDeprecated()) + s += "deprecated "; //$NON-NLS-1$ + if (isPublic()) + s += "public "; //$NON-NLS-1$ + if (isProtected()) + s += "protected "; //$NON-NLS-1$ + if (isPrivate()) + s += "private "; //$NON-NLS-1$ + if (isAbstract() && isClass()) + s += "abstract "; //$NON-NLS-1$ + if (isStatic() && isNestedType()) + s += "static "; //$NON-NLS-1$ + if (isFinal()) + s += "final "; //$NON-NLS-1$ + + s += isInterface() ? "interface " : "class "; //$NON-NLS-1$ //$NON-NLS-2$ + s += (compoundName != null) ? CharOperation.toString(compoundName) + : "UNNAMED TYPE"; //$NON-NLS-1$ + + s += "\n\textends "; //$NON-NLS-1$ + s += (superclass != null) ? superclass.debugName() : "NULL TYPE"; //$NON-NLS-1$ + + if (superInterfaces != null) { + if (superInterfaces != NoSuperInterfaces) { + s += "\n\timplements : "; //$NON-NLS-1$ + for (int i = 0, length = superInterfaces.length; i < length; i++) { + if (i > 0) + s += ", "; //$NON-NLS-1$ + s += (superInterfaces[i] != null) ? superInterfaces[i] + .debugName() : "NULL TYPE"; //$NON-NLS-1$ + } } + } else { + s += "NULL SUPERINTERFACES"; //$NON-NLS-1$ } - } else { - s += "NULL SUPERINTERFACES"; //$NON-NLS-1$ - } - if (enclosingType != null) { - s += "\n\tenclosing type : "; //$NON-NLS-1$ - s += enclosingType.debugName(); - } + if (enclosingType != null) { + s += "\n\tenclosing type : "; //$NON-NLS-1$ + s += enclosingType.debugName(); + } - if (fields != null) { - if (fields != NoFields) { - s += "\n/* fields */"; //$NON-NLS-1$ - for (int i = 0, length = fields.length; i < length; i++) - s += (fields[i] != null) ? "\n" + fields[i].toString() : "\nNULL FIELD"; //$NON-NLS-1$ //$NON-NLS-2$ + if (fields != null) { + if (fields != NoFields) { + s += "\n/* fields */"; //$NON-NLS-1$ + for (int i = 0, length = fields.length; i < length; i++) + s += (fields[i] != null) ? "\n" + fields[i].toString() : "\nNULL FIELD"; //$NON-NLS-1$ //$NON-NLS-2$ + } + } else { + s += "NULL FIELDS"; //$NON-NLS-1$ } - } else { - s += "NULL FIELDS"; //$NON-NLS-1$ - } - if (methods != null) { - if (methods != NoMethods) { - s += "\n/* methods */"; //$NON-NLS-1$ - for (int i = 0, length = methods.length; i < length; i++) - s += (methods[i] != null) ? "\n" + methods[i].toString() : "\nNULL METHOD"; //$NON-NLS-1$ //$NON-NLS-2$ + if (methods != null) { + if (methods != NoMethods) { + s += "\n/* methods */"; //$NON-NLS-1$ + for (int i = 0, length = methods.length; i < length; i++) + s += (methods[i] != null) ? "\n" + methods[i].toString() : "\nNULL METHOD"; //$NON-NLS-1$ //$NON-NLS-2$ + } + } else { + s += "NULL METHODS"; //$NON-NLS-1$ } - } else { - s += "NULL METHODS"; //$NON-NLS-1$ - } - if (memberTypes != null) { - if (memberTypes != NoMemberTypes) { - s += "\n/* members */"; //$NON-NLS-1$ - for (int i = 0, length = memberTypes.length; i < length; i++) - s += (memberTypes[i] != null) ? "\n" + memberTypes[i].toString() : "\nNULL TYPE"; //$NON-NLS-1$ //$NON-NLS-2$ + if (memberTypes != null) { + if (memberTypes != NoMemberTypes) { + s += "\n/* members */"; //$NON-NLS-1$ + for (int i = 0, length = memberTypes.length; i < length; i++) + s += (memberTypes[i] != null) ? "\n" + memberTypes[i].toString() : "\nNULL TYPE"; //$NON-NLS-1$ //$NON-NLS-2$ + } + } else { + s += "NULL MEMBER TYPES"; //$NON-NLS-1$ } - } else { - s += "NULL MEMBER TYPES"; //$NON-NLS-1$ - } - s += "\n\n\n"; //$NON-NLS-1$ - return s; -} + s += "\n\n\n"; //$NON-NLS-1$ + return s; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/Binding.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/Binding.java index c446988..20f335e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/Binding.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/Binding.java @@ -10,36 +10,42 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.compiler.lookup; -public abstract class Binding implements BindingIds, CompilerModifiers, ProblemReasons { - /* API - * Answer the receiver's binding type from Binding.BindingID. - * - * Note: Do NOT expect this to be used very often... only in switch statements with - * more than 2 possible choices. - */ +public abstract class Binding implements BindingIds, CompilerModifiers, + ProblemReasons { + /* + * API Answer the receiver's binding type from Binding.BindingID. + * + * Note: Do NOT expect this to be used very often... only in switch + * statements with more than 2 possible choices. + */ public abstract int bindingType(); - /* API - * Answer true if the receiver is not a problem binding - */ - + + /* + * API Answer true if the receiver is not a problem binding + */ + public final boolean isValidBinding() { return problemId() == NoError; } - /* API - * Answer the problem id associated with the receiver. - * NoError if the receiver is a valid binding. - */ - + + /* + * API Answer the problem id associated with the receiver. NoError if the + * receiver is a valid binding. + */ + public int problemId() { return NoError; } - /* Answer a printable representation of the receiver. - */ + + /* + * Answer a printable representation of the receiver. + */ public abstract char[] readableName(); - /* Shorter printable representation of the receiver (no qualified type) - */ - public char[] shortReadableName(){ + /* + * Shorter printable representation of the receiver (no qualified type) + */ + public char[] shortReadableName() { return readableName(); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/BindingIds.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/BindingIds.java index e55c779..1c4054c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/BindingIds.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/BindingIds.java @@ -12,10 +12,16 @@ package net.sourceforge.phpdt.internal.compiler.lookup; public interface BindingIds { final int FIELD = 1; + final int LOCAL = 2; + final int VARIABLE = FIELD | LOCAL; + final int TYPE = 4; + final int METHOD = 8; + final int PACKAGE = 16; + final int IMPORT = 32; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/BlockScope.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/BlockScope.java index b6cc496..4c1adb1 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/BlockScope.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/BlockScope.java @@ -20,20 +20,29 @@ public class BlockScope extends Scope { // Local variable management public LocalVariableBinding[] locals; + public int localIndex; // position for next variable - public int startIndex; // start position in this scope - for ordering scopes vs. variables + + public int startIndex; // start position in this scope - for ordering + // scopes vs. variables + public int offset; // for variable allocation throughout scopes + public int maxOffset; // for variable allocation throughout scopes - // finally scopes must be shifted behind respective try&catch scope(s) so as to avoid + // finally scopes must be shifted behind respective try&catch scope(s) so as + // to avoid // collisions of secret variables (return address, save value). - public BlockScope[] shiftScopes; + public BlockScope[] shiftScopes; public final static VariableBinding[] EmulationPathToImplicitThis = {}; + public final static VariableBinding[] NoEnclosingInstanceInConstructorCall = {}; + public final static VariableBinding[] NoEnclosingInstanceInStaticContext = {}; public Scope[] subscopes = new Scope[1]; // need access from code assist + public int scopeIndex = 0; // need access from code assist protected BlockScope(int kind, Scope parent) { @@ -50,7 +59,8 @@ public class BlockScope extends Scope { this(BLOCK_SCOPE, parent); locals = new LocalVariableBinding[5]; - if (addToParentScope) parent.addSubscope(this); + if (addToParentScope) + parent.addSubscope(this); this.startIndex = parent.localIndex; } @@ -62,19 +72,19 @@ public class BlockScope extends Scope { this.startIndex = parent.localIndex; } - /* Create the class scope & binding for the anonymous type. + /* + * Create the class scope & binding for the anonymous type. */ - public final void addAnonymousType( - TypeDeclaration anonymousType, - ReferenceBinding superBinding) { + public final void addAnonymousType(TypeDeclaration anonymousType, + ReferenceBinding superBinding) { ClassScope anonymousClassScope = new ClassScope(this, anonymousType); - anonymousClassScope.buildAnonymousTypeBinding( - enclosingSourceType(), - superBinding); + anonymousClassScope.buildAnonymousTypeBinding(enclosingSourceType(), + superBinding); } - /* Create the class scope & binding for the local type. + /* + * Create the class scope & binding for the local type. */ public final void addLocalType(TypeDeclaration localType) { @@ -88,7 +98,8 @@ public class BlockScope extends Scope { type = type.enclosingType(); } while (type != null); - // check that the localType does not conflict with another sibling local type + // check that the localType does not conflict with another sibling local + // type Scope scope = this; do { if (((BlockScope) scope).findLocalType(localType.name) != null) { @@ -102,8 +113,9 @@ public class BlockScope extends Scope { localTypeScope.buildLocalTypeBinding(enclosingSourceType()); } - /* Insert a local variable into a given scope, updating its position - * and checking there are not too many locals or arguments allocated. + /* + * Insert a local variable into a given scope, updating its position and + * checking there are not too many locals or arguments allocated. */ public final void addLocalVariable(LocalVariableBinding binding) { @@ -111,15 +123,12 @@ public class BlockScope extends Scope { // insert local in scope if (localIndex == locals.length) - System.arraycopy( - locals, - 0, - (locals = new LocalVariableBinding[localIndex * 2]), - 0, - localIndex); + System.arraycopy(locals, 0, + (locals = new LocalVariableBinding[localIndex * 2]), 0, + localIndex); locals[localIndex++] = binding; - // update local variable binding + // update local variable binding binding.declaringScope = this; binding.id = this.outerMostMethodScope().analysisIndex++; // share the outermost method scope analysisIndex @@ -127,18 +136,15 @@ public class BlockScope extends Scope { public void addSubscope(Scope childScope) { if (scopeIndex == subscopes.length) - System.arraycopy( - subscopes, - 0, - (subscopes = new Scope[scopeIndex * 2]), - 0, - scopeIndex); + System.arraycopy(subscopes, 0, + (subscopes = new Scope[scopeIndex * 2]), 0, scopeIndex); subscopes[scopeIndex++] = childScope; } - /* Answer true if the receiver is suitable for assigning final blank fields. - * - * in other words, it is inside an initializer, a constructor or a clinit + /* + * Answer true if the receiver is suitable for assigning final blank fields. + * + * in other words, it is inside an initializer, a constructor or a clinit */ public final boolean allowBlankFinalFieldAssignment(FieldBinding binding) { @@ -150,8 +156,10 @@ public class BlockScope extends Scope { return false; return methodScope.isInsideInitializer() // inside initializer || ((AbstractMethodDeclaration) methodScope.referenceContext) - .isInitializationMethod(); // inside constructor or clinit + .isInitializationMethod(); // inside constructor or + // clinit } + String basicToString(int tab) { String newLine = "\n"; //$NON-NLS-1$ for (int i = tab; --i >= 0;) @@ -169,105 +177,121 @@ public class BlockScope extends Scope { private void checkAndSetModifiersForVariable(LocalVariableBinding varBinding) { int modifiers = varBinding.modifiers; - if ((modifiers & AccAlternateModifierProblem) != 0 && varBinding.declaration != null){ - problemReporter().duplicateModifierForVariable(varBinding.declaration, this instanceof MethodScope); + if ((modifiers & AccAlternateModifierProblem) != 0 + && varBinding.declaration != null) { + problemReporter().duplicateModifierForVariable( + varBinding.declaration, this instanceof MethodScope); } int realModifiers = modifiers & AccJustFlag; - + int unexpectedModifiers = ~AccFinal; - if ((realModifiers & unexpectedModifiers) != 0 && varBinding.declaration != null){ - problemReporter().illegalModifierForVariable(varBinding.declaration, this instanceof MethodScope); + if ((realModifiers & unexpectedModifiers) != 0 + && varBinding.declaration != null) { + problemReporter().illegalModifierForVariable( + varBinding.declaration, this instanceof MethodScope); } varBinding.modifiers = modifiers; } - /* Compute variable positions in scopes given an initial position offset + /* + * Compute variable positions in scopes given an initial position offset * ignoring unused local variables. * - * No argument is expected here (ilocal is the first non-argument local of the outermost scope) - * Arguments are managed by the MethodScope method + * No argument is expected here (ilocal is the first non-argument local of + * the outermost scope) Arguments are managed by the MethodScope method */ -// void computeLocalVariablePositions(int ilocal, int initOffset, CodeStream codeStream) { -// -// this.offset = initOffset; -// this.maxOffset = initOffset; -// -// // local variable init -// int maxLocals = this.localIndex; -// boolean hasMoreVariables = ilocal < maxLocals; -// -// // scope init -// int iscope = 0, maxScopes = this.scopeIndex; -// boolean hasMoreScopes = maxScopes > 0; -// -// // iterate scopes and variables in parallel -// while (hasMoreVariables || hasMoreScopes) { -// if (hasMoreScopes -// && (!hasMoreVariables || (subscopes[iscope].startIndex() <= ilocal))) { -// // consider subscope first -// if (subscopes[iscope] instanceof BlockScope) { -// BlockScope subscope = (BlockScope) subscopes[iscope]; -// int subOffset = subscope.shiftScopes == null ? this.offset : subscope.maxShiftedOffset(); -// subscope.computeLocalVariablePositions(0, subOffset, codeStream); -// if (subscope.maxOffset > this.maxOffset) -// this.maxOffset = subscope.maxOffset; -// } -// hasMoreScopes = ++iscope < maxScopes; -// } else { -// -// // consider variable first -// LocalVariableBinding local = locals[ilocal]; // if no local at all, will be locals[ilocal]==null -// -// // check if variable is actually used, and may force it to be preserved -// boolean generateCurrentLocalVar = (local.useFlag == LocalVariableBinding.USED && (local.constant == Constant.NotAConstant)); -// -// // do not report fake used variable -// if (local.useFlag == LocalVariableBinding.UNUSED -// && (local.declaration != null) // unused (and non secret) local -// && ((local.declaration.bits & ASTNode.IsLocalDeclarationReachableMASK) != 0)) { // declaration is reachable -// -// if (!(local.declaration instanceof Argument)) // do not report unused catch arguments -// this.problemReporter().unusedLocalVariable(local.declaration); -// } -// -// // could be optimized out, but does need to preserve unread variables ? -//// if (!generateCurrentLocalVar) { -//// if (local.declaration != null && environment().options.preserveAllLocalVariables) { -//// generateCurrentLocalVar = true; // force it to be preserved in the generated code -//// local.useFlag = LocalVariableBinding.USED; -//// } -//// } -// -// // allocate variable -// if (generateCurrentLocalVar) { -// -// if (local.declaration != null) { -// codeStream.record(local); // record user-defined local variables for attribute generation -// } -// // assign variable position -// local.resolvedPosition = this.offset; -// -// if ((local.type == LongBinding) || (local.type == DoubleBinding)) { -// this.offset += 2; -// } else { -// this.offset++; -// } -// if (this.offset > 0xFFFF) { // no more than 65535 words of locals -// this.problemReporter().noMoreAvailableSpaceForLocal( -// local, -// local.declaration == null ? (ASTNode)this.methodScope().referenceContext : local.declaration); -// } -// } else { -// local.resolvedPosition = -1; // not generated -// } -// hasMoreVariables = ++ilocal < maxLocals; -// } -// } -// if (this.offset > this.maxOffset) -// this.maxOffset = this.offset; -// } - - /* Answer true if the variable name already exists within the receiver's scope. + // void computeLocalVariablePositions(int ilocal, int initOffset, CodeStream + // codeStream) { + // + // this.offset = initOffset; + // this.maxOffset = initOffset; + // + // // local variable init + // int maxLocals = this.localIndex; + // boolean hasMoreVariables = ilocal < maxLocals; + // + // // scope init + // int iscope = 0, maxScopes = this.scopeIndex; + // boolean hasMoreScopes = maxScopes > 0; + // + // // iterate scopes and variables in parallel + // while (hasMoreVariables || hasMoreScopes) { + // if (hasMoreScopes + // && (!hasMoreVariables || (subscopes[iscope].startIndex() <= ilocal))) { + // // consider subscope first + // if (subscopes[iscope] instanceof BlockScope) { + // BlockScope subscope = (BlockScope) subscopes[iscope]; + // int subOffset = subscope.shiftScopes == null ? this.offset : + // subscope.maxShiftedOffset(); + // subscope.computeLocalVariablePositions(0, subOffset, codeStream); + // if (subscope.maxOffset > this.maxOffset) + // this.maxOffset = subscope.maxOffset; + // } + // hasMoreScopes = ++iscope < maxScopes; + // } else { + // + // // consider variable first + // LocalVariableBinding local = locals[ilocal]; // if no local at all, will + // be locals[ilocal]==null + // + // // check if variable is actually used, and may force it to be preserved + // boolean generateCurrentLocalVar = (local.useFlag == + // LocalVariableBinding.USED && (local.constant == Constant.NotAConstant)); + // + // // do not report fake used variable + // if (local.useFlag == LocalVariableBinding.UNUSED + // && (local.declaration != null) // unused (and non secret) local + // && ((local.declaration.bits & ASTNode.IsLocalDeclarationReachableMASK) != + // 0)) { // declaration is reachable + // + // if (!(local.declaration instanceof Argument)) // do not report unused + // catch arguments + // this.problemReporter().unusedLocalVariable(local.declaration); + // } + // + // // could be optimized out, but does need to preserve unread variables ? + // // if (!generateCurrentLocalVar) { + // // if (local.declaration != null && + // environment().options.preserveAllLocalVariables) { + // // generateCurrentLocalVar = true; // force it to be preserved in the + // generated code + // // local.useFlag = LocalVariableBinding.USED; + // // } + // // } + // + // // allocate variable + // if (generateCurrentLocalVar) { + // + // if (local.declaration != null) { + // codeStream.record(local); // record user-defined local variables for + // attribute generation + // } + // // assign variable position + // local.resolvedPosition = this.offset; + // + // if ((local.type == LongBinding) || (local.type == DoubleBinding)) { + // this.offset += 2; + // } else { + // this.offset++; + // } + // if (this.offset > 0xFFFF) { // no more than 65535 words of locals + // this.problemReporter().noMoreAvailableSpaceForLocal( + // local, + // local.declaration == null ? (ASTNode)this.methodScope().referenceContext + // : local.declaration); + // } + // } else { + // local.resolvedPosition = -1; // not generated + // } + // hasMoreVariables = ++ilocal < maxLocals; + // } + // } + // if (this.offset > this.maxOffset) + // this.maxOffset = this.offset; + // } + /* + * Answer true if the variable name already exists within the receiver's + * scope. */ public final LocalVariableBinding duplicateName(char[] name) { for (int i = 0; i < localIndex; i++) @@ -281,20 +305,21 @@ public class BlockScope extends Scope { } /* - * Record the suitable binding denoting a synthetic field or constructor argument, - * mapping to the actual outer local variable in the scope context. - * Note that this may not need any effect, in case the outer local variable does not - * need to be emulated and can directly be used as is (using its back pointer to its - * declaring scope). + * Record the suitable binding denoting a synthetic field or constructor + * argument, mapping to the actual outer local variable in the scope + * context. Note that this may not need any effect, in case the outer local + * variable does not need to be emulated and can directly be used as is + * (using its back pointer to its declaring scope). */ public void emulateOuterAccess(LocalVariableBinding outerLocalVariable) { MethodScope currentMethodScope; - if ((currentMethodScope = this.methodScope()) - != outerLocalVariable.declaringScope.methodScope()) { - NestedTypeBinding currentType = (NestedTypeBinding) this.enclosingSourceType(); + if ((currentMethodScope = this.methodScope()) != outerLocalVariable.declaringScope + .methodScope()) { + NestedTypeBinding currentType = (NestedTypeBinding) this + .enclosingSourceType(); - //do nothing for member types, pre emulation was performed already + // do nothing for member types, pre emulation was performed already if (!currentType.isLocalType()) { return; } @@ -307,31 +332,21 @@ public class BlockScope extends Scope { } } - /* Note that it must never produce a direct access to the targetEnclosingType, - * but instead a field sequence (this$2.this$1.this$0) so as to handle such a test case: - * - * class XX { - * void foo() { - * class A { - * class B { - * class C { - * boolean foo() { - * return (Object) A.this == (Object) B.this; - * } - * } - * } - * } - * new A().new B().new C(); - * } - * } - * where we only want to deal with ONE enclosing instance for C (could not figure out an A for C) + /* + * Note that it must never produce a direct access to the + * targetEnclosingType, but instead a field sequence (this$2.this$1.this$0) + * so as to handle such a test case: + * + * class XX { void foo() { class A { class B { class C { boolean foo() { + * return (Object) A.this == (Object) B.this; } } } } new A().new B().new + * C(); } } where we only want to deal with ONE enclosing instance for C + * (could not figure out an A for C) */ public final ReferenceBinding findLocalType(char[] name) { for (int i = 0, length = scopeIndex; i < length; i++) { if (subscopes[i] instanceof ClassScope) { - SourceTypeBinding sourceType = - ((ClassScope) subscopes[i]).referenceContext.binding; + SourceTypeBinding sourceType = ((ClassScope) subscopes[i]).referenceContext.binding; if (CharOperation.equals(sourceType.sourceName(), name)) return sourceType; } @@ -347,88 +362,97 @@ public class BlockScope extends Scope { if (local == null) return null; if (local.name.length == variableLength - && CharOperation.prefixEquals(local.name, variable)) + && CharOperation.prefixEquals(local.name, variable)) return local; } return null; } - /* API - * flag is a mask of the following values VARIABLE (= FIELD or LOCAL), TYPE. - * Only bindings corresponding to the mask will be answered. - * - * if the VARIABLE mask is set then - * If the first name provided is a field (or local) then the field (or local) is answered - * Otherwise, package names and type names are consumed until a field is found. - * In this case, the field is answered. - * - * if the TYPE mask is set, - * package names and type names are consumed until the end of the input. - * Only if all of the input is consumed is the type answered - * - * All other conditions are errors, and a problem binding is returned. - * - * NOTE: If a problem binding is returned, senders should extract the compound name - * from the binding & not assume the problem applies to the entire compoundName. - * - * The VARIABLE mask has precedence over the TYPE mask. - * - * InvocationSite implements - * isSuperAccess(); this is used to determine if the discovered field is visible. - * setFieldIndex(int); this is used to record the number of names that were consumed. - * - * For example, getBinding({"foo","y","q", VARIABLE, site) will answer - * the binding for the field or local named "foo" (or an error binding if none exists). - * In addition, setFieldIndex(1) will be sent to the invocation site. - * If a type named "foo" exists, it will not be detected (and an error binding will be answered) - * - * IMPORTANT NOTE: This method is written under the assumption that compoundName is longer than length 1. + + /* + * API flag is a mask of the following values VARIABLE (= FIELD or LOCAL), + * TYPE. Only bindings corresponding to the mask will be answered. + * + * if the VARIABLE mask is set then If the first name provided is a field + * (or local) then the field (or local) is answered Otherwise, package names + * and type names are consumed until a field is found. In this case, the + * field is answered. + * + * if the TYPE mask is set, package names and type names are consumed until + * the end of the input. Only if all of the input is consumed is the type + * answered + * + * All other conditions are errors, and a problem binding is returned. + * + * NOTE: If a problem binding is returned, senders should extract the + * compound name from the binding & not assume the problem applies to the + * entire compoundName. + * + * The VARIABLE mask has precedence over the TYPE mask. + * + * InvocationSite implements isSuperAccess(); this is used to determine if + * the discovered field is visible. setFieldIndex(int); this is used to + * record the number of names that were consumed. + * + * For example, getBinding({"foo","y","q", VARIABLE, site) will answer the + * binding for the field or local named "foo" (or an error binding if none + * exists). In addition, setFieldIndex(1) will be sent to the invocation + * site. If a type named "foo" exists, it will not be detected (and an error + * binding will be answered) + * + * IMPORTANT NOTE: This method is written under the assumption that + * compoundName is longer than length 1. */ - public Binding getBinding(char[][] compoundName, int mask, InvocationSite invocationSite) { + public Binding getBinding(char[][] compoundName, int mask, + InvocationSite invocationSite) { - Binding binding = getBinding(compoundName[0], mask | TYPE | PACKAGE, invocationSite); + Binding binding = getBinding(compoundName[0], mask | TYPE | PACKAGE, + invocationSite); invocationSite.setFieldIndex(1); - if (binding instanceof VariableBinding) return binding; + if (binding instanceof VariableBinding) + return binding; compilationUnitScope().recordSimpleReference(compoundName[0]); - if (!binding.isValidBinding()) return binding; + if (!binding.isValidBinding()) + return binding; int length = compoundName.length; int currentIndex = 1; - foundType : if (binding instanceof PackageBinding) { + foundType: if (binding instanceof PackageBinding) { PackageBinding packageBinding = (PackageBinding) binding; while (currentIndex < length) { - compilationUnitScope().recordReference(packageBinding.compoundName, compoundName[currentIndex]); - binding = packageBinding.getTypeOrPackage(compoundName[currentIndex++]); + compilationUnitScope() + .recordReference(packageBinding.compoundName, + compoundName[currentIndex]); + binding = packageBinding + .getTypeOrPackage(compoundName[currentIndex++]); invocationSite.setFieldIndex(currentIndex); if (binding == null) { if (currentIndex == length) - // must be a type if its the last name, otherwise we have no idea if its a package or type - return new ProblemReferenceBinding( - CharOperation.subarray(compoundName, 0, currentIndex), - NotFound); + // must be a type if its the last name, otherwise we + // have no idea if its a package or type + return new ProblemReferenceBinding(CharOperation + .subarray(compoundName, 0, currentIndex), + NotFound); else - return new ProblemBinding( - CharOperation.subarray(compoundName, 0, currentIndex), - NotFound); + return new ProblemBinding(CharOperation.subarray( + compoundName, 0, currentIndex), NotFound); } if (binding instanceof ReferenceBinding) { if (!binding.isValidBinding()) - return new ProblemReferenceBinding( - CharOperation.subarray(compoundName, 0, currentIndex), - binding.problemId()); + return new ProblemReferenceBinding(CharOperation + .subarray(compoundName, 0, currentIndex), + binding.problemId()); if (!((ReferenceBinding) binding).canBeSeenBy(this)) - return new ProblemReferenceBinding( - CharOperation.subarray(compoundName, 0, currentIndex), - (ReferenceBinding)binding, - NotVisible); + return new ProblemReferenceBinding(CharOperation + .subarray(compoundName, 0, currentIndex), + (ReferenceBinding) binding, NotVisible); break foundType; } packageBinding = (PackageBinding) binding; } // It is illegal to request a PACKAGE from this method. - return new ProblemReferenceBinding( - CharOperation.subarray(compoundName, 0, currentIndex), - NotFound); + return new ProblemReferenceBinding(CharOperation.subarray( + compoundName, 0, currentIndex), NotFound); } // know binding is now a ReferenceBinding @@ -437,41 +461,39 @@ public class BlockScope extends Scope { char[] nextName = compoundName[currentIndex++]; invocationSite.setFieldIndex(currentIndex); invocationSite.setActualReceiverType(typeBinding); - if ((mask & FIELD) != 0 && (binding = findField(typeBinding, nextName, invocationSite)) != null) { + if ((mask & FIELD) != 0 + && (binding = findField(typeBinding, nextName, + invocationSite)) != null) { if (!binding.isValidBinding()) return new ProblemFieldBinding( - ((FieldBinding) binding).declaringClass, - CharOperation.subarray(compoundName, 0, currentIndex), - binding.problemId()); + ((FieldBinding) binding).declaringClass, + CharOperation.subarray(compoundName, 0, + currentIndex), binding.problemId()); break; // binding is now a field } if ((binding = findMemberType(nextName, typeBinding)) == null) { if ((mask & FIELD) != 0) { - return new ProblemBinding( - CharOperation.subarray(compoundName, 0, currentIndex), - typeBinding, - NotFound); + return new ProblemBinding(CharOperation.subarray( + compoundName, 0, currentIndex), typeBinding, + NotFound); } else { - return new ProblemReferenceBinding( - CharOperation.subarray(compoundName, 0, currentIndex), - typeBinding, - NotFound); + return new ProblemReferenceBinding(CharOperation.subarray( + compoundName, 0, currentIndex), typeBinding, + NotFound); } } if (!binding.isValidBinding()) - return new ProblemReferenceBinding( - CharOperation.subarray(compoundName, 0, currentIndex), - binding.problemId()); + return new ProblemReferenceBinding(CharOperation.subarray( + compoundName, 0, currentIndex), binding.problemId()); } if ((mask & FIELD) != 0 && (binding instanceof FieldBinding)) { // was looking for a field and found a field FieldBinding field = (FieldBinding) binding; if (!field.isStatic()) - return new ProblemFieldBinding( - field.declaringClass, - CharOperation.subarray(compoundName, 0, currentIndex), - NonStaticReferenceInStaticContext); + return new ProblemFieldBinding(field.declaringClass, + CharOperation.subarray(compoundName, 0, currentIndex), + NonStaticReferenceInStaticContext); return binding; } if ((mask & TYPE) != 0 && (binding instanceof ReferenceBinding)) { @@ -479,83 +501,78 @@ public class BlockScope extends Scope { return binding; } - // handle the case when a field or type was asked for but we resolved the compoundName to a type or field - return new ProblemBinding( - CharOperation.subarray(compoundName, 0, currentIndex), - NotFound); + // handle the case when a field or type was asked for but we resolved + // the compoundName to a type or field + return new ProblemBinding(CharOperation.subarray(compoundName, 0, + currentIndex), NotFound); } // Added for code assist... NOT Public API - public final Binding getBinding( - char[][] compoundName, - InvocationSite invocationSite) { + public final Binding getBinding(char[][] compoundName, + InvocationSite invocationSite) { int currentIndex = 0; int length = compoundName.length; - Binding binding = - getBinding( - compoundName[currentIndex++], - VARIABLE | TYPE | PACKAGE, - invocationSite); + Binding binding = getBinding(compoundName[currentIndex++], VARIABLE + | TYPE | PACKAGE, invocationSite); if (!binding.isValidBinding()) return binding; - foundType : if (binding instanceof PackageBinding) { + foundType: if (binding instanceof PackageBinding) { while (currentIndex < length) { PackageBinding packageBinding = (PackageBinding) binding; - binding = packageBinding.getTypeOrPackage(compoundName[currentIndex++]); + binding = packageBinding + .getTypeOrPackage(compoundName[currentIndex++]); if (binding == null) { if (currentIndex == length) - // must be a type if its the last name, otherwise we have no idea if its a package or type - return new ProblemReferenceBinding( - CharOperation.subarray(compoundName, 0, currentIndex), - NotFound); + // must be a type if its the last name, otherwise we + // have no idea if its a package or type + return new ProblemReferenceBinding(CharOperation + .subarray(compoundName, 0, currentIndex), + NotFound); else - return new ProblemBinding( - CharOperation.subarray(compoundName, 0, currentIndex), - NotFound); + return new ProblemBinding(CharOperation.subarray( + compoundName, 0, currentIndex), NotFound); } if (binding instanceof ReferenceBinding) { if (!binding.isValidBinding()) - return new ProblemReferenceBinding( - CharOperation.subarray(compoundName, 0, currentIndex), - binding.problemId()); + return new ProblemReferenceBinding(CharOperation + .subarray(compoundName, 0, currentIndex), + binding.problemId()); if (!((ReferenceBinding) binding).canBeSeenBy(this)) - return new ProblemReferenceBinding( - CharOperation.subarray(compoundName, 0, currentIndex), - (ReferenceBinding)binding, - NotVisible); + return new ProblemReferenceBinding(CharOperation + .subarray(compoundName, 0, currentIndex), + (ReferenceBinding) binding, NotVisible); break foundType; } } return binding; } - foundField : if (binding instanceof ReferenceBinding) { + foundField: if (binding instanceof ReferenceBinding) { while (currentIndex < length) { ReferenceBinding typeBinding = (ReferenceBinding) binding; char[] nextName = compoundName[currentIndex++]; if ((binding = findField(typeBinding, nextName, invocationSite)) != null) { if (!binding.isValidBinding()) return new ProblemFieldBinding( - ((FieldBinding) binding).declaringClass, - CharOperation.subarray(compoundName, 0, currentIndex), - binding.problemId()); + ((FieldBinding) binding).declaringClass, + CharOperation.subarray(compoundName, 0, + currentIndex), binding.problemId()); if (!((FieldBinding) binding).isStatic()) return new ProblemFieldBinding( - ((FieldBinding) binding).declaringClass, - CharOperation.subarray(compoundName, 0, currentIndex), - NonStaticReferenceInStaticContext); + ((FieldBinding) binding).declaringClass, + CharOperation.subarray(compoundName, 0, + currentIndex), + NonStaticReferenceInStaticContext); break foundField; // binding is now a field } if ((binding = findMemberType(nextName, typeBinding)) == null) - return new ProblemBinding( - CharOperation.subarray(compoundName, 0, currentIndex), - typeBinding, - NotFound); + return new ProblemBinding(CharOperation.subarray( + compoundName, 0, currentIndex), typeBinding, + NotFound); if (!binding.isValidBinding()) - return new ProblemReferenceBinding( - CharOperation.subarray(compoundName, 0, currentIndex), - binding.problemId()); + return new ProblemReferenceBinding(CharOperation.subarray( + compoundName, 0, currentIndex), binding.problemId()); } return binding; } @@ -564,51 +581,52 @@ public class BlockScope extends Scope { while (currentIndex < length) { TypeBinding typeBinding = variableBinding.type; if (typeBinding == null) - return new ProblemFieldBinding( - null, - CharOperation.subarray(compoundName, 0, currentIndex + 1), - NotFound); - variableBinding = - findField(typeBinding, compoundName[currentIndex++], invocationSite); + return new ProblemFieldBinding(null, CharOperation.subarray( + compoundName, 0, currentIndex + 1), NotFound); + variableBinding = findField(typeBinding, + compoundName[currentIndex++], invocationSite); if (variableBinding == null) - return new ProblemFieldBinding( - null, - CharOperation.subarray(compoundName, 0, currentIndex), - NotFound); + return new ProblemFieldBinding(null, CharOperation.subarray( + compoundName, 0, currentIndex), NotFound); if (!variableBinding.isValidBinding()) return variableBinding; } return variableBinding; } - /* API - * - * Answer the binding that corresponds to the argument name. - * flag is a mask of the following values VARIABLE (= FIELD or LOCAL), TYPE, PACKAGE. - * Only bindings corresponding to the mask can be answered. - * - * For example, getBinding("foo", VARIABLE, site) will answer - * the binding for the field or local named "foo" (or an error binding if none exists). - * If a type named "foo" exists, it will not be detected (and an error binding will be answered) - * - * The VARIABLE mask has precedence over the TYPE mask. - * - * If the VARIABLE mask is not set, neither fields nor locals will be looked for. - * - * InvocationSite implements: - * isSuperAccess(); this is used to determine if the discovered field is visible. - * - * Limitations: cannot request FIELD independently of LOCAL, or vice versa + /* + * API + * + * Answer the binding that corresponds to the argument name. flag is a mask + * of the following values VARIABLE (= FIELD or LOCAL), TYPE, PACKAGE. Only + * bindings corresponding to the mask can be answered. + * + * For example, getBinding("foo", VARIABLE, site) will answer the binding + * for the field or local named "foo" (or an error binding if none exists). + * If a type named "foo" exists, it will not be detected (and an error + * binding will be answered) + * + * The VARIABLE mask has precedence over the TYPE mask. + * + * If the VARIABLE mask is not set, neither fields nor locals will be looked + * for. + * + * InvocationSite implements: isSuperAccess(); this is used to determine if + * the discovered field is visible. + * + * Limitations: cannot request FIELD independently of LOCAL, or vice versa */ - public Binding getBinding(char[] name, int mask, InvocationSite invocationSite) { - + public Binding getBinding(char[] name, int mask, + InvocationSite invocationSite) { + Binding binding = null; FieldBinding problemField = null; if ((mask & VARIABLE) != 0) { if (this.kind == BLOCK_SCOPE || this.kind == METHOD_SCOPE) { LocalVariableBinding variableBinding = findVariable(name); // looks in this scope only - if (variableBinding != null) return variableBinding; + if (variableBinding != null) + return variableBinding; } boolean insideStaticContext = false; @@ -620,127 +638,147 @@ public class BlockScope extends Scope { } FieldBinding foundField = null; - // can be a problem field which is answered if a valid field is not found + // can be a problem field which is answered if a valid field is not + // found ProblemFieldBinding foundInsideProblem = null; // inside Constructor call or inside static context Scope scope = parent; int depth = 0; int foundDepth = 0; ReferenceBinding foundActualReceiverType = null; - done : while (true) { // done when a COMPILATION_UNIT_SCOPE is found + done: while (true) { // done when a COMPILATION_UNIT_SCOPE is + // found switch (scope.kind) { - case METHOD_SCOPE : - MethodScope methodScope = (MethodScope) scope; - insideStaticContext |= methodScope.isStatic; - insideConstructorCall |= methodScope.isConstructorCall; - // Fall through... could duplicate the code below to save a cast - questionable optimization - case BLOCK_SCOPE : - LocalVariableBinding variableBinding = ((BlockScope) scope).findVariable(name); - // looks in this scope only - if (variableBinding != null) { - if (foundField != null && foundField.isValidBinding()) - return new ProblemFieldBinding( - foundField.declaringClass, - name, + case METHOD_SCOPE: + MethodScope methodScope = (MethodScope) scope; + insideStaticContext |= methodScope.isStatic; + insideConstructorCall |= methodScope.isConstructorCall; + // Fall through... could duplicate the code below to save a + // cast - questionable optimization + case BLOCK_SCOPE: + LocalVariableBinding variableBinding = ((BlockScope) scope) + .findVariable(name); + // looks in this scope only + if (variableBinding != null) { + if (foundField != null && foundField.isValidBinding()) + return new ProblemFieldBinding( + foundField.declaringClass, name, InheritedNameHidesEnclosingName); - if (depth > 0) - invocationSite.setDepth(depth); - return variableBinding; - } - break; - case CLASS_SCOPE : - ClassScope classScope = (ClassScope) scope; - SourceTypeBinding enclosingType = classScope.referenceContext.binding; - FieldBinding fieldBinding = - classScope.findField(enclosingType, name, invocationSite); - // Use next line instead if willing to enable protected access accross inner types - // FieldBinding fieldBinding = findField(enclosingType, name, invocationSite); - if (fieldBinding != null) { // skip it if we did not find anything - if (fieldBinding.problemId() == Ambiguous) { - if (foundField == null || foundField.problemId() == NotVisible) - // supercedes any potential InheritedNameHidesEnclosingName problem - return fieldBinding; - else - // make the user qualify the field, likely wants the first inherited field (javac generates an ambiguous error instead) - return new ProblemFieldBinding( - fieldBinding.declaringClass, - name, + if (depth > 0) + invocationSite.setDepth(depth); + return variableBinding; + } + break; + case CLASS_SCOPE: + ClassScope classScope = (ClassScope) scope; + SourceTypeBinding enclosingType = classScope.referenceContext.binding; + FieldBinding fieldBinding = classScope.findField( + enclosingType, name, invocationSite); + // Use next line instead if willing to enable protected + // access accross inner types + // FieldBinding fieldBinding = findField(enclosingType, + // name, invocationSite); + if (fieldBinding != null) { // skip it if we did not find + // anything + if (fieldBinding.problemId() == Ambiguous) { + if (foundField == null + || foundField.problemId() == NotVisible) + // supercedes any potential + // InheritedNameHidesEnclosingName problem + return fieldBinding; + else + // make the user qualify the field, likely wants + // the first inherited field (javac generates an + // ambiguous error instead) + return new ProblemFieldBinding( + fieldBinding.declaringClass, name, InheritedNameHidesEnclosingName); - } + } - ProblemFieldBinding insideProblem = null; - if (fieldBinding.isValidBinding()) { - if (!fieldBinding.isStatic()) { - if (insideConstructorCall) { - insideProblem = - new ProblemFieldBinding( - fieldBinding.declaringClass, - name, - NonStaticReferenceInConstructorInvocation); - } else if (insideStaticContext) { - insideProblem = - new ProblemFieldBinding( - fieldBinding.declaringClass, - name, - NonStaticReferenceInStaticContext); - } + ProblemFieldBinding insideProblem = null; + if (fieldBinding.isValidBinding()) { + if (!fieldBinding.isStatic()) { + if (insideConstructorCall) { + insideProblem = new ProblemFieldBinding( + fieldBinding.declaringClass, name, + NonStaticReferenceInConstructorInvocation); + } else if (insideStaticContext) { + insideProblem = new ProblemFieldBinding( + fieldBinding.declaringClass, name, + NonStaticReferenceInStaticContext); } -// if (enclosingType == fieldBinding.declaringClass -// || environment().options.complianceLevel >= CompilerOptions.JDK1_4){ -// // found a valid field in the 'immediate' scope (ie. not inherited) -// // OR in 1.4 mode (inherited shadows enclosing) -// if (foundField == null) { -// if (depth > 0){ -// invocationSite.setDepth(depth); -// invocationSite.setActualReceiverType(enclosingType); -// } -// // return the fieldBinding if it is not declared in a superclass of the scope's binding (that is, inherited) -// return insideProblem == null ? fieldBinding : insideProblem; -// } -// if (foundField.isValidBinding()) -// // if a valid field was found, complain when another is found in an 'immediate' enclosing type (that is, not inherited) -// if (foundField.declaringClass != fieldBinding.declaringClass) -// // ie. have we found the same field - do not trust field identity yet -// return new ProblemFieldBinding( -// fieldBinding.declaringClass, -// name, -// InheritedNameHidesEnclosingName); -// } } + // if (enclosingType == fieldBinding.declaringClass + // || environment().options.complianceLevel >= + // CompilerOptions.JDK1_4){ + // // found a valid field in the 'immediate' scope + // (ie. not inherited) + // // OR in 1.4 mode (inherited shadows enclosing) + // if (foundField == null) { + // if (depth > 0){ + // invocationSite.setDepth(depth); + // invocationSite.setActualReceiverType(enclosingType); + // } + // // return the fieldBinding if it is not declared + // in a superclass of the scope's binding (that is, + // inherited) + // return insideProblem == null ? fieldBinding : + // insideProblem; + // } + // if (foundField.isValidBinding()) + // // if a valid field was found, complain when + // another is found in an 'immediate' enclosing type + // (that is, not inherited) + // if (foundField.declaringClass != + // fieldBinding.declaringClass) + // // ie. have we found the same field - do not + // trust field identity yet + // return new ProblemFieldBinding( + // fieldBinding.declaringClass, + // name, + // InheritedNameHidesEnclosingName); + // } + } - if (foundField == null - || (foundField.problemId() == NotVisible - && fieldBinding.problemId() != NotVisible)) { - // only remember the fieldBinding if its the first one found or the previous one was not visible & fieldBinding is... - foundDepth = depth; - foundActualReceiverType = enclosingType; - foundInsideProblem = insideProblem; - foundField = fieldBinding; - } + if (foundField == null + || (foundField.problemId() == NotVisible && fieldBinding + .problemId() != NotVisible)) { + // only remember the fieldBinding if its the first + // one found or the previous one was not visible & + // fieldBinding is... + foundDepth = depth; + foundActualReceiverType = enclosingType; + foundInsideProblem = insideProblem; + foundField = fieldBinding; } - depth++; - insideStaticContext |= enclosingType.isStatic(); - // 1EX5I8Z - accessing outer fields within a constructor call is permitted - // in order to do so, we change the flag as we exit from the type, not the method - // itself, because the class scope is used to retrieve the fields. - MethodScope enclosingMethodScope = scope.methodScope(); - insideConstructorCall = - enclosingMethodScope == null ? false : enclosingMethodScope.isConstructorCall; - break; - case COMPILATION_UNIT_SCOPE : - break done; + } + depth++; + insideStaticContext |= enclosingType.isStatic(); + // 1EX5I8Z - accessing outer fields within a constructor + // call is permitted + // in order to do so, we change the flag as we exit from the + // type, not the method + // itself, because the class scope is used to retrieve the + // fields. + MethodScope enclosingMethodScope = scope.methodScope(); + insideConstructorCall = enclosingMethodScope == null ? false + : enclosingMethodScope.isConstructorCall; + break; + case COMPILATION_UNIT_SCOPE: + break done; } scope = scope.parent; } - if (foundInsideProblem != null){ + if (foundInsideProblem != null) { return foundInsideProblem; } if (foundField != null) { - if (foundField.isValidBinding()){ - if (foundDepth > 0){ + if (foundField.isValidBinding()) { + if (foundDepth > 0) { invocationSite.setDepth(foundDepth); - invocationSite.setActualReceiverType(foundActualReceiverType); + invocationSite + .setActualReceiverType(foundActualReceiverType); } return foundField; } @@ -752,7 +790,8 @@ public class BlockScope extends Scope { if ((mask & TYPE) != 0) { if ((binding = getBaseType(name)) != null) return binding; - binding = getTypeOrPackage(name, (mask & PACKAGE) == 0 ? TYPE : TYPE | PACKAGE); + binding = getTypeOrPackage(name, (mask & PACKAGE) == 0 ? TYPE + : TYPE | PACKAGE); if (binding.isValidBinding() || mask == TYPE) return binding; // answer the problem type binding if we are only looking for a type @@ -767,34 +806,34 @@ public class BlockScope extends Scope { return new ProblemBinding(name, enclosingSourceType(), NotFound); } - /* API - * - * Answer the constructor binding that corresponds to receiverType, argumentTypes. - * - * InvocationSite implements - * isSuperAccess(); this is used to determine if the discovered constructor is visible. - * - * If no visible constructor is discovered, an error binding is answered. + /* + * API + * + * Answer the constructor binding that corresponds to receiverType, + * argumentTypes. + * + * InvocationSite implements isSuperAccess(); this is used to determine if + * the discovered constructor is visible. + * + * If no visible constructor is discovered, an error binding is answered. */ - public MethodBinding getConstructor( - ReferenceBinding receiverType, - TypeBinding[] argumentTypes, - InvocationSite invocationSite) { + public MethodBinding getConstructor(ReferenceBinding receiverType, + TypeBinding[] argumentTypes, InvocationSite invocationSite) { compilationUnitScope().recordTypeReference(receiverType); compilationUnitScope().recordTypeReferences(argumentTypes); - MethodBinding methodBinding = receiverType.getExactConstructor(argumentTypes); + MethodBinding methodBinding = receiverType + .getExactConstructor(argumentTypes); if (methodBinding != null) { if (methodBinding.canBeSeenBy(invocationSite, this)) return methodBinding; } - MethodBinding[] methods = - receiverType.getMethods(ConstructorDeclaration.ConstantPoolName); + MethodBinding[] methods = receiverType + .getMethods(ConstructorDeclaration.ConstantPoolName); if (methods == NoMethods) { return new ProblemMethodBinding( - ConstructorDeclaration.ConstantPoolName, - argumentTypes, - NotFound); + ConstructorDeclaration.ConstantPoolName, argumentTypes, + NotFound); } MethodBinding[] compatible = new MethodBinding[methods.length]; int compatibleIndex = 0; @@ -803,9 +842,8 @@ public class BlockScope extends Scope { compatible[compatibleIndex++] = methods[i]; if (compatibleIndex == 0) return new ProblemMethodBinding( - ConstructorDeclaration.ConstantPoolName, - argumentTypes, - NotFound); + ConstructorDeclaration.ConstantPoolName, argumentTypes, + NotFound); // need a more descriptive error... cannot convert from X to Y MethodBinding[] visible = new MethodBinding[compatibleIndex]; @@ -818,53 +856,52 @@ public class BlockScope extends Scope { if (visibleIndex == 1) return visible[0]; if (visibleIndex == 0) - return new ProblemMethodBinding( - compatible[0], - ConstructorDeclaration.ConstantPoolName, - compatible[0].parameters, - NotVisible); + return new ProblemMethodBinding(compatible[0], + ConstructorDeclaration.ConstantPoolName, + compatible[0].parameters, NotVisible); return mostSpecificClassMethodBinding(visible, visibleIndex); } /* - * This retrieves the argument that maps to an enclosing instance of the suitable type, - * if not found then answers nil -- do not create one - * - * #implicitThis : the implicit this will be ok - * #((arg) this$n) : available as a constructor arg - * #((arg) this$n ... this$p) : available as as a constructor arg + a sequence of fields - * #((fieldDescr) this$n ... this$p) : available as a sequence of fields - * nil : not found - * - * Note that this algorithm should answer the shortest possible sequence when - * shortcuts are available: - * this$0 . this$0 . this$0 - * instead of - * this$2 . this$1 . this$0 . this$1 . this$0 - * thus the code generation will be more compact and runtime faster + * This retrieves the argument that maps to an enclosing instance of the + * suitable type, if not found then answers nil -- do not create one + * + * #implicitThis : the implicit this will be ok #((arg) this$n) : available + * as a constructor arg #((arg) this$n ... this$p) : available as as a + * constructor arg + a sequence of fields #((fieldDescr) this$n ... this$p) : + * available as a sequence of fields nil : not found + * + * Note that this algorithm should answer the shortest possible sequence + * when shortcuts are available: this$0 . this$0 . this$0 instead of this$2 . + * this$1 . this$0 . this$1 . this$0 thus the code generation will be more + * compact and runtime faster */ - public VariableBinding[] getEmulationPath(LocalVariableBinding outerLocalVariable) { + public VariableBinding[] getEmulationPath( + LocalVariableBinding outerLocalVariable) { MethodScope currentMethodScope = this.methodScope(); SourceTypeBinding sourceType = currentMethodScope.enclosingSourceType(); // identity check - if (currentMethodScope == outerLocalVariable.declaringScope.methodScope()) { + if (currentMethodScope == outerLocalVariable.declaringScope + .methodScope()) { return new VariableBinding[] { outerLocalVariable }; // implicit this is good enough } // use synthetic constructor arguments if possible if (currentMethodScope.isInsideInitializerOrConstructor() - && (sourceType.isNestedType())) { + && (sourceType.isNestedType())) { SyntheticArgumentBinding syntheticArg; - if ((syntheticArg = ((NestedTypeBinding) sourceType).getSyntheticArgument(outerLocalVariable)) != null) { + if ((syntheticArg = ((NestedTypeBinding) sourceType) + .getSyntheticArgument(outerLocalVariable)) != null) { return new VariableBinding[] { syntheticArg }; } } // use a synthetic field then if (!currentMethodScope.isStatic) { FieldBinding syntheticField; - if ((syntheticField = sourceType.getSyntheticField(outerLocalVariable)) != null) { + if ((syntheticField = sourceType + .getSyntheticField(outerLocalVariable)) != null) { return new VariableBinding[] { syntheticField }; } } @@ -872,51 +909,57 @@ public class BlockScope extends Scope { } /* - * This retrieves the argument that maps to an enclosing instance of the suitable type, - * if not found then answers nil -- do not create one - * - * #implicitThis : the implicit this will be ok - * #((arg) this$n) : available as a constructor arg - * #((arg) this$n access$m... access$p) : available as as a constructor arg + a sequence of synthetic accessors to synthetic fields - * #((fieldDescr) this$n access#m... access$p) : available as a first synthetic field + a sequence of synthetic accessors to synthetic fields - * nil : not found - * jls 15.9.2 + * This retrieves the argument that maps to an enclosing instance of the + * suitable type, if not found then answers nil -- do not create one + * + * #implicitThis : the implicit this will be ok #((arg) this$n) : available + * as a constructor arg #((arg) this$n access$m... access$p) : available as + * as a constructor arg + a sequence of synthetic accessors to synthetic + * fields #((fieldDescr) this$n access#m... access$p) : available as a first + * synthetic field + a sequence of synthetic accessors to synthetic fields + * nil : not found jls 15.9.2 */ - public Object[] getEmulationPath( - ReferenceBinding targetEnclosingType, - boolean onlyExactMatch, - boolean ignoreEnclosingArgInConstructorCall) { - //TODO: (philippe) investigate why exactly test76 fails if ignoreEnclosingArgInConstructorCall is always false + public Object[] getEmulationPath(ReferenceBinding targetEnclosingType, + boolean onlyExactMatch, boolean ignoreEnclosingArgInConstructorCall) { + // TODO: (philippe) investigate why exactly test76 fails if + // ignoreEnclosingArgInConstructorCall is always false MethodScope currentMethodScope = this.methodScope(); SourceTypeBinding sourceType = currentMethodScope.enclosingSourceType(); // identity check - if (!currentMethodScope.isStatic - && (!currentMethodScope.isConstructorCall || ignoreEnclosingArgInConstructorCall) - && (sourceType == targetEnclosingType - || (!onlyExactMatch && targetEnclosingType.isSuperclassOf(sourceType)))) { + if (!currentMethodScope.isStatic + && (!currentMethodScope.isConstructorCall || ignoreEnclosingArgInConstructorCall) + && (sourceType == targetEnclosingType || (!onlyExactMatch && targetEnclosingType + .isSuperclassOf(sourceType)))) { if (currentMethodScope.isConstructorCall) { return NoEnclosingInstanceInConstructorCall; } - if (currentMethodScope.isStatic){ + if (currentMethodScope.isStatic) { return NoEnclosingInstanceInStaticContext; } return EmulationPathToImplicitThis; // implicit this is good enough } - if (!sourceType.isNestedType() || sourceType.isStatic()) { // no emulation from within non-inner types + if (!sourceType.isNestedType() || sourceType.isStatic()) { // no + // emulation + // from + // within + // non-inner + // types if (currentMethodScope.isConstructorCall) { return NoEnclosingInstanceInConstructorCall; } - if (currentMethodScope.isStatic){ - return NoEnclosingInstanceInStaticContext; - } + if (currentMethodScope.isStatic) { + return NoEnclosingInstanceInStaticContext; + } return null; } - boolean insideConstructor = currentMethodScope.isInsideInitializerOrConstructor(); + boolean insideConstructor = currentMethodScope + .isInsideInitializerOrConstructor(); // use synthetic constructor arguments if possible if (insideConstructor) { SyntheticArgumentBinding syntheticArg; - if ((syntheticArg = ((NestedTypeBinding) sourceType).getSyntheticArgument(targetEnclosingType, onlyExactMatch)) != null) { + if ((syntheticArg = ((NestedTypeBinding) sourceType) + .getSyntheticArgument(targetEnclosingType, onlyExactMatch)) != null) { return new Object[] { syntheticArg }; } } @@ -925,257 +968,298 @@ public class BlockScope extends Scope { if (currentMethodScope.isStatic) { return NoEnclosingInstanceInStaticContext; } - FieldBinding syntheticField = sourceType.getSyntheticField(targetEnclosingType, onlyExactMatch); + FieldBinding syntheticField = sourceType.getSyntheticField( + targetEnclosingType, onlyExactMatch); if (syntheticField != null) { - if (currentMethodScope.isConstructorCall){ + if (currentMethodScope.isConstructorCall) { return NoEnclosingInstanceInConstructorCall; } return new Object[] { syntheticField }; } - // could be reached through a sequence of enclosing instance link (nested members) + // could be reached through a sequence of enclosing instance link + // (nested members) Object[] path = new Object[2]; // probably at least 2 of them ReferenceBinding currentType = sourceType.enclosingType(); if (insideConstructor) { - path[0] = ((NestedTypeBinding) sourceType).getSyntheticArgument((SourceTypeBinding) currentType, onlyExactMatch); + path[0] = ((NestedTypeBinding) sourceType).getSyntheticArgument( + (SourceTypeBinding) currentType, onlyExactMatch); } else { - if (currentMethodScope.isConstructorCall){ + if (currentMethodScope.isConstructorCall) { return NoEnclosingInstanceInConstructorCall; } - path[0] = sourceType.getSyntheticField((SourceTypeBinding) currentType, onlyExactMatch); + path[0] = sourceType.getSyntheticField( + (SourceTypeBinding) currentType, onlyExactMatch); } if (path[0] != null) { // keep accumulating - + int count = 1; ReferenceBinding currentEnclosingType; while ((currentEnclosingType = currentType.enclosingType()) != null) { - //done? + // done? if (currentType == targetEnclosingType - || (!onlyExactMatch && targetEnclosingType.isSuperclassOf(currentType))) break; + || (!onlyExactMatch && targetEnclosingType + .isSuperclassOf(currentType))) + break; if (currentMethodScope != null) { - currentMethodScope = currentMethodScope.enclosingMethodScope(); - if (currentMethodScope != null && currentMethodScope.isConstructorCall){ + currentMethodScope = currentMethodScope + .enclosingMethodScope(); + if (currentMethodScope != null + && currentMethodScope.isConstructorCall) { return NoEnclosingInstanceInConstructorCall; } - if (currentMethodScope != null && currentMethodScope.isStatic){ + if (currentMethodScope != null + && currentMethodScope.isStatic) { return NoEnclosingInstanceInStaticContext; } } - - syntheticField = ((NestedTypeBinding) currentType).getSyntheticField((SourceTypeBinding) currentEnclosingType, onlyExactMatch); - if (syntheticField == null) break; + + syntheticField = ((NestedTypeBinding) currentType) + .getSyntheticField( + (SourceTypeBinding) currentEnclosingType, + onlyExactMatch); + if (syntheticField == null) + break; // append inside the path if (count == path.length) { - System.arraycopy(path, 0, (path = new Object[count + 1]), 0, count); + System.arraycopy(path, 0, (path = new Object[count + 1]), + 0, count); } - // private access emulation is necessary since synthetic field is private - path[count++] = ((SourceTypeBinding) syntheticField.declaringClass).addSyntheticMethod(syntheticField, true); + // private access emulation is necessary since synthetic field + // is private + path[count++] = ((SourceTypeBinding) syntheticField.declaringClass) + .addSyntheticMethod(syntheticField, true); currentType = currentEnclosingType; } if (currentType == targetEnclosingType - || (!onlyExactMatch && targetEnclosingType.isSuperclassOf(currentType))) { + || (!onlyExactMatch && targetEnclosingType + .isSuperclassOf(currentType))) { return path; } } return null; } - /* API - * - * Answer the field binding that corresponds to fieldName. - * Start the lookup at the receiverType. - * InvocationSite implements - * isSuperAccess(); this is used to determine if the discovered field is visible. - * Only fields defined by the receiverType or its supertypes are answered; - * a field of an enclosing type will not be found using this API. - * - * If no visible field is discovered, an error binding is answered. + /* + * API + * + * Answer the field binding that corresponds to fieldName. Start the lookup + * at the receiverType. InvocationSite implements isSuperAccess(); this is + * used to determine if the discovered field is visible. Only fields defined + * by the receiverType or its supertypes are answered; a field of an + * enclosing type will not be found using this API. + * + * If no visible field is discovered, an error binding is answered. */ - public FieldBinding getField( - TypeBinding receiverType, - char[] fieldName, - InvocationSite invocationSite) { + public FieldBinding getField(TypeBinding receiverType, char[] fieldName, + InvocationSite invocationSite) { FieldBinding field = findField(receiverType, fieldName, invocationSite); if (field == null) return new ProblemFieldBinding( - receiverType instanceof ReferenceBinding - ? (ReferenceBinding) receiverType - : null, - fieldName, - NotFound); + receiverType instanceof ReferenceBinding ? (ReferenceBinding) receiverType + : null, fieldName, NotFound); else return field; } - /* API - * - * Answer the method binding that corresponds to selector, argumentTypes. - * Start the lookup at the enclosing type of the receiver. - * InvocationSite implements - * isSuperAccess(); this is used to determine if the discovered method is visible. - * setDepth(int); this is used to record the depth of the discovered method - * relative to the enclosing type of the receiver. (If the method is defined - * in the enclosing type of the receiver, the depth is 0; in the next enclosing - * type, the depth is 1; and so on + /* + * API + * + * Answer the method binding that corresponds to selector, argumentTypes. + * Start the lookup at the enclosing type of the receiver. InvocationSite + * implements isSuperAccess(); this is used to determine if the discovered + * method is visible. setDepth(int); this is used to record the depth of the + * discovered method relative to the enclosing type of the receiver. (If the + * method is defined in the enclosing type of the receiver, the depth is 0; + * in the next enclosing type, the depth is 1; and so on * - * If no visible method is discovered, an error binding is answered. + * If no visible method is discovered, an error binding is answered. */ - public MethodBinding getImplicitMethod( - char[] selector, - TypeBinding[] argumentTypes, - InvocationSite invocationSite) { + public MethodBinding getImplicitMethod(char[] selector, + TypeBinding[] argumentTypes, InvocationSite invocationSite) { boolean insideStaticContext = false; boolean insideConstructorCall = false; MethodBinding foundMethod = null; ProblemMethodBinding foundFuzzyProblem = null; - // the weird method lookup case (matches method name in scope, then arg types, then visibility) + // the weird method lookup case (matches method name in scope, then arg + // types, then visibility) ProblemMethodBinding foundInsideProblem = null; // inside Constructor call or inside static context Scope scope = this; int depth = 0; - done : while (true) { // done when a COMPILATION_UNIT_SCOPE is found + done: while (true) { // done when a COMPILATION_UNIT_SCOPE is found switch (scope.kind) { - case METHOD_SCOPE : - MethodScope methodScope = (MethodScope) scope; - insideStaticContext |= methodScope.isStatic; - insideConstructorCall |= methodScope.isConstructorCall; - break; - case CLASS_SCOPE : - ClassScope classScope = (ClassScope) scope; - SourceTypeBinding receiverType = classScope.referenceContext.binding; - boolean isExactMatch = true; - // retrieve an exact visible match (if possible) - MethodBinding methodBinding = - (foundMethod == null) - ? classScope.findExactMethod( - receiverType, - selector, - argumentTypes, + case METHOD_SCOPE: + MethodScope methodScope = (MethodScope) scope; + insideStaticContext |= methodScope.isStatic; + insideConstructorCall |= methodScope.isConstructorCall; + break; + case CLASS_SCOPE: + ClassScope classScope = (ClassScope) scope; + SourceTypeBinding receiverType = classScope.referenceContext.binding; + boolean isExactMatch = true; + // retrieve an exact visible match (if possible) + MethodBinding methodBinding = (foundMethod == null) ? classScope + .findExactMethod(receiverType, selector, argumentTypes, invocationSite) - : classScope.findExactMethod( - receiverType, - foundMethod.selector, - foundMethod.parameters, + : classScope.findExactMethod(receiverType, + foundMethod.selector, foundMethod.parameters, invocationSite); - // ? findExactMethod(receiverType, selector, argumentTypes, invocationSite) - // : findExactMethod(receiverType, foundMethod.selector, foundMethod.parameters, invocationSite); - if (methodBinding == null) { - // answers closest approximation, may not check argumentTypes or visibility - isExactMatch = false; - methodBinding = - classScope.findMethod(receiverType, selector, argumentTypes, invocationSite); - // methodBinding = findMethod(receiverType, selector, argumentTypes, invocationSite); - } - if (methodBinding != null) { // skip it if we did not find anything - if (methodBinding.problemId() == Ambiguous) { - if (foundMethod == null || foundMethod.problemId() == NotVisible) - // supercedes any potential InheritedNameHidesEnclosingName problem - return methodBinding; - else - // make the user qualify the method, likely wants the first inherited method (javac generates an ambiguous error instead) - return new ProblemMethodBinding( - selector, + // ? findExactMethod(receiverType, selector, argumentTypes, + // invocationSite) + // : findExactMethod(receiverType, foundMethod.selector, + // foundMethod.parameters, invocationSite); + if (methodBinding == null) { + // answers closest approximation, may not check + // argumentTypes or visibility + isExactMatch = false; + methodBinding = classScope.findMethod(receiverType, + selector, argumentTypes, invocationSite); + // methodBinding = findMethod(receiverType, selector, + // argumentTypes, invocationSite); + } + if (methodBinding != null) { // skip it if we did not find + // anything + if (methodBinding.problemId() == Ambiguous) { + if (foundMethod == null + || foundMethod.problemId() == NotVisible) + // supercedes any potential + // InheritedNameHidesEnclosingName problem + return methodBinding; + else + // make the user qualify the method, likely wants + // the first inherited method (javac generates an + // ambiguous error instead) + return new ProblemMethodBinding(selector, argumentTypes, InheritedNameHidesEnclosingName); - } + } - ProblemMethodBinding fuzzyProblem = null; - ProblemMethodBinding insideProblem = null; - if (methodBinding.isValidBinding()) { - if (!isExactMatch) { - if (!areParametersAssignable(methodBinding.parameters, argumentTypes)) { - if (foundMethod == null || foundMethod.problemId() == NotVisible){ - // inherited mismatch is reported directly, not looking at enclosing matches - return new ProblemMethodBinding(methodBinding, selector, argumentTypes, NotFound); - } - // make the user qualify the method, likely wants the first inherited method (javac generates an ambiguous error instead) - fuzzyProblem = new ProblemMethodBinding(selector, methodBinding.parameters, InheritedNameHidesEnclosingName); - - } else if (!methodBinding.canBeSeenBy(receiverType, invocationSite, classScope)) { - // using instead of for visibility check does grant all access to innerclass - fuzzyProblem = - new ProblemMethodBinding( - methodBinding, - selector, - methodBinding.parameters, - NotVisible); + ProblemMethodBinding fuzzyProblem = null; + ProblemMethodBinding insideProblem = null; + if (methodBinding.isValidBinding()) { + if (!isExactMatch) { + if (!areParametersAssignable( + methodBinding.parameters, argumentTypes)) { + if (foundMethod == null + || foundMethod.problemId() == NotVisible) { + // inherited mismatch is reported directly, + // not looking at enclosing matches + return new ProblemMethodBinding( + methodBinding, selector, + argumentTypes, NotFound); } + // make the user qualify the method, likely + // wants the first inherited method (javac + // generates an ambiguous error instead) + fuzzyProblem = new ProblemMethodBinding( + selector, methodBinding.parameters, + InheritedNameHidesEnclosingName); + + } else if (!methodBinding.canBeSeenBy(receiverType, + invocationSite, classScope)) { + // using instead of for + // visibility check does grant all access to + // innerclass + fuzzyProblem = new ProblemMethodBinding( + methodBinding, selector, + methodBinding.parameters, NotVisible); } - if (fuzzyProblem == null && !methodBinding.isStatic()) { - if (insideConstructorCall) { - insideProblem = - new ProblemMethodBinding( - methodBinding.selector, - methodBinding.parameters, - NonStaticReferenceInConstructorInvocation); - } else if (insideStaticContext) { - insideProblem = - new ProblemMethodBinding( - methodBinding.selector, - methodBinding.parameters, - NonStaticReferenceInStaticContext); - } + } + if (fuzzyProblem == null && !methodBinding.isStatic()) { + if (insideConstructorCall) { + insideProblem = new ProblemMethodBinding( + methodBinding.selector, + methodBinding.parameters, + NonStaticReferenceInConstructorInvocation); + } else if (insideStaticContext) { + insideProblem = new ProblemMethodBinding( + methodBinding.selector, + methodBinding.parameters, + NonStaticReferenceInStaticContext); } - -// if (receiverType == methodBinding.declaringClass -// || (receiverType.getMethods(selector)) != NoMethods -// || ((fuzzyProblem == null || fuzzyProblem.problemId() != NotVisible) && environment().options.complianceLevel >= CompilerOptions.JDK1_4)){ -// // found a valid method in the 'immediate' scope (ie. not inherited) -// // OR the receiverType implemented a method with the correct name -// // OR in 1.4 mode (inherited visible shadows enclosing) -// if (foundMethod == null) { -// if (depth > 0){ -// invocationSite.setDepth(depth); -// invocationSite.setActualReceiverType(receiverType); -// } -// // return the methodBinding if it is not declared in a superclass of the scope's binding (that is, inherited) -// if (fuzzyProblem != null) -// return fuzzyProblem; -// if (insideProblem != null) -// return insideProblem; -// return methodBinding; -// } -// // if a method was found, complain when another is found in an 'immediate' enclosing type (that is, not inherited) -// // NOTE: Unlike fields, a non visible method hides a visible method -// if (foundMethod.declaringClass != methodBinding.declaringClass) -// // ie. have we found the same method - do not trust field identity yet -// return new ProblemMethodBinding( -// methodBinding.selector, -// methodBinding.parameters, -// InheritedNameHidesEnclosingName); -// } } - if (foundMethod == null - || (foundMethod.problemId() == NotVisible - && methodBinding.problemId() != NotVisible)) { - // only remember the methodBinding if its the first one found or the previous one was not visible & methodBinding is... - // remember that private methods are visible if defined directly by an enclosing class - if (depth > 0){ - invocationSite.setDepth(depth); - invocationSite.setActualReceiverType(receiverType); - } - foundFuzzyProblem = fuzzyProblem; - foundInsideProblem = insideProblem; - if (fuzzyProblem == null) - foundMethod = methodBinding; // only keep it if no error was found + // if (receiverType == methodBinding.declaringClass + // || (receiverType.getMethods(selector)) != NoMethods + // || ((fuzzyProblem == null || fuzzyProblem.problemId() + // != NotVisible) && + // environment().options.complianceLevel >= + // CompilerOptions.JDK1_4)){ + // // found a valid method in the 'immediate' scope (ie. + // not inherited) + // // OR the receiverType implemented a method with the + // correct name + // // OR in 1.4 mode (inherited visible shadows + // enclosing) + // if (foundMethod == null) { + // if (depth > 0){ + // invocationSite.setDepth(depth); + // invocationSite.setActualReceiverType(receiverType); + // } + // // return the methodBinding if it is not declared in + // a superclass of the scope's binding (that is, + // inherited) + // if (fuzzyProblem != null) + // return fuzzyProblem; + // if (insideProblem != null) + // return insideProblem; + // return methodBinding; + // } + // // if a method was found, complain when another is + // found in an 'immediate' enclosing type (that is, not + // inherited) + // // NOTE: Unlike fields, a non visible method hides a + // visible method + // if (foundMethod.declaringClass != + // methodBinding.declaringClass) + // // ie. have we found the same method - do not trust + // field identity yet + // return new ProblemMethodBinding( + // methodBinding.selector, + // methodBinding.parameters, + // InheritedNameHidesEnclosingName); + // } + } + + if (foundMethod == null + || (foundMethod.problemId() == NotVisible && methodBinding + .problemId() != NotVisible)) { + // only remember the methodBinding if its the first one + // found or the previous one was not visible & + // methodBinding is... + // remember that private methods are visible if defined + // directly by an enclosing class + if (depth > 0) { + invocationSite.setDepth(depth); + invocationSite.setActualReceiverType(receiverType); } + foundFuzzyProblem = fuzzyProblem; + foundInsideProblem = insideProblem; + if (fuzzyProblem == null) + foundMethod = methodBinding; // only keep it if + // no error was + // found } - depth++; - insideStaticContext |= receiverType.isStatic(); - // 1EX5I8Z - accessing outer fields within a constructor call is permitted - // in order to do so, we change the flag as we exit from the type, not the method - // itself, because the class scope is used to retrieve the fields. - MethodScope enclosingMethodScope = scope.methodScope(); - insideConstructorCall = - enclosingMethodScope == null ? false : enclosingMethodScope.isConstructorCall; - break; - case COMPILATION_UNIT_SCOPE : - break done; + } + depth++; + insideStaticContext |= receiverType.isStatic(); + // 1EX5I8Z - accessing outer fields within a constructor call is + // permitted + // in order to do so, we change the flag as we exit from the + // type, not the method + // itself, because the class scope is used to retrieve the + // fields. + MethodScope enclosingMethodScope = scope.methodScope(); + insideConstructorCall = enclosingMethodScope == null ? false + : enclosingMethodScope.isConstructorCall; + break; + case COMPILATION_UNIT_SCOPE: + break done; } scope = scope.parent; } @@ -1189,81 +1273,75 @@ public class BlockScope extends Scope { return new ProblemMethodBinding(selector, argumentTypes, NotFound); } - /* API - * - * Answer the method binding that corresponds to selector, argumentTypes. - * Start the lookup at the receiverType. - * InvocationSite implements - * isSuperAccess(); this is used to determine if the discovered method is visible. - * - * Only methods defined by the receiverType or its supertypes are answered; - * use getImplicitMethod() to discover methods of enclosing types. - * - * If no visible method is discovered, an error binding is answered. + /* + * API + * + * Answer the method binding that corresponds to selector, argumentTypes. + * Start the lookup at the receiverType. InvocationSite implements + * isSuperAccess(); this is used to determine if the discovered method is + * visible. + * + * Only methods defined by the receiverType or its supertypes are answered; + * use getImplicitMethod() to discover methods of enclosing types. + * + * If no visible method is discovered, an error binding is answered. */ - public MethodBinding getMethod( - TypeBinding receiverType, - char[] selector, - TypeBinding[] argumentTypes, - InvocationSite invocationSite) { + public MethodBinding getMethod(TypeBinding receiverType, char[] selector, + TypeBinding[] argumentTypes, InvocationSite invocationSite) { if (receiverType.isArrayType()) - return findMethodForArray( - (ArrayBinding) receiverType, - selector, - argumentTypes, - invocationSite); + return findMethodForArray((ArrayBinding) receiverType, selector, + argumentTypes, invocationSite); if (receiverType.isBaseType()) return new ProblemMethodBinding(selector, argumentTypes, NotFound); ReferenceBinding currentType = (ReferenceBinding) receiverType; if (!currentType.canBeSeenBy(this)) - return new ProblemMethodBinding(selector, argumentTypes, ReceiverTypeNotVisible); + return new ProblemMethodBinding(selector, argumentTypes, + ReceiverTypeNotVisible); // retrieve an exact visible match (if possible) - MethodBinding methodBinding = - findExactMethod(currentType, selector, argumentTypes, invocationSite); + MethodBinding methodBinding = findExactMethod(currentType, selector, + argumentTypes, invocationSite); if (methodBinding != null) return methodBinding; - // answers closest approximation, may not check argumentTypes or visibility - methodBinding = - findMethod(currentType, selector, argumentTypes, invocationSite); + // answers closest approximation, may not check argumentTypes or + // visibility + methodBinding = findMethod(currentType, selector, argumentTypes, + invocationSite); if (methodBinding == null) return new ProblemMethodBinding(selector, argumentTypes, NotFound); if (methodBinding.isValidBinding()) { - if (!areParametersAssignable(methodBinding.parameters, argumentTypes)) - return new ProblemMethodBinding( - methodBinding, - selector, - argumentTypes, - NotFound); + if (!areParametersAssignable(methodBinding.parameters, + argumentTypes)) + return new ProblemMethodBinding(methodBinding, selector, + argumentTypes, NotFound); if (!methodBinding.canBeSeenBy(currentType, invocationSite, this)) - return new ProblemMethodBinding( - methodBinding, - selector, - methodBinding.parameters, - NotVisible); + return new ProblemMethodBinding(methodBinding, selector, + methodBinding.parameters, NotVisible); } return methodBinding; } public int maxShiftedOffset() { int max = -1; - if (this.shiftScopes != null){ - for (int i = 0, length = this.shiftScopes.length; i < length; i++){ + if (this.shiftScopes != null) { + for (int i = 0, length = this.shiftScopes.length; i < length; i++) { int subMaxOffset = this.shiftScopes[i].maxOffset; - if (subMaxOffset > max) max = subMaxOffset; + if (subMaxOffset > max) + max = subMaxOffset; } } return max; } - - /* Answer the problem reporter to use for raising new problems. - * + + /* + * Answer the problem reporter to use for raising new problems. + * * Note that as a side-effect, this updates the current reference context - * (unit, type or method) in case the problem handler decides it is necessary - * to abort. + * (unit, type or method) in case the problem handler decides it is + * necessary to abort. */ public ProblemReporter problemReporter() { @@ -1271,28 +1349,34 @@ public class BlockScope extends Scope { } /* - * Code responsible to request some more emulation work inside the invocation type, so as to supply - * correct synthetic arguments to any allocation of the target type. + * Code responsible to request some more emulation work inside the + * invocation type, so as to supply correct synthetic arguments to any + * allocation of the target type. */ - public void propagateInnerEmulation(ReferenceBinding targetType, boolean isEnclosingInstanceSupplied) { + public void propagateInnerEmulation(ReferenceBinding targetType, + boolean isEnclosingInstanceSupplied) { + + // no need to propagate enclosing instances, they got eagerly allocated + // already. - // no need to propagate enclosing instances, they got eagerly allocated already. - SyntheticArgumentBinding[] syntheticArguments; if ((syntheticArguments = targetType.syntheticOuterLocalVariables()) != null) { for (int i = 0, max = syntheticArguments.length; i < max; i++) { SyntheticArgumentBinding syntheticArg = syntheticArguments[i]; - // need to filter out the one that could match a supplied enclosing instance - if (!(isEnclosingInstanceSupplied - && (syntheticArg.type == targetType.enclosingType()))) { - this.emulateOuterAccess(syntheticArg.actualOuterLocalVariable); + // need to filter out the one that could match a supplied + // enclosing instance + if (!(isEnclosingInstanceSupplied && (syntheticArg.type == targetType + .enclosingType()))) { + this + .emulateOuterAccess(syntheticArg.actualOuterLocalVariable); } } } } - /* Answer the reference type of this scope. - * + /* + * Answer the reference type of this scope. + * * It is the nearest enclosing type of this scope. */ public TypeDeclaration referenceType() { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ClassScope.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ClassScope.java index 4fd2e45..256ad1e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ClassScope.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ClassScope.java @@ -22,15 +22,17 @@ import net.sourceforge.phpdt.internal.compiler.util.HashtableOfObject; public class ClassScope extends Scope { public TypeDeclaration referenceContext; - + public ClassScope(Scope parent, TypeDeclaration context) { super(CLASS_SCOPE, parent); this.referenceContext = context; } - - void buildAnonymousTypeBinding(SourceTypeBinding enclosingType, ReferenceBinding supertype) { - - LocalTypeBinding anonymousType = buildLocalType(enclosingType, enclosingType.fPackage); + + void buildAnonymousTypeBinding(SourceTypeBinding enclosingType, + ReferenceBinding supertype) { + + LocalTypeBinding anonymousType = buildLocalType(enclosingType, + enclosingType.fPackage); SourceTypeBinding sourceType = referenceContext.binding; if (supertype.isInterface()) { @@ -45,7 +47,7 @@ public class ClassScope extends Scope { anonymousType.faultInTypesForFieldsAndMethods(); sourceType.verifyMethods(environment().methodVerifier()); } - + private void buildFields() { if (referenceContext.fields == null) { referenceContext.binding.fields = NoFields; @@ -59,7 +61,8 @@ public class ClassScope extends Scope { if (fields[i].isField()) count++; - // iterate the field declarations to create the bindings, lose all duplicates + // iterate the field declarations to create the bindings, lose all + // duplicates FieldBinding[] fieldBindings = new FieldBinding[count]; HashtableOfObject knownFieldNames = new HashtableOfObject(count); boolean duplicate = false; @@ -68,27 +71,37 @@ public class ClassScope extends Scope { FieldDeclaration field = fields[i]; if (!field.isField()) { if (referenceContext.binding.isInterface()) - problemReporter().interfaceCannotHaveInitializers(referenceContext.binding, field); + problemReporter().interfaceCannotHaveInitializers( + referenceContext.binding, field); } else { - FieldBinding fieldBinding = new FieldBinding(field, null, referenceContext.binding); + FieldBinding fieldBinding = new FieldBinding(field, null, + referenceContext.binding); // field's type will be resolved when needed for top level types checkAndSetModifiersForField(fieldBinding, field); if (knownFieldNames.containsKey(field.name)) { duplicate = true; - FieldBinding previousBinding = (FieldBinding) knownFieldNames.get(field.name); + FieldBinding previousBinding = (FieldBinding) knownFieldNames + .get(field.name); if (previousBinding != null) { for (int f = 0; f < i; f++) { FieldDeclaration previousField = fields[f]; if (previousField.binding == previousBinding) { - problemReporter().duplicateFieldInType(referenceContext.binding, previousField); + problemReporter() + .duplicateFieldInType( + referenceContext.binding, + previousField); previousField.binding = null; break; } } } - knownFieldNames.put(field.name, null); // ensure that the duplicate field is found & removed - problemReporter().duplicateFieldInType(referenceContext.binding, field); + knownFieldNames.put(field.name, null); // ensure that the + // duplicate field + // is found & + // removed + problemReporter().duplicateFieldInType( + referenceContext.binding, field); field.binding = null; } else { knownFieldNames.put(field.name, fieldBinding); @@ -100,7 +113,8 @@ public class ClassScope extends Scope { } // remove duplicate fields if (duplicate) { - FieldBinding[] newFieldBindings = new FieldBinding[knownFieldNames.size() - 1]; + FieldBinding[] newFieldBindings = new FieldBinding[knownFieldNames + .size() - 1]; // we know we'll be removing at least 1 duplicate name size = count; count = 0; @@ -113,31 +127,33 @@ public class ClassScope extends Scope { } if (count != fieldBindings.length) - System.arraycopy(fieldBindings, 0, fieldBindings = new FieldBinding[count], 0, count); + System.arraycopy(fieldBindings, 0, + fieldBindings = new FieldBinding[count], 0, count); for (int i = 0; i < count; i++) fieldBindings[i].id = i; referenceContext.binding.fields = fieldBindings; } - + void buildFieldsAndMethods() { buildFields(); buildMethods(); SourceTypeBinding sourceType = referenceContext.binding; if (sourceType.isMemberType() && !sourceType.isLocalType()) - ((MemberTypeBinding) sourceType).checkSyntheticArgsAndFields(); + ((MemberTypeBinding) sourceType).checkSyntheticArgsAndFields(); ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) - ((SourceTypeBinding) memberTypes[i]).scope.buildFieldsAndMethods(); + ((SourceTypeBinding) memberTypes[i]).scope.buildFieldsAndMethods(); } - - private LocalTypeBinding buildLocalType( - SourceTypeBinding enclosingType, - PackageBinding packageBinding) { + + private LocalTypeBinding buildLocalType(SourceTypeBinding enclosingType, + PackageBinding packageBinding) { referenceContext.scope = this; - referenceContext.staticInitializerScope = new MethodScope(this, referenceContext, true); - referenceContext.initializerScope = new MethodScope(this, referenceContext, false); + referenceContext.staticInitializerScope = new MethodScope(this, + referenceContext, true); + referenceContext.initializerScope = new MethodScope(this, + referenceContext, false); // build the binding or the local type LocalTypeBinding localType = new LocalTypeBinding(this, enclosingType); @@ -150,51 +166,62 @@ public class ClassScope extends Scope { int size = referenceContext.memberTypes.length; memberTypeBindings = new ReferenceBinding[size]; int count = 0; - nextMember : for (int i = 0; i < size; i++) { + nextMember: for (int i = 0; i < size; i++) { TypeDeclaration memberContext = referenceContext.memberTypes[i]; if (memberContext.isInterface()) { - problemReporter().nestedClassCannotDeclareInterface(memberContext); + problemReporter().nestedClassCannotDeclareInterface( + memberContext); continue nextMember; } ReferenceBinding type = localType; - // check that the member does not conflict with an enclosing type + // check that the member does not conflict with an enclosing + // type do { - if (CharOperation.equals(type.sourceName, memberContext.name)) { + if (CharOperation.equals(type.sourceName, + memberContext.name)) { problemReporter().hidingEnclosingType(memberContext); continue nextMember; } type = type.enclosingType(); } while (type != null); - // check the member type does not conflict with another sibling member type + // check the member type does not conflict with another sibling + // member type for (int j = 0; j < i; j++) { - if (CharOperation.equals(referenceContext.memberTypes[j].name, memberContext.name)) { + if (CharOperation.equals( + referenceContext.memberTypes[j].name, + memberContext.name)) { problemReporter().duplicateNestedType(memberContext); continue nextMember; } } - ClassScope memberScope = new ClassScope(this, referenceContext.memberTypes[i]); - LocalTypeBinding memberBinding = memberScope.buildLocalType(localType, packageBinding); + ClassScope memberScope = new ClassScope(this, + referenceContext.memberTypes[i]); + LocalTypeBinding memberBinding = memberScope.buildLocalType( + localType, packageBinding); memberBinding.setAsMemberType(); memberTypeBindings[count++] = memberBinding; } if (count != size) - System.arraycopy(memberTypeBindings, 0, memberTypeBindings = new ReferenceBinding[count], 0, count); + System.arraycopy(memberTypeBindings, 0, + memberTypeBindings = new ReferenceBinding[count], 0, + count); } localType.memberTypes = memberTypeBindings; return localType; } - + void buildLocalTypeBinding(SourceTypeBinding enclosingType) { - LocalTypeBinding localType = buildLocalType(enclosingType, enclosingType.fPackage); + LocalTypeBinding localType = buildLocalType(enclosingType, + enclosingType.fPackage); connectTypeHierarchy(); buildFieldsAndMethods(); localType.faultInTypesForFieldsAndMethods(); referenceContext.binding.verifyMethods(environment().methodVerifier()); } - + private void buildMethods() { if (referenceContext.methods == null) { referenceContext.binding.methods = NoMethods; @@ -211,37 +238,51 @@ public class ClassScope extends Scope { break; } } - MethodBinding[] methodBindings = new MethodBinding[clinitIndex == -1 ? size : size - 1]; + MethodBinding[] methodBindings = new MethodBinding[clinitIndex == -1 ? size + : size - 1]; int count = 0; for (int i = 0; i < size; i++) { if (i != clinitIndex) { MethodScope scope = new MethodScope(this, methods[i], false); MethodBinding methodBinding = scope.createMethod(methods[i]); - if (methodBinding != null) // is null if binding could not be created + if (methodBinding != null) // is null if binding could not be + // created methodBindings[count++] = methodBinding; } } if (count != methodBindings.length) - System.arraycopy(methodBindings, 0, methodBindings = new MethodBinding[count], 0, count); + System.arraycopy(methodBindings, 0, + methodBindings = new MethodBinding[count], 0, count); referenceContext.binding.methods = methodBindings; - referenceContext.binding.modifiers |= AccUnresolved; // until methods() is sent + referenceContext.binding.modifiers |= AccUnresolved; // until + // methods() is + // sent } - SourceTypeBinding buildType(SourceTypeBinding enclosingType, PackageBinding packageBinding) { + + SourceTypeBinding buildType(SourceTypeBinding enclosingType, + PackageBinding packageBinding) { // provide the typeDeclaration with needed scopes referenceContext.scope = this; - referenceContext.staticInitializerScope = new MethodScope(this, referenceContext, true); - referenceContext.initializerScope = new MethodScope(this, referenceContext, false); + referenceContext.staticInitializerScope = new MethodScope(this, + referenceContext, true); + referenceContext.initializerScope = new MethodScope(this, + referenceContext, false); if (enclosingType == null) { - char[][] className = CharOperation.arrayConcat(packageBinding.compoundName, referenceContext.name); - referenceContext.binding = new SourceTypeBinding(className, packageBinding, this); + char[][] className = CharOperation.arrayConcat( + packageBinding.compoundName, referenceContext.name); + referenceContext.binding = new SourceTypeBinding(className, + packageBinding, this); } else { - char[][] className = CharOperation.deepCopy(enclosingType.compoundName); - className[className.length - 1] = - CharOperation.concat(className[className.length - 1], referenceContext.name, '$'); - referenceContext.binding = new MemberTypeBinding(className, this, enclosingType); + char[][] className = CharOperation + .deepCopy(enclosingType.compoundName); + className[className.length - 1] = CharOperation + .concat(className[className.length - 1], + referenceContext.name, '$'); + referenceContext.binding = new MemberTypeBinding(className, this, + enclosingType); } SourceTypeBinding sourceType = referenceContext.binding; @@ -254,42 +295,49 @@ public class ClassScope extends Scope { int size = referenceContext.memberTypes.length; memberTypeBindings = new ReferenceBinding[size]; int count = 0; - nextMember : for (int i = 0; i < size; i++) { + nextMember: for (int i = 0; i < size; i++) { TypeDeclaration memberContext = referenceContext.memberTypes[i]; - if (memberContext.isInterface() - && sourceType.isNestedType() - && sourceType.isClass() - && !sourceType.isStatic()) { - problemReporter().nestedClassCannotDeclareInterface(memberContext); + if (memberContext.isInterface() && sourceType.isNestedType() + && sourceType.isClass() && !sourceType.isStatic()) { + problemReporter().nestedClassCannotDeclareInterface( + memberContext); continue nextMember; } ReferenceBinding type = sourceType; - // check that the member does not conflict with an enclosing type + // check that the member does not conflict with an enclosing + // type do { - if (CharOperation.equals(type.sourceName, memberContext.name)) { + if (CharOperation.equals(type.sourceName, + memberContext.name)) { problemReporter().hidingEnclosingType(memberContext); continue nextMember; } type = type.enclosingType(); } while (type != null); - // check that the member type does not conflict with another sibling member type + // check that the member type does not conflict with another + // sibling member type for (int j = 0; j < i; j++) { - if (CharOperation.equals(referenceContext.memberTypes[j].name, memberContext.name)) { + if (CharOperation.equals( + referenceContext.memberTypes[j].name, + memberContext.name)) { problemReporter().duplicateNestedType(memberContext); continue nextMember; } } ClassScope memberScope = new ClassScope(this, memberContext); - memberTypeBindings[count++] = memberScope.buildType(sourceType, packageBinding); + memberTypeBindings[count++] = memberScope.buildType(sourceType, + packageBinding); } if (count != size) - System.arraycopy(memberTypeBindings, 0, memberTypeBindings = new ReferenceBinding[count], 0, count); + System.arraycopy(memberTypeBindings, 0, + memberTypeBindings = new ReferenceBinding[count], 0, + count); } sourceType.memberTypes = memberTypeBindings; return sourceType; } - + private void checkAndSetModifiers() { SourceTypeBinding sourceType = referenceContext.binding; int modifiers = sourceType.modifiers; @@ -298,11 +346,11 @@ public class ClassScope extends Scope { ReferenceBinding enclosingType = sourceType.enclosingType(); boolean isMemberType = sourceType.isMemberType(); - + if (isMemberType) { // checks for member types before local types to catch local members -// if (enclosingType.isStrictfp()) -// modifiers |= AccStrictfp; + // if (enclosingType.isStrictfp()) + // modifiers |= AccStrictfp; if (enclosingType.isDeprecated()) modifiers |= AccDeprecatedImplicitly; if (enclosingType.isInterface()) @@ -313,15 +361,15 @@ public class ClassScope extends Scope { ReferenceContext refContext = methodScope().referenceContext; if (refContext instanceof TypeDeclaration) { ReferenceBinding type = ((TypeDeclaration) refContext).binding; -// if (type.isStrictfp()) -// modifiers |= AccStrictfp; + // if (type.isStrictfp()) + // modifiers |= AccStrictfp; if (type.isDeprecated()) modifiers |= AccDeprecatedImplicitly; } else { MethodBinding method = ((AbstractMethodDeclaration) refContext).binding; - if (method != null){ -// if (method.isStrictfp()) -// modifiers |= AccStrictfp; + if (method != null) { + // if (method.isStrictfp()) + // modifiers |= AccStrictfp; if (method.isDeprecated()) modifiers |= AccDeprecatedImplicitly; } @@ -333,49 +381,62 @@ public class ClassScope extends Scope { if ((realModifiers & AccInterface) != 0) { // detect abnormal cases for interfaces if (isMemberType) { - int unexpectedModifiers = - ~(AccPublic | AccPrivate | AccProtected | AccStatic | AccAbstract | AccInterface );//| AccStrictfp); + int unexpectedModifiers = ~(AccPublic | AccPrivate + | AccProtected | AccStatic | AccAbstract | AccInterface);// | + // AccStrictfp); if ((realModifiers & unexpectedModifiers) != 0) - problemReporter().illegalModifierForMemberInterface(sourceType); + problemReporter().illegalModifierForMemberInterface( + sourceType); /* - } else if (sourceType.isLocalType()) { //interfaces cannot be defined inside a method - int unexpectedModifiers = ~(AccAbstract | AccInterface | AccStrictfp); - if ((realModifiers & unexpectedModifiers) != 0) - problemReporter().illegalModifierForLocalInterface(sourceType); - */ + * } else if (sourceType.isLocalType()) { //interfaces cannot be + * defined inside a method int unexpectedModifiers = + * ~(AccAbstract | AccInterface | AccStrictfp); if + * ((realModifiers & unexpectedModifiers) != 0) + * problemReporter().illegalModifierForLocalInterface(sourceType); + */ } else { - int unexpectedModifiers = ~(AccPublic | AccAbstract | AccInterface);// | AccStrictfp); + int unexpectedModifiers = ~(AccPublic | AccAbstract | AccInterface);// | + // AccStrictfp); if ((realModifiers & unexpectedModifiers) != 0) problemReporter().illegalModifierForInterface(sourceType); } modifiers |= AccAbstract; } else { // detect abnormal cases for types - if (isMemberType) { // includes member types defined inside local types - int unexpectedModifiers = - ~(AccPublic | AccPrivate | AccProtected | AccStatic | AccAbstract | AccFinal);// | AccStrictfp); + if (isMemberType) { // includes member types defined inside local + // types + int unexpectedModifiers = ~(AccPublic | AccPrivate + | AccProtected | AccStatic | AccAbstract | AccFinal);// | + // AccStrictfp); if ((realModifiers & unexpectedModifiers) != 0) problemReporter().illegalModifierForMemberClass(sourceType); } else if (sourceType.isLocalType()) { - int unexpectedModifiers = ~(AccAbstract | AccFinal);// | AccStrictfp); + int unexpectedModifiers = ~(AccAbstract | AccFinal);// | + // AccStrictfp); if ((realModifiers & unexpectedModifiers) != 0) problemReporter().illegalModifierForLocalClass(sourceType); } else { - int unexpectedModifiers = ~(AccPublic | AccAbstract | AccFinal);// | AccStrictfp); + int unexpectedModifiers = ~(AccPublic | AccAbstract | AccFinal);// | + // AccStrictfp); if ((realModifiers & unexpectedModifiers) != 0) problemReporter().illegalModifierForClass(sourceType); } // check that Final and Abstract are not set together if ((realModifiers & (AccFinal | AccAbstract)) == (AccFinal | AccAbstract)) - problemReporter().illegalModifierCombinationFinalAbstractForClass(sourceType); + problemReporter() + .illegalModifierCombinationFinalAbstractForClass( + sourceType); } if (isMemberType) { - // test visibility modifiers inconsistency, isolate the accessors bits + // test visibility modifiers inconsistency, isolate the accessors + // bits if (enclosingType.isInterface()) { if ((realModifiers & (AccProtected | AccPrivate)) != 0) { - problemReporter().illegalVisibilityModifierForInterfaceMemberType(sourceType); + problemReporter() + .illegalVisibilityModifierForInterfaceMemberType( + sourceType); // need to keep the less restrictive if ((realModifiers & AccProtected) != 0) @@ -384,9 +445,12 @@ public class ClassScope extends Scope { modifiers ^= AccPrivate; } } else { - int accessorBits = realModifiers & (AccPublic | AccProtected | AccPrivate); + int accessorBits = realModifiers + & (AccPublic | AccProtected | AccPrivate); if ((accessorBits & (accessorBits - 1)) > 1) { - problemReporter().illegalVisibilityModifierCombinationForMemberType(sourceType); + problemReporter() + .illegalVisibilityModifierCombinationForMemberType( + sourceType); // need to keep the less restrictive if ((accessorBits & AccPublic) != 0) { @@ -407,25 +471,30 @@ public class ClassScope extends Scope { modifiers |= AccStatic; } else { if (!enclosingType.isStatic()) - // error the enclosing type of a static field must be static or a top-level type - problemReporter().illegalStaticModifierForMemberType(sourceType); + // error the enclosing type of a static field must be static + // or a top-level type + problemReporter().illegalStaticModifierForMemberType( + sourceType); } } sourceType.modifiers = modifiers; } - - /* This method checks the modifiers of a field. - * - * 9.3 & 8.3 - * Need to integrate the check for the final modifiers for nested types - * - * Note : A scope is accessible by : fieldBinding.declaringClass.scope - */ - private void checkAndSetModifiersForField(FieldBinding fieldBinding, FieldDeclaration fieldDecl) { + + /* + * This method checks the modifiers of a field. + * + * 9.3 & 8.3 Need to integrate the check for the final modifiers for nested + * types + * + * Note : A scope is accessible by : fieldBinding.declaringClass.scope + */ + private void checkAndSetModifiersForField(FieldBinding fieldBinding, + FieldDeclaration fieldDecl) { int modifiers = fieldBinding.modifiers; if ((modifiers & AccAlternateModifierProblem) != 0) - problemReporter().duplicateModifierForField(fieldBinding.declaringClass, fieldDecl); + problemReporter().duplicateModifierForField( + fieldBinding.declaringClass, fieldDecl); if (fieldBinding.declaringClass.isInterface()) { int expectedValue = AccPublic | AccStatic | AccFinal; @@ -434,23 +503,25 @@ public class ClassScope extends Scope { // and then check that they are the only ones if ((modifiers & AccJustFlag) != expectedValue) - problemReporter().illegalModifierForInterfaceField(fieldBinding.declaringClass, fieldDecl); + problemReporter().illegalModifierForInterfaceField( + fieldBinding.declaringClass, fieldDecl); fieldBinding.modifiers = modifiers; return; } // after this point, tests on the 16 bits reserved. int realModifiers = modifiers & AccJustFlag; - int unexpectedModifiers = - ~(AccPublic | AccPrivate | AccProtected | AccFinal | AccStatic);// | AccTransient | AccVolatile); + int unexpectedModifiers = ~(AccPublic | AccPrivate | AccProtected + | AccFinal | AccStatic);// | AccTransient | AccVolatile); if ((realModifiers & unexpectedModifiers) != 0) - problemReporter().illegalModifierForField(fieldBinding.declaringClass, fieldDecl); + problemReporter().illegalModifierForField( + fieldBinding.declaringClass, fieldDecl); - int accessorBits = realModifiers & (AccPublic | AccProtected | AccPrivate); + int accessorBits = realModifiers + & (AccPublic | AccProtected | AccPrivate); if ((accessorBits & (accessorBits - 1)) > 1) { problemReporter().illegalVisibilityModifierCombinationForField( - fieldBinding.declaringClass, - fieldDecl); + fieldBinding.declaringClass, fieldDecl); // need to keep the less restrictive if ((accessorBits & AccPublic) != 0) { @@ -464,26 +535,30 @@ public class ClassScope extends Scope { modifiers ^= AccPrivate; } -// if ((realModifiers & (AccFinal | AccVolatile)) == (AccFinal | AccVolatile)) -// problemReporter().illegalModifierCombinationFinalVolatileForField( -// fieldBinding.declaringClass, -// fieldDecl); + // if ((realModifiers & (AccFinal | AccVolatile)) == (AccFinal | + // AccVolatile)) + // problemReporter().illegalModifierCombinationFinalVolatileForField( + // fieldBinding.declaringClass, + // fieldDecl); if (fieldDecl.initialization == null && (modifiers & AccFinal) != 0) { modifiers |= AccBlankFinal; } fieldBinding.modifiers = modifiers; } - + private void checkForInheritedMemberTypes(SourceTypeBinding sourceType) { - // search up the hierarchy of the sourceType to see if any superType defines a member type - // when no member types are defined, tag the sourceType & each superType with the HasNoMemberTypes bit + // search up the hierarchy of the sourceType to see if any superType + // defines a member type + // when no member types are defined, tag the sourceType & each superType + // with the HasNoMemberTypes bit ReferenceBinding currentType = sourceType; ReferenceBinding[][] interfacesToVisit = null; int lastPosition = -1; do { if ((currentType.tagBits & HasNoMemberTypes) != 0) - break; // already know it has no inherited member types, can stop looking up + break; // already know it has no inherited member types, can + // stop looking up if (currentType.memberTypes() != NoMemberTypes) return; // has member types ReferenceBinding[] itsInterfaces = currentType.superInterfaces(); @@ -491,40 +566,48 @@ public class ClassScope extends Scope { if (interfacesToVisit == null) interfacesToVisit = new ReferenceBinding[5][]; if (++lastPosition == interfacesToVisit.length) - System.arraycopy( - interfacesToVisit, - 0, - interfacesToVisit = new ReferenceBinding[lastPosition * 2][], - 0, - lastPosition); + System + .arraycopy( + interfacesToVisit, + 0, + interfacesToVisit = new ReferenceBinding[lastPosition * 2][], + 0, lastPosition); interfacesToVisit[lastPosition] = itsInterfaces; } } while ((currentType = currentType.superclass()) != null); boolean hasMembers = false; if (interfacesToVisit != null) { - done : for (int i = 0; i <= lastPosition; i++) { + done: for (int i = 0; i <= lastPosition; i++) { ReferenceBinding[] interfaces = interfacesToVisit[i]; for (int j = 0, length = interfaces.length; j < length; j++) { ReferenceBinding anInterface = interfaces[j]; - if ((anInterface.tagBits & InterfaceVisited) == 0) { // if interface as not already been visited + if ((anInterface.tagBits & InterfaceVisited) == 0) { // if + // interface + // as + // not + // already + // been + // visited anInterface.tagBits |= InterfaceVisited; if ((anInterface.tagBits & HasNoMemberTypes) != 0) - continue; // already know it has no inherited member types + continue; // already know it has no inherited + // member types if (anInterface.memberTypes() != NoMemberTypes) { hasMembers = true; break done; } - ReferenceBinding[] itsInterfaces = anInterface.superInterfaces(); + ReferenceBinding[] itsInterfaces = anInterface + .superInterfaces(); if (itsInterfaces != NoSuperInterfaces) { if (++lastPosition == interfacesToVisit.length) - System.arraycopy( - interfacesToVisit, - 0, - interfacesToVisit = new ReferenceBinding[lastPosition * 2][], - 0, - lastPosition); + System + .arraycopy( + interfacesToVisit, + 0, + interfacesToVisit = new ReferenceBinding[lastPosition * 2][], + 0, lastPosition); interfacesToVisit[lastPosition] = itsInterfaces; } } @@ -548,32 +631,36 @@ public class ClassScope extends Scope { } while ((currentType = currentType.superclass()) != null); } } - + private void connectMemberTypes() { SourceTypeBinding sourceType = referenceContext.binding; if (sourceType.memberTypes != NoMemberTypes) for (int i = 0, size = sourceType.memberTypes.length; i < size; i++) - ((SourceTypeBinding) sourceType.memberTypes[i]).scope.connectTypeHierarchy(); + ((SourceTypeBinding) sourceType.memberTypes[i]).scope + .connectTypeHierarchy(); } + /* - Our current belief based on available JCK tests is: - inherited member types are visible as a potential superclass. - inherited interfaces are not visible when defining a superinterface. - - Error recovery story: - ensure the superclass is set to java.lang.Object if a problem is detected - resolving the superclass. - - Answer false if an error was reported against the sourceType. - */ + * Our current belief based on available JCK tests is: inherited member + * types are visible as a potential superclass. inherited interfaces are not + * visible when defining a superinterface. + * + * Error recovery story: ensure the superclass is set to java.lang.Object if + * a problem is detected resolving the superclass. + * + * Answer false if an error was reported against the sourceType. + */ private boolean connectSuperclass() { SourceTypeBinding sourceType = referenceContext.binding; - if (isJavaLangObject(sourceType)) { // handle the case of redefining java.lang.Object up front + if (isJavaLangObject(sourceType)) { // handle the case of redefining + // java.lang.Object up front sourceType.superclass = null; sourceType.superInterfaces = NoSuperInterfaces; - if (referenceContext.superclass != null || referenceContext.superInterfaces != null) + if (referenceContext.superclass != null + || referenceContext.superInterfaces != null) problemReporter().objectCannotHaveSuperTypes(sourceType); - return true; // do not propagate Object's hierarchy problems down to every subtype + return true; // do not propagate Object's hierarchy problems down + // to every subtype } if (referenceContext.superclass == null) { sourceType.superclass = getJavaLangObject(); @@ -582,11 +669,14 @@ public class ClassScope extends Scope { ReferenceBinding superclass = findSupertype(referenceContext.superclass); if (superclass != null) { // is null if a cycle was detected cycle if (!superclass.isValidBinding()) { - problemReporter().invalidSuperclass(sourceType, referenceContext.superclass, superclass); + problemReporter().invalidSuperclass(sourceType, + referenceContext.superclass, superclass); } else if (superclass.isInterface()) { - problemReporter().superclassMustBeAClass(sourceType, referenceContext.superclass, superclass); + problemReporter().superclassMustBeAClass(sourceType, + referenceContext.superclass, superclass); } else if (superclass.isFinal()) { - problemReporter().classExtendFinalClass(sourceType, referenceContext.superclass, superclass); + problemReporter().classExtendFinalClass(sourceType, + referenceContext.superclass, superclass); } else { // only want to reach here when no errors are reported referenceContext.superclass.resolvedType = superclass; @@ -602,52 +692,54 @@ public class ClassScope extends Scope { } /* - Our current belief based on available JCK 1.3 tests is: - inherited member types are visible as a potential superclass. - inherited interfaces are visible when defining a superinterface. - - Error recovery story: - ensure the superinterfaces contain only valid visible interfaces. - - Answer false if an error was reported against the sourceType. - */ + * Our current belief based on available JCK 1.3 tests is: inherited member + * types are visible as a potential superclass. inherited interfaces are + * visible when defining a superinterface. + * + * Error recovery story: ensure the superinterfaces contain only valid + * visible interfaces. + * + * Answer false if an error was reported against the sourceType. + */ private boolean connectSuperInterfaces() { SourceTypeBinding sourceType = referenceContext.binding; sourceType.superInterfaces = NoSuperInterfaces; if (referenceContext.superInterfaces == null) return true; - if (isJavaLangObject(sourceType)) // already handled the case of redefining java.lang.Object + if (isJavaLangObject(sourceType)) // already handled the case of + // redefining java.lang.Object return true; boolean noProblems = true; int length = referenceContext.superInterfaces.length; ReferenceBinding[] interfaceBindings = new ReferenceBinding[length]; int count = 0; - nextInterface : for (int i = 0; i < length; i++) { + nextInterface: for (int i = 0; i < length; i++) { ReferenceBinding superInterface = findSupertype(referenceContext.superInterfaces[i]); if (superInterface == null) { // detected cycle noProblems = false; continue nextInterface; } if (!superInterface.isValidBinding()) { - problemReporter().invalidSuperinterface( - sourceType, - referenceContext.superInterfaces[i], - superInterface); + problemReporter().invalidSuperinterface(sourceType, + referenceContext.superInterfaces[i], superInterface); sourceType.tagBits |= HierarchyHasProblems; noProblems = false; continue nextInterface; } - // Check for a duplicate interface once the name is resolved, otherwise we may be confused (ie : a.b.I and c.d.I) + // Check for a duplicate interface once the name is resolved, + // otherwise we may be confused (ie : a.b.I and c.d.I) for (int k = 0; k < count; k++) { if (interfaceBindings[k] == superInterface) { // should this be treated as a warning? - problemReporter().duplicateSuperinterface(sourceType, referenceContext, superInterface); + problemReporter().duplicateSuperinterface(sourceType, + referenceContext, superInterface); continue nextInterface; } } if (superInterface.isClass()) { - problemReporter().superinterfaceMustBeAnInterface(sourceType, referenceContext, superInterface); + problemReporter().superinterfaceMustBeAnInterface(sourceType, + referenceContext, superInterface); sourceType.tagBits |= HierarchyHasProblems; noProblems = false; continue nextInterface; @@ -660,12 +752,14 @@ public class ClassScope extends Scope { // hold onto all correctly resolved superinterfaces if (count > 0) { if (count != length) - System.arraycopy(interfaceBindings, 0, interfaceBindings = new ReferenceBinding[count], 0, count); + System.arraycopy(interfaceBindings, 0, + interfaceBindings = new ReferenceBinding[count], 0, + count); sourceType.superInterfaces = interfaceBindings; } return noProblems; } - + void connectTypeHierarchy() { SourceTypeBinding sourceType = referenceContext.binding; if ((sourceType.tagBits & BeginHierarchyCheck) == 0) { @@ -681,15 +775,15 @@ public class ClassScope extends Scope { connectMemberTypes(); checkForInheritedMemberTypes(sourceType); } - + private void connectTypeHierarchyWithoutMembers() { // must ensure the imports are resolved if (parent instanceof CompilationUnitScope) { -// if (((CompilationUnitScope) parent).imports == null) -// ((CompilationUnitScope) parent).checkAndSetImports(); + // if (((CompilationUnitScope) parent).imports == null) + // ((CompilationUnitScope) parent).checkAndSetImports(); } else if (parent instanceof ClassScope) { // ensure that the enclosing type has already been checked - ((ClassScope) parent).connectTypeHierarchyWithoutMembers(); + ((ClassScope) parent).connectTypeHierarchyWithoutMembers(); } // double check that the hierarchy search has not already begun... @@ -706,34 +800,40 @@ public class ClassScope extends Scope { if (noProblems && sourceType.isHierarchyInconsistent()) problemReporter().hierarchyHasProblems(sourceType); } - + // Answer whether a cycle was found between the sourceType & the superType - private boolean detectCycle( - SourceTypeBinding sourceType, - ReferenceBinding superType, - TypeReference reference) { + private boolean detectCycle(SourceTypeBinding sourceType, + ReferenceBinding superType, TypeReference reference) { if (sourceType == superType) { - problemReporter().hierarchyCircularity(sourceType, superType, reference); + problemReporter().hierarchyCircularity(sourceType, superType, + reference); sourceType.tagBits |= HierarchyHasProblems; return true; } if (superType.isBinaryBinding()) { - // force its superclass & superinterfaces to be found... 2 possibilities exist - the source type is included in the hierarchy of: - // - a binary type... this case MUST be caught & reported here - // - another source type... this case is reported against the other source type + // force its superclass & superinterfaces to be found... 2 + // possibilities exist - the source type is included in the + // hierarchy of: + // - a binary type... this case MUST be caught & reported here + // - another source type... this case is reported against the other + // source type boolean hasCycle = false; if (superType.superclass() != null) { if (sourceType == superType.superclass()) { - problemReporter().hierarchyCircularity(sourceType, superType, reference); + problemReporter().hierarchyCircularity(sourceType, + superType, reference); sourceType.tagBits |= HierarchyHasProblems; superType.tagBits |= HierarchyHasProblems; return true; } - hasCycle |= detectCycle(sourceType, superType.superclass(), reference); + hasCycle |= detectCycle(sourceType, superType.superclass(), + reference); if ((superType.superclass().tagBits & HierarchyHasProblems) != 0) { sourceType.tagBits |= HierarchyHasProblems; - superType.tagBits |= HierarchyHasProblems; // propagate down the hierarchy + superType.tagBits |= HierarchyHasProblems; // propagate + // down the + // hierarchy } } @@ -742,7 +842,8 @@ public class ClassScope extends Scope { for (int i = 0, length = itsInterfaces.length; i < length; i++) { ReferenceBinding anInterface = itsInterfaces[i]; if (sourceType == anInterface) { - problemReporter().hierarchyCircularity(sourceType, superType, reference); + problemReporter().hierarchyCircularity(sourceType, + superType, reference); sourceType.tagBits |= HierarchyHasProblems; superType.tagBits |= HierarchyHasProblems; return true; @@ -758,22 +859,26 @@ public class ClassScope extends Scope { } if ((superType.tagBits & EndHierarchyCheck) == 0 - && (superType.tagBits & BeginHierarchyCheck) != 0) { - problemReporter().hierarchyCircularity(sourceType, superType, reference); + && (superType.tagBits & BeginHierarchyCheck) != 0) { + problemReporter().hierarchyCircularity(sourceType, superType, + reference); sourceType.tagBits |= HierarchyHasProblems; superType.tagBits |= HierarchyHasProblems; return true; } if ((superType.tagBits & BeginHierarchyCheck) == 0) - // ensure if this is a source superclass that it has already been checked - ((SourceTypeBinding) superType).scope.connectTypeHierarchyWithoutMembers(); + // ensure if this is a source superclass that it has already been + // checked + ((SourceTypeBinding) superType).scope + .connectTypeHierarchyWithoutMembers(); if ((superType.tagBits & HierarchyHasProblems) != 0) sourceType.tagBits |= HierarchyHasProblems; return false; } - + private ReferenceBinding findSupertype(TypeReference typeReference) { - typeReference.aboutToResolve(this); // allows us to trap completion & selection nodes + typeReference.aboutToResolve(this); // allows us to trap completion & + // selection nodes char[][] compoundName = typeReference.getTypeName(); compilationUnitScope().recordQualifiedReference(compoundName); SourceTypeBinding sourceType = referenceContext.binding; @@ -784,43 +889,54 @@ public class ClassScope extends Scope { // resolve the first name of the compoundName if (CharOperation.equals(compoundName[0], sourceType.sourceName)) { superType = sourceType; - // match against the sourceType even though nested members cannot be supertypes + // match against the sourceType even though nested members cannot be + // supertypes } else { - Binding typeOrPackage = parent.getTypeOrPackage(compoundName[0], TYPE | PACKAGE); + Binding typeOrPackage = parent.getTypeOrPackage(compoundName[0], + TYPE | PACKAGE); if (typeOrPackage == null || !typeOrPackage.isValidBinding()) - return new ProblemReferenceBinding( - compoundName[0], - typeOrPackage == null ? NotFound : typeOrPackage.problemId()); + return new ProblemReferenceBinding(compoundName[0], + typeOrPackage == null ? NotFound : typeOrPackage + .problemId()); boolean checkVisibility = false; for (; n < size; n++) { if (!(typeOrPackage instanceof PackageBinding)) break; PackageBinding packageBinding = (PackageBinding) typeOrPackage; - typeOrPackage = packageBinding.getTypeOrPackage(compoundName[n]); + typeOrPackage = packageBinding + .getTypeOrPackage(compoundName[n]); if (typeOrPackage == null || !typeOrPackage.isValidBinding()) - return new ProblemReferenceBinding( - CharOperation.subarray(compoundName, 0, n + 1), - typeOrPackage == null ? NotFound : typeOrPackage.problemId()); + return new ProblemReferenceBinding(CharOperation.subarray( + compoundName, 0, n + 1), + typeOrPackage == null ? NotFound : typeOrPackage + .problemId()); checkVisibility = true; } // convert to a ReferenceBinding - if (typeOrPackage instanceof PackageBinding) // error, the compoundName is a packageName - return new ProblemReferenceBinding(CharOperation.subarray(compoundName, 0, n), NotFound); + if (typeOrPackage instanceof PackageBinding) // error, the + // compoundName is a + // packageName + return new ProblemReferenceBinding(CharOperation.subarray( + compoundName, 0, n), NotFound); superType = (ReferenceBinding) typeOrPackage; - compilationUnitScope().recordTypeReference(superType); // to record supertypes + compilationUnitScope().recordTypeReference(superType); // to record + // supertypes - if (checkVisibility - && n == size) { // if we're finished and know the final supertype then check visibility + if (checkVisibility && n == size) { // if we're finished and know + // the final supertype then + // check visibility if (!superType.canBeSeenBy(sourceType.fPackage)) // its a toplevel type so just check package access - return new ProblemReferenceBinding(CharOperation.subarray(compoundName, 0, n), superType, NotVisible); + return new ProblemReferenceBinding(CharOperation.subarray( + compoundName, 0, n), superType, NotVisible); } } // at this point we know we have a type but we have to look for cycles while (true) { - // must detect cycles & force connection up the hierarchy... also handle cycles with binary types. + // must detect cycles & force connection up the hierarchy... also + // handle cycles with binary types. // must be guaranteed that the superType knows its entire hierarchy if (detectCycle(sourceType, superType, typeReference)) return null; // cycle error was already reported @@ -832,21 +948,24 @@ public class ClassScope extends Scope { char[] typeName = compoundName[n++]; superType = findMemberType(typeName, superType); if (superType == null) - return new ProblemReferenceBinding(CharOperation.subarray(compoundName, 0, n), NotFound); + return new ProblemReferenceBinding(CharOperation.subarray( + compoundName, 0, n), NotFound); if (!superType.isValidBinding()) { - superType.compoundName = CharOperation.subarray(compoundName, 0, n); + superType.compoundName = CharOperation.subarray(compoundName, + 0, n); return superType; } } return superType; } - /* Answer the problem reporter to use for raising new problems. - * - * Note that as a side-effect, this updates the current reference context - * (unit, type or method) in case the problem handler decides it is necessary - * to abort. - */ + /* + * Answer the problem reporter to use for raising new problems. + * + * Note that as a side-effect, this updates the current reference context + * (unit, type or method) in case the problem handler decides it is + * necessary to abort. + */ public ProblemReporter problemReporter() { MethodScope outerMethodScope; if ((outerMethodScope = outerMostMethodScope()) == null) { @@ -858,18 +977,19 @@ public class ClassScope extends Scope { } } - /* Answer the reference type of this scope. - * It is the nearest enclosing type of this scope. - */ + /* + * Answer the reference type of this scope. It is the nearest enclosing type + * of this scope. + */ public TypeDeclaration referenceType() { return referenceContext; } - + public String toString() { if (referenceContext != null) - return "--- Class Scope ---\n\n" //$NON-NLS-1$ - +referenceContext.binding.toString(); + return "--- Class Scope ---\n\n" //$NON-NLS-1$ + + referenceContext.binding.toString(); else - return "--- Class Scope ---\n\n Binding not initialized" ; //$NON-NLS-1$ + return "--- Class Scope ---\n\n Binding not initialized"; //$NON-NLS-1$ } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/CompilationUnitScope.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/CompilationUnitScope.java index b07c8f8..0e03ef2 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/CompilationUnitScope.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/CompilationUnitScope.java @@ -28,600 +28,701 @@ import org.eclipse.core.runtime.IPath; public class CompilationUnitScope extends Scope { - public LookupEnvironment environment; - public CompilationUnitDeclaration referenceContext; - public char[][] currentPackageName; - public PackageBinding fPackage; - public ImportBinding[] imports; - - public SourceTypeBinding[] topLevelTypes; - - private CompoundNameVector qualifiedReferences; - private SimpleNameVector simpleNameReferences; - private ObjectVector referencedTypes; - - HashtableOfType constantPoolNameUsage; - public HashtableOfObject resolvedSingeTypeImports; - - public CompilationUnitScope(CompilationUnitDeclaration unit, LookupEnvironment environment) { - super(COMPILATION_UNIT_SCOPE, null); - this.environment = environment; - this.referenceContext = unit; - unit.scope = this; -// this.currentPackageName = unit.currentPackage == null ? CharOperation.NO_CHAR_CHAR : unit.currentPackage.tokens; - this.currentPackageName = null; - // if (environment.options.produceReferenceInfo) { - // this.qualifiedReferences = new CompoundNameVector(); - // this.simpleNameReferences = new SimpleNameVector(); - // this.referencedTypes = new ObjectVector(); - // } else { - this.qualifiedReferences = null; // used to test if dependencies should be recorded - this.simpleNameReferences = null; - this.referencedTypes = null; - // } - } - void buildFieldsAndMethods() { - for (int i = 0, length = topLevelTypes.length; i < length; i++) - topLevelTypes[i].scope.buildFieldsAndMethods(); - } - void buildTypeBindings() { - if (referenceContext.compilationResult.compilationUnit != null) { - char[][] expectedPackageName = referenceContext.compilationResult.compilationUnit.getPackageName(); - if (expectedPackageName != null && !CharOperation.equals(currentPackageName, expectedPackageName)) { - - // only report if the unit isn't structurally empty - // if (referenceContext.currentPackage != null - // || referenceContext.types != null - // || referenceContext.imports != null) { - // problemReporter().packageIsNotExpectedPackage(referenceContext); - // } - currentPackageName = expectedPackageName.length == 0 ? CharOperation.NO_CHAR_CHAR : expectedPackageName; - } - } - if (currentPackageName == CharOperation.NO_CHAR_CHAR) { - if ((fPackage = environment.defaultPackage) == null) { - problemReporter().mustSpecifyPackage(referenceContext); - return; - } - } else { - if ((fPackage = environment.createPackage(currentPackageName)) == null) { -// problemReporter().packageCollidesWithType(referenceContext); - return; - } - recordQualifiedReference(currentPackageName); // always dependent on your own package - } - - // Skip typeDeclarations which know of previously reported errors - ArrayList types = referenceContext.types; - int typeLength = (types == null) ? 0 : types.size(); - topLevelTypes = new SourceTypeBinding[typeLength]; - int count = 0; - nextType : for (int i = 0; i < typeLength; i++) { - if (types.get(i) instanceof TypeDeclaration) { - TypeDeclaration typeDecl = (TypeDeclaration) types.get(i); - ReferenceBinding typeBinding = fPackage.getType0(typeDecl.name); - recordSimpleReference(typeDecl.name); // needed to detect collision cases - if (typeBinding != null && !(typeBinding instanceof UnresolvedReferenceBinding)) { - // if a type exists, it must be a valid type - cannot be a NotFound problem type - // unless its an unresolved type which is now being defined - problemReporter().duplicateTypes(referenceContext, typeDecl); - continue nextType; - } - if (fPackage != environment.defaultPackage && fPackage.getPackage(typeDecl.name) != null) { - // if a package exists, it must be a valid package - cannot be a NotFound problem package - problemReporter().typeCollidesWithPackage(referenceContext, typeDecl); - continue nextType; - } - - if ((typeDecl.modifiers & AccPublic) != 0) { - char[] mainTypeName; - if ((mainTypeName = referenceContext.getMainTypeName()) != null - // mainTypeName == null means that implementor of ICompilationUnit decided to return null - && !CharOperation.equals(mainTypeName, typeDecl.name)) { - problemReporter().publicClassMustMatchFileName(referenceContext, typeDecl); - continue nextType; - } - } - - ClassScope child = new ClassScope(this, typeDecl); - SourceTypeBinding type = child.buildType(null, fPackage); - if (type != null) { - topLevelTypes[count++] = type; - } - } - } - - // shrink topLevelTypes... only happens if an error was reported - if (count != topLevelTypes.length) - System.arraycopy(topLevelTypes, 0, topLevelTypes = new SourceTypeBinding[count], 0, count); - } - - void checkAndSetImports() { - // initialize the default imports if necessary... share the default java.lang.* import - if (environment.defaultImports == null) { - Binding importBinding = environment.getTopLevelPackage(JAVA); - if (importBinding != null) - importBinding = ((PackageBinding) importBinding).getTypeOrPackage(JAVA_LANG[1]); - - // abort if java.lang cannot be found... - if (importBinding == null || !importBinding.isValidBinding()) - problemReporter().isClassPathCorrect(JAVA_LANG_OBJECT, referenceCompilationUnit()); - - environment.defaultImports = new ImportBinding[] { new ImportBinding(JAVA_LANG, true, importBinding, null)}; - } - if (referenceContext.imports == null) { - imports = environment.defaultImports; - return; - } - - // allocate the import array, add java.lang.* by default - int numberOfStatements = referenceContext.imports.length; -// int numberOfImports = numberOfStatements + 1; - int numberOfImports = numberOfStatements; -// for (int i = 0; i < numberOfStatements; i++) { -// ImportReference importReference = referenceContext.imports[i]; -// if (importReference.onDemand && CharOperation.equals(JAVA_LANG, importReference.tokens)) { -// numberOfImports--; -// break; -// } -// } - ImportBinding[] resolvedImports = new ImportBinding[numberOfImports]; - resolvedImports[0] = environment.defaultImports[0]; - int index = 1; - - nextImport : for (int i = 0; i < numberOfStatements; i++) { - ImportReference importReference = referenceContext.imports[i]; - IFile file = importReference.getFile(); - SourceTypeBinding typeBinding; -// char[][] compoundName = importReference.tokens; - char[][] compoundName=null; - if (file != null){ - IPath path = file.getProjectRelativePath(); - String[] segs = path.segments(); - compoundName = new char[segs.length][]; - for (int j = 0; j < segs.length; j++) { - compoundName[j] = segs[j].toCharArray(); - } - } - if (compoundName==null) { - continue nextImport; - } - - // skip duplicates or imports of the current package - for (int j = 0; j < index; j++) - if (resolvedImports[j].onDemand == importReference.onDemand) - if (CharOperation.equals(compoundName, resolvedImports[j].compoundName)) - continue nextImport; - if (importReference.onDemand == true) - if (CharOperation.equals(compoundName, currentPackageName)) - continue nextImport; - - if (importReference.onDemand) { - Binding importBinding = findOnDemandImport(compoundName); - if (!importBinding.isValidBinding()) - continue nextImport; // we report all problems in faultInImports() - resolvedImports[index++] = new ImportBinding(compoundName, true, importBinding, importReference); - } else { - resolvedImports[index++] = new ImportBinding(compoundName, false, null, importReference); - } - } - - // shrink resolvedImports... only happens if an error was reported - if (resolvedImports.length > index) - System.arraycopy(resolvedImports, 0, resolvedImports = new ImportBinding[index], 0, index); - imports = resolvedImports; - } - /* - * INTERNAL USE-ONLY - * Innerclasses get their name computed as they are generated, since some may not - * be actually outputed if sitting inside unreachable code. - */ - public char[] computeConstantPoolName(LocalTypeBinding localType) { - if (localType.constantPoolName() != null) { - return localType.constantPoolName(); - } - // delegates to the outermost enclosing classfile, since it is the only one with a global vision of its innertypes. - - if (constantPoolNameUsage == null) - constantPoolNameUsage = new HashtableOfType(); - - ReferenceBinding outerMostEnclosingType = localType.scope.outerMostClassScope().enclosingSourceType(); - - // ensure there is not already such a local type name defined by the user - int index = 0; - char[] candidateName; - while (true) { - if (localType.isMemberType()) { - if (index == 0) { - candidateName = CharOperation.concat(localType.enclosingType().constantPoolName(), localType.sourceName, '$'); - } else { - // in case of collision, then member name gets extra $1 inserted - // e.g. class X { { class L{} new X(){ class L{} } } } - candidateName = - CharOperation.concat(localType.enclosingType().constantPoolName(), '$', String.valueOf(index).toCharArray(), '$', localType.sourceName); - } - } else if (localType.isAnonymousType()) { - candidateName = CharOperation.concat(outerMostEnclosingType.constantPoolName(), String.valueOf(index + 1).toCharArray(), '$'); - } else { - candidateName = - CharOperation.concat(outerMostEnclosingType.constantPoolName(), '$', String.valueOf(index + 1).toCharArray(), '$', localType.sourceName); - } - if (constantPoolNameUsage.get(candidateName) != null) { - index++; - } else { - constantPoolNameUsage.put(candidateName, localType); - break; - } - } - return candidateName; - } - - void connectTypeHierarchy() { - for (int i = 0, length = topLevelTypes.length; i < length; i++) - topLevelTypes[i].scope.connectTypeHierarchy(); - } - void faultInImports() { - if (referenceContext.imports == null) - return; -// -// // collect the top level type names if a single type import exists - int numberOfStatements = referenceContext.imports.length; -// HashtableOfType typesBySimpleNames = null; -// for (int i = 0; i < numberOfStatements; i++) { -// if (!referenceContext.imports[i].onDemand) { -// typesBySimpleNames = new HashtableOfType(topLevelTypes.length + numberOfStatements); -// for (int j = 0, length = topLevelTypes.length; j < length; j++) -// typesBySimpleNames.put(topLevelTypes[j].sourceName, topLevelTypes[j]); -// break; -// } -// } -// -// // allocate the import array, add java.lang.* by default -// int numberOfImports = numberOfStatements + 1; -// for (int i = 0; i < numberOfStatements; i++) { -// ImportReference importReference = referenceContext.imports[i]; -// if (importReference.onDemand && CharOperation.equals(JAVA_LANG, importReference.tokens)) { -// numberOfImports--; -// break; -// } -// } - ImportBinding[] resolvedImports = new ImportBinding[numberOfStatements]; -// resolvedImports[0] = environment.defaultImports[0]; -// int index = 1; - int index = 0; - nextImport : for (int i = 0; i < numberOfStatements; i++) { - ImportReference importReference = referenceContext.imports[i]; - // create the file name segments here: -// char[][] compoundName = importReference.tokens; -// -// // skip duplicates or imports of the current package -// for (int j = 0; j < index; j++) -// if (resolvedImports[j].onDemand == importReference.onDemand) -// if (CharOperation.equals(compoundName, resolvedImports[j].compoundName)) { -// problemReporter().unusedImport(importReference); // since skipped, must be reported now -// continue nextImport; -// } -// if (importReference.onDemand == true) -// if (CharOperation.equals(compoundName, currentPackageName)) { -// problemReporter().unusedImport(importReference); // since skipped, must be reported now -// continue nextImport; -// } -// if (importReference.onDemand) { -// Binding importBinding = findOnDemandImport(compoundName); -// if (!importBinding.isValidBinding()) { -// problemReporter().importProblem(importReference, importBinding); -// continue nextImport; -// } -// resolvedImports[index++] = new ImportBinding(compoundName, true, importBinding, importReference); -// } else { - IFile file = importReference.getFile(); - SourceTypeBinding typeBinding; - char[][] compoundName; - if (file != null){ - typeBinding = new SourceTypeBinding(); -// findSingleTypeImport(compoundName); - IPath path = file.getProjectRelativePath(); - String[] segs = path.segments(); - compoundName = new char[segs.length][]; - for (int j = 0; j < segs.length; j++) { - compoundName[j] = segs[j].toCharArray(); - } - typeBinding.compoundName = compoundName; // compoundName; -// this.fPackage = fPackage; - typeBinding.fileName = file.getLocation().toString().toCharArray(); -// typeBinding.modifiers = scope.referenceContext.modifiers; -// typeBinding.sourceName = scope.referenceContext.name; - typeBinding.sourceName = path.lastSegment().toCharArray(); -// this.scope = scope; - } else { -// if (!typeBinding.isValidBinding()) { -// problemReporter().importProblem(importReference, typeBinding); - continue nextImport; -// } - } -// if (typeBinding instanceof PackageBinding) { -// problemReporter().cannotImportPackage(importReference); -// continue nextImport; -// } -// if (typeBinding instanceof ReferenceBinding) { -// ReferenceBinding referenceBinding = (ReferenceBinding) typeBinding; -// if (importReference.isTypeUseDeprecated(referenceBinding, this)) { -// problemReporter().deprecatedType((TypeBinding) typeBinding, importReference); -// } -// } -// ReferenceBinding existingType = typesBySimpleNames.get(compoundName[compoundName.length - 1]); -// if (existingType != null) { -// // duplicate test above should have caught this case, but make sure -// if (existingType == typeBinding) { -// continue nextImport; -// } -// // either the type collides with a top level type or another imported type -// for (int j = 0, length = topLevelTypes.length; j < length; j++) { -// if (CharOperation.equals(topLevelTypes[j].sourceName, existingType.sourceName)) { -// problemReporter().conflictingImport(importReference); -// continue nextImport; -// } -// } -// problemReporter().duplicateImport(importReference); -// continue nextImport; -// } - resolvedImports[index++] = new ImportBinding(compoundName, false, typeBinding, importReference); - imports = resolvedImports; -// typesBySimpleNames.put(compoundName[compoundName.length - 1], (ReferenceBinding) typeBinding); -// } - } -// -// // shrink resolvedImports... only happens if an error was reported - if (resolvedImports.length > index) - System.arraycopy(resolvedImports, 0, resolvedImports = new ImportBinding[index], 0, index); - imports = resolvedImports; - - int length = imports.length; - resolvedSingeTypeImports = new HashtableOfObject(length); - for (int i = 0; i < length; i++) { - ImportBinding binding = imports[i]; - if (!binding.onDemand) - resolvedSingeTypeImports.put(binding.compoundName[binding.compoundName.length - 1], binding); + public LookupEnvironment environment; + + public CompilationUnitDeclaration referenceContext; + + public char[][] currentPackageName; + + public PackageBinding fPackage; + + public ImportBinding[] imports; + + public SourceTypeBinding[] topLevelTypes; + + private CompoundNameVector qualifiedReferences; + + private SimpleNameVector simpleNameReferences; + + private ObjectVector referencedTypes; + + HashtableOfType constantPoolNameUsage; + + public HashtableOfObject resolvedSingeTypeImports; + + public CompilationUnitScope(CompilationUnitDeclaration unit, + LookupEnvironment environment) { + super(COMPILATION_UNIT_SCOPE, null); + this.environment = environment; + this.referenceContext = unit; + unit.scope = this; + // this.currentPackageName = unit.currentPackage == null ? + // CharOperation.NO_CHAR_CHAR : unit.currentPackage.tokens; + this.currentPackageName = null; + // if (environment.options.produceReferenceInfo) { + // this.qualifiedReferences = new CompoundNameVector(); + // this.simpleNameReferences = new SimpleNameVector(); + // this.referencedTypes = new ObjectVector(); + // } else { + this.qualifiedReferences = null; // used to test if dependencies + // should be recorded + this.simpleNameReferences = null; + this.referencedTypes = null; + // } + } + + void buildFieldsAndMethods() { + for (int i = 0, length = topLevelTypes.length; i < length; i++) + topLevelTypes[i].scope.buildFieldsAndMethods(); } - } - public void faultInTypes() { - faultInImports(); - if (topLevelTypes==null) { + + void buildTypeBindings() { + if (referenceContext.compilationResult.compilationUnit != null) { + char[][] expectedPackageName = referenceContext.compilationResult.compilationUnit + .getPackageName(); + if (expectedPackageName != null + && !CharOperation.equals(currentPackageName, + expectedPackageName)) { + + // only report if the unit isn't structurally empty + // if (referenceContext.currentPackage != null + // || referenceContext.types != null + // || referenceContext.imports != null) { + // problemReporter().packageIsNotExpectedPackage(referenceContext); + // } + currentPackageName = expectedPackageName.length == 0 ? CharOperation.NO_CHAR_CHAR + : expectedPackageName; + } + } + if (currentPackageName == CharOperation.NO_CHAR_CHAR) { + if ((fPackage = environment.defaultPackage) == null) { + problemReporter().mustSpecifyPackage(referenceContext); + return; + } + } else { + if ((fPackage = environment.createPackage(currentPackageName)) == null) { + // problemReporter().packageCollidesWithType(referenceContext); + return; + } + recordQualifiedReference(currentPackageName); // always dependent + // on your own + // package + } + + // Skip typeDeclarations which know of previously reported errors + ArrayList types = referenceContext.types; + int typeLength = (types == null) ? 0 : types.size(); + topLevelTypes = new SourceTypeBinding[typeLength]; + int count = 0; + nextType: for (int i = 0; i < typeLength; i++) { + if (types.get(i) instanceof TypeDeclaration) { + TypeDeclaration typeDecl = (TypeDeclaration) types.get(i); + ReferenceBinding typeBinding = fPackage.getType0(typeDecl.name); + recordSimpleReference(typeDecl.name); // needed to detect + // collision cases + if (typeBinding != null + && !(typeBinding instanceof UnresolvedReferenceBinding)) { + // if a type exists, it must be a valid type - cannot be a + // NotFound problem type + // unless its an unresolved type which is now being defined + problemReporter() + .duplicateTypes(referenceContext, typeDecl); + continue nextType; + } + if (fPackage != environment.defaultPackage + && fPackage.getPackage(typeDecl.name) != null) { + // if a package exists, it must be a valid package - cannot + // be a NotFound problem package + problemReporter().typeCollidesWithPackage(referenceContext, + typeDecl); + continue nextType; + } + + if ((typeDecl.modifiers & AccPublic) != 0) { + char[] mainTypeName; + if ((mainTypeName = referenceContext.getMainTypeName()) != null + // mainTypeName == null means that implementor of + // ICompilationUnit decided to return null + && !CharOperation.equals(mainTypeName, + typeDecl.name)) { + problemReporter().publicClassMustMatchFileName( + referenceContext, typeDecl); + continue nextType; + } + } + + ClassScope child = new ClassScope(this, typeDecl); + SourceTypeBinding type = child.buildType(null, fPackage); + if (type != null) { + topLevelTypes[count++] = type; + } + } + } + + // shrink topLevelTypes... only happens if an error was reported + if (count != topLevelTypes.length) + System.arraycopy(topLevelTypes, 0, + topLevelTypes = new SourceTypeBinding[count], 0, count); + } + + void checkAndSetImports() { + // initialize the default imports if necessary... share the default + // java.lang.* import + if (environment.defaultImports == null) { + Binding importBinding = environment.getTopLevelPackage(JAVA); + if (importBinding != null) + importBinding = ((PackageBinding) importBinding) + .getTypeOrPackage(JAVA_LANG[1]); + + // abort if java.lang cannot be found... + if (importBinding == null || !importBinding.isValidBinding()) + problemReporter().isClassPathCorrect(JAVA_LANG_OBJECT, + referenceCompilationUnit()); + + environment.defaultImports = new ImportBinding[] { new ImportBinding( + JAVA_LANG, true, importBinding, null) }; + } + if (referenceContext.imports == null) { + imports = environment.defaultImports; + return; + } + + // allocate the import array, add java.lang.* by default + int numberOfStatements = referenceContext.imports.length; + // int numberOfImports = numberOfStatements + 1; + int numberOfImports = numberOfStatements; + // for (int i = 0; i < numberOfStatements; i++) { + // ImportReference importReference = referenceContext.imports[i]; + // if (importReference.onDemand && CharOperation.equals(JAVA_LANG, + // importReference.tokens)) { + // numberOfImports--; + // break; + // } + // } + ImportBinding[] resolvedImports = new ImportBinding[numberOfImports]; + resolvedImports[0] = environment.defaultImports[0]; + int index = 1; + + nextImport: for (int i = 0; i < numberOfStatements; i++) { + ImportReference importReference = referenceContext.imports[i]; + IFile file = importReference.getFile(); + SourceTypeBinding typeBinding; + // char[][] compoundName = importReference.tokens; + char[][] compoundName = null; + if (file != null) { + IPath path = file.getProjectRelativePath(); + String[] segs = path.segments(); + compoundName = new char[segs.length][]; + for (int j = 0; j < segs.length; j++) { + compoundName[j] = segs[j].toCharArray(); + } + } + if (compoundName == null) { + continue nextImport; + } + + // skip duplicates or imports of the current package + for (int j = 0; j < index; j++) + if (resolvedImports[j].onDemand == importReference.onDemand) + if (CharOperation.equals(compoundName, + resolvedImports[j].compoundName)) + continue nextImport; + if (importReference.onDemand == true) + if (CharOperation.equals(compoundName, currentPackageName)) + continue nextImport; + + if (importReference.onDemand) { + Binding importBinding = findOnDemandImport(compoundName); + if (!importBinding.isValidBinding()) + continue nextImport; // we report all problems in + // faultInImports() + resolvedImports[index++] = new ImportBinding(compoundName, + true, importBinding, importReference); + } else { + resolvedImports[index++] = new ImportBinding(compoundName, + false, null, importReference); + } + } + + // shrink resolvedImports... only happens if an error was reported + if (resolvedImports.length > index) + System.arraycopy(resolvedImports, 0, + resolvedImports = new ImportBinding[index], 0, index); + imports = resolvedImports; + } + + /* + * INTERNAL USE-ONLY Innerclasses get their name computed as they are + * generated, since some may not be actually outputed if sitting inside + * unreachable code. + */ + public char[] computeConstantPoolName(LocalTypeBinding localType) { + if (localType.constantPoolName() != null) { + return localType.constantPoolName(); + } + // delegates to the outermost enclosing classfile, since it is the only + // one with a global vision of its innertypes. + + if (constantPoolNameUsage == null) + constantPoolNameUsage = new HashtableOfType(); + + ReferenceBinding outerMostEnclosingType = localType.scope + .outerMostClassScope().enclosingSourceType(); + + // ensure there is not already such a local type name defined by the + // user + int index = 0; + char[] candidateName; + while (true) { + if (localType.isMemberType()) { + if (index == 0) { + candidateName = CharOperation.concat(localType + .enclosingType().constantPoolName(), + localType.sourceName, '$'); + } else { + // in case of collision, then member name gets extra $1 + // inserted + // e.g. class X { { class L{} new X(){ class L{} } } } + candidateName = CharOperation.concat(localType + .enclosingType().constantPoolName(), '$', String + .valueOf(index).toCharArray(), '$', + localType.sourceName); + } + } else if (localType.isAnonymousType()) { + candidateName = CharOperation.concat(outerMostEnclosingType + .constantPoolName(), String.valueOf(index + 1) + .toCharArray(), '$'); + } else { + candidateName = CharOperation.concat(outerMostEnclosingType + .constantPoolName(), '$', String.valueOf(index + 1) + .toCharArray(), '$', localType.sourceName); + } + if (constantPoolNameUsage.get(candidateName) != null) { + index++; + } else { + constantPoolNameUsage.put(candidateName, localType); + break; + } + } + return candidateName; + } + + void connectTypeHierarchy() { + for (int i = 0, length = topLevelTypes.length; i < length; i++) + topLevelTypes[i].scope.connectTypeHierarchy(); + } + + void faultInImports() { + if (referenceContext.imports == null) + return; + // + // // collect the top level type names if a single type import exists + int numberOfStatements = referenceContext.imports.length; + // HashtableOfType typesBySimpleNames = null; + // for (int i = 0; i < numberOfStatements; i++) { + // if (!referenceContext.imports[i].onDemand) { + // typesBySimpleNames = new HashtableOfType(topLevelTypes.length + + // numberOfStatements); + // for (int j = 0, length = topLevelTypes.length; j < length; j++) + // typesBySimpleNames.put(topLevelTypes[j].sourceName, + // topLevelTypes[j]); + // break; + // } + // } + // + // // allocate the import array, add java.lang.* by default + // int numberOfImports = numberOfStatements + 1; + // for (int i = 0; i < numberOfStatements; i++) { + // ImportReference importReference = referenceContext.imports[i]; + // if (importReference.onDemand && CharOperation.equals(JAVA_LANG, + // importReference.tokens)) { + // numberOfImports--; + // break; + // } + // } + ImportBinding[] resolvedImports = new ImportBinding[numberOfStatements]; + // resolvedImports[0] = environment.defaultImports[0]; + // int index = 1; + int index = 0; + nextImport: for (int i = 0; i < numberOfStatements; i++) { + ImportReference importReference = referenceContext.imports[i]; + // create the file name segments here: + // char[][] compoundName = importReference.tokens; + // + // // skip duplicates or imports of the current package + // for (int j = 0; j < index; j++) + // if (resolvedImports[j].onDemand == importReference.onDemand) + // if (CharOperation.equals(compoundName, + // resolvedImports[j].compoundName)) { + // problemReporter().unusedImport(importReference); // since + // skipped, must be reported now + // continue nextImport; + // } + // if (importReference.onDemand == true) + // if (CharOperation.equals(compoundName, currentPackageName)) { + // problemReporter().unusedImport(importReference); // since + // skipped, must be reported now + // continue nextImport; + // } + // if (importReference.onDemand) { + // Binding importBinding = findOnDemandImport(compoundName); + // if (!importBinding.isValidBinding()) { + // problemReporter().importProblem(importReference, importBinding); + // continue nextImport; + // } + // resolvedImports[index++] = new ImportBinding(compoundName, true, + // importBinding, importReference); + // } else { + IFile file = importReference.getFile(); + SourceTypeBinding typeBinding; + char[][] compoundName; + if (file != null) { + typeBinding = new SourceTypeBinding(); + // findSingleTypeImport(compoundName); + IPath path = file.getProjectRelativePath(); + String[] segs = path.segments(); + compoundName = new char[segs.length][]; + for (int j = 0; j < segs.length; j++) { + compoundName[j] = segs[j].toCharArray(); + } + typeBinding.compoundName = compoundName; // compoundName; + // this.fPackage = fPackage; + typeBinding.fileName = file.getLocation().toString() + .toCharArray(); + // typeBinding.modifiers = scope.referenceContext.modifiers; + // typeBinding.sourceName = scope.referenceContext.name; + typeBinding.sourceName = path.lastSegment().toCharArray(); + // this.scope = scope; + } else { + // if (!typeBinding.isValidBinding()) { + // problemReporter().importProblem(importReference, + // typeBinding); + continue nextImport; + // } + } + // if (typeBinding instanceof PackageBinding) { + // problemReporter().cannotImportPackage(importReference); + // continue nextImport; + // } + // if (typeBinding instanceof ReferenceBinding) { + // ReferenceBinding referenceBinding = (ReferenceBinding) + // typeBinding; + // if (importReference.isTypeUseDeprecated(referenceBinding, this)) + // { + // problemReporter().deprecatedType((TypeBinding) typeBinding, + // importReference); + // } + // } + // ReferenceBinding existingType = + // typesBySimpleNames.get(compoundName[compoundName.length - 1]); + // if (existingType != null) { + // // duplicate test above should have caught this case, but make + // sure + // if (existingType == typeBinding) { + // continue nextImport; + // } + // // either the type collides with a top level type or another + // imported type + // for (int j = 0, length = topLevelTypes.length; j < length; j++) { + // if (CharOperation.equals(topLevelTypes[j].sourceName, + // existingType.sourceName)) { + // problemReporter().conflictingImport(importReference); + // continue nextImport; + // } + // } + // problemReporter().duplicateImport(importReference); + // continue nextImport; + // } + resolvedImports[index++] = new ImportBinding(compoundName, false, + typeBinding, importReference); + imports = resolvedImports; + // typesBySimpleNames.put(compoundName[compoundName.length - 1], + // (ReferenceBinding) typeBinding); + // } + } + // + // // shrink resolvedImports... only happens if an error was reported + if (resolvedImports.length > index) + System.arraycopy(resolvedImports, 0, + resolvedImports = new ImportBinding[index], 0, index); + imports = resolvedImports; + + int length = imports.length; + resolvedSingeTypeImports = new HashtableOfObject(length); + for (int i = 0; i < length; i++) { + ImportBinding binding = imports[i]; + if (!binding.onDemand) + resolvedSingeTypeImports.put( + binding.compoundName[binding.compoundName.length - 1], + binding); + } + } + + public void faultInTypes() { + faultInImports(); + if (topLevelTypes == null) { topLevelTypes = new SourceTypeBinding[0]; - } - for (int i = 0, length = topLevelTypes.length; i < length; i++) - topLevelTypes[i].faultInTypesForFieldsAndMethods(); - } - private Binding findOnDemandImport(char[][] compoundName) { - recordQualifiedReference(compoundName); - - Binding binding = environment.getTopLevelPackage(compoundName[0]); - int i = 1; - int length = compoundName.length; - foundNothingOrType : if (binding != null) { - PackageBinding packageBinding = (PackageBinding) binding; - while (i < length) { - binding = packageBinding.getTypeOrPackage(compoundName[i++]); - if (binding == null || !binding.isValidBinding()) { - binding = null; - break foundNothingOrType; - } - if (!(binding instanceof PackageBinding)) - break foundNothingOrType; - - packageBinding = (PackageBinding) binding; - } - return packageBinding; - } - - ReferenceBinding type; - if (binding == null) { - // if (environment.defaultPackage == null - // || environment.options.complianceLevel >= CompilerOptions.JDK1_4){ - // return new ProblemReferenceBinding( - // CharOperation.subarray(compoundName, 0, i), - // NotFound); - // } - type = findType(compoundName[0], environment.defaultPackage, environment.defaultPackage); - if (type == null || !type.isValidBinding()) - return new ProblemReferenceBinding(CharOperation.subarray(compoundName, 0, i), NotFound); - i = 1; // reset to look for member types inside the default package type - } else { - type = (ReferenceBinding) binding; - } - - for (; i < length; i++) { - if (!type.canBeSeenBy(fPackage)) { - return new ProblemReferenceBinding(CharOperation.subarray(compoundName, 0, i), type, NotVisible); - } - // does not look for inherited member types on purpose - if ((type = type.getMemberType(compoundName[i])) == null) { - return new ProblemReferenceBinding(CharOperation.subarray(compoundName, 0, i + 1), NotFound); - } - } - if (!type.canBeSeenBy(fPackage)) - return new ProblemReferenceBinding(compoundName, type, NotVisible); - return type; - } - private Binding findSingleTypeImport(char[][] compoundName) { -// if (compoundName.length == 1) { - // findType records the reference - // the name cannot be a package - // if (environment.defaultPackage == null - // || environment.options.complianceLevel >= CompilerOptions.JDK1_4) - // return new ProblemReferenceBinding(compoundName, NotFound); - ReferenceBinding typeBinding = findType(compoundName[0], environment.defaultPackage, fPackage); - if (typeBinding == null) - return new ProblemReferenceBinding(compoundName, NotFound); - else - return typeBinding; -// } -// return findOnDemandImport(compoundName); - } - /* Answer the problem reporter to use for raising new problems. - * - * Note that as a side-effect, this updates the current reference context - * (unit, type or method) in case the problem handler decides it is necessary - * to abort. - */ - - public ProblemReporter problemReporter() { - ProblemReporter problemReporter = referenceContext.problemReporter; - problemReporter.referenceContext = referenceContext; - return problemReporter; - } - - /* - What do we hold onto: - - 1. when we resolve 'a.b.c', say we keep only 'a.b.c' - & when we fail to resolve 'c' in 'a.b', lets keep 'a.b.c' - THEN when we come across a new/changed/removed item named 'a.b.c', - we would find all references to 'a.b.c' - -> This approach fails because every type is resolved in every onDemand import to - detect collision cases... so the references could be 10 times bigger than necessary. - - 2. when we resolve 'a.b.c', lets keep 'a.b' & 'c' - & when we fail to resolve 'c' in 'a.b', lets keep 'a.b' & 'c' - THEN when we come across a new/changed/removed item named 'a.b.c', - we would find all references to 'a.b' & 'c' - -> This approach does not have a space problem but fails to handle collision cases. - What happens if a type is added named 'a.b'? We would search for 'a' & 'b' but - would not find a match. - - 3. when we resolve 'a.b.c', lets keep 'a', 'a.b' & 'a', 'b', 'c' - & when we fail to resolve 'c' in 'a.b', lets keep 'a', 'a.b' & 'a', 'b', 'c' - THEN when we come across a new/changed/removed item named 'a.b.c', - we would find all references to 'a.b' & 'c' - OR 'a.b' -> 'a' & 'b' - OR 'a' -> '' & 'a' - -> As long as each single char[] is interned, we should not have a space problem - and can handle collision cases. - - 4. when we resolve 'a.b.c', lets keep 'a.b' & 'a', 'b', 'c' - & when we fail to resolve 'c' in 'a.b', lets keep 'a.b' & 'a', 'b', 'c' - THEN when we come across a new/changed/removed item named 'a.b.c', - we would find all references to 'a.b' & 'c' - OR 'a.b' -> 'a' & 'b' in the simple name collection - OR 'a' -> 'a' in the simple name collection - -> As long as each single char[] is interned, we should not have a space problem - and can handle collision cases. - */ - void recordQualifiedReference(char[][] qualifiedName) { - if (qualifiedReferences == null) - return; // not recording dependencies - - int length = qualifiedName.length; - if (length > 1) { - while (!qualifiedReferences.contains(qualifiedName)) { - qualifiedReferences.add(qualifiedName); - if (length == 2) { - recordSimpleReference(qualifiedName[0]); - recordSimpleReference(qualifiedName[1]); - return; - } - length--; - recordSimpleReference(qualifiedName[length]); - System.arraycopy(qualifiedName, 0, qualifiedName = new char[length][], 0, length); - } - } else if (length == 1) { - recordSimpleReference(qualifiedName[0]); - } - } - void recordReference(char[][] qualifiedEnclosingName, char[] simpleName) { - recordQualifiedReference(qualifiedEnclosingName); - recordSimpleReference(simpleName); - } - void recordSimpleReference(char[] simpleName) { - if (simpleNameReferences == null) - return; // not recording dependencies - - if (!simpleNameReferences.contains(simpleName)) - simpleNameReferences.add(simpleName); - } - void recordTypeReference(TypeBinding type) { - if (referencedTypes == null) - return; // not recording dependencies - - if (type.isArrayType()) - type = ((ArrayBinding) type).leafComponentType; - if (!type.isBaseType() && !referencedTypes.containsIdentical(type)) - referencedTypes.add(type); - } - void recordTypeReferences(TypeBinding[] types) { - if (qualifiedReferences == null) - return; // not recording dependencies - if (types == null || types.length == 0) - return; - - for (int i = 0, max = types.length; i < max; i++) { - // No need to record supertypes of method arguments & thrown exceptions, just the compoundName - // If a field/method is retrieved from such a type then a separate call does the job - TypeBinding type = types[i]; - if (type.isArrayType()) - type = ((ArrayBinding) type).leafComponentType; - if (!type.isBaseType()) { - ReferenceBinding actualType = (ReferenceBinding) type; - if (!actualType.isLocalType()) - recordQualifiedReference(actualType.isMemberType() ? CharOperation.splitOn('.', actualType.readableName()) : actualType.compoundName); - } - } - } - Binding resolveSingleTypeImport(ImportBinding importBinding) { - if (importBinding.resolvedImport == null) { - importBinding.resolvedImport = findSingleTypeImport(importBinding.compoundName); - if (!importBinding.resolvedImport.isValidBinding() || importBinding.resolvedImport instanceof PackageBinding) { - if (this.imports != null) { - ImportBinding[] newImports = new ImportBinding[imports.length - 1]; - for (int i = 0, n = 0, max = this.imports.length; i < max; i++) - if (this.imports[i] != importBinding) { - newImports[n++] = this.imports[i]; - } - this.imports = newImports; - } - return null; - } - } - return importBinding.resolvedImport; - } - public void storeDependencyInfo() { - // add the type hierarchy of each referenced type - // cannot do early since the hierarchy may not be fully resolved - for (int i = 0; i < referencedTypes.size; i++) { // grows as more types are added - ReferenceBinding type = (ReferenceBinding) referencedTypes.elementAt(i); - if (!type.isLocalType()) { - recordQualifiedReference(type.isMemberType() ? CharOperation.splitOn('.', type.readableName()) : type.compoundName); - ReferenceBinding enclosing = type.enclosingType(); - if (enclosing != null && !referencedTypes.containsIdentical(enclosing)) - referencedTypes.add(enclosing); // to record its supertypes - } - ReferenceBinding superclass = type.superclass(); - if (superclass != null && !referencedTypes.containsIdentical(superclass)) - referencedTypes.add(superclass); // to record its supertypes - ReferenceBinding[] interfaces = type.superInterfaces(); - if (interfaces != null && interfaces.length > 0) - for (int j = 0, length = interfaces.length; j < length; j++) - if (!referencedTypes.containsIdentical(interfaces[j])) - referencedTypes.add(interfaces[j]); // to record its supertypes - } - - int size = qualifiedReferences.size; - char[][][] qualifiedRefs = new char[size][][]; - for (int i = 0; i < size; i++) - qualifiedRefs[i] = qualifiedReferences.elementAt(i); - referenceContext.compilationResult.qualifiedReferences = qualifiedRefs; - - size = simpleNameReferences.size; - char[][] simpleRefs = new char[size][]; - for (int i = 0; i < size; i++) - simpleRefs[i] = simpleNameReferences.elementAt(i); - referenceContext.compilationResult.simpleNameReferences = simpleRefs; - } - public String toString() { - return "--- CompilationUnit Scope : " + new String(referenceContext.getFileName()); //$NON-NLS-1$ - } - public void verifyMethods(MethodVerifier verifier) { - for (int i = 0, length = topLevelTypes.length; i < length; i++) - topLevelTypes[i].verifyMethods(verifier); - } + } + for (int i = 0, length = topLevelTypes.length; i < length; i++) + topLevelTypes[i].faultInTypesForFieldsAndMethods(); + } + + private Binding findOnDemandImport(char[][] compoundName) { + recordQualifiedReference(compoundName); + + Binding binding = environment.getTopLevelPackage(compoundName[0]); + int i = 1; + int length = compoundName.length; + foundNothingOrType: if (binding != null) { + PackageBinding packageBinding = (PackageBinding) binding; + while (i < length) { + binding = packageBinding.getTypeOrPackage(compoundName[i++]); + if (binding == null || !binding.isValidBinding()) { + binding = null; + break foundNothingOrType; + } + if (!(binding instanceof PackageBinding)) + break foundNothingOrType; + + packageBinding = (PackageBinding) binding; + } + return packageBinding; + } + + ReferenceBinding type; + if (binding == null) { + // if (environment.defaultPackage == null + // || environment.options.complianceLevel >= + // CompilerOptions.JDK1_4){ + // return new ProblemReferenceBinding( + // CharOperation.subarray(compoundName, 0, i), + // NotFound); + // } + type = findType(compoundName[0], environment.defaultPackage, + environment.defaultPackage); + if (type == null || !type.isValidBinding()) + return new ProblemReferenceBinding(CharOperation.subarray( + compoundName, 0, i), NotFound); + i = 1; // reset to look for member types inside the default package + // type + } else { + type = (ReferenceBinding) binding; + } + + for (; i < length; i++) { + if (!type.canBeSeenBy(fPackage)) { + return new ProblemReferenceBinding(CharOperation.subarray( + compoundName, 0, i), type, NotVisible); + } + // does not look for inherited member types on purpose + if ((type = type.getMemberType(compoundName[i])) == null) { + return new ProblemReferenceBinding(CharOperation.subarray( + compoundName, 0, i + 1), NotFound); + } + } + if (!type.canBeSeenBy(fPackage)) + return new ProblemReferenceBinding(compoundName, type, NotVisible); + return type; + } + + private Binding findSingleTypeImport(char[][] compoundName) { + // if (compoundName.length == 1) { + // findType records the reference + // the name cannot be a package + // if (environment.defaultPackage == null + // || environment.options.complianceLevel >= CompilerOptions.JDK1_4) + // return new ProblemReferenceBinding(compoundName, NotFound); + ReferenceBinding typeBinding = findType(compoundName[0], + environment.defaultPackage, fPackage); + if (typeBinding == null) + return new ProblemReferenceBinding(compoundName, NotFound); + else + return typeBinding; + // } + // return findOnDemandImport(compoundName); + } + + /* + * Answer the problem reporter to use for raising new problems. + * + * Note that as a side-effect, this updates the current reference context + * (unit, type or method) in case the problem handler decides it is + * necessary to abort. + */ + + public ProblemReporter problemReporter() { + ProblemReporter problemReporter = referenceContext.problemReporter; + problemReporter.referenceContext = referenceContext; + return problemReporter; + } + + /* + * What do we hold onto: + * + * 1. when we resolve 'a.b.c', say we keep only 'a.b.c' & when we fail to + * resolve 'c' in 'a.b', lets keep 'a.b.c' THEN when we come across a + * new/changed/removed item named 'a.b.c', we would find all references to + * 'a.b.c' -> This approach fails because every type is resolved in every + * onDemand import to detect collision cases... so the references could be + * 10 times bigger than necessary. + * + * 2. when we resolve 'a.b.c', lets keep 'a.b' & 'c' & when we fail to + * resolve 'c' in 'a.b', lets keep 'a.b' & 'c' THEN when we come across a + * new/changed/removed item named 'a.b.c', we would find all references to + * 'a.b' & 'c' -> This approach does not have a space problem but fails to + * handle collision cases. What happens if a type is added named 'a.b'? We + * would search for 'a' & 'b' but would not find a match. + * + * 3. when we resolve 'a.b.c', lets keep 'a', 'a.b' & 'a', 'b', 'c' & when + * we fail to resolve 'c' in 'a.b', lets keep 'a', 'a.b' & 'a', 'b', 'c' + * THEN when we come across a new/changed/removed item named 'a.b.c', we + * would find all references to 'a.b' & 'c' OR 'a.b' -> 'a' & 'b' OR 'a' -> '' & + * 'a' -> As long as each single char[] is interned, we should not have a + * space problem and can handle collision cases. + * + * 4. when we resolve 'a.b.c', lets keep 'a.b' & 'a', 'b', 'c' & when we + * fail to resolve 'c' in 'a.b', lets keep 'a.b' & 'a', 'b', 'c' THEN when + * we come across a new/changed/removed item named 'a.b.c', we would find + * all references to 'a.b' & 'c' OR 'a.b' -> 'a' & 'b' in the simple name + * collection OR 'a' -> 'a' in the simple name collection -> As long as each + * single char[] is interned, we should not have a space problem and can + * handle collision cases. + */ + void recordQualifiedReference(char[][] qualifiedName) { + if (qualifiedReferences == null) + return; // not recording dependencies + + int length = qualifiedName.length; + if (length > 1) { + while (!qualifiedReferences.contains(qualifiedName)) { + qualifiedReferences.add(qualifiedName); + if (length == 2) { + recordSimpleReference(qualifiedName[0]); + recordSimpleReference(qualifiedName[1]); + return; + } + length--; + recordSimpleReference(qualifiedName[length]); + System.arraycopy(qualifiedName, 0, + qualifiedName = new char[length][], 0, length); + } + } else if (length == 1) { + recordSimpleReference(qualifiedName[0]); + } + } + + void recordReference(char[][] qualifiedEnclosingName, char[] simpleName) { + recordQualifiedReference(qualifiedEnclosingName); + recordSimpleReference(simpleName); + } + + void recordSimpleReference(char[] simpleName) { + if (simpleNameReferences == null) + return; // not recording dependencies + + if (!simpleNameReferences.contains(simpleName)) + simpleNameReferences.add(simpleName); + } + + void recordTypeReference(TypeBinding type) { + if (referencedTypes == null) + return; // not recording dependencies + + if (type.isArrayType()) + type = ((ArrayBinding) type).leafComponentType; + if (!type.isBaseType() && !referencedTypes.containsIdentical(type)) + referencedTypes.add(type); + } + + void recordTypeReferences(TypeBinding[] types) { + if (qualifiedReferences == null) + return; // not recording dependencies + if (types == null || types.length == 0) + return; + + for (int i = 0, max = types.length; i < max; i++) { + // No need to record supertypes of method arguments & thrown + // exceptions, just the compoundName + // If a field/method is retrieved from such a type then a separate + // call does the job + TypeBinding type = types[i]; + if (type.isArrayType()) + type = ((ArrayBinding) type).leafComponentType; + if (!type.isBaseType()) { + ReferenceBinding actualType = (ReferenceBinding) type; + if (!actualType.isLocalType()) + recordQualifiedReference(actualType.isMemberType() ? CharOperation + .splitOn('.', actualType.readableName()) + : actualType.compoundName); + } + } + } + + Binding resolveSingleTypeImport(ImportBinding importBinding) { + if (importBinding.resolvedImport == null) { + importBinding.resolvedImport = findSingleTypeImport(importBinding.compoundName); + if (!importBinding.resolvedImport.isValidBinding() + || importBinding.resolvedImport instanceof PackageBinding) { + if (this.imports != null) { + ImportBinding[] newImports = new ImportBinding[imports.length - 1]; + for (int i = 0, n = 0, max = this.imports.length; i < max; i++) + if (this.imports[i] != importBinding) { + newImports[n++] = this.imports[i]; + } + this.imports = newImports; + } + return null; + } + } + return importBinding.resolvedImport; + } + + public void storeDependencyInfo() { + // add the type hierarchy of each referenced type + // cannot do early since the hierarchy may not be fully resolved + for (int i = 0; i < referencedTypes.size; i++) { // grows as more + // types are added + ReferenceBinding type = (ReferenceBinding) referencedTypes + .elementAt(i); + if (!type.isLocalType()) { + recordQualifiedReference(type.isMemberType() ? CharOperation + .splitOn('.', type.readableName()) : type.compoundName); + ReferenceBinding enclosing = type.enclosingType(); + if (enclosing != null + && !referencedTypes.containsIdentical(enclosing)) + referencedTypes.add(enclosing); // to record its supertypes + } + ReferenceBinding superclass = type.superclass(); + if (superclass != null + && !referencedTypes.containsIdentical(superclass)) + referencedTypes.add(superclass); // to record its supertypes + ReferenceBinding[] interfaces = type.superInterfaces(); + if (interfaces != null && interfaces.length > 0) + for (int j = 0, length = interfaces.length; j < length; j++) + if (!referencedTypes.containsIdentical(interfaces[j])) + referencedTypes.add(interfaces[j]); // to record its + // supertypes + } + + int size = qualifiedReferences.size; + char[][][] qualifiedRefs = new char[size][][]; + for (int i = 0; i < size; i++) + qualifiedRefs[i] = qualifiedReferences.elementAt(i); + referenceContext.compilationResult.qualifiedReferences = qualifiedRefs; + + size = simpleNameReferences.size; + char[][] simpleRefs = new char[size][]; + for (int i = 0; i < size; i++) + simpleRefs[i] = simpleNameReferences.elementAt(i); + referenceContext.compilationResult.simpleNameReferences = simpleRefs; + } + + public String toString() { + return "--- CompilationUnit Scope : " + new String(referenceContext.getFileName()); //$NON-NLS-1$ + } + + public void verifyMethods(MethodVerifier verifier) { + for (int i = 0, length = topLevelTypes.length; i < length; i++) + topLevelTypes[i].verifyMethods(verifier); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/CompilerModifiers.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/CompilerModifiers.java index 0e881bc..d326593 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/CompilerModifiers.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/CompilerModifiers.java @@ -13,26 +13,55 @@ package net.sourceforge.phpdt.internal.compiler.lookup; import net.sourceforge.phpdt.internal.compiler.env.IConstants; public interface CompilerModifiers extends IConstants { // modifier constant - // those constants are depending upon ClassFileConstants (relying that classfiles only use the 16 lower bits) + // those constants are depending upon ClassFileConstants (relying that + // classfiles only use the 16 lower bits) final int AccDefault = 0; + final int AccJustFlag = 0xFFFF; + final int AccCatchesExceptions = 0x10000; // bit17 - final int AccThrowsExceptions = 0x20000; // bit18 - also IConstants.AccSynthetic + + final int AccThrowsExceptions = 0x20000; // bit18 - also + // IConstants.AccSynthetic + final int AccProblem = 0x40000; // bit19 + final int AccFromClassFile = 0x80000; // bit20 - final int AccIsConstantValue = 0x80000; // bit20 + + final int AccIsConstantValue = 0x80000; // bit20 + final int AccDefaultAbstract = 0x80000; // bit20 + // bit21 - IConstants.AccDeprecated - final int AccDeprecatedImplicitly = 0x200000; // bit22 to record whether deprecated itself or contained by a deprecated type + final int AccDeprecatedImplicitly = 0x200000; // bit22 to record whether + // deprecated itself or + // contained by a deprecated + // type + final int AccAlternateModifierProblem = 0x400000; // bit23 + final int AccModifierProblem = 0x800000; // bit24 + final int AccSemicolonBody = 0x1000000; // bit25 + final int AccUnresolved = 0x2000000; // bit26 - final int AccClearPrivateModifier = 0x4000000; // bit27 might be requested during private access emulation + + final int AccClearPrivateModifier = 0x4000000; // bit27 might be requested + // during private access + // emulation + final int AccBlankFinal = 0x4000000; // bit27 for blank final variables - final int AccPrivateUsed = 0x8000000; // bit28 used to diagnose unused private members + + final int AccPrivateUsed = 0x8000000; // bit28 used to diagnose unused + // private members + final int AccVisibilityMASK = AccPublic | AccProtected | AccPrivate; - - final int AccOverriding = 0x10000000; // bit29 to record fact a method overrides another one - final int AccImplementing = 0x20000000; // bit30 to record fact a method implements another one (it is concrete and overrides an abstract one) + + final int AccOverriding = 0x10000000; // bit29 to record fact a method + // overrides another one + + final int AccImplementing = 0x20000000; // bit30 to record fact a method + // implements another one (it is + // concrete and overrides an + // abstract one) } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/FieldBinding.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/FieldBinding.java index 598715f..142e883 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/FieldBinding.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/FieldBinding.java @@ -13,199 +13,247 @@ package net.sourceforge.phpdt.internal.compiler.lookup; import net.sourceforge.phpdt.internal.compiler.ast.FieldDeclaration; import net.sourceforge.phpdt.internal.compiler.impl.Constant; - - public class FieldBinding extends VariableBinding { public ReferenceBinding declaringClass; -protected FieldBinding() { -} -public FieldBinding(char[] name, TypeBinding type, int modifiers, ReferenceBinding declaringClass, Constant constant) { - this.modifiers = modifiers; - this.type = type; - this.name = name; - this.declaringClass = declaringClass; - this.constant = constant; - - // propagate the deprecated modifier - if (this.declaringClass != null) - if (this.declaringClass.isViewedAsDeprecated() && !isDeprecated()) - this.modifiers |= AccDeprecatedImplicitly; -} -public FieldBinding(FieldDeclaration field, TypeBinding type, ReferenceBinding declaringClass) { - this(field.name, type, field.modifiers, declaringClass, null); - field.binding = this; -} -// special API used to change field declaring class for runtime visibility check -public FieldBinding(FieldBinding initialFieldBinding, ReferenceBinding declaringClass) { - this.modifiers = initialFieldBinding.modifiers; - this.type = initialFieldBinding.type; - this.name = initialFieldBinding.name; - this.declaringClass = declaringClass; - this.constant = initialFieldBinding.constant; - this.id = initialFieldBinding.id; -} -/* API -* Answer the receiver's binding type from Binding.BindingID. -*/ + protected FieldBinding() { + } -public final int bindingType() { - return FIELD; -} -/* Answer true if the receiver is visible to the type provided by the scope. -* InvocationSite implements isSuperAccess() to provide additional information -* if the receiver is protected. -* -* NOTE: Cannot invoke this method with a compilation unit scope. -*/ - -public final boolean canBeSeenBy(TypeBinding receiverType, InvocationSite invocationSite, Scope scope) { - if (isPublic()) return true; - - SourceTypeBinding invocationType = scope.enclosingSourceType(); - if (invocationType == declaringClass && invocationType == receiverType) return true; - - if (isProtected()) { - // answer true if the invocationType is the declaringClass or they are in the same package - // OR the invocationType is a subclass of the declaringClass - // AND the receiverType is the invocationType or its subclass - // OR the method is a static method accessed directly through a type - // OR previous assertions are true for one of the enclosing type - if (invocationType == declaringClass) return true; - if (invocationType.fPackage == declaringClass.fPackage) return true; - - ReferenceBinding currentType = invocationType; - int depth = 0; - do { - if (declaringClass.isSuperclassOf(currentType)) { - if (invocationSite.isSuperAccess()){ - return true; - } - // receiverType can be an array binding in one case... see if you can change it - if (receiverType instanceof ArrayBinding){ - return false; + public FieldBinding(char[] name, TypeBinding type, int modifiers, + ReferenceBinding declaringClass, Constant constant) { + this.modifiers = modifiers; + this.type = type; + this.name = name; + this.declaringClass = declaringClass; + this.constant = constant; + + // propagate the deprecated modifier + if (this.declaringClass != null) + if (this.declaringClass.isViewedAsDeprecated() && !isDeprecated()) + this.modifiers |= AccDeprecatedImplicitly; + } + + public FieldBinding(FieldDeclaration field, TypeBinding type, + ReferenceBinding declaringClass) { + this(field.name, type, field.modifiers, declaringClass, null); + + field.binding = this; + } + + // special API used to change field declaring class for runtime visibility + // check + public FieldBinding(FieldBinding initialFieldBinding, + ReferenceBinding declaringClass) { + this.modifiers = initialFieldBinding.modifiers; + this.type = initialFieldBinding.type; + this.name = initialFieldBinding.name; + this.declaringClass = declaringClass; + this.constant = initialFieldBinding.constant; + this.id = initialFieldBinding.id; + } + + /* + * API Answer the receiver's binding type from Binding.BindingID. + */ + + public final int bindingType() { + return FIELD; + } + + /* + * Answer true if the receiver is visible to the type provided by the scope. + * InvocationSite implements isSuperAccess() to provide additional + * information if the receiver is protected. + * + * NOTE: Cannot invoke this method with a compilation unit scope. + */ + + public final boolean canBeSeenBy(TypeBinding receiverType, + InvocationSite invocationSite, Scope scope) { + if (isPublic()) + return true; + + SourceTypeBinding invocationType = scope.enclosingSourceType(); + if (invocationType == declaringClass && invocationType == receiverType) + return true; + + if (isProtected()) { + // answer true if the invocationType is the declaringClass or they + // are in the same package + // OR the invocationType is a subclass of the declaringClass + // AND the receiverType is the invocationType or its subclass + // OR the method is a static method accessed directly through a type + // OR previous assertions are true for one of the enclosing type + if (invocationType == declaringClass) + return true; + if (invocationType.fPackage == declaringClass.fPackage) + return true; + + ReferenceBinding currentType = invocationType; + int depth = 0; + do { + if (declaringClass.isSuperclassOf(currentType)) { + if (invocationSite.isSuperAccess()) { + return true; + } + // receiverType can be an array binding in one case... see + // if you can change it + if (receiverType instanceof ArrayBinding) { + return false; + } + if (isStatic()) { + return true; // see 1FMEPDL - return + // invocationSite.isTypeAccess(); + } + if (currentType == receiverType + || currentType + .isSuperclassOf((ReferenceBinding) receiverType)) { + if (depth > 0) + invocationSite.setDepth(depth); + return true; + } } - if (isStatic()){ - return true; // see 1FMEPDL - return invocationSite.isTypeAccess(); + depth++; + currentType = currentType.enclosingType(); + } while (currentType != null); + return false; + } + + if (isPrivate()) { + // answer true if the receiverType is the declaringClass + // AND the invocationType and the declaringClass have a common + // enclosingType + if (receiverType != declaringClass) + return false; + + if (invocationType != declaringClass) { + ReferenceBinding outerInvocationType = invocationType; + ReferenceBinding temp = outerInvocationType.enclosingType(); + while (temp != null) { + outerInvocationType = temp; + temp = temp.enclosingType(); } - if (currentType == receiverType || currentType.isSuperclassOf((ReferenceBinding) receiverType)){ - if (depth > 0) invocationSite.setDepth(depth); - return true; + + ReferenceBinding outerDeclaringClass = declaringClass; + temp = outerDeclaringClass.enclosingType(); + while (temp != null) { + outerDeclaringClass = temp; + temp = temp.enclosingType(); } + if (outerInvocationType != outerDeclaringClass) + return false; } - depth++; - currentType = currentType.enclosingType(); - } while (currentType != null); + return true; + } + + // isDefault() + if (invocationType.fPackage != declaringClass.fPackage) + return false; + + // receiverType can be an array binding in one case... see if you can + // change it + if (receiverType instanceof ArrayBinding) + return false; + ReferenceBinding type = (ReferenceBinding) receiverType; + PackageBinding declaringPackage = declaringClass.fPackage; + do { + if (declaringClass == type) + return true; + if (declaringPackage != type.fPackage) + return false; + } while ((type = type.superclass()) != null); return false; } - if (isPrivate()) { - // answer true if the receiverType is the declaringClass - // AND the invocationType and the declaringClass have a common enclosingType - if (receiverType != declaringClass) return false; - - if (invocationType != declaringClass) { - ReferenceBinding outerInvocationType = invocationType; - ReferenceBinding temp = outerInvocationType.enclosingType(); - while (temp != null) { - outerInvocationType = temp; - temp = temp.enclosingType(); - } + public final int getAccessFlags() { + return modifiers & AccJustFlag; + } - ReferenceBinding outerDeclaringClass = declaringClass; - temp = outerDeclaringClass.enclosingType(); - while (temp != null) { - outerDeclaringClass = temp; - temp = temp.enclosingType(); - } - if (outerInvocationType != outerDeclaringClass) return false; - } - return true; + /* + * Answer true if the receiver has default visibility + */ + + public final boolean isDefault() { + return !isPublic() && !isProtected() && !isPrivate(); } - // isDefault() - if (invocationType.fPackage != declaringClass.fPackage) return false; + /* + * Answer true if the receiver is a deprecated field + */ - // receiverType can be an array binding in one case... see if you can change it - if (receiverType instanceof ArrayBinding) - return false; - ReferenceBinding type = (ReferenceBinding) receiverType; - PackageBinding declaringPackage = declaringClass.fPackage; - do { - if (declaringClass == type) return true; - if (declaringPackage != type.fPackage) return false; - } while ((type = type.superclass()) != null); - return false; -} -public final int getAccessFlags() { - return modifiers & AccJustFlag; -} + public final boolean isDeprecated() { + return (modifiers & AccDeprecated) != 0; + } -/* Answer true if the receiver has default visibility -*/ + /* + * Answer true if the receiver has private visibility + */ -public final boolean isDefault() { - return !isPublic() && !isProtected() && !isPrivate(); -} -/* Answer true if the receiver is a deprecated field -*/ + public final boolean isPrivate() { + return (modifiers & AccPrivate) != 0; + } -public final boolean isDeprecated() { - return (modifiers & AccDeprecated) != 0; -} -/* Answer true if the receiver has private visibility -*/ + /* + * Answer true if the receiver has private visibility and is used locally + */ -public final boolean isPrivate() { - return (modifiers & AccPrivate) != 0; -} -/* Answer true if the receiver has private visibility and is used locally -*/ + public final boolean isPrivateUsed() { + return (modifiers & AccPrivateUsed) != 0; + } -public final boolean isPrivateUsed() { - return (modifiers & AccPrivateUsed) != 0; -} -/* Answer true if the receiver has protected visibility -*/ + /* + * Answer true if the receiver has protected visibility + */ -public final boolean isProtected() { - return (modifiers & AccProtected) != 0; -} -/* Answer true if the receiver has public visibility -*/ + public final boolean isProtected() { + return (modifiers & AccProtected) != 0; + } -public final boolean isPublic() { - return (modifiers & AccPublic) != 0; -} -/* Answer true if the receiver is a static field -*/ + /* + * Answer true if the receiver has public visibility + */ -public final boolean isStatic() { - return (modifiers & AccStatic) != 0; -} -/* Answer true if the receiver is not defined in the source of the declaringClass -*/ - -//public final boolean isSynthetic() { -// return (modifiers & AccSynthetic) != 0; -//} -/* Answer true if the receiver is a transient field -*/ - -//public final boolean isTransient() { -// return (modifiers & AccTransient) != 0; -//} -/* Answer true if the receiver's declaring type is deprecated (or any of its enclosing types) -*/ - -public final boolean isViewedAsDeprecated() { - return (modifiers & AccDeprecated) != 0 || - (modifiers & AccDeprecatedImplicitly) != 0; -} -/* Answer true if the receiver is a volatile field -*/ + public final boolean isPublic() { + return (modifiers & AccPublic) != 0; + } + + /* + * Answer true if the receiver is a static field + */ + + public final boolean isStatic() { + return (modifiers & AccStatic) != 0; + } + + /* + * Answer true if the receiver is not defined in the source of the + * declaringClass + */ + + // public final boolean isSynthetic() { + // return (modifiers & AccSynthetic) != 0; + // } + /* + * Answer true if the receiver is a transient field + */ + + // public final boolean isTransient() { + // return (modifiers & AccTransient) != 0; + // } + /* + * Answer true if the receiver's declaring type is deprecated (or any of its + * enclosing types) + */ + + public final boolean isViewedAsDeprecated() { + return (modifiers & AccDeprecated) != 0 + || (modifiers & AccDeprecatedImplicitly) != 0; + } + /* + * Answer true if the receiver is a volatile field + */ -//public final boolean isVolatile() { -// return (modifiers & AccVolatile) != 0; -//} + // public final boolean isVolatile() { + // return (modifiers & AccVolatile) != 0; + // } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ImportBinding.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ImportBinding.java index b226412..2ad87a5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ImportBinding.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ImportBinding.java @@ -15,31 +15,38 @@ import net.sourceforge.phpdt.internal.compiler.ast.ImportReference; public class ImportBinding extends Binding { public char[][] compoundName; + public boolean onDemand; + public ImportReference reference; Binding resolvedImport; // must ensure the import is resolved - -public ImportBinding(char[][] compoundName, boolean isOnDemand, Binding binding, ImportReference reference) { - this.compoundName = compoundName; - this.onDemand = isOnDemand; - this.resolvedImport = binding; - this.reference = reference; -} -/* API -* Answer the receiver's binding type from Binding.BindingID. -*/ -public final int bindingType() { - return IMPORT; -} -public char[] readableName() { - if (onDemand) - return CharOperation.concat(CharOperation.concatWith(compoundName, '.'), ".*".toCharArray()); //$NON-NLS-1$ - else - return CharOperation.concatWith(compoundName, '.'); -} -public String toString() { - return "include : " + new String(readableName()); //$NON-NLS-1$ -} + public ImportBinding(char[][] compoundName, boolean isOnDemand, + Binding binding, ImportReference reference) { + this.compoundName = compoundName; + this.onDemand = isOnDemand; + this.resolvedImport = binding; + this.reference = reference; + } + + /* + * API Answer the receiver's binding type from Binding.BindingID. + */ + + public final int bindingType() { + return IMPORT; + } + + public char[] readableName() { + if (onDemand) + return CharOperation.concat(CharOperation.concatWith(compoundName, + '.'), ".*".toCharArray()); //$NON-NLS-1$ + else + return CharOperation.concatWith(compoundName, '.'); + } + + public String toString() { + return "include : " + new String(readableName()); //$NON-NLS-1$ + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/InnerEmulationDependency.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/InnerEmulationDependency.java index 0a7071d..9f67057 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/InnerEmulationDependency.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/InnerEmulationDependency.java @@ -10,12 +10,14 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.compiler.lookup; -public class InnerEmulationDependency{ +public class InnerEmulationDependency { public BlockScope scope; + public boolean wasEnclosingInstanceSupplied; - - public InnerEmulationDependency(BlockScope scope, boolean wasEnclosingInstanceSupplied) { + + public InnerEmulationDependency(BlockScope scope, + boolean wasEnclosingInstanceSupplied) { this.scope = scope; this.wasEnclosingInstanceSupplied = wasEnclosingInstanceSupplied; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/InvocationSite.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/InvocationSite.java index af3ec22..42638ee 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/InvocationSite.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/InvocationSite.java @@ -12,13 +12,16 @@ package net.sourceforge.phpdt.internal.compiler.lookup; public interface InvocationSite { boolean isSuperAccess(); + boolean isTypeAccess(); + void setDepth(int depth); + void setFieldIndex(int depth); - - // in case the receiver type does not match the actual receiver type - // e.g. pkg.Type.C (receiver type of C is type of source context, - // but actual receiver type is pkg.Type) + + // in case the receiver type does not match the actual receiver type + // e.g. pkg.Type.C (receiver type of C is type of source context, + // but actual receiver type is pkg.Type) // e.g2. in presence of implicit access to enclosing type void setActualReceiverType(ReferenceBinding receiverType); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/LocalTypeBinding.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/LocalTypeBinding.java index 438e006..e31d1b2 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/LocalTypeBinding.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/LocalTypeBinding.java @@ -18,129 +18,151 @@ public final class LocalTypeBinding extends NestedTypeBinding { final static char[] LocalTypePrefix = { '$', 'L', 'o', 'c', 'a', 'l', '$' }; private InnerEmulationDependency[] dependents; - ArrayBinding[] localArrayBindings; // used to cache array bindings of various dimensions for this local type - -public LocalTypeBinding(ClassScope scope, SourceTypeBinding enclosingType) { - super( - new char[][] {CharOperation.concat(LocalTypePrefix, scope.referenceContext.name)}, - scope, - enclosingType); - - if (this.sourceName == AnonymousLocalTypeDeclaration.ANONYMOUS_EMPTY_NAME) - this.tagBits |= AnonymousTypeMask; - else - this.tagBits |= LocalTypeMask; -} -/* Record a dependency onto a source target type which may be altered -* by the end of the innerclass emulation. Later on, we will revisit -* all its dependents so as to update them (see updateInnerEmulationDependents()). -*/ - -public void addInnerEmulationDependent(BlockScope scope, boolean wasEnclosingInstanceSupplied) { - int index; - if (dependents == null) { - index = 0; - dependents = new InnerEmulationDependency[1]; - } else { - index = dependents.length; - for (int i = 0; i < index; i++) - if (dependents[i].scope == scope) - return; // already stored - System.arraycopy(dependents, 0, (dependents = new InnerEmulationDependency[index + 1]), 0, index); + + ArrayBinding[] localArrayBindings; // used to cache array bindings of + // various dimensions for this local + // type + + public LocalTypeBinding(ClassScope scope, SourceTypeBinding enclosingType) { + super(new char[][] { CharOperation.concat(LocalTypePrefix, + scope.referenceContext.name) }, scope, enclosingType); + + if (this.sourceName == AnonymousLocalTypeDeclaration.ANONYMOUS_EMPTY_NAME) + this.tagBits |= AnonymousTypeMask; + else + this.tagBits |= LocalTypeMask; } - dependents[index] = new InnerEmulationDependency(scope, wasEnclosingInstanceSupplied); - // System.out.println("Adding dependency: "+ new String(scope.enclosingType().readableName()) + " --> " + new String(this.readableName())); -} -/* Answer the receiver's constant pool name. -* -* NOTE: This method should only be used during/after code gen. -*/ -public char[] constantPoolName() /* java/lang/Object */ { - return constantPoolName; -} + /* + * Record a dependency onto a source target type which may be altered by the + * end of the innerclass emulation. Later on, we will revisit all its + * dependents so as to update them (see updateInnerEmulationDependents()). + */ + + public void addInnerEmulationDependent(BlockScope scope, + boolean wasEnclosingInstanceSupplied) { + int index; + if (dependents == null) { + index = 0; + dependents = new InnerEmulationDependency[1]; + } else { + index = dependents.length; + for (int i = 0; i < index; i++) + if (dependents[i].scope == scope) + return; // already stored + System.arraycopy(dependents, 0, + (dependents = new InnerEmulationDependency[index + 1]), 0, + index); + } + dependents[index] = new InnerEmulationDependency(scope, + wasEnclosingInstanceSupplied); + // System.out.println("Adding dependency: "+ new + // String(scope.enclosingType().readableName()) + " --> " + new + // String(this.readableName())); + } + + /* + * Answer the receiver's constant pool name. + * + * NOTE: This method should only be used during/after code gen. + */ -ArrayBinding createArrayType(int dimensionCount) { - if (localArrayBindings == null) { - localArrayBindings = new ArrayBinding[] {new ArrayBinding(this, dimensionCount)}; - return localArrayBindings[0]; + public char[] constantPoolName() /* java/lang/Object */{ + return constantPoolName; } - // find the cached array binding for this dimensionCount (if any) - int length = localArrayBindings.length; - for (int i = 0; i < length; i++) - if (localArrayBindings[i].dimensions == dimensionCount) - return localArrayBindings[i]; + ArrayBinding createArrayType(int dimensionCount) { + if (localArrayBindings == null) { + localArrayBindings = new ArrayBinding[] { new ArrayBinding(this, + dimensionCount) }; + return localArrayBindings[0]; + } - // no matching array - System.arraycopy(localArrayBindings, 0, localArrayBindings = new ArrayBinding[length + 1], 0, length); - return localArrayBindings[length] = new ArrayBinding(this, dimensionCount); -} + // find the cached array binding for this dimensionCount (if any) + int length = localArrayBindings.length; + for (int i = 0; i < length; i++) + if (localArrayBindings[i].dimensions == dimensionCount) + return localArrayBindings[i]; + + // no matching array + System.arraycopy(localArrayBindings, 0, + localArrayBindings = new ArrayBinding[length + 1], 0, length); + return localArrayBindings[length] = new ArrayBinding(this, + dimensionCount); + } -public char[] readableName() { - if (isAnonymousType()) { - if (superInterfaces == NoSuperInterfaces) - return ("<"+Util.bind("binding.subclass",new String(superclass.readableName())) + ">").toCharArray(); //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-1$ - else - return ("<"+Util.bind("binding.implementation",new String(superInterfaces[0].readableName())) + ">").toCharArray(); //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-1$ - } else if (isMemberType()) { - return CharOperation.concat(enclosingType().readableName(), sourceName, '.'); - } else { - return sourceName; + public char[] readableName() { + if (isAnonymousType()) { + if (superInterfaces == NoSuperInterfaces) + return ("<" + Util.bind("binding.subclass", new String(superclass.readableName())) + ">").toCharArray(); //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-1$ + else + return ("<" + Util.bind("binding.implementation", new String(superInterfaces[0].readableName())) + ">").toCharArray(); //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-1$ + } else if (isMemberType()) { + return CharOperation.concat(enclosingType().readableName(), + sourceName, '.'); + } else { + return sourceName; + } } -} -public char[] shortReadableName() { - if (isAnonymousType()) { - if (superInterfaces == NoSuperInterfaces) - return ("<"+Util.bind("binding.subclass",new String(superclass.shortReadableName())) + ">").toCharArray(); //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-1$ - else - return ("<"+Util.bind("binding.implementation",new String(superInterfaces[0].shortReadableName())) + ">").toCharArray(); //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-1$ - } else if (isMemberType()) { - return CharOperation.concat(enclosingType().shortReadableName(), sourceName, '.'); - } else { - return sourceName; + public char[] shortReadableName() { + if (isAnonymousType()) { + if (superInterfaces == NoSuperInterfaces) + return ("<" + Util.bind("binding.subclass", new String(superclass.shortReadableName())) + ">").toCharArray(); //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-1$ + else + return ("<" + Util.bind("binding.implementation", new String(superInterfaces[0].shortReadableName())) + ">").toCharArray(); //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-1$ + } else if (isMemberType()) { + return CharOperation.concat(enclosingType().shortReadableName(), + sourceName, '.'); + } else { + return sourceName; + } } -} -// Record that the type is a local member type -public void setAsMemberType() { - tagBits |= MemberTypeMask; -} + // Record that the type is a local member type + public void setAsMemberType() { + tagBits |= MemberTypeMask; + } -public void setConstantPoolName(char[] computedConstantPoolName) /* java/lang/Object */ { - this.constantPoolName = computedConstantPoolName; -} + public void setConstantPoolName(char[] computedConstantPoolName) /* java/lang/Object */{ + this.constantPoolName = computedConstantPoolName; + } -public char[] sourceName() { - if (isAnonymousType()) { - //return readableName(); - if (superInterfaces == NoSuperInterfaces) - return ("<"+Util.bind("binding.subclass",new String(superclass.sourceName())) + ">").toCharArray(); //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-1$ - else - return ("<"+Util.bind("binding.implementation",new String(superInterfaces[0].sourceName())) + ">").toCharArray(); //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-1$ - - } else - return sourceName; -} -public String toString() { - if (isAnonymousType()) - return "Anonymous type : " + super.toString(); //$NON-NLS-1$ - if (isMemberType()) - return "Local member type : " + new String(sourceName()) + " " + super.toString(); //$NON-NLS-2$ //$NON-NLS-1$ - return "Local type : " + new String(sourceName()) + " " + super.toString(); //$NON-NLS-2$ //$NON-NLS-1$ -} -/* Trigger the dependency mechanism forcing the innerclass emulation -* to be propagated to all dependent source types. -*/ - -public void updateInnerEmulationDependents() { - if (dependents != null) { - for (int i = 0; i < dependents.length; i++) { - InnerEmulationDependency dependency = dependents[i]; - // System.out.println("Updating " + new String(this.readableName()) + " --> " + new String(dependency.scope.enclosingType().readableName())); - dependency.scope.propagateInnerEmulation(this, dependency.wasEnclosingInstanceSupplied); + public char[] sourceName() { + if (isAnonymousType()) { + // return readableName(); + if (superInterfaces == NoSuperInterfaces) + return ("<" + Util.bind("binding.subclass", new String(superclass.sourceName())) + ">").toCharArray(); //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-1$ + else + return ("<" + Util.bind("binding.implementation", new String(superInterfaces[0].sourceName())) + ">").toCharArray(); //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-1$ + + } else + return sourceName; + } + + public String toString() { + if (isAnonymousType()) + return "Anonymous type : " + super.toString(); //$NON-NLS-1$ + if (isMemberType()) + return "Local member type : " + new String(sourceName()) + " " + super.toString(); //$NON-NLS-2$ //$NON-NLS-1$ + return "Local type : " + new String(sourceName()) + " " + super.toString(); //$NON-NLS-2$ //$NON-NLS-1$ + } + + /* + * Trigger the dependency mechanism forcing the innerclass emulation to be + * propagated to all dependent source types. + */ + + public void updateInnerEmulationDependents() { + if (dependents != null) { + for (int i = 0; i < dependents.length; i++) { + InnerEmulationDependency dependency = dependents[i]; + // System.out.println("Updating " + new + // String(this.readableName()) + " --> " + new + // String(dependency.scope.enclosingType().readableName())); + dependency.scope.propagateInnerEmulation(this, + dependency.wasEnclosingInstanceSupplied); + } } } } -} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/LocalVariableBinding.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/LocalVariableBinding.java index c69d11b..de53879 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/LocalVariableBinding.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/LocalVariableBinding.java @@ -16,21 +16,29 @@ import net.sourceforge.phpdt.internal.compiler.impl.Constant; public class LocalVariableBinding extends VariableBinding { public boolean isArgument; - public int resolvedPosition; // for code generation (position in method context) - + + public int resolvedPosition; // for code generation (position in method + // context) + public static final int UNUSED = 0; + public static final int USED = 1; + public static final int FAKE_USED = 2; + public int useFlag; // for flow analysis (default is UNUSED) - + public BlockScope declaringScope; // back-pointer to its declaring scope + public LocalDeclaration declaration; // for source-positions public int[] initializationPCs; + public int initializationCount = 0; - // for synthetic local variables - public LocalVariableBinding(char[] name, TypeBinding type, int modifiers, boolean isArgument) { + // for synthetic local variables + public LocalVariableBinding(char[] name, TypeBinding type, int modifiers, + boolean isArgument) { this.name = name; this.type = type; @@ -38,23 +46,25 @@ public class LocalVariableBinding extends VariableBinding { if (this.isArgument = isArgument) this.constant = Constant.NotAConstant; } - + // regular local variable or argument - public LocalVariableBinding(LocalDeclaration declaration, TypeBinding type, int modifiers, boolean isArgument) { + public LocalVariableBinding(LocalDeclaration declaration, TypeBinding type, + int modifiers, boolean isArgument) { this(declaration.name, type, modifiers, isArgument); this.declaration = declaration; } - /* API - * Answer the receiver's binding type from Binding.BindingID. - */ + /* + * API Answer the receiver's binding type from Binding.BindingID. + */ public final int bindingType() { return LOCAL; } - - // Answer whether the variable binding is a secret variable added for code gen purposes + + // Answer whether the variable binding is a secret variable added for code + // gen purposes public boolean isSecret() { return declaration == null && !isArgument; @@ -68,14 +78,28 @@ public class LocalVariableBinding extends VariableBinding { public void recordInitializationStartPC(int pc) { - if (initializationPCs == null) return; + if (initializationPCs == null) + return; // optimize cases where reopening a contiguous interval - if ((initializationCount > 0) && (initializationPCs[ ((initializationCount - 1) << 1) + 1] == pc)) { - initializationPCs[ ((initializationCount - 1) << 1) + 1] = -1; // reuse previous interval (its range will be augmented) + if ((initializationCount > 0) + && (initializationPCs[((initializationCount - 1) << 1) + 1] == pc)) { + initializationPCs[((initializationCount - 1) << 1) + 1] = -1; // reuse + // previous + // interval + // (its + // range + // will + // be + // augmented) } else { int index = initializationCount << 1; if (index == initializationPCs.length) { - System.arraycopy(initializationPCs, 0, (initializationPCs = new int[initializationCount << 2]), 0, index); + System + .arraycopy( + initializationPCs, + 0, + (initializationPCs = new int[initializationCount << 2]), + 0, index); } initializationPCs[index] = pc; initializationPCs[index + 1] = -1; @@ -86,16 +110,16 @@ public class LocalVariableBinding extends VariableBinding { public String toString() { String s = super.toString(); - switch (useFlag){ - case USED: - s += "[pos: " + String.valueOf(resolvedPosition) + "]"; //$NON-NLS-2$ //$NON-NLS-1$ - break; - case UNUSED: - s += "[pos: unused]"; //$NON-NLS-1$ - break; - case FAKE_USED: - s += "[pos: fake_used]"; //$NON-NLS-1$ - break; + switch (useFlag) { + case USED: + s += "[pos: " + String.valueOf(resolvedPosition) + "]"; //$NON-NLS-2$ //$NON-NLS-1$ + break; + case UNUSED: + s += "[pos: unused]"; //$NON-NLS-1$ + break; + case FAKE_USED: + s += "[pos: fake_used]"; //$NON-NLS-1$ + break; } s += "[id:" + String.valueOf(id) + "]"; //$NON-NLS-2$ //$NON-NLS-1$ if (initializationCount > 0) { @@ -103,7 +127,8 @@ public class LocalVariableBinding extends VariableBinding { for (int i = 0; i < initializationCount; i++) { if (i > 0) s += ", "; //$NON-NLS-1$ - s += String.valueOf(initializationPCs[i << 1]) + "-" + ((initializationPCs[(i << 1) + 1] == -1) ? "?" : String.valueOf(initializationPCs[(i<< 1) + 1])); //$NON-NLS-2$ //$NON-NLS-1$ + s += String.valueOf(initializationPCs[i << 1]) + + "-" + ((initializationPCs[(i << 1) + 1] == -1) ? "?" : String.valueOf(initializationPCs[(i << 1) + 1])); //$NON-NLS-2$ //$NON-NLS-1$ } s += "]"; //$NON-NLS-1$ } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/LookupEnvironment.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/LookupEnvironment.java index 54e6de2..bbe5a89 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/LookupEnvironment.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/LookupEnvironment.java @@ -20,23 +20,35 @@ import net.sourceforge.phpdt.internal.compiler.problem.ProblemReporter; import net.sourceforge.phpdt.internal.compiler.util.HashtableOfPackage; import net.sourceforge.phpdt.internal.compiler.util.Util; -public class LookupEnvironment implements BaseTypes, ProblemReasons, TypeConstants { -// public CompilerOptions options; +public class LookupEnvironment implements BaseTypes, ProblemReasons, + TypeConstants { + // public CompilerOptions options; public ProblemReporter problemReporter; + public ITypeRequestor typeRequestor; PackageBinding defaultPackage; + ImportBinding[] defaultImports; + HashtableOfPackage knownPackages; - static final ProblemPackageBinding TheNotFoundPackage = new ProblemPackageBinding(CharOperation.NO_CHAR, NotFound); - static final ProblemReferenceBinding TheNotFoundType = new ProblemReferenceBinding(CharOperation.NO_CHAR, NotFound); + + static final ProblemPackageBinding TheNotFoundPackage = new ProblemPackageBinding( + CharOperation.NO_CHAR, NotFound); + + static final ProblemReferenceBinding TheNotFoundType = new ProblemReferenceBinding( + CharOperation.NO_CHAR, NotFound); private INameEnvironment nameEnvironment; + private MethodVerifier verifier; + private ArrayBinding[][] uniqueArrayBindings; private CompilationUnitDeclaration[] units = new CompilationUnitDeclaration[4]; + private int lastUnitIndex = -1; + private int lastCompletedUnitIndex = -1; // indicate in which step on the compilation we are. @@ -44,542 +56,655 @@ public class LookupEnvironment implements BaseTypes, ProblemReasons, TypeConstan // step 2 : conect the hierarchy (connect bindings) // step 3 : build fields and method bindings. private int stepCompleted; + final static int BUILD_TYPE_HIERARCHY = 1; + final static int CHECK_AND_SET_IMPORTS = 2; + final static int CONNECT_TYPE_HIERARCHY = 3; + final static int BUILD_FIELDS_AND_METHODS = 4; -public LookupEnvironment(ITypeRequestor typeRequestor,ProblemReporter problemReporter, INameEnvironment nameEnvironment) { -// CompilerOptions options, ProblemReporter problemReporter, INameEnvironment nameEnvironment) { - this.typeRequestor = typeRequestor; -// this.options = options; - this.problemReporter = problemReporter; - this.defaultPackage = new PackageBinding(this); // assume the default package always exists - this.defaultImports = null; - this.nameEnvironment = nameEnvironment; - this.knownPackages = new HashtableOfPackage(); - this.uniqueArrayBindings = new ArrayBinding[5][]; - this.uniqueArrayBindings[0] = new ArrayBinding[50]; // start off the most common 1 dimension array @ 50 -} -/* Ask the oracle for a type which corresponds to the compoundName. -* Answer null if the name cannot be found. -*/ -public ReferenceBinding askForType(char[][] compoundName) { - NameEnvironmentAnswer answer = nameEnvironment.findType(compoundName); - if (answer == null) - return null; + public LookupEnvironment(ITypeRequestor typeRequestor, + ProblemReporter problemReporter, INameEnvironment nameEnvironment) { + // CompilerOptions options, ProblemReporter problemReporter, + // INameEnvironment nameEnvironment) { + this.typeRequestor = typeRequestor; + // this.options = options; + this.problemReporter = problemReporter; + this.defaultPackage = new PackageBinding(this); // assume the default + // package always exists + this.defaultImports = null; + this.nameEnvironment = nameEnvironment; + this.knownPackages = new HashtableOfPackage(); + this.uniqueArrayBindings = new ArrayBinding[5][]; + this.uniqueArrayBindings[0] = new ArrayBinding[50]; // start off the + // most common 1 + // dimension array @ + // 50 + } - if (answer.isBinaryType()) - // the type was found as a .class file - typeRequestor.accept(answer.getBinaryType(), computePackageFrom(compoundName)); - else if (answer.isCompilationUnit()) - // the type was found as a .java file, try to build it then search the cache - typeRequestor.accept(answer.getCompilationUnit()); - else if (answer.isSourceType()) - // the type was found as a source model - typeRequestor.accept(answer.getSourceTypes(), computePackageFrom(compoundName)); - - return getCachedType(compoundName); -} -/* Ask the oracle for a type named name in the packageBinding. -* Answer null if the name cannot be found. -*/ + /* + * Ask the oracle for a type which corresponds to the compoundName. Answer + * null if the name cannot be found. + */ -ReferenceBinding askForType(PackageBinding packageBinding, char[] name) { - if (packageBinding == null) { - if (defaultPackage == null) + public ReferenceBinding askForType(char[][] compoundName) { + NameEnvironmentAnswer answer = nameEnvironment.findType(compoundName); + if (answer == null) return null; - packageBinding = defaultPackage; + + if (answer.isBinaryType()) + // the type was found as a .class file + typeRequestor.accept(answer.getBinaryType(), + computePackageFrom(compoundName)); + else if (answer.isCompilationUnit()) + // the type was found as a .java file, try to build it then search + // the cache + typeRequestor.accept(answer.getCompilationUnit()); + else if (answer.isSourceType()) + // the type was found as a source model + typeRequestor.accept(answer.getSourceTypes(), + computePackageFrom(compoundName)); + + return getCachedType(compoundName); } - NameEnvironmentAnswer answer = nameEnvironment.findType(name, packageBinding.compoundName); - if (answer == null) - return null; - if (answer.isBinaryType()) - // the type was found as a .class file - typeRequestor.accept(answer.getBinaryType(), packageBinding); - else if (answer.isCompilationUnit()) - // the type was found as a .java file, try to build it then search the cache - typeRequestor.accept(answer.getCompilationUnit()); - else if (answer.isSourceType()) - // the type was found as a source model - typeRequestor.accept(answer.getSourceTypes(), packageBinding); - - return packageBinding.getType0(name); -} -/* Create the initial type bindings for the compilation unit. -* -* See completeTypeBindings() for a description of the remaining steps -* -* NOTE: This method can be called multiple times as additional source files are needed -*/ - -public void buildTypeBindings(CompilationUnitDeclaration unit) { - CompilationUnitScope scope = new CompilationUnitScope(unit, this); - scope.buildTypeBindings(); - - int unitsLength = units.length; - if (++lastUnitIndex >= unitsLength) - System.arraycopy(units, 0, units = new CompilationUnitDeclaration[2 * unitsLength], 0, unitsLength); - units[lastUnitIndex] = unit; -} -/* Cache the binary type since we know it is needed during this compile. -* -* Answer the created BinaryTypeBinding or null if the type is already in the cache. -*/ + /* + * Ask the oracle for a type named name in the packageBinding. Answer null + * if the name cannot be found. + */ -public BinaryTypeBinding cacheBinaryType(IBinaryType binaryType) { - return cacheBinaryType(binaryType, true); -} -/* Cache the binary type since we know it is needed during this compile. -* -* Answer the created BinaryTypeBinding or null if the type is already in the cache. -*/ - -public BinaryTypeBinding cacheBinaryType(IBinaryType binaryType, boolean needFieldsAndMethods) { - char[][] compoundName = CharOperation.splitOn('/', binaryType.getName()); - ReferenceBinding existingType = getCachedType(compoundName); - - if (existingType == null || existingType instanceof UnresolvedReferenceBinding) - // only add the binary type if its not already in the cache - return createBinaryTypeFrom(binaryType, computePackageFrom(compoundName), needFieldsAndMethods); - return null; // the type already exists & can be retrieved from the cache -} -/* -* 1. Connect the type hierarchy for the type bindings created for parsedUnits. -* 2. Create the field bindings -* 3. Create the method bindings -*/ - -/* We know each known compilationUnit is free of errors at this point... -* -* Each step will create additional bindings unless a problem is detected, in which -* case either the faulty import/superinterface/field/method will be skipped or a -* suitable replacement will be substituted (such as Object for a missing superclass) -*/ - -public void completeTypeBindings() { - stepCompleted = BUILD_TYPE_HIERARCHY; - -// for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { -// units[i].scope.checkAndSetImports(); -// } - stepCompleted = CHECK_AND_SET_IMPORTS; - -// for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { -// units[i].scope.connectTypeHierarchy(); -// } - stepCompleted = CONNECT_TYPE_HIERARCHY; - - for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { -// units[i].scope.buildFieldsAndMethods(); - units[i] = null; // release unnecessary reference to the parsed unit + ReferenceBinding askForType(PackageBinding packageBinding, char[] name) { + if (packageBinding == null) { + if (defaultPackage == null) + return null; + packageBinding = defaultPackage; + } + NameEnvironmentAnswer answer = nameEnvironment.findType(name, + packageBinding.compoundName); + if (answer == null) + return null; + + if (answer.isBinaryType()) + // the type was found as a .class file + typeRequestor.accept(answer.getBinaryType(), packageBinding); + else if (answer.isCompilationUnit()) + // the type was found as a .java file, try to build it then search + // the cache + typeRequestor.accept(answer.getCompilationUnit()); + else if (answer.isSourceType()) + // the type was found as a source model + typeRequestor.accept(answer.getSourceTypes(), packageBinding); + + return packageBinding.getType0(name); } - stepCompleted = BUILD_FIELDS_AND_METHODS; - lastCompletedUnitIndex = lastUnitIndex; -} -/* -* 1. Connect the type hierarchy for the type bindings created for parsedUnits. -* 2. Create the field bindings -* 3. Create the method bindings -*/ - -/* -* Each step will create additional bindings unless a problem is detected, in which -* case either the faulty import/superinterface/field/method will be skipped or a -* suitable replacement will be substituted (such as Object for a missing superclass) -*/ - -public void completeTypeBindings(CompilationUnitDeclaration parsedUnit) { - if (stepCompleted == BUILD_FIELDS_AND_METHODS) { - // This can only happen because the original set of units are completely built and - // are now being processed, so we want to treat all the additional units as a group - // until they too are completely processed. - completeTypeBindings(); - } else { - if (parsedUnit.scope == null) return; // parsing errors were too severe - -// if (stepCompleted >= CHECK_AND_SET_IMPORTS) -// parsedUnit.scope.checkAndSetImports(); - - if (stepCompleted >= CONNECT_TYPE_HIERARCHY) - parsedUnit.scope.connectTypeHierarchy(); + + /* + * Create the initial type bindings for the compilation unit. + * + * See completeTypeBindings() for a description of the remaining steps + * + * NOTE: This method can be called multiple times as additional source files + * are needed + */ + + public void buildTypeBindings(CompilationUnitDeclaration unit) { + CompilationUnitScope scope = new CompilationUnitScope(unit, this); + scope.buildTypeBindings(); + + int unitsLength = units.length; + if (++lastUnitIndex >= unitsLength) + System.arraycopy(units, 0, + units = new CompilationUnitDeclaration[2 * unitsLength], 0, + unitsLength); + units[lastUnitIndex] = unit; } -} -/* -* Used by other compiler tools which do not start by calling completeTypeBindings(). -* -* 1. Connect the type hierarchy for the type bindings created for parsedUnits. -* 2. Create the field bindings -* 3. Create the method bindings -*/ - -public void completeTypeBindings(CompilationUnitDeclaration parsedUnit, boolean buildFieldsAndMethods) { - if (parsedUnit.scope == null) return; // parsing errors were too severe - - parsedUnit.scope.checkAndSetImports(); - parsedUnit.scope.connectTypeHierarchy(); - - if (buildFieldsAndMethods) - parsedUnit.scope.buildFieldsAndMethods(); -} -private PackageBinding computePackageFrom(char[][] constantPoolName) { - if (constantPoolName.length == 1) - return defaultPackage; + /* + * Cache the binary type since we know it is needed during this compile. + * + * Answer the created BinaryTypeBinding or null if the type is already in + * the cache. + */ - PackageBinding packageBinding = getPackage0(constantPoolName[0]); - if (packageBinding == null || packageBinding == TheNotFoundPackage) { - packageBinding = new PackageBinding(constantPoolName[0], this); - knownPackages.put(constantPoolName[0], packageBinding); + public BinaryTypeBinding cacheBinaryType(IBinaryType binaryType) { + return cacheBinaryType(binaryType, true); } - for (int i = 1, length = constantPoolName.length - 1; i < length; i++) { - PackageBinding parent = packageBinding; - if ((packageBinding = parent.getPackage0(constantPoolName[i])) == null || packageBinding == TheNotFoundPackage) { - packageBinding = new PackageBinding(CharOperation.subarray(constantPoolName, 0, i + 1), parent, this); - parent.addPackage(packageBinding); - } + /* + * Cache the binary type since we know it is needed during this compile. + * + * Answer the created BinaryTypeBinding or null if the type is already in + * the cache. + */ + + public BinaryTypeBinding cacheBinaryType(IBinaryType binaryType, + boolean needFieldsAndMethods) { + char[][] compoundName = CharOperation + .splitOn('/', binaryType.getName()); + ReferenceBinding existingType = getCachedType(compoundName); + + if (existingType == null + || existingType instanceof UnresolvedReferenceBinding) + // only add the binary type if its not already in the cache + return createBinaryTypeFrom(binaryType, + computePackageFrom(compoundName), needFieldsAndMethods); + return null; // the type already exists & can be retrieved from the + // cache } - return packageBinding; -} -/* Used to guarantee array type identity. -*/ - -ArrayBinding createArrayType(TypeBinding type, int dimensionCount) { - if (type instanceof LocalTypeBinding) // cache local type arrays with the local type itself - return ((LocalTypeBinding) type).createArrayType(dimensionCount); - - // find the array binding cache for this dimension - int dimIndex = dimensionCount - 1; - int length = uniqueArrayBindings.length; - ArrayBinding[] arrayBindings; - if (dimIndex < length) { - if ((arrayBindings = uniqueArrayBindings[dimIndex]) == null) - uniqueArrayBindings[dimIndex] = arrayBindings = new ArrayBinding[10]; - } else { - System.arraycopy( - uniqueArrayBindings, 0, - uniqueArrayBindings = new ArrayBinding[dimensionCount][], 0, - length); - uniqueArrayBindings[dimIndex] = arrayBindings = new ArrayBinding[10]; + + /* + * 1. Connect the type hierarchy for the type bindings created for + * parsedUnits. 2. Create the field bindings 3. Create the method bindings + */ + + /* + * We know each known compilationUnit is free of errors at this point... + * + * Each step will create additional bindings unless a problem is detected, + * in which case either the faulty import/superinterface/field/method will + * be skipped or a suitable replacement will be substituted (such as Object + * for a missing superclass) + */ + + public void completeTypeBindings() { + stepCompleted = BUILD_TYPE_HIERARCHY; + + // for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { + // units[i].scope.checkAndSetImports(); + // } + stepCompleted = CHECK_AND_SET_IMPORTS; + + // for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { + // units[i].scope.connectTypeHierarchy(); + // } + stepCompleted = CONNECT_TYPE_HIERARCHY; + + for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { + // units[i].scope.buildFieldsAndMethods(); + units[i] = null; // release unnecessary reference to the parsed + // unit + } + stepCompleted = BUILD_FIELDS_AND_METHODS; + lastCompletedUnitIndex = lastUnitIndex; } - // find the cached array binding for this leaf component type (if any) - int index = -1; - length = arrayBindings.length; - while (++index < length) { - ArrayBinding currentBinding = arrayBindings[index]; - if (currentBinding == null) // no matching array, but space left - return arrayBindings[index] = new ArrayBinding(type, dimensionCount); - if (currentBinding.leafComponentType == type) - return currentBinding; + /* + * 1. Connect the type hierarchy for the type bindings created for + * parsedUnits. 2. Create the field bindings 3. Create the method bindings + */ + + /* + * Each step will create additional bindings unless a problem is detected, + * in which case either the faulty import/superinterface/field/method will + * be skipped or a suitable replacement will be substituted (such as Object + * for a missing superclass) + */ + + public void completeTypeBindings(CompilationUnitDeclaration parsedUnit) { + if (stepCompleted == BUILD_FIELDS_AND_METHODS) { + // This can only happen because the original set of units are + // completely built and + // are now being processed, so we want to treat all the additional + // units as a group + // until they too are completely processed. + completeTypeBindings(); + } else { + if (parsedUnit.scope == null) + return; // parsing errors were too severe + + // if (stepCompleted >= CHECK_AND_SET_IMPORTS) + // parsedUnit.scope.checkAndSetImports(); + + if (stepCompleted >= CONNECT_TYPE_HIERARCHY) + parsedUnit.scope.connectTypeHierarchy(); + } } - // no matching array, no space left - System.arraycopy( - arrayBindings, 0, - (arrayBindings = new ArrayBinding[length * 2]), 0, - length); - uniqueArrayBindings[dimIndex] = arrayBindings; - return arrayBindings[length] = new ArrayBinding(type, dimensionCount); -} -public BinaryTypeBinding createBinaryTypeFrom(IBinaryType binaryType, PackageBinding packageBinding) { - return createBinaryTypeFrom(binaryType, packageBinding, true); -} -public BinaryTypeBinding createBinaryTypeFrom(IBinaryType binaryType, PackageBinding packageBinding, boolean needFieldsAndMethods) { - BinaryTypeBinding binaryBinding = new BinaryTypeBinding(packageBinding, binaryType, this); - - // resolve any array bindings which reference the unresolvedType - ReferenceBinding cachedType = packageBinding.getType0(binaryBinding.compoundName[binaryBinding.compoundName.length - 1]); - if (cachedType != null) { - if (cachedType.isBinaryBinding()) // sanity check before the cast... at this point the cache should ONLY contain unresolved types - return (BinaryTypeBinding) cachedType; - - UnresolvedReferenceBinding unresolvedType = (UnresolvedReferenceBinding) cachedType; - unresolvedType.resolvedType = binaryBinding; - updateArrayCache(unresolvedType, binaryBinding); + /* + * Used by other compiler tools which do not start by calling + * completeTypeBindings(). + * + * 1. Connect the type hierarchy for the type bindings created for + * parsedUnits. 2. Create the field bindings 3. Create the method bindings + */ + + public void completeTypeBindings(CompilationUnitDeclaration parsedUnit, + boolean buildFieldsAndMethods) { + if (parsedUnit.scope == null) + return; // parsing errors were too severe + + parsedUnit.scope.checkAndSetImports(); + parsedUnit.scope.connectTypeHierarchy(); + + if (buildFieldsAndMethods) + parsedUnit.scope.buildFieldsAndMethods(); } - packageBinding.addType(binaryBinding); - binaryBinding.cachePartsFrom(binaryType, needFieldsAndMethods); - return binaryBinding; -} -/* Used to create packages from the package statement. -*/ - -PackageBinding createPackage(char[][] compoundName) { - return null; -// PackageBinding packageBinding = getPackage0(compoundName[0]); -// if (packageBinding == null || packageBinding == TheNotFoundPackage) { -// packageBinding = new PackageBinding(compoundName[0], this); -// knownPackages.put(compoundName[0], packageBinding); -// } -// -// for (int i = 1, length = compoundName.length; i < length; i++) { -// // check to see if it collides with a known type... -// // this case can only happen if the package does not exist as a directory in the file system -// // otherwise when the source type was defined, the correct error would have been reported -// // unless its an unresolved type which is referenced from an inconsistent class file -// ReferenceBinding type = packageBinding.getType0(compoundName[i]); -// if (type != null && type != TheNotFoundType && !(type instanceof UnresolvedReferenceBinding)) -// return null; -// -// PackageBinding parent = packageBinding; -// if ((packageBinding = parent.getPackage0(compoundName[i])) == null || packageBinding == TheNotFoundPackage) { -// // if the package is unknown, check to see if a type exists which would collide with the new package -// // catches the case of a package statement of: package java.lang.Object; -// // since the package can be added after a set of source files have already been compiled, we need -// // whenever a package statement is encountered -// if (nameEnvironment.findType(compoundName[i], parent.compoundName) != null) -// return null; -// -// packageBinding = new PackageBinding(CharOperation.subarray(compoundName, 0, i + 1), parent, this); -// parent.addPackage(packageBinding); -// } -// } -// return packageBinding; -} -/* Answer the type for the compoundName if it exists in the cache. -* Answer theNotFoundType if it could not be resolved the first time -* it was looked up, otherwise answer null. -* -* NOTE: Do not use for nested types... the answer is NOT the same for a.b.C or a.b.C.D.E -* assuming C is a type in both cases. In the a.b.C.D.E case, null is the answer. -*/ - -public ReferenceBinding getCachedType(char[][] compoundName) { - if (compoundName.length == 1) { - if (defaultPackage == null) - return null; - return defaultPackage.getType0(compoundName[0]); + private PackageBinding computePackageFrom(char[][] constantPoolName) { + if (constantPoolName.length == 1) + return defaultPackage; + + PackageBinding packageBinding = getPackage0(constantPoolName[0]); + if (packageBinding == null || packageBinding == TheNotFoundPackage) { + packageBinding = new PackageBinding(constantPoolName[0], this); + knownPackages.put(constantPoolName[0], packageBinding); + } + + for (int i = 1, length = constantPoolName.length - 1; i < length; i++) { + PackageBinding parent = packageBinding; + if ((packageBinding = parent.getPackage0(constantPoolName[i])) == null + || packageBinding == TheNotFoundPackage) { + packageBinding = new PackageBinding(CharOperation.subarray( + constantPoolName, 0, i + 1), parent, this); + parent.addPackage(packageBinding); + } + } + return packageBinding; } - PackageBinding packageBinding = getPackage0(compoundName[0]); - if (packageBinding == null || packageBinding == TheNotFoundPackage) - return null; + /* + * Used to guarantee array type identity. + */ + + ArrayBinding createArrayType(TypeBinding type, int dimensionCount) { + if (type instanceof LocalTypeBinding) // cache local type arrays with + // the local type itself + return ((LocalTypeBinding) type).createArrayType(dimensionCount); + + // find the array binding cache for this dimension + int dimIndex = dimensionCount - 1; + int length = uniqueArrayBindings.length; + ArrayBinding[] arrayBindings; + if (dimIndex < length) { + if ((arrayBindings = uniqueArrayBindings[dimIndex]) == null) + uniqueArrayBindings[dimIndex] = arrayBindings = new ArrayBinding[10]; + } else { + System.arraycopy(uniqueArrayBindings, 0, + uniqueArrayBindings = new ArrayBinding[dimensionCount][], + 0, length); + uniqueArrayBindings[dimIndex] = arrayBindings = new ArrayBinding[10]; + } - for (int i = 1, packageLength = compoundName.length - 1; i < packageLength; i++) - if ((packageBinding = packageBinding.getPackage0(compoundName[i])) == null || packageBinding == TheNotFoundPackage) - return null; - return packageBinding.getType0(compoundName[compoundName.length - 1]); -} -/* Answer the top level package named name if it exists in the cache. -* Answer theNotFoundPackage if it could not be resolved the first time -* it was looked up, otherwise answer null. -* -* NOTE: Senders must convert theNotFoundPackage into a real problem -* package if its to returned. -*/ - -PackageBinding getPackage0(char[] name) { - return knownPackages.get(name); -} -/* Answer the top level package named name. -* Ask the oracle for the package if its not in the cache. -* Answer null if the package cannot be found. -*/ - -PackageBinding getTopLevelPackage(char[] name) { - PackageBinding packageBinding = getPackage0(name); - if (packageBinding != null) { - if (packageBinding == TheNotFoundPackage) - return null; - else - return packageBinding; + // find the cached array binding for this leaf component type (if any) + int index = -1; + length = arrayBindings.length; + while (++index < length) { + ArrayBinding currentBinding = arrayBindings[index]; + if (currentBinding == null) // no matching array, but space left + return arrayBindings[index] = new ArrayBinding(type, + dimensionCount); + if (currentBinding.leafComponentType == type) + return currentBinding; + } + + // no matching array, no space left + System.arraycopy(arrayBindings, 0, + (arrayBindings = new ArrayBinding[length * 2]), 0, length); + uniqueArrayBindings[dimIndex] = arrayBindings; + return arrayBindings[length] = new ArrayBinding(type, dimensionCount); } - if (nameEnvironment.isPackage(null, name)) { - knownPackages.put(name, packageBinding = new PackageBinding(name, this)); - return packageBinding; + public BinaryTypeBinding createBinaryTypeFrom(IBinaryType binaryType, + PackageBinding packageBinding) { + return createBinaryTypeFrom(binaryType, packageBinding, true); } - knownPackages.put(name, TheNotFoundPackage); // saves asking the oracle next time - return null; -} -/* Answer the type corresponding to the compoundName. -* Ask the oracle for the type if its not in the cache. -* Answer null if the type cannot be found... likely a fatal error. -*/ + public BinaryTypeBinding createBinaryTypeFrom(IBinaryType binaryType, + PackageBinding packageBinding, boolean needFieldsAndMethods) { + BinaryTypeBinding binaryBinding = new BinaryTypeBinding(packageBinding, + binaryType, this); + + // resolve any array bindings which reference the unresolvedType + ReferenceBinding cachedType = packageBinding + .getType0(binaryBinding.compoundName[binaryBinding.compoundName.length - 1]); + if (cachedType != null) { + if (cachedType.isBinaryBinding()) // sanity check before the + // cast... at this point the + // cache should ONLY contain + // unresolved types + return (BinaryTypeBinding) cachedType; + + UnresolvedReferenceBinding unresolvedType = (UnresolvedReferenceBinding) cachedType; + unresolvedType.resolvedType = binaryBinding; + updateArrayCache(unresolvedType, binaryBinding); + } -public ReferenceBinding getType(char[][] compoundName) { - ReferenceBinding referenceBinding; + packageBinding.addType(binaryBinding); + binaryBinding.cachePartsFrom(binaryType, needFieldsAndMethods); + return binaryBinding; + } - if (compoundName.length == 1) { - if (defaultPackage == null) - return null; + /* + * Used to create packages from the package statement. + */ - if ((referenceBinding = defaultPackage.getType0(compoundName[0])) == null) { - PackageBinding packageBinding = getPackage0(compoundName[0]); - if (packageBinding != null && packageBinding != TheNotFoundPackage) - return null; // collides with a known package... should not call this method in such a case - referenceBinding = askForType(defaultPackage, compoundName[0]); + PackageBinding createPackage(char[][] compoundName) { + return null; + // PackageBinding packageBinding = getPackage0(compoundName[0]); + // if (packageBinding == null || packageBinding == TheNotFoundPackage) { + // packageBinding = new PackageBinding(compoundName[0], this); + // knownPackages.put(compoundName[0], packageBinding); + // } + // + // for (int i = 1, length = compoundName.length; i < length; i++) { + // // check to see if it collides with a known type... + // // this case can only happen if the package does not exist as a + // directory in the file system + // // otherwise when the source type was defined, the correct error + // would have been reported + // // unless its an unresolved type which is referenced from an + // inconsistent class file + // ReferenceBinding type = packageBinding.getType0(compoundName[i]); + // if (type != null && type != TheNotFoundType && !(type instanceof + // UnresolvedReferenceBinding)) + // return null; + // + // PackageBinding parent = packageBinding; + // if ((packageBinding = parent.getPackage0(compoundName[i])) == null || + // packageBinding == TheNotFoundPackage) { + // // if the package is unknown, check to see if a type exists which + // would collide with the new package + // // catches the case of a package statement of: package + // java.lang.Object; + // // since the package can be added after a set of source files have + // already been compiled, we need + // // whenever a package statement is encountered + // if (nameEnvironment.findType(compoundName[i], parent.compoundName) != + // null) + // return null; + // + // packageBinding = new + // PackageBinding(CharOperation.subarray(compoundName, 0, i + 1), + // parent, this); + // parent.addPackage(packageBinding); + // } + // } + // return packageBinding; + } + + /* + * Answer the type for the compoundName if it exists in the cache. Answer + * theNotFoundType if it could not be resolved the first time it was looked + * up, otherwise answer null. + * + * NOTE: Do not use for nested types... the answer is NOT the same for a.b.C + * or a.b.C.D.E assuming C is a type in both cases. In the a.b.C.D.E case, + * null is the answer. + */ + + public ReferenceBinding getCachedType(char[][] compoundName) { + if (compoundName.length == 1) { + if (defaultPackage == null) + return null; + return defaultPackage.getType0(compoundName[0]); } - } else { + PackageBinding packageBinding = getPackage0(compoundName[0]); - if (packageBinding == TheNotFoundPackage) + if (packageBinding == null || packageBinding == TheNotFoundPackage) return null; + for (int i = 1, packageLength = compoundName.length - 1; i < packageLength; i++) + if ((packageBinding = packageBinding.getPackage0(compoundName[i])) == null + || packageBinding == TheNotFoundPackage) + return null; + return packageBinding.getType0(compoundName[compoundName.length - 1]); + } + + /* + * Answer the top level package named name if it exists in the cache. Answer + * theNotFoundPackage if it could not be resolved the first time it was + * looked up, otherwise answer null. + * + * NOTE: Senders must convert theNotFoundPackage into a real problem package + * if its to returned. + */ + + PackageBinding getPackage0(char[] name) { + return knownPackages.get(name); + } + + /* + * Answer the top level package named name. Ask the oracle for the package + * if its not in the cache. Answer null if the package cannot be found. + */ + + PackageBinding getTopLevelPackage(char[] name) { + PackageBinding packageBinding = getPackage0(name); if (packageBinding != null) { - for (int i = 1, packageLength = compoundName.length - 1; i < packageLength; i++) { - if ((packageBinding = packageBinding.getPackage0(compoundName[i])) == null) - break; - if (packageBinding == TheNotFoundPackage) - return null; - } + if (packageBinding == TheNotFoundPackage) + return null; + else + return packageBinding; } - if (packageBinding == null) - referenceBinding = askForType(compoundName); - else if ((referenceBinding = packageBinding.getType0(compoundName[compoundName.length - 1])) == null) - referenceBinding = askForType(packageBinding, compoundName[compoundName.length - 1]); - } + if (nameEnvironment.isPackage(null, name)) { + knownPackages.put(name, packageBinding = new PackageBinding(name, + this)); + return packageBinding; + } - if (referenceBinding == null || referenceBinding == TheNotFoundType) + knownPackages.put(name, TheNotFoundPackage); // saves asking the + // oracle next time return null; - if (referenceBinding instanceof UnresolvedReferenceBinding) - referenceBinding = ((UnresolvedReferenceBinding) referenceBinding).resolve(this); - - // compoundName refers to a nested type incorrectly (for example, package1.A$B) - if (referenceBinding.isNestedType()) - return new ProblemReferenceBinding(compoundName, InternalNameProvided); - else - return referenceBinding; -} -/* Answer the type corresponding to the name from the binary file. -* Does not ask the oracle for the type if its not found in the cache... instead an -* unresolved type is returned which must be resolved before used. -* -* NOTE: Does NOT answer base types nor array types! -* -* NOTE: Aborts compilation if the class file cannot be found. -*/ - -ReferenceBinding getTypeFromConstantPoolName(char[] signature, int start, int end) { - if (end == -1) - end = signature.length; - - char[][] compoundName = CharOperation.splitOn('/', signature, start, end); - ReferenceBinding binding = getCachedType(compoundName); - if (binding == null) { - PackageBinding packageBinding = computePackageFrom(compoundName); - binding = new UnresolvedReferenceBinding(compoundName, packageBinding); - packageBinding.addType(binding); - } else if (binding == TheNotFoundType) { - problemReporter.isClassPathCorrect(compoundName, null); - return null; // will not get here since the above error aborts the compilation } - return binding; -} -/* Answer the type corresponding to the signature from the binary file. -* Does not ask the oracle for the type if its not found in the cache... instead an -* unresolved type is returned which must be resolved before used. -* -* NOTE: Does answer base types & array types. -* -* NOTE: Aborts compilation if the class file cannot be found. -*/ - -TypeBinding getTypeFromSignature(char[] signature, int start, int end) { - int dimension = 0; - while (signature[start] == '[') { - start++; - dimension++; + + /* + * Answer the type corresponding to the compoundName. Ask the oracle for the + * type if its not in the cache. Answer null if the type cannot be found... + * likely a fatal error. + */ + + public ReferenceBinding getType(char[][] compoundName) { + ReferenceBinding referenceBinding; + + if (compoundName.length == 1) { + if (defaultPackage == null) + return null; + + if ((referenceBinding = defaultPackage.getType0(compoundName[0])) == null) { + PackageBinding packageBinding = getPackage0(compoundName[0]); + if (packageBinding != null + && packageBinding != TheNotFoundPackage) + return null; // collides with a known package... should + // not call this method in such a case + referenceBinding = askForType(defaultPackage, compoundName[0]); + } + } else { + PackageBinding packageBinding = getPackage0(compoundName[0]); + if (packageBinding == TheNotFoundPackage) + return null; + + if (packageBinding != null) { + for (int i = 1, packageLength = compoundName.length - 1; i < packageLength; i++) { + if ((packageBinding = packageBinding + .getPackage0(compoundName[i])) == null) + break; + if (packageBinding == TheNotFoundPackage) + return null; + } + } + + if (packageBinding == null) + referenceBinding = askForType(compoundName); + else if ((referenceBinding = packageBinding + .getType0(compoundName[compoundName.length - 1])) == null) + referenceBinding = askForType(packageBinding, + compoundName[compoundName.length - 1]); + } + + if (referenceBinding == null || referenceBinding == TheNotFoundType) + return null; + if (referenceBinding instanceof UnresolvedReferenceBinding) + referenceBinding = ((UnresolvedReferenceBinding) referenceBinding) + .resolve(this); + + // compoundName refers to a nested type incorrectly (for example, + // package1.A$B) + if (referenceBinding.isNestedType()) + return new ProblemReferenceBinding(compoundName, + InternalNameProvided); + else + return referenceBinding; + } + + /* + * Answer the type corresponding to the name from the binary file. Does not + * ask the oracle for the type if its not found in the cache... instead an + * unresolved type is returned which must be resolved before used. + * + * NOTE: Does NOT answer base types nor array types! + * + * NOTE: Aborts compilation if the class file cannot be found. + */ + + ReferenceBinding getTypeFromConstantPoolName(char[] signature, int start, + int end) { + if (end == -1) + end = signature.length; + + char[][] compoundName = CharOperation.splitOn('/', signature, start, + end); + ReferenceBinding binding = getCachedType(compoundName); + if (binding == null) { + PackageBinding packageBinding = computePackageFrom(compoundName); + binding = new UnresolvedReferenceBinding(compoundName, + packageBinding); + packageBinding.addType(binding); + } else if (binding == TheNotFoundType) { + problemReporter.isClassPathCorrect(compoundName, null); + return null; // will not get here since the above error aborts + // the compilation + } + return binding; } - if (end == -1) - end = signature.length - 1; - - // Just switch on signature[start] - the L case is the else - TypeBinding binding = null; - if (start == end) { - switch (signature[start]) { - case 'I' : + + /* + * Answer the type corresponding to the signature from the binary file. Does + * not ask the oracle for the type if its not found in the cache... instead + * an unresolved type is returned which must be resolved before used. + * + * NOTE: Does answer base types & array types. + * + * NOTE: Aborts compilation if the class file cannot be found. + */ + + TypeBinding getTypeFromSignature(char[] signature, int start, int end) { + int dimension = 0; + while (signature[start] == '[') { + start++; + dimension++; + } + if (end == -1) + end = signature.length - 1; + + // Just switch on signature[start] - the L case is the else + TypeBinding binding = null; + if (start == end) { + switch (signature[start]) { + case 'I': binding = IntBinding; break; - case 'Z' : + case 'Z': binding = BooleanBinding; break; - case 'V' : + case 'V': binding = VoidBinding; break; - case 'C' : + case 'C': binding = CharBinding; break; - case 'D' : + case 'D': binding = DoubleBinding; break; - case 'B' : + case 'B': binding = ByteBinding; break; - case 'F' : + case 'F': binding = FloatBinding; break; - case 'J' : + case 'J': binding = LongBinding; break; - case 'S' : + case 'S': binding = ShortBinding; break; - default : - throw new Error(Util.bind("error.undefinedBaseType",String.valueOf(signature[start]))); //$NON-NLS-1$ + default: + throw new Error( + Util + .bind( + "error.undefinedBaseType", String.valueOf(signature[start]))); //$NON-NLS-1$ + } + } else { + binding = getTypeFromConstantPoolName(signature, start + 1, end); } - } else { - binding = getTypeFromConstantPoolName(signature, start + 1, end); + + if (dimension == 0) + return binding; + else + return createArrayType(binding, dimension); } - if (dimension == 0) - return binding; - else - return createArrayType(binding, dimension); -} -/* Ask the oracle if a package exists named name in the package named compoundName. -*/ - -boolean isPackage(char[][] compoundName, char[] name) { - if (compoundName == null || compoundName.length == 0) - return nameEnvironment.isPackage(null, name); - else - return nameEnvironment.isPackage(compoundName, name); -} -// The method verifier is lazily initialized to guarantee the receiver, the compiler & the oracle are ready. + /* + * Ask the oracle if a package exists named name in the package named + * compoundName. + */ -public MethodVerifier methodVerifier() { - if (verifier == null) - verifier = new MethodVerifier(this); - return verifier; -} -public void reset() { - this.defaultPackage = new PackageBinding(this); // assume the default package always exists - this.defaultImports = null; - this.knownPackages = new HashtableOfPackage(); - - this.verifier = null; - for (int i = this.uniqueArrayBindings.length; --i >= 0;) - this.uniqueArrayBindings[i] = null; - this.uniqueArrayBindings[0] = new ArrayBinding[50]; // start off the most common 1 dimension array @ 50 - - for (int i = this.units.length; --i >= 0;) - this.units[i] = null; - this.lastUnitIndex = -1; - this.lastCompletedUnitIndex = -1; - - // name environment has a longer life cycle, and must be reset in - // the code which created it. -} -void updateArrayCache(UnresolvedReferenceBinding unresolvedType, ReferenceBinding resolvedType) { - nextDimension : for (int i = 0, length = uniqueArrayBindings.length; i < length; i++) { - ArrayBinding[] arrayBindings = uniqueArrayBindings[i]; - if (arrayBindings != null) { - for (int j = 0, max = arrayBindings.length; j < max; j++) { - ArrayBinding currentBinding = arrayBindings[j]; - if (currentBinding == null) - continue nextDimension; - if (currentBinding.leafComponentType == unresolvedType) { - currentBinding.leafComponentType = resolvedType; - continue nextDimension; + boolean isPackage(char[][] compoundName, char[] name) { + if (compoundName == null || compoundName.length == 0) + return nameEnvironment.isPackage(null, name); + else + return nameEnvironment.isPackage(compoundName, name); + } + + // The method verifier is lazily initialized to guarantee the receiver, the + // compiler & the oracle are ready. + + public MethodVerifier methodVerifier() { + if (verifier == null) + verifier = new MethodVerifier(this); + return verifier; + } + + public void reset() { + this.defaultPackage = new PackageBinding(this); // assume the default + // package always exists + this.defaultImports = null; + this.knownPackages = new HashtableOfPackage(); + + this.verifier = null; + for (int i = this.uniqueArrayBindings.length; --i >= 0;) + this.uniqueArrayBindings[i] = null; + this.uniqueArrayBindings[0] = new ArrayBinding[50]; // start off the + // most common 1 + // dimension array @ + // 50 + + for (int i = this.units.length; --i >= 0;) + this.units[i] = null; + this.lastUnitIndex = -1; + this.lastCompletedUnitIndex = -1; + + // name environment has a longer life cycle, and must be reset in + // the code which created it. + } + + void updateArrayCache(UnresolvedReferenceBinding unresolvedType, + ReferenceBinding resolvedType) { + nextDimension: for (int i = 0, length = uniqueArrayBindings.length; i < length; i++) { + ArrayBinding[] arrayBindings = uniqueArrayBindings[i]; + if (arrayBindings != null) { + for (int j = 0, max = arrayBindings.length; j < max; j++) { + ArrayBinding currentBinding = arrayBindings[j]; + if (currentBinding == null) + continue nextDimension; + if (currentBinding.leafComponentType == unresolvedType) { + currentBinding.leafComponentType = resolvedType; + continue nextDimension; + } } } } } } -} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/MemberTypeBinding.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/MemberTypeBinding.java index 1d3d67f..2f35672 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/MemberTypeBinding.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/MemberTypeBinding.java @@ -13,27 +13,35 @@ package net.sourceforge.phpdt.internal.compiler.lookup; import net.sourceforge.phpdt.core.compiler.CharOperation; public final class MemberTypeBinding extends NestedTypeBinding { -public MemberTypeBinding(char[][] compoundName, ClassScope scope, SourceTypeBinding enclosingType) { - super(compoundName, scope, enclosingType); - this.tagBits |= MemberTypeMask; -} -void checkSyntheticArgsAndFields() { - if (this.isStatic()) return; - if (this.isInterface()) return; - this.addSyntheticArgumentAndField(this.enclosingType); -} -/* Answer the receiver's constant pool name. -* -* NOTE: This method should only be used during/after code gen. -*/ + public MemberTypeBinding(char[][] compoundName, ClassScope scope, + SourceTypeBinding enclosingType) { + super(compoundName, scope, enclosingType); + this.tagBits |= MemberTypeMask; + } -public char[] constantPoolName() /* java/lang/Object */ { - if (constantPoolName != null) - return constantPoolName; + void checkSyntheticArgsAndFields() { + if (this.isStatic()) + return; + if (this.isInterface()) + return; + this.addSyntheticArgumentAndField(this.enclosingType); + } - return constantPoolName = CharOperation.concat(enclosingType().constantPoolName(), sourceName, '$'); -} -public String toString() { - return "Member type : " + new String(sourceName()) + " " + super.toString(); //$NON-NLS-2$ //$NON-NLS-1$ -} + /* + * Answer the receiver's constant pool name. + * + * NOTE: This method should only be used during/after code gen. + */ + + public char[] constantPoolName() /* java/lang/Object */{ + if (constantPoolName != null) + return constantPoolName; + + return constantPoolName = CharOperation.concat(enclosingType() + .constantPoolName(), sourceName, '$'); + } + + public String toString() { + return "Member type : " + new String(sourceName()) + " " + super.toString(); //$NON-NLS-2$ //$NON-NLS-1$ + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/MethodBinding.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/MethodBinding.java index 0d91862..4ed5ad0 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/MethodBinding.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/MethodBinding.java @@ -16,164 +16,119 @@ import net.sourceforge.phpdt.internal.compiler.ast.ConstructorDeclaration; public class MethodBinding extends Binding implements BaseTypes, TypeConstants { public int modifiers; + public char[] selector; + public TypeBinding returnType; + public TypeBinding[] parameters; + public ReferenceBinding[] thrownExceptions; + public ReferenceBinding declaringClass; char[] signature; -protected MethodBinding() { -} -public MethodBinding(int modifiers, char[] selector, TypeBinding returnType, TypeBinding[] args, ReferenceBinding[] exceptions, ReferenceBinding declaringClass) { - this.modifiers = modifiers; - this.selector = selector; - this.returnType = returnType; - this.parameters = (args == null || args.length == 0) ? NoParameters : args; - this.thrownExceptions = (exceptions == null || exceptions.length == 0) ? NoExceptions : exceptions; - this.declaringClass = declaringClass; - - // propagate the strictfp & deprecated modifiers - if (this.declaringClass != null) { -// if (this.declaringClass.isStrictfp()) -// if (!(isNative() || isAbstract())) -// this.modifiers |= AccStrictfp; - if (this.declaringClass.isViewedAsDeprecated() && !isDeprecated()) - this.modifiers |= AccDeprecatedImplicitly; + protected MethodBinding() { } -} -public MethodBinding(int modifiers, TypeBinding[] args, ReferenceBinding[] exceptions, ReferenceBinding declaringClass) { - this(modifiers, ConstructorDeclaration.ConstantPoolName, VoidBinding, args, exceptions, declaringClass); -} -// special API used to change method declaring class for runtime visibility check -public MethodBinding(MethodBinding initialMethodBinding, ReferenceBinding declaringClass) { - this.modifiers = initialMethodBinding.modifiers; - this.selector = initialMethodBinding.selector; - this.returnType = initialMethodBinding.returnType; - this.parameters = initialMethodBinding.parameters; - this.thrownExceptions = initialMethodBinding.thrownExceptions; - this.declaringClass = declaringClass; -} -/* Answer true if the argument types & the receiver's parameters are equal -*/ -public final boolean areParametersEqual(MethodBinding method) { - TypeBinding[] args = method.parameters; - if (parameters == args) - return true; + public MethodBinding(int modifiers, char[] selector, + TypeBinding returnType, TypeBinding[] args, + ReferenceBinding[] exceptions, ReferenceBinding declaringClass) { + this.modifiers = modifiers; + this.selector = selector; + this.returnType = returnType; + this.parameters = (args == null || args.length == 0) ? NoParameters + : args; + this.thrownExceptions = (exceptions == null || exceptions.length == 0) ? NoExceptions + : exceptions; + this.declaringClass = declaringClass; + + // propagate the strictfp & deprecated modifiers + if (this.declaringClass != null) { + // if (this.declaringClass.isStrictfp()) + // if (!(isNative() || isAbstract())) + // this.modifiers |= AccStrictfp; + if (this.declaringClass.isViewedAsDeprecated() && !isDeprecated()) + this.modifiers |= AccDeprecatedImplicitly; + } + } - int length = parameters.length; - if (length != args.length) - return false; - - for (int i = 0; i < length; i++) - if (parameters[i] != args[i]) - return false; - return true; -} -/* API -* Answer the receiver's binding type from Binding.BindingID. -*/ + public MethodBinding(int modifiers, TypeBinding[] args, + ReferenceBinding[] exceptions, ReferenceBinding declaringClass) { + this(modifiers, ConstructorDeclaration.ConstantPoolName, VoidBinding, + args, exceptions, declaringClass); + } -public final int bindingType() { - return METHOD; -} -/* Answer true if the receiver is visible to the type provided by the scope. -* InvocationSite implements isSuperAccess() to provide additional information -* if the receiver is protected. -* -* NOTE: This method should ONLY be sent if the receiver is a constructor. -* -* NOTE: Cannot invoke this method with a compilation unit scope. -*/ - -public final boolean canBeSeenBy(InvocationSite invocationSite, Scope scope) { - if (isPublic()) return true; - - SourceTypeBinding invocationType = scope.enclosingSourceType(); - if (invocationType == declaringClass) return true; - - if (isProtected()) { - // answer true if the receiver is in the same package as the invocationType - if (invocationType.fPackage == declaringClass.fPackage) return true; - return invocationSite.isSuperAccess(); - } - - if (isPrivate()) { - // answer true if the invocationType and the declaringClass have a common enclosingType - // already know they are not the identical type - ReferenceBinding outerInvocationType = invocationType; - ReferenceBinding temp = outerInvocationType.enclosingType(); - while (temp != null) { - outerInvocationType = temp; - temp = temp.enclosingType(); - } + // special API used to change method declaring class for runtime visibility + // check + public MethodBinding(MethodBinding initialMethodBinding, + ReferenceBinding declaringClass) { + this.modifiers = initialMethodBinding.modifiers; + this.selector = initialMethodBinding.selector; + this.returnType = initialMethodBinding.returnType; + this.parameters = initialMethodBinding.parameters; + this.thrownExceptions = initialMethodBinding.thrownExceptions; + this.declaringClass = declaringClass; + } - ReferenceBinding outerDeclaringClass = declaringClass; - temp = outerDeclaringClass.enclosingType(); - while (temp != null) { - outerDeclaringClass = temp; - temp = temp.enclosingType(); - } - return outerInvocationType == outerDeclaringClass; + /* + * Answer true if the argument types & the receiver's parameters are equal + */ + + public final boolean areParametersEqual(MethodBinding method) { + TypeBinding[] args = method.parameters; + if (parameters == args) + return true; + + int length = parameters.length; + if (length != args.length) + return false; + + for (int i = 0; i < length; i++) + if (parameters[i] != args[i]) + return false; + return true; } - // isDefault() - return invocationType.fPackage == declaringClass.fPackage; -} -/* Answer true if the receiver is visible to the type provided by the scope. -* InvocationSite implements isSuperAccess() to provide additional information -* if the receiver is protected. -* -* NOTE: Cannot invoke this method with a compilation unit scope. -*/ -public final boolean canBeSeenBy(TypeBinding receiverType, InvocationSite invocationSite, Scope scope) { - if (isPublic()) return true; - - SourceTypeBinding invocationType = scope.enclosingSourceType(); - if (invocationType == declaringClass && invocationType == receiverType) return true; - - if (isProtected()) { - // answer true if the invocationType is the declaringClass or they are in the same package - // OR the invocationType is a subclass of the declaringClass - // AND the receiverType is the invocationType or its subclass - // OR the method is a static method accessed directly through a type - // OR previous assertions are true for one of the enclosing type - if (invocationType == declaringClass) return true; - if (invocationType.fPackage == declaringClass.fPackage) return true; - - ReferenceBinding currentType = invocationType; - int depth = 0; - do { - if (declaringClass.isSuperclassOf(currentType)) { - if (invocationSite.isSuperAccess()){ - return true; - } - // receiverType can be an array binding in one case... see if you can change it - if (receiverType instanceof ArrayBinding){ - return false; - } - if (isStatic()){ - return true; // see 1FMEPDL - return invocationSite.isTypeAccess(); - } - if (currentType == receiverType || currentType.isSuperclassOf((ReferenceBinding) receiverType)){ - if (depth > 0) invocationSite.setDepth(depth); - return true; - } - } - depth++; - currentType = currentType.enclosingType(); - } while (currentType != null); - return false; + /* + * API Answer the receiver's binding type from Binding.BindingID. + */ + + public final int bindingType() { + return METHOD; } - if (isPrivate()) { - // answer true if the receiverType is the declaringClass - // AND the invocationType and the declaringClass have a common enclosingType - if (receiverType != declaringClass) return false; + /* + * Answer true if the receiver is visible to the type provided by the scope. + * InvocationSite implements isSuperAccess() to provide additional + * information if the receiver is protected. + * + * NOTE: This method should ONLY be sent if the receiver is a constructor. + * + * NOTE: Cannot invoke this method with a compilation unit scope. + */ + + public final boolean canBeSeenBy(InvocationSite invocationSite, Scope scope) { + if (isPublic()) + return true; + + SourceTypeBinding invocationType = scope.enclosingSourceType(); + if (invocationType == declaringClass) + return true; + + if (isProtected()) { + // answer true if the receiver is in the same package as the + // invocationType + if (invocationType.fPackage == declaringClass.fPackage) + return true; + return invocationSite.isSuperAccess(); + } - if (invocationType != declaringClass) { + if (isPrivate()) { + // answer true if the invocationType and the declaringClass have a + // common enclosingType + // already know they are not the identical type ReferenceBinding outerInvocationType = invocationType; ReferenceBinding temp = outerInvocationType.enclosingType(); while (temp != null) { @@ -187,334 +142,464 @@ public final boolean canBeSeenBy(TypeBinding receiverType, InvocationSite invoca outerDeclaringClass = temp; temp = temp.enclosingType(); } - if (outerInvocationType != outerDeclaringClass) return false; + return outerInvocationType == outerDeclaringClass; } - return true; + + // isDefault() + return invocationType.fPackage == declaringClass.fPackage; } - // isDefault() - if (invocationType.fPackage != declaringClass.fPackage) return false; + /* + * Answer true if the receiver is visible to the type provided by the scope. + * InvocationSite implements isSuperAccess() to provide additional + * information if the receiver is protected. + * + * NOTE: Cannot invoke this method with a compilation unit scope. + */ + public final boolean canBeSeenBy(TypeBinding receiverType, + InvocationSite invocationSite, Scope scope) { + if (isPublic()) + return true; + + SourceTypeBinding invocationType = scope.enclosingSourceType(); + if (invocationType == declaringClass && invocationType == receiverType) + return true; + + if (isProtected()) { + // answer true if the invocationType is the declaringClass or they + // are in the same package + // OR the invocationType is a subclass of the declaringClass + // AND the receiverType is the invocationType or its subclass + // OR the method is a static method accessed directly through a type + // OR previous assertions are true for one of the enclosing type + if (invocationType == declaringClass) + return true; + if (invocationType.fPackage == declaringClass.fPackage) + return true; + + ReferenceBinding currentType = invocationType; + int depth = 0; + do { + if (declaringClass.isSuperclassOf(currentType)) { + if (invocationSite.isSuperAccess()) { + return true; + } + // receiverType can be an array binding in one case... see + // if you can change it + if (receiverType instanceof ArrayBinding) { + return false; + } + if (isStatic()) { + return true; // see 1FMEPDL - return + // invocationSite.isTypeAccess(); + } + if (currentType == receiverType + || currentType + .isSuperclassOf((ReferenceBinding) receiverType)) { + if (depth > 0) + invocationSite.setDepth(depth); + return true; + } + } + depth++; + currentType = currentType.enclosingType(); + } while (currentType != null); + return false; + } + + if (isPrivate()) { + // answer true if the receiverType is the declaringClass + // AND the invocationType and the declaringClass have a common + // enclosingType + if (receiverType != declaringClass) + return false; + + if (invocationType != declaringClass) { + ReferenceBinding outerInvocationType = invocationType; + ReferenceBinding temp = outerInvocationType.enclosingType(); + while (temp != null) { + outerInvocationType = temp; + temp = temp.enclosingType(); + } + + ReferenceBinding outerDeclaringClass = declaringClass; + temp = outerDeclaringClass.enclosingType(); + while (temp != null) { + outerDeclaringClass = temp; + temp = temp.enclosingType(); + } + if (outerInvocationType != outerDeclaringClass) + return false; + } + return true; + } + + // isDefault() + if (invocationType.fPackage != declaringClass.fPackage) + return false; - // receiverType can be an array binding in one case... see if you can change it - if (receiverType instanceof ArrayBinding) + // receiverType can be an array binding in one case... see if you can + // change it + if (receiverType instanceof ArrayBinding) + return false; + ReferenceBinding type = (ReferenceBinding) receiverType; + PackageBinding declaringPackage = declaringClass.fPackage; + do { + if (declaringClass == type) + return true; + if (declaringPackage != type.fPackage) + return false; + } while ((type = type.superclass()) != null); return false; - ReferenceBinding type = (ReferenceBinding) receiverType; - PackageBinding declaringPackage = declaringClass.fPackage; - do { - if (declaringClass == type) return true; - if (declaringPackage != type.fPackage) return false; - } while ((type = type.superclass()) != null); - return false; -} + } -/* Answer the receiver's constant pool name. -* -* for constructors -* for clinit methods -* or the source name of the method -*/ -public final char[] constantPoolName() { - return selector; -} -public final int getAccessFlags() { - return modifiers & AccJustFlag; -} + /* + * Answer the receiver's constant pool name. + * + * for constructors for clinit methods or the source name of + * the method + */ + public final char[] constantPoolName() { + return selector; + } -/* Answer true if the receiver is an abstract method -*/ -public final boolean isAbstract() { - return (modifiers & AccAbstract) != 0; -} + public final int getAccessFlags() { + return modifiers & AccJustFlag; + } -/* Answer true if the receiver is a constructor -*/ -public final boolean isConstructor() { - return selector == ConstructorDeclaration.ConstantPoolName; -} -protected boolean isConstructorRelated() { - return isConstructor(); -} + /* + * Answer true if the receiver is an abstract method + */ + public final boolean isAbstract() { + return (modifiers & AccAbstract) != 0; + } -/* Answer true if the receiver has default visibility -*/ -public final boolean isDefault() { - return !isPublic() && !isProtected() && !isPrivate(); -} + /* + * Answer true if the receiver is a constructor + */ + public final boolean isConstructor() { + return selector == ConstructorDeclaration.ConstantPoolName; + } -/* Answer true if the receiver is a system generated default abstract method -*/ -public final boolean isDefaultAbstract() { - return (modifiers & AccDefaultAbstract) != 0; -} + protected boolean isConstructorRelated() { + return isConstructor(); + } -/* Answer true if the receiver is a deprecated method -*/ -public final boolean isDeprecated() { - return (modifiers & AccDeprecated) != 0; -} + /* + * Answer true if the receiver has default visibility + */ + public final boolean isDefault() { + return !isPublic() && !isProtected() && !isPrivate(); + } -/* Answer true if the receiver is final and cannot be overridden -*/ -public final boolean isFinal() { - return (modifiers & AccFinal) != 0; -} + /* + * Answer true if the receiver is a system generated default abstract method + */ + public final boolean isDefaultAbstract() { + return (modifiers & AccDefaultAbstract) != 0; + } -/* Answer true if the receiver is implementing another method - * in other words, it is overriding and concrete, and overriden method is abstract - * Only set for source methods -*/ -public final boolean isImplementing() { - return (modifiers & AccImplementing) != 0; -} + /* + * Answer true if the receiver is a deprecated method + */ + public final boolean isDeprecated() { + return (modifiers & AccDeprecated) != 0; + } -/* Answer true if the receiver is a native method -*/ -//public final boolean isNative() { -// return (modifiers & AccNative) != 0; -//} - -/* Answer true if the receiver is overriding another method - * Only set for source methods -*/ -public final boolean isOverriding() { - return (modifiers & AccOverriding) != 0; -} -/* - * Answer true if the receiver is a "public static void main(String[])" method - */ -public final boolean isMain() { - if (this.selector.length == 4 && CharOperation.equals(this.selector, MAIN) - && ((this.modifiers & (AccPublic | AccStatic)) != 0) - && VoidBinding == this.returnType - && this.parameters.length == 1) { - TypeBinding paramType = this.parameters[0]; - if (paramType.dimensions() == 1 && paramType.leafComponentType().id == TypeIds.T_JavaLangString) { - return true; + /* + * Answer true if the receiver is final and cannot be overridden + */ + public final boolean isFinal() { + return (modifiers & AccFinal) != 0; + } + + /* + * Answer true if the receiver is implementing another method in other + * words, it is overriding and concrete, and overriden method is abstract + * Only set for source methods + */ + public final boolean isImplementing() { + return (modifiers & AccImplementing) != 0; + } + + /* + * Answer true if the receiver is a native method + */ + // public final boolean isNative() { + // return (modifiers & AccNative) != 0; + // } + /* + * Answer true if the receiver is overriding another method Only set for + * source methods + */ + public final boolean isOverriding() { + return (modifiers & AccOverriding) != 0; + } + + /* + * Answer true if the receiver is a "public static void main(String[])" + * method + */ + public final boolean isMain() { + if (this.selector.length == 4 + && CharOperation.equals(this.selector, MAIN) + && ((this.modifiers & (AccPublic | AccStatic)) != 0) + && VoidBinding == this.returnType + && this.parameters.length == 1) { + TypeBinding paramType = this.parameters[0]; + if (paramType.dimensions() == 1 + && paramType.leafComponentType().id == TypeIds.T_JavaLangString) { + return true; + } } + return false; } - return false; -} -/* Answer true if the receiver has private visibility -*/ -public final boolean isPrivate() { - return (modifiers & AccPrivate) != 0; -} -/* Answer true if the receiver has private visibility and is used locally -*/ -public final boolean isPrivateUsed() { - return (modifiers & AccPrivateUsed) != 0; -} + /* + * Answer true if the receiver has private visibility + */ + public final boolean isPrivate() { + return (modifiers & AccPrivate) != 0; + } -/* Answer true if the receiver has protected visibility -*/ -public final boolean isProtected() { - return (modifiers & AccProtected) != 0; -} + /* + * Answer true if the receiver has private visibility and is used locally + */ + public final boolean isPrivateUsed() { + return (modifiers & AccPrivateUsed) != 0; + } -/* Answer true if the receiver has public visibility -*/ -public final boolean isPublic() { - return (modifiers & AccPublic) != 0; -} + /* + * Answer true if the receiver has protected visibility + */ + public final boolean isProtected() { + return (modifiers & AccProtected) != 0; + } -/* Answer true if the receiver got requested to clear the private modifier - * during private access emulation. - */ -public final boolean isRequiredToClearPrivateModifier() { - return (modifiers & AccClearPrivateModifier) != 0; -} + /* + * Answer true if the receiver has public visibility + */ + public final boolean isPublic() { + return (modifiers & AccPublic) != 0; + } -/* Answer true if the receiver is a static method -*/ -public final boolean isStatic() { - return (modifiers & AccStatic) != 0; -} + /* + * Answer true if the receiver got requested to clear the private modifier + * during private access emulation. + */ + public final boolean isRequiredToClearPrivateModifier() { + return (modifiers & AccClearPrivateModifier) != 0; + } -/* Answer true if all float operations must adher to IEEE 754 float/double rules -*/ -//public final boolean isStrictfp() { -// return (modifiers & AccStrictfp) != 0; -//} - -/* Answer true if the receiver is a synchronized method -*/ -//public final boolean isSynchronized() { -// return (modifiers & AccSynchronized) != 0; -//} - -/* Answer true if the receiver has public visibility -*/ -//public final boolean isSynthetic() { -// return (modifiers & AccSynthetic) != 0; -//} - -/* Answer true if the receiver's declaring type is deprecated (or any of its enclosing types) -*/ -public final boolean isViewedAsDeprecated() { - return (modifiers & AccDeprecated) != 0 || - (modifiers & AccDeprecatedImplicitly) != 0; -} + /* + * Answer true if the receiver is a static method + */ + public final boolean isStatic() { + return (modifiers & AccStatic) != 0; + } + + /* + * Answer true if all float operations must adher to IEEE 754 float/double + * rules + */ + // public final boolean isStrictfp() { + // return (modifiers & AccStrictfp) != 0; + // } + /* + * Answer true if the receiver is a synchronized method + */ + // public final boolean isSynchronized() { + // return (modifiers & AccSynchronized) != 0; + // } + /* + * Answer true if the receiver has public visibility + */ + // public final boolean isSynthetic() { + // return (modifiers & AccSynthetic) != 0; + // } + /* + * Answer true if the receiver's declaring type is deprecated (or any of its + * enclosing types) + */ + public final boolean isViewedAsDeprecated() { + return (modifiers & AccDeprecated) != 0 + || (modifiers & AccDeprecatedImplicitly) != 0; + } -public char[] readableName() /* foo(int, Thread) */ { - StringBuffer buffer = new StringBuffer(parameters.length + 1 * 20); - if (isConstructor()) - buffer.append(declaringClass.sourceName()); - else - buffer.append(selector); - buffer.append('('); - if (parameters != NoParameters) { - for (int i = 0, length = parameters.length; i < length; i++) { - if (i > 0) - buffer.append(", "); //$NON-NLS-1$ - buffer.append(parameters[i].sourceName()); + public char[] readableName() /* foo(int, Thread) */{ + StringBuffer buffer = new StringBuffer(parameters.length + 1 * 20); + if (isConstructor()) + buffer.append(declaringClass.sourceName()); + else + buffer.append(selector); + buffer.append('('); + if (parameters != NoParameters) { + for (int i = 0, length = parameters.length; i < length; i++) { + if (i > 0) + buffer.append(", "); //$NON-NLS-1$ + buffer.append(parameters[i].sourceName()); + } } + buffer.append(')'); + return buffer.toString().toCharArray(); } - buffer.append(')'); - return buffer.toString().toCharArray(); -} -/** - * @see net.sourceforge.phpdt.internal.compiler.lookup.Binding#shortReadableName() - */ -public char[] shortReadableName() { - StringBuffer buffer = new StringBuffer(parameters.length + 1 * 20); - if (isConstructor()) - buffer.append(declaringClass.shortReadableName()); - else - buffer.append(selector); - buffer.append('('); - if (parameters != NoParameters) { - for (int i = 0, length = parameters.length; i < length; i++) { - if (i > 0) - buffer.append(", "); //$NON-NLS-1$ - buffer.append(parameters[i].shortReadableName()); + /** + * @see net.sourceforge.phpdt.internal.compiler.lookup.Binding#shortReadableName() + */ + public char[] shortReadableName() { + StringBuffer buffer = new StringBuffer(parameters.length + 1 * 20); + if (isConstructor()) + buffer.append(declaringClass.shortReadableName()); + else + buffer.append(selector); + buffer.append('('); + if (parameters != NoParameters) { + for (int i = 0, length = parameters.length; i < length; i++) { + if (i > 0) + buffer.append(", "); //$NON-NLS-1$ + buffer.append(parameters[i].shortReadableName()); + } } + buffer.append(')'); + return buffer.toString().toCharArray(); } - buffer.append(')'); - return buffer.toString().toCharArray(); -} -protected final void selector(char[] selector) { - this.selector = selector; - this.signature = null; -} + protected final void selector(char[] selector) { + this.selector = selector; + this.signature = null; + } + + /* + * Answer the receiver's signature. + * + * NOTE: This method should only be used during/after code gen. The + * signature is cached so if the signature of the return type or any + * parameter type changes, the cached state is invalid. + */ + public final char[] signature() /* (ILjava/lang/Thread;)Ljava/lang/Object; */{ + if (signature != null) + return signature; + + StringBuffer buffer = new StringBuffer(parameters.length + 1 * 20); + buffer.append('('); + + TypeBinding[] targetParameters = this.parameters; + boolean considerSynthetics = isConstructorRelated() + && declaringClass.isNestedType(); + if (considerSynthetics) { + + // take into account the synthetic argument type signatures as well + ReferenceBinding[] syntheticArgumentTypes = declaringClass + .syntheticEnclosingInstanceTypes(); + int count = syntheticArgumentTypes == null ? 0 + : syntheticArgumentTypes.length; + for (int i = 0; i < count; i++) { + buffer.append(syntheticArgumentTypes[i].signature()); + } -/* Answer the receiver's signature. -* -* NOTE: This method should only be used during/after code gen. -* The signature is cached so if the signature of the return type or any parameter -* type changes, the cached state is invalid. -*/ -public final char[] signature() /* (ILjava/lang/Thread;)Ljava/lang/Object; */ { - if (signature != null) - return signature; - - StringBuffer buffer = new StringBuffer(parameters.length + 1 * 20); - buffer.append('('); - - TypeBinding[] targetParameters = this.parameters; - boolean considerSynthetics = isConstructorRelated() && declaringClass.isNestedType(); - if (considerSynthetics) { - - // take into account the synthetic argument type signatures as well - ReferenceBinding[] syntheticArgumentTypes = declaringClass.syntheticEnclosingInstanceTypes(); - int count = syntheticArgumentTypes == null ? 0 : syntheticArgumentTypes.length; - for (int i = 0; i < count; i++) { - buffer.append(syntheticArgumentTypes[i].signature()); + if (this instanceof SyntheticAccessMethodBinding) { + targetParameters = ((SyntheticAccessMethodBinding) this).targetMethod.parameters; + } } - - if (this instanceof SyntheticAccessMethodBinding) { - targetParameters = ((SyntheticAccessMethodBinding)this).targetMethod.parameters; + + if (targetParameters != NoParameters) { + for (int i = 0; i < targetParameters.length; i++) { + buffer.append(targetParameters[i].signature()); + } + } + if (considerSynthetics) { + SyntheticArgumentBinding[] syntheticOuterArguments = declaringClass + .syntheticOuterLocalVariables(); + int count = syntheticOuterArguments == null ? 0 + : syntheticOuterArguments.length; + for (int i = 0; i < count; i++) { + buffer.append(syntheticOuterArguments[i].type.signature()); + } + // move the extra padding arguments of the synthetic constructor + // invocation to the end + for (int i = targetParameters.length, extraLength = parameters.length; i < extraLength; i++) { + buffer.append(parameters[i].signature()); + } } + buffer.append(')'); + buffer.append(returnType.signature()); + return signature = buffer.toString().toCharArray(); } - if (targetParameters != NoParameters) { - for (int i = 0; i < targetParameters.length; i++) { - buffer.append(targetParameters[i].signature()); - } + public final int sourceEnd() { + AbstractMethodDeclaration method = sourceMethod(); + if (method == null) + return 0; + else + return method.sourceEnd; } - if (considerSynthetics) { - SyntheticArgumentBinding[] syntheticOuterArguments = declaringClass.syntheticOuterLocalVariables(); - int count = syntheticOuterArguments == null ? 0 : syntheticOuterArguments.length; - for (int i = 0; i < count; i++) { - buffer.append(syntheticOuterArguments[i].type.signature()); - } - // move the extra padding arguments of the synthetic constructor invocation to the end - for (int i = targetParameters.length, extraLength = parameters.length; i < extraLength; i++) { - buffer.append(parameters[i].signature()); + + AbstractMethodDeclaration sourceMethod() { + SourceTypeBinding sourceType; + try { + sourceType = (SourceTypeBinding) declaringClass; + } catch (ClassCastException e) { + return null; } + + AbstractMethodDeclaration[] methods = sourceType.scope.referenceContext.methods; + for (int i = methods.length; --i >= 0;) + if (this == methods[i].binding) + return methods[i]; + return null; } - buffer.append(')'); - buffer.append(returnType.signature()); - return signature = buffer.toString().toCharArray(); -} -public final int sourceEnd() { - AbstractMethodDeclaration method = sourceMethod(); - if (method == null) - return 0; - else - return method.sourceEnd; -} -AbstractMethodDeclaration sourceMethod() { - SourceTypeBinding sourceType; - try { - sourceType = (SourceTypeBinding) declaringClass; - } catch (ClassCastException e) { - return null; - } - - AbstractMethodDeclaration[] methods = sourceType.scope.referenceContext.methods; - for (int i = methods.length; --i >= 0;) - if (this == methods[i].binding) - return methods[i]; - return null; -} -public final int sourceStart() { - AbstractMethodDeclaration method = sourceMethod(); - if (method == null) - return 0; - else - return method.sourceStart; -} -/* During private access emulation, the binding can be requested to loose its - * private visibility when the class file is dumped. - */ -public final void tagForClearingPrivateModifier() { - modifiers |= AccClearPrivateModifier; -} -public String toString() { - String s = (returnType != null) ? returnType.debugName() : "NULL TYPE"; //$NON-NLS-1$ - s += " "; //$NON-NLS-1$ - s += (selector != null) ? new String(selector) : "UNNAMED METHOD"; //$NON-NLS-1$ + public final int sourceStart() { + AbstractMethodDeclaration method = sourceMethod(); + if (method == null) + return 0; + else + return method.sourceStart; + } - s += "("; //$NON-NLS-1$ - if (parameters != null) { - if (parameters != NoParameters) { - for (int i = 0, length = parameters.length; i < length; i++) { - if (i > 0) - s += ", "; //$NON-NLS-1$ - s += (parameters[i] != null) ? parameters[i].debugName() : "NULL TYPE"; //$NON-NLS-1$ + /* + * During private access emulation, the binding can be requested to loose + * its private visibility when the class file is dumped. + */ + + public final void tagForClearingPrivateModifier() { + modifiers |= AccClearPrivateModifier; + } + + public String toString() { + String s = (returnType != null) ? returnType.debugName() : "NULL TYPE"; //$NON-NLS-1$ + s += " "; //$NON-NLS-1$ + s += (selector != null) ? new String(selector) : "UNNAMED METHOD"; //$NON-NLS-1$ + + s += "("; //$NON-NLS-1$ + if (parameters != null) { + if (parameters != NoParameters) { + for (int i = 0, length = parameters.length; i < length; i++) { + if (i > 0) + s += ", "; //$NON-NLS-1$ + s += (parameters[i] != null) ? parameters[i].debugName() + : "NULL TYPE"; //$NON-NLS-1$ + } } + } else { + s += "NULL PARAMETERS"; //$NON-NLS-1$ } - } else { - s += "NULL PARAMETERS"; //$NON-NLS-1$ - } - s += ") "; //$NON-NLS-1$ - - if (thrownExceptions != null) { - if (thrownExceptions != NoExceptions) { - s += "throws "; //$NON-NLS-1$ - for (int i = 0, length = thrownExceptions.length; i < length; i++) { - if (i > 0) - s += ", "; //$NON-NLS-1$ - s += (thrownExceptions[i] != null) ? thrownExceptions[i].debugName() : "NULL TYPE"; //$NON-NLS-1$ + s += ") "; //$NON-NLS-1$ + + if (thrownExceptions != null) { + if (thrownExceptions != NoExceptions) { + s += "throws "; //$NON-NLS-1$ + for (int i = 0, length = thrownExceptions.length; i < length; i++) { + if (i > 0) + s += ", "; //$NON-NLS-1$ + s += (thrownExceptions[i] != null) ? thrownExceptions[i] + .debugName() : "NULL TYPE"; //$NON-NLS-1$ + } } + } else { + s += "NULL THROWN EXCEPTIONS"; //$NON-NLS-1$ } - } else { - s += "NULL THROWN EXCEPTIONS"; //$NON-NLS-1$ + return s; } - return s; -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/MethodScope.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/MethodScope.java index b4d38bf..5059768 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/MethodScope.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/MethodScope.java @@ -21,34 +21,42 @@ import net.sourceforge.phpdt.internal.compiler.impl.ReferenceContext; import net.sourceforge.phpdt.internal.compiler.problem.ProblemReporter; /** - * Particular block scope used for methods, constructors or clinits, representing - * its outermost blockscope. Note also that such a scope will be provided to enclose - * field initializers subscopes as well. + * Particular block scope used for methods, constructors or clinits, + * representing its outermost blockscope. Note also that such a scope will be + * provided to enclose field initializers subscopes as well. */ public class MethodScope extends BlockScope { public ReferenceContext referenceContext; + public boolean isStatic; // method modifier or initializer one - //fields used during name resolution - public static final int NotInFieldDecl = -1; //must be a negative value - public boolean isConstructorCall = false; + // fields used during name resolution + public static final int NotInFieldDecl = -1; // must be a negative value + + public boolean isConstructorCall = false; + public FieldBinding initializedField; // the field being initialized - public int fieldDeclarationIndex = NotInFieldDecl; + + public int fieldDeclarationIndex = NotInFieldDecl; // flow analysis public int analysisIndex; // for setting flow-analysis id + public boolean isPropagatingInnerClassEmulation; // for local variables table attributes public int lastIndex = 0; + public long[] definiteInits = new long[4]; + public long[][] extraDefiniteInits = new long[4][]; // inner-emulation public SyntheticArgumentBinding[] extraSyntheticArguments; - - public MethodScope(ClassScope parent, ReferenceContext context, boolean isStatic) { + + public MethodScope(ClassScope parent, ReferenceContext context, + boolean isStatic) { super(METHOD_SCOPE, parent); locals = new LocalVariableBinding[5]; @@ -57,15 +65,16 @@ public class MethodScope extends BlockScope { this.startIndex = 0; } - /* Spec : 8.4.3 & 9.4 + /* + * Spec : 8.4.3 & 9.4 */ private void checkAndSetModifiersForConstructor(MethodBinding methodBinding) { - + int modifiers = methodBinding.modifiers; if ((modifiers & AccAlternateModifierProblem) != 0) problemReporter().duplicateModifierForMethod( - methodBinding.declaringClass, - (AbstractMethodDeclaration) referenceContext); + methodBinding.declaringClass, + (AbstractMethodDeclaration) referenceContext); if (((ConstructorDeclaration) referenceContext).isDefaultConstructor) { if (methodBinding.declaringClass.isPublic()) @@ -78,25 +87,28 @@ public class MethodScope extends BlockScope { int realModifiers = modifiers & AccJustFlag; // check for abnormal modifiers - int unexpectedModifiers = - ~(AccPublic | AccPrivate | AccProtected);// | AccStrictfp); + int unexpectedModifiers = ~(AccPublic | AccPrivate | AccProtected);// | + // AccStrictfp); if ((realModifiers & unexpectedModifiers) != 0) problemReporter().illegalModifierForMethod( - methodBinding.declaringClass, - (AbstractMethodDeclaration) referenceContext); -// else if ( -// (((AbstractMethodDeclaration) referenceContext).modifiers & AccStrictfp) != 0) -// // must check the parse node explicitly -// problemReporter().illegalModifierForMethod( -// methodBinding.declaringClass, -// (AbstractMethodDeclaration) referenceContext); - - // check for incompatible modifiers in the visibility bits, isolate the visibility bits - int accessorBits = realModifiers & (AccPublic | AccProtected | AccPrivate); + methodBinding.declaringClass, + (AbstractMethodDeclaration) referenceContext); + // else if ( + // (((AbstractMethodDeclaration) referenceContext).modifiers & + // AccStrictfp) != 0) + // // must check the parse node explicitly + // problemReporter().illegalModifierForMethod( + // methodBinding.declaringClass, + // (AbstractMethodDeclaration) referenceContext); + + // check for incompatible modifiers in the visibility bits, isolate the + // visibility bits + int accessorBits = realModifiers + & (AccPublic | AccProtected | AccPrivate); if ((accessorBits & (accessorBits - 1)) != 0) { problemReporter().illegalVisibilityModifierCombinationForMethod( - methodBinding.declaringClass, - (AbstractMethodDeclaration) referenceContext); + methodBinding.declaringClass, + (AbstractMethodDeclaration) referenceContext); // need to keep the less restrictive if ((accessorBits & AccPublic) != 0) { @@ -110,23 +122,26 @@ public class MethodScope extends BlockScope { modifiers ^= AccPrivate; } - // if the receiver's declaring class is a private nested type, then make sure the receiver is not private (causes problems for inner type emulation) + // if the receiver's declaring class is a private nested type, then make + // sure the receiver is not private (causes problems for inner type + // emulation) if (methodBinding.declaringClass.isPrivate()) if ((modifiers & AccPrivate) != 0) modifiers ^= AccPrivate; methodBinding.modifiers = modifiers; } - - /* Spec : 8.4.3 & 9.4 + + /* + * Spec : 8.4.3 & 9.4 */ private void checkAndSetModifiersForMethod(MethodBinding methodBinding) { - + int modifiers = methodBinding.modifiers; if ((modifiers & AccAlternateModifierProblem) != 0) problemReporter().duplicateModifierForMethod( - methodBinding.declaringClass, - (AbstractMethodDeclaration) referenceContext); + methodBinding.declaringClass, + (AbstractMethodDeclaration) referenceContext); // after this point, tests on the 16 bits reserved. int realModifiers = modifiers & AccJustFlag; @@ -135,34 +150,30 @@ public class MethodScope extends BlockScope { if (methodBinding.declaringClass.isInterface()) { if ((realModifiers & ~(AccPublic | AccAbstract)) != 0) problemReporter().illegalModifierForInterfaceMethod( - methodBinding.declaringClass, - (AbstractMethodDeclaration) referenceContext); + methodBinding.declaringClass, + (AbstractMethodDeclaration) referenceContext); return; } // check for abnormal modifiers - int unexpectedModifiers = - ~( - AccPublic - | AccPrivate - | AccProtected - | AccAbstract - | AccStatic - | AccFinal); -// | AccSynchronized -// | AccNative -// | AccStrictfp); + int unexpectedModifiers = ~(AccPublic | AccPrivate | AccProtected + | AccAbstract | AccStatic | AccFinal); + // | AccSynchronized + // | AccNative + // | AccStrictfp); if ((realModifiers & unexpectedModifiers) != 0) problemReporter().illegalModifierForMethod( - methodBinding.declaringClass, - (AbstractMethodDeclaration) referenceContext); + methodBinding.declaringClass, + (AbstractMethodDeclaration) referenceContext); - // check for incompatible modifiers in the visibility bits, isolate the visibility bits - int accessorBits = realModifiers & (AccPublic | AccProtected | AccPrivate); + // check for incompatible modifiers in the visibility bits, isolate the + // visibility bits + int accessorBits = realModifiers + & (AccPublic | AccProtected | AccPrivate); if ((accessorBits & (accessorBits - 1)) != 0) { problemReporter().illegalVisibilityModifierCombinationForMethod( - methodBinding.declaringClass, - (AbstractMethodDeclaration) referenceContext); + methodBinding.declaringClass, + (AbstractMethodDeclaration) referenceContext); // need to keep the less restrictive if ((accessorBits & AccPublic) != 0) { @@ -178,116 +189,130 @@ public class MethodScope extends BlockScope { // check for modifiers incompatible with abstract modifier if ((modifiers & AccAbstract) != 0) { - int incompatibleWithAbstract = - AccPrivate | AccStatic | AccFinal;// | AccSynchronized | AccNative | AccStrictfp; + int incompatibleWithAbstract = AccPrivate | AccStatic | AccFinal;// | + // AccSynchronized + // | + // AccNative + // | + // AccStrictfp; if ((modifiers & incompatibleWithAbstract) != 0) problemReporter().illegalAbstractModifierCombinationForMethod( - methodBinding.declaringClass, - (AbstractMethodDeclaration) referenceContext); + methodBinding.declaringClass, + (AbstractMethodDeclaration) referenceContext); if (!methodBinding.declaringClass.isAbstract()) problemReporter().abstractMethodInAbstractClass( - (SourceTypeBinding) methodBinding.declaringClass, - (AbstractMethodDeclaration) referenceContext); + (SourceTypeBinding) methodBinding.declaringClass, + (AbstractMethodDeclaration) referenceContext); } - /* DISABLED for backward compatibility with javac (if enabled should also mark private methods as final) - // methods from a final class are final : 8.4.3.3 - if (methodBinding.declaringClass.isFinal()) - modifiers |= AccFinal; - */ + /* + * DISABLED for backward compatibility with javac (if enabled should + * also mark private methods as final) // methods from a final class are + * final : 8.4.3.3 if (methodBinding.declaringClass.isFinal()) modifiers |= + * AccFinal; + */ // native methods cannot also be tagged as strictfp -// if ((modifiers & AccNative) != 0 && (modifiers & AccStrictfp) != 0) -// problemReporter().nativeMethodsCannotBeStrictfp( -// methodBinding.declaringClass, -// (AbstractMethodDeclaration) referenceContext); - - // static members are only authorized in a static member or top level type + // if ((modifiers & AccNative) != 0 && (modifiers & AccStrictfp) != 0) + // problemReporter().nativeMethodsCannotBeStrictfp( + // methodBinding.declaringClass, + // (AbstractMethodDeclaration) referenceContext); + // static members are only authorized in a static member or top level + // type if (((realModifiers & AccStatic) != 0) - && methodBinding.declaringClass.isNestedType() - && !methodBinding.declaringClass.isStatic()) + && methodBinding.declaringClass.isNestedType() + && !methodBinding.declaringClass.isStatic()) problemReporter().unexpectedStaticModifierForMethod( - methodBinding.declaringClass, - (AbstractMethodDeclaration) referenceContext); + methodBinding.declaringClass, + (AbstractMethodDeclaration) referenceContext); methodBinding.modifiers = modifiers; } - - /* Compute variable positions in scopes given an initial position offset + + /* + * Compute variable positions in scopes given an initial position offset * ignoring unused local variables. * - * Deal with arguments here, locals and subscopes are processed in BlockScope method + * Deal with arguments here, locals and subscopes are processed in + * BlockScope method */ -// public void computeLocalVariablePositions(int initOffset, CodeStream codeStream) { -// -// boolean isReportingUnusedArgument = false; -// -// if (referenceContext instanceof AbstractMethodDeclaration) { -// AbstractMethodDeclaration methodDecl = (AbstractMethodDeclaration)referenceContext; -// MethodBinding method = methodDecl.binding; -// CompilerOptions options = compilationUnitScope().environment.options; -// if (!(method.isAbstract() -// || (method.isImplementing() && !options.reportUnusedParameterWhenImplementingAbstract) -// || (method.isOverriding() && !method.isImplementing() && !options.reportUnusedParameterWhenOverridingConcrete) -// || method.isMain())) { -// isReportingUnusedArgument = true; -// } -// } -// this.offset = initOffset; -// this.maxOffset = initOffset; -// -// // manage arguments -// int ilocal = 0, maxLocals = this.localIndex; -// while (ilocal < maxLocals) { -// LocalVariableBinding local = locals[ilocal]; -// if (local == null || !local.isArgument) break; // done with arguments -// -// // do not report fake used variable -// if (isReportingUnusedArgument -// && local.useFlag == LocalVariableBinding.UNUSED -// && ((local.declaration.bits & ASTNode.IsLocalDeclarationReachableMASK) != 0)) { // declaration is reachable -// this.problemReporter().unusedArgument(local.declaration); -// } -// -// // record user-defined argument for attribute generation -// codeStream.record(local); -// -// // assign variable position -// local.resolvedPosition = this.offset; -// -// if ((local.type == LongBinding) || (local.type == DoubleBinding)) { -// this.offset += 2; -// } else { -// this.offset++; -// } -// // check for too many arguments/local variables -// if (this.offset > 0xFF) { // no more than 255 words of arguments -// this.problemReporter().noMoreAvailableSpaceForArgument(local, local.declaration); -// } -// ilocal++; -// } -// -// // sneak in extra argument before other local variables -// if (extraSyntheticArguments != null) { -// for (int iarg = 0, maxArguments = extraSyntheticArguments.length; iarg < maxArguments; iarg++){ -// SyntheticArgumentBinding argument = extraSyntheticArguments[iarg]; -// argument.resolvedPosition = this.offset; -// if ((argument.type == LongBinding) || (argument.type == DoubleBinding)){ -// this.offset += 2; -// } else { -// this.offset++; -// } -// if (this.offset > 0xFF) { // no more than 255 words of arguments -// this.problemReporter().noMoreAvailableSpaceForArgument(argument, (ASTNode)this.referenceContext); -// } -// } -// } -// this.computeLocalVariablePositions(ilocal, this.offset, codeStream); -// } - - /* Error management: - * keep null for all the errors that prevent the method to be created - * otherwise return a correct method binding (but without the element - * that caused the problem) : ie : Incorrect thrown exception + // public void computeLocalVariablePositions(int initOffset, CodeStream + // codeStream) { + // + // boolean isReportingUnusedArgument = false; + // + // if (referenceContext instanceof AbstractMethodDeclaration) { + // AbstractMethodDeclaration methodDecl = + // (AbstractMethodDeclaration)referenceContext; + // MethodBinding method = methodDecl.binding; + // CompilerOptions options = compilationUnitScope().environment.options; + // if (!(method.isAbstract() + // || (method.isImplementing() && + // !options.reportUnusedParameterWhenImplementingAbstract) + // || (method.isOverriding() && !method.isImplementing() && + // !options.reportUnusedParameterWhenOverridingConcrete) + // || method.isMain())) { + // isReportingUnusedArgument = true; + // } + // } + // this.offset = initOffset; + // this.maxOffset = initOffset; + // + // // manage arguments + // int ilocal = 0, maxLocals = this.localIndex; + // while (ilocal < maxLocals) { + // LocalVariableBinding local = locals[ilocal]; + // if (local == null || !local.isArgument) break; // done with arguments + // + // // do not report fake used variable + // if (isReportingUnusedArgument + // && local.useFlag == LocalVariableBinding.UNUSED + // && ((local.declaration.bits & ASTNode.IsLocalDeclarationReachableMASK) != + // 0)) { // declaration is reachable + // this.problemReporter().unusedArgument(local.declaration); + // } + // + // // record user-defined argument for attribute generation + // codeStream.record(local); + // + // // assign variable position + // local.resolvedPosition = this.offset; + // + // if ((local.type == LongBinding) || (local.type == DoubleBinding)) { + // this.offset += 2; + // } else { + // this.offset++; + // } + // // check for too many arguments/local variables + // if (this.offset > 0xFF) { // no more than 255 words of arguments + // this.problemReporter().noMoreAvailableSpaceForArgument(local, + // local.declaration); + // } + // ilocal++; + // } + // + // // sneak in extra argument before other local variables + // if (extraSyntheticArguments != null) { + // for (int iarg = 0, maxArguments = extraSyntheticArguments.length; iarg < + // maxArguments; iarg++){ + // SyntheticArgumentBinding argument = extraSyntheticArguments[iarg]; + // argument.resolvedPosition = this.offset; + // if ((argument.type == LongBinding) || (argument.type == DoubleBinding)){ + // this.offset += 2; + // } else { + // this.offset++; + // } + // if (this.offset > 0xFF) { // no more than 255 words of arguments + // this.problemReporter().noMoreAvailableSpaceForArgument(argument, + // (ASTNode)this.referenceContext); + // } + // } + // } + // this.computeLocalVariablePositions(ilocal, this.offset, codeStream); + // } + /* + * Error management: keep null for all the errors that prevent the method to + * be created otherwise return a correct method binding (but without the + * element that caused the problem) : ie : Incorrect thrown exception */ MethodBinding createMethod(AbstractMethodDeclaration method) { @@ -297,13 +322,14 @@ public class MethodScope extends BlockScope { SourceTypeBinding declaringClass = referenceType().binding; int modifiers = method.modifiers | AccUnresolved; if (method.isConstructor()) { - method.binding = new MethodBinding(modifiers, null, null, declaringClass); + method.binding = new MethodBinding(modifiers, null, null, + declaringClass); checkAndSetModifiersForConstructor(method.binding); } else { if (declaringClass.isInterface()) modifiers |= AccPublic | AccAbstract; - method.binding = - new MethodBinding(modifiers, method.selector, null, null, null, declaringClass); + method.binding = new MethodBinding(modifiers, method.selector, + null, null, null, declaringClass); checkAndSetModifiersForMethod(method.binding); } @@ -311,22 +337,17 @@ public class MethodScope extends BlockScope { return method.binding; } - /* Overridden to detect the error case inside an explicit constructor call: - - class X { - int i; - X myX; - X(X x) { - this(i, myX.i, x.i); // same for super calls... only the first 2 field accesses are errors - } - } - */ - public FieldBinding findField( - TypeBinding receiverType, - char[] fieldName, - InvocationSite invocationSite) { + /* + * Overridden to detect the error case inside an explicit constructor call: + * + * class X { int i; X myX; X(X x) { this(i, myX.i, x.i); // same for super + * calls... only the first 2 field accesses are errors } } + */ + public FieldBinding findField(TypeBinding receiverType, char[] fieldName, + InvocationSite invocationSite) { - FieldBinding field = super.findField(receiverType, fieldName, invocationSite); + FieldBinding field = super.findField(receiverType, fieldName, + invocationSite); if (field == null) return null; if (!field.isValidBinding()) @@ -338,19 +359,16 @@ public class MethodScope extends BlockScope { return field; if (invocationSite instanceof SingleNameReference) - return new ProblemFieldBinding( - field.declaringClass, - fieldName, - NonStaticReferenceInConstructorInvocation); + return new ProblemFieldBinding(field.declaringClass, fieldName, + NonStaticReferenceInConstructorInvocation); if (invocationSite instanceof QualifiedNameReference) { // look to see if the field is the first binding QualifiedNameReference name = (QualifiedNameReference) invocationSite; if (name.binding == null) - // only true when the field is the fieldbinding at the beginning of name's tokens - return new ProblemFieldBinding( - field.declaringClass, - fieldName, - NonStaticReferenceInConstructorInvocation); + // only true when the field is the fieldbinding at the beginning + // of name's tokens + return new ProblemFieldBinding(field.declaringClass, fieldName, + NonStaticReferenceInConstructorInvocation); } return field; } @@ -363,14 +381,15 @@ public class MethodScope extends BlockScope { public boolean isInsideInitializerOrConstructor() { return (referenceContext instanceof TypeDeclaration) - || (referenceContext instanceof ConstructorDeclaration); + || (referenceContext instanceof ConstructorDeclaration); } - /* Answer the problem reporter to use for raising new problems. - * + /* + * Answer the problem reporter to use for raising new problems. + * * Note that as a side-effect, this updates the current reference context - * (unit, type or method) in case the problem handler decides it is necessary - * to abort. + * (unit, type or method) in case the problem handler decides it is + * necessary to abort. */ public ProblemReporter problemReporter() { @@ -386,12 +405,14 @@ public class MethodScope extends BlockScope { public final int recordInitializationStates(FlowInfo flowInfo) { - if (!flowInfo.isReachable()) return -1; + if (!flowInfo.isReachable()) + return -1; - UnconditionalFlowInfo unconditionalFlowInfo = flowInfo.unconditionalInits(); + UnconditionalFlowInfo unconditionalFlowInfo = flowInfo + .unconditionalInits(); long[] extraInits = unconditionalFlowInfo.extraDefiniteInits; long inits = unconditionalFlowInfo.definiteInits; - checkNextEntry : for (int i = lastIndex; --i >= 0;) { + checkNextEntry: for (int i = lastIndex; --i >= 0;) { if (definiteInits[i] == inits) { long[] otherInits = extraDefiniteInits[i]; if ((extraInits != null) && (otherInits != null)) { @@ -415,36 +436,26 @@ public class MethodScope extends BlockScope { // add a new entry if (definiteInits.length == lastIndex) { // need a resize - System.arraycopy( - definiteInits, - 0, - (definiteInits = new long[lastIndex + 20]), - 0, - lastIndex); - System.arraycopy( - extraDefiniteInits, - 0, - (extraDefiniteInits = new long[lastIndex + 20][]), - 0, - lastIndex); + System.arraycopy(definiteInits, 0, + (definiteInits = new long[lastIndex + 20]), 0, lastIndex); + System.arraycopy(extraDefiniteInits, 0, + (extraDefiniteInits = new long[lastIndex + 20][]), 0, + lastIndex); } definiteInits[lastIndex] = inits; if (extraInits != null) { extraDefiniteInits[lastIndex] = new long[extraInits.length]; - System.arraycopy( - extraInits, - 0, - extraDefiniteInits[lastIndex], - 0, - extraInits.length); + System.arraycopy(extraInits, 0, extraDefiniteInits[lastIndex], 0, + extraInits.length); } return lastIndex++; } - /* Answer the reference type of this scope. - * - * It is the nearest enclosing type of this scope. - */ + /* + * Answer the reference type of this scope. + * + * It is the nearest enclosing type of this scope. + */ public TypeDeclaration referenceType() { return (TypeDeclaration) ((ClassScope) parent).referenceContext; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/MethodVerifier.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/MethodVerifier.java index cf46cd2..98c7fd2 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/MethodVerifier.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/MethodVerifier.java @@ -18,442 +18,684 @@ import net.sourceforge.phpdt.internal.compiler.util.HashtableOfObject; public final class MethodVerifier implements TagBits, TypeConstants { SourceTypeBinding type; + HashtableOfObject inheritedMethods; + HashtableOfObject currentMethods; + ReferenceBinding runtimeException; + ReferenceBinding errorException; + LookupEnvironment environment; -/* -Binding creation is responsible for reporting all problems with types: - - all modifier problems (duplicates & multiple visibility modifiers + incompatible combinations - abstract/final) - - plus invalid modifiers given the context (the verifier did not do this before) - - qualified name collisions between a type and a package (types in default packages are excluded) - - all type hierarchy problems: - - cycles in the superclass or superinterface hierarchy - - an ambiguous, invisible or missing superclass or superinterface - - extending a final class - - extending an interface instead of a class - - implementing a class instead of an interface - - implementing the same interface more than once (ie. duplicate interfaces) - - with nested types: - - shadowing an enclosing type's source name - - defining a static class or interface inside a non-static nested class - - defining an interface as a local type (local types can only be classes) -*/ -public MethodVerifier(LookupEnvironment environment) { - this.type = null; // Initialized with the public method verify(SourceTypeBinding) - this.inheritedMethods = null; - this.currentMethods = null; - this.runtimeException = null; - this.errorException = null; - this.environment = environment; -} -private void checkAgainstInheritedMethods(MethodBinding currentMethod, MethodBinding[] methods, int length) { - currentMethod.modifiers |= CompilerModifiers.AccOverriding; - for (int i = length; --i >= 0;) { - MethodBinding inheritedMethod = methods[i]; - if (!currentMethod.isAbstract() && inheritedMethod.isAbstract()) - currentMethod.modifiers |= CompilerModifiers.AccImplementing; - - if (currentMethod.returnType != inheritedMethod.returnType) { - this.problemReporter(currentMethod).incompatibleReturnType(currentMethod, inheritedMethod); - } else if (currentMethod.isStatic() != inheritedMethod.isStatic()) { // Cannot override a static method or hide an instance method - this.problemReporter(currentMethod).staticAndInstanceConflict(currentMethod, inheritedMethod); - } else { - if (currentMethod.thrownExceptions != NoExceptions) - this.checkExceptions(currentMethod, inheritedMethod); - if (inheritedMethod.isFinal()) - this.problemReporter(currentMethod).finalMethodCannotBeOverridden(currentMethod, inheritedMethod); - if (!this.isAsVisible(currentMethod, inheritedMethod)) - this.problemReporter(currentMethod).visibilityConflict(currentMethod, inheritedMethod); -// if (inheritedMethod.isViewedAsDeprecated()) -// if (!currentMethod.isViewedAsDeprecated() || environment.options.reportDeprecationInsideDeprecatedCode) -// this.problemReporter(currentMethod).overridesDeprecatedMethod(currentMethod, inheritedMethod); - } + + /* + * Binding creation is responsible for reporting all problems with types: - + * all modifier problems (duplicates & multiple visibility modifiers + + * incompatible combinations - abstract/final) - plus invalid modifiers + * given the context (the verifier did not do this before) - qualified name + * collisions between a type and a package (types in default packages are + * excluded) - all type hierarchy problems: - cycles in the superclass or + * superinterface hierarchy - an ambiguous, invisible or missing superclass + * or superinterface - extending a final class - extending an interface + * instead of a class - implementing a class instead of an interface - + * implementing the same interface more than once (ie. duplicate interfaces) - + * with nested types: - shadowing an enclosing type's source name - defining + * a static class or interface inside a non-static nested class - defining + * an interface as a local type (local types can only be classes) + */ + public MethodVerifier(LookupEnvironment environment) { + this.type = null; // Initialized with the public method + // verify(SourceTypeBinding) + this.inheritedMethods = null; + this.currentMethods = null; + this.runtimeException = null; + this.errorException = null; + this.environment = environment; } -} -/* -"8.4.4" -Verify that newExceptions are all included in inheritedExceptions. -Assumes all exceptions are valid and throwable. -Unchecked exceptions (compatible with runtime & error) are ignored (see the spec on pg. 203). -*/ -private void checkExceptions(MethodBinding newMethod, MethodBinding inheritedMethod) { - ReferenceBinding[] newExceptions = newMethod.thrownExceptions; - ReferenceBinding[] inheritedExceptions = inheritedMethod.thrownExceptions; - for (int i = newExceptions.length; --i >= 0;) { - ReferenceBinding newException = newExceptions[i]; - int j = inheritedExceptions.length; - while (--j > -1 && !this.isSameClassOrSubclassOf(newException, inheritedExceptions[j])); - if (j == -1) - if (!(newException.isCompatibleWith(this.runtimeException()) || newException.isCompatibleWith(this.errorException()))) - this.problemReporter(newMethod).incompatibleExceptionInThrowsClause(this.type, newMethod, inheritedMethod, newException); + + private void checkAgainstInheritedMethods(MethodBinding currentMethod, + MethodBinding[] methods, int length) { + currentMethod.modifiers |= CompilerModifiers.AccOverriding; + for (int i = length; --i >= 0;) { + MethodBinding inheritedMethod = methods[i]; + if (!currentMethod.isAbstract() && inheritedMethod.isAbstract()) + currentMethod.modifiers |= CompilerModifiers.AccImplementing; + + if (currentMethod.returnType != inheritedMethod.returnType) { + this.problemReporter(currentMethod).incompatibleReturnType( + currentMethod, inheritedMethod); + } else if (currentMethod.isStatic() != inheritedMethod.isStatic()) { // Cannot + // override + // a + // static + // method + // or + // hide + // an + // instance + // method + this.problemReporter(currentMethod).staticAndInstanceConflict( + currentMethod, inheritedMethod); + } else { + if (currentMethod.thrownExceptions != NoExceptions) + this.checkExceptions(currentMethod, inheritedMethod); + if (inheritedMethod.isFinal()) + this.problemReporter(currentMethod) + .finalMethodCannotBeOverridden(currentMethod, + inheritedMethod); + if (!this.isAsVisible(currentMethod, inheritedMethod)) + this.problemReporter(currentMethod).visibilityConflict( + currentMethod, inheritedMethod); + // if (inheritedMethod.isViewedAsDeprecated()) + // if (!currentMethod.isViewedAsDeprecated() || + // environment.options.reportDeprecationInsideDeprecatedCode) + // this.problemReporter(currentMethod).overridesDeprecatedMethod(currentMethod, + // inheritedMethod); + } + } } -} -private void checkInheritedMethods(MethodBinding[] methods, int length) { - TypeBinding returnType = methods[0].returnType; - int index = length; - while (--index > 0 && returnType == methods[index].returnType); - if (index > 0) { // All inherited methods do NOT have the same vmSignature - this.problemReporter().inheritedMethodsHaveIncompatibleReturnTypes(this.type, methods, length); - return; + + /* + * "8.4.4" Verify that newExceptions are all included in + * inheritedExceptions. Assumes all exceptions are valid and throwable. + * Unchecked exceptions (compatible with runtime & error) are ignored (see + * the spec on pg. 203). + */ + private void checkExceptions(MethodBinding newMethod, + MethodBinding inheritedMethod) { + ReferenceBinding[] newExceptions = newMethod.thrownExceptions; + ReferenceBinding[] inheritedExceptions = inheritedMethod.thrownExceptions; + for (int i = newExceptions.length; --i >= 0;) { + ReferenceBinding newException = newExceptions[i]; + int j = inheritedExceptions.length; + while (--j > -1 + && !this.isSameClassOrSubclassOf(newException, + inheritedExceptions[j])) + ; + if (j == -1) + if (!(newException.isCompatibleWith(this.runtimeException()) || newException + .isCompatibleWith(this.errorException()))) + this.problemReporter(newMethod) + .incompatibleExceptionInThrowsClause(this.type, + newMethod, inheritedMethod, newException); + } } - MethodBinding concreteMethod = null; - if (!type.isInterface()) { // ignore concrete methods for interfaces - for (int i = length; --i >= 0;) { // Remember that only one of the methods can be non-abstract - if (!methods[i].isAbstract()) { - concreteMethod = methods[i]; - break; + private void checkInheritedMethods(MethodBinding[] methods, int length) { + TypeBinding returnType = methods[0].returnType; + int index = length; + while (--index > 0 && returnType == methods[index].returnType) + ; + if (index > 0) { // All inherited methods do NOT have the same + // vmSignature + this.problemReporter().inheritedMethodsHaveIncompatibleReturnTypes( + this.type, methods, length); + return; + } + + MethodBinding concreteMethod = null; + if (!type.isInterface()) { // ignore concrete methods for interfaces + for (int i = length; --i >= 0;) { // Remember that only one of the + // methods can be non-abstract + if (!methods[i].isAbstract()) { + concreteMethod = methods[i]; + break; + } } } - } - if (concreteMethod == null) { - if (this.type.isClass() && !this.type.isAbstract()) { - for (int i = length; --i >= 0;) - if (!mustImplementAbstractMethod(methods[i])) return; // have already reported problem against the concrete superclass - - TypeDeclaration typeDeclaration = this.type.scope.referenceContext; - if (typeDeclaration != null) { - MethodDeclaration missingAbstractMethod = typeDeclaration.addMissingAbstractMethodFor(methods[0]); - missingAbstractMethod.scope.problemReporter().abstractMethodMustBeImplemented(this.type, methods[0]); - } else { - this.problemReporter().abstractMethodMustBeImplemented(this.type, methods[0]); + if (concreteMethod == null) { + if (this.type.isClass() && !this.type.isAbstract()) { + for (int i = length; --i >= 0;) + if (!mustImplementAbstractMethod(methods[i])) + return; // have already reported problem against the + // concrete superclass + + TypeDeclaration typeDeclaration = this.type.scope.referenceContext; + if (typeDeclaration != null) { + MethodDeclaration missingAbstractMethod = typeDeclaration + .addMissingAbstractMethodFor(methods[0]); + missingAbstractMethod.scope.problemReporter() + .abstractMethodMustBeImplemented(this.type, + methods[0]); + } else { + this.problemReporter().abstractMethodMustBeImplemented( + this.type, methods[0]); + } } + return; } - return; + + MethodBinding[] abstractMethods = new MethodBinding[length - 1]; + index = 0; + for (int i = length; --i >= 0;) + if (methods[i] != concreteMethod) + abstractMethods[index++] = methods[i]; + + // Remember that interfaces can only define public instance methods + if (concreteMethod.isStatic()) + // Cannot inherit a static method which is specified as an instance + // method by an interface + this.problemReporter().staticInheritedMethodConflicts(type, + concreteMethod, abstractMethods); + if (!concreteMethod.isPublic()) + // Cannot reduce visibility of a public method specified by an + // interface + this.problemReporter().inheritedMethodReducesVisibility(type, + concreteMethod, abstractMethods); + if (concreteMethod.thrownExceptions != NoExceptions) + for (int i = abstractMethods.length; --i >= 0;) + this.checkExceptions(concreteMethod, abstractMethods[i]); } - MethodBinding[] abstractMethods = new MethodBinding[length - 1]; - index = 0; - for (int i = length; --i >= 0;) - if (methods[i] != concreteMethod) - abstractMethods[index++] = methods[i]; - - // Remember that interfaces can only define public instance methods - if (concreteMethod.isStatic()) - // Cannot inherit a static method which is specified as an instance method by an interface - this.problemReporter().staticInheritedMethodConflicts(type, concreteMethod, abstractMethods); - if (!concreteMethod.isPublic()) - // Cannot reduce visibility of a public method specified by an interface - this.problemReporter().inheritedMethodReducesVisibility(type, concreteMethod, abstractMethods); - if (concreteMethod.thrownExceptions != NoExceptions) - for (int i = abstractMethods.length; --i >= 0;) - this.checkExceptions(concreteMethod, abstractMethods[i]); -} -/* -For each inherited method identifier (message pattern - vm signature minus the return type) - if current method exists - if current's vm signature does not match an inherited signature then complain - else compare current's exceptions & visibility against each inherited method - else - if inherited methods = 1 - if inherited is abstract && type is NOT an interface or abstract, complain - else - if vm signatures do not match complain - else - find the concrete implementation amongst the abstract methods (can only be 1) - if one exists then - it must be a public instance method - compare concrete's exceptions against each abstract method - else - complain about missing implementation only if type is NOT an interface or abstract -*/ -private void checkMethods() { - boolean mustImplementAbstractMethods = this.type.isClass() && !this.type.isAbstract(); - char[][] methodSelectors = this.inheritedMethods.keyTable; - for (int s = methodSelectors.length; --s >= 0;) { - if (methodSelectors[s] != null) { - MethodBinding[] current = (MethodBinding[]) this.currentMethods.get(methodSelectors[s]); - MethodBinding[] inherited = (MethodBinding[]) this.inheritedMethods.valueTable[s]; - - int index = -1; - MethodBinding[] matchingInherited = new MethodBinding[inherited.length]; - if (current != null) { - for (int i = 0, length1 = current.length; i < length1; i++) { - while (index >= 0) matchingInherited[index--] = null; // clear the previous contents of the matching methods - MethodBinding currentMethod = current[i]; - for (int j = 0, length2 = inherited.length; j < length2; j++) { - if (inherited[j] != null && currentMethod.areParametersEqual(inherited[j])) { - matchingInherited[++index] = inherited[j]; - inherited[j] = null; // do not want to find it again + /* + * For each inherited method identifier (message pattern - vm signature + * minus the return type) if current method exists if current's vm signature + * does not match an inherited signature then complain else compare + * current's exceptions & visibility against each inherited method else if + * inherited methods = 1 if inherited is abstract && type is NOT an + * interface or abstract, complain else if vm signatures do not match + * complain else find the concrete implementation amongst the abstract + * methods (can only be 1) if one exists then it must be a public instance + * method compare concrete's exceptions against each abstract method else + * complain about missing implementation only if type is NOT an interface or + * abstract + */ + private void checkMethods() { + boolean mustImplementAbstractMethods = this.type.isClass() + && !this.type.isAbstract(); + char[][] methodSelectors = this.inheritedMethods.keyTable; + for (int s = methodSelectors.length; --s >= 0;) { + if (methodSelectors[s] != null) { + MethodBinding[] current = (MethodBinding[]) this.currentMethods + .get(methodSelectors[s]); + MethodBinding[] inherited = (MethodBinding[]) this.inheritedMethods.valueTable[s]; + + int index = -1; + MethodBinding[] matchingInherited = new MethodBinding[inherited.length]; + if (current != null) { + for (int i = 0, length1 = current.length; i < length1; i++) { + while (index >= 0) + matchingInherited[index--] = null; // clear the + // previous + // contents of + // the matching + // methods + MethodBinding currentMethod = current[i]; + for (int j = 0, length2 = inherited.length; j < length2; j++) { + if (inherited[j] != null + && currentMethod + .areParametersEqual(inherited[j])) { + matchingInherited[++index] = inherited[j]; + inherited[j] = null; // do not want to find + // it again + } } + if (index >= 0) + this.checkAgainstInheritedMethods(currentMethod, + matchingInherited, index + 1); // pass in + // the + // length of + // matching } - if (index >= 0) - this.checkAgainstInheritedMethods(currentMethod, matchingInherited, index + 1); // pass in the length of matching } - } - for (int i = 0, length = inherited.length; i < length; i++) { - while (index >= 0) matchingInherited[index--] = null; // clear the previous contents of the matching methods - if (inherited[i] != null) { - matchingInherited[++index] = inherited[i]; - for (int j = i + 1; j < length; j++) { - if (inherited[j] != null && inherited[i].areParametersEqual(inherited[j])) { - matchingInherited[++index] = inherited[j]; - inherited[j] = null; // do not want to find it again + for (int i = 0, length = inherited.length; i < length; i++) { + while (index >= 0) + matchingInherited[index--] = null; // clear the + // previous contents + // of the matching + // methods + if (inherited[i] != null) { + matchingInherited[++index] = inherited[i]; + for (int j = i + 1; j < length; j++) { + if (inherited[j] != null + && inherited[i] + .areParametersEqual(inherited[j])) { + matchingInherited[++index] = inherited[j]; + inherited[j] = null; // do not want to find + // it again + } } } - } - if (index > 0) { - this.checkInheritedMethods(matchingInherited, index + 1); // pass in the length of matching - } else if (mustImplementAbstractMethods && index == 0 && matchingInherited[0].isAbstract()) { - if (mustImplementAbstractMethod(matchingInherited[0])) { - TypeDeclaration typeDeclaration = this.type.scope.referenceContext; - if (typeDeclaration != null) { - MethodDeclaration missingAbstractMethod = typeDeclaration.addMissingAbstractMethodFor(matchingInherited[0]); - missingAbstractMethod.scope.problemReporter().abstractMethodMustBeImplemented(this.type, matchingInherited[0]); - } else { - this.problemReporter().abstractMethodMustBeImplemented(this.type, matchingInherited[0]); + if (index > 0) { + this + .checkInheritedMethods(matchingInherited, + index + 1); // pass in the length of + // matching + } else if (mustImplementAbstractMethods && index == 0 + && matchingInherited[0].isAbstract()) { + if (mustImplementAbstractMethod(matchingInherited[0])) { + TypeDeclaration typeDeclaration = this.type.scope.referenceContext; + if (typeDeclaration != null) { + MethodDeclaration missingAbstractMethod = typeDeclaration + .addMissingAbstractMethodFor(matchingInherited[0]); + missingAbstractMethod.scope + .problemReporter() + .abstractMethodMustBeImplemented( + this.type, matchingInherited[0]); + } else { + this + .problemReporter() + .abstractMethodMustBeImplemented( + this.type, matchingInherited[0]); + } } } } } } } -} -private void checkPackagePrivateAbstractMethod(MethodBinding abstractMethod) { - ReferenceBinding superType = this.type.superclass(); - char[] selector = abstractMethod.selector; - do { - if (!superType.isValidBinding()) return; - if (!superType.isAbstract()) return; // closer non abstract super type will be flagged instead - - MethodBinding[] methods = superType.getMethods(selector); - nextMethod : for (int m = methods.length; --m >= 0;) { - MethodBinding method = methods[m]; - if (method.returnType != abstractMethod.returnType || !method.areParametersEqual(abstractMethod)) - continue nextMethod; - if (method.isPrivate() || method.isConstructor() || method.isDefaultAbstract()) - continue nextMethod; - if (superType.fPackage == abstractMethod.declaringClass.fPackage) return; // found concrete implementation of abstract method in same package - } - } while ((superType = superType.superclass()) != abstractMethod.declaringClass); - // non visible abstract methods cannot be overridden so the type must be defined abstract - this.problemReporter().abstractMethodCannotBeOverridden(this.type, abstractMethod); -} -/* -Binding creation is responsible for reporting: - - all modifier problems (duplicates & multiple visibility modifiers + incompatible combinations) - - plus invalid modifiers given the context... examples: - - interface methods can only be public - - abstract methods can only be defined by abstract classes - - collisions... 2 methods with identical vmSelectors - - multiple methods with the same message pattern but different return types - - ambiguous, invisible or missing return/argument/exception types - - check the type of any array is not void - - check that each exception type is Throwable or a subclass of it -*/ -private void computeInheritedMethods() { - this.inheritedMethods = new HashtableOfObject(51); // maps method selectors to an array of methods... must search to match paramaters & return type - ReferenceBinding[][] interfacesToVisit = new ReferenceBinding[5][]; - int lastPosition = 0; - interfacesToVisit[lastPosition] = type.superInterfaces(); - - ReferenceBinding superType = this.type.isClass() - ? this.type.superclass() - : this.type.scope.getJavaLangObject(); // check interface methods against Object - MethodBinding[] nonVisibleDefaultMethods = null; - int nonVisibleCount = 0; - - while (superType != null) { - if (superType.isValidBinding()) { - ReferenceBinding[] itsInterfaces = superType.superInterfaces(); - if (itsInterfaces != NoSuperInterfaces) { - if (++lastPosition == interfacesToVisit.length) - System.arraycopy(interfacesToVisit, 0, interfacesToVisit = new ReferenceBinding[lastPosition * 2][], 0, lastPosition); - interfacesToVisit[lastPosition] = itsInterfaces; - } + private void checkPackagePrivateAbstractMethod(MethodBinding abstractMethod) { + ReferenceBinding superType = this.type.superclass(); + char[] selector = abstractMethod.selector; + do { + if (!superType.isValidBinding()) + return; + if (!superType.isAbstract()) + return; // closer non abstract super type will be flagged + // instead - MethodBinding[] methods = superType.methods(); - nextMethod : for (int m = methods.length; --m >= 0;) { + MethodBinding[] methods = superType.getMethods(selector); + nextMethod: for (int m = methods.length; --m >= 0;) { MethodBinding method = methods[m]; - if (!(method.isPrivate() || method.isConstructor() || method.isDefaultAbstract())) { // look at all methods which are NOT private or constructors or default abstract - MethodBinding[] existingMethods = (MethodBinding[]) this.inheritedMethods.get(method.selector); - if (existingMethods != null) { - for (int i = 0, length = existingMethods.length; i < length; i++) { - if (method.returnType == existingMethods[i].returnType && method.areParametersEqual(existingMethods[i])) { - if (method.isDefault() && method.isAbstract() && method.declaringClass.fPackage != type.fPackage) - checkPackagePrivateAbstractMethod(method); - continue nextMethod; + if (method.returnType != abstractMethod.returnType + || !method.areParametersEqual(abstractMethod)) + continue nextMethod; + if (method.isPrivate() || method.isConstructor() + || method.isDefaultAbstract()) + continue nextMethod; + if (superType.fPackage == abstractMethod.declaringClass.fPackage) + return; // found concrete implementation of abstract method + // in same package + } + } while ((superType = superType.superclass()) != abstractMethod.declaringClass); + + // non visible abstract methods cannot be overridden so the type must be + // defined abstract + this.problemReporter().abstractMethodCannotBeOverridden(this.type, + abstractMethod); + } + + /* + * Binding creation is responsible for reporting: - all modifier problems + * (duplicates & multiple visibility modifiers + incompatible combinations) - + * plus invalid modifiers given the context... examples: - interface methods + * can only be public - abstract methods can only be defined by abstract + * classes - collisions... 2 methods with identical vmSelectors - multiple + * methods with the same message pattern but different return types - + * ambiguous, invisible or missing return/argument/exception types - check + * the type of any array is not void - check that each exception type is + * Throwable or a subclass of it + */ + private void computeInheritedMethods() { + this.inheritedMethods = new HashtableOfObject(51); // maps method + // selectors to an + // array of + // methods... must + // search to match + // paramaters & + // return type + ReferenceBinding[][] interfacesToVisit = new ReferenceBinding[5][]; + int lastPosition = 0; + interfacesToVisit[lastPosition] = type.superInterfaces(); + + ReferenceBinding superType = this.type.isClass() ? this.type + .superclass() : this.type.scope.getJavaLangObject(); // check + // interface + // methods + // against + // Object + MethodBinding[] nonVisibleDefaultMethods = null; + int nonVisibleCount = 0; + + while (superType != null) { + if (superType.isValidBinding()) { + ReferenceBinding[] itsInterfaces = superType.superInterfaces(); + if (itsInterfaces != NoSuperInterfaces) { + if (++lastPosition == interfacesToVisit.length) + System + .arraycopy( + interfacesToVisit, + 0, + interfacesToVisit = new ReferenceBinding[lastPosition * 2][], + 0, lastPosition); + interfacesToVisit[lastPosition] = itsInterfaces; + } + + MethodBinding[] methods = superType.methods(); + nextMethod: for (int m = methods.length; --m >= 0;) { + MethodBinding method = methods[m]; + if (!(method.isPrivate() || method.isConstructor() || method + .isDefaultAbstract())) { // look at all methods + // which are NOT private + // or constructors or + // default abstract + MethodBinding[] existingMethods = (MethodBinding[]) this.inheritedMethods + .get(method.selector); + if (existingMethods != null) { + for (int i = 0, length = existingMethods.length; i < length; i++) { + if (method.returnType == existingMethods[i].returnType + && method + .areParametersEqual(existingMethods[i])) { + if (method.isDefault() + && method.isAbstract() + && method.declaringClass.fPackage != type.fPackage) + checkPackagePrivateAbstractMethod(method); + continue nextMethod; + } } } - } - if (nonVisibleDefaultMethods != null) - for (int i = 0; i < nonVisibleCount; i++) - if (method.returnType == nonVisibleDefaultMethods[i].returnType - && CharOperation.equals(method.selector, nonVisibleDefaultMethods[i].selector) - && method.areParametersEqual(nonVisibleDefaultMethods[i])) + if (nonVisibleDefaultMethods != null) + for (int i = 0; i < nonVisibleCount; i++) + if (method.returnType == nonVisibleDefaultMethods[i].returnType + && CharOperation + .equals( + method.selector, + nonVisibleDefaultMethods[i].selector) + && method + .areParametersEqual(nonVisibleDefaultMethods[i])) continue nextMethod; - if (!(method.isDefault() && method.declaringClass.fPackage != type.fPackage)) { // ignore methods which have default visibility and are NOT defined in another package - if (existingMethods == null) - existingMethods = new MethodBinding[1]; - else - System.arraycopy(existingMethods, 0, - (existingMethods = new MethodBinding[existingMethods.length + 1]), 0, existingMethods.length - 1); - existingMethods[existingMethods.length - 1] = method; - this.inheritedMethods.put(method.selector, existingMethods); - } else { - if (nonVisibleDefaultMethods == null) - nonVisibleDefaultMethods = new MethodBinding[10]; - else if (nonVisibleCount == nonVisibleDefaultMethods.length) - System.arraycopy(nonVisibleDefaultMethods, 0, - (nonVisibleDefaultMethods = new MethodBinding[nonVisibleCount * 2]), 0, nonVisibleCount); - nonVisibleDefaultMethods[nonVisibleCount++] = method; - - if (method.isAbstract() && !this.type.isAbstract()) // non visible abstract methods cannot be overridden so the type must be defined abstract - this.problemReporter().abstractMethodCannotBeOverridden(this.type, method); - - MethodBinding[] current = (MethodBinding[]) this.currentMethods.get(method.selector); - if (current != null) { // non visible methods cannot be overridden so a warning is issued - foundMatch : for (int i = 0, length = current.length; i < length; i++) { - if (method.returnType == current[i].returnType && method.areParametersEqual(current[i])) { - this.problemReporter().overridesPackageDefaultMethod(current[i], method); - break foundMatch; + if (!(method.isDefault() && method.declaringClass.fPackage != type.fPackage)) { // ignore + // methods + // which + // have + // default + // visibility + // and + // are + // NOT + // defined + // in + // another + // package + if (existingMethods == null) + existingMethods = new MethodBinding[1]; + else + System + .arraycopy( + existingMethods, + 0, + (existingMethods = new MethodBinding[existingMethods.length + 1]), + 0, existingMethods.length - 1); + existingMethods[existingMethods.length - 1] = method; + this.inheritedMethods.put(method.selector, + existingMethods); + } else { + if (nonVisibleDefaultMethods == null) + nonVisibleDefaultMethods = new MethodBinding[10]; + else if (nonVisibleCount == nonVisibleDefaultMethods.length) + System + .arraycopy( + nonVisibleDefaultMethods, + 0, + (nonVisibleDefaultMethods = new MethodBinding[nonVisibleCount * 2]), + 0, nonVisibleCount); + nonVisibleDefaultMethods[nonVisibleCount++] = method; + + if (method.isAbstract() && !this.type.isAbstract()) // non + // visible + // abstract + // methods + // cannot + // be + // overridden + // so + // the + // type + // must + // be + // defined + // abstract + this.problemReporter() + .abstractMethodCannotBeOverridden( + this.type, method); + + MethodBinding[] current = (MethodBinding[]) this.currentMethods + .get(method.selector); + if (current != null) { // non visible methods + // cannot be overridden so a + // warning is issued + foundMatch: for (int i = 0, length = current.length; i < length; i++) { + if (method.returnType == current[i].returnType + && method + .areParametersEqual(current[i])) { + this.problemReporter() + .overridesPackageDefaultMethod( + current[i], method); + break foundMatch; + } } } } } } + superType = superType.superclass(); } - superType = superType.superclass(); } - } - for (int i = 0; i <= lastPosition; i++) { - ReferenceBinding[] interfaces = interfacesToVisit[i]; - if (interfaces==null) { - interfaces = new ReferenceBinding[0]; - } - for (int j = 0, length = interfaces.length; j < length; j++) { - superType = interfaces[j]; - if ((superType.tagBits & InterfaceVisited) == 0) { - superType.tagBits |= InterfaceVisited; - if (superType.isValidBinding()) { - ReferenceBinding[] itsInterfaces = superType.superInterfaces(); - if (itsInterfaces != NoSuperInterfaces) { - if (++lastPosition == interfacesToVisit.length) - System.arraycopy(interfacesToVisit, 0, interfacesToVisit = new ReferenceBinding[lastPosition * 2][], 0, lastPosition); - interfacesToVisit[lastPosition] = itsInterfaces; - } + for (int i = 0; i <= lastPosition; i++) { + ReferenceBinding[] interfaces = interfacesToVisit[i]; + if (interfaces == null) { + interfaces = new ReferenceBinding[0]; + } + for (int j = 0, length = interfaces.length; j < length; j++) { + superType = interfaces[j]; + if ((superType.tagBits & InterfaceVisited) == 0) { + superType.tagBits |= InterfaceVisited; + if (superType.isValidBinding()) { + ReferenceBinding[] itsInterfaces = superType + .superInterfaces(); + if (itsInterfaces != NoSuperInterfaces) { + if (++lastPosition == interfacesToVisit.length) + System + .arraycopy( + interfacesToVisit, + 0, + interfacesToVisit = new ReferenceBinding[lastPosition * 2][], + 0, lastPosition); + interfacesToVisit[lastPosition] = itsInterfaces; + } - MethodBinding[] methods = superType.methods(); - for (int m = methods.length; --m >= 0;) { // Interface methods are all abstract public - MethodBinding method = methods[m]; - MethodBinding[] existingMethods = (MethodBinding[]) this.inheritedMethods.get(method.selector); - if (existingMethods == null) - existingMethods = new MethodBinding[1]; - else - System.arraycopy(existingMethods, 0, - (existingMethods = new MethodBinding[existingMethods.length + 1]), 0, existingMethods.length - 1); - existingMethods[existingMethods.length - 1] = method; - this.inheritedMethods.put(method.selector, existingMethods); + MethodBinding[] methods = superType.methods(); + for (int m = methods.length; --m >= 0;) { // Interface + // methods + // are all + // abstract + // public + MethodBinding method = methods[m]; + MethodBinding[] existingMethods = (MethodBinding[]) this.inheritedMethods + .get(method.selector); + if (existingMethods == null) + existingMethods = new MethodBinding[1]; + else + System + .arraycopy( + existingMethods, + 0, + (existingMethods = new MethodBinding[existingMethods.length + 1]), + 0, existingMethods.length - 1); + existingMethods[existingMethods.length - 1] = method; + this.inheritedMethods.put(method.selector, + existingMethods); + } } } } } - } - // bit reinitialization - for (int i = 0; i <= lastPosition; i++) { - ReferenceBinding[] interfaces = interfacesToVisit[i]; - if (interfaces==null) { - interfaces = new ReferenceBinding[0]; + // bit reinitialization + for (int i = 0; i <= lastPosition; i++) { + ReferenceBinding[] interfaces = interfacesToVisit[i]; + if (interfaces == null) { + interfaces = new ReferenceBinding[0]; + } + for (int j = 0, length = interfaces.length; j < length; j++) + interfaces[j].tagBits &= ~InterfaceVisited; } - for (int j = 0, length = interfaces.length; j < length; j++) - interfaces[j].tagBits &= ~InterfaceVisited; } -} -private void computeMethods() { - MethodBinding[] methods = type.methods(); - if (methods==null) { - methods = new MethodBinding[0]; - } - int size = methods.length; - this.currentMethods = new HashtableOfObject(size == 0 ? 1 : size); // maps method selectors to an array of methods... must search to match paramaters & return type - for (int m = size; --m >= 0;) { - MethodBinding method = methods[m]; - if (!(method.isConstructor() || method.isDefaultAbstract())) { // keep all methods which are NOT constructors or default abstract - MethodBinding[] existingMethods = (MethodBinding[]) this.currentMethods.get(method.selector); - if (existingMethods == null) - existingMethods = new MethodBinding[1]; - else - System.arraycopy(existingMethods, 0, - (existingMethods = new MethodBinding[existingMethods.length + 1]), 0, existingMethods.length - 1); - existingMethods[existingMethods.length - 1] = method; - this.currentMethods.put(method.selector, existingMethods); + + private void computeMethods() { + MethodBinding[] methods = type.methods(); + if (methods == null) { + methods = new MethodBinding[0]; + } + int size = methods.length; + this.currentMethods = new HashtableOfObject(size == 0 ? 1 : size); // maps + // method + // selectors + // to + // an + // array + // of + // methods... + // must + // search + // to + // match + // paramaters + // & + // return + // type + for (int m = size; --m >= 0;) { + MethodBinding method = methods[m]; + if (!(method.isConstructor() || method.isDefaultAbstract())) { // keep + // all + // methods + // which + // are + // NOT + // constructors + // or + // default + // abstract + MethodBinding[] existingMethods = (MethodBinding[]) this.currentMethods + .get(method.selector); + if (existingMethods == null) + existingMethods = new MethodBinding[1]; + else + System + .arraycopy( + existingMethods, + 0, + (existingMethods = new MethodBinding[existingMethods.length + 1]), + 0, existingMethods.length - 1); + existingMethods[existingMethods.length - 1] = method; + this.currentMethods.put(method.selector, existingMethods); + } } } -} -private ReferenceBinding errorException() { - if (errorException == null) - this.errorException = this.type.scope.getJavaLangError(); - return errorException; -} -private boolean isAsVisible(MethodBinding newMethod, MethodBinding inheritedMethod) { - if (inheritedMethod.modifiers == newMethod.modifiers) return true; - if (newMethod.isPublic()) return true; // Covers everything - if (inheritedMethod.isPublic()) return false; + private ReferenceBinding errorException() { + if (errorException == null) + this.errorException = this.type.scope.getJavaLangError(); + return errorException; + } - if (newMethod.isProtected()) return true; - if (inheritedMethod.isProtected()) return false; + private boolean isAsVisible(MethodBinding newMethod, + MethodBinding inheritedMethod) { + if (inheritedMethod.modifiers == newMethod.modifiers) + return true; - return !newMethod.isPrivate(); // The inheritedMethod cannot be private since it would not be visible -} -private boolean isSameClassOrSubclassOf(ReferenceBinding testClass, ReferenceBinding superclass) { - do { - if (testClass == superclass) return true; - } while ((testClass = testClass.superclass()) != null); - return false; -} -private boolean mustImplementAbstractMethod(MethodBinding abstractMethod) { - // if the type's superclass is an abstract class, then all abstract methods must be implemented - // otherwise, skip it if the type's superclass must implement any of the inherited methods - ReferenceBinding superclass = this.type.superclass(); - ReferenceBinding declaringClass = abstractMethod.declaringClass; - if (declaringClass.isClass()) { - while (superclass.isAbstract() && superclass != declaringClass) - superclass = superclass.superclass(); // find the first concrete superclass or the abstract declaringClass - } else { - if (this.type.implementsInterface(declaringClass, false)) { - if (this.type.isAbstract()) return false; // leave it for the subclasses - if (!superclass.implementsInterface(declaringClass, true)) // only if a superclass does not also implement the interface + if (newMethod.isPublic()) + return true; // Covers everything + if (inheritedMethod.isPublic()) + return false; + + if (newMethod.isProtected()) + return true; + if (inheritedMethod.isProtected()) + return false; + + return !newMethod.isPrivate(); // The inheritedMethod cannot be private + // since it would not be visible + } + + private boolean isSameClassOrSubclassOf(ReferenceBinding testClass, + ReferenceBinding superclass) { + do { + if (testClass == superclass) return true; + } while ((testClass = testClass.superclass()) != null); + return false; + } + + private boolean mustImplementAbstractMethod(MethodBinding abstractMethod) { + // if the type's superclass is an abstract class, then all abstract + // methods must be implemented + // otherwise, skip it if the type's superclass must implement any of the + // inherited methods + ReferenceBinding superclass = this.type.superclass(); + ReferenceBinding declaringClass = abstractMethod.declaringClass; + if (declaringClass.isClass()) { + while (superclass.isAbstract() && superclass != declaringClass) + superclass = superclass.superclass(); // find the first + // concrete superclass + // or the abstract + // declaringClass + } else { + if (this.type.implementsInterface(declaringClass, false)) { + if (this.type.isAbstract()) + return false; // leave it for the subclasses + if (!superclass.implementsInterface(declaringClass, true)) // only + // if a + // superclass + // does + // not + // also + // implement + // the + // interface + return true; + } + while (superclass.isAbstract() + && !superclass.implementsInterface(declaringClass, false)) + superclass = superclass.superclass(); // find the first + // concrete superclass + // or the superclass + // which implements the + // interface } - while (superclass.isAbstract() && !superclass.implementsInterface(declaringClass, false)) - superclass = superclass.superclass(); // find the first concrete superclass or the superclass which implements the interface + return superclass.isAbstract(); // if it is a concrete class then we + // have already reported problem against + // it + } + + private ProblemReporter problemReporter() { + return this.type.scope.problemReporter(); + } + + private ProblemReporter problemReporter(MethodBinding currentMethod) { + ProblemReporter reporter = problemReporter(); + if (currentMethod.declaringClass == type) // only report against the + // currentMethod if its + // implemented by the type + reporter.referenceContext = currentMethod.sourceMethod(); + return reporter; + } + + private ReferenceBinding runtimeException() { + if (runtimeException == null) + this.runtimeException = this.type.scope + .getJavaLangRuntimeException(); + return runtimeException; + } + + public void verify(SourceTypeBinding type) { + this.type = type; + this.computeMethods(); + this.computeInheritedMethods(); + this.checkMethods(); + } + + public String toString() { + StringBuffer buffer = new StringBuffer(10); + buffer.append("MethodVerifier for type: "); //$NON-NLS-1$ + buffer.append(type.readableName()); + buffer.append('\n'); + buffer.append("\t-inherited methods: "); //$NON-NLS-1$ + buffer.append(this.inheritedMethods); + return buffer.toString(); } - return superclass.isAbstract(); // if it is a concrete class then we have already reported problem against it -} -private ProblemReporter problemReporter() { - return this.type.scope.problemReporter(); -} -private ProblemReporter problemReporter(MethodBinding currentMethod) { - ProblemReporter reporter = problemReporter(); - if (currentMethod.declaringClass == type) // only report against the currentMethod if its implemented by the type - reporter.referenceContext = currentMethod.sourceMethod(); - return reporter; -} -private ReferenceBinding runtimeException() { - if (runtimeException == null) - this.runtimeException = this.type.scope.getJavaLangRuntimeException(); - return runtimeException; -} -public void verify(SourceTypeBinding type) { - this.type = type; - this.computeMethods(); - this.computeInheritedMethods(); - this.checkMethods(); -} -public String toString() { - StringBuffer buffer = new StringBuffer(10); - buffer.append("MethodVerifier for type: "); //$NON-NLS-1$ - buffer.append(type.readableName()); - buffer.append('\n'); - buffer.append("\t-inherited methods: "); //$NON-NLS-1$ - buffer.append(this.inheritedMethods); - return buffer.toString(); -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/NestedTypeBinding.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/NestedTypeBinding.java index 2b95fd2..f6bf0ee 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/NestedTypeBinding.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/NestedTypeBinding.java @@ -15,54 +15,69 @@ public class NestedTypeBinding extends SourceTypeBinding { public SourceTypeBinding enclosingType; public SyntheticArgumentBinding[] enclosingInstances; + public SyntheticArgumentBinding[] outerLocalVariables; - public int enclosingInstancesSlotSize; // amount of slots used by synthetic enclosing instances - public int outerLocalVariablesSlotSize; // amount of slots used by synthetic outer local variables - - public NestedTypeBinding(char[][] typeName, ClassScope scope, SourceTypeBinding enclosingType) { + + public int enclosingInstancesSlotSize; // amount of slots used by synthetic + // enclosing instances + + public int outerLocalVariablesSlotSize; // amount of slots used by synthetic + // outer local variables + + public NestedTypeBinding(char[][] typeName, ClassScope scope, + SourceTypeBinding enclosingType) { super(typeName, enclosingType.fPackage, scope); this.tagBits |= IsNestedType; this.enclosingType = enclosingType; } - - /* Add a new synthetic argument for . - * Answer the new argument or the existing argument if one already existed. - */ - public SyntheticArgumentBinding addSyntheticArgument(LocalVariableBinding actualOuterLocalVariable) { + + /* + * Add a new synthetic argument for . Answer the + * new argument or the existing argument if one already existed. + */ + public SyntheticArgumentBinding addSyntheticArgument( + LocalVariableBinding actualOuterLocalVariable) { SyntheticArgumentBinding synthLocal = null; - + if (outerLocalVariables == null) { synthLocal = new SyntheticArgumentBinding(actualOuterLocalVariable); - outerLocalVariables = new SyntheticArgumentBinding[] {synthLocal}; + outerLocalVariables = new SyntheticArgumentBinding[] { synthLocal }; } else { int size = outerLocalVariables.length; int newArgIndex = size; - for (int i = size; --i >= 0;) { // must search backwards + for (int i = size; --i >= 0;) { // must search backwards if (outerLocalVariables[i].actualOuterLocalVariable == actualOuterLocalVariable) - return outerLocalVariables[i]; // already exists + return outerLocalVariables[i]; // already exists if (outerLocalVariables[i].id > actualOuterLocalVariable.id) newArgIndex = i; } SyntheticArgumentBinding[] synthLocals = new SyntheticArgumentBinding[size + 1]; - System.arraycopy(outerLocalVariables, 0, synthLocals, 0, newArgIndex); - synthLocals[newArgIndex] = synthLocal = new SyntheticArgumentBinding(actualOuterLocalVariable); - System.arraycopy(outerLocalVariables, newArgIndex, synthLocals, newArgIndex + 1, size - newArgIndex); + System.arraycopy(outerLocalVariables, 0, synthLocals, 0, + newArgIndex); + synthLocals[newArgIndex] = synthLocal = new SyntheticArgumentBinding( + actualOuterLocalVariable); + System.arraycopy(outerLocalVariables, newArgIndex, synthLocals, + newArgIndex + 1, size - newArgIndex); outerLocalVariables = synthLocals; } - //System.out.println("Adding synth arg for local var: " + new String(actualOuterLocalVariable.name) + " to: " + new String(this.readableName())); + // System.out.println("Adding synth arg for local var: " + new + // String(actualOuterLocalVariable.name) + " to: " + new + // String(this.readableName())); if (scope.referenceCompilationUnit().isPropagatingInnerClassEmulation) this.updateInnerEmulationDependents(); return synthLocal; } - /* Add a new synthetic argument for . - * Answer the new argument or the existing argument if one already existed. - */ - public SyntheticArgumentBinding addSyntheticArgument(ReferenceBinding enclosingType) { + /* + * Add a new synthetic argument for . Answer the new argument + * or the existing argument if one already existed. + */ + public SyntheticArgumentBinding addSyntheticArgument( + ReferenceBinding enclosingType) { SyntheticArgumentBinding synthLocal = null; if (enclosingInstances == null) { synthLocal = new SyntheticArgumentBinding(enclosingType); - enclosingInstances = new SyntheticArgumentBinding[] {synthLocal}; + enclosingInstances = new SyntheticArgumentBinding[] { synthLocal }; } else { int size = enclosingInstances.length; int newArgIndex = size; @@ -73,35 +88,45 @@ public class NestedTypeBinding extends SourceTypeBinding { newArgIndex = 0; } SyntheticArgumentBinding[] newInstances = new SyntheticArgumentBinding[size + 1]; - System.arraycopy(enclosingInstances, 0, newInstances, newArgIndex == 0 ? 1 : 0, size); - newInstances[newArgIndex] = synthLocal = new SyntheticArgumentBinding(enclosingType); + System.arraycopy(enclosingInstances, 0, newInstances, + newArgIndex == 0 ? 1 : 0, size); + newInstances[newArgIndex] = synthLocal = new SyntheticArgumentBinding( + enclosingType); enclosingInstances = newInstances; } - //System.out.println("Adding synth arg for enclosing type: " + new String(enclosingType.readableName()) + " to: " + new String(this.readableName())); + // System.out.println("Adding synth arg for enclosing type: " + new + // String(enclosingType.readableName()) + " to: " + new + // String(this.readableName())); if (scope.referenceCompilationUnit().isPropagatingInnerClassEmulation) this.updateInnerEmulationDependents(); return synthLocal; } - /* Add a new synthetic argument and field for . - * Answer the new argument or the existing argument if one already existed. - */ - public SyntheticArgumentBinding addSyntheticArgumentAndField(LocalVariableBinding actualOuterLocalVariable) { + /* + * Add a new synthetic argument and field for . + * Answer the new argument or the existing argument if one already existed. + */ + public SyntheticArgumentBinding addSyntheticArgumentAndField( + LocalVariableBinding actualOuterLocalVariable) { SyntheticArgumentBinding synthLocal = addSyntheticArgument(actualOuterLocalVariable); - if (synthLocal == null) return null; - + if (synthLocal == null) + return null; + if (synthLocal.matchingField == null) synthLocal.matchingField = addSyntheticField(actualOuterLocalVariable); return synthLocal; } - /* Add a new synthetic argument and field for . - * Answer the new argument or the existing argument if one already existed. - */ - public SyntheticArgumentBinding addSyntheticArgumentAndField(ReferenceBinding enclosingType) { + /* + * Add a new synthetic argument and field for . Answer the + * new argument or the existing argument if one already existed. + */ + public SyntheticArgumentBinding addSyntheticArgumentAndField( + ReferenceBinding enclosingType) { SyntheticArgumentBinding synthLocal = addSyntheticArgument(enclosingType); - if (synthLocal == null) return null; - + if (synthLocal == null) + return null; + if (synthLocal.matchingField == null) synthLocal.matchingField = addSyntheticField(enclosingType); return synthLocal; @@ -111,54 +136,69 @@ public class NestedTypeBinding extends SourceTypeBinding { * Compute the resolved positions for all the synthetic arguments */ final public void computeSyntheticArgumentSlotSizes() { - - int slotSize = 0; + + int slotSize = 0; // insert enclosing instances first, followed by the outerLocals - SyntheticArgumentBinding[] enclosingInstances = this.syntheticEnclosingInstances(); - int enclosingInstancesCount = enclosingInstances == null ? 0 : enclosingInstances.length; - for (int i = 0; i < enclosingInstancesCount; i++){ + SyntheticArgumentBinding[] enclosingInstances = this + .syntheticEnclosingInstances(); + int enclosingInstancesCount = enclosingInstances == null ? 0 + : enclosingInstances.length; + for (int i = 0; i < enclosingInstancesCount; i++) { SyntheticArgumentBinding argument = enclosingInstances[i]; // position the enclosing instance synthetic arg - argument.resolvedPosition = slotSize + 1; // shift by 1 to leave room for aload0==this + argument.resolvedPosition = slotSize + 1; // shift by 1 to leave + // room for aload0==this if (slotSize + 1 > 0xFF) { // no more than 255 words of arguments - this.scope.problemReporter().noMoreAvailableSpaceForArgument(argument, this.scope.referenceType()); + this.scope.problemReporter().noMoreAvailableSpaceForArgument( + argument, this.scope.referenceType()); } - if ((argument.type == LongBinding) || (argument.type == DoubleBinding)){ + if ((argument.type == LongBinding) + || (argument.type == DoubleBinding)) { slotSize += 2; } else { - slotSize ++; + slotSize++; } } - this.enclosingInstancesSlotSize = slotSize; - - slotSize = 0; // reset, outer local are not positionned yet, since will be appended to user arguments - SyntheticArgumentBinding[] outerLocals = this.syntheticOuterLocalVariables(); + this.enclosingInstancesSlotSize = slotSize; + + slotSize = 0; // reset, outer local are not positionned yet, since + // will be appended to user arguments + SyntheticArgumentBinding[] outerLocals = this + .syntheticOuterLocalVariables(); int outerLocalsCount = outerLocals == null ? 0 : outerLocals.length; - for (int i = 0; i < outerLocalsCount; i++){ + for (int i = 0; i < outerLocalsCount; i++) { SyntheticArgumentBinding argument = outerLocals[i]; - // do NOT position the outerlocal synthetic arg yet, since will be appended to user arguments - if ((argument.type == LongBinding) || (argument.type == DoubleBinding)){ + // do NOT position the outerlocal synthetic arg yet, since will be + // appended to user arguments + if ((argument.type == LongBinding) + || (argument.type == DoubleBinding)) { slotSize += 2; } else { - slotSize ++; + slotSize++; } } this.outerLocalVariablesSlotSize = slotSize; } - - /* Answer the receiver's enclosing type... null if the receiver is a top level type. - */ + + /* + * Answer the receiver's enclosing type... null if the receiver is a top + * level type. + */ public ReferenceBinding enclosingType() { return enclosingType; } - /* Answer the synthetic argument for or null if one does not exist. - */ - public SyntheticArgumentBinding getSyntheticArgument(LocalVariableBinding actualOuterLocalVariable) { + /* + * Answer the synthetic argument for or null if + * one does not exist. + */ + public SyntheticArgumentBinding getSyntheticArgument( + LocalVariableBinding actualOuterLocalVariable) { + + if (outerLocalVariables == null) + return null; // is null if no outer local variables are known - if (outerLocalVariables == null) return null; // is null if no outer local variables are known - for (int i = outerLocalVariables.length; --i >= 0;) if (outerLocalVariables[i].actualOuterLocalVariable == actualOuterLocalVariable) return outerLocalVariables[i]; @@ -166,13 +206,14 @@ public class NestedTypeBinding extends SourceTypeBinding { } public SyntheticArgumentBinding[] syntheticEnclosingInstances() { - return enclosingInstances; // is null if no enclosing instances are required + return enclosingInstances; // is null if no enclosing instances are + // required } public ReferenceBinding[] syntheticEnclosingInstanceTypes() { if (enclosingInstances == null) return null; - + int length = enclosingInstances.length; ReferenceBinding types[] = new ReferenceBinding[length]; for (int i = 0; i < length; i++) @@ -182,36 +223,42 @@ public class NestedTypeBinding extends SourceTypeBinding { public SyntheticArgumentBinding[] syntheticOuterLocalVariables() { - return outerLocalVariables; // is null if no outer locals are required + return outerLocalVariables; // is null if no outer locals are required } /* - * Trigger the dependency mechanism forcing the innerclass emulation - * to be propagated to all dependent source types. + * Trigger the dependency mechanism forcing the innerclass emulation to be + * propagated to all dependent source types. */ public void updateInnerEmulationDependents() { // nothing to do in general, only local types are doing anything } - - /* Answer the synthetic argument for or null if one does not exist. - */ - public SyntheticArgumentBinding getSyntheticArgument(ReferenceBinding targetEnclosingType, boolean onlyExactMatch) { - if (enclosingInstances == null) return null; // is null if no enclosing instances are known - + /* + * Answer the synthetic argument for or null if one + * does not exist. + */ + public SyntheticArgumentBinding getSyntheticArgument( + ReferenceBinding targetEnclosingType, boolean onlyExactMatch) { + + if (enclosingInstances == null) + return null; // is null if no enclosing instances are known + // exact match for (int i = enclosingInstances.length; --i >= 0;) if (enclosingInstances[i].type == targetEnclosingType) if (enclosingInstances[i].actualOuterLocalVariable == null) return enclosingInstances[i]; - + // type compatibility : to handle cases such as // class T { class M{}} - // class S extends T { class N extends M {}} --> need to use S as a default enclosing instance for the super constructor call in N(). - if (!onlyExactMatch){ + // class S extends T { class N extends M {}} --> need to use S as a + // default enclosing instance for the super constructor call in N(). + if (!onlyExactMatch) { for (int i = enclosingInstances.length; --i >= 0;) if (enclosingInstances[i].actualOuterLocalVariable == null) - if (targetEnclosingType.isSuperclassOf((ReferenceBinding) enclosingInstances[i].type)) + if (targetEnclosingType + .isSuperclassOf((ReferenceBinding) enclosingInstances[i].type)) return enclosingInstances[i]; } return null; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/PackageBinding.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/PackageBinding.java index f94c98b..a40cafa 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/PackageBinding.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/PackageBinding.java @@ -16,189 +16,235 @@ import net.sourceforge.phpdt.internal.compiler.util.HashtableOfType; public class PackageBinding extends Binding implements TypeConstants { public char[][] compoundName; + PackageBinding parent; + LookupEnvironment environment; + HashtableOfType knownTypes; + HashtableOfPackage knownPackages; -protected PackageBinding() { -} -public PackageBinding(char[][] compoundName, PackageBinding parent, LookupEnvironment environment) { - this.compoundName = compoundName; - this.parent = parent; - this.environment = environment; - this.knownTypes = null; // initialized if used... class counts can be very large 300-600 - this.knownPackages = new HashtableOfPackage(3); // sub-package counts are typically 0-3 -} -public PackageBinding(char[] topLevelPackageName, LookupEnvironment environment) { - this(new char[][] {topLevelPackageName}, null, environment); -} -/* Create the default package. -*/ -public PackageBinding(LookupEnvironment environment) { - this(CharOperation.NO_CHAR_CHAR, null, environment); -} -private void addNotFoundPackage(char[] simpleName) { - knownPackages.put(simpleName, LookupEnvironment.TheNotFoundPackage); -} -private void addNotFoundType(char[] simpleName) { - if (knownTypes == null) - knownTypes = new HashtableOfType(25); - knownTypes.put(simpleName, LookupEnvironment.TheNotFoundType); -} -void addPackage(PackageBinding element) { - knownPackages.put(element.compoundName[element.compoundName.length - 1], element); -} -void addType(ReferenceBinding element) { - if (knownTypes == null) - knownTypes = new HashtableOfType(25); - knownTypes.put(element.compoundName[element.compoundName.length - 1], element); -} -/* API -* Answer the receiver's binding type from Binding.BindingID. -*/ + protected PackageBinding() { + } -public final int bindingType() { - return PACKAGE; -} -private PackageBinding findPackage(char[] name) { - if (!environment.isPackage(this.compoundName, name)) - return null; + public PackageBinding(char[][] compoundName, PackageBinding parent, + LookupEnvironment environment) { + this.compoundName = compoundName; + this.parent = parent; + this.environment = environment; + this.knownTypes = null; // initialized if used... class counts can be + // very large 300-600 + this.knownPackages = new HashtableOfPackage(3); // sub-package counts + // are typically 0-3 + } - char[][] compoundName = CharOperation.arrayConcat(this.compoundName, name); - PackageBinding newPackageBinding = new PackageBinding(compoundName, this, environment); - addPackage(newPackageBinding); - return newPackageBinding; -} -/* Answer the subpackage named name; ask the oracle for the package if its not in the cache. -* Answer null if it could not be resolved. -* -* NOTE: This should only be used when we know there is NOT a type with the same name. -*/ - -PackageBinding getPackage(char[] name) { - PackageBinding binding = getPackage0(name); - if (binding != null) { - if (binding == LookupEnvironment.TheNotFoundPackage) - return null; - else - return binding; + public PackageBinding(char[] topLevelPackageName, + LookupEnvironment environment) { + this(new char[][] { topLevelPackageName }, null, environment); } - if ((binding = findPackage(name)) != null) - return binding; - // not found so remember a problem package binding in the cache for future lookups - addNotFoundPackage(name); - return null; -} -/* Answer the subpackage named name if it exists in the cache. -* Answer theNotFoundPackage if it could not be resolved the first time -* it was looked up, otherwise answer null. -* -* NOTE: Senders must convert theNotFoundPackage into a real problem -* package if its to returned. -*/ - -PackageBinding getPackage0(char[] name) { - return knownPackages.get(name); -} -/* Answer the type named name; ask the oracle for the type if its not in the cache. -* Answer a NotVisible problem type if the type is not visible from the invocationPackage. -* Answer null if it could not be resolved. -* -* NOTE: This should only be used by source types/scopes which know there is NOT a -* package with the same name. -*/ - -ReferenceBinding getType(char[] name) { - ReferenceBinding binding = getType0(name); - if (binding == null) { - if ((binding = environment.askForType(this, name)) == null) { - // not found so remember a problem type binding in the cache for future lookups - addNotFoundType(name); + /* + * Create the default package. + */ + + public PackageBinding(LookupEnvironment environment) { + this(CharOperation.NO_CHAR_CHAR, null, environment); + } + + private void addNotFoundPackage(char[] simpleName) { + knownPackages.put(simpleName, LookupEnvironment.TheNotFoundPackage); + } + + private void addNotFoundType(char[] simpleName) { + if (knownTypes == null) + knownTypes = new HashtableOfType(25); + knownTypes.put(simpleName, LookupEnvironment.TheNotFoundType); + } + + void addPackage(PackageBinding element) { + knownPackages.put( + element.compoundName[element.compoundName.length - 1], element); + } + + void addType(ReferenceBinding element) { + if (knownTypes == null) + knownTypes = new HashtableOfType(25); + knownTypes.put(element.compoundName[element.compoundName.length - 1], + element); + } + + /* + * API Answer the receiver's binding type from Binding.BindingID. + */ + + public final int bindingType() { + return PACKAGE; + } + + private PackageBinding findPackage(char[] name) { + if (!environment.isPackage(this.compoundName, name)) return null; - } + + char[][] compoundName = CharOperation.arrayConcat(this.compoundName, + name); + PackageBinding newPackageBinding = new PackageBinding(compoundName, + this, environment); + addPackage(newPackageBinding); + return newPackageBinding; } - if (binding == LookupEnvironment.TheNotFoundType) - return null; - if (binding instanceof UnresolvedReferenceBinding) - binding = ((UnresolvedReferenceBinding) binding).resolve(environment); - if (binding.isNestedType()) - return new ProblemReferenceBinding(name, InternalNameProvided); - return binding; -} -/* Answer the type named name if it exists in the cache. -* Answer theNotFoundType if it could not be resolved the first time -* it was looked up, otherwise answer null. -* -* NOTE: Senders must convert theNotFoundType into a real problem -* reference type if its to returned. -*/ - -ReferenceBinding getType0(char[] name) { - if (knownTypes == null) + /* + * Answer the subpackage named name; ask the oracle for the package if its + * not in the cache. Answer null if it could not be resolved. + * + * NOTE: This should only be used when we know there is NOT a type with the + * same name. + */ + + PackageBinding getPackage(char[] name) { + PackageBinding binding = getPackage0(name); + if (binding != null) { + if (binding == LookupEnvironment.TheNotFoundPackage) + return null; + else + return binding; + } + if ((binding = findPackage(name)) != null) + return binding; + + // not found so remember a problem package binding in the cache for + // future lookups + addNotFoundPackage(name); return null; - return knownTypes.get(name); -} -/* Answer the package or type named name; ask the oracle if it is not in the cache. -* Answer null if it could not be resolved. -* -* When collisions exist between a type name & a package name, answer the package. -* Treat the type as if it does not exist... a problem was already reported when the type was defined. -* -* NOTE: no visibility checks are performed. -* THIS SHOULD ONLY BE USED BY SOURCE TYPES/SCOPES. -*/ - -public Binding getTypeOrPackage(char[] name) { - PackageBinding packageBinding = getPackage0(name); - if (packageBinding != null && packageBinding != LookupEnvironment.TheNotFoundPackage) - return packageBinding; - - ReferenceBinding typeBinding = getType0(name); - if (typeBinding != null && typeBinding != LookupEnvironment.TheNotFoundType) { - if (typeBinding instanceof UnresolvedReferenceBinding) - typeBinding = ((UnresolvedReferenceBinding) typeBinding).resolve(environment); - if (typeBinding.isNestedType()) + } + + /* + * Answer the subpackage named name if it exists in the cache. Answer + * theNotFoundPackage if it could not be resolved the first time it was + * looked up, otherwise answer null. + * + * NOTE: Senders must convert theNotFoundPackage into a real problem package + * if its to returned. + */ + + PackageBinding getPackage0(char[] name) { + return knownPackages.get(name); + } + + /* + * Answer the type named name; ask the oracle for the type if its not in the + * cache. Answer a NotVisible problem type if the type is not visible from + * the invocationPackage. Answer null if it could not be resolved. + * + * NOTE: This should only be used by source types/scopes which know there is + * NOT a package with the same name. + */ + + ReferenceBinding getType(char[] name) { + ReferenceBinding binding = getType0(name); + if (binding == null) { + if ((binding = environment.askForType(this, name)) == null) { + // not found so remember a problem type binding in the cache for + // future lookups + addNotFoundType(name); + return null; + } + } + + if (binding == LookupEnvironment.TheNotFoundType) + return null; + if (binding instanceof UnresolvedReferenceBinding) + binding = ((UnresolvedReferenceBinding) binding) + .resolve(environment); + if (binding.isNestedType()) return new ProblemReferenceBinding(name, InternalNameProvided); - return typeBinding; + return binding; } - // always look for the name as a sub-package if its not a known type - if (packageBinding == null && (packageBinding = findPackage(name)) != null) - return packageBinding; - if (typeBinding == null) { - // if no package was found, find the type named name relative to the receiver - if ((typeBinding = environment.askForType(this, name)) != null) { + /* + * Answer the type named name if it exists in the cache. Answer + * theNotFoundType if it could not be resolved the first time it was looked + * up, otherwise answer null. + * + * NOTE: Senders must convert theNotFoundType into a real problem reference + * type if its to returned. + */ + + ReferenceBinding getType0(char[] name) { + if (knownTypes == null) + return null; + return knownTypes.get(name); + } + + /* + * Answer the package or type named name; ask the oracle if it is not in the + * cache. Answer null if it could not be resolved. + * + * When collisions exist between a type name & a package name, answer the + * package. Treat the type as if it does not exist... a problem was already + * reported when the type was defined. + * + * NOTE: no visibility checks are performed. THIS SHOULD ONLY BE USED BY + * SOURCE TYPES/SCOPES. + */ + + public Binding getTypeOrPackage(char[] name) { + PackageBinding packageBinding = getPackage0(name); + if (packageBinding != null + && packageBinding != LookupEnvironment.TheNotFoundPackage) + return packageBinding; + + ReferenceBinding typeBinding = getType0(name); + if (typeBinding != null + && typeBinding != LookupEnvironment.TheNotFoundType) { + if (typeBinding instanceof UnresolvedReferenceBinding) + typeBinding = ((UnresolvedReferenceBinding) typeBinding) + .resolve(environment); if (typeBinding.isNestedType()) return new ProblemReferenceBinding(name, InternalNameProvided); return typeBinding; } - // Since name could not be found, add problem bindings - // to the collections so it will be reported as an error next time. - addNotFoundPackage(name); - addNotFoundType(name); - } else { - if (packageBinding == LookupEnvironment.TheNotFoundPackage) - packageBinding = null; - if (typeBinding == LookupEnvironment.TheNotFoundType) - typeBinding = null; - } - - if (packageBinding != null) - return packageBinding; - else - return typeBinding; -} -public char[] readableName() /*java.lang*/ { - return CharOperation.concatWith(compoundName, '.'); -} -public String toString() { - if (compoundName == CharOperation.NO_CHAR_CHAR) - return "The Default Package"; //$NON-NLS-1$ - else - return "package " + ((compoundName != null) ? CharOperation.toString(compoundName) : "UNNAMED"); //$NON-NLS-1$ //$NON-NLS-2$ -} + // always look for the name as a sub-package if its not a known type + if (packageBinding == null + && (packageBinding = findPackage(name)) != null) + return packageBinding; + if (typeBinding == null) { + // if no package was found, find the type named name relative to the + // receiver + if ((typeBinding = environment.askForType(this, name)) != null) { + if (typeBinding.isNestedType()) + return new ProblemReferenceBinding(name, + InternalNameProvided); + return typeBinding; + } + + // Since name could not be found, add problem bindings + // to the collections so it will be reported as an error next time. + addNotFoundPackage(name); + addNotFoundType(name); + } else { + if (packageBinding == LookupEnvironment.TheNotFoundPackage) + packageBinding = null; + if (typeBinding == LookupEnvironment.TheNotFoundType) + typeBinding = null; + } + + if (packageBinding != null) + return packageBinding; + else + return typeBinding; + } + + public char[] readableName() /* java.lang */{ + return CharOperation.concatWith(compoundName, '.'); + } + + public String toString() { + if (compoundName == CharOperation.NO_CHAR_CHAR) + return "The Default Package"; //$NON-NLS-1$ + else + return "package " + ((compoundName != null) ? CharOperation.toString(compoundName) : "UNNAMED"); //$NON-NLS-1$ //$NON-NLS-2$ + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ProblemBinding.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ProblemBinding.java index a560f9f..212c08f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ProblemBinding.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ProblemBinding.java @@ -14,42 +14,52 @@ import net.sourceforge.phpdt.core.compiler.CharOperation; public class ProblemBinding extends Binding { public char[] name; + public ReferenceBinding searchType; + private int problemId; -// NOTE: must only answer the subset of the name related to the problem -public ProblemBinding(char[][] compoundName, int problemId) { - this(CharOperation.concatWith(compoundName, '.'), problemId); -} -// NOTE: must only answer the subset of the name related to the problem + // NOTE: must only answer the subset of the name related to the problem -public ProblemBinding(char[][] compoundName, ReferenceBinding searchType, int problemId) { - this(CharOperation.concatWith(compoundName, '.'), searchType, problemId); -} -ProblemBinding(char[] name, int problemId) { - this.name = name; - this.problemId = problemId; -} -ProblemBinding(char[] name, ReferenceBinding searchType, int problemId) { - this(name, problemId); - this.searchType = searchType; -} -/* API -* Answer the receiver's binding type from Binding.BindingID. -*/ + public ProblemBinding(char[][] compoundName, int problemId) { + this(CharOperation.concatWith(compoundName, '.'), problemId); + } -public final int bindingType() { - return VARIABLE | TYPE; -} -/* API -* Answer the problem id associated with the receiver. -* NoError if the receiver is a valid binding. -*/ + // NOTE: must only answer the subset of the name related to the problem -public final int problemId() { - return problemId; -} -public char[] readableName() { - return name; -} + public ProblemBinding(char[][] compoundName, ReferenceBinding searchType, + int problemId) { + this(CharOperation.concatWith(compoundName, '.'), searchType, problemId); + } + + ProblemBinding(char[] name, int problemId) { + this.name = name; + this.problemId = problemId; + } + + ProblemBinding(char[] name, ReferenceBinding searchType, int problemId) { + this(name, problemId); + this.searchType = searchType; + } + + /* + * API Answer the receiver's binding type from Binding.BindingID. + */ + + public final int bindingType() { + return VARIABLE | TYPE; + } + + /* + * API Answer the problem id associated with the receiver. NoError if the + * receiver is a valid binding. + */ + + public final int problemId() { + return problemId; + } + + public char[] readableName() { + return name; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ProblemFieldBinding.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ProblemFieldBinding.java index 21365f4..5317f21 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ProblemFieldBinding.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ProblemFieldBinding.java @@ -14,22 +14,28 @@ import net.sourceforge.phpdt.core.compiler.CharOperation; public class ProblemFieldBinding extends FieldBinding { private int problemId; -// NOTE: must only answer the subset of the name related to the problem -public ProblemFieldBinding(ReferenceBinding declaringClass, char[][] compoundName, int problemId) { - this(declaringClass, CharOperation.concatWith(compoundName, '.'), problemId); -} -public ProblemFieldBinding(ReferenceBinding declaringClass, char[] name, int problemId) { - this.declaringClass = declaringClass; - this.name = name; - this.problemId = problemId; -} -/* API -* Answer the problem id associated with the receiver. -* NoError if the receiver is a valid binding. -*/ + // NOTE: must only answer the subset of the name related to the problem -public final int problemId() { - return problemId; -} + public ProblemFieldBinding(ReferenceBinding declaringClass, + char[][] compoundName, int problemId) { + this(declaringClass, CharOperation.concatWith(compoundName, '.'), + problemId); + } + + public ProblemFieldBinding(ReferenceBinding declaringClass, char[] name, + int problemId) { + this.declaringClass = declaringClass; + this.name = name; + this.problemId = problemId; + } + + /* + * API Answer the problem id associated with the receiver. NoError if the + * receiver is a valid binding. + */ + + public final int problemId() { + return problemId; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ProblemMethodBinding.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ProblemMethodBinding.java index 19840fc..6bc2c6d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ProblemMethodBinding.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ProblemMethodBinding.java @@ -12,29 +12,40 @@ package net.sourceforge.phpdt.internal.compiler.lookup; public class ProblemMethodBinding extends MethodBinding { private int problemId; + public MethodBinding closestMatch; -public ProblemMethodBinding(char[] selector, TypeBinding[] args, int problemId) { - this.selector = selector; - this.parameters = (args == null || args.length == 0) ? NoParameters : args; - this.problemId = problemId; -} -public ProblemMethodBinding(char[] selector, TypeBinding[] args, ReferenceBinding declaringClass, int problemId) { - this.selector = selector; - this.parameters = (args == null || args.length == 0) ? NoParameters : args; - this.declaringClass = declaringClass; - this.problemId = problemId; -} -public ProblemMethodBinding(MethodBinding closestMatch, char[] selector, TypeBinding[] args, int problemId) { - this(selector, args, problemId); - this.closestMatch = closestMatch; - if (closestMatch != null) this.declaringClass = closestMatch.declaringClass; -} -/* API -* Answer the problem id associated with the receiver. -* NoError if the receiver is a valid binding. -*/ -public final int problemId() { - return problemId; -} + public ProblemMethodBinding(char[] selector, TypeBinding[] args, + int problemId) { + this.selector = selector; + this.parameters = (args == null || args.length == 0) ? NoParameters + : args; + this.problemId = problemId; + } + + public ProblemMethodBinding(char[] selector, TypeBinding[] args, + ReferenceBinding declaringClass, int problemId) { + this.selector = selector; + this.parameters = (args == null || args.length == 0) ? NoParameters + : args; + this.declaringClass = declaringClass; + this.problemId = problemId; + } + + public ProblemMethodBinding(MethodBinding closestMatch, char[] selector, + TypeBinding[] args, int problemId) { + this(selector, args, problemId); + this.closestMatch = closestMatch; + if (closestMatch != null) + this.declaringClass = closestMatch.declaringClass; + } + + /* + * API Answer the problem id associated with the receiver. NoError if the + * receiver is a valid binding. + */ + + public final int problemId() { + return problemId; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ProblemPackageBinding.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ProblemPackageBinding.java index ca3570d..f861286 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ProblemPackageBinding.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ProblemPackageBinding.java @@ -9,24 +9,27 @@ * IBM Corporation - initial API and implementation *******************************************************************************/ package net.sourceforge.phpdt.internal.compiler.lookup; - + public class ProblemPackageBinding extends PackageBinding { private int problemId; -// NOTE: must only answer the subset of the name related to the problem -ProblemPackageBinding(char[][] compoundName, int problemId) { - this.compoundName = compoundName; - this.problemId = problemId; -} -ProblemPackageBinding(char[] name, int problemId) { - this(new char[][] {name}, problemId); -} -/* API -* Answer the problem id associated with the receiver. -* NoError if the receiver is a valid binding. -*/ + // NOTE: must only answer the subset of the name related to the problem -public final int problemId() { - return problemId; -} + ProblemPackageBinding(char[][] compoundName, int problemId) { + this.compoundName = compoundName; + this.problemId = problemId; + } + + ProblemPackageBinding(char[] name, int problemId) { + this(new char[][] { name }, problemId); + } + + /* + * API Answer the problem id associated with the receiver. NoError if the + * receiver is a valid binding. + */ + + public final int problemId() { + return problemId; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ProblemReasons.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ProblemReasons.java index dd05fd9..3a9a4cd 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ProblemReasons.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ProblemReasons.java @@ -11,13 +11,22 @@ package net.sourceforge.phpdt.internal.compiler.lookup; public interface ProblemReasons { - final int NoError = 0; - final int NotFound = 1; - final int NotVisible = 2; - final int Ambiguous = 3; - final int InternalNameProvided = 4; // used if an internal name is used in source - final int InheritedNameHidesEnclosingName = 5; - final int NonStaticReferenceInConstructorInvocation = 6; - final int NonStaticReferenceInStaticContext = 7; - final int ReceiverTypeNotVisible = 8; + final int NoError = 0; + + final int NotFound = 1; + + final int NotVisible = 2; + + final int Ambiguous = 3; + + final int InternalNameProvided = 4; // used if an internal name is used in + // source + + final int InheritedNameHidesEnclosingName = 5; + + final int NonStaticReferenceInConstructorInvocation = 6; + + final int NonStaticReferenceInStaticContext = 7; + + final int ReceiverTypeNotVisible = 8; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ProblemReferenceBinding.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ProblemReferenceBinding.java index 3fa5886..8489e5d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ProblemReferenceBinding.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ProblemReferenceBinding.java @@ -12,38 +12,45 @@ package net.sourceforge.phpdt.internal.compiler.lookup; public class ProblemReferenceBinding extends ReferenceBinding { public ReferenceBinding original; + private int problemId; -// NOTE: must only answer the subset of the name related to the problem -public ProblemReferenceBinding(char[][] compoundName, int problemId) { - this(compoundName, null, problemId); -} -public ProblemReferenceBinding(char[] name, int problemId) { - this(new char[][] {name}, null, problemId); -} + // NOTE: must only answer the subset of the name related to the problem -public ProblemReferenceBinding(char[][] compoundName, ReferenceBinding original, int problemId) { - this.compoundName = compoundName; - this.original = original; - this.problemId = problemId; -} -public ProblemReferenceBinding(char[] name, ReferenceBinding original, int problemId) { - this(new char[][] {name}, original, problemId); -} -/* API -* Answer the problem id associated with the receiver. -* NoError if the receiver is a valid binding. -*/ + public ProblemReferenceBinding(char[][] compoundName, int problemId) { + this(compoundName, null, problemId); + } -public final int problemId() { - return problemId; -} + public ProblemReferenceBinding(char[] name, int problemId) { + this(new char[][] { name }, null, problemId); + } -/** - * @see net.sourceforge.phpdt.internal.compiler.lookup.ReferenceBinding#shortReadableName() - */ -public char[] shortReadableName() { - return readableName(); -} + public ProblemReferenceBinding(char[][] compoundName, + ReferenceBinding original, int problemId) { + this.compoundName = compoundName; + this.original = original; + this.problemId = problemId; + } + + public ProblemReferenceBinding(char[] name, ReferenceBinding original, + int problemId) { + this(new char[][] { name }, original, problemId); + } + + /* + * API Answer the problem id associated with the receiver. NoError if the + * receiver is a valid binding. + */ + + public final int problemId() { + return problemId; + } + + /** + * @see net.sourceforge.phpdt.internal.compiler.lookup.ReferenceBinding#shortReadableName() + */ + public char[] shortReadableName() { + return readableName(); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ReferenceBinding.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ReferenceBinding.java index ab0d9cf..d2dd308 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ReferenceBinding.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/ReferenceBinding.java @@ -14,86 +14,204 @@ import net.sourceforge.phpdt.core.compiler.CharOperation; import net.sourceforge.phpdt.internal.compiler.env.IDependent; /* -Not all fields defined by this type (& its subclasses) are initialized when it is created. -Some are initialized only when needed. - -Accessors have been provided for some public fields so all TypeBindings have the same API... -but access public fields directly whenever possible. -Non-public fields have accessors which should be used everywhere you expect the field to be initialized. - -null is NOT a valid value for a non-public field... it just means the field is not initialized. -*/ + * Not all fields defined by this type (& its subclasses) are initialized when + * it is created. Some are initialized only when needed. + * + * Accessors have been provided for some public fields so all TypeBindings have + * the same API... but access public fields directly whenever possible. + * Non-public fields have accessors which should be used everywhere you expect + * the field to be initialized. + * + * null is NOT a valid value for a non-public field... it just means the field + * is not initialized. + */ -abstract public class ReferenceBinding extends TypeBinding implements IDependent { +abstract public class ReferenceBinding extends TypeBinding implements + IDependent { public char[][] compoundName; + public char[] sourceName; + public int modifiers; + public PackageBinding fPackage; char[] fileName; + char[] constantPoolName; + char[] signature; -public FieldBinding[] availableFields() { - return fields(); -} + public FieldBinding[] availableFields() { + return fields(); + } -public MethodBinding[] availableMethods() { - return methods(); -} -/* Answer true if the receiver can be instantiated -*/ + public MethodBinding[] availableMethods() { + return methods(); + } -public boolean canBeInstantiated() { - return !(isAbstract() || isInterface()); -} -/* Answer true if the receiver is visible to the invocationPackage. -*/ + /* + * Answer true if the receiver can be instantiated + */ -public final boolean canBeSeenBy(PackageBinding invocationPackage) { - if (isPublic()) return true; - if (isPrivate()) return false; + public boolean canBeInstantiated() { + return !(isAbstract() || isInterface()); + } - // isProtected() or isDefault() - return invocationPackage == fPackage; -} -/* Answer true if the receiver is visible to the receiverType and the invocationType. -*/ + /* + * Answer true if the receiver is visible to the invocationPackage. + */ + + public final boolean canBeSeenBy(PackageBinding invocationPackage) { + if (isPublic()) + return true; + if (isPrivate()) + return false; + + // isProtected() or isDefault() + return invocationPackage == fPackage; + } -public final boolean canBeSeenBy(ReferenceBinding receiverType, SourceTypeBinding invocationType) { - if (isPublic()) return true; + /* + * Answer true if the receiver is visible to the receiverType and the + * invocationType. + */ - if (invocationType == this && invocationType == receiverType) return true; + public final boolean canBeSeenBy(ReferenceBinding receiverType, + SourceTypeBinding invocationType) { + if (isPublic()) + return true; - if (isProtected()) { + if (invocationType == this && invocationType == receiverType) + return true; - // answer true if the invocationType is the declaringClass or they are in the same package - // OR the invocationType is a subclass of the declaringClass - // AND the invocationType is the invocationType or its subclass - // OR the type is a static method accessed directly through a type - // OR previous assertions are true for one of the enclosing type - if (invocationType == this) return true; - if (invocationType.fPackage == fPackage) return true; + if (isProtected()) { - ReferenceBinding currentType = invocationType; - ReferenceBinding declaringClass = enclosingType(); // protected types always have an enclosing one - if (declaringClass == null) return false; // could be null if incorrect top-level protected type - //int depth = 0; + // answer true if the invocationType is the declaringClass or they + // are in the same package + // OR the invocationType is a subclass of the declaringClass + // AND the invocationType is the invocationType or its subclass + // OR the type is a static method accessed directly through a type + // OR previous assertions are true for one of the enclosing type + if (invocationType == this) + return true; + if (invocationType.fPackage == fPackage) + return true; + + ReferenceBinding currentType = invocationType; + ReferenceBinding declaringClass = enclosingType(); // protected + // types always + // have an + // enclosing one + if (declaringClass == null) + return false; // could be null if incorrect top-level + // protected type + // int depth = 0; + do { + if (declaringClass == invocationType) + return true; + if (declaringClass.isSuperclassOf(currentType)) + return true; + // depth++; + currentType = currentType.enclosingType(); + } while (currentType != null); + return false; + } + + if (isPrivate()) { + // answer true if the receiverType is the receiver or its + // enclosingType + // AND the invocationType and the receiver have a common + // enclosingType + if (!(receiverType == this || receiverType == enclosingType())) + return false; + + if (invocationType != this) { + ReferenceBinding outerInvocationType = invocationType; + ReferenceBinding temp = outerInvocationType.enclosingType(); + while (temp != null) { + outerInvocationType = temp; + temp = temp.enclosingType(); + } + + ReferenceBinding outerDeclaringClass = this; + temp = outerDeclaringClass.enclosingType(); + while (temp != null) { + outerDeclaringClass = temp; + temp = temp.enclosingType(); + } + if (outerInvocationType != outerDeclaringClass) + return false; + } + return true; + } + + // isDefault() + if (invocationType.fPackage != fPackage) + return false; + + ReferenceBinding type = receiverType; + ReferenceBinding declaringClass = enclosingType() == null ? this + : enclosingType(); do { - if (declaringClass == invocationType) return true; - if (declaringClass.isSuperclassOf(currentType)) return true; - //depth++; - currentType = currentType.enclosingType(); - } while (currentType != null); + if (declaringClass == type) + return true; + if (fPackage != type.fPackage) + return false; + } while ((type = type.superclass()) != null); return false; } - if (isPrivate()) { - // answer true if the receiverType is the receiver or its enclosingType - // AND the invocationType and the receiver have a common enclosingType - if (!(receiverType == this || receiverType == enclosingType())) return false; - - if (invocationType != this) { + /* + * Answer true if the receiver is visible to the type provided by the scope. + */ + + public final boolean canBeSeenBy(Scope scope) { + + if (isPublic()) + return true; + + if (scope.kind == Scope.COMPILATION_UNIT_SCOPE) { + return this.canBeSeenBy(((CompilationUnitScope) scope).fPackage); + } + + SourceTypeBinding invocationType = scope.enclosingSourceType(); + if (invocationType == this) + return true; + + if (isProtected()) { + // answer true if the invocationType is the declaringClass or they + // are in the same package + // OR the invocationType is a subclass of the declaringClass + // AND the invocationType is the invocationType or its subclass + // OR the type is a static method accessed directly through a type + // OR previous assertions are true for one of the enclosing type + if (invocationType.fPackage == fPackage) + return true; + + ReferenceBinding currentType = invocationType; + ReferenceBinding declaringClass = enclosingType(); // protected + // types always + // have an + // enclosing one + if (declaringClass == null) + return false; // could be null if incorrect top-level + // protected type + // int depth = 0; + do { + if (declaringClass == invocationType) + return true; + if (declaringClass.isSuperclassOf(currentType)) + return true; + // depth++; + currentType = currentType.enclosingType(); + } while (currentType != null); + return false; + } + if (isPrivate()) { + // answer true if the receiver and the invocationType have a common + // enclosingType + // already know they are not the identical type ReferenceBinding outerInvocationType = invocationType; ReferenceBinding temp = outerInvocationType.enclosingType(); while (temp != null) { @@ -107,503 +225,526 @@ public final boolean canBeSeenBy(ReferenceBinding receiverType, SourceTypeBindin outerDeclaringClass = temp; temp = temp.enclosingType(); } - if (outerInvocationType != outerDeclaringClass) return false; + return outerInvocationType == outerDeclaringClass; } - return true; + + // isDefault() + return invocationType.fPackage == fPackage; } - // isDefault() - if (invocationType.fPackage != fPackage) return false; + // public void computeId() { + // if (compoundName.length != 3) { + // if (compoundName.length == 4 && + // CharOperation.equals(JAVA_LANG_REFLECT_CONSTRUCTOR, compoundName)) { + // id = T_JavaLangReflectConstructor; + // return; + // } + // return; // all other types are in java.*.* + // } + // + // if (!CharOperation.equals(JAVA, compoundName[0])) + // return; // assumes we only look up types in java + // + // if (!CharOperation.equals(LANG, compoundName[1])) { + // if (CharOperation.equals(JAVA_IO_PRINTSTREAM, compoundName)) { + // id = T_JavaIoPrintStream; + // return; + // } + // return; // all other types are in java.lang + // } + // + // if (CharOperation.equals(JAVA_LANG_OBJECT, compoundName)) { + // id = T_JavaLangObject; + // return; + // } + // if (CharOperation.equals(JAVA_LANG_STRING, compoundName)) { + // id = T_JavaLangString; + // return; + // } + // + // // well-known exception types + // if (CharOperation.equals(JAVA_LANG_THROWABLE, compoundName)) { + // id = T_JavaLangThrowable; + // return; + // } + // if (CharOperation.equals(JAVA_LANG_ERROR, compoundName)) { + // id = T_JavaLangError; + // return; + // } + // if (CharOperation.equals(JAVA_LANG_EXCEPTION, compoundName)) { + // id = T_JavaLangException; + // return; + // } + // if (CharOperation.equals(JAVA_LANG_CLASSNOTFOUNDEXCEPTION, compoundName)) + // { + // id = T_JavaLangClassNotFoundException; + // return; + // } + // if (CharOperation.equals(JAVA_LANG_NOCLASSDEFERROR, compoundName)) { + // id = T_JavaLangNoClassDefError; + // return; + // } + // + // // other well-known types + // if (CharOperation.equals(JAVA_LANG_CLASS, compoundName)) { + // id = T_JavaLangClass; + // return; + // } + // if (CharOperation.equals(JAVA_LANG_STRINGBUFFER, compoundName)) { + // id = T_JavaLangStringBuffer; + // return; + // } + // if (CharOperation.equals(JAVA_LANG_SYSTEM, compoundName)) { + // id = T_JavaLangSystem; + // return; + // } + // + // if (CharOperation.equals(JAVA_LANG_INTEGER, compoundName)) { + // id = T_JavaLangInteger; + // return; + // } + // + // if (CharOperation.equals(JAVA_LANG_BYTE, compoundName)) { + // id = T_JavaLangByte; + // return; + // } + // + // if (CharOperation.equals(JAVA_LANG_CHARACTER, compoundName)) { + // id = T_JavaLangCharacter; + // return; + // } + // + // if (CharOperation.equals(JAVA_LANG_FLOAT, compoundName)) { + // id = T_JavaLangFloat; + // return; + // } + // + // if (CharOperation.equals(JAVA_LANG_DOUBLE, compoundName)) { + // id = T_JavaLangDouble; + // return; + // } + // + // if (CharOperation.equals(JAVA_LANG_BOOLEAN, compoundName)) { + // id = T_JavaLangBoolean; + // return; + // } + // + // if (CharOperation.equals(JAVA_LANG_SHORT, compoundName)) { + // id = T_JavaLangShort; + // return; + // } + // + // if (CharOperation.equals(JAVA_LANG_LONG, compoundName)) { + // id = T_JavaLangLong; + // return; + // } + // + // if (CharOperation.equals(JAVA_LANG_VOID, compoundName)) { + // id = T_JavaLangVoid; + // return; + // } + // + // if (CharOperation.equals(JAVA_LANG_ASSERTIONERROR, compoundName)) { + // id = T_JavaLangAssertionError; + // return; + // } + // } + /* + * Answer the receiver's constant pool name. + * + * NOTE: This method should only be used during/after code gen. + */ + + public char[] constantPoolName() /* java/lang/Object */{ + if (constantPoolName != null) + return constantPoolName; + return constantPoolName = CharOperation.concatWith(compoundName, '/'); + } - ReferenceBinding type = receiverType; - ReferenceBinding declaringClass = enclosingType() == null ? this : enclosingType(); - do { - if (declaringClass == type) return true; - if (fPackage != type.fPackage) return false; - } while ((type = type.superclass()) != null); - return false; -} -/* - * Answer true if the receiver is visible to the type provided by the scope. - */ + String debugName() { + return (compoundName != null) ? new String(readableName()) + : "UNNAMED TYPE"; //$NON-NLS-1$ + } -public final boolean canBeSeenBy(Scope scope) { - - if (isPublic()) return true; - - if (scope.kind == Scope.COMPILATION_UNIT_SCOPE){ - return this.canBeSeenBy(((CompilationUnitScope)scope).fPackage); - } - - SourceTypeBinding invocationType = scope.enclosingSourceType(); - if (invocationType == this) return true; - - if (isProtected()) { - // answer true if the invocationType is the declaringClass or they are in the same package - // OR the invocationType is a subclass of the declaringClass - // AND the invocationType is the invocationType or its subclass - // OR the type is a static method accessed directly through a type - // OR previous assertions are true for one of the enclosing type - if (invocationType.fPackage == fPackage) return true; - - ReferenceBinding currentType = invocationType; - ReferenceBinding declaringClass = enclosingType(); // protected types always have an enclosing one - if (declaringClass == null) return false; // could be null if incorrect top-level protected type - // int depth = 0; - do { - if (declaringClass == invocationType) return true; - if (declaringClass.isSuperclassOf(currentType)) return true; - // depth++; - currentType = currentType.enclosingType(); - } while (currentType != null); - return false; + public final int depth() { + int depth = 0; + ReferenceBinding current = this; + while ((current = current.enclosingType()) != null) + depth++; + return depth; } - if (isPrivate()) { - // answer true if the receiver and the invocationType have a common enclosingType - // already know they are not the identical type - ReferenceBinding outerInvocationType = invocationType; - ReferenceBinding temp = outerInvocationType.enclosingType(); - while (temp != null) { - outerInvocationType = temp; - temp = temp.enclosingType(); - } - ReferenceBinding outerDeclaringClass = this; - temp = outerDeclaringClass.enclosingType(); - while (temp != null) { - outerDeclaringClass = temp; - temp = temp.enclosingType(); - } - return outerInvocationType == outerDeclaringClass; + /* + * Answer the receiver's enclosing type... null if the receiver is a top + * level type. + */ + + public ReferenceBinding enclosingType() { + return null; } - // isDefault() - return invocationType.fPackage == fPackage; -} -//public void computeId() { -// if (compoundName.length != 3) { -// if (compoundName.length == 4 && CharOperation.equals(JAVA_LANG_REFLECT_CONSTRUCTOR, compoundName)) { -// id = T_JavaLangReflectConstructor; -// return; -// } -// return; // all other types are in java.*.* -// } -// -// if (!CharOperation.equals(JAVA, compoundName[0])) -// return; // assumes we only look up types in java -// -// if (!CharOperation.equals(LANG, compoundName[1])) { -// if (CharOperation.equals(JAVA_IO_PRINTSTREAM, compoundName)) { -// id = T_JavaIoPrintStream; -// return; -// } -// return; // all other types are in java.lang -// } -// -// if (CharOperation.equals(JAVA_LANG_OBJECT, compoundName)) { -// id = T_JavaLangObject; -// return; -// } -// if (CharOperation.equals(JAVA_LANG_STRING, compoundName)) { -// id = T_JavaLangString; -// return; -// } -// -// // well-known exception types -// if (CharOperation.equals(JAVA_LANG_THROWABLE, compoundName)) { -// id = T_JavaLangThrowable; -// return; -// } -// if (CharOperation.equals(JAVA_LANG_ERROR, compoundName)) { -// id = T_JavaLangError; -// return; -// } -// if (CharOperation.equals(JAVA_LANG_EXCEPTION, compoundName)) { -// id = T_JavaLangException; -// return; -// } -// if (CharOperation.equals(JAVA_LANG_CLASSNOTFOUNDEXCEPTION, compoundName)) { -// id = T_JavaLangClassNotFoundException; -// return; -// } -// if (CharOperation.equals(JAVA_LANG_NOCLASSDEFERROR, compoundName)) { -// id = T_JavaLangNoClassDefError; -// return; -// } -// -// // other well-known types -// if (CharOperation.equals(JAVA_LANG_CLASS, compoundName)) { -// id = T_JavaLangClass; -// return; -// } -// if (CharOperation.equals(JAVA_LANG_STRINGBUFFER, compoundName)) { -// id = T_JavaLangStringBuffer; -// return; -// } -// if (CharOperation.equals(JAVA_LANG_SYSTEM, compoundName)) { -// id = T_JavaLangSystem; -// return; -// } -// -// if (CharOperation.equals(JAVA_LANG_INTEGER, compoundName)) { -// id = T_JavaLangInteger; -// return; -// } -// -// if (CharOperation.equals(JAVA_LANG_BYTE, compoundName)) { -// id = T_JavaLangByte; -// return; -// } -// -// if (CharOperation.equals(JAVA_LANG_CHARACTER, compoundName)) { -// id = T_JavaLangCharacter; -// return; -// } -// -// if (CharOperation.equals(JAVA_LANG_FLOAT, compoundName)) { -// id = T_JavaLangFloat; -// return; -// } -// -// if (CharOperation.equals(JAVA_LANG_DOUBLE, compoundName)) { -// id = T_JavaLangDouble; -// return; -// } -// -// if (CharOperation.equals(JAVA_LANG_BOOLEAN, compoundName)) { -// id = T_JavaLangBoolean; -// return; -// } -// -// if (CharOperation.equals(JAVA_LANG_SHORT, compoundName)) { -// id = T_JavaLangShort; -// return; -// } -// -// if (CharOperation.equals(JAVA_LANG_LONG, compoundName)) { -// id = T_JavaLangLong; -// return; -// } -// -// if (CharOperation.equals(JAVA_LANG_VOID, compoundName)) { -// id = T_JavaLangVoid; -// return; -// } -// -// if (CharOperation.equals(JAVA_LANG_ASSERTIONERROR, compoundName)) { -// id = T_JavaLangAssertionError; -// return; -// } -//} -/* Answer the receiver's constant pool name. -* -* NOTE: This method should only be used during/after code gen. -*/ - -public char[] constantPoolName() /* java/lang/Object */ { - if (constantPoolName != null) return constantPoolName; - return constantPoolName = CharOperation.concatWith(compoundName, '/'); -} -String debugName() { - return (compoundName != null) ? new String(readableName()) : "UNNAMED TYPE"; //$NON-NLS-1$ -} -public final int depth() { - int depth = 0; - ReferenceBinding current = this; - while ((current = current.enclosingType()) != null) - depth++; - return depth; -} -/* Answer the receiver's enclosing type... null if the receiver is a top level type. -*/ + public final ReferenceBinding enclosingTypeAt(int relativeDepth) { + ReferenceBinding current = this; + while (relativeDepth-- > 0 && current != null) + current = current.enclosingType(); + return current; + } -public ReferenceBinding enclosingType() { - return null; -} -public final ReferenceBinding enclosingTypeAt(int relativeDepth) { - ReferenceBinding current = this; - while (relativeDepth-- > 0 && current != null) - current = current.enclosingType(); - return current; -} -public int fieldCount() { - return fields().length; -} -public FieldBinding[] fields() { - return NoFields; -} -public final int getAccessFlags() { - return modifiers & AccJustFlag; -} -public MethodBinding getExactConstructor(TypeBinding[] argumentTypes) { - return null; -} -public MethodBinding getExactMethod(char[] selector, TypeBinding[] argumentTypes) { - return null; -} -public FieldBinding getField(char[] fieldName) { - return null; -} -/** - * Answer the file name which defines the type. - * - * The path part (optional) must be separated from the actual - * file proper name by a java.io.File.separator. - * - * The proper file name includes the suffix extension (e.g. ".java") - * - * e.g. "c:/com/ibm/compiler/java/api/Compiler.java" - */ + public int fieldCount() { + return fields().length; + } -public char[] getFileName() { - return fileName; -} -public ReferenceBinding getMemberType(char[] typeName) { - ReferenceBinding[] memberTypes = memberTypes(); - for (int i = memberTypes.length; --i >= 0;) - if (CharOperation.equals(memberTypes[i].sourceName, typeName)) - return memberTypes[i]; - return null; -} -public MethodBinding[] getMethods(char[] selector) { - return NoMethods; -} -public PackageBinding getPackage() { - return fPackage; -} -/* Answer true if the receiver implements anInterface or is identical to anInterface. -* If searchHierarchy is true, then also search the receiver's superclasses. -* -* NOTE: Assume that anInterface is an interface. -*/ - -public boolean implementsInterface(ReferenceBinding anInterface, boolean searchHierarchy) { - if (this == anInterface) - return true; - - ReferenceBinding[][] interfacesToVisit = new ReferenceBinding[5][]; - int lastPosition = -1; - ReferenceBinding currentType = this; - do { - ReferenceBinding[] itsInterfaces = currentType.superInterfaces(); - if (itsInterfaces != NoSuperInterfaces) { - if (++lastPosition == interfacesToVisit.length) - System.arraycopy(interfacesToVisit, 0, interfacesToVisit = new ReferenceBinding[lastPosition * 2][], 0, lastPosition); - interfacesToVisit[lastPosition] = itsInterfaces; - } - } while (searchHierarchy && (currentType = currentType.superclass()) != null); - - for (int i = 0; i <= lastPosition; i++) { - ReferenceBinding[] interfaces = interfacesToVisit[i]; - for (int j = 0, length = interfaces.length; j < length; j++) { - if ((currentType = interfaces[j]) == anInterface) - return true; + public FieldBinding[] fields() { + return NoFields; + } + + public final int getAccessFlags() { + return modifiers & AccJustFlag; + } + + public MethodBinding getExactConstructor(TypeBinding[] argumentTypes) { + return null; + } + + public MethodBinding getExactMethod(char[] selector, + TypeBinding[] argumentTypes) { + return null; + } + + public FieldBinding getField(char[] fieldName) { + return null; + } + + /** + * Answer the file name which defines the type. + * + * The path part (optional) must be separated from the actual file proper + * name by a java.io.File.separator. + * + * The proper file name includes the suffix extension (e.g. ".java") + * + * e.g. "c:/com/ibm/compiler/java/api/Compiler.java" + */ + + public char[] getFileName() { + return fileName; + } + + public ReferenceBinding getMemberType(char[] typeName) { + ReferenceBinding[] memberTypes = memberTypes(); + for (int i = memberTypes.length; --i >= 0;) + if (CharOperation.equals(memberTypes[i].sourceName, typeName)) + return memberTypes[i]; + return null; + } + + public MethodBinding[] getMethods(char[] selector) { + return NoMethods; + } + public PackageBinding getPackage() { + return fPackage; + } + + /* + * Answer true if the receiver implements anInterface or is identical to + * anInterface. If searchHierarchy is true, then also search the receiver's + * superclasses. + * + * NOTE: Assume that anInterface is an interface. + */ + + public boolean implementsInterface(ReferenceBinding anInterface, + boolean searchHierarchy) { + if (this == anInterface) + return true; + + ReferenceBinding[][] interfacesToVisit = new ReferenceBinding[5][]; + int lastPosition = -1; + ReferenceBinding currentType = this; + do { ReferenceBinding[] itsInterfaces = currentType.superInterfaces(); if (itsInterfaces != NoSuperInterfaces) { if (++lastPosition == interfacesToVisit.length) - System.arraycopy(interfacesToVisit, 0, interfacesToVisit = new ReferenceBinding[lastPosition * 2][], 0, lastPosition); + System + .arraycopy( + interfacesToVisit, + 0, + interfacesToVisit = new ReferenceBinding[lastPosition * 2][], + 0, lastPosition); interfacesToVisit[lastPosition] = itsInterfaces; } + } while (searchHierarchy + && (currentType = currentType.superclass()) != null); + + for (int i = 0; i <= lastPosition; i++) { + ReferenceBinding[] interfaces = interfacesToVisit[i]; + for (int j = 0, length = interfaces.length; j < length; j++) { + if ((currentType = interfaces[j]) == anInterface) + return true; + + ReferenceBinding[] itsInterfaces = currentType + .superInterfaces(); + if (itsInterfaces != NoSuperInterfaces) { + if (++lastPosition == interfacesToVisit.length) + System + .arraycopy( + interfacesToVisit, + 0, + interfacesToVisit = new ReferenceBinding[lastPosition * 2][], + 0, lastPosition); + interfacesToVisit[lastPosition] = itsInterfaces; + } + } } + return false; } - return false; -} -// Internal method... assume its only sent to classes NOT interfaces - -boolean implementsMethod(MethodBinding method) { - ReferenceBinding type = this; - while (type != null) { - MethodBinding[] methods = type.getMethods(method.selector); - for (int i = methods.length; --i >= 0;) - if (methods[i].areParametersEqual(method)) - return true; - type = type.superclass(); - } - return false; -} -/* Answer true if the receiver is an abstract type -*/ -public final boolean isAbstract() { - return (modifiers & AccAbstract) != 0; -} -public final boolean isAnonymousType() { - return (tagBits & IsAnonymousType) != 0; -} -public final boolean isBinaryBinding() { - return (tagBits & IsBinaryBinding) != 0; -} -public final boolean isClass() { - return (modifiers & AccInterface) == 0; -} -/* Answer true if the receiver type can be assigned to the argument type (right) -*/ - -public boolean isCompatibleWith(TypeBinding right) { - if (right == this) - return true; - if (right.id == T_Object) - return true; - if (!(right instanceof ReferenceBinding)) + // Internal method... assume its only sent to classes NOT interfaces + + boolean implementsMethod(MethodBinding method) { + ReferenceBinding type = this; + while (type != null) { + MethodBinding[] methods = type.getMethods(method.selector); + for (int i = methods.length; --i >= 0;) + if (methods[i].areParametersEqual(method)) + return true; + type = type.superclass(); + } return false; + } + + /* + * Answer true if the receiver is an abstract type + */ + + public final boolean isAbstract() { + return (modifiers & AccAbstract) != 0; + } + + public final boolean isAnonymousType() { + return (tagBits & IsAnonymousType) != 0; + } + + public final boolean isBinaryBinding() { + return (tagBits & IsBinaryBinding) != 0; + } + + public final boolean isClass() { + return (modifiers & AccInterface) == 0; + } + + /* + * Answer true if the receiver type can be assigned to the argument type + * (right) + */ + + public boolean isCompatibleWith(TypeBinding right) { + if (right == this) + return true; + if (right.id == T_Object) + return true; + if (!(right instanceof ReferenceBinding)) + return false; + + ReferenceBinding referenceBinding = (ReferenceBinding) right; + if (referenceBinding.isInterface()) + return implementsInterface(referenceBinding, true); + if (isInterface()) // Explicit conversion from an interface to a class + // is not allowed + return false; + return referenceBinding.isSuperclassOf(this); + } + + /* + * Answer true if the receiver has default visibility + */ + + public final boolean isDefault() { + return (modifiers & (AccPublic | AccProtected | AccPrivate)) == 0; + } + + /* + * Answer true if the receiver is a deprecated type + */ + + public final boolean isDeprecated() { + return (modifiers & AccDeprecated) != 0; + } + + /* + * Answer true if the receiver is final and cannot be subclassed + */ + + public final boolean isFinal() { + return (modifiers & AccFinal) != 0; + } + + public final boolean isInterface() { + return (modifiers & AccInterface) != 0; + } + + public final boolean isLocalType() { + return (tagBits & IsLocalType) != 0; + } + + public final boolean isMemberType() { + return (tagBits & IsMemberType) != 0; + } + + public final boolean isNestedType() { + return (tagBits & IsNestedType) != 0; + } + + /* + * Answer true if the receiver has private visibility + */ + + public final boolean isPrivate() { + return (modifiers & AccPrivate) != 0; + } + + /* + * Answer true if the receiver has private visibility and is used locally + */ + + public final boolean isPrivateUsed() { + return (modifiers & AccPrivateUsed) != 0; + } + + /* + * Answer true if the receiver has protected visibility + */ + + public final boolean isProtected() { + return (modifiers & AccProtected) != 0; + } + + /* + * Answer true if the receiver has public visibility + */ + + public final boolean isPublic() { + return (modifiers & AccPublic) != 0; + } + + /* + * Answer true if the receiver is a static member type (or toplevel) + */ + + public final boolean isStatic() { + return (modifiers & (AccStatic | AccInterface)) != 0 + || (tagBits & IsNestedType) == 0; + } + + /* + * Answer true if all float operations must adher to IEEE 754 float/double + * rules + */ + + // public final boolean isStrictfp() { + // return (modifiers & AccStrictfp) != 0; + // } + /* + * Answer true if the receiver is in the superclass hierarchy of aType + * + * NOTE: Object.isSuperclassOf(Object) -> false + */ + + public boolean isSuperclassOf(ReferenceBinding type) { + do { + if (this == (type = type.superclass())) + return true; + } while (type != null); - ReferenceBinding referenceBinding = (ReferenceBinding) right; - if (referenceBinding.isInterface()) - return implementsInterface(referenceBinding, true); - if (isInterface()) // Explicit conversion from an interface to a class is not allowed return false; - return referenceBinding.isSuperclassOf(this); -} -/* Answer true if the receiver has default visibility -*/ + } -public final boolean isDefault() { - return (modifiers & (AccPublic | AccProtected | AccPrivate)) == 0; -} -/* Answer true if the receiver is a deprecated type -*/ + /* + * Answer true if the receiver is deprecated (or any of its enclosing types) + */ -public final boolean isDeprecated() { - return (modifiers & AccDeprecated) != 0; -} -/* Answer true if the receiver is final and cannot be subclassed -*/ + public final boolean isViewedAsDeprecated() { + return (modifiers & AccDeprecated) != 0 + || (modifiers & AccDeprecatedImplicitly) != 0; + } -public final boolean isFinal() { - return (modifiers & AccFinal) != 0; -} -public final boolean isInterface() { - return (modifiers & AccInterface) != 0; -} -public final boolean isLocalType() { - return (tagBits & IsLocalType) != 0; -} -public final boolean isMemberType() { - return (tagBits & IsMemberType) != 0; -} -public final boolean isNestedType() { - return (tagBits & IsNestedType) != 0; -} -/* Answer true if the receiver has private visibility -*/ + public ReferenceBinding[] memberTypes() { + return NoMemberTypes; + } -public final boolean isPrivate() { - return (modifiers & AccPrivate) != 0; -} -/* Answer true if the receiver has private visibility and is used locally -*/ + public MethodBinding[] methods() { + return NoMethods; + } -public final boolean isPrivateUsed() { - return (modifiers & AccPrivateUsed) != 0; -} -/* Answer true if the receiver has protected visibility -*/ + /** + * Answer the source name for the type. In the case of member types, as the + * qualified name from its top level type. For example, for a member type N + * defined inside M & A: "A.M.N". + */ + + public char[] qualifiedSourceName() { + if (isMemberType()) { + return CharOperation.concat(enclosingType().qualifiedSourceName(), + sourceName(), '.'); + } else { + return sourceName(); + } + } -public final boolean isProtected() { - return (modifiers & AccProtected) != 0; -} -/* Answer true if the receiver has public visibility -*/ + public char[] readableName() /* java.lang.Object */{ + if (isMemberType()) + return CharOperation.concat(enclosingType().readableName(), + sourceName, '.'); + else + return CharOperation.concatWith(compoundName, '.'); + } -public final boolean isPublic() { - return (modifiers & AccPublic) != 0; -} -/* Answer true if the receiver is a static member type (or toplevel) - */ + public char[] shortReadableName() /* Object */{ + if (isMemberType()) + return CharOperation.concat(enclosingType().shortReadableName(), + sourceName, '.'); + else + return sourceName; + } -public final boolean isStatic() { - return (modifiers & (AccStatic | AccInterface)) != 0 || - (tagBits & IsNestedType) == 0; -} -/* Answer true if all float operations must adher to IEEE 754 float/double rules -*/ - -//public final boolean isStrictfp() { -// return (modifiers & AccStrictfp) != 0; -//} -/* Answer true if the receiver is in the superclass hierarchy of aType -* -* NOTE: Object.isSuperclassOf(Object) -> false -*/ - -public boolean isSuperclassOf(ReferenceBinding type) { - do { - if (this == (type = type.superclass())) return true; - } while (type != null); - - return false; -} -/* Answer true if the receiver is deprecated (or any of its enclosing types) -*/ + /* + * Answer the receiver's signature. + * + * NOTE: This method should only be used during/after code gen. + */ -public final boolean isViewedAsDeprecated() { - return (modifiers & AccDeprecated) != 0 || - (modifiers & AccDeprecatedImplicitly) != 0; -} -public ReferenceBinding[] memberTypes() { - return NoMemberTypes; -} -public MethodBinding[] methods() { - return NoMethods; -} -/** -* Answer the source name for the type. -* In the case of member types, as the qualified name from its top level type. -* For example, for a member type N defined inside M & A: "A.M.N". -*/ - -public char[] qualifiedSourceName() { - if (isMemberType()) { - return CharOperation.concat(enclosingType().qualifiedSourceName(), sourceName(), '.'); - } else { - return sourceName(); + public char[] signature() /* Ljava/lang/Object; */{ + if (signature != null) + return signature; + + return signature = CharOperation.concat('L', constantPoolName(), ';'); } -} -public char[] readableName() /*java.lang.Object*/ { - if (isMemberType()) - return CharOperation.concat(enclosingType().readableName(), sourceName, '.'); - else - return CharOperation.concatWith(compoundName, '.'); -} -public char[] shortReadableName() /*Object*/ { - if (isMemberType()) - return CharOperation.concat(enclosingType().shortReadableName(), sourceName, '.'); - else + public char[] sourceName() { return sourceName; -} + } + + public ReferenceBinding superclass() { + return null; + } -/* Answer the receiver's signature. -* -* NOTE: This method should only be used during/after code gen. -*/ + public ReferenceBinding[] superInterfaces() { + return NoSuperInterfaces; + } -public char[] signature() /* Ljava/lang/Object; */ { - if (signature != null) - return signature; + public ReferenceBinding[] syntheticEnclosingInstanceTypes() { + if (isStatic()) + return null; - return signature = CharOperation.concat('L', constantPoolName(), ';'); -} -public char[] sourceName() { - return sourceName; -} -public ReferenceBinding superclass() { - return null; -} -public ReferenceBinding[] superInterfaces() { - return NoSuperInterfaces; -} -public ReferenceBinding[] syntheticEnclosingInstanceTypes() { - if (isStatic()) return null; + ReferenceBinding enclosingType = enclosingType(); + if (enclosingType == null) + return null; + else + return new ReferenceBinding[] { enclosingType }; + } - ReferenceBinding enclosingType = enclosingType(); - if (enclosingType == null) - return null; - else - return new ReferenceBinding[] {enclosingType}; -} -public SyntheticArgumentBinding[] syntheticOuterLocalVariables() { - return null; // is null if no enclosing instances are required -} + public SyntheticArgumentBinding[] syntheticOuterLocalVariables() { + return null; // is null if no enclosing instances are required + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/Scope.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/Scope.java index 2957f65..32fa127 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/Scope.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/Scope.java @@ -19,23 +19,21 @@ import net.sourceforge.phpdt.internal.compiler.impl.ReferenceContext; import net.sourceforge.phpdt.internal.compiler.problem.ProblemReporter; import net.sourceforge.phpdt.internal.compiler.util.ObjectVector; -public abstract class Scope - implements - BaseTypes, - BindingIds, - CompilerModifiers, - ProblemReasons, - TagBits, - TypeConstants, - TypeIds { +public abstract class Scope implements BaseTypes, BindingIds, + CompilerModifiers, ProblemReasons, TagBits, TypeConstants, TypeIds { public Scope parent; + public int kind; public final static int BLOCK_SCOPE = 1; + public final static int METHOD_SCOPE = 2; + public final static int CLASS_SCOPE = 3; + public final static int COMPILATION_UNIT_SCOPE = 4; + protected Scope(int kind, Scope parent) { this.kind = kind; this.parent = parent; @@ -44,7 +42,8 @@ public abstract class Scope public abstract ProblemReporter problemReporter(); // Internal use only - protected final boolean areParametersAssignable(TypeBinding[] parameters, TypeBinding[] arguments) { + protected final boolean areParametersAssignable(TypeBinding[] parameters, + TypeBinding[] arguments) { if (parameters == arguments) return true; @@ -59,12 +58,12 @@ public abstract class Scope return true; } - /* Answer an int describing the relationship between the given types. - * - * NotRelated - * EqualOrMoreSpecific : left is compatible with right - * MoreGeneric : right is compatible with left - */ + /* + * Answer an int describing the relationship between the given types. + * + * NotRelated EqualOrMoreSpecific : left is compatible with right + * MoreGeneric : right is compatible with left + */ public static int compareTypes(TypeBinding left, TypeBinding right) { if (left.isCompatibleWith(right)) return EqualOrMoreSpecific; @@ -73,15 +72,18 @@ public abstract class Scope return NotRelated; } - /* Answer an int describing the relationship between the given type and unchecked exceptions. - * - * NotRelated - * EqualOrMoreSpecific : type is known for sure to be an unchecked exception type - * MoreGeneric : type is a supertype of an actual unchecked exception type - */ + /* + * Answer an int describing the relationship between the given type and + * unchecked exceptions. + * + * NotRelated EqualOrMoreSpecific : type is known for sure to be an + * unchecked exception type MoreGeneric : type is a supertype of an actual + * unchecked exception type + */ public int compareUncheckedException(ReferenceBinding type) { int comparison = compareTypes(type, getJavaLangRuntimeException()); - if (comparison != 0) return comparison; + if (comparison != 0) + return comparison; return compareTypes(type, getJavaLangError()); } @@ -105,7 +107,8 @@ public abstract class Scope public final ClassScope enclosingClassScope() { Scope scope = this; while ((scope = scope.parent) != null) { - if (scope instanceof ClassScope) return (ClassScope)scope; + if (scope instanceof ClassScope) + return (ClassScope) scope; } return null; // may answer null if no type around } @@ -113,13 +116,15 @@ public abstract class Scope public final MethodScope enclosingMethodScope() { Scope scope = this; while ((scope = scope.parent) != null) { - if (scope instanceof MethodScope) return (MethodScope)scope; + if (scope instanceof MethodScope) + return (MethodScope) scope; } return null; // may answer null if no method around } - /* Answer the receiver's enclosing source type. - */ + /* + * Answer the receiver's enclosing source type. + */ public final SourceTypeBinding enclosingSourceType() { Scope scope = this; do { @@ -129,6 +134,7 @@ public abstract class Scope } while (scope != null); return null; } + public final LookupEnvironment environment() { Scope scope, unitScope = this; while ((scope = unitScope.parent) != null) @@ -137,60 +143,70 @@ public abstract class Scope } // Internal use only - public ReferenceBinding findDirectMemberType(char[] typeName, ReferenceBinding enclosingType) { + public ReferenceBinding findDirectMemberType(char[] typeName, + ReferenceBinding enclosingType) { if ((enclosingType.tagBits & HasNoMemberTypes) != 0) - return null; // know it has no member types (nor inherited member types) + return null; // know it has no member types (nor inherited member + // types) SourceTypeBinding enclosingSourceType = enclosingSourceType(); - compilationUnitScope().recordReference(enclosingType.compoundName, typeName); + compilationUnitScope().recordReference(enclosingType.compoundName, + typeName); ReferenceBinding memberType = enclosingType.getMemberType(typeName); if (memberType != null) { - compilationUnitScope().recordTypeReference(memberType); // to record supertypes - if (enclosingSourceType == null - ? memberType.canBeSeenBy(getCurrentPackage()) - : memberType.canBeSeenBy(enclosingType, enclosingSourceType)) + compilationUnitScope().recordTypeReference(memberType); // to record + // supertypes + if (enclosingSourceType == null ? memberType + .canBeSeenBy(getCurrentPackage()) : memberType.canBeSeenBy( + enclosingType, enclosingSourceType)) return memberType; else - return new ProblemReferenceBinding(typeName, memberType, NotVisible); + return new ProblemReferenceBinding(typeName, memberType, + NotVisible); } return null; } // Internal use only - public MethodBinding findExactMethod( - ReferenceBinding receiverType, - char[] selector, - TypeBinding[] argumentTypes, - InvocationSite invocationSite) { + public MethodBinding findExactMethod(ReferenceBinding receiverType, + char[] selector, TypeBinding[] argumentTypes, + InvocationSite invocationSite) { compilationUnitScope().recordTypeReference(receiverType); compilationUnitScope().recordTypeReferences(argumentTypes); - MethodBinding exactMethod = receiverType.getExactMethod(selector, argumentTypes); + MethodBinding exactMethod = receiverType.getExactMethod(selector, + argumentTypes); if (exactMethod != null) { - compilationUnitScope().recordTypeReferences(exactMethod.thrownExceptions); - if (receiverType.isInterface() || exactMethod.canBeSeenBy(receiverType, invocationSite, this)) + compilationUnitScope().recordTypeReferences( + exactMethod.thrownExceptions); + if (receiverType.isInterface() + || exactMethod.canBeSeenBy(receiverType, invocationSite, + this)) return exactMethod; } return null; } // Internal use only - /* Answer the field binding that corresponds to fieldName. - Start the lookup at the receiverType. - InvocationSite implements - isSuperAccess(); this is used to determine if the discovered field is visible. - Only fields defined by the receiverType or its supertypes are answered; - a field of an enclosing type will not be found using this API. - - If no visible field is discovered, null is answered. - */ - public FieldBinding findField(TypeBinding receiverType, char[] fieldName, InvocationSite invocationSite) { - if (receiverType.isBaseType()) return null; + /* + * Answer the field binding that corresponds to fieldName. Start the lookup + * at the receiverType. InvocationSite implements isSuperAccess(); this is + * used to determine if the discovered field is visible. Only fields defined + * by the receiverType or its supertypes are answered; a field of an + * enclosing type will not be found using this API. + * + * If no visible field is discovered, null is answered. + */ + public FieldBinding findField(TypeBinding receiverType, char[] fieldName, + InvocationSite invocationSite) { + if (receiverType.isBaseType()) + return null; if (receiverType.isArrayType()) { TypeBinding leafType = receiverType.leafComponentType(); if (leafType instanceof ReferenceBinding) { if (!((ReferenceBinding) leafType).canBeSeenBy(this)) - return new ProblemFieldBinding((ReferenceBinding)leafType, fieldName, ReceiverTypeNotVisible); + return new ProblemFieldBinding((ReferenceBinding) leafType, + fieldName, ReceiverTypeNotVisible); } if (CharOperation.equals(fieldName, LENGTH)) return ArrayBinding.LengthField; @@ -201,16 +217,19 @@ public abstract class Scope ReferenceBinding currentType = (ReferenceBinding) receiverType; if (!currentType.canBeSeenBy(this)) - return new ProblemFieldBinding(currentType, fieldName, ReceiverTypeNotVisible); + return new ProblemFieldBinding(currentType, fieldName, + ReceiverTypeNotVisible); FieldBinding field = currentType.getField(fieldName); if (field != null) { if (field.canBeSeenBy(currentType, invocationSite, this)) return field; else - return new ProblemFieldBinding(field.declaringClass, fieldName, NotVisible); + return new ProblemFieldBinding(field.declaringClass, fieldName, + NotVisible); } - // collect all superinterfaces of receiverType until the field is found in a supertype + // collect all superinterfaces of receiverType until the field is found + // in a supertype ReferenceBinding[][] interfacesToVisit = null; int lastPosition = -1; FieldBinding visibleField = null; @@ -223,12 +242,12 @@ public abstract class Scope if (interfacesToVisit == null) interfacesToVisit = new ReferenceBinding[5][]; if (++lastPosition == interfacesToVisit.length) - System.arraycopy( - interfacesToVisit, - 0, - interfacesToVisit = new ReferenceBinding[lastPosition * 2][], - 0, - lastPosition); + System + .arraycopy( + interfacesToVisit, + 0, + interfacesToVisit = new ReferenceBinding[lastPosition * 2][], + 0, lastPosition); interfacesToVisit[lastPosition] = itsInterfaces; } if ((currentType = currentType.superclass()) == null) @@ -240,7 +259,9 @@ public abstract class Scope if (visibleField == null) visibleField = field; else - return new ProblemFieldBinding(visibleField.declaringClass, fieldName, Ambiguous); + return new ProblemFieldBinding( + visibleField.declaringClass, fieldName, + Ambiguous); } else { notVisible = true; } @@ -250,7 +271,7 @@ public abstract class Scope // walk all visible interfaces to find ambiguous references if (interfacesToVisit != null) { ProblemFieldBinding ambiguous = null; - done : for (int i = 0; i <= lastPosition; i++) { + done: for (int i = 0; i <= lastPosition; i++) { ReferenceBinding[] interfaces = interfacesToVisit[i]; for (int j = 0, length = interfaces.length; j < length; j++) { ReferenceBinding anInterface = interfaces[j]; @@ -261,19 +282,22 @@ public abstract class Scope if (visibleField == null) { visibleField = field; } else { - ambiguous = new ProblemFieldBinding(visibleField.declaringClass, fieldName, Ambiguous); + ambiguous = new ProblemFieldBinding( + visibleField.declaringClass, fieldName, + Ambiguous); break done; } } else { - ReferenceBinding[] itsInterfaces = anInterface.superInterfaces(); + ReferenceBinding[] itsInterfaces = anInterface + .superInterfaces(); if (itsInterfaces != NoSuperInterfaces) { if (++lastPosition == interfacesToVisit.length) - System.arraycopy( - interfacesToVisit, - 0, - interfacesToVisit = new ReferenceBinding[lastPosition * 2][], - 0, - lastPosition); + System + .arraycopy( + interfacesToVisit, + 0, + interfacesToVisit = new ReferenceBinding[lastPosition * 2][], + 0, lastPosition); interfacesToVisit[lastPosition] = itsInterfaces; } } @@ -299,25 +323,31 @@ public abstract class Scope } // Internal use only - public ReferenceBinding findMemberType(char[] typeName, ReferenceBinding enclosingType) { + public ReferenceBinding findMemberType(char[] typeName, + ReferenceBinding enclosingType) { if ((enclosingType.tagBits & HasNoMemberTypes) != 0) - return null; // know it has no member types (nor inherited member types) + return null; // know it has no member types (nor inherited member + // types) SourceTypeBinding enclosingSourceType = enclosingSourceType(); PackageBinding currentPackage = getCurrentPackage(); - compilationUnitScope().recordReference(enclosingType.compoundName, typeName); + compilationUnitScope().recordReference(enclosingType.compoundName, + typeName); ReferenceBinding memberType = enclosingType.getMemberType(typeName); if (memberType != null) { - compilationUnitScope().recordTypeReference(memberType); // to record supertypes - if (enclosingSourceType == null - ? memberType.canBeSeenBy(currentPackage) - : memberType.canBeSeenBy(enclosingType, enclosingSourceType)) + compilationUnitScope().recordTypeReference(memberType); // to record + // supertypes + if (enclosingSourceType == null ? memberType + .canBeSeenBy(currentPackage) : memberType.canBeSeenBy( + enclosingType, enclosingSourceType)) return memberType; else - return new ProblemReferenceBinding(typeName, memberType, NotVisible); + return new ProblemReferenceBinding(typeName, memberType, + NotVisible); } - // collect all superinterfaces of receiverType until the memberType is found in a supertype + // collect all superinterfaces of receiverType until the memberType is + // found in a supertype ReferenceBinding currentType = enclosingType; ReferenceBinding[][] interfacesToVisit = null; int lastPosition = -1; @@ -331,28 +361,31 @@ public abstract class Scope if (interfacesToVisit == null) interfacesToVisit = new ReferenceBinding[5][]; if (++lastPosition == interfacesToVisit.length) - System.arraycopy( - interfacesToVisit, - 0, - interfacesToVisit = new ReferenceBinding[lastPosition * 2][], - 0, - lastPosition); + System + .arraycopy( + interfacesToVisit, + 0, + interfacesToVisit = new ReferenceBinding[lastPosition * 2][], + 0, lastPosition); interfacesToVisit[lastPosition] = itsInterfaces; } if ((currentType = currentType.superclass()) == null) break; - compilationUnitScope().recordReference(currentType.compoundName, typeName); + compilationUnitScope().recordReference(currentType.compoundName, + typeName); if ((memberType = currentType.getMemberType(typeName)) != null) { - compilationUnitScope().recordTypeReference(memberType); // to record supertypes + compilationUnitScope().recordTypeReference(memberType); // to + // record + // supertypes keepLooking = false; - if (enclosingSourceType == null - ? memberType.canBeSeenBy(currentPackage) - : memberType.canBeSeenBy(enclosingType, enclosingSourceType)) { - if (visibleMemberType == null) - visibleMemberType = memberType; - else - return new ProblemReferenceBinding(typeName, Ambiguous); + if (enclosingSourceType == null ? memberType + .canBeSeenBy(currentPackage) : memberType.canBeSeenBy( + enclosingType, enclosingSourceType)) { + if (visibleMemberType == null) + visibleMemberType = memberType; + else + return new ProblemReferenceBinding(typeName, Ambiguous); } else { notVisible = memberType; } @@ -361,32 +394,36 @@ public abstract class Scope // walk all visible interfaces to find ambiguous references if (interfacesToVisit != null) { ProblemReferenceBinding ambiguous = null; - done : for (int i = 0; i <= lastPosition; i++) { + done: for (int i = 0; i <= lastPosition; i++) { ReferenceBinding[] interfaces = interfacesToVisit[i]; for (int j = 0, length = interfaces.length; j < length; j++) { ReferenceBinding anInterface = interfaces[j]; if ((anInterface.tagBits & InterfaceVisited) == 0) { // if interface as not already been visited anInterface.tagBits |= InterfaceVisited; - compilationUnitScope().recordReference(anInterface.compoundName, typeName); + compilationUnitScope().recordReference( + anInterface.compoundName, typeName); if ((memberType = anInterface.getMemberType(typeName)) != null) { - compilationUnitScope().recordTypeReference(memberType); // to record supertypes + compilationUnitScope().recordTypeReference( + memberType); // to record supertypes if (visibleMemberType == null) { visibleMemberType = memberType; } else { - ambiguous = new ProblemReferenceBinding(typeName, Ambiguous); + ambiguous = new ProblemReferenceBinding( + typeName, Ambiguous); break done; } } else { - ReferenceBinding[] itsInterfaces = anInterface.superInterfaces(); + ReferenceBinding[] itsInterfaces = anInterface + .superInterfaces(); if (itsInterfaces != NoSuperInterfaces) { if (++lastPosition == interfacesToVisit.length) - System.arraycopy( - interfacesToVisit, - 0, - interfacesToVisit = new ReferenceBinding[lastPosition * 2][], - 0, - lastPosition); + System + .arraycopy( + interfacesToVisit, + 0, + interfacesToVisit = new ReferenceBinding[lastPosition * 2][], + 0, lastPosition); interfacesToVisit[lastPosition] = itsInterfaces; } } @@ -411,11 +448,9 @@ public abstract class Scope } // Internal use only - public MethodBinding findMethod( - ReferenceBinding receiverType, - char[] selector, - TypeBinding[] argumentTypes, - InvocationSite invocationSite) { + public MethodBinding findMethod(ReferenceBinding receiverType, + char[] selector, TypeBinding[] argumentTypes, + InvocationSite invocationSite) { ReferenceBinding currentType = receiverType; MethodBinding matchingMethod = null; @@ -432,44 +467,51 @@ public abstract class Scope } else if (currentLength > 1) { found.addAll(currentMethods); } - matchingMethod = findMethodInSuperInterfaces(currentType, selector, found, matchingMethod); + matchingMethod = findMethodInSuperInterfaces(currentType, selector, + found, matchingMethod); currentType = getJavaLangObject(); } -// boolean isCompliant14 = compilationUnitScope().environment.options.complianceLevel >= CompilerOptions.JDK1_4; + // boolean isCompliant14 = + // compilationUnitScope().environment.options.complianceLevel >= + // CompilerOptions.JDK1_4; // superclass lookup ReferenceBinding classHierarchyStart = currentType; while (currentType != null) { MethodBinding[] currentMethods = currentType.getMethods(selector); int currentLength = currentMethods.length; - + /* - * if 1.4 compliant, must filter out redundant protected methods from superclasses + * if 1.4 compliant, must filter out redundant protected methods + * from superclasses */ -// if (isCompliant14){ -// nextMethod: for (int i = 0; i < currentLength; i++){ -// MethodBinding currentMethod = currentMethods[i]; -// // protected method need to be checked only - default access is already dealt with in #canBeSeen implementation -// // when checking that p.C -> q.B -> p.A cannot see default access members from A through B. -// if ((currentMethod.modifiers & AccProtected) == 0) continue nextMethod; -// if (matchingMethod != null){ -// if (currentMethod.areParametersEqual(matchingMethod)){ -// currentLength--; -// currentMethods[i] = null; // discard this match -// continue nextMethod; -// } -// } else { -// for (int j = 0, max = found.size; j < max; j++) { -// if (((MethodBinding)found.elementAt(j)).areParametersEqual(currentMethod)){ -// currentLength--; -// currentMethods[i] = null; -// continue nextMethod; -// } -// } -// } -// } -// } - + // if (isCompliant14){ + // nextMethod: for (int i = 0; i < currentLength; i++){ + // MethodBinding currentMethod = currentMethods[i]; + // // protected method need to be checked only - default access is + // already dealt with in #canBeSeen implementation + // // when checking that p.C -> q.B -> p.A cannot see default access + // members from A through B. + // if ((currentMethod.modifiers & AccProtected) == 0) continue + // nextMethod; + // if (matchingMethod != null){ + // if (currentMethod.areParametersEqual(matchingMethod)){ + // currentLength--; + // currentMethods[i] = null; // discard this match + // continue nextMethod; + // } + // } else { + // for (int j = 0, max = found.size; j < max; j++) { + // if + // (((MethodBinding)found.elementAt(j)).areParametersEqual(currentMethod)){ + // currentLength--; + // currentMethods[i] = null; + // continue nextMethod; + // } + // } + // } + // } + // } if (currentLength == 1 && matchingMethod == null && found.size == 0) { matchingMethod = currentMethods[0]; } else if (currentLength > 0) { @@ -479,12 +521,15 @@ public abstract class Scope } // append currentMethods, filtering out null entries int maxMethod = currentMethods.length; - if (maxMethod == currentLength) { // no method was eliminated for 1.4 compliance (see above) + if (maxMethod == currentLength) { // no method was eliminated + // for 1.4 compliance (see + // above) found.addAll(currentMethods); } else { for (int i = 0, max = currentMethods.length; i < max; i++) { MethodBinding currentMethod = currentMethods[i]; - if (currentMethod != null) found.add(currentMethod); + if (currentMethod != null) + found.add(currentMethod); } } } @@ -493,16 +538,26 @@ public abstract class Scope int foundSize = found.size; if (foundSize == 0) { - if (matchingMethod != null && areParametersAssignable(matchingMethod.parameters, argumentTypes)) { - // (if no default abstract) must explicitly look for one instead, which could be a better match - if (!matchingMethod.canBeSeenBy(receiverType, invocationSite, this)) { - // ignore matching method (to be consistent with multiple matches, none visible (matching method is then null) - MethodBinding interfaceMethod = findDefaultAbstractMethod(receiverType, selector, argumentTypes, invocationSite, classHierarchyStart, null, found); - if (interfaceMethod != null) return interfaceMethod; + if (matchingMethod != null + && areParametersAssignable(matchingMethod.parameters, + argumentTypes)) { + // (if no default abstract) must explicitly look for one + // instead, which could be a better match + if (!matchingMethod.canBeSeenBy(receiverType, invocationSite, + this)) { + // ignore matching method (to be consistent with multiple + // matches, none visible (matching method is then null) + MethodBinding interfaceMethod = findDefaultAbstractMethod( + receiverType, selector, argumentTypes, + invocationSite, classHierarchyStart, null, found); + if (interfaceMethod != null) + return interfaceMethod; } return matchingMethod; - } - return findDefaultAbstractMethod(receiverType, selector, argumentTypes, invocationSite, classHierarchyStart, matchingMethod, found); + } + return findDefaultAbstractMethod(receiverType, selector, + argumentTypes, invocationSite, classHierarchyStart, + matchingMethod, found); } MethodBinding[] candidates = new MethodBinding[foundSize]; @@ -514,18 +569,24 @@ public abstract class Scope candidates[candidatesCount++] = methodBinding; } if (candidatesCount == 1) { - compilationUnitScope().recordTypeReferences(candidates[0].thrownExceptions); + compilationUnitScope().recordTypeReferences( + candidates[0].thrownExceptions); return candidates[0]; // have not checked visibility } - if (candidatesCount == 0) { // try to find a close match when the parameter order is wrong or missing some parameters - MethodBinding interfaceMethod = - findDefaultAbstractMethod(receiverType, selector, argumentTypes, invocationSite, classHierarchyStart, matchingMethod, found); - if (interfaceMethod != null) return interfaceMethod; + if (candidatesCount == 0) { // try to find a close match when the + // parameter order is wrong or missing some + // parameters + MethodBinding interfaceMethod = findDefaultAbstractMethod( + receiverType, selector, argumentTypes, invocationSite, + classHierarchyStart, matchingMethod, found); + if (interfaceMethod != null) + return interfaceMethod; int argLength = argumentTypes.length; foundSize = found.size; - nextMethod : for (int i = 0; i < foundSize; i++) { - MethodBinding methodBinding = (MethodBinding) found.elementAt(i); + nextMethod: for (int i = 0; i < foundSize; i++) { + MethodBinding methodBinding = (MethodBinding) found + .elementAt(i); TypeBinding[] params = methodBinding.parameters; int paramLength = params.length; nextArg: for (int a = 0; a < argLength; a++) { @@ -537,7 +598,9 @@ public abstract class Scope } return methodBinding; } - return (MethodBinding) found.elementAt(0); // no good match so just use the first one found + return (MethodBinding) found.elementAt(0); // no good match so just + // use the first one + // found } // visibility check @@ -553,15 +616,20 @@ public abstract class Scope } } if (visiblesCount == 1) { - compilationUnitScope().recordTypeReferences(candidates[0].thrownExceptions); + compilationUnitScope().recordTypeReferences( + candidates[0].thrownExceptions); return candidates[0]; } if (visiblesCount == 0) { - MethodBinding interfaceMethod = - findDefaultAbstractMethod(receiverType, selector, argumentTypes, invocationSite, classHierarchyStart, matchingMethod, found); - if (interfaceMethod != null) return interfaceMethod; - return new ProblemMethodBinding(candidates[0], candidates[0].selector, candidates[0].parameters, NotVisible); - } + MethodBinding interfaceMethod = findDefaultAbstractMethod( + receiverType, selector, argumentTypes, invocationSite, + classHierarchyStart, matchingMethod, found); + if (interfaceMethod != null) + return interfaceMethod; + return new ProblemMethodBinding(candidates[0], + candidates[0].selector, candidates[0].parameters, + NotVisible); + } if (candidates[0].declaringClass.isClass()) { return mostSpecificClassMethodBinding(candidates, visiblesCount); } else { @@ -569,26 +637,27 @@ public abstract class Scope } } - // abstract method lookup lookup (since maybe missing default abstract methods) + // abstract method lookup lookup (since maybe missing default abstract + // methods) public MethodBinding findDefaultAbstractMethod( - ReferenceBinding receiverType, - char[] selector, - TypeBinding[] argumentTypes, - InvocationSite invocationSite, - ReferenceBinding classHierarchyStart, - MethodBinding matchingMethod, - ObjectVector found) { + ReferenceBinding receiverType, char[] selector, + TypeBinding[] argumentTypes, InvocationSite invocationSite, + ReferenceBinding classHierarchyStart, MethodBinding matchingMethod, + ObjectVector found) { int startFoundSize = found.size; ReferenceBinding currentType = classHierarchyStart; while (currentType != null) { - matchingMethod = findMethodInSuperInterfaces(currentType, selector, found, matchingMethod); + matchingMethod = findMethodInSuperInterfaces(currentType, selector, + found, matchingMethod); currentType = currentType.superclass(); } int foundSize = found.size; - if (foundSize == startFoundSize) return matchingMethod; // maybe null + if (foundSize == startFoundSize) + return matchingMethod; // maybe null - MethodBinding[] candidates = new MethodBinding[foundSize - startFoundSize]; + MethodBinding[] candidates = new MethodBinding[foundSize + - startFoundSize]; int candidatesCount = 0; // argument type compatibility check for (int i = startFoundSize; i < foundSize; i++) { @@ -597,13 +666,17 @@ public abstract class Scope candidates[candidatesCount++] = methodBinding; } if (candidatesCount == 1) { - compilationUnitScope().recordTypeReferences(candidates[0].thrownExceptions); - return candidates[0]; + compilationUnitScope().recordTypeReferences( + candidates[0].thrownExceptions); + return candidates[0]; } - if (candidatesCount == 0) { // try to find a close match when the parameter order is wrong or missing some parameters + if (candidatesCount == 0) { // try to find a close match when the + // parameter order is wrong or missing some + // parameters int argLength = argumentTypes.length; - nextMethod : for (int i = 0; i < foundSize; i++) { - MethodBinding methodBinding = (MethodBinding) found.elementAt(i); + nextMethod: for (int i = 0; i < foundSize; i++) { + MethodBinding methodBinding = (MethodBinding) found + .elementAt(i); TypeBinding[] params = methodBinding.parameters; int paramLength = params.length; nextArg: for (int a = 0; a < argLength; a++) { @@ -615,27 +688,29 @@ public abstract class Scope } return methodBinding; } - return (MethodBinding) found.elementAt(0); // no good match so just use the first one found + return (MethodBinding) found.elementAt(0); // no good match so just + // use the first one + // found } // no need to check for visibility - interface methods are public return mostSpecificInterfaceMethodBinding(candidates, candidatesCount); } public MethodBinding findMethodInSuperInterfaces( - ReferenceBinding currentType, - char[] selector, - ObjectVector found, - MethodBinding matchingMethod) { + ReferenceBinding currentType, char[] selector, ObjectVector found, + MethodBinding matchingMethod) { ReferenceBinding[] itsInterfaces = currentType.superInterfaces(); if (itsInterfaces != NoSuperInterfaces) { ReferenceBinding[][] interfacesToVisit = new ReferenceBinding[5][]; int lastPosition = -1; if (++lastPosition == interfacesToVisit.length) - System.arraycopy( - interfacesToVisit, 0, - interfacesToVisit = new ReferenceBinding[lastPosition * 2][], 0, - lastPosition); + System + .arraycopy( + interfacesToVisit, + 0, + interfacesToVisit = new ReferenceBinding[lastPosition * 2][], + 0, lastPosition); interfacesToVisit[lastPosition] = itsInterfaces; for (int i = 0; i <= lastPosition; i++) { @@ -646,9 +721,11 @@ public abstract class Scope // if interface as not already been visited currentType.tagBits |= InterfaceVisited; - MethodBinding[] currentMethods = currentType.getMethods(selector); + MethodBinding[] currentMethods = currentType + .getMethods(selector); int currentLength = currentMethods.length; - if (currentLength == 1 && matchingMethod == null && found.size == 0) { + if (currentLength == 1 && matchingMethod == null + && found.size == 0) { matchingMethod = currentMethods[0]; } else if (currentLength > 0) { if (matchingMethod != null) { @@ -660,10 +737,12 @@ public abstract class Scope itsInterfaces = currentType.superInterfaces(); if (itsInterfaces != NoSuperInterfaces) { if (++lastPosition == interfacesToVisit.length) - System.arraycopy( - interfacesToVisit, 0, - interfacesToVisit = new ReferenceBinding[lastPosition * 2][], 0, - lastPosition); + System + .arraycopy( + interfacesToVisit, + 0, + interfacesToVisit = new ReferenceBinding[lastPosition * 2][], + 0, lastPosition); interfacesToVisit[lastPosition] = itsInterfaces; } } @@ -679,70 +758,68 @@ public abstract class Scope } return matchingMethod; } - + // Internal use only - public MethodBinding findMethodForArray( - ArrayBinding receiverType, - char[] selector, - TypeBinding[] argumentTypes, - InvocationSite invocationSite) { + public MethodBinding findMethodForArray(ArrayBinding receiverType, + char[] selector, TypeBinding[] argumentTypes, + InvocationSite invocationSite) { TypeBinding leafType = receiverType.leafComponentType(); if (leafType instanceof ReferenceBinding) { if (!((ReferenceBinding) leafType).canBeSeenBy(this)) - return new ProblemMethodBinding(selector, MethodBinding.NoParameters, (ReferenceBinding)leafType, ReceiverTypeNotVisible); + return new ProblemMethodBinding(selector, + MethodBinding.NoParameters, + (ReferenceBinding) leafType, ReceiverTypeNotVisible); } ReferenceBinding object = getJavaLangObject(); - MethodBinding methodBinding = object.getExactMethod(selector, argumentTypes); + MethodBinding methodBinding = object.getExactMethod(selector, + argumentTypes); if (methodBinding != null) { - // handle the method clone() specially... cannot be protected or throw exceptions - if (argumentTypes == NoParameters && CharOperation.equals(selector, CLONE)) + // handle the method clone() specially... cannot be protected or + // throw exceptions + if (argumentTypes == NoParameters + && CharOperation.equals(selector, CLONE)) return new MethodBinding( - (methodBinding.modifiers ^ AccProtected) | AccPublic, - CLONE, - methodBinding.returnType, - argumentTypes, - null, - object); + (methodBinding.modifiers ^ AccProtected) | AccPublic, + CLONE, methodBinding.returnType, argumentTypes, null, + object); if (methodBinding.canBeSeenBy(receiverType, invocationSite, this)) return methodBinding; } - // answers closest approximation, may not check argumentTypes or visibility - methodBinding = findMethod(object, selector, argumentTypes, invocationSite); + // answers closest approximation, may not check argumentTypes or + // visibility + methodBinding = findMethod(object, selector, argumentTypes, + invocationSite); if (methodBinding == null) return new ProblemMethodBinding(selector, argumentTypes, NotFound); if (methodBinding.isValidBinding()) { - if (!areParametersAssignable(methodBinding.parameters, argumentTypes)) - return new ProblemMethodBinding( - methodBinding, - selector, - argumentTypes, - NotFound); + if (!areParametersAssignable(methodBinding.parameters, + argumentTypes)) + return new ProblemMethodBinding(methodBinding, selector, + argumentTypes, NotFound); if (!methodBinding.canBeSeenBy(receiverType, invocationSite, this)) - return new ProblemMethodBinding( - methodBinding, - selector, - methodBinding.parameters, - NotVisible); + return new ProblemMethodBinding(methodBinding, selector, + methodBinding.parameters, NotVisible); } return methodBinding; } // Internal use only - public ReferenceBinding findType( - char[] typeName, - PackageBinding declarationPackage, - PackageBinding invocationPackage) { + public ReferenceBinding findType(char[] typeName, + PackageBinding declarationPackage, PackageBinding invocationPackage) { - compilationUnitScope().recordReference(declarationPackage.compoundName, typeName); + compilationUnitScope().recordReference(declarationPackage.compoundName, + typeName); ReferenceBinding typeBinding = declarationPackage.getType(typeName); if (typeBinding == null) return null; if (typeBinding.isValidBinding()) { - if (declarationPackage != invocationPackage && !typeBinding.canBeSeenBy(invocationPackage)) - return new ProblemReferenceBinding(typeName, typeBinding, NotVisible); + if (declarationPackage != invocationPackage + && !typeBinding.canBeSeenBy(invocationPackage)) + return new ProblemReferenceBinding(typeName, typeBinding, + NotVisible); } return typeBinding; } @@ -752,58 +829,48 @@ public abstract class Scope int length = name.length; if (length > 2 && length < 8) { switch (name[0]) { - case 'i' : - if (length == 3 && name[1] == 'n' && name[2] == 't') - return IntBinding; - break; - case 'v' : - if (length == 4 && name[1] == 'o' && name[2] == 'i' && name[3] == 'd') - return VoidBinding; - break; - case 'b' : - if (length == 7 - && name[1] == 'o' - && name[2] == 'o' - && name[3] == 'l' - && name[4] == 'e' - && name[5] == 'a' + case 'i': + if (length == 3 && name[1] == 'n' && name[2] == 't') + return IntBinding; + break; + case 'v': + if (length == 4 && name[1] == 'o' && name[2] == 'i' + && name[3] == 'd') + return VoidBinding; + break; + case 'b': + if (length == 7 && name[1] == 'o' && name[2] == 'o' + && name[3] == 'l' && name[4] == 'e' && name[5] == 'a' && name[6] == 'n') - return BooleanBinding; - if (length == 4 && name[1] == 'y' && name[2] == 't' && name[3] == 'e') - return ByteBinding; - break; - case 'c' : - if (length == 4 && name[1] == 'h' && name[2] == 'a' && name[3] == 'r') - return CharBinding; - break; - case 'd' : - if (length == 6 - && name[1] == 'o' - && name[2] == 'u' - && name[3] == 'b' - && name[4] == 'l' - && name[5] == 'e') - return DoubleBinding; - break; - case 'f' : - if (length == 5 - && name[1] == 'l' - && name[2] == 'o' - && name[3] == 'a' - && name[4] == 't') - return FloatBinding; - break; - case 'l' : - if (length == 4 && name[1] == 'o' && name[2] == 'n' && name[3] == 'g') - return LongBinding; - break; - case 's' : - if (length == 5 - && name[1] == 'h' - && name[2] == 'o' - && name[3] == 'r' - && name[4] == 't') - return ShortBinding; + return BooleanBinding; + if (length == 4 && name[1] == 'y' && name[2] == 't' + && name[3] == 'e') + return ByteBinding; + break; + case 'c': + if (length == 4 && name[1] == 'h' && name[2] == 'a' + && name[3] == 'r') + return CharBinding; + break; + case 'd': + if (length == 6 && name[1] == 'o' && name[2] == 'u' + && name[3] == 'b' && name[4] == 'l' && name[5] == 'e') + return DoubleBinding; + break; + case 'f': + if (length == 5 && name[1] == 'l' && name[2] == 'o' + && name[3] == 'a' && name[4] == 't') + return FloatBinding; + break; + case 'l': + if (length == 4 && name[1] == 'o' && name[2] == 'n' + && name[3] == 'g') + return LongBinding; + break; + case 's': + if (length == 5 && name[1] == 'h' && name[2] == 'o' + && name[3] == 'r' && name[4] == 't') + return ShortBinding; } } return null; @@ -815,39 +882,42 @@ public abstract class Scope unitScope = scope; return ((CompilationUnitScope) unitScope).fPackage; } + /** * Returns the modifiers of the innermost enclosing declaration. + * * @return modifiers */ - public int getDeclarationModifiers(){ - switch(this.kind){ - case Scope.BLOCK_SCOPE : - case Scope.METHOD_SCOPE : - MethodScope methodScope = methodScope(); - if (!methodScope.isInsideInitializer()){ - // check method modifiers to see if deprecated - MethodBinding context = ((AbstractMethodDeclaration)methodScope.referenceContext).binding; - if (context != null) { - return context.modifiers; - } - } else { - SourceTypeBinding type = ((BlockScope)this).referenceType().binding; - - // inside field declaration ? check field modifier to see if deprecated - if (methodScope.initializedField != null) { - return methodScope.initializedField.modifiers; - } - if (type != null) { - return type.modifiers; - } - } - break; - case Scope.CLASS_SCOPE : - ReferenceBinding context = ((ClassScope)this).referenceType().binding; + public int getDeclarationModifiers() { + switch (this.kind) { + case Scope.BLOCK_SCOPE: + case Scope.METHOD_SCOPE: + MethodScope methodScope = methodScope(); + if (!methodScope.isInsideInitializer()) { + // check method modifiers to see if deprecated + MethodBinding context = ((AbstractMethodDeclaration) methodScope.referenceContext).binding; if (context != null) { return context.modifiers; } - break; + } else { + SourceTypeBinding type = ((BlockScope) this).referenceType().binding; + + // inside field declaration ? check field modifier to see if + // deprecated + if (methodScope.initializedField != null) { + return methodScope.initializedField.modifiers; + } + if (type != null) { + return type.modifiers; + } + } + break; + case Scope.CLASS_SCOPE: + ReferenceBinding context = ((ClassScope) this).referenceType().binding; + if (context != null) { + return context.modifiers; + } + break; } return -1; } @@ -855,107 +925,145 @@ public abstract class Scope public final ReferenceBinding getJavaIoSerializable() { compilationUnitScope().recordQualifiedReference(JAVA_IO_SERIALIZABLE); ReferenceBinding type = environment().getType(JAVA_IO_SERIALIZABLE); - if (type != null) return type; - - problemReporter().isClassPathCorrect(JAVA_IO_SERIALIZABLE, referenceCompilationUnit()); - return null; // will not get here since the above error aborts the compilation + if (type != null) + return type; + + problemReporter().isClassPathCorrect(JAVA_IO_SERIALIZABLE, + referenceCompilationUnit()); + return null; // will not get here since the above error aborts the + // compilation } public final ReferenceBinding getJavaLangClass() { compilationUnitScope().recordQualifiedReference(JAVA_LANG_CLASS); ReferenceBinding type = environment().getType(JAVA_LANG_CLASS); - if (type != null) return type; - - problemReporter().isClassPathCorrect(JAVA_LANG_CLASS, referenceCompilationUnit()); - return null; // will not get here since the above error aborts the compilation + if (type != null) + return type; + + problemReporter().isClassPathCorrect(JAVA_LANG_CLASS, + referenceCompilationUnit()); + return null; // will not get here since the above error aborts the + // compilation } public final ReferenceBinding getJavaLangCloneable() { compilationUnitScope().recordQualifiedReference(JAVA_LANG_CLONEABLE); ReferenceBinding type = environment().getType(JAVA_LANG_CLONEABLE); - if (type != null) return type; - - problemReporter().isClassPathCorrect(JAVA_LANG_CLONEABLE, referenceCompilationUnit()); - return null; // will not get here since the above error aborts the compilation + if (type != null) + return type; + + problemReporter().isClassPathCorrect(JAVA_LANG_CLONEABLE, + referenceCompilationUnit()); + return null; // will not get here since the above error aborts the + // compilation } public final ReferenceBinding getJavaLangError() { compilationUnitScope().recordQualifiedReference(JAVA_LANG_ERROR); ReferenceBinding type = environment().getType(JAVA_LANG_ERROR); - if (type != null) return type; - - problemReporter().isClassPathCorrect(JAVA_LANG_ERROR, referenceCompilationUnit()); - return null; // will not get here since the above error aborts the compilation + if (type != null) + return type; + + problemReporter().isClassPathCorrect(JAVA_LANG_ERROR, + referenceCompilationUnit()); + return null; // will not get here since the above error aborts the + // compilation } public final ReferenceBinding getJavaLangAssertionError() { - compilationUnitScope().recordQualifiedReference(JAVA_LANG_ASSERTIONERROR); + compilationUnitScope().recordQualifiedReference( + JAVA_LANG_ASSERTIONERROR); ReferenceBinding type = environment().getType(JAVA_LANG_ASSERTIONERROR); - if (type != null) return type; - problemReporter().isClassPathCorrect(JAVA_LANG_ASSERTIONERROR, referenceCompilationUnit()); - return null; // will not get here since the above error aborts the compilation + if (type != null) + return type; + problemReporter().isClassPathCorrect(JAVA_LANG_ASSERTIONERROR, + referenceCompilationUnit()); + return null; // will not get here since the above error aborts the + // compilation } public final ReferenceBinding getJavaLangObject() { compilationUnitScope().recordQualifiedReference(JAVA_LANG_OBJECT); ReferenceBinding type = environment().getType(JAVA_LANG_OBJECT); - if (type != null) return type; - - problemReporter().isClassPathCorrect(JAVA_LANG_OBJECT, referenceCompilationUnit()); - return null; // will not get here since the above error aborts the compilation + if (type != null) + return type; + + problemReporter().isClassPathCorrect(JAVA_LANG_OBJECT, + referenceCompilationUnit()); + return null; // will not get here since the above error aborts the + // compilation } public final ReferenceBinding getJavaLangRuntimeException() { - compilationUnitScope().recordQualifiedReference(JAVA_LANG_RUNTIMEEXCEPTION); - ReferenceBinding type = environment().getType(JAVA_LANG_RUNTIMEEXCEPTION); - if (type != null) return type; - - problemReporter().isClassPathCorrect(JAVA_LANG_RUNTIMEEXCEPTION, referenceCompilationUnit()); - return null; // will not get here since the above error aborts the compilation + compilationUnitScope().recordQualifiedReference( + JAVA_LANG_RUNTIMEEXCEPTION); + ReferenceBinding type = environment().getType( + JAVA_LANG_RUNTIMEEXCEPTION); + if (type != null) + return type; + + problemReporter().isClassPathCorrect(JAVA_LANG_RUNTIMEEXCEPTION, + referenceCompilationUnit()); + return null; // will not get here since the above error aborts the + // compilation } public final ReferenceBinding getJavaLangString() { compilationUnitScope().recordQualifiedReference(JAVA_LANG_STRING); ReferenceBinding type = environment().getType(JAVA_LANG_STRING); - if (type != null) return type; - - problemReporter().isClassPathCorrect(JAVA_LANG_STRING, referenceCompilationUnit()); - return null; // will not get here since the above error aborts the compilation + if (type != null) + return type; + + problemReporter().isClassPathCorrect(JAVA_LANG_STRING, + referenceCompilationUnit()); + return null; // will not get here since the above error aborts the + // compilation } public final ReferenceBinding getJavaLangThrowable() { compilationUnitScope().recordQualifiedReference(JAVA_LANG_THROWABLE); ReferenceBinding type = environment().getType(JAVA_LANG_THROWABLE); - if (type != null) return type; - -// problemReporter().isClassPathCorrect(JAVA_LANG_THROWABLE, referenceCompilationUnit()); - return null; // will not get here since the above error aborts the compilation + if (type != null) + return type; + + // problemReporter().isClassPathCorrect(JAVA_LANG_THROWABLE, + // referenceCompilationUnit()); + return null; // will not get here since the above error aborts the + // compilation } - /* Answer the type binding corresponding to the typeName argument, relative to the enclosingType. - */ - public final ReferenceBinding getMemberType(char[] typeName, ReferenceBinding enclosingType) { + /* + * Answer the type binding corresponding to the typeName argument, relative + * to the enclosingType. + */ + public final ReferenceBinding getMemberType(char[] typeName, + ReferenceBinding enclosingType) { ReferenceBinding memberType = findMemberType(typeName, enclosingType); - if (memberType != null) return memberType; + if (memberType != null) + return memberType; return new ProblemReferenceBinding(typeName, NotFound); } - /* Answer the type binding corresponding to the compoundName. - * - * NOTE: If a problem binding is returned, senders should extract the compound name - * from the binding & not assume the problem applies to the entire compoundName. - */ + /* + * Answer the type binding corresponding to the compoundName. + * + * NOTE: If a problem binding is returned, senders should extract the + * compound name from the binding & not assume the problem applies to the + * entire compoundName. + */ public final TypeBinding getType(char[][] compoundName) { int typeNameLength = compoundName.length; if (typeNameLength == 1) { - // Would like to remove this test and require senders to specially handle base types + // Would like to remove this test and require senders to specially + // handle base types TypeBinding binding = getBaseType(compoundName[0]); - if (binding != null) return binding; + if (binding != null) + return binding; } compilationUnitScope().recordQualifiedReference(compoundName); - Binding binding = - getTypeOrPackage(compoundName[0], typeNameLength == 1 ? TYPE : TYPE | PACKAGE); + Binding binding = getTypeOrPackage(compoundName[0], + typeNameLength == 1 ? TYPE : TYPE | PACKAGE); if (binding == null) return new ProblemReferenceBinding(compoundName[0], NotFound); if (!binding.isValidBinding()) @@ -966,56 +1074,62 @@ public abstract class Scope if (binding instanceof PackageBinding) { PackageBinding packageBinding = (PackageBinding) binding; while (currentIndex < typeNameLength) { - binding = packageBinding.getTypeOrPackage(compoundName[currentIndex++]); // does not check visibility + binding = packageBinding + .getTypeOrPackage(compoundName[currentIndex++]); // does + // not + // check + // visibility if (binding == null) - return new ProblemReferenceBinding( - CharOperation.subarray(compoundName, 0, currentIndex), - NotFound); + return new ProblemReferenceBinding(CharOperation.subarray( + compoundName, 0, currentIndex), NotFound); if (!binding.isValidBinding()) - return new ProblemReferenceBinding( - CharOperation.subarray(compoundName, 0, currentIndex), - binding.problemId()); + return new ProblemReferenceBinding(CharOperation.subarray( + compoundName, 0, currentIndex), binding.problemId()); if (!(binding instanceof PackageBinding)) break; packageBinding = (PackageBinding) binding; } if (binding instanceof PackageBinding) - return new ProblemReferenceBinding( - CharOperation.subarray(compoundName, 0, currentIndex), - NotFound); + return new ProblemReferenceBinding(CharOperation.subarray( + compoundName, 0, currentIndex), NotFound); checkVisibility = true; } // binding is now a ReferenceBinding ReferenceBinding typeBinding = (ReferenceBinding) binding; - compilationUnitScope().recordTypeReference(typeBinding); // to record supertypes + compilationUnitScope().recordTypeReference(typeBinding); // to record + // supertypes if (checkVisibility) // handles the fall through case if (!typeBinding.canBeSeenBy(this)) - return new ProblemReferenceBinding( - CharOperation.subarray(compoundName, 0, currentIndex), - typeBinding, - NotVisible); + return new ProblemReferenceBinding(CharOperation.subarray( + compoundName, 0, currentIndex), typeBinding, NotVisible); while (currentIndex < typeNameLength) { - typeBinding = getMemberType(compoundName[currentIndex++], typeBinding); + typeBinding = getMemberType(compoundName[currentIndex++], + typeBinding); if (!typeBinding.isValidBinding()) - return new ProblemReferenceBinding( - CharOperation.subarray(compoundName, 0, currentIndex), - typeBinding.problemId()); + return new ProblemReferenceBinding(CharOperation.subarray( + compoundName, 0, currentIndex), typeBinding.problemId()); } return typeBinding; } - /* Answer the type binding that corresponds the given name, starting the lookup in the receiver. - * The name provided is a simple source name (e.g., "Object" , "Point", ...) - */ - // The return type of this method could be ReferenceBinding if we did not answer base types. - // NOTE: We could support looking for Base Types last in the search, however any code using - // this feature would be extraordinarily slow. Therefore we don't do this + /* + * Answer the type binding that corresponds the given name, starting the + * lookup in the receiver. The name provided is a simple source name (e.g., + * "Object" , "Point", ...) + */ + // The return type of this method could be ReferenceBinding if we did not + // answer base types. + // NOTE: We could support looking for Base Types last in the search, however + // any code using + // this feature would be extraordinarily slow. Therefore we don't do this public final TypeBinding getType(char[] name) { - // Would like to remove this test and require senders to specially handle base types + // Would like to remove this test and require senders to specially + // handle base types TypeBinding binding = getBaseType(name); - if (binding != null) return binding; + if (binding != null) + return binding; return (ReferenceBinding) getTypeOrPackage(name, TYPE); } @@ -1024,10 +1138,12 @@ public abstract class Scope int nameLength = compoundName.length; if (nameLength == 1) { TypeBinding binding = getBaseType(compoundName[0]); - if (binding != null) return binding; + if (binding != null) + return binding; } Binding binding = getTypeOrPackage(compoundName[0], TYPE | PACKAGE); - if (!binding.isValidBinding()) return binding; + if (!binding.isValidBinding()) + return binding; int currentIndex = 1; boolean checkVisibility = false; @@ -1035,44 +1151,43 @@ public abstract class Scope PackageBinding packageBinding = (PackageBinding) binding; while (currentIndex < nameLength) { - binding = packageBinding.getTypeOrPackage(compoundName[currentIndex++]); + binding = packageBinding + .getTypeOrPackage(compoundName[currentIndex++]); if (binding == null) - return new ProblemReferenceBinding( - CharOperation.subarray(compoundName, 0, currentIndex), - NotFound); + return new ProblemReferenceBinding(CharOperation.subarray( + compoundName, 0, currentIndex), NotFound); if (!binding.isValidBinding()) - return new ProblemReferenceBinding( - CharOperation.subarray(compoundName, 0, currentIndex), - binding.problemId()); + return new ProblemReferenceBinding(CharOperation.subarray( + compoundName, 0, currentIndex), binding.problemId()); if (!(binding instanceof PackageBinding)) break; packageBinding = (PackageBinding) binding; } - if (binding instanceof PackageBinding) return binding; + if (binding instanceof PackageBinding) + return binding; checkVisibility = true; } // binding is now a ReferenceBinding ReferenceBinding typeBinding = (ReferenceBinding) binding; if (checkVisibility) // handles the fall through case if (!typeBinding.canBeSeenBy(this)) - return new ProblemReferenceBinding( - CharOperation.subarray(compoundName, 0, currentIndex), - typeBinding, - NotVisible); + return new ProblemReferenceBinding(CharOperation.subarray( + compoundName, 0, currentIndex), typeBinding, NotVisible); while (currentIndex < nameLength) { - typeBinding = getMemberType(compoundName[currentIndex++], typeBinding); + typeBinding = getMemberType(compoundName[currentIndex++], + typeBinding); // checks visibility if (!typeBinding.isValidBinding()) - return new ProblemReferenceBinding( - CharOperation.subarray(compoundName, 0, currentIndex), - typeBinding.problemId()); + return new ProblemReferenceBinding(CharOperation.subarray( + compoundName, 0, currentIndex), typeBinding.problemId()); } return typeBinding; } - /* Internal use only - */ + /* + * Internal use only + */ final Binding getTypeOrPackage(char[] name, int mask) { Scope scope = this; ReferenceBinding foundType = null; @@ -1081,55 +1196,76 @@ public abstract class Scope while ((next = scope.parent) != null) scope = next; } else { - done : while (true) { // done when a COMPILATION_UNIT_SCOPE is found + done: while (true) { // done when a COMPILATION_UNIT_SCOPE is + // found switch (scope.kind) { - case METHOD_SCOPE : - case BLOCK_SCOPE : - ReferenceBinding localType = ((BlockScope) scope).findLocalType(name); // looks in this scope only - if (localType != null) { - if (foundType != null && foundType != localType) - return new ProblemReferenceBinding(name, InheritedNameHidesEnclosingName); - return localType; - } - break; - case CLASS_SCOPE : - SourceTypeBinding sourceType = ((ClassScope) scope).referenceContext.binding; - // 6.5.5.1 - simple name favors member type over top-level type in same unit - ReferenceBinding memberType = findMemberType(name, sourceType); - if (memberType != null) { // skip it if we did not find anything - if (memberType.problemId() == Ambiguous) { - if (foundType == null || foundType.problemId() == NotVisible) - // supercedes any potential InheritedNameHidesEnclosingName problem - return memberType; - else - // make the user qualify the type, likely wants the first inherited type - return new ProblemReferenceBinding(name, InheritedNameHidesEnclosingName); - } -// if (memberType.isValidBinding()) { -// if (sourceType == memberType.enclosingType() -// || environment().options.complianceLevel >= CompilerOptions.JDK1_4) { -// // found a valid type in the 'immediate' scope (ie. not inherited) -// // OR in 1.4 mode (inherited shadows enclosing) -// if (foundType == null) -// return memberType; -// if (foundType.isValidBinding()) -// // if a valid type was found, complain when another is found in an 'immediate' enclosing type (ie. not inherited) -// if (foundType != memberType) -// return new ProblemReferenceBinding(name, InheritedNameHidesEnclosingName); -// } -// } - if (foundType == null || (foundType.problemId() == NotVisible && memberType.problemId() != NotVisible)) - // only remember the memberType if its the first one found or the previous one was not visible & memberType is... - foundType = memberType; - } - if (CharOperation.equals(sourceType.sourceName, name)) { - if (foundType != null && foundType != sourceType && foundType.problemId() != NotVisible) - return new ProblemReferenceBinding(name, InheritedNameHidesEnclosingName); - return sourceType; + case METHOD_SCOPE: + case BLOCK_SCOPE: + ReferenceBinding localType = ((BlockScope) scope) + .findLocalType(name); // looks in this scope only + if (localType != null) { + if (foundType != null && foundType != localType) + return new ProblemReferenceBinding(name, + InheritedNameHidesEnclosingName); + return localType; + } + break; + case CLASS_SCOPE: + SourceTypeBinding sourceType = ((ClassScope) scope).referenceContext.binding; + // 6.5.5.1 - simple name favors member type over top-level + // type in same unit + ReferenceBinding memberType = findMemberType(name, + sourceType); + if (memberType != null) { // skip it if we did not find + // anything + if (memberType.problemId() == Ambiguous) { + if (foundType == null + || foundType.problemId() == NotVisible) + // supercedes any potential + // InheritedNameHidesEnclosingName problem + return memberType; + else + // make the user qualify the type, likely wants + // the first inherited type + return new ProblemReferenceBinding(name, + InheritedNameHidesEnclosingName); } - break; - case COMPILATION_UNIT_SCOPE : - break done; + // if (memberType.isValidBinding()) { + // if (sourceType == memberType.enclosingType() + // || environment().options.complianceLevel >= + // CompilerOptions.JDK1_4) { + // // found a valid type in the 'immediate' scope (ie. + // not inherited) + // // OR in 1.4 mode (inherited shadows enclosing) + // if (foundType == null) + // return memberType; + // if (foundType.isValidBinding()) + // // if a valid type was found, complain when another + // is found in an 'immediate' enclosing type (ie. not + // inherited) + // if (foundType != memberType) + // return new ProblemReferenceBinding(name, + // InheritedNameHidesEnclosingName); + // } + // } + if (foundType == null + || (foundType.problemId() == NotVisible && memberType + .problemId() != NotVisible)) + // only remember the memberType if its the first one + // found or the previous one was not visible & + // memberType is... + foundType = memberType; + } + if (CharOperation.equals(sourceType.sourceName, name)) { + if (foundType != null && foundType != sourceType + && foundType.problemId() != NotVisible) + return new ProblemReferenceBinding(name, + InheritedNameHidesEnclosingName); + return sourceType; + } + break; + case COMPILATION_UNIT_SCOPE: + break done; } scope = scope.parent; } @@ -1139,30 +1275,39 @@ public abstract class Scope // at this point the scope is a compilation unit scope CompilationUnitScope unitScope = (CompilationUnitScope) scope; - PackageBinding currentPackage = unitScope.fPackage; + PackageBinding currentPackage = unitScope.fPackage; // ask for the imports + name if ((mask & TYPE) != 0) { // check single type imports. ImportBinding[] imports = unitScope.imports; if (imports != null) { - // copy the list, since single type imports are removed if they cannot be resolved + // copy the list, since single type imports are removed if they + // cannot be resolved for (int i = 0, length = imports.length; i < length; i++) { ImportBinding typeImport = imports[i]; if (!typeImport.onDemand) { - if (CharOperation.equals(typeImport.compoundName[typeImport.compoundName.length - 1], name)) { + if (CharOperation + .equals( + typeImport.compoundName[typeImport.compoundName.length - 1], + name)) { if (unitScope.resolveSingleTypeImport(typeImport) != null) { ImportReference importReference = typeImport.reference; - if (importReference != null) importReference.used = true; - return typeImport.resolvedImport; // already know its visible + if (importReference != null) + importReference.used = true; + return typeImport.resolvedImport; // already + // know its + // visible } } } } } - // check if the name is in the current package, skip it if its a sub-package + // check if the name is in the current package, skip it if its a + // sub-package unitScope.recordReference(currentPackage.compoundName, name); Binding binding = currentPackage.getTypeOrPackage(name); - if (binding instanceof ReferenceBinding) return binding; // type is always visible to its own package + if (binding instanceof ReferenceBinding) + return binding; // type is always visible to its own package // check on demand imports boolean foundInImport = false; @@ -1172,37 +1317,50 @@ public abstract class Scope ImportBinding someImport = imports[i]; if (someImport.onDemand) { Binding resolvedImport = someImport.resolvedImport; - ReferenceBinding temp = resolvedImport instanceof PackageBinding - ? findType(name, (PackageBinding) resolvedImport, currentPackage) - : findDirectMemberType(name, (ReferenceBinding) resolvedImport); + ReferenceBinding temp = resolvedImport instanceof PackageBinding ? findType( + name, (PackageBinding) resolvedImport, + currentPackage) + : findDirectMemberType(name, + (ReferenceBinding) resolvedImport); if (temp != null && temp.isValidBinding()) { -// ImportReference importReference = someImport.reference; -// if (importReference != null) importReference.used = true; + // ImportReference importReference = + // someImport.reference; + // if (importReference != null) importReference.used + // = true; if (foundInImport) - // Answer error binding -- import on demand conflict; name found in two import on demand packages. - return new ProblemReferenceBinding(name, Ambiguous); + // Answer error binding -- import on demand + // conflict; name found in two import on demand + // packages. + return new ProblemReferenceBinding(name, + Ambiguous); type = temp; foundInImport = true; } } } } - if (type != null) return type; + if (type != null) + return type; } unitScope.recordSimpleReference(name); if ((mask & PACKAGE) != 0) { - PackageBinding packageBinding = unitScope.environment.getTopLevelPackage(name); - if (packageBinding != null) return packageBinding; + PackageBinding packageBinding = unitScope.environment + .getTopLevelPackage(name); + if (packageBinding != null) + return packageBinding; } // Answer error binding -- could not find name - if (foundType != null) return foundType; // problem type from above + if (foundType != null) + return foundType; // problem type from above return new ProblemReferenceBinding(name, NotFound); } - /* Answer whether the type is defined in the same compilation unit as the receiver - */ + /* + * Answer whether the type is defined in the same compilation unit as the + * receiver + */ public final boolean isDefinedInSameUnit(ReferenceBinding type) { // find the outer most enclosing type ReferenceBinding enclosingType = type; @@ -1215,18 +1373,18 @@ public abstract class Scope unitScope = scope; // test that the enclosingType is not part of the compilation unit - SourceTypeBinding[] topLevelTypes = - ((CompilationUnitScope) unitScope).topLevelTypes; + SourceTypeBinding[] topLevelTypes = ((CompilationUnitScope) unitScope).topLevelTypes; for (int i = topLevelTypes.length; --i >= 0;) if (topLevelTypes[i] == enclosingType) return true; return false; } - /* Answer true if the scope is nested inside a given field declaration. - * Note: it works as long as the scope.fieldDeclarationIndex is reflecting the field being traversed - * e.g. during name resolution. - */ + /* + * Answer true if the scope is nested inside a given field declaration. + * Note: it works as long as the scope.fieldDeclarationIndex is reflecting + * the field being traversed e.g. during name resolution. + */ public final boolean isDefinedInField(FieldBinding field) { Scope scope = this; do { @@ -1234,7 +1392,7 @@ public abstract class Scope MethodScope methodScope = (MethodScope) scope; ReferenceContext refContext = methodScope.referenceContext; if (refContext instanceof TypeDeclaration - && ((TypeDeclaration)refContext).binding == field.declaringClass + && ((TypeDeclaration) refContext).binding == field.declaringClass && methodScope.fieldDeclarationIndex == field.id) { return true; } @@ -1244,15 +1402,16 @@ public abstract class Scope return false; } - /* Answer true if the scope is nested inside a given method declaration - */ + /* + * Answer true if the scope is nested inside a given method declaration + */ public final boolean isDefinedInMethod(MethodBinding method) { Scope scope = this; do { if (scope instanceof MethodScope) { ReferenceContext refContext = ((MethodScope) scope).referenceContext; if (refContext instanceof AbstractMethodDeclaration - && ((AbstractMethodDeclaration)refContext).binding == method) { + && ((AbstractMethodDeclaration) refContext).binding == method) { return true; } } @@ -1260,14 +1419,15 @@ public abstract class Scope } while (scope != null); return false; } - - /* Answer true if the scope is nested inside a given type declaration - */ + + /* + * Answer true if the scope is nested inside a given type declaration + */ public final boolean isDefinedInType(ReferenceBinding type) { Scope scope = this; do { if (scope instanceof ClassScope) - if (((ClassScope) scope).referenceContext.binding == type){ + if (((ClassScope) scope).referenceContext.binding == type) { return true; } scope = scope.parent; @@ -1275,47 +1435,48 @@ public abstract class Scope return false; } - public boolean isInsideDeprecatedCode(){ - switch(kind){ - case Scope.BLOCK_SCOPE : - case Scope.METHOD_SCOPE : - MethodScope methodScope = methodScope(); - if (!methodScope.isInsideInitializer()){ - // check method modifiers to see if deprecated - MethodBinding context = ((AbstractMethodDeclaration)methodScope.referenceContext).binding; - if (context != null && context.isViewedAsDeprecated()) { - return true; - } - } else { - SourceTypeBinding type = ((BlockScope)this).referenceType().binding; - - // inside field declaration ? check field modifier to see if deprecated - if (methodScope.fieldDeclarationIndex != MethodScope.NotInFieldDecl) { - for (int i = 0; i < type.fields.length; i++){ - if (type.fields[i].id == methodScope.fieldDeclarationIndex) { - // currently inside this field initialization - if (type.fields[i].isViewedAsDeprecated()){ - return true; - } - break; + public boolean isInsideDeprecatedCode() { + switch (kind) { + case Scope.BLOCK_SCOPE: + case Scope.METHOD_SCOPE: + MethodScope methodScope = methodScope(); + if (!methodScope.isInsideInitializer()) { + // check method modifiers to see if deprecated + MethodBinding context = ((AbstractMethodDeclaration) methodScope.referenceContext).binding; + if (context != null && context.isViewedAsDeprecated()) { + return true; + } + } else { + SourceTypeBinding type = ((BlockScope) this).referenceType().binding; + + // inside field declaration ? check field modifier to see if + // deprecated + if (methodScope.fieldDeclarationIndex != MethodScope.NotInFieldDecl) { + for (int i = 0; i < type.fields.length; i++) { + if (type.fields[i].id == methodScope.fieldDeclarationIndex) { + // currently inside this field initialization + if (type.fields[i].isViewedAsDeprecated()) { + return true; } + break; } } - if (type != null && type.isViewedAsDeprecated()) { - return true; - } } - break; - case Scope.CLASS_SCOPE : - ReferenceBinding context = ((ClassScope)this).referenceType().binding; - if (context != null && context.isViewedAsDeprecated()) { + if (type != null && type.isViewedAsDeprecated()) { return true; } - break; + } + break; + case Scope.CLASS_SCOPE: + ReferenceBinding context = ((ClassScope) this).referenceType().binding; + if (context != null && context.isViewedAsDeprecated()) { + return true; + } + break; } return false; } - + public final boolean isJavaIoSerializable(TypeBinding tb) { return tb == getJavaIoSerializable(); } @@ -1339,81 +1500,87 @@ public abstract class Scope } // Internal use only - /* All methods in visible are acceptable matches for the method in question... - * The methods defined by the receiver type appear before those defined by its - * superclass and so on. We want to find the one which matches best. - * - * Since the receiver type is a class, we know each method's declaring class is - * either the receiver type or one of its superclasses. It is an error if the best match - * is defined by a superclass, when a lesser match is defined by the receiver type - * or a closer superclass. - */ - protected final MethodBinding mostSpecificClassMethodBinding(MethodBinding[] visible, int visibleSize) { + /* + * All methods in visible are acceptable matches for the method in + * question... The methods defined by the receiver type appear before those + * defined by its superclass and so on. We want to find the one which + * matches best. + * + * Since the receiver type is a class, we know each method's declaring class + * is either the receiver type or one of its superclasses. It is an error if + * the best match is defined by a superclass, when a lesser match is defined + * by the receiver type or a closer superclass. + */ + protected final MethodBinding mostSpecificClassMethodBinding( + MethodBinding[] visible, int visibleSize) { MethodBinding method = null; MethodBinding previous = null; - nextVisible : for (int i = 0; i < visibleSize; i++) { + nextVisible: for (int i = 0; i < visibleSize; i++) { method = visible[i]; - - if (previous != null && method.declaringClass != previous.declaringClass) - break; // cannot answer a method farther up the hierarchy than the first method found + + if (previous != null + && method.declaringClass != previous.declaringClass) + break; // cannot answer a method farther up the hierarchy than + // the first method found previous = method; for (int j = 0; j < visibleSize; j++) { - if (i == j) continue; + if (i == j) + continue; MethodBinding next = visible[j]; if (!areParametersAssignable(next.parameters, method.parameters)) continue nextVisible; } - compilationUnitScope().recordTypeReferences(method.thrownExceptions); + compilationUnitScope() + .recordTypeReferences(method.thrownExceptions); return method; } - return new ProblemMethodBinding(visible[0].selector, visible[0].parameters, Ambiguous); + return new ProblemMethodBinding(visible[0].selector, + visible[0].parameters, Ambiguous); } // Internal use only - /* All methods in visible are acceptable matches for the method in question... - * Since the receiver type is an interface, we ignore the possibility that 2 inherited - * but unrelated superinterfaces may define the same method in acceptable but - * not identical ways... we just take the best match that we find since any class which - * implements the receiver interface MUST implement all signatures for the method... - * in which case the best match is correct. - * - * NOTE: This is different than javac... in the following example, the message send of - * bar(X) in class Y is supposed to be ambiguous. But any class which implements the - * interface I MUST implement both signatures for bar. If this class was the receiver of - * the message send instead of the interface I, then no problem would be reported. - * - interface I1 { - void bar(J j); - } - interface I2 { - // void bar(J j); - void bar(Object o); - } - interface I extends I1, I2 {} - interface J {} - - class X implements J {} - - class Y extends X { - public void foo(I i, X x) { i.bar(x); } - } - */ - protected final MethodBinding mostSpecificInterfaceMethodBinding(MethodBinding[] visible, int visibleSize) { + /* + * All methods in visible are acceptable matches for the method in + * question... Since the receiver type is an interface, we ignore the + * possibility that 2 inherited but unrelated superinterfaces may define the + * same method in acceptable but not identical ways... we just take the best + * match that we find since any class which implements the receiver + * interface MUST implement all signatures for the method... in which case + * the best match is correct. + * + * NOTE: This is different than javac... in the following example, the + * message send of bar(X) in class Y is supposed to be ambiguous. But any + * class which implements the interface I MUST implement both signatures for + * bar. If this class was the receiver of the message send instead of the + * interface I, then no problem would be reported. + * + * interface I1 { void bar(J j); } interface I2 { // void bar(J j); void + * bar(Object o); } interface I extends I1, I2 {} interface J {} + * + * class X implements J {} + * + * class Y extends X { public void foo(I i, X x) { i.bar(x); } } + */ + protected final MethodBinding mostSpecificInterfaceMethodBinding( + MethodBinding[] visible, int visibleSize) { MethodBinding method = null; - nextVisible : for (int i = 0; i < visibleSize; i++) { + nextVisible: for (int i = 0; i < visibleSize; i++) { method = visible[i]; for (int j = 0; j < visibleSize; j++) { - if (i == j) continue; + if (i == j) + continue; MethodBinding next = visible[j]; if (!areParametersAssignable(next.parameters, method.parameters)) continue nextVisible; } - compilationUnitScope().recordTypeReferences(method.thrownExceptions); + compilationUnitScope() + .recordTypeReferences(method.thrownExceptions); return method; } - return new ProblemMethodBinding(visible[0].selector, visible[0].parameters, Ambiguous); + return new ProblemMethodBinding(visible[0].selector, + visible[0].parameters, Ambiguous); } public final ClassScope outerMostClassScope() { @@ -1444,6 +1611,7 @@ public abstract class Scope unitScope = scope; return ((CompilationUnitScope) unitScope).referenceContext; } + // start position in this scope - for ordering scopes vs. variables int startIndex() { return 0; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/SourceTypeBinding.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/SourceTypeBinding.java index 266a332..51345a4 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/SourceTypeBinding.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/SourceTypeBinding.java @@ -25,431 +25,450 @@ import net.sourceforge.phpdt.internal.compiler.ast.TypeReference; import net.sourceforge.phpdt.internal.compiler.impl.Constant; import net.sourceforge.phpdt.internal.compiler.problem.AbortCompilation; - public class SourceTypeBinding extends ReferenceBinding { public ReferenceBinding superclass; + public ReferenceBinding[] superInterfaces; + public FieldBinding[] fields; + public MethodBinding[] methods; + public ReferenceBinding[] memberTypes; public ClassScope scope; - // Synthetics are separated into 4 categories: methods, super methods, fields, class literals and changed declaring class bindings + // Synthetics are separated into 4 categories: methods, super methods, + // fields, class literals and changed declaring class bindings public final static int METHOD = 0; + public final static int FIELD = 1; + public final static int CLASS_LITERAL = 2; + public final static int CHANGED_DECLARING_CLASS = 3; Hashtable[] synthetics; -protected SourceTypeBinding() { -} -public SourceTypeBinding(char[][] compoundName, PackageBinding fPackage, ClassScope scope) { - this.compoundName = compoundName; - this.fPackage = fPackage; - this.fileName = scope.referenceCompilationUnit().getFileName(); - this.modifiers = scope.referenceContext.modifiers; - this.sourceName = scope.referenceContext.name; - this.scope = scope; - -// computeId(); -} -private void addDefaultAbstractMethod(MethodBinding abstractMethod) { - MethodBinding defaultAbstract = new MethodBinding( - abstractMethod.modifiers | AccDefaultAbstract, - abstractMethod.selector, - abstractMethod.returnType, - abstractMethod.parameters, - abstractMethod.thrownExceptions, - this); - - MethodBinding[] temp = new MethodBinding[methods.length + 1]; - System.arraycopy(methods, 0, temp, 0, methods.length); - temp[methods.length] = defaultAbstract; - methods = temp; -} -public void addDefaultAbstractMethods() { - if ((tagBits & KnowsDefaultAbstractMethods) != 0) return; + protected SourceTypeBinding() { + } - tagBits |= KnowsDefaultAbstractMethods; + public SourceTypeBinding(char[][] compoundName, PackageBinding fPackage, + ClassScope scope) { + this.compoundName = compoundName; + this.fPackage = fPackage; + this.fileName = scope.referenceCompilationUnit().getFileName(); + this.modifiers = scope.referenceContext.modifiers; + this.sourceName = scope.referenceContext.name; + this.scope = scope; - if (isClass() && isAbstract()) { -// if (fPackage.environment.options.targetJDK >= CompilerOptions.JDK1_2) return; // no longer added for post 1.2 targets + // computeId(); + } - ReferenceBinding[][] interfacesToVisit = new ReferenceBinding[5][]; - int lastPosition = 0; - interfacesToVisit[lastPosition] = superInterfaces(); + private void addDefaultAbstractMethod(MethodBinding abstractMethod) { + MethodBinding defaultAbstract = new MethodBinding( + abstractMethod.modifiers | AccDefaultAbstract, + abstractMethod.selector, abstractMethod.returnType, + abstractMethod.parameters, abstractMethod.thrownExceptions, + this); + + MethodBinding[] temp = new MethodBinding[methods.length + 1]; + System.arraycopy(methods, 0, temp, 0, methods.length); + temp[methods.length] = defaultAbstract; + methods = temp; + } - for (int i = 0; i <= lastPosition; i++) { - ReferenceBinding[] interfaces = interfacesToVisit[i]; - for (int j = 0, length = interfaces.length; j < length; j++) { - ReferenceBinding superType = interfaces[j]; - if (superType.isValidBinding()) { - MethodBinding[] methods = superType.methods(); - for (int m = methods.length; --m >= 0;) { - MethodBinding method = methods[m]; - if (!implementsMethod(method)) - addDefaultAbstractMethod(method); - } + public void addDefaultAbstractMethods() { + if ((tagBits & KnowsDefaultAbstractMethods) != 0) + return; + + tagBits |= KnowsDefaultAbstractMethods; + + if (isClass() && isAbstract()) { + // if (fPackage.environment.options.targetJDK >= + // CompilerOptions.JDK1_2) return; // no longer added for post 1.2 + // targets + + ReferenceBinding[][] interfacesToVisit = new ReferenceBinding[5][]; + int lastPosition = 0; + interfacesToVisit[lastPosition] = superInterfaces(); + + for (int i = 0; i <= lastPosition; i++) { + ReferenceBinding[] interfaces = interfacesToVisit[i]; + for (int j = 0, length = interfaces.length; j < length; j++) { + ReferenceBinding superType = interfaces[j]; + if (superType.isValidBinding()) { + MethodBinding[] methods = superType.methods(); + for (int m = methods.length; --m >= 0;) { + MethodBinding method = methods[m]; + if (!implementsMethod(method)) + addDefaultAbstractMethod(method); + } - ReferenceBinding[] itsInterfaces = superType.superInterfaces(); - if (itsInterfaces != NoSuperInterfaces) { - if (++lastPosition == interfacesToVisit.length) - System.arraycopy(interfacesToVisit, 0, interfacesToVisit = new ReferenceBinding[lastPosition * 2][], 0, lastPosition); - interfacesToVisit[lastPosition] = itsInterfaces; + ReferenceBinding[] itsInterfaces = superType + .superInterfaces(); + if (itsInterfaces != NoSuperInterfaces) { + if (++lastPosition == interfacesToVisit.length) + System + .arraycopy( + interfacesToVisit, + 0, + interfacesToVisit = new ReferenceBinding[lastPosition * 2][], + 0, lastPosition); + interfacesToVisit[lastPosition] = itsInterfaces; + } } } } } } -} -/* Add a new synthetic field for . -* Answer the new field or the existing field if one already existed. -*/ -public FieldBinding addSyntheticField(LocalVariableBinding actualOuterLocalVariable) { - if (synthetics == null) { - synthetics = new Hashtable[4]; - } - if (synthetics[FIELD] == null) { - synthetics[FIELD] = new Hashtable(5); - } + /* + * Add a new synthetic field for . Answer the new + * field or the existing field if one already existed. + */ + + public FieldBinding addSyntheticField( + LocalVariableBinding actualOuterLocalVariable) { + if (synthetics == null) { + synthetics = new Hashtable[4]; + } + if (synthetics[FIELD] == null) { + synthetics[FIELD] = new Hashtable(5); + } + + FieldBinding synthField = (FieldBinding) synthetics[FIELD] + .get(actualOuterLocalVariable); + if (synthField == null) { + synthField = new SyntheticFieldBinding(CharOperation.concat( + SyntheticArgumentBinding.OuterLocalPrefix, + actualOuterLocalVariable.name), + actualOuterLocalVariable.type, AccPrivate | AccFinal,// | + // AccSynthetic, + this, Constant.NotAConstant, synthetics[FIELD].size()); + synthetics[FIELD].put(actualOuterLocalVariable, synthField); + } - FieldBinding synthField = (FieldBinding) synthetics[FIELD].get(actualOuterLocalVariable); - if (synthField == null) { - synthField = new SyntheticFieldBinding( - CharOperation.concat(SyntheticArgumentBinding.OuterLocalPrefix, actualOuterLocalVariable.name), - actualOuterLocalVariable.type, - AccPrivate | AccFinal ,//| AccSynthetic, - this, - Constant.NotAConstant, - synthetics[FIELD].size()); - synthetics[FIELD].put(actualOuterLocalVariable, synthField); + // ensure there is not already such a field defined by the user + boolean needRecheck; + int index = 1; + do { + needRecheck = false; + FieldBinding existingField; + if ((existingField = this.getField(synthField.name)) != null) { + TypeDeclaration typeDecl = scope.referenceContext; + for (int i = 0, max = typeDecl.fields.length; i < max; i++) { + FieldDeclaration fieldDecl = typeDecl.fields[i]; + if (fieldDecl.binding == existingField) { + synthField.name = CharOperation.concat( + SyntheticArgumentBinding.OuterLocalPrefix, + actualOuterLocalVariable.name, + ("$" + String.valueOf(index++)).toCharArray()); //$NON-NLS-1$ + needRecheck = true; + break; + } + } + } + } while (needRecheck); + return synthField; } - // ensure there is not already such a field defined by the user - boolean needRecheck; - int index = 1; - do { - needRecheck = false; + /* + * Add a new synthetic field for . Answer the new field or + * the existing field if one already existed. + */ + + public FieldBinding addSyntheticField(ReferenceBinding enclosingType) { + + if (synthetics == null) { + synthetics = new Hashtable[4]; + } + if (synthetics[FIELD] == null) { + synthetics[FIELD] = new Hashtable(5); + } + + FieldBinding synthField = (FieldBinding) synthetics[FIELD] + .get(enclosingType); + if (synthField == null) { + synthField = new SyntheticFieldBinding(CharOperation.concat( + SyntheticArgumentBinding.EnclosingInstancePrefix, String + .valueOf(enclosingType.depth()).toCharArray()), + enclosingType, AccDefault | AccFinal,// | AccSynthetic, + this, Constant.NotAConstant, synthetics[FIELD].size()); + synthetics[FIELD].put(enclosingType, synthField); + } + // ensure there is not already such a field defined by the user FieldBinding existingField; if ((existingField = this.getField(synthField.name)) != null) { TypeDeclaration typeDecl = scope.referenceContext; for (int i = 0, max = typeDecl.fields.length; i < max; i++) { FieldDeclaration fieldDecl = typeDecl.fields[i]; if (fieldDecl.binding == existingField) { - synthField.name = CharOperation.concat( - SyntheticArgumentBinding.OuterLocalPrefix, - actualOuterLocalVariable.name, - ("$" + String.valueOf(index++)).toCharArray()); //$NON-NLS-1$ - needRecheck = true; + scope.problemReporter().duplicateFieldInType(this, + fieldDecl); break; } } } - } while (needRecheck); - return synthField; -} -/* Add a new synthetic field for . -* Answer the new field or the existing field if one already existed. -*/ - -public FieldBinding addSyntheticField(ReferenceBinding enclosingType) { - - if (synthetics == null) { - synthetics = new Hashtable[4]; - } - if (synthetics[FIELD] == null) { - synthetics[FIELD] = new Hashtable(5); + return synthField; } - FieldBinding synthField = (FieldBinding) synthetics[FIELD].get(enclosingType); - if (synthField == null) { - synthField = new SyntheticFieldBinding( - CharOperation.concat( - SyntheticArgumentBinding.EnclosingInstancePrefix, - String.valueOf(enclosingType.depth()).toCharArray()), - enclosingType, - AccDefault | AccFinal,// | AccSynthetic, - this, - Constant.NotAConstant, - synthetics[FIELD].size()); - synthetics[FIELD].put(enclosingType, synthField); - } - // ensure there is not already such a field defined by the user - FieldBinding existingField; - if ((existingField = this.getField(synthField.name)) != null) { - TypeDeclaration typeDecl = scope.referenceContext; - for (int i = 0, max = typeDecl.fields.length; i < max; i++) { - FieldDeclaration fieldDecl = typeDecl.fields[i]; - if (fieldDecl.binding == existingField) { - scope.problemReporter().duplicateFieldInType(this, fieldDecl); - break; - } - } - } - return synthField; -} -/* Add a new synthetic field for a class literal access. -* Answer the new field or the existing field if one already existed. -*/ + /* + * Add a new synthetic field for a class literal access. Answer the new + * field or the existing field if one already existed. + */ -public FieldBinding addSyntheticField(TypeBinding targetType, BlockScope blockScope) { - - if (synthetics == null) { - synthetics = new Hashtable[4]; - } - if (synthetics[CLASS_LITERAL] == null) { - synthetics[CLASS_LITERAL] = new Hashtable(5); - } + public FieldBinding addSyntheticField(TypeBinding targetType, + BlockScope blockScope) { - // use a different table than FIELDS, given there might be a collision between emulation of X.this$0 and X.class. - FieldBinding synthField = (FieldBinding) synthetics[CLASS_LITERAL].get(targetType); - if (synthField == null) { - synthField = new SyntheticFieldBinding( - ("class$" + synthetics[CLASS_LITERAL].size()).toCharArray(), //$NON-NLS-1$ - blockScope.getJavaLangClass(), - AccDefault | AccStatic,// | AccSynthetic, - this, - Constant.NotAConstant, - synthetics[CLASS_LITERAL].size()); - synthetics[CLASS_LITERAL].put(targetType, synthField); - } - // ensure there is not already such a field defined by the user - FieldBinding existingField; - if ((existingField = this.getField(synthField.name)) != null) { - TypeDeclaration typeDecl = blockScope.referenceType(); - for (int i = 0, max = typeDecl.fields.length; i < max; i++) { - FieldDeclaration fieldDecl = typeDecl.fields[i]; - if (fieldDecl.binding == existingField) { - blockScope.problemReporter().duplicateFieldInType(this, fieldDecl); - break; - } + if (synthetics == null) { + synthetics = new Hashtable[4]; + } + if (synthetics[CLASS_LITERAL] == null) { + synthetics[CLASS_LITERAL] = new Hashtable(5); } - } - return synthField; -} - -/* Add a new synthetic field for the emulation of the assert statement. -* Answer the new field or the existing field if one already existed. -*/ -public FieldBinding addSyntheticField(AssertStatement assertStatement, BlockScope blockScope) { - - if (synthetics == null) { - synthetics = new Hashtable[4]; - } - if (synthetics[FIELD] == null) { - synthetics[FIELD] = new Hashtable(5); - } - FieldBinding synthField = (FieldBinding) synthetics[FIELD].get("assertionEmulation"); //$NON-NLS-1$ - if (synthField == null) { - synthField = new SyntheticFieldBinding( - "$assertionsDisabled".toCharArray(), //$NON-NLS-1$ - BooleanBinding, - AccDefault | AccStatic | AccFinal,//| AccSynthetic | AccFinal, - this, - Constant.NotAConstant, - synthetics[FIELD].size()); - synthetics[FIELD].put("assertionEmulation", synthField); //$NON-NLS-1$ - } - // ensure there is not already such a field defined by the user - // ensure there is not already such a field defined by the user - boolean needRecheck; - int index = 0; - do { - needRecheck = false; + // use a different table than FIELDS, given there might be a collision + // between emulation of X.this$0 and X.class. + FieldBinding synthField = (FieldBinding) synthetics[CLASS_LITERAL] + .get(targetType); + if (synthField == null) { + synthField = new SyntheticFieldBinding( + ("class$" + synthetics[CLASS_LITERAL].size()).toCharArray(), //$NON-NLS-1$ + blockScope.getJavaLangClass(), AccDefault | AccStatic,// | + // AccSynthetic, + this, Constant.NotAConstant, synthetics[CLASS_LITERAL] + .size()); + synthetics[CLASS_LITERAL].put(targetType, synthField); + } + // ensure there is not already such a field defined by the user FieldBinding existingField; if ((existingField = this.getField(synthField.name)) != null) { - TypeDeclaration typeDecl = scope.referenceContext; + TypeDeclaration typeDecl = blockScope.referenceType(); for (int i = 0, max = typeDecl.fields.length; i < max; i++) { FieldDeclaration fieldDecl = typeDecl.fields[i]; if (fieldDecl.binding == existingField) { - synthField.name = CharOperation.concat( - "$assertionsDisabled".toCharArray(), //$NON-NLS-1$ - ("_" + String.valueOf(index++)).toCharArray()); //$NON-NLS-1$ - needRecheck = true; + blockScope.problemReporter().duplicateFieldInType(this, + fieldDecl); break; } } } - } while (needRecheck); - return synthField; -} + return synthField; + } -/* Add a new synthetic access method for read/write access to . - Answer the new method or the existing method if one already existed. -*/ + /* + * Add a new synthetic field for the emulation of the assert statement. + * Answer the new field or the existing field if one already existed. + */ + public FieldBinding addSyntheticField(AssertStatement assertStatement, + BlockScope blockScope) { -public SyntheticAccessMethodBinding addSyntheticMethod(FieldBinding targetField, boolean isReadAccess) { + if (synthetics == null) { + synthetics = new Hashtable[4]; + } + if (synthetics[FIELD] == null) { + synthetics[FIELD] = new Hashtable(5); + } - if (synthetics == null) { - synthetics = new Hashtable[4]; - } - if (synthetics[METHOD] == null) { - synthetics[METHOD] = new Hashtable(5); + FieldBinding synthField = (FieldBinding) synthetics[FIELD] + .get("assertionEmulation"); //$NON-NLS-1$ + if (synthField == null) { + synthField = new SyntheticFieldBinding( + "$assertionsDisabled".toCharArray(), //$NON-NLS-1$ + BooleanBinding, AccDefault | AccStatic | AccFinal,// | + // AccSynthetic + // | + // AccFinal, + this, Constant.NotAConstant, synthetics[FIELD].size()); + synthetics[FIELD].put("assertionEmulation", synthField); //$NON-NLS-1$ + } + // ensure there is not already such a field defined by the user + // ensure there is not already such a field defined by the user + boolean needRecheck; + int index = 0; + do { + needRecheck = false; + FieldBinding existingField; + if ((existingField = this.getField(synthField.name)) != null) { + TypeDeclaration typeDecl = scope.referenceContext; + for (int i = 0, max = typeDecl.fields.length; i < max; i++) { + FieldDeclaration fieldDecl = typeDecl.fields[i]; + if (fieldDecl.binding == existingField) { + synthField.name = CharOperation.concat( + "$assertionsDisabled".toCharArray(), //$NON-NLS-1$ + ("_" + String.valueOf(index++)).toCharArray()); //$NON-NLS-1$ + needRecheck = true; + break; + } + } + } + } while (needRecheck); + return synthField; } - SyntheticAccessMethodBinding accessMethod = null; - SyntheticAccessMethodBinding[] accessors = (SyntheticAccessMethodBinding[]) synthetics[METHOD].get(targetField); - if (accessors == null) { - accessMethod = new SyntheticAccessMethodBinding(targetField, isReadAccess, this); - synthetics[METHOD].put(targetField, accessors = new SyntheticAccessMethodBinding[2]); - accessors[isReadAccess ? 0 : 1] = accessMethod; - } else { - if ((accessMethod = accessors[isReadAccess ? 0 : 1]) == null) { - accessMethod = new SyntheticAccessMethodBinding(targetField, isReadAccess, this); + /* + * Add a new synthetic access method for read/write access to . + * Answer the new method or the existing method if one already existed. + */ + + public SyntheticAccessMethodBinding addSyntheticMethod( + FieldBinding targetField, boolean isReadAccess) { + + if (synthetics == null) { + synthetics = new Hashtable[4]; + } + if (synthetics[METHOD] == null) { + synthetics[METHOD] = new Hashtable(5); + } + + SyntheticAccessMethodBinding accessMethod = null; + SyntheticAccessMethodBinding[] accessors = (SyntheticAccessMethodBinding[]) synthetics[METHOD] + .get(targetField); + if (accessors == null) { + accessMethod = new SyntheticAccessMethodBinding(targetField, + isReadAccess, this); + synthetics[METHOD].put(targetField, + accessors = new SyntheticAccessMethodBinding[2]); accessors[isReadAccess ? 0 : 1] = accessMethod; + } else { + if ((accessMethod = accessors[isReadAccess ? 0 : 1]) == null) { + accessMethod = new SyntheticAccessMethodBinding(targetField, + isReadAccess, this); + accessors[isReadAccess ? 0 : 1] = accessMethod; + } } + return accessMethod; } - return accessMethod; -} -/* Add a new synthetic access method for access to . - * Must distinguish access method used for super access from others (need to use invokespecial bytecode) - Answer the new method or the existing method if one already existed. -*/ -public SyntheticAccessMethodBinding addSyntheticMethod(MethodBinding targetMethod, boolean isSuperAccess) { + /* + * Add a new synthetic access method for access to . Must + * distinguish access method used for super access from others (need to use + * invokespecial bytecode) Answer the new method or the existing method if + * one already existed. + */ - if (synthetics == null) { - synthetics = new Hashtable[4]; - } - if (synthetics[METHOD] == null) { - synthetics[METHOD] = new Hashtable(5); - } + public SyntheticAccessMethodBinding addSyntheticMethod( + MethodBinding targetMethod, boolean isSuperAccess) { - SyntheticAccessMethodBinding accessMethod = null; - SyntheticAccessMethodBinding[] accessors = (SyntheticAccessMethodBinding[]) synthetics[METHOD].get(targetMethod); - if (accessors == null) { - accessMethod = new SyntheticAccessMethodBinding(targetMethod, isSuperAccess, this); - synthetics[METHOD].put(targetMethod, accessors = new SyntheticAccessMethodBinding[2]); - accessors[isSuperAccess ? 0 : 1] = accessMethod; - } else { - if ((accessMethod = accessors[isSuperAccess ? 0 : 1]) == null) { - accessMethod = new SyntheticAccessMethodBinding(targetMethod, isSuperAccess, this); + if (synthetics == null) { + synthetics = new Hashtable[4]; + } + if (synthetics[METHOD] == null) { + synthetics[METHOD] = new Hashtable(5); + } + + SyntheticAccessMethodBinding accessMethod = null; + SyntheticAccessMethodBinding[] accessors = (SyntheticAccessMethodBinding[]) synthetics[METHOD] + .get(targetMethod); + if (accessors == null) { + accessMethod = new SyntheticAccessMethodBinding(targetMethod, + isSuperAccess, this); + synthetics[METHOD].put(targetMethod, + accessors = new SyntheticAccessMethodBinding[2]); accessors[isSuperAccess ? 0 : 1] = accessMethod; + } else { + if ((accessMethod = accessors[isSuperAccess ? 0 : 1]) == null) { + accessMethod = new SyntheticAccessMethodBinding(targetMethod, + isSuperAccess, this); + accessors[isSuperAccess ? 0 : 1] = accessMethod; + } } + return accessMethod; } - return accessMethod; -} -public FieldBinding[] availableFields() { - return fields(); -} -public MethodBinding[] availableMethods() { - return methods(); -} -void faultInTypesForFieldsAndMethods() { - fields(); - methods(); + public FieldBinding[] availableFields() { + return fields(); + } - for (int i = 0, length = memberTypes.length; i < length; i++) - ((SourceTypeBinding) memberTypes[i]).faultInTypesForFieldsAndMethods(); -} -// NOTE: the type of each field of a source type is resolved when needed + public MethodBinding[] availableMethods() { + return methods(); + } + + void faultInTypesForFieldsAndMethods() { + fields(); + methods(); -public FieldBinding[] fields() { - if (fields==null) { - fields = new FieldBinding[0]; + for (int i = 0, length = memberTypes.length; i < length; i++) + ((SourceTypeBinding) memberTypes[i]) + .faultInTypesForFieldsAndMethods(); } - try { - int failed = 0; - for (int f = 0, max = fields.length; f < max; f++) { - if (resolveTypeFor(fields[f]) == null) { - fields[f] = null; - failed++; - } - } - if (failed > 0) { - int newSize = fields.length - failed; - if (newSize == 0) - return fields = NoFields; - - FieldBinding[] newFields = new FieldBinding[newSize]; - for (int i = 0, n = 0, max = fields.length; i < max; i++) - if (fields[i] != null) - newFields[n++] = fields[i]; - fields = newFields; + + // NOTE: the type of each field of a source type is resolved when needed + + public FieldBinding[] fields() { + if (fields == null) { + fields = new FieldBinding[0]; } - } catch(AbortCompilation e){ - // ensure null fields are removed - FieldBinding[] newFields = null; - int count = 0; - for (int i = 0, max = fields.length; i < max; i++){ - FieldBinding field = fields[i]; - if (field == null && newFields == null){ - System.arraycopy(fields, 0, newFields = new FieldBinding[max], 0, i); - } else if (newFields != null && field != null) { - newFields[count++] = field; + try { + int failed = 0; + for (int f = 0, max = fields.length; f < max; f++) { + if (resolveTypeFor(fields[f]) == null) { + fields[f] = null; + failed++; + } } - } - if (newFields != null){ - System.arraycopy(newFields, 0, fields = new FieldBinding[count], 0, count); - } - throw e; - } - return fields; -} -public MethodBinding[] getDefaultAbstractMethods() { - int count = 0; - for (int i = methods.length; --i >= 0;) - if (methods[i].isDefaultAbstract()) - count++; - if (count == 0) return NoMethods; - - MethodBinding[] result = new MethodBinding[count]; - count = 0; - for (int i = methods.length; --i >= 0;) - if (methods[i].isDefaultAbstract()) - result[count++] = methods[i]; - return result; -} -// NOTE: the return type, arg & exception types of each method of a source type are resolved when needed + if (failed > 0) { + int newSize = fields.length - failed; + if (newSize == 0) + return fields = NoFields; -public MethodBinding getExactConstructor(TypeBinding[] argumentTypes) { - int argCount = argumentTypes.length; - - if ((modifiers & AccUnresolved) == 0) { // have resolved all arg types & return type of the methods - nextMethod : for (int m = methods.length; --m >= 0;) { - MethodBinding method = methods[m]; - if (method.selector == ConstructorDeclaration.ConstantPoolName && method.parameters.length == argCount) { - TypeBinding[] toMatch = method.parameters; - for (int p = 0; p < argCount; p++) - if (toMatch[p] != argumentTypes[p]) - continue nextMethod; - return method; + FieldBinding[] newFields = new FieldBinding[newSize]; + for (int i = 0, n = 0, max = fields.length; i < max; i++) + if (fields[i] != null) + newFields[n++] = fields[i]; + fields = newFields; } - } - } else { - MethodBinding[] methods = getMethods(ConstructorDeclaration.ConstantPoolName); // takes care of duplicates & default abstract methods - nextMethod : for (int m = methods.length; --m >= 0;) { - MethodBinding method = methods[m]; - TypeBinding[] toMatch = method.parameters; - if (toMatch.length == argCount) { - for (int p = 0; p < argCount; p++) - if (toMatch[p] != argumentTypes[p]) - continue nextMethod; - return method; + } catch (AbortCompilation e) { + // ensure null fields are removed + FieldBinding[] newFields = null; + int count = 0; + for (int i = 0, max = fields.length; i < max; i++) { + FieldBinding field = fields[i]; + if (field == null && newFields == null) { + System.arraycopy(fields, 0, + newFields = new FieldBinding[max], 0, i); + } else if (newFields != null && field != null) { + newFields[count++] = field; + } + } + if (newFields != null) { + System.arraycopy(newFields, 0, + fields = new FieldBinding[count], 0, count); } + throw e; } + return fields; } - return null; -} -// NOTE: the return type, arg & exception types of each method of a source type are resolved when needed -// searches up the hierarchy as long as no potential (but not exact) match was found. - -public MethodBinding getExactMethod(char[] selector, TypeBinding[] argumentTypes) { - int argCount = argumentTypes.length; - int selectorLength = selector.length; - boolean foundNothing = true; - - if ((modifiers & AccUnresolved) == 0) { // have resolved all arg types & return type of the methods - nextMethod : for (int m = methods.length; --m >= 0;) { - MethodBinding method = methods[m]; - if (method.selector.length == selectorLength && CharOperation.prefixEquals(method.selector, selector)) { - foundNothing = false; // inner type lookups must know that a method with this name exists - if (method.parameters.length == argCount) { + + public MethodBinding[] getDefaultAbstractMethods() { + int count = 0; + for (int i = methods.length; --i >= 0;) + if (methods[i].isDefaultAbstract()) + count++; + if (count == 0) + return NoMethods; + + MethodBinding[] result = new MethodBinding[count]; + count = 0; + for (int i = methods.length; --i >= 0;) + if (methods[i].isDefaultAbstract()) + result[count++] = methods[i]; + return result; + } + + // NOTE: the return type, arg & exception types of each method of a source + // type are resolved when needed + + public MethodBinding getExactConstructor(TypeBinding[] argumentTypes) { + int argCount = argumentTypes.length; + + if ((modifiers & AccUnresolved) == 0) { // have resolved all arg types & + // return type of the methods + nextMethod: for (int m = methods.length; --m >= 0;) { + MethodBinding method = methods[m]; + if (method.selector == ConstructorDeclaration.ConstantPoolName + && method.parameters.length == argCount) { TypeBinding[] toMatch = method.parameters; for (int p = 0; p < argCount; p++) if (toMatch[p] != argumentTypes[p]) @@ -457,608 +476,815 @@ public MethodBinding getExactMethod(char[] selector, TypeBinding[] argumentTypes return method; } } - } - } else { - MethodBinding[] methods = getMethods(selector); // takes care of duplicates & default abstract methods - foundNothing = methods == NoMethods; - nextMethod : for (int m = methods.length; --m >= 0;) { - MethodBinding method = methods[m]; - TypeBinding[] toMatch = method.parameters; - if (toMatch.length == argCount) { - for (int p = 0; p < argCount; p++) - if (toMatch[p] != argumentTypes[p]) - continue nextMethod; - return method; + } else { + MethodBinding[] methods = getMethods(ConstructorDeclaration.ConstantPoolName); // takes + // care + // of + // duplicates + // & + // default + // abstract + // methods + nextMethod: for (int m = methods.length; --m >= 0;) { + MethodBinding method = methods[m]; + TypeBinding[] toMatch = method.parameters; + if (toMatch.length == argCount) { + for (int p = 0; p < argCount; p++) + if (toMatch[p] != argumentTypes[p]) + continue nextMethod; + return method; + } } } + return null; } - if (foundNothing) { - if (isInterface()) { - if (superInterfaces.length == 1) - return superInterfaces[0].getExactMethod(selector, argumentTypes); - } else if (superclass != null) { - return superclass.getExactMethod(selector, argumentTypes); + // NOTE: the return type, arg & exception types of each method of a source + // type are resolved when needed + // searches up the hierarchy as long as no potential (but not exact) match + // was found. + + public MethodBinding getExactMethod(char[] selector, + TypeBinding[] argumentTypes) { + int argCount = argumentTypes.length; + int selectorLength = selector.length; + boolean foundNothing = true; + + if ((modifiers & AccUnresolved) == 0) { // have resolved all arg types & + // return type of the methods + nextMethod: for (int m = methods.length; --m >= 0;) { + MethodBinding method = methods[m]; + if (method.selector.length == selectorLength + && CharOperation + .prefixEquals(method.selector, selector)) { + foundNothing = false; // inner type lookups must know that + // a method with this name exists + if (method.parameters.length == argCount) { + TypeBinding[] toMatch = method.parameters; + for (int p = 0; p < argCount; p++) + if (toMatch[p] != argumentTypes[p]) + continue nextMethod; + return method; + } + } + } + } else { + MethodBinding[] methods = getMethods(selector); // takes care of + // duplicates & + // default abstract + // methods + foundNothing = methods == NoMethods; + nextMethod: for (int m = methods.length; --m >= 0;) { + MethodBinding method = methods[m]; + TypeBinding[] toMatch = method.parameters; + if (toMatch.length == argCount) { + for (int p = 0; p < argCount; p++) + if (toMatch[p] != argumentTypes[p]) + continue nextMethod; + return method; + } + } } - } - return null; -} -// NOTE: the type of a field of a source type is resolved when needed - -public FieldBinding getField(char[] fieldName) { - int fieldLength = fieldName.length; - for (int f = fields.length; --f >= 0;) { - FieldBinding field = fields[f]; - if (field.name.length == fieldLength && CharOperation.prefixEquals(field.name, fieldName)) { - if (resolveTypeFor(field) != null) - return field; - - int newSize = fields.length - 1; - if (newSize == 0) { - fields = NoFields; - } else { - FieldBinding[] newFields = new FieldBinding[newSize]; - System.arraycopy(fields, 0, newFields, 0, f); - System.arraycopy(fields, f + 1, newFields, f, newSize - f); - fields = newFields; + + if (foundNothing) { + if (isInterface()) { + if (superInterfaces.length == 1) + return superInterfaces[0].getExactMethod(selector, + argumentTypes); + } else if (superclass != null) { + return superclass.getExactMethod(selector, argumentTypes); } - return null; } + return null; } - return null; -} -// NOTE: the return type, arg & exception types of each method of a source type are resolved when needed -public MethodBinding[] getMethods(char[] selector) { - // handle forward references to potential default abstract methods - addDefaultAbstractMethods(); + // NOTE: the type of a field of a source type is resolved when needed - try{ - int count = 0; - int lastIndex = -1; - int selectorLength = selector.length; - if ((modifiers & AccUnresolved) == 0) { // have resolved all arg types & return type of the methods - for (int m = 0, length = methods.length; m < length; m++) { - MethodBinding method = methods[m]; - if (method.selector.length == selectorLength && CharOperation.prefixEquals(method.selector, selector)) { - count++; - lastIndex = m; + public FieldBinding getField(char[] fieldName) { + int fieldLength = fieldName.length; + for (int f = fields.length; --f >= 0;) { + FieldBinding field = fields[f]; + if (field.name.length == fieldLength + && CharOperation.prefixEquals(field.name, fieldName)) { + if (resolveTypeFor(field) != null) + return field; + + int newSize = fields.length - 1; + if (newSize == 0) { + fields = NoFields; + } else { + FieldBinding[] newFields = new FieldBinding[newSize]; + System.arraycopy(fields, 0, newFields, 0, f); + System.arraycopy(fields, f + 1, newFields, f, newSize - f); + fields = newFields; } + return null; } - } else { - boolean foundProblem = false; - int failed = 0; - for (int m = 0, length = methods.length; m < length; m++) { - MethodBinding method = methods[m]; - if (method.selector.length == selectorLength && CharOperation.prefixEquals(method.selector, selector)) { - if (resolveTypesFor(method) == null) { - foundProblem = true; - methods[m] = null; // unable to resolve parameters - failed++; - } else if (method.returnType == null) { - foundProblem = true; - } else { + } + return null; + } + + // NOTE: the return type, arg & exception types of each method of a source + // type are resolved when needed + + public MethodBinding[] getMethods(char[] selector) { + // handle forward references to potential default abstract methods + addDefaultAbstractMethods(); + + try { + int count = 0; + int lastIndex = -1; + int selectorLength = selector.length; + if ((modifiers & AccUnresolved) == 0) { // have resolved all arg + // types & return type of + // the methods + for (int m = 0, length = methods.length; m < length; m++) { + MethodBinding method = methods[m]; + if (method.selector.length == selectorLength + && CharOperation.prefixEquals(method.selector, + selector)) { count++; lastIndex = m; } } - } - - if (foundProblem || count > 1) { - for (int m = methods.length; --m >= 0;) { + } else { + boolean foundProblem = false; + int failed = 0; + for (int m = 0, length = methods.length; m < length; m++) { MethodBinding method = methods[m]; - if (method != null && method.selector.length == selectorLength && CharOperation.prefixEquals(method.selector, selector)) { - AbstractMethodDeclaration methodDecl = null; - for (int i = 0; i < m; i++) { - MethodBinding method2 = methods[i]; - if (method2 != null && CharOperation.equals(method.selector, method2.selector)) { - if (method.areParametersEqual(method2)) { - if (methodDecl == null) { - methodDecl = method.sourceMethod(); // cannot be retrieved after binding is lost - scope.problemReporter().duplicateMethodInType(this, methodDecl); - methodDecl.binding = null; - methods[m] = null; + if (method.selector.length == selectorLength + && CharOperation.prefixEquals(method.selector, + selector)) { + if (resolveTypesFor(method) == null) { + foundProblem = true; + methods[m] = null; // unable to resolve parameters + failed++; + } else if (method.returnType == null) { + foundProblem = true; + } else { + count++; + lastIndex = m; + } + } + } + + if (foundProblem || count > 1) { + for (int m = methods.length; --m >= 0;) { + MethodBinding method = methods[m]; + if (method != null + && method.selector.length == selectorLength + && CharOperation.prefixEquals(method.selector, + selector)) { + AbstractMethodDeclaration methodDecl = null; + for (int i = 0; i < m; i++) { + MethodBinding method2 = methods[i]; + if (method2 != null + && CharOperation.equals( + method.selector, + method2.selector)) { + if (method.areParametersEqual(method2)) { + if (methodDecl == null) { + methodDecl = method.sourceMethod(); // cannot + // be + // retrieved + // after + // binding + // is + // lost + scope.problemReporter() + .duplicateMethodInType( + this, methodDecl); + methodDecl.binding = null; + methods[m] = null; + failed++; + } + scope.problemReporter() + .duplicateMethodInType(this, + method2.sourceMethod()); + method2.sourceMethod().binding = null; + methods[i] = null; failed++; } - scope.problemReporter().duplicateMethodInType(this, method2.sourceMethod()); - method2.sourceMethod().binding = null; - methods[i] = null; - failed++; } } - } - if (method.returnType == null && methodDecl == null) { // forget method with invalid return type... was kept to detect possible collisions - method.sourceMethod().binding = null; - methods[m] = null; - failed++; + if (method.returnType == null && methodDecl == null) { // forget + // method + // with + // invalid + // return + // type... + // was + // kept + // to + // detect + // possible + // collisions + method.sourceMethod().binding = null; + methods[m] = null; + failed++; + } } } - } - if (failed > 0) { - int newSize = methods.length - failed; - if (newSize == 0) - return methods = NoMethods; - - MethodBinding[] newMethods = new MethodBinding[newSize]; - for (int i = 0, n = 0, max = methods.length; i < max; i++) - if (methods[i] != null) - newMethods[n++] = methods[i]; - methods = newMethods; - return getMethods(selector); // try again now that the problem methods have been removed + if (failed > 0) { + int newSize = methods.length - failed; + if (newSize == 0) + return methods = NoMethods; + + MethodBinding[] newMethods = new MethodBinding[newSize]; + for (int i = 0, n = 0, max = methods.length; i < max; i++) + if (methods[i] != null) + newMethods[n++] = methods[i]; + methods = newMethods; + return getMethods(selector); // try again now that + // the problem methods + // have been removed + } } } - } - if (count == 1) - return new MethodBinding[] {methods[lastIndex]}; - if (count > 1) { - MethodBinding[] result = new MethodBinding[count]; - count = 0; - for (int m = 0; m <= lastIndex; m++) { - MethodBinding method = methods[m]; - if (method.selector.length == selectorLength && CharOperation.prefixEquals(method.selector, selector)) - result[count++] = method; + if (count == 1) + return new MethodBinding[] { methods[lastIndex] }; + if (count > 1) { + MethodBinding[] result = new MethodBinding[count]; + count = 0; + for (int m = 0; m <= lastIndex; m++) { + MethodBinding method = methods[m]; + if (method.selector.length == selectorLength + && CharOperation.prefixEquals(method.selector, + selector)) + result[count++] = method; + } + return result; } - return result; - } - } catch(AbortCompilation e){ - // ensure null methods are removed - MethodBinding[] newMethods = null; - int count = 0; - for (int i = 0, max = methods.length; i < max; i++){ - MethodBinding method = methods[i]; - if (method == null && newMethods == null){ - System.arraycopy(methods, 0, newMethods = new MethodBinding[max], 0, i); - } else if (newMethods != null && method != null) { - newMethods[count++] = method; + } catch (AbortCompilation e) { + // ensure null methods are removed + MethodBinding[] newMethods = null; + int count = 0; + for (int i = 0, max = methods.length; i < max; i++) { + MethodBinding method = methods[i]; + if (method == null && newMethods == null) { + System.arraycopy(methods, 0, + newMethods = new MethodBinding[max], 0, i); + } else if (newMethods != null && method != null) { + newMethods[count++] = method; + } } + if (newMethods != null) { + System.arraycopy(newMethods, 0, + methods = new MethodBinding[count], 0, count); + } + modifiers ^= AccUnresolved; + throw e; } - if (newMethods != null){ - System.arraycopy(newMethods, 0, methods = new MethodBinding[count], 0, count); - } - modifiers ^= AccUnresolved; - throw e; + return NoMethods; } - return NoMethods; -} -/* Answer the synthetic field for -* or null if one does not exist. -*/ -public FieldBinding getSyntheticField(LocalVariableBinding actualOuterLocalVariable) { + /* + * Answer the synthetic field for or null if one + * does not exist. + */ - if (synthetics == null || synthetics[FIELD] == null) return null; - return (FieldBinding) synthetics[FIELD].get(actualOuterLocalVariable); -} -public ReferenceBinding[] memberTypes() { - return memberTypes; -} -public FieldBinding getUpdatedFieldBinding(FieldBinding targetField, ReferenceBinding newDeclaringClass) { + public FieldBinding getSyntheticField( + LocalVariableBinding actualOuterLocalVariable) { - if (synthetics == null) { - synthetics = new Hashtable[4]; - } - if (synthetics[CHANGED_DECLARING_CLASS] == null) { - synthetics[CHANGED_DECLARING_CLASS] = new Hashtable(5); + if (synthetics == null || synthetics[FIELD] == null) + return null; + return (FieldBinding) synthetics[FIELD].get(actualOuterLocalVariable); } - Hashtable fieldMap = (Hashtable) synthetics[CHANGED_DECLARING_CLASS].get(targetField); - if (fieldMap == null) { - fieldMap = new Hashtable(5); - synthetics[CHANGED_DECLARING_CLASS].put(targetField, fieldMap); - } - FieldBinding updatedField = (FieldBinding) fieldMap.get(newDeclaringClass); - if (updatedField == null){ - updatedField = new FieldBinding(targetField, newDeclaringClass); - fieldMap.put(newDeclaringClass, updatedField); + public ReferenceBinding[] memberTypes() { + return memberTypes; } - return updatedField; -} -public MethodBinding getUpdatedMethodBinding(MethodBinding targetMethod, ReferenceBinding newDeclaringClass) { + public FieldBinding getUpdatedFieldBinding(FieldBinding targetField, + ReferenceBinding newDeclaringClass) { - if (synthetics == null) { - synthetics = new Hashtable[4]; - } - if (synthetics[CHANGED_DECLARING_CLASS] == null) { - synthetics[CHANGED_DECLARING_CLASS] = new Hashtable(5); + if (synthetics == null) { + synthetics = new Hashtable[4]; + } + if (synthetics[CHANGED_DECLARING_CLASS] == null) { + synthetics[CHANGED_DECLARING_CLASS] = new Hashtable(5); + } + + Hashtable fieldMap = (Hashtable) synthetics[CHANGED_DECLARING_CLASS] + .get(targetField); + if (fieldMap == null) { + fieldMap = new Hashtable(5); + synthetics[CHANGED_DECLARING_CLASS].put(targetField, fieldMap); + } + FieldBinding updatedField = (FieldBinding) fieldMap + .get(newDeclaringClass); + if (updatedField == null) { + updatedField = new FieldBinding(targetField, newDeclaringClass); + fieldMap.put(newDeclaringClass, updatedField); + } + return updatedField; } + public MethodBinding getUpdatedMethodBinding(MethodBinding targetMethod, + ReferenceBinding newDeclaringClass) { - Hashtable methodMap = (Hashtable) synthetics[CHANGED_DECLARING_CLASS].get(targetMethod); - if (methodMap == null) { - methodMap = new Hashtable(5); - synthetics[CHANGED_DECLARING_CLASS].put(targetMethod, methodMap); - } - MethodBinding updatedMethod = (MethodBinding) methodMap.get(newDeclaringClass); - if (updatedMethod == null){ - updatedMethod = new MethodBinding(targetMethod, newDeclaringClass); - methodMap.put(newDeclaringClass, updatedMethod); + if (synthetics == null) { + synthetics = new Hashtable[4]; + } + if (synthetics[CHANGED_DECLARING_CLASS] == null) { + synthetics[CHANGED_DECLARING_CLASS] = new Hashtable(5); + } + + Hashtable methodMap = (Hashtable) synthetics[CHANGED_DECLARING_CLASS] + .get(targetMethod); + if (methodMap == null) { + methodMap = new Hashtable(5); + synthetics[CHANGED_DECLARING_CLASS].put(targetMethod, methodMap); + } + MethodBinding updatedMethod = (MethodBinding) methodMap + .get(newDeclaringClass); + if (updatedMethod == null) { + updatedMethod = new MethodBinding(targetMethod, newDeclaringClass); + methodMap.put(newDeclaringClass, updatedMethod); + } + return updatedMethod; } - return updatedMethod; -} -// NOTE: the return type, arg & exception types of each method of a source type are resolved when needed -public MethodBinding[] methods() { - try { - if ((modifiers & AccUnresolved) == 0) - return methods; - - int failed = 0; - for (int m = 0, max = methods.length; m < max; m++) { - if (resolveTypesFor(methods[m]) == null) { - methods[m] = null; // unable to resolve parameters - failed++; + // NOTE: the return type, arg & exception types of each method of a source + // type are resolved when needed + public MethodBinding[] methods() { + try { + if ((modifiers & AccUnresolved) == 0) + return methods; + + int failed = 0; + for (int m = 0, max = methods.length; m < max; m++) { + if (resolveTypesFor(methods[m]) == null) { + methods[m] = null; // unable to resolve parameters + failed++; + } } - } - for (int m = methods.length; --m >= 0;) { - MethodBinding method = methods[m]; - if (method != null) { - AbstractMethodDeclaration methodDecl = null; - for (int i = 0; i < m; i++) { - MethodBinding method2 = methods[i]; - if (method2 != null && CharOperation.equals(method.selector, method2.selector)) { - if (method.areParametersEqual(method2)) { - if (methodDecl == null) { - methodDecl = method.sourceMethod(); // cannot be retrieved after binding is lost - scope.problemReporter().duplicateMethodInType(this, methodDecl); - methodDecl.binding = null; - methods[m] = null; + for (int m = methods.length; --m >= 0;) { + MethodBinding method = methods[m]; + if (method != null) { + AbstractMethodDeclaration methodDecl = null; + for (int i = 0; i < m; i++) { + MethodBinding method2 = methods[i]; + if (method2 != null + && CharOperation.equals(method.selector, + method2.selector)) { + if (method.areParametersEqual(method2)) { + if (methodDecl == null) { + methodDecl = method.sourceMethod(); // cannot + // be + // retrieved + // after + // binding + // is + // lost + scope.problemReporter() + .duplicateMethodInType(this, + methodDecl); + methodDecl.binding = null; + methods[m] = null; + failed++; + } + scope.problemReporter().duplicateMethodInType( + this, method2.sourceMethod()); + method2.sourceMethod().binding = null; + methods[i] = null; failed++; } - scope.problemReporter().duplicateMethodInType(this, method2.sourceMethod()); - method2.sourceMethod().binding = null; - methods[i] = null; - failed++; } } - } - if (method.returnType == null && methodDecl == null) { // forget method with invalid return type... was kept to detect possible collisions - method.sourceMethod().binding = null; - methods[m] = null; - failed++; + if (method.returnType == null && methodDecl == null) { // forget + // method + // with + // invalid + // return + // type... + // was + // kept + // to + // detect + // possible + // collisions + method.sourceMethod().binding = null; + methods[m] = null; + failed++; + } } } - } - if (failed > 0) { - int newSize = methods.length - failed; - if (newSize == 0) { - methods = NoMethods; - } else { - MethodBinding[] newMethods = new MethodBinding[newSize]; - for (int m = 0, n = 0, max = methods.length; m < max; m++) - if (methods[m] != null) - newMethods[n++] = methods[m]; - methods = newMethods; + if (failed > 0) { + int newSize = methods.length - failed; + if (newSize == 0) { + methods = NoMethods; + } else { + MethodBinding[] newMethods = new MethodBinding[newSize]; + for (int m = 0, n = 0, max = methods.length; m < max; m++) + if (methods[m] != null) + newMethods[n++] = methods[m]; + methods = newMethods; + } } - } - // handle forward references to potential default abstract methods - addDefaultAbstractMethods(); - } catch(AbortCompilation e){ - // ensure null methods are removed - MethodBinding[] newMethods = null; - int count = 0; - for (int i = 0, max = methods.length; i < max; i++){ - MethodBinding method = methods[i]; - if (method == null && newMethods == null){ - System.arraycopy(methods, 0, newMethods = new MethodBinding[max], 0, i); - } else if (newMethods != null && method != null) { - newMethods[count++] = method; + // handle forward references to potential default abstract methods + addDefaultAbstractMethods(); + } catch (AbortCompilation e) { + // ensure null methods are removed + MethodBinding[] newMethods = null; + int count = 0; + for (int i = 0, max = methods.length; i < max; i++) { + MethodBinding method = methods[i]; + if (method == null && newMethods == null) { + System.arraycopy(methods, 0, + newMethods = new MethodBinding[max], 0, i); + } else if (newMethods != null && method != null) { + newMethods[count++] = method; + } } - } - if (newMethods != null){ - System.arraycopy(newMethods, 0, methods = new MethodBinding[count], 0, count); + if (newMethods != null) { + System.arraycopy(newMethods, 0, + methods = new MethodBinding[count], 0, count); + } + modifiers ^= AccUnresolved; + throw e; } modifiers ^= AccUnresolved; - throw e; + return methods; } - modifiers ^= AccUnresolved; - return methods; -} -private FieldBinding resolveTypeFor(FieldBinding field) { - if (field.type != null) - return field; - - FieldDeclaration[] fieldDecls = scope.referenceContext.fields; - for (int f = 0, length = fieldDecls.length; f < length; f++) { - if (fieldDecls[f].binding != field) - continue; - - field.type = fieldDecls[f].getTypeBinding(scope); - if (!field.type.isValidBinding()) { - scope.problemReporter().fieldTypeProblem(this, fieldDecls[f], field.type); - //scope.problemReporter().invalidType(fieldDecls[f].type, field.type); - fieldDecls[f].binding = null; - return null; - } - if (field.type == VoidBinding) { - scope.problemReporter().variableTypeCannotBeVoid(fieldDecls[f]); - fieldDecls[f].binding = null; - return null; - } - if (field.type.isArrayType() && ((ArrayBinding) field.type).leafComponentType == VoidBinding) { - scope.problemReporter().variableTypeCannotBeVoidArray(fieldDecls[f]); - fieldDecls[f].binding = null; - return null; - } - return field; - } - return null; // should never reach this point -} -private MethodBinding resolveTypesFor(MethodBinding method) { - if ((method.modifiers & AccUnresolved) == 0) - return method; - AbstractMethodDeclaration methodDecl = method.sourceMethod(); - TypeReference[] exceptionTypes = methodDecl.thrownExceptions; - if (exceptionTypes != null) { - int size = exceptionTypes.length; - method.thrownExceptions = new ReferenceBinding[size]; - ReferenceBinding throwable = scope.getJavaLangThrowable(); - int count = 0; - ReferenceBinding resolvedExceptionType; - for (int i = 0; i < size; i++) { - resolvedExceptionType = (ReferenceBinding) exceptionTypes[i].getTypeBinding(scope); - if (!resolvedExceptionType.isValidBinding()) { - methodDecl.scope.problemReporter().exceptionTypeProblem(this, methodDecl, exceptionTypes[i], resolvedExceptionType); - //methodDecl.scope.problemReporter().invalidType(exceptionTypes[i], resolvedExceptionType); + private FieldBinding resolveTypeFor(FieldBinding field) { + if (field.type != null) + return field; + + FieldDeclaration[] fieldDecls = scope.referenceContext.fields; + for (int f = 0, length = fieldDecls.length; f < length; f++) { + if (fieldDecls[f].binding != field) continue; + + field.type = fieldDecls[f].getTypeBinding(scope); + if (!field.type.isValidBinding()) { + scope.problemReporter().fieldTypeProblem(this, fieldDecls[f], + field.type); + // scope.problemReporter().invalidType(fieldDecls[f].type, + // field.type); + fieldDecls[f].binding = null; + return null; } - if (throwable != resolvedExceptionType && !throwable.isSuperclassOf(resolvedExceptionType)) { - methodDecl.scope.problemReporter().cannotThrowType(this, methodDecl, exceptionTypes[i], resolvedExceptionType); - continue; + if (field.type == VoidBinding) { + scope.problemReporter().variableTypeCannotBeVoid(fieldDecls[f]); + fieldDecls[f].binding = null; + return null; + } + if (field.type.isArrayType() + && ((ArrayBinding) field.type).leafComponentType == VoidBinding) { + scope.problemReporter().variableTypeCannotBeVoidArray( + fieldDecls[f]); + fieldDecls[f].binding = null; + return null; } - method.thrownExceptions[count++] = resolvedExceptionType; + return field; } - if (count < size) - System.arraycopy(method.thrownExceptions, 0, method.thrownExceptions = new ReferenceBinding[count], 0, count); + return null; // should never reach this point } - boolean foundArgProblem = false; - Argument[] arguments = methodDecl.arguments; - if (arguments != null) { - int size = arguments.length; - method.parameters = new TypeBinding[size]; - for (int i = 0; i < size; i++) { - Argument arg = arguments[i]; - method.parameters[i] = arg.type.getTypeBinding(scope); - if (!method.parameters[i].isValidBinding()) { - methodDecl.scope.problemReporter().argumentTypeProblem(this, methodDecl, arg, method.parameters[i]); - //methodDecl.scope.problemReporter().invalidType(arg, method.parameters[i]); - foundArgProblem = true; - } else if (method.parameters[i] == VoidBinding) { - methodDecl.scope.problemReporter().argumentTypeCannotBeVoid(this, methodDecl, arg); - foundArgProblem = true; - } else if (method.parameters[i].isArrayType() && ((ArrayBinding) method.parameters[i]).leafComponentType == VoidBinding) { - methodDecl.scope.problemReporter().argumentTypeCannotBeVoidArray(this, methodDecl, arg); - foundArgProblem = true; + private MethodBinding resolveTypesFor(MethodBinding method) { + if ((method.modifiers & AccUnresolved) == 0) + return method; + + AbstractMethodDeclaration methodDecl = method.sourceMethod(); + TypeReference[] exceptionTypes = methodDecl.thrownExceptions; + if (exceptionTypes != null) { + int size = exceptionTypes.length; + method.thrownExceptions = new ReferenceBinding[size]; + ReferenceBinding throwable = scope.getJavaLangThrowable(); + int count = 0; + ReferenceBinding resolvedExceptionType; + for (int i = 0; i < size; i++) { + resolvedExceptionType = (ReferenceBinding) exceptionTypes[i] + .getTypeBinding(scope); + if (!resolvedExceptionType.isValidBinding()) { + methodDecl.scope.problemReporter().exceptionTypeProblem( + this, methodDecl, exceptionTypes[i], + resolvedExceptionType); + // methodDecl.scope.problemReporter().invalidType(exceptionTypes[i], + // resolvedExceptionType); + continue; + } + if (throwable != resolvedExceptionType + && !throwable.isSuperclassOf(resolvedExceptionType)) { + methodDecl.scope.problemReporter().cannotThrowType(this, + methodDecl, exceptionTypes[i], + resolvedExceptionType); + continue; + } + method.thrownExceptions[count++] = resolvedExceptionType; } + if (count < size) + System.arraycopy(method.thrownExceptions, 0, + method.thrownExceptions = new ReferenceBinding[count], + 0, count); } - } - boolean foundReturnTypeProblem = false; - if (!method.isConstructor()) { - TypeReference returnType = ((MethodDeclaration) methodDecl).returnType; - if (returnType == null) { - methodDecl.scope.problemReporter().missingReturnType(methodDecl); - method.returnType = null; - foundReturnTypeProblem = true; - } else { - method.returnType = returnType.getTypeBinding(scope); - if (!method.returnType.isValidBinding()) { - methodDecl.scope.problemReporter().returnTypeProblem(this, (MethodDeclaration) methodDecl, method.returnType); - //methodDecl.scope.problemReporter().invalidType(returnType, method.returnType); - method.returnType = null; - foundReturnTypeProblem = true; - } else if (method.returnType.isArrayType() && ((ArrayBinding) method.returnType).leafComponentType == VoidBinding) { - methodDecl.scope.problemReporter().returnTypeCannotBeVoidArray(this, (MethodDeclaration) methodDecl); + boolean foundArgProblem = false; + Argument[] arguments = methodDecl.arguments; + if (arguments != null) { + int size = arguments.length; + method.parameters = new TypeBinding[size]; + for (int i = 0; i < size; i++) { + Argument arg = arguments[i]; + method.parameters[i] = arg.type.getTypeBinding(scope); + if (!method.parameters[i].isValidBinding()) { + methodDecl.scope.problemReporter().argumentTypeProblem( + this, methodDecl, arg, method.parameters[i]); + // methodDecl.scope.problemReporter().invalidType(arg, + // method.parameters[i]); + foundArgProblem = true; + } else if (method.parameters[i] == VoidBinding) { + methodDecl.scope.problemReporter() + .argumentTypeCannotBeVoid(this, methodDecl, arg); + foundArgProblem = true; + } else if (method.parameters[i].isArrayType() + && ((ArrayBinding) method.parameters[i]).leafComponentType == VoidBinding) { + methodDecl.scope.problemReporter() + .argumentTypeCannotBeVoidArray(this, methodDecl, + arg); + foundArgProblem = true; + } + } + } + + boolean foundReturnTypeProblem = false; + if (!method.isConstructor()) { + TypeReference returnType = ((MethodDeclaration) methodDecl).returnType; + if (returnType == null) { + methodDecl.scope.problemReporter() + .missingReturnType(methodDecl); method.returnType = null; foundReturnTypeProblem = true; + } else { + method.returnType = returnType.getTypeBinding(scope); + if (!method.returnType.isValidBinding()) { + methodDecl.scope.problemReporter().returnTypeProblem(this, + (MethodDeclaration) methodDecl, method.returnType); + // methodDecl.scope.problemReporter().invalidType(returnType, + // method.returnType); + method.returnType = null; + foundReturnTypeProblem = true; + } else if (method.returnType.isArrayType() + && ((ArrayBinding) method.returnType).leafComponentType == VoidBinding) { + methodDecl.scope.problemReporter() + .returnTypeCannotBeVoidArray(this, + (MethodDeclaration) methodDecl); + method.returnType = null; + foundReturnTypeProblem = true; + } } } + if (foundArgProblem) { + methodDecl.binding = null; + return null; + } + if (foundReturnTypeProblem) + return method; // but its still unresolved with a null return type + // & is still connected to its method declaration + + method.modifiers ^= AccUnresolved; + return method; } - if (foundArgProblem) { - methodDecl.binding = null; - return null; + + public final int sourceEnd() { + return scope.referenceContext.sourceEnd; } - if (foundReturnTypeProblem) - return method; // but its still unresolved with a null return type & is still connected to its method declaration - method.modifiers ^= AccUnresolved; - return method; -} -public final int sourceEnd() { - return scope.referenceContext.sourceEnd; -} -public final int sourceStart() { - return scope.referenceContext.sourceStart; -} -public ReferenceBinding superclass() { - return superclass; -} -public ReferenceBinding[] superInterfaces() { - return superInterfaces; -} -public SyntheticAccessMethodBinding[] syntheticAccessMethods() { + public final int sourceStart() { + return scope.referenceContext.sourceStart; + } + + public ReferenceBinding superclass() { + return superclass; + } - if (synthetics == null || synthetics[METHOD] == null || synthetics[METHOD].size() == 0) return null; + public ReferenceBinding[] superInterfaces() { + return superInterfaces; + } - // difficult to compute size up front because of the embedded arrays so assume there is only 1 - int index = 0; - SyntheticAccessMethodBinding[] bindings = new SyntheticAccessMethodBinding[1]; - Enumeration fieldsOrMethods = synthetics[METHOD].keys(); - while (fieldsOrMethods.hasMoreElements()) { + public SyntheticAccessMethodBinding[] syntheticAccessMethods() { - Object fieldOrMethod = fieldsOrMethods.nextElement(); + if (synthetics == null || synthetics[METHOD] == null + || synthetics[METHOD].size() == 0) + return null; - if (fieldOrMethod instanceof MethodBinding) { + // difficult to compute size up front because of the embedded arrays so + // assume there is only 1 + int index = 0; + SyntheticAccessMethodBinding[] bindings = new SyntheticAccessMethodBinding[1]; + Enumeration fieldsOrMethods = synthetics[METHOD].keys(); + while (fieldsOrMethods.hasMoreElements()) { + + Object fieldOrMethod = fieldsOrMethods.nextElement(); + + if (fieldOrMethod instanceof MethodBinding) { + + SyntheticAccessMethodBinding[] methodAccessors = (SyntheticAccessMethodBinding[]) synthetics[METHOD] + .get(fieldOrMethod); + int numberOfAccessors = 0; + if (methodAccessors[0] != null) + numberOfAccessors++; + if (methodAccessors[1] != null) + numberOfAccessors++; + if (index + numberOfAccessors > bindings.length) + System.arraycopy(bindings, 0, + (bindings = new SyntheticAccessMethodBinding[index + + numberOfAccessors]), 0, index); + if (methodAccessors[0] != null) + bindings[index++] = methodAccessors[0]; // super access + if (methodAccessors[1] != null) + bindings[index++] = methodAccessors[1]; // normal access - SyntheticAccessMethodBinding[] methodAccessors = (SyntheticAccessMethodBinding[]) synthetics[METHOD].get(fieldOrMethod); - int numberOfAccessors = 0; - if (methodAccessors[0] != null) numberOfAccessors++; - if (methodAccessors[1] != null) numberOfAccessors++; - if (index + numberOfAccessors > bindings.length) - System.arraycopy(bindings, 0, (bindings = new SyntheticAccessMethodBinding[index + numberOfAccessors]), 0, index); - if (methodAccessors[0] != null) - bindings[index++] = methodAccessors[0]; // super access - if (methodAccessors[1] != null) - bindings[index++] = methodAccessors[1]; // normal access + } else { - } else { + SyntheticAccessMethodBinding[] fieldAccessors = (SyntheticAccessMethodBinding[]) synthetics[METHOD] + .get(fieldOrMethod); + int numberOfAccessors = 0; + if (fieldAccessors[0] != null) + numberOfAccessors++; + if (fieldAccessors[1] != null) + numberOfAccessors++; + if (index + numberOfAccessors > bindings.length) + System.arraycopy(bindings, 0, + (bindings = new SyntheticAccessMethodBinding[index + + numberOfAccessors]), 0, index); + if (fieldAccessors[0] != null) + bindings[index++] = fieldAccessors[0]; // read access + if (fieldAccessors[1] != null) + bindings[index++] = fieldAccessors[1]; // write access + } + } - SyntheticAccessMethodBinding[] fieldAccessors = (SyntheticAccessMethodBinding[]) synthetics[METHOD].get(fieldOrMethod); - int numberOfAccessors = 0; - if (fieldAccessors[0] != null) numberOfAccessors++; - if (fieldAccessors[1] != null) numberOfAccessors++; - if (index + numberOfAccessors > bindings.length) - System.arraycopy(bindings, 0, (bindings = new SyntheticAccessMethodBinding[index + numberOfAccessors]), 0, index); - if (fieldAccessors[0] != null) - bindings[index++] = fieldAccessors[0]; // read access - if (fieldAccessors[1] != null) - bindings[index++] = fieldAccessors[1]; // write access + // sort them in according to their own indexes + int length; + SyntheticAccessMethodBinding[] sortedBindings = new SyntheticAccessMethodBinding[length = bindings.length]; + for (int i = 0; i < length; i++) { + SyntheticAccessMethodBinding binding = bindings[i]; + sortedBindings[binding.index] = binding; } + return sortedBindings; } - // sort them in according to their own indexes - int length; - SyntheticAccessMethodBinding[] sortedBindings = new SyntheticAccessMethodBinding[length = bindings.length]; - for (int i = 0; i < length; i++){ - SyntheticAccessMethodBinding binding = bindings[i]; - sortedBindings[binding.index] = binding; - } - return sortedBindings; -} -/** - * Answer the collection of synthetic fields to append into the classfile - */ -public FieldBinding[] syntheticFields() { - - if (synthetics == null) return null; - - int fieldSize = synthetics[FIELD] == null ? 0 : synthetics[FIELD].size(); - int literalSize = synthetics[CLASS_LITERAL] == null ? 0 :synthetics[CLASS_LITERAL].size(); - int totalSize = fieldSize + literalSize; - if (totalSize == 0) return null; - FieldBinding[] bindings = new FieldBinding[totalSize]; - - // add innerclass synthetics - if (synthetics[FIELD] != null){ - Enumeration elements = synthetics[FIELD].elements(); - for (int i = 0; i < fieldSize; i++) { - SyntheticFieldBinding synthBinding = (SyntheticFieldBinding) elements.nextElement(); - bindings[synthBinding.index] = synthBinding; + /** + * Answer the collection of synthetic fields to append into the classfile + */ + public FieldBinding[] syntheticFields() { + + if (synthetics == null) + return null; + + int fieldSize = synthetics[FIELD] == null ? 0 : synthetics[FIELD] + .size(); + int literalSize = synthetics[CLASS_LITERAL] == null ? 0 + : synthetics[CLASS_LITERAL].size(); + int totalSize = fieldSize + literalSize; + if (totalSize == 0) + return null; + FieldBinding[] bindings = new FieldBinding[totalSize]; + + // add innerclass synthetics + if (synthetics[FIELD] != null) { + Enumeration elements = synthetics[FIELD].elements(); + for (int i = 0; i < fieldSize; i++) { + SyntheticFieldBinding synthBinding = (SyntheticFieldBinding) elements + .nextElement(); + bindings[synthBinding.index] = synthBinding; + } } - } - // add class literal synthetics - if (synthetics[CLASS_LITERAL] != null){ - Enumeration elements = synthetics[CLASS_LITERAL].elements(); - for (int i = 0; i < literalSize; i++) { - SyntheticFieldBinding synthBinding = (SyntheticFieldBinding) elements.nextElement(); - bindings[fieldSize+synthBinding.index] = synthBinding; + // add class literal synthetics + if (synthetics[CLASS_LITERAL] != null) { + Enumeration elements = synthetics[CLASS_LITERAL].elements(); + for (int i = 0; i < literalSize; i++) { + SyntheticFieldBinding synthBinding = (SyntheticFieldBinding) elements + .nextElement(); + bindings[fieldSize + synthBinding.index] = synthBinding; + } } + return bindings; } - return bindings; -} -public String toString() { - String s = "(id="+(id == NoId ? "NoId" : (""+id) ) +")\n"; //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-4$ //$NON-NLS-1$ - - if (isDeprecated()) s += "deprecated "; //$NON-NLS-1$ - if (isPublic()) s += "public "; //$NON-NLS-1$ - if (isProtected()) s += "protected "; //$NON-NLS-1$ - if (isPrivate()) s += "private "; //$NON-NLS-1$ - if (isAbstract() && isClass()) s += "abstract "; //$NON-NLS-1$ - if (isStatic() && isNestedType()) s += "static "; //$NON-NLS-1$ - if (isFinal()) s += "final "; //$NON-NLS-1$ - - s += isInterface() ? "interface " : "class "; //$NON-NLS-1$ //$NON-NLS-2$ - s += (compoundName != null) ? CharOperation.toString(compoundName) : "UNNAMED TYPE"; //$NON-NLS-1$ - - s += "\n\textends "; //$NON-NLS-1$ - s += (superclass != null) ? superclass.debugName() : "NULL TYPE"; //$NON-NLS-1$ - - if (superInterfaces != null) { - if (superInterfaces != NoSuperInterfaces) { - s += "\n\timplements : "; //$NON-NLS-1$ - for (int i = 0, length = superInterfaces.length; i < length; i++) { - if (i > 0) - s += ", "; //$NON-NLS-1$ - s += (superInterfaces[i] != null) ? superInterfaces[i].debugName() : "NULL TYPE"; //$NON-NLS-1$ + + public String toString() { + String s = "(id=" + (id == NoId ? "NoId" : ("" + id)) + ")\n"; //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-4$ //$NON-NLS-1$ + + if (isDeprecated()) + s += "deprecated "; //$NON-NLS-1$ + if (isPublic()) + s += "public "; //$NON-NLS-1$ + if (isProtected()) + s += "protected "; //$NON-NLS-1$ + if (isPrivate()) + s += "private "; //$NON-NLS-1$ + if (isAbstract() && isClass()) + s += "abstract "; //$NON-NLS-1$ + if (isStatic() && isNestedType()) + s += "static "; //$NON-NLS-1$ + if (isFinal()) + s += "final "; //$NON-NLS-1$ + + s += isInterface() ? "interface " : "class "; //$NON-NLS-1$ //$NON-NLS-2$ + s += (compoundName != null) ? CharOperation.toString(compoundName) + : "UNNAMED TYPE"; //$NON-NLS-1$ + + s += "\n\textends "; //$NON-NLS-1$ + s += (superclass != null) ? superclass.debugName() : "NULL TYPE"; //$NON-NLS-1$ + + if (superInterfaces != null) { + if (superInterfaces != NoSuperInterfaces) { + s += "\n\timplements : "; //$NON-NLS-1$ + for (int i = 0, length = superInterfaces.length; i < length; i++) { + if (i > 0) + s += ", "; //$NON-NLS-1$ + s += (superInterfaces[i] != null) ? superInterfaces[i] + .debugName() : "NULL TYPE"; //$NON-NLS-1$ + } } + } else { + s += "NULL SUPERINTERFACES"; //$NON-NLS-1$ } - } else { - s += "NULL SUPERINTERFACES"; //$NON-NLS-1$ - } - if (enclosingType() != null) { - s += "\n\tenclosing type : "; //$NON-NLS-1$ - s += enclosingType().debugName(); - } + if (enclosingType() != null) { + s += "\n\tenclosing type : "; //$NON-NLS-1$ + s += enclosingType().debugName(); + } - if (fields != null) { - if (fields != NoFields) { - s += "\n/* fields */"; //$NON-NLS-1$ - for (int i = 0, length = fields.length; i < length; i++) - s += (fields[i] != null) ? "\n" + fields[i].toString() : "\nNULL FIELD"; //$NON-NLS-1$ //$NON-NLS-2$ + if (fields != null) { + if (fields != NoFields) { + s += "\n/* fields */"; //$NON-NLS-1$ + for (int i = 0, length = fields.length; i < length; i++) + s += (fields[i] != null) ? "\n" + fields[i].toString() : "\nNULL FIELD"; //$NON-NLS-1$ //$NON-NLS-2$ + } + } else { + s += "NULL FIELDS"; //$NON-NLS-1$ } - } else { - s += "NULL FIELDS"; //$NON-NLS-1$ - } - if (methods != null) { - if (methods != NoMethods) { - s += "\n/* methods */"; //$NON-NLS-1$ - for (int i = 0, length = methods.length; i < length; i++) - s += (methods[i] != null) ? "\n" + methods[i].toString() : "\nNULL METHOD"; //$NON-NLS-1$ //$NON-NLS-2$ + if (methods != null) { + if (methods != NoMethods) { + s += "\n/* methods */"; //$NON-NLS-1$ + for (int i = 0, length = methods.length; i < length; i++) + s += (methods[i] != null) ? "\n" + methods[i].toString() : "\nNULL METHOD"; //$NON-NLS-1$ //$NON-NLS-2$ + } + } else { + s += "NULL METHODS"; //$NON-NLS-1$ } - } else { - s += "NULL METHODS"; //$NON-NLS-1$ - } - if (memberTypes != null) { - if (memberTypes != NoMemberTypes) { - s += "\n/* members */"; //$NON-NLS-1$ - for (int i = 0, length = memberTypes.length; i < length; i++) - s += (memberTypes[i] != null) ? "\n" + memberTypes[i].toString() : "\nNULL TYPE"; //$NON-NLS-1$ //$NON-NLS-2$ + if (memberTypes != null) { + if (memberTypes != NoMemberTypes) { + s += "\n/* members */"; //$NON-NLS-1$ + for (int i = 0, length = memberTypes.length; i < length; i++) + s += (memberTypes[i] != null) ? "\n" + memberTypes[i].toString() : "\nNULL TYPE"; //$NON-NLS-1$ //$NON-NLS-2$ + } + } else { + s += "NULL MEMBER TYPES"; //$NON-NLS-1$ } - } else { - s += "NULL MEMBER TYPES"; //$NON-NLS-1$ + + s += "\n\n\n"; //$NON-NLS-1$ + return s; } - s += "\n\n\n"; //$NON-NLS-1$ - return s; -} -void verifyMethods(MethodVerifier verifier) { - verifier.verify(this); + void verifyMethods(MethodVerifier verifier) { + verifier.verify(this); - for (int i = memberTypes.length; --i >= 0;) - ((SourceTypeBinding) memberTypes[i]).verifyMethods(verifier); -} + for (int i = memberTypes.length; --i >= 0;) + ((SourceTypeBinding) memberTypes[i]).verifyMethods(verifier); + } + + /* + * Answer the synthetic field for or null if one does + * not exist. + */ -/* Answer the synthetic field for -* or null if one does not exist. -*/ - -public FieldBinding getSyntheticField(ReferenceBinding targetEnclosingType, boolean onlyExactMatch) { - - if (synthetics == null || synthetics[FIELD] == null) return null; - FieldBinding field = (FieldBinding) synthetics[FIELD].get(targetEnclosingType); - if (field != null) return field; - - // type compatibility : to handle cases such as - // class T { class M{}} - // class S extends T { class N extends M {}} --> need to use S as a default enclosing instance for the super constructor call in N(). - if (!onlyExactMatch){ - Enumeration e = synthetics[FIELD].elements(); - while (e.hasMoreElements()) { - field = (FieldBinding) e.nextElement(); - if (CharOperation.prefixEquals(SyntheticArgumentBinding.EnclosingInstancePrefix, field.name) - && targetEnclosingType.isSuperclassOf((ReferenceBinding) field.type)) + public FieldBinding getSyntheticField(ReferenceBinding targetEnclosingType, + boolean onlyExactMatch) { + + if (synthetics == null || synthetics[FIELD] == null) + return null; + FieldBinding field = (FieldBinding) synthetics[FIELD] + .get(targetEnclosingType); + if (field != null) + return field; + + // type compatibility : to handle cases such as + // class T { class M{}} + // class S extends T { class N extends M {}} --> need to use S as a + // default enclosing instance for the super constructor call in N(). + if (!onlyExactMatch) { + Enumeration e = synthetics[FIELD].elements(); + while (e.hasMoreElements()) { + field = (FieldBinding) e.nextElement(); + if (CharOperation.prefixEquals( + SyntheticArgumentBinding.EnclosingInstancePrefix, + field.name) + && targetEnclosingType + .isSuperclassOf((ReferenceBinding) field.type)) return field; + } } + return null; } - return null; -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/SyntheticAccessMethodBinding.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/SyntheticAccessMethodBinding.java index 852739a..3e2ea6f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/SyntheticAccessMethodBinding.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/SyntheticAccessMethodBinding.java @@ -16,31 +16,43 @@ import net.sourceforge.phpdt.internal.compiler.ast.FieldDeclaration; public class SyntheticAccessMethodBinding extends MethodBinding { - public FieldBinding targetReadField; // read access to a field - public FieldBinding targetWriteField; // write access to a field - public MethodBinding targetMethod; // method or constructor - + public FieldBinding targetReadField; // read access to a field + + public FieldBinding targetWriteField; // write access to a field + + public MethodBinding targetMethod; // method or constructor + public int accessType; - public final static int FieldReadAccess = 1; // field read - public final static int FieldWriteAccess = 2; // field write - public final static int MethodAccess = 3; // normal method - public final static int ConstructorAccess = 4; // constructor + public final static int FieldReadAccess = 1; // field read + + public final static int FieldWriteAccess = 2; // field write + + public final static int MethodAccess = 3; // normal method + + public final static int ConstructorAccess = 4; // constructor + public final static int SuperMethodAccess = 5; // super method - final static char[] AccessMethodPrefix = { 'a', 'c', 'c', 'e', 's', 's', '$' }; + final static char[] AccessMethodPrefix = { 'a', 'c', 'c', 'e', 's', 's', + '$' }; public int sourceStart = 0; // start position of the matching declaration + public int index; // used for sorting access methods in the class file - - public SyntheticAccessMethodBinding(FieldBinding targetField, boolean isReadAccess, ReferenceBinding declaringClass) { + + public SyntheticAccessMethodBinding(FieldBinding targetField, + boolean isReadAccess, ReferenceBinding declaringClass) { this.modifiers = AccDefault | AccStatic;// | AccSynthetic; SourceTypeBinding declaringSourceType = (SourceTypeBinding) declaringClass; - SyntheticAccessMethodBinding[] knownAccessMethods = declaringSourceType.syntheticAccessMethods(); - int methodId = knownAccessMethods == null ? 0 : knownAccessMethods.length; + SyntheticAccessMethodBinding[] knownAccessMethods = declaringSourceType + .syntheticAccessMethods(); + int methodId = knownAccessMethods == null ? 0 + : knownAccessMethods.length; this.index = methodId; - this.selector = CharOperation.concat(AccessMethodPrefix, String.valueOf(methodId).toCharArray()); + this.selector = CharOperation.concat(AccessMethodPrefix, String + .valueOf(methodId).toCharArray()); if (isReadAccess) { this.returnType = targetField.type; if (targetField.isStatic()) { @@ -66,16 +78,17 @@ public class SyntheticAccessMethodBinding extends MethodBinding { } this.thrownExceptions = NoExceptions; this.declaringClass = declaringSourceType; - + // check for method collision boolean needRename; do { - check : { + check: { needRename = false; // check for collision with known methods MethodBinding[] methods = declaringSourceType.methods; for (int i = 0, length = methods.length; i < length; i++) { - if (this.selector == methods[i].selector && this.areParametersEqual(methods[i])) { + if (this.selector == methods[i].selector + && this.areParametersEqual(methods[i])) { needRename = true; break check; } @@ -83,20 +96,25 @@ public class SyntheticAccessMethodBinding extends MethodBinding { // check for collision with synthetic accessors if (knownAccessMethods != null) { for (int i = 0, length = knownAccessMethods.length; i < length; i++) { - if (knownAccessMethods[i] == null) continue; - if (this.selector == knownAccessMethods[i].selector && this.areParametersEqual(methods[i])) { + if (knownAccessMethods[i] == null) + continue; + if (this.selector == knownAccessMethods[i].selector + && this.areParametersEqual(methods[i])) { needRename = true; break check; } } } } - if (needRename) { // retry with a selector postfixed by a growing methodId - this.selector(CharOperation.concat(AccessMethodPrefix, String.valueOf(++methodId).toCharArray())); + if (needRename) { // retry with a selector postfixed by a growing + // methodId + this.selector(CharOperation.concat(AccessMethodPrefix, String + .valueOf(++methodId).toCharArray())); } } while (needRename); - - // retrieve sourceStart position for the target field for line number attributes + + // retrieve sourceStart position for the target field for line number + // attributes FieldDeclaration[] fieldDecls = declaringSourceType.scope.referenceContext.fields; if (fieldDecls != null) { for (int i = 0, max = fieldDecls.length; i < max; i++) { @@ -106,73 +124,71 @@ public class SyntheticAccessMethodBinding extends MethodBinding { } } } - - /* did not find the target field declaration - it is a synthetic one - public class A { - public class B { - public class C { - void foo() { - System.out.println("A.this = " + A.this); - } - } - } - public static void main(String args[]) { - new A().new B().new C().foo(); - } - } - */ - // We now at this point - per construction - it is for sure an enclosing instance, we are going to + + /* + * did not find the target field declaration - it is a synthetic one + * public class A { public class B { public class C { void foo() { + * System.out.println("A.this = " + A.this); } } } public static void + * main(String args[]) { new A().new B().new C().foo(); } } + */ + // We now at this point - per construction - it is for sure an enclosing + // instance, we are going to // show the target field type declaration location. - this.sourceStart = declaringSourceType.scope.referenceContext.sourceStart; // use the target declaring class name position instead + this.sourceStart = declaringSourceType.scope.referenceContext.sourceStart; // use + // the + // target + // declaring + // class + // name + // position + // instead } - public SyntheticAccessMethodBinding(MethodBinding targetMethod, boolean isSuperAccess, ReferenceBinding receiverType) { - + public SyntheticAccessMethodBinding(MethodBinding targetMethod, + boolean isSuperAccess, ReferenceBinding receiverType) { + if (targetMethod.isConstructor()) { this.initializeConstructorAccessor(targetMethod); } else { - this.initializeMethodAccessor(targetMethod, isSuperAccess, receiverType); + this.initializeMethodAccessor(targetMethod, isSuperAccess, + receiverType); } } /** - * An constructor accessor is a constructor with an extra argument (declaringClass), in case of - * collision with an existing constructor, then add again an extra argument (declaringClass again). + * An constructor accessor is a constructor with an extra argument + * (declaringClass), in case of collision with an existing constructor, then + * add again an extra argument (declaringClass again). */ - public void initializeConstructorAccessor(MethodBinding targetConstructor) { - + public void initializeConstructorAccessor(MethodBinding targetConstructor) { + this.targetMethod = targetConstructor; this.modifiers = AccDefault;// | AccSynthetic; - SourceTypeBinding sourceType = (SourceTypeBinding) targetConstructor.declaringClass; - SyntheticAccessMethodBinding[] knownAccessMethods = - sourceType.syntheticAccessMethods(); + SourceTypeBinding sourceType = (SourceTypeBinding) targetConstructor.declaringClass; + SyntheticAccessMethodBinding[] knownAccessMethods = sourceType + .syntheticAccessMethods(); this.index = knownAccessMethods == null ? 0 : knownAccessMethods.length; - + this.selector = targetConstructor.selector; this.returnType = targetConstructor.returnType; this.accessType = ConstructorAccess; this.parameters = new TypeBinding[targetConstructor.parameters.length + 1]; - System.arraycopy( - targetConstructor.parameters, - 0, - this.parameters, - 0, - targetConstructor.parameters.length); - parameters[targetConstructor.parameters.length] = - targetConstructor.declaringClass; + System.arraycopy(targetConstructor.parameters, 0, this.parameters, 0, + targetConstructor.parameters.length); + parameters[targetConstructor.parameters.length] = targetConstructor.declaringClass; this.thrownExceptions = targetConstructor.thrownExceptions; this.declaringClass = sourceType; - + // check for method collision boolean needRename; do { - check : { + check: { needRename = false; // check for collision with known methods MethodBinding[] methods = sourceType.methods; for (int i = 0, length = methods.length; i < length; i++) { if (this.selector == methods[i].selector - && this.areParametersEqual(methods[i])) { + && this.areParametersEqual(methods[i])) { needRename = true; break check; } @@ -183,7 +199,8 @@ public class SyntheticAccessMethodBinding extends MethodBinding { if (knownAccessMethods[i] == null) continue; if (this.selector == knownAccessMethods[i].selector - && this.areParametersEqual(knownAccessMethods[i])) { + && this + .areParametersEqual(knownAccessMethods[i])) { needRename = true; break check; } @@ -192,19 +209,16 @@ public class SyntheticAccessMethodBinding extends MethodBinding { } if (needRename) { // retry with a new extra argument int length = this.parameters.length; - System.arraycopy( - this.parameters, - 0, - this.parameters = new TypeBinding[length + 1], - 0, - length); + System.arraycopy(this.parameters, 0, + this.parameters = new TypeBinding[length + 1], 0, + length); this.parameters[length] = this.declaringClass; } } while (needRename); - - // retrieve sourceStart position for the target method for line number attributes - AbstractMethodDeclaration[] methodDecls = - sourceType.scope.referenceContext.methods; + + // retrieve sourceStart position for the target method for line number + // attributes + AbstractMethodDeclaration[] methodDecls = sourceType.scope.referenceContext.methods; if (methodDecls != null) { for (int i = 0, length = methodDecls.length; i < length; i++) { if (methodDecls[i].binding == targetConstructor) { @@ -216,40 +230,47 @@ public class SyntheticAccessMethodBinding extends MethodBinding { } /** - * An method accessor is a method with an access$N selector, where N is incremented in case of collisions. + * An method accessor is a method with an access$N selector, where N is + * incremented in case of collisions. */ - public void initializeMethodAccessor(MethodBinding targetMethod, boolean isSuperAccess, ReferenceBinding declaringClass) { - + public void initializeMethodAccessor(MethodBinding targetMethod, + boolean isSuperAccess, ReferenceBinding declaringClass) { + this.targetMethod = targetMethod; this.modifiers = AccDefault | AccStatic;// | AccSynthetic; SourceTypeBinding declaringSourceType = (SourceTypeBinding) declaringClass; - SyntheticAccessMethodBinding[] knownAccessMethods = declaringSourceType.syntheticAccessMethods(); - int methodId = knownAccessMethods == null ? 0 : knownAccessMethods.length; + SyntheticAccessMethodBinding[] knownAccessMethods = declaringSourceType + .syntheticAccessMethods(); + int methodId = knownAccessMethods == null ? 0 + : knownAccessMethods.length; this.index = methodId; - - this.selector = CharOperation.concat(AccessMethodPrefix, String.valueOf(methodId).toCharArray()); + + this.selector = CharOperation.concat(AccessMethodPrefix, String + .valueOf(methodId).toCharArray()); this.returnType = targetMethod.returnType; this.accessType = isSuperAccess ? SuperMethodAccess : MethodAccess; - + if (targetMethod.isStatic()) { this.parameters = targetMethod.parameters; } else { this.parameters = new TypeBinding[targetMethod.parameters.length + 1]; this.parameters[0] = declaringSourceType; - System.arraycopy(targetMethod.parameters, 0, this.parameters, 1, targetMethod.parameters.length); + System.arraycopy(targetMethod.parameters, 0, this.parameters, 1, + targetMethod.parameters.length); } this.thrownExceptions = targetMethod.thrownExceptions; this.declaringClass = declaringSourceType; - + // check for method collision boolean needRename; do { - check : { + check: { needRename = false; // check for collision with known methods MethodBinding[] methods = declaringSourceType.methods; for (int i = 0, length = methods.length; i < length; i++) { - if (this.selector == methods[i].selector && this.areParametersEqual(methods[i])) { + if (this.selector == methods[i].selector + && this.areParametersEqual(methods[i])) { needRename = true; break check; } @@ -257,8 +278,11 @@ public class SyntheticAccessMethodBinding extends MethodBinding { // check for collision with synthetic accessors if (knownAccessMethods != null) { for (int i = 0, length = knownAccessMethods.length; i < length; i++) { - if (knownAccessMethods[i] == null) continue; - if (this.selector == knownAccessMethods[i].selector && this.areParametersEqual(knownAccessMethods[i])) { + if (knownAccessMethods[i] == null) + continue; + if (this.selector == knownAccessMethods[i].selector + && this + .areParametersEqual(knownAccessMethods[i])) { needRename = true; break check; } @@ -266,11 +290,13 @@ public class SyntheticAccessMethodBinding extends MethodBinding { } } if (needRename) { // retry with a selector & a growing methodId - this.selector(CharOperation.concat(AccessMethodPrefix, String.valueOf(++methodId).toCharArray())); + this.selector(CharOperation.concat(AccessMethodPrefix, String + .valueOf(++methodId).toCharArray())); } } while (needRename); - - // retrieve sourceStart position for the target method for line number attributes + + // retrieve sourceStart position for the target method for line number + // attributes AbstractMethodDeclaration[] methodDecls = declaringSourceType.scope.referenceContext.methods; if (methodDecls != null) { for (int i = 0, length = methodDecls.length; i < length; i++) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/SyntheticArgumentBinding.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/SyntheticArgumentBinding.java index 1afe5b8..0b51df0 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/SyntheticArgumentBinding.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/SyntheticArgumentBinding.java @@ -13,49 +13,48 @@ package net.sourceforge.phpdt.internal.compiler.lookup; import net.sourceforge.phpdt.core.compiler.CharOperation; /** - * Specific local variable location used to: - * - either provide emulation for outer local variables used from within innerclass constructs, - * - or provide emulation to enclosing instances. - * When it is mapping to an outer local variable, this actual outer local is accessible through - * the public field #actualOuterLocalVariable. - * - * Such a synthetic argument binding will be inserted in all constructors of local innertypes before - * the user arguments. + * Specific local variable location used to: - either provide emulation for + * outer local variables used from within innerclass constructs, - or provide + * emulation to enclosing instances. When it is mapping to an outer local + * variable, this actual outer local is accessible through the public field + * #actualOuterLocalVariable. + * + * Such a synthetic argument binding will be inserted in all constructors of + * local innertypes before the user arguments. */ public class SyntheticArgumentBinding extends LocalVariableBinding { - { + { this.isArgument = true; this.useFlag = USED; } - - // if the argument is mapping to an outer local variable, this denotes the outer actual variable + + // if the argument is mapping to an outer local variable, this denotes the + // outer actual variable public LocalVariableBinding actualOuterLocalVariable; + // if the argument has a matching synthetic field public FieldBinding matchingField; final static char[] OuterLocalPrefix = { 'v', 'a', 'l', '$' }; + final static char[] EnclosingInstancePrefix = { 't', 'h', 'i', 's', '$' }; - - public SyntheticArgumentBinding(LocalVariableBinding actualOuterLocalVariable) { - - super( - CharOperation.concat(OuterLocalPrefix, actualOuterLocalVariable.name), - actualOuterLocalVariable.type, - AccFinal, - true); + + public SyntheticArgumentBinding( + LocalVariableBinding actualOuterLocalVariable) { + + super(CharOperation.concat(OuterLocalPrefix, + actualOuterLocalVariable.name), actualOuterLocalVariable.type, + AccFinal, true); this.actualOuterLocalVariable = actualOuterLocalVariable; } public SyntheticArgumentBinding(ReferenceBinding enclosingType) { - super( - CharOperation.concat( - SyntheticArgumentBinding.EnclosingInstancePrefix, - String.valueOf(enclosingType.depth()).toCharArray()), - enclosingType, - AccFinal, - true); + super(CharOperation.concat( + SyntheticArgumentBinding.EnclosingInstancePrefix, String + .valueOf(enclosingType.depth()).toCharArray()), + enclosingType, AccFinal, true); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/SyntheticFieldBinding.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/SyntheticFieldBinding.java index 4206652..5468b8b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/SyntheticFieldBinding.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/SyntheticFieldBinding.java @@ -14,8 +14,10 @@ import net.sourceforge.phpdt.internal.compiler.impl.Constant; public class SyntheticFieldBinding extends FieldBinding { public int index; -public SyntheticFieldBinding(char[] name, TypeBinding type, int modifiers, ReferenceBinding declaringClass, Constant constant, int index) { - super(name, type, modifiers, declaringClass, constant); - this.index = index; -} + + public SyntheticFieldBinding(char[] name, TypeBinding type, int modifiers, + ReferenceBinding declaringClass, Constant constant, int index) { + super(name, type, modifiers, declaringClass, constant); + this.index = index; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/TagBits.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/TagBits.java index 5555c83..4dcb720 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/TagBits.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/TagBits.java @@ -13,18 +13,28 @@ package net.sourceforge.phpdt.internal.compiler.lookup; public interface TagBits { // Tag bits in the tagBits int of every TypeBinding final int IsArrayType = 0x0001; + final int IsBaseType = 0x0002; + final int IsNestedType = 0x0004; + final int IsMemberType = 0x0008; + final int MemberTypeMask = IsNestedType | IsMemberType; + final int IsLocalType = 0x0010; + final int LocalTypeMask = IsNestedType | IsLocalType; + final int IsAnonymousType = 0x0020; + final int AnonymousTypeMask = LocalTypeMask | IsAnonymousType; + final int IsBinaryBinding = 0x0040; // for the type hierarchy check used by ClassScope final int BeginHierarchyCheck = 0x0100; + final int EndHierarchyCheck = 0x0200; // test bit to see if default abstract methods were computed @@ -35,9 +45,11 @@ public interface TagBits { // test bits to see if parts of binary types are faulted final int AreFieldsComplete = 0x1000; + final int AreMethodsComplete = 0x2000; - // test bit to avoid asking a type for a member type (includes inherited member types) + // test bit to avoid asking a type for a member type (includes inherited + // member types) final int HasNoMemberTypes = 0x4000; // test bit to identify if the type's hierarchy is inconsistent diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/TypeBinding.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/TypeBinding.java index 7bb7ec3..3bdbafa 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/TypeBinding.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/TypeBinding.java @@ -13,123 +13,152 @@ package net.sourceforge.phpdt.internal.compiler.lookup; import net.sourceforge.phpdt.core.compiler.CharOperation; /* - * Not all fields defined by this type (& its subclasses) are initialized when it is created. - * Some are initialized only when needed. - * - * Accessors have been provided for some public fields so all TypeBindings have the same API... - * but access public fields directly whenever possible. - * Non-public fields have accessors which should be used everywhere you expect the field to be initialized. - * - * null is NOT a valid value for a non-public field... it just means the field is not initialized. + * Not all fields defined by this type (& its subclasses) are initialized when + * it is created. Some are initialized only when needed. + * + * Accessors have been provided for some public fields so all TypeBindings have + * the same API... but access public fields directly whenever possible. + * Non-public fields have accessors which should be used everywhere you expect + * the field to be initialized. + * + * null is NOT a valid value for a non-public field... it just means the field + * is not initialized. */ -abstract public class TypeBinding extends Binding implements BaseTypes, TagBits, TypeConstants, TypeIds { +abstract public class TypeBinding extends Binding implements BaseTypes, + TagBits, TypeConstants, TypeIds { public int id = NoId; + public int tagBits = 0; // See values in the interface TagBits below -/* API - * Answer the receiver's binding type from Binding.BindingID. - */ + /* + * API Answer the receiver's binding type from Binding.BindingID. + */ -public final int bindingType() { - return TYPE; -} -/* Answer true if the receiver can be instantiated - */ + public final int bindingType() { + return TYPE; + } -public boolean canBeInstantiated() { - return !isBaseType(); -} -/* Answer the receiver's constant pool name. - * - * NOTE: This method should only be used during/after code gen. - */ + /* + * Answer true if the receiver can be instantiated + */ -public abstract char[] constantPoolName(); /* java/lang/Object */ -String debugName() { - return new String(readableName()); -} -/* - * Answer the receiver's dimensions - 0 for non-array types - */ -public int dimensions(){ - return 0; -} -public abstract PackageBinding getPackage(); -/* Answer true if the receiver is an array -*/ + public boolean canBeInstantiated() { + return !isBaseType(); + } -public final boolean isArrayType() { - return (tagBits & IsArrayType) != 0; -} -/* Answer true if the receiver is a base type -*/ + /* + * Answer the receiver's constant pool name. + * + * NOTE: This method should only be used during/after code gen. + */ -public final boolean isBaseType() { - return (tagBits & IsBaseType) != 0; -} -public boolean isClass() { - return false; -} -/* Answer true if the receiver type can be assigned to the argument type (right) -*/ - -public abstract boolean isCompatibleWith(TypeBinding right); -/* Answer true if the receiver's hierarchy has problems (always false for arrays & base types) -*/ - -public final boolean isHierarchyInconsistent() { - return (tagBits & HierarchyHasProblems) != 0; -} -public boolean isInterface() { - return false; -} -public final boolean isNumericType() { - switch (id) { - case T_int : - case T_float : - case T_double : - case T_short : - case T_byte : - case T_long : - case T_char : + public abstract char[] constantPoolName(); /* java/lang/Object */ + + String debugName() { + return new String(readableName()); + } + + /* + * Answer the receiver's dimensions - 0 for non-array types + */ + public int dimensions() { + return 0; + } + + public abstract PackageBinding getPackage(); + + /* + * Answer true if the receiver is an array + */ + + public final boolean isArrayType() { + return (tagBits & IsArrayType) != 0; + } + + /* + * Answer true if the receiver is a base type + */ + + public final boolean isBaseType() { + return (tagBits & IsBaseType) != 0; + } + + public boolean isClass() { + return false; + } + + /* + * Answer true if the receiver type can be assigned to the argument type + * (right) + */ + + public abstract boolean isCompatibleWith(TypeBinding right); + + /* + * Answer true if the receiver's hierarchy has problems (always false for + * arrays & base types) + */ + + public final boolean isHierarchyInconsistent() { + return (tagBits & HierarchyHasProblems) != 0; + } + + public boolean isInterface() { + return false; + } + + public final boolean isNumericType() { + switch (id) { + case T_int: + case T_float: + case T_double: + case T_short: + case T_byte: + case T_long: + case T_char: return true; - default : + default: return false; + } } -} -public TypeBinding leafComponentType(){ - return this; -} + public TypeBinding leafComponentType() { + return this; + } -/** - * Answer the qualified name of the receiver's package separated by periods - * or an empty string if its the default package. - * - * For example, {java.util.Hashtable}. - */ + /** + * Answer the qualified name of the receiver's package separated by periods + * or an empty string if its the default package. + * + * For example, {java.util.Hashtable}. + */ -public char[] qualifiedPackageName() { - PackageBinding packageBinding = getPackage(); - return packageBinding == null || packageBinding.compoundName == CharOperation.NO_CHAR_CHAR - ? CharOperation.NO_CHAR - : packageBinding.readableName(); -} -/** -* Answer the source name for the type. -* In the case of member types, as the qualified name from its top level type. -* For example, for a member type N defined inside M & A: "A.M.N". -*/ - -public abstract char[] qualifiedSourceName(); -/* Answer the receiver's signature. -* -* Arrays & base types do not distinguish between signature() & constantPoolName(). -* -* NOTE: This method should only be used during/after code gen. -*/ - -public char[] signature() { - return constantPoolName(); -} -public abstract char[] sourceName(); + public char[] qualifiedPackageName() { + PackageBinding packageBinding = getPackage(); + return packageBinding == null + || packageBinding.compoundName == CharOperation.NO_CHAR_CHAR ? CharOperation.NO_CHAR + : packageBinding.readableName(); + } + + /** + * Answer the source name for the type. In the case of member types, as the + * qualified name from its top level type. For example, for a member type N + * defined inside M & A: "A.M.N". + */ + + public abstract char[] qualifiedSourceName(); + + /* + * Answer the receiver's signature. + * + * Arrays & base types do not distinguish between signature() & + * constantPoolName(). + * + * NOTE: This method should only be used during/after code gen. + */ + + public char[] signature() { + return constantPoolName(); + } + + public abstract char[] sourceName(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/TypeConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/TypeConstants.java index 394e0c9..a238fba 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/TypeConstants.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/TypeConstants.java @@ -12,62 +12,122 @@ package net.sourceforge.phpdt.internal.compiler.lookup; public interface TypeConstants { final char[] JAVA = "java".toCharArray(); //$NON-NLS-1$ + final char[] LANG = "lang".toCharArray(); //$NON-NLS-1$ + final char[] IO = "io".toCharArray(); //$NON-NLS-1$ + final char[] REFLECT = "reflect".toCharArray(); //$NON-NLS-1$ + final char[] CharArray_JAVA_LANG_OBJECT = "java.lang.Object".toCharArray(); //$NON-NLS-1$ + final char[] LENGTH = "length".toCharArray(); //$NON-NLS-1$ + final char[] CLONE = "clone".toCharArray(); //$NON-NLS-1$ + final char[] OBJECT = "Object".toCharArray(); //$NON-NLS-1$ + final char[] MAIN = "main".toCharArray(); //$NON-NLS-1$ + final char[] SERIALVERSIONUID = "serialVersionUID".toCharArray(); //$NON-NLS-1$ + final char[] READRESOLVE = "readResolve".toCharArray(); //$NON-NLS-1$ + final char[] WRITEREPLACE = "writeReplace".toCharArray(); //$NON-NLS-1$ + final char[] READOBJECT = "readObject".toCharArray(); //$NON-NLS-1$ + final char[] WRITEOBJECT = "writeObject".toCharArray(); //$NON-NLS-1$ + final char[] CharArray_JAVA_IO_OBJECTINPUTSTREAM = "java.io.ObjectInputStream".toCharArray(); //$NON-NLS-1$ + final char[] CharArray_JAVA_IO_OBJECTOUTPUTSTREAM = "java.io.ObjectOutputStream".toCharArray(); //$NON-NLS-1$ - + // Constant compound names - final char[][] JAVA_LANG = {JAVA, LANG}; - final char[][] JAVA_IO = {JAVA, IO}; - final char[][] JAVA_LANG_ASSERTIONERROR = {JAVA, LANG, "AssertionError".toCharArray()}; //$NON-NLS-1$ - final char[][] JAVA_LANG_CLASS = {JAVA, LANG, "Class".toCharArray()}; //$NON-NLS-1$ - final char[][] JAVA_LANG_CLASSNOTFOUNDEXCEPTION = {JAVA, LANG, "ClassNotFoundException".toCharArray()}; //$NON-NLS-1$ - final char[][] JAVA_LANG_CLONEABLE = {JAVA, LANG, "Cloneable".toCharArray()}; //$NON-NLS-1$ - final char[][] JAVA_LANG_EXCEPTION = {JAVA, LANG, "Exception".toCharArray()}; //$NON-NLS-1$ - final char[][] JAVA_LANG_ERROR = {JAVA, LANG, "Error".toCharArray()}; //$NON-NLS-1$ - final char[][] JAVA_LANG_NOCLASSDEFERROR = {JAVA, LANG, "NoClassDefError".toCharArray()}; //$NON-NLS-1$ - final char[][] JAVA_LANG_OBJECT = {OBJECT};//{JAVA, LANG, OBJECT}; - final char[][] JAVA_LANG_STRING = {JAVA, LANG, "String".toCharArray()}; //$NON-NLS-1$ - final char[][] JAVA_LANG_STRINGBUFFER = {JAVA, LANG, "StringBuffer".toCharArray()}; //$NON-NLS-1$ - final char[][] JAVA_LANG_SYSTEM = {JAVA, LANG, "System".toCharArray()}; //$NON-NLS-1$ - final char[][] JAVA_LANG_RUNTIMEEXCEPTION = {JAVA, LANG, "RuntimeException".toCharArray()}; //$NON-NLS-1$ - final char[][] JAVA_LANG_THROWABLE = {JAVA, LANG, "Throwable".toCharArray()}; //$NON-NLS-1$ - final char[][] JAVA_LANG_REFLECT_CONSTRUCTOR = {JAVA, LANG, REFLECT, "Constructor".toCharArray()}; //$NON-NLS-1$ - final char[][] JAVA_IO_PRINTSTREAM = {JAVA, IO, "PrintStream".toCharArray()}; //$NON-NLS-1$ - final char[][] JAVA_IO_SERIALIZABLE = {JAVA, IO, "Serializable".toCharArray()}; //$NON-NLS-1$ - final char[][] JAVA_LANG_BYTE = {JAVA, LANG, "Byte".toCharArray()}; //$NON-NLS-1$ - final char[][] JAVA_LANG_SHORT = {JAVA, LANG, "Short".toCharArray()}; //$NON-NLS-1$ - final char[][] JAVA_LANG_CHARACTER = {JAVA, LANG, "Character".toCharArray()}; //$NON-NLS-1$ - final char[][] JAVA_LANG_INTEGER = {JAVA, LANG, "Integer".toCharArray()}; //$NON-NLS-1$ - final char[][] JAVA_LANG_LONG = {JAVA, LANG, "Long".toCharArray()}; //$NON-NLS-1$ - final char[][] JAVA_LANG_FLOAT = {JAVA, LANG, "Float".toCharArray()}; //$NON-NLS-1$ - final char[][] JAVA_LANG_DOUBLE = {JAVA, LANG, "Double".toCharArray()}; //$NON-NLS-1$ - final char[][] JAVA_LANG_BOOLEAN = {JAVA, LANG, "Boolean".toCharArray()}; //$NON-NLS-1$ - final char[][] JAVA_LANG_VOID = {JAVA, LANG, "Void".toCharArray()}; //$NON-NLS-1$ + final char[][] JAVA_LANG = { JAVA, LANG }; + + final char[][] JAVA_IO = { JAVA, IO }; + + final char[][] JAVA_LANG_ASSERTIONERROR = { JAVA, LANG, + "AssertionError".toCharArray() }; //$NON-NLS-1$ + + final char[][] JAVA_LANG_CLASS = { JAVA, LANG, "Class".toCharArray() }; //$NON-NLS-1$ + + final char[][] JAVA_LANG_CLASSNOTFOUNDEXCEPTION = { JAVA, LANG, + "ClassNotFoundException".toCharArray() }; //$NON-NLS-1$ + + final char[][] JAVA_LANG_CLONEABLE = { JAVA, LANG, + "Cloneable".toCharArray() }; //$NON-NLS-1$ + + final char[][] JAVA_LANG_EXCEPTION = { JAVA, LANG, + "Exception".toCharArray() }; //$NON-NLS-1$ + + final char[][] JAVA_LANG_ERROR = { JAVA, LANG, "Error".toCharArray() }; //$NON-NLS-1$ + + final char[][] JAVA_LANG_NOCLASSDEFERROR = { JAVA, LANG, + "NoClassDefError".toCharArray() }; //$NON-NLS-1$ + + final char[][] JAVA_LANG_OBJECT = { OBJECT };// {JAVA, LANG, OBJECT}; + + final char[][] JAVA_LANG_STRING = { JAVA, LANG, "String".toCharArray() }; //$NON-NLS-1$ + + final char[][] JAVA_LANG_STRINGBUFFER = { JAVA, LANG, + "StringBuffer".toCharArray() }; //$NON-NLS-1$ + + final char[][] JAVA_LANG_SYSTEM = { JAVA, LANG, "System".toCharArray() }; //$NON-NLS-1$ + + final char[][] JAVA_LANG_RUNTIMEEXCEPTION = { JAVA, LANG, + "RuntimeException".toCharArray() }; //$NON-NLS-1$ + + final char[][] JAVA_LANG_THROWABLE = { JAVA, LANG, + "Throwable".toCharArray() }; //$NON-NLS-1$ + + final char[][] JAVA_LANG_REFLECT_CONSTRUCTOR = { JAVA, LANG, REFLECT, + "Constructor".toCharArray() }; //$NON-NLS-1$ + + final char[][] JAVA_IO_PRINTSTREAM = { JAVA, IO, + "PrintStream".toCharArray() }; //$NON-NLS-1$ + + final char[][] JAVA_IO_SERIALIZABLE = { JAVA, IO, + "Serializable".toCharArray() }; //$NON-NLS-1$ + + final char[][] JAVA_LANG_BYTE = { JAVA, LANG, "Byte".toCharArray() }; //$NON-NLS-1$ + + final char[][] JAVA_LANG_SHORT = { JAVA, LANG, "Short".toCharArray() }; //$NON-NLS-1$ + + final char[][] JAVA_LANG_CHARACTER = { JAVA, LANG, + "Character".toCharArray() }; //$NON-NLS-1$ + + final char[][] JAVA_LANG_INTEGER = { JAVA, LANG, "Integer".toCharArray() }; //$NON-NLS-1$ + + final char[][] JAVA_LANG_LONG = { JAVA, LANG, "Long".toCharArray() }; //$NON-NLS-1$ + + final char[][] JAVA_LANG_FLOAT = { JAVA, LANG, "Float".toCharArray() }; //$NON-NLS-1$ + + final char[][] JAVA_LANG_DOUBLE = { JAVA, LANG, "Double".toCharArray() }; //$NON-NLS-1$ + + final char[][] JAVA_LANG_BOOLEAN = { JAVA, LANG, "Boolean".toCharArray() }; //$NON-NLS-1$ + + final char[][] JAVA_LANG_VOID = { JAVA, LANG, "Void".toCharArray() }; //$NON-NLS-1$ // Constants used by the flow analysis final int EqualOrMoreSpecific = -1; + final int NotRelated = 0; + final int MoreGeneric = 1; // Method collections final TypeBinding[] NoParameters = new TypeBinding[0]; + final ReferenceBinding[] NoExceptions = new ReferenceBinding[0]; + // Type collections final FieldBinding[] NoFields = new FieldBinding[0]; + final MethodBinding[] NoMethods = new MethodBinding[0]; + final ReferenceBinding[] NoSuperInterfaces = new ReferenceBinding[0]; + final ReferenceBinding[] NoMemberTypes = new ReferenceBinding[0]; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/TypeIds.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/TypeIds.java index acca0a1..b987057 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/TypeIds.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/TypeIds.java @@ -11,119 +11,214 @@ package net.sourceforge.phpdt.internal.compiler.lookup; public interface TypeIds { - //base type void null undefined Object String - //should have an id that is 0<= id <= 15 + // base type void null undefined Object String + // should have an id that is 0<= id <= 15 final int T_undefined = 0; // should not be changed + final int T_Object = 1; + final int T_char = 2; + final int T_byte = 3; + final int T_short = 4; + final int T_boolean = 5; + final int T_void = 6; + final int T_long = 7; + final int T_double = 8; + final int T_float = 9; + final int T_int = 10; + final int T_String = 11; + final int T_null = 12; - //final int T_extendedDouble = 13; - //final int T_extendedLong = 14 - //=========end of 4 bits constraint=========== + // final int T_extendedDouble = 13; + // final int T_extendedLong = 14 + + // =========end of 4 bits constraint=========== final int T_JavaLangObject = T_Object; // for consistency + final int T_JavaLangString = T_String; // for consistency // well-known exception types final int T_JavaLangClass = 16; + final int T_JavaLangStringBuffer = 17; + final int T_JavaLangSystem = 18; + final int T_JavaLangError = 19; + final int T_JavaLangReflectConstructor = 20; + final int T_JavaLangThrowable = 21; + final int T_JavaLangNoClassDefError = 22; + final int T_JavaLangClassNotFoundException = 23; + final int T_JavaIoPrintStream = 24; + final int T_JavaLangException = 25; // wrapper types final int T_JavaLangByte = 26; + final int T_JavaLangShort = 27; + final int T_JavaLangCharacter = 28; + final int T_JavaLangInteger = 29; + final int T_JavaLangLong = 30; + final int T_JavaLangFloat = 31; + final int T_JavaLangDouble = 32; + final int T_JavaLangBoolean = 33; + final int T_JavaLangVoid = 34; // 1.4 feature final int T_JavaLangAssertionError = 35; + final int NoId = Integer.MAX_VALUE; - // implicit conversions: to (note: booleans are integers at runtime) + // implicit conversions: to (note: booleans are + // integers at runtime) final int Boolean2Int = T_boolean + (T_int << 4); + final int Boolean2String = T_boolean + (T_String << 4); + final int Boolean2Boolean = T_boolean + (T_boolean << 4); + final int Byte2Byte = T_byte + (T_byte << 4); + final int Byte2Short = T_byte + (T_short << 4); + final int Byte2Char = T_byte + (T_char << 4); + final int Byte2Int = T_byte + (T_int << 4); + final int Byte2Long = T_byte + (T_long << 4); + final int Byte2Float = T_byte + (T_float << 4); + final int Byte2Double = T_byte + (T_double << 4); + final int Byte2String = T_byte + (T_String << 4); + final int Short2Byte = T_short + (T_byte << 4); + final int Short2Short = T_short + (T_short << 4); + final int Short2Char = T_short + (T_char << 4); + final int Short2Int = T_short + (T_int << 4); + final int Short2Long = T_short + (T_long << 4); + final int Short2Float = T_short + (T_float << 4); + final int Short2Double = T_short + (T_double << 4); + final int Short2String = T_short + (T_String << 4); + final int Char2Byte = T_char + (T_byte << 4); + final int Char2Short = T_char + (T_short << 4); + final int Char2Char = T_char + (T_char << 4); + final int Char2Int = T_char + (T_int << 4); + final int Char2Long = T_char + (T_long << 4); + final int Char2Float = T_char + (T_float << 4); + final int Char2Double = T_char + (T_double << 4); + final int Char2String = T_char + (T_String << 4); + final int Int2Byte = T_int + (T_byte << 4); + final int Int2Short = T_int + (T_short << 4); + final int Int2Char = T_int + (T_char << 4); + final int Int2Int = T_int + (T_int << 4); + final int Int2Long = T_int + (T_long << 4); + final int Int2Float = T_int + (T_float << 4); + final int Int2Double = T_int + (T_double << 4); + final int Int2String = T_int + (T_String << 4); + final int Long2Byte = T_long + (T_byte << 4); + final int Long2Short = T_long + (T_short << 4); + final int Long2Char = T_long + (T_char << 4); + final int Long2Int = T_long + (T_int << 4); + final int Long2Long = T_long + (T_long << 4); + final int Long2Float = T_long + (T_float << 4); + final int Long2Double = T_long + (T_double << 4); + final int Long2String = T_long + (T_String << 4); + final int Float2Byte = T_float + (T_byte << 4); + final int Float2Short = T_float + (T_short << 4); + final int Float2Char = T_float + (T_char << 4); + final int Float2Int = T_float + (T_int << 4); + final int Float2Long = T_float + (T_long << 4); + final int Float2Float = T_float + (T_float << 4); + final int Float2Double = T_float + (T_double << 4); + final int Float2String = T_float + (T_String << 4); + final int Double2Byte = T_double + (T_byte << 4); + final int Double2Short = T_double + (T_short << 4); + final int Double2Char = T_double + (T_char << 4); + final int Double2Int = T_double + (T_int << 4); + final int Double2Long = T_double + (T_long << 4); + final int Double2Float = T_double + (T_float << 4); + final int Double2Double = T_double + (T_double << 4); + final int Double2String = T_double + (T_String << 4); + final int String2String = T_String + (T_String << 4); + final int Object2String = T_Object + (T_String << 4); + final int Null2String = T_null + (T_String << 4); + final int Object2Object = T_Object + (T_Object << 4); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/UnresolvedReferenceBinding.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/UnresolvedReferenceBinding.java index fdf1c4c..6dee732 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/UnresolvedReferenceBinding.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/UnresolvedReferenceBinding.java @@ -14,29 +14,46 @@ import net.sourceforge.phpdt.core.compiler.CharOperation; public class UnresolvedReferenceBinding extends ReferenceBinding { ReferenceBinding resolvedType; -UnresolvedReferenceBinding(char[][] compoundName, PackageBinding packageBinding) { - this.compoundName = compoundName; - this.fPackage = packageBinding; -} -String debugName() { - return toString(); -} -ReferenceBinding resolve(LookupEnvironment environment) { - if (resolvedType != null) return resolvedType; - - ReferenceBinding environmentType = fPackage.getType0(compoundName[compoundName.length - 1]); - if (environmentType == this) - environmentType = environment.askForType(compoundName); - if (environmentType != null && environmentType != this) { // could not resolve any better, error was already reported against it - resolvedType = environmentType; - environment.updateArrayCache(this, environmentType); - return environmentType; // when found, it replaces the unresolved type in the cache + + UnresolvedReferenceBinding(char[][] compoundName, + PackageBinding packageBinding) { + this.compoundName = compoundName; + this.fPackage = packageBinding; } - environment.problemReporter.isClassPathCorrect(compoundName, null); - return null; // will not get here since the above error aborts the compilation -} -public String toString() { - return "Unresolved type " + ((compoundName != null) ? CharOperation.toString(compoundName) : "UNNAMED"); //$NON-NLS-1$ //$NON-NLS-2$ -} + String debugName() { + return toString(); + } + + ReferenceBinding resolve(LookupEnvironment environment) { + if (resolvedType != null) + return resolvedType; + + ReferenceBinding environmentType = fPackage + .getType0(compoundName[compoundName.length - 1]); + if (environmentType == this) + environmentType = environment.askForType(compoundName); + if (environmentType != null && environmentType != this) { // could not + // resolve + // any + // better, + // error was + // already + // reported + // against + // it + resolvedType = environmentType; + environment.updateArrayCache(this, environmentType); + return environmentType; // when found, it replaces the unresolved + // type in the cache + } + + environment.problemReporter.isClassPathCorrect(compoundName, null); + return null; // will not get here since the above error aborts the + // compilation + } + + public String toString() { + return "Unresolved type " + ((compoundName != null) ? CharOperation.toString(compoundName) : "UNNAMED"); //$NON-NLS-1$ //$NON-NLS-2$ + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/VariableBinding.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/VariableBinding.java index 04ee3da..19371b5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/VariableBinding.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/lookup/VariableBinding.java @@ -14,31 +14,39 @@ import net.sourceforge.phpdt.internal.compiler.impl.Constant; public abstract class VariableBinding extends Binding { public int modifiers; + public TypeBinding type; + public char[] name; + public Constant constant; + public int id; // for flow-analysis (position in flowInfo bit vector) -public boolean isConstantValue() { - return constant != Constant.NotAConstant; -} + public boolean isConstantValue() { + return constant != Constant.NotAConstant; + } -public final boolean isBlankFinal(){ - return (modifiers & AccBlankFinal) != 0; -} -/* Answer true if the receiver is final and cannot be changed -*/ + public final boolean isBlankFinal() { + return (modifiers & AccBlankFinal) != 0; + } -public final boolean isFinal() { - return (modifiers & AccFinal) != 0; -} -public char[] readableName() { - return name; -} -public String toString() { - String s = (type != null) ? type.debugName() : "UNDEFINED TYPE"; //$NON-NLS-1$ - s += " "; //$NON-NLS-1$ - s += (name != null) ? new String(name) : "UNNAMED FIELD"; //$NON-NLS-1$ - return s; -} + /* + * Answer true if the receiver is final and cannot be changed + */ + + public final boolean isFinal() { + return (modifiers & AccFinal) != 0; + } + + public char[] readableName() { + return name; + } + + public String toString() { + String s = (type != null) ? type.debugName() : "UNDEFINED TYPE"; //$NON-NLS-1$ + s += " "; //$NON-NLS-1$ + s += (name != null) ? new String(name) : "UNNAMED FIELD"; //$NON-NLS-1$ + return s; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/AbstractCommentParser.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/AbstractCommentParser.java index eafaa62..08636d5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/AbstractCommentParser.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/AbstractCommentParser.java @@ -24,66 +24,101 @@ public abstract class AbstractCommentParser { // recognized tags public static final char[] TAG_DEPRECATED = "deprecated".toCharArray(); //$NON-NLS-1$ + public static final char[] TAG_PARAM = "param".toCharArray(); //$NON-NLS-1$ + public static final char[] TAG_RETURN = "return".toCharArray(); //$NON-NLS-1$ + public static final char[] TAG_THROWS = "throws".toCharArray(); //$NON-NLS-1$ + public static final char[] TAG_EXCEPTION = "exception".toCharArray(); //$NON-NLS-1$ + public static final char[] TAG_SEE = "see".toCharArray(); //$NON-NLS-1$ + public static final char[] TAG_LINK = "link".toCharArray(); //$NON-NLS-1$ + public static final char[] TAG_LINKPLAIN = "linkplain".toCharArray(); //$NON-NLS-1$ + public static final char[] TAG_INHERITDOC = "inheritDoc".toCharArray(); //$NON-NLS-1$ - + // tags expected positions public final static int ORDERED_TAGS_NUMBER = 3; + public final static int PARAM_TAG_EXPECTED_ORDER = 0; + public final static int THROWS_TAG_EXPECTED_ORDER = 1; + public final static int SEE_TAG_EXPECTED_ORDER = 2; - + // Kind of comment parser public final static int COMPIL_PARSER = 0x00000001; + public final static int DOM_PARSER = 0x00000002; - + // Public fields public Scanner scanner; + public boolean checkDocComment = false; - + // Protected fields protected boolean inherited, deprecated; + protected char[] source; + protected int index, endComment, lineEnd; - protected int tokenPreviousPosition, lastIdentifierEndPosition, starPosition; + + protected int tokenPreviousPosition, lastIdentifierEndPosition, + starPosition; + protected int textStart, memberStart; + protected int tagSourceStart, tagSourceEnd; + protected int inlineTagStart; + protected Parser sourceParser; + protected Object returnStatement; + protected boolean lineStarted = false, inlineTagStarted = false; + protected int kind; + protected int[] lineEnds; - + // Private fields private int currentTokenType = -1; - + // Line pointers private int linePtr, lastLinePtr; - + // Identifier stack protected int identifierPtr; + protected char[][] identifierStack; + protected int identifierLengthPtr; + protected int[] identifierLengthStack; + protected long[] identifierPositionStack; + // Ast stack protected static int AstStackIncrement = 10; + protected int astPtr; + protected Object[] astStack; + protected int astLengthPtr; + protected int[] astLengthStack; protected AbstractCommentParser(Parser sourceParser) { this.sourceParser = sourceParser; - this.scanner = new Scanner(false, false, false, false, false, null, null, false); - + this.scanner = new Scanner(false, false, false, false, false, null, + null, false); + this.identifierStack = new char[20][]; this.identifierPositionStack = new long[20]; this.identifierLengthStack = new int[10]; @@ -91,11 +126,14 @@ public abstract class AbstractCommentParser { this.astLengthStack = new int[20]; } - /* (non-Javadoc) - * Returns true if tag @deprecated is present in javadoc comment. + /* + * (non-Javadoc) Returns true if tag * - * If javadoc checking is enabled, will also construct an Javadoc node, which will be stored into Parser.javadoc - * slot for being consumed later on. + * @deprecated is present in javadoc comment. + * + * If javadoc checking is enabled, will also construct an Javadoc node, + * which will be stored into Parser.javadoc slot for being consumed later + * on. */ protected boolean parseComment(int javadocStart, int javadocEnd) { @@ -108,8 +146,8 @@ public abstract class AbstractCommentParser { readChar(); // starting '/' int previousPosition = this.index; readChar(); // first '*' - char nextCharacter= readChar(); // second '*' - + char nextCharacter = readChar(); // second '*' + // Init local variables this.astLengthPtr = -1; this.astPtr = -1; @@ -122,315 +160,398 @@ public abstract class AbstractCommentParser { this.deprecated = false; this.linePtr = getLineNumber(javadocStart); this.lastLinePtr = getLineNumber(javadocEnd); - this.lineEnd = (this.linePtr == this.lastLinePtr) ? this.endComment : this.scanner.getLineEnd(this.linePtr); + this.lineEnd = (this.linePtr == this.lastLinePtr) ? this.endComment + : this.scanner.getLineEnd(this.linePtr); this.textStart = -1; char previousChar = 0; int invalidTagLineEnd = -1; int invalidInlineTagLineEnd = -1; - + // Loop on each comment character while (this.index < this.endComment) { previousPosition = this.index; previousChar = nextCharacter; - - // Calculate line end (cannot use this.scanner.linePtr as scanner does not parse line ends again) - if (this.index > (this.lineEnd+1)) { + + // Calculate line end (cannot use this.scanner.linePtr as + // scanner does not parse line ends again) + if (this.index > (this.lineEnd + 1)) { updateLineEnd(); } - + // Read next char only if token was consumed if (this.currentTokenType < 0) { nextCharacter = readChar(); // consider unicodes } else { - previousPosition = this.scanner.getCurrentTokenStartPosition(); + previousPosition = this.scanner + .getCurrentTokenStartPosition(); switch (this.currentTokenType) { - case ITerminalSymbols.TokenNameRBRACE: - nextCharacter = '}'; - break; - case ITerminalSymbols.TokenNameMULTIPLY: - nextCharacter = '*'; - break; + case ITerminalSymbols.TokenNameRBRACE: + nextCharacter = '}'; + break; + case ITerminalSymbols.TokenNameMULTIPLY: + nextCharacter = '*'; + break; default: - nextCharacter = this.scanner.currentCharacter; + nextCharacter = this.scanner.currentCharacter; } consumeToken(); } - + if (this.index >= this.endComment) { break; } - + switch (nextCharacter) { - case '@' : - boolean valid = false; - // Start tag parsing only if we have a java identifier start character and if we are on line beginning or at inline tag beginning - if ((!this.lineStarted || previousChar == '{')) { - this.lineStarted = true; - if (this.inlineTagStarted) { - this.inlineTagStarted = false; - // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=53279 - // Cannot have @ inside inline comment - if (this.sourceParser != null) { - int end = previousPosition, * chars and + // spaces are not allowed in tag names + switch (pc) { + case '}': + case '!': + case '#': + case '%': + case '&': + case '\'': + case ':': + // case '-': allowed in tag names as + // this character is often used in + // doclets (bug 68087) + case '<': + case '>': + case '*': // break for '*' as this is + // perhaps the end of comment + // (bug 65288) + break tagNameToken; + default: + if (pc == ' ' + || Character.isWhitespace(pc)) + break tagNameToken; + } + tk = readTokenAndConsume(); + pc = peekChar(); } - this.inlineTagStarted = true; - invalidInlineTagLineEnd = this.lineEnd; - } else if (this.textStart != -1 && this.textStart < invalidTagLineEnd) { - pushText(this.textStart, invalidTagLineEnd); + int length = this.tagSourceEnd + - this.tagSourceStart + 1; + tag = new char[length]; + System.arraycopy(this.source, + this.tagSourceStart, tag, 0, length); + this.index = this.tagSourceEnd + 1; + this.scanner.currentPosition = this.tagSourceEnd + 1; + this.tagSourceStart = previousPosition; + this.lineEnd = le; } - this.scanner.resetTo(this.index, this.endComment); - this.currentTokenType = -1; // flush token cache at line begin - try { - int token = readTokenAndConsume(); - this.tagSourceStart = this.scanner.getCurrentTokenStartPosition(); - this.tagSourceEnd = this.scanner.getCurrentTokenEndPosition(); - char[] tag = this.scanner.getCurrentIdentifierSource(); // first token is either an identifier or a keyword - if (this.kind == DOM_PARSER) { - // For DOM parser, try to get tag name other than java identifier - // (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=51660) - int tk = token; - int le = this.lineEnd; - char pc = peekChar(); - tagNameToken: while (tk != ITerminalSymbols.TokenNameEOF) { - this.tagSourceEnd = this.scanner.getCurrentTokenEndPosition(); - token = tk; - // !, ", #, %, &, ', -, :, <, >, * chars and spaces are not allowed in tag names - switch (pc) { - case '}': - case '!': - case '#': - case '%': - case '&': - case '\'': - case ':': - // case '-': allowed in tag names as this character is often used in doclets (bug 68087) - case '<': - case '>': - case '*': // break for '*' as this is perhaps the end of comment (bug 65288) - break tagNameToken; - default: - if (pc == ' ' || Character.isWhitespace(pc)) break tagNameToken; - } - tk = readTokenAndConsume(); - pc = peekChar(); + switch (token) { + case ITerminalSymbols.TokenNameIdentifier: + if (CharOperation.equals(tag, TAG_DEPRECATED)) { + this.deprecated = true; + if (this.kind == DOM_PARSER) { + valid = parseTag(); + } else { + valid = true; + } + } else if (CharOperation.equals(tag, + TAG_INHERITDOC)) { + // inhibits inherited flag when tags have + // been already stored + // see bug + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=51606 + // Note that for DOM_PARSER, nodes stack may + // be not empty even no '@' tag + // was encountered in comment. But it cannot + // be the case for COMPILER_PARSER + // and so is enough as it is only this + // parser which signals the missing tag + // warnings... + this.inherited = this.astPtr == -1; + if (this.kind == DOM_PARSER) { + valid = parseTag(); + } else { + valid = true; + } + } else if (CharOperation.equals(tag, TAG_PARAM)) { + valid = parseParam(); + } else if (CharOperation.equals(tag, + TAG_EXCEPTION)) { + valid = parseThrows(false); + } else if (CharOperation.equals(tag, TAG_SEE)) { + if (this.inlineTagStarted) { + // bug + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=53290 + // Cannot have @see inside inline + // comment + valid = false; + if (this.sourceParser != null) + this.sourceParser + .problemReporter() + .javadocUnexpectedTag( + this.tagSourceStart, + this.tagSourceEnd); + } else { + valid = parseSee(false); } - int length = this.tagSourceEnd-this.tagSourceStart+1; - tag = new char[length]; - System.arraycopy(this.source, this.tagSourceStart, tag, 0, length); - this.index = this.tagSourceEnd+1; - this.scanner.currentPosition = this.tagSourceEnd+1; - this.tagSourceStart = previousPosition; - this.lineEnd = le; + } else if (CharOperation.equals(tag, TAG_LINK)) { + if (this.inlineTagStarted) { + valid = parseSee(false); + } else { + // bug + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=53290 + // Cannot have @link outside inline + // comment + valid = false; + if (this.sourceParser != null) + this.sourceParser + .problemReporter() + .javadocUnexpectedTag( + this.tagSourceStart, + this.tagSourceEnd); + } + } else if (CharOperation.equals(tag, + TAG_LINKPLAIN)) { + if (this.inlineTagStarted) { + valid = parseSee(true); + } else { + valid = parseTag(); + } + } else { + valid = parseTag(); } - switch (token) { - case ITerminalSymbols.TokenNameIdentifier : - if (CharOperation.equals(tag, TAG_DEPRECATED)) { - this.deprecated = true; - if (this.kind == DOM_PARSER) { - valid = parseTag(); - } else { - valid = true; - } - } else if (CharOperation.equals(tag, TAG_INHERITDOC)) { - // inhibits inherited flag when tags have been already stored - // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=51606 - // Note that for DOM_PARSER, nodes stack may be not empty even no '@' tag - // was encountered in comment. But it cannot be the case for COMPILER_PARSER - // and so is enough as it is only this parser which signals the missing tag warnings... - this.inherited = this.astPtr==-1; - if (this.kind == DOM_PARSER) { - valid = parseTag(); - } else { - valid = true; - } - } else if (CharOperation.equals(tag, TAG_PARAM)) { - valid = parseParam(); - } else if (CharOperation.equals(tag, TAG_EXCEPTION)) { - valid = parseThrows(false); - } else if (CharOperation.equals(tag, TAG_SEE)) { - if (this.inlineTagStarted) { - // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=53290 - // Cannot have @see inside inline comment - valid = false; - if (this.sourceParser != null) - this.sourceParser.problemReporter().javadocUnexpectedTag(this.tagSourceStart, this.tagSourceEnd); - } else { - valid = parseSee(false); - } - } else if (CharOperation.equals(tag, TAG_LINK)) { - if (this.inlineTagStarted) { - valid = parseSee(false); - } else { - // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=53290 - // Cannot have @link outside inline comment - valid = false; - if (this.sourceParser != null) - this.sourceParser.problemReporter().javadocUnexpectedTag(this.tagSourceStart, this.tagSourceEnd); - } - } else if (CharOperation.equals(tag, TAG_LINKPLAIN)) { - if (this.inlineTagStarted) { - valid = parseSee(true); - } else { - valid = parseTag(); - } - } else { - valid = parseTag(); - } - break; - case ITerminalSymbols.TokenNamereturn : - valid = parseReturn(); - // verify characters after return tag (we're expecting text description) - if(!verifyCharsAfterReturnTag(this.index)) { - if (this.sourceParser != null) { - int end = this.starPosition == -1 || this.lineEnd= this.endComment) end = invalidInlineTagLineEnd; - this.sourceParser.problemReporter().javadocUnterminatedInlineTag(this.inlineTagStart, end); + int end = previousPosition < invalidInlineTagLineEnd ? previousPosition + : invalidInlineTagLineEnd; + if (this.index >= this.endComment) + end = invalidInlineTagLineEnd; + this.sourceParser.problemReporter() + .javadocUnterminatedInlineTag(this.inlineTagStart, + end); } - if (this.lineStarted && this.textStart != -1 && this.textStart < previousPosition) { + if (this.lineStarted && this.textStart != -1 + && this.textStart < previousPosition) { pushText(this.textStart, previousPosition); } if (this.kind == DOM_PARSER) { @@ -463,12 +589,22 @@ public abstract class AbstractCommentParser { updateLineEnd(); } - protected abstract Object createArgumentReference(char[] name, int dim, Object typeRef, long[] dimPos, long argNamePos) throws InvalidInputException; - protected abstract Object createFieldReference(Object receiver) throws InvalidInputException; - protected abstract Object createMethodReference(Object receiver, List arguments) throws InvalidInputException; - protected Object createReturnStatement() { return null; } + protected abstract Object createArgumentReference(char[] name, int dim, + Object typeRef, long[] dimPos, long argNamePos) + throws InvalidInputException; + + protected abstract Object createFieldReference(Object receiver) + throws InvalidInputException; + + protected abstract Object createMethodReference(Object receiver, + List arguments) throws InvalidInputException; + + protected Object createReturnStatement() { + return null; + } + protected abstract Object createTypeReference(int primitiveToken); - + private int getEndPosition() { if (this.scanner.getCurrentTokenEndPosition() > this.lineEnd) { return this.lineEnd; @@ -478,36 +614,31 @@ public abstract class AbstractCommentParser { } /* - * Search the source position corresponding to the end of a given line number. - * Warning: returned position is 1-based index! - * @see Scanner#getLineEnd(int) We cannot directly use this method - * when linePtr field is not initialized. - * - private int getLineEnd(int lineNumber) { - - if (this.scanner.linePtr != -1) { - return this.scanner.getLineEnd(lineNumber); - } - if (this.lineEnds == null) - return -1; - if (lineNumber > this.lineEnds.length+1) - return -1; - if (lineNumber <= 0) - return -1; - if (lineNumber == this.lineEnds.length + 1) - return this.scanner.eofPosition; - return this.lineEnds[lineNumber-1]; // next line start one character behind the lineEnd of the previous line - } - */ + * Search the source position corresponding to the end of a given line + * number. Warning: returned position is 1-based index! + * + * @see Scanner#getLineEnd(int) We cannot directly use this method when + * linePtr field is not initialized. + * + * private int getLineEnd(int lineNumber) { + * + * if (this.scanner.linePtr != -1) { return + * this.scanner.getLineEnd(lineNumber); } if (this.lineEnds == null) return + * -1; if (lineNumber > this.lineEnds.length+1) return -1; if (lineNumber <= + * 0) return -1; if (lineNumber == this.lineEnds.length + 1) return + * this.scanner.eofPosition; return this.lineEnds[lineNumber-1]; // next + * line start one character behind the lineEnd of the previous line } + */ /** - * Search the line number corresponding to a specific position. - * Warning: returned position is 1-based index! - * @see Scanner#getLineNumber(int) We cannot directly use this method - * when linePtr field is not initialized. + * Search the line number corresponding to a specific position. Warning: + * returned position is 1-based index! + * + * @see Scanner#getLineNumber(int) We cannot directly use this method when + * linePtr field is not initialized. */ private int getLineNumber(int position) { - + if (this.scanner.linePtr != -1) { return this.scanner.getLineNumber(position); } @@ -519,35 +650,38 @@ public abstract class AbstractCommentParser { int g = 0, d = length - 1; int m = 0; while (g <= d) { - m = (g + d) /2; + m = (g + d) / 2; if (position < this.lineEnds[m]) { - d = m-1; + d = m - 1; } else if (position > this.lineEnds[m]) { - g = m+1; + g = m + 1; } else { return m + 1; } } if (position < this.lineEnds[m]) { - return m+1; + return m + 1; } - return m+2; + return m + 2; } /* - * Parse argument in @see tag method reference + * Parse argument in + * + * @see tag method reference */ private Object parseArguments(Object receiver) throws InvalidInputException { // Init - int modulo = 0; // should be 2 for (Type,Type,...) or 3 for (Type arg,Type arg,...) + int modulo = 0; // should be 2 for (Type,Type,...) or 3 for (Type + // arg,Type arg,...) int iToken = 0; char[] argName = null; List arguments = new ArrayList(10); int start = this.scanner.getCurrentTokenStartPosition(); - + // Parse arguments declaration if method reference - nextArg : while (this.index < this.scanner.eofPosition) { + nextArg: while (this.index < this.scanner.eofPosition) { // Read argument type reference Object typeRef; @@ -561,15 +695,21 @@ public abstract class AbstractCommentParser { if (iToken != 0) break nextArg; } else if ((iToken % modulo) != 0) { - break nextArg; + break nextArg; } if (typeRef == null) { - if (firstArg && this.currentTokenType == ITerminalSymbols.TokenNameRPAREN) { - // verify characters after arguments declaration (expecting white space or end comment) + if (firstArg + && this.currentTokenType == ITerminalSymbols.TokenNameRPAREN) { + // verify characters after arguments declaration (expecting + // white space or end comment) if (!verifySpaceOrEndComment()) { - int end = this.starPosition == -1 ? this.lineEnd : this.starPosition; - if (this.source[end]=='\n') end--; - if (this.sourceParser != null) this.sourceParser.problemReporter().javadocMalformedSeeReference(start, end); + int end = this.starPosition == -1 ? this.lineEnd + : this.starPosition; + if (this.source[end] == '\n') + end--; + if (this.sourceParser != null) + this.sourceParser.problemReporter() + .javadocMalformedSeeReference(start, end); return null; } this.lineStarted = true; @@ -581,7 +721,8 @@ public abstract class AbstractCommentParser { // Read possible array declaration int dim = 0; - long[] dimPositions = new long[20]; // assume that there won't be more than 20 dimensions... + long[] dimPositions = new long[20]; // assume that there won't be + // more than 20 dimensions... if (readToken() == ITerminalSymbols.TokenNameLBRACKET) { int dimStart = this.scanner.getCurrentTokenStartPosition(); while (readToken() == ITerminalSymbols.TokenNameLBRACKET) { @@ -590,7 +731,8 @@ public abstract class AbstractCommentParser { break nextArg; } consumeToken(); - dimPositions[dim++] = (((long) dimStart) << 32) + this.scanner.getCurrentTokenEndPosition(); + dimPositions[dim++] = (((long) dimStart) << 32) + + this.scanner.getCurrentTokenEndPosition(); } } @@ -602,20 +744,24 @@ public abstract class AbstractCommentParser { if (iToken != 1) break nextArg; } else if ((iToken % modulo) != 1) { - break nextArg; + break nextArg; } - if (argName == null) { // verify that all arguments name are declared + if (argName == null) { // verify that all arguments name are + // declared if (!firstArg) { break nextArg; } } argName = this.scanner.getCurrentIdentifierSource(); - argNamePos = (((long)this.scanner.getCurrentTokenStartPosition())<<32)+this.scanner.getCurrentTokenEndPosition(); + argNamePos = (((long) this.scanner + .getCurrentTokenStartPosition()) << 32) + + this.scanner.getCurrentTokenEndPosition(); iToken++; - } else if (argName != null) { // verify that no argument name is declared + } else if (argName != null) { // verify that no argument name is + // declared break nextArg; } - + // Verify token position if (firstArg) { modulo = iToken + 1; @@ -630,20 +776,27 @@ public abstract class AbstractCommentParser { char[] name = argName == null ? new char[0] : argName; if (token == ITerminalSymbols.TokenNameCOMMA) { // Create new argument - Object argument = createArgumentReference(name, dim, typeRef, dimPositions, argNamePos); + Object argument = createArgumentReference(name, dim, typeRef, + dimPositions, argNamePos); arguments.add(argument); consumeToken(); iToken++; } else if (token == ITerminalSymbols.TokenNameRPAREN) { - // verify characters after arguments declaration (expecting white space or end comment) + // verify characters after arguments declaration (expecting + // white space or end comment) if (!verifySpaceOrEndComment()) { - int end = this.starPosition == -1 ? this.lineEnd : this.starPosition; - if (this.source[end]=='\n') end--; - if (this.sourceParser != null) this.sourceParser.problemReporter().javadocMalformedSeeReference(start, end); + int end = this.starPosition == -1 ? this.lineEnd + : this.starPosition; + if (this.source[end] == '\n') + end--; + if (this.sourceParser != null) + this.sourceParser.problemReporter() + .javadocMalformedSeeReference(start, end); return null; } // Create new argument - Object argument = createArgumentReference(name, dim, typeRef, dimPositions, argNamePos); + Object argument = createArgumentReference(name, dim, typeRef, + dimPositions, argNamePos); arguments.add(argument); consumeToken(); return createMethodReference(receiver, arguments); @@ -657,7 +810,9 @@ public abstract class AbstractCommentParser { } /* - * Parse an URL link reference in @see tag + * Parse an URL link reference in + * + * @see tag */ private boolean parseHref() throws InvalidInputException { int start = this.scanner.getCurrentTokenStartPosition(); @@ -666,31 +821,46 @@ public abstract class AbstractCommentParser { if (readToken() == ITerminalSymbols.TokenNameIdentifier) { this.currentTokenType = -1; // do not update line end try { - if (CharOperation.equals(this.scanner.getCurrentIdentifierSource(), new char[]{'h', 'r', 'e', 'f'}, false) && - readToken() == ITerminalSymbols.TokenNameEQUAL) { + if (CharOperation.equals(this.scanner + .getCurrentIdentifierSource(), new char[] { 'h', + 'r', 'e', 'f' }, false) + && readToken() == ITerminalSymbols.TokenNameEQUAL) { this.currentTokenType = -1; // do not update line end - if (readToken() == ITerminalSymbols.TokenNameStringDoubleQuote || - readToken() == ITerminalSymbols.TokenNameStringSingleQuote) { - this.currentTokenType = -1; // do not update line end - // Skip all characters after string literal until closing '>' (see bug 68726) - while (this.index <= this.lineEnd && readToken() != ITerminalSymbols.TokenNameGREATER) { - this.currentTokenType = -1; // do not update line end + if (readToken() == ITerminalSymbols.TokenNameStringDoubleQuote + || readToken() == ITerminalSymbols.TokenNameStringSingleQuote) { + this.currentTokenType = -1; // do not update line + // end + // Skip all characters after string literal until + // closing '>' (see bug 68726) + while (this.index <= this.lineEnd + && readToken() != ITerminalSymbols.TokenNameGREATER) { + this.currentTokenType = -1; // do not update + // line end } if (this.currentTokenType == ITerminalSymbols.TokenNameGREATER) { - consumeToken(); // update line end as new lines are allowed in URL description + consumeToken(); // update line end as new lines + // are allowed in URL + // description while (readToken() != ITerminalSymbols.TokenNameLESS) { - if (this.scanner.currentPosition >= this.scanner.eofPosition || this.scanner.currentCharacter == '@') { - // Reset position: we want to rescan last token + if (this.scanner.currentPosition >= this.scanner.eofPosition + || this.scanner.currentCharacter == '@') { + // Reset position: we want to rescan + // last token this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; this.currentTokenType = -1; // Signal syntax error - if (this.sourceParser != null) this.sourceParser.problemReporter().javadocInvalidSeeUrlReference(start, this.lineEnd); + if (this.sourceParser != null) + this.sourceParser + .problemReporter() + .javadocInvalidSeeUrlReference( + start, this.lineEnd); return false; } consumeToken(); } - this.currentTokenType = -1; // do not update line end + this.currentTokenType = -1; // do not update + // line end if (readChar() == '/') { if (Character.toLowerCase(readChar()) == 'a') { if (readChar() == '>') { @@ -712,12 +882,16 @@ public abstract class AbstractCommentParser { this.scanner.currentPosition = this.tokenPreviousPosition; this.currentTokenType = -1; // Signal syntax error - if (this.sourceParser != null) this.sourceParser.problemReporter().javadocInvalidSeeUrlReference(start, this.lineEnd); + if (this.sourceParser != null) + this.sourceParser.problemReporter().javadocInvalidSeeUrlReference( + start, this.lineEnd); return false; } /* - * Parse a method reference in @see tag + * Parse a method reference in + * + * @see tag */ private Object parseMember(Object receiver) throws InvalidInputException { // Init @@ -730,7 +904,8 @@ public abstract class AbstractCommentParser { if (readToken() == ITerminalSymbols.TokenNameIdentifier) { consumeToken(); pushIdentifier(true); - // Look for next token to know whether it's a field or method reference + // Look for next token to know whether it's a field or method + // reference int previousPosition = this.index; if (readToken() == ITerminalSymbols.TokenNameLPAREN) { consumeToken(); @@ -738,11 +913,13 @@ public abstract class AbstractCommentParser { try { return parseArguments(receiver); } catch (InvalidInputException e) { - int end = this.scanner.getCurrentTokenEndPosition() < this.lineEnd ? - this.scanner.getCurrentTokenEndPosition() : - this.scanner.getCurrentTokenStartPosition(); + int end = this.scanner.getCurrentTokenEndPosition() < this.lineEnd ? this.scanner + .getCurrentTokenEndPosition() + : this.scanner.getCurrentTokenStartPosition(); end = end < this.lineEnd ? end : this.lineEnd; - if (this.sourceParser != null) this.sourceParser.problemReporter().javadocInvalidSeeReferenceArgs(start, end); + if (this.sourceParser != null) + this.sourceParser.problemReporter() + .javadocInvalidSeeReferenceArgs(start, end); } return null; } @@ -752,18 +929,25 @@ public abstract class AbstractCommentParser { this.scanner.currentPosition = previousPosition; this.currentTokenType = -1; - // Verify character(s) after identifier (expecting space or end comment) + // Verify character(s) after identifier (expecting space or end + // comment) if (!verifySpaceOrEndComment()) { - int end = this.starPosition == -1 ? this.lineEnd : this.starPosition; - if (this.source[end]=='\n') end--; - if (this.sourceParser != null) this.sourceParser.problemReporter().javadocMalformedSeeReference(start, end); + int end = this.starPosition == -1 ? this.lineEnd + : this.starPosition; + if (this.source[end] == '\n') + end--; + if (this.sourceParser != null) + this.sourceParser.problemReporter() + .javadocMalformedSeeReference(start, end); return null; } return createFieldReference(receiver); } int end = getEndPosition() - 1; end = start > end ? start : end; - if (this.sourceParser != null) this.sourceParser.problemReporter().javadocInvalidSeeReference(start, end); + if (this.sourceParser != null) + this.sourceParser.problemReporter().javadocInvalidSeeReference( + start, end); // Reset position: we want to rescan last token this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; @@ -784,16 +968,17 @@ public abstract class AbstractCommentParser { // Push identifier next int token = readToken(); switch (token) { - case ITerminalSymbols.TokenNameIdentifier : - consumeToken(); - return pushParamName(); - case ITerminalSymbols.TokenNameEOF : - break; - default : - start = this.scanner.getCurrentTokenStartPosition(); - end = getEndPosition(); - if (end < start) start = this.tagSourceStart; - break; + case ITerminalSymbols.TokenNameIdentifier: + consumeToken(); + return pushParamName(); + case ITerminalSymbols.TokenNameEOF: + break; + default: + start = this.scanner.getCurrentTokenStartPosition(); + end = getEndPosition(); + if (end < start) + start = this.tagSourceStart; + break; } } catch (InvalidInputException e) { end = getEndPosition(); @@ -805,14 +990,17 @@ public abstract class AbstractCommentParser { this.currentTokenType = -1; // Report problem - if (this.sourceParser != null) this.sourceParser.problemReporter().javadocMissingParamName(start, end); + if (this.sourceParser != null) + this.sourceParser.problemReporter().javadocMissingParamName(start, + end); return false; } /* * Parse a qualified name and built a type reference if the syntax is valid. */ - protected Object parseQualifiedName(boolean reset) throws InvalidInputException { + protected Object parseQualifiedName(boolean reset) + throws InvalidInputException { // Reset identifier stack if requested if (reset) { @@ -822,55 +1010,55 @@ public abstract class AbstractCommentParser { // Scan tokens int primitiveToken = -1; - nextToken : for (int iToken = 0; ; iToken++) { + nextToken: for (int iToken = 0;; iToken++) { int token = readToken(); switch (token) { - case ITerminalSymbols.TokenNameIdentifier : - if (((iToken % 2) > 0)) { // identifiers must be odd tokens - break nextToken; - } - pushIdentifier(iToken == 0); - consumeToken(); - break; + case ITerminalSymbols.TokenNameIdentifier: + if (((iToken % 2) > 0)) { // identifiers must be odd tokens + break nextToken; + } + pushIdentifier(iToken == 0); + consumeToken(); + break; - case ITerminalSymbols.TokenNameDOT : - if ((iToken % 2) == 0) { // dots must be even tokens - throw new InvalidInputException(); - } - consumeToken(); - break; + case ITerminalSymbols.TokenNameDOT: + if ((iToken % 2) == 0) { // dots must be even tokens + throw new InvalidInputException(); + } + consumeToken(); + break; + + // case ITerminalSymbols.TokenNamevoid : + // case ITerminalSymbols.TokenNameboolean : + // case ITerminalSymbols.TokenNamebyte : + // case ITerminalSymbols.TokenNamechar : + // case ITerminalSymbols.TokenNamedouble : + // case ITerminalSymbols.TokenNamefloat : + // case ITerminalSymbols.TokenNameint : + // case ITerminalSymbols.TokenNamelong : + // case ITerminalSymbols.TokenNameshort : + // if (iToken > 0) { + // throw new InvalidInputException(); + // } + // pushIdentifier(true); + // primitiveToken = token; + // consumeToken(); + // break nextToken; -// case ITerminalSymbols.TokenNamevoid : -// case ITerminalSymbols.TokenNameboolean : -// case ITerminalSymbols.TokenNamebyte : -// case ITerminalSymbols.TokenNamechar : -// case ITerminalSymbols.TokenNamedouble : -// case ITerminalSymbols.TokenNamefloat : -// case ITerminalSymbols.TokenNameint : -// case ITerminalSymbols.TokenNamelong : -// case ITerminalSymbols.TokenNameshort : -// if (iToken > 0) { -// throw new InvalidInputException(); -// } -// pushIdentifier(true); -// primitiveToken = token; -// consumeToken(); -// break nextToken; - - default : - if (iToken == 0) { - return null; - } - if ((iToken % 2) == 0) { // cannot leave on a dot - // Reset position: we want to rescan last token - if (this.kind == DOM_PARSER && this.currentTokenType != -1) { - this.index = this.tokenPreviousPosition; - this.scanner.currentPosition = this.tokenPreviousPosition; - this.currentTokenType = -1; - } - throw new InvalidInputException(); + default: + if (iToken == 0) { + return null; + } + if ((iToken % 2) == 0) { // cannot leave on a dot + // Reset position: we want to rescan last token + if (this.kind == DOM_PARSER && this.currentTokenType != -1) { + this.index = this.tokenPreviousPosition; + this.scanner.currentPosition = this.tokenPreviousPosition; + this.currentTokenType = -1; } - break nextToken; + throw new InvalidInputException(); + } + break nextToken; } } // Reset position: we want to rescan last token @@ -884,25 +1072,53 @@ public abstract class AbstractCommentParser { } /* - * Parse a reference in @see tag + * Parse a reference in + * + * @see tag */ - protected boolean parseReference(boolean plain) throws InvalidInputException { + protected boolean parseReference(boolean plain) + throws InvalidInputException { Object typeRef = null; Object reference = null; int previousPosition = -1; int typeRefStartPosition = -1; - nextToken : while (this.index < this.scanner.eofPosition) { + nextToken: while (this.index < this.scanner.eofPosition) { previousPosition = this.index; int token = readToken(); switch (token) { - case ITerminalSymbols.TokenNameStringDoubleQuote : // @see "string" - case ITerminalSymbols.TokenNameStringSingleQuote : - int start = this.scanner.getCurrentTokenStartPosition(); + case ITerminalSymbols.TokenNameStringDoubleQuote: // @see "string" + case ITerminalSymbols.TokenNameStringSingleQuote: + int start = this.scanner.getCurrentTokenStartPosition(); + consumeToken(); + // If typeRef != null we may raise a warning here to let user + // know there's an unused reference... + // Currently as javadoc 1.4.2 ignore it, we do the same (see bug + // 69302) + if (typeRef != null) { + start = this.tagSourceEnd + 1; + previousPosition = start; + typeRef = null; + } + // verify end line (expecting empty or end comment) + if (verifyEndLine(previousPosition)) { + return true; + } + if (this.sourceParser != null) + this.sourceParser.problemReporter() + .javadocInvalidSeeReference(start, this.lineEnd); + return false; + case ITerminalSymbols.TokenNameLESS: // @see "label + consumeToken(); + start = this.scanner.getCurrentTokenStartPosition(); + if (parseHref()) { consumeToken(); - // If typeRef != null we may raise a warning here to let user know there's an unused reference... - // Currently as javadoc 1.4.2 ignore it, we do the same (see bug 69302) + // If typeRef != null we may raise a warning here to let + // user know there's an unused reference... + // Currently as javadoc 1.4.2 ignore it, we do the same (see + // bug 69302) if (typeRef != null) { - start = this.tagSourceEnd+1; + start = this.tagSourceEnd + 1; previousPosition = start; typeRef = null; } @@ -910,69 +1126,61 @@ public abstract class AbstractCommentParser { if (verifyEndLine(previousPosition)) { return true; } - if (this.sourceParser != null) this.sourceParser.problemReporter().javadocInvalidSeeReference(start, this.lineEnd); - return false; - case ITerminalSymbols.TokenNameLESS : // @see "label + if (this.sourceParser != null) + this.sourceParser + .problemReporter() + .javadocInvalidSeeReference(start, this.lineEnd); + } + return false; + case ITerminalSymbols.TokenNameERROR: + if (this.scanner.currentCharacter == '#') { // @see ...#member consumeToken(); - start = this.scanner.getCurrentTokenStartPosition(); - if (parseHref()) { - consumeToken(); - // If typeRef != null we may raise a warning here to let user know there's an unused reference... - // Currently as javadoc 1.4.2 ignore it, we do the same (see bug 69302) - if (typeRef != null) { - start = this.tagSourceEnd+1; - previousPosition = start; - typeRef = null; - } - // verify end line (expecting empty or end comment) - if (verifyEndLine(previousPosition)) { - return true; - } - if (this.sourceParser != null) this.sourceParser.problemReporter().javadocInvalidSeeReference(start, this.lineEnd); + reference = parseMember(typeRef); + if (reference != null) { + return pushSeeRef(reference, plain); } return false; - case ITerminalSymbols.TokenNameERROR : - if (this.scanner.currentCharacter == '#') { // @see ...#member - consumeToken(); - reference = parseMember(typeRef); - if (reference != null) { - return pushSeeRef(reference, plain); - } - return false; - } - break nextToken; - case ITerminalSymbols.TokenNameIdentifier : - if (typeRef == null) { - typeRefStartPosition = this.scanner.getCurrentTokenStartPosition(); - typeRef = parseQualifiedName(true); - break; - } - break nextToken; - default : - break nextToken; + } + break nextToken; + case ITerminalSymbols.TokenNameIdentifier: + if (typeRef == null) { + typeRefStartPosition = this.scanner + .getCurrentTokenStartPosition(); + typeRef = parseQualifiedName(true); + break; + } + break nextToken; + default: + break nextToken; } } - + // Verify that we got a reference - if (reference == null) reference = typeRef; + if (reference == null) + reference = typeRef; if (reference == null) { this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; this.currentTokenType = -1; - if (this.sourceParser != null) this.sourceParser.problemReporter().javadocMissingSeeReference(this.tagSourceStart, this.tagSourceEnd); + if (this.sourceParser != null) + this.sourceParser.problemReporter().javadocMissingSeeReference( + this.tagSourceStart, this.tagSourceEnd); return false; } // Reset position at the end of type reference - this.index = this.lastIdentifierEndPosition+1; + this.index = this.lastIdentifierEndPosition + 1; this.scanner.currentPosition = this.index; this.currentTokenType = -1; - // Verify that line end does not start with an open parenthese (which could be a constructor reference wrongly written...) + // Verify that line end does not start with an open parenthese (which + // could be a constructor reference wrongly written...) // See bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=47215 char ch = peekChar(); if (ch == '(') { - if (this.sourceParser != null) this.sourceParser.problemReporter().javadocInvalidSeeReference(typeRefStartPosition, this.lineEnd); + if (this.sourceParser != null) + this.sourceParser.problemReporter().javadocInvalidSeeReference( + typeRefStartPosition, this.lineEnd); return false; } @@ -981,12 +1189,17 @@ public abstract class AbstractCommentParser { this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; this.currentTokenType = -1; - int end = this.starPosition == -1 ? this.lineEnd : this.starPosition; - if (this.source[end]=='\n') end--; - if (this.sourceParser != null) this.sourceParser.problemReporter().javadocMalformedSeeReference(typeRefStartPosition, end); + int end = this.starPosition == -1 ? this.lineEnd + : this.starPosition; + if (this.source[end] == '\n') + end--; + if (this.sourceParser != null) + this.sourceParser + .problemReporter() + .javadocMalformedSeeReference(typeRefStartPosition, end); return false; } - + // Everything is OK, store reference return pushSeeRef(reference, plain); } @@ -997,14 +1210,18 @@ public abstract class AbstractCommentParser { protected abstract boolean parseReturn(); /* - * Parse @see tag declaration + * Parse + * + * @see tag declaration */ protected boolean parseSee(boolean plain) { int start = this.scanner.currentPosition; try { return parseReference(plain); } catch (InvalidInputException ex) { - if (this.sourceParser != null) this.sourceParser.problemReporter().javadocInvalidSeeReference(start, getEndPosition()); + if (this.sourceParser != null) + this.sourceParser.problemReporter().javadocInvalidSeeReference( + start, getEndPosition()); } // Reset position to avoid missing tokens when new line was encountered this.index = this.tokenPreviousPosition; @@ -1026,12 +1243,17 @@ public abstract class AbstractCommentParser { try { Object typeRef = parseQualifiedName(true); if (typeRef == null) { - if (this.sourceParser != null) this.sourceParser.problemReporter().javadocMissingThrowsClassName(this.tagSourceStart, this.tagSourceEnd); + if (this.sourceParser != null) + this.sourceParser.problemReporter() + .javadocMissingThrowsClassName(this.tagSourceStart, + this.tagSourceEnd); } else { return pushThrowName(typeRef, real); } } catch (InvalidInputException ex) { - if (this.sourceParser != null) this.sourceParser.problemReporter().javadocInvalidThrowsClass(start, getEndPosition()); + if (this.sourceParser != null) + this.sourceParser.problemReporter().javadocInvalidThrowsClass( + start, getEndPosition()); } return false; } @@ -1049,7 +1271,8 @@ public abstract class AbstractCommentParser { idx++; if (!(((c1 = Character.getNumericValue(this.source[idx++])) > 15 || c1 < 0) || ((c2 = Character.getNumericValue(this.source[idx++])) > 15 || c2 < 0) - || ((c3 = Character.getNumericValue(this.source[idx++])) > 15 || c3 < 0) || ((c4 = Character.getNumericValue(this.source[idx++])) > 15 || c4 < 0))) { + || ((c3 = Character.getNumericValue(this.source[idx++])) > 15 || c3 < 0) || ((c4 = Character + .getNumericValue(this.source[idx++])) > 15 || c4 < 0))) { c = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); } } @@ -1057,31 +1280,31 @@ public abstract class AbstractCommentParser { } /* - * push the consumeToken on the identifier stack. Increase the total number of identifier in the stack. + * push the consumeToken on the identifier stack. Increase the total number + * of identifier in the stack. */ protected void pushIdentifier(boolean newLength) { int stackLength = this.identifierStack.length; if (++this.identifierPtr >= stackLength) { - System.arraycopy( - this.identifierStack, 0, - this.identifierStack = new char[stackLength + 10][], 0, - stackLength); - System.arraycopy( - this.identifierPositionStack, 0, - this.identifierPositionStack = new long[stackLength + 10], 0, - stackLength); + System.arraycopy(this.identifierStack, 0, + this.identifierStack = new char[stackLength + 10][], 0, + stackLength); + System.arraycopy(this.identifierPositionStack, 0, + this.identifierPositionStack = new long[stackLength + 10], + 0, stackLength); } - this.identifierStack[this.identifierPtr] = this.scanner.getCurrentIdentifierSource(); - this.identifierPositionStack[this.identifierPtr] = (((long) this.scanner.startPosition) << 32) + (this.scanner.currentPosition - 1); + this.identifierStack[this.identifierPtr] = this.scanner + .getCurrentIdentifierSource(); + this.identifierPositionStack[this.identifierPtr] = (((long) this.scanner.startPosition) << 32) + + (this.scanner.currentPosition - 1); if (newLength) { stackLength = this.identifierLengthStack.length; if (++this.identifierLengthPtr >= stackLength) { - System.arraycopy( - this.identifierLengthStack, 0, - this.identifierLengthStack = new int[stackLength + 10], 0, - stackLength); + System.arraycopy(this.identifierLengthStack, 0, + this.identifierLengthStack = new int[stackLength + 10], + 0, stackLength); } this.identifierLengthStack[this.identifierLengthPtr] = 1; } else { @@ -1090,8 +1313,8 @@ public abstract class AbstractCommentParser { } /* - * Add a new obj on top of the ast stack. - * If new length is required, then add also a new length in length stack. + * Add a new obj on top of the ast stack. If new length is required, then + * add also a new length in length stack. */ protected void pushOnAstStack(Object node, boolean newLength) { @@ -1102,10 +1325,10 @@ public abstract class AbstractCommentParser { int stackLength = this.astStack.length; if (++this.astPtr >= stackLength) { - System.arraycopy( - this.astStack, 0, - this.astStack = new Object[stackLength + AstStackIncrement], 0, - stackLength); + System + .arraycopy(this.astStack, 0, + this.astStack = new Object[stackLength + + AstStackIncrement], 0, stackLength); this.astPtr = stackLength; } this.astStack[this.astPtr] = node; @@ -1113,10 +1336,9 @@ public abstract class AbstractCommentParser { if (newLength) { stackLength = this.astLengthStack.length; if (++this.astLengthPtr >= stackLength) { - System.arraycopy( - this.astLengthStack, 0, - this.astLengthStack = new int[stackLength + AstStackIncrement], 0, - stackLength); + System.arraycopy(this.astLengthStack, 0, + this.astLengthStack = new int[stackLength + + AstStackIncrement], 0, stackLength); } this.astLengthStack[this.astLengthPtr] = 1; } else { @@ -1145,11 +1367,11 @@ public abstract class AbstractCommentParser { protected abstract boolean pushThrowName(Object typeRef, boolean real); /* - * Read current character and move index position. - * Warning: scanner position is unchanged using this method! + * Read current character and move index position. Warning: scanner position + * is unchanged using this method! */ protected char readChar() { - + char c = this.source[this.index++]; if (c == '\\' && this.source[this.index] == 'u') { int c1, c2, c3, c4; @@ -1158,11 +1380,15 @@ public abstract class AbstractCommentParser { while (this.source[this.index] == 'u') this.index++; if (!(((c1 = Character.getNumericValue(this.source[this.index++])) > 15 || c1 < 0) - || ((c2 = Character.getNumericValue(this.source[this.index++])) > 15 || c2 < 0) - || ((c3 = Character.getNumericValue(this.source[this.index++])) > 15 || c3 < 0) || ((c4 = Character.getNumericValue(this.source[this.index++])) > 15 || c4 < 0))) { + || ((c2 = Character + .getNumericValue(this.source[this.index++])) > 15 || c2 < 0) + || ((c3 = Character + .getNumericValue(this.source[this.index++])) > 15 || c3 < 0) || ((c4 = Character + .getNumericValue(this.source[this.index++])) > 15 || c4 < 0))) { c = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); } else { - // TODO (frederic) currently reset to previous position, perhaps signal a syntax error would be more appropriate + // TODO (frederic) currently reset to previous position, perhaps + // signal a syntax error would be more appropriate this.index = pos; } } @@ -1176,14 +1402,27 @@ public abstract class AbstractCommentParser { if (this.currentTokenType < 0) { this.tokenPreviousPosition = this.scanner.currentPosition; this.currentTokenType = this.scanner.getNextToken(); - if (this.scanner.currentPosition > (this.lineEnd+1)) { // be sure to be on next line (lineEnd is still on the same line) + if (this.scanner.currentPosition > (this.lineEnd + 1)) { // be + // sure + // to be + // on + // next + // line + // (lineEnd + // is + // still + // on + // the + // same + // line) this.lineStarted = false; while (this.currentTokenType == ITerminalSymbols.TokenNameMULTIPLY) { this.currentTokenType = this.scanner.getNextToken(); } } this.index = this.scanner.currentPosition; - this.lineStarted = true; // after having read a token, line is obviously started... + this.lineStarted = true; // after having read a token, line is + // obviously started... } return this.currentTokenType; } @@ -1193,7 +1432,7 @@ public abstract class AbstractCommentParser { consumeToken(); return token; } - + /* * Refresh start position and length of an inline tag. */ @@ -1203,49 +1442,46 @@ public abstract class AbstractCommentParser { public String toString() { StringBuffer buffer = new StringBuffer(); - int startPos = this.scanner.currentPosition this.source.length) return "behind the EOF\n\n" + new String(this.source); //$NON-NLS-1$ - + char front[] = new char[startPos]; System.arraycopy(this.source, 0, front, 0, startPos); - + int middleLength = (endPos - 1) - startPos + 1; char middle[]; if (middleLength > -1) { middle = new char[middleLength]; - System.arraycopy( - this.source, - startPos, - middle, - 0, - middleLength); + System.arraycopy(this.source, startPos, middle, 0, middleLength); } else { middle = CharOperation.NO_CHAR; } - + char end[] = new char[this.source.length - (endPos - 1)]; - System.arraycopy( - this.source, - (endPos - 1) + 1, - end, - 0, - this.source.length - (endPos - 1) - 1); - + System.arraycopy(this.source, (endPos - 1) + 1, end, 0, + this.source.length - (endPos - 1) - 1); + buffer.append(front); - if (this.scanner.currentPosition"); //$NON-NLS-1$ + if (this.scanner.currentPosition < this.index) { + buffer + .append("\n===============================\nScanner current position here -->"); //$NON-NLS-1$ } else { - buffer.append("\n===============================\nParser index here -->"); //$NON-NLS-1$ + buffer + .append("\n===============================\nParser index here -->"); //$NON-NLS-1$ } buffer.append(middle); - if (this.scanner.currentPosition (this.lineEnd+1)) { // be sure to be on next line (lineEnd is still on the same line) + while (this.index > (this.lineEnd + 1)) { // be sure to be on next + // line (lineEnd is still on + // the same line) if (this.linePtr < this.lastLinePtr) { this.lineEnd = this.scanner.getLineEnd(++this.linePtr) - 1; } else { @@ -1272,8 +1510,9 @@ public abstract class AbstractCommentParser { } /* - * Verify that end of the line only contains space characters or end of comment. - * Note that end of comment may be preceeding by several contiguous '*' chars. + * Verify that end of the line only contains space characters or end of + * comment. Note that end of comment may be preceeding by several contiguous + * '*' chars. */ private boolean verifyEndLine(int textPosition) { int startPosition = this.index; @@ -1282,34 +1521,35 @@ public abstract class AbstractCommentParser { char ch = readChar(); nextChar: while (true) { switch (ch) { - case '\r': - case '\n': + case '\r': + case '\n': + if (this.kind == DOM_PARSER) { + parseTag(); + pushText(textPosition, previousPosition); + } + this.index = previousPosition; + return true; + case '\u000c': /* FORM FEED */ + case ' ': /* SPACE */ + case '\t': /* HORIZONTAL TABULATION */ + if (this.starPosition >= 0) + break nextChar; + break; + case '*': + this.starPosition = previousPosition; + break; + case '/': + if (this.starPosition >= textPosition) { if (this.kind == DOM_PARSER) { parseTag(); - pushText(textPosition, previousPosition); + pushText(textPosition, this.starPosition); } - this.index = previousPosition; return true; - case '\u000c' : /* FORM FEED */ - case ' ' : /* SPACE */ - case '\t' : /* HORIZONTAL TABULATION */ - if (this.starPosition >= 0) break nextChar; - break; - case '*': - this.starPosition = previousPosition; - break; - case '/': - if (this.starPosition >= textPosition) { - if (this.kind == DOM_PARSER) { - parseTag(); - pushText(textPosition, this.starPosition); - } - return true; - } - default : - // leave loop - break nextChar; - + } + default: + // leave loop + break nextChar; + } previousPosition = this.index; ch = readChar(); @@ -1319,8 +1559,8 @@ public abstract class AbstractCommentParser { } /* - * Verify that some text exists after a @return tag. Text must be different than - * end of comment which may be preceeding by several '*' chars. + * Verify that some text exists after a @return tag. Text must be different + * than end of comment which may be preceeding by several '*' chars. */ private boolean verifyCharsAfterReturnTag(int startPosition) { // Whitespace or inline tag closing brace @@ -1330,25 +1570,28 @@ public abstract class AbstractCommentParser { while (Character.isWhitespace(ch)) { malformed = false; previousPosition = this.index; - ch = readChar(); + ch = readChar(); } // End of comment this.starPosition = -1; - nextChar: while (this.index= startPosition) { // valid only if a star was previous character - return false; - } - default : - // valid if any other character is encountered, even white spaces - this.index = startPosition; - return !malformed; - + case '*': + // valid whatever the number of star before last '/' + this.starPosition = previousPosition; + break; + case '/': + if (this.starPosition >= startPosition) { // valid only if a + // star was previous + // character + return false; + } + default: + // valid if any other character is encountered, even white + // spaces + this.index = startPosition; + return !malformed; + } previousPosition = this.index; ch = readChar(); @@ -1358,43 +1601,45 @@ public abstract class AbstractCommentParser { } /* - * Verify characters after a name matches one of following conditions: - * 1- first character is a white space - * 2- first character is a closing brace *and* we're currently parsing an inline tag - * 3- are the end of comment (several contiguous star ('*') characters may be - * found before the last slash ('/') character). + * Verify characters after a name matches one of following conditions: 1- + * first character is a white space 2- first character is a closing brace + * *and* we're currently parsing an inline tag 3- are the end of comment + * (several contiguous star ('*') characters may be found before the last + * slash ('/') character). */ private boolean verifySpaceOrEndComment() { int startPosition = this.index; // Whitespace or inline tag closing brace char ch = peekChar(); switch (ch) { - case '}': - return this.inlineTagStarted; - default: - if (Character.isWhitespace(ch)) { - return true; - } + case '}': + return this.inlineTagStarted; + default: + if (Character.isWhitespace(ch)) { + return true; + } } // End of comment int previousPosition = this.index; this.starPosition = -1; ch = readChar(); - nextChar: while (this.index= startPosition) { // valid only if a star was previous character - return true; - } - default : - // invalid whatever other character, even white spaces - this.index = startPosition; - return false; - + case '*': + // valid whatever the number of star before last '/' + this.starPosition = previousPosition; + break; + case '/': + if (this.starPosition >= startPosition) { // valid only if a + // star was previous + // character + return true; + } + default: + // invalid whatever other character, even white spaces + this.index = startPosition; + return false; + } previousPosition = this.index; ch = readChar(); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/NLSLine.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/NLSLine.java index 18f7135..cf8b0ed 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/NLSLine.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/NLSLine.java @@ -20,44 +20,43 @@ public class NLSLine { private List elements; - public NLSLine() { this.elements = new ArrayList(); } - + /** * Adds a NLS element to this line. */ public void add(StringLiteral element) { this.elements.add(element); } - + /** * returns an Iterator over NLSElements */ public Iterator iterator() { return this.elements.iterator(); } - + public StringLiteral get(int index) { return (StringLiteral) this.elements.get(index); } - + public void set(int index, StringLiteral literal) { this.elements.set(index, literal); } - + public boolean exists(int index) { return index >= 0 && index < this.elements.size(); } - - public int size(){ + + public int size() { return this.elements.size(); } - + public String toString() { - StringBuffer result= new StringBuffer(); - for (Iterator iter= iterator(); iter.hasNext(); ) { + StringBuffer result = new StringBuffer(); + for (Iterator iter = iterator(); iter.hasNext();) { result.append("\t"); //$NON-NLS-1$ result.append(iter.next().toString()); result.append("\n"); //$NON-NLS-1$ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/Parser.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/Parser.java index 052ec44..b27c78c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/Parser.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/Parser.java @@ -57,7 +57,8 @@ import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IPath; -public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicInformation { +public class Parser implements ITerminalSymbols, CompilerModifiers, + ParserBasicInformation { protected final static int StackIncrement = 255; protected int stateStackTop; @@ -99,10 +100,10 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI /** * ClassDeclaration Constructor. - * + * * @param s * @param sess - * Description of Parameter + * Description of Parameter * @see */ public Parser(IFile fileToParse) { @@ -127,9 +128,12 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI } public void initializeScanner() { - this.scanner = new Scanner(false /* comment */, false /* whitespace */, this.options - .getSeverity(CompilerOptions.NonExternalizedString) != ProblemSeverities.Ignore /* nls */, false, false, - this.options.taskTags/* taskTags */, this.options.taskPriorites/* taskPriorities */, true/* isTaskCaseSensitive */); + this.scanner = new Scanner( + false /* comment */, + false /* whitespace */, + this.options.getSeverity(CompilerOptions.NonExternalizedString) != ProblemSeverities.Ignore /* nls */, + false, false, this.options.taskTags/* taskTags */, + this.options.taskPriorites/* taskPriorities */, true/* isTaskCaseSensitive */); } /** @@ -142,18 +146,21 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI /** * This method will throw the SyntaxError. It will add the good lines and * columns to the Error - * + * * @param error - * the error message + * the error message * @throws SyntaxError - * the error raised + * the error raised */ private void throwSyntaxError(String error) { int problemStartPosition = scanner.getCurrentTokenStartPosition(); int problemEndPosition = scanner.getCurrentTokenEndPosition() + 1; - if (scanner.source.length <= problemEndPosition && problemEndPosition > 0) { + if (scanner.source.length <= problemEndPosition + && problemEndPosition > 0) { problemEndPosition = scanner.source.length - 1; - if (problemStartPosition > 0 && problemStartPosition >= problemEndPosition && problemEndPosition > 0) { + if (problemStartPosition > 0 + && problemStartPosition >= problemEndPosition + && problemEndPosition > 0) { problemStartPosition = problemEndPosition - 1; } } @@ -163,18 +170,20 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI /** * This method will throw the SyntaxError. It will add the good lines and * columns to the Error - * + * * @param error - * the error message + * the error message * @throws SyntaxError - * the error raised + * the error raised */ // private void throwSyntaxError(String error, int startRow) { // throw new SyntaxError(startRow, 0, " ", error); // } - private void throwSyntaxError(String error, int problemStartPosition, int problemEndPosition) { + private void throwSyntaxError(String error, int problemStartPosition, + int problemEndPosition) { if (referenceContext != null) { - problemReporter.phpParsingError(new String[] { error }, problemStartPosition, problemEndPosition, referenceContext, + problemReporter.phpParsingError(new String[] { error }, + problemStartPosition, problemEndPosition, referenceContext, compilationUnit.compilationResult); } throw new SyntaxError(1, 0, " ", error); @@ -186,9 +195,11 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI reportSyntaxError(error, problemStartPosition, problemEndPosition + 1); } - private void reportSyntaxError(String error, int problemStartPosition, int problemEndPosition) { + private void reportSyntaxError(String error, int problemStartPosition, + int problemEndPosition) { if (referenceContext != null) { - problemReporter.phpParsingError(new String[] { error }, problemStartPosition, problemEndPosition, referenceContext, + problemReporter.phpParsingError(new String[] { error }, + problemStartPosition, problemEndPosition, referenceContext, compilationUnit.compilationResult); } } @@ -210,8 +221,10 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI token = scanner.getNextToken(); if (Scanner.DEBUG) { int currentEndPosition = scanner.getCurrentTokenEndPosition(); - int currentStartPosition = scanner.getCurrentTokenStartPosition(); - System.out.print(currentStartPosition + "," + currentEndPosition + ": "); + int currentStartPosition = scanner + .getCurrentTokenStartPosition(); + System.out.print(currentStartPosition + "," + + currentEndPosition + ": "); System.out.println(scanner.toStringAction(token)); } } catch (InvalidInputException e) { @@ -246,7 +259,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI initialize(phpMode, null); } - protected void initialize(boolean phpMode, IdentifierIndexManager indexManager) { + protected void initialize(boolean phpMode, + IdentifierIndexManager indexManager) { compilationUnit = null; referenceContext = null; this.includesList = new ArrayList(); @@ -301,7 +315,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI } if (token != TokenNameEOF) { if (token == TokenNameERROR) { - throwSyntaxError("Scanner error (Found unknown token: " + scanner.toStringAction(token) + ")"); + throwSyntaxError("Scanner error (Found unknown token: " + + scanner.toStringAction(token) + ")"); } if (token == TokenNameRPAREN) { throwSyntaxError("Too many closing ')'; end-of-file not reached."); @@ -357,7 +372,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI this.fMethodVariables = variables; MethodDeclaration methodDecl = new MethodDeclaration(null); - methodDecl.declarationSourceStart = scanner.getCurrentTokenStartPosition(); + methodDecl.declarationSourceStart = scanner + .getCurrentTokenStartPosition(); methodDecl.modifiers = this.modifiers; methodDecl.type = MethodDeclaration.METHOD_DEFINITION; try { @@ -367,7 +383,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI return; } finally { int sourceEnd = methodDecl.sourceEnd; - if (sourceEnd <= 0 || methodDecl.declarationSourceStart > sourceEnd) { + if (sourceEnd <= 0 + || methodDecl.declarationSourceStart > sourceEnd) { sourceEnd = methodDecl.declarationSourceStart + 1; } methodDecl.sourceEnd = sourceEnd; @@ -386,7 +403,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // System.out.print(Util.bind("parser.syntaxRecovery")); //$NON-NLS-1$ // System.out.println("--------------------------"); //$NON-NLS-1$ // System.out.println(compilationUnit); - // System.out.println("----------------------------------"); //$NON-NLS-1$ + // System.out.println("----------------------------------"); + // //$NON-NLS-1$ // } // } else { if (diet & VERBOSE_RECOVERY) { @@ -397,13 +415,18 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI } // } if (scanner.recordLineSeparator) { - compilationUnit.compilationResult.lineSeparatorPositions = scanner.getLineEnds(); + compilationUnit.compilationResult.lineSeparatorPositions = scanner + .getLineEnds(); } if (scanner.taskTags != null) { for (int i = 0; i < scanner.foundTaskCount; i++) { - problemReporter().task(new String(scanner.foundTaskTags[i]), new String(scanner.foundTaskMessages[i]), - scanner.foundTaskPriorities[i] == null ? null : new String(scanner.foundTaskPriorities[i]), - scanner.foundTaskPositions[i][0], scanner.foundTaskPositions[i][1]); + problemReporter().task( + new String(scanner.foundTaskTags[i]), + new String(scanner.foundTaskMessages[i]), + scanner.foundTaskPriorities[i] == null ? null + : new String(scanner.foundTaskPriorities[i]), + scanner.foundTaskPositions[i][0], + scanner.foundTaskPositions[i][1]); } } compilationUnit.imports = new ImportReference[includesList.size()]; @@ -426,20 +449,34 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI return null; } if (branchStatement && statement != null) { - // reportSyntaxError("Unreachable code", statement.sourceStart, + // reportSyntaxError("Unreachable code", + // statement.sourceStart, // statement.sourceEnd); - if (! (statement instanceof BreakStatement)) { - /* don't give an error for break statement following return statement - Technically it's unreachable code, but in switch-case it's recommended to - avoid accidental fall-through later when editing the code */ - problemReporter.unreachableCode(new String(scanner.getCurrentIdentifierSource()), statement.sourceStart, - statement.sourceEnd, referenceContext, compilationUnit.compilationResult); + if (!(statement instanceof BreakStatement)) { + /* + * don't give an error for break statement following + * return statement Technically it's unreachable code, + * but in switch-case it's recommended to avoid + * accidental fall-through later when editing the code + */ + problemReporter.unreachableCode(new String(scanner + .getCurrentIdentifierSource()), + statement.sourceStart, statement.sourceEnd, + referenceContext, + compilationUnit.compilationResult); } } - if ((token == TokenNameRBRACE) || (token == TokenNamecase) || (token == TokenNamedefault) || (token == TokenNameelse) - || (token == TokenNameelseif) || (token == TokenNameendif) || (token == TokenNameendfor) - || (token == TokenNameendforeach) || (token == TokenNameendwhile) || (token == TokenNameendswitch) - || (token == TokenNameenddeclare) || (token == TokenNameEOF) || (token == TokenNameERROR)) { + if ((token == TokenNameRBRACE) || (token == TokenNamecase) + || (token == TokenNamedefault) + || (token == TokenNameelse) + || (token == TokenNameelseif) + || (token == TokenNameendif) + || (token == TokenNameendfor) + || (token == TokenNameendforeach) + || (token == TokenNameendwhile) + || (token == TokenNameendswitch) + || (token == TokenNameenddeclare) + || (token == TokenNameEOF) || (token == TokenNameERROR)) { return createBlock(blockStart, blockStatements); } branchStatement = checkUnreachableStatements(statement); @@ -453,18 +490,44 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI } try { while (token != TokenNameEOF) { - if ((token == TokenNameRBRACE) || (token == TokenNamecase) || (token == TokenNamedefault) || (token == TokenNameelse) - || (token == TokenNameelseif) || (token == TokenNameendif) || (token == TokenNameendfor) - || (token == TokenNameendforeach) || (token == TokenNameendwhile) || (token == TokenNameendswitch) - || (token == TokenNameenddeclare) || (token == TokenNameEOF) || (token == TokenNameERROR)) { + if ((token == TokenNameRBRACE) + || (token == TokenNamecase) + || (token == TokenNamedefault) + || (token == TokenNameelse) + || (token == TokenNameelseif) + || (token == TokenNameendif) + || (token == TokenNameendfor) + || (token == TokenNameendforeach) + || (token == TokenNameendwhile) + || (token == TokenNameendswitch) + || (token == TokenNameenddeclare) + || (token == TokenNameEOF) + || (token == TokenNameERROR)) { return createBlock(blockStart, blockStatements); } - if (token == TokenNameif || token == TokenNameswitch || token == TokenNamefor || token == TokenNamewhile - || token == TokenNamedo || token == TokenNameforeach || token == TokenNamecontinue || token == TokenNamebreak - || token == TokenNamereturn || token == TokenNameexit || token == TokenNameecho || token == TokenNameECHO_INVISIBLE - || token == TokenNameglobal || token == TokenNamestatic || token == TokenNameunset || token == TokenNamefunction - || token == TokenNamedeclare || token == TokenNametry || token == TokenNamecatch || token == TokenNamethrow - || token == TokenNamefinal || token == TokenNameabstract || token == TokenNameclass || token == TokenNameinterface) { + if (token == TokenNameif || token == TokenNameswitch + || token == TokenNamefor + || token == TokenNamewhile + || token == TokenNamedo + || token == TokenNameforeach + || token == TokenNamecontinue + || token == TokenNamebreak + || token == TokenNamereturn + || token == TokenNameexit + || token == TokenNameecho + || token == TokenNameECHO_INVISIBLE + || token == TokenNameglobal + || token == TokenNamestatic + || token == TokenNameunset + || token == TokenNamefunction + || token == TokenNamedeclare + || token == TokenNametry + || token == TokenNamecatch + || token == TokenNamethrow + || token == TokenNamefinal + || token == TokenNameabstract + || token == TokenNameclass + || token == TokenNameinterface) { break; } // System.out.println(scanner.toStringAction(token)); @@ -486,9 +549,12 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI * @return */ private boolean checkUnreachableStatements(Statement statement) { - if (statement instanceof ReturnStatement || statement instanceof ContinueStatement || statement instanceof BreakStatement) { + if (statement instanceof ReturnStatement + || statement instanceof ContinueStatement + || statement instanceof BreakStatement) { return true; - } else if (statement instanceof IfStatement && ((IfStatement) statement).checkUnreachable) { + } else if (statement instanceof IfStatement + && ((IfStatement) statement).checkUnreachable) { return true; } return false; @@ -549,7 +615,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI throwSyntaxError("')' expected after 'if' condition."); } // create basic IfStatement - IfStatement ifStatement = new IfStatement(expression, null, null, sourceStart, -1); + IfStatement ifStatement = new IfStatement(expression, null, null, + sourceStart, -1); if (token == TokenNameCOLON) { getNextToken(); ifStatementColon(ifStatement); @@ -824,8 +891,10 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI } return statement; } else if (token == TokenNamefunction) { - MethodDeclaration methodDecl = new MethodDeclaration(this.compilationUnit.compilationResult); - methodDecl.declarationSourceStart = scanner.getCurrentTokenStartPosition(); + MethodDeclaration methodDecl = new MethodDeclaration( + this.compilationUnit.compilationResult); + methodDecl.declarationSourceStart = scanner + .getCurrentTokenStartPosition(); methodDecl.modifiers = AccDefault; methodDecl.type = MethodDeclaration.FUNCTION_DEFINITION; try { @@ -833,7 +902,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI functionDefinition(methodDecl); } finally { sourceEnd = methodDecl.sourceEnd; - if (sourceEnd <= 0 || methodDecl.declarationSourceStart > sourceEnd) { + if (sourceEnd <= 0 + || methodDecl.declarationSourceStart > sourceEnd) { sourceEnd = methodDecl.declarationSourceStart + 1; } methodDecl.declarationSourceEnd = sourceEnd; @@ -904,14 +974,19 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI throwSyntaxError("';' expected after 'throw' exxpression."); } return statement; - } else if (token == TokenNamefinal || token == TokenNameabstract || token == TokenNameclass || token == TokenNameinterface) { + } else if (token == TokenNamefinal || token == TokenNameabstract + || token == TokenNameclass || token == TokenNameinterface) { try { - TypeDeclaration typeDecl = new TypeDeclaration(this.compilationUnit.compilationResult); - typeDecl.declarationSourceStart = scanner.getCurrentTokenStartPosition(); - typeDecl.declarationSourceEnd = scanner.getCurrentTokenEndPosition(); + TypeDeclaration typeDecl = new TypeDeclaration( + this.compilationUnit.compilationResult); + typeDecl.declarationSourceStart = scanner + .getCurrentTokenStartPosition(); + typeDecl.declarationSourceEnd = scanner + .getCurrentTokenEndPosition(); typeDecl.name = new char[] { ' ' }; // default super class - typeDecl.superclass = new SingleTypeReference(TypeConstants.OBJECT, 0); + typeDecl.superclass = new SingleTypeReference( + TypeConstants.OBJECT, 0); compilationUnit.types.add(typeDecl); pushOnAstStack(typeDecl); unticked_class_declaration_statement(typeDecl); @@ -943,10 +1018,12 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI return statement; } else { if (token == TokenNameRBRACE) { - reportSyntaxError("';' expected after expression (Found token: " + scanner.toStringAction(token) + ")"); + reportSyntaxError("';' expected after expression (Found token: " + + scanner.toStringAction(token) + ")"); } else { if (token != TokenNameINLINE_HTML && token != TokenNameEOF) { - throwSyntaxError("';' expected after expression (Found token: " + scanner.toStringAction(token) + ")"); + throwSyntaxError("';' expected after expression (Found token: " + + scanner.toStringAction(token) + ")"); } getNextToken(); } @@ -1067,8 +1144,11 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // | '$' '{' expr '}' if (token == TokenNameVariable) { if (fMethodVariables != null) { - VariableInfo info = new VariableInfo(scanner.getCurrentTokenStartPosition(), VariableInfo.LEVEL_GLOBAL_VAR); - fMethodVariables.put(new String(scanner.getCurrentIdentifierSource()), info); + VariableInfo info = new VariableInfo(scanner + .getCurrentTokenStartPosition(), + VariableInfo.LEVEL_GLOBAL_VAR); + fMethodVariables.put(new String(scanner + .getCurrentIdentifierSource()), info); } addVariableSet(set); getNextToken(); @@ -1097,8 +1177,11 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI while (true) { if (token == TokenNameVariable) { if (fMethodVariables != null) { - VariableInfo info = new VariableInfo(scanner.getCurrentTokenStartPosition(), VariableInfo.LEVEL_STATIC_VAR); - fMethodVariables.put(new String(scanner.getCurrentIdentifierSource()), info); + VariableInfo info = new VariableInfo(scanner + .getCurrentTokenStartPosition(), + VariableInfo.LEVEL_STATIC_VAR); + fMethodVariables.put(new String(scanner + .getCurrentIdentifierSource()), info); } addVariableSet(set); getNextToken(); @@ -1156,9 +1239,13 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI if (token == TokenNameIdentifier || token > TokenNameKEYWORD) { typeDecl.name = scanner.getCurrentIdentifierSource(); if (token > TokenNameKEYWORD) { - problemReporter.phpKeywordWarning(new String[] { scanner.toStringAction(token) }, scanner.getCurrentTokenStartPosition(), - scanner.getCurrentTokenEndPosition(), referenceContext, compilationUnit.compilationResult); - // throwSyntaxError("Don't use a keyword for interface declaration [" + problemReporter.phpKeywordWarning(new String[] { scanner + .toStringAction(token) }, scanner + .getCurrentTokenStartPosition(), scanner + .getCurrentTokenEndPosition(), referenceContext, + compilationUnit.compilationResult); + // throwSyntaxError("Don't use a keyword for interface + // declaration [" // + scanner.toStringAction(token) + "].", // typeDecl.sourceStart, typeDecl.sourceEnd); } @@ -1166,7 +1253,9 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI interface_extends_list(typeDecl); } else { typeDecl.name = new char[] { ' ' }; - throwSyntaxError("Interface name expected after keyword 'interface'.", typeDecl.sourceStart, typeDecl.sourceEnd); + throwSyntaxError( + "Interface name expected after keyword 'interface'.", + typeDecl.sourceStart, typeDecl.sourceEnd); return; } } else { @@ -1182,9 +1271,13 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI if (token == TokenNameIdentifier || token > TokenNameKEYWORD) { typeDecl.name = scanner.getCurrentIdentifierSource(); if (token > TokenNameKEYWORD) { - problemReporter.phpKeywordWarning(new String[] { scanner.toStringAction(token) }, scanner.getCurrentTokenStartPosition(), - scanner.getCurrentTokenEndPosition(), referenceContext, compilationUnit.compilationResult); - // throwSyntaxError("Don't use a keyword for class declaration [" + + problemReporter.phpKeywordWarning(new String[] { scanner + .toStringAction(token) }, scanner + .getCurrentTokenStartPosition(), scanner + .getCurrentTokenEndPosition(), referenceContext, + compilationUnit.compilationResult); + // throwSyntaxError("Don't use a keyword for class + // declaration [" + // scanner.toStringAction(token) + "].", // typeDecl.sourceStart, typeDecl.sourceEnd); } @@ -1205,7 +1298,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI implements_list(typeDecl); } else { typeDecl.name = new char[] { ' ' }; - throwSyntaxError("Class name expected after keyword 'class'.", typeDecl.sourceStart, typeDecl.sourceEnd); + throwSyntaxError("Class name expected after keyword 'class'.", + typeDecl.sourceStart, typeDecl.sourceEnd); return; } } @@ -1221,7 +1315,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI } } if (token == TokenNameRBRACE) { - typeDecl.declarationSourceEnd = scanner.getCurrentTokenEndPosition(); + typeDecl.declarationSourceEnd = scanner + .getCurrentTokenEndPosition(); getNextToken(); } else { throwSyntaxError("'}' expected at end of class body."); @@ -1304,7 +1399,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI if (token == TokenNameIdentifier) { char[] ident = scanner.getCurrentIdentifierSource(); // TODO make this code working better: - // SingleTypeReference ref = ParserUtil.getTypeReference(scanner, + // SingleTypeReference ref = + // ParserUtil.getTypeReference(scanner, // includesList, ident); // if (ref != null) { // typeDecl.superclass = ref; @@ -1361,8 +1457,12 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI do { try { class_statement(list); - if (token == TokenNamepublic || token == TokenNameprotected || token == TokenNameprivate || token == TokenNamestatic - || token == TokenNameabstract || token == TokenNamefinal || token == TokenNamefunction || token == TokenNamevar + if (token == TokenNamepublic || token == TokenNameprotected + || token == TokenNameprivate + || token == TokenNamestatic + || token == TokenNameabstract + || token == TokenNamefinal + || token == TokenNamefunction || token == TokenNamevar || token == TokenNameconst) { continue; } @@ -1380,8 +1480,14 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // try to find keywords // to parse the rest of the string while (token != TokenNameEOF) { - if (token == TokenNamepublic || token == TokenNameprotected || token == TokenNameprivate || token == TokenNamestatic - || token == TokenNameabstract || token == TokenNamefinal || token == TokenNamefunction || token == TokenNamevar + if (token == TokenNamepublic + || token == TokenNameprotected + || token == TokenNameprivate + || token == TokenNamestatic + || token == TokenNameabstract + || token == TokenNamefinal + || token == TokenNamefunction + || token == TokenNamevar || token == TokenNameconst) { break; } @@ -1409,8 +1515,10 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI if (token == TokenNamevar) { checkAndSetModifiers(AccPublic); - problemReporter.phpVarDeprecatedWarning(scanner.getCurrentTokenStartPosition(), scanner.getCurrentTokenEndPosition(), - referenceContext, compilationUnit.compilationResult); + problemReporter.phpVarDeprecatedWarning(scanner + .getCurrentTokenStartPosition(), scanner + .getCurrentTokenEndPosition(), referenceContext, + compilationUnit.compilationResult); getNextToken(); class_variable_declaration(declarationSourceStart, list); } else if (token == TokenNameconst) { @@ -1426,8 +1534,10 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI if (!hasModifiers) { checkAndSetModifiers(AccPublic); } - MethodDeclaration methodDecl = new MethodDeclaration(this.compilationUnit.compilationResult); - methodDecl.declarationSourceStart = scanner.getCurrentTokenStartPosition(); + MethodDeclaration methodDecl = new MethodDeclaration( + this.compilationUnit.compilationResult); + methodDecl.declarationSourceStart = scanner + .getCurrentTokenStartPosition(); methodDecl.modifiers = this.modifiers; methodDecl.type = MethodDeclaration.METHOD_DEFINITION; try { @@ -1435,7 +1545,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI functionDefinition(methodDecl); } finally { int sourceEnd = methodDecl.sourceEnd; - if (sourceEnd <= 0 || methodDecl.declarationSourceStart > sourceEnd) { + if (sourceEnd <= 0 + || methodDecl.declarationSourceStart > sourceEnd) { sourceEnd = methodDecl.declarationSourceStart + 1; } methodDecl.declarationSourceEnd = sourceEnd; @@ -1450,7 +1561,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI } } - private void class_constant_declaration(int declarationSourceStart, ArrayList list) { + private void class_constant_declaration(int declarationSourceStart, + ArrayList list) { // class_constant_declaration ',' T_STRING '=' static_scalar // | T_CONST T_STRING '=' static_scalar if (token != TokenNameconst) { @@ -1462,11 +1574,14 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI if (token != TokenNameIdentifier) { throwSyntaxError("Identifier expected in class const declaration."); } - FieldDeclaration fieldDeclaration = new FieldDeclaration(scanner.getCurrentIdentifierSource(), scanner - .getCurrentTokenStartPosition(), scanner.getCurrentTokenEndPosition()); + FieldDeclaration fieldDeclaration = new FieldDeclaration(scanner + .getCurrentIdentifierSource(), scanner + .getCurrentTokenStartPosition(), scanner + .getCurrentTokenEndPosition()); fieldDeclaration.modifiers = this.modifiers; fieldDeclaration.declarationSourceStart = declarationSourceStart; - fieldDeclaration.declarationSourceEnd = scanner.getCurrentTokenEndPosition(); + fieldDeclaration.declarationSourceEnd = scanner + .getCurrentTokenEndPosition(); fieldDeclaration.modifiersSourceStart = declarationSourceStart; // fieldDeclaration.type list.add(fieldDeclaration); @@ -1553,7 +1668,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI return foundToken; } - private void class_variable_declaration(int declarationSourceStart, ArrayList list) { + private void class_variable_declaration(int declarationSourceStart, + ArrayList list) { // class_variable_declaration: // class_variable_declaration ',' T_VARIABLE // | class_variable_declaration ',' T_VARIABLE '=' static_scalar @@ -1563,18 +1679,24 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI do { if (token == TokenNameVariable) { classVariable = scanner.getCurrentIdentifierSource(); - // indexManager.addIdentifierInformation('v', classVariable, buf, -1, + // indexManager.addIdentifierInformation('v', classVariable, + // buf, -1, // -1); - FieldDeclaration fieldDeclaration = new FieldDeclaration(classVariable, scanner.getCurrentTokenStartPosition(), scanner - .getCurrentTokenEndPosition()); + FieldDeclaration fieldDeclaration = new FieldDeclaration( + classVariable, scanner.getCurrentTokenStartPosition(), + scanner.getCurrentTokenEndPosition()); fieldDeclaration.modifiers = this.modifiers; fieldDeclaration.declarationSourceStart = declarationSourceStart; - fieldDeclaration.declarationSourceEnd = scanner.getCurrentTokenEndPosition(); + fieldDeclaration.declarationSourceEnd = scanner + .getCurrentTokenEndPosition(); fieldDeclaration.modifiersSourceStart = declarationSourceStart; list.add(fieldDeclaration); if (fTypeVariables != null) { - VariableInfo info = new VariableInfo(scanner.getCurrentTokenStartPosition(), VariableInfo.LEVEL_CLASS_UNIT); - fTypeVariables.put(new String(scanner.getCurrentIdentifierSource()), info); + VariableInfo info = new VariableInfo(scanner + .getCurrentTokenStartPosition(), + VariableInfo.LEVEL_CLASS_UNIT); + fTypeVariables.put(new String(scanner + .getCurrentIdentifierSource()), info); } getNextToken(); if (token == TokenNameEQUAL) { @@ -1613,8 +1735,12 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI typeDecl.methods = new AbstractMethodDeclaration[] { methodDecl }; } else { AbstractMethodDeclaration[] newMethods; - System.arraycopy(typeDecl.methods, 0, newMethods = new AbstractMethodDeclaration[typeDecl.methods.length + 1], 0, - typeDecl.methods.length); + System + .arraycopy( + typeDecl.methods, + 0, + newMethods = new AbstractMethodDeclaration[typeDecl.methods.length + 1], + 0, typeDecl.methods.length); newMethods[typeDecl.methods.length] = methodDecl; typeDecl.methods = newMethods; } @@ -1630,8 +1756,10 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI functionDeclarator(methodDecl); if (token == TokenNameSEMICOLON) { if (!isAbstract) { - methodDecl.sourceEnd = scanner.getCurrentTokenStartPosition() - 1; - throwSyntaxError("Body declaration expected for method: " + new String(methodDecl.selector)); + methodDecl.sourceEnd = scanner + .getCurrentTokenStartPosition() - 1; + throwSyntaxError("Body declaration expected for method: " + + new String(methodDecl.selector)); } getNextToken(); return; @@ -1654,8 +1782,11 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI if (Scanner.isIdentifierOrKeyword(token)) { methodDecl.selector = scanner.getCurrentIdentifierSource(); if (token > TokenNameKEYWORD) { - problemReporter.phpKeywordWarning(new String[] { scanner.toStringAction(token) }, scanner.getCurrentTokenStartPosition(), - scanner.getCurrentTokenEndPosition(), referenceContext, compilationUnit.compilationResult); + problemReporter.phpKeywordWarning(new String[] { scanner + .toStringAction(token) }, scanner + .getCurrentTokenStartPosition(), scanner + .getCurrentTokenEndPosition(), referenceContext, + compilationUnit.compilationResult); } getNextToken(); if (token == TokenNameLPAREN) { @@ -1688,7 +1819,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI non_empty_parameter_list(methodDecl, true); } - private void non_empty_parameter_list(MethodDeclaration methodDecl, boolean empty_allowed) { + private void non_empty_parameter_list(MethodDeclaration methodDecl, + boolean empty_allowed) { // optional_class_type T_VARIABLE // | optional_class_type '&' T_VARIABLE // | optional_class_type '&' T_VARIABLE '=' static_scalar @@ -1700,10 +1832,13 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // | non_empty_parameter_list ',' optional_class_type T_VARIABLE '=' // static_scalar char[] typeIdentifier = null; - if (token == TokenNameIdentifier || token == TokenNamearray || token == TokenNameVariable || token == TokenNameAND) { + if (token == TokenNameIdentifier || token == TokenNamearray + || token == TokenNameVariable || token == TokenNameAND) { HashSet set = peekVariableSet(); while (true) { - if (token == TokenNameIdentifier || token == TokenNamearray) {// feature req. #1254275 + if (token == TokenNameIdentifier || token == TokenNamearray) {// feature + // req. + // #1254275 typeIdentifier = scanner.getCurrentIdentifierSource(); getNextToken(); } @@ -1714,12 +1849,17 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI if (fMethodVariables != null) { VariableInfo info; if (methodDecl.type == MethodDeclaration.FUNCTION_DEFINITION) { - info = new VariableInfo(scanner.getCurrentTokenStartPosition(), VariableInfo.LEVEL_FUNCTION_DEFINITION); + info = new VariableInfo(scanner + .getCurrentTokenStartPosition(), + VariableInfo.LEVEL_FUNCTION_DEFINITION); } else { - info = new VariableInfo(scanner.getCurrentTokenStartPosition(), VariableInfo.LEVEL_METHOD_DEFINITION); + info = new VariableInfo(scanner + .getCurrentTokenStartPosition(), + VariableInfo.LEVEL_METHOD_DEFINITION); } info.typeIdentifier = typeIdentifier; - fMethodVariables.put(new String(scanner.getCurrentIdentifierSource()), info); + fMethodVariables.put(new String(scanner + .getCurrentIdentifierSource()), info); } addVariableSet(set); getNextToken(); @@ -1784,7 +1924,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI if (token == TokenNameCOLON || token == TokenNameSEMICOLON) { getNextToken(); if (token == TokenNameRBRACE) { - // empty case; assumes that the '}' token belongs to the wrapping + // empty case; assumes that the '}' token belongs to the + // wrapping // switch statement - #1371992 break; } @@ -1808,14 +1949,16 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // statementList(); // } else { - throwSyntaxError("':' character expected after 'case' constant (Found token: " + scanner.toStringAction(token) + ")"); + throwSyntaxError("':' character expected after 'case' constant (Found token: " + + scanner.toStringAction(token) + ")"); } } else { // TokenNamedefault getNextToken(); if (token == TokenNameCOLON || token == TokenNameSEMICOLON) { getNextToken(); if (token == TokenNameRBRACE) { - // empty default case; ; assumes that the '}' token belongs to the + // empty default case; ; assumes that the '}' token + // belongs to the // wrapping switch statement - #1371992 break; } @@ -2035,16 +2178,21 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI iState.checkUnreachable = false; } else { int off = b.statements.length - 1; - if (!(b.statements[off] instanceof ReturnStatement) && !(b.statements[off] instanceof ContinueStatement) + if (!(b.statements[off] instanceof ReturnStatement) + && !(b.statements[off] instanceof ContinueStatement) && !(b.statements[off] instanceof BreakStatement)) { - if (!(b.statements[off] instanceof IfStatement) || !((IfStatement) b.statements[off]).checkUnreachable) { + if (!(b.statements[off] instanceof IfStatement) + || !((IfStatement) b.statements[off]).checkUnreachable) { iState.checkUnreachable = false; } } } } else { - if (!(s instanceof ReturnStatement) && !(s instanceof ContinueStatement) && !(s instanceof BreakStatement)) { - if (!(s instanceof IfStatement) || !((IfStatement) s).checkUnreachable) { + if (!(s instanceof ReturnStatement) + && !(s instanceof ContinueStatement) + && !(s instanceof BreakStatement)) { + if (!(s instanceof IfStatement) + || !((IfStatement) s).checkUnreachable) { iState.checkUnreachable = false; } } @@ -2212,11 +2360,12 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI if (Scanner.TRACE) { System.out.println("TRACE: expr()"); } - return expr_without_variable(true,null); + return expr_without_variable(true, null); // } } - private Expression expr_without_variable(boolean only_variable, UninitializedVariableHandler initHandler) { + private Expression expr_without_variable(boolean only_variable, + UninitializedVariableHandler initHandler) { int exprSourceStart = scanner.getCurrentTokenStartPosition(); int exprSourceEnd = scanner.getCurrentTokenEndPosition(); Expression expression = new Expression(); @@ -2387,7 +2536,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // } else { // encaps_list(); // if (token != TokenNameEncapsedString0) { - // throwSyntaxError("\'`\' expected at end of string" + "(Found token: " + + // throwSyntaxError("\'`\' expected at end of string" + "(Found + // token: " + // scanner.toStringAction(token) + " )"); // } // } @@ -2410,7 +2560,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // } else { // encaps_list(); // if (token != TokenNameEncapsedString1) { - // throwSyntaxError("\'\'\' expected at end of string" + "(Found token: " + // throwSyntaxError("\'\'\' expected at end of string" + "(Found + // token: " // + scanner.toStringAction(token) + " )"); // } else { // expression = new @@ -2438,7 +2589,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // } else { // encaps_list(); // if (token != TokenNameEncapsedString2) { - // throwSyntaxError("'\"' expected at end of string" + "(Found token: " + + // throwSyntaxError("'\"' expected at end of string" + "(Found + // token: " + // scanner.toStringAction(token) + " )"); // } else { // expression = new @@ -2453,12 +2605,16 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // } // break; case TokenNameStringDoubleQuote: - expression = new StringLiteralDQ(scanner.getCurrentStringLiteralSource(), scanner.getCurrentTokenStartPosition(), scanner + expression = new StringLiteralDQ(scanner + .getCurrentStringLiteralSource(), scanner + .getCurrentTokenStartPosition(), scanner .getCurrentTokenEndPosition()); common_scalar(); break; case TokenNameStringSingleQuote: - expression = new StringLiteralSQ(scanner.getCurrentStringLiteralSource(), scanner.getCurrentTokenStartPosition(), scanner + expression = new StringLiteralSQ(scanner + .getCurrentStringLiteralSource(), scanner + .getCurrentTokenStartPosition(), scanner .getCurrentTokenEndPosition()); common_scalar(); break; @@ -2486,11 +2642,15 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI } array_pair_list(); if (token != TokenNameRPAREN) { - throwSyntaxError("')' or ',' expected after keyword 'array'" + "(Found token: " + scanner.toStringAction(token) + ")"); + throwSyntaxError("')' or ',' expected after keyword 'array'" + + "(Found token: " + + scanner.toStringAction(token) + ")"); } getNextToken(); } else { - throwSyntaxError("'(' expected after keyword 'array'" + "(Found token: " + scanner.toStringAction(token) + ")"); + throwSyntaxError("'(' expected after keyword 'array'" + + "(Found token: " + scanner.toStringAction(token) + + ")"); } break; case TokenNamelist: @@ -2559,16 +2719,27 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI if (lhs != null) { expression = lhs; } - if (lhs != null && lhs instanceof FieldReference && token != TokenNameEQUAL && token != TokenNamePLUS_EQUAL - && token != TokenNameMINUS_EQUAL && token != TokenNameMULTIPLY_EQUAL && token != TokenNameDIVIDE_EQUAL - && token != TokenNameDOT_EQUAL && token != TokenNameREMAINDER_EQUAL && token != TokenNameAND_EQUAL - && token != TokenNameOR_EQUAL && token != TokenNameXOR_EQUAL && token != TokenNameRIGHT_SHIFT_EQUAL + if (lhs != null && lhs instanceof FieldReference + && token != TokenNameEQUAL + && token != TokenNamePLUS_EQUAL + && token != TokenNameMINUS_EQUAL + && token != TokenNameMULTIPLY_EQUAL + && token != TokenNameDIVIDE_EQUAL + && token != TokenNameDOT_EQUAL + && token != TokenNameREMAINDER_EQUAL + && token != TokenNameAND_EQUAL + && token != TokenNameOR_EQUAL + && token != TokenNameXOR_EQUAL + && token != TokenNameRIGHT_SHIFT_EQUAL && token != TokenNameLEFT_SHIFT_EQUAL) { FieldReference ref = (FieldReference) lhs; if (!containsVariableSet(ref.token)) { - if (null==initHandler || initHandler.reportError()) { - problemReporter.uninitializedLocalVariable(new String(ref.token), ref.sourceStart, ref.sourceEnd, - referenceContext, compilationUnit.compilationResult); + if (null == initHandler + || initHandler.reportError()) { + problemReporter.uninitializedLocalVariable( + new String(ref.token), ref.sourceStart, + ref.sourceEnd, referenceContext, + compilationUnit.compilationResult); } addVariableSet(ref.token); } @@ -2589,30 +2760,41 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI SingleTypeReference classRef = class_name_reference(); ctor_arguments(); if (classRef != null) { - if (lhs != null && lhs instanceof FieldReference) { + if (lhs != null + && lhs instanceof FieldReference) { // example: // $var = & new Object(); if (fMethodVariables != null) { - VariableInfo lhsInfo = new VariableInfo(((FieldReference) lhs).sourceStart); + VariableInfo lhsInfo = new VariableInfo( + ((FieldReference) lhs).sourceStart); lhsInfo.reference = classRef; lhsInfo.typeIdentifier = classRef.token; - fMethodVariables.put(new String(((FieldReference) lhs).token), lhsInfo); + fMethodVariables.put(new String( + ((FieldReference) lhs).token), + lhsInfo); rememberedVar = true; } } } } else { Expression rhs = variable(false, false); - if (rhs != null && rhs instanceof FieldReference && lhs != null && lhs instanceof FieldReference) { + if (rhs != null && rhs instanceof FieldReference + && lhs != null + && lhs instanceof FieldReference) { // example: // $var = &$ref; if (fMethodVariables != null) { - VariableInfo rhsInfo = (VariableInfo) fMethodVariables.get(((FieldReference) rhs).token); - if (rhsInfo != null && rhsInfo.reference != null) { - VariableInfo lhsInfo = new VariableInfo(((FieldReference) lhs).sourceStart); + VariableInfo rhsInfo = (VariableInfo) fMethodVariables + .get(((FieldReference) rhs).token); + if (rhsInfo != null + && rhsInfo.reference != null) { + VariableInfo lhsInfo = new VariableInfo( + ((FieldReference) lhs).sourceStart); lhsInfo.reference = rhsInfo.reference; lhsInfo.typeIdentifier = rhsInfo.typeIdentifier; - fMethodVariables.put(new String(((FieldReference) lhs).token), lhsInfo); + fMethodVariables.put(new String( + ((FieldReference) lhs).token), + lhsInfo); rememberedVar = true; } } @@ -2625,32 +2807,44 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // example: // $var = $ref; if (fMethodVariables != null) { - VariableInfo rhsInfo = (VariableInfo) fMethodVariables.get(((FieldReference) rhs).token); - if (rhsInfo != null && rhsInfo.reference != null) { - VariableInfo lhsInfo = new VariableInfo(((FieldReference) lhs).sourceStart); + VariableInfo rhsInfo = (VariableInfo) fMethodVariables + .get(((FieldReference) rhs).token); + if (rhsInfo != null + && rhsInfo.reference != null) { + VariableInfo lhsInfo = new VariableInfo( + ((FieldReference) lhs).sourceStart); lhsInfo.reference = rhsInfo.reference; lhsInfo.typeIdentifier = rhsInfo.typeIdentifier; - fMethodVariables.put(new String(((FieldReference) lhs).token), lhsInfo); + fMethodVariables.put(new String( + ((FieldReference) lhs).token), + lhsInfo); rememberedVar = true; } } - } else if (rhs != null && rhs instanceof SingleTypeReference) { + } else if (rhs != null + && rhs instanceof SingleTypeReference) { // example: // $var = new Object(); if (fMethodVariables != null) { - VariableInfo lhsInfo = new VariableInfo(((FieldReference) lhs).sourceStart); + VariableInfo lhsInfo = new VariableInfo( + ((FieldReference) lhs).sourceStart); lhsInfo.reference = (SingleTypeReference) rhs; lhsInfo.typeIdentifier = ((SingleTypeReference) rhs).token; - fMethodVariables.put(new String(((FieldReference) lhs).token), lhsInfo); + fMethodVariables.put(new String( + ((FieldReference) lhs).token), + lhsInfo); rememberedVar = true; } } } } - if (rememberedVar == false && lhs != null && lhs instanceof FieldReference) { + if (rememberedVar == false && lhs != null + && lhs instanceof FieldReference) { if (fMethodVariables != null) { - VariableInfo lhsInfo = new VariableInfo(((FieldReference) lhs).sourceStart); - fMethodVariables.put(new String(((FieldReference) lhs).token), lhsInfo); + VariableInfo lhsInfo = new VariableInfo( + ((FieldReference) lhs).sourceStart); + fMethodVariables.put(new String( + ((FieldReference) lhs).token), lhsInfo); } } break; @@ -2677,7 +2871,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI break; default: if (!only_variable) { - throwSyntaxError("Variable expression not allowed (found token '" + scanner.toStringAction(token) + "')."); + throwSyntaxError("Variable expression not allowed (found token '" + + scanner.toStringAction(token) + "')."); } if (lhs != null) { expression = lhs; @@ -2693,7 +2888,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // System.out.println(scanner.getCurrentTokenStartPosition()); // System.out.println(scanner.getCurrentTokenEndPosition()); - throwSyntaxError("Error in expression (found token '" + scanner.toStringAction(token) + "')."); + throwSyntaxError("Error in expression (found token '" + + scanner.toStringAction(token) + "')."); } } return expression; @@ -2733,7 +2929,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI break; case TokenNameAND_AND: getNextToken(); - expression = new AND_AND_Expression(expression, expr(), token); + expression = new AND_AND_Expression(expression, expr(), + token); break; case TokenNameEQUAL_EQUAL: getNextToken(); @@ -2769,9 +2966,11 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI getNextToken(); TypeReference classRef = class_name_reference(); if (classRef != null) { - expression = new InstanceOfExpression(expression, classRef, OperatorIds.INSTANCEOF); + expression = new InstanceOfExpression(expression, + classRef, OperatorIds.INSTANCEOF); expression.sourceStart = exprSourceStart; - expression.sourceEnd = scanner.getCurrentTokenEndPosition(); + expression.sourceEnd = scanner + .getCurrentTokenEndPosition(); } break; case TokenNameQUESTION: @@ -2783,7 +2982,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI getNextToken(); Expression valueIfFalse = expr(); - expression = new ConditionalExpression(expression, valueIfTrue, valueIfFalse); + expression = new ConditionalExpression(expression, + valueIfTrue, valueIfFalse); break; default: return expression; @@ -2795,7 +2995,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI getNextToken(); return expression; } - if (token == TokenNameRBRACE || token == TokenNameRPAREN || token == TokenNameRBRACKET) { + if (token == TokenNameRBRACE || token == TokenNameRPAREN + || token == TokenNameRBRACKET) { getNextToken(); return expression; } @@ -2812,7 +3013,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI System.out.println("TRACE: class_name_reference()"); } if (token == TokenNameIdentifier) { - ref = new SingleTypeReference(scanner.getCurrentIdentifierSource(), scanner.getCurrentTokenStartPosition()); + ref = new SingleTypeReference(scanner.getCurrentIdentifierSource(), + scanner.getCurrentTokenStartPosition()); getNextToken(); } else { ref = null; @@ -2843,7 +3045,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // dynamic_class_name_variable_property // | /* empty */ if (Scanner.TRACE) { - System.out.println("TRACE: dynamic_class_name_variable_properties()"); + System.out + .println("TRACE: dynamic_class_name_variable_properties()"); } while (token == TokenNameMINUS_GREATER) { dynamic_class_name_variable_property(); @@ -2980,7 +3183,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // } // } while (true); // } - private Expression variable_without_objects(boolean lefthandside, boolean ignoreVar) { + private Expression variable_without_objects(boolean lefthandside, + boolean ignoreVar) { // variable_without_objects: // reference_variable // | simple_indirect_reference reference_variable @@ -3034,24 +3238,31 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI if (defineName != null) { // does this identifier contain only uppercase characters? if (defineName.length == 3) { - if (defineName[0] == 'd' && defineName[1] == 'i' && defineName[2] == 'e') { + if (defineName[0] == 'd' && defineName[1] == 'i' + && defineName[2] == 'e') { defineName = null; } } else if (defineName.length == 4) { - if (defineName[0] == 't' && defineName[1] == 'r' && defineName[2] == 'u' && defineName[3] == 'e') { + if (defineName[0] == 't' && defineName[1] == 'r' + && defineName[2] == 'u' && defineName[3] == 'e') { defineName = null; - } else if (defineName[0] == 'n' && defineName[1] == 'u' && defineName[2] == 'l' && defineName[3] == 'l') { + } else if (defineName[0] == 'n' && defineName[1] == 'u' + && defineName[2] == 'l' && defineName[3] == 'l') { defineName = null; } } else if (defineName.length == 5) { - if (defineName[0] == 'f' && defineName[1] == 'a' && defineName[2] == 'l' && defineName[3] == 's' && defineName[4] == 'e') { + if (defineName[0] == 'f' && defineName[1] == 'a' + && defineName[2] == 'l' && defineName[3] == 's' + && defineName[4] == 'e') { defineName = null; } } if (defineName != null) { for (int i = 0; i < defineName.length; i++) { if (Character.isLowerCase(defineName[i])) { - problemReporter.phpUppercaseIdentifierWarning(startPos, endPos, referenceContext, compilationUnit.compilationResult); + problemReporter.phpUppercaseIdentifierWarning( + startPos, endPos, referenceContext, + compilationUnit.compilationResult); break; } } @@ -3071,7 +3282,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI } else { functionName = new String(ident); } - throwSyntaxError("')' expected in function call (" + functionName + ")."); + throwSyntaxError("')' expected in function call (" + + functionName + ")."); } getNextToken(); } @@ -3096,7 +3308,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // | non_empty_function_call_parameter_list ',' variable // | non_empty_function_call_parameter_list ',' '&' w_variable if (Scanner.TRACE) { - System.out.println("TRACE: non_empty_function_call_parameter_list()"); + System.out + .println("TRACE: non_empty_function_call_parameter_list()"); } UninitializedVariableHandler initHandler = new UninitializedVariableHandler(); initHandler.setFunctionName(functionName); @@ -3144,7 +3357,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI variable_without_objects(false, false); } - private Expression base_variable_with_function_calls(boolean lefthandside, boolean ignoreVar) { + private Expression base_variable_with_function_calls(boolean lefthandside, + boolean ignoreVar) { // base_variable_with_function_calls: // base_variable // | function_call @@ -3179,7 +3393,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // // '$' // //| simple_indirect_reference '$' // } - private Expression reference_variable(boolean lefthandside, boolean ignoreVar) { + private Expression reference_variable(boolean lefthandside, + boolean ignoreVar) { // reference_variable: // reference_variable '[' dim_offset ']' // | reference_variable '{' expr '}' @@ -3199,7 +3414,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI } getNextToken(); } else if (token == TokenNameLBRACKET) { - // To remove "ref = null;" here, is probably better than the patch + // To remove "ref = null;" here, is probably better than the + // patch // commented in #1368081 - axelcl getNextToken(); if (token != TokenNameRBRACKET) { @@ -3230,8 +3446,10 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // reportSyntaxError("The local variable " + new // String(scanner.getCurrentIdentifierSource()) // + " may not have been initialized"); - problemReporter.uninitializedLocalVariable(new String(scanner.getCurrentIdentifierSource()), scanner - .getCurrentTokenStartPosition(), scanner.getCurrentTokenEndPosition(), referenceContext, + problemReporter.uninitializedLocalVariable(new String( + scanner.getCurrentIdentifierSource()), scanner + .getCurrentTokenStartPosition(), scanner + .getCurrentTokenEndPosition(), referenceContext, compilationUnit.compilationResult); } } else { @@ -3239,7 +3457,9 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI addVariableSet(); } } - FieldReference ref = new FieldReference(scanner.getCurrentIdentifierSource(), scanner.getCurrentTokenStartPosition()); + FieldReference ref = new FieldReference(scanner + .getCurrentIdentifierSource(), scanner + .getCurrentTokenStartPosition()); getNextToken(); return ref; } else { @@ -3354,7 +3574,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // base_variable_with_function_calls T_OBJECT_OPERATOR // object_property method_or_not variable_properties // | base_variable_with_function_calls - Expression ref = base_variable_with_function_calls(lefthandside, ignoreVar); + Expression ref = base_variable_with_function_calls(lefthandside, + ignoreVar); if (token == TokenNameMINUS_GREATER) { ref = null; getNextToken(); @@ -3417,12 +3638,22 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI endPos = scanner.getCurrentTokenEndPosition(); getNextToken(); - if (token == TokenNameEQUAL || token == TokenNamePLUS_EQUAL || token == TokenNameMINUS_EQUAL - || token == TokenNameMULTIPLY_EQUAL || token == TokenNameDIVIDE_EQUAL || token == TokenNameDOT_EQUAL - || token == TokenNameREMAINDER_EQUAL || token == TokenNameAND_EQUAL || token == TokenNameOR_EQUAL - || token == TokenNameXOR_EQUAL || token == TokenNameRIGHT_SHIFT_EQUAL || token == TokenNameLEFT_SHIFT_EQUAL) { - String error = "Assignment operator '" + scanner.toStringAction(token) + "' not allowed after identifier '" - + new String(ident) + "' (use 'define(...)' to define constants)."; + if (token == TokenNameEQUAL || token == TokenNamePLUS_EQUAL + || token == TokenNameMINUS_EQUAL + || token == TokenNameMULTIPLY_EQUAL + || token == TokenNameDIVIDE_EQUAL + || token == TokenNameDOT_EQUAL + || token == TokenNameREMAINDER_EQUAL + || token == TokenNameAND_EQUAL + || token == TokenNameOR_EQUAL + || token == TokenNameXOR_EQUAL + || token == TokenNameRIGHT_SHIFT_EQUAL + || token == TokenNameLEFT_SHIFT_EQUAL) { + String error = "Assignment operator '" + + scanner.toStringAction(token) + + "' not allowed after identifier '" + + new String(ident) + + "' (use 'define(...)' to define constants)."; reportSyntaxError(error); } @@ -3447,24 +3678,31 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI if (defineName != null) { // does this identifier contain only uppercase characters? if (defineName.length == 3) { - if (defineName[0] == 'd' && defineName[1] == 'i' && defineName[2] == 'e') { + if (defineName[0] == 'd' && defineName[1] == 'i' + && defineName[2] == 'e') { defineName = null; } } else if (defineName.length == 4) { - if (defineName[0] == 't' && defineName[1] == 'r' && defineName[2] == 'u' && defineName[3] == 'e') { + if (defineName[0] == 't' && defineName[1] == 'r' + && defineName[2] == 'u' && defineName[3] == 'e') { defineName = null; - } else if (defineName[0] == 'n' && defineName[1] == 'u' && defineName[2] == 'l' && defineName[3] == 'l') { + } else if (defineName[0] == 'n' && defineName[1] == 'u' + && defineName[2] == 'l' && defineName[3] == 'l') { defineName = null; } } else if (defineName.length == 5) { - if (defineName[0] == 'f' && defineName[1] == 'a' && defineName[2] == 'l' && defineName[3] == 's' && defineName[4] == 'e') { + if (defineName[0] == 'f' && defineName[1] == 'a' + && defineName[2] == 'l' && defineName[3] == 's' + && defineName[4] == 'e') { defineName = null; } } if (defineName != null) { for (int i = 0; i < defineName.length; i++) { if (Character.isLowerCase(defineName[i])) { - problemReporter.phpUppercaseIdentifierWarning(startPos, endPos, referenceContext, compilationUnit.compilationResult); + problemReporter.phpUppercaseIdentifierWarning( + startPos, endPos, referenceContext, + compilationUnit.compilationResult); break; } } @@ -3488,7 +3726,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI } non_empty_function_call_parameter_list(functionName); if (token != TokenNameRPAREN) { - throwSyntaxError("')' expected in function call (" + functionName + ")."); + throwSyntaxError("')' expected in function call (" + + functionName + ")."); } getNextToken(); } @@ -3849,7 +4088,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI /** * Parse and check the include file name - * + * * @param includeToken */ private void checkFileName(int includeToken) { @@ -3866,7 +4105,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI if (token == TokenNameRPAREN) { getNextToken(); } else { - throwSyntaxError("')' expected for keyword '" + scanner.toStringAction(includeToken) + "'"); + throwSyntaxError("')' expected for keyword '" + + scanner.toStringAction(includeToken) + "'"); } } char[] currTokenSource = scanner.getCurrentTokenSource(start); @@ -3881,7 +4121,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI tokens = new char[1][]; tokens[0] = currTokenSource; - ImportReference impt = new ImportReference(tokens, currTokenSource, start, scanner.getCurrentTokenEndPosition(), false); + ImportReference impt = new ImportReference(tokens, currTokenSource, + start, scanner.getCurrentTokenEndPosition(), false); impt.declarationSourceEnd = impt.sourceEnd; impt.declarationEnd = impt.declarationSourceEnd; // endPosition is just before the ; @@ -3892,13 +4133,15 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI StringLiteral literal = (StringLiteral) expression; char[] includeName = literal.source(); if (includeName.length == 0) { - reportSyntaxError("Empty filename after keyword '" + scanner.toStringAction(includeToken) + "'", literal.sourceStart, - literal.sourceStart + 1); + reportSyntaxError("Empty filename after keyword '" + + scanner.toStringAction(includeToken) + "'", + literal.sourceStart, literal.sourceStart + 1); } String includeNameString = new String(includeName); if (literal instanceof StringLiteralDQ) { if (includeNameString.indexOf('$') >= 0) { - // assuming that the filename contains a variable => no filename check + // assuming that the filename contains a variable => no + // filename check return; } } @@ -3908,26 +4151,35 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI } if (file != null) { // check the filename: - // System.out.println(new String(compilationUnit.getFileName())+" - "+ + // System.out.println(new + // String(compilationUnit.getFileName())+" - "+ // expression.toStringExpression()); IProject project = file.getProject(); if (project != null) { - IPath path = PHPFileUtil.determineFilePath(includeNameString, file, project); + IPath path = PHPFileUtil.determineFilePath( + includeNameString, file, project); if (path == null) { // SyntaxError: "File: << >> doesn't exist in project." - String[] args = { expression.toStringExpression(), project.getLocation().toString() }; - problemReporter.phpIncludeNotExistWarning(args, literal.sourceStart, literal.sourceEnd, referenceContext, + String[] args = { expression.toStringExpression(), + project.getLocation().toString() }; + problemReporter.phpIncludeNotExistWarning(args, + literal.sourceStart, literal.sourceEnd, + referenceContext, compilationUnit.compilationResult); } else { try { String filePath = path.toString(); - String ext = file.getRawLocation().getFileExtension(); - int fileExtensionLength = ext == null ? 0 : ext.length() + 1; + String ext = file.getRawLocation() + .getFileExtension(); + int fileExtensionLength = ext == null ? 0 : ext + .length() + 1; IFile f = PHPFileUtil.createFile(path, project); - impt.tokens = CharOperation.splitOn('/', filePath.toCharArray(), 0, filePath.length() - fileExtensionLength); + impt.tokens = CharOperation.splitOn('/', filePath + .toCharArray(), 0, filePath.length() + - fileExtensionLength); impt.setFile(f); } catch (Exception e) { // the file is outside of the workspace @@ -4192,8 +4444,9 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI ASTNode[] noAstNodes = new ASTNode[AstStackIncrement]; public CompilationUnitDeclaration compilationUnit; /* - * the result from parse() - */ + * the result from + * parse() + */ protected ReferenceContext referenceContext; @@ -4211,7 +4464,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI */ public ProblemReporter problemReporter() { if (scanner.recordLineSeparator) { - compilationUnit.compilationResult.lineSeparatorPositions = scanner.getLineEnds(); + compilationUnit.compilationResult.lineSeparatorPositions = scanner + .getLineEnds(); } problemReporter.referenceContext = referenceContext; return problemReporter; @@ -4229,9 +4483,11 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // int[] leftCount = { 0, 0, 0 }; // int[] rightCount = { 0, 0, 0 }; // int[] depths = { 0, 0, 0 }; - // int[][] leftPositions = new int[][] { new int[10], new int[10], new int[10] + // int[][] leftPositions = new int[][] { new int[10], new int[10], new + // int[10] + // }; + // int[][] leftDepths = new int[][] { new int[10], new int[10], new int[10] // }; - // int[][] leftDepths = new int[][] { new int[10], new int[10], new int[10] }; // int[][] rightPositions = new int[][] { new int[10], new int[10], new // int[10] }; // int[][] rightDepths = new int[][] { new int[10], new int[10], new int[10] @@ -4265,7 +4521,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // } // isWhiteSpace = CharOperation.isWhitespace(scanner.currentCharacter); // // } - // } while (isWhiteSpace && (scanner.currentPosition < scanner.eofPosition)); + // } while (isWhiteSpace && (scanner.currentPosition < + // scanner.eofPosition)); // // -------consume token until } is found--------- // switch (scanner.currentCharacter) { // case '{': { @@ -4285,7 +4542,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // if (index == rightPositions[CurlyBracket].length) { // System.arraycopy(rightPositions[CurlyBracket], 0, // (rightPositions[CurlyBracket] = new int[index * 2]), 0, index); - // System.arraycopy(rightDepths[CurlyBracket], 0, (rightDepths[CurlyBracket] = + // System.arraycopy(rightDepths[CurlyBracket], 0, (rightDepths[CurlyBracket] + // = // new int[index * 2]), 0, index); // } // rightPositions[CurlyBracket][index] = scanner.startPosition; @@ -4309,7 +4567,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // if (index == rightPositions[RoundBracket].length) { // System.arraycopy(rightPositions[RoundBracket], 0, // (rightPositions[RoundBracket] = new int[index * 2]), 0, index); - // System.arraycopy(rightDepths[RoundBracket], 0, (rightDepths[RoundBracket] = + // System.arraycopy(rightDepths[RoundBracket], 0, (rightDepths[RoundBracket] + // = // new int[index * 2]), 0, index); // } // rightPositions[RoundBracket][index] = scanner.startPosition; @@ -4321,7 +4580,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // if (index == leftPositions[SquareBracket].length) { // System.arraycopy(leftPositions[SquareBracket], 0, // (leftPositions[SquareBracket] = new int[index * 2]), 0, index); - // System.arraycopy(leftDepths[SquareBracket], 0, (leftDepths[SquareBracket] = + // System.arraycopy(leftDepths[SquareBracket], 0, (leftDepths[SquareBracket] + // = // new int[index * 2]), 0, index); // } // leftPositions[SquareBracket][index] = scanner.startPosition; @@ -4333,7 +4593,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // if (index == rightPositions[SquareBracket].length) { // System.arraycopy(rightPositions[SquareBracket], 0, // (rightPositions[SquareBracket] = new int[index * 2]), 0, index); - // System.arraycopy(rightDepths[SquareBracket], 0, (rightDepths[SquareBracket] + // System.arraycopy(rightDepths[SquareBracket], 0, + // (rightDepths[SquareBracket] // = new int[index * 2]), 0, index); // } // rightPositions[SquareBracket][index] = scanner.startPosition; @@ -4420,11 +4681,14 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // } // if ((c1 = Character.getNumericValue(source[scanner.currentPosition++])) > // 15 || c1 < 0 - // || (c2 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + // || (c2 = Character.getNumericValue(source[scanner.currentPosition++])) > + // 15 // || c2 < 0 - // || (c3 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + // || (c3 = Character.getNumericValue(source[scanner.currentPosition++])) > + // 15 // || c3 < 0 - // || (c4 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + // || (c4 = Character.getNumericValue(source[scanner.currentPosition++])) > + // 15 // || c4 < 0) { //error // // don't // // care of the @@ -4451,11 +4715,14 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // } // if ((c1 = Character.getNumericValue(source[scanner.currentPosition++])) > // 15 || c1 < 0 - // || (c2 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + // || (c2 = Character.getNumericValue(source[scanner.currentPosition++])) > + // 15 // || c2 < 0 - // || (c3 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + // || (c3 = Character.getNumericValue(source[scanner.currentPosition++])) > + // 15 // || c3 < 0 - // || (c4 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + // || (c4 = Character.getNumericValue(source[scanner.currentPosition++])) > + // 15 // || c4 < 0) { //error // // don't // // care of the @@ -4516,11 +4783,14 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // } // if ((c1 = Character.getNumericValue(source[scanner.currentPosition++])) > // 15 || c1 < 0 - // || (c2 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + // || (c2 = Character.getNumericValue(source[scanner.currentPosition++])) > + // 15 // || c2 < 0 - // || (c3 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + // || (c3 = Character.getNumericValue(source[scanner.currentPosition++])) > + // 15 // || c3 < 0 - // || (c4 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + // || (c4 = Character.getNumericValue(source[scanner.currentPosition++])) > + // 15 // || c4 < 0) { //error // // don't // // care of the @@ -4547,11 +4817,14 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // } // if ((c1 = Character.getNumericValue(source[scanner.currentPosition++])) > // 15 || c1 < 0 - // || (c2 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + // || (c2 = Character.getNumericValue(source[scanner.currentPosition++])) > + // 15 // || c2 < 0 - // || (c3 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + // || (c3 = Character.getNumericValue(source[scanner.currentPosition++])) > + // 15 // || c3 < 0 - // || (c4 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + // || (c4 = Character.getNumericValue(source[scanner.currentPosition++])) > + // 15 // || c4 < 0) { //error // // don't // // care of the @@ -4642,14 +4915,16 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI // // too many opening brackets ? // for (int i = rightCount[kind]; i < leftCount[kind]; i++) { // anomaliesDetected = true; - // problemReporter.unmatchedBracket(leftPositions[kind][leftCount[kind] - i - + // problemReporter.unmatchedBracket(leftPositions[kind][leftCount[kind] - i + // - // 1], referenceContext, // compilationUnit.compilationResult); // } // // too many closing brackets ? // for (int i = leftCount[kind]; i < rightCount[kind]; i++) { // anomaliesDetected = true; - // problemReporter.unmatchedBracket(rightPositions[kind][i], referenceContext, + // problemReporter.unmatchedBracket(rightPositions[kind][i], + // referenceContext, // compilationUnit.compilationResult); // } // if (anomaliesDetected) @@ -4708,22 +4983,26 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI protected void consumePackageDeclarationName(IFile file) { // create a package name similar to java package names - String projectPath = ProjectPrefUtil.getDocumentRoot(file.getProject()).toString(); + String projectPath = ProjectPrefUtil.getDocumentRoot(file.getProject()) + .toString(); String filePath = file.getRawLocation().toString(); String ext = file.getRawLocation().getFileExtension(); int fileExtensionLength = ext == null ? 0 : ext.length() + 1; ImportReference impt; char[][] tokens; if (filePath.startsWith(projectPath)) { - tokens = CharOperation - .splitOn('/', filePath.toCharArray(), projectPath.length() + 1, filePath.length() - fileExtensionLength); + tokens = CharOperation.splitOn('/', filePath.toCharArray(), + projectPath.length() + 1, filePath.length() + - fileExtensionLength); } else { String name = file.getName(); tokens = new char[1][]; - tokens[0] = name.substring(0, name.length() - fileExtensionLength).toCharArray(); + tokens[0] = name.substring(0, name.length() - fileExtensionLength) + .toCharArray(); } - this.compilationUnit.currentPackage = impt = new ImportReference(tokens, new char[0], 0, 0, true); + this.compilationUnit.currentPackage = impt = new ImportReference( + tokens, new char[0], 0, 0, true); impt.declarationSourceStart = 0; impt.declarationSourceEnd = 0; @@ -4732,11 +5011,12 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI } - public final static String[] GLOBALS = { "$this", "$_COOKIE", "$_ENV", "$_FILES", "$_GET", "$GLOBALS", "$_POST", "$_REQUEST", - "$_SESSION", "$_SERVER" }; + public final static String[] GLOBALS = { "$this", "$_COOKIE", "$_ENV", + "$_FILES", "$_GET", "$GLOBALS", "$_POST", "$_REQUEST", "$_SESSION", + "$_SERVER" }; /** - * + * */ private void pushFunctionVariableSet() { HashSet set = new HashSet(); @@ -4757,7 +5037,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI private HashSet removeIfVariableSet() { if (!fStackUnassigned.isEmpty()) { - return (HashSet) fStackUnassigned.remove(fStackUnassigned.size() - 1); + return (HashSet) fStackUnassigned + .remove(fStackUnassigned.size() - 1); } return null; } @@ -4774,8 +5055,9 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI } /** - * add the current identifier source to the set of assigned variables - * + * add the current identifier source to the set of assigned variables + * + * * @param set */ private void addVariableSet(HashSet set) { @@ -4785,8 +5067,9 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI } /** - * add the current identifier source to the set of assigned variables - * + * add the current identifier source to the set of assigned variables + * + * */ private void addVariableSet() { HashSet set = peekVariableSet(); @@ -4796,8 +5079,9 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI } /** - * add the current identifier source to the set of assigned variables - * + * add the current identifier source to the set of assigned variables + * + * */ private void addVariableSet(char[] token) { HashSet set = peekVariableSet(); @@ -4810,7 +5094,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ParserBasicI * check if the current identifier source is in the set of assigned * variables Returns true, if no set is defined for the current scanner * position - * + * */ private boolean containsVariableSet() { return containsVariableSet(scanner.getCurrentTokenSource()); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/ParserBasicInformation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/ParserBasicInformation.java index e5c59b5..c6d308f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/ParserBasicInformation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/ParserBasicInformation.java @@ -10,24 +10,17 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.compiler.parser; -/*An interface that contains static declarations for some basic information - about the parser such as the number of rules in the grammar, the starting state, etc...*/ +/* + * An interface that contains static declarations for some basic information + * about the parser such as the number of rules in the grammar, the starting + * state, etc... + */ public interface ParserBasicInformation { - public final static int - NT_OFFSET = 308, - SCOPE_UBOUND = -1, - SCOPE_SIZE = 0, - LA_STATE_OFFSET = 17759, - MAX_LA = 1, - NUM_RULES = 437, - NUM_TERMINALS = 104, - NUM_NON_TERMINALS = 204, - NUM_SYMBOLS = 308, - START_STATE = 16034, - EOFT_SYMBOL = 114, - EOLT_SYMBOL = 105, - ACCEPT_ACTION = 17758, - ERROR_ACTION = 17759; + public final static int NT_OFFSET = 308, SCOPE_UBOUND = -1, SCOPE_SIZE = 0, + LA_STATE_OFFSET = 17759, MAX_LA = 1, NUM_RULES = 437, + NUM_TERMINALS = 104, NUM_NON_TERMINALS = 204, NUM_SYMBOLS = 308, + START_STATE = 16034, EOFT_SYMBOL = 114, EOLT_SYMBOL = 105, + ACCEPT_ACTION = 17758, ERROR_ACTION = 17759; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/ParserUtil.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/ParserUtil.java index 5e7a44e..f81eb3c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/ParserUtil.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/ParserUtil.java @@ -13,7 +13,8 @@ import org.eclipse.core.resources.IFile; public class ParserUtil { - public static SingleTypeReference getTypeReference(Scanner scanner, List includesList, char[] ident) { + public static SingleTypeReference getTypeReference(Scanner scanner, + List includesList, char[] ident) { String identStr = new String(ident); ImportReference ir; IFile file = null; @@ -21,16 +22,23 @@ public class ParserUtil { ir = (ImportReference) includesList.get(i); file = ir.getFile(); if (file != null) { - ICompilationUnit unit = JavaCore.createCompilationUnitFrom(file); + ICompilationUnit unit = JavaCore + .createCompilationUnitFrom(file); if (unit != null) { try { - // TODO avoid recursion here. Sometimes we get a java.lang.StackOverflowError + // TODO avoid recursion here. Sometimes we get a + // java.lang.StackOverflowError IType[] types = unit.getAllTypes(); if (types != null) { for (int j = 0; j < types.length; j++) { if (types[j].getElementName().equals(identStr)) { - return new SingleTypeReference(file, ident, scanner.getCurrentTokenStartPosition(), scanner - .getCurrentTokenEndPosition()); + return new SingleTypeReference( + file, + ident, + scanner + .getCurrentTokenStartPosition(), + scanner + .getCurrentTokenEndPosition()); } } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/RecoveredElement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/RecoveredElement.java index 169bebd..4cf3d75 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/RecoveredElement.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/RecoveredElement.java @@ -15,303 +15,344 @@ import net.sourceforge.phpdt.internal.compiler.ast.Block; import net.sourceforge.phpdt.internal.compiler.ast.Statement; /** - * Internal structure for parsing recovery + * Internal structure for parsing recovery */ public class RecoveredElement { public RecoveredElement parent; + public int bracketBalance; + public boolean foundOpeningBrace; + protected Parser recoveringParser; -public RecoveredElement(RecoveredElement parent, int bracketBalance){ - this(parent, bracketBalance, null); -} -public RecoveredElement(RecoveredElement parent, int bracketBalance, Parser parser){ - this.parent = parent; - this.bracketBalance = bracketBalance; - this.recoveringParser = parser; -} -/* - * Record a method declaration - */ -//public RecoveredElement add(AbstractMethodDeclaration methodDeclaration, int bracketBalance) { -// -// /* default behavior is to delegate recording to parent if any */ -// if (parent == null) { -// return this; // ignore -// } else { -// this.updateSourceEndIfNecessary(this.previousAvailableLineEnd(methodDeclaration.declarationSourceStart - 1)); -// return this.parent.add(methodDeclaration, bracketBalance); -// } -//} -/* - * Record a nested block declaration - */ -public RecoveredElement add(Block nestedBlockDeclaration, int bracketBalance) { - - /* default behavior is to delegate recording to parent if any */ - if (parent == null) { - return this; // ignore - } else { - this.updateSourceEndIfNecessary(this.previousAvailableLineEnd(nestedBlockDeclaration.sourceStart - 1)); - return this.parent.add(nestedBlockDeclaration, bracketBalance); + + public RecoveredElement(RecoveredElement parent, int bracketBalance) { + this(parent, bracketBalance, null); } -} -/* - * Record a field declaration - */ -//public RecoveredElement add(FieldDeclaration fieldDeclaration, int bracketBalance) { -// -// /* default behavior is to delegate recording to parent if any */ -// if (parent == null) { -// return this; // ignore -// } else { -// this.updateSourceEndIfNecessary(this.previousAvailableLineEnd(fieldDeclaration.declarationSourceStart - 1)); -// return this.parent.add(fieldDeclaration, bracketBalance); -// } -//} -///* -// * Record an import reference -// */ -//public RecoveredElement add(ImportReference importReference, int bracketBalance){ -// -// /* default behavior is to delegate recording to parent if any */ -// if (parent == null) { -// return this; // ignore -// } else { -// this.updateSourceEndIfNecessary(this.previousAvailableLineEnd(importReference.declarationSourceStart - 1)); -// return this.parent.add(importReference, bracketBalance); -// } -//} -///* -// * Record a local declaration -// */ -//public RecoveredElement add(LocalDeclaration localDeclaration, int bracketBalance) { -// -// /* default behavior is to delegate recording to parent if any */ -// if (parent == null) { -// return this; // ignore -// } else { -// this.updateSourceEndIfNecessary(this.previousAvailableLineEnd(localDeclaration.declarationSourceStart - 1)); -// return this.parent.add(localDeclaration, bracketBalance); -// } -//} -/* - * Record a statement - */ -public RecoveredElement add(Statement statement, int bracketBalance) { - - /* default behavior is to delegate recording to parent if any */ - if (parent == null) { - return this; // ignore - } else { - this.updateSourceEndIfNecessary(this.previousAvailableLineEnd(statement.sourceStart - 1)); - return this.parent.add(statement, bracketBalance); + + public RecoveredElement(RecoveredElement parent, int bracketBalance, + Parser parser) { + this.parent = parent; + this.bracketBalance = bracketBalance; + this.recoveringParser = parser; } -} -/* - * Record a type declaration - */ -//public RecoveredElement add(TypeDeclaration typeDeclaration, int bracketBalance){ -// -// /* default behavior is to delegate recording to parent if any */ -// if (parent == null) { -// return this; // ignore -// } else { -// this.updateSourceEndIfNecessary(this.previousAvailableLineEnd(typeDeclaration.declarationSourceStart - 1)); -// return this.parent.add(typeDeclaration, bracketBalance); -// } -//} -/* - * Answer the depth of this element, considering the parent link. - */ -public int depth(){ - int depth = 0; - RecoveredElement current = this; - while ((current = current.parent) != null) depth++; - return depth; -} -/* - * Answer the enclosing method node, or null if none - */ -//public RecoveredInitializer enclosingInitializer(){ -// RecoveredElement current = this; -// while (current != null){ -// if (current instanceof RecoveredInitializer){ -// return (RecoveredInitializer) current; -// } -// current = current.parent; -// } -// return null; -//} -/* - * Answer the enclosing method node, or null if none - */ -//public RecoveredMethod enclosingMethod(){ -// RecoveredElement current = this; -// while (current != null){ -// if (current instanceof RecoveredMethod){ -// return (RecoveredMethod) current; -// } -// current = current.parent; -// } -// return null; -//} -/* - * Answer the enclosing type node, or null if none - */ -//public RecoveredType enclosingType(){ -// RecoveredElement current = this; -// while (current != null){ -// if (current instanceof RecoveredType){ -// return (RecoveredType) current; -// } -// current = current.parent; -// } -// return null; -//} -/* - * Answer the closest specified parser - */ -public Parser parser(){ - RecoveredElement current = this; - while (current != null){ - if (current.recoveringParser != null){ - return current.recoveringParser; + + /* + * Record a method declaration + */ + // public RecoveredElement add(AbstractMethodDeclaration methodDeclaration, + // int bracketBalance) { + // + // /* default behavior is to delegate recording to parent if any */ + // if (parent == null) { + // return this; // ignore + // } else { + // this.updateSourceEndIfNecessary(this.previousAvailableLineEnd(methodDeclaration.declarationSourceStart + // - 1)); + // return this.parent.add(methodDeclaration, bracketBalance); + // } + // } + /* + * Record a nested block declaration + */ + public RecoveredElement add(Block nestedBlockDeclaration, int bracketBalance) { + + /* default behavior is to delegate recording to parent if any */ + if (parent == null) { + return this; // ignore + } else { + this + .updateSourceEndIfNecessary(this + .previousAvailableLineEnd(nestedBlockDeclaration.sourceStart - 1)); + return this.parent.add(nestedBlockDeclaration, bracketBalance); } - current = current.parent; } - return null; -} -/* - * Answer the associated parsed structure - */ -public ASTNode parseTree(){ - return null; -} -/* - * Iterate the enclosing blocks and tag them so as to preserve their content - */ -//public void preserveEnclosingBlocks(){ -// RecoveredElement current = this; -// while (current != null){ -// if (current instanceof RecoveredBlock){ -// ((RecoveredBlock)current).preserveContent = true; -// } -// if (current instanceof RecoveredType){ // for anonymous types -// ((RecoveredType)current).preserveContent = true; -// } -// current = current.parent; -// } -//} -/* - * Answer the position of the previous line end if - * there is nothing but spaces in between it and the - * line end. Used to trim spaces on unclosed elements. - */ -public int previousAvailableLineEnd(int position){ - - Parser parser = this.parser(); - if (parser == null) return position; - - Scanner scanner = parser.scanner; - if (scanner.lineEnds == null) return position; - - int index = scanner.getLineNumber(position); - if (index < 2) return position; - int previousLineEnd = scanner.lineEnds[index-2]; - - char[] source = scanner.source; - for (int i = previousLineEnd+1; i < position; i++){ - if (!(source[i] == ' ' || source[i] == '\t')) return position; + + /* + * Record a field declaration + */ + // public RecoveredElement add(FieldDeclaration fieldDeclaration, int + // bracketBalance) { + // + // /* default behavior is to delegate recording to parent if any */ + // if (parent == null) { + // return this; // ignore + // } else { + // this.updateSourceEndIfNecessary(this.previousAvailableLineEnd(fieldDeclaration.declarationSourceStart + // - 1)); + // return this.parent.add(fieldDeclaration, bracketBalance); + // } + // } + // /* + // * Record an import reference + // */ + // public RecoveredElement add(ImportReference importReference, int + // bracketBalance){ + // + // /* default behavior is to delegate recording to parent if any */ + // if (parent == null) { + // return this; // ignore + // } else { + // this.updateSourceEndIfNecessary(this.previousAvailableLineEnd(importReference.declarationSourceStart + // - 1)); + // return this.parent.add(importReference, bracketBalance); + // } + // } + // /* + // * Record a local declaration + // */ + // public RecoveredElement add(LocalDeclaration localDeclaration, int + // bracketBalance) { + // + // /* default behavior is to delegate recording to parent if any */ + // if (parent == null) { + // return this; // ignore + // } else { + // this.updateSourceEndIfNecessary(this.previousAvailableLineEnd(localDeclaration.declarationSourceStart + // - 1)); + // return this.parent.add(localDeclaration, bracketBalance); + // } + // } + /* + * Record a statement + */ + public RecoveredElement add(Statement statement, int bracketBalance) { + + /* default behavior is to delegate recording to parent if any */ + if (parent == null) { + return this; // ignore + } else { + this.updateSourceEndIfNecessary(this + .previousAvailableLineEnd(statement.sourceStart - 1)); + return this.parent.add(statement, bracketBalance); + } } - return previousLineEnd; -} -/* - * Answer the very source end of the corresponding parse node - */ -public int sourceEnd(){ - return 0; -} -protected String tabString(int tab) { - StringBuffer result = new StringBuffer(); - for (int i = tab; i > 0; i--) { - result.append(" "); //$NON-NLS-1$ + + /* + * Record a type declaration + */ + // public RecoveredElement add(TypeDeclaration typeDeclaration, int + // bracketBalance){ + // + // /* default behavior is to delegate recording to parent if any */ + // if (parent == null) { + // return this; // ignore + // } else { + // this.updateSourceEndIfNecessary(this.previousAvailableLineEnd(typeDeclaration.declarationSourceStart + // - 1)); + // return this.parent.add(typeDeclaration, bracketBalance); + // } + // } + /* + * Answer the depth of this element, considering the parent link. + */ + public int depth() { + int depth = 0; + RecoveredElement current = this; + while ((current = current.parent) != null) + depth++; + return depth; } - return result.toString(); -} -/* - * Answer the top node - */ -public RecoveredElement topElement(){ - RecoveredElement current = this; - while (current.parent != null){ - current = current.parent; + + /* + * Answer the enclosing method node, or null if none + */ + // public RecoveredInitializer enclosingInitializer(){ + // RecoveredElement current = this; + // while (current != null){ + // if (current instanceof RecoveredInitializer){ + // return (RecoveredInitializer) current; + // } + // current = current.parent; + // } + // return null; + // } + /* + * Answer the enclosing method node, or null if none + */ + // public RecoveredMethod enclosingMethod(){ + // RecoveredElement current = this; + // while (current != null){ + // if (current instanceof RecoveredMethod){ + // return (RecoveredMethod) current; + // } + // current = current.parent; + // } + // return null; + // } + /* + * Answer the enclosing type node, or null if none + */ + // public RecoveredType enclosingType(){ + // RecoveredElement current = this; + // while (current != null){ + // if (current instanceof RecoveredType){ + // return (RecoveredType) current; + // } + // current = current.parent; + // } + // return null; + // } + /* + * Answer the closest specified parser + */ + public Parser parser() { + RecoveredElement current = this; + while (current != null) { + if (current.recoveringParser != null) { + return current.recoveringParser; + } + current = current.parent; + } + return null; } - return current; -} -public String toString() { - return toString(0); -} -public String toString(int tab) { - return super.toString(); -} -/* - * Answer the enclosing type node, or null if none - */ -//public RecoveredType type(){ -// RecoveredElement current = this; -// while (current != null){ -// if (current instanceof RecoveredType){ -// return (RecoveredType) current; -// } -// current = current.parent; -// } -// return null; -//} -/* - * Update the bodyStart of the corresponding parse node - */ -public void updateBodyStart(int bodyStart){ - this.foundOpeningBrace = true; -} -/* - * Update the corresponding parse node from parser state which - * is about to disappear because of restarting recovery - */ -public void updateFromParserState(){ -} -/* - * A closing brace got consumed, might have closed the current element, - * in which case both the currentElement is exited - */ -public RecoveredElement updateOnClosingBrace(int braceStart, int braceEnd){ - if ((--bracketBalance <= 0) && (parent != null)){ - this.updateSourceEndIfNecessary(braceEnd); - return parent; + + /* + * Answer the associated parsed structure + */ + public ASTNode parseTree() { + return null; + } + + /* + * Iterate the enclosing blocks and tag them so as to preserve their content + */ + // public void preserveEnclosingBlocks(){ + // RecoveredElement current = this; + // while (current != null){ + // if (current instanceof RecoveredBlock){ + // ((RecoveredBlock)current).preserveContent = true; + // } + // if (current instanceof RecoveredType){ // for anonymous types + // ((RecoveredType)current).preserveContent = true; + // } + // current = current.parent; + // } + // } + /* + * Answer the position of the previous line end if there is nothing but + * spaces in between it and the line end. Used to trim spaces on unclosed + * elements. + */ + public int previousAvailableLineEnd(int position) { + + Parser parser = this.parser(); + if (parser == null) + return position; + + Scanner scanner = parser.scanner; + if (scanner.lineEnds == null) + return position; + + int index = scanner.getLineNumber(position); + if (index < 2) + return position; + int previousLineEnd = scanner.lineEnds[index - 2]; + + char[] source = scanner.source; + for (int i = previousLineEnd + 1; i < position; i++) { + if (!(source[i] == ' ' || source[i] == '\t')) + return position; + } + return previousLineEnd; + } + + /* + * Answer the very source end of the corresponding parse node + */ + public int sourceEnd() { + return 0; } - return this; -} -/* - * An opening brace got consumed, might be the expected opening one of the current element, - * in which case the bodyStart is updated. - */ -public RecoveredElement updateOnOpeningBrace(int braceEnd){ - if (bracketBalance++ == 0){ - this.updateBodyStart(braceEnd + 1); + protected String tabString(int tab) { + StringBuffer result = new StringBuffer(); + for (int i = tab; i > 0; i--) { + result.append(" "); //$NON-NLS-1$ + } + return result.toString(); + } + + /* + * Answer the top node + */ + public RecoveredElement topElement() { + RecoveredElement current = this; + while (current.parent != null) { + current = current.parent; + } + return current; + } + + public String toString() { + return toString(0); + } + + public String toString(int tab) { + return super.toString(); + } + + /* + * Answer the enclosing type node, or null if none + */ + // public RecoveredType type(){ + // RecoveredElement current = this; + // while (current != null){ + // if (current instanceof RecoveredType){ + // return (RecoveredType) current; + // } + // current = current.parent; + // } + // return null; + // } + /* + * Update the bodyStart of the corresponding parse node + */ + public void updateBodyStart(int bodyStart) { + this.foundOpeningBrace = true; + } + + /* + * Update the corresponding parse node from parser state which is about to + * disappear because of restarting recovery + */ + public void updateFromParserState() { + } + + /* + * A closing brace got consumed, might have closed the current element, in + * which case both the currentElement is exited + */ + public RecoveredElement updateOnClosingBrace(int braceStart, int braceEnd) { + if ((--bracketBalance <= 0) && (parent != null)) { + this.updateSourceEndIfNecessary(braceEnd); + return parent; + } return this; } - return null; // no update is necessary -} -/* - * Final update the corresponding parse node - */ -public void updateParseTree(){ -} -/* - * Update the declarationSourceEnd of the corresponding parse node - */ -public void updateSourceEndIfNecessary(int sourceEnd){ -} + + /* + * An opening brace got consumed, might be the expected opening one of the + * current element, in which case the bodyStart is updated. + */ + public RecoveredElement updateOnOpeningBrace(int braceEnd) { + + if (bracketBalance++ == 0) { + this.updateBodyStart(braceEnd + 1); + return this; + } + return null; // no update is necessary + } + + /* + * Final update the corresponding parse node + */ + public void updateParseTree() { + } + + /* + * Update the declarationSourceEnd of the corresponding parse node + */ + public void updateSourceEndIfNecessary(int sourceEnd) { + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/Scanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/Scanner.java index b2ae4c6..6866e27 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/Scanner.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/Scanner.java @@ -20,17 +20,19 @@ import net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit; public class Scanner implements IScanner, ITerminalSymbols { /* - * APIs ares - getNextToken() which return the current type of the token (this - * value is not memorized by the scanner) - getCurrentTokenSource() which - * provides with the token "REAL" source (aka all unicode have been - * transformed into a correct char) - sourceStart gives the position into the - * stream - currentPosition-1 gives the sourceEnd position into the stream + * APIs ares - getNextToken() which return the current type of the token + * (this value is not memorized by the scanner) - getCurrentTokenSource() + * which provides with the token "REAL" source (aka all unicode have been + * transformed into a correct char) - sourceStart gives the position into + * the stream - currentPosition-1 gives the sourceEnd position into the + * stream */ // 1.4 feature // private boolean assertMode; public boolean useAssertAsAnIndentifier = false; - // flag indicating if processed source contains occurrences of keyword assert + // flag indicating if processed source contains occurrences of keyword + // assert public boolean containsAssertKeyword = false; public boolean recordLineSeparator; @@ -40,10 +42,12 @@ public class Scanner implements IScanner, ITerminalSymbols { public boolean phpMode = false; /** - * This token is set to TokenNameecho if a short tag block begins (i.e. >?= ... ) - * Directly after the "=" character the getNextToken() method returns TokenNameINLINE_HTML - * In the next call to the getNextToken() method the value of fFillerToken (==TokenNameecho) is returned - * + * This token is set to TokenNameecho if a short tag block begins (i.e. + * >?= ... ) Directly after the "=" character the + * getNextToken() method returns TokenNameINLINE_HTML In the next call to + * the getNextToken() method the value of fFillerToken (==TokenNameecho) is + * returned + * */ int fFillerToken = TokenNameEOF; @@ -122,25 +126,39 @@ public class Scanner implements IScanner, ITerminalSymbols { public static final String INVALID_CHAR_IN_STRING = "Invalid_Char_In_String"; //$NON-NLS-1$ // ----------------optimized identifier managment------------------ - static final char[] charArray_a = new char[] { 'a' }, charArray_b = new char[] { 'b' }, charArray_c = new char[] { 'c' }, - charArray_d = new char[] { 'd' }, charArray_e = new char[] { 'e' }, charArray_f = new char[] { 'f' }, - charArray_g = new char[] { 'g' }, charArray_h = new char[] { 'h' }, charArray_i = new char[] { 'i' }, - charArray_j = new char[] { 'j' }, charArray_k = new char[] { 'k' }, charArray_l = new char[] { 'l' }, - charArray_m = new char[] { 'm' }, charArray_n = new char[] { 'n' }, charArray_o = new char[] { 'o' }, - charArray_p = new char[] { 'p' }, charArray_q = new char[] { 'q' }, charArray_r = new char[] { 'r' }, - charArray_s = new char[] { 's' }, charArray_t = new char[] { 't' }, charArray_u = new char[] { 'u' }, - charArray_v = new char[] { 'v' }, charArray_w = new char[] { 'w' }, charArray_x = new char[] { 'x' }, - charArray_y = new char[] { 'y' }, charArray_z = new char[] { 'z' }; - - static final char[] charArray_va = new char[] { '$', 'a' }, charArray_vb = new char[] { '$', 'b' }, charArray_vc = new char[] { - '$', 'c' }, charArray_vd = new char[] { '$', 'd' }, charArray_ve = new char[] { '$', 'e' }, charArray_vf = new char[] { '$', - 'f' }, charArray_vg = new char[] { '$', 'g' }, charArray_vh = new char[] { '$', 'h' }, - charArray_vi = new char[] { '$', 'i' }, charArray_vj = new char[] { '$', 'j' }, charArray_vk = new char[] { '$', 'k' }, - charArray_vl = new char[] { '$', 'l' }, charArray_vm = new char[] { '$', 'm' }, charArray_vn = new char[] { '$', 'n' }, - charArray_vo = new char[] { '$', 'o' }, charArray_vp = new char[] { '$', 'p' }, charArray_vq = new char[] { '$', 'q' }, - charArray_vr = new char[] { '$', 'r' }, charArray_vs = new char[] { '$', 's' }, charArray_vt = new char[] { '$', 't' }, - charArray_vu = new char[] { '$', 'u' }, charArray_vv = new char[] { '$', 'v' }, charArray_vw = new char[] { '$', 'w' }, - charArray_vx = new char[] { '$', 'x' }, charArray_vy = new char[] { '$', 'y' }, charArray_vz = new char[] { '$', 'z' }; + static final char[] charArray_a = new char[] { 'a' }, + charArray_b = new char[] { 'b' }, charArray_c = new char[] { 'c' }, + charArray_d = new char[] { 'd' }, charArray_e = new char[] { 'e' }, + charArray_f = new char[] { 'f' }, charArray_g = new char[] { 'g' }, + charArray_h = new char[] { 'h' }, charArray_i = new char[] { 'i' }, + charArray_j = new char[] { 'j' }, charArray_k = new char[] { 'k' }, + charArray_l = new char[] { 'l' }, charArray_m = new char[] { 'm' }, + charArray_n = new char[] { 'n' }, charArray_o = new char[] { 'o' }, + charArray_p = new char[] { 'p' }, charArray_q = new char[] { 'q' }, + charArray_r = new char[] { 'r' }, charArray_s = new char[] { 's' }, + charArray_t = new char[] { 't' }, charArray_u = new char[] { 'u' }, + charArray_v = new char[] { 'v' }, charArray_w = new char[] { 'w' }, + charArray_x = new char[] { 'x' }, charArray_y = new char[] { 'y' }, + charArray_z = new char[] { 'z' }; + + static final char[] charArray_va = new char[] { '$', 'a' }, + charArray_vb = new char[] { '$', 'b' }, charArray_vc = new char[] { + '$', 'c' }, charArray_vd = new char[] { '$', 'd' }, + charArray_ve = new char[] { '$', 'e' }, charArray_vf = new char[] { + '$', 'f' }, charArray_vg = new char[] { '$', 'g' }, + charArray_vh = new char[] { '$', 'h' }, charArray_vi = new char[] { + '$', 'i' }, charArray_vj = new char[] { '$', 'j' }, + charArray_vk = new char[] { '$', 'k' }, charArray_vl = new char[] { + '$', 'l' }, charArray_vm = new char[] { '$', 'm' }, + charArray_vn = new char[] { '$', 'n' }, charArray_vo = new char[] { + '$', 'o' }, charArray_vp = new char[] { '$', 'p' }, + charArray_vq = new char[] { '$', 'q' }, charArray_vr = new char[] { + '$', 'r' }, charArray_vs = new char[] { '$', 's' }, + charArray_vt = new char[] { '$', 't' }, charArray_vu = new char[] { + '$', 'u' }, charArray_vv = new char[] { '$', 'v' }, + charArray_vw = new char[] { '$', 'w' }, charArray_vx = new char[] { + '$', 'x' }, charArray_vy = new char[] { '$', 'y' }, + charArray_vz = new char[] { '$', 'z' }; public final static int MAX_OBVIOUS = 256; @@ -173,7 +191,8 @@ public class Scanner implements IScanner, ITerminalSymbols { ObviousIdentCharNatures[12] = C_SPACE; // \ u000c: FORM FEED ObviousIdentCharNatures[13] = C_SPACE; // \ u000d: CARRIAGE RETURN ObviousIdentCharNatures[32] = C_SPACE; // \ u0020: SPACE - ObviousIdentCharNatures[9] = C_SPACE; // \ u0009: HORIZONTAL TABULATION + ObviousIdentCharNatures[9] = C_SPACE; // \ u0009: HORIZONTAL + // TABULATION ObviousIdentCharNatures['.'] = C_SEPARATOR; ObviousIdentCharNatures[':'] = C_SEPARATOR; @@ -203,7 +222,8 @@ public class Scanner implements IScanner, ITerminalSymbols { ObviousIdentCharNatures['\''] = C_SEPARATOR; } - static final char[] initCharArray = new char[] { '\u0000', '\u0000', '\u0000', '\u0000', '\u0000', '\u0000' }; + static final char[] initCharArray = new char[] { '\u0000', '\u0000', + '\u0000', '\u0000', '\u0000', '\u0000' }; static final int TableSize = 30, InternalTableSize = 6; @@ -246,7 +266,8 @@ public class Scanner implements IScanner, ITerminalSymbols { } } - static int newEntry2 = 0, newEntry3 = 0, newEntry4 = 0, newEntry5 = 0, newEntry6 = 0; + static int newEntry2 = 0, newEntry3 = 0, newEntry4 = 0, newEntry5 = 0, + newEntry6 = 0; public static final int RoundBracket = 0; @@ -280,26 +301,28 @@ public class Scanner implements IScanner, ITerminalSymbols { public ICompilationUnit compilationUnit = null; /** - * Determines if the specified character is permissible as the first character - * in a PHP identifier or variable - * + * Determines if the specified character is permissible as the first + * character in a PHP identifier or variable + * * The '$' character for PHP variables is regarded as a correct first * character ! - * + * */ public static boolean isPHPIdentOrVarStart(char ch) { if (ch < MAX_OBVIOUS) { - return ObviousIdentCharNatures[ch] == C_LETTER || ObviousIdentCharNatures[ch] == C_DOLLAR; + return ObviousIdentCharNatures[ch] == C_LETTER + || ObviousIdentCharNatures[ch] == C_DOLLAR; } return false; - // return Character.isLetter(ch) || (ch == '$') || (ch == '_') || (0x7F <= + // return Character.isLetter(ch) || (ch == '$') || (ch == '_') || (0x7F + // <= // ch && ch <= 0xFF); } /** - * Determines if the specified character is permissible as the first character - * in a PHP identifier. - * + * Determines if the specified character is permissible as the first + * character in a PHP identifier. + * * The '$' character for PHP variables isn't regarded as the first character ! */ public static boolean isPHPIdentifierStart(char ch) { @@ -317,16 +340,19 @@ public class Scanner implements IScanner, ITerminalSymbols { */ public static boolean isPHPIdentifierPart(char ch) { if (ch < MAX_OBVIOUS) { - return ObviousIdentCharNatures[ch] == C_LETTER || ObviousIdentCharNatures[ch] == C_DIGIT; + return ObviousIdentCharNatures[ch] == C_LETTER + || ObviousIdentCharNatures[ch] == C_DIGIT; } return false; - // return Character.isLetterOrDigit(ch) || (ch == '_') || (0x7F <= ch && ch + // return Character.isLetterOrDigit(ch) || (ch == '_') || (0x7F <= ch && + // ch // <= 0xFF); } public static boolean isSQLIdentifierPart(char ch) { if (ch < MAX_OBVIOUS) { - return ObviousIdentCharNatures[ch] == C_LETTER || ObviousIdentCharNatures[ch] == C_DIGIT; + return ObviousIdentCharNatures[ch] == C_LETTER + || ObviousIdentCharNatures[ch] == C_DIGIT; } return false; } @@ -341,7 +367,8 @@ public class Scanner implements IScanner, ITerminalSymbols { // return the token REAL source (aka unicodes are precomputed) char[] result; // if (withoutUnicodePtr != 0) - // //0 is used as a fast test flag so the real first char is in position 1 + // //0 is used as a fast test flag so the real first char is in position + // 1 // System.arraycopy( // withoutUnicodeBuffer, // 1, @@ -365,7 +392,8 @@ public class Scanner implements IScanner, ITerminalSymbols { return optimizedCurrentTokenSource6(); } // no optimization - System.arraycopy(source, startPosition, result = new char[length], 0, length); + System.arraycopy(source, startPosition, result = new char[length], 0, + length); // } return result; } @@ -378,7 +406,8 @@ public class Scanner implements IScanner, ITerminalSymbols { // Return the token REAL source (aka unicodes are precomputed) char[] result; // if (withoutUnicodePtr != 0) - // // 0 is used as a fast test flag so the real first char is in position 1 + // // 0 is used as a fast test flag so the real first char is in + // position 1 // System.arraycopy( // withoutUnicodeBuffer, // 1, @@ -387,7 +416,9 @@ public class Scanner implements IScanner, ITerminalSymbols { // withoutUnicodePtr); // else { int length; - System.arraycopy(source, startPosition, result = new char[length = currentPosition - startPosition], 0, length); + System.arraycopy(source, startPosition, + result = new char[length = currentPosition - startPosition], 0, + length); // } return result; } @@ -396,7 +427,8 @@ public class Scanner implements IScanner, ITerminalSymbols { // Return the token REAL source (aka unicodes are precomputed) char[] result; // if (withoutUnicodePtr != 0) - // // 0 is used as a fast test flag so the real first char is in position 1 + // // 0 is used as a fast test flag so the real first char is in + // position 1 // System.arraycopy( // withoutUnicodeBuffer, // 1, @@ -405,7 +437,9 @@ public class Scanner implements IScanner, ITerminalSymbols { // withoutUnicodePtr); // else { int length; - System.arraycopy(source, startPos, result = new char[length = currentPosition - startPos], 0, length); + System.arraycopy(source, startPos, + result = new char[length = currentPosition - startPos], 0, + length); // } return result; } @@ -415,13 +449,17 @@ public class Scanner implements IScanner, ITerminalSymbols { // REMOVE the two " that are at the beginning and the end. char[] result; if (withoutUnicodePtr != 0) - // 0 is used as a fast test flag so the real first char is in position 1 + // 0 is used as a fast test flag so the real first char is in + // position 1 System.arraycopy(withoutUnicodeBuffer, 2, - // 2 is 1 (real start) + 1 (to jump over the ") - result = new char[withoutUnicodePtr - 2], 0, withoutUnicodePtr - 2); + // 2 is 1 (real start) + 1 (to jump over the ") + result = new char[withoutUnicodePtr - 2], 0, + withoutUnicodePtr - 2); else { int length; - System.arraycopy(source, startPosition + 1, result = new char[length = currentPosition - startPosition - 2], 0, length); + System.arraycopy(source, startPosition + 1, + result = new char[length = currentPosition - startPosition + - 2], 0, length); } return result; } @@ -441,7 +479,8 @@ public class Scanner implements IScanner, ITerminalSymbols { public final char[] getRawTokenSourceEnd() { int length = this.eofPosition - this.currentPosition - 1; char[] sourceEnd = new char[length]; - System.arraycopy(this.source, this.currentPosition, sourceEnd, 0, length); + System.arraycopy(this.source, this.currentPosition, sourceEnd, 0, + length); return sourceEnd; } @@ -461,7 +500,10 @@ public class Scanner implements IScanner, ITerminalSymbols { } char[] result; int length; - System.arraycopy(source, startPosition + 1, result = new char[length = currentPosition - startPosition - 2], 0, length); + System + .arraycopy(source, startPosition + 1, + result = new char[length = currentPosition + - startPosition - 2], 0, length); // } return result; } @@ -470,17 +512,20 @@ public class Scanner implements IScanner, ITerminalSymbols { // Return the token REAL source (aka unicodes are precomputed) char[] result; int length; - System.arraycopy(source, startPos + 1, result = new char[length = currentPosition - startPos - 2], 0, length); + System.arraycopy(source, startPos + 1, + result = new char[length = currentPosition - startPos - 2], 0, + length); // } return result; } /* - * Search the source position corresponding to the end of a given line number - * + * Search the source position corresponding to the end of a given line + * number + * * Line numbers are 1-based, and relative to the scanner initialPosition. * Character positions are 0-based. - * + * * In case the given line number is inconsistent, answers -1. */ public final int getLineEnd(int lineNumber) { @@ -499,12 +544,12 @@ public class Scanner implements IScanner, ITerminalSymbols { /** * Search the source position corresponding to the beginning of a given line * number - * + * * Line numbers are 1-based, and relative to the scanner initialPosition. * Character positions are 0-based. - * + * * e.g. getLineStart(1) --> 0 i.e. first line starts at character 0. - * + * * In case the given line number is inconsistent, answers -1. */ public final int getLineStart(int lineNumber) { @@ -545,13 +590,17 @@ public class Scanner implements IScanner, ITerminalSymbols { // unicodeSize++; // } // - // if (((c1 = Character.getNumericValue(source[currentPosition++])) > 15 + // if (((c1 = Character.getNumericValue(source[currentPosition++])) + // > 15 // || c1 < 0) - // || ((c2 = Character.getNumericValue(source[currentPosition++])) > 15 + // || ((c2 = Character.getNumericValue(source[currentPosition++])) > + // 15 // || c2 < 0) - // || ((c3 = Character.getNumericValue(source[currentPosition++])) > 15 + // || ((c3 = Character.getNumericValue(source[currentPosition++])) > + // 15 // || c3 < 0) - // || ((c4 = Character.getNumericValue(source[currentPosition++])) > 15 + // || ((c4 = Character.getNumericValue(source[currentPosition++])) > + // 15 // || c4 < 0)) { // currentPosition = temp; // return false; @@ -567,7 +616,8 @@ public class Scanner implements IScanner, ITerminalSymbols { // //need the unicode buffer // if (withoutUnicodePtr == 0) { // //buffer all the entries that have been left aside.... - // withoutUnicodePtr = currentPosition - unicodeSize - startPosition; + // withoutUnicodePtr = currentPosition - unicodeSize - + // startPosition; // System.arraycopy( // source, // startPosition, @@ -624,13 +674,17 @@ public class Scanner implements IScanner, ITerminalSymbols { // unicodeSize++; // } // - // if (((c1 = Character.getNumericValue(source[currentPosition++])) > 15 + // if (((c1 = Character.getNumericValue(source[currentPosition++])) + // > 15 // || c1 < 0) - // || ((c2 = Character.getNumericValue(source[currentPosition++])) > 15 + // || ((c2 = Character.getNumericValue(source[currentPosition++])) > + // 15 // || c2 < 0) - // || ((c3 = Character.getNumericValue(source[currentPosition++])) > 15 + // || ((c3 = Character.getNumericValue(source[currentPosition++])) > + // 15 // || c3 < 0) - // || ((c4 = Character.getNumericValue(source[currentPosition++])) > 15 + // || ((c4 = Character.getNumericValue(source[currentPosition++])) > + // 15 // || c4 < 0)) { // currentPosition = temp; // return 2; @@ -649,7 +703,8 @@ public class Scanner implements IScanner, ITerminalSymbols { // //need the unicode buffer // if (withoutUnicodePtr == 0) { // //buffer all the entries that have been left aside.... - // withoutUnicodePtr = currentPosition - unicodeSize - startPosition; + // withoutUnicodePtr = currentPosition - unicodeSize - + // startPosition; // System.arraycopy( // source, // startPosition, @@ -704,13 +759,17 @@ public class Scanner implements IScanner, ITerminalSymbols { // unicodeSize++; // } // - // if (((c1 = Character.getNumericValue(source[currentPosition++])) > 15 + // if (((c1 = Character.getNumericValue(source[currentPosition++])) + // > 15 // || c1 < 0) - // || ((c2 = Character.getNumericValue(source[currentPosition++])) > 15 + // || ((c2 = Character.getNumericValue(source[currentPosition++])) > + // 15 // || c2 < 0) - // || ((c3 = Character.getNumericValue(source[currentPosition++])) > 15 + // || ((c3 = Character.getNumericValue(source[currentPosition++])) > + // 15 // || c3 < 0) - // || ((c4 = Character.getNumericValue(source[currentPosition++])) > 15 + // || ((c4 = Character.getNumericValue(source[currentPosition++])) > + // 15 // || c4 < 0)) { // currentPosition = temp; // return false; @@ -725,7 +784,8 @@ public class Scanner implements IScanner, ITerminalSymbols { // //need the unicode buffer // if (withoutUnicodePtr == 0) { // //buffer all the entries that have been left aside.... - // withoutUnicodePtr = currentPosition - unicodeSize - startPosition; + // withoutUnicodePtr = currentPosition - unicodeSize - + // startPosition; // System.arraycopy( // source, // startPosition, @@ -759,7 +819,8 @@ public class Scanner implements IScanner, ITerminalSymbols { // internal values // At the end of this method currentCharacter holds the new visited char // and currentPosition points right next after it - // Both previous lines are true if the currentCharacter is a digit base on + // Both previous lines are true if the currentCharacter is a digit base + // on // radix // On false, no side effect has occured. // ALL getNextChar.... ARE OPTIMIZED COPIES @@ -777,13 +838,17 @@ public class Scanner implements IScanner, ITerminalSymbols { // unicodeSize++; // } // - // if (((c1 = Character.getNumericValue(source[currentPosition++])) > 15 + // if (((c1 = Character.getNumericValue(source[currentPosition++])) + // > 15 // || c1 < 0) - // || ((c2 = Character.getNumericValue(source[currentPosition++])) > 15 + // || ((c2 = Character.getNumericValue(source[currentPosition++])) > + // 15 // || c2 < 0) - // || ((c3 = Character.getNumericValue(source[currentPosition++])) > 15 + // || ((c3 = Character.getNumericValue(source[currentPosition++])) > + // 15 // || c3 < 0) - // || ((c4 = Character.getNumericValue(source[currentPosition++])) > 15 + // || ((c4 = Character.getNumericValue(source[currentPosition++])) > + // 15 // || c4 < 0)) { // currentPosition = temp; // return false; @@ -798,7 +863,8 @@ public class Scanner implements IScanner, ITerminalSymbols { // //need the unicode buffer // if (withoutUnicodePtr == 0) { // //buffer all the entries that have been left aside.... - // withoutUnicodePtr = currentPosition - unicodeSize - startPosition; + // withoutUnicodePtr = currentPosition - unicodeSize - + // startPosition; // System.arraycopy( // source, // startPosition, @@ -850,13 +916,17 @@ public class Scanner implements IScanner, ITerminalSymbols { // unicodeSize++; // } // - // if (((c1 = Character.getNumericValue(source[currentPosition++])) > 15 + // if (((c1 = Character.getNumericValue(source[currentPosition++])) + // > 15 // || c1 < 0) - // || ((c2 = Character.getNumericValue(source[currentPosition++])) > 15 + // || ((c2 = Character.getNumericValue(source[currentPosition++])) > + // 15 // || c2 < 0) - // || ((c3 = Character.getNumericValue(source[currentPosition++])) > 15 + // || ((c3 = Character.getNumericValue(source[currentPosition++])) > + // 15 // || c3 < 0) - // || ((c4 = Character.getNumericValue(source[currentPosition++])) > 15 + // || ((c4 = Character.getNumericValue(source[currentPosition++])) > + // 15 // || c4 < 0)) { // currentPosition = temp; // return false; @@ -871,7 +941,8 @@ public class Scanner implements IScanner, ITerminalSymbols { // //need the unicode buffer // if (withoutUnicodePtr == 0) { // //buffer all the entries that have been left aside.... - // withoutUnicodePtr = currentPosition - unicodeSize - startPosition; + // withoutUnicodePtr = currentPosition - unicodeSize - + // startPosition; // System.arraycopy( // source, // startPosition, @@ -920,19 +991,23 @@ public class Scanner implements IScanner, ITerminalSymbols { switch (data.length) { case 3: // int - if ((data[index] == 'i') && (data[++index] == 'n') && (data[++index] == 't')) { + if ((data[index] == 'i') && (data[++index] == 'n') + && (data[++index] == 't')) { found = true; tempToken = TokenNameintCAST; } break; case 4: // bool real - if ((data[index] == 'b') && (data[++index] == 'o') && (data[++index] == 'o') && (data[++index] == 'l')) { + if ((data[index] == 'b') && (data[++index] == 'o') + && (data[++index] == 'o') && (data[++index] == 'l')) { found = true; tempToken = TokenNameboolCAST; } else { index = 0; - if ((data[index] == 'r') && (data[++index] == 'e') && (data[++index] == 'a') && (data[++index] == 'l')) { + if ((data[index] == 'r') && (data[++index] == 'e') + && (data[++index] == 'a') + && (data[++index] == 'l')) { found = true; tempToken = TokenNamedoubleCAST; } @@ -940,19 +1015,24 @@ public class Scanner implements IScanner, ITerminalSymbols { break; case 5: // array unset float - if ((data[index] == 'a') && (data[++index] == 'r') && (data[++index] == 'r') && (data[++index] == 'a') + if ((data[index] == 'a') && (data[++index] == 'r') + && (data[++index] == 'r') && (data[++index] == 'a') && (data[++index] == 'y')) { found = true; tempToken = TokenNamearrayCAST; } else { index = 0; - if ((data[index] == 'u') && (data[++index] == 'n') && (data[++index] == 's') && (data[++index] == 'e') + if ((data[index] == 'u') && (data[++index] == 'n') + && (data[++index] == 's') + && (data[++index] == 'e') && (data[++index] == 't')) { found = true; tempToken = TokenNameunsetCAST; } else { index = 0; - if ((data[index] == 'f') && (data[++index] == 'l') && (data[++index] == 'o') && (data[++index] == 'a') + if ((data[index] == 'f') && (data[++index] == 'l') + && (data[++index] == 'o') + && (data[++index] == 'a') && (data[++index] == 't')) { found = true; tempToken = TokenNamedoubleCAST; @@ -962,20 +1042,27 @@ public class Scanner implements IScanner, ITerminalSymbols { break; case 6: // object string double - if ((data[index] == 'o') && (data[++index] == 'b') && (data[++index] == 'j') && (data[++index] == 'e') + if ((data[index] == 'o') && (data[++index] == 'b') + && (data[++index] == 'j') && (data[++index] == 'e') && (data[++index] == 'c') && (data[++index] == 't')) { found = true; tempToken = TokenNameobjectCAST; } else { index = 0; - if ((data[index] == 's') && (data[++index] == 't') && (data[++index] == 'r') && (data[++index] == 'i') - && (data[++index] == 'n') && (data[++index] == 'g')) { + if ((data[index] == 's') && (data[++index] == 't') + && (data[++index] == 'r') + && (data[++index] == 'i') + && (data[++index] == 'n') + && (data[++index] == 'g')) { found = true; tempToken = TokenNamestringCAST; } else { index = 0; - if ((data[index] == 'd') && (data[++index] == 'o') && (data[++index] == 'u') && (data[++index] == 'b') - && (data[++index] == 'l') && (data[++index] == 'e')) { + if ((data[index] == 'd') && (data[++index] == 'o') + && (data[++index] == 'u') + && (data[++index] == 'b') + && (data[++index] == 'l') + && (data[++index] == 'e')) { found = true; tempToken = TokenNamedoubleCAST; } @@ -984,14 +1071,20 @@ public class Scanner implements IScanner, ITerminalSymbols { break; case 7: // boolean integer - if ((data[index] == 'b') && (data[++index] == 'o') && (data[++index] == 'o') && (data[++index] == 'l') - && (data[++index] == 'e') && (data[++index] == 'a') && (data[++index] == 'n')) { + if ((data[index] == 'b') && (data[++index] == 'o') + && (data[++index] == 'o') && (data[++index] == 'l') + && (data[++index] == 'e') && (data[++index] == 'a') + && (data[++index] == 'n')) { found = true; tempToken = TokenNameboolCAST; } else { index = 0; - if ((data[index] == 'i') && (data[++index] == 'n') && (data[++index] == 't') && (data[++index] == 'e') - && (data[++index] == 'g') && (data[++index] == 'e') && (data[++index] == 'r')) { + if ((data[index] == 'i') && (data[++index] == 'n') + && (data[++index] == 't') + && (data[++index] == 'e') + && (data[++index] == 'g') + && (data[++index] == 'e') + && (data[++index] == 'r')) { found = true; tempToken = TokenNameintCAST; } @@ -1032,7 +1125,8 @@ public class Scanner implements IScanner, ITerminalSymbols { /** ** in PHP \r and \n are valid in string literals *** */ // if ((currentCharacter == '\n') // || (currentCharacter == '\r')) { - // // relocate if finding another quote fairly close: thus unicode + // // relocate if finding another quote fairly close: thus + // unicode // '/u000D' will be fully consumed // for (int lookAhead = 0; lookAhead < 50; lookAhead++) { // if (currentPosition + lookAhead == source.length) @@ -1049,23 +1143,28 @@ public class Scanner implements IScanner, ITerminalSymbols { if (currentCharacter == '\\') { int escapeSize = currentPosition; boolean backSlashAsUnicodeInString = unicodeAsBackSlash; - // scanEscapeCharacter make a side effect on this value and we need + // scanEscapeCharacter make a side effect on this value and + // we need // the previous value few lines down this one scanDoubleQuotedEscapeCharacter(); escapeSize = currentPosition - escapeSize; if (withoutUnicodePtr == 0) { // buffer all the entries that have been left aside.... - withoutUnicodePtr = currentPosition - escapeSize - 1 - startPosition; - System.arraycopy(source, startPosition, withoutUnicodeBuffer, 1, withoutUnicodePtr); + withoutUnicodePtr = currentPosition - escapeSize - 1 + - startPosition; + System.arraycopy(source, startPosition, + withoutUnicodeBuffer, 1, withoutUnicodePtr); withoutUnicodeBuffer[++withoutUnicodePtr] = currentCharacter; } else { // overwrite the / in the buffer withoutUnicodeBuffer[withoutUnicodePtr] = currentCharacter; - if (backSlashAsUnicodeInString) { // there are TWO \ in the stream + if (backSlashAsUnicodeInString) { // there are TWO \ + // in the stream // where only one is correct withoutUnicodePtr--; } } - } else if ((currentCharacter == '\r') || (currentCharacter == '\n')) { + } else if ((currentCharacter == '\r') + || (currentCharacter == '\n')) { if (recordLineSeparator) { pushLineSeparator(); } @@ -1103,14 +1202,16 @@ public class Scanner implements IScanner, ITerminalSymbols { } throw e; // rethrow } - if (checkNonExternalizedStringLiterals) { // check for presence of NLS tags + if (checkNonExternalizedStringLiterals) { // check for presence of NLS + // tags // //$NON-NLS-?$ where ? is an // int. if (currentLine == null) { currentLine = new NLSLine(); lines.add(currentLine); } - currentLine.add(new StringLiteral(getCurrentTokenSourceString(), startPosition, currentPosition - 1)); + currentLine.add(new StringLiteral(getCurrentTokenSourceString(), + startPosition, currentPosition - 1)); } } @@ -1132,7 +1233,8 @@ public class Scanner implements IScanner, ITerminalSymbols { /** ** in PHP \r and \n are valid in string literals *** */ // if ((currentCharacter == '\n') // || (currentCharacter == '\r')) { - // // relocate if finding another quote fairly close: thus unicode + // // relocate if finding another quote fairly close: thus + // unicode // '/u000D' will be fully consumed // for (int lookAhead = 0; lookAhead < 50; lookAhead++) { // if (currentPosition + lookAhead == source.length) @@ -1149,23 +1251,28 @@ public class Scanner implements IScanner, ITerminalSymbols { if (currentCharacter == '\\') { int escapeSize = currentPosition; boolean backSlashAsUnicodeInString = unicodeAsBackSlash; - // scanEscapeCharacter make a side effect on this value and we need + // scanEscapeCharacter make a side effect on this value and + // we need // the previous value few lines down this one scanSingleQuotedEscapeCharacter(); escapeSize = currentPosition - escapeSize; if (withoutUnicodePtr == 0) { // buffer all the entries that have been left aside.... - withoutUnicodePtr = currentPosition - escapeSize - 1 - startPosition; - System.arraycopy(source, startPosition, withoutUnicodeBuffer, 1, withoutUnicodePtr); + withoutUnicodePtr = currentPosition - escapeSize - 1 + - startPosition; + System.arraycopy(source, startPosition, + withoutUnicodeBuffer, 1, withoutUnicodePtr); withoutUnicodeBuffer[++withoutUnicodePtr] = currentCharacter; } else { // overwrite the / in the buffer withoutUnicodeBuffer[withoutUnicodePtr] = currentCharacter; - if (backSlashAsUnicodeInString) { // there are TWO \ in the stream + if (backSlashAsUnicodeInString) { // there are TWO \ + // in the stream // where only one is correct withoutUnicodePtr--; } } - } else if ((currentCharacter == '\r') || (currentCharacter == '\n')) { + } else if ((currentCharacter == '\r') + || (currentCharacter == '\n')) { if (recordLineSeparator) { pushLineSeparator(); } @@ -1203,14 +1310,16 @@ public class Scanner implements IScanner, ITerminalSymbols { } throw e; // rethrow } - if (checkNonExternalizedStringLiterals) { // check for presence of NLS tags + if (checkNonExternalizedStringLiterals) { // check for presence of NLS + // tags // //$NON-NLS-?$ where ? is an // int. if (currentLine == null) { currentLine = new NLSLine(); lines.add(currentLine); } - currentLine.add(new StringLiteral(getCurrentTokenSourceString(), startPosition, currentPosition - 1)); + currentLine.add(new StringLiteral(getCurrentTokenSourceString(), + startPosition, currentPosition - 1)); } } @@ -1220,34 +1329,41 @@ public class Scanner implements IScanner, ITerminalSymbols { // consume next character unicodeAsBackSlash = false; currentCharacter = source[currentPosition++]; - while (currentCharacter != '"' || openDollarBrace>0) { + while (currentCharacter != '"' || openDollarBrace > 0) { /** ** in PHP \r and \n are valid in string literals *** */ if (currentCharacter == '\\') { int escapeSize = currentPosition; boolean backSlashAsUnicodeInString = unicodeAsBackSlash; - // scanEscapeCharacter make a side effect on this value and we need + // scanEscapeCharacter make a side effect on this value and + // we need // the previous value few lines down this one scanDoubleQuotedEscapeCharacter(); escapeSize = currentPosition - escapeSize; if (withoutUnicodePtr == 0) { // buffer all the entries that have been left aside.... - withoutUnicodePtr = currentPosition - escapeSize - 1 - startPosition; - System.arraycopy(source, startPosition, withoutUnicodeBuffer, 1, withoutUnicodePtr); + withoutUnicodePtr = currentPosition - escapeSize - 1 + - startPosition; + System.arraycopy(source, startPosition, + withoutUnicodeBuffer, 1, withoutUnicodePtr); withoutUnicodeBuffer[++withoutUnicodePtr] = currentCharacter; } else { // overwrite the / in the buffer withoutUnicodeBuffer[withoutUnicodePtr] = currentCharacter; - if (backSlashAsUnicodeInString) { // there are TWO \ in the stream + if (backSlashAsUnicodeInString) { // there are TWO \ + // in the stream // where only one is correct withoutUnicodePtr--; } } - } else if (currentCharacter == '$' && source[currentPosition] == '{') { + } else if (currentCharacter == '$' + && source[currentPosition] == '{') { openDollarBrace++; - } else if (currentCharacter == '{' && source[currentPosition] == '$') { + } else if (currentCharacter == '{' + && source[currentPosition] == '$') { openDollarBrace++; } else if (currentCharacter == '}') { openDollarBrace--; - } else if ((currentCharacter == '\r') || (currentCharacter == '\n')) { + } else if ((currentCharacter == '\r') + || (currentCharacter == '\n')) { if (recordLineSeparator) { pushLineSeparator(); } @@ -1280,14 +1396,16 @@ public class Scanner implements IScanner, ITerminalSymbols { } throw e; // rethrow } - if (checkNonExternalizedStringLiterals) { // check for presence of NLS tags + if (checkNonExternalizedStringLiterals) { // check for presence of NLS + // tags // //$NON-NLS-?$ where ? is an // int. if (currentLine == null) { currentLine = new NLSLine(); lines.add(currentLine); } - currentLine.add(new StringLiteral(getCurrentTokenSourceString(), startPosition, currentPosition - 1)); + currentLine.add(new StringLiteral(getCurrentTokenSourceString(), + startPosition, currentPosition - 1)); } } @@ -1306,20 +1424,24 @@ public class Scanner implements IScanner, ITerminalSymbols { if (diet) { jumpOverMethodBody(); diet = false; - return currentPosition > source.length ? TokenNameEOF : TokenNameRBRACE; + return currentPosition > source.length ? TokenNameEOF + : TokenNameRBRACE; } try { while (true) { withoutUnicodePtr = 0; - // ---------Consume white space and handles startPosition--------- + // ---------Consume white space and handles + // startPosition--------- int whiteStart = currentPosition; startPosition = currentPosition; currentCharacter = source[currentPosition++]; - while ((currentCharacter == ' ') || Character.isWhitespace(currentCharacter)) { + while ((currentCharacter == ' ') + || Character.isWhitespace(currentCharacter)) { startPosition = currentPosition; currentCharacter = source[currentPosition++]; - if ((currentCharacter == '\r') || (currentCharacter == '\n')) { + if ((currentCharacter == '\r') + || (currentCharacter == '\n')) { checkNonExternalizeString(); if (recordLineSeparator) { pushLineSeparator(); @@ -1328,13 +1450,16 @@ public class Scanner implements IScanner, ITerminalSymbols { } } } - if (tokenizeWhiteSpace && (whiteStart != currentPosition - 1)) { - // reposition scanner in case we are interested by spaces as tokens + if (tokenizeWhiteSpace + && (whiteStart != currentPosition - 1)) { + // reposition scanner in case we are interested by + // spaces as tokens currentPosition--; startPosition = whiteStart; return TokenNameWHITESPACE; } - // little trick to get out in the middle of a source compuation + // little trick to get out in the middle of a source + // compuation if (currentPosition > eofPosition) return TokenNameEOF; // ---------Identify the next token------------- @@ -1430,7 +1555,8 @@ public class Scanner implements IScanner, ITerminalSymbols { while (isPHPIdentifierPart(currentCharacter)) { currentCharacter = source[currentPosition++]; } - heredocLength = currentPosition - heredocStart - 1; + heredocLength = currentPosition - heredocStart + - 1; // heredoc end-tag determination boolean endTag = true; char ch; @@ -1443,7 +1569,8 @@ public class Scanner implements IScanner, ITerminalSymbols { currentLine = null; } for (int i = 0; i < heredocLength; i++) { - if (source[currentPosition + i] != source[heredocStart + i]) { + if (source[currentPosition + i] != source[heredocStart + + i]) { endTag = false; break; } @@ -1528,14 +1655,14 @@ public class Scanner implements IScanner, ITerminalSymbols { // if (tokenizeStrings) { consumeStringLiteral(); return TokenNameStringDoubleQuote; - // } - // return TokenNameEncapsedString2; + // } + // return TokenNameEncapsedString2; case '`': // if (tokenizeStrings) { consumeStringInterpolated(); return TokenNameStringInterpolated; - // } - // return TokenNameEncapsedString0; + // } + // return TokenNameEncapsedString0; case '#': case '/': { char startChar = currentCharacter; @@ -1543,16 +1670,19 @@ public class Scanner implements IScanner, ITerminalSymbols { return TokenNameDIVIDE_EQUAL; } int test; - if ((startChar == '#') || (test = getNextChar('/', '*')) == 0) { + if ((startChar == '#') + || (test = getNextChar('/', '*')) == 0) { // line comment this.lastCommentLinePosition = this.currentPosition; int endPositionForLineComment = 0; try { // get the next char currentCharacter = source[currentPosition++]; - // if (((currentCharacter = source[currentPosition++]) + // if (((currentCharacter = + // source[currentPosition++]) // == '\\') // && (source[currentPosition] == 'u')) { - // //-------------unicode traitement ------------ + // //-------------unicode traitement + // ------------ // int c1 = 0, c2 = 0, c3 = 0, c4 = 0; // currentPosition++; // while (source[currentPosition] == 'u') { @@ -1578,7 +1708,8 @@ public class Scanner implements IScanner, ITerminalSymbols { // InvalidInputException(INVALID_UNICODE_ESCAPE); // } else { // currentCharacter = - // (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); + // (char) (((c1 * 16 + c2) * 16 + c3) * 16 + + // c4); // } // } // handle the \\u case manually into comment @@ -1587,7 +1718,8 @@ public class Scanner implements IScanner, ITerminalSymbols { // currentPosition++; // } //jump over the \\ boolean isUnicode = false; - while (currentCharacter != '\r' && currentCharacter != '\n') { + while (currentCharacter != '\r' + && currentCharacter != '\n') { this.lastCommentLinePosition = this.currentPosition; if (currentCharacter == '?') { if (getNextChar('>')) { @@ -1600,11 +1732,13 @@ public class Scanner implements IScanner, ITerminalSymbols { // get the next char isUnicode = false; currentCharacter = source[currentPosition++]; - // if (((currentCharacter = source[currentPosition++]) + // if (((currentCharacter = + // source[currentPosition++]) // == '\\') // && (source[currentPosition] == 'u')) { // isUnicode = true; - // //-------------unicode traitement ------------ + // //-------------unicode traitement + // ------------ // int c1 = 0, c2 = 0, c3 = 0, c4 = 0; // currentPosition++; // while (source[currentPosition] == 'u') { @@ -1633,7 +1767,8 @@ public class Scanner implements IScanner, ITerminalSymbols { // InvalidInputException(INVALID_UNICODE_ESCAPE); // } else { // currentCharacter = - // (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); + // (char) (((c1 * 16 + c2) * 16 + c3) * 16 + + // c4); // } // } // handle the \\u case manually into comment @@ -1650,8 +1785,10 @@ public class Scanner implements IScanner, ITerminalSymbols { // recordComment(false); recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) - checkTaskTag(this.startPosition, this.currentPosition); - if ((currentCharacter == '\r') || (currentCharacter == '\n')) { + checkTaskTag(this.startPosition, + this.currentPosition); + if ((currentCharacter == '\r') + || (currentCharacter == '\n')) { checkNonExternalizeString(); if (recordLineSeparator) { if (isUnicode) { @@ -1670,7 +1807,8 @@ public class Scanner implements IScanner, ITerminalSymbols { } return TokenNameCOMMENT_LINE; } - } catch (IndexOutOfBoundsException e) { // an eof will them + } catch (IndexOutOfBoundsException e) { // an eof + // will them // be generated if (tokenizeComments) { currentPosition--; @@ -1686,7 +1824,8 @@ public class Scanner implements IScanner, ITerminalSymbols { // consume next character unicodeAsBackSlash = false; currentCharacter = source[currentPosition++]; - // if (((currentCharacter = source[currentPosition++]) == + // if (((currentCharacter = + // source[currentPosition++]) == // '\\') // && (source[currentPosition] == 'u')) { // getNextUnicodeChar(); @@ -1700,7 +1839,8 @@ public class Scanner implements IScanner, ITerminalSymbols { isJavadoc = true; star = true; } - if ((currentCharacter == '\r') || (currentCharacter == '\n')) { + if ((currentCharacter == '\r') + || (currentCharacter == '\n')) { checkNonExternalizeString(); if (recordLineSeparator) { pushLineSeparator(); @@ -1710,10 +1850,12 @@ public class Scanner implements IScanner, ITerminalSymbols { } try { // get the next char currentCharacter = source[currentPosition++]; - // if (((currentCharacter = source[currentPosition++]) + // if (((currentCharacter = + // source[currentPosition++]) // == '\\') // && (source[currentPosition] == 'u')) { - // //-------------unicode traitement ------------ + // //-------------unicode traitement + // ------------ // getNextUnicodeChar(); // } // handle the \\u case manually into comment @@ -1728,7 +1870,8 @@ public class Scanner implements IScanner, ITerminalSymbols { } // loop until end of comment */ while ((currentCharacter != '/') || (!star)) { - if ((currentCharacter == '\r') || (currentCharacter == '\n')) { + if ((currentCharacter == '\r') + || (currentCharacter == '\n')) { checkNonExternalizeString(); if (recordLineSeparator) { pushLineSeparator(); @@ -1739,10 +1882,12 @@ public class Scanner implements IScanner, ITerminalSymbols { star = currentCharacter == '*'; // get next char currentCharacter = source[currentPosition++]; - // if (((currentCharacter = source[currentPosition++]) + // if (((currentCharacter = + // source[currentPosition++]) // == '\\') // && (source[currentPosition] == 'u')) { - // //-------------unicode traitement ------------ + // //-------------unicode traitement + // ------------ // getNextUnicodeChar(); // } // handle the \\u case manually into comment @@ -1765,12 +1910,14 @@ public class Scanner implements IScanner, ITerminalSymbols { } if (this.taskTags != null) { - checkTaskTag(this.startPosition, this.currentPosition); + checkTaskTag(this.startPosition, + this.currentPosition); } } catch (IndexOutOfBoundsException e) { // reset end position for error reporting currentPosition -= 2; - throw new InvalidInputException(UNTERMINATED_COMMENT); + throw new InvalidInputException( + UNTERMINATED_COMMENT); } break; } @@ -1779,7 +1926,8 @@ public class Scanner implements IScanner, ITerminalSymbols { case '\u001a': if (atEnd()) return TokenNameEOF; - // the atEnd may not be if + // the atEnd may not be if // source is only some part of a real (external) stream throw new InvalidInputException("Ctrl-Z"); //$NON-NLS-1$ default: @@ -1829,7 +1977,8 @@ public class Scanner implements IScanner, ITerminalSymbols { if (currentCharacter == '<') { if (getNextChar('?')) { currentCharacter = source[currentPosition++]; - if ((currentCharacter != 'P') && (currentCharacter != 'p')) { + if ((currentCharacter != 'P') + && (currentCharacter != 'p')) { if (currentCharacter != '=') { // =0) { - if (getNextChar('M','m')>=0) { - if (getNextChar('L','l')>=0) { - foundXML=true; + boolean foundXML = false; + if (getNextChar('X', 'x') >= 0) { + if (getNextChar('M', 'm') >= 0) { + if (getNextChar('L', 'l') >= 0) { + foundXML = true; } } } @@ -1902,7 +2051,7 @@ public class Scanner implements IScanner, ITerminalSymbols { /** * check if the PHP is only in this line (for CodeFormatter) - * + * * @return */ private int lookAheadLinePHPTag() { @@ -1962,13 +2111,15 @@ public class Scanner implements IScanner, ITerminalSymbols { } break; case '/': - if (previousCharInLine == '/' && !singleQuotedStringActive && !doubleQuotedStringActive) { + if (previousCharInLine == '/' && !singleQuotedStringActive + && !doubleQuotedStringActive) { phpMode = true; return TokenNameINLINE_HTML; } break; case '*': - if (previousCharInLine == '/' && !singleQuotedStringActive && !doubleQuotedStringActive) { + if (previousCharInLine == '/' && !singleQuotedStringActive + && !doubleQuotedStringActive) { phpMode = true; return TokenNameINLINE_HTML; } @@ -2028,23 +2179,27 @@ public class Scanner implements IScanner, ITerminalSymbols { // unicodeAsBackSlash = currentCharacter == '\\'; // } /* - * Tokenize a method body, assuming that curly brackets are properly balanced. + * Tokenize a method body, assuming that curly brackets are properly + * balanced. */ public final void jumpOverMethodBody() { this.wasAcr = false; int found = 1; try { while (true) { // loop for jumping over comments - // ---------Consume white space and handles startPosition--------- + // ---------Consume white space and handles + // startPosition--------- boolean isWhiteSpace; do { startPosition = currentPosition; currentCharacter = source[currentPosition++]; - // if (((currentCharacter = source[currentPosition++]) == '\\') + // if (((currentCharacter = source[currentPosition++]) == + // '\\') // && (source[currentPosition] == 'u')) { // isWhiteSpace = jumpOverUnicodeWhiteSpace(); // } else { - if (recordLineSeparator && ((currentCharacter == '\r') || (currentCharacter == '\n'))) + if (recordLineSeparator + && ((currentCharacter == '\r') || (currentCharacter == '\n'))) pushLineSeparator(); isWhiteSpace = Character.isWhitespace(currentCharacter); // } @@ -2072,7 +2227,8 @@ public class Scanner implements IScanner, ITerminalSymbols { // try { // consume next character unicodeAsBackSlash = false; currentCharacter = source[currentPosition++]; - // if (((currentCharacter = source[currentPosition++]) == '\\') + // if (((currentCharacter = source[currentPosition++]) + // == '\\') // && (source[currentPosition] == 'u')) { // getNextUnicodeChar(); // } else { @@ -2091,7 +2247,8 @@ public class Scanner implements IScanner, ITerminalSymbols { // try { // consume next character unicodeAsBackSlash = false; currentCharacter = source[currentPosition++]; - // if (((currentCharacter = source[currentPosition++]) == '\\') + // if (((currentCharacter = source[currentPosition++]) + // == '\\') // && (source[currentPosition] == 'u')) { // getNextUnicodeChar(); // } else { @@ -2122,7 +2279,8 @@ public class Scanner implements IScanner, ITerminalSymbols { // try { // consume next character unicodeAsBackSlash = false; currentCharacter = source[currentPosition++]; - // if (((currentCharacter = source[currentPosition++]) == '\\') + // if (((currentCharacter = + // source[currentPosition++]) == '\\') // && (source[currentPosition] == 'u')) { // getNextUnicodeChar(); // } else { @@ -2144,7 +2302,8 @@ public class Scanner implements IScanner, ITerminalSymbols { try { // get the next char currentCharacter = source[currentPosition++]; - // if (((currentCharacter = source[currentPosition++]) == + // if (((currentCharacter = + // source[currentPosition++]) == // '\\') // && (source[currentPosition] == 'u')) { // //-------------unicode traitement ------------ @@ -2177,13 +2336,16 @@ public class Scanner implements IScanner, ITerminalSymbols { // (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); // } // } - while (currentCharacter != '\r' && currentCharacter != '\n') { + while (currentCharacter != '\r' + && currentCharacter != '\n') { // get the next char currentCharacter = source[currentPosition++]; - // if (((currentCharacter = source[currentPosition++]) + // if (((currentCharacter = + // source[currentPosition++]) // == '\\') // && (source[currentPosition] == 'u')) { - // //-------------unicode traitement ------------ + // //-------------unicode traitement + // ------------ // int c1 = 0, c2 = 0, c3 = 0, c4 = 0; // currentPosition++; // while (source[currentPosition] == 'u') { @@ -2210,11 +2372,13 @@ public class Scanner implements IScanner, ITerminalSymbols { // } //something different from \n and \r // else { // currentCharacter = - // (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); + // (char) (((c1 * 16 + c2) * 16 + c3) * 16 + + // c4); // } // } } - if (recordLineSeparator && ((currentCharacter == '\r') || (currentCharacter == '\n'))) + if (recordLineSeparator + && ((currentCharacter == '\r') || (currentCharacter == '\n'))) pushLineSeparator(); } catch (IndexOutOfBoundsException e) { } // an eof will them be generated @@ -2226,7 +2390,8 @@ public class Scanner implements IScanner, ITerminalSymbols { // try { // consume next character unicodeAsBackSlash = false; currentCharacter = source[currentPosition++]; - // if (((currentCharacter = source[currentPosition++]) == '\\') + // if (((currentCharacter = source[currentPosition++]) + // == '\\') // && (source[currentPosition] == 'u')) { // getNextUnicodeChar(); // } else { @@ -2239,11 +2404,13 @@ public class Scanner implements IScanner, ITerminalSymbols { if (currentCharacter == '*') { star = true; } - if (recordLineSeparator && ((currentCharacter == '\r') || (currentCharacter == '\n'))) + if (recordLineSeparator + && ((currentCharacter == '\r') || (currentCharacter == '\n'))) pushLineSeparator(); try { // get the next char currentCharacter = source[currentPosition++]; - // if (((currentCharacter = source[currentPosition++]) == + // if (((currentCharacter = + // source[currentPosition++]) == // '\\') // && (source[currentPosition] == 'u')) { // //-------------unicode traitement ------------ @@ -2278,15 +2445,18 @@ public class Scanner implements IScanner, ITerminalSymbols { // } // loop until end of comment */ while ((currentCharacter != '/') || (!star)) { - if (recordLineSeparator && ((currentCharacter == '\r') || (currentCharacter == '\n'))) + if (recordLineSeparator + && ((currentCharacter == '\r') || (currentCharacter == '\n'))) pushLineSeparator(); star = currentCharacter == '*'; // get next char currentCharacter = source[currentPosition++]; - // if (((currentCharacter = source[currentPosition++]) + // if (((currentCharacter = + // source[currentPosition++]) // == '\\') // && (source[currentPosition] == 'u')) { - // //-------------unicode traitement ------------ + // //-------------unicode traitement + // ------------ // int c1 = 0, c2 = 0, c3 = 0, c4 = 0; // currentPosition++; // while (source[currentPosition] == 'u') { @@ -2313,7 +2483,8 @@ public class Scanner implements IScanner, ITerminalSymbols { // } //something different from * and / // else { // currentCharacter = - // (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); + // (char) (((c1 * 16 + c2) * 16 + c3) * 16 + + // c4); // } // } } @@ -2398,7 +2569,8 @@ public class Scanner implements IScanner, ITerminalSymbols { public final int[] getLineEnds() { // return a bounded copy of this.lineEnds int[] copy; - System.arraycopy(lineEnds, 0, copy = new int[linePtr + 1], 0, linePtr + 1); + System.arraycopy(lineEnds, 0, copy = new int[linePtr + 1], 0, + linePtr + 1); return copy; } @@ -2478,7 +2650,8 @@ public class Scanner implements IScanner, ITerminalSymbols { c1 = source[startPosition + 1]; if (c0 == '$') { // return always the same char[] build only once - // optimization at no speed cost of 99.5 % of the singleCharIdentifier + // optimization at no speed cost of 99.5 % of the + // singleCharIdentifier switch (c1) { case 'a': return charArray_va; @@ -2563,13 +2736,15 @@ public class Scanner implements IScanner, ITerminalSymbols { final char[] optimizedCurrentTokenSource3() { // try to return the same char[] build only once char c0, c1, c2; - int hash = (((c0 = source[startPosition]) << 12) + ((c1 = source[startPosition + 1]) << 6) + (c2 = source[startPosition + 2])) + int hash = (((c0 = source[startPosition]) << 12) + + ((c1 = source[startPosition + 1]) << 6) + (c2 = source[startPosition + 2])) % TableSize; char[][] table = charArray_length[1][hash]; int i = newEntry3; while (++i < InternalTableSize) { char[] charArray = table[i]; - if ((c0 == charArray[0]) && (c1 == charArray[1]) && (c2 == charArray[2])) + if ((c0 == charArray[0]) && (c1 == charArray[1]) + && (c2 == charArray[2])) return charArray; } // ---------other side--------- @@ -2577,7 +2752,8 @@ public class Scanner implements IScanner, ITerminalSymbols { int max = newEntry3; while (++i <= max) { char[] charArray = table[i]; - if ((c0 == charArray[0]) && (c1 == charArray[1]) && (c2 == charArray[2])) + if ((c0 == charArray[0]) && (c1 == charArray[1]) + && (c2 == charArray[2])) return charArray; } // --------add the entry------- @@ -2592,14 +2768,16 @@ public class Scanner implements IScanner, ITerminalSymbols { final char[] optimizedCurrentTokenSource4() { // try to return the same char[] build only once char c0, c1, c2, c3; - long hash = ((((long) (c0 = source[startPosition])) << 18) + ((c1 = source[startPosition + 1]) << 12) + long hash = ((((long) (c0 = source[startPosition])) << 18) + + ((c1 = source[startPosition + 1]) << 12) + ((c2 = source[startPosition + 2]) << 6) + (c3 = source[startPosition + 3])) % TableSize; char[][] table = charArray_length[2][(int) hash]; int i = newEntry4; while (++i < InternalTableSize) { char[] charArray = table[i]; - if ((c0 == charArray[0]) && (c1 == charArray[1]) && (c2 == charArray[2]) && (c3 == charArray[3])) + if ((c0 == charArray[0]) && (c1 == charArray[1]) + && (c2 == charArray[2]) && (c3 == charArray[3])) return charArray; } // ---------other side--------- @@ -2607,7 +2785,8 @@ public class Scanner implements IScanner, ITerminalSymbols { int max = newEntry4; while (++i <= max) { char[] charArray = table[i]; - if ((c0 == charArray[0]) && (c1 == charArray[1]) && (c2 == charArray[2]) && (c3 == charArray[3])) + if ((c0 == charArray[0]) && (c1 == charArray[1]) + && (c2 == charArray[2]) && (c3 == charArray[3])) return charArray; } // --------add the entry------- @@ -2622,14 +2801,18 @@ public class Scanner implements IScanner, ITerminalSymbols { final char[] optimizedCurrentTokenSource5() { // try to return the same char[] build only once char c0, c1, c2, c3, c4; - long hash = ((((long) (c0 = source[startPosition])) << 24) + (((long) (c1 = source[startPosition + 1])) << 18) - + ((c2 = source[startPosition + 2]) << 12) + ((c3 = source[startPosition + 3]) << 6) + (c4 = source[startPosition + 4])) + long hash = ((((long) (c0 = source[startPosition])) << 24) + + (((long) (c1 = source[startPosition + 1])) << 18) + + ((c2 = source[startPosition + 2]) << 12) + + ((c3 = source[startPosition + 3]) << 6) + (c4 = source[startPosition + 4])) % TableSize; char[][] table = charArray_length[3][(int) hash]; int i = newEntry5; while (++i < InternalTableSize) { char[] charArray = table[i]; - if ((c0 == charArray[0]) && (c1 == charArray[1]) && (c2 == charArray[2]) && (c3 == charArray[3]) && (c4 == charArray[4])) + if ((c0 == charArray[0]) && (c1 == charArray[1]) + && (c2 == charArray[2]) && (c3 == charArray[3]) + && (c4 == charArray[4])) return charArray; } // ---------other side--------- @@ -2637,7 +2820,9 @@ public class Scanner implements IScanner, ITerminalSymbols { int max = newEntry5; while (++i <= max) { char[] charArray = table[i]; - if ((c0 == charArray[0]) && (c1 == charArray[1]) && (c2 == charArray[2]) && (c3 == charArray[3]) && (c4 == charArray[4])) + if ((c0 == charArray[0]) && (c1 == charArray[1]) + && (c2 == charArray[2]) && (c3 == charArray[3]) + && (c4 == charArray[4])) return charArray; } // --------add the entry------- @@ -2652,16 +2837,19 @@ public class Scanner implements IScanner, ITerminalSymbols { final char[] optimizedCurrentTokenSource6() { // try to return the same char[] build only once char c0, c1, c2, c3, c4, c5; - long hash = ((((long) (c0 = source[startPosition])) << 32) + (((long) (c1 = source[startPosition + 1])) << 24) - + (((long) (c2 = source[startPosition + 2])) << 18) + ((c3 = source[startPosition + 3]) << 12) + long hash = ((((long) (c0 = source[startPosition])) << 32) + + (((long) (c1 = source[startPosition + 1])) << 24) + + (((long) (c2 = source[startPosition + 2])) << 18) + + ((c3 = source[startPosition + 3]) << 12) + ((c4 = source[startPosition + 4]) << 6) + (c5 = source[startPosition + 5])) % TableSize; char[][] table = charArray_length[4][(int) hash]; int i = newEntry6; while (++i < InternalTableSize) { char[] charArray = table[i]; - if ((c0 == charArray[0]) && (c1 == charArray[1]) && (c2 == charArray[2]) && (c3 == charArray[3]) && (c4 == charArray[4]) - && (c5 == charArray[5])) + if ((c0 == charArray[0]) && (c1 == charArray[1]) + && (c2 == charArray[2]) && (c3 == charArray[3]) + && (c4 == charArray[4]) && (c5 == charArray[5])) return charArray; } // ---------other side--------- @@ -2669,8 +2857,9 @@ public class Scanner implements IScanner, ITerminalSymbols { int max = newEntry6; while (++i <= max) { char[] charArray = table[i]; - if ((c0 == charArray[0]) && (c1 == charArray[1]) && (c2 == charArray[2]) && (c3 == charArray[3]) && (c4 == charArray[4]) - && (c5 == charArray[5])) + if ((c0 == charArray[0]) && (c1 == charArray[1]) + && (c2 == charArray[2]) && (c3 == charArray[3]) + && (c4 == charArray[4]) && (c5 == charArray[5])) return charArray; } // --------add the entry------- @@ -2748,7 +2937,8 @@ public class Scanner implements IScanner, ITerminalSymbols { } public final void pushUnicodeLineSeparator() { - // isUnicode means that the \r or \n has been read as a unicode character + // isUnicode means that the \r or \n has been read as a unicode + // character // see comment on isLineDelimiter(char) for the use of '\n' and '\r' final int INCREMENT = 250; // currentCharacter is at position currentPosition-1 @@ -2824,9 +3014,11 @@ public class Scanner implements IScanner, ITerminalSymbols { // a new comment is recorded int length = this.commentStops.length; if (++this.commentPtr >= length) { - System.arraycopy(this.commentStops, 0, this.commentStops = new int[length + 30], 0, length); + System.arraycopy(this.commentStops, 0, + this.commentStops = new int[length + 30], 0, length); // grows the positions buffers too - System.arraycopy(this.commentStarts, 0, this.commentStarts = new int[length + 30], 0, length); + System.arraycopy(this.commentStarts, 0, + this.commentStarts = new int[length + 30], 0, length); } this.commentStops[this.commentPtr] = stopPosition; this.commentStarts[this.commentPtr] = this.startPosition; @@ -2843,7 +3035,8 @@ public class Scanner implements IScanner, ITerminalSymbols { // int[] oldStack = commentStops; // commentStops = new int[oldStackLength + 30]; // System.arraycopy(oldStack, 0, commentStops, 0, oldStackLength); - // commentStops[commentPtr] = isJavadoc ? currentPosition : -currentPosition; + // commentStops[commentPtr] = isJavadoc ? currentPosition : + // -currentPosition; // //grows the positions buffers too // int[] old = commentStarts; // commentStarts = new int[oldStackLength + 30]; @@ -2860,7 +3053,8 @@ public class Scanner implements IScanner, ITerminalSymbols { commentPtr = -1; // reset comment stack } - public final void scanSingleQuotedEscapeCharacter() throws InvalidInputException { + public final void scanSingleQuotedEscapeCharacter() + throws InvalidInputException { // the string with "\\u" is a legal string of two chars \ and u // thus we use a direct access to the source (for regular cases). // if (unicodeAsBackSlash) { @@ -2889,7 +3083,8 @@ public class Scanner implements IScanner, ITerminalSymbols { } } - public final void scanDoubleQuotedEscapeCharacter() throws InvalidInputException { + public final void scanDoubleQuotedEscapeCharacter() + throws InvalidInputException { currentCharacter = source[currentPosition++]; switch (currentCharacter) { // case 'b' : @@ -2927,29 +3122,37 @@ public class Scanner implements IScanner, ITerminalSymbols { int number = Character.getNumericValue(currentCharacter); if (number >= 0 && number <= 7) { boolean zeroToThreeNot = number > 3; - if (Character.isDigit(currentCharacter = source[currentPosition++])) { + if (Character + .isDigit(currentCharacter = source[currentPosition++])) { int digit = Character.getNumericValue(currentCharacter); if (digit >= 0 && digit <= 7) { number = (number * 8) + digit; - if (Character.isDigit(currentCharacter = source[currentPosition++])) { - if (zeroToThreeNot) { // has read \NotZeroToThree OctalDigit + if (Character + .isDigit(currentCharacter = source[currentPosition++])) { + if (zeroToThreeNot) { // has read \NotZeroToThree + // OctalDigit // Digit --> ignore last character currentPosition--; } else { - digit = Character.getNumericValue(currentCharacter); + digit = Character + .getNumericValue(currentCharacter); if (digit >= 0 && digit <= 7) { - // has read \ZeroToThree OctalDigit OctalDigit + // has read \ZeroToThree OctalDigit + // OctalDigit number = (number * 8) + digit; - } else { // has read \ZeroToThree OctalDigit NonOctalDigit + } else { // has read \ZeroToThree OctalDigit + // NonOctalDigit // --> ignore last character currentPosition--; } } - } else { // has read \OctalDigit NonDigit--> ignore last + } else { // has read \OctalDigit NonDigit--> ignore + // last // character currentPosition--; } - } else { // has read \OctalDigit NonOctalDigit--> ignore last + } else { // has read \OctalDigit NonOctalDigit--> ignore + // last // character currentPosition--; } @@ -2960,15 +3163,16 @@ public class Scanner implements IScanner, ITerminalSymbols { throw new InvalidInputException(INVALID_ESCAPE); currentCharacter = (char) number; } - // else - // throw new InvalidInputException(INVALID_ESCAPE); + // else + // throw new InvalidInputException(INVALID_ESCAPE); } } // public int scanIdentifierOrKeyword() throws InvalidInputException { // return scanIdentifierOrKeyword( false ); // } - public int scanIdentifierOrKeyword(boolean isVariable) throws InvalidInputException { + public int scanIdentifierOrKeyword(boolean isVariable) + throws InvalidInputException { // test keywords // first dispatch on the first char. // then the length. If there are several @@ -2988,7 +3192,8 @@ public class Scanner implements IScanner, ITerminalSymbols { char[] data; char firstLetter; // if (withoutUnicodePtr == 0) - // quick test on length == 1 but not on length > 12 while most identifier + // quick test on length == 1 but not on length > 12 while most + // identifier // have a length which is <= 12...but there are lots of identifier with // only one char.... // { @@ -3017,32 +3222,43 @@ public class Scanner implements IScanner, ITerminalSymbols { switch (length) { case 8: // __FILE__ - if ((data[++index] == '_') && (data[++index] == 'f') && (data[++index] == 'i') && (data[++index] == 'l') - && (data[++index] == 'e') && (data[++index] == '_') && (data[++index] == '_')) + if ((data[++index] == '_') && (data[++index] == 'f') + && (data[++index] == 'i') && (data[++index] == 'l') + && (data[++index] == 'e') && (data[++index] == '_') + && (data[++index] == '_')) return TokenNameFILE; index = 0; // __LINE__ - if ((data[++index] == '_') && (data[++index] == 'l') && (data[++index] == 'i') && (data[++index] == 'n') - && (data[++index] == 'e') && (data[++index] == '_') && (data[++index] == '_')) + if ((data[++index] == '_') && (data[++index] == 'l') + && (data[++index] == 'i') && (data[++index] == 'n') + && (data[++index] == 'e') && (data[++index] == '_') + && (data[++index] == '_')) return TokenNameLINE; break; case 9: // __CLASS__ - if ((data[++index] == '_') && (data[++index] == 'c') && (data[++index] == 'l') && (data[++index] == 'a') - && (data[++index] == 's') && (data[++index] == 's') && (data[++index] == '_') && (data[++index] == '_')) + if ((data[++index] == '_') && (data[++index] == 'c') + && (data[++index] == 'l') && (data[++index] == 'a') + && (data[++index] == 's') && (data[++index] == 's') + && (data[++index] == '_') && (data[++index] == '_')) return TokenNameCLASS_C; break; case 11: // __METHOD__ - if ((data[++index] == '_') && (data[++index] == 'm') && (data[++index] == 'e') && (data[++index] == 't') - && (data[++index] == 'h') && (data[++index] == 'o') && (data[++index] == 'd') && (data[++index] == '_') + if ((data[++index] == '_') && (data[++index] == 'm') + && (data[++index] == 'e') && (data[++index] == 't') + && (data[++index] == 'h') && (data[++index] == 'o') + && (data[++index] == 'd') && (data[++index] == '_') && (data[++index] == '_')) return TokenNameMETHOD_C; break; case 12: // __FUNCTION__ - if ((data[++index] == '_') && (data[++index] == 'f') && (data[++index] == 'u') && (data[++index] == 'n') - && (data[++index] == 'c') && (data[++index] == 't') && (data[++index] == 'i') && (data[++index] == 'o') - && (data[++index] == 'n') && (data[++index] == '_') && (data[++index] == '_')) + if ((data[++index] == '_') && (data[++index] == 'f') + && (data[++index] == 'u') && (data[++index] == 'n') + && (data[++index] == 'c') && (data[++index] == 't') + && (data[++index] == 'i') && (data[++index] == 'o') + && (data[++index] == 'n') && (data[++index] == '_') + && (data[++index] == '_')) return TokenNameFUNC_C; break; } @@ -3064,12 +3280,15 @@ public class Scanner implements IScanner, ITerminalSymbols { return TokenNameIdentifier; case 5: // array - if ((data[++index] == 'r') && (data[++index] == 'r') && (data[++index] == 'a') && (data[++index] == 'y')) + if ((data[++index] == 'r') && (data[++index] == 'r') + && (data[++index] == 'a') && (data[++index] == 'y')) return TokenNamearray; return TokenNameIdentifier; case 8: - if ((data[++index] == 'b') && (data[++index] == 's') && (data[++index] == 't') && (data[++index] == 'r') - && (data[++index] == 'a') && (data[++index] == 'c') && (data[++index] == 't')) + if ((data[++index] == 'b') && (data[++index] == 's') + && (data[++index] == 't') && (data[++index] == 'r') + && (data[++index] == 'a') && (data[++index] == 'c') + && (data[++index] == 't')) return TokenNameabstract; return TokenNameIdentifier; } @@ -3078,7 +3297,8 @@ public class Scanner implements IScanner, ITerminalSymbols { // break switch (length) { case 5: - if ((data[++index] == 'r') && (data[++index] == 'e') && (data[++index] == 'a') && (data[++index] == 'k')) + if ((data[++index] == 'r') && (data[++index] == 'e') + && (data[++index] == 'a') && (data[++index] == 'k')) return TokenNamebreak; return TokenNameIdentifier; } @@ -3087,25 +3307,32 @@ public class Scanner implements IScanner, ITerminalSymbols { // case catch class clone const continue switch (length) { case 4: - if ((data[++index] == 'a') && (data[++index] == 's') && (data[++index] == 'e')) + if ((data[++index] == 'a') && (data[++index] == 's') + && (data[++index] == 'e')) return TokenNamecase; return TokenNameIdentifier; case 5: - if ((data[++index] == 'a') && (data[++index] == 't') && (data[++index] == 'c') && (data[++index] == 'h')) + if ((data[++index] == 'a') && (data[++index] == 't') + && (data[++index] == 'c') && (data[++index] == 'h')) return TokenNamecatch; index = 0; - if ((data[++index] == 'l') && (data[++index] == 'a') && (data[++index] == 's') && (data[++index] == 's')) + if ((data[++index] == 'l') && (data[++index] == 'a') + && (data[++index] == 's') && (data[++index] == 's')) return TokenNameclass; index = 0; - if ((data[++index] == 'l') && (data[++index] == 'o') && (data[++index] == 'n') && (data[++index] == 'e')) + if ((data[++index] == 'l') && (data[++index] == 'o') + && (data[++index] == 'n') && (data[++index] == 'e')) return TokenNameclone; index = 0; - if ((data[++index] == 'o') && (data[++index] == 'n') && (data[++index] == 's') && (data[++index] == 't')) + if ((data[++index] == 'o') && (data[++index] == 'n') + && (data[++index] == 's') && (data[++index] == 't')) return TokenNameconst; return TokenNameIdentifier; case 8: - if ((data[++index] == 'o') && (data[++index] == 'n') && (data[++index] == 't') && (data[++index] == 'i') - && (data[++index] == 'n') && (data[++index] == 'u') && (data[++index] == 'e')) + if ((data[++index] == 'o') && (data[++index] == 'n') + && (data[++index] == 't') && (data[++index] == 'i') + && (data[++index] == 'n') && (data[++index] == 'u') + && (data[++index] == 'e')) return TokenNamecontinue; return TokenNameIdentifier; } @@ -3118,21 +3345,23 @@ public class Scanner implements IScanner, ITerminalSymbols { if ((data[++index] == 'o')) return TokenNamedo; return TokenNameIdentifier; - // case 6 : - // if ((data[++index] == 'e') - // && (data[++index] == 'f') - // && (data[++index] == 'i') - // && (data[++index] == 'n') - // && (data[++index] == 'e')) - // return TokenNamedefine; - // else - // return TokenNameIdentifier; + // case 6 : + // if ((data[++index] == 'e') + // && (data[++index] == 'f') + // && (data[++index] == 'i') + // && (data[++index] == 'n') + // && (data[++index] == 'e')) + // return TokenNamedefine; + // else + // return TokenNameIdentifier; case 7: - if ((data[++index] == 'e') && (data[++index] == 'c') && (data[++index] == 'l') && (data[++index] == 'a') + if ((data[++index] == 'e') && (data[++index] == 'c') + && (data[++index] == 'l') && (data[++index] == 'a') && (data[++index] == 'r') && (data[++index] == 'e')) return TokenNamedeclare; index = 0; - if ((data[++index] == 'e') && (data[++index] == 'f') && (data[++index] == 'a') && (data[++index] == 'u') + if ((data[++index] == 'e') && (data[++index] == 'f') + && (data[++index] == 'a') && (data[++index] == 'u') && (data[++index] == 'l') && (data[++index] == 't')) return TokenNamedefault; return TokenNameIdentifier; @@ -3142,58 +3371,78 @@ public class Scanner implements IScanner, ITerminalSymbols { // echo else exit elseif extends eval switch (length) { case 4: - if ((data[++index] == 'c') && (data[++index] == 'h') && (data[++index] == 'o')) + if ((data[++index] == 'c') && (data[++index] == 'h') + && (data[++index] == 'o')) return TokenNameecho; - else if ((data[index] == 'l') && (data[++index] == 's') && (data[++index] == 'e')) + else if ((data[index] == 'l') && (data[++index] == 's') + && (data[++index] == 'e')) return TokenNameelse; - else if ((data[index] == 'x') && (data[++index] == 'i') && (data[++index] == 't')) + else if ((data[index] == 'x') && (data[++index] == 'i') + && (data[++index] == 't')) return TokenNameexit; - else if ((data[index] == 'v') && (data[++index] == 'a') && (data[++index] == 'l')) + else if ((data[index] == 'v') && (data[++index] == 'a') + && (data[++index] == 'l')) return TokenNameeval; return TokenNameIdentifier; case 5: // endif empty - if ((data[++index] == 'n') && (data[++index] == 'd') && (data[++index] == 'i') && (data[++index] == 'f')) + if ((data[++index] == 'n') && (data[++index] == 'd') + && (data[++index] == 'i') && (data[++index] == 'f')) return TokenNameendif; - if ((data[index] == 'm') && (data[++index] == 'p') && (data[++index] == 't') && (data[++index] == 'y')) + if ((data[index] == 'm') && (data[++index] == 'p') + && (data[++index] == 't') && (data[++index] == 'y')) return TokenNameempty; return TokenNameIdentifier; case 6: // endfor - if ((data[++index] == 'n') && (data[++index] == 'd') && (data[++index] == 'f') && (data[++index] == 'o') + if ((data[++index] == 'n') && (data[++index] == 'd') + && (data[++index] == 'f') && (data[++index] == 'o') && (data[++index] == 'r')) return TokenNameendfor; - else if ((data[index] == 'l') && (data[++index] == 's') && (data[++index] == 'e') && (data[++index] == 'i') + else if ((data[index] == 'l') && (data[++index] == 's') + && (data[++index] == 'e') && (data[++index] == 'i') && (data[++index] == 'f')) return TokenNameelseif; return TokenNameIdentifier; case 7: - if ((data[++index] == 'x') && (data[++index] == 't') && (data[++index] == 'e') && (data[++index] == 'n') + if ((data[++index] == 'x') && (data[++index] == 't') + && (data[++index] == 'e') && (data[++index] == 'n') && (data[++index] == 'd') && (data[++index] == 's')) return TokenNameextends; return TokenNameIdentifier; case 8: // endwhile - if ((data[++index] == 'n') && (data[++index] == 'd') && (data[++index] == 'w') && (data[++index] == 'h') - && (data[++index] == 'i') && (data[++index] == 'l') && (data[++index] == 'e')) + if ((data[++index] == 'n') && (data[++index] == 'd') + && (data[++index] == 'w') && (data[++index] == 'h') + && (data[++index] == 'i') && (data[++index] == 'l') + && (data[++index] == 'e')) return TokenNameendwhile; return TokenNameIdentifier; case 9: // endswitch - if ((data[++index] == 'n') && (data[++index] == 'd') && (data[++index] == 's') && (data[++index] == 'w') - && (data[++index] == 'i') && (data[++index] == 't') && (data[++index] == 'c') && (data[++index] == 'h')) + if ((data[++index] == 'n') && (data[++index] == 'd') + && (data[++index] == 's') && (data[++index] == 'w') + && (data[++index] == 'i') && (data[++index] == 't') + && (data[++index] == 'c') && (data[++index] == 'h')) return TokenNameendswitch; return TokenNameIdentifier; case 10: // enddeclare - if ((data[++index] == 'n') && (data[++index] == 'd') && (data[++index] == 'd') && (data[++index] == 'e') - && (data[++index] == 'c') && (data[++index] == 'l') && (data[++index] == 'a') && (data[++index] == 'r') + if ((data[++index] == 'n') && (data[++index] == 'd') + && (data[++index] == 'd') && (data[++index] == 'e') + && (data[++index] == 'c') && (data[++index] == 'l') + && (data[++index] == 'a') && (data[++index] == 'r') && (data[++index] == 'e')) return TokenNameenddeclare; index = 0; if ((data[++index] == 'n') // endforeach - && (data[++index] == 'd') && (data[++index] == 'f') && (data[++index] == 'o') && (data[++index] == 'r') - && (data[++index] == 'e') && (data[++index] == 'a') && (data[++index] == 'c') && (data[++index] == 'h')) + && (data[++index] == 'd') + && (data[++index] == 'f') + && (data[++index] == 'o') + && (data[++index] == 'r') + && (data[++index] == 'e') + && (data[++index] == 'a') + && (data[++index] == 'c') && (data[++index] == 'h')) return TokenNameendforeach; return TokenNameIdentifier; } @@ -3209,19 +3458,23 @@ public class Scanner implements IScanner, ITerminalSymbols { // if ((data[++index] == 'a') && (data[++index] == 'l') // && (data[++index] == 's') && (data[++index] == 'e')) // return TokenNamefalse; - if ((data[++index] == 'i') && (data[++index] == 'n') && (data[++index] == 'a') && (data[++index] == 'l')) + if ((data[++index] == 'i') && (data[++index] == 'n') + && (data[++index] == 'a') && (data[++index] == 'l')) return TokenNamefinal; return TokenNameIdentifier; case 7: // foreach - if ((data[++index] == 'o') && (data[++index] == 'r') && (data[++index] == 'e') && (data[++index] == 'a') + if ((data[++index] == 'o') && (data[++index] == 'r') + && (data[++index] == 'e') && (data[++index] == 'a') && (data[++index] == 'c') && (data[++index] == 'h')) return TokenNameforeach; return TokenNameIdentifier; case 8: // function - if ((data[++index] == 'u') && (data[++index] == 'n') && (data[++index] == 'c') && (data[++index] == 't') - && (data[++index] == 'i') && (data[++index] == 'o') && (data[++index] == 'n')) + if ((data[++index] == 'u') && (data[++index] == 'n') + && (data[++index] == 'c') && (data[++index] == 't') + && (data[++index] == 'i') && (data[++index] == 'o') + && (data[++index] == 'n')) return TokenNamefunction; return TokenNameIdentifier; } @@ -3229,7 +3482,8 @@ public class Scanner implements IScanner, ITerminalSymbols { case 'g': // global if (length == 6) { - if ((data[++index] == 'l') && (data[++index] == 'o') && (data[++index] == 'b') && (data[++index] == 'a') + if ((data[++index] == 'l') && (data[++index] == 'o') + && (data[++index] == 'b') && (data[++index] == 'a') && (data[++index] == 'l')) { return TokenNameglobal; } @@ -3242,41 +3496,52 @@ public class Scanner implements IScanner, ITerminalSymbols { if (data[++index] == 'f') return TokenNameif; return TokenNameIdentifier; - // case 3 : - // if ((data[++index] == 'n') && (data[++index] == 't')) - // return TokenNameint; - // else - // return TokenNameIdentifier; + // case 3 : + // if ((data[++index] == 'n') && (data[++index] == 't')) + // return TokenNameint; + // else + // return TokenNameIdentifier; case 5: - if ((data[++index] == 's') && (data[++index] == 's') && (data[++index] == 'e') && (data[++index] == 't')) + if ((data[++index] == 's') && (data[++index] == 's') + && (data[++index] == 'e') && (data[++index] == 't')) return TokenNameisset; return TokenNameIdentifier; case 7: - if ((data[++index] == 'n') && (data[++index] == 'c') && (data[++index] == 'l') && (data[++index] == 'u') + if ((data[++index] == 'n') && (data[++index] == 'c') + && (data[++index] == 'l') && (data[++index] == 'u') && (data[++index] == 'd') && (data[++index] == 'e')) return TokenNameinclude; return TokenNameIdentifier; case 9: // interface - if ((data[++index] == 'n') && (data[++index] == 't') && (data[++index] == 'e') && (data[++index] == 'r') - && (data[++index] == 'f') && (data[++index] == 'a') && (data[++index] == 'c') && (data[++index] == 'e')) + if ((data[++index] == 'n') && (data[++index] == 't') + && (data[++index] == 'e') && (data[++index] == 'r') + && (data[++index] == 'f') && (data[++index] == 'a') + && (data[++index] == 'c') && (data[++index] == 'e')) return TokenNameinterface; return TokenNameIdentifier; case 10: // instanceof - if ((data[++index] == 'n') && (data[++index] == 's') && (data[++index] == 't') && (data[++index] == 'a') - && (data[++index] == 'n') && (data[++index] == 'c') && (data[++index] == 'e') && (data[++index] == 'o') + if ((data[++index] == 'n') && (data[++index] == 's') + && (data[++index] == 't') && (data[++index] == 'a') + && (data[++index] == 'n') && (data[++index] == 'c') + && (data[++index] == 'e') && (data[++index] == 'o') && (data[++index] == 'f')) return TokenNameinstanceof; - if ((data[index] == 'm') && (data[++index] == 'p') && (data[++index] == 'l') && (data[++index] == 'e') - && (data[++index] == 'm') && (data[++index] == 'e') && (data[++index] == 'n') && (data[++index] == 't') + if ((data[index] == 'm') && (data[++index] == 'p') + && (data[++index] == 'l') && (data[++index] == 'e') + && (data[++index] == 'm') && (data[++index] == 'e') + && (data[++index] == 'n') && (data[++index] == 't') && (data[++index] == 's')) return TokenNameimplements; return TokenNameIdentifier; case 12: - if ((data[++index] == 'n') && (data[++index] == 'c') && (data[++index] == 'l') && (data[++index] == 'u') - && (data[++index] == 'd') && (data[++index] == 'e') && (data[++index] == '_') && (data[++index] == 'o') - && (data[++index] == 'n') && (data[++index] == 'c') && (data[++index] == 'e')) + if ((data[++index] == 'n') && (data[++index] == 'c') + && (data[++index] == 'l') && (data[++index] == 'u') + && (data[++index] == 'd') && (data[++index] == 'e') + && (data[++index] == '_') && (data[++index] == 'o') + && (data[++index] == 'n') && (data[++index] == 'c') + && (data[++index] == 'e')) return TokenNameinclude_once; return TokenNameIdentifier; } @@ -3284,7 +3549,8 @@ public class Scanner implements IScanner, ITerminalSymbols { case 'l': // list if (length == 4) { - if ((data[++index] == 'i') && (data[++index] == 's') && (data[++index] == 't')) { + if ((data[++index] == 'i') && (data[++index] == 's') + && (data[++index] == 't')) { return TokenNamelist; } } @@ -3296,12 +3562,12 @@ public class Scanner implements IScanner, ITerminalSymbols { if ((data[++index] == 'e') && (data[++index] == 'w')) return TokenNamenew; return TokenNameIdentifier; - // case 4 : - // if ((data[++index] == 'u') && (data[++index] == 'l') - // && (data[++index] == 'l')) - // return TokenNamenull; - // else - // return TokenNameIdentifier; + // case 4 : + // if ((data[++index] == 'u') && (data[++index] == 'l') + // && (data[++index] == 'l')) + // return TokenNamenull; + // else + // return TokenNameIdentifier; } return TokenNameIdentifier; case 'o': @@ -3331,25 +3597,30 @@ public class Scanner implements IScanner, ITerminalSymbols { // print public private protected switch (length) { case 5: - if ((data[++index] == 'r') && (data[++index] == 'i') && (data[++index] == 'n') && (data[++index] == 't')) { + if ((data[++index] == 'r') && (data[++index] == 'i') + && (data[++index] == 'n') && (data[++index] == 't')) { return TokenNameprint; } return TokenNameIdentifier; case 6: - if ((data[++index] == 'u') && (data[++index] == 'b') && (data[++index] == 'l') && (data[++index] == 'i') + if ((data[++index] == 'u') && (data[++index] == 'b') + && (data[++index] == 'l') && (data[++index] == 'i') && (data[++index] == 'c')) { return TokenNamepublic; } return TokenNameIdentifier; case 7: - if ((data[++index] == 'r') && (data[++index] == 'i') && (data[++index] == 'v') && (data[++index] == 'a') + if ((data[++index] == 'r') && (data[++index] == 'i') + && (data[++index] == 'v') && (data[++index] == 'a') && (data[++index] == 't') && (data[++index] == 'e')) { return TokenNameprivate; } return TokenNameIdentifier; case 9: - if ((data[++index] == 'r') && (data[++index] == 'o') && (data[++index] == 't') && (data[++index] == 'e') - && (data[++index] == 'c') && (data[++index] == 't') && (data[++index] == 'e') && (data[++index] == 'd')) { + if ((data[++index] == 'r') && (data[++index] == 'o') + && (data[++index] == 't') && (data[++index] == 'e') + && (data[++index] == 'c') && (data[++index] == 't') + && (data[++index] == 'e') && (data[++index] == 'd')) { return TokenNameprotected; } return TokenNameIdentifier; @@ -3358,19 +3629,24 @@ public class Scanner implements IScanner, ITerminalSymbols { case 'r': // return require require_once if (length == 6) { - if ((data[++index] == 'e') && (data[++index] == 't') && (data[++index] == 'u') && (data[++index] == 'r') + if ((data[++index] == 'e') && (data[++index] == 't') + && (data[++index] == 'u') && (data[++index] == 'r') && (data[++index] == 'n')) { return TokenNamereturn; } } else if (length == 7) { - if ((data[++index] == 'e') && (data[++index] == 'q') && (data[++index] == 'u') && (data[++index] == 'i') + if ((data[++index] == 'e') && (data[++index] == 'q') + && (data[++index] == 'u') && (data[++index] == 'i') && (data[++index] == 'r') && (data[++index] == 'e')) { return TokenNamerequire; } } else if (length == 12) { - if ((data[++index] == 'e') && (data[++index] == 'q') && (data[++index] == 'u') && (data[++index] == 'i') - && (data[++index] == 'r') && (data[++index] == 'e') && (data[++index] == '_') && (data[++index] == 'o') - && (data[++index] == 'n') && (data[++index] == 'c') && (data[++index] == 'e')) { + if ((data[++index] == 'e') && (data[++index] == 'q') + && (data[++index] == 'u') && (data[++index] == 'i') + && (data[++index] == 'r') && (data[++index] == 'e') + && (data[++index] == '_') && (data[++index] == 'o') + && (data[++index] == 'n') && (data[++index] == 'c') + && (data[++index] == 'e')) { return TokenNamerequire_once; } } @@ -3379,18 +3655,21 @@ public class Scanner implements IScanner, ITerminalSymbols { // self static switch switch (length) { // case 4: - // if ((data[++index] == 'e') && (data[++index] == 'l') && (data[++index] + // if ((data[++index] == 'e') && (data[++index] == 'l') && + // (data[++index] // == 'f')) { // return TokenNameself; // } // return TokenNameIdentifier; case 6: if (data[++index] == 't') - if ((data[++index] == 'a') && (data[++index] == 't') && (data[++index] == 'i') && (data[++index] == 'c')) { + if ((data[++index] == 'a') && (data[++index] == 't') + && (data[++index] == 'i') && (data[++index] == 'c')) { return TokenNamestatic; } else return TokenNameIdentifier; - else if ((data[index] == 'w') && (data[++index] == 'i') && (data[++index] == 't') && (data[++index] == 'c') + else if ((data[index] == 'w') && (data[++index] == 'i') + && (data[++index] == 't') && (data[++index] == 'c') && (data[++index] == 'h')) return TokenNameswitch; } @@ -3401,14 +3680,15 @@ public class Scanner implements IScanner, ITerminalSymbols { case 3: if ((data[++index] == 'r') && (data[++index] == 'y')) return TokenNametry; - // case 4 : - // if ((data[++index] == 'r') && (data[++index] == 'u') - // && (data[++index] == 'e')) - // return TokenNametrue; - // else - // return TokenNameIdentifier; + // case 4 : + // if ((data[++index] == 'r') && (data[++index] == 'u') + // && (data[++index] == 'e')) + // return TokenNametrue; + // else + // return TokenNameIdentifier; case 5: - if ((data[++index] == 'h') && (data[++index] == 'r') && (data[++index] == 'o') && (data[++index] == 'w')) + if ((data[++index] == 'h') && (data[++index] == 'r') + && (data[++index] == 'o') && (data[++index] == 'w')) return TokenNamethrow; } return TokenNameIdentifier; @@ -3419,7 +3699,8 @@ public class Scanner implements IScanner, ITerminalSymbols { if ((data[++index] == 's') && (data[++index] == 'e')) return TokenNameuse; case 5: - if ((data[++index] == 'n') && (data[++index] == 's') && (data[++index] == 'e') && (data[++index] == 't')) + if ((data[++index] == 'n') && (data[++index] == 's') + && (data[++index] == 'e') && (data[++index] == 't')) return TokenNameunset; } return TokenNameIdentifier; @@ -3435,14 +3716,15 @@ public class Scanner implements IScanner, ITerminalSymbols { // while switch (length) { case 5: - if ((data[++index] == 'h') && (data[++index] == 'i') && (data[++index] == 'l') && (data[++index] == 'e')) + if ((data[++index] == 'h') && (data[++index] == 'i') + && (data[++index] == 'l') && (data[++index] == 'e')) return TokenNamewhile; - // case 6:if ( (data[++index] =='i') && (data[++index]=='d') && - // (data[++index]=='e') && (data[++index]=='f')&& - // (data[++index]=='p')) - // return TokenNamewidefp ; - // else - // return TokenNameIdentifier; + // case 6:if ( (data[++index] =='i') && (data[++index]=='d') && + // (data[++index]=='e') && (data[++index]=='f')&& + // (data[++index]=='p')) + // return TokenNamewidefp ; + // else + // return TokenNameIdentifier; } return TokenNameIdentifier; case 'x': @@ -3515,19 +3797,23 @@ public class Scanner implements IScanner, ITerminalSymbols { // consume next character unicodeAsBackSlash = false; currentCharacter = source[currentPosition++]; - // if (((currentCharacter = source[currentPosition++]) == '\\') + // if (((currentCharacter = + // source[currentPosition++]) == '\\') // && (source[currentPosition] == 'u')) { // getNextUnicodeChar(); // } else { // if (withoutUnicodePtr != 0) { - // withoutUnicodeBuffer[++withoutUnicodePtr] = currentCharacter; + // withoutUnicodeBuffer[++withoutUnicodePtr] = + // currentCharacter; // } // } - if ((currentCharacter == '-') || (currentCharacter == '+')) { + if ((currentCharacter == '-') + || (currentCharacter == '+')) { // consume next character unicodeAsBackSlash = false; currentCharacter = source[currentPosition++]; - // if (((currentCharacter = source[currentPosition++]) == '\\') + // if (((currentCharacter = + // source[currentPosition++]) == '\\') // && (source[currentPosition] == 'u')) { // getNextUnicodeChar(); // } else { @@ -3560,7 +3846,8 @@ public class Scanner implements IScanner, ITerminalSymbols { ; // if ((!dotPrefix) && (getNextChar('l', 'L') >= 0)) // return TokenNameLongLiteral; - if ((!dotPrefix) && (getNextChar('.'))) { // decimal part that can be empty + if ((!dotPrefix) && (getNextChar('.'))) { // decimal part that can be + // empty while (getNextCharAsDigit()) { } ; @@ -3610,7 +3897,7 @@ public class Scanner implements IScanner, ITerminalSymbols { /** * Search the line number corresponding to a specific position - * + * */ public final int getLineNumber(int position) { if (lineEnds == null) @@ -3676,21 +3963,25 @@ public class Scanner implements IScanner, ITerminalSymbols { middle = new char[0]; } char end[] = new char[source.length - (currentPosition - 1)]; - System.arraycopy(source, (currentPosition - 1) + 1, end, 0, source.length - (currentPosition - 1) - 1); - return new String(front) + "\n===============================\nStarts here -->" //$NON-NLS-1$ - + new String(middle) + "<-- Ends here\n===============================\n" //$NON-NLS-1$ + System.arraycopy(source, (currentPosition - 1) + 1, end, 0, + source.length - (currentPosition - 1) - 1); + return new String(front) + + "\n===============================\nStarts here -->" //$NON-NLS-1$ + + new String(middle) + + "<-- Ends here\n===============================\n" //$NON-NLS-1$ + new String(end); } public final String toStringAction(int act) { switch (act) { case TokenNameERROR: - return "ScannerError"; // + new String(getCurrentTokenSource()) + ")"; - // //$NON-NLS-1$ + return "ScannerError"; // + new String(getCurrentTokenSource()) + + // ")"; + // //$NON-NLS-1$ case TokenNameINLINE_HTML: return "Inline-HTML(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$ - case TokenNameECHO_INVISIBLE: - //0-length token + case TokenNameECHO_INVISIBLE: + // 0-length token return ""; case TokenNameIdentifier: return "Identifier(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$ @@ -3722,8 +4013,8 @@ public class Scanner implements IScanner, ITerminalSymbols { return "continue"; //$NON-NLS-1$ case TokenNamedefault: return "default"; //$NON-NLS-1$ - // case TokenNamedefine : - // return "define"; //$NON-NLS-1$ + // case TokenNamedefine : + // return "define"; //$NON-NLS-1$ case TokenNamedo: return "do"; //$NON-NLS-1$ case TokenNameecho: @@ -3746,8 +4037,8 @@ public class Scanner implements IScanner, ITerminalSymbols { return "exit"; case TokenNameextends: return "extends"; //$NON-NLS-1$ - // case TokenNamefalse : - // return "false"; //$NON-NLS-1$ + // case TokenNamefalse : + // return "false"; //$NON-NLS-1$ case TokenNamefinal: return "final"; //$NON-NLS-1$ case TokenNamefor: @@ -3776,8 +4067,8 @@ public class Scanner implements IScanner, ITerminalSymbols { return "list"; //$NON-NLS-1$ case TokenNamenew: return "new"; //$NON-NLS-1$ - // case TokenNamenull : - // return "null"; //$NON-NLS-1$ + // case TokenNamenull : + // return "null"; //$NON-NLS-1$ case TokenNameor: return "OR"; //$NON-NLS-1$ case TokenNameprint: @@ -3800,8 +4091,8 @@ public class Scanner implements IScanner, ITerminalSymbols { return "static"; //$NON-NLS-1$ case TokenNameswitch: return "switch"; //$NON-NLS-1$ - // case TokenNametrue : - // return "true"; //$NON-NLS-1$ + // case TokenNametrue : + // return "true"; //$NON-NLS-1$ case TokenNameunset: return "unset"; //$NON-NLS-1$ case TokenNamevar: @@ -3810,8 +4101,8 @@ public class Scanner implements IScanner, ITerminalSymbols { return "while"; //$NON-NLS-1$ case TokenNamexor: return "XOR"; //$NON-NLS-1$ - // case TokenNamethis : - // return "$this"; //$NON-NLS-1$ + // case TokenNamethis : + // return "$this"; //$NON-NLS-1$ case TokenNameIntegerLiteral: return "Integer(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$ case TokenNameDoubleLiteral: @@ -3824,10 +4115,10 @@ public class Scanner implements IScanner, ITerminalSymbols { return "StringInterpolated(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$ case TokenNameEncapsedString0: return "`"; //$NON-NLS-1$ - // case TokenNameEncapsedString1: - // return "\'"; //$NON-NLS-1$ - // case TokenNameEncapsedString2: - // return "\""; //$NON-NLS-1$ + // case TokenNameEncapsedString1: + // return "\'"; //$NON-NLS-1$ + // case TokenNameEncapsedString2: + // return "\""; //$NON-NLS-1$ case TokenNameSTRING: return "STRING_DQ(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$ case TokenNameHEREDOC: @@ -3950,9 +4241,9 @@ public class Scanner implements IScanner, ITerminalSymbols { return "COMMENT_BLOCK(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ case TokenNameCOMMENT_PHPDOC: return "COMMENT_PHPDOC(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ - // case TokenNameHTML : - // return "HTML(" + new String(getCurrentTokenSource()) + ")"; - // //$NON-NLS-1$ + // case TokenNameHTML : + // return "HTML(" + new String(getCurrentTokenSource()) + ")"; + // //$NON-NLS-1$ case TokenNameFILE: return "__FILE__"; //$NON-NLS-1$ case TokenNameLINE: @@ -3986,17 +4277,23 @@ public class Scanner implements IScanner, ITerminalSymbols { this(tokenizeComments, tokenizeWhiteSpace, false); } - public Scanner(boolean tokenizeComments, boolean tokenizeWhiteSpace, boolean checkNonExternalizedStringLiterals) { - this(tokenizeComments, tokenizeWhiteSpace, checkNonExternalizedStringLiterals, false); + public Scanner(boolean tokenizeComments, boolean tokenizeWhiteSpace, + boolean checkNonExternalizedStringLiterals) { + this(tokenizeComments, tokenizeWhiteSpace, + checkNonExternalizedStringLiterals, false); } - public Scanner(boolean tokenizeComments, boolean tokenizeWhiteSpace, boolean checkNonExternalizedStringLiterals, - boolean assertMode) { - this(tokenizeComments, tokenizeWhiteSpace, checkNonExternalizedStringLiterals, assertMode, false, null, null, true); + public Scanner(boolean tokenizeComments, boolean tokenizeWhiteSpace, + boolean checkNonExternalizedStringLiterals, boolean assertMode) { + this(tokenizeComments, tokenizeWhiteSpace, + checkNonExternalizedStringLiterals, assertMode, false, null, + null, true); } - public Scanner(boolean tokenizeComments, boolean tokenizeWhiteSpace, boolean checkNonExternalizedStringLiterals, - boolean assertMode, boolean tokenizeStrings, char[][] taskTags, char[][] taskPriorities, boolean isTaskCaseSensitive) { + public Scanner(boolean tokenizeComments, boolean tokenizeWhiteSpace, + boolean checkNonExternalizedStringLiterals, boolean assertMode, + boolean tokenizeStrings, char[][] taskTags, + char[][] taskPriorities, boolean isTaskCaseSensitive) { this.eofPosition = Integer.MAX_VALUE; this.tokenizeComments = tokenizeComments; this.tokenizeWhiteSpace = tokenizeWhiteSpace; @@ -4049,7 +4346,9 @@ public class Scanner implements IScanner, ITerminalSymbols { } this.wasNonExternalizedStringLiteral = true; if (nonNLSCounter != lineLength) { - System.arraycopy(this.nonNLSStrings, 0, (this.nonNLSStrings = new StringLiteral[nonNLSCounter]), 0, nonNLSCounter); + System.arraycopy(this.nonNLSStrings, 0, + (this.nonNLSStrings = new StringLiteral[nonNLSCounter]), 0, + nonNLSCounter); } currentLine = null; } @@ -4103,29 +4402,37 @@ public class Scanner implements IScanner, ITerminalSymbols { int number = Character.getNumericValue(currentCharacter); if (number >= 0 && number <= 7) { boolean zeroToThreeNot = number > 3; - if (Character.isDigit(currentCharacter = source[currentPosition++])) { + if (Character + .isDigit(currentCharacter = source[currentPosition++])) { int digit = Character.getNumericValue(currentCharacter); if (digit >= 0 && digit <= 7) { number = (number * 8) + digit; - if (Character.isDigit(currentCharacter = source[currentPosition++])) { - if (zeroToThreeNot) { // has read \NotZeroToThree OctalDigit + if (Character + .isDigit(currentCharacter = source[currentPosition++])) { + if (zeroToThreeNot) { // has read \NotZeroToThree + // OctalDigit // Digit --> ignore last character currentPosition--; } else { - digit = Character.getNumericValue(currentCharacter); - if (digit >= 0 && digit <= 7) { // has read \ZeroToThree + digit = Character + .getNumericValue(currentCharacter); + if (digit >= 0 && digit <= 7) { // has read + // \ZeroToThree // OctalDigit OctalDigit number = (number * 8) + digit; - } else { // has read \ZeroToThree OctalDigit NonOctalDigit + } else { // has read \ZeroToThree OctalDigit + // NonOctalDigit // --> ignore last character currentPosition--; } } - } else { // has read \OctalDigit NonDigit--> ignore last + } else { // has read \OctalDigit NonDigit--> ignore + // last // character currentPosition--; } - } else { // has read \OctalDigit NonOctalDigit--> ignore last + } else { // has read \OctalDigit NonOctalDigit--> ignore + // last // character currentPosition--; } @@ -4146,12 +4453,14 @@ public class Scanner implements IScanner, ITerminalSymbols { char[] src = this.source; // only look for newer task: tags - if (this.foundTaskCount > 0 && this.foundTaskPositions[this.foundTaskCount - 1][0] >= commentStart) { + if (this.foundTaskCount > 0 + && this.foundTaskPositions[this.foundTaskCount - 1][0] >= commentStart) { return; } int foundTaskIndex = this.foundTaskCount; char previous = src[commentStart + 1]; // should be '*' or '/' - nextChar: for (int i = commentStart + 2; i < commentEnd && i < this.eofPosition; i++) { + nextChar: for (int i = commentStart + 2; i < commentEnd + && i < this.eofPosition; i++) { char[] tag = null; char[] priority = null; // check for tag occurrence only if not ambiguous with javadoc tag @@ -4162,7 +4471,8 @@ public class Scanner implements IScanner, ITerminalSymbols { if (tagLength == 0) continue nextTag; - // ensure tag is not leaded with letter if tag starts with a letter + // ensure tag is not leaded with letter if tag starts with a + // letter if (Scanner.isPHPIdentifierStart(tag[0])) { if (Scanner.isPHPIdentifierPart(previous)) { continue nextTag; @@ -4174,17 +4484,24 @@ public class Scanner implements IScanner, ITerminalSymbols { int x = i + t; if (x >= this.eofPosition || x >= commentEnd) continue nextTag; - if ((sc = src[i + t]) != (tc = tag[t])) { // case sensitive check - if (this.isTaskCaseSensitive || (Character.toLowerCase(sc) != Character.toLowerCase(tc))) { // case + if ((sc = src[i + t]) != (tc = tag[t])) { // case + // sensitive + // check + if (this.isTaskCaseSensitive + || (Character.toLowerCase(sc) != Character + .toLowerCase(tc))) { // case // insensitive // check continue nextTag; } } } - // ensure tag is not followed with letter if tag finishes with a + // ensure tag is not followed with letter if tag finishes + // with a // letter - if (i + tagLength < commentEnd && Scanner.isPHPIdentifierPart(src[i + tagLength - 1])) { + if (i + tagLength < commentEnd + && Scanner.isPHPIdentifierPart(src[i + tagLength + - 1])) { if (Scanner.isPHPIdentifierPart(src[i + tagLength])) continue nextTag; } @@ -4194,21 +4511,40 @@ public class Scanner implements IScanner, ITerminalSymbols { this.foundTaskPriorities = new char[5][]; this.foundTaskPositions = new int[5][]; } else if (this.foundTaskCount == this.foundTaskTags.length) { - System.arraycopy(this.foundTaskTags, 0, this.foundTaskTags = new char[this.foundTaskCount * 2][], 0, - this.foundTaskCount); - System.arraycopy(this.foundTaskMessages, 0, this.foundTaskMessages = new char[this.foundTaskCount * 2][], 0, - this.foundTaskCount); - System.arraycopy(this.foundTaskPriorities, 0, this.foundTaskPriorities = new char[this.foundTaskCount * 2][], 0, - this.foundTaskCount); - System.arraycopy(this.foundTaskPositions, 0, this.foundTaskPositions = new int[this.foundTaskCount * 2][], 0, - this.foundTaskCount); + System + .arraycopy( + this.foundTaskTags, + 0, + this.foundTaskTags = new char[this.foundTaskCount * 2][], + 0, this.foundTaskCount); + System + .arraycopy( + this.foundTaskMessages, + 0, + this.foundTaskMessages = new char[this.foundTaskCount * 2][], + 0, this.foundTaskCount); + System + .arraycopy( + this.foundTaskPriorities, + 0, + this.foundTaskPriorities = new char[this.foundTaskCount * 2][], + 0, this.foundTaskCount); + System + .arraycopy( + this.foundTaskPositions, + 0, + this.foundTaskPositions = new int[this.foundTaskCount * 2][], + 0, this.foundTaskCount); } - priority = this.taskPriorities != null && itag < this.taskPriorities.length ? this.taskPriorities[itag] : null; + priority = this.taskPriorities != null + && itag < this.taskPriorities.length ? this.taskPriorities[itag] + : null; this.foundTaskTags[this.foundTaskCount] = tag; this.foundTaskPriorities[this.foundTaskCount] = priority; - this.foundTaskPositions[this.foundTaskCount] = new int[] { i, i + tagLength - 1 }; + this.foundTaskPositions[this.foundTaskCount] = new int[] { + i, i + tagLength - 1 }; this.foundTaskMessages[this.foundTaskCount] = CharOperation.NO_CHAR; this.foundTaskCount++; i += tagLength - 1; // will be incremented when looping @@ -4219,11 +4555,14 @@ public class Scanner implements IScanner, ITerminalSymbols { } for (int i = foundTaskIndex; i < this.foundTaskCount; i++) { // retrieve message start and end positions - int msgStart = this.foundTaskPositions[i][0] + this.foundTaskTags[i].length; - int max_value = i + 1 < this.foundTaskCount ? this.foundTaskPositions[i + 1][0] - 1 : commentEnd - 1; + int msgStart = this.foundTaskPositions[i][0] + + this.foundTaskTags[i].length; + int max_value = i + 1 < this.foundTaskCount ? this.foundTaskPositions[i + 1][0] - 1 + : commentEnd - 1; // at most beginning of next task if (max_value < msgStart) { - max_value = msgStart; // would only occur if tag is before EOF. + max_value = msgStart; // would only occur if tag is before + // EOF. } int end = -1; char c; @@ -4263,7 +4602,8 @@ public class Scanner implements IScanner, ITerminalSymbols { // chech presence of task: tags // public void checkTaskTag(int commentStart, int commentEnd) { // // only look for newer task: tags - // if (this.foundTaskCount > 0 && this.foundTaskPositions[this.foundTaskCount + // if (this.foundTaskCount > 0 && + // this.foundTaskPositions[this.foundTaskCount // - 1][0] >= commentStart) { // return; // } @@ -4275,7 +4615,8 @@ public class Scanner implements IScanner, ITerminalSymbols { // // check for tag occurrence // nextTag: for (int itag = 0; itag < this.taskTags.length; itag++) { // tag = this.taskTags[itag]; - // priority = this.taskPriorities != null && itag < this.taskPriorities.length + // priority = this.taskPriorities != null && itag < + // this.taskPriorities.length // ? this.taskPriorities[itag] : null; // int tagLength = tag.length; // for (int t = 0; t < tagLength; t++) { @@ -4296,13 +4637,15 @@ public class Scanner implements IScanner, ITerminalSymbols { // System.arraycopy(this.foundTaskPriorities, 0, this.foundTaskPriorities = // new char[this.foundTaskCount * 2][], 0, // this.foundTaskCount); - // System.arraycopy(this.foundTaskPositions, 0, this.foundTaskPositions = new + // System.arraycopy(this.foundTaskPositions, 0, this.foundTaskPositions = + // new // int[this.foundTaskCount * 2][], 0, // this.foundTaskCount); // } // this.foundTaskTags[this.foundTaskCount] = tag; // this.foundTaskPriorities[this.foundTaskCount] = priority; - // this.foundTaskPositions[this.foundTaskCount] = new int[] { i, i + tagLength + // this.foundTaskPositions[this.foundTaskCount] = new int[] { i, i + + // tagLength // - 1 }; // this.foundTaskMessages[this.foundTaskCount] = CharOperation.NO_CHAR; // this.foundTaskCount++; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/SourceTypeConverter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/SourceTypeConverter.java index e32922d..4d6d794 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/SourceTypeConverter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/SourceTypeConverter.java @@ -12,15 +12,14 @@ package net.sourceforge.phpdt.internal.compiler.parser; /** * Converter from source element type to parsed compilation unit. - * - * Limitation: - * | The source element field does not carry any information for its constant part, thus - * | the converted parse tree will not include any field initializations. - * | Therefore, any binary produced by compiling against converted source elements will - * | not take advantage of remote field constant inlining. - * | Given the intended purpose of the conversion is to resolve references, this is not - * | a problem. - * + * + * Limitation: | The source element field does not carry any information for its + * constant part, thus | the converted parse tree will not include any field + * initializations. | Therefore, any binary produced by compiling against + * converted source elements will | not take advantage of remote field constant + * inlining. | Given the intended purpose of the conversion is to resolve + * references, this is not | a problem. + * */ import java.util.ArrayList; @@ -48,54 +47,51 @@ import net.sourceforge.phpdt.internal.compiler.lookup.CompilerModifiers; import net.sourceforge.phpdt.internal.compiler.problem.ProblemReporter; public class SourceTypeConverter implements CompilerModifiers { - + private boolean needFieldInitialization; + private CompilationUnitDeclaration unit; + private UnitParser parser; + private ProblemReporter problemReporter; - - private SourceTypeConverter(boolean needFieldInitialization, ProblemReporter problemReporter) { + + private SourceTypeConverter(boolean needFieldInitialization, + ProblemReporter problemReporter) { this.needFieldInitialization = needFieldInitialization; this.problemReporter = problemReporter; } /* - * Convert a set of source element types into a parsed compilation unit declaration - * The argument types are then all grouped in the same unit. The argument types must - * at least contain one type. - * Can optionally ignore fields & methods or member types or field initialization + * Convert a set of source element types into a parsed compilation unit + * declaration The argument types are then all grouped in the same unit. The + * argument types must at least contain one type. Can optionally ignore + * fields & methods or member types or field initialization */ public static CompilationUnitDeclaration buildCompilationUnit( - ISourceType[] sourceTypes, - boolean needFieldsAndMethods, - boolean needMemberTypes, - boolean needFieldInitialization, - ProblemReporter problemReporter, - CompilationResult compilationResult) { - - return - new SourceTypeConverter(needFieldInitialization, problemReporter).convert( - sourceTypes, - needFieldsAndMethods, - needMemberTypes, - compilationResult); + ISourceType[] sourceTypes, boolean needFieldsAndMethods, + boolean needMemberTypes, boolean needFieldInitialization, + ProblemReporter problemReporter, CompilationResult compilationResult) { + + return new SourceTypeConverter(needFieldInitialization, problemReporter) + .convert(sourceTypes, needFieldsAndMethods, needMemberTypes, + compilationResult); } /* - * Convert a set of source element types into a parsed compilation unit declaration - * The argument types are then all grouped in the same unit. The argument types must - * at least contain one type. + * Convert a set of source element types into a parsed compilation unit + * declaration The argument types are then all grouped in the same unit. The + * argument types must at least contain one type. */ - private CompilationUnitDeclaration convert( - ISourceType[] sourceTypes, - boolean needFieldsAndMethods, - boolean needMemberTypes, - CompilationResult compilationResult) { + private CompilationUnitDeclaration convert(ISourceType[] sourceTypes, + boolean needFieldsAndMethods, boolean needMemberTypes, + CompilationResult compilationResult) { ISourceType sourceType = sourceTypes[0]; if (sourceType.getName() == null) return null; // do a basic test that the sourceType is valid - this.unit = new CompilationUnitDeclaration(problemReporter, compilationResult, 0); + this.unit = new CompilationUnitDeclaration(problemReporter, + compilationResult, 0); // not filled at this point /* only positions available */ @@ -103,32 +99,35 @@ public class SourceTypeConverter implements CompilerModifiers { int end = sourceType.getNameSourceEnd(); /* convert package and imports */ -// if (sourceType.getPackageName() != null -// && sourceType.getPackageName().length > 0) -// // if its null then it is defined in the default package -// this.unit.currentPackage = -// createImportReference(sourceType.getPackageName(), start, end); + // if (sourceType.getPackageName() != null + // && sourceType.getPackageName().length > 0) + // // if its null then it is defined in the default package + // this.unit.currentPackage = + // createImportReference(sourceType.getPackageName(), start, end); char[][] importNames = sourceType.getImports(); int importCount = importNames == null ? 0 : importNames.length; this.unit.imports = new ImportReference[importCount]; -// for (int i = 0; i < importCount; i++) -// this.unit.imports[i] = createImportReference(importNames[i], start, end); + // for (int i = 0; i < importCount; i++) + // this.unit.imports[i] = createImportReference(importNames[i], start, + // end); /* convert type(s) */ int typeCount = sourceTypes.length; this.unit.types = new ArrayList(typeCount); for (int i = 0; i < typeCount; i++) { - this.unit.types.set(i, - convert(sourceTypes[i], needFieldsAndMethods, needMemberTypes, compilationResult)); -// this.unit.types[i] = -// convert(sourceTypes[i], needFieldsAndMethods, needMemberTypes, compilationResult); + this.unit.types.set(i, convert(sourceTypes[i], + needFieldsAndMethods, needMemberTypes, compilationResult)); + // this.unit.types[i] = + // convert(sourceTypes[i], needFieldsAndMethods, needMemberTypes, + // compilationResult); } return this.unit; } - + /* * Convert a field source element into a parsed field declaration */ - private FieldDeclaration convert(ISourceField sourceField, TypeDeclaration type) { + private FieldDeclaration convert(ISourceField sourceField, + TypeDeclaration type) { FieldDeclaration field = new FieldDeclaration(); @@ -148,23 +147,24 @@ public class SourceTypeConverter implements CompilerModifiers { char[] initializationSource = sourceField.getInitializationSource(); if (initializationSource != null) { if (this.parser == null) { - this.parser = - new UnitParser( - this.problemReporter); -// true, -// this.problemReporter.options.sourceLevel >= CompilerOptions.JDK1_4); + this.parser = new UnitParser(this.problemReporter); + // true, + // this.problemReporter.options.sourceLevel >= + // CompilerOptions.JDK1_4); } this.parser.parse(field, type, this.unit, initializationSource); } } - + return field; } /* - * Convert a method source element into a parsed method/constructor declaration + * Convert a method source element into a parsed method/constructor + * declaration */ - private AbstractMethodDeclaration convert(ISourceMethod sourceMethod, CompilationResult compilationResult) { + private AbstractMethodDeclaration convert(ISourceMethod sourceMethod, + CompilationResult compilationResult) { AbstractMethodDeclaration method; @@ -173,34 +173,34 @@ public class SourceTypeConverter implements CompilerModifiers { int end = sourceMethod.getNameSourceEnd(); if (sourceMethod.isConstructor()) { - ConstructorDeclaration decl = new ConstructorDeclaration(compilationResult); + ConstructorDeclaration decl = new ConstructorDeclaration( + compilationResult); decl.isDefaultConstructor = false; method = decl; } else { MethodDeclaration decl = new MethodDeclaration(compilationResult); /* convert return type */ - decl.returnType = - createTypeReference(sourceMethod.getReturnTypeName(), start, end); + decl.returnType = createTypeReference(sourceMethod + .getReturnTypeName(), start, end); method = decl; } method.selector = sourceMethod.getSelector(); method.modifiers = sourceMethod.getModifiers(); method.sourceStart = start; method.sourceEnd = end; - method.declarationSourceStart = sourceMethod.getDeclarationSourceStart(); + method.declarationSourceStart = sourceMethod + .getDeclarationSourceStart(); method.declarationSourceEnd = sourceMethod.getDeclarationSourceEnd(); /* convert arguments */ char[][] argumentTypeNames = sourceMethod.getArgumentTypeNames(); char[][] argumentNames = sourceMethod.getArgumentNames(); - int argumentCount = argumentTypeNames == null ? 0 : argumentTypeNames.length; + int argumentCount = argumentTypeNames == null ? 0 + : argumentTypeNames.length; long position = (long) start << 32 + end; method.arguments = new Argument[argumentCount]; for (int i = 0; i < argumentCount; i++) { - method.arguments[i] = - new Argument( - argumentNames[i], - position, + method.arguments[i] = new Argument(argumentNames[i], position, createTypeReference(argumentTypeNames[i], start, end), AccDefault); // do not care whether was final or not @@ -208,25 +208,24 @@ public class SourceTypeConverter implements CompilerModifiers { /* convert thrown exceptions */ char[][] exceptionTypeNames = sourceMethod.getExceptionTypeNames(); - int exceptionCount = exceptionTypeNames == null ? 0 : exceptionTypeNames.length; + int exceptionCount = exceptionTypeNames == null ? 0 + : exceptionTypeNames.length; method.thrownExceptions = new TypeReference[exceptionCount]; for (int i = 0; i < exceptionCount; i++) { - method.thrownExceptions[i] = - createTypeReference(exceptionTypeNames[i], start, end); + method.thrownExceptions[i] = createTypeReference( + exceptionTypeNames[i], start, end); } return method; } /* * Convert a source element type into a parsed type declaration - * + * * Can optionally ignore fields & methods */ - private TypeDeclaration convert( - ISourceType sourceType, - boolean needFieldsAndMethods, - boolean needMemberTypes, - CompilationResult compilationResult) { + private TypeDeclaration convert(ISourceType sourceType, + boolean needFieldsAndMethods, boolean needMemberTypes, + CompilationResult compilationResult) { /* create type declaration - can be member type */ TypeDeclaration type; if (sourceType.getEnclosingType() == null) { @@ -245,25 +244,24 @@ public class SourceTypeConverter implements CompilerModifiers { /* set superclass and superinterfaces */ if (sourceType.getSuperclassName() != null) - type.superclass = - createTypeReference(sourceType.getSuperclassName(), start, end); + type.superclass = createTypeReference(sourceType + .getSuperclassName(), start, end); char[][] interfaceNames = sourceType.getInterfaceNames(); int interfaceCount = interfaceNames == null ? 0 : interfaceNames.length; type.superInterfaces = new TypeReference[interfaceCount]; for (int i = 0; i < interfaceCount; i++) { - type.superInterfaces[i] = createTypeReference(interfaceNames[i], start, end); + type.superInterfaces[i] = createTypeReference(interfaceNames[i], + start, end); } /* convert member types */ if (needMemberTypes) { ISourceType[] sourceMemberTypes = sourceType.getMemberTypes(); - int sourceMemberTypeCount = - sourceMemberTypes == null ? 0 : sourceMemberTypes.length; + int sourceMemberTypeCount = sourceMemberTypes == null ? 0 + : sourceMemberTypes.length; type.memberTypes = new MemberTypeDeclaration[sourceMemberTypeCount]; for (int i = 0; i < sourceMemberTypeCount; i++) { - type.memberTypes[i] = - (MemberTypeDeclaration) convert(sourceMemberTypes[i], - needFieldsAndMethods, - true, + type.memberTypes[i] = (MemberTypeDeclaration) convert( + sourceMemberTypes[i], needFieldsAndMethods, true, compilationResult); } } @@ -271,7 +269,8 @@ public class SourceTypeConverter implements CompilerModifiers { if (needFieldsAndMethods) { /* convert fields */ ISourceField[] sourceFields = sourceType.getFields(); - int sourceFieldCount = sourceFields == null ? 0 : sourceFields.length; + int sourceFieldCount = sourceFields == null ? 0 + : sourceFields.length; type.fields = new FieldDeclaration[sourceFieldCount]; for (int i = 0; i < sourceFieldCount; i++) { type.fields[i] = convert(sourceFields[i], type); @@ -279,9 +278,10 @@ public class SourceTypeConverter implements CompilerModifiers { /* convert methods - need to add default constructor if necessary */ ISourceMethod[] sourceMethods = sourceType.getMethods(); - int sourceMethodCount = sourceMethods == null ? 0 : sourceMethods.length; + int sourceMethodCount = sourceMethods == null ? 0 + : sourceMethods.length; - /* source type has a constructor ? */ + /* source type has a constructor ? */ /* by default, we assume that one is needed. */ int neededCount = 0; if (!type.isInterface()) { @@ -289,19 +289,22 @@ public class SourceTypeConverter implements CompilerModifiers { for (int i = 0; i < sourceMethodCount; i++) { if (sourceMethods[i].isConstructor()) { neededCount = 0; - // Does not need the extra constructor since one constructor already exists. + // Does not need the extra constructor since one + // constructor already exists. break; } } } - type.methods = new AbstractMethodDeclaration[sourceMethodCount + neededCount]; + type.methods = new AbstractMethodDeclaration[sourceMethodCount + + neededCount]; if (neededCount != 0) { // add default constructor in first position type.methods[0] = type.createsInternalConstructor(false, false); } boolean isInterface = type.isInterface(); for (int i = 0; i < sourceMethodCount; i++) { - AbstractMethodDeclaration method =convert(sourceMethods[i], compilationResult); - if (isInterface || method.isAbstract()) { // fix-up flag + AbstractMethodDeclaration method = convert(sourceMethods[i], + compilationResult); + if (isInterface || method.isAbstract()) { // fix-up flag method.modifiers |= AccSemicolonBody; } type.methods[neededCount + i] = method; @@ -313,41 +316,38 @@ public class SourceTypeConverter implements CompilerModifiers { /* * Build an import reference from an import name, e.g. java.lang.* */ -// private ImportReference createImportReference( -// char[] importName, -// int start, -// int end) { -// -// /* count identifiers */ -// int max = importName.length; -// int identCount = 0; -// for (int i = 0; i < max; i++) { -// if (importName[i] == '.') -// identCount++; -// } -// /* import on demand? */ -// boolean onDemand = importName[max - 1] == '*'; -// if (!onDemand) -// identCount++; // one more ident than dots -// -// long[] positions = new long[identCount]; -// long position = (long) start << 32 + end; -// for (int i = 0; i < identCount; i++) { -// positions[i] = position; -// } -// return new ImportReference( -// CharOperation.splitOn('.', importName, 0, max - (onDemand ? 2 : 0)), -// positions, -// onDemand); -// } - + // private ImportReference createImportReference( + // char[] importName, + // int start, + // int end) { + // + // /* count identifiers */ + // int max = importName.length; + // int identCount = 0; + // for (int i = 0; i < max; i++) { + // if (importName[i] == '.') + // identCount++; + // } + // /* import on demand? */ + // boolean onDemand = importName[max - 1] == '*'; + // if (!onDemand) + // identCount++; // one more ident than dots + // + // long[] positions = new long[identCount]; + // long position = (long) start << 32 + end; + // for (int i = 0; i < identCount; i++) { + // positions[i] = position; + // } + // return new ImportReference( + // CharOperation.splitOn('.', importName, 0, max - (onDemand ? 2 : 0)), + // positions, + // onDemand); + // } /* * Build a type reference from a readable name, e.g. java.lang.Object[][] */ - private TypeReference createTypeReference( - char[] typeSignature, - int start, - int end) { + private TypeReference createTypeReference(char[] typeSignature, int start, + int end) { /* count identifiers and dimensions */ int max = typeSignature.length; @@ -356,24 +356,26 @@ public class SourceTypeConverter implements CompilerModifiers { int identCount = 1; for (int i = 0; i < max; i++) { switch (typeSignature[i]) { - case '[' : - if (dim == 0) - dimStart = i; - dim++; - break; - case '.' : - identCount++; - break; + case '[': + if (dim == 0) + dimStart = i; + dim++; + break; + case '.': + identCount++; + break; } } /* rebuild identifiers and dimensions */ if (identCount == 1) { // simple type reference if (dim == 0) { - return new SingleTypeReference(typeSignature, (((long) start )<< 32) + end); + return new SingleTypeReference(typeSignature, + (((long) start) << 32) + end); } else { char[] identifier = new char[dimStart]; System.arraycopy(typeSignature, 0, identifier, 0, dimStart); - return new ArrayTypeReference(identifier, dim, (((long) start) << 32) + end); + return new ArrayTypeReference(identifier, dim, + (((long) start) << 32) + end); } } else { // qualified type reference long[] positions = new long[identCount]; @@ -381,12 +383,13 @@ public class SourceTypeConverter implements CompilerModifiers { for (int i = 0; i < identCount; i++) { positions[i] = pos; } - char[][] identifiers = - CharOperation.splitOn('.', typeSignature, 0, dimStart); + char[][] identifiers = CharOperation.splitOn('.', typeSignature, 0, + dimStart); if (dim == 0) { return new QualifiedTypeReference(identifiers, positions); } else { - return new ArrayQualifiedTypeReference(identifiers, dim, positions); + return new ArrayQualifiedTypeReference(identifiers, dim, + positions); } } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/SyntaxError.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/SyntaxError.java index 90ca397..be39dd6 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/SyntaxError.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/SyntaxError.java @@ -5,57 +5,67 @@ package net.sourceforge.phpdt.internal.compiler.parser; */ public class SyntaxError extends Error { - /** The line where the error start */ - int lineNumber; - /** The column where the error start */ - int columnNumber; - /** the current line. */ - String currentLine; - /** The error message. */ - String error; - - /** - * SyntaxError exception - * @param lineNumber the line number where the error start - * @param columnNumber the column where the error start - * @param currentLine the line where the error end - * @param error the error message - * @see - */ - public SyntaxError(int lineNumber, int columnNumber, String currentLine, String error) { - this.lineNumber = lineNumber; - this.columnNumber = columnNumber; - this.currentLine = currentLine; - this.error = error; - } - - /** - * Get the error message. - * @return the error message - */ - public String getMessage() { - // StringBuffer buf = new StringBuffer(256); - // buf.append("Syntax error in line:"); - // buf.append(lineNumber+1); - // buf.append(": "+ error + "\n"); - // buf.append( currentLine + "\n"); - // for (int i=0; i<(columnNumber-1); i++) { - // buf.append(' '); - // } - // buf.append('^'); - // return buf.toString(); - - - // System.err.println(currentLine); - //System.err.println(columnNumber); - return error; - } - - /** - * Get the line number where the error happens - * @return the line number - */ - public int getLine() { - return lineNumber; - } + /** The line where the error start */ + int lineNumber; + + /** The column where the error start */ + int columnNumber; + + /** the current line. */ + String currentLine; + + /** The error message. */ + String error; + + /** + * SyntaxError exception + * + * @param lineNumber + * the line number where the error start + * @param columnNumber + * the column where the error start + * @param currentLine + * the line where the error end + * @param error + * the error message + * @see + */ + public SyntaxError(int lineNumber, int columnNumber, String currentLine, + String error) { + this.lineNumber = lineNumber; + this.columnNumber = columnNumber; + this.currentLine = currentLine; + this.error = error; + } + + /** + * Get the error message. + * + * @return the error message + */ + public String getMessage() { + // StringBuffer buf = new StringBuffer(256); + // buf.append("Syntax error in line:"); + // buf.append(lineNumber+1); + // buf.append(": "+ error + "\n"); + // buf.append( currentLine + "\n"); + // for (int i=0; i<(columnNumber-1); i++) { + // buf.append(' '); + // } + // buf.append('^'); + // return buf.toString(); + + // System.err.println(currentLine); + // System.err.println(columnNumber); + return error; + } + + /** + * Get the line number where the error happens + * + * @return the line number + */ + public int getLine() { + return lineNumber; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/UninitializedVariableHandler.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/UninitializedVariableHandler.java index f19dd61..f68c8c6 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/UninitializedVariableHandler.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/UninitializedVariableHandler.java @@ -6,37 +6,41 @@ public class UninitializedVariableHandler { private class Function { private int count; + private String name; public Function(String name, int count) { - this.name=name; - this.count=count; + this.name = name; + this.count = count; } } - private String functionName=null; - private int argumentCount=0; - private ArrayList functions=new ArrayList(); + private String functionName = null; + + private int argumentCount = 0; + + private ArrayList functions = new ArrayList(); public UninitializedVariableHandler() { - add("ereg",3); - add("eregi",3); - add("fsockopen",3); - add("preg_match",3); - add("preg_match_all",3); - add("preg_replace",5); - add("preg_replace_callback",5); + add("ereg", 3); + add("eregi", 3); + add("fsockopen", 3); + add("preg_match", 3); + add("preg_match_all", 3); + add("preg_replace", 5); + add("preg_replace_callback", 5); } private void add(String name, int countFrom) { - functions.add(new Function(name,countFrom)); + functions.add(new Function(name, countFrom)); } protected boolean reportError() { - if (functionName!=null) { - for (int i=0; i=function.count) { + if (functionName != null) { + for (int i = 0; i < functions.size(); i++) { + Function function = (Function) functions.get(i); + if (functionName.equalsIgnoreCase(function.name) + && argumentCount >= function.count) { return false; } } @@ -45,7 +49,7 @@ public class UninitializedVariableHandler { } public void setFunctionName(String functionName) { - this.functionName=functionName; + this.functionName = functionName; } public void incrementArgumentCount() { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/UnitParser.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/UnitParser.java index 06855a0..2cb8d91 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/UnitParser.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/UnitParser.java @@ -1,6 +1,5 @@ package net.sourceforge.phpdt.internal.compiler.parser; - import net.sourceforge.phpdt.core.IJavaModelMarker; import net.sourceforge.phpdt.core.compiler.IProblem; import net.sourceforge.phpdt.internal.compiler.CompilationResult; @@ -25,461 +24,493 @@ import org.eclipse.core.runtime.CoreException; */ public class UnitParser extends Parser { - public UnitParser(ProblemReporter problemReporter) { //, boolean optimizeStringLiterals, boolean assertMode) { - super(problemReporter); - nestedMethod = new int[30]; - - // this.optimizeStringLiterals = optimizeStringLiterals; - // this.assertMode = assertMode; - // this.initializeScanner(); - astLengthStack = new int[50]; - // expressionLengthStack = new int[30]; - // intStack = new int[50]; - // identifierStack = new char[30][]; - // identifierLengthStack = new int[30]; - // nestedMethod = new int[30]; - // realBlockStack = new int[30]; - // identifierPositionStack = new long[30]; - // variablesCounter = new int[30]; - } - - public void goForConstructorBody() { - //tells the scanner to go for compilation unit parsing - - firstToken = TokenNameEQUAL_EQUAL; - scanner.recordLineSeparator = false; - } - public void goForExpression() { - //tells the scanner to go for an expression parsing - - firstToken = TokenNameREMAINDER; - scanner.recordLineSeparator = false; - } - public void goForCompilationUnit() { - //tells the scanner to go for compilation unit parsing - - firstToken = TokenNamePLUS_PLUS; - scanner.linePtr = -1; - scanner.foundTaskCount = 0; - scanner.recordLineSeparator = true; - // scanner.currentLine= null; - } - public void goForInitializer() { - //tells the scanner to go for initializer parsing - - firstToken = TokenNameRIGHT_SHIFT; - scanner.recordLineSeparator = false; - } - public void goForMethodBody() { - //tells the scanner to go for method body parsing - - firstToken = TokenNameMINUS_MINUS; - scanner.recordLineSeparator = false; - } - public void initialize(boolean phpMode) { - super.initialize(phpMode); - //positionning the parser for a new compilation unit - //avoiding stack reallocation and all that.... - // astPtr = -1; - // astLengthPtr = -1; - // expressionPtr = -1; - // expressionLengthPtr = -1; - // identifierPtr = -1; - // identifierLengthPtr = -1; - // intPtr = -1; - // nestedMethod[nestedType = 0] = 0; // need to reset for further reuse - // variablesCounter[nestedType] = 0; - // dimensions = 0 ; - // realBlockPtr = -1; - // endStatementPosition = 0; - - //remove objects from stack too, while the same parser/compiler couple is - //re-used between two compilations .... - - // int astLength = astStack.length; - // if (noAstNodes.length < astLength){ - // noAstNodes = new ASTNode[astLength]; - // //System.out.println("Resized AST stacks : "+ astLength); - // - // } - // System.arraycopy(noAstNodes, 0, astStack, 0, astLength); - // - // int expressionLength = expressionStack.length; - // if (noExpressions.length < expressionLength){ - // noExpressions = new Expression[expressionLength]; - // //System.out.println("Resized EXPR stacks : "+ expressionLength); - // } - // System.arraycopy(noExpressions, 0, expressionStack, 0, expressionLength); - - // reset scanner state - scanner.commentPtr = -1; - scanner.foundTaskCount = 0; - scanner.eofPosition = Integer.MAX_VALUE; - - // resetModifiers(); - // - // // recovery - // lastCheckPoint = -1; - // currentElement = null; - // restartRecovery = false; - // hasReportedError = false; - // recoveredStaticInitializerStart = 0; - // lastIgnoredToken = -1; - // lastErrorEndPosition = -1; - // listLength = 0; - } - - // A P I - - public CompilationUnitDeclaration parse(ICompilationUnit sourceUnit, CompilationResult compilationResult, boolean phpMode) { - // parses a compilation unit and manages error handling (even bugs....) - - CompilationUnitDeclaration unit; - try { - /* automaton initialization */ - initialize(phpMode); - goForCompilationUnit(); - - /* scanner initialization */ - scanner.setSource(sourceUnit, sourceUnit.getContents()); - - /* unit creation */ - referenceContext = - compilationUnit = new CompilationUnitDeclaration(problemReporter, compilationResult, scanner.source.length); - // TODO TypeDeclaration test - // TypeDeclaration typeDecl = new TypeDeclaration(this.compilationUnit.compilationResult); - // typeDecl.sourceStart = 0; - // typeDecl.sourceEnd = 10; - // typeDecl.name = new char[]{'t', 'e','s','t'}; - // this.compilationUnit.types = new ArrayList(); - // this.compilationUnit.types.add(typeDecl); - /* run automaton */ - super.parse(); -// // TODO jsurfer start -// if (sourceUnit instanceof BasicCompilationUnit) { -// storeProblemsFor(((BasicCompilationUnit)sourceUnit).getResource(), compilationResult.getAllProblems()); -// } -// // jsurfer end - - } finally { - unit = compilationUnit; - compilationUnit = null; // reset parser - } - return unit; - } - /** - * Creates a marker from each problem and adds it to the resource. - * The marker is as follows: - * - its type is T_PROBLEM - * - its plugin ID is the JavaBuilder's plugin ID - * - its message is the problem's message - * - its priority reflects the severity of the problem - * - its range is the problem's range - * - it has an extra attribute "ID" which holds the problem's id - */ - protected void storeProblemsFor(IResource resource, IProblem[] problems) throws CoreException { - if (resource == null || problems == null || problems.length == 0) - return; - - for (int i = 0, l = problems.length; i < l; i++) { - IProblem problem = problems[i]; - int id = problem.getID(); - if (id != IProblem.Task) { - IMarker marker = resource.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); - marker.setAttributes( - new String[] { - IMarker.MESSAGE, - IMarker.SEVERITY, - IJavaModelMarker.ID, - IMarker.CHAR_START, - IMarker.CHAR_END, - IMarker.LINE_NUMBER, - IJavaModelMarker.ARGUMENTS }, - new Object[] { - problem.getMessage(), - new Integer(problem.isError() ? IMarker.SEVERITY_ERROR : IMarker.SEVERITY_WARNING), - new Integer(id), - new Integer(problem.getSourceStart()), - new Integer(problem.getSourceEnd() + 1), - new Integer(problem.getSourceLineNumber()), - net.sourceforge.phpdt.internal.core.util.Util.getProblemArgumentsForMarker(problem.getArguments())}); - } - - } - } - - - // A P I - - public void parse(ConstructorDeclaration cd, CompilationUnitDeclaration unit) { - //only parse the method body of cd - //fill out its statements - - //convert bugs into parse error - - initialize(false); - goForConstructorBody(); - nestedMethod[nestedType]++; - - referenceContext = cd; - compilationUnit = unit; - - scanner.resetTo(cd.sourceEnd + 1, cd.declarationSourceEnd); - try { - parse(); - } catch (AbortCompilation ex) { - lastAct = ERROR_ACTION; - - } finally { - nestedMethod[nestedType]--; - } - - if (lastAct == ERROR_ACTION) { - initialize(false); - return; - } - - //statements - // cd.explicitDeclarations = realBlockStack[realBlockPtr--]; - // int length; - // if ((length = astLengthStack[astLengthPtr--]) != 0) { - // astPtr -= length; - // if (astStack[astPtr + 1] instanceof ExplicitConstructorCall) - // //avoid a isSomeThing that would only be used here BUT what is faster between two alternatives ? - // { - // System.arraycopy( - // astStack, - // astPtr + 2, - // cd.statements = new Statement[length - 1], - // 0, - // length - 1); - // cd.constructorCall = (ExplicitConstructorCall) astStack[astPtr + 1]; - // } else { //need to add explicitly the super(); - // System.arraycopy( - // astStack, - // astPtr + 1, - // cd.statements = new Statement[length], - // 0, - // length); - // cd.constructorCall = SuperReference.implicitSuperConstructorCall(); - // } - // } else { - // cd.constructorCall = SuperReference.implicitSuperConstructorCall(); - // } - // - // if (cd.constructorCall.sourceEnd == 0) { - // cd.constructorCall.sourceEnd = cd.sourceEnd; - // cd.constructorCall.sourceStart = cd.sourceStart; - // } - } - // A P I - - public void parse(FieldDeclaration field, TypeDeclaration type, CompilationUnitDeclaration unit, char[] initializationSource) { - //only parse the initializationSource of the given field - - //convert bugs into parse error - - initialize(false); - goForExpression(); - nestedMethod[nestedType]++; - - referenceContext = type; - compilationUnit = unit; - - scanner.setSource(initializationSource); - scanner.resetTo(0, initializationSource.length - 1); - try { - parse(); - } catch (AbortCompilation ex) { - lastAct = ERROR_ACTION; - } finally { - nestedMethod[nestedType]--; - } - - // if (lastAct == ERROR_ACTION) { - // return; - // } - // - // field.initialization = expressionStack[expressionPtr]; - // - // // mark field with local type if one was found during parsing - // if ((type.bits & ASTNode.HasLocalTypeMASK) != 0) { - // field.bits |= ASTNode.HasLocalTypeMASK; - // } - } - // A P I - - public void parse(Initializer ini, TypeDeclaration type, CompilationUnitDeclaration unit) { - //only parse the method body of md - //fill out method statements - - //convert bugs into parse error - - initialize(false); - goForInitializer(); - nestedMethod[nestedType]++; - - referenceContext = type; - compilationUnit = unit; - - scanner.resetTo(ini.sourceStart, ini.sourceEnd); // just on the beginning { - try { - parse(); - } catch (AbortCompilation ex) { - lastAct = ERROR_ACTION; - } finally { - nestedMethod[nestedType]--; - } - - // if (lastAct == ERROR_ACTION) { - // return; - // } - // - // ini.block = ((Initializer) astStack[astPtr]).block; - // - // // mark initializer with local type if one was found during parsing - // if ((type.bits & ASTNode.HasLocalTypeMASK) != 0) { - // ini.bits |= ASTNode.HasLocalTypeMASK; - // } - } - // A P I - - public void parse(MethodDeclaration md, CompilationUnitDeclaration unit) { -// TODO jsurfer - make the parse process work on methods ? - return; - -// //only parse the method body of md -// //fill out method statements -// -// //convert bugs into parse error -// -// if (md.isAbstract()) -// return; -// // if (md.isNative()) -// // return; -// // if ((md.modifiers & AccSemicolonBody) != 0) -// // return; -// -// initialize(false); -// goForMethodBody(); -// nestedMethod[nestedType]++; -// -// referenceContext = md; -// compilationUnit = unit; -// -// scanner.resetTo(md.sourceEnd + 1, md.declarationSourceEnd); -// -// // reset the scanner to parser from { down to } -// try { -// parse(); -// } catch (AbortCompilation ex) { -// lastAct = ERROR_ACTION; -// } finally { -// nestedMethod[nestedType]--; -// } -// -// // if (lastAct == ERROR_ACTION) { -// // return; -// // } -// // -// // //refill statements -// // md.explicitDeclarations = realBlockStack[realBlockPtr--]; -// // int length; -// // if ((length = astLengthStack[astLengthPtr--]) != 0) -// // System.arraycopy( -// // astStack, -// // (astPtr -= length) + 1, -// // md.statements = new Statement[length], -// // 0, -// // length); - } - - // A P I - - public CompilationUnitDeclaration parse(ICompilationUnit sourceUnit, CompilationResult compilationResult, int start, int end) { - // parses a compilation unit and manages error handling (even bugs....) - - CompilationUnitDeclaration unit; - try { - /* automaton initialization */ - initialize(false); - goForCompilationUnit(); - - /* scanner initialization */ - scanner.setSource(sourceUnit, sourceUnit.getContents()); - scanner.resetTo(start, end); - /* unit creation */ - referenceContext = - compilationUnit = new CompilationUnitDeclaration(problemReporter, compilationResult, scanner.source.length); - - /* run automaton */ - parse(); - } catch (SyntaxError syntaxError) { - // - } finally { - unit = compilationUnit; - compilationUnit = null; // reset parser - } - return unit; - } - - public CompilationUnitDeclaration dietParse(ICompilationUnit sourceUnit, CompilationResult compilationResult) { - return dietParse(sourceUnit, compilationResult, false); - } - public CompilationUnitDeclaration dietParse(ICompilationUnit sourceUnit, CompilationResult compilationResult, boolean phpMode) { - - CompilationUnitDeclaration parsedUnit; - boolean old = diet; - try { - diet = true; - parsedUnit = parse(sourceUnit, compilationResult, phpMode); - } finally { - diet = old; - } - return parsedUnit; - } - - public void getMethodBodies(CompilationUnitDeclaration unit) { - //fill the methods bodies in order for the code to be generated - - if (unit == null) return; - - if (unit.ignoreMethodBodies) { - unit.ignoreFurtherInvestigation = true; + public UnitParser(ProblemReporter problemReporter) { // , boolean + // optimizeStringLiterals, + // boolean + // assertMode) { + super(problemReporter); + nestedMethod = new int[30]; + + // this.optimizeStringLiterals = optimizeStringLiterals; + // this.assertMode = assertMode; + // this.initializeScanner(); + astLengthStack = new int[50]; + // expressionLengthStack = new int[30]; + // intStack = new int[50]; + // identifierStack = new char[30][]; + // identifierLengthStack = new int[30]; + // nestedMethod = new int[30]; + // realBlockStack = new int[30]; + // identifierPositionStack = new long[30]; + // variablesCounter = new int[30]; + } + + public void goForConstructorBody() { + // tells the scanner to go for compilation unit parsing + + firstToken = TokenNameEQUAL_EQUAL; + scanner.recordLineSeparator = false; + } + + public void goForExpression() { + // tells the scanner to go for an expression parsing + + firstToken = TokenNameREMAINDER; + scanner.recordLineSeparator = false; + } + + public void goForCompilationUnit() { + // tells the scanner to go for compilation unit parsing + + firstToken = TokenNamePLUS_PLUS; + scanner.linePtr = -1; + scanner.foundTaskCount = 0; + scanner.recordLineSeparator = true; + // scanner.currentLine= null; + } + + public void goForInitializer() { + // tells the scanner to go for initializer parsing + + firstToken = TokenNameRIGHT_SHIFT; + scanner.recordLineSeparator = false; + } + + public void goForMethodBody() { + // tells the scanner to go for method body parsing + + firstToken = TokenNameMINUS_MINUS; + scanner.recordLineSeparator = false; + } + + public void initialize(boolean phpMode) { + super.initialize(phpMode); + // positionning the parser for a new compilation unit + // avoiding stack reallocation and all that.... + // astPtr = -1; + // astLengthPtr = -1; + // expressionPtr = -1; + // expressionLengthPtr = -1; + // identifierPtr = -1; + // identifierLengthPtr = -1; + // intPtr = -1; + // nestedMethod[nestedType = 0] = 0; // need to reset for further reuse + // variablesCounter[nestedType] = 0; + // dimensions = 0 ; + // realBlockPtr = -1; + // endStatementPosition = 0; + + // remove objects from stack too, while the same parser/compiler couple + // is + // re-used between two compilations .... + + // int astLength = astStack.length; + // if (noAstNodes.length < astLength){ + // noAstNodes = new ASTNode[astLength]; + // //System.out.println("Resized AST stacks : "+ astLength); + // + // } + // System.arraycopy(noAstNodes, 0, astStack, 0, astLength); + // + // int expressionLength = expressionStack.length; + // if (noExpressions.length < expressionLength){ + // noExpressions = new Expression[expressionLength]; + // //System.out.println("Resized EXPR stacks : "+ expressionLength); + // } + // System.arraycopy(noExpressions, 0, expressionStack, 0, + // expressionLength); + + // reset scanner state + scanner.commentPtr = -1; + scanner.foundTaskCount = 0; + scanner.eofPosition = Integer.MAX_VALUE; + + // resetModifiers(); + // + // // recovery + // lastCheckPoint = -1; + // currentElement = null; + // restartRecovery = false; + // hasReportedError = false; + // recoveredStaticInitializerStart = 0; + // lastIgnoredToken = -1; + // lastErrorEndPosition = -1; + // listLength = 0; + } + + // A P I + + public CompilationUnitDeclaration parse(ICompilationUnit sourceUnit, + CompilationResult compilationResult, boolean phpMode) { + // parses a compilation unit and manages error handling (even bugs....) + + CompilationUnitDeclaration unit; + try { + /* automaton initialization */ + initialize(phpMode); + goForCompilationUnit(); + + /* scanner initialization */ + scanner.setSource(sourceUnit, sourceUnit.getContents()); + + /* unit creation */ + referenceContext = compilationUnit = new CompilationUnitDeclaration( + problemReporter, compilationResult, scanner.source.length); + // TODO TypeDeclaration test + // TypeDeclaration typeDecl = new + // TypeDeclaration(this.compilationUnit.compilationResult); + // typeDecl.sourceStart = 0; + // typeDecl.sourceEnd = 10; + // typeDecl.name = new char[]{'t', 'e','s','t'}; + // this.compilationUnit.types = new ArrayList(); + // this.compilationUnit.types.add(typeDecl); + /* run automaton */ + super.parse(); + // // TODO jsurfer start + // if (sourceUnit instanceof BasicCompilationUnit) { + // storeProblemsFor(((BasicCompilationUnit)sourceUnit).getResource(), + // compilationResult.getAllProblems()); + // } + // // jsurfer end + + } finally { + unit = compilationUnit; + compilationUnit = null; // reset parser + } + return unit; + } + + /** + * Creates a marker from each problem and adds it to the resource. The + * marker is as follows: - its type is T_PROBLEM - its plugin ID is the + * JavaBuilder's plugin ID - its message is the problem's message - its + * priority reflects the severity of the problem - its range is the + * problem's range - it has an extra attribute "ID" which holds the + * problem's id + */ + protected void storeProblemsFor(IResource resource, IProblem[] problems) + throws CoreException { + if (resource == null || problems == null || problems.length == 0) + return; + + for (int i = 0, l = problems.length; i < l; i++) { + IProblem problem = problems[i]; + int id = problem.getID(); + if (id != IProblem.Task) { + IMarker marker = resource + .createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); + marker + .setAttributes( + new String[] { IMarker.MESSAGE, + IMarker.SEVERITY, IJavaModelMarker.ID, + IMarker.CHAR_START, IMarker.CHAR_END, + IMarker.LINE_NUMBER, + IJavaModelMarker.ARGUMENTS }, + new Object[] { + problem.getMessage(), + new Integer( + problem.isError() ? IMarker.SEVERITY_ERROR + : IMarker.SEVERITY_WARNING), + new Integer(id), + new Integer(problem.getSourceStart()), + new Integer(problem.getSourceEnd() + 1), + new Integer(problem + .getSourceLineNumber()), + net.sourceforge.phpdt.internal.core.util.Util + .getProblemArgumentsForMarker(problem + .getArguments()) }); + } + + } + } + + // A P I + + public void parse(ConstructorDeclaration cd, CompilationUnitDeclaration unit) { + // only parse the method body of cd + // fill out its statements + + // convert bugs into parse error + + initialize(false); + goForConstructorBody(); + nestedMethod[nestedType]++; + + referenceContext = cd; + compilationUnit = unit; + + scanner.resetTo(cd.sourceEnd + 1, cd.declarationSourceEnd); + try { + parse(); + } catch (AbortCompilation ex) { + lastAct = ERROR_ACTION; + + } finally { + nestedMethod[nestedType]--; + } + + if (lastAct == ERROR_ACTION) { + initialize(false); + return; + } + + // statements + // cd.explicitDeclarations = realBlockStack[realBlockPtr--]; + // int length; + // if ((length = astLengthStack[astLengthPtr--]) != 0) { + // astPtr -= length; + // if (astStack[astPtr + 1] instanceof ExplicitConstructorCall) + // //avoid a isSomeThing that would only be used here BUT what is faster + // between two alternatives ? + // { + // System.arraycopy( + // astStack, + // astPtr + 2, + // cd.statements = new Statement[length - 1], + // 0, + // length - 1); + // cd.constructorCall = (ExplicitConstructorCall) astStack[astPtr + 1]; + // } else { //need to add explicitly the super(); + // System.arraycopy( + // astStack, + // astPtr + 1, + // cd.statements = new Statement[length], + // 0, + // length); + // cd.constructorCall = SuperReference.implicitSuperConstructorCall(); + // } + // } else { + // cd.constructorCall = SuperReference.implicitSuperConstructorCall(); + // } + // + // if (cd.constructorCall.sourceEnd == 0) { + // cd.constructorCall.sourceEnd = cd.sourceEnd; + // cd.constructorCall.sourceStart = cd.sourceStart; + // } + } + + // A P I + + public void parse(FieldDeclaration field, TypeDeclaration type, + CompilationUnitDeclaration unit, char[] initializationSource) { + // only parse the initializationSource of the given field + + // convert bugs into parse error + + initialize(false); + goForExpression(); + nestedMethod[nestedType]++; + + referenceContext = type; + compilationUnit = unit; + + scanner.setSource(initializationSource); + scanner.resetTo(0, initializationSource.length - 1); + try { + parse(); + } catch (AbortCompilation ex) { + lastAct = ERROR_ACTION; + } finally { + nestedMethod[nestedType]--; + } + + // if (lastAct == ERROR_ACTION) { + // return; + // } + // + // field.initialization = expressionStack[expressionPtr]; + // + // // mark field with local type if one was found during parsing + // if ((type.bits & ASTNode.HasLocalTypeMASK) != 0) { + // field.bits |= ASTNode.HasLocalTypeMASK; + // } + } + + // A P I + + public void parse(Initializer ini, TypeDeclaration type, + CompilationUnitDeclaration unit) { + // only parse the method body of md + // fill out method statements + + // convert bugs into parse error + + initialize(false); + goForInitializer(); + nestedMethod[nestedType]++; + + referenceContext = type; + compilationUnit = unit; + + scanner.resetTo(ini.sourceStart, ini.sourceEnd); // just on the + // beginning { + try { + parse(); + } catch (AbortCompilation ex) { + lastAct = ERROR_ACTION; + } finally { + nestedMethod[nestedType]--; + } + + // if (lastAct == ERROR_ACTION) { + // return; + // } + // + // ini.block = ((Initializer) astStack[astPtr]).block; + // + // // mark initializer with local type if one was found during parsing + // if ((type.bits & ASTNode.HasLocalTypeMASK) != 0) { + // ini.bits |= ASTNode.HasLocalTypeMASK; + // } + } + + // A P I + + public void parse(MethodDeclaration md, CompilationUnitDeclaration unit) { + // TODO jsurfer - make the parse process work on methods ? return; - // if initial diet parse did not work, no need to dig into method bodies. + + // //only parse the method body of md + // //fill out method statements + // + // //convert bugs into parse error + // + // if (md.isAbstract()) + // return; + // // if (md.isNative()) + // // return; + // // if ((md.modifiers & AccSemicolonBody) != 0) + // // return; + // + // initialize(false); + // goForMethodBody(); + // nestedMethod[nestedType]++; + // + // referenceContext = md; + // compilationUnit = unit; + // + // scanner.resetTo(md.sourceEnd + 1, md.declarationSourceEnd); + // + // // reset the scanner to parser from { down to } + // try { + // parse(); + // } catch (AbortCompilation ex) { + // lastAct = ERROR_ACTION; + // } finally { + // nestedMethod[nestedType]--; + // } + // + // // if (lastAct == ERROR_ACTION) { + // // return; + // // } + // // + // // //refill statements + // // md.explicitDeclarations = realBlockStack[realBlockPtr--]; + // // int length; + // // if ((length = astLengthStack[astLengthPtr--]) != 0) + // // System.arraycopy( + // // astStack, + // // (astPtr -= length) + 1, + // // md.statements = new Statement[length], + // // 0, + // // length); } - if ((unit.bits & ASTNode.HasAllMethodBodies) != 0) - return; //work already done ... - - //real parse of the method.... - char[] contents = unit.compilationResult.compilationUnit.getContents(); - this.scanner.setSource(contents); - - // save existing values to restore them at the end of the parsing process - // see bug 47079 for more details - int[] oldLineEnds = this.scanner.lineEnds; - int oldLinePtr = this.scanner.linePtr; - - final int[] lineSeparatorPositions = unit.compilationResult.lineSeparatorPositions; - this.scanner.lineEnds = lineSeparatorPositions; - this.scanner.linePtr = lineSeparatorPositions.length - 1; - -// if (this.javadocParser != null && this.javadocParser.checkDocComment) { -// this.javadocParser.scanner.setSource(contents); -// } - if (unit.types != null) { - for (int i = unit.types.size(); --i >= 0;) - ((TypeDeclaration)unit.types.get(i)).parseMethod(this, unit); + // A P I + + public CompilationUnitDeclaration parse(ICompilationUnit sourceUnit, + CompilationResult compilationResult, int start, int end) { + // parses a compilation unit and manages error handling (even bugs....) + + CompilationUnitDeclaration unit; + try { + /* automaton initialization */ + initialize(false); + goForCompilationUnit(); + + /* scanner initialization */ + scanner.setSource(sourceUnit, sourceUnit.getContents()); + scanner.resetTo(start, end); + /* unit creation */ + referenceContext = compilationUnit = new CompilationUnitDeclaration( + problemReporter, compilationResult, scanner.source.length); + + /* run automaton */ + parse(); + } catch (SyntaxError syntaxError) { + // + } finally { + unit = compilationUnit; + compilationUnit = null; // reset parser + } + return unit; + } + + public CompilationUnitDeclaration dietParse(ICompilationUnit sourceUnit, + CompilationResult compilationResult) { + return dietParse(sourceUnit, compilationResult, false); + } + + public CompilationUnitDeclaration dietParse(ICompilationUnit sourceUnit, + CompilationResult compilationResult, boolean phpMode) { + + CompilationUnitDeclaration parsedUnit; + boolean old = diet; + try { + diet = true; + parsedUnit = parse(sourceUnit, compilationResult, phpMode); + } finally { + diet = old; + } + return parsedUnit; + } + + public void getMethodBodies(CompilationUnitDeclaration unit) { + // fill the methods bodies in order for the code to be generated + + if (unit == null) + return; + + if (unit.ignoreMethodBodies) { + unit.ignoreFurtherInvestigation = true; + return; + // if initial diet parse did not work, no need to dig into method + // bodies. + } + + if ((unit.bits & ASTNode.HasAllMethodBodies) != 0) + return; // work already done ... + + // real parse of the method.... + char[] contents = unit.compilationResult.compilationUnit.getContents(); + this.scanner.setSource(contents); + + // save existing values to restore them at the end of the parsing + // process + // see bug 47079 for more details + int[] oldLineEnds = this.scanner.lineEnds; + int oldLinePtr = this.scanner.linePtr; + + final int[] lineSeparatorPositions = unit.compilationResult.lineSeparatorPositions; + this.scanner.lineEnds = lineSeparatorPositions; + this.scanner.linePtr = lineSeparatorPositions.length - 1; + + // if (this.javadocParser != null && this.javadocParser.checkDocComment) + // { + // this.javadocParser.scanner.setSource(contents); + // } + if (unit.types != null) { + for (int i = unit.types.size(); --i >= 0;) + ((TypeDeclaration) unit.types.get(i)).parseMethod(this, unit); + } + + // tag unit has having read bodies + unit.bits |= ASTNode.HasAllMethodBodies; + + // this is done to prevent any side effects on the compilation unit + // result + // line separator positions array. + this.scanner.lineEnds = oldLineEnds; + this.scanner.linePtr = oldLinePtr; } - - // tag unit has having read bodies - unit.bits |= ASTNode.HasAllMethodBodies; - - // this is done to prevent any side effects on the compilation unit result - // line separator positions array. - this.scanner.lineEnds = oldLineEnds; - this.scanner.linePtr = oldLinePtr; -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/VariableInfo.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/VariableInfo.java index 4f79776..7699108 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/VariableInfo.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/VariableInfo.java @@ -3,32 +3,32 @@ package net.sourceforge.phpdt.internal.compiler.parser; import net.sourceforge.phpdt.internal.compiler.ast.SingleTypeReference; public class VariableInfo { - static final public int LEVEL_UNDEFINED = 0; + static final public int LEVEL_UNDEFINED = 0; - static final public int LEVEL_GLOBAL_VAR = 3; + static final public int LEVEL_GLOBAL_VAR = 3; - static final public int LEVEL_STATIC_VAR = 4; + static final public int LEVEL_STATIC_VAR = 4; - static final public int LEVEL_CLASS_UNIT = 5; + static final public int LEVEL_CLASS_UNIT = 5; - static final public int LEVEL_FUNCTION_DEFINITION = 6; + static final public int LEVEL_FUNCTION_DEFINITION = 6; - static final public int LEVEL_METHOD_DEFINITION = 7; + static final public int LEVEL_METHOD_DEFINITION = 7; - public int level = LEVEL_UNDEFINED; + public int level = LEVEL_UNDEFINED; - int startPosition; + int startPosition; - public SingleTypeReference reference = null; + public SingleTypeReference reference = null; - public char[] typeIdentifier = null; - - public VariableInfo(int startPosition) { - this(startPosition, LEVEL_UNDEFINED); - } + public char[] typeIdentifier = null; - public VariableInfo(int startPosition, int level) { - this.startPosition = startPosition; - this.level = level; - } + public VariableInfo(int startPosition) { + this(startPosition, LEVEL_UNDEFINED); + } + + public VariableInfo(int startPosition, int level) { + this.startPosition = startPosition; + this.level = level; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/AbortCompilation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/AbortCompilation.java index f954e99..6d4c650 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/AbortCompilation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/AbortCompilation.java @@ -13,28 +13,36 @@ package net.sourceforge.phpdt.internal.compiler.problem; import net.sourceforge.phpdt.internal.compiler.CompilationResult; /* - * Special unchecked exception type used - * to abort from the compilation process - * + * Special unchecked exception type used to abort from the compilation process + * * should only be thrown from within problem handlers. */ public class AbortCompilation extends RuntimeException { public CompilationResult compilationResult; + public Throwable exception; - public int problemId; + + public int problemId; + public String[] problemArguments, messageArguments; - /* special fields used to abort silently (e.g. when cancelling build process) */ + + /* + * special fields used to abort silently (e.g. when cancelling build + * process) + */ public boolean isSilent; + public RuntimeException silentException; public AbortCompilation() { - this((CompilationResult)null); + this((CompilationResult) null); } - public AbortCompilation(int problemId, String[] problemArguments, String[] messageArguments) { - + public AbortCompilation(int problemId, String[] problemArguments, + String[] messageArguments) { + this.problemId = problemId; this.problemArguments = problemArguments; this.messageArguments = messageArguments; @@ -45,7 +53,8 @@ public class AbortCompilation extends RuntimeException { this(compilationResult, null); } - public AbortCompilation(CompilationResult compilationResult, Throwable exception) { + public AbortCompilation(CompilationResult compilationResult, + Throwable exception) { this.compilationResult = compilationResult; this.exception = exception; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/AbortCompilationUnit.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/AbortCompilationUnit.java index d708839..8e4407b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/AbortCompilationUnit.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/AbortCompilationUnit.java @@ -13,13 +13,12 @@ package net.sourceforge.phpdt.internal.compiler.problem; import net.sourceforge.phpdt.internal.compiler.CompilationResult; /* - * Special unchecked exception type used - * to abort from the compilation process - * + * Special unchecked exception type used to abort from the compilation process + * * should only be thrown from within problem handlers. */ public class AbortCompilationUnit extends AbortCompilation { -public AbortCompilationUnit(CompilationResult compilationResult) { - super(compilationResult); -} + public AbortCompilationUnit(CompilationResult compilationResult) { + super(compilationResult); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/AbortMethod.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/AbortMethod.java index 77e8920..8ac6b34 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/AbortMethod.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/AbortMethod.java @@ -13,13 +13,12 @@ package net.sourceforge.phpdt.internal.compiler.problem; import net.sourceforge.phpdt.internal.compiler.CompilationResult; /* - * Special unchecked exception type used - * to abort from the compilation process - * + * Special unchecked exception type used to abort from the compilation process + * * should only be thrown from within problem handlers. */ public class AbortMethod extends AbortType { -public AbortMethod(CompilationResult compilationResult) { - super(compilationResult); -} + public AbortMethod(CompilationResult compilationResult) { + super(compilationResult); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/AbortType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/AbortType.java index 16e388e..8f370d6 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/AbortType.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/AbortType.java @@ -13,13 +13,12 @@ package net.sourceforge.phpdt.internal.compiler.problem; import net.sourceforge.phpdt.internal.compiler.CompilationResult; /* - * Special unchecked exception type used - * to abort from the compilation process - * + * Special unchecked exception type used to abort from the compilation process + * * should only be thrown from within problem handlers. */ public class AbortType extends AbortCompilationUnit { -public AbortType(CompilationResult compilationResult) { - super(compilationResult); -} + public AbortType(CompilationResult compilationResult) { + super(compilationResult); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/DefaultProblem.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/DefaultProblem.java index c154b28..be82160 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/DefaultProblem.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/DefaultProblem.java @@ -9,16 +9,23 @@ * IBM Corporation - initial API and implementation *******************************************************************************/ package net.sourceforge.phpdt.internal.compiler.problem; + import net.sourceforge.phpdt.core.compiler.IProblem; import net.sourceforge.phpdt.internal.compiler.util.Util; - + public class DefaultProblem implements ProblemSeverities, IProblem { private char[] fileName; + private int id; + private int startPosition, endPosition, line; + private int severity; + private String[] arguments; + private String message; + public DefaultProblem(char[] originatingFileName, String message, int id, String[] stringArguments, int severity, int startPosition, int endPosition, int line) { @@ -31,12 +38,13 @@ public class DefaultProblem implements ProblemSeverities, IProblem { this.endPosition = endPosition; this.line = line; } + public String errorReportSource(char[] unitSource) { - //extra from the source the innacurate token - //and "highlight" it using some underneath ^^^^^ - //put some context around too. - //this code assumes that the font used in the console is fixed size - //sanity ..... + // extra from the source the innacurate token + // and "highlight" it using some underneath ^^^^^ + // put some context around too. + // this code assumes that the font used in the console is fixed size + // sanity ..... if ((startPosition > endPosition) || ((startPosition < 0) && (endPosition < 0))) return Util.bind("problem.noSourceInformation"); //$NON-NLS-1$ @@ -47,10 +55,10 @@ public class DefaultProblem implements ProblemSeverities, IProblem { final char SPACE = '\u0020'; final char MARK = '^'; final char TAB = '\t'; - //the next code tries to underline the token..... - //it assumes (for a good display) that token source does not - //contain any \r \n. This is false on statements ! - //(the code still works but the display is not optimal !) + // the next code tries to underline the token..... + // it assumes (for a good display) that token source does not + // contain any \r \n. This is false on statements ! + // (the code still works but the display is not optimal !) // expand to line limits int length = unitSource.length, begin, end; for (begin = startPosition >= length ? length - 1 : startPosition; begin > 0; begin--) { @@ -64,7 +72,7 @@ public class DefaultProblem implements ProblemSeverities, IProblem { // trim left and right spaces/tabs while ((c = unitSource[begin]) == ' ' || c == '\t') begin++; - //while ((c = unitSource[end]) == ' ' || c == '\t') end--; TODO + // while ((c = unitSource[end]) == ' ' || c == '\t') end--; TODO // (philippe) should also trim right, but all tests are to be updated // copy source errorBuffer.append(unitSource, begin, end - begin + 1); @@ -73,98 +81,98 @@ public class DefaultProblem implements ProblemSeverities, IProblem { for (int i = begin; i < startPosition; i++) { errorBuffer.append((unitSource[i] == TAB) ? TAB : SPACE); } - for (int i = startPosition; i <= (endPosition >= length - ? length - 1 + for (int i = startPosition; i <= (endPosition >= length ? length - 1 : endPosition); i++) { errorBuffer.append(MARK); } return errorBuffer.toString(); } - // public String errorReportSource(ITextEditor textEditor){ + + // public String errorReportSource(ITextEditor textEditor){ // //ICompilationUnit compilationUnit) { - // //extra from the source the innacurate token - // //and "highlight" it using some underneath ^^^^^ - // //put some context around too. + // //extra from the source the innacurate token + // //and "highlight" it using some underneath ^^^^^ + // //put some context around too. // - // //this code assumes that the font used in the console is fixed size + // //this code assumes that the font used in the console is fixed size // - // //sanity ..... - // if ((startPosition > endPosition) - // || ((startPosition <= 0) && (endPosition <= 0))) - // return ProjectPrefUtil.bind("problem.noSourceInformation"); //$NON-NLS-1$ + // //sanity ..... + // if ((startPosition > endPosition) + // || ((startPosition <= 0) && (endPosition <= 0))) + // return ProjectPrefUtil.bind("problem.noSourceInformation"); //$NON-NLS-1$ // - // final char SPACE = '\u0020'; - // final char MARK = '^'; - // final char TAB = '\t'; - //// char[] source = compilationUnit.getContents(); - // char[] source = + // final char SPACE = '\u0020'; + // final char MARK = '^'; + // final char TAB = '\t'; + // // char[] source = compilationUnit.getContents(); + // char[] source = // textEditor.getDocumentProvider().getDocument(null).get().toCharArray(); - // //the next code tries to underline the token..... - // //it assumes (for a good display) that token source does not - // //contain any \r \n. This is false on statements ! - // //(the code still works but the display is not optimal !) + // //the next code tries to underline the token..... + // //it assumes (for a good display) that token source does not + // //contain any \r \n. This is false on statements ! + // //(the code still works but the display is not optimal !) // - // //compute the how-much-char we are displaying around the inaccurate + // //compute the how-much-char we are displaying around the inaccurate // token - // int begin = startPosition >= source.length ? source.length - 1 : + // int begin = startPosition >= source.length ? source.length - 1 : // startPosition; - // int relativeStart = 0; - // int end = endPosition >= source.length ? source.length - 1 : + // int relativeStart = 0; + // int end = endPosition >= source.length ? source.length - 1 : // endPosition; - // int relativeEnd = 0; - // label : for (relativeStart = 0;; relativeStart++) { - // if (begin == 0) - // break label; - // if ((source[begin - 1] == '\n') || (source[begin - 1] == '\r')) - // break label; - // begin--; - // } - // label : for (relativeEnd = 0;; relativeEnd++) { - // if ((end + 1) >= source.length) - // break label; - // if ((source[end + 1] == '\r') || (source[end + 1] == '\n')) { - // break label; - // } - // end++; - // } - // //extract the message form the source - // char[] extract = new char[end - begin + 1]; - // System.arraycopy(source, begin, extract, 0, extract.length); - // char c; - // //remove all SPACE and TAB that begin the error message... - // int trimLeftIndex = 0; - // while (((c = extract[trimLeftIndex++]) == TAB) || (c == SPACE)) { - // }; - // System.arraycopy( - // extract, - // trimLeftIndex - 1, - // extract = new char[extract.length - trimLeftIndex + 1], - // 0, - // extract.length); - // relativeStart -= trimLeftIndex; - // //buffer spaces and tabs in order to reach the error position - // int pos = 0; - // char[] underneath = new char[extract.length]; // can't be bigger - // for (int i = 0; i <= relativeStart; i++) { - // if (extract[i] == TAB) { - // underneath[pos++] = TAB; - // } else { - // underneath[pos++] = SPACE; - // } - // } - // //mark the error position - // for (int i = startPosition; - // i <= (endPosition >= source.length ? source.length - 1 : endPosition); - // i++) - // underneath[pos++] = MARK; - // //resize underneathto remove 'null' chars - // System.arraycopy(underneath, 0, underneath = new char[pos], 0, pos); + // int relativeEnd = 0; + // label : for (relativeStart = 0;; relativeStart++) { + // if (begin == 0) + // break label; + // if ((source[begin - 1] == '\n') || (source[begin - 1] == '\r')) + // break label; + // begin--; + // } + // label : for (relativeEnd = 0;; relativeEnd++) { + // if ((end + 1) >= source.length) + // break label; + // if ((source[end + 1] == '\r') || (source[end + 1] == '\n')) { + // break label; + // } + // end++; + // } + // //extract the message form the source + // char[] extract = new char[end - begin + 1]; + // System.arraycopy(source, begin, extract, 0, extract.length); + // char c; + // //remove all SPACE and TAB that begin the error message... + // int trimLeftIndex = 0; + // while (((c = extract[trimLeftIndex++]) == TAB) || (c == SPACE)) { + // }; + // System.arraycopy( + // extract, + // trimLeftIndex - 1, + // extract = new char[extract.length - trimLeftIndex + 1], + // 0, + // extract.length); + // relativeStart -= trimLeftIndex; + // //buffer spaces and tabs in order to reach the error position + // int pos = 0; + // char[] underneath = new char[extract.length]; // can't be bigger + // for (int i = 0; i <= relativeStart; i++) { + // if (extract[i] == TAB) { + // underneath[pos++] = TAB; + // } else { + // underneath[pos++] = SPACE; + // } + // } + // //mark the error position + // for (int i = startPosition; + // i <= (endPosition >= source.length ? source.length - 1 : endPosition); + // i++) + // underneath[pos++] = MARK; + // //resize underneathto remove 'null' chars + // System.arraycopy(underneath, 0, underneath = new char[pos], 0, pos); // - // return " " + ProjectPrefUtil.bind("problem.atLine", String.valueOf(line)) + // return " " + ProjectPrefUtil.bind("problem.atLine", String.valueOf(line)) // //$NON-NLS-2$ //$NON-NLS-1$ - // + "\n\t" + new String(extract) + "\n\t" + new String(underneath); + // + "\n\t" + new String(extract) + "\n\t" + new String(underneath); // //$NON-NLS-2$ //$NON-NLS-1$ - // } + // } /** * Answer back the original arguments recorded into the problem. * @@ -173,6 +181,7 @@ public class DefaultProblem implements ProblemSeverities, IProblem { public String[] getArguments() { return arguments; } + /** * Answer the type of problem. * @@ -182,6 +191,7 @@ public class DefaultProblem implements ProblemSeverities, IProblem { public int getID() { return id; } + /** * Answer a localized, human-readable message string which describes the * problem. @@ -191,6 +201,7 @@ public class DefaultProblem implements ProblemSeverities, IProblem { public String getMessage() { return message; } + /** * Answer the file name in which the problem was found. * @@ -199,6 +210,7 @@ public class DefaultProblem implements ProblemSeverities, IProblem { public char[] getOriginatingFileName() { return fileName; } + /** * Answer the end position of the problem (inclusive), or -1 if unknown. * @@ -207,6 +219,7 @@ public class DefaultProblem implements ProblemSeverities, IProblem { public int getSourceEnd() { return endPosition; } + /** * Answer the line number in source where the problem begins. * @@ -215,6 +228,7 @@ public class DefaultProblem implements ProblemSeverities, IProblem { public int getSourceLineNumber() { return line; } + /** * Answer the start position of the problem (inclusive), or -1 if unknown. * @@ -223,6 +237,7 @@ public class DefaultProblem implements ProblemSeverities, IProblem { public int getSourceStart() { return startPosition; } + /* * Helper method: checks the severity to see if the Error bit is set. * @return boolean @@ -230,6 +245,7 @@ public class DefaultProblem implements ProblemSeverities, IProblem { public boolean isError() { return (severity & ProblemSeverities.Error) != 0; } + /* * Helper method: checks the severity to see if the Error bit is not set. * @return boolean @@ -237,6 +253,7 @@ public class DefaultProblem implements ProblemSeverities, IProblem { public boolean isWarning() { return (severity & ProblemSeverities.Error) == 0; } + /** * Set the end position of the problem (inclusive), or -1 if unknown. * @@ -248,6 +265,7 @@ public class DefaultProblem implements ProblemSeverities, IProblem { public void setSourceEnd(int sourceEnd) { endPosition = sourceEnd; } + /** * Set the line number in source where the problem begins. * @@ -257,6 +275,7 @@ public class DefaultProblem implements ProblemSeverities, IProblem { public void setSourceLineNumber(int lineNumber) { line = lineNumber; } + /** * Set the start position of the problem (inclusive), or -1 if unknown. * @@ -268,6 +287,7 @@ public class DefaultProblem implements ProblemSeverities, IProblem { public void setSourceStart(int sourceStart) { startPosition = sourceStart; } + public String toString() { String s = "Pb(" + (id & IgnoreCategoriesMask) + ") "; //$NON-NLS-1$ //$NON-NLS-2$ if (message != null) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/DefaultProblemFactory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/DefaultProblemFactory.java index 33b6b24..a9bcabc 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/DefaultProblemFactory.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/DefaultProblemFactory.java @@ -20,150 +20,161 @@ import net.sourceforge.phpdt.internal.compiler.IProblemFactory; public class DefaultProblemFactory implements IProblemFactory { - public String[] messageTemplates; + private Locale locale; + private static String[] DEFAULT_LOCALE_TEMPLATES; + private final static char[] DOUBLE_QUOTES = "''".toCharArray(); //$NON-NLS-1$ + private final static char[] SINGLE_QUOTE = "'".toCharArray(); //$NON-NLS-1$ -/** - * @param loc the locale used to get the right message - */ -public DefaultProblemFactory(Locale loc) { - this.locale = loc; - if (Locale.getDefault().equals(loc)){ - if (DEFAULT_LOCALE_TEMPLATES == null){ - DEFAULT_LOCALE_TEMPLATES = loadMessageTemplates(loc); + /** + * @param loc + * the locale used to get the right message + */ + public DefaultProblemFactory(Locale loc) { + this.locale = loc; + if (Locale.getDefault().equals(loc)) { + if (DEFAULT_LOCALE_TEMPLATES == null) { + DEFAULT_LOCALE_TEMPLATES = loadMessageTemplates(loc); + } + this.messageTemplates = DEFAULT_LOCALE_TEMPLATES; + } else { + this.messageTemplates = loadMessageTemplates(loc); } - this.messageTemplates = DEFAULT_LOCALE_TEMPLATES; - } else { - this.messageTemplates = loadMessageTemplates(loc); } -} -/** - * Answer a new IProblem created according to the parameters value - *
                  - *
                • originatingFileName the name of the file name from which the problem is originated - *
                • problemId the problem id - *
                • problemArguments the fully qualified arguments recorded inside the problem - *
                • messageArguments the arguments needed to set the error message (shorter names than problemArguments ones) - *
                • severity the severity of the problem - *
                • startPosition the starting position of the problem - *
                • endPosition the end position of the problem - *
                • lineNumber the line on which the problem occured - *
                - * @param originatingFileName char[] - * @param problemId int - * @param arguments String[] - * @param severity int - * @param startPosition int - * @param endPosition int - * @param lineNumber int - * @return net.sourceforge.phpdt.internal.compiler.IProblem - */ -public IProblem createProblem( - char[] originatingFileName, - int problemId, - String[] problemArguments, - String[] messageArguments, - int severity, - int startPosition, - int endPosition, - int lineNumber) { - - return new DefaultProblem( - originatingFileName, - this.getLocalizedMessage(problemId, messageArguments), - problemId, - problemArguments, - severity, - startPosition, - endPosition, - lineNumber); -} -/** - * Answer the locale used to retrieve the error messages - * @return java.util.Locale - */ -public Locale getLocale() { - return locale; -} -public final String getLocalizedMessage(int id, String[] problemArguments) { - StringBuffer output = new StringBuffer(80); - String message = - messageTemplates[(id & IProblem.IgnoreCategoriesMask)]; - if (message == null) { - return "Unable to retrieve the error message for problem id: " //$NON-NLS-1$ - + (id & IProblem.IgnoreCategoriesMask) - + ". Check compiler resources."; //$NON-NLS-1$ + + /** + * Answer a new IProblem created according to the parameters value + *
                  + *
                • originatingFileName the name of the file name from which the problem + * is originated + *
                • problemId the problem id + *
                • problemArguments the fully qualified arguments recorded inside the + * problem + *
                • messageArguments the arguments needed to set the error message + * (shorter names than problemArguments ones) + *
                • severity the severity of the problem + *
                • startPosition the starting position of the problem + *
                • endPosition the end position of the problem + *
                • lineNumber the line on which the problem occured + *
                + * + * @param originatingFileName + * char[] + * @param problemId + * int + * @param arguments + * String[] + * @param severity + * int + * @param startPosition + * int + * @param endPosition + * int + * @param lineNumber + * int + * @return net.sourceforge.phpdt.internal.compiler.IProblem + */ + public IProblem createProblem(char[] originatingFileName, int problemId, + String[] problemArguments, String[] messageArguments, int severity, + int startPosition, int endPosition, int lineNumber) { + + return new DefaultProblem(originatingFileName, this + .getLocalizedMessage(problemId, messageArguments), problemId, + problemArguments, severity, startPosition, endPosition, + lineNumber); + } + + /** + * Answer the locale used to retrieve the error messages + * + * @return java.util.Locale + */ + public Locale getLocale() { + return locale; } - // for compatibility with MessageFormat which eliminates double quotes in original message - char[] messageWithNoDoubleQuotes = - CharOperation.replace(message.toCharArray(), DOUBLE_QUOTES, SINGLE_QUOTE); - message = new String(messageWithNoDoubleQuotes); - - int length = message.length(); - int start = -1, end = length; - while (true) { - if ((end = message.indexOf('{', start)) > -1) { - output.append(message.substring(start + 1, end)); - if ((start = message.indexOf('}', end)) > -1) { - try { - output.append( - problemArguments[Integer.parseInt(message.substring(end + 1, start))]); - } catch (NumberFormatException nfe) { - output.append(message.substring(end + 1, start + 1)); - } catch (ArrayIndexOutOfBoundsException e) { - return "Corrupted compiler resources for problem id: " //$NON-NLS-1$ - + (id & IProblem.IgnoreCategoriesMask) - + ". Check compiler resources."; //$NON-NLS-1$ + public final String getLocalizedMessage(int id, String[] problemArguments) { + StringBuffer output = new StringBuffer(80); + String message = messageTemplates[(id & IProblem.IgnoreCategoriesMask)]; + if (message == null) { + return "Unable to retrieve the error message for problem id: " //$NON-NLS-1$ + + (id & IProblem.IgnoreCategoriesMask) + + ". Check compiler resources."; //$NON-NLS-1$ + } + + // for compatibility with MessageFormat which eliminates double quotes + // in original message + char[] messageWithNoDoubleQuotes = CharOperation.replace(message + .toCharArray(), DOUBLE_QUOTES, SINGLE_QUOTE); + message = new String(messageWithNoDoubleQuotes); + + int length = message.length(); + int start = -1, end = length; + while (true) { + if ((end = message.indexOf('{', start)) > -1) { + output.append(message.substring(start + 1, end)); + if ((start = message.indexOf('}', end)) > -1) { + try { + output.append(problemArguments[Integer.parseInt(message + .substring(end + 1, start))]); + } catch (NumberFormatException nfe) { + output.append(message.substring(end + 1, start + 1)); + } catch (ArrayIndexOutOfBoundsException e) { + return "Corrupted compiler resources for problem id: " //$NON-NLS-1$ + + (id & IProblem.IgnoreCategoriesMask) + + ". Check compiler resources."; //$NON-NLS-1$ + } + } else { + output.append(message.substring(end, length)); + break; } } else { - output.append(message.substring(end, length)); + output.append(message.substring(start + 1, length)); break; } - } else { - output.append(message.substring(start + 1, length)); - break; } + return output.toString(); } - return output.toString(); -} -/** - * @param problem net.sourceforge.phpdt.internal.compiler.IProblem - * @return String - */ -public final String localizedMessage(IProblem problem) { - return getLocalizedMessage(problem.getID(), problem.getArguments()); -} -/** - * This method initializes the MessageTemplates class variable according - * to the current Locale. - */ -public static String[] loadMessageTemplates(Locale loc) { - ResourceBundle bundle = null; - String bundleName = "net.sourceforge.phpdt.internal.compiler.problem.messages"; //$NON-NLS-1$ - try { - bundle = ResourceBundle.getBundle(bundleName, loc); - } catch(MissingResourceException e) { - System.out.println("Missing resource : " + bundleName.replace('.', '/') + ".properties for locale " + loc); //$NON-NLS-1$//$NON-NLS-2$ - throw e; + /** + * @param problem + * net.sourceforge.phpdt.internal.compiler.IProblem + * @return String + */ + public final String localizedMessage(IProblem problem) { + return getLocalizedMessage(problem.getID(), problem.getArguments()); } - String[] templates = new String[500]; - for (int i = 0, max = templates.length; i < max; i++) { + + /** + * This method initializes the MessageTemplates class variable according to + * the current Locale. + */ + public static String[] loadMessageTemplates(Locale loc) { + ResourceBundle bundle = null; + String bundleName = "net.sourceforge.phpdt.internal.compiler.problem.messages"; //$NON-NLS-1$ try { - templates[i] = bundle.getString(String.valueOf(i)); + bundle = ResourceBundle.getBundle(bundleName, loc); } catch (MissingResourceException e) { - // available ID + System.out + .println("Missing resource : " + bundleName.replace('.', '/') + ".properties for locale " + loc); //$NON-NLS-1$//$NON-NLS-2$ + throw e; + } + String[] templates = new String[500]; + for (int i = 0, max = templates.length; i < max; i++) { + try { + templates[i] = bundle.getString(String.valueOf(i)); + } catch (MissingResourceException e) { + // available ID + } } + return templates; } - return templates; -} -public DefaultProblemFactory() { - this(Locale.getDefault()); -} + public DefaultProblemFactory() { + this(Locale.getDefault()); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/ProblemHandler.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/ProblemHandler.java index f29e11d..11fa4e1 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/ProblemHandler.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/ProblemHandler.java @@ -17,172 +17,153 @@ import net.sourceforge.phpdt.internal.compiler.IProblemFactory; import net.sourceforge.phpdt.internal.compiler.impl.CompilerOptions; import net.sourceforge.phpdt.internal.compiler.impl.ReferenceContext; - /* - * Compiler error handler, responsible to determine whether - * a problem is actually a warning or an error; also will - * decide whether the compilation task can be processed further or not. - * - * Behavior : will request its current policy if need to stop on - * first error, and if should proceed (persist) with problems. + * Compiler error handler, responsible to determine whether a problem is + * actually a warning or an error; also will decide whether the compilation task + * can be processed further or not. + * + * Behavior : will request its current policy if need to stop on first error, + * and if should proceed (persist) with problems. */ public class ProblemHandler implements ProblemSeverities { public final static String[] NoArgument = new String[0]; - + final public IErrorHandlingPolicy policy; + public final IProblemFactory problemFactory; - public final CompilerOptions options; -/* - * Problem handler can be supplied with a policy to specify - * its behavior in error handling. Also see static methods for - * built-in policies. - * - */ -public ProblemHandler(IErrorHandlingPolicy policy, CompilerOptions options, IProblemFactory problemFactory) { - this.policy = policy; - this.problemFactory = problemFactory; - this.options = options; -} -/* - * Given the current configuration, answers which category the problem - * falls into: - * Error | Warning | Ignore - */ -public int computeSeverity(int problemId){ - return Error; // by default all problems are errors -} -public IProblem createProblem( - char[] fileName, - int problemId, - String[] problemArguments, - String[] messageArguments, - int severity, - int problemStartPosition, - int problemEndPosition, - int lineNumber, - ReferenceContext referenceContext, - CompilationResult unitResult) { - - return problemFactory.createProblem( - fileName, - problemId, - problemArguments, - messageArguments, - severity, - problemStartPosition, - problemEndPosition, - lineNumber); -} -public void handle( - int problemId, - String[] problemArguments, - String[] messageArguments, - int severity, - int problemStartPosition, - int problemEndPosition, - ReferenceContext referenceContext, - CompilationResult unitResult) { - - if (severity == Ignore) - return; - - // if no reference context, we need to abort from the current compilation process - if (referenceContext == null) { - if ((severity & Error) != 0) { // non reportable error is fatal - throw new AbortCompilation(problemId, problemArguments, messageArguments); - } else { - return; // ignore non reportable warning - } + + public final CompilerOptions options; + + /* + * Problem handler can be supplied with a policy to specify its behavior in + * error handling. Also see static methods for built-in policies. + * + */ + public ProblemHandler(IErrorHandlingPolicy policy, CompilerOptions options, + IProblemFactory problemFactory) { + this.policy = policy; + this.problemFactory = problemFactory; + this.options = options; + } + + /* + * Given the current configuration, answers which category the problem falls + * into: Error | Warning | Ignore + */ + public int computeSeverity(int problemId) { + return Error; // by default all problems are errors } - IProblem problem = - this.createProblem( - unitResult.getFileName(), - problemId, - problemArguments, - messageArguments, - severity, - problemStartPosition, - problemEndPosition, - problemStartPosition >= 0 - ? searchLineNumber(unitResult.lineSeparatorPositions, problemStartPosition) - : 0, - referenceContext, - unitResult); - if (problem == null) return; // problem couldn't be created, ignore - - switch (severity & Error) { - case Error : + public IProblem createProblem(char[] fileName, int problemId, + String[] problemArguments, String[] messageArguments, int severity, + int problemStartPosition, int problemEndPosition, int lineNumber, + ReferenceContext referenceContext, CompilationResult unitResult) { + + return problemFactory.createProblem(fileName, problemId, + problemArguments, messageArguments, severity, + problemStartPosition, problemEndPosition, lineNumber); + } + + public void handle(int problemId, String[] problemArguments, + String[] messageArguments, int severity, int problemStartPosition, + int problemEndPosition, ReferenceContext referenceContext, + CompilationResult unitResult) { + + if (severity == Ignore) + return; + + // if no reference context, we need to abort from the current + // compilation process + if (referenceContext == null) { + if ((severity & Error) != 0) { // non reportable error is fatal + throw new AbortCompilation(problemId, problemArguments, + messageArguments); + } else { + return; // ignore non reportable warning + } + } + + IProblem problem = this + .createProblem(unitResult.getFileName(), problemId, + problemArguments, messageArguments, severity, + problemStartPosition, problemEndPosition, + problemStartPosition >= 0 ? searchLineNumber( + unitResult.lineSeparatorPositions, + problemStartPosition) : 0, referenceContext, + unitResult); + if (problem == null) + return; // problem couldn't be created, ignore + + switch (severity & Error) { + case Error: this.record(problem, unitResult, referenceContext); referenceContext.tagAsHavingErrors(); // should abort ? int abortLevel; - if ((abortLevel = - (policy.stopOnFirstError() ? AbortCompilation : severity & Abort)) != 0) { + if ((abortLevel = (policy.stopOnFirstError() ? AbortCompilation + : severity & Abort)) != 0) { referenceContext.abort(abortLevel); } break; - case Warning : + case Warning: this.record(problem, unitResult, referenceContext); break; + } } -} -/** - * Standard problem handling API, the actual severity (warning/error/ignore) is deducted - * from the problem ID and the current compiler options. - */ -public void handle( - int problemId, - String[] problemArguments, - String[] messageArguments, - int problemStartPosition, - int problemEndPosition, - ReferenceContext referenceContext, - CompilationResult unitResult) { - - this.handle( - problemId, - problemArguments, - messageArguments, - this.computeSeverity(problemId), // severity inferred using the ID - problemStartPosition, - problemEndPosition, - referenceContext, - unitResult); -} -public void record(IProblem problem, CompilationResult unitResult, ReferenceContext referenceContext) { - unitResult.record(problem, referenceContext); -} -/** - * Search the line number corresponding to a specific position - * - * @param methodBinding net.sourceforge.phpdt.internal.compiler.nameloopkup.SyntheticAccessMethodBinding - */ -public static final int searchLineNumber(int[] startLineIndexes, int position) { - if (startLineIndexes == null) - return 1; - int length = startLineIndexes.length; - if (length == 0) - return 1; - int g = 0, d = length - 1; - int m = 0; - while (g <= d) { - m = (g + d) /2; + + /** + * Standard problem handling API, the actual severity (warning/error/ignore) + * is deducted from the problem ID and the current compiler options. + */ + public void handle(int problemId, String[] problemArguments, + String[] messageArguments, int problemStartPosition, + int problemEndPosition, ReferenceContext referenceContext, + CompilationResult unitResult) { + + this.handle(problemId, problemArguments, messageArguments, + this.computeSeverity(problemId), // severity inferred using + // the ID + problemStartPosition, problemEndPosition, referenceContext, + unitResult); + } + + public void record(IProblem problem, CompilationResult unitResult, + ReferenceContext referenceContext) { + unitResult.record(problem, referenceContext); + } + + /** + * Search the line number corresponding to a specific position + * + * @param methodBinding + * net.sourceforge.phpdt.internal.compiler.nameloopkup.SyntheticAccessMethodBinding + */ + public static final int searchLineNumber(int[] startLineIndexes, + int position) { + if (startLineIndexes == null) + return 1; + int length = startLineIndexes.length; + if (length == 0) + return 1; + int g = 0, d = length - 1; + int m = 0; + while (g <= d) { + m = (g + d) / 2; + if (position < startLineIndexes[m]) { + d = m - 1; + } else if (position > startLineIndexes[m]) { + g = m + 1; + } else { + return m + 1; + } + } if (position < startLineIndexes[m]) { - d = m-1; - } else if (position > startLineIndexes[m]) { - g = m+1; - } else { return m + 1; } + return m + 2; } - if (position < startLineIndexes[m]) { - return m+1; - } - return m+2; -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/ProblemReporter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/ProblemReporter.java index d2842a0..2c92e38 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/ProblemReporter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/ProblemReporter.java @@ -74,2879 +74,3592 @@ import net.sourceforge.phpdt.internal.compiler.parser.Scanner; import net.sourceforge.phpdt.internal.compiler.util.Util; public class ProblemReporter extends ProblemHandler implements ProblemReasons { - public ReferenceContext referenceContext; - - public ProblemReporter(IErrorHandlingPolicy policy, CompilerOptions options, IProblemFactory problemFactory) { - - // IProblemFactory problemFactory) { - super(policy, options, problemFactory); //), problemFactory); - } - - public void abortDueToInternalError(String errorMessage) { - String[] arguments = new String[] { errorMessage }; - this.handle(IProblem.Unclassified, arguments, arguments, Error | Abort, 0, 0); - } - - public void abortDueToInternalError(String errorMessage, ASTNode location) { - String[] arguments = new String[] { errorMessage }; - this.handle(IProblem.Unclassified, arguments, arguments, Error | Abort, location.sourceStart, location.sourceEnd); - } - - public void abstractMethodCannotBeOverridden(SourceTypeBinding type, MethodBinding concreteMethod) { - this.handle( - // %1 must be abstract since it cannot override the inherited - // package-private abstract method %2 - IProblem.AbstractMethodCannotBeOverridden, new String[] { - new String(type.sourceName()), - new String(CharOperation.concat(concreteMethod.declaringClass.readableName(), concreteMethod.readableName(), '.')) }, - new String[] { - new String(type.sourceName()), - new String(CharOperation.concat(concreteMethod.declaringClass.shortReadableName(), concreteMethod.shortReadableName(), - '.')) }, type.sourceStart(), type.sourceEnd()); - } - - public void abstractMethodInAbstractClass(SourceTypeBinding type, AbstractMethodDeclaration methodDecl) { - String[] arguments = new String[] { new String(type.sourceName()), new String(methodDecl.selector) }; - this.handle(IProblem.AbstractMethodInAbstractClass, arguments, arguments, methodDecl.sourceStart, methodDecl.sourceEnd); - } - - public void abstractMethodMustBeImplemented(SourceTypeBinding type, MethodBinding abstractMethod) { - this.handle( - // Must implement the inherited abstract method %1 - // 8.4.3 - Every non-abstract subclass of an abstract type, A, - // must provide a concrete implementation of all of A's - // methods. - IProblem.AbstractMethodMustBeImplemented, new String[] { new String(CharOperation.concat(abstractMethod.declaringClass - .readableName(), abstractMethod.readableName(), '.')) }, new String[] { new String(CharOperation.concat( - abstractMethod.declaringClass.shortReadableName(), abstractMethod.shortReadableName(), '.')) }, type.sourceStart(), - type.sourceEnd()); - } - - public void abstractMethodNeedingNoBody(AbstractMethodDeclaration method) { - this.handle(IProblem.BodyForAbstractMethod, NoArgument, NoArgument, method.sourceStart, method.sourceEnd, method, method - .compilationResult()); - } - - public void alreadyDefinedLabel(char[] labelName, ASTNode location) { - String[] arguments = new String[] { new String(labelName) }; - this.handle(IProblem.DuplicateLabel, arguments, arguments, location.sourceStart, location.sourceEnd); - } - - public void anonymousClassCannotExtendFinalClass(Expression expression, TypeBinding type) { - this.handle(IProblem.AnonymousClassCannotExtendFinalClass, new String[] { new String(type.readableName()) }, - new String[] { new String(type.shortReadableName()) }, expression.sourceStart, expression.sourceEnd); - } - - public void argumentTypeCannotBeVoid(SourceTypeBinding type, AbstractMethodDeclaration methodDecl, Argument arg) { - String[] arguments = new String[] { new String(methodDecl.selector), new String(arg.name) }; - this.handle(IProblem.ArgumentTypeCannotBeVoid, arguments, arguments, methodDecl.sourceStart, methodDecl.sourceEnd); - } - - public void argumentTypeCannotBeVoidArray(SourceTypeBinding type, AbstractMethodDeclaration methodDecl, Argument arg) { - String[] arguments = new String[] { new String(methodDecl.selector), new String(arg.name) }; - this.handle(IProblem.ArgumentTypeCannotBeVoidArray, arguments, arguments, methodDecl.sourceStart, methodDecl.sourceEnd); - } - - public void argumentTypeProblem(SourceTypeBinding type, AbstractMethodDeclaration methodDecl, Argument arg, - TypeBinding expectedType) { - int problemId = expectedType.problemId(); - int id; - switch (problemId) { - case NotFound: - // 1 - id = IProblem.ArgumentTypeNotFound; - break; - case NotVisible: - // 2 - id = IProblem.ArgumentTypeNotVisible; - break; - case Ambiguous: - // 3 - id = IProblem.ArgumentTypeAmbiguous; - break; - case InternalNameProvided: - // 4 - id = IProblem.ArgumentTypeInternalNameProvided; - break; - case InheritedNameHidesEnclosingName: - // 5 - id = IProblem.ArgumentTypeInheritedNameHidesEnclosingName; - break; - case NoError: - // 0 - default: - needImplementation(); // want to fail to see why we were - // here... - return; - } - this.handle(id, new String[] { new String(methodDecl.selector), arg.name(), new String(expectedType.readableName()) }, - new String[] { new String(methodDecl.selector), arg.name(), new String(expectedType.shortReadableName()) }, - arg.type.sourceStart, arg.type.sourceEnd); - } - - public void arrayConstantsOnlyInArrayInitializers(int sourceStart, int sourceEnd) { - this.handle(IProblem.ArrayConstantsOnlyInArrayInitializers, NoArgument, NoArgument, sourceStart, sourceEnd); - } - - public void assignmentHasNoEffect(Assignment assignment, char[] name) { - String[] arguments = new String[] { new String(name) }; - this.handle(IProblem.AssignmentHasNoEffect, arguments, arguments, assignment.sourceStart, assignment.sourceEnd); - } - - public void attemptToReturnNonVoidExpression(ReturnStatement returnStatement, TypeBinding expectedType) { - this.handle(IProblem.VoidMethodReturnsValue, new String[] { new String(expectedType.readableName()) }, - new String[] { new String(expectedType.shortReadableName()) }, returnStatement.sourceStart, returnStatement.sourceEnd); - } - - public void attemptToReturnVoidValue(ReturnStatement returnStatement) { - this.handle(IProblem.MethodReturnsVoid, NoArgument, NoArgument, returnStatement.sourceStart, returnStatement.sourceEnd); - } - - //public void bytecodeExceeds64KLimit(AbstractMethodDeclaration location) - // { - // String[] arguments = new String[] {new String(location.selector), - // parametersAsString(location.binding)}; - // if (location.isConstructor()) { - // this.handle( - // IProblem.BytecodeExceeds64KLimitForConstructor, - // arguments, - // arguments, - // Error | Abort, - // location.sourceStart, - // location.sourceEnd); - // } else { - // this.handle( - // IProblem.BytecodeExceeds64KLimit, - // arguments, - // arguments, - // Error | Abort, - // location.sourceStart, - // location.sourceEnd); - // } - //} - public void bytecodeExceeds64KLimit(TypeDeclaration location) { - this.handle(IProblem.BytecodeExceeds64KLimitForClinit, NoArgument, NoArgument, Error | Abort, location.sourceStart, - location.sourceEnd); - } - - public void cannotAllocateVoidArray(Expression expression) { - this.handle(IProblem.CannotAllocateVoidArray, NoArgument, NoArgument, expression.sourceStart, expression.sourceEnd); - } - - public void cannotAssignToFinalField(FieldBinding field, ASTNode location) { - this.handle(IProblem.FinalFieldAssignment, new String[] { - (field.declaringClass == null ? "array" : new String(field.declaringClass.readableName())), //$NON-NLS-1$ - new String(field.readableName()) }, new String[] { - (field.declaringClass == null ? "array" : new String(field.declaringClass.shortReadableName())), //$NON-NLS-1$ - new String(field.shortReadableName()) }, location.sourceStart, location.sourceEnd); - } - - public void cannotAssignToFinalLocal(LocalVariableBinding local, ASTNode location) { - String[] arguments = new String[] { new String(local.readableName()) }; - this.handle(IProblem.NonBlankFinalLocalAssignment, arguments, arguments, location.sourceStart, location.sourceEnd); - } - - public void cannotAssignToFinalOuterLocal(LocalVariableBinding local, ASTNode location) { - String[] arguments = new String[] { new String(local.readableName()) }; - this.handle(IProblem.FinalOuterLocalAssignment, arguments, arguments, location.sourceStart, location.sourceEnd); - } - - public void cannotDeclareLocalInterface(char[] interfaceName, int sourceStart, int sourceEnd) { - String[] arguments = new String[] { new String(interfaceName) }; - this.handle(IProblem.CannotDefineInterfaceInLocalType, arguments, arguments, sourceStart, sourceEnd); - } - - public void cannotDefineDimensionsAndInitializer(ArrayAllocationExpression expresssion) { - this.handle(IProblem.CannotDefineDimensionExpressionsWithInit, NoArgument, NoArgument, expresssion.sourceStart, - expresssion.sourceEnd); - } - - public void cannotDireclyInvokeAbstractMethod(MessageSend messageSend, MethodBinding method) { - this.handle(IProblem.DirectInvocationOfAbstractMethod, new String[] { - new String(method.declaringClass.readableName()), - new String(method.selector), - parametersAsString(method) }, new String[] { - new String(method.declaringClass.shortReadableName()), - new String(method.selector), - parametersAsShortString(method) }, messageSend.sourceStart, messageSend.sourceEnd); - } - - // public void cannotImportPackage(ImportReference importRef) { - // String[] arguments = new String[]{CharOperation.toString(importRef.tokens)}; - // this.handle(IProblem.CannotImportPackage, arguments, arguments, - // importRef.sourceStart, importRef.sourceEnd); - // } - public void cannotInstantiate(TypeReference typeRef, TypeBinding type) { - this.handle(IProblem.InvalidClassInstantiation, new String[] { new String(type.readableName()) }, new String[] { new String( - type.shortReadableName()) }, typeRef.sourceStart, typeRef.sourceEnd); - } - - public void cannotReferToNonFinalOuterLocal(LocalVariableBinding local, ASTNode location) { - String[] arguments = new String[] { new String(local.readableName()) }; - this.handle(IProblem.OuterLocalMustBeFinal, arguments, arguments, location.sourceStart, location.sourceEnd); - } - - public void cannotReturnInInitializer(ASTNode location) { - this.handle(IProblem.CannotReturnInInitializer, NoArgument, NoArgument, location.sourceStart, location.sourceEnd); - } - - public void cannotThrowNull(ThrowStatement statement) { - this.handle(IProblem.CannotThrowNull, NoArgument, NoArgument, statement.sourceStart, statement.sourceEnd); - } - - public void cannotThrowType(SourceTypeBinding type, AbstractMethodDeclaration methodDecl, TypeReference exceptionType, - TypeBinding expectedType) { - this.handle(IProblem.CannotThrowType, new String[] { new String(expectedType.readableName()) }, new String[] { new String( - expectedType.shortReadableName()) }, exceptionType.sourceStart, exceptionType.sourceEnd); - } - - public void cannotUseSuperInJavaLangObject(ASTNode reference) { - this.handle(IProblem.ObjectHasNoSuperclass, NoArgument, NoArgument, reference.sourceStart, reference.sourceEnd); - } - - public void cannotUseSuperInCodeSnippet(int start, int end) { - this.handle(IProblem.CannotUseSuperInCodeSnippet, NoArgument, NoArgument, Error | Abort, start, end); - } - - public void caseExpressionMustBeConstant(Expression expression) { - this.handle(IProblem.NonConstantExpression, NoArgument, NoArgument, expression.sourceStart, expression.sourceEnd); - } - - public void classExtendFinalClass(SourceTypeBinding type, TypeReference superclass, TypeBinding expectedType) { - String name = new String(type.sourceName()); - String expectedFullName = new String(expectedType.readableName()); - String expectedShortName = new String(expectedType.shortReadableName()); - if (expectedShortName.equals(name)) - expectedShortName = expectedFullName; - this.handle(IProblem.ClassExtendFinalClass, new String[] { expectedFullName, name }, new String[] { expectedShortName, name }, - superclass.sourceStart, superclass.sourceEnd); - } - - public void codeSnippetMissingClass(String missing, int start, int end) { - String[] arguments = new String[] { missing }; - this.handle(IProblem.CodeSnippetMissingClass, arguments, arguments, Error | Abort, start, end); - } - - public void codeSnippetMissingMethod(String className, String missingMethod, String argumentTypes, int start, int end) { - String[] arguments = new String[] { className, missingMethod, argumentTypes }; - this.handle(IProblem.CodeSnippetMissingMethod, arguments, arguments, Error | Abort, start, end); - } - - /* - * Given the current configuration, answers which category the problem falls into: Error | Warning | Ignore - */ - public int computeSeverity(int problemId) { - - // severity can have been preset on the problem - // if ((problem.severity & Fatal) != 0){ - // return Error; - // } - - // if not then check whether it is a configurable problem - switch (problemId) { - case IProblem.PHPIncludeNotExistWarning: - return this.options.getSeverity(CompilerOptions.PHPIncludeNotExistWarning); - case IProblem.PHPVarDeprecatedWarning: - return this.options.getSeverity(CompilerOptions.PHPVarDeprecatedWarning); - case IProblem.PHPBadStyleKeywordWarning: - return this.options.getSeverity(CompilerOptions.PHPBadStyleKeywordWarning); - case IProblem.PHPBadStyleUppercaseIdentifierWarning: - return this.options.getSeverity(CompilerOptions.PHPBadStyleUppercaseIdentifierWarning); - - case IProblem.UninitializedLocalVariable: - return this.options.getSeverity(CompilerOptions.UninitializedLocalVariableWarning); - case IProblem.CodeCannotBeReached: - return this.options.getSeverity(CompilerOptions.CodeCannotBeReachedWarning); - - case IProblem.MaskedCatch: - return this.options.getSeverity(CompilerOptions.MaskedCatchBlock); - - case IProblem.UnusedImport: - return this.options.getSeverity(CompilerOptions.UnusedImport); - - case IProblem.MethodButWithConstructorName: - return this.options.getSeverity(CompilerOptions.MethodWithConstructorName); - - case IProblem.OverridingNonVisibleMethod: - return this.options.getSeverity(CompilerOptions.OverriddenPackageDefaultMethod); - - case IProblem.IncompatibleReturnTypeForNonInheritedInterfaceMethod: - case IProblem.IncompatibleExceptionInThrowsClauseForNonInheritedInterfaceMethod: - return this.options.getSeverity(CompilerOptions.IncompatibleNonInheritedInterfaceMethod); - - case IProblem.OverridingDeprecatedMethod: - case IProblem.UsingDeprecatedType: - case IProblem.UsingDeprecatedMethod: - case IProblem.UsingDeprecatedConstructor: - case IProblem.UsingDeprecatedField: - return this.options.getSeverity(CompilerOptions.UsingDeprecatedAPI); - - case IProblem.LocalVariableIsNeverUsed: - return this.options.getSeverity(CompilerOptions.UnusedLocalVariable); - - case IProblem.ArgumentIsNeverUsed: - return this.options.getSeverity(CompilerOptions.UnusedArgument); - - case IProblem.NoImplicitStringConversionForCharArrayExpression: - return this.options.getSeverity(CompilerOptions.NoImplicitStringConversion); - - case IProblem.NeedToEmulateFieldReadAccess: - case IProblem.NeedToEmulateFieldWriteAccess: - case IProblem.NeedToEmulateMethodAccess: - case IProblem.NeedToEmulateConstructorAccess: - return this.options.getSeverity(CompilerOptions.AccessEmulation); - - case IProblem.NonExternalizedStringLiteral: - return this.options.getSeverity(CompilerOptions.NonExternalizedString); - - case IProblem.UseAssertAsAnIdentifier: - return this.options.getSeverity(CompilerOptions.AssertUsedAsAnIdentifier); - - case IProblem.NonStaticAccessToStaticMethod: - case IProblem.NonStaticAccessToStaticField: - return this.options.getSeverity(CompilerOptions.NonStaticAccessToStatic); - - // case IProblem.IndirectAccessToStaticMethod : - // case IProblem.IndirectAccessToStaticField : - // case IProblem.IndirectAccessToStaticType : - // return this.options.getSeverity(CompilerOptions.IndirectStaticAccess); - - case IProblem.AssignmentHasNoEffect: - return this.options.getSeverity(CompilerOptions.NoEffectAssignment); - - case IProblem.UnusedPrivateConstructor: - case IProblem.UnusedPrivateMethod: - case IProblem.UnusedPrivateField: - case IProblem.UnusedPrivateType: - return this.options.getSeverity(CompilerOptions.UnusedPrivateMember); - - case IProblem.Task: - return Warning; - - // case IProblem.LocalVariableHidingLocalVariable: - // case IProblem.LocalVariableHidingField: - // case IProblem.ArgumentHidingLocalVariable: - // case IProblem.ArgumentHidingField: - // return this.options.getSeverity(CompilerOptions.LocalVariableHiding); - - // case IProblem.FieldHidingLocalVariable: - // case IProblem.FieldHidingField: - // return this.options.getSeverity(CompilerOptions.FieldHiding); - - // case IProblem.PossibleAccidentalBooleanAssignment: - // return this.options.getSeverity(CompilerOptions.AccidentalBooleanAssign); - - // case IProblem.SuperfluousSemicolon: - // return this.options.getSeverity(CompilerOptions.SuperfluousSemicolon); - // - // case IProblem.UndocumentedEmptyBlock: - // return this.options.getSeverity(CompilerOptions.UndocumentedEmptyBlock); - // - // case IProblem.UnnecessaryCast: - // case IProblem.UnnecessaryArgumentCast: - // case IProblem.UnnecessaryInstanceof: - // return this.options.getSeverity(CompilerOptions.UnnecessaryTypeCheck); - // - // case IProblem.FinallyMustCompleteNormally: - // return this.options.getSeverity(CompilerOptions.FinallyBlockNotCompleting); - // - // case IProblem.UnusedMethodDeclaredThrownException: - // case IProblem.UnusedConstructorDeclaredThrownException: - // return this.options.getSeverity(CompilerOptions.UnusedDeclaredThrownException); - // - // case IProblem.UnqualifiedFieldAccess: - // return this.options.getSeverity(CompilerOptions.UnqualifiedFieldAccess); - - /* - * Javadoc syntax errors - */ - // Javadoc explicit IDs - // case IProblem.JavadocUnexpectedTag: - // case IProblem.JavadocDuplicateReturnTag: - // case IProblem.JavadocInvalidThrowsClass: - // case IProblem.JavadocInvalidSeeReference: - // case IProblem.JavadocInvalidSeeHref: - // case IProblem.JavadocInvalidSeeArgs: - // case IProblem.JavadocInvalidTag: - // return this.options.getSeverity(CompilerOptions.InvalidJavadoc); - /* - * Javadoc tags resolved references errors - */ - // case IProblem.JavadocInvalidParamName: - // case IProblem.JavadocDuplicateParamName: - // case IProblem.JavadocMissingParamName: - // case IProblem.JavadocInvalidThrowsClassName: - // case IProblem.JavadocDuplicateThrowsClassName: - // case IProblem.JavadocMissingThrowsClassName: - // case IProblem.JavadocMissingSeeReference: - // case IProblem.JavadocUsingDeprecatedField: - // case IProblem.JavadocUsingDeprecatedConstructor: - // case IProblem.JavadocUsingDeprecatedMethod: - // case IProblem.JavadocUsingDeprecatedType: - // case IProblem.JavadocUndefinedField: - // case IProblem.JavadocNotVisibleField: - // case IProblem.JavadocAmbiguousField: - // case IProblem.JavadocUndefinedConstructor: - // case IProblem.JavadocNotVisibleConstructor: - // case IProblem.JavadocAmbiguousConstructor: - // case IProblem.JavadocUndefinedMethod: - // case IProblem.JavadocNotVisibleMethod: - // case IProblem.JavadocAmbiguousMethod: - // case IProblem.JavadocParameterMismatch: - // case IProblem.JavadocUndefinedType: - // case IProblem.JavadocNotVisibleType: - // case IProblem.JavadocAmbiguousType: - // case IProblem.JavadocInternalTypeNameProvided: - // case IProblem.JavadocNoMessageSendOnArrayType: - // case IProblem.JavadocNoMessageSendOnBaseType: - // if (!this.options.reportInvalidJavadocTags) - // return ProblemSeverities.Ignore; - // else - // return this.options.getSeverity(CompilerOptions.InvalidJavadoc); - /* - * Javadoc missing tags errors - */ - // case IProblem.JavadocMissingParamTag: - // case IProblem.JavadocMissingReturnTag: - // case IProblem.JavadocMissingThrowsTag: - // return this.options.getSeverity(CompilerOptions.MissingJavadocTags); - /* - * Missing Javadoc errors - */ - // case IProblem.JavadocMissing: - // return this.options.getSeverity(CompilerOptions.MissingJavadocComments); - // by default problems are errors. - default: - return Error; - } - } - - //public void conditionalArgumentsIncompatibleTypes(ConditionalExpression - // expression, TypeBinding trueType, TypeBinding falseType) { - // this.handle( - // IProblem.IncompatibleTypesInConditionalOperator, - // new String[] {new String(trueType.readableName()), new - // String(falseType.readableName())}, - // new String[] {new String(trueType.sourceName()), new - // String(falseType.sourceName())}, - // expression.sourceStart, - // expression.sourceEnd); - //} - // public void conflictingImport(ImportReference importRef) { - // String[] arguments = new String[]{CharOperation.toString(importRef.tokens)}; - // this.handle(IProblem.ConflictingImport, arguments, arguments, - // importRef.sourceStart, importRef.sourceEnd); - // } - public void constantOutOfFormat(NumberLiteral lit) { - // the literal is not in a correct format - // this code is called on IntLiteral and LongLiteral - // example 000811 ...the 8 is uncorrect. - if ((lit instanceof LongLiteral) || (lit instanceof IntLiteral)) { - char[] source = lit.source(); - try { - final String Radix; - final int radix; - if ((source[1] == 'x') || (source[1] == 'X')) { - radix = 16; - Radix = "Hexa"; //$NON-NLS-1$ - } else { - radix = 8; - Radix = "Octal"; //$NON-NLS-1$ - } - //look for the first digit that is incorrect - int place = -1; - label: for (int i = radix == 8 ? 1 : 2; i < source.length; i++) { - if (Character.digit(source[i], radix) == -1) { - place = i; - break label; - } - } - String[] arguments = new String[] { Radix + " " + new String(source) - + " (digit " + new String(new char[] { source[place] }) + ")" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - this.handle(IProblem.NumericValueOutOfRange, arguments, arguments, lit.sourceStart, lit.sourceEnd); - return; - } catch (IndexOutOfBoundsException ex) { - } - // just in case .... use a predefined error.. - // we should never come here...(except if the code changes !) - this.constantOutOfRange(lit); - } - } - - public void constantOutOfRange(Literal lit) { - // lit is some how out of range of it declared type - // example - // 9999999999999999999999999999999999999999999999999999999999999999999 - String[] arguments = new String[] { new String(lit.source()) }; - this.handle(IProblem.NumericValueOutOfRange, arguments, arguments, lit.sourceStart, lit.sourceEnd); - } - - public void deprecatedField(FieldBinding field, ASTNode location) { - this.handle(IProblem.UsingDeprecatedField, new String[] { - new String(field.declaringClass.readableName()), - new String(field.name) }, new String[] { new String(field.declaringClass.shortReadableName()), new String(field.name) }, - location.sourceStart, location.sourceEnd); - } - - public void deprecatedMethod(MethodBinding method, ASTNode location) { - if (method.isConstructor()) - this.handle(IProblem.UsingDeprecatedConstructor, new String[] { - new String(method.declaringClass.readableName()), - parametersAsString(method) }, new String[] { - new String(method.declaringClass.shortReadableName()), - parametersAsShortString(method) }, location.sourceStart, location.sourceEnd); - else - this.handle(IProblem.UsingDeprecatedMethod, new String[] { - new String(method.declaringClass.readableName()), - new String(method.selector), - parametersAsString(method) }, new String[] { - new String(method.declaringClass.shortReadableName()), - new String(method.selector), - parametersAsShortString(method) }, location.sourceStart, location.sourceEnd); - } - - public void deprecatedType(TypeBinding type, ASTNode location) { - if (location == null) - return; // 1G828DN - no type ref for synthetic arguments - this.handle(IProblem.UsingDeprecatedType, new String[] { new String(type.readableName()) }, new String[] { new String(type - .shortReadableName()) }, location.sourceStart, location.sourceEnd); - } - - public void duplicateCase(CaseStatement statement, Constant constant) { - String[] arguments = new String[] { String.valueOf(constant.intValue()) }; - this.handle(IProblem.DuplicateCase, arguments, arguments, statement.sourceStart, statement.sourceEnd); - } - - public void duplicateDefaultCase(DefaultCase statement) { - this.handle(IProblem.DuplicateDefaultCase, NoArgument, NoArgument, statement.sourceStart, statement.sourceEnd); - } - - public void duplicateFieldInType(SourceTypeBinding type, FieldDeclaration fieldDecl) { - this.handle(IProblem.DuplicateField, new String[] { new String(type.sourceName()), fieldDecl.name() }, new String[] { - new String(type.shortReadableName()), - fieldDecl.name() }, fieldDecl.sourceStart, fieldDecl.sourceEnd); - } - - // public void duplicateImport(ImportReference importRef) { - // String[] arguments = new String[]{CharOperation.toString(importRef.tokens)}; - // this.handle(IProblem.DuplicateImport, arguments, arguments, - // importRef.sourceStart, importRef.sourceEnd); - // } - public void duplicateInitializationOfBlankFinalField(FieldBinding field, Reference reference) { - String[] arguments = new String[] { new String(field.readableName()) }; - this.handle(IProblem.DuplicateBlankFinalFieldInitialization, arguments, arguments, reference.sourceStart, reference.sourceEnd); - } - - public void duplicateInitializationOfFinalLocal(LocalVariableBinding local, ASTNode location) { - String[] arguments = new String[] { new String(local.readableName()) }; - this.handle(IProblem.DuplicateFinalLocalInitialization, arguments, arguments, location.sourceStart, location.sourceEnd); - } - - public void duplicateMethodInType(SourceTypeBinding type, AbstractMethodDeclaration methodDecl) { - String[] arguments = new String[] { new String(methodDecl.selector), new String(type.sourceName()) }; - this.handle(IProblem.DuplicateMethod, arguments, arguments, methodDecl.sourceStart, methodDecl.sourceEnd); - } - - public void duplicateModifierForField(ReferenceBinding type, FieldDeclaration fieldDecl) { - /* - * to highlight modifiers use: this.handle( new Problem( DuplicateModifierForField, new String[] {fieldDecl.name()}, - * fieldDecl.modifiers.sourceStart, fieldDecl.modifiers.sourceEnd)); - */ - String[] arguments = new String[] { fieldDecl.name() }; - this.handle(IProblem.DuplicateModifierForField, arguments, arguments, fieldDecl.sourceStart, fieldDecl.sourceEnd); - } - - public void duplicateModifierForMethod(ReferenceBinding type, AbstractMethodDeclaration methodDecl) { - this.handle(IProblem.DuplicateModifierForMethod, - new String[] { new String(type.sourceName()), new String(methodDecl.selector) }, new String[] { - new String(type.shortReadableName()), - new String(methodDecl.selector) }, methodDecl.sourceStart, methodDecl.sourceEnd); - } - - public void duplicateModifierForType(SourceTypeBinding type) { - String[] arguments = new String[] { new String(type.sourceName()) }; - this.handle(IProblem.DuplicateModifierForType, arguments, arguments, type.sourceStart(), type.sourceEnd()); - } - - public void duplicateModifierForVariable(LocalDeclaration localDecl, boolean complainForArgument) { - String[] arguments = new String[] { localDecl.name() }; - this.handle(complainForArgument ? IProblem.DuplicateModifierForArgument : IProblem.DuplicateModifierForVariable, arguments, - arguments, localDecl.sourceStart, localDecl.sourceEnd); - } - - public void duplicateNestedType(TypeDeclaration typeDecl) { - String[] arguments = new String[] { new String(typeDecl.name) }; - this.handle(IProblem.DuplicateNestedType, arguments, arguments, typeDecl.sourceStart, typeDecl.sourceEnd); - } - - public void duplicateSuperinterface(SourceTypeBinding type, TypeDeclaration typeDecl, ReferenceBinding superType) { - this.handle(IProblem.DuplicateSuperInterface, new String[] { - new String(superType.readableName()), - new String(type.sourceName()) }, new String[] { new String(superType.shortReadableName()), new String(type.sourceName()) }, - typeDecl.sourceStart, typeDecl.sourceEnd); - } - - public void duplicateTypes(CompilationUnitDeclaration compUnitDecl, TypeDeclaration typeDecl) { - String[] arguments = new String[] { new String(compUnitDecl.getFileName()), new String(typeDecl.name) }; - this.referenceContext = typeDecl; // report the problem against the - // type not the entire compilation - // unit - this.handle(IProblem.DuplicateTypes, arguments, arguments, typeDecl.sourceStart, typeDecl.sourceEnd, - compUnitDecl.compilationResult); - } - - public void errorNoMethodFor(MessageSend messageSend, TypeBinding recType, TypeBinding[] params) { - StringBuffer buffer = new StringBuffer(); - StringBuffer shortBuffer = new StringBuffer(); - for (int i = 0, length = params.length; i < length; i++) { - if (i != 0) { - buffer.append(", "); //$NON-NLS-1$ - shortBuffer.append(", "); //$NON-NLS-1$ - } - buffer.append(new String(params[i].readableName())); - shortBuffer.append(new String(params[i].shortReadableName())); - } - this.handle(recType.isArrayType() ? IProblem.NoMessageSendOnArrayType : IProblem.NoMessageSendOnBaseType, new String[] { - new String(recType.readableName()), - new String(messageSend.selector), - buffer.toString() }, new String[] { - new String(recType.shortReadableName()), - new String(messageSend.selector), - shortBuffer.toString() }, messageSend.sourceStart, messageSend.sourceEnd); - } - - public void errorThisSuperInStatic(ASTNode reference) { - String[] arguments = new String[] { reference.isSuper() ? "super" : "this" }; //$NON-NLS-2$ //$NON-NLS-1$ - this.handle(IProblem.ThisInStaticContext, arguments, arguments, reference.sourceStart, reference.sourceEnd); - } - - public void exceptionTypeProblem(SourceTypeBinding type, AbstractMethodDeclaration methodDecl, TypeReference exceptionType, - TypeBinding expectedType) { - int problemId = expectedType.problemId(); - int id; - switch (problemId) { - case NotFound: - // 1 - id = IProblem.ExceptionTypeNotFound; - break; - case NotVisible: - // 2 - id = IProblem.ExceptionTypeNotVisible; - break; - case Ambiguous: - // 3 - id = IProblem.ExceptionTypeAmbiguous; - break; - case InternalNameProvided: - // 4 - id = IProblem.ExceptionTypeInternalNameProvided; - break; - case InheritedNameHidesEnclosingName: - // 5 - id = IProblem.ExceptionTypeInheritedNameHidesEnclosingName; - break; - case NoError: - // 0 - default: - needImplementation(); // want to fail to see why we were - // here... - return; - } - this.handle(id, new String[] { new String(methodDecl.selector), new String(expectedType.readableName()) }, new String[] { - new String(methodDecl.selector), - new String(expectedType.shortReadableName()) }, exceptionType.sourceStart, exceptionType.sourceEnd); - } - - public void expressionShouldBeAVariable(Expression expression) { - this.handle(IProblem.ExpressionShouldBeAVariable, NoArgument, NoArgument, expression.sourceStart, expression.sourceEnd); - } - - public void fieldsOrThisBeforeConstructorInvocation(ThisReference reference) { - this.handle(IProblem.ThisSuperDuringConstructorInvocation, NoArgument, NoArgument, reference.sourceStart, reference.sourceEnd); - } - - public void fieldTypeProblem(SourceTypeBinding type, FieldDeclaration fieldDecl, TypeBinding expectedType) { - int problemId = expectedType.problemId(); - int id; - switch (problemId) { - case NotFound: - // 1 - id = IProblem.FieldTypeNotFound; - break; - case NotVisible: - // 2 - id = IProblem.FieldTypeNotVisible; - break; - case Ambiguous: - // 3 - id = IProblem.FieldTypeAmbiguous; - break; - case InternalNameProvided: - // 4 - id = IProblem.FieldTypeInternalNameProvided; - break; - case InheritedNameHidesEnclosingName: - // 5 - id = IProblem.FieldTypeInheritedNameHidesEnclosingName; - break; - case NoError: - // 0 - default: - needImplementation(); // want to fail to see why we were - // here... - return; - } - this.handle(id, new String[] { fieldDecl.name(), new String(type.sourceName()), new String(expectedType.readableName()) }, - new String[] { fieldDecl.name(), new String(type.sourceName()), new String(expectedType.shortReadableName()) }, - fieldDecl.type.sourceStart, fieldDecl.type.sourceEnd); - } - - public void finalMethodCannotBeOverridden(MethodBinding currentMethod, MethodBinding inheritedMethod) { - this.handle( - // Cannot override the final method from %1 - // 8.4.3.3 - Final methods cannot be overridden or hidden. - IProblem.FinalMethodCannotBeOverridden, new String[] { new String(inheritedMethod.declaringClass.readableName()) }, - new String[] { new String(inheritedMethod.declaringClass.shortReadableName()) }, currentMethod.sourceStart(), currentMethod - .sourceEnd()); - } - - public void forwardReference(Reference reference, int indexInQualification, TypeBinding type) { - this.handle(IProblem.ReferenceToForwardField, NoArgument, NoArgument, reference.sourceStart, reference.sourceEnd); - } - - // use this private API when the compilation unit result can be found - // through the - // reference context. Otherwise, use the other API taking a problem and a - // compilation result - // as arguments - private void handle(int problemId, String[] problemArguments, String[] messageArguments, int problemStartPosition, - int problemEndPosition) { - this.handle(problemId, problemArguments, messageArguments, problemStartPosition, problemEndPosition, referenceContext, - referenceContext == null ? null : referenceContext.compilationResult()); - referenceContext = null; - } - - // use this private API when the compilation unit result can be found - // through the - // reference context. Otherwise, use the other API taking a problem and a - // compilation result - // as arguments - private void handle(int problemId, String[] problemArguments, String[] messageArguments, int severity, int problemStartPosition, - int problemEndPosition) { - this.handle(problemId, problemArguments, messageArguments, severity, problemStartPosition, problemEndPosition, - referenceContext, referenceContext == null ? null : referenceContext.compilationResult()); - referenceContext = null; - } - - // use this private API when the compilation unit result cannot be found - // through the - // reference context. - private void handle(int problemId, String[] problemArguments, String[] messageArguments, int problemStartPosition, - int problemEndPosition, CompilationResult unitResult) { - this.handle(problemId, problemArguments, messageArguments, problemStartPosition, problemEndPosition, referenceContext, - unitResult); - referenceContext = null; - } - - public void hidingEnclosingType(TypeDeclaration typeDecl) { - String[] arguments = new String[] { new String(typeDecl.name) }; - this.handle(IProblem.HidingEnclosingType, arguments, arguments, typeDecl.sourceStart, typeDecl.sourceEnd); - } - - public void hierarchyCircularity(SourceTypeBinding sourceType, ReferenceBinding superType, TypeReference reference) { - int start = 0; - int end = 0; - String typeName = ""; //$NON-NLS-1$ - String shortTypeName = ""; //$NON-NLS-1$ - if (reference == null) { // can only happen when java.lang.Object is - // busted - start = sourceType.sourceStart(); - end = sourceType.sourceEnd(); - typeName = new String(superType.readableName()); - shortTypeName = new String(superType.sourceName()); - } else { - start = reference.sourceStart; - end = reference.sourceEnd; - char[][] qName = reference.getTypeName(); - typeName = CharOperation.toString(qName); - shortTypeName = new String(qName[qName.length - 1]); - } - if (sourceType == superType) - this.handle(IProblem.HierarchyCircularitySelfReference, new String[] { new String(sourceType.sourceName()), typeName }, - new String[] { new String(sourceType.sourceName()), shortTypeName }, start, end); - else - this.handle(IProblem.HierarchyCircularity, new String[] { new String(sourceType.sourceName()), typeName }, new String[] { - new String(sourceType.sourceName()), - shortTypeName }, start, end); - } - - public void hierarchyHasProblems(SourceTypeBinding type) { - String[] arguments = new String[] { new String(type.sourceName()) }; - this.handle(IProblem.HierarchyHasProblems, arguments, arguments, type.sourceStart(), type.sourceEnd()); - } - - public void illegalAbstractModifierCombinationForMethod(ReferenceBinding type, AbstractMethodDeclaration methodDecl) { - String[] arguments = new String[] { new String(type.sourceName()), new String(methodDecl.selector) }; - this.handle(IProblem.IllegalAbstractModifierCombinationForMethod, arguments, arguments, methodDecl.sourceStart, - methodDecl.sourceEnd); - } - - public void illegalModifierCombinationFinalAbstractForClass(SourceTypeBinding type) { - String[] arguments = new String[] { new String(type.sourceName()) }; - this.handle(IProblem.IllegalModifierCombinationFinalAbstractForClass, arguments, arguments, type.sourceStart(), type - .sourceEnd()); - } - - public void illegalModifierCombinationFinalVolatileForField(ReferenceBinding type, FieldDeclaration fieldDecl) { - String[] arguments = new String[] { fieldDecl.name() }; - this.handle(IProblem.IllegalModifierCombinationFinalVolatileForField, arguments, arguments, fieldDecl.sourceStart, - fieldDecl.sourceEnd); - } - - public void illegalModifierForClass(SourceTypeBinding type) { - String[] arguments = new String[] { new String(type.sourceName()) }; - this.handle(IProblem.IllegalModifierForClass, arguments, arguments, type.sourceStart(), type.sourceEnd()); - } - - public void illegalModifierForField(ReferenceBinding type, FieldDeclaration fieldDecl) { - String[] arguments = new String[] { fieldDecl.name() }; - this.handle(IProblem.IllegalModifierForField, arguments, arguments, fieldDecl.sourceStart, fieldDecl.sourceEnd); - } - - public void illegalModifierForInterface(SourceTypeBinding type) { - String[] arguments = new String[] { new String(type.sourceName()) }; - this.handle(IProblem.IllegalModifierForInterface, arguments, arguments, type.sourceStart(), type.sourceEnd()); - } - - public void illegalModifierForInterfaceField(ReferenceBinding type, FieldDeclaration fieldDecl) { - String[] arguments = new String[] { fieldDecl.name() }; - this.handle(IProblem.IllegalModifierForInterfaceField, arguments, arguments, fieldDecl.sourceStart, fieldDecl.sourceEnd); - } - - public void illegalModifierForInterfaceMethod(ReferenceBinding type, AbstractMethodDeclaration methodDecl) { - String[] arguments = new String[] { new String(type.sourceName()), new String(methodDecl.selector) }; - this.handle(IProblem.IllegalModifierForInterfaceMethod, arguments, arguments, methodDecl.sourceStart, methodDecl.sourceEnd); - } - - public void illegalModifierForLocalClass(SourceTypeBinding type) { - String[] arguments = new String[] { new String(type.sourceName()) }; - this.handle(IProblem.IllegalModifierForLocalClass, arguments, arguments, type.sourceStart(), type.sourceEnd()); - } - - public void illegalModifierForMemberClass(SourceTypeBinding type) { - String[] arguments = new String[] { new String(type.sourceName()) }; - this.handle(IProblem.IllegalModifierForMemberClass, arguments, arguments, type.sourceStart(), type.sourceEnd()); - } - - public void illegalModifierForMemberInterface(SourceTypeBinding type) { - String[] arguments = new String[] { new String(type.sourceName()) }; - this.handle(IProblem.IllegalModifierForMemberInterface, arguments, arguments, type.sourceStart(), type.sourceEnd()); - } - - public void illegalModifierForMethod(ReferenceBinding type, AbstractMethodDeclaration methodDecl) { - String[] arguments = new String[] { new String(type.sourceName()), new String(methodDecl.selector) }; - this.handle(IProblem.IllegalModifierForMethod, arguments, arguments, methodDecl.sourceStart, methodDecl.sourceEnd); - } - - public void illegalModifierForVariable(LocalDeclaration localDecl, boolean complainAsArgument) { - String[] arguments = new String[] { localDecl.name() }; - this.handle(complainAsArgument ? IProblem.IllegalModifierForArgument : IProblem.IllegalModifierForVariable, arguments, - arguments, localDecl.sourceStart, localDecl.sourceEnd); - } - - public void illegalPrimitiveOrArrayTypeForEnclosingInstance(TypeBinding enclosingType, ASTNode location) { - this.handle(IProblem.IllegalPrimitiveOrArrayTypeForEnclosingInstance, - new String[] { new String(enclosingType.readableName()) }, new String[] { new String(enclosingType.shortReadableName()) }, - location.sourceStart, location.sourceEnd); - } - - public void illegalStaticModifierForMemberType(SourceTypeBinding type) { - String[] arguments = new String[] { new String(type.sourceName()) }; - this.handle(IProblem.IllegalStaticModifierForMemberType, arguments, arguments, type.sourceStart(), type.sourceEnd()); - } - - public void illegalVisibilityModifierCombinationForField(ReferenceBinding type, FieldDeclaration fieldDecl) { - String[] arguments = new String[] { new String(fieldDecl.name()) }; - this.handle(IProblem.IllegalVisibilityModifierCombinationForField, arguments, arguments, fieldDecl.sourceStart, - fieldDecl.sourceEnd); - } - - public void illegalVisibilityModifierCombinationForMemberType(SourceTypeBinding type) { - String[] arguments = new String[] { new String(type.sourceName()) }; - this.handle(IProblem.IllegalVisibilityModifierCombinationForMemberType, arguments, arguments, type.sourceStart(), type - .sourceEnd()); - } - - public void illegalVisibilityModifierCombinationForMethod(ReferenceBinding type, AbstractMethodDeclaration methodDecl) { - String[] arguments = new String[] { new String(type.sourceName()), new String(methodDecl.selector) }; - this.handle(IProblem.IllegalVisibilityModifierCombinationForMethod, arguments, arguments, methodDecl.sourceStart, - methodDecl.sourceEnd); - } - - public void illegalVisibilityModifierForInterfaceMemberType(SourceTypeBinding type) { - String[] arguments = new String[] { new String(type.sourceName()) }; - this.handle(IProblem.IllegalVisibilityModifierForInterfaceMemberType, arguments, arguments, type.sourceStart(), type - .sourceEnd()); - } - - public void illegalVoidExpression(ASTNode location) { - this.handle(IProblem.InvalidVoidExpression, NoArgument, NoArgument, location.sourceStart, location.sourceEnd); - } - - // public void importProblem(ImportReference importRef, Binding expectedImport) { - // int problemId = expectedImport.problemId(); - // int id; - // switch (problemId) { - // case NotFound : - // // 1 - // id = IProblem.ImportNotFound; - // break; - // case NotVisible : - // // 2 - // id = IProblem.ImportNotVisible; - // break; - // case Ambiguous : - // // 3 - // id = IProblem.ImportAmbiguous; - // break; - // case InternalNameProvided : - // // 4 - // id = IProblem.ImportInternalNameProvided; - // break; - // case InheritedNameHidesEnclosingName : - // // 5 - // id = IProblem.ImportInheritedNameHidesEnclosingName; - // break; - // case NoError : - // // 0 - // default : - // needImplementation(); // want to fail to see why we were - // // here... - // return; - // } - // String argument; - // if (expectedImport instanceof ProblemReferenceBinding) { - // argument = CharOperation - // .toString(((ProblemReferenceBinding) expectedImport).compoundName); - // } else { - // argument = CharOperation.toString(importRef.tokens); - // } - // String[] arguments = new String[]{argument}; - // this.handle(id, arguments, arguments, importRef.sourceStart, - // importRef.sourceEnd); - // } - public void incompatibleExceptionInThrowsClause(SourceTypeBinding type, MethodBinding currentMethod, - MethodBinding inheritedMethod, ReferenceBinding exceptionType) { - if (type == currentMethod.declaringClass) { - int id; - if (currentMethod.declaringClass.isInterface() && !inheritedMethod.isPublic()) { // interface inheriting - // Object protected - // method - id = IProblem.IncompatibleExceptionInThrowsClauseForNonInheritedInterfaceMethod; - } else { - id = IProblem.IncompatibleExceptionInThrowsClause; - } - this - .handle( - // Exception %1 is not compatible with throws - // clause in %2 - // 9.4.4 - The type of exception in the throws - // clause is incompatible. - id, new String[] { - new String(exceptionType.sourceName()), - new String(CharOperation.concat(inheritedMethod.declaringClass.readableName(), inheritedMethod.readableName(), - '.')) }, new String[] { - new String(exceptionType.sourceName()), - new String(CharOperation.concat(inheritedMethod.declaringClass.shortReadableName(), inheritedMethod - .shortReadableName(), '.')) }, currentMethod.sourceStart(), currentMethod.sourceEnd()); - } else - this - .handle( - // Exception %1 in throws clause of %2 is not - // compatible with %3 - // 9.4.4 - The type of exception in the throws - // clause is incompatible. - IProblem.IncompatibleExceptionInInheritedMethodThrowsClause, new String[] { - new String(exceptionType.sourceName()), - new String(CharOperation.concat(currentMethod.declaringClass.sourceName(), currentMethod.readableName(), '.')), - new String(CharOperation.concat(inheritedMethod.declaringClass.readableName(), inheritedMethod.readableName(), - '.')) }, new String[] { - new String(exceptionType.sourceName()), - new String(CharOperation - .concat(currentMethod.declaringClass.sourceName(), currentMethod.shortReadableName(), '.')), - new String(CharOperation.concat(inheritedMethod.declaringClass.shortReadableName(), inheritedMethod - .shortReadableName(), '.')) }, type.sourceStart(), type.sourceEnd()); - } - - public void incompatibleReturnType(MethodBinding currentMethod, MethodBinding inheritedMethod) { - StringBuffer methodSignature = new StringBuffer(); - methodSignature.append(inheritedMethod.declaringClass.readableName()).append('.').append(inheritedMethod.readableName()); - StringBuffer shortSignature = new StringBuffer(); - shortSignature.append(inheritedMethod.declaringClass.shortReadableName()).append('.').append( - inheritedMethod.shortReadableName()); - int id; - if (currentMethod.declaringClass.isInterface() && !inheritedMethod.isPublic()) { // interface inheriting - // Object protected method - id = IProblem.IncompatibleReturnTypeForNonInheritedInterfaceMethod; - } else { - id = IProblem.IncompatibleReturnType; - } - this.handle(id, new String[] { methodSignature.toString() }, new String[] { shortSignature.toString() }, currentMethod - .sourceStart(), currentMethod.sourceEnd()); - } - - public void incorrectLocationForEmptyDimension(ArrayAllocationExpression expression, int index) { - this.handle(IProblem.IllegalDimension, NoArgument, NoArgument, expression.dimensions[index + 1].sourceStart, - expression.dimensions[index + 1].sourceEnd); - } - - public void incorrectSwitchType(Expression expression, TypeBinding testType) { - this.handle(IProblem.IncorrectSwitchType, new String[] { new String(testType.readableName()) }, new String[] { new String( - testType.shortReadableName()) }, expression.sourceStart, expression.sourceEnd); - } - - public void inheritedMethodReducesVisibility(SourceTypeBinding type, MethodBinding concreteMethod, MethodBinding[] abstractMethods) { - StringBuffer concreteSignature = new StringBuffer(); - concreteSignature.append(concreteMethod.declaringClass.readableName()).append('.').append(concreteMethod.readableName()); - StringBuffer shortSignature = new StringBuffer(); - shortSignature.append(concreteMethod.declaringClass.shortReadableName()).append('.').append(concreteMethod.shortReadableName()); - this.handle( - // The inherited method %1 cannot hide the public abstract method in %2 - IProblem.InheritedMethodReducesVisibility, new String[] { - new String(concreteSignature.toString()), - new String(abstractMethods[0].declaringClass.readableName()) }, new String[] { - new String(shortSignature.toString()), - new String(abstractMethods[0].declaringClass.shortReadableName()) }, type.sourceStart(), type.sourceEnd()); - } - - public void inheritedMethodsHaveIncompatibleReturnTypes(SourceTypeBinding type, MethodBinding[] inheritedMethods, int length) { - StringBuffer methodSignatures = new StringBuffer(); - StringBuffer shortSignatures = new StringBuffer(); - for (int i = length; --i >= 0;) { - methodSignatures.append(inheritedMethods[i].declaringClass.readableName()).append('.').append( - inheritedMethods[i].readableName()); - shortSignatures.append(inheritedMethods[i].declaringClass.shortReadableName()).append('.').append( - inheritedMethods[i].shortReadableName()); - if (i != 0) { - methodSignatures.append(", "); //$NON-NLS-1$ - shortSignatures.append(", "); //$NON-NLS-1$ - } - } - this.handle( - // Return type is incompatible with %1 - // 9.4.2 - The return type from the method is incompatible with - // the declaration. - IProblem.IncompatibleReturnType, new String[] { methodSignatures.toString() }, new String[] { shortSignatures.toString() }, - type.sourceStart(), type.sourceEnd()); - } - - public void initializerMustCompleteNormally(FieldDeclaration fieldDecl) { - this.handle(IProblem.InitializerMustCompleteNormally, NoArgument, NoArgument, fieldDecl.sourceStart, fieldDecl.sourceEnd); - } - - public void innerTypesCannotDeclareStaticInitializers(ReferenceBinding innerType, ASTNode location) { - this.handle(IProblem.CannotDefineStaticInitializerInLocalType, new String[] { new String(innerType.readableName()) }, - new String[] { new String(innerType.shortReadableName()) }, location.sourceStart, location.sourceEnd); - } - - public void interfaceCannotHaveConstructors(ConstructorDeclaration constructor) { - this.handle(IProblem.InterfaceCannotHaveConstructors, NoArgument, NoArgument, constructor.sourceStart, constructor.sourceEnd, - constructor, constructor.compilationResult()); - } - - public void interfaceCannotHaveInitializers(SourceTypeBinding type, FieldDeclaration fieldDecl) { - String[] arguments = new String[] { new String(type.sourceName()) }; - this.handle(IProblem.InterfaceCannotHaveInitializers, arguments, arguments, fieldDecl.sourceStart, fieldDecl.sourceEnd); - } - - public void invalidBreak(ASTNode location) { - this.handle(IProblem.InvalidBreak, NoArgument, NoArgument, location.sourceStart, location.sourceEnd); - } - - public void invalidConstructor(Statement statement, MethodBinding targetConstructor) { - boolean insideDefaultConstructor = (referenceContext instanceof ConstructorDeclaration) - && ((ConstructorDeclaration) referenceContext).isDefaultConstructor(); - boolean insideImplicitConstructorCall = (statement instanceof ExplicitConstructorCall) - && (((ExplicitConstructorCall) statement).accessMode == ExplicitConstructorCall.ImplicitSuper); - int flag = IProblem.UndefinedConstructor; //default... - switch (targetConstructor.problemId()) { - case NotFound: - if (insideDefaultConstructor) { - flag = IProblem.UndefinedConstructorInDefaultConstructor; - } else if (insideImplicitConstructorCall) { - flag = IProblem.UndefinedConstructorInImplicitConstructorCall; - } else { - flag = IProblem.UndefinedConstructor; - } - break; - case NotVisible: - if (insideDefaultConstructor) { - flag = IProblem.NotVisibleConstructorInDefaultConstructor; - } else if (insideImplicitConstructorCall) { - flag = IProblem.NotVisibleConstructorInImplicitConstructorCall; - } else { - flag = IProblem.NotVisibleConstructor; - } - break; - case Ambiguous: - if (insideDefaultConstructor) { - flag = IProblem.AmbiguousConstructorInDefaultConstructor; - } else if (insideImplicitConstructorCall) { - flag = IProblem.AmbiguousConstructorInImplicitConstructorCall; - } else { - flag = IProblem.AmbiguousConstructor; - } - break; - case NoError: - // 0 - default: - needImplementation(); // want to fail to see why we were - // here... - break; - } - this.handle(flag, new String[] { - new String(targetConstructor.declaringClass.readableName()), - parametersAsString(targetConstructor) }, new String[] { - new String(targetConstructor.declaringClass.shortReadableName()), - parametersAsShortString(targetConstructor) }, statement.sourceStart, statement.sourceEnd); - } - - public void invalidContinue(ASTNode location) { - this.handle(IProblem.InvalidContinue, NoArgument, NoArgument, location.sourceStart, location.sourceEnd); - } - - public void invalidEnclosingType(Expression expression, TypeBinding type, ReferenceBinding enclosingType) { - if (enclosingType.isAnonymousType()) - enclosingType = enclosingType.superclass(); - int flag = IProblem.UndefinedType; // default - switch (type.problemId()) { - case NotFound: - // 1 - flag = IProblem.UndefinedType; - break; - case NotVisible: - // 2 - flag = IProblem.NotVisibleType; - break; - case Ambiguous: - // 3 - flag = IProblem.AmbiguousType; - break; - case InternalNameProvided: - flag = IProblem.InternalTypeNameProvided; - break; - case NoError: - // 0 - default: - needImplementation(); // want to fail to see why we were - // here... - break; - } - this.handle(flag, new String[] { new String(enclosingType.readableName()) + "." + new String(type.readableName()) }, //$NON-NLS-1$ - new String[] { new String(enclosingType.shortReadableName()) + "." + new String(type.shortReadableName()) }, //$NON-NLS-1$ - expression.sourceStart, expression.sourceEnd); - } - - public void invalidExpressionAsStatement(Expression expression) { - this.handle(IProblem.InvalidExpressionAsStatement, NoArgument, NoArgument, expression.sourceStart, expression.sourceEnd); - } - - public void invalidField(FieldReference fieldRef, TypeBinding searchedType) { - int severity = Error; - int flag = IProblem.UndefinedField; - FieldBinding field = fieldRef.binding; - switch (field.problemId()) { - case NotFound: - flag = IProblem.UndefinedField; - /* - * also need to check that the searchedType is the receiver type if (searchedType.isHierarchyInconsistent()) severity = - * SecondaryError; - */ - break; - case NotVisible: - flag = IProblem.NotVisibleField; - break; - case Ambiguous: - flag = IProblem.AmbiguousField; - break; - case NonStaticReferenceInStaticContext: - flag = IProblem.NonStaticFieldFromStaticInvocation; - break; - case NonStaticReferenceInConstructorInvocation: - flag = IProblem.InstanceFieldDuringConstructorInvocation; - break; - case InheritedNameHidesEnclosingName: - flag = IProblem.InheritedFieldHidesEnclosingName; - break; - case ReceiverTypeNotVisible: - this.handle(IProblem.NotVisibleType, new String[] { new String(searchedType.leafComponentType().readableName()) }, - new String[] { new String(searchedType.leafComponentType().shortReadableName()) }, fieldRef.receiver.sourceStart, - fieldRef.receiver.sourceEnd); - return; - case NoError: - // 0 - default: - needImplementation(); // want to fail to see why we were - // here... - break; - } - String[] arguments = new String[] { new String(field.readableName()) }; - this.handle(flag, arguments, arguments, severity, fieldRef.sourceStart, fieldRef.sourceEnd); - } - - public void invalidField(NameReference nameRef, FieldBinding field) { - int flag = IProblem.UndefinedField; - switch (field.problemId()) { - case NotFound: - flag = IProblem.UndefinedField; - break; - case NotVisible: - flag = IProblem.NotVisibleField; - break; - case Ambiguous: - flag = IProblem.AmbiguousField; - break; - case NonStaticReferenceInStaticContext: - flag = IProblem.NonStaticFieldFromStaticInvocation; - break; - case NonStaticReferenceInConstructorInvocation: - flag = IProblem.InstanceFieldDuringConstructorInvocation; - break; - case InheritedNameHidesEnclosingName: - flag = IProblem.InheritedFieldHidesEnclosingName; - break; - case ReceiverTypeNotVisible: - this.handle(IProblem.NotVisibleType, new String[] { new String(field.declaringClass.leafComponentType().readableName()) }, - new String[] { new String(field.declaringClass.leafComponentType().shortReadableName()) }, nameRef.sourceStart, - nameRef.sourceEnd); - return; - case NoError: - // 0 - default: - needImplementation(); // want to fail to see why we were - // here... - break; - } - String[] arguments = new String[] { new String(field.readableName()) }; - this.handle(flag, arguments, arguments, nameRef.sourceStart, nameRef.sourceEnd); - } - - public void invalidField(QualifiedNameReference nameRef, FieldBinding field, int index, TypeBinding searchedType) { - //the resolution of the index-th field of qname failed - //qname.otherBindings[index] is the binding that has produced the - // error - //The different targetted errors should be : - //UndefinedField - //NotVisibleField - //AmbiguousField - if (searchedType.isBaseType()) { - this.handle(IProblem.NoFieldOnBaseType, new String[] { - new String(searchedType.readableName()), - CharOperation.toString(CharOperation.subarray(nameRef.tokens, 0, index)), - new String(nameRef.tokens[index]) }, new String[] { - new String(searchedType.sourceName()), - CharOperation.toString(CharOperation.subarray(nameRef.tokens, 0, index)), - new String(nameRef.tokens[index]) }, nameRef.sourceStart, nameRef.sourceEnd); - return; - } - int flag = IProblem.UndefinedField; - switch (field.problemId()) { - case NotFound: - flag = IProblem.UndefinedField; - /* - * also need to check that the searchedType is the receiver type if (searchedType.isHierarchyInconsistent()) severity = - * SecondaryError; - */ - break; - case NotVisible: - flag = IProblem.NotVisibleField; - break; - case Ambiguous: - flag = IProblem.AmbiguousField; - break; - case NonStaticReferenceInStaticContext: - flag = IProblem.NonStaticFieldFromStaticInvocation; - break; - case NonStaticReferenceInConstructorInvocation: - flag = IProblem.InstanceFieldDuringConstructorInvocation; - break; - case InheritedNameHidesEnclosingName: - flag = IProblem.InheritedFieldHidesEnclosingName; - break; - case ReceiverTypeNotVisible: - this - .handle(IProblem.NotVisibleType, new String[] { new String(searchedType.leafComponentType().readableName()) }, - new String[] { new String(searchedType.leafComponentType().shortReadableName()) }, nameRef.sourceStart, - nameRef.sourceEnd); - return; - case NoError: - // 0 - default: - needImplementation(); // want to fail to see why we were - // here... - break; - } - String[] arguments = new String[] { CharOperation.toString(CharOperation.subarray(nameRef.tokens, 0, index + 1)) }; - this.handle(flag, arguments, arguments, nameRef.sourceStart, nameRef.sourceEnd); - } - - public void invalidMethod(MessageSend messageSend, MethodBinding method) { - // CODE should be UPDATED according to error coding in the different - // method binding errors - // The different targetted errors should be : - // UndefinedMethod - // NotVisibleMethod - // AmbiguousMethod - // InheritedNameHidesEnclosingName - // InstanceMethodDuringConstructorInvocation - // StaticMethodRequested - int flag = IProblem.UndefinedMethod; //default... - switch (method.problemId()) { - case NotFound: - flag = IProblem.UndefinedMethod; - break; - case NotVisible: - flag = IProblem.NotVisibleMethod; - break; - case Ambiguous: - flag = IProblem.AmbiguousMethod; - break; - case InheritedNameHidesEnclosingName: - flag = IProblem.InheritedMethodHidesEnclosingName; - break; - case NonStaticReferenceInConstructorInvocation: - flag = IProblem.InstanceMethodDuringConstructorInvocation; - break; - case NonStaticReferenceInStaticContext: - flag = IProblem.StaticMethodRequested; - break; - case ReceiverTypeNotVisible: - this.handle(IProblem.NotVisibleType, new String[] { new String(method.declaringClass.leafComponentType().readableName()) }, - new String[] { new String(method.declaringClass.leafComponentType().shortReadableName()) }, - messageSend.receiver.sourceStart, messageSend.receiver.sourceEnd); - return; - case NoError: - // 0 - default: - needImplementation(); // want to fail to see why we were - // here... - break; - } - if (flag == IProblem.UndefinedMethod) { - ProblemMethodBinding problemMethod = (ProblemMethodBinding) method; - if (problemMethod.closestMatch != null) { - String closestParameterTypeNames = parametersAsString(problemMethod.closestMatch); - String parameterTypeNames = parametersAsString(method); - String closestParameterTypeShortNames = parametersAsShortString(problemMethod.closestMatch); - String parameterTypeShortNames = parametersAsShortString(method); - if (closestParameterTypeShortNames.equals(parameterTypeShortNames)) { - closestParameterTypeShortNames = closestParameterTypeNames; - parameterTypeShortNames = parameterTypeNames; - } - this.handle(IProblem.ParameterMismatch, new String[] { - new String(problemMethod.closestMatch.declaringClass.readableName()), - new String(problemMethod.closestMatch.selector), - closestParameterTypeNames, - parameterTypeNames }, new String[] { - new String(problemMethod.closestMatch.declaringClass.shortReadableName()), - new String(problemMethod.closestMatch.selector), - closestParameterTypeShortNames, - parameterTypeShortNames }, (int) (messageSend.nameSourcePosition >>> 32), (int) messageSend.nameSourcePosition); - return; - } - } - this.handle(flag, new String[] { - new String(method.declaringClass.readableName()), - new String(method.selector), - parametersAsString(method) }, new String[] { - new String(method.declaringClass.shortReadableName()), - new String(method.selector), - parametersAsShortString(method) }, (int) (messageSend.nameSourcePosition >>> 32), (int) messageSend.nameSourcePosition); - } - - public void invalidNullToSynchronize(Expression expression) { - this.handle(IProblem.InvalidNullToSynchronized, NoArgument, NoArgument, expression.sourceStart, expression.sourceEnd); - } - - public void invalidOperator(BinaryExpression expression, TypeBinding leftType, TypeBinding rightType) { - String leftName = new String(leftType.readableName()); - String rightName = new String(rightType.readableName()); - String leftShortName = new String(leftType.shortReadableName()); - String rightShortName = new String(rightType.shortReadableName()); - if (leftShortName.equals(rightShortName)) { - leftShortName = leftName; - rightShortName = rightName; - } - this.handle(IProblem.InvalidOperator, new String[] { expression.operatorToString(), leftName + ", " + rightName }, //$NON-NLS-1$ - new String[] { expression.operatorToString(), leftShortName + ", " + rightShortName }, //$NON-NLS-1$ - expression.sourceStart, expression.sourceEnd); - } - - public void invalidOperator(CompoundAssignment assign, TypeBinding leftType, TypeBinding rightType) { - String leftName = new String(leftType.readableName()); - String rightName = new String(rightType.readableName()); - String leftShortName = new String(leftType.shortReadableName()); - String rightShortName = new String(rightType.shortReadableName()); - if (leftShortName.equals(rightShortName)) { - leftShortName = leftName; - rightShortName = rightName; - } - this.handle(IProblem.InvalidOperator, new String[] { assign.operatorToString(), leftName + ", " + rightName }, //$NON-NLS-1$ - new String[] { assign.operatorToString(), leftShortName + ", " + rightShortName }, //$NON-NLS-1$ - assign.sourceStart, assign.sourceEnd); - } - - public void invalidOperator(UnaryExpression expression, TypeBinding type) { - this.handle(IProblem.InvalidOperator, new String[] { expression.operatorToString(), new String(type.readableName()) }, - new String[] { expression.operatorToString(), new String(type.shortReadableName()) }, expression.sourceStart, - expression.sourceEnd); - } - - public void invalidParenthesizedExpression(ASTNode reference) { - this.handle(IProblem.InvalidParenthesizedExpression, NoArgument, NoArgument, reference.sourceStart, reference.sourceEnd); - } - - public void invalidSuperclass(SourceTypeBinding type, TypeReference superclassRef, ReferenceBinding expectedType) { - int problemId = expectedType.problemId(); - int id; - switch (problemId) { - case NotFound: - // 1 - id = IProblem.SuperclassNotFound; - break; - case NotVisible: - // 2 - id = IProblem.SuperclassNotVisible; - break; - case Ambiguous: - // 3 - id = IProblem.SuperclassAmbiguous; - break; - case InternalNameProvided: - // 4 - id = IProblem.SuperclassInternalNameProvided; - break; - case InheritedNameHidesEnclosingName: - // 5 - id = IProblem.SuperclassInheritedNameHidesEnclosingName; - break; - case NoError: - // 0 - default: - needImplementation(); // want to fail to see why we were - // here... - return; - } - this.handle(id, new String[] { new String(expectedType.readableName()), new String(type.sourceName()) }, new String[] { - new String(expectedType.shortReadableName()), - new String(type.sourceName()) }, superclassRef.sourceStart, superclassRef.sourceEnd); - } - - public void invalidSuperinterface(SourceTypeBinding type, TypeReference superinterfaceRef, ReferenceBinding expectedType) { - int problemId = expectedType.problemId(); - int id; - switch (problemId) { - case NotFound: - // 1 - id = IProblem.InterfaceNotFound; - break; - case NotVisible: - // 2 - id = IProblem.InterfaceNotVisible; - break; - case Ambiguous: - // 3 - id = IProblem.InterfaceAmbiguous; - break; - case InternalNameProvided: - // 4 - id = IProblem.InterfaceInternalNameProvided; - break; - case InheritedNameHidesEnclosingName: - // 5 - id = IProblem.InterfaceInheritedNameHidesEnclosingName; - break; - case NoError: - // 0 - default: - needImplementation(); // want to fail to see why we were - // here... - return; - } - this.handle(id, new String[] { new String(expectedType.readableName()), new String(type.sourceName()) }, new String[] { - new String(expectedType.shortReadableName()), - new String(type.sourceName()) }, superinterfaceRef.sourceStart, superinterfaceRef.sourceEnd); - } - - public void invalidType(ASTNode location, TypeBinding type) { - int flag = IProblem.UndefinedType; // default - switch (type.problemId()) { - case NotFound: - flag = IProblem.UndefinedType; - break; - case NotVisible: - flag = IProblem.NotVisibleType; - break; - case Ambiguous: - flag = IProblem.AmbiguousType; - break; - case InternalNameProvided: - flag = IProblem.InternalTypeNameProvided; - break; - case InheritedNameHidesEnclosingName: - flag = IProblem.InheritedTypeHidesEnclosingName; - break; - case NoError: - // 0 - default: - needImplementation(); // want to fail to see why we were - // here... - break; - } - this.handle(flag, new String[] { new String(type.readableName()) }, new String[] { new String(type.shortReadableName()) }, - location.sourceStart, location.sourceEnd); - } - - public void invalidTypeReference(Expression expression) { - this.handle(IProblem.InvalidTypeExpression, NoArgument, NoArgument, expression.sourceStart, expression.sourceEnd); - } - - public void invalidTypeToSynchronize(Expression expression, TypeBinding type) { - this.handle(IProblem.InvalidTypeToSynchronized, new String[] { new String(type.readableName()) }, new String[] { new String( - type.shortReadableName()) }, expression.sourceStart, expression.sourceEnd); - } - - public void invalidUnaryExpression(Expression expression) { - this.handle(IProblem.InvalidUnaryExpression, NoArgument, NoArgument, expression.sourceStart, expression.sourceEnd); - } - - public void isClassPathCorrect(char[][] wellKnownTypeName, CompilationUnitDeclaration compUnitDecl) { - referenceContext = compUnitDecl; - String[] arguments = new String[] { CharOperation.toString(wellKnownTypeName) }; - this.handle(IProblem.IsClassPathCorrect, arguments, arguments, AbortCompilation | Error, compUnitDecl == null ? 0 - : compUnitDecl.sourceStart, compUnitDecl == null ? 1 : compUnitDecl.sourceEnd); - } - - public void javadocDuplicatedReturnTag(int sourceStart, int sourceEnd) { - this.handle(IProblem.JavadocDuplicateReturnTag, NoArgument, NoArgument, sourceStart, sourceEnd); - } - - public void javadocDeprecatedField(FieldBinding field, ASTNode location, int modifiers) { - if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers)) { - this.handle(IProblem.JavadocUsingDeprecatedField, new String[] { - new String(field.declaringClass.readableName()), - new String(field.name) }, new String[] { new String(field.declaringClass.shortReadableName()), new String(field.name) }, - location.sourceStart, location.sourceEnd); - } - } - - public void javadocDeprecatedMethod(MethodBinding method, ASTNode location, int modifiers) { - if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers)) { - if (method.isConstructor()) { - this.handle(IProblem.JavadocUsingDeprecatedConstructor, new String[] { - new String(method.declaringClass.readableName()), - parametersAsString(method) }, new String[] { - new String(method.declaringClass.shortReadableName()), - parametersAsShortString(method) }, location.sourceStart, location.sourceEnd); - } else { - this.handle(IProblem.JavadocUsingDeprecatedMethod, new String[] { - new String(method.declaringClass.readableName()), - new String(method.selector), - parametersAsString(method) }, new String[] { - new String(method.declaringClass.shortReadableName()), - new String(method.selector), - parametersAsShortString(method) }, location.sourceStart, location.sourceEnd); - } - } - } - - public void javadocDeprecatedType(TypeBinding type, ASTNode location, int modifiers) { - if (location == null) - return; // 1G828DN - no type ref for synthetic arguments - if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers)) { - this.handle(IProblem.JavadocUsingDeprecatedType, new String[] { new String(type.readableName()) }, new String[] { new String( - type.shortReadableName()) }, location.sourceStart, location.sourceEnd); - } - } - - //public void javadocDuplicatedParamTag(JavadocSingleNameReference param, int modifiers) { - // if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers)) { - // String[] arguments = new String[] {String.valueOf(param.token)}; - // this.handle(IProblem.JavadocDuplicateParamName, arguments, arguments, param.sourceStart, param.sourceEnd); - // } - //} - public void javadocDuplicatedThrowsClassName(TypeReference typeReference, int modifiers) { - if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers)) { - String[] arguments = new String[] { String.valueOf(typeReference.resolvedType.sourceName()) }; - this.handle(IProblem.JavadocDuplicateThrowsClassName, arguments, arguments, typeReference.sourceStart, - typeReference.sourceEnd); - } - } - - public void javadocErrorNoMethodFor(MessageSend messageSend, TypeBinding recType, TypeBinding[] params, int modifiers) { - StringBuffer buffer = new StringBuffer(); - StringBuffer shortBuffer = new StringBuffer(); - for (int i = 0, length = params.length; i < length; i++) { - if (i != 0) { - buffer.append(", "); //$NON-NLS-1$ - shortBuffer.append(", "); //$NON-NLS-1$ - } - buffer.append(new String(params[i].readableName())); - shortBuffer.append(new String(params[i].shortReadableName())); - } - - int id = recType.isArrayType() ? IProblem.JavadocNoMessageSendOnArrayType : IProblem.JavadocNoMessageSendOnBaseType; - if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers)) { - this.handle(id, new String[] { new String(recType.readableName()), new String(messageSend.selector), buffer.toString() }, - new String[] { new String(recType.shortReadableName()), new String(messageSend.selector), shortBuffer.toString() }, - messageSend.sourceStart, messageSend.sourceEnd); - } - } - - public void javadocInvalidConstructor(Statement statement, MethodBinding targetConstructor, int modifiers) { - - if (!javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers)) { - return; - } - // boolean insideDefaultConstructor = - // (this.referenceContext instanceof ConstructorDeclaration) - // && ((ConstructorDeclaration)this.referenceContext).isDefaultConstructor(); - // boolean insideImplicitConstructorCall = - // (statement instanceof ExplicitConstructorCall) - // && (((ExplicitConstructorCall) statement).accessMode == ExplicitConstructorCall.ImplicitSuper); - - int id = IProblem.JavadocUndefinedConstructor; //default... - switch (targetConstructor.problemId()) { - case NotFound: - // if (insideDefaultConstructor){ - // id = IProblem.JavadocUndefinedConstructorInDefaultConstructor; - // } else if (insideImplicitConstructorCall){ - // id = IProblem.JavadocUndefinedConstructorInImplicitConstructorCall; - // } else { - id = IProblem.JavadocUndefinedConstructor; - // } - break; - case NotVisible: - // if (insideDefaultConstructor){ - // id = IProblem.JavadocNotVisibleConstructorInDefaultConstructor; - // } else if (insideImplicitConstructorCall){ - // id = IProblem.JavadocNotVisibleConstructorInImplicitConstructorCall; - // } else { - id = IProblem.JavadocNotVisibleConstructor; - // } - break; - case Ambiguous: - // if (insideDefaultConstructor){ - // id = IProblem.AmbiguousConstructorInDefaultConstructor; - // } else if (insideImplicitConstructorCall){ - // id = IProblem.AmbiguousConstructorInImplicitConstructorCall; - // } else { - id = IProblem.JavadocAmbiguousConstructor; - // } - break; - case NoError: // 0 - default: - needImplementation(); // want to fail to see why we were here... - break; - } - - this.handle(id, new String[] { - new String(targetConstructor.declaringClass.readableName()), - parametersAsString(targetConstructor) }, new String[] { - new String(targetConstructor.declaringClass.shortReadableName()), - parametersAsShortString(targetConstructor) }, statement.sourceStart, statement.sourceEnd); - } - - public void javadocAmbiguousMethodReference(int sourceStart, int sourceEnd, Binding fieldBinding, int modifiers) { - int id = IProblem.JavadocAmbiguousMethodReference; - if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers)) { - String[] arguments = new String[] { new String(fieldBinding.readableName()) }; - handle(id, arguments, arguments, sourceStart, sourceEnd); - } - } - - /* - * Similar implementation than invalidField(FieldReference...) Note that following problem id cannot occur for Javadoc: - - * NonStaticReferenceInStaticContext : - NonStaticReferenceInConstructorInvocation : - ReceiverTypeNotVisible : - */ - public void javadocInvalidField(int sourceStart, int sourceEnd, Binding fieldBinding, TypeBinding searchedType, int modifiers) { - int id = IProblem.JavadocUndefinedField; - switch (fieldBinding.problemId()) { - case NotFound: - id = IProblem.JavadocUndefinedField; - break; - case NotVisible: - id = IProblem.JavadocNotVisibleField; - break; - case Ambiguous: - id = IProblem.JavadocAmbiguousField; - break; - case InheritedNameHidesEnclosingName: - id = IProblem.JavadocInheritedFieldHidesEnclosingName; - break; - case NoError: // 0 - default: - needImplementation(); // want to fail to see why we were here... - break; - } - - if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers)) { - String[] arguments = new String[] { new String(fieldBinding.readableName()) }; - handle(id, arguments, arguments, sourceStart, sourceEnd); - } - } - - /* - * Similar implementation than invalidMethod(MessageSend...) Note that following problem id cannot occur for Javadoc: - - * NonStaticReferenceInStaticContext : - NonStaticReferenceInConstructorInvocation : - ReceiverTypeNotVisible : - */ - public void javadocInvalidMethod(MessageSend messageSend, MethodBinding method, int modifiers) { - if (!javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers)) { - return; - } - int id = IProblem.JavadocUndefinedMethod; //default... - switch (method.problemId()) { - case NotFound: - id = IProblem.JavadocUndefinedMethod; - break; - case NotVisible: - id = IProblem.JavadocNotVisibleMethod; - break; - case Ambiguous: - id = IProblem.JavadocAmbiguousMethod; - break; - case InheritedNameHidesEnclosingName: - id = IProblem.JavadocInheritedMethodHidesEnclosingName; - break; - case NoError: // 0 - default: - needImplementation(); // want to fail to see why we were here... - break; - } - - if (id == IProblem.JavadocUndefinedMethod) { - ProblemMethodBinding problemMethod = (ProblemMethodBinding) method; - if (problemMethod.closestMatch != null) { - String closestParameterTypeNames = parametersAsString(problemMethod.closestMatch); - String parameterTypeNames = parametersAsString(method); - String closestParameterTypeShortNames = parametersAsShortString(problemMethod.closestMatch); - String parameterTypeShortNames = parametersAsShortString(method); - if (closestParameterTypeShortNames.equals(parameterTypeShortNames)) { - closestParameterTypeShortNames = closestParameterTypeNames; - parameterTypeShortNames = parameterTypeNames; - } - this.handle(IProblem.JavadocParameterMismatch, new String[] { - new String(problemMethod.closestMatch.declaringClass.readableName()), - new String(problemMethod.closestMatch.selector), - closestParameterTypeNames, - parameterTypeNames }, new String[] { - new String(problemMethod.closestMatch.declaringClass.shortReadableName()), - new String(problemMethod.closestMatch.selector), - closestParameterTypeShortNames, - parameterTypeShortNames }, (int) (messageSend.nameSourcePosition >>> 32), (int) messageSend.nameSourcePosition); - return; - } - } - - this.handle(id, new String[] { - new String(method.declaringClass.readableName()), - new String(method.selector), - parametersAsString(method) }, new String[] { - new String(method.declaringClass.shortReadableName()), - new String(method.selector), - parametersAsShortString(method) }, (int) (messageSend.nameSourcePosition >>> 32), (int) messageSend.nameSourcePosition); - } - - //public void javadocInvalidParamName(JavadocSingleNameReference param, int modifiers) { - // if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers)) { - // String[] arguments = new String[] {String.valueOf(param.token)}; - // this.handle(IProblem.JavadocInvalidParamName, arguments, arguments, param.sourceStart, param.sourceEnd); - // } - //} - public void javadocInvalidSeeReference(int sourceStart, int sourceEnd) { - this.handle(IProblem.JavadocInvalidSeeReference, NoArgument, NoArgument, sourceStart, sourceEnd); - } - - public void javadocInvalidSeeReferenceArgs(int sourceStart, int sourceEnd) { - this.handle(IProblem.JavadocInvalidSeeArgs, NoArgument, NoArgument, sourceStart, sourceEnd); - } - - public void javadocInvalidSeeUrlReference(int sourceStart, int sourceEnd) { - this.handle(IProblem.JavadocInvalidSeeHref, NoArgument, NoArgument, sourceStart, sourceEnd); - } - - public void javadocInvalidTag(int sourceStart, int sourceEnd) { - this.handle(IProblem.JavadocInvalidTag, NoArgument, NoArgument, sourceStart, sourceEnd); - } - - public void javadocInvalidThrowsClass(int sourceStart, int sourceEnd) { - this.handle(IProblem.JavadocInvalidThrowsClass, NoArgument, NoArgument, sourceStart, sourceEnd); - } - - public void javadocInvalidThrowsClassName(TypeReference typeReference, int modifiers) { - if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers)) { - String[] arguments = new String[] { String.valueOf(typeReference.resolvedType.sourceName()) }; - this.handle(IProblem.JavadocInvalidThrowsClassName, arguments, arguments, typeReference.sourceStart, typeReference.sourceEnd); - } - } - - public void javadocInvalidType(ASTNode location, TypeBinding type, int modifiers) { - if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, modifiers)) { - int id = IProblem.JavadocUndefinedType; // default - switch (type.problemId()) { - case NotFound: - id = IProblem.JavadocUndefinedType; - break; - case NotVisible: - id = IProblem.JavadocNotVisibleType; - break; - case Ambiguous: - id = IProblem.JavadocAmbiguousType; - break; - case InternalNameProvided: - id = IProblem.JavadocInternalTypeNameProvided; - break; - case InheritedNameHidesEnclosingName: - id = IProblem.JavadocInheritedNameHidesEnclosingTypeName; - break; - case NoError: // 0 - default: - needImplementation(); // want to fail to see why we were here... - break; - } - this.handle(id, new String[] { new String(type.readableName()) }, new String[] { new String(type.shortReadableName()) }, - location.sourceStart, location.sourceEnd); - } - } - - public void javadocMalformedSeeReference(int sourceStart, int sourceEnd) { - this.handle(IProblem.JavadocMalformedSeeReference, NoArgument, NoArgument, sourceStart, sourceEnd); - } - - public void javadocMissing(int sourceStart, int sourceEnd, int modifiers) { - boolean overriding = (modifiers & (CompilerModifiers.AccImplementing + CompilerModifiers.AccOverriding)) != 0; - boolean report = (this.options.getSeverity(CompilerOptions.MissingJavadocComments) != ProblemSeverities.Ignore) - && (!overriding || this.options.reportMissingJavadocCommentsOverriding); - if (report) { - String arg = javadocVisibilityArgument(this.options.reportMissingJavadocCommentsVisibility, modifiers); - if (arg != null) { - String[] arguments = new String[] { arg }; - this.handle(IProblem.JavadocMissing, arguments, arguments, sourceStart, sourceEnd); - } - } - } - - public void javadocMissingParamName(int sourceStart, int sourceEnd) { - this.handle(IProblem.JavadocMissingParamName, NoArgument, NoArgument, sourceStart, sourceEnd); - } - - public void javadocMissingParamTag(Argument param, int modifiers) { - boolean overriding = (modifiers & (CompilerModifiers.AccImplementing + CompilerModifiers.AccOverriding)) != 0; - boolean report = (this.options.getSeverity(CompilerOptions.MissingJavadocTags) != ProblemSeverities.Ignore) - && (!overriding || this.options.reportMissingJavadocTagsOverriding); - if (report && javadocVisibility(this.options.reportMissingJavadocTagsVisibility, modifiers)) { - String[] arguments = new String[] { String.valueOf(param.name) }; - this.handle(IProblem.JavadocMissingParamTag, arguments, arguments, param.sourceStart, param.sourceEnd); - } - } - - public void javadocMissingReturnTag(int sourceStart, int sourceEnd, int modifiers) { - boolean overriding = (modifiers & (CompilerModifiers.AccImplementing + CompilerModifiers.AccOverriding)) != 0; - boolean report = (this.options.getSeverity(CompilerOptions.MissingJavadocTags) != ProblemSeverities.Ignore) - && (!overriding || this.options.reportMissingJavadocTagsOverriding); - if (report && javadocVisibility(this.options.reportMissingJavadocTagsVisibility, modifiers)) { - this.handle(IProblem.JavadocMissingReturnTag, NoArgument, NoArgument, sourceStart, sourceEnd); - } - } - - public void javadocMissingSeeReference(int sourceStart, int sourceEnd) { - this.handle(IProblem.JavadocMissingSeeReference, NoArgument, NoArgument, sourceStart, sourceEnd); - } - - public void javadocMissingThrowsClassName(int sourceStart, int sourceEnd) { - this.handle(IProblem.JavadocMissingThrowsClassName, NoArgument, NoArgument, sourceStart, sourceEnd); - } - - public void javadocMissingThrowsTag(TypeReference typeRef, int modifiers) { - boolean overriding = (modifiers & (CompilerModifiers.AccImplementing + CompilerModifiers.AccOverriding)) != 0; - boolean report = (this.options.getSeverity(CompilerOptions.MissingJavadocTags) != ProblemSeverities.Ignore) - && (!overriding || this.options.reportMissingJavadocTagsOverriding); - if (report && javadocVisibility(this.options.reportMissingJavadocTagsVisibility, modifiers)) { - String[] arguments = new String[] { String.valueOf(typeRef.resolvedType.sourceName()) }; - this.handle(IProblem.JavadocMissingThrowsTag, arguments, arguments, typeRef.sourceStart, typeRef.sourceEnd); - } - } - - public void javadocUnexpectedTag(int sourceStart, int sourceEnd) { - this.handle(IProblem.JavadocUnexpectedTag, NoArgument, NoArgument, sourceStart, sourceEnd); - } - - public void javadocUnterminatedInlineTag(int sourceStart, int sourceEnd) { - this.handle(IProblem.JavadocUnterminatedInlineTag, NoArgument, NoArgument, sourceStart, sourceEnd); - } - - private boolean javadocVisibility(int visibility, int modifiers) { - switch (modifiers & CompilerModifiers.AccVisibilityMASK) { - case IConstants.AccPublic: - return true; - case IConstants.AccProtected: - return (visibility != IConstants.AccPublic); - // case IConstants.AccDefault: - // return (visibility == IConstants.AccDefault || visibility == IConstants.AccPrivate); - case IConstants.AccPrivate: - return (visibility == IConstants.AccPrivate); - } - return true; - } - - private String javadocVisibilityArgument(int visibility, int modifiers) { - String argument = null; - switch (modifiers & CompilerModifiers.AccVisibilityMASK) { - case IConstants.AccPublic: - argument = CompilerOptions.PUBLIC; - break; - case IConstants.AccProtected: - if (visibility != IConstants.AccPublic) { - argument = CompilerOptions.PROTECTED; - } - break; - // case IConstants.AccDefault: - // if (visibility == IConstants.AccDefault || visibility == IConstants.AccPrivate) { - // argument = CompilerOptions.DEFAULT; - // } - // break; - case IConstants.AccPrivate: - if (visibility == IConstants.AccPrivate) { - argument = CompilerOptions.PRIVATE; - } - break; - } - return argument; - } - - public void methodNeedingAbstractModifier(MethodDeclaration methodDecl) { - this.handle(IProblem.MethodRequiresBody, NoArgument, NoArgument, methodDecl.sourceStart, methodDecl.sourceEnd); - } - - public void methodNeedingNoBody(MethodDeclaration methodDecl) { - this.handle( - // ((methodDecl.modifiers & CompilerModifiers.AccNative) != 0) ? - // IProblem.BodyForNativeMethod : IProblem.BodyForAbstractMethod, - IProblem.BodyForAbstractMethod, NoArgument, NoArgument, methodDecl.sourceStart, methodDecl.sourceEnd); - } - - public void methodWithConstructorName(MethodDeclaration methodDecl) { - this.handle(IProblem.MethodButWithConstructorName, NoArgument, NoArgument, methodDecl.sourceStart, methodDecl.sourceEnd); - } - - //public void missingEnclosingInstanceSpecification(ReferenceBinding - // enclosingType, ASTNode location) { - // boolean insideConstructorCall = - // (location instanceof ExplicitConstructorCall) - // && (((ExplicitConstructorCall) location).accessMode == - // ExplicitConstructorCall.ImplicitSuper); - // - // this.handle( - // insideConstructorCall - // ? IProblem.MissingEnclosingInstanceForConstructorCall - // : IProblem.MissingEnclosingInstance, - // new String[] {new String(enclosingType.readableName())}, - // new String[] {new String(enclosingType.shortReadableName())}, - // location.sourceStart, - // location.sourceEnd); - //} - public void missingReturnType(AbstractMethodDeclaration methodDecl) { - this.handle(IProblem.MissingReturnType, NoArgument, NoArgument, methodDecl.sourceStart, methodDecl.sourceEnd); - } - - public void missingSemiColon(Expression expression) { - this.handle(IProblem.MissingSemiColon, NoArgument, NoArgument, expression.sourceStart, expression.sourceEnd); - } - - public void mustDefineDimensionsOrInitializer(ArrayAllocationExpression expression) { - this.handle(IProblem.MustDefineEitherDimensionExpressionsOrInitializer, NoArgument, NoArgument, expression.sourceStart, - expression.sourceEnd); - } - - public void mustSpecifyPackage(CompilationUnitDeclaration compUnitDecl) { - String[] arguments = new String[] { new String(compUnitDecl.getFileName()) }; - this.handle(IProblem.MustSpecifyPackage, arguments, arguments, compUnitDecl.sourceStart, compUnitDecl.sourceStart + 1); - } - - public void mustUseAStaticMethod(MessageSend messageSend, MethodBinding method) { - this.handle(IProblem.StaticMethodRequested, new String[] { - new String(method.declaringClass.readableName()), - new String(method.selector), - parametersAsString(method) }, new String[] { - new String(method.declaringClass.shortReadableName()), - new String(method.selector), - parametersAsShortString(method) }, messageSend.sourceStart, messageSend.sourceEnd); - } - - public void nativeMethodsCannotBeStrictfp(ReferenceBinding type, AbstractMethodDeclaration methodDecl) { - String[] arguments = new String[] { new String(type.sourceName()), new String(methodDecl.selector) }; - this.handle(IProblem.NativeMethodsCannotBeStrictfp, arguments, arguments, methodDecl.sourceStart, methodDecl.sourceEnd); - } - - public void needImplementation() { - this.abortDueToInternalError(Util.bind("abort.missingCode")); //$NON-NLS-1$ - } - - public void needToEmulateFieldReadAccess(FieldBinding field, ASTNode location) { - this.handle(IProblem.NeedToEmulateFieldReadAccess, new String[] { - new String(field.declaringClass.readableName()), - new String(field.name) }, new String[] { new String(field.declaringClass.shortReadableName()), new String(field.name) }, - location.sourceStart, location.sourceEnd); - } - - public void needToEmulateFieldWriteAccess(FieldBinding field, ASTNode location) { - this.handle(IProblem.NeedToEmulateFieldWriteAccess, new String[] { - new String(field.declaringClass.readableName()), - new String(field.name) }, new String[] { new String(field.declaringClass.shortReadableName()), new String(field.name) }, - location.sourceStart, location.sourceEnd); - } - - public void needToEmulateMethodAccess(MethodBinding method, ASTNode location) { - if (method.isConstructor()) - this.handle(IProblem.NeedToEmulateConstructorAccess, new String[] { - new String(method.declaringClass.readableName()), - parametersAsString(method) }, new String[] { - new String(method.declaringClass.shortReadableName()), - parametersAsShortString(method) }, location.sourceStart, location.sourceEnd); - else - this.handle(IProblem.NeedToEmulateMethodAccess, new String[] { - new String(method.declaringClass.readableName()), - new String(method.selector), - parametersAsString(method) }, new String[] { - new String(method.declaringClass.shortReadableName()), - new String(method.selector), - parametersAsShortString(method) }, location.sourceStart, location.sourceEnd); - } - - public void nestedClassCannotDeclareInterface(TypeDeclaration typeDecl) { - String[] arguments = new String[] { new String(typeDecl.name) }; - this.handle(IProblem.CannotDefineInterfaceInLocalType, arguments, arguments, typeDecl.sourceStart, typeDecl.sourceEnd); - } - - public void noMoreAvailableSpaceForArgument(LocalVariableBinding local, ASTNode location) { - String[] arguments = new String[] { new String(local.name) }; - this.handle(local instanceof SyntheticArgumentBinding ? IProblem.TooManySyntheticArgumentSlots : IProblem.TooManyArgumentSlots, - arguments, arguments, Abort | Error, location.sourceStart, location.sourceEnd); - } - - public void noMoreAvailableSpaceForLocal(LocalVariableBinding local, ASTNode location) { - String[] arguments = new String[] { new String(local.name) }; - this.handle(IProblem.TooManyLocalVariableSlots, arguments, arguments, Abort | Error, location.sourceStart, location.sourceEnd); - } - - public void noSuchEnclosingInstance(TypeBinding targetType, ASTNode location, boolean isConstructorCall) { - int id; - if (isConstructorCall) { - //28 = No enclosing instance of type {0} is available due to some - // intermediate constructor invocation - id = IProblem.EnclosingInstanceInConstructorCall; - } else if ((location instanceof ExplicitConstructorCall) - && ((ExplicitConstructorCall) location).accessMode == ExplicitConstructorCall.ImplicitSuper) { - //20 = No enclosing instance of type {0} is accessible to invoke - // the super constructor. Must define a constructor and explicitly - // qualify its super constructor invocation with an instance of {0} - // (e.g. x.super() where x is an instance of {0}). - id = IProblem.MissingEnclosingInstanceForConstructorCall; - } else if (location instanceof AllocationExpression - && (((AllocationExpression) location).binding.declaringClass.isMemberType() || (((AllocationExpression) location).binding.declaringClass - .isAnonymousType() && ((AllocationExpression) location).binding.declaringClass.superclass().isMemberType()))) { - //21 = No enclosing instance of type {0} is accessible. Must - // qualify the allocation with an enclosing instance of type {0} - // (e.g. x.new A() where x is an instance of {0}). - id = IProblem.MissingEnclosingInstance; - } else { // default - //22 = No enclosing instance of the type {0} is accessible in - // scope - id = IProblem.IncorrectEnclosingInstanceReference; - } - this.handle(id, new String[] { new String(targetType.readableName()) }, new String[] { new String(targetType - .shortReadableName()) }, location.sourceStart, location.sourceEnd); - } - - public void notCompatibleTypesError(EqualExpression expression, TypeBinding leftType, TypeBinding rightType) { - String leftName = new String(leftType.readableName()); - String rightName = new String(rightType.readableName()); - String leftShortName = new String(leftType.shortReadableName()); - String rightShortName = new String(rightType.shortReadableName()); - if (leftShortName.equals(rightShortName)) { - leftShortName = leftName; - rightShortName = rightName; - } - this.handle(IProblem.IncompatibleTypesInEqualityOperator, new String[] { leftName, rightName }, new String[] { - leftShortName, - rightShortName }, expression.sourceStart, expression.sourceEnd); - } - - public void notCompatibleTypesError(InstanceOfExpression expression, TypeBinding leftType, TypeBinding rightType) { - String leftName = new String(leftType.readableName()); - String rightName = new String(rightType.readableName()); - String leftShortName = new String(leftType.shortReadableName()); - String rightShortName = new String(rightType.shortReadableName()); - if (leftShortName.equals(rightShortName)) { - leftShortName = leftName; - rightShortName = rightName; - } - this.handle(IProblem.IncompatibleTypesInConditionalOperator, new String[] { leftName, rightName }, new String[] { - leftShortName, - rightShortName }, expression.sourceStart, expression.sourceEnd); - } - - public void objectCannotHaveSuperTypes(SourceTypeBinding type) { - this.handle(IProblem.ObjectCannotHaveSuperTypes, NoArgument, NoArgument, type.sourceStart(), type.sourceEnd()); - } - - public void operatorOnlyValidOnNumericType(CompoundAssignment assignment, TypeBinding leftType, TypeBinding rightType) { - String leftName = new String(leftType.readableName()); - String rightName = new String(rightType.readableName()); - String leftShortName = new String(leftType.shortReadableName()); - String rightShortName = new String(rightType.shortReadableName()); - if (leftShortName.equals(rightShortName)) { - leftShortName = leftName; - rightShortName = rightName; - } - this.handle(IProblem.TypeMismatch, new String[] { leftName, rightName }, new String[] { leftShortName, rightShortName }, - assignment.sourceStart, assignment.sourceEnd); - } - - public void overridesDeprecatedMethod(MethodBinding localMethod, MethodBinding inheritedMethod) { - this.handle(IProblem.OverridingDeprecatedMethod, new String[] { - new String(CharOperation.concat(localMethod.declaringClass.readableName(), localMethod.readableName(), '.')), - new String(inheritedMethod.declaringClass.readableName()) }, new String[] { - new String(CharOperation.concat(localMethod.declaringClass.shortReadableName(), localMethod.shortReadableName(), '.')), - new String(inheritedMethod.declaringClass.shortReadableName()) }, localMethod.sourceStart(), localMethod.sourceEnd()); - } - - public void overridesPackageDefaultMethod(MethodBinding localMethod, MethodBinding inheritedMethod) { - this.handle(IProblem.OverridingNonVisibleMethod, new String[] { - new String(CharOperation.concat(localMethod.declaringClass.readableName(), localMethod.readableName(), '.')), - new String(inheritedMethod.declaringClass.readableName()) }, new String[] { - new String(CharOperation.concat(localMethod.declaringClass.shortReadableName(), localMethod.shortReadableName(), '.')), - new String(inheritedMethod.declaringClass.shortReadableName()) }, localMethod.sourceStart(), localMethod.sourceEnd()); - } - - // public void packageCollidesWithType(CompilationUnitDeclaration compUnitDecl) { - // String[] arguments = new String[]{CharOperation - // .toString(compUnitDecl.currentPackage.tokens)}; - // this.handle(IProblem.PackageCollidesWithType, arguments, arguments, - // compUnitDecl.currentPackage.sourceStart, - // compUnitDecl.currentPackage.sourceEnd); - // } - public void packageIsNotExpectedPackage(CompilationUnitDeclaration compUnitDecl) { - String[] arguments = new String[] { CharOperation.toString(compUnitDecl.compilationResult.compilationUnit.getPackageName()) }; - this.handle(IProblem.PackageIsNotExpectedPackage, arguments, arguments, compUnitDecl.currentPackage == null ? 0 - : compUnitDecl.currentPackage.sourceStart, compUnitDecl.currentPackage == null ? 0 : compUnitDecl.currentPackage.sourceEnd); - } - - private String parametersAsString(MethodBinding method) { - TypeBinding[] params = method.parameters; - StringBuffer buffer = new StringBuffer(); - for (int i = 0, length = params.length; i < length; i++) { - if (i != 0) - buffer.append(", "); //$NON-NLS-1$ - buffer.append(new String(params[i].readableName())); - } - return buffer.toString(); - } - - private String parametersAsShortString(MethodBinding method) { - TypeBinding[] params = method.parameters; - StringBuffer buffer = new StringBuffer(); - for (int i = 0, length = params.length; i < length; i++) { - if (i != 0) - buffer.append(", "); //$NON-NLS-1$ - buffer.append(new String(params[i].shortReadableName())); - } - return buffer.toString(); - } - - public void parseError(int startPosition, int endPosition, char[] currentTokenSource, String errorTokenName, - String[] possibleTokens) { - if (possibleTokens.length == 0) { //no suggestion available - if (isKeyword(currentTokenSource)) { - String[] arguments = new String[] { new String(currentTokenSource) }; - this.handle(IProblem.ParsingErrorOnKeywordNoSuggestion, arguments, arguments, - // this is the current -invalid- token position - startPosition, endPosition); - return; - } else { - String[] arguments = new String[] { errorTokenName }; - this.handle(IProblem.ParsingErrorNoSuggestion, arguments, arguments, - // this is the current -invalid- token position - startPosition, endPosition); - return; - } - } - //build a list of probable right tokens - StringBuffer list = new StringBuffer(20); - for (int i = 0, max = possibleTokens.length; i < max; i++) { - if (i > 0) - list.append(", "); //$NON-NLS-1$ - list.append('"'); - list.append(possibleTokens[i]); - list.append('"'); - } - if (isKeyword(currentTokenSource)) { - String[] arguments = new String[] { new String(currentTokenSource), list.toString() }; - this.handle(IProblem.ParsingErrorOnKeyword, arguments, arguments, - // this is the current -invalid- token position - startPosition, endPosition); - return; - } - //extract the literal when it's a literal - if ((errorTokenName.equals("IntegerLiteral")) || //$NON-NLS-1$ - (errorTokenName.equals("LongLiteral")) || //$NON-NLS-1$ - (errorTokenName.equals("FloatingPointLiteral")) || //$NON-NLS-1$ - (errorTokenName.equals("DoubleLiteral")) || //$NON-NLS-1$ - (errorTokenName.equals("StringLiteral")) || //$NON-NLS-1$ - (errorTokenName.equals("CharacterLiteral")) || //$NON-NLS-1$ - (errorTokenName.equals("Identifier"))) { //$NON-NLS-1$ - errorTokenName = new String(currentTokenSource); - } - String[] arguments = new String[] { errorTokenName, list.toString() }; - this.handle(IProblem.ParsingError, arguments, arguments, - // this is the current -invalid- token position - startPosition, endPosition); - } - - public void publicClassMustMatchFileName(CompilationUnitDeclaration compUnitDecl, TypeDeclaration typeDecl) { - this.referenceContext = typeDecl; // report the problem against the - // type not the entire compilation - // unit - String[] arguments = new String[] { new String(compUnitDecl.getFileName()), new String(typeDecl.name) }; - this.handle(IProblem.PublicClassMustMatchFileName, arguments, arguments, typeDecl.sourceStart, typeDecl.sourceEnd, - compUnitDecl.compilationResult); - } - - public void recursiveConstructorInvocation(ExplicitConstructorCall constructorCall) { - this.handle(IProblem.RecursiveConstructorInvocation, new String[] { - new String(constructorCall.binding.declaringClass.readableName()), - parametersAsString(constructorCall.binding) }, new String[] { - new String(constructorCall.binding.declaringClass.shortReadableName()), - parametersAsShortString(constructorCall.binding) }, constructorCall.sourceStart, constructorCall.sourceEnd); - } - - public void redefineArgument(Argument arg) { - String[] arguments = new String[] { new String(arg.name) }; - this.handle(IProblem.RedefinedArgument, arguments, arguments, arg.sourceStart, arg.sourceEnd); - } - - public void redefineLocal(LocalDeclaration localDecl) { - String[] arguments = new String[] { new String(localDecl.name) }; - this.handle(IProblem.RedefinedLocal, arguments, arguments, localDecl.sourceStart, localDecl.sourceEnd); - } - - public void referenceMustBeArrayTypeAt(TypeBinding arrayType, ArrayReference arrayRef) { - this.handle(IProblem.ArrayReferenceRequired, new String[] { new String(arrayType.readableName()) }, new String[] { new String( - arrayType.shortReadableName()) }, arrayRef.sourceStart, arrayRef.sourceEnd); - } - - public void returnTypeCannotBeVoidArray(SourceTypeBinding type, MethodDeclaration methodDecl) { - String[] arguments = new String[] { new String(methodDecl.selector) }; - this.handle(IProblem.ReturnTypeCannotBeVoidArray, arguments, arguments, methodDecl.sourceStart, methodDecl.sourceEnd); - } - - public void returnTypeProblem(SourceTypeBinding type, MethodDeclaration methodDecl, TypeBinding expectedType) { - int problemId = expectedType.problemId(); - int id; - switch (problemId) { - case NotFound: - // 1 - id = IProblem.ReturnTypeNotFound; - break; - case NotVisible: - // 2 - id = IProblem.ReturnTypeNotVisible; - break; - case Ambiguous: - // 3 - id = IProblem.ReturnTypeAmbiguous; - break; - case InternalNameProvided: - // 4 - id = IProblem.ReturnTypeInternalNameProvided; - break; - case InheritedNameHidesEnclosingName: - // 5 - id = IProblem.ReturnTypeInheritedNameHidesEnclosingName; - break; - case NoError: - // 0 - default: - needImplementation(); // want to fail to see why we were - // here... - return; - } - this.handle(id, new String[] { new String(methodDecl.selector), new String(expectedType.readableName()) }, new String[] { - new String(methodDecl.selector), - new String(expectedType.shortReadableName()) }, methodDecl.returnType.sourceStart, methodDecl.returnType.sourceEnd); - } - - public void scannerError(Parser parser, String errorTokenName) { - Scanner scanner = parser.scanner; - int flag = IProblem.ParsingErrorNoSuggestion; - int startPos = scanner.startPosition; - //special treatment for recognized errors.... - if (errorTokenName.equals(Scanner.END_OF_SOURCE)) - flag = IProblem.EndOfSource; - else if (errorTokenName.equals(Scanner.INVALID_HEXA)) - flag = IProblem.InvalidHexa; - else if (errorTokenName.equals(Scanner.INVALID_OCTAL)) - flag = IProblem.InvalidOctal; - else if (errorTokenName.equals(Scanner.INVALID_CHARACTER_CONSTANT)) - flag = IProblem.InvalidCharacterConstant; - else if (errorTokenName.equals(Scanner.INVALID_ESCAPE)) - flag = IProblem.InvalidEscape; - else if (errorTokenName.equals(Scanner.INVALID_UNICODE_ESCAPE)) { - flag = IProblem.InvalidUnicodeEscape; - // better locate the error message - char[] source = scanner.source; - int checkPos = scanner.currentPosition - 1; - if (checkPos >= source.length) - checkPos = source.length - 1; - while (checkPos >= startPos) { - if (source[checkPos] == '\\') - break; - checkPos--; - } - startPos = checkPos; - } else if (errorTokenName.equals(Scanner.INVALID_FLOAT)) - flag = IProblem.InvalidFloat; - else if (errorTokenName.equals(Scanner.UNTERMINATED_STRING)) - flag = IProblem.UnterminatedString; - else if (errorTokenName.equals(Scanner.UNTERMINATED_COMMENT)) - flag = IProblem.UnterminatedComment; - else if (errorTokenName.equals(Scanner.INVALID_CHAR_IN_STRING)) - flag = IProblem.UnterminatedString; - String[] arguments = flag == IProblem.ParsingErrorNoSuggestion ? new String[] { errorTokenName } : NoArgument; - this.handle(flag, arguments, arguments, - // this is the current -invalid- token position - startPos, scanner.currentPosition - 1, parser.compilationUnit.compilationResult); - } - - public void shouldReturn(TypeBinding returnType, ASTNode location) { - this.handle(IProblem.ShouldReturnValue, new String[] { new String(returnType.readableName()) }, new String[] { new String( - returnType.shortReadableName()) }, location.sourceStart, location.sourceEnd); - } - - public void signalNoImplicitStringConversionForCharArrayExpression(Expression expression) { - this.handle(IProblem.NoImplicitStringConversionForCharArrayExpression, NoArgument, NoArgument, expression.sourceStart, - expression.sourceEnd); - } - - public void staticAndInstanceConflict(MethodBinding currentMethod, MethodBinding inheritedMethod) { - if (currentMethod.isStatic()) - this.handle( - // This static method cannot hide the instance method from %1 - // 8.4.6.4 - If a class inherits more than one method with - // the same signature a static (non-abstract) method cannot - // hide an instance method. - IProblem.CannotHideAnInstanceMethodWithAStaticMethod, new String[] { new String(inheritedMethod.declaringClass - .readableName()) }, new String[] { new String(inheritedMethod.declaringClass.shortReadableName()) }, currentMethod - .sourceStart(), currentMethod.sourceEnd()); - else - this.handle( - // This instance method cannot override the static method from %1 - // 8.4.6.4 - If a class inherits more than one method with - // the same signature an instance (non-abstract) method - // cannot override a static method. - IProblem.CannotOverrideAStaticMethodWithAnInstanceMethod, new String[] { new String(inheritedMethod.declaringClass - .readableName()) }, new String[] { new String(inheritedMethod.declaringClass.shortReadableName()) }, currentMethod - .sourceStart(), currentMethod.sourceEnd()); - } - - public void staticFieldAccessToNonStaticVariable(FieldReference fieldRef, FieldBinding field) { - String[] arguments = new String[] { new String(field.readableName()) }; - this.handle(IProblem.NonStaticFieldFromStaticInvocation, arguments, arguments, fieldRef.sourceStart, fieldRef.sourceEnd); - } - - public void staticFieldAccessToNonStaticVariable(QualifiedNameReference nameRef, FieldBinding field) { - String[] arguments = new String[] { new String(field.readableName()) }; - this.handle(IProblem.NonStaticFieldFromStaticInvocation, arguments, arguments, nameRef.sourceStart, nameRef.sourceEnd); - } - - public void staticFieldAccessToNonStaticVariable(SingleNameReference nameRef, FieldBinding field) { - String[] arguments = new String[] { new String(field.readableName()) }; - this.handle(IProblem.NonStaticFieldFromStaticInvocation, arguments, arguments, nameRef.sourceStart, nameRef.sourceEnd); - } - - public void staticInheritedMethodConflicts(SourceTypeBinding type, MethodBinding concreteMethod, MethodBinding[] abstractMethods) { - this.handle( - // The static method %1 conflicts with the abstract method in %2 - // 8.4.6.4 - If a class inherits more than one method with the - // same signature it is an error for one to be static - // (non-abstract) and the other abstract. - IProblem.StaticInheritedMethodConflicts, new String[] { - new String(concreteMethod.readableName()), - new String(abstractMethods[0].declaringClass.readableName()) }, new String[] { - new String(concreteMethod.readableName()), - new String(abstractMethods[0].declaringClass.shortReadableName()) }, type.sourceStart(), type.sourceEnd()); - } - - public void stringConstantIsExceedingUtf8Limit(ASTNode location) { - this.handle(IProblem.StringConstantIsExceedingUtf8Limit, NoArgument, NoArgument, location.sourceStart, location.sourceEnd); - } - - public void superclassMustBeAClass(SourceTypeBinding type, TypeReference superclassRef, ReferenceBinding superType) { - this.handle(IProblem.SuperclassMustBeAClass, - new String[] { new String(superType.readableName()), new String(type.sourceName()) }, new String[] { - new String(superType.shortReadableName()), - new String(type.sourceName()) }, superclassRef.sourceStart, superclassRef.sourceEnd); - } - - public void superinterfaceMustBeAnInterface(SourceTypeBinding type, TypeDeclaration typeDecl, ReferenceBinding superType) { - this.handle(IProblem.SuperInterfaceMustBeAnInterface, new String[] { - new String(superType.readableName()), - new String(type.sourceName()) }, new String[] { new String(superType.shortReadableName()), new String(type.sourceName()) }, - typeDecl.sourceStart, typeDecl.sourceEnd); - } - - public void task(String tag, String message, String priority, int start, int end) { - this.handle(IProblem.Task, new String[] { tag, message, priority /* - * secret argument that is not surfaced in getMessage() - */}, new String[] { tag, message, priority /* - * secret argument that is not surfaced in getMessage() - */}, start, end); - } - - public void tooManyDimensions(ASTNode expression) { - this.handle(IProblem.TooManyArrayDimensions, NoArgument, NoArgument, expression.sourceStart, expression.sourceEnd); - } - - public void tooManyFields(TypeDeclaration typeDeclaration) { - this.handle(IProblem.TooManyFields, new String[] { new String(typeDeclaration.binding.readableName()) }, - new String[] { new String(typeDeclaration.binding.shortReadableName()) }, Abort | Error, typeDeclaration.sourceStart, - typeDeclaration.sourceEnd); - } - - public void tooManyMethods(TypeDeclaration typeDeclaration) { - this.handle(IProblem.TooManyMethods, new String[] { new String(typeDeclaration.binding.readableName()) }, - new String[] { new String(typeDeclaration.binding.shortReadableName()) }, Abort | Error, typeDeclaration.sourceStart, - typeDeclaration.sourceEnd); - } - - public void typeCastError(CastExpression expression, TypeBinding leftType, TypeBinding rightType) { - String leftName = new String(leftType.readableName()); - String rightName = new String(rightType.readableName()); - String leftShortName = new String(leftType.shortReadableName()); - String rightShortName = new String(rightType.shortReadableName()); - if (leftShortName.equals(rightShortName)) { - leftShortName = leftName; - rightShortName = rightName; - } - this.handle(IProblem.IllegalCast, new String[] { rightName, leftName }, new String[] { rightShortName, leftShortName }, - expression.sourceStart, expression.sourceEnd); - } - - public void typeCollidesWithPackage(CompilationUnitDeclaration compUnitDecl, TypeDeclaration typeDecl) { - this.referenceContext = typeDecl; // report the problem against the - // type not the entire compilation - // unit - String[] arguments = new String[] { new String(compUnitDecl.getFileName()), new String(typeDecl.name) }; - this.handle(IProblem.TypeCollidesWithPackage, arguments, arguments, typeDecl.sourceStart, typeDecl.sourceEnd, - compUnitDecl.compilationResult); - } - - public void typeMismatchError(TypeBinding resultType, TypeBinding expectedType, ASTNode location) { - String resultTypeName = new String(resultType.readableName()); - String expectedTypeName = new String(expectedType.readableName()); - String resultTypeShortName = new String(resultType.shortReadableName()); - String expectedTypeShortName = new String(expectedType.shortReadableName()); - if (resultTypeShortName.equals(expectedTypeShortName)) { - resultTypeShortName = resultTypeName; - expectedTypeShortName = expectedTypeName; - } - this.handle(IProblem.TypeMismatch, new String[] { resultTypeName, expectedTypeName }, new String[] { - resultTypeShortName, - expectedTypeShortName }, location.sourceStart, location.sourceEnd); - } - - public void typeMismatchErrorActualTypeExpectedType(Expression expression, TypeBinding constantType, TypeBinding expectedType) { - String constantTypeName = new String(constantType.readableName()); - String expectedTypeName = new String(expectedType.readableName()); - String constantTypeShortName = new String(constantType.shortReadableName()); - String expectedTypeShortName = new String(expectedType.shortReadableName()); - if (constantTypeShortName.equals(expectedTypeShortName)) { - constantTypeShortName = constantTypeName; - expectedTypeShortName = expectedTypeName; - } - this.handle(IProblem.TypeMismatch, new String[] { constantTypeName, expectedTypeName }, new String[] { - constantTypeShortName, - expectedTypeShortName }, expression.sourceStart, expression.sourceEnd); - } - - // public void undefinedLabel(BranchStatement statement) { - // String[] arguments = new String[] { new String(statement.label) }; - // this.handle(IProblem.UndefinedLabel, arguments, arguments, statement.sourceStart, statement.sourceEnd); - // } - - public void unexpectedStaticModifierForField(SourceTypeBinding type, FieldDeclaration fieldDecl) { - String[] arguments = new String[] { fieldDecl.name() }; - this.handle(IProblem.UnexpectedStaticModifierForField, arguments, arguments, fieldDecl.sourceStart, fieldDecl.sourceEnd); - } - - public void unexpectedStaticModifierForMethod(ReferenceBinding type, AbstractMethodDeclaration methodDecl) { - String[] arguments = new String[] { new String(type.sourceName()), new String(methodDecl.selector) }; - this.handle(IProblem.UnexpectedStaticModifierForMethod, arguments, arguments, methodDecl.sourceStart, methodDecl.sourceEnd); - } - - public void unhandledException(TypeBinding exceptionType, ASTNode location) { - boolean insideDefaultConstructor = (referenceContext instanceof ConstructorDeclaration) - && ((ConstructorDeclaration) referenceContext).isDefaultConstructor(); - boolean insideImplicitConstructorCall = (location instanceof ExplicitConstructorCall) - && (((ExplicitConstructorCall) location).accessMode == ExplicitConstructorCall.ImplicitSuper); - this.handle(insideDefaultConstructor ? IProblem.UnhandledExceptionInDefaultConstructor - : (insideImplicitConstructorCall ? IProblem.UndefinedConstructorInImplicitConstructorCall : IProblem.UnhandledException), - new String[] { new String(exceptionType.readableName()) }, new String[] { new String(exceptionType.shortReadableName()) }, - location.sourceStart, location.sourceEnd); - } - - public void uninitializedBlankFinalField(FieldBinding binding, ASTNode location) { - String[] arguments = new String[] { new String(binding.readableName()) }; - this.handle(IProblem.UninitializedBlankFinalField, arguments, arguments, location.sourceStart, location.sourceEnd); - } - - public void unmatchedBracket(int position, ReferenceContext context, CompilationResult compilationResult) { - this.handle(IProblem.UnmatchedBracket, NoArgument, NoArgument, position, position, context, compilationResult); - } - - public void unnecessaryEnclosingInstanceSpecification(Expression expression, ReferenceBinding targetType) { - this.handle(IProblem.IllegalEnclosingInstanceSpecification, new String[] { new String(targetType.readableName()) }, - new String[] { new String(targetType.shortReadableName()) }, expression.sourceStart, expression.sourceEnd); - } - - public void unnecessaryReceiverForStaticMethod(ASTNode location, MethodBinding method) { - this.handle(IProblem.NonStaticAccessToStaticMethod, new String[] { - new String(method.declaringClass.readableName()), - new String(method.selector), - parametersAsString(method) }, new String[] { - new String(method.declaringClass.shortReadableName()), - new String(method.selector), - parametersAsShortString(method) }, location.sourceStart, location.sourceEnd); - } - - public void unnecessaryReceiverForStaticField(ASTNode location, FieldBinding field) { - this.handle(IProblem.NonStaticAccessToStaticField, new String[] { - new String(field.declaringClass.readableName()), - new String(field.name) }, new String[] { new String(field.declaringClass.shortReadableName()), new String(field.name) }, - location.sourceStart, location.sourceEnd); - } - - public void unreachableExceptionHandler(ReferenceBinding exceptionType, ASTNode location) { - this.handle(IProblem.UnreachableCatch, NoArgument, NoArgument, location.sourceStart, location.sourceEnd); - } - - public void unresolvableReference(NameReference nameRef, Binding binding) { - int severity = Error; - /* - * also need to check that the searchedType is the receiver type if (binding instanceof ProblemBinding) { ProblemBinding problem = - * (ProblemBinding) binding; if (problem.searchType != null && problem.searchType.isHierarchyInconsistent()) severity = - * SecondaryError; } - */ - String[] arguments = new String[] { new String(binding.readableName()) }; - this.handle(IProblem.UndefinedName, arguments, arguments, severity, nameRef.sourceStart, nameRef.sourceEnd); - } - - public void unusedArgument(LocalDeclaration localDecl) { - String[] arguments = new String[] { localDecl.name() }; - this.handle(IProblem.ArgumentIsNeverUsed, arguments, arguments, localDecl.sourceStart, localDecl.sourceEnd); - } - - // public void unusedImport(ImportReference importRef) { - // String[] arguments = new String[]{CharOperation.toString(importRef.tokens)}; - // this.handle(IProblem.UnusedImport, arguments, arguments, - // importRef.sourceStart, importRef.sourceEnd); - // } - public void unusedLocalVariable(LocalDeclaration localDecl) { - String[] arguments = new String[] { localDecl.name() }; - this.handle(IProblem.LocalVariableIsNeverUsed, arguments, arguments, localDecl.sourceStart, localDecl.sourceEnd); - } - - public void unusedPrivateConstructor(ConstructorDeclaration constructorDecl) { - if (computeSeverity(IProblem.UnusedPrivateConstructor) == Ignore) - return; - // no complaint for no-arg constructors (or default ones) - known - // pattern to block instantiation - if (constructorDecl.arguments == null || constructorDecl.arguments.length == 0) - return; - MethodBinding constructor = constructorDecl.binding; - this.handle(IProblem.UnusedPrivateConstructor, new String[] { - new String(constructor.declaringClass.readableName()), - parametersAsString(constructor) }, new String[] { - new String(constructor.declaringClass.shortReadableName()), - parametersAsShortString(constructor) }, constructorDecl.sourceStart, constructorDecl.sourceEnd); - } - - public void unusedPrivateField(FieldDeclaration fieldDecl) { - if (computeSeverity(IProblem.UnusedPrivateField) == Ignore) - return; - FieldBinding field = fieldDecl.binding; - if (CharOperation.equals(TypeConstants.SERIALVERSIONUID, field.name) && field.isStatic() && field.isFinal() - && TypeBinding.LongBinding == field.type) { - return; // do not report unused serialVersionUID field - } - this.handle(IProblem.UnusedPrivateField, new String[] { - new String(field.declaringClass.readableName()), - new String(field.name), }, new String[] { new String(field.declaringClass.shortReadableName()), new String(field.name), }, - fieldDecl.sourceStart, fieldDecl.sourceEnd); - } - - public void unusedPrivateMethod(AbstractMethodDeclaration methodDecl) { - if (computeSeverity(IProblem.UnusedPrivateMethod) == Ignore) - return; - MethodBinding method = methodDecl.binding; - // no report for serialization support 'void - // readObject(ObjectInputStream)' - if (!method.isStatic() && TypeBinding.VoidBinding == method.returnType && method.parameters.length == 1 - && method.parameters[0].dimensions() == 0 && CharOperation.equals(method.selector, TypeConstants.READOBJECT) - && CharOperation.equals(TypeConstants.CharArray_JAVA_IO_OBJECTINPUTSTREAM, method.parameters[0].readableName())) { - return; - } - // no report for serialization support 'void - // writeObject(ObjectOutputStream)' - if (!method.isStatic() && TypeBinding.VoidBinding == method.returnType && method.parameters.length == 1 - && method.parameters[0].dimensions() == 0 && CharOperation.equals(method.selector, TypeConstants.WRITEOBJECT) - && CharOperation.equals(TypeConstants.CharArray_JAVA_IO_OBJECTOUTPUTSTREAM, method.parameters[0].readableName())) { - return; - } - // no report for serialization support 'Object readResolve()' - if (!method.isStatic() && TypeBinding.T_Object == method.returnType.id && method.parameters.length == 0 - && CharOperation.equals(method.selector, TypeConstants.READRESOLVE)) { - return; - } - // no report for serialization support 'Object writeReplace()' - if (!method.isStatic() && TypeBinding.T_Object == method.returnType.id && method.parameters.length == 0 - && CharOperation.equals(method.selector, TypeConstants.WRITEREPLACE)) { - return; - } - this.handle(IProblem.UnusedPrivateMethod, new String[] { - new String(method.declaringClass.readableName()), - new String(method.selector), - parametersAsString(method) }, new String[] { - new String(method.declaringClass.shortReadableName()), - new String(method.selector), - parametersAsShortString(method) }, methodDecl.sourceStart, methodDecl.sourceEnd); - } - - public void unusedPrivateType(TypeDeclaration typeDecl) { - if (computeSeverity(IProblem.UnusedPrivateType) == Ignore) - return; - ReferenceBinding type = typeDecl.binding; - this.handle(IProblem.UnusedPrivateType, new String[] { new String(type.readableName()), }, new String[] { new String(type - .shortReadableName()), }, typeDecl.sourceStart, typeDecl.sourceEnd); - } - - public void useAssertAsAnIdentifier(int sourceStart, int sourceEnd) { - this.handle(IProblem.UseAssertAsAnIdentifier, NoArgument, NoArgument, sourceStart, sourceEnd); - } - - public void variableTypeCannotBeVoid(AbstractVariableDeclaration varDecl) { - String[] arguments = new String[] { new String(varDecl.name) }; - this.handle(IProblem.VariableTypeCannotBeVoid, arguments, arguments, varDecl.sourceStart, varDecl.sourceEnd); - } - - public void variableTypeCannotBeVoidArray(AbstractVariableDeclaration varDecl) { - String[] arguments = new String[] { new String(varDecl.name) }; - this.handle(IProblem.VariableTypeCannotBeVoidArray, arguments, arguments, varDecl.sourceStart, varDecl.sourceEnd); - } - - public void visibilityConflict(MethodBinding currentMethod, MethodBinding inheritedMethod) { - this.handle( - // Cannot reduce the visibility of the inherited method from %1 - // 8.4.6.3 - The access modifier of an hiding method must - // provide at least as much access as the hidden method. - // 8.4.6.3 - The access modifier of an overiding method must - // provide at least as much access as the overriden method. - IProblem.MethodReducesVisibility, new String[] { new String(inheritedMethod.declaringClass.readableName()) }, - new String[] { new String(inheritedMethod.declaringClass.shortReadableName()) }, currentMethod.sourceStart(), currentMethod - .sourceEnd()); - } - - public void wrongSequenceOfExceptionTypesError(TryStatement statement, int under, int upper) { - //the two catch block under and upper are in an incorrect order. - //under should be define BEFORE upper in the source - TypeReference typeRef = statement.catchArguments[under].type; - this.handle(IProblem.UnreachableCatch, NoArgument, NoArgument, typeRef.sourceStart, typeRef.sourceEnd); - } - - public void nonExternalizedStringLiteral(ASTNode location) { - this.handle(IProblem.NonExternalizedStringLiteral, NoArgument, NoArgument, location.sourceStart, location.sourceEnd); - } - - public void noMoreAvailableSpaceForConstant(TypeDeclaration typeDeclaration) { - this.handle(IProblem.TooManyBytesForStringConstant, new String[] { new String(typeDeclaration.binding.readableName()) }, - new String[] { new String(typeDeclaration.binding.shortReadableName()) }, Abort | Error, typeDeclaration.sourceStart, - typeDeclaration.sourceEnd); - } - - public void noMoreAvailableSpaceInConstantPool(TypeDeclaration typeDeclaration) { - this.handle(IProblem.TooManyConstantsInConstantPool, new String[] { new String(typeDeclaration.binding.readableName()) }, - new String[] { new String(typeDeclaration.binding.shortReadableName()) }, Abort | Error, typeDeclaration.sourceStart, - typeDeclaration.sourceEnd); - } - - private boolean isKeyword(char[] tokenSource) { - /* - * This code is heavily grammar dependant - */ - if (tokenSource == null) { - return false; - } - try { - Scanner scanner = new Scanner(); - scanner.setSource(tokenSource); - int token = scanner.getNextToken(); - char[] currentKeyword; - try { - currentKeyword = scanner.getCurrentIdentifierSource(); - } catch (ArrayIndexOutOfBoundsException e) { - return false; - } - int nextToken = scanner.getNextToken(); - if (nextToken == Scanner.TokenNameEOF && scanner.startPosition == scanner.source.length) { // to - // handle - // case - // where - // we - // had - // an - // ArrayIndexOutOfBoundsException - // while reading the last token - switch (token) { - case Scanner.TokenNameERROR: - if (CharOperation.equals("goto".toCharArray(), currentKeyword) - || CharOperation.equals("const".toCharArray(), currentKeyword)) { //$NON-NLS-1$ //$NON-NLS-2$ - return true; - } else { - return false; - } - case Scanner.TokenNameabstract: - // case Scanner.TokenNameassert: - // case Scanner.TokenNamebyte: - case Scanner.TokenNamebreak: - // case Scanner.TokenNameboolean: - case Scanner.TokenNamecase: - // case Scanner.TokenNamechar: - case Scanner.TokenNamecatch: - case Scanner.TokenNameclass: - case Scanner.TokenNamecontinue: - case Scanner.TokenNamedo: - // case Scanner.TokenNamedouble: - case Scanner.TokenNamedefault: - case Scanner.TokenNameelse: - case Scanner.TokenNameextends: - case Scanner.TokenNamefor: - // case Scanner.TokenNamefinal: - // case Scanner.TokenNamefloat: - // case Scanner.TokenNamefalse : - case Scanner.TokenNamefinally: - case Scanner.TokenNameif: - // case Scanner.TokenNameint: - // case Scanner.TokenNameimport: - case Scanner.TokenNameinterface: - case Scanner.TokenNameimplements: - case Scanner.TokenNameinstanceof: - // case Scanner.TokenNamelong: - case Scanner.TokenNamenew: - // case Scanner.TokenNamenull : - // case Scanner.TokenNamenative: - case Scanner.TokenNamepublic: - // case Scanner.TokenNamepackage: - case Scanner.TokenNameprivate: - case Scanner.TokenNameprotected: - case Scanner.TokenNamereturn: - // case Scanner.TokenNameshort: - case Scanner.TokenNamesuper: - case Scanner.TokenNamestatic: - case Scanner.TokenNameswitch: - // case Scanner.TokenNamestrictfp: - // case Scanner.TokenNamesynchronized: - case Scanner.TokenNametry: - // case Scanner.TokenNamethis : - // case Scanner.TokenNametrue : - case Scanner.TokenNamethrow: - // case Scanner.TokenNamethrows: - // case Scanner.TokenNametransient: - // case Scanner.TokenNamevoid: - // case Scanner.TokenNamevolatile: - case Scanner.TokenNamewhile: - return true; - default: - return false; - } - } else { - return false; - } - } catch (InvalidInputException e) { - return false; - } - } - - // jsurfer start - public void phpParsingError(String[] messageArguments, int problemStartPosition, int problemEndPosition, - ReferenceContext context, CompilationResult compilationResult) { - this.handle(IProblem.PHPParsingError, NoArgument, messageArguments, problemStartPosition, problemEndPosition, context, - compilationResult); - } - - public void phpParsingWarning(String[] messageArguments, int problemStartPosition, int problemEndPosition, - ReferenceContext context, CompilationResult compilationResult) { - this.handle(IProblem.PHPParsingWarning, NoArgument, messageArguments, problemStartPosition, problemEndPosition, context, - compilationResult); - } - - public void phpVarDeprecatedWarning(int problemStartPosition, int problemEndPosition, ReferenceContext context, - CompilationResult compilationResult) { - if (computeSeverity(IProblem.PHPVarDeprecatedWarning) == Ignore) - return; - this.handle(IProblem.PHPVarDeprecatedWarning, NoArgument, new String[] {}, problemStartPosition, problemEndPosition, context, - compilationResult); - } - - public void phpIncludeNotExistWarning(String[] messageArguments, int problemStartPosition, int problemEndPosition, - ReferenceContext context, CompilationResult compilationResult) { - if (computeSeverity(IProblem.PHPIncludeNotExistWarning) == Ignore) - return; - this.handle(IProblem.PHPIncludeNotExistWarning, NoArgument, messageArguments, problemStartPosition, problemEndPosition, - context, compilationResult); - } - - public void phpKeywordWarning(String[] messageArguments, int problemStartPosition, int problemEndPosition, - ReferenceContext context, CompilationResult compilationResult) { - if (computeSeverity(IProblem.PHPBadStyleKeywordWarning) == Ignore) - return; - this.handle(IProblem.PHPBadStyleKeywordWarning, NoArgument, messageArguments, problemStartPosition, problemEndPosition, - context, compilationResult); - } - - public void phpUppercaseIdentifierWarning(int problemStartPosition, int problemEndPosition, ReferenceContext context, - CompilationResult compilationResult) { - if (computeSeverity(IProblem.PHPBadStyleUppercaseIdentifierWarning) == Ignore) - return; - this.handle(IProblem.PHPBadStyleUppercaseIdentifierWarning, NoArgument, new String[] {}, problemStartPosition, - problemEndPosition, context, compilationResult); - } - - public void uninitializedLocalVariable(String token, int problemStartPosition, int problemEndPosition, ReferenceContext context, - CompilationResult compilationResult) { - if (computeSeverity(IProblem.UninitializedLocalVariable) == Ignore) - return; - // String[] arguments = new String[] { new String(binding.readableName()) }; - String[] arguments = new String[] { token }; - this.handle(IProblem.UninitializedLocalVariable, arguments, arguments, problemStartPosition, problemEndPosition, context, - compilationResult); - } - - public void unreachableCode(String token, int problemStartPosition, int problemEndPosition, ReferenceContext context, - CompilationResult compilationResult) { - if (computeSeverity(IProblem.CodeCannotBeReached) == Ignore) - return; - this.handle(IProblem.CodeCannotBeReached, NoArgument, new String[] {}, problemStartPosition, - problemEndPosition, context, compilationResult); - } + public ReferenceContext referenceContext; + + public ProblemReporter(IErrorHandlingPolicy policy, + CompilerOptions options, IProblemFactory problemFactory) { + + // IProblemFactory problemFactory) { + super(policy, options, problemFactory); // ), problemFactory); + } + + public void abortDueToInternalError(String errorMessage) { + String[] arguments = new String[] { errorMessage }; + this.handle(IProblem.Unclassified, arguments, arguments, Error | Abort, + 0, 0); + } + + public void abortDueToInternalError(String errorMessage, ASTNode location) { + String[] arguments = new String[] { errorMessage }; + this.handle(IProblem.Unclassified, arguments, arguments, Error | Abort, + location.sourceStart, location.sourceEnd); + } + + public void abstractMethodCannotBeOverridden(SourceTypeBinding type, + MethodBinding concreteMethod) { + this.handle( + // %1 must be abstract since it cannot override the inherited + // package-private abstract method %2 + IProblem.AbstractMethodCannotBeOverridden, new String[] { + new String(type.sourceName()), + new String(CharOperation.concat( + concreteMethod.declaringClass.readableName(), + concreteMethod.readableName(), '.')) }, + new String[] { + new String(type.sourceName()), + new String(CharOperation.concat( + concreteMethod.declaringClass + .shortReadableName(), concreteMethod + .shortReadableName(), '.')) }, type + .sourceStart(), type.sourceEnd()); + } + + public void abstractMethodInAbstractClass(SourceTypeBinding type, + AbstractMethodDeclaration methodDecl) { + String[] arguments = new String[] { new String(type.sourceName()), + new String(methodDecl.selector) }; + this.handle(IProblem.AbstractMethodInAbstractClass, arguments, + arguments, methodDecl.sourceStart, methodDecl.sourceEnd); + } + + public void abstractMethodMustBeImplemented(SourceTypeBinding type, + MethodBinding abstractMethod) { + this.handle( + // Must implement the inherited abstract method %1 + // 8.4.3 - Every non-abstract subclass of an abstract type, A, + // must provide a concrete implementation of all of A's + // methods. + IProblem.AbstractMethodMustBeImplemented, + new String[] { new String(CharOperation.concat( + abstractMethod.declaringClass.readableName(), + abstractMethod.readableName(), '.')) }, + new String[] { new String(CharOperation.concat( + abstractMethod.declaringClass.shortReadableName(), + abstractMethod.shortReadableName(), '.')) }, type + .sourceStart(), type.sourceEnd()); + } + + public void abstractMethodNeedingNoBody(AbstractMethodDeclaration method) { + this.handle(IProblem.BodyForAbstractMethod, NoArgument, NoArgument, + method.sourceStart, method.sourceEnd, method, method + .compilationResult()); + } + + public void alreadyDefinedLabel(char[] labelName, ASTNode location) { + String[] arguments = new String[] { new String(labelName) }; + this.handle(IProblem.DuplicateLabel, arguments, arguments, + location.sourceStart, location.sourceEnd); + } + + public void anonymousClassCannotExtendFinalClass(Expression expression, + TypeBinding type) { + this.handle(IProblem.AnonymousClassCannotExtendFinalClass, + new String[] { new String(type.readableName()) }, + new String[] { new String(type.shortReadableName()) }, + expression.sourceStart, expression.sourceEnd); + } + + public void argumentTypeCannotBeVoid(SourceTypeBinding type, + AbstractMethodDeclaration methodDecl, Argument arg) { + String[] arguments = new String[] { new String(methodDecl.selector), + new String(arg.name) }; + this.handle(IProblem.ArgumentTypeCannotBeVoid, arguments, arguments, + methodDecl.sourceStart, methodDecl.sourceEnd); + } + + public void argumentTypeCannotBeVoidArray(SourceTypeBinding type, + AbstractMethodDeclaration methodDecl, Argument arg) { + String[] arguments = new String[] { new String(methodDecl.selector), + new String(arg.name) }; + this.handle(IProblem.ArgumentTypeCannotBeVoidArray, arguments, + arguments, methodDecl.sourceStart, methodDecl.sourceEnd); + } + + public void argumentTypeProblem(SourceTypeBinding type, + AbstractMethodDeclaration methodDecl, Argument arg, + TypeBinding expectedType) { + int problemId = expectedType.problemId(); + int id; + switch (problemId) { + case NotFound: + // 1 + id = IProblem.ArgumentTypeNotFound; + break; + case NotVisible: + // 2 + id = IProblem.ArgumentTypeNotVisible; + break; + case Ambiguous: + // 3 + id = IProblem.ArgumentTypeAmbiguous; + break; + case InternalNameProvided: + // 4 + id = IProblem.ArgumentTypeInternalNameProvided; + break; + case InheritedNameHidesEnclosingName: + // 5 + id = IProblem.ArgumentTypeInheritedNameHidesEnclosingName; + break; + case NoError: + // 0 + default: + needImplementation(); // want to fail to see why we were + // here... + return; + } + this.handle(id, new String[] { new String(methodDecl.selector), + arg.name(), new String(expectedType.readableName()) }, + new String[] { new String(methodDecl.selector), arg.name(), + new String(expectedType.shortReadableName()) }, + arg.type.sourceStart, arg.type.sourceEnd); + } + + public void arrayConstantsOnlyInArrayInitializers(int sourceStart, + int sourceEnd) { + this.handle(IProblem.ArrayConstantsOnlyInArrayInitializers, NoArgument, + NoArgument, sourceStart, sourceEnd); + } + + public void assignmentHasNoEffect(Assignment assignment, char[] name) { + String[] arguments = new String[] { new String(name) }; + this.handle(IProblem.AssignmentHasNoEffect, arguments, arguments, + assignment.sourceStart, assignment.sourceEnd); + } + + public void attemptToReturnNonVoidExpression( + ReturnStatement returnStatement, TypeBinding expectedType) { + this.handle(IProblem.VoidMethodReturnsValue, new String[] { new String( + expectedType.readableName()) }, new String[] { new String( + expectedType.shortReadableName()) }, + returnStatement.sourceStart, returnStatement.sourceEnd); + } + + public void attemptToReturnVoidValue(ReturnStatement returnStatement) { + this.handle(IProblem.MethodReturnsVoid, NoArgument, NoArgument, + returnStatement.sourceStart, returnStatement.sourceEnd); + } + + // public void bytecodeExceeds64KLimit(AbstractMethodDeclaration location) + // { + // String[] arguments = new String[] {new String(location.selector), + // parametersAsString(location.binding)}; + // if (location.isConstructor()) { + // this.handle( + // IProblem.BytecodeExceeds64KLimitForConstructor, + // arguments, + // arguments, + // Error | Abort, + // location.sourceStart, + // location.sourceEnd); + // } else { + // this.handle( + // IProblem.BytecodeExceeds64KLimit, + // arguments, + // arguments, + // Error | Abort, + // location.sourceStart, + // location.sourceEnd); + // } + // } + public void bytecodeExceeds64KLimit(TypeDeclaration location) { + this.handle(IProblem.BytecodeExceeds64KLimitForClinit, NoArgument, + NoArgument, Error | Abort, location.sourceStart, + location.sourceEnd); + } + + public void cannotAllocateVoidArray(Expression expression) { + this.handle(IProblem.CannotAllocateVoidArray, NoArgument, NoArgument, + expression.sourceStart, expression.sourceEnd); + } + + public void cannotAssignToFinalField(FieldBinding field, ASTNode location) { + this + .handle( + IProblem.FinalFieldAssignment, + new String[] { + (field.declaringClass == null ? "array" : new String(field.declaringClass.readableName())), //$NON-NLS-1$ + new String(field.readableName()) }, + new String[] { + (field.declaringClass == null ? "array" : new String(field.declaringClass.shortReadableName())), //$NON-NLS-1$ + new String(field.shortReadableName()) }, + location.sourceStart, location.sourceEnd); + } + + public void cannotAssignToFinalLocal(LocalVariableBinding local, + ASTNode location) { + String[] arguments = new String[] { new String(local.readableName()) }; + this.handle(IProblem.NonBlankFinalLocalAssignment, arguments, + arguments, location.sourceStart, location.sourceEnd); + } + + public void cannotAssignToFinalOuterLocal(LocalVariableBinding local, + ASTNode location) { + String[] arguments = new String[] { new String(local.readableName()) }; + this.handle(IProblem.FinalOuterLocalAssignment, arguments, arguments, + location.sourceStart, location.sourceEnd); + } + + public void cannotDeclareLocalInterface(char[] interfaceName, + int sourceStart, int sourceEnd) { + String[] arguments = new String[] { new String(interfaceName) }; + this.handle(IProblem.CannotDefineInterfaceInLocalType, arguments, + arguments, sourceStart, sourceEnd); + } + + public void cannotDefineDimensionsAndInitializer( + ArrayAllocationExpression expresssion) { + this.handle(IProblem.CannotDefineDimensionExpressionsWithInit, + NoArgument, NoArgument, expresssion.sourceStart, + expresssion.sourceEnd); + } + + public void cannotDireclyInvokeAbstractMethod(MessageSend messageSend, + MethodBinding method) { + this.handle(IProblem.DirectInvocationOfAbstractMethod, new String[] { + new String(method.declaringClass.readableName()), + new String(method.selector), parametersAsString(method) }, + new String[] { + new String(method.declaringClass.shortReadableName()), + new String(method.selector), + parametersAsShortString(method) }, + messageSend.sourceStart, messageSend.sourceEnd); + } + + // public void cannotImportPackage(ImportReference importRef) { + // String[] arguments = new + // String[]{CharOperation.toString(importRef.tokens)}; + // this.handle(IProblem.CannotImportPackage, arguments, arguments, + // importRef.sourceStart, importRef.sourceEnd); + // } + public void cannotInstantiate(TypeReference typeRef, TypeBinding type) { + this.handle(IProblem.InvalidClassInstantiation, + new String[] { new String(type.readableName()) }, + new String[] { new String(type.shortReadableName()) }, + typeRef.sourceStart, typeRef.sourceEnd); + } + + public void cannotReferToNonFinalOuterLocal(LocalVariableBinding local, + ASTNode location) { + String[] arguments = new String[] { new String(local.readableName()) }; + this.handle(IProblem.OuterLocalMustBeFinal, arguments, arguments, + location.sourceStart, location.sourceEnd); + } + + public void cannotReturnInInitializer(ASTNode location) { + this.handle(IProblem.CannotReturnInInitializer, NoArgument, NoArgument, + location.sourceStart, location.sourceEnd); + } + + public void cannotThrowNull(ThrowStatement statement) { + this.handle(IProblem.CannotThrowNull, NoArgument, NoArgument, + statement.sourceStart, statement.sourceEnd); + } + + public void cannotThrowType(SourceTypeBinding type, + AbstractMethodDeclaration methodDecl, TypeReference exceptionType, + TypeBinding expectedType) { + this.handle(IProblem.CannotThrowType, new String[] { new String( + expectedType.readableName()) }, new String[] { new String( + expectedType.shortReadableName()) }, exceptionType.sourceStart, + exceptionType.sourceEnd); + } + + public void cannotUseSuperInJavaLangObject(ASTNode reference) { + this.handle(IProblem.ObjectHasNoSuperclass, NoArgument, NoArgument, + reference.sourceStart, reference.sourceEnd); + } + + public void cannotUseSuperInCodeSnippet(int start, int end) { + this.handle(IProblem.CannotUseSuperInCodeSnippet, NoArgument, + NoArgument, Error | Abort, start, end); + } + + public void caseExpressionMustBeConstant(Expression expression) { + this.handle(IProblem.NonConstantExpression, NoArgument, NoArgument, + expression.sourceStart, expression.sourceEnd); + } + + public void classExtendFinalClass(SourceTypeBinding type, + TypeReference superclass, TypeBinding expectedType) { + String name = new String(type.sourceName()); + String expectedFullName = new String(expectedType.readableName()); + String expectedShortName = new String(expectedType.shortReadableName()); + if (expectedShortName.equals(name)) + expectedShortName = expectedFullName; + this.handle(IProblem.ClassExtendFinalClass, new String[] { + expectedFullName, name }, new String[] { expectedShortName, + name }, superclass.sourceStart, superclass.sourceEnd); + } + + public void codeSnippetMissingClass(String missing, int start, int end) { + String[] arguments = new String[] { missing }; + this.handle(IProblem.CodeSnippetMissingClass, arguments, arguments, + Error | Abort, start, end); + } + + public void codeSnippetMissingMethod(String className, + String missingMethod, String argumentTypes, int start, int end) { + String[] arguments = new String[] { className, missingMethod, + argumentTypes }; + this.handle(IProblem.CodeSnippetMissingMethod, arguments, arguments, + Error | Abort, start, end); + } + + /* + * Given the current configuration, answers which category the problem falls + * into: Error | Warning | Ignore + */ + public int computeSeverity(int problemId) { + + // severity can have been preset on the problem + // if ((problem.severity & Fatal) != 0){ + // return Error; + // } + + // if not then check whether it is a configurable problem + switch (problemId) { + case IProblem.PHPIncludeNotExistWarning: + return this.options + .getSeverity(CompilerOptions.PHPIncludeNotExistWarning); + case IProblem.PHPVarDeprecatedWarning: + return this.options + .getSeverity(CompilerOptions.PHPVarDeprecatedWarning); + case IProblem.PHPBadStyleKeywordWarning: + return this.options + .getSeverity(CompilerOptions.PHPBadStyleKeywordWarning); + case IProblem.PHPBadStyleUppercaseIdentifierWarning: + return this.options + .getSeverity(CompilerOptions.PHPBadStyleUppercaseIdentifierWarning); + + case IProblem.UninitializedLocalVariable: + return this.options + .getSeverity(CompilerOptions.UninitializedLocalVariableWarning); + case IProblem.CodeCannotBeReached: + return this.options + .getSeverity(CompilerOptions.CodeCannotBeReachedWarning); + + case IProblem.MaskedCatch: + return this.options.getSeverity(CompilerOptions.MaskedCatchBlock); + + case IProblem.UnusedImport: + return this.options.getSeverity(CompilerOptions.UnusedImport); + + case IProblem.MethodButWithConstructorName: + return this.options + .getSeverity(CompilerOptions.MethodWithConstructorName); + + case IProblem.OverridingNonVisibleMethod: + return this.options + .getSeverity(CompilerOptions.OverriddenPackageDefaultMethod); + + case IProblem.IncompatibleReturnTypeForNonInheritedInterfaceMethod: + case IProblem.IncompatibleExceptionInThrowsClauseForNonInheritedInterfaceMethod: + return this.options + .getSeverity(CompilerOptions.IncompatibleNonInheritedInterfaceMethod); + + case IProblem.OverridingDeprecatedMethod: + case IProblem.UsingDeprecatedType: + case IProblem.UsingDeprecatedMethod: + case IProblem.UsingDeprecatedConstructor: + case IProblem.UsingDeprecatedField: + return this.options.getSeverity(CompilerOptions.UsingDeprecatedAPI); + + case IProblem.LocalVariableIsNeverUsed: + return this.options + .getSeverity(CompilerOptions.UnusedLocalVariable); + + case IProblem.ArgumentIsNeverUsed: + return this.options.getSeverity(CompilerOptions.UnusedArgument); + + case IProblem.NoImplicitStringConversionForCharArrayExpression: + return this.options + .getSeverity(CompilerOptions.NoImplicitStringConversion); + + case IProblem.NeedToEmulateFieldReadAccess: + case IProblem.NeedToEmulateFieldWriteAccess: + case IProblem.NeedToEmulateMethodAccess: + case IProblem.NeedToEmulateConstructorAccess: + return this.options.getSeverity(CompilerOptions.AccessEmulation); + + case IProblem.NonExternalizedStringLiteral: + return this.options + .getSeverity(CompilerOptions.NonExternalizedString); + + case IProblem.UseAssertAsAnIdentifier: + return this.options + .getSeverity(CompilerOptions.AssertUsedAsAnIdentifier); + + case IProblem.NonStaticAccessToStaticMethod: + case IProblem.NonStaticAccessToStaticField: + return this.options + .getSeverity(CompilerOptions.NonStaticAccessToStatic); + + // case IProblem.IndirectAccessToStaticMethod : + // case IProblem.IndirectAccessToStaticField : + // case IProblem.IndirectAccessToStaticType : + // return + // this.options.getSeverity(CompilerOptions.IndirectStaticAccess); + + case IProblem.AssignmentHasNoEffect: + return this.options.getSeverity(CompilerOptions.NoEffectAssignment); + + case IProblem.UnusedPrivateConstructor: + case IProblem.UnusedPrivateMethod: + case IProblem.UnusedPrivateField: + case IProblem.UnusedPrivateType: + return this.options + .getSeverity(CompilerOptions.UnusedPrivateMember); + + case IProblem.Task: + return Warning; + + // case IProblem.LocalVariableHidingLocalVariable: + // case IProblem.LocalVariableHidingField: + // case IProblem.ArgumentHidingLocalVariable: + // case IProblem.ArgumentHidingField: + // return + // this.options.getSeverity(CompilerOptions.LocalVariableHiding); + + // case IProblem.FieldHidingLocalVariable: + // case IProblem.FieldHidingField: + // return this.options.getSeverity(CompilerOptions.FieldHiding); + + // case IProblem.PossibleAccidentalBooleanAssignment: + // return + // this.options.getSeverity(CompilerOptions.AccidentalBooleanAssign); + + // case IProblem.SuperfluousSemicolon: + // return + // this.options.getSeverity(CompilerOptions.SuperfluousSemicolon); + // + // case IProblem.UndocumentedEmptyBlock: + // return + // this.options.getSeverity(CompilerOptions.UndocumentedEmptyBlock); + // + // case IProblem.UnnecessaryCast: + // case IProblem.UnnecessaryArgumentCast: + // case IProblem.UnnecessaryInstanceof: + // return + // this.options.getSeverity(CompilerOptions.UnnecessaryTypeCheck); + // + // case IProblem.FinallyMustCompleteNormally: + // return + // this.options.getSeverity(CompilerOptions.FinallyBlockNotCompleting); + // + // case IProblem.UnusedMethodDeclaredThrownException: + // case IProblem.UnusedConstructorDeclaredThrownException: + // return + // this.options.getSeverity(CompilerOptions.UnusedDeclaredThrownException); + // + // case IProblem.UnqualifiedFieldAccess: + // return + // this.options.getSeverity(CompilerOptions.UnqualifiedFieldAccess); + + /* + * Javadoc syntax errors + */ + // Javadoc explicit IDs + // case IProblem.JavadocUnexpectedTag: + // case IProblem.JavadocDuplicateReturnTag: + // case IProblem.JavadocInvalidThrowsClass: + // case IProblem.JavadocInvalidSeeReference: + // case IProblem.JavadocInvalidSeeHref: + // case IProblem.JavadocInvalidSeeArgs: + // case IProblem.JavadocInvalidTag: + // return this.options.getSeverity(CompilerOptions.InvalidJavadoc); + /* + * Javadoc tags resolved references errors + */ + // case IProblem.JavadocInvalidParamName: + // case IProblem.JavadocDuplicateParamName: + // case IProblem.JavadocMissingParamName: + // case IProblem.JavadocInvalidThrowsClassName: + // case IProblem.JavadocDuplicateThrowsClassName: + // case IProblem.JavadocMissingThrowsClassName: + // case IProblem.JavadocMissingSeeReference: + // case IProblem.JavadocUsingDeprecatedField: + // case IProblem.JavadocUsingDeprecatedConstructor: + // case IProblem.JavadocUsingDeprecatedMethod: + // case IProblem.JavadocUsingDeprecatedType: + // case IProblem.JavadocUndefinedField: + // case IProblem.JavadocNotVisibleField: + // case IProblem.JavadocAmbiguousField: + // case IProblem.JavadocUndefinedConstructor: + // case IProblem.JavadocNotVisibleConstructor: + // case IProblem.JavadocAmbiguousConstructor: + // case IProblem.JavadocUndefinedMethod: + // case IProblem.JavadocNotVisibleMethod: + // case IProblem.JavadocAmbiguousMethod: + // case IProblem.JavadocParameterMismatch: + // case IProblem.JavadocUndefinedType: + // case IProblem.JavadocNotVisibleType: + // case IProblem.JavadocAmbiguousType: + // case IProblem.JavadocInternalTypeNameProvided: + // case IProblem.JavadocNoMessageSendOnArrayType: + // case IProblem.JavadocNoMessageSendOnBaseType: + // if (!this.options.reportInvalidJavadocTags) + // return ProblemSeverities.Ignore; + // else + // return this.options.getSeverity(CompilerOptions.InvalidJavadoc); + /* + * Javadoc missing tags errors + */ + // case IProblem.JavadocMissingParamTag: + // case IProblem.JavadocMissingReturnTag: + // case IProblem.JavadocMissingThrowsTag: + // return + // this.options.getSeverity(CompilerOptions.MissingJavadocTags); + /* + * Missing Javadoc errors + */ + // case IProblem.JavadocMissing: + // return + // this.options.getSeverity(CompilerOptions.MissingJavadocComments); + // by default problems are errors. + default: + return Error; + } + } + + // public void conditionalArgumentsIncompatibleTypes(ConditionalExpression + // expression, TypeBinding trueType, TypeBinding falseType) { + // this.handle( + // IProblem.IncompatibleTypesInConditionalOperator, + // new String[] {new String(trueType.readableName()), new + // String(falseType.readableName())}, + // new String[] {new String(trueType.sourceName()), new + // String(falseType.sourceName())}, + // expression.sourceStart, + // expression.sourceEnd); + // } + // public void conflictingImport(ImportReference importRef) { + // String[] arguments = new + // String[]{CharOperation.toString(importRef.tokens)}; + // this.handle(IProblem.ConflictingImport, arguments, arguments, + // importRef.sourceStart, importRef.sourceEnd); + // } + public void constantOutOfFormat(NumberLiteral lit) { + // the literal is not in a correct format + // this code is called on IntLiteral and LongLiteral + // example 000811 ...the 8 is uncorrect. + if ((lit instanceof LongLiteral) || (lit instanceof IntLiteral)) { + char[] source = lit.source(); + try { + final String Radix; + final int radix; + if ((source[1] == 'x') || (source[1] == 'X')) { + radix = 16; + Radix = "Hexa"; //$NON-NLS-1$ + } else { + radix = 8; + Radix = "Octal"; //$NON-NLS-1$ + } + // look for the first digit that is incorrect + int place = -1; + label: for (int i = radix == 8 ? 1 : 2; i < source.length; i++) { + if (Character.digit(source[i], radix) == -1) { + place = i; + break label; + } + } + String[] arguments = new String[] { Radix + + " " + + new String(source) + + " (digit " + new String(new char[] { source[place] }) + ")" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + this.handle(IProblem.NumericValueOutOfRange, arguments, + arguments, lit.sourceStart, lit.sourceEnd); + return; + } catch (IndexOutOfBoundsException ex) { + } + // just in case .... use a predefined error.. + // we should never come here...(except if the code changes !) + this.constantOutOfRange(lit); + } + } + + public void constantOutOfRange(Literal lit) { + // lit is some how out of range of it declared type + // example + // 9999999999999999999999999999999999999999999999999999999999999999999 + String[] arguments = new String[] { new String(lit.source()) }; + this.handle(IProblem.NumericValueOutOfRange, arguments, arguments, + lit.sourceStart, lit.sourceEnd); + } + + public void deprecatedField(FieldBinding field, ASTNode location) { + this.handle(IProblem.UsingDeprecatedField, new String[] { + new String(field.declaringClass.readableName()), + new String(field.name) }, new String[] { + new String(field.declaringClass.shortReadableName()), + new String(field.name) }, location.sourceStart, + location.sourceEnd); + } + + public void deprecatedMethod(MethodBinding method, ASTNode location) { + if (method.isConstructor()) + this.handle(IProblem.UsingDeprecatedConstructor, new String[] { + new String(method.declaringClass.readableName()), + parametersAsString(method) }, new String[] { + new String(method.declaringClass.shortReadableName()), + parametersAsShortString(method) }, location.sourceStart, + location.sourceEnd); + else + this.handle(IProblem.UsingDeprecatedMethod, new String[] { + new String(method.declaringClass.readableName()), + new String(method.selector), parametersAsString(method) }, + new String[] { + new String(method.declaringClass + .shortReadableName()), + new String(method.selector), + parametersAsShortString(method) }, + location.sourceStart, location.sourceEnd); + } + + public void deprecatedType(TypeBinding type, ASTNode location) { + if (location == null) + return; // 1G828DN - no type ref for synthetic arguments + this.handle(IProblem.UsingDeprecatedType, new String[] { new String( + type.readableName()) }, new String[] { new String(type + .shortReadableName()) }, location.sourceStart, + location.sourceEnd); + } + + public void duplicateCase(CaseStatement statement, Constant constant) { + String[] arguments = new String[] { String.valueOf(constant.intValue()) }; + this.handle(IProblem.DuplicateCase, arguments, arguments, + statement.sourceStart, statement.sourceEnd); + } + + public void duplicateDefaultCase(DefaultCase statement) { + this.handle(IProblem.DuplicateDefaultCase, NoArgument, NoArgument, + statement.sourceStart, statement.sourceEnd); + } + + public void duplicateFieldInType(SourceTypeBinding type, + FieldDeclaration fieldDecl) { + this.handle(IProblem.DuplicateField, new String[] { + new String(type.sourceName()), fieldDecl.name() }, + new String[] { new String(type.shortReadableName()), + fieldDecl.name() }, fieldDecl.sourceStart, + fieldDecl.sourceEnd); + } + + // public void duplicateImport(ImportReference importRef) { + // String[] arguments = new + // String[]{CharOperation.toString(importRef.tokens)}; + // this.handle(IProblem.DuplicateImport, arguments, arguments, + // importRef.sourceStart, importRef.sourceEnd); + // } + public void duplicateInitializationOfBlankFinalField(FieldBinding field, + Reference reference) { + String[] arguments = new String[] { new String(field.readableName()) }; + this.handle(IProblem.DuplicateBlankFinalFieldInitialization, arguments, + arguments, reference.sourceStart, reference.sourceEnd); + } + + public void duplicateInitializationOfFinalLocal(LocalVariableBinding local, + ASTNode location) { + String[] arguments = new String[] { new String(local.readableName()) }; + this.handle(IProblem.DuplicateFinalLocalInitialization, arguments, + arguments, location.sourceStart, location.sourceEnd); + } + + public void duplicateMethodInType(SourceTypeBinding type, + AbstractMethodDeclaration methodDecl) { + String[] arguments = new String[] { new String(methodDecl.selector), + new String(type.sourceName()) }; + this.handle(IProblem.DuplicateMethod, arguments, arguments, + methodDecl.sourceStart, methodDecl.sourceEnd); + } + + public void duplicateModifierForField(ReferenceBinding type, + FieldDeclaration fieldDecl) { + /* + * to highlight modifiers use: this.handle( new Problem( + * DuplicateModifierForField, new String[] {fieldDecl.name()}, + * fieldDecl.modifiers.sourceStart, fieldDecl.modifiers.sourceEnd)); + */ + String[] arguments = new String[] { fieldDecl.name() }; + this.handle(IProblem.DuplicateModifierForField, arguments, arguments, + fieldDecl.sourceStart, fieldDecl.sourceEnd); + } + + public void duplicateModifierForMethod(ReferenceBinding type, + AbstractMethodDeclaration methodDecl) { + this.handle(IProblem.DuplicateModifierForMethod, + new String[] { new String(type.sourceName()), + new String(methodDecl.selector) }, new String[] { + new String(type.shortReadableName()), + new String(methodDecl.selector) }, + methodDecl.sourceStart, methodDecl.sourceEnd); + } + + public void duplicateModifierForType(SourceTypeBinding type) { + String[] arguments = new String[] { new String(type.sourceName()) }; + this.handle(IProblem.DuplicateModifierForType, arguments, arguments, + type.sourceStart(), type.sourceEnd()); + } + + public void duplicateModifierForVariable(LocalDeclaration localDecl, + boolean complainForArgument) { + String[] arguments = new String[] { localDecl.name() }; + this.handle(complainForArgument ? IProblem.DuplicateModifierForArgument + : IProblem.DuplicateModifierForVariable, arguments, arguments, + localDecl.sourceStart, localDecl.sourceEnd); + } + + public void duplicateNestedType(TypeDeclaration typeDecl) { + String[] arguments = new String[] { new String(typeDecl.name) }; + this.handle(IProblem.DuplicateNestedType, arguments, arguments, + typeDecl.sourceStart, typeDecl.sourceEnd); + } + + public void duplicateSuperinterface(SourceTypeBinding type, + TypeDeclaration typeDecl, ReferenceBinding superType) { + this.handle(IProblem.DuplicateSuperInterface, new String[] { + new String(superType.readableName()), + new String(type.sourceName()) }, new String[] { + new String(superType.shortReadableName()), + new String(type.sourceName()) }, typeDecl.sourceStart, + typeDecl.sourceEnd); + } + + public void duplicateTypes(CompilationUnitDeclaration compUnitDecl, + TypeDeclaration typeDecl) { + String[] arguments = new String[] { + new String(compUnitDecl.getFileName()), + new String(typeDecl.name) }; + this.referenceContext = typeDecl; // report the problem against the + // type not the entire compilation + // unit + this.handle(IProblem.DuplicateTypes, arguments, arguments, + typeDecl.sourceStart, typeDecl.sourceEnd, + compUnitDecl.compilationResult); + } + + public void errorNoMethodFor(MessageSend messageSend, TypeBinding recType, + TypeBinding[] params) { + StringBuffer buffer = new StringBuffer(); + StringBuffer shortBuffer = new StringBuffer(); + for (int i = 0, length = params.length; i < length; i++) { + if (i != 0) { + buffer.append(", "); //$NON-NLS-1$ + shortBuffer.append(", "); //$NON-NLS-1$ + } + buffer.append(new String(params[i].readableName())); + shortBuffer.append(new String(params[i].shortReadableName())); + } + this.handle(recType.isArrayType() ? IProblem.NoMessageSendOnArrayType + : IProblem.NoMessageSendOnBaseType, new String[] { + new String(recType.readableName()), + new String(messageSend.selector), buffer.toString() }, + new String[] { new String(recType.shortReadableName()), + new String(messageSend.selector), + shortBuffer.toString() }, messageSend.sourceStart, + messageSend.sourceEnd); + } + + public void errorThisSuperInStatic(ASTNode reference) { + String[] arguments = new String[] { reference.isSuper() ? "super" : "this" }; //$NON-NLS-2$ //$NON-NLS-1$ + this.handle(IProblem.ThisInStaticContext, arguments, arguments, + reference.sourceStart, reference.sourceEnd); + } + + public void exceptionTypeProblem(SourceTypeBinding type, + AbstractMethodDeclaration methodDecl, TypeReference exceptionType, + TypeBinding expectedType) { + int problemId = expectedType.problemId(); + int id; + switch (problemId) { + case NotFound: + // 1 + id = IProblem.ExceptionTypeNotFound; + break; + case NotVisible: + // 2 + id = IProblem.ExceptionTypeNotVisible; + break; + case Ambiguous: + // 3 + id = IProblem.ExceptionTypeAmbiguous; + break; + case InternalNameProvided: + // 4 + id = IProblem.ExceptionTypeInternalNameProvided; + break; + case InheritedNameHidesEnclosingName: + // 5 + id = IProblem.ExceptionTypeInheritedNameHidesEnclosingName; + break; + case NoError: + // 0 + default: + needImplementation(); // want to fail to see why we were + // here... + return; + } + this.handle(id, new String[] { new String(methodDecl.selector), + new String(expectedType.readableName()) }, new String[] { + new String(methodDecl.selector), + new String(expectedType.shortReadableName()) }, + exceptionType.sourceStart, exceptionType.sourceEnd); + } + + public void expressionShouldBeAVariable(Expression expression) { + this.handle(IProblem.ExpressionShouldBeAVariable, NoArgument, + NoArgument, expression.sourceStart, expression.sourceEnd); + } + + public void fieldsOrThisBeforeConstructorInvocation(ThisReference reference) { + this.handle(IProblem.ThisSuperDuringConstructorInvocation, NoArgument, + NoArgument, reference.sourceStart, reference.sourceEnd); + } + + public void fieldTypeProblem(SourceTypeBinding type, + FieldDeclaration fieldDecl, TypeBinding expectedType) { + int problemId = expectedType.problemId(); + int id; + switch (problemId) { + case NotFound: + // 1 + id = IProblem.FieldTypeNotFound; + break; + case NotVisible: + // 2 + id = IProblem.FieldTypeNotVisible; + break; + case Ambiguous: + // 3 + id = IProblem.FieldTypeAmbiguous; + break; + case InternalNameProvided: + // 4 + id = IProblem.FieldTypeInternalNameProvided; + break; + case InheritedNameHidesEnclosingName: + // 5 + id = IProblem.FieldTypeInheritedNameHidesEnclosingName; + break; + case NoError: + // 0 + default: + needImplementation(); // want to fail to see why we were + // here... + return; + } + this.handle(id, new String[] { fieldDecl.name(), + new String(type.sourceName()), + new String(expectedType.readableName()) }, new String[] { + fieldDecl.name(), new String(type.sourceName()), + new String(expectedType.shortReadableName()) }, + fieldDecl.type.sourceStart, fieldDecl.type.sourceEnd); + } + + public void finalMethodCannotBeOverridden(MethodBinding currentMethod, + MethodBinding inheritedMethod) { + this.handle( + // Cannot override the final method from %1 + // 8.4.3.3 - Final methods cannot be overridden or hidden. + IProblem.FinalMethodCannotBeOverridden, + new String[] { new String(inheritedMethod.declaringClass + .readableName()) }, new String[] { new String( + inheritedMethod.declaringClass.shortReadableName()) }, + currentMethod.sourceStart(), currentMethod.sourceEnd()); + } + + public void forwardReference(Reference reference, int indexInQualification, + TypeBinding type) { + this.handle(IProblem.ReferenceToForwardField, NoArgument, NoArgument, + reference.sourceStart, reference.sourceEnd); + } + + // use this private API when the compilation unit result can be found + // through the + // reference context. Otherwise, use the other API taking a problem and a + // compilation result + // as arguments + private void handle(int problemId, String[] problemArguments, + String[] messageArguments, int problemStartPosition, + int problemEndPosition) { + this.handle(problemId, problemArguments, messageArguments, + problemStartPosition, problemEndPosition, referenceContext, + referenceContext == null ? null : referenceContext + .compilationResult()); + referenceContext = null; + } + + // use this private API when the compilation unit result can be found + // through the + // reference context. Otherwise, use the other API taking a problem and a + // compilation result + // as arguments + private void handle(int problemId, String[] problemArguments, + String[] messageArguments, int severity, int problemStartPosition, + int problemEndPosition) { + this.handle(problemId, problemArguments, messageArguments, severity, + problemStartPosition, problemEndPosition, referenceContext, + referenceContext == null ? null : referenceContext + .compilationResult()); + referenceContext = null; + } + + // use this private API when the compilation unit result cannot be found + // through the + // reference context. + private void handle(int problemId, String[] problemArguments, + String[] messageArguments, int problemStartPosition, + int problemEndPosition, CompilationResult unitResult) { + this.handle(problemId, problemArguments, messageArguments, + problemStartPosition, problemEndPosition, referenceContext, + unitResult); + referenceContext = null; + } + + public void hidingEnclosingType(TypeDeclaration typeDecl) { + String[] arguments = new String[] { new String(typeDecl.name) }; + this.handle(IProblem.HidingEnclosingType, arguments, arguments, + typeDecl.sourceStart, typeDecl.sourceEnd); + } + + public void hierarchyCircularity(SourceTypeBinding sourceType, + ReferenceBinding superType, TypeReference reference) { + int start = 0; + int end = 0; + String typeName = ""; //$NON-NLS-1$ + String shortTypeName = ""; //$NON-NLS-1$ + if (reference == null) { // can only happen when java.lang.Object is + // busted + start = sourceType.sourceStart(); + end = sourceType.sourceEnd(); + typeName = new String(superType.readableName()); + shortTypeName = new String(superType.sourceName()); + } else { + start = reference.sourceStart; + end = reference.sourceEnd; + char[][] qName = reference.getTypeName(); + typeName = CharOperation.toString(qName); + shortTypeName = new String(qName[qName.length - 1]); + } + if (sourceType == superType) + this.handle(IProblem.HierarchyCircularitySelfReference, + new String[] { new String(sourceType.sourceName()), + typeName }, + new String[] { new String(sourceType.sourceName()), + shortTypeName }, start, end); + else + this.handle(IProblem.HierarchyCircularity, new String[] { + new String(sourceType.sourceName()), typeName }, + new String[] { new String(sourceType.sourceName()), + shortTypeName }, start, end); + } + + public void hierarchyHasProblems(SourceTypeBinding type) { + String[] arguments = new String[] { new String(type.sourceName()) }; + this.handle(IProblem.HierarchyHasProblems, arguments, arguments, type + .sourceStart(), type.sourceEnd()); + } + + public void illegalAbstractModifierCombinationForMethod( + ReferenceBinding type, AbstractMethodDeclaration methodDecl) { + String[] arguments = new String[] { new String(type.sourceName()), + new String(methodDecl.selector) }; + this.handle(IProblem.IllegalAbstractModifierCombinationForMethod, + arguments, arguments, methodDecl.sourceStart, + methodDecl.sourceEnd); + } + + public void illegalModifierCombinationFinalAbstractForClass( + SourceTypeBinding type) { + String[] arguments = new String[] { new String(type.sourceName()) }; + this.handle(IProblem.IllegalModifierCombinationFinalAbstractForClass, + arguments, arguments, type.sourceStart(), type.sourceEnd()); + } + + public void illegalModifierCombinationFinalVolatileForField( + ReferenceBinding type, FieldDeclaration fieldDecl) { + String[] arguments = new String[] { fieldDecl.name() }; + this.handle(IProblem.IllegalModifierCombinationFinalVolatileForField, + arguments, arguments, fieldDecl.sourceStart, + fieldDecl.sourceEnd); + } + + public void illegalModifierForClass(SourceTypeBinding type) { + String[] arguments = new String[] { new String(type.sourceName()) }; + this.handle(IProblem.IllegalModifierForClass, arguments, arguments, + type.sourceStart(), type.sourceEnd()); + } + + public void illegalModifierForField(ReferenceBinding type, + FieldDeclaration fieldDecl) { + String[] arguments = new String[] { fieldDecl.name() }; + this.handle(IProblem.IllegalModifierForField, arguments, arguments, + fieldDecl.sourceStart, fieldDecl.sourceEnd); + } + + public void illegalModifierForInterface(SourceTypeBinding type) { + String[] arguments = new String[] { new String(type.sourceName()) }; + this.handle(IProblem.IllegalModifierForInterface, arguments, arguments, + type.sourceStart(), type.sourceEnd()); + } + + public void illegalModifierForInterfaceField(ReferenceBinding type, + FieldDeclaration fieldDecl) { + String[] arguments = new String[] { fieldDecl.name() }; + this.handle(IProblem.IllegalModifierForInterfaceField, arguments, + arguments, fieldDecl.sourceStart, fieldDecl.sourceEnd); + } + + public void illegalModifierForInterfaceMethod(ReferenceBinding type, + AbstractMethodDeclaration methodDecl) { + String[] arguments = new String[] { new String(type.sourceName()), + new String(methodDecl.selector) }; + this.handle(IProblem.IllegalModifierForInterfaceMethod, arguments, + arguments, methodDecl.sourceStart, methodDecl.sourceEnd); + } + + public void illegalModifierForLocalClass(SourceTypeBinding type) { + String[] arguments = new String[] { new String(type.sourceName()) }; + this.handle(IProblem.IllegalModifierForLocalClass, arguments, + arguments, type.sourceStart(), type.sourceEnd()); + } + + public void illegalModifierForMemberClass(SourceTypeBinding type) { + String[] arguments = new String[] { new String(type.sourceName()) }; + this.handle(IProblem.IllegalModifierForMemberClass, arguments, + arguments, type.sourceStart(), type.sourceEnd()); + } + + public void illegalModifierForMemberInterface(SourceTypeBinding type) { + String[] arguments = new String[] { new String(type.sourceName()) }; + this.handle(IProblem.IllegalModifierForMemberInterface, arguments, + arguments, type.sourceStart(), type.sourceEnd()); + } + + public void illegalModifierForMethod(ReferenceBinding type, + AbstractMethodDeclaration methodDecl) { + String[] arguments = new String[] { new String(type.sourceName()), + new String(methodDecl.selector) }; + this.handle(IProblem.IllegalModifierForMethod, arguments, arguments, + methodDecl.sourceStart, methodDecl.sourceEnd); + } + + public void illegalModifierForVariable(LocalDeclaration localDecl, + boolean complainAsArgument) { + String[] arguments = new String[] { localDecl.name() }; + this.handle(complainAsArgument ? IProblem.IllegalModifierForArgument + : IProblem.IllegalModifierForVariable, arguments, arguments, + localDecl.sourceStart, localDecl.sourceEnd); + } + + public void illegalPrimitiveOrArrayTypeForEnclosingInstance( + TypeBinding enclosingType, ASTNode location) { + this.handle(IProblem.IllegalPrimitiveOrArrayTypeForEnclosingInstance, + new String[] { new String(enclosingType.readableName()) }, + new String[] { new String(enclosingType.shortReadableName()) }, + location.sourceStart, location.sourceEnd); + } + + public void illegalStaticModifierForMemberType(SourceTypeBinding type) { + String[] arguments = new String[] { new String(type.sourceName()) }; + this.handle(IProblem.IllegalStaticModifierForMemberType, arguments, + arguments, type.sourceStart(), type.sourceEnd()); + } + + public void illegalVisibilityModifierCombinationForField( + ReferenceBinding type, FieldDeclaration fieldDecl) { + String[] arguments = new String[] { new String(fieldDecl.name()) }; + this.handle(IProblem.IllegalVisibilityModifierCombinationForField, + arguments, arguments, fieldDecl.sourceStart, + fieldDecl.sourceEnd); + } + + public void illegalVisibilityModifierCombinationForMemberType( + SourceTypeBinding type) { + String[] arguments = new String[] { new String(type.sourceName()) }; + this.handle(IProblem.IllegalVisibilityModifierCombinationForMemberType, + arguments, arguments, type.sourceStart(), type.sourceEnd()); + } + + public void illegalVisibilityModifierCombinationForMethod( + ReferenceBinding type, AbstractMethodDeclaration methodDecl) { + String[] arguments = new String[] { new String(type.sourceName()), + new String(methodDecl.selector) }; + this.handle(IProblem.IllegalVisibilityModifierCombinationForMethod, + arguments, arguments, methodDecl.sourceStart, + methodDecl.sourceEnd); + } + + public void illegalVisibilityModifierForInterfaceMemberType( + SourceTypeBinding type) { + String[] arguments = new String[] { new String(type.sourceName()) }; + this.handle(IProblem.IllegalVisibilityModifierForInterfaceMemberType, + arguments, arguments, type.sourceStart(), type.sourceEnd()); + } + + public void illegalVoidExpression(ASTNode location) { + this.handle(IProblem.InvalidVoidExpression, NoArgument, NoArgument, + location.sourceStart, location.sourceEnd); + } + + // public void importProblem(ImportReference importRef, Binding + // expectedImport) { + // int problemId = expectedImport.problemId(); + // int id; + // switch (problemId) { + // case NotFound : + // // 1 + // id = IProblem.ImportNotFound; + // break; + // case NotVisible : + // // 2 + // id = IProblem.ImportNotVisible; + // break; + // case Ambiguous : + // // 3 + // id = IProblem.ImportAmbiguous; + // break; + // case InternalNameProvided : + // // 4 + // id = IProblem.ImportInternalNameProvided; + // break; + // case InheritedNameHidesEnclosingName : + // // 5 + // id = IProblem.ImportInheritedNameHidesEnclosingName; + // break; + // case NoError : + // // 0 + // default : + // needImplementation(); // want to fail to see why we were + // // here... + // return; + // } + // String argument; + // if (expectedImport instanceof ProblemReferenceBinding) { + // argument = CharOperation + // .toString(((ProblemReferenceBinding) expectedImport).compoundName); + // } else { + // argument = CharOperation.toString(importRef.tokens); + // } + // String[] arguments = new String[]{argument}; + // this.handle(id, arguments, arguments, importRef.sourceStart, + // importRef.sourceEnd); + // } + public void incompatibleExceptionInThrowsClause(SourceTypeBinding type, + MethodBinding currentMethod, MethodBinding inheritedMethod, + ReferenceBinding exceptionType) { + if (type == currentMethod.declaringClass) { + int id; + if (currentMethod.declaringClass.isInterface() + && !inheritedMethod.isPublic()) { // interface inheriting + // Object protected + // method + id = IProblem.IncompatibleExceptionInThrowsClauseForNonInheritedInterfaceMethod; + } else { + id = IProblem.IncompatibleExceptionInThrowsClause; + } + this + .handle( + // Exception %1 is not compatible with throws + // clause in %2 + // 9.4.4 - The type of exception in the throws + // clause is incompatible. + id, + new String[] { + new String(exceptionType.sourceName()), + new String( + CharOperation + .concat( + inheritedMethod.declaringClass + .readableName(), + inheritedMethod + .readableName(), + '.')) }, + new String[] { + new String(exceptionType.sourceName()), + new String( + CharOperation + .concat( + inheritedMethod.declaringClass + .shortReadableName(), + inheritedMethod + .shortReadableName(), + '.')) }, + currentMethod.sourceStart(), currentMethod + .sourceEnd()); + } else + this + .handle( + // Exception %1 in throws clause of %2 is not + // compatible with %3 + // 9.4.4 - The type of exception in the throws + // clause is incompatible. + IProblem.IncompatibleExceptionInInheritedMethodThrowsClause, + new String[] { + new String(exceptionType.sourceName()), + new String(CharOperation.concat( + currentMethod.declaringClass + .sourceName(), + currentMethod.readableName(), '.')), + new String( + CharOperation + .concat( + inheritedMethod.declaringClass + .readableName(), + inheritedMethod + .readableName(), + '.')) }, + new String[] { + new String(exceptionType.sourceName()), + new String(CharOperation.concat( + currentMethod.declaringClass + .sourceName(), + currentMethod.shortReadableName(), + '.')), + new String( + CharOperation + .concat( + inheritedMethod.declaringClass + .shortReadableName(), + inheritedMethod + .shortReadableName(), + '.')) }, type + .sourceStart(), type.sourceEnd()); + } + + public void incompatibleReturnType(MethodBinding currentMethod, + MethodBinding inheritedMethod) { + StringBuffer methodSignature = new StringBuffer(); + methodSignature.append(inheritedMethod.declaringClass.readableName()) + .append('.').append(inheritedMethod.readableName()); + StringBuffer shortSignature = new StringBuffer(); + shortSignature.append( + inheritedMethod.declaringClass.shortReadableName()).append('.') + .append(inheritedMethod.shortReadableName()); + int id; + if (currentMethod.declaringClass.isInterface() + && !inheritedMethod.isPublic()) { // interface inheriting + // Object protected method + id = IProblem.IncompatibleReturnTypeForNonInheritedInterfaceMethod; + } else { + id = IProblem.IncompatibleReturnType; + } + this.handle(id, new String[] { methodSignature.toString() }, + new String[] { shortSignature.toString() }, currentMethod + .sourceStart(), currentMethod.sourceEnd()); + } + + public void incorrectLocationForEmptyDimension( + ArrayAllocationExpression expression, int index) { + this.handle(IProblem.IllegalDimension, NoArgument, NoArgument, + expression.dimensions[index + 1].sourceStart, + expression.dimensions[index + 1].sourceEnd); + } + + public void incorrectSwitchType(Expression expression, TypeBinding testType) { + this.handle(IProblem.IncorrectSwitchType, new String[] { new String( + testType.readableName()) }, new String[] { new String(testType + .shortReadableName()) }, expression.sourceStart, + expression.sourceEnd); + } + + public void inheritedMethodReducesVisibility(SourceTypeBinding type, + MethodBinding concreteMethod, MethodBinding[] abstractMethods) { + StringBuffer concreteSignature = new StringBuffer(); + concreteSignature.append(concreteMethod.declaringClass.readableName()) + .append('.').append(concreteMethod.readableName()); + StringBuffer shortSignature = new StringBuffer(); + shortSignature + .append(concreteMethod.declaringClass.shortReadableName()) + .append('.').append(concreteMethod.shortReadableName()); + this.handle( + // The inherited method %1 cannot hide the public abstract + // method in %2 + IProblem.InheritedMethodReducesVisibility, new String[] { + new String(concreteSignature.toString()), + new String(abstractMethods[0].declaringClass + .readableName()) }, new String[] { + new String(shortSignature.toString()), + new String(abstractMethods[0].declaringClass + .shortReadableName()) }, type.sourceStart(), + type.sourceEnd()); + } + + public void inheritedMethodsHaveIncompatibleReturnTypes( + SourceTypeBinding type, MethodBinding[] inheritedMethods, int length) { + StringBuffer methodSignatures = new StringBuffer(); + StringBuffer shortSignatures = new StringBuffer(); + for (int i = length; --i >= 0;) { + methodSignatures.append( + inheritedMethods[i].declaringClass.readableName()).append( + '.').append(inheritedMethods[i].readableName()); + shortSignatures.append( + inheritedMethods[i].declaringClass.shortReadableName()) + .append('.') + .append(inheritedMethods[i].shortReadableName()); + if (i != 0) { + methodSignatures.append(", "); //$NON-NLS-1$ + shortSignatures.append(", "); //$NON-NLS-1$ + } + } + this.handle( + // Return type is incompatible with %1 + // 9.4.2 - The return type from the method is incompatible with + // the declaration. + IProblem.IncompatibleReturnType, + new String[] { methodSignatures.toString() }, + new String[] { shortSignatures.toString() }, + type.sourceStart(), type.sourceEnd()); + } + + public void initializerMustCompleteNormally(FieldDeclaration fieldDecl) { + this.handle(IProblem.InitializerMustCompleteNormally, NoArgument, + NoArgument, fieldDecl.sourceStart, fieldDecl.sourceEnd); + } + + public void innerTypesCannotDeclareStaticInitializers( + ReferenceBinding innerType, ASTNode location) { + this.handle(IProblem.CannotDefineStaticInitializerInLocalType, + new String[] { new String(innerType.readableName()) }, + new String[] { new String(innerType.shortReadableName()) }, + location.sourceStart, location.sourceEnd); + } + + public void interfaceCannotHaveConstructors( + ConstructorDeclaration constructor) { + this.handle(IProblem.InterfaceCannotHaveConstructors, NoArgument, + NoArgument, constructor.sourceStart, constructor.sourceEnd, + constructor, constructor.compilationResult()); + } + + public void interfaceCannotHaveInitializers(SourceTypeBinding type, + FieldDeclaration fieldDecl) { + String[] arguments = new String[] { new String(type.sourceName()) }; + this.handle(IProblem.InterfaceCannotHaveInitializers, arguments, + arguments, fieldDecl.sourceStart, fieldDecl.sourceEnd); + } + + public void invalidBreak(ASTNode location) { + this.handle(IProblem.InvalidBreak, NoArgument, NoArgument, + location.sourceStart, location.sourceEnd); + } + + public void invalidConstructor(Statement statement, + MethodBinding targetConstructor) { + boolean insideDefaultConstructor = (referenceContext instanceof ConstructorDeclaration) + && ((ConstructorDeclaration) referenceContext) + .isDefaultConstructor(); + boolean insideImplicitConstructorCall = (statement instanceof ExplicitConstructorCall) + && (((ExplicitConstructorCall) statement).accessMode == ExplicitConstructorCall.ImplicitSuper); + int flag = IProblem.UndefinedConstructor; // default... + switch (targetConstructor.problemId()) { + case NotFound: + if (insideDefaultConstructor) { + flag = IProblem.UndefinedConstructorInDefaultConstructor; + } else if (insideImplicitConstructorCall) { + flag = IProblem.UndefinedConstructorInImplicitConstructorCall; + } else { + flag = IProblem.UndefinedConstructor; + } + break; + case NotVisible: + if (insideDefaultConstructor) { + flag = IProblem.NotVisibleConstructorInDefaultConstructor; + } else if (insideImplicitConstructorCall) { + flag = IProblem.NotVisibleConstructorInImplicitConstructorCall; + } else { + flag = IProblem.NotVisibleConstructor; + } + break; + case Ambiguous: + if (insideDefaultConstructor) { + flag = IProblem.AmbiguousConstructorInDefaultConstructor; + } else if (insideImplicitConstructorCall) { + flag = IProblem.AmbiguousConstructorInImplicitConstructorCall; + } else { + flag = IProblem.AmbiguousConstructor; + } + break; + case NoError: + // 0 + default: + needImplementation(); // want to fail to see why we were + // here... + break; + } + this.handle(flag, new String[] { + new String(targetConstructor.declaringClass.readableName()), + parametersAsString(targetConstructor) }, + new String[] { + new String(targetConstructor.declaringClass + .shortReadableName()), + parametersAsShortString(targetConstructor) }, + statement.sourceStart, statement.sourceEnd); + } + + public void invalidContinue(ASTNode location) { + this.handle(IProblem.InvalidContinue, NoArgument, NoArgument, + location.sourceStart, location.sourceEnd); + } + + public void invalidEnclosingType(Expression expression, TypeBinding type, + ReferenceBinding enclosingType) { + if (enclosingType.isAnonymousType()) + enclosingType = enclosingType.superclass(); + int flag = IProblem.UndefinedType; // default + switch (type.problemId()) { + case NotFound: + // 1 + flag = IProblem.UndefinedType; + break; + case NotVisible: + // 2 + flag = IProblem.NotVisibleType; + break; + case Ambiguous: + // 3 + flag = IProblem.AmbiguousType; + break; + case InternalNameProvided: + flag = IProblem.InternalTypeNameProvided; + break; + case NoError: + // 0 + default: + needImplementation(); // want to fail to see why we were + // here... + break; + } + this.handle(flag, new String[] { new String(enclosingType + .readableName()) + + "." + new String(type.readableName()) }, //$NON-NLS-1$ + new String[] { new String(enclosingType.shortReadableName()) + + "." + new String(type.shortReadableName()) }, //$NON-NLS-1$ + expression.sourceStart, expression.sourceEnd); + } + + public void invalidExpressionAsStatement(Expression expression) { + this.handle(IProblem.InvalidExpressionAsStatement, NoArgument, + NoArgument, expression.sourceStart, expression.sourceEnd); + } + + public void invalidField(FieldReference fieldRef, TypeBinding searchedType) { + int severity = Error; + int flag = IProblem.UndefinedField; + FieldBinding field = fieldRef.binding; + switch (field.problemId()) { + case NotFound: + flag = IProblem.UndefinedField; + /* + * also need to check that the searchedType is the receiver type if + * (searchedType.isHierarchyInconsistent()) severity = + * SecondaryError; + */ + break; + case NotVisible: + flag = IProblem.NotVisibleField; + break; + case Ambiguous: + flag = IProblem.AmbiguousField; + break; + case NonStaticReferenceInStaticContext: + flag = IProblem.NonStaticFieldFromStaticInvocation; + break; + case NonStaticReferenceInConstructorInvocation: + flag = IProblem.InstanceFieldDuringConstructorInvocation; + break; + case InheritedNameHidesEnclosingName: + flag = IProblem.InheritedFieldHidesEnclosingName; + break; + case ReceiverTypeNotVisible: + this.handle(IProblem.NotVisibleType, new String[] { new String( + searchedType.leafComponentType().readableName()) }, + new String[] { new String(searchedType.leafComponentType() + .shortReadableName()) }, + fieldRef.receiver.sourceStart, fieldRef.receiver.sourceEnd); + return; + case NoError: + // 0 + default: + needImplementation(); // want to fail to see why we were + // here... + break; + } + String[] arguments = new String[] { new String(field.readableName()) }; + this.handle(flag, arguments, arguments, severity, fieldRef.sourceStart, + fieldRef.sourceEnd); + } + + public void invalidField(NameReference nameRef, FieldBinding field) { + int flag = IProblem.UndefinedField; + switch (field.problemId()) { + case NotFound: + flag = IProblem.UndefinedField; + break; + case NotVisible: + flag = IProblem.NotVisibleField; + break; + case Ambiguous: + flag = IProblem.AmbiguousField; + break; + case NonStaticReferenceInStaticContext: + flag = IProblem.NonStaticFieldFromStaticInvocation; + break; + case NonStaticReferenceInConstructorInvocation: + flag = IProblem.InstanceFieldDuringConstructorInvocation; + break; + case InheritedNameHidesEnclosingName: + flag = IProblem.InheritedFieldHidesEnclosingName; + break; + case ReceiverTypeNotVisible: + this.handle(IProblem.NotVisibleType, new String[] { new String( + field.declaringClass.leafComponentType().readableName()) }, + new String[] { new String(field.declaringClass + .leafComponentType().shortReadableName()) }, + nameRef.sourceStart, nameRef.sourceEnd); + return; + case NoError: + // 0 + default: + needImplementation(); // want to fail to see why we were + // here... + break; + } + String[] arguments = new String[] { new String(field.readableName()) }; + this.handle(flag, arguments, arguments, nameRef.sourceStart, + nameRef.sourceEnd); + } + + public void invalidField(QualifiedNameReference nameRef, + FieldBinding field, int index, TypeBinding searchedType) { + // the resolution of the index-th field of qname failed + // qname.otherBindings[index] is the binding that has produced the + // error + // The different targetted errors should be : + // UndefinedField + // NotVisibleField + // AmbiguousField + if (searchedType.isBaseType()) { + this.handle(IProblem.NoFieldOnBaseType, new String[] { + new String(searchedType.readableName()), + CharOperation.toString(CharOperation.subarray( + nameRef.tokens, 0, index)), + new String(nameRef.tokens[index]) }, new String[] { + new String(searchedType.sourceName()), + CharOperation.toString(CharOperation.subarray( + nameRef.tokens, 0, index)), + new String(nameRef.tokens[index]) }, nameRef.sourceStart, + nameRef.sourceEnd); + return; + } + int flag = IProblem.UndefinedField; + switch (field.problemId()) { + case NotFound: + flag = IProblem.UndefinedField; + /* + * also need to check that the searchedType is the receiver type if + * (searchedType.isHierarchyInconsistent()) severity = + * SecondaryError; + */ + break; + case NotVisible: + flag = IProblem.NotVisibleField; + break; + case Ambiguous: + flag = IProblem.AmbiguousField; + break; + case NonStaticReferenceInStaticContext: + flag = IProblem.NonStaticFieldFromStaticInvocation; + break; + case NonStaticReferenceInConstructorInvocation: + flag = IProblem.InstanceFieldDuringConstructorInvocation; + break; + case InheritedNameHidesEnclosingName: + flag = IProblem.InheritedFieldHidesEnclosingName; + break; + case ReceiverTypeNotVisible: + this.handle(IProblem.NotVisibleType, new String[] { new String( + searchedType.leafComponentType().readableName()) }, + new String[] { new String(searchedType.leafComponentType() + .shortReadableName()) }, nameRef.sourceStart, + nameRef.sourceEnd); + return; + case NoError: + // 0 + default: + needImplementation(); // want to fail to see why we were + // here... + break; + } + String[] arguments = new String[] { CharOperation + .toString(CharOperation.subarray(nameRef.tokens, 0, index + 1)) }; + this.handle(flag, arguments, arguments, nameRef.sourceStart, + nameRef.sourceEnd); + } + + public void invalidMethod(MessageSend messageSend, MethodBinding method) { + // CODE should be UPDATED according to error coding in the different + // method binding errors + // The different targetted errors should be : + // UndefinedMethod + // NotVisibleMethod + // AmbiguousMethod + // InheritedNameHidesEnclosingName + // InstanceMethodDuringConstructorInvocation + // StaticMethodRequested + int flag = IProblem.UndefinedMethod; // default... + switch (method.problemId()) { + case NotFound: + flag = IProblem.UndefinedMethod; + break; + case NotVisible: + flag = IProblem.NotVisibleMethod; + break; + case Ambiguous: + flag = IProblem.AmbiguousMethod; + break; + case InheritedNameHidesEnclosingName: + flag = IProblem.InheritedMethodHidesEnclosingName; + break; + case NonStaticReferenceInConstructorInvocation: + flag = IProblem.InstanceMethodDuringConstructorInvocation; + break; + case NonStaticReferenceInStaticContext: + flag = IProblem.StaticMethodRequested; + break; + case ReceiverTypeNotVisible: + this.handle(IProblem.NotVisibleType, + new String[] { new String(method.declaringClass + .leafComponentType().readableName()) }, + new String[] { new String(method.declaringClass + .leafComponentType().shortReadableName()) }, + messageSend.receiver.sourceStart, + messageSend.receiver.sourceEnd); + return; + case NoError: + // 0 + default: + needImplementation(); // want to fail to see why we were + // here... + break; + } + if (flag == IProblem.UndefinedMethod) { + ProblemMethodBinding problemMethod = (ProblemMethodBinding) method; + if (problemMethod.closestMatch != null) { + String closestParameterTypeNames = parametersAsString(problemMethod.closestMatch); + String parameterTypeNames = parametersAsString(method); + String closestParameterTypeShortNames = parametersAsShortString(problemMethod.closestMatch); + String parameterTypeShortNames = parametersAsShortString(method); + if (closestParameterTypeShortNames + .equals(parameterTypeShortNames)) { + closestParameterTypeShortNames = closestParameterTypeNames; + parameterTypeShortNames = parameterTypeNames; + } + this + .handle( + IProblem.ParameterMismatch, + new String[] { + new String( + problemMethod.closestMatch.declaringClass + .readableName()), + new String( + problemMethod.closestMatch.selector), + closestParameterTypeNames, + parameterTypeNames }, + new String[] { + new String( + problemMethod.closestMatch.declaringClass + .shortReadableName()), + new String( + problemMethod.closestMatch.selector), + closestParameterTypeShortNames, + parameterTypeShortNames }, + (int) (messageSend.nameSourcePosition >>> 32), + (int) messageSend.nameSourcePosition); + return; + } + } + this.handle(flag, new String[] { + new String(method.declaringClass.readableName()), + new String(method.selector), parametersAsString(method) }, + new String[] { + new String(method.declaringClass.shortReadableName()), + new String(method.selector), + parametersAsShortString(method) }, + (int) (messageSend.nameSourcePosition >>> 32), + (int) messageSend.nameSourcePosition); + } + + public void invalidNullToSynchronize(Expression expression) { + this.handle(IProblem.InvalidNullToSynchronized, NoArgument, NoArgument, + expression.sourceStart, expression.sourceEnd); + } + + public void invalidOperator(BinaryExpression expression, + TypeBinding leftType, TypeBinding rightType) { + String leftName = new String(leftType.readableName()); + String rightName = new String(rightType.readableName()); + String leftShortName = new String(leftType.shortReadableName()); + String rightShortName = new String(rightType.shortReadableName()); + if (leftShortName.equals(rightShortName)) { + leftShortName = leftName; + rightShortName = rightName; + } + this.handle(IProblem.InvalidOperator, new String[] { + expression.operatorToString(), leftName + ", " + rightName }, //$NON-NLS-1$ + new String[] { expression.operatorToString(), + leftShortName + ", " + rightShortName }, //$NON-NLS-1$ + expression.sourceStart, expression.sourceEnd); + } + + public void invalidOperator(CompoundAssignment assign, + TypeBinding leftType, TypeBinding rightType) { + String leftName = new String(leftType.readableName()); + String rightName = new String(rightType.readableName()); + String leftShortName = new String(leftType.shortReadableName()); + String rightShortName = new String(rightType.shortReadableName()); + if (leftShortName.equals(rightShortName)) { + leftShortName = leftName; + rightShortName = rightName; + } + this.handle(IProblem.InvalidOperator, new String[] { + assign.operatorToString(), leftName + ", " + rightName }, //$NON-NLS-1$ + new String[] { assign.operatorToString(), + leftShortName + ", " + rightShortName }, //$NON-NLS-1$ + assign.sourceStart, assign.sourceEnd); + } + + public void invalidOperator(UnaryExpression expression, TypeBinding type) { + this.handle(IProblem.InvalidOperator, + new String[] { expression.operatorToString(), + new String(type.readableName()) }, new String[] { + expression.operatorToString(), + new String(type.shortReadableName()) }, + expression.sourceStart, expression.sourceEnd); + } + + public void invalidParenthesizedExpression(ASTNode reference) { + this.handle(IProblem.InvalidParenthesizedExpression, NoArgument, + NoArgument, reference.sourceStart, reference.sourceEnd); + } + + public void invalidSuperclass(SourceTypeBinding type, + TypeReference superclassRef, ReferenceBinding expectedType) { + int problemId = expectedType.problemId(); + int id; + switch (problemId) { + case NotFound: + // 1 + id = IProblem.SuperclassNotFound; + break; + case NotVisible: + // 2 + id = IProblem.SuperclassNotVisible; + break; + case Ambiguous: + // 3 + id = IProblem.SuperclassAmbiguous; + break; + case InternalNameProvided: + // 4 + id = IProblem.SuperclassInternalNameProvided; + break; + case InheritedNameHidesEnclosingName: + // 5 + id = IProblem.SuperclassInheritedNameHidesEnclosingName; + break; + case NoError: + // 0 + default: + needImplementation(); // want to fail to see why we were + // here... + return; + } + this.handle(id, new String[] { new String(expectedType.readableName()), + new String(type.sourceName()) }, new String[] { + new String(expectedType.shortReadableName()), + new String(type.sourceName()) }, superclassRef.sourceStart, + superclassRef.sourceEnd); + } + + public void invalidSuperinterface(SourceTypeBinding type, + TypeReference superinterfaceRef, ReferenceBinding expectedType) { + int problemId = expectedType.problemId(); + int id; + switch (problemId) { + case NotFound: + // 1 + id = IProblem.InterfaceNotFound; + break; + case NotVisible: + // 2 + id = IProblem.InterfaceNotVisible; + break; + case Ambiguous: + // 3 + id = IProblem.InterfaceAmbiguous; + break; + case InternalNameProvided: + // 4 + id = IProblem.InterfaceInternalNameProvided; + break; + case InheritedNameHidesEnclosingName: + // 5 + id = IProblem.InterfaceInheritedNameHidesEnclosingName; + break; + case NoError: + // 0 + default: + needImplementation(); // want to fail to see why we were + // here... + return; + } + this.handle(id, new String[] { new String(expectedType.readableName()), + new String(type.sourceName()) }, new String[] { + new String(expectedType.shortReadableName()), + new String(type.sourceName()) }, superinterfaceRef.sourceStart, + superinterfaceRef.sourceEnd); + } + + public void invalidType(ASTNode location, TypeBinding type) { + int flag = IProblem.UndefinedType; // default + switch (type.problemId()) { + case NotFound: + flag = IProblem.UndefinedType; + break; + case NotVisible: + flag = IProblem.NotVisibleType; + break; + case Ambiguous: + flag = IProblem.AmbiguousType; + break; + case InternalNameProvided: + flag = IProblem.InternalTypeNameProvided; + break; + case InheritedNameHidesEnclosingName: + flag = IProblem.InheritedTypeHidesEnclosingName; + break; + case NoError: + // 0 + default: + needImplementation(); // want to fail to see why we were + // here... + break; + } + this.handle(flag, new String[] { new String(type.readableName()) }, + new String[] { new String(type.shortReadableName()) }, + location.sourceStart, location.sourceEnd); + } + + public void invalidTypeReference(Expression expression) { + this.handle(IProblem.InvalidTypeExpression, NoArgument, NoArgument, + expression.sourceStart, expression.sourceEnd); + } + + public void invalidTypeToSynchronize(Expression expression, TypeBinding type) { + this.handle(IProblem.InvalidTypeToSynchronized, + new String[] { new String(type.readableName()) }, + new String[] { new String(type.shortReadableName()) }, + expression.sourceStart, expression.sourceEnd); + } + + public void invalidUnaryExpression(Expression expression) { + this.handle(IProblem.InvalidUnaryExpression, NoArgument, NoArgument, + expression.sourceStart, expression.sourceEnd); + } + + public void isClassPathCorrect(char[][] wellKnownTypeName, + CompilationUnitDeclaration compUnitDecl) { + referenceContext = compUnitDecl; + String[] arguments = new String[] { CharOperation + .toString(wellKnownTypeName) }; + this.handle(IProblem.IsClassPathCorrect, arguments, arguments, + AbortCompilation | Error, compUnitDecl == null ? 0 + : compUnitDecl.sourceStart, compUnitDecl == null ? 1 + : compUnitDecl.sourceEnd); + } + + public void javadocDuplicatedReturnTag(int sourceStart, int sourceEnd) { + this.handle(IProblem.JavadocDuplicateReturnTag, NoArgument, NoArgument, + sourceStart, sourceEnd); + } + + public void javadocDeprecatedField(FieldBinding field, ASTNode location, + int modifiers) { + if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, + modifiers)) { + this.handle(IProblem.JavadocUsingDeprecatedField, new String[] { + new String(field.declaringClass.readableName()), + new String(field.name) }, new String[] { + new String(field.declaringClass.shortReadableName()), + new String(field.name) }, location.sourceStart, + location.sourceEnd); + } + } + + public void javadocDeprecatedMethod(MethodBinding method, ASTNode location, + int modifiers) { + if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, + modifiers)) { + if (method.isConstructor()) { + this + .handle(IProblem.JavadocUsingDeprecatedConstructor, + new String[] { + new String(method.declaringClass + .readableName()), + parametersAsString(method) }, + new String[] { + new String(method.declaringClass + .shortReadableName()), + parametersAsShortString(method) }, + location.sourceStart, location.sourceEnd); + } else { + this + .handle(IProblem.JavadocUsingDeprecatedMethod, + new String[] { + new String(method.declaringClass + .readableName()), + new String(method.selector), + parametersAsString(method) }, + new String[] { + new String(method.declaringClass + .shortReadableName()), + new String(method.selector), + parametersAsShortString(method) }, + location.sourceStart, location.sourceEnd); + } + } + } + + public void javadocDeprecatedType(TypeBinding type, ASTNode location, + int modifiers) { + if (location == null) + return; // 1G828DN - no type ref for synthetic arguments + if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, + modifiers)) { + this.handle(IProblem.JavadocUsingDeprecatedType, + new String[] { new String(type.readableName()) }, + new String[] { new String(type.shortReadableName()) }, + location.sourceStart, location.sourceEnd); + } + } + + // public void javadocDuplicatedParamTag(JavadocSingleNameReference param, + // int modifiers) { + // if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, + // modifiers)) { + // String[] arguments = new String[] {String.valueOf(param.token)}; + // this.handle(IProblem.JavadocDuplicateParamName, arguments, arguments, + // param.sourceStart, param.sourceEnd); + // } + // } + public void javadocDuplicatedThrowsClassName(TypeReference typeReference, + int modifiers) { + if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, + modifiers)) { + String[] arguments = new String[] { String + .valueOf(typeReference.resolvedType.sourceName()) }; + this.handle(IProblem.JavadocDuplicateThrowsClassName, arguments, + arguments, typeReference.sourceStart, + typeReference.sourceEnd); + } + } + + public void javadocErrorNoMethodFor(MessageSend messageSend, + TypeBinding recType, TypeBinding[] params, int modifiers) { + StringBuffer buffer = new StringBuffer(); + StringBuffer shortBuffer = new StringBuffer(); + for (int i = 0, length = params.length; i < length; i++) { + if (i != 0) { + buffer.append(", "); //$NON-NLS-1$ + shortBuffer.append(", "); //$NON-NLS-1$ + } + buffer.append(new String(params[i].readableName())); + shortBuffer.append(new String(params[i].shortReadableName())); + } + + int id = recType.isArrayType() ? IProblem.JavadocNoMessageSendOnArrayType + : IProblem.JavadocNoMessageSendOnBaseType; + if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, + modifiers)) { + this.handle(id, new String[] { new String(recType.readableName()), + new String(messageSend.selector), buffer.toString() }, + new String[] { new String(recType.shortReadableName()), + new String(messageSend.selector), + shortBuffer.toString() }, messageSend.sourceStart, + messageSend.sourceEnd); + } + } + + public void javadocInvalidConstructor(Statement statement, + MethodBinding targetConstructor, int modifiers) { + + if (!javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, + modifiers)) { + return; + } + // boolean insideDefaultConstructor = + // (this.referenceContext instanceof ConstructorDeclaration) + // && + // ((ConstructorDeclaration)this.referenceContext).isDefaultConstructor(); + // boolean insideImplicitConstructorCall = + // (statement instanceof ExplicitConstructorCall) + // && (((ExplicitConstructorCall) statement).accessMode == + // ExplicitConstructorCall.ImplicitSuper); + + int id = IProblem.JavadocUndefinedConstructor; // default... + switch (targetConstructor.problemId()) { + case NotFound: + // if (insideDefaultConstructor){ + // id = IProblem.JavadocUndefinedConstructorInDefaultConstructor; + // } else if (insideImplicitConstructorCall){ + // id = + // IProblem.JavadocUndefinedConstructorInImplicitConstructorCall; + // } else { + id = IProblem.JavadocUndefinedConstructor; + // } + break; + case NotVisible: + // if (insideDefaultConstructor){ + // id = IProblem.JavadocNotVisibleConstructorInDefaultConstructor; + // } else if (insideImplicitConstructorCall){ + // id = + // IProblem.JavadocNotVisibleConstructorInImplicitConstructorCall; + // } else { + id = IProblem.JavadocNotVisibleConstructor; + // } + break; + case Ambiguous: + // if (insideDefaultConstructor){ + // id = IProblem.AmbiguousConstructorInDefaultConstructor; + // } else if (insideImplicitConstructorCall){ + // id = IProblem.AmbiguousConstructorInImplicitConstructorCall; + // } else { + id = IProblem.JavadocAmbiguousConstructor; + // } + break; + case NoError: // 0 + default: + needImplementation(); // want to fail to see why we were here... + break; + } + + this.handle(id, new String[] { + new String(targetConstructor.declaringClass.readableName()), + parametersAsString(targetConstructor) }, + new String[] { + new String(targetConstructor.declaringClass + .shortReadableName()), + parametersAsShortString(targetConstructor) }, + statement.sourceStart, statement.sourceEnd); + } + + public void javadocAmbiguousMethodReference(int sourceStart, int sourceEnd, + Binding fieldBinding, int modifiers) { + int id = IProblem.JavadocAmbiguousMethodReference; + if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, + modifiers)) { + String[] arguments = new String[] { new String(fieldBinding + .readableName()) }; + handle(id, arguments, arguments, sourceStart, sourceEnd); + } + } + + /* + * Similar implementation than invalidField(FieldReference...) Note that + * following problem id cannot occur for Javadoc: - + * NonStaticReferenceInStaticContext : - + * NonStaticReferenceInConstructorInvocation : - ReceiverTypeNotVisible : + */ + public void javadocInvalidField(int sourceStart, int sourceEnd, + Binding fieldBinding, TypeBinding searchedType, int modifiers) { + int id = IProblem.JavadocUndefinedField; + switch (fieldBinding.problemId()) { + case NotFound: + id = IProblem.JavadocUndefinedField; + break; + case NotVisible: + id = IProblem.JavadocNotVisibleField; + break; + case Ambiguous: + id = IProblem.JavadocAmbiguousField; + break; + case InheritedNameHidesEnclosingName: + id = IProblem.JavadocInheritedFieldHidesEnclosingName; + break; + case NoError: // 0 + default: + needImplementation(); // want to fail to see why we were here... + break; + } + + if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, + modifiers)) { + String[] arguments = new String[] { new String(fieldBinding + .readableName()) }; + handle(id, arguments, arguments, sourceStart, sourceEnd); + } + } + + /* + * Similar implementation than invalidMethod(MessageSend...) Note that + * following problem id cannot occur for Javadoc: - + * NonStaticReferenceInStaticContext : - + * NonStaticReferenceInConstructorInvocation : - ReceiverTypeNotVisible : + */ + public void javadocInvalidMethod(MessageSend messageSend, + MethodBinding method, int modifiers) { + if (!javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, + modifiers)) { + return; + } + int id = IProblem.JavadocUndefinedMethod; // default... + switch (method.problemId()) { + case NotFound: + id = IProblem.JavadocUndefinedMethod; + break; + case NotVisible: + id = IProblem.JavadocNotVisibleMethod; + break; + case Ambiguous: + id = IProblem.JavadocAmbiguousMethod; + break; + case InheritedNameHidesEnclosingName: + id = IProblem.JavadocInheritedMethodHidesEnclosingName; + break; + case NoError: // 0 + default: + needImplementation(); // want to fail to see why we were here... + break; + } + + if (id == IProblem.JavadocUndefinedMethod) { + ProblemMethodBinding problemMethod = (ProblemMethodBinding) method; + if (problemMethod.closestMatch != null) { + String closestParameterTypeNames = parametersAsString(problemMethod.closestMatch); + String parameterTypeNames = parametersAsString(method); + String closestParameterTypeShortNames = parametersAsShortString(problemMethod.closestMatch); + String parameterTypeShortNames = parametersAsShortString(method); + if (closestParameterTypeShortNames + .equals(parameterTypeShortNames)) { + closestParameterTypeShortNames = closestParameterTypeNames; + parameterTypeShortNames = parameterTypeNames; + } + this + .handle( + IProblem.JavadocParameterMismatch, + new String[] { + new String( + problemMethod.closestMatch.declaringClass + .readableName()), + new String( + problemMethod.closestMatch.selector), + closestParameterTypeNames, + parameterTypeNames }, + new String[] { + new String( + problemMethod.closestMatch.declaringClass + .shortReadableName()), + new String( + problemMethod.closestMatch.selector), + closestParameterTypeShortNames, + parameterTypeShortNames }, + (int) (messageSend.nameSourcePosition >>> 32), + (int) messageSend.nameSourcePosition); + return; + } + } + + this.handle(id, new String[] { + new String(method.declaringClass.readableName()), + new String(method.selector), parametersAsString(method) }, + new String[] { + new String(method.declaringClass.shortReadableName()), + new String(method.selector), + parametersAsShortString(method) }, + (int) (messageSend.nameSourcePosition >>> 32), + (int) messageSend.nameSourcePosition); + } + + // public void javadocInvalidParamName(JavadocSingleNameReference param, int + // modifiers) { + // if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, + // modifiers)) { + // String[] arguments = new String[] {String.valueOf(param.token)}; + // this.handle(IProblem.JavadocInvalidParamName, arguments, arguments, + // param.sourceStart, param.sourceEnd); + // } + // } + public void javadocInvalidSeeReference(int sourceStart, int sourceEnd) { + this.handle(IProblem.JavadocInvalidSeeReference, NoArgument, + NoArgument, sourceStart, sourceEnd); + } + + public void javadocInvalidSeeReferenceArgs(int sourceStart, int sourceEnd) { + this.handle(IProblem.JavadocInvalidSeeArgs, NoArgument, NoArgument, + sourceStart, sourceEnd); + } + + public void javadocInvalidSeeUrlReference(int sourceStart, int sourceEnd) { + this.handle(IProblem.JavadocInvalidSeeHref, NoArgument, NoArgument, + sourceStart, sourceEnd); + } + + public void javadocInvalidTag(int sourceStart, int sourceEnd) { + this.handle(IProblem.JavadocInvalidTag, NoArgument, NoArgument, + sourceStart, sourceEnd); + } + + public void javadocInvalidThrowsClass(int sourceStart, int sourceEnd) { + this.handle(IProblem.JavadocInvalidThrowsClass, NoArgument, NoArgument, + sourceStart, sourceEnd); + } + + public void javadocInvalidThrowsClassName(TypeReference typeReference, + int modifiers) { + if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, + modifiers)) { + String[] arguments = new String[] { String + .valueOf(typeReference.resolvedType.sourceName()) }; + this.handle(IProblem.JavadocInvalidThrowsClassName, arguments, + arguments, typeReference.sourceStart, + typeReference.sourceEnd); + } + } + + public void javadocInvalidType(ASTNode location, TypeBinding type, + int modifiers) { + if (javadocVisibility(this.options.reportInvalidJavadocTagsVisibility, + modifiers)) { + int id = IProblem.JavadocUndefinedType; // default + switch (type.problemId()) { + case NotFound: + id = IProblem.JavadocUndefinedType; + break; + case NotVisible: + id = IProblem.JavadocNotVisibleType; + break; + case Ambiguous: + id = IProblem.JavadocAmbiguousType; + break; + case InternalNameProvided: + id = IProblem.JavadocInternalTypeNameProvided; + break; + case InheritedNameHidesEnclosingName: + id = IProblem.JavadocInheritedNameHidesEnclosingTypeName; + break; + case NoError: // 0 + default: + needImplementation(); // want to fail to see why we were + // here... + break; + } + this.handle(id, new String[] { new String(type.readableName()) }, + new String[] { new String(type.shortReadableName()) }, + location.sourceStart, location.sourceEnd); + } + } + + public void javadocMalformedSeeReference(int sourceStart, int sourceEnd) { + this.handle(IProblem.JavadocMalformedSeeReference, NoArgument, + NoArgument, sourceStart, sourceEnd); + } + + public void javadocMissing(int sourceStart, int sourceEnd, int modifiers) { + boolean overriding = (modifiers & (CompilerModifiers.AccImplementing + CompilerModifiers.AccOverriding)) != 0; + boolean report = (this.options + .getSeverity(CompilerOptions.MissingJavadocComments) != ProblemSeverities.Ignore) + && (!overriding || this.options.reportMissingJavadocCommentsOverriding); + if (report) { + String arg = javadocVisibilityArgument( + this.options.reportMissingJavadocCommentsVisibility, + modifiers); + if (arg != null) { + String[] arguments = new String[] { arg }; + this.handle(IProblem.JavadocMissing, arguments, arguments, + sourceStart, sourceEnd); + } + } + } + + public void javadocMissingParamName(int sourceStart, int sourceEnd) { + this.handle(IProblem.JavadocMissingParamName, NoArgument, NoArgument, + sourceStart, sourceEnd); + } + + public void javadocMissingParamTag(Argument param, int modifiers) { + boolean overriding = (modifiers & (CompilerModifiers.AccImplementing + CompilerModifiers.AccOverriding)) != 0; + boolean report = (this.options + .getSeverity(CompilerOptions.MissingJavadocTags) != ProblemSeverities.Ignore) + && (!overriding || this.options.reportMissingJavadocTagsOverriding); + if (report + && javadocVisibility( + this.options.reportMissingJavadocTagsVisibility, + modifiers)) { + String[] arguments = new String[] { String.valueOf(param.name) }; + this.handle(IProblem.JavadocMissingParamTag, arguments, arguments, + param.sourceStart, param.sourceEnd); + } + } + + public void javadocMissingReturnTag(int sourceStart, int sourceEnd, + int modifiers) { + boolean overriding = (modifiers & (CompilerModifiers.AccImplementing + CompilerModifiers.AccOverriding)) != 0; + boolean report = (this.options + .getSeverity(CompilerOptions.MissingJavadocTags) != ProblemSeverities.Ignore) + && (!overriding || this.options.reportMissingJavadocTagsOverriding); + if (report + && javadocVisibility( + this.options.reportMissingJavadocTagsVisibility, + modifiers)) { + this.handle(IProblem.JavadocMissingReturnTag, NoArgument, + NoArgument, sourceStart, sourceEnd); + } + } + + public void javadocMissingSeeReference(int sourceStart, int sourceEnd) { + this.handle(IProblem.JavadocMissingSeeReference, NoArgument, + NoArgument, sourceStart, sourceEnd); + } + + public void javadocMissingThrowsClassName(int sourceStart, int sourceEnd) { + this.handle(IProblem.JavadocMissingThrowsClassName, NoArgument, + NoArgument, sourceStart, sourceEnd); + } + + public void javadocMissingThrowsTag(TypeReference typeRef, int modifiers) { + boolean overriding = (modifiers & (CompilerModifiers.AccImplementing + CompilerModifiers.AccOverriding)) != 0; + boolean report = (this.options + .getSeverity(CompilerOptions.MissingJavadocTags) != ProblemSeverities.Ignore) + && (!overriding || this.options.reportMissingJavadocTagsOverriding); + if (report + && javadocVisibility( + this.options.reportMissingJavadocTagsVisibility, + modifiers)) { + String[] arguments = new String[] { String + .valueOf(typeRef.resolvedType.sourceName()) }; + this.handle(IProblem.JavadocMissingThrowsTag, arguments, arguments, + typeRef.sourceStart, typeRef.sourceEnd); + } + } + + public void javadocUnexpectedTag(int sourceStart, int sourceEnd) { + this.handle(IProblem.JavadocUnexpectedTag, NoArgument, NoArgument, + sourceStart, sourceEnd); + } + + public void javadocUnterminatedInlineTag(int sourceStart, int sourceEnd) { + this.handle(IProblem.JavadocUnterminatedInlineTag, NoArgument, + NoArgument, sourceStart, sourceEnd); + } + + private boolean javadocVisibility(int visibility, int modifiers) { + switch (modifiers & CompilerModifiers.AccVisibilityMASK) { + case IConstants.AccPublic: + return true; + case IConstants.AccProtected: + return (visibility != IConstants.AccPublic); + // case IConstants.AccDefault: + // return (visibility == IConstants.AccDefault || visibility == + // IConstants.AccPrivate); + case IConstants.AccPrivate: + return (visibility == IConstants.AccPrivate); + } + return true; + } + + private String javadocVisibilityArgument(int visibility, int modifiers) { + String argument = null; + switch (modifiers & CompilerModifiers.AccVisibilityMASK) { + case IConstants.AccPublic: + argument = CompilerOptions.PUBLIC; + break; + case IConstants.AccProtected: + if (visibility != IConstants.AccPublic) { + argument = CompilerOptions.PROTECTED; + } + break; + // case IConstants.AccDefault: + // if (visibility == IConstants.AccDefault || visibility == + // IConstants.AccPrivate) { + // argument = CompilerOptions.DEFAULT; + // } + // break; + case IConstants.AccPrivate: + if (visibility == IConstants.AccPrivate) { + argument = CompilerOptions.PRIVATE; + } + break; + } + return argument; + } + + public void methodNeedingAbstractModifier(MethodDeclaration methodDecl) { + this.handle(IProblem.MethodRequiresBody, NoArgument, NoArgument, + methodDecl.sourceStart, methodDecl.sourceEnd); + } + + public void methodNeedingNoBody(MethodDeclaration methodDecl) { + this.handle( + // ((methodDecl.modifiers & CompilerModifiers.AccNative) != 0) ? + // IProblem.BodyForNativeMethod : + // IProblem.BodyForAbstractMethod, + IProblem.BodyForAbstractMethod, NoArgument, NoArgument, + methodDecl.sourceStart, methodDecl.sourceEnd); + } + + public void methodWithConstructorName(MethodDeclaration methodDecl) { + this.handle(IProblem.MethodButWithConstructorName, NoArgument, + NoArgument, methodDecl.sourceStart, methodDecl.sourceEnd); + } + + // public void missingEnclosingInstanceSpecification(ReferenceBinding + // enclosingType, ASTNode location) { + // boolean insideConstructorCall = + // (location instanceof ExplicitConstructorCall) + // && (((ExplicitConstructorCall) location).accessMode == + // ExplicitConstructorCall.ImplicitSuper); + // + // this.handle( + // insideConstructorCall + // ? IProblem.MissingEnclosingInstanceForConstructorCall + // : IProblem.MissingEnclosingInstance, + // new String[] {new String(enclosingType.readableName())}, + // new String[] {new String(enclosingType.shortReadableName())}, + // location.sourceStart, + // location.sourceEnd); + // } + public void missingReturnType(AbstractMethodDeclaration methodDecl) { + this.handle(IProblem.MissingReturnType, NoArgument, NoArgument, + methodDecl.sourceStart, methodDecl.sourceEnd); + } + + public void missingSemiColon(Expression expression) { + this.handle(IProblem.MissingSemiColon, NoArgument, NoArgument, + expression.sourceStart, expression.sourceEnd); + } + + public void mustDefineDimensionsOrInitializer( + ArrayAllocationExpression expression) { + this.handle(IProblem.MustDefineEitherDimensionExpressionsOrInitializer, + NoArgument, NoArgument, expression.sourceStart, + expression.sourceEnd); + } + + public void mustSpecifyPackage(CompilationUnitDeclaration compUnitDecl) { + String[] arguments = new String[] { new String(compUnitDecl + .getFileName()) }; + this.handle(IProblem.MustSpecifyPackage, arguments, arguments, + compUnitDecl.sourceStart, compUnitDecl.sourceStart + 1); + } + + public void mustUseAStaticMethod(MessageSend messageSend, + MethodBinding method) { + this.handle(IProblem.StaticMethodRequested, new String[] { + new String(method.declaringClass.readableName()), + new String(method.selector), parametersAsString(method) }, + new String[] { + new String(method.declaringClass.shortReadableName()), + new String(method.selector), + parametersAsShortString(method) }, + messageSend.sourceStart, messageSend.sourceEnd); + } + + public void nativeMethodsCannotBeStrictfp(ReferenceBinding type, + AbstractMethodDeclaration methodDecl) { + String[] arguments = new String[] { new String(type.sourceName()), + new String(methodDecl.selector) }; + this.handle(IProblem.NativeMethodsCannotBeStrictfp, arguments, + arguments, methodDecl.sourceStart, methodDecl.sourceEnd); + } + + public void needImplementation() { + this.abortDueToInternalError(Util.bind("abort.missingCode")); //$NON-NLS-1$ + } + + public void needToEmulateFieldReadAccess(FieldBinding field, + ASTNode location) { + this.handle(IProblem.NeedToEmulateFieldReadAccess, new String[] { + new String(field.declaringClass.readableName()), + new String(field.name) }, new String[] { + new String(field.declaringClass.shortReadableName()), + new String(field.name) }, location.sourceStart, + location.sourceEnd); + } + + public void needToEmulateFieldWriteAccess(FieldBinding field, + ASTNode location) { + this.handle(IProblem.NeedToEmulateFieldWriteAccess, new String[] { + new String(field.declaringClass.readableName()), + new String(field.name) }, new String[] { + new String(field.declaringClass.shortReadableName()), + new String(field.name) }, location.sourceStart, + location.sourceEnd); + } + + public void needToEmulateMethodAccess(MethodBinding method, ASTNode location) { + if (method.isConstructor()) + this.handle(IProblem.NeedToEmulateConstructorAccess, new String[] { + new String(method.declaringClass.readableName()), + parametersAsString(method) }, new String[] { + new String(method.declaringClass.shortReadableName()), + parametersAsShortString(method) }, location.sourceStart, + location.sourceEnd); + else + this.handle(IProblem.NeedToEmulateMethodAccess, new String[] { + new String(method.declaringClass.readableName()), + new String(method.selector), parametersAsString(method) }, + new String[] { + new String(method.declaringClass + .shortReadableName()), + new String(method.selector), + parametersAsShortString(method) }, + location.sourceStart, location.sourceEnd); + } + + public void nestedClassCannotDeclareInterface(TypeDeclaration typeDecl) { + String[] arguments = new String[] { new String(typeDecl.name) }; + this.handle(IProblem.CannotDefineInterfaceInLocalType, arguments, + arguments, typeDecl.sourceStart, typeDecl.sourceEnd); + } + + public void noMoreAvailableSpaceForArgument(LocalVariableBinding local, + ASTNode location) { + String[] arguments = new String[] { new String(local.name) }; + this + .handle( + local instanceof SyntheticArgumentBinding ? IProblem.TooManySyntheticArgumentSlots + : IProblem.TooManyArgumentSlots, arguments, + arguments, Abort | Error, location.sourceStart, + location.sourceEnd); + } + + public void noMoreAvailableSpaceForLocal(LocalVariableBinding local, + ASTNode location) { + String[] arguments = new String[] { new String(local.name) }; + this.handle(IProblem.TooManyLocalVariableSlots, arguments, arguments, + Abort | Error, location.sourceStart, location.sourceEnd); + } + + public void noSuchEnclosingInstance(TypeBinding targetType, + ASTNode location, boolean isConstructorCall) { + int id; + if (isConstructorCall) { + // 28 = No enclosing instance of type {0} is available due to some + // intermediate constructor invocation + id = IProblem.EnclosingInstanceInConstructorCall; + } else if ((location instanceof ExplicitConstructorCall) + && ((ExplicitConstructorCall) location).accessMode == ExplicitConstructorCall.ImplicitSuper) { + // 20 = No enclosing instance of type {0} is accessible to invoke + // the super constructor. Must define a constructor and explicitly + // qualify its super constructor invocation with an instance of {0} + // (e.g. x.super() where x is an instance of {0}). + id = IProblem.MissingEnclosingInstanceForConstructorCall; + } else if (location instanceof AllocationExpression + && (((AllocationExpression) location).binding.declaringClass + .isMemberType() || (((AllocationExpression) location).binding.declaringClass + .isAnonymousType() && ((AllocationExpression) location).binding.declaringClass + .superclass().isMemberType()))) { + // 21 = No enclosing instance of type {0} is accessible. Must + // qualify the allocation with an enclosing instance of type {0} + // (e.g. x.new A() where x is an instance of {0}). + id = IProblem.MissingEnclosingInstance; + } else { // default + // 22 = No enclosing instance of the type {0} is accessible in + // scope + id = IProblem.IncorrectEnclosingInstanceReference; + } + this.handle(id, new String[] { new String(targetType.readableName()) }, + new String[] { new String(targetType.shortReadableName()) }, + location.sourceStart, location.sourceEnd); + } + + public void notCompatibleTypesError(EqualExpression expression, + TypeBinding leftType, TypeBinding rightType) { + String leftName = new String(leftType.readableName()); + String rightName = new String(rightType.readableName()); + String leftShortName = new String(leftType.shortReadableName()); + String rightShortName = new String(rightType.shortReadableName()); + if (leftShortName.equals(rightShortName)) { + leftShortName = leftName; + rightShortName = rightName; + } + this.handle(IProblem.IncompatibleTypesInEqualityOperator, new String[] { + leftName, rightName }, new String[] { leftShortName, + rightShortName }, expression.sourceStart, expression.sourceEnd); + } + + public void notCompatibleTypesError(InstanceOfExpression expression, + TypeBinding leftType, TypeBinding rightType) { + String leftName = new String(leftType.readableName()); + String rightName = new String(rightType.readableName()); + String leftShortName = new String(leftType.shortReadableName()); + String rightShortName = new String(rightType.shortReadableName()); + if (leftShortName.equals(rightShortName)) { + leftShortName = leftName; + rightShortName = rightName; + } + this.handle(IProblem.IncompatibleTypesInConditionalOperator, + new String[] { leftName, rightName }, new String[] { + leftShortName, rightShortName }, + expression.sourceStart, expression.sourceEnd); + } + + public void objectCannotHaveSuperTypes(SourceTypeBinding type) { + this.handle(IProblem.ObjectCannotHaveSuperTypes, NoArgument, + NoArgument, type.sourceStart(), type.sourceEnd()); + } + + public void operatorOnlyValidOnNumericType(CompoundAssignment assignment, + TypeBinding leftType, TypeBinding rightType) { + String leftName = new String(leftType.readableName()); + String rightName = new String(rightType.readableName()); + String leftShortName = new String(leftType.shortReadableName()); + String rightShortName = new String(rightType.shortReadableName()); + if (leftShortName.equals(rightShortName)) { + leftShortName = leftName; + rightShortName = rightName; + } + this.handle(IProblem.TypeMismatch, + new String[] { leftName, rightName }, new String[] { + leftShortName, rightShortName }, + assignment.sourceStart, assignment.sourceEnd); + } + + public void overridesDeprecatedMethod(MethodBinding localMethod, + MethodBinding inheritedMethod) { + this.handle(IProblem.OverridingDeprecatedMethod, new String[] { + new String(CharOperation.concat(localMethod.declaringClass + .readableName(), localMethod.readableName(), '.')), + new String(inheritedMethod.declaringClass.readableName()) }, + new String[] { + new String(CharOperation.concat( + localMethod.declaringClass.shortReadableName(), + localMethod.shortReadableName(), '.')), + new String(inheritedMethod.declaringClass + .shortReadableName()) }, localMethod + .sourceStart(), localMethod.sourceEnd()); + } + + public void overridesPackageDefaultMethod(MethodBinding localMethod, + MethodBinding inheritedMethod) { + this.handle(IProblem.OverridingNonVisibleMethod, new String[] { + new String(CharOperation.concat(localMethod.declaringClass + .readableName(), localMethod.readableName(), '.')), + new String(inheritedMethod.declaringClass.readableName()) }, + new String[] { + new String(CharOperation.concat( + localMethod.declaringClass.shortReadableName(), + localMethod.shortReadableName(), '.')), + new String(inheritedMethod.declaringClass + .shortReadableName()) }, localMethod + .sourceStart(), localMethod.sourceEnd()); + } + + // public void packageCollidesWithType(CompilationUnitDeclaration + // compUnitDecl) { + // String[] arguments = new String[]{CharOperation + // .toString(compUnitDecl.currentPackage.tokens)}; + // this.handle(IProblem.PackageCollidesWithType, arguments, arguments, + // compUnitDecl.currentPackage.sourceStart, + // compUnitDecl.currentPackage.sourceEnd); + // } + public void packageIsNotExpectedPackage( + CompilationUnitDeclaration compUnitDecl) { + String[] arguments = new String[] { CharOperation + .toString(compUnitDecl.compilationResult.compilationUnit + .getPackageName()) }; + this.handle(IProblem.PackageIsNotExpectedPackage, arguments, arguments, + compUnitDecl.currentPackage == null ? 0 + : compUnitDecl.currentPackage.sourceStart, + compUnitDecl.currentPackage == null ? 0 + : compUnitDecl.currentPackage.sourceEnd); + } + + private String parametersAsString(MethodBinding method) { + TypeBinding[] params = method.parameters; + StringBuffer buffer = new StringBuffer(); + for (int i = 0, length = params.length; i < length; i++) { + if (i != 0) + buffer.append(", "); //$NON-NLS-1$ + buffer.append(new String(params[i].readableName())); + } + return buffer.toString(); + } + + private String parametersAsShortString(MethodBinding method) { + TypeBinding[] params = method.parameters; + StringBuffer buffer = new StringBuffer(); + for (int i = 0, length = params.length; i < length; i++) { + if (i != 0) + buffer.append(", "); //$NON-NLS-1$ + buffer.append(new String(params[i].shortReadableName())); + } + return buffer.toString(); + } + + public void parseError(int startPosition, int endPosition, + char[] currentTokenSource, String errorTokenName, + String[] possibleTokens) { + if (possibleTokens.length == 0) { // no suggestion available + if (isKeyword(currentTokenSource)) { + String[] arguments = new String[] { new String( + currentTokenSource) }; + this.handle(IProblem.ParsingErrorOnKeywordNoSuggestion, + arguments, arguments, + // this is the current -invalid- token position + startPosition, endPosition); + return; + } else { + String[] arguments = new String[] { errorTokenName }; + this.handle(IProblem.ParsingErrorNoSuggestion, arguments, + arguments, + // this is the current -invalid- token position + startPosition, endPosition); + return; + } + } + // build a list of probable right tokens + StringBuffer list = new StringBuffer(20); + for (int i = 0, max = possibleTokens.length; i < max; i++) { + if (i > 0) + list.append(", "); //$NON-NLS-1$ + list.append('"'); + list.append(possibleTokens[i]); + list.append('"'); + } + if (isKeyword(currentTokenSource)) { + String[] arguments = new String[] { new String(currentTokenSource), + list.toString() }; + this.handle(IProblem.ParsingErrorOnKeyword, arguments, arguments, + // this is the current -invalid- token position + startPosition, endPosition); + return; + } + // extract the literal when it's a literal + if ((errorTokenName.equals("IntegerLiteral")) || //$NON-NLS-1$ + (errorTokenName.equals("LongLiteral")) || //$NON-NLS-1$ + (errorTokenName.equals("FloatingPointLiteral")) || //$NON-NLS-1$ + (errorTokenName.equals("DoubleLiteral")) || //$NON-NLS-1$ + (errorTokenName.equals("StringLiteral")) || //$NON-NLS-1$ + (errorTokenName.equals("CharacterLiteral")) || //$NON-NLS-1$ + (errorTokenName.equals("Identifier"))) { //$NON-NLS-1$ + errorTokenName = new String(currentTokenSource); + } + String[] arguments = new String[] { errorTokenName, list.toString() }; + this.handle(IProblem.ParsingError, arguments, arguments, + // this is the current -invalid- token position + startPosition, endPosition); + } + + public void publicClassMustMatchFileName( + CompilationUnitDeclaration compUnitDecl, TypeDeclaration typeDecl) { + this.referenceContext = typeDecl; // report the problem against the + // type not the entire compilation + // unit + String[] arguments = new String[] { + new String(compUnitDecl.getFileName()), + new String(typeDecl.name) }; + this.handle(IProblem.PublicClassMustMatchFileName, arguments, + arguments, typeDecl.sourceStart, typeDecl.sourceEnd, + compUnitDecl.compilationResult); + } + + public void recursiveConstructorInvocation( + ExplicitConstructorCall constructorCall) { + this.handle(IProblem.RecursiveConstructorInvocation, new String[] { + new String(constructorCall.binding.declaringClass + .readableName()), + parametersAsString(constructorCall.binding) }, new String[] { + new String(constructorCall.binding.declaringClass + .shortReadableName()), + parametersAsShortString(constructorCall.binding) }, + constructorCall.sourceStart, constructorCall.sourceEnd); + } + + public void redefineArgument(Argument arg) { + String[] arguments = new String[] { new String(arg.name) }; + this.handle(IProblem.RedefinedArgument, arguments, arguments, + arg.sourceStart, arg.sourceEnd); + } + + public void redefineLocal(LocalDeclaration localDecl) { + String[] arguments = new String[] { new String(localDecl.name) }; + this.handle(IProblem.RedefinedLocal, arguments, arguments, + localDecl.sourceStart, localDecl.sourceEnd); + } + + public void referenceMustBeArrayTypeAt(TypeBinding arrayType, + ArrayReference arrayRef) { + this.handle(IProblem.ArrayReferenceRequired, new String[] { new String( + arrayType.readableName()) }, new String[] { new String( + arrayType.shortReadableName()) }, arrayRef.sourceStart, + arrayRef.sourceEnd); + } + + public void returnTypeCannotBeVoidArray(SourceTypeBinding type, + MethodDeclaration methodDecl) { + String[] arguments = new String[] { new String(methodDecl.selector) }; + this.handle(IProblem.ReturnTypeCannotBeVoidArray, arguments, arguments, + methodDecl.sourceStart, methodDecl.sourceEnd); + } + + public void returnTypeProblem(SourceTypeBinding type, + MethodDeclaration methodDecl, TypeBinding expectedType) { + int problemId = expectedType.problemId(); + int id; + switch (problemId) { + case NotFound: + // 1 + id = IProblem.ReturnTypeNotFound; + break; + case NotVisible: + // 2 + id = IProblem.ReturnTypeNotVisible; + break; + case Ambiguous: + // 3 + id = IProblem.ReturnTypeAmbiguous; + break; + case InternalNameProvided: + // 4 + id = IProblem.ReturnTypeInternalNameProvided; + break; + case InheritedNameHidesEnclosingName: + // 5 + id = IProblem.ReturnTypeInheritedNameHidesEnclosingName; + break; + case NoError: + // 0 + default: + needImplementation(); // want to fail to see why we were + // here... + return; + } + this.handle(id, new String[] { new String(methodDecl.selector), + new String(expectedType.readableName()) }, new String[] { + new String(methodDecl.selector), + new String(expectedType.shortReadableName()) }, + methodDecl.returnType.sourceStart, + methodDecl.returnType.sourceEnd); + } + + public void scannerError(Parser parser, String errorTokenName) { + Scanner scanner = parser.scanner; + int flag = IProblem.ParsingErrorNoSuggestion; + int startPos = scanner.startPosition; + // special treatment for recognized errors.... + if (errorTokenName.equals(Scanner.END_OF_SOURCE)) + flag = IProblem.EndOfSource; + else if (errorTokenName.equals(Scanner.INVALID_HEXA)) + flag = IProblem.InvalidHexa; + else if (errorTokenName.equals(Scanner.INVALID_OCTAL)) + flag = IProblem.InvalidOctal; + else if (errorTokenName.equals(Scanner.INVALID_CHARACTER_CONSTANT)) + flag = IProblem.InvalidCharacterConstant; + else if (errorTokenName.equals(Scanner.INVALID_ESCAPE)) + flag = IProblem.InvalidEscape; + else if (errorTokenName.equals(Scanner.INVALID_UNICODE_ESCAPE)) { + flag = IProblem.InvalidUnicodeEscape; + // better locate the error message + char[] source = scanner.source; + int checkPos = scanner.currentPosition - 1; + if (checkPos >= source.length) + checkPos = source.length - 1; + while (checkPos >= startPos) { + if (source[checkPos] == '\\') + break; + checkPos--; + } + startPos = checkPos; + } else if (errorTokenName.equals(Scanner.INVALID_FLOAT)) + flag = IProblem.InvalidFloat; + else if (errorTokenName.equals(Scanner.UNTERMINATED_STRING)) + flag = IProblem.UnterminatedString; + else if (errorTokenName.equals(Scanner.UNTERMINATED_COMMENT)) + flag = IProblem.UnterminatedComment; + else if (errorTokenName.equals(Scanner.INVALID_CHAR_IN_STRING)) + flag = IProblem.UnterminatedString; + String[] arguments = flag == IProblem.ParsingErrorNoSuggestion ? new String[] { errorTokenName } + : NoArgument; + this.handle(flag, arguments, arguments, + // this is the current -invalid- token position + startPos, scanner.currentPosition - 1, + parser.compilationUnit.compilationResult); + } + + public void shouldReturn(TypeBinding returnType, ASTNode location) { + this.handle(IProblem.ShouldReturnValue, new String[] { new String( + returnType.readableName()) }, new String[] { new String( + returnType.shortReadableName()) }, location.sourceStart, + location.sourceEnd); + } + + public void signalNoImplicitStringConversionForCharArrayExpression( + Expression expression) { + this.handle(IProblem.NoImplicitStringConversionForCharArrayExpression, + NoArgument, NoArgument, expression.sourceStart, + expression.sourceEnd); + } + + public void staticAndInstanceConflict(MethodBinding currentMethod, + MethodBinding inheritedMethod) { + if (currentMethod.isStatic()) + this.handle( + // This static method cannot hide the instance method from + // %1 + // 8.4.6.4 - If a class inherits more than one method with + // the same signature a static (non-abstract) method cannot + // hide an instance method. + IProblem.CannotHideAnInstanceMethodWithAStaticMethod, + new String[] { new String(inheritedMethod.declaringClass + .readableName()) }, + new String[] { new String(inheritedMethod.declaringClass + .shortReadableName()) }, currentMethod + .sourceStart(), currentMethod.sourceEnd()); + else + this.handle( + // This instance method cannot override the static method + // from %1 + // 8.4.6.4 - If a class inherits more than one method with + // the same signature an instance (non-abstract) method + // cannot override a static method. + IProblem.CannotOverrideAStaticMethodWithAnInstanceMethod, + new String[] { new String(inheritedMethod.declaringClass + .readableName()) }, + new String[] { new String(inheritedMethod.declaringClass + .shortReadableName()) }, currentMethod + .sourceStart(), currentMethod.sourceEnd()); + } + + public void staticFieldAccessToNonStaticVariable(FieldReference fieldRef, + FieldBinding field) { + String[] arguments = new String[] { new String(field.readableName()) }; + this.handle(IProblem.NonStaticFieldFromStaticInvocation, arguments, + arguments, fieldRef.sourceStart, fieldRef.sourceEnd); + } + + public void staticFieldAccessToNonStaticVariable( + QualifiedNameReference nameRef, FieldBinding field) { + String[] arguments = new String[] { new String(field.readableName()) }; + this.handle(IProblem.NonStaticFieldFromStaticInvocation, arguments, + arguments, nameRef.sourceStart, nameRef.sourceEnd); + } + + public void staticFieldAccessToNonStaticVariable( + SingleNameReference nameRef, FieldBinding field) { + String[] arguments = new String[] { new String(field.readableName()) }; + this.handle(IProblem.NonStaticFieldFromStaticInvocation, arguments, + arguments, nameRef.sourceStart, nameRef.sourceEnd); + } + + public void staticInheritedMethodConflicts(SourceTypeBinding type, + MethodBinding concreteMethod, MethodBinding[] abstractMethods) { + this.handle( + // The static method %1 conflicts with the abstract method in %2 + // 8.4.6.4 - If a class inherits more than one method with the + // same signature it is an error for one to be static + // (non-abstract) and the other abstract. + IProblem.StaticInheritedMethodConflicts, new String[] { + new String(concreteMethod.readableName()), + new String(abstractMethods[0].declaringClass + .readableName()) }, new String[] { + new String(concreteMethod.readableName()), + new String(abstractMethods[0].declaringClass + .shortReadableName()) }, type.sourceStart(), + type.sourceEnd()); + } + + public void stringConstantIsExceedingUtf8Limit(ASTNode location) { + this.handle(IProblem.StringConstantIsExceedingUtf8Limit, NoArgument, + NoArgument, location.sourceStart, location.sourceEnd); + } + + public void superclassMustBeAClass(SourceTypeBinding type, + TypeReference superclassRef, ReferenceBinding superType) { + this.handle(IProblem.SuperclassMustBeAClass, new String[] { + new String(superType.readableName()), + new String(type.sourceName()) }, new String[] { + new String(superType.shortReadableName()), + new String(type.sourceName()) }, superclassRef.sourceStart, + superclassRef.sourceEnd); + } + + public void superinterfaceMustBeAnInterface(SourceTypeBinding type, + TypeDeclaration typeDecl, ReferenceBinding superType) { + this.handle(IProblem.SuperInterfaceMustBeAnInterface, new String[] { + new String(superType.readableName()), + new String(type.sourceName()) }, new String[] { + new String(superType.shortReadableName()), + new String(type.sourceName()) }, typeDecl.sourceStart, + typeDecl.sourceEnd); + } + + public void task(String tag, String message, String priority, int start, + int end) { + this.handle(IProblem.Task, new String[] { tag, message, priority /* + * secret + * argument + * that + * is + * not + * surfaced + * in + * getMessage() + */}, new String[] { tag, message, priority /* + * secret argument that is + * not surfaced in + * getMessage() + */}, start, end); + } + + public void tooManyDimensions(ASTNode expression) { + this.handle(IProblem.TooManyArrayDimensions, NoArgument, NoArgument, + expression.sourceStart, expression.sourceEnd); + } + + public void tooManyFields(TypeDeclaration typeDeclaration) { + this.handle(IProblem.TooManyFields, new String[] { new String( + typeDeclaration.binding.readableName()) }, + new String[] { new String(typeDeclaration.binding + .shortReadableName()) }, Abort | Error, + typeDeclaration.sourceStart, typeDeclaration.sourceEnd); + } + + public void tooManyMethods(TypeDeclaration typeDeclaration) { + this.handle(IProblem.TooManyMethods, new String[] { new String( + typeDeclaration.binding.readableName()) }, + new String[] { new String(typeDeclaration.binding + .shortReadableName()) }, Abort | Error, + typeDeclaration.sourceStart, typeDeclaration.sourceEnd); + } + + public void typeCastError(CastExpression expression, TypeBinding leftType, + TypeBinding rightType) { + String leftName = new String(leftType.readableName()); + String rightName = new String(rightType.readableName()); + String leftShortName = new String(leftType.shortReadableName()); + String rightShortName = new String(rightType.shortReadableName()); + if (leftShortName.equals(rightShortName)) { + leftShortName = leftName; + rightShortName = rightName; + } + this.handle(IProblem.IllegalCast, new String[] { rightName, leftName }, + new String[] { rightShortName, leftShortName }, + expression.sourceStart, expression.sourceEnd); + } + + public void typeCollidesWithPackage( + CompilationUnitDeclaration compUnitDecl, TypeDeclaration typeDecl) { + this.referenceContext = typeDecl; // report the problem against the + // type not the entire compilation + // unit + String[] arguments = new String[] { + new String(compUnitDecl.getFileName()), + new String(typeDecl.name) }; + this.handle(IProblem.TypeCollidesWithPackage, arguments, arguments, + typeDecl.sourceStart, typeDecl.sourceEnd, + compUnitDecl.compilationResult); + } + + public void typeMismatchError(TypeBinding resultType, + TypeBinding expectedType, ASTNode location) { + String resultTypeName = new String(resultType.readableName()); + String expectedTypeName = new String(expectedType.readableName()); + String resultTypeShortName = new String(resultType.shortReadableName()); + String expectedTypeShortName = new String(expectedType + .shortReadableName()); + if (resultTypeShortName.equals(expectedTypeShortName)) { + resultTypeShortName = resultTypeName; + expectedTypeShortName = expectedTypeName; + } + this.handle(IProblem.TypeMismatch, new String[] { resultTypeName, + expectedTypeName }, new String[] { resultTypeShortName, + expectedTypeShortName }, location.sourceStart, + location.sourceEnd); + } + + public void typeMismatchErrorActualTypeExpectedType(Expression expression, + TypeBinding constantType, TypeBinding expectedType) { + String constantTypeName = new String(constantType.readableName()); + String expectedTypeName = new String(expectedType.readableName()); + String constantTypeShortName = new String(constantType + .shortReadableName()); + String expectedTypeShortName = new String(expectedType + .shortReadableName()); + if (constantTypeShortName.equals(expectedTypeShortName)) { + constantTypeShortName = constantTypeName; + expectedTypeShortName = expectedTypeName; + } + this.handle(IProblem.TypeMismatch, new String[] { constantTypeName, + expectedTypeName }, new String[] { constantTypeShortName, + expectedTypeShortName }, expression.sourceStart, + expression.sourceEnd); + } + + // public void undefinedLabel(BranchStatement statement) { + // String[] arguments = new String[] { new String(statement.label) }; + // this.handle(IProblem.UndefinedLabel, arguments, arguments, + // statement.sourceStart, statement.sourceEnd); + // } + + public void unexpectedStaticModifierForField(SourceTypeBinding type, + FieldDeclaration fieldDecl) { + String[] arguments = new String[] { fieldDecl.name() }; + this.handle(IProblem.UnexpectedStaticModifierForField, arguments, + arguments, fieldDecl.sourceStart, fieldDecl.sourceEnd); + } + + public void unexpectedStaticModifierForMethod(ReferenceBinding type, + AbstractMethodDeclaration methodDecl) { + String[] arguments = new String[] { new String(type.sourceName()), + new String(methodDecl.selector) }; + this.handle(IProblem.UnexpectedStaticModifierForMethod, arguments, + arguments, methodDecl.sourceStart, methodDecl.sourceEnd); + } + + public void unhandledException(TypeBinding exceptionType, ASTNode location) { + boolean insideDefaultConstructor = (referenceContext instanceof ConstructorDeclaration) + && ((ConstructorDeclaration) referenceContext) + .isDefaultConstructor(); + boolean insideImplicitConstructorCall = (location instanceof ExplicitConstructorCall) + && (((ExplicitConstructorCall) location).accessMode == ExplicitConstructorCall.ImplicitSuper); + this + .handle( + insideDefaultConstructor ? IProblem.UnhandledExceptionInDefaultConstructor + : (insideImplicitConstructorCall ? IProblem.UndefinedConstructorInImplicitConstructorCall + : IProblem.UnhandledException), + new String[] { new String(exceptionType.readableName()) }, + new String[] { new String(exceptionType + .shortReadableName()) }, location.sourceStart, + location.sourceEnd); + } + + public void uninitializedBlankFinalField(FieldBinding binding, + ASTNode location) { + String[] arguments = new String[] { new String(binding.readableName()) }; + this.handle(IProblem.UninitializedBlankFinalField, arguments, + arguments, location.sourceStart, location.sourceEnd); + } + + public void unmatchedBracket(int position, ReferenceContext context, + CompilationResult compilationResult) { + this.handle(IProblem.UnmatchedBracket, NoArgument, NoArgument, + position, position, context, compilationResult); + } + + public void unnecessaryEnclosingInstanceSpecification( + Expression expression, ReferenceBinding targetType) { + this.handle(IProblem.IllegalEnclosingInstanceSpecification, + new String[] { new String(targetType.readableName()) }, + new String[] { new String(targetType.shortReadableName()) }, + expression.sourceStart, expression.sourceEnd); + } + + public void unnecessaryReceiverForStaticMethod(ASTNode location, + MethodBinding method) { + this.handle(IProblem.NonStaticAccessToStaticMethod, new String[] { + new String(method.declaringClass.readableName()), + new String(method.selector), parametersAsString(method) }, + new String[] { + new String(method.declaringClass.shortReadableName()), + new String(method.selector), + parametersAsShortString(method) }, + location.sourceStart, location.sourceEnd); + } + + public void unnecessaryReceiverForStaticField(ASTNode location, + FieldBinding field) { + this.handle(IProblem.NonStaticAccessToStaticField, new String[] { + new String(field.declaringClass.readableName()), + new String(field.name) }, new String[] { + new String(field.declaringClass.shortReadableName()), + new String(field.name) }, location.sourceStart, + location.sourceEnd); + } + + public void unreachableExceptionHandler(ReferenceBinding exceptionType, + ASTNode location) { + this.handle(IProblem.UnreachableCatch, NoArgument, NoArgument, + location.sourceStart, location.sourceEnd); + } + + public void unresolvableReference(NameReference nameRef, Binding binding) { + int severity = Error; + /* + * also need to check that the searchedType is the receiver type if + * (binding instanceof ProblemBinding) { ProblemBinding problem = + * (ProblemBinding) binding; if (problem.searchType != null && + * problem.searchType.isHierarchyInconsistent()) severity = + * SecondaryError; } + */ + String[] arguments = new String[] { new String(binding.readableName()) }; + this.handle(IProblem.UndefinedName, arguments, arguments, severity, + nameRef.sourceStart, nameRef.sourceEnd); + } + + public void unusedArgument(LocalDeclaration localDecl) { + String[] arguments = new String[] { localDecl.name() }; + this.handle(IProblem.ArgumentIsNeverUsed, arguments, arguments, + localDecl.sourceStart, localDecl.sourceEnd); + } + + // public void unusedImport(ImportReference importRef) { + // String[] arguments = new + // String[]{CharOperation.toString(importRef.tokens)}; + // this.handle(IProblem.UnusedImport, arguments, arguments, + // importRef.sourceStart, importRef.sourceEnd); + // } + public void unusedLocalVariable(LocalDeclaration localDecl) { + String[] arguments = new String[] { localDecl.name() }; + this.handle(IProblem.LocalVariableIsNeverUsed, arguments, arguments, + localDecl.sourceStart, localDecl.sourceEnd); + } + + public void unusedPrivateConstructor(ConstructorDeclaration constructorDecl) { + if (computeSeverity(IProblem.UnusedPrivateConstructor) == Ignore) + return; + // no complaint for no-arg constructors (or default ones) - known + // pattern to block instantiation + if (constructorDecl.arguments == null + || constructorDecl.arguments.length == 0) + return; + MethodBinding constructor = constructorDecl.binding; + this.handle(IProblem.UnusedPrivateConstructor, new String[] { + new String(constructor.declaringClass.readableName()), + parametersAsString(constructor) }, new String[] { + new String(constructor.declaringClass.shortReadableName()), + parametersAsShortString(constructor) }, + constructorDecl.sourceStart, constructorDecl.sourceEnd); + } + + public void unusedPrivateField(FieldDeclaration fieldDecl) { + if (computeSeverity(IProblem.UnusedPrivateField) == Ignore) + return; + FieldBinding field = fieldDecl.binding; + if (CharOperation.equals(TypeConstants.SERIALVERSIONUID, field.name) + && field.isStatic() && field.isFinal() + && TypeBinding.LongBinding == field.type) { + return; // do not report unused serialVersionUID field + } + this.handle(IProblem.UnusedPrivateField, new String[] { + new String(field.declaringClass.readableName()), + new String(field.name), }, new String[] { + new String(field.declaringClass.shortReadableName()), + new String(field.name), }, fieldDecl.sourceStart, + fieldDecl.sourceEnd); + } + + public void unusedPrivateMethod(AbstractMethodDeclaration methodDecl) { + if (computeSeverity(IProblem.UnusedPrivateMethod) == Ignore) + return; + MethodBinding method = methodDecl.binding; + // no report for serialization support 'void + // readObject(ObjectInputStream)' + if (!method.isStatic() + && TypeBinding.VoidBinding == method.returnType + && method.parameters.length == 1 + && method.parameters[0].dimensions() == 0 + && CharOperation.equals(method.selector, + TypeConstants.READOBJECT) + && CharOperation.equals( + TypeConstants.CharArray_JAVA_IO_OBJECTINPUTSTREAM, + method.parameters[0].readableName())) { + return; + } + // no report for serialization support 'void + // writeObject(ObjectOutputStream)' + if (!method.isStatic() + && TypeBinding.VoidBinding == method.returnType + && method.parameters.length == 1 + && method.parameters[0].dimensions() == 0 + && CharOperation.equals(method.selector, + TypeConstants.WRITEOBJECT) + && CharOperation.equals( + TypeConstants.CharArray_JAVA_IO_OBJECTOUTPUTSTREAM, + method.parameters[0].readableName())) { + return; + } + // no report for serialization support 'Object readResolve()' + if (!method.isStatic() + && TypeBinding.T_Object == method.returnType.id + && method.parameters.length == 0 + && CharOperation.equals(method.selector, + TypeConstants.READRESOLVE)) { + return; + } + // no report for serialization support 'Object writeReplace()' + if (!method.isStatic() + && TypeBinding.T_Object == method.returnType.id + && method.parameters.length == 0 + && CharOperation.equals(method.selector, + TypeConstants.WRITEREPLACE)) { + return; + } + this.handle(IProblem.UnusedPrivateMethod, new String[] { + new String(method.declaringClass.readableName()), + new String(method.selector), parametersAsString(method) }, + new String[] { + new String(method.declaringClass.shortReadableName()), + new String(method.selector), + parametersAsShortString(method) }, + methodDecl.sourceStart, methodDecl.sourceEnd); + } + + public void unusedPrivateType(TypeDeclaration typeDecl) { + if (computeSeverity(IProblem.UnusedPrivateType) == Ignore) + return; + ReferenceBinding type = typeDecl.binding; + this.handle(IProblem.UnusedPrivateType, new String[] { new String(type + .readableName()), }, new String[] { new String(type + .shortReadableName()), }, typeDecl.sourceStart, + typeDecl.sourceEnd); + } + + public void useAssertAsAnIdentifier(int sourceStart, int sourceEnd) { + this.handle(IProblem.UseAssertAsAnIdentifier, NoArgument, NoArgument, + sourceStart, sourceEnd); + } + + public void variableTypeCannotBeVoid(AbstractVariableDeclaration varDecl) { + String[] arguments = new String[] { new String(varDecl.name) }; + this.handle(IProblem.VariableTypeCannotBeVoid, arguments, arguments, + varDecl.sourceStart, varDecl.sourceEnd); + } + + public void variableTypeCannotBeVoidArray( + AbstractVariableDeclaration varDecl) { + String[] arguments = new String[] { new String(varDecl.name) }; + this.handle(IProblem.VariableTypeCannotBeVoidArray, arguments, + arguments, varDecl.sourceStart, varDecl.sourceEnd); + } + + public void visibilityConflict(MethodBinding currentMethod, + MethodBinding inheritedMethod) { + this.handle( + // Cannot reduce the visibility of the inherited method from %1 + // 8.4.6.3 - The access modifier of an hiding method must + // provide at least as much access as the hidden method. + // 8.4.6.3 - The access modifier of an overiding method must + // provide at least as much access as the overriden method. + IProblem.MethodReducesVisibility, new String[] { new String( + inheritedMethod.declaringClass.readableName()) }, + new String[] { new String(inheritedMethod.declaringClass + .shortReadableName()) }, currentMethod.sourceStart(), + currentMethod.sourceEnd()); + } + + public void wrongSequenceOfExceptionTypesError(TryStatement statement, + int under, int upper) { + // the two catch block under and upper are in an incorrect order. + // under should be define BEFORE upper in the source + TypeReference typeRef = statement.catchArguments[under].type; + this.handle(IProblem.UnreachableCatch, NoArgument, NoArgument, + typeRef.sourceStart, typeRef.sourceEnd); + } + + public void nonExternalizedStringLiteral(ASTNode location) { + this.handle(IProblem.NonExternalizedStringLiteral, NoArgument, + NoArgument, location.sourceStart, location.sourceEnd); + } + + public void noMoreAvailableSpaceForConstant(TypeDeclaration typeDeclaration) { + this.handle(IProblem.TooManyBytesForStringConstant, + new String[] { new String(typeDeclaration.binding + .readableName()) }, new String[] { new String( + typeDeclaration.binding.shortReadableName()) }, Abort + | Error, typeDeclaration.sourceStart, + typeDeclaration.sourceEnd); + } + + public void noMoreAvailableSpaceInConstantPool( + TypeDeclaration typeDeclaration) { + this.handle(IProblem.TooManyConstantsInConstantPool, + new String[] { new String(typeDeclaration.binding + .readableName()) }, new String[] { new String( + typeDeclaration.binding.shortReadableName()) }, Abort + | Error, typeDeclaration.sourceStart, + typeDeclaration.sourceEnd); + } + + private boolean isKeyword(char[] tokenSource) { + /* + * This code is heavily grammar dependant + */ + if (tokenSource == null) { + return false; + } + try { + Scanner scanner = new Scanner(); + scanner.setSource(tokenSource); + int token = scanner.getNextToken(); + char[] currentKeyword; + try { + currentKeyword = scanner.getCurrentIdentifierSource(); + } catch (ArrayIndexOutOfBoundsException e) { + return false; + } + int nextToken = scanner.getNextToken(); + if (nextToken == Scanner.TokenNameEOF + && scanner.startPosition == scanner.source.length) { // to + // handle + // case + // where + // we + // had + // an + // ArrayIndexOutOfBoundsException + // while reading the last token + switch (token) { + case Scanner.TokenNameERROR: + if (CharOperation.equals("goto".toCharArray(), + currentKeyword) + || CharOperation.equals( + "const".toCharArray(), currentKeyword)) { //$NON-NLS-1$ //$NON-NLS-2$ + return true; + } else { + return false; + } + case Scanner.TokenNameabstract: + // case Scanner.TokenNameassert: + // case Scanner.TokenNamebyte: + case Scanner.TokenNamebreak: + // case Scanner.TokenNameboolean: + case Scanner.TokenNamecase: + // case Scanner.TokenNamechar: + case Scanner.TokenNamecatch: + case Scanner.TokenNameclass: + case Scanner.TokenNamecontinue: + case Scanner.TokenNamedo: + // case Scanner.TokenNamedouble: + case Scanner.TokenNamedefault: + case Scanner.TokenNameelse: + case Scanner.TokenNameextends: + case Scanner.TokenNamefor: + // case Scanner.TokenNamefinal: + // case Scanner.TokenNamefloat: + // case Scanner.TokenNamefalse : + case Scanner.TokenNamefinally: + case Scanner.TokenNameif: + // case Scanner.TokenNameint: + // case Scanner.TokenNameimport: + case Scanner.TokenNameinterface: + case Scanner.TokenNameimplements: + case Scanner.TokenNameinstanceof: + // case Scanner.TokenNamelong: + case Scanner.TokenNamenew: + // case Scanner.TokenNamenull : + // case Scanner.TokenNamenative: + case Scanner.TokenNamepublic: + // case Scanner.TokenNamepackage: + case Scanner.TokenNameprivate: + case Scanner.TokenNameprotected: + case Scanner.TokenNamereturn: + // case Scanner.TokenNameshort: + case Scanner.TokenNamesuper: + case Scanner.TokenNamestatic: + case Scanner.TokenNameswitch: + // case Scanner.TokenNamestrictfp: + // case Scanner.TokenNamesynchronized: + case Scanner.TokenNametry: + // case Scanner.TokenNamethis : + // case Scanner.TokenNametrue : + case Scanner.TokenNamethrow: + // case Scanner.TokenNamethrows: + // case Scanner.TokenNametransient: + // case Scanner.TokenNamevoid: + // case Scanner.TokenNamevolatile: + case Scanner.TokenNamewhile: + return true; + default: + return false; + } + } else { + return false; + } + } catch (InvalidInputException e) { + return false; + } + } + + // jsurfer start + public void phpParsingError(String[] messageArguments, + int problemStartPosition, int problemEndPosition, + ReferenceContext context, CompilationResult compilationResult) { + this.handle(IProblem.PHPParsingError, NoArgument, messageArguments, + problemStartPosition, problemEndPosition, context, + compilationResult); + } + + public void phpParsingWarning(String[] messageArguments, + int problemStartPosition, int problemEndPosition, + ReferenceContext context, CompilationResult compilationResult) { + this.handle(IProblem.PHPParsingWarning, NoArgument, messageArguments, + problemStartPosition, problemEndPosition, context, + compilationResult); + } + + public void phpVarDeprecatedWarning(int problemStartPosition, + int problemEndPosition, ReferenceContext context, + CompilationResult compilationResult) { + if (computeSeverity(IProblem.PHPVarDeprecatedWarning) == Ignore) + return; + this.handle(IProblem.PHPVarDeprecatedWarning, NoArgument, + new String[] {}, problemStartPosition, problemEndPosition, + context, compilationResult); + } + + public void phpIncludeNotExistWarning(String[] messageArguments, + int problemStartPosition, int problemEndPosition, + ReferenceContext context, CompilationResult compilationResult) { + if (computeSeverity(IProblem.PHPIncludeNotExistWarning) == Ignore) + return; + this.handle(IProblem.PHPIncludeNotExistWarning, NoArgument, + messageArguments, problemStartPosition, problemEndPosition, + context, compilationResult); + } + + public void phpKeywordWarning(String[] messageArguments, + int problemStartPosition, int problemEndPosition, + ReferenceContext context, CompilationResult compilationResult) { + if (computeSeverity(IProblem.PHPBadStyleKeywordWarning) == Ignore) + return; + this.handle(IProblem.PHPBadStyleKeywordWarning, NoArgument, + messageArguments, problemStartPosition, problemEndPosition, + context, compilationResult); + } + + public void phpUppercaseIdentifierWarning(int problemStartPosition, + int problemEndPosition, ReferenceContext context, + CompilationResult compilationResult) { + if (computeSeverity(IProblem.PHPBadStyleUppercaseIdentifierWarning) == Ignore) + return; + this.handle(IProblem.PHPBadStyleUppercaseIdentifierWarning, NoArgument, + new String[] {}, problemStartPosition, problemEndPosition, + context, compilationResult); + } + + public void uninitializedLocalVariable(String token, + int problemStartPosition, int problemEndPosition, + ReferenceContext context, CompilationResult compilationResult) { + if (computeSeverity(IProblem.UninitializedLocalVariable) == Ignore) + return; + // String[] arguments = new String[] { new + // String(binding.readableName()) }; + String[] arguments = new String[] { token }; + this.handle(IProblem.UninitializedLocalVariable, arguments, arguments, + problemStartPosition, problemEndPosition, context, + compilationResult); + } + + public void unreachableCode(String token, int problemStartPosition, + int problemEndPosition, ReferenceContext context, + CompilationResult compilationResult) { + if (computeSeverity(IProblem.CodeCannotBeReached) == Ignore) + return; + this.handle(IProblem.CodeCannotBeReached, NoArgument, new String[] {}, + problemStartPosition, problemEndPosition, context, + compilationResult); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/ProblemSeverities.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/ProblemSeverities.java index f6f20de..8edaf1e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/ProblemSeverities.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/ProblemSeverities.java @@ -11,15 +11,23 @@ package net.sourceforge.phpdt.internal.compiler.problem; public interface ProblemSeverities { - + final int Ignore = -1; // during handling only + final int Warning = 0; // during handling only - final int Error = 1; // when bit is set: problem is error, if not it is a warning + final int Error = 1; // when bit is set: problem is error, if not it is a + // warning + final int AbortCompilation = 2; + final int AbortCompilationUnit = 4; + final int AbortType = 8; + final int AbortMethod = 16; + final int Abort = 30; // 2r11110 + final int SecondaryError = 64; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/ShouldNotImplement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/ShouldNotImplement.java index 2df4b5a..d0834bc 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/ShouldNotImplement.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/ShouldNotImplement.java @@ -11,15 +11,16 @@ package net.sourceforge.phpdt.internal.compiler.problem; /* - * Special unchecked exception type used - * to denote implementation that should never be reached. - * - * (internal only) + * Special unchecked exception type used to denote implementation that should + * never be reached. + * + * (internal only) */ public class ShouldNotImplement extends RuntimeException { -public ShouldNotImplement(){ -} -public ShouldNotImplement(String message){ - super(message); -} + public ShouldNotImplement() { + } + + public ShouldNotImplement(String message) { + super(message); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/CompoundNameVector.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/CompoundNameVector.java index 10832b6..bb12be0 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/CompoundNameVector.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/CompoundNameVector.java @@ -14,58 +14,71 @@ import net.sourceforge.phpdt.core.compiler.CharOperation; public final class CompoundNameVector { static int INITIAL_SIZE = 10; - + public int size; + int maxSize; + char[][][] elements; -public CompoundNameVector() { - maxSize = INITIAL_SIZE; - size = 0; - elements = new char[maxSize][][]; -} -public void add(char[][] newElement) { - if (size == maxSize) // knows that size starts <= maxSize - System.arraycopy(elements, 0, (elements = new char[maxSize *= 2][][]), 0, size); - elements[size++] = newElement; -} -public void addAll(char[][][] newElements) { - if (size + newElements.length >= maxSize) { - maxSize = size + newElements.length; // assume no more elements will be added - System.arraycopy(elements, 0, (elements = new char[maxSize][][]), 0, size); + + public CompoundNameVector() { + maxSize = INITIAL_SIZE; + size = 0; + elements = new char[maxSize][][]; } - System.arraycopy(newElements, 0, elements, size, newElements.length); - size += newElements.length; -} -public boolean contains(char[][] element) { - for (int i = size; --i >= 0;) - if (CharOperation.equals(element, elements[i])) - return true; - return false; -} -public char[][] elementAt(int index) { - return elements[index]; -} -public char[][] remove(char[][] element) { - // assumes only one occurrence of the element exists - for (int i = size; --i >= 0;) - if (element == elements[i]) { - // shift the remaining elements down one spot - System.arraycopy(elements, i + 1, elements, i, --size - i); - elements[size] = null; - return element; + + public void add(char[][] newElement) { + if (size == maxSize) // knows that size starts <= maxSize + System.arraycopy(elements, 0, + (elements = new char[maxSize *= 2][][]), 0, size); + elements[size++] = newElement; + } + + public void addAll(char[][][] newElements) { + if (size + newElements.length >= maxSize) { + maxSize = size + newElements.length; // assume no more elements + // will be added + System.arraycopy(elements, 0, (elements = new char[maxSize][][]), + 0, size); } - return null; -} -public void removeAll() { - for (int i = size; --i >= 0;) - elements[i] = null; - size = 0; -} -public String toString() { - StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < size; i++) { - buffer.append(CharOperation.toString(elements[i])).append("\n"); //$NON-NLS-1$ + System.arraycopy(newElements, 0, elements, size, newElements.length); + size += newElements.length; + } + + public boolean contains(char[][] element) { + for (int i = size; --i >= 0;) + if (CharOperation.equals(element, elements[i])) + return true; + return false; + } + + public char[][] elementAt(int index) { + return elements[index]; + } + + public char[][] remove(char[][] element) { + // assumes only one occurrence of the element exists + for (int i = size; --i >= 0;) + if (element == elements[i]) { + // shift the remaining elements down one spot + System.arraycopy(elements, i + 1, elements, i, --size - i); + elements[size] = null; + return element; + } + return null; + } + + public void removeAll() { + for (int i = size; --i >= 0;) + elements[i] = null; + size = 0; + } + + public String toString() { + StringBuffer buffer = new StringBuffer(); + for (int i = 0; i < size; i++) { + buffer.append(CharOperation.toString(elements[i])).append("\n"); //$NON-NLS-1$ + } + return buffer.toString(); } - return buffer.toString(); -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/HashtableOfInt.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/HashtableOfInt.java index cf20807..751806c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/HashtableOfInt.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/HashtableOfInt.java @@ -9,84 +9,102 @@ * IBM Corporation - initial API and implementation *******************************************************************************/ package net.sourceforge.phpdt.internal.compiler.util; - - /** - * Hashtable for non-zero int keys. - */ - + +/** + * Hashtable for non-zero int keys. + */ + public final class HashtableOfInt { // to avoid using Enumerations, walk the individual tables skipping nulls public int[] keyTable; + public Object[] valueTable; int elementSize; // number of elements in the table + int threshold; -public HashtableOfInt() { - this(13); -} -public HashtableOfInt(int size) { - this.elementSize = 0; - this.threshold = size; // size represents the expected number of elements - int extraRoom = (int) (size * 1.75f); - if (this.threshold == extraRoom) - extraRoom++; - this.keyTable = new int[extraRoom]; - this.valueTable = new Object[extraRoom]; -} -public boolean containsKey(int key) { - int index = key % valueTable.length; - int currentKey; - while ((currentKey = keyTable[index]) != 0) { - if (currentKey == key) - return true; - index = (index + 1) % keyTable.length; + + public HashtableOfInt() { + this(13); } - return false; -} -public Object get(int key) { - int index = key % valueTable.length; - int currentKey; - while ((currentKey = keyTable[index]) != 0) { - if (currentKey == key) return valueTable[index]; - index = (index + 1) % keyTable.length; + + public HashtableOfInt(int size) { + this.elementSize = 0; + this.threshold = size; // size represents the expected number of + // elements + int extraRoom = (int) (size * 1.75f); + if (this.threshold == extraRoom) + extraRoom++; + this.keyTable = new int[extraRoom]; + this.valueTable = new Object[extraRoom]; } - return null; -} -public Object put(int key, Object value) { - int index = key % valueTable.length; - int currentKey; - while ((currentKey = keyTable[index]) != 0) { - if (currentKey == key) return valueTable[index] = value; - index = (index + 1) % keyTable.length; + + public boolean containsKey(int key) { + int index = key % valueTable.length; + int currentKey; + while ((currentKey = keyTable[index]) != 0) { + if (currentKey == key) + return true; + index = (index + 1) % keyTable.length; + } + return false; } - keyTable[index] = key; - valueTable[index] = value; - // assumes the threshold is never equal to the size of the table - if (++elementSize > threshold) - rehash(); - return value; -} -private void rehash() { - HashtableOfInt newHashtable = new HashtableOfInt(elementSize * 2); // double the number of expected elements - int currentKey; - for (int i = keyTable.length; --i >= 0;) - if ((currentKey = keyTable[i]) != 0) - newHashtable.put(currentKey, valueTable[i]); + public Object get(int key) { + int index = key % valueTable.length; + int currentKey; + while ((currentKey = keyTable[index]) != 0) { + if (currentKey == key) + return valueTable[index]; + index = (index + 1) % keyTable.length; + } + return null; + } - this.keyTable = newHashtable.keyTable; - this.valueTable = newHashtable.valueTable; - this.threshold = newHashtable.threshold; -} -public int size() { - return elementSize; -} -public String toString() { - String s = ""; //$NON-NLS-1$ - Object object; - for (int i = 0, length = valueTable.length; i < length; i++) - if ((object = valueTable[i]) != null) - s += keyTable[i] + " -> " + object.toString() + "\n"; //$NON-NLS-2$ //$NON-NLS-1$ - return s; -} + public Object put(int key, Object value) { + int index = key % valueTable.length; + int currentKey; + while ((currentKey = keyTable[index]) != 0) { + if (currentKey == key) + return valueTable[index] = value; + index = (index + 1) % keyTable.length; + } + keyTable[index] = key; + valueTable[index] = value; + + // assumes the threshold is never equal to the size of the table + if (++elementSize > threshold) + rehash(); + return value; + } + + private void rehash() { + HashtableOfInt newHashtable = new HashtableOfInt(elementSize * 2); // double + // the + // number + // of + // expected + // elements + int currentKey; + for (int i = keyTable.length; --i >= 0;) + if ((currentKey = keyTable[i]) != 0) + newHashtable.put(currentKey, valueTable[i]); + + this.keyTable = newHashtable.keyTable; + this.valueTable = newHashtable.valueTable; + this.threshold = newHashtable.threshold; + } + + public int size() { + return elementSize; + } + + public String toString() { + String s = ""; //$NON-NLS-1$ + Object object; + for (int i = 0, length = valueTable.length; i < length; i++) + if ((object = valueTable[i]) != null) + s += keyTable[i] + " -> " + object.toString() + "\n"; //$NON-NLS-2$ //$NON-NLS-1$ + return s; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/HashtableOfIntValues.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/HashtableOfIntValues.java index f7e6bb7..1423f9e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/HashtableOfIntValues.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/HashtableOfIntValues.java @@ -16,14 +16,16 @@ import net.sourceforge.phpdt.core.compiler.CharOperation; * Hashtable of {char[] --> int} */ public final class HashtableOfIntValues implements Cloneable { - + public static final int NO_VALUE = Integer.MIN_VALUE; - + // to avoid using Enumerations, walk the individual tables skipping nulls public char[] keyTable[]; + public int valueTable[]; public int elementSize; // number of elements in the table + int threshold; public HashtableOfIntValues() { @@ -33,7 +35,8 @@ public final class HashtableOfIntValues implements Cloneable { public HashtableOfIntValues(int size) { this.elementSize = 0; - this.threshold = size; // size represents the expected number of elements + this.threshold = size; // size represents the expected number of + // elements int extraRoom = (int) (size * 1.75f); if (this.threshold == extraRoom) extraRoom++; @@ -62,7 +65,8 @@ public final class HashtableOfIntValues implements Cloneable { int keyLength = key.length; char[] currentKey; while ((currentKey = keyTable[index]) != null) { - if (currentKey.length == keyLength && CharOperation.equals(currentKey, key)) + if (currentKey.length == keyLength + && CharOperation.equals(currentKey, key)) return true; index = (index + 1) % keyTable.length; } @@ -75,7 +79,8 @@ public final class HashtableOfIntValues implements Cloneable { int keyLength = key.length; char[] currentKey; while ((currentKey = keyTable[index]) != null) { - if (currentKey.length == keyLength && CharOperation.equals(currentKey, key)) + if (currentKey.length == keyLength + && CharOperation.equals(currentKey, key)) return valueTable[index]; index = (index + 1) % keyTable.length; } @@ -88,7 +93,8 @@ public final class HashtableOfIntValues implements Cloneable { int keyLength = key.length; char[] currentKey; while ((currentKey = keyTable[index]) != null) { - if (currentKey.length == keyLength && CharOperation.equals(currentKey, key)) + if (currentKey.length == keyLength + && CharOperation.equals(currentKey, key)) return valueTable[index] = value; index = (index + 1) % keyTable.length; } @@ -107,7 +113,8 @@ public final class HashtableOfIntValues implements Cloneable { int keyLength = key.length; char[] currentKey; while ((currentKey = keyTable[index]) != null) { - if (currentKey.length == keyLength && CharOperation.equals(currentKey, key)) { + if (currentKey.length == keyLength + && CharOperation.equals(currentKey, key)) { int value = valueTable[index]; elementSize--; keyTable[index] = null; @@ -122,7 +129,8 @@ public final class HashtableOfIntValues implements Cloneable { private void rehash() { - HashtableOfIntValues newHashtable = new HashtableOfIntValues(elementSize * 2); // double the number of expected elements + HashtableOfIntValues newHashtable = new HashtableOfIntValues( + elementSize * 2); // double the number of expected elements char[] currentKey; for (int i = keyTable.length; --i >= 0;) if ((currentKey = keyTable[i]) != null) @@ -142,7 +150,7 @@ public final class HashtableOfIntValues implements Cloneable { char[] key; for (int i = 0, length = valueTable.length; i < length; i++) if ((key = keyTable[i]) != null) - s += new String(key) + " -> " + valueTable[i] + "\n"; //$NON-NLS-2$ //$NON-NLS-1$ + s += new String(key) + " -> " + valueTable[i] + "\n"; //$NON-NLS-2$ //$NON-NLS-1$ return s; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/HashtableOfLong.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/HashtableOfLong.java index 833a631..4b80c87 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/HashtableOfLong.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/HashtableOfLong.java @@ -9,84 +9,102 @@ * IBM Corporation - initial API and implementation *******************************************************************************/ package net.sourceforge.phpdt.internal.compiler.util; - - /** - * Hashtable for non-zero long keys. - */ - + +/** + * Hashtable for non-zero long keys. + */ + public final class HashtableOfLong { // to avoid using Enumerations, walk the individual tables skipping nulls public long[] keyTable; + public Object[] valueTable; int elementSize; // number of elements in the table + int threshold; -public HashtableOfLong() { - this(13); -} -public HashtableOfLong(int size) { - this.elementSize = 0; - this.threshold = size; // size represents the expected number of elements - int extraRoom = (int) (size * 1.75f); - if (this.threshold == extraRoom) - extraRoom++; - this.keyTable = new long[extraRoom]; - this.valueTable = new Object[extraRoom]; -} -public boolean containsKey(long key) { - int index = ((int)(key >>> 32)) % valueTable.length; - long currentKey; - while ((currentKey = keyTable[index]) != 0) { - if (currentKey == key) - return true; - index = (index + 1) % keyTable.length; + + public HashtableOfLong() { + this(13); } - return false; -} -public Object get(long key) { - int index = ((int)(key >>> 32)) % valueTable.length; - long currentKey; - while ((currentKey = keyTable[index]) != 0) { - if (currentKey == key) return valueTable[index]; - index = (index + 1) % keyTable.length; + + public HashtableOfLong(int size) { + this.elementSize = 0; + this.threshold = size; // size represents the expected number of + // elements + int extraRoom = (int) (size * 1.75f); + if (this.threshold == extraRoom) + extraRoom++; + this.keyTable = new long[extraRoom]; + this.valueTable = new Object[extraRoom]; } - return null; -} -public Object put(long key, Object value) { - int index = ((int)(key >>> 32)) % valueTable.length; - long currentKey; - while ((currentKey = keyTable[index]) != 0) { - if (currentKey == key) return valueTable[index] = value; - index = (index + 1) % keyTable.length; + + public boolean containsKey(long key) { + int index = ((int) (key >>> 32)) % valueTable.length; + long currentKey; + while ((currentKey = keyTable[index]) != 0) { + if (currentKey == key) + return true; + index = (index + 1) % keyTable.length; + } + return false; } - keyTable[index] = key; - valueTable[index] = value; - // assumes the threshold is never equal to the size of the table - if (++elementSize > threshold) - rehash(); - return value; -} -private void rehash() { - HashtableOfLong newHashtable = new HashtableOfLong(elementSize * 2); // double the number of expected elements - long currentKey; - for (int i = keyTable.length; --i >= 0;) - if ((currentKey = keyTable[i]) != 0) - newHashtable.put(currentKey, valueTable[i]); + public Object get(long key) { + int index = ((int) (key >>> 32)) % valueTable.length; + long currentKey; + while ((currentKey = keyTable[index]) != 0) { + if (currentKey == key) + return valueTable[index]; + index = (index + 1) % keyTable.length; + } + return null; + } - this.keyTable = newHashtable.keyTable; - this.valueTable = newHashtable.valueTable; - this.threshold = newHashtable.threshold; -} -public int size() { - return elementSize; -} -public String toString() { - String s = ""; //$NON-NLS-1$ - Object object; - for (int i = 0, length = valueTable.length; i < length; i++) - if ((object = valueTable[i]) != null) - s += keyTable[i] + " -> " + object.toString() + "\n"; //$NON-NLS-2$ //$NON-NLS-1$ - return s; -} + public Object put(long key, Object value) { + int index = ((int) (key >>> 32)) % valueTable.length; + long currentKey; + while ((currentKey = keyTable[index]) != 0) { + if (currentKey == key) + return valueTable[index] = value; + index = (index + 1) % keyTable.length; + } + keyTable[index] = key; + valueTable[index] = value; + + // assumes the threshold is never equal to the size of the table + if (++elementSize > threshold) + rehash(); + return value; + } + + private void rehash() { + HashtableOfLong newHashtable = new HashtableOfLong(elementSize * 2); // double + // the + // number + // of + // expected + // elements + long currentKey; + for (int i = keyTable.length; --i >= 0;) + if ((currentKey = keyTable[i]) != 0) + newHashtable.put(currentKey, valueTable[i]); + + this.keyTable = newHashtable.keyTable; + this.valueTable = newHashtable.valueTable; + this.threshold = newHashtable.threshold; + } + + public int size() { + return elementSize; + } + + public String toString() { + String s = ""; //$NON-NLS-1$ + Object object; + for (int i = 0, length = valueTable.length; i < length; i++) + if ((object = valueTable[i]) != null) + s += keyTable[i] + " -> " + object.toString() + "\n"; //$NON-NLS-2$ //$NON-NLS-1$ + return s; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/HashtableOfObject.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/HashtableOfObject.java index a739830..09e959a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/HashtableOfObject.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/HashtableOfObject.java @@ -16,12 +16,14 @@ import net.sourceforge.phpdt.core.compiler.CharOperation; * Hashtable of {char[] --> Object } */ public final class HashtableOfObject implements Cloneable { - + // to avoid using Enumerations, walk the individual tables skipping nulls public char[] keyTable[]; + public Object valueTable[]; public int elementSize; // number of elements in the table + int threshold; public HashtableOfObject() { @@ -31,7 +33,8 @@ public final class HashtableOfObject implements Cloneable { public HashtableOfObject(int size) { this.elementSize = 0; - this.threshold = size; // size represents the expected number of elements + this.threshold = size; // size represents the expected number of + // elements int extraRoom = (int) (size * 1.75f); if (this.threshold == extraRoom) extraRoom++; @@ -61,7 +64,7 @@ public final class HashtableOfObject implements Cloneable { char[] currentKey; while ((currentKey = keyTable[index]) != null) { if (currentKey.length == keyLength - && CharOperation.prefixEquals(currentKey, key)) + && CharOperation.prefixEquals(currentKey, key)) return true; index = (index + 1) % keyTable.length; } @@ -75,7 +78,7 @@ public final class HashtableOfObject implements Cloneable { char[] currentKey; while ((currentKey = keyTable[index]) != null) { if (currentKey.length == keyLength - && CharOperation.prefixEquals(currentKey, key)) + && CharOperation.prefixEquals(currentKey, key)) return valueTable[index]; index = (index + 1) % keyTable.length; } @@ -89,7 +92,7 @@ public final class HashtableOfObject implements Cloneable { char[] currentKey; while ((currentKey = keyTable[index]) != null) { if (currentKey.length == keyLength - && CharOperation.prefixEquals(currentKey, key)) + && CharOperation.prefixEquals(currentKey, key)) return valueTable[index] = value; index = (index + 1) % keyTable.length; } @@ -109,14 +112,14 @@ public final class HashtableOfObject implements Cloneable { char[] currentKey; while ((currentKey = keyTable[index]) != null) { if (currentKey.length == keyLength - && CharOperation.prefixEquals(currentKey, key)) { - Object value = valueTable[index]; - elementSize--; - keyTable[index] = null; - valueTable[index] = null; - rehash(); - return value; - } + && CharOperation.prefixEquals(currentKey, key)) { + Object value = valueTable[index]; + elementSize--; + keyTable[index] = null; + valueTable[index] = null; + rehash(); + return value; + } index = (index + 1) % keyTable.length; } return null; @@ -124,7 +127,12 @@ public final class HashtableOfObject implements Cloneable { private void rehash() { - HashtableOfObject newHashtable = new HashtableOfObject(elementSize * 2); // double the number of expected elements + HashtableOfObject newHashtable = new HashtableOfObject(elementSize * 2); // double + // the + // number + // of + // expected + // elements char[] currentKey; for (int i = keyTable.length; --i >= 0;) if ((currentKey = keyTable[i]) != null) @@ -144,7 +152,8 @@ public final class HashtableOfObject implements Cloneable { Object object; for (int i = 0, length = valueTable.length; i < length; i++) if ((object = valueTable[i]) != null) - s += new String(keyTable[i]) + " -> " + object.toString() + "\n"; //$NON-NLS-2$ //$NON-NLS-1$ + s += new String(keyTable[i]) + + " -> " + object.toString() + "\n"; //$NON-NLS-2$ //$NON-NLS-1$ return s; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/HashtableOfPackage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/HashtableOfPackage.java index 8dab8c3..e86a621 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/HashtableOfPackage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/HashtableOfPackage.java @@ -16,81 +16,96 @@ import net.sourceforge.phpdt.internal.compiler.lookup.PackageBinding; public final class HashtableOfPackage { // to avoid using Enumerations, walk the individual tables skipping nulls public char[] keyTable[]; + public PackageBinding valueTable[]; int elementSize; // number of elements in the table + int threshold; -public HashtableOfPackage() { - this(3); // usually not very large -} -public HashtableOfPackage(int size) { - this.elementSize = 0; - this.threshold = size; // size represents the expected number of elements - int extraRoom = (int) (size * 1.75f); - if (this.threshold == extraRoom) - extraRoom++; - this.keyTable = new char[extraRoom][]; - this.valueTable = new PackageBinding[extraRoom]; -} -public boolean containsKey(char[] key) { - int index = CharOperation.hashCode(key) % valueTable.length; - int keyLength = key.length; - char[] currentKey; - while ((currentKey = keyTable[index]) != null) { - if (currentKey.length == keyLength && CharOperation.prefixEquals(currentKey, key)) - return true; - index = (index + 1) % keyTable.length; + + public HashtableOfPackage() { + this(3); // usually not very large } - return false; -} -public PackageBinding get(char[] key) { - int index = CharOperation.hashCode(key) % valueTable.length; - int keyLength = key.length; - char[] currentKey; - while ((currentKey = keyTable[index]) != null) { - if (currentKey.length == keyLength && CharOperation.prefixEquals(currentKey, key)) - return valueTable[index]; - index = (index + 1) % keyTable.length; + + public HashtableOfPackage(int size) { + this.elementSize = 0; + this.threshold = size; // size represents the expected number of + // elements + int extraRoom = (int) (size * 1.75f); + if (this.threshold == extraRoom) + extraRoom++; + this.keyTable = new char[extraRoom][]; + this.valueTable = new PackageBinding[extraRoom]; } - return null; -} -public PackageBinding put(char[] key, PackageBinding value) { - int index = CharOperation.hashCode(key) % valueTable.length; - int keyLength = key.length; - char[] currentKey; - while ((currentKey = keyTable[index]) != null) { - if (currentKey.length == keyLength && CharOperation.prefixEquals(currentKey, key)) - return valueTable[index] = value; - index = (index + 1) % keyTable.length; + + public boolean containsKey(char[] key) { + int index = CharOperation.hashCode(key) % valueTable.length; + int keyLength = key.length; + char[] currentKey; + while ((currentKey = keyTable[index]) != null) { + if (currentKey.length == keyLength + && CharOperation.prefixEquals(currentKey, key)) + return true; + index = (index + 1) % keyTable.length; + } + return false; } - keyTable[index] = key; - valueTable[index] = value; - // assumes the threshold is never equal to the size of the table - if (++elementSize > threshold) - rehash(); - return value; -} -private void rehash() { - HashtableOfPackage newHashtable = new HashtableOfPackage(elementSize * 2); // double the number of expected elements - char[] currentKey; - for (int i = keyTable.length; --i >= 0;) - if ((currentKey = keyTable[i]) != null) - newHashtable.put(currentKey, valueTable[i]); + public PackageBinding get(char[] key) { + int index = CharOperation.hashCode(key) % valueTable.length; + int keyLength = key.length; + char[] currentKey; + while ((currentKey = keyTable[index]) != null) { + if (currentKey.length == keyLength + && CharOperation.prefixEquals(currentKey, key)) + return valueTable[index]; + index = (index + 1) % keyTable.length; + } + return null; + } - this.keyTable = newHashtable.keyTable; - this.valueTable = newHashtable.valueTable; - this.threshold = newHashtable.threshold; -} -public int size() { - return elementSize; -} -public String toString() { - String s = ""; //$NON-NLS-1$ - PackageBinding pkg; - for (int i = 0, length = valueTable.length; i < length; i++) - if ((pkg = valueTable[i]) != null) - s += pkg.toString() + "\n"; //$NON-NLS-1$ - return s; -} + public PackageBinding put(char[] key, PackageBinding value) { + int index = CharOperation.hashCode(key) % valueTable.length; + int keyLength = key.length; + char[] currentKey; + while ((currentKey = keyTable[index]) != null) { + if (currentKey.length == keyLength + && CharOperation.prefixEquals(currentKey, key)) + return valueTable[index] = value; + index = (index + 1) % keyTable.length; + } + keyTable[index] = key; + valueTable[index] = value; + + // assumes the threshold is never equal to the size of the table + if (++elementSize > threshold) + rehash(); + return value; + } + + private void rehash() { + HashtableOfPackage newHashtable = new HashtableOfPackage( + elementSize * 2); // double the number of expected elements + char[] currentKey; + for (int i = keyTable.length; --i >= 0;) + if ((currentKey = keyTable[i]) != null) + newHashtable.put(currentKey, valueTable[i]); + + this.keyTable = newHashtable.keyTable; + this.valueTable = newHashtable.valueTable; + this.threshold = newHashtable.threshold; + } + + public int size() { + return elementSize; + } + + public String toString() { + String s = ""; //$NON-NLS-1$ + PackageBinding pkg; + for (int i = 0, length = valueTable.length; i < length; i++) + if ((pkg = valueTable[i]) != null) + s += pkg.toString() + "\n"; //$NON-NLS-1$ + return s; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/HashtableOfType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/HashtableOfType.java index fbeec53..8102ee1 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/HashtableOfType.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/HashtableOfType.java @@ -16,81 +16,98 @@ import net.sourceforge.phpdt.internal.compiler.lookup.ReferenceBinding; public final class HashtableOfType { // to avoid using Enumerations, walk the individual tables skipping nulls public char[] keyTable[]; + public ReferenceBinding valueTable[]; int elementSize; // number of elements in the table + int threshold; -public HashtableOfType() { - this(3); -} -public HashtableOfType(int size) { - this.elementSize = 0; - this.threshold = size; // size represents the expected number of elements - int extraRoom = (int) (size * 1.75f); - if (this.threshold == extraRoom) - extraRoom++; - this.keyTable = new char[extraRoom][]; - this.valueTable = new ReferenceBinding[extraRoom]; -} -public boolean containsKey(char[] key) { - int index = CharOperation.hashCode(key) % valueTable.length; - int keyLength = key.length; - char[] currentKey; - while ((currentKey = keyTable[index]) != null) { - if (currentKey.length == keyLength && CharOperation.prefixEquals(currentKey, key)) - return true; - index = (index + 1) % keyTable.length; + + public HashtableOfType() { + this(3); } - return false; -} -public ReferenceBinding get(char[] key) { - int index = CharOperation.hashCode(key) % valueTable.length; - int keyLength = key.length; - char[] currentKey; - while ((currentKey = keyTable[index]) != null) { - if (currentKey.length == keyLength && CharOperation.prefixEquals(currentKey, key)) - return valueTable[index]; - index = (index + 1) % keyTable.length; + + public HashtableOfType(int size) { + this.elementSize = 0; + this.threshold = size; // size represents the expected number of + // elements + int extraRoom = (int) (size * 1.75f); + if (this.threshold == extraRoom) + extraRoom++; + this.keyTable = new char[extraRoom][]; + this.valueTable = new ReferenceBinding[extraRoom]; } - return null; -} -public ReferenceBinding put(char[] key, ReferenceBinding value) { - int index = CharOperation.hashCode(key) % valueTable.length; - int keyLength = key.length; - char[] currentKey; - while ((currentKey = keyTable[index]) != null) { - if (currentKey.length == keyLength && CharOperation.prefixEquals(currentKey, key)) - return valueTable[index] = value; - index = (index + 1) % keyTable.length; + + public boolean containsKey(char[] key) { + int index = CharOperation.hashCode(key) % valueTable.length; + int keyLength = key.length; + char[] currentKey; + while ((currentKey = keyTable[index]) != null) { + if (currentKey.length == keyLength + && CharOperation.prefixEquals(currentKey, key)) + return true; + index = (index + 1) % keyTable.length; + } + return false; } - keyTable[index] = key; - valueTable[index] = value; - // assumes the threshold is never equal to the size of the table - if (++elementSize > threshold) - rehash(); - return value; -} -private void rehash() { - HashtableOfType newHashtable = new HashtableOfType(elementSize < 100 ? 100 : elementSize * 2); // double the number of expected elements - char[] currentKey; - for (int i = keyTable.length; --i >= 0;) - if ((currentKey = keyTable[i]) != null) - newHashtable.put(currentKey, valueTable[i]); + public ReferenceBinding get(char[] key) { + int index = CharOperation.hashCode(key) % valueTable.length; + int keyLength = key.length; + char[] currentKey; + while ((currentKey = keyTable[index]) != null) { + if (currentKey.length == keyLength + && CharOperation.prefixEquals(currentKey, key)) + return valueTable[index]; + index = (index + 1) % keyTable.length; + } + return null; + } - this.keyTable = newHashtable.keyTable; - this.valueTable = newHashtable.valueTable; - this.threshold = newHashtable.threshold; -} -public int size() { - return elementSize; -} -public String toString() { - String s = ""; //$NON-NLS-1$ - ReferenceBinding type; - for (int i = 0, length = valueTable.length; i < length; i++) - if ((type = valueTable[i]) != null) - s += type.toString() + "\n"; //$NON-NLS-1$ - return s; -} + public ReferenceBinding put(char[] key, ReferenceBinding value) { + int index = CharOperation.hashCode(key) % valueTable.length; + int keyLength = key.length; + char[] currentKey; + while ((currentKey = keyTable[index]) != null) { + if (currentKey.length == keyLength + && CharOperation.prefixEquals(currentKey, key)) + return valueTable[index] = value; + index = (index + 1) % keyTable.length; + } + keyTable[index] = key; + valueTable[index] = value; + + // assumes the threshold is never equal to the size of the table + if (++elementSize > threshold) + rehash(); + return value; + } + + private void rehash() { + HashtableOfType newHashtable = new HashtableOfType( + elementSize < 100 ? 100 : elementSize * 2); // double the number + // of expected + // elements + char[] currentKey; + for (int i = keyTable.length; --i >= 0;) + if ((currentKey = keyTable[i]) != null) + newHashtable.put(currentKey, valueTable[i]); + + this.keyTable = newHashtable.keyTable; + this.valueTable = newHashtable.valueTable; + this.threshold = newHashtable.threshold; + } + + public int size() { + return elementSize; + } + + public String toString() { + String s = ""; //$NON-NLS-1$ + ReferenceBinding type; + for (int i = 0, length = valueTable.length; i < length; i++) + if ((type = valueTable[i]) != null) + s += type.toString() + "\n"; //$NON-NLS-1$ + return s; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/ObjectVector.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/ObjectVector.java index 40dd438..f842b7c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/ObjectVector.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/ObjectVector.java @@ -11,13 +11,15 @@ package net.sourceforge.phpdt.internal.compiler.util; public final class ObjectVector { - + static int INITIAL_SIZE = 10; public int size; + int maxSize; + Object[] elements; - + public ObjectVector() { this.maxSize = INITIAL_SIZE; @@ -28,27 +30,36 @@ public final class ObjectVector { public void add(Object newElement) { if (this.size == this.maxSize) // knows that size starts <= maxSize - System.arraycopy(this.elements, 0, (this.elements = new Object[this.maxSize *= 2]), 0, this.size); + System.arraycopy(this.elements, 0, + (this.elements = new Object[this.maxSize *= 2]), 0, + this.size); this.elements[this.size++] = newElement; } public void addAll(Object[] newElements) { if (this.size + newElements.length >= this.maxSize) { - maxSize = this.size + newElements.length; // assume no more elements will be added - System.arraycopy(this.elements, 0, (this.elements = new Object[this.maxSize]), 0, this.size); + maxSize = this.size + newElements.length; // assume no more + // elements will be + // added + System.arraycopy(this.elements, 0, + (this.elements = new Object[this.maxSize]), 0, this.size); } - System.arraycopy(newElements, 0, this.elements, size, newElements.length); + System.arraycopy(newElements, 0, this.elements, size, + newElements.length); this.size += newElements.length; } public void addAll(ObjectVector newVector) { if (this.size + newVector.size >= this.maxSize) { - maxSize = this.size + newVector.size; // assume no more elements will be added - System.arraycopy(this.elements, 0, (this.elements = new Object[this.maxSize]), 0, this.size); + maxSize = this.size + newVector.size; // assume no more elements + // will be added + System.arraycopy(this.elements, 0, + (this.elements = new Object[this.maxSize]), 0, this.size); } - System.arraycopy(newVector.elements, 0, this.elements, size, newVector.size); + System.arraycopy(newVector.elements, 0, this.elements, size, + newVector.size); this.size += newVector.size; } @@ -74,16 +85,16 @@ public final class ObjectVector { return false; } - public void copyInto(Object[] targetArray){ - + public void copyInto(Object[] targetArray) { + this.copyInto(targetArray, 0); } - - public void copyInto(Object[] targetArray, int index){ - + + public void copyInto(Object[] targetArray, int index) { + System.arraycopy(this.elements, 0, targetArray, index, this.size); - } - + } + public Object elementAt(int index) { return this.elements[index]; @@ -103,7 +114,8 @@ public final class ObjectVector { for (int i = this.size; --i >= 0;) if (element.equals(this.elements[i])) { // shift the remaining elements down one spot - System.arraycopy(this.elements, i + 1, this.elements, i, --this.size - i); + System.arraycopy(this.elements, i + 1, this.elements, i, + --this.size - i); this.elements[this.size] = null; return element; } @@ -111,19 +123,19 @@ public final class ObjectVector { } public void removeAll() { - + for (int i = this.size; --i >= 0;) this.elements[i] = null; this.size = 0; } - public int size(){ - + public int size() { + return this.size; } - + public String toString() { - + String s = ""; //$NON-NLS-1$ for (int i = 0; i < this.size; i++) s += this.elements[i].toString() + "\n"; //$NON-NLS-1$ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/SimpleNameVector.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/SimpleNameVector.java index 1814923..5766543 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/SimpleNameVector.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/SimpleNameVector.java @@ -13,79 +13,88 @@ package net.sourceforge.phpdt.internal.compiler.util; import net.sourceforge.phpdt.core.compiler.CharOperation; public final class SimpleNameVector { - + static int INITIAL_SIZE = 10; public int size; + int maxSize; + char[][] elements; - + public SimpleNameVector() { - + this.maxSize = INITIAL_SIZE; this.size = 0; this.elements = new char[this.maxSize][]; } - + public void add(char[] newElement) { - + if (this.size == this.maxSize) // knows that size starts <= maxSize - System.arraycopy(this.elements, 0, (this.elements = new char[this.maxSize *= 2][]), 0, this.size); + System.arraycopy(this.elements, 0, + (this.elements = new char[this.maxSize *= 2][]), 0, + this.size); this.elements[size++] = newElement; } - + public void addAll(char[][] newElements) { - + if (this.size + newElements.length >= this.maxSize) { - this.maxSize = this.size + newElements.length; // assume no more elements will be added - System.arraycopy(this.elements, 0, (this.elements = new char[this.maxSize][]), 0, this.size); + this.maxSize = this.size + newElements.length; // assume no more + // elements will be + // added + System.arraycopy(this.elements, 0, + (this.elements = new char[this.maxSize][]), 0, this.size); } - System.arraycopy(newElements, 0, this.elements, this.size, newElements.length); + System.arraycopy(newElements, 0, this.elements, this.size, + newElements.length); this.size += newElements.length; } - - public void copyInto(Object[] targetArray){ - + + public void copyInto(Object[] targetArray) { + System.arraycopy(this.elements, 0, targetArray, 0, this.size); } - + public boolean contains(char[] element) { - + for (int i = this.size; --i >= 0;) if (CharOperation.equals(element, this.elements[i])) return true; return false; } - + public char[] elementAt(int index) { return this.elements[index]; } - + public char[] remove(char[] element) { - + // assumes only one occurrence of the element exists for (int i = this.size; --i >= 0;) if (element == this.elements[i]) { // shift the remaining elements down one spot - System.arraycopy(this.elements, i + 1, this.elements, i, --this.size - i); + System.arraycopy(this.elements, i + 1, this.elements, i, + --this.size - i); this.elements[this.size] = null; return element; } return null; } - + public void removeAll() { - + for (int i = this.size; --i >= 0;) this.elements[i] = null; this.size = 0; } - - public int size(){ - + + public int size() { + return this.size; } - + public String toString() { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < this.size; i++) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/SuffixConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/SuffixConstants.java index 972bf8a..8dd10d9 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/SuffixConstants.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/SuffixConstants.java @@ -11,33 +11,44 @@ package net.sourceforge.phpdt.internal.compiler.util; public interface SuffixConstants { -// public final static String EXTENSION_class = "class"; //$NON-NLS-1$ -// public final static String EXTENSION_CLASS = "CLASS"; //$NON-NLS-1$ + // public final static String EXTENSION_class = "class"; //$NON-NLS-1$ + // public final static String EXTENSION_CLASS = "CLASS"; //$NON-NLS-1$ public final static String EXTENSION_php = "php"; //$NON-NLS-1$ + public final static String EXTENSION_PHP = "PHP"; //$NON-NLS-1$ - -// public final static String SUFFIX_STRING_class = "." + EXTENSION_class; //$NON-NLS-1$ -// public final static String SUFFIX_STRING_CLASS = "." + EXTENSION_CLASS; //$NON-NLS-1$ + + // public final static String SUFFIX_STRING_class = "." + EXTENSION_class; + // //$NON-NLS-1$ + // public final static String SUFFIX_STRING_CLASS = "." + EXTENSION_CLASS; + // //$NON-NLS-1$ public final static String SUFFIX_STRING_php = "." + EXTENSION_php; //$NON-NLS-1$ + public final static String SUFFIX_STRING_PHP = "." + EXTENSION_PHP; //$NON-NLS-1$ - -// public final static char[] SUFFIX_class = SUFFIX_STRING_class.toCharArray(); -// public final static char[] SUFFIX_CLASS = SUFFIX_STRING_CLASS.toCharArray(); + + // public final static char[] SUFFIX_class = + // SUFFIX_STRING_class.toCharArray(); + // public final static char[] SUFFIX_CLASS = + // SUFFIX_STRING_CLASS.toCharArray(); public final static char[] SUFFIX_php = SUFFIX_STRING_php.toCharArray(); + public final static char[] SUFFIX_PHP = SUFFIX_STRING_PHP.toCharArray(); - -// public final static String EXTENSION_jar = "jar"; //$NON-NLS-1$ -// public final static String EXTENSION_JAR = "JAR"; //$NON-NLS-1$ -// public final static String EXTENSION_zip = "zip"; //$NON-NLS-1$ -// public final static String EXTENSION_ZIP = "ZIP"; //$NON-NLS-1$ - -// public final static String SUFFIX_STRING_jar = "." + EXTENSION_jar; //$NON-NLS-1$ -// public final static String SUFFIX_STRING_JAR = "." + EXTENSION_JAR; //$NON-NLS-1$ -// public final static String SUFFIX_STRING_zip = "." + EXTENSION_zip; //$NON-NLS-1$ -// public final static String SUFFIX_STRING_ZIP = "." + EXTENSION_ZIP; //$NON-NLS-1$ - -// public final static char[] SUFFIX_jar = SUFFIX_STRING_jar.toCharArray(); -// public final static char[] SUFFIX_JAR = SUFFIX_STRING_JAR.toCharArray(); -// public final static char[] SUFFIX_zip = SUFFIX_STRING_zip.toCharArray(); -// public final static char[] SUFFIX_ZIP = SUFFIX_STRING_ZIP.toCharArray(); + + // public final static String EXTENSION_jar = "jar"; //$NON-NLS-1$ + // public final static String EXTENSION_JAR = "JAR"; //$NON-NLS-1$ + // public final static String EXTENSION_zip = "zip"; //$NON-NLS-1$ + // public final static String EXTENSION_ZIP = "ZIP"; //$NON-NLS-1$ + + // public final static String SUFFIX_STRING_jar = "." + EXTENSION_jar; + // //$NON-NLS-1$ + // public final static String SUFFIX_STRING_JAR = "." + EXTENSION_JAR; + // //$NON-NLS-1$ + // public final static String SUFFIX_STRING_zip = "." + EXTENSION_zip; + // //$NON-NLS-1$ + // public final static String SUFFIX_STRING_ZIP = "." + EXTENSION_ZIP; + // //$NON-NLS-1$ + + // public final static char[] SUFFIX_jar = SUFFIX_STRING_jar.toCharArray(); + // public final static char[] SUFFIX_JAR = SUFFIX_STRING_JAR.toCharArray(); + // public final static char[] SUFFIX_zip = SUFFIX_STRING_zip.toCharArray(); + // public final static char[] SUFFIX_ZIP = SUFFIX_STRING_ZIP.toCharArray(); } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/Util.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/Util.java index 85f7fad..4629147 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/Util.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/util/Util.java @@ -29,27 +29,39 @@ import net.sourceforge.phpdt.internal.ui.util.PHPFileUtil; public class Util { public static String LINE_SEPARATOR = System.getProperty("line.separator"); //$NON-NLS-1$ + public static char[] LINE_SEPARATOR_CHARS = LINE_SEPARATOR.toCharArray(); -// public final static char[] SUFFIX_class = ".class".toCharArray(); //$NON-NLS-1$ -// public final static char[] SUFFIX_CLASS = ".CLASS".toCharArray(); //$NON-NLS-1$ + + // public final static char[] SUFFIX_class = ".class".toCharArray(); + // //$NON-NLS-1$ + // public final static char[] SUFFIX_CLASS = ".CLASS".toCharArray(); + // //$NON-NLS-1$ public final static char[] SUFFIX_java = ".java".toCharArray(); //$NON-NLS-1$ + public final static char[] SUFFIX_JAVA = ".JAVA".toCharArray(); //$NON-NLS-1$ -// public final static char[] SUFFIX_jar = ".jar".toCharArray(); //$NON-NLS-1$ -// public final static char[] SUFFIX_JAR = ".JAR".toCharArray(); //$NON-NLS-1$ + // public final static char[] SUFFIX_jar = ".jar".toCharArray(); + // //$NON-NLS-1$ + // public final static char[] SUFFIX_JAR = ".JAR".toCharArray(); + // //$NON-NLS-1$ + public final static char[] SUFFIX_zip = ".zip".toCharArray(); //$NON-NLS-1$ + public final static char[] SUFFIX_ZIP = ".ZIP".toCharArray(); //$NON-NLS-1$ - + private final static char[] DOUBLE_QUOTES = "''".toCharArray(); //$NON-NLS-1$ + private final static char[] SINGLE_QUOTE = "'".toCharArray(); //$NON-NLS-1$ + private static final int DEFAULT_READING_SIZE = 8192; - + /* Bundle containing messages */ protected static ResourceBundle bundle; - private final static String bundleName = - "net.sourceforge.phpdt.internal.compiler.util.messages"; //$NON-NLS-1$ + + private final static String bundleName = "net.sourceforge.phpdt.internal.compiler.util.messages"; //$NON-NLS-1$ static { relocalize(); } + /** * Lookup the message with the given ID in this catalog and bind its * substitution locations with the given strings. @@ -57,6 +69,7 @@ public class Util { public static String bind(String id, String binding1, String binding2) { return bind(id, new String[] { binding1, binding2 }); } + /** * Lookup the message with the given ID in this catalog and bind its * substitution locations with the given string. @@ -64,6 +77,7 @@ public class Util { public static String bind(String id, String binding) { return bind(id, new String[] { binding }); } + /** * Lookup the message with the given ID in this catalog and bind its * substitution locations with the given string values. @@ -75,13 +89,16 @@ public class Util { try { message = bundle.getString(id); } catch (MissingResourceException e) { - // If we got an exception looking for the message, fail gracefully by just returning - // the id we were looking for. In most cases this is semi-informative so is not too bad. + // If we got an exception looking for the message, fail gracefully + // by just returning + // the id we were looking for. In most cases this is + // semi-informative so is not too bad. return "Missing message: " + id + " in: " + bundleName; //$NON-NLS-2$ //$NON-NLS-1$ } - // for compatibility with MessageFormat which eliminates double quotes in original message - char[] messageWithNoDoubleQuotes = - CharOperation.replace(message.toCharArray(), DOUBLE_QUOTES, SINGLE_QUOTE); + // for compatibility with MessageFormat which eliminates double quotes + // in original message + char[] messageWithNoDoubleQuotes = CharOperation.replace(message + .toCharArray(), DOUBLE_QUOTES, SINGLE_QUOTE); message = new String(messageWithNoDoubleQuotes); if (bindings == null) @@ -97,12 +114,14 @@ public class Util { if ((start = message.indexOf('}', end)) > -1) { int index = -1; try { - index = Integer.parseInt(message.substring(end + 1, start)); + index = Integer.parseInt(message.substring(end + 1, + start)); output.append(bindings[index]); } catch (NumberFormatException nfe) { output.append(message.substring(end + 1, start + 1)); } catch (ArrayIndexOutOfBoundsException e) { - output.append("{missing " + Integer.toString(index) + "}"); //$NON-NLS-2$ //$NON-NLS-1$ + output + .append("{missing " + Integer.toString(index) + "}"); //$NON-NLS-2$ //$NON-NLS-1$ } } else { output.append(message.substring(end, length)); @@ -115,34 +134,44 @@ public class Util { } return output.toString(); } + /** - * Lookup the message with the given ID in this catalog + * Lookup the message with the given ID in this catalog */ public static String bind(String id) { return bind(id, (String[]) null); } + /** * Creates a NLS catalog for the given locale. */ public static void relocalize() { try { bundle = ResourceBundle.getBundle(bundleName, Locale.getDefault()); - } catch(MissingResourceException e) { - System.out.println("Missing resource : " + bundleName.replace('.', '/') + ".properties for locale " + Locale.getDefault()); //$NON-NLS-1$//$NON-NLS-2$ + } catch (MissingResourceException e) { + System.out + .println("Missing resource : " + bundleName.replace('.', '/') + ".properties for locale " + Locale.getDefault()); //$NON-NLS-1$//$NON-NLS-2$ throw e; } } + /** - * Returns the given bytes as a char array using a given encoding (null means platform default). + * Returns the given bytes as a char array using a given encoding (null + * means platform default). */ - public static char[] bytesToChar(byte[] bytes, String encoding) throws IOException { + public static char[] bytesToChar(byte[] bytes, String encoding) + throws IOException { - return getInputStreamAsCharArray(new ByteArrayInputStream(bytes), bytes.length, encoding); + return getInputStreamAsCharArray(new ByteArrayInputStream(bytes), + bytes.length, encoding); } + /** * Returns the contents of the given file as a byte array. - * @throws IOException if a problem occured reading the file. + * + * @throws IOException + * if a problem occured reading the file. */ public static byte[] getFileByteContent(File file) throws IOException { InputStream stream = null; @@ -158,16 +187,21 @@ public class Util { } } } + /** - * Returns the contents of the given file as a char array. - * When encoding is null, then the platform default one is used - * @throws IOException if a problem occured reading the file. + * Returns the contents of the given file as a char array. When encoding is + * null, then the platform default one is used + * + * @throws IOException + * if a problem occured reading the file. */ - public static char[] getFileCharContent(File file, String encoding) throws IOException { + public static char[] getFileCharContent(File file, String encoding) + throws IOException { InputStream stream = null; try { stream = new BufferedInputStream(new FileInputStream(file)); - return Util.getInputStreamAsCharArray(stream, (int) file.length(), encoding); + return Util.getInputStreamAsCharArray(stream, (int) file.length(), + encoding); } finally { if (stream != null) { try { @@ -177,50 +211,48 @@ public class Util { } } } + /** - * Returns the given input stream's contents as a byte array. - * If a length is specified (ie. if length != -1), only length bytes - * are returned. Otherwise all bytes in the stream are returned. - * Note this doesn't close the stream. - * @throws IOException if a problem occured reading the stream. + * Returns the given input stream's contents as a byte array. If a length is + * specified (ie. if length != -1), only length bytes are returned. + * Otherwise all bytes in the stream are returned. Note this doesn't close + * the stream. + * + * @throws IOException + * if a problem occured reading the stream. */ - public static byte[] getInputStreamAsByteArray(InputStream stream, int length) - throws IOException { + public static byte[] getInputStreamAsByteArray(InputStream stream, + int length) throws IOException { byte[] contents; if (length == -1) { contents = new byte[0]; int contentsLength = 0; int amountRead = -1; do { - int amountRequested = Math.max(stream.available(), DEFAULT_READING_SIZE); // read at least 8K - + int amountRequested = Math.max(stream.available(), + DEFAULT_READING_SIZE); // read at least 8K + // resize contents if needed if (contentsLength + amountRequested > contents.length) { - System.arraycopy( - contents, - 0, - contents = new byte[contentsLength + amountRequested], - 0, - contentsLength); + System.arraycopy(contents, 0, + contents = new byte[contentsLength + + amountRequested], 0, contentsLength); } // read as many bytes as possible - amountRead = stream.read(contents, contentsLength, amountRequested); + amountRead = stream.read(contents, contentsLength, + amountRequested); if (amountRead > 0) { // remember length of contents contentsLength += amountRead; } - } while (amountRead != -1); + } while (amountRead != -1); // resize contents if necessary if (contentsLength < contents.length) { - System.arraycopy( - contents, - 0, - contents = new byte[contentsLength], - 0, - contentsLength); + System.arraycopy(contents, 0, + contents = new byte[contentsLength], 0, contentsLength); } } else { contents = new byte[length]; @@ -228,7 +260,8 @@ public class Util { int readSize = 0; while ((readSize != -1) && (len != length)) { // See PR 1FMS89U - // We record first the read size. In this case len is the actual read size. + // We record first the read size. In this case len is the actual + // read size. len += readSize; readSize = stream.read(contents, len, length - len); } @@ -236,39 +269,40 @@ public class Util { return contents; } + /** - * Returns the given input stream's contents as a character array. - * If a length is specified (ie. if length != -1), only length chars - * are returned. Otherwise all chars in the stream are returned. - * Note this doesn't close the stream. - * @throws IOException if a problem occured reading the stream. + * Returns the given input stream's contents as a character array. If a + * length is specified (ie. if length != -1), only length chars are + * returned. Otherwise all chars in the stream are returned. Note this + * doesn't close the stream. + * + * @throws IOException + * if a problem occured reading the stream. */ - public static char[] getInputStreamAsCharArray(InputStream stream, int length, String encoding) - throws IOException { + public static char[] getInputStreamAsCharArray(InputStream stream, + int length, String encoding) throws IOException { InputStreamReader reader = null; - reader = encoding == null - ? new InputStreamReader(stream) - : new InputStreamReader(stream, encoding); + reader = encoding == null ? new InputStreamReader(stream) + : new InputStreamReader(stream, encoding); char[] contents; if (length == -1) { contents = CharOperation.NO_CHAR; int contentsLength = 0; int amountRead = -1; do { - int amountRequested = Math.max(stream.available(), DEFAULT_READING_SIZE); // read at least 8K + int amountRequested = Math.max(stream.available(), + DEFAULT_READING_SIZE); // read at least 8K // resize contents if needed if (contentsLength + amountRequested > contents.length) { - System.arraycopy( - contents, - 0, - contents = new char[contentsLength + amountRequested], - 0, - contentsLength); + System.arraycopy(contents, 0, + contents = new char[contentsLength + + amountRequested], 0, contentsLength); } // read as many chars as possible - amountRead = reader.read(contents, contentsLength, amountRequested); + amountRead = reader.read(contents, contentsLength, + amountRequested); if (amountRead > 0) { // remember length of contents @@ -278,12 +312,8 @@ public class Util { // resize contents if necessary if (contentsLength < contents.length) { - System.arraycopy( - contents, - 0, - contents = new char[contentsLength], - 0, - contentsLength); + System.arraycopy(contents, 0, + contents = new char[contentsLength], 0, contentsLength); } } else { contents = new char[length]; @@ -291,26 +321,31 @@ public class Util { int readSize = 0; while ((readSize != -1) && (len != length)) { // See PR 1FMS89U - // We record first the read size. In this case len is the actual read size. + // We record first the read size. In this case len is the actual + // read size. len += readSize; readSize = reader.read(contents, len, length - len); } // See PR 1FMS89U - // Now we need to resize in case the default encoding used more than one byte for each + // Now we need to resize in case the default encoding used more than + // one byte for each // character if (len != length) - System.arraycopy(contents, 0, (contents = new char[len]), 0, len); + System.arraycopy(contents, 0, (contents = new char[len]), 0, + len); } return contents; } - + /** * Returns the contents of the given zip entry as a byte array. - * @throws IOException if a problem occured reading the zip entry. + * + * @throws IOException + * if a problem occured reading the zip entry. */ public static byte[] getZipEntryByteContent(ZipEntry ze, ZipFile zip) - throws IOException { + throws IOException { InputStream stream = null; try { @@ -325,66 +360,70 @@ public class Util { } } } + /** - * Returns true iff str.toLowerCase().endsWith(".jar") || str.toLowerCase().endsWith(".zip") - * implementation is not creating extra strings. + * Returns true iff str.toLowerCase().endsWith(".jar") || + * str.toLowerCase().endsWith(".zip") implementation is not creating extra + * strings. */ -// public final static boolean isArchiveFileName(String name) { -// int nameLength = name == null ? 0 : name.length(); -// int suffixLength = SUFFIX_JAR.length; -// if (nameLength < suffixLength) return false; -// -// // try to match as JAR file -// for (int i = 0; i < suffixLength; i++) { -// char c = name.charAt(nameLength - i - 1); -// int suffixIndex = suffixLength - i - 1; -// if (c != SUFFIX_jar[suffixIndex] && c != SUFFIX_JAR[suffixIndex]) { -// -// // try to match as ZIP file -// suffixLength = SUFFIX_ZIP.length; -// if (nameLength < suffixLength) return false; -// for (int j = 0; j < suffixLength; j++) { -// c = name.charAt(nameLength - j - 1); -// suffixIndex = suffixLength - j - 1; -// if (c != SUFFIX_zip[suffixIndex] && c != SUFFIX_ZIP[suffixIndex]) return false; -// } -// return true; -// } -// } -// return true; -// } + // public final static boolean isArchiveFileName(String name) { + // int nameLength = name == null ? 0 : name.length(); + // int suffixLength = SUFFIX_JAR.length; + // if (nameLength < suffixLength) return false; + // + // // try to match as JAR file + // for (int i = 0; i < suffixLength; i++) { + // char c = name.charAt(nameLength - i - 1); + // int suffixIndex = suffixLength - i - 1; + // if (c != SUFFIX_jar[suffixIndex] && c != SUFFIX_JAR[suffixIndex]) { + // + // // try to match as ZIP file + // suffixLength = SUFFIX_ZIP.length; + // if (nameLength < suffixLength) return false; + // for (int j = 0; j < suffixLength; j++) { + // c = name.charAt(nameLength - j - 1); + // suffixIndex = suffixLength - j - 1; + // if (c != SUFFIX_zip[suffixIndex] && c != SUFFIX_ZIP[suffixIndex]) return + // false; + // } + // return true; + // } + // } + // return true; + // } /** - * Returns true iff str.toLowerCase().endsWith(".class") - * implementation is not creating extra strings. + * Returns true iff str.toLowerCase().endsWith(".class") implementation is + * not creating extra strings. */ -// public final static boolean isClassFileName(String name) { -// int nameLength = name == null ? 0 : name.length(); -// int suffixLength = SUFFIX_CLASS.length; -// if (nameLength < suffixLength) return false; -// -// for (int i = 0; i < suffixLength; i++) { -// char c = name.charAt(nameLength - i - 1); -// int suffixIndex = suffixLength - i - 1; -// if (c != SUFFIX_class[suffixIndex] && c != SUFFIX_CLASS[suffixIndex]) return false; -// } -// return true; -// } - + // public final static boolean isClassFileName(String name) { + // int nameLength = name == null ? 0 : name.length(); + // int suffixLength = SUFFIX_CLASS.length; + // if (nameLength < suffixLength) return false; + // + // for (int i = 0; i < suffixLength; i++) { + // char c = name.charAt(nameLength - i - 1); + // int suffixIndex = suffixLength - i - 1; + // if (c != SUFFIX_class[suffixIndex] && c != SUFFIX_CLASS[suffixIndex]) + // return false; + // } + // return true; + // } /** - * Returns true iff str.toLowerCase().endsWith(".java") - * implementation is not creating extra strings. + * Returns true iff str.toLowerCase().endsWith(".java") implementation is + * not creating extra strings. */ public final static boolean isJavaFileName(String name) { return PHPFileUtil.isPHPFileName(name); -// int nameLength = name == null ? 0 : name.length(); -// int suffixLength = SUFFIX_JAVA.length; -// if (nameLength < suffixLength) return false; -// -// for (int i = 0; i < suffixLength; i++) { -// char c = name.charAt(nameLength - i - 1); -// int suffixIndex = suffixLength - i - 1; -// if (c != SUFFIX_java[suffixIndex] && c != SUFFIX_JAVA[suffixIndex]) return false; -// } -// return true; + // int nameLength = name == null ? 0 : name.length(); + // int suffixLength = SUFFIX_JAVA.length; + // if (nameLength < suffixLength) return false; + // + // for (int i = 0; i < suffixLength; i++) { + // char c = name.charAt(nameLength - i - 1); + // int suffixIndex = suffixLength - i - 1; + // if (c != SUFFIX_java[suffixIndex] && c != SUFFIX_JAVA[suffixIndex]) + // return false; + // } + // return true; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Assert.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Assert.java index 894ca7e..5cb5cd6 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Assert.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Assert.java @@ -13,82 +13,107 @@ package net.sourceforge.phpdt.internal.core; /* This class is not intended to be instantiated. */ public final class Assert { -private Assert() { - // cannot be instantiated -} -/** Asserts that an argument is legal. If the given boolean is - * not true, an IllegalArgumentException - * is thrown. - * - * @param expression the outcode of the check - * @return true if the check passes (does not return - * if the check fails) - * @exception IllegalArgumentException if the legality test failed - */ -public static boolean isLegal(boolean expression) { - return isLegal(expression, ""); //$NON-NLS-1$ -} -/** Asserts that an argument is legal. If the given boolean is - * not true, an IllegalArgumentException - * is thrown. - * The given message is included in that exception, to aid debugging. - * - * @param expression the outcode of the check - * @param message the message to include in the exception - * @return true if the check passes (does not return - * if the check fails) - * @exception IllegalArgumentException if the legality test failed - */ -public static boolean isLegal(boolean expression, String message) { - if (!expression) - throw new IllegalArgumentException(message); - return expression; -} -/** Asserts that the given object is not null. If this - * is not the case, some kind of unchecked exception is thrown. - * - * @param object the value to test - * @exception IllegalArgumentException if the object is null - */ -public static void isNotNull(Object object) { - isNotNull(object, ""); //$NON-NLS-1$ -} -/** Asserts that the given object is not null. If this - * is not the case, some kind of unchecked exception is thrown. - * The given message is included in that exception, to aid debugging. - * - * @param object the value to test - * @param message the message to include in the exception - * @exception IllegalArgumentException if the object is null - */ -public static void isNotNull(Object object, String message) { - if (object == null) - throw new AssertionFailedException("null argument; " + message); //$NON-NLS-1$ -} -/** Asserts that the given boolean is true. If this - * is not the case, some kind of unchecked exception is thrown. - * - * @param expression the outcode of the check - * @return true if the check passes (does not return - * if the check fails) - */ -public static boolean isTrue(boolean expression) { - return isTrue(expression, ""); //$NON-NLS-1$ -} -/** Asserts that the given boolean is true. If this - * is not the case, some kind of unchecked exception is thrown. - * The given message is included in that exception, to aid debugging. - * - * @param expression the outcode of the check - * @param message the message to include in the exception - * @return true if the check passes (does not return - * if the check fails) - */ -public static boolean isTrue(boolean expression, String message) { - if (!expression) - throw new AssertionFailedException("Assertion failed; " + message); //$NON-NLS-1$ - return expression; -} + private Assert() { + // cannot be instantiated + } + + /** + * Asserts that an argument is legal. If the given boolean is not + * true, an IllegalArgumentException is + * thrown. + * + * @param expression + * the outcode of the check + * @return true if the check passes (does not return if the + * check fails) + * @exception IllegalArgumentException + * if the legality test failed + */ + public static boolean isLegal(boolean expression) { + return isLegal(expression, ""); //$NON-NLS-1$ + } + + /** + * Asserts that an argument is legal. If the given boolean is not + * true, an IllegalArgumentException is + * thrown. The given message is included in that exception, to aid + * debugging. + * + * @param expression + * the outcode of the check + * @param message + * the message to include in the exception + * @return true if the check passes (does not return if the + * check fails) + * @exception IllegalArgumentException + * if the legality test failed + */ + public static boolean isLegal(boolean expression, String message) { + if (!expression) + throw new IllegalArgumentException(message); + return expression; + } + + /** + * Asserts that the given object is not null. If this is not + * the case, some kind of unchecked exception is thrown. + * + * @param object + * the value to test + * @exception IllegalArgumentException + * if the object is null + */ + public static void isNotNull(Object object) { + isNotNull(object, ""); //$NON-NLS-1$ + } + + /** + * Asserts that the given object is not null. If this is not + * the case, some kind of unchecked exception is thrown. The given message + * is included in that exception, to aid debugging. + * + * @param object + * the value to test + * @param message + * the message to include in the exception + * @exception IllegalArgumentException + * if the object is null + */ + public static void isNotNull(Object object, String message) { + if (object == null) + throw new AssertionFailedException("null argument; " + message); //$NON-NLS-1$ + } + + /** + * Asserts that the given boolean is true. If this is not + * the case, some kind of unchecked exception is thrown. + * + * @param expression + * the outcode of the check + * @return true if the check passes (does not return if the + * check fails) + */ + public static boolean isTrue(boolean expression) { + return isTrue(expression, ""); //$NON-NLS-1$ + } + + /** + * Asserts that the given boolean is true. If this is not + * the case, some kind of unchecked exception is thrown. The given message + * is included in that exception, to aid debugging. + * + * @param expression + * the outcode of the check + * @param message + * the message to include in the exception + * @return true if the check passes (does not return if the + * check fails) + */ + public static boolean isTrue(boolean expression, String message) { + if (!expression) + throw new AssertionFailedException("Assertion failed; " + message); //$NON-NLS-1$ + return expression; + } public static class AssertionFailedException extends RuntimeException { public AssertionFailedException(String detail) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BasicCompilationUnit.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BasicCompilationUnit.java index cf5d8d5..55cc761 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BasicCompilationUnit.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BasicCompilationUnit.java @@ -25,135 +25,146 @@ import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; /** - * A basic implementation of ICompilationUnit for use in the SourceMapper. + * A basic implementation of ICompilationUnit for use in the + * SourceMapper. * * @see ICompilationUnit */ public class BasicCompilationUnit implements ICompilationUnit { - protected char[] contents; - - protected char[] fileName; - - protected char[][] packageName; - - protected char[] mainTypeName; - - protected String encoding; - - protected IResource resource; - - // public BasicCompilationUnit(char[] contents, char[][] packageName, String fileName, String encoding) { - // this.contents = contents; - // this.fileName = fileName.toCharArray(); - // this.packageName = packageName; - // - // int start = fileName.lastIndexOf("/") + 1; //$NON-NLS-1$ - // if (start == 0 || start < fileName.lastIndexOf("\\")) //$NON-NLS-1$ - // start = fileName.lastIndexOf("\\") + 1; //$NON-NLS-1$ - // - // int end = fileName.lastIndexOf("."); //$NON-NLS-1$ - // if (end == -1) - // end = fileName.length(); - // - // this.mainTypeName = fileName.substring(start, end).toCharArray(); - // this.encoding = encoding; - // } - public BasicCompilationUnit(char[] contents, char[][] packageName, String fileName) { - this.contents = contents; - this.fileName = fileName.toCharArray(); - this.packageName = packageName; - - int start = fileName.lastIndexOf("/") + 1; //$NON-NLS-1$ - if (start == 0 || start < fileName.lastIndexOf("\\")) //$NON-NLS-1$ - start = fileName.lastIndexOf("\\") + 1; //$NON-NLS-1$ - - int end = fileName.lastIndexOf("."); //$NON-NLS-1$ - if (end == -1) - end = fileName.length(); - - this.mainTypeName = fileName.substring(start, end).toCharArray(); - this.encoding = null; - this.resource = null; - } - - public BasicCompilationUnit(char[] contents, char[][] packageName, String fileName, String encoding) { - this(contents, packageName, fileName); - this.encoding = encoding; - this.resource = null; - } - - public BasicCompilationUnit(char[] contents, char[][] packageName, String fileName, IJavaElement javaElement) { - this(contents, packageName, fileName); - initEncoding(javaElement); - } - - /* - * Initialize compilation unit encoding. If we have a project, then get file name corresponding IFile and retrieve its encoding - * using new API for encoding. In case of a class file, then go through project in order to let the possibility to retrieve a - * corresponding source file resource. If we have a compilation unit, then get encoding from its resource directly... - */ - private void initEncoding(IJavaElement javaElement) { - if (javaElement != null) { - try { - IJavaProject javaProject = javaElement.getJavaProject(); - switch (javaElement.getElementType()) { - case IJavaElement.COMPILATION_UNIT: - IFile file = (IFile) javaElement.getResource(); - - if (file != null) { - resource = file; - this.encoding = file.getCharset(); - break; - } - // if no file, then get project encoding - default: - IProject project = (IProject) javaProject.getResource(); - if (project != null) { - resource = project; - this.encoding = project.getDefaultCharset(); - } - break; - } - } catch (CoreException e1) { - this.encoding = null; - } - } else { - this.encoding = null; - } - } - - public char[] getContents() { - if (this.contents != null) - return this.contents; // answer the cached source - - // otherwise retrieve it - try { - return Util.getFileCharContent(new File(new String(fileName)), this.encoding); - } catch (IOException e) { - } - return CharOperation.NO_CHAR; - } - - public char[] getFileName() { - return this.fileName; - } - - public char[] getMainTypeName() { - return this.mainTypeName; - } - - public char[][] getPackageName() { - return this.packageName; - } - - public String toString() { - return "CompilationUnit: " + new String(fileName); //$NON-NLS-1$ - } - - /* (non-Javadoc) - * @see net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit#getResource() - */ - public IResource getResource() { - return resource; - } + protected char[] contents; + + protected char[] fileName; + + protected char[][] packageName; + + protected char[] mainTypeName; + + protected String encoding; + + protected IResource resource; + + // public BasicCompilationUnit(char[] contents, char[][] packageName, String + // fileName, String encoding) { + // this.contents = contents; + // this.fileName = fileName.toCharArray(); + // this.packageName = packageName; + // + // int start = fileName.lastIndexOf("/") + 1; //$NON-NLS-1$ + // if (start == 0 || start < fileName.lastIndexOf("\\")) //$NON-NLS-1$ + // start = fileName.lastIndexOf("\\") + 1; //$NON-NLS-1$ + // + // int end = fileName.lastIndexOf("."); //$NON-NLS-1$ + // if (end == -1) + // end = fileName.length(); + // + // this.mainTypeName = fileName.substring(start, end).toCharArray(); + // this.encoding = encoding; + // } + public BasicCompilationUnit(char[] contents, char[][] packageName, + String fileName) { + this.contents = contents; + this.fileName = fileName.toCharArray(); + this.packageName = packageName; + + int start = fileName.lastIndexOf("/") + 1; //$NON-NLS-1$ + if (start == 0 || start < fileName.lastIndexOf("\\")) //$NON-NLS-1$ + start = fileName.lastIndexOf("\\") + 1; //$NON-NLS-1$ + + int end = fileName.lastIndexOf("."); //$NON-NLS-1$ + if (end == -1) + end = fileName.length(); + + this.mainTypeName = fileName.substring(start, end).toCharArray(); + this.encoding = null; + this.resource = null; + } + + public BasicCompilationUnit(char[] contents, char[][] packageName, + String fileName, String encoding) { + this(contents, packageName, fileName); + this.encoding = encoding; + this.resource = null; + } + + public BasicCompilationUnit(char[] contents, char[][] packageName, + String fileName, IJavaElement javaElement) { + this(contents, packageName, fileName); + initEncoding(javaElement); + } + + /* + * Initialize compilation unit encoding. If we have a project, then get file + * name corresponding IFile and retrieve its encoding using new API for + * encoding. In case of a class file, then go through project in order to + * let the possibility to retrieve a corresponding source file resource. If + * we have a compilation unit, then get encoding from its resource + * directly... + */ + private void initEncoding(IJavaElement javaElement) { + if (javaElement != null) { + try { + IJavaProject javaProject = javaElement.getJavaProject(); + switch (javaElement.getElementType()) { + case IJavaElement.COMPILATION_UNIT: + IFile file = (IFile) javaElement.getResource(); + + if (file != null) { + resource = file; + this.encoding = file.getCharset(); + break; + } + // if no file, then get project encoding + default: + IProject project = (IProject) javaProject.getResource(); + if (project != null) { + resource = project; + this.encoding = project.getDefaultCharset(); + } + break; + } + } catch (CoreException e1) { + this.encoding = null; + } + } else { + this.encoding = null; + } + } + + public char[] getContents() { + if (this.contents != null) + return this.contents; // answer the cached source + + // otherwise retrieve it + try { + return Util.getFileCharContent(new File(new String(fileName)), + this.encoding); + } catch (IOException e) { + } + return CharOperation.NO_CHAR; + } + + public char[] getFileName() { + return this.fileName; + } + + public char[] getMainTypeName() { + return this.mainTypeName; + } + + public char[][] getPackageName() { + return this.packageName; + } + + public String toString() { + return "CompilationUnit: " + new String(fileName); //$NON-NLS-1$ + } + + /* + * (non-Javadoc) + * + * @see net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit#getResource() + */ + public IResource getResource() { + return resource; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BatchOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BatchOperation.java index be36943..85e4221 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BatchOperation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BatchOperation.java @@ -17,18 +17,21 @@ import org.eclipse.core.resources.IResourceStatus; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.runtime.CoreException; - /** - * An operation created as a result of a call to JavaCore.run(IWorkspaceRunnable, IProgressMonitor) - * that encapsulates a user defined IWorkspaceRunnable. + * An operation created as a result of a call to + * JavaCore.run(IWorkspaceRunnable, IProgressMonitor) that encapsulates a user + * defined IWorkspaceRunnable. */ public class BatchOperation extends JavaModelOperation { protected IWorkspaceRunnable runnable; + public BatchOperation(IWorkspaceRunnable runnable) { this.runnable = runnable; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpdt.internal.core.JavaModelOperation#executeOperation() */ protected void executeOperation() throws JavaModelException { @@ -36,10 +39,10 @@ public class BatchOperation extends JavaModelOperation { this.runnable.run(progressMonitor); } catch (CoreException ce) { if (ce instanceof JavaModelException) { - throw (JavaModelException)ce; + throw (JavaModelException) ce; } else { if (ce.getStatus().getCode() == IResourceStatus.OPERATION_FAILED) { - Throwable e= ce.getStatus().getException(); + Throwable e = ce.getStatus().getException(); if (e instanceof JavaModelException) { throw (JavaModelException) e; } @@ -48,8 +51,10 @@ public class BatchOperation extends JavaModelOperation { } } } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see net.sourceforge.phpdt.internal.core.JavaModelOperation#verify() */ protected IJavaModelStatus verify() { @@ -57,5 +62,4 @@ public class BatchOperation extends JavaModelOperation { return JavaModelStatus.VERIFIED_OK; } - } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BecomeWorkingCopyOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BecomeWorkingCopyOperation.java index a3150db..41b83bb 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BecomeWorkingCopyOperation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BecomeWorkingCopyOperation.java @@ -16,27 +16,34 @@ import net.sourceforge.phpdt.core.IProblemRequestor; import net.sourceforge.phpdt.core.JavaModelException; /** - * Switch and ICompilationUnit to working copy mode - * and signal the working copy addition through a delta. + * Switch and ICompilationUnit to working copy mode and signal the working copy + * addition through a delta. */ public class BecomeWorkingCopyOperation extends JavaModelOperation { - + IProblemRequestor problemRequestor; - + /* * Creates a BecomeWorkingCopyOperation for the given working copy. - * perOwnerWorkingCopies map is not null if the working copy is a shared working copy. + * perOwnerWorkingCopies map is not null if the working copy is a shared + * working copy. */ - public BecomeWorkingCopyOperation(CompilationUnit workingCopy, IProblemRequestor problemRequestor) { - super(new IJavaElement[] {workingCopy}); + public BecomeWorkingCopyOperation(CompilationUnit workingCopy, + IProblemRequestor problemRequestor) { + super(new IJavaElement[] { workingCopy }); this.problemRequestor = problemRequestor; } + protected void executeOperation() throws JavaModelException { - // open the working copy now to ensure contents are that of the current state of this element + // open the working copy now to ensure contents are that of the current + // state of this element CompilationUnit workingCopy = getWorkingCopy(); - JavaModelManager.getJavaModelManager().getPerWorkingCopyInfo(workingCopy, true/*create if needed*/, true/*record usage*/, this.problemRequestor); - workingCopy.openWhenClosed(workingCopy.createElementInfo(), this.progressMonitor); + JavaModelManager.getJavaModelManager().getPerWorkingCopyInfo( + workingCopy, true/* create if needed */, true/* record usage */, + this.problemRequestor); + workingCopy.openWhenClosed(workingCopy.createElementInfo(), + this.progressMonitor); if (!workingCopy.isPrimary()) { // report added java delta for a non-primary working copy @@ -45,26 +52,33 @@ public class BecomeWorkingCopyOperation extends JavaModelOperation { addDelta(delta); } else { if (workingCopy.getResource().isAccessible()) { - // report a F_PRIMARY_WORKING_COPY change delta for a primary working copy - JavaElementDelta delta = new JavaElementDelta(this.getJavaModel()); - delta.changed(workingCopy, IJavaElementDelta.F_PRIMARY_WORKING_COPY); + // report a F_PRIMARY_WORKING_COPY change delta for a primary + // working copy + JavaElementDelta delta = new JavaElementDelta(this + .getJavaModel()); + delta.changed(workingCopy, + IJavaElementDelta.F_PRIMARY_WORKING_COPY); addDelta(delta); } else { // report an ADDED delta - JavaElementDelta delta = new JavaElementDelta(this.getJavaModel()); - delta.added(workingCopy, IJavaElementDelta.F_PRIMARY_WORKING_COPY); + JavaElementDelta delta = new JavaElementDelta(this + .getJavaModel()); + delta.added(workingCopy, + IJavaElementDelta.F_PRIMARY_WORKING_COPY); addDelta(delta); } } - this.resultElements = new IJavaElement[] {workingCopy}; + this.resultElements = new IJavaElement[] { workingCopy }; } + /* * Returns the working copy this operation is working on. */ protected CompilationUnit getWorkingCopy() { - return (CompilationUnit)getElementToProcess(); + return (CompilationUnit) getElementToProcess(); } + /* * @see JavaModelOperation#isReadOnly */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Buffer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Buffer.java index fba30a0..f10bdf0 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Buffer.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Buffer.java @@ -34,397 +34,453 @@ import org.eclipse.core.runtime.Platform; */ public class Buffer implements IBuffer { protected IFile file; + protected int flags; + protected char[] contents; + protected ArrayList changeListeners; + protected IOpenable owner; - protected int gapStart= -1; - protected int gapEnd= -1; - protected Object lock= new Object(); + protected int gapStart = -1; - protected static final int F_HAS_UNSAVED_CHANGES= 1; - protected static final int F_IS_READ_ONLY= 2; - protected static final int F_IS_CLOSED= 4; + protected int gapEnd = -1; -/** - * Creates a new buffer on an underlying resource. - */ -protected Buffer(IFile file, IOpenable owner, boolean readOnly) { - this.file = file; - this.owner = owner; - if (file == null) { - setReadOnly(readOnly); + protected Object lock = new Object(); + + protected static final int F_HAS_UNSAVED_CHANGES = 1; + + protected static final int F_IS_READ_ONLY = 2; + + protected static final int F_IS_CLOSED = 4; + + /** + * Creates a new buffer on an underlying resource. + */ + protected Buffer(IFile file, IOpenable owner, boolean readOnly) { + this.file = file; + this.owner = owner; + if (file == null) { + setReadOnly(readOnly); + } } -} -/** - * @see IBuffer - */ -public void addBufferChangedListener(IBufferChangedListener listener) { - if (this.changeListeners == null) { - this.changeListeners = new ArrayList(5); + + /** + * @see IBuffer + */ + public void addBufferChangedListener(IBufferChangedListener listener) { + if (this.changeListeners == null) { + this.changeListeners = new ArrayList(5); + } + if (!this.changeListeners.contains(listener)) { + this.changeListeners.add(listener); + } } - if (!this.changeListeners.contains(listener)) { - this.changeListeners.add(listener); + + /** + * Append the text to the actual content, the gap is moved to + * the end of the text. + */ + public void append(char[] text) { + if (!isReadOnly()) { + if (text == null || text.length == 0) { + return; + } + int length = getLength(); + moveAndResizeGap(length, text.length); + System.arraycopy(text, 0, this.contents, length, text.length); + this.gapStart += text.length; + this.flags |= F_HAS_UNSAVED_CHANGES; + notifyChanged(new BufferChangedEvent(this, length, 0, new String( + text))); + } } -} -/** - * Append the text to the actual content, the gap is moved - * to the end of the text. - */ -public void append(char[] text) { - if (!isReadOnly()) { - if (text == null || text.length == 0) { + + /** + * Append the text to the actual content, the gap is moved to + * the end of the text. + */ + public void append(String text) { + if (text == null) { return; } - int length = getLength(); - moveAndResizeGap(length, text.length); - System.arraycopy(text, 0, this.contents, length, text.length); - this.gapStart += text.length; - this.flags |= F_HAS_UNSAVED_CHANGES; - notifyChanged(new BufferChangedEvent(this, length, 0, new String(text))); + this.append(text.toCharArray()); } -} -/** - * Append the text to the actual content, the gap is moved - * to the end of the text. - */ -public void append(String text) { - if (text == null) { - return; + + /** + * @see IBuffer + */ + public void close() throws IllegalArgumentException { + BufferChangedEvent event = null; + synchronized (this.lock) { + if (isClosed()) + return; + event = new BufferChangedEvent(this, 0, 0, null); + this.contents = null; + this.flags |= F_IS_CLOSED; + } + notifyChanged(event); // notify outside of synchronized block + this.changeListeners = null; } - this.append(text.toCharArray()); -} -/** - * @see IBuffer - */ -public void close() throws IllegalArgumentException { - BufferChangedEvent event = null; - synchronized (this.lock) { - if (isClosed()) - return; - event = new BufferChangedEvent(this, 0, 0, null); - this.contents = null; - this.flags |= F_IS_CLOSED; + + /** + * @see IBuffer + */ + public char getChar(int position) { + synchronized (this.lock) { + if (position < this.gapStart) { + return this.contents[position]; + } + int gapLength = this.gapEnd - this.gapStart; + return this.contents[position + gapLength]; + } } - notifyChanged(event); // notify outside of synchronized block - this.changeListeners = null; -} -/** - * @see IBuffer - */ -public char getChar(int position) { - synchronized (this.lock) { - if (position < this.gapStart) { - return this.contents[position]; + + /** + * @see IBuffer + */ + public char[] getCharacters() { + if (this.contents == null) + return null; + synchronized (this.lock) { + if (this.gapStart < 0) { + return this.contents; + } + int length = this.contents.length; + char[] newContents = new char[length - this.gapEnd + this.gapStart]; + System.arraycopy(this.contents, 0, newContents, 0, this.gapStart); + System.arraycopy(this.contents, this.gapEnd, newContents, + this.gapStart, length - this.gapEnd); + return newContents; } - int gapLength = this.gapEnd - this.gapStart; - return this.contents[position + gapLength]; } -} -/** - * @see IBuffer - */ -public char[] getCharacters() { - if (this.contents == null) return null; - synchronized (this.lock) { - if (this.gapStart < 0) { - return this.contents; + + /** + * @see IBuffer + */ + public String getContents() { + char[] chars = this.getCharacters(); + if (chars == null) + return null; + return new String(chars); + } + + /** + * @see IBuffer + */ + public int getLength() { + synchronized (this.lock) { + int length = this.gapEnd - this.gapStart; + return (this.contents.length - length); } - int length = this.contents.length; - char[] newContents = new char[length - this.gapEnd + this.gapStart]; - System.arraycopy(this.contents, 0, newContents, 0, this.gapStart); - System.arraycopy(this.contents, this.gapEnd, newContents, this.gapStart, length - this.gapEnd); - return newContents; } -} -/** - * @see IBuffer - */ -public String getContents() { - char[] chars = this.getCharacters(); - if (chars == null) return null; - return new String(chars); -} -/** - * @see IBuffer - */ -public int getLength() { - synchronized (this.lock) { - int length = this.gapEnd - this.gapStart; - return (this.contents.length - length); + + /** + * @see IBuffer + */ + public IOpenable getOwner() { + return this.owner; } -} -/** - * @see IBuffer - */ -public IOpenable getOwner() { - return this.owner; -} -/** - * @see IBuffer - */ -public String getText(int offset, int length) { - if (this.contents == null) - return ""; //$NON-NLS-1$ - synchronized (this.lock) { - if (offset + length < this.gapStart) - return new String(this.contents, offset, length); - if (this.gapStart < offset) { - int gapLength = this.gapEnd - this.gapStart; - return new String(this.contents, offset + gapLength, length); + + /** + * @see IBuffer + */ + public String getText(int offset, int length) { + if (this.contents == null) + return ""; //$NON-NLS-1$ + synchronized (this.lock) { + if (offset + length < this.gapStart) + return new String(this.contents, offset, length); + if (this.gapStart < offset) { + int gapLength = this.gapEnd - this.gapStart; + return new String(this.contents, offset + gapLength, length); + } + StringBuffer buf = new StringBuffer(); + buf.append(this.contents, offset, this.gapStart - offset); + buf.append(this.contents, this.gapEnd, offset + length + - this.gapStart); + return buf.toString(); } - StringBuffer buf = new StringBuffer(); - buf.append(this.contents, offset, this.gapStart - offset); - buf.append(this.contents, this.gapEnd, offset + length - this.gapStart); - return buf.toString(); } -} -/** - * @see IBuffer - */ -public IResource getUnderlyingResource() { - return this.file; -} -/** - * @see IBuffer - */ -public boolean hasUnsavedChanges() { - return (this.flags & F_HAS_UNSAVED_CHANGES) != 0; -} -/** - * @see IBuffer - */ -public boolean isClosed() { - return (this.flags & F_IS_CLOSED) != 0; -} -/** - * @see IBuffer - */ -public boolean isReadOnly() { - if (this.file == null) { - return (this.flags & F_IS_READ_ONLY) != 0; - } else { - return this.file.isReadOnly(); + + /** + * @see IBuffer + */ + public IResource getUnderlyingResource() { + return this.file; } -} -/** - * Moves the gap to location and adjust its size to the - * anticipated change size. The size represents the expected - * range of the gap that will be filled after the gap has been moved. - * Thus the gap is resized to actual size + the specified size and - * moved to the given position. - */ -protected void moveAndResizeGap(int position, int size) { - char[] content = null; - int oldSize = this.gapEnd - this.gapStart; - if (size < 0) { - if (oldSize > 0) { - content = new char[this.contents.length - oldSize]; - System.arraycopy(this.contents, 0, content, 0, this.gapStart); - System.arraycopy(this.contents, this.gapEnd, content, this.gapStart, content.length - this.gapStart); - this.contents = content; + + /** + * @see IBuffer + */ + public boolean hasUnsavedChanges() { + return (this.flags & F_HAS_UNSAVED_CHANGES) != 0; + } + + /** + * @see IBuffer + */ + public boolean isClosed() { + return (this.flags & F_IS_CLOSED) != 0; + } + + /** + * @see IBuffer + */ + public boolean isReadOnly() { + if (this.file == null) { + return (this.flags & F_IS_READ_ONLY) != 0; + } else { + return this.file.isReadOnly(); } - this.gapStart = this.gapEnd = position; - return; } - content = new char[this.contents.length + (size - oldSize)]; - int newGapStart = position; - int newGapEnd = newGapStart + size; - if (oldSize == 0) { - System.arraycopy(this.contents, 0, content, 0, newGapStart); - System.arraycopy(this.contents, newGapStart, content, newGapEnd, content.length - newGapEnd); - } else - if (newGapStart < this.gapStart) { + + /** + * Moves the gap to location and adjust its size to the anticipated change + * size. The size represents the expected range of the gap that will be + * filled after the gap has been moved. Thus the gap is resized to actual + * size + the specified size and moved to the given position. + */ + protected void moveAndResizeGap(int position, int size) { + char[] content = null; + int oldSize = this.gapEnd - this.gapStart; + if (size < 0) { + if (oldSize > 0) { + content = new char[this.contents.length - oldSize]; + System.arraycopy(this.contents, 0, content, 0, this.gapStart); + System.arraycopy(this.contents, this.gapEnd, content, + this.gapStart, content.length - this.gapStart); + this.contents = content; + } + this.gapStart = this.gapEnd = position; + return; + } + content = new char[this.contents.length + (size - oldSize)]; + int newGapStart = position; + int newGapEnd = newGapStart + size; + if (oldSize == 0) { + System.arraycopy(this.contents, 0, content, 0, newGapStart); + System.arraycopy(this.contents, newGapStart, content, newGapEnd, + content.length - newGapEnd); + } else if (newGapStart < this.gapStart) { int delta = this.gapStart - newGapStart; System.arraycopy(this.contents, 0, content, 0, newGapStart); - System.arraycopy(this.contents, newGapStart, content, newGapEnd, delta); - System.arraycopy(this.contents, this.gapEnd, content, newGapEnd + delta, this.contents.length - this.gapEnd); + System.arraycopy(this.contents, newGapStart, content, newGapEnd, + delta); + System.arraycopy(this.contents, this.gapEnd, content, newGapEnd + + delta, this.contents.length - this.gapEnd); } else { int delta = newGapStart - this.gapStart; System.arraycopy(this.contents, 0, content, 0, this.gapStart); - System.arraycopy(this.contents, this.gapEnd, content, this.gapStart, delta); - System.arraycopy(this.contents, this.gapEnd + delta, content, newGapEnd, content.length - newGapEnd); + System.arraycopy(this.contents, this.gapEnd, content, + this.gapStart, delta); + System.arraycopy(this.contents, this.gapEnd + delta, content, + newGapEnd, content.length - newGapEnd); } - this.contents = content; - this.gapStart = newGapStart; - this.gapEnd = newGapEnd; -} -/** - * Notify the listeners that this buffer has changed. - * To avoid deadlock, this should not be called in a synchronized block. - */ -protected void notifyChanged(final BufferChangedEvent event) { - if (this.changeListeners != null) { - for (int i = 0, size = this.changeListeners.size(); i < size; ++i) { - final IBufferChangedListener listener = (IBufferChangedListener) this.changeListeners.get(i); - Platform.run(new ISafeRunnable() { - public void handleException(Throwable exception) { - Util.log(exception, "Exception occurred in listener of buffer change notification"); //$NON-NLS-1$ - } - public void run() throws Exception { - listener.bufferChanged(event); - } - }); - + this.contents = content; + this.gapStart = newGapStart; + this.gapEnd = newGapEnd; + } + + /** + * Notify the listeners that this buffer has changed. To avoid deadlock, + * this should not be called in a synchronized block. + */ + protected void notifyChanged(final BufferChangedEvent event) { + if (this.changeListeners != null) { + for (int i = 0, size = this.changeListeners.size(); i < size; ++i) { + final IBufferChangedListener listener = (IBufferChangedListener) this.changeListeners + .get(i); + Platform.run(new ISafeRunnable() { + public void handleException(Throwable exception) { + Util + .log(exception, + "Exception occurred in listener of buffer change notification"); //$NON-NLS-1$ + } + + public void run() throws Exception { + listener.bufferChanged(event); + } + }); + + } } } -} -/** - * @see IBuffer - */ -public void removeBufferChangedListener(IBufferChangedListener listener) { - if (this.changeListeners != null) { - this.changeListeners.remove(listener); - if (this.changeListeners.size() == 0) { - this.changeListeners = null; + + /** + * @see IBuffer + */ + public void removeBufferChangedListener(IBufferChangedListener listener) { + if (this.changeListeners != null) { + this.changeListeners.remove(listener); + if (this.changeListeners.size() == 0) { + this.changeListeners = null; + } } } -} -/** - * Replaces length characters starting from position with text. - * After that operation, the gap is placed at the end of the - * inserted text. - */ -public void replace(int position, int length, char[] text) { - if (!isReadOnly()) { - int textLength = text == null ? 0 : text.length; - synchronized (this.lock) { - // move gap - moveAndResizeGap(position + length, textLength - length); - // overwrite - int min = Math.min(textLength, length); - if (min > 0) { - System.arraycopy(text, 0, this.contents, position, min); + /** + * Replaces length characters starting from + * position with text. + * After that operation, the gap is placed at the end of the + * inserted text. + */ + public void replace(int position, int length, char[] text) { + if (!isReadOnly()) { + int textLength = text == null ? 0 : text.length; + synchronized (this.lock) { + // move gap + moveAndResizeGap(position + length, textLength - length); + + // overwrite + int min = Math.min(textLength, length); + if (min > 0) { + System.arraycopy(text, 0, this.contents, position, min); + } + if (length > textLength) { + // enlarge the gap + this.gapStart -= length - textLength; + } else if (textLength > length) { + // shrink gap + this.gapStart += textLength - length; + System.arraycopy(text, 0, this.contents, position, + textLength); + } } - if (length > textLength) { - // enlarge the gap - this.gapStart -= length - textLength; - } else if (textLength > length) { - // shrink gap - this.gapStart += textLength - length; - System.arraycopy(text, 0, this.contents, position, textLength); + this.flags |= F_HAS_UNSAVED_CHANGES; + String string = null; + if (textLength > 0) { + string = new String(text); } + notifyChanged(new BufferChangedEvent(this, position, length, string)); } - this.flags |= F_HAS_UNSAVED_CHANGES; - String string = null; - if (textLength > 0) { - string = new String(text); - } - notifyChanged(new BufferChangedEvent(this, position, length, string)); } -} -/** - * Replaces length characters starting from position with text. - * After that operation, the gap is placed at the end of the - * inserted text. - */ -public void replace(int position, int length, String text) { - this.replace(position, length, text == null ? null : text.toCharArray()); -} -/** - * @see IBuffer - */ -public void save(IProgressMonitor progress, boolean force) throws JavaModelException { - // determine if saving is required - if (isReadOnly() || this.file == null) { - return; + /** + * Replaces length characters starting from + * position with text. + * After that operation, the gap is placed at the end of the + * inserted text. + */ + public void replace(int position, int length, String text) { + this + .replace(position, length, text == null ? null : text + .toCharArray()); } - synchronized (this.lock) { - if (!hasUnsavedChanges()) + + /** + * @see IBuffer + */ + public void save(IProgressMonitor progress, boolean force) + throws JavaModelException { + + // determine if saving is required + if (isReadOnly() || this.file == null) { return; - - // use a platform operation to update the resource contents - try { -// String encoding = ((IJavaElement)this.owner).getJavaProject().getOption(PHPCore.CORE_ENCODING, true); - String encoding = null; - String contents = this.getContents(); - if (contents == null) return; - byte[] bytes = encoding == null - ? contents.getBytes() - : contents.getBytes(encoding); - ByteArrayInputStream stream = new ByteArrayInputStream(bytes); - - this.file.setContents( - stream, - force ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY, - null); - } catch (IOException e) { - throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); - } catch (CoreException e) { - throw new JavaModelException(e); } + synchronized (this.lock) { + if (!hasUnsavedChanges()) + return; - // the resource no longer has unsaved changes - this.flags &= ~ (F_HAS_UNSAVED_CHANGES); - } -} -/** - * @see IBuffer - */ -public void setContents(char[] newContents) { - // allow special case for first initialization - // after creation by buffer factory - if (this.contents == null) { - this.contents = newContents; - this.flags &= ~ (F_HAS_UNSAVED_CHANGES); - return; - } - - if (!isReadOnly()) { - String string = null; - if (newContents != null) { - string = new String(newContents); + // use a platform operation to update the resource contents + try { + // String encoding = + // ((IJavaElement)this.owner).getJavaProject().getOption(PHPCore.CORE_ENCODING, + // true); + String encoding = null; + String contents = this.getContents(); + if (contents == null) + return; + byte[] bytes = encoding == null ? contents.getBytes() + : contents.getBytes(encoding); + ByteArrayInputStream stream = new ByteArrayInputStream(bytes); + + this.file + .setContents(stream, force ? IResource.FORCE + | IResource.KEEP_HISTORY + : IResource.KEEP_HISTORY, null); + } catch (IOException e) { + throw new JavaModelException(e, + IJavaModelStatusConstants.IO_EXCEPTION); + } catch (CoreException e) { + throw new JavaModelException(e); + } + + // the resource no longer has unsaved changes + this.flags &= ~(F_HAS_UNSAVED_CHANGES); } - BufferChangedEvent event = new BufferChangedEvent(this, 0, this.getLength(), string); - synchronized (this.lock) { + } + + /** + * @see IBuffer + */ + public void setContents(char[] newContents) { + // allow special case for first initialization + // after creation by buffer factory + if (this.contents == null) { this.contents = newContents; - this.flags |= F_HAS_UNSAVED_CHANGES; - this.gapStart = -1; - this.gapEnd = -1; + this.flags &= ~(F_HAS_UNSAVED_CHANGES); + return; + } + + if (!isReadOnly()) { + String string = null; + if (newContents != null) { + string = new String(newContents); + } + BufferChangedEvent event = new BufferChangedEvent(this, 0, this + .getLength(), string); + synchronized (this.lock) { + this.contents = newContents; + this.flags |= F_HAS_UNSAVED_CHANGES; + this.gapStart = -1; + this.gapEnd = -1; + } + notifyChanged(event); } - notifyChanged(event); } -} -/** - * @see IBuffer - */ -public void setContents(String newContents) { - this.setContents(newContents.toCharArray()); -} -/** - * Sets this Buffer to be read only. - */ -protected void setReadOnly(boolean readOnly) { - if (readOnly) { - this.flags |= F_IS_READ_ONLY; - } else { - this.flags &= ~(F_IS_READ_ONLY); + + /** + * @see IBuffer + */ + public void setContents(String newContents) { + this.setContents(newContents.toCharArray()); } -} -public String toString() { - StringBuffer buffer = new StringBuffer(); -// buffer.append("Owner: " + ((JavaElement)this.owner).toStringWithAncestors()); //$NON-NLS-1$ - buffer.append("Owner: " + (this.owner).toString()); //$NON-NLS-1$ - buffer.append("\nHas unsaved changes: " + this.hasUnsavedChanges()); //$NON-NLS-1$ - buffer.append("\nIs readonly: " + this.isReadOnly()); //$NON-NLS-1$ - buffer.append("\nIs closed: " + this.isClosed()); //$NON-NLS-1$ - buffer.append("\nContents:\n"); //$NON-NLS-1$ - char[] contents = this.getCharacters(); - if (contents == null) { - buffer.append(""); //$NON-NLS-1$ - } else { - int length = contents.length; - for (int i = 0; i < length; i++) { - char car = contents[i]; - switch (car) { - case '\n': + + /** + * Sets this Buffer to be read only. + */ + protected void setReadOnly(boolean readOnly) { + if (readOnly) { + this.flags |= F_IS_READ_ONLY; + } else { + this.flags &= ~(F_IS_READ_ONLY); + } + } + + public String toString() { + StringBuffer buffer = new StringBuffer(); + // buffer.append("Owner: " + + // ((JavaElement)this.owner).toStringWithAncestors()); //$NON-NLS-1$ + buffer.append("Owner: " + (this.owner).toString()); //$NON-NLS-1$ + buffer.append("\nHas unsaved changes: " + this.hasUnsavedChanges()); //$NON-NLS-1$ + buffer.append("\nIs readonly: " + this.isReadOnly()); //$NON-NLS-1$ + buffer.append("\nIs closed: " + this.isClosed()); //$NON-NLS-1$ + buffer.append("\nContents:\n"); //$NON-NLS-1$ + char[] contents = this.getCharacters(); + if (contents == null) { + buffer.append(""); //$NON-NLS-1$ + } else { + int length = contents.length; + for (int i = 0; i < length; i++) { + char car = contents[i]; + switch (car) { + case '\n': buffer.append("\\n\n"); //$NON-NLS-1$ break; case '\r': - if (i < length-1 && this.contents[i+1] == '\n') { + if (i < length - 1 && this.contents[i + 1] == '\n') { buffer.append("\\r\\n\n"); //$NON-NLS-1$ i++; } else { @@ -434,9 +490,9 @@ public String toString() { default: buffer.append(car); break; + } } } + return buffer.toString(); } - return buffer.toString(); -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BufferCache.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BufferCache.java index 7413c26..a923a82 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BufferCache.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BufferCache.java @@ -17,34 +17,38 @@ import net.sourceforge.phpdt.internal.core.util.LRUCache; * An LRU cache of IBuffers. */ public class BufferCache extends OverflowingLRUCache { -/** - * Constructs a new buffer cache of the given size. - */ -public BufferCache(int size) { - super(size); -} -/** - * Constructs a new buffer cache of the given size. - */ -public BufferCache(int size, int overflow) { - super(size, overflow); -} -/** - * Returns true if the buffer is successfully closed and - * removed from the cache, otherwise false. - * - *

                NOTE: this triggers an external removal of this buffer - * by closing the buffer. - */ -protected boolean close(LRUCacheEntry entry) { - IBuffer buffer= (IBuffer) entry._fValue; - if (buffer.hasUnsavedChanges()) { - return false; - } else { - buffer.close(); - return true; + /** + * Constructs a new buffer cache of the given size. + */ + public BufferCache(int size) { + super(size); } -} + + /** + * Constructs a new buffer cache of the given size. + */ + public BufferCache(int size, int overflow) { + super(size, overflow); + } + + /** + * Returns true if the buffer is successfully closed and removed from the + * cache, otherwise false. + * + *

                + * NOTE: this triggers an external removal of this buffer by closing the + * buffer. + */ + protected boolean close(LRUCacheEntry entry) { + IBuffer buffer = (IBuffer) entry._fValue; + if (buffer.hasUnsavedChanges()) { + return false; + } else { + buffer.close(); + return true; + } + } + /** * Returns a new instance of the reciever. */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BufferFactoryWrapper.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BufferFactoryWrapper.java index a12e82a..fa2485c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BufferFactoryWrapper.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BufferFactoryWrapper.java @@ -15,40 +15,50 @@ import net.sourceforge.phpdt.core.ICompilationUnit; import net.sourceforge.phpdt.core.WorkingCopyOwner; /** - * Wraps an IBufferFactory. - * TODO remove when removing IBufferFactory + * Wraps an IBufferFactory. TODO remove when removing IBufferFactory + * * @deprecated */ public class BufferFactoryWrapper extends WorkingCopyOwner { public net.sourceforge.phpdt.core.IBufferFactory factory; - - private BufferFactoryWrapper(net.sourceforge.phpdt.core.IBufferFactory factory) { + + private BufferFactoryWrapper( + net.sourceforge.phpdt.core.IBufferFactory factory) { this.factory = factory; } - - public static WorkingCopyOwner create(net.sourceforge.phpdt.core.IBufferFactory factory) { + + public static WorkingCopyOwner create( + net.sourceforge.phpdt.core.IBufferFactory factory) { return new BufferFactoryWrapper(factory); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpdt.core.WorkingCopyOwner#createBuffer(net.sourceforge.phpdt.core.ICompilationUnit) */ public IBuffer createBuffer(ICompilationUnit workingCopy) { - if (this.factory == null) return super.createBuffer(workingCopy); + if (this.factory == null) + return super.createBuffer(workingCopy); return this.factory.createBuffer(workingCopy); - } - + } + public boolean equals(Object obj) { - if (!(obj instanceof BufferFactoryWrapper)) return false; - BufferFactoryWrapper other = (BufferFactoryWrapper)obj; - if (this.factory == null) return other.factory == null; + if (!(obj instanceof BufferFactoryWrapper)) + return false; + BufferFactoryWrapper other = (BufferFactoryWrapper) obj; + if (this.factory == null) + return other.factory == null; return this.factory.equals(other.factory); } + public int hashCode() { - if (this.factory == null) return 0; + if (this.factory == null) + return 0; return this.factory.hashCode(); } + public String toString() { return "FactoryWrapper for " + this.factory; //$NON-NLS-1$ } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BufferManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BufferManager.java index 511d041..02839c8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BufferManager.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BufferManager.java @@ -20,88 +20,88 @@ import net.sourceforge.phpdt.core.IOpenable; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; - /** - * The buffer manager manages the set of open buffers. - * It implements an LRU cache of buffers. + * The buffer manager manages the set of open buffers. It implements an LRU + * cache of buffers. */ public class BufferManager implements IBufferFactory { protected static BufferManager DEFAULT_BUFFER_MANAGER; /** - * LRU cache of buffers. The key and value for an entry - * in the table is the identical buffer. + * LRU cache of buffers. The key and value for an entry in the table is the + * identical buffer. */ protected OverflowingLRUCache openBuffers = new BufferCache(60); -/** - * Creates a new buffer manager. - */ -public BufferManager() { -} -/** - * Adds a buffer to the table of open buffers. - */ -protected void addBuffer(IBuffer buffer) { - openBuffers.put(buffer.getOwner(), buffer); -} -/** - * @see IBufferFactory#createBuffer(IOpenable) - */ -public IBuffer createBuffer(IOpenable owner) { - IJavaElement element = (IJavaElement)owner; - IResource resource = element.getResource(); - return - new Buffer( - resource instanceof IFile ? (IFile)resource : null, - owner, - element.isReadOnly()); -} + /** + * Creates a new buffer manager. + */ + public BufferManager() { + } -/** - * Returns the open buffer associated with the given owner, - * or null if the owner does not have an open - * buffer associated with it. - */ -public IBuffer getBuffer(IOpenable owner) { - return (IBuffer)openBuffers.get(owner); -} -/** - * Returns the default buffer manager. - */ -public synchronized static BufferManager getDefaultBufferManager() { - if (DEFAULT_BUFFER_MANAGER == null) { - DEFAULT_BUFFER_MANAGER = new BufferManager(); + /** + * Adds a buffer to the table of open buffers. + */ + protected void addBuffer(IBuffer buffer) { + openBuffers.put(buffer.getOwner(), buffer); } - return DEFAULT_BUFFER_MANAGER; -} -/** - * Returns the default buffer factory. - */ -public IBufferFactory getDefaultBufferFactory() { - return this; -} -/** - * Returns an enumeration of all open buffers. - *

                - * The Enumeration answered is thread safe. - * - * @see OverflowingLRUCache - * @return Enumeration of IBuffer - */ -public Enumeration getOpenBuffers() { - synchronized (openBuffers) { - openBuffers.shrink(); - return openBuffers.elements(); + + /** + * @see IBufferFactory#createBuffer(IOpenable) + */ + public IBuffer createBuffer(IOpenable owner) { + IJavaElement element = (IJavaElement) owner; + IResource resource = element.getResource(); + return new Buffer(resource instanceof IFile ? (IFile) resource : null, + owner, element.isReadOnly()); } -} + /** + * Returns the open buffer associated with the given owner, or + * null if the owner does not have an open buffer associated + * with it. + */ + public IBuffer getBuffer(IOpenable owner) { + return (IBuffer) openBuffers.get(owner); + } -/** - * Removes a buffer from the table of open buffers. - */ -protected void removeBuffer(IBuffer buffer) { - openBuffers.remove(buffer.getOwner()); -} + /** + * Returns the default buffer manager. + */ + public synchronized static BufferManager getDefaultBufferManager() { + if (DEFAULT_BUFFER_MANAGER == null) { + DEFAULT_BUFFER_MANAGER = new BufferManager(); + } + return DEFAULT_BUFFER_MANAGER; + } + + /** + * Returns the default buffer factory. + */ + public IBufferFactory getDefaultBufferFactory() { + return this; + } + + /** + * Returns an enumeration of all open buffers. + *

                + * The Enumeration answered is thread safe. + * + * @see OverflowingLRUCache + * @return Enumeration of IBuffer + */ + public Enumeration getOpenBuffers() { + synchronized (openBuffers) { + openBuffers.shrink(); + return openBuffers.elements(); + } + } + + /** + * Removes a buffer from the table of open buffers. + */ + protected void removeBuffer(IBuffer buffer) { + openBuffers.remove(buffer.getOwner()); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ClasspathEntry.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ClasspathEntry.java index 8599066..fc56c48 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ClasspathEntry.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ClasspathEntry.java @@ -40,84 +40,93 @@ import org.w3c.dom.Element; public class ClasspathEntry implements IClasspathEntry { /** - * Describes the kind of classpath entry - one of - * CPE_PROJECT, CPE_LIBRARY, CPE_SOURCE, CPE_VARIABLE or CPE_CONTAINER + * Describes the kind of classpath entry - one of CPE_PROJECT, CPE_LIBRARY, + * CPE_SOURCE, CPE_VARIABLE or CPE_CONTAINER */ public int entryKind; /** - * Describes the kind of package fragment roots found on - * this classpath entry - either K_BINARY or K_SOURCE or - * K_OUTPUT. + * Describes the kind of package fragment roots found on this classpath + * entry - either K_BINARY or K_SOURCE or K_OUTPUT. */ public int contentKind; /** - * The meaning of the path of a classpath entry depends on its entry kind:

                  - *
                • Source code in the current project (CPE_SOURCE) - - * The path associated with this entry is the absolute path to the root folder.
                • - *
                • A binary library in the current project (CPE_LIBRARY) - the path - * associated with this entry is the absolute path to the JAR (or root folder), and - * in case it refers to an external JAR, then there is no associated resource in - * the workbench. - *
                • A required project (CPE_PROJECT) - the path of the entry denotes the - * path to the corresponding project resource.
                • - *
                • A variable entry (CPE_VARIABLE) - the first segment of the path - * is the name of a classpath variable. If this classpath variable - * is bound to the path P, the path of the corresponding classpath entry - * is computed by appending to P the segments of the returned - * path without the variable.
                • - *
                • A container entry (CPE_CONTAINER) - the first segment of the path is denoting - * the unique container identifier (for which a ClasspathContainerInitializer could be - * registered), and the remaining segments are used as additional hints for resolving the container entry to - * an actual IClasspathContainer.
                • + * The meaning of the path of a classpath entry depends on its entry kind: + *
                    + *
                  • Source code in the current project (CPE_SOURCE) - + * The path associated with this entry is the absolute path to the root + * folder.
                  • + *
                  • A binary library in the current project (CPE_LIBRARY) - + * the path associated with this entry is the absolute path to the JAR (or + * root folder), and in case it refers to an external JAR, then there is no + * associated resource in the workbench. + *
                  • A required project (CPE_PROJECT) - the path of the + * entry denotes the path to the corresponding project resource.
                  • + *
                  • A variable entry (CPE_VARIABLE) - the first segment + * of the path is the name of a classpath variable. If this classpath + * variable is bound to the path P, the path of the corresponding + * classpath entry is computed by appending to P the segments of + * the returned path without the variable.
                  • + *
                  • A container entry (CPE_CONTAINER) - the first + * segment of the path is denoting the unique container identifier (for + * which a ClasspathContainerInitializer could be + * registered), and the remaining segments are used as additional hints for + * resolving the container entry to an actual + * IClasspathContainer.
                  • */ public IPath path; - /** - * Patterns allowing to include/exclude portions of the resource tree denoted by this entry path. + * Patterns allowing to include/exclude portions of the resource tree + * denoted by this entry path. */ public IPath[] inclusionPatterns; + private char[][] fullCharInclusionPatterns; + public IPath[] exclusionPatterns; + private char[][] fullCharExclusionPatterns; + private final static char[][] UNINIT_PATTERNS = new char[][] { "Non-initialized yet".toCharArray() }; //$NON-NLS-1$ private String rootID; + /* * Default inclusion pattern set */ public final static IPath[] INCLUDE_ALL = {}; - + /* * Default exclusion pattern set */ public final static IPath[] EXCLUDE_NONE = {}; + /** * Default exclusion pattern set */ public final static IPath[] NO_EXCLUSION_PATTERNS = {}; - + /** - * Describes the path to the source archive associated with this - * classpath entry, or null if this classpath entry has no - * source attachment. + * Describes the path to the source archive associated with this classpath + * entry, or null if this classpath entry has no source + * attachment. *

                    * Only library and variable classpath entries may have source attachments. - * For library classpath entries, the result path (if present) locates a source - * archive. For variable classpath entries, the result path (if present) has - * an analogous form and meaning as the variable path, namely the first segment - * is the name of a classpath variable. + * For library classpath entries, the result path (if present) locates a + * source archive. For variable classpath entries, the result path (if + * present) has an analogous form and meaning as the variable path, namely + * the first segment is the name of a classpath variable. */ public IPath sourceAttachmentPath; /** - * Describes the path within the source archive where package fragments - * are located. An empty path indicates that packages are located at - * the root of the source archive. Returns a non-null value - * if and only if getSourceAttachmentPath returns - * a non-null value. + * Describes the path within the source archive where package fragments are + * located. An empty path indicates that packages are located at the root of + * the source archive. Returns a non-null value if and only + * if getSourceAttachmentPath returns a non-null + * value. */ public IPath sourceAttachmentRootPath; @@ -125,7 +134,7 @@ public class ClasspathEntry implements IClasspathEntry { * Specific output location (for this source entry) */ public IPath specificOutputLocation; - + /** * A constant indicating an output location. */ @@ -139,26 +148,22 @@ public class ClasspathEntry implements IClasspathEntry { /** * Creates a class path entry of the specified kind with the given path. */ - public ClasspathEntry( - int contentKind, - int entryKind, - IPath path, - IPath[] inclusionPatterns, - IPath[] exclusionPatterns, - IPath sourceAttachmentPath, - IPath sourceAttachmentRootPath, - IPath specificOutputLocation, - boolean isExported) { + public ClasspathEntry(int contentKind, int entryKind, IPath path, + IPath[] inclusionPatterns, IPath[] exclusionPatterns, + IPath sourceAttachmentPath, IPath sourceAttachmentRootPath, + IPath specificOutputLocation, boolean isExported) { this.contentKind = contentKind; this.entryKind = entryKind; this.path = path; this.inclusionPatterns = inclusionPatterns; - if (inclusionPatterns != INCLUDE_ALL && inclusionPatterns.length > 0) { + if (inclusionPatterns != INCLUDE_ALL && inclusionPatterns.length > 0) { this.fullCharInclusionPatterns = UNINIT_PATTERNS; - } else { - this.fullCharInclusionPatterns = null; // empty inclusion pattern means everything is included - } + } else { + this.fullCharInclusionPatterns = null; // empty inclusion pattern + // means everything is + // included + } this.exclusionPatterns = exclusionPatterns; if (exclusionPatterns.length > 0) { this.fullCharExclusionPatterns = UNINIT_PATTERNS; @@ -168,7 +173,7 @@ public class ClasspathEntry implements IClasspathEntry { this.specificOutputLocation = specificOutputLocation; this.isExported = isExported; } - + /* * Returns a char based representation of the exclusions patterns full path. */ @@ -179,13 +184,13 @@ public class ClasspathEntry implements IClasspathEntry { this.fullCharExclusionPatterns = new char[length][]; IPath prefixPath = this.path.removeTrailingSeparator(); for (int i = 0; i < length; i++) { - this.fullCharExclusionPatterns[i] = - prefixPath.append(this.exclusionPatterns[i]).toString().toCharArray(); + this.fullCharExclusionPatterns[i] = prefixPath.append( + this.exclusionPatterns[i]).toString().toCharArray(); } } return this.fullCharExclusionPatterns; } - + /* * Returns a char based representation of the exclusions patterns full path. */ @@ -196,25 +201,26 @@ public class ClasspathEntry implements IClasspathEntry { this.fullCharInclusionPatterns = new char[length][]; IPath prefixPath = this.path.removeTrailingSeparator(); for (int i = 0; i < length; i++) { - this.fullCharInclusionPatterns[i] = - prefixPath.append(this.inclusionPatterns[i]).toString().toCharArray(); + this.fullCharInclusionPatterns[i] = prefixPath.append( + this.inclusionPatterns[i]).toString().toCharArray(); } } return this.fullCharInclusionPatterns; } + /** * Returns the XML encoding of the class path. */ - public Element elementEncode( - Document document, - IPath projectPath) - throws JavaModelException { + public Element elementEncode(Document document, IPath projectPath) + throws JavaModelException { Element element = document.createElement("classpathentry"); //$NON-NLS-1$ - element.setAttribute("kind", kindToString(this.entryKind)); //$NON-NLS-1$ + element.setAttribute("kind", kindToString(this.entryKind)); //$NON-NLS-1$ IPath xmlPath = this.path; - if (this.entryKind != IClasspathEntry.CPE_VARIABLE && this.entryKind != IClasspathEntry.CPE_CONTAINER) { - // translate to project relative from absolute (unless a device path) + if (this.entryKind != IClasspathEntry.CPE_VARIABLE + && this.entryKind != IClasspathEntry.CPE_CONTAINER) { + // translate to project relative from absolute (unless a device + // path) if (xmlPath.isAbsolute()) { if (projectPath != null && projectPath.isPrefixOf(xmlPath)) { if (xmlPath.segment(0).equals(projectPath.segment(0))) { @@ -228,54 +234,58 @@ public class ClasspathEntry implements IClasspathEntry { } element.setAttribute("path", xmlPath.toString()); //$NON-NLS-1$ if (this.sourceAttachmentPath != null) { - element.setAttribute("sourcepath", this.sourceAttachmentPath.toString()); //$NON-NLS-1$ + element.setAttribute( + "sourcepath", this.sourceAttachmentPath.toString()); //$NON-NLS-1$ } if (this.sourceAttachmentRootPath != null) { - element.setAttribute("rootpath", this.sourceAttachmentRootPath.toString()); //$NON-NLS-1$ + element.setAttribute( + "rootpath", this.sourceAttachmentRootPath.toString()); //$NON-NLS-1$ } if (this.isExported) { element.setAttribute("exported", "true"); //$NON-NLS-1$ //$NON-NLS-2$ } - + if (this.exclusionPatterns.length > 0) { StringBuffer excludeRule = new StringBuffer(10); - for (int i = 0, max = this.exclusionPatterns.length; i < max; i++){ - if (i > 0) excludeRule.append('|'); + for (int i = 0, max = this.exclusionPatterns.length; i < max; i++) { + if (i > 0) + excludeRule.append('|'); excludeRule.append(this.exclusionPatterns[i]); } - element.setAttribute("excluding", excludeRule.toString()); //$NON-NLS-1$ + element.setAttribute("excluding", excludeRule.toString()); //$NON-NLS-1$ } - + if (this.specificOutputLocation != null) { - IPath outputLocation = this.specificOutputLocation.removeFirstSegments(1); + IPath outputLocation = this.specificOutputLocation + .removeFirstSegments(1); outputLocation = outputLocation.makeRelative(); element.setAttribute("output", outputLocation.toString()); //$NON-NLS-1$ } return element; } - - public static IClasspathEntry elementDecode(Element element, IJavaProject project) { - + + public static IClasspathEntry elementDecode(Element element, + IJavaProject project) { + IPath projectPath = project.getProject().getFullPath(); String kindAttr = element.getAttribute("kind"); //$NON-NLS-1$ String pathAttr = element.getAttribute("path"); //$NON-NLS-1$ // ensure path is absolute - IPath path = new Path(pathAttr); + IPath path = new Path(pathAttr); int kind = kindFromString(kindAttr); - if (kind != IClasspathEntry.CPE_VARIABLE && kind != IClasspathEntry.CPE_CONTAINER && !path.isAbsolute()) { + if (kind != IClasspathEntry.CPE_VARIABLE + && kind != IClasspathEntry.CPE_CONTAINER && !path.isAbsolute()) { path = projectPath.append(path); } // source attachment info (optional) - IPath sourceAttachmentPath = - element.hasAttribute("sourcepath") //$NON-NLS-1$ - ? new Path(element.getAttribute("sourcepath")) //$NON-NLS-1$ - : null; - IPath sourceAttachmentRootPath = - element.hasAttribute("rootpath") //$NON-NLS-1$ - ? new Path(element.getAttribute("rootpath")) //$NON-NLS-1$ - : null; - + IPath sourceAttachmentPath = element.hasAttribute("sourcepath") //$NON-NLS-1$ + ? new Path(element.getAttribute("sourcepath")) //$NON-NLS-1$ + : null; + IPath sourceAttachmentRootPath = element.hasAttribute("rootpath") //$NON-NLS-1$ + ? new Path(element.getAttribute("rootpath")) //$NON-NLS-1$ + : null; + // exported flag (optional) boolean isExported = element.getAttribute("exported").equals("true"); //$NON-NLS-1$ //$NON-NLS-2$ @@ -283,11 +293,12 @@ public class ClasspathEntry implements IClasspathEntry { String exclusion = element.getAttribute("excluding"); //$NON-NLS-1$ IPath[] exclusionPatterns = ClasspathEntry.NO_EXCLUSION_PATTERNS; if (!exclusion.equals("")) { //$NON-NLS-1$ - char[][] patterns = CharOperation.splitOn('|', exclusion.toCharArray()); + char[][] patterns = CharOperation.splitOn('|', exclusion + .toCharArray()); int patternCount; - if ((patternCount = patterns.length) > 0) { + if ((patternCount = patterns.length) > 0) { exclusionPatterns = new IPath[patternCount]; - for (int j = 0; j < patterns.length; j++){ + for (int j = 0; j < patterns.length; j++) { exclusionPatterns[j] = new Path(new String(patterns[j])); } } @@ -295,62 +306,62 @@ public class ClasspathEntry implements IClasspathEntry { // custom output location IPath outputLocation = element.hasAttribute("output") ? projectPath.append(element.getAttribute("output")) : null; //$NON-NLS-1$ //$NON-NLS-2$ - + // recreate the CP entry switch (kind) { - case IClasspathEntry.CPE_PROJECT : + case IClasspathEntry.CPE_PROJECT: + return JavaCore.newProjectEntry(path, isExported); + + // case IClasspathEntry.CPE_LIBRARY : + // return JavaCore.newLibraryEntry( + // path, + // sourceAttachmentPath, + // sourceAttachmentRootPath, + // isExported); + + case IClasspathEntry.CPE_SOURCE: + // must be an entry in this project or specify another project + String projSegment = path.segment(0); + if (projSegment != null + && projSegment.equals(project.getElementName())) { // this + // project + return JavaCore.newSourceEntry(path, exclusionPatterns, + outputLocation); + } else { // another project return JavaCore.newProjectEntry(path, isExported); - -// case IClasspathEntry.CPE_LIBRARY : -// return JavaCore.newLibraryEntry( -// path, -// sourceAttachmentPath, -// sourceAttachmentRootPath, -// isExported); - - case IClasspathEntry.CPE_SOURCE : - // must be an entry in this project or specify another project - String projSegment = path.segment(0); - if (projSegment != null && projSegment.equals(project.getElementName())) { // this project - return JavaCore.newSourceEntry(path, exclusionPatterns, outputLocation); - } else { // another project - return JavaCore.newProjectEntry(path, isExported); - } + } + + // case IClasspathEntry.CPE_VARIABLE : + // return PHPCore.newVariableEntry( + // path, + // sourceAttachmentPath, + // sourceAttachmentRootPath, + // isExported); -// case IClasspathEntry.CPE_VARIABLE : -// return PHPCore.newVariableEntry( -// path, -// sourceAttachmentPath, -// sourceAttachmentRootPath, -// isExported); - - case IClasspathEntry.CPE_CONTAINER : - return JavaCore.newContainerEntry( - path, - isExported); - - case ClasspathEntry.K_OUTPUT : - if (!path.isAbsolute()) return null; - return new ClasspathEntry( - ClasspathEntry.K_OUTPUT, - IClasspathEntry.CPE_LIBRARY, - path, - ClasspathEntry.INCLUDE_ALL, - ClasspathEntry.EXCLUDE_NONE, + case IClasspathEntry.CPE_CONTAINER: + return JavaCore.newContainerEntry(path, isExported); + + case ClasspathEntry.K_OUTPUT: + if (!path.isAbsolute()) + return null; + return new ClasspathEntry(ClasspathEntry.K_OUTPUT, + IClasspathEntry.CPE_LIBRARY, path, + ClasspathEntry.INCLUDE_ALL, ClasspathEntry.EXCLUDE_NONE, null, // source attachment null, // source attachment root null, // custom output location false); - - default : - throw new Assert.AssertionFailedException(Util.bind("classpath.unknownKind", kindAttr)); //$NON-NLS-1$ + + default: + throw new Assert.AssertionFailedException(Util.bind( + "classpath.unknownKind", kindAttr)); //$NON-NLS-1$ } } /** - * Returns true if the given object is a classpath entry - * with equivalent attributes. + * Returns true if the given object is a classpath entry with equivalent + * attributes. */ public boolean equals(Object object) { if (this == object) @@ -389,32 +400,38 @@ public class ClasspathEntry implements IClasspathEntry { } IPath[] otherIncludes = otherEntry.getInclusionPatterns(); - if (this.inclusionPatterns != otherIncludes){ - if (this.inclusionPatterns == null) return false; + if (this.inclusionPatterns != otherIncludes) { + if (this.inclusionPatterns == null) + return false; int includeLength = this.inclusionPatterns.length; - if (otherIncludes == null || otherIncludes.length != includeLength) + if (otherIncludes == null + || otherIncludes.length != includeLength) return false; for (int i = 0; i < includeLength; i++) { - // compare toStrings instead of IPaths - // since IPath.equals is specified to ignore trailing separators - if (!this.inclusionPatterns[i].toString().equals(otherIncludes[i].toString())) + // compare toStrings instead of IPaths + // since IPath.equals is specified to ignore trailing + // separators + if (!this.inclusionPatterns[i].toString().equals( + otherIncludes[i].toString())) return false; } } - + IPath[] otherExcludes = otherEntry.getExclusionPatterns(); - if (this.exclusionPatterns != otherExcludes){ + if (this.exclusionPatterns != otherExcludes) { int excludeLength = this.exclusionPatterns.length; - if (otherExcludes.length != excludeLength) + if (otherExcludes.length != excludeLength) return false; for (int i = 0; i < excludeLength; i++) { - // compare toStrings instead of IPaths - // since IPath.equals is specified to ignore trailing separators - if (!this.exclusionPatterns[i].toString().equals(otherExcludes[i].toString())) + // compare toStrings instead of IPaths + // since IPath.equals is specified to ignore trailing + // separators + if (!this.exclusionPatterns[i].toString().equals( + otherExcludes[i].toString())) return false; } } - + otherPath = otherEntry.getOutputLocation(); if (this.specificOutputLocation == null) { if (otherPath != null) @@ -449,12 +466,14 @@ public class ClasspathEntry implements IClasspathEntry { public IPath[] getExclusionPatterns() { return this.exclusionPatterns; } + /** * @see IClasspathEntry#getExclusionPatterns() */ public IPath[] getInclusionPatterns() { return this.inclusionPatterns; } + /** * @see IClasspathEntry#getOutputLocation() */ @@ -498,7 +517,8 @@ public class ClasspathEntry implements IClasspathEntry { } /** - * Returns the kind of a PackageFragmentRoot from its String form. + * Returns the kind of a PackageFragmentRoot from its + * String form. */ static int kindFromString(String kindStr) { @@ -523,20 +543,20 @@ public class ClasspathEntry implements IClasspathEntry { static String kindToString(int kind) { switch (kind) { - case IClasspathEntry.CPE_PROJECT : - return "src"; // backward compatibility //$NON-NLS-1$ - case IClasspathEntry.CPE_SOURCE : - return "src"; //$NON-NLS-1$ - case IClasspathEntry.CPE_LIBRARY : - return "lib"; //$NON-NLS-1$ - case IClasspathEntry.CPE_VARIABLE : - return "var"; //$NON-NLS-1$ - case IClasspathEntry.CPE_CONTAINER : - return "con"; //$NON-NLS-1$ - case ClasspathEntry.K_OUTPUT : - return "output"; //$NON-NLS-1$ - default : - return "unknown"; //$NON-NLS-1$ + case IClasspathEntry.CPE_PROJECT: + return "src"; // backward compatibility //$NON-NLS-1$ + case IClasspathEntry.CPE_SOURCE: + return "src"; //$NON-NLS-1$ + case IClasspathEntry.CPE_LIBRARY: + return "lib"; //$NON-NLS-1$ + case IClasspathEntry.CPE_VARIABLE: + return "var"; //$NON-NLS-1$ + case IClasspathEntry.CPE_CONTAINER: + return "con"; //$NON-NLS-1$ + case ClasspathEntry.K_OUTPUT: + return "output"; //$NON-NLS-1$ + default: + return "unknown"; //$NON-NLS-1$ } } @@ -548,33 +568,33 @@ public class ClasspathEntry implements IClasspathEntry { buffer.append(getPath().toString()); buffer.append('['); switch (getEntryKind()) { - case IClasspathEntry.CPE_LIBRARY : - buffer.append("CPE_LIBRARY"); //$NON-NLS-1$ - break; - case IClasspathEntry.CPE_PROJECT : - buffer.append("CPE_PROJECT"); //$NON-NLS-1$ - break; - case IClasspathEntry.CPE_SOURCE : - buffer.append("CPE_SOURCE"); //$NON-NLS-1$ - break; - case IClasspathEntry.CPE_VARIABLE : - buffer.append("CPE_VARIABLE"); //$NON-NLS-1$ - break; - case IClasspathEntry.CPE_CONTAINER : - buffer.append("CPE_CONTAINER"); //$NON-NLS-1$ - break; + case IClasspathEntry.CPE_LIBRARY: + buffer.append("CPE_LIBRARY"); //$NON-NLS-1$ + break; + case IClasspathEntry.CPE_PROJECT: + buffer.append("CPE_PROJECT"); //$NON-NLS-1$ + break; + case IClasspathEntry.CPE_SOURCE: + buffer.append("CPE_SOURCE"); //$NON-NLS-1$ + break; + case IClasspathEntry.CPE_VARIABLE: + buffer.append("CPE_VARIABLE"); //$NON-NLS-1$ + break; + case IClasspathEntry.CPE_CONTAINER: + buffer.append("CPE_CONTAINER"); //$NON-NLS-1$ + break; } buffer.append("]["); //$NON-NLS-1$ switch (getContentKind()) { - case IPackageFragmentRoot.K_BINARY : - buffer.append("K_BINARY"); //$NON-NLS-1$ - break; - case IPackageFragmentRoot.K_SOURCE : - buffer.append("K_SOURCE"); //$NON-NLS-1$ - break; - case ClasspathEntry.K_OUTPUT : - buffer.append("K_OUTPUT"); //$NON-NLS-1$ - break; + case IPackageFragmentRoot.K_BINARY: + buffer.append("K_BINARY"); //$NON-NLS-1$ + break; + case IPackageFragmentRoot.K_SOURCE: + buffer.append("K_SOURCE"); //$NON-NLS-1$ + break; + case ClasspathEntry.K_OUTPUT: + buffer.append("K_OUTPUT"); //$NON-NLS-1$ + break; } buffer.append(']'); if (getSourceAttachmentPath() != null) { @@ -596,7 +616,7 @@ public class ClasspathEntry implements IClasspathEntry { buffer.append("[excluding:"); //$NON-NLS-1$ for (int i = 0; i < length; i++) { buffer.append(patterns[i]); - if (i != length-1) { + if (i != length - 1) { buffer.append('|'); } } @@ -609,57 +629,61 @@ public class ClasspathEntry implements IClasspathEntry { } return buffer.toString(); } - + /** * Answers an ID which is used to distinguish entries during package * fragment root computations */ - public String rootID(){ + public String rootID() { if (this.rootID == null) { - switch(this.entryKind){ - case IClasspathEntry.CPE_LIBRARY : - this.rootID = "[LIB]"+this.path; //$NON-NLS-1$ - break; - case IClasspathEntry.CPE_PROJECT : - this.rootID = "[PRJ]"+this.path; //$NON-NLS-1$ - break; - case IClasspathEntry.CPE_SOURCE : - this.rootID = "[SRC]"+this.path; //$NON-NLS-1$ - break; - case IClasspathEntry.CPE_VARIABLE : - this.rootID = "[VAR]"+this.path; //$NON-NLS-1$ - break; - case IClasspathEntry.CPE_CONTAINER : - this.rootID = "[CON]"+this.path; //$NON-NLS-1$ - break; - default : - this.rootID = ""; //$NON-NLS-1$ - break; + switch (this.entryKind) { + case IClasspathEntry.CPE_LIBRARY: + this.rootID = "[LIB]" + this.path; //$NON-NLS-1$ + break; + case IClasspathEntry.CPE_PROJECT: + this.rootID = "[PRJ]" + this.path; //$NON-NLS-1$ + break; + case IClasspathEntry.CPE_SOURCE: + this.rootID = "[SRC]" + this.path; //$NON-NLS-1$ + break; + case IClasspathEntry.CPE_VARIABLE: + this.rootID = "[VAR]" + this.path; //$NON-NLS-1$ + break; + case IClasspathEntry.CPE_CONTAINER: + this.rootID = "[CON]" + this.path; //$NON-NLS-1$ + break; + default: + this.rootID = ""; //$NON-NLS-1$ + break; } } return this.rootID; } - + /** * @see IClasspathEntry * @deprecated */ public IClasspathEntry getResolvedEntry() { - + return JavaCore.getResolvedClasspathEntry(this); } + /** * Returns the XML encoding of the class path. */ - public void elementEncode(XMLWriter writer, IPath projectPath, boolean indent, boolean newLine) { + public void elementEncode(XMLWriter writer, IPath projectPath, + boolean indent, boolean newLine) { HashMap parameters = new HashMap(); - + parameters.put("kind", ClasspathEntry.kindToString(this.entryKind));//$NON-NLS-1$ - + IPath xmlPath = this.path; - if (this.entryKind != IClasspathEntry.CPE_VARIABLE && this.entryKind != IClasspathEntry.CPE_CONTAINER) { - // translate to project relative from absolute (unless a device path) + if (this.entryKind != IClasspathEntry.CPE_VARIABLE + && this.entryKind != IClasspathEntry.CPE_CONTAINER) { + // translate to project relative from absolute (unless a device + // path) if (xmlPath.isAbsolute()) { if (projectPath != null && projectPath.isPrefixOf(xmlPath)) { if (xmlPath.segment(0).equals(projectPath.segment(0))) { @@ -672,11 +696,12 @@ public class ClasspathEntry implements IClasspathEntry { } } parameters.put("path", String.valueOf(xmlPath));//$NON-NLS-1$ - + if (this.sourceAttachmentPath != null) { xmlPath = this.sourceAttachmentPath; - // translate to project relative from absolute - if (this.entryKind != IClasspathEntry.CPE_VARIABLE && projectPath != null && projectPath.isPrefixOf(xmlPath)) { + // translate to project relative from absolute + if (this.entryKind != IClasspathEntry.CPE_VARIABLE + && projectPath != null && projectPath.isPrefixOf(xmlPath)) { if (xmlPath.segment(0).equals(projectPath.segment(0))) { xmlPath = xmlPath.removeFirstSegments(1); xmlPath = xmlPath.makeRelative(); @@ -685,506 +710,775 @@ public class ClasspathEntry implements IClasspathEntry { parameters.put("sourcepath", String.valueOf(xmlPath));//$NON-NLS-1$ } if (this.sourceAttachmentRootPath != null) { - parameters.put("rootpath", String.valueOf(this.sourceAttachmentRootPath));//$NON-NLS-1$ + parameters.put( + "rootpath", String.valueOf(this.sourceAttachmentRootPath));//$NON-NLS-1$ } if (this.isExported) { parameters.put("exported", "true");//$NON-NLS-1$//$NON-NLS-2$ } -// if (this.inclusionPatterns != null && this.inclusionPatterns.length > 0) { -// StringBuffer includeRule = new StringBuffer(10); -// for (int i = 0, max = this.inclusionPatterns.length; i < max; i++){ -// if (i > 0) includeRule.append('|'); -// includeRule.append(this.inclusionPatterns[i]); -// } -// parameters.put("including", String.valueOf(includeRule));//$NON-NLS-1$ -// } + // if (this.inclusionPatterns != null && this.inclusionPatterns.length > + // 0) { + // StringBuffer includeRule = new StringBuffer(10); + // for (int i = 0, max = this.inclusionPatterns.length; i < max; i++){ + // if (i > 0) includeRule.append('|'); + // includeRule.append(this.inclusionPatterns[i]); + // } + // parameters.put("including", + // String.valueOf(includeRule));//$NON-NLS-1$ + // } if (this.exclusionPatterns != null && this.exclusionPatterns.length > 0) { StringBuffer excludeRule = new StringBuffer(10); - for (int i = 0, max = this.exclusionPatterns.length; i < max; i++){ - if (i > 0) excludeRule.append('|'); + for (int i = 0, max = this.exclusionPatterns.length; i < max; i++) { + if (i > 0) + excludeRule.append('|'); excludeRule.append(this.exclusionPatterns[i]); } parameters.put("excluding", String.valueOf(excludeRule));//$NON-NLS-1$ } - + if (this.specificOutputLocation != null) { - IPath outputLocation = this.specificOutputLocation.removeFirstSegments(1); + IPath outputLocation = this.specificOutputLocation + .removeFirstSegments(1); outputLocation = outputLocation.makeRelative(); parameters.put("output", String.valueOf(outputLocation));//$NON-NLS-1$ } writer.printTag("classpathentry", parameters, indent, newLine, true);//$NON-NLS-1$ } - + /** - * Validate a given classpath and output location for a project, using the following rules: + * Validate a given classpath and output location for a project, using the + * following rules: *

                      - *
                    • Classpath entries cannot collide with each other; that is, all entry paths must be unique. - *
                    • The project output location path cannot be null, must be absolute and located inside the project. - *
                    • Specific output locations (specified on source entries) can be null, if not they must be located inside the project, - *
                    • A project entry cannot refer to itself directly (that is, a project cannot prerequisite itself). - *
                    • Classpath entries or output locations cannot coincidate or be nested in each other, except for the following scenarii listed below: - *
                      • A source folder can coincidate with its own output location, in which case this output can then contain library archives. - * However, a specific output location cannot coincidate with any library or a distinct source folder than the one referring to it.
                      • - *
                      • A source/library folder can be nested in any source folder as long as the nested folder is excluded from the enclosing one.
                      • - *
                      • An output location can be nested in a source folder, if the source folder coincidates with the project itself, or if the output - * location is excluded from the source folder.
                      • - *
                      + *
                    • Classpath entries cannot collide with each other; that is, all entry + * paths must be unique. + *
                    • The project output location path cannot be null, must be absolute + * and located inside the project. + *
                    • Specific output locations (specified on source entries) can be null, + * if not they must be located inside the project, + *
                    • A project entry cannot refer to itself directly (that is, a project + * cannot prerequisite itself). + *
                    • Classpath entries or output locations cannot coincidate or be nested + * in each other, except for the following scenarii listed below: + *
                        + *
                      • A source folder can coincidate with its own output location, in + * which case this output can then contain library archives. However, a + * specific output location cannot coincidate with any library or a distinct + * source folder than the one referring to it.
                      • + *
                      • A source/library folder can be nested in any source folder as long + * as the nested folder is excluded from the enclosing one.
                      • + *
                      • An output location can be nested in a source folder, if the source + * folder coincidates with the project itself, or if the output location is + * excluded from the source folder.
                      • + *
                      *
                    * - * Note that the classpath entries are not validated automatically. Only bound variables or containers are considered - * in the checking process (this allows to perform a consistency check on a classpath which has references to - * yet non existing projects, folders, ...). - *

                    - * This validation is intended to anticipate classpath issues prior to assigning it to a project. In particular, it will automatically - * be performed during the classpath setting operation (if validation fails, the classpath setting will not complete). - *

                    - * @param javaProject the given java project - * @param rawClasspath a given classpath - * @param projectOutputLocation a given output location - * @return a status object with code IStatus.OK if - * the given classpath and output location are compatible, otherwise a status - * object indicating what is wrong with the classpath or output location + * Note that the classpath entries are not validated automatically. Only + * bound variables or containers are considered in the checking process + * (this allows to perform a consistency check on a classpath which has + * references to yet non existing projects, folders, ...). + *

                    + * This validation is intended to anticipate classpath issues prior to + * assigning it to a project. In particular, it will automatically be + * performed during the classpath setting operation (if validation fails, + * the classpath setting will not complete). + *

                    + * + * @param javaProject + * the given java project + * @param rawClasspath + * a given classpath + * @param projectOutputLocation + * a given output location + * @return a status object with code IStatus.OK if the given + * classpath and output location are compatible, otherwise a status + * object indicating what is wrong with the classpath or output + * location */ - public static IJavaModelStatus validateClasspath(IJavaProject javaProject, IClasspathEntry[] rawClasspath, IPath projectOutputLocation) { - + public static IJavaModelStatus validateClasspath(IJavaProject javaProject, + IClasspathEntry[] rawClasspath, IPath projectOutputLocation) { + IProject project = javaProject.getProject(); - IPath projectPath= project.getFullPath(); + IPath projectPath = project.getFullPath(); String projectName = javaProject.getElementName(); - + /* validate output location */ if (projectOutputLocation == null) { return new JavaModelStatus(IJavaModelStatusConstants.NULL_PATH); } if (projectOutputLocation.isAbsolute()) { if (!projectPath.isPrefixOf(projectOutputLocation)) { - return new JavaModelStatus(IJavaModelStatusConstants.PATH_OUTSIDE_PROJECT, javaProject, projectOutputLocation.toString()); + return new JavaModelStatus( + IJavaModelStatusConstants.PATH_OUTSIDE_PROJECT, + javaProject, projectOutputLocation.toString()); } } else { - return new JavaModelStatus(IJavaModelStatusConstants.RELATIVE_PATH, projectOutputLocation); + return new JavaModelStatus(IJavaModelStatusConstants.RELATIVE_PATH, + projectOutputLocation); } - + boolean hasSource = false; boolean hasLibFolder = false; - // tolerate null path, it will be reset to default - if (rawClasspath == null) + if (rawClasspath == null) return JavaModelStatus.VERIFIED_OK; - + // retrieve resolved classpath - IClasspathEntry[] classpath; + IClasspathEntry[] classpath; try { - classpath = ((JavaProject)javaProject).getResolvedClasspath(rawClasspath, null /*output*/, true/*ignore pb*/, false/*no marker*/, null /*no reverse map*/); - } catch(JavaModelException e){ + classpath = ((JavaProject) javaProject).getResolvedClasspath( + rawClasspath, null /* output */, true/* ignore pb */, + false/* no marker */, null /* no reverse map */); + } catch (JavaModelException e) { return e.getJavaModelStatus(); } - int length = classpath.length; + int length = classpath.length; int outputCount = 1; - IPath[] outputLocations = new IPath[length+1]; - boolean[] allowNestingInOutputLocations = new boolean[length+1]; + IPath[] outputLocations = new IPath[length + 1]; + boolean[] allowNestingInOutputLocations = new boolean[length + 1]; outputLocations[0] = projectOutputLocation; - + // retrieve and check output locations IPath potentialNestedOutput = null; // for error reporting purpose int sourceEntryCount = 0; - boolean disableExclusionPatterns = JavaCore.DISABLED.equals(javaProject.getOption(JavaCore.CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS, true)); - boolean disableCustomOutputLocations = JavaCore.DISABLED.equals(javaProject.getOption(JavaCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS, true)); - - for (int i = 0 ; i < length; i++) { + boolean disableExclusionPatterns = JavaCore.DISABLED.equals(javaProject + .getOption(JavaCore.CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS, + true)); + boolean disableCustomOutputLocations = JavaCore.DISABLED + .equals(javaProject + .getOption( + JavaCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS, + true)); + + for (int i = 0; i < length; i++) { IClasspathEntry resolvedEntry = classpath[i]; - switch(resolvedEntry.getEntryKind()){ - case IClasspathEntry.CPE_SOURCE : - sourceEntryCount++; - - if (disableExclusionPatterns && - ((resolvedEntry.getInclusionPatterns() != null && resolvedEntry.getInclusionPatterns().length > 0) - || (resolvedEntry.getExclusionPatterns() != null && resolvedEntry.getExclusionPatterns().length > 0))) { - return new JavaModelStatus(IJavaModelStatusConstants.DISABLED_CP_EXCLUSION_PATTERNS, javaProject, resolvedEntry.getPath()); - } - IPath customOutput; - if ((customOutput = resolvedEntry.getOutputLocation()) != null) { + switch (resolvedEntry.getEntryKind()) { + case IClasspathEntry.CPE_SOURCE: + sourceEntryCount++; - if (disableCustomOutputLocations) { - return new JavaModelStatus(IJavaModelStatusConstants.DISABLED_CP_MULTIPLE_OUTPUT_LOCATIONS, javaProject, resolvedEntry.getPath()); - } - // ensure custom output is in project - if (customOutput.isAbsolute()) { - if (!javaProject.getPath().isPrefixOf(customOutput)) { - return new JavaModelStatus(IJavaModelStatusConstants.PATH_OUTSIDE_PROJECT, javaProject, customOutput.toString()); - } - } else { - return new JavaModelStatus(IJavaModelStatusConstants.RELATIVE_PATH, customOutput); - } - - // ensure custom output doesn't conflict with other outputs - // check exact match - if (Util.indexOfMatchingPath(customOutput, outputLocations, outputCount) != -1) { - continue; // already found + if (disableExclusionPatterns + && ((resolvedEntry.getInclusionPatterns() != null && resolvedEntry + .getInclusionPatterns().length > 0) || (resolvedEntry + .getExclusionPatterns() != null && resolvedEntry + .getExclusionPatterns().length > 0))) { + return new JavaModelStatus( + IJavaModelStatusConstants.DISABLED_CP_EXCLUSION_PATTERNS, + javaProject, resolvedEntry.getPath()); + } + IPath customOutput; + if ((customOutput = resolvedEntry.getOutputLocation()) != null) { + + if (disableCustomOutputLocations) { + return new JavaModelStatus( + IJavaModelStatusConstants.DISABLED_CP_MULTIPLE_OUTPUT_LOCATIONS, + javaProject, resolvedEntry.getPath()); + } + // ensure custom output is in project + if (customOutput.isAbsolute()) { + if (!javaProject.getPath().isPrefixOf(customOutput)) { + return new JavaModelStatus( + IJavaModelStatusConstants.PATH_OUTSIDE_PROJECT, + javaProject, customOutput.toString()); } - // accumulate all outputs, will check nesting once all available (to handle ordering issues) - outputLocations[outputCount++] = customOutput; + } else { + return new JavaModelStatus( + IJavaModelStatusConstants.RELATIVE_PATH, + customOutput); + } + + // ensure custom output doesn't conflict with other outputs + // check exact match + if (Util.indexOfMatchingPath(customOutput, outputLocations, + outputCount) != -1) { + continue; // already found } + // accumulate all outputs, will check nesting once all + // available (to handle ordering issues) + outputLocations[outputCount++] = customOutput; + } } } // check nesting across output locations - for (int i = 1 /*no check for default output*/ ; i < outputCount; i++) { - IPath customOutput = outputLocations[i]; - int index; + for (int i = 1 /* no check for default output */; i < outputCount; i++) { + IPath customOutput = outputLocations[i]; + int index; // check nesting - if ((index = Util.indexOfEnclosingPath(customOutput, outputLocations, outputCount)) != -1 && index != i) { + if ((index = Util.indexOfEnclosingPath(customOutput, + outputLocations, outputCount)) != -1 + && index != i) { if (index == 0) { - // custom output is nested in project's output: need to check if all source entries have a custom + // custom output is nested in project's output: need to + // check if all source entries have a custom // output before complaining - if (potentialNestedOutput == null) potentialNestedOutput = customOutput; + if (potentialNestedOutput == null) + potentialNestedOutput = customOutput; } else { - return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.cannotNestOutputInOutput", customOutput.makeRelative().toString(), outputLocations[index].makeRelative().toString())); //$NON-NLS-1$ + return new JavaModelStatus( + IJavaModelStatusConstants.INVALID_CLASSPATH, + Util + .bind( + "classpath.cannotNestOutputInOutput", customOutput.makeRelative().toString(), outputLocations[index].makeRelative().toString())); //$NON-NLS-1$ } } - } - // allow custom output nesting in project's output if all source entries have a custom output - if (sourceEntryCount <= outputCount-1) { - allowNestingInOutputLocations[0] = true; + } + // allow custom output nesting in project's output if all source entries + // have a custom output + if (sourceEntryCount <= outputCount - 1) { + allowNestingInOutputLocations[0] = true; } else if (potentialNestedOutput != null) { - return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.cannotNestOutputInOutput", potentialNestedOutput.makeRelative().toString(), outputLocations[0].makeRelative().toString())); //$NON-NLS-1$ + return new JavaModelStatus( + IJavaModelStatusConstants.INVALID_CLASSPATH, + Util + .bind( + "classpath.cannotNestOutputInOutput", potentialNestedOutput.makeRelative().toString(), outputLocations[0].makeRelative().toString())); //$NON-NLS-1$ } - for (int i = 0 ; i < length; i++) { + for (int i = 0; i < length; i++) { IClasspathEntry resolvedEntry = classpath[i]; IPath path = resolvedEntry.getPath(); int index; - switch(resolvedEntry.getEntryKind()){ - - case IClasspathEntry.CPE_SOURCE : - hasSource = true; - if ((index = Util.indexOfMatchingPath(path, outputLocations, outputCount)) != -1){ - allowNestingInOutputLocations[index] = true; - } - break; - -// case IClasspathEntry.CPE_LIBRARY: -// hasLibFolder |= !org.eclipse.jdt.internal.compiler.util.Util.isArchiveFileName(path.lastSegment()); -// if ((index = Util.indexOfMatchingPath(path, outputLocations, outputCount)) != -1){ -// allowNestingInOutputLocations[index] = true; -// } -// break; + switch (resolvedEntry.getEntryKind()) { + + case IClasspathEntry.CPE_SOURCE: + hasSource = true; + if ((index = Util.indexOfMatchingPath(path, outputLocations, + outputCount)) != -1) { + allowNestingInOutputLocations[index] = true; + } + break; + + // case IClasspathEntry.CPE_LIBRARY: + // hasLibFolder |= + // !org.eclipse.jdt.internal.compiler.util.Util.isArchiveFileName(path.lastSegment()); + // if ((index = Util.indexOfMatchingPath(path, outputLocations, + // outputCount)) != -1){ + // allowNestingInOutputLocations[index] = true; + // } + // break; } } - if (!hasSource && !hasLibFolder) { // if no source and no lib folder, then allowed - for (int i = 0; i < outputCount; i++) allowNestingInOutputLocations[i] = true; + if (!hasSource && !hasLibFolder) { // if no source and no lib folder, + // then allowed + for (int i = 0; i < outputCount; i++) + allowNestingInOutputLocations[i] = true; } - + HashSet pathes = new HashSet(length); - + // check all entries - for (int i = 0 ; i < length; i++) { + for (int i = 0; i < length; i++) { IClasspathEntry entry = classpath[i]; - if (entry == null) continue; + if (entry == null) + continue; IPath entryPath = entry.getPath(); int kind = entry.getEntryKind(); - + // Build some common strings for status message - boolean isProjectRelative = entryPath.segment(0).toString().equals(projectName); - String entryPathMsg = isProjectRelative ? entryPath.removeFirstSegments(1).toString() : entryPath.makeRelative().toString(); - + boolean isProjectRelative = entryPath.segment(0).toString().equals( + projectName); + String entryPathMsg = isProjectRelative ? entryPath + .removeFirstSegments(1).toString() : entryPath + .makeRelative().toString(); + // complain if duplicate path - if (!pathes.add(entryPath)){ - return new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION, Util.bind("classpath.duplicateEntryPath", entryPathMsg, projectName)); //$NON-NLS-1$ + if (!pathes.add(entryPath)) { + return new JavaModelStatus( + IJavaModelStatusConstants.NAME_COLLISION, + Util + .bind( + "classpath.duplicateEntryPath", entryPathMsg, projectName)); //$NON-NLS-1$ } - // no further check if entry coincidates with project or output location - if (entryPath.equals(projectPath)){ + // no further check if entry coincidates with project or output + // location + if (entryPath.equals(projectPath)) { // complain if self-referring project entry - if (kind == IClasspathEntry.CPE_PROJECT){ - return new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, Util.bind("classpath.cannotReferToItself", entryPath.makeRelative().toString()));//$NON-NLS-1$ + if (kind == IClasspathEntry.CPE_PROJECT) { + return new JavaModelStatus( + IJavaModelStatusConstants.INVALID_PATH, + Util + .bind( + "classpath.cannotReferToItself", entryPath.makeRelative().toString()));//$NON-NLS-1$ } // tolerate nesting output in src if src==prj continue; } - - // allow nesting source entries in each other as long as the outer entry excludes the inner one - if (kind == IClasspathEntry.CPE_SOURCE ) { -// || (kind == IClasspathEntry.CPE_LIBRARY && !org.eclipse.jdt.internal.compiler.util.Util.isArchiveFileName(entryPath.lastSegment()))){ - for (int j = 0; j < classpath.length; j++){ + + // allow nesting source entries in each other as long as the outer + // entry excludes the inner one + if (kind == IClasspathEntry.CPE_SOURCE) { + // || (kind == IClasspathEntry.CPE_LIBRARY && + // !org.eclipse.jdt.internal.compiler.util.Util.isArchiveFileName(entryPath.lastSegment()))){ + for (int j = 0; j < classpath.length; j++) { IClasspathEntry otherEntry = classpath[j]; - if (otherEntry == null) continue; + if (otherEntry == null) + continue; int otherKind = otherEntry.getEntryKind(); IPath otherPath = otherEntry.getPath(); - if (entry != otherEntry - && (otherKind == IClasspathEntry.CPE_SOURCE ) ) { -// || (otherKind == IClasspathEntry.CPE_LIBRARY -// && !org.eclipse.jdt.internal.compiler.util.Util.isArchiveFileName(otherPath.lastSegment())))){ + if (entry != otherEntry + && (otherKind == IClasspathEntry.CPE_SOURCE)) { + // || (otherKind == IClasspathEntry.CPE_LIBRARY + // && + // !org.eclipse.jdt.internal.compiler.util.Util.isArchiveFileName(otherPath.lastSegment())))){ char[][] inclusionPatterns, exclusionPatterns; - if (otherPath.isPrefixOf(entryPath) + if (otherPath.isPrefixOf(entryPath) && !otherPath.equals(entryPath) - && !Util.isExcluded(entryPath.append("*"), inclusionPatterns = ((ClasspathEntry)otherEntry).fullInclusionPatternChars(), exclusionPatterns = ((ClasspathEntry)otherEntry).fullExclusionPatternChars(), false)) { //$NON-NLS-1$ - String exclusionPattern = entryPath.removeFirstSegments(otherPath.segmentCount()).segment(0); - if (Util.isExcluded(entryPath, inclusionPatterns, exclusionPatterns, false)) { - return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.mustEndWithSlash", exclusionPattern, entryPath.makeRelative().toString())); //$NON-NLS-1$ + && !Util + .isExcluded( + entryPath.append("*"), inclusionPatterns = ((ClasspathEntry) otherEntry).fullInclusionPatternChars(), exclusionPatterns = ((ClasspathEntry) otherEntry).fullExclusionPatternChars(), false)) { //$NON-NLS-1$ + String exclusionPattern = entryPath + .removeFirstSegments( + otherPath.segmentCount()) + .segment(0); + if (Util.isExcluded(entryPath, inclusionPatterns, + exclusionPatterns, false)) { + return new JavaModelStatus( + IJavaModelStatusConstants.INVALID_CLASSPATH, + Util + .bind( + "classpath.mustEndWithSlash", exclusionPattern, entryPath.makeRelative().toString())); //$NON-NLS-1$ } else { if (otherKind == IClasspathEntry.CPE_SOURCE) { exclusionPattern += '/'; - return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.cannotNestEntryInEntry", new String[] {entryPath.makeRelative().toString(), otherEntry.getPath().makeRelative().toString(), exclusionPattern})); //$NON-NLS-1$ + return new JavaModelStatus( + IJavaModelStatusConstants.INVALID_CLASSPATH, + Util + .bind( + "classpath.cannotNestEntryInEntry", new String[] { entryPath.makeRelative().toString(), otherEntry.getPath().makeRelative().toString(), exclusionPattern })); //$NON-NLS-1$ } else { - return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.cannotNestEntryInLibrary", entryPath.makeRelative().toString(), otherEntry.getPath().makeRelative().toString())); //$NON-NLS-1$ + return new JavaModelStatus( + IJavaModelStatusConstants.INVALID_CLASSPATH, + Util + .bind( + "classpath.cannotNestEntryInLibrary", entryPath.makeRelative().toString(), otherEntry.getPath().makeRelative().toString())); //$NON-NLS-1$ } } } } } } - - // prevent nesting output location inside entry unless enclosing is a source entry which explicitly exclude the output location - char[][] inclusionPatterns = ((ClasspathEntry)entry).fullInclusionPatternChars(); - char[][] exclusionPatterns = ((ClasspathEntry)entry).fullExclusionPatternChars(); - for (int j = 0; j < outputCount; j++){ - IPath currentOutput = outputLocations[j]; - if (entryPath.equals(currentOutput)) continue; + + // prevent nesting output location inside entry unless enclosing is + // a source entry which explicitly exclude the output location + char[][] inclusionPatterns = ((ClasspathEntry) entry) + .fullInclusionPatternChars(); + char[][] exclusionPatterns = ((ClasspathEntry) entry) + .fullExclusionPatternChars(); + for (int j = 0; j < outputCount; j++) { + IPath currentOutput = outputLocations[j]; + if (entryPath.equals(currentOutput)) + continue; if (entryPath.isPrefixOf(currentOutput)) { - if (kind != IClasspathEntry.CPE_SOURCE || !Util.isExcluded(currentOutput, inclusionPatterns, exclusionPatterns, true)) { - return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.cannotNestOutputInEntry", currentOutput.makeRelative().toString(), entryPath.makeRelative().toString())); //$NON-NLS-1$ - } + if (kind != IClasspathEntry.CPE_SOURCE + || !Util.isExcluded(currentOutput, + inclusionPatterns, exclusionPatterns, true)) { + return new JavaModelStatus( + IJavaModelStatusConstants.INVALID_CLASSPATH, + Util + .bind( + "classpath.cannotNestOutputInEntry", currentOutput.makeRelative().toString(), entryPath.makeRelative().toString())); //$NON-NLS-1$ + } } - } + } - // prevent nesting entry inside output location - when distinct from project or a source folder - for (int j = 0; j < outputCount; j++){ - if (allowNestingInOutputLocations[j]) continue; - IPath currentOutput = outputLocations[j]; + // prevent nesting entry inside output location - when distinct from + // project or a source folder + for (int j = 0; j < outputCount; j++) { + if (allowNestingInOutputLocations[j]) + continue; + IPath currentOutput = outputLocations[j]; if (currentOutput.isPrefixOf(entryPath)) { - return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.cannotNestEntryInOutput", entryPath.makeRelative().toString(), currentOutput.makeRelative().toString())); //$NON-NLS-1$ + return new JavaModelStatus( + IJavaModelStatusConstants.INVALID_CLASSPATH, + Util + .bind( + "classpath.cannotNestEntryInOutput", entryPath.makeRelative().toString(), currentOutput.makeRelative().toString())); //$NON-NLS-1$ } - } + } } - // ensure that no specific output is coincidating with another source folder (only allowed if matching current source folder) - // 36465 - for 2.0 backward compatibility, only check specific output locations (the default can still coincidate) - // perform one separate iteration so as to not take precedence over previously checked scenarii (in particular should - // diagnose nesting source folder issue before this one, for example, [src]"Project/", [src]"Project/source/" and output="Project/" should + // ensure that no specific output is coincidating with another source + // folder (only allowed if matching current source folder) + // 36465 - for 2.0 backward compatibility, only check specific output + // locations (the default can still coincidate) + // perform one separate iteration so as to not take precedence over + // previously checked scenarii (in particular should + // diagnose nesting source folder issue before this one, for example, + // [src]"Project/", [src]"Project/source/" and output="Project/" should // first complain about missing exclusion pattern - for (int i = 0 ; i < length; i++) { + for (int i = 0; i < length; i++) { IClasspathEntry entry = classpath[i]; - if (entry == null) continue; + if (entry == null) + continue; IPath entryPath = entry.getPath(); int kind = entry.getEntryKind(); // Build some common strings for status message - boolean isProjectRelative = entryPath.segment(0).toString().equals(projectName); - String entryPathMsg = isProjectRelative ? entryPath.removeFirstSegments(1).toString() : entryPath.makeRelative().toString(); - + boolean isProjectRelative = entryPath.segment(0).toString().equals( + projectName); + String entryPathMsg = isProjectRelative ? entryPath + .removeFirstSegments(1).toString() : entryPath + .makeRelative().toString(); + if (kind == IClasspathEntry.CPE_SOURCE) { IPath output = entry.getOutputLocation(); - if (output == null) continue; // 36465 - for 2.0 backward compatibility, only check specific output locations (the default can still coincidate) - // if (output == null) output = projectOutputLocation; // if no specific output, still need to check using default output (this line would check default output) + if (output == null) + continue; // 36465 - for 2.0 backward compatibility, only + // check specific output locations (the default + // can still coincidate) + // if (output == null) output = projectOutputLocation; // if no + // specific output, still need to check using default output + // (this line would check default output) for (int j = 0; j < length; j++) { IClasspathEntry otherEntry = classpath[j]; - if (otherEntry == entry) continue; + if (otherEntry == entry) + continue; // Build some common strings for status message - boolean opStartsWithProject = otherEntry.getPath().segment(0).toString().equals(projectName); - String otherPathMsg = opStartsWithProject ? otherEntry.getPath().removeFirstSegments(1).toString() : otherEntry.getPath().makeRelative().toString(); - + boolean opStartsWithProject = otherEntry.getPath().segment( + 0).toString().equals(projectName); + String otherPathMsg = opStartsWithProject ? otherEntry + .getPath().removeFirstSegments(1).toString() + : otherEntry.getPath().makeRelative().toString(); + switch (otherEntry.getEntryKind()) { - case IClasspathEntry.CPE_SOURCE : - if (otherEntry.getPath().equals(output)) { - return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.cannotUseDistinctSourceFolderAsOutput", new String[] {entryPathMsg, otherPathMsg, projectName})); //$NON-NLS-1$ - } - break; - case IClasspathEntry.CPE_LIBRARY : - if (otherEntry.getPath().equals(output)) { - return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.cannotUseLibraryAsOutput", new String[] {entryPathMsg, otherPathMsg, projectName})); //$NON-NLS-1$ - } + case IClasspathEntry.CPE_SOURCE: + if (otherEntry.getPath().equals(output)) { + return new JavaModelStatus( + IJavaModelStatusConstants.INVALID_CLASSPATH, + Util + .bind( + "classpath.cannotUseDistinctSourceFolderAsOutput", new String[] { entryPathMsg, otherPathMsg, projectName })); //$NON-NLS-1$ + } + break; + case IClasspathEntry.CPE_LIBRARY: + if (otherEntry.getPath().equals(output)) { + return new JavaModelStatus( + IJavaModelStatusConstants.INVALID_CLASSPATH, + Util + .bind( + "classpath.cannotUseLibraryAsOutput", new String[] { entryPathMsg, otherPathMsg, projectName })); //$NON-NLS-1$ + } } } - } + } } - return JavaModelStatus.VERIFIED_OK; + return JavaModelStatus.VERIFIED_OK; } - + /** - * Returns a Java model status describing the problem related to this classpath entry if any, - * a status object with code IStatus.OK if the entry is fine (that is, if the - * given classpath entry denotes a valid element to be referenced onto a classpath). + * Returns a Java model status describing the problem related to this + * classpath entry if any, a status object with code IStatus.OK + * if the entry is fine (that is, if the given classpath entry denotes a + * valid element to be referenced onto a classpath). * - * @param project the given java project - * @param entry the given classpath entry - * @param checkSourceAttachment a flag to determine if source attachement should be checked - * @param recurseInContainers flag indicating whether validation should be applied to container entries recursively - * @return a java model status describing the problem related to this classpath entry if any, a status object with code IStatus.OK if the entry is fine + * @param project + * the given java project + * @param entry + * the given classpath entry + * @param checkSourceAttachment + * a flag to determine if source attachement should be checked + * @param recurseInContainers + * flag indicating whether validation should be applied to + * container entries recursively + * @return a java model status describing the problem related to this + * classpath entry if any, a status object with code + * IStatus.OK if the entry is fine */ - public static IJavaModelStatus validateClasspathEntry(IJavaProject project, IClasspathEntry entry, boolean checkSourceAttachment, boolean recurseInContainers){ - - IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); + public static IJavaModelStatus validateClasspathEntry(IJavaProject project, + IClasspathEntry entry, boolean checkSourceAttachment, + boolean recurseInContainers) { + + IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); IPath path = entry.getPath(); - + // Build some common strings for status message String projectName = project.getElementName(); - boolean pathStartsWithProject = path.segment(0).toString().equals(projectName); - String entryPathMsg = pathStartsWithProject ? path.removeFirstSegments(1).toString() : path.makeRelative().toString(); - - switch(entry.getEntryKind()){ - - // container entry check -// case IClasspathEntry.CPE_CONTAINER : -// if (path != null && path.segmentCount() >= 1){ -// try { -// IClasspathContainer container = JavaModelManager.getJavaModelManager().getClasspathContainer(path, project); -// // container retrieval is performing validation check on container entry kinds. -// if (container == null){ -// return new JavaModelStatus(IJavaModelStatusConstants.CP_CONTAINER_PATH_UNBOUND, project, path); -// } else if (container == JavaModelManager.CONTAINER_INITIALIZATION_IN_PROGRESS) { -// // don't create a marker if initialization is in progress (case of cp initialization batching) -// return JavaModelStatus.VERIFIED_OK; -// } -// IClasspathEntry[] containerEntries = container.getClasspathEntries(); -// if (containerEntries != null){ -// for (int i = 0, length = containerEntries.length; i < length; i++){ -// IClasspathEntry containerEntry = containerEntries[i]; -// int kind = containerEntry == null ? 0 : containerEntry.getEntryKind(); -// if (containerEntry == null -// || kind == IClasspathEntry.CPE_SOURCE -// || kind == IClasspathEntry.CPE_VARIABLE -// || kind == IClasspathEntry.CPE_CONTAINER){ -// String description = container.getDescription(); -// if (description == null) description = path.makeRelative().toString(); -// return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CP_CONTAINER_ENTRY, project, path); -// } -// if (recurseInContainers) { -// IJavaModelStatus containerEntryStatus = validateClasspathEntry(project, containerEntry, checkSourceAttachment, recurseInContainers); -// if (!containerEntryStatus.isOK()){ -// return containerEntryStatus; -// } -// } -// } -// } -// } catch(JavaModelException e){ -// return new JavaModelStatus(e); -// } -// } else { -// return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.illegalContainerPath", entryPathMsg, projectName)); //$NON-NLS-1$ -// } -// break; - - // variable entry check - case IClasspathEntry.CPE_VARIABLE : - if (path != null && path.segmentCount() >= 1){ - try { - entry = JavaCore.getResolvedClasspathEntry(entry); - } catch (Assert.AssertionFailedException e) { - // Catch the assertion failure and throw java model exception instead - // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=55992 - return new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage()); - } - if (entry == null){ - return new JavaModelStatus(IJavaModelStatusConstants.CP_VARIABLE_PATH_UNBOUND, project, path); - } - return validateClasspathEntry(project, entry, checkSourceAttachment, recurseInContainers); - } else { - return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.illegalVariablePath", path.makeRelative().toString(), projectName)); //$NON-NLS-1$ + boolean pathStartsWithProject = path.segment(0).toString().equals( + projectName); + String entryPathMsg = pathStartsWithProject ? path.removeFirstSegments( + 1).toString() : path.makeRelative().toString(); + + switch (entry.getEntryKind()) { + + // container entry check + // case IClasspathEntry.CPE_CONTAINER : + // if (path != null && path.segmentCount() >= 1){ + // try { + // IClasspathContainer container = + // JavaModelManager.getJavaModelManager().getClasspathContainer(path, + // project); + // // container retrieval is performing validation check on container + // entry kinds. + // if (container == null){ + // return new + // JavaModelStatus(IJavaModelStatusConstants.CP_CONTAINER_PATH_UNBOUND, + // project, path); + // } else if (container == + // JavaModelManager.CONTAINER_INITIALIZATION_IN_PROGRESS) { + // // don't create a marker if initialization is in progress (case of cp + // initialization batching) + // return JavaModelStatus.VERIFIED_OK; + // } + // IClasspathEntry[] containerEntries = container.getClasspathEntries(); + // if (containerEntries != null){ + // for (int i = 0, length = containerEntries.length; i < length; i++){ + // IClasspathEntry containerEntry = containerEntries[i]; + // int kind = containerEntry == null ? 0 : + // containerEntry.getEntryKind(); + // if (containerEntry == null + // || kind == IClasspathEntry.CPE_SOURCE + // || kind == IClasspathEntry.CPE_VARIABLE + // || kind == IClasspathEntry.CPE_CONTAINER){ + // String description = container.getDescription(); + // if (description == null) description = + // path.makeRelative().toString(); + // return new + // JavaModelStatus(IJavaModelStatusConstants.INVALID_CP_CONTAINER_ENTRY, + // project, path); + // } + // if (recurseInContainers) { + // IJavaModelStatus containerEntryStatus = + // validateClasspathEntry(project, containerEntry, + // checkSourceAttachment, recurseInContainers); + // if (!containerEntryStatus.isOK()){ + // return containerEntryStatus; + // } + // } + // } + // } + // } catch(JavaModelException e){ + // return new JavaModelStatus(e); + // } + // } else { + // return new + // JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, + // Util.bind("classpath.illegalContainerPath", entryPathMsg, + // projectName)); //$NON-NLS-1$ + // } + // break; + + // variable entry check + case IClasspathEntry.CPE_VARIABLE: + if (path != null && path.segmentCount() >= 1) { + try { + entry = JavaCore.getResolvedClasspathEntry(entry); + } catch (Assert.AssertionFailedException e) { + // Catch the assertion failure and throw java model + // exception instead + // see bug + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=55992 + return new JavaModelStatus( + IJavaModelStatusConstants.INVALID_PATH, e + .getMessage()); } - + if (entry == null) { + return new JavaModelStatus( + IJavaModelStatusConstants.CP_VARIABLE_PATH_UNBOUND, + project, path); + } + return validateClasspathEntry(project, entry, + checkSourceAttachment, recurseInContainers); + } else { + return new JavaModelStatus( + IJavaModelStatusConstants.INVALID_CLASSPATH, + Util + .bind( + "classpath.illegalVariablePath", path.makeRelative().toString(), projectName)); //$NON-NLS-1$ + } + // library entry check -// case IClasspathEntry.CPE_LIBRARY : -// if (path != null && path.isAbsolute() && !path.isEmpty()) { -// IPath sourceAttachment = entry.getSourceAttachmentPath(); -// Object target = JavaModel.getTarget(workspaceRoot, path, true); -// if (target != null && project.getOption(JavaCore.CORE_INCOMPATIBLE_JDK_LEVEL, true) != JavaCore.IGNORE) { -// long projectTargetJDK = CompilerOptions.versionToJdkLevel(project.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, true)); -// long libraryJDK = Util.getJdkLevel(target); -// if (libraryJDK != 0 && libraryJDK > projectTargetJDK) { -// return new JavaModelStatus(IJavaModelStatusConstants.INCOMPATIBLE_JDK_LEVEL, project, path, CompilerOptions.versionFromJdkLevel(libraryJDK)); -// } -// } -// if (target instanceof IResource){ -// IResource resolvedResource = (IResource) target; -// switch(resolvedResource.getType()){ -// case IResource.FILE : -// if (org.eclipse.jdt.internal.compiler.util.Util.isArchiveFileName(resolvedResource.getName())) { -// if (checkSourceAttachment -// && sourceAttachment != null -// && !sourceAttachment.isEmpty() -// && JavaModel.getTarget(workspaceRoot, sourceAttachment, true) == null){ -// return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.unboundSourceAttachment", new String [] {sourceAttachment.makeRelative().toString(), path.makeRelative().toString(), projectName})); //$NON-NLS-1$ -// } -// } else { -// return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.illegalLibraryArchive", entryPathMsg, projectName)); //$NON-NLS-1$ -// } -// break; -// case IResource.FOLDER : // internal binary folder -// if (checkSourceAttachment -// && sourceAttachment != null -// && !sourceAttachment.isEmpty() -// && JavaModel.getTarget(workspaceRoot, sourceAttachment, true) == null){ -// return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.unboundSourceAttachment", new String [] {sourceAttachment.makeRelative().toString(), path.makeRelative().toString(), projectName})); //$NON-NLS-1$ -// } -// } -// } else if (target instanceof File){ -// File file = (File) target; -// if (!file.isFile()) { -// return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.illegalExternalFolder", path.toOSString(), projectName)); //$NON-NLS-1$ -// } else if (!org.eclipse.jdt.internal.compiler.util.Util.isArchiveFileName(file.getName())) { -// return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.illegalLibraryArchive", path.toOSString(), projectName)); //$NON-NLS-1$ -// } else if (checkSourceAttachment -// && sourceAttachment != null -// && !sourceAttachment.isEmpty() -// && JavaModel.getTarget(workspaceRoot, sourceAttachment, true) == null){ -// return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.unboundSourceAttachment", new String [] {sourceAttachment.toString(), path.makeRelative().toString(), projectName})); //$NON-NLS-1$ -// } -// } else { -// return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.unboundLibrary", path.makeRelative().toString(), projectName)); //$NON-NLS-1$ -// } -// } else { -// return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.illegalLibraryPath", path.makeRelative().toString(), projectName)); //$NON-NLS-1$ -// } -// break; - + // case IClasspathEntry.CPE_LIBRARY : + // if (path != null && path.isAbsolute() && !path.isEmpty()) { + // IPath sourceAttachment = entry.getSourceAttachmentPath(); + // Object target = JavaModel.getTarget(workspaceRoot, path, true); + // if (target != null && + // project.getOption(JavaCore.CORE_INCOMPATIBLE_JDK_LEVEL, true) != + // JavaCore.IGNORE) { + // long projectTargetJDK = + // CompilerOptions.versionToJdkLevel(project.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, + // true)); + // long libraryJDK = Util.getJdkLevel(target); + // if (libraryJDK != 0 && libraryJDK > projectTargetJDK) { + // return new + // JavaModelStatus(IJavaModelStatusConstants.INCOMPATIBLE_JDK_LEVEL, + // project, path, CompilerOptions.versionFromJdkLevel(libraryJDK)); + // } + // } + // if (target instanceof IResource){ + // IResource resolvedResource = (IResource) target; + // switch(resolvedResource.getType()){ + // case IResource.FILE : + // if + // (org.eclipse.jdt.internal.compiler.util.Util.isArchiveFileName(resolvedResource.getName())) + // { + // if (checkSourceAttachment + // && sourceAttachment != null + // && !sourceAttachment.isEmpty() + // && JavaModel.getTarget(workspaceRoot, sourceAttachment, true) == + // null){ + // return new + // JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, + // Util.bind("classpath.unboundSourceAttachment", new String [] + // {sourceAttachment.makeRelative().toString(), + // path.makeRelative().toString(), projectName})); //$NON-NLS-1$ + // } + // } else { + // return new + // JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, + // Util.bind("classpath.illegalLibraryArchive", entryPathMsg, + // projectName)); //$NON-NLS-1$ + // } + // break; + // case IResource.FOLDER : // internal binary folder + // if (checkSourceAttachment + // && sourceAttachment != null + // && !sourceAttachment.isEmpty() + // && JavaModel.getTarget(workspaceRoot, sourceAttachment, true) == + // null){ + // return new + // JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, + // Util.bind("classpath.unboundSourceAttachment", new String [] + // {sourceAttachment.makeRelative().toString(), + // path.makeRelative().toString(), projectName})); //$NON-NLS-1$ + // } + // } + // } else if (target instanceof File){ + // File file = (File) target; + // if (!file.isFile()) { + // return new + // JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, + // Util.bind("classpath.illegalExternalFolder", path.toOSString(), + // projectName)); //$NON-NLS-1$ + // } else if + // (!org.eclipse.jdt.internal.compiler.util.Util.isArchiveFileName(file.getName())) + // { + // return new + // JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, + // Util.bind("classpath.illegalLibraryArchive", path.toOSString(), + // projectName)); //$NON-NLS-1$ + // } else if (checkSourceAttachment + // && sourceAttachment != null + // && !sourceAttachment.isEmpty() + // && JavaModel.getTarget(workspaceRoot, sourceAttachment, true) == + // null){ + // return new + // JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, + // Util.bind("classpath.unboundSourceAttachment", new String [] + // {sourceAttachment.toString(), path.makeRelative().toString(), + // projectName})); //$NON-NLS-1$ + // } + // } else { + // return new + // JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, + // Util.bind("classpath.unboundLibrary", + // path.makeRelative().toString(), projectName)); //$NON-NLS-1$ + // } + // } else { + // return new + // JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, + // Util.bind("classpath.illegalLibraryPath", + // path.makeRelative().toString(), projectName)); //$NON-NLS-1$ + // } + // break; + // project entry check - case IClasspathEntry.CPE_PROJECT : - if (path != null && path.isAbsolute() && !path.isEmpty()) { - IProject prereqProjectRsc = workspaceRoot.getProject(path.segment(0)); - IJavaProject prereqProject = JavaCore.create(prereqProjectRsc); - try { - if (!prereqProjectRsc.exists() || !prereqProjectRsc.hasNature(PHPeclipsePlugin.PHP_NATURE_ID)){ - return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.unboundProject", path.makeRelative().segment(0).toString(), projectName)); //$NON-NLS-1$ - } - if (!prereqProjectRsc.isOpen()){ - return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.closedProject", path.segment(0).toString())); //$NON-NLS-1$ - } -// if (project.getOption(JavaCore.CORE_INCOMPATIBLE_JDK_LEVEL, true) != JavaCore.IGNORE) { -// long projectTargetJDK = CompilerOptions.versionToJdkLevel(project.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, true)); -// long prereqProjectTargetJDK = CompilerOptions.versionToJdkLevel(prereqProject.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, true)); -// if (prereqProjectTargetJDK > projectTargetJDK) { -// return new JavaModelStatus(IJavaModelStatusConstants.INCOMPATIBLE_JDK_LEVEL, project, path, CompilerOptions.versionFromJdkLevel(prereqProjectTargetJDK)); -// } -// } - } catch (CoreException e){ - return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.unboundProject", path.segment(0).toString(), projectName)); //$NON-NLS-1$ + case IClasspathEntry.CPE_PROJECT: + if (path != null && path.isAbsolute() && !path.isEmpty()) { + IProject prereqProjectRsc = workspaceRoot.getProject(path + .segment(0)); + IJavaProject prereqProject = JavaCore.create(prereqProjectRsc); + try { + if (!prereqProjectRsc.exists() + || !prereqProjectRsc + .hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) { + return new JavaModelStatus( + IJavaModelStatusConstants.INVALID_CLASSPATH, + Util + .bind( + "classpath.unboundProject", path.makeRelative().segment(0).toString(), projectName)); //$NON-NLS-1$ } - } else { - return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.illegalProjectPath", path.segment(0).toString(), projectName)); //$NON-NLS-1$ - } - break; - - // project source folder - case IClasspathEntry.CPE_SOURCE : - if (((entry.getInclusionPatterns() != null && entry.getInclusionPatterns().length > 0) - || (entry.getExclusionPatterns() != null && entry.getExclusionPatterns().length > 0)) - && JavaCore.DISABLED.equals(project.getOption(JavaCore.CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS, true))) { - return new JavaModelStatus(IJavaModelStatusConstants.DISABLED_CP_EXCLUSION_PATTERNS, project, path); - } - if (entry.getOutputLocation() != null && JavaCore.DISABLED.equals(project.getOption(JavaCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS, true))) { - return new JavaModelStatus(IJavaModelStatusConstants.DISABLED_CP_MULTIPLE_OUTPUT_LOCATIONS, project, path); - } - if (path != null && path.isAbsolute() && !path.isEmpty()) { - IPath projectPath= project.getProject().getFullPath(); - if (!projectPath.isPrefixOf(path) || JavaModel.getTarget(workspaceRoot, path, true) == null){ - return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.unboundSourceFolder", entryPathMsg, projectName)); //$NON-NLS-1$ + if (!prereqProjectRsc.isOpen()) { + return new JavaModelStatus( + IJavaModelStatusConstants.INVALID_CLASSPATH, + Util + .bind( + "classpath.closedProject", path.segment(0).toString())); //$NON-NLS-1$ } - } else { - return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.illegalSourceFolderPath", entryPathMsg, projectName)); //$NON-NLS-1$ + // if + // (project.getOption(JavaCore.CORE_INCOMPATIBLE_JDK_LEVEL, + // true) != JavaCore.IGNORE) { + // long projectTargetJDK = + // CompilerOptions.versionToJdkLevel(project.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, + // true)); + // long prereqProjectTargetJDK = + // CompilerOptions.versionToJdkLevel(prereqProject.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, + // true)); + // if (prereqProjectTargetJDK > projectTargetJDK) { + // return new + // JavaModelStatus(IJavaModelStatusConstants.INCOMPATIBLE_JDK_LEVEL, + // project, path, + // CompilerOptions.versionFromJdkLevel(prereqProjectTargetJDK)); + // } + // } + } catch (CoreException e) { + return new JavaModelStatus( + IJavaModelStatusConstants.INVALID_CLASSPATH, + Util + .bind( + "classpath.unboundProject", path.segment(0).toString(), projectName)); //$NON-NLS-1$ } - break; + } else { + return new JavaModelStatus( + IJavaModelStatusConstants.INVALID_CLASSPATH, + Util + .bind( + "classpath.illegalProjectPath", path.segment(0).toString(), projectName)); //$NON-NLS-1$ + } + break; + + // project source folder + case IClasspathEntry.CPE_SOURCE: + if (((entry.getInclusionPatterns() != null && entry + .getInclusionPatterns().length > 0) || (entry + .getExclusionPatterns() != null && entry + .getExclusionPatterns().length > 0)) + && JavaCore.DISABLED.equals(project.getOption( + JavaCore.CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS, + true))) { + return new JavaModelStatus( + IJavaModelStatusConstants.DISABLED_CP_EXCLUSION_PATTERNS, + project, path); + } + if (entry.getOutputLocation() != null + && JavaCore.DISABLED + .equals(project + .getOption( + JavaCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS, + true))) { + return new JavaModelStatus( + IJavaModelStatusConstants.DISABLED_CP_MULTIPLE_OUTPUT_LOCATIONS, + project, path); + } + if (path != null && path.isAbsolute() && !path.isEmpty()) { + IPath projectPath = project.getProject().getFullPath(); + if (!projectPath.isPrefixOf(path) + || JavaModel.getTarget(workspaceRoot, path, true) == null) { + return new JavaModelStatus( + IJavaModelStatusConstants.INVALID_CLASSPATH, + Util + .bind( + "classpath.unboundSourceFolder", entryPathMsg, projectName)); //$NON-NLS-1$ + } + } else { + return new JavaModelStatus( + IJavaModelStatusConstants.INVALID_CLASSPATH, + Util + .bind( + "classpath.illegalSourceFolderPath", entryPathMsg, projectName)); //$NON-NLS-1$ + } + break; } - return JavaModelStatus.VERIFIED_OK; + return JavaModelStatus.VERIFIED_OK; } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CommitWorkingCopyOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CommitWorkingCopyOperation.java index b03a1c5..96e21dd 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CommitWorkingCopyOperation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CommitWorkingCopyOperation.java @@ -28,179 +28,212 @@ import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.jobs.ISchedulingRule; /** - * Commits the contents of a working copy compilation unit to its original element and resource, bringing the Java Model up-to-date - * with the current contents of the working copy. + * Commits the contents of a working copy compilation unit to its original + * element and resource, bringing the Java Model up-to-date with the current + * contents of the working copy. * *

                    - * It is possible that the contents of the original resource have changed since the working copy was created, in which case there is - * an update conflict. This operation allows for two settings to resolve conflict set by the fForce flag: + * It is possible that the contents of the original resource have changed since + * the working copy was created, in which case there is an update conflict. This + * operation allows for two settings to resolve conflict set by the + * fForce flag: *

                      - *
                    • force flag is false- in this case an JavaModelException is thrown
                    • - *
                    • force flag is true- in this case the contents of the working copy are applied to the underlying resource - * even though the working copy was created before a subsequent change in the resource
                    • + *
                    • force flag is false- in this case an + * JavaModelException is thrown
                    • + *
                    • force flag is true- in this case the contents of the + * working copy are applied to the underlying resource even though the working + * copy was created before a subsequent change in the resource
                    • *
                    * *

                    - * The default conflict resolution setting is the force flag is false + * The default conflict resolution setting is the force flag is + * false * - * A JavaModelOperation exception is thrown either if the commit could not be performed or if the new content of the compilation - * unit violates some Java Model constraint (e.g. if the new package declaration doesn't match the name of the folder containing the - * compilation unit). + * A JavaModelOperation exception is thrown either if the commit could not be + * performed or if the new content of the compilation unit violates some Java + * Model constraint (e.g. if the new package declaration doesn't match the name + * of the folder containing the compilation unit). */ public class CommitWorkingCopyOperation extends JavaModelOperation { - /** - * Constructs an operation to commit the contents of a working copy to its original compilation unit. - */ - public CommitWorkingCopyOperation(ICompilationUnit element, boolean force) { - super(new IJavaElement[] { element }, force); - } - - /** - * @exception JavaModelException - * if setting the source of the original compilation unit fails - */ - protected void executeOperation() throws JavaModelException { - try { - beginTask(Util.bind("workingCopy.commit"), 2); //$NON-NLS-1$ - CompilationUnit workingCopy = getCompilationUnit(); - IFile resource = (IFile) workingCopy.getResource(); - ICompilationUnit primary = workingCopy.getPrimary(); - boolean isPrimary = workingCopy.isPrimary(); - - JavaElementDeltaBuilder deltaBuilder = null; - // PackageFragmentRoot root = (PackageFragmentRoot)workingCopy.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); - boolean isIncluded = !Util.isExcluded(workingCopy); - // if (isPrimary || (root.isOnClasspath() && isIncluded && resource.isAccessible() && - // ProjectPrefUtil.isValidCompilationUnitName(workingCopy.getElementName()))) { - if (isPrimary || (isIncluded && resource.isAccessible() && Util.isValidCompilationUnitName(workingCopy.getElementName()))) { - - // force opening so that the delta builder can get the old info - if (!isPrimary && !primary.isOpen()) { - primary.open(null); - } - - // creates the delta builder (this remembers the content of the cu) if: - // - it is not excluded - // - and it is not a primary or it is a non-consistent primary - if (isIncluded && (!isPrimary || !workingCopy.isConsistent())) { - deltaBuilder = new JavaElementDeltaBuilder(primary); - } - - // save the cu - IBuffer primaryBuffer = primary.getBuffer(); - if (!isPrimary) { - if (primaryBuffer == null) - return; - char[] primaryContents = primaryBuffer.getCharacters(); - boolean hasSaved = false; - try { - IBuffer workingCopyBuffer = workingCopy.getBuffer(); - if (workingCopyBuffer == null) - return; - primaryBuffer.setContents(workingCopyBuffer.getCharacters()); - primaryBuffer.save(this.progressMonitor, this.force); - primary.makeConsistent(this); - hasSaved = true; - } finally { - if (!hasSaved) { - // restore original buffer contents since something went wrong - primaryBuffer.setContents(primaryContents); - } - } - } else { - // for a primary working copy no need to set the content of the buffer again - primaryBuffer.save(this.progressMonitor, this.force); - primary.makeConsistent(this); - } - } else { - // working copy on cu outside classpath OR resource doesn't exist yet - String encoding = null; - try { - encoding = resource.getCharset(); - } catch (CoreException ce) { - // use no encoding - } - String contents = workingCopy.getSource(); - if (contents == null) - return; - try { - byte[] bytes = encoding == null ? contents.getBytes() : contents.getBytes(encoding); - ByteArrayInputStream stream = new ByteArrayInputStream(bytes); - if (resource.exists()) { - resource.setContents(stream, this.force ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY, null); - } else { - resource.create(stream, this.force, this.progressMonitor); - } - } catch (CoreException e) { - throw new JavaModelException(e); - } catch (UnsupportedEncodingException e) { - throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); - } - - } - - setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); - - // make sure working copy is in sync - workingCopy.updateTimeStamp((CompilationUnit) primary); - workingCopy.makeConsistent(this); - worked(1); - - // build the deltas - if (deltaBuilder != null) { - deltaBuilder.buildDeltas(); - - // add the deltas to the list of deltas created during this operation - if (deltaBuilder.delta != null) { - addDelta(deltaBuilder.delta); - } - } - worked(1); - } finally { - done(); - } - } - - /** - * Returns the compilation unit this operation is working on. - */ - protected CompilationUnit getCompilationUnit() { - return (CompilationUnit) getElementToProcess(); - } - - protected ISchedulingRule getSchedulingRule() { - IResource resource = getElementToProcess().getResource(); - IWorkspace workspace = resource.getWorkspace(); - if (resource.exists()) { - return workspace.getRuleFactory().modifyRule(resource); - } else { - return workspace.getRuleFactory().createRule(resource); - } - } - - /** - * Possible failures: - *

                      - *
                    • INVALID_ELEMENT_TYPES - the compilation unit supplied to this operation is not a working copy - *
                    • ELEMENT_NOT_PRESENT - the compilation unit the working copy is based on no longer exists. - *
                    • UPDATE_CONFLICT - the original compilation unit has changed since the working copy was created and the operation specifies - * no force - *
                    • READ_ONLY - the original compilation unit is in read-only mode - *
                    - */ - public IJavaModelStatus verify() { - CompilationUnit cu = getCompilationUnit(); - if (!cu.isWorkingCopy()) { - return new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, cu); - } - if (cu.hasResourceChanged() && !this.force) { - // axelcl deleted start - force it to VERIFIED_OK, need to be fixed - // return new JavaModelStatus(IJavaModelStatusConstants.UPDATE_CONFLICT); - // axelcl end - } - - // no read-only check, since some repository adapters can change the flag on save - // operation. - return JavaModelStatus.VERIFIED_OK; - } + /** + * Constructs an operation to commit the contents of a working copy to its + * original compilation unit. + */ + public CommitWorkingCopyOperation(ICompilationUnit element, boolean force) { + super(new IJavaElement[] { element }, force); + } + + /** + * @exception JavaModelException + * if setting the source of the original compilation unit + * fails + */ + protected void executeOperation() throws JavaModelException { + try { + beginTask(Util.bind("workingCopy.commit"), 2); //$NON-NLS-1$ + CompilationUnit workingCopy = getCompilationUnit(); + IFile resource = (IFile) workingCopy.getResource(); + ICompilationUnit primary = workingCopy.getPrimary(); + boolean isPrimary = workingCopy.isPrimary(); + + JavaElementDeltaBuilder deltaBuilder = null; + // PackageFragmentRoot root = + // (PackageFragmentRoot)workingCopy.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); + boolean isIncluded = !Util.isExcluded(workingCopy); + // if (isPrimary || (root.isOnClasspath() && isIncluded && + // resource.isAccessible() && + // ProjectPrefUtil.isValidCompilationUnitName(workingCopy.getElementName()))) + // { + if (isPrimary + || (isIncluded && resource.isAccessible() && Util + .isValidCompilationUnitName(workingCopy + .getElementName()))) { + + // force opening so that the delta builder can get the old info + if (!isPrimary && !primary.isOpen()) { + primary.open(null); + } + + // creates the delta builder (this remembers the content of the + // cu) if: + // - it is not excluded + // - and it is not a primary or it is a non-consistent primary + if (isIncluded && (!isPrimary || !workingCopy.isConsistent())) { + deltaBuilder = new JavaElementDeltaBuilder(primary); + } + + // save the cu + IBuffer primaryBuffer = primary.getBuffer(); + if (!isPrimary) { + if (primaryBuffer == null) + return; + char[] primaryContents = primaryBuffer.getCharacters(); + boolean hasSaved = false; + try { + IBuffer workingCopyBuffer = workingCopy.getBuffer(); + if (workingCopyBuffer == null) + return; + primaryBuffer.setContents(workingCopyBuffer + .getCharacters()); + primaryBuffer.save(this.progressMonitor, this.force); + primary.makeConsistent(this); + hasSaved = true; + } finally { + if (!hasSaved) { + // restore original buffer contents since something + // went wrong + primaryBuffer.setContents(primaryContents); + } + } + } else { + // for a primary working copy no need to set the content of + // the buffer again + primaryBuffer.save(this.progressMonitor, this.force); + primary.makeConsistent(this); + } + } else { + // working copy on cu outside classpath OR resource doesn't + // exist yet + String encoding = null; + try { + encoding = resource.getCharset(); + } catch (CoreException ce) { + // use no encoding + } + String contents = workingCopy.getSource(); + if (contents == null) + return; + try { + byte[] bytes = encoding == null ? contents.getBytes() + : contents.getBytes(encoding); + ByteArrayInputStream stream = new ByteArrayInputStream( + bytes); + if (resource.exists()) { + resource.setContents(stream, + this.force ? IResource.FORCE + | IResource.KEEP_HISTORY + : IResource.KEEP_HISTORY, null); + } else { + resource.create(stream, this.force, + this.progressMonitor); + } + } catch (CoreException e) { + throw new JavaModelException(e); + } catch (UnsupportedEncodingException e) { + throw new JavaModelException(e, + IJavaModelStatusConstants.IO_EXCEPTION); + } + + } + + setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); + + // make sure working copy is in sync + workingCopy.updateTimeStamp((CompilationUnit) primary); + workingCopy.makeConsistent(this); + worked(1); + + // build the deltas + if (deltaBuilder != null) { + deltaBuilder.buildDeltas(); + + // add the deltas to the list of deltas created during this + // operation + if (deltaBuilder.delta != null) { + addDelta(deltaBuilder.delta); + } + } + worked(1); + } finally { + done(); + } + } + + /** + * Returns the compilation unit this operation is working on. + */ + protected CompilationUnit getCompilationUnit() { + return (CompilationUnit) getElementToProcess(); + } + + protected ISchedulingRule getSchedulingRule() { + IResource resource = getElementToProcess().getResource(); + IWorkspace workspace = resource.getWorkspace(); + if (resource.exists()) { + return workspace.getRuleFactory().modifyRule(resource); + } else { + return workspace.getRuleFactory().createRule(resource); + } + } + + /** + * Possible failures: + *
                      + *
                    • INVALID_ELEMENT_TYPES - the compilation unit supplied to this + * operation is not a working copy + *
                    • ELEMENT_NOT_PRESENT - the compilation unit the working copy is based + * on no longer exists. + *
                    • UPDATE_CONFLICT - the original compilation unit has changed since + * the working copy was created and the operation specifies no force + *
                    • READ_ONLY - the original compilation unit is in read-only mode + *
                    + */ + public IJavaModelStatus verify() { + CompilationUnit cu = getCompilationUnit(); + if (!cu.isWorkingCopy()) { + return new JavaModelStatus( + IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, cu); + } + if (cu.hasResourceChanged() && !this.force) { + // axelcl deleted start - force it to VERIFIED_OK, need to be fixed + // return new + // JavaModelStatus(IJavaModelStatusConstants.UPDATE_CONFLICT); + // axelcl end + } + + // no read-only check, since some repository adapters can change the + // flag on save + // operation. + return JavaModelStatus.VERIFIED_OK; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CompilationUnit.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CompilationUnit.java index b9a6ffb..9bc011a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CompilationUnit.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CompilationUnit.java @@ -60,1293 +60,1478 @@ import org.eclipse.core.runtime.Path; */ public class CompilationUnit extends Openable implements ICompilationUnit, - net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit { - public WorkingCopyOwner owner; - /** - * Constructs a handle to a compilation unit with the given name in the specified package for the specified owner - * - * @exception IllegalArgumentException - * if the name of the compilation unit does not end with ".java" - */ - protected CompilationUnit(PackageFragment parent, String name, WorkingCopyOwner owner) { - super(parent, name); - this.owner = owner; - } - - /** - * Accepts the given visitor onto the parsed tree of this compilation unit, after having runned the name resolution. The visitor's - * corresponding visit method is called with the corresponding parse tree. If the visitor returns true, - * this method visits this parse node's members. - * - * @param visitor - * the visitor - * @exception JavaModelException - * if this method fails. Reasons include: - *
                      - *
                    • This element does not exist.
                    • - *
                    • The visitor failed with this exception.
                    • - *
                    - */ - //public void accept(IAbstractSyntaxTreeVisitor visitor) throws JavaModelException { - // CompilationUnitVisitor.visit(this, visitor); - //} - /* - * @see ICompilationUnit#becomeWorkingCopy(IProblemRequestor, IProgressMonitor) - */ - public void becomeWorkingCopy(IProblemRequestor problemRequestor, IProgressMonitor monitor) throws JavaModelException { - JavaModelManager manager = JavaModelManager.getJavaModelManager(); - JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = manager.getPerWorkingCopyInfo(this, false/* don't create */, - true /* record usage */, null/* no problem requestor needed */); - if (perWorkingCopyInfo == null) { - // close cu and its children - close(); - - BecomeWorkingCopyOperation operation = new BecomeWorkingCopyOperation(this, problemRequestor); - operation.runOperation(monitor); - } - } - - //protected void buildStructure(OpenableElementInfo info, IProgressMonitor monitor) throws JavaModelException { - // - // if (monitor != null && monitor.isCanceled()) return; - // - // // remove existing (old) infos - // removeInfo(); - // - // HashMap newElements = new HashMap(11); - // info.setIsStructureKnown(generateInfos(info, monitor, newElements, getResource())); - // JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().remove(this); - // for (Iterator iter = newElements.keySet().iterator(); iter.hasNext();) { - // IJavaElement key = (IJavaElement) iter.next(); - // Object value = newElements.get(key); - // JavaModelManager.getJavaModelManager().putInfo(key, value); - // } - // // add the info for this at the end, to ensure that a getInfo cannot reply null in case the LRU cache needs - // // to be flushed. Might lead to performance issues. - // // see PR 1G2K5S7: ITPJCORE:ALL - NPE when accessing source for a binary type - // JavaModelManager.getJavaModelManager().putInfo(this, info); - //} - protected boolean buildStructure(OpenableElementInfo info, final IProgressMonitor pm, Map newElements, - IResource underlyingResource) throws JavaModelException { - - // check if this compilation unit can be opened - if (!isWorkingCopy()) { // no check is done on root kind or exclusion pattern for working copies - if ( // ((IPackageFragment)getParent()).getKind() == IPackageFragmentRoot.K_BINARY|| - !isValidCompilationUnit() || !underlyingResource.isAccessible()) { - throw newNotPresentException(); - } - } - - // prevents reopening of non-primary working copies (they are closed when they are discarded and should not be reopened) - if (!isPrimary() && getPerWorkingCopyInfo() == null) { - throw newNotPresentException(); - } - - CompilationUnitElementInfo unitInfo = (CompilationUnitElementInfo) info; - - // get buffer contents - IBuffer buffer = getBufferManager().getBuffer(CompilationUnit.this); - if (buffer == null) { - buffer = openBuffer(pm, unitInfo); // open buffer independently from the info, since we are building the info - } - final char[] contents = buffer == null ? null : buffer.getCharacters(); - - // generate structure and compute syntax problems if needed - CompilationUnitStructureRequestor requestor = new CompilationUnitStructureRequestor(this, unitInfo, newElements); - JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = getPerWorkingCopyInfo(); - IJavaProject project = getJavaProject(); - boolean computeProblems = JavaProject.hasJavaNature(project.getProject()) && perWorkingCopyInfo != null - && perWorkingCopyInfo.isActive(); - IProblemFactory problemFactory = new DefaultProblemFactory(); - Map options = project.getOptions(true); - - if (underlyingResource == null) { - underlyingResource = getResource(); - } - - SourceElementParser parser = new SourceElementParser(requestor, problemFactory, - new CompilerOptions(options)); - //, true/*report local declarations*/); - requestor.parser = parser; - CompilationUnitDeclaration unit = parser.parseCompilationUnit( - new net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit() { - public char[] getContents() { - return contents; - } - - public char[] getMainTypeName() { - return CompilationUnit.this.getMainTypeName(); - } - - public char[][] getPackageName() { - return CompilationUnit.this.getPackageName(); - } - - public char[] getFileName() { - return CompilationUnit.this.getFileName(); - } - - public IResource getResource() { - return CompilationUnit.this.getResource(); - } - }, true /* full parse to find local elements */); - - // update timestamp (might be IResource.NULL_STAMP if original does not exist) - - unitInfo.timestamp = ((IFile) underlyingResource).getModificationStamp(); - // compute other problems if needed - CompilationUnitDeclaration compilationUnitDeclaration = null; - try { - if (computeProblems) { - perWorkingCopyInfo.beginReporting(); - compilationUnitDeclaration = CompilationUnitProblemFinder.process(unit, this, contents, parser, this.owner, - perWorkingCopyInfo, problemFactory, false/* don't cleanup cu */, pm); - perWorkingCopyInfo.endReporting(); - } - - // if (info instanceof ASTHolderCUInfo) { - // int astLevel = ((ASTHolderCUInfo) info).astLevel; - // net.sourceforge.phpdt.core.dom.CompilationUnit cu = AST.convertCompilationUnit(astLevel, unit, contents, options, pm); - // ((ASTHolderCUInfo) info).ast = cu; - // } - } finally { - if (compilationUnitDeclaration != null) { - compilationUnitDeclaration.cleanUp(); - } - } - - return unitInfo.isStructureKnown(); - } - - ///** - // * @see ICodeAssist#codeComplete(int, ICompletionRequestor) - // */ - //public void codeComplete(int offset, ICompletionRequestor requestor) throws JavaModelException { - // codeComplete(this, isWorkingCopy() ? (net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit) getOriginalElement() : this, - // offset, requestor); - //} - /** - * @see ICodeAssist#codeSelect(int, int) - */ - //public IJavaElement[] codeSelect(int offset, int length) throws JavaModelException { - // return super.codeSelect(this, offset, length); - //} - /** - * @see IWorkingCopy#commit(boolean, IProgressMonitor) - */ - public void commit(boolean force, IProgressMonitor monitor) throws JavaModelException { - commitWorkingCopy(force, monitor); - // throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, this)); - } - - /** - * @see ICompilationUnit#commitWorkingCopy(boolean, IProgressMonitor) - */ - public void commitWorkingCopy(boolean force, IProgressMonitor monitor) throws JavaModelException { - CommitWorkingCopyOperation op = new CommitWorkingCopyOperation(this, force); - op.runOperation(monitor); - } - - /** - * @see ISourceManipulation#copy(IJavaElement, IJavaElement, String, boolean, IProgressMonitor) - */ - public void copy(IJavaElement container, IJavaElement sibling, String rename, boolean force, IProgressMonitor monitor) - throws JavaModelException { - if (container == null) { - throw new IllegalArgumentException(Util.bind("operation.nullContainer")); //$NON-NLS-1$ - } - IJavaElement[] elements = new IJavaElement[] { this }; - IJavaElement[] containers = new IJavaElement[] { container }; - String[] renamings = null; - if (rename != null) { - renamings = new String[] { rename }; - } - getJavaModel().copy(elements, containers, null, renamings, force, monitor); - } - - /** - * Returns a new element info for this element. - */ - protected Object createElementInfo() { - return new CompilationUnitElementInfo(); - } - - ///** - // * @see ICompilationUnit#createImport(String, IJavaElement, IProgressMonitor) - // */ - //public IImportDeclaration createImport(String name, IJavaElement sibling, IProgressMonitor monitor) throws JavaModelException { - // CreateImportOperation op = new CreateImportOperation(name, this); - // if (sibling != null) { - // op.createBefore(sibling); - // } - // runOperation(op, monitor); - // return getImport(name); - //} - /** - * @see ICompilationUnit#createPackageDeclaration(String, IProgressMonitor) - */ - public IPackageDeclaration createPackageDeclaration(String name, IProgressMonitor monitor) throws JavaModelException { - - CreatePackageDeclarationOperation op = new CreatePackageDeclarationOperation(name, this); - runOperation(op, monitor); - return getPackageDeclaration(name); - } - - ///** - // * @see ICompilationUnit#createType(String, IJavaElement, boolean, IProgressMonitor) - // */ - //public IType createType(String content, IJavaElement sibling, boolean force, IProgressMonitor monitor) throws - // JavaModelException { - // if (!exists()) { - // //autogenerate this compilation unit - // IPackageFragment pkg = (IPackageFragment) getParent(); - // String source = ""; //$NON-NLS-1$ - // if (pkg.getElementName().length() > 0) { - // //not the default package...add the package declaration - // source = "package " + pkg.getElementName() + ";" + net.sourceforge.phpdt.internal.compiler.util.ProjectPrefUtil.LINE_SEPARATOR + - // net.sourceforge.phpdt.internal.compiler.util.ProjectPrefUtil.LINE_SEPARATOR; //$NON-NLS-1$ //$NON-NLS-2$ - // } - // CreateCompilationUnitOperation op = new CreateCompilationUnitOperation(pkg, fName, source, force); - // runOperation(op, monitor); - // } - // CreateTypeOperation op = new CreateTypeOperation(this, content, force); - // if (sibling != null) { - // op.createBefore(sibling); - // } - // runOperation(op, monitor); - // return (IType) op.getResultElements()[0]; - //} - /** - * @see ISourceManipulation#delete(boolean, IProgressMonitor) - */ - public void delete(boolean force, IProgressMonitor monitor) throws JavaModelException { - IJavaElement[] elements = new IJavaElement[] { this }; - getJavaModel().delete(elements, force, monitor); - } - - /** - * @see IWorkingCopy#destroy() - * @deprecated - */ - public void destroy() { - try { - discardWorkingCopy(); - } catch (JavaModelException e) { - e.printStackTrace(); - } - } - - /* - * @see ICompilationUnit#discardWorkingCopy - */ - public void discardWorkingCopy() throws JavaModelException { - // discard working copy and its children - DiscardWorkingCopyOperation op = new DiscardWorkingCopyOperation(this); - op.runOperation(null); - } - - /** - * Returns true if this handle represents the same Java element as the given handle. - * - * @see Object#equals(java.lang.Object) - */ - public boolean equals(Object obj) { - if (!(obj instanceof CompilationUnit)) - return false; - CompilationUnit other = (CompilationUnit) obj; - return this.owner.equals(other.owner) && super.equals(obj); - } - - /** - * @see JavaElement#equalsDOMNode(IDOMNode) - */ - protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException { - String name = getElementName(); - if (node.getNodeType() == IDOMNode.COMPILATION_UNIT && name != null) { - String nodeName = node.getName(); - if (nodeName == null) + net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit { + public WorkingCopyOwner owner; + + /** + * Constructs a handle to a compilation unit with the given name in the + * specified package for the specified owner + * + * @exception IllegalArgumentException + * if the name of the compilation unit does not end with + * ".java" + */ + protected CompilationUnit(PackageFragment parent, String name, + WorkingCopyOwner owner) { + super(parent, name); + this.owner = owner; + } + + /** + * Accepts the given visitor onto the parsed tree of this compilation unit, + * after having runned the name resolution. The visitor's corresponding + * visit method is called with the corresponding parse tree. + * If the visitor returns true, this method visits this + * parse node's members. + * + * @param visitor + * the visitor + * @exception JavaModelException + * if this method fails. Reasons include: + *
                      + *
                    • This element does not exist.
                    • + *
                    • The visitor failed with this exception.
                    • + *
                    + */ + // public void accept(IAbstractSyntaxTreeVisitor visitor) throws + // JavaModelException { + // CompilationUnitVisitor.visit(this, visitor); + // } + /* + * @see ICompilationUnit#becomeWorkingCopy(IProblemRequestor, + * IProgressMonitor) + */ + public void becomeWorkingCopy(IProblemRequestor problemRequestor, + IProgressMonitor monitor) throws JavaModelException { + JavaModelManager manager = JavaModelManager.getJavaModelManager(); + JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = manager + .getPerWorkingCopyInfo(this, false/* don't create */, + true /* record usage */, null/* + * no problem requestor + * needed + */); + if (perWorkingCopyInfo == null) { + // close cu and its children + close(); + + BecomeWorkingCopyOperation operation = new BecomeWorkingCopyOperation( + this, problemRequestor); + operation.runOperation(monitor); + } + } + + // protected void buildStructure(OpenableElementInfo info, IProgressMonitor + // monitor) throws JavaModelException { + // + // if (monitor != null && monitor.isCanceled()) return; + // + // // remove existing (old) infos + // removeInfo(); + // + // HashMap newElements = new HashMap(11); + // info.setIsStructureKnown(generateInfos(info, monitor, newElements, + // getResource())); + // JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().remove(this); + // for (Iterator iter = newElements.keySet().iterator(); iter.hasNext();) { + // IJavaElement key = (IJavaElement) iter.next(); + // Object value = newElements.get(key); + // JavaModelManager.getJavaModelManager().putInfo(key, value); + // } + // // add the info for this at the end, to ensure that a getInfo cannot + // reply null in case the LRU cache needs + // // to be flushed. Might lead to performance issues. + // // see PR 1G2K5S7: ITPJCORE:ALL - NPE when accessing source for a binary + // type + // JavaModelManager.getJavaModelManager().putInfo(this, info); + // } + protected boolean buildStructure(OpenableElementInfo info, + final IProgressMonitor pm, Map newElements, + IResource underlyingResource) throws JavaModelException { + + // check if this compilation unit can be opened + if (!isWorkingCopy()) { // no check is done on root kind or exclusion + // pattern for working copies + if ( // ((IPackageFragment)getParent()).getKind() == + // IPackageFragmentRoot.K_BINARY|| + !isValidCompilationUnit() || !underlyingResource.isAccessible()) { + throw newNotPresentException(); + } + } + + // prevents reopening of non-primary working copies (they are closed + // when they are discarded and should not be reopened) + if (!isPrimary() && getPerWorkingCopyInfo() == null) { + throw newNotPresentException(); + } + + CompilationUnitElementInfo unitInfo = (CompilationUnitElementInfo) info; + + // get buffer contents + IBuffer buffer = getBufferManager().getBuffer(CompilationUnit.this); + if (buffer == null) { + buffer = openBuffer(pm, unitInfo); // open buffer independently + // from the info, since we are + // building the info + } + final char[] contents = buffer == null ? null : buffer.getCharacters(); + + // generate structure and compute syntax problems if needed + CompilationUnitStructureRequestor requestor = new CompilationUnitStructureRequestor( + this, unitInfo, newElements); + JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = getPerWorkingCopyInfo(); + IJavaProject project = getJavaProject(); + boolean computeProblems = JavaProject.hasJavaNature(project + .getProject()) + && perWorkingCopyInfo != null && perWorkingCopyInfo.isActive(); + IProblemFactory problemFactory = new DefaultProblemFactory(); + Map options = project.getOptions(true); + + if (underlyingResource == null) { + underlyingResource = getResource(); + } + + SourceElementParser parser = new SourceElementParser(requestor, + problemFactory, new CompilerOptions(options)); + // , true/*report local declarations*/); + requestor.parser = parser; + CompilationUnitDeclaration unit = parser + .parseCompilationUnit( + new net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit() { + public char[] getContents() { + return contents; + } + + public char[] getMainTypeName() { + return CompilationUnit.this.getMainTypeName(); + } + + public char[][] getPackageName() { + return CompilationUnit.this.getPackageName(); + } + + public char[] getFileName() { + return CompilationUnit.this.getFileName(); + } + + public IResource getResource() { + return CompilationUnit.this.getResource(); + } + }, true /* full parse to find local elements */); + + // update timestamp (might be IResource.NULL_STAMP if original does not + // exist) + + unitInfo.timestamp = ((IFile) underlyingResource) + .getModificationStamp(); + // compute other problems if needed + CompilationUnitDeclaration compilationUnitDeclaration = null; + try { + if (computeProblems) { + perWorkingCopyInfo.beginReporting(); + compilationUnitDeclaration = CompilationUnitProblemFinder + .process(unit, this, contents, parser, this.owner, + perWorkingCopyInfo, problemFactory, + false/* don't cleanup cu */, pm); + perWorkingCopyInfo.endReporting(); + } + + // if (info instanceof ASTHolderCUInfo) { + // int astLevel = ((ASTHolderCUInfo) info).astLevel; + // net.sourceforge.phpdt.core.dom.CompilationUnit cu = + // AST.convertCompilationUnit(astLevel, unit, contents, options, + // pm); + // ((ASTHolderCUInfo) info).ast = cu; + // } + } finally { + if (compilationUnitDeclaration != null) { + compilationUnitDeclaration.cleanUp(); + } + } + + return unitInfo.isStructureKnown(); + } + + // /** + // * @see ICodeAssist#codeComplete(int, ICompletionRequestor) + // */ + // public void codeComplete(int offset, ICompletionRequestor requestor) + // throws JavaModelException { + // codeComplete(this, isWorkingCopy() ? + // (net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit) + // getOriginalElement() : this, + // offset, requestor); + // } + /** + * @see ICodeAssist#codeSelect(int, int) + */ + // public IJavaElement[] codeSelect(int offset, int length) throws + // JavaModelException { + // return super.codeSelect(this, offset, length); + // } + /** + * @see IWorkingCopy#commit(boolean, IProgressMonitor) + */ + public void commit(boolean force, IProgressMonitor monitor) + throws JavaModelException { + commitWorkingCopy(force, monitor); + // throw new JavaModelException(new + // JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, + // this)); + } + + /** + * @see ICompilationUnit#commitWorkingCopy(boolean, IProgressMonitor) + */ + public void commitWorkingCopy(boolean force, IProgressMonitor monitor) + throws JavaModelException { + CommitWorkingCopyOperation op = new CommitWorkingCopyOperation(this, + force); + op.runOperation(monitor); + } + + /** + * @see ISourceManipulation#copy(IJavaElement, IJavaElement, String, + * boolean, IProgressMonitor) + */ + public void copy(IJavaElement container, IJavaElement sibling, + String rename, boolean force, IProgressMonitor monitor) + throws JavaModelException { + if (container == null) { + throw new IllegalArgumentException(Util + .bind("operation.nullContainer")); //$NON-NLS-1$ + } + IJavaElement[] elements = new IJavaElement[] { this }; + IJavaElement[] containers = new IJavaElement[] { container }; + String[] renamings = null; + if (rename != null) { + renamings = new String[] { rename }; + } + getJavaModel().copy(elements, containers, null, renamings, force, + monitor); + } + + /** + * Returns a new element info for this element. + */ + protected Object createElementInfo() { + return new CompilationUnitElementInfo(); + } + + // /** + // * @see ICompilationUnit#createImport(String, IJavaElement, + // IProgressMonitor) + // */ + // public IImportDeclaration createImport(String name, IJavaElement sibling, + // IProgressMonitor monitor) throws JavaModelException { + // CreateImportOperation op = new CreateImportOperation(name, this); + // if (sibling != null) { + // op.createBefore(sibling); + // } + // runOperation(op, monitor); + // return getImport(name); + // } + /** + * @see ICompilationUnit#createPackageDeclaration(String, IProgressMonitor) + */ + public IPackageDeclaration createPackageDeclaration(String name, + IProgressMonitor monitor) throws JavaModelException { + + CreatePackageDeclarationOperation op = new CreatePackageDeclarationOperation( + name, this); + runOperation(op, monitor); + return getPackageDeclaration(name); + } + + // /** + // * @see ICompilationUnit#createType(String, IJavaElement, boolean, + // IProgressMonitor) + // */ + // public IType createType(String content, IJavaElement sibling, boolean + // force, IProgressMonitor monitor) throws + // JavaModelException { + // if (!exists()) { + // //autogenerate this compilation unit + // IPackageFragment pkg = (IPackageFragment) getParent(); + // String source = ""; //$NON-NLS-1$ + // if (pkg.getElementName().length() > 0) { + // //not the default package...add the package declaration + // source = "package " + pkg.getElementName() + ";" + + // net.sourceforge.phpdt.internal.compiler.util.ProjectPrefUtil.LINE_SEPARATOR + // + + // net.sourceforge.phpdt.internal.compiler.util.ProjectPrefUtil.LINE_SEPARATOR; + // //$NON-NLS-1$ //$NON-NLS-2$ + // } + // CreateCompilationUnitOperation op = new + // CreateCompilationUnitOperation(pkg, fName, source, force); + // runOperation(op, monitor); + // } + // CreateTypeOperation op = new CreateTypeOperation(this, content, force); + // if (sibling != null) { + // op.createBefore(sibling); + // } + // runOperation(op, monitor); + // return (IType) op.getResultElements()[0]; + // } + /** + * @see ISourceManipulation#delete(boolean, IProgressMonitor) + */ + public void delete(boolean force, IProgressMonitor monitor) + throws JavaModelException { + IJavaElement[] elements = new IJavaElement[] { this }; + getJavaModel().delete(elements, force, monitor); + } + + /** + * @see IWorkingCopy#destroy() + * @deprecated + */ + public void destroy() { + try { + discardWorkingCopy(); + } catch (JavaModelException e) { + e.printStackTrace(); + } + } + + /* + * @see ICompilationUnit#discardWorkingCopy + */ + public void discardWorkingCopy() throws JavaModelException { + // discard working copy and its children + DiscardWorkingCopyOperation op = new DiscardWorkingCopyOperation(this); + op.runOperation(null); + } + + /** + * Returns true if this handle represents the same Java element as the given + * handle. + * + * @see Object#equals(java.lang.Object) + */ + public boolean equals(Object obj) { + if (!(obj instanceof CompilationUnit)) + return false; + CompilationUnit other = (CompilationUnit) obj; + return this.owner.equals(other.owner) && super.equals(obj); + } + + /** + * @see JavaElement#equalsDOMNode(IDOMNode) + */ + protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException { + String name = getElementName(); + if (node.getNodeType() == IDOMNode.COMPILATION_UNIT && name != null) { + String nodeName = node.getName(); + if (nodeName == null) + return false; + if (name.equals(nodeName)) { + return true; + } else { + // iterate through all the types inside the receiver and see if + // one of them can fit + IType[] types = getTypes(); + String typeNodeName = nodeName.substring(0, nodeName + .indexOf(".java")); //$NON-NLS-1$ + for (int i = 0, max = types.length; i < max; i++) { + if (types[i].getElementName().equals(typeNodeName)) { + return true; + } + } + } + } return false; - if (name.equals(nodeName)) { - return true; - } else { - // iterate through all the types inside the receiver and see if one of them can fit - IType[] types = getTypes(); - String typeNodeName = nodeName.substring(0, nodeName.indexOf(".java")); //$NON-NLS-1$ - for (int i = 0, max = types.length; i < max; i++) { - if (types[i].getElementName().equals(typeNodeName)) { - return true; - } + } + + /** + * @see IWorkingCopy#findElements(IJavaElement) + */ + public IJavaElement[] findElements(IJavaElement element) { + ArrayList children = new ArrayList(); + while (element != null + && element.getElementType() != IJavaElement.COMPILATION_UNIT) { + children.add(element); + element = element.getParent(); } - } - } - return false; - } - - /** - * @see IWorkingCopy#findElements(IJavaElement) - */ - public IJavaElement[] findElements(IJavaElement element) { - ArrayList children = new ArrayList(); - while (element != null && element.getElementType() != IJavaElement.COMPILATION_UNIT) { - children.add(element); - element = element.getParent(); - } - if (element == null) - return null; - IJavaElement currentElement = this; - for (int i = children.size() - 1; i >= 0; i--) { - IJavaElement child = (IJavaElement) children.get(i); - switch (child.getElementType()) { - // case IJavaElement.PACKAGE_DECLARATION: - // currentElement = ((ICompilationUnit)currentElement).getPackageDeclaration(child.getElementName()); - // break; - // case IJavaElement.IMPORT_CONTAINER: - // currentElement = ((ICompilationUnit)currentElement).getImportContainer(); - // break; - // case IJavaElement.IMPORT_DECLARATION: - // currentElement = ((IImportContainer)currentElement).getImport(child.getElementName()); - // break; - case IJavaElement.TYPE: - if (currentElement.getElementType() == IJavaElement.COMPILATION_UNIT) { - currentElement = ((ICompilationUnit) currentElement).getType(child.getElementName()); + if (element == null) + return null; + IJavaElement currentElement = this; + for (int i = children.size() - 1; i >= 0; i--) { + IJavaElement child = (IJavaElement) children.get(i); + switch (child.getElementType()) { + // case IJavaElement.PACKAGE_DECLARATION: + // currentElement = + // ((ICompilationUnit)currentElement).getPackageDeclaration(child.getElementName()); + // break; + // case IJavaElement.IMPORT_CONTAINER: + // currentElement = + // ((ICompilationUnit)currentElement).getImportContainer(); + // break; + // case IJavaElement.IMPORT_DECLARATION: + // currentElement = + // ((IImportContainer)currentElement).getImport(child.getElementName()); + // break; + case IJavaElement.TYPE: + if (currentElement.getElementType() == IJavaElement.COMPILATION_UNIT) { + currentElement = ((ICompilationUnit) currentElement) + .getType(child.getElementName()); + } else { + currentElement = ((IType) currentElement).getType(child + .getElementName()); + } + break; + // case IJavaElement.INITIALIZER: + // currentElement = + // ((IType)currentElement).getInitializer(((JavaElement)child).getOccurrenceCount()); + // break; + case IJavaElement.FIELD: + currentElement = ((IType) currentElement).getField(child + .getElementName()); + break; + case IJavaElement.METHOD: + return ((IType) currentElement).findMethods((IMethod) child); + } + + } + if (currentElement != null && currentElement.exists()) { + return new IJavaElement[] { currentElement }; } else { - currentElement = ((IType) currentElement).getType(child.getElementName()); + return null; + } + } + + /** + * @see IWorkingCopy#findPrimaryType() + */ + public IType findPrimaryType() { + String typeName = Signature.getQualifier(this.getElementName()); + IType primaryType = this.getType(typeName); + if (primaryType.exists()) { + return primaryType; } - break; - // case IJavaElement.INITIALIZER: - // currentElement = ((IType)currentElement).getInitializer(((JavaElement)child).getOccurrenceCount()); - // break; - case IJavaElement.FIELD: - currentElement = ((IType) currentElement).getField(child.getElementName()); - break; - case IJavaElement.METHOD: - return ((IType) currentElement).findMethods((IMethod) child); - } - - } - if (currentElement != null && currentElement.exists()) { - return new IJavaElement[] { currentElement }; - } else { - return null; - } - } - - /** - * @see IWorkingCopy#findPrimaryType() - */ - public IType findPrimaryType() { - String typeName = Signature.getQualifier(this.getElementName()); - IType primaryType = this.getType(typeName); - if (primaryType.exists()) { - return primaryType; - } - return null; - } - - /** - * @see IWorkingCopy#findSharedWorkingCopy(IBufferFactory) - * @deprecated - */ - public IJavaElement findSharedWorkingCopy(IBufferFactory factory) { - - // if factory is null, default factory must be used - if (factory == null) - factory = this.getBufferManager().getDefaultBufferFactory(); - - return findWorkingCopy(BufferFactoryWrapper.create(factory)); - } - - /** - * @see ICompilationUnit#findWorkingCopy(WorkingCopyOwner) - */ - public ICompilationUnit findWorkingCopy(WorkingCopyOwner workingCopyOwner) { - CompilationUnit cu = new CompilationUnit((PackageFragment) this.parent, getElementName(), workingCopyOwner); - if (workingCopyOwner == DefaultWorkingCopyOwner.PRIMARY) { - return cu; - } else { - // must be a working copy - JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = cu.getPerWorkingCopyInfo(); - if (perWorkingCopyInfo != null) { - return perWorkingCopyInfo.getWorkingCopy(); - } else { return null; - } - } - } - - //protected boolean generateInfos(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) - // throws JavaModelException { - // - //// if (getParent() instanceof JarPackageFragment) { - //// // ignore .java files in jar - //// throw newNotPresentException(); - //// } else { - // // put the info now, because getting the contents requires it - // JavaModelManager.getJavaModelManager().putInfo(this, info); - // CompilationUnitElementInfo unitInfo = (CompilationUnitElementInfo) info; - // - // // generate structure - // CompilationUnitStructureRequestor requestor = new CompilationUnitStructureRequestor(this, unitInfo, newElements); - // IProblemFactory factory = new DefaultProblemFactory(); - // SourceElementParser parser = new SourceElementParser(requestor, factory, new - // CompilerOptions(getJavaProject().getOptions(true))); - //// SourceElementParser parser = new SourceElementParser(requestor, factory); - // requestor.parser = parser; - // parser.parseCompilationUnit(this, false); - // if (isWorkingCopy()) { - // CompilationUnit original = (CompilationUnit) getOriginalElement(); - // // might be IResource.NULL_STAMP if original does not exist - // unitInfo.timestamp = ((IFile) original.getResource()).getModificationStamp(); - // } - // return unitInfo.isStructureKnown(); - //// } - //} - /** - * @see ICompilationUnit#getAllTypes() - */ - public IType[] getAllTypes() throws JavaModelException { - IJavaElement[] types = getTypes(); - int i; - ArrayList allTypes = new ArrayList(types.length); - ArrayList typesToTraverse = new ArrayList(types.length); - for (i = 0; i < types.length; i++) { - typesToTraverse.add(types[i]); - } - while (!typesToTraverse.isEmpty()) { - IType type = (IType) typesToTraverse.get(0); - typesToTraverse.remove(type); - allTypes.add(type); - types = type.getTypes(); - for (i = 0; i < types.length; i++) { - typesToTraverse.add(types[i]); - } - } - IType[] arrayOfAllTypes = new IType[allTypes.size()]; - allTypes.toArray(arrayOfAllTypes); - return arrayOfAllTypes; - } - - /** - * @see IMember#getCompilationUnit() - */ - public ICompilationUnit getCompilationUnit() { - return this; - } - - /** - * @see net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit#getContents() - */ - public char[] getContents() { - try { - IBuffer buffer = this.getBuffer(); - return buffer == null ? null : buffer.getCharacters(); - } catch (JavaModelException e) { - return CharOperation.NO_CHAR; - } - } - - /** - * A compilation unit has a corresponding resource unless it is contained in a jar. - * - * @see IJavaElement#getCorrespondingResource() - */ - public IResource getCorrespondingResource() throws JavaModelException { - IPackageFragmentRoot root = (IPackageFragmentRoot) getParent().getParent(); - if (root.isArchive()) { - return null; - } else { - return getUnderlyingResource(); - } - } - - /** - * @see ICompilationUnit#getElementAt(int) - */ - public IJavaElement getElementAt(int position) throws JavaModelException { - - IJavaElement e = getSourceElementAt(position); - if (e == this) { - return null; - } else { - return e; - } - } - - /** - * @see IJavaElement - */ - public int getElementType() { - return COMPILATION_UNIT; - } - - public char[] getFileName() { - return getElementName().toCharArray(); - } - /* - * @see JavaElement - */ - public IJavaElement getHandleFromMemento(String token, MementoTokenizer memento, WorkingCopyOwner workingCopyOwner) { - switch (token.charAt(0)) { - case JEM_COUNT: - return getHandleUpdatingCountFromMemento(memento, workingCopyOwner); - case JEM_IMPORTDECLARATION: - JavaElement container = (JavaElement)getImportContainer(); - return container.getHandleFromMemento(token, memento, workingCopyOwner); - case JEM_PACKAGEDECLARATION: - String pkgName = memento.nextToken(); - JavaElement pkgDecl = (JavaElement)getPackageDeclaration(pkgName); - return pkgDecl.getHandleFromMemento(memento, workingCopyOwner); - case JEM_TYPE: - String typeName = memento.nextToken(); - JavaElement type = (JavaElement)getType(typeName); - return type.getHandleFromMemento(memento, workingCopyOwner); - } - return null; - } - - /** - * @see JavaElement#getHandleMementoDelimiter() - */ - protected char getHandleMementoDelimiter() { - return JavaElement.JEM_COMPILATIONUNIT; - } - /** - * @see ICompilationUnit#getImport(String) - */ - public IImportDeclaration getImport(String importName) { - return new ImportDeclaration((ImportContainer)getImportContainer(), importName); - } - /** - * @see ICompilationUnit#getImportContainer() - */ - public IImportContainer getImportContainer() { - return new ImportContainer(this); - } - - - /** - * @see ICompilationUnit#getImports() - */ - public IImportDeclaration[] getImports() throws JavaModelException { - IImportContainer container= getImportContainer(); - if (container.exists()) { - IJavaElement[] elements= container.getChildren(); - IImportDeclaration[] imprts= new IImportDeclaration[elements.length]; - System.arraycopy(elements, 0, imprts, 0, elements.length); - return imprts; - } else if (!exists()) { - throw newNotPresentException(); - } else { - return new IImportDeclaration[0]; - } - - } - - /** - * @see net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit#getMainTypeName() - */ - public char[] getMainTypeName() { - String name = getElementName(); - //remove the .java - name = name.substring(0, name.length() - 5); - return name.toCharArray(); - } - - /** - * @see IWorkingCopy#getOriginal(IJavaElement) - * @deprecated - */ - public IJavaElement getOriginal(IJavaElement workingCopyElement) { - // backward compatibility - if (!isWorkingCopy()) - return null; - CompilationUnit cu = (CompilationUnit) workingCopyElement.getAncestor(COMPILATION_UNIT); - if (cu == null || !this.owner.equals(cu.owner)) { - return null; - } - - return workingCopyElement.getPrimaryElement(); - } - - /** - * @see IWorkingCopy#getOriginalElement() - * @deprecated - */ - public IJavaElement getOriginalElement() { - // backward compatibility - if (!isWorkingCopy()) - return null; - - return getPrimaryElement(); - } - - /* - * @see ICompilationUnit#getOwner() - */ - public WorkingCopyOwner getOwner() { - return isPrimary() || !isWorkingCopy() ? null : this.owner; - } - - /** - * @see ICompilationUnit#getPackageDeclaration(String) - */ - public IPackageDeclaration getPackageDeclaration(String name) { - return new PackageDeclaration(this, name); - } - - /** - * @see ICompilationUnit#getPackageDeclarations() - */ - public IPackageDeclaration[] getPackageDeclarations() throws JavaModelException { - ArrayList list = getChildrenOfType(PACKAGE_DECLARATION); - IPackageDeclaration[] array = new IPackageDeclaration[list.size()]; - list.toArray(array); - return array; - } - - /** - * @see net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit#getPackageName() - */ - public char[][] getPackageName() { - return null; - } - - /** - * @see IJavaElement#getPath() - */ - public IPath getPath() { - PackageFragmentRoot root = this.getPackageFragmentRoot(); - if (root.isArchive()) { - return root.getPath(); - } else { - return this.getParent().getPath().append(this.getElementName()); - } - } - - /* - * Returns the per working copy info for the receiver, or null if none exist. Note: the use count of the per working copy info is - * NOT incremented. - */ - public JavaModelManager.PerWorkingCopyInfo getPerWorkingCopyInfo() { - return JavaModelManager.getJavaModelManager().getPerWorkingCopyInfo(this, false/* don't create */, false/* don't record usage */, - null/* no problem requestor needed */); - } - - /* - * @see ICompilationUnit#getPrimary() - */ - public ICompilationUnit getPrimary() { - return (ICompilationUnit) getPrimaryElement(true); - } - - /* - * @see JavaElement#getPrimaryElement(boolean) - */ - public IJavaElement getPrimaryElement(boolean checkOwner) { - if (checkOwner && isPrimary()) - return this; - return new CompilationUnit((PackageFragment) getParent(), getElementName(), DefaultWorkingCopyOwner.PRIMARY); - } - - /** - * @see IJavaElement#getResource() - */ - public IResource getResource() { - PackageFragmentRoot root = this.getPackageFragmentRoot(); - if (root.isArchive()) { - return root.getResource(); - } else { - return ((IContainer) this.getParent().getResource()).getFile(new Path(this.getElementName())); - } - } - - /** - * @see ISourceReference#getSource() - */ - public String getSource() throws JavaModelException { - IBuffer buffer = getBuffer(); - if (buffer == null) - return ""; //$NON-NLS-1$ - return buffer.getContents(); - } - - /** - * @see ISourceReference#getSourceRange() - */ - public ISourceRange getSourceRange() throws JavaModelException { - return ((CompilationUnitElementInfo) getElementInfo()).getSourceRange(); - } - - /** - * @see ICompilationUnit#getType(String) - */ - public IType getType(String name) { - return new SourceType(this, name); - } - - /** - * @see ICompilationUnit#getTypes() - */ - public IType[] getTypes() throws JavaModelException { - ArrayList list = getChildrenOfType(TYPE); - IType[] array = new IType[list.size()]; - list.toArray(array); - return array; - } - - /** - * @see IJavaElement - */ - public IResource getUnderlyingResource() throws JavaModelException { - if (isWorkingCopy() && !isPrimary()) - return null; - return super.getUnderlyingResource(); - } - - ///** - // * @see IWorkingCopy#getSharedWorkingCopy(IProgressMonitor, IBufferFactory, IProblemRequestor) - // */ - //public IJavaElement getSharedWorkingCopy(IProgressMonitor pm, IBufferFactory factory, IProblemRequestor problemRequestor) - // throws JavaModelException { - // - // // if factory is null, default factory must be used - // if (factory == null) factory = this.getBufferManager().getDefaultBufferFactory(); - // - // JavaModelManager manager = JavaModelManager.getJavaModelManager(); - // - // // In order to be shared, working copies have to denote the same compilation unit - // // AND use the same buffer factory. - // // Assuming there is a little set of buffer factories, then use a 2 level Map cache. - // Map sharedWorkingCopies = manager.sharedWorkingCopies; - // - // Map perFactoryWorkingCopies = (Map) sharedWorkingCopies.get(factory); - // if (perFactoryWorkingCopies == null){ - // perFactoryWorkingCopies = new HashMap(); - // sharedWorkingCopies.put(factory, perFactoryWorkingCopies); - // } - // WorkingCopy workingCopy = (WorkingCopy)perFactoryWorkingCopies.get(this); - // if (workingCopy != null) { - // workingCopy.useCount++; - // - // if (SHARED_WC_VERBOSE) { - // System.out.println("Incrementing use count of shared working copy " + workingCopy.toStringWithAncestors()); //$NON-NLS-1$ - // } - // - // return workingCopy; - // } else { - // CreateWorkingCopyOperation op = new CreateWorkingCopyOperation(this, perFactoryWorkingCopies, factory, problemRequestor); - // runOperation(op, pm); - // return op.getResultElements()[0]; - // } - //} - ///** - // * @see IWorkingCopy#getWorkingCopy() - // */ - //public IJavaElement getWorkingCopy() throws JavaModelException { - // return this.getWorkingCopy(null, null, null); - //} - // - ///** - // * @see IWorkingCopy#getWorkingCopy(IProgressMonitor, IBufferFactory, IProblemRequestor) - // */ - //public IJavaElement getWorkingCopy(IProgressMonitor pm, IBufferFactory factory, IProblemRequestor problemRequestor) throws - // JavaModelException { - // CreateWorkingCopyOperation op = new CreateWorkingCopyOperation(this, null, factory, problemRequestor); - // runOperation(op, pm); - // return op.getResultElements()[0]; - //} - /** - * @see IWorkingCopy#getSharedWorkingCopy(IProgressMonitor, IBufferFactory, IProblemRequestor) - * @deprecated - */ - public IJavaElement getSharedWorkingCopy(IProgressMonitor pm, IBufferFactory factory, IProblemRequestor problemRequestor) - throws JavaModelException { - - // if factory is null, default factory must be used - if (factory == null) - factory = this.getBufferManager().getDefaultBufferFactory(); - - return getWorkingCopy(BufferFactoryWrapper.create(factory), problemRequestor, pm); - } - - /** - * @see IWorkingCopy#getWorkingCopy() - * @deprecated - */ - public IJavaElement getWorkingCopy() throws JavaModelException { - return getWorkingCopy(null); - } - - /** - * @see ICompilationUnit#getWorkingCopy(IProgressMonitor) - */ - public ICompilationUnit getWorkingCopy(IProgressMonitor monitor) throws JavaModelException { - return getWorkingCopy(new WorkingCopyOwner() {/* non shared working copy */ - }, null/* no problem requestor */, monitor); - } - - /** - * @see IWorkingCopy#getWorkingCopy(IProgressMonitor, IBufferFactory, IProblemRequestor) - * @deprecated - */ - public IJavaElement getWorkingCopy(IProgressMonitor monitor, IBufferFactory factory, IProblemRequestor problemRequestor) - throws JavaModelException { - return getWorkingCopy(BufferFactoryWrapper.create(factory), problemRequestor, monitor); - } - - /** - * @see ICompilationUnit#getWorkingCopy(WorkingCopyOwner, IProblemRequestor, IProgressMonitor) - */ - public ICompilationUnit getWorkingCopy(WorkingCopyOwner workingCopyOwner, IProblemRequestor problemRequestor, - IProgressMonitor monitor) throws JavaModelException { - if (!isPrimary()) - return this; - - JavaModelManager manager = JavaModelManager.getJavaModelManager(); - - CompilationUnit workingCopy = new CompilationUnit((PackageFragment) getParent(), getElementName(), workingCopyOwner); - JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = manager.getPerWorkingCopyInfo(workingCopy, false/* don't create */, - true/* record usage */, null/* not used since don't create */); - if (perWorkingCopyInfo != null) { - return perWorkingCopyInfo.getWorkingCopy(); // return existing handle instead of the one created above - } - BecomeWorkingCopyOperation op = new BecomeWorkingCopyOperation(workingCopy, problemRequestor); - op.runOperation(monitor); - return workingCopy; - } - - /** - * If I am not open, return true to avoid parsing. - * - * @see IParent#hasChildren() - */ - public boolean hasChildren() throws JavaModelException { - // if (isOpen()) { - // return getChildren().length > 0; - // } else { - // return true; - // } - return false; - } - - /** - * @see Openable#hasBuffer() - */ - protected boolean hasBuffer() { - return true; - } - - /* - * @see ICompilationUnit#hasResourceChanged() - */ - public boolean hasResourceChanged() { - if (!isWorkingCopy()) - return false; - - // if resource got deleted, then #getModificationStamp() will answer IResource.NULL_STAMP, which is always different from the - // cached - // timestamp - Object info = JavaModelManager.getJavaModelManager().getInfo(this); - if (info == null) - return false; - return ((CompilationUnitElementInfo) info).timestamp != getResource().getModificationStamp(); - } - - /** - * @see IWorkingCopy#isBasedOn(IResource) - * @deprecated - */ - public boolean isBasedOn(IResource resource) { - if (!isWorkingCopy()) - return false; - if (!getResource().equals(resource)) - return false; - return !hasResourceChanged(); - } - - /** - * @see IOpenable#isConsistent() - */ - public boolean isConsistent() { - return JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().get(this) == null; - } - - /** - * - * @see IOpenable - */ - public boolean isOpen() { - Object info = JavaModelManager.getJavaModelManager().getInfo(this); - return info != null && ((CompilationUnitElementInfo) info).isOpen(); - } - - public boolean isPrimary() { - return this.owner == DefaultWorkingCopyOwner.PRIMARY; - } - - /** - * @see Openable#isSourceElement() - */ - protected boolean isSourceElement() { - return true; - } - - protected boolean isValidCompilationUnit() { - IPackageFragmentRoot root = getPackageFragmentRoot(); - try { - if (root.getKind() != IPackageFragmentRoot.K_SOURCE) - return false; - } catch (JavaModelException e) { - return false; - } - // IResource resource = getResource(); - // if (resource != null) { - // char[][] inclusionPatterns = ((PackageFragmentRoot)root).fullInclusionPatternChars(); - // char[][] exclusionPatterns = ((PackageFragmentRoot)root).fullExclusionPatternChars(); - // if (ProjectPrefUtil.isExcluded(resource, inclusionPatterns, exclusionPatterns)) return false; - // } - if (!Util.isValidCompilationUnitName(getElementName())) - return false; - return true; - } - - /* - * @see ICompilationUnit#isWorkingCopy() - */ - public boolean isWorkingCopy() { - // For backward compatibility, non primary working copies are always returning true; in removal - // delta, clients can still check that element was a working copy before being discarded. - return !isPrimary() || getPerWorkingCopyInfo() != null; - } - - /** - * @see IOpenable#makeConsistent(IProgressMonitor) - */ - public void makeConsistent(IProgressMonitor monitor) throws JavaModelException { - makeConsistent(false/* don't create AST */, 0, monitor); - } - - public Object makeConsistent(boolean createAST, int astLevel, IProgressMonitor monitor) throws JavaModelException { - if (isConsistent()) - return null; - - // create a new info and make it the current info - // (this will remove the info and its children just before storing the new infos) - // if (createAST) { - // ASTHolderCUInfo info = new ASTHolderCUInfo(); - // info.astLevel = astLevel; - // openWhenClosed(info, monitor); - // net.sourceforge.phpdt.core.dom.CompilationUnit result = info.ast; - // info.ast = null; - // return result; - // } else { - openWhenClosed(createElementInfo(), monitor); - return null; - // } - } - - //public net.sourceforge.phpdt.core.dom.CompilationUnit makeConsistent(boolean createAST, int astLevel, IProgressMonitor monitor) - // throws JavaModelException { - // if (isConsistent()) return null; - // - // // create a new info and make it the current info - // // (this will remove the info and its children just before storing the new infos) - // if (createAST) { - // ASTHolderCUInfo info = new ASTHolderCUInfo(); - // info.astLevel = astLevel; - // openWhenClosed(info, monitor); - // net.sourceforge.phpdt.core.dom.CompilationUnit result = info.ast; - // info.ast = null; - // return result; - // } else { - // openWhenClosed(createElementInfo(), monitor); - // return null; - // } - //} - - /** - * @see ISourceManipulation#move(IJavaElement, IJavaElement, String, boolean, IProgressMonitor) - */ - public void move(IJavaElement container, IJavaElement sibling, String rename, boolean force, IProgressMonitor monitor) - throws JavaModelException { - if (container == null) { - throw new IllegalArgumentException(Util.bind("operation.nullContainer")); //$NON-NLS-1$ - } - IJavaElement[] elements = new IJavaElement[] { this }; - IJavaElement[] containers = new IJavaElement[] { container }; - - String[] renamings = null; - if (rename != null) { - renamings = new String[] { rename }; - } - getJavaModel().move(elements, containers, null, renamings, force, monitor); - } - - ///** - // * @see Openable#openBuffer(IProgressMonitor) - // */ - //protected IBuffer openBuffer(IProgressMonitor pm) throws JavaModelException { - // - // // create buffer - compilation units only use default buffer factory - // BufferManager bufManager = getBufferManager(); - // IBuffer buffer = getBufferFactory().createBuffer(this); - // if (buffer == null) return null; - // - // // set the buffer source - // if (buffer.getCharacters() == null){ - // IFile file = (IFile)this.getResource(); - // if (file == null || !file.exists()) throw newNotPresentException(); - // buffer.setContents(ProjectPrefUtil.getResourceContentsAsCharArray(file)); - // } - // - // // add buffer to buffer cache - // bufManager.addBuffer(buffer); - // - // // listen to buffer changes - // buffer.addBufferChangedListener(this); - // - // return buffer; - //} - /** - * @see Openable#openBuffer(IProgressMonitor, Object) - */ - protected IBuffer openBuffer(IProgressMonitor pm, Object info) throws JavaModelException { - - // create buffer - boolean isWorkingCopy = isWorkingCopy(); - IBuffer buffer = isWorkingCopy ? this.owner.createBuffer(this) : BufferManager.getDefaultBufferManager().createBuffer(this); - if (buffer == null) - return null; - - // set the buffer source - if (buffer.getCharacters() == null) { - if (isWorkingCopy) { - ICompilationUnit original; - if (!isPrimary() - && (original = new CompilationUnit((PackageFragment) getParent(), getElementName(), DefaultWorkingCopyOwner.PRIMARY)) - .isOpen()) { - buffer.setContents(original.getSource()); + } + + /** + * @see IWorkingCopy#findSharedWorkingCopy(IBufferFactory) + * @deprecated + */ + public IJavaElement findSharedWorkingCopy(IBufferFactory factory) { + + // if factory is null, default factory must be used + if (factory == null) + factory = this.getBufferManager().getDefaultBufferFactory(); + + return findWorkingCopy(BufferFactoryWrapper.create(factory)); + } + + /** + * @see ICompilationUnit#findWorkingCopy(WorkingCopyOwner) + */ + public ICompilationUnit findWorkingCopy(WorkingCopyOwner workingCopyOwner) { + CompilationUnit cu = new CompilationUnit((PackageFragment) this.parent, + getElementName(), workingCopyOwner); + if (workingCopyOwner == DefaultWorkingCopyOwner.PRIMARY) { + return cu; + } else { + // must be a working copy + JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = cu + .getPerWorkingCopyInfo(); + if (perWorkingCopyInfo != null) { + return perWorkingCopyInfo.getWorkingCopy(); + } else { + return null; + } + } + } + + // protected boolean generateInfos(OpenableElementInfo info, + // IProgressMonitor pm, Map newElements, IResource underlyingResource) + // throws JavaModelException { + // + // // if (getParent() instanceof JarPackageFragment) { + // // // ignore .java files in jar + // // throw newNotPresentException(); + // // } else { + // // put the info now, because getting the contents requires it + // JavaModelManager.getJavaModelManager().putInfo(this, info); + // CompilationUnitElementInfo unitInfo = (CompilationUnitElementInfo) info; + // + // // generate structure + // CompilationUnitStructureRequestor requestor = new + // CompilationUnitStructureRequestor(this, unitInfo, newElements); + // IProblemFactory factory = new DefaultProblemFactory(); + // SourceElementParser parser = new SourceElementParser(requestor, factory, + // new + // CompilerOptions(getJavaProject().getOptions(true))); + // // SourceElementParser parser = new SourceElementParser(requestor, + // factory); + // requestor.parser = parser; + // parser.parseCompilationUnit(this, false); + // if (isWorkingCopy()) { + // CompilationUnit original = (CompilationUnit) getOriginalElement(); + // // might be IResource.NULL_STAMP if original does not exist + // unitInfo.timestamp = ((IFile) + // original.getResource()).getModificationStamp(); + // } + // return unitInfo.isStructureKnown(); + // // } + // } + /** + * @see ICompilationUnit#getAllTypes() + */ + public IType[] getAllTypes() throws JavaModelException { + IJavaElement[] types = getTypes(); + int i; + ArrayList allTypes = new ArrayList(types.length); + ArrayList typesToTraverse = new ArrayList(types.length); + for (i = 0; i < types.length; i++) { + typesToTraverse.add(types[i]); + } + while (!typesToTraverse.isEmpty()) { + IType type = (IType) typesToTraverse.get(0); + typesToTraverse.remove(type); + allTypes.add(type); + types = type.getTypes(); + for (i = 0; i < types.length; i++) { + typesToTraverse.add(types[i]); + } + } + IType[] arrayOfAllTypes = new IType[allTypes.size()]; + allTypes.toArray(arrayOfAllTypes); + return arrayOfAllTypes; + } + + /** + * @see IMember#getCompilationUnit() + */ + public ICompilationUnit getCompilationUnit() { + return this; + } + + /** + * @see net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit#getContents() + */ + public char[] getContents() { + try { + IBuffer buffer = this.getBuffer(); + return buffer == null ? null : buffer.getCharacters(); + } catch (JavaModelException e) { + return CharOperation.NO_CHAR; + } + } + + /** + * A compilation unit has a corresponding resource unless it is contained in + * a jar. + * + * @see IJavaElement#getCorrespondingResource() + */ + public IResource getCorrespondingResource() throws JavaModelException { + IPackageFragmentRoot root = (IPackageFragmentRoot) getParent() + .getParent(); + if (root.isArchive()) { + return null; + } else { + return getUnderlyingResource(); + } + } + + /** + * @see ICompilationUnit#getElementAt(int) + */ + public IJavaElement getElementAt(int position) throws JavaModelException { + + IJavaElement e = getSourceElementAt(position); + if (e == this) { + return null; } else { - IFile file = (IFile) getResource(); - if (file == null || !file.exists()) { - // initialize buffer with empty contents - buffer.setContents(CharOperation.NO_CHAR); - } else { - buffer.setContents(Util.getResourceContentsAsCharArray(file)); - } + return e; } - } else { - IFile file = (IFile) this.getResource(); - if (file == null || !file.exists()) - throw newNotPresentException(); - buffer.setContents(Util.getResourceContentsAsCharArray(file)); - } - } - - // add buffer to buffer cache - BufferManager bufManager = getBufferManager(); - bufManager.addBuffer(buffer); - - // listen to buffer changes - buffer.addBufferChangedListener(this); - - return buffer; - } - - /* - * @see Openable#openParent - */ - protected void openParent(Object childInfo, HashMap newElements, IProgressMonitor pm) throws JavaModelException { - try { - super.openParent(childInfo, newElements, pm); - } catch (JavaModelException e) { - // allow parent to not exist for working copies defined outside classpath - if (!isWorkingCopy() && !e.isDoesNotExist()) { - throw e; - } - } - } - - /** - * @see ICompilationUnit#reconcile() - * @deprecated - */ - public IMarker[] reconcile() throws JavaModelException { - reconcile(NO_AST, false/* don't force problem detection */, null/* use primary owner */, null/* no progress monitor */); - return null; - } - - /** - * @see ICompilationUnit#reconcile(int, boolean, WorkingCopyOwner, IProgressMonitor) - */ - public void reconcile(boolean forceProblemDetection, IProgressMonitor monitor) throws JavaModelException { - reconcile(NO_AST, forceProblemDetection, null/* use primary owner */, monitor); - } - - /** - * @see ICompilationUnit#reconcile(int, boolean, WorkingCopyOwner, IProgressMonitor) - * @since 3.0 - */ - //public net.sourceforge.phpdt.core.dom.CompilationUnit reconcile( - public Object reconcile(int astLevel, boolean forceProblemDetection, WorkingCopyOwner workingCopyOwner, IProgressMonitor monitor) - throws JavaModelException { - - if (!isWorkingCopy()) - return null; // Reconciling is not supported on non working copies - if (workingCopyOwner == null) - workingCopyOwner = DefaultWorkingCopyOwner.PRIMARY; - - boolean createAST = false; - // if (astLevel == AST.JLS2) { - // // client asking for level 2 AST; these are supported - // createAST = true; - // } else if (astLevel == AST.JLS3) { - // // client asking for level 3 ASTs; these are not supported - // // TODO (jerome) - these should also be supported in 1.5 stream - // createAST = false; - // } else { - // // client asking for no AST (0) or unknown ast level - // // either way, request denied - // createAST = false; - // } - ReconcileWorkingCopyOperation op = new ReconcileWorkingCopyOperation(this, createAST, astLevel, forceProblemDetection, - workingCopyOwner); - op.runOperation(monitor); - // return op.ast; - return null; - } - - /** - * @see ISourceManipulation#rename(String, boolean, IProgressMonitor) - */ - public void rename(String name, boolean force, IProgressMonitor monitor) throws JavaModelException { - if (name == null) { - throw new IllegalArgumentException(Util.bind("operation.nullName")); //$NON-NLS-1$ - } - IJavaElement[] elements = new IJavaElement[] { this }; - IJavaElement[] dests = new IJavaElement[] { this.getParent() }; - String[] renamings = new String[] { name }; - getJavaModel().rename(elements, dests, renamings, force, monitor); - } - - /* - * @see ICompilationUnit - */ - public void restore() throws JavaModelException { - - if (!isWorkingCopy()) - return; - - CompilationUnit original = (CompilationUnit) getOriginalElement(); - IBuffer buffer = this.getBuffer(); - if (buffer == null) - return; - buffer.setContents(original.getContents()); - updateTimeStamp(original); - makeConsistent(null); - } - -// /** -// * @see ICodeAssist#codeComplete(int, ICodeCompletionRequestor) -// * @deprecated - use codeComplete(int, ICompletionRequestor) -// */ - //public void codeComplete(int offset, final ICodeCompletionRequestor requestor) throws JavaModelException { - // - // if (requestor == null){ - // codeComplete(offset, (ICompletionRequestor)null); - // return; - // } - // codeComplete( - // offset, - // new ICompletionRequestor(){ - // public void acceptAnonymousType(char[] superTypePackageName,char[] superTypeName,char[][] parameterPackageNames,char[][] - // parameterTypeNames,char[][] parameterNames,char[] completionName,int modifiers,int completionStart,int completionEnd, int - // relevance){ - // } - // public void acceptClass(char[] packageName, char[] className, char[] completionName, int modifiers, int completionStart, int - // completionEnd, int relevance) { - // requestor.acceptClass(packageName, className, completionName, modifiers, completionStart, completionEnd); - // } - // public void acceptError(IProblem error) { - // if (true) return; // was disabled in 1.0 - // - // try { - // IMarker marker = ResourcesPlugin.getWorkspace().getRoot().createMarker(IJavaModelMarker.TRANSIENT_PROBLEM); - // marker.setAttribute(IJavaModelMarker.ID, error.getID()); - // marker.setAttribute(IMarker.CHAR_START, error.getSourceStart()); - // marker.setAttribute(IMarker.CHAR_END, error.getSourceEnd() + 1); - // marker.setAttribute(IMarker.LINE_NUMBER, error.getSourceLineNumber()); - // marker.setAttribute(IMarker.MESSAGE, error.getMessage()); - // marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); - // requestor.acceptError(marker); - // } catch(CoreException e){ - // } - // } - // public void acceptField(char[] declaringTypePackageName, char[] declaringTypeName, char[] name, char[] typePackageName, char[] - // typeName, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) { - // requestor.acceptField(declaringTypePackageName, declaringTypeName, name, typePackageName, typeName, completionName, modifiers, - // completionStart, completionEnd); - // } - // public void acceptInterface(char[] packageName,char[] interfaceName,char[] completionName,int modifiers,int completionStart,int - // completionEnd, int relevance) { - // requestor.acceptInterface(packageName, interfaceName, completionName, modifiers, completionStart, completionEnd); - // } - // public void acceptKeyword(char[] keywordName,int completionStart,int completionEnd, int relevance){ - // requestor.acceptKeyword(keywordName, completionStart, completionEnd); - // } - // public void acceptLabel(char[] labelName,int completionStart,int completionEnd, int relevance){ - // requestor.acceptLabel(labelName, completionStart, completionEnd); - // } - // public void acceptLocalVariable(char[] name,char[] typePackageName,char[] typeName,int modifiers,int completionStart,int - // completionEnd, int relevance){ - // // ignore - // } - // public void acceptMethod(char[] declaringTypePackageName,char[] declaringTypeName,char[] selector,char[][] - // parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] returnTypePackageName,char[] - // returnTypeName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance){ - // // skip parameter names - // requestor.acceptMethod(declaringTypePackageName, declaringTypeName, selector, parameterPackageNames, parameterTypeNames, - // returnTypePackageName, returnTypeName, completionName, modifiers, completionStart, completionEnd); - // } - // public void acceptMethodDeclaration(char[] declaringTypePackageName,char[] declaringTypeName,char[] selector,char[][] - // parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] returnTypePackageName,char[] - // returnTypeName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance){ - // // ignore - // } - // public void acceptModifier(char[] modifierName,int completionStart,int completionEnd, int relevance){ - // requestor.acceptModifier(modifierName, completionStart, completionEnd); - // } - // public void acceptPackage(char[] packageName,char[] completionName,int completionStart,int completionEnd, int relevance){ - // requestor.acceptPackage(packageName, completionName, completionStart, completionEnd); - // } - // public void acceptType(char[] packageName,char[] typeName,char[] completionName,int completionStart,int completionEnd, int - // relevance){ - // requestor.acceptType(packageName, typeName, completionName, completionStart, completionEnd); - // } - // public void acceptVariableName(char[] typePackageName,char[] typeName,char[] name,char[] completionName,int completionStart,int - // completionEnd, int relevance){ - // // ignore - // } - // }); - //} - ///** - // * @see JavaElement#rootedAt(IJavaProject) - // */ - //public IJavaElement rootedAt(IJavaProject project) { - // return - // new CompilationUnit( - // (IPackageFragment)((JavaElement)parent).rootedAt(project), - // name); - //} - - /* - * Assume that this is a working copy - */ - protected void updateTimeStamp(CompilationUnit original) throws JavaModelException { - long timeStamp = ((IFile) original.getResource()).getModificationStamp(); - if (timeStamp == IResource.NULL_STAMP) { - throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_RESOURCE)); - } - ((CompilationUnitElementInfo) getElementInfo()).timestamp = timeStamp; - } + } + + /** + * @see IJavaElement + */ + public int getElementType() { + return COMPILATION_UNIT; + } + + public char[] getFileName() { + return getElementName().toCharArray(); + } + + /* + * @see JavaElement + */ + public IJavaElement getHandleFromMemento(String token, + MementoTokenizer memento, WorkingCopyOwner workingCopyOwner) { + switch (token.charAt(0)) { + case JEM_COUNT: + return getHandleUpdatingCountFromMemento(memento, workingCopyOwner); + case JEM_IMPORTDECLARATION: + JavaElement container = (JavaElement) getImportContainer(); + return container.getHandleFromMemento(token, memento, + workingCopyOwner); + case JEM_PACKAGEDECLARATION: + String pkgName = memento.nextToken(); + JavaElement pkgDecl = (JavaElement) getPackageDeclaration(pkgName); + return pkgDecl.getHandleFromMemento(memento, workingCopyOwner); + case JEM_TYPE: + String typeName = memento.nextToken(); + JavaElement type = (JavaElement) getType(typeName); + return type.getHandleFromMemento(memento, workingCopyOwner); + } + return null; + } + + /** + * @see JavaElement#getHandleMementoDelimiter() + */ + protected char getHandleMementoDelimiter() { + return JavaElement.JEM_COMPILATIONUNIT; + } + + /** + * @see ICompilationUnit#getImport(String) + */ + public IImportDeclaration getImport(String importName) { + return new ImportDeclaration((ImportContainer) getImportContainer(), + importName); + } + + /** + * @see ICompilationUnit#getImportContainer() + */ + public IImportContainer getImportContainer() { + return new ImportContainer(this); + } + + /** + * @see ICompilationUnit#getImports() + */ + public IImportDeclaration[] getImports() throws JavaModelException { + IImportContainer container = getImportContainer(); + if (container.exists()) { + IJavaElement[] elements = container.getChildren(); + IImportDeclaration[] imprts = new IImportDeclaration[elements.length]; + System.arraycopy(elements, 0, imprts, 0, elements.length); + return imprts; + } else if (!exists()) { + throw newNotPresentException(); + } else { + return new IImportDeclaration[0]; + } + + } + + /** + * @see net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit#getMainTypeName() + */ + public char[] getMainTypeName() { + String name = getElementName(); + // remove the .java + name = name.substring(0, name.length() - 5); + return name.toCharArray(); + } + + /** + * @see IWorkingCopy#getOriginal(IJavaElement) + * @deprecated + */ + public IJavaElement getOriginal(IJavaElement workingCopyElement) { + // backward compatibility + if (!isWorkingCopy()) + return null; + CompilationUnit cu = (CompilationUnit) workingCopyElement + .getAncestor(COMPILATION_UNIT); + if (cu == null || !this.owner.equals(cu.owner)) { + return null; + } + + return workingCopyElement.getPrimaryElement(); + } + + /** + * @see IWorkingCopy#getOriginalElement() + * @deprecated + */ + public IJavaElement getOriginalElement() { + // backward compatibility + if (!isWorkingCopy()) + return null; + + return getPrimaryElement(); + } + + /* + * @see ICompilationUnit#getOwner() + */ + public WorkingCopyOwner getOwner() { + return isPrimary() || !isWorkingCopy() ? null : this.owner; + } + + /** + * @see ICompilationUnit#getPackageDeclaration(String) + */ + public IPackageDeclaration getPackageDeclaration(String name) { + return new PackageDeclaration(this, name); + } + + /** + * @see ICompilationUnit#getPackageDeclarations() + */ + public IPackageDeclaration[] getPackageDeclarations() + throws JavaModelException { + ArrayList list = getChildrenOfType(PACKAGE_DECLARATION); + IPackageDeclaration[] array = new IPackageDeclaration[list.size()]; + list.toArray(array); + return array; + } + + /** + * @see net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit#getPackageName() + */ + public char[][] getPackageName() { + return null; + } + + /** + * @see IJavaElement#getPath() + */ + public IPath getPath() { + PackageFragmentRoot root = this.getPackageFragmentRoot(); + if (root.isArchive()) { + return root.getPath(); + } else { + return this.getParent().getPath().append(this.getElementName()); + } + } + + /* + * Returns the per working copy info for the receiver, or null if none + * exist. Note: the use count of the per working copy info is NOT + * incremented. + */ + public JavaModelManager.PerWorkingCopyInfo getPerWorkingCopyInfo() { + return JavaModelManager.getJavaModelManager().getPerWorkingCopyInfo( + this, false/* don't create */, false/* don't record usage */, + null/* no problem requestor needed */); + } + + /* + * @see ICompilationUnit#getPrimary() + */ + public ICompilationUnit getPrimary() { + return (ICompilationUnit) getPrimaryElement(true); + } + + /* + * @see JavaElement#getPrimaryElement(boolean) + */ + public IJavaElement getPrimaryElement(boolean checkOwner) { + if (checkOwner && isPrimary()) + return this; + return new CompilationUnit((PackageFragment) getParent(), + getElementName(), DefaultWorkingCopyOwner.PRIMARY); + } + + /** + * @see IJavaElement#getResource() + */ + public IResource getResource() { + PackageFragmentRoot root = this.getPackageFragmentRoot(); + if (root.isArchive()) { + return root.getResource(); + } else { + return ((IContainer) this.getParent().getResource()) + .getFile(new Path(this.getElementName())); + } + } + + /** + * @see ISourceReference#getSource() + */ + public String getSource() throws JavaModelException { + IBuffer buffer = getBuffer(); + if (buffer == null) + return ""; //$NON-NLS-1$ + return buffer.getContents(); + } + + /** + * @see ISourceReference#getSourceRange() + */ + public ISourceRange getSourceRange() throws JavaModelException { + return ((CompilationUnitElementInfo) getElementInfo()).getSourceRange(); + } + + /** + * @see ICompilationUnit#getType(String) + */ + public IType getType(String name) { + return new SourceType(this, name); + } + + /** + * @see ICompilationUnit#getTypes() + */ + public IType[] getTypes() throws JavaModelException { + ArrayList list = getChildrenOfType(TYPE); + IType[] array = new IType[list.size()]; + list.toArray(array); + return array; + } + + /** + * @see IJavaElement + */ + public IResource getUnderlyingResource() throws JavaModelException { + if (isWorkingCopy() && !isPrimary()) + return null; + return super.getUnderlyingResource(); + } + + // /** + // * @see IWorkingCopy#getSharedWorkingCopy(IProgressMonitor, + // IBufferFactory, IProblemRequestor) + // */ + // public IJavaElement getSharedWorkingCopy(IProgressMonitor pm, + // IBufferFactory factory, IProblemRequestor problemRequestor) + // throws JavaModelException { + // + // // if factory is null, default factory must be used + // if (factory == null) factory = + // this.getBufferManager().getDefaultBufferFactory(); + // + // JavaModelManager manager = JavaModelManager.getJavaModelManager(); + // + // // In order to be shared, working copies have to denote the same + // compilation unit + // // AND use the same buffer factory. + // // Assuming there is a little set of buffer factories, then use a 2 level + // Map cache. + // Map sharedWorkingCopies = manager.sharedWorkingCopies; + // + // Map perFactoryWorkingCopies = (Map) sharedWorkingCopies.get(factory); + // if (perFactoryWorkingCopies == null){ + // perFactoryWorkingCopies = new HashMap(); + // sharedWorkingCopies.put(factory, perFactoryWorkingCopies); + // } + // WorkingCopy workingCopy = (WorkingCopy)perFactoryWorkingCopies.get(this); + // if (workingCopy != null) { + // workingCopy.useCount++; + // + // if (SHARED_WC_VERBOSE) { + // System.out.println("Incrementing use count of shared working copy " + + // workingCopy.toStringWithAncestors()); //$NON-NLS-1$ + // } + // + // return workingCopy; + // } else { + // CreateWorkingCopyOperation op = new CreateWorkingCopyOperation(this, + // perFactoryWorkingCopies, factory, problemRequestor); + // runOperation(op, pm); + // return op.getResultElements()[0]; + // } + // } + // /** + // * @see IWorkingCopy#getWorkingCopy() + // */ + // public IJavaElement getWorkingCopy() throws JavaModelException { + // return this.getWorkingCopy(null, null, null); + // } + // + // /** + // * @see IWorkingCopy#getWorkingCopy(IProgressMonitor, IBufferFactory, + // IProblemRequestor) + // */ + // public IJavaElement getWorkingCopy(IProgressMonitor pm, IBufferFactory + // factory, IProblemRequestor problemRequestor) throws + // JavaModelException { + // CreateWorkingCopyOperation op = new CreateWorkingCopyOperation(this, + // null, factory, problemRequestor); + // runOperation(op, pm); + // return op.getResultElements()[0]; + // } + /** + * @see IWorkingCopy#getSharedWorkingCopy(IProgressMonitor, IBufferFactory, + * IProblemRequestor) + * @deprecated + */ + public IJavaElement getSharedWorkingCopy(IProgressMonitor pm, + IBufferFactory factory, IProblemRequestor problemRequestor) + throws JavaModelException { + + // if factory is null, default factory must be used + if (factory == null) + factory = this.getBufferManager().getDefaultBufferFactory(); + + return getWorkingCopy(BufferFactoryWrapper.create(factory), + problemRequestor, pm); + } + + /** + * @see IWorkingCopy#getWorkingCopy() + * @deprecated + */ + public IJavaElement getWorkingCopy() throws JavaModelException { + return getWorkingCopy(null); + } + + /** + * @see ICompilationUnit#getWorkingCopy(IProgressMonitor) + */ + public ICompilationUnit getWorkingCopy(IProgressMonitor monitor) + throws JavaModelException { + return getWorkingCopy(new WorkingCopyOwner() {/* + * non shared working + * copy + */ + }, null/* no problem requestor */, monitor); + } + + /** + * @see IWorkingCopy#getWorkingCopy(IProgressMonitor, IBufferFactory, + * IProblemRequestor) + * @deprecated + */ + public IJavaElement getWorkingCopy(IProgressMonitor monitor, + IBufferFactory factory, IProblemRequestor problemRequestor) + throws JavaModelException { + return getWorkingCopy(BufferFactoryWrapper.create(factory), + problemRequestor, monitor); + } + + /** + * @see ICompilationUnit#getWorkingCopy(WorkingCopyOwner, IProblemRequestor, + * IProgressMonitor) + */ + public ICompilationUnit getWorkingCopy(WorkingCopyOwner workingCopyOwner, + IProblemRequestor problemRequestor, IProgressMonitor monitor) + throws JavaModelException { + if (!isPrimary()) + return this; + + JavaModelManager manager = JavaModelManager.getJavaModelManager(); + + CompilationUnit workingCopy = new CompilationUnit( + (PackageFragment) getParent(), getElementName(), + workingCopyOwner); + JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = manager + .getPerWorkingCopyInfo(workingCopy, false/* don't create */, + true/* record usage */, null/* + * not used since don't + * create + */); + if (perWorkingCopyInfo != null) { + return perWorkingCopyInfo.getWorkingCopy(); // return existing + // handle instead of the + // one created above + } + BecomeWorkingCopyOperation op = new BecomeWorkingCopyOperation( + workingCopy, problemRequestor); + op.runOperation(monitor); + return workingCopy; + } + + /** + * If I am not open, return true to avoid parsing. + * + * @see IParent#hasChildren() + */ + public boolean hasChildren() throws JavaModelException { + // if (isOpen()) { + // return getChildren().length > 0; + // } else { + // return true; + // } + return false; + } + + /** + * @see Openable#hasBuffer() + */ + protected boolean hasBuffer() { + return true; + } + + /* + * @see ICompilationUnit#hasResourceChanged() + */ + public boolean hasResourceChanged() { + if (!isWorkingCopy()) + return false; + + // if resource got deleted, then #getModificationStamp() will answer + // IResource.NULL_STAMP, which is always different from the + // cached + // timestamp + Object info = JavaModelManager.getJavaModelManager().getInfo(this); + if (info == null) + return false; + return ((CompilationUnitElementInfo) info).timestamp != getResource() + .getModificationStamp(); + } + + /** + * @see IWorkingCopy#isBasedOn(IResource) + * @deprecated + */ + public boolean isBasedOn(IResource resource) { + if (!isWorkingCopy()) + return false; + if (!getResource().equals(resource)) + return false; + return !hasResourceChanged(); + } + + /** + * @see IOpenable#isConsistent() + */ + public boolean isConsistent() { + return JavaModelManager.getJavaModelManager() + .getElementsOutOfSynchWithBuffers().get(this) == null; + } + + /** + * + * @see IOpenable + */ + public boolean isOpen() { + Object info = JavaModelManager.getJavaModelManager().getInfo(this); + return info != null && ((CompilationUnitElementInfo) info).isOpen(); + } + + public boolean isPrimary() { + return this.owner == DefaultWorkingCopyOwner.PRIMARY; + } + + /** + * @see Openable#isSourceElement() + */ + protected boolean isSourceElement() { + return true; + } + + protected boolean isValidCompilationUnit() { + IPackageFragmentRoot root = getPackageFragmentRoot(); + try { + if (root.getKind() != IPackageFragmentRoot.K_SOURCE) + return false; + } catch (JavaModelException e) { + return false; + } + // IResource resource = getResource(); + // if (resource != null) { + // char[][] inclusionPatterns = + // ((PackageFragmentRoot)root).fullInclusionPatternChars(); + // char[][] exclusionPatterns = + // ((PackageFragmentRoot)root).fullExclusionPatternChars(); + // if (ProjectPrefUtil.isExcluded(resource, inclusionPatterns, + // exclusionPatterns)) return false; + // } + if (!Util.isValidCompilationUnitName(getElementName())) + return false; + return true; + } + + /* + * @see ICompilationUnit#isWorkingCopy() + */ + public boolean isWorkingCopy() { + // For backward compatibility, non primary working copies are always + // returning true; in removal + // delta, clients can still check that element was a working copy before + // being discarded. + return !isPrimary() || getPerWorkingCopyInfo() != null; + } + + /** + * @see IOpenable#makeConsistent(IProgressMonitor) + */ + public void makeConsistent(IProgressMonitor monitor) + throws JavaModelException { + makeConsistent(false/* don't create AST */, 0, monitor); + } + + public Object makeConsistent(boolean createAST, int astLevel, + IProgressMonitor monitor) throws JavaModelException { + if (isConsistent()) + return null; + + // create a new info and make it the current info + // (this will remove the info and its children just before storing the + // new infos) + // if (createAST) { + // ASTHolderCUInfo info = new ASTHolderCUInfo(); + // info.astLevel = astLevel; + // openWhenClosed(info, monitor); + // net.sourceforge.phpdt.core.dom.CompilationUnit result = info.ast; + // info.ast = null; + // return result; + // } else { + openWhenClosed(createElementInfo(), monitor); + return null; + // } + } + + // public net.sourceforge.phpdt.core.dom.CompilationUnit + // makeConsistent(boolean createAST, int astLevel, IProgressMonitor monitor) + // throws JavaModelException { + // if (isConsistent()) return null; + // + // // create a new info and make it the current info + // // (this will remove the info and its children just before storing the + // new infos) + // if (createAST) { + // ASTHolderCUInfo info = new ASTHolderCUInfo(); + // info.astLevel = astLevel; + // openWhenClosed(info, monitor); + // net.sourceforge.phpdt.core.dom.CompilationUnit result = info.ast; + // info.ast = null; + // return result; + // } else { + // openWhenClosed(createElementInfo(), monitor); + // return null; + // } + // } + + /** + * @see ISourceManipulation#move(IJavaElement, IJavaElement, String, + * boolean, IProgressMonitor) + */ + public void move(IJavaElement container, IJavaElement sibling, + String rename, boolean force, IProgressMonitor monitor) + throws JavaModelException { + if (container == null) { + throw new IllegalArgumentException(Util + .bind("operation.nullContainer")); //$NON-NLS-1$ + } + IJavaElement[] elements = new IJavaElement[] { this }; + IJavaElement[] containers = new IJavaElement[] { container }; + + String[] renamings = null; + if (rename != null) { + renamings = new String[] { rename }; + } + getJavaModel().move(elements, containers, null, renamings, force, + monitor); + } + + // /** + // * @see Openable#openBuffer(IProgressMonitor) + // */ + // protected IBuffer openBuffer(IProgressMonitor pm) throws + // JavaModelException { + // + // // create buffer - compilation units only use default buffer factory + // BufferManager bufManager = getBufferManager(); + // IBuffer buffer = getBufferFactory().createBuffer(this); + // if (buffer == null) return null; + // + // // set the buffer source + // if (buffer.getCharacters() == null){ + // IFile file = (IFile)this.getResource(); + // if (file == null || !file.exists()) throw newNotPresentException(); + // buffer.setContents(ProjectPrefUtil.getResourceContentsAsCharArray(file)); + // } + // + // // add buffer to buffer cache + // bufManager.addBuffer(buffer); + // + // // listen to buffer changes + // buffer.addBufferChangedListener(this); + // + // return buffer; + // } + /** + * @see Openable#openBuffer(IProgressMonitor, Object) + */ + protected IBuffer openBuffer(IProgressMonitor pm, Object info) + throws JavaModelException { + + // create buffer + boolean isWorkingCopy = isWorkingCopy(); + IBuffer buffer = isWorkingCopy ? this.owner.createBuffer(this) + : BufferManager.getDefaultBufferManager().createBuffer(this); + if (buffer == null) + return null; + + // set the buffer source + if (buffer.getCharacters() == null) { + if (isWorkingCopy) { + ICompilationUnit original; + if (!isPrimary() + && (original = new CompilationUnit( + (PackageFragment) getParent(), + getElementName(), + DefaultWorkingCopyOwner.PRIMARY)).isOpen()) { + buffer.setContents(original.getSource()); + } else { + IFile file = (IFile) getResource(); + if (file == null || !file.exists()) { + // initialize buffer with empty contents + buffer.setContents(CharOperation.NO_CHAR); + } else { + buffer.setContents(Util + .getResourceContentsAsCharArray(file)); + } + } + } else { + IFile file = (IFile) this.getResource(); + if (file == null || !file.exists()) + throw newNotPresentException(); + buffer.setContents(Util.getResourceContentsAsCharArray(file)); + } + } + + // add buffer to buffer cache + BufferManager bufManager = getBufferManager(); + bufManager.addBuffer(buffer); + + // listen to buffer changes + buffer.addBufferChangedListener(this); + + return buffer; + } + + /* + * @see Openable#openParent + */ + protected void openParent(Object childInfo, HashMap newElements, + IProgressMonitor pm) throws JavaModelException { + try { + super.openParent(childInfo, newElements, pm); + } catch (JavaModelException e) { + // allow parent to not exist for working copies defined outside + // classpath + if (!isWorkingCopy() && !e.isDoesNotExist()) { + throw e; + } + } + } + + /** + * @see ICompilationUnit#reconcile() + * @deprecated + */ + public IMarker[] reconcile() throws JavaModelException { + reconcile(NO_AST, false/* don't force problem detection */, + null/* use primary owner */, null/* no progress monitor */); + return null; + } + + /** + * @see ICompilationUnit#reconcile(int, boolean, WorkingCopyOwner, + * IProgressMonitor) + */ + public void reconcile(boolean forceProblemDetection, + IProgressMonitor monitor) throws JavaModelException { + reconcile(NO_AST, forceProblemDetection, null/* use primary owner */, + monitor); + } + + /** + * @see ICompilationUnit#reconcile(int, boolean, WorkingCopyOwner, + * IProgressMonitor) + * @since 3.0 + */ + // public net.sourceforge.phpdt.core.dom.CompilationUnit reconcile( + public Object reconcile(int astLevel, boolean forceProblemDetection, + WorkingCopyOwner workingCopyOwner, IProgressMonitor monitor) + throws JavaModelException { + + if (!isWorkingCopy()) + return null; // Reconciling is not supported on non working + // copies + if (workingCopyOwner == null) + workingCopyOwner = DefaultWorkingCopyOwner.PRIMARY; + + boolean createAST = false; + // if (astLevel == AST.JLS2) { + // // client asking for level 2 AST; these are supported + // createAST = true; + // } else if (astLevel == AST.JLS3) { + // // client asking for level 3 ASTs; these are not supported + // // TODO (jerome) - these should also be supported in 1.5 stream + // createAST = false; + // } else { + // // client asking for no AST (0) or unknown ast level + // // either way, request denied + // createAST = false; + // } + ReconcileWorkingCopyOperation op = new ReconcileWorkingCopyOperation( + this, createAST, astLevel, forceProblemDetection, + workingCopyOwner); + op.runOperation(monitor); + // return op.ast; + return null; + } + + /** + * @see ISourceManipulation#rename(String, boolean, IProgressMonitor) + */ + public void rename(String name, boolean force, IProgressMonitor monitor) + throws JavaModelException { + if (name == null) { + throw new IllegalArgumentException(Util.bind("operation.nullName")); //$NON-NLS-1$ + } + IJavaElement[] elements = new IJavaElement[] { this }; + IJavaElement[] dests = new IJavaElement[] { this.getParent() }; + String[] renamings = new String[] { name }; + getJavaModel().rename(elements, dests, renamings, force, monitor); + } + + /* + * @see ICompilationUnit + */ + public void restore() throws JavaModelException { + + if (!isWorkingCopy()) + return; + + CompilationUnit original = (CompilationUnit) getOriginalElement(); + IBuffer buffer = this.getBuffer(); + if (buffer == null) + return; + buffer.setContents(original.getContents()); + updateTimeStamp(original); + makeConsistent(null); + } + + // /** + // * @see ICodeAssist#codeComplete(int, ICodeCompletionRequestor) + // * @deprecated - use codeComplete(int, ICompletionRequestor) + // */ + // public void codeComplete(int offset, final ICodeCompletionRequestor + // requestor) throws JavaModelException { + // + // if (requestor == null){ + // codeComplete(offset, (ICompletionRequestor)null); + // return; + // } + // codeComplete( + // offset, + // new ICompletionRequestor(){ + // public void acceptAnonymousType(char[] superTypePackageName,char[] + // superTypeName,char[][] parameterPackageNames,char[][] + // parameterTypeNames,char[][] parameterNames,char[] completionName,int + // modifiers,int completionStart,int completionEnd, int + // relevance){ + // } + // public void acceptClass(char[] packageName, char[] className, char[] + // completionName, int modifiers, int completionStart, int + // completionEnd, int relevance) { + // requestor.acceptClass(packageName, className, completionName, modifiers, + // completionStart, completionEnd); + // } + // public void acceptError(IProblem error) { + // if (true) return; // was disabled in 1.0 + // + // try { + // IMarker marker = + // ResourcesPlugin.getWorkspace().getRoot().createMarker(IJavaModelMarker.TRANSIENT_PROBLEM); + // marker.setAttribute(IJavaModelMarker.ID, error.getID()); + // marker.setAttribute(IMarker.CHAR_START, error.getSourceStart()); + // marker.setAttribute(IMarker.CHAR_END, error.getSourceEnd() + 1); + // marker.setAttribute(IMarker.LINE_NUMBER, error.getSourceLineNumber()); + // marker.setAttribute(IMarker.MESSAGE, error.getMessage()); + // marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); + // requestor.acceptError(marker); + // } catch(CoreException e){ + // } + // } + // public void acceptField(char[] declaringTypePackageName, char[] + // declaringTypeName, char[] name, char[] typePackageName, char[] + // typeName, char[] completionName, int modifiers, int completionStart, int + // completionEnd, int relevance) { + // requestor.acceptField(declaringTypePackageName, declaringTypeName, name, + // typePackageName, typeName, completionName, modifiers, + // completionStart, completionEnd); + // } + // public void acceptInterface(char[] packageName,char[] + // interfaceName,char[] completionName,int modifiers,int completionStart,int + // completionEnd, int relevance) { + // requestor.acceptInterface(packageName, interfaceName, completionName, + // modifiers, completionStart, completionEnd); + // } + // public void acceptKeyword(char[] keywordName,int completionStart,int + // completionEnd, int relevance){ + // requestor.acceptKeyword(keywordName, completionStart, completionEnd); + // } + // public void acceptLabel(char[] labelName,int completionStart,int + // completionEnd, int relevance){ + // requestor.acceptLabel(labelName, completionStart, completionEnd); + // } + // public void acceptLocalVariable(char[] name,char[] typePackageName,char[] + // typeName,int modifiers,int completionStart,int + // completionEnd, int relevance){ + // // ignore + // } + // public void acceptMethod(char[] declaringTypePackageName,char[] + // declaringTypeName,char[] selector,char[][] + // parameterPackageNames,char[][] parameterTypeNames,char[][] + // parameterNames,char[] returnTypePackageName,char[] + // returnTypeName,char[] completionName,int modifiers,int + // completionStart,int completionEnd, int relevance){ + // // skip parameter names + // requestor.acceptMethod(declaringTypePackageName, declaringTypeName, + // selector, parameterPackageNames, parameterTypeNames, + // returnTypePackageName, returnTypeName, completionName, modifiers, + // completionStart, completionEnd); + // } + // public void acceptMethodDeclaration(char[] + // declaringTypePackageName,char[] declaringTypeName,char[] + // selector,char[][] + // parameterPackageNames,char[][] parameterTypeNames,char[][] + // parameterNames,char[] returnTypePackageName,char[] + // returnTypeName,char[] completionName,int modifiers,int + // completionStart,int completionEnd, int relevance){ + // // ignore + // } + // public void acceptModifier(char[] modifierName,int completionStart,int + // completionEnd, int relevance){ + // requestor.acceptModifier(modifierName, completionStart, completionEnd); + // } + // public void acceptPackage(char[] packageName,char[] completionName,int + // completionStart,int completionEnd, int relevance){ + // requestor.acceptPackage(packageName, completionName, completionStart, + // completionEnd); + // } + // public void acceptType(char[] packageName,char[] typeName,char[] + // completionName,int completionStart,int completionEnd, int + // relevance){ + // requestor.acceptType(packageName, typeName, completionName, + // completionStart, completionEnd); + // } + // public void acceptVariableName(char[] typePackageName,char[] + // typeName,char[] name,char[] completionName,int completionStart,int + // completionEnd, int relevance){ + // // ignore + // } + // }); + // } + // /** + // * @see JavaElement#rootedAt(IJavaProject) + // */ + // public IJavaElement rootedAt(IJavaProject project) { + // return + // new CompilationUnit( + // (IPackageFragment)((JavaElement)parent).rootedAt(project), + // name); + // } + + /* + * Assume that this is a working copy + */ + protected void updateTimeStamp(CompilationUnit original) + throws JavaModelException { + long timeStamp = ((IFile) original.getResource()) + .getModificationStamp(); + if (timeStamp == IResource.NULL_STAMP) { + throw new JavaModelException(new JavaModelStatus( + IJavaModelStatusConstants.INVALID_RESOURCE)); + } + ((CompilationUnitElementInfo) getElementInfo()).timestamp = timeStamp; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CompilationUnitElementInfo.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CompilationUnitElementInfo.java index a25c0e3..3ec282a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CompilationUnitElementInfo.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CompilationUnitElementInfo.java @@ -12,35 +12,38 @@ package net.sourceforge.phpdt.internal.core; import net.sourceforge.phpdt.core.ISourceRange; - -/* package */ class CompilationUnitElementInfo extends OpenableElementInfo { +/* package */class CompilationUnitElementInfo extends OpenableElementInfo { /** * The length of this compilation unit's source code String */ protected int sourceLength; - - /** - * Timestamp of original resource at the time this element - * was opened or last updated. + + /** + * Timestamp of original resource at the time this element was opened or + * last updated. */ protected long timestamp; -/** - * Returns the length of the source string. - */ -public int getSourceLength() { - return sourceLength; -} -protected ISourceRange getSourceRange() { - return new SourceRange(0, sourceLength); -} -protected boolean isOpen() { - return true; -} -/** - * Sets the length of the source string. - */ -public void setSourceLength(int newSourceLength) { - sourceLength = newSourceLength; -} + + /** + * Returns the length of the source string. + */ + public int getSourceLength() { + return sourceLength; + } + + protected ISourceRange getSourceRange() { + return new SourceRange(0, sourceLength); + } + + protected boolean isOpen() { + return true; + } + + /** + * Sets the length of the source string. + */ + public void setSourceLength(int newSourceLength) { + sourceLength = newSourceLength; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CompilationUnitProblemFinder.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CompilationUnitProblemFinder.java index 243ddc2..a2a534e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CompilationUnitProblemFinder.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CompilationUnitProblemFinder.java @@ -49,46 +49,53 @@ import org.eclipse.core.runtime.IProgressMonitor; public class CompilationUnitProblemFinder extends Compiler { /** - * Answer a new CompilationUnitVisitor using the given name environment and compiler options. - * The environment and options will be in effect for the lifetime of the compiler. - * When the compiler is run, compilation results are sent to the given requestor. - * - * @param environment org.eclipse.jdt.internal.compiler.api.env.INameEnvironment - * Environment used by the compiler in order to resolve type and package - * names. The name environment implements the actual connection of the compiler - * to the outside world (e.g. in batch mode the name environment is performing - * pure file accesses, reuse previous build state or connection to repositories). - * Note: the name environment is responsible for implementing the actual classpath - * rules. - * - * @param policy org.eclipse.jdt.internal.compiler.api.problem.IErrorHandlingPolicy - * Configurable part for problem handling, allowing the compiler client to - * specify the rules for handling problems (stop on first error or accumulate - * them all) and at the same time perform some actions such as opening a dialog - * in UI when compiling interactively. - * @see org.eclipse.jdt.internal.compiler.api.problem.DefaultErrorHandlingPolicies + * Answer a new CompilationUnitVisitor using the given name environment and + * compiler options. The environment and options will be in effect for the + * lifetime of the compiler. When the compiler is run, compilation results + * are sent to the given requestor. * - * @param settings The settings to use for the resolution. - * - * @param requestor org.eclipse.jdt.internal.compiler.api.ICompilerRequestor - * Component which will receive and persist all compilation results and is intended - * to consume them as they are produced. Typically, in a batch compiler, it is - * responsible for writing out the actual .class files to the file system. - * @see org.eclipse.jdt.internal.compiler.api.CompilationResult - * - * @param problemFactory org.eclipse.jdt.internal.compiler.api.problem.IProblemFactory - * Factory used inside the compiler to create problem descriptors. It allows the - * compiler client to supply its own representation of compilation problems in - * order to avoid object conversions. Note that the factory is not supposed - * to accumulate the created problems, the compiler will gather them all and hand - * them back as part of the compilation unit result. + * @param environment + * org.eclipse.jdt.internal.compiler.api.env.INameEnvironment + * Environment used by the compiler in order to resolve type and + * package names. The name environment implements the actual + * connection of the compiler to the outside world (e.g. in batch + * mode the name environment is performing pure file accesses, + * reuse previous build state or connection to repositories). + * Note: the name environment is responsible for implementing the + * actual classpath rules. + * + * @param policy + * org.eclipse.jdt.internal.compiler.api.problem.IErrorHandlingPolicy + * Configurable part for problem handling, allowing the compiler + * client to specify the rules for handling problems (stop on + * first error or accumulate them all) and at the same time + * perform some actions such as opening a dialog in UI when + * compiling interactively. + * @see org.eclipse.jdt.internal.compiler.api.problem.DefaultErrorHandlingPolicies + * + * @param settings + * The settings to use for the resolution. + * + * @param requestor + * org.eclipse.jdt.internal.compiler.api.ICompilerRequestor + * Component which will receive and persist all compilation + * results and is intended to consume them as they are produced. + * Typically, in a batch compiler, it is responsible for writing + * out the actual .class files to the file system. + * @see org.eclipse.jdt.internal.compiler.api.CompilationResult + * + * @param problemFactory + * org.eclipse.jdt.internal.compiler.api.problem.IProblemFactory + * Factory used inside the compiler to create problem + * descriptors. It allows the compiler client to supply its own + * representation of compilation problems in order to avoid + * object conversions. Note that the factory is not supposed to + * accumulate the created problems, the compiler will gather them + * all and hand them back as part of the compilation unit result. */ - protected CompilationUnitProblemFinder( - INameEnvironment environment, - IErrorHandlingPolicy policy, - Map settings, - ICompilerRequestor requestor, - IProblemFactory problemFactory) { + protected CompilationUnitProblemFinder(INameEnvironment environment, + IErrorHandlingPolicy policy, Map settings, + ICompilerRequestor requestor, IProblemFactory problemFactory) { super(environment, policy, settings, requestor, problemFactory, true); } @@ -97,22 +104,22 @@ public class CompilationUnitProblemFinder extends Compiler { * Add additional source types */ public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding) { - // ensure to jump back to toplevel type for first one (could be a member) -// while (sourceTypes[0].getEnclosingType() != null) -// sourceTypes[0] = sourceTypes[0].getEnclosingType(); + // ensure to jump back to toplevel type for first one (could be a + // member) + // while (sourceTypes[0].getEnclosingType() != null) + // sourceTypes[0] = sourceTypes[0].getEnclosingType(); - CompilationResult result = - new CompilationResult(sourceTypes[0].getFileName(), 1, 1, 10); //this.options.maxProblemsPerUnit); + CompilationResult result = new CompilationResult(sourceTypes[0] + .getFileName(), 1, 1, 10); // this.options.maxProblemsPerUnit); // need to hold onto this - CompilationUnitDeclaration unit = - SourceTypeConverter.buildCompilationUnit( - sourceTypes,//sourceTypes[0] is always toplevel here - true, // need field and methods - true, // need member types - true, // need field initialization - lookupEnvironment.problemReporter, - result); + CompilationUnitDeclaration unit = SourceTypeConverter + .buildCompilationUnit(sourceTypes,// sourceTypes[0] is always + // toplevel here + true, // need field and methods + true, // need member types + true, // need field initialization + lookupEnvironment.problemReporter, result); if (unit != null) { this.lookupEnvironment.buildTypeBindings(unit); @@ -121,20 +128,21 @@ public class CompilationUnitProblemFinder extends Compiler { } /* - * Low-level API performing the actual compilation + * Low-level API performing the actual compilation */ protected static IErrorHandlingPolicy getHandlingPolicy() { return DefaultErrorHandlingPolicies.proceedWithAllProblems(); } - protected static INameEnvironment getNameEnvironment(ICompilationUnit sourceUnit) - throws JavaModelException { - return (SearchableEnvironment) ((JavaProject) sourceUnit.getJavaProject()) - .getSearchableNameEnvironment(); - } + protected static INameEnvironment getNameEnvironment( + ICompilationUnit sourceUnit) throws JavaModelException { + return (SearchableEnvironment) ((JavaProject) sourceUnit + .getJavaProject()).getSearchableNameEnvironment(); + } /* - * Answer the component to which will be handed back compilation results from the compiler + * Answer the component to which will be handed back compilation results + * from the compiler */ protected static ICompilerRequestor getRequestor() { return new ICompilerRequestor() { @@ -143,44 +151,32 @@ public class CompilationUnitProblemFinder extends Compiler { }; } - protected static IProblemFactory getProblemFactory( - final char[] fileName, - final IProblemRequestor problemRequestor, - final IProgressMonitor monitor) { + protected static IProblemFactory getProblemFactory(final char[] fileName, + final IProblemRequestor problemRequestor, + final IProgressMonitor monitor) { return new DefaultProblemFactory(Locale.getDefault()) { - public IProblem createProblem( - char[] originatingFileName, - int problemId, - String[] problemArguments, - String[] messageArguments, - int severity, - int startPosition, - int endPosition, - int lineNumber) { - - if (monitor != null && monitor.isCanceled()){ + public IProblem createProblem(char[] originatingFileName, + int problemId, String[] problemArguments, + String[] messageArguments, int severity, int startPosition, + int endPosition, int lineNumber) { + + if (monitor != null && monitor.isCanceled()) { throw new AbortCompilation(true, null); // silent abort } - - IProblem problem = - super.createProblem( - originatingFileName, - problemId, - problemArguments, - messageArguments, - severity, - startPosition, - endPosition, - lineNumber); + + IProblem problem = super.createProblem(originatingFileName, + problemId, problemArguments, messageArguments, + severity, startPosition, endPosition, lineNumber); // only report local problems - if (CharOperation.equals(originatingFileName, fileName)){ - if (JavaModelManager.VERBOSE){ - System.out.println("PROBLEM FOUND while reconciling : "+problem.getMessage());//$NON-NLS-1$ + if (CharOperation.equals(originatingFileName, fileName)) { + if (JavaModelManager.VERBOSE) { + System.out + .println("PROBLEM FOUND while reconciling : " + problem.getMessage());//$NON-NLS-1$ } problemRequestor.acceptProblem(problem); } - if (monitor != null && monitor.isCanceled()){ + if (monitor != null && monitor.isCanceled()) { throw new AbortCompilation(true, null); // silent abort } @@ -190,134 +186,124 @@ public class CompilationUnitProblemFinder extends Compiler { } public static CompilationUnitDeclaration process( - CompilationUnitDeclaration unit, - ICompilationUnit unitElement, - char[] contents, - UnitParser parser, + CompilationUnitDeclaration unit, ICompilationUnit unitElement, + char[] contents, UnitParser parser, WorkingCopyOwner workingCopyOwner, - IProblemRequestor problemRequestor, - IProblemFactory problemFactory, - boolean cleanupCU, - IProgressMonitor monitor) + IProblemRequestor problemRequestor, IProblemFactory problemFactory, + boolean cleanupCU, IProgressMonitor monitor) throws JavaModelException { - char[] fileName = unitElement.getElementName().toCharArray(); - - JavaProject project = (JavaProject) unitElement.getJavaProject(); - CompilationUnitProblemFinder problemFinder = - new CompilationUnitProblemFinder( - project.newSearchableNameEnvironment(workingCopyOwner), - getHandlingPolicy(), - project.getOptions(true), - getRequestor(), - problemFactory); - if (parser != null) { - problemFinder.parser = parser; - } + char[] fileName = unitElement.getElementName().toCharArray(); - try { - - IPackageFragment packageFragment = (IPackageFragment)unitElement.getAncestor(IJavaElement.PACKAGE_FRAGMENT); - char[][] expectedPackageName = null; - if (packageFragment != null){ - expectedPackageName = CharOperation.splitOn('.', packageFragment.getElementName().toCharArray()); - } - if (unit == null) { - unit = problemFinder.resolve( - new BasicCompilationUnit( - contents, - expectedPackageName, - new String(fileName), - unitElement), - true, // verify methods - true); //, // analyze code - //true); // generate code - } else { - problemFinder.resolve( - unit, - null, // no need for source + JavaProject project = (JavaProject) unitElement.getJavaProject(); + CompilationUnitProblemFinder problemFinder = new CompilationUnitProblemFinder( + project.newSearchableNameEnvironment(workingCopyOwner), + getHandlingPolicy(), project.getOptions(true), getRequestor(), + problemFactory); + if (parser != null) { + problemFinder.parser = parser; + } + + try { + + IPackageFragment packageFragment = (IPackageFragment) unitElement + .getAncestor(IJavaElement.PACKAGE_FRAGMENT); + char[][] expectedPackageName = null; + if (packageFragment != null) { + expectedPackageName = CharOperation.splitOn('.', + packageFragment.getElementName().toCharArray()); + } + if (unit == null) { + unit = problemFinder.resolve( + new BasicCompilationUnit(contents, expectedPackageName, + new String(fileName), unitElement), true, // verify + // methods + true); // , // analyze code + // true); // generate code + } else { + problemFinder.resolve(unit, null, // no need for source true, // verify methods - true); //, // analyze code - // true); // generate code - } - reportProblems(unit, problemRequestor, monitor); - return unit; - } catch(RuntimeException e) { - // avoid breaking other tools due to internal compiler failure (40334) - Util.log(e, "Exception occurred during problem detection: "); //$NON-NLS-1$ - throw new JavaModelException(e, IJavaModelStatusConstants.COMPILER_FAILURE); - } finally { - if (cleanupCU && unit != null) { - unit.cleanUp(); - } - problemFinder.lookupEnvironment.reset(); + true); // , // analyze code + // true); // generate code + } + reportProblems(unit, problemRequestor, monitor); + return unit; + } catch (RuntimeException e) { + // avoid breaking other tools due to internal compiler failure + // (40334) + Util.log(e, "Exception occurred during problem detection: "); //$NON-NLS-1$ + throw new JavaModelException(e, + IJavaModelStatusConstants.COMPILER_FAILURE); + } finally { + if (cleanupCU && unit != null) { + unit.cleanUp(); } + problemFinder.lookupEnvironment.reset(); } + } + public static CompilationUnitDeclaration process( - ICompilationUnit unitElement, - char[] contents, + ICompilationUnit unitElement, char[] contents, WorkingCopyOwner workingCopyOwner, - IProblemRequestor problemRequestor, - boolean cleanupCU, - IProgressMonitor monitor) - throws JavaModelException { - - return process(null/*no CompilationUnitDeclaration*/, unitElement, contents, null/*use default Parser*/, workingCopyOwner, problemRequestor, new DefaultProblemFactory(), cleanupCU, monitor); - } + IProblemRequestor problemRequestor, boolean cleanupCU, + IProgressMonitor monitor) throws JavaModelException { + + return process(null/* no CompilationUnitDeclaration */, unitElement, + contents, null/* use default Parser */, workingCopyOwner, + problemRequestor, new DefaultProblemFactory(), cleanupCU, + monitor); + } + public static CompilationUnitDeclaration process( - ICompilationUnit unitElement, - IProblemRequestor problemRequestor, - IProgressMonitor monitor) - throws JavaModelException { + ICompilationUnit unitElement, IProblemRequestor problemRequestor, + IProgressMonitor monitor) throws JavaModelException { char[] fileName = unitElement.getElementName().toCharArray(); - + IJavaProject project = unitElement.getJavaProject(); - CompilationUnitProblemFinder problemFinder = - new CompilationUnitProblemFinder( - getNameEnvironment(unitElement), - getHandlingPolicy(), - project.getOptions(true), - getRequestor(), - getProblemFactory(fileName, problemRequestor, monitor)); + CompilationUnitProblemFinder problemFinder = new CompilationUnitProblemFinder( + getNameEnvironment(unitElement), getHandlingPolicy(), project + .getOptions(true), getRequestor(), getProblemFactory( + fileName, problemRequestor, monitor)); CompilationUnitDeclaration unit = null; try { String encoding = project.getOption(JavaCore.CORE_ENCODING, true); - - IPackageFragment packageFragment = (IPackageFragment)unitElement.getAncestor(IJavaElement.PACKAGE_FRAGMENT); + + IPackageFragment packageFragment = (IPackageFragment) unitElement + .getAncestor(IJavaElement.PACKAGE_FRAGMENT); char[][] expectedPackageName = null; - if (packageFragment != null){ - expectedPackageName = CharOperation.splitOn('.', packageFragment.getElementName().toCharArray()); + if (packageFragment != null) { + expectedPackageName = CharOperation.splitOn('.', + packageFragment.getElementName().toCharArray()); } - unit = problemFinder.resolve( - new BasicCompilationUnit( - unitElement.getSource().toCharArray(), - expectedPackageName, - new String(fileName), - encoding), - true, // verify methods + unit = problemFinder.resolve(new BasicCompilationUnit(unitElement + .getSource().toCharArray(), expectedPackageName, + new String(fileName), encoding), true, // verify methods true); // analyze code -// true); // generate code + // true); // generate code return unit; } finally { if (unit != null) { unit.cleanUp(); } - problemFinder.lookupEnvironment.reset(); + problemFinder.lookupEnvironment.reset(); } } - private static void reportProblems(CompilationUnitDeclaration unit, IProblemRequestor problemRequestor, IProgressMonitor monitor) { + + private static void reportProblems(CompilationUnitDeclaration unit, + IProblemRequestor problemRequestor, IProgressMonitor monitor) { CompilationResult unitResult = unit.compilationResult; IProblem[] problems = unitResult.getAllProblems(); for (int i = 0, problemLength = problems == null ? 0 : problems.length; i < problemLength; i++) { - if (JavaModelManager.VERBOSE){ - System.out.println("PROBLEM FOUND while reconciling : "+problems[i].getMessage());//$NON-NLS-1$ + if (JavaModelManager.VERBOSE) { + System.out + .println("PROBLEM FOUND while reconciling : " + problems[i].getMessage());//$NON-NLS-1$ } - if (monitor != null && monitor.isCanceled()) break; - - problemRequestor.acceptProblem(problems[i]); + if (monitor != null && monitor.isCanceled()) + break; + + problemRequestor.acceptProblem(problems[i]); } } -} - +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CompilationUnitStructureRequestor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CompilationUnitStructureRequestor.java index 162e83d..d828458 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CompilationUnitStructureRequestor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CompilationUnitStructureRequestor.java @@ -29,570 +29,563 @@ import net.sourceforge.phpdt.internal.core.util.ReferenceInfoAdapter; import net.sourceforge.phpdt.internal.corext.Assert; /** - * A requestor for the fuzzy parser, used to compute the children of an ICompilationUnit. + * A requestor for the fuzzy parser, used to compute the children of an + * ICompilationUnit. */ -public class CompilationUnitStructureRequestor extends ReferenceInfoAdapter implements ISourceElementRequestor { - - /** - * The handle to the compilation unit being parsed - */ - protected ICompilationUnit unit; - - /** - * The info object for the compilation unit being parsed - */ - protected CompilationUnitElementInfo unitInfo; - - /** - * The import container info - null until created - */ - protected JavaElementInfo importContainerInfo = null; - - /** - * Hashtable of children elements of the compilation unit. - * Children are added to the table as they are found by - * the parser. Keys are handles, values are corresponding - * info objects. - */ - protected Map newElements; - - /** - * Stack of parent scope info objects. The info on the - * top of the stack is the parent of the next element found. - * For example, when we locate a method, the parent info object - * will be the type the method is contained in. - */ - protected Stack infoStack; - - /** - * Stack of parent handles, corresponding to the info stack. We - * keep both, since info objects do not have back pointers to - * handles. - */ - protected Stack handleStack; - - /** - * The name of the source file being parsed. - */ - protected char[] fSourceFileName = null; - - /** - * The dot-separated name of the package the compilation unit - * is contained in - based on the package statement in the - * compilation unit, and initialized by #acceptPackage. - * Initialized to null for the default package. - */ - protected char[] fPackageName = null; - - /** - * The number of references reported thus far. Used to - * expand the arrays of reference kinds and names. - */ - protected int fRefCount = 0; - - /** - * The initial size of the reference kind and name - * arrays. If the arrays fill, they are doubled in - * size - */ - protected static int fgReferenceAllocation = 50; - - /** - * Problem requestor which will get notified of discovered problems - */ - protected boolean hasSyntaxErrors = false; - - /* - * The parser this requestor is using. - */ - // protected Parser parser; - protected Parser parser; - - /** - * Empty collections used for efficient initialization - */ - protected static String[] fgEmptyStringArray = new String[0]; - protected static byte[] fgEmptyByte = new byte[] { - }; - protected static char[][] fgEmptyCharChar = new char[][] { - }; - protected static char[] fgEmptyChar = new char[] { - }; - - protected HashtableOfObject fieldRefCache; - protected HashtableOfObject messageRefCache; - protected HashtableOfObject typeRefCache; - protected HashtableOfObject unknownRefCache; - - protected CompilationUnitStructureRequestor(ICompilationUnit unit, CompilationUnitElementInfo unitInfo, Map newElements) - throws JavaModelException { - this.unit = unit; - this.unitInfo = unitInfo; - this.newElements = newElements; - this.fSourceFileName = unit.getElementName().toCharArray(); - } - /** - * @see ISourceElementRequestor - */ - public void acceptImport(int declarationStart, int declarationEnd, char[] name, boolean onDemand) { - //, int modifiers) { - - JavaElementInfo parentInfo = (JavaElementInfo) this.infoStack.peek(); - JavaElement parentHandle= (JavaElement) this.handleStack.peek(); - if (!(parentHandle.getElementType() == IJavaElement.COMPILATION_UNIT)) { - Assert.isTrue(false); // Should not happen - } - - ICompilationUnit parentCU= (ICompilationUnit)parentHandle; - //create the import container and its info - ImportContainer importContainer= (ImportContainer)parentCU.getImportContainer(); - if (this.importContainerInfo == null) { - this.importContainerInfo= new JavaElementInfo(); - this.importContainerInfo.setIsStructureKnown(true); - parentInfo.addChild(importContainer); - this.newElements.put(importContainer, this.importContainerInfo); - } - - // tack on the '.*' if it is onDemand - String importName; - if (onDemand) { - importName= new String(name) + ".*"; //$NON-NLS-1$ - } else { - importName= new String(name); - } - - ImportDeclaration handle = new ImportDeclaration(importContainer, importName); - resolveDuplicates(handle); - - ImportDeclarationElementInfo info = new ImportDeclarationElementInfo(); - info.setSourceRangeStart(declarationStart); - info.setSourceRangeEnd(declarationEnd); -// info.setFlags(modifiers); - info.setName(name); // no trailing * if onDemand - info.setOnDemand(onDemand); - - this.importContainerInfo.addChild(handle); - this.newElements.put(handle, info); - } - /** - * @see ISourceElementRequestor - */ - - /* - * Table of line separator position. This table is passed once at the end - * of the parse action, so as to allow computation of normalized ranges. - * - * A line separator might corresponds to several characters in the source, - * - */ - public void acceptLineSeparatorPositions(int[] positions) { - } - /** - * @see ISourceElementRequestor - */ - //public void acceptPackage(int declarationStart, int declarationEnd, char[] name) { - // - // JavaElementInfo parentInfo = (JavaElementInfo) fInfoStack.peek(); - // JavaElement parentHandle= (JavaElement)fHandleStack.peek(); - // IPackageDeclaration handle = null; - // fPackageName= name; - // - // if (parentHandle.getElementType() == IJavaElement.COMPILATION_UNIT) { - // handle = new PackageDeclaration((ICompilationUnit) parentHandle, new String(name)); - // } - // else { - // Assert.isTrue(false); // Should not happen - // } - // resolveDuplicates(handle); - // - // SourceRefElementInfo info = new SourceRefElementInfo(); - // info.setSourceRangeStart(declarationStart); - // info.setSourceRangeEnd(declarationEnd); - // - // parentInfo.addChild(handle); - // fNewElements.put(handle, info); - // - //} - public void acceptProblem(IProblem problem) { - if ((problem.getID() & IProblem.Syntax) != 0) { - this.hasSyntaxErrors = true; - } - } - /** - * Convert these type names to signatures. - * @see Signature. - */ - /* default */ - static String[] convertTypeNamesToSigs(char[][] typeNames) { - if (typeNames == null) - return fgEmptyStringArray; - int n = typeNames.length; - if (n == 0) - return fgEmptyStringArray; - String[] typeSigs = new String[n]; - for (int i = 0; i < n; ++i) { - typeSigs[i] = Signature.createTypeSignature(typeNames[i], false); - } - return typeSigs; - } - /** - * @see ISourceElementRequestor - */ - public void enterClass( - int declarationStart, - int modifiers, - char[] name, - int nameSourceStart, - int nameSourceEnd, - char[] superclass, - char[][] superinterfaces) { - - enterType(declarationStart, modifiers, name, nameSourceStart, nameSourceEnd, superclass, superinterfaces); - - } - /** - * @see ISourceElementRequestor - */ - public void enterCompilationUnit() { - infoStack = new Stack(); - handleStack = new Stack(); - infoStack.push(unitInfo); - handleStack.push(unit); - } - /** - * @see ISourceElementRequestor - */ - public void enterConstructor( - int declarationStart, - int modifiers, - char[] name, - int nameSourceStart, - int nameSourceEnd, - char[][] parameterTypes, - char[][] parameterNames, - char[][] exceptionTypes) { - - enterMethod( - declarationStart, - modifiers, - null, - name, - nameSourceStart, - nameSourceEnd, - parameterTypes, - parameterNames, - exceptionTypes, - true); - } - - /** - * @see ISourceElementRequestor - */ - public void enterField(int declarationStart, int modifiers, char[] type, char[] name, int nameSourceStart, int nameSourceEnd) { - - SourceTypeElementInfo parentInfo = (SourceTypeElementInfo) infoStack.peek(); - JavaElement parentHandle = (JavaElement) handleStack.peek(); - IField handle = null; - - if (parentHandle.getElementType() == IJavaElement.TYPE) { - handle = new SourceField(parentHandle, new String(name)); - } else { - Assert.isTrue(false); // Should not happen - } - resolveDuplicates(handle); - - SourceFieldElementInfo info = new SourceFieldElementInfo(); - info.setName(name); - info.setNameSourceStart(nameSourceStart); - info.setNameSourceEnd(nameSourceEnd); - info.setSourceRangeStart(declarationStart); - info.setFlags(modifiers); - info.setTypeName(type); - - parentInfo.addChild(handle); - newElements.put(handle, info); - - infoStack.push(info); - handleStack.push(handle); - } - /** - * @see ISourceElementRequestor - */ - //public void enterInitializer( - // int declarationSourceStart, - // int modifiers) { - // JavaElementInfo parentInfo = (JavaElementInfo) fInfoStack.peek(); - // JavaElement parentHandle= (JavaElement)fHandleStack.peek(); - // IInitializer handle = null; - // - // if (parentHandle.getElementType() == IJavaElement.TYPE) { - // handle = ((IType) parentHandle).getInitializer(1); - // } - // else { - // Assert.isTrue(false); // Should not happen - // } - // resolveDuplicates(handle); - // - // InitializerElementInfo info = new InitializerElementInfo(); - // info.setSourceRangeStart(declarationSourceStart); - // info.setFlags(modifiers); - // - // parentInfo.addChild(handle); - // fNewElements.put(handle, info); - // - // fInfoStack.push(info); - // fHandleStack.push(handle); - //} - /** - * @see ISourceElementRequestor - */ - public void enterInterface( - int declarationStart, - int modifiers, - char[] name, - int nameSourceStart, - int nameSourceEnd, - char[][] superinterfaces) { - - enterType(declarationStart, modifiers, name, nameSourceStart, nameSourceEnd, null, superinterfaces); - - } - /** - * @see ISourceElementRequestor - */ - public void enterMethod( - int declarationStart, - int modifiers, - char[] returnType, - char[] name, - int nameSourceStart, - int nameSourceEnd, - char[][] parameterTypes, - char[][] parameterNames, - char[][] exceptionTypes) { - - enterMethod( - declarationStart, - modifiers, - returnType, - name, - nameSourceStart, - nameSourceEnd, - parameterTypes, - parameterNames, - exceptionTypes, - false); - } - /** - * @see ISourceElementRequestor - */ - protected void enterMethod( - int declarationStart, - int modifiers, - char[] returnType, - char[] name, - int nameSourceStart, - int nameSourceEnd, - char[][] parameterTypes, - char[][] parameterNames, - char[][] exceptionTypes, - boolean isConstructor) { - SourceTypeElementInfo parentInfo = null; - try { - parentInfo = (SourceTypeElementInfo) infoStack.peek(); - } catch (ClassCastException e) { - // parentInfo = null; - } - JavaElement parentHandle = (JavaElement) handleStack.peek(); - IMethod handle = null; - - // translate nulls to empty arrays - if (parameterTypes == null) { - parameterTypes = fgEmptyCharChar; - } - if (parameterNames == null) { - parameterNames = fgEmptyCharChar; - } - if (exceptionTypes == null) { - exceptionTypes = fgEmptyCharChar; - } - - String[] parameterTypeSigs = convertTypeNamesToSigs(parameterTypes); - // TODO : jsurfer changed -// if (parentHandle.getElementType() == IJavaElement.TYPE) { - handle = new SourceMethod(parentHandle, new String(name), parameterTypeSigs); -// } -// else { -// Assert.isTrue(false); // Should not happen -// } - resolveDuplicates(handle); - - SourceMethodElementInfo info = new SourceMethodElementInfo(); - info.setSourceRangeStart(declarationStart); - int flags = modifiers; - info.setName(name); - info.setNameSourceStart(nameSourceStart); - info.setNameSourceEnd(nameSourceEnd); - info.setConstructor(isConstructor); - info.setFlags(flags); - info.setArgumentNames(parameterNames); - info.setArgumentTypeNames(parameterTypes); - info.setReturnType(returnType == null ? new char[] { 'v', 'o', 'i', 'd' } - : returnType); - info.setExceptionTypeNames(exceptionTypes); - - if (parentInfo == null) { - unitInfo.addChild(handle); - } else { - parentInfo.addChild(handle); - } - newElements.put(handle, info); - infoStack.push(info); - handleStack.push(handle); - } - /** - * Common processing for classes and interfaces. - */ - protected void enterType( - int declarationStart, - int modifiers, - char[] name, - int nameSourceStart, - int nameSourceEnd, - char[] superclass, - char[][] superinterfaces) { - - char[] enclosingTypeName = null; - char[] qualifiedName = null; - - JavaElementInfo parentInfo = (JavaElementInfo) infoStack.peek(); - JavaElement parentHandle = (JavaElement) handleStack.peek(); - IType handle = null; - String nameString = new String(name); - - if (parentHandle.getElementType() == IJavaElement.COMPILATION_UNIT) { - handle = ((ICompilationUnit) parentHandle).getType(nameString); - if (fPackageName == null) { - qualifiedName = nameString.toCharArray(); - } else { - qualifiedName = (new String(fPackageName) + "." + nameString).toCharArray(); //$NON-NLS-1$ - } - } else if (parentHandle.getElementType() == IJavaElement.TYPE) { - handle = ((IType) parentHandle).getType(nameString); - enclosingTypeName = ((SourceTypeElementInfo) parentInfo).getName(); - qualifiedName = (new String(((SourceTypeElementInfo) parentInfo).getQualifiedName()) + "." + nameString).toCharArray(); //$NON-NLS-1$ - } else { - Assert.isTrue(false); // Should not happen - } - resolveDuplicates(handle); - - SourceTypeElementInfo info = new SourceTypeElementInfo(); - info.setHandle(handle); - info.setSourceRangeStart(declarationStart); - info.setFlags(modifiers); - info.setName(name); - info.setNameSourceStart(nameSourceStart); - info.setNameSourceEnd(nameSourceEnd); - info.setSuperclassName(superclass); - info.setSuperInterfaceNames(superinterfaces); - info.setEnclosingTypeName(enclosingTypeName); - info.setSourceFileName(fSourceFileName); - info.setPackageName(fPackageName); - info.setQualifiedName(qualifiedName); - // for (Iterator iter = fNewElements.keySet().iterator(); iter.hasNext();){ - // Object object = iter.next(); - // if (object instanceof IImportDeclaration) - // info.addImport(((IImportDeclaration)object).getElementName().toCharArray()); - // } - - parentInfo.addChild(handle); - newElements.put(handle, info); - - infoStack.push(info); - handleStack.push(handle); - - } - /** - * @see ISourceElementRequestor - */ - public void exitClass(int declarationEnd) { - - exitMember(declarationEnd); - } - /** - * @see ISourceElementRequestor - */ - public void exitCompilationUnit(int declarationEnd) { - unitInfo.setSourceLength(declarationEnd + 1); - - // determine if there were any parsing errors - unitInfo.setIsStructureKnown(!this.hasSyntaxErrors); - } - /** - * @see ISourceElementRequestor - */ - public void exitConstructor(int declarationEnd) { - exitMember(declarationEnd); - } - /** - * @see ISourceElementRequestor - */ - public void exitField(int initializationStart, int declarationEnd, int declarationSourceEnd) { - SourceFieldElementInfo info = (SourceFieldElementInfo) infoStack.pop(); - info.setSourceRangeEnd(declarationSourceEnd); - - // remember initializer source if field is a constant - if (initializationStart != -1) { - int flags = info.flags; - Object typeInfo; - if (Flags.isStatic(flags) && Flags.isFinal(flags) - || ((typeInfo = infoStack.peek()) instanceof SourceTypeElementInfo - && (Flags.isInterface(((SourceTypeElementInfo)typeInfo).flags)))) { - int length = declarationEnd - initializationStart; - if (length > 0) { - char[] initializer = new char[length]; - System.arraycopy(this.parser.scanner.source, initializationStart, initializer, 0, length); - info.initializationSource = initializer; - } - } - } - handleStack.pop(); - } - /** - * @see ISourceElementRequestor - */ - public void exitInitializer(int declarationEnd) { - exitMember(declarationEnd); - } - /** - * @see ISourceElementRequestor - */ - public void exitInterface(int declarationEnd) { - exitMember(declarationEnd); - } - /** - * common processing for classes and interfaces - */ - protected void exitMember(int declarationEnd) { - SourceRefElementInfo info = (SourceRefElementInfo) infoStack.pop(); - info.setSourceRangeEnd(declarationEnd); - handleStack.pop(); - } - /** - * @see ISourceElementRequestor - */ - public void exitMethod(int declarationEnd) { - exitMember(declarationEnd); - } - - /** - * Resolves duplicate handles by incrementing the occurrence count - * of the handle being created until there is no conflict. - */ - protected void resolveDuplicates(IJavaElement handle) { - while (newElements.containsKey(handle)) { - JavaElement h = (JavaElement) handle; - h.setOccurrenceCount(h.getOccurrenceCount() + 1); - } - } +public class CompilationUnitStructureRequestor extends ReferenceInfoAdapter + implements ISourceElementRequestor { + + /** + * The handle to the compilation unit being parsed + */ + protected ICompilationUnit unit; + + /** + * The info object for the compilation unit being parsed + */ + protected CompilationUnitElementInfo unitInfo; + + /** + * The import container info - null until created + */ + protected JavaElementInfo importContainerInfo = null; + + /** + * Hashtable of children elements of the compilation unit. Children are + * added to the table as they are found by the parser. Keys are handles, + * values are corresponding info objects. + */ + protected Map newElements; + + /** + * Stack of parent scope info objects. The info on the top of the stack is + * the parent of the next element found. For example, when we locate a + * method, the parent info object will be the type the method is contained + * in. + */ + protected Stack infoStack; + + /** + * Stack of parent handles, corresponding to the info stack. We keep both, + * since info objects do not have back pointers to handles. + */ + protected Stack handleStack; + + /** + * The name of the source file being parsed. + */ + protected char[] fSourceFileName = null; + + /** + * The dot-separated name of the package the compilation unit is contained + * in - based on the package statement in the compilation unit, and + * initialized by #acceptPackage. Initialized to null for the + * default package. + */ + protected char[] fPackageName = null; + + /** + * The number of references reported thus far. Used to expand the arrays of + * reference kinds and names. + */ + protected int fRefCount = 0; + + /** + * The initial size of the reference kind and name arrays. If the arrays + * fill, they are doubled in size + */ + protected static int fgReferenceAllocation = 50; + + /** + * Problem requestor which will get notified of discovered problems + */ + protected boolean hasSyntaxErrors = false; + + /* + * The parser this requestor is using. + */ + // protected Parser parser; + protected Parser parser; + + /** + * Empty collections used for efficient initialization + */ + protected static String[] fgEmptyStringArray = new String[0]; + + protected static byte[] fgEmptyByte = new byte[] {}; + + protected static char[][] fgEmptyCharChar = new char[][] {}; + + protected static char[] fgEmptyChar = new char[] {}; + + protected HashtableOfObject fieldRefCache; + + protected HashtableOfObject messageRefCache; + + protected HashtableOfObject typeRefCache; + + protected HashtableOfObject unknownRefCache; + + protected CompilationUnitStructureRequestor(ICompilationUnit unit, + CompilationUnitElementInfo unitInfo, Map newElements) + throws JavaModelException { + this.unit = unit; + this.unitInfo = unitInfo; + this.newElements = newElements; + this.fSourceFileName = unit.getElementName().toCharArray(); + } + + /** + * @see ISourceElementRequestor + */ + public void acceptImport(int declarationStart, int declarationEnd, + char[] name, boolean onDemand) { + // , int modifiers) { + + JavaElementInfo parentInfo = (JavaElementInfo) this.infoStack.peek(); + JavaElement parentHandle = (JavaElement) this.handleStack.peek(); + if (!(parentHandle.getElementType() == IJavaElement.COMPILATION_UNIT)) { + Assert.isTrue(false); // Should not happen + } + + ICompilationUnit parentCU = (ICompilationUnit) parentHandle; + // create the import container and its info + ImportContainer importContainer = (ImportContainer) parentCU + .getImportContainer(); + if (this.importContainerInfo == null) { + this.importContainerInfo = new JavaElementInfo(); + this.importContainerInfo.setIsStructureKnown(true); + parentInfo.addChild(importContainer); + this.newElements.put(importContainer, this.importContainerInfo); + } + + // tack on the '.*' if it is onDemand + String importName; + if (onDemand) { + importName = new String(name) + ".*"; //$NON-NLS-1$ + } else { + importName = new String(name); + } + + ImportDeclaration handle = new ImportDeclaration(importContainer, + importName); + resolveDuplicates(handle); + + ImportDeclarationElementInfo info = new ImportDeclarationElementInfo(); + info.setSourceRangeStart(declarationStart); + info.setSourceRangeEnd(declarationEnd); + // info.setFlags(modifiers); + info.setName(name); // no trailing * if onDemand + info.setOnDemand(onDemand); + + this.importContainerInfo.addChild(handle); + this.newElements.put(handle, info); + } + + /** + * @see ISourceElementRequestor + */ + + /* + * Table of line separator position. This table is passed once at the end of + * the parse action, so as to allow computation of normalized ranges. + * + * A line separator might corresponds to several characters in the source, + * + */ + public void acceptLineSeparatorPositions(int[] positions) { + } + + /** + * @see ISourceElementRequestor + */ + // public void acceptPackage(int declarationStart, int declarationEnd, + // char[] name) { + // + // JavaElementInfo parentInfo = (JavaElementInfo) fInfoStack.peek(); + // JavaElement parentHandle= (JavaElement)fHandleStack.peek(); + // IPackageDeclaration handle = null; + // fPackageName= name; + // + // if (parentHandle.getElementType() == IJavaElement.COMPILATION_UNIT) { + // handle = new PackageDeclaration((ICompilationUnit) parentHandle, new + // String(name)); + // } + // else { + // Assert.isTrue(false); // Should not happen + // } + // resolveDuplicates(handle); + // + // SourceRefElementInfo info = new SourceRefElementInfo(); + // info.setSourceRangeStart(declarationStart); + // info.setSourceRangeEnd(declarationEnd); + // + // parentInfo.addChild(handle); + // fNewElements.put(handle, info); + // + // } + public void acceptProblem(IProblem problem) { + if ((problem.getID() & IProblem.Syntax) != 0) { + this.hasSyntaxErrors = true; + } + } + + /** + * Convert these type names to signatures. + * + * @see Signature. + */ + /* default */ + static String[] convertTypeNamesToSigs(char[][] typeNames) { + if (typeNames == null) + return fgEmptyStringArray; + int n = typeNames.length; + if (n == 0) + return fgEmptyStringArray; + String[] typeSigs = new String[n]; + for (int i = 0; i < n; ++i) { + typeSigs[i] = Signature.createTypeSignature(typeNames[i], false); + } + return typeSigs; + } + + /** + * @see ISourceElementRequestor + */ + public void enterClass(int declarationStart, int modifiers, char[] name, + int nameSourceStart, int nameSourceEnd, char[] superclass, + char[][] superinterfaces) { + + enterType(declarationStart, modifiers, name, nameSourceStart, + nameSourceEnd, superclass, superinterfaces); + + } + + /** + * @see ISourceElementRequestor + */ + public void enterCompilationUnit() { + infoStack = new Stack(); + handleStack = new Stack(); + infoStack.push(unitInfo); + handleStack.push(unit); + } + + /** + * @see ISourceElementRequestor + */ + public void enterConstructor(int declarationStart, int modifiers, + char[] name, int nameSourceStart, int nameSourceEnd, + char[][] parameterTypes, char[][] parameterNames, + char[][] exceptionTypes) { + + enterMethod(declarationStart, modifiers, null, name, nameSourceStart, + nameSourceEnd, parameterTypes, parameterNames, exceptionTypes, + true); + } + + /** + * @see ISourceElementRequestor + */ + public void enterField(int declarationStart, int modifiers, char[] type, + char[] name, int nameSourceStart, int nameSourceEnd) { + + SourceTypeElementInfo parentInfo = (SourceTypeElementInfo) infoStack + .peek(); + JavaElement parentHandle = (JavaElement) handleStack.peek(); + IField handle = null; + + if (parentHandle.getElementType() == IJavaElement.TYPE) { + handle = new SourceField(parentHandle, new String(name)); + } else { + Assert.isTrue(false); // Should not happen + } + resolveDuplicates(handle); + + SourceFieldElementInfo info = new SourceFieldElementInfo(); + info.setName(name); + info.setNameSourceStart(nameSourceStart); + info.setNameSourceEnd(nameSourceEnd); + info.setSourceRangeStart(declarationStart); + info.setFlags(modifiers); + info.setTypeName(type); + + parentInfo.addChild(handle); + newElements.put(handle, info); + + infoStack.push(info); + handleStack.push(handle); + } + + /** + * @see ISourceElementRequestor + */ + // public void enterInitializer( + // int declarationSourceStart, + // int modifiers) { + // JavaElementInfo parentInfo = (JavaElementInfo) fInfoStack.peek(); + // JavaElement parentHandle= (JavaElement)fHandleStack.peek(); + // IInitializer handle = null; + // + // if (parentHandle.getElementType() == IJavaElement.TYPE) { + // handle = ((IType) parentHandle).getInitializer(1); + // } + // else { + // Assert.isTrue(false); // Should not happen + // } + // resolveDuplicates(handle); + // + // InitializerElementInfo info = new InitializerElementInfo(); + // info.setSourceRangeStart(declarationSourceStart); + // info.setFlags(modifiers); + // + // parentInfo.addChild(handle); + // fNewElements.put(handle, info); + // + // fInfoStack.push(info); + // fHandleStack.push(handle); + // } + /** + * @see ISourceElementRequestor + */ + public void enterInterface(int declarationStart, int modifiers, + char[] name, int nameSourceStart, int nameSourceEnd, + char[][] superinterfaces) { + + enterType(declarationStart, modifiers, name, nameSourceStart, + nameSourceEnd, null, superinterfaces); + + } + + /** + * @see ISourceElementRequestor + */ + public void enterMethod(int declarationStart, int modifiers, + char[] returnType, char[] name, int nameSourceStart, + int nameSourceEnd, char[][] parameterTypes, + char[][] parameterNames, char[][] exceptionTypes) { + + enterMethod(declarationStart, modifiers, returnType, name, + nameSourceStart, nameSourceEnd, parameterTypes, parameterNames, + exceptionTypes, false); + } + + /** + * @see ISourceElementRequestor + */ + protected void enterMethod(int declarationStart, int modifiers, + char[] returnType, char[] name, int nameSourceStart, + int nameSourceEnd, char[][] parameterTypes, + char[][] parameterNames, char[][] exceptionTypes, + boolean isConstructor) { + SourceTypeElementInfo parentInfo = null; + try { + parentInfo = (SourceTypeElementInfo) infoStack.peek(); + } catch (ClassCastException e) { + // parentInfo = null; + } + JavaElement parentHandle = (JavaElement) handleStack.peek(); + IMethod handle = null; + + // translate nulls to empty arrays + if (parameterTypes == null) { + parameterTypes = fgEmptyCharChar; + } + if (parameterNames == null) { + parameterNames = fgEmptyCharChar; + } + if (exceptionTypes == null) { + exceptionTypes = fgEmptyCharChar; + } + + String[] parameterTypeSigs = convertTypeNamesToSigs(parameterTypes); + // TODO : jsurfer changed + // if (parentHandle.getElementType() == IJavaElement.TYPE) { + handle = new SourceMethod(parentHandle, new String(name), + parameterTypeSigs); + // } + // else { + // Assert.isTrue(false); // Should not happen + // } + resolveDuplicates(handle); + + SourceMethodElementInfo info = new SourceMethodElementInfo(); + info.setSourceRangeStart(declarationStart); + int flags = modifiers; + info.setName(name); + info.setNameSourceStart(nameSourceStart); + info.setNameSourceEnd(nameSourceEnd); + info.setConstructor(isConstructor); + info.setFlags(flags); + info.setArgumentNames(parameterNames); + info.setArgumentTypeNames(parameterTypes); + info + .setReturnType(returnType == null ? new char[] { 'v', 'o', 'i', + 'd' } : returnType); + info.setExceptionTypeNames(exceptionTypes); + + if (parentInfo == null) { + unitInfo.addChild(handle); + } else { + parentInfo.addChild(handle); + } + newElements.put(handle, info); + infoStack.push(info); + handleStack.push(handle); + } + + /** + * Common processing for classes and interfaces. + */ + protected void enterType(int declarationStart, int modifiers, char[] name, + int nameSourceStart, int nameSourceEnd, char[] superclass, + char[][] superinterfaces) { + + char[] enclosingTypeName = null; + char[] qualifiedName = null; + + JavaElementInfo parentInfo = (JavaElementInfo) infoStack.peek(); + JavaElement parentHandle = (JavaElement) handleStack.peek(); + IType handle = null; + String nameString = new String(name); + + if (parentHandle.getElementType() == IJavaElement.COMPILATION_UNIT) { + handle = ((ICompilationUnit) parentHandle).getType(nameString); + if (fPackageName == null) { + qualifiedName = nameString.toCharArray(); + } else { + qualifiedName = (new String(fPackageName) + "." + nameString).toCharArray(); //$NON-NLS-1$ + } + } else if (parentHandle.getElementType() == IJavaElement.TYPE) { + handle = ((IType) parentHandle).getType(nameString); + enclosingTypeName = ((SourceTypeElementInfo) parentInfo).getName(); + qualifiedName = (new String(((SourceTypeElementInfo) parentInfo) + .getQualifiedName()) + + "." + nameString).toCharArray(); //$NON-NLS-1$ + } else { + Assert.isTrue(false); // Should not happen + } + resolveDuplicates(handle); + + SourceTypeElementInfo info = new SourceTypeElementInfo(); + info.setHandle(handle); + info.setSourceRangeStart(declarationStart); + info.setFlags(modifiers); + info.setName(name); + info.setNameSourceStart(nameSourceStart); + info.setNameSourceEnd(nameSourceEnd); + info.setSuperclassName(superclass); + info.setSuperInterfaceNames(superinterfaces); + info.setEnclosingTypeName(enclosingTypeName); + info.setSourceFileName(fSourceFileName); + info.setPackageName(fPackageName); + info.setQualifiedName(qualifiedName); + // for (Iterator iter = fNewElements.keySet().iterator(); + // iter.hasNext();){ + // Object object = iter.next(); + // if (object instanceof IImportDeclaration) + // info.addImport(((IImportDeclaration)object).getElementName().toCharArray()); + // } + + parentInfo.addChild(handle); + newElements.put(handle, info); + + infoStack.push(info); + handleStack.push(handle); + + } + + /** + * @see ISourceElementRequestor + */ + public void exitClass(int declarationEnd) { + + exitMember(declarationEnd); + } + + /** + * @see ISourceElementRequestor + */ + public void exitCompilationUnit(int declarationEnd) { + unitInfo.setSourceLength(declarationEnd + 1); + + // determine if there were any parsing errors + unitInfo.setIsStructureKnown(!this.hasSyntaxErrors); + } + + /** + * @see ISourceElementRequestor + */ + public void exitConstructor(int declarationEnd) { + exitMember(declarationEnd); + } + + /** + * @see ISourceElementRequestor + */ + public void exitField(int initializationStart, int declarationEnd, + int declarationSourceEnd) { + SourceFieldElementInfo info = (SourceFieldElementInfo) infoStack.pop(); + info.setSourceRangeEnd(declarationSourceEnd); + + // remember initializer source if field is a constant + if (initializationStart != -1) { + int flags = info.flags; + Object typeInfo; + if (Flags.isStatic(flags) + && Flags.isFinal(flags) + || ((typeInfo = infoStack.peek()) instanceof SourceTypeElementInfo && (Flags + .isInterface(((SourceTypeElementInfo) typeInfo).flags)))) { + int length = declarationEnd - initializationStart; + if (length > 0) { + char[] initializer = new char[length]; + System.arraycopy(this.parser.scanner.source, + initializationStart, initializer, 0, length); + info.initializationSource = initializer; + } + } + } + handleStack.pop(); + } + + /** + * @see ISourceElementRequestor + */ + public void exitInitializer(int declarationEnd) { + exitMember(declarationEnd); + } + + /** + * @see ISourceElementRequestor + */ + public void exitInterface(int declarationEnd) { + exitMember(declarationEnd); + } + + /** + * common processing for classes and interfaces + */ + protected void exitMember(int declarationEnd) { + SourceRefElementInfo info = (SourceRefElementInfo) infoStack.pop(); + info.setSourceRangeEnd(declarationEnd); + handleStack.pop(); + } + + /** + * @see ISourceElementRequestor + */ + public void exitMethod(int declarationEnd) { + exitMember(declarationEnd); + } + + /** + * Resolves duplicate handles by incrementing the occurrence count of the + * handle being created until there is no conflict. + */ + protected void resolveDuplicates(IJavaElement handle) { + while (newElements.containsKey(handle)) { + JavaElement h = (JavaElement) handle; + h.setOccurrenceCount(h.getOccurrenceCount() + 1); + } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CopyElementsOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CopyElementsOperation.java index aa9b7a2..03578f8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CopyElementsOperation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CopyElementsOperation.java @@ -27,237 +27,283 @@ import net.sourceforge.phpdt.internal.core.util.Util; /** * This operation copies/moves a collection of elements from their current - * container to a new container, optionally renaming the - * elements. - *

                    Notes:

                      - *
                    • If there is already an element with the same name in - * the new container, the operation either overwrites or aborts, - * depending on the collision policy setting. The default setting is - * abort. - * - *
                    • When constructors are copied to a type, the constructors - * are automatically renamed to the name of the destination - * type. - * - *
                    • When main types are renamed (move within the same parent), - * the compilation unit and constructors are automatically renamed - * - *
                    • The collection of elements being copied must all share the - * same type of container (for example, must all be type members). - * - *
                    • The elements are inserted in the new container in the order given. - * - *
                    • The elements can be positioned in the new container - see #setInsertBefore. - * By default, the elements are inserted based on the default positions as specified in - * the creation operation for that element type. - * - *
                    • This operation can be used to copy and rename elements within - * the same container. - * - *
                    • This operation only copies elements contained within compilation units. + * container to a new container, optionally renaming the elements. + *

                      + * Notes: + *

                        + *
                      • If there is already an element with the same name in the new container, + * the operation either overwrites or aborts, depending on the collision policy + * setting. The default setting is abort. + * + *
                      • When constructors are copied to a type, the constructors are + * automatically renamed to the name of the destination type. + * + *
                      • When main types are renamed (move within the same parent), the + * compilation unit and constructors are automatically renamed + * + *
                      • The collection of elements being copied must all share the same type of + * container (for example, must all be type members). + * + *
                      • The elements are inserted in the new container in the order given. + * + *
                      • The elements can be positioned in the new container - see + * #setInsertBefore. By default, the elements are inserted based on the default + * positions as specified in the creation operation for that element type. + * + *
                      • This operation can be used to copy and rename elements within the same + * container. + * + *
                      • This operation only copies elements contained within compilation units. *
                      - * + * */ public class CopyElementsOperation extends MultiOperation { - private Map fSources = new HashMap(); -/** - * When executed, this operation will copy the given elements to the - * given containers. The elements and destination containers must be in - * the correct order. If there is > 1 destination, the number of destinations - * must be the same as the number of elements being copied/moved/renamed. - */ -public CopyElementsOperation(IJavaElement[] elementsToCopy, IJavaElement[] destContainers, boolean force) { - super(elementsToCopy, destContainers, force); -} -/** - * When executed, this operation will copy the given elements to the - * given container. - */ -public CopyElementsOperation(IJavaElement[] elementsToCopy, IJavaElement destContainer, boolean force) { - this(elementsToCopy, new IJavaElement[]{destContainer}, force); -} -/** - * Returns the String to use as the main task name - * for progress monitoring. - */ -protected String getMainTaskName() { - return Util.bind("operation.copyElementProgress"); //$NON-NLS-1$ -} -/** - * Returns the nested operation to use for processing this element - */ -protected JavaModelOperation getNestedOperation(IJavaElement element) { - return null; -// try { -// IJavaElement dest = getDestinationParent(element); -// switch (element.getElementType()) { -// case IJavaElement.PACKAGE_DECLARATION : -// return new CreatePackageDeclarationOperation(element.getElementName(), (ICompilationUnit) dest); -// case IJavaElement.IMPORT_DECLARATION : -// return new CreateImportOperation(element.getElementName(), (ICompilationUnit) dest); -// case IJavaElement.TYPE : -// if (isRenamingMainType(element, dest)) { -// return new RenameResourceElementsOperation(new IJavaElement[] {dest}, new IJavaElement[] {dest.getParent()}, new String[]{getNewNameFor(element) + ".php"}, fForce); //$NON-NLS-1$ -// } else { -// return new CreateTypeOperation(dest, getSourceFor(element) + ProjectPrefUtil.LINE_SEPARATOR, fForce); -// } -// case IJavaElement.METHOD : -// return new CreateMethodOperation((IType) dest, getSourceFor(element) + ProjectPrefUtil.LINE_SEPARATOR, fForce); -// case IJavaElement.FIELD : -// return new CreateFieldOperation((IType) dest, getSourceFor(element) + ProjectPrefUtil.LINE_SEPARATOR, fForce); -// case IJavaElement.INITIALIZER : -// return new CreateInitializerOperation((IType) dest, getSourceFor(element) + ProjectPrefUtil.LINE_SEPARATOR); -// default : -// return null; -// } -// } catch (JavaModelException npe) { -// return null; -// } -} -/** - * Returns the cached source for this element or compute it if not already cached. - */ -private String getSourceFor(IJavaElement element) throws JavaModelException { - String source = (String) fSources.get(element); - if (source == null && element instanceof IMember) { - IMember member = (IMember)element; - ICompilationUnit cu = member.getCompilationUnit(); - String cuSource = cu.getSource(); - IDOMCompilationUnit domCU = new DOMFactory().createCompilationUnit(cuSource, cu.getElementName()); - IDOMNode node = ((JavaElement)element).findNode(domCU); - source = new String(node.getCharacters()); - fSources.put(element, source); + + /** + * When executed, this operation will copy the given elements to the given + * containers. The elements and destination containers must be in the + * correct order. If there is > 1 destination, the number of destinations + * must be the same as the number of elements being copied/moved/renamed. + */ + public CopyElementsOperation(IJavaElement[] elementsToCopy, + IJavaElement[] destContainers, boolean force) { + super(elementsToCopy, destContainers, force); } - return source; -} -/** - * Returns true if this element is the main type of its compilation unit. - */ -protected boolean isRenamingMainType(IJavaElement element, IJavaElement dest) { - if ((isRename() || getNewNameFor(element) != null) - && dest.getElementType() == IJavaElement.COMPILATION_UNIT) { - String typeName = dest.getElementName(); - typeName = typeName.substring(0, typeName.length() - 5); - return element.getElementName().equals(typeName) && element.getParent().equals(dest); + + /** + * When executed, this operation will copy the given elements to the given + * container. + */ + public CopyElementsOperation(IJavaElement[] elementsToCopy, + IJavaElement destContainer, boolean force) { + this(elementsToCopy, new IJavaElement[] { destContainer }, force); } - return false; -} -/** - * Copy/move the element from the source to destination, renaming - * the elements as specified, honoring the collision policy. - * - * @exception JavaModelException if the operation is unable to - * be completed - */ -protected void processElement(IJavaElement element) throws JavaModelException { - JavaModelOperation op = getNestedOperation(element); - boolean createElementInCUOperation =op instanceof CreateElementInCUOperation; - if (op == null) { - return; + + /** + * Returns the String to use as the main task name for + * progress monitoring. + */ + protected String getMainTaskName() { + return Util.bind("operation.copyElementProgress"); //$NON-NLS-1$ + } + + /** + * Returns the nested operation to use for processing this element + */ + protected JavaModelOperation getNestedOperation(IJavaElement element) { + return null; + // try { + // IJavaElement dest = getDestinationParent(element); + // switch (element.getElementType()) { + // case IJavaElement.PACKAGE_DECLARATION : + // return new + // CreatePackageDeclarationOperation(element.getElementName(), + // (ICompilationUnit) dest); + // case IJavaElement.IMPORT_DECLARATION : + // return new CreateImportOperation(element.getElementName(), + // (ICompilationUnit) dest); + // case IJavaElement.TYPE : + // if (isRenamingMainType(element, dest)) { + // return new RenameResourceElementsOperation(new IJavaElement[] {dest}, + // new IJavaElement[] {dest.getParent()}, new + // String[]{getNewNameFor(element) + ".php"}, fForce); //$NON-NLS-1$ + // } else { + // return new CreateTypeOperation(dest, getSourceFor(element) + + // ProjectPrefUtil.LINE_SEPARATOR, fForce); + // } + // case IJavaElement.METHOD : + // return new CreateMethodOperation((IType) dest, getSourceFor(element) + // + ProjectPrefUtil.LINE_SEPARATOR, fForce); + // case IJavaElement.FIELD : + // return new CreateFieldOperation((IType) dest, getSourceFor(element) + + // ProjectPrefUtil.LINE_SEPARATOR, fForce); + // case IJavaElement.INITIALIZER : + // return new CreateInitializerOperation((IType) dest, + // getSourceFor(element) + ProjectPrefUtil.LINE_SEPARATOR); + // default : + // return null; + // } + // } catch (JavaModelException npe) { + // return null; + // } } - if (createElementInCUOperation) { - IJavaElement sibling = (IJavaElement) fInsertBeforeElements.get(element); - if (sibling != null) { - ((CreateElementInCUOperation) op).setRelativePosition(sibling, CreateElementInCUOperation.INSERT_BEFORE); - } else - if (isRename()) { + + /** + * Returns the cached source for this element or compute it if not already + * cached. + */ + private String getSourceFor(IJavaElement element) throws JavaModelException { + String source = (String) fSources.get(element); + if (source == null && element instanceof IMember) { + IMember member = (IMember) element; + ICompilationUnit cu = member.getCompilationUnit(); + String cuSource = cu.getSource(); + IDOMCompilationUnit domCU = new DOMFactory().createCompilationUnit( + cuSource, cu.getElementName()); + IDOMNode node = ((JavaElement) element).findNode(domCU); + source = new String(node.getCharacters()); + fSources.put(element, source); + } + return source; + } + + /** + * Returns true if this element is the main type of its + * compilation unit. + */ + protected boolean isRenamingMainType(IJavaElement element, IJavaElement dest) { + if ((isRename() || getNewNameFor(element) != null) + && dest.getElementType() == IJavaElement.COMPILATION_UNIT) { + String typeName = dest.getElementName(); + typeName = typeName.substring(0, typeName.length() - 5); + return element.getElementName().equals(typeName) + && element.getParent().equals(dest); + } + return false; + } + + /** + * Copy/move the element from the source to destination, renaming the + * elements as specified, honoring the collision policy. + * + * @exception JavaModelException + * if the operation is unable to be completed + */ + protected void processElement(IJavaElement element) + throws JavaModelException { + JavaModelOperation op = getNestedOperation(element); + boolean createElementInCUOperation = op instanceof CreateElementInCUOperation; + if (op == null) { + return; + } + if (createElementInCUOperation) { + IJavaElement sibling = (IJavaElement) fInsertBeforeElements + .get(element); + if (sibling != null) { + ((CreateElementInCUOperation) op).setRelativePosition(sibling, + CreateElementInCUOperation.INSERT_BEFORE); + } else if (isRename()) { IJavaElement anchor = resolveRenameAnchor(element); if (anchor != null) { - ((CreateElementInCUOperation) op).setRelativePosition(anchor, CreateElementInCUOperation.INSERT_AFTER); // insert after so that the anchor is found before when deleted below + ((CreateElementInCUOperation) op).setRelativePosition( + anchor, CreateElementInCUOperation.INSERT_AFTER); // insert + // after + // so + // that + // the + // anchor + // is + // found + // before + // when + // deleted + // below } } - String newName = getNewNameFor(element); - if (newName != null) { - ((CreateElementInCUOperation) op).setAlteredName(newName); + String newName = getNewNameFor(element); + if (newName != null) { + ((CreateElementInCUOperation) op).setAlteredName(newName); + } } - } - executeNestedOperation(op, 1); + executeNestedOperation(op, 1); - JavaElement destination = (JavaElement) getDestinationParent(element); - ICompilationUnit unit= destination.getCompilationUnit(); - if (!unit.isWorkingCopy()) { - unit.close(); - } + JavaElement destination = (JavaElement) getDestinationParent(element); + ICompilationUnit unit = destination.getCompilationUnit(); + if (!unit.isWorkingCopy()) { + unit.close(); + } - if (createElementInCUOperation && isMove() && !isRenamingMainType(element, destination)) { - DeleteElementsOperation deleteOp = new DeleteElementsOperation(new IJavaElement[] { element }, force); - executeNestedOperation(deleteOp, 1); - } -} -/** - * Returns the anchor used for positioning in the destination for - * the element being renamed. For renaming, if no anchor has - * explicitly been provided, the element is anchored in the same position. - */ -private IJavaElement resolveRenameAnchor(IJavaElement element) throws JavaModelException { - IParent parent = (IParent) element.getParent(); - IJavaElement[] children = parent.getChildren(); - for (int i = 0; i < children.length; i++) { - IJavaElement child = children[i]; - if (child.equals(element)) { - return child; + if (createElementInCUOperation && isMove() + && !isRenamingMainType(element, destination)) { + DeleteElementsOperation deleteOp = new DeleteElementsOperation( + new IJavaElement[] { element }, force); + executeNestedOperation(deleteOp, 1); } } - return null; -} -/** - * Possible failures: - *
                        - *
                      • NO_ELEMENTS_TO_PROCESS - no elements supplied to the operation - *
                      • INDEX_OUT_OF_BOUNDS - the number of renamings supplied to the operation - * does not match the number of elements that were supplied. - *
                      - */ -protected IJavaModelStatus verify() { - IJavaModelStatus status = super.verify(); - if (!status.isOK()) { - return status; + + /** + * Returns the anchor used for positioning in the destination for the + * element being renamed. For renaming, if no anchor has explicitly been + * provided, the element is anchored in the same position. + */ + private IJavaElement resolveRenameAnchor(IJavaElement element) + throws JavaModelException { + IParent parent = (IParent) element.getParent(); + IJavaElement[] children = parent.getChildren(); + for (int i = 0; i < children.length; i++) { + IJavaElement child = children[i]; + if (child.equals(element)) { + return child; + } + } + return null; } - if (fRenamingsList != null && fRenamingsList.length != fElementsToProcess.length) { - return new JavaModelStatus(IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS); + + /** + * Possible failures: + *
                        + *
                      • NO_ELEMENTS_TO_PROCESS - no elements supplied to the operation + *
                      • INDEX_OUT_OF_BOUNDS - the number of renamings supplied to the + * operation does not match the number of elements that were supplied. + *
                      + */ + protected IJavaModelStatus verify() { + IJavaModelStatus status = super.verify(); + if (!status.isOK()) { + return status; + } + if (fRenamingsList != null + && fRenamingsList.length != fElementsToProcess.length) { + return new JavaModelStatus( + IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS); + } + return JavaModelStatus.VERIFIED_OK; } - return JavaModelStatus.VERIFIED_OK; -} -/** - * @see MultiOperation - * - * Possible failure codes: - *
                        - * - *
                      • ELEMENT_DOES_NOT_EXIST - element or its specified destination is - * is null or does not exist. If a null element is - * supplied, no element is provided in the status, otherwise, the non-existant element - * is supplied in the status. - *
                      • INVALID_ELEMENT_TYPES - element is not contained within a compilation unit. - * This operation only operates on elements contained within compilation units. - *
                      • READ_ONLY - element is read only. - *
                      • INVALID_DESTINATION - The destination parent specified for element - * is of an incompatible type. The destination for a package declaration or import declaration must - * be a compilation unit; the destination for a type must be a type or compilation - * unit; the destinaion for any type member (other than a type) must be a type. When - * this error occurs, the element provided in the operation status is the element. - *
                      • INVALID_NAME - the new name for element does not have valid syntax. - * In this case the element and name are provided in the status. - *
                      - */ -protected void verify(IJavaElement element) throws JavaModelException { - if (element == null || !element.exists()) - error(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, element); + /** + * @see MultiOperation + * + * Possible failure codes: + *
                        + * + *
                      • ELEMENT_DOES_NOT_EXIST - element or its specified + * destination is is null or does not exist. If a + * null element is supplied, no element is provided in the + * status, otherwise, the non-existant element is supplied in the status. + *
                      • INVALID_ELEMENT_TYPES - element is not contained + * within a compilation unit. This operation only operates on elements + * contained within compilation units. + *
                      • READ_ONLY - element is read only. + *
                      • INVALID_DESTINATION - The destination parent specified for + * element is of an incompatible type. The destination for a + * package declaration or import declaration must be a compilation unit; the + * destination for a type must be a type or compilation unit; the destinaion + * for any type member (other than a type) must be a type. When this error + * occurs, the element provided in the operation status is the + * element. + *
                      • INVALID_NAME - the new name for element does not have + * valid syntax. In this case the element and name are provided in the + * status. + * + *
                      + */ + protected void verify(IJavaElement element) throws JavaModelException { + if (element == null || !element.exists()) + error(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, element); - if (element.getElementType() < IJavaElement.TYPE) - error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element); + if (element.getElementType() < IJavaElement.TYPE) + error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element); - if (element.isReadOnly()) - error(IJavaModelStatusConstants.READ_ONLY, element); + if (element.isReadOnly()) + error(IJavaModelStatusConstants.READ_ONLY, element); - IJavaElement dest = getDestinationParent(element); - verifyDestination(element, dest); - verifySibling(element, dest); - if (fRenamingsList != null) { - verifyRenaming(element); + IJavaElement dest = getDestinationParent(element); + verifyDestination(element, dest); + verifySibling(element, dest); + if (fRenamingsList != null) { + verifyRenaming(element); + } } } -} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CopyResourceElementsOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CopyResourceElementsOperation.java index 12ebbfe..fe25204 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CopyResourceElementsOperation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CopyResourceElementsOperation.java @@ -46,78 +46,88 @@ import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; /** - * This operation copies/moves/renames a collection of resources from their current - * container to a new container, optionally renaming the - * elements. - *

                      Notes:

                        - *
                      • If there is already an resource with the same name in - * the new container, the operation either overwrites or aborts, - * depending on the collision policy setting. The default setting is - * abort. - * - *
                      • When a compilation unit is copied to a new package, the - * package declaration in the compilation unit is automatically updated. - * - *
                      • The collection of elements being copied must all share the - * same type of container. - * - *
                      • This operation can be used to copy and rename elements within - * the same container. - * - *
                      • This operation only copies compilation units and package fragments. - * It does not copy package fragment roots - a platform operation must be used for that. + * This operation copies/moves/renames a collection of resources from their + * current container to a new container, optionally renaming the elements. + *

                        + * Notes: + *

                          + *
                        • If there is already an resource with the same name in the new container, + * the operation either overwrites or aborts, depending on the collision policy + * setting. The default setting is abort. + * + *
                        • When a compilation unit is copied to a new package, the package + * declaration in the compilation unit is automatically updated. + * + *
                        • The collection of elements being copied must all share the same type of + * container. + * + *
                        • This operation can be used to copy and rename elements within the same + * container. + * + *
                        • This operation only copies compilation units and package fragments. It + * does not copy package fragment roots - a platform operation must be used for + * that. *
                        - * + * */ public class CopyResourceElementsOperation extends MultiOperation { /** - * A collection of renamed compilation units. These cus do - * not need to be saved as they no longer exist. + * A collection of renamed compilation units. These cus do not need to be + * saved as they no longer exist. */ protected ArrayList fRenamedCompilationUnits = null; + /** - * Table specifying deltas for elements being - * copied/moved/renamed. Keyed by elements' project(s), and - * values are the corresponding deltas. + * Table specifying deltas for elements being copied/moved/renamed. Keyed by + * elements' project(s), and values are the corresponding deltas. */ - protected Map fDeltasPerProject= new HashMap(1); + protected Map fDeltasPerProject = new HashMap(1); + /** * The DOMFactory used to manipulate the source code of * ICompilationUnit. */ protected DOMFactory fFactory; + /** * The list of new resources created during this operation. */ protected ArrayList fCreatedElements; + /** - * When executed, this operation will copy the given resources to the - * given containers. The resources and destination containers must be in - * the correct order. If there is > 1 destination, the number of destinations + * When executed, this operation will copy the given resources to the given + * containers. The resources and destination containers must be in the + * correct order. If there is > 1 destination, the number of destinations * must be the same as the number of resources being copied/moved. */ - public CopyResourceElementsOperation(IJavaElement[] resourcesToCopy, IJavaElement[] destContainers, boolean force) { + public CopyResourceElementsOperation(IJavaElement[] resourcesToCopy, + IJavaElement[] destContainers, boolean force) { super(resourcesToCopy, destContainers, force); fFactory = new DOMFactory(); } + /** - * When executed, this operation will copy the given resources to the - * given container. + * When executed, this operation will copy the given resources to the given + * container. */ - public CopyResourceElementsOperation(IJavaElement[] resourcesToCopy, IJavaElement destContainer, boolean force) { - this(resourcesToCopy, new IJavaElement[]{destContainer}, force); + public CopyResourceElementsOperation(IJavaElement[] resourcesToCopy, + IJavaElement destContainer, boolean force) { + this(resourcesToCopy, new IJavaElement[] { destContainer }, force); } + /** - * Returns the children of source which are affected by this operation. - * If source is a K_SOURCE, these are the .java - * files, if it is a K_BINARY, they are the .class files. + * Returns the children of source which are affected by this + * operation. If source is a K_SOURCE, these + * are the .java files, if it is a K_BINARY, + * they are the .class files. */ - private IResource[] collectResourcesOfInterest(IPackageFragment source) throws JavaModelException { + private IResource[] collectResourcesOfInterest(IPackageFragment source) + throws JavaModelException { IJavaElement[] children = source.getChildren(); int childOfInterest = IJavaElement.COMPILATION_UNIT; -// if (source.getKind() == IPackageFragmentRoot.K_BINARY) { -// childOfInterest = IJavaElement.CLASS_FILE; -// } + // if (source.getKind() == IPackageFragmentRoot.K_BINARY) { + // childOfInterest = IJavaElement.CLASS_FILE; + // } ArrayList correctKindChildren = new ArrayList(children.length); for (int i = 0; i < children.length; i++) { IJavaElement child = children[i]; @@ -126,44 +136,56 @@ public class CopyResourceElementsOperation extends MultiOperation { } } // Gather non-java resources -// Object[] nonJavaResources = source.getNonJavaResources(); -// int actualNonJavaResourceCount = 0; -// for (int i = 0, max = nonJavaResources.length; i < max; i++){ -// if (nonJavaResources[i] instanceof IResource) actualNonJavaResourceCount++; -// } -// IResource[] actualNonJavaResources = new IResource[actualNonJavaResourceCount]; -// for (int i = 0, max = nonJavaResources.length, index = 0; i < max; i++){ -// if (nonJavaResources[i] instanceof IResource) actualNonJavaResources[index++] = (IResource)nonJavaResources[i]; -// } - -// if (actualNonJavaResourceCount != 0) { -// int correctKindChildrenSize = correctKindChildren.size(); -// IResource[] result = new IResource[correctKindChildrenSize + actualNonJavaResourceCount]; -// correctKindChildren.toArray(result); -// System.arraycopy(actualNonJavaResources, 0, result, correctKindChildrenSize, actualNonJavaResourceCount); -// return result; -// } else { - IResource[] result = new IResource[correctKindChildren.size()]; - correctKindChildren.toArray(result); - return result; -// } + // Object[] nonJavaResources = source.getNonJavaResources(); + // int actualNonJavaResourceCount = 0; + // for (int i = 0, max = nonJavaResources.length; i < max; i++){ + // if (nonJavaResources[i] instanceof IResource) + // actualNonJavaResourceCount++; + // } + // IResource[] actualNonJavaResources = new + // IResource[actualNonJavaResourceCount]; + // for (int i = 0, max = nonJavaResources.length, index = 0; i < max; + // i++){ + // if (nonJavaResources[i] instanceof IResource) + // actualNonJavaResources[index++] = (IResource)nonJavaResources[i]; + // } + + // if (actualNonJavaResourceCount != 0) { + // int correctKindChildrenSize = correctKindChildren.size(); + // IResource[] result = new IResource[correctKindChildrenSize + + // actualNonJavaResourceCount]; + // correctKindChildren.toArray(result); + // System.arraycopy(actualNonJavaResources, 0, result, + // correctKindChildrenSize, actualNonJavaResourceCount); + // return result; + // } else { + IResource[] result = new IResource[correctKindChildren.size()]; + correctKindChildren.toArray(result); + return result; + // } } + /** * Creates any destination package fragment(s) which do not exists yet. */ - private void createNeededPackageFragments(IContainer sourceFolder, IPackageFragmentRoot root, String newFragName, boolean moveFolder) throws JavaModelException { + private void createNeededPackageFragments(IContainer sourceFolder, + IPackageFragmentRoot root, String newFragName, boolean moveFolder) + throws JavaModelException { IContainer parentFolder = (IContainer) root.getResource(); JavaElementDelta projectDelta = null; - String[] names = net.sourceforge.phpdt.internal.core.util.Util.getTrimmedSimpleNames(newFragName); + String[] names = net.sourceforge.phpdt.internal.core.util.Util + .getTrimmedSimpleNames(newFragName); StringBuffer sideEffectPackageName = new StringBuffer(); - char[][] exclusionsPatterns = ((PackageFragmentRoot)root).fullExclusionPatternChars(); + char[][] exclusionsPatterns = ((PackageFragmentRoot) root) + .fullExclusionPatternChars(); for (int i = 0; i < names.length; i++) { String subFolderName = names[i]; sideEffectPackageName.append(subFolderName); IResource subFolder = parentFolder.findMember(subFolderName); if (subFolder == null) { - // create deepest folder only if not a move (folder will be moved in processPackageFragmentResource) - if (!(moveFolder && i == names.length-1)) { + // create deepest folder only if not a move (folder will be + // moved in processPackageFragmentResource) + if (!(moveFolder && i == names.length - 1)) { createFolder(parentFolder, subFolderName, force); } parentFolder = parentFolder.getFolder(new Path(subFolderName)); @@ -171,9 +193,12 @@ public class CopyResourceElementsOperation extends MultiOperation { if (sourceFolder.getResourceAttributes().isReadOnly()) { parentFolder.getResourceAttributes().setReadOnly(true); } - IPackageFragment sideEffectPackage = root.getPackageFragment(sideEffectPackageName.toString()); - if (i < names.length - 1 // all but the last one are side effect packages - && !net.sourceforge.phpdt.internal.core.util.Util.isExcluded(parentFolder, exclusionsPatterns)) { + IPackageFragment sideEffectPackage = root + .getPackageFragment(sideEffectPackageName.toString()); + if (i < names.length - 1 // all but the last one are side + // effect packages + && !net.sourceforge.phpdt.internal.core.util.Util + .isExcluded(parentFolder, exclusionsPatterns)) { if (projectDelta == null) { projectDelta = getDeltaFor(root.getJavaProject()); } @@ -186,64 +211,89 @@ public class CopyResourceElementsOperation extends MultiOperation { sideEffectPackageName.append('.'); } } + /** * Returns the JavaElementDelta for javaProject, - * creating it and putting it in fDeltasPerProject if - * it does not exist yet. + * creating it and putting it in fDeltasPerProject if it does + * not exist yet. */ private JavaElementDelta getDeltaFor(IJavaProject javaProject) { - JavaElementDelta delta = (JavaElementDelta) fDeltasPerProject.get(javaProject); + JavaElementDelta delta = (JavaElementDelta) fDeltasPerProject + .get(javaProject); if (delta == null) { delta = new JavaElementDelta(javaProject); fDeltasPerProject.put(javaProject, delta); } return delta; } + /** * @see MultiOperation */ protected String getMainTaskName() { - return net.sourceforge.phpdt.internal.core.util.Util.bind("operation.copyResourceProgress"); //$NON-NLS-1$ + return net.sourceforge.phpdt.internal.core.util.Util + .bind("operation.copyResourceProgress"); //$NON-NLS-1$ } + /** - * Sets the deltas to register the changes resulting from this operation - * for this source element and its destination. - * If the operation is a cross project operation
                          + * Sets the deltas to register the changes resulting from this operation for + * this source element and its destination. If the operation is a cross + * project operation + *
                            *
                          • On a copy, the delta should be rooted in the dest project - *
                          • On a move, two deltas are generated
                              - *
                            • one rooted in the source project - *
                            • one rooted in the destination project
                          - * If the operation is rooted in a single project, the delta is rooted in that project - * + *
                        • On a move, two deltas are generated + *
                            + *
                          • one rooted in the source project + *
                          • one rooted in the destination project + *
                          + *
                        + * If the operation is rooted in a single project, the delta is rooted in + * that project + * */ - protected void prepareDeltas(IJavaElement sourceElement, IJavaElement destinationElement, boolean isMove) { - if (net.sourceforge.phpdt.internal.core.util.Util.isExcluded(sourceElement) || net.sourceforge.phpdt.internal.core.util.Util.isExcluded(destinationElement)) return; + protected void prepareDeltas(IJavaElement sourceElement, + IJavaElement destinationElement, boolean isMove) { + if (net.sourceforge.phpdt.internal.core.util.Util + .isExcluded(sourceElement) + || net.sourceforge.phpdt.internal.core.util.Util + .isExcluded(destinationElement)) + return; IJavaProject destProject = destinationElement.getJavaProject(); if (isMove) { IJavaProject sourceProject = sourceElement.getJavaProject(); - getDeltaFor(sourceProject).movedFrom(sourceElement, destinationElement); + getDeltaFor(sourceProject).movedFrom(sourceElement, + destinationElement); getDeltaFor(destProject).movedTo(destinationElement, sourceElement); } else { getDeltaFor(destProject).added(destinationElement); } } + /** - * Copies/moves a compilation unit with the name newCUName - * to the destination package.
                        + * Copies/moves a compilation unit with the name newCUName to + * the destination package.
                        * The package statement in the compilation unit is updated if necessary. * The main type of the compilation unit is renamed if necessary. - * - * @exception JavaModelException if the operation is unable to - * complete + * + * @exception JavaModelException + * if the operation is unable to complete */ - private void processCompilationUnitResource(ICompilationUnit source, IPackageFragment dest) throws JavaModelException { + private void processCompilationUnitResource(ICompilationUnit source, + IPackageFragment dest) throws JavaModelException { String newCUName = getNewNameFor(source); - String destName = (newCUName != null) ? newCUName : source.getElementName(); - String newContent = updatedContent(source, dest, newCUName); // null if unchanged + String destName = (newCUName != null) ? newCUName : source + .getElementName(); + String newContent = updatedContent(source, dest, newCUName); // null + // if + // unchanged // copy resource - IFile sourceResource = (IFile)(source.isWorkingCopy() ? source.getOriginalElement() : source).getResource(); - IContainer destFolder = (IContainer)dest.getResource(); // can be an IFolder or an IProject + IFile sourceResource = (IFile) (source.isWorkingCopy() ? source + .getOriginalElement() : source).getResource(); + IContainer destFolder = (IContainer) dest.getResource(); // can be an + // IFolder + // or an + // IProject IFile destFile = destFolder.getFile(new Path(destName)); if (!destFile.equals(sourceResource)) { try { @@ -253,18 +303,24 @@ public class CopyResourceElementsOperation extends MultiOperation { deleteResource(destFile, IResource.KEEP_HISTORY); } else { // abort - throw new JavaModelException(new JavaModelStatus( - IJavaModelStatusConstants.NAME_COLLISION, - Util.bind("status.nameCollision", destFile.getFullPath().toString()))); //$NON-NLS-1$ + throw new JavaModelException( + new JavaModelStatus( + IJavaModelStatusConstants.NAME_COLLISION, + Util + .bind( + "status.nameCollision", destFile.getFullPath().toString()))); //$NON-NLS-1$ } } int flags = force ? IResource.FORCE : IResource.NONE; if (this.isMove()) { flags |= IResource.KEEP_HISTORY; - sourceResource.move(destFile.getFullPath(), flags, getSubProgressMonitor(1)); + sourceResource.move(destFile.getFullPath(), flags, + getSubProgressMonitor(1)); } else { - if (newContent != null) flags |= IResource.KEEP_HISTORY; - sourceResource.copy(destFile.getFullPath(), flags, getSubProgressMonitor(1)); + if (newContent != null) + flags |= IResource.KEEP_HISTORY; + sourceResource.copy(destFile.getFullPath(), flags, + getSubProgressMonitor(1)); } this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); } catch (JavaModelException e) { @@ -275,15 +331,19 @@ public class CopyResourceElementsOperation extends MultiOperation { // update new resource content try { - if (newContent != null){ - String encoding = source.getJavaProject().getOption(JavaCore.CORE_ENCODING, true); - destFile.setContents( - new ByteArrayInputStream(encoding == null ? newContent.getBytes() : newContent.getBytes(encoding)), - force ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY, - getSubProgressMonitor(1)); + if (newContent != null) { + String encoding = source.getJavaProject().getOption( + JavaCore.CORE_ENCODING, true); + destFile.setContents(new ByteArrayInputStream( + encoding == null ? newContent.getBytes() + : newContent.getBytes(encoding)), + force ? IResource.FORCE | IResource.KEEP_HISTORY + : IResource.KEEP_HISTORY, + getSubProgressMonitor(1)); } - } catch(IOException e) { - throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); + } catch (IOException e) { + throw new JavaModelException(e, + IJavaModelStatusConstants.IO_EXCEPTION); } catch (CoreException e) { throw new JavaModelException(e); } @@ -292,69 +352,86 @@ public class CopyResourceElementsOperation extends MultiOperation { ICompilationUnit destCU = dest.getCompilationUnit(destName); prepareDeltas(source, destCU, isMove()); if (newCUName != null) { - //the main type has been renamed + // the main type has been renamed String oldName = source.getElementName(); oldName = oldName.substring(0, oldName.length() - 5); String newName = newCUName; newName = newName.substring(0, newName.length() - 5); - prepareDeltas(source.getType(oldName), destCU.getType(newName), isMove()); + prepareDeltas(source.getType(oldName), destCU.getType(newName), + isMove()); } } else { if (!force) { - throw new JavaModelException(new JavaModelStatus( - IJavaModelStatusConstants.NAME_COLLISION, - Util.bind("status.nameCollision", destFile.getFullPath().toString()))); //$NON-NLS-1$ + throw new JavaModelException( + new JavaModelStatus( + IJavaModelStatusConstants.NAME_COLLISION, + Util + .bind( + "status.nameCollision", destFile.getFullPath().toString()))); //$NON-NLS-1$ } // update new resource content - // in case we do a saveas on the same resource we have to simply update the contents + // in case we do a saveas on the same resource we have to simply + // update the contents // see http://dev.eclipse.org/bugs/show_bug.cgi?id=9351 try { - if (newContent != null){ - String encoding = source.getJavaProject().getOption(JavaCore.CORE_ENCODING, true); - destFile.setContents( - new ByteArrayInputStream(encoding == null ? newContent.getBytes() : newContent.getBytes(encoding)), - force ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY, - getSubProgressMonitor(1)); + if (newContent != null) { + String encoding = source.getJavaProject().getOption( + JavaCore.CORE_ENCODING, true); + destFile.setContents(new ByteArrayInputStream( + encoding == null ? newContent.getBytes() + : newContent.getBytes(encoding)), + force ? IResource.FORCE | IResource.KEEP_HISTORY + : IResource.KEEP_HISTORY, + getSubProgressMonitor(1)); } - } catch(IOException e) { - throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); + } catch (IOException e) { + throw new JavaModelException(e, + IJavaModelStatusConstants.IO_EXCEPTION); } catch (CoreException e) { throw new JavaModelException(e); } } } + /** * Process all of the changed deltas generated by this operation. */ protected void processDeltas() { - for (Iterator deltas = this.fDeltasPerProject.values().iterator(); deltas.hasNext();){ + for (Iterator deltas = this.fDeltasPerProject.values().iterator(); deltas + .hasNext();) { addDelta((IJavaElementDelta) deltas.next()); } } + /** - * @see MultiOperation - * This method delegates to processCompilationUnitResource or - * processPackageFragmentResource, depending on the type of - * element. + * @see MultiOperation This method delegates to + * processCompilationUnitResource or + * processPackageFragmentResource, depending on the + * type of element. */ - protected void processElement(IJavaElement element) throws JavaModelException { + protected void processElement(IJavaElement element) + throws JavaModelException { IJavaElement dest = getDestinationParent(element); switch (element.getElementType()) { - case IJavaElement.COMPILATION_UNIT : - processCompilationUnitResource((ICompilationUnit) element, (IPackageFragment) dest); - fCreatedElements.add(((IPackageFragment) dest).getCompilationUnit(element.getElementName())); - break; - case IJavaElement.PACKAGE_FRAGMENT : - processPackageFragmentResource((IPackageFragment) element, (IPackageFragmentRoot) dest, getNewNameFor(element)); - break; - default : - throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element)); + case IJavaElement.COMPILATION_UNIT: + processCompilationUnitResource((ICompilationUnit) element, + (IPackageFragment) dest); + fCreatedElements.add(((IPackageFragment) dest) + .getCompilationUnit(element.getElementName())); + break; + case IJavaElement.PACKAGE_FRAGMENT: + processPackageFragmentResource((IPackageFragment) element, + (IPackageFragmentRoot) dest, getNewNameFor(element)); + break; + default: + throw new JavaModelException(new JavaModelStatus( + IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element)); } } + /** - * @see MultiOperation - * Overridden to allow special processing of JavaElementDeltas - * and fResultElements. + * @see MultiOperation Overridden to allow special processing of + * JavaElementDeltas and fResultElements. */ protected void processElements() throws JavaModelException { fCreatedElements = new ArrayList(fElementsToProcess.length); @@ -370,21 +447,28 @@ public class CopyResourceElementsOperation extends MultiOperation { } /** - * Copies/moves a package fragment with the name newName - * to the destination package.
                        - * - * @exception JavaModelException if the operation is unable to - * complete + * Copies/moves a package fragment with the name newName to + * the destination package.
                        + * + * @exception JavaModelException + * if the operation is unable to complete */ - private void processPackageFragmentResource(IPackageFragment source, IPackageFragmentRoot root, String newName) throws JavaModelException { + private void processPackageFragmentResource(IPackageFragment source, + IPackageFragmentRoot root, String newName) + throws JavaModelException { try { - String newFragName = (newName == null) ? source.getElementName() : newName; + String newFragName = (newName == null) ? source.getElementName() + : newName; IPackageFragment newFrag = root.getPackageFragment(newFragName); IResource[] resources = collectResourcesOfInterest(source); - // if isMove() can we move the folder itself ? (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=22458) - boolean shouldMoveFolder = isMove() && !newFrag.getResource().exists(); // if new pkg fragment exists, it is an override - IFolder srcFolder = (IFolder)source.getResource(); + // if isMove() can we move the folder itself ? (see + // http://bugs.eclipse.org/bugs/show_bug.cgi?id=22458) + boolean shouldMoveFolder = isMove() + && !newFrag.getResource().exists(); // if new pkg fragment + // exists, it is an + // override + IFolder srcFolder = (IFolder) source.getResource(); IPath destPath = newFrag.getPath(); if (shouldMoveFolder) { // check if destination is not included in source @@ -394,54 +478,74 @@ public class CopyResourceElementsOperation extends MultiOperation { // check if there are no sub-packages IResource[] members = srcFolder.members(); for (int i = 0; i < members.length; i++) { - if ( members[i] instanceof IFolder) { + if (members[i] instanceof IFolder) { shouldMoveFolder = false; break; } } } } - createNeededPackageFragments((IContainer) source.getParent().getResource(), root, newFragName, shouldMoveFolder); + createNeededPackageFragments((IContainer) source.getParent() + .getResource(), root, newFragName, shouldMoveFolder); // Process resources if (shouldMoveFolder) { // move underlying resource - srcFolder.move(destPath, force, true /* keep history */, getSubProgressMonitor(1)); + srcFolder.move(destPath, force, true /* keep history */, + getSubProgressMonitor(1)); this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); } else { // process the leaf resources if (resources.length > 0) { if (isRename()) { - if (! destPath.equals(source.getPath())) { + if (!destPath.equals(source.getPath())) { moveResources(resources, destPath); } } else if (isMove()) { - // we need to delete this resource if this operation wants to override existing resources + // we need to delete this resource if this operation + // wants to override existing resources for (int i = 0, max = resources.length; i < max; i++) { - IResource destinationResource = ResourcesPlugin.getWorkspace().getRoot().findMember(destPath.append(resources[i].getName())); + IResource destinationResource = ResourcesPlugin + .getWorkspace().getRoot().findMember( + destPath.append(resources[i] + .getName())); if (destinationResource != null) { if (force) { - deleteResource(destinationResource, IResource.KEEP_HISTORY); + deleteResource(destinationResource, + IResource.KEEP_HISTORY); } else { - throw new JavaModelException(new JavaModelStatus( - IJavaModelStatusConstants.NAME_COLLISION, - Util.bind("status.nameCollision", destinationResource.getFullPath().toString()))); //$NON-NLS-1$ + throw new JavaModelException( + new JavaModelStatus( + IJavaModelStatusConstants.NAME_COLLISION, + Util + .bind( + "status.nameCollision", destinationResource.getFullPath().toString()))); //$NON-NLS-1$ } } } moveResources(resources, destPath); } else { - // we need to delete this resource if this operation wants to override existing resources + // we need to delete this resource if this operation + // wants to override existing resources for (int i = 0, max = resources.length; i < max; i++) { - IResource destinationResource = ResourcesPlugin.getWorkspace().getRoot().findMember(destPath.append(resources[i].getName())); + IResource destinationResource = ResourcesPlugin + .getWorkspace().getRoot().findMember( + destPath.append(resources[i] + .getName())); if (destinationResource != null) { if (force) { - // we need to delete this resource if this operation wants to override existing resources - deleteResource(destinationResource, IResource.KEEP_HISTORY); + // we need to delete this resource if this + // operation wants to override existing + // resources + deleteResource(destinationResource, + IResource.KEEP_HISTORY); } else { - throw new JavaModelException(new JavaModelStatus( - IJavaModelStatusConstants.NAME_COLLISION, - Util.bind("status.nameCollision", destinationResource.getFullPath().toString()))); //$NON-NLS-1$ + throw new JavaModelException( + new JavaModelStatus( + IJavaModelStatusConstants.NAME_COLLISION, + Util + .bind( + "status.nameCollision", destinationResource.getFullPath().toString()))); //$NON-NLS-1$ } } } @@ -453,13 +557,15 @@ public class CopyResourceElementsOperation extends MultiOperation { // Discard empty old package (if still empty after the rename) boolean isEmpty = true; if (isMove()) { - // delete remaining files in this package (.class file in the case where Proj=src=bin) + // delete remaining files in this package (.class file in the + // case where Proj=src=bin) if (srcFolder.exists()) { IResource[] remaingFiles = srcFolder.members(); for (int i = 0, length = remaingFiles.length; i < length; i++) { IResource file = remaingFiles[i]; if (file instanceof IFile) { - this.deleteResource(file, IResource.FORCE | IResource.KEEP_HISTORY); + this.deleteResource(file, IResource.FORCE + | IResource.KEEP_HISTORY); } else { isEmpty = false; } @@ -471,7 +577,7 @@ public class CopyResourceElementsOperation extends MultiOperation { if (destPath.isPrefixOf(srcFolder.getFullPath())) { rootResource = newFrag.getResource(); } else { - rootResource = source.getParent().getResource(); + rootResource = source.getParent().getResource(); } // delete recursively empty folders @@ -480,24 +586,40 @@ public class CopyResourceElementsOperation extends MultiOperation { } // Update package statement in compilation unit if needed - if (!newFrag.getElementName().equals(source.getElementName())) { // if package has been renamed, update the compilation units + if (!newFrag.getElementName().equals(source.getElementName())) { // if + // package + // has + // been + // renamed, + // update + // the + // compilation + // units for (int i = 0; i < resources.length; i++) { if (resources[i].getName().endsWith(".java")) { //$NON-NLS-1$ // we only consider potential compilation units - ICompilationUnit cu = newFrag.getCompilationUnit(resources[i].getName()); - IDOMCompilationUnit domCU = fFactory.createCompilationUnit(cu.getSource(), cu.getElementName()); + ICompilationUnit cu = newFrag + .getCompilationUnit(resources[i].getName()); + IDOMCompilationUnit domCU = fFactory + .createCompilationUnit(cu.getSource(), cu + .getElementName()); if (domCU != null) { updatePackageStatement(domCU, newFragName); IBuffer buffer = cu.getBuffer(); - if (buffer == null) continue; + if (buffer == null) + continue; String bufferContents = buffer.getContents(); - if (bufferContents == null) continue; + if (bufferContents == null) + continue; String domCUContents = domCU.getContents(); String cuContents = null; if (domCUContents != null) { - cuContents = net.sourceforge.phpdt.internal.core.util.Util.normalizeCRs(domCU.getContents(), bufferContents); + cuContents = net.sourceforge.phpdt.internal.core.util.Util + .normalizeCRs(domCU.getContents(), + bufferContents); } else { - // See PR http://dev.eclipse.org/bugs/show_bug.cgi?id=11285 + // See PR + // http://dev.eclipse.org/bugs/show_bug.cgi?id=11285 cuContents = bufferContents;//$NON-NLS-1$ } buffer.setContents(cuContents); @@ -507,52 +629,61 @@ public class CopyResourceElementsOperation extends MultiOperation { } } - //register the correct change deltas + // register the correct change deltas prepareDeltas(source, newFrag, isMove() && isEmpty); } catch (DOMException dom) { - throw new JavaModelException(dom, IJavaModelStatusConstants.DOM_EXCEPTION); + throw new JavaModelException(dom, + IJavaModelStatusConstants.DOM_EXCEPTION); } catch (JavaModelException e) { throw e; } catch (CoreException ce) { throw new JavaModelException(ce); } } + /** - * Updates the content of cu, modifying the type name and/or package - * declaration as necessary. - * + * Updates the content of cu, modifying the type name and/or + * package declaration as necessary. + * * @return the new source */ - private String updatedContent(ICompilationUnit cu, IPackageFragment dest, String newName) throws JavaModelException { + private String updatedContent(ICompilationUnit cu, IPackageFragment dest, + String newName) throws JavaModelException { String currPackageName = cu.getParent().getElementName(); String destPackageName = dest.getElementName(); if (currPackageName.equals(destPackageName) && newName == null) { - return null; //nothing to change + return null; // nothing to change } else { String typeName = cu.getElementName(); typeName = typeName.substring(0, typeName.length() - 5); IDOMCompilationUnit cuDOM = null; IBuffer buffer = cu.getBuffer(); - if (buffer == null) return null; + if (buffer == null) + return null; char[] contents = buffer.getCharacters(); - if (contents == null) return null; + if (contents == null) + return null; cuDOM = fFactory.createCompilationUnit(contents, typeName); updateTypeName(cu, cuDOM, cu.getElementName(), newName); updatePackageStatement(cuDOM, destPackageName); return cuDOM.getContents(); } } + /** - * Makes sure that cu declares to be in the pkgName package. + * Makes sure that cu declares to be in the + * pkgName package. */ - private void updatePackageStatement(IDOMCompilationUnit domCU, String pkgName) throws JavaModelException { - boolean defaultPackage = pkgName.equals(IPackageFragment.DEFAULT_PACKAGE_NAME); + private void updatePackageStatement(IDOMCompilationUnit domCU, + String pkgName) throws JavaModelException { + boolean defaultPackage = pkgName + .equals(IPackageFragment.DEFAULT_PACKAGE_NAME); boolean seenPackageNode = false; Enumeration e = domCU.getChildren(); while (e.hasMoreElements()) { IDOMNode node = (IDOMNode) e.nextElement(); if (node.getNodeType() == IDOMNode.PACKAGE) { - if (! defaultPackage) { + if (!defaultPackage) { node.setName(pkgName); } else { node.remove(); @@ -562,45 +693,52 @@ public class CopyResourceElementsOperation extends MultiOperation { } } if (!seenPackageNode && !defaultPackage) { - //the cu was in a default package...no package declaration - //create the new package declaration as the first child of the cu -// IDOMPackage pkg = fFactory.createPackage("package " + pkgName + ";" + net.sourceforge.phpdt.internal.compiler.util.ProjectPrefUtil.LINE_SEPARATOR); //$NON-NLS-1$ //$NON-NLS-2$ -// IDOMNode firstChild = domCU.getFirstChild(); -// if (firstChild != null) { -// firstChild.insertSibling(pkg); -// } // else the cu was empty: leave it empty + // the cu was in a default package...no package declaration + // create the new package declaration as the first child of the cu + // IDOMPackage pkg = fFactory.createPackage("package " + pkgName + + // ";" + + // net.sourceforge.phpdt.internal.compiler.util.ProjectPrefUtil.LINE_SEPARATOR); + // //$NON-NLS-1$ //$NON-NLS-2$ + // IDOMNode firstChild = domCU.getFirstChild(); + // if (firstChild != null) { + // firstChild.insertSibling(pkg); + // } // else the cu was empty: leave it empty } } - /** - * Renames the main type in cu. - */ - private void updateTypeName(ICompilationUnit cu, IDOMCompilationUnit domCU, String oldName, String newName) throws JavaModelException { - if (newName != null) { - if (fRenamedCompilationUnits == null) { - fRenamedCompilationUnits= new ArrayList(1); - } - fRenamedCompilationUnits.add(cu); - String oldTypeName= oldName.substring(0, oldName.length() - 5); - String newTypeName= newName.substring(0, newName.length() - 5); - // update main type name - IType[] types = cu.getTypes(); - for (int i = 0, max = types.length; i < max; i++) { - IType currentType = types[i]; - if (currentType.getElementName().equals(oldTypeName)) { - IDOMNode typeNode = ((JavaElement) currentType).findNode(domCU); - if (typeNode != null) { - typeNode.setName(newTypeName); - } + + /** + * Renames the main type in cu. + */ + private void updateTypeName(ICompilationUnit cu, IDOMCompilationUnit domCU, + String oldName, String newName) throws JavaModelException { + if (newName != null) { + if (fRenamedCompilationUnits == null) { + fRenamedCompilationUnits = new ArrayList(1); + } + fRenamedCompilationUnits.add(cu); + String oldTypeName = oldName.substring(0, oldName.length() - 5); + String newTypeName = newName.substring(0, newName.length() - 5); + // update main type name + IType[] types = cu.getTypes(); + for (int i = 0, max = types.length; i < max; i++) { + IType currentType = types[i]; + if (currentType.getElementName().equals(oldTypeName)) { + IDOMNode typeNode = ((JavaElement) currentType) + .findNode(domCU); + if (typeNode != null) { + typeNode.setName(newTypeName); } } } } + } + /** * Possible failures: *
                          - *
                        • NO_ELEMENTS_TO_PROCESS - no elements supplied to the operation - *
                        • INDEX_OUT_OF_BOUNDS - the number of renamings supplied to the operation - * does not match the number of elements that were supplied. + *
                        • NO_ELEMENTS_TO_PROCESS - no elements supplied to the operation + *
                        • INDEX_OUT_OF_BOUNDS - the number of renamings supplied to the + * operation does not match the number of elements that were supplied. *
                        */ protected IJavaModelStatus verify() { @@ -609,11 +747,14 @@ public class CopyResourceElementsOperation extends MultiOperation { return status; } - if (fRenamingsList != null && fRenamingsList.length != fElementsToProcess.length) { - return new JavaModelStatus(IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS); + if (fRenamingsList != null + && fRenamingsList.length != fElementsToProcess.length) { + return new JavaModelStatus( + IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS); } return JavaModelStatus.VERIFIED_OK; } + /** * @see MultiOperation */ @@ -645,5 +786,5 @@ public class CopyResourceElementsOperation extends MultiOperation { if (fRenamings != null) { verifyRenaming(element); } -} + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CreateElementInCUOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CreateElementInCUOperation.java index 3952555..c2e35e5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CreateElementInCUOperation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CreateElementInCUOperation.java @@ -28,79 +28,90 @@ import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.runtime.jobs.ISchedulingRule; /** - *

                        This abstract class implements behavior common to CreateElementInCUOperations. - * To create a compilation unit, or an element contained in a compilation unit, the - * source code for the entire compilation unit is updated and saved. - * - *

                        The element being created can be positioned relative to an existing - * element in the compilation unit via the methods #createAfter - * and #createBefore. By default, the new element is positioned - * as the last child of its parent element. - * + *

                        + * This abstract class implements behavior common to + * CreateElementInCUOperations. To create a compilation unit, or + * an element contained in a compilation unit, the source code for the entire + * compilation unit is updated and saved. + * + *

                        + * The element being created can be positioned relative to an existing element + * in the compilation unit via the methods #createAfter and + * #createBefore. By default, the new element is positioned as + * the last child of its parent element. + * */ public abstract class CreateElementInCUOperation extends JavaModelOperation { /** * The compilation unit DOM used for this operation */ protected IDOMCompilationUnit fCUDOM; + /** - * A constant meaning to position the new element - * as the last child of its parent element. + * A constant meaning to position the new element as the last child of its + * parent element. */ protected static final int INSERT_LAST = 1; + /** - * A constant meaning to position the new element - * after the element defined by fAnchorElement. + * A constant meaning to position the new element after the element defined + * by fAnchorElement. */ protected static final int INSERT_AFTER = 2; /** - * A constant meaning to position the new element - * before the element defined by fAnchorElement. + * A constant meaning to position the new element before the element defined + * by fAnchorElement. */ protected static final int INSERT_BEFORE = 3; + /** - * One of the position constants, describing where - * to position the newly created element. + * One of the position constants, describing where to position the newly + * created element. */ protected int fInsertionPolicy = INSERT_LAST; + /** - * The element that the newly created element is - * positioned relative to, as described by - * fInsertPosition, or null - * if the newly created element will be positioned - * last. + * The element that the newly created element is positioned relative to, as + * described by fInsertPosition, or null if + * the newly created element will be positioned last. */ protected IJavaElement fAnchorElement = null; + /** - * A flag indicating whether creation of a new element occurred. - * A request for creating a duplicate element would request in this - * flag being set to false. Ensures that no deltas are generated - * when creation does not occur. + * A flag indicating whether creation of a new element occurred. A request + * for creating a duplicate element would request in this flag being set to + * false. Ensures that no deltas are generated when creation + * does not occur. */ protected boolean fCreationOccurred = true; + /** * The element that is being created. */ protected DOMNode fCreatedElement; + /** * The position of the element that is being created. */ protected int fInsertionPosition = -1; + /** - * The number of characters the new element replaces, - * or 0 if the new element is inserted, - * or -1 if the new element is append to the end of the CU. + * The number of characters the new element replaces, or 0 if the new + * element is inserted, or -1 if the new element is append to the end of the + * CU. */ protected int fReplacementLength = -1; + /** - * Constructs an operation that creates a Java Language Element with - * the specified parent, contained within a compilation unit. + * Constructs an operation that creates a Java Language Element with the + * specified parent, contained within a compilation unit. */ public CreateElementInCUOperation(IJavaElement parentElement) { - super(null, new IJavaElement[]{parentElement}); + super(null, new IJavaElement[] { parentElement }); initializeDefaultPosition(); } + /** * Only allow cancelling if this operation is not nested. */ @@ -109,27 +120,31 @@ public abstract class CreateElementInCUOperation extends JavaModelOperation { super.checkCanceled(); } } + /** - * Instructs this operation to position the new element after - * the given sibling, or to add the new element as the last child - * of its parent if null. + * Instructs this operation to position the new element after the given + * sibling, or to add the new element as the last child of its parent if + * null. */ public void createAfter(IJavaElement sibling) { setRelativePosition(sibling, INSERT_AFTER); } + /** - * Instructs this operation to position the new element before - * the given sibling, or to add the new element as the last child - * of its parent if null. + * Instructs this operation to position the new element before the given + * sibling, or to add the new element as the last child of its parent if + * null. */ public void createBefore(IJavaElement sibling) { setRelativePosition(sibling, INSERT_BEFORE); } + /** - * Execute the operation - generate new source for the compilation unit - * and save the results. - * - * @exception JavaModelException if the operation is unable to complete + * Execute the operation - generate new source for the compilation unit and + * save the results. + * + * @exception JavaModelException + * if the operation is unable to complete */ protected void executeOperation() throws JavaModelException { try { @@ -138,24 +153,29 @@ public abstract class CreateElementInCUOperation extends JavaModelOperation { ICompilationUnit unit = getCompilationUnit(); generateNewCompilationUnitDOM(unit); if (fCreationOccurred) { - //a change has really occurred + // a change has really occurred IBuffer buffer = unit.getBuffer(); - if (buffer == null) return; + if (buffer == null) + return; char[] bufferContents = buffer.getCharacters(); - if (bufferContents == null) return; - char[] elementContents = net.sourceforge.phpdt.internal.core.util.Util.normalizeCRs(fCreatedElement.getCharacters(), bufferContents); + if (bufferContents == null) + return; + char[] elementContents = net.sourceforge.phpdt.internal.core.util.Util + .normalizeCRs(fCreatedElement.getCharacters(), + bufferContents); switch (fReplacementLength) { - case -1 : - // element is append at the end - buffer.append(elementContents); - break; - case 0 : - // element is inserted - buffer.replace(fInsertionPosition, 0, elementContents); - break; - default : - // element is replacing the previous one - buffer.replace(fInsertionPosition, fReplacementLength, elementContents); + case -1: + // element is append at the end + buffer.append(elementContents); + break; + case 0: + // element is inserted + buffer.replace(fInsertionPosition, 0, elementContents); + break; + default: + // element is replacing the previous one + buffer.replace(fInsertionPosition, fReplacementLength, + elementContents); } unit.save(null, false); boolean isWorkingCopy = unit.isWorkingCopy(); @@ -163,134 +183,152 @@ public abstract class CreateElementInCUOperation extends JavaModelOperation { this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); worked(1); resultElements = generateResultHandles(); - if (!isWorkingCopy // if unit is working copy, then save will have already fired the delta - && !Util.isExcluded(unit) - && unit.getParent().exists()) { + if (!isWorkingCopy // if unit is working copy, then save will + // have already fired the delta + && !Util.isExcluded(unit) && unit.getParent().exists()) { for (int i = 0; i < resultElements.length; i++) { delta.added(resultElements[i]); } addDelta(delta); } // else unit is created outside classpath - // non-java resource delta will be notified by delta processor + // non-java resource delta will be notified by delta processor } } finally { done(); } } + /** * Returns a JDOM document fragment for the element being created. */ protected abstract IDOMNode generateElementDOM() throws JavaModelException; + /** - * Returns the DOM with the new source to use for the given compilation unit. + * Returns the DOM with the new source to use for the given compilation + * unit. */ - protected void generateNewCompilationUnitDOM(ICompilationUnit cu) throws JavaModelException { + protected void generateNewCompilationUnitDOM(ICompilationUnit cu) + throws JavaModelException { IBuffer buffer = cu.getBuffer(); - if (buffer == null) return; + if (buffer == null) + return; char[] prevSource = buffer.getCharacters(); - if (prevSource == null) return; - + if (prevSource == null) + return; + // create a JDOM for the compilation unit - fCUDOM = (new DOMFactory()).createCompilationUnit(prevSource, cu.getElementName()); + fCUDOM = (new DOMFactory()).createCompilationUnit(prevSource, cu + .getElementName()); IDOMNode child = generateElementDOM(); if (child != null) { insertDOMNode(fCUDOM, child); } worked(1); } + /** * Creates and returns the handle for the element this operation created. */ protected abstract IJavaElement generateResultHandle(); + /** * Creates and returns the handles for the elements this operation created. */ protected IJavaElement[] generateResultHandles() throws JavaModelException { - return new IJavaElement[]{generateResultHandle()}; + return new IJavaElement[] { generateResultHandle() }; } + /** * Returns the compilation unit in which the new element is being created. */ protected ICompilationUnit getCompilationUnit() { return getCompilationUnitFor(getParentElement()); } + /** * Returns the amount of work for the main task of this operation for * progress reporting. */ - protected int getMainAmountOfWork(){ + protected int getMainAmountOfWork() { return 2; } + /** - * Returns the name of the main task of this operation for - * progress reporting. + * Returns the name of the main task of this operation for progress + * reporting. */ public abstract String getMainTaskName(); - + protected ISchedulingRule getSchedulingRule() { IResource resource = getCompilationUnit().getResource(); IWorkspace workspace = resource.getWorkspace(); return workspace.getRuleFactory().modifyRule(resource); } + /** * Returns the elements created by this operation. */ public IJavaElement[] getResultElements() { return resultElements; } + /** - * Sets the default position in which to create the new type - * member. By default, the new element is positioned as the - * last child of the parent element in which it is created. - * Operations that require a different default position must - * override this method. + * Sets the default position in which to create the new type member. By + * default, the new element is positioned as the last child of the parent + * element in which it is created. Operations that require a different + * default position must override this method. */ protected void initializeDefaultPosition() { - + } + /** - * Inserts the given child into the given JDOM, - * based on the position settings of this operation. - * + * Inserts the given child into the given JDOM, based on the position + * settings of this operation. + * * @see createAfter(IJavaElement) * @see createBefore(IJavaElement); */ protected void insertDOMNode(IDOMNode parent, IDOMNode child) { if (fInsertionPolicy != INSERT_LAST) { - IDOMNode sibling = ((JavaElement)fAnchorElement).findNode(fCUDOM); + IDOMNode sibling = ((JavaElement) fAnchorElement).findNode(fCUDOM); if (sibling != null && fInsertionPolicy == INSERT_AFTER) { sibling = sibling.getNextNode(); } if (sibling != null) { sibling.insertSibling(child); - fCreatedElement = (DOMNode)child; - fInsertionPosition = ((DOMNode)sibling).getStartPosition(); + fCreatedElement = (DOMNode) child; + fInsertionPosition = ((DOMNode) sibling).getStartPosition(); fReplacementLength = 0; return; } } - //add as the last element of the parent + // add as the last element of the parent parent.addChild(child); - fCreatedElement = (DOMNode)child; - fInsertionPosition = ((DOMNode)parent).getInsertionPosition(); - // fInsertionPosition = lastChild == null ? ((DOMNode)parent).getInsertionPosition() : lastChild.getInsertionPosition(); + fCreatedElement = (DOMNode) child; + fInsertionPosition = ((DOMNode) parent).getInsertionPosition(); + // fInsertionPosition = lastChild == null ? + // ((DOMNode)parent).getInsertionPosition() : + // lastChild.getInsertionPosition(); fReplacementLength = parent.getParent() == null ? -1 : 0; } + /** - * Sets the name of the DOMNode that will be used to - * create this new element. - * Used by the CopyElementsOperation for renaming. - * Only used for CreateTypeMemberOperation + * Sets the name of the DOMNode that will be used to create + * this new element. Used by the CopyElementsOperation for + * renaming. Only used for CreateTypeMemberOperation */ protected void setAlteredName(String newName) { } + /** - * Instructs this operation to position the new element relative - * to the given sibling, or to add the new element as the last child - * of its parent if null. The position - * must be one of the position constants. + * Instructs this operation to position the new element relative to the + * given sibling, or to add the new element as the last child of its parent + * if null. The position must be one of the + * position constants. */ - protected void setRelativePosition(IJavaElement sibling, int policy) throws IllegalArgumentException { + protected void setRelativePosition(IJavaElement sibling, int policy) + throws IllegalArgumentException { if (sibling == null) { fAnchorElement = null; fInsertionPolicy = INSERT_LAST; @@ -299,20 +337,24 @@ public abstract class CreateElementInCUOperation extends JavaModelOperation { fInsertionPolicy = policy; } } + /** - * Possible failures:

                          - *
                        • NO_ELEMENTS_TO_PROCESS - the compilation unit supplied to the operation is - * null. - *
                        • INVALID_NAME - no name, a name was null or not a valid - * import declaration name. - *
                        • INVALID_SIBLING - the sibling provided for positioning is not valid. + * Possible failures: + *
                            + *
                          • NO_ELEMENTS_TO_PROCESS - the compilation unit supplied to the + * operation is null. + *
                          • INVALID_NAME - no name, a name was null or not a valid import + * declaration name. + *
                          • INVALID_SIBLING - the sibling provided for positioning is not valid. *
                          + * * @see IJavaModelStatus * @see JavaConventions */ public IJavaModelStatus verify() { if (getParentElement() == null) { - return new JavaModelStatus(IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS); + return new JavaModelStatus( + IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS); } if (fAnchorElement != null) { IJavaElement domPresentParent = fAnchorElement.getParent(); @@ -320,7 +362,9 @@ public abstract class CreateElementInCUOperation extends JavaModelOperation { domPresentParent = domPresentParent.getParent(); } if (!domPresentParent.equals(getParentElement())) { - return new JavaModelStatus(IJavaModelStatusConstants.INVALID_SIBLING, fAnchorElement); + return new JavaModelStatus( + IJavaModelStatusConstants.INVALID_SIBLING, + fAnchorElement); } } return JavaModelStatus.VERIFIED_OK; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CreatePackageDeclarationOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CreatePackageDeclarationOperation.java index edb31a1..7cf5a72 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CreatePackageDeclarationOperation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CreatePackageDeclarationOperation.java @@ -24,109 +24,130 @@ import net.sourceforge.phpdt.internal.core.jdom.DOMNode; import net.sourceforge.phpdt.internal.core.util.Util; /** - *

                          This operation adds/replaces a package declaration in an existing compilation unit. - * If the compilation unit already includes the specified package declaration, - * it is not generated (it does not generate duplicates). - * - *

                          Required Attributes:

                            - *
                          • Compilation unit element - *
                          • Package name + *

                            + * This operation adds/replaces a package declaration in an existing compilation + * unit. If the compilation unit already includes the specified package + * declaration, it is not generated (it does not generate duplicates). + * + *

                            + * Required Attributes: + *

                              + *
                            • Compilation unit element + *
                            • Package name *
                            */ -public class CreatePackageDeclarationOperation extends CreateElementInCUOperation { +public class CreatePackageDeclarationOperation extends + CreateElementInCUOperation { /** * The name of the package declaration being created */ protected String fName = null; -/** - * When executed, this operation will add a package declaration to the given compilation unit. - */ -public CreatePackageDeclarationOperation(String name, ICompilationUnit parentElement) { - super(parentElement); - fName= name; -} -/** - * @see CreateTypeMemberOperation#generateElementDOM - */ -protected IDOMNode generateElementDOM() throws JavaModelException { - IJavaElement[] children = getCompilationUnit().getChildren(); - //look for an existing package declaration - for (int i = 0; i < children.length; i++) { - if (children[i].getElementType() == IJavaElement.PACKAGE_DECLARATION) { - IPackageDeclaration pck = (IPackageDeclaration) children[i]; - IDOMPackage pack = (IDOMPackage) ((JavaElement)pck).findNode(fCUDOM); - if (!pack.getName().equals(fName)) { - // get the insertion position before setting the name, as this makes it a detailed node - // thus the start position is always 0 - DOMNode node = (DOMNode)pack; - fInsertionPosition = node.getStartPosition(); - fReplacementLength = node.getEndPosition() - fInsertionPosition + 1; - pack.setName(fName); - fCreatedElement = (net.sourceforge.phpdt.internal.core.jdom.DOMNode)pack; - } else { - //equivalent package declaration already exists - fCreationOccurred= false; + + /** + * When executed, this operation will add a package declaration to the given + * compilation unit. + */ + public CreatePackageDeclarationOperation(String name, + ICompilationUnit parentElement) { + super(parentElement); + fName = name; + } + + /** + * @see CreateTypeMemberOperation#generateElementDOM + */ + protected IDOMNode generateElementDOM() throws JavaModelException { + IJavaElement[] children = getCompilationUnit().getChildren(); + // look for an existing package declaration + for (int i = 0; i < children.length; i++) { + if (children[i].getElementType() == IJavaElement.PACKAGE_DECLARATION) { + IPackageDeclaration pck = (IPackageDeclaration) children[i]; + IDOMPackage pack = (IDOMPackage) ((JavaElement) pck) + .findNode(fCUDOM); + if (!pack.getName().equals(fName)) { + // get the insertion position before setting the name, as + // this makes it a detailed node + // thus the start position is always 0 + DOMNode node = (DOMNode) pack; + fInsertionPosition = node.getStartPosition(); + fReplacementLength = node.getEndPosition() + - fInsertionPosition + 1; + pack.setName(fName); + fCreatedElement = (net.sourceforge.phpdt.internal.core.jdom.DOMNode) pack; + } else { + // equivalent package declaration already exists + fCreationOccurred = false; + } + + return null; } - - return null; } + IDOMPackage pack = (new DOMFactory()).createPackage(); + pack.setName(fName); + return pack; } - IDOMPackage pack = (new DOMFactory()).createPackage(); - pack.setName(fName); - return pack; -} -/** - * Creates and returns the handle for the element this operation created. - */ -protected IJavaElement generateResultHandle() { - return getCompilationUnit().getPackageDeclaration(fName); -} -/** - * @see CreateElementInCUOperation#getMainTaskName() - */ -public String getMainTaskName(){ - return Util.bind("operation.createPackageProgress"); //$NON-NLS-1$ -} -/** - * Sets the correct position for new package declaration:
                              - *
                            • before the first import - *
                            • if no imports, before the first type - *
                            • if no type - first thing in the CU - *
                            • - */ -protected void initializeDefaultPosition() { - try { - ICompilationUnit cu = getCompilationUnit(); -// IImportDeclaration[] imports = cu.getImports(); -// if (imports.length > 0) { -// createBefore(imports[0]); -// return; -// } - IType[] types = cu.getTypes(); - if (types.length > 0) { - createBefore(types[0]); - return; + + /** + * Creates and returns the handle for the element this operation created. + */ + protected IJavaElement generateResultHandle() { + return getCompilationUnit().getPackageDeclaration(fName); + } + + /** + * @see CreateElementInCUOperation#getMainTaskName() + */ + public String getMainTaskName() { + return Util.bind("operation.createPackageProgress"); //$NON-NLS-1$ + } + + /** + * Sets the correct position for new package declaration: + *
                                + *
                              • before the first import + *
                              • if no imports, before the first type + *
                              • if no type - first thing in the CU + *
                              • + */ + protected void initializeDefaultPosition() { + try { + ICompilationUnit cu = getCompilationUnit(); + // IImportDeclaration[] imports = cu.getImports(); + // if (imports.length > 0) { + // createBefore(imports[0]); + // return; + // } + IType[] types = cu.getTypes(); + if (types.length > 0) { + createBefore(types[0]); + return; + } + } catch (JavaModelException npe) { } - } catch (JavaModelException npe) { } -} -/** - * Possible failures:
                                  - *
                                • NO_ELEMENTS_TO_PROCESS - no compilation unit was supplied to the operation - *
                                • INVALID_NAME - a name supplied to the operation was not a valid - * package declaration name. - *
                                - * @see IJavaModelStatus - * @see JavaConventions - */ -public IJavaModelStatus verify() { - IJavaModelStatus status = super.verify(); - if (!status.isOK()) { - return status; + + /** + * Possible failures: + *
                                  + *
                                • NO_ELEMENTS_TO_PROCESS - no compilation unit was supplied to the + * operation + *
                                • INVALID_NAME - a name supplied to the operation was not a valid + * package declaration name. + *
                                + * + * @see IJavaModelStatus + * @see JavaConventions + */ + public IJavaModelStatus verify() { + IJavaModelStatus status = super.verify(); + if (!status.isOK()) { + return status; + } + // if (JavaConventions.validatePackageName(fName).getSeverity() == + // IStatus.ERROR) { + // return new JavaModelStatus(IJavaModelStatusConstants.INVALID_NAME, + // fName); + // } + return JavaModelStatus.VERIFIED_OK; } -// if (JavaConventions.validatePackageName(fName).getSeverity() == IStatus.ERROR) { -// return new JavaModelStatus(IJavaModelStatusConstants.INVALID_NAME, fName); -// } - return JavaModelStatus.VERIFIED_OK; -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DefaultWorkingCopyOwner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DefaultWorkingCopyOwner.java index 6628114..e466002 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DefaultWorkingCopyOwner.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DefaultWorkingCopyOwner.java @@ -15,15 +15,15 @@ import net.sourceforge.phpdt.core.ICompilationUnit; import net.sourceforge.phpdt.core.WorkingCopyOwner; /** - * A working copy owner that creates internal buffers. - * It also defines the PRIMARY working copy owner that is used by JDT/Core. + * A working copy owner that creates internal buffers. It also defines the + * PRIMARY working copy owner that is used by JDT/Core. */ public class DefaultWorkingCopyOwner extends WorkingCopyOwner { - + public WorkingCopyOwner primaryBufferProvider; - - public static final DefaultWorkingCopyOwner PRIMARY = new DefaultWorkingCopyOwner(); - + + public static final DefaultWorkingCopyOwner PRIMARY = new DefaultWorkingCopyOwner(); + private DefaultWorkingCopyOwner() { // only one instance can be created } @@ -32,9 +32,11 @@ public class DefaultWorkingCopyOwner extends WorkingCopyOwner { * @deprecated Marked deprecated as it is using deprecated code */ public IBuffer createBuffer(ICompilationUnit workingCopy) { - if (this.primaryBufferProvider != null) return this.primaryBufferProvider.createBuffer(workingCopy); + if (this.primaryBufferProvider != null) + return this.primaryBufferProvider.createBuffer(workingCopy); return super.createBuffer(workingCopy); } + public String toString() { return "Primary owner"; //$NON-NLS-1$ } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DeleteElementsOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DeleteElementsOperation.java index a8073cb..9096e30 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DeleteElementsOperation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DeleteElementsOperation.java @@ -28,49 +28,54 @@ import net.sourceforge.phpdt.internal.core.util.Util; import net.sourceforge.phpdt.internal.corext.Assert; /** - * This operation deletes a collection of elements (and - * all of their children). + * This operation deletes a collection of elements (and all of their children). * If an element does not exist, it is ignored. - * - *

                                NOTE: This operation only deletes elements contained within leaf resources - - * that is, elements within compilation units. To delete a compilation unit or - * a package, etc (which have an actual resource), a DeleteResourcesOperation + * + *

                                + * NOTE: This operation only deletes elements contained within leaf resources - + * that is, elements within compilation units. To delete a compilation unit or a + * package, etc (which have an actual resource), a DeleteResourcesOperation * should be used. */ public class DeleteElementsOperation extends MultiOperation { /** * The elements this operation processes grouped by compilation unit - * @see processElements(). Keys are compilation units, - * values are IRegions of elements to be processed in each - * compilation unit. - */ + * + * @see processElements(). Keys are compilation units, values are + * IRegions of elements to be processed in each + * compilation unit. + */ protected Map fChildrenToRemove; + /** * The DOMFactory used to manipulate the source code of * ICompilationUnits. */ protected DOMFactory fFactory; + /** - * When executed, this operation will delete the given elements. The elements - * to delete cannot be null or empty, and must be contained within a - * compilation unit. + * When executed, this operation will delete the given elements. The + * elements to delete cannot be null or empty, and must be + * contained within a compilation unit. */ - public DeleteElementsOperation(IJavaElement[] elementsToDelete, boolean force) { + public DeleteElementsOperation(IJavaElement[] elementsToDelete, + boolean force) { super(elementsToDelete, force); fFactory = new DOMFactory(); } - + /** * @see MultiOperation */ protected String getMainTaskName() { return Util.bind("operation.deleteElementProgress"); //$NON-NLS-1$ } + /** - * Groups the elements to be processed by their compilation unit. - * If parent/child combinations are present, children are - * discarded (only the parents are processed). Removes any - * duplicates specified in elements to be processed. + * Groups the elements to be processed by their compilation unit. If + * parent/child combinations are present, children are discarded (only the + * parents are processed). Removes any duplicates specified in elements to + * be processed. */ protected void groupElements() throws JavaModelException { fChildrenToRemove = new HashMap(1); @@ -79,7 +84,8 @@ public class DeleteElementsOperation extends MultiOperation { IJavaElement e = fElementsToProcess[i]; ICompilationUnit cu = getCompilationUnitFor(e); if (cu == null) { - throw new JavaModelException(new JavaModelStatus(JavaModelStatus.READ_ONLY, e)); + throw new JavaModelException(new JavaModelStatus( + JavaModelStatus.READ_ONLY, e)); } else { IRegion region = (IRegion) fChildrenToRemove.get(cu); if (region == null) { @@ -97,63 +103,79 @@ public class DeleteElementsOperation extends MultiOperation { fElementsToProcess[i++] = (IJavaElement) iter.next(); } } + /** * Deletes this element from its compilation unit. + * * @see MultiOperation */ - protected void processElement(IJavaElement element) throws JavaModelException { + protected void processElement(IJavaElement element) + throws JavaModelException { ICompilationUnit cu = (ICompilationUnit) element; - + // keep track of the import statements - if all are removed, delete // the import container (and report it in the delta) -// int numberOfImports = cu.getImports().length; - + // int numberOfImports = cu.getImports().length; + IBuffer buffer = cu.getBuffer(); - if (buffer == null) return; + if (buffer == null) + return; JavaElementDelta delta = new JavaElementDelta(cu); - IJavaElement[] cuElements = ((IRegion) fChildrenToRemove.get(cu)).getElements(); + IJavaElement[] cuElements = ((IRegion) fChildrenToRemove.get(cu)) + .getElements(); for (int i = 0, length = cuElements.length; i < length; i++) { IJavaElement e = cuElements[i]; if (e.exists()) { char[] contents = buffer.getCharacters(); - if (contents == null) continue; - IDOMCompilationUnit cuDOM = fFactory.createCompilationUnit(contents, cu.getElementName()); - DOMNode node = (DOMNode)((JavaElement) e).findNode(cuDOM); - if (node == null) Assert.isTrue(false, "Failed to locate " + e.getElementName() + " in " + cuDOM.getName()); //$NON-NLS-1$//$NON-NLS-2$ + if (contents == null) + continue; + IDOMCompilationUnit cuDOM = fFactory.createCompilationUnit( + contents, cu.getElementName()); + DOMNode node = (DOMNode) ((JavaElement) e).findNode(cuDOM); + if (node == null) + Assert + .isTrue( + false, + "Failed to locate " + e.getElementName() + " in " + cuDOM.getName()); //$NON-NLS-1$//$NON-NLS-2$ int startPosition = node.getStartPosition(); - buffer.replace(startPosition, node.getEndPosition() - startPosition + 1, CharOperation.NO_CHAR); + buffer.replace(startPosition, node.getEndPosition() + - startPosition + 1, CharOperation.NO_CHAR); delta.removed(e); -// if (e.getElementType() == IJavaElement.IMPORT_DECLARATION) { -// numberOfImports--; -// if (numberOfImports == 0) { -// delta.removed(cu.getImportContainer()); -// } -// } + // if (e.getElementType() == IJavaElement.IMPORT_DECLARATION) { + // numberOfImports--; + // if (numberOfImports == 0) { + // delta.removed(cu.getImportContainer()); + // } + // } } } if (delta.getAffectedChildren().length > 0) { cu.save(getSubProgressMonitor(1), force); - if (!cu.isWorkingCopy()) { // if unit is working copy, then save will have already fired the delta + if (!cu.isWorkingCopy()) { // if unit is working copy, then save + // will have already fired the delta addDelta(delta); this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); } } } + /** - * @see MultiOperation - * This method first group the elements by ICompilationUnit, - * and then processes the ICompilationUnit. + * @see MultiOperation This method first group the elements by + * ICompilationUnit, and then processes the + * ICompilationUnit. */ protected void processElements() throws JavaModelException { groupElements(); super.processElements(); } + /** * @see MultiOperation */ protected void verify(IJavaElement element) throws JavaModelException { - IJavaElement[] children = ((IRegion) fChildrenToRemove.get(element)).getElements(); + IJavaElement[] children = ((IRegion) fChildrenToRemove.get(element)) + .getElements(); for (int i = 0; i < children.length; i++) { IJavaElement child = children[i]; if (child.getCorrespondingResource() != null) diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DeleteResourceElementsOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DeleteResourceElementsOperation.java index 1e1fd04..2c1f488 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DeleteResourceElementsOperation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DeleteResourceElementsOperation.java @@ -23,119 +23,138 @@ import org.eclipse.core.runtime.CoreException; /** * This operation deletes a collection of resources and all of their children. - * It does not delete resources which do not belong to the Java Model - * (eg GIF files). + * It does not delete resources which do not belong to the Java Model (eg GIF + * files). */ public class DeleteResourceElementsOperation extends MultiOperation { -/** - * When executed, this operation will delete the given elements. The elements - * to delete cannot be null or empty, and must have a corresponding - * resource. - */ -protected DeleteResourceElementsOperation(IJavaElement[] elementsToProcess, boolean force) { - super(elementsToProcess, force); -} -/** - * Deletes the direct children of frag corresponding to its kind - * (K_SOURCE or K_BINARY), and deletes the corresponding folder if it is then - * empty. - */ -private void deletePackageFragment(IPackageFragment frag) - throws JavaModelException { - IResource res = frag.getResource(); - if (res != null && res.getType() == IResource.FOLDER) { - // collect the children to remove - IJavaElement[] childrenOfInterest = frag.getChildren(); - if (childrenOfInterest.length > 0) { - IResource[] resources = new IResource[childrenOfInterest.length]; - // remove the children - for (int i = 0; i < childrenOfInterest.length; i++) { - resources[i] = childrenOfInterest[i].getCorrespondingResource(); + /** + * When executed, this operation will delete the given elements. The + * elements to delete cannot be null or empty, and must have + * a corresponding resource. + */ + protected DeleteResourceElementsOperation(IJavaElement[] elementsToProcess, + boolean force) { + super(elementsToProcess, force); + } + + /** + * Deletes the direct children of frag corresponding to its + * kind (K_SOURCE or K_BINARY), and deletes the corresponding folder if it + * is then empty. + */ + private void deletePackageFragment(IPackageFragment frag) + throws JavaModelException { + IResource res = frag.getResource(); + if (res != null && res.getType() == IResource.FOLDER) { + // collect the children to remove + IJavaElement[] childrenOfInterest = frag.getChildren(); + if (childrenOfInterest.length > 0) { + IResource[] resources = new IResource[childrenOfInterest.length]; + // remove the children + for (int i = 0; i < childrenOfInterest.length; i++) { + resources[i] = childrenOfInterest[i] + .getCorrespondingResource(); + } + deleteResources(resources, force); } - deleteResources(resources, force); - } - // Discard non-java resources -// Object[] nonJavaResources = frag.getNonJavaResources(); -// int actualResourceCount = 0; -// for (int i = 0, max = nonJavaResources.length; i < max; i++){ -// if (nonJavaResources[i] instanceof IResource) actualResourceCount++; -// } -// IResource[] actualNonJavaResources = new IResource[actualResourceCount]; -// for (int i = 0, max = nonJavaResources.length, index = 0; i < max; i++){ -// if (nonJavaResources[i] instanceof IResource) actualNonJavaResources[index++] = (IResource)nonJavaResources[i]; -// } -// deleteResources(actualNonJavaResources, fForce); - - // delete remaining files in this package (.class file in the case where Proj=src=bin) - IResource[] remainingFiles; - try { - remainingFiles = ((IFolder) res).members(); - } catch (CoreException ce) { - throw new JavaModelException(ce); - } - boolean isEmpty = true; - for (int i = 0, length = remainingFiles.length; i < length; i++) { - IResource file = remainingFiles[i]; - if (file instanceof IFile) { - this.deleteResource(file, IResource.FORCE | IResource.KEEP_HISTORY); - } else { - isEmpty = false; + // Discard non-java resources + // Object[] nonJavaResources = frag.getNonJavaResources(); + // int actualResourceCount = 0; + // for (int i = 0, max = nonJavaResources.length; i < max; i++){ + // if (nonJavaResources[i] instanceof IResource) + // actualResourceCount++; + // } + // IResource[] actualNonJavaResources = new + // IResource[actualResourceCount]; + // for (int i = 0, max = nonJavaResources.length, index = 0; i < + // max; i++){ + // if (nonJavaResources[i] instanceof IResource) + // actualNonJavaResources[index++] = (IResource)nonJavaResources[i]; + // } + // deleteResources(actualNonJavaResources, fForce); + + // delete remaining files in this package (.class file in the case + // where Proj=src=bin) + IResource[] remainingFiles; + try { + remainingFiles = ((IFolder) res).members(); + } catch (CoreException ce) { + throw new JavaModelException(ce); } - } - if (isEmpty) { - // delete recursively empty folders - IResource fragResource = frag.getResource(); - if (fragResource != null) { - deleteEmptyPackageFragment(frag, false, fragResource.getParent()); + boolean isEmpty = true; + for (int i = 0, length = remainingFiles.length; i < length; i++) { + IResource file = remainingFiles[i]; + if (file instanceof IFile) { + this.deleteResource(file, IResource.FORCE + | IResource.KEEP_HISTORY); + } else { + isEmpty = false; + } + } + if (isEmpty) { + // delete recursively empty folders + IResource fragResource = frag.getResource(); + if (fragResource != null) { + deleteEmptyPackageFragment(frag, false, fragResource + .getParent()); + } } } } -} -/** - * @see MultiOperation - */ -protected String getMainTaskName() { - return Util.bind("operation.deleteResourceProgress"); //$NON-NLS-1$ -} -/** - * @see MultiOperation. This method delegate to deleteResource or - * deletePackageFragment depending on the type of element. - */ -protected void processElement(IJavaElement element) throws JavaModelException { - switch (element.getElementType()) { - case IJavaElement.CLASS_FILE : - case IJavaElement.COMPILATION_UNIT : - deleteResource(element.getResource(), force ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY); + + /** + * @see MultiOperation + */ + protected String getMainTaskName() { + return Util.bind("operation.deleteResourceProgress"); //$NON-NLS-1$ + } + + /** + * @see MultiOperation. This method delegate to deleteResource + * or deletePackageFragment depending on the type of + * element. + */ + protected void processElement(IJavaElement element) + throws JavaModelException { + switch (element.getElementType()) { + case IJavaElement.CLASS_FILE: + case IJavaElement.COMPILATION_UNIT: + deleteResource(element.getResource(), force ? IResource.FORCE + | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY); break; - case IJavaElement.PACKAGE_FRAGMENT : + case IJavaElement.PACKAGE_FRAGMENT: deletePackageFragment((IPackageFragment) element); break; - default : - throw new JavaModelException(new JavaModelStatus(JavaModelStatus.INVALID_ELEMENT_TYPES, element)); - } - // ensure the element is closed - if (element instanceof IOpenable) { - ((IOpenable)element).close(); + default: + throw new JavaModelException(new JavaModelStatus( + JavaModelStatus.INVALID_ELEMENT_TYPES, element)); + } + // ensure the element is closed + if (element instanceof IOpenable) { + ((IOpenable) element).close(); + } } -} -/** - * @see MultiOperation - */ -protected void verify(IJavaElement element) throws JavaModelException { - if (element == null || !element.exists()) - error(JavaModelStatus.ELEMENT_DOES_NOT_EXIST, element); - int type = element.getElementType(); - if (type <= IJavaElement.PACKAGE_FRAGMENT_ROOT || type > IJavaElement.COMPILATION_UNIT) - error(JavaModelStatus.INVALID_ELEMENT_TYPES, element); -// else if (type == IJavaElement.PACKAGE_FRAGMENT && element instanceof JarPackageFragment) -// error(JavaModelStatus.INVALID_ELEMENT_TYPES, element); - IResource resource = element.getResource(); - if (resource instanceof IFolder) { - if (resource.isLinked()) { - error(JavaModelStatus.INVALID_RESOURCE, element); + /** + * @see MultiOperation + */ + protected void verify(IJavaElement element) throws JavaModelException { + if (element == null || !element.exists()) + error(JavaModelStatus.ELEMENT_DOES_NOT_EXIST, element); + + int type = element.getElementType(); + if (type <= IJavaElement.PACKAGE_FRAGMENT_ROOT + || type > IJavaElement.COMPILATION_UNIT) + error(JavaModelStatus.INVALID_ELEMENT_TYPES, element); + // else if (type == IJavaElement.PACKAGE_FRAGMENT && element instanceof + // JarPackageFragment) + // error(JavaModelStatus.INVALID_ELEMENT_TYPES, element); + IResource resource = element.getResource(); + if (resource instanceof IFolder) { + if (resource.isLinked()) { + error(JavaModelStatus.INVALID_RESOURCE, element); + } } } } -} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DeltaProcessingState.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DeltaProcessingState.java index 015593b..89b0477 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DeltaProcessingState.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DeltaProcessingState.java @@ -37,101 +37,125 @@ import org.eclipse.core.runtime.Platform; * Keep the global states used during Java element delta processing. */ public class DeltaProcessingState implements IResourceChangeListener { - + /* * Collection of listeners for Java element deltas */ public IElementChangedListener[] elementChangedListeners = new IElementChangedListener[5]; + public int[] elementChangedListenerMasks = new int[5]; + public int elementChangedListenerCount = 0; - + /* * Collection of pre Java resource change listeners */ public IResourceChangeListener[] preResourceChangeListeners = new IResourceChangeListener[1]; + public int preResourceChangeListenerCount = 0; /* * The delta processor for the current thread. */ private ThreadLocal deltaProcessors = new ThreadLocal(); - + /* A table from IPath (from a classpath entry) to RootInfo */ public HashMap roots = new HashMap(); - - /* A table from IPath (from a classpath entry) to ArrayList of RootInfo - * Used when an IPath corresponds to more than one root */ + + /* + * A table from IPath (from a classpath entry) to ArrayList of RootInfo Used + * when an IPath corresponds to more than one root + */ public HashMap otherRoots = new HashMap(); - - /* A table from IPath (from a classpath entry) to RootInfo - * from the last time the delta processor was invoked. */ + + /* + * A table from IPath (from a classpath entry) to RootInfo from the last + * time the delta processor was invoked. + */ public HashMap oldRoots = new HashMap(); - - /* A table from IPath (from a classpath entry) to ArrayList of RootInfo - * from the last time the delta processor was invoked. - * Used when an IPath corresponds to more than one root */ + + /* + * A table from IPath (from a classpath entry) to ArrayList of RootInfo from + * the last time the delta processor was invoked. Used when an IPath + * corresponds to more than one root + */ public HashMap oldOtherRoots = new HashMap(); - - /* A table from IPath (a source attachment path from a classpath entry) to IPath (a root path) */ + + /* + * A table from IPath (a source attachment path from a classpath entry) to + * IPath (a root path) + */ public HashMap sourceAttachments = new HashMap(); /* Whether the roots tables should be recomputed */ public boolean rootsAreStale = true; - + /* Threads that are currently running initializeRoots() */ - private Set initializingThreads = Collections.synchronizedSet(new HashSet()); - + private Set initializingThreads = Collections + .synchronizedSet(new HashSet()); + public Hashtable externalTimeStamps = new Hashtable(); - + public HashMap projectUpdates = new HashMap(); public static class ProjectUpdateInfo { JavaProject project; + IClasspathEntry[] oldResolvedPath; + IClasspathEntry[] newResolvedPath; + IClasspathEntry[] newRawPath; - + /** - * Update projects references so that the build order is consistent with the classpath + * Update projects references so that the build order is consistent with + * the classpath */ - public void updateProjectReferencesIfNecessary() throws JavaModelException { - - String[] oldRequired = this.project.projectPrerequisites(this.oldResolvedPath); - + public void updateProjectReferencesIfNecessary() + throws JavaModelException { + + String[] oldRequired = this.project + .projectPrerequisites(this.oldResolvedPath); + if (this.newResolvedPath == null) { - this.newResolvedPath = this.project.getResolvedClasspath(this.newRawPath, null, true, true, null/*no reverse map*/); + this.newResolvedPath = this.project + .getResolvedClasspath(this.newRawPath, null, true, + true, null/* no reverse map */); } - String[] newRequired = this.project.projectPrerequisites(this.newResolvedPath); + String[] newRequired = this.project + .projectPrerequisites(this.newResolvedPath); try { IProject projectResource = this.project.getProject(); - IProjectDescription description = projectResource.getDescription(); - - IProject[] projectReferences = description.getDynamicReferences(); - + IProjectDescription description = projectResource + .getDescription(); + + IProject[] projectReferences = description + .getDynamicReferences(); + HashSet oldReferences = new HashSet(projectReferences.length); - for (int i = 0; i < projectReferences.length; i++){ + for (int i = 0; i < projectReferences.length; i++) { String projectName = projectReferences[i].getName(); oldReferences.add(projectName); } - HashSet newReferences = (HashSet)oldReferences.clone(); - - for (int i = 0; i < oldRequired.length; i++){ + HashSet newReferences = (HashSet) oldReferences.clone(); + + for (int i = 0; i < oldRequired.length; i++) { String projectName = oldRequired[i]; newReferences.remove(projectName); } - for (int i = 0; i < newRequired.length; i++){ + for (int i = 0; i < newRequired.length; i++) { String projectName = newRequired[i]; newReferences.add(projectName); } - + Iterator iter; int newSize = newReferences.size(); - + checkIdentity: { - if (oldReferences.size() == newSize){ + if (oldReferences.size() == newSize) { iter = newReferences.iterator(); - while (iter.hasNext()){ - if (!oldReferences.contains(iter.next())){ + while (iter.hasNext()) { + if (!oldReferences.contains(iter.next())) { break checkIdentity; } } @@ -141,53 +165,72 @@ public class DeltaProcessingState implements IResourceChangeListener { String[] requiredProjectNames = new String[newSize]; int index = 0; iter = newReferences.iterator(); - while (iter.hasNext()){ - requiredProjectNames[index++] = (String)iter.next(); + while (iter.hasNext()) { + requiredProjectNames[index++] = (String) iter.next(); } - Util.sort(requiredProjectNames); // ensure that if changed, the order is consistent - + Util.sort(requiredProjectNames); // ensure that if changed, + // the order is consistent + IProject[] requiredProjectArray = new IProject[newSize]; - IWorkspaceRoot wksRoot = projectResource.getWorkspace().getRoot(); - for (int i = 0; i < newSize; i++){ - requiredProjectArray[i] = wksRoot.getProject(requiredProjectNames[i]); + IWorkspaceRoot wksRoot = projectResource.getWorkspace() + .getRoot(); + for (int i = 0; i < newSize; i++) { + requiredProjectArray[i] = wksRoot + .getProject(requiredProjectNames[i]); } description.setDynamicReferences(requiredProjectArray); projectResource.setDescription(description, null); - - } catch(CoreException e){ + + } catch (CoreException e) { throw new JavaModelException(e); } } } - - + /** - * Workaround for bug 15168 circular errors not reported - * This is a cache of the projects before any project addition/deletion has started. + * Workaround for bug 15168 circular errors not reported This is a cache of + * the projects before any project addition/deletion has started. */ public IJavaProject[] modelProjectsCache; - + /* - * Need to clone defensively the listener information, in case some listener is reacting to some notification iteration by adding/changing/removing + * Need to clone defensively the listener information, in case some listener + * is reacting to some notification iteration by adding/changing/removing * any of the other (for example, if it deregisters itself). */ - public void addElementChangedListener(IElementChangedListener listener, int eventMask) { - for (int i = 0; i < this.elementChangedListenerCount; i++){ - if (this.elementChangedListeners[i].equals(listener)){ - - // only clone the masks, since we could be in the middle of notifications and one listener decide to change + public void addElementChangedListener(IElementChangedListener listener, + int eventMask) { + for (int i = 0; i < this.elementChangedListenerCount; i++) { + if (this.elementChangedListeners[i].equals(listener)) { + + // only clone the masks, since we could be in the middle of + // notifications and one listener decide to change // any event mask of another listeners (yet not notified). int cloneLength = this.elementChangedListenerMasks.length; - System.arraycopy(this.elementChangedListenerMasks, 0, this.elementChangedListenerMasks = new int[cloneLength], 0, cloneLength); - this.elementChangedListenerMasks[i] = eventMask; // could be different + System + .arraycopy( + this.elementChangedListenerMasks, + 0, + this.elementChangedListenerMasks = new int[cloneLength], + 0, cloneLength); + this.elementChangedListenerMasks[i] = eventMask; // could be + // different return; } } - // may need to grow, no need to clone, since iterators will have cached original arrays and max boundary and we only add to the end. + // may need to grow, no need to clone, since iterators will have cached + // original arrays and max boundary and we only add to the end. int length; - if ((length = this.elementChangedListeners.length) == this.elementChangedListenerCount){ - System.arraycopy(this.elementChangedListeners, 0, this.elementChangedListeners = new IElementChangedListener[length*2], 0, length); - System.arraycopy(this.elementChangedListenerMasks, 0, this.elementChangedListenerMasks = new int[length*2], 0, length); + if ((length = this.elementChangedListeners.length) == this.elementChangedListenerCount) { + System + .arraycopy( + this.elementChangedListeners, + 0, + this.elementChangedListeners = new IElementChangedListener[length * 2], + 0, length); + System.arraycopy(this.elementChangedListenerMasks, 0, + this.elementChangedListenerMasks = new int[length * 2], 0, + length); } this.elementChangedListeners[this.elementChangedListenerCount] = listener; this.elementChangedListenerMasks[this.elementChangedListenerCount] = eventMask; @@ -195,62 +238,78 @@ public class DeltaProcessingState implements IResourceChangeListener { } public void addPreResourceChangedListener(IResourceChangeListener listener) { - for (int i = 0; i < this.preResourceChangeListenerCount; i++){ + for (int i = 0; i < this.preResourceChangeListenerCount; i++) { if (this.preResourceChangeListeners[i].equals(listener)) { return; } } - // may need to grow, no need to clone, since iterators will have cached original arrays and max boundary and we only add to the end. + // may need to grow, no need to clone, since iterators will have cached + // original arrays and max boundary and we only add to the end. int length; - if ((length = this.preResourceChangeListeners.length) == this.preResourceChangeListenerCount){ - System.arraycopy(this.preResourceChangeListeners, 0, this.preResourceChangeListeners = new IResourceChangeListener[length*2], 0, length); + if ((length = this.preResourceChangeListeners.length) == this.preResourceChangeListenerCount) { + System + .arraycopy( + this.preResourceChangeListeners, + 0, + this.preResourceChangeListeners = new IResourceChangeListener[length * 2], + 0, length); } this.preResourceChangeListeners[this.preResourceChangeListenerCount] = listener; this.preResourceChangeListenerCount++; } public DeltaProcessor getDeltaProcessor() { - DeltaProcessor deltaProcessor = (DeltaProcessor)this.deltaProcessors.get(); - if (deltaProcessor != null) return deltaProcessor; - deltaProcessor = new DeltaProcessor(this, JavaModelManager.getJavaModelManager()); + DeltaProcessor deltaProcessor = (DeltaProcessor) this.deltaProcessors + .get(); + if (deltaProcessor != null) + return deltaProcessor; + deltaProcessor = new DeltaProcessor(this, JavaModelManager + .getJavaModelManager()); this.deltaProcessors.set(deltaProcessor); return deltaProcessor; } - public void performClasspathResourceChange(JavaProject project, IClasspathEntry[] oldResolvedPath, IClasspathEntry[] newResolvedPath, IClasspathEntry[] newRawPath, boolean canChangeResources) throws JavaModelException { - ProjectUpdateInfo info = new ProjectUpdateInfo(); - info.project = project; - info.oldResolvedPath = oldResolvedPath; - info.newResolvedPath = newResolvedPath; - info.newRawPath = newRawPath; - if (canChangeResources) { - this.projectUpdates.remove(project); // remove possibly awaiting one - info.updateProjectReferencesIfNecessary(); - return; - } - this.recordProjectUpdate(info); + public void performClasspathResourceChange(JavaProject project, + IClasspathEntry[] oldResolvedPath, + IClasspathEntry[] newResolvedPath, IClasspathEntry[] newRawPath, + boolean canChangeResources) throws JavaModelException { + ProjectUpdateInfo info = new ProjectUpdateInfo(); + info.project = project; + info.oldResolvedPath = oldResolvedPath; + info.newResolvedPath = newResolvedPath; + info.newRawPath = newRawPath; + if (canChangeResources) { + this.projectUpdates.remove(project); // remove possibly awaiting + // one + info.updateProjectReferencesIfNecessary(); + return; + } + this.recordProjectUpdate(info); } - + public void initializeRoots() { - + // recompute root infos only if necessary HashMap newRoots = null; HashMap newOtherRoots = null; HashMap newSourceAttachments = null; if (this.rootsAreStale) { Thread currentThread = Thread.currentThread(); - boolean addedCurrentThread = false; + boolean addedCurrentThread = false; try { - // if reentering initialization (through a container initializer for example) no need to compute roots again + // if reentering initialization (through a container initializer + // for example) no need to compute roots again // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=47213 - if (!this.initializingThreads.add(currentThread)) return; + if (!this.initializingThreads.add(currentThread)) + return; addedCurrentThread = true; newRoots = new HashMap(); newOtherRoots = new HashMap(); newSourceAttachments = new HashMap(); - - IJavaModel model = JavaModelManager.getJavaModelManager().getJavaModel(); + + IJavaModel model = JavaModelManager.getJavaModelManager() + .getJavaModel(); IJavaProject[] projects; try { projects = model.getJavaProjects(); @@ -260,50 +319,69 @@ public class DeltaProcessingState implements IResourceChangeListener { } for (int i = 0, length = projects.length; i < length; i++) { JavaProject project = (JavaProject) projects[i]; -// IClasspathEntry[] classpath; -// try { -// classpath = project.getResolvedClasspath(true/*ignoreUnresolvedEntry*/, false/*don't generateMarkerOnError*/, false/*don't returnResolutionInProgress*/); -// } catch (JavaModelException e) { -// // continue with next project -// continue; -// } -// for (int j= 0, classpathLength = classpath.length; j < classpathLength; j++) { -// IClasspathEntry entry = classpath[j]; -// if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) continue; -// -// // root path -// IPath path = entry.getPath(); -// if (newRoots.get(path) == null) { -// newRoots.put(path, new DeltaProcessor.RootInfo(project, path, ((ClasspathEntry)entry).fullInclusionPatternChars(), ((ClasspathEntry)entry).fullExclusionPatternChars(), entry.getEntryKind())); -// } else { -// ArrayList rootList = (ArrayList)newOtherRoots.get(path); -// if (rootList == null) { -// rootList = new ArrayList(); -// newOtherRoots.put(path, rootList); -// } -// rootList.add(new DeltaProcessor.RootInfo(project, path, ((ClasspathEntry)entry).fullInclusionPatternChars(), ((ClasspathEntry)entry).fullExclusionPatternChars(), entry.getEntryKind())); -// } -// -// // source attachment path -// if (entry.getEntryKind() != IClasspathEntry.CPE_LIBRARY) continue; -// QualifiedName qName = new QualifiedName(JavaCore.PLUGIN_ID, "sourceattachment: " + path.toOSString()); //$NON-NLS-1$; -// String propertyString = null; -// try { -// propertyString = ResourcesPlugin.getWorkspace().getRoot().getPersistentProperty(qName); -// } catch (CoreException e) { -// continue; -// } -// IPath sourceAttachmentPath; -// if (propertyString != null) { -// int index= propertyString.lastIndexOf(PackageFragmentRoot.ATTACHMENT_PROPERTY_DELIMITER); -// sourceAttachmentPath = (index < 0) ? new Path(propertyString) : new Path(propertyString.substring(0, index)); -// } else { -// sourceAttachmentPath = entry.getSourceAttachmentPath(); -// } -// if (sourceAttachmentPath != null) { -// newSourceAttachments.put(sourceAttachmentPath, path); -// } -// } + // IClasspathEntry[] classpath; + // try { + // classpath = + // project.getResolvedClasspath(true/*ignoreUnresolvedEntry*/, + // false/*don't generateMarkerOnError*/, false/*don't + // returnResolutionInProgress*/); + // } catch (JavaModelException e) { + // // continue with next project + // continue; + // } + // for (int j= 0, classpathLength = classpath.length; j < + // classpathLength; j++) { + // IClasspathEntry entry = classpath[j]; + // if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) + // continue; + // + // // root path + // IPath path = entry.getPath(); + // if (newRoots.get(path) == null) { + // newRoots.put(path, new DeltaProcessor.RootInfo(project, + // path, + // ((ClasspathEntry)entry).fullInclusionPatternChars(), + // ((ClasspathEntry)entry).fullExclusionPatternChars(), + // entry.getEntryKind())); + // } else { + // ArrayList rootList = (ArrayList)newOtherRoots.get(path); + // if (rootList == null) { + // rootList = new ArrayList(); + // newOtherRoots.put(path, rootList); + // } + // rootList.add(new DeltaProcessor.RootInfo(project, path, + // ((ClasspathEntry)entry).fullInclusionPatternChars(), + // ((ClasspathEntry)entry).fullExclusionPatternChars(), + // entry.getEntryKind())); + // } + // + // // source attachment path + // if (entry.getEntryKind() != IClasspathEntry.CPE_LIBRARY) + // continue; + // QualifiedName qName = new + // QualifiedName(JavaCore.PLUGIN_ID, "sourceattachment: " + + // path.toOSString()); //$NON-NLS-1$; + // String propertyString = null; + // try { + // propertyString = + // ResourcesPlugin.getWorkspace().getRoot().getPersistentProperty(qName); + // } catch (CoreException e) { + // continue; + // } + // IPath sourceAttachmentPath; + // if (propertyString != null) { + // int index= + // propertyString.lastIndexOf(PackageFragmentRoot.ATTACHMENT_PROPERTY_DELIMITER); + // sourceAttachmentPath = (index < 0) ? new + // Path(propertyString) : new + // Path(propertyString.substring(0, index)); + // } else { + // sourceAttachmentPath = entry.getSourceAttachmentPath(); + // } + // if (sourceAttachmentPath != null) { + // newSourceAttachments.put(sourceAttachmentPath, path); + // } + // } } } finally { if (addedCurrentThread) { @@ -311,10 +389,11 @@ public class DeltaProcessingState implements IResourceChangeListener { } } } - synchronized(this) { + synchronized (this) { this.oldRoots = this.roots; - this.oldOtherRoots = this.otherRoots; - if (this.rootsAreStale && newRoots != null) { // double check again + this.oldOtherRoots = this.otherRoots; + if (this.rootsAreStale && newRoots != null) { // double check + // again this.roots = newRoots; this.otherRoots = newOtherRoots; this.sourceAttachments = newSourceAttachments; @@ -324,46 +403,55 @@ public class DeltaProcessingState implements IResourceChangeListener { } public synchronized void recordProjectUpdate(ProjectUpdateInfo newInfo) { - - JavaProject project = newInfo.project; - ProjectUpdateInfo oldInfo = (ProjectUpdateInfo) this.projectUpdates.get(project); - if (oldInfo != null) { // refresh new classpath information - oldInfo.newRawPath = newInfo.newRawPath; - oldInfo.newResolvedPath = newInfo.newResolvedPath; - } else { - this.projectUpdates.put(project, newInfo); - } + + JavaProject project = newInfo.project; + ProjectUpdateInfo oldInfo = (ProjectUpdateInfo) this.projectUpdates + .get(project); + if (oldInfo != null) { // refresh new classpath information + oldInfo.newRawPath = newInfo.newRawPath; + oldInfo.newResolvedPath = newInfo.newResolvedPath; + } else { + this.projectUpdates.put(project, newInfo); + } } + public synchronized ProjectUpdateInfo[] removeAllProjectUpdates() { - int length = this.projectUpdates.size(); - if (length == 0) return null; - ProjectUpdateInfo[] updates = new ProjectUpdateInfo[length]; - this.projectUpdates.values().toArray(updates); - this.projectUpdates.clear(); - return updates; + int length = this.projectUpdates.size(); + if (length == 0) + return null; + ProjectUpdateInfo[] updates = new ProjectUpdateInfo[length]; + this.projectUpdates.values().toArray(updates); + this.projectUpdates.clear(); + return updates; } - + public void removeElementChangedListener(IElementChangedListener listener) { - - for (int i = 0; i < this.elementChangedListenerCount; i++){ - - if (this.elementChangedListeners[i].equals(listener)){ - - // need to clone defensively since we might be in the middle of listener notifications (#fire) + + for (int i = 0; i < this.elementChangedListenerCount; i++) { + + if (this.elementChangedListeners[i].equals(listener)) { + + // need to clone defensively since we might be in the middle of + // listener notifications (#fire) int length = this.elementChangedListeners.length; IElementChangedListener[] newListeners = new IElementChangedListener[length]; - System.arraycopy(this.elementChangedListeners, 0, newListeners, 0, i); + System.arraycopy(this.elementChangedListeners, 0, newListeners, + 0, i); int[] newMasks = new int[length]; - System.arraycopy(this.elementChangedListenerMasks, 0, newMasks, 0, i); - + System.arraycopy(this.elementChangedListenerMasks, 0, newMasks, + 0, i); + // copy trailing listeners int trailingLength = this.elementChangedListenerCount - i - 1; - if (trailingLength > 0){ - System.arraycopy(this.elementChangedListeners, i+1, newListeners, i, trailingLength); - System.arraycopy(this.elementChangedListenerMasks, i+1, newMasks, i, trailingLength); + if (trailingLength > 0) { + System.arraycopy(this.elementChangedListeners, i + 1, + newListeners, i, trailingLength); + System.arraycopy(this.elementChangedListenerMasks, i + 1, + newMasks, i, trailingLength); } - - // update manager listener state (#fire need to iterate over original listeners through a local variable to hold onto + + // update manager listener state (#fire need to iterate over + // original listeners through a local variable to hold onto // the original ones) this.elementChangedListeners = newListeners; this.elementChangedListenerMasks = newMasks; @@ -373,24 +461,30 @@ public class DeltaProcessingState implements IResourceChangeListener { } } - public void removePreResourceChangedListener(IResourceChangeListener listener) { - - for (int i = 0; i < this.preResourceChangeListenerCount; i++){ - - if (this.preResourceChangeListeners[i].equals(listener)){ - - // need to clone defensively since we might be in the middle of listener notifications (#fire) + public void removePreResourceChangedListener( + IResourceChangeListener listener) { + + for (int i = 0; i < this.preResourceChangeListenerCount; i++) { + + if (this.preResourceChangeListeners[i].equals(listener)) { + + // need to clone defensively since we might be in the middle of + // listener notifications (#fire) int length = this.preResourceChangeListeners.length; IResourceChangeListener[] newListeners = new IResourceChangeListener[length]; - System.arraycopy(this.preResourceChangeListeners, 0, newListeners, 0, i); - + System.arraycopy(this.preResourceChangeListeners, 0, + newListeners, 0, i); + // copy trailing listeners - int trailingLength = this.preResourceChangeListenerCount - i - 1; - if (trailingLength > 0){ - System.arraycopy(this.preResourceChangeListeners, i+1, newListeners, i, trailingLength); + int trailingLength = this.preResourceChangeListenerCount - i + - 1; + if (trailingLength > 0) { + System.arraycopy(this.preResourceChangeListeners, i + 1, + newListeners, i, trailingLength); } - - // update manager listener state (#fire need to iterate over original listeners through a local variable to hold onto + + // update manager listener state (#fire need to iterate over + // original listeners through a local variable to hold onto // the original ones) this.preResourceChangeListeners = newListeners; this.preResourceChangeListenerCount--; @@ -403,12 +497,16 @@ public class DeltaProcessingState implements IResourceChangeListener { boolean isPostChange = event.getType() == IResourceChangeEvent.POST_CHANGE; if (isPostChange) { for (int i = 0; i < this.preResourceChangeListenerCount; i++) { - // wrap callbacks with Safe runnable for subsequent listeners to be called when some are causing grief + // wrap callbacks with Safe runnable for subsequent listeners to + // be called when some are causing grief final IResourceChangeListener listener = this.preResourceChangeListeners[i]; Platform.run(new ISafeRunnable() { public void handleException(Throwable exception) { - Util.log(exception, "Exception occurred in listener of pre Java resource change notification"); //$NON-NLS-1$ + Util + .log(exception, + "Exception occurred in listener of pre Java resource change notification"); //$NON-NLS-1$ } + public void run() throws Exception { listener.resourceChanged(event); } @@ -418,51 +516,59 @@ public class DeltaProcessingState implements IResourceChangeListener { try { getDeltaProcessor().resourceChanged(event); } finally { - // TODO (jerome) see 47631, may want to get rid of following so as to reuse delta processor ? + // TODO (jerome) see 47631, may want to get rid of following so as + // to reuse delta processor ? if (isPostChange) { this.deltaProcessors.set(null); } } } - + /* - * Update the roots that are affected by the addition or the removal of the given container resource. + * Update the roots that are affected by the addition or the removal of the + * given container resource. */ -// public synchronized void updateRoots(IPath containerPath, IResourceDelta containerDelta, DeltaProcessor deltaProcessor) { -// Map updatedRoots; -// Map otherUpdatedRoots; -// if (containerDelta.getKind() == IResourceDelta.REMOVED) { -// updatedRoots = this.oldRoots; -// otherUpdatedRoots = this.oldOtherRoots; -// } else { -// updatedRoots = this.roots; -// otherUpdatedRoots = this.otherRoots; -// } -// Iterator iterator = updatedRoots.keySet().iterator(); -// while (iterator.hasNext()) { -// IPath path = (IPath)iterator.next(); -// if (containerPath.isPrefixOf(path) && !containerPath.equals(path)) { -// IResourceDelta rootDelta = containerDelta.findMember(path.removeFirstSegments(1)); -// if (rootDelta == null) continue; -// DeltaProcessor.RootInfo rootInfo = (DeltaProcessor.RootInfo)updatedRoots.get(path); -// -// if (!rootInfo.project.getPath().isPrefixOf(path)) { // only consider roots that are not included in the container -// deltaProcessor.updateCurrentDeltaAndIndex(rootDelta, IJavaElement.PACKAGE_FRAGMENT_ROOT, rootInfo); -// } -// -// ArrayList rootList = (ArrayList)otherUpdatedRoots.get(path); -// if (rootList != null) { -// Iterator otherProjects = rootList.iterator(); -// while (otherProjects.hasNext()) { -// rootInfo = (DeltaProcessor.RootInfo)otherProjects.next(); -// if (!rootInfo.project.getPath().isPrefixOf(path)) { // only consider roots that are not included in the container -// deltaProcessor.updateCurrentDeltaAndIndex(rootDelta, IJavaElement.PACKAGE_FRAGMENT_ROOT, rootInfo); -// } -// } -// } -// } -// } -// } - + // public synchronized void updateRoots(IPath containerPath, IResourceDelta + // containerDelta, DeltaProcessor deltaProcessor) { + // Map updatedRoots; + // Map otherUpdatedRoots; + // if (containerDelta.getKind() == IResourceDelta.REMOVED) { + // updatedRoots = this.oldRoots; + // otherUpdatedRoots = this.oldOtherRoots; + // } else { + // updatedRoots = this.roots; + // otherUpdatedRoots = this.otherRoots; + // } + // Iterator iterator = updatedRoots.keySet().iterator(); + // while (iterator.hasNext()) { + // IPath path = (IPath)iterator.next(); + // if (containerPath.isPrefixOf(path) && !containerPath.equals(path)) { + // IResourceDelta rootDelta = + // containerDelta.findMember(path.removeFirstSegments(1)); + // if (rootDelta == null) continue; + // DeltaProcessor.RootInfo rootInfo = + // (DeltaProcessor.RootInfo)updatedRoots.get(path); + // + // if (!rootInfo.project.getPath().isPrefixOf(path)) { // only consider + // roots that are not included in the container + // deltaProcessor.updateCurrentDeltaAndIndex(rootDelta, + // IJavaElement.PACKAGE_FRAGMENT_ROOT, rootInfo); + // } + // + // ArrayList rootList = (ArrayList)otherUpdatedRoots.get(path); + // if (rootList != null) { + // Iterator otherProjects = rootList.iterator(); + // while (otherProjects.hasNext()) { + // rootInfo = (DeltaProcessor.RootInfo)otherProjects.next(); + // if (!rootInfo.project.getPath().isPrefixOf(path)) { // only consider + // roots that are not included in the container + // deltaProcessor.updateCurrentDeltaAndIndex(rootDelta, + // IJavaElement.PACKAGE_FRAGMENT_ROOT, rootInfo); + // } + // } + // } + // } + // } + // } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DeltaProcessor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DeltaProcessor.java index 41d5e07..eacba58 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DeltaProcessor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DeltaProcessor.java @@ -47,68 +47,92 @@ import org.eclipse.core.runtime.ISafeRunnable; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.QualifiedName; - /** * This class is used by JavaModelManager to convert - * IResourceDeltas into IJavaElementDeltas. - * It also does some processing on the JavaElements involved - * (e.g. closing them or updating classpaths). + * IResourceDeltas into IJavaElementDeltas. It + * also does some processing on the JavaElements involved (e.g. + * closing them or updating classpaths). */ public class DeltaProcessor implements IResourceChangeListener { - + final static int IGNORE = 0; + final static int SOURCE = 1; + final static int BINARY = 2; - + final static String EXTERNAL_JAR_ADDED = "external jar added"; //$NON-NLS-1$ + final static String EXTERNAL_JAR_REMOVED = "external jar removed"; //$NON-NLS-1$ + final static String EXTERNAL_JAR_CHANGED = "external jar changed"; //$NON-NLS-1$ + final static String EXTERNAL_JAR_UNCHANGED = "external jar unchanged"; //$NON-NLS-1$ + final static String INTERNAL_JAR_IGNORE = "internal jar ignore"; //$NON-NLS-1$ - + private final static int NON_JAVA_RESOURCE = -1; + public static boolean DEBUG = false; + public static boolean VERBOSE = false; - - public static final int DEFAULT_CHANGE_EVENT = 0; // must not collide with ElementChangedEvent event masks + + public static final int DEFAULT_CHANGE_EVENT = 0; // must not collide with + // ElementChangedEvent + // event masks + /** - * The JavaElementDelta corresponding to the IResourceDelta being translated. + * The JavaElementDelta corresponding to the + * IResourceDelta being translated. */ protected JavaElementDelta currentDelta; - -// protected IndexManager indexManager = new IndexManager(); - + + // protected IndexManager indexManager = new IndexManager(); + /* A table from IPath (from a classpath entry) to RootInfo */ public Map roots; - - /* A table from IPath (from a classpath entry) to ArrayList of RootInfo - * Used when an IPath corresponds to more than one root */ + + /* + * A table from IPath (from a classpath entry) to ArrayList of RootInfo Used + * when an IPath corresponds to more than one root + */ Map otherRoots; - + /* Whether the roots tables should be recomputed */ public boolean rootsAreStale = true; - - /* A table from IPath (from a classpath entry) to RootInfo - * from the last time the delta processor was invoked. */ + + /* + * A table from IPath (from a classpath entry) to RootInfo from the last + * time the delta processor was invoked. + */ public Map oldRoots; - /* A table from IPath (from a classpath entry) to ArrayList of RootInfo - * from the last time the delta processor was invoked. - * Used when an IPath corresponds to more than one root */ + /* + * A table from IPath (from a classpath entry) to ArrayList of RootInfo from + * the last time the delta processor was invoked. Used when an IPath + * corresponds to more than one root + */ Map oldOtherRoots; - - /* A table from IPath (a source attachment path from a classpath entry) to IPath (a root path) */ + + /* + * A table from IPath (a source attachment path from a classpath entry) to + * IPath (a root path) + */ Map sourceAttachments; - /* The java element that was last created (see createElement(IResource)). - * This is used as a stack of java elements (using getParent() to pop it, and - * using the various get*(...) to push it. */ + /* + * The java element that was last created (see createElement(IResource)). + * This is used as a stack of java elements (using getParent() to pop it, + * and using the various get*(...) to push it. + */ Openable currentElement; + /* - * Queue of deltas created explicily by the Java Model that - * have yet to be fired. + * Queue of deltas created explicily by the Java Model that have yet to be + * fired. */ - public ArrayList javaModelDeltas= new ArrayList(); + public ArrayList javaModelDeltas = new ArrayList(); + /* * Queue of reconcile deltas on working copies that have yet to be fired. * This is a table form IWorkingCopy to IJavaElementDelta @@ -118,84 +142,100 @@ public class DeltaProcessor implements IResourceChangeListener { /* * Turns delta firing on/off. By default it is on. */ - private boolean isFiring= true; - - + private boolean isFiring = true; + public HashMap externalTimeStamps = new HashMap(); + public HashSet projectsToUpdate = new HashSet(); - // list of root projects which namelookup caches need to be updated for dependents + + // list of root projects which namelookup caches need to be updated for + // dependents // TODO: (jerome) is it needed? projectsToUpdate might be sufficient - public HashSet projectsForDependentNamelookupRefresh = new HashSet(); - + public HashSet projectsForDependentNamelookupRefresh = new HashSet(); + /* * The global state of delta processing. */ private DeltaProcessingState state; - + /* * The Java model manager */ private JavaModelManager manager; - - /* A table from IJavaProject to an array of IPackageFragmentRoot. - * This table contains the pkg fragment roots of the project that are being deleted. + + /* + * A table from IJavaProject to an array of IPackageFragmentRoot. This table + * contains the pkg fragment roots of the project that are being deleted. */ Map removedRoots; - + /* - * A list of IJavaElement used as a scope for external archives refresh during POST_CHANGE. - * This is null if no refresh is needed. + * A list of IJavaElement used as a scope for external archives refresh + * during POST_CHANGE. This is null if no refresh is needed. */ HashSet refreshedElements; - + class OutputsInfo { IPath[] paths; + int[] traverseModes; + int outputCount; + OutputsInfo(IPath[] paths, int[] traverseModes, int outputCount) { this.paths = paths; this.traverseModes = traverseModes; this.outputCount = outputCount; } + public String toString() { - if (this.paths == null) return ""; //$NON-NLS-1$ + if (this.paths == null) + return ""; //$NON-NLS-1$ StringBuffer buffer = new StringBuffer(); for (int i = 0; i < this.outputCount; i++) { buffer.append("path="); //$NON-NLS-1$ buffer.append(this.paths[i].toString()); buffer.append("\n->traverse="); //$NON-NLS-1$ switch (this.traverseModes[i]) { - case BINARY: - buffer.append("BINARY"); //$NON-NLS-1$ - break; - case IGNORE: - buffer.append("IGNORE"); //$NON-NLS-1$ - break; - case SOURCE: - buffer.append("SOURCE"); //$NON-NLS-1$ - break; - default: - buffer.append(""); //$NON-NLS-1$ + case BINARY: + buffer.append("BINARY"); //$NON-NLS-1$ + break; + case IGNORE: + buffer.append("IGNORE"); //$NON-NLS-1$ + break; + case SOURCE: + buffer.append("SOURCE"); //$NON-NLS-1$ + break; + default: + buffer.append(""); //$NON-NLS-1$ } - if (i+1 < this.outputCount) { + if (i + 1 < this.outputCount) { buffer.append('\n'); } } return buffer.toString(); } } + class RootInfo { IJavaProject project; + IPath rootPath; + char[][] exclusionPatterns; - RootInfo(IJavaProject project, IPath rootPath, char[][] exclusionPatterns) { + + RootInfo(IJavaProject project, IPath rootPath, + char[][] exclusionPatterns) { this.project = project; this.rootPath = rootPath; this.exclusionPatterns = exclusionPatterns; } + boolean isRootOfProject(IPath path) { - return this.rootPath.equals(path) && this.project.getProject().getFullPath().isPrefixOf(path); + return this.rootPath.equals(path) + && this.project.getProject().getFullPath().isPrefixOf(path); } + public String toString() { StringBuffer buffer = new StringBuffer("project="); //$NON-NLS-1$ if (this.project == null) { @@ -215,7 +255,7 @@ public class DeltaProcessor implements IResourceChangeListener { } else { for (int i = 0, length = this.exclusionPatterns.length; i < length; i++) { buffer.append(new String(this.exclusionPatterns[i])); - if (i < length-1) { + if (i < length - 1) { buffer.append("|"); //$NON-NLS-1$ } } @@ -224,42 +264,46 @@ public class DeltaProcessor implements IResourceChangeListener { } } -// DeltaProcessor(JavaModelManager manager) { -// this.manager = manager; -// } + // DeltaProcessor(JavaModelManager manager) { + // this.manager = manager; + // } /* - * Type of event that should be processed no matter what the real event type is. + * Type of event that should be processed no matter what the real event type + * is. */ public int overridenEventType = -1; - + public DeltaProcessor(DeltaProcessingState state, JavaModelManager manager) { this.state = state; this.manager = manager; } + /* - * Adds the dependents of the given project to the list of the projects - * to update. + * Adds the dependents of the given project to the list of the projects to + * update. */ -// void addDependentProjects(IPath projectPath, HashSet result) { -// try { -// IJavaProject[] projects = this.manager.getJavaModel().getJavaProjects(); -// for (int i = 0, length = projects.length; i < length; i++) { -// IJavaProject project = projects[i]; -// IClasspathEntry[] classpath = ((JavaProject)project).getExpandedClasspath(true); -// for (int j = 0, length2 = classpath.length; j < length2; j++) { -// IClasspathEntry entry = classpath[j]; -// if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT -// && entry.getPath().equals(projectPath)) { -// result.add(project); -// } -// } -// } -// } catch (JavaModelException e) { -// } -// } + // void addDependentProjects(IPath projectPath, HashSet result) { + // try { + // IJavaProject[] projects = this.manager.getJavaModel().getJavaProjects(); + // for (int i = 0, length = projects.length; i < length; i++) { + // IJavaProject project = projects[i]; + // IClasspathEntry[] classpath = + // ((JavaProject)project).getExpandedClasspath(true); + // for (int j = 0, length2 = classpath.length; j < length2; j++) { + // IClasspathEntry entry = classpath[j]; + // if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT + // && entry.getPath().equals(projectPath)) { + // result.add(project); + // } + // } + // } + // } catch (JavaModelException e) { + // } + // } /* - * Adds the given element to the list of elements used as a scope for external jars refresh. + * Adds the given element to the list of elements used as a scope for + * external jars refresh. */ public void addForRefresh(IJavaElement element) { if (this.refreshedElements == null) { @@ -267,24 +311,27 @@ public class DeltaProcessor implements IResourceChangeListener { } this.refreshedElements.add(element); } + /* - * Adds the given project and its dependents to the list of the projects - * to update. + * Adds the given project and its dependents to the list of the projects to + * update. */ void addToProjectsToUpdateWithDependents(IProject project) { this.projectsToUpdate.add(JavaCore.create(project)); -// this.addDependentProjects(project.getFullPath(), this.projectsToUpdate); + // this.addDependentProjects(project.getFullPath(), + // this.projectsToUpdate); } - + /** - * Adds the given child handle to its parent's cache of children. + * Adds the given child handle to its parent's cache of children. */ protected void addToParentInfo(Openable child) { Openable parent = (Openable) child.getParent(); if (parent != null && parent.isOpen()) { try { - JavaElementInfo info = (JavaElementInfo)parent.getElementInfo(); + JavaElementInfo info = (JavaElementInfo) parent + .getElementInfo(); info.addChild(child); } catch (JavaModelException e) { // do nothing - we already checked if open @@ -293,817 +340,873 @@ public class DeltaProcessor implements IResourceChangeListener { } /** - * Check all external archive (referenced by given roots, projects or model) status and issue a corresponding root delta. - * Also triggers index updates + * Check all external archive (referenced by given roots, projects or model) + * status and issue a corresponding root delta. Also triggers index updates */ -// public void checkExternalArchiveChanges(IJavaElement[] refreshedElements, IProgressMonitor monitor) throws JavaModelException { -// try { -// for (int i = 0, length = refreshedElements.length; i < length; i++) { -// this.addForRefresh(refreshedElements[i]); -// } -// boolean hasDelta = this.createExternalArchiveDelta(monitor); -// if (monitor != null && monitor.isCanceled()) return; -// if (hasDelta){ -// // force classpath marker refresh of affected projects -// JavaModel.flushExternalFileCache(); -// IJavaElementDelta[] projectDeltas = this.currentDelta.getAffectedChildren(); -// for (int i = 0, length = projectDeltas.length; i < length; i++) { -// IJavaElementDelta delta = projectDeltas[i]; -// ((JavaProject)delta.getElement()).getResolvedClasspath( -// true, // ignoreUnresolvedEntry -// true); // generateMarkerOnError -// } -// if (this.currentDelta != null) { // if delta has not been fired while creating markers -// this.manager.fire(this.currentDelta, JavaModelManager.DEFAULT_CHANGE_EVENT); -// } -// } -// } finally { -// this.currentDelta = null; -// if (monitor != null) monitor.done(); -// } -// } + // public void checkExternalArchiveChanges(IJavaElement[] refreshedElements, + // IProgressMonitor monitor) throws JavaModelException { + // try { + // for (int i = 0, length = refreshedElements.length; i < length; i++) { + // this.addForRefresh(refreshedElements[i]); + // } + // boolean hasDelta = this.createExternalArchiveDelta(monitor); + // if (monitor != null && monitor.isCanceled()) return; + // if (hasDelta){ + // // force classpath marker refresh of affected projects + // JavaModel.flushExternalFileCache(); + // IJavaElementDelta[] projectDeltas = + // this.currentDelta.getAffectedChildren(); + // for (int i = 0, length = projectDeltas.length; i < length; i++) { + // IJavaElementDelta delta = projectDeltas[i]; + // ((JavaProject)delta.getElement()).getResolvedClasspath( + // true, // ignoreUnresolvedEntry + // true); // generateMarkerOnError + // } + // if (this.currentDelta != null) { // if delta has not been fired while + // creating markers + // this.manager.fire(this.currentDelta, + // JavaModelManager.DEFAULT_CHANGE_EVENT); + // } + // } + // } finally { + // this.currentDelta = null; + // if (monitor != null) monitor.done(); + // } + // } /* - * Check if external archives have changed and create the corresponding deltas. - * Returns whether at least on delta was created. + * Check if external archives have changed and create the corresponding + * deltas. Returns whether at least on delta was created. */ -// public boolean createExternalArchiveDelta(IProgressMonitor monitor) throws JavaModelException { -// -// if (this.refreshedElements == null) return false; -// -// HashMap externalArchivesStatus = new HashMap(); -// boolean hasDelta = false; -// -// // find JARs to refresh -// HashSet archivePathsToRefresh = new HashSet(); -// try { -// Iterator iterator = this.refreshedElements.iterator(); -// while (iterator.hasNext()) { -// IJavaElement element = (IJavaElement)iterator.next(); -// switch(element.getElementType()){ -// case IJavaElement.PACKAGE_FRAGMENT_ROOT : -// archivePathsToRefresh.add(element.getPath()); -// break; -// case IJavaElement.JAVA_PROJECT : -// IJavaProject project = (IJavaProject) element; -// if (!JavaProject.hasJavaNature(project.getProject())) { -// // project is not accessible or has lost its Java nature -// break; -// } -// IClasspathEntry[] classpath = project.getResolvedClasspath(true); -// for (int j = 0, cpLength = classpath.length; j < cpLength; j++){ -// if (classpath[j].getEntryKind() == IClasspathEntry.CPE_LIBRARY){ -// archivePathsToRefresh.add(classpath[j].getPath()); -// } -// } -// break; -// case IJavaElement.JAVA_MODEL : -// IJavaProject[] projects = manager.getJavaModel().getOldJavaProjectsList(); -// for (int j = 0, projectsLength = projects.length; j < projectsLength; j++){ -// project = projects[j]; -// if (!JavaProject.hasJavaNature(project.getProject())) { -// // project is not accessible or has lost its Java nature -// continue; -// } -// classpath = project.getResolvedClasspath(true); -// for (int k = 0, cpLength = classpath.length; k < cpLength; k++){ -// if (classpath[k].getEntryKind() == IClasspathEntry.CPE_LIBRARY){ -// archivePathsToRefresh.add(classpath[k].getPath()); -// } -// } -// } -// break; -// } -// } -// } finally { -// this.refreshedElements = null; -// } -// -// // perform refresh -// IJavaProject[] projects = manager.getJavaModel().getOldJavaProjectsList(); -// IWorkspaceRoot wksRoot = ResourcesPlugin.getWorkspace().getRoot(); -// for (int i = 0, length = projects.length; i < length; i++) { -// -// if (monitor != null && monitor.isCanceled()) break; -// -// IJavaProject project = projects[i]; -// if (!JavaProject.hasJavaNature(project.getProject())) { -// // project is not accessible or has lost its Java nature -// continue; -// } -// IClasspathEntry[] entries = project.getResolvedClasspath(true); -// for (int j = 0; j < entries.length; j++){ -// if (entries[j].getEntryKind() == IClasspathEntry.CPE_LIBRARY) { -// -// IPath entryPath = entries[j].getPath(); -// -// if (!archivePathsToRefresh.contains(entryPath)) continue; // not supposed to be refreshed -// -// String status = (String)externalArchivesStatus.get(entryPath); -// if (status == null){ -// -// // compute shared status -// Object targetLibrary = JavaModel.getTarget(wksRoot, entryPath, true); -// -// if (targetLibrary == null){ // missing JAR -// if (this.externalTimeStamps.containsKey(entryPath)){ -// this.externalTimeStamps.remove(entryPath); -// externalArchivesStatus.put(entryPath, EXTERNAL_JAR_REMOVED); -// // the jar was physically removed: remove the index -// indexManager.removeIndex(entryPath); -// } -// -// } else if (targetLibrary instanceof File){ // external JAR -// -// File externalFile = (File)targetLibrary; -// -// // check timestamp to figure if JAR has changed in some way -// Long oldTimestamp =(Long) this.externalTimeStamps.get(entryPath); -// long newTimeStamp = getTimeStamp(externalFile); -// if (oldTimestamp != null){ -// -// if (newTimeStamp == 0){ // file doesn't exist -// externalArchivesStatus.put(entryPath, EXTERNAL_JAR_REMOVED); -// this.externalTimeStamps.remove(entryPath); -// // remove the index -// indexManager.removeIndex(entryPath); -// -// } else if (oldTimestamp.longValue() != newTimeStamp){ -// externalArchivesStatus.put(entryPath, EXTERNAL_JAR_CHANGED); -// this.externalTimeStamps.put(entryPath, new Long(newTimeStamp)); -// // first remove the index so that it is forced to be re-indexed -// indexManager.removeIndex(entryPath); -// // then index the jar -// indexManager.indexLibrary(entryPath, project.getProject()); -// } else { -// externalArchivesStatus.put(entryPath, EXTERNAL_JAR_UNCHANGED); -// } -// } else { -// if (newTimeStamp == 0){ // jar still doesn't exist -// externalArchivesStatus.put(entryPath, EXTERNAL_JAR_UNCHANGED); -// } else { -// externalArchivesStatus.put(entryPath, EXTERNAL_JAR_ADDED); -// this.externalTimeStamps.put(entryPath, new Long(newTimeStamp)); -// // index the new jar -// indexManager.indexLibrary(entryPath, project.getProject()); -// } -// } -// } else { // internal JAR -// externalArchivesStatus.put(entryPath, INTERNAL_JAR_IGNORE); -// } -// } -// // according to computed status, generate a delta -// status = (String)externalArchivesStatus.get(entryPath); -// if (status != null){ -// if (status == EXTERNAL_JAR_ADDED){ -// PackageFragmentRoot root = (PackageFragmentRoot)project.getPackageFragmentRoot(entryPath.toString()); -// if (VERBOSE){ -// System.out.println("- External JAR ADDED, affecting root: "+root.getElementName()); //$NON-NLS-1$ -// } -// elementAdded(root, null, null); -// hasDelta = true; -// } else if (status == EXTERNAL_JAR_CHANGED) { -// PackageFragmentRoot root = (PackageFragmentRoot)project.getPackageFragmentRoot(entryPath.toString()); -// if (VERBOSE){ -// System.out.println("- External JAR CHANGED, affecting root: "+root.getElementName()); //$NON-NLS-1$ -// } -// // reset the corresponding project built state, since the builder would miss this change -// this.manager.setLastBuiltState(project.getProject(), null /*no state*/); -// contentChanged(root, null); -// hasDelta = true; -// } else if (status == EXTERNAL_JAR_REMOVED) { -// PackageFragmentRoot root = (PackageFragmentRoot)project.getPackageFragmentRoot(entryPath.toString()); -// if (VERBOSE){ -// System.out.println("- External JAR REMOVED, affecting root: "+root.getElementName()); //$NON-NLS-1$ -// } -// elementRemoved(root, null, null); -// hasDelta = true; -// } -// } -// } -// } -// } -// return hasDelta; -// } + // public boolean createExternalArchiveDelta(IProgressMonitor monitor) + // throws JavaModelException { + // + // if (this.refreshedElements == null) return false; + // + // HashMap externalArchivesStatus = new HashMap(); + // boolean hasDelta = false; + // + // // find JARs to refresh + // HashSet archivePathsToRefresh = new HashSet(); + // try { + // Iterator iterator = this.refreshedElements.iterator(); + // while (iterator.hasNext()) { + // IJavaElement element = (IJavaElement)iterator.next(); + // switch(element.getElementType()){ + // case IJavaElement.PACKAGE_FRAGMENT_ROOT : + // archivePathsToRefresh.add(element.getPath()); + // break; + // case IJavaElement.JAVA_PROJECT : + // IJavaProject project = (IJavaProject) element; + // if (!JavaProject.hasJavaNature(project.getProject())) { + // // project is not accessible or has lost its Java nature + // break; + // } + // IClasspathEntry[] classpath = project.getResolvedClasspath(true); + // for (int j = 0, cpLength = classpath.length; j < cpLength; j++){ + // if (classpath[j].getEntryKind() == IClasspathEntry.CPE_LIBRARY){ + // archivePathsToRefresh.add(classpath[j].getPath()); + // } + // } + // break; + // case IJavaElement.JAVA_MODEL : + // IJavaProject[] projects = + // manager.getJavaModel().getOldJavaProjectsList(); + // for (int j = 0, projectsLength = projects.length; j < projectsLength; + // j++){ + // project = projects[j]; + // if (!JavaProject.hasJavaNature(project.getProject())) { + // // project is not accessible or has lost its Java nature + // continue; + // } + // classpath = project.getResolvedClasspath(true); + // for (int k = 0, cpLength = classpath.length; k < cpLength; k++){ + // if (classpath[k].getEntryKind() == IClasspathEntry.CPE_LIBRARY){ + // archivePathsToRefresh.add(classpath[k].getPath()); + // } + // } + // } + // break; + // } + // } + // } finally { + // this.refreshedElements = null; + // } + // + // // perform refresh + // IJavaProject[] projects = + // manager.getJavaModel().getOldJavaProjectsList(); + // IWorkspaceRoot wksRoot = ResourcesPlugin.getWorkspace().getRoot(); + // for (int i = 0, length = projects.length; i < length; i++) { + // + // if (monitor != null && monitor.isCanceled()) break; + // + // IJavaProject project = projects[i]; + // if (!JavaProject.hasJavaNature(project.getProject())) { + // // project is not accessible or has lost its Java nature + // continue; + // } + // IClasspathEntry[] entries = project.getResolvedClasspath(true); + // for (int j = 0; j < entries.length; j++){ + // if (entries[j].getEntryKind() == IClasspathEntry.CPE_LIBRARY) { + // + // IPath entryPath = entries[j].getPath(); + // + // if (!archivePathsToRefresh.contains(entryPath)) continue; // not supposed + // to be refreshed + // + // String status = (String)externalArchivesStatus.get(entryPath); + // if (status == null){ + // + // // compute shared status + // Object targetLibrary = JavaModel.getTarget(wksRoot, entryPath, true); + // + // if (targetLibrary == null){ // missing JAR + // if (this.externalTimeStamps.containsKey(entryPath)){ + // this.externalTimeStamps.remove(entryPath); + // externalArchivesStatus.put(entryPath, EXTERNAL_JAR_REMOVED); + // // the jar was physically removed: remove the index + // indexManager.removeIndex(entryPath); + // } + // + // } else if (targetLibrary instanceof File){ // external JAR + // + // File externalFile = (File)targetLibrary; + // + // // check timestamp to figure if JAR has changed in some way + // Long oldTimestamp =(Long) this.externalTimeStamps.get(entryPath); + // long newTimeStamp = getTimeStamp(externalFile); + // if (oldTimestamp != null){ + // + // if (newTimeStamp == 0){ // file doesn't exist + // externalArchivesStatus.put(entryPath, EXTERNAL_JAR_REMOVED); + // this.externalTimeStamps.remove(entryPath); + // // remove the index + // indexManager.removeIndex(entryPath); + // + // } else if (oldTimestamp.longValue() != newTimeStamp){ + // externalArchivesStatus.put(entryPath, EXTERNAL_JAR_CHANGED); + // this.externalTimeStamps.put(entryPath, new Long(newTimeStamp)); + // // first remove the index so that it is forced to be re-indexed + // indexManager.removeIndex(entryPath); + // // then index the jar + // indexManager.indexLibrary(entryPath, project.getProject()); + // } else { + // externalArchivesStatus.put(entryPath, EXTERNAL_JAR_UNCHANGED); + // } + // } else { + // if (newTimeStamp == 0){ // jar still doesn't exist + // externalArchivesStatus.put(entryPath, EXTERNAL_JAR_UNCHANGED); + // } else { + // externalArchivesStatus.put(entryPath, EXTERNAL_JAR_ADDED); + // this.externalTimeStamps.put(entryPath, new Long(newTimeStamp)); + // // index the new jar + // indexManager.indexLibrary(entryPath, project.getProject()); + // } + // } + // } else { // internal JAR + // externalArchivesStatus.put(entryPath, INTERNAL_JAR_IGNORE); + // } + // } + // // according to computed status, generate a delta + // status = (String)externalArchivesStatus.get(entryPath); + // if (status != null){ + // if (status == EXTERNAL_JAR_ADDED){ + // PackageFragmentRoot root = + // (PackageFragmentRoot)project.getPackageFragmentRoot(entryPath.toString()); + // if (VERBOSE){ + // System.out.println("- External JAR ADDED, affecting root: + // "+root.getElementName()); //$NON-NLS-1$ + // } + // elementAdded(root, null, null); + // hasDelta = true; + // } else if (status == EXTERNAL_JAR_CHANGED) { + // PackageFragmentRoot root = + // (PackageFragmentRoot)project.getPackageFragmentRoot(entryPath.toString()); + // if (VERBOSE){ + // System.out.println("- External JAR CHANGED, affecting root: + // "+root.getElementName()); //$NON-NLS-1$ + // } + // // reset the corresponding project built state, since the builder would + // miss this change + // this.manager.setLastBuiltState(project.getProject(), null /*no state*/); + // contentChanged(root, null); + // hasDelta = true; + // } else if (status == EXTERNAL_JAR_REMOVED) { + // PackageFragmentRoot root = + // (PackageFragmentRoot)project.getPackageFragmentRoot(entryPath.toString()); + // if (VERBOSE){ + // System.out.println("- External JAR REMOVED, affecting root: + // "+root.getElementName()); //$NON-NLS-1$ + // } + // elementRemoved(root, null, null); + // hasDelta = true; + // } + // } + // } + // } + // } + // return hasDelta; + // } JavaElementDelta currentDelta() { if (this.currentDelta == null) { - this.currentDelta = new JavaElementDelta(this.manager.getJavaModel()); + this.currentDelta = new JavaElementDelta(this.manager + .getJavaModel()); } return this.currentDelta; } - + /* - * Process the given delta and look for projects being added, opened, closed or - * with a java nature being added or removed. - * Note that projects being deleted are checked in deleting(IProject). - * In all cases, add the project's dependents to the list of projects to update - * so that the classpath related markers can be updated. + * Process the given delta and look for projects being added, opened, closed + * or with a java nature being added or removed. Note that projects being + * deleted are checked in deleting(IProject). In all cases, add the + * project's dependents to the list of projects to update so that the + * classpath related markers can be updated. */ -// public void checkProjectsBeingAddedOrRemoved(IResourceDelta delta) { -// IResource resource = delta.getResource(); -// switch (resource.getType()) { -// case IResource.ROOT : -// // workaround for bug 15168 circular errors not reported -// if (this.manager.javaProjectsCache == null) { -// try { -// this.manager.javaProjectsCache = this.manager.getJavaModel().getJavaProjects(); -// } catch (JavaModelException e) { -// } -// } -// -// IResourceDelta[] children = delta.getAffectedChildren(); -// for (int i = 0, length = children.length; i < length; i++) { -// this.checkProjectsBeingAddedOrRemoved(children[i]); -// } -// break; -// case IResource.PROJECT : -// // NB: No need to check project's nature as if the project is not a java project: -// // - if the project is added or changed this is a noop for projectsBeingDeleted -// // - if the project is closed, it has already lost its java nature -// int deltaKind = delta.getKind(); -// if (deltaKind == IResourceDelta.ADDED) { -// // remember project and its dependents -// IProject project = (IProject)resource; -// this.addToProjectsToUpdateWithDependents(project); -// -// // workaround for bug 15168 circular errors not reported -// if (JavaProject.hasJavaNature(project)) { -// this.addToParentInfo((JavaProject)JavaCore.create(project)); -// } -// -// } else if (deltaKind == IResourceDelta.CHANGED) { -// IProject project = (IProject)resource; -// if ((delta.getFlags() & IResourceDelta.OPEN) != 0) { -// // project opened or closed: remember project and its dependents -// this.addToProjectsToUpdateWithDependents(project); -// -// // workaround for bug 15168 circular errors not reported -// if (project.isOpen()) { -// if (JavaProject.hasJavaNature(project)) { -// this.addToParentInfo((JavaProject)JavaCore.create(project)); -// } -// } else { -// JavaProject javaProject = (JavaProject)this.manager.getJavaModel().findJavaProject(project); -// if (javaProject != null) { -// try { -// javaProject.close(); -// } catch (JavaModelException e) { -// } -// this.removeFromParentInfo(javaProject); -// } -// } -// } else if ((delta.getFlags() & IResourceDelta.DESCRIPTION) != 0) { -// boolean wasJavaProject = this.manager.getJavaModel().findJavaProject(project) != null; -// boolean isJavaProject = JavaProject.hasJavaNature(project); -// if (wasJavaProject != isJavaProject) { -// // java nature added or removed: remember project and its dependents -// this.addToProjectsToUpdateWithDependents(project); -// -// // workaround for bug 15168 circular errors not reported -// if (isJavaProject) { -// this.addToParentInfo((JavaProject)JavaCore.create(project)); -// } else { -// JavaProject javaProject = (JavaProject)JavaCore.create(project); -// -// // flush classpath markers -// javaProject. -// flushClasspathProblemMarkers( -// true, // flush cycle markers -// true //flush classpath format markers -// ); -// -// // remove problems and tasks created by the builder -// JavaBuilder.removeProblemsAndTasksFor(project); -// -// // close project -// try { -// javaProject.close(); -// } catch (JavaModelException e) { -// } -// this.removeFromParentInfo(javaProject); -// } -// } else { -// // in case the project was removed then added then changed (see bug 19799) -// if (JavaProject.hasJavaNature(project)) { // need nature check - 18698 -// this.addToParentInfo((JavaProject)JavaCore.create(project)); -// } -// } -// } else { -// // workaround for bug 15168 circular errors not reported -// // in case the project was removed then added then changed -// if (JavaProject.hasJavaNature(project)) { // need nature check - 18698 -// this.addToParentInfo((JavaProject)JavaCore.create(project)); -// } -// } -// } -// break; -// } -// } - -// private void checkSourceAttachmentChange(IResourceDelta delta, IResource res) { -// IPath rootPath = (IPath)this.sourceAttachments.get(res.getFullPath()); -// if (rootPath != null) { -// RootInfo rootInfo = this.rootInfo(rootPath, delta.getKind()); -// if (rootInfo != null) { -// IJavaProject projectOfRoot = rootInfo.project; -// IPackageFragmentRoot root = null; -// try { -// // close the root so that source attachement cache is flushed -// root = projectOfRoot.findPackageFragmentRoot(rootPath); -// if (root != null) { -// root.close(); -// } -// } catch (JavaModelException e) { -// } -// if (root == null) return; -// switch (delta.getKind()) { -// case IResourceDelta.ADDED: -// currentDelta().sourceAttached(root); -// break; -// case IResourceDelta.CHANGED: -// currentDelta().sourceDetached(root); -// currentDelta().sourceAttached(root); -// break; -// case IResourceDelta.REMOVED: -// currentDelta().sourceDetached(root); -// break; -// } -// } -// } -// } - + // public void checkProjectsBeingAddedOrRemoved(IResourceDelta delta) { + // IResource resource = delta.getResource(); + // switch (resource.getType()) { + // case IResource.ROOT : + // // workaround for bug 15168 circular errors not reported + // if (this.manager.javaProjectsCache == null) { + // try { + // this.manager.javaProjectsCache = + // this.manager.getJavaModel().getJavaProjects(); + // } catch (JavaModelException e) { + // } + // } + // + // IResourceDelta[] children = delta.getAffectedChildren(); + // for (int i = 0, length = children.length; i < length; i++) { + // this.checkProjectsBeingAddedOrRemoved(children[i]); + // } + // break; + // case IResource.PROJECT : + // // NB: No need to check project's nature as if the project is not a java + // project: + // // - if the project is added or changed this is a noop for + // projectsBeingDeleted + // // - if the project is closed, it has already lost its java nature + // int deltaKind = delta.getKind(); + // if (deltaKind == IResourceDelta.ADDED) { + // // remember project and its dependents + // IProject project = (IProject)resource; + // this.addToProjectsToUpdateWithDependents(project); + // + // // workaround for bug 15168 circular errors not reported + // if (JavaProject.hasJavaNature(project)) { + // this.addToParentInfo((JavaProject)JavaCore.create(project)); + // } + // + // } else if (deltaKind == IResourceDelta.CHANGED) { + // IProject project = (IProject)resource; + // if ((delta.getFlags() & IResourceDelta.OPEN) != 0) { + // // project opened or closed: remember project and its dependents + // this.addToProjectsToUpdateWithDependents(project); + // + // // workaround for bug 15168 circular errors not reported + // if (project.isOpen()) { + // if (JavaProject.hasJavaNature(project)) { + // this.addToParentInfo((JavaProject)JavaCore.create(project)); + // } + // } else { + // JavaProject javaProject = + // (JavaProject)this.manager.getJavaModel().findJavaProject(project); + // if (javaProject != null) { + // try { + // javaProject.close(); + // } catch (JavaModelException e) { + // } + // this.removeFromParentInfo(javaProject); + // } + // } + // } else if ((delta.getFlags() & IResourceDelta.DESCRIPTION) != 0) { + // boolean wasJavaProject = + // this.manager.getJavaModel().findJavaProject(project) != null; + // boolean isJavaProject = JavaProject.hasJavaNature(project); + // if (wasJavaProject != isJavaProject) { + // // java nature added or removed: remember project and its dependents + // this.addToProjectsToUpdateWithDependents(project); + // + // // workaround for bug 15168 circular errors not reported + // if (isJavaProject) { + // this.addToParentInfo((JavaProject)JavaCore.create(project)); + // } else { + // JavaProject javaProject = (JavaProject)JavaCore.create(project); + // + // // flush classpath markers + // javaProject. + // flushClasspathProblemMarkers( + // true, // flush cycle markers + // true //flush classpath format markers + // ); + // + // // remove problems and tasks created by the builder + // JavaBuilder.removeProblemsAndTasksFor(project); + // + // // close project + // try { + // javaProject.close(); + // } catch (JavaModelException e) { + // } + // this.removeFromParentInfo(javaProject); + // } + // } else { + // // in case the project was removed then added then changed (see bug + // 19799) + // if (JavaProject.hasJavaNature(project)) { // need nature check - 18698 + // this.addToParentInfo((JavaProject)JavaCore.create(project)); + // } + // } + // } else { + // // workaround for bug 15168 circular errors not reported + // // in case the project was removed then added then changed + // if (JavaProject.hasJavaNature(project)) { // need nature check - 18698 + // this.addToParentInfo((JavaProject)JavaCore.create(project)); + // } + // } + // } + // break; + // } + // } + // private void checkSourceAttachmentChange(IResourceDelta delta, IResource + // res) { + // IPath rootPath = (IPath)this.sourceAttachments.get(res.getFullPath()); + // if (rootPath != null) { + // RootInfo rootInfo = this.rootInfo(rootPath, delta.getKind()); + // if (rootInfo != null) { + // IJavaProject projectOfRoot = rootInfo.project; + // IPackageFragmentRoot root = null; + // try { + // // close the root so that source attachement cache is flushed + // root = projectOfRoot.findPackageFragmentRoot(rootPath); + // if (root != null) { + // root.close(); + // } + // } catch (JavaModelException e) { + // } + // if (root == null) return; + // switch (delta.getKind()) { + // case IResourceDelta.ADDED: + // currentDelta().sourceAttached(root); + // break; + // case IResourceDelta.CHANGED: + // currentDelta().sourceDetached(root); + // currentDelta().sourceAttached(root); + // break; + // case IResourceDelta.REMOVED: + // currentDelta().sourceDetached(root); + // break; + // } + // } + // } + // } /** - * Closes the given element, which removes it from the cache of open elements. + * Closes the given element, which removes it from the cache of open + * elements. */ -// protected static void close(Openable element) { -// -// try { -// element.close(); -// } catch (JavaModelException e) { -// // do nothing -// } -// } + // protected static void close(Openable element) { + // + // try { + // element.close(); + // } catch (JavaModelException e) { + // // do nothing + // } + // } /** - * Generic processing for elements with changed contents:

                                  + * Generic processing for elements with changed contents: + *
                                    *
                                  • The element is closed such that any subsequent accesses will re-open * the element reflecting its new structure. - *
                                  • An entry is made in the delta reporting a content change (K_CHANGE with F_CONTENT flag set). + *
                                  • An entry is made in the delta reporting a content change (K_CHANGE + * with F_CONTENT flag set). *
                                  * Delta argument could be null if processing an external JAR change */ -// protected void contentChanged(Openable element, IResourceDelta delta) { -// -// close(element); -// int flags = IJavaElementDelta.F_CONTENT; -// if (element instanceof JarPackageFragmentRoot){ -// flags |= IJavaElementDelta.F_ARCHIVE_CONTENT_CHANGED; -// } -// currentDelta().changed(element, flags); -// } -// + // protected void contentChanged(Openable element, IResourceDelta delta) { + // + // close(element); + // int flags = IJavaElementDelta.F_CONTENT; + // if (element instanceof JarPackageFragmentRoot){ + // flags |= IJavaElementDelta.F_ARCHIVE_CONTENT_CHANGED; + // } + // currentDelta().changed(element, flags); + // } + // /** - * Creates the openables corresponding to this resource. - * Returns null if none was found. + * Creates the openables corresponding to this resource. Returns null if + * none was found. */ -// protected Openable createElement(IResource resource, int elementType, RootInfo rootInfo) { -// if (resource == null) return null; -// -// IPath path = resource.getFullPath(); -// IJavaElement element = null; -// switch (elementType) { -// -// case IJavaElement.JAVA_PROJECT: -// -// // note that non-java resources rooted at the project level will also enter this code with -// // an elementType JAVA_PROJECT (see #elementType(...)). -// if (resource instanceof IProject){ -// -// this.popUntilPrefixOf(path); -// -// if (this.currentElement != null -// && this.currentElement.getElementType() == IJavaElement.JAVA_PROJECT -// && ((IJavaProject)this.currentElement).getProject().equals(resource)) { -// return this.currentElement; -// } -// if (rootInfo != null && rootInfo.project.getProject().equals(resource)){ -// element = (Openable)rootInfo.project; -// break; -// } -// IProject proj = (IProject)resource; -// if (JavaProject.hasJavaNature(proj)) { -// element = JavaCore.create(proj); -// } else { -// // java project may have been been closed or removed (look for -// // element amongst old java project s list). -// element = (Openable) manager.getJavaModel().findJavaProject(proj); -// } -// } -// break; -// case IJavaElement.PACKAGE_FRAGMENT_ROOT: -// element = rootInfo == null ? JavaCore.create(resource) : rootInfo.project.getPackageFragmentRoot(resource); -// break; -// case IJavaElement.PACKAGE_FRAGMENT: -// // find the element that encloses the resource -// this.popUntilPrefixOf(path); -// -// if (this.currentElement == null) { -// element = rootInfo == null ? JavaCore.create(resource) : JavaModelManager.create(resource, rootInfo.project); -// } else { -// // find the root -// IPackageFragmentRoot root = this.currentElement.getPackageFragmentRoot(); -// if (root == null) { -// element = rootInfo == null ? JavaCore.create(resource) : JavaModelManager.create(resource, rootInfo.project); -// } else if (((JavaProject)root.getJavaProject()).contains(resource)) { -// // create package handle -// IPath pkgPath = path.removeFirstSegments(root.getPath().segmentCount()); -// String pkg = ProjectPrefUtil.packageName(pkgPath); -// if (pkg == null) return null; -// element = root.getPackageFragment(pkg); -// } -// } -// break; -// case IJavaElement.COMPILATION_UNIT: -// case IJavaElement.CLASS_FILE: -// // find the element that encloses the resource -// this.popUntilPrefixOf(path); -// -// if (this.currentElement == null) { -// element = rootInfo == null ? JavaCore.create(resource) : JavaModelManager.create(resource, rootInfo.project); -// } else { -// // find the package -// IPackageFragment pkgFragment = null; -// switch (this.currentElement.getElementType()) { -// case IJavaElement.PACKAGE_FRAGMENT_ROOT: -// IPackageFragmentRoot root = (IPackageFragmentRoot)this.currentElement; -// IPath rootPath = root.getPath(); -// IPath pkgPath = path.removeLastSegments(1); -// String pkgName = ProjectPrefUtil.packageName(pkgPath.removeFirstSegments(rootPath.segmentCount())); -// if (pkgName != null) { -// pkgFragment = root.getPackageFragment(pkgName); -// } -// break; -// case IJavaElement.PACKAGE_FRAGMENT: -// Openable pkg = (Openable)this.currentElement; -// if (pkg.getPath().equals(path.removeLastSegments(1))) { -// pkgFragment = (IPackageFragment)pkg; -// } // else case of package x which is a prefix of x.y -// break; -// case IJavaElement.COMPILATION_UNIT: -// case IJavaElement.CLASS_FILE: -// pkgFragment = (IPackageFragment)this.currentElement.getParent(); -// break; -// } -// if (pkgFragment == null) { -// element = rootInfo == null ? JavaCore.create(resource) : JavaModelManager.create(resource, rootInfo.project); -// } else { -// if (elementType == IJavaElement.COMPILATION_UNIT) { -// // create compilation unit handle -// // fileName validation has been done in elementType(IResourceDelta, int, boolean) -// String fileName = path.lastSegment(); -// element = pkgFragment.getCompilationUnit(fileName); -// } else { -// // create class file handle -// // fileName validation has been done in elementType(IResourceDelta, int, boolean) -// String fileName = path.lastSegment(); -// element = pkgFragment.getClassFile(fileName); -// } -// } -// } -// break; -// } -// if (element == null) { -// return null; -// } else { -// this.currentElement = (Openable)element; -// return this.currentElement; -// } -// } + // protected Openable createElement(IResource resource, int elementType, + // RootInfo rootInfo) { + // if (resource == null) return null; + // + // IPath path = resource.getFullPath(); + // IJavaElement element = null; + // switch (elementType) { + // + // case IJavaElement.JAVA_PROJECT: + // + // // note that non-java resources rooted at the project level will also + // enter this code with + // // an elementType JAVA_PROJECT (see #elementType(...)). + // if (resource instanceof IProject){ + // + // this.popUntilPrefixOf(path); + // + // if (this.currentElement != null + // && this.currentElement.getElementType() == IJavaElement.JAVA_PROJECT + // && ((IJavaProject)this.currentElement).getProject().equals(resource)) { + // return this.currentElement; + // } + // if (rootInfo != null && rootInfo.project.getProject().equals(resource)){ + // element = (Openable)rootInfo.project; + // break; + // } + // IProject proj = (IProject)resource; + // if (JavaProject.hasJavaNature(proj)) { + // element = JavaCore.create(proj); + // } else { + // // java project may have been been closed or removed (look for + // // element amongst old java project s list). + // element = (Openable) manager.getJavaModel().findJavaProject(proj); + // } + // } + // break; + // case IJavaElement.PACKAGE_FRAGMENT_ROOT: + // element = rootInfo == null ? JavaCore.create(resource) : + // rootInfo.project.getPackageFragmentRoot(resource); + // break; + // case IJavaElement.PACKAGE_FRAGMENT: + // // find the element that encloses the resource + // this.popUntilPrefixOf(path); + // + // if (this.currentElement == null) { + // element = rootInfo == null ? JavaCore.create(resource) : + // JavaModelManager.create(resource, rootInfo.project); + // } else { + // // find the root + // IPackageFragmentRoot root = this.currentElement.getPackageFragmentRoot(); + // if (root == null) { + // element = rootInfo == null ? JavaCore.create(resource) : + // JavaModelManager.create(resource, rootInfo.project); + // } else if (((JavaProject)root.getJavaProject()).contains(resource)) { + // // create package handle + // IPath pkgPath = path.removeFirstSegments(root.getPath().segmentCount()); + // String pkg = ProjectPrefUtil.packageName(pkgPath); + // if (pkg == null) return null; + // element = root.getPackageFragment(pkg); + // } + // } + // break; + // case IJavaElement.COMPILATION_UNIT: + // case IJavaElement.CLASS_FILE: + // // find the element that encloses the resource + // this.popUntilPrefixOf(path); + // + // if (this.currentElement == null) { + // element = rootInfo == null ? JavaCore.create(resource) : + // JavaModelManager.create(resource, rootInfo.project); + // } else { + // // find the package + // IPackageFragment pkgFragment = null; + // switch (this.currentElement.getElementType()) { + // case IJavaElement.PACKAGE_FRAGMENT_ROOT: + // IPackageFragmentRoot root = (IPackageFragmentRoot)this.currentElement; + // IPath rootPath = root.getPath(); + // IPath pkgPath = path.removeLastSegments(1); + // String pkgName = + // ProjectPrefUtil.packageName(pkgPath.removeFirstSegments(rootPath.segmentCount())); + // if (pkgName != null) { + // pkgFragment = root.getPackageFragment(pkgName); + // } + // break; + // case IJavaElement.PACKAGE_FRAGMENT: + // Openable pkg = (Openable)this.currentElement; + // if (pkg.getPath().equals(path.removeLastSegments(1))) { + // pkgFragment = (IPackageFragment)pkg; + // } // else case of package x which is a prefix of x.y + // break; + // case IJavaElement.COMPILATION_UNIT: + // case IJavaElement.CLASS_FILE: + // pkgFragment = (IPackageFragment)this.currentElement.getParent(); + // break; + // } + // if (pkgFragment == null) { + // element = rootInfo == null ? JavaCore.create(resource) : + // JavaModelManager.create(resource, rootInfo.project); + // } else { + // if (elementType == IJavaElement.COMPILATION_UNIT) { + // // create compilation unit handle + // // fileName validation has been done in elementType(IResourceDelta, int, + // boolean) + // String fileName = path.lastSegment(); + // element = pkgFragment.getCompilationUnit(fileName); + // } else { + // // create class file handle + // // fileName validation has been done in elementType(IResourceDelta, int, + // boolean) + // String fileName = path.lastSegment(); + // element = pkgFragment.getClassFile(fileName); + // } + // } + // } + // break; + // } + // if (element == null) { + // return null; + // } else { + // this.currentElement = (Openable)element; + // return this.currentElement; + // } + // } /** * Note that the project is about to be deleted. */ -// public void deleting(IProject project) { -// -// try { -// // discard indexing jobs that belong to this project so that the project can be -// // deleted without interferences from the index manager -// this.indexManager.discardJobs(project.getName()); -// -// JavaProject javaProject = (JavaProject)JavaCore.create(project); -// -// // remember roots of this project -// if (this.removedRoots == null) { -// this.removedRoots = new HashMap(); -// } -// if (javaProject.isOpen()) { -// this.removedRoots.put(javaProject, javaProject.getPackageFragmentRoots()); -// } else { -// // compute roots without opening project -// this.removedRoots.put( -// javaProject, -// javaProject.computePackageFragmentRoots( -// javaProject.getResolvedClasspath(true), -// false)); -// } -// -// javaProject.close(); -// -// // workaround for bug 15168 circular errors not reported -// if (this.manager.javaProjectsCache == null) { -// this.manager.javaProjectsCache = this.manager.getJavaModel().getJavaProjects(); -// } -// this.removeFromParentInfo(javaProject); -// -// } catch (JavaModelException e) { -// } -// -// this.addDependentProjects(project.getFullPath(), this.projectsToUpdate); -// } - + // public void deleting(IProject project) { + // + // try { + // // discard indexing jobs that belong to this project so that the project + // can be + // // deleted without interferences from the index manager + // this.indexManager.discardJobs(project.getName()); + // + // JavaProject javaProject = (JavaProject)JavaCore.create(project); + // + // // remember roots of this project + // if (this.removedRoots == null) { + // this.removedRoots = new HashMap(); + // } + // if (javaProject.isOpen()) { + // this.removedRoots.put(javaProject, + // javaProject.getPackageFragmentRoots()); + // } else { + // // compute roots without opening project + // this.removedRoots.put( + // javaProject, + // javaProject.computePackageFragmentRoots( + // javaProject.getResolvedClasspath(true), + // false)); + // } + // + // javaProject.close(); + // + // // workaround for bug 15168 circular errors not reported + // if (this.manager.javaProjectsCache == null) { + // this.manager.javaProjectsCache = + // this.manager.getJavaModel().getJavaProjects(); + // } + // this.removeFromParentInfo(javaProject); + // + // } catch (JavaModelException e) { + // } + // + // this.addDependentProjects(project.getFullPath(), this.projectsToUpdate); + // } /** - * Processing for an element that has been added:
                                    + * Processing for an element that has been added: + *
                                      *
                                    • If the element is a project, do nothing, and do not process - * children, as when a project is created it does not yet have any - * natures - specifically a java nature. + * children, as when a project is created it does not yet have any natures - + * specifically a java nature. *
                                    • If the elemet is not a project, process it as added (see * basicElementAdded. *
                                    * Delta argument could be null if processing an external JAR change */ -// protected void elementAdded(Openable element, IResourceDelta delta, RootInfo rootInfo) { -// int elementType = element.getElementType(); -// -// if (elementType == IJavaElement.JAVA_PROJECT) { -// // project add is handled by JavaProject.configure() because -// // when a project is created, it does not yet have a java nature -// if (delta != null && JavaProject.hasJavaNature((IProject)delta.getResource())) { -// addToParentInfo(element); -// if ((delta.getFlags() & IResourceDelta.MOVED_FROM) != 0) { -// Openable movedFromElement = (Openable)element.getJavaModel().getJavaProject(delta.getMovedFromPath().lastSegment()); -// currentDelta().movedTo(element, movedFromElement); -// } else { -// currentDelta().added(element); -// } -// this.projectsToUpdate.add(element); -// this.updateRoots(element.getPath(), delta); -// this.projectsForDependentNamelookupRefresh.add((JavaProject) element); -// } -// } else { -// addToParentInfo(element); -// -// // Force the element to be closed as it might have been opened -// // before the resource modification came in and it might have a new child -// // For example, in an IWorkspaceRunnable: -// // 1. create a package fragment p using a java model operation -// // 2. open package p -// // 3. add file X.java in folder p -// // When the resource delta comes in, only the addition of p is notified, -// // but the package p is already opened, thus its children are not recomputed -// // and it appears empty. -// close(element); -// -// if (delta != null && (delta.getFlags() & IResourceDelta.MOVED_FROM) != 0) { -// IPath movedFromPath = delta.getMovedFromPath(); -// IResource res = delta.getResource(); -// IResource movedFromRes; -// if (res instanceof IFile) { -// movedFromRes = res.getWorkspace().getRoot().getFile(movedFromPath); -// } else { -// movedFromRes = res.getWorkspace().getRoot().getFolder(movedFromPath); -// } -// -// // find the element type of the moved from element -// RootInfo movedFromInfo = this.enclosingRootInfo(movedFromPath, IResourceDelta.REMOVED); -// int movedFromType = -// this.elementType( -// movedFromRes, -// IResourceDelta.REMOVED, -// element.getParent().getElementType(), -// movedFromInfo); -// -// // reset current element as it might be inside a nested root (popUntilPrefixOf() may use the outer root) -// this.currentElement = null; -// -// // create the moved from element -// Openable movedFromElement = -// elementType != IJavaElement.JAVA_PROJECT && movedFromType == IJavaElement.JAVA_PROJECT ? -// null : // outside classpath -// this.createElement(movedFromRes, movedFromType, movedFromInfo); -// if (movedFromElement == null) { -// // moved from outside classpath -// currentDelta().added(element); -// } else { -// currentDelta().movedTo(element, movedFromElement); -// } -// } else { -// currentDelta().added(element); -// } -// -// switch (elementType) { -// case IJavaElement.PACKAGE_FRAGMENT_ROOT : -// // when a root is added, and is on the classpath, the project must be updated -// JavaProject project = (JavaProject) element.getJavaProject(); -// this.projectsToUpdate.add(project); -// this.projectsForDependentNamelookupRefresh.add(project); -// -// break; -// case IJavaElement.PACKAGE_FRAGMENT : -// // get rid of namelookup since it holds onto obsolete cached info -// project = (JavaProject) element.getJavaProject(); -// try { -// project.getJavaProjectElementInfo().setNameLookup(null); -// this.projectsForDependentNamelookupRefresh.add(project); -// } catch (JavaModelException e) { -// } -// // add subpackages -// if (delta != null){ -// PackageFragmentRoot root = element.getPackageFragmentRoot(); -// String name = element.getElementName(); -// IResourceDelta[] children = delta.getAffectedChildren(); -// for (int i = 0, length = children.length; i < length; i++) { -// IResourceDelta child = children[i]; -// IResource resource = child.getResource(); -// if (resource instanceof IFolder) { -// String folderName = resource.getName(); -// if (ProjectPrefUtil.isValidFolderNameForPackage(folderName)) { -// String subpkgName = -// name.length() == 0 ? -// folderName : -// name + "." + folderName; //$NON-NLS-1$ -// Openable subpkg = (Openable)root.getPackageFragment(subpkgName); -// this.updateIndex(subpkg, child); -// this.elementAdded(subpkg, child, rootInfo); -// } -// } -// } -// } -// break; -// } -// } -// } - + // protected void elementAdded(Openable element, IResourceDelta delta, + // RootInfo rootInfo) { + // int elementType = element.getElementType(); + // + // if (elementType == IJavaElement.JAVA_PROJECT) { + // // project add is handled by JavaProject.configure() because + // // when a project is created, it does not yet have a java nature + // if (delta != null && + // JavaProject.hasJavaNature((IProject)delta.getResource())) { + // addToParentInfo(element); + // if ((delta.getFlags() & IResourceDelta.MOVED_FROM) != 0) { + // Openable movedFromElement = + // (Openable)element.getJavaModel().getJavaProject(delta.getMovedFromPath().lastSegment()); + // currentDelta().movedTo(element, movedFromElement); + // } else { + // currentDelta().added(element); + // } + // this.projectsToUpdate.add(element); + // this.updateRoots(element.getPath(), delta); + // this.projectsForDependentNamelookupRefresh.add((JavaProject) element); + // } + // } else { + // addToParentInfo(element); + // + // // Force the element to be closed as it might have been opened + // // before the resource modification came in and it might have a new child + // // For example, in an IWorkspaceRunnable: + // // 1. create a package fragment p using a java model operation + // // 2. open package p + // // 3. add file X.java in folder p + // // When the resource delta comes in, only the addition of p is notified, + // // but the package p is already opened, thus its children are not + // recomputed + // // and it appears empty. + // close(element); + // + // if (delta != null && (delta.getFlags() & IResourceDelta.MOVED_FROM) != 0) + // { + // IPath movedFromPath = delta.getMovedFromPath(); + // IResource res = delta.getResource(); + // IResource movedFromRes; + // if (res instanceof IFile) { + // movedFromRes = res.getWorkspace().getRoot().getFile(movedFromPath); + // } else { + // movedFromRes = res.getWorkspace().getRoot().getFolder(movedFromPath); + // } + // + // // find the element type of the moved from element + // RootInfo movedFromInfo = this.enclosingRootInfo(movedFromPath, + // IResourceDelta.REMOVED); + // int movedFromType = + // this.elementType( + // movedFromRes, + // IResourceDelta.REMOVED, + // element.getParent().getElementType(), + // movedFromInfo); + // + // // reset current element as it might be inside a nested root + // (popUntilPrefixOf() may use the outer root) + // this.currentElement = null; + // + // // create the moved from element + // Openable movedFromElement = + // elementType != IJavaElement.JAVA_PROJECT && movedFromType == + // IJavaElement.JAVA_PROJECT ? + // null : // outside classpath + // this.createElement(movedFromRes, movedFromType, movedFromInfo); + // if (movedFromElement == null) { + // // moved from outside classpath + // currentDelta().added(element); + // } else { + // currentDelta().movedTo(element, movedFromElement); + // } + // } else { + // currentDelta().added(element); + // } + // + // switch (elementType) { + // case IJavaElement.PACKAGE_FRAGMENT_ROOT : + // // when a root is added, and is on the classpath, the project must be + // updated + // JavaProject project = (JavaProject) element.getJavaProject(); + // this.projectsToUpdate.add(project); + // this.projectsForDependentNamelookupRefresh.add(project); + // + // break; + // case IJavaElement.PACKAGE_FRAGMENT : + // // get rid of namelookup since it holds onto obsolete cached info + // project = (JavaProject) element.getJavaProject(); + // try { + // project.getJavaProjectElementInfo().setNameLookup(null); + // this.projectsForDependentNamelookupRefresh.add(project); + // } catch (JavaModelException e) { + // } + // // add subpackages + // if (delta != null){ + // PackageFragmentRoot root = element.getPackageFragmentRoot(); + // String name = element.getElementName(); + // IResourceDelta[] children = delta.getAffectedChildren(); + // for (int i = 0, length = children.length; i < length; i++) { + // IResourceDelta child = children[i]; + // IResource resource = child.getResource(); + // if (resource instanceof IFolder) { + // String folderName = resource.getName(); + // if (ProjectPrefUtil.isValidFolderNameForPackage(folderName)) { + // String subpkgName = + // name.length() == 0 ? + // folderName : + // name + "." + folderName; //$NON-NLS-1$ + // Openable subpkg = (Openable)root.getPackageFragment(subpkgName); + // this.updateIndex(subpkg, child); + // this.elementAdded(subpkg, child, rootInfo); + // } + // } + // } + // } + // break; + // } + // } + // } /** - * Generic processing for a removed element:
                                      + * Generic processing for a removed element: + *
                                        *
                                      • Close the element, removing its structure from the cache *
                                      • Remove the element from its parent's cache of children *
                                      • Add a REMOVED entry in the delta *
                                      * Delta argument could be null if processing an external JAR change */ -// protected void elementRemoved(Openable element, IResourceDelta delta, RootInfo rootInfo) { -// -// if (element.isOpen()) { -// close(element); -// } -// removeFromParentInfo(element); -// int elementType = element.getElementType(); -// if (delta != null && (delta.getFlags() & IResourceDelta.MOVED_TO) != 0) { -// IPath movedToPath = delta.getMovedToPath(); -// IResource res = delta.getResource(); -// IResource movedToRes; -// switch (res.getType()) { -// case IResource.PROJECT: -// movedToRes = res.getWorkspace().getRoot().getProject(movedToPath.lastSegment()); -// break; -// case IResource.FOLDER: -// movedToRes = res.getWorkspace().getRoot().getFolder(movedToPath); -// break; -// case IResource.FILE: -// movedToRes = res.getWorkspace().getRoot().getFile(movedToPath); -// break; -// default: -// return; -// } -// -// // find the element type of the moved from element -// RootInfo movedToInfo = this.enclosingRootInfo(movedToPath, IResourceDelta.ADDED); -// int movedToType = -// this.elementType( -// movedToRes, -// IResourceDelta.ADDED, -// element.getParent().getElementType(), -// movedToInfo); -// -// // reset current element as it might be inside a nested root (popUntilPrefixOf() may use the outer root) -// this.currentElement = null; -// -// // create the moved To element -// Openable movedToElement = -// elementType != IJavaElement.JAVA_PROJECT && movedToType == IJavaElement.JAVA_PROJECT ? -// null : // outside classpath -// this.createElement(movedToRes, movedToType, movedToInfo); -// if (movedToElement == null) { -// // moved outside classpath -// currentDelta().removed(element); -// } else { -// currentDelta().movedFrom(element, movedToElement); -// } -// } else { -// currentDelta().removed(element); -// } -// -// switch (elementType) { -// case IJavaElement.JAVA_MODEL : -// this.indexManager.reset(); -// break; -// case IJavaElement.JAVA_PROJECT : -// this.manager.removePerProjectInfo( -// (JavaProject) element); -// this.updateRoots(element.getPath(), delta); -// this.projectsForDependentNamelookupRefresh.add((JavaProject) element); -// break; -// case IJavaElement.PACKAGE_FRAGMENT_ROOT : -// JavaProject project = (JavaProject) element.getJavaProject(); -// this.projectsToUpdate.add(project); -// this.projectsForDependentNamelookupRefresh.add(project); -// break; -// case IJavaElement.PACKAGE_FRAGMENT : -// //1G1TW2T - get rid of namelookup since it holds onto obsolete cached info -// project = (JavaProject) element.getJavaProject(); -// try { -// project.getJavaProjectElementInfo().setNameLookup(null); -// this.projectsForDependentNamelookupRefresh.add(project); -// } catch (JavaModelException e) { -// } -// // remove subpackages -// if (delta != null){ -// PackageFragmentRoot root = element.getPackageFragmentRoot(); -// String name = element.getElementName(); -// IResourceDelta[] children = delta.getAffectedChildren(); -// for (int i = 0, length = children.length; i < length; i++) { -// IResourceDelta child = children[i]; -// IResource resource = child.getResource(); -// if (resource instanceof IFolder) { -// String folderName = resource.getName(); -// if (ProjectPrefUtil.isValidFolderNameForPackage(folderName)) { -// String subpkgName = -// name.length() == 0 ? -// folderName : -// name + "." + folderName; //$NON-NLS-1$ -// Openable subpkg = (Openable)root.getPackageFragment(subpkgName); -// this.updateIndex(subpkg, child); -// this.elementRemoved(subpkg, child, rootInfo); -// } -// } -// } -// } -// break; -// } -// } - + // protected void elementRemoved(Openable element, IResourceDelta delta, + // RootInfo rootInfo) { + // + // if (element.isOpen()) { + // close(element); + // } + // removeFromParentInfo(element); + // int elementType = element.getElementType(); + // if (delta != null && (delta.getFlags() & IResourceDelta.MOVED_TO) != 0) { + // IPath movedToPath = delta.getMovedToPath(); + // IResource res = delta.getResource(); + // IResource movedToRes; + // switch (res.getType()) { + // case IResource.PROJECT: + // movedToRes = + // res.getWorkspace().getRoot().getProject(movedToPath.lastSegment()); + // break; + // case IResource.FOLDER: + // movedToRes = res.getWorkspace().getRoot().getFolder(movedToPath); + // break; + // case IResource.FILE: + // movedToRes = res.getWorkspace().getRoot().getFile(movedToPath); + // break; + // default: + // return; + // } + // + // // find the element type of the moved from element + // RootInfo movedToInfo = this.enclosingRootInfo(movedToPath, + // IResourceDelta.ADDED); + // int movedToType = + // this.elementType( + // movedToRes, + // IResourceDelta.ADDED, + // element.getParent().getElementType(), + // movedToInfo); + // + // // reset current element as it might be inside a nested root + // (popUntilPrefixOf() may use the outer root) + // this.currentElement = null; + // + // // create the moved To element + // Openable movedToElement = + // elementType != IJavaElement.JAVA_PROJECT && movedToType == + // IJavaElement.JAVA_PROJECT ? + // null : // outside classpath + // this.createElement(movedToRes, movedToType, movedToInfo); + // if (movedToElement == null) { + // // moved outside classpath + // currentDelta().removed(element); + // } else { + // currentDelta().movedFrom(element, movedToElement); + // } + // } else { + // currentDelta().removed(element); + // } + // + // switch (elementType) { + // case IJavaElement.JAVA_MODEL : + // this.indexManager.reset(); + // break; + // case IJavaElement.JAVA_PROJECT : + // this.manager.removePerProjectInfo( + // (JavaProject) element); + // this.updateRoots(element.getPath(), delta); + // this.projectsForDependentNamelookupRefresh.add((JavaProject) element); + // break; + // case IJavaElement.PACKAGE_FRAGMENT_ROOT : + // JavaProject project = (JavaProject) element.getJavaProject(); + // this.projectsToUpdate.add(project); + // this.projectsForDependentNamelookupRefresh.add(project); + // break; + // case IJavaElement.PACKAGE_FRAGMENT : + // //1G1TW2T - get rid of namelookup since it holds onto obsolete cached + // info + // project = (JavaProject) element.getJavaProject(); + // try { + // project.getJavaProjectElementInfo().setNameLookup(null); + // this.projectsForDependentNamelookupRefresh.add(project); + // } catch (JavaModelException e) { + // } + // // remove subpackages + // if (delta != null){ + // PackageFragmentRoot root = element.getPackageFragmentRoot(); + // String name = element.getElementName(); + // IResourceDelta[] children = delta.getAffectedChildren(); + // for (int i = 0, length = children.length; i < length; i++) { + // IResourceDelta child = children[i]; + // IResource resource = child.getResource(); + // if (resource instanceof IFolder) { + // String folderName = resource.getName(); + // if (ProjectPrefUtil.isValidFolderNameForPackage(folderName)) { + // String subpkgName = + // name.length() == 0 ? + // folderName : + // name + "." + folderName; //$NON-NLS-1$ + // Openable subpkg = (Openable)root.getPackageFragment(subpkgName); + // this.updateIndex(subpkg, child); + // this.elementRemoved(subpkg, child, rootInfo); + // } + // } + // } + // } + // break; + // } + // } /* - * Returns the type of the java element the given delta matches to. - * Returns NON_JAVA_RESOURCE if unknown (e.g. a non-java resource or excluded .java file) + * Returns the type of the java element the given delta matches to. Returns + * NON_JAVA_RESOURCE if unknown (e.g. a non-java resource or excluded .java + * file) */ -// private int elementType(IResource res, int kind, int parentType, RootInfo rootInfo) { -// switch (parentType) { -// case IJavaElement.JAVA_MODEL: -// // case of a movedTo or movedFrom project (other cases are handled in processResourceDelta(...) -// return IJavaElement.JAVA_PROJECT; -// case NON_JAVA_RESOURCE: -// case IJavaElement.JAVA_PROJECT: -// if (rootInfo == null) { -// rootInfo = this.enclosingRootInfo(res.getFullPath(), kind); -// } -// if (rootInfo != null && rootInfo.isRootOfProject(res.getFullPath())) { -// return IJavaElement.PACKAGE_FRAGMENT_ROOT; -// } else { -// return NON_JAVA_RESOURCE; // not yet in a package fragment root or root of another project -// } -// case IJavaElement.PACKAGE_FRAGMENT_ROOT: -// case IJavaElement.PACKAGE_FRAGMENT: -// if (rootInfo == null) { -// rootInfo = this.enclosingRootInfo(res.getFullPath(), kind); -// } -// if (rootInfo == null || ProjectPrefUtil.isExcluded(res, rootInfo.exclusionPatterns)) { -// return NON_JAVA_RESOURCE; -// } -// if (res instanceof IFolder) { -// if (ProjectPrefUtil.isValidFolderNameForPackage(res.getName())) { -// return IJavaElement.PACKAGE_FRAGMENT; -// } else { -// return NON_JAVA_RESOURCE; -// } -// } else { -// String fileName = res.getName(); -// if (ProjectPrefUtil.isValidCompilationUnitName(fileName)) { -// return IJavaElement.COMPILATION_UNIT; -// } else if (ProjectPrefUtil.isValidClassFileName(fileName)) { -// return IJavaElement.CLASS_FILE; -// } else if (this.rootInfo(res.getFullPath(), kind) != null) { -// // case of proj=src=bin and resource is a jar file on the classpath -// return IJavaElement.PACKAGE_FRAGMENT_ROOT; -// } else { -// return NON_JAVA_RESOURCE; -// } -// } -// default: -// return NON_JAVA_RESOURCE; -// } -// } - + // private int elementType(IResource res, int kind, int parentType, RootInfo + // rootInfo) { + // switch (parentType) { + // case IJavaElement.JAVA_MODEL: + // // case of a movedTo or movedFrom project (other cases are handled in + // processResourceDelta(...) + // return IJavaElement.JAVA_PROJECT; + // case NON_JAVA_RESOURCE: + // case IJavaElement.JAVA_PROJECT: + // if (rootInfo == null) { + // rootInfo = this.enclosingRootInfo(res.getFullPath(), kind); + // } + // if (rootInfo != null && rootInfo.isRootOfProject(res.getFullPath())) { + // return IJavaElement.PACKAGE_FRAGMENT_ROOT; + // } else { + // return NON_JAVA_RESOURCE; // not yet in a package fragment root or root + // of another project + // } + // case IJavaElement.PACKAGE_FRAGMENT_ROOT: + // case IJavaElement.PACKAGE_FRAGMENT: + // if (rootInfo == null) { + // rootInfo = this.enclosingRootInfo(res.getFullPath(), kind); + // } + // if (rootInfo == null || ProjectPrefUtil.isExcluded(res, + // rootInfo.exclusionPatterns)) { + // return NON_JAVA_RESOURCE; + // } + // if (res instanceof IFolder) { + // if (ProjectPrefUtil.isValidFolderNameForPackage(res.getName())) { + // return IJavaElement.PACKAGE_FRAGMENT; + // } else { + // return NON_JAVA_RESOURCE; + // } + // } else { + // String fileName = res.getName(); + // if (ProjectPrefUtil.isValidCompilationUnitName(fileName)) { + // return IJavaElement.COMPILATION_UNIT; + // } else if (ProjectPrefUtil.isValidClassFileName(fileName)) { + // return IJavaElement.CLASS_FILE; + // } else if (this.rootInfo(res.getFullPath(), kind) != null) { + // // case of proj=src=bin and resource is a jar file on the classpath + // return IJavaElement.PACKAGE_FRAGMENT_ROOT; + // } else { + // return NON_JAVA_RESOURCE; + // } + // } + // default: + // return NON_JAVA_RESOURCE; + // } + // } /** - * Answer a combination of the lastModified stamp and the size. - * Used for detecting external JAR changes + * Answer a combination of the lastModified stamp and the size. Used for + * detecting external JAR changes */ public static long getTimeStamp(File file) { return file.lastModified() + file.length(); @@ -1112,15 +1215,17 @@ public class DeltaProcessor implements IResourceChangeListener { public void initializeRoots() { // remember roots infos as old roots infos this.oldRoots = this.roots == null ? new HashMap() : this.roots; - this.oldOtherRoots = this.otherRoots == null ? new HashMap() : this.otherRoots; - + this.oldOtherRoots = this.otherRoots == null ? new HashMap() + : this.otherRoots; + // recompute root infos only if necessary - if (!rootsAreStale) return; + if (!rootsAreStale) + return; this.roots = new HashMap(); this.otherRoots = new HashMap(); this.sourceAttachments = new HashMap(); - + IJavaModel model = this.manager.getJavaModel(); IJavaProject[] projects; try { @@ -1138,39 +1243,49 @@ public class DeltaProcessor implements IResourceChangeListener { // continue with next project continue; } - for (int j= 0, classpathLength = classpath.length; j < classpathLength; j++) { + for (int j = 0, classpathLength = classpath.length; j < classpathLength; j++) { IClasspathEntry entry = classpath[j]; - if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) continue; - -// root path + if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) + continue; + + // root path IPath path = entry.getPath(); if (this.roots.get(path) == null) { - this.roots.put(path, new RootInfo(project, path, ((ClasspathEntry)entry).fullExclusionPatternChars())); + this.roots.put(path, new RootInfo(project, path, + ((ClasspathEntry) entry) + .fullExclusionPatternChars())); } else { - ArrayList rootList = (ArrayList)this.otherRoots.get(path); + ArrayList rootList = (ArrayList) this.otherRoots.get(path); if (rootList == null) { rootList = new ArrayList(); this.otherRoots.put(path, rootList); } - rootList.add(new RootInfo(project, path, ((ClasspathEntry)entry).fullExclusionPatternChars())); + rootList.add(new RootInfo(project, path, + ((ClasspathEntry) entry) + .fullExclusionPatternChars())); } - + // source attachment path - if (entry.getEntryKind() != IClasspathEntry.CPE_LIBRARY) continue; - QualifiedName qName = new QualifiedName(JavaCore.PLUGIN_ID, "sourceattachment: " + path.toOSString()); //$NON-NLS-1$; + if (entry.getEntryKind() != IClasspathEntry.CPE_LIBRARY) + continue; + QualifiedName qName = new QualifiedName(JavaCore.PLUGIN_ID, + "sourceattachment: " + path.toOSString()); //$NON-NLS-1$; String propertyString = null; try { - propertyString = ResourcesPlugin.getWorkspace().getRoot().getPersistentProperty(qName); + propertyString = ResourcesPlugin.getWorkspace().getRoot() + .getPersistentProperty(qName); } catch (CoreException e) { continue; } IPath sourceAttachmentPath; -// if (propertyString != null) { -// int index= propertyString.lastIndexOf(JarPackageFragmentRoot.ATTACHMENT_PROPERTY_DELIMITER); -// sourceAttachmentPath = (index < 0) ? new Path(propertyString) : new Path(propertyString.substring(0, index)); -// } else { - sourceAttachmentPath = entry.getSourceAttachmentPath(); -// } + // if (propertyString != null) { + // int index= + // propertyString.lastIndexOf(JarPackageFragmentRoot.ATTACHMENT_PROPERTY_DELIMITER); + // sourceAttachmentPath = (index < 0) ? new Path(propertyString) + // : new Path(propertyString.substring(0, index)); + // } else { + sourceAttachmentPath = entry.getSourceAttachmentPath(); + // } if (sourceAttachmentPath != null) { this.sourceAttachments.put(sourceAttachmentPath, path); } @@ -1180,61 +1295,73 @@ public class DeltaProcessor implements IResourceChangeListener { } /* - * Returns whether a given delta contains some information relevant to the JavaModel, - * in particular it will not consider SYNC or MARKER only deltas. + * Returns whether a given delta contains some information relevant to the + * JavaModel, in particular it will not consider SYNC or MARKER only deltas. */ - public boolean isAffectedBy(IResourceDelta rootDelta){ - //if (rootDelta == null) System.out.println("NULL DELTA"); - //long start = System.currentTimeMillis(); + public boolean isAffectedBy(IResourceDelta rootDelta) { + // if (rootDelta == null) System.out.println("NULL DELTA"); + // long start = System.currentTimeMillis(); if (rootDelta != null) { // use local exception to quickly escape from delta traversal - class FoundRelevantDeltaException extends RuntimeException {} + class FoundRelevantDeltaException extends RuntimeException { + } try { rootDelta.accept(new IResourceDeltaVisitor() { - public boolean visit(IResourceDelta delta) throws CoreException { - switch (delta.getKind()){ - case IResourceDelta.ADDED : - case IResourceDelta.REMOVED : + public boolean visit(IResourceDelta delta) + throws CoreException { + switch (delta.getKind()) { + case IResourceDelta.ADDED: + case IResourceDelta.REMOVED: + throw new FoundRelevantDeltaException(); + case IResourceDelta.CHANGED: + // if any flag is set but SYNC or MARKER, this delta + // should be considered + if (delta.getAffectedChildren().length == 0 // only + // check + // leaf + // delta + // nodes + && (delta.getFlags() & ~(IResourceDelta.SYNC | IResourceDelta.MARKERS)) != 0) { throw new FoundRelevantDeltaException(); - case IResourceDelta.CHANGED : - // if any flag is set but SYNC or MARKER, this delta should be considered - if (delta.getAffectedChildren().length == 0 // only check leaf delta nodes - && (delta.getFlags() & ~(IResourceDelta.SYNC | IResourceDelta.MARKERS)) != 0) { - throw new FoundRelevantDeltaException(); - } + } } return true; } }); - } catch(FoundRelevantDeltaException e) { - //System.out.println("RELEVANT DELTA detected in: "+ (System.currentTimeMillis() - start)); + } catch (FoundRelevantDeltaException e) { + // System.out.println("RELEVANT DELTA detected in: "+ + // (System.currentTimeMillis() - start)); return true; - } catch(CoreException e) { // ignore delta if not able to traverse + } catch (CoreException e) { // ignore delta if not able to traverse } } - //System.out.println("IGNORE SYNC DELTA took: "+ (System.currentTimeMillis() - start)); + // System.out.println("IGNORE SYNC DELTA took: "+ + // (System.currentTimeMillis() - start)); return false; } - + /* - * Returns whether the given resource is in one of the given output folders and if - * it is filtered out from this output folder. + * Returns whether the given resource is in one of the given output folders + * and if it is filtered out from this output folder. */ - private boolean isResFilteredFromOutput(OutputsInfo info, IResource res, int elementType) { + private boolean isResFilteredFromOutput(OutputsInfo info, IResource res, + int elementType) { if (info != null) { IPath resPath = res.getFullPath(); - for (int i = 0; i < info.outputCount; i++) { + for (int i = 0; i < info.outputCount; i++) { if (info.paths[i].isPrefixOf(resPath)) { if (info.traverseModes[i] != IGNORE) { // case of bin=src - if (info.traverseModes[i] == SOURCE && elementType == IJavaElement.CLASS_FILE) { + if (info.traverseModes[i] == SOURCE + && elementType == IJavaElement.CLASS_FILE) { return true; } else { - // case of .class file under project and no source folder + // case of .class file under project and no source + // folder // proj=bin - if (elementType == IJavaElement.JAVA_PROJECT - && res instanceof IFile - && PHPFileUtil.isPHPFile((IFile)res)) { + if (elementType == IJavaElement.JAVA_PROJECT + && res instanceof IFile + && PHPFileUtil.isPHPFile((IFile) res)) { return true; } } @@ -1246,22 +1373,27 @@ public class DeltaProcessor implements IResourceChangeListener { } return false; } + /* * Merges all awaiting deltas. */ private IJavaElementDelta mergeDeltas(Collection deltas) { - if (deltas.size() == 0) return null; - if (deltas.size() == 1) return (IJavaElementDelta)deltas.iterator().next(); - + if (deltas.size() == 0) + return null; + if (deltas.size() == 1) + return (IJavaElementDelta) deltas.iterator().next(); + if (VERBOSE) { - System.out.println("MERGING " + deltas.size() + " DELTAS ["+Thread.currentThread()+"]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + System.out + .println("MERGING " + deltas.size() + " DELTAS [" + Thread.currentThread() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } - + Iterator iterator = deltas.iterator(); - JavaElementDelta rootDelta = new JavaElementDelta(this.manager.javaModel); + JavaElementDelta rootDelta = new JavaElementDelta( + this.manager.javaModel); boolean insertedTree = false; while (iterator.hasNext()) { - JavaElementDelta delta = (JavaElementDelta)iterator.next(); + JavaElementDelta delta = (JavaElementDelta) iterator.next(); if (VERBOSE) { System.out.println(delta.toString()); } @@ -1270,7 +1402,8 @@ public class DeltaProcessor implements IResourceChangeListener { IJavaElementDelta[] children = delta.getAffectedChildren(); for (int j = 0; j < children.length; j++) { JavaElementDelta projectDelta = (JavaElementDelta) children[j]; - rootDelta.insertDeltaTree(projectDelta.getElement(), projectDelta); + rootDelta.insertDeltaTree(projectDelta.getElement(), + projectDelta); insertedTree = true; } IResourceDelta[] resourceDeltas = delta.getResourceDeltas(); @@ -1285,496 +1418,550 @@ public class DeltaProcessor implements IResourceChangeListener { insertedTree = true; } } - if (insertedTree) return rootDelta; + if (insertedTree) + return rootDelta; return null; - } - + } + /** - * Check whether the updated file is affecting some of the properties of a given project (like - * its classpath persisted as a file). - * Also force classpath problems to be refresh if not running in autobuild mode. - * NOTE: It can induce resource changes, and cannot be called during POST_CHANGE notification. - * + * Check whether the updated file is affecting some of the properties of a + * given project (like its classpath persisted as a file). Also force + * classpath problems to be refresh if not running in autobuild mode. NOTE: + * It can induce resource changes, and cannot be called during POST_CHANGE + * notification. + * */ -// public void performPreBuildCheck( -// IResourceDelta delta, -// IJavaElement parent) { -// -// IResource resource = delta.getResource(); -// IJavaElement element = null; -// boolean processChildren = false; -// -// switch (resource.getType()) { -// -// case IResource.ROOT : -// if (delta.getKind() == IResourceDelta.CHANGED) { -// element = JavaCore.create(resource); -// processChildren = true; -// } -// break; -// case IResource.PROJECT : -// int kind = delta.getKind(); -// switch (kind) { -// case IResourceDelta.CHANGED: -// // do not visit non-java projects (see bug 16140 Non-java project gets .classpath) -// IProject project = (IProject)resource; -// if (JavaProject.hasJavaNature(project)) { -// element = JavaCore.create(resource); -// processChildren = true; -// } else if (JavaModelManager.getJavaModelManager().getJavaModel().findJavaProject(project) != null) { -// // project had the java nature -// this.rootsAreStale = true; -// -// // remove classpath cache so that initializeRoots() will not consider the project has a classpath -// this.manager.removePerProjectInfo((JavaProject)JavaCore.create(project)); -// } -// break; -// case IResourceDelta.ADDED: -// this.rootsAreStale = true; -// break; -// case IResourceDelta.REMOVED: -// // remove classpath cache so that initializeRoots() will not consider the project has a classpath -// this.manager.removePerProjectInfo((JavaProject)JavaCore.create(resource)); -// -// this.rootsAreStale = true; -// break; -// } -// break; -// case IResource.FILE : -// if (parent.getElementType() == IJavaElement.JAVA_PROJECT) { -// IFile file = (IFile) resource; -// JavaProject project = (JavaProject) parent; -// -// /* check classpath file change */ -// if (file.getName().equals(JavaProject.CLASSPATH_FILENAME)) { -// reconcileClasspathFileUpdate(delta, file, project); -// this.rootsAreStale = true; -// break; -// } -//// /* check custom preference file change */ -//// if (file.getName().equals(JavaProject.PREF_FILENAME)) { -//// reconcilePreferenceFileUpdate(delta, file, project); -//// break; -//// } -// } -// break; -// } -// if (processChildren) { -// IResourceDelta[] children = delta.getAffectedChildren(); -// for (int i = 0; i < children.length; i++) { -// performPreBuildCheck(children[i], element); -// } -// } -// } - -// private void popUntilPrefixOf(IPath path) { -// while (this.currentElement != null) { -// IPath currentElementPath = null; -// if (this.currentElement instanceof IPackageFragmentRoot) { -// currentElementPath = ((IPackageFragmentRoot)this.currentElement).getPath(); -// } else { -// IResource currentElementResource = this.currentElement.getResource(); -// if (currentElementResource != null) { -// currentElementPath = currentElementResource.getFullPath(); -// } -// } -// if (currentElementPath != null) { -// if (this.currentElement instanceof IPackageFragment -// && this.currentElement.getElementName().length() == 0 -// && currentElementPath.segmentCount() != path.segmentCount()-1) { -// // default package and path is not a direct child -// this.currentElement = (Openable)this.currentElement.getParent(); -// } -// if (currentElementPath.isPrefixOf(path)) { -// return; -// } -// } -// this.currentElement = (Openable)this.currentElement.getParent(); -// } -// } - + // public void performPreBuildCheck( + // IResourceDelta delta, + // IJavaElement parent) { + // + // IResource resource = delta.getResource(); + // IJavaElement element = null; + // boolean processChildren = false; + // + // switch (resource.getType()) { + // + // case IResource.ROOT : + // if (delta.getKind() == IResourceDelta.CHANGED) { + // element = JavaCore.create(resource); + // processChildren = true; + // } + // break; + // case IResource.PROJECT : + // int kind = delta.getKind(); + // switch (kind) { + // case IResourceDelta.CHANGED: + // // do not visit non-java projects (see bug 16140 Non-java project gets + // .classpath) + // IProject project = (IProject)resource; + // if (JavaProject.hasJavaNature(project)) { + // element = JavaCore.create(resource); + // processChildren = true; + // } else if + // (JavaModelManager.getJavaModelManager().getJavaModel().findJavaProject(project) + // != null) { + // // project had the java nature + // this.rootsAreStale = true; + // + // // remove classpath cache so that initializeRoots() will not consider the + // project has a classpath + // this.manager.removePerProjectInfo((JavaProject)JavaCore.create(project)); + // } + // break; + // case IResourceDelta.ADDED: + // this.rootsAreStale = true; + // break; + // case IResourceDelta.REMOVED: + // // remove classpath cache so that initializeRoots() will not consider the + // project has a classpath + // this.manager.removePerProjectInfo((JavaProject)JavaCore.create(resource)); + // + // this.rootsAreStale = true; + // break; + // } + // break; + // case IResource.FILE : + // if (parent.getElementType() == IJavaElement.JAVA_PROJECT) { + // IFile file = (IFile) resource; + // JavaProject project = (JavaProject) parent; + // + // /* check classpath file change */ + // if (file.getName().equals(JavaProject.CLASSPATH_FILENAME)) { + // reconcileClasspathFileUpdate(delta, file, project); + // this.rootsAreStale = true; + // break; + // } + // // /* check custom preference file change */ + // // if (file.getName().equals(JavaProject.PREF_FILENAME)) { + // // reconcilePreferenceFileUpdate(delta, file, project); + // // break; + // // } + // } + // break; + // } + // if (processChildren) { + // IResourceDelta[] children = delta.getAffectedChildren(); + // for (int i = 0; i < children.length; i++) { + // performPreBuildCheck(children[i], element); + // } + // } + // } + // private void popUntilPrefixOf(IPath path) { + // while (this.currentElement != null) { + // IPath currentElementPath = null; + // if (this.currentElement instanceof IPackageFragmentRoot) { + // currentElementPath = + // ((IPackageFragmentRoot)this.currentElement).getPath(); + // } else { + // IResource currentElementResource = this.currentElement.getResource(); + // if (currentElementResource != null) { + // currentElementPath = currentElementResource.getFullPath(); + // } + // } + // if (currentElementPath != null) { + // if (this.currentElement instanceof IPackageFragment + // && this.currentElement.getElementName().length() == 0 + // && currentElementPath.segmentCount() != path.segmentCount()-1) { + // // default package and path is not a direct child + // this.currentElement = (Openable)this.currentElement.getParent(); + // } + // if (currentElementPath.isPrefixOf(path)) { + // return; + // } + // } + // this.currentElement = (Openable)this.currentElement.getParent(); + // } + // } /** - * Converts a IResourceDelta rooted in a Workspace into - * the corresponding set of IJavaElementDelta, rooted in the - * relevant JavaModels. + * Converts a IResourceDelta rooted in a + * Workspace into the corresponding set of + * IJavaElementDelta, rooted in the relevant + * JavaModels. */ /** - * Update the JavaModel according to a .classpath file change. The file can have changed as a result of a previous - * call to JavaProject#setRawClasspath or as a result of some user update (through repository) + * Update the JavaModel according to a .classpath file change. The file can + * have changed as a result of a previous call to + * JavaProject#setRawClasspath or as a result of some user update (through + * repository) */ -// void reconcileClasspathFileUpdate(IResourceDelta delta, IFile file, JavaProject project) { -// -// switch (delta.getKind()) { -// case IResourceDelta.REMOVED : // recreate one based on in-memory classpath -// try { -// JavaModelManager.PerProjectInfo info = JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(project.getProject()); -// if (info.classpath != null) { // if there is an in-memory classpath -// project.saveClasspath(info.classpath, info.outputLocation); -// } -// } catch (JavaModelException e) { -// if (project.getProject().isAccessible()) { -// ProjectPrefUtil.log(e, "Could not save classpath for "+ project.getPath()); //$NON-NLS-1$ -// } -// } -// break; -// case IResourceDelta.CHANGED : -// if ((delta.getFlags() & IResourceDelta.CONTENT) == 0 // only consider content change -// && (delta.getFlags() & IResourceDelta.MOVED_FROM) == 0) // and also move and overide scenario (see http://dev.eclipse.org/bugs/show_bug.cgi?id=21420) -// break; -// case IResourceDelta.ADDED : -// // check if any actual difference -// project.flushClasspathProblemMarkers(false, true); -// boolean wasSuccessful = false; // flag recording if .classpath file change got reflected -// try { -// // force to (re)read the property file -// IClasspathEntry[] fileEntries = project.readClasspathFile(true/*create markers*/, false/*don't log problems*/); -// if (fileEntries == null) -// break; // could not read, ignore -// JavaModelManager.PerProjectInfo info = JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(project.getProject()); -// if (info.classpath != null) { // if there is an in-memory classpath -// if (project.isClasspathEqualsTo(info.classpath, info.outputLocation, fileEntries)) { -// wasSuccessful = true; -// break; -// } -// } -// -// // will force an update of the classpath/output location based on the file information -// // extract out the output location -// IPath outputLocation = null; -// if (fileEntries != null && fileEntries.length > 0) { -// IClasspathEntry entry = fileEntries[fileEntries.length - 1]; -// if (entry.getContentKind() == ClasspathEntry.K_OUTPUT) { -// outputLocation = entry.getPath(); -// IClasspathEntry[] copy = new IClasspathEntry[fileEntries.length - 1]; -// System.arraycopy(fileEntries, 0, copy, 0, copy.length); -// fileEntries = copy; -// } -// } -// // restore output location -// if (outputLocation == null) { -// outputLocation = SetClasspathOperation.ReuseOutputLocation; -// // clean mode will also default to reusing current one -// } -// project.setRawClasspath( -// fileEntries, -// outputLocation, -// null, // monitor -// true, // canChangeResource -// project.getResolvedClasspath(true), // ignoreUnresolvedVariable -// true, // needValidation -// false); // no need to save -// -// // if reach that far, the classpath file change got absorbed -// wasSuccessful = true; -// } catch (RuntimeException e) { -// // setRawClasspath might fire a delta, and a listener may throw an exception -// if (project.getProject().isAccessible()) { -// ProjectPrefUtil.log(e, "Could not set classpath for "+ project.getPath()); //$NON-NLS-1$ -// } -// break; -// } catch (JavaModelException e) { // CP failed validation -// if (project.getProject().isAccessible()) { -// if (e.getJavaModelStatus().getException() instanceof CoreException) { -// // happens if the .classpath could not be written to disk -// project.createClasspathProblemMarker(new JavaModelStatus( -// IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, -// ProjectPrefUtil.bind("classpath.couldNotWriteClasspathFile", project.getElementName(), e.getMessage()))); //$NON-NLS-1$ -// } else { -// project.createClasspathProblemMarker(new JavaModelStatus( -// IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, -// ProjectPrefUtil.bind("classpath.invalidClasspathInClasspathFile", project.getElementName(), e.getMessage()))); //$NON-NLS-1$ -// } -// } -// break; -// } finally { -// if (!wasSuccessful) { -// try { -// project.setRawClasspath0(JavaProject.INVALID_CLASSPATH); -// project.updatePackageFragmentRoots(); -// } catch (JavaModelException e) { -// } -// } -// } -// } -// } - + // void reconcileClasspathFileUpdate(IResourceDelta delta, IFile file, + // JavaProject project) { + // + // switch (delta.getKind()) { + // case IResourceDelta.REMOVED : // recreate one based on in-memory + // classpath + // try { + // JavaModelManager.PerProjectInfo info = + // JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(project.getProject()); + // if (info.classpath != null) { // if there is an in-memory classpath + // project.saveClasspath(info.classpath, info.outputLocation); + // } + // } catch (JavaModelException e) { + // if (project.getProject().isAccessible()) { + // ProjectPrefUtil.log(e, "Could not save classpath for "+ + // project.getPath()); //$NON-NLS-1$ + // } + // } + // break; + // case IResourceDelta.CHANGED : + // if ((delta.getFlags() & IResourceDelta.CONTENT) == 0 // only consider + // content change + // && (delta.getFlags() & IResourceDelta.MOVED_FROM) == 0) // and also move + // and overide scenario (see + // http://dev.eclipse.org/bugs/show_bug.cgi?id=21420) + // break; + // case IResourceDelta.ADDED : + // // check if any actual difference + // project.flushClasspathProblemMarkers(false, true); + // boolean wasSuccessful = false; // flag recording if .classpath file + // change got reflected + // try { + // // force to (re)read the property file + // IClasspathEntry[] fileEntries = project.readClasspathFile(true/*create + // markers*/, false/*don't log problems*/); + // if (fileEntries == null) + // break; // could not read, ignore + // JavaModelManager.PerProjectInfo info = + // JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(project.getProject()); + // if (info.classpath != null) { // if there is an in-memory classpath + // if (project.isClasspathEqualsTo(info.classpath, info.outputLocation, + // fileEntries)) { + // wasSuccessful = true; + // break; + // } + // } + // + // // will force an update of the classpath/output location based on the + // file information + // // extract out the output location + // IPath outputLocation = null; + // if (fileEntries != null && fileEntries.length > 0) { + // IClasspathEntry entry = fileEntries[fileEntries.length - 1]; + // if (entry.getContentKind() == ClasspathEntry.K_OUTPUT) { + // outputLocation = entry.getPath(); + // IClasspathEntry[] copy = new IClasspathEntry[fileEntries.length - 1]; + // System.arraycopy(fileEntries, 0, copy, 0, copy.length); + // fileEntries = copy; + // } + // } + // // restore output location + // if (outputLocation == null) { + // outputLocation = SetClasspathOperation.ReuseOutputLocation; + // // clean mode will also default to reusing current one + // } + // project.setRawClasspath( + // fileEntries, + // outputLocation, + // null, // monitor + // true, // canChangeResource + // project.getResolvedClasspath(true), // ignoreUnresolvedVariable + // true, // needValidation + // false); // no need to save + // + // // if reach that far, the classpath file change got absorbed + // wasSuccessful = true; + // } catch (RuntimeException e) { + // // setRawClasspath might fire a delta, and a listener may throw an + // exception + // if (project.getProject().isAccessible()) { + // ProjectPrefUtil.log(e, "Could not set classpath for "+ + // project.getPath()); //$NON-NLS-1$ + // } + // break; + // } catch (JavaModelException e) { // CP failed validation + // if (project.getProject().isAccessible()) { + // if (e.getJavaModelStatus().getException() instanceof CoreException) { + // // happens if the .classpath could not be written to disk + // project.createClasspathProblemMarker(new JavaModelStatus( + // IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, + // ProjectPrefUtil.bind("classpath.couldNotWriteClasspathFile", + // project.getElementName(), e.getMessage()))); //$NON-NLS-1$ + // } else { + // project.createClasspathProblemMarker(new JavaModelStatus( + // IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, + // ProjectPrefUtil.bind("classpath.invalidClasspathInClasspathFile", + // project.getElementName(), e.getMessage()))); //$NON-NLS-1$ + // } + // } + // break; + // } finally { + // if (!wasSuccessful) { + // try { + // project.setRawClasspath0(JavaProject.INVALID_CLASSPATH); + // project.updatePackageFragmentRoots(); + // } catch (JavaModelException e) { + // } + // } + // } + // } + // } /** - * Update the JavaModel according to a .jprefs file change. The file can have changed as a result of a previous - * call to JavaProject#setOptions or as a result of some user update (through repository) - * Unused until preference file get shared (.jpref) + * Update the JavaModel according to a .jprefs file change. The file can + * have changed as a result of a previous call to JavaProject#setOptions or + * as a result of some user update (through repository) Unused until + * preference file get shared (.jpref) */ -// void reconcilePreferenceFileUpdate(IResourceDelta delta, IFile file, JavaProject project) { -// -// switch (delta.getKind()) { -// case IResourceDelta.REMOVED : // flush project custom settings -// project.setOptions(null); -// return; -// case IResourceDelta.CHANGED : -// if ((delta.getFlags() & IResourceDelta.CONTENT) == 0 // only consider content change -// && (delta.getFlags() & IResourceDelta.MOVED_FROM) == 0) // and also move and overide scenario -// break; -// identityCheck : { // check if any actual difference -// // force to (re)read the property file -// Preferences filePreferences = project.loadPreferences(); -// if (filePreferences == null){ -// project.setOptions(null); // should have got removed delta. -// return; -// } -// Preferences projectPreferences = project.getPreferences(); -// if (projectPreferences == null) return; // not a Java project -// -// // compare preferences set to their default -// String[] defaultProjectPropertyNames = projectPreferences.defaultPropertyNames(); -// String[] defaultFilePropertyNames = filePreferences.defaultPropertyNames(); -// if (defaultProjectPropertyNames.length == defaultFilePropertyNames.length) { -// for (int i = 0; i < defaultProjectPropertyNames.length; i++){ -// String propertyName = defaultProjectPropertyNames[i]; -// if (!projectPreferences.getString(propertyName).trim().equals(filePreferences.getString(propertyName).trim())){ -// break identityCheck; -// } -// } -// } else break identityCheck; -// -// // compare custom preferences not set to their default -// String[] projectPropertyNames = projectPreferences.propertyNames(); -// String[] filePropertyNames = filePreferences.propertyNames(); -// if (projectPropertyNames.length == filePropertyNames.length) { -// for (int i = 0; i < projectPropertyNames.length; i++){ -// String propertyName = projectPropertyNames[i]; -// if (!projectPreferences.getString(propertyName).trim().equals(filePreferences.getString(propertyName).trim())){ -// break identityCheck; -// } -// } -// } else break identityCheck; -// -// // identical - do nothing -// return; -// } -// case IResourceDelta.ADDED : -// // not identical, create delta and reset cached preferences -// project.setPreferences(null); -// // create delta -// //fCurrentDelta.changed(project, IJavaElementDelta.F_OPTIONS_CHANGED); -// } -// } + // void reconcilePreferenceFileUpdate(IResourceDelta delta, IFile file, + // JavaProject project) { + // + // switch (delta.getKind()) { + // case IResourceDelta.REMOVED : // flush project custom settings + // project.setOptions(null); + // return; + // case IResourceDelta.CHANGED : + // if ((delta.getFlags() & IResourceDelta.CONTENT) == 0 // only consider + // content change + // && (delta.getFlags() & IResourceDelta.MOVED_FROM) == 0) // and also move + // and overide scenario + // break; + // identityCheck : { // check if any actual difference + // // force to (re)read the property file + // Preferences filePreferences = project.loadPreferences(); + // if (filePreferences == null){ + // project.setOptions(null); // should have got removed delta. + // return; + // } + // Preferences projectPreferences = project.getPreferences(); + // if (projectPreferences == null) return; // not a Java project + // + // // compare preferences set to their default + // String[] defaultProjectPropertyNames = + // projectPreferences.defaultPropertyNames(); + // String[] defaultFilePropertyNames = + // filePreferences.defaultPropertyNames(); + // if (defaultProjectPropertyNames.length == + // defaultFilePropertyNames.length) { + // for (int i = 0; i < defaultProjectPropertyNames.length; i++){ + // String propertyName = defaultProjectPropertyNames[i]; + // if + // (!projectPreferences.getString(propertyName).trim().equals(filePreferences.getString(propertyName).trim())){ + // break identityCheck; + // } + // } + // } else break identityCheck; + // + // // compare custom preferences not set to their default + // String[] projectPropertyNames = projectPreferences.propertyNames(); + // String[] filePropertyNames = filePreferences.propertyNames(); + // if (projectPropertyNames.length == filePropertyNames.length) { + // for (int i = 0; i < projectPropertyNames.length; i++){ + // String propertyName = projectPropertyNames[i]; + // if + // (!projectPreferences.getString(propertyName).trim().equals(filePreferences.getString(propertyName).trim())){ + // break identityCheck; + // } + // } + // } else break identityCheck; + // + // // identical - do nothing + // return; + // } + // case IResourceDelta.ADDED : + // // not identical, create delta and reset cached preferences + // project.setPreferences(null); + // // create delta + // //fCurrentDelta.changed(project, IJavaElementDelta.F_OPTIONS_CHANGED); + // } + // } /* * Registers the given delta with this delta processor. */ public void registerJavaModelDelta(IJavaElementDelta delta) { this.javaModelDeltas.add(delta); } + /** * Removes the given element from its parents cache of children. If the - * element does not have a parent, or the parent is not currently open, - * this has no effect. + * element does not have a parent, or the parent is not currently open, this + * has no effect. */ protected void removeFromParentInfo(Openable child) { Openable parent = (Openable) child.getParent(); if (parent != null && parent.isOpen()) { try { - JavaElementInfo info = (JavaElementInfo)parent.getElementInfo(); + JavaElementInfo info = (JavaElementInfo) parent + .getElementInfo(); info.removeChild(child); } catch (JavaModelException e) { // do nothing - we already checked if open } } } - + /** - * Notification that some resource changes have happened - * on the platform, and that the Java Model should update any required - * internal structures such that its elements remain consistent. - * Translates IResourceDeltas into IJavaElementDeltas. - * + * Notification that some resource changes have happened on the platform, + * and that the Java Model should update any required internal structures + * such that its elements remain consistent. Translates + * IResourceDeltas into IJavaElementDeltas. + * * @see IResourceDelta - * @see IResource + * @see IResource */ public void resourceChanged(IResourceChangeEvent event) { - if (event.getSource() instanceof IWorkspace) { - int eventType = this.overridenEventType == -1 ? event.getType() : this.overridenEventType; - IResource resource = event.getResource(); - IResourceDelta delta = event.getDelta(); - - switch(eventType){ - case IResourceChangeEvent.PRE_DELETE : + if (event.getSource() instanceof IWorkspace) { + int eventType = this.overridenEventType == -1 ? event.getType() + : this.overridenEventType; + IResource resource = event.getResource(); + IResourceDelta delta = event.getDelta(); + + switch (eventType) { + case IResourceChangeEvent.PRE_DELETE: try { - if(resource.getType() == IResource.PROJECT - && ((IProject) resource).hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) { - - deleting((IProject)resource); + if (resource.getType() == IResource.PROJECT + && ((IProject) resource) + .hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) { + + deleting((IProject) resource); } - } catch(CoreException e){ + } catch (CoreException e) { // project doesn't exist or is not open: ignore } return; - - case IResourceChangeEvent.POST_CHANGE : - if (isAffectedBy(delta)) { // avoid populating for SYNC or MARKER deltas + + case IResourceChangeEvent.POST_CHANGE: + if (isAffectedBy(delta)) { // avoid populating for SYNC or + // MARKER deltas try { try { stopDeltas(); -// checkProjectsBeingAddedOrRemoved(delta); -// if (this.refreshedElements != null) { -// createExternalArchiveDelta(null); -// } + // checkProjectsBeingAddedOrRemoved(delta); + // if (this.refreshedElements != null) { + // createExternalArchiveDelta(null); + // } IJavaElementDelta translatedDelta = processResourceDelta(delta); - if (translatedDelta != null) { + if (translatedDelta != null) { registerJavaModelDelta(translatedDelta); } } finally { startDeltas(); } -// notifyTypeHierarchies(this.state.elementChangedListeners, this.state.elementChangedListenerCount); + // notifyTypeHierarchies(this.state.elementChangedListeners, + // this.state.elementChangedListenerCount); fire(null, ElementChangedEvent.POST_CHANGE); } finally { - // workaround for bug 15168 circular errors not reported + // workaround for bug 15168 circular errors not reported this.state.modelProjectsCache = null; this.removedRoots = null; } } return; - - case IResourceChangeEvent.PRE_BUILD : - DeltaProcessingState.ProjectUpdateInfo[] updates = this.state.removeAllProjectUpdates(); + + case IResourceChangeEvent.PRE_BUILD: + DeltaProcessingState.ProjectUpdateInfo[] updates = this.state + .removeAllProjectUpdates(); if (updates != null) { - for (int i = 0, length = updates.length; i < length; i++) { - try { - updates[i].updateProjectReferencesIfNecessary(); - } catch(JavaModelException e) { - // do nothing - } - } + for (int i = 0, length = updates.length; i < length; i++) { + try { + updates[i].updateProjectReferencesIfNecessary(); + } catch (JavaModelException e) { + // do nothing + } + } } // this.processPostChange = false; - if(isAffectedBy(delta)) { // avoid populating for SYNC or MARKER deltas -// updateClasspathMarkers(delta); + if (isAffectedBy(delta)) { // avoid populating for SYNC or + // MARKER deltas + // updateClasspathMarkers(delta); PHPBuilder.buildStarting(); } // does not fire any deltas return; - case IResourceChangeEvent.POST_BUILD : + case IResourceChangeEvent.POST_BUILD: PHPBuilder.buildFinished(); return; + } } + // // jsurfer TODO compare 3.0 sources + // if (event.getSource() instanceof IWorkspace) { + // int eventType = this.overridenEventType == -1 ? event.getType() : + // this.overridenEventType; + // IResource resource = event.getResource(); + // IResourceDelta delta = event.getDelta(); + // + // switch(eventType){ + // case IResourceChangeEvent.PRE_DELETE : + // try { + // if(resource.getType() == IResource.PROJECT + // && ((IProject) resource).hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) { + // // TODO jsurfer temp-del + // // this.deleting((IProject)resource); + // } + // } catch(CoreException e){ + // } + // return; + // + // case IResourceChangeEvent.PRE_BUILD : + // // TODO jsurfer temp-del + // // if(isAffectedBy(delta)) { // avoid populating for SYNC or MARKER + // deltas + // // this.checkProjectsBeingAddedOrRemoved(delta); + // // + // // // update the classpath related markers + // // this.updateClasspathMarkers(); + // // + // // // the following will close project if affected by the property + // file change + // // try { + // // // don't fire classpath change deltas right away, but batch them + // // this.manager.stopDeltas(); + // // this.performPreBuildCheck(delta, null); + // // } finally { + // // this.manager.startDeltas(); + // // } + // // } + // // only fire already computed deltas (resource ones will be processed + // in post change only) + // this.manager.fire(null, ElementChangedEvent.PRE_AUTO_BUILD); + // break; + // + // case IResourceChangeEvent.POST_BUILD : + // // TODO jsurfer temp-del + // // JavaBuilder.finishedBuilding(event); + // break; + // + // case IResourceChangeEvent.POST_CHANGE : + // // TODO jsurfer temp-del + // // if (isAffectedBy(delta)) { + // // try { + // // if (this.refreshedElements != null) { + // // try { + // // createExternalArchiveDelta(null); + // // } catch (JavaModelException e) { + // // e.printStackTrace(); + // // } + // // } + // // IJavaElementDelta translatedDelta = + // this.processResourceDelta(delta); + // // if (translatedDelta != null) { + // // this.manager.registerJavaModelDelta(translatedDelta); + // // } + // // this.manager.fire(null, ElementChangedEvent.POST_CHANGE); + // // } finally { + // // // workaround for bug 15168 circular errors not reported + // // this.manager.javaProjectsCache = null; + // // this.removedRoots = null; + // // } + // // } + // } + // } } -// // jsurfer TODO compare 3.0 sources -// if (event.getSource() instanceof IWorkspace) { -// int eventType = this.overridenEventType == -1 ? event.getType() : this.overridenEventType; -// IResource resource = event.getResource(); -// IResourceDelta delta = event.getDelta(); -// -// switch(eventType){ -// case IResourceChangeEvent.PRE_DELETE : -// try { -// if(resource.getType() == IResource.PROJECT -// && ((IProject) resource).hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) { -// // TODO jsurfer temp-del -//// this.deleting((IProject)resource); -// } -// } catch(CoreException e){ -// } -// return; -// -// case IResourceChangeEvent.PRE_BUILD : -//// TODO jsurfer temp-del -//// if(isAffectedBy(delta)) { // avoid populating for SYNC or MARKER deltas -//// this.checkProjectsBeingAddedOrRemoved(delta); -//// -//// // update the classpath related markers -//// this.updateClasspathMarkers(); -//// -//// // the following will close project if affected by the property file change -//// try { -//// // don't fire classpath change deltas right away, but batch them -//// this.manager.stopDeltas(); -//// this.performPreBuildCheck(delta, null); -//// } finally { -//// this.manager.startDeltas(); -//// } -//// } -// // only fire already computed deltas (resource ones will be processed in post change only) -// this.manager.fire(null, ElementChangedEvent.PRE_AUTO_BUILD); -// break; -// -// case IResourceChangeEvent.POST_BUILD : -//// TODO jsurfer temp-del -//// JavaBuilder.finishedBuilding(event); -// break; -// -// case IResourceChangeEvent.POST_CHANGE : -//// TODO jsurfer temp-del -//// if (isAffectedBy(delta)) { -//// try { -//// if (this.refreshedElements != null) { -//// try { -//// createExternalArchiveDelta(null); -//// } catch (JavaModelException e) { -//// e.printStackTrace(); -//// } -//// } -//// IJavaElementDelta translatedDelta = this.processResourceDelta(delta); -//// if (translatedDelta != null) { -//// this.manager.registerJavaModelDelta(translatedDelta); -//// } -//// this.manager.fire(null, ElementChangedEvent.POST_CHANGE); -//// } finally { -//// // workaround for bug 15168 circular errors not reported -//// this.manager.javaProjectsCache = null; -//// this.removedRoots = null; -//// } -//// } -// } -// } - } + /* * Turns the firing mode to on. That is, deltas that are/have been * registered will be fired. */ private void startDeltas() { - this.isFiring= true; + this.isFiring = true; } + /* * Turns the firing mode to off. That is, deltas that are/have been * registered will not be fired until deltas are started again. */ private void stopDeltas() { - this.isFiring= false; + this.isFiring = false; } + /* * Note that the project is about to be deleted. */ private void deleting(IProject project) { - + try { - // discard indexing jobs that belong to this project so that the project can be + // discard indexing jobs that belong to this project so that the + // project can be // deleted without interferences from the index manager -// this.manager.indexManager.discardJobs(project.getName()); + // this.manager.indexManager.discardJobs(project.getName()); + + JavaProject javaProject = (JavaProject) JavaCore.create(project); - JavaProject javaProject = (JavaProject)JavaCore.create(project); - // remember roots of this project if (this.removedRoots == null) { this.removedRoots = new HashMap(); } if (javaProject.isOpen()) { - this.removedRoots.put(javaProject, javaProject.getPackageFragmentRoots()); + this.removedRoots.put(javaProject, javaProject + .getPackageFragmentRoots()); } else { // compute roots without opening project -// this.removedRoots.put( -// javaProject, -// javaProject.computePackageFragmentRoots( -// javaProject.getResolvedClasspath(true/*ignoreUnresolvedEntry*/, false/*don't generateMarkerOnError*/, false/*don't returnResolutionInProgress*/), -// false)); + // this.removedRoots.put( + // javaProject, + // javaProject.computePackageFragmentRoots( + // javaProject.getResolvedClasspath(true/*ignoreUnresolvedEntry*/, + // false/*don't generateMarkerOnError*/, false/*don't + // returnResolutionInProgress*/), + // false)); } - + javaProject.close(); // workaround for bug 15168 circular errors not reported if (this.state.modelProjectsCache == null) { - this.state.modelProjectsCache = this.manager.getJavaModel().getJavaProjects(); + this.state.modelProjectsCache = this.manager.getJavaModel() + .getJavaProjects(); } this.removeFromParentInfo(javaProject); @@ -1782,17 +1969,19 @@ public class DeltaProcessor implements IResourceChangeListener { // java project doesn't exist: ignore } } + /* - * Converts a IResourceDelta rooted in a Workspace into - * the corresponding set of IJavaElementDelta, rooted in the - * relevant JavaModels. + * Converts a IResourceDelta rooted in a Workspace + * into the corresponding set of IJavaElementDelta, rooted + * in the relevant JavaModels. */ private IJavaElementDelta processResourceDelta(IResourceDelta changes) { try { IJavaModel model = this.manager.getJavaModel(); if (!model.isOpen()) { - // force opening of java model so that java element delta are reported + // force opening of java model so that java element delta are + // reported try { model.open(null); } catch (JavaModelException e) { @@ -1804,927 +1993,1021 @@ public class DeltaProcessor implements IResourceChangeListener { } this.state.initializeRoots(); this.currentElement = null; - + // get the workspace delta, and start processing there. IResourceDelta[] deltas = changes.getAffectedChildren(); for (int i = 0; i < deltas.length; i++) { IResourceDelta delta = deltas[i]; IResource res = delta.getResource(); - + // find out the element type -// RootInfo rootInfo = null; + // RootInfo rootInfo = null; int elementType; - IProject proj = (IProject)res; - boolean wasJavaProject = this.manager.getJavaModel().findJavaProject(proj) != null; + IProject proj = (IProject) res; + boolean wasJavaProject = this.manager.getJavaModel() + .findJavaProject(proj) != null; boolean isJavaProject = JavaProject.hasJavaNature(proj); if (!wasJavaProject && !isJavaProject) { elementType = NON_JAVA_RESOURCE; } else { -// rootInfo = this.enclosingRootInfo(res.getFullPath(), delta.getKind()); -// if (rootInfo != null && rootInfo.isRootOfProject(res.getFullPath())) { -// elementType = IJavaElement.PACKAGE_FRAGMENT_ROOT; -// } else { - elementType = IJavaElement.JAVA_PROJECT; -// } + // rootInfo = this.enclosingRootInfo(res.getFullPath(), + // delta.getKind()); + // if (rootInfo != null && + // rootInfo.isRootOfProject(res.getFullPath())) { + // elementType = IJavaElement.PACKAGE_FRAGMENT_ROOT; + // } else { + elementType = IJavaElement.JAVA_PROJECT; + // } } - + // traverse delta -// this.traverseDelta(delta, elementType, rootInfo, null); - + // this.traverseDelta(delta, elementType, rootInfo, null); + if (elementType == NON_JAVA_RESOURCE - || (wasJavaProject != isJavaProject && (delta.getKind()) == IResourceDelta.CHANGED)) { // project has changed nature (description or open/closed) + || (wasJavaProject != isJavaProject && (delta.getKind()) == IResourceDelta.CHANGED)) { // project + // has + // changed + // nature + // (description + // or + // open/closed) try { // add child as non java resource - nonJavaResourcesChanged((JavaModel)model, delta); + nonJavaResourcesChanged((JavaModel) model, delta); } catch (JavaModelException e) { // java model could not be opened } } } -// refreshPackageFragmentRoots(); -// resetProjectCaches(); + // refreshPackageFragmentRoots(); + // resetProjectCaches(); return this.currentDelta; } finally { this.currentDelta = null; -// this.rootsToRefresh.clear(); -// this.projectCachesToReset.clear(); + // this.rootsToRefresh.clear(); + // this.projectCachesToReset.clear(); } } - + /* - * Converts an IResourceDelta and its children into - * the corresponding IJavaElementDeltas. + * Converts an IResourceDelta and its children into the + * corresponding IJavaElementDeltas. */ -// private void traverseDelta( -// IResourceDelta delta, -// int elementType, -// RootInfo rootInfo, -// OutputsInfo outputsInfo) { -// -// IResource res = delta.getResource(); -// -// // set stack of elements -// if (this.currentElement == null && rootInfo != null) { -//// this.currentElement = rootInfo.project; -// } -// -// // process current delta -// boolean processChildren = true; -// if (res instanceof IProject) { -// processChildren = -// this.updateCurrentDeltaAndIndex( -// delta, -// elementType == IJavaElement.PACKAGE_FRAGMENT_ROOT ? -// IJavaElement.JAVA_PROJECT : // case of prj=src -// elementType, -// rootInfo); -// } else if (rootInfo != null) { -// processChildren = this.updateCurrentDeltaAndIndex(delta, elementType, rootInfo); -// } else { -// // not yet inside a package fragment root -// processChildren = true; -// } -// -// // get the project's output locations and traverse mode -// if (outputsInfo == null) outputsInfo = this.outputsInfo(rootInfo, res); -// -// // process children if needed -// if (processChildren) { -// IResourceDelta[] children = delta.getAffectedChildren(); -// boolean oneChildOnClasspath = false; -// int length = children.length; -// IResourceDelta[] orphanChildren = null; -// Openable parent = null; -// boolean isValidParent = true; -// for (int i = 0; i < length; i++) { -// IResourceDelta child = children[i]; -// IResource childRes = child.getResource(); -// -// // check source attachment change -// this.checkSourceAttachmentChange(child, childRes); -// -// // find out whether the child is a package fragment root of the current project -// IPath childPath = childRes.getFullPath(); -// int childKind = child.getKind(); -// RootInfo childRootInfo = this.rootInfo(childPath, childKind); -// if (childRootInfo != null && !childRootInfo.isRootOfProject(childPath)) { -// // package fragment root of another project (dealt with later) -// childRootInfo = null; -// } -// -// // compute child type -// int childType = -// this.elementType( -// childRes, -// childKind, -// elementType, -// rootInfo == null ? childRootInfo : rootInfo -// ); -// -// // is childRes in the output folder and is it filtered out ? -// boolean isResFilteredFromOutput = this.isResFilteredFromOutput(outputsInfo, childRes, childType); -// -// boolean isNestedRoot = rootInfo != null && childRootInfo != null; -// if (!isResFilteredFromOutput -// && !isNestedRoot) { // do not treat as non-java rsc if nested root -// -// this.traverseDelta(child, childType, rootInfo == null ? childRootInfo : rootInfo, outputsInfo); // traverse delta for child in the same project -// -// if (childType == NON_JAVA_RESOURCE) { -// if (rootInfo != null) { // if inside a package fragment root -// if (!isValidParent) continue; -// if (parent == null) { -// // find the parent of the non-java resource to attach to -// if (this.currentElement == null -// || !rootInfo.project.equals(this.currentElement.getJavaProject())) { // note if currentElement is the IJavaModel, getJavaProject() is null -// // force the currentProject to be used -// this.currentElement = rootInfo.project; -// } -// if (elementType == IJavaElement.JAVA_PROJECT -// || (elementType == IJavaElement.PACKAGE_FRAGMENT_ROOT -// && res instanceof IProject)) { -// // NB: attach non-java resource to project (not to its package fragment root) -// parent = rootInfo.project; -// } else { -// parent = this.createElement(res, elementType, rootInfo); -// } -// if (parent == null) { -// isValidParent = false; -// continue; -// } -// } -// // add child as non java resource -// try { -// nonJavaResourcesChanged(parent, child); -// } catch (JavaModelException e) { -// // ignore -// } -// } else { -// // the non-java resource (or its parent folder) will be attached to the java project -// if (orphanChildren == null) orphanChildren = new IResourceDelta[length]; -// orphanChildren[i] = child; -// } -// } else { -// oneChildOnClasspath = true; -// } -// } else { -// oneChildOnClasspath = true; // to avoid reporting child delta as non-java resource delta -// } -// -// // if child is a nested root -// // or if it is not a package fragment root of the current project -// // but it is a package fragment root of another project, traverse delta too -// if (isNestedRoot -// || (childRootInfo == null && (childRootInfo = this.rootInfo(childPath, childKind)) != null)) { -// this.traverseDelta(child, IJavaElement.PACKAGE_FRAGMENT_ROOT, childRootInfo, null); // binary output of childRootInfo.project cannot be this root -// } -// -// // if the child is a package fragment root of one or several other projects -// ArrayList rootList; -// if ((rootList = this.otherRootsInfo(childPath, childKind)) != null) { -// Iterator iterator = rootList.iterator(); -// while (iterator.hasNext()) { -// childRootInfo = (RootInfo) iterator.next(); -// this.traverseDelta(child, IJavaElement.PACKAGE_FRAGMENT_ROOT, childRootInfo, null); // binary output of childRootInfo.project cannot be this root -// } -// } -// } -// if (orphanChildren != null -// && (oneChildOnClasspath // orphan children are siblings of a package fragment root -// || res instanceof IProject)) { // non-java resource directly under a project -// -// // attach orphan children -// IProject rscProject = res.getProject(); -// JavaProject adoptiveProject = (JavaProject)JavaCore.create(rscProject); -// if (adoptiveProject != null -// && JavaProject.hasJavaNature(rscProject)) { // delta iff Java project (18698) -// for (int i = 0; i < length; i++) { -// if (orphanChildren[i] != null) { -// try { -// nonJavaResourcesChanged(adoptiveProject, orphanChildren[i]); -// } catch (JavaModelException e) { -// // ignore -// } -// } -// } -// } -// } // else resource delta will be added by parent -// } // else resource delta will be added by parent -// } - private void notifyListeners(IJavaElementDelta deltaToNotify, int eventType, IElementChangedListener[] listeners, int[] listenerMask, int listenerCount) { - final ElementChangedEvent extraEvent = new ElementChangedEvent(deltaToNotify, eventType); - for (int i= 0; i < listenerCount; i++) { - if ((listenerMask[i] & eventType) != 0){ + // private void traverseDelta( + // IResourceDelta delta, + // int elementType, + // RootInfo rootInfo, + // OutputsInfo outputsInfo) { + // + // IResource res = delta.getResource(); + // + // // set stack of elements + // if (this.currentElement == null && rootInfo != null) { + // // this.currentElement = rootInfo.project; + // } + // + // // process current delta + // boolean processChildren = true; + // if (res instanceof IProject) { + // processChildren = + // this.updateCurrentDeltaAndIndex( + // delta, + // elementType == IJavaElement.PACKAGE_FRAGMENT_ROOT ? + // IJavaElement.JAVA_PROJECT : // case of prj=src + // elementType, + // rootInfo); + // } else if (rootInfo != null) { + // processChildren = this.updateCurrentDeltaAndIndex(delta, elementType, + // rootInfo); + // } else { + // // not yet inside a package fragment root + // processChildren = true; + // } + // + // // get the project's output locations and traverse mode + // if (outputsInfo == null) outputsInfo = this.outputsInfo(rootInfo, res); + // + // // process children if needed + // if (processChildren) { + // IResourceDelta[] children = delta.getAffectedChildren(); + // boolean oneChildOnClasspath = false; + // int length = children.length; + // IResourceDelta[] orphanChildren = null; + // Openable parent = null; + // boolean isValidParent = true; + // for (int i = 0; i < length; i++) { + // IResourceDelta child = children[i]; + // IResource childRes = child.getResource(); + // + // // check source attachment change + // this.checkSourceAttachmentChange(child, childRes); + // + // // find out whether the child is a package fragment root of the current + // project + // IPath childPath = childRes.getFullPath(); + // int childKind = child.getKind(); + // RootInfo childRootInfo = this.rootInfo(childPath, childKind); + // if (childRootInfo != null && !childRootInfo.isRootOfProject(childPath)) { + // // package fragment root of another project (dealt with later) + // childRootInfo = null; + // } + // + // // compute child type + // int childType = + // this.elementType( + // childRes, + // childKind, + // elementType, + // rootInfo == null ? childRootInfo : rootInfo + // ); + // + // // is childRes in the output folder and is it filtered out ? + // boolean isResFilteredFromOutput = + // this.isResFilteredFromOutput(outputsInfo, childRes, childType); + // + // boolean isNestedRoot = rootInfo != null && childRootInfo != null; + // if (!isResFilteredFromOutput + // && !isNestedRoot) { // do not treat as non-java rsc if nested root + // + // this.traverseDelta(child, childType, rootInfo == null ? childRootInfo : + // rootInfo, outputsInfo); // traverse delta for child in the same project + // + // if (childType == NON_JAVA_RESOURCE) { + // if (rootInfo != null) { // if inside a package fragment root + // if (!isValidParent) continue; + // if (parent == null) { + // // find the parent of the non-java resource to attach to + // if (this.currentElement == null + // || !rootInfo.project.equals(this.currentElement.getJavaProject())) { // + // note if currentElement is the IJavaModel, getJavaProject() is null + // // force the currentProject to be used + // this.currentElement = rootInfo.project; + // } + // if (elementType == IJavaElement.JAVA_PROJECT + // || (elementType == IJavaElement.PACKAGE_FRAGMENT_ROOT + // && res instanceof IProject)) { + // // NB: attach non-java resource to project (not to its package fragment + // root) + // parent = rootInfo.project; + // } else { + // parent = this.createElement(res, elementType, rootInfo); + // } + // if (parent == null) { + // isValidParent = false; + // continue; + // } + // } + // // add child as non java resource + // try { + // nonJavaResourcesChanged(parent, child); + // } catch (JavaModelException e) { + // // ignore + // } + // } else { + // // the non-java resource (or its parent folder) will be attached to the + // java project + // if (orphanChildren == null) orphanChildren = new IResourceDelta[length]; + // orphanChildren[i] = child; + // } + // } else { + // oneChildOnClasspath = true; + // } + // } else { + // oneChildOnClasspath = true; // to avoid reporting child delta as non-java + // resource delta + // } + // + // // if child is a nested root + // // or if it is not a package fragment root of the current project + // // but it is a package fragment root of another project, traverse delta + // too + // if (isNestedRoot + // || (childRootInfo == null && (childRootInfo = this.rootInfo(childPath, + // childKind)) != null)) { + // this.traverseDelta(child, IJavaElement.PACKAGE_FRAGMENT_ROOT, + // childRootInfo, null); // binary output of childRootInfo.project cannot be + // this root + // } + // + // // if the child is a package fragment root of one or several other + // projects + // ArrayList rootList; + // if ((rootList = this.otherRootsInfo(childPath, childKind)) != null) { + // Iterator iterator = rootList.iterator(); + // while (iterator.hasNext()) { + // childRootInfo = (RootInfo) iterator.next(); + // this.traverseDelta(child, IJavaElement.PACKAGE_FRAGMENT_ROOT, + // childRootInfo, null); // binary output of childRootInfo.project cannot be + // this root + // } + // } + // } + // if (orphanChildren != null + // && (oneChildOnClasspath // orphan children are siblings of a package + // fragment root + // || res instanceof IProject)) { // non-java resource directly under a + // project + // + // // attach orphan children + // IProject rscProject = res.getProject(); + // JavaProject adoptiveProject = (JavaProject)JavaCore.create(rscProject); + // if (adoptiveProject != null + // && JavaProject.hasJavaNature(rscProject)) { // delta iff Java project + // (18698) + // for (int i = 0; i < length; i++) { + // if (orphanChildren[i] != null) { + // try { + // nonJavaResourcesChanged(adoptiveProject, orphanChildren[i]); + // } catch (JavaModelException e) { + // // ignore + // } + // } + // } + // } + // } // else resource delta will be added by parent + // } // else resource delta will be added by parent + // } + private void notifyListeners(IJavaElementDelta deltaToNotify, + int eventType, IElementChangedListener[] listeners, + int[] listenerMask, int listenerCount) { + final ElementChangedEvent extraEvent = new ElementChangedEvent( + deltaToNotify, eventType); + for (int i = 0; i < listenerCount; i++) { + if ((listenerMask[i] & eventType) != 0) { final IElementChangedListener listener = listeners[i]; long start = -1; if (VERBOSE) { - System.out.print("Listener #" + (i+1) + "=" + listener.toString());//$NON-NLS-1$//$NON-NLS-2$ + System.out + .print("Listener #" + (i + 1) + "=" + listener.toString());//$NON-NLS-1$//$NON-NLS-2$ start = System.currentTimeMillis(); } - // wrap callbacks with Safe runnable for subsequent listeners to be called when some are causing grief + // wrap callbacks with Safe runnable for subsequent listeners to + // be called when some are causing grief Platform.run(new ISafeRunnable() { public void handleException(Throwable exception) { - Util.log(exception, "Exception occurred in listener of Java element change notification"); //$NON-NLS-1$ + Util + .log(exception, + "Exception occurred in listener of Java element change notification"); //$NON-NLS-1$ } + public void run() throws Exception { listener.elementChanged(extraEvent); } }); if (VERBOSE) { - System.out.println(" -> " + (System.currentTimeMillis()-start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ + System.out + .println(" -> " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ } } } } -// private void notifyTypeHierarchies(IElementChangedListener[] listeners, int listenerCount) { -// for (int i= 0; i < listenerCount; i++) { -// final IElementChangedListener listener = listeners[i]; -// if (!(listener instanceof TypeHierarchy)) continue; -// -// // wrap callbacks with Safe runnable for subsequent listeners to be called when some are causing grief -// Platform.run(new ISafeRunnable() { -// public void handleException(Throwable exception) { -// ProjectPrefUtil.log(exception, "Exception occurred in listener of Java element change notification"); //$NON-NLS-1$ -// } -// public void run() throws Exception { -// TypeHierarchy typeHierarchy = (TypeHierarchy)listener; -// if (typeHierarchy.hasFineGrainChanges()) { -// // case of changes in primary working copies -// typeHierarchy.needsRefresh = true; -// typeHierarchy.fireChange(); -// } -// } -// }); -// } -// } + + // private void notifyTypeHierarchies(IElementChangedListener[] listeners, + // int listenerCount) { + // for (int i= 0; i < listenerCount; i++) { + // final IElementChangedListener listener = listeners[i]; + // if (!(listener instanceof TypeHierarchy)) continue; + // + // // wrap callbacks with Safe runnable for subsequent listeners to be + // called when some are causing grief + // Platform.run(new ISafeRunnable() { + // public void handleException(Throwable exception) { + // ProjectPrefUtil.log(exception, "Exception occurred in listener of Java + // element change notification"); //$NON-NLS-1$ + // } + // public void run() throws Exception { + // TypeHierarchy typeHierarchy = (TypeHierarchy)listener; + // if (typeHierarchy.hasFineGrainChanges()) { + // // case of changes in primary working copies + // typeHierarchy.needsRefresh = true; + // typeHierarchy.fireChange(); + // } + // } + // }); + // } + // } /* - * Generic processing for elements with changed contents:
                                        - *
                                      • The element is closed such that any subsequent accesses will re-open - * the element reflecting its new structure. - *
                                      • An entry is made in the delta reporting a content change (K_CHANGE with F_CONTENT flag set). - *
                                      + * Generic processing for elements with changed contents:
                                      • The + * element is closed such that any subsequent accesses will re-open the + * element reflecting its new structure.
                                      • An entry is made in the delta + * reporting a content change (K_CHANGE with F_CONTENT flag set).
                                      */ private void nonJavaResourcesChanged(Openable element, IResourceDelta delta) - throws JavaModelException { + throws JavaModelException { // reset non-java resources if element was open if (element.isOpen()) { - JavaElementInfo info = (JavaElementInfo)element.getElementInfo(); + JavaElementInfo info = (JavaElementInfo) element.getElementInfo(); switch (element.getElementType()) { - case IJavaElement.JAVA_MODEL : - ((JavaModelInfo) info).nonJavaResources = null; - currentDelta().addResourceDelta(delta); - return; - case IJavaElement.JAVA_PROJECT : - ((JavaProjectElementInfo) info).setNonJavaResources(null); - - // if a package fragment root is the project, clear it too - JavaProject project = (JavaProject) element; - PackageFragmentRoot projectRoot = - (PackageFragmentRoot) project.getPackageFragmentRoot(project.getProject()); - if (projectRoot.isOpen()) { - ((PackageFragmentRootInfo) projectRoot.getElementInfo()).setNonJavaResources( - null); - } - break; - case IJavaElement.PACKAGE_FRAGMENT : - ((PackageFragmentInfo) info).setNonJavaResources(null); - break; - case IJavaElement.PACKAGE_FRAGMENT_ROOT : - ((PackageFragmentRootInfo) info).setNonJavaResources(null); + case IJavaElement.JAVA_MODEL: + ((JavaModelInfo) info).nonJavaResources = null; + currentDelta().addResourceDelta(delta); + return; + case IJavaElement.JAVA_PROJECT: + ((JavaProjectElementInfo) info).setNonJavaResources(null); + + // if a package fragment root is the project, clear it too + JavaProject project = (JavaProject) element; + PackageFragmentRoot projectRoot = (PackageFragmentRoot) project + .getPackageFragmentRoot(project.getProject()); + if (projectRoot.isOpen()) { + ((PackageFragmentRootInfo) projectRoot.getElementInfo()) + .setNonJavaResources(null); + } + break; + case IJavaElement.PACKAGE_FRAGMENT: + ((PackageFragmentInfo) info).setNonJavaResources(null); + break; + case IJavaElement.PACKAGE_FRAGMENT_ROOT: + ((PackageFragmentRootInfo) info).setNonJavaResources(null); } } JavaElementDelta current = currentDelta(); JavaElementDelta elementDelta = current.find(element); if (elementDelta == null) { - // don't use find after creating the delta as it can be null (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=63434) - elementDelta = current.changed(element, IJavaElementDelta.F_CONTENT); + // don't use find after creating the delta as it can be null (see + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=63434) + elementDelta = current + .changed(element, IJavaElementDelta.F_CONTENT); } elementDelta.addResourceDelta(delta); } + /* * Flushes all deltas without firing them. */ public void flush() { this.javaModelDeltas = new ArrayList(); } + /* - * Finds the root info this path is included in. - * Returns null if not found. + * Finds the root info this path is included in. Returns null if not found. */ RootInfo enclosingRootInfo(IPath path, int kind) { while (path != null && path.segmentCount() > 0) { - RootInfo rootInfo = this.rootInfo(path, kind); - if (rootInfo != null) return rootInfo; + RootInfo rootInfo = this.rootInfo(path, kind); + if (rootInfo != null) + return rootInfo; path = path.removeLastSegments(1); } return null; } + /* - * Fire Java Model delta, flushing them after the fact after post_change notification. - * If the firing mode has been turned off, this has no effect. + * Fire Java Model delta, flushing them after the fact after post_change + * notification. If the firing mode has been turned off, this has no effect. */ public void fire(IJavaElementDelta customDelta, int eventType) { - if (!this.isFiring) return; - + if (!this.isFiring) + return; + if (DEBUG) { - System.out.println("-----------------------------------------------------------------------------------------------------------------------");//$NON-NLS-1$ + System.out + .println("-----------------------------------------------------------------------------------------------------------------------");//$NON-NLS-1$ } IJavaElementDelta deltaToNotify; - if (customDelta == null){ + if (customDelta == null) { deltaToNotify = this.mergeDeltas(this.javaModelDeltas); } else { deltaToNotify = customDelta; } - + // Refresh internal scopes -// if (deltaToNotify != null) { -// Iterator scopes = this.manager.searchScopes.keySet().iterator(); -// while (scopes.hasNext()) { -// AbstractSearchScope scope = (AbstractSearchScope)scopes.next(); -// scope.processDelta(deltaToNotify); -// } -// } - + // if (deltaToNotify != null) { + // Iterator scopes = this.manager.searchScopes.keySet().iterator(); + // while (scopes.hasNext()) { + // AbstractSearchScope scope = (AbstractSearchScope)scopes.next(); + // scope.processDelta(deltaToNotify); + // } + // } + // Notification - - // Important: if any listener reacts to notification by updating the listeners list or mask, these lists will - // be duplicated, so it is necessary to remember original lists in a variable (since field values may change under us) + + // Important: if any listener reacts to notification by updating the + // listeners list or mask, these lists will + // be duplicated, so it is necessary to remember original lists in a + // variable (since field values may change under us) IElementChangedListener[] listeners = this.state.elementChangedListeners; int[] listenerMask = this.state.elementChangedListenerMasks; int listenerCount = this.state.elementChangedListenerCount; switch (eventType) { - case DEFAULT_CHANGE_EVENT: - firePostChangeDelta(deltaToNotify, listeners, listenerMask, listenerCount); - fireReconcileDelta(listeners, listenerMask, listenerCount); - break; - case ElementChangedEvent.POST_CHANGE: - firePostChangeDelta(deltaToNotify, listeners, listenerMask, listenerCount); - fireReconcileDelta(listeners, listenerMask, listenerCount); - break; + case DEFAULT_CHANGE_EVENT: + firePostChangeDelta(deltaToNotify, listeners, listenerMask, + listenerCount); + fireReconcileDelta(listeners, listenerMask, listenerCount); + break; + case ElementChangedEvent.POST_CHANGE: + firePostChangeDelta(deltaToNotify, listeners, listenerMask, + listenerCount); + fireReconcileDelta(listeners, listenerMask, listenerCount); + break; } } - - private void firePostChangeDelta( - IJavaElementDelta deltaToNotify, - IElementChangedListener[] listeners, - int[] listenerMask, - int listenerCount) { - - // post change deltas - if (DEBUG){ - System.out.println("FIRING POST_CHANGE Delta ["+Thread.currentThread()+"]:"); //$NON-NLS-1$//$NON-NLS-2$ - System.out.println(deltaToNotify == null ? "" : deltaToNotify.toString()); //$NON-NLS-1$ - } - if (deltaToNotify != null) { - // flush now so as to keep listener reactions to post their own deltas for subsequent iteration - this.flush(); - - notifyListeners(deltaToNotify, ElementChangedEvent.POST_CHANGE, listeners, listenerMask, listenerCount); - } - } - private void fireReconcileDelta( - IElementChangedListener[] listeners, - int[] listenerMask, + + private void firePostChangeDelta(IJavaElementDelta deltaToNotify, + IElementChangedListener[] listeners, int[] listenerMask, int listenerCount) { + // post change deltas + if (DEBUG) { + System.out + .println("FIRING POST_CHANGE Delta [" + Thread.currentThread() + "]:"); //$NON-NLS-1$//$NON-NLS-2$ + System.out + .println(deltaToNotify == null ? "" : deltaToNotify.toString()); //$NON-NLS-1$ + } + if (deltaToNotify != null) { + // flush now so as to keep listener reactions to post their own + // deltas for subsequent iteration + this.flush(); - IJavaElementDelta deltaToNotify = mergeDeltas(this.reconcileDeltas.values()); - if (DEBUG){ - System.out.println("FIRING POST_RECONCILE Delta ["+Thread.currentThread()+"]:"); //$NON-NLS-1$//$NON-NLS-2$ - System.out.println(deltaToNotify == null ? "" : deltaToNotify.toString()); //$NON-NLS-1$ - } - if (deltaToNotify != null) { - // flush now so as to keep listener reactions to post their own deltas for subsequent iteration - this.reconcileDeltas = new HashMap(); - - notifyListeners(deltaToNotify, ElementChangedEvent.POST_RECONCILE, listeners, listenerMask, listenerCount); - } + notifyListeners(deltaToNotify, ElementChangedEvent.POST_CHANGE, + listeners, listenerMask, listenerCount); } + } + + private void fireReconcileDelta(IElementChangedListener[] listeners, + int[] listenerMask, int listenerCount) { + + IJavaElementDelta deltaToNotify = mergeDeltas(this.reconcileDeltas + .values()); + if (DEBUG) { + System.out + .println("FIRING POST_RECONCILE Delta [" + Thread.currentThread() + "]:"); //$NON-NLS-1$//$NON-NLS-2$ + System.out + .println(deltaToNotify == null ? "" : deltaToNotify.toString()); //$NON-NLS-1$ + } + if (deltaToNotify != null) { + // flush now so as to keep listener reactions to post their own + // deltas for subsequent iteration + this.reconcileDeltas = new HashMap(); + + notifyListeners(deltaToNotify, ElementChangedEvent.POST_RECONCILE, + listeners, listenerMask, listenerCount); + } + } + /* - * Returns the root info for the given path. Look in the old roots table if kind is REMOVED. + * Returns the root info for the given path. Look in the old roots table if + * kind is REMOVED. */ RootInfo rootInfo(IPath path, int kind) { if (kind == IResourceDelta.REMOVED) { - return (RootInfo)this.oldRoots.get(path); + return (RootInfo) this.oldRoots.get(path); } else { - return (RootInfo)this.roots.get(path); + return (RootInfo) this.roots.get(path); } } + /* - * Returns the other root infos for the given path. Look in the old other roots table if kind is REMOVED. + * Returns the other root infos for the given path. Look in the old other + * roots table if kind is REMOVED. */ ArrayList otherRootsInfo(IPath path, int kind) { if (kind == IResourceDelta.REMOVED) { - return (ArrayList)this.oldOtherRoots.get(path); + return (ArrayList) this.oldOtherRoots.get(path); } else { - return (ArrayList)this.otherRoots.get(path); + return (ArrayList) this.otherRoots.get(path); } - } + } /** - * Converts an IResourceDelta and its children into - * the corresponding IJavaElementDeltas. - * Return whether the delta corresponds to a java element. - * If it is not a java element, it will be added as a non-java - * resource by the sender of this method. + * Converts an IResourceDelta and its children into the + * corresponding IJavaElementDeltas. Return whether the + * delta corresponds to a java element. If it is not a java element, it will + * be added as a non-java resource by the sender of this method. */ -// protected boolean traverseDelta( -// IResourceDelta delta, -// int elementType, -// RootInfo rootInfo, -// OutputsInfo outputsInfo) { -// -// IResource res = delta.getResource(); -// -// // set stack of elements -// if (this.currentElement == null && rootInfo != null) { -// this.currentElement = (Openable)rootInfo.project; -// } -// -// // process current delta -// boolean processChildren = true; -// if (res instanceof IProject) { -// processChildren = -// this.updateCurrentDeltaAndIndex( -// delta, -// elementType == IJavaElement.PACKAGE_FRAGMENT_ROOT ? -// IJavaElement.JAVA_PROJECT : // case of prj=src -// elementType, -// rootInfo); -// } else if (rootInfo != null) { -// processChildren = this.updateCurrentDeltaAndIndex(delta, elementType, rootInfo); -// } else { -// // not yet inside a package fragment root -// processChildren = true; -// } -// -// // get the project's output locations and traverse mode -// if (outputsInfo == null) outputsInfo = this.outputsInfo(rootInfo, res); -// -// // process children if needed -// if (processChildren) { -// IResourceDelta[] children = delta.getAffectedChildren(); -// boolean oneChildOnClasspath = false; -// int length = children.length; -// IResourceDelta[] orphanChildren = null; -// Openable parent = null; -// boolean isValidParent = true; -// for (int i = 0; i < length; i++) { -// IResourceDelta child = children[i]; -// IResource childRes = child.getResource(); -// -// // check source attachment change -// this.checkSourceAttachmentChange(child, childRes); -// -// // find out whether the child is a package fragment root of the current project -// IPath childPath = childRes.getFullPath(); -// int childKind = child.getKind(); -// RootInfo childRootInfo = this.rootInfo(childPath, childKind); -// if (childRootInfo != null && !childRootInfo.isRootOfProject(childPath)) { -// // package fragment root of another project (dealt with later) -// childRootInfo = null; -// } -// -// // compute child type -// int childType = -// this.elementType( -// childRes, -// childKind, -// elementType, -// rootInfo == null ? childRootInfo : rootInfo -// ); -// -// // is childRes in the output folder and is it filtered out ? -// boolean isResFilteredFromOutput = this.isResFilteredFromOutput(outputsInfo, childRes, childType); -// -// boolean isNestedRoot = rootInfo != null && childRootInfo != null; -// if (!isResFilteredFromOutput -// && !isNestedRoot) { // do not treat as non-java rsc if nested root -// if (!this.traverseDelta(child, childType, rootInfo == null ? childRootInfo : rootInfo, outputsInfo)) { // traverse delta for child in the same project -// // it is a non-java resource -// try { -// if (rootInfo != null) { // if inside a package fragment root -// if (!isValidParent) continue; -// if (parent == null) { -// // find the parent of the non-java resource to attach to -// if (this.currentElement == null -// || !this.currentElement.getJavaProject().equals(rootInfo.project)) { -// // force the currentProject to be used -// this.currentElement = (Openable)rootInfo.project; -// } -// if (elementType == IJavaElement.JAVA_PROJECT -// || (elementType == IJavaElement.PACKAGE_FRAGMENT_ROOT -// && res instanceof IProject)) { -// // NB: attach non-java resource to project (not to its package fragment root) -// parent = (Openable)rootInfo.project; -// } else { -// parent = this.createElement(res, elementType, rootInfo); -// } -// if (parent == null) { -// isValidParent = false; -// continue; -// } -// } -// // add child as non java resource -// nonJavaResourcesChanged(parent, child); -// } else { -// // the non-java resource (or its parent folder) will be attached to the java project -// if (orphanChildren == null) orphanChildren = new IResourceDelta[length]; -// orphanChildren[i] = child; -// } -// } catch (JavaModelException e) { -// } -// } else { -// oneChildOnClasspath = true; -// } -// } else { -// oneChildOnClasspath = true; // to avoid reporting child delta as non-java resource delta -// } -// -// // if child is a nested root -// // or if it is not a package fragment root of the current project -// // but it is a package fragment root of another project, traverse delta too -// if (isNestedRoot -// || (childRootInfo == null && (childRootInfo = this.rootInfo(childPath, childKind)) != null)) { -// this.traverseDelta(child, IJavaElement.PACKAGE_FRAGMENT_ROOT, childRootInfo, null); // binary output of childRootInfo.project cannot be this root -// // NB: No need to check the return value as the child can only be on the classpath -// } -// -// // if the child is a package fragment root of one or several other projects -// ArrayList rootList; -// if ((rootList = this.otherRootsInfo(childPath, childKind)) != null) { -// Iterator iterator = rootList.iterator(); -// while (iterator.hasNext()) { -// childRootInfo = (RootInfo) iterator.next(); -// this.traverseDelta(child, IJavaElement.PACKAGE_FRAGMENT_ROOT, childRootInfo, null); // binary output of childRootInfo.project cannot be this root -// } -// } -// } -// if (orphanChildren != null -// && (oneChildOnClasspath // orphan children are siblings of a package fragment root -// || res instanceof IProject)) { // non-java resource directly under a project -// -// // attach orphan children -// IProject rscProject = res.getProject(); -// JavaProject adoptiveProject = (JavaProject)JavaCore.create(rscProject); -// if (adoptiveProject != null -// && JavaProject.hasJavaNature(rscProject)) { // delta iff Java project (18698) -// for (int i = 0; i < length; i++) { -// if (orphanChildren[i] != null) { -// try { -// nonJavaResourcesChanged(adoptiveProject, orphanChildren[i]); -// } catch (JavaModelException e) { -// } -// } -// } -// } -// } // else resource delta will be added by parent -// return elementType != NON_JAVA_RESOURCE; // TODO: (jerome) do we still need to return? (check could be done by caller) -// } else { -// return elementType != NON_JAVA_RESOURCE; -// } -// } - + // protected boolean traverseDelta( + // IResourceDelta delta, + // int elementType, + // RootInfo rootInfo, + // OutputsInfo outputsInfo) { + // + // IResource res = delta.getResource(); + // + // // set stack of elements + // if (this.currentElement == null && rootInfo != null) { + // this.currentElement = (Openable)rootInfo.project; + // } + // + // // process current delta + // boolean processChildren = true; + // if (res instanceof IProject) { + // processChildren = + // this.updateCurrentDeltaAndIndex( + // delta, + // elementType == IJavaElement.PACKAGE_FRAGMENT_ROOT ? + // IJavaElement.JAVA_PROJECT : // case of prj=src + // elementType, + // rootInfo); + // } else if (rootInfo != null) { + // processChildren = this.updateCurrentDeltaAndIndex(delta, elementType, + // rootInfo); + // } else { + // // not yet inside a package fragment root + // processChildren = true; + // } + // + // // get the project's output locations and traverse mode + // if (outputsInfo == null) outputsInfo = this.outputsInfo(rootInfo, res); + // + // // process children if needed + // if (processChildren) { + // IResourceDelta[] children = delta.getAffectedChildren(); + // boolean oneChildOnClasspath = false; + // int length = children.length; + // IResourceDelta[] orphanChildren = null; + // Openable parent = null; + // boolean isValidParent = true; + // for (int i = 0; i < length; i++) { + // IResourceDelta child = children[i]; + // IResource childRes = child.getResource(); + // + // // check source attachment change + // this.checkSourceAttachmentChange(child, childRes); + // + // // find out whether the child is a package fragment root of the current + // project + // IPath childPath = childRes.getFullPath(); + // int childKind = child.getKind(); + // RootInfo childRootInfo = this.rootInfo(childPath, childKind); + // if (childRootInfo != null && !childRootInfo.isRootOfProject(childPath)) { + // // package fragment root of another project (dealt with later) + // childRootInfo = null; + // } + // + // // compute child type + // int childType = + // this.elementType( + // childRes, + // childKind, + // elementType, + // rootInfo == null ? childRootInfo : rootInfo + // ); + // + // // is childRes in the output folder and is it filtered out ? + // boolean isResFilteredFromOutput = + // this.isResFilteredFromOutput(outputsInfo, childRes, childType); + // + // boolean isNestedRoot = rootInfo != null && childRootInfo != null; + // if (!isResFilteredFromOutput + // && !isNestedRoot) { // do not treat as non-java rsc if nested root + // if (!this.traverseDelta(child, childType, rootInfo == null ? + // childRootInfo : rootInfo, outputsInfo)) { // traverse delta for child in + // the same project + // // it is a non-java resource + // try { + // if (rootInfo != null) { // if inside a package fragment root + // if (!isValidParent) continue; + // if (parent == null) { + // // find the parent of the non-java resource to attach to + // if (this.currentElement == null + // || !this.currentElement.getJavaProject().equals(rootInfo.project)) { + // // force the currentProject to be used + // this.currentElement = (Openable)rootInfo.project; + // } + // if (elementType == IJavaElement.JAVA_PROJECT + // || (elementType == IJavaElement.PACKAGE_FRAGMENT_ROOT + // && res instanceof IProject)) { + // // NB: attach non-java resource to project (not to its package fragment + // root) + // parent = (Openable)rootInfo.project; + // } else { + // parent = this.createElement(res, elementType, rootInfo); + // } + // if (parent == null) { + // isValidParent = false; + // continue; + // } + // } + // // add child as non java resource + // nonJavaResourcesChanged(parent, child); + // } else { + // // the non-java resource (or its parent folder) will be attached to the + // java project + // if (orphanChildren == null) orphanChildren = new IResourceDelta[length]; + // orphanChildren[i] = child; + // } + // } catch (JavaModelException e) { + // } + // } else { + // oneChildOnClasspath = true; + // } + // } else { + // oneChildOnClasspath = true; // to avoid reporting child delta as non-java + // resource delta + // } + // + // // if child is a nested root + // // or if it is not a package fragment root of the current project + // // but it is a package fragment root of another project, traverse delta + // too + // if (isNestedRoot + // || (childRootInfo == null && (childRootInfo = this.rootInfo(childPath, + // childKind)) != null)) { + // this.traverseDelta(child, IJavaElement.PACKAGE_FRAGMENT_ROOT, + // childRootInfo, null); // binary output of childRootInfo.project cannot be + // this root + // // NB: No need to check the return value as the child can only be on the + // classpath + // } + // + // // if the child is a package fragment root of one or several other + // projects + // ArrayList rootList; + // if ((rootList = this.otherRootsInfo(childPath, childKind)) != null) { + // Iterator iterator = rootList.iterator(); + // while (iterator.hasNext()) { + // childRootInfo = (RootInfo) iterator.next(); + // this.traverseDelta(child, IJavaElement.PACKAGE_FRAGMENT_ROOT, + // childRootInfo, null); // binary output of childRootInfo.project cannot be + // this root + // } + // } + // } + // if (orphanChildren != null + // && (oneChildOnClasspath // orphan children are siblings of a package + // fragment root + // || res instanceof IProject)) { // non-java resource directly under a + // project + // + // // attach orphan children + // IProject rscProject = res.getProject(); + // JavaProject adoptiveProject = (JavaProject)JavaCore.create(rscProject); + // if (adoptiveProject != null + // && JavaProject.hasJavaNature(rscProject)) { // delta iff Java project + // (18698) + // for (int i = 0; i < length; i++) { + // if (orphanChildren[i] != null) { + // try { + // nonJavaResourcesChanged(adoptiveProject, orphanChildren[i]); + // } catch (JavaModelException e) { + // } + // } + // } + // } + // } // else resource delta will be added by parent + // return elementType != NON_JAVA_RESOURCE; // TODO: (jerome) do we still + // need to return? (check could be done by caller) + // } else { + // return elementType != NON_JAVA_RESOURCE; + // } + // } /** - * Update the classpath markers and cycle markers for the projects to update. + * Update the classpath markers and cycle markers for the projects to + * update. */ -// void updateClasspathMarkers() { -// try { -// if (!ResourcesPlugin.getWorkspace().isAutoBuilding()) { -// Iterator iterator = this.projectsToUpdate.iterator(); -// while (iterator.hasNext()) { -// try { -// JavaProject project = (JavaProject)iterator.next(); -// -// // force classpath marker refresh -// project.getResolvedClasspath( -// true, // ignoreUnresolvedEntry -// true); // generateMarkerOnError -// -// } catch (JavaModelException e) { -// } -// } -// } -// if (!this.projectsToUpdate.isEmpty()){ -// try { -// // update all cycle markers -// JavaProject.updateAllCycleMarkers(); -// } catch (JavaModelException e) { -// } -// } -// } finally { -// this.projectsToUpdate = new HashSet(); -// } -// } - + // void updateClasspathMarkers() { + // try { + // if (!ResourcesPlugin.getWorkspace().isAutoBuilding()) { + // Iterator iterator = this.projectsToUpdate.iterator(); + // while (iterator.hasNext()) { + // try { + // JavaProject project = (JavaProject)iterator.next(); + // + // // force classpath marker refresh + // project.getResolvedClasspath( + // true, // ignoreUnresolvedEntry + // true); // generateMarkerOnError + // + // } catch (JavaModelException e) { + // } + // } + // } + // if (!this.projectsToUpdate.isEmpty()){ + // try { + // // update all cycle markers + // JavaProject.updateAllCycleMarkers(); + // } catch (JavaModelException e) { + // } + // } + // } finally { + // this.projectsToUpdate = new HashSet(); + // } + // } /* - * Update the current delta (ie. add/remove/change the given element) and update the correponding index. - * Returns whether the children of the given delta must be processed. - * @throws a JavaModelException if the delta doesn't correspond to a java element of the given type. + * Update the current delta (ie. add/remove/change the given element) and + * update the correponding index. Returns whether the children of the given + * delta must be processed. @throws a JavaModelException if the delta + * doesn't correspond to a java element of the given type. */ -// private boolean updateCurrentDeltaAndIndex(IResourceDelta delta, int elementType, RootInfo rootInfo) { -// Openable element; -// switch (delta.getKind()) { -// case IResourceDelta.ADDED : -// IResource deltaRes = delta.getResource(); -// element = this.createElement(deltaRes, elementType, rootInfo); -// if (element == null) { -// // resource might be containing shared roots (see bug 19058) -// this.updateRoots(deltaRes.getFullPath(), delta); -// return false; -// } -// this.updateIndex(element, delta); -// this.elementAdded(element, delta, rootInfo); -// return false; -// case IResourceDelta.REMOVED : -// deltaRes = delta.getResource(); -// element = this.createElement(deltaRes, elementType, rootInfo); -// if (element == null) { -// // resource might be containing shared roots (see bug 19058) -// this.updateRoots(deltaRes.getFullPath(), delta); -// return false; -// } -// this.updateIndex(element, delta); -// this.elementRemoved(element, delta, rootInfo); -// -// if (deltaRes.getType() == IResource.PROJECT){ -// // reset the corresponding project built state, since cannot reuse if added back -// this.manager.setLastBuiltState((IProject)deltaRes, null /*no state*/); -// } -// return false; -// case IResourceDelta.CHANGED : -// int flags = delta.getFlags(); -// if ((flags & IResourceDelta.CONTENT) != 0) { -// // content has changed -// element = this.createElement(delta.getResource(), elementType, rootInfo); -// if (element == null) return false; -// this.updateIndex(element, delta); -// this.contentChanged(element, delta); -// } else if (elementType == IJavaElement.JAVA_PROJECT) { -// if ((flags & IResourceDelta.OPEN) != 0) { -// // project has been opened or closed -// IProject res = (IProject)delta.getResource(); -// element = this.createElement(res, elementType, rootInfo); -// if (element == null) { -// // resource might be containing shared roots (see bug 19058) -// this.updateRoots(res.getFullPath(), delta); -// return false; -// } -// if (res.isOpen()) { -// if (JavaProject.hasJavaNature(res)) { -// this.elementAdded(element, delta, rootInfo); -// this.indexManager.indexAll(res); -// } -// } else { -// JavaModel javaModel = this.manager.getJavaModel(); -// boolean wasJavaProject = javaModel.findJavaProject(res) != null; -// if (wasJavaProject) { -// this.elementRemoved(element, delta, rootInfo); -// this.indexManager.discardJobs(element.getElementName()); -// this.indexManager.removeIndexFamily(res.getFullPath()); -// -// } -// } -// return false; // when a project is open/closed don't process children -// } -// if ((flags & IResourceDelta.DESCRIPTION) != 0) { -// IProject res = (IProject)delta.getResource(); -// JavaModel javaModel = this.manager.getJavaModel(); -// boolean wasJavaProject = javaModel.findJavaProject(res) != null; -// boolean isJavaProject = JavaProject.hasJavaNature(res); -// if (wasJavaProject != isJavaProject) { -// // project's nature has been added or removed -// element = this.createElement(res, elementType, rootInfo); -// if (element == null) return false; // note its resources are still visible as roots to other projects -// if (isJavaProject) { -// this.elementAdded(element, delta, rootInfo); -// this.indexManager.indexAll(res); -// } else { -// this.elementRemoved(element, delta, rootInfo); -// this.indexManager.discardJobs(element.getElementName()); -// this.indexManager.removeIndexFamily(res.getFullPath()); -// // reset the corresponding project built state, since cannot reuse if added back -// this.manager.setLastBuiltState(res, null /*no state*/); -// } -// return false; // when a project's nature is added/removed don't process children -// } -// } -// } -// return true; -// } -// return true; -// } - + // private boolean updateCurrentDeltaAndIndex(IResourceDelta delta, int + // elementType, RootInfo rootInfo) { + // Openable element; + // switch (delta.getKind()) { + // case IResourceDelta.ADDED : + // IResource deltaRes = delta.getResource(); + // element = this.createElement(deltaRes, elementType, rootInfo); + // if (element == null) { + // // resource might be containing shared roots (see bug 19058) + // this.updateRoots(deltaRes.getFullPath(), delta); + // return false; + // } + // this.updateIndex(element, delta); + // this.elementAdded(element, delta, rootInfo); + // return false; + // case IResourceDelta.REMOVED : + // deltaRes = delta.getResource(); + // element = this.createElement(deltaRes, elementType, rootInfo); + // if (element == null) { + // // resource might be containing shared roots (see bug 19058) + // this.updateRoots(deltaRes.getFullPath(), delta); + // return false; + // } + // this.updateIndex(element, delta); + // this.elementRemoved(element, delta, rootInfo); + // + // if (deltaRes.getType() == IResource.PROJECT){ + // // reset the corresponding project built state, since cannot reuse if + // added back + // this.manager.setLastBuiltState((IProject)deltaRes, null /*no state*/); + // } + // return false; + // case IResourceDelta.CHANGED : + // int flags = delta.getFlags(); + // if ((flags & IResourceDelta.CONTENT) != 0) { + // // content has changed + // element = this.createElement(delta.getResource(), elementType, rootInfo); + // if (element == null) return false; + // this.updateIndex(element, delta); + // this.contentChanged(element, delta); + // } else if (elementType == IJavaElement.JAVA_PROJECT) { + // if ((flags & IResourceDelta.OPEN) != 0) { + // // project has been opened or closed + // IProject res = (IProject)delta.getResource(); + // element = this.createElement(res, elementType, rootInfo); + // if (element == null) { + // // resource might be containing shared roots (see bug 19058) + // this.updateRoots(res.getFullPath(), delta); + // return false; + // } + // if (res.isOpen()) { + // if (JavaProject.hasJavaNature(res)) { + // this.elementAdded(element, delta, rootInfo); + // this.indexManager.indexAll(res); + // } + // } else { + // JavaModel javaModel = this.manager.getJavaModel(); + // boolean wasJavaProject = javaModel.findJavaProject(res) != null; + // if (wasJavaProject) { + // this.elementRemoved(element, delta, rootInfo); + // this.indexManager.discardJobs(element.getElementName()); + // this.indexManager.removeIndexFamily(res.getFullPath()); + // + // } + // } + // return false; // when a project is open/closed don't process children + // } + // if ((flags & IResourceDelta.DESCRIPTION) != 0) { + // IProject res = (IProject)delta.getResource(); + // JavaModel javaModel = this.manager.getJavaModel(); + // boolean wasJavaProject = javaModel.findJavaProject(res) != null; + // boolean isJavaProject = JavaProject.hasJavaNature(res); + // if (wasJavaProject != isJavaProject) { + // // project's nature has been added or removed + // element = this.createElement(res, elementType, rootInfo); + // if (element == null) return false; // note its resources are still + // visible as roots to other projects + // if (isJavaProject) { + // this.elementAdded(element, delta, rootInfo); + // this.indexManager.indexAll(res); + // } else { + // this.elementRemoved(element, delta, rootInfo); + // this.indexManager.discardJobs(element.getElementName()); + // this.indexManager.removeIndexFamily(res.getFullPath()); + // // reset the corresponding project built state, since cannot reuse if + // added back + // this.manager.setLastBuiltState(res, null /*no state*/); + // } + // return false; // when a project's nature is added/removed don't process + // children + // } + // } + // } + // return true; + // } + // return true; + // } /** - * Traverse the set of projects which have changed namespace, and refresh their dependents + * Traverse the set of projects which have changed namespace, and refresh + * their dependents */ -// public void updateDependentNamelookups() { -// Iterator iterator; -// // update namelookup of dependent projects -// iterator = this.projectsForDependentNamelookupRefresh.iterator(); -// HashSet affectedDependents = new HashSet(); -// while (iterator.hasNext()) { -// JavaProject project = (JavaProject)iterator.next(); -// addDependentProjects(project.getPath(), affectedDependents); -// } -// iterator = affectedDependents.iterator(); -// while (iterator.hasNext()) { -// JavaProject project = (JavaProject) iterator.next(); -// if (project.isOpen()){ -// try { -// ((JavaProjectElementInfo)project.getElementInfo()).setNameLookup(null); -// } catch (JavaModelException e) { -// } -// } -// } -// } - -//protected void updateIndex(Openable element, IResourceDelta delta) { -// -// if (indexManager == null) -// return; -// -// switch (element.getElementType()) { -// case IJavaElement.JAVA_PROJECT : -// switch (delta.getKind()) { -// case IResourceDelta.ADDED : -// this.indexManager.indexAll(element.getJavaProject().getProject()); -// break; -// case IResourceDelta.REMOVED : -// this.indexManager.removeIndexFamily(element.getJavaProject().getProject().getFullPath()); -// // NB: Discarding index jobs belonging to this project was done during PRE_DELETE -// break; -// // NB: Update of index if project is opened, closed, or its java nature is added or removed -// // is done in updateCurrentDeltaAndIndex -// } -// break; -// case IJavaElement.PACKAGE_FRAGMENT_ROOT : -// if (element instanceof JarPackageFragmentRoot) { -// JarPackageFragmentRoot root = (JarPackageFragmentRoot)element; -// // index jar file only once (if the root is in its declaring project) -// IPath jarPath = root.getPath(); -// switch (delta.getKind()) { -// case IResourceDelta.ADDED: -// // index the new jar -// indexManager.indexLibrary(jarPath, root.getJavaProject().getProject()); -// break; -// case IResourceDelta.CHANGED: -// // first remove the index so that it is forced to be re-indexed -// indexManager.removeIndex(jarPath); -// // then index the jar -// indexManager.indexLibrary(jarPath, root.getJavaProject().getProject()); -// break; -// case IResourceDelta.REMOVED: -// // the jar was physically removed: remove the index -// this.indexManager.discardJobs(jarPath.toString()); -// this.indexManager.removeIndex(jarPath); -// break; -// } -// break; -// } else { -// int kind = delta.getKind(); -// if (kind == IResourceDelta.ADDED || kind == IResourceDelta.REMOVED) { -// IPackageFragmentRoot root = (IPackageFragmentRoot)element; -// this.updateRootIndex(root, root.getPackageFragment(""), delta); //$NON-NLS-1$ -// break; -// } -// } -// // don't break as packages of the package fragment root can be indexed below -// case IJavaElement.PACKAGE_FRAGMENT : -// switch (delta.getKind()) { -// case IResourceDelta.ADDED: -// case IResourceDelta.REMOVED: -// IPackageFragment pkg = null; -// if (element instanceof IPackageFragmentRoot) { -// IPackageFragmentRoot root = (IPackageFragmentRoot)element; -// pkg = root.getPackageFragment(""); //$NON-NLS-1$ -// } else { -// pkg = (IPackageFragment)element; -// } -// IResourceDelta[] children = delta.getAffectedChildren(); -// for (int i = 0, length = children.length; i < length; i++) { -// IResourceDelta child = children[i]; -// IResource resource = child.getResource(); -// if (resource instanceof IFile) { -// String name = resource.getName(); -// if (ProjectPrefUtil.isJavaFileName(name)) { -// Openable cu = (Openable)pkg.getCompilationUnit(name); -// this.updateIndex(cu, child); -// } else if (ProjectPrefUtil.isClassFileName(name)) { -// Openable classFile = (Openable)pkg.getClassFile(name); -// this.updateIndex(classFile, child); -// } -// } -// } -// break; -// } -// break; -// case IJavaElement.CLASS_FILE : -// IFile file = (IFile) delta.getResource(); -// IJavaProject project = element.getJavaProject(); -// IPath binaryFolderPath = element.getPackageFragmentRoot().getPath(); -// // if the class file is part of the binary output, it has been created by -// // the java builder -> ignore -// try { -// if (binaryFolderPath.equals(project.getOutputLocation())) { -// break; -// } -// } catch (JavaModelException e) { -// } -// switch (delta.getKind()) { -// case IResourceDelta.CHANGED : -// // no need to index if the content has not changed -// if ((delta.getFlags() & IResourceDelta.CONTENT) == 0) -// break; -// case IResourceDelta.ADDED : -// indexManager.addBinary(file, binaryFolderPath); -// break; -// case IResourceDelta.REMOVED : -// indexManager.remove(file.getFullPath().toString(), binaryFolderPath); -// break; -// } -// break; -// case IJavaElement.COMPILATION_UNIT : -// file = (IFile) delta.getResource(); -// switch (delta.getKind()) { -// case IResourceDelta.CHANGED : -// // no need to index if the content has not changed -// if ((delta.getFlags() & IResourceDelta.CONTENT) == 0) -// break; -// case IResourceDelta.ADDED : -// indexManager.addSource(file, file.getProject().getProject().getFullPath()); -// break; -// case IResourceDelta.REMOVED : -// indexManager.remove(file.getFullPath().toString(), file.getProject().getProject().getFullPath()); -// break; -// } -// } -//} - -/** - * Upadtes the index of the given root (assuming it's an addition or a removal). - * This is done recusively, pkg being the current package. - */ -//private void updateRootIndex(IPackageFragmentRoot root, IPackageFragment pkg, IResourceDelta delta) { -// this.updateIndex((Openable)pkg, delta); -// IResourceDelta[] children = delta.getAffectedChildren(); -// String name = pkg.getElementName(); -// for (int i = 0, length = children.length; i < length; i++) { -// IResourceDelta child = children[i]; -// IResource resource = child.getResource(); -// if (resource instanceof IFolder) { -// String subpkgName = -// name.length() == 0 ? -// resource.getName() : -// name + "." + resource.getName(); //$NON-NLS-1$ -// IPackageFragment subpkg = root.getPackageFragment(subpkgName); -// this.updateRootIndex(root, subpkg, child); -// } -// } -//} -/* - * Update the roots that are affected by the addition or the removal of the given container resource. - */ -//private void updateRoots(IPath containerPath, IResourceDelta containerDelta) { -// Map roots; -// Map otherRoots; -// if (containerDelta.getKind() == IResourceDelta.REMOVED) { -// roots = this.oldRoots; -// otherRoots = this.oldOtherRoots; -// } else { -// roots = this.roots; -// otherRoots = this.otherRoots; -// } -// Iterator iterator = roots.keySet().iterator(); -// while (iterator.hasNext()) { -// IPath path = (IPath)iterator.next(); -// if (containerPath.isPrefixOf(path) && !containerPath.equals(path)) { -// IResourceDelta rootDelta = containerDelta.findMember(path.removeFirstSegments(1)); -// if (rootDelta == null) continue; -// RootInfo rootInfo = (RootInfo)roots.get(path); -// -// if (!rootInfo.project.getPath().isPrefixOf(path)) { // only consider roots that are not included in the container -// this.updateCurrentDeltaAndIndex(rootDelta, IJavaElement.PACKAGE_FRAGMENT_ROOT, rootInfo); -// } -// -// ArrayList rootList = (ArrayList)otherRoots.get(path); -// if (rootList != null) { -// Iterator otherProjects = rootList.iterator(); -// while (otherProjects.hasNext()) { -// rootInfo = (RootInfo)otherProjects.next(); -// if (!rootInfo.project.getPath().isPrefixOf(path)) { // only consider roots that are not included in the container -// this.updateCurrentDeltaAndIndex(rootDelta, IJavaElement.PACKAGE_FRAGMENT_ROOT, rootInfo); -// } -// } -// } -// } -// } -//} - + // public void updateDependentNamelookups() { + // Iterator iterator; + // // update namelookup of dependent projects + // iterator = this.projectsForDependentNamelookupRefresh.iterator(); + // HashSet affectedDependents = new HashSet(); + // while (iterator.hasNext()) { + // JavaProject project = (JavaProject)iterator.next(); + // addDependentProjects(project.getPath(), affectedDependents); + // } + // iterator = affectedDependents.iterator(); + // while (iterator.hasNext()) { + // JavaProject project = (JavaProject) iterator.next(); + // if (project.isOpen()){ + // try { + // ((JavaProjectElementInfo)project.getElementInfo()).setNameLookup(null); + // } catch (JavaModelException e) { + // } + // } + // } + // } + // protected void updateIndex(Openable element, IResourceDelta delta) { + // + // if (indexManager == null) + // return; + // + // switch (element.getElementType()) { + // case IJavaElement.JAVA_PROJECT : + // switch (delta.getKind()) { + // case IResourceDelta.ADDED : + // this.indexManager.indexAll(element.getJavaProject().getProject()); + // break; + // case IResourceDelta.REMOVED : + // this.indexManager.removeIndexFamily(element.getJavaProject().getProject().getFullPath()); + // // NB: Discarding index jobs belonging to this project was done during + // PRE_DELETE + // break; + // // NB: Update of index if project is opened, closed, or its java nature + // is added or removed + // // is done in updateCurrentDeltaAndIndex + // } + // break; + // case IJavaElement.PACKAGE_FRAGMENT_ROOT : + // if (element instanceof JarPackageFragmentRoot) { + // JarPackageFragmentRoot root = (JarPackageFragmentRoot)element; + // // index jar file only once (if the root is in its declaring project) + // IPath jarPath = root.getPath(); + // switch (delta.getKind()) { + // case IResourceDelta.ADDED: + // // index the new jar + // indexManager.indexLibrary(jarPath, root.getJavaProject().getProject()); + // break; + // case IResourceDelta.CHANGED: + // // first remove the index so that it is forced to be re-indexed + // indexManager.removeIndex(jarPath); + // // then index the jar + // indexManager.indexLibrary(jarPath, root.getJavaProject().getProject()); + // break; + // case IResourceDelta.REMOVED: + // // the jar was physically removed: remove the index + // this.indexManager.discardJobs(jarPath.toString()); + // this.indexManager.removeIndex(jarPath); + // break; + // } + // break; + // } else { + // int kind = delta.getKind(); + // if (kind == IResourceDelta.ADDED || kind == IResourceDelta.REMOVED) { + // IPackageFragmentRoot root = (IPackageFragmentRoot)element; + // this.updateRootIndex(root, root.getPackageFragment(""), delta); + // //$NON-NLS-1$ + // break; + // } + // } + // // don't break as packages of the package fragment root can be indexed + // below + // case IJavaElement.PACKAGE_FRAGMENT : + // switch (delta.getKind()) { + // case IResourceDelta.ADDED: + // case IResourceDelta.REMOVED: + // IPackageFragment pkg = null; + // if (element instanceof IPackageFragmentRoot) { + // IPackageFragmentRoot root = (IPackageFragmentRoot)element; + // pkg = root.getPackageFragment(""); //$NON-NLS-1$ + // } else { + // pkg = (IPackageFragment)element; + // } + // IResourceDelta[] children = delta.getAffectedChildren(); + // for (int i = 0, length = children.length; i < length; i++) { + // IResourceDelta child = children[i]; + // IResource resource = child.getResource(); + // if (resource instanceof IFile) { + // String name = resource.getName(); + // if (ProjectPrefUtil.isJavaFileName(name)) { + // Openable cu = (Openable)pkg.getCompilationUnit(name); + // this.updateIndex(cu, child); + // } else if (ProjectPrefUtil.isClassFileName(name)) { + // Openable classFile = (Openable)pkg.getClassFile(name); + // this.updateIndex(classFile, child); + // } + // } + // } + // break; + // } + // break; + // case IJavaElement.CLASS_FILE : + // IFile file = (IFile) delta.getResource(); + // IJavaProject project = element.getJavaProject(); + // IPath binaryFolderPath = element.getPackageFragmentRoot().getPath(); + // // if the class file is part of the binary output, it has been created by + // // the java builder -> ignore + // try { + // if (binaryFolderPath.equals(project.getOutputLocation())) { + // break; + // } + // } catch (JavaModelException e) { + // } + // switch (delta.getKind()) { + // case IResourceDelta.CHANGED : + // // no need to index if the content has not changed + // if ((delta.getFlags() & IResourceDelta.CONTENT) == 0) + // break; + // case IResourceDelta.ADDED : + // indexManager.addBinary(file, binaryFolderPath); + // break; + // case IResourceDelta.REMOVED : + // indexManager.remove(file.getFullPath().toString(), binaryFolderPath); + // break; + // } + // break; + // case IJavaElement.COMPILATION_UNIT : + // file = (IFile) delta.getResource(); + // switch (delta.getKind()) { + // case IResourceDelta.CHANGED : + // // no need to index if the content has not changed + // if ((delta.getFlags() & IResourceDelta.CONTENT) == 0) + // break; + // case IResourceDelta.ADDED : + // indexManager.addSource(file, + // file.getProject().getProject().getFullPath()); + // break; + // case IResourceDelta.REMOVED : + // indexManager.remove(file.getFullPath().toString(), + // file.getProject().getProject().getFullPath()); + // break; + // } + // } + // } + /** + * Upadtes the index of the given root (assuming it's an addition or a + * removal). This is done recusively, pkg being the current package. + */ + // private void updateRootIndex(IPackageFragmentRoot root, IPackageFragment + // pkg, IResourceDelta delta) { + // this.updateIndex((Openable)pkg, delta); + // IResourceDelta[] children = delta.getAffectedChildren(); + // String name = pkg.getElementName(); + // for (int i = 0, length = children.length; i < length; i++) { + // IResourceDelta child = children[i]; + // IResource resource = child.getResource(); + // if (resource instanceof IFolder) { + // String subpkgName = + // name.length() == 0 ? + // resource.getName() : + // name + "." + resource.getName(); //$NON-NLS-1$ + // IPackageFragment subpkg = root.getPackageFragment(subpkgName); + // this.updateRootIndex(root, subpkg, child); + // } + // } + // } + /* + * Update the roots that are affected by the addition or the removal of the + * given container resource. + */ + // private void updateRoots(IPath containerPath, IResourceDelta + // containerDelta) { + // Map roots; + // Map otherRoots; + // if (containerDelta.getKind() == IResourceDelta.REMOVED) { + // roots = this.oldRoots; + // otherRoots = this.oldOtherRoots; + // } else { + // roots = this.roots; + // otherRoots = this.otherRoots; + // } + // Iterator iterator = roots.keySet().iterator(); + // while (iterator.hasNext()) { + // IPath path = (IPath)iterator.next(); + // if (containerPath.isPrefixOf(path) && !containerPath.equals(path)) { + // IResourceDelta rootDelta = + // containerDelta.findMember(path.removeFirstSegments(1)); + // if (rootDelta == null) continue; + // RootInfo rootInfo = (RootInfo)roots.get(path); + // + // if (!rootInfo.project.getPath().isPrefixOf(path)) { // only consider + // roots that are not included in the container + // this.updateCurrentDeltaAndIndex(rootDelta, + // IJavaElement.PACKAGE_FRAGMENT_ROOT, rootInfo); + // } + // + // ArrayList rootList = (ArrayList)otherRoots.get(path); + // if (rootList != null) { + // Iterator otherProjects = rootList.iterator(); + // while (otherProjects.hasNext()) { + // rootInfo = (RootInfo)otherProjects.next(); + // if (!rootInfo.project.getPath().isPrefixOf(path)) { // only consider + // roots that are not included in the container + // this.updateCurrentDeltaAndIndex(rootDelta, + // IJavaElement.PACKAGE_FRAGMENT_ROOT, rootInfo); + // } + // } + // } + // } + // } + // } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DiscardWorkingCopyOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DiscardWorkingCopyOperation.java index 78f0f8a..75b92d3 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DiscardWorkingCopyOperation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DiscardWorkingCopyOperation.java @@ -15,46 +15,56 @@ import net.sourceforge.phpdt.core.IJavaElementDelta; import net.sourceforge.phpdt.core.JavaModelException; /** - * Discards a working copy (decrement its use count and remove its working copy info if the use count is 0) - * and signal its removal through a delta. + * Discards a working copy (decrement its use count and remove its working copy + * info if the use count is 0) and signal its removal through a delta. */ public class DiscardWorkingCopyOperation extends JavaModelOperation { - + public DiscardWorkingCopyOperation(IJavaElement workingCopy) { - super(new IJavaElement[] {workingCopy}); + super(new IJavaElement[] { workingCopy }); } + protected void executeOperation() throws JavaModelException { CompilationUnit workingCopy = getWorkingCopy(); - - int useCount = JavaModelManager.getJavaModelManager().discardPerWorkingCopyInfo(workingCopy); + + int useCount = JavaModelManager.getJavaModelManager() + .discardPerWorkingCopyInfo(workingCopy); if (useCount == 0) { if (!workingCopy.isPrimary()) { // report removed java delta for a non-primary working copy - JavaElementDelta delta = new JavaElementDelta(this.getJavaModel()); + JavaElementDelta delta = new JavaElementDelta(this + .getJavaModel()); delta.removed(workingCopy); addDelta(delta); removeReconcileDelta(workingCopy); } else { if (workingCopy.getResource().isAccessible()) { - // report a F_PRIMARY_WORKING_COPY change delta for a primary working copy - JavaElementDelta delta = new JavaElementDelta(this.getJavaModel()); - delta.changed(workingCopy, IJavaElementDelta.F_PRIMARY_WORKING_COPY); + // report a F_PRIMARY_WORKING_COPY change delta for a + // primary working copy + JavaElementDelta delta = new JavaElementDelta(this + .getJavaModel()); + delta.changed(workingCopy, + IJavaElementDelta.F_PRIMARY_WORKING_COPY); addDelta(delta); } else { // report a REMOVED delta - JavaElementDelta delta = new JavaElementDelta(this.getJavaModel()); - delta.removed(workingCopy, IJavaElementDelta.F_PRIMARY_WORKING_COPY); + JavaElementDelta delta = new JavaElementDelta(this + .getJavaModel()); + delta.removed(workingCopy, + IJavaElementDelta.F_PRIMARY_WORKING_COPY); addDelta(delta); } } } } + /** * Returns the working copy this operation is working on. */ protected CompilationUnit getWorkingCopy() { - return (CompilationUnit)getElementToProcess(); + return (CompilationUnit) getElementToProcess(); } + /** * @see JavaModelOperation#isReadOnly */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ElementCache.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ElementCache.java index 2f990d7..c004404 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ElementCache.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ElementCache.java @@ -18,45 +18,51 @@ import net.sourceforge.phpdt.internal.core.util.LRUCache; * An LRU cache of JavaElements. */ public class ElementCache extends OverflowingLRUCache { -/** - * Constructs a new element cache of the given size. - */ -public ElementCache(int size) { - super(size); -} -/** - * Constructs a new element cache of the given size. - */ -public ElementCache(int size, int overflow) { - super(size, overflow); -} -/** - * Returns true if the element is successfully closed and - * removed from the cache, otherwise false. - * - *

                                      NOTE: this triggers an external removal of this element - * by closing the element. - */ -protected boolean close(LRUCacheEntry entry) { - IOpenable element = (IOpenable) entry._fKey; - try { - if (element.hasUnsavedChanges()) { - return false; - } else { - // We must close an entire JarPackageFragmentRoot at once. -// if (element instanceof JarPackageFragment) { -// JarPackageFragment packageFragment= (JarPackageFragment) element; -// JarPackageFragmentRoot root = (JarPackageFragmentRoot) packageFragment.getParent(); -// root.close(); -// } else { + /** + * Constructs a new element cache of the given size. + */ + public ElementCache(int size) { + super(size); + } + + /** + * Constructs a new element cache of the given size. + */ + public ElementCache(int size, int overflow) { + super(size, overflow); + } + + /** + * Returns true if the element is successfully closed and removed from the + * cache, otherwise false. + * + *

                                      + * NOTE: this triggers an external removal of this element by closing the + * element. + */ + protected boolean close(LRUCacheEntry entry) { + IOpenable element = (IOpenable) entry._fKey; + try { + if (element.hasUnsavedChanges()) { + return false; + } else { + // We must close an entire JarPackageFragmentRoot at once. + // if (element instanceof JarPackageFragment) { + // JarPackageFragment packageFragment= (JarPackageFragment) + // element; + // JarPackageFragmentRoot root = (JarPackageFragmentRoot) + // packageFragment.getParent(); + // root.close(); + // } else { element.close(); -// } - return true; + // } + return true; + } + } catch (JavaModelException npe) { + return false; } - } catch (JavaModelException npe) { - return false; } -} + /** * Returns a new instance of the reciever. */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/IJavaElementRequestor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/IJavaElementRequestor.java index 79f5725..0cef475 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/IJavaElementRequestor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/IJavaElementRequestor.java @@ -16,22 +16,26 @@ import net.sourceforge.phpdt.core.IPackageFragment; import net.sourceforge.phpdt.core.IType; /** - * This interface is used by IRequestorNameLookup. As results - * are found by IRequestorNameLookup, they are reported to this - * interface. An IJavaElementRequestor is able to cancel - * at any time (that is, stop receiving results), by responding - * true to #isCancelled. + * This interface is used by IRequestorNameLookup. As results are found by + * IRequestorNameLookup, they are reported to this interface. An + * IJavaElementRequestor is able to cancel at any time (that is, stop receiving + * results), by responding true to #isCancelled. */ public interface IJavaElementRequestor { -public void acceptField(IField field); -//public void acceptInitializer(IInitializer initializer); -public void acceptMemberType(IType type); -public void acceptMethod(IMethod method); -public void acceptPackageFragment(IPackageFragment packageFragment); -public void acceptType(IType type); -/** - * Returns true if this IJavaElementRequestor does - * not want to receive any more results. - */ -boolean isCanceled(); + public void acceptField(IField field); + + // public void acceptInitializer(IInitializer initializer); + public void acceptMemberType(IType type); + + public void acceptMethod(IMethod method); + + public void acceptPackageFragment(IPackageFragment packageFragment); + + public void acceptType(IType type); + + /** + * Returns true if this IJavaElementRequestor does not want + * to receive any more results. + */ + boolean isCanceled(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/INamingRequestor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/INamingRequestor.java index 4efbb83..d394e06 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/INamingRequestor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/INamingRequestor.java @@ -11,8 +11,12 @@ package net.sourceforge.phpdt.internal.core; public interface INamingRequestor { - void acceptNameWithPrefixAndSuffix(char[] name, boolean isFirstPrefix, boolean isFirstSuffix); + void acceptNameWithPrefixAndSuffix(char[] name, boolean isFirstPrefix, + boolean isFirstSuffix); + void acceptNameWithPrefix(char[] name, boolean isFirstPrefix); + void acceptNameWithSuffix(char[] name, boolean isFirstSuffix); + void acceptNameWithoutPrefixAndSuffix(char[] name); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ImportContainer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ImportContainer.java index e8da010..775c053 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ImportContainer.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ImportContainer.java @@ -20,123 +20,129 @@ import net.sourceforge.phpdt.core.JavaModelException; import net.sourceforge.phpdt.core.WorkingCopyOwner; import net.sourceforge.phpdt.internal.core.util.MementoTokenizer; -//import net.sourceforge.phpdt.internal.core.util.MementoTokenizer; +// import net.sourceforge.phpdt.internal.core.util.MementoTokenizer; /** * @see IImportContainer */ -public class ImportContainer extends SourceRefElement implements IImportContainer { - protected ImportContainer(CompilationUnit parent) { - super(parent, ""); //$NON-NLS-1$ - } +public class ImportContainer extends SourceRefElement implements + IImportContainer { + protected ImportContainer(CompilationUnit parent) { + super(parent, ""); //$NON-NLS-1$ + } - public boolean equals(Object o) { - if (!(o instanceof ImportContainer)) - return false; - return super.equals(o); - } + public boolean equals(Object o) { + if (!(o instanceof ImportContainer)) + return false; + return super.equals(o); + } - /** - * @see IJavaElement - */ - public int getElementType() { - return IMPORT_CONTAINER; - } + /** + * @see IJavaElement + */ + public int getElementType() { + return IMPORT_CONTAINER; + } - /* - * @see JavaElement - */ - public IJavaElement getHandleFromMemento(String token, MementoTokenizer memento, WorkingCopyOwner workingCopyOwner) { - switch (token.charAt(0)) { - case JEM_COUNT: - return getHandleUpdatingCountFromMemento(memento, workingCopyOwner); - case JEM_IMPORTDECLARATION: - if (memento.hasMoreTokens()) { - String importName = memento.nextToken(); - JavaElement importDecl = (JavaElement) getImport(importName); - return importDecl.getHandleFromMemento(memento, workingCopyOwner); - } else { - return this; - } - } - return null; - } + /* + * @see JavaElement + */ + public IJavaElement getHandleFromMemento(String token, + MementoTokenizer memento, WorkingCopyOwner workingCopyOwner) { + switch (token.charAt(0)) { + case JEM_COUNT: + return getHandleUpdatingCountFromMemento(memento, workingCopyOwner); + case JEM_IMPORTDECLARATION: + if (memento.hasMoreTokens()) { + String importName = memento.nextToken(); + JavaElement importDecl = (JavaElement) getImport(importName); + return importDecl.getHandleFromMemento(memento, + workingCopyOwner); + } else { + return this; + } + } + return null; + } - /** - * @see JavaElement#getHandleMemento() - */ - protected char getHandleMementoDelimiter() { - return JavaElement.JEM_IMPORTDECLARATION; - } + /** + * @see JavaElement#getHandleMemento() + */ + protected char getHandleMementoDelimiter() { + return JavaElement.JEM_IMPORTDECLARATION; + } - /** - * @see IImportContainer - */ - public IImportDeclaration getImport(String importName) { - return new ImportDeclaration(this, importName); - } + /** + * @see IImportContainer + */ + public IImportDeclaration getImport(String importName) { + return new ImportDeclaration(this, importName); + } - /* - * @see JavaElement#getPrimaryElement(boolean) - */ - public IJavaElement getPrimaryElement(boolean checkOwner) { - CompilationUnit cu = (CompilationUnit) this.parent; - if (checkOwner && cu.isPrimary()) - return this; - return cu.getImportContainer(); - } + /* + * @see JavaElement#getPrimaryElement(boolean) + */ + public IJavaElement getPrimaryElement(boolean checkOwner) { + CompilationUnit cu = (CompilationUnit) this.parent; + if (checkOwner && cu.isPrimary()) + return this; + return cu.getImportContainer(); + } - /** - * @see ISourceReference - */ - public ISourceRange getSourceRange() throws JavaModelException { - IJavaElement[] imports = getChildren(); - ISourceRange firstRange = ((ISourceReference) imports[0]).getSourceRange(); - ISourceRange lastRange = ((ISourceReference) imports[imports.length - 1]).getSourceRange(); - SourceRange range = new SourceRange(firstRange.getOffset(), lastRange.getOffset() + lastRange.getLength() - - firstRange.getOffset()); - return range; - } + /** + * @see ISourceReference + */ + public ISourceRange getSourceRange() throws JavaModelException { + IJavaElement[] imports = getChildren(); + ISourceRange firstRange = ((ISourceReference) imports[0]) + .getSourceRange(); + ISourceRange lastRange = ((ISourceReference) imports[imports.length - 1]) + .getSourceRange(); + SourceRange range = new SourceRange(firstRange.getOffset(), lastRange + .getOffset() + + lastRange.getLength() - firstRange.getOffset()); + return range; + } - /** - * Import containers only exist if they have children. - * - * @see IParent - */ - public boolean hasChildren() { - return true; - } + /** + * Import containers only exist if they have children. + * + * @see IParent + */ + public boolean hasChildren() { + return true; + } - /** - */ - public String readableName() { + /** + */ + public String readableName() { - return null; - } + return null; + } - /** - * @private Debugging purposes - */ - protected void toString(int tab, StringBuffer buffer) { - Object info = JavaModelManager.getJavaModelManager().peekAtInfo(this); - if (info == null || !(info instanceof JavaElementInfo)) - return; - IJavaElement[] children = ((JavaElementInfo) info).getChildren(); - for (int i = 0; i < children.length; i++) { - if (i > 0) - buffer.append("\n"); //$NON-NLS-1$ - ((JavaElement) children[i]).toString(tab, buffer); - } - } + /** + * @private Debugging purposes + */ + protected void toString(int tab, StringBuffer buffer) { + Object info = JavaModelManager.getJavaModelManager().peekAtInfo(this); + if (info == null || !(info instanceof JavaElementInfo)) + return; + IJavaElement[] children = ((JavaElementInfo) info).getChildren(); + for (int i = 0; i < children.length; i++) { + if (i > 0) + buffer.append("\n"); //$NON-NLS-1$ + ((JavaElement) children[i]).toString(tab, buffer); + } + } - /** - * Debugging purposes - */ - protected void toStringInfo(int tab, StringBuffer buffer, Object info) { - buffer.append(this.tabString(tab)); - buffer.append(""); //$NON-NLS-1$ - if (info == null) { - buffer.append(" (not open)"); //$NON-NLS-1$ - } - } + /** + * Debugging purposes + */ + protected void toStringInfo(int tab, StringBuffer buffer, Object info) { + buffer.append(this.tabString(tab)); + buffer.append(""); //$NON-NLS-1$ + if (info == null) { + buffer.append(" (not open)"); //$NON-NLS-1$ + } + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ImportDeclaration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ImportDeclaration.java index 0ae4f78..73a103f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ImportDeclaration.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ImportDeclaration.java @@ -16,96 +16,112 @@ import net.sourceforge.phpdt.core.JavaModelException; import net.sourceforge.phpdt.core.jdom.IDOMNode; /** - * Handle for an import declaration. Info object is a ImportDeclarationElementInfo. + * Handle for an import declaration. Info object is a + * ImportDeclarationElementInfo. + * * @see IImportDeclaration */ -/* package */ class ImportDeclaration extends SourceRefElement implements IImportDeclaration { +/* package */class ImportDeclaration extends SourceRefElement implements + IImportDeclaration { + /** + * Constructs an ImportDeclaration in the given import container with the + * given name. + */ + protected ImportDeclaration(ImportContainer parent, String name) { + super(parent, name); + } -/** - * Constructs an ImportDeclaration in the given import container - * with the given name. - */ -protected ImportDeclaration(ImportContainer parent, String name) { - super(parent, name); -} -public boolean equals(Object o) { - if (!(o instanceof ImportDeclaration)) return false; - return super.equals(o); -} -/** - * @see JavaElement#equalsDOMNode - * @deprecated JDOM is obsolete - */ -// TODO - JDOM - remove once model ported off of JDOM -protected boolean equalsDOMNode(IDOMNode node) { - return (node.getNodeType() == IDOMNode.IMPORT) && getElementName().equals(node.getName()); -} -/** - * @see IJavaElement - */ -public int getElementType() { - return IMPORT_DECLARATION; -} -/** - * @see net.sourceforge.phpdt.core.IImportDeclaration#getFlags() - */ -public int getFlags() throws JavaModelException { - ImportDeclarationElementInfo info = (ImportDeclarationElementInfo)getElementInfo(); - return info.getModifiers(); -} -/** - * @see JavaElement#getHandleMemento() - * For import declarations, the handle delimiter is associated to the import container already - */ -public String getHandleMemento(){ - StringBuffer buff= new StringBuffer(((JavaElement)getParent()).getHandleMemento()); - escapeMementoName(buff, getElementName()); - if (this.occurrenceCount > 1) { - buff.append(JEM_COUNT); - buff.append(this.occurrenceCount); + public boolean equals(Object o) { + if (!(o instanceof ImportDeclaration)) + return false; + return super.equals(o); } - return buff.toString(); -} -/** - * @see JavaElement#getHandleMemento() - */ -protected char getHandleMementoDelimiter() { - // For import declarations, the handle delimiter is associated to the import container already - Assert.isTrue(false, "Should not be called"); //$NON-NLS-1$ - return 0; -} -/* - * @see JavaElement#getPrimaryElement(boolean) - */ -public IJavaElement getPrimaryElement(boolean checkOwner) { - CompilationUnit cu = (CompilationUnit)this.parent.getParent(); - if (checkOwner && cu.isPrimary()) return this; - return cu.getImport(this.name); -} -/** - * Returns true if the import is on-demand (ends with ".*") - */ -public boolean isOnDemand() { - return this.name.endsWith(".*"); //$NON-NLS-1$ -} -/** - */ -public String readableName() { + /** + * @see JavaElement#equalsDOMNode + * @deprecated JDOM is obsolete + */ + // TODO - JDOM - remove once model ported off of JDOM + protected boolean equalsDOMNode(IDOMNode node) { + return (node.getNodeType() == IDOMNode.IMPORT) + && getElementName().equals(node.getName()); + } - return null; -} -/** - * @private Debugging purposes - */ -protected void toStringInfo(int tab, StringBuffer buffer, Object info) { - buffer.append(this.tabString(tab)); - buffer.append("include "); //$NON-NLS-1$ - toStringName(buffer); - if (info == null) { - buffer.append(" (not open)"); //$NON-NLS-1$ + /** + * @see IJavaElement + */ + public int getElementType() { + return IMPORT_DECLARATION; + } + + /** + * @see net.sourceforge.phpdt.core.IImportDeclaration#getFlags() + */ + public int getFlags() throws JavaModelException { + ImportDeclarationElementInfo info = (ImportDeclarationElementInfo) getElementInfo(); + return info.getModifiers(); + } + + /** + * @see JavaElement#getHandleMemento() For import declarations, the handle + * delimiter is associated to the import container already + */ + public String getHandleMemento() { + StringBuffer buff = new StringBuffer(((JavaElement) getParent()) + .getHandleMemento()); + escapeMementoName(buff, getElementName()); + if (this.occurrenceCount > 1) { + buff.append(JEM_COUNT); + buff.append(this.occurrenceCount); + } + return buff.toString(); + } + + /** + * @see JavaElement#getHandleMemento() + */ + protected char getHandleMementoDelimiter() { + // For import declarations, the handle delimiter is associated to the + // import container already + Assert.isTrue(false, "Should not be called"); //$NON-NLS-1$ + return 0; + } + + /* + * @see JavaElement#getPrimaryElement(boolean) + */ + public IJavaElement getPrimaryElement(boolean checkOwner) { + CompilationUnit cu = (CompilationUnit) this.parent.getParent(); + if (checkOwner && cu.isPrimary()) + return this; + return cu.getImport(this.name); + } + + /** + * Returns true if the import is on-demand (ends with ".*") + */ + public boolean isOnDemand() { + return this.name.endsWith(".*"); //$NON-NLS-1$ + } + + /** + */ + public String readableName() { + + return null; + } + + /** + * @private Debugging purposes + */ + protected void toStringInfo(int tab, StringBuffer buffer, Object info) { + buffer.append(this.tabString(tab)); + buffer.append("include "); //$NON-NLS-1$ + toStringName(buffer); + if (info == null) { + buffer.append(" (not open)"); //$NON-NLS-1$ + } } -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ImportDeclarationElementInfo.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ImportDeclarationElementInfo.java index 2f99fc0..751314e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ImportDeclarationElementInfo.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ImportDeclarationElementInfo.java @@ -14,14 +14,19 @@ import net.sourceforge.phpdt.internal.compiler.env.ISourceImport; /** * Element info for IImportDeclaration elements. + * * @see net.sourceforge.phpdt.core.IImportDeclaration */ -public class ImportDeclarationElementInfo extends MemberElementInfo implements ISourceImport{ - - // record if import is on demand, the import name doesn't have trailing start +public class ImportDeclarationElementInfo extends MemberElementInfo implements + ISourceImport { + + // record if import is on demand, the import name doesn't have trailing + // start boolean onDemand; - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see net.sourceforge.phpdt.internal.compiler.env.ISourceImport#onDemand() */ public boolean onDemand() { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/InternalNamingConventions.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/InternalNamingConventions.java index 55ede66..3e4ffde 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/InternalNamingConventions.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/InternalNamingConventions.java @@ -22,246 +22,233 @@ import net.sourceforge.phpdt.internal.compiler.parser.Scanner; public class InternalNamingConventions { private static final char[] DEFAULT_NAME = "name".toCharArray(); //$NON-NLS-1$ - + private static Scanner getNameScanner(CompilerOptions compilerOptions) { - return - new Scanner( - false /*comment*/, - false /*whitespace*/, - false /*nls*/, -// compilerOptions.sourceLevel /*sourceLevel*/, - false, - false, - null /*taskTags*/, - null/*taskPriorities*/, false); - + return new Scanner(false /* comment */, false /* whitespace */, + false /* nls */, + // compilerOptions.sourceLevel /*sourceLevel*/, + false, false, null /* taskTags */, null/* taskPriorities */, + false); + } - public static void suggestArgumentNames(IJavaProject javaProject, char[] packageName, char[] qualifiedTypeName, int dim, char[][] excludedNames, INamingRequestor requestor) { + + public static void suggestArgumentNames(IJavaProject javaProject, + char[] packageName, char[] qualifiedTypeName, int dim, + char[][] excludedNames, INamingRequestor requestor) { Map options = javaProject.getOptions(true); CompilerOptions compilerOptions = new CompilerOptions(options); AssistOptions assistOptions = new AssistOptions(options); - suggestNames( - packageName, - qualifiedTypeName, - dim, - assistOptions.argumentPrefixes, - assistOptions.argumentSuffixes, - excludedNames, - getNameScanner(compilerOptions), - requestor); + suggestNames(packageName, qualifiedTypeName, dim, + assistOptions.argumentPrefixes, assistOptions.argumentSuffixes, + excludedNames, getNameScanner(compilerOptions), requestor); } - public static void suggestFieldNames(IJavaProject javaProject, char[] packageName, char[] qualifiedTypeName, int dim, int modifiers, char[][] excludedNames, INamingRequestor requestor) { + + public static void suggestFieldNames(IJavaProject javaProject, + char[] packageName, char[] qualifiedTypeName, int dim, + int modifiers, char[][] excludedNames, INamingRequestor requestor) { boolean isStatic = Flags.isStatic(modifiers); - + Map options = javaProject.getOptions(true); CompilerOptions compilerOptions = new CompilerOptions(options); AssistOptions assistOptions = new AssistOptions(options); - suggestNames( - packageName, - qualifiedTypeName, - dim, - isStatic ? assistOptions.staticFieldPrefixes : assistOptions.fieldPrefixes, - isStatic ? assistOptions.staticFieldSuffixes : assistOptions.fieldSuffixes, - excludedNames, - getNameScanner(compilerOptions), - requestor); + suggestNames(packageName, qualifiedTypeName, dim, + isStatic ? assistOptions.staticFieldPrefixes + : assistOptions.fieldPrefixes, + isStatic ? assistOptions.staticFieldSuffixes + : assistOptions.fieldSuffixes, excludedNames, + getNameScanner(compilerOptions), requestor); } - public static void suggestLocalVariableNames(IJavaProject javaProject, char[] packageName, char[] qualifiedTypeName, int dim, char[][] excludedNames, INamingRequestor requestor) { + + public static void suggestLocalVariableNames(IJavaProject javaProject, + char[] packageName, char[] qualifiedTypeName, int dim, + char[][] excludedNames, INamingRequestor requestor) { Map options = javaProject.getOptions(true); CompilerOptions compilerOptions = new CompilerOptions(options); AssistOptions assistOptions = new AssistOptions(options); - suggestNames( - packageName, - qualifiedTypeName, - dim, - assistOptions.localPrefixes, - assistOptions.localSuffixes, - excludedNames, - getNameScanner(compilerOptions), - requestor); + suggestNames(packageName, qualifiedTypeName, dim, + assistOptions.localPrefixes, assistOptions.localSuffixes, + excludedNames, getNameScanner(compilerOptions), requestor); } - - private static void suggestNames( - char[] packageName, - char[] qualifiedTypeName, - int dim, - char[][] prefixes, - char[][] suffixes, - char[][] excludedNames, - Scanner nameScanner, - INamingRequestor requestor){ - - if(qualifiedTypeName == null || qualifiedTypeName.length == 0) + + private static void suggestNames(char[] packageName, + char[] qualifiedTypeName, int dim, char[][] prefixes, + char[][] suffixes, char[][] excludedNames, Scanner nameScanner, + INamingRequestor requestor) { + + if (qualifiedTypeName == null || qualifiedTypeName.length == 0) return; - + char[] typeName = CharOperation.lastSegment(qualifiedTypeName, '.'); - - if(prefixes == null || prefixes.length == 0) { + + if (prefixes == null || prefixes.length == 0) { prefixes = new char[1][0]; } else { int length = prefixes.length; - System.arraycopy(prefixes, 0, prefixes = new char[length+1][], 0, length); + System.arraycopy(prefixes, 0, prefixes = new char[length + 1][], 0, + length); prefixes[length] = CharOperation.NO_CHAR; } - - if(suffixes == null || suffixes.length == 0) { + + if (suffixes == null || suffixes.length == 0) { suffixes = new char[1][0]; } else { int length = suffixes.length; - System.arraycopy(suffixes, 0, suffixes = new char[length+1][], 0, length); + System.arraycopy(suffixes, 0, suffixes = new char[length + 1][], 0, + length); suffixes[length] = CharOperation.NO_CHAR; } - + char[][] tempNames = null; - + // compute variable name for base type -// try{ -// nameScanner.setSource(typeName); -// switch (nameScanner.getNextToken()) { -// case TerminalTokens.TokenNameint : -// case TerminalTokens.TokenNamebyte : -// case TerminalTokens.TokenNameshort : -// case TerminalTokens.TokenNamechar : -// case TerminalTokens.TokenNamelong : -// case TerminalTokens.TokenNamefloat : -// case TerminalTokens.TokenNamedouble : -// case TerminalTokens.TokenNameboolean : -// char[] name = computeBaseTypeNames(typeName[0], excludedNames); -// if(name != null) { -// tempNames = new char[][]{name}; -// } -// break; -// } -// } catch(InvalidInputException e){ -// // ignore -// } + // try{ + // nameScanner.setSource(typeName); + // switch (nameScanner.getNextToken()) { + // case TerminalTokens.TokenNameint : + // case TerminalTokens.TokenNamebyte : + // case TerminalTokens.TokenNameshort : + // case TerminalTokens.TokenNamechar : + // case TerminalTokens.TokenNamelong : + // case TerminalTokens.TokenNamefloat : + // case TerminalTokens.TokenNamedouble : + // case TerminalTokens.TokenNameboolean : + // char[] name = computeBaseTypeNames(typeName[0], excludedNames); + // if(name != null) { + // tempNames = new char[][]{name}; + // } + // break; + // } + // } catch(InvalidInputException e){ + // // ignore + // } // compute variable name for non base type - if(tempNames == null) { + if (tempNames == null) { tempNames = computeNames(typeName); } - + boolean acceptDefaultName = true; - + for (int i = 0; i < tempNames.length; i++) { char[] tempName = tempNames[i]; - if(dim > 0) { + if (dim > 0) { int length = tempName.length; - if (tempName[length-1] == 's'){ - if(tempName.length > 1 && tempName[length-2] == 's') { - System.arraycopy(tempName, 0, tempName = new char[length + 2], 0, length); + if (tempName[length - 1] == 's') { + if (tempName.length > 1 && tempName[length - 2] == 's') { + System.arraycopy(tempName, 0, + tempName = new char[length + 2], 0, length); tempName[length] = 'e'; - tempName[length+1] = 's'; + tempName[length + 1] = 's'; } - } else if(tempName[length-1] == 'y') { - System.arraycopy(tempName, 0, tempName = new char[length + 2], 0, length); - tempName[length-1] = 'i'; + } else if (tempName[length - 1] == 'y') { + System.arraycopy(tempName, 0, + tempName = new char[length + 2], 0, length); + tempName[length - 1] = 'i'; tempName[length] = 'e'; - tempName[length+1] = 's'; + tempName[length + 1] = 's'; } else { - System.arraycopy(tempName, 0, tempName = new char[length + 1], 0, length); + System.arraycopy(tempName, 0, + tempName = new char[length + 1], 0, length); tempName[length] = 's'; } } - + for (int j = 0; j < prefixes.length; j++) { - if(prefixes[j].length > 0 - && Character.isLetterOrDigit(prefixes[j][prefixes[j].length - 1])) { + if (prefixes[j].length > 0 + && Character + .isLetterOrDigit(prefixes[j][prefixes[j].length - 1])) { tempName[0] = Character.toUpperCase(tempName[0]); } else { tempName[0] = Character.toLowerCase(tempName[0]); } char[] prefixName = CharOperation.concat(prefixes[j], tempName); for (int k = 0; k < suffixes.length; k++) { - char[] suffixName = CharOperation.concat(prefixName, suffixes[k]); - suffixName = - excludeNames( - suffixName, - prefixName, - suffixes[k], - excludedNames); - if(JavaConventions.validateFieldName(new String(suffixName)).isOK()) { - acceptName(suffixName, prefixes[j], suffixes[k], j == 0, k == 0, requestor); + char[] suffixName = CharOperation.concat(prefixName, + suffixes[k]); + suffixName = excludeNames(suffixName, prefixName, + suffixes[k], excludedNames); + if (JavaConventions.validateFieldName( + new String(suffixName)).isOK()) { + acceptName(suffixName, prefixes[j], suffixes[k], + j == 0, k == 0, requestor); acceptDefaultName = false; } else { - suffixName = CharOperation.concat( - prefixName, - String.valueOf(1).toCharArray(), - suffixes[k] - ); - suffixName = - excludeNames( - suffixName, - prefixName, - suffixes[k], - excludedNames); - if(JavaConventions.validateFieldName(new String(suffixName)).isOK()) { - acceptName(suffixName, prefixes[j], suffixes[k], j == 0, k == 0, requestor); + suffixName = CharOperation.concat(prefixName, String + .valueOf(1).toCharArray(), suffixes[k]); + suffixName = excludeNames(suffixName, prefixName, + suffixes[k], excludedNames); + if (JavaConventions.validateFieldName( + new String(suffixName)).isOK()) { + acceptName(suffixName, prefixes[j], suffixes[k], + j == 0, k == 0, requestor); acceptDefaultName = false; } } } - + } } // if no names were found - if(acceptDefaultName) { - char[] name = excludeNames(DEFAULT_NAME, DEFAULT_NAME, CharOperation.NO_CHAR, excludedNames); + if (acceptDefaultName) { + char[] name = excludeNames(DEFAULT_NAME, DEFAULT_NAME, + CharOperation.NO_CHAR, excludedNames); requestor.acceptNameWithoutPrefixAndSuffix(name); } } - - private static void acceptName( - char[] name, - char[] prefix, - char[] suffix, - boolean isFirstPrefix, - boolean isFirstSuffix, - INamingRequestor requestor) { - if(prefix.length > 0 && suffix.length > 0) { - requestor.acceptNameWithPrefixAndSuffix(name, isFirstPrefix, isFirstSuffix); - } else if(prefix.length > 0){ + + private static void acceptName(char[] name, char[] prefix, char[] suffix, + boolean isFirstPrefix, boolean isFirstSuffix, + INamingRequestor requestor) { + if (prefix.length > 0 && suffix.length > 0) { + requestor.acceptNameWithPrefixAndSuffix(name, isFirstPrefix, + isFirstSuffix); + } else if (prefix.length > 0) { requestor.acceptNameWithPrefix(name, isFirstPrefix); - } else if(suffix.length > 0){ + } else if (suffix.length > 0) { requestor.acceptNameWithSuffix(name, isFirstSuffix); } else { requestor.acceptNameWithoutPrefixAndSuffix(name); } } - - private static char[] computeBaseTypeNames(char firstName, char[][] excludedNames){ - char[] name = new char[]{firstName}; - - for(int i = 0 ; i < excludedNames.length ; i++){ - if(CharOperation.equals(name, excludedNames[i], false)) { + + private static char[] computeBaseTypeNames(char firstName, + char[][] excludedNames) { + char[] name = new char[] { firstName }; + + for (int i = 0; i < excludedNames.length; i++) { + if (CharOperation.equals(name, excludedNames[i], false)) { name[0]++; - if(name[0] > 'z') + if (name[0] > 'z') name[0] = 'a'; - if(name[0] == firstName) + if (name[0] == firstName) return null; i = 0; - } + } } - + return name; } - - private static char[][] computeNames(char[] sourceName){ + + private static char[][] computeNames(char[] sourceName) { char[][] names = new char[5][]; int nameCount = 0; boolean previousIsUpperCase = false; boolean previousIsLetter = true; - for(int i = sourceName.length - 1 ; i >= 0 ; i--){ + for (int i = sourceName.length - 1; i >= 0; i--) { boolean isUpperCase = Character.isUpperCase(sourceName[i]); boolean isLetter = Character.isLetter(sourceName[i]); - if(isUpperCase && !previousIsUpperCase && previousIsLetter){ - char[] name = CharOperation.subarray(sourceName,i,sourceName.length); - if(name.length > 1){ - if(nameCount == names.length) { - System.arraycopy(names, 0, names = new char[nameCount * 2][], 0, nameCount); + if (isUpperCase && !previousIsUpperCase && previousIsLetter) { + char[] name = CharOperation.subarray(sourceName, i, + sourceName.length); + if (name.length > 1) { + if (nameCount == names.length) { + System + .arraycopy(names, 0, + names = new char[nameCount * 2][], 0, + nameCount); } name[0] = Character.toLowerCase(name[0]); names[nameCount++] = name; @@ -270,27 +257,21 @@ public class InternalNamingConventions { previousIsUpperCase = isUpperCase; previousIsLetter = isLetter; } - if(nameCount == 0){ - names[nameCount++] = CharOperation.toLowerCase(sourceName); + if (nameCount == 0) { + names[nameCount++] = CharOperation.toLowerCase(sourceName); } System.arraycopy(names, 0, names = new char[nameCount][], 0, nameCount); return names; } - private static char[] excludeNames( - char[] suffixName, - char[] prefixName, - char[] suffix, - char[][] excludedNames) { + private static char[] excludeNames(char[] suffixName, char[] prefixName, + char[] suffix, char[][] excludedNames) { int count = 2; int m = 0; while (m < excludedNames.length) { - if(CharOperation.equals(suffixName, excludedNames[m], false)) { - suffixName = CharOperation.concat( - prefixName, - String.valueOf(count++).toCharArray(), - suffix - ); + if (CharOperation.equals(suffixName, excludedNames[m], false)) { + suffixName = CharOperation.concat(prefixName, String.valueOf( + count++).toCharArray(), suffix); m = 0; } else { m++; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElement.java index a14455c..3afb507 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElement.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElement.java @@ -45,25 +45,36 @@ import org.eclipse.core.runtime.jobs.ISchedulingRule; /** * Root of Java element handle hierarchy. - * + * * @see IJavaElement */ -public abstract class JavaElement extends PlatformObject - implements - IJavaElement { - public static final char JEM_ESCAPE = '\\'; +public abstract class JavaElement extends PlatformObject implements + IJavaElement { + public static final char JEM_ESCAPE = '\\'; + public static final char JEM_JAVAPROJECT = '='; + public static final char JEM_PACKAGEFRAGMENTROOT = Path.SEPARATOR; + public static final char JEM_PACKAGEFRAGMENT = '<'; + public static final char JEM_FIELD = '^'; + public static final char JEM_METHOD = '~'; + public static final char JEM_INITIALIZER = '|'; + public static final char JEM_COMPILATIONUNIT = '{'; -// public static final char JEM_CLASSFILE = '('; + + // public static final char JEM_CLASSFILE = '('; public static final char JEM_TYPE = '['; + public static final char JEM_PACKAGEDECLARATION = '%'; + public static final char JEM_IMPORTDECLARATION = '#'; + public static final char JEM_COUNT = '!'; + public static final char JEM_LOCALVARIABLE = '@'; /** @@ -79,10 +90,10 @@ public abstract class JavaElement extends PlatformObject * This element's type - one of the constants defined in * IJavaLanguageElementTypes. */ - //protected int fLEType = 0; + // protected int fLEType = 0; /** - * This element's parent, or null if this - * element does not have a parent. + * This element's parent, or null if this element does not + * have a parent. */ protected JavaElement parent; @@ -106,27 +117,31 @@ public abstract class JavaElement extends PlatformObject * @exception IllegalArgumentException * if the type is not one of the valid Java element type * constants - * + * */ protected JavaElement(JavaElement parent, String name) throws IllegalArgumentException { this.parent = parent; this.name = name; } + /** * @see IOpenable */ public void close() throws JavaModelException { JavaModelManager.getJavaModelManager().removeInfoAndChildren(this); } + /** * This element is being closed. Do any necessary cleanup. */ protected abstract void closing(Object info) throws JavaModelException; + /* * Returns a new element info for this element. */ protected abstract Object createElementInfo(); + /** * Returns true if this handle represents the same Java element as the given * handle. By default, two handles represent the same element if they are @@ -156,6 +171,7 @@ public abstract class JavaElement extends PlatformObject } return false; } + /** * Returns true if this JavaElement is equivalent to the * given IDOMNode. @@ -163,30 +179,31 @@ public abstract class JavaElement extends PlatformObject protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException { return false; } + protected void escapeMementoName(StringBuffer buffer, String mementoName) { for (int i = 0, length = mementoName.length(); i < length; i++) { char character = mementoName.charAt(i); switch (character) { - case JEM_ESCAPE: - case JEM_COUNT: - case JEM_JAVAPROJECT: - case JEM_PACKAGEFRAGMENTROOT: - case JEM_PACKAGEFRAGMENT: - case JEM_FIELD: - case JEM_METHOD: - case JEM_INITIALIZER: - case JEM_COMPILATIONUNIT: -// case JEM_CLASSFILE: - case JEM_TYPE: - case JEM_PACKAGEDECLARATION: - case JEM_IMPORTDECLARATION: - case JEM_LOCALVARIABLE: - buffer.append(JEM_ESCAPE); + case JEM_ESCAPE: + case JEM_COUNT: + case JEM_JAVAPROJECT: + case JEM_PACKAGEFRAGMENTROOT: + case JEM_PACKAGEFRAGMENT: + case JEM_FIELD: + case JEM_METHOD: + case JEM_INITIALIZER: + case JEM_COMPILATIONUNIT: + // case JEM_CLASSFILE: + case JEM_TYPE: + case JEM_PACKAGEDECLARATION: + case JEM_IMPORTDECLARATION: + case JEM_LOCALVARIABLE: + buffer.append(JEM_ESCAPE); } buffer.append(character); } } - + /** * @see IJavaElement */ @@ -240,6 +257,7 @@ public abstract class JavaElement extends PlatformObject return null; } } + /** */ protected IDOMNode followPath(ArrayList path, int position, IDOMNode node) { @@ -267,6 +285,7 @@ public abstract class JavaElement extends PlatformObject } } + /** * @see IJavaElement */ @@ -280,6 +299,7 @@ public abstract class JavaElement extends PlatformObject } return null; } + /** * Generates the element infos for this element, its ancestors (if they are * not opened) and its children (if it is an Openable). Puts the newly @@ -294,6 +314,7 @@ public abstract class JavaElement extends PlatformObject public IJavaElement[] getChildren() throws JavaModelException { return ((JavaElementInfo) getElementInfo()).getChildren(); } + /** * Returns a collection of (immediate) children of this node of the * specified type. @@ -313,18 +334,20 @@ public abstract class JavaElement extends PlatformObject } return list; } + /** * @see IMember */ - // public IClassFile getClassFile() { - // return null; - // } + // public IClassFile getClassFile() { + // return null; + // } /** * @see IMember */ public ICompilationUnit getCompilationUnit() { return null; } + /** * Returns the info for this handle. If this element is not already open, it * and all of its parents are opened. Does not return null. NOTE: BinaryType @@ -336,6 +359,7 @@ public abstract class JavaElement extends PlatformObject public Object getElementInfo() throws JavaModelException { return getElementInfo(null); } + /** * Returns the info for this handle. If this element is not already open, it * and all of its parents are opened. Does not return null. NOTE: BinaryType @@ -353,6 +377,7 @@ public abstract class JavaElement extends PlatformObject return info; return openWhenClosed(createElementInfo(), monitor); } + /** * @see IAdaptable */ @@ -361,41 +386,52 @@ public abstract class JavaElement extends PlatformObject } /* - * Creates a Java element handle from the given memento. - * The given token is the current delimiter indicating the type of the next token(s). - * The given working copy owner is used only for compilation unit handles. + * Creates a Java element handle from the given memento. The given token is + * the current delimiter indicating the type of the next token(s). The given + * working copy owner is used only for compilation unit handles. */ - public abstract IJavaElement getHandleFromMemento(String token, MementoTokenizer memento, WorkingCopyOwner owner); + public abstract IJavaElement getHandleFromMemento(String token, + MementoTokenizer memento, WorkingCopyOwner owner); + /* - * Creates a Java element handle from the given memento. - * The given working copy owner is used only for compilation unit handles. + * Creates a Java element handle from the given memento. The given working + * copy owner is used only for compilation unit handles. */ - public IJavaElement getHandleFromMemento(MementoTokenizer memento, WorkingCopyOwner owner) { - if (!memento.hasMoreTokens()) return this; + public IJavaElement getHandleFromMemento(MementoTokenizer memento, + WorkingCopyOwner owner) { + if (!memento.hasMoreTokens()) + return this; String token = memento.nextToken(); return getHandleFromMemento(token, memento, owner); } + /* - * Update the occurence count of the receiver and creates a Java element handle from the given memento. - * The given working copy owner is used only for compilation unit handles. + * Update the occurence count of the receiver and creates a Java element + * handle from the given memento. The given working copy owner is used only + * for compilation unit handles. */ - public IJavaElement getHandleUpdatingCountFromMemento(MementoTokenizer memento, WorkingCopyOwner owner) { + public IJavaElement getHandleUpdatingCountFromMemento( + MementoTokenizer memento, WorkingCopyOwner owner) { this.occurrenceCount = Integer.parseInt(memento.nextToken()); - if (!memento.hasMoreTokens()) return this; + if (!memento.hasMoreTokens()) + return this; String token = memento.nextToken(); return getHandleFromMemento(token, memento, owner); } + /** * @see IJavaElement */ public String getHandleIdentifier() { return getHandleMemento(); } + /** * @see JavaElement#getHandleMemento() */ - public String getHandleMemento(){ - StringBuffer buff= new StringBuffer(((JavaElement)getParent()).getHandleMemento()); + public String getHandleMemento() { + StringBuffer buff = new StringBuffer(((JavaElement) getParent()) + .getHandleMemento()); buff.append(getHandleMementoDelimiter()); escapeMementoName(buff, getElementName()); if (this.occurrenceCount > 1) { @@ -404,16 +440,18 @@ public abstract class JavaElement extends PlatformObject } return buff.toString(); } + /** * Returns the char that marks the start of this handles * contribution to a memento. */ - + /** * Returns the char that marks the start of this handles * contribution to a memento. */ protected abstract char getHandleMementoDelimiter(); + /** * @see IJavaElement */ @@ -437,18 +475,21 @@ public abstract class JavaElement extends PlatformObject } while ((current = current.getParent()) != null); return null; } + /** * Returns the occurrence count of the handle. */ protected int getOccurrenceCount() { return occurrenceCount; } + /* * @see IJavaElement */ public IOpenable getOpenable() { return this.getOpenableParent(); } + /** * Return the first instance of IOpenable in the parent hierarchy of this * element. @@ -460,7 +501,7 @@ public abstract class JavaElement extends PlatformObject return (IOpenable) parent; } - + /** * @see IJavaElement */ @@ -474,6 +515,7 @@ public abstract class JavaElement extends PlatformObject public IJavaElement getPrimaryElement() { return getPrimaryElement(true); } + /* * Returns the primary element. If checkOwner, and the cu owner is primary, * return this element. @@ -481,6 +523,7 @@ public abstract class JavaElement extends PlatformObject public IJavaElement getPrimaryElement(boolean checkOwner) { return this; } + /** * Returns the element that is located at the given source position in this * element. This is a helper method for @@ -496,13 +539,14 @@ public abstract class JavaElement extends PlatformObject int i; for (i = 0; i < children.length; i++) { IJavaElement aChild = children[i]; - + if (aChild instanceof SourceRefElement) { SourceRefElement child = (SourceRefElement) children[i]; ISourceRange range = child.getSourceRange(); -// if (child.name.equals("stopObject")||range==null || range.getOffset()<=0) { -// System.out.println(child.name); -// } + // if (child.name.equals("stopObject")||range==null || + // range.getOffset()<=0) { + // System.out.println(child.name); + // } if (position < range.getOffset() + range.getLength() && position >= range.getOffset()) { if (child instanceof IParent) { @@ -519,13 +563,14 @@ public abstract class JavaElement extends PlatformObject } return this; } + /** * Returns the SourceMapper facility for this element, or null * if this element does not have a SourceMapper. */ - // public SourceMapper getSourceMapper() { - // return ((JavaElement)getParent()).getSourceMapper(); - // } + // public SourceMapper getSourceMapper() { + // return ((JavaElement)getParent()).getSourceMapper(); + // } /* * (non-Javadoc) * @@ -536,9 +581,11 @@ public abstract class JavaElement extends PlatformObject if (resource == null) { class NoResourceSchedulingRule implements ISchedulingRule { public IPath path; + public NoResourceSchedulingRule(IPath path) { this.path = path; } + public boolean contains(ISchedulingRule rule) { if (rule instanceof NoResourceSchedulingRule) { return this.path @@ -547,6 +594,7 @@ public abstract class JavaElement extends PlatformObject return false; } } + public boolean isConflicting(ISchedulingRule rule) { if (rule instanceof NoResourceSchedulingRule) { IPath otherPath = ((NoResourceSchedulingRule) rule).path; @@ -562,6 +610,7 @@ public abstract class JavaElement extends PlatformObject return resource; } } + /** * @see IParent */ @@ -589,30 +638,33 @@ public abstract class JavaElement extends PlatformObject return Util.combineHashCodes(this.name.hashCode(), this.parent .hashCode()); } + /** * Returns true if this element is an ancestor of the given element, * otherwise false. */ public boolean isAncestorOf(IJavaElement e) { - IJavaElement parentElement= e.getParent(); + IJavaElement parentElement = e.getParent(); while (parentElement != null && !parentElement.equals(this)) { - parentElement= parentElement.getParent(); + parentElement = parentElement.getParent(); } return parentElement != null; } - + /** * @see IJavaElement */ public boolean isReadOnly() { return false; } + /** * @see IJavaElement */ public boolean isStructureKnown() throws JavaModelException { return ((JavaElementInfo) getElementInfo()).isStructureKnown(); } + /** * Creates and returns and not present exception for this element. */ @@ -620,34 +672,36 @@ public abstract class JavaElement extends PlatformObject return new JavaModelException(new JavaModelStatus( IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, this)); } + /** * Opens this element and all parents that are not already open. * * @exception JavaModelException * this element is not present or accessible */ - // protected void openHierarchy() throws JavaModelException { - // if (this instanceof IOpenable) { - // ((Openable) this).openWhenClosed(null); - // } else { - // Openable openableParent = (Openable)getOpenableParent(); - // if (openableParent != null) { - // JavaElementInfo openableParentInfo = (JavaElementInfo) + // protected void openHierarchy() throws JavaModelException { + // if (this instanceof IOpenable) { + // ((Openable) this).openWhenClosed(null); + // } else { + // Openable openableParent = (Openable)getOpenableParent(); + // if (openableParent != null) { + // JavaElementInfo openableParentInfo = (JavaElementInfo) // JavaModelManager.getJavaModelManager().getInfo((IJavaElement) // openableParent); - // if (openableParentInfo == null) { - // openableParent.openWhenClosed(null); - // } else { - // throw newNotPresentException(); - // } - // } - // } - // } + // if (openableParentInfo == null) { + // openableParent.openWhenClosed(null); + // } else { + // throw newNotPresentException(); + // } + // } + // } + // } /** * This element has just been opened. Do any necessary setup. */ protected void opening(Object info) { } + /* * Opens an Openable that is known to be closed (no check for * isOpen() ). Returns the created element info. @@ -683,32 +737,34 @@ public abstract class JavaElement extends PlatformObject } return info; } + /** */ public String readableName() { return this.getElementName(); } + /** * Removes all cached info from the Java Model, including all children, but * does not close this element. */ - // protected void removeInfo() { - // Object info = JavaModelManager.getJavaModelManager().peekAtInfo(this); - // if (info != null) { - // if (this instanceof IParent) { - // IJavaElement[] children = ((JavaElementInfo)info).getChildren(); - // for (int i = 0, size = children.length; i < size; ++i) { - // JavaElement child = (JavaElement) children[i]; - // child.removeInfo(); - // } - // } - // JavaModelManager.getJavaModelManager().removeInfo(this); - // } - // } - // /** - // * Returns a copy of this element rooted at the given project. - // */ - // public abstract IJavaElement rootedAt(IJavaProject project); + // protected void removeInfo() { + // Object info = JavaModelManager.getJavaModelManager().peekAtInfo(this); + // if (info != null) { + // if (this instanceof IParent) { + // IJavaElement[] children = ((JavaElementInfo)info).getChildren(); + // for (int i = 0, size = children.length; i < size; ++i) { + // JavaElement child = (JavaElement) children[i]; + // child.removeInfo(); + // } + // } + // JavaModelManager.getJavaModelManager().removeInfo(this); + // } + // } + // /** + // * Returns a copy of this element rooted at the given project. + // */ + // public abstract IJavaElement rootedAt(IJavaProject project); /** * Runs a Java Model Operation */ @@ -737,18 +793,21 @@ public abstract class JavaElement extends PlatformObject } } } + /** * Sets the occurrence count of the handle. */ protected void setOccurrenceCount(int count) { occurrenceCount = count; } + protected String tabString(int tab) { StringBuffer buffer = new StringBuffer(); for (int i = tab; i > 0; i--) buffer.append(" "); //$NON-NLS-1$ return buffer.toString(); } + /** * Debugging purposes */ @@ -757,6 +816,7 @@ public abstract class JavaElement extends PlatformObject this.toStringInfo(0, buffer, NO_INFO); return buffer.toString(); } + /** * Debugging purposes */ @@ -765,8 +825,9 @@ public abstract class JavaElement extends PlatformObject toString(0, buffer); return buffer.toString(); } + /** - * Debugging purposes + * Debugging purposes */ protected void toStringName(StringBuffer buffer) { buffer.append(getElementName()); @@ -775,17 +836,19 @@ public abstract class JavaElement extends PlatformObject buffer.append(this.occurrenceCount); } } + /** * Debugging purposes */ protected void toString(int tab, StringBuffer buffer) { - // Object info = this.toStringInfo(tab, buffer); + // Object info = this.toStringInfo(tab, buffer); Object info = null; if (tab == 0) { this.toStringAncestors(buffer); } this.toStringChildren(tab, buffer, info); } + /** * Debugging purposes */ @@ -795,6 +858,7 @@ public abstract class JavaElement extends PlatformObject this.toStringAncestors(buffer); return buffer.toString(); } + /** * Debugging purposes */ @@ -807,6 +871,7 @@ public abstract class JavaElement extends PlatformObject buffer.append("]"); //$NON-NLS-1$ } } + /** * Debugging purposes */ @@ -819,14 +884,15 @@ public abstract class JavaElement extends PlatformObject ((JavaElement) children[i]).toString(tab + 1, buffer); } } + /** * Debugging purposes */ - // public Object toStringInfo(int tab, StringBuffer buffer) { - // Object info = JavaModelManager.getJavaModelManager().peekAtInfo(this); - // this.toStringInfo(tab, buffer, info); - // return info; - // } + // public Object toStringInfo(int tab, StringBuffer buffer) { + // Object info = JavaModelManager.getJavaModelManager().peekAtInfo(this); + // this.toStringInfo(tab, buffer, info); + // return info; + // } /** * Debugging purposes */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElementDelta.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElementDelta.java index 1dfedd9..4e3ef02 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElementDelta.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElementDelta.java @@ -17,31 +17,35 @@ import net.sourceforge.phpdt.core.IJavaElementDelta; import org.eclipse.core.resources.IResourceDelta; - /** * @see IJavaElementDelta */ public class JavaElementDelta extends SimpleDelta implements IJavaElementDelta { /** * The element that this delta describes the change to. + * * @see #getElement() */ protected IJavaElement fChangedElement; + /** * @see #getKind() */ private int fKind = 0; + /** * @see #getFlags() */ private int fChangeFlags = 0; + /** * @see #getAffectedChildren() */ protected IJavaElementDelta[] fAffectedChildren = fgEmptyDelta; /** - * Collection of resource deltas that correspond to non java resources deltas. + * Collection of resource deltas that correspond to non java resources + * deltas. */ protected IResourceDelta[] resourceDeltas = null; @@ -49,41 +53,45 @@ public class JavaElementDelta extends SimpleDelta implements IJavaElementDelta { * Counter of resource deltas */ protected int resourceDeltasCounter; + /** * @see #getMovedFromHandle() */ protected IJavaElement fMovedFromHandle = null; + /** * @see #getMovedToHandle() */ protected IJavaElement fMovedToHandle = null; + /** * Empty array of IJavaElementDelta */ - protected static IJavaElementDelta[] fgEmptyDelta= new IJavaElementDelta[] {}; -/** - * Creates the root delta. To create the nested delta - * hierarchies use the following convenience methods. The root - * delta can be created at any level (for example: project, package root, - * package fragment...). - *

                                        - *
                                      • added(IJavaElement) - *
                                      • changed(IJavaElement) - *
                                      • moved(IJavaElement, IJavaElement) - *
                                      • removed(IJavaElement) - *
                                      • renamed(IJavaElement, IJavaElement) - *
                                      - */ -public JavaElementDelta(IJavaElement element) { - super(); - fChangedElement = element; -} -/** - * Adds the child delta to the collection of affected children. If the - * child is already in the collection, walk down the hierarchy. - */ -protected void addAffectedChild(JavaElementDelta child) { - switch (fKind) { + protected static IJavaElementDelta[] fgEmptyDelta = new IJavaElementDelta[] {}; + + /** + * Creates the root delta. To create the nested delta hierarchies use the + * following convenience methods. The root delta can be created at any level + * (for example: project, package root, package fragment...). + *
                                        + *
                                      • added(IJavaElement) + *
                                      • changed(IJavaElement) + *
                                      • moved(IJavaElement, IJavaElement) + *
                                      • removed(IJavaElement) + *
                                      • renamed(IJavaElement, IJavaElement) + *
                                      + */ + public JavaElementDelta(IJavaElement element) { + super(); + fChangedElement = element; + } + + /** + * Adds the child delta to the collection of affected children. If the child + * is already in the collection, walk down the hierarchy. + */ + protected void addAffectedChild(JavaElementDelta child) { + switch (fKind) { case ADDED: case REMOVED: // no need to add a child if this parent is added or removed @@ -94,128 +102,142 @@ protected void addAffectedChild(JavaElementDelta child) { default: fKind = CHANGED; fChangeFlags |= F_CHILDREN; - } + } - // if a child delta is added to a compilation unit delta or below, - // it's a fine grained delta - if (fChangedElement.getElementType() >= IJavaElement.COMPILATION_UNIT) { - this.fineGrained(); - } - - if (fAffectedChildren.length == 0) { - fAffectedChildren = new IJavaElementDelta[] {child}; - return; - } - IJavaElementDelta existingChild = null; - int existingChildIndex = -1; - if (fAffectedChildren != null) { - for (int i = 0; i < fAffectedChildren.length; i++) { - if (this.equalsAndSameParent(fAffectedChildren[i].getElement(), child.getElement())) { // handle case of two jars that can be equals but not in the same project - existingChild = fAffectedChildren[i]; - existingChildIndex = i; - break; + // if a child delta is added to a compilation unit delta or below, + // it's a fine grained delta + if (fChangedElement.getElementType() >= IJavaElement.COMPILATION_UNIT) { + this.fineGrained(); + } + + if (fAffectedChildren.length == 0) { + fAffectedChildren = new IJavaElementDelta[] { child }; + return; + } + IJavaElementDelta existingChild = null; + int existingChildIndex = -1; + if (fAffectedChildren != null) { + for (int i = 0; i < fAffectedChildren.length; i++) { + if (this.equalsAndSameParent(fAffectedChildren[i].getElement(), + child.getElement())) { // handle case of two jars that + // can be equals but not in the + // same project + existingChild = fAffectedChildren[i]; + existingChildIndex = i; + break; + } } } - } - if (existingChild == null) { //new affected child - fAffectedChildren= growAndAddToArray(fAffectedChildren, child); - } else { - switch (existingChild.getKind()) { + if (existingChild == null) { // new affected child + fAffectedChildren = growAndAddToArray(fAffectedChildren, child); + } else { + switch (existingChild.getKind()) { case ADDED: switch (child.getKind()) { - case ADDED: // child was added then added -> it is added - case CHANGED: // child was added then changed -> it is added - return; - case REMOVED: // child was added then removed -> noop - fAffectedChildren = this.removeAndShrinkArray(fAffectedChildren, existingChildIndex); - return; + case ADDED: // child was added then added -> it is added + case CHANGED: // child was added then changed -> it is added + return; + case REMOVED: // child was added then removed -> noop + fAffectedChildren = this.removeAndShrinkArray( + fAffectedChildren, existingChildIndex); + return; } break; case REMOVED: switch (child.getKind()) { - case ADDED: // child was removed then added -> it is changed - child.fKind = CHANGED; - fAffectedChildren[existingChildIndex] = child; - return; - case CHANGED: // child was removed then changed -> it is removed - case REMOVED: // child was removed then removed -> it is removed - return; + case ADDED: // child was removed then added -> it is changed + child.fKind = CHANGED; + fAffectedChildren[existingChildIndex] = child; + return; + case CHANGED: // child was removed then changed -> it is + // removed + case REMOVED: // child was removed then removed -> it is + // removed + return; } break; case CHANGED: switch (child.getKind()) { - case ADDED: // child was changed then added -> it is added - case REMOVED: // child was changed then removed -> it is removed - fAffectedChildren[existingChildIndex] = child; - return; - case CHANGED: // child was changed then changed -> it is changed - IJavaElementDelta[] children = child.getAffectedChildren(); - for (int i = 0; i < children.length; i++) { - JavaElementDelta childsChild = (JavaElementDelta) children[i]; - ((JavaElementDelta) existingChild).addAffectedChild(childsChild); - } - - // update flags if needed - switch (((JavaElementDelta) existingChild).fChangeFlags) { - case F_ADDED_TO_CLASSPATH: - case F_REMOVED_FROM_CLASSPATH: - case F_SOURCEATTACHED: - case F_SOURCEDETACHED: - ((JavaElementDelta) existingChild).fChangeFlags |= ((JavaElementDelta) child).fChangeFlags; - break; - } - - // add the non-java resource deltas if needed - // note that the child delta always takes precedence over this existing child delta - // as non-java resource deltas are always created last (by the DeltaProcessor) - IResourceDelta[] resDeltas = child.getResourceDeltas(); - if (resDeltas != null) { - ((JavaElementDelta)existingChild).resourceDeltas = resDeltas; - ((JavaElementDelta)existingChild).resourceDeltasCounter = child.resourceDeltasCounter; - } - return; + case ADDED: // child was changed then added -> it is added + case REMOVED: // child was changed then removed -> it is + // removed + fAffectedChildren[existingChildIndex] = child; + return; + case CHANGED: // child was changed then changed -> it is + // changed + IJavaElementDelta[] children = child.getAffectedChildren(); + for (int i = 0; i < children.length; i++) { + JavaElementDelta childsChild = (JavaElementDelta) children[i]; + ((JavaElementDelta) existingChild) + .addAffectedChild(childsChild); + } + + // update flags if needed + switch (((JavaElementDelta) existingChild).fChangeFlags) { + case F_ADDED_TO_CLASSPATH: + case F_REMOVED_FROM_CLASSPATH: + case F_SOURCEATTACHED: + case F_SOURCEDETACHED: + ((JavaElementDelta) existingChild).fChangeFlags |= ((JavaElementDelta) child).fChangeFlags; + break; + } + + // add the non-java resource deltas if needed + // note that the child delta always takes precedence over + // this existing child delta + // as non-java resource deltas are always created last (by + // the DeltaProcessor) + IResourceDelta[] resDeltas = child.getResourceDeltas(); + if (resDeltas != null) { + ((JavaElementDelta) existingChild).resourceDeltas = resDeltas; + ((JavaElementDelta) existingChild).resourceDeltasCounter = child.resourceDeltasCounter; + } + return; } break; - default: - // unknown -> existing child becomes the child with the existing child's flags + default: + // unknown -> existing child becomes the child with the existing + // child's flags int flags = existingChild.getFlags(); fAffectedChildren[existingChildIndex] = child; child.fChangeFlags |= flags; + } } } -} -///** -// * Creates the nested deltas resulting from an add operation. -// * Convenience method for creating add deltas. -// * The constructor should be used to create the root delta -// * and then an add operation should call this method. -// */ -//public void added(IJavaElement element) { -// JavaElementDelta addedDelta = new JavaElementDelta(element); -// addedDelta.fKind = ADDED; -// insertDeltaTree(element, addedDelta); -//} -/** - * Creates the nested deltas resulting from an add operation. - * Convenience method for creating add deltas. - * The constructor should be used to create the root delta - * and then an add operation should call this method. - */ -public void added(IJavaElement element) { - added(element, 0); -} -public void added(IJavaElement element, int flags) { - JavaElementDelta addedDelta = new JavaElementDelta(element); - addedDelta.added(); - addedDelta.changeFlags |= flags; - insertDeltaTree(element, addedDelta); -} -/** - * Adds the child delta to the collection of affected children. If the - * child is already in the collection, walk down the hierarchy. - */ -protected void addResourceDelta(IResourceDelta child) { - switch (fKind) { + + // /** + // * Creates the nested deltas resulting from an add operation. + // * Convenience method for creating add deltas. + // * The constructor should be used to create the root delta + // * and then an add operation should call this method. + // */ + // public void added(IJavaElement element) { + // JavaElementDelta addedDelta = new JavaElementDelta(element); + // addedDelta.fKind = ADDED; + // insertDeltaTree(element, addedDelta); + // } + /** + * Creates the nested deltas resulting from an add operation. Convenience + * method for creating add deltas. The constructor should be used to create + * the root delta and then an add operation should call this method. + */ + public void added(IJavaElement element) { + added(element, 0); + } + + public void added(IJavaElement element, int flags) { + JavaElementDelta addedDelta = new JavaElementDelta(element); + addedDelta.added(); + addedDelta.changeFlags |= flags; + insertDeltaTree(element, addedDelta); + } + + /** + * Adds the child delta to the collection of affected children. If the child + * is already in the collection, walk down the hierarchy. + */ + protected void addResourceDelta(IResourceDelta child) { + switch (fKind) { case ADDED: case REMOVED: // no need to add a child if this parent is added or removed @@ -226,537 +248,634 @@ protected void addResourceDelta(IResourceDelta child) { default: fKind = CHANGED; fChangeFlags |= F_CONTENT; - } - if (resourceDeltas == null) { - resourceDeltas = new IResourceDelta[5]; + } + if (resourceDeltas == null) { + resourceDeltas = new IResourceDelta[5]; + resourceDeltas[resourceDeltasCounter++] = child; + return; + } + if (resourceDeltas.length == resourceDeltasCounter) { + // need a resize + System + .arraycopy( + resourceDeltas, + 0, + (resourceDeltas = new IResourceDelta[resourceDeltasCounter * 2]), + 0, resourceDeltasCounter); + } resourceDeltas[resourceDeltasCounter++] = child; - return; } - if (resourceDeltas.length == resourceDeltasCounter) { - // need a resize - System.arraycopy(resourceDeltas, 0, (resourceDeltas = new IResourceDelta[resourceDeltasCounter * 2]), 0, resourceDeltasCounter); + + /** + * Creates the nested deltas resulting from a change operation. Convenience + * method for creating change deltas. The constructor should be used to + * create the root delta and then a change operation should call this + * method. + */ + public JavaElementDelta changed(IJavaElement element, int changeFlag) { + JavaElementDelta changedDelta = new JavaElementDelta(element); + changedDelta.changed(changeFlag); + insertDeltaTree(element, changedDelta); + return changedDelta; } - resourceDeltas[resourceDeltasCounter++] = child; -} -/** - * Creates the nested deltas resulting from a change operation. - * Convenience method for creating change deltas. - * The constructor should be used to create the root delta - * and then a change operation should call this method. - */ -public JavaElementDelta changed(IJavaElement element, int changeFlag) { - JavaElementDelta changedDelta = new JavaElementDelta(element); - changedDelta.changed(changeFlag); - insertDeltaTree(element, changedDelta); - return changedDelta; -} -/** - * Mark this delta as a content changed delta. - */ -public void contentChanged() { - fChangeFlags |= F_CONTENT; -} -///** -// * Clone this delta so that its elements are rooted at the given project. -// */ -//public IJavaElementDelta clone(IJavaProject project) { -// JavaElementDelta clone = -// new JavaElementDelta(((JavaElement)fChangedElement).rootedAt(project)); -// if (fAffectedChildren != fgEmptyDelta) { -// int length = fAffectedChildren.length; -// IJavaElementDelta[] cloneChildren = new IJavaElementDelta[length]; -// for (int i= 0; i < length; i++) { -// cloneChildren[i] = ((JavaElementDelta)fAffectedChildren[i]).clone(project); -// } -// clone.fAffectedChildren = cloneChildren; -// } -// clone.fChangeFlags = fChangeFlags; -// clone.fKind = fKind; -// if (fMovedFromHandle != null) { -// clone.fMovedFromHandle = ((JavaElement)fMovedFromHandle).rootedAt(project); -// } -// if (fMovedToHandle != null) { -// clone.fMovedToHandle = ((JavaElement)fMovedToHandle).rootedAt(project); -// } -// clone.resourceDeltas = this.resourceDeltas; -// clone.resourceDeltasCounter = this.resourceDeltasCounter; -// return clone; -//} + /** + * Mark this delta as a content changed delta. + */ + public void contentChanged() { + fChangeFlags |= F_CONTENT; + } -/** - * Creates the nested deltas for a closed element. - */ -public void closed(IJavaElement element) { - JavaElementDelta delta = new JavaElementDelta(element); - delta.fKind = CHANGED; - delta.fChangeFlags |= F_CLOSED; - insertDeltaTree(element, delta); -} -/** - * Creates the nested delta deltas based on the affected element - * its delta, and the root of this delta tree. Returns the root - * of the created delta tree. - */ -protected JavaElementDelta createDeltaTree(IJavaElement element, JavaElementDelta delta) { - JavaElementDelta childDelta = delta; - ArrayList ancestors= getAncestors(element); - if (ancestors == null) { - if (this.equalsAndSameParent(delta.getElement(), getElement())) { // handle case of two jars that can be equals but not in the same project - // the element being changed is the root element - fKind= delta.fKind; - fChangeFlags = delta.fChangeFlags; - fMovedToHandle = delta.fMovedToHandle; - fMovedFromHandle = delta.fMovedFromHandle; - } - } else { - for (int i = 0, size = ancestors.size(); i < size; i++) { - IJavaElement ancestor = (IJavaElement) ancestors.get(i); - JavaElementDelta ancestorDelta = new JavaElementDelta(ancestor); - ancestorDelta.addAffectedChild(childDelta); - childDelta = ancestorDelta; - } - } - return childDelta; -} -/** - * Returns whether the two java elements are equals and have the same parent. - */ -protected boolean equalsAndSameParent(IJavaElement e1, IJavaElement e2) { - IJavaElement parent1; - return e1.equals(e2) && ((parent1 = e1.getParent()) != null) && parent1.equals(e2.getParent()); -} -/** - * Returns the JavaElementDelta for the given element - * in the delta tree, or null, if no delta for the given element is found. - */ -protected JavaElementDelta find(IJavaElement e) { - if (this.equalsAndSameParent(fChangedElement, e)) { // handle case of two jars that can be equals but not in the same project - return this; - } else { - for (int i = 0; i < fAffectedChildren.length; i++) { - JavaElementDelta delta = ((JavaElementDelta)fAffectedChildren[i]).find(e); - if (delta != null) { - return delta; + // /** + // * Clone this delta so that its elements are rooted at the given project. + // */ + // public IJavaElementDelta clone(IJavaProject project) { + // JavaElementDelta clone = + // new JavaElementDelta(((JavaElement)fChangedElement).rootedAt(project)); + // if (fAffectedChildren != fgEmptyDelta) { + // int length = fAffectedChildren.length; + // IJavaElementDelta[] cloneChildren = new IJavaElementDelta[length]; + // for (int i= 0; i < length; i++) { + // cloneChildren[i] = + // ((JavaElementDelta)fAffectedChildren[i]).clone(project); + // } + // clone.fAffectedChildren = cloneChildren; + // } + // clone.fChangeFlags = fChangeFlags; + // clone.fKind = fKind; + // if (fMovedFromHandle != null) { + // clone.fMovedFromHandle = + // ((JavaElement)fMovedFromHandle).rootedAt(project); + // } + // if (fMovedToHandle != null) { + // clone.fMovedToHandle = ((JavaElement)fMovedToHandle).rootedAt(project); + // } + // clone.resourceDeltas = this.resourceDeltas; + // clone.resourceDeltasCounter = this.resourceDeltasCounter; + // return clone; + // } + + /** + * Creates the nested deltas for a closed element. + */ + public void closed(IJavaElement element) { + JavaElementDelta delta = new JavaElementDelta(element); + delta.fKind = CHANGED; + delta.fChangeFlags |= F_CLOSED; + insertDeltaTree(element, delta); + } + + /** + * Creates the nested delta deltas based on the affected element its delta, + * and the root of this delta tree. Returns the root of the created delta + * tree. + */ + protected JavaElementDelta createDeltaTree(IJavaElement element, + JavaElementDelta delta) { + JavaElementDelta childDelta = delta; + ArrayList ancestors = getAncestors(element); + if (ancestors == null) { + if (this.equalsAndSameParent(delta.getElement(), getElement())) { // handle + // case + // of + // two + // jars + // that + // can + // be + // equals + // but + // not + // in + // the + // same + // project + // the element being changed is the root element + fKind = delta.fKind; + fChangeFlags = delta.fChangeFlags; + fMovedToHandle = delta.fMovedToHandle; + fMovedFromHandle = delta.fMovedFromHandle; + } + } else { + for (int i = 0, size = ancestors.size(); i < size; i++) { + IJavaElement ancestor = (IJavaElement) ancestors.get(i); + JavaElementDelta ancestorDelta = new JavaElementDelta(ancestor); + ancestorDelta.addAffectedChild(childDelta); + childDelta = ancestorDelta; } } + return childDelta; } - return null; -} -/** - * Mark this delta as a fine-grained delta. - */ -public void fineGrained() { - if (fKind == 0) { // if not set yet - fKind = CHANGED; + + /** + * Returns whether the two java elements are equals and have the same + * parent. + */ + protected boolean equalsAndSameParent(IJavaElement e1, IJavaElement e2) { + IJavaElement parent1; + return e1.equals(e2) && ((parent1 = e1.getParent()) != null) + && parent1.equals(e2.getParent()); } - fChangeFlags |= F_FINE_GRAINED; -} -/** - * @see IJavaElementDelta - */ -public IJavaElementDelta[] getAddedChildren() { - return getChildrenOfType(ADDED); -} -/** - * @see IJavaElementDelta - */ -public IJavaElementDelta[] getAffectedChildren() { - return fAffectedChildren; -} -/** - * Returns a collection of all the parents of this element up to (but - * not including) the root of this tree in bottom-up order. If the given - * element is not a descendant of the root of this tree, null - * is returned. - */ -private ArrayList getAncestors(IJavaElement element) { - IJavaElement parent = element.getParent(); - if (parent == null) { + + /** + * Returns the JavaElementDelta for the given element in the + * delta tree, or null, if no delta for the given element is found. + */ + protected JavaElementDelta find(IJavaElement e) { + if (this.equalsAndSameParent(fChangedElement, e)) { // handle case of + // two jars that can + // be equals but not + // in the same + // project + return this; + } else { + for (int i = 0; i < fAffectedChildren.length; i++) { + JavaElementDelta delta = ((JavaElementDelta) fAffectedChildren[i]) + .find(e); + if (delta != null) { + return delta; + } + } + } return null; } - ArrayList parents = new ArrayList(); - while (!parent.equals(fChangedElement)) { - parents.add(parent); - parent = parent.getParent(); + + /** + * Mark this delta as a fine-grained delta. + */ + public void fineGrained() { + if (fKind == 0) { // if not set yet + fKind = CHANGED; + } + fChangeFlags |= F_FINE_GRAINED; + } + + /** + * @see IJavaElementDelta + */ + public IJavaElementDelta[] getAddedChildren() { + return getChildrenOfType(ADDED); + } + + /** + * @see IJavaElementDelta + */ + public IJavaElementDelta[] getAffectedChildren() { + return fAffectedChildren; + } + + /** + * Returns a collection of all the parents of this element up to (but not + * including) the root of this tree in bottom-up order. If the given element + * is not a descendant of the root of this tree, null is + * returned. + */ + private ArrayList getAncestors(IJavaElement element) { + IJavaElement parent = element.getParent(); if (parent == null) { return null; } + ArrayList parents = new ArrayList(); + while (!parent.equals(fChangedElement)) { + parents.add(parent); + parent = parent.getParent(); + if (parent == null) { + return null; + } + } + parents.trimToSize(); + return parents; } - parents.trimToSize(); - return parents; -} -/** - * @see IJavaElementDelta - */ -public IJavaElementDelta[] getChangedChildren() { - return getChildrenOfType(CHANGED); -} -/** - * @see IJavaElementDelta - */ -protected IJavaElementDelta[] getChildrenOfType(int type) { - int length = fAffectedChildren.length; - if (length == 0) { - return new IJavaElementDelta[] {}; + + /** + * @see IJavaElementDelta + */ + public IJavaElementDelta[] getChangedChildren() { + return getChildrenOfType(CHANGED); } - ArrayList children= new ArrayList(length); - for (int i = 0; i < length; i++) { - if (fAffectedChildren[i].getKind() == type) { - children.add(fAffectedChildren[i]); + + /** + * @see IJavaElementDelta + */ + protected IJavaElementDelta[] getChildrenOfType(int type) { + int length = fAffectedChildren.length; + if (length == 0) { + return new IJavaElementDelta[] {}; + } + ArrayList children = new ArrayList(length); + for (int i = 0; i < length; i++) { + if (fAffectedChildren[i].getKind() == type) { + children.add(fAffectedChildren[i]); + } } + + IJavaElementDelta[] childrenOfType = new IJavaElementDelta[children + .size()]; + children.toArray(childrenOfType); + + return childrenOfType; } - IJavaElementDelta[] childrenOfType = new IJavaElementDelta[children.size()]; - children.toArray(childrenOfType); - - return childrenOfType; -} -/** - * Returns the delta for a given element. Only looks below this - * delta. - */ -protected JavaElementDelta getDeltaFor(IJavaElement element) { - if (this.equalsAndSameParent(getElement(), element)) // handle case of two jars that can be equals but not in the same project - return this; - if (fAffectedChildren.length == 0) - return null; - int childrenCount = fAffectedChildren.length; - for (int i = 0; i < childrenCount; i++) { - JavaElementDelta delta = (JavaElementDelta)fAffectedChildren[i]; - if (this.equalsAndSameParent(delta.getElement(), element)) { // handle case of two jars that can be equals but not in the same project - return delta; - } else { - delta = ((JavaElementDelta)delta).getDeltaFor(element); - if (delta != null) + /** + * Returns the delta for a given element. Only looks below this delta. + */ + protected JavaElementDelta getDeltaFor(IJavaElement element) { + if (this.equalsAndSameParent(getElement(), element)) // handle case + // of two jars + // that can be + // equals but + // not in the + // same project + return this; + if (fAffectedChildren.length == 0) + return null; + int childrenCount = fAffectedChildren.length; + for (int i = 0; i < childrenCount; i++) { + JavaElementDelta delta = (JavaElementDelta) fAffectedChildren[i]; + if (this.equalsAndSameParent(delta.getElement(), element)) { // handle + // case + // of + // two + // jars + // that + // can + // be + // equals + // but + // not + // in + // the + // same + // project return delta; + } else { + delta = ((JavaElementDelta) delta).getDeltaFor(element); + if (delta != null) + return delta; + } } + return null; } - return null; -} -/** - * @see IJavaElementDelta - */ -public IJavaElement getElement() { - return fChangedElement; -} -/** - * @see IJavaElementDelta - */ -public int getFlags() { - return fChangeFlags; -} -/** - * @see IJavaElementDelta - */ -public int getKind() { - return fKind; -} -/** - * @see IJavaElementDelta - */ -public IJavaElement getMovedFromElement() { - return fMovedFromHandle; -} -/** - * @see IJavaElementDelta - */ -public IJavaElement getMovedToElement() { - return fMovedToHandle; -} -/** - * @see IJavaElementDelta - */ -public IJavaElementDelta[] getRemovedChildren() { - return getChildrenOfType(REMOVED); -} -/** - * Return the collection of resource deltas. Return null if none. - */ -public IResourceDelta[] getResourceDeltas() { - if (resourceDeltas == null) return null; - if (resourceDeltas.length != resourceDeltasCounter) { - System.arraycopy(resourceDeltas, 0, resourceDeltas = new IResourceDelta[resourceDeltasCounter], 0, resourceDeltasCounter); + + /** + * @see IJavaElementDelta + */ + public IJavaElement getElement() { + return fChangedElement; } - return resourceDeltas; -} -/** - * Adds the new element to a new array that contains all of the elements of the old array. - * Returns the new array. - */ -protected IJavaElementDelta[] growAndAddToArray(IJavaElementDelta[] array, IJavaElementDelta addition) { - IJavaElementDelta[] old = array; - array = new IJavaElementDelta[old.length + 1]; - System.arraycopy(old, 0, array, 0, old.length); - array[old.length] = addition; - return array; -} -/** - * Creates the delta tree for the given element and delta, and then - * inserts the tree as an affected child of this node. - */ -protected void insertDeltaTree(IJavaElement element, JavaElementDelta delta) { - JavaElementDelta childDelta= createDeltaTree(element, delta); - if (!this.equalsAndSameParent(element, getElement())) { // handle case of two jars that can be equals but not in the same project - addAffectedChild(childDelta); + + /** + * @see IJavaElementDelta + */ + public int getFlags() { + return fChangeFlags; } -} -/** - * Creates the nested deltas resulting from an move operation. - * Convenience method for creating the "move from" delta. - * The constructor should be used to create the root delta - * and then the move operation should call this method. - */ -public void movedFrom(IJavaElement movedFromElement, IJavaElement movedToElement) { - JavaElementDelta removedDelta = new JavaElementDelta(movedFromElement); - removedDelta.fKind = REMOVED; - removedDelta.fChangeFlags |= F_MOVED_TO; - removedDelta.fMovedToHandle = movedToElement; - insertDeltaTree(movedFromElement, removedDelta); -} -/** - * Creates the nested deltas resulting from an move operation. - * Convenience method for creating the "move to" delta. - * The constructor should be used to create the root delta - * and then the move operation should call this method. - */ -public void movedTo(IJavaElement movedToElement, IJavaElement movedFromElement) { - JavaElementDelta addedDelta = new JavaElementDelta(movedToElement); - addedDelta.fKind = ADDED; - addedDelta.fChangeFlags |= F_MOVED_FROM; - addedDelta.fMovedFromHandle = movedFromElement; - insertDeltaTree(movedToElement, addedDelta); -} -/** - * Creates the nested deltas for an opened element. - */ -public void opened(IJavaElement element) { - JavaElementDelta delta = new JavaElementDelta(element); - delta.fKind = CHANGED; - delta.fChangeFlags |= F_OPENED; - insertDeltaTree(element, delta); -} -/** - * Removes the child delta from the collection of affected children. - */ -protected void removeAffectedChild(JavaElementDelta child) { - int index = -1; - if (fAffectedChildren != null) { - for (int i = 0; i < fAffectedChildren.length; i++) { - if (this.equalsAndSameParent(fAffectedChildren[i].getElement(), child.getElement())) { // handle case of two jars that can be equals but not in the same project - index = i; - break; + + /** + * @see IJavaElementDelta + */ + public int getKind() { + return fKind; + } + + /** + * @see IJavaElementDelta + */ + public IJavaElement getMovedFromElement() { + return fMovedFromHandle; + } + + /** + * @see IJavaElementDelta + */ + public IJavaElement getMovedToElement() { + return fMovedToHandle; + } + + /** + * @see IJavaElementDelta + */ + public IJavaElementDelta[] getRemovedChildren() { + return getChildrenOfType(REMOVED); + } + + /** + * Return the collection of resource deltas. Return null if none. + */ + public IResourceDelta[] getResourceDeltas() { + if (resourceDeltas == null) + return null; + if (resourceDeltas.length != resourceDeltasCounter) { + System.arraycopy(resourceDeltas, 0, + resourceDeltas = new IResourceDelta[resourceDeltasCounter], + 0, resourceDeltasCounter); + } + return resourceDeltas; + } + + /** + * Adds the new element to a new array that contains all of the elements of + * the old array. Returns the new array. + */ + protected IJavaElementDelta[] growAndAddToArray(IJavaElementDelta[] array, + IJavaElementDelta addition) { + IJavaElementDelta[] old = array; + array = new IJavaElementDelta[old.length + 1]; + System.arraycopy(old, 0, array, 0, old.length); + array[old.length] = addition; + return array; + } + + /** + * Creates the delta tree for the given element and delta, and then inserts + * the tree as an affected child of this node. + */ + protected void insertDeltaTree(IJavaElement element, JavaElementDelta delta) { + JavaElementDelta childDelta = createDeltaTree(element, delta); + if (!this.equalsAndSameParent(element, getElement())) { // handle case + // of two jars + // that can be + // equals but + // not in the + // same project + addAffectedChild(childDelta); + } + } + + /** + * Creates the nested deltas resulting from an move operation. Convenience + * method for creating the "move from" delta. The constructor should be used + * to create the root delta and then the move operation should call this + * method. + */ + public void movedFrom(IJavaElement movedFromElement, + IJavaElement movedToElement) { + JavaElementDelta removedDelta = new JavaElementDelta(movedFromElement); + removedDelta.fKind = REMOVED; + removedDelta.fChangeFlags |= F_MOVED_TO; + removedDelta.fMovedToHandle = movedToElement; + insertDeltaTree(movedFromElement, removedDelta); + } + + /** + * Creates the nested deltas resulting from an move operation. Convenience + * method for creating the "move to" delta. The constructor should be used + * to create the root delta and then the move operation should call this + * method. + */ + public void movedTo(IJavaElement movedToElement, + IJavaElement movedFromElement) { + JavaElementDelta addedDelta = new JavaElementDelta(movedToElement); + addedDelta.fKind = ADDED; + addedDelta.fChangeFlags |= F_MOVED_FROM; + addedDelta.fMovedFromHandle = movedFromElement; + insertDeltaTree(movedToElement, addedDelta); + } + + /** + * Creates the nested deltas for an opened element. + */ + public void opened(IJavaElement element) { + JavaElementDelta delta = new JavaElementDelta(element); + delta.fKind = CHANGED; + delta.fChangeFlags |= F_OPENED; + insertDeltaTree(element, delta); + } + + /** + * Removes the child delta from the collection of affected children. + */ + protected void removeAffectedChild(JavaElementDelta child) { + int index = -1; + if (fAffectedChildren != null) { + for (int i = 0; i < fAffectedChildren.length; i++) { + if (this.equalsAndSameParent(fAffectedChildren[i].getElement(), + child.getElement())) { // handle case of two jars that + // can be equals but not in the + // same project + index = i; + break; + } } } + if (index >= 0) { + fAffectedChildren = removeAndShrinkArray(fAffectedChildren, index); + } } - if (index >= 0) { - fAffectedChildren= removeAndShrinkArray(fAffectedChildren, index); + + /** + * Removes the element from the array. Returns the a new array which has + * shrunk. + */ + protected IJavaElementDelta[] removeAndShrinkArray(IJavaElementDelta[] old, + int index) { + IJavaElementDelta[] array = new IJavaElementDelta[old.length - 1]; + if (index > 0) + System.arraycopy(old, 0, array, 0, index); + int rest = old.length - index - 1; + if (rest > 0) + System.arraycopy(old, index + 1, array, index, rest); + return array; } -} -/** - * Removes the element from the array. - * Returns the a new array which has shrunk. - */ -protected IJavaElementDelta[] removeAndShrinkArray(IJavaElementDelta[] old, int index) { - IJavaElementDelta[] array = new IJavaElementDelta[old.length - 1]; - if (index > 0) - System.arraycopy(old, 0, array, 0, index); - int rest = old.length - index - 1; - if (rest > 0) - System.arraycopy(old, index + 1, array, index, rest); - return array; -} -/** - * Creates the nested deltas resulting from an delete operation. - * Convenience method for creating removed deltas. - * The constructor should be used to create the root delta - * and then the delete operation should call this method. - */ -public void removed(IJavaElement element) { - removed(element, 0); -} -public void removed(IJavaElement element, int flags) { - JavaElementDelta removedDelta= new JavaElementDelta(element); - insertDeltaTree(element, removedDelta); - JavaElementDelta actualDelta = getDeltaFor(element); - if (actualDelta != null) { - actualDelta.removed(); - actualDelta.changeFlags |= flags; - actualDelta.fAffectedChildren = fgEmptyDelta; + + /** + * Creates the nested deltas resulting from an delete operation. Convenience + * method for creating removed deltas. The constructor should be used to + * create the root delta and then the delete operation should call this + * method. + */ + public void removed(IJavaElement element) { + removed(element, 0); } -} -/** - * Creates the nested deltas resulting from a change operation. - * Convenience method for creating change deltas. - * The constructor should be used to create the root delta - * and then a change operation should call this method. - */ -public void sourceAttached(IJavaElement element) { - JavaElementDelta attachedDelta = new JavaElementDelta(element); - attachedDelta.fKind = CHANGED; - attachedDelta.fChangeFlags |= F_SOURCEATTACHED; - insertDeltaTree(element, attachedDelta); -} -/** - * Creates the nested deltas resulting from a change operation. - * Convenience method for creating change deltas. - * The constructor should be used to create the root delta - * and then a change operation should call this method. - */ -public void sourceDetached(IJavaElement element) { - JavaElementDelta detachedDelta = new JavaElementDelta(element); - detachedDelta.fKind = CHANGED; - detachedDelta.fChangeFlags |= F_SOURCEDETACHED; - insertDeltaTree(element, detachedDelta); -} -/** - * Returns a string representation of this delta's - * structure suitable for debug purposes. - * - * @see #toString() - */ -public String toDebugString(int depth) { - StringBuffer buffer = new StringBuffer(); - for (int i= 0; i < depth; i++) { - buffer.append('\t'); - } - buffer.append(((JavaElement)getElement()).toDebugString()); - buffer.append("["); //$NON-NLS-1$ - switch (getKind()) { - case IJavaElementDelta.ADDED : + public void removed(IJavaElement element, int flags) { + JavaElementDelta removedDelta = new JavaElementDelta(element); + insertDeltaTree(element, removedDelta); + JavaElementDelta actualDelta = getDeltaFor(element); + if (actualDelta != null) { + actualDelta.removed(); + actualDelta.changeFlags |= flags; + actualDelta.fAffectedChildren = fgEmptyDelta; + } + } + + /** + * Creates the nested deltas resulting from a change operation. Convenience + * method for creating change deltas. The constructor should be used to + * create the root delta and then a change operation should call this + * method. + */ + public void sourceAttached(IJavaElement element) { + JavaElementDelta attachedDelta = new JavaElementDelta(element); + attachedDelta.fKind = CHANGED; + attachedDelta.fChangeFlags |= F_SOURCEATTACHED; + insertDeltaTree(element, attachedDelta); + } + + /** + * Creates the nested deltas resulting from a change operation. Convenience + * method for creating change deltas. The constructor should be used to + * create the root delta and then a change operation should call this + * method. + */ + public void sourceDetached(IJavaElement element) { + JavaElementDelta detachedDelta = new JavaElementDelta(element); + detachedDelta.fKind = CHANGED; + detachedDelta.fChangeFlags |= F_SOURCEDETACHED; + insertDeltaTree(element, detachedDelta); + } + + /** + * Returns a string representation of this delta's structure suitable for + * debug purposes. + * + * @see #toString() + */ + public String toDebugString(int depth) { + StringBuffer buffer = new StringBuffer(); + for (int i = 0; i < depth; i++) { + buffer.append('\t'); + } + buffer.append(((JavaElement) getElement()).toDebugString()); + buffer.append("["); //$NON-NLS-1$ + switch (getKind()) { + case IJavaElementDelta.ADDED: buffer.append('+'); break; - case IJavaElementDelta.REMOVED : + case IJavaElementDelta.REMOVED: buffer.append('-'); break; - case IJavaElementDelta.CHANGED : + case IJavaElementDelta.CHANGED: buffer.append('*'); break; - default : + default: buffer.append('?'); break; - } - buffer.append("]: {"); //$NON-NLS-1$ - int changeFlags = getFlags(); - boolean prev = false; - if ((changeFlags & IJavaElementDelta.F_CHILDREN) != 0) { - if (prev) - buffer.append(" | "); //$NON-NLS-1$ - buffer.append("CHILDREN"); //$NON-NLS-1$ - prev = true; - } - if ((changeFlags & IJavaElementDelta.F_CONTENT) != 0) { - if (prev) - buffer.append(" | "); //$NON-NLS-1$ - buffer.append("CONTENT"); //$NON-NLS-1$ - prev = true; - } - if ((changeFlags & IJavaElementDelta.F_MOVED_FROM) != 0) { - if (prev) - buffer.append(" | "); //$NON-NLS-1$ - buffer.append("MOVED_FROM(" + ((JavaElement)getMovedFromElement()).toStringWithAncestors() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ - prev = true; - } - if ((changeFlags & IJavaElementDelta.F_MOVED_TO) != 0) { - if (prev) - buffer.append(" | "); //$NON-NLS-1$ - buffer.append("MOVED_TO(" + ((JavaElement)getMovedToElement()).toStringWithAncestors() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ - prev = true; - } - if ((changeFlags & IJavaElementDelta.F_ADDED_TO_CLASSPATH) != 0) { - if (prev) - buffer.append(" | "); //$NON-NLS-1$ - buffer.append("ADDED TO CLASSPATH"); //$NON-NLS-1$ - prev = true; - } - if ((changeFlags & IJavaElementDelta.F_REMOVED_FROM_CLASSPATH) != 0) { - if (prev) - buffer.append(" | "); //$NON-NLS-1$ - buffer.append("REMOVED FROM CLASSPATH"); //$NON-NLS-1$ - prev = true; - } - if ((changeFlags & IJavaElementDelta.F_REORDER) != 0) { - if (prev) - buffer.append(" | "); //$NON-NLS-1$ - buffer.append("REORDERED"); //$NON-NLS-1$ - prev = true; - } - if ((changeFlags & IJavaElementDelta.F_ARCHIVE_CONTENT_CHANGED) != 0) { - if (prev) - buffer.append(" | "); //$NON-NLS-1$ - buffer.append("ARCHIVE CONTENT CHANGED"); //$NON-NLS-1$ - prev = true; - } - if ((changeFlags & IJavaElementDelta.F_SOURCEATTACHED) != 0) { - if (prev) - buffer.append(" | "); //$NON-NLS-1$ - buffer.append("SOURCE ATTACHED"); //$NON-NLS-1$ - prev = true; - } - if ((changeFlags & IJavaElementDelta.F_SOURCEDETACHED) != 0) { - if (prev) - buffer.append(" | "); //$NON-NLS-1$ - buffer.append("SOURCE DETACHED"); //$NON-NLS-1$ - prev = true; - } - if ((changeFlags & IJavaElementDelta.F_MODIFIERS) != 0) { - if (prev) - buffer.append(" | "); //$NON-NLS-1$ - buffer.append("MODIFIERS CHANGED"); //$NON-NLS-1$ - prev = true; - } - if ((changeFlags & IJavaElementDelta.F_SUPER_TYPES) != 0) { - if (prev) - buffer.append(" | "); //$NON-NLS-1$ - buffer.append("SUPER TYPES CHANGED"); //$NON-NLS-1$ - prev = true; - } - if ((changeFlags & IJavaElementDelta.F_FINE_GRAINED) != 0) { - if (prev) - buffer.append(" | "); //$NON-NLS-1$ - buffer.append("FINE GRAINED"); //$NON-NLS-1$ - prev = true; - } - buffer.append("}"); //$NON-NLS-1$ - IJavaElementDelta[] children = getAffectedChildren(); - if (children != null) { - for (int i = 0; i < children.length; ++i) { - buffer.append("\n"); //$NON-NLS-1$ - buffer.append(((JavaElementDelta) children[i]).toDebugString(depth + 1)); - } - } - for (int i = 0; i < resourceDeltasCounter; i++) { - buffer.append("\n");//$NON-NLS-1$ - for (int j = 0; j < depth+1; j++) { - buffer.append('\t'); } - IResourceDelta resourceDelta = resourceDeltas[i]; - buffer.append(resourceDelta.toString()); - buffer.append("["); //$NON-NLS-1$ - switch (resourceDelta.getKind()) { - case IResourceDelta.ADDED : + buffer.append("]: {"); //$NON-NLS-1$ + int changeFlags = getFlags(); + boolean prev = false; + if ((changeFlags & IJavaElementDelta.F_CHILDREN) != 0) { + if (prev) + buffer.append(" | "); //$NON-NLS-1$ + buffer.append("CHILDREN"); //$NON-NLS-1$ + prev = true; + } + if ((changeFlags & IJavaElementDelta.F_CONTENT) != 0) { + if (prev) + buffer.append(" | "); //$NON-NLS-1$ + buffer.append("CONTENT"); //$NON-NLS-1$ + prev = true; + } + if ((changeFlags & IJavaElementDelta.F_MOVED_FROM) != 0) { + if (prev) + buffer.append(" | "); //$NON-NLS-1$ + buffer + .append("MOVED_FROM(" + ((JavaElement) getMovedFromElement()).toStringWithAncestors() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ + prev = true; + } + if ((changeFlags & IJavaElementDelta.F_MOVED_TO) != 0) { + if (prev) + buffer.append(" | "); //$NON-NLS-1$ + buffer + .append("MOVED_TO(" + ((JavaElement) getMovedToElement()).toStringWithAncestors() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ + prev = true; + } + if ((changeFlags & IJavaElementDelta.F_ADDED_TO_CLASSPATH) != 0) { + if (prev) + buffer.append(" | "); //$NON-NLS-1$ + buffer.append("ADDED TO CLASSPATH"); //$NON-NLS-1$ + prev = true; + } + if ((changeFlags & IJavaElementDelta.F_REMOVED_FROM_CLASSPATH) != 0) { + if (prev) + buffer.append(" | "); //$NON-NLS-1$ + buffer.append("REMOVED FROM CLASSPATH"); //$NON-NLS-1$ + prev = true; + } + if ((changeFlags & IJavaElementDelta.F_REORDER) != 0) { + if (prev) + buffer.append(" | "); //$NON-NLS-1$ + buffer.append("REORDERED"); //$NON-NLS-1$ + prev = true; + } + if ((changeFlags & IJavaElementDelta.F_ARCHIVE_CONTENT_CHANGED) != 0) { + if (prev) + buffer.append(" | "); //$NON-NLS-1$ + buffer.append("ARCHIVE CONTENT CHANGED"); //$NON-NLS-1$ + prev = true; + } + if ((changeFlags & IJavaElementDelta.F_SOURCEATTACHED) != 0) { + if (prev) + buffer.append(" | "); //$NON-NLS-1$ + buffer.append("SOURCE ATTACHED"); //$NON-NLS-1$ + prev = true; + } + if ((changeFlags & IJavaElementDelta.F_SOURCEDETACHED) != 0) { + if (prev) + buffer.append(" | "); //$NON-NLS-1$ + buffer.append("SOURCE DETACHED"); //$NON-NLS-1$ + prev = true; + } + if ((changeFlags & IJavaElementDelta.F_MODIFIERS) != 0) { + if (prev) + buffer.append(" | "); //$NON-NLS-1$ + buffer.append("MODIFIERS CHANGED"); //$NON-NLS-1$ + prev = true; + } + if ((changeFlags & IJavaElementDelta.F_SUPER_TYPES) != 0) { + if (prev) + buffer.append(" | "); //$NON-NLS-1$ + buffer.append("SUPER TYPES CHANGED"); //$NON-NLS-1$ + prev = true; + } + if ((changeFlags & IJavaElementDelta.F_FINE_GRAINED) != 0) { + if (prev) + buffer.append(" | "); //$NON-NLS-1$ + buffer.append("FINE GRAINED"); //$NON-NLS-1$ + prev = true; + } + buffer.append("}"); //$NON-NLS-1$ + IJavaElementDelta[] children = getAffectedChildren(); + if (children != null) { + for (int i = 0; i < children.length; ++i) { + buffer.append("\n"); //$NON-NLS-1$ + buffer.append(((JavaElementDelta) children[i]) + .toDebugString(depth + 1)); + } + } + for (int i = 0; i < resourceDeltasCounter; i++) { + buffer.append("\n");//$NON-NLS-1$ + for (int j = 0; j < depth + 1; j++) { + buffer.append('\t'); + } + IResourceDelta resourceDelta = resourceDeltas[i]; + buffer.append(resourceDelta.toString()); + buffer.append("["); //$NON-NLS-1$ + switch (resourceDelta.getKind()) { + case IResourceDelta.ADDED: buffer.append('+'); break; - case IResourceDelta.REMOVED : + case IResourceDelta.REMOVED: buffer.append('-'); break; - case IResourceDelta.CHANGED : + case IResourceDelta.CHANGED: buffer.append('*'); break; - default : + default: buffer.append('?'); break; + } + buffer.append("]"); //$NON-NLS-1$ } - buffer.append("]"); //$NON-NLS-1$ + return buffer.toString(); + } + + /** + * Returns a string representation of this delta's structure suitable for + * debug purposes. + */ + public String toString() { + return toDebugString(0); } - return buffer.toString(); -} -/** - * Returns a string representation of this delta's - * structure suitable for debug purposes. - */ -public String toString() { - return toDebugString(0); -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElementDeltaBuilder.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElementDeltaBuilder.java index 0376079..226e795 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElementDeltaBuilder.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElementDeltaBuilder.java @@ -21,17 +21,14 @@ import net.sourceforge.phpdt.core.IParent; import net.sourceforge.phpdt.core.JavaModelException; import net.sourceforge.phpdt.core.compiler.CharOperation; - /** - * A java element delta biulder creates a java element delta on - * a java element between the version of the java element - * at the time the comparator was created and the current version - * of the java element. - * - * It performs this operation by locally caching the contents of - * the java element when it is created. When the method - * createDeltas() is called, it creates a delta over the cached - * contents and the new contents. + * A java element delta biulder creates a java element delta on a java element + * between the version of the java element at the time the comparator was + * created and the current version of the java element. + * + * It performs this operation by locally caching the contents of the java + * element when it is created. When the method createDeltas() is called, it + * creates a delta over the cached contents and the new contents. */ public class JavaElementDeltaBuilder { /** @@ -73,12 +70,13 @@ public class JavaElementDeltaBuilder { * List of removed elements */ ArrayList removed; - + /** * Doubly linked list item */ class ListItem { public IJavaElement previous; + public IJavaElement next; public ListItem(IJavaElement previous, IJavaElement next) { @@ -86,324 +84,362 @@ public class JavaElementDeltaBuilder { this.next = next; } } -/** - * Creates a java element comparator on a java element - * looking as deep as necessary. - */ -public JavaElementDeltaBuilder(IJavaElement javaElement) { - this.javaElement = javaElement; - this.initialize(); - this.recordElementInfo( - javaElement, - (JavaModel)this.javaElement.getJavaModel(), - 0); -} -/** - * Creates a java element comparator on a java element - * looking only 'maxDepth' levels deep. - */ -public JavaElementDeltaBuilder(IJavaElement javaElement, int maxDepth) { - this.javaElement = javaElement; - this.maxDepth = maxDepth; - this.initialize(); - this.recordElementInfo( - javaElement, - (JavaModel)this.javaElement.getJavaModel(), - 0); -} -/** - * Repairs the positioning information - * after an element has been added - */ -private void added(IJavaElement element) { - this.added.add(element); - ListItem current = this.getNewPosition(element); - ListItem previous = null, next = null; - if (current.previous != null) - previous = this.getNewPosition(current.previous); - if (current.next != null) - next = this.getNewPosition(current.next); - if (previous != null) - previous.next = current.next; - if (next != null) - next.previous = current.previous; -} -/** - * Builds the java element deltas between the old content of the compilation - * unit and its new content. - */ -public void buildDeltas() { - this.recordNewPositions(this.javaElement, 0); - this.findAdditions(this.javaElement, 0); - this.findDeletions(); - this.findChangesInPositioning(this.javaElement, 0); - this.trimDelta(this.delta); - if (this.delta.getAffectedChildren().length == 0) { - // this is a fine grained but not children affected -> mark as content changed - this.delta.contentChanged(); + + /** + * Creates a java element comparator on a java element looking as deep as + * necessary. + */ + public JavaElementDeltaBuilder(IJavaElement javaElement) { + this.javaElement = javaElement; + this.initialize(); + this.recordElementInfo(javaElement, (JavaModel) this.javaElement + .getJavaModel(), 0); } -} -/** - * Finds elements which have been added or changed. - */ -private void findAdditions(IJavaElement newElement, int depth) { - JavaElementInfo oldInfo = this.getElementInfo(newElement); - if (oldInfo == null && depth < this.maxDepth) { - this.delta.added(newElement); - added(newElement); - } else { - this.removeElementInfo(newElement); + + /** + * Creates a java element comparator on a java element looking only + * 'maxDepth' levels deep. + */ + public JavaElementDeltaBuilder(IJavaElement javaElement, int maxDepth) { + this.javaElement = javaElement; + this.maxDepth = maxDepth; + this.initialize(); + this.recordElementInfo(javaElement, (JavaModel) this.javaElement + .getJavaModel(), 0); } - - if (depth >= this.maxDepth) { - // mark element as changed - this.delta.changed(newElement, IJavaElementDelta.F_CONTENT); - return; + + /** + * Repairs the positioning information after an element has been added + */ + private void added(IJavaElement element) { + this.added.add(element); + ListItem current = this.getNewPosition(element); + ListItem previous = null, next = null; + if (current.previous != null) + previous = this.getNewPosition(current.previous); + if (current.next != null) + next = this.getNewPosition(current.next); + if (previous != null) + previous.next = current.next; + if (next != null) + next.previous = current.previous; } - JavaElementInfo newInfo = null; - try { - newInfo = (JavaElementInfo)((JavaElement)newElement).getElementInfo(); - } catch (JavaModelException npe) { - return; + /** + * Builds the java element deltas between the old content of the compilation + * unit and its new content. + */ + public void buildDeltas() { + this.recordNewPositions(this.javaElement, 0); + this.findAdditions(this.javaElement, 0); + this.findDeletions(); + this.findChangesInPositioning(this.javaElement, 0); + this.trimDelta(this.delta); + if (this.delta.getAffectedChildren().length == 0) { + // this is a fine grained but not children affected -> mark as + // content changed + this.delta.contentChanged(); + } } - - this.findContentChange(oldInfo, newInfo, newElement); - - if (oldInfo != null && newElement instanceof IParent) { - - IJavaElement[] children = newInfo.getChildren(); - if (children != null) { - int length = children.length; - for(int i = 0; i < length; i++) { - this.findAdditions(children[i], depth + 1); + + /** + * Finds elements which have been added or changed. + */ + private void findAdditions(IJavaElement newElement, int depth) { + JavaElementInfo oldInfo = this.getElementInfo(newElement); + if (oldInfo == null && depth < this.maxDepth) { + this.delta.added(newElement); + added(newElement); + } else { + this.removeElementInfo(newElement); + } + + if (depth >= this.maxDepth) { + // mark element as changed + this.delta.changed(newElement, IJavaElementDelta.F_CONTENT); + return; + } + + JavaElementInfo newInfo = null; + try { + newInfo = (JavaElementInfo) ((JavaElement) newElement) + .getElementInfo(); + } catch (JavaModelException npe) { + return; + } + + this.findContentChange(oldInfo, newInfo, newElement); + + if (oldInfo != null && newElement instanceof IParent) { + + IJavaElement[] children = newInfo.getChildren(); + if (children != null) { + int length = children.length; + for (int i = 0; i < length; i++) { + this.findAdditions(children[i], depth + 1); + } } - } + } } -} -/** - * Looks for changed positioning of elements. - */ -private void findChangesInPositioning(IJavaElement element, int depth) { - if (depth >= this.maxDepth || this.added.contains(element) || this.removed.contains(element)) - return; - - if (!isPositionedCorrectly(element)) { - this.delta.changed(element, IJavaElementDelta.F_REORDER); - } - - if (element instanceof IParent) { - JavaElementInfo info = null; - try { - info = (JavaElementInfo)((JavaElement)element).getElementInfo(); - } catch (JavaModelException npe) { + + /** + * Looks for changed positioning of elements. + */ + private void findChangesInPositioning(IJavaElement element, int depth) { + if (depth >= this.maxDepth || this.added.contains(element) + || this.removed.contains(element)) return; + + if (!isPositionedCorrectly(element)) { + this.delta.changed(element, IJavaElementDelta.F_REORDER); } - IJavaElement[] children = info.getChildren(); - if (children != null) { - int length = children.length; - for(int i = 0; i < length; i++) { - this.findChangesInPositioning(children[i], depth + 1); + if (element instanceof IParent) { + JavaElementInfo info = null; + try { + info = (JavaElementInfo) ((JavaElement) element) + .getElementInfo(); + } catch (JavaModelException npe) { + return; + } + + IJavaElement[] children = info.getChildren(); + if (children != null) { + int length = children.length; + for (int i = 0; i < length; i++) { + this.findChangesInPositioning(children[i], depth + 1); + } } - } + } } -} -/** - * The elements are equivalent, but might have content changes. - */ -private void findContentChange(JavaElementInfo oldInfo, JavaElementInfo newInfo, IJavaElement newElement) { - if (oldInfo instanceof MemberElementInfo && newInfo instanceof MemberElementInfo) { - if (((MemberElementInfo)oldInfo).getModifiers() != ((MemberElementInfo)newInfo).getModifiers()) { - this.delta.changed(newElement, IJavaElementDelta.F_MODIFIERS); - } else if (oldInfo instanceof SourceMethodElementInfo && newInfo instanceof SourceMethodElementInfo) { - if (!CharOperation.equals( - ((SourceMethodElementInfo)oldInfo).getReturnTypeName(), - ((SourceMethodElementInfo)newInfo).getReturnTypeName())) { - this.delta.changed(newElement, IJavaElementDelta.F_CONTENT); + + /** + * The elements are equivalent, but might have content changes. + */ + private void findContentChange(JavaElementInfo oldInfo, + JavaElementInfo newInfo, IJavaElement newElement) { + if (oldInfo instanceof MemberElementInfo + && newInfo instanceof MemberElementInfo) { + if (((MemberElementInfo) oldInfo).getModifiers() != ((MemberElementInfo) newInfo) + .getModifiers()) { + this.delta.changed(newElement, IJavaElementDelta.F_MODIFIERS); + } else if (oldInfo instanceof SourceMethodElementInfo + && newInfo instanceof SourceMethodElementInfo) { + if (!CharOperation + .equals(((SourceMethodElementInfo) oldInfo) + .getReturnTypeName(), + ((SourceMethodElementInfo) newInfo) + .getReturnTypeName())) { + this.delta.changed(newElement, IJavaElementDelta.F_CONTENT); + } + } else if (oldInfo instanceof SourceFieldElementInfo + && newInfo instanceof SourceFieldElementInfo) { + if (!CharOperation.equals(((SourceFieldElementInfo) oldInfo) + .getTypeName(), ((SourceFieldElementInfo) newInfo) + .getTypeName())) { + this.delta.changed(newElement, IJavaElementDelta.F_CONTENT); + } } - } else if (oldInfo instanceof SourceFieldElementInfo && newInfo instanceof SourceFieldElementInfo) { - if (!CharOperation.equals( - ((SourceFieldElementInfo)oldInfo).getTypeName(), - ((SourceFieldElementInfo)newInfo).getTypeName())) { - this.delta.changed(newElement, IJavaElementDelta.F_CONTENT); + } + if (oldInfo instanceof SourceTypeElementInfo + && newInfo instanceof SourceTypeElementInfo) { + SourceTypeElementInfo oldSourceTypeInfo = (SourceTypeElementInfo) oldInfo; + SourceTypeElementInfo newSourceTypeInfo = (SourceTypeElementInfo) newInfo; + if (!CharOperation.equals(oldSourceTypeInfo.getSuperclassName(), + newSourceTypeInfo.getSuperclassName()) + || !CharOperation.equals(oldSourceTypeInfo + .getInterfaceNames(), newSourceTypeInfo + .getInterfaceNames())) { + this.delta.changed(newElement, IJavaElementDelta.F_SUPER_TYPES); } } } - if (oldInfo instanceof SourceTypeElementInfo && newInfo instanceof SourceTypeElementInfo) { - SourceTypeElementInfo oldSourceTypeInfo = (SourceTypeElementInfo)oldInfo; - SourceTypeElementInfo newSourceTypeInfo = (SourceTypeElementInfo)newInfo; - if (!CharOperation.equals(oldSourceTypeInfo.getSuperclassName(), newSourceTypeInfo.getSuperclassName()) - || !CharOperation.equals(oldSourceTypeInfo.getInterfaceNames(), newSourceTypeInfo.getInterfaceNames())) { - this.delta.changed(newElement, IJavaElementDelta.F_SUPER_TYPES); + + /** + * Adds removed deltas for any handles left in the table + */ + private void findDeletions() { + Iterator iter = this.infos.keySet().iterator(); + while (iter.hasNext()) { + IJavaElement element = (IJavaElement) iter.next(); + this.delta.removed(element); + this.removed(element); } } -} -/** - * Adds removed deltas for any handles left in the table - */ -private void findDeletions() { - Iterator iter = this.infos.keySet().iterator(); - while(iter.hasNext()) { - IJavaElement element = (IJavaElement)iter.next(); - this.delta.removed(element); - this.removed(element); + + private JavaElementInfo getElementInfo(IJavaElement element) { + return (JavaElementInfo) this.infos.get(element); } -} -private JavaElementInfo getElementInfo(IJavaElement element) { - return (JavaElementInfo)this.infos.get(element); -} -private ListItem getNewPosition(IJavaElement element) { - return (ListItem)this.newPositions.get(element); -} -private ListItem getOldPosition(IJavaElement element) { - return (ListItem)this.oldPositions.get(element); -} -private void initialize() { - this.infos = new HashMap(20); - this.oldPositions = new HashMap(20); - this.newPositions = new HashMap(20); - this.putOldPosition(this.javaElement, new ListItem(null, null)); - this.putNewPosition(this.javaElement, new ListItem(null, null)); - this.delta = new JavaElementDelta(javaElement); - - // if building a delta on a compilation unit or below, - // it's a fine grained delta - if (javaElement.getElementType() >= IJavaElement.COMPILATION_UNIT) { - this.delta.fineGrained(); + + private ListItem getNewPosition(IJavaElement element) { + return (ListItem) this.newPositions.get(element); } - - this.added = new ArrayList(5); - this.removed = new ArrayList(5); -} -/** - * Inserts position information for the elements into the new or old positions table - */ -private void insertPositions(IJavaElement[] elements, boolean isNew) { - int length = elements.length; - IJavaElement previous = null, current = null, next = (length > 0) ? elements[0] : null; - for(int i = 0; i < length; i++) { - previous = current; - current = next; - next = (i + 1 < length) ? elements[i + 1] : null; - if (isNew) { - this.putNewPosition(current, new ListItem(previous, next)); + + private ListItem getOldPosition(IJavaElement element) { + return (ListItem) this.oldPositions.get(element); + } + + private void initialize() { + this.infos = new HashMap(20); + this.oldPositions = new HashMap(20); + this.newPositions = new HashMap(20); + this.putOldPosition(this.javaElement, new ListItem(null, null)); + this.putNewPosition(this.javaElement, new ListItem(null, null)); + this.delta = new JavaElementDelta(javaElement); + + // if building a delta on a compilation unit or below, + // it's a fine grained delta + if (javaElement.getElementType() >= IJavaElement.COMPILATION_UNIT) { + this.delta.fineGrained(); + } + + this.added = new ArrayList(5); + this.removed = new ArrayList(5); + } + + /** + * Inserts position information for the elements into the new or old + * positions table + */ + private void insertPositions(IJavaElement[] elements, boolean isNew) { + int length = elements.length; + IJavaElement previous = null, current = null, next = (length > 0) ? elements[0] + : null; + for (int i = 0; i < length; i++) { + previous = current; + current = next; + next = (i + 1 < length) ? elements[i + 1] : null; + if (isNew) { + this.putNewPosition(current, new ListItem(previous, next)); + } else { + this.putOldPosition(current, new ListItem(previous, next)); + } + } + } + + /** + * Returns whether the elements position has not changed. + */ + private boolean isPositionedCorrectly(IJavaElement element) { + ListItem oldListItem = this.getOldPosition(element); + if (oldListItem == null) + return false; + + ListItem newListItem = this.getNewPosition(element); + if (newListItem == null) + return false; + + IJavaElement oldPrevious = oldListItem.previous; + IJavaElement newPrevious = newListItem.previous; + if (oldPrevious == null) { + return newPrevious == null; } else { - this.putOldPosition(current, new ListItem(previous, next)); + return oldPrevious.equals(newPrevious); } } -} -/** - * Returns whether the elements position has not changed. - */ -private boolean isPositionedCorrectly(IJavaElement element) { - ListItem oldListItem = this.getOldPosition(element); - if (oldListItem == null) return false; - - ListItem newListItem = this.getNewPosition(element); - if (newListItem == null) return false; - - IJavaElement oldPrevious = oldListItem.previous; - IJavaElement newPrevious = newListItem.previous; - if (oldPrevious == null) { - return newPrevious == null; - } else { - return oldPrevious.equals(newPrevious); + + private void putElementInfo(IJavaElement element, JavaElementInfo info) { + this.infos.put(element, info); } -} -private void putElementInfo(IJavaElement element, JavaElementInfo info) { - this.infos.put(element, info); -} -private void putNewPosition(IJavaElement element, ListItem position) { - this.newPositions.put(element, position); -} -private void putOldPosition(IJavaElement element, ListItem position) { - this.oldPositions.put(element, position); -} -/** - * Records this elements info, and attempts - * to record the info for the children. - */ -private void recordElementInfo(IJavaElement element, JavaModel model, int depth) { - if (depth >= this.maxDepth) { - return; + + private void putNewPosition(IJavaElement element, ListItem position) { + this.newPositions.put(element, position); } - JavaElementInfo info = null;//(JavaElementInfo)JavaModelManager.getJavaModelManager().getInfo(element); - if (info == null) // no longer in the java model. - return; - this.putElementInfo(element, info); - - if (element instanceof IParent) { - IJavaElement[] children = info.getChildren(); - if (children != null) { - insertPositions(children, false); - for(int i = 0, length = children.length; i < length; i++) - recordElementInfo(children[i], model, depth + 1); - } + + private void putOldPosition(IJavaElement element, ListItem position) { + this.oldPositions.put(element, position); } -} -/** - * Fills the newPositions hashtable with the new position information - */ -private void recordNewPositions(IJavaElement newElement, int depth) { - if (depth < this.maxDepth && newElement instanceof IParent) { - JavaElementInfo info = null; - try { - info = (JavaElementInfo)((JavaElement)newElement).getElementInfo(); - } catch (JavaModelException npe) { + + /** + * Records this elements info, and attempts to record the info for the + * children. + */ + private void recordElementInfo(IJavaElement element, JavaModel model, + int depth) { + if (depth >= this.maxDepth) { return; } + JavaElementInfo info = null;// (JavaElementInfo)JavaModelManager.getJavaModelManager().getInfo(element); + if (info == null) // no longer in the java model. + return; + this.putElementInfo(element, info); - IJavaElement[] children = info.getChildren(); - if (children != null) { - insertPositions(children, true); - for(int i = 0, length = children.length; i < length; i++) { - recordNewPositions(children[i], depth + 1); + if (element instanceof IParent) { + IJavaElement[] children = info.getChildren(); + if (children != null) { + insertPositions(children, false); + for (int i = 0, length = children.length; i < length; i++) + recordElementInfo(children[i], model, depth + 1); } } } -} -/** - * Repairs the positioning information - * after an element has been removed - */ -private void removed(IJavaElement element) { - this.removed.add(element); - ListItem current = this.getOldPosition(element); - ListItem previous = null, next = null; - if (current.previous != null) - previous = this.getOldPosition(current.previous); - if (current.next != null) - next = this.getOldPosition(current.next); - if (previous != null) - previous.next = current.next; - if (next != null) - next.previous = current.previous; - -} -private void removeElementInfo(IJavaElement element) { - this.infos.remove(element); -} -public String toString() { - StringBuffer buffer = new StringBuffer(); - buffer.append("Built delta:\n"); //$NON-NLS-1$ - buffer.append(this.delta.toString()); - return buffer.toString(); -} -/** - * Trims deletion deltas to only report the highest level of deletion - */ -private void trimDelta(JavaElementDelta delta) { - if (delta.getKind() == IJavaElementDelta.REMOVED) { - IJavaElementDelta[] children = delta.getAffectedChildren(); - for(int i = 0, length = children.length; i < length; i++) { - delta.removeAffectedChild((JavaElementDelta)children[i]); + + /** + * Fills the newPositions hashtable with the new position information + */ + private void recordNewPositions(IJavaElement newElement, int depth) { + if (depth < this.maxDepth && newElement instanceof IParent) { + JavaElementInfo info = null; + try { + info = (JavaElementInfo) ((JavaElement) newElement) + .getElementInfo(); + } catch (JavaModelException npe) { + return; + } + + IJavaElement[] children = info.getChildren(); + if (children != null) { + insertPositions(children, true); + for (int i = 0, length = children.length; i < length; i++) { + recordNewPositions(children[i], depth + 1); + } + } } - } else { - IJavaElementDelta[] children = delta.getAffectedChildren(); - for(int i = 0, length = children.length; i < length; i++) { - trimDelta((JavaElementDelta)children[i]); + } + + /** + * Repairs the positioning information after an element has been removed + */ + private void removed(IJavaElement element) { + this.removed.add(element); + ListItem current = this.getOldPosition(element); + ListItem previous = null, next = null; + if (current.previous != null) + previous = this.getOldPosition(current.previous); + if (current.next != null) + next = this.getOldPosition(current.next); + if (previous != null) + previous.next = current.next; + if (next != null) + next.previous = current.previous; + + } + + private void removeElementInfo(IJavaElement element) { + this.infos.remove(element); + } + + public String toString() { + StringBuffer buffer = new StringBuffer(); + buffer.append("Built delta:\n"); //$NON-NLS-1$ + buffer.append(this.delta.toString()); + return buffer.toString(); + } + + /** + * Trims deletion deltas to only report the highest level of deletion + */ + private void trimDelta(JavaElementDelta delta) { + if (delta.getKind() == IJavaElementDelta.REMOVED) { + IJavaElementDelta[] children = delta.getAffectedChildren(); + for (int i = 0, length = children.length; i < length; i++) { + delta.removeAffectedChild((JavaElementDelta) children[i]); + } + } else { + IJavaElementDelta[] children = delta.getAffectedChildren(); + for (int i = 0, length = children.length; i < length; i++) { + trimDelta((JavaElementDelta) children[i]); + } } } } -} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElementInfo.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElementInfo.java index 532ddd3..f8c3b01 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElementInfo.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElementInfo.java @@ -12,27 +12,26 @@ package net.sourceforge.phpdt.internal.core; import net.sourceforge.phpdt.core.IJavaElement; - - /** - * Holds cached structure and properties for a Java element. - * Subclassed to carry properties for specific kinds of elements. + * Holds cached structure and properties for a Java element. Subclassed to carry + * properties for specific kinds of elements. */ -/* package */ class JavaElementInfo { +/* package */class JavaElementInfo { /** - * Collection of handles of immediate children of this - * object. This is an empty array if this element has - * no children. + * Collection of handles of immediate children of this object. This is an + * empty array if this element has no children. */ protected IJavaElement[] fChildren; /** * Shared empty collection used for efficiency. */ - protected static IJavaElement[] fgEmptyChildren = new IJavaElement[]{}; + protected static IJavaElement[] fgEmptyChildren = new IJavaElement[] {}; + /** * Is the structure of this element known + * * @see IJavaElement#isStructureKnown() */ protected boolean fIsStructureKnown = false; @@ -40,64 +39,74 @@ import net.sourceforge.phpdt.core.IJavaElement; /** * Shared empty collection used for efficiency. */ - static Object[] NO_NON_JAVA_RESOURCES = new Object[] {}; + static Object[] NO_NON_JAVA_RESOURCES = new Object[] {}; + protected JavaElementInfo() { fChildren = fgEmptyChildren; } + public void addChild(IJavaElement child) { if (fChildren == fgEmptyChildren) { - setChildren(new IJavaElement[] {child}); + setChildren(new IJavaElement[] { child }); } else { if (!includesChild(child)) { setChildren(growAndAddToArray(fChildren, child)); } } } + public Object clone() { try { return super.clone(); - } - catch (CloneNotSupportedException e) { + } catch (CloneNotSupportedException e) { throw new Error(); } } + public IJavaElement[] getChildren() { return fChildren; } + /** - * Adds the new element to a new array that contains all of the elements of the old array. - * Returns the new array. + * Adds the new element to a new array that contains all of the elements of + * the old array. Returns the new array. */ - protected IJavaElement[] growAndAddToArray(IJavaElement[] array, IJavaElement addition) { + protected IJavaElement[] growAndAddToArray(IJavaElement[] array, + IJavaElement addition) { IJavaElement[] old = array; array = new IJavaElement[old.length + 1]; System.arraycopy(old, 0, array, 0, old.length); array[old.length] = addition; return array; } + /** * Returns true if this child is in my children collection */ protected boolean includesChild(IJavaElement child) { - - for (int i= 0; i < fChildren.length; i++) { + + for (int i = 0; i < fChildren.length; i++) { if (fChildren[i].equals(child)) { return true; } } return false; } + /** * @see IJavaElement#isStructureKnown() */ public boolean isStructureKnown() { return fIsStructureKnown; } + /** - * Returns an array with all the same elements as the specified array except for - * the element to remove. Assumes that the deletion is contained in the array. + * Returns an array with all the same elements as the specified array except + * for the element to remove. Assumes that the deletion is contained in the + * array. */ - protected IJavaElement[] removeAndShrinkArray(IJavaElement[] array, IJavaElement deletion) { + protected IJavaElement[] removeAndShrinkArray(IJavaElement[] array, + IJavaElement deletion) { IJavaElement[] old = array; array = new IJavaElement[old.length - 1]; int j = 0; @@ -112,16 +121,20 @@ import net.sourceforge.phpdt.core.IJavaElement; } return array; } + public void removeChild(IJavaElement child) { if (includesChild(child)) { setChildren(removeAndShrinkArray(fChildren, child)); } } + public void setChildren(IJavaElement[] children) { fChildren = children; } + /** * Sets whether the structure of this element known + * * @see IJavaElement#isStructureKnown() */ public void setIsStructureKnown(boolean newIsStructureKnown) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElementRequestor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElementRequestor.java index 88201b0..00fa191 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElementRequestor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElementRequestor.java @@ -23,203 +23,220 @@ import net.sourceforge.phpdt.core.IType; public class JavaElementRequestor implements IJavaElementRequestor { /** - * True if this requestor no longer wants to receive - * results from its IRequestorNameLookup. + * True if this requestor no longer wants to receive results from its + * IRequestorNameLookup. */ - protected boolean fCanceled= false; - + protected boolean fCanceled = false; + /** - * A collection of the resulting fields, or null - * if no field results have been received. + * A collection of the resulting fields, or null if no field + * results have been received. */ - protected ArrayList fFields= null; + protected ArrayList fFields = null; /** - * A collection of the resulting initializers, or null - * if no initializer results have been received. + * A collection of the resulting initializers, or null if no + * initializer results have been received. */ - protected ArrayList fInitializers= null; + protected ArrayList fInitializers = null; /** - * A collection of the resulting member types, or null - * if no member type results have been received. + * A collection of the resulting member types, or null if no + * member type results have been received. */ - protected ArrayList fMemberTypes= null; + protected ArrayList fMemberTypes = null; /** - * A collection of the resulting methods, or null - * if no method results have been received. + * A collection of the resulting methods, or null if no + * method results have been received. */ - protected ArrayList fMethods= null; + protected ArrayList fMethods = null; /** * A collection of the resulting package fragments, or null * if no package fragment results have been received. */ - protected ArrayList fPackageFragments= null; + protected ArrayList fPackageFragments = null; /** - * A collection of the resulting types, or null - * if no type results have been received. + * A collection of the resulting types, or null if no type + * results have been received. */ - protected ArrayList fTypes= null; + protected ArrayList fTypes = null; /** * Empty arrays used for efficiency */ - protected static IField[] fgEmptyFieldArray= new IField[0]; -// protected static IInitializer[] fgEmptyInitializerArray= new IInitializer[0]; - protected static IType[] fgEmptyTypeArray= new IType[0]; - protected static IPackageFragment[] fgEmptyPackageFragmentArray= new IPackageFragment[0]; - protected static IMethod[] fgEmptyMethodArray= new IMethod[0]; -/** - * @see IJavaElementRequestor - */ -public void acceptField(IField field) { - if (fFields == null) { - fFields= new ArrayList(); + protected static IField[] fgEmptyFieldArray = new IField[0]; + + // protected static IInitializer[] fgEmptyInitializerArray= new + // IInitializer[0]; + protected static IType[] fgEmptyTypeArray = new IType[0]; + + protected static IPackageFragment[] fgEmptyPackageFragmentArray = new IPackageFragment[0]; + + protected static IMethod[] fgEmptyMethodArray = new IMethod[0]; + + /** + * @see IJavaElementRequestor + */ + public void acceptField(IField field) { + if (fFields == null) { + fFields = new ArrayList(); + } + fFields.add(field); } - fFields.add(field); -} -/** - * @see IJavaElementRequestor - */ -//public void acceptInitializer(IInitializer initializer) { -// if (fInitializers == null) { -// fInitializers= new ArrayList(); -// } -// fInitializers.add(initializer); -//} -/** - * @see IJavaElementRequestor - */ -public void acceptMemberType(IType type) { - if (fMemberTypes == null) { - fMemberTypes= new ArrayList(); + + /** + * @see IJavaElementRequestor + */ + // public void acceptInitializer(IInitializer initializer) { + // if (fInitializers == null) { + // fInitializers= new ArrayList(); + // } + // fInitializers.add(initializer); + // } + /** + * @see IJavaElementRequestor + */ + public void acceptMemberType(IType type) { + if (fMemberTypes == null) { + fMemberTypes = new ArrayList(); + } + fMemberTypes.add(type); } - fMemberTypes.add(type); -} -/** - * @see IJavaElementRequestor - */ -public void acceptMethod(IMethod method) { - if (fMethods == null) { - fMethods = new ArrayList(); + + /** + * @see IJavaElementRequestor + */ + public void acceptMethod(IMethod method) { + if (fMethods == null) { + fMethods = new ArrayList(); + } + fMethods.add(method); } - fMethods.add(method); -} -/** - * @see IJavaElementRequestor - */ -public void acceptPackageFragment(IPackageFragment packageFragment) { - if (fPackageFragments== null) { - fPackageFragments= new ArrayList(); + + /** + * @see IJavaElementRequestor + */ + public void acceptPackageFragment(IPackageFragment packageFragment) { + if (fPackageFragments == null) { + fPackageFragments = new ArrayList(); + } + fPackageFragments.add(packageFragment); } - fPackageFragments.add(packageFragment); -} -/** - * @see IJavaElementRequestor - */ -public void acceptType(IType type) { - if (fTypes == null) { - fTypes= new ArrayList(); + + /** + * @see IJavaElementRequestor + */ + public void acceptType(IType type) { + if (fTypes == null) { + fTypes = new ArrayList(); + } + fTypes.add(type); } - fTypes.add(type); -} -/** - * @see IJavaElementRequestor - */ -public IField[] getFields() { - if (fFields == null) { - return fgEmptyFieldArray; + + /** + * @see IJavaElementRequestor + */ + public IField[] getFields() { + if (fFields == null) { + return fgEmptyFieldArray; + } + int size = fFields.size(); + IField[] results = new IField[size]; + fFields.toArray(results); + return results; } - int size = fFields.size(); - IField[] results = new IField[size]; - fFields.toArray(results); - return results; -} -/** - * @see IJavaElementRequestor - */ -//public IInitializer[] getInitializers() { -// if (fInitializers == null) { -// return fgEmptyInitializerArray; -// } -// int size = fInitializers.size(); -// IInitializer[] results = new IInitializer[size]; -// fInitializers.toArray(results); -// return results; -//} -/** - * @see IJavaElementRequestor - */ -public IType[] getMemberTypes() { - if (fMemberTypes == null) { - return fgEmptyTypeArray; + + /** + * @see IJavaElementRequestor + */ + // public IInitializer[] getInitializers() { + // if (fInitializers == null) { + // return fgEmptyInitializerArray; + // } + // int size = fInitializers.size(); + // IInitializer[] results = new IInitializer[size]; + // fInitializers.toArray(results); + // return results; + // } + /** + * @see IJavaElementRequestor + */ + public IType[] getMemberTypes() { + if (fMemberTypes == null) { + return fgEmptyTypeArray; + } + int size = fMemberTypes.size(); + IType[] results = new IType[size]; + fMemberTypes.toArray(results); + return results; } - int size = fMemberTypes.size(); - IType[] results = new IType[size]; - fMemberTypes.toArray(results); - return results; -} -/** - * @see IJavaElementRequestor - */ -public IMethod[] getMethods() { - if (fMethods == null) { - return fgEmptyMethodArray; + + /** + * @see IJavaElementRequestor + */ + public IMethod[] getMethods() { + if (fMethods == null) { + return fgEmptyMethodArray; + } + int size = fMethods.size(); + IMethod[] results = new IMethod[size]; + fMethods.toArray(results); + return results; } - int size = fMethods.size(); - IMethod[] results = new IMethod[size]; - fMethods.toArray(results); - return results; -} -/** - * @see IJavaElementRequestor - */ -public IPackageFragment[] getPackageFragments() { - if (fPackageFragments== null) { - return fgEmptyPackageFragmentArray; + + /** + * @see IJavaElementRequestor + */ + public IPackageFragment[] getPackageFragments() { + if (fPackageFragments == null) { + return fgEmptyPackageFragmentArray; + } + int size = fPackageFragments.size(); + IPackageFragment[] results = new IPackageFragment[size]; + fPackageFragments.toArray(results); + return results; } - int size = fPackageFragments.size(); - IPackageFragment[] results = new IPackageFragment[size]; - fPackageFragments.toArray(results); - return results; -} -/** - * @see IJavaElementRequestor - */ -public IType[] getTypes() { - if (fTypes== null) { - return fgEmptyTypeArray; + + /** + * @see IJavaElementRequestor + */ + public IType[] getTypes() { + if (fTypes == null) { + return fgEmptyTypeArray; + } + int size = fTypes.size(); + IType[] results = new IType[size]; + fTypes.toArray(results); + return results; + } + + /** + * @see IJavaElementRequestor + */ + public boolean isCanceled() { + return fCanceled; + } + + /** + * Reset the state of this requestor. + */ + public void reset() { + fCanceled = false; + fFields = null; + fInitializers = null; + fMemberTypes = null; + fMethods = null; + fPackageFragments = null; + fTypes = null; + } + + /** + * Sets the #isCanceled state of this requestor to true or false. + */ + public void setCanceled(boolean b) { + fCanceled = b; } - int size = fTypes.size(); - IType[] results = new IType[size]; - fTypes.toArray(results); - return results; -} -/** - * @see IJavaElementRequestor - */ -public boolean isCanceled() { - return fCanceled; -} -/** - * Reset the state of this requestor. - */ -public void reset() { - fCanceled = false; - fFields = null; - fInitializers = null; - fMemberTypes = null; - fMethods = null; - fPackageFragments = null; - fTypes = null; -} -/** - * Sets the #isCanceled state of this requestor to true or false. - */ -public void setCanceled(boolean b) { - fCanceled= b; -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModel.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModel.java index e184748..cdeb0fa 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModel.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModel.java @@ -36,7 +36,6 @@ import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.jface.util.Assert; - /** * Implementation of IJavaModel. The Java Model maintains a cache of * active IJavaProjects in a workspace. A Java Model is specific to a @@ -48,530 +47,602 @@ import org.eclipse.jface.util.Assert; public class JavaModel extends Openable implements IJavaModel { /** - * A set of java.io.Files used as a cache of external jars that - * are known to be existing. - * Note this cache is kept for the whole session. - */ + * A set of java.io.Files used as a cache of external jars that are known to + * be existing. Note this cache is kept for the whole session. + */ public static HashSet existingExternalFiles = new HashSet(); - -/** - * Constructs a new Java Model on the given workspace. - * Note that only one instance of JavaModel handle should ever be created. - * One should only indirect through JavaModelManager#getJavaModel() to get - * access to it. - * - * @exception Error if called more than once - */ -protected JavaModel() throws Error { - super(null, "" /*workspace has empty name*/); //$NON-NLS-1$ -} -protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) /*throws JavaModelException*/ { - - // determine my children - IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); - for (int i = 0, max = projects.length; i < max; i++) { - IProject project = projects[i]; - if (JavaProject.hasJavaNature(project)) { - info.addChild(getJavaProject(project)); + + /** + * Constructs a new Java Model on the given workspace. Note that only one + * instance of JavaModel handle should ever be created. One should only + * indirect through JavaModelManager#getJavaModel() to get access to it. + * + * @exception Error + * if called more than once + */ + protected JavaModel() throws Error { + super(null, "" /* workspace has empty name */); //$NON-NLS-1$ + } + + protected boolean buildStructure(OpenableElementInfo info, + IProgressMonitor pm, Map newElements, IResource underlyingResource) /* + * throws + * JavaModelException + */{ + + // determine my children + IProject[] projects = ResourcesPlugin.getWorkspace().getRoot() + .getProjects(); + for (int i = 0, max = projects.length; i < max; i++) { + IProject project = projects[i]; + if (JavaProject.hasJavaNature(project)) { + info.addChild(getJavaProject(project)); + } } + + newElements.put(this, info); + + return true; } - newElements.put(this, info); - - return true; -} -/* - * @see IJavaModel - */ -public boolean contains(IResource resource) { - switch (resource.getType()) { + /* + * @see IJavaModel + */ + public boolean contains(IResource resource) { + switch (resource.getType()) { case IResource.ROOT: case IResource.PROJECT: return true; - } - // file or folder - IJavaProject[] projects; - try { - projects = this.getJavaProjects(); - } catch (JavaModelException e) { - return false; - } - for (int i = 0, length = projects.length; i < length; i++) { - JavaProject project = (JavaProject)projects[i]; - - if (!project.contains(resource)) { + } + // file or folder + IJavaProject[] projects; + try { + projects = this.getJavaProjects(); + } catch (JavaModelException e) { return false; } + for (int i = 0, length = projects.length; i < length; i++) { + JavaProject project = (JavaProject) projects[i]; + + if (!project.contains(resource)) { + return false; + } + } + return true; } - return true; -} -/** - * @see IJavaModel - */ -public void copy(IJavaElement[] elements, IJavaElement[] containers, IJavaElement[] siblings, String[] renamings, boolean force, IProgressMonitor monitor) throws JavaModelException { - if (elements != null && elements.length > 0 && elements[0] != null && elements[0].getElementType() < IJavaElement.TYPE) { - runOperation(new CopyResourceElementsOperation(elements, containers, force), elements, siblings, renamings, monitor); - } else { - runOperation(new CopyElementsOperation(elements, containers, force), elements, siblings, renamings, monitor); + + /** + * @see IJavaModel + */ + public void copy(IJavaElement[] elements, IJavaElement[] containers, + IJavaElement[] siblings, String[] renamings, boolean force, + IProgressMonitor monitor) throws JavaModelException { + if (elements != null && elements.length > 0 && elements[0] != null + && elements[0].getElementType() < IJavaElement.TYPE) { + runOperation(new CopyResourceElementsOperation(elements, + containers, force), elements, siblings, renamings, monitor); + } else { + runOperation( + new CopyElementsOperation(elements, containers, force), + elements, siblings, renamings, monitor); + } } -} -/** - * Returns a new element info for this element. - */ -protected Object createElementInfo() { - return new JavaModelInfo(); -} -/** - * @see IJavaModel - */ -public void delete(IJavaElement[] elements, boolean force, IProgressMonitor monitor) throws JavaModelException { - if (elements != null && elements.length > 0 && elements[0] != null && elements[0].getElementType() < IJavaElement.TYPE) { - runOperation(new DeleteResourceElementsOperation(elements, force), monitor); - } else { - runOperation(new DeleteElementsOperation(elements, force), monitor); + /** + * Returns a new element info for this element. + */ + protected Object createElementInfo() { + return new JavaModelInfo(); } -} -/** - * Finds the given project in the list of the java model's children. - * Returns null if not found. - */ -public IJavaProject findJavaProject(IProject project) { - try { - IJavaProject[] projects = this.getOldJavaProjectsList(); - for (int i = 0, length = projects.length; i < length; i++) { - IJavaProject javaProject = projects[i]; - if (project.equals(javaProject.getProject())) { - return javaProject; + + /** + * @see IJavaModel + */ + public void delete(IJavaElement[] elements, boolean force, + IProgressMonitor monitor) throws JavaModelException { + if (elements != null && elements.length > 0 && elements[0] != null + && elements[0].getElementType() < IJavaElement.TYPE) { + runOperation(new DeleteResourceElementsOperation(elements, force), + monitor); + } else { + runOperation(new DeleteElementsOperation(elements, force), monitor); + } + } + + /** + * Finds the given project in the list of the java model's children. Returns + * null if not found. + */ + public IJavaProject findJavaProject(IProject project) { + try { + IJavaProject[] projects = this.getOldJavaProjectsList(); + for (int i = 0, length = projects.length; i < length; i++) { + IJavaProject javaProject = projects[i]; + if (project.equals(javaProject.getProject())) { + return javaProject; + } } + } catch (JavaModelException e) { } - } catch (JavaModelException e) { + return null; } - return null; -} -/** - * @see IJavaElement - */ -public int getElementType() { - return JAVA_MODEL; -} -/** - * Flushes the cache of external files known to be existing. - */ -public static void flushExternalFileCache() { - existingExternalFiles = new HashSet(); -} -/** - */ -protected boolean generateInfos( - OpenableElementInfo info, - IProgressMonitor pm, - Map newElements, - IResource underlyingResource) throws JavaModelException { - - JavaModelManager.getJavaModelManager().putInfo(this, info); - // determine my children - IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); - for (int i = 0, max = projects.length; i < max; i++) { - IProject project = projects[i]; - if (JavaProject.hasJavaNature(project)) { - info.addChild(getJavaProject(project)); + /** + * @see IJavaElement + */ + public int getElementType() { + return JAVA_MODEL; + } + + /** + * Flushes the cache of external files known to be existing. + */ + public static void flushExternalFileCache() { + existingExternalFiles = new HashSet(); + } + + /** + */ + protected boolean generateInfos(OpenableElementInfo info, + IProgressMonitor pm, Map newElements, IResource underlyingResource) + throws JavaModelException { + + JavaModelManager.getJavaModelManager().putInfo(this, info); + // determine my children + IProject[] projects = ResourcesPlugin.getWorkspace().getRoot() + .getProjects(); + for (int i = 0, max = projects.length; i < max; i++) { + IProject project = projects[i]; + if (JavaProject.hasJavaNature(project)) { + info.addChild(getJavaProject(project)); + } } + return true; } - return true; -} -/** - * Returns the IJavaElement represented by the String - * memento. - * @see getHandleMemento() - */ -//protected IJavaElement getHandleFromMementoForBinaryMembers(String memento, IPackageFragmentRoot root, int rootEnd, int end) throws JavaModelException { -// -// //deal with class file and binary members -// IPackageFragment frag = null; -// if (rootEnd == end - 1) { -// //default package -// frag= root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME); -// } else { -// frag= root.getPackageFragment(memento.substring(rootEnd + 1, end)); -// } -// int oldEnd = end; -// end = memento.indexOf(JavaElement.JEM_TYPE, oldEnd); -// if (end == -1) { -// //we ended with a class file -// return frag.getClassFile(memento.substring(oldEnd + 1)); -// } -// IClassFile cf = frag.getClassFile(memento.substring(oldEnd + 1, end)); -// oldEnd = end; -// end = memento.indexOf(JavaElement.JEM_TYPE, oldEnd); -// oldEnd = end; -// end = memento.indexOf(JavaElement.JEM_FIELD, end); -// if (end != -1) { -// //binary field -// IType type = cf.getType(); -// return type.getField(memento.substring(end + 1)); -// } -// end = memento.indexOf(JavaElement.JEM_METHOD, oldEnd); -// if (end != -1) { -// //binary method -// oldEnd = end; -// IType type = cf.getType(); -// String methodName; -// end = memento.lastIndexOf(JavaElement.JEM_METHOD); -// String[] parameterTypes = null; -// if (end == oldEnd) { -// methodName = memento.substring(end + 1); -// //no parameter types -// parameterTypes = new String[] {}; -// } else { -// String parameters = memento.substring(oldEnd + 1); -// StringTokenizer tokenizer = new StringTokenizer(parameters, new String(new char[] {JavaElement.JEM_METHOD})); -// parameterTypes = new String[tokenizer.countTokens() - 1]; -// methodName= tokenizer.nextToken(); -// int i = 0; -// while (tokenizer.hasMoreTokens()) { -// parameterTypes[i] = tokenizer.nextToken(); -// i++; -// } -// } -// return type.getMethod(methodName, parameterTypes); -// } -// -// //binary type -// return cf.getType(); -//} -/** - * Returns the IPackageFragmentRoot represented by the String - * memento. - * @see getHandleMemento() - */ -//protected IPackageFragmentRoot getHandleFromMementoForRoot(String memento, JavaProject project, int projectEnd, int rootEnd) { -// String rootName = null; -// if (rootEnd == projectEnd - 1) { -// //default root -// rootName = IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH; -// } else { -// rootName = memento.substring(projectEnd + 1, rootEnd); -// } -// return project.getPackageFragmentRoot(new Path(rootName)); -//} -/** - * Returns the IJavaElement represented by the String - * memento. - * @see getHandleMemento() - */ -//protected IJavaElement getHandleFromMementoForSourceMembers(String memento, IPackageFragmentRoot root, int rootEnd, int end) throws JavaModelException { -// -// //deal with compilation units and source members -// IPackageFragment frag = null; -// if (rootEnd == end - 1) { -// //default package -// frag= root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME); -// } else { -// frag= root.getPackageFragment(memento.substring(rootEnd + 1, end)); -// } -// int oldEnd = end; -// end = memento.indexOf(JavaElement.JEM_PACKAGEDECLARATION, end); -// if (end != -1) { -// //package declaration -// ICompilationUnit cu = frag.getCompilationUnit(memento.substring(oldEnd + 1, end)); -// return cu.getPackageDeclaration(memento.substring(end + 1)); -// } -// end = memento.indexOf(JavaElement.JEM_IMPORTDECLARATION, oldEnd); -// if (end != -1) { -// //import declaration -// ICompilationUnit cu = frag.getCompilationUnit(memento.substring(oldEnd + 1, end)); -// return cu.getImport(memento.substring(end + 1)); -// } -// int typeStart = memento.indexOf(JavaElement.JEM_TYPE, oldEnd); -// if (typeStart == -1) { -// //we ended with a compilation unit -// return frag.getCompilationUnit(memento.substring(oldEnd + 1)); -// } -// -// //source members -// ICompilationUnit cu = frag.getCompilationUnit(memento.substring(oldEnd + 1, typeStart)); -// end = memento.indexOf(JavaElement.JEM_FIELD, oldEnd); -// if (end != -1) { -// //source field -// IType type = getHandleFromMementoForSourceType(memento, cu, typeStart, end); -// return type.getField(memento.substring(end + 1)); -// } -// end = memento.indexOf(JavaElement.JEM_METHOD, oldEnd); -// if (end != -1) { -// //source method -// IType type = getHandleFromMementoForSourceType(memento, cu, typeStart, end); -// oldEnd = end; -// String methodName; -// end = memento.lastIndexOf(JavaElement.JEM_METHOD); -// String[] parameterTypes = null; -// if (end == oldEnd) { -// methodName = memento.substring(end + 1); -// //no parameter types -// parameterTypes = new String[] {}; -// } else { -// String parameters = memento.substring(oldEnd + 1); -// StringTokenizer mTokenizer = new StringTokenizer(parameters, new String(new char[] {JavaElement.JEM_METHOD})); -// parameterTypes = new String[mTokenizer.countTokens() - 1]; -// methodName = mTokenizer.nextToken(); -// int i = 0; -// while (mTokenizer.hasMoreTokens()) { -// parameterTypes[i] = mTokenizer.nextToken(); -// i++; -// } -// } -// return type.getMethod(methodName, parameterTypes); -// } -// -// end = memento.indexOf(JavaElement.JEM_INITIALIZER, oldEnd); -// if (end != -1 ) { -// //initializer -// IType type = getHandleFromMementoForSourceType(memento, cu, typeStart, end); -// return type.getInitializer(Integer.parseInt(memento.substring(end + 1))); -// } -// //source type -// return getHandleFromMementoForSourceType(memento, cu, typeStart, memento.length()); -//} -/** - * Returns the IJavaElement represented by the String - * memento. - * @see getHandleMemento() - */ -//protected IType getHandleFromMementoForSourceType(String memento, ICompilationUnit cu, int typeStart, int typeEnd) throws JavaModelException { -// int end = memento.lastIndexOf(JavaElement.JEM_TYPE); -// IType type = null; -// if (end == typeStart) { -// String typeName = memento.substring(typeStart + 1, typeEnd); -// type = cu.getType(typeName); -// -// } else { -// String typeNames = memento.substring(typeStart + 1, typeEnd); -// StringTokenizer tokenizer = new StringTokenizer(typeNames, new String(new char[] {JavaElement.JEM_TYPE})); -// type = cu.getType(tokenizer.nextToken()); -// while (tokenizer.hasMoreTokens()) { -// //deal with inner types -// type= type.getType(tokenizer.nextToken()); -// } -// } -// return type; -//} - - -/* - * @see JavaElement - */ -public IJavaElement getHandleFromMemento(String token, MementoTokenizer memento, WorkingCopyOwner owner) { - switch (token.charAt(0)) { + + /** + * Returns the IJavaElement represented by the + * String memento. + * + * @see getHandleMemento() + */ + // protected IJavaElement getHandleFromMementoForBinaryMembers(String + // memento, IPackageFragmentRoot root, int rootEnd, int end) throws + // JavaModelException { + // + // //deal with class file and binary members + // IPackageFragment frag = null; + // if (rootEnd == end - 1) { + // //default package + // frag= root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME); + // } else { + // frag= root.getPackageFragment(memento.substring(rootEnd + 1, end)); + // } + // int oldEnd = end; + // end = memento.indexOf(JavaElement.JEM_TYPE, oldEnd); + // if (end == -1) { + // //we ended with a class file + // return frag.getClassFile(memento.substring(oldEnd + 1)); + // } + // IClassFile cf = frag.getClassFile(memento.substring(oldEnd + 1, end)); + // oldEnd = end; + // end = memento.indexOf(JavaElement.JEM_TYPE, oldEnd); + // oldEnd = end; + // end = memento.indexOf(JavaElement.JEM_FIELD, end); + // if (end != -1) { + // //binary field + // IType type = cf.getType(); + // return type.getField(memento.substring(end + 1)); + // } + // end = memento.indexOf(JavaElement.JEM_METHOD, oldEnd); + // if (end != -1) { + // //binary method + // oldEnd = end; + // IType type = cf.getType(); + // String methodName; + // end = memento.lastIndexOf(JavaElement.JEM_METHOD); + // String[] parameterTypes = null; + // if (end == oldEnd) { + // methodName = memento.substring(end + 1); + // //no parameter types + // parameterTypes = new String[] {}; + // } else { + // String parameters = memento.substring(oldEnd + 1); + // StringTokenizer tokenizer = new StringTokenizer(parameters, new + // String(new char[] {JavaElement.JEM_METHOD})); + // parameterTypes = new String[tokenizer.countTokens() - 1]; + // methodName= tokenizer.nextToken(); + // int i = 0; + // while (tokenizer.hasMoreTokens()) { + // parameterTypes[i] = tokenizer.nextToken(); + // i++; + // } + // } + // return type.getMethod(methodName, parameterTypes); + // } + // + // //binary type + // return cf.getType(); + // } + /** + * Returns the IPackageFragmentRoot represented by the + * String memento. + * + * @see getHandleMemento() + */ + // protected IPackageFragmentRoot getHandleFromMementoForRoot(String + // memento, JavaProject project, int projectEnd, int rootEnd) { + // String rootName = null; + // if (rootEnd == projectEnd - 1) { + // //default root + // rootName = IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH; + // } else { + // rootName = memento.substring(projectEnd + 1, rootEnd); + // } + // return project.getPackageFragmentRoot(new Path(rootName)); + // } + /** + * Returns the IJavaElement represented by the + * String memento. + * + * @see getHandleMemento() + */ + // protected IJavaElement getHandleFromMementoForSourceMembers(String + // memento, IPackageFragmentRoot root, int rootEnd, int end) throws + // JavaModelException { + // + // //deal with compilation units and source members + // IPackageFragment frag = null; + // if (rootEnd == end - 1) { + // //default package + // frag= root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME); + // } else { + // frag= root.getPackageFragment(memento.substring(rootEnd + 1, end)); + // } + // int oldEnd = end; + // end = memento.indexOf(JavaElement.JEM_PACKAGEDECLARATION, end); + // if (end != -1) { + // //package declaration + // ICompilationUnit cu = frag.getCompilationUnit(memento.substring(oldEnd + + // 1, end)); + // return cu.getPackageDeclaration(memento.substring(end + 1)); + // } + // end = memento.indexOf(JavaElement.JEM_IMPORTDECLARATION, oldEnd); + // if (end != -1) { + // //import declaration + // ICompilationUnit cu = frag.getCompilationUnit(memento.substring(oldEnd + + // 1, end)); + // return cu.getImport(memento.substring(end + 1)); + // } + // int typeStart = memento.indexOf(JavaElement.JEM_TYPE, oldEnd); + // if (typeStart == -1) { + // //we ended with a compilation unit + // return frag.getCompilationUnit(memento.substring(oldEnd + 1)); + // } + // + // //source members + // ICompilationUnit cu = frag.getCompilationUnit(memento.substring(oldEnd + + // 1, typeStart)); + // end = memento.indexOf(JavaElement.JEM_FIELD, oldEnd); + // if (end != -1) { + // //source field + // IType type = getHandleFromMementoForSourceType(memento, cu, typeStart, + // end); + // return type.getField(memento.substring(end + 1)); + // } + // end = memento.indexOf(JavaElement.JEM_METHOD, oldEnd); + // if (end != -1) { + // //source method + // IType type = getHandleFromMementoForSourceType(memento, cu, typeStart, + // end); + // oldEnd = end; + // String methodName; + // end = memento.lastIndexOf(JavaElement.JEM_METHOD); + // String[] parameterTypes = null; + // if (end == oldEnd) { + // methodName = memento.substring(end + 1); + // //no parameter types + // parameterTypes = new String[] {}; + // } else { + // String parameters = memento.substring(oldEnd + 1); + // StringTokenizer mTokenizer = new StringTokenizer(parameters, new + // String(new char[] {JavaElement.JEM_METHOD})); + // parameterTypes = new String[mTokenizer.countTokens() - 1]; + // methodName = mTokenizer.nextToken(); + // int i = 0; + // while (mTokenizer.hasMoreTokens()) { + // parameterTypes[i] = mTokenizer.nextToken(); + // i++; + // } + // } + // return type.getMethod(methodName, parameterTypes); + // } + // + // end = memento.indexOf(JavaElement.JEM_INITIALIZER, oldEnd); + // if (end != -1 ) { + // //initializer + // IType type = getHandleFromMementoForSourceType(memento, cu, typeStart, + // end); + // return type.getInitializer(Integer.parseInt(memento.substring(end + 1))); + // } + // //source type + // return getHandleFromMementoForSourceType(memento, cu, typeStart, + // memento.length()); + // } + /** + * Returns the IJavaElement represented by the + * String memento. + * + * @see getHandleMemento() + */ + // protected IType getHandleFromMementoForSourceType(String memento, + // ICompilationUnit cu, int typeStart, int typeEnd) throws + // JavaModelException { + // int end = memento.lastIndexOf(JavaElement.JEM_TYPE); + // IType type = null; + // if (end == typeStart) { + // String typeName = memento.substring(typeStart + 1, typeEnd); + // type = cu.getType(typeName); + // + // } else { + // String typeNames = memento.substring(typeStart + 1, typeEnd); + // StringTokenizer tokenizer = new StringTokenizer(typeNames, new String(new + // char[] {JavaElement.JEM_TYPE})); + // type = cu.getType(tokenizer.nextToken()); + // while (tokenizer.hasMoreTokens()) { + // //deal with inner types + // type= type.getType(tokenizer.nextToken()); + // } + // } + // return type; + // } + + /* + * @see JavaElement + */ + public IJavaElement getHandleFromMemento(String token, + MementoTokenizer memento, WorkingCopyOwner owner) { + switch (token.charAt(0)) { case JEM_COUNT: return getHandleUpdatingCountFromMemento(memento, owner); case JEM_JAVAPROJECT: String projectName = memento.nextToken(); - JavaElement project = (JavaElement)getJavaProject(projectName); + JavaElement project = (JavaElement) getJavaProject(projectName); return project.getHandleFromMemento(memento, owner); + } + return null; } - return null; -} -/** - * @see JavaElement#getHandleMemento() - */ -public String getHandleMemento(){ - return getElementName(); -} -/** - * Returns the char that marks the start of this handles - * contribution to a memento. - */ -protected char getHandleMementoDelimiter(){ - Assert.isTrue(false, "Should not be called"); //$NON-NLS-1$ - return 0; -} -/** - * @see IJavaModel - */ -public IJavaProject getJavaProject(String name) { - return new JavaProject(ResourcesPlugin.getWorkspace().getRoot().getProject(name), this); -} -/** - * Returns the active Java project associated with the specified - * resource, or null if no Java project yet exists - * for the resource. - * - * @exception IllegalArgumentException if the given resource - * is not one of an IProject, IFolder, or IFile. - */ -public IJavaProject getJavaProject(IResource resource) { - switch(resource.getType()){ + /** + * @see JavaElement#getHandleMemento() + */ + public String getHandleMemento() { + return getElementName(); + } + + /** + * Returns the char that marks the start of this handles + * contribution to a memento. + */ + protected char getHandleMementoDelimiter() { + Assert.isTrue(false, "Should not be called"); //$NON-NLS-1$ + return 0; + } + + /** + * @see IJavaModel + */ + public IJavaProject getJavaProject(String name) { + return new JavaProject(ResourcesPlugin.getWorkspace().getRoot() + .getProject(name), this); + } + + /** + * Returns the active Java project associated with the specified resource, + * or null if no Java project yet exists for the resource. + * + * @exception IllegalArgumentException + * if the given resource is not one of an IProject, IFolder, + * or IFile. + */ + public IJavaProject getJavaProject(IResource resource) { + switch (resource.getType()) { case IResource.FOLDER: - return new JavaProject(((IFolder)resource).getProject(), this); + return new JavaProject(((IFolder) resource).getProject(), this); case IResource.FILE: - return new JavaProject(((IFile)resource).getProject(), this); + return new JavaProject(((IFile) resource).getProject(), this); case IResource.PROJECT: - return new JavaProject((IProject)resource, this); + return new JavaProject((IProject) resource, this); default: - throw new IllegalArgumentException(Util.bind("element.invalidResourceForProject")); //$NON-NLS-1$ + throw new IllegalArgumentException(Util + .bind("element.invalidResourceForProject")); //$NON-NLS-1$ + } } -} -/** - * @see IJavaModel - */ -public IJavaProject[] getJavaProjects() throws JavaModelException { - ArrayList list = getChildrenOfType(JAVA_PROJECT); - IJavaProject[] array= new IJavaProject[list.size()]; - list.toArray(array); - return array; -} -///** -// * @see IJavaModel -// */ -//public Object[] getNonJavaResources() throws JavaModelException { -// return ((JavaModelInfo) getElementInfo()).getNonJavaResources(); -//} + /** + * @see IJavaModel + */ + public IJavaProject[] getJavaProjects() throws JavaModelException { + ArrayList list = getChildrenOfType(JAVA_PROJECT); + IJavaProject[] array = new IJavaProject[list.size()]; + list.toArray(array); + return array; -/** - * Workaround for bug 15168 circular errors not reported - * Returns the list of java projects before resource delta processing - * has started. - */ -public IJavaProject[] getOldJavaProjectsList() throws JavaModelException { - JavaModelManager manager = JavaModelManager.getJavaModelManager(); - return - manager.javaProjectsCache == null ? - this.getJavaProjects() : - manager.javaProjectsCache; -} -/* - * @see IJavaElement - */ -public IPath getPath() { - return Path.ROOT; -} -/* - * @see IJavaElement - */ -public IResource getResource() { - return ResourcesPlugin.getWorkspace().getRoot(); -} -/** - * @see IOpenable - */ -public IResource getUnderlyingResource() throws JavaModelException { - return null; -} -/** - * Returns the workbench associated with this object. - */ -public IWorkspace getWorkspace() { - return ResourcesPlugin.getWorkspace(); -} + } -/** - * @see IJavaModel - */ -public void move(IJavaElement[] elements, IJavaElement[] containers, IJavaElement[] siblings, String[] renamings, boolean force, IProgressMonitor monitor) throws JavaModelException { - if (elements != null && elements.length > 0 && elements[0] != null && elements[0].getElementType() < IJavaElement.TYPE) { - runOperation(new MoveResourceElementsOperation(elements, containers, force), elements, siblings, renamings, monitor); - } else { - runOperation(new MoveElementsOperation(elements, containers, force), elements, siblings, renamings, monitor); + // /** + // * @see IJavaModel + // */ + // public Object[] getNonJavaResources() throws JavaModelException { + // return ((JavaModelInfo) getElementInfo()).getNonJavaResources(); + // } + + /** + * Workaround for bug 15168 circular errors not reported Returns the list of + * java projects before resource delta processing has started. + */ + public IJavaProject[] getOldJavaProjectsList() throws JavaModelException { + JavaModelManager manager = JavaModelManager.getJavaModelManager(); + return manager.javaProjectsCache == null ? this.getJavaProjects() + : manager.javaProjectsCache; } -} -/** - * @see IJavaModel#refreshExternalArchives(IJavaElement[], IProgressMonitor) - */ -//public void refreshExternalArchives(IJavaElement[] elementsScope, IProgressMonitor monitor) throws JavaModelException { -// if (elementsScope == null){ -// elementsScope = new IJavaElement[] { this }; -// } -// JavaModelManager.getJavaModelManager().deltaProcessor.checkExternalArchiveChanges(elementsScope, monitor); -//} + /* + * @see IJavaElement + */ + public IPath getPath() { + return Path.ROOT; + } -/** - * @see IJavaModel - */ -public void rename(IJavaElement[] elements, IJavaElement[] destinations, String[] renamings, boolean force, IProgressMonitor monitor) throws JavaModelException { - MultiOperation op; - if (elements != null && elements.length > 0 && elements[0] != null && elements[0].getElementType() < IJavaElement.TYPE) { - op = new RenameResourceElementsOperation(elements, destinations, renamings, force); - } else { - op = new RenameElementsOperation(elements, destinations, renamings, force); + /* + * @see IJavaElement + */ + public IResource getResource() { + return ResourcesPlugin.getWorkspace().getRoot(); } - - runOperation(op, monitor); -} -/* - * @see JavaElement#rootedAt(IJavaProject) - */ -public IJavaElement rootedAt(IJavaProject project) { - return this; -} -/** - * Configures and runs the MultiOperation. - */ -protected void runOperation(MultiOperation op, IJavaElement[] elements, IJavaElement[] siblings, String[] renamings, IProgressMonitor monitor) throws JavaModelException { - op.setRenamings(renamings); - if (siblings != null) { - for (int i = 0; i < elements.length; i++) { - op.setInsertBefore(elements[i], siblings[i]); + /** + * @see IOpenable + */ + public IResource getUnderlyingResource() throws JavaModelException { + return null; + } + + /** + * Returns the workbench associated with this object. + */ + public IWorkspace getWorkspace() { + return ResourcesPlugin.getWorkspace(); + } + + /** + * @see IJavaModel + */ + public void move(IJavaElement[] elements, IJavaElement[] containers, + IJavaElement[] siblings, String[] renamings, boolean force, + IProgressMonitor monitor) throws JavaModelException { + if (elements != null && elements.length > 0 && elements[0] != null + && elements[0].getElementType() < IJavaElement.TYPE) { + runOperation(new MoveResourceElementsOperation(elements, + containers, force), elements, siblings, renamings, monitor); + } else { + runOperation( + new MoveElementsOperation(elements, containers, force), + elements, siblings, renamings, monitor); } } -// runOperation(op, monitor); - op.runOperation(monitor); -} -/** - * @private Debugging purposes - */ -protected void toStringInfo(int tab, StringBuffer buffer, Object info) { - buffer.append(this.tabString(tab)); - buffer.append("Java Model"); //$NON-NLS-1$ - if (info == null) { - buffer.append(" (not open)"); //$NON-NLS-1$ + + /** + * @see IJavaModel#refreshExternalArchives(IJavaElement[], IProgressMonitor) + */ + // public void refreshExternalArchives(IJavaElement[] elementsScope, + // IProgressMonitor monitor) throws JavaModelException { + // if (elementsScope == null){ + // elementsScope = new IJavaElement[] { this }; + // } + // JavaModelManager.getJavaModelManager().deltaProcessor.checkExternalArchiveChanges(elementsScope, + // monitor); + // } + /** + * @see IJavaModel + */ + public void rename(IJavaElement[] elements, IJavaElement[] destinations, + String[] renamings, boolean force, IProgressMonitor monitor) + throws JavaModelException { + MultiOperation op; + if (elements != null && elements.length > 0 && elements[0] != null + && elements[0].getElementType() < IJavaElement.TYPE) { + op = new RenameResourceElementsOperation(elements, destinations, + renamings, force); + } else { + op = new RenameElementsOperation(elements, destinations, renamings, + force); + } + + runOperation(op, monitor); } -} -/** - * Helper method - returns the targeted item (IResource if internal or java.io.File if external), - * or null if unbound - * Internal items must be referred to using container relative paths. - */ -public static Object getTarget(IContainer container, IPath path, boolean checkResourceExistence) { - - if (path == null) return null; - - // lookup - inside the container - if (path.getDevice() == null) { // container relative paths should not contain a device - // (see http://dev.eclipse.org/bugs/show_bug.cgi?id=18684) - // (case of a workspace rooted at d:\ ) - IResource resource = container.findMember(path); - if (resource != null){ - if (!checkResourceExistence ||resource.exists()) return resource; - return null; + /* + * @see JavaElement#rootedAt(IJavaProject) + */ + public IJavaElement rootedAt(IJavaProject project) { + return this; + + } + + /** + * Configures and runs the MultiOperation. + */ + protected void runOperation(MultiOperation op, IJavaElement[] elements, + IJavaElement[] siblings, String[] renamings, + IProgressMonitor monitor) throws JavaModelException { + op.setRenamings(renamings); + if (siblings != null) { + for (int i = 0; i < elements.length; i++) { + op.setInsertBefore(elements[i], siblings[i]); + } } + // runOperation(op, monitor); + op.runOperation(monitor); } - - // if path is relative, it cannot be an external path - // (see http://dev.eclipse.org/bugs/show_bug.cgi?id=22517) - if (!path.isAbsolute()) return null; - - // lookup - outside the container - File externalFile = new File(path.toOSString()); - if (!checkResourceExistence) { - return externalFile; - } else if (existingExternalFiles.contains(externalFile)) { - return externalFile; - } else { - if (JavaModelManager.ZIP_ACCESS_VERBOSE) { - System.out.println("(" + Thread.currentThread() + ") [JavaModel.getTarget(...)] Checking existence of " + path.toString()); //$NON-NLS-1$ //$NON-NLS-2$ + + /** + * @private Debugging purposes + */ + protected void toStringInfo(int tab, StringBuffer buffer, Object info) { + buffer.append(this.tabString(tab)); + buffer.append("Java Model"); //$NON-NLS-1$ + if (info == null) { + buffer.append(" (not open)"); //$NON-NLS-1$ } - if (externalFile.exists()) { - // cache external file - existingExternalFiles.add(externalFile); + } + + /** + * Helper method - returns the targeted item (IResource if internal or + * java.io.File if external), or null if unbound Internal items must be + * referred to using container relative paths. + */ + public static Object getTarget(IContainer container, IPath path, + boolean checkResourceExistence) { + + if (path == null) + return null; + + // lookup - inside the container + if (path.getDevice() == null) { // container relative paths should not + // contain a device + // (see http://dev.eclipse.org/bugs/show_bug.cgi?id=18684) + // (case of a workspace rooted at d:\ ) + IResource resource = container.findMember(path); + if (resource != null) { + if (!checkResourceExistence || resource.exists()) + return resource; + return null; + } + } + + // if path is relative, it cannot be an external path + // (see http://dev.eclipse.org/bugs/show_bug.cgi?id=22517) + if (!path.isAbsolute()) + return null; + + // lookup - outside the container + File externalFile = new File(path.toOSString()); + if (!checkResourceExistence) { + return externalFile; + } else if (existingExternalFiles.contains(externalFile)) { return externalFile; + } else { + if (JavaModelManager.ZIP_ACCESS_VERBOSE) { + System.out + .println("(" + Thread.currentThread() + ") [JavaModel.getTarget(...)] Checking existence of " + path.toString()); //$NON-NLS-1$ //$NON-NLS-2$ + } + if (externalFile.exists()) { + // cache external file + existingExternalFiles.add(externalFile); + return externalFile; + } } + return null; } - return null; -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelCache.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelCache.java index 4121aa3..41a6458 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelCache.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelCache.java @@ -9,6 +9,7 @@ * IBM Corporation - initial API and implementation *******************************************************************************/ package net.sourceforge.phpdt.internal.core; + import java.util.HashMap; import java.util.Map; @@ -19,18 +20,19 @@ import net.sourceforge.phpdt.core.IJavaElement; */ public class JavaModelCache { public static final int PKG_CACHE_SIZE = 500; + public static final int OPENABLE_CACHE_SIZE = 2000; - + /** * Active Java Model Info */ protected JavaModelInfo modelInfo; - + /** * Cache of open projects and package fragment roots. */ protected Map projectAndRootCache; - + /** * Cache of open package fragments */ @@ -45,26 +47,31 @@ public class JavaModelCache { * Cache of open children of openable Java Model Java elements */ protected Map childrenCache; - -public JavaModelCache() { - this.projectAndRootCache = new HashMap(50); - this.pkgCache = new HashMap(PKG_CACHE_SIZE); - this.openableCache = new ElementCache(OPENABLE_CACHE_SIZE); - this.childrenCache = new HashMap(OPENABLE_CACHE_SIZE*20); // average 20 chilren per openable -} -public double openableFillingRatio() { - return this.openableCache.fillingRatio(); -} -public int pkgSize() { - return this.pkgCache.size(); -} - -/** - * Returns the info for the element. - */ -public Object getInfo(IJavaElement element) { - switch (element.getElementType()) { + public JavaModelCache() { + this.projectAndRootCache = new HashMap(50); + this.pkgCache = new HashMap(PKG_CACHE_SIZE); + this.openableCache = new ElementCache(OPENABLE_CACHE_SIZE); + this.childrenCache = new HashMap(OPENABLE_CACHE_SIZE * 20); // average + // 20 + // chilren + // per + // openable + } + + public double openableFillingRatio() { + return this.openableCache.fillingRatio(); + } + + public int pkgSize() { + return this.pkgCache.size(); + } + + /** + * Returns the info for the element. + */ + public Object getInfo(IJavaElement element) { + switch (element.getElementType()) { case IJavaElement.JAVA_MODEL: return this.modelInfo; case IJavaElement.JAVA_PROJECT: @@ -77,15 +84,14 @@ public Object getInfo(IJavaElement element) { return this.openableCache.get(element); default: return this.childrenCache.get(element); + } } -} -/** - * Returns the info for this element without - * disturbing the cache ordering. - */ -protected Object peekAtInfo(IJavaElement element) { - switch (element.getElementType()) { + /** + * Returns the info for this element without disturbing the cache ordering. + */ + protected Object peekAtInfo(IJavaElement element) { + switch (element.getElementType()) { case IJavaElement.JAVA_MODEL: return this.modelInfo; case IJavaElement.JAVA_PROJECT: @@ -98,14 +104,14 @@ protected Object peekAtInfo(IJavaElement element) { return this.openableCache.peek(element); default: return this.childrenCache.get(element); + } } -} -/** - * Remember the info for the element. - */ -protected void putInfo(IJavaElement element, Object info) { - switch (element.getElementType()) { + /** + * Remember the info for the element. + */ + protected void putInfo(IJavaElement element, Object info) { + switch (element.getElementType()) { case IJavaElement.JAVA_MODEL: this.modelInfo = (JavaModelInfo) info; break; @@ -122,13 +128,14 @@ protected void putInfo(IJavaElement element, Object info) { break; default: this.childrenCache.put(element, info); + } } -} -/** - * Removes the info of the element from the cache. - */ -protected void removeInfo(IJavaElement element) { - switch (element.getElementType()) { + + /** + * Removes the info of the element from the cache. + */ + protected void removeInfo(IJavaElement element) { + switch (element.getElementType()) { case IJavaElement.JAVA_MODEL: this.modelInfo = null; break; @@ -145,6 +152,6 @@ protected void removeInfo(IJavaElement element) { break; default: this.childrenCache.remove(element); + } } } -} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelInfo.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelInfo.java index 958a178..4dce222 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelInfo.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelInfo.java @@ -16,9 +16,8 @@ import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; /** - * Implementation of IJavaModel. A Java Model is specific to a - * workspace. - * + * Implementation of IJavaModel. A Java Model is specific to a workspace. + * * @see IJavaModel */ public class JavaModelInfo extends OpenableElementInfo { @@ -28,45 +27,49 @@ public class JavaModelInfo extends OpenableElementInfo { */ Object[] nonJavaResources; -/** - * Constructs a new Java Model Info - */ -protected JavaModelInfo() { -} -/** - * Compute the non-java resources contained in this java project. - */ -private Object[] computeNonJavaResources() { - IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); - int length = projects.length; - Object[] nonJavaResources = null; - int index = 0; - for (int i = 0; i < length; i++) { - IProject project = projects[i]; - if (!JavaProject.hasJavaNature(project)) { - if (nonJavaResources == null) { - nonJavaResources = new Object[length]; + /** + * Constructs a new Java Model Info + */ + protected JavaModelInfo() { + } + + /** + * Compute the non-java resources contained in this java project. + */ + private Object[] computeNonJavaResources() { + IProject[] projects = ResourcesPlugin.getWorkspace().getRoot() + .getProjects(); + int length = projects.length; + Object[] nonJavaResources = null; + int index = 0; + for (int i = 0; i < length; i++) { + IProject project = projects[i]; + if (!JavaProject.hasJavaNature(project)) { + if (nonJavaResources == null) { + nonJavaResources = new Object[length]; + } + nonJavaResources[index++] = project; } - nonJavaResources[index++] = project; } + if (index == 0) + return NO_NON_JAVA_RESOURCES; + if (index < length) { + System.arraycopy(nonJavaResources, 0, + nonJavaResources = new Object[index], 0, index); + } + return nonJavaResources; } - if (index == 0) return NO_NON_JAVA_RESOURCES; - if (index < length) { - System.arraycopy(nonJavaResources, 0, nonJavaResources = new Object[index], 0, index); - } - return nonJavaResources; -} -/** - * Returns an array of non-java resources contained in the receiver. - */ -Object[] getNonJavaResources() { + /** + * Returns an array of non-java resources contained in the receiver. + */ + Object[] getNonJavaResources() { - Object[] nonJavaResources = this.nonJavaResources; - if (nonJavaResources == null) { - nonJavaResources = computeNonJavaResources(); - this.nonJavaResources = nonJavaResources; + Object[] nonJavaResources = this.nonJavaResources; + if (nonJavaResources == null) { + nonJavaResources = computeNonJavaResources(); + this.nonJavaResources = nonJavaResources; + } + return nonJavaResources; } - return nonJavaResources; -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelManager.java index 39978d1..b64d468 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelManager.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelManager.java @@ -75,93 +75,138 @@ import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.Preferences.PropertyChangeEvent; /** - * The JavaModelManager manages instances of IJavaModel. - * IElementChangedListeners register with the JavaModelManager, - * and receive ElementChangedEvents for all IJavaModels. + * The JavaModelManager manages instances of + * IJavaModel. IElementChangedListeners register + * with the JavaModelManager, and receive + * ElementChangedEvents for all IJavaModels. *

                                      - * The single instance of JavaModelManager is available from - * the static method JavaModelManager.getJavaModelManager(). + * The single instance of JavaModelManager is available from the + * static method JavaModelManager.getJavaModelManager(). */ public class JavaModelManager implements ISaveParticipant { - /** + /** * Unique handle onto the JavaModel */ final JavaModel javaModel = new JavaModel(); -// public IndexManager indexManager = new IndexManager(); + + // public IndexManager indexManager = new IndexManager(); /** * Classpath variables pool */ public static HashMap Variables = new HashMap(5); + public static HashMap PreviousSessionVariables = new HashMap(5); + public static HashSet OptionNames = new HashSet(20); - public final static String CP_VARIABLE_PREFERENCES_PREFIX = PHPeclipsePlugin.PLUGIN_ID+".classpathVariable."; //$NON-NLS-1$ - public final static String CP_CONTAINER_PREFERENCES_PREFIX = PHPeclipsePlugin.PLUGIN_ID+".classpathContainer."; //$NON-NLS-1$ + + public final static String CP_VARIABLE_PREFERENCES_PREFIX = PHPeclipsePlugin.PLUGIN_ID + + ".classpathVariable."; //$NON-NLS-1$ + + public final static String CP_CONTAINER_PREFERENCES_PREFIX = PHPeclipsePlugin.PLUGIN_ID + + ".classpathContainer."; //$NON-NLS-1$ + public final static String CP_ENTRY_IGNORE = "####"; //$NON-NLS-1$ /** * Classpath containers pool */ public static HashMap containers = new HashMap(5); + public static HashMap PreviousSessionContainers = new HashMap(5); /** - * Name of the extension point for contributing classpath variable initializers + * Name of the extension point for contributing classpath variable + * initializers */ -// public static final String CPVARIABLE_INITIALIZER_EXTPOINT_ID = "classpathVariableInitializer" ; //$NON-NLS-1$ - + // public static final String CPVARIABLE_INITIALIZER_EXTPOINT_ID = + // "classpathVariableInitializer" ; //$NON-NLS-1$ /** - * Name of the extension point for contributing classpath container initializers + * Name of the extension point for contributing classpath container + * initializers */ -// public static final String CPCONTAINER_INITIALIZER_EXTPOINT_ID = "classpathContainerInitializer" ; //$NON-NLS-1$ - + // public static final String CPCONTAINER_INITIALIZER_EXTPOINT_ID = + // "classpathContainerInitializer" ; //$NON-NLS-1$ /** * Name of the extension point for contributing a source code formatter */ - public static final String FORMATTER_EXTPOINT_ID = "codeFormatter" ; //$/** + public static final String FORMATTER_EXTPOINT_ID = "codeFormatter"; // $/** /** * Value of the content-type for Java source files */ - public static final String JAVA_SOURCE_CONTENT_TYPE = PHPeclipsePlugin.PLUGIN_ID+".phpSource" ; //$NON-NLS-1$NON-NLS-1$ - - /** - * Special value used for recognizing ongoing initialization and breaking initialization cycles - */ - public final static IPath VariableInitializationInProgress = new Path("Variable Initialization In Progress"); //$NON-NLS-1$ -// public final static IClasspathContainer ContainerInitializationInProgress = new IClasspathContainer() { -// public IClasspathEntry[] getClasspathEntries() { return null; } -// public String getDescription() { return "Container Initialization In Progress"; } //$NON-NLS-1$ -// public int getKind() { return 0; } -// public IPath getPath() { return null; } -// public String toString() { return getDescription(); } -// }; - - private static final String INDEX_MANAGER_DEBUG = PHPeclipsePlugin.PLUGIN_ID + "/debug/indexmanager" ; //$NON-NLS-1$ - private static final String COMPILER_DEBUG = PHPeclipsePlugin.PLUGIN_ID + "/debug/compiler" ; //$NON-NLS-1$ - private static final String JAVAMODEL_DEBUG = PHPeclipsePlugin.PLUGIN_ID + "/debug/javamodel" ; //$NON-NLS-1$ - private static final String CP_RESOLVE_DEBUG = PHPeclipsePlugin.PLUGIN_ID + "/debug/cpresolution" ; //$NON-NLS-1$ - private static final String ZIP_ACCESS_DEBUG = PHPeclipsePlugin.PLUGIN_ID + "/debug/zipaccess" ; //$NON-NLS-1$ - private static final String DELTA_DEBUG =PHPeclipsePlugin.PLUGIN_ID + "/debug/javadelta" ; //$NON-NLS-1$ - private static final String HIERARCHY_DEBUG = PHPeclipsePlugin.PLUGIN_ID + "/debug/hierarchy" ; //$NON-NLS-1$ - private static final String POST_ACTION_DEBUG = PHPeclipsePlugin.PLUGIN_ID + "/debug/postaction" ; //$NON-NLS-1$ - private static final String BUILDER_DEBUG = PHPeclipsePlugin.PLUGIN_ID + "/debug/builder" ; //$NON-NLS-1$ - private static final String COMPLETION_DEBUG = PHPeclipsePlugin.PLUGIN_ID + "/debug/completion" ; //$NON-NLS-1$ - private static final String SELECTION_DEBUG = PHPeclipsePlugin.PLUGIN_ID + "/debug/selection" ; //$NON-NLS-1$ - private static final String SHARED_WC_DEBUG = PHPeclipsePlugin.PLUGIN_ID + "/debug/sharedworkingcopy" ; //$NON-NLS-1$ - private static final String SEARCH_DEBUG = PHPeclipsePlugin.PLUGIN_ID + "/debug/search" ; //$NON-NLS-1$ + public static final String JAVA_SOURCE_CONTENT_TYPE = PHPeclipsePlugin.PLUGIN_ID + + ".phpSource"; //$NON-NLS-1$NON-NLS-1$ + + /** + * Special value used for recognizing ongoing initialization and breaking + * initialization cycles + */ + public final static IPath VariableInitializationInProgress = new Path( + "Variable Initialization In Progress"); //$NON-NLS-1$ + // public final static IClasspathContainer ContainerInitializationInProgress + // = new IClasspathContainer() { + // public IClasspathEntry[] getClasspathEntries() { return null; } + // public String getDescription() { return "Container Initialization In + // Progress"; } //$NON-NLS-1$ + // public int getKind() { return 0; } + // public IPath getPath() { return null; } + // public String toString() { return getDescription(); } + // }; + + private static final String INDEX_MANAGER_DEBUG = PHPeclipsePlugin.PLUGIN_ID + + "/debug/indexmanager"; //$NON-NLS-1$ + + private static final String COMPILER_DEBUG = PHPeclipsePlugin.PLUGIN_ID + + "/debug/compiler"; //$NON-NLS-1$ + + private static final String JAVAMODEL_DEBUG = PHPeclipsePlugin.PLUGIN_ID + + "/debug/javamodel"; //$NON-NLS-1$ + + private static final String CP_RESOLVE_DEBUG = PHPeclipsePlugin.PLUGIN_ID + + "/debug/cpresolution"; //$NON-NLS-1$ + + private static final String ZIP_ACCESS_DEBUG = PHPeclipsePlugin.PLUGIN_ID + + "/debug/zipaccess"; //$NON-NLS-1$ + + private static final String DELTA_DEBUG = PHPeclipsePlugin.PLUGIN_ID + + "/debug/javadelta"; //$NON-NLS-1$ + + private static final String HIERARCHY_DEBUG = PHPeclipsePlugin.PLUGIN_ID + + "/debug/hierarchy"; //$NON-NLS-1$ + + private static final String POST_ACTION_DEBUG = PHPeclipsePlugin.PLUGIN_ID + + "/debug/postaction"; //$NON-NLS-1$ + + private static final String BUILDER_DEBUG = PHPeclipsePlugin.PLUGIN_ID + + "/debug/builder"; //$NON-NLS-1$ + + private static final String COMPLETION_DEBUG = PHPeclipsePlugin.PLUGIN_ID + + "/debug/completion"; //$NON-NLS-1$ + + private static final String SELECTION_DEBUG = PHPeclipsePlugin.PLUGIN_ID + + "/debug/selection"; //$NON-NLS-1$ + + private static final String SHARED_WC_DEBUG = PHPeclipsePlugin.PLUGIN_ID + + "/debug/sharedworkingcopy"; //$NON-NLS-1$ + + private static final String SEARCH_DEBUG = PHPeclipsePlugin.PLUGIN_ID + + "/debug/search"; //$NON-NLS-1$ public final static IWorkingCopy[] NoWorkingCopy = new IWorkingCopy[0]; /** - * Table from WorkingCopyOwner to a table of ICompilationUnit (working copy handle) to PerWorkingCopyInfo. - * NOTE: this object itself is used as a lock to synchronize creation/removal of per working copy infos + * Table from WorkingCopyOwner to a table of ICompilationUnit (working copy + * handle) to PerWorkingCopyInfo. NOTE: this object itself is used as a lock + * to synchronize creation/removal of per working copy infos */ protected Map perWorkingCopyInfos = new HashMap(5); + /** - * Returns whether the given full path (for a package) conflicts with the output location - * of the given project. + * Returns whether the given full path (for a package) conflicts with the + * output location of the given project. */ - public static boolean conflictsWithOutputLocation(IPath folderPath, JavaProject project) { + public static boolean conflictsWithOutputLocation(IPath folderPath, + JavaProject project) { try { IPath outputLocation = project.getOutputLocation(); if (outputLocation == null) { @@ -169,9 +214,12 @@ public class JavaModelManager implements ISaveParticipant { return true; } if (outputLocation.isPrefixOf(folderPath)) { - // only allow nesting in project's output if there is a corresponding source folder - // or if the project's output is not used (in other words, if all source folders have their custom output) - IClasspathEntry[] classpath = project.getResolvedClasspath(true); + // only allow nesting in project's output if there is a + // corresponding source folder + // or if the project's output is not used (in other words, if + // all source folders have their custom output) + IClasspathEntry[] classpath = project + .getResolvedClasspath(true); boolean isOutputUsed = false; for (int i = 0, length = classpath.length; i < length; i++) { IClasspathEntry entry = classpath[i]; @@ -193,68 +241,83 @@ public class JavaModelManager implements ISaveParticipant { } } -// public static IClasspathContainer containerGet(IJavaProject project, IPath containerPath) { -// Map projectContainers = (Map)Containers.get(project); -// if (projectContainers == null){ -// return null; -// } -// IClasspathContainer container = (IClasspathContainer)projectContainers.get(containerPath); -// return container; -// } - -// public static void containerPut(IJavaProject project, IPath containerPath, IClasspathContainer container){ -// -// Map projectContainers = (Map)Containers.get(project); -// if (projectContainers == null){ -// projectContainers = new HashMap(1); -// Containers.put(project, projectContainers); -// } -// -// if (container == null) { -// projectContainers.remove(containerPath); -// Map previousContainers = (Map)PreviousSessionContainers.get(project); -// if (previousContainers != null){ -// previousContainers.remove(containerPath); -// } -// } else { -// projectContainers.put(containerPath, container); -// } -// -// // do not write out intermediate initialization value -// if (container == JavaModelManager.ContainerInitializationInProgress) { -// return; -// } -// Preferences preferences = PHPeclipsePlugin.getPlugin().getPluginPreferences(); -// String containerKey = CP_CONTAINER_PREFERENCES_PREFIX+project.getElementName() +"|"+containerPath;//$NON-NLS-1$ -// String containerString = CP_ENTRY_IGNORE; -// try { -// if (container != null) { -// containerString = ((JavaProject)project).encodeClasspath(container.getClasspathEntries(), null, false); -// } -// } catch(JavaModelException e){ -// } -// preferences.setDefault(containerKey, CP_ENTRY_IGNORE); // use this default to get rid of removed ones -// preferences.setValue(containerKey, containerString); -// PHPeclipsePlugin.getPlugin().savePluginPreferences(); -// } + // public static IClasspathContainer containerGet(IJavaProject project, + // IPath containerPath) { + // Map projectContainers = (Map)Containers.get(project); + // if (projectContainers == null){ + // return null; + // } + // IClasspathContainer container = + // (IClasspathContainer)projectContainers.get(containerPath); + // return container; + // } + + // public static void containerPut(IJavaProject project, IPath + // containerPath, IClasspathContainer container){ + // + // Map projectContainers = (Map)Containers.get(project); + // if (projectContainers == null){ + // projectContainers = new HashMap(1); + // Containers.put(project, projectContainers); + // } + // + // if (container == null) { + // projectContainers.remove(containerPath); + // Map previousContainers = (Map)PreviousSessionContainers.get(project); + // if (previousContainers != null){ + // previousContainers.remove(containerPath); + // } + // } else { + // projectContainers.put(containerPath, container); + // } + // + // // do not write out intermediate initialization value + // if (container == JavaModelManager.ContainerInitializationInProgress) { + // return; + // } + // Preferences preferences = + // PHPeclipsePlugin.getPlugin().getPluginPreferences(); + // String containerKey = + // CP_CONTAINER_PREFERENCES_PREFIX+project.getElementName() + // +"|"+containerPath;//$NON-NLS-1$ + // String containerString = CP_ENTRY_IGNORE; + // try { + // if (container != null) { + // containerString = + // ((JavaProject)project).encodeClasspath(container.getClasspathEntries(), + // null, false); + // } + // } catch(JavaModelException e){ + // } + // preferences.setDefault(containerKey, CP_ENTRY_IGNORE); // use this + // default to get rid of removed ones + // preferences.setValue(containerKey, containerString); + // PHPeclipsePlugin.getPlugin().savePluginPreferences(); + // } /** * Returns the Java element corresponding to the given resource, or - * null if unable to associate the given resource - * with a Java element. + * null if unable to associate the given resource with a Java + * element. *

                                      - * The resource must be one of:

                                        - *
                                      • a project - the element returned is the corresponding IJavaProject
                                      • - *
                                      • a .java file - the element returned is the corresponding ICompilationUnit
                                      • - *
                                      • a .class file - the element returned is the corresponding IClassFile
                                      • - *
                                      • a .jar file - the element returned is the corresponding IPackageFragmentRoot
                                      • - *
                                      • a folder - the element returned is the corresponding IPackageFragmentRoot - * or IPackageFragment
                                      • - *
                                      • the workspace root resource - the element returned is the IJavaModel
                                      • - *
                                      + * The resource must be one of: + *
                                        + *
                                      • a project - the element returned is the corresponding + * IJavaProject
                                      • + *
                                      • a .java file - the element returned is the + * corresponding ICompilationUnit
                                      • + *
                                      • a .class file - the element returned is the + * corresponding IClassFile
                                      • + *
                                      • a .jar file - the element returned is the + * corresponding IPackageFragmentRoot
                                      • + *
                                      • a folder - the element returned is the corresponding + * IPackageFragmentRoot or IPackageFragment
                                      • + *
                                      • the workspace root resource - the element returned is the + * IJavaModel
                                      • + *
                                      *

                                      - * Creating a Java element has the side effect of creating and opening all of the - * element's parents if they are not yet open. + * Creating a Java element has the side effect of creating and opening all + * of the element's parents if they are not yet open. */ public static IJavaElement create(IResource resource, IJavaProject project) { if (resource == null) { @@ -262,33 +325,37 @@ public class JavaModelManager implements ISaveParticipant { } int type = resource.getType(); switch (type) { - case IResource.PROJECT : - return JavaCore.create((IProject) resource); - case IResource.FILE : - return create((IFile) resource, project); - case IResource.FOLDER : - return create((IFolder) resource, project); - case IResource.ROOT : - return JavaCore.create((IWorkspaceRoot) resource); - default : - return null; - } - } - - /** - * Returns the Java element corresponding to the given file, its project being the given - * project. - * Returns null if unable to associate the given file - * with a Java element. - * - *

                                      The file must be one of:

                                        - *
                                      • a .java file - the element returned is the corresponding ICompilationUnit
                                      • - *
                                      • a .class file - the element returned is the corresponding IClassFile
                                      • - *
                                      • a .jar file - the element returned is the corresponding IPackageFragmentRoot
                                      • - *
                                      + case IResource.PROJECT: + return JavaCore.create((IProject) resource); + case IResource.FILE: + return create((IFile) resource, project); + case IResource.FOLDER: + return create((IFolder) resource, project); + case IResource.ROOT: + return JavaCore.create((IWorkspaceRoot) resource); + default: + return null; + } + } + + /** + * Returns the Java element corresponding to the given file, its project + * being the given project. Returns null if unable to + * associate the given file with a Java element. + * *

                                      - * Creating a Java element has the side effect of creating and opening all of the - * element's parents if they are not yet open. + * The file must be one of: + *

                                        + *
                                      • a .java file - the element returned is the + * corresponding ICompilationUnit
                                      • + *
                                      • a .class file - the element returned is the + * corresponding IClassFile
                                      • + *
                                      • a .jar file - the element returned is the + * corresponding IPackageFragmentRoot
                                      • + *
                                      + *

                                      + * Creating a Java element has the side effect of creating and opening all + * of the element's parents if they are not yet open. */ public static IJavaElement create(IFile file, IJavaProject project) { if (file == null) { @@ -301,25 +368,27 @@ public class JavaModelManager implements ISaveParticipant { if (file.getFileExtension() != null) { String name = file.getName(); if (PHPFileUtil.isValidPHPUnitName(name)) - //if (PHPFileUtil.isPHPFile(file)) + // if (PHPFileUtil.isPHPFile(file)) return createCompilationUnitFrom(file, project); -// if (ProjectPrefUtil.isValidClassFileName(name)) -// return createClassFileFrom(file, project); -// if (ProjectPrefUtil.isArchiveFileName(name)) -// return createJarPackageFragmentRootFrom(file, project); + // if (ProjectPrefUtil.isValidClassFileName(name)) + // return createClassFileFrom(file, project); + // if (ProjectPrefUtil.isArchiveFileName(name)) + // return createJarPackageFragmentRootFrom(file, project); } return null; } /** - * Returns the package fragment or package fragment root corresponding to the given folder, - * its parent or great parent being the given project. - * or null if unable to associate the given folder with a Java element. + * Returns the package fragment or package fragment root corresponding to + * the given folder, its parent or great parent being the given project. or + * null if unable to associate the given folder with a Java + * element. *

                                      - * Note that a package fragment root is returned rather than a default package. + * Note that a package fragment root is returned rather than a default + * package. *

                                      - * Creating a Java element has the side effect of creating and opening all of the - * element's parents if they are not yet open. + * Creating a Java element has the side effect of creating and opening all + * of the element's parents if they are not yet open. */ public static IJavaElement create(IFolder folder, IJavaProject project) { if (folder == null) { @@ -329,131 +398,156 @@ public class JavaModelManager implements ISaveParticipant { project = JavaCore.create(folder.getProject()); } IJavaElement element = determineIfOnClasspath(folder, project); - if (conflictsWithOutputLocation(folder.getFullPath(), (JavaProject)project) - || (folder.getName().indexOf('.') >= 0 - && !(element instanceof IPackageFragmentRoot))) { - return null; // only package fragment roots are allowed with dot names + if (conflictsWithOutputLocation(folder.getFullPath(), + (JavaProject) project) + || (folder.getName().indexOf('.') >= 0 && !(element instanceof IPackageFragmentRoot))) { + return null; // only package fragment roots are allowed with dot + // names } else { return element; } } /** - * Creates and returns a class file element for the given .class file, - * its project being the given project. Returns null if unable - * to recognize the class file. - */ -// public static IClassFile createClassFileFrom(IFile file, IJavaProject project ) { -// if (file == null) { -// return null; -// } -// if (project == null) { -// project = PHPCore.create(file.getProject()); -// } -// IPackageFragment pkg = (IPackageFragment) determineIfOnClasspath(file, project); -// if (pkg == null) { -// // fix for 1FVS7WE -// // not on classpath - make the root its folder, and a default package -// IPackageFragmentRoot root = project.getPackageFragmentRoot(file.getParent()); -// pkg = root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME); -// } -// return pkg.getClassFile(file.getName()); -// } - - /** - * Creates and returns a compilation unit element for the given .java - * file, its project being the given project. Returns null if unable - * to recognize the compilation unit. - */ - public static ICompilationUnit createCompilationUnitFrom(IFile file, IJavaProject project) { - - if (file == null) return null; + * Creates and returns a class file element for the given + * .class file, its project being the given project. Returns + * null if unable to recognize the class file. + */ + // public static IClassFile createClassFileFrom(IFile file, IJavaProject + // project ) { + // if (file == null) { + // return null; + // } + // if (project == null) { + // project = PHPCore.create(file.getProject()); + // } + // IPackageFragment pkg = (IPackageFragment) determineIfOnClasspath(file, + // project); + // if (pkg == null) { + // // fix for 1FVS7WE + // // not on classpath - make the root its folder, and a default package + // IPackageFragmentRoot root = + // project.getPackageFragmentRoot(file.getParent()); + // pkg = root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME); + // } + // return pkg.getClassFile(file.getName()); + // } + /** + * Creates and returns a compilation unit element for the given + * .java file, its project being the given project. Returns + * null if unable to recognize the compilation unit. + */ + public static ICompilationUnit createCompilationUnitFrom(IFile file, + IJavaProject project) { + + if (file == null) + return null; if (project == null) { project = JavaCore.create(file.getProject()); } - IPackageFragment pkg = (IPackageFragment) determineIfOnClasspath(file, project); + IPackageFragment pkg = (IPackageFragment) determineIfOnClasspath(file, + project); if (pkg == null) { - // not on classpath - make the root its folder, and a default package - IPackageFragmentRoot root = project.getPackageFragmentRoot(file.getParent()); - pkg = root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME); - - if (VERBOSE){ - System.out.println("WARNING : creating unit element outside classpath ("+ Thread.currentThread()+"): " + file.getFullPath()); //$NON-NLS-1$//$NON-NLS-2$ + // not on classpath - make the root its folder, and a default + // package + IPackageFragmentRoot root = project.getPackageFragmentRoot(file + .getParent()); + pkg = root + .getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME); + + if (VERBOSE) { + System.out + .println("WARNING : creating unit element outside classpath (" + Thread.currentThread() + "): " + file.getFullPath()); //$NON-NLS-1$//$NON-NLS-2$ } } return pkg.getCompilationUnit(file.getName()); } + /** - * Creates and returns a handle for the given JAR file, its project being the given project. - * The Java model associated with the JAR's project may be - * created as a side effect. - * Returns null if unable to create a JAR package fragment root. - * (for example, if the JAR file represents a non-Java resource) - */ -// public static IPackageFragmentRoot createJarPackageFragmentRootFrom(IFile file, IJavaProject project) { -// if (file == null) { -// return null; -// } -// if (project == null) { -// project = PHPCore.create(file.getProject()); -// } -// -// // Create a jar package fragment root only if on the classpath -// IPath resourcePath = file.getFullPath(); -// try { -// IClasspathEntry[] entries = ((JavaProject)project).getResolvedClasspath(true); -// for (int i = 0, length = entries.length; i < length; i++) { -// IClasspathEntry entry = entries[i]; -// IPath rootPath = entry.getPath(); -// if (rootPath.equals(resourcePath)) { -// return project.getPackageFragmentRoot(file); -// } -// } -// } catch (JavaModelException e) { -// } -// return null; -// } - - /** - * Returns the package fragment root represented by the resource, or - * the package fragment the given resource is located in, or null + * Creates and returns a handle for the given JAR file, its project being + * the given project. The Java model associated with the JAR's project may + * be created as a side effect. Returns null if unable to + * create a JAR package fragment root. (for example, if the JAR file + * represents a non-Java resource) + */ + // public static IPackageFragmentRoot createJarPackageFragmentRootFrom(IFile + // file, IJavaProject project) { + // if (file == null) { + // return null; + // } + // if (project == null) { + // project = PHPCore.create(file.getProject()); + // } + // + // // Create a jar package fragment root only if on the classpath + // IPath resourcePath = file.getFullPath(); + // try { + // IClasspathEntry[] entries = + // ((JavaProject)project).getResolvedClasspath(true); + // for (int i = 0, length = entries.length; i < length; i++) { + // IClasspathEntry entry = entries[i]; + // IPath rootPath = entry.getPath(); + // if (rootPath.equals(resourcePath)) { + // return project.getPackageFragmentRoot(file); + // } + // } + // } catch (JavaModelException e) { + // } + // return null; + // } + /** + * Returns the package fragment root represented by the resource, or the + * package fragment the given resource is located in, or null * if the given resource is not on the classpath of the given project. */ - public static IJavaElement determineIfOnClasspath( - IResource resource, - IJavaProject project) { + public static IJavaElement determineIfOnClasspath(IResource resource, + IJavaProject project) { IPath resourcePath = resource.getFullPath(); try { - IClasspathEntry[] entries = - net.sourceforge.phpdt.internal.compiler.util.Util.isJavaFileName(resourcePath.lastSegment()) - ? project.getRawClasspath() // JAVA file can only live inside SRC folder (on the raw path) - : ((JavaProject)project).getResolvedClasspath(true); + IClasspathEntry[] entries = net.sourceforge.phpdt.internal.compiler.util.Util + .isJavaFileName(resourcePath.lastSegment()) ? project + .getRawClasspath() // JAVA file can only live inside SRC + // folder (on the raw path) + : ((JavaProject) project).getResolvedClasspath(true); for (int i = 0; i < entries.length; i++) { IClasspathEntry entry = entries[i]; - if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) continue; + if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) + continue; IPath rootPath = entry.getPath(); if (rootPath.equals(resourcePath)) { return project.getPackageFragmentRoot(resource); - } else if (rootPath.isPrefixOf(resourcePath) && !Util.isExcluded(resource, null, ((ClasspathEntry)entry).fullExclusionPatternChars())) { - // given we have a resource child of the root, it cannot be a JAR pkg root - IPackageFragmentRoot root = ((JavaProject) project).getFolderPackageFragmentRoot(rootPath); - if (root == null) return null; - IPath pkgPath = resourcePath.removeFirstSegments(rootPath.segmentCount()); + } else if (rootPath.isPrefixOf(resourcePath) + && !Util.isExcluded(resource, null, + ((ClasspathEntry) entry) + .fullExclusionPatternChars())) { + // given we have a resource child of the root, it cannot be + // a JAR pkg root + IPackageFragmentRoot root = ((JavaProject) project) + .getFolderPackageFragmentRoot(rootPath); + if (root == null) + return null; + IPath pkgPath = resourcePath.removeFirstSegments(rootPath + .segmentCount()); if (resource.getType() == IResource.FILE) { - // if the resource is a file, then remove the last segment which + // if the resource is a file, then remove the last + // segment which // is the file name in the package pkgPath = pkgPath.removeLastSegments(1); - // don't check validity of package name (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=26706) -// String pkgName = pkgPath.toString().replace('/', '.'); + // don't check validity of package name (see + // http://bugs.eclipse.org/bugs/show_bug.cgi?id=26706) + // String pkgName = pkgPath.toString().replace('/', + // '.'); String pkgName = pkgPath.toString(); return root.getPackageFragment(pkgName); } else { String pkgName = Util.packageName(pkgPath); - if (pkgName == null){// || JavaConventions.validatePackageName(pkgName).getSeverity() == IStatus.ERROR) { + if (pkgName == null) {// || + // JavaConventions.validatePackageName(pkgName).getSeverity() + // == IStatus.ERROR) { return null; } return root.getPackageFragment(pkgName); @@ -469,7 +563,7 @@ public class JavaModelManager implements ISaveParticipant { /** * The singleton manager */ - private final static JavaModelManager Manager= new JavaModelManager(); + private final static JavaModelManager Manager = new JavaModelManager(); /** * Infos cache. @@ -480,65 +574,73 @@ public class JavaModelManager implements ISaveParticipant { * Temporary cache of newly opened elements */ private ThreadLocal temporaryCache = new ThreadLocal(); + /** * Set of elements which are out of sync with their buffers. */ protected Map elementsOutOfSynchWithBuffers = new HashMap(11); + /** * Holds the state used for delta processing. */ public DeltaProcessingState deltaState = new DeltaProcessingState(); + /** * Turns delta firing on/off. By default it is on. */ - private boolean isFiring= true; + private boolean isFiring = true; /** - * Queue of deltas created explicily by the Java Model that - * have yet to be fired. + * Queue of deltas created explicily by the Java Model that have yet to be + * fired. */ - ArrayList javaModelDeltas= new ArrayList(); + ArrayList javaModelDeltas = new ArrayList(); + /** * Queue of reconcile deltas on working copies that have yet to be fired. * This is a table form IWorkingCopy to IJavaElementDelta */ HashMap reconcileDeltas = new HashMap(); - /** * Collection of listeners for Java element deltas */ private IElementChangedListener[] elementChangedListeners = new IElementChangedListener[5]; + private int[] elementChangedListenerMasks = new int[5]; + private int elementChangedListenerCount = 0; - public int currentChangeEventType = ElementChangedEvent.PRE_AUTO_BUILD; - public static final int DEFAULT_CHANGE_EVENT = 0; // must not collide with ElementChangedEvent event masks + public int currentChangeEventType = ElementChangedEvent.PRE_AUTO_BUILD; + public static final int DEFAULT_CHANGE_EVENT = 0; // must not collide with + // ElementChangedEvent + // event masks /** - * Used to convert IResourceDeltas into IJavaElementDeltas. + * Used to convert IResourceDeltas into + * IJavaElementDeltas. */ -// public final DeltaProcessor deltaProcessor = new DeltaProcessor(this); + // public final DeltaProcessor deltaProcessor = new DeltaProcessor(this); /** * Used to update the JavaModel for IJavaElementDeltas. */ - private final ModelUpdater modelUpdater =new ModelUpdater(); + private final ModelUpdater modelUpdater = new ModelUpdater(); + /** - * Workaround for bug 15168 circular errors not reported - * This is a cache of the projects before any project addition/deletion has started. + * Workaround for bug 15168 circular errors not reported This is a cache of + * the projects before any project addition/deletion has started. */ public IJavaProject[] javaProjectsCache; /** - * Table from IProject to PerProjectInfo. - * NOTE: this object itself is used as a lock to synchronize creation/removal of per project infos + * Table from IProject to PerProjectInfo. NOTE: this object itself is used + * as a lock to synchronize creation/removal of per project infos */ protected Map perProjectInfo = new HashMap(5); /** - * A map from ICompilationUnit to IWorkingCopy - * of the shared working copies. + * A map from ICompilationUnit to IWorkingCopy of the shared working copies. */ public Map sharedWorkingCopies = new HashMap(); @@ -547,32 +649,41 @@ public class JavaModelManager implements ISaveParticipant { */ protected WeakHashMap searchScopes = new WeakHashMap(); -// public static class PerProjectInfo { -// public IProject project; -// public Object savedState; -// public boolean triedRead; -// public IClasspathEntry[] classpath; -// public IClasspathEntry[] lastResolvedClasspath; -// public Map resolvedPathToRawEntries; // reverse map from resolved path to raw entries -// public IPath outputLocation; -// public Preferences preferences; -// public PerProjectInfo(IProject project) { -// -// this.triedRead = false; -// this.savedState = null; -// this.project = project; -// } -// } + // public static class PerProjectInfo { + // public IProject project; + // public Object savedState; + // public boolean triedRead; + // public IClasspathEntry[] classpath; + // public IClasspathEntry[] lastResolvedClasspath; + // public Map resolvedPathToRawEntries; // reverse map from resolved path to + // raw entries + // public IPath outputLocation; + // public Preferences preferences; + // public PerProjectInfo(IProject project) { + // + // this.triedRead = false; + // this.savedState = null; + // this.project = project; + // } + // } public static class PerProjectInfo { public IProject project; + public Object savedState; + public boolean triedRead; + public IClasspathEntry[] rawClasspath; + public IClasspathEntry[] resolvedClasspath; - public Map resolvedPathToRawEntries; // reverse map from resolved path to raw entries + + public Map resolvedPathToRawEntries; // reverse map from resolved + // path to raw entries + public IPath outputLocation; + public Preferences preferences; public PerProjectInfo(IProject project) { @@ -582,13 +693,16 @@ public class JavaModelManager implements ISaveParticipant { this.project = project; } - // updating raw classpath need to flush obsoleted cached information about resolved entries - public synchronized void updateClasspathInformation(IClasspathEntry[] newRawClasspath) { + // updating raw classpath need to flush obsoleted cached information + // about resolved entries + public synchronized void updateClasspathInformation( + IClasspathEntry[] newRawClasspath) { this.rawClasspath = newRawClasspath; this.resolvedClasspath = null; this.resolvedPathToRawEntries = null; } + public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("Info for "); //$NON-NLS-1$ @@ -626,34 +740,48 @@ public class JavaModelManager implements ISaveParticipant { public static class PerWorkingCopyInfo implements IProblemRequestor { int useCount = 0; + IProblemRequestor problemRequestor; + ICompilationUnit workingCopy; - public PerWorkingCopyInfo(ICompilationUnit workingCopy, IProblemRequestor problemRequestor) { + + public PerWorkingCopyInfo(ICompilationUnit workingCopy, + IProblemRequestor problemRequestor) { this.workingCopy = workingCopy; this.problemRequestor = problemRequestor; } + public void acceptProblem(IProblem problem) { - if (this.problemRequestor == null) return; + if (this.problemRequestor == null) + return; this.problemRequestor.acceptProblem(problem); } + public void beginReporting() { - if (this.problemRequestor == null) return; + if (this.problemRequestor == null) + return; this.problemRequestor.beginReporting(); } + public void endReporting() { - if (this.problemRequestor == null) return; + if (this.problemRequestor == null) + return; this.problemRequestor.endReporting(); } + public ICompilationUnit getWorkingCopy() { return this.workingCopy; } + public boolean isActive() { - return this.problemRequestor != null && this.problemRequestor.isActive(); + return this.problemRequestor != null + && this.problemRequestor.isActive(); } + public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("Info for "); //$NON-NLS-1$ - buffer.append(((JavaElement)workingCopy).toStringWithAncestors()); + buffer.append(((JavaElement) workingCopy).toStringWithAncestors()); buffer.append("\nUse count = "); //$NON-NLS-1$ buffer.append(this.useCount); buffer.append("\nProblem requestor:\n "); //$NON-NLS-1$ @@ -661,47 +789,55 @@ public class JavaModelManager implements ISaveParticipant { return buffer.toString(); } } + public static boolean VERBOSE = false; + public static boolean CP_RESOLVE_VERBOSE = false; + public static boolean ZIP_ACCESS_VERBOSE = false; /** - * A cache of opened zip files per thread. - * (map from Thread to map of IPath to java.io.ZipFile) - * NOTE: this object itself is used as a lock to synchronize creation/removal of entries + * A cache of opened zip files per thread. (map from Thread to map of IPath + * to java.io.ZipFile) NOTE: this object itself is used as a lock to + * synchronize creation/removal of entries */ private HashMap zipFiles = new HashMap(); - /** * Update the classpath variable cache */ - public static class PluginPreferencesListener implements Preferences.IPropertyChangeListener { + public static class PluginPreferencesListener implements + Preferences.IPropertyChangeListener { /** * @see org.eclipse.core.runtime.Preferences.IPropertyChangeListener#propertyChange(PropertyChangeEvent) */ public void propertyChange(Preferences.PropertyChangeEvent event) { -// TODO : jsurfer temp-del -// String propertyName = event.getProperty(); -// if (propertyName.startsWith(CP_VARIABLE_PREFERENCES_PREFIX)) { -// String varName = propertyName.substring(CP_VARIABLE_PREFERENCES_PREFIX.length()); -// String newValue = (String)event.getNewValue(); -// if (newValue != null && !(newValue = newValue.trim()).equals(CP_ENTRY_IGNORE)) { -// Variables.put(varName, new Path(newValue)); -// } else { -// Variables.remove(varName); -// } -// } -// if (propertyName.startsWith(CP_CONTAINER_PREFERENCES_PREFIX)) { -// recreatePersistedContainer(propertyName, (String)event.getNewValue(), false); -// } + // TODO : jsurfer temp-del + // String propertyName = event.getProperty(); + // if (propertyName.startsWith(CP_VARIABLE_PREFERENCES_PREFIX)) { + // String varName = + // propertyName.substring(CP_VARIABLE_PREFERENCES_PREFIX.length()); + // String newValue = (String)event.getNewValue(); + // if (newValue != null && !(newValue = + // newValue.trim()).equals(CP_ENTRY_IGNORE)) { + // Variables.put(varName, new Path(newValue)); + // } else { + // Variables.remove(varName); + // } + // } + // if (propertyName.startsWith(CP_CONTAINER_PREFERENCES_PREFIX)) { + // recreatePersistedContainer(propertyName, + // (String)event.getNewValue(), false); + // } } } /** - * Line separator to use throughout the JavaModel for any source edit operation + * Line separator to use throughout the JavaModel for any source edit + * operation */ - public static String LINE_SEPARATOR = System.getProperty("line.separator"); //$NON-NLS-1$ + public static String LINE_SEPARATOR = System.getProperty("line.separator"); //$NON-NLS-1$ + /** * Constructs a new JavaModelManager */ @@ -712,30 +848,50 @@ public class JavaModelManager implements ISaveParticipant { * @deprecated - discard once debug has converted to not using it */ public void addElementChangedListener(IElementChangedListener listener) { - this.addElementChangedListener(listener, ElementChangedEvent.POST_CHANGE | ElementChangedEvent.POST_RECONCILE); + this.addElementChangedListener(listener, + ElementChangedEvent.POST_CHANGE + | ElementChangedEvent.POST_RECONCILE); } + /** - * addElementChangedListener method comment. - * Need to clone defensively the listener information, in case some listener is reacting to some notification iteration by adding/changing/removing - * any of the other (for example, if it deregisters itself). + * addElementChangedListener method comment. Need to clone defensively the + * listener information, in case some listener is reacting to some + * notification iteration by adding/changing/removing any of the other (for + * example, if it deregisters itself). */ - public void addElementChangedListener(IElementChangedListener listener, int eventMask) { - for (int i = 0; i < this.elementChangedListenerCount; i++){ - if (this.elementChangedListeners[i].equals(listener)){ + public void addElementChangedListener(IElementChangedListener listener, + int eventMask) { + for (int i = 0; i < this.elementChangedListenerCount; i++) { + if (this.elementChangedListeners[i].equals(listener)) { - // only clone the masks, since we could be in the middle of notifications and one listener decide to change + // only clone the masks, since we could be in the middle of + // notifications and one listener decide to change // any event mask of another listeners (yet not notified). int cloneLength = this.elementChangedListenerMasks.length; - System.arraycopy(this.elementChangedListenerMasks, 0, this.elementChangedListenerMasks = new int[cloneLength], 0, cloneLength); - this.elementChangedListenerMasks[i] = eventMask; // could be different + System + .arraycopy( + this.elementChangedListenerMasks, + 0, + this.elementChangedListenerMasks = new int[cloneLength], + 0, cloneLength); + this.elementChangedListenerMasks[i] = eventMask; // could be + // different return; } } - // may need to grow, no need to clone, since iterators will have cached original arrays and max boundary and we only add to the end. + // may need to grow, no need to clone, since iterators will have cached + // original arrays and max boundary and we only add to the end. int length; - if ((length = this.elementChangedListeners.length) == this.elementChangedListenerCount){ - System.arraycopy(this.elementChangedListeners, 0, this.elementChangedListeners = new IElementChangedListener[length*2], 0, length); - System.arraycopy(this.elementChangedListenerMasks, 0, this.elementChangedListenerMasks = new int[length*2], 0, length); + if ((length = this.elementChangedListeners.length) == this.elementChangedListenerCount) { + System + .arraycopy( + this.elementChangedListeners, + 0, + this.elementChangedListeners = new IElementChangedListener[length * 2], + 0, length); + System.arraycopy(this.elementChangedListenerMasks, 0, + this.elementChangedListenerMasks = new int[length * 2], 0, + length); } this.elementChangedListeners[this.elementChangedListenerCount] = listener; this.elementChangedListenerMasks[this.elementChangedListenerCount] = eventMask; @@ -743,25 +899,28 @@ public class JavaModelManager implements ISaveParticipant { } /** - * Starts caching ZipFiles. - * Ignores if there are already clients. + * Starts caching ZipFiles. Ignores if there are already clients. */ public void cacheZipFiles() { - synchronized(this.zipFiles) { + synchronized (this.zipFiles) { Thread currentThread = Thread.currentThread(); - if (this.zipFiles.get(currentThread) != null) return; + if (this.zipFiles.get(currentThread) != null) + return; this.zipFiles.put(currentThread, new HashMap()); } } + public void closeZipFile(ZipFile zipFile) { - if (zipFile == null) return; - synchronized(this.zipFiles) { + if (zipFile == null) + return; + synchronized (this.zipFiles) { if (this.zipFiles.get(Thread.currentThread()) != null) { return; // zip file will be closed by call to flushZipFiles } try { if (JavaModelManager.ZIP_ACCESS_VERBOSE) { - System.out.println("(" + Thread.currentThread() + ") [JavaModelManager.closeZipFile(ZipFile)] Closing ZipFile on " +zipFile.getName()); //$NON-NLS-1$ //$NON-NLS-2$ + System.out + .println("(" + Thread.currentThread() + ") [JavaModelManager.closeZipFile(ZipFile)] Closing ZipFile on " + zipFile.getName()); //$NON-NLS-1$ //$NON-NLS-2$ } zipFile.close(); } catch (IOException e) { @@ -769,75 +928,94 @@ public class JavaModelManager implements ISaveParticipant { } } - - /** - * Configure the plugin with respect to option settings defined in ".options" file + * Configure the plugin with respect to option settings defined in + * ".options" file */ - public void configurePluginDebugOptions(){ - if(JavaCore.getPlugin().isDebugging()){ -// TODO jsurfer temp-del + public void configurePluginDebugOptions() { + if (JavaCore.getPlugin().isDebugging()) { + // TODO jsurfer temp-del String option = Platform.getDebugOption(BUILDER_DEBUG); -// if(option != null) JavaBuilder.DEBUG = option.equalsIgnoreCase("true") ; //$NON-NLS-1$ -// -// option = Platform.getDebugOption(COMPILER_DEBUG); -// if(option != null) Compiler.DEBUG = option.equalsIgnoreCase("true") ; //$NON-NLS-1$ -// -// option = Platform.getDebugOption(COMPLETION_DEBUG); -// if(option != null) CompletionEngine.DEBUG = option.equalsIgnoreCase("true") ; //$NON-NLS-1$ -// + // if(option != null) JavaBuilder.DEBUG = + // option.equalsIgnoreCase("true") ; //$NON-NLS-1$ + // + // option = Platform.getDebugOption(COMPILER_DEBUG); + // if(option != null) Compiler.DEBUG = + // option.equalsIgnoreCase("true") ; //$NON-NLS-1$ + // + // option = Platform.getDebugOption(COMPLETION_DEBUG); + // if(option != null) CompletionEngine.DEBUG = + // option.equalsIgnoreCase("true") ; //$NON-NLS-1$ + // option = Platform.getDebugOption(CP_RESOLVE_DEBUG); - if(option != null) JavaModelManager.CP_RESOLVE_VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$ + if (option != null) + JavaModelManager.CP_RESOLVE_VERBOSE = option + .equalsIgnoreCase("true"); //$NON-NLS-1$ option = Platform.getDebugOption(DELTA_DEBUG); - if(option != null) DeltaProcessor.VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$ + if (option != null) + DeltaProcessor.VERBOSE = option.equalsIgnoreCase("true"); //$NON-NLS-1$ -// option = Platform.getDebugOption(HIERARCHY_DEBUG); -// if(option != null) TypeHierarchy.DEBUG = option.equalsIgnoreCase("true") ; //$NON-NLS-1$ -// -// option = Platform.getDebugOption(INDEX_MANAGER_DEBUG); -// if(option != null) IndexManager.VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$ + // option = Platform.getDebugOption(HIERARCHY_DEBUG); + // if(option != null) TypeHierarchy.DEBUG = + // option.equalsIgnoreCase("true") ; //$NON-NLS-1$ + // + // option = Platform.getDebugOption(INDEX_MANAGER_DEBUG); + // if(option != null) IndexManager.VERBOSE = + // option.equalsIgnoreCase("true") ; //$NON-NLS-1$ option = Platform.getDebugOption(JAVAMODEL_DEBUG); - if(option != null) JavaModelManager.VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$ + if (option != null) + JavaModelManager.VERBOSE = option.equalsIgnoreCase("true"); //$NON-NLS-1$ option = Platform.getDebugOption(POST_ACTION_DEBUG); - if(option != null) JavaModelOperation.POST_ACTION_VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$ - -// option = Platform.getDebugOption(SEARCH_DEBUG); -// if(option != null) SearchEngine.VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$ -// -// option = Platform.getDebugOption(SELECTION_DEBUG); -// if(option != null) SelectionEngine.DEBUG = option.equalsIgnoreCase("true") ; //$NON-NLS-1$ + if (option != null) + JavaModelOperation.POST_ACTION_VERBOSE = option + .equalsIgnoreCase("true"); //$NON-NLS-1$ + + // option = Platform.getDebugOption(SEARCH_DEBUG); + // if(option != null) SearchEngine.VERBOSE = + // option.equalsIgnoreCase("true") ; //$NON-NLS-1$ + // + // option = Platform.getDebugOption(SELECTION_DEBUG); + // if(option != null) SelectionEngine.DEBUG = + // option.equalsIgnoreCase("true") ; //$NON-NLS-1$ option = Platform.getDebugOption(ZIP_ACCESS_DEBUG); - if(option != null) JavaModelManager.ZIP_ACCESS_VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$ + if (option != null) + JavaModelManager.ZIP_ACCESS_VERBOSE = option + .equalsIgnoreCase("true"); //$NON-NLS-1$ } } - /* - * Discards the per working copy info for the given working copy (making it a compilation unit) - * if its use count was 1. Otherwise, just decrement the use count. - * If the working copy is primary, computes the delta between its state and the original compilation unit - * and register it. - * Close the working copy, its buffer and remove it from the shared working copy table. - * Ignore if no per-working copy info existed. - * NOTE: it must be synchronized as it may interact with the element info cache (if useCount is decremented to 0), see bug 50667. - * Returns the new use count (or -1 if it didn't exist). - */ - public synchronized int discardPerWorkingCopyInfo(CompilationUnit workingCopy) throws JavaModelException { - synchronized(perWorkingCopyInfos) { + * Discards the per working copy info for the given working copy (making it + * a compilation unit) if its use count was 1. Otherwise, just decrement the + * use count. If the working copy is primary, computes the delta between its + * state and the original compilation unit and register it. Close the + * working copy, its buffer and remove it from the shared working copy + * table. Ignore if no per-working copy info existed. NOTE: it must be + * synchronized as it may interact with the element info cache (if useCount + * is decremented to 0), see bug 50667. Returns the new use count (or -1 if + * it didn't exist). + */ + public synchronized int discardPerWorkingCopyInfo( + CompilationUnit workingCopy) throws JavaModelException { + synchronized (perWorkingCopyInfos) { WorkingCopyOwner owner = workingCopy.owner; - Map workingCopyToInfos = (Map)this.perWorkingCopyInfos.get(owner); - if (workingCopyToInfos == null) return -1; + Map workingCopyToInfos = (Map) this.perWorkingCopyInfos.get(owner); + if (workingCopyToInfos == null) + return -1; - PerWorkingCopyInfo info = (PerWorkingCopyInfo)workingCopyToInfos.get(workingCopy); - if (info == null) return -1; + PerWorkingCopyInfo info = (PerWorkingCopyInfo) workingCopyToInfos + .get(workingCopy); + if (info == null) + return -1; if (--info.useCount == 0) { - // create the delta builder (this remembers the current content of the working copy) + // create the delta builder (this remembers the current content + // of the working copy) JavaElementDeltaBuilder deltaBuilder = null; if (workingCopy.isPrimary()) { deltaBuilder = new JavaElementDeltaBuilder(workingCopy); @@ -853,11 +1031,14 @@ public class JavaModelManager implements ISaveParticipant { removeInfoAndChildren(workingCopy); workingCopy.closeBuffer(); - // compute the delta if needed and register it if there are changes + // compute the delta if needed and register it if there are + // changes if (deltaBuilder != null) { deltaBuilder.buildDeltas(); - if ((deltaBuilder.delta != null) && (deltaBuilder.delta.getAffectedChildren().length > 0)) { - getDeltaProcessor().registerJavaModelDelta(deltaBuilder.delta); + if ((deltaBuilder.delta != null) + && (deltaBuilder.delta.getAffectedChildren().length > 0)) { + getDeltaProcessor().registerJavaModelDelta( + deltaBuilder.delta); } } @@ -869,23 +1050,26 @@ public class JavaModelManager implements ISaveParticipant { /** * @see ISaveParticipant */ - public void doneSaving(ISaveContext context){ + public void doneSaving(ISaveContext context) { } /** - * Fire Java Model delta, flushing them after the fact after post_change notification. - * If the firing mode has been turned off, this has no effect. + * Fire Java Model delta, flushing them after the fact after post_change + * notification. If the firing mode has been turned off, this has no effect. */ public void fire(IJavaElementDelta customDelta, int eventType) { - if (!this.isFiring) return; + if (!this.isFiring) + return; - if (DeltaProcessor.VERBOSE && (eventType == DEFAULT_CHANGE_EVENT || eventType == ElementChangedEvent.PRE_AUTO_BUILD)) { - System.out.println("-----------------------------------------------------------------------------------------------------------------------");//$NON-NLS-1$ + if (DeltaProcessor.VERBOSE + && (eventType == DEFAULT_CHANGE_EVENT || eventType == ElementChangedEvent.PRE_AUTO_BUILD)) { + System.out + .println("-----------------------------------------------------------------------------------------------------------------------");//$NON-NLS-1$ } IJavaElementDelta deltaToNotify; - if (customDelta == null){ + if (customDelta == null) { deltaToNotify = this.mergeDeltas(this.javaModelDeltas); } else { deltaToNotify = customDelta; @@ -893,112 +1077,133 @@ public class JavaModelManager implements ISaveParticipant { // Refresh internal scopes if (deltaToNotify != null) { -// TODO temp-del -// Iterator scopes = this.scopes.keySet().iterator(); -// while (scopes.hasNext()) { -// AbstractSearchScope scope = (AbstractSearchScope)scopes.next(); -// scope.processDelta(deltaToNotify); -// } + // TODO temp-del + // Iterator scopes = this.scopes.keySet().iterator(); + // while (scopes.hasNext()) { + // AbstractSearchScope scope = (AbstractSearchScope)scopes.next(); + // scope.processDelta(deltaToNotify); + // } } // Notification - // Important: if any listener reacts to notification by updating the listeners list or mask, these lists will - // be duplicated, so it is necessary to remember original lists in a variable (since field values may change under us) + // Important: if any listener reacts to notification by updating the + // listeners list or mask, these lists will + // be duplicated, so it is necessary to remember original lists in a + // variable (since field values may change under us) IElementChangedListener[] listeners = this.elementChangedListeners; int[] listenerMask = this.elementChangedListenerMasks; int listenerCount = this.elementChangedListenerCount; switch (eventType) { - case DEFAULT_CHANGE_EVENT: - firePreAutoBuildDelta(deltaToNotify, listeners, listenerMask, listenerCount); - firePostChangeDelta(deltaToNotify, listeners, listenerMask, listenerCount); - fireReconcileDelta(listeners, listenerMask, listenerCount); - break; - case ElementChangedEvent.PRE_AUTO_BUILD: - firePreAutoBuildDelta(deltaToNotify, listeners, listenerMask, listenerCount); - break; - case ElementChangedEvent.POST_CHANGE: - firePostChangeDelta(deltaToNotify, listeners, listenerMask, listenerCount); - fireReconcileDelta(listeners, listenerMask, listenerCount); - break; - } + case DEFAULT_CHANGE_EVENT: + firePreAutoBuildDelta(deltaToNotify, listeners, listenerMask, + listenerCount); + firePostChangeDelta(deltaToNotify, listeners, listenerMask, + listenerCount); + fireReconcileDelta(listeners, listenerMask, listenerCount); + break; + case ElementChangedEvent.PRE_AUTO_BUILD: + firePreAutoBuildDelta(deltaToNotify, listeners, listenerMask, + listenerCount); + break; + case ElementChangedEvent.POST_CHANGE: + firePostChangeDelta(deltaToNotify, listeners, listenerMask, + listenerCount); + fireReconcileDelta(listeners, listenerMask, listenerCount); + break; + } + + } + + private void firePreAutoBuildDelta(IJavaElementDelta deltaToNotify, + IElementChangedListener[] listeners, int[] listenerMask, + int listenerCount) { - } - - private void firePreAutoBuildDelta( - IJavaElementDelta deltaToNotify, - IElementChangedListener[] listeners, - int[] listenerMask, - int listenerCount) { - - if (DeltaProcessor.VERBOSE){ - System.out.println("FIRING PRE_AUTO_BUILD Delta ["+Thread.currentThread()+"]:"); //$NON-NLS-1$//$NON-NLS-2$ - System.out.println(deltaToNotify == null ? "" : deltaToNotify.toString()); //$NON-NLS-1$ + if (DeltaProcessor.VERBOSE) { + System.out + .println("FIRING PRE_AUTO_BUILD Delta [" + Thread.currentThread() + "]:"); //$NON-NLS-1$//$NON-NLS-2$ + System.out + .println(deltaToNotify == null ? "" : deltaToNotify.toString()); //$NON-NLS-1$ } if (deltaToNotify != null) { - notifyListeners(deltaToNotify, ElementChangedEvent.PRE_AUTO_BUILD, listeners, listenerMask, listenerCount); + notifyListeners(deltaToNotify, ElementChangedEvent.PRE_AUTO_BUILD, + listeners, listenerMask, listenerCount); } } - private void firePostChangeDelta( - IJavaElementDelta deltaToNotify, - IElementChangedListener[] listeners, - int[] listenerMask, - int listenerCount) { + private void firePostChangeDelta(IJavaElementDelta deltaToNotify, + IElementChangedListener[] listeners, int[] listenerMask, + int listenerCount) { // post change deltas - if (DeltaProcessor.VERBOSE){ - System.out.println("FIRING POST_CHANGE Delta ["+Thread.currentThread()+"]:"); //$NON-NLS-1$//$NON-NLS-2$ - System.out.println(deltaToNotify == null ? "" : deltaToNotify.toString()); //$NON-NLS-1$ + if (DeltaProcessor.VERBOSE) { + System.out + .println("FIRING POST_CHANGE Delta [" + Thread.currentThread() + "]:"); //$NON-NLS-1$//$NON-NLS-2$ + System.out + .println(deltaToNotify == null ? "" : deltaToNotify.toString()); //$NON-NLS-1$ } if (deltaToNotify != null) { - // flush now so as to keep listener reactions to post their own deltas for subsequent iteration + // flush now so as to keep listener reactions to post their own + // deltas for subsequent iteration this.flush(); - notifyListeners(deltaToNotify, ElementChangedEvent.POST_CHANGE, listeners, listenerMask, listenerCount); + notifyListeners(deltaToNotify, ElementChangedEvent.POST_CHANGE, + listeners, listenerMask, listenerCount); } } - private void fireReconcileDelta( - IElementChangedListener[] listeners, - int[] listenerMask, - int listenerCount) { + private void fireReconcileDelta(IElementChangedListener[] listeners, + int[] listenerMask, int listenerCount) { - IJavaElementDelta deltaToNotify = mergeDeltas(this.reconcileDeltas.values()); - if (DeltaProcessor.VERBOSE){ - System.out.println("FIRING POST_RECONCILE Delta ["+Thread.currentThread()+"]:"); //$NON-NLS-1$//$NON-NLS-2$ - System.out.println(deltaToNotify == null ? "" : deltaToNotify.toString()); //$NON-NLS-1$ + IJavaElementDelta deltaToNotify = mergeDeltas(this.reconcileDeltas + .values()); + if (DeltaProcessor.VERBOSE) { + System.out + .println("FIRING POST_RECONCILE Delta [" + Thread.currentThread() + "]:"); //$NON-NLS-1$//$NON-NLS-2$ + System.out + .println(deltaToNotify == null ? "" : deltaToNotify.toString()); //$NON-NLS-1$ } if (deltaToNotify != null) { - // flush now so as to keep listener reactions to post their own deltas for subsequent iteration + // flush now so as to keep listener reactions to post their own + // deltas for subsequent iteration this.reconcileDeltas = new HashMap(); - notifyListeners(deltaToNotify, ElementChangedEvent.POST_RECONCILE, listeners, listenerMask, listenerCount); + notifyListeners(deltaToNotify, ElementChangedEvent.POST_RECONCILE, + listeners, listenerMask, listenerCount); } } - public void notifyListeners(IJavaElementDelta deltaToNotify, int eventType, IElementChangedListener[] listeners, int[] listenerMask, int listenerCount) { - final ElementChangedEvent extraEvent = new ElementChangedEvent(deltaToNotify, eventType); - for (int i= 0; i < listenerCount; i++) { - if ((listenerMask[i] & eventType) != 0){ + public void notifyListeners(IJavaElementDelta deltaToNotify, int eventType, + IElementChangedListener[] listeners, int[] listenerMask, + int listenerCount) { + final ElementChangedEvent extraEvent = new ElementChangedEvent( + deltaToNotify, eventType); + for (int i = 0; i < listenerCount; i++) { + if ((listenerMask[i] & eventType) != 0) { final IElementChangedListener listener = listeners[i]; long start = -1; if (DeltaProcessor.VERBOSE) { - System.out.print("Listener #" + (i+1) + "=" + listener.toString());//$NON-NLS-1$//$NON-NLS-2$ + System.out + .print("Listener #" + (i + 1) + "=" + listener.toString());//$NON-NLS-1$//$NON-NLS-2$ start = System.currentTimeMillis(); } - // wrap callbacks with Safe runnable for subsequent listeners to be called when some are causing grief + // wrap callbacks with Safe runnable for subsequent listeners to + // be called when some are causing grief Platform.run(new ISafeRunnable() { public void handleException(Throwable exception) { - Util.log(exception, "Exception occurred in listener of Java element change notification"); //$NON-NLS-1$ + Util + .log(exception, + "Exception occurred in listener of Java element change notification"); //$NON-NLS-1$ } + public void run() throws Exception { listener.elementChanged(extraEvent); } }); if (DeltaProcessor.VERBOSE) { - System.out.println(" -> " + (System.currentTimeMillis()-start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ + System.out + .println(" -> " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ } } } @@ -1015,16 +1220,18 @@ public class JavaModelManager implements ISaveParticipant { * Flushes ZipFiles cache if there are no more clients. */ public void flushZipFiles() { - synchronized(this.zipFiles) { + synchronized (this.zipFiles) { Thread currentThread = Thread.currentThread(); - HashMap map = (HashMap)this.zipFiles.remove(currentThread); - if (map == null) return; + HashMap map = (HashMap) this.zipFiles.remove(currentThread); + if (map == null) + return; Iterator iterator = map.values().iterator(); while (iterator.hasNext()) { try { - ZipFile zipFile = (ZipFile)iterator.next(); + ZipFile zipFile = (ZipFile) iterator.next(); if (JavaModelManager.ZIP_ACCESS_VERBOSE) { - System.out.println("(" + currentThread + ") [JavaModelManager.flushZipFiles()] Closing ZipFile on " +zipFile.getName()); //$NON-NLS-1$//$NON-NLS-2$ + System.out + .println("(" + currentThread + ") [JavaModelManager.flushZipFiles()] Closing ZipFile on " + zipFile.getName()); //$NON-NLS-1$//$NON-NLS-2$ } zipFile.close(); } catch (IOException e) { @@ -1033,10 +1240,10 @@ public class JavaModelManager implements ISaveParticipant { } } - public DeltaProcessor getDeltaProcessor() { return this.deltaState.getDeltaProcessor(); } + /** * Returns the set of elements which are out of synch with their buffers. */ @@ -1044,69 +1251,79 @@ public class JavaModelManager implements ISaveParticipant { return this.elementsOutOfSynchWithBuffers; } -// public IndexManager getIndexManager() { -// return this.indexManager; -// } + // public IndexManager getIndexManager() { + // return this.indexManager; + // } /** * Returns the IJavaElement represented by the * String memento. */ - public IJavaElement getHandleFromMemento(String memento) throws JavaModelException { + public IJavaElement getHandleFromMemento(String memento) + throws JavaModelException { if (memento == null) { return null; } - JavaModel model= (JavaModel) getJavaModel(); - if (memento.equals("")){ // workspace memento //$NON-NLS-1$ + JavaModel model = (JavaModel) getJavaModel(); + if (memento.equals("")) { // workspace memento //$NON-NLS-1$ return model; } - int modelEnd= memento.indexOf(JavaElement.JEM_JAVAPROJECT); + int modelEnd = memento.indexOf(JavaElement.JEM_JAVAPROJECT); if (modelEnd == -1) { return null; } - boolean returnProject= false; - int projectEnd= memento.indexOf(JavaElement.JEM_PACKAGEFRAGMENTROOT, modelEnd); + boolean returnProject = false; + int projectEnd = memento.indexOf(JavaElement.JEM_PACKAGEFRAGMENTROOT, + modelEnd); if (projectEnd == -1) { - projectEnd= memento.length(); - returnProject= true; + projectEnd = memento.length(); + returnProject = true; } - String projectName= memento.substring(modelEnd + 1, projectEnd); - JavaProject proj= (JavaProject) model.getJavaProject(projectName); + String projectName = memento.substring(modelEnd + 1, projectEnd); + JavaProject proj = (JavaProject) model.getJavaProject(projectName); if (returnProject) { return proj; } - int rootEnd= memento.indexOf(JavaElement.JEM_PACKAGEFRAGMENT, projectEnd + 1); -// TODO temp-del -// if (rootEnd == -1) { -// return model.getHandleFromMementoForRoot(memento, proj, projectEnd, memento.length()); -// } -// IPackageFragmentRoot root = model.getHandleFromMementoForRoot(memento, proj, projectEnd, rootEnd); -// if (root == null) -// return null; -// -// int end= memento.indexOf(JavaElement.JEM_COMPILATIONUNIT, rootEnd); -// if (end == -1) { -// end= memento.indexOf(JavaElement.JEM_CLASSFILE, rootEnd); -// if (end == -1) { -// if (rootEnd + 1 == memento.length()) { -// return root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME); -// } else { -// return root.getPackageFragment(memento.substring(rootEnd + 1)); -// } -// } -// //deal with class file and binary members -// return model.getHandleFromMementoForBinaryMembers(memento, root, rootEnd, end); -// } -// -// //deal with compilation units and source members -// return model.getHandleFromMementoForSourceMembers(memento, root, rootEnd, end); - return null; - } -// public IndexManager getIndexManager() { -// return this.deltaProcessor.indexManager; -// } - - /** - * Returns the info for the element. + int rootEnd = memento.indexOf(JavaElement.JEM_PACKAGEFRAGMENT, + projectEnd + 1); + // TODO temp-del + // if (rootEnd == -1) { + // return model.getHandleFromMementoForRoot(memento, proj, projectEnd, + // memento.length()); + // } + // IPackageFragmentRoot root = + // model.getHandleFromMementoForRoot(memento, proj, projectEnd, + // rootEnd); + // if (root == null) + // return null; + // + // int end= memento.indexOf(JavaElement.JEM_COMPILATIONUNIT, rootEnd); + // if (end == -1) { + // end= memento.indexOf(JavaElement.JEM_CLASSFILE, rootEnd); + // if (end == -1) { + // if (rootEnd + 1 == memento.length()) { + // return + // root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME); + // } else { + // return root.getPackageFragment(memento.substring(rootEnd + 1)); + // } + // } + // //deal with class file and binary members + // return model.getHandleFromMementoForBinaryMembers(memento, root, + // rootEnd, end); + // } + // + // //deal with compilation units and source members + // return model.getHandleFromMementoForSourceMembers(memento, root, + // rootEnd, end); + return null; + } + + // public IndexManager getIndexManager() { + // return this.deltaProcessor.indexManager; + // } + + /** + * Returns the info for the element. */ public Object getInfo(IJavaElement element) { return this.cache.getInfo(element); @@ -1127,19 +1344,24 @@ public class JavaModelManager implements ISaveParticipant { } /** - * Returns the last built state for the given project, or null if there is none. - * Deserializes the state if necessary. - * + * Returns the last built state for the given project, or null if there is + * none. Deserializes the state if necessary. + * * For use by image builder and evaluation support only */ public Object getLastBuiltState(IProject project, IProgressMonitor monitor) { - if (!JavaProject.hasJavaNature(project)) return null; // should never be requested on non-Java projects - PerProjectInfo info = getPerProjectInfo(project, true/*create if missing*/); + if (!JavaProject.hasJavaNature(project)) + return null; // should never be requested on non-Java projects + PerProjectInfo info = getPerProjectInfo(project, true/* + * create if + * missing + */); if (!info.triedRead) { info.triedRead = true; try { if (monitor != null) - monitor.subTask(Util.bind("build.readStateProgress", project.getName())); //$NON-NLS-1$ + monitor.subTask(Util.bind( + "build.readStateProgress", project.getName())); //$NON-NLS-1$ info.savedState = readState(project); } catch (CoreException e) { e.printStackTrace(); @@ -1149,13 +1371,15 @@ public class JavaModelManager implements ISaveParticipant { } /* - * Returns the per-project info for the given project. If specified, create the info if the info doesn't exist. + * Returns the per-project info for the given project. If specified, create + * the info if the info doesn't exist. */ public PerProjectInfo getPerProjectInfo(IProject project, boolean create) { - synchronized(perProjectInfo) { // use the perProjectInfo collection as its own lock - PerProjectInfo info= (PerProjectInfo) perProjectInfo.get(project); + synchronized (perProjectInfo) { // use the perProjectInfo collection as + // its own lock + PerProjectInfo info = (PerProjectInfo) perProjectInfo.get(project); if (info == null && create) { - info= new PerProjectInfo(project); + info = new PerProjectInfo(project); perProjectInfo.put(project, info); } return info; @@ -1163,163 +1387,202 @@ public class JavaModelManager implements ISaveParticipant { } /* - * Returns the per-project info for the given project. - * If the info doesn't exist, check for the project existence and create the info. - * @throws JavaModelException if the project doesn't exist. - */ - public PerProjectInfo getPerProjectInfoCheckExistence(IProject project) throws JavaModelException { - JavaModelManager.PerProjectInfo info = getPerProjectInfo(project, false /* don't create info */); + * Returns the per-project info for the given project. If the info doesn't + * exist, check for the project existence and create the info. @throws + * JavaModelException if the project doesn't exist. + */ + public PerProjectInfo getPerProjectInfoCheckExistence(IProject project) + throws JavaModelException { + JavaModelManager.PerProjectInfo info = getPerProjectInfo(project, false /* + * don't + * create + * info + */); if (info == null) { if (!JavaProject.hasJavaNature(project)) { - throw ((JavaProject)JavaCore.create(project)).newNotPresentException(); + throw ((JavaProject) JavaCore.create(project)) + .newNotPresentException(); } info = getPerProjectInfo(project, true /* create info */); } return info; } + /* - * Returns the per-working copy info for the given working copy at the given path. - * If it doesn't exist and if create, add a new per-working copy info with the given problem requestor. - * If recordUsage, increment the per-working copy info's use count. - * Returns null if it doesn't exist and not create. - */ - public PerWorkingCopyInfo getPerWorkingCopyInfo(CompilationUnit workingCopy,boolean create, boolean recordUsage, IProblemRequestor problemRequestor) { - synchronized(perWorkingCopyInfos) { // use the perWorkingCopyInfo collection as its own lock + * Returns the per-working copy info for the given working copy at the given + * path. If it doesn't exist and if create, add a new per-working copy info + * with the given problem requestor. If recordUsage, increment the + * per-working copy info's use count. Returns null if it doesn't exist and + * not create. + */ + public PerWorkingCopyInfo getPerWorkingCopyInfo( + CompilationUnit workingCopy, boolean create, boolean recordUsage, + IProblemRequestor problemRequestor) { + synchronized (perWorkingCopyInfos) { // use the perWorkingCopyInfo + // collection as its own lock WorkingCopyOwner owner = workingCopy.owner; - Map workingCopyToInfos = (Map)this.perWorkingCopyInfos.get(owner); + Map workingCopyToInfos = (Map) this.perWorkingCopyInfos.get(owner); if (workingCopyToInfos == null && create) { workingCopyToInfos = new HashMap(); this.perWorkingCopyInfos.put(owner, workingCopyToInfos); } - PerWorkingCopyInfo info = workingCopyToInfos == null ? null : (PerWorkingCopyInfo) workingCopyToInfos.get(workingCopy); + PerWorkingCopyInfo info = workingCopyToInfos == null ? null + : (PerWorkingCopyInfo) workingCopyToInfos.get(workingCopy); if (info == null && create) { - info= new PerWorkingCopyInfo(workingCopy, problemRequestor); + info = new PerWorkingCopyInfo(workingCopy, problemRequestor); workingCopyToInfos.put(workingCopy, info); } - if (info != null && recordUsage) info.useCount++; + if (info != null && recordUsage) + info.useCount++; return info; } } + /** - * Returns the name of the variables for which an CP variable initializer is registered through an extension point - */ - public static String[] getRegisteredVariableNames(){ + * Returns the name of the variables for which an CP variable initializer is + * registered through an extension point + */ + public static String[] getRegisteredVariableNames() { Plugin jdtCorePlugin = JavaCore.getPlugin(); - if (jdtCorePlugin == null) return null; + if (jdtCorePlugin == null) + return null; ArrayList variableList = new ArrayList(5); -// IExtensionPoint extension = jdtCorePlugin.getDescriptor().getExtensionPoint(JavaModelManager.CPVARIABLE_INITIALIZER_EXTPOINT_ID); -// if (extension != null) { -// IExtension[] extensions = extension.getExtensions(); -// for(int i = 0; i < extensions.length; i++){ -// IConfigurationElement [] configElements = extensions[i].getConfigurationElements(); -// for(int j = 0; j < configElements.length; j++){ -// String varAttribute = configElements[j].getAttribute("variable"); //$NON-NLS-1$ -// if (varAttribute != null) variableList.add(varAttribute); -// } -// } -// } + // IExtensionPoint extension = + // jdtCorePlugin.getDescriptor().getExtensionPoint(JavaModelManager.CPVARIABLE_INITIALIZER_EXTPOINT_ID); + // if (extension != null) { + // IExtension[] extensions = extension.getExtensions(); + // for(int i = 0; i < extensions.length; i++){ + // IConfigurationElement [] configElements = + // extensions[i].getConfigurationElements(); + // for(int j = 0; j < configElements.length; j++){ + // String varAttribute = configElements[j].getAttribute("variable"); + // //$NON-NLS-1$ + // if (varAttribute != null) variableList.add(varAttribute); + // } + // } + // } String[] variableNames = new String[variableList.size()]; variableList.toArray(variableNames); return variableNames; } /** - * Returns the name of the container IDs for which an CP container initializer is registered through an extension point - */ -// public static String[] getRegisteredContainerIDs(){ -// -// Plugin jdtCorePlugin = PHPCore.getPlugin(); -// if (jdtCorePlugin == null) return null; -// -// ArrayList containerIDList = new ArrayList(5); -// IExtensionPoint extension = jdtCorePlugin.getDescriptor().getExtensionPoint(JavaModelManager.CPCONTAINER_INITIALIZER_EXTPOINT_ID); -// if (extension != null) { -// IExtension[] extensions = extension.getExtensions(); -// for(int i = 0; i < extensions.length; i++){ -// IConfigurationElement [] configElements = extensions[i].getConfigurationElements(); -// for(int j = 0; j < configElements.length; j++){ -// String idAttribute = configElements[j].getAttribute("id"); //$NON-NLS-1$ -// if (idAttribute != null) containerIDList.add(idAttribute); -// } -// } -// } -// String[] containerIDs = new String[containerIDList.size()]; -// containerIDList.toArray(containerIDs); -// return containerIDs; -// } - - /** - * Returns the File to use for saving and restoring the last built state for the given project. + * Returns the name of the container IDs for which an CP container + * initializer is registered through an extension point + */ + // public static String[] getRegisteredContainerIDs(){ + // + // Plugin jdtCorePlugin = PHPCore.getPlugin(); + // if (jdtCorePlugin == null) return null; + // + // ArrayList containerIDList = new ArrayList(5); + // IExtensionPoint extension = + // jdtCorePlugin.getDescriptor().getExtensionPoint(JavaModelManager.CPCONTAINER_INITIALIZER_EXTPOINT_ID); + // if (extension != null) { + // IExtension[] extensions = extension.getExtensions(); + // for(int i = 0; i < extensions.length; i++){ + // IConfigurationElement [] configElements = + // extensions[i].getConfigurationElements(); + // for(int j = 0; j < configElements.length; j++){ + // String idAttribute = configElements[j].getAttribute("id"); //$NON-NLS-1$ + // if (idAttribute != null) containerIDList.add(idAttribute); + // } + // } + // } + // String[] containerIDs = new String[containerIDList.size()]; + // containerIDList.toArray(containerIDs); + // return containerIDs; + // } + /** + * Returns the File to use for saving and restoring the last built state for + * the given project. */ private File getSerializationFile(IProject project) { - if (!project.exists()) return null; + if (!project.exists()) + return null; IPath workingLocation = project.getWorkingLocation(JavaCore.PLUGIN_ID); return workingLocation.append("state.dat").toFile(); //$NON-NLS-1$ } /* - * Returns the temporary cache for newly opened elements for the current thread. - * Creates it if not already created. + * Returns the temporary cache for newly opened elements for the current + * thread. Creates it if not already created. */ public HashMap getTemporaryCache() { - HashMap result = (HashMap)this.temporaryCache.get(); + HashMap result = (HashMap) this.temporaryCache.get(); if (result == null) { result = new HashMap(); this.temporaryCache.set(result); } return result; } + /** - * Returns the open ZipFile at the given location. If the ZipFile - * does not yet exist, it is created, opened, and added to the cache - * of open ZipFiles. The location must be a absolute path. - * - * @exception CoreException If unable to create/open the ZipFile + * Returns the open ZipFile at the given location. If the ZipFile does not + * yet exist, it is created, opened, and added to the cache of open + * ZipFiles. The location must be a absolute path. + * + * @exception CoreException + * If unable to create/open the ZipFile */ public ZipFile getZipFile(IPath path) throws CoreException { - synchronized(this.zipFiles) { // TODO: use PeThreadObject which does synchronization + synchronized (this.zipFiles) { // TODO: use PeThreadObject which does + // synchronization Thread currentThread = Thread.currentThread(); HashMap map = null; ZipFile zipFile; - if ((map = (HashMap)this.zipFiles.get(currentThread)) != null - && (zipFile = (ZipFile)map.get(path)) != null) { + if ((map = (HashMap) this.zipFiles.get(currentThread)) != null + && (zipFile = (ZipFile) map.get(path)) != null) { return zipFile; } - String fileSystemPath= null; + String fileSystemPath = null; IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IResource file = root.findMember(path); if (path.isAbsolute() && file != null) { if (file == null) { // external file - fileSystemPath= path.toOSString(); + fileSystemPath = path.toOSString(); } else { // internal resource (not an IFile or not existing) IPath location; - if (file.getType() != IResource.FILE || (location = file.getLocation()) == null) { - throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("file.notFound", path.toString()), null)); //$NON-NLS-1$ + if (file.getType() != IResource.FILE + || (location = file.getLocation()) == null) { + throw new CoreException( + new Status( + IStatus.ERROR, + JavaCore.PLUGIN_ID, + -1, + Util + .bind( + "file.notFound", path.toString()), null)); //$NON-NLS-1$ } - fileSystemPath= location.toOSString(); + fileSystemPath = location.toOSString(); } } else if (!path.isAbsolute()) { - file= root.getFile(path); + file = root.getFile(path); if (file == null || file.getType() != IResource.FILE) { - throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("file.notFound", path.toString()), null)); //$NON-NLS-1$ + throw new CoreException(new Status(IStatus.ERROR, + JavaCore.PLUGIN_ID, -1, Util.bind( + "file.notFound", path.toString()), null)); //$NON-NLS-1$ } IPath location = file.getLocation(); if (location == null) { - throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("file.notFound", path.toString()), null)); //$NON-NLS-1$ + throw new CoreException(new Status(IStatus.ERROR, + JavaCore.PLUGIN_ID, -1, Util.bind( + "file.notFound", path.toString()), null)); //$NON-NLS-1$ } - fileSystemPath= location.toOSString(); + fileSystemPath = location.toOSString(); } else { - fileSystemPath= path.toOSString(); + fileSystemPath = path.toOSString(); } try { if (ZIP_ACCESS_VERBOSE) { - System.out.println("(" + currentThread + ") [JavaModelManager.getZipFile(IPath)] Creating ZipFile on " + fileSystemPath ); //$NON-NLS-1$ //$NON-NLS-2$ + System.out + .println("(" + currentThread + ") [JavaModelManager.getZipFile(IPath)] Creating ZipFile on " + fileSystemPath); //$NON-NLS-1$ //$NON-NLS-2$ } zipFile = new ZipFile(fileSystemPath); if (map != null) { @@ -1327,119 +1590,138 @@ public class JavaModelManager implements ISaveParticipant { } return zipFile; } catch (IOException e) { - throw new CoreException(new Status(Status.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("status.IOException"), e)); //$NON-NLS-1$ + throw new CoreException(new Status(Status.ERROR, + JavaCore.PLUGIN_ID, -1, + Util.bind("status.IOException"), e)); //$NON-NLS-1$ } } } + /* * Returns whether there is a temporary cache for the current thread. */ public boolean hasTemporaryCache() { return this.temporaryCache.get() != null; } -// public void loadVariablesAndContainers() throws CoreException { -// -// // backward compatibility, consider persistent property -// QualifiedName qName = new QualifiedName(PHPCore.PLUGIN_ID, "variables"); //$NON-NLS-1$ -// String xmlString = ResourcesPlugin.getWorkspace().getRoot().getPersistentProperty(qName); -// -// try { -// if (xmlString != null){ -// StringReader reader = new StringReader(xmlString); -// Element cpElement; -// try { -// DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); -// cpElement = parser.parse(new InputSource(reader)).getDocumentElement(); -// } catch(SAXException e) { -// return; -// } catch(ParserConfigurationException e){ -// return; -// } finally { -// reader.close(); -// } -// if (cpElement == null) return; -// if (!cpElement.getNodeName().equalsIgnoreCase("variables")) { //$NON-NLS-1$ -// return; -// } -// -// NodeList list= cpElement.getChildNodes(); -// int length= list.getLength(); -// for (int i= 0; i < length; ++i) { -// Node node= list.item(i); -// short type= node.getNodeType(); -// if (type == Node.ELEMENT_NODE) { -// Element element= (Element) node; -// if (element.getNodeName().equalsIgnoreCase("variable")) { //$NON-NLS-1$ -// variablePut( -// element.getAttribute("name"), //$NON-NLS-1$ -// new Path(element.getAttribute("path"))); //$NON-NLS-1$ -// } -// } -// } -// } -// } catch(IOException e){ -// } finally { -// if (xmlString != null){ -// ResourcesPlugin.getWorkspace().getRoot().setPersistentProperty(qName, null); // flush old one -// } -// -// } -// -// // load variables and containers from preferences into cache -// Preferences preferences = PHPeclipsePlugin.getDefault().getPluginPreferences(); - -// // only get variable from preferences not set to their default -// String[] propertyNames = preferences.propertyNames(); -// int variablePrefixLength = CP_VARIABLE_PREFERENCES_PREFIX.length(); -// for (int i = 0; i < propertyNames.length; i++){ -// String propertyName = propertyNames[i]; -// if (propertyName.startsWith(CP_VARIABLE_PREFERENCES_PREFIX)){ -// String varName = propertyName.substring(variablePrefixLength); -// IPath varPath = new Path(preferences.getString(propertyName).trim()); -// -// Variables.put(varName, varPath); -// PreviousSessionVariables.put(varName, varPath); -// } -// if (propertyName.startsWith(CP_CONTAINER_PREFERENCES_PREFIX)){ -// recreatePersistedContainer(propertyName, preferences.getString(propertyName), true/*add to container values*/); -// } -// } -// // override persisted values for variables which have a registered initializer -// String[] registeredVariables = getRegisteredVariableNames(); -// for (int i = 0; i < registeredVariables.length; i++) { -// String varName = registeredVariables[i]; -// Variables.put(varName, null); // reset variable, but leave its entry in the Map, so it will be part of variable names. -// } -// // override persisted values for containers which have a registered initializer -// String[] registeredContainerIDs = getRegisteredContainerIDs(); -// for (int i = 0; i < registeredContainerIDs.length; i++) { -// String containerID = registeredContainerIDs[i]; -// Iterator projectIterator = Containers.keySet().iterator(); -// while (projectIterator.hasNext()){ -// IJavaProject project = (IJavaProject)projectIterator.next(); -// Map projectContainers = (Map)Containers.get(project); -// if (projectContainers != null){ -// Iterator containerIterator = projectContainers.keySet().iterator(); -// while (containerIterator.hasNext()){ -// IPath containerPath = (IPath)containerIterator.next(); -// if (containerPath.segment(0).equals(containerID)) { // registered container -// projectContainers.put(containerPath, null); // reset container value, but leave entry in Map -// } -// } -// } -// } -// } -// } + + // public void loadVariablesAndContainers() throws CoreException { + // + // // backward compatibility, consider persistent property + // QualifiedName qName = new QualifiedName(PHPCore.PLUGIN_ID, "variables"); + // //$NON-NLS-1$ + // String xmlString = + // ResourcesPlugin.getWorkspace().getRoot().getPersistentProperty(qName); + // + // try { + // if (xmlString != null){ + // StringReader reader = new StringReader(xmlString); + // Element cpElement; + // try { + // DocumentBuilder parser = + // DocumentBuilderFactory.newInstance().newDocumentBuilder(); + // cpElement = parser.parse(new InputSource(reader)).getDocumentElement(); + // } catch(SAXException e) { + // return; + // } catch(ParserConfigurationException e){ + // return; + // } finally { + // reader.close(); + // } + // if (cpElement == null) return; + // if (!cpElement.getNodeName().equalsIgnoreCase("variables")) { + // //$NON-NLS-1$ + // return; + // } + // + // NodeList list= cpElement.getChildNodes(); + // int length= list.getLength(); + // for (int i= 0; i < length; ++i) { + // Node node= list.item(i); + // short type= node.getNodeType(); + // if (type == Node.ELEMENT_NODE) { + // Element element= (Element) node; + // if (element.getNodeName().equalsIgnoreCase("variable")) { //$NON-NLS-1$ + // variablePut( + // element.getAttribute("name"), //$NON-NLS-1$ + // new Path(element.getAttribute("path"))); //$NON-NLS-1$ + // } + // } + // } + // } + // } catch(IOException e){ + // } finally { + // if (xmlString != null){ + // ResourcesPlugin.getWorkspace().getRoot().setPersistentProperty(qName, + // null); // flush old one + // } + // + // } + // + // // load variables and containers from preferences into cache + // Preferences preferences = + // PHPeclipsePlugin.getDefault().getPluginPreferences(); + + // // only get variable from preferences not set to their default + // String[] propertyNames = preferences.propertyNames(); + // int variablePrefixLength = CP_VARIABLE_PREFERENCES_PREFIX.length(); + // for (int i = 0; i < propertyNames.length; i++){ + // String propertyName = propertyNames[i]; + // if (propertyName.startsWith(CP_VARIABLE_PREFERENCES_PREFIX)){ + // String varName = propertyName.substring(variablePrefixLength); + // IPath varPath = new Path(preferences.getString(propertyName).trim()); + // + // Variables.put(varName, varPath); + // PreviousSessionVariables.put(varName, varPath); + // } + // if (propertyName.startsWith(CP_CONTAINER_PREFERENCES_PREFIX)){ + // recreatePersistedContainer(propertyName, + // preferences.getString(propertyName), true/*add to container values*/); + // } + // } + // // override persisted values for variables which have a registered + // initializer + // String[] registeredVariables = getRegisteredVariableNames(); + // for (int i = 0; i < registeredVariables.length; i++) { + // String varName = registeredVariables[i]; + // Variables.put(varName, null); // reset variable, but leave its entry in + // the Map, so it will be part of variable names. + // } + // // override persisted values for containers which have a registered + // initializer + // String[] registeredContainerIDs = getRegisteredContainerIDs(); + // for (int i = 0; i < registeredContainerIDs.length; i++) { + // String containerID = registeredContainerIDs[i]; + // Iterator projectIterator = Containers.keySet().iterator(); + // while (projectIterator.hasNext()){ + // IJavaProject project = (IJavaProject)projectIterator.next(); + // Map projectContainers = (Map)Containers.get(project); + // if (projectContainers != null){ + // Iterator containerIterator = projectContainers.keySet().iterator(); + // while (containerIterator.hasNext()){ + // IPath containerPath = (IPath)containerIterator.next(); + // if (containerPath.segment(0).equals(containerID)) { // registered + // container + // projectContainers.put(containerPath, null); // reset container value, but + // leave entry in Map + // } + // } + // } + // } + // } + // } /** * Merged all awaiting deltas. */ public IJavaElementDelta mergeDeltas(Collection deltas) { - if (deltas.size() == 0) return null; - if (deltas.size() == 1) return (IJavaElementDelta)deltas.iterator().next(); + if (deltas.size() == 0) + return null; + if (deltas.size() == 1) + return (IJavaElementDelta) deltas.iterator().next(); if (DeltaProcessor.VERBOSE) { - System.out.println("MERGING " + deltas.size() + " DELTAS ["+Thread.currentThread()+"]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + System.out + .println("MERGING " + deltas.size() + " DELTAS [" + Thread.currentThread() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } Iterator iterator = deltas.iterator(); @@ -1447,7 +1729,7 @@ public class JavaModelManager implements ISaveParticipant { JavaElementDelta rootDelta = new JavaElementDelta(javaModel); boolean insertedTree = false; while (iterator.hasNext()) { - JavaElementDelta delta = (JavaElementDelta)iterator.next(); + JavaElementDelta delta = (JavaElementDelta) iterator.next(); if (DeltaProcessor.VERBOSE) { System.out.println(delta.toString()); } @@ -1456,7 +1738,8 @@ public class JavaModelManager implements ISaveParticipant { IJavaElementDelta[] children = delta.getAffectedChildren(); for (int j = 0; j < children.length; j++) { JavaElementDelta projectDelta = (JavaElementDelta) children[j]; - rootDelta.insertDeltaTree(projectDelta.getElement(), projectDelta); + rootDelta.insertDeltaTree(projectDelta.getElement(), + projectDelta); insertedTree = true; } IResourceDelta[] resourceDeltas = delta.getResourceDeltas(); @@ -1473,16 +1756,16 @@ public class JavaModelManager implements ISaveParticipant { } if (insertedTree) { return rootDelta; - } - else { + } else { return null; } } /** - * Returns the info for this element without - * disturbing the cache ordering. - */ // TODO: should be synchronized, could answer unitialized info or if cache is in middle of rehash, could even answer distinct element info + * Returns the info for this element without disturbing the cache ordering. + */ + // TODO: should be synchronized, could answer unitialized info or if cache + // is in middle of rehash, could even answer distinct element info protected Object peekAtInfo(IJavaElement element) { return this.cache.peekAtInfo(element); } @@ -1496,18 +1779,22 @@ public class JavaModelManager implements ISaveParticipant { protected void putInfo(IJavaElement element, Object info) { this.cache.putInfo(element, info); } + /* - * Puts the infos in the given map (keys are IJavaElements and values are JavaElementInfos) - * in the Java model cache in an atomic way. - * First checks that the info for the opened element (or one of its ancestors) has not been - * added to the cache. If it is the case, another thread has opened the element (or one of - * its ancestors). So returns without updating the cache. - */ - protected synchronized void putInfos(IJavaElement openedElement, Map newElements) { + * Puts the infos in the given map (keys are IJavaElements and values are + * JavaElementInfos) in the Java model cache in an atomic way. First checks + * that the info for the opened element (or one of its ancestors) has not + * been added to the cache. If it is the case, another thread has opened the + * element (or one of its ancestors). So returns without updating the cache. + */ + protected synchronized void putInfos(IJavaElement openedElement, + Map newElements) { // remove children Object existingInfo = this.cache.peekAtInfo(openedElement); - if (openedElement instanceof IParent && existingInfo instanceof JavaElementInfo) { - IJavaElement[] children = ((JavaElementInfo)existingInfo).getChildren(); + if (openedElement instanceof IParent + && existingInfo instanceof JavaElementInfo) { + IJavaElement[] children = ((JavaElementInfo) existingInfo) + .getChildren(); for (int i = 0, size = children.length; i < size; ++i) { JavaElement child = (JavaElement) children[i]; try { @@ -1520,11 +1807,12 @@ public class JavaModelManager implements ISaveParticipant { Iterator iterator = newElements.keySet().iterator(); while (iterator.hasNext()) { - IJavaElement element = (IJavaElement)iterator.next(); + IJavaElement element = (IJavaElement) iterator.next(); Object info = newElements.get(element); this.cache.putInfo(element, info); } } + /** * Reads the build state for the relevant project. */ @@ -1532,74 +1820,90 @@ public class JavaModelManager implements ISaveParticipant { File file = getSerializationFile(project); if (file != null && file.exists()) { try { - DataInputStream in= new DataInputStream(new BufferedInputStream(new FileInputStream(file))); + DataInputStream in = new DataInputStream( + new BufferedInputStream(new FileInputStream(file))); try { - String pluginID= in.readUTF(); + String pluginID = in.readUTF(); if (!pluginID.equals(JavaCore.PLUGIN_ID)) - throw new IOException(Util.bind("build.wrongFileFormat")); //$NON-NLS-1$ - String kind= in.readUTF(); + throw new IOException(Util + .bind("build.wrongFileFormat")); //$NON-NLS-1$ + String kind = in.readUTF(); if (!kind.equals("STATE")) //$NON-NLS-1$ - throw new IOException(Util.bind("build.wrongFileFormat")); //$NON-NLS-1$ + throw new IOException(Util + .bind("build.wrongFileFormat")); //$NON-NLS-1$ if (in.readBoolean()) return PHPBuilder.readState(project, in); if (PHPBuilder.DEBUG) - System.out.println("Saved state thinks last build failed for " + project.getName()); //$NON-NLS-1$ + System.out + .println("Saved state thinks last build failed for " + project.getName()); //$NON-NLS-1$ } finally { in.close(); } } catch (Exception e) { e.printStackTrace(); - throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, "Error reading last build state for project "+ project.getName(), e)); //$NON-NLS-1$ + throw new CoreException( + new Status( + IStatus.ERROR, + JavaCore.PLUGIN_ID, + Platform.PLUGIN_ERROR, + "Error reading last build state for project " + project.getName(), e)); //$NON-NLS-1$ } } return null; } -// public static void recreatePersistedContainer(String propertyName, String containerString, boolean addToContainerValues) { -// int containerPrefixLength = CP_CONTAINER_PREFERENCES_PREFIX.length(); -// int index = propertyName.indexOf('|', containerPrefixLength); -// if (containerString != null) containerString = containerString.trim(); -// if (index > 0) { -// final String projectName = propertyName.substring(containerPrefixLength, index).trim(); -// JavaProject project = (JavaProject)getJavaModelManager().getJavaModel().getJavaProject(projectName); -// final IPath containerPath = new Path(propertyName.substring(index+1).trim()); -// -// if (containerString == null || containerString.equals(CP_ENTRY_IGNORE)) { -// containerPut(project, containerPath, null); -// } else { -// final IClasspathEntry[] containerEntries = project.decodeClasspath(containerString, false, false); -// if (containerEntries != null && containerEntries != JavaProject.INVALID_CLASSPATH) { -// IClasspathContainer container = new IClasspathContainer() { -// public IClasspathEntry[] getClasspathEntries() { -// return containerEntries; -// } -// public String getDescription() { -// return "Persisted container ["+containerPath+" for project ["+ projectName+"]"; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ -// } -// public int getKind() { -// return 0; -// } -// public IPath getPath() { -// return containerPath; -// } -// public String toString() { -// return getDescription(); -// } -// -// }; -// if (addToContainerValues) { -// containerPut(project, containerPath, container); -// } -// Map projectContainers = (Map)PreviousSessionContainers.get(project); -// if (projectContainers == null){ -// projectContainers = new HashMap(1); -// PreviousSessionContainers.put(project, projectContainers); -// } -// projectContainers.put(containerPath, container); -// } -// } -// } -// } + // public static void recreatePersistedContainer(String propertyName, String + // containerString, boolean addToContainerValues) { + // int containerPrefixLength = CP_CONTAINER_PREFERENCES_PREFIX.length(); + // int index = propertyName.indexOf('|', containerPrefixLength); + // if (containerString != null) containerString = containerString.trim(); + // if (index > 0) { + // final String projectName = propertyName.substring(containerPrefixLength, + // index).trim(); + // JavaProject project = + // (JavaProject)getJavaModelManager().getJavaModel().getJavaProject(projectName); + // final IPath containerPath = new + // Path(propertyName.substring(index+1).trim()); + // + // if (containerString == null || containerString.equals(CP_ENTRY_IGNORE)) { + // containerPut(project, containerPath, null); + // } else { + // final IClasspathEntry[] containerEntries = + // project.decodeClasspath(containerString, false, false); + // if (containerEntries != null && containerEntries != + // JavaProject.INVALID_CLASSPATH) { + // IClasspathContainer container = new IClasspathContainer() { + // public IClasspathEntry[] getClasspathEntries() { + // return containerEntries; + // } + // public String getDescription() { + // return "Persisted container ["+containerPath+" for project ["+ + // projectName+"]"; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ + // } + // public int getKind() { + // return 0; + // } + // public IPath getPath() { + // return containerPath; + // } + // public String toString() { + // return getDescription(); + // } + // + // }; + // if (addToContainerValues) { + // containerPut(project, containerPath, container); + // } + // Map projectContainers = (Map)PreviousSessionContainers.get(project); + // if (projectContainers == null){ + // projectContainers = new HashMap(1); + // PreviousSessionContainers.put(project, projectContainers); + // } + // projectContainers.put(containerPath, container); + // } + // } + // } + // } /** * Registers the given delta with this manager. @@ -1609,38 +1913,44 @@ public class JavaModelManager implements ISaveParticipant { } /** - * Remembers the given scope in a weak set - * (so no need to remove it: it will be removed by the garbage collector) + * Remembers the given scope in a weak set (so no need to remove it: it will + * be removed by the garbage collector) */ -// public void rememberScope(AbstractSearchScope scope) { -// // NB: The value has to be null so as to not create a strong reference on the scope -// this.scopes.put(scope, null); -// } - + // public void rememberScope(AbstractSearchScope scope) { + // // NB: The value has to be null so as to not create a strong reference on + // the scope + // this.scopes.put(scope, null); + // } /** * removeElementChangedListener method comment. */ public void removeElementChangedListener(IElementChangedListener listener) { - for (int i = 0; i < this.elementChangedListenerCount; i++){ + for (int i = 0; i < this.elementChangedListenerCount; i++) { - if (this.elementChangedListeners[i].equals(listener)){ + if (this.elementChangedListeners[i].equals(listener)) { - // need to clone defensively since we might be in the middle of listener notifications (#fire) + // need to clone defensively since we might be in the middle of + // listener notifications (#fire) int length = this.elementChangedListeners.length; IElementChangedListener[] newListeners = new IElementChangedListener[length]; - System.arraycopy(this.elementChangedListeners, 0, newListeners, 0, i); + System.arraycopy(this.elementChangedListeners, 0, newListeners, + 0, i); int[] newMasks = new int[length]; - System.arraycopy(this.elementChangedListenerMasks, 0, newMasks, 0, i); + System.arraycopy(this.elementChangedListenerMasks, 0, newMasks, + 0, i); // copy trailing listeners int trailingLength = this.elementChangedListenerCount - i - 1; - if (trailingLength > 0){ - System.arraycopy(this.elementChangedListeners, i+1, newListeners, i, trailingLength); - System.arraycopy(this.elementChangedListenerMasks, i+1, newMasks, i, trailingLength); + if (trailingLength > 0) { + System.arraycopy(this.elementChangedListeners, i + 1, + newListeners, i, trailingLength); + System.arraycopy(this.elementChangedListenerMasks, i + 1, + newMasks, i, trailingLength); } - // update manager listener state (#fire need to iterate over original listeners through a local variable to hold onto + // update manager listener state (#fire need to iterate over + // original listeners through a local variable to hold onto // the original ones) this.elementChangedListeners = newListeners; this.elementChangedListenerMasks = newMasks; @@ -1651,31 +1961,36 @@ public class JavaModelManager implements ISaveParticipant { } /** - * Remembers the given scope in a weak set - * (so no need to remove it: it will be removed by the garbage collector) + * Remembers the given scope in a weak set (so no need to remove it: it will + * be removed by the garbage collector) */ -// public void rememberScope(AbstractSearchScope scope) { -// // NB: The value has to be null so as to not create a strong reference on the scope -// this.searchScopes.put(scope, null); -// } + // public void rememberScope(AbstractSearchScope scope) { + // // NB: The value has to be null so as to not create a strong reference on + // the scope + // this.searchScopes.put(scope, null); + // } /* * Removes all cached info for the given element (including all children) - * from the cache. - * Returns the info for the given element, or null if it was closed. + * from the cache. Returns the info for the given element, or null if it was + * closed. */ - public synchronized Object removeInfoAndChildren(JavaElement element) throws JavaModelException { + public synchronized Object removeInfoAndChildren(JavaElement element) + throws JavaModelException { Object info = this.cache.peekAtInfo(element); if (info != null) { boolean wasVerbose = false; try { if (VERBOSE) { - System.out.println("CLOSING Element ("+ Thread.currentThread()+"): " + element.toStringWithAncestors()); //$NON-NLS-1$//$NON-NLS-2$ + System.out + .println("CLOSING Element (" + Thread.currentThread() + "): " + element.toStringWithAncestors()); //$NON-NLS-1$//$NON-NLS-2$ wasVerbose = true; VERBOSE = false; } element.closing(info); - if (element instanceof IParent && info instanceof JavaElementInfo) { - IJavaElement[] children = ((JavaElementInfo)info).getChildren(); + if (element instanceof IParent + && info instanceof JavaElementInfo) { + IJavaElement[] children = ((JavaElementInfo) info) + .getChildren(); for (int i = 0, size = children.length; i < size; ++i) { JavaElement child = (JavaElement) children[i]; child.close(); @@ -1683,8 +1998,10 @@ public class JavaModelManager implements ISaveParticipant { } this.cache.removeInfo(element); if (wasVerbose) { - System.out.println("-> Package cache size = " + this.cache.pkgSize()); //$NON-NLS-1$ - System.out.println("-> Openable cache filling ratio = " + NumberFormat.getInstance().format(this.cache.openableFillingRatio()) + "%"); //$NON-NLS-1$//$NON-NLS-2$ + System.out + .println("-> Package cache size = " + this.cache.pkgSize()); //$NON-NLS-1$ + System.out + .println("-> Openable cache filling ratio = " + NumberFormat.getInstance().format(this.cache.openableFillingRatio()) + "%"); //$NON-NLS-1$//$NON-NLS-2$ } } finally { JavaModelManager.VERBOSE = wasVerbose; @@ -1693,34 +2010,41 @@ public class JavaModelManager implements ISaveParticipant { } return null; } + public void removePerProjectInfo(JavaProject javaProject) { - synchronized(perProjectInfo) { // use the perProjectInfo collection as its own lock + synchronized (perProjectInfo) { // use the perProjectInfo collection as + // its own lock IProject project = javaProject.getProject(); - PerProjectInfo info= (PerProjectInfo) perProjectInfo.get(project); + PerProjectInfo info = (PerProjectInfo) perProjectInfo.get(project); if (info != null) { perProjectInfo.remove(project); } } } + /* * Resets the temporary cache for newly created elements to null. */ public void resetTemporaryCache() { this.temporaryCache.set(null); } + /** * @see ISaveParticipant */ - public void rollback(ISaveContext context){ + public void rollback(ISaveContext context) { } - private void saveState(PerProjectInfo info, ISaveContext context) throws CoreException { + private void saveState(PerProjectInfo info, ISaveContext context) + throws CoreException { // passed this point, save actions are non trivial - if (context.getKind() == ISaveContext.SNAPSHOT) return; + if (context.getKind() == ISaveContext.SNAPSHOT) + return; // save built state - if (info.triedRead) saveBuiltState(info); + if (info.triedRead) + saveBuiltState(info); } /** @@ -1728,12 +2052,15 @@ public class JavaModelManager implements ISaveParticipant { */ private void saveBuiltState(PerProjectInfo info) throws CoreException { if (PHPBuilder.DEBUG) - System.out.println(Util.bind("build.saveStateProgress", info.project.getName())); //$NON-NLS-1$ + System.out.println(Util.bind( + "build.saveStateProgress", info.project.getName())); //$NON-NLS-1$ File file = getSerializationFile(info.project); - if (file == null) return; + if (file == null) + return; long t = System.currentTimeMillis(); try { - DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); + DataOutputStream out = new DataOutputStream( + new BufferedOutputStream(new FileOutputStream(file))); try { out.writeUTF(JavaCore.PLUGIN_ID); out.writeUTF("STATE"); //$NON-NLS-1$ @@ -1747,169 +2074,225 @@ public class JavaModelManager implements ISaveParticipant { out.close(); } } catch (RuntimeException e) { - try {file.delete();} catch(SecurityException se) {} + try { + file.delete(); + } catch (SecurityException se) { + } throw new CoreException( - new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, - Util.bind("build.cannotSaveState", info.project.getName()), e)); //$NON-NLS-1$ + new Status( + IStatus.ERROR, + JavaCore.PLUGIN_ID, + Platform.PLUGIN_ERROR, + Util + .bind( + "build.cannotSaveState", info.project.getName()), e)); //$NON-NLS-1$ } catch (IOException e) { - try {file.delete();} catch(SecurityException se) {} + try { + file.delete(); + } catch (SecurityException se) { + } throw new CoreException( - new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, - Util.bind("build.cannotSaveState", info.project.getName()), e)); //$NON-NLS-1$ + new Status( + IStatus.ERROR, + JavaCore.PLUGIN_ID, + Platform.PLUGIN_ERROR, + Util + .bind( + "build.cannotSaveState", info.project.getName()), e)); //$NON-NLS-1$ } if (PHPBuilder.DEBUG) { t = System.currentTimeMillis() - t; - System.out.println(Util.bind("build.saveStateComplete", String.valueOf(t))); //$NON-NLS-1$ + System.out.println(Util.bind( + "build.saveStateComplete", String.valueOf(t))); //$NON-NLS-1$ } } + private synchronized Map containerClone(IJavaProject project) { - Map originalProjectContainers = (Map)this.containers.get(project); - if (originalProjectContainers == null) return null; + Map originalProjectContainers = (Map) this.containers.get(project); + if (originalProjectContainers == null) + return null; Map projectContainers = new HashMap(originalProjectContainers.size()); projectContainers.putAll(originalProjectContainers); return projectContainers; } + /** * @see ISaveParticipant */ public void saving(ISaveContext context) throws CoreException { - // save container values on snapshot/full save + // save container values on snapshot/full save Preferences preferences = JavaCore.getPlugin().getPluginPreferences(); IJavaProject[] projects = getJavaModel().getJavaProjects(); for (int i = 0, length = projects.length; i < length; i++) { - IJavaProject project = projects[i]; - // clone while iterating (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=59638) + IJavaProject project = projects[i]; + // clone while iterating (see + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=59638) Map projectContainers = containerClone(project); - if (projectContainers == null) continue; - for (Iterator keys = projectContainers.keySet().iterator(); keys.hasNext();) { - IPath containerPath = (IPath) keys.next(); -// IClasspathContainer container = (IClasspathContainer) projectContainers.get(containerPath); - String containerKey = CP_CONTAINER_PREFERENCES_PREFIX+project.getElementName() +"|"+containerPath;//$NON-NLS-1$ + if (projectContainers == null) + continue; + for (Iterator keys = projectContainers.keySet().iterator(); keys + .hasNext();) { + IPath containerPath = (IPath) keys.next(); + // IClasspathContainer container = (IClasspathContainer) + // projectContainers.get(containerPath); + String containerKey = CP_CONTAINER_PREFERENCES_PREFIX + + project.getElementName() + "|" + containerPath;//$NON-NLS-1$ String containerString = CP_ENTRY_IGNORE; -// try { -// if (container != null) { -// containerString = ((JavaProject)project).encodeClasspath(container.getClasspathEntries(), null, false); -// } -// } catch(JavaModelException e){ -// // could not encode entry: leave it as CP_ENTRY_IGNORE -// } - preferences.setDefault(containerKey, CP_ENTRY_IGNORE); // use this default to get rid of removed ones + // try { + // if (container != null) { + // containerString = + // ((JavaProject)project).encodeClasspath(container.getClasspathEntries(), + // null, false); + // } + // } catch(JavaModelException e){ + // // could not encode entry: leave it as CP_ENTRY_IGNORE + // } + preferences.setDefault(containerKey, CP_ENTRY_IGNORE); // use + // this + // default + // to + // get + // rid + // of + // removed + // ones preferences.setValue(containerKey, containerString); } } JavaCore.getPlugin().savePluginPreferences(); -// if (context.getKind() == ISaveContext.FULL_SAVE) { -// // will need delta since this save (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38658) -// context.needDelta(); -// -// // clean up indexes on workspace full save -// // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=52347) -// IndexManager manager = this.indexManager; -// if (manager != null) { -// manager.cleanUpIndexes(); -// } -// } + // if (context.getKind() == ISaveContext.FULL_SAVE) { + // // will need delta since this save (see + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=38658) + // context.needDelta(); + // + // // clean up indexes on workspace full save + // // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=52347) + // IndexManager manager = this.indexManager; + // if (manager != null) { + // manager.cleanUpIndexes(); + // } + // } IProject savedProject = context.getProject(); if (savedProject != null) { - if (!JavaProject.hasJavaNature(savedProject)) return; // ignore - PerProjectInfo info = getPerProjectInfo(savedProject, true /* create info */); + if (!JavaProject.hasJavaNature(savedProject)) + return; // ignore + PerProjectInfo info = getPerProjectInfo(savedProject, true /* + * create + * info + */); saveState(info, context); return; } - ArrayList vStats= null; // lazy initialized - for (Iterator iter = perProjectInfo.values().iterator(); iter.hasNext();) { + ArrayList vStats = null; // lazy initialized + for (Iterator iter = perProjectInfo.values().iterator(); iter.hasNext();) { try { PerProjectInfo info = (PerProjectInfo) iter.next(); saveState(info, context); } catch (CoreException e) { if (vStats == null) - vStats= new ArrayList(); + vStats = new ArrayList(); vStats.add(e.getStatus()); } } if (vStats != null) { - IStatus[] stats= new IStatus[vStats.size()]; + IStatus[] stats = new IStatus[vStats.size()]; vStats.toArray(stats); - throw new CoreException(new MultiStatus(JavaCore.PLUGIN_ID, IStatus.ERROR, stats, Util.bind("build.cannotSaveStates"), null)); //$NON-NLS-1$ + throw new CoreException(new MultiStatus(JavaCore.PLUGIN_ID, + IStatus.ERROR, stats, + Util.bind("build.cannotSaveStates"), null)); //$NON-NLS-1$ } } + /** * @see ISaveParticipant */ -// public void saving(ISaveContext context) throws CoreException { -// -// IProject savedProject = context.getProject(); -// if (savedProject != null) { -// if (!JavaProject.hasJavaNature(savedProject)) return; // ignore -// PerProjectInfo info = getPerProjectInfo(savedProject, true /* create info */); -// saveState(info, context); -// return; -// } -// -// ArrayList vStats= null; // lazy initialized -// for (Iterator iter = perProjectInfo.values().iterator(); iter.hasNext();) { -// try { -// PerProjectInfo info = (PerProjectInfo) iter.next(); -// saveState(info, context); -// } catch (CoreException e) { -// if (vStats == null) -// vStats= new ArrayList(); -// vStats.add(e.getStatus()); -// } -// } -// if (vStats != null) { -// IStatus[] stats= new IStatus[vStats.size()]; -// vStats.toArray(stats); -// throw new CoreException(new MultiStatus(JavaCore.PLUGIN_ID, IStatus.ERROR, stats, Util.bind("build.cannotSaveStates"), null)); //$NON-NLS-1$ -// } -// } - - /** - * Record the order in which to build the java projects (batch build). This order is based - * on the projects classpath settings. - */ - protected void setBuildOrder(String[] javaBuildOrder) throws JavaModelException { + // public void saving(ISaveContext context) throws CoreException { + // + // IProject savedProject = context.getProject(); + // if (savedProject != null) { + // if (!JavaProject.hasJavaNature(savedProject)) return; // ignore + // PerProjectInfo info = getPerProjectInfo(savedProject, true /* create info + // */); + // saveState(info, context); + // return; + // } + // + // ArrayList vStats= null; // lazy initialized + // for (Iterator iter = perProjectInfo.values().iterator(); iter.hasNext();) + // { + // try { + // PerProjectInfo info = (PerProjectInfo) iter.next(); + // saveState(info, context); + // } catch (CoreException e) { + // if (vStats == null) + // vStats= new ArrayList(); + // vStats.add(e.getStatus()); + // } + // } + // if (vStats != null) { + // IStatus[] stats= new IStatus[vStats.size()]; + // vStats.toArray(stats); + // throw new CoreException(new MultiStatus(JavaCore.PLUGIN_ID, + // IStatus.ERROR, stats, Util.bind("build.cannotSaveStates"), null)); + // //$NON-NLS-1$ + // } + // } + /** + * Record the order in which to build the java projects (batch build). This + * order is based on the projects classpath settings. + */ + protected void setBuildOrder(String[] javaBuildOrder) + throws JavaModelException { // optional behaviour // possible value of index 0 is Compute - if (!JavaCore.COMPUTE.equals(JavaCore.getOption(JavaCore.CORE_JAVA_BUILD_ORDER))) return; // cannot be customized at project level + if (!JavaCore.COMPUTE.equals(JavaCore + .getOption(JavaCore.CORE_JAVA_BUILD_ORDER))) + return; // cannot be customized at project level - if (javaBuildOrder == null || javaBuildOrder.length <= 1) return; + if (javaBuildOrder == null || javaBuildOrder.length <= 1) + return; IWorkspace workspace = ResourcesPlugin.getWorkspace(); IWorkspaceDescription description = workspace.getDescription(); String[] wksBuildOrder = description.getBuildOrder(); String[] newOrder; - if (wksBuildOrder == null){ + if (wksBuildOrder == null) { newOrder = javaBuildOrder; } else { - // remove projects which are already mentionned in java builder order + // remove projects which are already mentionned in java builder + // order int javaCount = javaBuildOrder.length; - HashMap newSet = new HashMap(javaCount); // create a set for fast check - for (int i = 0; i < javaCount; i++){ + HashMap newSet = new HashMap(javaCount); // create a set for fast + // check + for (int i = 0; i < javaCount; i++) { newSet.put(javaBuildOrder[i], javaBuildOrder[i]); } int removed = 0; int oldCount = wksBuildOrder.length; - for (int i = 0; i < oldCount; i++){ - if (newSet.containsKey(wksBuildOrder[i])){ + for (int i = 0; i < oldCount; i++) { + if (newSet.containsKey(wksBuildOrder[i])) { wksBuildOrder[i] = null; removed++; } } // add Java ones first newOrder = new String[oldCount - removed + javaCount]; - System.arraycopy(javaBuildOrder, 0, newOrder, 0, javaCount); // java projects are built first + System.arraycopy(javaBuildOrder, 0, newOrder, 0, javaCount); // java + // projects + // are + // built + // first // copy previous items in their respective order int index = javaCount; - for (int i = 0; i < oldCount; i++){ - if (wksBuildOrder[i] != null){ + for (int i = 0; i < oldCount; i++) { + if (wksBuildOrder[i] != null) { newOrder[index++] = wksBuildOrder[i]; } } @@ -1918,7 +2301,7 @@ public class JavaModelManager implements ISaveParticipant { description.setBuildOrder(newOrder); try { workspace.setDescription(description); - } catch(CoreException e){ + } catch (CoreException e) { throw new JavaModelException(e); } } @@ -1927,24 +2310,30 @@ public class JavaModelManager implements ISaveParticipant { * Sets the last built state for the given project, or null to reset it. */ public void setLastBuiltState(IProject project, Object state) { - if (!JavaProject.hasJavaNature(project)) return; // should never be requested on non-Java projects - PerProjectInfo info = getPerProjectInfo(project, true /*create if missing*/); + if (!JavaProject.hasJavaNature(project)) + return; // should never be requested on non-Java projects + PerProjectInfo info = getPerProjectInfo(project, true /* + * create if + * missing + */); info.triedRead = true; // no point trying to re-read once using setter info.savedState = state; - if (state == null) { // delete state file to ensure a full build happens if the workspace crashes + if (state == null) { // delete state file to ensure a full build + // happens if the workspace crashes try { File file = getSerializationFile(project); if (file != null && file.exists()) file.delete(); - } catch(SecurityException se) {} + } catch (SecurityException se) { + } } } - public void shutdown () { -// TODO temp-del -// if (this.deltaProcessor.indexManager != null){ // no more indexing -// this.deltaProcessor.indexManager.shutdown(); -// } + public void shutdown() { + // TODO temp-del + // if (this.deltaProcessor.indexManager != null){ // no more indexing + // this.deltaProcessor.indexManager.shutdown(); + // } try { IJavaModel model = this.getJavaModel(); if (model != null) { @@ -1960,7 +2349,7 @@ public class JavaModelManager implements ISaveParticipant { * registered will be fired. */ public void startDeltas() { - this.isFiring= true; + this.isFiring = true; } /** @@ -1968,7 +2357,7 @@ public class JavaModelManager implements ISaveParticipant { * registered will not be fired until deltas are started again. */ public void stopDeltas() { - this.isFiring= false; + this.isFiring = false; } /** @@ -1976,9 +2365,10 @@ public class JavaModelManager implements ISaveParticipant { */ public void updateJavaModel(IJavaElementDelta customDelta) { - if (customDelta == null){ - for (int i = 0, length = this.javaModelDeltas.size(); i < length; i++){ - IJavaElementDelta delta = (IJavaElementDelta)this.javaModelDeltas.get(i); + if (customDelta == null) { + for (int i = 0, length = this.javaModelDeltas.size(); i < length; i++) { + IJavaElementDelta delta = (IJavaElementDelta) this.javaModelDeltas + .get(i); this.modelUpdater.processJavaDelta(delta); } } else { @@ -1986,13 +2376,11 @@ public class JavaModelManager implements ISaveParticipant { } } - - - public static IPath variableGet(String variableName){ - return (IPath)Variables.get(variableName); + public static IPath variableGet(String variableName) { + return (IPath) Variables.get(variableName); } - public static String[] variableNames(){ + public static String[] variableNames() { int length = Variables.size(); String[] result = new String[length]; Iterator vars = Variables.keySet().iterator(); @@ -2003,7 +2391,7 @@ public class JavaModelManager implements ISaveParticipant { return result; } - public static void variablePut(String variableName, IPath variablePath){ + public static void variablePut(String variableName, IPath variablePath) { // update cache - do not only rely on listener refresh if (variablePath == null) { @@ -2014,65 +2402,81 @@ public class JavaModelManager implements ISaveParticipant { } // do not write out intermediate initialization value - if (variablePath == JavaModelManager.VariableInitializationInProgress){ + if (variablePath == JavaModelManager.VariableInitializationInProgress) { return; } Preferences preferences = JavaCore.getPlugin().getPluginPreferences(); - String variableKey = CP_VARIABLE_PREFERENCES_PREFIX+variableName; - String variableString = variablePath == null ? CP_ENTRY_IGNORE : variablePath.toString(); - preferences.setDefault(variableKey, CP_ENTRY_IGNORE); // use this default to get rid of removed ones + String variableKey = CP_VARIABLE_PREFERENCES_PREFIX + variableName; + String variableString = variablePath == null ? CP_ENTRY_IGNORE + : variablePath.toString(); + preferences.setDefault(variableKey, CP_ENTRY_IGNORE); // use this + // default to + // get rid of + // removed ones preferences.setValue(variableKey, variableString); JavaCore.getPlugin().savePluginPreferences(); } + /* - * Returns all the working copies which have the given owner. - * Adds the working copies of the primary owner if specified. - * Returns null if it has none. - */ - public ICompilationUnit[] getWorkingCopies(WorkingCopyOwner owner, boolean addPrimary) { - synchronized(perWorkingCopyInfos) { - ICompilationUnit[] primaryWCs = addPrimary && owner != DefaultWorkingCopyOwner.PRIMARY - ? getWorkingCopies(DefaultWorkingCopyOwner.PRIMARY, false) - : null; - Map workingCopyToInfos = (Map)perWorkingCopyInfos.get(owner); - if (workingCopyToInfos == null) return primaryWCs; + * Returns all the working copies which have the given owner. Adds the + * working copies of the primary owner if specified. Returns null if it has + * none. + */ + public ICompilationUnit[] getWorkingCopies(WorkingCopyOwner owner, + boolean addPrimary) { + synchronized (perWorkingCopyInfos) { + ICompilationUnit[] primaryWCs = addPrimary + && owner != DefaultWorkingCopyOwner.PRIMARY ? getWorkingCopies( + DefaultWorkingCopyOwner.PRIMARY, false) + : null; + Map workingCopyToInfos = (Map) perWorkingCopyInfos.get(owner); + if (workingCopyToInfos == null) + return primaryWCs; int primaryLength = primaryWCs == null ? 0 : primaryWCs.length; - int size = workingCopyToInfos.size(); // note size is > 0 otherwise pathToPerWorkingCopyInfos would be null - ICompilationUnit[] result = new ICompilationUnit[primaryLength + size]; + int size = workingCopyToInfos.size(); // note size is > 0 + // otherwise + // pathToPerWorkingCopyInfos + // would be null + ICompilationUnit[] result = new ICompilationUnit[primaryLength + + size]; if (primaryWCs != null) { System.arraycopy(primaryWCs, 0, result, 0, primaryLength); } Iterator iterator = workingCopyToInfos.values().iterator(); int index = primaryLength; - while(iterator.hasNext()) { - result[index++] = ((JavaModelManager.PerWorkingCopyInfo)iterator.next()).getWorkingCopy(); + while (iterator.hasNext()) { + result[index++] = ((JavaModelManager.PerWorkingCopyInfo) iterator + .next()).getWorkingCopy(); } return result; } } /* - * A HashSet that contains the IJavaProject whose classpath is being resolved. + * A HashSet that contains the IJavaProject whose classpath is being + * resolved. */ private ThreadLocal classpathsBeingResolved = new ThreadLocal(); private HashSet getClasspathBeingResolved() { - HashSet result = (HashSet) this.classpathsBeingResolved.get(); - if (result == null) { - result = new HashSet(); - this.classpathsBeingResolved.set(result); - } - return result; + HashSet result = (HashSet) this.classpathsBeingResolved.get(); + if (result == null) { + result = new HashSet(); + this.classpathsBeingResolved.set(result); + } + return result; } + public boolean isClasspathBeingResolved(IJavaProject project) { - return getClasspathBeingResolved().contains(project); + return getClasspathBeingResolved().contains(project); } - public void setClasspathBeingResolved(IJavaProject project, boolean classpathIsResolved) { - if (classpathIsResolved) { - getClasspathBeingResolved().add(project); - } else { - getClasspathBeingResolved().remove(project); - } + public void setClasspathBeingResolved(IJavaProject project, + boolean classpathIsResolved) { + if (classpathIsResolved) { + getClasspathBeingResolved().add(project); + } else { + getClasspathBeingResolved().remove(project); + } } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelOperation.java index 752990c..89a9a40 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelOperation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelOperation.java @@ -45,845 +45,928 @@ import org.eclipse.core.runtime.jobs.ISchedulingRule; /** * Defines behavior common to all Java Model operations */ -public abstract class JavaModelOperation implements IWorkspaceRunnable, IProgressMonitor { - protected interface IPostAction { - /* - * Returns the id of this action. - * - * @see JavaModelOperation#postAction - */ - String getID(); - - /* - * Run this action. - */ - void run() throws JavaModelException; - } - - /* - * Constants controlling the insertion mode of an action. - * - * @see JavaModelOperation#postAction - */ - protected static final int APPEND = 1; // insert at the end - - protected static final int REMOVEALL_APPEND = 2; // remove all existing ones with same ID, and add new one at the end - - protected static final int KEEP_EXISTING = 3; // do not insert if already existing with same ID - - /* - * Whether tracing post actions is enabled. - */ - protected static boolean POST_ACTION_VERBOSE; - - /* - * A list of IPostActions. - */ - protected IPostAction[] actions; - - protected int actionsStart = 0; - - protected int actionsEnd = -1; - - /* - * A HashMap of attributes that can be used by operations - */ - protected HashMap attributes; - - public static final String HAS_MODIFIED_RESOURCE_ATTR = "hasModifiedResource"; //$NON-NLS-1$ - - public static final String TRUE = "true"; //$NON-NLS-1$ - - //public static final String FALSE = "false"; //$NON-NLS-1$ - - /** - * The elements this operation operates on, or null if this operation does not operate on specific elements. - */ - protected IJavaElement[] fElementsToProcess; - - /** - * The parent elements this operation operates with or null if this operation does not operate with specific parent - * elements. - */ - protected IJavaElement[] fParentElements; - - /** - * An empty collection of IJavaElement s - the common empty result if no elements are created, or if this operation - * is not actually executed. - */ - protected static IJavaElement[] NO_ELEMENTS = new IJavaElement[] {}; - - /** - * The elements created by this operation - empty until the operation actually creates elements. - */ - protected IJavaElement[] resultElements = NO_ELEMENTS; - - /** - * The progress monitor passed into this operation - */ - protected IProgressMonitor progressMonitor = null; - - /** - * A flag indicating whether this operation is nested. - */ - protected boolean isNested = false; - - /** - * Conflict resolution policy - by default do not force (fail on a conflict). - */ - protected boolean force = false; - - /* - * A per thread stack of java model operations (PerThreadObject of ArrayList). - */ - protected static PerThreadObject operationStacks = new PerThreadObject(); - - protected JavaModelOperation() { - } - - /** - * A common constructor for all Java Model operations. - */ - protected JavaModelOperation(IJavaElement[] elements) { - fElementsToProcess = elements; - } - - /** - * Common constructor for all Java Model operations. - */ - protected JavaModelOperation(IJavaElement[] elementsToProcess, IJavaElement[] parentElements) { - fElementsToProcess = elementsToProcess; - fParentElements = parentElements; - } - - /** - * A common constructor for all Java Model operations. - */ - protected JavaModelOperation(IJavaElement[] elementsToProcess, IJavaElement[] parentElements, boolean force) { - fElementsToProcess = elementsToProcess; - fParentElements = parentElements; - this.force = force; - } - - /** - * A common constructor for all Java Model operations. - */ - protected JavaModelOperation(IJavaElement[] elements, boolean force) { - fElementsToProcess = elements; - this.force = force; - } - - /** - * Common constructor for all Java Model operations. - */ - protected JavaModelOperation(IJavaElement element) { - fElementsToProcess = new IJavaElement[] { element }; - } - - /** - * A common constructor for all Java Model operations. - */ - protected JavaModelOperation(IJavaElement element, boolean force) { - fElementsToProcess = new IJavaElement[] { element }; - this.force = force; - } - - /* - * Registers the given action at the end of the list of actions to run. - */ - protected void addAction(IPostAction action) { - int length = this.actions.length; - if (length == ++this.actionsEnd) { - System.arraycopy(this.actions, 0, this.actions = new IPostAction[length * 2], 0, length); - } - this.actions[this.actionsEnd] = action; - } - - /* - * Registers the given delta with the Java Model Manager. - */ - protected void addDelta(IJavaElementDelta delta) { - JavaModelManager.getJavaModelManager().registerJavaModelDelta(delta); - } - - /* - * Registers the given reconcile delta with the Java Model Manager. - */ - protected void addReconcileDelta(IWorkingCopy workingCopy, IJavaElementDelta delta) { - HashMap reconcileDeltas = JavaModelManager.getJavaModelManager().reconcileDeltas; - JavaElementDelta previousDelta = (JavaElementDelta) reconcileDeltas.get(workingCopy); - if (previousDelta != null) { - IJavaElementDelta[] children = delta.getAffectedChildren(); - for (int i = 0, length = children.length; i < length; i++) { - JavaElementDelta child = (JavaElementDelta) children[i]; - previousDelta.insertDeltaTree(child.getElement(), child); - } - } else { - reconcileDeltas.put(workingCopy, delta); - } - } - - /* - * Deregister the reconcile delta for the given working copy - */ - protected void removeReconcileDelta(IWorkingCopy workingCopy) { - JavaModelManager.getJavaModelManager().reconcileDeltas.remove(workingCopy); - } - - /** - * @see IProgressMonitor - */ - public void beginTask(String name, int totalWork) { - if (progressMonitor != null) { - progressMonitor.beginTask(name, totalWork); - } - } - - /** - * Checks with the progress monitor to see whether this operation should be canceled. An operation should regularly call this - * method during its operation so that the user can cancel it. - * - * @exception OperationCanceledException - * if cancelling the operation has been requested - * @see IProgressMonitor#isCanceled - */ - protected void checkCanceled() { - if (isCanceled()) { - throw new OperationCanceledException(Util.bind("operation.cancelled")); //$NON-NLS-1$ - } - } - - /** - * Common code used to verify the elements this operation is processing. - * - * @see JavaModelOperation#verify() - */ - protected IJavaModelStatus commonVerify() { - if (fElementsToProcess == null || fElementsToProcess.length == 0) { - return new JavaModelStatus(IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS); - } - for (int i = 0; i < fElementsToProcess.length; i++) { - if (fElementsToProcess[i] == null) { - return new JavaModelStatus(IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS); - } - } - return JavaModelStatus.VERIFIED_OK; - } - - /** - * Convenience method to copy resources - */ - protected void copyResources(IResource[] resources, IPath destinationPath) throws JavaModelException { - IProgressMonitor subProgressMonitor = getSubProgressMonitor(resources.length); - IWorkspace workspace = resources[0].getWorkspace(); - try { - workspace.copy(resources, destinationPath, false, subProgressMonitor); - this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); - } catch (CoreException e) { - throw new JavaModelException(e); - } - } - - /** - * Convenience method to create a file - */ - protected void createFile(IContainer folder, String name, InputStream contents, boolean force) throws JavaModelException { - IFile file = folder.getFile(new Path(name)); - try { - file.create(contents, force ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY, getSubProgressMonitor(1)); - this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); - } catch (CoreException e) { - throw new JavaModelException(e); - } - } - - /** - * Convenience method to create a folder - */ - protected void createFolder(IContainer parentFolder, String name, boolean force) throws JavaModelException { - IFolder folder = parentFolder.getFolder(new Path(name)); - try { - // we should use true to create the file locally. Only VCM should use tru/false - folder.create(force ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY, true, // local - getSubProgressMonitor(1)); - this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); - } catch (CoreException e) { - throw new JavaModelException(e); - } - } - - /** - * Convenience method to delete an empty package fragment - */ - protected void deleteEmptyPackageFragment(IPackageFragment fragment, boolean force, IResource rootResource) - throws JavaModelException { - - IContainer resource = (IContainer) fragment.getResource(); - - try { - resource.delete(force ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY, getSubProgressMonitor(1)); - this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); - while (resource instanceof IFolder) { - // deleting a package: delete the parent if it is empty (eg. deleting x.y where folder x doesn't have resources but y) - // without deleting the package fragment root - resource = resource.getParent(); - if (!resource.equals(rootResource) && resource.members().length == 0) { - resource.delete(force ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY, getSubProgressMonitor(1)); - this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); - } - } - } catch (CoreException e) { - throw new JavaModelException(e); - } - } - - /** - * Convenience method to delete a resource - */ - protected void deleteResource(IResource resource, int flags) throws JavaModelException { - try { - resource.delete(flags, getSubProgressMonitor(1)); - this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); - } catch (CoreException e) { - throw new JavaModelException(e); - } - } - - /** - * Convenience method to delete resources - */ - protected void deleteResources(IResource[] resources, boolean force) throws JavaModelException { - if (resources == null || resources.length == 0) - return; - IProgressMonitor subProgressMonitor = getSubProgressMonitor(resources.length); - IWorkspace workspace = resources[0].getWorkspace(); - try { - workspace.delete(resources, force ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY, subProgressMonitor); - this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); - } catch (CoreException e) { - throw new JavaModelException(e); - } - } - - /** - * @see IProgressMonitor - */ - public void done() { - if (progressMonitor != null) { - progressMonitor.done(); - } - } - - /* - * Returns whether the given path is equals to one of the given other paths. - */ - protected boolean equalsOneOf(IPath path, IPath[] otherPaths) { - for (int i = 0, length = otherPaths.length; i < length; i++) { - if (path.equals(otherPaths[i])) { - return true; - } - } - return false; - } - - /** - * Verifies the operation can proceed and executes the operation. Subclasses should override #verify and - * executeOperation to implement the specific operation behavior. - * - * @exception JavaModelException - * The operation has failed. - */ - // protected void execute() throws JavaModelException { - // IJavaModelStatus status= verify(); - // if (status.isOK()) { - // // if first time here, computes the root infos before executing the operation - // DeltaProcessor deltaProcessor = JavaModelManager.getJavaModelManager().deltaProcessor; - // if (deltaProcessor.roots == null) { - // deltaProcessor.initializeRoots(); - // } - // executeOperation(); - // } else { - // throw new JavaModelException(status); - // } - // } - /** - * Convenience method to run an operation within this operation - */ - public void executeNestedOperation(JavaModelOperation operation, int subWorkAmount) throws JavaModelException { - IProgressMonitor subProgressMonitor = getSubProgressMonitor(subWorkAmount); - // fix for 1FW7IKC, part (1) - try { - operation.setNested(true); - operation.run(subProgressMonitor); - } catch (CoreException ce) { - if (ce instanceof JavaModelException) { - throw (JavaModelException) ce; - } else { - // translate the core exception to a java model exception - if (ce.getStatus().getCode() == IResourceStatus.OPERATION_FAILED) { - Throwable e = ce.getStatus().getException(); - if (e instanceof JavaModelException) { - throw (JavaModelException) e; - } - } - throw new JavaModelException(ce); - } - } - } - - /** - * Performs the operation specific behavior. Subclasses must override. - */ - protected abstract void executeOperation() throws JavaModelException; - - /* - * Returns the attribute registered at the given key with the top level operation. Returns null if no such attribute is found. - */ - protected Object getAttribute(Object key) { - ArrayList stack = this.getCurrentOperationStack(); - if (stack.size() == 0) - return null; - JavaModelOperation topLevelOp = (JavaModelOperation) stack.get(0); - if (topLevelOp.attributes == null) { - return null; - } else { - return topLevelOp.attributes.get(key); - } - } - - /** - * Returns the compilation unit the given element is contained in, or the element itself (if it is a compilation unit), otherwise - * null. - */ - protected ICompilationUnit getCompilationUnitFor(IJavaElement element) { - - return ((JavaElement) element).getCompilationUnit(); - } - - /* - * Returns the stack of operations running in the current thread. Returns an empty stack if no operations are currently running in - * this thread. - */ - protected ArrayList getCurrentOperationStack() { - ArrayList stack = (ArrayList) operationStacks.getCurrent(); - if (stack == null) { - stack = new ArrayList(); - operationStacks.setCurrent(stack); - } - return stack; - } - - /** - * Returns the elements to which this operation applies, or null if not applicable. - */ - protected IJavaElement[] getElementsToProcess() { - return fElementsToProcess; - } - - /** - * Returns the element to which this operation applies, or null if not applicable. - */ - protected IJavaElement getElementToProcess() { - if (fElementsToProcess == null || fElementsToProcess.length == 0) { - return null; - } - return fElementsToProcess[0]; - } - - /** - * Returns the Java Model this operation is operating in. - */ - public IJavaModel getJavaModel() { - if (fElementsToProcess == null || fElementsToProcess.length == 0) { - return getParentElement().getJavaModel(); - } else { - return fElementsToProcess[0].getJavaModel(); - } - } - - // protected IPath[] getNestedFolders(IPackageFragmentRoot root) throws JavaModelException { - // IPath rootPath = root.getPath(); - // IClasspathEntry[] classpath = root.getJavaProject().getRawClasspath(); - // int length = classpath.length; - // IPath[] result = new IPath[length]; - // int index = 0; - // for (int i = 0; i < length; i++) { - // IPath path = classpath[i].getPath(); - // if (rootPath.isPrefixOf(path) && !rootPath.equals(path)) { - // result[index++] = path; - // } - // } - // if (index < length) { - // System.arraycopy(result, 0, result = new IPath[index], 0, index); - // } - // return result; - // } - /** - * Returns the parent element to which this operation applies, or null if not applicable. - */ - protected IJavaElement getParentElement() { - if (fParentElements == null || fParentElements.length == 0) { - return null; - } - return fParentElements[0]; - } - - /** - * Returns the parent elements to which this operation applies, or null if not applicable. - */ - protected IJavaElement[] getParentElements() { - return fParentElements; - } - - /** - * Returns the elements created by this operation. - */ - public IJavaElement[] getResultElements() { - return resultElements; - } - - /* - * Returns the scheduling rule for this operation (i.e. the resource that needs to be locked while this operation is running. - * Subclasses can override. - */ - protected ISchedulingRule getSchedulingRule() { - return ResourcesPlugin.getWorkspace().getRoot(); - } - - /** - * Creates and returns a subprogress monitor if appropriate. - */ - protected IProgressMonitor getSubProgressMonitor(int workAmount) { - IProgressMonitor sub = null; - if (progressMonitor != null) { - sub = new SubProgressMonitor(progressMonitor, workAmount, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK); - } - return sub; - } - - /** - * Returns whether this operation has performed any resource modifications. Returns false if this operation has not been executed - * yet. - */ - public boolean hasModifiedResource() { - return !this.isReadOnly() && this.getAttribute(HAS_MODIFIED_RESOURCE_ATTR) == TRUE; - } - - public void internalWorked(double work) { - if (progressMonitor != null) { - progressMonitor.internalWorked(work); - } - } - - /** - * @see IProgressMonitor - */ - public boolean isCanceled() { - if (progressMonitor != null) { - return progressMonitor.isCanceled(); - } - return false; - } - - /** - * Returns true if this operation performs no resource modifications, otherwise false. Subclasses - * must override. - */ - public boolean isReadOnly() { - return false; - } - - /* - * Returns whether this operation is the first operation to run in the current thread. - */ - protected boolean isTopLevelOperation() { - ArrayList stack; - return (stack = this.getCurrentOperationStack()).size() > 0 && stack.get(0) == this; - } - - /* - * Returns the index of the first registered action with the given id, starting from a given position. Returns -1 if not found. - */ - protected int firstActionWithID(String id, int start) { - for (int i = start; i <= this.actionsEnd; i++) { - if (this.actions[i].getID().equals(id)) { - return i; - } - } - return -1; - } - - /** - * Convenience method to move resources - */ - protected void moveResources(IResource[] resources, IPath destinationPath) throws JavaModelException { - IProgressMonitor subProgressMonitor = null; - if (progressMonitor != null) { - subProgressMonitor = new SubProgressMonitor(progressMonitor, resources.length, - SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK); - } - IWorkspace workspace = resources[0].getWorkspace(); - try { - workspace.move(resources, destinationPath, false, subProgressMonitor); - this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); - } catch (CoreException e) { - throw new JavaModelException(e); - } - } - - /** - * Creates and returns a new IJavaElementDelta on the Java Model. - */ - public JavaElementDelta newJavaElementDelta() { - return new JavaElementDelta(getJavaModel()); - } - - /* - * Removes the last pushed operation from the stack of running operations. Returns the poped operation or null if the stack was - * empty. - */ - protected JavaModelOperation popOperation() { - ArrayList stack = getCurrentOperationStack(); - int size = stack.size(); - if (size > 0) { - if (size == 1) { // top level operation - operationStacks.setCurrent(null); // release reference (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=33927) - } - return (JavaModelOperation) stack.remove(size - 1); - } else { - return null; - } - } - - /* - * Registers the given action to be run when the outer most java model operation has finished. The insertion mode controls - * whether: - the action should discard all existing actions with the same id, and be queued at the end (REMOVEALL_APPEND), - the - * action should be ignored if there is already an action with the same id (KEEP_EXISTING), - the action should be queued at the - * end without looking at existing actions (APPEND) - */ - protected void postAction(IPostAction action, int insertionMode) { - if (POST_ACTION_VERBOSE) { - System.out - .print("(" + Thread.currentThread() + ") [JavaModelOperation.postAction(IPostAction, int)] Posting action " + action.getID()); //$NON-NLS-1$ //$NON-NLS-2$ - switch (insertionMode) { - case REMOVEALL_APPEND: - System.out.println(" (REMOVEALL_APPEND)"); //$NON-NLS-1$ - break; - case KEEP_EXISTING: - System.out.println(" (KEEP_EXISTING)"); //$NON-NLS-1$ - break; - case APPEND: - System.out.println(" (APPEND)"); //$NON-NLS-1$ - break; - } - } - - JavaModelOperation topLevelOp = (JavaModelOperation) getCurrentOperationStack().get(0); - IPostAction[] postActions = topLevelOp.actions; - if (postActions == null) { - topLevelOp.actions = postActions = new IPostAction[1]; - postActions[0] = action; - topLevelOp.actionsEnd = 0; - } else { - String id = action.getID(); - switch (insertionMode) { - case REMOVEALL_APPEND: - int index = this.actionsStart - 1; - while ((index = topLevelOp.firstActionWithID(id, index + 1)) >= 0) { - // remove action[index] - System.arraycopy(postActions, index + 1, postActions, index, topLevelOp.actionsEnd - index); - postActions[topLevelOp.actionsEnd--] = null; - } - topLevelOp.addAction(action); - break; - case KEEP_EXISTING: - if (topLevelOp.firstActionWithID(id, 0) < 0) { - topLevelOp.addAction(action); - } - break; - case APPEND: - topLevelOp.addAction(action); - break; - } - } - } - - /* - * Returns whether the given path is the prefix of one of the given other paths. - */ - protected boolean prefixesOneOf(IPath path, IPath[] otherPaths) { - for (int i = 0, length = otherPaths.length; i < length; i++) { - if (path.isPrefixOf(otherPaths[i])) { - return true; - } - } - return false; - } - - /* - * Pushes the given operation on the stack of operations currently running in this thread. - */ - protected void pushOperation(JavaModelOperation operation) { - getCurrentOperationStack().add(operation); - } - - /** - * Main entry point for Java Model operations. Executes this operation and registers any deltas created. - * - * @see IWorkspaceRunnable - * @exception CoreException - * if the operation fails - */ - public void run(IProgressMonitor monitor) throws CoreException { - JavaModelManager manager = JavaModelManager.getJavaModelManager(); - DeltaProcessor deltaProcessor = manager.getDeltaProcessor(); - int previousDeltaCount = deltaProcessor.javaModelDeltas.size(); - try { - progressMonitor = monitor; - pushOperation(this); - try { - // computes the root infos before executing the operation - // noop if aready initialized - JavaModelManager.getJavaModelManager().deltaState.initializeRoots(); - - executeOperation(); - } finally { - if (this.isTopLevelOperation()) { - this.runPostActions(); - } - } - } finally { - - try { - // update JavaModel using deltas that were recorded during this operation - for (int i = previousDeltaCount, size = manager.javaModelDeltas.size(); i < size; i++) { - manager.updateJavaModel((IJavaElementDelta)manager.javaModelDeltas.get(i)); - } - - // fire only iff: - // - the operation is a top level operation - // - the operation did produce some delta(s) - // - but the operation has not modified any resource - if (this.isTopLevelOperation()) { - if ((manager.javaModelDeltas.size() > previousDeltaCount || !manager.reconcileDeltas.isEmpty()) - && !this.hasModifiedResource()) { - manager.fire(null, JavaModelManager.DEFAULT_CHANGE_EVENT); - } // else deltas are fired while processing the resource delta - } - } finally { - popOperation(); - } - } - } - - /** - * Main entry point for Java Model operations. Runs a Java Model Operation as an IWorkspaceRunnable if not read-only. - */ - public void runOperation(IProgressMonitor monitor) throws JavaModelException { - IJavaModelStatus status = verify(); - if (!status.isOK()) { - throw new JavaModelException(status); - } - try { - if (isReadOnly()) { - run(monitor); - } else { - // Use IWorkspace.run(...) to ensure that a build will be done in autobuild mode. - // Note that if the tree is locked, this will throw a CoreException, but this is ok - // as this operation is modifying the tree (not read-only) and a CoreException will be thrown anyway. - ResourcesPlugin.getWorkspace().run(this, getSchedulingRule(), IWorkspace.AVOID_UPDATE, monitor); - } - } catch (CoreException ce) { - if (ce instanceof JavaModelException) { - throw (JavaModelException) ce; - } else { - if (ce.getStatus().getCode() == IResourceStatus.OPERATION_FAILED) { - Throwable e = ce.getStatus().getException(); - if (e instanceof JavaModelException) { - throw (JavaModelException) e; - } - } - throw new JavaModelException(ce); - } - } - } - - protected void runPostActions() throws JavaModelException { - while (this.actionsStart <= this.actionsEnd) { - IPostAction postAction = this.actions[this.actionsStart++]; - if (POST_ACTION_VERBOSE) { - System.out - .println("(" + Thread.currentThread() + ") [JavaModelOperation.runPostActions()] Running action " + postAction.getID()); //$NON-NLS-1$ //$NON-NLS-2$ - } - postAction.run(); - } - } - - /* - * Registers the given attribute at the given key with the top level operation. - */ - protected void setAttribute(Object key, Object attribute) { - JavaModelOperation topLevelOp = (JavaModelOperation) this.getCurrentOperationStack().get(0); - if (topLevelOp.attributes == null) { - topLevelOp.attributes = new HashMap(); - } - topLevelOp.attributes.put(key, attribute); - } - - /** - * @see IProgressMonitor - */ - public void setCanceled(boolean b) { - if (progressMonitor != null) { - progressMonitor.setCanceled(b); - } - } - - /** - * Sets whether this operation is nested or not. - * - * @see CreateElementInCUOperation#checkCanceled - */ - protected void setNested(boolean nested) { - isNested = nested; - } - - /** - * @see IProgressMonitor - */ - public void setTaskName(String name) { - if (progressMonitor != null) { - progressMonitor.setTaskName(name); - } - } - - /** - * @see IProgressMonitor - */ - public void subTask(String name) { - if (progressMonitor != null) { - progressMonitor.subTask(name); - } - } - - /** - * Returns a status indicating if there is any known reason this operation will fail. Operations are verified before they are run. - * - * Subclasses must override if they have any conditions to verify before this operation executes. - * - * @see IJavaModelStatus - */ - protected IJavaModelStatus verify() { - return commonVerify(); - } - - /** - * @see IProgressMonitor - */ - public void worked(int work) { - if (progressMonitor != null) { - progressMonitor.worked(work); - checkCanceled(); - } - } +public abstract class JavaModelOperation implements IWorkspaceRunnable, + IProgressMonitor { + protected interface IPostAction { + /* + * Returns the id of this action. + * + * @see JavaModelOperation#postAction + */ + String getID(); + + /* + * Run this action. + */ + void run() throws JavaModelException; + } + + /* + * Constants controlling the insertion mode of an action. + * + * @see JavaModelOperation#postAction + */ + protected static final int APPEND = 1; // insert at the end + + protected static final int REMOVEALL_APPEND = 2; // remove all existing + // ones with same ID, + // and add new one at + // the end + + protected static final int KEEP_EXISTING = 3; // do not insert if already + // existing with same ID + + /* + * Whether tracing post actions is enabled. + */ + protected static boolean POST_ACTION_VERBOSE; + + /* + * A list of IPostActions. + */ + protected IPostAction[] actions; + + protected int actionsStart = 0; + + protected int actionsEnd = -1; + + /* + * A HashMap of attributes that can be used by operations + */ + protected HashMap attributes; + + public static final String HAS_MODIFIED_RESOURCE_ATTR = "hasModifiedResource"; //$NON-NLS-1$ + + public static final String TRUE = "true"; //$NON-NLS-1$ + + // public static final String FALSE = "false"; //$NON-NLS-1$ + + /** + * The elements this operation operates on, or null if this + * operation does not operate on specific elements. + */ + protected IJavaElement[] fElementsToProcess; + + /** + * The parent elements this operation operates with or null + * if this operation does not operate with specific parent elements. + */ + protected IJavaElement[] fParentElements; + + /** + * An empty collection of IJavaElement s - the common empty + * result if no elements are created, or if this operation is not actually + * executed. + */ + protected static IJavaElement[] NO_ELEMENTS = new IJavaElement[] {}; + + /** + * The elements created by this operation - empty until the operation + * actually creates elements. + */ + protected IJavaElement[] resultElements = NO_ELEMENTS; + + /** + * The progress monitor passed into this operation + */ + protected IProgressMonitor progressMonitor = null; + + /** + * A flag indicating whether this operation is nested. + */ + protected boolean isNested = false; + + /** + * Conflict resolution policy - by default do not force (fail on a + * conflict). + */ + protected boolean force = false; + + /* + * A per thread stack of java model operations (PerThreadObject of + * ArrayList). + */ + protected static PerThreadObject operationStacks = new PerThreadObject(); + + protected JavaModelOperation() { + } + + /** + * A common constructor for all Java Model operations. + */ + protected JavaModelOperation(IJavaElement[] elements) { + fElementsToProcess = elements; + } + + /** + * Common constructor for all Java Model operations. + */ + protected JavaModelOperation(IJavaElement[] elementsToProcess, + IJavaElement[] parentElements) { + fElementsToProcess = elementsToProcess; + fParentElements = parentElements; + } + + /** + * A common constructor for all Java Model operations. + */ + protected JavaModelOperation(IJavaElement[] elementsToProcess, + IJavaElement[] parentElements, boolean force) { + fElementsToProcess = elementsToProcess; + fParentElements = parentElements; + this.force = force; + } + + /** + * A common constructor for all Java Model operations. + */ + protected JavaModelOperation(IJavaElement[] elements, boolean force) { + fElementsToProcess = elements; + this.force = force; + } + + /** + * Common constructor for all Java Model operations. + */ + protected JavaModelOperation(IJavaElement element) { + fElementsToProcess = new IJavaElement[] { element }; + } + + /** + * A common constructor for all Java Model operations. + */ + protected JavaModelOperation(IJavaElement element, boolean force) { + fElementsToProcess = new IJavaElement[] { element }; + this.force = force; + } + + /* + * Registers the given action at the end of the list of actions to run. + */ + protected void addAction(IPostAction action) { + int length = this.actions.length; + if (length == ++this.actionsEnd) { + System.arraycopy(this.actions, 0, + this.actions = new IPostAction[length * 2], 0, length); + } + this.actions[this.actionsEnd] = action; + } + + /* + * Registers the given delta with the Java Model Manager. + */ + protected void addDelta(IJavaElementDelta delta) { + JavaModelManager.getJavaModelManager().registerJavaModelDelta(delta); + } + + /* + * Registers the given reconcile delta with the Java Model Manager. + */ + protected void addReconcileDelta(IWorkingCopy workingCopy, + IJavaElementDelta delta) { + HashMap reconcileDeltas = JavaModelManager.getJavaModelManager().reconcileDeltas; + JavaElementDelta previousDelta = (JavaElementDelta) reconcileDeltas + .get(workingCopy); + if (previousDelta != null) { + IJavaElementDelta[] children = delta.getAffectedChildren(); + for (int i = 0, length = children.length; i < length; i++) { + JavaElementDelta child = (JavaElementDelta) children[i]; + previousDelta.insertDeltaTree(child.getElement(), child); + } + } else { + reconcileDeltas.put(workingCopy, delta); + } + } + + /* + * Deregister the reconcile delta for the given working copy + */ + protected void removeReconcileDelta(IWorkingCopy workingCopy) { + JavaModelManager.getJavaModelManager().reconcileDeltas + .remove(workingCopy); + } + + /** + * @see IProgressMonitor + */ + public void beginTask(String name, int totalWork) { + if (progressMonitor != null) { + progressMonitor.beginTask(name, totalWork); + } + } + + /** + * Checks with the progress monitor to see whether this operation should be + * canceled. An operation should regularly call this method during its + * operation so that the user can cancel it. + * + * @exception OperationCanceledException + * if cancelling the operation has been requested + * @see IProgressMonitor#isCanceled + */ + protected void checkCanceled() { + if (isCanceled()) { + throw new OperationCanceledException(Util + .bind("operation.cancelled")); //$NON-NLS-1$ + } + } + + /** + * Common code used to verify the elements this operation is processing. + * + * @see JavaModelOperation#verify() + */ + protected IJavaModelStatus commonVerify() { + if (fElementsToProcess == null || fElementsToProcess.length == 0) { + return new JavaModelStatus( + IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS); + } + for (int i = 0; i < fElementsToProcess.length; i++) { + if (fElementsToProcess[i] == null) { + return new JavaModelStatus( + IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS); + } + } + return JavaModelStatus.VERIFIED_OK; + } + + /** + * Convenience method to copy resources + */ + protected void copyResources(IResource[] resources, IPath destinationPath) + throws JavaModelException { + IProgressMonitor subProgressMonitor = getSubProgressMonitor(resources.length); + IWorkspace workspace = resources[0].getWorkspace(); + try { + workspace.copy(resources, destinationPath, false, + subProgressMonitor); + this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); + } catch (CoreException e) { + throw new JavaModelException(e); + } + } + + /** + * Convenience method to create a file + */ + protected void createFile(IContainer folder, String name, + InputStream contents, boolean force) throws JavaModelException { + IFile file = folder.getFile(new Path(name)); + try { + file.create(contents, force ? IResource.FORCE + | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY, + getSubProgressMonitor(1)); + this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); + } catch (CoreException e) { + throw new JavaModelException(e); + } + } + + /** + * Convenience method to create a folder + */ + protected void createFolder(IContainer parentFolder, String name, + boolean force) throws JavaModelException { + IFolder folder = parentFolder.getFolder(new Path(name)); + try { + // we should use true to create the file locally. Only VCM should + // use tru/false + folder.create(force ? IResource.FORCE | IResource.KEEP_HISTORY + : IResource.KEEP_HISTORY, true, // local + getSubProgressMonitor(1)); + this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); + } catch (CoreException e) { + throw new JavaModelException(e); + } + } + + /** + * Convenience method to delete an empty package fragment + */ + protected void deleteEmptyPackageFragment(IPackageFragment fragment, + boolean force, IResource rootResource) throws JavaModelException { + + IContainer resource = (IContainer) fragment.getResource(); + + try { + resource.delete(force ? IResource.FORCE | IResource.KEEP_HISTORY + : IResource.KEEP_HISTORY, getSubProgressMonitor(1)); + this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); + while (resource instanceof IFolder) { + // deleting a package: delete the parent if it is empty (eg. + // deleting x.y where folder x doesn't have resources but y) + // without deleting the package fragment root + resource = resource.getParent(); + if (!resource.equals(rootResource) + && resource.members().length == 0) { + resource.delete(force ? IResource.FORCE + | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY, + getSubProgressMonitor(1)); + this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); + } + } + } catch (CoreException e) { + throw new JavaModelException(e); + } + } + + /** + * Convenience method to delete a resource + */ + protected void deleteResource(IResource resource, int flags) + throws JavaModelException { + try { + resource.delete(flags, getSubProgressMonitor(1)); + this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); + } catch (CoreException e) { + throw new JavaModelException(e); + } + } + + /** + * Convenience method to delete resources + */ + protected void deleteResources(IResource[] resources, boolean force) + throws JavaModelException { + if (resources == null || resources.length == 0) + return; + IProgressMonitor subProgressMonitor = getSubProgressMonitor(resources.length); + IWorkspace workspace = resources[0].getWorkspace(); + try { + workspace.delete(resources, force ? IResource.FORCE + | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY, + subProgressMonitor); + this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); + } catch (CoreException e) { + throw new JavaModelException(e); + } + } + + /** + * @see IProgressMonitor + */ + public void done() { + if (progressMonitor != null) { + progressMonitor.done(); + } + } + + /* + * Returns whether the given path is equals to one of the given other paths. + */ + protected boolean equalsOneOf(IPath path, IPath[] otherPaths) { + for (int i = 0, length = otherPaths.length; i < length; i++) { + if (path.equals(otherPaths[i])) { + return true; + } + } + return false; + } + + /** + * Verifies the operation can proceed and executes the operation. Subclasses + * should override #verify and executeOperation + * to implement the specific operation behavior. + * + * @exception JavaModelException + * The operation has failed. + */ + // protected void execute() throws JavaModelException { + // IJavaModelStatus status= verify(); + // if (status.isOK()) { + // // if first time here, computes the root infos before executing the + // operation + // DeltaProcessor deltaProcessor = + // JavaModelManager.getJavaModelManager().deltaProcessor; + // if (deltaProcessor.roots == null) { + // deltaProcessor.initializeRoots(); + // } + // executeOperation(); + // } else { + // throw new JavaModelException(status); + // } + // } + /** + * Convenience method to run an operation within this operation + */ + public void executeNestedOperation(JavaModelOperation operation, + int subWorkAmount) throws JavaModelException { + IProgressMonitor subProgressMonitor = getSubProgressMonitor(subWorkAmount); + // fix for 1FW7IKC, part (1) + try { + operation.setNested(true); + operation.run(subProgressMonitor); + } catch (CoreException ce) { + if (ce instanceof JavaModelException) { + throw (JavaModelException) ce; + } else { + // translate the core exception to a java model exception + if (ce.getStatus().getCode() == IResourceStatus.OPERATION_FAILED) { + Throwable e = ce.getStatus().getException(); + if (e instanceof JavaModelException) { + throw (JavaModelException) e; + } + } + throw new JavaModelException(ce); + } + } + } + + /** + * Performs the operation specific behavior. Subclasses must override. + */ + protected abstract void executeOperation() throws JavaModelException; + + /* + * Returns the attribute registered at the given key with the top level + * operation. Returns null if no such attribute is found. + */ + protected Object getAttribute(Object key) { + ArrayList stack = this.getCurrentOperationStack(); + if (stack.size() == 0) + return null; + JavaModelOperation topLevelOp = (JavaModelOperation) stack.get(0); + if (topLevelOp.attributes == null) { + return null; + } else { + return topLevelOp.attributes.get(key); + } + } + + /** + * Returns the compilation unit the given element is contained in, or the + * element itself (if it is a compilation unit), otherwise null. + */ + protected ICompilationUnit getCompilationUnitFor(IJavaElement element) { + + return ((JavaElement) element).getCompilationUnit(); + } + + /* + * Returns the stack of operations running in the current thread. Returns an + * empty stack if no operations are currently running in this thread. + */ + protected ArrayList getCurrentOperationStack() { + ArrayList stack = (ArrayList) operationStacks.getCurrent(); + if (stack == null) { + stack = new ArrayList(); + operationStacks.setCurrent(stack); + } + return stack; + } + + /** + * Returns the elements to which this operation applies, or + * null if not applicable. + */ + protected IJavaElement[] getElementsToProcess() { + return fElementsToProcess; + } + + /** + * Returns the element to which this operation applies, or null + * if not applicable. + */ + protected IJavaElement getElementToProcess() { + if (fElementsToProcess == null || fElementsToProcess.length == 0) { + return null; + } + return fElementsToProcess[0]; + } + + /** + * Returns the Java Model this operation is operating in. + */ + public IJavaModel getJavaModel() { + if (fElementsToProcess == null || fElementsToProcess.length == 0) { + return getParentElement().getJavaModel(); + } else { + return fElementsToProcess[0].getJavaModel(); + } + } + + // protected IPath[] getNestedFolders(IPackageFragmentRoot root) throws + // JavaModelException { + // IPath rootPath = root.getPath(); + // IClasspathEntry[] classpath = root.getJavaProject().getRawClasspath(); + // int length = classpath.length; + // IPath[] result = new IPath[length]; + // int index = 0; + // for (int i = 0; i < length; i++) { + // IPath path = classpath[i].getPath(); + // if (rootPath.isPrefixOf(path) && !rootPath.equals(path)) { + // result[index++] = path; + // } + // } + // if (index < length) { + // System.arraycopy(result, 0, result = new IPath[index], 0, index); + // } + // return result; + // } + /** + * Returns the parent element to which this operation applies, or + * null if not applicable. + */ + protected IJavaElement getParentElement() { + if (fParentElements == null || fParentElements.length == 0) { + return null; + } + return fParentElements[0]; + } + + /** + * Returns the parent elements to which this operation applies, or + * null if not applicable. + */ + protected IJavaElement[] getParentElements() { + return fParentElements; + } + + /** + * Returns the elements created by this operation. + */ + public IJavaElement[] getResultElements() { + return resultElements; + } + + /* + * Returns the scheduling rule for this operation (i.e. the resource that + * needs to be locked while this operation is running. Subclasses can + * override. + */ + protected ISchedulingRule getSchedulingRule() { + return ResourcesPlugin.getWorkspace().getRoot(); + } + + /** + * Creates and returns a subprogress monitor if appropriate. + */ + protected IProgressMonitor getSubProgressMonitor(int workAmount) { + IProgressMonitor sub = null; + if (progressMonitor != null) { + sub = new SubProgressMonitor(progressMonitor, workAmount, + SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK); + } + return sub; + } + + /** + * Returns whether this operation has performed any resource modifications. + * Returns false if this operation has not been executed yet. + */ + public boolean hasModifiedResource() { + return !this.isReadOnly() + && this.getAttribute(HAS_MODIFIED_RESOURCE_ATTR) == TRUE; + } + + public void internalWorked(double work) { + if (progressMonitor != null) { + progressMonitor.internalWorked(work); + } + } + + /** + * @see IProgressMonitor + */ + public boolean isCanceled() { + if (progressMonitor != null) { + return progressMonitor.isCanceled(); + } + return false; + } + + /** + * Returns true if this operation performs no resource + * modifications, otherwise false. Subclasses must override. + */ + public boolean isReadOnly() { + return false; + } + + /* + * Returns whether this operation is the first operation to run in the + * current thread. + */ + protected boolean isTopLevelOperation() { + ArrayList stack; + return (stack = this.getCurrentOperationStack()).size() > 0 + && stack.get(0) == this; + } + + /* + * Returns the index of the first registered action with the given id, + * starting from a given position. Returns -1 if not found. + */ + protected int firstActionWithID(String id, int start) { + for (int i = start; i <= this.actionsEnd; i++) { + if (this.actions[i].getID().equals(id)) { + return i; + } + } + return -1; + } + + /** + * Convenience method to move resources + */ + protected void moveResources(IResource[] resources, IPath destinationPath) + throws JavaModelException { + IProgressMonitor subProgressMonitor = null; + if (progressMonitor != null) { + subProgressMonitor = new SubProgressMonitor(progressMonitor, + resources.length, + SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK); + } + IWorkspace workspace = resources[0].getWorkspace(); + try { + workspace.move(resources, destinationPath, false, + subProgressMonitor); + this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); + } catch (CoreException e) { + throw new JavaModelException(e); + } + } + + /** + * Creates and returns a new IJavaElementDelta on the Java + * Model. + */ + public JavaElementDelta newJavaElementDelta() { + return new JavaElementDelta(getJavaModel()); + } + + /* + * Removes the last pushed operation from the stack of running operations. + * Returns the poped operation or null if the stack was empty. + */ + protected JavaModelOperation popOperation() { + ArrayList stack = getCurrentOperationStack(); + int size = stack.size(); + if (size > 0) { + if (size == 1) { // top level operation + operationStacks.setCurrent(null); // release reference (see + // http://bugs.eclipse.org/bugs/show_bug.cgi?id=33927) + } + return (JavaModelOperation) stack.remove(size - 1); + } else { + return null; + } + } + + /* + * Registers the given action to be run when the outer most java model + * operation has finished. The insertion mode controls whether: - the action + * should discard all existing actions with the same id, and be queued at + * the end (REMOVEALL_APPEND), - the action should be ignored if there is + * already an action with the same id (KEEP_EXISTING), - the action should + * be queued at the end without looking at existing actions (APPEND) + */ + protected void postAction(IPostAction action, int insertionMode) { + if (POST_ACTION_VERBOSE) { + System.out + .print("(" + Thread.currentThread() + ") [JavaModelOperation.postAction(IPostAction, int)] Posting action " + action.getID()); //$NON-NLS-1$ //$NON-NLS-2$ + switch (insertionMode) { + case REMOVEALL_APPEND: + System.out.println(" (REMOVEALL_APPEND)"); //$NON-NLS-1$ + break; + case KEEP_EXISTING: + System.out.println(" (KEEP_EXISTING)"); //$NON-NLS-1$ + break; + case APPEND: + System.out.println(" (APPEND)"); //$NON-NLS-1$ + break; + } + } + + JavaModelOperation topLevelOp = (JavaModelOperation) getCurrentOperationStack() + .get(0); + IPostAction[] postActions = topLevelOp.actions; + if (postActions == null) { + topLevelOp.actions = postActions = new IPostAction[1]; + postActions[0] = action; + topLevelOp.actionsEnd = 0; + } else { + String id = action.getID(); + switch (insertionMode) { + case REMOVEALL_APPEND: + int index = this.actionsStart - 1; + while ((index = topLevelOp.firstActionWithID(id, index + 1)) >= 0) { + // remove action[index] + System.arraycopy(postActions, index + 1, postActions, + index, topLevelOp.actionsEnd - index); + postActions[topLevelOp.actionsEnd--] = null; + } + topLevelOp.addAction(action); + break; + case KEEP_EXISTING: + if (topLevelOp.firstActionWithID(id, 0) < 0) { + topLevelOp.addAction(action); + } + break; + case APPEND: + topLevelOp.addAction(action); + break; + } + } + } + + /* + * Returns whether the given path is the prefix of one of the given other + * paths. + */ + protected boolean prefixesOneOf(IPath path, IPath[] otherPaths) { + for (int i = 0, length = otherPaths.length; i < length; i++) { + if (path.isPrefixOf(otherPaths[i])) { + return true; + } + } + return false; + } + + /* + * Pushes the given operation on the stack of operations currently running + * in this thread. + */ + protected void pushOperation(JavaModelOperation operation) { + getCurrentOperationStack().add(operation); + } + + /** + * Main entry point for Java Model operations. Executes this operation and + * registers any deltas created. + * + * @see IWorkspaceRunnable + * @exception CoreException + * if the operation fails + */ + public void run(IProgressMonitor monitor) throws CoreException { + JavaModelManager manager = JavaModelManager.getJavaModelManager(); + DeltaProcessor deltaProcessor = manager.getDeltaProcessor(); + int previousDeltaCount = deltaProcessor.javaModelDeltas.size(); + try { + progressMonitor = monitor; + pushOperation(this); + try { + // computes the root infos before executing the operation + // noop if aready initialized + JavaModelManager.getJavaModelManager().deltaState + .initializeRoots(); + + executeOperation(); + } finally { + if (this.isTopLevelOperation()) { + this.runPostActions(); + } + } + } finally { + + try { + // update JavaModel using deltas that were recorded during this + // operation + for (int i = previousDeltaCount, size = manager.javaModelDeltas + .size(); i < size; i++) { + manager + .updateJavaModel((IJavaElementDelta) manager.javaModelDeltas + .get(i)); + } + + // fire only iff: + // - the operation is a top level operation + // - the operation did produce some delta(s) + // - but the operation has not modified any resource + if (this.isTopLevelOperation()) { + if ((manager.javaModelDeltas.size() > previousDeltaCount || !manager.reconcileDeltas + .isEmpty()) + && !this.hasModifiedResource()) { + manager.fire(null, + JavaModelManager.DEFAULT_CHANGE_EVENT); + } // else deltas are fired while processing the resource + // delta + } + } finally { + popOperation(); + } + } + } + + /** + * Main entry point for Java Model operations. Runs a Java Model Operation + * as an IWorkspaceRunnable if not read-only. + */ + public void runOperation(IProgressMonitor monitor) + throws JavaModelException { + IJavaModelStatus status = verify(); + if (!status.isOK()) { + throw new JavaModelException(status); + } + try { + if (isReadOnly()) { + run(monitor); + } else { + // Use IWorkspace.run(...) to ensure that a build will be done + // in autobuild mode. + // Note that if the tree is locked, this will throw a + // CoreException, but this is ok + // as this operation is modifying the tree (not read-only) and a + // CoreException will be thrown anyway. + ResourcesPlugin.getWorkspace().run(this, getSchedulingRule(), + IWorkspace.AVOID_UPDATE, monitor); + } + } catch (CoreException ce) { + if (ce instanceof JavaModelException) { + throw (JavaModelException) ce; + } else { + if (ce.getStatus().getCode() == IResourceStatus.OPERATION_FAILED) { + Throwable e = ce.getStatus().getException(); + if (e instanceof JavaModelException) { + throw (JavaModelException) e; + } + } + throw new JavaModelException(ce); + } + } + } + + protected void runPostActions() throws JavaModelException { + while (this.actionsStart <= this.actionsEnd) { + IPostAction postAction = this.actions[this.actionsStart++]; + if (POST_ACTION_VERBOSE) { + System.out + .println("(" + Thread.currentThread() + ") [JavaModelOperation.runPostActions()] Running action " + postAction.getID()); //$NON-NLS-1$ //$NON-NLS-2$ + } + postAction.run(); + } + } + + /* + * Registers the given attribute at the given key with the top level + * operation. + */ + protected void setAttribute(Object key, Object attribute) { + JavaModelOperation topLevelOp = (JavaModelOperation) this + .getCurrentOperationStack().get(0); + if (topLevelOp.attributes == null) { + topLevelOp.attributes = new HashMap(); + } + topLevelOp.attributes.put(key, attribute); + } + + /** + * @see IProgressMonitor + */ + public void setCanceled(boolean b) { + if (progressMonitor != null) { + progressMonitor.setCanceled(b); + } + } + + /** + * Sets whether this operation is nested or not. + * + * @see CreateElementInCUOperation#checkCanceled + */ + protected void setNested(boolean nested) { + isNested = nested; + } + + /** + * @see IProgressMonitor + */ + public void setTaskName(String name) { + if (progressMonitor != null) { + progressMonitor.setTaskName(name); + } + } + + /** + * @see IProgressMonitor + */ + public void subTask(String name) { + if (progressMonitor != null) { + progressMonitor.subTask(name); + } + } + + /** + * Returns a status indicating if there is any known reason this operation + * will fail. Operations are verified before they are run. + * + * Subclasses must override if they have any conditions to verify before + * this operation executes. + * + * @see IJavaModelStatus + */ + protected IJavaModelStatus verify() { + return commonVerify(); + } + + /** + * @see IProgressMonitor + */ + public void worked(int work) { + if (progressMonitor != null) { + progressMonitor.worked(work); + checkCanceled(); + } + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelStatus.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelStatus.java index c1d7cd7..dd39b63 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelStatus.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelStatus.java @@ -26,427 +26,488 @@ import org.eclipse.core.runtime.Status; * @see IJavaModelStatus */ -public class JavaModelStatus - extends Status - implements IJavaModelStatus, IJavaModelStatusConstants, IResourceStatus { - - /** - * The elements related to the failure, or null - * if no elements are involved. - */ - protected IJavaElement[] fElements = new IJavaElement[0]; - - /** - * The path related to the failure, or null - * if no path is involved. - */ - protected IPath fPath; - /** - * The String related to the failure, or null - * if no String is involved. - */ - protected String fString; - /** - * Empty children - */ - protected final static IStatus[] fgEmptyChildren = new IStatus[] { - }; - protected IStatus[] fChildren = fgEmptyChildren; - - /** - * Shared empty collection used for efficiency. - */ - protected static IJavaElement[] fgObjectEmptyChildren = new IJavaElement[]{}; - - - /** - * Singleton OK object - */ - public static final IJavaModelStatus VERIFIED_OK = new JavaModelStatus(OK, OK, Util.bind("status.OK")); //$NON-NLS-1$ - - /** - * Constructs an Java model status with no corresponding elements. - */ - public JavaModelStatus() { - // no code for an multi-status - super(ERROR, JavaCore.PLUGIN_ID, 0, "JavaModelStatus", null); //$NON-NLS-1$ - } - /** - * Constructs an Java model status with no corresponding elements. - */ - public JavaModelStatus(int code) { - super(ERROR, JavaCore.PLUGIN_ID, code, "JavaModelStatus", null); //$NON-NLS-1$ - // fElements= JavaElementInfo.fgEmptyChildren; - fElements = fgObjectEmptyChildren; - } - /** - * Constructs an Java model status with the given corresponding - * elements. - */ - public JavaModelStatus(int code, IJavaElement[] elements) { - super(ERROR, JavaCore.PLUGIN_ID, code, "JavaModelStatus", null); //$NON-NLS-1$ - fElements = elements; - fPath = null; - } - /** - * Constructs an Java model status with no corresponding elements. - */ - public JavaModelStatus(int code, String string) { - this(ERROR, code, string); - } - /** - * Constructs an Java model status with no corresponding elements. - */ - public JavaModelStatus(int severity, int code, String string) { - super(severity, JavaCore.PLUGIN_ID, code, "JavaModelStatus", null); //$NON-NLS-1$ - // fElements= JavaElementInfo.fgEmptyChildren; - fElements = fgObjectEmptyChildren; - fPath = null; - fString = string; - } - /** - * Constructs an Java model status with no corresponding elements. - */ - public JavaModelStatus(int code, Throwable throwable) { - super(ERROR, JavaCore.PLUGIN_ID, code, "JavaModelStatus", throwable); //$NON-NLS-1$ - // fElements= JavaElementInfo.fgEmptyChildren; - fElements = fgObjectEmptyChildren; - } - /** - * Constructs an Java model status with no corresponding elements. - */ - public JavaModelStatus(int code, IPath path) { - super(ERROR, JavaCore.PLUGIN_ID, code, "JavaModelStatus", null); //$NON-NLS-1$ - // fElements= JavaElementInfo.fgEmptyChildren; - fElements = fgObjectEmptyChildren; - fPath = path; - } - /** - * Constructs an Java model status with the given corresponding - * element. - */ - public JavaModelStatus(int code, IJavaElement element) { - this(code, new IJavaElement[]{element}); - } - /** - * Constructs an Java model status with the given corresponding - * element and string - */ - public JavaModelStatus(int code, IJavaElement element, String string) { - this(code, new IJavaElement[]{element}); - fString = string; - } - - /** - * Constructs an Java model status with the given corresponding - * element and path - */ - public JavaModelStatus(int code, IJavaElement element, IPath path) { - this(code, new IJavaElement[]{element}); - fPath = path; - } - /** - * Constructs an Java model status with no corresponding elements. - */ - public JavaModelStatus(CoreException coreException) { - super(ERROR, JavaCore.PLUGIN_ID, CORE_EXCEPTION, "JavaModelStatus", coreException); //$NON-NLS-1$ - // fElements= JavaElementInfo.fgEmptyChildren; - fElements = fgObjectEmptyChildren; - } - protected int getBits() { - int severity = 1 << (getCode() % 100 / 33); - int category = 1 << ((getCode() / 100) + 3); - return severity | category; - } - /** - * @see IStatus - */ - public IStatus[] getChildren() { - return fChildren; - } - /** - * @see IJavaModelStatus - */ - public IJavaElement[] getElements() { - return fElements; - } - /** - * Returns the message that is relevant to the code of this status. - */ - public String getMessage() { - Throwable exception = getException(); - if (exception == null) { - switch (getCode()) { - case CORE_EXCEPTION : - return Util.bind("status.coreException"); //$NON-NLS-1$ - - case BUILDER_INITIALIZATION_ERROR : - return Util.bind("build.initializationError"); //$NON-NLS-1$ - - case BUILDER_SERIALIZATION_ERROR : - return Util.bind("build.serializationError"); //$NON-NLS-1$ - - case DEVICE_PATH : - return Util.bind("status.cannotUseDeviceOnPath", getPath().toString()); //$NON-NLS-1$ - - case DOM_EXCEPTION : - return Util.bind("status.JDOMError"); //$NON-NLS-1$ - -// case ELEMENT_DOES_NOT_EXIST: -// return ProjectPrefUtil.bind("element.doesNotExist",((JavaElement)fElements[0]).toStringWithAncestors()); //$NON-NLS-1$ - - case EVALUATION_ERROR : - return Util.bind("status.evaluationError", fString); //$NON-NLS-1$ - - case INDEX_OUT_OF_BOUNDS : - return Util.bind("status.indexOutOfBounds"); //$NON-NLS-1$ - - case INVALID_CONTENTS : - return Util.bind("status.invalidContents"); //$NON-NLS-1$ - - // case INVALID_DESTINATION: - // return ProjectPrefUtil.bind("status.invalidDestination", ((JavaElement)fElements[0]).toStringWithAncestors()); //$NON-NLS-1$ - // - // case INVALID_ELEMENT_TYPES: - // StringBuffer buff= new StringBuffer(ProjectPrefUtil.bind("operation.notSupported")); //$NON-NLS-1$ - // for (int i= 0; i < fElements.length; i++) { - // if (i > 0) { - // buff.append(", "); //$NON-NLS-1$ - // } - // buff.append(((JavaElement)fElements[i]).toStringWithAncestors()); - // } - // return buff.toString(); - - case INVALID_NAME : - return Util.bind("status.invalidName", fString); //$NON-NLS-1$ - - case INVALID_PACKAGE : - return Util.bind("status.invalidPackage", fString); //$NON-NLS-1$ - - case INVALID_PATH : - if (fString != null) { - return fString; - } else { - return Util.bind("status.invalidPath", getPath() == null ? "null" : getPath().toString()); //$NON-NLS-1$ //$NON-NLS-2$ - } - - case INVALID_PROJECT : - return Util.bind("status.invalidProject", fString); //$NON-NLS-1$ - - case INVALID_RESOURCE : - return Util.bind("status.invalidResource", fString); //$NON-NLS-1$ - - case INVALID_RESOURCE_TYPE : - return Util.bind("status.invalidResourceType", fString); //$NON-NLS-1$ - - // case INVALID_SIBLING: - // if (fString != null) { - // return ProjectPrefUtil.bind("status.invalidSibling", fString); //$NON-NLS-1$ - // } else { - // return ProjectPrefUtil.bind("status.invalidSibling", ((JavaElement)fElements[0]).toStringWithAncestors()); //$NON-NLS-1$ - // } - - case IO_EXCEPTION : - return Util.bind("status.IOException"); //$NON-NLS-1$ - - // case NAME_COLLISION: - // if (fElements != null && fElements.length > 0) { - // IJavaElement element = fElements[0]; - // String name = element.getElementName(); - // if (element instanceof IPackageFragment && name.equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) { - // return ProjectPrefUtil.bind("operation.cannotRenameDefaultPackage"); //$NON-NLS-1$ - // } - // } - // if (fString != null) { - // return fString; - // } else { - // return ProjectPrefUtil.bind("status.nameCollision", ""); //$NON-NLS-1$ //$NON-NLS-2$ - // } - case NO_ELEMENTS_TO_PROCESS : - return Util.bind("operation.needElements"); //$NON-NLS-1$ - - case NULL_NAME : - return Util.bind("operation.needName"); //$NON-NLS-1$ - - case NULL_PATH : - return Util.bind("operation.needPath"); //$NON-NLS-1$ - - case NULL_STRING : - return Util.bind("operation.needString"); //$NON-NLS-1$ - - // case PATH_OUTSIDE_PROJECT: - // return ProjectPrefUtil.bind("operation.pathOutsideProject", fString, ((JavaElement)fElements[0]).toStringWithAncestors()); //$NON-NLS-1$ - // - // case READ_ONLY: - // IJavaElement element = fElements[0]; - // String name = element.getElementName(); - // if (element instanceof IPackageFragment && name.equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) { - // return ProjectPrefUtil.bind("status.defaultPackageReadOnly"); //$NON-NLS-1$ - // } - // return ProjectPrefUtil.bind("status.readOnly", name); //$NON-NLS-1$ - - case RELATIVE_PATH : - return Util.bind("operation.needAbsolutePath", getPath().toString()); //$NON-NLS-1$ - - case TARGET_EXCEPTION : - return Util.bind("status.targetException"); //$NON-NLS-1$ - - case UPDATE_CONFLICT : - return Util.bind("status.updateConflict"); //$NON-NLS-1$ - - case NO_LOCAL_CONTENTS : - return Util.bind("status.noLocalContents", getPath().toString()); //$NON-NLS-1$ - - // case CP_CONTAINER_PATH_UNBOUND: - // IPath path = this.fPath; - // IJavaProject javaProject = (IJavaProject)fElements[0]; - // ClasspathContainerInitializer initializer = PHPCore.getClasspathContainerInitializer(path.segment(0)); - // String description = null; - // if (initializer != null) description = initializer.getDescription(path, javaProject); - // if (description == null) description = path.makeRelative().toString(); - // return ProjectPrefUtil.bind("classpath.unboundContainerPath", description); //$NON-NLS-1$ - // - // case INVALID_CP_CONTAINER_ENTRY: - // path = this.fPath; - // javaProject = (IJavaProject)fElements[0]; - // IClasspathContainer container = null; - // description = null; - // try { - // container = PHPCore.getClasspathContainer(path, javaProject); - // } catch(JavaModelException e){ - // } - // if (container == null) { - // initializer = PHPCore.getClasspathContainerInitializer(path.segment(0)); - // if (initializer != null) description = initializer.getDescription(path, javaProject); - // } else { - // description = container.getDescription(); - // } - // if (description == null) description = path.makeRelative().toString(); - // return ProjectPrefUtil.bind("classpath.invalidContainer", description); //$NON-NLS-1$ - // - // case CP_VARIABLE_PATH_UNBOUND: - // path = this.fPath; - // return ProjectPrefUtil.bind("classpath.unboundVariablePath", path.makeRelative().toString()); //$NON-NLS-1$ - // - // case CLASSPATH_CYCLE: - // javaProject = (IJavaProject)fElements[0]; - // return ProjectPrefUtil.bind("classpath.cycle", javaProject.getElementName()); //$NON-NLS-1$ - - // case DISABLED_CP_EXCLUSION_PATTERNS: - // path = this.fPath; - // return ProjectPrefUtil.bind("classpath.disabledExclusionPatterns", path.makeRelative().toString()); //$NON-NLS-1$ - // - // case DISABLED_CP_MULTIPLE_OUTPUT_LOCATIONS: - // path = this.fPath; - // return ProjectPrefUtil.bind("classpath.disabledMultipleOutputLocations", path.makeRelative().toString()); //$NON-NLS-1$ - } - if (fString != null) { - return fString; - } else { - return ""; // //$NON-NLS-1$ - } - } else { - String message = exception.getMessage(); - if (message != null) { - return message; - } else { - return exception.toString(); - } - } - } - /** - * @see IJavaModelStatus#getPath() - */ - public IPath getPath() { - return fPath; - } - /** - * @see IStatus#getSeverity() - */ - public int getSeverity() { - if (fChildren == fgEmptyChildren) - return super.getSeverity(); - int severity = -1; - for (int i = 0, max = fChildren.length; i < max; i++) { - int childrenSeverity = fChildren[i].getSeverity(); - if (childrenSeverity > severity) { - severity = childrenSeverity; - } - } - return severity; - } - /** - * @see IJavaModelStatus#getString() - * @deprecated - */ - public String getString() { - return fString; - } - /** - * @see IJavaModelStatus#isDoesNotExist() - */ - public boolean isDoesNotExist() { - return getCode() == ELEMENT_DOES_NOT_EXIST; - } - /** - * @see IStatus#isMultiStatus() - */ - public boolean isMultiStatus() { - return fChildren != fgEmptyChildren; - } - /** - * @see IStatus#isOK() - */ - public boolean isOK() { - return getCode() == OK; - } - /** - * @see IStatus#matches(int) - */ - public boolean matches(int mask) { - if (!isMultiStatus()) { - return matches(this, mask); - } else { - for (int i = 0, max = fChildren.length; i < max; i++) { - if (matches((JavaModelStatus) fChildren[i], mask)) - return true; - } - return false; - } - } - /** - * Helper for matches(int). - */ - protected boolean matches(JavaModelStatus status, int mask) { - int severityMask = mask & 0x7; - int categoryMask = mask & ~0x7; - int bits = status.getBits(); - return ((severityMask == 0) || (bits & severityMask) != 0) - && ((categoryMask == 0) || (bits & categoryMask) != 0); - } - /** - * Creates and returns a new IJavaModelStatus that is a - * a multi-status status. - * - * @see IStatus#isMultiStatus() - */ - public static IJavaModelStatus newMultiStatus(IJavaModelStatus[] children) { - JavaModelStatus jms = new JavaModelStatus(); - jms.fChildren = children; - return jms; - } - /** - * Returns a printable representation of this exception for debugging - * purposes. - */ - public String toString() { - if (this == VERIFIED_OK) { - return "JavaModelStatus[OK]"; //$NON-NLS-1$ - } - StringBuffer buffer = new StringBuffer(); - buffer.append("Java Model Status ["); //$NON-NLS-1$ - buffer.append(getMessage()); - buffer.append("]"); //$NON-NLS-1$ - return buffer.toString(); - } +public class JavaModelStatus extends Status implements IJavaModelStatus, + IJavaModelStatusConstants, IResourceStatus { + + /** + * The elements related to the failure, or null if no + * elements are involved. + */ + protected IJavaElement[] fElements = new IJavaElement[0]; + + /** + * The path related to the failure, or null if no path is + * involved. + */ + protected IPath fPath; + + /** + * The String related to the failure, or null + * if no String is involved. + */ + protected String fString; + + /** + * Empty children + */ + protected final static IStatus[] fgEmptyChildren = new IStatus[] {}; + + protected IStatus[] fChildren = fgEmptyChildren; + + /** + * Shared empty collection used for efficiency. + */ + protected static IJavaElement[] fgObjectEmptyChildren = new IJavaElement[] {}; + + /** + * Singleton OK object + */ + public static final IJavaModelStatus VERIFIED_OK = new JavaModelStatus(OK, + OK, Util.bind("status.OK")); //$NON-NLS-1$ + + /** + * Constructs an Java model status with no corresponding elements. + */ + public JavaModelStatus() { + // no code for an multi-status + super(ERROR, JavaCore.PLUGIN_ID, 0, "JavaModelStatus", null); //$NON-NLS-1$ + } + + /** + * Constructs an Java model status with no corresponding elements. + */ + public JavaModelStatus(int code) { + super(ERROR, JavaCore.PLUGIN_ID, code, "JavaModelStatus", null); //$NON-NLS-1$ + // fElements= JavaElementInfo.fgEmptyChildren; + fElements = fgObjectEmptyChildren; + } + + /** + * Constructs an Java model status with the given corresponding elements. + */ + public JavaModelStatus(int code, IJavaElement[] elements) { + super(ERROR, JavaCore.PLUGIN_ID, code, "JavaModelStatus", null); //$NON-NLS-1$ + fElements = elements; + fPath = null; + } + + /** + * Constructs an Java model status with no corresponding elements. + */ + public JavaModelStatus(int code, String string) { + this(ERROR, code, string); + } + + /** + * Constructs an Java model status with no corresponding elements. + */ + public JavaModelStatus(int severity, int code, String string) { + super(severity, JavaCore.PLUGIN_ID, code, "JavaModelStatus", null); //$NON-NLS-1$ + // fElements= JavaElementInfo.fgEmptyChildren; + fElements = fgObjectEmptyChildren; + fPath = null; + fString = string; + } + + /** + * Constructs an Java model status with no corresponding elements. + */ + public JavaModelStatus(int code, Throwable throwable) { + super(ERROR, JavaCore.PLUGIN_ID, code, "JavaModelStatus", throwable); //$NON-NLS-1$ + // fElements= JavaElementInfo.fgEmptyChildren; + fElements = fgObjectEmptyChildren; + } + + /** + * Constructs an Java model status with no corresponding elements. + */ + public JavaModelStatus(int code, IPath path) { + super(ERROR, JavaCore.PLUGIN_ID, code, "JavaModelStatus", null); //$NON-NLS-1$ + // fElements= JavaElementInfo.fgEmptyChildren; + fElements = fgObjectEmptyChildren; + fPath = path; + } + + /** + * Constructs an Java model status with the given corresponding element. + */ + public JavaModelStatus(int code, IJavaElement element) { + this(code, new IJavaElement[] { element }); + } + + /** + * Constructs an Java model status with the given corresponding element and + * string + */ + public JavaModelStatus(int code, IJavaElement element, String string) { + this(code, new IJavaElement[] { element }); + fString = string; + } + + /** + * Constructs an Java model status with the given corresponding element and + * path + */ + public JavaModelStatus(int code, IJavaElement element, IPath path) { + this(code, new IJavaElement[] { element }); + fPath = path; + } + + /** + * Constructs an Java model status with no corresponding elements. + */ + public JavaModelStatus(CoreException coreException) { + super(ERROR, JavaCore.PLUGIN_ID, CORE_EXCEPTION, + "JavaModelStatus", coreException); //$NON-NLS-1$ + // fElements= JavaElementInfo.fgEmptyChildren; + fElements = fgObjectEmptyChildren; + } + + protected int getBits() { + int severity = 1 << (getCode() % 100 / 33); + int category = 1 << ((getCode() / 100) + 3); + return severity | category; + } + + /** + * @see IStatus + */ + public IStatus[] getChildren() { + return fChildren; + } + + /** + * @see IJavaModelStatus + */ + public IJavaElement[] getElements() { + return fElements; + } + + /** + * Returns the message that is relevant to the code of this status. + */ + public String getMessage() { + Throwable exception = getException(); + if (exception == null) { + switch (getCode()) { + case CORE_EXCEPTION: + return Util.bind("status.coreException"); //$NON-NLS-1$ + + case BUILDER_INITIALIZATION_ERROR: + return Util.bind("build.initializationError"); //$NON-NLS-1$ + + case BUILDER_SERIALIZATION_ERROR: + return Util.bind("build.serializationError"); //$NON-NLS-1$ + + case DEVICE_PATH: + return Util.bind( + "status.cannotUseDeviceOnPath", getPath().toString()); //$NON-NLS-1$ + + case DOM_EXCEPTION: + return Util.bind("status.JDOMError"); //$NON-NLS-1$ + + // case ELEMENT_DOES_NOT_EXIST: + // return + // ProjectPrefUtil.bind("element.doesNotExist",((JavaElement)fElements[0]).toStringWithAncestors()); + // //$NON-NLS-1$ + + case EVALUATION_ERROR: + return Util.bind("status.evaluationError", fString); //$NON-NLS-1$ + + case INDEX_OUT_OF_BOUNDS: + return Util.bind("status.indexOutOfBounds"); //$NON-NLS-1$ + + case INVALID_CONTENTS: + return Util.bind("status.invalidContents"); //$NON-NLS-1$ + + // case INVALID_DESTINATION: + // return ProjectPrefUtil.bind("status.invalidDestination", + // ((JavaElement)fElements[0]).toStringWithAncestors()); + // //$NON-NLS-1$ + // + // case INVALID_ELEMENT_TYPES: + // StringBuffer buff= new + // StringBuffer(ProjectPrefUtil.bind("operation.notSupported")); + // //$NON-NLS-1$ + // for (int i= 0; i < fElements.length; i++) { + // if (i > 0) { + // buff.append(", "); //$NON-NLS-1$ + // } + // buff.append(((JavaElement)fElements[i]).toStringWithAncestors()); + // } + // return buff.toString(); + + case INVALID_NAME: + return Util.bind("status.invalidName", fString); //$NON-NLS-1$ + + case INVALID_PACKAGE: + return Util.bind("status.invalidPackage", fString); //$NON-NLS-1$ + + case INVALID_PATH: + if (fString != null) { + return fString; + } else { + return Util + .bind( + "status.invalidPath", getPath() == null ? "null" : getPath().toString()); //$NON-NLS-1$ //$NON-NLS-2$ + } + + case INVALID_PROJECT: + return Util.bind("status.invalidProject", fString); //$NON-NLS-1$ + + case INVALID_RESOURCE: + return Util.bind("status.invalidResource", fString); //$NON-NLS-1$ + + case INVALID_RESOURCE_TYPE: + return Util.bind("status.invalidResourceType", fString); //$NON-NLS-1$ + + // case INVALID_SIBLING: + // if (fString != null) { + // return ProjectPrefUtil.bind("status.invalidSibling", + // fString); //$NON-NLS-1$ + // } else { + // return ProjectPrefUtil.bind("status.invalidSibling", + // ((JavaElement)fElements[0]).toStringWithAncestors()); + // //$NON-NLS-1$ + // } + + case IO_EXCEPTION: + return Util.bind("status.IOException"); //$NON-NLS-1$ + + // case NAME_COLLISION: + // if (fElements != null && fElements.length > 0) { + // IJavaElement element = fElements[0]; + // String name = element.getElementName(); + // if (element instanceof IPackageFragment && + // name.equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) { + // return + // ProjectPrefUtil.bind("operation.cannotRenameDefaultPackage"); + // //$NON-NLS-1$ + // } + // } + // if (fString != null) { + // return fString; + // } else { + // return ProjectPrefUtil.bind("status.nameCollision", ""); + // //$NON-NLS-1$ //$NON-NLS-2$ + // } + case NO_ELEMENTS_TO_PROCESS: + return Util.bind("operation.needElements"); //$NON-NLS-1$ + + case NULL_NAME: + return Util.bind("operation.needName"); //$NON-NLS-1$ + + case NULL_PATH: + return Util.bind("operation.needPath"); //$NON-NLS-1$ + + case NULL_STRING: + return Util.bind("operation.needString"); //$NON-NLS-1$ + + // case PATH_OUTSIDE_PROJECT: + // return ProjectPrefUtil.bind("operation.pathOutsideProject", + // fString, + // ((JavaElement)fElements[0]).toStringWithAncestors()); + // //$NON-NLS-1$ + // + // case READ_ONLY: + // IJavaElement element = fElements[0]; + // String name = element.getElementName(); + // if (element instanceof IPackageFragment && + // name.equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) { + // return ProjectPrefUtil.bind("status.defaultPackageReadOnly"); + // //$NON-NLS-1$ + // } + // return ProjectPrefUtil.bind("status.readOnly", name); + // //$NON-NLS-1$ + + case RELATIVE_PATH: + return Util.bind( + "operation.needAbsolutePath", getPath().toString()); //$NON-NLS-1$ + + case TARGET_EXCEPTION: + return Util.bind("status.targetException"); //$NON-NLS-1$ + + case UPDATE_CONFLICT: + return Util.bind("status.updateConflict"); //$NON-NLS-1$ + + case NO_LOCAL_CONTENTS: + return Util + .bind("status.noLocalContents", getPath().toString()); //$NON-NLS-1$ + + // case CP_CONTAINER_PATH_UNBOUND: + // IPath path = this.fPath; + // IJavaProject javaProject = (IJavaProject)fElements[0]; + // ClasspathContainerInitializer initializer = + // PHPCore.getClasspathContainerInitializer(path.segment(0)); + // String description = null; + // if (initializer != null) description = + // initializer.getDescription(path, javaProject); + // if (description == null) description = + // path.makeRelative().toString(); + // return ProjectPrefUtil.bind("classpath.unboundContainerPath", + // description); //$NON-NLS-1$ + // + // case INVALID_CP_CONTAINER_ENTRY: + // path = this.fPath; + // javaProject = (IJavaProject)fElements[0]; + // IClasspathContainer container = null; + // description = null; + // try { + // container = PHPCore.getClasspathContainer(path, javaProject); + // } catch(JavaModelException e){ + // } + // if (container == null) { + // initializer = + // PHPCore.getClasspathContainerInitializer(path.segment(0)); + // if (initializer != null) description = + // initializer.getDescription(path, javaProject); + // } else { + // description = container.getDescription(); + // } + // if (description == null) description = + // path.makeRelative().toString(); + // return ProjectPrefUtil.bind("classpath.invalidContainer", + // description); //$NON-NLS-1$ + // + // case CP_VARIABLE_PATH_UNBOUND: + // path = this.fPath; + // return ProjectPrefUtil.bind("classpath.unboundVariablePath", + // path.makeRelative().toString()); //$NON-NLS-1$ + // + // case CLASSPATH_CYCLE: + // javaProject = (IJavaProject)fElements[0]; + // return ProjectPrefUtil.bind("classpath.cycle", + // javaProject.getElementName()); //$NON-NLS-1$ + + // case DISABLED_CP_EXCLUSION_PATTERNS: + // path = this.fPath; + // return + // ProjectPrefUtil.bind("classpath.disabledExclusionPatterns", + // path.makeRelative().toString()); //$NON-NLS-1$ + // + // case DISABLED_CP_MULTIPLE_OUTPUT_LOCATIONS: + // path = this.fPath; + // return + // ProjectPrefUtil.bind("classpath.disabledMultipleOutputLocations", + // path.makeRelative().toString()); //$NON-NLS-1$ + } + if (fString != null) { + return fString; + } else { + return ""; // //$NON-NLS-1$ + } + } else { + String message = exception.getMessage(); + if (message != null) { + return message; + } else { + return exception.toString(); + } + } + } + + /** + * @see IJavaModelStatus#getPath() + */ + public IPath getPath() { + return fPath; + } + + /** + * @see IStatus#getSeverity() + */ + public int getSeverity() { + if (fChildren == fgEmptyChildren) + return super.getSeverity(); + int severity = -1; + for (int i = 0, max = fChildren.length; i < max; i++) { + int childrenSeverity = fChildren[i].getSeverity(); + if (childrenSeverity > severity) { + severity = childrenSeverity; + } + } + return severity; + } + + /** + * @see IJavaModelStatus#getString() + * @deprecated + */ + public String getString() { + return fString; + } + + /** + * @see IJavaModelStatus#isDoesNotExist() + */ + public boolean isDoesNotExist() { + return getCode() == ELEMENT_DOES_NOT_EXIST; + } + + /** + * @see IStatus#isMultiStatus() + */ + public boolean isMultiStatus() { + return fChildren != fgEmptyChildren; + } + + /** + * @see IStatus#isOK() + */ + public boolean isOK() { + return getCode() == OK; + } + + /** + * @see IStatus#matches(int) + */ + public boolean matches(int mask) { + if (!isMultiStatus()) { + return matches(this, mask); + } else { + for (int i = 0, max = fChildren.length; i < max; i++) { + if (matches((JavaModelStatus) fChildren[i], mask)) + return true; + } + return false; + } + } + + /** + * Helper for matches(int). + */ + protected boolean matches(JavaModelStatus status, int mask) { + int severityMask = mask & 0x7; + int categoryMask = mask & ~0x7; + int bits = status.getBits(); + return ((severityMask == 0) || (bits & severityMask) != 0) + && ((categoryMask == 0) || (bits & categoryMask) != 0); + } + + /** + * Creates and returns a new IJavaModelStatus that is a a + * multi-status status. + * + * @see IStatus#isMultiStatus() + */ + public static IJavaModelStatus newMultiStatus(IJavaModelStatus[] children) { + JavaModelStatus jms = new JavaModelStatus(); + jms.fChildren = children; + return jms; + } + + /** + * Returns a printable representation of this exception for debugging + * purposes. + */ + public String toString() { + if (this == VERIFIED_OK) { + return "JavaModelStatus[OK]"; //$NON-NLS-1$ + } + StringBuffer buffer = new StringBuffer(); + buffer.append("Java Model Status ["); //$NON-NLS-1$ + buffer.append(getMessage()); + buffer.append("]"); //$NON-NLS-1$ + return buffer.toString(); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaProject.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaProject.java index e3fdb4d..ab66e39 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaProject.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaProject.java @@ -84,25 +84,25 @@ import org.xml.sax.XMLReader; /** * Handle for a Java Project. - * - *

                                      A Java Project internally maintains a devpath that corresponds - * to the project's classpath. The classpath may include source folders - * from the current project; jars in the current project, other projects, - * and the local file system; and binary folders (output location) of other - * projects. The Java Model presents source elements corresponding to output - * .class files in other projects, and thus uses the devpath rather than - * the classpath (which is really a compilation path). The devpath mimics - * the classpath, except has source folder entries in place of output - * locations in external projects. - * - *

                                      Each JavaProject has a NameLookup facility that locates elements - * on by name, based on the devpath. - * + * + *

                                      + * A Java Project internally maintains a devpath that corresponds to the + * project's classpath. The classpath may include source folders from the + * current project; jars in the current project, other projects, and the local + * file system; and binary folders (output location) of other projects. The Java + * Model presents source elements corresponding to output .class files in other + * projects, and thus uses the devpath rather than the classpath (which is + * really a compilation path). The devpath mimics the classpath, except has + * source folder entries in place of output locations in external projects. + * + *

                                      + * Each JavaProject has a NameLookup facility that locates elements on by name, + * based on the devpath. + * * @see IJavaProject */ -public class JavaProject - extends Openable - implements IJavaProject , IProjectNature { +public class JavaProject extends Openable implements IJavaProject, + IProjectNature { /** * Whether the underlying file system is case sensitive. @@ -110,7 +110,8 @@ public class JavaProject protected static final boolean IS_CASE_SENSITIVE = !new File("Temp").equals(new File("temp")); //$NON-NLS-1$ //$NON-NLS-2$ /** - * An empty array of strings indicating that a project doesn't have any prerequesite projects. + * An empty array of strings indicating that a project doesn't have any + * prerequesite projects. */ protected static final String[] NO_PREREQUISITES = new String[0]; @@ -118,111 +119,130 @@ public class JavaProject * The platform project this IJavaProject is based on */ protected IProject project; + protected List fLoadPathEntries; + protected boolean fScratched; - + /** * Name of file containing project classpath */ - public static final String CLASSPATH_FILENAME = ".classpath"; //$NON-NLS-1$ + public static final String CLASSPATH_FILENAME = ".classpath"; //$NON-NLS-1$ /** * Name of file containing custom project preferences */ - public static final String PREF_FILENAME = ".jprefs"; //$NON-NLS-1$ - + public static final String PREF_FILENAME = ".jprefs"; //$NON-NLS-1$ + /** - * Value of the project's raw classpath if the .classpath file contains invalid entries. + * Value of the project's raw classpath if the .classpath file contains + * invalid entries. */ public static final IClasspathEntry[] INVALID_CLASSPATH = new IClasspathEntry[0]; private static final String CUSTOM_DEFAULT_OPTION_VALUE = "#\r\n\r#custom-non-empty-default-value#\r\n\r#"; //$NON-NLS-1$ + /* * Value of project's resolved classpath while it is being resolved */ private static final IClasspathEntry[] RESOLUTION_IN_PROGRESS = new IClasspathEntry[0]; /** - * Returns a canonicalized path from the given external path. - * Note that the return path contains the same number of segments - * and it contains a device only if the given path contained one. + * Returns a canonicalized path from the given external path. Note that the + * return path contains the same number of segments and it contains a device + * only if the given path contained one. + * * @see java.io.File for the definition of a canonicalized path */ public static IPath canonicalizedPath(IPath externalPath) { - + if (externalPath == null) return null; if (JavaModelManager.VERBOSE) { - System.out.println("JAVA MODEL - Canonicalizing " + externalPath.toString()); //$NON-NLS-1$ + System.out + .println("JAVA MODEL - Canonicalizing " + externalPath.toString()); //$NON-NLS-1$ } if (IS_CASE_SENSITIVE) { if (JavaModelManager.VERBOSE) { - System.out.println("JAVA MODEL - Canonical path is original path (file system is case sensitive)"); //$NON-NLS-1$ + System.out + .println("JAVA MODEL - Canonical path is original path (file system is case sensitive)"); //$NON-NLS-1$ } return externalPath; } // if not external path, return original path IWorkspace workspace = ResourcesPlugin.getWorkspace(); - if (workspace == null) return externalPath; // protection during shutdown (30487) + if (workspace == null) + return externalPath; // protection during shutdown (30487) if (workspace.getRoot().findMember(externalPath) != null) { if (JavaModelManager.VERBOSE) { - System.out.println("JAVA MODEL - Canonical path is original path (member of workspace)"); //$NON-NLS-1$ + System.out + .println("JAVA MODEL - Canonical path is original path (member of workspace)"); //$NON-NLS-1$ } return externalPath; } IPath canonicalPath = null; try { - canonicalPath = - new Path(new File(externalPath.toOSString()).getCanonicalPath()); + canonicalPath = new Path(new File(externalPath.toOSString()) + .getCanonicalPath()); } catch (IOException e) { // default to original path if (JavaModelManager.VERBOSE) { - System.out.println("JAVA MODEL - Canonical path is original path (IOException)"); //$NON-NLS-1$ + System.out + .println("JAVA MODEL - Canonical path is original path (IOException)"); //$NON-NLS-1$ } return externalPath; } - + IPath result; int canonicalLength = canonicalPath.segmentCount(); if (canonicalLength == 0) { // the java.io.File canonicalization failed if (JavaModelManager.VERBOSE) { - System.out.println("JAVA MODEL - Canonical path is original path (canonical path is empty)"); //$NON-NLS-1$ + System.out + .println("JAVA MODEL - Canonical path is original path (canonical path is empty)"); //$NON-NLS-1$ } return externalPath; } else if (externalPath.isAbsolute()) { result = canonicalPath; } else { - // if path is relative, remove the first segments that were added by the java.io.File canonicalization - // e.g. 'lib/classes.zip' was converted to 'd:/myfolder/lib/classes.zip' + // if path is relative, remove the first segments that were added by + // the java.io.File canonicalization + // e.g. 'lib/classes.zip' was converted to + // 'd:/myfolder/lib/classes.zip' int externalLength = externalPath.segmentCount(); if (canonicalLength >= externalLength) { - result = canonicalPath.removeFirstSegments(canonicalLength - externalLength); + result = canonicalPath.removeFirstSegments(canonicalLength + - externalLength); } else { if (JavaModelManager.VERBOSE) { - System.out.println("JAVA MODEL - Canonical path is original path (canonical path is " + canonicalPath.toString() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ + System.out + .println("JAVA MODEL - Canonical path is original path (canonical path is " + canonicalPath.toString() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ } return externalPath; } } - - // keep device only if it was specified (this is because File.getCanonicalPath() converts '/lib/classed.zip' to 'd:/lib/classes/zip') + + // keep device only if it was specified (this is because + // File.getCanonicalPath() converts '/lib/classed.zip' to + // 'd:/lib/classes/zip') if (externalPath.getDevice() == null) { result = result.setDevice(null); - } + } if (JavaModelManager.VERBOSE) { - System.out.println("JAVA MODEL - Canonical path is " + result.toString()); //$NON-NLS-1$ + System.out + .println("JAVA MODEL - Canonical path is " + result.toString()); //$NON-NLS-1$ } return result; } /** - * Constructor needed for IProject.getNature() and IProject.addNature(). - * + * Constructor needed for IProject.getNature() and + * IProject.addNature(). + * * @see #setProject(IProject) */ public JavaProject() { @@ -233,6 +253,7 @@ public class JavaProject super(parent, project.getName()); this.project = project; } + public void addLoadPathEntry(IProject anotherPHPProject) { fScratched = true; @@ -241,14 +262,15 @@ public class JavaProject } public void configure() throws CoreException { - // get project description and then the associated build commands + // get project description and then the associated build commands IProjectDescription desc = project.getDescription(); ICommand[] commands = desc.getBuildSpec(); // determine if builder already associated boolean found = false; for (int i = 0; i < commands.length; ++i) { - if (commands[i].getBuilderName().equals(PHPeclipsePlugin.BUILDER_PARSER_ID)) { + if (commands[i].getBuilderName().equals( + PHPeclipsePlugin.BUILDER_PARSER_ID)) { found = true; break; } @@ -260,7 +282,7 @@ public class JavaProject command.setBuilderName(PHPeclipsePlugin.BUILDER_PARSER_ID); ICommand[] newCommands = new ICommand[commands.length + 1]; - // Add it before other builders. + // Add it before other builders. System.arraycopy(commands, 0, newCommands, 1, commands.length); newCommands[0] = command; desc.setBuildSpec(newCommands); @@ -269,20 +291,21 @@ public class JavaProject } protected void loadLoadPathEntries() { - fLoadPathEntries = new ArrayList(); + fLoadPathEntries = new ArrayList(); - IFile loadPathsFile = getLoadPathEntriesFile(); + IFile loadPathsFile = getLoadPathEntriesFile(); - XMLReader reader = null; - try { - reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); - reader.setContentHandler(getLoadPathEntriesContentHandler()); - reader.parse(new InputSource(loadPathsFile.getContents())); - } catch (Exception e) { - //the file is nonextant or unreadable - } + XMLReader reader = null; + try { + reader = SAXParserFactory.newInstance().newSAXParser() + .getXMLReader(); + reader.setContentHandler(getLoadPathEntriesContentHandler()); + reader.parse(new InputSource(loadPathsFile.getContents())); + } catch (Exception e) { + // the file is nonextant or unreadable } - + } + public List getLoadPathEntries() { if (fLoadPathEntries == null) { loadLoadPathEntries(); @@ -293,22 +316,26 @@ public class JavaProject protected ContentHandler getLoadPathEntriesContentHandler() { return new ContentHandler() { - public void characters(char[] arg0, int arg1, int arg2) throws SAXException { + public void characters(char[] arg0, int arg1, int arg2) + throws SAXException { } public void endDocument() throws SAXException { } - public void endElement(String arg0, String arg1, String arg2) throws SAXException { + public void endElement(String arg0, String arg1, String arg2) + throws SAXException { } public void endPrefixMapping(String arg0) throws SAXException { } - public void ignorableWhitespace(char[] arg0, int arg1, int arg2) throws SAXException { + public void ignorableWhitespace(char[] arg0, int arg1, int arg2) + throws SAXException { } - public void processingInstruction(String arg0, String arg1) throws SAXException { + public void processingInstruction(String arg0, String arg1) + throws SAXException { } public void setDocumentLocator(Locator arg0) { @@ -320,16 +347,21 @@ public class JavaProject public void startDocument() throws SAXException { } - public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { + public void startElement(String namespaceURI, String localName, + String qName, Attributes atts) throws SAXException { if ("pathentry".equals(qName)) if ("project".equals(atts.getValue("type"))) { - IPath referencedProjectPath = new Path(atts.getValue("path")); - IProject referencedProject = getProject(referencedProjectPath.lastSegment()); - fLoadPathEntries.add(new LoadPathEntry(referencedProject)); + IPath referencedProjectPath = new Path(atts + .getValue("path")); + IProject referencedProject = getProject(referencedProjectPath + .lastSegment()); + fLoadPathEntries.add(new LoadPathEntry( + referencedProject)); } } - public void startPrefixMapping(String arg0, String arg1) throws SAXException { + public void startPrefixMapping(String arg0, String arg1) + throws SAXException { } }; } @@ -352,6 +384,7 @@ public class JavaProject buffer.append(""); return buffer.toString(); } + /** * Adds a builder to the build spec for the given project. */ @@ -368,347 +401,389 @@ public class JavaProject setJavaCommand(description, command); } } + /** * @see Openable */ - protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException { - + protected boolean buildStructure(OpenableElementInfo info, + IProgressMonitor pm, Map newElements, IResource underlyingResource) + throws JavaModelException { + // check whether the java project can be opened if (!underlyingResource.isAccessible()) { throw newNotPresentException(); } - + IWorkspace workspace = ResourcesPlugin.getWorkspace(); IWorkspaceRoot wRoot = workspace.getRoot(); - // cannot refresh cp markers on opening (emulate cp check on startup) since can create deadlocks (see bug 37274) -// IClasspathEntry[] resolvedClasspath = getResolvedClasspath(true/*ignoreUnresolvedEntry*/, false/*don't generateMarkerOnError*/, false/*don't returnResolutionInProgress*/); - -// // compute the pkg fragment roots -// info.setChildren(computePackageFragmentRoots(resolvedClasspath, false)); -// -// // remember the timestamps of external libraries the first time they are looked up -// for (int i = 0, length = resolvedClasspath.length; i < length; i++) { -// IClasspathEntry entry = resolvedClasspath[i]; -// if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) { -// IPath path = entry.getPath(); -// Object target = JavaModel.getTarget(wRoot, path, true); -// if (target instanceof java.io.File) { -// Map externalTimeStamps = JavaModelManager.getJavaModelManager().deltaState.externalTimeStamps; -// if (externalTimeStamps.get(path) == null) { -// long timestamp = DeltaProcessor.getTimeStamp((java.io.File)target); -// externalTimeStamps.put(path, new Long(timestamp)); -// } -// } -// } -// } + // cannot refresh cp markers on opening (emulate cp check on startup) + // since can create deadlocks (see bug 37274) + // IClasspathEntry[] resolvedClasspath = + // getResolvedClasspath(true/*ignoreUnresolvedEntry*/, false/*don't + // generateMarkerOnError*/, false/*don't returnResolutionInProgress*/); + + // // compute the pkg fragment roots + // info.setChildren(computePackageFragmentRoots(resolvedClasspath, + // false)); + // + // // remember the timestamps of external libraries the first time they + // are looked up + // for (int i = 0, length = resolvedClasspath.length; i < length; i++) { + // IClasspathEntry entry = resolvedClasspath[i]; + // if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) { + // IPath path = entry.getPath(); + // Object target = JavaModel.getTarget(wRoot, path, true); + // if (target instanceof java.io.File) { + // Map externalTimeStamps = + // JavaModelManager.getJavaModelManager().deltaState.externalTimeStamps; + // if (externalTimeStamps.get(path) == null) { + // long timestamp = DeltaProcessor.getTimeStamp((java.io.File)target); + // externalTimeStamps.put(path, new Long(timestamp)); + // } + // } + // } + // } return true; } + protected void closing(Object info) { - -// // forget source attachment recommendations -// Object[] children = ((JavaElementInfo)info).children; -// for (int i = 0, length = children.length; i < length; i++) { -// Object child = children[i]; -// if (child instanceof JarPackageFragmentRoot){ -// ((JarPackageFragmentRoot)child).setSourceAttachmentProperty(null); -// } -// } - + + // // forget source attachment recommendations + // Object[] children = ((JavaElementInfo)info).children; + // for (int i = 0, length = children.length; i < length; i++) { + // Object child = children[i]; + // if (child instanceof JarPackageFragmentRoot){ + // ((JarPackageFragmentRoot)child).setSourceAttachmentProperty(null); + // } + // } + super.closing(info); } -// protected void closing(Object info) throws JavaModelException { -// -// // forget source attachment recommendations -// IPackageFragmentRoot[] roots = this.getPackageFragmentRoots(); -//// for (int i = 0; i < roots.length; i++) { -//// if (roots[i] instanceof JarPackageFragmentRoot){ -//// ((JarPackageFragmentRoot) roots[i]).setSourceAttachmentProperty(null); -//// } -//// } -// -// super.closing(info); -// } - - - /** - * Internal computation of an expanded classpath. It will eliminate duplicates, and produce copies - * of exported classpath entries to avoid possible side-effects ever after. - */ - private void computeExpandedClasspath( - JavaProject initialProject, - boolean ignoreUnresolvedVariable, - boolean generateMarkerOnError, - HashSet rootIDs, - ObjectVector accumulatedEntries, - Map preferredClasspaths, - Map preferredOutputs) throws JavaModelException { - + + // protected void closing(Object info) throws JavaModelException { + // + // // forget source attachment recommendations + // IPackageFragmentRoot[] roots = this.getPackageFragmentRoots(); + // // for (int i = 0; i < roots.length; i++) { + // // if (roots[i] instanceof JarPackageFragmentRoot){ + // // ((JarPackageFragmentRoot) roots[i]).setSourceAttachmentProperty(null); + // // } + // // } + // + // super.closing(info); + // } + + /** + * Internal computation of an expanded classpath. It will eliminate + * duplicates, and produce copies of exported classpath entries to avoid + * possible side-effects ever after. + */ + private void computeExpandedClasspath(JavaProject initialProject, + boolean ignoreUnresolvedVariable, boolean generateMarkerOnError, + HashSet rootIDs, ObjectVector accumulatedEntries, + Map preferredClasspaths, Map preferredOutputs) + throws JavaModelException { + String projectRootId = this.rootID(); - if (rootIDs.contains(projectRootId)){ + if (rootIDs.contains(projectRootId)) { return; // break cycles if any } rootIDs.add(projectRootId); - IClasspathEntry[] preferredClasspath = preferredClasspaths != null ? (IClasspathEntry[])preferredClasspaths.get(this) : null; - IPath preferredOutput = preferredOutputs != null ? (IPath)preferredOutputs.get(this) : null; - IClasspathEntry[] immediateClasspath = - preferredClasspath != null - ? getResolvedClasspath(preferredClasspath, preferredOutput, ignoreUnresolvedVariable, generateMarkerOnError, null) - : getResolvedClasspath(ignoreUnresolvedVariable, generateMarkerOnError, false/*don't returnResolutionInProgress*/); - + IClasspathEntry[] preferredClasspath = preferredClasspaths != null ? (IClasspathEntry[]) preferredClasspaths + .get(this) + : null; + IPath preferredOutput = preferredOutputs != null ? (IPath) preferredOutputs + .get(this) + : null; + IClasspathEntry[] immediateClasspath = preferredClasspath != null ? getResolvedClasspath( + preferredClasspath, preferredOutput, ignoreUnresolvedVariable, + generateMarkerOnError, null) + : getResolvedClasspath(ignoreUnresolvedVariable, + generateMarkerOnError, false/* + * don't + * returnResolutionInProgress + */); + IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); boolean isInitialProject = this.equals(initialProject); - for (int i = 0, length = immediateClasspath.length; i < length; i++){ + for (int i = 0, length = immediateClasspath.length; i < length; i++) { ClasspathEntry entry = (ClasspathEntry) immediateClasspath[i]; - if (isInitialProject || entry.isExported()){ + if (isInitialProject || entry.isExported()) { String rootID = entry.rootID(); if (rootIDs.contains(rootID)) { continue; } - + accumulatedEntries.add(entry); - - // recurse in project to get all its indirect exports (only consider exported entries from there on) + + // recurse in project to get all its indirect exports (only + // consider exported entries from there on) if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) { - IResource member = workspaceRoot.findMember(entry.getPath()); - if (member != null && member.getType() == IResource.PROJECT){ // double check if bound to project (23977) + IResource member = workspaceRoot + .findMember(entry.getPath()); + if (member != null && member.getType() == IResource.PROJECT) { // double + // check + // if + // bound + // to + // project + // (23977) IProject projRsc = (IProject) member; - if (JavaProject.hasJavaNature(projRsc)) { - JavaProject javaProject = (JavaProject) JavaCore.create(projRsc); - javaProject.computeExpandedClasspath( - initialProject, - ignoreUnresolvedVariable, - false /* no marker when recursing in prereq*/, - rootIDs, - accumulatedEntries, - preferredClasspaths, - preferredOutputs); + if (JavaProject.hasJavaNature(projRsc)) { + JavaProject javaProject = (JavaProject) JavaCore + .create(projRsc); + javaProject + .computeExpandedClasspath( + initialProject, + ignoreUnresolvedVariable, + false /* + * no marker when recursing + * in prereq + */, + rootIDs, accumulatedEntries, + preferredClasspaths, + preferredOutputs); } } } else { rootIDs.add(rootID); } - } - } - } - /** - * Internal computation of an expanded classpath. It will eliminate duplicates, and produce copies - * of exported classpath entries to avoid possible side-effects ever after. - */ -// private void computeExpandedClasspath( -// JavaProject initialProject, -// boolean ignoreUnresolvedVariable, -// boolean generateMarkerOnError, -// HashSet visitedProjects, -// ObjectVector accumulatedEntries) throws JavaModelException { -// -// if (visitedProjects.contains(this)){ -// return; // break cycles if any -// } -// visitedProjects.add(this); -// -// if (generateMarkerOnError && !this.equals(initialProject)){ -// generateMarkerOnError = false; -// } -// IClasspathEntry[] immediateClasspath = -// getResolvedClasspath(ignoreUnresolvedVariable, generateMarkerOnError); -// -// IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); -// for (int i = 0, length = immediateClasspath.length; i < length; i++){ -// IClasspathEntry entry = immediateClasspath[i]; -// -// boolean isInitialProject = this.equals(initialProject); -// if (isInitialProject || entry.isExported()){ -// -// accumulatedEntries.add(entry); -// -// // recurse in project to get all its indirect exports (only consider exported entries from there on) -// if (entry.getEntryKind() == ClasspathEntry.CPE_PROJECT) { -// IResource member = workspaceRoot.findMember(entry.getPath()); -// if (member != null && member.getType() == IResource.PROJECT){ // double check if bound to project (23977) -// IProject projRsc = (IProject) member; -// if (JavaProject.hasJavaNature(projRsc)) { -// JavaProject project = (JavaProject) JavaCore.create(projRsc); -// project.computeExpandedClasspath( -// initialProject, -// ignoreUnresolvedVariable, -// generateMarkerOnError, -// visitedProjects, -// accumulatedEntries); -// } -// } -// } -// } -// } -// } - - /** - * Returns (local/all) the package fragment roots identified by the given project's classpath. - * Note: this follows project classpath references to find required project contributions, - * eliminating duplicates silently. + } + } + } + + /** + * Internal computation of an expanded classpath. It will eliminate + * duplicates, and produce copies of exported classpath entries to avoid + * possible side-effects ever after. + */ + // private void computeExpandedClasspath( + // JavaProject initialProject, + // boolean ignoreUnresolvedVariable, + // boolean generateMarkerOnError, + // HashSet visitedProjects, + // ObjectVector accumulatedEntries) throws JavaModelException { + // + // if (visitedProjects.contains(this)){ + // return; // break cycles if any + // } + // visitedProjects.add(this); + // + // if (generateMarkerOnError && !this.equals(initialProject)){ + // generateMarkerOnError = false; + // } + // IClasspathEntry[] immediateClasspath = + // getResolvedClasspath(ignoreUnresolvedVariable, generateMarkerOnError); + // + // IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); + // for (int i = 0, length = immediateClasspath.length; i < length; i++){ + // IClasspathEntry entry = immediateClasspath[i]; + // + // boolean isInitialProject = this.equals(initialProject); + // if (isInitialProject || entry.isExported()){ + // + // accumulatedEntries.add(entry); + // + // // recurse in project to get all its indirect exports (only consider + // exported entries from there on) + // if (entry.getEntryKind() == ClasspathEntry.CPE_PROJECT) { + // IResource member = workspaceRoot.findMember(entry.getPath()); + // if (member != null && member.getType() == IResource.PROJECT){ // double + // check if bound to project (23977) + // IProject projRsc = (IProject) member; + // if (JavaProject.hasJavaNature(projRsc)) { + // JavaProject project = (JavaProject) JavaCore.create(projRsc); + // project.computeExpandedClasspath( + // initialProject, + // ignoreUnresolvedVariable, + // generateMarkerOnError, + // visitedProjects, + // accumulatedEntries); + // } + // } + // } + // } + // } + // } + /** + * Returns (local/all) the package fragment roots identified by the given + * project's classpath. Note: this follows project classpath references to + * find required project contributions, eliminating duplicates silently. * Only works with resolved entries */ - public IPackageFragmentRoot[] computePackageFragmentRoots(IClasspathEntry[] resolvedClasspath, boolean retrieveExportedRoots) throws JavaModelException { + public IPackageFragmentRoot[] computePackageFragmentRoots( + IClasspathEntry[] resolvedClasspath, boolean retrieveExportedRoots) + throws JavaModelException { ObjectVector accumulatedRoots = new ObjectVector(); - computePackageFragmentRoots( - resolvedClasspath, - accumulatedRoots, - new HashSet(5), // rootIDs - true, // inside original project - true, // check existency - retrieveExportedRoots); - IPackageFragmentRoot[] rootArray = new IPackageFragmentRoot[accumulatedRoots.size()]; + computePackageFragmentRoots(resolvedClasspath, accumulatedRoots, + new HashSet(5), // rootIDs + true, // inside original project + true, // check existency + retrieveExportedRoots); + IPackageFragmentRoot[] rootArray = new IPackageFragmentRoot[accumulatedRoots + .size()]; accumulatedRoots.copyInto(rootArray); return rootArray; } /** - * Computes the package fragment roots identified by the given entry. - * Only works with resolved entry + * Computes the package fragment roots identified by the given entry. Only + * works with resolved entry */ - public IPackageFragmentRoot[] computePackageFragmentRoots(IClasspathEntry resolvedEntry) { + public IPackageFragmentRoot[] computePackageFragmentRoots( + IClasspathEntry resolvedEntry) { try { - return - computePackageFragmentRoots( - new IClasspathEntry[]{ resolvedEntry }, - false // don't retrieve exported roots - ); + return computePackageFragmentRoots( + new IClasspathEntry[] { resolvedEntry }, false // don't + // retrieve + // exported + // roots + ); } catch (JavaModelException e) { return new IPackageFragmentRoot[] {}; } } - + /** - * Returns the package fragment roots identified by the given entry. In case it refers to - * a project, it will follow its classpath so as to find exported roots as well. - * Only works with resolved entry + * Returns the package fragment roots identified by the given entry. In case + * it refers to a project, it will follow its classpath so as to find + * exported roots as well. Only works with resolved entry */ - public void computePackageFragmentRoots( - IClasspathEntry resolvedEntry, - ObjectVector accumulatedRoots, - HashSet rootIDs, - boolean insideOriginalProject, - boolean checkExistency, - boolean retrieveExportedRoots) throws JavaModelException { - - String rootID = ((ClasspathEntry)resolvedEntry).rootID(); - if (rootIDs.contains(rootID)) return; + public void computePackageFragmentRoots(IClasspathEntry resolvedEntry, + ObjectVector accumulatedRoots, HashSet rootIDs, + boolean insideOriginalProject, boolean checkExistency, + boolean retrieveExportedRoots) throws JavaModelException { + + String rootID = ((ClasspathEntry) resolvedEntry).rootID(); + if (rootIDs.contains(rootID)) + return; IPath projectPath = getProject().getFullPath(); IPath entryPath = resolvedEntry.getPath(); IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); - - switch(resolvedEntry.getEntryKind()){ - - // source folder - case IClasspathEntry.CPE_SOURCE : - - if (projectPath.isPrefixOf(entryPath)){ - if (checkExistency) { - Object target = JavaModel.getTarget(workspaceRoot, entryPath, checkExistency); - if (target == null) return; - - if (target instanceof IFolder || target instanceof IProject){ - accumulatedRoots.add( - getPackageFragmentRoot((IResource)target)); - rootIDs.add(rootID); - } - } else { - IPackageFragmentRoot root = getFolderPackageFragmentRoot(entryPath); - if (root != null) { - accumulatedRoots.add(root); - rootIDs.add(rootID); - } - } - } - break; - // internal/external JAR or folder - case IClasspathEntry.CPE_LIBRARY : - - if (!insideOriginalProject && !resolvedEntry.isExported()) return; - + switch (resolvedEntry.getEntryKind()) { + + // source folder + case IClasspathEntry.CPE_SOURCE: + + if (projectPath.isPrefixOf(entryPath)) { if (checkExistency) { - Object target = JavaModel.getTarget(workspaceRoot, entryPath, checkExistency); - if (target == null) return; - - if (target instanceof IResource){ - // internal target - IResource resource = (IResource) target; - IPackageFragmentRoot root = getPackageFragmentRoot(resource); - if (root != null) { - accumulatedRoots.add(root); - rootIDs.add(rootID); - } - } else { - // external target - only JARs allowed -// if (((java.io.File)target).isFile() && (ProjectPrefUtil.isArchiveFileName(entryPath.lastSegment()))) { -// accumulatedRoots.add( -// new JarPackageFragmentRoot(entryPath, this)); -// rootIDs.add(rootID); -// } + Object target = JavaModel.getTarget(workspaceRoot, + entryPath, checkExistency); + if (target == null) + return; + + if (target instanceof IFolder || target instanceof IProject) { + accumulatedRoots + .add(getPackageFragmentRoot((IResource) target)); + rootIDs.add(rootID); } } else { - IPackageFragmentRoot root = getPackageFragmentRoot(entryPath); + IPackageFragmentRoot root = getFolderPackageFragmentRoot(entryPath); if (root != null) { accumulatedRoots.add(root); rootIDs.add(rootID); } } - break; + } + break; - // recurse into required project - case IClasspathEntry.CPE_PROJECT : + // internal/external JAR or folder + case IClasspathEntry.CPE_LIBRARY: + + if (!insideOriginalProject && !resolvedEntry.isExported()) + return; - if (!retrieveExportedRoots) return; - if (!insideOriginalProject && !resolvedEntry.isExported()) return; + if (checkExistency) { + Object target = JavaModel.getTarget(workspaceRoot, entryPath, + checkExistency); + if (target == null) + return; - IResource member = workspaceRoot.findMember(entryPath); - if (member != null && member.getType() == IResource.PROJECT){// double check if bound to project (23977) - IProject requiredProjectRsc = (IProject) member; - if (JavaProject.hasJavaNature(requiredProjectRsc)){ // special builder binary output + if (target instanceof IResource) { + // internal target + IResource resource = (IResource) target; + IPackageFragmentRoot root = getPackageFragmentRoot(resource); + if (root != null) { + accumulatedRoots.add(root); rootIDs.add(rootID); - JavaProject requiredProject = (JavaProject)JavaCore.create(requiredProjectRsc); - requiredProject.computePackageFragmentRoots( - requiredProject.getResolvedClasspath(true), - accumulatedRoots, - rootIDs, - false, - checkExistency, - retrieveExportedRoots); } + } else { + // external target - only JARs allowed + // if (((java.io.File)target).isFile() && + // (ProjectPrefUtil.isArchiveFileName(entryPath.lastSegment()))) + // { + // accumulatedRoots.add( + // new JarPackageFragmentRoot(entryPath, this)); + // rootIDs.add(rootID); + // } + } + } else { + IPackageFragmentRoot root = getPackageFragmentRoot(entryPath); + if (root != null) { + accumulatedRoots.add(root); + rootIDs.add(rootID); + } + } + break; + + // recurse into required project + case IClasspathEntry.CPE_PROJECT: + + if (!retrieveExportedRoots) + return; + if (!insideOriginalProject && !resolvedEntry.isExported()) + return; + + IResource member = workspaceRoot.findMember(entryPath); + if (member != null && member.getType() == IResource.PROJECT) {// double + // check + // if + // bound + // to + // project + // (23977) + IProject requiredProjectRsc = (IProject) member; + if (JavaProject.hasJavaNature(requiredProjectRsc)) { // special + // builder + // binary + // output + rootIDs.add(rootID); + JavaProject requiredProject = (JavaProject) JavaCore + .create(requiredProjectRsc); + requiredProject.computePackageFragmentRoots(requiredProject + .getResolvedClasspath(true), accumulatedRoots, + rootIDs, false, checkExistency, + retrieveExportedRoots); + } break; } } } /** - * Returns (local/all) the package fragment roots identified by the given project's classpath. - * Note: this follows project classpath references to find required project contributions, - * eliminating duplicates silently. + * Returns (local/all) the package fragment roots identified by the given + * project's classpath. Note: this follows project classpath references to + * find required project contributions, eliminating duplicates silently. * Only works with resolved entries */ public void computePackageFragmentRoots( - IClasspathEntry[] resolvedClasspath, - ObjectVector accumulatedRoots, - HashSet rootIDs, - boolean insideOriginalProject, - boolean checkExistency, - boolean retrieveExportedRoots) throws JavaModelException { - - if (insideOriginalProject){ + IClasspathEntry[] resolvedClasspath, ObjectVector accumulatedRoots, + HashSet rootIDs, boolean insideOriginalProject, + boolean checkExistency, boolean retrieveExportedRoots) + throws JavaModelException { + + if (insideOriginalProject) { rootIDs.add(rootID()); - } - for (int i = 0, length = resolvedClasspath.length; i < length; i++){ - computePackageFragmentRoots( - resolvedClasspath[i], - accumulatedRoots, - rootIDs, - insideOriginalProject, - checkExistency, - retrieveExportedRoots); + } + for (int i = 0, length = resolvedClasspath.length; i < length; i++) { + computePackageFragmentRoots(resolvedClasspath[i], accumulatedRoots, + rootIDs, insideOriginalProject, checkExistency, + retrieveExportedRoots); } } @@ -719,14 +794,14 @@ public class JavaProject return '.' + qName.getLocalName(); } - + /* - * Returns whether the given resource is accessible through the children or the non-Java resources of this project. - * Returns true if the resource is not in the project. - * Assumes that the resource is a folder or a file. + * Returns whether the given resource is accessible through the children or + * the non-Java resources of this project. Returns true if the resource is + * not in the project. Assumes that the resource is a folder or a file. */ public boolean contains(IResource resource) { - + IClasspathEntry[] classpath; IPath output; try { @@ -735,15 +810,16 @@ public class JavaProject } catch (JavaModelException e) { return false; } - + IPath fullPath = resource.getFullPath(); IPath innerMostOutput = output.isPrefixOf(fullPath) ? output : null; IClasspathEntry innerMostEntry = null; for (int j = 0, cpLength = classpath.length; j < cpLength; j++) { IClasspathEntry entry = classpath[j]; - + IPath entryPath = entry.getPath(); - if ((innerMostEntry == null || innerMostEntry.getPath().isPrefixOf(entryPath)) + if ((innerMostEntry == null || innerMostEntry.getPath().isPrefixOf( + entryPath)) && entryPath.isPrefixOf(fullPath)) { innerMostEntry = entry; } @@ -754,21 +830,29 @@ public class JavaProject } if (innerMostEntry != null) { // special case prj==src and nested output location - if (innerMostOutput != null && innerMostOutput.segmentCount() > 1 // output isn't project - && innerMostEntry.getPath().segmentCount() == 1) { // 1 segment must be project name + if (innerMostOutput != null && innerMostOutput.segmentCount() > 1 // output + // isn't + // project + && innerMostEntry.getPath().segmentCount() == 1) { // 1 + // segment + // must + // be + // project + // name return false; } - if (resource instanceof IFolder) { - // folders are always included in src/lib entries - return true; + if (resource instanceof IFolder) { + // folders are always included in src/lib entries + return true; } switch (innerMostEntry.getEntryKind()) { - case IClasspathEntry.CPE_SOURCE: - // .class files are not visible in source folders - return true; //!net.sourceforge.phpdt.internal.compiler.util.ProjectPrefUtil.isClassFileName(fullPath.lastSegment()); - case IClasspathEntry.CPE_LIBRARY: - // .java files are not visible in library folders - return !net.sourceforge.phpdt.internal.compiler.util.Util.isJavaFileName(fullPath.lastSegment()); + case IClasspathEntry.CPE_SOURCE: + // .class files are not visible in source folders + return true; // !net.sourceforge.phpdt.internal.compiler.util.ProjectPrefUtil.isClassFileName(fullPath.lastSegment()); + case IClasspathEntry.CPE_LIBRARY: + // .java files are not visible in library folders + return !net.sourceforge.phpdt.internal.compiler.util.Util + .isJavaFileName(fullPath.lastSegment()); } } if (innerMostOutput != null) { @@ -781,103 +865,105 @@ public class JavaProject * Record a new marker denoting a classpath problem */ IMarker createClasspathProblemMarker(IJavaModelStatus status) { - + IMarker marker = null; int severity; String[] arguments = new String[0]; boolean isCycleProblem = false, isClasspathFileFormatProblem = false; switch (status.getCode()) { - case IJavaModelStatusConstants.CLASSPATH_CYCLE : - isCycleProblem = true; - if (JavaCore.ERROR.equals(getOption(JavaCore.CORE_CIRCULAR_CLASSPATH, true))) { - severity = IMarker.SEVERITY_ERROR; - } else { - severity = IMarker.SEVERITY_WARNING; - } - break; - - case IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT : - isClasspathFileFormatProblem = true; + case IJavaModelStatusConstants.CLASSPATH_CYCLE: + isCycleProblem = true; + if (JavaCore.ERROR.equals(getOption( + JavaCore.CORE_CIRCULAR_CLASSPATH, true))) { severity = IMarker.SEVERITY_ERROR; - break; + } else { + severity = IMarker.SEVERITY_WARNING; + } + break; - default: - IPath path = status.getPath(); - if (path != null) arguments = new String[] { path.toString() }; - if (JavaCore.ERROR.equals(getOption(JavaCore.CORE_INCOMPLETE_CLASSPATH, true))) { - severity = IMarker.SEVERITY_ERROR; - } else { - severity = IMarker.SEVERITY_WARNING; - } - break; + case IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT: + isClasspathFileFormatProblem = true; + severity = IMarker.SEVERITY_ERROR; + break; + + default: + IPath path = status.getPath(); + if (path != null) + arguments = new String[] { path.toString() }; + if (JavaCore.ERROR.equals(getOption( + JavaCore.CORE_INCOMPLETE_CLASSPATH, true))) { + severity = IMarker.SEVERITY_ERROR; + } else { + severity = IMarker.SEVERITY_WARNING; + } + break; } - + try { - marker = getProject().createMarker(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER); - marker.setAttributes( - new String[] { - IMarker.MESSAGE, - IMarker.SEVERITY, - IMarker.LOCATION, + marker = getProject().createMarker( + IJavaModelMarker.BUILDPATH_PROBLEM_MARKER); + marker.setAttributes(new String[] { IMarker.MESSAGE, + IMarker.SEVERITY, IMarker.LOCATION, IJavaModelMarker.CYCLE_DETECTED, IJavaModelMarker.CLASSPATH_FILE_FORMAT, - IJavaModelMarker.ID, - IJavaModelMarker.ARGUMENTS , - }, - new Object[] { - status.getMessage(), - new Integer(severity), - Util.bind("classpath.buildPath"),//$NON-NLS-1$ - isCycleProblem ? "true" : "false",//$NON-NLS-1$ //$NON-NLS-2$ - isClasspathFileFormatProblem ? "true" : "false",//$NON-NLS-1$ //$NON-NLS-2$ - new Integer(status.getCode()), - Util.getProblemArgumentsForMarker(arguments) , - } - ); + IJavaModelMarker.ID, IJavaModelMarker.ARGUMENTS, }, + new Object[] { status.getMessage(), + new Integer(severity), + Util.bind("classpath.buildPath"),//$NON-NLS-1$ + isCycleProblem ? "true" : "false",//$NON-NLS-1$ //$NON-NLS-2$ + isClasspathFileFormatProblem ? "true" : "false",//$NON-NLS-1$ //$NON-NLS-2$ + new Integer(status.getCode()), + Util.getProblemArgumentsForMarker(arguments), }); } catch (CoreException e) { } return marker; } - + /** * Returns a new element info for this element. */ protected Object createElementInfo() { return new JavaProjectElementInfo(); } - /* - * Returns a new search name environment for this project. This name environment first looks in the given working copies. - */ -// public ISearchableNameEnvironment newSearchableNameEnvironment(ICompilationUnit[] workingCopies) throws JavaModelException { -// return new SearchableEnvironment(this, workingCopies); -// } - + * Returns a new search name environment for this project. This name + * environment first looks in the given working copies. + */ + // public ISearchableNameEnvironment + // newSearchableNameEnvironment(ICompilationUnit[] workingCopies) throws + // JavaModelException { + // return new SearchableEnvironment(this, workingCopies); + // } /* - * Returns a new search name environment for this project. This name environment first looks in the working copies - * of the given owner. + * Returns a new search name environment for this project. This name + * environment first looks in the working copies of the given owner. */ - public ISearchableNameEnvironment newSearchableNameEnvironment(WorkingCopyOwner owner) throws JavaModelException { + public ISearchableNameEnvironment newSearchableNameEnvironment( + WorkingCopyOwner owner) throws JavaModelException { return new SearchableEnvironment(this, owner); } + /** * Reads and decode an XML classpath string */ - protected IClasspathEntry[] decodeClasspath(String xmlClasspath, boolean createMarker, boolean logProblems) { + protected IClasspathEntry[] decodeClasspath(String xmlClasspath, + boolean createMarker, boolean logProblems) { ArrayList paths = new ArrayList(); IClasspathEntry defaultOutput = null; try { - if (xmlClasspath == null) return null; + if (xmlClasspath == null) + return null; StringReader reader = new StringReader(xmlClasspath); Element cpElement; - + try { - DocumentBuilder parser = - DocumentBuilderFactory.newInstance().newDocumentBuilder(); - cpElement = parser.parse(new InputSource(reader)).getDocumentElement(); + DocumentBuilder parser = DocumentBuilderFactory.newInstance() + .newDocumentBuilder(); + cpElement = parser.parse(new InputSource(reader)) + .getDocumentElement(); } catch (SAXException e) { throw new IOException(Util.bind("file.badFormat")); //$NON-NLS-1$ } catch (ParserConfigurationException e) { @@ -885,58 +971,66 @@ public class JavaProject } finally { reader.close(); } - + if (!cpElement.getNodeName().equalsIgnoreCase("classpath")) { //$NON-NLS-1$ throw new IOException(Util.bind("file.badFormat")); //$NON-NLS-1$ } NodeList list = cpElement.getElementsByTagName("classpathentry"); //$NON-NLS-1$ int length = list.getLength(); - + for (int i = 0; i < length; ++i) { Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { - IClasspathEntry entry = ClasspathEntry.elementDecode((Element)node, this); - if (entry != null){ - if (entry.getContentKind() == ClasspathEntry.K_OUTPUT) { + IClasspathEntry entry = ClasspathEntry.elementDecode( + (Element) node, this); + if (entry != null) { + if (entry.getContentKind() == ClasspathEntry.K_OUTPUT) { defaultOutput = entry; // separate output } else { paths.add(entry); - } - } + } + } } } } catch (IOException e) { // bad format if (createMarker && this.getProject().isAccessible()) { - this.createClasspathProblemMarker(new JavaModelStatus( - IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, - Util.bind("classpath.xmlFormatError", this.getElementName(), e.getMessage()))); //$NON-NLS-1$ + this + .createClasspathProblemMarker(new JavaModelStatus( + IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, + Util + .bind( + "classpath.xmlFormatError", this.getElementName(), e.getMessage()))); //$NON-NLS-1$ } if (logProblems) { - Util.log(e, - "Exception while retrieving "+ this.getPath() //$NON-NLS-1$ - +"/.classpath, will mark classpath as invalid"); //$NON-NLS-1$ + Util.log(e, "Exception while retrieving " + this.getPath() //$NON-NLS-1$ + + "/.classpath, will mark classpath as invalid"); //$NON-NLS-1$ } return INVALID_CLASSPATH; - } catch (Assert.AssertionFailedException e) { + } catch (Assert.AssertionFailedException e) { // failed creating CP entries from file if (createMarker && this.getProject().isAccessible()) { - this.createClasspathProblemMarker(new JavaModelStatus( - IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, - Util.bind("classpath.illegalEntryInClasspathFile", this.getElementName(), e.getMessage()))); //$NON-NLS-1$ + this + .createClasspathProblemMarker(new JavaModelStatus( + IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, + Util + .bind( + "classpath.illegalEntryInClasspathFile", this.getElementName(), e.getMessage()))); //$NON-NLS-1$ } if (logProblems) { - Util.log(e, - "Exception while retrieving "+ this.getPath() //$NON-NLS-1$ - +"/.classpath, will mark classpath as invalid"); //$NON-NLS-1$ + Util.log(e, "Exception while retrieving " + this.getPath() //$NON-NLS-1$ + + "/.classpath, will mark classpath as invalid"); //$NON-NLS-1$ } return INVALID_CLASSPATH; } int pathSize = paths.size(); if (pathSize > 0 || defaultOutput != null) { - IClasspathEntry[] entries = new IClasspathEntry[pathSize + (defaultOutput == null ? 0 : 1)]; + IClasspathEntry[] entries = new IClasspathEntry[pathSize + + (defaultOutput == null ? 0 : 1)]; paths.toArray(entries); - if (defaultOutput != null) entries[pathSize] = defaultOutput; // ensure output is last item + if (defaultOutput != null) + entries[pathSize] = defaultOutput; // ensure output is last + // item return entries; } else { return null; @@ -944,8 +1038,7 @@ public class JavaProject } /** - /** - * Removes the Java nature from the project. + * /** Removes the Java nature from the project. */ public void deconfigure() throws CoreException { @@ -954,103 +1047,113 @@ public class JavaProject } /** - * Returns a default class path. - * This is the root of the project + * Returns a default class path. This is the root of the project */ protected IClasspathEntry[] defaultClasspath() throws JavaModelException { - return new IClasspathEntry[] { - JavaCore.newSourceEntry(getProject().getFullPath())}; + return new IClasspathEntry[] { JavaCore.newSourceEntry(getProject() + .getFullPath()) }; } /** - * Returns a default output location. - * This is the project bin folder + * Returns a default output location. This is the project bin folder */ protected IPath defaultOutputLocation() throws JavaModelException { - return null; //getProject().getFullPath().append("bin"); //$NON-NLS-1$ + return null; // getProject().getFullPath().append("bin"); + // //$NON-NLS-1$ } /** * Returns the XML String encoding of the class path. */ - protected String encodeClasspath(IClasspathEntry[] classpath, IPath outputLocation, boolean indent) throws JavaModelException { + protected String encodeClasspath(IClasspathEntry[] classpath, + IPath outputLocation, boolean indent) throws JavaModelException { try { ByteArrayOutputStream s = new ByteArrayOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(s, "UTF8"); //$NON-NLS-1$ XMLWriter xmlWriter = new XMLWriter(writer); - + xmlWriter.startTag("classpath", indent); //$NON-NLS-1$ for (int i = 0; i < classpath.length; ++i) { - ((ClasspathEntry)classpath[i]).elementEncode(xmlWriter, this.project.getFullPath(), indent, true); + ((ClasspathEntry) classpath[i]).elementEncode(xmlWriter, + this.project.getFullPath(), indent, true); } - + if (outputLocation != null) { outputLocation = outputLocation.removeFirstSegments(1); outputLocation = outputLocation.makeRelative(); HashMap parameters = new HashMap(); - parameters.put("kind", ClasspathEntry.kindToString(ClasspathEntry.K_OUTPUT));//$NON-NLS-1$ + parameters + .put( + "kind", ClasspathEntry.kindToString(ClasspathEntry.K_OUTPUT));//$NON-NLS-1$ parameters.put("path", String.valueOf(outputLocation));//$NON-NLS-1$ - xmlWriter.printTag("classpathentry", parameters, indent, true, true);//$NON-NLS-1$ + xmlWriter.printTag( + "classpathentry", parameters, indent, true, true);//$NON-NLS-1$ } - + xmlWriter.endTag("classpath", indent);//$NON-NLS-1$ writer.flush(); writer.close(); return s.toString("UTF8");//$NON-NLS-1$ } catch (IOException e) { - throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); + throw new JavaModelException(e, + IJavaModelStatusConstants.IO_EXCEPTION); } } + /** * Returns the XML String encoding of the class path. */ -// protected String encodeClasspath(IClasspathEntry[] classpath, IPath outputLocation, boolean useLineSeparator) throws JavaModelException { -// -// Document document = new DocumentImpl(); -// Element cpElement = document.createElement("classpath"); //$NON-NLS-1$ -// document.appendChild(cpElement); -// -// for (int i = 0; i < classpath.length; ++i) { -// cpElement.appendChild(((ClasspathEntry)classpath[i]).elementEncode(document, getProject().getFullPath())); -// } -// -// if (outputLocation != null) { -// outputLocation = outputLocation.removeFirstSegments(1); -// outputLocation = outputLocation.makeRelative(); -// Element oElement = document.createElement("classpathentry"); //$NON-NLS-1$ -// oElement.setAttribute("kind", ClasspathEntry.kindToString(ClasspathEntry.K_OUTPUT)); //$NON-NLS-1$ -// oElement.setAttribute("path", outputLocation.toString()); //$NON-NLS-1$ -// cpElement.appendChild(oElement); -// } -// -// // produce a String output -// try { -// ByteArrayOutputStream s = new ByteArrayOutputStream(); -// OutputFormat format = new OutputFormat(); -// if (useLineSeparator) { -// format.setIndenting(true); -// format.setLineSeparator(System.getProperty("line.separator")); //$NON-NLS-1$ -// } else { -// format.setPreserveSpace(true); -// } -// Serializer serializer = -// SerializerFactory.getSerializerFactory(Method.XML).makeSerializer( -// new OutputStreamWriter(s, "UTF8"), //$NON-NLS-1$ -// format); -// serializer.asDOMSerializer().serialize(document); -// return s.toString("UTF8"); //$NON-NLS-1$ -// } catch (IOException e) { -// throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); -// } -// } - - /** - * Returns true if this handle represents the same Java project - * as the given handle. Two handles represent the same - * project if they are identical or if they represent a project with - * the same underlying resource and occurrence counts. - * + // protected String encodeClasspath(IClasspathEntry[] classpath, IPath + // outputLocation, boolean useLineSeparator) throws JavaModelException { + // + // Document document = new DocumentImpl(); + // Element cpElement = document.createElement("classpath"); //$NON-NLS-1$ + // document.appendChild(cpElement); + // + // for (int i = 0; i < classpath.length; ++i) { + // cpElement.appendChild(((ClasspathEntry)classpath[i]).elementEncode(document, + // getProject().getFullPath())); + // } + // + // if (outputLocation != null) { + // outputLocation = outputLocation.removeFirstSegments(1); + // outputLocation = outputLocation.makeRelative(); + // Element oElement = document.createElement("classpathentry"); + // //$NON-NLS-1$ + // oElement.setAttribute("kind", + // ClasspathEntry.kindToString(ClasspathEntry.K_OUTPUT)); //$NON-NLS-1$ + // oElement.setAttribute("path", outputLocation.toString()); //$NON-NLS-1$ + // cpElement.appendChild(oElement); + // } + // + // // produce a String output + // try { + // ByteArrayOutputStream s = new ByteArrayOutputStream(); + // OutputFormat format = new OutputFormat(); + // if (useLineSeparator) { + // format.setIndenting(true); + // format.setLineSeparator(System.getProperty("line.separator")); + // //$NON-NLS-1$ + // } else { + // format.setPreserveSpace(true); + // } + // Serializer serializer = + // SerializerFactory.getSerializerFactory(Method.XML).makeSerializer( + // new OutputStreamWriter(s, "UTF8"), //$NON-NLS-1$ + // format); + // serializer.asDOMSerializer().serialize(document); + // return s.toString("UTF8"); //$NON-NLS-1$ + // } catch (IOException e) { + // throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); + // } + // } + /** + * Returns true if this handle represents the same Java project as the given + * handle. Two handles represent the same project if they are identical or + * if they represent a project with the same underlying resource and + * occurrence counts. + * * @see JavaElement#equals */ public boolean equals(Object o) { @@ -1063,13 +1166,14 @@ public class JavaProject JavaProject other = (JavaProject) o; return getProject().equals(other.getProject()) - && occurrenceCount == other.occurrenceCount; + && occurrenceCount == other.occurrenceCount; } public boolean exists() { - if (!hasJavaNature(project)) return false; + if (!hasJavaNature(project)) + return false; return super.exists(); - } + } /** * @see IJavaProject @@ -1077,114 +1181,115 @@ public class JavaProject public IJavaElement findElement(IPath path) throws JavaModelException { if (path == null || path.isAbsolute()) { - throw new JavaModelException( - new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, path)); - } -// try { - - String extension = path.getFileExtension(); - if (extension == null) { - String packageName = path.toString().replace(IPath.SEPARATOR, '.'); - -// IPackageFragment[] pkgFragments = -// getNameLookup().findPackageFragments(packageName, false); -// if (pkgFragments == null) { - return null; - -// } else { -// // try to return one that is a child of this project -// for (int i = 0, length = pkgFragments.length; i < length; i++) { -// -// IPackageFragment pkgFragment = pkgFragments[i]; -// if (this.equals(pkgFragment.getParent().getParent())) { -// return pkgFragment; -// } -// } -// // default to the first one -// return pkgFragments[0]; -// } - } else if ( - extension.equalsIgnoreCase("java") //$NON-NLS-1$ - || extension.equalsIgnoreCase("class")) { //$NON-NLS-1$ - IPath packagePath = path.removeLastSegments(1); - String packageName = packagePath.toString().replace(IPath.SEPARATOR, '.'); - String typeName = path.lastSegment(); - typeName = typeName.substring(0, typeName.length() - extension.length() - 1); - String qualifiedName = null; - if (packageName.length() > 0) { - qualifiedName = packageName + "." + typeName; //$NON-NLS-1$ - } else { - qualifiedName = typeName; - } -// IType type = -// getNameLookup().findType( -// qualifiedName, -// false, -// NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES); -// if (type != null) { -// return type.getParent(); -// } else { - return null; -// } + throw new JavaModelException(new JavaModelStatus( + IJavaModelStatusConstants.INVALID_PATH, path)); + } + // try { + + String extension = path.getFileExtension(); + if (extension == null) { + String packageName = path.toString().replace(IPath.SEPARATOR, '.'); + + // IPackageFragment[] pkgFragments = + // getNameLookup().findPackageFragments(packageName, false); + // if (pkgFragments == null) { + return null; + + // } else { + // // try to return one that is a child of this project + // for (int i = 0, length = pkgFragments.length; i < length; i++) { + // + // IPackageFragment pkgFragment = pkgFragments[i]; + // if (this.equals(pkgFragment.getParent().getParent())) { + // return pkgFragment; + // } + // } + // // default to the first one + // return pkgFragments[0]; + // } + } else if (extension.equalsIgnoreCase("java") //$NON-NLS-1$ + || extension.equalsIgnoreCase("class")) { //$NON-NLS-1$ + IPath packagePath = path.removeLastSegments(1); + String packageName = packagePath.toString().replace( + IPath.SEPARATOR, '.'); + String typeName = path.lastSegment(); + typeName = typeName.substring(0, typeName.length() + - extension.length() - 1); + String qualifiedName = null; + if (packageName.length() > 0) { + qualifiedName = packageName + "." + typeName; //$NON-NLS-1$ } else { - // unsupported extension - return null; - } -// } catch (JavaModelException e) { -// if (e.getStatus().getCode() -// == IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST) { -// return null; -// } else { -// throw e; -// } -// } + qualifiedName = typeName; + } + // IType type = + // getNameLookup().findType( + // qualifiedName, + // false, + // NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES); + // if (type != null) { + // return type.getParent(); + // } else { + return null; + // } + } else { + // unsupported extension + return null; + } + // } catch (JavaModelException e) { + // if (e.getStatus().getCode() + // == IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST) { + // return null; + // } else { + // throw e; + // } + // } } /** * @see IJavaProject */ -// public IPackageFragment findPackageFragment(IPath path) -// throws JavaModelException { -// -// return findPackageFragment0(JavaProject.canonicalizedPath(path)); -// } -// -// /** -// * non path canonicalizing version -// */ -// public IPackageFragment findPackageFragment0(IPath path) -// throws JavaModelException { -// -// return getNameLookup().findPackageFragment(path); -// } - + // public IPackageFragment findPackageFragment(IPath path) + // throws JavaModelException { + // + // return findPackageFragment0(JavaProject.canonicalizedPath(path)); + // } + // + // /** + // * non path canonicalizing version + // */ + // public IPackageFragment findPackageFragment0(IPath path) + // throws JavaModelException { + // + // return getNameLookup().findPackageFragment(path); + // } /** * @see IJavaProject */ public IPackageFragmentRoot findPackageFragmentRoot(IPath path) - throws JavaModelException { + throws JavaModelException { return findPackageFragmentRoot0(JavaProject.canonicalizedPath(path)); } /** - * no path canonicalization + * no path canonicalization */ public IPackageFragmentRoot findPackageFragmentRoot0(IPath path) - throws JavaModelException { + throws JavaModelException { IPackageFragmentRoot[] allRoots = this.getAllPackageFragmentRoots(); if (!path.isAbsolute()) { throw new IllegalArgumentException(Util.bind("path.mustBeAbsolute")); //$NON-NLS-1$ } - for (int i= 0; i < allRoots.length; i++) { - IPackageFragmentRoot classpathRoot= allRoots[i]; + for (int i = 0; i < allRoots.length; i++) { + IPackageFragmentRoot classpathRoot = allRoots[i]; if (classpathRoot.getPath().equals(path)) { return classpathRoot; } } return null; } + /** * @see IJavaProject */ @@ -1192,71 +1297,82 @@ public class JavaProject try { IClasspathEntry[] classpath = this.getRawClasspath(); for (int i = 0, length = classpath.length; i < length; i++) { - if (classpath[i].equals(entry)) { // entry may need to be resolved - return - computePackageFragmentRoots( - getResolvedClasspath(new IClasspathEntry[] {entry}, null, true, false, null/*no reverse map*/), - false); // don't retrieve exported roots + if (classpath[i].equals(entry)) { // entry may need to be + // resolved + return computePackageFragmentRoots(getResolvedClasspath( + new IClasspathEntry[] { entry }, null, true, false, + null/* no reverse map */), false); // don't + // retrieve + // exported + // roots } } } catch (JavaModelException e) { } return new IPackageFragmentRoot[] {}; } - + /** * @see IJavaProject#findType(String) */ -// public IType findType(String fullyQualifiedName) throws JavaModelException { -// IType type = -// this.getNameLookup().findType( -// fullyQualifiedName, -// false, -// NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES); -// if (type == null) { -// // try to find enclosing type -// int lastDot = fullyQualifiedName.lastIndexOf('.'); -// if (lastDot == -1) return null; -// type = this.findType(fullyQualifiedName.substring(0, lastDot)); -// if (type != null) { -// type = type.getType(fullyQualifiedName.substring(lastDot+1)); -// if (!type.exists()) { -// return null; -// } -// } -// } -// return type; -// } - + // public IType findType(String fullyQualifiedName) throws + // JavaModelException { + // IType type = + // this.getNameLookup().findType( + // fullyQualifiedName, + // false, + // NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES); + // if (type == null) { + // // try to find enclosing type + // int lastDot = fullyQualifiedName.lastIndexOf('.'); + // if (lastDot == -1) return null; + // type = this.findType(fullyQualifiedName.substring(0, lastDot)); + // if (type != null) { + // type = type.getType(fullyQualifiedName.substring(lastDot+1)); + // if (!type.exists()) { + // return null; + // } + // } + // } + // return type; + // } /** * @see IJavaProject#findType(String, String) */ -// public IType findType(String packageName, String typeQualifiedName) throws JavaModelException { -// return -// this.getNameLookup().findType( -// typeQualifiedName, -// packageName, -// false, -// NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES); -// } -// + // public IType findType(String packageName, String typeQualifiedName) + // throws JavaModelException { + // return + // this.getNameLookup().findType( + // typeQualifiedName, + // packageName, + // false, + // NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES); + // } + // /** * Remove all markers denoting classpath problems */ - protected void flushClasspathProblemMarkers(boolean flushCycleMarkers, boolean flushClasspathFormatMarkers) { + protected void flushClasspathProblemMarkers(boolean flushCycleMarkers, + boolean flushClasspathFormatMarkers) { try { IProject project = getProject(); if (project.exists()) { - IMarker[] markers = project.findMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, false, IResource.DEPTH_ZERO); + IMarker[] markers = project.findMarkers( + IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, false, + IResource.DEPTH_ZERO); for (int i = 0, length = markers.length; i < length; i++) { IMarker marker = markers[i]; if (flushCycleMarkers && flushClasspathFormatMarkers) { marker.delete(); } else { - String cycleAttr = (String)marker.getAttribute(IJavaModelMarker.CYCLE_DETECTED); - String classpathFileFormatAttr = (String)marker.getAttribute(IJavaModelMarker.CLASSPATH_FILE_FORMAT); - if ((flushCycleMarkers == (cycleAttr != null && cycleAttr.equals("true"))) //$NON-NLS-1$ - && (flushClasspathFormatMarkers == (classpathFileFormatAttr != null && classpathFileFormatAttr.equals("true")))){ //$NON-NLS-1$ + String cycleAttr = (String) marker + .getAttribute(IJavaModelMarker.CYCLE_DETECTED); + String classpathFileFormatAttr = (String) marker + .getAttribute(IJavaModelMarker.CLASSPATH_FILE_FORMAT); + if ((flushCycleMarkers == (cycleAttr != null && cycleAttr + .equals("true"))) //$NON-NLS-1$ + && (flushClasspathFormatMarkers == (classpathFileFormatAttr != null && classpathFileFormatAttr + .equals("true")))) { //$NON-NLS-1$ marker.delete(); } } @@ -1266,66 +1382,71 @@ public class JavaProject } } -// /** -// * @see Openable -// */ -// protected boolean generateInfos( -// OpenableElementInfo info, -// IProgressMonitor pm, -// Map newElements, -// IResource underlyingResource) throws JavaModelException { -// -// boolean validInfo = false; -// try { -// if (getProject().isOpen()) { -// // put the info now, because computing the roots requires it -// JavaModelManager.getJavaModelManager().putInfo(this, info); -// -// // compute the pkg fragment roots -// updatePackageFragmentRoots(); -// -// // remember the timestamps of external libraries the first time they are looked up -// IClasspathEntry[] resolvedClasspath = getResolvedClasspath(true/*ignore unresolved variable*/); -// for (int i = 0, length = resolvedClasspath.length; i < length; i++) { -// IClasspathEntry entry = resolvedClasspath[i]; -// if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) { -// IPath path = entry.getPath(); -// Object target = JavaModel.getTarget(ResourcesPlugin.getWorkspace().getRoot(), path, true); -// if (target instanceof java.io.File) { -// Map externalTimeStamps = JavaModelManager.getJavaModelManager().deltaProcessor.externalTimeStamps; -// if (externalTimeStamps.get(path) == null) { -// long timestamp = DeltaProcessor.getTimeStamp((java.io.File)target); -// externalTimeStamps.put(path, new Long(timestamp)); -// } -// } -// } -// } -// -// // only valid if reaches here -// validInfo = true; -// } -// } finally { -// if (!validInfo) -// JavaModelManager.getJavaModelManager().removeInfo(this); -// } -// return validInfo; -// } + // /** + // * @see Openable + // */ + // protected boolean generateInfos( + // OpenableElementInfo info, + // IProgressMonitor pm, + // Map newElements, + // IResource underlyingResource) throws JavaModelException { + // + // boolean validInfo = false; + // try { + // if (getProject().isOpen()) { + // // put the info now, because computing the roots requires it + // JavaModelManager.getJavaModelManager().putInfo(this, info); + // + // // compute the pkg fragment roots + // updatePackageFragmentRoots(); + // + // // remember the timestamps of external libraries the first time they are + // looked up + // IClasspathEntry[] resolvedClasspath = getResolvedClasspath(true/*ignore + // unresolved variable*/); + // for (int i = 0, length = resolvedClasspath.length; i < length; i++) { + // IClasspathEntry entry = resolvedClasspath[i]; + // if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) { + // IPath path = entry.getPath(); + // Object target = + // JavaModel.getTarget(ResourcesPlugin.getWorkspace().getRoot(), path, + // true); + // if (target instanceof java.io.File) { + // Map externalTimeStamps = + // JavaModelManager.getJavaModelManager().deltaProcessor.externalTimeStamps; + // if (externalTimeStamps.get(path) == null) { + // long timestamp = DeltaProcessor.getTimeStamp((java.io.File)target); + // externalTimeStamps.put(path, new Long(timestamp)); + // } + // } + // } + // } + // + // // only valid if reaches here + // validInfo = true; + // } + // } finally { + // if (!validInfo) + // JavaModelManager.getJavaModelManager().removeInfo(this); + // } + // return validInfo; + // } /** * @see IJavaProject */ public IPackageFragmentRoot[] getAllPackageFragmentRoots() - throws JavaModelException { + throws JavaModelException { return computePackageFragmentRoots(getResolvedClasspath(true), true); } /** - * Returns the classpath entry that refers to the given path - * or null if there is no reference to the path. + * Returns the classpath entry that refers to the given path or + * null if there is no reference to the path. */ public IClasspathEntry getClasspathEntryFor(IPath path) - throws JavaModelException { + throws JavaModelException { IClasspathEntry[] entries = getExpandedClasspath(true); for (int i = 0; i < entries.length; i++) { @@ -1339,15 +1460,18 @@ public class JavaProject /* * Returns the cycle marker associated with this project or null if none. */ - public IMarker getCycleMarker(){ + public IMarker getCycleMarker() { try { IProject project = getProject(); if (project.exists()) { - IMarker[] markers = project.findMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, false, IResource.DEPTH_ZERO); + IMarker[] markers = project.findMarkers( + IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, false, + IResource.DEPTH_ZERO); for (int i = 0, length = markers.length; i < length; i++) { IMarker marker = markers[i]; - String cycleAttr = (String)marker.getAttribute(IJavaModelMarker.CYCLE_DETECTED); - if (cycleAttr != null && cycleAttr.equals("true")){ //$NON-NLS-1$ + String cycleAttr = (String) marker + .getAttribute(IJavaModelMarker.CYCLE_DETECTED); + if (cycleAttr != null && cycleAttr.equals("true")) { //$NON-NLS-1$ return marker; } } @@ -1356,50 +1480,59 @@ public class JavaProject } return null; } + /** * @see IJavaElement */ public int getElementType() { return JAVA_PROJECT; } + /** - * This is a helper method returning the expanded classpath for the project, as a list of classpath entries, - * where all classpath variable entries have been resolved and substituted with their final target entries. - * All project exports have been appended to project entries. - * @param ignoreUnresolvedVariable boolean + * This is a helper method returning the expanded classpath for the project, + * as a list of classpath entries, where all classpath variable entries have + * been resolved and substituted with their final target entries. All + * project exports have been appended to project entries. + * + * @param ignoreUnresolvedVariable + * boolean * @return IClasspathEntry[] * @throws JavaModelException */ - public IClasspathEntry[] getExpandedClasspath(boolean ignoreUnresolvedVariable) throws JavaModelException { - - return getExpandedClasspath(ignoreUnresolvedVariable, false/*don't create markers*/, null, null); + public IClasspathEntry[] getExpandedClasspath( + boolean ignoreUnresolvedVariable) throws JavaModelException { + + return getExpandedClasspath(ignoreUnresolvedVariable, + false/* don't create markers */, null, null); } - + /* * @see JavaElement */ - public IJavaElement getHandleFromMemento(String token, MementoTokenizer memento, WorkingCopyOwner owner) { + public IJavaElement getHandleFromMemento(String token, + MementoTokenizer memento, WorkingCopyOwner owner) { switch (token.charAt(0)) { - case JEM_COUNT: - return getHandleUpdatingCountFromMemento(memento, owner); - case JEM_PACKAGEFRAGMENTROOT: - String rootPath = IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH; - token = null; - while (memento.hasMoreTokens()) { - token = memento.nextToken(); - char firstChar = token.charAt(0); - if (firstChar != JEM_PACKAGEFRAGMENT && firstChar != JEM_COUNT) { - rootPath += token; - } else { - break; - } - } - JavaElement root = (JavaElement)getPackageFragmentRoot(new Path(rootPath)); - if (token != null && token.charAt(0) == JEM_PACKAGEFRAGMENT) { - return root.getHandleFromMemento(token, memento, owner); + case JEM_COUNT: + return getHandleUpdatingCountFromMemento(memento, owner); + case JEM_PACKAGEFRAGMENTROOT: + String rootPath = IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH; + token = null; + while (memento.hasMoreTokens()) { + token = memento.nextToken(); + char firstChar = token.charAt(0); + if (firstChar != JEM_PACKAGEFRAGMENT && firstChar != JEM_COUNT) { + rootPath += token; } else { - return root.getHandleFromMemento(memento, owner); + break; } + } + JavaElement root = (JavaElement) getPackageFragmentRoot(new Path( + rootPath)); + if (token != null && token.charAt(0) == JEM_PACKAGEFRAGMENT) { + return root.getHandleFromMemento(token, memento, owner); + } else { + return root.getHandleFromMemento(memento, owner); + } } return null; } @@ -1412,59 +1545,73 @@ public class JavaProject return JEM_JAVAPROJECT; } - + /** * Internal variant which can create marker on project for invalid entries, - * it will also perform classpath expansion in presence of project prerequisites - * exporting their entries. - * @param ignoreUnresolvedVariable boolean - * @param generateMarkerOnError boolean - * @param preferredClasspaths Map - * @param preferredOutputs Map + * it will also perform classpath expansion in presence of project + * prerequisites exporting their entries. + * + * @param ignoreUnresolvedVariable + * boolean + * @param generateMarkerOnError + * boolean + * @param preferredClasspaths + * Map + * @param preferredOutputs + * Map * @return IClasspathEntry[] * @throws JavaModelException */ public IClasspathEntry[] getExpandedClasspath( - boolean ignoreUnresolvedVariable, - boolean generateMarkerOnError, - Map preferredClasspaths, - Map preferredOutputs) throws JavaModelException { - - ObjectVector accumulatedEntries = new ObjectVector(); - computeExpandedClasspath(this, ignoreUnresolvedVariable, generateMarkerOnError, new HashSet(5), accumulatedEntries, preferredClasspaths, preferredOutputs); - - IClasspathEntry[] expandedPath = new IClasspathEntry[accumulatedEntries.size()]; + boolean ignoreUnresolvedVariable, boolean generateMarkerOnError, + Map preferredClasspaths, Map preferredOutputs) + throws JavaModelException { + + ObjectVector accumulatedEntries = new ObjectVector(); + computeExpandedClasspath(this, ignoreUnresolvedVariable, + generateMarkerOnError, new HashSet(5), accumulatedEntries, + preferredClasspaths, preferredOutputs); + + IClasspathEntry[] expandedPath = new IClasspathEntry[accumulatedEntries + .size()]; accumulatedEntries.copyInto(expandedPath); return expandedPath; } -// /** -// * Internal variant which can create marker on project for invalid entries, -// * it will also perform classpath expansion in presence of project prerequisites -// * exporting their entries. -// */ -// public IClasspathEntry[] getExpandedClasspath( -// boolean ignoreUnresolvedVariable, -// boolean generateMarkerOnError) throws JavaModelException { -// -// ObjectVector accumulatedEntries = new ObjectVector(); -// computeExpandedClasspath(this, ignoreUnresolvedVariable, generateMarkerOnError, new HashSet(5), accumulatedEntries); -// -// IClasspathEntry[] expandedPath = new IClasspathEntry[accumulatedEntries.size()]; -// accumulatedEntries.copyInto(expandedPath); -// -// return expandedPath; -// } - - /** - * Find the specific Java command amongst the build spec of a given description + + // /** + // * Internal variant which can create marker on project for invalid + // entries, + // * it will also perform classpath expansion in presence of project + // prerequisites + // * exporting their entries. + // */ + // public IClasspathEntry[] getExpandedClasspath( + // boolean ignoreUnresolvedVariable, + // boolean generateMarkerOnError) throws JavaModelException { + // + // ObjectVector accumulatedEntries = new ObjectVector(); + // computeExpandedClasspath(this, ignoreUnresolvedVariable, + // generateMarkerOnError, new HashSet(5), accumulatedEntries); + // + // IClasspathEntry[] expandedPath = new + // IClasspathEntry[accumulatedEntries.size()]; + // accumulatedEntries.copyInto(expandedPath); + // + // return expandedPath; + // } + + /** + * Find the specific Java command amongst the build spec of a given + * description */ private ICommand getJavaCommand(IProjectDescription description) - throws CoreException { + throws CoreException { ICommand[] commands = description.getBuildSpec(); for (int i = 0; i < commands.length; ++i) { - if (commands[i].getBuilderName().equals(PHPeclipsePlugin.BUILDER_PARSER_ID)) { + if (commands[i].getBuilderName().equals( + PHPeclipsePlugin.BUILDER_PARSER_ID)) { return commands[i]; } } @@ -1472,10 +1619,11 @@ public class JavaProject } /** - * Convenience method that returns the specific type of info for a Java project. + * Convenience method that returns the specific type of info for a Java + * project. */ protected JavaProjectElementInfo getJavaProjectElementInfo() - throws JavaModelException { + throws JavaModelException { return (JavaProjectElementInfo) getElementInfo(); } @@ -1487,111 +1635,127 @@ public class JavaProject JavaProjectElementInfo info = getJavaProjectElementInfo(); // lock on the project info to avoid race condition - synchronized(info){ + synchronized (info) { NameLookup nameLookup; - if ((nameLookup = info.getNameLookup()) == null){ + if ((nameLookup = info.getNameLookup()) == null) { info.setNameLookup(nameLookup = new NameLookup(this)); } return nameLookup; } } + /* - * Returns a new name lookup. This name lookup first looks in the given working copies. + * Returns a new name lookup. This name lookup first looks in the given + * working copies. */ - public NameLookup newNameLookup(ICompilationUnit[] workingCopies) throws JavaModelException { + public NameLookup newNameLookup(ICompilationUnit[] workingCopies) + throws JavaModelException { JavaProjectElementInfo info = getJavaProjectElementInfo(); - // lock on the project info to avoid race condition while computing the pkg fragment roots and package fragment caches -// synchronized(info){ -// return new NameLookup(info.getAllPackageFragmentRoots(this), info.getAllPackageFragments(this), workingCopies); -// } + // lock on the project info to avoid race condition while computing the + // pkg fragment roots and package fragment caches + // synchronized(info){ + // return new NameLookup(info.getAllPackageFragmentRoots(this), + // info.getAllPackageFragments(this), workingCopies); + // } return null; } /* - * Returns a new name lookup. This name lookup first looks in the working copies of the given owner. + * Returns a new name lookup. This name lookup first looks in the working + * copies of the given owner. */ - public NameLookup newNameLookup(WorkingCopyOwner owner) throws JavaModelException { - + public NameLookup newNameLookup(WorkingCopyOwner owner) + throws JavaModelException { + JavaModelManager manager = JavaModelManager.getJavaModelManager(); - ICompilationUnit[] workingCopies = owner == null ? null : manager.getWorkingCopies(owner, true/*add primary WCs*/); + ICompilationUnit[] workingCopies = owner == null ? null : manager + .getWorkingCopies(owner, true/* add primary WCs */); return newNameLookup(workingCopies); } -// -// /** -// * Returns an array of non-java resources contained in the receiver. -// */ -// public Object[] getNonJavaResources() throws JavaModelException { -// -// return ((JavaProjectElementInfo) getElementInfo()).getNonJavaResources(this); -// } + + // + // /** + // * Returns an array of non-java resources contained in the receiver. + // */ + // public Object[] getNonJavaResources() throws JavaModelException { + // + // return ((JavaProjectElementInfo) + // getElementInfo()).getNonJavaResources(this); + // } /** * @see net.sourceforge.phpdt.core.IJavaProject#getOption(String, boolean) - */ + */ public String getOption(String optionName, boolean inheritJavaCoreOptions) { - - if (JavaModelManager.OptionNames.contains(optionName)){ - + + if (JavaModelManager.OptionNames.contains(optionName)) { + Preferences preferences = getPreferences(); if (preferences == null || preferences.isDefault(optionName)) { - return inheritJavaCoreOptions ? JavaCore.getOption(optionName) : null; + return inheritJavaCoreOptions ? JavaCore.getOption(optionName) + : null; } return preferences.getString(optionName).trim(); } return null; } - + /** * @see net.sourceforge.phpdt.core.IJavaProject#getOptions(boolean) */ public Map getOptions(boolean inheritJavaCoreOptions) { - + // initialize to the defaults from JavaCore options pool - Map options = inheritJavaCoreOptions ? JavaCore.getOptions() : new Hashtable(5); + Map options = inheritJavaCoreOptions ? JavaCore.getOptions() + : new Hashtable(5); Preferences preferences = getPreferences(); - if (preferences == null) return options; // cannot do better (non-Java project) + if (preferences == null) + return options; // cannot do better (non-Java project) HashSet optionNames = JavaModelManager.OptionNames; - + // get preferences set to their default - if (inheritJavaCoreOptions){ + if (inheritJavaCoreOptions) { String[] defaultPropertyNames = preferences.defaultPropertyNames(); - for (int i = 0; i < defaultPropertyNames.length; i++){ + for (int i = 0; i < defaultPropertyNames.length; i++) { String propertyName = defaultPropertyNames[i]; - if (optionNames.contains(propertyName)){ - options.put(propertyName, preferences.getDefaultString(propertyName).trim()); + if (optionNames.contains(propertyName)) { + options.put(propertyName, preferences.getDefaultString( + propertyName).trim()); } - } + } } // get custom preferences not set to their default String[] propertyNames = preferences.propertyNames(); - for (int i = 0; i < propertyNames.length; i++){ + for (int i = 0; i < propertyNames.length; i++) { String propertyName = propertyNames[i]; - if (optionNames.contains(propertyName)){ - options.put(propertyName, preferences.getString(propertyName).trim()); + if (optionNames.contains(propertyName)) { + options.put(propertyName, preferences.getString(propertyName) + .trim()); } - } + } return options; } - + /** * @see IJavaProject */ -// public IPath getOutputLocation() throws JavaModelException { -// -// JavaModelManager.PerProjectInfo perProjectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(project); -// IPath outputLocation = perProjectInfo.outputLocation; -// if (outputLocation != null) return outputLocation; -// -// // force to read classpath - will position output location as well -// this.getRawClasspath(); -// outputLocation = perProjectInfo.outputLocation; -// if (outputLocation == null) { -// return defaultOutputLocation(); -// } -// return outputLocation; -// } + // public IPath getOutputLocation() throws JavaModelException { + // + // JavaModelManager.PerProjectInfo perProjectInfo = + // JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(project); + // IPath outputLocation = perProjectInfo.outputLocation; + // if (outputLocation != null) return outputLocation; + // + // // force to read classpath - will position output location as well + // this.getRawClasspath(); + // outputLocation = perProjectInfo.outputLocation; + // if (outputLocation == null) { + // return defaultOutputLocation(); + // } + // return outputLocation; + // } /** * @see IJavaProject */ @@ -1599,18 +1763,22 @@ public class JavaProject // Do not create marker but log problems while getting output location return this.getOutputLocation(false, true); } - + /** - * @param createMarkers boolean - * @param logProblems boolean + * @param createMarkers + * boolean + * @param logProblems + * boolean * @return IPath * @throws JavaModelException */ - public IPath getOutputLocation(boolean createMarkers, boolean logProblems) throws JavaModelException { + public IPath getOutputLocation(boolean createMarkers, boolean logProblems) + throws JavaModelException { JavaModelManager.PerProjectInfo perProjectInfo = getPerProjectInfo(); IPath outputLocation = perProjectInfo.outputLocation; - if (outputLocation != null) return outputLocation; + if (outputLocation != null) + return outputLocation; // force to read classpath - will position output location as well this.getRawClasspath(createMarkers, logProblems); @@ -1620,12 +1788,13 @@ public class JavaProject } return outputLocation; } + /** - * @return A handle to the package fragment root identified by the given path. - * This method is handle-only and the element may or may not exist. Returns - * null if unable to generate a handle from the path (for example, - * an absolute path that has less than 1 segment. The path may be relative or - * absolute. + * @return A handle to the package fragment root identified by the given + * path. This method is handle-only and the element may or may not + * exist. Returns null if unable to generate a handle + * from the path (for example, an absolute path that has less than 1 + * segment. The path may be relative or absolute. */ public IPackageFragmentRoot getPackageFragmentRoot(IPath path) { if (!path.isAbsolute()) { @@ -1633,23 +1802,26 @@ public class JavaProject } int segmentCount = path.segmentCount(); switch (segmentCount) { - case 0: - return null; - case 1: - // default root - return getPackageFragmentRoot(getProject()); - default: - // a path ending with .jar/.zip is still ambiguous and could still resolve to a source/lib folder - // thus will try to guess based on existing resource -// if (ProjectPrefUtil.isArchiveFileName(path.lastSegment())) { -// IResource resource = getProject().getWorkspace().getRoot().findMember(path); -// if (resource != null && resource.getType() == IResource.FOLDER){ -// return getPackageFragmentRoot(resource); -// } -// return getPackageFragmentRoot0(path); -// } else { - return getPackageFragmentRoot(getProject().getWorkspace().getRoot().getFolder(path)); -// } + case 0: + return null; + case 1: + // default root + return getPackageFragmentRoot(getProject()); + default: + // a path ending with .jar/.zip is still ambiguous and could still + // resolve to a source/lib folder + // thus will try to guess based on existing resource + // if (ProjectPrefUtil.isArchiveFileName(path.lastSegment())) { + // IResource resource = + // getProject().getWorkspace().getRoot().findMember(path); + // if (resource != null && resource.getType() == IResource.FOLDER){ + // return getPackageFragmentRoot(resource); + // } + // return getPackageFragmentRoot0(path); + // } else { + return getPackageFragmentRoot(getProject().getWorkspace().getRoot() + .getFolder(path)); + // } } } @@ -1660,63 +1832,61 @@ public class JavaProject if (path.segmentCount() == 1) { // default project root return getPackageFragmentRoot(getProject()); } - return getPackageFragmentRoot(getProject().getWorkspace().getRoot().getFolder(path)); + return getPackageFragmentRoot(getProject().getWorkspace().getRoot() + .getFolder(path)); } - + /** * @see IJavaProject */ public IPackageFragmentRoot getPackageFragmentRoot(IResource resource) { switch (resource.getType()) { - case IResource.FILE: -// if (ProjectPrefUtil.isArchiveFileName(resource.getName())) { -// return new JarPackageFragmentRoot(resource, this); -// } else { - return null; -// } - case IResource.FOLDER: - return new PackageFragmentRoot(resource, this, resource.getName()); - case IResource.PROJECT: - return new PackageFragmentRoot(resource, this, ""); //$NON-NLS-1$ - default: - return null; + case IResource.FILE: + // if (ProjectPrefUtil.isArchiveFileName(resource.getName())) { + // return new JarPackageFragmentRoot(resource, this); + // } else { + return null; + // } + case IResource.FOLDER: + return new PackageFragmentRoot(resource, this, resource.getName()); + case IResource.PROJECT: + return new PackageFragmentRoot(resource, this, ""); //$NON-NLS-1$ + default: + return null; } } /** * @see IJavaProject */ -// public IPackageFragmentRoot getPackageFragmentRoot(String jarPath) { -// -// return getPackageFragmentRoot0(JavaProject.canonicalizedPath(new Path(jarPath))); -// } -// -// /** -// * no path canonicalization -// */ -// public IPackageFragmentRoot getPackageFragmentRoot0(IPath jarPath) { -// -// return new JarPackageFragmentRoot(jarPath, this); -// } - + // public IPackageFragmentRoot getPackageFragmentRoot(String jarPath) { + // + // return getPackageFragmentRoot0(JavaProject.canonicalizedPath(new + // Path(jarPath))); + // } + // + // /** + // * no path canonicalization + // */ + // public IPackageFragmentRoot getPackageFragmentRoot0(IPath jarPath) { + // + // return new JarPackageFragmentRoot(jarPath, this); + // } /** * @see IJavaProject */ public IPackageFragmentRoot[] getPackageFragmentRoots() - throws JavaModelException { + throws JavaModelException { Object[] children; int length; IPackageFragmentRoot[] roots; - System.arraycopy( - children = getChildren(), - 0, - roots = new IPackageFragmentRoot[length = children.length], - 0, - length); - + System.arraycopy(children = getChildren(), 0, + roots = new IPackageFragmentRoot[length = children.length], 0, + length); + return roots; } @@ -1729,12 +1899,12 @@ public class JavaProject } /** - * Returns the package fragment root prefixed by the given path, or - * an empty collection if there are no such elements in the model. + * Returns the package fragment root prefixed by the given path, or an empty + * collection if there are no such elements in the model. */ protected IPackageFragmentRoot[] getPackageFragmentRoots(IPath path) - throws JavaModelException { + throws JavaModelException { IPackageFragmentRoot[] roots = getAllPackageFragmentRoots(); ArrayList matches = new ArrayList(); @@ -1758,10 +1928,11 @@ public class JavaProject } /** - * Returns all the package fragments found in the specified - * package fragment roots. + * Returns all the package fragments found in the specified package fragment + * roots. */ - public IPackageFragment[] getPackageFragmentsInRoots(IPackageFragmentRoot[] roots) { + public IPackageFragment[] getPackageFragmentsInRoots( + IPackageFragmentRoot[] roots) { ArrayList frags = new ArrayList(); for (int i = 0; i < roots.length; i++) { @@ -1779,18 +1950,20 @@ public class JavaProject frags.toArray(fragments); return fragments; } - + /* * @see IJavaElement */ public IPath getPath() { return this.getProject().getFullPath(); } - - public JavaModelManager.PerProjectInfo getPerProjectInfo() throws JavaModelException { - return JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(this.project); + + public JavaModelManager.PerProjectInfo getPerProjectInfo() + throws JavaModelException { + return JavaModelManager.getJavaModelManager() + .getPerProjectInfoCheckExistence(this.project); } - + /** * @see IJavaProject */ @@ -1798,11 +1971,11 @@ public class JavaProject return project; } + /** - * Sets the underlying kernel project of this Java project, - * and fills in its parent and name. - * Called by IProject.getNature(). - * + * Sets the underlying kernel project of this Java project, and fills in its + * parent and name. Called by IProject.getNature(). + * * @see IProjectNature#setProject(IProject) */ public void setProject(IProject project) { @@ -1811,35 +1984,40 @@ public class JavaProject this.parent = JavaModelManager.getJavaModelManager().getJavaModel(); this.name = project.getName(); } + protected IProject getProject(String name) { return PHPeclipsePlugin.getWorkspace().getRoot().getProject(name); } - - public List getReferencedProjects() { - List referencedProjects = new ArrayList(); - Iterator iterator = getLoadPathEntries().iterator(); - while (iterator.hasNext()) { - LoadPathEntry pathEntry = (LoadPathEntry) iterator.next(); - if (pathEntry.getType() == LoadPathEntry.TYPE_PROJECT) - referencedProjects.add(pathEntry.getProject()); - } + public List getReferencedProjects() { + List referencedProjects = new ArrayList(); - return referencedProjects; + Iterator iterator = getLoadPathEntries().iterator(); + while (iterator.hasNext()) { + LoadPathEntry pathEntry = (LoadPathEntry) iterator.next(); + if (pathEntry.getType() == LoadPathEntry.TYPE_PROJECT) + referencedProjects.add(pathEntry.getProject()); } - + + return referencedProjects; + } + /** - * Returns the project custom preference pool. - * Project preferences may include custom encoding. - */ - public Preferences getPreferences(){ + * Returns the project custom preference pool. Project preferences may + * include custom encoding. + */ + public Preferences getPreferences() { IProject project = getProject(); - if (!JavaProject.hasJavaNature(project)) return null; - JavaModelManager.PerProjectInfo perProjectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfo(project, true); - Preferences preferences = perProjectInfo.preferences; - if (preferences != null) return preferences; + if (!JavaProject.hasJavaNature(project)) + return null; + JavaModelManager.PerProjectInfo perProjectInfo = JavaModelManager + .getJavaModelManager().getPerProjectInfo(project, true); + Preferences preferences = perProjectInfo.preferences; + if (preferences != null) + return preferences; preferences = loadPreferences(); - if (preferences == null) preferences = new Preferences(); + if (preferences == null) + preferences = new Preferences(); perProjectInfo.preferences = preferences; return preferences; } @@ -1847,37 +2025,41 @@ public class JavaProject /** * @see IJavaProject */ -// public IClasspathEntry[] getRawClasspath() throws JavaModelException { -// -// JavaModelManager.PerProjectInfo perProjectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(project); -// IClasspathEntry[] classpath = perProjectInfo.classpath; -// if (classpath != null) return classpath; -// classpath = this.readClasspathFile(false/*don't create markers*/, true/*log problems*/); -// -// // extract out the output location -// IPath outputLocation = null; -// if (classpath != null && classpath.length > 0) { -// IClasspathEntry entry = classpath[classpath.length - 1]; -// if (entry.getContentKind() == ClasspathEntry.K_OUTPUT) { -// outputLocation = entry.getPath(); -// IClasspathEntry[] copy = new IClasspathEntry[classpath.length - 1]; -// System.arraycopy(classpath, 0, copy, 0, copy.length); -// classpath = copy; -// } -// } -// if (classpath == null) { -// return defaultClasspath(); -// } -// /* Disable validate: classpath can contain CP variables and container that need to be resolved -// if (classpath != INVALID_CLASSPATH -// && !JavaConventions.validateClasspath(this, classpath, outputLocation).isOK()) { -// classpath = INVALID_CLASSPATH; -// } -// */ -// perProjectInfo.classpath = classpath; -// perProjectInfo.outputLocation = outputLocation; -// return classpath; -// } + // public IClasspathEntry[] getRawClasspath() throws JavaModelException { + // + // JavaModelManager.PerProjectInfo perProjectInfo = + // JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(project); + // IClasspathEntry[] classpath = perProjectInfo.classpath; + // if (classpath != null) return classpath; + // classpath = this.readClasspathFile(false/*don't create markers*/, + // true/*log problems*/); + // + // // extract out the output location + // IPath outputLocation = null; + // if (classpath != null && classpath.length > 0) { + // IClasspathEntry entry = classpath[classpath.length - 1]; + // if (entry.getContentKind() == ClasspathEntry.K_OUTPUT) { + // outputLocation = entry.getPath(); + // IClasspathEntry[] copy = new IClasspathEntry[classpath.length - 1]; + // System.arraycopy(classpath, 0, copy, 0, copy.length); + // classpath = copy; + // } + // } + // if (classpath == null) { + // return defaultClasspath(); + // } + // /* Disable validate: classpath can contain CP variables and container + // that need to be resolved + // if (classpath != INVALID_CLASSPATH + // && !JavaConventions.validateClasspath(this, classpath, + // outputLocation).isOK()) { + // classpath = INVALID_CLASSPATH; + // } + // */ + // perProjectInfo.classpath = classpath; + // perProjectInfo.outputLocation = outputLocation; + // return classpath; + // } /** * @see IJavaProject */ @@ -1889,17 +2071,19 @@ public class JavaProject /* * Internal variant allowing to parameterize problem creation/logging */ - public IClasspathEntry[] getRawClasspath(boolean createMarkers, boolean logProblems) throws JavaModelException { + public IClasspathEntry[] getRawClasspath(boolean createMarkers, + boolean logProblems) throws JavaModelException { JavaModelManager.PerProjectInfo perProjectInfo = null; IClasspathEntry[] classpath; if (createMarkers) { - this.flushClasspathProblemMarkers(false/*cycle*/, true/*format*/); + this.flushClasspathProblemMarkers(false/* cycle */, true/* format */); classpath = this.readClasspathFile(createMarkers, logProblems); } else { perProjectInfo = getPerProjectInfo(); classpath = perProjectInfo.rawClasspath; - if (classpath != null) return classpath; + if (classpath != null) + return classpath; classpath = this.readClasspathFile(createMarkers, logProblems); } // extract out the output location @@ -1916,19 +2100,19 @@ public class JavaProject if (classpath == null) { return defaultClasspath(); } - /* Disable validate: classpath can contain CP variables and container that need to be resolved - if (classpath != INVALID_CLASSPATH - && !JavaConventions.validateClasspath(this, classpath, outputLocation).isOK()) { - classpath = INVALID_CLASSPATH; - } - */ + /* + * Disable validate: classpath can contain CP variables and container + * that need to be resolved if (classpath != INVALID_CLASSPATH && + * !JavaConventions.validateClasspath(this, classpath, + * outputLocation).isOK()) { classpath = INVALID_CLASSPATH; } + */ if (!createMarkers) { perProjectInfo.rawClasspath = classpath; perProjectInfo.outputLocation = outputLocation; } return classpath; } - + /** * @see IJavaProject#getRequiredProjectNames */ @@ -1941,12 +2125,9 @@ public class JavaProject * @see IJavaProject */ public IClasspathEntry[] getResolvedClasspath(boolean ignoreUnresolvedEntry) - throws JavaModelException { + throws JavaModelException { - return - this.getResolvedClasspath( - ignoreUnresolvedEntry, - false); // generateMarkerOnError + return this.getResolvedClasspath(ignoreUnresolvedEntry, false); // generateMarkerOnError } /** @@ -1954,58 +2135,59 @@ public class JavaProject * and caches the resolved classpath on perProjectInfo */ public IClasspathEntry[] getResolvedClasspath( - boolean ignoreUnresolvedEntry, - boolean generateMarkerOnError) - throws JavaModelException { - return - getResolvedClasspath( - ignoreUnresolvedEntry, - generateMarkerOnError, - true // returnResolutionInProgress + boolean ignoreUnresolvedEntry, boolean generateMarkerOnError) + throws JavaModelException { + return getResolvedClasspath(ignoreUnresolvedEntry, + generateMarkerOnError, true // returnResolutionInProgress ); -// JavaModelManager manager = JavaModelManager.getJavaModelManager(); -// JavaModelManager.PerProjectInfo perProjectInfo = manager.getPerProjectInfoCheckExistence(project); -// -// // reuse cache if not needing to refresh markers or checking bound variables -// if (ignoreUnresolvedEntry && !generateMarkerOnError && perProjectInfo != null){ -// // resolved path is cached on its info -// IClasspathEntry[] infoPath = perProjectInfo.lastResolvedClasspath; -// if (infoPath != null) return infoPath; -// } -// Map reverseMap = perProjectInfo == null ? null : new HashMap(5); -// IClasspathEntry[] resolvedPath = getResolvedClasspath( -// getRawClasspath(), -// generateMarkerOnError ? getOutputLocation() : null, -// ignoreUnresolvedEntry, -// generateMarkerOnError, -// reverseMap); -// -// if (perProjectInfo != null){ -// if (perProjectInfo.classpath == null // .classpath file could not be read -// && generateMarkerOnError -// && JavaProject.hasJavaNature(project)) { -// this.createClasspathProblemMarker(new JavaModelStatus( -// IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, -// Util.bind("classpath.cannotReadClasspathFile", this.getElementName()))); //$NON-NLS-1$ -// } -// -// perProjectInfo.lastResolvedClasspath = resolvedPath; -// perProjectInfo.resolvedPathToRawEntries = reverseMap; -// } -// return resolvedPath; + // JavaModelManager manager = JavaModelManager.getJavaModelManager(); + // JavaModelManager.PerProjectInfo perProjectInfo = + // manager.getPerProjectInfoCheckExistence(project); + // + // // reuse cache if not needing to refresh markers or checking bound + // variables + // if (ignoreUnresolvedEntry && !generateMarkerOnError && perProjectInfo + // != null){ + // // resolved path is cached on its info + // IClasspathEntry[] infoPath = perProjectInfo.lastResolvedClasspath; + // if (infoPath != null) return infoPath; + // } + // Map reverseMap = perProjectInfo == null ? null : new HashMap(5); + // IClasspathEntry[] resolvedPath = getResolvedClasspath( + // getRawClasspath(), + // generateMarkerOnError ? getOutputLocation() : null, + // ignoreUnresolvedEntry, + // generateMarkerOnError, + // reverseMap); + // + // if (perProjectInfo != null){ + // if (perProjectInfo.classpath == null // .classpath file could not be + // read + // && generateMarkerOnError + // && JavaProject.hasJavaNature(project)) { + // this.createClasspathProblemMarker(new JavaModelStatus( + // IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, + // Util.bind("classpath.cannotReadClasspathFile", + // this.getElementName()))); //$NON-NLS-1$ + // } + // + // perProjectInfo.lastResolvedClasspath = resolvedPath; + // perProjectInfo.resolvedPathToRawEntries = reverseMap; + // } + // return resolvedPath; } + /* * Internal variant which can create marker on project for invalid entries - * and caches the resolved classpath on perProjectInfo. - * If requested, return a special classpath (RESOLUTION_IN_PROGRESS) if the classpath is being resolved. + * and caches the resolved classpath on perProjectInfo. If requested, return + * a special classpath (RESOLUTION_IN_PROGRESS) if the classpath is being + * resolved. */ public IClasspathEntry[] getResolvedClasspath( - boolean ignoreUnresolvedEntry, - boolean generateMarkerOnError, - boolean returnResolutionInProgress) - throws JavaModelException { + boolean ignoreUnresolvedEntry, boolean generateMarkerOnError, + boolean returnResolutionInProgress) throws JavaModelException { - JavaModelManager manager = JavaModelManager.getJavaModelManager(); + JavaModelManager manager = JavaModelManager.getJavaModelManager(); JavaModelManager.PerProjectInfo perProjectInfo = null; if (ignoreUnresolvedEntry && !generateMarkerOnError) { perProjectInfo = getPerProjectInfo(); @@ -2014,43 +2196,51 @@ public class JavaProject IClasspathEntry[] infoPath = perProjectInfo.resolvedClasspath; if (infoPath != null) { return infoPath; - } else if (returnResolutionInProgress && manager.isClasspathBeingResolved(this)) { + } else if (returnResolutionInProgress + && manager.isClasspathBeingResolved(this)) { if (JavaModelManager.CP_RESOLVE_VERBOSE) { - Util.verbose( - "CPResolution: reentering raw classpath resolution, will use empty classpath instead" + //$NON-NLS-1$ - " project: " + getElementName() + '\n' + //$NON-NLS-1$ - " invocation stack trace:"); //$NON-NLS-1$ + Util + .verbose("CPResolution: reentering raw classpath resolution, will use empty classpath instead" + //$NON-NLS-1$ + " project: " + getElementName() + '\n' + //$NON-NLS-1$ + " invocation stack trace:"); //$NON-NLS-1$ new Exception("").printStackTrace(System.out); //$NON-NLS-1$ - } - return RESOLUTION_IN_PROGRESS; + } + return RESOLUTION_IN_PROGRESS; } } } Map reverseMap = perProjectInfo == null ? null : new HashMap(5); IClasspathEntry[] resolvedPath = null; - boolean nullOldResolvedCP = perProjectInfo != null && perProjectInfo.resolvedClasspath == null; + boolean nullOldResolvedCP = perProjectInfo != null + && perProjectInfo.resolvedClasspath == null; try { - // protect against misbehaving clients (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=61040) - if (nullOldResolvedCP) manager.setClasspathBeingResolved(this, true); - resolvedPath = getResolvedClasspath( - getRawClasspath(generateMarkerOnError, !generateMarkerOnError), - generateMarkerOnError ? getOutputLocation() : null, - ignoreUnresolvedEntry, - generateMarkerOnError, - reverseMap); + // protect against misbehaving clients (see + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=61040) + if (nullOldResolvedCP) + manager.setClasspathBeingResolved(this, true); + resolvedPath = getResolvedClasspath(getRawClasspath( + generateMarkerOnError, !generateMarkerOnError), + generateMarkerOnError ? getOutputLocation() : null, + ignoreUnresolvedEntry, generateMarkerOnError, reverseMap); } finally { - if (nullOldResolvedCP) perProjectInfo.resolvedClasspath = null; - } - - if (perProjectInfo != null){ - if (perProjectInfo.rawClasspath == null // .classpath file could not be read - && generateMarkerOnError - && JavaProject.hasJavaNature(this.project)) { - // flush .classpath format markers (bug 39877), but only when file cannot be read (bug 42366) - this.flushClasspathProblemMarkers(false, true); - this.createClasspathProblemMarker(new JavaModelStatus( - IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, - Util.bind("classpath.cannotReadClasspathFile", this.getElementName()))); //$NON-NLS-1$ + if (nullOldResolvedCP) + perProjectInfo.resolvedClasspath = null; + } + + if (perProjectInfo != null) { + if (perProjectInfo.rawClasspath == null // .classpath file could not + // be read + && generateMarkerOnError + && JavaProject.hasJavaNature(this.project)) { + // flush .classpath format markers (bug 39877), but only when + // file cannot be read (bug 42366) + this.flushClasspathProblemMarkers(false, true); + this + .createClasspathProblemMarker(new JavaModelStatus( + IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, + Util + .bind( + "classpath.cannotReadClasspathFile", this.getElementName()))); //$NON-NLS-1$ } perProjectInfo.resolvedClasspath = resolvedPath; @@ -2059,97 +2249,125 @@ public class JavaProject } return resolvedPath; } + /** * Internal variant which can process any arbitrary classpath */ public IClasspathEntry[] getResolvedClasspath( - IClasspathEntry[] classpathEntries, - IPath projectOutputLocation, // only set if needing full classpath validation (and markers) - boolean ignoreUnresolvedEntry, // if unresolved entries are met, should it trigger initializations - boolean generateMarkerOnError, - Map reverseMap) // can be null if not interested in reverse mapping - throws JavaModelException { + IClasspathEntry[] classpathEntries, IPath projectOutputLocation, // only + // set + // if + // needing + // full + // classpath + // validation + // (and + // markers) + boolean ignoreUnresolvedEntry, // if unresolved entries are met, + // should it trigger initializations + boolean generateMarkerOnError, Map reverseMap) // can be null if + // not interested in + // reverse mapping + throws JavaModelException { IJavaModelStatus status; - if (generateMarkerOnError){ + if (generateMarkerOnError) { flushClasspathProblemMarkers(false, false); } int length = classpathEntries.length; ArrayList resolvedEntries = new ArrayList(); - + for (int i = 0; i < length; i++) { IClasspathEntry rawEntry = classpathEntries[i]; IPath resolvedPath; status = null; - + /* validation if needed */ -// if (generateMarkerOnError || !ignoreUnresolvedEntry) { -// status = JavaConventions.validateClasspathEntry(this, rawEntry, false); -// if (generateMarkerOnError && !status.isOK()) createClasspathProblemMarker(status); -// } - - switch (rawEntry.getEntryKind()){ - - case IClasspathEntry.CPE_VARIABLE : - - IClasspathEntry resolvedEntry = JavaCore.getResolvedClasspathEntry(rawEntry); - if (resolvedEntry == null) { - if (!ignoreUnresolvedEntry) throw new JavaModelException(status); - } else { - if (reverseMap != null && reverseMap.get(resolvedPath = resolvedEntry.getPath()) == null) reverseMap.put(resolvedPath , rawEntry); - resolvedEntries.add(resolvedEntry); - } - break; - -// case IClasspathEntry.CPE_CONTAINER : -// -// IClasspathContainer container = PHPCore.getClasspathContainer(rawEntry.getPath(), this); -// if (container == null){ -// if (!ignoreUnresolvedEntry) throw new JavaModelException(status); -// break; -// } -// -// IClasspathEntry[] containerEntries = container.getClasspathEntries(); -// if (containerEntries == null) break; -// -// // container was bound -// for (int j = 0, containerLength = containerEntries.length; j < containerLength; j++){ -// IClasspathEntry cEntry = containerEntries[j]; -// -// if (generateMarkerOnError) { -// IJavaModelStatus containerStatus = JavaConventions.validateClasspathEntry(this, cEntry, false); -// if (!containerStatus.isOK()) createClasspathProblemMarker(containerStatus); -// } -// // if container is exported, then its nested entries must in turn be exported (21749) -// if (rawEntry.isExported()){ -// cEntry = new ClasspathEntry(cEntry.getContentKind(), -// cEntry.getEntryKind(), cEntry.getPath(), -// cEntry.getExclusionPatterns(), cEntry.getSourceAttachmentPath(), -// cEntry.getSourceAttachmentRootPath(), cEntry.getOutputLocation(), -// true); // duplicate container entry for tagging it as exported -// } -// if (reverseMap != null && reverseMap.get(resolvedPath = cEntry.getPath()) == null) reverseMap.put(resolvedPath, rawEntry); -// resolvedEntries.add(cEntry); -// } -// break; - - default : - - if (reverseMap != null && reverseMap.get(resolvedPath = rawEntry.getPath()) == null) reverseMap.put(resolvedPath, rawEntry); - resolvedEntries.add(rawEntry); - - } - } - - IClasspathEntry[] resolvedPath = new IClasspathEntry[resolvedEntries.size()]; + // if (generateMarkerOnError || !ignoreUnresolvedEntry) { + // status = JavaConventions.validateClasspathEntry(this, rawEntry, + // false); + // if (generateMarkerOnError && !status.isOK()) + // createClasspathProblemMarker(status); + // } + switch (rawEntry.getEntryKind()) { + + case IClasspathEntry.CPE_VARIABLE: + + IClasspathEntry resolvedEntry = JavaCore + .getResolvedClasspathEntry(rawEntry); + if (resolvedEntry == null) { + if (!ignoreUnresolvedEntry) + throw new JavaModelException(status); + } else { + if (reverseMap != null + && reverseMap.get(resolvedPath = resolvedEntry + .getPath()) == null) + reverseMap.put(resolvedPath, rawEntry); + resolvedEntries.add(resolvedEntry); + } + break; + + // case IClasspathEntry.CPE_CONTAINER : + // + // IClasspathContainer container = + // PHPCore.getClasspathContainer(rawEntry.getPath(), this); + // if (container == null){ + // if (!ignoreUnresolvedEntry) throw new JavaModelException(status); + // break; + // } + // + // IClasspathEntry[] containerEntries = + // container.getClasspathEntries(); + // if (containerEntries == null) break; + // + // // container was bound + // for (int j = 0, containerLength = containerEntries.length; j < + // containerLength; j++){ + // IClasspathEntry cEntry = containerEntries[j]; + // + // if (generateMarkerOnError) { + // IJavaModelStatus containerStatus = + // JavaConventions.validateClasspathEntry(this, cEntry, false); + // if (!containerStatus.isOK()) + // createClasspathProblemMarker(containerStatus); + // } + // // if container is exported, then its nested entries must in turn + // be exported (21749) + // if (rawEntry.isExported()){ + // cEntry = new ClasspathEntry(cEntry.getContentKind(), + // cEntry.getEntryKind(), cEntry.getPath(), + // cEntry.getExclusionPatterns(), cEntry.getSourceAttachmentPath(), + // cEntry.getSourceAttachmentRootPath(), cEntry.getOutputLocation(), + // true); // duplicate container entry for tagging it as exported + // } + // if (reverseMap != null && reverseMap.get(resolvedPath = + // cEntry.getPath()) == null) reverseMap.put(resolvedPath, + // rawEntry); + // resolvedEntries.add(cEntry); + // } + // break; + + default: + + if (reverseMap != null + && reverseMap.get(resolvedPath = rawEntry.getPath()) == null) + reverseMap.put(resolvedPath, rawEntry); + resolvedEntries.add(rawEntry); + + } + } + + IClasspathEntry[] resolvedPath = new IClasspathEntry[resolvedEntries + .size()]; resolvedEntries.toArray(resolvedPath); -// if (generateMarkerOnError && projectOutputLocation != null) { -// status = JavaConventions.validateClasspath(this, resolvedPath, projectOutputLocation); -// if (!status.isOK()) createClasspathProblemMarker(status); -// } + // if (generateMarkerOnError && projectOutputLocation != null) { + // status = JavaConventions.validateClasspath(this, resolvedPath, + // projectOutputLocation); + // if (!status.isOK()) createClasspathProblemMarker(status); + // } return resolvedPath; } @@ -2164,22 +2382,24 @@ public class JavaProject * @see IJavaProject */ public ISearchableNameEnvironment getSearchableNameEnvironment() - throws JavaModelException { + throws JavaModelException { -// JavaProjectElementInfo info = getJavaProjectElementInfo(); -// if (info.getSearchableEnvironment() == null) { -// info.setSearchableEnvironment(new SearchableEnvironment(this)); -// } -// return info.getSearchableEnvironment(); - return null; + // JavaProjectElementInfo info = getJavaProjectElementInfo(); + // if (info.getSearchableEnvironment() == null) { + // info.setSearchableEnvironment(new SearchableEnvironment(this)); + // } + // return info.getSearchableEnvironment(); + return null; } /** - * Retrieve a shared property on a project. If the property is not defined, answers null. - * Note that it is orthogonal to IResource persistent properties, and client code has to decide - * which form of storage to use appropriately. Shared properties produce real resource files which - * can be shared through a VCM onto a server. Persistent properties are not shareable. - * + * Retrieve a shared property on a project. If the property is not defined, + * answers null. Note that it is orthogonal to IResource persistent + * properties, and client code has to decide which form of storage to use + * appropriately. Shared properties produce real resource files which can be + * shared through a VCM onto a server. Persistent properties are not + * shareable. + * * @see JavaProject#setSharedProperty(String, String) */ public String getSharedProperty(String key) throws CoreException { @@ -2195,16 +2415,16 @@ public class JavaProject /** * @see JavaElement */ -// public SourceMapper getSourceMapper() { -// -// return null; -// } - + // public SourceMapper getSourceMapper() { + // + // return null; + // } /** * @see IJavaElement */ public IResource getUnderlyingResource() throws JavaModelException { - if (!exists()) throw newNotPresentException(); + if (!exists()) + throw newNotPresentException(); return getProject(); } @@ -2213,7 +2433,8 @@ public class JavaProject */ public boolean hasBuildState() { - return JavaModelManager.getJavaModelManager().getLastBuiltState(this.getProject(), null) != null; + return JavaModelManager.getJavaModelManager().getLastBuiltState( + this.getProject(), null) != null; } /** @@ -2221,11 +2442,13 @@ public class JavaProject */ public boolean hasClasspathCycle(IClasspathEntry[] preferredClasspath) { HashSet cycleParticipants = new HashSet(); - updateCycleParticipants(preferredClasspath, new ArrayList(2), cycleParticipants, ResourcesPlugin.getWorkspace().getRoot(), new HashSet(2)); + updateCycleParticipants(preferredClasspath, new ArrayList(2), + cycleParticipants, ResourcesPlugin.getWorkspace().getRoot(), + new HashSet(2)); return !cycleParticipants.isEmpty(); } - - public boolean hasCycleMarker(){ + + public boolean hasCycleMarker() { return this.getCycleMarker() != null; } @@ -2234,10 +2457,10 @@ public class JavaProject } /** - * Returns true if the given project is accessible and it has - * a java nature, otherwise false. + * Returns true if the given project is accessible and it has a java nature, + * otherwise false. */ - public static boolean hasJavaNature(IProject project) { + public static boolean hasJavaNature(IProject project) { try { return project.hasNature(PHPeclipsePlugin.PHP_NATURE_ID); } catch (CoreException e) { @@ -2245,9 +2468,10 @@ public class JavaProject } return false; } - + /** - * Answers true if the project potentially contains any source. A project which has no source is immutable. + * Answers true if the project potentially contains any source. A project + * which has no source is immutable. */ public boolean hasSource() { @@ -2268,13 +2492,15 @@ public class JavaProject } /** - * Compare current classpath with given one to see if any different. - * Note that the argument classpath contains its binary output. + * Compare current classpath with given one to see if any different. Note + * that the argument classpath contains its binary output. */ - public boolean isClasspathEqualsTo(IClasspathEntry[] newClasspath, IPath newOutputLocation, IClasspathEntry[] otherClasspathWithOutput) - throws JavaModelException { + public boolean isClasspathEqualsTo(IClasspathEntry[] newClasspath, + IPath newOutputLocation, IClasspathEntry[] otherClasspathWithOutput) + throws JavaModelException { - if (otherClasspathWithOutput != null && otherClasspathWithOutput.length > 0) { + if (otherClasspathWithOutput != null + && otherClasspathWithOutput.length > 0) { int length = otherClasspathWithOutput.length; if (length == newClasspath.length + 1) { @@ -2294,71 +2520,78 @@ public class JavaProject } return false; } - - /* * @see IJavaProject */ public boolean isOnClasspath(IJavaElement element) { IPath path = element.getPath(); switch (element.getElementType()) { - case IJavaElement.PACKAGE_FRAGMENT_ROOT: - if (!((IPackageFragmentRoot)element).isArchive()) { - // ensure that folders are only excluded if all of their children are excluded - path = path.append("*"); //$NON-NLS-1$ - } - break; - case IJavaElement.PACKAGE_FRAGMENT: - if (!((IPackageFragmentRoot)element.getParent()).isArchive()) { - // ensure that folders are only excluded if all of their children are excluded - path = path.append("*"); //$NON-NLS-1$ - } - break; + case IJavaElement.PACKAGE_FRAGMENT_ROOT: + if (!((IPackageFragmentRoot) element).isArchive()) { + // ensure that folders are only excluded if all of their + // children are excluded + path = path.append("*"); //$NON-NLS-1$ + } + break; + case IJavaElement.PACKAGE_FRAGMENT: + if (!((IPackageFragmentRoot) element.getParent()).isArchive()) { + // ensure that folders are only excluded if all of their + // children are excluded + path = path.append("*"); //$NON-NLS-1$ + } + break; } return this.isOnClasspath(path); } + private boolean isOnClasspath(IPath path) { IClasspathEntry[] classpath; try { - classpath = this.getResolvedClasspath(true/*ignore unresolved variable*/); - } catch(JavaModelException e){ + classpath = this + .getResolvedClasspath(true/* ignore unresolved variable */); + } catch (JavaModelException e) { return false; // not a Java project } for (int i = 0; i < classpath.length; i++) { IClasspathEntry entry = classpath[i]; - if (entry.getPath().isPrefixOf(path) - && !Util.isExcluded(path, null,((ClasspathEntry)entry).fullExclusionPatternChars(),true)) { + if (entry.getPath().isPrefixOf(path) + && !Util.isExcluded(path, null, ((ClasspathEntry) entry) + .fullExclusionPatternChars(), true)) { return true; } } return false; } + /* * @see IJavaProject */ public boolean isOnClasspath(IResource resource) { IPath path = resource.getFullPath(); - - // ensure that folders are only excluded if all of their children are excluded + + // ensure that folders are only excluded if all of their children are + // excluded if (resource.getType() == IResource.FOLDER) { path = path.append("*"); //$NON-NLS-1$ } - + return this.isOnClasspath(path); } private IPath getPluginWorkingLocation() { return this.project.getWorkingLocation(JavaCore.PLUGIN_ID); - } + } + /* * load preferences from a shareable format (VCM-wise) */ - public Preferences loadPreferences() { - - Preferences preferences = new Preferences(); - -// File prefFile = getProject().getLocation().append(PREF_FILENAME).toFile(); + public Preferences loadPreferences() { + + Preferences preferences = new Preferences(); + + // File prefFile = + // getProject().getLocation().append(PREF_FILENAME).toFile(); IPath projectMetaLocation = getPluginWorkingLocation(); if (projectMetaLocation != null) { File prefFile = projectMetaLocation.append(PREF_FILENAME).toFile(); @@ -2368,84 +2601,90 @@ public class JavaProject in = new BufferedInputStream(new FileInputStream(prefFile)); preferences.load(in); return preferences; - } catch (IOException e) { // problems loading preference store - quietly ignore + } catch (IOException e) { // problems loading preference store + // - quietly ignore } finally { if (in != null) { try { in.close(); - } catch (IOException e) { // ignore problems with close + } catch (IOException e) { // ignore problems with + // close } } } } } return null; - } - + } + /** * @see IJavaProject#newEvaluationContext */ -// public IEvaluationContext newEvaluationContext() { -// -// return new EvaluationContextWrapper(new EvaluationContext(), this); -// } - + // public IEvaluationContext newEvaluationContext() { + // + // return new EvaluationContextWrapper(new EvaluationContext(), this); + // } /** * @see IJavaProject */ -// public ITypeHierarchy newTypeHierarchy( -// IRegion region, -// IProgressMonitor monitor) -// throws JavaModelException { -// -// if (region == null) { -// throw new IllegalArgumentException(ProjectPrefUtil.bind("hierarchy.nullRegion"));//$NON-NLS-1$ -// } -// CreateTypeHierarchyOperation op = -// new CreateTypeHierarchyOperation(null, region, this, true); -// runOperation(op, monitor); -// return op.getResult(); -// } - + // public ITypeHierarchy newTypeHierarchy( + // IRegion region, + // IProgressMonitor monitor) + // throws JavaModelException { + // + // if (region == null) { + // throw new + // IllegalArgumentException(ProjectPrefUtil.bind("hierarchy.nullRegion"));//$NON-NLS-1$ + // } + // CreateTypeHierarchyOperation op = + // new CreateTypeHierarchyOperation(null, region, this, true); + // runOperation(op, monitor); + // return op.getResult(); + // } /** * @see IJavaProject */ -// public ITypeHierarchy newTypeHierarchy( -// IType type, -// IRegion region, -// IProgressMonitor monitor) -// throws JavaModelException { -// -// if (type == null) { -// throw new IllegalArgumentException(ProjectPrefUtil.bind("hierarchy.nullFocusType"));//$NON-NLS-1$ -// } -// if (region == null) { -// throw new IllegalArgumentException(ProjectPrefUtil.bind("hierarchy.nullRegion"));//$NON-NLS-1$ -// } -// CreateTypeHierarchyOperation op = -// new CreateTypeHierarchyOperation(type, region, this, true); -// runOperation(op, monitor); -// return op.getResult(); -// } - -// /** -// * Open project if resource isn't closed -// */ -// protected void openWhenClosed(IProgressMonitor pm) throws JavaModelException { -// -// if (!this.fProject.isOpen()) { -// throw newNotPresentException(); -// } else { -// super.openWhenClosed(pm); -// } -// } - + // public ITypeHierarchy newTypeHierarchy( + // IType type, + // IRegion region, + // IProgressMonitor monitor) + // throws JavaModelException { + // + // if (type == null) { + // throw new + // IllegalArgumentException(ProjectPrefUtil.bind("hierarchy.nullFocusType"));//$NON-NLS-1$ + // } + // if (region == null) { + // throw new + // IllegalArgumentException(ProjectPrefUtil.bind("hierarchy.nullRegion"));//$NON-NLS-1$ + // } + // CreateTypeHierarchyOperation op = + // new CreateTypeHierarchyOperation(type, region, this, true); + // runOperation(op, monitor); + // return op.getResult(); + // } + // /** + // * Open project if resource isn't closed + // */ + // protected void openWhenClosed(IProgressMonitor pm) throws + // JavaModelException { + // + // if (!this.fProject.isOpen()) { + // throw newNotPresentException(); + // } else { + // super.openWhenClosed(pm); + // } + // } public String[] projectPrerequisites(IClasspathEntry[] entries) - throws JavaModelException { - + throws JavaModelException { + ArrayList prerequisites = new ArrayList(); // need resolution - entries = getResolvedClasspath(entries, null, true, false, null/*no reverse map*/); + entries = getResolvedClasspath(entries, null, true, false, null/* + * no + * reverse + * map + */); for (int i = 0, length = entries.length; i < length; i++) { IClasspathEntry entry = entries[i]; if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) { @@ -2462,29 +2701,32 @@ public class JavaProject } } - /** - * Reads the .classpath file from disk and returns the list of entries it contains (including output location entry) - * Returns null if .classfile is not present. - * Returns INVALID_CLASSPATH if it has a format problem. + * Reads the .classpath file from disk and returns the list of entries it + * contains (including output location entry) Returns null if .classfile is + * not present. Returns INVALID_CLASSPATH if it has a format problem. */ - protected IClasspathEntry[] readClasspathFile(boolean createMarker, boolean logProblems) { + protected IClasspathEntry[] readClasspathFile(boolean createMarker, + boolean logProblems) { try { String xmlClasspath = getSharedProperty(CLASSPATH_FILENAME); - if (xmlClasspath == null) return null; + if (xmlClasspath == null) + return null; return decodeClasspath(xmlClasspath, createMarker, logProblems); - } catch(CoreException e) { + } catch (CoreException e) { // file does not exist (or not accessible) if (createMarker && this.getProject().isAccessible()) { - this.createClasspathProblemMarker(new JavaModelStatus( - IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, - Util.bind("classpath.cannotReadClasspathFile", this.getElementName()))); //$NON-NLS-1$ + this + .createClasspathProblemMarker(new JavaModelStatus( + IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, + Util + .bind( + "classpath.cannotReadClasspathFile", this.getElementName()))); //$NON-NLS-1$ } if (logProblems) { - Util.log(e, - "Exception while retrieving "+ this.getPath() //$NON-NLS-1$ - +"/.classpath, will revert to default classpath"); //$NON-NLS-1$ + Util.log(e, "Exception while retrieving " + this.getPath() //$NON-NLS-1$ + + "/.classpath, will revert to default classpath"); //$NON-NLS-1$ } } return null; @@ -2501,7 +2743,8 @@ public class JavaProject if (commands[i].getBuilderName().equals(builderID)) { ICommand[] newCommands = new ICommand[commands.length - 1]; System.arraycopy(commands, 0, newCommands, 0, i); - System.arraycopy(commands, i + 1, newCommands, i, commands.length - i - 1); + System.arraycopy(commands, i + 1, newCommands, i, + commands.length - i - 1); description.setBuildSpec(newCommands); getProject().setDescription(description, null); return; @@ -2509,66 +2752,75 @@ public class JavaProject } } - /** * @see JavaElement#rootedAt(IJavaProject) */ public IJavaElement rootedAt(IJavaProject project) { return project; - + } - + /** * Answers an ID which is used to distinguish project/entries during package * fragment root computations */ - public String rootID(){ - return "[PRJ]"+this.getProject().getFullPath(); //$NON-NLS-1$ + public String rootID() { + return "[PRJ]" + this.getProject().getFullPath(); //$NON-NLS-1$ } - + /** - * Saves the classpath in a shareable format (VCM-wise) only when necessary, that is, if it is semantically different - * from the existing one in file. Will never write an identical one. + * Saves the classpath in a shareable format (VCM-wise) only when necessary, + * that is, if it is semantically different from the existing one in file. + * Will never write an identical one. * * @return Return whether the .classpath file was modified. */ - public boolean saveClasspath(IClasspathEntry[] newClasspath, IPath newOutputLocation) throws JavaModelException { + public boolean saveClasspath(IClasspathEntry[] newClasspath, + IPath newOutputLocation) throws JavaModelException { - if (!getProject().exists()) return false; + if (!getProject().exists()) + return false; - IClasspathEntry[] fileEntries = readClasspathFile(false /*don't create markers*/, false/*don't log problems*/); - if (fileEntries != null && isClasspathEqualsTo(newClasspath, newOutputLocation, fileEntries)) { + IClasspathEntry[] fileEntries = readClasspathFile( + false /* don't create markers */, false/* don't log problems */); + if (fileEntries != null + && isClasspathEqualsTo(newClasspath, newOutputLocation, + fileEntries)) { // no need to save it, it is the same return false; } // actual file saving try { - setSharedProperty(CLASSPATH_FILENAME, encodeClasspath(newClasspath, newOutputLocation, true)); + setSharedProperty(CLASSPATH_FILENAME, encodeClasspath(newClasspath, + newOutputLocation, true)); return true; } catch (CoreException e) { throw new JavaModelException(e); } } - /** * Save project custom preferences to shareable file (.jprefs) */ private void savePreferences(Preferences preferences) { - - if (!JavaProject.hasJavaNature(this.project)) return; // ignore - - if (preferences == null || (!preferences.needsSaving() && preferences.propertyNames().length != 0)) { + + if (!JavaProject.hasJavaNature(this.project)) + return; // ignore + + if (preferences == null + || (!preferences.needsSaving() && preferences.propertyNames().length != 0)) { // nothing to save return; } - + // preferences need to be saved // the preferences file is located in the plug-in's state area // at a well-known name (.jprefs) -// File prefFile = this.project.getLocation().append(PREF_FILENAME).toFile(); - File prefFile = getPluginWorkingLocation().append(PREF_FILENAME).toFile(); + // File prefFile = + // this.project.getLocation().append(PREF_FILENAME).toFile(); + File prefFile = getPluginWorkingLocation().append(PREF_FILENAME) + .toFile(); if (preferences.propertyNames().length == 0) { // there are no preference settings // rather than write an empty file, just delete any existing file @@ -2577,7 +2829,7 @@ public class JavaProject } return; } - + // write file, overwriting an existing one OutputStream out = null; try { @@ -2585,7 +2837,8 @@ public class JavaProject // the setting in times of stress out = new BufferedOutputStream(new FileOutputStream(prefFile)); preferences.store(out, null); - } catch (IOException e) { // problems saving preference store - quietly ignore + } catch (IOException e) { // problems saving preference store - + // quietly ignore } finally { if (out != null) { try { @@ -2595,14 +2848,13 @@ public class JavaProject } } } + /** - * Update the Java command in the build spec (replace existing one if present, - * add one first if none). + * Update the Java command in the build spec (replace existing one if + * present, add one first if none). */ - private void setJavaCommand( - IProjectDescription description, - ICommand newCommand) - throws CoreException { + private void setJavaCommand(IProjectDescription description, + ICommand newCommand) throws CoreException { ICommand[] oldCommands = description.getBuildSpec(); ICommand oldJavaCommand = getJavaCommand(description); @@ -2611,7 +2863,9 @@ public class JavaProject if (oldJavaCommand == null) { // Add a Java build spec before other builders (1FWJK7I) newCommands = new ICommand[oldCommands.length + 1]; - System.arraycopy(oldCommands, 0, newCommands, 1, oldCommands.length); + System + .arraycopy(oldCommands, 0, newCommands, 1, + oldCommands.length); newCommands[0] = newCommand; } else { for (int i = 0, max = oldCommands.length; i < max; i++) { @@ -2634,28 +2888,36 @@ public class JavaProject public void setOptions(Map newOptions) { Preferences preferences; - setPreferences(preferences = new Preferences()); // always reset (26255) - if (newOptions != null){ + setPreferences(preferences = new Preferences()); // always reset + // (26255) + if (newOptions != null) { Iterator keys = newOptions.keySet().iterator(); - while (keys.hasNext()){ - String key = (String)keys.next(); - if (!JavaModelManager.OptionNames.contains(key)) continue; // unrecognized option - // no filtering for encoding (custom encoding for project is allowed) - String value = (String)newOptions.get(key); - preferences.setDefault(key, CUSTOM_DEFAULT_OPTION_VALUE); // empty string isn't the default (26251) + while (keys.hasNext()) { + String key = (String) keys.next(); + if (!JavaModelManager.OptionNames.contains(key)) + continue; // unrecognized option + // no filtering for encoding (custom encoding for project is + // allowed) + String value = (String) newOptions.get(key); + preferences.setDefault(key, CUSTOM_DEFAULT_OPTION_VALUE); // empty + // string + // isn't + // the + // default + // (26251) preferences.setValue(key, value); } } - + // persist options - savePreferences(preferences); + savePreferences(preferences); } /** * @see IJavaProject */ public void setOutputLocation(IPath path, IProgressMonitor monitor) - throws JavaModelException { + throws JavaModelException { if (path == null) { throw new IllegalArgumentException(Util.bind("path.nullpath")); //$NON-NLS-1$ @@ -2663,7 +2925,8 @@ public class JavaProject if (path.equals(getOutputLocation())) { return; } - this.setRawClasspath(SetClasspathOperation.ReuseClasspath, path, monitor); + this.setRawClasspath(SetClasspathOperation.ReuseClasspath, path, + monitor); } /* @@ -2671,58 +2934,46 @@ public class JavaProject */ public void setPreferences(Preferences preferences) { IProject project = getProject(); - if (!JavaProject.hasJavaNature(project)) return; // ignore - JavaModelManager.PerProjectInfo perProjectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfo(project, true); + if (!JavaProject.hasJavaNature(project)) + return; // ignore + JavaModelManager.PerProjectInfo perProjectInfo = JavaModelManager + .getJavaModelManager().getPerProjectInfo(project, true); perProjectInfo.preferences = preferences; } /** * @see IJavaProject */ - public void setRawClasspath( - IClasspathEntry[] entries, - IPath outputLocation, - IProgressMonitor monitor) - throws JavaModelException { - - setRawClasspath( - entries, - outputLocation, - monitor, - true, // canChangeResource (as per API contract) - getResolvedClasspath(true), // ignoreUnresolvedVariable - true, // needValidation - true); // need to save - } - - public void setRawClasspath( - IClasspathEntry[] newEntries, - IPath newOutputLocation, - IProgressMonitor monitor, - boolean canChangeResource, - IClasspathEntry[] oldResolvedPath, - boolean needValidation, - boolean needSave) - throws JavaModelException { - - JavaModelManager manager = - (JavaModelManager) JavaModelManager.getJavaModelManager(); + public void setRawClasspath(IClasspathEntry[] entries, + IPath outputLocation, IProgressMonitor monitor) + throws JavaModelException { + + setRawClasspath(entries, outputLocation, monitor, true, // canChangeResource + // (as per API + // contract) + getResolvedClasspath(true), // ignoreUnresolvedVariable + true, // needValidation + true); // need to save + } + + public void setRawClasspath(IClasspathEntry[] newEntries, + IPath newOutputLocation, IProgressMonitor monitor, + boolean canChangeResource, IClasspathEntry[] oldResolvedPath, + boolean needValidation, boolean needSave) throws JavaModelException { + + JavaModelManager manager = (JavaModelManager) JavaModelManager + .getJavaModelManager(); try { IClasspathEntry[] newRawPath = newEntries; - if (newRawPath == null) { //are we already with the default classpath + if (newRawPath == null) { // are we already with the default + // classpath newRawPath = defaultClasspath(); } - SetClasspathOperation op = - new SetClasspathOperation( - this, - oldResolvedPath, - newRawPath, - newOutputLocation, - canChangeResource, - needValidation, - needSave); + SetClasspathOperation op = new SetClasspathOperation(this, + oldResolvedPath, newRawPath, newOutputLocation, + canChangeResource, needValidation, needSave); runOperation(op, monitor); - + } catch (JavaModelException e) { manager.flush(); throw e; @@ -2732,63 +2983,63 @@ public class JavaProject /** * @see IJavaProject */ - public void setRawClasspath( - IClasspathEntry[] entries, - IProgressMonitor monitor) - throws JavaModelException { - - setRawClasspath( - entries, - SetClasspathOperation.ReuseOutputLocation, - monitor, - true, // canChangeResource (as per API contract) - getResolvedClasspath(true), // ignoreUnresolvedVariable - true, // needValidation - true); // need to save - } - - /** - * NOTE: null specifies default classpath, and an empty - * array specifies an empty classpath. - * - * @exception NotPresentException if this project does not exist. - */ -// protected void setRawClasspath0(IClasspathEntry[] rawEntries) -// throws JavaModelException { -// -// JavaModelManager.PerProjectInfo info = JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(project); -// -// synchronized (info) { -// if (rawEntries != null) { -// info.classpath = rawEntries; -// } -// -// // clear cache of resolved classpath -// info.lastResolvedClasspath = null; -// info.resolvedPathToRawEntries = null; -// } -// } - - /** - * Record a shared persistent property onto a project. - * Note that it is orthogonal to IResource persistent properties, and client code has to decide - * which form of storage to use appropriately. Shared properties produce real resource files which - * can be shared through a VCM onto a server. Persistent properties are not shareable. + public void setRawClasspath(IClasspathEntry[] entries, + IProgressMonitor monitor) throws JavaModelException { + + setRawClasspath(entries, SetClasspathOperation.ReuseOutputLocation, + monitor, true, // canChangeResource (as per API contract) + getResolvedClasspath(true), // ignoreUnresolvedVariable + true, // needValidation + true); // need to save + } + + /** + * NOTE: null specifies default classpath, and an empty array + * specifies an empty classpath. * - * shared properties end up in resource files, and thus cannot be modified during - * delta notifications (a CoreException would then be thrown). + * @exception NotPresentException + * if this project does not exist. + */ + // protected void setRawClasspath0(IClasspathEntry[] rawEntries) + // throws JavaModelException { + // + // JavaModelManager.PerProjectInfo info = + // JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(project); + // + // synchronized (info) { + // if (rawEntries != null) { + // info.classpath = rawEntries; + // } + // + // // clear cache of resolved classpath + // info.lastResolvedClasspath = null; + // info.resolvedPathToRawEntries = null; + // } + // } + /** + * Record a shared persistent property onto a project. Note that it is + * orthogonal to IResource persistent properties, and client code has to + * decide which form of storage to use appropriately. Shared properties + * produce real resource files which can be shared through a VCM onto a + * server. Persistent properties are not shareable. + * + * shared properties end up in resource files, and thus cannot be modified + * during delta notifications (a CoreException would then be thrown). * * @see JavaProject#getSharedProperty(String key) */ - public void setSharedProperty(String key, String value) throws CoreException { + public void setSharedProperty(String key, String value) + throws CoreException { IFile rscFile = getProject().getFile(key); InputStream inputStream = new ByteArrayInputStream(value.getBytes()); // update the resource content if (rscFile.exists()) { if (rscFile.isReadOnly()) { - // provide opportunity to checkout read-only .classpath file (23984) - ResourcesPlugin.getWorkspace().validateEdit(new IFile[]{rscFile}, null); + // provide opportunity to checkout read-only .classpath file + // (23984) + ResourcesPlugin.getWorkspace().validateEdit( + new IFile[] { rscFile }, null); } rscFile.setContents(inputStream, IResource.FORCE, null); } else { @@ -2801,7 +3052,7 @@ public class JavaProject */ public static void updateAllCycleMarkers() throws JavaModelException { - //long start = System.currentTimeMillis(); + // long start = System.currentTimeMillis(); JavaModelManager manager = JavaModelManager.getJavaModelManager(); IJavaProject[] projects = manager.getJavaModel().getJavaProjects(); @@ -2810,150 +3061,171 @@ public class JavaProject HashSet cycleParticipants = new HashSet(); HashSet traversed = new HashSet(); int length = projects.length; - + // compute cycle participants ArrayList prereqChain = new ArrayList(); - for (int i = 0; i < length; i++){ - JavaProject project = (JavaProject)projects[i]; - if (!traversed.contains(project.getPath())){ + for (int i = 0; i < length; i++) { + JavaProject project = (JavaProject) projects[i]; + if (!traversed.contains(project.getPath())) { prereqChain.clear(); - project.updateCycleParticipants(null, prereqChain, cycleParticipants, workspaceRoot, traversed); + project.updateCycleParticipants(null, prereqChain, + cycleParticipants, workspaceRoot, traversed); } } - //System.out.println("updateAllCycleMarkers: " + (System.currentTimeMillis() - start) + " ms"); + // System.out.println("updateAllCycleMarkers: " + + // (System.currentTimeMillis() - start) + " ms"); + + for (int i = 0; i < length; i++) { + JavaProject project = (JavaProject) projects[i]; - for (int i = 0; i < length; i++){ - JavaProject project = (JavaProject)projects[i]; - - if (cycleParticipants.contains(project.getPath())){ + if (cycleParticipants.contains(project.getPath())) { IMarker cycleMarker = project.getCycleMarker(); - String circularCPOption = project.getOption(JavaCore.CORE_CIRCULAR_CLASSPATH, true); - int circularCPSeverity = JavaCore.ERROR.equals(circularCPOption) ? IMarker.SEVERITY_ERROR : IMarker.SEVERITY_WARNING; + String circularCPOption = project.getOption( + JavaCore.CORE_CIRCULAR_CLASSPATH, true); + int circularCPSeverity = JavaCore.ERROR + .equals(circularCPOption) ? IMarker.SEVERITY_ERROR + : IMarker.SEVERITY_WARNING; if (cycleMarker != null) { // update existing cycle marker if needed try { - int existingSeverity = ((Integer)cycleMarker.getAttribute(IMarker.SEVERITY)).intValue(); + int existingSeverity = ((Integer) cycleMarker + .getAttribute(IMarker.SEVERITY)).intValue(); if (existingSeverity != circularCPSeverity) { - cycleMarker.setAttribute(IMarker.SEVERITY, circularCPSeverity); + cycleMarker.setAttribute(IMarker.SEVERITY, + circularCPSeverity); } } catch (CoreException e) { throw new JavaModelException(e); } } else { // create new marker - project.createClasspathProblemMarker( - new JavaModelStatus(IJavaModelStatusConstants.CLASSPATH_CYCLE, project)); + project + .createClasspathProblemMarker(new JavaModelStatus( + IJavaModelStatusConstants.CLASSPATH_CYCLE, + project)); } } else { project.flushClasspathProblemMarkers(true, false); - } + } } } /** - * If a cycle is detected, then cycleParticipants contains all the paths of projects involved in this cycle (directly and indirectly), - * no cycle if the set is empty (and started empty) + * If a cycle is detected, then cycleParticipants contains all the paths of + * projects involved in this cycle (directly and indirectly), no cycle if + * the set is empty (and started empty) */ - public void updateCycleParticipants( - IClasspathEntry[] preferredClasspath, - ArrayList prereqChain, - HashSet cycleParticipants, - IWorkspaceRoot workspaceRoot, - HashSet traversed){ + public void updateCycleParticipants(IClasspathEntry[] preferredClasspath, + ArrayList prereqChain, HashSet cycleParticipants, + IWorkspaceRoot workspaceRoot, HashSet traversed) { IPath path = this.getPath(); prereqChain.add(path); traversed.add(path); try { - IClasspathEntry[] classpath = preferredClasspath == null ? getResolvedClasspath(true) : preferredClasspath; + IClasspathEntry[] classpath = preferredClasspath == null ? getResolvedClasspath(true) + : preferredClasspath; for (int i = 0, length = classpath.length; i < length; i++) { IClasspathEntry entry = classpath[i]; - - if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT){ + + if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) { IPath prereqProjectPath = entry.getPath(); - int index = cycleParticipants.contains(prereqProjectPath) ? 0 : prereqChain.indexOf(prereqProjectPath); + int index = cycleParticipants.contains(prereqProjectPath) ? 0 + : prereqChain.indexOf(prereqProjectPath); if (index >= 0) { // refer to cycle, or in cycle itself for (int size = prereqChain.size(); index < size; index++) { - cycleParticipants.add(prereqChain.get(index)); + cycleParticipants.add(prereqChain.get(index)); } } else { if (!traversed.contains(prereqProjectPath)) { - IResource member = workspaceRoot.findMember(prereqProjectPath); - if (member != null && member.getType() == IResource.PROJECT){ - JavaProject project = (JavaProject)JavaCore.create((IProject)member); - project.updateCycleParticipants(null, prereqChain, cycleParticipants, workspaceRoot, traversed); + IResource member = workspaceRoot + .findMember(prereqProjectPath); + if (member != null + && member.getType() == IResource.PROJECT) { + JavaProject project = (JavaProject) JavaCore + .create((IProject) member); + project.updateCycleParticipants(null, + prereqChain, cycleParticipants, + workspaceRoot, traversed); } } } } } - } catch(JavaModelException e){ + } catch (JavaModelException e) { } prereqChain.remove(path); } + /** - * Reset the collection of package fragment roots (local ones) - only if opened. - * Need to check *all* package fragment roots in order to reset NameLookup + * Reset the collection of package fragment roots (local ones) - only if + * opened. Need to check *all* package fragment roots in order to reset + * NameLookup */ - public void updatePackageFragmentRoots(){ - - if (this.isOpen()) { + public void updatePackageFragmentRoots() { + + if (this.isOpen()) { + try { + JavaProjectElementInfo info = getJavaProjectElementInfo(); + + IClasspathEntry[] classpath = getResolvedClasspath(true); + // NameLookup lookup = info.getNameLookup(); + // if (lookup != null){ + // IPackageFragmentRoot[] oldRoots = + // lookup.fPackageFragmentRoots; + // IPackageFragmentRoot[] newRoots = + // computePackageFragmentRoots(classpath, true); + // checkIdentical: { // compare all pkg fragment root lists + // if (oldRoots.length == newRoots.length){ + // for (int i = 0, length = oldRoots.length; i < length; i++){ + // if (!oldRoots[i].equals(newRoots[i])){ + // break checkIdentical; + // } + // } + // return; // no need to update + // } + // } + // info.setNameLookup(null); // discard name lookup (hold onto + // roots) + // } + info.setNonJavaResources(null); + info.setChildren(computePackageFragmentRoots(classpath, false)); + + } catch (JavaModelException e) { try { - JavaProjectElementInfo info = getJavaProjectElementInfo(); - - IClasspathEntry[] classpath = getResolvedClasspath(true); -// NameLookup lookup = info.getNameLookup(); -// if (lookup != null){ -// IPackageFragmentRoot[] oldRoots = lookup.fPackageFragmentRoots; -// IPackageFragmentRoot[] newRoots = computePackageFragmentRoots(classpath, true); -// checkIdentical: { // compare all pkg fragment root lists -// if (oldRoots.length == newRoots.length){ -// for (int i = 0, length = oldRoots.length; i < length; i++){ -// if (!oldRoots[i].equals(newRoots[i])){ -// break checkIdentical; -// } -// } -// return; // no need to update -// } -// } -// info.setNameLookup(null); // discard name lookup (hold onto roots) -// } - info.setNonJavaResources(null); - info.setChildren( - computePackageFragmentRoots(classpath, false)); - - } catch(JavaModelException e){ - try { - close(); // could not do better - } catch(JavaModelException ex){ - } + close(); // could not do better + } catch (JavaModelException ex) { } } + } } - public void removeLoadPathEntry(IProject anotherPHPProject) { - Iterator entries = getLoadPathEntries().iterator(); - while (entries.hasNext()) { - LoadPathEntry entry = (LoadPathEntry) entries.next(); - if (entry.getType() == LoadPathEntry.TYPE_PROJECT && entry.getProject().getName().equals(anotherPHPProject.getName())) { - getLoadPathEntries().remove(entry); - fScratched = true; - break; - } + public void removeLoadPathEntry(IProject anotherPHPProject) { + Iterator entries = getLoadPathEntries().iterator(); + while (entries.hasNext()) { + LoadPathEntry entry = (LoadPathEntry) entries.next(); + if (entry.getType() == LoadPathEntry.TYPE_PROJECT + && entry.getProject().getName().equals( + anotherPHPProject.getName())) { + getLoadPathEntries().remove(entry); + fScratched = true; + break; } } + } - public void save() throws CoreException { - if (fScratched) { - InputStream xmlPath = new ByteArrayInputStream(getLoadPathXML().getBytes()); - IFile loadPathsFile = getLoadPathEntriesFile(); - if (!loadPathsFile.exists()) - loadPathsFile.create(xmlPath, true, null); - else - loadPathsFile.setContents(xmlPath, true, false, null); + public void save() throws CoreException { + if (fScratched) { + InputStream xmlPath = new ByteArrayInputStream(getLoadPathXML() + .getBytes()); + IFile loadPathsFile = getLoadPathEntriesFile(); + if (!loadPathsFile.exists()) + loadPathsFile.create(xmlPath, true, null); + else + loadPathsFile.setContents(xmlPath, true, false, null); - fScratched = false; - } + fScratched = false; } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaProjectElementInfo.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaProjectElementInfo.java index 7da81a6..9d5ab81 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaProjectElementInfo.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaProjectElementInfo.java @@ -20,14 +20,16 @@ import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; -/** +/** * Info for IJavaProject. *

                                      - * Note: getChildren() returns all of the IPackageFragmentRoots - * specified on the classpath for the project. This can include roots external to the - * project. See JavaProject#getAllPackageFragmentRoots() and - * JavaProject#getPackageFragmentRoots(). To get only the IPackageFragmentRoots - * that are internal to the project, use JavaProject#getChildren(). + * Note: getChildren() returns all of the + * IPackageFragmentRoots specified on the classpath for the + * project. This can include roots external to the project. See + * JavaProject#getAllPackageFragmentRoots() and + * JavaProject#getPackageFragmentRoots(). To get only the + * IPackageFragmentRoots that are internal to the project, use + * JavaProject#getChildren(). */ /* package */ @@ -39,11 +41,10 @@ class JavaProjectElementInfo extends OpenableElementInfo { protected NameLookup fNameLookup = null; /** - * The searchable builder environment facility used - * with this project (doubles as the builder environment). + * The searchable builder environment facility used with this project + * (doubles as the builder environment). */ -// protected SearchableEnvironment fSearchableEnvironment = null; - + // protected SearchableEnvironment fSearchableEnvironment = null; /** * A array with all the non-java resources contained by this PackageFragment */ @@ -55,12 +56,12 @@ class JavaProjectElementInfo extends OpenableElementInfo { public JavaProjectElementInfo() { fNonJavaResources = null; } - + /** * Compute the non-java resources contained in this java project. */ private Object[] computeNonJavaResources(JavaProject project) { - + // determine if src == project and/or if bin == project IPath projectPath = project.getProject().getFullPath(); boolean srcIsProject = false; @@ -69,12 +70,14 @@ class JavaProjectElementInfo extends OpenableElementInfo { IClasspathEntry[] classpath = null; IPath projectOutput = null; try { - classpath = project.getResolvedClasspath(true/*ignore unresolved variable*/); + classpath = project + .getResolvedClasspath(true/* ignore unresolved variable */); for (int i = 0; i < classpath.length; i++) { IClasspathEntry entry = classpath[i]; if (projectPath.equals(entry.getPath())) { srcIsProject = true; - exclusionPatterns = ((ClasspathEntry)entry).fullExclusionPatternChars(); + exclusionPatterns = ((ClasspathEntry) entry) + .fullExclusionPatternChars(); break; } } @@ -87,68 +90,76 @@ class JavaProjectElementInfo extends OpenableElementInfo { Object[] nonJavaResources = new IResource[5]; int nonJavaResourcesCounter = 0; try { - IResource[] members = ((IContainer) project.getResource()).members(); + IResource[] members = ((IContainer) project.getResource()) + .members(); for (int i = 0, max = members.length; i < max; i++) { IResource res = members[i]; switch (res.getType()) { - case IResource.FILE : - IPath resFullPath = res.getFullPath(); - String resName = res.getName(); - - // ignore a jar file on the classpath -// if (ProjectPrefUtil.isArchiveFileName(resName) && this.isClasspathEntryOrOutputLocation(resFullPath, classpath, projectOutput)) { -// break; -// } - // ignore .java file if src == project - if (srcIsProject -// && ProjectPrefUtil.isValidCompilationUnitName(resName) + case IResource.FILE: + IPath resFullPath = res.getFullPath(); + String resName = res.getName(); + + // ignore a jar file on the classpath + // if (ProjectPrefUtil.isArchiveFileName(resName) && + // this.isClasspathEntryOrOutputLocation(resFullPath, + // classpath, projectOutput)) { + // break; + // } + // ignore .java file if src == project + if (srcIsProject + // && ProjectPrefUtil.isValidCompilationUnitName(resName) && !Util.isExcluded(res, exclusionPatterns)) { - break; - } - // ignore .class file if bin == project -// if (binIsProject && ProjectPrefUtil.isValidClassFileName(resName)) { -// break; -// } - // else add non java resource - if (nonJavaResources.length == nonJavaResourcesCounter) { - // resize - System.arraycopy( - nonJavaResources, - 0, - (nonJavaResources = new IResource[nonJavaResourcesCounter * 2]), - 0, - nonJavaResourcesCounter); - } - nonJavaResources[nonJavaResourcesCounter++] = res; break; - case IResource.FOLDER : - resFullPath = res.getFullPath(); - - // ignore non-excluded folders on the classpath or that correspond to an output location - if ((srcIsProject && !Util.isExcluded(res, exclusionPatterns) && Util.isValidFolderNameForPackage(res.getName())) - || this.isClasspathEntryOrOutputLocation(resFullPath, classpath, projectOutput)) { - break; - } - // else add non java resource - if (nonJavaResources.length == nonJavaResourcesCounter) { - // resize - System.arraycopy( - nonJavaResources, - 0, - (nonJavaResources = new IResource[nonJavaResourcesCounter * 2]), - 0, - nonJavaResourcesCounter); - } - nonJavaResources[nonJavaResourcesCounter++] = res; + } + // ignore .class file if bin == project + // if (binIsProject && + // ProjectPrefUtil.isValidClassFileName(resName)) { + // break; + // } + // else add non java resource + if (nonJavaResources.length == nonJavaResourcesCounter) { + // resize + System + .arraycopy( + nonJavaResources, + 0, + (nonJavaResources = new IResource[nonJavaResourcesCounter * 2]), + 0, nonJavaResourcesCounter); + } + nonJavaResources[nonJavaResourcesCounter++] = res; + break; + case IResource.FOLDER: + resFullPath = res.getFullPath(); + + // ignore non-excluded folders on the classpath or that + // correspond to an output location + if ((srcIsProject + && !Util.isExcluded(res, exclusionPatterns) && Util + .isValidFolderNameForPackage(res.getName())) + || this.isClasspathEntryOrOutputLocation( + resFullPath, classpath, projectOutput)) { + break; + } + // else add non java resource + if (nonJavaResources.length == nonJavaResourcesCounter) { + // resize + System + .arraycopy( + nonJavaResources, + 0, + (nonJavaResources = new IResource[nonJavaResourcesCounter * 2]), + 0, nonJavaResourcesCounter); + } + nonJavaResources[nonJavaResourcesCounter++] = res; } } if (nonJavaResources.length != nonJavaResourcesCounter) { - System.arraycopy( - nonJavaResources, - 0, - (nonJavaResources = new IResource[nonJavaResourcesCounter]), - 0, - nonJavaResourcesCounter); + System + .arraycopy( + nonJavaResources, + 0, + (nonJavaResources = new IResource[nonJavaResourcesCounter]), + 0, nonJavaResourcesCounter); } } catch (CoreException e) { nonJavaResources = NO_NON_JAVA_RESOURCES; @@ -156,7 +167,7 @@ class JavaProjectElementInfo extends OpenableElementInfo { } return nonJavaResources; } - + /** * @see IJavaProject */ @@ -164,7 +175,7 @@ class JavaProjectElementInfo extends OpenableElementInfo { return fNameLookup; } - + /** * Returns an array of non-java resources contained in the receiver. */ @@ -177,41 +188,45 @@ class JavaProjectElementInfo extends OpenableElementInfo { } return nonJavaResources; } - + /** - * @see IJavaProject + * @see IJavaProject */ -// protected SearchableEnvironment getSearchableEnvironment() { -// -// return fSearchableEnvironment; -// } + // protected SearchableEnvironment getSearchableEnvironment() { + // + // return fSearchableEnvironment; + // } /* - * Returns whether the given path is a classpath entry or an output location. + * Returns whether the given path is a classpath entry or an output + * location. */ - private boolean isClasspathEntryOrOutputLocation(IPath path, IClasspathEntry[] resolvedClasspath, IPath projectOutput) { - if (projectOutput.equals(path)) return true; + private boolean isClasspathEntryOrOutputLocation(IPath path, + IClasspathEntry[] resolvedClasspath, IPath projectOutput) { + if (projectOutput.equals(path)) + return true; for (int i = 0, length = resolvedClasspath.length; i < length; i++) { IClasspathEntry entry = resolvedClasspath[i]; if (entry.getPath().equals(path)) { return true; } IPath output; - if ((output = entry.getOutputLocation()) != null && output.equals(path)) { + if ((output = entry.getOutputLocation()) != null + && output.equals(path)) { return true; } } return false; } - + protected void setNameLookup(NameLookup newNameLookup) { fNameLookup = newNameLookup; // Reinitialize the searchable name environment since it caches // the name lookup. -// fSearchableEnvironment = null; + // fSearchableEnvironment = null; } - + /** * Set the fNonJavaResources to res value */ @@ -219,9 +234,10 @@ class JavaProjectElementInfo extends OpenableElementInfo { fNonJavaResources = resources; } - -// protected void setSearchableEnvironment(SearchableEnvironment newSearchableEnvironment) { -// -// fSearchableEnvironment = newSearchableEnvironment; -// } + + // protected void setSearchableEnvironment(SearchableEnvironment + // newSearchableEnvironment) { + // + // fSearchableEnvironment = newSearchableEnvironment; + // } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/LRUCacheEnumerator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/LRUCacheEnumerator.java index 8a04b28..1aa66be 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/LRUCacheEnumerator.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/LRUCacheEnumerator.java @@ -13,29 +13,28 @@ package net.sourceforge.phpdt.internal.core; import java.util.Enumeration; /** - * The LRUCacheEnumerator returns its elements in - * the order they are found in the LRUCache, with the - * most recent elements first. - * - * Once the enumerator is created, elements which are later added - * to the cache are not returned by the enumerator. However, - * elements returned from the enumerator could have been closed - * by the cache. + * The LRUCacheEnumerator returns its elements in the order they + * are found in the LRUCache, with the most recent elements + * first. + * + * Once the enumerator is created, elements which are later added to the cache + * are not returned by the enumerator. However, elements returned from the + * enumerator could have been closed by the cache. */ public class LRUCacheEnumerator implements Enumeration { /** - * Current element; + * Current element; */ protected LRUEnumeratorElement fElementQueue; public static class LRUEnumeratorElement { /** - * Value returned by nextElement(); + * Value returned by nextElement(); */ public Object fValue; - + /** - * Next element + * Next element */ public LRUEnumeratorElement fNext; @@ -46,24 +45,28 @@ public class LRUCacheEnumerator implements Enumeration { fValue = value; } } -/** - * Creates a CacheEnumerator on the list of LRUEnumeratorElements. - */ -public LRUCacheEnumerator(LRUEnumeratorElement firstElement) { - fElementQueue = firstElement; -} -/** - * Returns true if more elements exist. - */ -public boolean hasMoreElements() { - return fElementQueue != null; -} -/** - * Returns the next element. - */ -public Object nextElement() { - Object temp = fElementQueue.fValue; - fElementQueue = fElementQueue.fNext; - return temp; -} + + /** + * Creates a CacheEnumerator on the list of + * LRUEnumeratorElements. + */ + public LRUCacheEnumerator(LRUEnumeratorElement firstElement) { + fElementQueue = firstElement; + } + + /** + * Returns true if more elements exist. + */ + public boolean hasMoreElements() { + return fElementQueue != null; + } + + /** + * Returns the next element. + */ + public Object nextElement() { + Object temp = fElementQueue.fValue; + fElementQueue = fElementQueue.fNext; + return temp; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/LocalVariable.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/LocalVariable.java index 63312b5..40e31ec 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/LocalVariable.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/LocalVariable.java @@ -28,22 +28,18 @@ import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; - public class LocalVariable extends JavaElement implements ILocalVariable { public int declarationSourceStart, declarationSourceEnd; + public int nameStart, nameEnd; + String typeSignature; - - public LocalVariable( - JavaElement parent, - String name, - int declarationSourceStart, - int declarationSourceEnd, - int nameStart, - int nameEnd, - String typeSignature) { - + + public LocalVariable(JavaElement parent, String name, + int declarationSourceStart, int declarationSourceEnd, + int nameStart, int nameEnd, String typeSignature) { + super(parent, name); this.declarationSourceStart = declarationSourceStart; this.declarationSourceEnd = declarationSourceEnd; @@ -62,28 +58,30 @@ public class LocalVariable extends JavaElement implements ILocalVariable { } public boolean equals(Object o) { - if (!(o instanceof LocalVariable)) return false; - LocalVariable other = (LocalVariable)o; - return - this.declarationSourceStart == other.declarationSourceStart - && this.declarationSourceEnd == other.declarationSourceEnd - && this.nameStart == other.nameStart - && this.nameEnd == other.nameEnd - && super.equals(o); - } - + if (!(o instanceof LocalVariable)) + return false; + LocalVariable other = (LocalVariable) o; + return this.declarationSourceStart == other.declarationSourceStart + && this.declarationSourceEnd == other.declarationSourceEnd + && this.nameStart == other.nameStart + && this.nameEnd == other.nameEnd && super.equals(o); + } + public boolean exists() { - return this.parent.exists(); // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=46192 + return this.parent.exists(); // see + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=46192 } - protected void generateInfos(Object info, HashMap newElements, IProgressMonitor pm) { + protected void generateInfos(Object info, HashMap newElements, + IProgressMonitor pm) { // a local variable has no info } - public IJavaElement getHandleFromMemento(String token, MementoTokenizer memento, WorkingCopyOwner owner) { + public IJavaElement getHandleFromMemento(String token, + MementoTokenizer memento, WorkingCopyOwner owner) { switch (token.charAt(0)) { - case JEM_COUNT: - return getHandleUpdatingCountFromMemento(memento, owner); + case JEM_COUNT: + return getHandleUpdatingCountFromMemento(memento, owner); } return this; } @@ -91,8 +89,9 @@ public class LocalVariable extends JavaElement implements ILocalVariable { /* * @see JavaElement#getHandleMemento() */ - public String getHandleMemento(){ - StringBuffer buff= new StringBuffer(((JavaElement)getParent()).getHandleMemento()); + public String getHandleMemento() { + StringBuffer buff = new StringBuffer(((JavaElement) getParent()) + .getHandleMemento()); buff.append(getHandleMementoDelimiter()); buff.append(this.name); buff.append(JEM_COUNT); @@ -125,9 +124,10 @@ public class LocalVariable extends JavaElement implements ILocalVariable { } public ISourceRange getNameRange() { - return new SourceRange(this.nameStart, this.nameEnd-this.nameStart+1); + return new SourceRange(this.nameStart, this.nameEnd - this.nameStart + + 1); } - + public IPath getPath() { return this.parent.getPath(); } @@ -148,23 +148,24 @@ public class LocalVariable extends JavaElement implements ILocalVariable { ISourceRange range = getSourceRange(); int offset = range.getOffset(); int length = range.getLength(); - if (offset == -1 || length == 0 ) { + if (offset == -1 || length == 0) { return null; } try { return buffer.getText(offset, length); - } catch(RuntimeException e) { + } catch (RuntimeException e) { return null; } } - + /** * @see ISourceReference */ public ISourceRange getSourceRange() { - return new SourceRange(this.declarationSourceStart, this.declarationSourceEnd-this.declarationSourceStart+1); + return new SourceRange(this.declarationSourceStart, + this.declarationSourceEnd - this.declarationSourceStart + 1); } - + public String getTypeSignature() { return this.typeSignature; } @@ -176,11 +177,11 @@ public class LocalVariable extends JavaElement implements ILocalVariable { public int hashCode() { return Util.combineHashCodes(this.parent.hashCode(), this.nameStart); } - + public boolean isStructureKnown() throws JavaModelException { - return true; - } - + return true; + } + protected void toStringInfo(int tab, StringBuffer buffer, Object info) { buffer.append(this.tabString(tab)); if (info != NO_INFO) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Member.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Member.java index e98ed5b..46c5e93 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Member.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Member.java @@ -22,7 +22,6 @@ import net.sourceforge.phpdt.core.JavaModelException; import net.sourceforge.phpdt.core.Signature; import net.sourceforge.phpdt.core.jdom.IDOMNode; - /** * @see IMember */ @@ -31,139 +30,143 @@ public abstract class Member extends SourceRefElement implements IMember { protected Member(JavaElement parent, String name) { super(parent, name); } -protected boolean areSimilarMethods( - String name1, String[] params1, - String name2, String[] params2, - String[] simpleNames1) { - - if (name1.equals(name2)) { - int params1Length = params1.length; - if (params1Length == params2.length) { - for (int i = 0; i < params1Length; i++) { - String simpleName1 = - simpleNames1 == null ? - Signature.getSimpleName(Signature.toString(params1[i])) : - simpleNames1[i]; - String simpleName2 = Signature.getSimpleName(Signature.toString(params2[i])); - if (!simpleName1.equals(simpleName2)) { - return false; + + protected boolean areSimilarMethods(String name1, String[] params1, + String name2, String[] params2, String[] simpleNames1) { + + if (name1.equals(name2)) { + int params1Length = params1.length; + if (params1Length == params2.length) { + for (int i = 0; i < params1Length; i++) { + String simpleName1 = simpleNames1 == null ? Signature + .getSimpleName(Signature.toString(params1[i])) + : simpleNames1[i]; + String simpleName2 = Signature.getSimpleName(Signature + .toString(params2[i])); + if (!simpleName1.equals(simpleName2)) { + return false; + } } + return true; } - return true; } + return false; } - return false; -} -/** - * Converts a field constant from the compiler's representation - * to the Java Model constant representation (Number or String). - */ -//protected static Object convertConstant(Constant constant) { -// if (constant == null) -// return null; -// if (constant == Constant.NotAConstant) { -// return null; -// } -// switch (constant.typeID()) { -// case TypeIds.T_boolean : -// return constant.booleanValue() ? Boolean.TRUE : Boolean.FALSE; -// case TypeIds.T_byte : -// return new Byte(constant.byteValue()); -// case TypeIds.T_char : -// return new Character(constant.charValue()); -// case TypeIds.T_double : -// return new Double(constant.doubleValue()); -// case TypeIds.T_float : -// return new Float(constant.floatValue()); -// case TypeIds.T_int : -// return new Integer(constant.intValue()); -// case TypeIds.T_long : -// return new Long(constant.longValue()); -// case TypeIds.T_short : -// return new Short(constant.shortValue()); -// case TypeIds.T_String : -// return constant.stringValue(); -// default : -// return null; -// } -//} -/** - * @see JavaElement#equalsDOMNode - */ -protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException { - return getElementName().equals(node.getName()); -} -/* - * Helper method for SourceType.findMethods and BinaryType.findMethods - */ -protected IMethod[] findMethods(IMethod method, IMethod[] methods) { - String elementName = method.getElementName(); - String[] parameters = method.getParameterTypes(); - int paramLength = parameters.length; - String[] simpleNames = new String[paramLength]; - for (int i = 0; i < paramLength; i++) { - simpleNames[i] = Signature.getSimpleName(Signature.toString(parameters[i])); + + /** + * Converts a field constant from the compiler's representation to the Java + * Model constant representation (Number or String). + */ + // protected static Object convertConstant(Constant constant) { + // if (constant == null) + // return null; + // if (constant == Constant.NotAConstant) { + // return null; + // } + // switch (constant.typeID()) { + // case TypeIds.T_boolean : + // return constant.booleanValue() ? Boolean.TRUE : Boolean.FALSE; + // case TypeIds.T_byte : + // return new Byte(constant.byteValue()); + // case TypeIds.T_char : + // return new Character(constant.charValue()); + // case TypeIds.T_double : + // return new Double(constant.doubleValue()); + // case TypeIds.T_float : + // return new Float(constant.floatValue()); + // case TypeIds.T_int : + // return new Integer(constant.intValue()); + // case TypeIds.T_long : + // return new Long(constant.longValue()); + // case TypeIds.T_short : + // return new Short(constant.shortValue()); + // case TypeIds.T_String : + // return constant.stringValue(); + // default : + // return null; + // } + // } + /** + * @see JavaElement#equalsDOMNode + */ + protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException { + return getElementName().equals(node.getName()); } - ArrayList list = new ArrayList(); - next: for (int i = 0, length = methods.length; i < length; i++) { - IMethod existingMethod = methods[i]; - if (this.areSimilarMethods( - elementName, - parameters, - existingMethod.getElementName(), - existingMethod.getParameterTypes(), - simpleNames)) { - list.add(existingMethod); + + /* + * Helper method for SourceType.findMethods and BinaryType.findMethods + */ + protected IMethod[] findMethods(IMethod method, IMethod[] methods) { + String elementName = method.getElementName(); + String[] parameters = method.getParameterTypes(); + int paramLength = parameters.length; + String[] simpleNames = new String[paramLength]; + for (int i = 0; i < paramLength; i++) { + simpleNames[i] = Signature.getSimpleName(Signature + .toString(parameters[i])); + } + ArrayList list = new ArrayList(); + next: for (int i = 0, length = methods.length; i < length; i++) { + IMethod existingMethod = methods[i]; + if (this.areSimilarMethods(elementName, parameters, existingMethod + .getElementName(), existingMethod.getParameterTypes(), + simpleNames)) { + list.add(existingMethod); + } + } + int size = list.size(); + if (size == 0) { + return null; + } else { + IMethod[] result = new IMethod[size]; + list.toArray(result); + return result; } } - int size = list.size(); - if (size == 0) { + + /** + * @see IMember + */ + // public IClassFile getClassFile() { + // return ((JavaElement)getParent()).getClassFile(); + // } + /** + * @see IMember + */ + public IType getDeclaringType() { + JavaElement parentElement = (JavaElement) getParent(); + if (parentElement.getElementType() == TYPE) { + return (IType) parentElement; + } return null; - } else { - IMethod[] result = new IMethod[size]; - list.toArray(result); - return result; } -} -/** - * @see IMember - */ -//public IClassFile getClassFile() { -// return ((JavaElement)getParent()).getClassFile(); -//} -/** - * @see IMember - */ -public IType getDeclaringType() { - JavaElement parentElement = (JavaElement)getParent(); - if (parentElement.getElementType() == TYPE) { - return (IType) parentElement; + + /** + * @see IMember + */ + public int getFlags() throws JavaModelException { + MemberElementInfo info = (MemberElementInfo) getElementInfo(); + return info.getModifiers(); } - return null; -} -/** - * @see IMember - */ -public int getFlags() throws JavaModelException { - MemberElementInfo info = (MemberElementInfo) getElementInfo(); - return info.getModifiers(); -} -/** - * @see JavaElement#getHandleMemento() - */ -protected char getHandleMementoDelimiter() { - return JavaElement.JEM_TYPE; -} -/* - * Returns the outermost context defining a local element. Per construction, it can only be a - * method/field/initializarer member; thus, returns null if this member is already a top-level type or member type. - * e.g for X.java/X/Y/foo()/Z/bar()/T, it will return X.java/X/Y/foo() - */ -public Member getOuterMostLocalContext() { - IJavaElement current = this; - Member lastLocalContext = null; - parentLoop: while (true) { - switch (current.getElementType()) { + + /** + * @see JavaElement#getHandleMemento() + */ + protected char getHandleMementoDelimiter() { + return JavaElement.JEM_TYPE; + } + + /* + * Returns the outermost context defining a local element. Per construction, + * it can only be a method/field/initializarer member; thus, returns null if + * this member is already a top-level type or member type. e.g for + * X.java/X/Y/foo()/Z/bar()/T, it will return X.java/X/Y/foo() + */ + public Member getOuterMostLocalContext() { + IJavaElement current = this; + Member lastLocalContext = null; + parentLoop: while (true) { + switch (current.getElementType()) { case CLASS_FILE: case COMPILATION_UNIT: break parentLoop; // done recursing @@ -173,83 +176,94 @@ public Member getOuterMostLocalContext() { case INITIALIZER: case FIELD: case METHOD: - // these elements can define local members + // these elements can define local members lastLocalContext = (Member) current; break; - } - current = current.getParent(); - } - return lastLocalContext; -} -/** - * @see IMember - */ -public ISourceRange getNameRange() throws JavaModelException { - MemberElementInfo info= (MemberElementInfo)getElementInfo(); - return new SourceRange(info.getNameSourceStart(), info.getNameSourceEnd() - info.getNameSourceStart() + 1); -} -/** - * @see IMember - */ -public IType getType(String typeName, int count) { - if (isBinary()) { - throw new IllegalArgumentException("Not a source member " + toStringWithAncestors()); //$NON-NLS-1$ - } else { - SourceType type = new SourceType(this, typeName); - type.occurrenceCount = count; - return type; + } + current = current.getParent(); + } + return lastLocalContext; } -} -/** - * @see IMember - */ -public boolean isBinary() { - return false; -} -protected boolean isMainMethod(IMethod method) throws JavaModelException { - if ("main".equals(method.getElementName()) && Signature.SIG_VOID.equals(method.getReturnType())) { //$NON-NLS-1$ - int flags= method.getFlags(); - if (Flags.isStatic(flags) && Flags.isPublic(flags)) { - String[] paramTypes= method.getParameterTypes(); - if (paramTypes.length == 1) { - String name= Signature.toString(paramTypes[0]); - return "String[]".equals(Signature.getSimpleName(name)); //$NON-NLS-1$ + + /** + * @see IMember + */ + public ISourceRange getNameRange() throws JavaModelException { + MemberElementInfo info = (MemberElementInfo) getElementInfo(); + return new SourceRange(info.getNameSourceStart(), info + .getNameSourceEnd() + - info.getNameSourceStart() + 1); + } + + /** + * @see IMember + */ + public IType getType(String typeName, int count) { + if (isBinary()) { + throw new IllegalArgumentException( + "Not a source member " + toStringWithAncestors()); //$NON-NLS-1$ + } else { + SourceType type = new SourceType(this, typeName); + type.occurrenceCount = count; + return type; + } + } + + /** + * @see IMember + */ + public boolean isBinary() { + return false; + } + + protected boolean isMainMethod(IMethod method) throws JavaModelException { + if ("main".equals(method.getElementName()) && Signature.SIG_VOID.equals(method.getReturnType())) { //$NON-NLS-1$ + int flags = method.getFlags(); + if (Flags.isStatic(flags) && Flags.isPublic(flags)) { + String[] paramTypes = method.getParameterTypes(); + if (paramTypes.length == 1) { + String name = Signature.toString(paramTypes[0]); + return "String[]".equals(Signature.getSimpleName(name)); //$NON-NLS-1$ + } } } + return false; } - return false; -} -/** - * @see IJavaElement - */ -public boolean isReadOnly() { - return false; //getClassFile() != null; -} -/** - */ -public String readableName() { - - IJavaElement declaringType = getDeclaringType(); - if (declaringType != null) { - String declaringName = ((JavaElement) getDeclaringType()).readableName(); - StringBuffer buffer = new StringBuffer(declaringName); - buffer.append('.'); - buffer.append(this.getElementName()); - return buffer.toString(); - } else { - return super.readableName(); + + /** + * @see IJavaElement + */ + public boolean isReadOnly() { + return false; // getClassFile() != null; } -} -/** - * Updates the name range for this element. - */ -protected void updateNameRange(int nameStart, int nameEnd) { - try { - MemberElementInfo info = (MemberElementInfo) getElementInfo(); - info.setNameSourceStart(nameStart); - info.setNameSourceEnd(nameEnd); - } catch (JavaModelException npe) { - return; + + /** + */ + public String readableName() { + + IJavaElement declaringType = getDeclaringType(); + if (declaringType != null) { + String declaringName = ((JavaElement) getDeclaringType()) + .readableName(); + StringBuffer buffer = new StringBuffer(declaringName); + buffer.append('.'); + buffer.append(this.getElementName()); + return buffer.toString(); + } else { + return super.readableName(); + } + } + + /** + * Updates the name range for this element. + */ + protected void updateNameRange(int nameStart, int nameEnd) { + try { + MemberElementInfo info = (MemberElementInfo) getElementInfo(); + info.setNameSourceStart(nameStart); + info.setNameSourceEnd(nameEnd); + } catch (JavaModelException npe) { + return; + } } -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MemberElementInfo.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MemberElementInfo.java index fe6a5bf..0b78e42 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MemberElementInfo.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MemberElementInfo.java @@ -12,33 +12,32 @@ package net.sourceforge.phpdt.internal.core; import net.sourceforge.phpdt.internal.compiler.env.IConstants; -/** - *Element info for IMember elements. +/** + * Element info for IMember elements. */ -/* package */ abstract class MemberElementInfo extends SourceRefElementInfo { +/* package */abstract class MemberElementInfo extends SourceRefElementInfo { /** * The modifiers associated with this member. - * + * * @see IConstants */ protected int flags; /** - * The start position of this member's name in the its - * openable's buffer. + * The start position of this member's name in the its openable's buffer. */ - protected int nameStart= -1; + protected int nameStart = -1; /** - * The last position of this member's name in the its - * openable's buffer. + * The last position of this member's name in the its openable's buffer. */ - protected int nameEnd= -1; + protected int nameEnd = -1; /** * This member's name */ protected char[] name; + /** * @see net.sourceforge.phpdt.internal.compiler.env.IGenericType#getModifiers() * @see net.sourceforge.phpdt.internal.compiler.env.IGenericMethod#getModifiers() @@ -47,12 +46,14 @@ import net.sourceforge.phpdt.internal.compiler.env.IConstants; public int getModifiers() { return this.flags; } + /** * @see net.sourceforge.phpdt.internal.compiler.env.ISourceType#getName() */ public char[] getName() { return this.name; } + /** * @see net.sourceforge.phpdt.internal.compiler.env.ISourceType#getNameSourceEnd() * @see net.sourceforge.phpdt.internal.compiler.env.ISourceMethod#getNameSourceEnd() @@ -61,6 +62,7 @@ import net.sourceforge.phpdt.internal.compiler.env.IConstants; public int getNameSourceEnd() { return this.nameEnd; } + /** * @see net.sourceforge.phpdt.internal.compiler.env.ISourceType#getNameSourceStart() * @see net.sourceforge.phpdt.internal.compiler.env.ISourceMethod#getNameSourceStart() @@ -69,27 +71,31 @@ import net.sourceforge.phpdt.internal.compiler.env.IConstants; public int getNameSourceStart() { return this.nameStart; } + protected void setFlags(int flags) { this.flags = flags; } + /** * Sets this member's name */ protected void setName(char[] name) { - this.name= name; + this.name = name; } + /** - * Sets the last position of this member's name, relative - * to its openable's source buffer. + * Sets the last position of this member's name, relative to its openable's + * source buffer. */ protected void setNameSourceEnd(int end) { - this.nameEnd= end; + this.nameEnd = end; } + /** - * Sets the start position of this member's name, relative - * to its openable's source buffer. + * Sets the start position of this member's name, relative to its openable's + * source buffer. */ protected void setNameSourceStart(int start) { - this.nameStart= start; + this.nameStart = start; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ModelUpdater.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ModelUpdater.java index 83f09e9..9d3c1bb 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ModelUpdater.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ModelUpdater.java @@ -29,14 +29,15 @@ public class ModelUpdater { HashSet projectsToUpdate = new HashSet(); /** - * Adds the given child handle to its parent's cache of children. + * Adds the given child handle to its parent's cache of children. */ protected void addToParentInfo(Openable child) { Openable parent = (Openable) child.getParent(); if (parent != null && parent.isOpen()) { try { - JavaElementInfo info = (JavaElementInfo)parent.getElementInfo(); + JavaElementInfo info = (JavaElementInfo) parent + .getElementInfo(); info.addChild(child); } catch (JavaModelException e) { // do nothing - we already checked if open @@ -45,7 +46,8 @@ public class ModelUpdater { } /** - * Closes the given element, which removes it from the cache of open elements. + * Closes the given element, which removes it from the cache of open + * elements. */ protected static void close(Openable element) { @@ -57,10 +59,11 @@ public class ModelUpdater { } /** - * Processing for an element that has been added:

                                        + * Processing for an element that has been added: + *
                                          *
                                        • If the element is a project, do nothing, and do not process - * children, as when a project is created it does not yet have any - * natures - specifically a java nature. + * children, as when a project is created it does not yet have any natures - + * specifically a java nature. *
                                        • If the elemet is not a project, process it as added (see * basicElementAdded. *
                                        @@ -76,33 +79,38 @@ public class ModelUpdater { } else { addToParentInfo(element); - // Force the element to be closed as it might have been opened - // before the resource modification came in and it might have a new child + // Force the element to be closed as it might have been opened + // before the resource modification came in and it might have a new + // child // For example, in an IWorkspaceRunnable: // 1. create a package fragment p using a java model operation // 2. open package p // 3. add file X.java in folder p - // When the resource delta comes in, only the addition of p is notified, - // but the package p is already opened, thus its children are not recomputed + // When the resource delta comes in, only the addition of p is + // notified, + // but the package p is already opened, thus its children are not + // recomputed // and it appears empty. close(element); } switch (elementType) { - case IJavaElement.PACKAGE_FRAGMENT_ROOT : - // when a root is added, and is on the classpath, the project must be updated - this.projectsToUpdate.add(element.getJavaProject()); - break; - case IJavaElement.PACKAGE_FRAGMENT : - // get rid of package fragment cache - JavaProject project = (JavaProject) element.getJavaProject(); -// project.resetCaches(); - break; + case IJavaElement.PACKAGE_FRAGMENT_ROOT: + // when a root is added, and is on the classpath, the project must + // be updated + this.projectsToUpdate.add(element.getJavaProject()); + break; + case IJavaElement.PACKAGE_FRAGMENT: + // get rid of package fragment cache + JavaProject project = (JavaProject) element.getJavaProject(); + // project.resetCaches(); + break; } } /** - * Generic processing for elements with changed contents:
                                          + * Generic processing for elements with changed contents: + *
                                            *
                                          • The element is closed such that any subsequent accesses will re-open * the element reflecting its new structure. *
                                          @@ -113,7 +121,8 @@ public class ModelUpdater { } /** - * Generic processing for a removed element:
                                            + * Generic processing for a removed element: + *
                                              *
                                            • Close the element, removing its structure from the cache *
                                            • Remove the element from its parent's cache of children *
                                            • Add a REMOVED entry in the delta @@ -128,34 +137,37 @@ public class ModelUpdater { int elementType = element.getElementType(); switch (elementType) { - case IJavaElement.JAVA_MODEL : -// JavaModelManager.getJavaModelManager().getIndexManager().reset(); - break; - case IJavaElement.JAVA_PROJECT : - JavaModelManager.getJavaModelManager().removePerProjectInfo( + case IJavaElement.JAVA_MODEL: + // JavaModelManager.getJavaModelManager().getIndexManager().reset(); + break; + case IJavaElement.JAVA_PROJECT: + JavaModelManager.getJavaModelManager().removePerProjectInfo( (JavaProject) element); - break; - case IJavaElement.PACKAGE_FRAGMENT_ROOT : - this.projectsToUpdate.add(element.getJavaProject()); - break; - case IJavaElement.PACKAGE_FRAGMENT : - // get rid of package fragment cache - JavaProject project = (JavaProject) element.getJavaProject(); -// project.resetCaches(); - break; + break; + case IJavaElement.PACKAGE_FRAGMENT_ROOT: + this.projectsToUpdate.add(element.getJavaProject()); + break; + case IJavaElement.PACKAGE_FRAGMENT: + // get rid of package fragment cache + JavaProject project = (JavaProject) element.getJavaProject(); + // project.resetCaches(); + break; } } /** - * Converts a IResourceDelta rooted in a Workspace into - * the corresponding set of IJavaElementDelta, rooted in the - * relevant JavaModels. + * Converts a IResourceDelta rooted in a + * Workspace into the corresponding set of + * IJavaElementDelta, rooted in the relevant + * JavaModels. */ public void processJavaDelta(IJavaElementDelta delta) { -// if (DeltaProcessor.VERBOSE){ -// System.out.println("UPDATING Model with Delta: ["+Thread.currentThread()+":" + delta + "]:");//$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ -// } + // if (DeltaProcessor.VERBOSE){ + // System.out.println("UPDATING Model with Delta: + // ["+Thread.currentThread()+":" + delta + + // "]:");//$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ + // } try { this.traverseDelta(delta, null, null); // traverse delta @@ -173,15 +185,16 @@ public class ModelUpdater { /** * Removes the given element from its parents cache of children. If the - * element does not have a parent, or the parent is not currently open, - * this has no effect. + * element does not have a parent, or the parent is not currently open, this + * has no effect. */ protected void removeFromParentInfo(Openable child) { Openable parent = (Openable) child.getParent(); if (parent != null && parent.isOpen()) { try { - JavaElementInfo info = (JavaElementInfo)parent.getElementInfo(); + JavaElementInfo info = (JavaElementInfo) parent + .getElementInfo(); info.removeChild(child); } catch (JavaModelException e) { // do nothing - we already checked if open @@ -190,50 +203,49 @@ public class ModelUpdater { } /** - * Converts an IResourceDelta and its children into - * the corresponding IJavaElementDeltas. - * Return whether the delta corresponds to a resource on the classpath. - * If it is not a resource on the classpath, it will be added as a non-java - * resource by the sender of this method. + * Converts an IResourceDelta and its children into the + * corresponding IJavaElementDeltas. Return whether the + * delta corresponds to a resource on the classpath. If it is not a resource + * on the classpath, it will be added as a non-java resource by the sender + * of this method. */ - protected void traverseDelta( - IJavaElementDelta delta, - IPackageFragmentRoot root, - IJavaProject project) { + protected void traverseDelta(IJavaElementDelta delta, + IPackageFragmentRoot root, IJavaProject project) { boolean processChildren = true; Openable element = (Openable) delta.getElement(); switch (element.getElementType()) { - case IJavaElement.JAVA_PROJECT : - project = (IJavaProject) element; - break; - case IJavaElement.PACKAGE_FRAGMENT_ROOT : - root = (IPackageFragmentRoot) element; - break; - case IJavaElement.COMPILATION_UNIT : - // filter out working copies that are not primary (we don't want to add/remove them to/from the package fragment - CompilationUnit cu = (CompilationUnit)element; - if (cu.isWorkingCopy() && !cu.isPrimary()) { - return; - } - case IJavaElement.CLASS_FILE : - processChildren = false; - break; + case IJavaElement.JAVA_PROJECT: + project = (IJavaProject) element; + break; + case IJavaElement.PACKAGE_FRAGMENT_ROOT: + root = (IPackageFragmentRoot) element; + break; + case IJavaElement.COMPILATION_UNIT: + // filter out working copies that are not primary (we don't want to + // add/remove them to/from the package fragment + CompilationUnit cu = (CompilationUnit) element; + if (cu.isWorkingCopy() && !cu.isPrimary()) { + return; + } + case IJavaElement.CLASS_FILE: + processChildren = false; + break; } switch (delta.getKind()) { - case IJavaElementDelta.ADDED : - elementAdded(element); - break; - case IJavaElementDelta.REMOVED : - elementRemoved(element); - break; - case IJavaElementDelta.CHANGED : - if ((delta.getFlags() & IJavaElementDelta.F_CONTENT) != 0){ - elementChanged(element); - } - break; + case IJavaElementDelta.ADDED: + elementAdded(element); + break; + case IJavaElementDelta.REMOVED: + elementRemoved(element); + break; + case IJavaElementDelta.CHANGED: + if ((delta.getFlags() & IJavaElementDelta.F_CONTENT) != 0) { + elementChanged(element); + } + break; } if (processChildren) { IJavaElementDelta[] children = delta.getAffectedChildren(); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MoveElementsOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MoveElementsOperation.java index 60975ab..47e8106 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MoveElementsOperation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MoveElementsOperation.java @@ -14,33 +14,38 @@ import net.sourceforge.phpdt.core.IJavaElement; import net.sourceforge.phpdt.internal.core.util.Util; /** - * This operation moves elements from their current - * container to a specified destination container, optionally renaming the - * elements. - * A move operation is equivalent to a copy operation, where - * the source elements are deleted after the copy. - *

                                              This operation can be used for reorganizing elements within the same container. - * + * This operation moves elements from their current container to a specified + * destination container, optionally renaming the elements. A move operation is + * equivalent to a copy operation, where the source elements are deleted after + * the copy. + *

                                              + * This operation can be used for reorganizing elements within the same + * container. + * * @see CopyElementsOperation */ public class MoveElementsOperation extends CopyElementsOperation { -/** - * When executed, this operation will move the given elements to the given containers. - */ -public MoveElementsOperation(IJavaElement[] elementsToMove, IJavaElement[] destContainers, boolean force) { - super(elementsToMove, destContainers, force); -} -/** - * Returns the String to use as the main task name - * for progress monitoring. - */ -protected String getMainTaskName() { - return Util.bind("operation.moveElementProgress"); //$NON-NLS-1$ -} -/** - * @see CopyElementsOperation#isMove() - */ -protected boolean isMove() { - return true; -} + /** + * When executed, this operation will move the given elements to the given + * containers. + */ + public MoveElementsOperation(IJavaElement[] elementsToMove, + IJavaElement[] destContainers, boolean force) { + super(elementsToMove, destContainers, force); + } + + /** + * Returns the String to use as the main task name for + * progress monitoring. + */ + protected String getMainTaskName() { + return Util.bind("operation.moveElementProgress"); //$NON-NLS-1$ + } + + /** + * @see CopyElementsOperation#isMove() + */ + protected boolean isMove() { + return true; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MoveResourceElementsOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MoveResourceElementsOperation.java index 53e2585..0008f5d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MoveResourceElementsOperation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MoveResourceElementsOperation.java @@ -14,32 +14,38 @@ import net.sourceforge.phpdt.core.IJavaElement; import net.sourceforge.phpdt.internal.core.util.Util; /** - * This operation moves resources (package fragments and compilation units) from their current - * container to a specified destination container, optionally renaming the - * elements. - * A move resource operation is equivalent to a copy resource operation, where - * the source resources are deleted after the copy. - *

                                              This operation can be used for reorganizing resources within the same container. - * + * This operation moves resources (package fragments and compilation units) from + * their current container to a specified destination container, optionally + * renaming the elements. A move resource operation is equivalent to a copy + * resource operation, where the source resources are deleted after the copy. + *

                                              + * This operation can be used for reorganizing resources within the same + * container. + * * @see CopyResourceElementsOperation */ -public class MoveResourceElementsOperation extends CopyResourceElementsOperation { -/** - * When executed, this operation will move the given elements to the given containers. - */ -public MoveResourceElementsOperation(IJavaElement[] elementsToMove, IJavaElement[] destContainers, boolean force) { - super(elementsToMove, destContainers, force); -} -/** - * @see MultiOperation - */ -protected String getMainTaskName() { - return Util.bind("operation.moveResourceProgress"); //$NON-NLS-1$ -} -/** - * @see CopyResourceElementsOperation#isMove() - */ -protected boolean isMove() { - return true; -} +public class MoveResourceElementsOperation extends + CopyResourceElementsOperation { + /** + * When executed, this operation will move the given elements to the given + * containers. + */ + public MoveResourceElementsOperation(IJavaElement[] elementsToMove, + IJavaElement[] destContainers, boolean force) { + super(elementsToMove, destContainers, force); + } + + /** + * @see MultiOperation + */ + protected String getMainTaskName() { + return Util.bind("operation.moveResourceProgress"); //$NON-NLS-1$ + } + + /** + * @see CopyResourceElementsOperation#isMove() + */ + protected boolean isMove() { + return true; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MultiOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MultiOperation.java index a5b4f45..ff0d80e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MultiOperation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MultiOperation.java @@ -20,90 +20,106 @@ import net.sourceforge.phpdt.core.IJavaModelStatusConstants; import net.sourceforge.phpdt.core.IPackageFragment; import net.sourceforge.phpdt.core.JavaModelException; - /** - * This class is used to perform operations on multiple IJavaElement. - * It is responible for running each operation in turn, collecting - * the errors and merging the corresponding JavaElementDeltas. + * This class is used to perform operations on multiple + * IJavaElement. It is responible for running each operation in + * turn, collecting the errors and merging the corresponding + * JavaElementDeltas. *

                                              * If several errors occured, they are collected in a multi-status - * JavaModelStatus. Otherwise, a simple JavaModelStatus - * is thrown. + * JavaModelStatus. Otherwise, a simple + * JavaModelStatus is thrown. */ public abstract class MultiOperation extends JavaModelOperation { /** * The list of renamings supplied to the operation */ - protected String[] fRenamingsList= null; + protected String[] fRenamingsList = null; + /** - * Table specifying the new parent for elements being - * copied/moved/renamed. - * Keyed by elements being processed, and - * values are the corresponding destination parent. + * Table specifying the new parent for elements being copied/moved/renamed. + * Keyed by elements being processed, and values are the corresponding + * destination parent. */ protected Map fParentElements; + /** - * Table specifying insertion positions for elements being - * copied/moved/renamed. Keyed by elements being processed, and - * values are the corresponding insertion point. + * Table specifying insertion positions for elements being + * copied/moved/renamed. Keyed by elements being processed, and values are + * the corresponding insertion point. + * * @see processElements(IProgressMonitor) */ - protected Map fInsertBeforeElements= new HashMap(1); + protected Map fInsertBeforeElements = new HashMap(1); + /** * This table presents the data in fRenamingList in a more * convenient way. */ protected Map fRenamings; + /** * Creates a new MultiOperation. */ - protected MultiOperation(IJavaElement[] elementsToProcess, IJavaElement[] parentElements, boolean force) { + protected MultiOperation(IJavaElement[] elementsToProcess, + IJavaElement[] parentElements, boolean force) { super(elementsToProcess, parentElements, force); fParentElements = new HashMap(elementsToProcess.length); if (elementsToProcess.length == parentElements.length) { for (int i = 0; i < elementsToProcess.length; i++) { fParentElements.put(elementsToProcess[i], parentElements[i]); } - } else { //same destination for all elements to be moved/copied/renamed + } else { // same destination for all elements to be + // moved/copied/renamed for (int i = 0; i < elementsToProcess.length; i++) { fParentElements.put(elementsToProcess[i], parentElements[0]); } } - + } + /** - * Creates a new MultiOperation on elementsToProcess. + * Creates a new MultiOperation on + * elementsToProcess. */ protected MultiOperation(IJavaElement[] elementsToProcess, boolean force) { super(elementsToProcess, force); } + /** * Convenience method to create a JavaModelException * embending a JavaModelStatus. */ - protected void error(int code, IJavaElement element) throws JavaModelException { + protected void error(int code, IJavaElement element) + throws JavaModelException { throw new JavaModelException(new JavaModelStatus(code, element)); } + /** * Executes the operation. - * - * @exception JavaModelException if one or several errors occured during the operation. - * If multiple errors occured, the corresponding JavaModelStatus is a - * multi-status. Otherwise, it is a simple one. + * + * @exception JavaModelException + * if one or several errors occured during the operation. If + * multiple errors occured, the corresponding + * JavaModelStatus is a multi-status. + * Otherwise, it is a simple one. */ protected void executeOperation() throws JavaModelException { processElements(); } + /** * Returns the parent of the element being copied/moved/renamed. */ protected IJavaElement getDestinationParent(IJavaElement child) { - return (IJavaElement)fParentElements.get(child); + return (IJavaElement) fParentElements.get(child); } + /** * Returns the name to be used by the progress monitor. */ protected abstract String getMainTaskName(); + /** * Returns the new name for element, or null * if there are no renamings specified. @@ -114,12 +130,14 @@ public abstract class MultiOperation extends JavaModelOperation { else return null; } + /** - * Sets up the renamings hashtable - keys are the elements and - * values are the new name. + * Sets up the renamings hashtable - keys are the elements and values are + * the new name. */ private void initializeRenamings() { - if (fRenamingsList != null && fRenamingsList.length == fElementsToProcess.length) { + if (fRenamingsList != null + && fRenamingsList.length == fElementsToProcess.length) { fRenamings = new HashMap(fRenamingsList.length); for (int i = 0; i < fRenamingsList.length; i++) { if (fRenamingsList[i] != null) { @@ -128,32 +146,37 @@ public abstract class MultiOperation extends JavaModelOperation { } } } + /** - * Returns true if this operation represents a move or rename, false - * if this operation represents a copy.
                                              + * Returns true if this operation represents a move or + * rename, false if this operation represents a copy.
                                              * Note: a rename is just a move within the same parent with a name change. */ protected boolean isMove() { return false; } + /** - * Returns true if this operation represents a rename, false - * if this operation represents a copy or move. + * Returns true if this operation represents a rename, + * false if this operation represents a copy or move. */ protected boolean isRename() { return false; } - + /** - * Subclasses must implement this method to process a given IJavaElement. + * Subclasses must implement this method to process a given + * IJavaElement. */ - protected abstract void processElement(IJavaElement element) throws JavaModelException; + protected abstract void processElement(IJavaElement element) + throws JavaModelException; + /** - * Processes all the IJavaElements in turn, collecting errors - * and updating the progress monitor. - * - * @exception JavaModelException if one or several operation(s) was unable to - * be completed. + * Processes all the IJavaElements in turn, collecting + * errors and updating the progress monitor. + * + * @exception JavaModelException + * if one or several operation(s) was unable to be completed. */ protected void processElements() throws JavaModelException { beginTask(getMainTaskName(), fElementsToProcess.length); @@ -166,7 +189,9 @@ public abstract class MultiOperation extends JavaModelOperation { } catch (JavaModelException jme) { if (errorsCounter == errors.length) { // resize - System.arraycopy(errors, 0, (errors = new IJavaModelStatus[errorsCounter*2]), 0, errorsCounter); + System.arraycopy(errors, 0, + (errors = new IJavaModelStatus[errorsCounter * 2]), + 0, errorsCounter); } errors[errorsCounter++] = jme.getJavaModelStatus(); } finally { @@ -179,129 +204,159 @@ public abstract class MultiOperation extends JavaModelOperation { } else if (errorsCounter > 1) { if (errorsCounter != errors.length) { // resize - System.arraycopy(errors, 0, (errors = new IJavaModelStatus[errorsCounter]), 0, errorsCounter); + System.arraycopy(errors, 0, + (errors = new IJavaModelStatus[errorsCounter]), 0, + errorsCounter); } throw new JavaModelException(JavaModelStatus.newMultiStatus(errors)); } } + /** - * Sets the insertion position in the new container for the modified element. The element - * being modified will be inserted before the specified new sibling. The given sibling - * must be a child of the destination container specified for the modified element. - * The default is null, which indicates that the element is to be - * inserted at the end of the container. + * Sets the insertion position in the new container for the modified + * element. The element being modified will be inserted before the specified + * new sibling. The given sibling must be a child of the destination + * container specified for the modified element. The default is + * null, which indicates that the element is to be inserted + * at the end of the container. */ - public void setInsertBefore(IJavaElement modifiedElement, IJavaElement newSibling) { + public void setInsertBefore(IJavaElement modifiedElement, + IJavaElement newSibling) { fInsertBeforeElements.put(modifiedElement, newSibling); } + /** * Sets the new names to use for each element being copied. The renamings - * correspond to the elements being processed, and the number of - * renamings must match the number of elements being processed. - * A null entry in the list indicates that an element - * is not to be renamed. - * - *

                                              Note that some renamings may not be used. If both a parent - * and a child have been selected for copy/move, only the parent - * is changed. Therefore, if a new name is specified for the child, - * the child's name will not be changed. + * correspond to the elements being processed, and the number of renamings + * must match the number of elements being processed. A null + * entry in the list indicates that an element is not to be renamed. + * + *

                                              + * Note that some renamings may not be used. If both a parent and a child + * have been selected for copy/move, only the parent is changed. Therefore, + * if a new name is specified for the child, the child's name will not be + * changed. */ public void setRenamings(String[] renamings) { fRenamingsList = renamings; initializeRenamings(); } + /** * This method is called for each IJavaElement before - * processElement. It should check that this element - * can be processed. + * processElement. It should check that this + * element can be processed. */ - protected abstract void verify(IJavaElement element) throws JavaModelException; + protected abstract void verify(IJavaElement element) + throws JavaModelException; + /** - * Verifies that the destination specified for the element is valid for the types of the - * element and destination. + * Verifies that the destination specified for the + * element is valid for the types of the element + * and destination. */ - protected void verifyDestination(IJavaElement element, IJavaElement destination) throws JavaModelException { + protected void verifyDestination(IJavaElement element, + IJavaElement destination) throws JavaModelException { if (destination == null || !destination.exists()) error(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, destination); - + int destType = destination.getElementType(); switch (element.getElementType()) { - case IJavaElement.PACKAGE_DECLARATION : - case IJavaElement.IMPORT_DECLARATION : - if (destType != IJavaElement.COMPILATION_UNIT) - error(IJavaModelStatusConstants.INVALID_DESTINATION, element); - break; - case IJavaElement.TYPE : - if (destType != IJavaElement.COMPILATION_UNIT && destType != IJavaElement.TYPE) - error(IJavaModelStatusConstants.INVALID_DESTINATION, element); - break; - case IJavaElement.METHOD : - case IJavaElement.FIELD : -// case IJavaElement.INITIALIZER : -// if (destType != IJavaElement.TYPE || destination instanceof BinaryType) -// error(IJavaModelStatusConstants.INVALID_DESTINATION, element); -// break; - case IJavaElement.COMPILATION_UNIT : - if (destType != IJavaElement.PACKAGE_FRAGMENT) - error(IJavaModelStatusConstants.INVALID_DESTINATION, element); - else if (isMove() && ((ICompilationUnit) element).isWorkingCopy()) - error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element); - break; - case IJavaElement.PACKAGE_FRAGMENT : - IPackageFragment fragment = (IPackageFragment) element; - IJavaElement parent = fragment.getParent(); - if (parent.isReadOnly()) - error(IJavaModelStatusConstants.READ_ONLY, element); - else if (destType != IJavaElement.PACKAGE_FRAGMENT_ROOT) - error(IJavaModelStatusConstants.INVALID_DESTINATION, element); - break; - default : + case IJavaElement.PACKAGE_DECLARATION: + case IJavaElement.IMPORT_DECLARATION: + if (destType != IJavaElement.COMPILATION_UNIT) + error(IJavaModelStatusConstants.INVALID_DESTINATION, element); + break; + case IJavaElement.TYPE: + if (destType != IJavaElement.COMPILATION_UNIT + && destType != IJavaElement.TYPE) + error(IJavaModelStatusConstants.INVALID_DESTINATION, element); + break; + case IJavaElement.METHOD: + case IJavaElement.FIELD: + // case IJavaElement.INITIALIZER : + // if (destType != IJavaElement.TYPE || destination instanceof + // BinaryType) + // error(IJavaModelStatusConstants.INVALID_DESTINATION, element); + // break; + case IJavaElement.COMPILATION_UNIT: + if (destType != IJavaElement.PACKAGE_FRAGMENT) + error(IJavaModelStatusConstants.INVALID_DESTINATION, element); + else if (isMove() && ((ICompilationUnit) element).isWorkingCopy()) error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element); + break; + case IJavaElement.PACKAGE_FRAGMENT: + IPackageFragment fragment = (IPackageFragment) element; + IJavaElement parent = fragment.getParent(); + if (parent.isReadOnly()) + error(IJavaModelStatusConstants.READ_ONLY, element); + else if (destType != IJavaElement.PACKAGE_FRAGMENT_ROOT) + error(IJavaModelStatusConstants.INVALID_DESTINATION, element); + break; + default: + error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element); } } + /** - * Verify that the new name specified for element is - * valid for that type of Java element. + * Verify that the new name specified for element is valid + * for that type of Java element. */ - protected void verifyRenaming(IJavaElement element) throws JavaModelException { + protected void verifyRenaming(IJavaElement element) + throws JavaModelException { String newName = getNewNameFor(element); boolean isValid = true; - + switch (element.getElementType()) { - case IJavaElement.PACKAGE_FRAGMENT : - if (element.getElementName().equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) { - // don't allow renaming of default package (see PR #1G47GUM) - throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION, element)); - } -// isValid = JavaConventions.validatePackageName(newName).getSeverity() != IStatus.ERROR; - isValid = true; - break; - case IJavaElement.COMPILATION_UNIT : -// isValid = JavaConventions.validateCompilationUnitName(newName).getSeverity() != IStatus.ERROR; + case IJavaElement.PACKAGE_FRAGMENT: + if (element.getElementName().equals( + IPackageFragment.DEFAULT_PACKAGE_NAME)) { + // don't allow renaming of default package (see PR #1G47GUM) + throw new JavaModelException(new JavaModelStatus( + IJavaModelStatusConstants.NAME_COLLISION, element)); + } + // isValid = + // JavaConventions.validatePackageName(newName).getSeverity() != + // IStatus.ERROR; isValid = true; - break; - case IJavaElement.INITIALIZER : - isValid = false; //cannot rename initializers - break; - default : -// isValid = JavaConventions.validateIdentifier(newName).getSeverity() != IStatus.ERROR; + break; + case IJavaElement.COMPILATION_UNIT: + // isValid = + // JavaConventions.validateCompilationUnitName(newName).getSeverity() + // != IStatus.ERROR; isValid = true; - break; + break; + case IJavaElement.INITIALIZER: + isValid = false; // cannot rename initializers + break; + default: + // isValid = + // JavaConventions.validateIdentifier(newName).getSeverity() != + // IStatus.ERROR; + isValid = true; + break; } - + if (!isValid) { - throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_NAME, element, newName)); + throw new JavaModelException(new JavaModelStatus( + IJavaModelStatusConstants.INVALID_NAME, element, newName)); } } + /** - * Verifies that the positioning sibling specified for the element is exists and - * its parent is the destination container of this element. + * Verifies that the positioning sibling specified for the + * element is exists and its parent is the destination + * container of this element. */ - protected void verifySibling(IJavaElement element, IJavaElement destination) throws JavaModelException { - IJavaElement insertBeforeElement = (IJavaElement) fInsertBeforeElements.get(element); + protected void verifySibling(IJavaElement element, IJavaElement destination) + throws JavaModelException { + IJavaElement insertBeforeElement = (IJavaElement) fInsertBeforeElements + .get(element); if (insertBeforeElement != null) { - if (!insertBeforeElement.exists() || !insertBeforeElement.getParent().equals(destination)) { - error(IJavaModelStatusConstants.INVALID_SIBLING, insertBeforeElement); + if (!insertBeforeElement.exists() + || !insertBeforeElement.getParent().equals(destination)) { + error(IJavaModelStatusConstants.INVALID_SIBLING, + insertBeforeElement); } } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/NameLookup.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/NameLookup.java index 66ec3f7..fc9fcd8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/NameLookup.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/NameLookup.java @@ -32,21 +32,25 @@ import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; + /** * A NameLookup provides name resolution within a Java project. - * The name lookup facility uses the project's classpath to prioritize the - * order in which package fragments are searched when resolving a name. - * - *

                                              Name lookup only returns a handle when the named element actually - * exists in the model; otherwise null is returned. - * - *

                                              There are two logical sets of methods within this interface. Methods - * which start with find* are intended to be convenience methods for quickly - * finding an element within another element; for instance, for finding a class within a - * package. The other set of methods all begin with seek*. These methods - * do comprehensive searches of the IJavaProject returning hits - * in real time through an IJavaElementRequestor. - * + * The name lookup facility uses the project's classpath to prioritize the order + * in which package fragments are searched when resolving a name. + * + *

                                              + * Name lookup only returns a handle when the named element actually exists in + * the model; otherwise null is returned. + * + *

                                              + * There are two logical sets of methods within this interface. Methods which + * start with find* are intended to be convenience methods for + * quickly finding an element within another element; for instance, for finding + * a class within a package. The other set of methods all begin with + * seek*. These methods do comprehensive searches of the + * IJavaProject returning hits in real time through an + * IJavaElementRequestor. + * */ public class NameLookup { /** @@ -60,32 +64,28 @@ public class NameLookup { public static final int ACCEPT_INTERFACES = 0x00000004; /** - * The IPackageFragmentRoot's associated - * with the classpath of this NameLookup facility's - * project. + * The IPackageFragmentRoot's associated with the classpath + * of this NameLookup facility's project. */ - protected IPackageFragmentRoot[] fPackageFragmentRoots= null; + protected IPackageFragmentRoot[] fPackageFragmentRoots = null; /** - * Table that maps package names to lists of package fragments for - * all package fragments in the package fragment roots known - * by this name lookup facility. To allow > 1 package fragment - * with the same name, values are arrays of package fragments - * ordered as they appear on the classpath. + * Table that maps package names to lists of package fragments for all + * package fragments in the package fragment roots known by this name lookup + * facility. To allow > 1 package fragment with the same name, values are + * arrays of package fragments ordered as they appear on the classpath. */ protected Map fPackageFragments; /** - * The IWorkspace that this NameLookup - * is configure within. + * The IWorkspace that this NameLookup is configure within. */ protected IWorkspace workspace; - + /** * A map from compilation unit handles to units to look inside (compilation - * units or working copies). - * Allows working copies to take precedence over compilation units. - * The cache is a 2-level cache, first keyed by thread. + * units or working copies). Allows working copies to take precedence over + * compilation units. The cache is a 2-level cache, first keyed by thread. */ protected PerThreadObject unitsToLookInside = new PerThreadObject(); @@ -94,15 +94,16 @@ public class NameLookup { } /** - * Returns true if:

                                                - *
                                              • the given type is an existing class and the flag's ACCEPT_CLASSES - * bit is on - *
                                              • the given type is an existing interface and the ACCEPT_INTERFACES - * bit is on - *
                                              • neither the ACCEPT_CLASSES or ACCEPT_INTERFACES - * bit is on - *
                                              - * Otherwise, false is returned. + * Returns true if: + *
                                                + *
                                              • the given type is an existing class and the flag's + * ACCEPT_CLASSES bit is on + *
                                              • the given type is an existing interface and the + * ACCEPT_INTERFACES bit is on + *
                                              • neither the ACCEPT_CLASSES or + * ACCEPT_INTERFACES bit is on + *
                                              + * Otherwise, false is returned. */ protected boolean acceptType(IType type, int acceptFlags) { if (acceptFlags == 0) @@ -119,120 +120,130 @@ public class NameLookup { } /** - * Configures this NameLookup based on the - * info of the given IJavaProject. - * - * @throws JavaModelException if the IJavaProject has no classpath. + * Configures this NameLookup based on the info of the given + * IJavaProject. + * + * @throws JavaModelException + * if the IJavaProject has no classpath. */ - private void configureFromProject(IJavaProject project) throws JavaModelException { - workspace= ResourcesPlugin.getWorkspace(); - fPackageFragmentRoots= ((JavaProject) project).getAllPackageFragmentRoots(); - fPackageFragments= new HashMap(); - IPackageFragment[] frags = this.getPackageFragmentsInRoots(fPackageFragmentRoots, project); - for (int i= 0; i < frags.length; i++) { - IPackageFragment fragment= frags[i]; - IPackageFragment[] entry= (IPackageFragment[]) fPackageFragments.get(fragment.getElementName()); + private void configureFromProject(IJavaProject project) + throws JavaModelException { + workspace = ResourcesPlugin.getWorkspace(); + fPackageFragmentRoots = ((JavaProject) project) + .getAllPackageFragmentRoots(); + fPackageFragments = new HashMap(); + IPackageFragment[] frags = this.getPackageFragmentsInRoots( + fPackageFragmentRoots, project); + for (int i = 0; i < frags.length; i++) { + IPackageFragment fragment = frags[i]; + IPackageFragment[] entry = (IPackageFragment[]) fPackageFragments + .get(fragment.getElementName()); if (entry == null) { - entry= new IPackageFragment[1]; - entry[0]= fragment; + entry = new IPackageFragment[1]; + entry[0] = fragment; fPackageFragments.put(fragment.getElementName(), entry); } else { - IPackageFragment[] copy= new IPackageFragment[entry.length + 1]; + IPackageFragment[] copy = new IPackageFragment[entry.length + 1]; System.arraycopy(entry, 0, copy, 0, entry.length); - copy[entry.length]= fragment; + copy[entry.length] = fragment; fPackageFragments.put(fragment.getElementName(), copy); } } } /** - * Finds every type in the project whose simple name matches - * the prefix, informing the requestor of each hit. The requestor - * is polled for cancellation at regular intervals. - * - *

                                              The partialMatch argument indicates partial matches - * should be considered. + * Finds every type in the project whose simple name matches the prefix, + * informing the requestor of each hit. The requestor is polled for + * cancellation at regular intervals. + * + *

                                              + * The partialMatch argument indicates partial matches should + * be considered. */ - private void findAllTypes(String prefix, boolean partialMatch, int acceptFlags, IJavaElementRequestor requestor) { - int count= fPackageFragmentRoots.length; - for (int i= 0; i < count; i++) { + private void findAllTypes(String prefix, boolean partialMatch, + int acceptFlags, IJavaElementRequestor requestor) { + int count = fPackageFragmentRoots.length; + for (int i = 0; i < count; i++) { if (requestor.isCanceled()) return; - IPackageFragmentRoot root= fPackageFragmentRoots[i]; - IJavaElement[] packages= null; + IPackageFragmentRoot root = fPackageFragmentRoots[i]; + IJavaElement[] packages = null; try { - packages= root.getChildren(); + packages = root.getChildren(); } catch (JavaModelException npe) { continue; // the root is not present, continue; } if (packages != null) { - for (int j= 0, packageCount= packages.length; j < packageCount; j++) { + for (int j = 0, packageCount = packages.length; j < packageCount; j++) { if (requestor.isCanceled()) return; - seekTypes(prefix, (IPackageFragment) packages[j], partialMatch, acceptFlags, requestor); + seekTypes(prefix, (IPackageFragment) packages[j], + partialMatch, acceptFlags, requestor); } } } } /** - * Returns the ICompilationUnit which defines the type - * named qualifiedTypeName, or null if - * none exists. The domain of the search is bounded by the classpath - * of the IJavaProject this NameLookup was - * obtained from. + * Returns the ICompilationUnit which defines the type named + * qualifiedTypeName, or null if none exists. + * The domain of the search is bounded by the classpath of the + * IJavaProject this NameLookup was obtained + * from. *

                                              - * The name must be fully qualified (eg "java.lang.Object", "java.util.Hashtable$Entry") + * The name must be fully qualified (eg "java.lang.Object", + * "java.util.Hashtable$Entry") */ public ICompilationUnit findCompilationUnit(String qualifiedTypeName) { - String pkgName= IPackageFragment.DEFAULT_PACKAGE_NAME; - String cuName= qualifiedTypeName; + String pkgName = IPackageFragment.DEFAULT_PACKAGE_NAME; + String cuName = qualifiedTypeName; - int index= qualifiedTypeName.lastIndexOf('.'); + int index = qualifiedTypeName.lastIndexOf('.'); if (index != -1) { - pkgName= qualifiedTypeName.substring(0, index); - cuName= qualifiedTypeName.substring(index + 1); + pkgName = qualifiedTypeName.substring(0, index); + cuName = qualifiedTypeName.substring(index + 1); } - index= cuName.indexOf('$'); + index = cuName.indexOf('$'); if (index != -1) { - cuName= cuName.substring(0, index); + cuName = cuName.substring(0, index); } cuName += ".java"; //$NON-NLS-1$ - IPackageFragment[] frags= (IPackageFragment[]) fPackageFragments.get(pkgName); + IPackageFragment[] frags = (IPackageFragment[]) fPackageFragments + .get(pkgName); if (frags != null) { - for (int i= 0; i < frags.length; i++) { - IPackageFragment frag= frags[i]; -// if (!(frag instanceof JarPackageFragment)) { -// ICompilationUnit cu= frag.getCompilationUnit(cuName); -// if (cu != null && cu.exists()) { -// return cu; -// } -// } + for (int i = 0; i < frags.length; i++) { + IPackageFragment frag = frags[i]; + // if (!(frag instanceof JarPackageFragment)) { + // ICompilationUnit cu= frag.getCompilationUnit(cuName); + // if (cu != null && cu.exists()) { + // return cu; + // } + // } } } return null; } - + /** - * Returns the package fragment whose path matches the given - * (absolute) path, or null if none exist. The domain of - * the search is bounded by the classpath of the IJavaProject - * this NameLookup was obtained from. - * The path can be: - * - internal to the workbench: "/Project/src" - * - external to the workbench: "c:/jdk/classes.zip/java/lang" + * Returns the package fragment whose path matches the given (absolute) + * path, or null if none exist. The domain of the search is + * bounded by the classpath of the IJavaProject this + * NameLookup was obtained from. The path can be: - internal + * to the workbench: "/Project/src" - external to the workbench: + * "c:/jdk/classes.zip/java/lang" */ public IPackageFragment findPackageFragment(IPath path) { if (!path.isAbsolute()) { throw new IllegalArgumentException(Util.bind("path.mustBeAbsolute")); //$NON-NLS-1$ } -/* - * this code should rather use the package fragment map to find the candidate package, then - * check if the respective enclosing root maps to the one on this given IPath. - */ + /* + * this code should rather use the package fragment map to find the + * candidate package, then check if the respective enclosing root maps + * to the one on this given IPath. + */ IResource possibleFragment = workspace.getRoot().findMember(path); if (possibleFragment == null) { - //external jar + // external jar for (int i = 0; i < fPackageFragmentRoots.length; i++) { IPackageFragmentRoot root = fPackageFragmentRoots[i]; if (!root.isExternal()) { @@ -243,7 +254,8 @@ public class NameLookup { if (matchingCount != 0) { String name = path.toOSString(); // + 1 is for the File.separatorChar - name = name.substring(rootPath.toOSString().length() + 1, name.length()); + name = name.substring(rootPath.toOSString().length() + 1, + name.length()); name = name.replace(File.separatorChar, '.'); IJavaElement[] list = null; try { @@ -267,82 +279,88 @@ public class NameLookup { } if (fromFactory instanceof IPackageFragment) { return (IPackageFragment) fromFactory; - } else - if (fromFactory instanceof IJavaProject) { - // default package in a default root - JavaProject project = (JavaProject) fromFactory; - try { - IClasspathEntry entry = project.getClasspathEntryFor(path); - if (entry != null) { - IPackageFragmentRoot root = - project.getPackageFragmentRoot(project.getResource()); - IPackageFragment[] pkgs = (IPackageFragment[]) fPackageFragments.get(IPackageFragment.DEFAULT_PACKAGE_NAME); - if (pkgs == null) { - return null; - } - for (int i = 0; i < pkgs.length; i++) { - if (pkgs[i].getParent().equals(root)) { - return pkgs[i]; - } + } else if (fromFactory instanceof IJavaProject) { + // default package in a default root + JavaProject project = (JavaProject) fromFactory; + try { + IClasspathEntry entry = project.getClasspathEntryFor(path); + if (entry != null) { + IPackageFragmentRoot root = project + .getPackageFragmentRoot(project.getResource()); + IPackageFragment[] pkgs = (IPackageFragment[]) fPackageFragments + .get(IPackageFragment.DEFAULT_PACKAGE_NAME); + if (pkgs == null) { + return null; + } + for (int i = 0; i < pkgs.length; i++) { + if (pkgs[i].getParent().equals(root)) { + return pkgs[i]; } } - } catch (JavaModelException e) { - return null; } + } catch (JavaModelException e) { + return null; } + } } return null; } /** - * Returns the package fragments whose name matches the given - * (qualified) name, or null if none exist. - * - * The name can be: - * - empty: "" - * - qualified: "pack.pack1.pack2" - * @param partialMatch partial name matches qualify when true, - * only exact name matches qualify when false + * Returns the package fragments whose name matches the given (qualified) + * name, or null if none exist. + * + * The name can be: - empty: "" - qualified: "pack.pack1.pack2" + * + * @param partialMatch + * partial name matches qualify when true, only + * exact name matches qualify when false */ - public IPackageFragment[] findPackageFragments(String name, boolean partialMatch) { - int count= fPackageFragmentRoots.length; + public IPackageFragment[] findPackageFragments(String name, + boolean partialMatch) { + int count = fPackageFragmentRoots.length; if (partialMatch) { - name= name.toLowerCase(); - for (int i= 0; i < count; i++) { - IPackageFragmentRoot root= fPackageFragmentRoots[i]; - IJavaElement[] list= null; + name = name.toLowerCase(); + for (int i = 0; i < count; i++) { + IPackageFragmentRoot root = fPackageFragmentRoots[i]; + IJavaElement[] list = null; try { - list= root.getChildren(); + list = root.getChildren(); } catch (JavaModelException npe) { continue; // the package fragment root is not present; } - int elementCount= list.length; + int elementCount = list.length; IPackageFragment[] result = new IPackageFragment[elementCount]; - int resultLength = 0; - for (int j= 0; j < elementCount; j++) { - IPackageFragment packageFragment= (IPackageFragment) list[j]; + int resultLength = 0; + for (int j = 0; j < elementCount; j++) { + IPackageFragment packageFragment = (IPackageFragment) list[j]; if (nameMatches(name, packageFragment, true)) { result[resultLength++] = packageFragment; } } if (resultLength > 0) { - System.arraycopy(result, 0, result = new IPackageFragment[resultLength], 0, resultLength); + System.arraycopy(result, 0, + result = new IPackageFragment[resultLength], 0, + resultLength); return result; } else { return null; } } } else { - IPackageFragment[] fragments= (IPackageFragment[]) fPackageFragments.get(name); + IPackageFragment[] fragments = (IPackageFragment[]) fPackageFragments + .get(name); if (fragments != null) { IPackageFragment[] result = new IPackageFragment[fragments.length]; - int resultLength = 0; - for (int i= 0; i < fragments.length; i++) { - IPackageFragment packageFragment= fragments[i]; + int resultLength = 0; + for (int i = 0; i < fragments.length; i++) { + IPackageFragment packageFragment = fragments[i]; result[resultLength++] = packageFragment; } if (resultLength > 0) { - System.arraycopy(result, 0, result = new IPackageFragment[resultLength], 0, resultLength); + System.arraycopy(result, 0, + result = new IPackageFragment[resultLength], 0, + resultLength); return result; } else { return null; @@ -355,54 +373,63 @@ public class NameLookup { /** * */ - public IType findType(String typeName, String packageName, boolean partialMatch, int acceptFlags) { + public IType findType(String typeName, String packageName, + boolean partialMatch, int acceptFlags) { if (packageName == null) { - packageName= IPackageFragment.DEFAULT_PACKAGE_NAME; + packageName = IPackageFragment.DEFAULT_PACKAGE_NAME; } JavaElementRequestor elementRequestor = new JavaElementRequestor(); seekPackageFragments(packageName, false, elementRequestor); - IPackageFragment[] packages= elementRequestor.getPackageFragments(); + IPackageFragment[] packages = elementRequestor.getPackageFragments(); - for (int i= 0, length= packages.length; i < length; i++) { - IType type= findType(typeName, packages[i], partialMatch, acceptFlags); + for (int i = 0, length = packages.length; i < length; i++) { + IType type = findType(typeName, packages[i], partialMatch, + acceptFlags); if (type != null) return type; } return null; } + /** - * Returns all the package fragments found in the specified - * package fragment roots. Make sure the returned fragments have the given - * project as great parent. This ensures the name lookup will not refer to another - * project (through jar package fragment roots) + * Returns all the package fragments found in the specified package fragment + * roots. Make sure the returned fragments have the given project as great + * parent. This ensures the name lookup will not refer to another project + * (through jar package fragment roots) */ - private IPackageFragment[] getPackageFragmentsInRoots(IPackageFragmentRoot[] roots, IJavaProject project) { + private IPackageFragment[] getPackageFragmentsInRoots( + IPackageFragmentRoot[] roots, IJavaProject project) { - // The following code assumes that all the roots have the given project as their parent + // The following code assumes that all the roots have the given project + // as their parent ArrayList frags = new ArrayList(); for (int i = 0; i < roots.length; i++) { IPackageFragmentRoot root = roots[i]; try { IJavaElement[] children = root.getChildren(); - /* 2 jar package fragment roots can be equals but not belonging - to the same project. As a result, they share the same element info. - So this jar package fragment root could get the children of - another jar package fragment root. - The following code ensures that the children of this jar package - fragment root have the given project as a great parent. + /* + * 2 jar package fragment roots can be equals but not belonging + * to the same project. As a result, they share the same element + * info. So this jar package fragment root could get the + * children of another jar package fragment root. The following + * code ensures that the children of this jar package fragment + * root have the given project as a great parent. */ int length = children.length; - if (length == 0) continue; + if (length == 0) + continue; if (children[0].getParent().getParent().equals(project)) { - // the children have the right parent, simply add them to the list + // the children have the right parent, simply add them to + // the list for (int j = 0; j < length; j++) { frags.add(children[j]); } } else { // create a new handle with the root as the parent for (int j = 0; j < length; j++) { - frags.add(root.getPackageFragment(children[j].getElementName())); + frags.add(root.getPackageFragment(children[j] + .getElementName())); } } } catch (JavaModelException e) { @@ -415,109 +442,124 @@ public class NameLookup { } /** - * Returns the first type in the given package whose name - * matches the given (unqualified) name, or null if none - * exist. Specifying a null package will result in no matches. - * The domain of the search is bounded by the Java project from which - * this name lookup was obtained. - * - * @param name the name of the type to find - * @param pkg the package to search - * @param partialMatch partial name matches qualify when true, - * only exact name matches qualify when false - * @param acceptFlags a bit mask describing if classes, interfaces or both classes and interfaces - * are desired results. If no flags are specified, all types are returned. - * + * Returns the first type in the given package whose name matches the given + * (unqualified) name, or null if none exist. Specifying a + * null package will result in no matches. The domain of the + * search is bounded by the Java project from which this name lookup was + * obtained. + * + * @param name + * the name of the type to find + * @param pkg + * the package to search + * @param partialMatch + * partial name matches qualify when true, only + * exact name matches qualify when false + * @param acceptFlags + * a bit mask describing if classes, interfaces or both classes + * and interfaces are desired results. If no flags are specified, + * all types are returned. + * * @see #ACCEPT_CLASSES * @see #ACCEPT_INTERFACES */ - public IType findType(String name, IPackageFragment pkg, boolean partialMatch, int acceptFlags) { + public IType findType(String name, IPackageFragment pkg, + boolean partialMatch, int acceptFlags) { if (pkg == null) { return null; } // Return first found (ignore duplicates). -//synchronized(JavaModelManager.getJavaModelManager()){ -// SingleTypeRequestor typeRequestor = new SingleTypeRequestor(); -// seekTypes(name, pkg, partialMatch, acceptFlags, typeRequestor); -// IType type= typeRequestor.getType(); -// return type; -//} - return null; + // synchronized(JavaModelManager.getJavaModelManager()){ + // SingleTypeRequestor typeRequestor = new SingleTypeRequestor(); + // seekTypes(name, pkg, partialMatch, acceptFlags, typeRequestor); + // IType type= typeRequestor.getType(); + // return type; + // } + return null; } /** * Returns the type specified by the qualified name, or null - * if none exist. The domain of - * the search is bounded by the Java project from which this name lookup was obtained. - * - * @param name the name of the type to find - * @param partialMatch partial name matches qualify when true, - * only exact name matches qualify when false - * @param acceptFlags a bit mask describing if classes, interfaces or both classes and interfaces - * are desired results. If no flags are specified, all types are returned. - * + * if none exist. The domain of the search is bounded by the Java project + * from which this name lookup was obtained. + * + * @param name + * the name of the type to find + * @param partialMatch + * partial name matches qualify when true, only + * exact name matches qualify when false + * @param acceptFlags + * a bit mask describing if classes, interfaces or both classes + * and interfaces are desired results. If no flags are specified, + * all types are returned. + * * @see #ACCEPT_CLASSES * @see #ACCEPT_INTERFACES */ public IType findType(String name, boolean partialMatch, int acceptFlags) { - int index= name.lastIndexOf('.'); - String className= null, packageName= null; + int index = name.lastIndexOf('.'); + String className = null, packageName = null; if (index == -1) { - packageName= IPackageFragment.DEFAULT_PACKAGE_NAME; - className= name; + packageName = IPackageFragment.DEFAULT_PACKAGE_NAME; + className = name; } else { - packageName= name.substring(0, index); - className= name.substring(index + 1); + packageName = name.substring(0, index); + className = name.substring(index + 1); } return findType(className, packageName, partialMatch, acceptFlags); } /** - * Returns true if the given element's name matches the - * specified searchName, otherwise false. - * - *

                                              The partialMatch argument indicates partial matches - * should be considered. - * NOTE: in partialMatch mode, the case will be ignored, and the searchName must already have - * been lowercased. + * Returns true if the given element's name matches the specified + * searchName, otherwise false. + * + *

                                              + * The partialMatch argument indicates partial matches should + * be considered. NOTE: in partialMatch mode, the case will be ignored, and + * the searchName must already have been lowercased. */ - protected boolean nameMatches(String searchName, IJavaElement element, boolean partialMatch) { + protected boolean nameMatches(String searchName, IJavaElement element, + boolean partialMatch) { if (partialMatch) { - // partial matches are used in completion mode, thus case insensitive mode - return element.getElementName().toLowerCase().startsWith(searchName); + // partial matches are used in completion mode, thus case + // insensitive mode + return element.getElementName().toLowerCase() + .startsWith(searchName); } else { return element.getElementName().equals(searchName); } } /** - * Notifies the given requestor of all package fragments with the - * given name. Checks the requestor at regular intervals to see if the - * requestor has canceled. The domain of - * the search is bounded by the IJavaProject - * this NameLookup was obtained from. - * - * @param partialMatch partial name matches qualify when true; - * only exact name matches qualify when false + * Notifies the given requestor of all package fragments with the given + * name. Checks the requestor at regular intervals to see if the requestor + * has canceled. The domain of the search is bounded by the + * IJavaProject this NameLookup was obtained + * from. + * + * @param partialMatch + * partial name matches qualify when true; only + * exact name matches qualify when false */ - public void seekPackageFragments(String name, boolean partialMatch, IJavaElementRequestor requestor) { - int count= fPackageFragmentRoots.length; - String matchName= partialMatch ? name.toLowerCase() : name; - for (int i= 0; i < count; i++) { + public void seekPackageFragments(String name, boolean partialMatch, + IJavaElementRequestor requestor) { + int count = fPackageFragmentRoots.length; + String matchName = partialMatch ? name.toLowerCase() : name; + for (int i = 0; i < count; i++) { if (requestor.isCanceled()) return; - IPackageFragmentRoot root= fPackageFragmentRoots[i]; - IJavaElement[] list= null; + IPackageFragmentRoot root = fPackageFragmentRoots[i]; + IJavaElement[] list = null; try { - list= root.getChildren(); + list = root.getChildren(); } catch (JavaModelException npe) { continue; // this root package fragment is not present } - int elementCount= list.length; - for (int j= 0; j < elementCount; j++) { + int elementCount = list.length; + for (int j = 0; j < elementCount; j++) { if (requestor.isCanceled()) return; - IPackageFragment packageFragment= (IPackageFragment) list[j]; + IPackageFragment packageFragment = (IPackageFragment) list[j]; if (nameMatches(matchName, packageFragment, partialMatch)) requestor.acceptPackageFragment(packageFragment); } @@ -526,44 +568,54 @@ public class NameLookup { /** * Notifies the given requestor of all types (classes and interfaces) in the - * given package fragment with the given (unqualified) name. - * Checks the requestor at regular intervals to see if the requestor - * has canceled. If the given package fragment is null, all types in the + * given package fragment with the given (unqualified) name. Checks the + * requestor at regular intervals to see if the requestor has canceled. If + * the given package fragment is null, all types in the * project whose simple name matches the given name are found. - * - * @param name The name to search - * @param pkg The corresponding package fragment - * @param partialMatch partial name matches qualify when true; - * only exact name matches qualify when false - * @param acceptFlags a bit mask describing if classes, interfaces or both classes and interfaces - * are desired results. If no flags are specified, all types are returned. - * @param requestor The requestor that collects the result - * + * + * @param name + * The name to search + * @param pkg + * The corresponding package fragment + * @param partialMatch + * partial name matches qualify when true; only + * exact name matches qualify when false + * @param acceptFlags + * a bit mask describing if classes, interfaces or both classes + * and interfaces are desired results. If no flags are specified, + * all types are returned. + * @param requestor + * The requestor that collects the result + * * @see #ACCEPT_CLASSES * @see #ACCEPT_INTERFACES */ - public void seekTypes(String name, IPackageFragment pkg, boolean partialMatch, int acceptFlags, IJavaElementRequestor requestor) { + public void seekTypes(String name, IPackageFragment pkg, + boolean partialMatch, int acceptFlags, + IJavaElementRequestor requestor) { - String matchName= partialMatch ? name.toLowerCase() : name; - if (matchName.indexOf('.') >= 0) { //looks for member type A.B - matchName= matchName.replace('.', '$'); + String matchName = partialMatch ? name.toLowerCase() : name; + if (matchName.indexOf('.') >= 0) { // looks for member type A.B + matchName = matchName.replace('.', '$'); } if (pkg == null) { findAllTypes(matchName, partialMatch, acceptFlags, requestor); return; } - IPackageFragmentRoot root= (IPackageFragmentRoot) pkg.getParent(); + IPackageFragmentRoot root = (IPackageFragmentRoot) pkg.getParent(); try { - int packageFlavor= root.getKind(); + int packageFlavor = root.getKind(); switch (packageFlavor) { -// case IPackageFragmentRoot.K_BINARY : -// seekTypesInBinaryPackage(matchName, pkg, partialMatch, acceptFlags, requestor); -// break; - case IPackageFragmentRoot.K_SOURCE : - seekTypesInSourcePackage(matchName, pkg, partialMatch, acceptFlags, requestor); - break; - default : - return; + // case IPackageFragmentRoot.K_BINARY : + // seekTypesInBinaryPackage(matchName, pkg, partialMatch, + // acceptFlags, requestor); + // break; + case IPackageFragmentRoot.K_SOURCE: + seekTypesInSourcePackage(matchName, pkg, partialMatch, + acceptFlags, requestor); + break; + default: + return; } } catch (JavaModelException e) { return; @@ -573,193 +625,217 @@ public class NameLookup { /** * Performs type search in a binary package. */ -// protected void seekTypesInBinaryPackage(String name, IPackageFragment pkg, boolean partialMatch, int acceptFlags, IJavaElementRequestor requestor) { -// IClassFile[] classFiles= null; -// try { -// classFiles= pkg.getClassFiles(); -// } catch (JavaModelException npe) { -// return; // the package is not present -// } -// int length= classFiles.length; -// -// String unqualifiedName= name; -// int index= name.lastIndexOf('$'); -// if (index != -1) { -// //the type name of the inner type -// unqualifiedName= name.substring(index + 1, name.length()); -// // unqualifiedName is empty if the name ends with a '$' sign. -// // See http://dev.eclipse.org/bugs/show_bug.cgi?id=14642 -// if ((unqualifiedName.length() > 0 && Character.isDigit(unqualifiedName.charAt(0))) || unqualifiedName.length() == 0){ -// unqualifiedName = name; -// } -// } -// String matchName= partialMatch ? name.toLowerCase() : name; -// for (int i= 0; i < length; i++) { -// if (requestor.isCanceled()) -// return; -// IClassFile classFile= classFiles[i]; -// String elementName = classFile.getElementName(); -// if (partialMatch) elementName = elementName.toLowerCase(); -// -// /** -// * Must use startWith because matchName will never have the -// * extension ".class" and the elementName always will. -// */ -// if (elementName.startsWith(matchName)) { -// IType type= null; -// try { -// type= classFile.getType(); -// } catch (JavaModelException npe) { -// continue; // the classFile is not present -// } -// if (!partialMatch || (type.getElementName().length() > 0 && !Character.isDigit(type.getElementName().charAt(0)))) { //not an anonymous type -// if (nameMatches(unqualifiedName, type, partialMatch) && acceptType(type, acceptFlags)) -// requestor.acceptType(type); -// } -// } -// } -// } - + // protected void seekTypesInBinaryPackage(String name, IPackageFragment + // pkg, boolean partialMatch, int acceptFlags, IJavaElementRequestor + // requestor) { + // IClassFile[] classFiles= null; + // try { + // classFiles= pkg.getClassFiles(); + // } catch (JavaModelException npe) { + // return; // the package is not present + // } + // int length= classFiles.length; + // + // String unqualifiedName= name; + // int index= name.lastIndexOf('$'); + // if (index != -1) { + // //the type name of the inner type + // unqualifiedName= name.substring(index + 1, name.length()); + // // unqualifiedName is empty if the name ends with a '$' sign. + // // See http://dev.eclipse.org/bugs/show_bug.cgi?id=14642 + // if ((unqualifiedName.length() > 0 && + // Character.isDigit(unqualifiedName.charAt(0))) || unqualifiedName.length() + // == 0){ + // unqualifiedName = name; + // } + // } + // String matchName= partialMatch ? name.toLowerCase() : name; + // for (int i= 0; i < length; i++) { + // if (requestor.isCanceled()) + // return; + // IClassFile classFile= classFiles[i]; + // String elementName = classFile.getElementName(); + // if (partialMatch) elementName = elementName.toLowerCase(); + // + // /** + // * Must use startWith because matchName will never have the + // * extension ".class" and the elementName always will. + // */ + // if (elementName.startsWith(matchName)) { + // IType type= null; + // try { + // type= classFile.getType(); + // } catch (JavaModelException npe) { + // continue; // the classFile is not present + // } + // if (!partialMatch || (type.getElementName().length() > 0 && + // !Character.isDigit(type.getElementName().charAt(0)))) { //not an + // anonymous type + // if (nameMatches(unqualifiedName, type, partialMatch) && acceptType(type, + // acceptFlags)) + // requestor.acceptType(type); + // } + // } + // } + // } /** * Performs type search in a source package. */ - protected void seekTypesInSourcePackage(String name, IPackageFragment pkg, boolean partialMatch, int acceptFlags, IJavaElementRequestor requestor) { + protected void seekTypesInSourcePackage(String name, IPackageFragment pkg, + boolean partialMatch, int acceptFlags, + IJavaElementRequestor requestor) { ICompilationUnit[] compilationUnits = null; try { compilationUnits = pkg.getCompilationUnits(); } catch (JavaModelException npe) { return; // the package is not present } - int length= compilationUnits.length; + int length = compilationUnits.length; String matchName = name; - int index= name.indexOf('$'); + int index = name.indexOf('$'); boolean potentialMemberType = false; String potentialMatchName = null; if (index != -1) { - //the compilation unit name of the inner type + // the compilation unit name of the inner type potentialMatchName = name.substring(0, index); potentialMemberType = true; } /** - * In the following, matchName will never have the extension ".java" and - * the compilationUnits always will. So add it if we're looking for - * an exact match. + * In the following, matchName will never have the extension ".java" and + * the compilationUnits always will. So add it if we're looking for an + * exact match. */ - String unitName = partialMatch ? matchName.toLowerCase() : matchName + ".java"; //$NON-NLS-1$ + String unitName = partialMatch ? matchName.toLowerCase() : matchName + + ".java"; //$NON-NLS-1$ String potentialUnitName = null; if (potentialMemberType) { - potentialUnitName = partialMatch ? potentialMatchName.toLowerCase() : potentialMatchName + ".java"; //$NON-NLS-1$ + potentialUnitName = partialMatch ? potentialMatchName.toLowerCase() + : potentialMatchName + ".java"; //$NON-NLS-1$ } - for (int i= 0; i < length; i++) { + for (int i = 0; i < length; i++) { if (requestor.isCanceled()) return; - ICompilationUnit compilationUnit= compilationUnits[i]; - + ICompilationUnit compilationUnit = compilationUnits[i]; + // unit to look inside ICompilationUnit unitToLookInside = null; Map workingCopies = (Map) this.unitsToLookInside.getCurrent(); - if (workingCopies != null - && (unitToLookInside = (ICompilationUnit)workingCopies.get(compilationUnit)) != null){ - compilationUnit = unitToLookInside; - } - if ((unitToLookInside != null && !potentialMemberType) || nameMatches(unitName, compilationUnit, partialMatch)) { - IType[] types= null; + if (workingCopies != null + && (unitToLookInside = (ICompilationUnit) workingCopies + .get(compilationUnit)) != null) { + compilationUnit = unitToLookInside; + } + if ((unitToLookInside != null && !potentialMemberType) + || nameMatches(unitName, compilationUnit, partialMatch)) { + IType[] types = null; try { - types= compilationUnit.getTypes(); + types = compilationUnit.getTypes(); } catch (JavaModelException npe) { continue; // the compilation unit is not present } - int typeLength= types.length; - for (int j= 0; j < typeLength; j++) { + int typeLength = types.length; + for (int j = 0; j < typeLength; j++) { if (requestor.isCanceled()) return; - IType type= types[j]; + IType type = types[j]; if (nameMatches(matchName, type, partialMatch)) { - if (acceptType(type, acceptFlags)) requestor.acceptType(type); + if (acceptType(type, acceptFlags)) + requestor.acceptType(type); } } - } else if (potentialMemberType && nameMatches(potentialUnitName, compilationUnit, partialMatch)) { - IType[] types= null; + } else if (potentialMemberType + && nameMatches(potentialUnitName, compilationUnit, + partialMatch)) { + IType[] types = null; try { - types= compilationUnit.getTypes(); + types = compilationUnit.getTypes(); } catch (JavaModelException npe) { continue; // the compilation unit is not present } - int typeLength= types.length; - for (int j= 0; j < typeLength; j++) { + int typeLength = types.length; + for (int j = 0; j < typeLength; j++) { if (requestor.isCanceled()) return; - IType type= types[j]; + IType type = types[j]; if (nameMatches(potentialMatchName, type, partialMatch)) { - seekQualifiedMemberTypes(name.substring(index + 1, name.length()), type, partialMatch, requestor, acceptFlags); + seekQualifiedMemberTypes(name.substring(index + 1, name + .length()), type, partialMatch, requestor, + acceptFlags); } } } } } -/** - * Remembers a set of compilation units that will be looked inside - * when looking up a type. If they are working copies, they take - * precedence of their compilation units. - * null means that no special compilation units should be used. - */ -public void setUnitsToLookInside(IWorkingCopy[] unitsToLookInside) { - - if (unitsToLookInside == null) { - this.unitsToLookInside.setCurrent(null); - } else { - HashMap workingCopies = new HashMap(); - this.unitsToLookInside.setCurrent(workingCopies); - for (int i = 0, length = unitsToLookInside.length; i < length; i++) { - IWorkingCopy unitToLookInside = unitsToLookInside[i]; - ICompilationUnit original = (ICompilationUnit)unitToLookInside.getOriginalElement(); - if (original != null) { - workingCopies.put(original, unitToLookInside); - } else { - workingCopies.put(unitToLookInside, unitToLookInside); + + /** + * Remembers a set of compilation units that will be looked inside when + * looking up a type. If they are working copies, they take precedence of + * their compilation units. null means that no special + * compilation units should be used. + */ + public void setUnitsToLookInside(IWorkingCopy[] unitsToLookInside) { + + if (unitsToLookInside == null) { + this.unitsToLookInside.setCurrent(null); + } else { + HashMap workingCopies = new HashMap(); + this.unitsToLookInside.setCurrent(workingCopies); + for (int i = 0, length = unitsToLookInside.length; i < length; i++) { + IWorkingCopy unitToLookInside = unitsToLookInside[i]; + ICompilationUnit original = (ICompilationUnit) unitToLookInside + .getOriginalElement(); + if (original != null) { + workingCopies.put(original, unitToLookInside); + } else { + workingCopies.put(unitToLookInside, unitToLookInside); + } } } } -} /** * Notifies the given requestor of all types (classes and interfaces) in the - * given type with the given (possibly qualified) name. Checks - * the requestor at regular intervals to see if the requestor - * has canceled. - * - * @param partialMatch partial name matches qualify when true, - * only exact name matches qualify when false + * given type with the given (possibly qualified) name. Checks the requestor + * at regular intervals to see if the requestor has canceled. + * + * @param partialMatch + * partial name matches qualify when true, only + * exact name matches qualify when false */ - protected void seekQualifiedMemberTypes(String qualifiedName, IType type, boolean partialMatch, IJavaElementRequestor requestor, int acceptFlags) { + protected void seekQualifiedMemberTypes(String qualifiedName, IType type, + boolean partialMatch, IJavaElementRequestor requestor, + int acceptFlags) { if (type == null) return; - IType[] types= null; + IType[] types = null; try { - types= type.getTypes(); + types = type.getTypes(); } catch (JavaModelException npe) { return; // the enclosing type is not present } - String matchName= qualifiedName; - int index= qualifiedName.indexOf('$'); - boolean nested= false; + String matchName = qualifiedName; + int index = qualifiedName.indexOf('$'); + boolean nested = false; if (index != -1) { - matchName= qualifiedName.substring(0, index); - nested= true; + matchName = qualifiedName.substring(0, index); + nested = true; } - int length= types.length; - for (int i= 0; i < length; i++) { + int length = types.length; + for (int i = 0; i < length; i++) { if (requestor.isCanceled()) return; - IType memberType= types[i]; + IType memberType = types[i]; if (nameMatches(matchName, memberType, partialMatch)) if (nested) { - seekQualifiedMemberTypes(qualifiedName.substring(index + 1, qualifiedName.length()), memberType, partialMatch, requestor, acceptFlags); + seekQualifiedMemberTypes(qualifiedName.substring(index + 1, + qualifiedName.length()), memberType, partialMatch, + requestor, acceptFlags); } else { - if (acceptType(memberType, acceptFlags)) requestor.acceptMemberType(memberType); + if (acceptType(memberType, acceptFlags)) + requestor.acceptMemberType(memberType); } } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Openable.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Openable.java index 1364b4f..7b9b52c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Openable.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Openable.java @@ -36,603 +36,723 @@ import org.eclipse.core.runtime.IProgressMonitor; /** * Abstract class for implementations of java elements which are IOpenable. - * + * * @see IJavaElement * @see IOpenable */ -public abstract class Openable extends JavaElement implements IOpenable, IBufferChangedListener { +public abstract class Openable extends JavaElement implements IOpenable, + IBufferChangedListener { + + protected Openable(JavaElement parent, String name) { + super(parent, name); + } -protected Openable(JavaElement parent, String name) { - super(parent, name); -} /** - * The buffer associated with this element has changed. Registers - * this element as being out of synch with its buffer's contents. - * If the buffer has been closed, this element is set as NOT out of - * synch with the contents. - * + * The buffer associated with this element has changed. Registers this + * element as being out of synch with its buffer's contents. If the buffer + * has been closed, this element is set as NOT out of synch with the + * contents. + * * @see IBufferChangedListener */ public void bufferChanged(BufferChangedEvent event) { if (event.getBuffer().isClosed()) { - JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().remove(this); + JavaModelManager.getJavaModelManager() + .getElementsOutOfSynchWithBuffers().remove(this); getBufferManager().removeBuffer(event.getBuffer()); } else { - JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().put(this, this); + JavaModelManager.getJavaModelManager() + .getElementsOutOfSynchWithBuffers().put(this, this); } } /** - * Builds this element's structure and properties in the given - * info object, based on this element's current contents (reuse buffer - * contents if this element has an open buffer, or resource contents - * if this element does not have an open buffer). Children - * are placed in the given newElements table (note, this element - * has already been placed in the newElements table). Returns true - * if successful, or false if an error is encountered while determining - * the structure of this element. + * Builds this element's structure and properties in the given info object, + * based on this element's current contents (reuse buffer contents if this + * element has an open buffer, or resource contents if this element does not + * have an open buffer). Children are placed in the given newElements table + * (note, this element has already been placed in the newElements table). + * Returns true if successful, or false if an error is encountered while + * determining the structure of this element. */ - protected abstract boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException; - -///** -// * Updates the info objects for this element and all of its children by -// * removing the current infos, generating new infos, and then placing -// * the new infos into the Java Model cache tables. -// */ -//protected void buildStructure(OpenableElementInfo info, IProgressMonitor monitor) throws JavaModelException { -// -// if (monitor != null && monitor.isCanceled()) return; -// -// // remove existing (old) infos -// removeInfo(); -// HashMap newElements = new HashMap(11); -// info.setIsStructureKnown(generateInfos(info, monitor, newElements, getResource())); -// JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().remove(this); -// for (Iterator iter = newElements.keySet().iterator(); iter.hasNext();) { -// IJavaElement key = (IJavaElement) iter.next(); -// Object value = newElements.get(key); -// JavaModelManager.getJavaModelManager().putInfo(key, value); -// } -// -// // add the info for this at the end, to ensure that a getInfo cannot reply null in case the LRU cache needs -// // to be flushed. Might lead to performance issues. -// // see PR 1G2K5S7: ITPJCORE:ALL - NPE when accessing source for a binary type -// JavaModelManager.getJavaModelManager().putInfo(this, info); -//} -/* - * Returns whether this element can be removed from the Java model cache to make space. - */ -public boolean canBeRemovedFromCache() { - try { - return !hasUnsavedChanges(); - } catch (JavaModelException e) { - return false; - } -} -/* - * Returns whether the buffer of this element can be removed from the Java model cache to make space. - */ -public boolean canBufferBeRemovedFromCache(IBuffer buffer) { - return !buffer.hasUnsavedChanges(); -} -/** - * Close the buffer associated with this element, if any. - */ -protected void closeBuffer() { - if (!hasBuffer()) return; // nothing to do - IBuffer buffer = getBufferManager().getBuffer(this); - if (buffer != null) { - buffer.close(); - buffer.removeBufferChangedListener(this); + protected abstract boolean buildStructure(OpenableElementInfo info, + IProgressMonitor pm, Map newElements, IResource underlyingResource) + throws JavaModelException; + + // /** + // * Updates the info objects for this element and all of its children by + // * removing the current infos, generating new infos, and then placing + // * the new infos into the Java Model cache tables. + // */ + // protected void buildStructure(OpenableElementInfo info, IProgressMonitor + // monitor) throws JavaModelException { + // + // if (monitor != null && monitor.isCanceled()) return; + // + // // remove existing (old) infos + // removeInfo(); + // HashMap newElements = new HashMap(11); + // info.setIsStructureKnown(generateInfos(info, monitor, newElements, + // getResource())); + // JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().remove(this); + // for (Iterator iter = newElements.keySet().iterator(); iter.hasNext();) { + // IJavaElement key = (IJavaElement) iter.next(); + // Object value = newElements.get(key); + // JavaModelManager.getJavaModelManager().putInfo(key, value); + // } + // + // // add the info for this at the end, to ensure that a getInfo cannot + // reply null in case the LRU cache needs + // // to be flushed. Might lead to performance issues. + // // see PR 1G2K5S7: ITPJCORE:ALL - NPE when accessing source for a binary + // type + // JavaModelManager.getJavaModelManager().putInfo(this, info); + // } + /* + * Returns whether this element can be removed from the Java model cache to + * make space. + */ + public boolean canBeRemovedFromCache() { + try { + return !hasUnsavedChanges(); + } catch (JavaModelException e) { + return false; + } } -} -/** - * Close the buffer associated with this element, if any. - */ -protected void closeBuffer(OpenableElementInfo info) { - if (!hasBuffer()) return; // nothing to do - IBuffer buffer = null; - buffer = getBufferManager().getBuffer(this); - if (buffer != null) { - buffer.close(); - buffer.removeBufferChangedListener(this); + + /* + * Returns whether the buffer of this element can be removed from the Java + * model cache to make space. + */ + public boolean canBufferBeRemovedFromCache(IBuffer buffer) { + return !buffer.hasUnsavedChanges(); } -} -/** - * This element is being closed. Do any necessary cleanup. - */ -protected void closing(Object info) { - closeBuffer(); -} -///** -// * @see ICodeAssist -// */ -//protected void codeComplete(net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit cu, net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit unitToSkip, int position, ICompletionRequestor requestor) throws JavaModelException { -// if (requestor == null) { -// throw new IllegalArgumentException(ProjectPrefUtil.bind("codeAssist.nullRequestor")); //$NON-NLS-1$ -// } -// IBuffer buffer = getBuffer(); -// if (buffer == null) { -// return; -// } -// if (position < -1 || position > buffer.getLength()) { -// throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS)); -// } -// JavaProject project = (JavaProject) getJavaProject(); -// SearchableEnvironment environment = (SearchableEnvironment) project.getSearchableNameEnvironment(); -// NameLookup nameLookup = project.getNameLookup(); -// environment.unitToSkip = unitToSkip; -// -// CompletionEngine engine = new CompletionEngine(environment, new CompletionRequestorWrapper(requestor,nameLookup), project.getOptions(true), project); -// engine.complete(cu, position, 0); -// environment.unitToSkip = null; -//} -/** - * @see ICodeAssist - */ -//protected IJavaElement[] codeSelect(net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit cu, int offset, int length) throws JavaModelException { -// SelectionRequestor requestor= new SelectionRequestor(((JavaProject)getJavaProject()).getNameLookup(), this); -// this.codeSelect(cu, offset, length, requestor); -// return requestor.getElements(); -//} -/** - * @see ICodeAssist - */ -//protected void codeSelect(net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit cu, int offset, int length, ISelectionRequestor requestor) throws JavaModelException { -// IBuffer buffer = getBuffer(); -// if (buffer == null) { -// return; -// } -// int end= buffer.getLength(); -// if (offset < 0 || length < 0 || offset + length > end ) { -// throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS)); -// } -// -// // fix for 1FVGGKF -// JavaProject project = (JavaProject)getJavaProject(); -// ISearchableNameEnvironment environment = project.getSearchableNameEnvironment(); -// -// // fix for 1FVXGDK -// SelectionEngine engine = new SelectionEngine(environment, requestor, project.getOptions(true)); -// engine.select(cu, offset, offset + length - 1); -//} -/* - * Returns a new element info for this element. - */ -protected Object createElementInfo() { - return new OpenableElementInfo(); -} -///** -// * Builds this element's structure and properties in the given -// * info object, based on this element's current contents (reuse buffer -// * contents if this element has an open buffer, or resource contents -// * if this element does not have an open buffer). Children -// * are placed in the given newElements table (note, this element -// * has already been placed in the newElements table). Returns true -// * if successful, or false if an error is encountered while determining -// * the structure of this element. -// */ -//protected abstract boolean generateInfos(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException; - -protected void generateInfos(Object info, HashMap newElements, IProgressMonitor monitor) throws JavaModelException { - - if (JavaModelManager.VERBOSE){ - System.out.println("OPENING Element ("+ Thread.currentThread()+"): " + this.toStringWithAncestors()); //$NON-NLS-1$//$NON-NLS-2$ + /** + * Close the buffer associated with this element, if any. + */ + protected void closeBuffer() { + if (!hasBuffer()) + return; // nothing to do + IBuffer buffer = getBufferManager().getBuffer(this); + if (buffer != null) { + buffer.close(); + buffer.removeBufferChangedListener(this); + } } - // open the parent if necessary - openParent(info, newElements, monitor); - if (monitor != null && monitor.isCanceled()) return; - - // puts the info before building the structure so that questions to the handle behave as if the element existed - // (case of compilation units becoming working copies) - newElements.put(this, info); - - // build the structure of the openable (this will open the buffer if needed) - try { - OpenableElementInfo openableElementInfo = (OpenableElementInfo)info; - boolean isStructureKnown = buildStructure(openableElementInfo, monitor, newElements, getResource()); - openableElementInfo.setIsStructureKnown(isStructureKnown); - } catch (JavaModelException e) { - newElements.remove(this); - throw e; + /** + * Close the buffer associated with this element, if any. + */ + protected void closeBuffer(OpenableElementInfo info) { + if (!hasBuffer()) + return; // nothing to do + IBuffer buffer = null; + buffer = getBufferManager().getBuffer(this); + if (buffer != null) { + buffer.close(); + buffer.removeBufferChangedListener(this); + } } - // remove out of sync buffer for this element - JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().remove(this); + /** + * This element is being closed. Do any necessary cleanup. + */ + protected void closing(Object info) { + closeBuffer(); + } - if (JavaModelManager.VERBOSE) { - System.out.println("-> Package cache size = " + JavaModelManager.getJavaModelManager().cache.pkgSize()); //$NON-NLS-1$ - System.out.println("-> Openable cache filling ratio = " + NumberFormat.getInstance().format(JavaModelManager.getJavaModelManager().cache.openableFillingRatio()) + "%"); //$NON-NLS-1$//$NON-NLS-2$ + // /** + // * @see ICodeAssist + // */ + // protected void + // codeComplete(net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit + // cu, net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit + // unitToSkip, int position, ICompletionRequestor requestor) throws + // JavaModelException { + // if (requestor == null) { + // throw new + // IllegalArgumentException(ProjectPrefUtil.bind("codeAssist.nullRequestor")); + // //$NON-NLS-1$ + // } + // IBuffer buffer = getBuffer(); + // if (buffer == null) { + // return; + // } + // if (position < -1 || position > buffer.getLength()) { + // throw new JavaModelException(new + // JavaModelStatus(IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS)); + // } + // JavaProject project = (JavaProject) getJavaProject(); + // SearchableEnvironment environment = (SearchableEnvironment) + // project.getSearchableNameEnvironment(); + // NameLookup nameLookup = project.getNameLookup(); + // environment.unitToSkip = unitToSkip; + // + // CompletionEngine engine = new CompletionEngine(environment, new + // CompletionRequestorWrapper(requestor,nameLookup), + // project.getOptions(true), project); + // engine.complete(cu, position, 0); + // environment.unitToSkip = null; + // } + /** + * @see ICodeAssist + */ + // protected IJavaElement[] + // codeSelect(net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit + // cu, int offset, int length) throws JavaModelException { + // SelectionRequestor requestor= new + // SelectionRequestor(((JavaProject)getJavaProject()).getNameLookup(), + // this); + // this.codeSelect(cu, offset, length, requestor); + // return requestor.getElements(); + // } + /** + * @see ICodeAssist + */ + // protected void + // codeSelect(net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit + // cu, int offset, int length, ISelectionRequestor requestor) throws + // JavaModelException { + // IBuffer buffer = getBuffer(); + // if (buffer == null) { + // return; + // } + // int end= buffer.getLength(); + // if (offset < 0 || length < 0 || offset + length > end ) { + // throw new JavaModelException(new + // JavaModelStatus(IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS)); + // } + // + // // fix for 1FVGGKF + // JavaProject project = (JavaProject)getJavaProject(); + // ISearchableNameEnvironment environment = + // project.getSearchableNameEnvironment(); + // + // // fix for 1FVXGDK + // SelectionEngine engine = new SelectionEngine(environment, requestor, + // project.getOptions(true)); + // engine.select(cu, offset, offset + length - 1); + // } + /* + * Returns a new element info for this element. + */ + protected Object createElementInfo() { + return new OpenableElementInfo(); } -} -/** - * Note: a buffer with no unsaved changes can be closed by the Java Model - * since it has a finite number of buffers allowed open at one time. If this - * is the first time a request is being made for the buffer, an attempt is - * made to create and fill this element's buffer. If the buffer has been - * closed since it was first opened, the buffer is re-created. - * - * @see IOpenable - */ -public IBuffer getBuffer() throws JavaModelException { - if (hasBuffer()) { - // ensure element is open - if (!isOpen()) { - getElementInfo(); + + // /** + // * Builds this element's structure and properties in the given + // * info object, based on this element's current contents (reuse buffer + // * contents if this element has an open buffer, or resource contents + // * if this element does not have an open buffer). Children + // * are placed in the given newElements table (note, this element + // * has already been placed in the newElements table). Returns true + // * if successful, or false if an error is encountered while determining + // * the structure of this element. + // */ + // protected abstract boolean generateInfos(OpenableElementInfo info, + // IProgressMonitor pm, Map newElements, IResource underlyingResource) + // throws JavaModelException; + + protected void generateInfos(Object info, HashMap newElements, + IProgressMonitor monitor) throws JavaModelException { + + if (JavaModelManager.VERBOSE) { + System.out + .println("OPENING Element (" + Thread.currentThread() + "): " + this.toStringWithAncestors()); //$NON-NLS-1$//$NON-NLS-2$ } - IBuffer buffer = getBufferManager().getBuffer(this); - if (buffer == null) { - // try to (re)open a buffer - buffer = openBuffer(null); + + // open the parent if necessary + openParent(info, newElements, monitor); + if (monitor != null && monitor.isCanceled()) + return; + + // puts the info before building the structure so that questions to the + // handle behave as if the element existed + // (case of compilation units becoming working copies) + newElements.put(this, info); + + // build the structure of the openable (this will open the buffer if + // needed) + try { + OpenableElementInfo openableElementInfo = (OpenableElementInfo) info; + boolean isStructureKnown = buildStructure(openableElementInfo, + monitor, newElements, getResource()); + openableElementInfo.setIsStructureKnown(isStructureKnown); + } catch (JavaModelException e) { + newElements.remove(this); + throw e; + } + + // remove out of sync buffer for this element + JavaModelManager.getJavaModelManager() + .getElementsOutOfSynchWithBuffers().remove(this); + + if (JavaModelManager.VERBOSE) { + System.out + .println("-> Package cache size = " + JavaModelManager.getJavaModelManager().cache.pkgSize()); //$NON-NLS-1$ + System.out + .println("-> Openable cache filling ratio = " + NumberFormat.getInstance().format(JavaModelManager.getJavaModelManager().cache.openableFillingRatio()) + "%"); //$NON-NLS-1$//$NON-NLS-2$ } - return buffer; - } else { - return null; } -} -/** - * Answers the buffer factory to use for creating new buffers - */ -public IBufferFactory getBufferFactory(){ - return getBufferManager().getDefaultBufferFactory(); -} + /** + * Note: a buffer with no unsaved changes can be closed by the Java Model + * since it has a finite number of buffers allowed open at one time. If this + * is the first time a request is being made for the buffer, an attempt is + * made to create and fill this element's buffer. If the buffer has been + * closed since it was first opened, the buffer is re-created. + * + * @see IOpenable + */ + public IBuffer getBuffer() throws JavaModelException { + if (hasBuffer()) { + // ensure element is open + if (!isOpen()) { + getElementInfo(); + } + IBuffer buffer = getBufferManager().getBuffer(this); + if (buffer == null) { + // try to (re)open a buffer + buffer = openBuffer(null); + } + return buffer; + } else { + return null; + } + } -/** - * Returns the buffer manager for this element. - */ -protected BufferManager getBufferManager() { - return BufferManager.getDefaultBufferManager(); -} -/** - * Return my underlying resource. Elements that may not have a - * corresponding resource must override this method. - * - * @see IJavaElement - */ -public IResource getCorrespondingResource() throws JavaModelException { - return getUnderlyingResource(); -} -/* - * @see IJavaElement - */ -public IOpenable getOpenable() { - return this; -} + /** + * Answers the buffer factory to use for creating new buffers + */ + public IBufferFactory getBufferFactory() { + return getBufferManager().getDefaultBufferFactory(); + } + /** + * Returns the buffer manager for this element. + */ + protected BufferManager getBufferManager() { + return BufferManager.getDefaultBufferManager(); + } + /** + * Return my underlying resource. Elements that may not have a corresponding + * resource must override this method. + * + * @see IJavaElement + */ + public IResource getCorrespondingResource() throws JavaModelException { + return getUnderlyingResource(); + } -/** - * @see IJavaElement - */ -public IResource getUnderlyingResource() throws JavaModelException { - IResource parentResource = parent.getUnderlyingResource(); - if (parentResource == null) { - return null; + /* + * @see IJavaElement + */ + public IOpenable getOpenable() { + return this; } - int type = parentResource.getType(); - if (type == IResource.FOLDER || type == IResource.PROJECT) { - IContainer folder = (IContainer) parentResource; - IResource resource = folder.findMember(name); - if (resource == null) { - throw newNotPresentException(); + + /** + * @see IJavaElement + */ + public IResource getUnderlyingResource() throws JavaModelException { + IResource parentResource = parent.getUnderlyingResource(); + if (parentResource == null) { + return null; + } + int type = parentResource.getType(); + if (type == IResource.FOLDER || type == IResource.PROJECT) { + IContainer folder = (IContainer) parentResource; + IResource resource = folder.findMember(name); + if (resource == null) { + throw newNotPresentException(); + } else { + return resource; + } } else { - return resource; + return parentResource; } - } else { - return parentResource; } -} -public boolean exists() { + public boolean exists() { - IPackageFragmentRoot root = this.getPackageFragmentRoot(); - if (root == null || root == this || !root.isArchive()) { - return parentExists() && resourceExists(); - } else { - return super.exists(); + IPackageFragmentRoot root = this.getPackageFragmentRoot(); + if (root == null || root == this || !root.isArchive()) { + return parentExists() && resourceExists(); + } else { + return super.exists(); + } } -} -/** - * Returns true if this element may have an associated source buffer, - * otherwise false. Subclasses must override as required. - */ -protected boolean hasBuffer() { - return false; -} -/** - * @see IParent - */ -public boolean hasChildren() throws JavaModelException { - return getChildren().length > 0; -} -/** - * @see IOpenable - */ -public boolean hasUnsavedChanges() throws JavaModelException{ - - if (isReadOnly() || !isOpen()) { + /** + * Returns true if this element may have an associated source buffer, + * otherwise false. Subclasses must override as required. + */ + protected boolean hasBuffer() { return false; } - IBuffer buf = this.getBuffer(); - if (buf != null && buf.hasUnsavedChanges()) { - return true; + + /** + * @see IParent + */ + public boolean hasChildren() throws JavaModelException { + return getChildren().length > 0; } -// for package fragments, package fragment roots, and projects must check open buffers - // to see if they have an child with unsaved changes - int elementType = getElementType(); - if (elementType == PACKAGE_FRAGMENT || - elementType == PACKAGE_FRAGMENT_ROOT || - elementType == JAVA_PROJECT || - elementType == JAVA_MODEL) { // fix for 1FWNMHH - Enumeration openBuffers= getBufferManager().getOpenBuffers(); - while (openBuffers.hasMoreElements()) { - IBuffer buffer= (IBuffer)openBuffers.nextElement(); - if (buffer.hasUnsavedChanges()) { - IJavaElement owner= (IJavaElement)buffer.getOwner(); - if (isAncestorOf(owner)) { - return true; + + /** + * @see IOpenable + */ + public boolean hasUnsavedChanges() throws JavaModelException { + + if (isReadOnly() || !isOpen()) { + return false; + } + IBuffer buf = this.getBuffer(); + if (buf != null && buf.hasUnsavedChanges()) { + return true; + } + // for package fragments, package fragment roots, and projects must + // check open buffers + // to see if they have an child with unsaved changes + int elementType = getElementType(); + if (elementType == PACKAGE_FRAGMENT + || elementType == PACKAGE_FRAGMENT_ROOT + || elementType == JAVA_PROJECT || elementType == JAVA_MODEL) { // fix + // for + // 1FWNMHH + Enumeration openBuffers = getBufferManager().getOpenBuffers(); + while (openBuffers.hasMoreElements()) { + IBuffer buffer = (IBuffer) openBuffers.nextElement(); + if (buffer.hasUnsavedChanges()) { + IJavaElement owner = (IJavaElement) buffer.getOwner(); + if (isAncestorOf(owner)) { + return true; + } } } } + + return false; } - return false; -} -/** - * Subclasses must override as required. - * - * @see IOpenable - */ -public boolean isConsistent() throws JavaModelException { - return true; -} -/** - * - * @see IOpenable - */ -public boolean isOpen() { - synchronized(JavaModelManager.getJavaModelManager()){ - return JavaModelManager.getJavaModelManager().getInfo(this) != null; + /** + * Subclasses must override as required. + * + * @see IOpenable + */ + public boolean isConsistent() throws JavaModelException { + return true; } -} -/** - * Returns true if this represents a source element. - * Openable source elements have an associated buffer created - * when they are opened. - */ -protected boolean isSourceElement() { - return false; -} -///** -// * @see IOpenable -// */ -//public void makeConsistent(IProgressMonitor pm) throws JavaModelException { -// if (!isConsistent()) { -// buildStructure((OpenableElementInfo)getElementInfo(), pm); -// } -//} -/** - * @see IOpenable - */ -public void makeConsistent(IProgressMonitor monitor) throws JavaModelException { - if (isConsistent()) return; - - // create a new info and make it the current info - // (this will remove the info and its children just before storing the new infos) - JavaModelManager manager = JavaModelManager.getJavaModelManager(); - boolean hadTemporaryCache = manager.hasTemporaryCache(); - try { - HashMap newElements = manager.getTemporaryCache(); - openWhenClosed(newElements, monitor); - if (newElements.get(this) == null) { - // close any buffer that was opened for the new elements - Iterator iterator = newElements.keySet().iterator(); - while (iterator.hasNext()) { - IJavaElement element = (IJavaElement)iterator.next(); - if (element instanceof Openable) { - ((Openable)element).closeBuffer(); + + /** + * + * @see IOpenable + */ + public boolean isOpen() { + synchronized (JavaModelManager.getJavaModelManager()) { + return JavaModelManager.getJavaModelManager().getInfo(this) != null; + } + } + + /** + * Returns true if this represents a source element. Openable source + * elements have an associated buffer created when they are opened. + */ + protected boolean isSourceElement() { + return false; + } + + // /** + // * @see IOpenable + // */ + // public void makeConsistent(IProgressMonitor pm) throws JavaModelException + // { + // if (!isConsistent()) { + // buildStructure((OpenableElementInfo)getElementInfo(), pm); + // } + // } + /** + * @see IOpenable + */ + public void makeConsistent(IProgressMonitor monitor) + throws JavaModelException { + if (isConsistent()) + return; + + // create a new info and make it the current info + // (this will remove the info and its children just before storing the + // new infos) + JavaModelManager manager = JavaModelManager.getJavaModelManager(); + boolean hadTemporaryCache = manager.hasTemporaryCache(); + try { + HashMap newElements = manager.getTemporaryCache(); + openWhenClosed(newElements, monitor); + if (newElements.get(this) == null) { + // close any buffer that was opened for the new elements + Iterator iterator = newElements.keySet().iterator(); + while (iterator.hasNext()) { + IJavaElement element = (IJavaElement) iterator.next(); + if (element instanceof Openable) { + ((Openable) element).closeBuffer(); + } } + throw newNotPresentException(); + } + if (!hadTemporaryCache) { + manager.putInfos(this, newElements); + } + } finally { + if (!hadTemporaryCache) { + manager.resetTemporaryCache(); } - throw newNotPresentException(); - } - if (!hadTemporaryCache) { - manager.putInfos(this, newElements); - } - } finally { - if (!hadTemporaryCache) { - manager.resetTemporaryCache(); } } -} - -/** - * @see IOpenable - */ -public void open(IProgressMonitor pm) throws JavaModelException { - getElementInfo(pm); -} -/** - * Opens a buffer on the contents of this element, and returns - * the buffer, or returns null if opening fails. - * By default, do nothing - subclasses that have buffers - * must override as required. - */ -protected IBuffer openBuffer(IProgressMonitor pm) throws JavaModelException { - return null; -} -/** - * Open the parent element if necessary. - */ -protected void openParent(Object childInfo, HashMap newElements, IProgressMonitor pm) throws JavaModelException { + /** + * @see IOpenable + */ + public void open(IProgressMonitor pm) throws JavaModelException { + getElementInfo(pm); + } - Openable openableParent = (Openable)getOpenableParent(); - if (openableParent != null && !openableParent.isOpen()){ - openableParent.generateInfos(openableParent.createElementInfo(), newElements, pm); + /** + * Opens a buffer on the contents of this element, and returns the buffer, + * or returns null if opening fails. By default, do nothing - + * subclasses that have buffers must override as required. + */ + protected IBuffer openBuffer(IProgressMonitor pm) throws JavaModelException { + return null; } -} -///** -// * Open an Openable that is known to be closed (no check for isOpen()). -// */ -//protected void openWhenClosed(IProgressMonitor pm) throws JavaModelException { -// try { -// -// if (JavaModelManager.VERBOSE){ -// System.out.println("OPENING Element ("+ Thread.currentThread()+"): " + this.toStringWithAncestors()); //$NON-NLS-1$//$NON-NLS-2$ -// } -// -// // 1) Parent must be open - open the parent if necessary -// openParent(pm); -// -// // 2) create the new element info and open a buffer if needed -// OpenableElementInfo info = createElementInfo(); -// if (isSourceElement()) { -// this.openBuffer(pm); -// } -// -// // 3) build the structure of the openable -// buildStructure(info, pm); -// -// // 4) anything special -// opening(info); -// -//// if (JavaModelManager.VERBOSE) { -//// System.out.println("-> Package cache size = " + JavaModelManager.getJavaModelManager().cache.pkgSize()); //$NON-NLS-1$ -//// System.out.println("-> Openable cache filling ratio = " + JavaModelManager.getJavaModelManager().cache.openableFillingRatio() + "%"); //$NON-NLS-1$//$NON-NLS-2$ -//// } -// -// // if any problems occuring openning the element, ensure that it's info -// // does not remain in the cache (some elements, pre-cache their info -// // as they are being opened). -// } catch (JavaModelException e) { -// JavaModelManager.getJavaModelManager().removeInfo(this); -// throw e; -// } -//} + /** + * Open the parent element if necessary. + */ + protected void openParent(Object childInfo, HashMap newElements, + IProgressMonitor pm) throws JavaModelException { -/** - * Answers true if the parent exists (null parent is answering true) - * - */ -protected boolean parentExists(){ + Openable openableParent = (Openable) getOpenableParent(); + if (openableParent != null && !openableParent.isOpen()) { + openableParent.generateInfos(openableParent.createElementInfo(), + newElements, pm); + } + } - IJavaElement parent = this.getParent(); - if (parent == null) return true; - return parent.exists(); -} + // /** + // * Open an Openable that is known to be closed (no check for + // isOpen()). + // */ + // protected void openWhenClosed(IProgressMonitor pm) throws + // JavaModelException { + // try { + // + // if (JavaModelManager.VERBOSE){ + // System.out.println("OPENING Element ("+ Thread.currentThread()+"): " + + // this.toStringWithAncestors()); //$NON-NLS-1$//$NON-NLS-2$ + // } + // + // // 1) Parent must be open - open the parent if necessary + // openParent(pm); + // + // // 2) create the new element info and open a buffer if needed + // OpenableElementInfo info = createElementInfo(); + // if (isSourceElement()) { + // this.openBuffer(pm); + // } + // + // // 3) build the structure of the openable + // buildStructure(info, pm); + // + // // 4) anything special + // opening(info); + // + // // if (JavaModelManager.VERBOSE) { + // // System.out.println("-> Package cache size = " + + // JavaModelManager.getJavaModelManager().cache.pkgSize()); //$NON-NLS-1$ + // // System.out.println("-> Openable cache filling ratio = " + + // JavaModelManager.getJavaModelManager().cache.openableFillingRatio() + + // "%"); //$NON-NLS-1$//$NON-NLS-2$ + // // } + // + // // if any problems occuring openning the element, ensure that it's info + // // does not remain in the cache (some elements, pre-cache their info + // // as they are being opened). + // } catch (JavaModelException e) { + // JavaModelManager.getJavaModelManager().removeInfo(this); + // throw e; + // } + // } -/** - * Returns whether the corresponding resource or associated file exists - */ -protected boolean resourceExists() { - IWorkspace workspace = ResourcesPlugin.getWorkspace(); - if (workspace == null) return false; // workaround for http://bugs.eclipse.org/bugs/show_bug.cgi?id=34069 - return - JavaModel.getTarget( - workspace.getRoot(), - this.getPath().makeRelative(), // ensure path is relative (see http://dev.eclipse.org/bugs/show_bug.cgi?id=22517) - true) != null; -} + /** + * Answers true if the parent exists (null parent is answering true) + * + */ + protected boolean parentExists() { -/** - * @see IOpenable - */ -public void save(IProgressMonitor pm, boolean force) throws JavaModelException { - if (isReadOnly() || this.getResource().getResourceAttributes().isReadOnly()) { - throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this)); + IJavaElement parent = this.getParent(); + if (parent == null) + return true; + return parent.exists(); } - IBuffer buf = getBuffer(); - if (buf != null) { // some Openables (like a JavaProject) don't have a buffer - buf.save(pm, force); - this.makeConsistent(pm); // update the element info of this element + + /** + * Returns whether the corresponding resource or associated file exists + */ + protected boolean resourceExists() { + IWorkspace workspace = ResourcesPlugin.getWorkspace(); + if (workspace == null) + return false; // workaround for + // http://bugs.eclipse.org/bugs/show_bug.cgi?id=34069 + return JavaModel.getTarget(workspace.getRoot(), this.getPath() + .makeRelative(), // ensure path is relative (see + // http://dev.eclipse.org/bugs/show_bug.cgi?id=22517) + true) != null; } -} -/** - * Find enclosing package fragment root if any - */ -public PackageFragmentRoot getPackageFragmentRoot() { - IJavaElement current = this; - do { - if (current instanceof PackageFragmentRoot) return (PackageFragmentRoot)current; - current = current.getParent(); - } while(current != null); - return null; -} -///** -// * @see ICodeAssist -// * @deprecated - use codeComplete(ICompilationUnit, ICompilationUnit, int, ICompletionRequestor) instead -// */ -//protected void codeComplete(net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit cu, net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit unitToSkip, int position, final ICodeCompletionRequestor requestor) throws JavaModelException { -// -// if (requestor == null){ -// codeComplete(cu, unitToSkip, position, (ICompletionRequestor)null); -// return; -// } -// codeComplete( -// cu, -// unitToSkip, -// position, -// new ICompletionRequestor(){ -// public void acceptAnonymousType(char[] superTypePackageName,char[] superTypeName,char[][] parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance) { -// } -// public void acceptClass(char[] packageName, char[] className, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) { -// requestor.acceptClass(packageName, className, completionName, modifiers, completionStart, completionEnd); -// } -// public void acceptError(IProblem error) { -// if (true) return; // was disabled in 1.0 -// -// try { -// IMarker marker = ResourcesPlugin.getWorkspace().getRoot().createMarker(IJavaModelMarker.TRANSIENT_PROBLEM); -// marker.setAttribute(IJavaModelMarker.ID, error.getID()); -// marker.setAttribute(IMarker.CHAR_START, error.getSourceStart()); -// marker.setAttribute(IMarker.CHAR_END, error.getSourceEnd() + 1); -// marker.setAttribute(IMarker.LINE_NUMBER, error.getSourceLineNumber()); -// marker.setAttribute(IMarker.MESSAGE, error.getMessage()); -// marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); -// requestor.acceptError(marker); -// } catch(CoreException e){ -// } -// } -// public void acceptField(char[] declaringTypePackageName, char[] declaringTypeName, char[] name, char[] typePackageName, char[] typeName, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) { -// requestor.acceptField(declaringTypePackageName, declaringTypeName, name, typePackageName, typeName, completionName, modifiers, completionStart, completionEnd); -// } -// public void acceptInterface(char[] packageName,char[] interfaceName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance) { -// requestor.acceptInterface(packageName, interfaceName, completionName, modifiers, completionStart, completionEnd); -// } -// public void acceptKeyword(char[] keywordName,int completionStart,int completionEnd, int relevance){ -// requestor.acceptKeyword(keywordName, completionStart, completionEnd); -// } -// public void acceptLabel(char[] labelName,int completionStart,int completionEnd, int relevance){ -// requestor.acceptLabel(labelName, completionStart, completionEnd); -// } -// public void acceptLocalVariable(char[] name,char[] typePackageName,char[] typeName,int modifiers,int completionStart,int completionEnd, int relevance){ -// // ignore -// } -// public void acceptMethod(char[] declaringTypePackageName,char[] declaringTypeName,char[] selector,char[][] parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] returnTypePackageName,char[] returnTypeName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance){ -// // skip parameter names -// requestor.acceptMethod(declaringTypePackageName, declaringTypeName, selector, parameterPackageNames, parameterTypeNames, returnTypePackageName, returnTypeName, completionName, modifiers, completionStart, completionEnd); -// } -// public void acceptMethodDeclaration(char[] declaringTypePackageName,char[] declaringTypeName,char[] selector,char[][] parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] returnTypePackageName,char[] returnTypeName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance){ -// // ignore -// } -// public void acceptModifier(char[] modifierName,int completionStart,int completionEnd, int relevance){ -// requestor.acceptModifier(modifierName, completionStart, completionEnd); -// } -// public void acceptPackage(char[] packageName,char[] completionName,int completionStart,int completionEnd, int relevance){ -// requestor.acceptPackage(packageName, completionName, completionStart, completionEnd); -// } -// public void acceptType(char[] packageName,char[] typeName,char[] completionName,int completionStart,int completionEnd, int relevance){ -// requestor.acceptType(packageName, typeName, completionName, completionStart, completionEnd); -// } -// public void acceptVariableName(char[] typePackageName,char[] typeName,char[] name,char[] completionName,int completionStart,int completionEnd, int relevance){ -// // ignore -// } -// }); -//} + /** + * @see IOpenable + */ + public void save(IProgressMonitor pm, boolean force) + throws JavaModelException { + if (isReadOnly() + || this.getResource().getResourceAttributes().isReadOnly()) { + throw new JavaModelException(new JavaModelStatus( + IJavaModelStatusConstants.READ_ONLY, this)); + } + IBuffer buf = getBuffer(); + if (buf != null) { // some Openables (like a JavaProject) don't have a + // buffer + buf.save(pm, force); + this.makeConsistent(pm); // update the element info of this + // element + } + } + + /** + * Find enclosing package fragment root if any + */ + public PackageFragmentRoot getPackageFragmentRoot() { + IJavaElement current = this; + do { + if (current instanceof PackageFragmentRoot) + return (PackageFragmentRoot) current; + current = current.getParent(); + } while (current != null); + return null; + } + // /** + // * @see ICodeAssist + // * @deprecated - use codeComplete(ICompilationUnit, ICompilationUnit, int, + // ICompletionRequestor) instead + // */ + // protected void + // codeComplete(net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit + // cu, net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit + // unitToSkip, int position, final ICodeCompletionRequestor requestor) + // throws JavaModelException { + // + // if (requestor == null){ + // codeComplete(cu, unitToSkip, position, (ICompletionRequestor)null); + // return; + // } + // codeComplete( + // cu, + // unitToSkip, + // position, + // new ICompletionRequestor(){ + // public void acceptAnonymousType(char[] superTypePackageName,char[] + // superTypeName,char[][] parameterPackageNames,char[][] + // parameterTypeNames,char[][] parameterNames,char[] completionName,int + // modifiers,int completionStart,int completionEnd, int relevance) { + // } + // public void acceptClass(char[] packageName, char[] className, char[] + // completionName, int modifiers, int completionStart, int completionEnd, + // int relevance) { + // requestor.acceptClass(packageName, className, completionName, modifiers, + // completionStart, completionEnd); + // } + // public void acceptError(IProblem error) { + // if (true) return; // was disabled in 1.0 + // + // try { + // IMarker marker = + // ResourcesPlugin.getWorkspace().getRoot().createMarker(IJavaModelMarker.TRANSIENT_PROBLEM); + // marker.setAttribute(IJavaModelMarker.ID, error.getID()); + // marker.setAttribute(IMarker.CHAR_START, error.getSourceStart()); + // marker.setAttribute(IMarker.CHAR_END, error.getSourceEnd() + 1); + // marker.setAttribute(IMarker.LINE_NUMBER, error.getSourceLineNumber()); + // marker.setAttribute(IMarker.MESSAGE, error.getMessage()); + // marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); + // requestor.acceptError(marker); + // } catch(CoreException e){ + // } + // } + // public void acceptField(char[] declaringTypePackageName, char[] + // declaringTypeName, char[] name, char[] typePackageName, char[] typeName, + // char[] completionName, int modifiers, int completionStart, int + // completionEnd, int relevance) { + // requestor.acceptField(declaringTypePackageName, declaringTypeName, name, + // typePackageName, typeName, completionName, modifiers, completionStart, + // completionEnd); + // } + // public void acceptInterface(char[] packageName,char[] + // interfaceName,char[] completionName,int modifiers,int completionStart,int + // completionEnd, int relevance) { + // requestor.acceptInterface(packageName, interfaceName, completionName, + // modifiers, completionStart, completionEnd); + // } + // public void acceptKeyword(char[] keywordName,int completionStart,int + // completionEnd, int relevance){ + // requestor.acceptKeyword(keywordName, completionStart, completionEnd); + // } + // public void acceptLabel(char[] labelName,int completionStart,int + // completionEnd, int relevance){ + // requestor.acceptLabel(labelName, completionStart, completionEnd); + // } + // public void acceptLocalVariable(char[] name,char[] typePackageName,char[] + // typeName,int modifiers,int completionStart,int completionEnd, int + // relevance){ + // // ignore + // } + // public void acceptMethod(char[] declaringTypePackageName,char[] + // declaringTypeName,char[] selector,char[][] parameterPackageNames,char[][] + // parameterTypeNames,char[][] parameterNames,char[] + // returnTypePackageName,char[] returnTypeName,char[] completionName,int + // modifiers,int completionStart,int completionEnd, int relevance){ + // // skip parameter names + // requestor.acceptMethod(declaringTypePackageName, declaringTypeName, + // selector, parameterPackageNames, parameterTypeNames, + // returnTypePackageName, returnTypeName, completionName, modifiers, + // completionStart, completionEnd); + // } + // public void acceptMethodDeclaration(char[] + // declaringTypePackageName,char[] declaringTypeName,char[] + // selector,char[][] parameterPackageNames,char[][] + // parameterTypeNames,char[][] parameterNames,char[] + // returnTypePackageName,char[] returnTypeName,char[] completionName,int + // modifiers,int completionStart,int completionEnd, int relevance){ + // // ignore + // } + // public void acceptModifier(char[] modifierName,int completionStart,int + // completionEnd, int relevance){ + // requestor.acceptModifier(modifierName, completionStart, completionEnd); + // } + // public void acceptPackage(char[] packageName,char[] completionName,int + // completionStart,int completionEnd, int relevance){ + // requestor.acceptPackage(packageName, completionName, completionStart, + // completionEnd); + // } + // public void acceptType(char[] packageName,char[] typeName,char[] + // completionName,int completionStart,int completionEnd, int relevance){ + // requestor.acceptType(packageName, typeName, completionName, + // completionStart, completionEnd); + // } + // public void acceptVariableName(char[] typePackageName,char[] + // typeName,char[] name,char[] completionName,int completionStart,int + // completionEnd, int relevance){ + // // ignore + // } + // }); + // } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/OpenableElementInfo.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/OpenableElementInfo.java index 660c9f1..58d0e07 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/OpenableElementInfo.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/OpenableElementInfo.java @@ -11,7 +11,6 @@ package net.sourceforge.phpdt.internal.core; /** Element info for IOpenable elements. */ -/* package */ class OpenableElementInfo extends JavaElementInfo { - +/* package */class OpenableElementInfo extends JavaElementInfo { } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/OverflowingLRUCache.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/OverflowingLRUCache.java index 9192499..de4c7a4 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/OverflowingLRUCache.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/OverflowingLRUCache.java @@ -17,149 +17,178 @@ import net.sourceforge.phpdt.internal.core.util.LRUCache; import net.sourceforge.phpdt.internal.core.util.Util; /** - * The OverflowingLRUCache is an LRUCache which attempts - * to maintain a size equal or less than its fSpaceLimit - * by removing the least recently used elements. - * - *

                                              The cache will remove elements which successfully close and all - * elements which are explicitly removed. - * - *

                                              If the cache cannot remove enough old elements to add new elements - * it will grow beyond fSpaceLimit. Later, it will attempt to - * shink back to the maximum space limit. - * - * The method close should attempt to close the element. If - * the element is successfully closed it will return true and the element will - * be removed from the cache. Otherwise the element will remain in the cache. - * - *

                                              The cache implicitly attempts shrinks on calls to putand - * setSpaceLimit. Explicitly calling the shrink method - * will also cause the cache to attempt to shrink. - * - *

                                              The cache calculates the used space of all elements which implement - * ILRUCacheable. All other elements are assumed to be of size one. - * - *

                                              Use the #peek(Object) and #disableTimestamps() method to - * circumvent the timestamp feature of the cache. This feature is intended to be used - * only when the #close(LRUCacheEntry) method causes changes to the cache. - * For example, if a parent closes its children when #close(LRUCacheEntry) is called, - * it should be careful not to change the LRU linked list. It can be sure it is not causing - * problems by calling #peek(Object) instead of #get(Object) method. - * - * @see LRUCache + * The OverflowingLRUCache is an LRUCache which attempts to + * maintain a size equal or less than its fSpaceLimit by removing + * the least recently used elements. + * + *

                                              + * The cache will remove elements which successfully close and all elements + * which are explicitly removed. + * + *

                                              + * If the cache cannot remove enough old elements to add new elements it will + * grow beyond fSpaceLimit. Later, it will attempt to shink back + * to the maximum space limit. + * + * The method close should attempt to close the element. If the + * element is successfully closed it will return true and the element will be + * removed from the cache. Otherwise the element will remain in the cache. + * + *

                                              + * The cache implicitly attempts shrinks on calls to putand + * setSpaceLimit. Explicitly calling the shrink + * method will also cause the cache to attempt to shrink. + * + *

                                              + * The cache calculates the used space of all elements which implement + * ILRUCacheable. All other elements are assumed to be of size + * one. + * + *

                                              + * Use the #peek(Object) and #disableTimestamps() + * method to circumvent the timestamp feature of the cache. This feature is + * intended to be used only when the #close(LRUCacheEntry) method + * causes changes to the cache. For example, if a parent closes its children + * when #close(LRUCacheEntry) is called, it should be careful + * not to change the LRU linked list. It can be sure it is not causing problems + * by calling #peek(Object) instead of #get(Object) + * method. + * + * @see LRUCache */ public abstract class OverflowingLRUCache extends LRUCache { /** * Indicates if the cache has been over filled and by how much. */ protected int fOverflow = 0; + /** - * Indicates whether or not timestamps should be updated + * Indicates whether or not timestamps should be updated */ protected boolean fTimestampsOn = true; + /** - * Indicates how much space should be reclaimed when the cache overflows. - * Inital load factor of one third. + * Indicates how much space should be reclaimed when the cache overflows. + * Inital load factor of one third. */ protected double fLoadFactor = 0.333; -/** - * Creates a OverflowingLRUCache. - * @param size Size limit of cache. - */ -public OverflowingLRUCache(int size) { - this(size, 0); -} -/** - * Creates a OverflowingLRUCache. - * @param size Size limit of cache. - * @param overflow Size of the overflow. - */ -public OverflowingLRUCache(int size, int overflow) { - super(size); - fOverflow = overflow; -} + + /** + * Creates a OverflowingLRUCache. + * + * @param size + * Size limit of cache. + */ + public OverflowingLRUCache(int size) { + this(size, 0); + } + + /** + * Creates a OverflowingLRUCache. + * + * @param size + * Size limit of cache. + * @param overflow + * Size of the overflow. + */ + public OverflowingLRUCache(int size, int overflow) { + super(size); + fOverflow = overflow; + } + /** * Returns a new cache containing the same contents. - * + * * @return New copy of this object. */ public Object clone() { - - OverflowingLRUCache newCache = (OverflowingLRUCache)newInstance(fSpaceLimit, fOverflow); + + OverflowingLRUCache newCache = (OverflowingLRUCache) newInstance( + fSpaceLimit, fOverflow); LRUCacheEntry qEntry; - + /* Preserve order of entries by copying from oldest to newest */ qEntry = this.fEntryQueueTail; while (qEntry != null) { - newCache.privateAdd (qEntry._fKey, qEntry._fValue, qEntry._fSpace); + newCache.privateAdd(qEntry._fKey, qEntry._fValue, qEntry._fSpace); qEntry = qEntry._fPrevious; } return newCache; } -/** - * Returns true if the element is successfully closed and - * removed from the cache, otherwise false. - * - *

                                              NOTE: this triggers an external remove from the cache - * by closing the obejct. - * - */ -protected abstract boolean close(LRUCacheEntry entry); + + /** + * Returns true if the element is successfully closed and removed from the + * cache, otherwise false. + * + *

                                              + * NOTE: this triggers an external remove from the cache by closing the + * obejct. + * + */ + protected abstract boolean close(LRUCacheEntry entry); + /** - * Returns an enumerator of the values in the cache with the most - * recently used first. + * Returns an enumerator of the values in the cache with the most recently + * used first. */ public Enumeration elements() { if (fEntryQueue == null) return new LRUCacheEnumerator(null); - LRUCacheEnumerator.LRUEnumeratorElement head = - new LRUCacheEnumerator.LRUEnumeratorElement(fEntryQueue._fValue); + LRUCacheEnumerator.LRUEnumeratorElement head = new LRUCacheEnumerator.LRUEnumeratorElement( + fEntryQueue._fValue); LRUCacheEntry currentEntry = fEntryQueue._fNext; LRUCacheEnumerator.LRUEnumeratorElement currentElement = head; - while(currentEntry != null) { - currentElement.fNext = new LRUCacheEnumerator.LRUEnumeratorElement(currentEntry._fValue); + while (currentEntry != null) { + currentElement.fNext = new LRUCacheEnumerator.LRUEnumeratorElement( + currentEntry._fValue); currentElement = currentElement.fNext; - + currentEntry = currentEntry._fNext; } return new LRUCacheEnumerator(head); } + public double fillingRatio() { return (fCurrentSpace + fOverflow) * 100.0 / fSpaceLimit; } + /** - * For internal testing only. - * This method exposed only for testing purposes! - * + * For internal testing only. This method exposed only for testing purposes! + * * @return Hashtable of entries */ public java.util.Hashtable getEntryTable() { return fEntryTable; } -/** - * Returns the load factor for the cache. The load factor determines how - * much space is reclaimed when the cache exceeds its space limit. - * @return double - */ -public double getLoadFactor() { - return fLoadFactor; -} + /** - * @return The space by which the cache has overflown. + * Returns the load factor for the cache. The load factor determines how + * much space is reclaimed when the cache exceeds its space limit. + * + * @return double + */ + public double getLoadFactor() { + return fLoadFactor; + } + + /** + * @return The space by which the cache has overflown. */ public int getOverflow() { return fOverflow; } + /** - * Ensures there is the specified amount of free space in the receiver, - * by removing old entries if necessary. Returns true if the requested space was - * made available, false otherwise. May not be able to free enough space + * Ensures there is the specified amount of free space in the receiver, by + * removing old entries if necessary. Returns true if the requested space + * was made available, false otherwise. May not be able to free enough space * since some elements cannot be removed until they are saved. - * - * @param space Amount of space to free up + * + * @param space + * Amount of space to free up */ protected boolean makeSpace(int space) { - + int limit = fSpaceLimit; if (fOverflow == 0) { /* if space is already available */ @@ -167,223 +196,251 @@ public double getLoadFactor() { return true; } } - + /* Free up space by removing oldest entries */ - int spaceNeeded = (int)((1 - fLoadFactor) * fSpaceLimit); + int spaceNeeded = (int) ((1 - fLoadFactor) * fSpaceLimit); spaceNeeded = (spaceNeeded > space) ? spaceNeeded : space; LRUCacheEntry entry = fEntryQueueTail; - + while (fCurrentSpace + spaceNeeded > limit && entry != null) { this.privateRemoveEntry(entry, false, false); entry = entry._fPrevious; } - + /* check again, since we may have aquired enough space */ if (fCurrentSpace + space <= limit) { fOverflow = 0; return true; } - + /* update fOverflow */ fOverflow = fCurrentSpace + space - limit; return false; } + /** * Returns a new instance of the reciever. */ protected abstract LRUCache newInstance(int size, int overflow); + /** - * Answers the value in the cache at the given key. - * If the value is not in the cache, returns null - * + * Answers the value in the cache at the given key. If the value is not in + * the cache, returns null + * * This function does not modify timestamps. */ public Object peek(Object key) { - + LRUCacheEntry entry = (LRUCacheEntry) fEntryTable.get(key); if (entry == null) { return null; } return entry._fValue; } -/** - * For testing purposes only - */ -public void printStats() { - int forwardListLength = 0; - LRUCacheEntry entry = fEntryQueue; - while(entry != null) { - forwardListLength++; - entry = entry._fNext; - } - System.out.println("Forward length: " + forwardListLength); //$NON-NLS-1$ - - int backwardListLength = 0; - entry = fEntryQueueTail; - while(entry != null) { - backwardListLength++; - entry = entry._fPrevious; - } - System.out.println("Backward length: " + backwardListLength); //$NON-NLS-1$ - - Enumeration keys = fEntryTable.keys(); - class Temp { - public Class fClass; - public int fCount; - public Temp(Class aClass) { - fClass = aClass; - fCount = 1; + + /** + * For testing purposes only + */ + public void printStats() { + int forwardListLength = 0; + LRUCacheEntry entry = fEntryQueue; + while (entry != null) { + forwardListLength++; + entry = entry._fNext; } - public String toString() { - return "Class: " + fClass + " has " + fCount + " entries."; //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-1$ + System.out.println("Forward length: " + forwardListLength); //$NON-NLS-1$ + + int backwardListLength = 0; + entry = fEntryQueueTail; + while (entry != null) { + backwardListLength++; + entry = entry._fPrevious; } - } - java.util.HashMap h = new java.util.HashMap(); - while(keys.hasMoreElements()) { - entry = (LRUCacheEntry)fEntryTable.get(keys.nextElement()); - Class key = entry._fValue.getClass(); - Temp t = (Temp)h.get(key); - if (t == null) { - h.put(key, new Temp(key)); - } else { - t.fCount++; + System.out.println("Backward length: " + backwardListLength); //$NON-NLS-1$ + + Enumeration keys = fEntryTable.keys(); + class Temp { + public Class fClass; + + public int fCount; + + public Temp(Class aClass) { + fClass = aClass; + fCount = 1; + } + + public String toString() { + return "Class: " + fClass + " has " + fCount + " entries."; //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-1$ + } + } + java.util.HashMap h = new java.util.HashMap(); + while (keys.hasMoreElements()) { + entry = (LRUCacheEntry) fEntryTable.get(keys.nextElement()); + Class key = entry._fValue.getClass(); + Temp t = (Temp) h.get(key); + if (t == null) { + h.put(key, new Temp(key)); + } else { + t.fCount++; + } } - } - for (Iterator iter = h.keySet().iterator(); iter.hasNext();){ - System.out.println(h.get(iter.next())); + for (Iterator iter = h.keySet().iterator(); iter.hasNext();) { + System.out.println(h.get(iter.next())); + } } -} + /** - * Removes the entry from the entry queue. - * Calls privateRemoveEntry with the external functionality enabled. - * - * @param shuffle indicates whether we are just shuffling the queue - * (in which case, the entry table is not modified). + * Removes the entry from the entry queue. Calls + * privateRemoveEntry with the external functionality + * enabled. + * + * @param shuffle + * indicates whether we are just shuffling the queue (in which + * case, the entry table is not modified). */ - protected void privateRemoveEntry (LRUCacheEntry entry, boolean shuffle) { + protected void privateRemoveEntry(LRUCacheEntry entry, boolean shuffle) { privateRemoveEntry(entry, shuffle, true); } -/** - * Removes the entry from the entry queue. If external is true, the entry is removed - * without checking if it can be removed. It is assumed that the client has already closed - * the element it is trying to remove (or will close it promptly). - * - * If external is false, and the entry could not be closed, it is not removed and the - * pointers are not changed. - * - * @param shuffle indicates whether we are just shuffling the queue - * (in which case, the entry table is not modified). - */ -protected void privateRemoveEntry(LRUCacheEntry entry, boolean shuffle, boolean external) { - if (!shuffle) { - if (external) { - fEntryTable.remove(entry._fKey); - fCurrentSpace -= entry._fSpace; - privateNotifyDeletionFromCache(entry); - } else { - if (!close(entry)) return; - // buffer close will recursively call #privateRemoveEntry with external==true - // thus entry will already be removed if reaching this point. - if (fEntryTable.get(entry._fKey) == null){ - return; - } else { - // basic removal - fEntryTable.remove(entry._fKey); + /** + * Removes the entry from the entry queue. If external is true, the + * entry is removed without checking if it can be removed. It is assumed + * that the client has already closed the element it is trying to remove (or + * will close it promptly). + * + * If external is false, and the entry could not be closed, it is + * not removed and the pointers are not changed. + * + * @param shuffle + * indicates whether we are just shuffling the queue (in which + * case, the entry table is not modified). + */ + protected void privateRemoveEntry(LRUCacheEntry entry, boolean shuffle, + boolean external) { + + if (!shuffle) { + if (external) { + fEntryTable.remove(entry._fKey); fCurrentSpace -= entry._fSpace; privateNotifyDeletionFromCache(entry); + } else { + if (!close(entry)) + return; + // buffer close will recursively call #privateRemoveEntry with + // external==true + // thus entry will already be removed if reaching this point. + if (fEntryTable.get(entry._fKey) == null) { + return; + } else { + // basic removal + fEntryTable.remove(entry._fKey); + fCurrentSpace -= entry._fSpace; + privateNotifyDeletionFromCache(entry); + } } } + LRUCacheEntry previous = entry._fPrevious; + LRUCacheEntry next = entry._fNext; + + /* if this was the first entry */ + if (previous == null) { + fEntryQueue = next; + } else { + previous._fNext = next; + } + /* if this was the last entry */ + if (next == null) { + fEntryQueueTail = previous; + } else { + next._fPrevious = previous; + } } - LRUCacheEntry previous = entry._fPrevious; - LRUCacheEntry next = entry._fNext; - - /* if this was the first entry */ - if (previous == null) { - fEntryQueue = next; - } else { - previous._fNext = next; - } - /* if this was the last entry */ - if (next == null) { - fEntryQueueTail = previous; - } else { - next._fPrevious = previous; - } -} + /** * Sets the value in the cache at the given key. Returns the value. - * - * @param key Key of object to add. - * @param value Value of object to add. + * + * @param key + * Key of object to add. + * @param value + * Value of object to add. * @return added value. */ public Object put(Object key, Object value) { /* attempt to rid ourselves of the overflow, if there is any */ if (fOverflow > 0) shrink(); - + /* Check whether there's an entry in the cache */ - int newSpace = spaceFor (key, value); - LRUCacheEntry entry = (LRUCacheEntry) fEntryTable.get (key); - + int newSpace = spaceFor(key, value); + LRUCacheEntry entry = (LRUCacheEntry) fEntryTable.get(key); + if (entry != null) { - + /** - * Replace the entry in the cache if it would not overflow - * the cache. Otherwise flush the entry and re-add it so as - * to keep cache within budget + * Replace the entry in the cache if it would not overflow the + * cache. Otherwise flush the entry and re-add it so as to keep + * cache within budget */ int oldSpace = entry._fSpace; int newTotal = fCurrentSpace - oldSpace + newSpace; if (newTotal <= fSpaceLimit) { - updateTimestamp (entry); + updateTimestamp(entry); entry._fValue = value; entry._fSpace = newSpace; fCurrentSpace = newTotal; fOverflow = 0; return value; } else { - privateRemoveEntry (entry, false, false); + privateRemoveEntry(entry, false, false); } } - + // attempt to make new space makeSpace(newSpace); - + // add without worring about space, it will // be handled later in a makeSpace call - privateAdd (key, value, newSpace); - + privateAdd(key, value, newSpace); + return value; } + /** - * Removes and returns the value in the cache for the given key. - * If the key is not in the cache, returns null. - * - * @param key Key of object to remove from cache. + * Removes and returns the value in the cache for the given key. If the key + * is not in the cache, returns null. + * + * @param key + * Key of object to remove from cache. * @return Value removed from cache. */ public Object remove(Object key) { return removeKey(key); } -/** - * Sets the load factor for the cache. The load factor determines how - * much space is reclaimed when the cache exceeds its space limit. - * @param newLoadFactor double - * @throws IllegalArgumentException when the new load factor is not in (0.0, 1.0] - */ -public void setLoadFactor(double newLoadFactor) throws IllegalArgumentException { - if(newLoadFactor <= 1.0 && newLoadFactor > 0.0) - fLoadFactor = newLoadFactor; - else - throw new IllegalArgumentException(Util.bind("cache.invalidLoadFactor")); //$NON-NLS-1$ -} + + /** + * Sets the load factor for the cache. The load factor determines how much + * space is reclaimed when the cache exceeds its space limit. + * + * @param newLoadFactor + * double + * @throws IllegalArgumentException + * when the new load factor is not in (0.0, 1.0] + */ + public void setLoadFactor(double newLoadFactor) + throws IllegalArgumentException { + if (newLoadFactor <= 1.0 && newLoadFactor > 0.0) + fLoadFactor = newLoadFactor; + else + throw new IllegalArgumentException(Util + .bind("cache.invalidLoadFactor")); //$NON-NLS-1$ + } + /** * Sets the maximum amount of space that the cache can store - * - * @param limit Number of units of cache space + * + * @param limit + * Number of units of cache space */ public void setSpaceLimit(int limit) { if (limit < fSpaceLimit) { @@ -391,37 +448,40 @@ public void setLoadFactor(double newLoadFactor) throws IllegalArgumentException } fSpaceLimit = limit; } + /** - * Attempts to shrink the cache if it has overflown. - * Returns true if the cache shrinks to less than or equal to fSpaceLimit. + * Attempts to shrink the cache if it has overflown. Returns true if the + * cache shrinks to less than or equal to fSpaceLimit. */ public boolean shrink() { if (fOverflow > 0) return makeSpace(0); return true; } -/** - * Returns a String that represents the value of this object. This method - * is for debugging purposes only. - */ -public String toString() { - return - "OverflowingLRUCache " + this.fillingRatio() + "% full\n" + //$NON-NLS-1$ //$NON-NLS-2$ - this.toStringContents(); -} -/** - * Updates the timestamp for the given entry, ensuring that the queue is - * kept in correct order. The entry must exist. - * - *

                                              This method will do nothing if timestamps have been disabled. - */ -protected void updateTimestamp(LRUCacheEntry entry) { - if (fTimestampsOn) { - entry._fTimestamp = fTimestampCounter++; - if (fEntryQueue != entry) { - this.privateRemoveEntry(entry, true); - this.privateAddEntry(entry, true); + + /** + * Returns a String that represents the value of this object. This method is + * for debugging purposes only. + */ + public String toString() { + return "OverflowingLRUCache " + this.fillingRatio() + "% full\n" + //$NON-NLS-1$ //$NON-NLS-2$ + this.toStringContents(); + } + + /** + * Updates the timestamp for the given entry, ensuring that the queue is + * kept in correct order. The entry must exist. + * + *

                                              + * This method will do nothing if timestamps have been disabled. + */ + protected void updateTimestamp(LRUCacheEntry entry) { + if (fTimestampsOn) { + entry._fTimestamp = fTimestampCounter++; + if (fEntryQueue != entry) { + this.privateRemoveEntry(entry, true); + this.privateAddEntry(entry, true); + } } } } -} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageDeclaration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageDeclaration.java index 138b007..9f9ced5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageDeclaration.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageDeclaration.java @@ -19,41 +19,49 @@ import net.sourceforge.phpdt.core.jdom.IDOMNode; * @see IPackageDeclaration */ -/* package */ class PackageDeclaration extends SourceRefElement implements IPackageDeclaration { +/* package */class PackageDeclaration extends SourceRefElement implements + IPackageDeclaration { protected PackageDeclaration(CompilationUnit parent, String name) { super(parent, name); } + public boolean equals(Object o) { - if (!(o instanceof PackageDeclaration)) return false; + if (!(o instanceof PackageDeclaration)) + return false; return super.equals(o); } -/** - * @see JavaElement#equalsDOMNode - */ -protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException { - return (node.getNodeType() == IDOMNode.PACKAGE) && getElementName().equals(node.getName()); -} -/** - * @see IJavaElement - */ -public int getElementType() { - return PACKAGE_DECLARATION; -} -/** - * @see JavaElement#getHandleMemento() - */ -protected char getHandleMementoDelimiter() { - return JavaElement.JEM_PACKAGEDECLARATION; -} -/** - * @private Debugging purposes - */ -protected void toStringInfo(int tab, StringBuffer buffer, Object info) { - buffer.append(this.tabString(tab)); - buffer.append("package "); //$NON-NLS-1$ - buffer.append(getElementName()); - if (info == null) { - buffer.append(" (not open)"); //$NON-NLS-1$ + + /** + * @see JavaElement#equalsDOMNode + */ + protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException { + return (node.getNodeType() == IDOMNode.PACKAGE) + && getElementName().equals(node.getName()); + } + + /** + * @see IJavaElement + */ + public int getElementType() { + return PACKAGE_DECLARATION; + } + + /** + * @see JavaElement#getHandleMemento() + */ + protected char getHandleMementoDelimiter() { + return JavaElement.JEM_PACKAGEDECLARATION; + } + + /** + * @private Debugging purposes + */ + protected void toStringInfo(int tab, StringBuffer buffer, Object info) { + buffer.append(this.tabString(tab)); + buffer.append("package "); //$NON-NLS-1$ + buffer.append(getElementName()); + if (info == null) { + buffer.append(" (not open)"); //$NON-NLS-1$ + } } -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragment.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragment.java index 9af6588..d54d251 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragment.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragment.java @@ -31,61 +31,72 @@ import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; - /** * @see IPackageFragment */ public class PackageFragment extends Openable implements IPackageFragment { - /** + /** * Constant empty list of compilation units */ - protected static ICompilationUnit[] fgEmptyCompilationUnitList= new ICompilationUnit[] {}; + protected static ICompilationUnit[] fgEmptyCompilationUnitList = new ICompilationUnit[] {}; + /** * Constructs a handle for a package fragment - * + * * @see IPackageFragment */ protected PackageFragment(PackageFragmentRoot root, String name) { super(root, name); } + /** * @see Openable */ - protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException { + protected boolean buildStructure(OpenableElementInfo info, + IProgressMonitor pm, Map newElements, IResource underlyingResource) + throws JavaModelException { // check whether this pkg can be opened - if (!underlyingResource.isAccessible()) throw newNotPresentException(); + if (!underlyingResource.isAccessible()) + throw newNotPresentException(); int kind = getKind(); String extType; -// if (kind == IPackageFragmentRoot.K_SOURCE) { - extType = "php"; //EXTENSION_java; -// } else { -// extType = EXTENSION_class; -// } + // if (kind == IPackageFragmentRoot.K_SOURCE) { + extType = "php"; // EXTENSION_java; + // } else { + // extType = EXTENSION_class; + // } // add compilation units/class files from resources HashSet vChildren = new HashSet(); try { - PackageFragmentRoot root = getPackageFragmentRoot(); -// char[][] inclusionPatterns = root.fullInclusionPatternChars(); + PackageFragmentRoot root = getPackageFragmentRoot(); + // char[][] inclusionPatterns = root.fullInclusionPatternChars(); char[][] exclusionPatterns = root.fullExclusionPatternChars(); IResource[] members = ((IContainer) underlyingResource).members(); for (int i = 0, max = members.length; i < max; i++) { IResource child = members[i]; if (child.getType() != IResource.FOLDER && !Util.isExcluded(child, exclusionPatterns)) { - String extension = child.getProjectRelativePath().getFileExtension(); + String extension = child.getProjectRelativePath() + .getFileExtension(); if (extension != null) { if (extension.equalsIgnoreCase(extType)) { IJavaElement childElement; -// if (kind == IPackageFragmentRoot.K_SOURCE && ProjectPrefUtil.isValidCompilationUnitName(child.getName())) { -// childElement = new CompilationUnit(this, child.getName(), DefaultWorkingCopyOwner.PRIMARY); -// vChildren.add(childElement); -// } else if (ProjectPrefUtil.isValidClassFileName(child.getName())) { -// childElement = getClassFile(child.getName()); -// vChildren.add(childElement); -// } + // if (kind == IPackageFragmentRoot.K_SOURCE && + // ProjectPrefUtil.isValidCompilationUnitName(child.getName())) + // { + // childElement = new CompilationUnit(this, + // child.getName(), + // DefaultWorkingCopyOwner.PRIMARY); + // vChildren.add(childElement); + // } else if + // (ProjectPrefUtil.isValidClassFileName(child.getName())) + // { + // childElement = getClassFile(child.getName()); + // vChildren.add(childElement); + // } } } } @@ -93,373 +104,427 @@ public class PackageFragment extends Openable implements IPackageFragment { } catch (CoreException e) { throw new JavaModelException(e); } - -// if (kind == IPackageFragmentRoot.K_SOURCE) { -// // add primary compilation units -// ICompilationUnit[] primaryCompilationUnits = getCompilationUnits(DefaultWorkingCopyOwner.PRIMARY); -// for (int i = 0, length = primaryCompilationUnits.length; i < length; i++) { -// ICompilationUnit primary = primaryCompilationUnits[i]; -// vChildren.add(primary); -// } -// } - + + // if (kind == IPackageFragmentRoot.K_SOURCE) { + // // add primary compilation units + // ICompilationUnit[] primaryCompilationUnits = + // getCompilationUnits(DefaultWorkingCopyOwner.PRIMARY); + // for (int i = 0, length = primaryCompilationUnits.length; i < length; + // i++) { + // ICompilationUnit primary = primaryCompilationUnits[i]; + // vChildren.add(primary); + // } + // } + IJavaElement[] children = new IJavaElement[vChildren.size()]; vChildren.toArray(children); info.setChildren(children); return true; } -///** -// * Compute the children of this package fragment. -// * -// *

                                              Package fragments which are folders recognize files based on the -// * type of the fragment -// *

                                              Package fragments which are in a jar only recognize .class files ( -// * @see JarPackageFragment). -// */ -//protected boolean computeChildren(OpenableElementInfo info, IResource resource) throws JavaModelException { -// ArrayList vChildren = new ArrayList(); -//// int kind = getKind(); -// String extType; -//// if (kind == IPackageFragmentRoot.K_SOURCE) { -// extType = "php"; //$NON-NLS-1$ -//// } else { -//// extType = "class"; //$NON-NLS-1$ -//// } -// try { -// char[][] exclusionPatterns = ((PackageFragmentRoot)getPackageFragmentRoot()).fullExclusionPatternChars(); -// IResource[] members = ((IContainer) resource).members(); -// for (int i = 0, max = members.length; i < max; i++) { -// IResource child = members[i]; -// if (child.getType() != IResource.FOLDER -// && !ProjectPrefUtil.isExcluded(child, exclusionPatterns)) { -// String extension = child.getProjectRelativePath().getFileExtension(); -// if (extension != null) { -// if (extension.equalsIgnoreCase(extType)) { -// IJavaElement childElement; -//// if (kind == IPackageFragmentRoot.K_SOURCE && ProjectPrefUtil.isValidCompilationUnitName(child.getName())) { -//// childElement = getCompilationUnit(child.getName()); -//// vChildren.add(childElement); -//// } else if (ProjectPrefUtil.isValidClassFileName(child.getName())) { -//// childElement = getClassFile(child.getName()); -//// vChildren.add(childElement); -//// } -// } -// } -// } -// } -// } catch (CoreException e) { -// throw new JavaModelException(e); -// } -// IJavaElement[] children = new IJavaElement[vChildren.size()]; -// vChildren.toArray(children); -// info.setChildren(children); -// return true; -//} -/** - * Returns true if this fragment contains at least one java resource. - * Returns false otherwise. - */ -//public boolean containsJavaResources() throws JavaModelException { -// return ((PackageFragmentInfo) getElementInfo()).containsJavaResources(); -//} -/** - * @see ISourceManipulation - */ -//public void copy(IJavaElement container, IJavaElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaModelException { -// if (container == null) { -// throw new IllegalArgumentException(ProjectPrefUtil.bind("operation.nullContainer")); //$NON-NLS-1$ -// } -// IJavaElement[] elements= new IJavaElement[] {this}; -// IJavaElement[] containers= new IJavaElement[] {container}; -// IJavaElement[] siblings= null; -// if (sibling != null) { -// siblings= new IJavaElement[] {sibling}; -// } -// String[] renamings= null; -// if (rename != null) { -// renamings= new String[] {rename}; -// } -// getJavaModel().copy(elements, containers, siblings, renamings, force, monitor); -//} -/** - * @see IPackageFragment - */ -public ICompilationUnit createCompilationUnit(String name, String contents, boolean force, IProgressMonitor monitor) throws JavaModelException { -// CreateCompilationUnitOperation op= new CreateCompilationUnitOperation(this, name, contents, force); -// runOperation(op, monitor); -// return getCompilationUnit(name); - return null; -} -/** - * @see JavaElement - */ -protected Object createElementInfo() { - return new PackageFragmentInfo(); -} -/** - * @see ISourceManipulation - */ -//public void delete(boolean force, IProgressMonitor monitor) throws JavaModelException { -// IJavaElement[] elements = new IJavaElement[] {this}; -// getJavaModel().delete(elements, force, monitor); -//} -///** -// * @see Openable -// */ -//protected boolean generateInfos(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException { -// -// return computeChildren(info, underlyingResource); -//} -///** -// * @see IPackageFragment#getClassFile(String) -// */ -//public IClassFile getClassFile(String name) { -// return new ClassFile(this, name); -//} -/** - * Returns a the collection of class files in this - a folder package fragment which has a root - * that has its kind set to IPackageFragmentRoot.K_Source does not - * recognize class files. - * - * @see IPackageFragment#getClassFiles() - */ -//public IClassFile[] getClassFiles() throws JavaModelException { -// if (getKind() == IPackageFragmentRoot.K_SOURCE) { -// return fgEmptyClassFileList; -// } -// -// ArrayList list = getChildrenOfType(CLASS_FILE); -// IClassFile[] array= new IClassFile[list.size()]; -// list.toArray(array); -// return array; -//} -/** - * @see IPackageFragment#getCompilationUnit(String) - * @exception IllegalArgumentExcpetion if the name does not end with a php file extension - */ -public ICompilationUnit getCompilationUnit(String cuName) { - if (! PHPFileUtil.isValidPHPUnitName(cuName)) { - throw new IllegalArgumentException(Util.bind("convention.unit.notJavaName")); //$NON-NLS-1$ + + // /** + // * Compute the children of this package fragment. + // * + // *

                                              Package fragments which are folders recognize files based on the + // * type of the fragment + // *

                                              Package fragments which are in a jar only recognize .class files ( + // * @see JarPackageFragment). + // */ + // protected boolean computeChildren(OpenableElementInfo info, IResource + // resource) throws JavaModelException { + // ArrayList vChildren = new ArrayList(); + // // int kind = getKind(); + // String extType; + // // if (kind == IPackageFragmentRoot.K_SOURCE) { + // extType = "php"; //$NON-NLS-1$ + // // } else { + // // extType = "class"; //$NON-NLS-1$ + // // } + // try { + // char[][] exclusionPatterns = + // ((PackageFragmentRoot)getPackageFragmentRoot()).fullExclusionPatternChars(); + // IResource[] members = ((IContainer) resource).members(); + // for (int i = 0, max = members.length; i < max; i++) { + // IResource child = members[i]; + // if (child.getType() != IResource.FOLDER + // && !ProjectPrefUtil.isExcluded(child, exclusionPatterns)) { + // String extension = child.getProjectRelativePath().getFileExtension(); + // if (extension != null) { + // if (extension.equalsIgnoreCase(extType)) { + // IJavaElement childElement; + // // if (kind == IPackageFragmentRoot.K_SOURCE && + // ProjectPrefUtil.isValidCompilationUnitName(child.getName())) { + // // childElement = getCompilationUnit(child.getName()); + // // vChildren.add(childElement); + // // } else if (ProjectPrefUtil.isValidClassFileName(child.getName())) { + // // childElement = getClassFile(child.getName()); + // // vChildren.add(childElement); + // // } + // } + // } + // } + // } + // } catch (CoreException e) { + // throw new JavaModelException(e); + // } + // IJavaElement[] children = new IJavaElement[vChildren.size()]; + // vChildren.toArray(children); + // info.setChildren(children); + // return true; + // } + /** + * Returns true if this fragment contains at least one java resource. + * Returns false otherwise. + */ + // public boolean containsJavaResources() throws JavaModelException { + // return ((PackageFragmentInfo) getElementInfo()).containsJavaResources(); + // } + /** + * @see ISourceManipulation + */ + // public void copy(IJavaElement container, IJavaElement sibling, String + // rename, boolean force, IProgressMonitor monitor) throws + // JavaModelException { + // if (container == null) { + // throw new + // IllegalArgumentException(ProjectPrefUtil.bind("operation.nullContainer")); + // //$NON-NLS-1$ + // } + // IJavaElement[] elements= new IJavaElement[] {this}; + // IJavaElement[] containers= new IJavaElement[] {container}; + // IJavaElement[] siblings= null; + // if (sibling != null) { + // siblings= new IJavaElement[] {sibling}; + // } + // String[] renamings= null; + // if (rename != null) { + // renamings= new String[] {rename}; + // } + // getJavaModel().copy(elements, containers, siblings, renamings, force, + // monitor); + // } + /** + * @see IPackageFragment + */ + public ICompilationUnit createCompilationUnit(String name, String contents, + boolean force, IProgressMonitor monitor) throws JavaModelException { + // CreateCompilationUnitOperation op= new + // CreateCompilationUnitOperation(this, name, contents, force); + // runOperation(op, monitor); + // return getCompilationUnit(name); + return null; } - return new CompilationUnit(this, cuName, DefaultWorkingCopyOwner.PRIMARY); -} -/** - * @see IPackageFragment#getCompilationUnits() - */ -public ICompilationUnit[] getCompilationUnits() throws JavaModelException { - if (getKind() == IPackageFragmentRoot.K_BINARY) { - return fgEmptyCompilationUnitList; + + /** + * @see JavaElement + */ + protected Object createElementInfo() { + return new PackageFragmentInfo(); } - - ArrayList list = getChildrenOfType(COMPILATION_UNIT); - ICompilationUnit[] array= new ICompilationUnit[list.size()]; - list.toArray(array); - return array; -} -/** - * @see IJavaElement - */ -public int getElementType() { - return PACKAGE_FRAGMENT; -} -/* - * @see JavaElement - */ -public IJavaElement getHandleFromMemento(String token, MementoTokenizer memento, WorkingCopyOwner owner) { - switch (token.charAt(0)) { + + /** + * @see ISourceManipulation + */ + // public void delete(boolean force, IProgressMonitor monitor) throws + // JavaModelException { + // IJavaElement[] elements = new IJavaElement[] {this}; + // getJavaModel().delete(elements, force, monitor); + // } + // /** + // * @see Openable + // */ + // protected boolean generateInfos(OpenableElementInfo info, + // IProgressMonitor pm, Map newElements, IResource underlyingResource) + // throws JavaModelException { + // + // return computeChildren(info, underlyingResource); + // } + // /** + // * @see IPackageFragment#getClassFile(String) + // */ + // public IClassFile getClassFile(String name) { + // return new ClassFile(this, name); + // } + /** + * Returns a the collection of class files in this - a folder package + * fragment which has a root that has its kind set to + * IPackageFragmentRoot.K_Source does not recognize class + * files. + * + * @see IPackageFragment#getClassFiles() + */ + // public IClassFile[] getClassFiles() throws JavaModelException { + // if (getKind() == IPackageFragmentRoot.K_SOURCE) { + // return fgEmptyClassFileList; + // } + // + // ArrayList list = getChildrenOfType(CLASS_FILE); + // IClassFile[] array= new IClassFile[list.size()]; + // list.toArray(array); + // return array; + // } + /** + * @see IPackageFragment#getCompilationUnit(String) + * @exception IllegalArgumentExcpetion + * if the name does not end with a php file extension + */ + public ICompilationUnit getCompilationUnit(String cuName) { + if (!PHPFileUtil.isValidPHPUnitName(cuName)) { + throw new IllegalArgumentException(Util + .bind("convention.unit.notJavaName")); //$NON-NLS-1$ + } + return new CompilationUnit(this, cuName, + DefaultWorkingCopyOwner.PRIMARY); + } + + /** + * @see IPackageFragment#getCompilationUnits() + */ + public ICompilationUnit[] getCompilationUnits() throws JavaModelException { + if (getKind() == IPackageFragmentRoot.K_BINARY) { + return fgEmptyCompilationUnitList; + } + + ArrayList list = getChildrenOfType(COMPILATION_UNIT); + ICompilationUnit[] array = new ICompilationUnit[list.size()]; + list.toArray(array); + return array; + } + + /** + * @see IJavaElement + */ + public int getElementType() { + return PACKAGE_FRAGMENT; + } + + /* + * @see JavaElement + */ + public IJavaElement getHandleFromMemento(String token, + MementoTokenizer memento, WorkingCopyOwner owner) { + switch (token.charAt(0)) { case JEM_COUNT: return getHandleUpdatingCountFromMemento(memento, owner); -// case JEM_CLASSFILE: -// String classFileName = memento.nextToken(); -// JavaElement classFile = (JavaElement)getClassFile(classFileName); -// return classFile.getHandleFromMemento(memento, owner); + // case JEM_CLASSFILE: + // String classFileName = memento.nextToken(); + // JavaElement classFile = (JavaElement)getClassFile(classFileName); + // return classFile.getHandleFromMemento(memento, owner); case JEM_COMPILATIONUNIT: String cuName = memento.nextToken(); JavaElement cu = new CompilationUnit(this, cuName, owner); return cu.getHandleFromMemento(memento, owner); + } + return null; } - return null; -} -/** - * @see JavaElement#getHandleMementoDelimiter() - */ -protected char getHandleMementoDelimiter() { - return JavaElement.JEM_PACKAGEFRAGMENT; -} -/** - * @see IPackageFragment#getKind() - */ -public int getKind() throws JavaModelException { - return ((IPackageFragmentRoot)getParent()).getKind(); -} -/** - * Returns an array of non-java resources contained in the receiver. - */ -//public Object[] getNonJavaResources() throws JavaModelException { -// if (this.isDefaultPackage()) { -// // We don't want to show non java resources of the default package (see PR #1G58NB8) -// return JavaElementInfo.NO_NON_JAVA_RESOURCES; -// } else { -// return ((PackageFragmentInfo) getElementInfo()).getNonJavaResources(getResource(), (PackageFragmentRoot)getPackageFragmentRoot()); -// } -//} -/** - * @see IJavaElement#getPath() - */ -public IPath getPath() { - PackageFragmentRoot root = this.getPackageFragmentRoot(); - if (root.isArchive()) { - return root.getPath(); - } else { -// return root.getPath().append(this.getElementName().replace('.', '/')); - return root.getPath().append(this.getElementName()); + + /** + * @see JavaElement#getHandleMementoDelimiter() + */ + protected char getHandleMementoDelimiter() { + return JavaElement.JEM_PACKAGEFRAGMENT; } -} -/** - * @see IJavaElement#getResource() - */ -public IResource getResource() { - PackageFragmentRoot root = this.getPackageFragmentRoot(); - if (root.isArchive()) { - return root.getResource(); - } else { - String elementName = this.getElementName(); - if (elementName.length() == 0) { - return root.getResource(); + + /** + * @see IPackageFragment#getKind() + */ + public int getKind() throws JavaModelException { + return ((IPackageFragmentRoot) getParent()).getKind(); + } + + /** + * Returns an array of non-java resources contained in the receiver. + */ + // public Object[] getNonJavaResources() throws JavaModelException { + // if (this.isDefaultPackage()) { + // // We don't want to show non java resources of the default package (see + // PR #1G58NB8) + // return JavaElementInfo.NO_NON_JAVA_RESOURCES; + // } else { + // return ((PackageFragmentInfo) + // getElementInfo()).getNonJavaResources(getResource(), + // (PackageFragmentRoot)getPackageFragmentRoot()); + // } + // } + /** + * @see IJavaElement#getPath() + */ + public IPath getPath() { + PackageFragmentRoot root = this.getPackageFragmentRoot(); + if (root.isArchive()) { + return root.getPath(); } else { -// return ((IContainer)root.getResource()).getFolder(new Path(this.getElementName().replace('.', '/'))); - return ((IContainer)root.getResource()).getFolder(new Path(this.getElementName())); + // return root.getPath().append(this.getElementName().replace('.', + // '/')); + return root.getPath().append(this.getElementName()); } } -} -/** - * @see IJavaElement#getUnderlyingResource() - */ -public IResource getUnderlyingResource() throws JavaModelException { - IResource rootResource = parent.getUnderlyingResource(); - if (rootResource == null) { - //jar package fragment root that has no associated resource - return null; + + /** + * @see IJavaElement#getResource() + */ + public IResource getResource() { + PackageFragmentRoot root = this.getPackageFragmentRoot(); + if (root.isArchive()) { + return root.getResource(); + } else { + String elementName = this.getElementName(); + if (elementName.length() == 0) { + return root.getResource(); + } else { + // return ((IContainer)root.getResource()).getFolder(new + // Path(this.getElementName().replace('.', '/'))); + return ((IContainer) root.getResource()).getFolder(new Path( + this.getElementName())); + } + } } - // the underlying resource may be a folder or a project (in the case that the project folder - // is atually the package fragment root) -// if (rootResource.getType() == IResource.FOLDER || rootResource.getType() == IResource.PROJECT) { -// IContainer folder = (IContainer) rootResource; -// String[] segs = Signature.getSimpleNames(fName); -// for (int i = 0; i < segs.length; ++i) { -// IResource child = folder.findMember(segs[i]); -// if (child == null || child.getType() != IResource.FOLDER) { -// throw newNotPresentException(); -// } -// folder = (IFolder) child; -// } -// return folder; -// } else { + + /** + * @see IJavaElement#getUnderlyingResource() + */ + public IResource getUnderlyingResource() throws JavaModelException { + IResource rootResource = parent.getUnderlyingResource(); + if (rootResource == null) { + // jar package fragment root that has no associated resource + return null; + } + // the underlying resource may be a folder or a project (in the case + // that the project folder + // is atually the package fragment root) + // if (rootResource.getType() == IResource.FOLDER || + // rootResource.getType() == IResource.PROJECT) { + // IContainer folder = (IContainer) rootResource; + // String[] segs = Signature.getSimpleNames(fName); + // for (int i = 0; i < segs.length; ++i) { + // IResource child = folder.findMember(segs[i]); + // if (child == null || child.getType() != IResource.FOLDER) { + // throw newNotPresentException(); + // } + // folder = (IFolder) child; + // } + // return folder; + // } else { return rootResource; -// } -} -/** - * @see IPackageFragment#hasSubpackages() - */ -//public boolean hasSubpackages() throws JavaModelException { -// IJavaElement[] packages= ((IPackageFragmentRoot)getParent()).getChildren(); -// String name = getElementName(); -// int nameLength = name.length(); -// String packageName = isDefaultPackage() ? name : name+"."; //$NON-NLS-1$ -// for (int i= 0; i < packages.length; i++) { -// String otherName = packages[i].getElementName(); -// if (otherName.length() > nameLength && otherName.startsWith(packageName)) { -// return true; -// } -// } -// return false; -//} -/** - * @see IPackageFragment#isDefaultPackage() - */ -public boolean isDefaultPackage() { - return this.getElementName().length() == 0; -} -/** - * @see ISourceManipulation#move(IJavaElement, IJavaElement, String, boolean, IProgressMonitor) - */ -//public void move(IJavaElement container, IJavaElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaModelException { -// if (container == null) { -// throw new IllegalArgumentException(ProjectPrefUtil.bind("operation.nullContainer")); //$NON-NLS-1$ -// } -// IJavaElement[] elements= new IJavaElement[] {this}; -// IJavaElement[] containers= new IJavaElement[] {container}; -// IJavaElement[] siblings= null; -// if (sibling != null) { -// siblings= new IJavaElement[] {sibling}; -// } -// String[] renamings= null; -// if (rename != null) { -// renamings= new String[] {rename}; -// } -// getJavaModel().move(elements, containers, siblings, renamings, force, monitor); -//} -//protected void openWhenClosed(IProgressMonitor pm) throws JavaModelException { -// if (!this.resourceExists()) throw newNotPresentException(); -// super.openWhenClosed(pm); -//} -/** - * Recomputes the children of this element, based on the current state - * of the workbench. - */ -//public void refreshChildren() { -// try { -// OpenableElementInfo info= (OpenableElementInfo)getElementInfo(); -// computeChildren(info, getResource()); -// } catch (JavaModelException e) { -// // do nothing. -// } -//} -/** - * @see ISourceManipulation#rename(String, boolean, IProgressMonitor) - */ -//public void rename(String name, boolean force, IProgressMonitor monitor) throws JavaModelException { -// if (name == null) { -// throw new IllegalArgumentException(ProjectPrefUtil.bind("element.nullName")); //$NON-NLS-1$ -// } -// IJavaElement[] elements= new IJavaElement[] {this}; -// IJavaElement[] dests= new IJavaElement[] {this.getParent()}; -// String[] renamings= new String[] {name}; -// getJavaModel().rename(elements, dests, renamings, force, monitor); -//} -///* -// * @see JavaElement#rootedAt(IJavaProject) -// */ -//public IJavaElement rootedAt(IJavaProject project) { -// return -// new PackageFragment( -// (IPackageFragmentRoot)((JavaElement)parent).rootedAt(project), -// name); -//} -/** - * Debugging purposes - */ -protected void toStringChildren(int tab, StringBuffer buffer, Object info) { - if (tab == 0) { - super.toStringChildren(tab, buffer, info); + // } } -} -/** - * Debugging purposes - */ -protected void toStringInfo(int tab, StringBuffer buffer, Object info) { - buffer.append(this.tabString(tab)); - if (getElementName().length() == 0) { - buffer.append("[default]"); //$NON-NLS-1$ - } else { - buffer.append(getElementName()); + + /** + * @see IPackageFragment#hasSubpackages() + */ + // public boolean hasSubpackages() throws JavaModelException { + // IJavaElement[] packages= + // ((IPackageFragmentRoot)getParent()).getChildren(); + // String name = getElementName(); + // int nameLength = name.length(); + // String packageName = isDefaultPackage() ? name : name+"."; //$NON-NLS-1$ + // for (int i= 0; i < packages.length; i++) { + // String otherName = packages[i].getElementName(); + // if (otherName.length() > nameLength && otherName.startsWith(packageName)) + // { + // return true; + // } + // } + // return false; + // } + /** + * @see IPackageFragment#isDefaultPackage() + */ + public boolean isDefaultPackage() { + return this.getElementName().length() == 0; } - if (info == null) { - buffer.append(" (not open)"); //$NON-NLS-1$ - } else { - if (tab > 0) { - buffer.append(" (...)"); //$NON-NLS-1$ + + /** + * @see ISourceManipulation#move(IJavaElement, IJavaElement, String, + * boolean, IProgressMonitor) + */ + // public void move(IJavaElement container, IJavaElement sibling, String + // rename, boolean force, IProgressMonitor monitor) throws + // JavaModelException { + // if (container == null) { + // throw new + // IllegalArgumentException(ProjectPrefUtil.bind("operation.nullContainer")); + // //$NON-NLS-1$ + // } + // IJavaElement[] elements= new IJavaElement[] {this}; + // IJavaElement[] containers= new IJavaElement[] {container}; + // IJavaElement[] siblings= null; + // if (sibling != null) { + // siblings= new IJavaElement[] {sibling}; + // } + // String[] renamings= null; + // if (rename != null) { + // renamings= new String[] {rename}; + // } + // getJavaModel().move(elements, containers, siblings, renamings, force, + // monitor); + // } + // protected void openWhenClosed(IProgressMonitor pm) throws + // JavaModelException { + // if (!this.resourceExists()) throw newNotPresentException(); + // super.openWhenClosed(pm); + // } + /** + * Recomputes the children of this element, based on the current state of + * the workbench. + */ + // public void refreshChildren() { + // try { + // OpenableElementInfo info= (OpenableElementInfo)getElementInfo(); + // computeChildren(info, getResource()); + // } catch (JavaModelException e) { + // // do nothing. + // } + // } + /** + * @see ISourceManipulation#rename(String, boolean, IProgressMonitor) + */ + // public void rename(String name, boolean force, IProgressMonitor monitor) + // throws JavaModelException { + // if (name == null) { + // throw new + // IllegalArgumentException(ProjectPrefUtil.bind("element.nullName")); + // //$NON-NLS-1$ + // } + // IJavaElement[] elements= new IJavaElement[] {this}; + // IJavaElement[] dests= new IJavaElement[] {this.getParent()}; + // String[] renamings= new String[] {name}; + // getJavaModel().rename(elements, dests, renamings, force, monitor); + // } + // /* + // * @see JavaElement#rootedAt(IJavaProject) + // */ + // public IJavaElement rootedAt(IJavaProject project) { + // return + // new PackageFragment( + // (IPackageFragmentRoot)((JavaElement)parent).rootedAt(project), + // name); + // } + /** + * Debugging purposes + */ + protected void toStringChildren(int tab, StringBuffer buffer, Object info) { + if (tab == 0) { + super.toStringChildren(tab, buffer, info); + } + } + + /** + * Debugging purposes + */ + protected void toStringInfo(int tab, StringBuffer buffer, Object info) { + buffer.append(this.tabString(tab)); + if (getElementName().length() == 0) { + buffer.append("[default]"); //$NON-NLS-1$ + } else { + buffer.append(getElementName()); + } + if (info == null) { + buffer.append(" (not open)"); //$NON-NLS-1$ + } else { + if (tab > 0) { + buffer.append(" (...)"); //$NON-NLS-1$ + } } } -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragmentInfo.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragmentInfo.java index 01a8258..835ce31 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragmentInfo.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragmentInfo.java @@ -15,7 +15,6 @@ import net.sourceforge.phpdt.core.JavaModelException; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IResource; - /** * Element info for PackageFragments. */ @@ -26,39 +25,43 @@ class PackageFragmentInfo extends OpenableElementInfo { */ protected Object[] fNonJavaResources; -/** - * Create and initialize a new instance of the receiver - */ -public PackageFragmentInfo() { - fNonJavaResources = null; -} -/** - */ -boolean containsJavaResources() { - return fChildren.length != 0; -} -/** - * Returns an array of non-java resources contained in the receiver. - */ -Object[] getNonJavaResources(IResource underlyingResource, PackageFragmentRoot rootHandle) { - Object[] nonJavaResources = fNonJavaResources; - if (nonJavaResources == null) { - try { - nonJavaResources = - PackageFragmentRootInfo.computeFolderNonJavaResources( - (JavaProject)rootHandle.getJavaProject(), - (IContainer)underlyingResource, - rootHandle.fullExclusionPatternChars()); - } catch (JavaModelException e) { + /** + * Create and initialize a new instance of the receiver + */ + public PackageFragmentInfo() { + fNonJavaResources = null; + } + + /** + */ + boolean containsJavaResources() { + return fChildren.length != 0; + } + + /** + * Returns an array of non-java resources contained in the receiver. + */ + Object[] getNonJavaResources(IResource underlyingResource, + PackageFragmentRoot rootHandle) { + Object[] nonJavaResources = fNonJavaResources; + if (nonJavaResources == null) { + try { + nonJavaResources = PackageFragmentRootInfo + .computeFolderNonJavaResources((JavaProject) rootHandle + .getJavaProject(), + (IContainer) underlyingResource, rootHandle + .fullExclusionPatternChars()); + } catch (JavaModelException e) { + } + fNonJavaResources = nonJavaResources; } - fNonJavaResources = nonJavaResources; + return nonJavaResources; + } + + /** + * Set the fNonJavaResources to res value + */ + synchronized void setNonJavaResources(Object[] resources) { + fNonJavaResources = resources; } - return nonJavaResources; -} -/** - * Set the fNonJavaResources to res value - */ -synchronized void setNonJavaResources(Object[] resources) { - fNonJavaResources = resources; -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragmentRoot.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragmentRoot.java index a07e245..bc95281 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragmentRoot.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragmentRoot.java @@ -36,959 +36,1077 @@ import org.eclipse.core.runtime.QualifiedName; /** * @see IPackageFragmentRoot */ -public class PackageFragmentRoot extends Openable implements IPackageFragmentRoot { - - /** - * The delimiter between the source path and root path in the attachment server property. - */ - protected final static char ATTACHMENT_PROPERTY_DELIMITER = '*'; - - /* - * No source attachment property - */ - protected final static String NO_SOURCE_ATTACHMENT = ""; //$NON-NLS-1$ - - /* - * No source mapper singleton - */ - // protected final static SourceMapper NO_SOURCE_MAPPER = new SourceMapper(); - /** - * The resource associated with this root. (an IResource or a java.io.File (for external jar only)) - */ - protected Object resource; - - /** - * Constructs a package fragment root which is the root of the java package directory hierarchy. - */ - protected PackageFragmentRoot(IResource resource, JavaProject project, String name) { - super(project, name); - this.resource = resource; - } - - /** - * @see Openable - */ - protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) - throws JavaModelException { - - // check whether this pkg fragment root can be opened - if (!resourceExists()) { //|| !isOnClasspath()) { - throw newNotPresentException(); - } - - ((PackageFragmentRootInfo) info).setRootKind(determineKind(underlyingResource)); - return computeChildren(info, newElements); - } - - /** - * Returns the root's kind - K_SOURCE or K_BINARY, defaults to K_SOURCE if it is not on the classpath. - * - * @exception NotPresentException - * if the project and root do not exist. - */ - protected int determineKind(IResource underlyingResource) throws JavaModelException { - // IClasspathEntry[] entries= ((JavaProject)getJavaProject()).getExpandedClasspath(true); - // for (int i= 0; i < entries.length; i++) { - // IClasspathEntry entry= entries[i]; - // if (entry.getPath().equals(underlyingResource.getFullPath())) { - // return entry.getContentKind(); - // } - // } - return IPackageFragmentRoot.K_SOURCE; - } - - /** - * Compute the package fragment children of this package fragment root. - * - * @exception JavaModelException - * The resource associated with this package fragment root does not exist - */ - protected boolean computeChildren(OpenableElementInfo info, Map newElements) throws JavaModelException { - // Note the children are not opened (so not added to newElements) for a regular package fragment root - // Howver they are opened for a Jar package fragment root (see JarPackageFragmentRoot#computeChildren) - try { - // the underlying resource may be a folder or a project (in the case that the project folder - // is actually the package fragment root) - IResource underlyingResource = getResource(); - if (underlyingResource.getType() == IResource.FOLDER || underlyingResource.getType() == IResource.PROJECT) { - ArrayList vChildren = new ArrayList(5); - IContainer rootFolder = (IContainer) underlyingResource; - // char[][] inclusionPatterns = fullInclusionPatternChars(); - char[][] exclusionPatterns = fullExclusionPatternChars(); - computeFolderChildren(rootFolder, !Util.isExcluded(rootFolder, exclusionPatterns), "", vChildren, exclusionPatterns); //$NON-NLS-1$ - - IJavaElement[] children = new IJavaElement[vChildren.size()]; - vChildren.toArray(children); - info.setChildren(children); - } - } catch (JavaModelException e) { - //problem resolving children; structure remains unknown - info.setChildren(new IJavaElement[] {}); - throw e; - } - return true; - } - - /** - * Starting at this folder, create package fragments and add the fragments that are not exclused to the collection of children. - * - * @exception JavaModelException - * The resource associated with this package fragment does not exist - */ - protected void computeFolderChildren(IContainer folder, boolean isIncluded, String prefix, ArrayList vChildren, - char[][] exclusionPatterns) throws JavaModelException { - //, char[][] inclusionPatterns, char[][] exclusionPatterns) throws JavaModelException { - - if (isIncluded) { - IPackageFragment pkg = getPackageFragment(prefix); - vChildren.add(pkg); - } - try { - JavaProject javaProject = (JavaProject) getJavaProject(); - IResource[] members = folder.members(); - boolean hasIncluded = isIncluded; - for (int i = 0, max = members.length; i < max; i++) { - IResource member = members[i]; - String memberName = member.getName(); - - switch (member.getType()) { - - case IResource.FOLDER: - if (Util.isValidFolderNameForPackage(memberName)) { - boolean isMemberIncluded = !Util.isExcluded(member, exclusionPatterns); - // keep looking inside as long as included already, or may have child included due to inclusion patterns - // if (isMemberIncluded || inclusionPatterns != null) { - // // eliminate binary output only if nested inside direct subfolders - // if (javaProject.contains(member)) { - // String newPrefix; - // if (prefix.length() == 0) { - // newPrefix = memberName; - // } else { - // newPrefix = prefix + "." + memberName; //$NON-NLS-1$ - // } - // computeFolderChildren((IFolder) member, isMemberIncluded, newPrefix, vChildren, inclusionPatterns, - // exclusionPatterns); - // } - // } - } - break; - case IResource.FILE: - // inclusion filter may only include files, in which case we still want to include the immediate parent package (lazily) - if (!hasIncluded && Util.isValidCompilationUnitName(memberName) && !Util.isExcluded(member, exclusionPatterns)) { - hasIncluded = true; - IPackageFragment pkg = getPackageFragment(prefix); - vChildren.add(pkg); - } - break; - } - } - } catch (IllegalArgumentException e) { - throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); // could be thrown by ElementTree when path - // is not found - } catch (CoreException e) { - throw new JavaModelException(e); - } - } - - /** - * @see IPackageFragmentRoot - */ - //public void attachSource(IPath sourcePath, IPath rootPath, IProgressMonitor monitor) throws JavaModelException { - // try { - // verifyAttachSource(sourcePath); - // if (monitor != null) { - // monitor.beginTask(ProjectPrefUtil.bind("element.attachingSource"), 2); //$NON-NLS-1$ - // } - // SourceMapper oldMapper= getSourceMapper(); - // IWorkspace workspace = ResourcesPlugin.getWorkspace(); - // boolean rootNeedsToBeClosed= false; - // - // if (sourcePath == null) { - // //source being detached - // rootNeedsToBeClosed= true; - // setSourceMapper(null); - // /* Disable deltas (see 1GDTUSD) - // // fire a delta to notify the UI about the source detachement. - // JavaModelManager manager = (JavaModelManager) JavaModelManager.getJavaModelManager(); - // JavaModel model = (JavaModel) getJavaModel(); - // JavaElementDelta attachedSourceDelta = new JavaElementDelta(model); - // attachedSourceDelta .sourceDetached(this); // this would be a PackageFragmentRoot - // manager.registerResourceDelta(attachedSourceDelta ); - // manager.fire(); // maybe you want to fire the change later. Let us know about it. - // */ - // } else { - // /* - // // fire a delta to notify the UI about the source attachement. - // JavaModelManager manager = (JavaModelManager) JavaModelManager.getJavaModelManager(); - // JavaModel model = (JavaModel) getJavaModel(); - // JavaElementDelta attachedSourceDelta = new JavaElementDelta(model); - // attachedSourceDelta .sourceAttached(this); // this would be a PackageFragmentRoot - // manager.registerResourceDelta(attachedSourceDelta ); - // manager.fire(); // maybe you want to fire the change later. Let us know about it. - // */ - // - // //check if different from the current attachment - // IPath storedSourcePath= getSourceAttachmentPath(); - // IPath storedRootPath= getSourceAttachmentRootPath(); - // if (monitor != null) { - // monitor.worked(1); - // } - // if (storedSourcePath != null) { - // if (!(storedSourcePath.equals(sourcePath) && (rootPath != null && rootPath.equals(storedRootPath)) || storedRootPath == null)) - // { - // rootNeedsToBeClosed= true; - // } - // } - // // check if source path is valid - // Object target = JavaModel.getTarget(workspace.getRoot(), sourcePath, false); - // if (target == null) { - // if (monitor != null) { - // monitor.done(); - // } - // throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, sourcePath)); - // } - // SourceMapper mapper = createSourceMapper(sourcePath, rootPath); - // if (rootPath == null && mapper.rootPath != null) { - // // as a side effect of calling the SourceMapper constructor, the root path was computed - // rootPath = new Path(mapper.rootPath); - // } - // setSourceMapper(mapper); - // } - // if (sourcePath == null) { - // setSourceAttachmentProperty(null); //remove the property - // } else { - // //set the property to the path of the mapped source - // setSourceAttachmentProperty( - // sourcePath.toString() - // + (rootPath == null ? "" : (ATTACHMENT_PROPERTY_DELIMITER + rootPath.toString()))); //$NON-NLS-1$ - // } - // if (rootNeedsToBeClosed) { - // if (oldMapper != null) { - // oldMapper.close(); - // } - // BufferManager manager= BufferManager.getDefaultBufferManager(); - // Enumeration openBuffers= manager.getOpenBuffers(); - // while (openBuffers.hasMoreElements()) { - // IBuffer buffer= (IBuffer) openBuffers.nextElement(); - // IOpenable possibleMember= buffer.getOwner(); - // if (isAncestorOf((IJavaElement) possibleMember)) { - // buffer.close(); - // } - // } - // if (monitor != null) { - // monitor.worked(1); - // } - // } - // } catch (JavaModelException e) { - // setSourceAttachmentProperty(null); // loose info - will be recomputed - // throw e; - // } finally { - // if (monitor != null) { - // monitor.done(); - // } - // } - //} - //SourceMapper createSourceMapper(IPath sourcePath, IPath rootPath) { - // SourceMapper mapper = new SourceMapper( - // sourcePath, - // rootPath == null ? null : rootPath.toOSString(), - // this.isExternal() ? JavaCore.getOptions() : this.getJavaProject().getOptions(true)); // only project options if associated with - // resource - // return mapper; - //} - /* - * @see net.sourceforge.phpdt.core.IPackageFragmentRoot#delete - */ - //public void delete( - // int updateResourceFlags, - // int updateModelFlags, - // IProgressMonitor monitor) - // throws JavaModelException { - // - // DeletePackageFragmentRootOperation op = new DeletePackageFragmentRootOperation(this, updateResourceFlags, updateModelFlags); - // runOperation(op, monitor); - //} - /** - * This root is being closed. If this root has an associated source attachment, close it too. - * - * @see JavaElement - */ - //protected void closing(Object info) throws JavaModelException { TODO remove after 2.1 - // ((PackageFragmentRootInfo) info).sourceMapper = null; - // super.closing(info); - //} - /** - * Compute the package fragment children of this package fragment root. - * - * @exception JavaModelException - * The resource associated with this package fragment root does not exist - */ - //protected boolean computeChildren(OpenableElementInfo info) throws JavaModelException { - // try { - // // the underlying resource may be a folder or a project (in the case that the project folder - // // is actually the package fragment root) - // IResource resource = getResource(); - // if (resource.getType() == IResource.FOLDER || resource.getType() == IResource.PROJECT) { - // ArrayList vChildren = new ArrayList(5); - // char[][] exclusionPatterns = fullExclusionPatternChars(); - // computeFolderChildren((IContainer) resource, "", vChildren, exclusionPatterns); //$NON-NLS-1$ - // IJavaElement[] children = new IJavaElement[vChildren.size()]; - // vChildren.toArray(children); - // info.setChildren(children); - // } - // } catch (JavaModelException e) { - // //problem resolving children; structure remains unknown - // info.setChildren(new IJavaElement[]{}); - // throw e; - // } - // return true; - //} - /** - * Starting at this folder, create package fragments and add the fragments that are not exclused to the collection of children. - * - * @exception JavaModelException - * The resource associated with this package fragment does not exist - */ - //protected void computeFolderChildren(IContainer folder, String prefix, ArrayList vChildren, char[][] exclusionPatterns) throws - // JavaModelException { - // IPackageFragment pkg = getPackageFragment(prefix); - // vChildren.add(pkg); - // try { - // JavaProject javaProject = (JavaProject)getJavaProject(); - // IResource[] members = folder.members(); - // for (int i = 0, max = members.length; i < max; i++) { - // IResource member = members[i]; - // String memberName = member.getName(); - // if (member.getType() == IResource.FOLDER - // && ProjectPrefUtil.isValidFolderNameForPackage(memberName) - // && !ProjectPrefUtil.isExcluded(member, exclusionPatterns)) { - // - // // eliminate binary output only if nested inside direct subfolders - // if (javaProject.contains(member)) { - // String newPrefix; - // if (prefix.length() == 0) { - // newPrefix = memberName; - // } else { - // newPrefix = prefix + "." + memberName; //$NON-NLS-1$ - // } - // computeFolderChildren((IFolder) member, newPrefix, vChildren, exclusionPatterns); - // } - // } - // } - // } catch(IllegalArgumentException e){ - // throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); // could be thrown by ElementTree when path - // is not found - // } catch (CoreException e) { - // throw new JavaModelException(e); - // } - //} - /* - * Computes and returns the source attachment root path for the given source attachment path. Returns null if none - * could be found. - * - * @param sourceAttachmentPath the given absolute path to the source archive or folder @return the computed source attachment root - * path or null if none could be found @throws JavaModelException - */ - //public IPath computeSourceAttachmentRootPath(IPath sourceAttachmentPath) throws JavaModelException { - // IPath sourcePath = this.getSourceAttachmentPath(); - // if (sourcePath == null) return null; - // SourceMapper mapper = - // new SourceMapper( - // sourcePath, - // null, // detect root path - // this.isExternal() ? JavaCore.getOptions() : this.getJavaProject().getOptions(true) // only project options if associated with - // resource - // ); - // if (mapper.rootPath == null) return null; - // return new Path(mapper.rootPath); - //} - /* - * @see net.sourceforge.phpdt.core.IPackageFragmentRoot#copy - */ - //public void copy( - // IPath destination, - // int updateResourceFlags, - // int updateModelFlags, - // IClasspathEntry sibling, - // IProgressMonitor monitor) - // throws JavaModelException { - // - // CopyPackageFragmentRootOperation op = - // new CopyPackageFragmentRootOperation(this, destination, updateResourceFlags, updateModelFlags, sibling); - // runOperation(op, monitor); - //} - - /** - * Returns a new element info for this element. - */ - protected Object createElementInfo() { - return new PackageFragmentRootInfo(); - } - - /** - * @see IPackageFragmentRoot - */ - //public IPackageFragment createPackageFragment(String name, boolean force, IProgressMonitor monitor) throws JavaModelException { - // CreatePackageFragmentOperation op = new CreatePackageFragmentOperation(this, name, force); - // runOperation(op, monitor); - // return getPackageFragment(name); - //} - /** - * Returns the root's kind - K_SOURCE or K_BINARY, defaults to K_SOURCE if it is not on the classpath. - * - * @exception NotPresentException - * if the project and root do not exist. - */ - //protected int determineKind(IResource underlyingResource) throws JavaModelException { - // IClasspathEntry[] entries= ((JavaProject)getJavaProject()).getExpandedClasspath(true); - // for (int i= 0; i < entries.length; i++) { - // IClasspathEntry entry= entries[i]; - // if (entry.getPath().equals(underlyingResource.getFullPath())) { - // return entry.getContentKind(); - // } - // } - // return IPackageFragmentRoot.K_SOURCE; - //} - /** - * Compares two objects for equality; for PackageFragmentRoots, equality is having the same JavaModel, - * same resources, and occurrence count. - * - */ - public boolean equals(Object o) { - if (this == o) - return true; - if (!(o instanceof PackageFragmentRoot)) - return false; - PackageFragmentRoot other = (PackageFragmentRoot) o; - return getJavaModel().equals(other.getJavaModel()) && this.resource.equals(other.resource) - && occurrenceCount == other.occurrenceCount; - } - - /** - * @see IJavaElement - */ - //public boolean exists() { - // return super.exists() - // && isOnClasspath(); - //} - //public IClasspathEntry findSourceAttachmentRecommendation() { - // try { - // IPath rootPath = this.getPath(); - // IClasspathEntry entry; - // IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); - // - // // try on enclosing project first - // JavaProject parentProject = (JavaProject) getJavaProject(); - // try { - // entry = parentProject.getClasspathEntryFor(rootPath); - // if (entry != null){ - // Object target = JavaModel.getTarget(workspaceRoot, entry.getSourceAttachmentPath(), true); - // if (target instanceof IFile){ - // IFile file = (IFile) target; - // if (ProjectPrefUtil.isArchiveFileName(file.getName())){ - // return entry; - // } - // } else if (target instanceof IFolder) { - // return entry; - // } - // if (target instanceof java.io.File){ - // java.io.File file = (java.io.File) target; - // if (file.isFile()) { - // if (ProjectPrefUtil.isArchiveFileName(file.getName())){ - // return entry; - // } - // } else { - // // external directory - // return entry; - // } - // } - // } - // } catch(JavaModelException e){ - // } - // - // // iterate over all projects - // IJavaModel model = getJavaModel(); - // IJavaProject[] jProjects = model.getJavaProjects(); - // for (int i = 0, max = jProjects.length; i < max; i++){ - // JavaProject jProject = (JavaProject) jProjects[i]; - // if (jProject == parentProject) continue; // already done - // try { - // entry = jProject.getClasspathEntryFor(rootPath); - // if (entry != null){ - // Object target = JavaModel.getTarget(workspaceRoot, entry.getSourceAttachmentPath(), true); - // if (target instanceof IFile){ - // IFile file = (IFile) target; - // if (ProjectPrefUtil.isArchiveFileName(file.getName())){ - // return entry; - // } - // } else if (target instanceof IFolder) { - // return entry; - // } - // if (target instanceof java.io.File){ - // java.io.File file = (java.io.File) target; - // if (file.isFile()) { - // if (ProjectPrefUtil.isArchiveFileName(file.getName())){ - // return entry; - // } - // } else { - // // external directory - // return entry; - // } - // } - // } - // } catch(JavaModelException e){ - // } - // } - // } catch(JavaModelException e){ - // } - // - // return null; - //} - /* - * Returns the exclusion patterns from the classpath entry associated with this root. - */ - char[][] fullExclusionPatternChars() { - return null; - // try { - - // if (this.isOpen() && this.getKind() != IPackageFragmentRoot.K_SOURCE) return null; - // ClasspathEntry entry = (ClasspathEntry)getRawClasspathEntry(); - // if (entry == null) { - // return null; - // } else { - // return entry.fullExclusionPatternChars(); - // } - // } catch (JavaModelException e) { - // return null; - // } - } - - /** - * @see Openable - */ - protected boolean generateInfos(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) - throws JavaModelException { - - // ((PackageFragmentRootInfo) info).setRootKind(determineKind(underlyingResource)); - // return computeChildren(info); - return false; - } - - /** - * @see JavaElement#getHandleMemento() - */ - protected char getHandleMementoDelimiter() { - return JavaElement.JEM_PACKAGEFRAGMENTROOT; - } - - /** - * @see IJavaElement - */ - public int getElementType() { - return PACKAGE_FRAGMENT_ROOT; - } - - /* - * @see JavaElement - */ - public IJavaElement getHandleFromMemento(String token, MementoTokenizer memento, WorkingCopyOwner owner) { - switch (token.charAt(0)) { - case JEM_COUNT: - return getHandleUpdatingCountFromMemento(memento, owner); - case JEM_PACKAGEFRAGMENT: - String pkgName; - if (memento.hasMoreTokens()) { - pkgName = memento.nextToken(); - char firstChar = pkgName.charAt(0); - // if (firstChar == JEM_CLASSFILE || firstChar == JEM_COMPILATIONUNIT || firstChar == JEM_COUNT) { - if (firstChar == JEM_COMPILATIONUNIT || firstChar == JEM_COUNT) { - token = pkgName; - pkgName = IPackageFragment.DEFAULT_PACKAGE_NAME; - } else { - token = null; - } - } else { - pkgName = IPackageFragment.DEFAULT_PACKAGE_NAME; - token = null; - } - JavaElement pkg = (JavaElement) getPackageFragment(pkgName); - if (token == null) { - return pkg.getHandleFromMemento(memento, owner); - } else { - return pkg.getHandleFromMemento(token, memento, owner); - } - } - return null; - } - - /** - * @see JavaElement#getHandleMemento() - */ - public String getHandleMemento() { - IPath path; - IResource underlyingResource = getResource(); - if (underlyingResource != null) { - // internal jar or regular root - if (getResource().getProject().equals(getJavaProject().getProject())) { - path = underlyingResource.getProjectRelativePath(); - } else { - path = underlyingResource.getFullPath(); - } - } else { - // external jar - path = getPath(); - } - StringBuffer buff = new StringBuffer(((JavaElement) getParent()).getHandleMemento()); - buff.append(getHandleMementoDelimiter()); - escapeMementoName(buff, path.toString()); - if (this.occurrenceCount > 1) { - buff.append(JEM_COUNT); - buff.append(this.occurrenceCount); - } - return buff.toString(); - } - - /** - * @see IPackageFragmentRoot - */ - public int getKind() throws JavaModelException { - return ((PackageFragmentRootInfo) getElementInfo()).getRootKind(); - } - - /** - * Returns an array of non-java resources contained in the receiver. - */ - //public Object[] getNonJavaResources() throws JavaModelException { - // return ((PackageFragmentRootInfo) getElementInfo()).getNonJavaResources(getJavaProject(), getResource(), this); - //} - /** - * @see IPackageFragmentRoot - */ - public IPackageFragment getPackageFragment(String packageName) { - if (packageName.indexOf(' ') != -1) { // tolerate package names with spaces (e.g. 'x . y') - // (http://bugs.eclipse.org/bugs/show_bug.cgi?id=21957) - char[][] compoundName = Util.toCompoundChars(packageName); - StringBuffer buffer = new StringBuffer(packageName.length()); - for (int i = 0, length = compoundName.length; i < length; i++) { - buffer.append(CharOperation.trim(compoundName[i])); - if (i != length - 1) { - buffer.append('.'); - } - } - packageName = buffer.toString(); - } - return new PackageFragment(this, packageName); - } - - /** - * Returns the package name for the given folder (which is a decendent of this root). - */ - protected String getPackageName(IFolder folder) throws JavaModelException { - IPath myPath = getPath(); - IPath pkgPath = folder.getFullPath(); - int mySegmentCount = myPath.segmentCount(); - int pkgSegmentCount = pkgPath.segmentCount(); - StringBuffer name = new StringBuffer(IPackageFragment.DEFAULT_PACKAGE_NAME); - for (int i = mySegmentCount; i < pkgSegmentCount; i++) { - if (i > mySegmentCount) { - name.append('.'); - } - name.append(pkgPath.segment(i)); - } - return name.toString(); - } - - /** - * @see IJavaElement - */ - public IPath getPath() { - return getResource().getFullPath(); - } - - /* - * @see IPackageFragmentRoot - */ - //public IClasspathEntry getRawClasspathEntry() throws JavaModelException { - // - // IClasspathEntry rawEntry = null; - // IJavaProject project = this.getJavaProject(); - // project.getResolvedClasspath(true); // force the reverse rawEntry cache to be populated - // JavaModelManager.PerProjectInfo perProjectInfo = - // JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(project.getProject()); - // if (perProjectInfo != null && perProjectInfo.resolvedPathToRawEntries != null) { - // rawEntry = (IClasspathEntry) perProjectInfo.resolvedPathToRawEntries.get(this.getPath()); - // } - // return rawEntry; - //} - /* - * @see IJavaElement - */ - public IResource getResource() { - return (IResource) this.resource; - } - - /** - * @see IPackageFragmentRoot - */ - //public IPath getSourceAttachmentPath() throws JavaModelException { - // if (getKind() != K_BINARY) return null; - // - // String serverPathString= getSourceAttachmentProperty(); - // if (serverPathString == null) { - // return null; - // } - // int index= serverPathString.lastIndexOf(ATTACHMENT_PROPERTY_DELIMITER); - // if (index < 0) { - // // no root path specified - // return new Path(serverPathString); - // } else { - // String serverSourcePathString= serverPathString.substring(0, index); - // return new Path(serverSourcePathString); - // } - //} - /** - * Returns the server property for this package fragment root's source attachement. - */ - //protected String getSourceAttachmentProperty() throws JavaModelException { - // String propertyString = null; - // QualifiedName qName= getSourceAttachmentPropertyName(); - // try { - // propertyString = ResourcesPlugin.getWorkspace().getRoot().getPersistentProperty(qName); - // - // // if no existing source attachment information, then lookup a recommendation from classpath entries - // if (propertyString == null) { - // IClasspathEntry recommendation = findSourceAttachmentRecommendation(); - // if (recommendation != null) { - // IPath rootPath = recommendation.getSourceAttachmentRootPath(); - // propertyString = - // recommendation.getSourceAttachmentPath().toString() - // + ((rootPath == null) - // ? "" : //$NON-NLS-1$ - // (ATTACHMENT_PROPERTY_DELIMITER + rootPath.toString())); - // setSourceAttachmentProperty(propertyString); - // } else { - // // mark as being already looked up - // setSourceAttachmentProperty(NO_SOURCE_ATTACHMENT); - // } - // } else if (NO_SOURCE_ATTACHMENT.equals(propertyString)) { - // // already looked up and no source attachment found - // return null; - // } - // return propertyString; - // } catch (CoreException ce) { - // throw new JavaModelException(ce); - // } - //} - /** - * Returns the qualified name for the source attachment property of this root. - */ - protected QualifiedName getSourceAttachmentPropertyName() throws JavaModelException { - return new QualifiedName(JavaCore.PLUGIN_ID, "sourceattachment: " + this.getPath().toOSString()); //$NON-NLS-1$ - } - - public void setSourceAttachmentProperty(String property) { - try { - ResourcesPlugin.getWorkspace().getRoot().setPersistentProperty(this.getSourceAttachmentPropertyName(), property); - } catch (CoreException ce) { - } - } - - /** - * For use by AttachSourceOperation only. Sets the source mapper associated with this root. - */ - //public void setSourceMapper(SourceMapper mapper) throws JavaModelException { - // ((PackageFragmentRootInfo) getElementInfo()).setSourceMapper(mapper); - //} - - /** - * @see IPackageFragmentRoot - */ - //public IPath getSourceAttachmentRootPath() throws JavaModelException { - // if (getKind() != K_BINARY) return null; - // - // String serverPathString= getSourceAttachmentProperty(); - // if (serverPathString == null) { - // return null; - // } - // int index = serverPathString.lastIndexOf(ATTACHMENT_PROPERTY_DELIMITER); - // if (index == -1) return null; - // String serverRootPathString= IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH; - // if (index != serverPathString.length() - 1) { - // serverRootPathString= serverPathString.substring(index + 1); - // } - // return new Path(serverRootPathString); - //} - /** - * @see JavaElement - */ - //public SourceMapper getSourceMapper() { - // SourceMapper mapper; - // try { - // PackageFragmentRootInfo rootInfo = (PackageFragmentRootInfo) getElementInfo(); - // mapper = rootInfo.getSourceMapper(); - // if (mapper == null) { - // // first call to this method - // IPath sourcePath= getSourceAttachmentPath(); - // if (sourcePath != null) { - // IPath rootPath= getSourceAttachmentRootPath(); - // mapper = this.createSourceMapper(sourcePath, rootPath); - // if (rootPath == null && mapper.rootPath != null) { - // // as a side effect of calling the SourceMapper constructor, the root path was computed - // rootPath = new Path(mapper.rootPath); - // - // //set the property to the path of the mapped source - // this.setSourceAttachmentProperty( - // sourcePath.toString() - // + ATTACHMENT_PROPERTY_DELIMITER - // + rootPath.toString()); - // } - // rootInfo.setSourceMapper(mapper); - // } else { - // // remember that no source is attached - // rootInfo.setSourceMapper(NO_SOURCE_MAPPER); - // mapper = null; - // } - // } else if (mapper == NO_SOURCE_MAPPER) { - // // a previous call to this method found out that no source was attached - // mapper = null; - // } - // } catch (JavaModelException e) { - // // no source can be attached - // mapper = null; - // } - // return mapper; - //} - /** - * @see IJavaElement - */ - public IResource getUnderlyingResource() throws JavaModelException { - if (!exists()) - throw newNotPresentException(); - return getResource(); - } - - public int hashCode() { - return this.resource.hashCode(); - } - - /** - * @see IPackageFragmentRoot - */ - public boolean isArchive() { - return false; - } - - /** - * @see IPackageFragmentRoot - */ - public boolean isExternal() { - return false; - } - - /* - * Returns whether this package fragment root is on the classpath of its project. - */ - //protected boolean isOnClasspath() { - // if (this.getElementType() == IJavaElement.JAVA_PROJECT){ - // return true; - // } - // - // IPath path = this.getPath(); - // try { - // // check package fragment root on classpath of its project - // IJavaProject project = this.getJavaProject(); - // IClasspathEntry[] classpath = project.getResolvedClasspath(true); - // for (int i = 0, length = classpath.length; i < length; i++) { - // IClasspathEntry entry = classpath[i]; - // if (entry.getPath().equals(path)) { - // return true; - // } - // } - // } catch(JavaModelException e){ - // // could not read classpath, then assume it is outside - // } - // return false; - //} - /* - * @see net.sourceforge.phpdt.core.IPackageFragmentRoot#move - */ - //public void move( - // IPath destination, - // int updateResourceFlags, - // int updateModelFlags, - // IClasspathEntry sibling, - // IProgressMonitor monitor) - // throws JavaModelException { - // - // MovePackageFragmentRootOperation op = - // new MovePackageFragmentRootOperation(this, destination, updateResourceFlags, updateModelFlags, sibling); - // runOperation(op, monitor); - //} - // - // - //protected void openWhenClosed(IProgressMonitor pm) throws JavaModelException { - // if (!this.resourceExists() - // || !this.isOnClasspath()) { - // throw newNotPresentException(); - // } - // super.openWhenClosed(pm); - //} - /** - * Recomputes the children of this element, based on the current state of the workbench. - */ - //public void refreshChildren() { - // try { - // OpenableElementInfo info= (OpenableElementInfo)getElementInfo(); - // computeChildren(info); - // } catch (JavaModelException e) { - // // do nothing. - // } - //} - ///* - // * @see JavaElement#rootedAt(IJavaProject) - // */ - //public IJavaElement rootedAt(IJavaProject project) { - // return - // new PackageFragmentRoot( - // getResource(), - // project, - // name); - //} - /** - * @private Debugging purposes - */ - protected void toStringInfo(int tab, StringBuffer buffer, Object info) { - buffer.append(this.tabString(tab)); - if (getElementName().length() == 0) { - buffer.append("[project root]"); //$NON-NLS-1$ - } else { - IPath path = getPath(); - if (getJavaProject().getElementName().equals(path.segment(0))) { - buffer.append(path.removeFirstSegments(1).makeRelative()); - } else { - buffer.append(path); - } - } - if (info == null) { - buffer.append(" (not open)"); //$NON-NLS-1$ - } - } - - /** - * Possible failures: - *

                                                - *
                                              • ELEMENT_NOT_PRESENT - the root supplied to the operation does not exist - *
                                              • INVALID_ELEMENT_TYPES - the root is not of kind K_BINARY - *
                                              • RELATIVE_PATH - the path supplied to this operation must be an absolute path - *
                                              - */ - //protected void verifyAttachSource(IPath sourcePath) throws JavaModelException { - // if (!exists()) { - // throw newNotPresentException(); - // } else if (this.getKind() != K_BINARY) { - // throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, this)); - // } else if (sourcePath != null && !sourcePath.isAbsolute()) { - // throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.RELATIVE_PATH, sourcePath)); - // } - //} +public class PackageFragmentRoot extends Openable implements + IPackageFragmentRoot { + + /** + * The delimiter between the source path and root path in the attachment + * server property. + */ + protected final static char ATTACHMENT_PROPERTY_DELIMITER = '*'; + + /* + * No source attachment property + */ + protected final static String NO_SOURCE_ATTACHMENT = ""; //$NON-NLS-1$ + + /* + * No source mapper singleton + */ + // protected final static SourceMapper NO_SOURCE_MAPPER = new + // SourceMapper(); + /** + * The resource associated with this root. (an IResource or a java.io.File + * (for external jar only)) + */ + protected Object resource; + + /** + * Constructs a package fragment root which is the root of the java package + * directory hierarchy. + */ + protected PackageFragmentRoot(IResource resource, JavaProject project, + String name) { + super(project, name); + this.resource = resource; + } + + /** + * @see Openable + */ + protected boolean buildStructure(OpenableElementInfo info, + IProgressMonitor pm, Map newElements, IResource underlyingResource) + throws JavaModelException { + + // check whether this pkg fragment root can be opened + if (!resourceExists()) { // || !isOnClasspath()) { + throw newNotPresentException(); + } + + ((PackageFragmentRootInfo) info) + .setRootKind(determineKind(underlyingResource)); + return computeChildren(info, newElements); + } + + /** + * Returns the root's kind - K_SOURCE or K_BINARY, defaults to K_SOURCE if + * it is not on the classpath. + * + * @exception NotPresentException + * if the project and root do not exist. + */ + protected int determineKind(IResource underlyingResource) + throws JavaModelException { + // IClasspathEntry[] entries= + // ((JavaProject)getJavaProject()).getExpandedClasspath(true); + // for (int i= 0; i < entries.length; i++) { + // IClasspathEntry entry= entries[i]; + // if (entry.getPath().equals(underlyingResource.getFullPath())) { + // return entry.getContentKind(); + // } + // } + return IPackageFragmentRoot.K_SOURCE; + } + + /** + * Compute the package fragment children of this package fragment root. + * + * @exception JavaModelException + * The resource associated with this package fragment root + * does not exist + */ + protected boolean computeChildren(OpenableElementInfo info, Map newElements) + throws JavaModelException { + // Note the children are not opened (so not added to newElements) for a + // regular package fragment root + // Howver they are opened for a Jar package fragment root (see + // JarPackageFragmentRoot#computeChildren) + try { + // the underlying resource may be a folder or a project (in the case + // that the project folder + // is actually the package fragment root) + IResource underlyingResource = getResource(); + if (underlyingResource.getType() == IResource.FOLDER + || underlyingResource.getType() == IResource.PROJECT) { + ArrayList vChildren = new ArrayList(5); + IContainer rootFolder = (IContainer) underlyingResource; + // char[][] inclusionPatterns = fullInclusionPatternChars(); + char[][] exclusionPatterns = fullExclusionPatternChars(); + computeFolderChildren(rootFolder, !Util.isExcluded(rootFolder, + exclusionPatterns), "", vChildren, exclusionPatterns); //$NON-NLS-1$ + + IJavaElement[] children = new IJavaElement[vChildren.size()]; + vChildren.toArray(children); + info.setChildren(children); + } + } catch (JavaModelException e) { + // problem resolving children; structure remains unknown + info.setChildren(new IJavaElement[] {}); + throw e; + } + return true; + } + + /** + * Starting at this folder, create package fragments and add the fragments + * that are not exclused to the collection of children. + * + * @exception JavaModelException + * The resource associated with this package fragment does + * not exist + */ + protected void computeFolderChildren(IContainer folder, boolean isIncluded, + String prefix, ArrayList vChildren, char[][] exclusionPatterns) + throws JavaModelException { + // , char[][] inclusionPatterns, char[][] exclusionPatterns) throws + // JavaModelException { + + if (isIncluded) { + IPackageFragment pkg = getPackageFragment(prefix); + vChildren.add(pkg); + } + try { + JavaProject javaProject = (JavaProject) getJavaProject(); + IResource[] members = folder.members(); + boolean hasIncluded = isIncluded; + for (int i = 0, max = members.length; i < max; i++) { + IResource member = members[i]; + String memberName = member.getName(); + + switch (member.getType()) { + + case IResource.FOLDER: + if (Util.isValidFolderNameForPackage(memberName)) { + boolean isMemberIncluded = !Util.isExcluded(member, + exclusionPatterns); + // keep looking inside as long as included already, or + // may have child included due to inclusion patterns + // if (isMemberIncluded || inclusionPatterns != null) { + // // eliminate binary output only if nested inside + // direct subfolders + // if (javaProject.contains(member)) { + // String newPrefix; + // if (prefix.length() == 0) { + // newPrefix = memberName; + // } else { + // newPrefix = prefix + "." + memberName; //$NON-NLS-1$ + // } + // computeFolderChildren((IFolder) member, + // isMemberIncluded, newPrefix, vChildren, + // inclusionPatterns, + // exclusionPatterns); + // } + // } + } + break; + case IResource.FILE: + // inclusion filter may only include files, in which case we + // still want to include the immediate parent package + // (lazily) + if (!hasIncluded + && Util.isValidCompilationUnitName(memberName) + && !Util.isExcluded(member, exclusionPatterns)) { + hasIncluded = true; + IPackageFragment pkg = getPackageFragment(prefix); + vChildren.add(pkg); + } + break; + } + } + } catch (IllegalArgumentException e) { + throw new JavaModelException(e, + IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); // could + // be + // thrown + // by + // ElementTree + // when + // path + // is not found + } catch (CoreException e) { + throw new JavaModelException(e); + } + } + + /** + * @see IPackageFragmentRoot + */ + // public void attachSource(IPath sourcePath, IPath rootPath, + // IProgressMonitor monitor) throws JavaModelException { + // try { + // verifyAttachSource(sourcePath); + // if (monitor != null) { + // monitor.beginTask(ProjectPrefUtil.bind("element.attachingSource"), 2); + // //$NON-NLS-1$ + // } + // SourceMapper oldMapper= getSourceMapper(); + // IWorkspace workspace = ResourcesPlugin.getWorkspace(); + // boolean rootNeedsToBeClosed= false; + // + // if (sourcePath == null) { + // //source being detached + // rootNeedsToBeClosed= true; + // setSourceMapper(null); + // /* Disable deltas (see 1GDTUSD) + // // fire a delta to notify the UI about the source detachement. + // JavaModelManager manager = (JavaModelManager) + // JavaModelManager.getJavaModelManager(); + // JavaModel model = (JavaModel) getJavaModel(); + // JavaElementDelta attachedSourceDelta = new JavaElementDelta(model); + // attachedSourceDelta .sourceDetached(this); // this would be a + // PackageFragmentRoot + // manager.registerResourceDelta(attachedSourceDelta ); + // manager.fire(); // maybe you want to fire the change later. Let us know + // about it. + // */ + // } else { + // /* + // // fire a delta to notify the UI about the source attachement. + // JavaModelManager manager = (JavaModelManager) + // JavaModelManager.getJavaModelManager(); + // JavaModel model = (JavaModel) getJavaModel(); + // JavaElementDelta attachedSourceDelta = new JavaElementDelta(model); + // attachedSourceDelta .sourceAttached(this); // this would be a + // PackageFragmentRoot + // manager.registerResourceDelta(attachedSourceDelta ); + // manager.fire(); // maybe you want to fire the change later. Let us know + // about it. + // */ + // + // //check if different from the current attachment + // IPath storedSourcePath= getSourceAttachmentPath(); + // IPath storedRootPath= getSourceAttachmentRootPath(); + // if (monitor != null) { + // monitor.worked(1); + // } + // if (storedSourcePath != null) { + // if (!(storedSourcePath.equals(sourcePath) && (rootPath != null && + // rootPath.equals(storedRootPath)) || storedRootPath == null)) + // { + // rootNeedsToBeClosed= true; + // } + // } + // // check if source path is valid + // Object target = JavaModel.getTarget(workspace.getRoot(), sourcePath, + // false); + // if (target == null) { + // if (monitor != null) { + // monitor.done(); + // } + // throw new JavaModelException(new + // JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, sourcePath)); + // } + // SourceMapper mapper = createSourceMapper(sourcePath, rootPath); + // if (rootPath == null && mapper.rootPath != null) { + // // as a side effect of calling the SourceMapper constructor, the root + // path was computed + // rootPath = new Path(mapper.rootPath); + // } + // setSourceMapper(mapper); + // } + // if (sourcePath == null) { + // setSourceAttachmentProperty(null); //remove the property + // } else { + // //set the property to the path of the mapped source + // setSourceAttachmentProperty( + // sourcePath.toString() + // + (rootPath == null ? "" : (ATTACHMENT_PROPERTY_DELIMITER + + // rootPath.toString()))); //$NON-NLS-1$ + // } + // if (rootNeedsToBeClosed) { + // if (oldMapper != null) { + // oldMapper.close(); + // } + // BufferManager manager= BufferManager.getDefaultBufferManager(); + // Enumeration openBuffers= manager.getOpenBuffers(); + // while (openBuffers.hasMoreElements()) { + // IBuffer buffer= (IBuffer) openBuffers.nextElement(); + // IOpenable possibleMember= buffer.getOwner(); + // if (isAncestorOf((IJavaElement) possibleMember)) { + // buffer.close(); + // } + // } + // if (monitor != null) { + // monitor.worked(1); + // } + // } + // } catch (JavaModelException e) { + // setSourceAttachmentProperty(null); // loose info - will be recomputed + // throw e; + // } finally { + // if (monitor != null) { + // monitor.done(); + // } + // } + // } + // SourceMapper createSourceMapper(IPath sourcePath, IPath rootPath) { + // SourceMapper mapper = new SourceMapper( + // sourcePath, + // rootPath == null ? null : rootPath.toOSString(), + // this.isExternal() ? JavaCore.getOptions() : + // this.getJavaProject().getOptions(true)); // only project options if + // associated with + // resource + // return mapper; + // } + /* + * @see net.sourceforge.phpdt.core.IPackageFragmentRoot#delete + */ + // public void delete( + // int updateResourceFlags, + // int updateModelFlags, + // IProgressMonitor monitor) + // throws JavaModelException { + // + // DeletePackageFragmentRootOperation op = new + // DeletePackageFragmentRootOperation(this, updateResourceFlags, + // updateModelFlags); + // runOperation(op, monitor); + // } + /** + * This root is being closed. If this root has an associated source + * attachment, close it too. + * + * @see JavaElement + */ + // protected void closing(Object info) throws JavaModelException { TODO + // remove after 2.1 + // ((PackageFragmentRootInfo) info).sourceMapper = null; + // super.closing(info); + // } + /** + * Compute the package fragment children of this package fragment root. + * + * @exception JavaModelException + * The resource associated with this package fragment root + * does not exist + */ + // protected boolean computeChildren(OpenableElementInfo info) throws + // JavaModelException { + // try { + // // the underlying resource may be a folder or a project (in the case that + // the project folder + // // is actually the package fragment root) + // IResource resource = getResource(); + // if (resource.getType() == IResource.FOLDER || resource.getType() == + // IResource.PROJECT) { + // ArrayList vChildren = new ArrayList(5); + // char[][] exclusionPatterns = fullExclusionPatternChars(); + // computeFolderChildren((IContainer) resource, "", vChildren, + // exclusionPatterns); //$NON-NLS-1$ + // IJavaElement[] children = new IJavaElement[vChildren.size()]; + // vChildren.toArray(children); + // info.setChildren(children); + // } + // } catch (JavaModelException e) { + // //problem resolving children; structure remains unknown + // info.setChildren(new IJavaElement[]{}); + // throw e; + // } + // return true; + // } + /** + * Starting at this folder, create package fragments and add the fragments + * that are not exclused to the collection of children. + * + * @exception JavaModelException + * The resource associated with this package fragment does + * not exist + */ + // protected void computeFolderChildren(IContainer folder, String prefix, + // ArrayList vChildren, char[][] exclusionPatterns) throws + // JavaModelException { + // IPackageFragment pkg = getPackageFragment(prefix); + // vChildren.add(pkg); + // try { + // JavaProject javaProject = (JavaProject)getJavaProject(); + // IResource[] members = folder.members(); + // for (int i = 0, max = members.length; i < max; i++) { + // IResource member = members[i]; + // String memberName = member.getName(); + // if (member.getType() == IResource.FOLDER + // && ProjectPrefUtil.isValidFolderNameForPackage(memberName) + // && !ProjectPrefUtil.isExcluded(member, exclusionPatterns)) { + // + // // eliminate binary output only if nested inside direct subfolders + // if (javaProject.contains(member)) { + // String newPrefix; + // if (prefix.length() == 0) { + // newPrefix = memberName; + // } else { + // newPrefix = prefix + "." + memberName; //$NON-NLS-1$ + // } + // computeFolderChildren((IFolder) member, newPrefix, vChildren, + // exclusionPatterns); + // } + // } + // } + // } catch(IllegalArgumentException e){ + // throw new JavaModelException(e, + // IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); // could be thrown by + // ElementTree when path + // is not found + // } catch (CoreException e) { + // throw new JavaModelException(e); + // } + // } + /* + * Computes and returns the source attachment root path for the given source + * attachment path. Returns null if none could be found. + * + * @param sourceAttachmentPath the given absolute path to the source archive + * or folder @return the computed source attachment root path or null + * if none could be found @throws JavaModelException + */ + // public IPath computeSourceAttachmentRootPath(IPath sourceAttachmentPath) + // throws JavaModelException { + // IPath sourcePath = this.getSourceAttachmentPath(); + // if (sourcePath == null) return null; + // SourceMapper mapper = + // new SourceMapper( + // sourcePath, + // null, // detect root path + // this.isExternal() ? JavaCore.getOptions() : + // this.getJavaProject().getOptions(true) // only project options if + // associated with + // resource + // ); + // if (mapper.rootPath == null) return null; + // return new Path(mapper.rootPath); + // } + /* + * @see net.sourceforge.phpdt.core.IPackageFragmentRoot#copy + */ + // public void copy( + // IPath destination, + // int updateResourceFlags, + // int updateModelFlags, + // IClasspathEntry sibling, + // IProgressMonitor monitor) + // throws JavaModelException { + // + // CopyPackageFragmentRootOperation op = + // new CopyPackageFragmentRootOperation(this, destination, + // updateResourceFlags, updateModelFlags, sibling); + // runOperation(op, monitor); + // } + /** + * Returns a new element info for this element. + */ + protected Object createElementInfo() { + return new PackageFragmentRootInfo(); + } + + /** + * @see IPackageFragmentRoot + */ + // public IPackageFragment createPackageFragment(String name, boolean force, + // IProgressMonitor monitor) throws JavaModelException { + // CreatePackageFragmentOperation op = new + // CreatePackageFragmentOperation(this, name, force); + // runOperation(op, monitor); + // return getPackageFragment(name); + // } + /** + * Returns the root's kind - K_SOURCE or K_BINARY, defaults to K_SOURCE if + * it is not on the classpath. + * + * @exception NotPresentException + * if the project and root do not exist. + */ + // protected int determineKind(IResource underlyingResource) throws + // JavaModelException { + // IClasspathEntry[] entries= + // ((JavaProject)getJavaProject()).getExpandedClasspath(true); + // for (int i= 0; i < entries.length; i++) { + // IClasspathEntry entry= entries[i]; + // if (entry.getPath().equals(underlyingResource.getFullPath())) { + // return entry.getContentKind(); + // } + // } + // return IPackageFragmentRoot.K_SOURCE; + // } + /** + * Compares two objects for equality; for PackageFragmentRoots, + * equality is having the same JavaModel, same resources, + * and occurrence count. + * + */ + public boolean equals(Object o) { + if (this == o) + return true; + if (!(o instanceof PackageFragmentRoot)) + return false; + PackageFragmentRoot other = (PackageFragmentRoot) o; + return getJavaModel().equals(other.getJavaModel()) + && this.resource.equals(other.resource) + && occurrenceCount == other.occurrenceCount; + } + + /** + * @see IJavaElement + */ + // public boolean exists() { + // return super.exists() + // && isOnClasspath(); + // } + // public IClasspathEntry findSourceAttachmentRecommendation() { + // try { + // IPath rootPath = this.getPath(); + // IClasspathEntry entry; + // IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); + // + // // try on enclosing project first + // JavaProject parentProject = (JavaProject) getJavaProject(); + // try { + // entry = parentProject.getClasspathEntryFor(rootPath); + // if (entry != null){ + // Object target = JavaModel.getTarget(workspaceRoot, + // entry.getSourceAttachmentPath(), true); + // if (target instanceof IFile){ + // IFile file = (IFile) target; + // if (ProjectPrefUtil.isArchiveFileName(file.getName())){ + // return entry; + // } + // } else if (target instanceof IFolder) { + // return entry; + // } + // if (target instanceof java.io.File){ + // java.io.File file = (java.io.File) target; + // if (file.isFile()) { + // if (ProjectPrefUtil.isArchiveFileName(file.getName())){ + // return entry; + // } + // } else { + // // external directory + // return entry; + // } + // } + // } + // } catch(JavaModelException e){ + // } + // + // // iterate over all projects + // IJavaModel model = getJavaModel(); + // IJavaProject[] jProjects = model.getJavaProjects(); + // for (int i = 0, max = jProjects.length; i < max; i++){ + // JavaProject jProject = (JavaProject) jProjects[i]; + // if (jProject == parentProject) continue; // already done + // try { + // entry = jProject.getClasspathEntryFor(rootPath); + // if (entry != null){ + // Object target = JavaModel.getTarget(workspaceRoot, + // entry.getSourceAttachmentPath(), true); + // if (target instanceof IFile){ + // IFile file = (IFile) target; + // if (ProjectPrefUtil.isArchiveFileName(file.getName())){ + // return entry; + // } + // } else if (target instanceof IFolder) { + // return entry; + // } + // if (target instanceof java.io.File){ + // java.io.File file = (java.io.File) target; + // if (file.isFile()) { + // if (ProjectPrefUtil.isArchiveFileName(file.getName())){ + // return entry; + // } + // } else { + // // external directory + // return entry; + // } + // } + // } + // } catch(JavaModelException e){ + // } + // } + // } catch(JavaModelException e){ + // } + // + // return null; + // } + /* + * Returns the exclusion patterns from the classpath entry associated with + * this root. + */ + char[][] fullExclusionPatternChars() { + return null; + // try { + + // if (this.isOpen() && this.getKind() != IPackageFragmentRoot.K_SOURCE) + // return null; + // ClasspathEntry entry = (ClasspathEntry)getRawClasspathEntry(); + // if (entry == null) { + // return null; + // } else { + // return entry.fullExclusionPatternChars(); + // } + // } catch (JavaModelException e) { + // return null; + // } + } + + /** + * @see Openable + */ + protected boolean generateInfos(OpenableElementInfo info, + IProgressMonitor pm, Map newElements, IResource underlyingResource) + throws JavaModelException { + + // ((PackageFragmentRootInfo) + // info).setRootKind(determineKind(underlyingResource)); + // return computeChildren(info); + return false; + } + + /** + * @see JavaElement#getHandleMemento() + */ + protected char getHandleMementoDelimiter() { + return JavaElement.JEM_PACKAGEFRAGMENTROOT; + } + + /** + * @see IJavaElement + */ + public int getElementType() { + return PACKAGE_FRAGMENT_ROOT; + } + + /* + * @see JavaElement + */ + public IJavaElement getHandleFromMemento(String token, + MementoTokenizer memento, WorkingCopyOwner owner) { + switch (token.charAt(0)) { + case JEM_COUNT: + return getHandleUpdatingCountFromMemento(memento, owner); + case JEM_PACKAGEFRAGMENT: + String pkgName; + if (memento.hasMoreTokens()) { + pkgName = memento.nextToken(); + char firstChar = pkgName.charAt(0); + // if (firstChar == JEM_CLASSFILE || firstChar == + // JEM_COMPILATIONUNIT || firstChar == JEM_COUNT) { + if (firstChar == JEM_COMPILATIONUNIT || firstChar == JEM_COUNT) { + token = pkgName; + pkgName = IPackageFragment.DEFAULT_PACKAGE_NAME; + } else { + token = null; + } + } else { + pkgName = IPackageFragment.DEFAULT_PACKAGE_NAME; + token = null; + } + JavaElement pkg = (JavaElement) getPackageFragment(pkgName); + if (token == null) { + return pkg.getHandleFromMemento(memento, owner); + } else { + return pkg.getHandleFromMemento(token, memento, owner); + } + } + return null; + } + + /** + * @see JavaElement#getHandleMemento() + */ + public String getHandleMemento() { + IPath path; + IResource underlyingResource = getResource(); + if (underlyingResource != null) { + // internal jar or regular root + if (getResource().getProject() + .equals(getJavaProject().getProject())) { + path = underlyingResource.getProjectRelativePath(); + } else { + path = underlyingResource.getFullPath(); + } + } else { + // external jar + path = getPath(); + } + StringBuffer buff = new StringBuffer(((JavaElement) getParent()) + .getHandleMemento()); + buff.append(getHandleMementoDelimiter()); + escapeMementoName(buff, path.toString()); + if (this.occurrenceCount > 1) { + buff.append(JEM_COUNT); + buff.append(this.occurrenceCount); + } + return buff.toString(); + } + + /** + * @see IPackageFragmentRoot + */ + public int getKind() throws JavaModelException { + return ((PackageFragmentRootInfo) getElementInfo()).getRootKind(); + } + + /** + * Returns an array of non-java resources contained in the receiver. + */ + // public Object[] getNonJavaResources() throws JavaModelException { + // return ((PackageFragmentRootInfo) + // getElementInfo()).getNonJavaResources(getJavaProject(), getResource(), + // this); + // } + /** + * @see IPackageFragmentRoot + */ + public IPackageFragment getPackageFragment(String packageName) { + if (packageName.indexOf(' ') != -1) { // tolerate package names with + // spaces (e.g. 'x . y') + // (http://bugs.eclipse.org/bugs/show_bug.cgi?id=21957) + char[][] compoundName = Util.toCompoundChars(packageName); + StringBuffer buffer = new StringBuffer(packageName.length()); + for (int i = 0, length = compoundName.length; i < length; i++) { + buffer.append(CharOperation.trim(compoundName[i])); + if (i != length - 1) { + buffer.append('.'); + } + } + packageName = buffer.toString(); + } + return new PackageFragment(this, packageName); + } + + /** + * Returns the package name for the given folder (which is a decendent of + * this root). + */ + protected String getPackageName(IFolder folder) throws JavaModelException { + IPath myPath = getPath(); + IPath pkgPath = folder.getFullPath(); + int mySegmentCount = myPath.segmentCount(); + int pkgSegmentCount = pkgPath.segmentCount(); + StringBuffer name = new StringBuffer( + IPackageFragment.DEFAULT_PACKAGE_NAME); + for (int i = mySegmentCount; i < pkgSegmentCount; i++) { + if (i > mySegmentCount) { + name.append('.'); + } + name.append(pkgPath.segment(i)); + } + return name.toString(); + } + + /** + * @see IJavaElement + */ + public IPath getPath() { + return getResource().getFullPath(); + } + + /* + * @see IPackageFragmentRoot + */ + // public IClasspathEntry getRawClasspathEntry() throws JavaModelException { + // + // IClasspathEntry rawEntry = null; + // IJavaProject project = this.getJavaProject(); + // project.getResolvedClasspath(true); // force the reverse rawEntry cache + // to be populated + // JavaModelManager.PerProjectInfo perProjectInfo = + // JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(project.getProject()); + // if (perProjectInfo != null && perProjectInfo.resolvedPathToRawEntries != + // null) { + // rawEntry = (IClasspathEntry) + // perProjectInfo.resolvedPathToRawEntries.get(this.getPath()); + // } + // return rawEntry; + // } + /* + * @see IJavaElement + */ + public IResource getResource() { + return (IResource) this.resource; + } + + /** + * @see IPackageFragmentRoot + */ + // public IPath getSourceAttachmentPath() throws JavaModelException { + // if (getKind() != K_BINARY) return null; + // + // String serverPathString= getSourceAttachmentProperty(); + // if (serverPathString == null) { + // return null; + // } + // int index= serverPathString.lastIndexOf(ATTACHMENT_PROPERTY_DELIMITER); + // if (index < 0) { + // // no root path specified + // return new Path(serverPathString); + // } else { + // String serverSourcePathString= serverPathString.substring(0, index); + // return new Path(serverSourcePathString); + // } + // } + /** + * Returns the server property for this package fragment root's source + * attachement. + */ + // protected String getSourceAttachmentProperty() throws JavaModelException + // { + // String propertyString = null; + // QualifiedName qName= getSourceAttachmentPropertyName(); + // try { + // propertyString = + // ResourcesPlugin.getWorkspace().getRoot().getPersistentProperty(qName); + // + // // if no existing source attachment information, then lookup a + // recommendation from classpath entries + // if (propertyString == null) { + // IClasspathEntry recommendation = findSourceAttachmentRecommendation(); + // if (recommendation != null) { + // IPath rootPath = recommendation.getSourceAttachmentRootPath(); + // propertyString = + // recommendation.getSourceAttachmentPath().toString() + // + ((rootPath == null) + // ? "" : //$NON-NLS-1$ + // (ATTACHMENT_PROPERTY_DELIMITER + rootPath.toString())); + // setSourceAttachmentProperty(propertyString); + // } else { + // // mark as being already looked up + // setSourceAttachmentProperty(NO_SOURCE_ATTACHMENT); + // } + // } else if (NO_SOURCE_ATTACHMENT.equals(propertyString)) { + // // already looked up and no source attachment found + // return null; + // } + // return propertyString; + // } catch (CoreException ce) { + // throw new JavaModelException(ce); + // } + // } + /** + * Returns the qualified name for the source attachment property of this + * root. + */ + protected QualifiedName getSourceAttachmentPropertyName() + throws JavaModelException { + return new QualifiedName(JavaCore.PLUGIN_ID, + "sourceattachment: " + this.getPath().toOSString()); //$NON-NLS-1$ + } + + public void setSourceAttachmentProperty(String property) { + try { + ResourcesPlugin.getWorkspace().getRoot().setPersistentProperty( + this.getSourceAttachmentPropertyName(), property); + } catch (CoreException ce) { + } + } + + /** + * For use by AttachSourceOperation only. Sets the source + * mapper associated with this root. + */ + // public void setSourceMapper(SourceMapper mapper) throws + // JavaModelException { + // ((PackageFragmentRootInfo) getElementInfo()).setSourceMapper(mapper); + // } + /** + * @see IPackageFragmentRoot + */ + // public IPath getSourceAttachmentRootPath() throws JavaModelException { + // if (getKind() != K_BINARY) return null; + // + // String serverPathString= getSourceAttachmentProperty(); + // if (serverPathString == null) { + // return null; + // } + // int index = serverPathString.lastIndexOf(ATTACHMENT_PROPERTY_DELIMITER); + // if (index == -1) return null; + // String serverRootPathString= + // IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH; + // if (index != serverPathString.length() - 1) { + // serverRootPathString= serverPathString.substring(index + 1); + // } + // return new Path(serverRootPathString); + // } + /** + * @see JavaElement + */ + // public SourceMapper getSourceMapper() { + // SourceMapper mapper; + // try { + // PackageFragmentRootInfo rootInfo = (PackageFragmentRootInfo) + // getElementInfo(); + // mapper = rootInfo.getSourceMapper(); + // if (mapper == null) { + // // first call to this method + // IPath sourcePath= getSourceAttachmentPath(); + // if (sourcePath != null) { + // IPath rootPath= getSourceAttachmentRootPath(); + // mapper = this.createSourceMapper(sourcePath, rootPath); + // if (rootPath == null && mapper.rootPath != null) { + // // as a side effect of calling the SourceMapper constructor, the root + // path was computed + // rootPath = new Path(mapper.rootPath); + // + // //set the property to the path of the mapped source + // this.setSourceAttachmentProperty( + // sourcePath.toString() + // + ATTACHMENT_PROPERTY_DELIMITER + // + rootPath.toString()); + // } + // rootInfo.setSourceMapper(mapper); + // } else { + // // remember that no source is attached + // rootInfo.setSourceMapper(NO_SOURCE_MAPPER); + // mapper = null; + // } + // } else if (mapper == NO_SOURCE_MAPPER) { + // // a previous call to this method found out that no source was attached + // mapper = null; + // } + // } catch (JavaModelException e) { + // // no source can be attached + // mapper = null; + // } + // return mapper; + // } + /** + * @see IJavaElement + */ + public IResource getUnderlyingResource() throws JavaModelException { + if (!exists()) + throw newNotPresentException(); + return getResource(); + } + + public int hashCode() { + return this.resource.hashCode(); + } + + /** + * @see IPackageFragmentRoot + */ + public boolean isArchive() { + return false; + } + + /** + * @see IPackageFragmentRoot + */ + public boolean isExternal() { + return false; + } + + /* + * Returns whether this package fragment root is on the classpath of its + * project. + */ + // protected boolean isOnClasspath() { + // if (this.getElementType() == IJavaElement.JAVA_PROJECT){ + // return true; + // } + // + // IPath path = this.getPath(); + // try { + // // check package fragment root on classpath of its project + // IJavaProject project = this.getJavaProject(); + // IClasspathEntry[] classpath = project.getResolvedClasspath(true); + // for (int i = 0, length = classpath.length; i < length; i++) { + // IClasspathEntry entry = classpath[i]; + // if (entry.getPath().equals(path)) { + // return true; + // } + // } + // } catch(JavaModelException e){ + // // could not read classpath, then assume it is outside + // } + // return false; + // } + /* + * @see net.sourceforge.phpdt.core.IPackageFragmentRoot#move + */ + // public void move( + // IPath destination, + // int updateResourceFlags, + // int updateModelFlags, + // IClasspathEntry sibling, + // IProgressMonitor monitor) + // throws JavaModelException { + // + // MovePackageFragmentRootOperation op = + // new MovePackageFragmentRootOperation(this, destination, + // updateResourceFlags, updateModelFlags, sibling); + // runOperation(op, monitor); + // } + // + // + // protected void openWhenClosed(IProgressMonitor pm) throws + // JavaModelException { + // if (!this.resourceExists() + // || !this.isOnClasspath()) { + // throw newNotPresentException(); + // } + // super.openWhenClosed(pm); + // } + /** + * Recomputes the children of this element, based on the current state of + * the workbench. + */ + // public void refreshChildren() { + // try { + // OpenableElementInfo info= (OpenableElementInfo)getElementInfo(); + // computeChildren(info); + // } catch (JavaModelException e) { + // // do nothing. + // } + // } + // /* + // * @see JavaElement#rootedAt(IJavaProject) + // */ + // public IJavaElement rootedAt(IJavaProject project) { + // return + // new PackageFragmentRoot( + // getResource(), + // project, + // name); + // } + /** + * @private Debugging purposes + */ + protected void toStringInfo(int tab, StringBuffer buffer, Object info) { + buffer.append(this.tabString(tab)); + if (getElementName().length() == 0) { + buffer.append("[project root]"); //$NON-NLS-1$ + } else { + IPath path = getPath(); + if (getJavaProject().getElementName().equals(path.segment(0))) { + buffer.append(path.removeFirstSegments(1).makeRelative()); + } else { + buffer.append(path); + } + } + if (info == null) { + buffer.append(" (not open)"); //$NON-NLS-1$ + } + } + + /** + * Possible failures: + *
                                                + *
                                              • ELEMENT_NOT_PRESENT - the root supplied to the operation does not + * exist + *
                                              • INVALID_ELEMENT_TYPES - the root is not of kind K_BINARY + *
                                              • RELATIVE_PATH - the path supplied to this operation must be an + * absolute path + *
                                              + */ + // protected void verifyAttachSource(IPath sourcePath) throws + // JavaModelException { + // if (!exists()) { + // throw newNotPresentException(); + // } else if (this.getKind() != K_BINARY) { + // throw new JavaModelException(new + // JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, this)); + // } else if (sourcePath != null && !sourcePath.isAbsolute()) { + // throw new JavaModelException(new + // JavaModelStatus(IJavaModelStatusConstants.RELATIVE_PATH, sourcePath)); + // } + // } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragmentRootInfo.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragmentRootInfo.java index 0848af2..45bdc6b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragmentRootInfo.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragmentRootInfo.java @@ -27,151 +27,185 @@ import org.eclipse.core.runtime.IPath; class PackageFragmentRootInfo extends OpenableElementInfo { /** - * The SourceMapper for this JAR (or null if - * this JAR does not have source attached). + * The SourceMapper for this JAR (or null if this JAR does + * not have source attached). */ -// protected SourceMapper sourceMapper = null; - + // protected SourceMapper sourceMapper = null; /** - * The kind of the root associated with this info. - * Valid kinds are:
                                                + * The kind of the root associated with this info. Valid kinds are: + *
                                                  *
                                                • IPackageFragmentRoot.K_SOURCE - *
                                                • IPackageFragmentRoot.K_BINARY
                                                + *
                                              • IPackageFragmentRoot.K_BINARY + *
                                              */ - protected int fRootKind= IPackageFragmentRoot.K_SOURCE; + protected int fRootKind = IPackageFragmentRoot.K_SOURCE; /** * A array with all the non-java resources contained by this PackageFragment */ protected Object[] fNonJavaResources; -/** - * Create and initialize a new instance of the receiver - */ -public PackageFragmentRootInfo() { - fNonJavaResources = null; -} -/** - * Starting at this folder, create non-java resources for this package fragment root - * and add them to the non-java resources collection. - * - * @exception JavaModelException The resource associated with this package fragment does not exist - */ -static Object[] computeFolderNonJavaResources(JavaProject project, IContainer folder, char[][] exclusionPatterns) throws JavaModelException { - Object[] nonJavaResources = new IResource[5]; - int nonJavaResourcesCounter = 0; - try { - IClasspathEntry[] classpath = project.getResolvedClasspath(true/*ignore unresolved variable*/); - IResource[] members = folder.members(); - nextResource: for (int i = 0, max = members.length; i < max; i++) { - IResource member = members[i]; - switch (member.getType()) { - case IResource.FILE : + + /** + * Create and initialize a new instance of the receiver + */ + public PackageFragmentRootInfo() { + fNonJavaResources = null; + } + + /** + * Starting at this folder, create non-java resources for this package + * fragment root and add them to the non-java resources collection. + * + * @exception JavaModelException + * The resource associated with this package fragment does + * not exist + */ + static Object[] computeFolderNonJavaResources(JavaProject project, + IContainer folder, char[][] exclusionPatterns) + throws JavaModelException { + Object[] nonJavaResources = new IResource[5]; + int nonJavaResourcesCounter = 0; + try { + IClasspathEntry[] classpath = project + .getResolvedClasspath(true/* ignore unresolved variable */); + IResource[] members = folder.members(); + nextResource: for (int i = 0, max = members.length; i < max; i++) { + IResource member = members[i]; + switch (member.getType()) { + case IResource.FILE: String fileName = member.getName(); - + // ignore .java files that are not excluded - if (Util.isValidCompilationUnitName(fileName) && !Util.isExcluded(member, exclusionPatterns)) + if (Util.isValidCompilationUnitName(fileName) + && !Util.isExcluded(member, exclusionPatterns)) continue nextResource; // ignore .class files -// if (ProjectPrefUtil.isValidClassFileName(fileName)) -// continue nextResource; -// // ignore .zip or .jar file on classpath -// if (ProjectPrefUtil.isArchiveFileName(fileName) && isClasspathEntry(member.getFullPath(), classpath)) -// continue nextResource; + // if (ProjectPrefUtil.isValidClassFileName(fileName)) + // continue nextResource; + // // ignore .zip or .jar file on classpath + // if (ProjectPrefUtil.isArchiveFileName(fileName) && + // isClasspathEntry(member.getFullPath(), classpath)) + // continue nextResource; break; - case IResource.FOLDER : - // ignore valid packages or excluded folders that correspond to a nested pkg fragment root -// if (ProjectPrefUtil.isValidFolderNameForPackage(member.getName()) -// && (!ProjectPrefUtil.isExcluded(member, exclusionPatterns) -// || isClasspathEntry(member.getFullPath(), classpath))) -// continue nextResource; + case IResource.FOLDER: + // ignore valid packages or excluded folders that correspond + // to a nested pkg fragment root + // if + // (ProjectPrefUtil.isValidFolderNameForPackage(member.getName()) + // && (!ProjectPrefUtil.isExcluded(member, + // exclusionPatterns) + // || isClasspathEntry(member.getFullPath(), classpath))) + // continue nextResource; break; + } + if (nonJavaResources.length == nonJavaResourcesCounter) { + // resize + System + .arraycopy( + nonJavaResources, + 0, + (nonJavaResources = new IResource[nonJavaResourcesCounter * 2]), + 0, nonJavaResourcesCounter); + } + nonJavaResources[nonJavaResourcesCounter++] = member; + } - if (nonJavaResources.length == nonJavaResourcesCounter) { - // resize - System.arraycopy(nonJavaResources, 0, (nonJavaResources = new IResource[nonJavaResourcesCounter * 2]), 0, nonJavaResourcesCounter); + if (nonJavaResources.length != nonJavaResourcesCounter) { + System + .arraycopy( + nonJavaResources, + 0, + (nonJavaResources = new IResource[nonJavaResourcesCounter]), + 0, nonJavaResourcesCounter); } - nonJavaResources[nonJavaResourcesCounter++] = member; - + return nonJavaResources; + } catch (CoreException e) { + throw new JavaModelException(e); } - if (nonJavaResources.length != nonJavaResourcesCounter) { - System.arraycopy(nonJavaResources, 0, (nonJavaResources = new IResource[nonJavaResourcesCounter]), 0, nonJavaResourcesCounter); + } + + /** + * Compute the non-package resources of this package fragment root. + * + * @exception JavaModelException + * The resource associated with this package fragment root + * does not exist + */ + private Object[] computeNonJavaResources(IJavaProject project, + IResource underlyingResource, PackageFragmentRoot handle) { + Object[] nonJavaResources = NO_NON_JAVA_RESOURCES; + try { + // the underlying resource may be a folder or a project (in the case + // that the project folder + // is actually the package fragment root) + if (underlyingResource.getType() == IResource.FOLDER + || underlyingResource.getType() == IResource.PROJECT) { + nonJavaResources = computeFolderNonJavaResources( + (JavaProject) project, (IContainer) underlyingResource, + handle.fullExclusionPatternChars()); + } + } catch (JavaModelException e) { } return nonJavaResources; - } catch (CoreException e) { - throw new JavaModelException(e); } -} -/** - * Compute the non-package resources of this package fragment root. - * - * @exception JavaModelException The resource associated with this package fragment root does not exist - */ -private Object[] computeNonJavaResources(IJavaProject project, IResource underlyingResource, PackageFragmentRoot handle) { - Object[] nonJavaResources = NO_NON_JAVA_RESOURCES; - try { - // the underlying resource may be a folder or a project (in the case that the project folder - // is actually the package fragment root) - if (underlyingResource.getType() == IResource.FOLDER || underlyingResource.getType() == IResource.PROJECT) { - nonJavaResources = - computeFolderNonJavaResources( - (JavaProject)project, - (IContainer) underlyingResource, - handle.fullExclusionPatternChars()); + + /** + * Returns an array of non-java resources contained in the receiver. + */ + synchronized Object[] getNonJavaResources(IJavaProject project, + IResource underlyingResource, PackageFragmentRoot handle) { + Object[] nonJavaResources = fNonJavaResources; + if (nonJavaResources == null) { + nonJavaResources = this.computeNonJavaResources(project, + underlyingResource, handle); + fNonJavaResources = nonJavaResources; } - } catch (JavaModelException e) { + return nonJavaResources; } - return nonJavaResources; -} -/** - * Returns an array of non-java resources contained in the receiver. - */ -synchronized Object[] getNonJavaResources(IJavaProject project, IResource underlyingResource, PackageFragmentRoot handle) { - Object[] nonJavaResources = fNonJavaResources; - if (nonJavaResources == null) { - nonJavaResources = this.computeNonJavaResources(project, underlyingResource, handle); - fNonJavaResources = nonJavaResources; + + /** + * Returns the kind of this root. + */ + public int getRootKind() { + return fRootKind; } - return nonJavaResources; -} -/** - * Returns the kind of this root. - */ -public int getRootKind() { - return fRootKind; -} -/** - * Retuns the SourceMapper for this root, or null - * if this root does not have attached source. - */ -//protected synchronized SourceMapper getSourceMapper() { -// return this.sourceMapper; -//} -private static boolean isClasspathEntry(IPath path, IClasspathEntry[] resolvedClasspath) { - for (int i = 0, length = resolvedClasspath.length; i < length; i++) { - IClasspathEntry entry = resolvedClasspath[i]; - if (entry.getPath().equals(path)) { - return true; + + /** + * Retuns the SourceMapper for this root, or null if this + * root does not have attached source. + */ + // protected synchronized SourceMapper getSourceMapper() { + // return this.sourceMapper; + // } + private static boolean isClasspathEntry(IPath path, + IClasspathEntry[] resolvedClasspath) { + for (int i = 0, length = resolvedClasspath.length; i < length; i++) { + IClasspathEntry entry = resolvedClasspath[i]; + if (entry.getPath().equals(path)) { + return true; + } } + return false; } - return false; -} -/** - * Set the fNonJavaResources to res value - */ -synchronized void setNonJavaResources(Object[] resources) { - fNonJavaResources = resources; -} -/** - * Sets the kind of this root. - */ -protected void setRootKind(int newRootKind) { - fRootKind = newRootKind; -} -/** - * Sets the SourceMapper for this root. - */ -//protected synchronized void setSourceMapper(SourceMapper mapper) { -// this.sourceMapper= mapper; -//} + + /** + * Set the fNonJavaResources to res value + */ + synchronized void setNonJavaResources(Object[] resources) { + fNonJavaResources = resources; + } + + /** + * Sets the kind of this root. + */ + protected void setRootKind(int newRootKind) { + fRootKind = newRootKind; + } + /** + * Sets the SourceMapper for this root. + */ + // protected synchronized void setSourceMapper(SourceMapper mapper) { + // this.sourceMapper= mapper; + // } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ReconcileWorkingCopyOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ReconcileWorkingCopyOperation.java index 09ea48e..5356891 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ReconcileWorkingCopyOperation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ReconcileWorkingCopyOperation.java @@ -23,146 +23,177 @@ import net.sourceforge.phpdt.internal.core.util.Util; * Reconcile a working copy and signal the changes through a delta. */ public class ReconcileWorkingCopyOperation extends JavaModelOperation { - + boolean createAST; + int astLevel; + boolean forceProblemDetection; + WorkingCopyOwner workingCopyOwner; -// net.sourceforge.phpdt.core.dom.CompilationUnit ast; - - public ReconcileWorkingCopyOperation(IJavaElement workingCopy, boolean forceProblemDetection) { - super(new IJavaElement[] {workingCopy}); + + // net.sourceforge.phpdt.core.dom.CompilationUnit ast; + + public ReconcileWorkingCopyOperation(IJavaElement workingCopy, + boolean forceProblemDetection) { + super(new IJavaElement[] { workingCopy }); this.forceProblemDetection = forceProblemDetection; } - public ReconcileWorkingCopyOperation(IJavaElement workingCopy, boolean creatAST, int astLevel, boolean forceProblemDetection, WorkingCopyOwner workingCopyOwner) { - super(new IJavaElement[] {workingCopy}); + + public ReconcileWorkingCopyOperation(IJavaElement workingCopy, + boolean creatAST, int astLevel, boolean forceProblemDetection, + WorkingCopyOwner workingCopyOwner) { + super(new IJavaElement[] { workingCopy }); this.createAST = creatAST; this.astLevel = astLevel; this.forceProblemDetection = forceProblemDetection; this.workingCopyOwner = workingCopyOwner; } + /** - * @exception JavaModelException if setting the source - * of the original compilation unit fails + * @exception JavaModelException + * if setting the source of the original compilation unit + * fails */ -// protected void executeOperation() throws JavaModelException { -// if (fMonitor != null){ -// if (fMonitor.isCanceled()) return; -// fMonitor.beginTask(ProjectPrefUtil.bind("element.reconciling"), 10); //$NON-NLS-1$ -// } -// -// WorkingCopy workingCopy = getWorkingCopy(); -// boolean wasConsistent = workingCopy.isConsistent(); -// JavaElementDeltaBuilder deltaBuilder = null; -// -// try { -// // create the delta builder (this remembers the current content of the cu) -// if (!wasConsistent){ -// deltaBuilder = new JavaElementDeltaBuilder(workingCopy); -// -// // update the element infos with the content of the working copy -// workingCopy.makeConsistent(fMonitor); -// deltaBuilder.buildDeltas(); -// -// } -// -// if (fMonitor != null) fMonitor.worked(2); -// -// // force problem detection? - if structure was consistent -// if (forceProblemDetection && wasConsistent){ -// if (fMonitor != null && fMonitor.isCanceled()) return; -// -// IProblemRequestor problemRequestor = workingCopy.problemRequestor; -// if (problemRequestor != null && problemRequestor.isActive()){ -// problemRequestor.beginReporting(); -// CompilationUnitProblemFinder.process(workingCopy, problemRequestor, fMonitor); -// problemRequestor.endReporting(); -// } -// } -// -// // register the deltas -// if (deltaBuilder != null){ -// if ((deltaBuilder.delta != null) && (deltaBuilder.delta.getAffectedChildren().length > 0)) { -// addReconcileDelta(workingCopy, deltaBuilder.delta); -// } -// } -// } finally { -// if (fMonitor != null) fMonitor.done(); -// } -// } + // protected void executeOperation() throws JavaModelException { + // if (fMonitor != null){ + // if (fMonitor.isCanceled()) return; + // fMonitor.beginTask(ProjectPrefUtil.bind("element.reconciling"), 10); + // //$NON-NLS-1$ + // } + // + // WorkingCopy workingCopy = getWorkingCopy(); + // boolean wasConsistent = workingCopy.isConsistent(); + // JavaElementDeltaBuilder deltaBuilder = null; + // + // try { + // // create the delta builder (this remembers the current content of the + // cu) + // if (!wasConsistent){ + // deltaBuilder = new JavaElementDeltaBuilder(workingCopy); + // + // // update the element infos with the content of the working copy + // workingCopy.makeConsistent(fMonitor); + // deltaBuilder.buildDeltas(); + // + // } + // + // if (fMonitor != null) fMonitor.worked(2); + // + // // force problem detection? - if structure was consistent + // if (forceProblemDetection && wasConsistent){ + // if (fMonitor != null && fMonitor.isCanceled()) return; + // + // IProblemRequestor problemRequestor = workingCopy.problemRequestor; + // if (problemRequestor != null && problemRequestor.isActive()){ + // problemRequestor.beginReporting(); + // CompilationUnitProblemFinder.process(workingCopy, problemRequestor, + // fMonitor); + // problemRequestor.endReporting(); + // } + // } + // + // // register the deltas + // if (deltaBuilder != null){ + // if ((deltaBuilder.delta != null) && + // (deltaBuilder.delta.getAffectedChildren().length > 0)) { + // addReconcileDelta(workingCopy, deltaBuilder.delta); + // } + // } + // } finally { + // if (fMonitor != null) fMonitor.done(); + // } + // } protected void executeOperation() throws JavaModelException { - // TODO jsurfer optimize for PHP - if (progressMonitor != null){ - if (progressMonitor.isCanceled()) return; + // TODO jsurfer optimize for PHP + if (progressMonitor != null) { + if (progressMonitor.isCanceled()) + return; progressMonitor.beginTask(Util.bind("element.reconciling"), 10); //$NON-NLS-1$ } - + CompilationUnit workingCopy = getWorkingCopy(); -// boolean wasConsistent = workingCopy.isConsistent(); -// JavaElementDeltaBuilder deltaBuilder = null; - + // boolean wasConsistent = workingCopy.isConsistent(); + // JavaElementDeltaBuilder deltaBuilder = null; + try { - // create the delta builder (this remembers the current content of the cu) -// if (!wasConsistent){ -// deltaBuilder = new JavaElementDeltaBuilder(workingCopy); -// -// // update the element infos with the content of the working copy -// workingCopy.makeConsistent(fMonitor); -// deltaBuilder.buildDeltas(); -// -// } - - if (progressMonitor != null) progressMonitor.worked(2); - + // create the delta builder (this remembers the current content of + // the cu) + // if (!wasConsistent){ + // deltaBuilder = new JavaElementDeltaBuilder(workingCopy); + // + // // update the element infos with the content of the working copy + // workingCopy.makeConsistent(fMonitor); + // deltaBuilder.buildDeltas(); + // + // } + + if (progressMonitor != null) + progressMonitor.worked(2); + // force problem detection? - if structure was consistent - if (forceProblemDetection){ - if (progressMonitor != null && progressMonitor.isCanceled()) return; + if (forceProblemDetection) { + if (progressMonitor != null && progressMonitor.isCanceled()) + return; CompilationUnitDeclaration unit = null; try { - IProblemRequestor problemRequestor = workingCopy.getPerWorkingCopyInfo(); - if (problemRequestor != null && problemRequestor.isActive()){ - problemRequestor.beginReporting(); - char[] contents = workingCopy.getContents(); - unit = CompilationUnitProblemFinder.process(workingCopy, contents, this.workingCopyOwner, problemRequestor, false/*don't cleanup cu*/, this.progressMonitor); - CompilationUnitProblemFinder.process(workingCopy, problemRequestor, progressMonitor); - problemRequestor.endReporting(); - } - if (progressMonitor != null) progressMonitor.worked(1); - if (this.createAST && unit != null) { -// Map options = workingCopy.getJavaProject().getOptions(true); -// this.ast = AST.convertCompilationUnit(this.astLevel, unit, contents, options, this.progressMonitor); - if (progressMonitor != null) progressMonitor.worked(1); - } + IProblemRequestor problemRequestor = workingCopy + .getPerWorkingCopyInfo(); + if (problemRequestor != null && problemRequestor.isActive()) { + problemRequestor.beginReporting(); + char[] contents = workingCopy.getContents(); + unit = CompilationUnitProblemFinder.process( + workingCopy, contents, this.workingCopyOwner, + problemRequestor, false/* don't cleanup cu */, + this.progressMonitor); + CompilationUnitProblemFinder.process(workingCopy, + problemRequestor, progressMonitor); + problemRequestor.endReporting(); + } + if (progressMonitor != null) + progressMonitor.worked(1); + if (this.createAST && unit != null) { + // Map options = + // workingCopy.getJavaProject().getOptions(true); + // this.ast = AST.convertCompilationUnit(this.astLevel, + // unit, contents, options, this.progressMonitor); + if (progressMonitor != null) + progressMonitor.worked(1); + } } finally { - if (unit != null) { - unit.cleanUp(); - } - } + if (unit != null) { + unit.cleanUp(); + } + } } - + // register the deltas -// if (deltaBuilder != null){ -// if ((deltaBuilder.delta != null) && (deltaBuilder.delta.getAffectedChildren().length > 0)) { -// addReconcileDelta(workingCopy, deltaBuilder.delta); -// } -// } + // if (deltaBuilder != null){ + // if ((deltaBuilder.delta != null) && + // (deltaBuilder.delta.getAffectedChildren().length > 0)) { + // addReconcileDelta(workingCopy, deltaBuilder.delta); + // } + // } } finally { - if (progressMonitor != null) progressMonitor.done(); + if (progressMonitor != null) + progressMonitor.done(); } } + /** * Returns the working copy this operation is working on. */ protected CompilationUnit getWorkingCopy() { - return (CompilationUnit)getElementToProcess(); + return (CompilationUnit) getElementToProcess(); } + /** * @see JavaModelOperation#isReadOnly */ public boolean isReadOnly() { return true; } - + protected IJavaModelStatus verify() { IJavaModelStatus status = super.verify(); if (!status.isOK()) { @@ -170,7 +201,9 @@ public class ReconcileWorkingCopyOperation extends JavaModelOperation { } CompilationUnit workingCopy = getWorkingCopy(); if (!workingCopy.isWorkingCopy()) { - return new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, workingCopy); //was destroyed + return new JavaModelStatus( + IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, + workingCopy); // was destroyed } return status; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Region.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Region.java index 45c3cc8..dd745d9 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Region.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Region.java @@ -19,132 +19,140 @@ import net.sourceforge.phpdt.core.IRegion; /** * @see IRegion */ - + public class Region implements IRegion { /** - * A collection of the top level elements - * that have been added to the region + * A collection of the top level elements that have been added to the region */ protected ArrayList fRootElements; -/** - * Creates an empty region. - * - * @see IRegion - */ -public Region() { - fRootElements = new ArrayList(1); -} -/** - * @see IRegion#add(IJavaElement) - */ -public void add(IJavaElement element) { - if (!contains(element)) { - //"new" element added to region - removeAllChildren(element); - fRootElements.add(element); - fRootElements.trimToSize(); + + /** + * Creates an empty region. + * + * @see IRegion + */ + public Region() { + fRootElements = new ArrayList(1); } -} -/** - * @see IRegion - */ -public boolean contains(IJavaElement element) { - - int size = fRootElements.size(); - ArrayList parents = getAncestors(element); - - for (int i = 0; i < size; i++) { - IJavaElement aTop = (IJavaElement) fRootElements.get(i); - if (aTop.equals(element)) { - return true; + + /** + * @see IRegion#add(IJavaElement) + */ + public void add(IJavaElement element) { + if (!contains(element)) { + // "new" element added to region + removeAllChildren(element); + fRootElements.add(element); + fRootElements.trimToSize(); } - for (int j = 0, pSize = parents.size(); j < pSize; j++) { - if (aTop.equals(parents.get(j))) { - //an ancestor is already included + } + + /** + * @see IRegion + */ + public boolean contains(IJavaElement element) { + + int size = fRootElements.size(); + ArrayList parents = getAncestors(element); + + for (int i = 0; i < size; i++) { + IJavaElement aTop = (IJavaElement) fRootElements.get(i); + if (aTop.equals(element)) { return true; } + for (int j = 0, pSize = parents.size(); j < pSize; j++) { + if (aTop.equals(parents.get(j))) { + // an ancestor is already included + return true; + } + } } + return false; } - return false; -} -/** - * Returns a collection of all the parents of this element - * in bottom-up order. - * - */ -private ArrayList getAncestors(IJavaElement element) { - ArrayList parents = new ArrayList(); - IJavaElement parent = element.getParent(); - while (parent != null) { - parents.add(parent); - parent = parent.getParent(); + + /** + * Returns a collection of all the parents of this element in bottom-up + * order. + * + */ + private ArrayList getAncestors(IJavaElement element) { + ArrayList parents = new ArrayList(); + IJavaElement parent = element.getParent(); + while (parent != null) { + parents.add(parent); + parent = parent.getParent(); + } + parents.trimToSize(); + return parents; } - parents.trimToSize(); - return parents; -} -/** - * @see IRegion - */ -public IJavaElement[] getElements() { - int size= fRootElements.size(); - IJavaElement[] roots= new IJavaElement[size]; - for (int i = 0; i < size; i++) { - roots[i]= (IJavaElement) fRootElements.get(i); + + /** + * @see IRegion + */ + public IJavaElement[] getElements() { + int size = fRootElements.size(); + IJavaElement[] roots = new IJavaElement[size]; + for (int i = 0; i < size; i++) { + roots[i] = (IJavaElement) fRootElements.get(i); + } + + return roots; } - return roots; -} -/** - * @see IRegion#remove(IJavaElement) - */ -public boolean remove(IJavaElement element) { + /** + * @see IRegion#remove(IJavaElement) + */ + public boolean remove(IJavaElement element) { - removeAllChildren(element); - return fRootElements.remove(element); -} -/** - * Removes any children of this element that are contained within this - * region as this parent is about to be added to the region. - * - *

                                              Children are all children, not just direct children. - */ -private void removeAllChildren(IJavaElement element) { - if (element instanceof IParent) { - ArrayList newRootElements = new ArrayList(); - for (int i = 0, size = fRootElements.size(); i < size; i++) { - IJavaElement currentRoot = (IJavaElement)fRootElements.get(i); - //walk the current root hierarchy - IJavaElement parent = currentRoot.getParent(); - boolean isChild= false; - while (parent != null) { - if (parent.equals(element)) { - isChild= true; - break; + removeAllChildren(element); + return fRootElements.remove(element); + } + + /** + * Removes any children of this element that are contained within this + * region as this parent is about to be added to the region. + * + *

                                              + * Children are all children, not just direct children. + */ + private void removeAllChildren(IJavaElement element) { + if (element instanceof IParent) { + ArrayList newRootElements = new ArrayList(); + for (int i = 0, size = fRootElements.size(); i < size; i++) { + IJavaElement currentRoot = (IJavaElement) fRootElements.get(i); + // walk the current root hierarchy + IJavaElement parent = currentRoot.getParent(); + boolean isChild = false; + while (parent != null) { + if (parent.equals(element)) { + isChild = true; + break; + } + parent = parent.getParent(); + } + if (!isChild) { + newRootElements.add(currentRoot); } - parent = parent.getParent(); - } - if (!isChild) { - newRootElements.add(currentRoot); } + fRootElements = newRootElements; } - fRootElements= newRootElements; } -} -/** - * Returns a printable representation of this region. - */ -public String toString() { - StringBuffer buffer= new StringBuffer(); - IJavaElement[] roots= getElements(); - buffer.append('['); - for (int i= 0; i < roots.length; i++) { - buffer.append(roots[i].getElementName()); - if (i < (roots.length - 1)) { - buffer.append(", "); //$NON-NLS-1$ + + /** + * Returns a printable representation of this region. + */ + public String toString() { + StringBuffer buffer = new StringBuffer(); + IJavaElement[] roots = getElements(); + buffer.append('['); + for (int i = 0; i < roots.length; i++) { + buffer.append(roots[i].getElementName()); + if (i < (roots.length - 1)) { + buffer.append(", "); //$NON-NLS-1$ + } } + buffer.append(']'); + return buffer.toString(); } - buffer.append(']'); - return buffer.toString(); -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/RenameElementsOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/RenameElementsOperation.java index 145d546..44652a0 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/RenameElementsOperation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/RenameElementsOperation.java @@ -19,66 +19,75 @@ import net.sourceforge.phpdt.internal.core.util.Util; /** * This operation renames elements. - * - *

                                              Notes:

                                                - *
                                              • Resource rename is not supported - this operation only renames - * elements contained in compilation units. - *
                                              • When a main type is renamed, its compilation unit and constructors are renamed. + * + *

                                                + * Notes: + *

                                                  + *
                                                • Resource rename is not supported - this operation only renames elements + * contained in compilation units. + *
                                                • When a main type is renamed, its compilation unit and constructors are + * renamed. *
                                                • Constructors cannot be renamed. *
                                                */ public class RenameElementsOperation extends MoveElementsOperation { -/** - * When executed, this operation will rename the specified elements with the given names in the - * corresponding destinations. - */ -public RenameElementsOperation(IJavaElement[] elements, IJavaElement[] destinations, String[] newNames, boolean force) { - //a rename is a move to the same parent with a new name specified - //these elements are from different parents - super(elements, destinations, force); - setRenamings(newNames); -} -/** - * @see MultiOperation - */ -protected String getMainTaskName() { - return Util.bind("operation.renameElementProgress"); //$NON-NLS-1$ -} -/** - * @see CopyElementsOperation#isRename() - */ -protected boolean isRename() { - return true; -} -/** - * @see MultiOperation - */ -protected IJavaModelStatus verify() { - IJavaModelStatus status = super.verify(); - if (! status.isOK()) - return status; - if (fRenamingsList == null || fRenamingsList.length == 0) - return new JavaModelStatus(IJavaModelStatusConstants.NULL_NAME); - return JavaModelStatus.VERIFIED_OK; -} -/** - * @see MultiOperation - */ -protected void verify(IJavaElement element) throws JavaModelException { - int elementType = element.getElementType(); - - if (element == null || !element.exists()) - error(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, element); - - if (element.isReadOnly()) - error(IJavaModelStatusConstants.READ_ONLY, element); - - if (!(element instanceof ISourceReference)) - error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element); - - if (elementType < IJavaElement.TYPE || elementType == IJavaElement.INITIALIZER) - error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element); - - verifyRenaming(element); -} + /** + * When executed, this operation will rename the specified elements with the + * given names in the corresponding destinations. + */ + public RenameElementsOperation(IJavaElement[] elements, + IJavaElement[] destinations, String[] newNames, boolean force) { + // a rename is a move to the same parent with a new name specified + // these elements are from different parents + super(elements, destinations, force); + setRenamings(newNames); + } + + /** + * @see MultiOperation + */ + protected String getMainTaskName() { + return Util.bind("operation.renameElementProgress"); //$NON-NLS-1$ + } + + /** + * @see CopyElementsOperation#isRename() + */ + protected boolean isRename() { + return true; + } + + /** + * @see MultiOperation + */ + protected IJavaModelStatus verify() { + IJavaModelStatus status = super.verify(); + if (!status.isOK()) + return status; + if (fRenamingsList == null || fRenamingsList.length == 0) + return new JavaModelStatus(IJavaModelStatusConstants.NULL_NAME); + return JavaModelStatus.VERIFIED_OK; + } + + /** + * @see MultiOperation + */ + protected void verify(IJavaElement element) throws JavaModelException { + int elementType = element.getElementType(); + + if (element == null || !element.exists()) + error(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, element); + + if (element.isReadOnly()) + error(IJavaModelStatusConstants.READ_ONLY, element); + + if (!(element instanceof ISourceReference)) + error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element); + + if (elementType < IJavaElement.TYPE + || elementType == IJavaElement.INITIALIZER) + error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element); + + verifyRenaming(element); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/RenameResourceElementsOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/RenameResourceElementsOperation.java index 36d01c4..663c6a4 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/RenameResourceElementsOperation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/RenameResourceElementsOperation.java @@ -18,51 +18,58 @@ import net.sourceforge.phpdt.internal.core.util.Util; /** * This operation renames resources (Package fragments and compilation units). - * - *

                                                Notes:

                                                  - *
                                                • When a compilation unit is renamed, its main type and the constructors of the - * main type are renamed. + * + *

                                                  + * Notes: + *

                                                    + *
                                                  • When a compilation unit is renamed, its main type and the constructors + * of the main type are renamed. *
                                                  */ -public class RenameResourceElementsOperation extends MoveResourceElementsOperation { -/** - * When executed, this operation will rename the specified elements with the given names in the - * corresponding destinations. - */ -public RenameResourceElementsOperation(IJavaElement[] elements, IJavaElement[] destinations, String[] newNames, boolean force) { - //a rename is a move to the same parent with a new name specified - //these elements are from different parents - super(elements, destinations, force); - setRenamings(newNames); -} -/** - * @see MultiOperation - */ -protected String getMainTaskName() { - return Util.bind("operation.renameResourceProgress"); //$NON-NLS-1$ -} -/** - * @see CopyResourceElementsOperation#isRename() - */ -protected boolean isRename() { - return true; -} -/** - * @see MultiOperation - */ -protected void verify(IJavaElement element) throws JavaModelException { - super.verify(element); +public class RenameResourceElementsOperation extends + MoveResourceElementsOperation { + /** + * When executed, this operation will rename the specified elements with the + * given names in the corresponding destinations. + */ + public RenameResourceElementsOperation(IJavaElement[] elements, + IJavaElement[] destinations, String[] newNames, boolean force) { + // a rename is a move to the same parent with a new name specified + // these elements are from different parents + super(elements, destinations, force); + setRenamings(newNames); + } + + /** + * @see MultiOperation + */ + protected String getMainTaskName() { + return Util.bind("operation.renameResourceProgress"); //$NON-NLS-1$ + } - int elementType = element.getElementType(); - - if (!(elementType == IJavaElement.COMPILATION_UNIT || elementType == IJavaElement.PACKAGE_FRAGMENT)) { - error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element); + /** + * @see CopyResourceElementsOperation#isRename() + */ + protected boolean isRename() { + return true; } - if (elementType == IJavaElement.COMPILATION_UNIT) { - if (((ICompilationUnit) element).isWorkingCopy()) { + + /** + * @see MultiOperation + */ + protected void verify(IJavaElement element) throws JavaModelException { + super.verify(element); + + int elementType = element.getElementType(); + + if (!(elementType == IJavaElement.COMPILATION_UNIT || elementType == IJavaElement.PACKAGE_FRAGMENT)) { error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element); } + if (elementType == IJavaElement.COMPILATION_UNIT) { + if (((ICompilationUnit) element).isWorkingCopy()) { + error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element); + } + } + verifyRenaming(element); } - verifyRenaming(element); -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SearchableEnvironment.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SearchableEnvironment.java index 87fe51a..6a405c9 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SearchableEnvironment.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SearchableEnvironment.java @@ -30,291 +30,328 @@ import net.sourceforge.phpdt.internal.compiler.env.NameEnvironmentAnswer; import org.eclipse.core.runtime.IProgressMonitor; /** - * This class provides a SearchableBuilderEnvironment for code assist which - * uses the Java model as a search tool. + * This class provides a SearchableBuilderEnvironment for code + * assist which uses the Java model as a search tool. */ -public class SearchableEnvironment implements ISearchableNameEnvironment, IJavaSearchConstants { - protected NameLookup nameLookup; - protected ICompilationUnit unitToSkip; +public class SearchableEnvironment implements ISearchableNameEnvironment, + IJavaSearchConstants { + protected NameLookup nameLookup; - protected IJavaProject project; - //protected IJavaSearchScope searchScope; + protected ICompilationUnit unitToSkip; + + protected IJavaProject project; + + // protected IJavaSearchScope searchScope; /** - * Creates a Sea - /** - * Creates a SearchableEnvironment on the given project - */ - public SearchableEnvironment(IJavaProject project) throws JavaModelException { - this.project = project; - this.nameLookup = (NameLookup) ((JavaProject) project).getNameLookup(); - - // Create search scope with visible entry on the project's classpath - // this.searchScope = SearchEngine.createJavaSearchScope(this.project.getAllPackageFragmentRoots()); - } - - + * Creates a Sea /** Creates a SearchableEnvironment on the given project + */ + public SearchableEnvironment(IJavaProject project) + throws JavaModelException { + this.project = project; + this.nameLookup = (NameLookup) ((JavaProject) project).getNameLookup(); + + // Create search scope with visible entry on the project's classpath + // this.searchScope = + // SearchEngine.createJavaSearchScope(this.project.getAllPackageFragmentRoots()); + } /** * Creates a SearchableEnvironment on the given project */ - public SearchableEnvironment(JavaProject project, WorkingCopyOwner owner) throws JavaModelException { + public SearchableEnvironment(JavaProject project, WorkingCopyOwner owner) + throws JavaModelException { this.project = project; this.nameLookup = project.newNameLookup(owner); // Create search scope with visible entry on the project's classpath -// this.searchScope = SearchEngine.createJavaSearchScope(this.project.getAllPackageFragmentRoots()); + // this.searchScope = + // SearchEngine.createJavaSearchScope(this.project.getAllPackageFragmentRoots()); + } + + /** + * Returns the given type in the the given package if it exists, otherwise + * null. + */ + protected NameEnvironmentAnswer find(String typeName, String packageName) { + if (packageName == null) + packageName = IPackageFragment.DEFAULT_PACKAGE_NAME; + + if (this.nameLookup != null) { // ins axelcl + IType type = this.nameLookup.findType(typeName, packageName, false, + NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES); + if (type != null) { + // if (type instanceof BinaryType) { + // try { + // return new NameEnvironmentAnswer( + // (IBinaryType) ((BinaryType) type).getElementInfo()); + // } catch (JavaModelException npe) { + // return null; + // } + // } else { //SourceType + try { + // retrieve the requested type + SourceTypeElementInfo sourceType = (SourceTypeElementInfo) ((SourceType) type) + .getElementInfo(); + ISourceType topLevelType = sourceType; + while (topLevelType.getEnclosingType() != null) { + topLevelType = topLevelType.getEnclosingType(); + } + // find all siblings (other types declared in same unit, + // since may be used for name resolution) + IType[] types = sourceType.getHandle().getCompilationUnit() + .getTypes(); + ISourceType[] sourceTypes = new ISourceType[types.length]; + + // in the resulting collection, ensure the requested type is + // the first one + sourceTypes[0] = sourceType; + for (int i = 0, index = 1; i < types.length; i++) { + ISourceType otherType = (ISourceType) ((JavaElement) types[i]) + .getElementInfo(); + if (!otherType.equals(topLevelType)) + sourceTypes[index++] = otherType; + } + return new NameEnvironmentAnswer(sourceTypes); + } catch (JavaModelException npe) { + return null; + } + // } + } + } + return null; + } + + /** + * @see ISearchableNameEnvironment#findPackages(char[], ISearchRequestor) + */ + public void findPackages(char[] prefix, ISearchRequestor requestor) { + // this.nameLookup.seekPackageFragments( + // new String(prefix), + // true, + // new SearchableEnvironmentRequestor(requestor)); + } + + /** + * @see INameEnvironment#findType(char[][]) + */ + public NameEnvironmentAnswer findType(char[][] compoundTypeName) { + if (compoundTypeName == null) + return null; + + int length = compoundTypeName.length; + if (length <= 1) { + if (length == 0) + return null; + return find(new String(compoundTypeName[0]), null); + } + + int lengthM1 = length - 1; + char[][] packageName = new char[lengthM1][]; + System.arraycopy(compoundTypeName, 0, packageName, 0, lengthM1); + + return find(new String(compoundTypeName[lengthM1]), CharOperation + .toString(packageName)); + } + + /** + * @see INameEnvironment#findType(char[], char[][]) + */ + public NameEnvironmentAnswer findType(char[] name, char[][] packageName) { + if (name == null) + return null; + + return find(new String(name), packageName == null + || packageName.length == 0 ? null : CharOperation + .toString(packageName)); + } + + /** + * @see ISearchableNameEnvironment#findTypes(char[], ISearchRequestor) + */ + public void findTypes(char[] prefix, final ISearchRequestor storage) { + + /* + * if (true){ findTypes(new String(prefix), storage, + * NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES); return; } + */ + // try { + final String excludePath; + if (this.unitToSkip != null) { + if (!(this.unitToSkip instanceof IJavaElement)) { + // revert to model investigation + findTypes(new String(prefix), storage, + NameLookup.ACCEPT_CLASSES + | NameLookup.ACCEPT_INTERFACES); + return; + } + excludePath = ((IJavaElement) this.unitToSkip).getPath().toString(); + } else { + excludePath = null; + } + int lastDotIndex = CharOperation.lastIndexOf('.', prefix); + char[] qualification, simpleName; + if (lastDotIndex < 0) { + qualification = null; + simpleName = CharOperation.toLowerCase(prefix); + } else { + qualification = CharOperation.subarray(prefix, 0, lastDotIndex); + simpleName = CharOperation.toLowerCase(CharOperation.subarray( + prefix, lastDotIndex + 1, prefix.length)); + } + + IProgressMonitor progressMonitor = new IProgressMonitor() { + boolean isCanceled = false; + + public void beginTask(String name, int totalWork) { + } + + public void done() { + } + + public void internalWorked(double work) { + } + + public boolean isCanceled() { + return isCanceled; + } + + public void setCanceled(boolean value) { + isCanceled = value; + } + + public void setTaskName(String name) { + } + + public void subTask(String name) { + } + + public void worked(int work) { + } + }; + ITypeNameRequestor nameRequestor = new ITypeNameRequestor() { + public void acceptClass(char[] packageName, char[] simpleTypeName, + char[][] enclosingTypeNames, String path) { + if (excludePath != null && excludePath.equals(path)) + return; + if (enclosingTypeNames != null && enclosingTypeNames.length > 0) + return; // accept only top level types + storage.acceptClass(packageName, simpleTypeName, + IConstants.AccPublic); + } + + public void acceptInterface(char[] packageName, + char[] simpleTypeName, char[][] enclosingTypeNames, + String path) { + if (excludePath != null && excludePath.equals(path)) + return; + if (enclosingTypeNames != null && enclosingTypeNames.length > 0) + return; // accept only top level types + storage.acceptInterface(packageName, simpleTypeName, + IConstants.AccPublic); + } + }; + // try { + // new SearchEngine().searchAllTypeNames( + // this.project.getProject().getWorkspace(), + // qualification, + // simpleName, + // PREFIX_MATCH, + // CASE_INSENSITIVE, + // IJavaSearchConstants.TYPE, + // this.searchScope, + // nameRequestor, + // CANCEL_IF_NOT_READY_TO_SEARCH, + // progressMonitor); + // } catch (OperationCanceledException e) { + // findTypes( + // new String(prefix), + // storage, + // NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES); + // } + // } catch (JavaModelException e) { + // findTypes( + // new String(prefix), + // storage, + // NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES); + // } + } + + /** + * Returns all types whose name starts with the given (qualified) + * prefix. + * + * If the prefix is unqualified, all types whose simple name + * matches the prefix are returned. + */ + private void findTypes(String prefix, ISearchRequestor storage, int type) { + SearchableEnvironmentRequestor requestor = new SearchableEnvironmentRequestor( + storage, this.unitToSkip); + int index = prefix.lastIndexOf('.'); + if (index == -1) { + this.nameLookup.seekTypes(prefix, null, true, type, requestor); + } else { + String packageName = prefix.substring(0, index); + JavaElementRequestor elementRequestor = new JavaElementRequestor(); + this.nameLookup.seekPackageFragments(packageName, false, + elementRequestor); + IPackageFragment[] fragments = elementRequestor + .getPackageFragments(); + if (fragments != null) { + String className = prefix.substring(index + 1); + for (int i = 0, length = fragments.length; i < length; i++) + if (fragments[i] != null) + this.nameLookup.seekTypes(className, fragments[i], + true, type, requestor); + } + } + } + + /** + * @see INameEnvironment#isPackage(char[][], char[]) + */ + public boolean isPackage(char[][] parentPackageName, char[] subPackageName) { + if (subPackageName == null + || CharOperation.contains('.', subPackageName)) + return false; + if (parentPackageName == null || parentPackageName.length == 0) + return isTopLevelPackage(subPackageName); + for (int i = 0, length = parentPackageName.length; i < length; i++) + if (parentPackageName[i] == null + || CharOperation.contains('.', parentPackageName[i])) + return false; + + String packageName = new String(CharOperation.concatWith( + parentPackageName, subPackageName, '.')); + return this.nameLookup.findPackageFragments(packageName, false) != null; + } + + public boolean isTopLevelPackage(char[] packageName) { + return packageName != null + && !CharOperation.contains('.', packageName) + && this.nameLookup.findPackageFragments( + new String(packageName), false) != null; + } + + /** + * Returns a printable string for the array. + */ + protected String toStringChar(char[] name) { + return "[" //$NON-NLS-1$ + + new String(name) + "]"; //$NON-NLS-1$ + } + + /** + * Returns a printable string for the array. + */ + protected String toStringCharChar(char[][] names) { + StringBuffer result = new StringBuffer(); + for (int i = 0; i < names.length; i++) { + result.append(toStringChar(names[i])); + } + return result.toString(); + } + + public void cleanup() { } - /** - * Returns the given type in the the given package if it exists, - * otherwise null. - */ - protected NameEnvironmentAnswer find(String typeName, String packageName) { - if (packageName == null) - packageName = IPackageFragment.DEFAULT_PACKAGE_NAME; - - if (this.nameLookup!=null) { // ins axelcl - IType type = this.nameLookup.findType(typeName, packageName, false, NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES); - if (type != null) { - // if (type instanceof BinaryType) { - // try { - // return new NameEnvironmentAnswer( - // (IBinaryType) ((BinaryType) type).getElementInfo()); - // } catch (JavaModelException npe) { - // return null; - // } - // } else { //SourceType - try { - // retrieve the requested type - SourceTypeElementInfo sourceType = (SourceTypeElementInfo) ((SourceType) type).getElementInfo(); - ISourceType topLevelType = sourceType; - while (topLevelType.getEnclosingType() != null) { - topLevelType = topLevelType.getEnclosingType(); - } - // find all siblings (other types declared in same unit, since may be used for name resolution) - IType[] types = sourceType.getHandle().getCompilationUnit().getTypes(); - ISourceType[] sourceTypes = new ISourceType[types.length]; - - // in the resulting collection, ensure the requested type is the first one - sourceTypes[0] = sourceType; - for (int i = 0, index = 1; i < types.length; i++) { - ISourceType otherType = (ISourceType) ((JavaElement) types[i]).getElementInfo(); - if (!otherType.equals(topLevelType)) - sourceTypes[index++] = otherType; - } - return new NameEnvironmentAnswer(sourceTypes); - } catch (JavaModelException npe) { - return null; - } - // } - } - } - return null; - } - - /** - * @see ISearchableNameEnvironment#findPackages(char[], ISearchRequestor) - */ - public void findPackages(char[] prefix, ISearchRequestor requestor) { - // this.nameLookup.seekPackageFragments( - // new String(prefix), - // true, - // new SearchableEnvironmentRequestor(requestor)); - } - - /** - * @see INameEnvironment#findType(char[][]) - */ - public NameEnvironmentAnswer findType(char[][] compoundTypeName) { - if (compoundTypeName == null) - return null; - - int length = compoundTypeName.length; - if (length <= 1) { - if (length == 0) - return null; - return find(new String(compoundTypeName[0]), null); - } - - int lengthM1 = length - 1; - char[][] packageName = new char[lengthM1][]; - System.arraycopy(compoundTypeName, 0, packageName, 0, lengthM1); - - return find(new String(compoundTypeName[lengthM1]), CharOperation.toString(packageName)); - } - - /** - * @see INameEnvironment#findType(char[], char[][]) - */ - public NameEnvironmentAnswer findType(char[] name, char[][] packageName) { - if (name == null) - return null; - - return find(new String(name), packageName == null || packageName.length == 0 ? null : CharOperation.toString(packageName)); - } - - /** - * @see ISearchableNameEnvironment#findTypes(char[], ISearchRequestor) - */ - public void findTypes(char[] prefix, final ISearchRequestor storage) { - - /* - if (true){ - findTypes(new String(prefix), storage, NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES); - return; - } - */ - // try { - final String excludePath; - if (this.unitToSkip != null) { - if (!(this.unitToSkip instanceof IJavaElement)) { - // revert to model investigation - findTypes(new String(prefix), storage, NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES); - return; - } - excludePath = ((IJavaElement) this.unitToSkip).getPath().toString(); - } else { - excludePath = null; - } - int lastDotIndex = CharOperation.lastIndexOf('.', prefix); - char[] qualification, simpleName; - if (lastDotIndex < 0) { - qualification = null; - simpleName = CharOperation.toLowerCase(prefix); - } else { - qualification = CharOperation.subarray(prefix, 0, lastDotIndex); - simpleName = CharOperation.toLowerCase(CharOperation.subarray(prefix, lastDotIndex + 1, prefix.length)); - } - - IProgressMonitor progressMonitor = new IProgressMonitor() { - boolean isCanceled = false; - public void beginTask(String name, int totalWork) { - } - public void done() { - } - public void internalWorked(double work) { - } - public boolean isCanceled() { - return isCanceled; - } - public void setCanceled(boolean value) { - isCanceled = value; - } - public void setTaskName(String name) { - } - public void subTask(String name) { - } - public void worked(int work) { - } - }; - ITypeNameRequestor nameRequestor = new ITypeNameRequestor() { - public void acceptClass(char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path) { - if (excludePath != null && excludePath.equals(path)) - return; - if (enclosingTypeNames != null && enclosingTypeNames.length > 0) - return; // accept only top level types - storage.acceptClass(packageName, simpleTypeName, IConstants.AccPublic); - } - public void acceptInterface(char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path) { - if (excludePath != null && excludePath.equals(path)) - return; - if (enclosingTypeNames != null && enclosingTypeNames.length > 0) - return; // accept only top level types - storage.acceptInterface(packageName, simpleTypeName, IConstants.AccPublic); - } - }; - // try { - // new SearchEngine().searchAllTypeNames( - // this.project.getProject().getWorkspace(), - // qualification, - // simpleName, - // PREFIX_MATCH, - // CASE_INSENSITIVE, - // IJavaSearchConstants.TYPE, - // this.searchScope, - // nameRequestor, - // CANCEL_IF_NOT_READY_TO_SEARCH, - // progressMonitor); - // } catch (OperationCanceledException e) { - // findTypes( - // new String(prefix), - // storage, - // NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES); - // } - // } catch (JavaModelException e) { - // findTypes( - // new String(prefix), - // storage, - // NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES); - // } - } - - /** - * Returns all types whose name starts with the given (qualified) prefix. - * - * If the prefix is unqualified, all types whose simple name matches - * the prefix are returned. - */ - private void findTypes(String prefix, ISearchRequestor storage, int type) { - SearchableEnvironmentRequestor requestor = new SearchableEnvironmentRequestor(storage, this.unitToSkip); - int index = prefix.lastIndexOf('.'); - if (index == -1) { - this.nameLookup.seekTypes(prefix, null, true, type, requestor); - } else { - String packageName = prefix.substring(0, index); - JavaElementRequestor elementRequestor = new JavaElementRequestor(); - this.nameLookup.seekPackageFragments(packageName, false, elementRequestor); - IPackageFragment[] fragments = elementRequestor.getPackageFragments(); - if (fragments != null) { - String className = prefix.substring(index + 1); - for (int i = 0, length = fragments.length; i < length; i++) - if (fragments[i] != null) - this.nameLookup.seekTypes(className, fragments[i], true, type, requestor); - } - } - } - - /** - * @see INameEnvironment#isPackage(char[][], char[]) - */ - public boolean isPackage(char[][] parentPackageName, char[] subPackageName) { - if (subPackageName == null || CharOperation.contains('.', subPackageName)) - return false; - if (parentPackageName == null || parentPackageName.length == 0) - return isTopLevelPackage(subPackageName); - for (int i = 0, length = parentPackageName.length; i < length; i++) - if (parentPackageName[i] == null || CharOperation.contains('.', parentPackageName[i])) - return false; - - String packageName = new String(CharOperation.concatWith(parentPackageName, subPackageName, '.')); - return this.nameLookup.findPackageFragments(packageName, false) != null; - } - - public boolean isTopLevelPackage(char[] packageName) { - return packageName != null - && !CharOperation.contains('.', packageName) - && this.nameLookup.findPackageFragments(new String(packageName), false) != null; - } - - /** - * Returns a printable string for the array. - */ - protected String toStringChar(char[] name) { - return "[" //$NON-NLS-1$ - + new String(name) + "]"; //$NON-NLS-1$ - } - - /** - * Returns a printable string for the array. - */ - protected String toStringCharChar(char[][] names) { - StringBuffer result = new StringBuffer(); - for (int i = 0; i < names.length; i++) { - result.append(toStringChar(names[i])); - } - return result.toString(); - } - - public void cleanup() { - } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SearchableEnvironmentRequestor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SearchableEnvironmentRequestor.java index caf3e0f..15cb8b0 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SearchableEnvironmentRequestor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SearchableEnvironmentRequestor.java @@ -18,65 +18,79 @@ import net.sourceforge.phpdt.internal.codeassist.ISearchRequestor; /** * Implements IJavaElementRequestor, wrappering and forwarding - * results onto a org.eclipse.jdt.internal.codeassist.api.ISearchRequestor. + * results onto a + * org.eclipse.jdt.internal.codeassist.api.ISearchRequestor. */ -class SearchableEnvironmentRequestor extends JavaElementRequestor implements IJavaElementRequestor { +class SearchableEnvironmentRequestor extends JavaElementRequestor implements + IJavaElementRequestor { /** - * The ISearchRequestor this JavaElementRequestor wraps - * and forwards results to. + * The ISearchRequestor this JavaElementRequestor wraps and + * forwards results to. */ protected ISearchRequestor fRequestor; + /** * The ICompilationUNit this JavaElementRequestor will not * accept types within. */ protected ICompilationUnit fUnitToSkip; -/** - * Constructs a SearchableEnvironmentRequestor that wraps the - * given SearchRequestor. - */ -public SearchableEnvironmentRequestor(ISearchRequestor requestor) { - fRequestor = requestor; - fUnitToSkip= null; -} -/** - * Constructs a SearchableEnvironmentRequestor that wraps the - * given SearchRequestor. The requestor will not accept types in - * the unitToSkip. - */ -public SearchableEnvironmentRequestor(ISearchRequestor requestor, ICompilationUnit unitToSkip) { - fRequestor = requestor; - fUnitToSkip= unitToSkip; -} -/** - * Do nothing, a SearchRequestor does not accept initializers - * so there is no need to forward this results. - * - * @see IJavaElementRequestor - */ -//public void acceptInitializer(IInitializer initializer) { -// -//} -/** - * @see IJavaElementRequestor - */ -public void acceptPackageFragment(IPackageFragment packageFragment) { - fRequestor.acceptPackage(packageFragment.getElementName().toCharArray()); -} -/** - * @see IJavaElementRequestor - */ -public void acceptType(IType type) { - try { - if (fUnitToSkip != null && fUnitToSkip.equals(type.getCompilationUnit())){ - return; - } - if (type.isClass()) { - fRequestor.acceptClass(type.getPackageFragment().getElementName().toCharArray(), type.getElementName().toCharArray(), type.getFlags()); - } else { - fRequestor.acceptInterface(type.getPackageFragment().getElementName().toCharArray(), type.getElementName().toCharArray(), type.getFlags()); + + /** + * Constructs a SearchableEnvironmentRequestor that wraps the given + * SearchRequestor. + */ + public SearchableEnvironmentRequestor(ISearchRequestor requestor) { + fRequestor = requestor; + fUnitToSkip = null; + } + + /** + * Constructs a SearchableEnvironmentRequestor that wraps the given + * SearchRequestor. The requestor will not accept types in the + * unitToSkip. + */ + public SearchableEnvironmentRequestor(ISearchRequestor requestor, + ICompilationUnit unitToSkip) { + fRequestor = requestor; + fUnitToSkip = unitToSkip; + } + + /** + * Do nothing, a SearchRequestor does not accept initializers so there is no + * need to forward this results. + * + * @see IJavaElementRequestor + */ + // public void acceptInitializer(IInitializer initializer) { + // + // } + /** + * @see IJavaElementRequestor + */ + public void acceptPackageFragment(IPackageFragment packageFragment) { + fRequestor + .acceptPackage(packageFragment.getElementName().toCharArray()); + } + + /** + * @see IJavaElementRequestor + */ + public void acceptType(IType type) { + try { + if (fUnitToSkip != null + && fUnitToSkip.equals(type.getCompilationUnit())) { + return; + } + if (type.isClass()) { + fRequestor.acceptClass(type.getPackageFragment() + .getElementName().toCharArray(), type.getElementName() + .toCharArray(), type.getFlags()); + } else { + fRequestor.acceptInterface(type.getPackageFragment() + .getElementName().toCharArray(), type.getElementName() + .toCharArray(), type.getFlags()); + } + } catch (JavaModelException npe) { } - } catch (JavaModelException npe) { } } -} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SetClasspathOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SetClasspathOperation.java index 0329e7e..4a5b35a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SetClasspathOperation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SetClasspathOperation.java @@ -38,38 +38,46 @@ import org.eclipse.core.runtime.Path; /** * This operation sets an IJavaProject's classpath. - * + * * @see IJavaProject */ public class SetClasspathOperation extends JavaModelOperation { IClasspathEntry[] oldResolvedPath, newResolvedPath; + IClasspathEntry[] newRawPath; + boolean canChangeResources; + boolean classpathWasSaved; + boolean needCycleCheck; + boolean needValidation; + boolean needSave; + IPath newOutputLocation; + JavaProject project; + boolean identicalRoots; - + public static final IClasspathEntry[] ReuseClasspath = new IClasspathEntry[0]; + public static final IClasspathEntry[] UpdateClasspath = new IClasspathEntry[0]; + // if reusing output location, then also reuse clean flag - public static final IPath ReuseOutputLocation = new Path("Reuse Existing Output Location"); //$NON-NLS-1$ - + public static final IPath ReuseOutputLocation = new Path( + "Reuse Existing Output Location"); //$NON-NLS-1$ + /** * When executed, this operation sets the classpath of the given project. */ - public SetClasspathOperation( - JavaProject project, - IClasspathEntry[] oldResolvedPath, - IClasspathEntry[] newRawPath, - IPath newOutputLocation, - boolean canChangeResource, - boolean needValidation, - boolean needSave) { + public SetClasspathOperation(JavaProject project, + IClasspathEntry[] oldResolvedPath, IClasspathEntry[] newRawPath, + IPath newOutputLocation, boolean canChangeResource, + boolean needValidation, boolean needSave) { super(new IJavaElement[] { project }); this.oldResolvedPath = oldResolvedPath; @@ -82,200 +90,221 @@ public class SetClasspathOperation extends JavaModelOperation { } /** - * Adds deltas for the given roots, with the specified change flag, - * and closes the root. Helper method for #setClasspath + * Adds deltas for the given roots, with the specified change flag, and + * closes the root. Helper method for #setClasspath */ - protected void addClasspathDeltas( - IPackageFragmentRoot[] roots, - int flag, - JavaElementDelta delta) { + protected void addClasspathDeltas(IPackageFragmentRoot[] roots, int flag, + JavaElementDelta delta) { for (int i = 0; i < roots.length; i++) { IPackageFragmentRoot root = roots[i]; delta.changed(root, flag); - if ((flag & IJavaElementDelta.F_REMOVED_FROM_CLASSPATH) != 0 + if ((flag & IJavaElementDelta.F_REMOVED_FROM_CLASSPATH) != 0 || (flag & IJavaElementDelta.F_SOURCEATTACHED) != 0 - || (flag & IJavaElementDelta.F_SOURCEDETACHED) != 0){ + || (flag & IJavaElementDelta.F_SOURCEDETACHED) != 0) { try { root.close(); } catch (JavaModelException e) { } - // force detach source on jar package fragment roots (source will be lazily computed when needed) - ((PackageFragmentRoot) root).setSourceAttachmentProperty(null);// loose info - will be recomputed + // force detach source on jar package fragment roots (source + // will be lazily computed when needed) + ((PackageFragmentRoot) root).setSourceAttachmentProperty(null);// loose + // info + // - + // will + // be + // recomputed } } } - - /** - * Returns the index of the item in the list if the given list contains the specified entry. If the list does - * not contain the entry, -1 is returned. + * Returns the index of the item in the list if the given list contains the + * specified entry. If the list does not contain the entry, -1 is returned. * A helper method for #setClasspath */ - protected int classpathContains( - IClasspathEntry[] list, - IClasspathEntry entry) { + protected int classpathContains(IClasspathEntry[] list, + IClasspathEntry entry) { IPath[] exclusionPatterns = entry.getExclusionPatterns(); nextEntry: for (int i = 0; i < list.length; i++) { IClasspathEntry other = list[i]; if (other.getContentKind() == entry.getContentKind() - && other.getEntryKind() == entry.getEntryKind() - && other.isExported() == entry.isExported() - && other.getPath().equals(entry.getPath())) { - // check custom outputs - IPath entryOutput = entry.getOutputLocation(); - IPath otherOutput = other.getOutputLocation(); - if (entryOutput == null) { - if (otherOutput != null) - continue; - } else { - if (!entryOutput.equals(otherOutput)) - continue; - } - - // check exclusion patterns - IPath[] otherExcludes = other.getExclusionPatterns(); - if (exclusionPatterns != otherExcludes) { - int excludeLength = exclusionPatterns.length; - if (otherExcludes.length != excludeLength) - continue; - for (int j = 0; j < excludeLength; j++) { - // compare toStrings instead of IPaths - // since IPath.equals is specified to ignore trailing separators - if (!exclusionPatterns[j].toString().equals(otherExcludes[j].toString())) - continue nextEntry; - } + && other.getEntryKind() == entry.getEntryKind() + && other.isExported() == entry.isExported() + && other.getPath().equals(entry.getPath())) { + // check custom outputs + IPath entryOutput = entry.getOutputLocation(); + IPath otherOutput = other.getOutputLocation(); + if (entryOutput == null) { + if (otherOutput != null) + continue; + } else { + if (!entryOutput.equals(otherOutput)) + continue; + } + + // check exclusion patterns + IPath[] otherExcludes = other.getExclusionPatterns(); + if (exclusionPatterns != otherExcludes) { + int excludeLength = exclusionPatterns.length; + if (otherExcludes.length != excludeLength) + continue; + for (int j = 0; j < excludeLength; j++) { + // compare toStrings instead of IPaths + // since IPath.equals is specified to ignore trailing + // separators + if (!exclusionPatterns[j].toString().equals( + otherExcludes[j].toString())) + continue nextEntry; } - return i; + } + return i; } } return -1; } /** - * Recursively adds all subfolders of folder to the given collection. + * Recursively adds all subfolders of folder to the given + * collection. */ - protected void collectAllSubfolders(IFolder folder, ArrayList collection) throws JavaModelException { + protected void collectAllSubfolders(IFolder folder, ArrayList collection) + throws JavaModelException { try { - IResource[] members= folder.members(); + IResource[] members = folder.members(); for (int i = 0, max = members.length; i < max; i++) { - IResource r= members[i]; + IResource r = members[i]; if (r.getType() == IResource.FOLDER) { collection.add(r); - collectAllSubfolders((IFolder)r, collection); + collectAllSubfolders((IFolder) r, collection); } - } + } } catch (CoreException e) { throw new JavaModelException(e); } } /** - * Returns a collection of package fragments that have been added/removed - * as the result of changing the output location to/from the given - * location. The collection is empty if no package fragments are - * affected. + * Returns a collection of package fragments that have been added/removed as + * the result of changing the output location to/from the given location. + * The collection is empty if no package fragments are affected. */ -// protected ArrayList determineAffectedPackageFragments(IPath location) throws JavaModelException { -// ArrayList fragments = new ArrayList(); -// JavaProject project =getProject(); -// -// // see if this will cause any package fragments to be affected -// IWorkspace workspace = ResourcesPlugin.getWorkspace(); -// IResource resource = null; -// if (location != null) { -// resource = workspace.getRoot().findMember(location); -// } -// if (resource != null && resource.getType() == IResource.FOLDER) { -// IFolder folder = (IFolder) resource; -// // only changes if it actually existed -// IClasspathEntry[] classpath = project.getExpandedClasspath(true); -// for (int i = 0; i < classpath.length; i++) { -// IClasspathEntry entry = classpath[i]; -// IPath path = classpath[i].getPath(); -// if (entry.getEntryKind() != IClasspathEntry.CPE_PROJECT && path.isPrefixOf(location) && !path.equals(location)) { -// IPackageFragmentRoot[] roots = project.computePackageFragmentRoots(classpath[i]); -// IPackageFragmentRoot root = roots[0]; -// // now the output location becomes a package fragment - along with any subfolders -// ArrayList folders = new ArrayList(); -// folders.add(folder); -// collectAllSubfolders(folder, folders); -// Iterator elements = folders.iterator(); -// int segments = path.segmentCount(); -// while (elements.hasNext()) { -// IFolder f = (IFolder) elements.next(); -// IPath relativePath = f.getFullPath().removeFirstSegments(segments); -// String name = relativePath.toOSString(); -// name = name.replace(File.pathSeparatorChar, '.'); -// if (name.endsWith(".")) { //$NON-NLS-1$ -// name = name.substring(0, name.length() - 1); -// } -// IPackageFragment pkg = root.getPackageFragment(name); -// fragments.add(pkg); -// } -// } -// } -// } -// return fragments; -// } + // protected ArrayList determineAffectedPackageFragments(IPath location) + // throws JavaModelException { + // ArrayList fragments = new ArrayList(); + // JavaProject project =getProject(); + // + // // see if this will cause any package fragments to be affected + // IWorkspace workspace = ResourcesPlugin.getWorkspace(); + // IResource resource = null; + // if (location != null) { + // resource = workspace.getRoot().findMember(location); + // } + // if (resource != null && resource.getType() == IResource.FOLDER) { + // IFolder folder = (IFolder) resource; + // // only changes if it actually existed + // IClasspathEntry[] classpath = project.getExpandedClasspath(true); + // for (int i = 0; i < classpath.length; i++) { + // IClasspathEntry entry = classpath[i]; + // IPath path = classpath[i].getPath(); + // if (entry.getEntryKind() != IClasspathEntry.CPE_PROJECT && + // path.isPrefixOf(location) && !path.equals(location)) { + // IPackageFragmentRoot[] roots = + // project.computePackageFragmentRoots(classpath[i]); + // IPackageFragmentRoot root = roots[0]; + // // now the output location becomes a package fragment - along with any + // subfolders + // ArrayList folders = new ArrayList(); + // folders.add(folder); + // collectAllSubfolders(folder, folders); + // Iterator elements = folders.iterator(); + // int segments = path.segmentCount(); + // while (elements.hasNext()) { + // IFolder f = (IFolder) elements.next(); + // IPath relativePath = f.getFullPath().removeFirstSegments(segments); + // String name = relativePath.toOSString(); + // name = name.replace(File.pathSeparatorChar, '.'); + // if (name.endsWith(".")) { //$NON-NLS-1$ + // name = name.substring(0, name.length() - 1); + // } + // IPackageFragment pkg = root.getPackageFragment(name); + // fragments.add(pkg); + // } + // } + // } + // } + // return fragments; + // } /** * Sets the classpath of the pre-specified project. */ protected void executeOperation() throws JavaModelException { - // project reference updated - may throw an exception if unable to write .project file + // project reference updated - may throw an exception if unable to write + // .project file updateProjectReferencesIfNecessary(); - // classpath file updated - may throw an exception if unable to write .classpath file + // classpath file updated - may throw an exception if unable to write + // .classpath file saveClasspathIfNecessary(); - - // perform classpath and output location updates, if exception occurs in classpath update, - // make sure the output location is updated before surfacing the exception (in case the output - // location update also throws an exception, give priority to the classpath update one). + + // perform classpath and output location updates, if exception occurs in + // classpath update, + // make sure the output location is updated before surfacing the + // exception (in case the output + // location update also throws an exception, give priority to the + // classpath update one). JavaModelException originalException = null; try { - if (this.newRawPath == UpdateClasspath) this.newRawPath = project.getRawClasspath(); - if (this.newRawPath != ReuseClasspath){ + if (this.newRawPath == UpdateClasspath) + this.newRawPath = project.getRawClasspath(); + if (this.newRawPath != ReuseClasspath) { updateClasspath(); project.updatePackageFragmentRoots(); - JavaModelManager.getJavaModelManager().getDeltaProcessor().addForRefresh(project); + JavaModelManager.getJavaModelManager().getDeltaProcessor() + .addForRefresh(project); } - } catch(JavaModelException e){ + } catch (JavaModelException e) { originalException = e; throw e; - } finally { // if traversed by an exception we still need to update the output location when necessary + } finally { // if traversed by an exception we still need to update the + // output location when necessary try { - if (this.newOutputLocation != ReuseOutputLocation) updateOutputLocation(); + if (this.newOutputLocation != ReuseOutputLocation) + updateOutputLocation(); - } catch(JavaModelException e){ - if (originalException != null) throw originalException; + } catch (JavaModelException e) { + if (originalException != null) + throw originalException; throw e; } finally { - // ensures the project is getting rebuilt if only variable is modified + // ensures the project is getting rebuilt if only variable is + // modified if (!this.identicalRoots && this.canChangeResources) { try { this.project.getProject().touch(this.progressMonitor); } catch (CoreException e) { - if (JavaModelManager.CP_RESOLVE_VERBOSE){ - Util.verbose("CPContainer INIT - FAILED to touch project: "+ this.project.getElementName(), System.err); //$NON-NLS-1$ + if (JavaModelManager.CP_RESOLVE_VERBOSE) { + Util + .verbose( + "CPContainer INIT - FAILED to touch project: " + this.project.getElementName(), System.err); //$NON-NLS-1$ e.printStackTrace(); } } - } + } } } done(); } - + /** - * Generates the delta of removed/added/reordered roots. - * Use three deltas in case the same root is removed/added/reordered (for - * instance, if it is changed from K_SOURCE to K_BINARY or vice versa) + * Generates the delta of removed/added/reordered roots. Use three deltas in + * case the same root is removed/added/reordered (for instance, if it is + * changed from K_SOURCE to K_BINARY or vice versa) */ protected void generateClasspathChangeDeltas() { @@ -289,8 +318,8 @@ public class SetClasspathOperation extends JavaModelOperation { } int oldLength = oldResolvedPath.length; int newLength = newResolvedPath.length; - -// final IndexManager indexManager = manager.getIndexManager(); + + // final IndexManager indexManager = manager.getIndexManager(); Map oldRoots = null; IPackageFragmentRoot[] roots = null; if (project.isOpen()) { @@ -300,9 +329,9 @@ public class SetClasspathOperation extends JavaModelOperation { // ignore } } else { - Map allRemovedRoots ; + Map allRemovedRoots; if ((allRemovedRoots = manager.getDeltaProcessor().removedRoots) != null) { - roots = (IPackageFragmentRoot[]) allRemovedRoots.get(project); + roots = (IPackageFragmentRoot[]) allRemovedRoots.get(project); } } if (roots != null) { @@ -313,20 +342,22 @@ public class SetClasspathOperation extends JavaModelOperation { } } for (int i = 0; i < oldLength; i++) { - + int index = classpathContains(newResolvedPath, oldResolvedPath[i]); if (index == -1) { // do not notify remote project changes - if (oldResolvedPath[i].getEntryKind() == IClasspathEntry.CPE_PROJECT){ + if (oldResolvedPath[i].getEntryKind() == IClasspathEntry.CPE_PROJECT) { needToUpdateDependents = true; this.needCycleCheck = true; - continue; + continue; } IPackageFragmentRoot[] pkgFragmentRoots = null; if (oldRoots != null) { - IPackageFragmentRoot oldRoot = (IPackageFragmentRoot) oldRoots.get(oldResolvedPath[i].getPath()); - if (oldRoot != null) { // use old root if any (could be none if entry wasn't bound) + IPackageFragmentRoot oldRoot = (IPackageFragmentRoot) oldRoots + .get(oldResolvedPath[i].getPath()); + if (oldRoot != null) { // use old root if any (could be + // none if entry wasn't bound) pkgFragmentRoots = new IPackageFragmentRoot[] { oldRoot }; } } @@ -335,108 +366,132 @@ public class SetClasspathOperation extends JavaModelOperation { ObjectVector accumulatedRoots = new ObjectVector(); HashSet rootIDs = new HashSet(5); rootIDs.add(project.rootID()); - project.computePackageFragmentRoots( - oldResolvedPath[i], - accumulatedRoots, - rootIDs, - true, // inside original project - false, // don't check existency - false); // don't retrieve exported roots - pkgFragmentRoots = new IPackageFragmentRoot[accumulatedRoots.size()]; + project.computePackageFragmentRoots(oldResolvedPath[i], + accumulatedRoots, rootIDs, true, // inside + // original + // project + false, // don't check existency + false); // don't retrieve exported roots + pkgFragmentRoots = new IPackageFragmentRoot[accumulatedRoots + .size()]; accumulatedRoots.copyInto(pkgFragmentRoots); } catch (JavaModelException e) { - pkgFragmentRoots = new IPackageFragmentRoot[] {}; + pkgFragmentRoots = new IPackageFragmentRoot[] {}; } } - addClasspathDeltas(pkgFragmentRoots, IJavaElementDelta.F_REMOVED_FROM_CLASSPATH, delta); - + addClasspathDeltas(pkgFragmentRoots, + IJavaElementDelta.F_REMOVED_FROM_CLASSPATH, delta); + int changeKind = oldResolvedPath[i].getEntryKind(); - needToUpdateDependents |= (changeKind == IClasspathEntry.CPE_SOURCE) || oldResolvedPath[i].isExported(); + needToUpdateDependents |= (changeKind == IClasspathEntry.CPE_SOURCE) + || oldResolvedPath[i].isExported(); // Remove the .java files from the index for a source folder - // For a lib folder or a .jar file, remove the corresponding index if not shared. -// if (indexManager != null) { -// IClasspathEntry oldEntry = oldResolvedPath[i]; -// final IPath path = oldEntry.getPath(); -// switch (changeKind) { -// case IClasspathEntry.CPE_SOURCE: -// final char[][] inclusionPatterns = null; //((ClasspathEntry)oldEntry).fullInclusionPatternChars(); -// final char[][] exclusionPatterns = ((ClasspathEntry)oldEntry).fullExclusionPatternChars(); -// postAction(new IPostAction() { -// public String getID() { -// return path.toString(); -// } -// public void run() /* throws JavaModelException */ { -// indexManager.removeSourceFolderFromIndex(project, path, inclusionPatterns, exclusionPatterns); -// } -// }, -// REMOVEALL_APPEND); -// break; -// case IClasspathEntry.CPE_LIBRARY: -// final DeltaProcessingState deltaState = manager.deltaState; -// postAction(new IPostAction() { -// public String getID() { -// return path.toString(); -// } -// public void run() /* throws JavaModelException */ { -// if (deltaState.otherRoots.get(path) == null) { // if root was not shared -// indexManager.discardJobs(path.toString()); -// indexManager.removeIndex(path); -// // TODO (kent) we could just remove the in-memory index and have the indexing check for timestamps -// } -// } -// }, -// REMOVEALL_APPEND); -// break; -// } -// } + // For a lib folder or a .jar file, remove the corresponding + // index if not shared. + // if (indexManager != null) { + // IClasspathEntry oldEntry = oldResolvedPath[i]; + // final IPath path = oldEntry.getPath(); + // switch (changeKind) { + // case IClasspathEntry.CPE_SOURCE: + // final char[][] inclusionPatterns = null; + // //((ClasspathEntry)oldEntry).fullInclusionPatternChars(); + // final char[][] exclusionPatterns = + // ((ClasspathEntry)oldEntry).fullExclusionPatternChars(); + // postAction(new IPostAction() { + // public String getID() { + // return path.toString(); + // } + // public void run() /* throws JavaModelException */ { + // indexManager.removeSourceFolderFromIndex(project, path, + // inclusionPatterns, exclusionPatterns); + // } + // }, + // REMOVEALL_APPEND); + // break; + // case IClasspathEntry.CPE_LIBRARY: + // final DeltaProcessingState deltaState = manager.deltaState; + // postAction(new IPostAction() { + // public String getID() { + // return path.toString(); + // } + // public void run() /* throws JavaModelException */ { + // if (deltaState.otherRoots.get(path) == null) { // if root was + // not shared + // indexManager.discardJobs(path.toString()); + // indexManager.removeIndex(path); + // // TODO (kent) we could just remove the in-memory index and + // have the indexing check for timestamps + // } + // } + // }, + // REMOVEALL_APPEND); + // break; + // } + // } hasDelta = true; } else { // do not notify remote project changes - if (oldResolvedPath[i].getEntryKind() == IClasspathEntry.CPE_PROJECT){ - this.needCycleCheck |= (oldResolvedPath[i].isExported() != newResolvedPath[index].isExported()); - continue; - } - needToUpdateDependents |= (oldResolvedPath[i].isExported() != newResolvedPath[index].isExported()); - if (index != i) { //reordering of the classpath - addClasspathDeltas( - project.computePackageFragmentRoots(oldResolvedPath[i]), - IJavaElementDelta.F_REORDER, - delta); - int changeKind = oldResolvedPath[i].getEntryKind(); - needToUpdateDependents |= (changeKind == IClasspathEntry.CPE_SOURCE); - - hasDelta = true; + if (oldResolvedPath[i].getEntryKind() == IClasspathEntry.CPE_PROJECT) { + this.needCycleCheck |= (oldResolvedPath[i].isExported() != newResolvedPath[index] + .isExported()); + continue; } - + needToUpdateDependents |= (oldResolvedPath[i].isExported() != newResolvedPath[index] + .isExported()); + if (index != i) { // reordering of the classpath + addClasspathDeltas(project + .computePackageFragmentRoots(oldResolvedPath[i]), + IJavaElementDelta.F_REORDER, delta); + int changeKind = oldResolvedPath[i].getEntryKind(); + needToUpdateDependents |= (changeKind == IClasspathEntry.CPE_SOURCE); + + hasDelta = true; + } + // check source attachment - IPath newSourcePath = newResolvedPath[index].getSourceAttachmentPath(); - int sourceAttachmentFlags = - this.getSourceAttachmentDeltaFlag( + IPath newSourcePath = newResolvedPath[index] + .getSourceAttachmentPath(); + int sourceAttachmentFlags = this.getSourceAttachmentDeltaFlag( oldResolvedPath[i].getSourceAttachmentPath(), newSourcePath); - IPath oldRootPath = oldResolvedPath[i].getSourceAttachmentRootPath(); - IPath newRootPath = newResolvedPath[index].getSourceAttachmentRootPath(); - int sourceAttachmentRootFlags = getSourceAttachmentDeltaFlag(oldRootPath, newRootPath); + IPath oldRootPath = oldResolvedPath[i] + .getSourceAttachmentRootPath(); + IPath newRootPath = newResolvedPath[index] + .getSourceAttachmentRootPath(); + int sourceAttachmentRootFlags = getSourceAttachmentDeltaFlag( + oldRootPath, newRootPath); int flags = sourceAttachmentFlags | sourceAttachmentRootFlags; if (flags != 0) { - addClasspathDeltas(project.computePackageFragmentRoots(oldResolvedPath[i]), flags, delta); + addClasspathDeltas(project + .computePackageFragmentRoots(oldResolvedPath[i]), + flags, delta); hasDelta = true; } else { if (oldRootPath == null && newRootPath == null) { - // if source path is specified and no root path, it needs to be recomputed dynamically - // force detach source on jar package fragment roots (source will be lazily computed when needed) - IPackageFragmentRoot[] computedRoots = project.computePackageFragmentRoots(oldResolvedPath[i]); + // if source path is specified and no root path, it + // needs to be recomputed dynamically + // force detach source on jar package fragment roots + // (source will be lazily computed when needed) + IPackageFragmentRoot[] computedRoots = project + .computePackageFragmentRoots(oldResolvedPath[i]); for (int j = 0; j < computedRoots.length; j++) { IPackageFragmentRoot root = computedRoots[j]; - // force detach source on jar package fragment roots (source will be lazily computed when needed) + // force detach source on jar package fragment roots + // (source will be lazily computed when needed) try { root.close(); } catch (JavaModelException e) { // ignore } - ((PackageFragmentRoot) root).setSourceAttachmentProperty(null);// loose info - will be recomputed + ((PackageFragmentRoot) root) + .setSourceAttachmentProperty(null);// loose + // info + // - + // will + // be + // recomputed } } } @@ -448,64 +503,69 @@ public class SetClasspathOperation extends JavaModelOperation { int index = classpathContains(oldResolvedPath, newResolvedPath[i]); if (index == -1) { // do not notify remote project changes - if (newResolvedPath[i].getEntryKind() == IClasspathEntry.CPE_PROJECT){ + if (newResolvedPath[i].getEntryKind() == IClasspathEntry.CPE_PROJECT) { needToUpdateDependents = true; this.needCycleCheck = true; - continue; + continue; } - addClasspathDeltas( - project.computePackageFragmentRoots(newResolvedPath[i]), - IJavaElementDelta.F_ADDED_TO_CLASSPATH, - delta); + addClasspathDeltas(project + .computePackageFragmentRoots(newResolvedPath[i]), + IJavaElementDelta.F_ADDED_TO_CLASSPATH, delta); int changeKind = newResolvedPath[i].getEntryKind(); - + // Request indexing -// if (indexManager != null) { -// switch (changeKind) { -// case IClasspathEntry.CPE_LIBRARY: -// boolean pathHasChanged = true; -// final IPath newPath = newResolvedPath[i].getPath(); -// for (int j = 0; j < oldLength; j++) { -// IClasspathEntry oldEntry = oldResolvedPath[j]; -// if (oldEntry.getPath().equals(newPath)) { -// pathHasChanged = false; -// break; -// } -// } -// if (pathHasChanged) { -// postAction(new IPostAction() { -// public String getID() { -// return newPath.toString(); -// } -// public void run() /* throws JavaModelException */ { -// indexManager.indexLibrary(newPath, project.getProject()); -// } -// }, -// REMOVEALL_APPEND); -// } -// break; -// case IClasspathEntry.CPE_SOURCE: -// IClasspathEntry entry = newResolvedPath[i]; -// final IPath path = entry.getPath(); -// final char[][] inclusionPatterns = null; //((ClasspathEntry)entry).fullInclusionPatternChars(); -// final char[][] exclusionPatterns = ((ClasspathEntry)entry).fullExclusionPatternChars(); -// postAction(new IPostAction() { -// public String getID() { -// return path.toString(); -// } -// public void run() /* throws JavaModelException */ { -// indexManager.indexSourceFolder(project, path, inclusionPatterns, exclusionPatterns); -// } -// }, -// APPEND); // append so that a removeSourceFolder action is not removed -// break; -// } -// } - - needToUpdateDependents |= (changeKind == IClasspathEntry.CPE_SOURCE) || newResolvedPath[i].isExported(); + // if (indexManager != null) { + // switch (changeKind) { + // case IClasspathEntry.CPE_LIBRARY: + // boolean pathHasChanged = true; + // final IPath newPath = newResolvedPath[i].getPath(); + // for (int j = 0; j < oldLength; j++) { + // IClasspathEntry oldEntry = oldResolvedPath[j]; + // if (oldEntry.getPath().equals(newPath)) { + // pathHasChanged = false; + // break; + // } + // } + // if (pathHasChanged) { + // postAction(new IPostAction() { + // public String getID() { + // return newPath.toString(); + // } + // public void run() /* throws JavaModelException */ { + // indexManager.indexLibrary(newPath, project.getProject()); + // } + // }, + // REMOVEALL_APPEND); + // } + // break; + // case IClasspathEntry.CPE_SOURCE: + // IClasspathEntry entry = newResolvedPath[i]; + // final IPath path = entry.getPath(); + // final char[][] inclusionPatterns = null; + // //((ClasspathEntry)entry).fullInclusionPatternChars(); + // final char[][] exclusionPatterns = + // ((ClasspathEntry)entry).fullExclusionPatternChars(); + // postAction(new IPostAction() { + // public String getID() { + // return path.toString(); + // } + // public void run() /* throws JavaModelException */ { + // indexManager.indexSourceFolder(project, path, + // inclusionPatterns, exclusionPatterns); + // } + // }, + // APPEND); // append so that a removeSourceFolder action is not + // removed + // break; + // } + // } + + needToUpdateDependents |= (changeKind == IClasspathEntry.CPE_SOURCE) + || newResolvedPath[i].isExported(); hasDelta = true; - } // classpath reordering has already been generated in previous loop + } // classpath reordering has already been generated in previous + // loop } if (hasDelta) { @@ -513,49 +573,57 @@ public class SetClasspathOperation extends JavaModelOperation { } else { this.identicalRoots = true; } - if (needToUpdateDependents){ + if (needToUpdateDependents) { updateAffectedProjects(project.getProject().getFullPath()); } } + protected void saveClasspathIfNecessary() throws JavaModelException { - - if (!this.canChangeResources || !this.needSave) return; - + + if (!this.canChangeResources || !this.needSave) + return; + IClasspathEntry[] classpathForSave; - if (this.newRawPath == ReuseClasspath || this.newRawPath == UpdateClasspath){ + if (this.newRawPath == ReuseClasspath + || this.newRawPath == UpdateClasspath) { classpathForSave = project.getRawClasspath(); } else { classpathForSave = this.newRawPath; } IPath outputLocationForSave; - if (this.newOutputLocation == ReuseOutputLocation){ + if (this.newOutputLocation == ReuseOutputLocation) { outputLocationForSave = project.getOutputLocation(); } else { outputLocationForSave = this.newOutputLocation; } - // if read-only .classpath, then the classpath setting will never been performed completely + // if read-only .classpath, then the classpath setting will never been + // performed completely if (project.saveClasspath(classpathForSave, outputLocationForSave)) { this.classpathWasSaved = true; - this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); + this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); } } + protected JavaProject getProject() { return ((JavaProject) getElementsToProcess()[0]); } /* - * Returns the source attachment flag for the delta between the 2 give source paths. - * Returns either F_SOURCEATTACHED, F_SOURCEDETACHED, F_SOURCEATTACHED | F_SOURCEDETACHED - * or 0 if there is no difference. + * Returns the source attachment flag for the delta between the 2 give + * source paths. Returns either F_SOURCEATTACHED, F_SOURCEDETACHED, + * F_SOURCEATTACHED | F_SOURCEDETACHED or 0 if there is no difference. */ - private int getSourceAttachmentDeltaFlag(IPath oldPath, IPath newPath, IPath sourcePath) { + private int getSourceAttachmentDeltaFlag(IPath oldPath, IPath newPath, + IPath sourcePath) { if (oldPath == null) { if (newPath != null) { return IJavaElementDelta.F_SOURCEATTACHED; } else { if (sourcePath != null) { - // if source path is specified and no root path, it needs to be recomputed dynamically - return IJavaElementDelta.F_SOURCEATTACHED | IJavaElementDelta.F_SOURCEDETACHED; + // if source path is specified and no root path, it needs to + // be recomputed dynamically + return IJavaElementDelta.F_SOURCEATTACHED + | IJavaElementDelta.F_SOURCEDETACHED; } else { return 0; } @@ -563,16 +631,17 @@ public class SetClasspathOperation extends JavaModelOperation { } else if (newPath == null) { return IJavaElementDelta.F_SOURCEDETACHED; } else if (!oldPath.equals(newPath)) { - return IJavaElementDelta.F_SOURCEATTACHED | IJavaElementDelta.F_SOURCEDETACHED; + return IJavaElementDelta.F_SOURCEATTACHED + | IJavaElementDelta.F_SOURCEDETACHED; } else { return 0; } } /* - * Returns the source attachment flag for the delta between the 2 give source paths. - * Returns either F_SOURCEATTACHED, F_SOURCEDETACHED, F_SOURCEATTACHED | F_SOURCEDETACHED - * or 0 if there is no difference. + * Returns the source attachment flag for the delta between the 2 give + * source paths. Returns either F_SOURCEATTACHED, F_SOURCEDETACHED, + * F_SOURCEATTACHED | F_SOURCEDETACHED or 0 if there is no difference. */ private int getSourceAttachmentDeltaFlag(IPath oldPath, IPath newPath) { if (oldPath == null) { @@ -584,59 +653,63 @@ public class SetClasspathOperation extends JavaModelOperation { } else if (newPath == null) { return IJavaElementDelta.F_SOURCEDETACHED; } else if (!oldPath.equals(newPath)) { - return IJavaElementDelta.F_SOURCEATTACHED | IJavaElementDelta.F_SOURCEDETACHED; + return IJavaElementDelta.F_SOURCEATTACHED + | IJavaElementDelta.F_SOURCEDETACHED; } else { return 0; } } - + /** - * Returns true if this operation performs no resource modifications, - * otherwise false. Subclasses must override. + * Returns true if this operation performs no resource + * modifications, otherwise false. Subclasses must override. */ public boolean isReadOnly() { return !this.canChangeResources; } -// protected void saveClasspathIfNecessary() throws JavaModelException { -// -// if (!this.canChangeResources || !this.needSave) return; -// -// IClasspathEntry[] classpathForSave; -// JavaProject project = getProject(); -// if (this.newRawPath == ReuseClasspath || this.newRawPath == UpdateClasspath){ -// classpathForSave = project.getRawClasspath(); -// } else { -// classpathForSave = this.newRawPath; -// } -// IPath outputLocationForSave; -// if (this.newOutputLocation == ReuseOutputLocation){ -// outputLocationForSave = project.getOutputLocation(); -// } else { -// outputLocationForSave = this.newOutputLocation; -// } -// // if read-only .classpath, then the classpath setting will never been performed completely -// if (project.saveClasspath(classpathForSave, outputLocationForSave)) { -// this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); -// } -// } - - public String toString(){ + // protected void saveClasspathIfNecessary() throws JavaModelException { + // + // if (!this.canChangeResources || !this.needSave) return; + // + // IClasspathEntry[] classpathForSave; + // JavaProject project = getProject(); + // if (this.newRawPath == ReuseClasspath || this.newRawPath == + // UpdateClasspath){ + // classpathForSave = project.getRawClasspath(); + // } else { + // classpathForSave = this.newRawPath; + // } + // IPath outputLocationForSave; + // if (this.newOutputLocation == ReuseOutputLocation){ + // outputLocationForSave = project.getOutputLocation(); + // } else { + // outputLocationForSave = this.newOutputLocation; + // } + // // if read-only .classpath, then the classpath setting will never been + // performed completely + // if (project.saveClasspath(classpathForSave, outputLocationForSave)) { + // this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); + // } + // } + + public String toString() { StringBuffer buffer = new StringBuffer(20); buffer.append("SetClasspathOperation\n"); //$NON-NLS-1$ buffer.append(" - classpath : "); //$NON-NLS-1$ - if (this.newRawPath == ReuseClasspath){ + if (this.newRawPath == ReuseClasspath) { buffer.append(""); //$NON-NLS-1$ } else { buffer.append("{"); //$NON-NLS-1$ for (int i = 0; i < this.newRawPath.length; i++) { - if (i > 0) buffer.append(","); //$NON-NLS-1$ + if (i > 0) + buffer.append(","); //$NON-NLS-1$ IClasspathEntry element = this.newRawPath[i]; buffer.append(" ").append(element.toString()); //$NON-NLS-1$ } } - buffer.append("\n - output location : "); //$NON-NLS-1$ - if (this.newOutputLocation == ReuseOutputLocation){ + buffer.append("\n - output location : "); //$NON-NLS-1$ + if (this.newOutputLocation == ReuseOutputLocation) { buffer.append(""); //$NON-NLS-1$ } else { buffer.append(this.newOutputLocation.toString()); //$NON-NLS-1$ @@ -644,85 +717,99 @@ public class SetClasspathOperation extends JavaModelOperation { return buffer.toString(); } -// private void updateClasspath() throws JavaModelException { -// -// JavaProject project = ((JavaProject) getElementsToProcess()[0]); -// -// beginTask(Util.bind("classpath.settingProgress", project.getElementName()), 2); //$NON-NLS-1$ -// -// // SIDE-EFFECT: from thereon, the classpath got modified -// project.setRawClasspath0(this.newRawPath); -// -// // resolve new path (asking for marker creation if problems) -// if (this.newResolvedPath == null) { -// this.newResolvedPath = project.getResolvedClasspath(true, this.canChangeResources); -// } -// -//// if (this.oldResolvedPath != null) { -//// generateClasspathChangeDeltas( -//// this.oldResolvedPath, -//// this.newResolvedPath, -//// project); -//// } else { -// this.needCycleCheck = true; -// updateAffectedProjects(project.getProject().getFullPath()); -//// } -// -// updateCycleMarkersIfNecessary(newResolvedPath); -// } + // private void updateClasspath() throws JavaModelException { + // + // JavaProject project = ((JavaProject) getElementsToProcess()[0]); + // + // beginTask(Util.bind("classpath.settingProgress", + // project.getElementName()), 2); //$NON-NLS-1$ + // + // // SIDE-EFFECT: from thereon, the classpath got modified + // project.setRawClasspath0(this.newRawPath); + // + // // resolve new path (asking for marker creation if problems) + // if (this.newResolvedPath == null) { + // this.newResolvedPath = project.getResolvedClasspath(true, + // this.canChangeResources); + // } + // + // // if (this.oldResolvedPath != null) { + // // generateClasspathChangeDeltas( + // // this.oldResolvedPath, + // // this.newResolvedPath, + // // project); + // // } else { + // this.needCycleCheck = true; + // updateAffectedProjects(project.getProject().getFullPath()); + // // } + // + // updateCycleMarkersIfNecessary(newResolvedPath); + // } private void updateClasspath() throws JavaModelException { - beginTask(Util.bind("classpath.settingProgress", project.getElementName()), 2); //$NON-NLS-1$ + beginTask(Util.bind( + "classpath.settingProgress", project.getElementName()), 2); //$NON-NLS-1$ // SIDE-EFFECT: from thereon, the classpath got modified project.getPerProjectInfo().updateClasspathInformation(this.newRawPath); // resolve new path (asking for marker creation if problems) if (this.newResolvedPath == null) { - this.newResolvedPath = project.getResolvedClasspath(true, this.canChangeResources, false/*don't returnResolutionInProgress*/); + this.newResolvedPath = project + .getResolvedClasspath(true, this.canChangeResources, false/* + * don't + * returnResolutionInProgress + */); } - + if (this.oldResolvedPath != null) { generateClasspathChangeDeltas(); } else { this.needCycleCheck = true; updateAffectedProjects(project.getProject().getFullPath()); } - + updateCycleMarkersIfNecessary(); } /** - * Update projects which are affected by this classpath change: - * those which refers to the current project as source + * Update projects which are affected by this classpath change: those which + * refers to the current project as source */ protected void updateAffectedProjects(IPath prerequisiteProjectPath) { try { - IJavaModel model = JavaModelManager.getJavaModelManager().getJavaModel(); + IJavaModel model = JavaModelManager.getJavaModelManager() + .getJavaModel(); IJavaProject originatingProject = getProject(); IJavaProject[] projects = model.getJavaProjects(); for (int i = 0, projectCount = projects.length; i < projectCount; i++) { try { JavaProject project = (JavaProject) projects[i]; - if (project.equals(originatingProject)) continue; // skip itself - - // consider ALL dependents (even indirect ones), since they may need to - // flush their respective namelookup caches (all pkg fragment roots). + if (project.equals(originatingProject)) + continue; // skip itself + + // consider ALL dependents (even indirect ones), since they + // may need to + // flush their respective namelookup caches (all pkg + // fragment roots). - IClasspathEntry[] classpath = project.getExpandedClasspath(true); + IClasspathEntry[] classpath = project + .getExpandedClasspath(true); for (int j = 0, entryCount = classpath.length; j < entryCount; j++) { IClasspathEntry entry = classpath[j]; if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT - && entry.getPath().equals(prerequisiteProjectPath)) { - project.setRawClasspath( - UpdateClasspath, - SetClasspathOperation.ReuseOutputLocation, - this.progressMonitor, - this.canChangeResources, - project.getResolvedClasspath(true), - false, // updating only - no validation - false); // updating only - no need to save + && entry.getPath().equals( + prerequisiteProjectPath)) { + project.setRawClasspath(UpdateClasspath, + SetClasspathOperation.ReuseOutputLocation, + this.progressMonitor, + this.canChangeResources, project + .getResolvedClasspath(true), false, // updating + // only + // - no + // validation + false); // updating only - no need to save break; } } @@ -731,7 +818,7 @@ public class SetClasspathOperation extends JavaModelOperation { } } catch (JavaModelException e) { } - + } /** @@ -739,149 +826,170 @@ public class SetClasspathOperation extends JavaModelOperation { */ protected void updateCycleMarkersIfNecessary() { - if (!this.needCycleCheck) return; - if (!this.canChangeResources) return; - - if (!project.hasCycleMarker() && !project.hasClasspathCycle(newResolvedPath)){ + if (!this.needCycleCheck) + return; + if (!this.canChangeResources) + return; + + if (!project.hasCycleMarker() + && !project.hasClasspathCycle(newResolvedPath)) { return; } - - postAction( - new IPostAction() { - public String getID() { - return "updateCycleMarkers"; //$NON-NLS-1$ - } - public void run() throws JavaModelException { - JavaProject.updateAllCycleMarkers(); - } - }, - REMOVEALL_APPEND); + + postAction(new IPostAction() { + public String getID() { + return "updateCycleMarkers"; //$NON-NLS-1$ + } + + public void run() throws JavaModelException { + JavaProject.updateAllCycleMarkers(); + } + }, REMOVEALL_APPEND); } -// /** -// * Update cycle markers -// */ -// protected void updateCycleMarkersIfNecessary(IClasspathEntry[] newResolvedPath) { -// -// if (!this.needCycleCheck) return; -// if (!this.canChangeResources) return; -// -// try { -// JavaProject project = getProject(); -// if (!project.hasCycleMarker() && !project.hasClasspathCycle(project.getResolvedClasspath(true))){ -// return; -// } -// -// postAction( -// new IPostAction() { -// public String getID() { -// return "updateCycleMarkers"; //$NON-NLS-1$ -// } -// public void run() throws JavaModelException { -// JavaProject.updateAllCycleMarkers(); -// } -// }, -// REMOVEALL_APPEND); -// } catch(JavaModelException e){ -// } -// } + + // /** + // * Update cycle markers + // */ + // protected void updateCycleMarkersIfNecessary(IClasspathEntry[] + // newResolvedPath) { + // + // if (!this.needCycleCheck) return; + // if (!this.canChangeResources) return; + // + // try { + // JavaProject project = getProject(); + // if (!project.hasCycleMarker() && + // !project.hasClasspathCycle(project.getResolvedClasspath(true))){ + // return; + // } + // + // postAction( + // new IPostAction() { + // public String getID() { + // return "updateCycleMarkers"; //$NON-NLS-1$ + // } + // public void run() throws JavaModelException { + // JavaProject.updateAllCycleMarkers(); + // } + // }, + // REMOVEALL_APPEND); + // } catch(JavaModelException e){ + // } + // } /** * Sets the output location of the pre-specified project. - * - *

                                                  This can cause changes in package fragments, in case either the - * old or new output location folder are considered as a package fragment. + * + *

                                                  + * This can cause changes in package fragments, in case either the old or + * new output location folder are considered as a package fragment. */ protected void updateOutputLocation() throws JavaModelException { - - JavaProject project= ((JavaProject) getElementsToProcess()[0]); - beginTask(Util.bind("classpath.settingOutputLocationProgress", project.getElementName()), 2); //$NON-NLS-1$ - - IPath oldLocation= project.getOutputLocation(); - + JavaProject project = ((JavaProject) getElementsToProcess()[0]); + + beginTask( + Util + .bind( + "classpath.settingOutputLocationProgress", project.getElementName()), 2); //$NON-NLS-1$ + + IPath oldLocation = project.getOutputLocation(); + // see if this will cause any package fragments to be added - boolean deltaToFire= false; + boolean deltaToFire = false; JavaElementDelta delta = newJavaElementDelta(); -// ArrayList added= determineAffectedPackageFragments(oldLocation); -// Iterator iter = added.iterator(); -// while (iter.hasNext()){ -// IPackageFragment frag= (IPackageFragment)iter.next(); -// ((IPackageFragmentRoot)frag.getParent()).close(); -// if (!ProjectPrefUtil.isExcluded(frag)) { -// delta.added(frag); -// deltaToFire = true; -// } -// } - + // ArrayList added= determineAffectedPackageFragments(oldLocation); + // Iterator iter = added.iterator(); + // while (iter.hasNext()){ + // IPackageFragment frag= (IPackageFragment)iter.next(); + // ((IPackageFragmentRoot)frag.getParent()).close(); + // if (!ProjectPrefUtil.isExcluded(frag)) { + // delta.added(frag); + // deltaToFire = true; + // } + // } + // see if this will cause any package fragments to be removed -// ArrayList removed= determineAffectedPackageFragments(this.newOutputLocation); -// iter = removed.iterator(); -// while (iter.hasNext()){ -// IPackageFragment frag= (IPackageFragment)iter.next(); -// ((IPackageFragmentRoot)frag.getParent()).close(); -// if (!ProjectPrefUtil.isExcluded(frag)) { -// delta.removed(frag); -// deltaToFire = true; -// } -// } - - JavaModelManager.PerProjectInfo perProjectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(project.getProject()); + // ArrayList removed= + // determineAffectedPackageFragments(this.newOutputLocation); + // iter = removed.iterator(); + // while (iter.hasNext()){ + // IPackageFragment frag= (IPackageFragment)iter.next(); + // ((IPackageFragmentRoot)frag.getParent()).close(); + // if (!ProjectPrefUtil.isExcluded(frag)) { + // delta.removed(frag); + // deltaToFire = true; + // } + // } + + JavaModelManager.PerProjectInfo perProjectInfo = JavaModelManager + .getJavaModelManager().getPerProjectInfoCheckExistence( + project.getProject()); synchronized (perProjectInfo) { perProjectInfo.outputLocation = this.newOutputLocation; } - + if (deltaToFire) { - addDelta(delta); + addDelta(delta); } worked(1); } - + /** - * Update projects references so that the build order is consistent with the classpath + * Update projects references so that the build order is consistent with the + * classpath */ - protected void updateProjectReferencesIfNecessary() throws JavaModelException { - - if (!this.canChangeResources) return; - if (this.newRawPath == ReuseClasspath || this.newRawPath == UpdateClasspath) return; - + protected void updateProjectReferencesIfNecessary() + throws JavaModelException { + + if (!this.canChangeResources) + return; + if (this.newRawPath == ReuseClasspath + || this.newRawPath == UpdateClasspath) + return; + JavaProject jproject = getProject(); - String[] oldRequired = jproject.projectPrerequisites(this.oldResolvedPath); + String[] oldRequired = jproject + .projectPrerequisites(this.oldResolvedPath); if (this.newResolvedPath == null) { - this.newResolvedPath = jproject.getResolvedClasspath(this.newRawPath, null, true, this.needValidation, null /*no reverse map*/); + this.newResolvedPath = jproject + .getResolvedClasspath(this.newRawPath, null, true, + this.needValidation, null /* no reverse map */); } - String[] newRequired = jproject.projectPrerequisites(this.newResolvedPath); - - try { + String[] newRequired = jproject + .projectPrerequisites(this.newResolvedPath); + + try { IProject project = jproject.getProject(); IProjectDescription description = project.getDescription(); - + IProject[] projectReferences = description.getReferencedProjects(); - + HashSet oldReferences = new HashSet(projectReferences.length); - for (int i = 0; i < projectReferences.length; i++){ + for (int i = 0; i < projectReferences.length; i++) { String projectName = projectReferences[i].getName(); oldReferences.add(projectName); } - HashSet newReferences = (HashSet)oldReferences.clone(); - - for (int i = 0; i < oldRequired.length; i++){ + HashSet newReferences = (HashSet) oldReferences.clone(); + + for (int i = 0; i < oldRequired.length; i++) { String projectName = oldRequired[i]; newReferences.remove(projectName); } - for (int i = 0; i < newRequired.length; i++){ + for (int i = 0; i < newRequired.length; i++) { String projectName = newRequired[i]; newReferences.add(projectName); } - + Iterator iter; int newSize = newReferences.size(); - + checkIdentity: { - if (oldReferences.size() == newSize){ + if (oldReferences.size() == newSize) { iter = newReferences.iterator(); - while (iter.hasNext()){ - if (!oldReferences.contains(iter.next())){ + while (iter.hasNext()) { + if (!oldReferences.contains(iter.next())) { break checkIdentity; } } @@ -891,21 +999,23 @@ public class SetClasspathOperation extends JavaModelOperation { String[] requiredProjectNames = new String[newSize]; int index = 0; iter = newReferences.iterator(); - while (iter.hasNext()){ - requiredProjectNames[index++] = (String)iter.next(); + while (iter.hasNext()) { + requiredProjectNames[index++] = (String) iter.next(); } - Util.sort(requiredProjectNames); // ensure that if changed, the order is consistent - + Util.sort(requiredProjectNames); // ensure that if changed, the + // order is consistent + IProject[] requiredProjectArray = new IProject[newSize]; IWorkspaceRoot wksRoot = project.getWorkspace().getRoot(); - for (int i = 0; i < newSize; i++){ - requiredProjectArray[i] = wksRoot.getProject(requiredProjectNames[i]); + for (int i = 0; i < newSize; i++) { + requiredProjectArray[i] = wksRoot + .getProject(requiredProjectNames[i]); } - + description.setReferencedProjects(requiredProjectArray); project.setDescription(description, this.progressMonitor); - - } catch(CoreException e){ + + } catch (CoreException e) { throw new JavaModelException(e); } } @@ -919,32 +1029,32 @@ public class SetClasspathOperation extends JavaModelOperation { if (needValidation) { IJavaProject project = (IJavaProject) getElementToProcess(); - // retrieve classpath + // retrieve classpath IClasspathEntry[] entries = this.newRawPath; - if (entries == ReuseClasspath){ + if (entries == ReuseClasspath) { try { - entries = project.getRawClasspath(); + entries = project.getRawClasspath(); } catch (JavaModelException e) { return e.getJavaModelStatus(); } - } + } // retrieve output location IPath outputLocation = this.newOutputLocation; - if (outputLocation == ReuseOutputLocation){ + if (outputLocation == ReuseOutputLocation) { try { outputLocation = project.getOutputLocation(); } catch (JavaModelException e) { return e.getJavaModelStatus(); } } - + // perform validation -// return JavaConventions.validateClasspath( -// project, -// entries, -// outputLocation); + // return JavaConventions.validateClasspath( + // project, + // entries, + // outputLocation); } - + return JavaModelStatus.VERIFIED_OK; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SimpleDelta.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SimpleDelta.java index 0fc058c..21b4dcb 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SimpleDelta.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SimpleDelta.java @@ -21,19 +21,19 @@ public class SimpleDelta { * @see IJavaElementDelta#getKind() */ protected int kind = 0; - + /* * @see IJavaElementDelta#getFlags() */ protected int changeFlags = 0; - + /* * Marks this delta as added */ public void added() { this.kind = IJavaElementDelta.ADDED; } - + /* * Marks this delta as changed with the given change flag */ @@ -41,14 +41,14 @@ public class SimpleDelta { this.kind = IJavaElementDelta.CHANGED; this.changeFlags |= flags; } - + /* * @see IJavaElementDelta#getFlags() */ public int getFlags() { return this.changeFlags; } - + /* * @see IJavaElementDelta#getKind() */ @@ -70,7 +70,7 @@ public class SimpleDelta { this.kind = IJavaElementDelta.REMOVED; this.changeFlags = 0; } - + /* * Mark this delta has a having a super type change */ @@ -81,18 +81,18 @@ public class SimpleDelta { protected void toDebugString(StringBuffer buffer) { buffer.append("["); //$NON-NLS-1$ switch (getKind()) { - case IJavaElementDelta.ADDED : - buffer.append('+'); - break; - case IJavaElementDelta.REMOVED : - buffer.append('-'); - break; - case IJavaElementDelta.CHANGED : - buffer.append('*'); - break; - default : - buffer.append('?'); - break; + case IJavaElementDelta.ADDED: + buffer.append('+'); + break; + case IJavaElementDelta.REMOVED: + buffer.append('-'); + break; + case IJavaElementDelta.CHANGED: + buffer.append('*'); + break; + default: + buffer.append('?'); + break; } buffer.append("]: {"); //$NON-NLS-1$ toDebugString(buffer, getFlags()); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SourceField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SourceField.java index 1854e1c..266d430 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SourceField.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SourceField.java @@ -20,69 +20,81 @@ import net.sourceforge.phpdt.core.jdom.IDOMNode; * @see IField */ -/* package */ class SourceField extends Member implements IField { +/* package */class SourceField extends Member implements IField { /** - * Constructs a handle to the field with the given name in the specified type. + * Constructs a handle to the field with the given name in the specified + * type. */ protected SourceField(JavaElement parent, String name) { super(parent, name); } + public boolean equals(Object o) { - if (!(o instanceof SourceField)) return false; + if (!(o instanceof SourceField)) + return false; return super.equals(o); } -/** - * @see JavaElement#equalsDOMNode - */ -protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException { - return (node.getNodeType() == IDOMNode.FIELD) && super.equalsDOMNode(node); -} -/** - * @see IField - */ -public Object getConstant() throws JavaModelException { - SourceFieldElementInfo info = (SourceFieldElementInfo) getElementInfo(); - return info.initializationSource; -} -/** - * @see IJavaElement - */ -public int getElementType() { - return FIELD; -} -/** - * @see JavaElement#getHandleMemento() - */ -protected char getHandleMementoDelimiter() { - return JavaElement.JEM_FIELD; -} -/** - * @see IField - */ -public String getTypeSignature() throws JavaModelException { -// SourceFieldElementInfo info = (SourceFieldElementInfo) getElementInfo(); -// return info.getTypeSignature(); - return ""; -} -/** - * @private Debugging purposes - */ -protected void toStringInfo(int tab, StringBuffer buffer, Object info) { - buffer.append(this.tabString(tab)); - if (info == null) { - buffer.append(getElementName()); - buffer.append(" (not open)"); //$NON-NLS-1$ - } else if (info == NO_INFO) { - buffer.append(getElementName()); - } else { - try { - buffer.append(Signature.toString(this.getTypeSignature())); - buffer.append(" "); //$NON-NLS-1$ - buffer.append(this.getElementName()); - } catch (JavaModelException e) { - buffer.append("null indicates no - * parameters. + * The parameter type signatures of the method - stored locally to perform + * equality test. null indicates no parameters. */ protected String[] fParameterTypes; /** * An empty list of Strings */ - protected static final String[] fgEmptyList= new String[] {}; - protected SourceMethod(JavaElement parent, String name, String[] parameterTypes) { + protected static final String[] fgEmptyList = new String[] {}; + + protected SourceMethod(JavaElement parent, String name, + String[] parameterTypes) { super(parent, name); Assert.isTrue(name.indexOf('.') == -1); if (parameterTypes == null) { - fParameterTypes= fgEmptyList; + fParameterTypes = fgEmptyList; } else { - fParameterTypes= parameterTypes; + fParameterTypes = parameterTypes; } } + public boolean equals(Object o) { - if (!(o instanceof SourceMethod)) return false; - return super.equals(o) && Util.equalArraysOrNull(fParameterTypes, ((SourceMethod)o).fParameterTypes); + if (!(o instanceof SourceMethod)) + return false; + return super.equals(o) + && Util.equalArraysOrNull(fParameterTypes, + ((SourceMethod) o).fParameterTypes); } -/** - * @see JavaElement#equalsDOMNode - */ -protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException { - if (node.getNodeType() == IDOMNode.METHOD) { - IDOMMethod m = (IDOMMethod)node; - if (isConstructor()) { - return - (m.isConstructor() || m.getName().equals(this.getElementName()) /* case of a constructor that is being renamed */) - && signatureEquals(m); + + /** + * @see JavaElement#equalsDOMNode + */ + protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException { + if (node.getNodeType() == IDOMNode.METHOD) { + IDOMMethod m = (IDOMMethod) node; + if (isConstructor()) { + return (m.isConstructor() || m.getName().equals( + this.getElementName()) /* + * case of a constructor that is + * being renamed + */) + && signatureEquals(m); + } else { + return super.equalsDOMNode(node) && signatureEquals(m); + } } else { - return super.equalsDOMNode(node) && signatureEquals(m); + return false; } - } else { - return false; + } -} -/** - * @see IJavaElement - */ -public int getElementType() { - return METHOD; -} -/** - * @see IMethod - */ -public String[] getExceptionTypes() throws JavaModelException { - SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo(); - char[][] exs= info.getExceptionTypeNames(); - return CompilationUnitStructureRequestor.convertTypeNamesToSigs(exs); -} -/** - * @see JavaElement#getHandleMemento() - */ -public String getHandleMemento() { - StringBuffer buff = new StringBuffer(((JavaElement) getParent()).getHandleMemento()); - buff.append(getHandleMementoDelimiter()); - buff.append(getElementName()); - for (int i = 0; i < fParameterTypes.length; i++) { - buff.append(getHandleMementoDelimiter()); - buff.append(fParameterTypes[i]); + /** + * @see IJavaElement + */ + public int getElementType() { + return METHOD; } - return buff.toString(); -} -/** - * @see JavaElement#getHandleMemento() - */ -protected char getHandleMementoDelimiter() { - return JavaElement.JEM_METHOD; -} -/** - * @see IMethod - */ -public int getNumberOfParameters() { - return fParameterTypes == null ? 0 : fParameterTypes.length; -} -/** - * @see IMethod - */ -public String[] getParameterNames() throws JavaModelException { - SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo(); - char[][] names= info.getArgumentNames(); - if (names == null || names.length == 0) { - return fgEmptyList; + + /** + * @see IMethod + */ + public String[] getExceptionTypes() throws JavaModelException { + SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo(); + char[][] exs = info.getExceptionTypeNames(); + return CompilationUnitStructureRequestor.convertTypeNamesToSigs(exs); } - String[] strings= new String[names.length]; - for (int i= 0; i < names.length; i++) { - strings[i]= new String(names[i]); + + /** + * @see JavaElement#getHandleMemento() + */ + public String getHandleMemento() { + StringBuffer buff = new StringBuffer(((JavaElement) getParent()) + .getHandleMemento()); + buff.append(getHandleMementoDelimiter()); + buff.append(getElementName()); + for (int i = 0; i < fParameterTypes.length; i++) { + buff.append(getHandleMementoDelimiter()); + buff.append(fParameterTypes[i]); + } + return buff.toString(); } - return strings; -} -/** - * @see IMethod - */ -public String[] getParameterTypes() { - return fParameterTypes; -} -/** - * @see IMethod - */ -public String getReturnType() throws JavaModelException { - SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo(); - return Signature.createTypeSignature(info.getReturnTypeName(), false); -} -/** - * @see IMethod - */ -public String getSignature() throws JavaModelException { - SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo(); - return info.getSignature(); -} -/** - * @see IMethod - */ -public boolean isConstructor() throws JavaModelException { - SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo(); - return info.isConstructor(); -} -/** - * @see IMethod#isMainMethod() - */ -public boolean isMainMethod() throws JavaModelException { - return this.isMainMethod(this); -} -/** - * @see IMethod#isSimilar(IMethod) - */ -public boolean isSimilar(IMethod method) { - return - this.areSimilarMethods( - this.getElementName(), this.getParameterTypes(), - method.getElementName(), method.getParameterTypes(), - null); -} + /** + * @see JavaElement#getHandleMemento() + */ + protected char getHandleMementoDelimiter() { + return JavaElement.JEM_METHOD; + } -/** - */ -public String readableName() { + /** + * @see IMethod + */ + public int getNumberOfParameters() { + return fParameterTypes == null ? 0 : fParameterTypes.length; + } - StringBuffer buffer = new StringBuffer(super.readableName()); - buffer.append('('); - String[] parameterTypes = this.getParameterTypes(); - int length; - if (parameterTypes != null && (length = parameterTypes.length) > 0) { - for (int i = 0; i < length; i++) { - buffer.append(Signature.toString(parameterTypes[i])); - if (i < length - 1) { - buffer.append(", "); //$NON-NLS-1$ - } + /** + * @see IMethod + */ + public String[] getParameterNames() throws JavaModelException { + SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo(); + char[][] names = info.getArgumentNames(); + if (names == null || names.length == 0) { + return fgEmptyList; } + String[] strings = new String[names.length]; + for (int i = 0; i < names.length; i++) { + strings[i] = new String(names[i]); + } + return strings; } - buffer.append(')'); - return buffer.toString(); -} -/** - * Returns true if the signature of this SourceMethod matches that of the given - * IDOMMethod, otherwise false. - */ -protected boolean signatureEquals(IDOMMethod method) throws JavaModelException { - String[] otherTypes= method.getParameterTypes(); - String[] types= getParameterTypes(); - boolean ok= true; - // ensure the number of parameters match - if (otherTypes == null || otherTypes.length == 0) { - ok= (types == null || types.length == 0); - } else if (types != null) { - ok= (otherTypes.length == types.length); - } else { - return false; + /** + * @see IMethod + */ + public String[] getParameterTypes() { + return fParameterTypes; + } + + /** + * @see IMethod + */ + public String getReturnType() throws JavaModelException { + SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo(); + return Signature.createTypeSignature(info.getReturnTypeName(), false); + } + + /** + * @see IMethod + */ + public String getSignature() throws JavaModelException { + SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo(); + return info.getSignature(); + } + + /** + * @see IMethod + */ + public boolean isConstructor() throws JavaModelException { + SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo(); + return info.isConstructor(); } - // ensure the parameter type signatures match - if (ok) { - if (types != null) { - int i; - for (i= 0; i < types.length; i++) { - String otherType= Signature.createTypeSignature(otherTypes[i].toCharArray(), false); - if (!types[i].equals(otherType)) { - ok= false; - break; + /** + * @see IMethod#isMainMethod() + */ + public boolean isMainMethod() throws JavaModelException { + return this.isMainMethod(this); + } + + /** + * @see IMethod#isSimilar(IMethod) + */ + public boolean isSimilar(IMethod method) { + return this.areSimilarMethods(this.getElementName(), this + .getParameterTypes(), method.getElementName(), method + .getParameterTypes(), null); + } + + /** + */ + public String readableName() { + + StringBuffer buffer = new StringBuffer(super.readableName()); + buffer.append('('); + String[] parameterTypes = this.getParameterTypes(); + int length; + if (parameterTypes != null && (length = parameterTypes.length) > 0) { + for (int i = 0; i < length; i++) { + buffer.append(Signature.toString(parameterTypes[i])); + if (i < length - 1) { + buffer.append(", "); //$NON-NLS-1$ } } } + buffer.append(')'); + return buffer.toString(); } - return ok; -} -/** - * @private Debugging purposes - */ -protected void toStringInfo(int tab, StringBuffer buffer, Object info) { - buffer.append(this.tabString(tab)); - if (info == null) { - buffer.append(getElementName()); - buffer.append(" (not open)"); //$NON-NLS-1$ - } else if (info == NO_INFO) { - buffer.append(getElementName()); - } else { - try { - if (Flags.isStatic(this.getFlags())) { - buffer.append("static "); //$NON-NLS-1$ - } - if (!this.isConstructor()) { - buffer.append(Signature.toString(this.getReturnType())); - buffer.append(' '); + /** + * Returns true if the signature of this + * SourceMethod matches that of the given + * IDOMMethod, otherwise false. + */ + protected boolean signatureEquals(IDOMMethod method) + throws JavaModelException { + String[] otherTypes = method.getParameterTypes(); + String[] types = getParameterTypes(); + boolean ok = true; + + // ensure the number of parameters match + if (otherTypes == null || otherTypes.length == 0) { + ok = (types == null || types.length == 0); + } else if (types != null) { + ok = (otherTypes.length == types.length); + } else { + return false; + } + + // ensure the parameter type signatures match + if (ok) { + if (types != null) { + int i; + for (i = 0; i < types.length; i++) { + String otherType = Signature.createTypeSignature( + otherTypes[i].toCharArray(), false); + if (!types[i].equals(otherType)) { + ok = false; + break; + } + } } - buffer.append(this.getElementName()); - buffer.append('('); - String[] parameterTypes = this.getParameterTypes(); - int length; - if (parameterTypes != null && (length = parameterTypes.length) > 0) { - for (int i = 0; i < length; i++) { - buffer.append(Signature.toString(parameterTypes[i])); - if (i < length - 1) { - buffer.append(", "); //$NON-NLS-1$ + } + + return ok; + } + + /** + * @private Debugging purposes + */ + protected void toStringInfo(int tab, StringBuffer buffer, Object info) { + buffer.append(this.tabString(tab)); + if (info == null) { + buffer.append(getElementName()); + buffer.append(" (not open)"); //$NON-NLS-1$ + } else if (info == NO_INFO) { + buffer.append(getElementName()); + } else { + try { + if (Flags.isStatic(this.getFlags())) { + buffer.append("static "); //$NON-NLS-1$ + } + if (!this.isConstructor()) { + buffer.append(Signature.toString(this.getReturnType())); + buffer.append(' '); + } + buffer.append(this.getElementName()); + buffer.append('('); + String[] parameterTypes = this.getParameterTypes(); + int length; + if (parameterTypes != null + && (length = parameterTypes.length) > 0) { + for (int i = 0; i < length; i++) { + buffer.append(Signature.toString(parameterTypes[i])); + if (i < length - 1) { + buffer.append(", "); //$NON-NLS-1$ + } } } + buffer.append(')'); + } catch (JavaModelException e) { + buffer + .append(" -1 && insertion < source.length()) { - // String encoding = project.getOption(JavaCore.CORE_ENCODING, true); - // - // char[] prefix = CharOperation.concat(source.substring(0, insertion).toCharArray(), new char[]{'{'}); - // char[] suffix = CharOperation.concat(new char[]{'}'}, source.substring(insertion).toCharArray()); - // char[] fakeSource = CharOperation.concat(prefix, snippet, suffix); - // - // BasicCompilationUnit cu = - // new BasicCompilationUnit( - // fakeSource, - // null, - // getElementName(), - // encoding); - // - // engine.complete(cu, prefix.length + position, prefix.length); - // } else { - // engine.complete(this, snippet, position, localVariableTypeNames, localVariableNames, localVariableModifiers, isStatic); - // } - //} - /** - * @see IType - */ - //public IField createField(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) throws - // JavaModelException { - // CreateFieldOperation op = new CreateFieldOperation(this, contents, force); - // if (sibling != null) { - // op.createBefore(sibling); - // } - // runOperation(op, monitor); - // return (IField) op.getResultElements()[0]; - //} - /** - * @see IType - */ - //public IInitializer createInitializer(String contents, IJavaElement sibling, IProgressMonitor monitor) throws - // JavaModelException { - // CreateInitializerOperation op = new CreateInitializerOperation(this, contents); - // if (sibling != null) { - // op.createBefore(sibling); - // } - // runOperation(op, monitor); - // return (IInitializer) op.getResultElements()[0]; - //} - /** - * @see IType - */ - //public IMethod createMethod(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) throws - // JavaModelException { - // CreateMethodOperation op = new CreateMethodOperation(this, contents, force); - // if (sibling != null) { - // op.createBefore(sibling); - // } - // runOperation(op, monitor); - // return (IMethod) op.getResultElements()[0]; - //} - /** - * @see IType - */ - //public IType createType(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) throws - // JavaModelException { - // CreateTypeOperation op = new CreateTypeOperation(this, contents, force); - // if (sibling != null) { - // op.createBefore(sibling); - // } - // runOperation(op, monitor); - // return (IType) op.getResultElements()[0]; - //} - /** - * @see JavaElement#equalsDOMNode - */ - protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException { - return (node.getNodeType() == IDOMNode.TYPE) && super.equalsDOMNode(node); - } - - /* - * @see IType - */ - public IMethod[] findMethods(IMethod method) { - try { - return this.findMethods(method, this.getMethods()); - } catch (JavaModelException e) { - // if type doesn't exist, no matching method can exist - return null; - } - } - - /** - * @see IMember - */ - public IType getDeclaringType() { - IJavaElement parent = getParent(); - while (parent != null) { - if (parent.getElementType() == IJavaElement.TYPE) { - return (IType) parent; - } else if (parent instanceof IMember) { - parent = parent.getParent(); - } else { - return null; - } - } - return null; - } - - /** - * @see IJavaElement - */ - public int getElementType() { - return TYPE; - } - - /** - * @see IType#getField - */ - public IField getField(String name) { - return new SourceField(this, name); - } - - /** - * @see IType - */ - public IField[] getFields() throws JavaModelException { - ArrayList list = getChildrenOfType(FIELD); - IField[] array = new IField[list.size()]; - list.toArray(array); - return array; - } - - /** - * @see IType#getFullyQualifiedName - */ - public String getFullyQualifiedName() { - return this.getFullyQualifiedName('$'); - } - - /** - * @see IType#getFullyQualifiedName(char) - */ - public String getFullyQualifiedName(char enclosingTypeSeparator) { - String packageName = getPackageFragment().getElementName(); - if (packageName.equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) { - return getTypeQualifiedName(enclosingTypeSeparator); - } - return packageName + '.' + getTypeQualifiedName(enclosingTypeSeparator); - } - - /** - * @see IType - */ - //public IInitializer getInitializer(int occurrenceCount) { - // return new Initializer(this, occurrenceCount); - //} - /** - * @see IType - */ - //public IInitializer[] getInitializers() throws JavaModelException { - // ArrayList list = getChildrenOfType(INITIALIZER); - // IInitializer[] array= new IInitializer[list.size()]; - // list.toArray(array); - // return array; - //} - /** - * @see IType#getMethod - */ - public IMethod getMethod(String name, String[] parameterTypeSignatures) { - return new SourceMethod(this, name, parameterTypeSignatures); - } - - /** - * @see IType - */ - public IMethod[] getMethods() throws JavaModelException { - ArrayList list = getChildrenOfType(METHOD); - IMethod[] array = new IMethod[list.size()]; - list.toArray(array); - return array; - } - - /** - * @see IType - */ - public IPackageFragment getPackageFragment() { - IJavaElement parentElement = this.parent; - while (parentElement != null) { - if (parentElement.getElementType() == IJavaElement.PACKAGE_FRAGMENT) { - return (IPackageFragment) parentElement; - } else { - parentElement = parentElement.getParent(); - } - } - Assert.isTrue(false); // should not happen - return null; - } - - /** - * @see IType - */ - public String getSuperclassName() throws JavaModelException { - SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo(); - char[] superclassName = info.getSuperclassName(); - if (superclassName == null) { - return null; - } - return new String(superclassName); - } - - /** - * @see IType - */ - public String[] getSuperInterfaceNames() throws JavaModelException { - SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo(); - char[][] names = info.getInterfaceNames(); - if (names == null) { - return fgEmptyList; - } - String[] strings = new String[names.length]; - for (int i = 0; i < names.length; i++) { - strings[i] = new String(names[i]); - } - return strings; - } - - /** - * @see IType - */ - public IType getType(String name) { - return new SourceType(this, name); - } - - /** - * @see IType#getTypeQualifiedName - */ - public String getTypeQualifiedName() { - return this.getTypeQualifiedName('$'); - } - - /** - * @see IType#getTypeQualifiedName(char) - */ - public String getTypeQualifiedName(char enclosingTypeSeparator) { - if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) { - return name; - } else { - return ((IType) parent).getTypeQualifiedName(enclosingTypeSeparator) + enclosingTypeSeparator + name; - } - } - - /** - * @see IType - */ - public IType[] getTypes() throws JavaModelException { - ArrayList list = getChildrenOfType(TYPE); - IType[] array = new IType[list.size()]; - list.toArray(array); - return array; - } - - /** - * @see IParent - */ - public boolean hasChildren() throws JavaModelException { - return getChildren().length > 0; - } - - /** - * @see IType#isAnonymous() - */ - public boolean isAnonymous() throws JavaModelException { - return false; // cannot create source handle onto anonymous types - } - - /** - * @see IType - */ - public boolean isClass() throws JavaModelException { - return !isInterface(); - } - - /** - * @see IType - */ - public boolean isInterface() throws JavaModelException { - Object obj = getElementInfo(); - if (obj instanceof SourceTypeElementInfo) { - SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo(); - return info.isInterface(); - } - return false; - } - - /** - * @see IType#isLocal() - */ - public boolean isLocal() throws JavaModelException { - return false; // cannot create source handle onto local types - } - - /** - * @see IType#isMember() - */ - public boolean isMember() throws JavaModelException { - return getDeclaringType() != null; - } - - /** - * @see IType - */ -// public ITypeHierarchy loadTypeHierachy(InputStream input, IProgressMonitor monitor) throws JavaModelException { -// return loadTypeHierachy(input, DefaultWorkingCopyOwner.PRIMARY, monitor); -// } - /** - * NOTE: This method is not part of the API has it is not clear clients would easily use it: they would need to - * first make sure all working copies for the given owner exist before calling it. This is especially har at startup - * time. - * In case clients want this API, here is how it should be specified: - *

                                                  - * Loads a previously saved ITypeHierarchy from an input stream. A type hierarchy can - * be stored using ITypeHierachy#store(OutputStream). A compilation unit of a - * loaded type has the given owner if such a working copy exists, otherwise the type's - * compilation unit is a primary compilation unit. - * - * Only hierarchies originally created by the following methods can be loaded: - *

                                                    - *
                                                  • IType#newSupertypeHierarchy(IProgressMonitor)
                                                  • - *
                                                  • IType#newSupertypeHierarchy(WorkingCopyOwner, IProgressMonitor)
                                                  • - *
                                                  • IType#newTypeHierarchy(IJavaProject, IProgressMonitor)
                                                  • - *
                                                  • IType#newTypeHierarchy(IJavaProject, WorkingCopyOwner, IProgressMonitor)
                                                  • - *
                                                  • IType#newTypeHierarchy(IProgressMonitor)
                                                  • - *
                                                  • IType#newTypeHierarchy(WorkingCopyOwner, IProgressMonitor)
                                                  • - * - * - * @param input stream where hierarchy will be read - * @param monitor the given progress monitor - * @return the stored hierarchy - * @exception JavaModelException if the hierarchy could not be restored, reasons include: - * - type is not the focus of the hierarchy or - * - unable to read the input stream (wrong format, IOException during reading, ...) - * @see ITypeHierarchy#store(java.io.OutputStream, IProgressMonitor) - * @since 3.0 - */ -// public ITypeHierarchy loadTypeHierachy(InputStream input, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaModelException { -// // TODO monitor should be passed to TypeHierarchy.load(...) -// return TypeHierarchy.load(this, input, owner); -// } - /** - * @see IType - */ -// public ITypeHierarchy newSupertypeHierarchy(IProgressMonitor monitor) throws JavaModelException { -// return this.newSupertypeHierarchy(DefaultWorkingCopyOwner.PRIMARY, monitor); -// } - /* - * @see IType#newSupertypeHierarchy(ICompilationUnit[], IProgressMonitor) - */ -// public ITypeHierarchy newSupertypeHierarchy( -// ICompilationUnit[] workingCopies, -// IProgressMonitor monitor) -// throws JavaModelException { -// -// CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, workingCopies, SearchEngine.createWorkspaceScope(), false); -// op.runOperation(monitor); -// return op.getResult(); -// } - /** - * @param workingCopies the working copies that take precedence over their original compilation units - * @param monitor the given progress monitor - * @return a type hierarchy for this type containing this type and all of its supertypes - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its corresponding resource. - * - * @see IType#newSupertypeHierarchy(IWorkingCopy[], IProgressMonitor) - * @deprecated - */ - public ITypeHierarchy newSupertypeHierarchy( - IWorkingCopy[] workingCopies, - IProgressMonitor monitor) - throws JavaModelException { - - ICompilationUnit[] copies; - if (workingCopies == null) { - copies = null; - } else { - int length = workingCopies.length; - System.arraycopy(workingCopies, 0, copies = new ICompilationUnit[length], 0, length); - } - return newSupertypeHierarchy(copies, monitor); - } - /** - * @see IType#newSupertypeHierarchy(WorkingCopyOwner, IProgressMonitor) - */ -// public ITypeHierarchy newSupertypeHierarchy( -// WorkingCopyOwner owner, -// IProgressMonitor monitor) -// throws JavaModelException { -// -// ICompilationUnit[] workingCopies = JavaModelManager.getJavaModelManager().getWorkingCopies(owner, true/*add primary working copies*/); -// CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, workingCopies, SearchEngine.createWorkspaceScope(), false); -// op.runOperation(monitor); -// return op.getResult(); -// } - /** - * @see IType - */ -// public ITypeHierarchy newTypeHierarchy(IJavaProject project, IProgressMonitor monitor) throws JavaModelException { -// return newTypeHierarchy(project, DefaultWorkingCopyOwner.PRIMARY, monitor); -// } - /** - * @see IType#newTypeHierarchy(IJavaProject, WorkingCopyOwner, IProgressMonitor) - */ -// public ITypeHierarchy newTypeHierarchy(IJavaProject project, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaModelException { -// if (project == null) { -// throw new IllegalArgumentException(Util.bind("hierarchy.nullProject")); //$NON-NLS-1$ -// } -// ICompilationUnit[] workingCopies = JavaModelManager.getJavaModelManager().getWorkingCopies(owner, true/*add primary working copies*/); -// ICompilationUnit[] projectWCs = null; -// if (workingCopies != null) { -// int length = workingCopies.length; -// projectWCs = new ICompilationUnit[length]; -// int index = 0; -// for (int i = 0; i < length; i++) { -// ICompilationUnit wc = workingCopies[i]; -// if (project.equals(wc.getJavaProject())) { -// projectWCs[index++] = wc; -// } -// } -// if (index != length) { -// System.arraycopy(projectWCs, 0, projectWCs = new ICompilationUnit[index], 0, index); -// } -// } -// CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation( -// this, -// projectWCs, -// project, -// true); -// op.runOperation(monitor); -// return op.getResult(); -// } - /** - * @see IType - */ -// public ITypeHierarchy newTypeHierarchy(IProgressMonitor monitor) throws JavaModelException { -// CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, null, SearchEngine.createWorkspaceScope(), true); -// op.runOperation(monitor); -// return op.getResult(); -// } - /* - * @see IType#newTypeHierarchy(ICompilationUnit[], IProgressMonitor) - */ -// public ITypeHierarchy newTypeHierarchy( -// ICompilationUnit[] workingCopies, -// IProgressMonitor monitor) -// throws JavaModelException { -// -// CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, workingCopies, SearchEngine.createWorkspaceScope(), true); -// op.runOperation(monitor); -// return op.getResult(); -// } - /** - * @see IType#newTypeHierarchy(IWorkingCopy[], IProgressMonitor) - * @deprecated - */ - public ITypeHierarchy newTypeHierarchy( - IWorkingCopy[] workingCopies, - IProgressMonitor monitor) - throws JavaModelException { - - ICompilationUnit[] copies; - if (workingCopies == null) { - copies = null; - } else { - int length = workingCopies.length; - System.arraycopy(workingCopies, 0, copies = new ICompilationUnit[length], 0, length); - } - return newTypeHierarchy(copies, monitor); - } - /** - * @see IType#newTypeHierarchy(WorkingCopyOwner, IProgressMonitor) - */ -// public ITypeHierarchy newTypeHierarchy( -// WorkingCopyOwner owner, -// IProgressMonitor monitor) -// throws JavaModelException { -// -// ICompilationUnit[] workingCopies = JavaModelManager.getJavaModelManager().getWorkingCopies(owner, true/*add primary working copies*/); -// CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, workingCopies, SearchEngine.createWorkspaceScope(), true); -// op.runOperation(monitor); -// return op.getResult(); -// } - - // public String[][] resolveType(String typeName) throws JavaModelException { - // ISourceType info = (ISourceType) this.getElementInfo(); - // ISearchableNameEnvironment environment = ((JavaProject)getJavaProject()).getSearchableNameEnvironment(); - // - // class TypeResolveRequestor implements ISelectionRequestor { - // String[][] answers = null; - // void acceptType(String[] answer){ - // if (answers == null) { - // answers = new String[][]{ answer }; - // } else { - // // grow - // int length = answers.length; - // System.arraycopy(answers, 0, answers = new String[length+1][], 0, length); - // answers[length] = answer; - // } - // } - // public void acceptClass(char[] packageName, char[] className, boolean needQualification) { - // acceptType(new String[] { new String(packageName), new String(className) }); - // } - // - // public void acceptInterface(char[] packageName, char[] interfaceName, boolean needQualification) { - // acceptType(new String[] { new String(packageName), new String(interfaceName) }); - // } - // - // public void acceptError(IProblem error) {} - // public void acceptField(char[] declaringTypePackageName, char[] declaringTypeName, char[] name) {} - // public void acceptMethod(char[] declaringTypePackageName, char[] declaringTypeName, char[] selector, char[][] - // parameterPackageNames, char[][] parameterTypeNames, boolean isConstructor) {} - // public void acceptPackage(char[] packageName){} - // - // } - // TypeResolveRequestor requestor = new TypeResolveRequestor(); - // SelectionEngine engine = - // new SelectionEngine(environment, requestor, this.getJavaProject().getOptions(true)); - // - // IType[] topLevelTypes = this.getCompilationUnit().getTypes(); - // int length = topLevelTypes.length; - // ISourceType[] topLevelInfos = new ISourceType[length]; - // for (int i = 0; i < length; i++) { - // topLevelInfos[i] = (ISourceType)((SourceType)topLevelTypes[i]).getElementInfo(); - // } - // - // engine.selectType(info, typeName.toCharArray(), topLevelInfos, false); - // return requestor.answers; - //} - /** - * @private Debugging purposes - */ - protected void toStringInfo(int tab, StringBuffer buffer, Object info) { - buffer.append(this.tabString(tab)); - if (info == null) { - buffer.append(this.getElementName()); - buffer.append(" (not open)"); //$NON-NLS-1$ - } else if (info == NO_INFO) { - buffer.append(getElementName()); - } else { - try { - if (this.isInterface()) { - buffer.append("interface "); //$NON-NLS-1$ - } else { - buffer.append("class "); //$NON-NLS-1$ - } - buffer.append(this.getElementName()); - } catch (JavaModelException e) { - buffer.append(" -1 && insertion < source.length()) { + // String encoding = project.getOption(JavaCore.CORE_ENCODING, true); + // + // char[] prefix = CharOperation.concat(source.substring(0, + // insertion).toCharArray(), new char[]{'{'}); + // char[] suffix = CharOperation.concat(new char[]{'}'}, + // source.substring(insertion).toCharArray()); + // char[] fakeSource = CharOperation.concat(prefix, snippet, suffix); + // + // BasicCompilationUnit cu = + // new BasicCompilationUnit( + // fakeSource, + // null, + // getElementName(), + // encoding); + // + // engine.complete(cu, prefix.length + position, prefix.length); + // } else { + // engine.complete(this, snippet, position, localVariableTypeNames, + // localVariableNames, localVariableModifiers, isStatic); + // } + // } + /** + * @see IType + */ + // public IField createField(String contents, IJavaElement sibling, boolean + // force, IProgressMonitor monitor) throws + // JavaModelException { + // CreateFieldOperation op = new CreateFieldOperation(this, contents, + // force); + // if (sibling != null) { + // op.createBefore(sibling); + // } + // runOperation(op, monitor); + // return (IField) op.getResultElements()[0]; + // } + /** + * @see IType + */ + // public IInitializer createInitializer(String contents, IJavaElement + // sibling, IProgressMonitor monitor) throws + // JavaModelException { + // CreateInitializerOperation op = new CreateInitializerOperation(this, + // contents); + // if (sibling != null) { + // op.createBefore(sibling); + // } + // runOperation(op, monitor); + // return (IInitializer) op.getResultElements()[0]; + // } + /** + * @see IType + */ + // public IMethod createMethod(String contents, IJavaElement sibling, + // boolean force, IProgressMonitor monitor) throws + // JavaModelException { + // CreateMethodOperation op = new CreateMethodOperation(this, contents, + // force); + // if (sibling != null) { + // op.createBefore(sibling); + // } + // runOperation(op, monitor); + // return (IMethod) op.getResultElements()[0]; + // } + /** + * @see IType + */ + // public IType createType(String contents, IJavaElement sibling, boolean + // force, IProgressMonitor monitor) throws + // JavaModelException { + // CreateTypeOperation op = new CreateTypeOperation(this, contents, force); + // if (sibling != null) { + // op.createBefore(sibling); + // } + // runOperation(op, monitor); + // return (IType) op.getResultElements()[0]; + // } + /** + * @see JavaElement#equalsDOMNode + */ + protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException { + return (node.getNodeType() == IDOMNode.TYPE) + && super.equalsDOMNode(node); + } + + /* + * @see IType + */ + public IMethod[] findMethods(IMethod method) { + try { + return this.findMethods(method, this.getMethods()); + } catch (JavaModelException e) { + // if type doesn't exist, no matching method can exist + return null; + } + } + + /** + * @see IMember + */ + public IType getDeclaringType() { + IJavaElement parent = getParent(); + while (parent != null) { + if (parent.getElementType() == IJavaElement.TYPE) { + return (IType) parent; + } else if (parent instanceof IMember) { + parent = parent.getParent(); + } else { + return null; + } + } + return null; + } + + /** + * @see IJavaElement + */ + public int getElementType() { + return TYPE; + } + + /** + * @see IType#getField + */ + public IField getField(String name) { + return new SourceField(this, name); + } + + /** + * @see IType + */ + public IField[] getFields() throws JavaModelException { + ArrayList list = getChildrenOfType(FIELD); + IField[] array = new IField[list.size()]; + list.toArray(array); + return array; + } + + /** + * @see IType#getFullyQualifiedName + */ + public String getFullyQualifiedName() { + return this.getFullyQualifiedName('$'); + } + + /** + * @see IType#getFullyQualifiedName(char) + */ + public String getFullyQualifiedName(char enclosingTypeSeparator) { + String packageName = getPackageFragment().getElementName(); + if (packageName.equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) { + return getTypeQualifiedName(enclosingTypeSeparator); + } + return packageName + '.' + getTypeQualifiedName(enclosingTypeSeparator); + } + + /** + * @see IType + */ + // public IInitializer getInitializer(int occurrenceCount) { + // return new Initializer(this, occurrenceCount); + // } + /** + * @see IType + */ + // public IInitializer[] getInitializers() throws JavaModelException { + // ArrayList list = getChildrenOfType(INITIALIZER); + // IInitializer[] array= new IInitializer[list.size()]; + // list.toArray(array); + // return array; + // } + /** + * @see IType#getMethod + */ + public IMethod getMethod(String name, String[] parameterTypeSignatures) { + return new SourceMethod(this, name, parameterTypeSignatures); + } + + /** + * @see IType + */ + public IMethod[] getMethods() throws JavaModelException { + ArrayList list = getChildrenOfType(METHOD); + IMethod[] array = new IMethod[list.size()]; + list.toArray(array); + return array; + } + + /** + * @see IType + */ + public IPackageFragment getPackageFragment() { + IJavaElement parentElement = this.parent; + while (parentElement != null) { + if (parentElement.getElementType() == IJavaElement.PACKAGE_FRAGMENT) { + return (IPackageFragment) parentElement; + } else { + parentElement = parentElement.getParent(); + } + } + Assert.isTrue(false); // should not happen + return null; + } + + /** + * @see IType + */ + public String getSuperclassName() throws JavaModelException { + SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo(); + char[] superclassName = info.getSuperclassName(); + if (superclassName == null) { + return null; + } + return new String(superclassName); + } + + /** + * @see IType + */ + public String[] getSuperInterfaceNames() throws JavaModelException { + SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo(); + char[][] names = info.getInterfaceNames(); + if (names == null) { + return fgEmptyList; + } + String[] strings = new String[names.length]; + for (int i = 0; i < names.length; i++) { + strings[i] = new String(names[i]); + } + return strings; + } + + /** + * @see IType + */ + public IType getType(String name) { + return new SourceType(this, name); + } + + /** + * @see IType#getTypeQualifiedName + */ + public String getTypeQualifiedName() { + return this.getTypeQualifiedName('$'); + } + + /** + * @see IType#getTypeQualifiedName(char) + */ + public String getTypeQualifiedName(char enclosingTypeSeparator) { + if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) { + return name; + } else { + return ((IType) parent) + .getTypeQualifiedName(enclosingTypeSeparator) + + enclosingTypeSeparator + name; + } + } + + /** + * @see IType + */ + public IType[] getTypes() throws JavaModelException { + ArrayList list = getChildrenOfType(TYPE); + IType[] array = new IType[list.size()]; + list.toArray(array); + return array; + } + + /** + * @see IParent + */ + public boolean hasChildren() throws JavaModelException { + return getChildren().length > 0; + } + + /** + * @see IType#isAnonymous() + */ + public boolean isAnonymous() throws JavaModelException { + return false; // cannot create source handle onto anonymous types + } + + /** + * @see IType + */ + public boolean isClass() throws JavaModelException { + return !isInterface(); + } + + /** + * @see IType + */ + public boolean isInterface() throws JavaModelException { + Object obj = getElementInfo(); + if (obj instanceof SourceTypeElementInfo) { + SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo(); + return info.isInterface(); + } + return false; + } + + /** + * @see IType#isLocal() + */ + public boolean isLocal() throws JavaModelException { + return false; // cannot create source handle onto local types + } + + /** + * @see IType#isMember() + */ + public boolean isMember() throws JavaModelException { + return getDeclaringType() != null; + } + + /** + * @see IType + */ + // public ITypeHierarchy loadTypeHierachy(InputStream input, + // IProgressMonitor monitor) throws JavaModelException { + // return loadTypeHierachy(input, DefaultWorkingCopyOwner.PRIMARY, monitor); + // } + /** + * NOTE: This method is not part of the API has it is not clear clients + * would easily use it: they would need to first make sure all working + * copies for the given owner exist before calling it. This is especially + * har at startup time. In case clients want this API, here is how it should + * be specified: + *

                                                    + * Loads a previously saved ITypeHierarchy from an input stream. A type + * hierarchy can be stored using ITypeHierachy#store(OutputStream). A + * compilation unit of a loaded type has the given owner if such a working + * copy exists, otherwise the type's compilation unit is a primary + * compilation unit. + * + * Only hierarchies originally created by the following methods can be + * loaded: + *

                                                      + *
                                                    • IType#newSupertypeHierarchy(IProgressMonitor)
                                                    • + *
                                                    • IType#newSupertypeHierarchy(WorkingCopyOwner, IProgressMonitor)
                                                    • + *
                                                    • IType#newTypeHierarchy(IJavaProject, IProgressMonitor)
                                                    • + *
                                                    • IType#newTypeHierarchy(IJavaProject, WorkingCopyOwner, + * IProgressMonitor)
                                                    • + *
                                                    • IType#newTypeHierarchy(IProgressMonitor)
                                                    • + *
                                                    • IType#newTypeHierarchy(WorkingCopyOwner, IProgressMonitor)
                                                    • + * + * + * @param input + * stream where hierarchy will be read + * @param monitor + * the given progress monitor + * @return the stored hierarchy + * @exception JavaModelException + * if the hierarchy could not be restored, reasons include: - + * type is not the focus of the hierarchy or - unable to read + * the input stream (wrong format, IOException during + * reading, ...) + * @see ITypeHierarchy#store(java.io.OutputStream, IProgressMonitor) + * @since 3.0 + */ + // public ITypeHierarchy loadTypeHierachy(InputStream input, + // WorkingCopyOwner owner, IProgressMonitor monitor) throws + // JavaModelException { + // // TODO monitor should be passed to TypeHierarchy.load(...) + // return TypeHierarchy.load(this, input, owner); + // } + /** + * @see IType + */ + // public ITypeHierarchy newSupertypeHierarchy(IProgressMonitor monitor) + // throws JavaModelException { + // return this.newSupertypeHierarchy(DefaultWorkingCopyOwner.PRIMARY, + // monitor); + // } + /* + * @see IType#newSupertypeHierarchy(ICompilationUnit[], IProgressMonitor) + */ + // public ITypeHierarchy newSupertypeHierarchy( + // ICompilationUnit[] workingCopies, + // IProgressMonitor monitor) + // throws JavaModelException { + // + // CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, + // workingCopies, SearchEngine.createWorkspaceScope(), false); + // op.runOperation(monitor); + // return op.getResult(); + // } + /** + * @param workingCopies + * the working copies that take precedence over their original + * compilation units + * @param monitor + * the given progress monitor + * @return a type hierarchy for this type containing this type and all of + * its supertypes + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its corresponding resource. + * + * @see IType#newSupertypeHierarchy(IWorkingCopy[], IProgressMonitor) + * @deprecated + */ + public ITypeHierarchy newSupertypeHierarchy(IWorkingCopy[] workingCopies, + IProgressMonitor monitor) throws JavaModelException { + + ICompilationUnit[] copies; + if (workingCopies == null) { + copies = null; + } else { + int length = workingCopies.length; + System.arraycopy(workingCopies, 0, + copies = new ICompilationUnit[length], 0, length); + } + return newSupertypeHierarchy(copies, monitor); + } + + /** + * @see IType#newSupertypeHierarchy(WorkingCopyOwner, IProgressMonitor) + */ + // public ITypeHierarchy newSupertypeHierarchy( + // WorkingCopyOwner owner, + // IProgressMonitor monitor) + // throws JavaModelException { + // + // ICompilationUnit[] workingCopies = + // JavaModelManager.getJavaModelManager().getWorkingCopies(owner, true/*add + // primary working copies*/); + // CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, + // workingCopies, SearchEngine.createWorkspaceScope(), false); + // op.runOperation(monitor); + // return op.getResult(); + // } + /** + * @see IType + */ + // public ITypeHierarchy newTypeHierarchy(IJavaProject project, + // IProgressMonitor monitor) throws JavaModelException { + // return newTypeHierarchy(project, DefaultWorkingCopyOwner.PRIMARY, + // monitor); + // } + /** + * @see IType#newTypeHierarchy(IJavaProject, WorkingCopyOwner, + * IProgressMonitor) + */ + // public ITypeHierarchy newTypeHierarchy(IJavaProject project, + // WorkingCopyOwner owner, IProgressMonitor monitor) throws + // JavaModelException { + // if (project == null) { + // throw new IllegalArgumentException(Util.bind("hierarchy.nullProject")); + // //$NON-NLS-1$ + // } + // ICompilationUnit[] workingCopies = + // JavaModelManager.getJavaModelManager().getWorkingCopies(owner, true/*add + // primary working copies*/); + // ICompilationUnit[] projectWCs = null; + // if (workingCopies != null) { + // int length = workingCopies.length; + // projectWCs = new ICompilationUnit[length]; + // int index = 0; + // for (int i = 0; i < length; i++) { + // ICompilationUnit wc = workingCopies[i]; + // if (project.equals(wc.getJavaProject())) { + // projectWCs[index++] = wc; + // } + // } + // if (index != length) { + // System.arraycopy(projectWCs, 0, projectWCs = new ICompilationUnit[index], + // 0, index); + // } + // } + // CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation( + // this, + // projectWCs, + // project, + // true); + // op.runOperation(monitor); + // return op.getResult(); + // } + /** + * @see IType + */ + // public ITypeHierarchy newTypeHierarchy(IProgressMonitor monitor) throws + // JavaModelException { + // CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, + // null, SearchEngine.createWorkspaceScope(), true); + // op.runOperation(monitor); + // return op.getResult(); + // } + /* + * @see IType#newTypeHierarchy(ICompilationUnit[], IProgressMonitor) + */ + // public ITypeHierarchy newTypeHierarchy( + // ICompilationUnit[] workingCopies, + // IProgressMonitor monitor) + // throws JavaModelException { + // + // CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, + // workingCopies, SearchEngine.createWorkspaceScope(), true); + // op.runOperation(monitor); + // return op.getResult(); + // } + /** + * @see IType#newTypeHierarchy(IWorkingCopy[], IProgressMonitor) + * @deprecated + */ + public ITypeHierarchy newTypeHierarchy(IWorkingCopy[] workingCopies, + IProgressMonitor monitor) throws JavaModelException { + + ICompilationUnit[] copies; + if (workingCopies == null) { + copies = null; + } else { + int length = workingCopies.length; + System.arraycopy(workingCopies, 0, + copies = new ICompilationUnit[length], 0, length); + } + return newTypeHierarchy(copies, monitor); + } + + /** + * @see IType#newTypeHierarchy(WorkingCopyOwner, IProgressMonitor) + */ + // public ITypeHierarchy newTypeHierarchy( + // WorkingCopyOwner owner, + // IProgressMonitor monitor) + // throws JavaModelException { + // + // ICompilationUnit[] workingCopies = + // JavaModelManager.getJavaModelManager().getWorkingCopies(owner, true/*add + // primary working copies*/); + // CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, + // workingCopies, SearchEngine.createWorkspaceScope(), true); + // op.runOperation(monitor); + // return op.getResult(); + // } + // public String[][] resolveType(String typeName) throws JavaModelException + // { + // ISourceType info = (ISourceType) this.getElementInfo(); + // ISearchableNameEnvironment environment = + // ((JavaProject)getJavaProject()).getSearchableNameEnvironment(); + // + // class TypeResolveRequestor implements ISelectionRequestor { + // String[][] answers = null; + // void acceptType(String[] answer){ + // if (answers == null) { + // answers = new String[][]{ answer }; + // } else { + // // grow + // int length = answers.length; + // System.arraycopy(answers, 0, answers = new String[length+1][], 0, + // length); + // answers[length] = answer; + // } + // } + // public void acceptClass(char[] packageName, char[] className, boolean + // needQualification) { + // acceptType(new String[] { new String(packageName), new String(className) + // }); + // } + // + // public void acceptInterface(char[] packageName, char[] interfaceName, + // boolean needQualification) { + // acceptType(new String[] { new String(packageName), new + // String(interfaceName) }); + // } + // + // public void acceptError(IProblem error) {} + // public void acceptField(char[] declaringTypePackageName, char[] + // declaringTypeName, char[] name) {} + // public void acceptMethod(char[] declaringTypePackageName, char[] + // declaringTypeName, char[] selector, char[][] + // parameterPackageNames, char[][] parameterTypeNames, boolean + // isConstructor) {} + // public void acceptPackage(char[] packageName){} + // + // } + // TypeResolveRequestor requestor = new TypeResolveRequestor(); + // SelectionEngine engine = + // new SelectionEngine(environment, requestor, + // this.getJavaProject().getOptions(true)); + // + // IType[] topLevelTypes = this.getCompilationUnit().getTypes(); + // int length = topLevelTypes.length; + // ISourceType[] topLevelInfos = new ISourceType[length]; + // for (int i = 0; i < length; i++) { + // topLevelInfos[i] = + // (ISourceType)((SourceType)topLevelTypes[i]).getElementInfo(); + // } + // + // engine.selectType(info, typeName.toCharArray(), topLevelInfos, false); + // return requestor.answers; + // } + /** + * @private Debugging purposes + */ + protected void toStringInfo(int tab, StringBuffer buffer, Object info) { + buffer.append(this.tabString(tab)); + if (info == null) { + buffer.append(this.getElementName()); + buffer.append(" (not open)"); //$NON-NLS-1$ + } else if (info == NO_INFO) { + buffer.append(getElementName()); + } else { + try { + if (this.isInterface()) { + buffer.append("interface "); //$NON-NLS-1$ + } else { + buffer.append("class "); //$NON-NLS-1$ + } + buffer.append(this.getElementName()); + } catch (JavaModelException e) { + buffer + .append("null
                                                      if this type is a top level type. + */ + public ISourceType getEnclosingType() { + IJavaElement parent = fHandle.getParent(); + if (parent != null && parent.getElementType() == IJavaElement.TYPE) { + try { + return (ISourceType) ((JavaElement) parent).getElementInfo(); + } catch (JavaModelException e) { + return null; + } + } else { + return null; + } + } + /** + * @see ISourceType + */ + public char[] getEnclosingTypeName() { + return fEnclosingTypeName; + } + /** + * @see ISourceType + */ + public ISourceField[] getFields() { + int length = fChildren.length; + if (length == 0) + return NO_FIELDS; + ISourceField[] fields = new ISourceField[length]; + int fieldIndex = 0; + for (int i = 0; i < length; i++) { + IJavaElement child = fChildren[i]; + if (child instanceof SourceField) { + try { + ISourceField field = (ISourceField) ((SourceField) child) + .getElementInfo(); + fields[fieldIndex++] = field; + } catch (JavaModelException e) { + } + } + } + if (fieldIndex == 0) + return NO_FIELDS; + System.arraycopy(fields, 0, fields = new ISourceField[fieldIndex], 0, + fieldIndex); + return fields; + } /** - * The imports in this type's compilation unit + * @see ISourceType */ - protected char[][] fImports= null; + public char[] getFileName() { + return fSourceFileName; + } /** - * Backpointer to my type handle - useful for translation - * from info to handle. + * Returns the handle for this type info */ - protected IType fHandle= null; - + public IType getHandle() { + return fHandle; + } + /** + * @see ISourceType + */ + public char[][] getImports() { + return fImports; + } + /** + * @see ISourceType + */ + public char[][] getInterfaceNames() { + return fSuperInterfaceNames; + } + /** + * @see ISourceType + */ + public ISourceType[] getMemberTypes() { + int length = fChildren.length; + if (length == 0) + return NO_TYPES; + ISourceType[] memberTypes = new ISourceType[length]; + int typeIndex = 0; + for (int i = 0; i < length; i++) { + IJavaElement child = fChildren[i]; + if (child instanceof SourceType) { + try { + ISourceType type = (ISourceType) ((SourceType) child) + .getElementInfo(); + memberTypes[typeIndex++] = type; + } catch (JavaModelException e) { + } + } + } + if (typeIndex == 0) + return NO_TYPES; + System.arraycopy(memberTypes, 0, + memberTypes = new ISourceType[typeIndex], 0, typeIndex); + return memberTypes; + } + /** + * @see ISourceType + */ + public ISourceMethod[] getMethods() { + int length = fChildren.length; + if (length == 0) + return NO_METHODS; + ISourceMethod[] methods = new ISourceMethod[length]; + int methodIndex = 0; + for (int i = 0; i < length; i++) { + IJavaElement child = fChildren[i]; + if (child instanceof SourceMethod) { + try { + ISourceMethod method = (ISourceMethod) ((SourceMethod) child) + .getElementInfo(); + methods[methodIndex++] = method; + } catch (JavaModelException e) { + } + } + } + if (methodIndex == 0) + return NO_METHODS; + System.arraycopy(methods, 0, methods = new ISourceMethod[methodIndex], + 0, methodIndex); + return methods; + } + /** + * @see ISourceType + */ + public char[] getPackageName() { + return fPackageName; + } + /** + * @see ISourceType + */ + public char[] getQualifiedName() { + return fQualifiedName; + } + /** + * @see ISourceType + */ + public char[] getSuperclassName() { + return fSuperclassName; + } -/** - * Adds the given import to this type's collection of imports - */ -protected void addImport(char[] i) { - if (fImports == null) { - fImports = new char[][] {i}; - } else { - char[][] copy = new char[fImports.length + 1][]; - System.arraycopy(fImports, 0, copy, 0, fImports.length); - copy[fImports.length] = i; - fImports = copy; + /** + * @see ISourceType + */ + public boolean isBinaryType() { + return false; } -} + /** + * @see ISourceType + */ + public boolean isClass() { + return (this.flags & IConstants.AccInterface) == 0; + } -/** - * Returns the ISourceType that is the enclosing type for this - * type, or null if this type is a top level type. - */ -public ISourceType getEnclosingType() { - IJavaElement parent= fHandle.getParent(); - if (parent != null && parent.getElementType() == IJavaElement.TYPE) { - try { - return (ISourceType)((JavaElement)parent).getElementInfo(); - } catch (JavaModelException e) { - return null; - } - } else { - return null; + /** + * @see ISourceType + */ + public boolean isInterface() { + return (this.flags & IConstants.AccInterface) != 0; } -} -/** - * @see ISourceType - */ -public char[] getEnclosingTypeName() { - return fEnclosingTypeName; -} -/** - * @see ISourceType - */ -public ISourceField[] getFields() { - int length = fChildren.length; - if (length == 0) return NO_FIELDS; - ISourceField[] fields = new ISourceField[length]; - int fieldIndex = 0; - for (int i = 0; i < length; i++) { - IJavaElement child = fChildren[i]; - if (child instanceof SourceField) { - try { - ISourceField field = (ISourceField)((SourceField)child).getElementInfo(); - fields[fieldIndex++] = field; - } catch (JavaModelException e) { - } - } + + /** + * Sets the (unqualified) name of the type that encloses this type. + */ + protected void setEnclosingTypeName(char[] enclosingTypeName) { + fEnclosingTypeName = enclosingTypeName; } - if (fieldIndex == 0) return NO_FIELDS; - System.arraycopy(fields, 0, fields = new ISourceField[fieldIndex], 0, fieldIndex); - return fields; -} -/** - * @see ISourceType - */ -public char[] getFileName() { - return fSourceFileName; -} -/** - * Returns the handle for this type info - */ -public IType getHandle() { - return fHandle; -} -/** - * @see ISourceType - */ -public char[][] getImports() { - return fImports; -} -/** - * @see ISourceType - */ -public char[][] getInterfaceNames() { - return fSuperInterfaceNames; -} -/** - * @see ISourceType - */ -public ISourceType[] getMemberTypes() { - int length = fChildren.length; - if (length == 0) return NO_TYPES; - ISourceType[] memberTypes = new ISourceType[length]; - int typeIndex = 0; - for (int i = 0; i < length; i++) { - IJavaElement child = fChildren[i]; - if (child instanceof SourceType) { - try { - ISourceType type = (ISourceType)((SourceType)child).getElementInfo(); - memberTypes[typeIndex++] = type; - } catch (JavaModelException e) { - } - } + + /** + * Sets the handle for this type info + */ + protected void setHandle(IType handle) { + fHandle = handle; } - if (typeIndex == 0) return NO_TYPES; - System.arraycopy(memberTypes, 0, memberTypes = new ISourceType[typeIndex], 0, typeIndex); - return memberTypes; -} -/** - * @see ISourceType - */ -public ISourceMethod[] getMethods() { - int length = fChildren.length; - if (length == 0) return NO_METHODS; - ISourceMethod[] methods = new ISourceMethod[length]; - int methodIndex = 0; - for (int i = 0; i < length; i++) { - IJavaElement child = fChildren[i]; - if (child instanceof SourceMethod) { - try { - ISourceMethod method = (ISourceMethod)((SourceMethod)child).getElementInfo(); - methods[methodIndex++] = method; - } catch (JavaModelException e) { - } - } + + /** + * Sets the name of the package this type is declared in. + */ + protected void setPackageName(char[] name) { + fPackageName = name; + } + + /** + * Sets this type's qualified name. + */ + protected void setQualifiedName(char[] name) { + fQualifiedName = name; + } + + /** + * Sets the name of the source file this type is declared in. + */ + protected void setSourceFileName(char[] name) { + fSourceFileName = name; + } + + /** + * Sets the (unqualified) name of this type's superclass + */ + protected void setSuperclassName(char[] superclassName) { + fSuperclassName = superclassName; + } + + /** + * Sets the (unqualified) names of the interfaces this type implements or + * extends + */ + protected void setSuperInterfaceNames(char[][] superInterfaceNames) { + fSuperInterfaceNames = superInterfaceNames; + } + + public String toString() { + return "Info for " + fHandle.toString(); //$NON-NLS-1$ } - if (methodIndex == 0) return NO_METHODS; - System.arraycopy(methods, 0, methods = new ISourceMethod[methodIndex], 0, methodIndex); - return methods; -} -/** - * @see ISourceType - */ -public char[] getPackageName() { - return fPackageName; -} -/** - * @see ISourceType - */ -public char[] getQualifiedName() { - return fQualifiedName; -} -/** - * @see ISourceType - */ -public char[] getSuperclassName() { - return fSuperclassName; -} -/** - * @see ISourceType - */ -public boolean isBinaryType() { - return false; -} -/** - * @see ISourceType - */ -public boolean isClass() { - return (this.flags & IConstants.AccInterface) == 0; -} -/** - * @see ISourceType - */ -public boolean isInterface() { - return (this.flags & IConstants.AccInterface) != 0; -} -/** - * Sets the (unqualified) name of the type that encloses this type. - */ -protected void setEnclosingTypeName(char[] enclosingTypeName) { - fEnclosingTypeName = enclosingTypeName; -} -/** - * Sets the handle for this type info - */ -protected void setHandle(IType handle) { - fHandle= handle; -} -/** - * Sets the name of the package this type is declared in. - */ -protected void setPackageName(char[] name) { - fPackageName= name; -} -/** - * Sets this type's qualified name. - */ -protected void setQualifiedName(char[] name) { - fQualifiedName= name; -} -/** - * Sets the name of the source file this type is declared in. - */ -protected void setSourceFileName(char[] name) { - fSourceFileName= name; -} -/** - * Sets the (unqualified) name of this type's superclass - */ -protected void setSuperclassName(char[] superclassName) { - fSuperclassName = superclassName; -} -/** - * Sets the (unqualified) names of the interfaces this type implements or extends - */ -protected void setSuperInterfaceNames(char[][] superInterfaceNames) { - fSuperInterfaceNames = superInterfaceNames; -} -public String toString() { - return "Info for " + fHandle.toString(); //$NON-NLS-1$ -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/TypeVector.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/TypeVector.java index 39ccea4..41f8863 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/TypeVector.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/TypeVector.java @@ -14,100 +14,121 @@ import net.sourceforge.phpdt.core.IType; public final class TypeVector { static int INITIAL_SIZE = 10; - + public int size; + int maxSize; + IType[] elements; - + public final static IType[] NoElements = new IType[0]; - -public TypeVector() { - maxSize = INITIAL_SIZE; - size = 0; - elements = new IType[maxSize]; -} -public TypeVector(IType[] types) { - this.size = types.length; - this.maxSize = this.size + 1; // when an element is added, it assumes that the length is > 0 - elements = new IType[this.maxSize]; - System.arraycopy(types, 0, elements, 0, this.size); -} -public TypeVector(IType type) { - this.maxSize = INITIAL_SIZE; - this.size = 1; - elements = new IType[this.maxSize]; - elements[0] = type; -} -public void add(IType newElement) { - if (size == maxSize) // knows that size starts <= maxSize - System.arraycopy(elements, 0, (elements = new IType[maxSize *= 2]), 0, size); - elements[size++] = newElement; -} -public void addAll(IType[] newElements) { - if (size + newElements.length >= maxSize) { - maxSize = size + newElements.length; // assume no more elements will be added - System.arraycopy(elements, 0, (elements = new IType[maxSize]), 0, size); + + public TypeVector() { + maxSize = INITIAL_SIZE; + size = 0; + elements = new IType[maxSize]; } - System.arraycopy(newElements, 0, elements, size, newElements.length); - size += newElements.length; -} -public boolean contains(IType element) { - for (int i = size; --i >= 0;) - if (element.equals(elements[i])) - return true; - return false; -} -public TypeVector copy() { - TypeVector clone = new TypeVector(); - int length = this.elements.length; - System.arraycopy(this.elements, 0, clone.elements = new IType[length], 0, length); - clone.size = this.size; - clone.maxSize = this.maxSize; - return clone; -} -public IType elementAt(int index) { - return elements[index]; -} -public IType[] elements() { - - // do not resize to 0 if empty since may add more elements later - if (this.size == 0) return NoElements; - - if (this.size < this.maxSize) { - maxSize = size; - System.arraycopy(this.elements, 0, (this.elements = new IType[maxSize]), 0, size); + + public TypeVector(IType[] types) { + this.size = types.length; + this.maxSize = this.size + 1; // when an element is added, it assumes + // that the length is > 0 + elements = new IType[this.maxSize]; + System.arraycopy(types, 0, elements, 0, this.size); } - return this.elements; -} -public IType find(IType element) { - for (int i = size; --i >= 0;) - if (element == elements[i]) - return elements[i]; - return null; -} -public IType remove(IType element) { - // assumes only one occurrence of the element exists - for (int i = size; --i >= 0;) - if (element == elements[i]) { - // shift the remaining elements down one spot - System.arraycopy(elements, i + 1, elements, i, --size - i); - elements[size] = null; - return element; + + public TypeVector(IType type) { + this.maxSize = INITIAL_SIZE; + this.size = 1; + elements = new IType[this.maxSize]; + elements[0] = type; + } + + public void add(IType newElement) { + if (size == maxSize) // knows that size starts <= maxSize + System.arraycopy(elements, 0, (elements = new IType[maxSize *= 2]), + 0, size); + elements[size++] = newElement; + } + + public void addAll(IType[] newElements) { + if (size + newElements.length >= maxSize) { + maxSize = size + newElements.length; // assume no more elements + // will be added + System.arraycopy(elements, 0, (elements = new IType[maxSize]), 0, + size); } - return null; -} -public void removeAll() { - for (int i = size; --i >= 0;) - elements[i] = null; - size = 0; -} -public String toString() { - StringBuffer buffer = new StringBuffer("["); //$NON-NLS-1$ - for (int i = 0; i < size; i++) { - buffer.append("\n"); //$NON-NLS-1$ - buffer.append(elements[i]); + System.arraycopy(newElements, 0, elements, size, newElements.length); + size += newElements.length; + } + + public boolean contains(IType element) { + for (int i = size; --i >= 0;) + if (element.equals(elements[i])) + return true; + return false; + } + + public TypeVector copy() { + TypeVector clone = new TypeVector(); + int length = this.elements.length; + System.arraycopy(this.elements, 0, clone.elements = new IType[length], + 0, length); + clone.size = this.size; + clone.maxSize = this.maxSize; + return clone; + } + + public IType elementAt(int index) { + return elements[index]; + } + + public IType[] elements() { + + // do not resize to 0 if empty since may add more elements later + if (this.size == 0) + return NoElements; + + if (this.size < this.maxSize) { + maxSize = size; + System.arraycopy(this.elements, 0, + (this.elements = new IType[maxSize]), 0, size); + } + return this.elements; + } + + public IType find(IType element) { + for (int i = size; --i >= 0;) + if (element == elements[i]) + return elements[i]; + return null; + } + + public IType remove(IType element) { + // assumes only one occurrence of the element exists + for (int i = size; --i >= 0;) + if (element == elements[i]) { + // shift the remaining elements down one spot + System.arraycopy(elements, i + 1, elements, i, --size - i); + elements[size] = null; + return element; + } + return null; + } + + public void removeAll() { + for (int i = size; --i >= 0;) + elements[i] = null; + size = 0; + } + + public String toString() { + StringBuffer buffer = new StringBuffer("["); //$NON-NLS-1$ + for (int i = 0; i < size; i++) { + buffer.append("\n"); //$NON-NLS-1$ + buffer.append(elements[i]); + } + buffer.append("\n]"); //$NON-NLS-1$ + return buffer.toString(); } - buffer.append("\n]"); //$NON-NLS-1$ - return buffer.toString(); -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/XMLWriter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/XMLWriter.java index cf2d3b0..a165e45 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/XMLWriter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/XMLWriter.java @@ -9,19 +9,22 @@ * IBM Corporation - initial API and implementation *******************************************************************************/ package net.sourceforge.phpdt.internal.core; + import java.io.PrintWriter; import java.io.Writer; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; + /** * @since 3.0 */ class XMLWriter extends PrintWriter { /* constants */ - private static final String XML_VERSION= ""; //$NON-NLS-1$ + private static final String XML_VERSION = ""; //$NON-NLS-1$ + private static void appendEscapedChar(StringBuffer buffer, char c) { - String replacement= getReplacement(c); + String replacement = getReplacement(c); if (replacement != null) { buffer.append('&'); buffer.append(replacement); @@ -30,51 +33,61 @@ class XMLWriter extends PrintWriter { buffer.append(c); } } + private static String getEscaped(String s) { - StringBuffer result= new StringBuffer(s.length() + 10); - for (int i= 0; i < s.length(); ++i) + StringBuffer result = new StringBuffer(s.length() + 10); + for (int i = 0; i < s.length(); ++i) appendEscapedChar(result, s.charAt(i)); return result.toString(); } + private static String getReplacement(char c) { - // Encode special XML characters into the equivalent character references. + // Encode special XML characters into the equivalent character + // references. // These five are defined by default for all XML documents. switch (c) { - case '<' : - return "lt"; //$NON-NLS-1$ - case '>' : - return "gt"; //$NON-NLS-1$ - case '"' : - return "quot"; //$NON-NLS-1$ - case '\'' : - return "apos"; //$NON-NLS-1$ - case '&' : - return "amp"; //$NON-NLS-1$ + case '<': + return "lt"; //$NON-NLS-1$ + case '>': + return "gt"; //$NON-NLS-1$ + case '"': + return "quot"; //$NON-NLS-1$ + case '\'': + return "apos"; //$NON-NLS-1$ + case '&': + return "amp"; //$NON-NLS-1$ } return null; } + private int tab; + public XMLWriter(Writer writer) { super(writer); - tab= 0; + tab = 0; println(XML_VERSION); } + public void endTag(String name, boolean insertTab) { tab--; printTag('/' + name, null, insertTab, true, false); } + private void printTabulation() { - for (int i= 0; i < tab; i++) + for (int i = 0; i < tab; i++) super.print('\t'); } - public void printTag(String name, HashMap parameters, boolean insertTab, boolean insertNewLine, boolean closeTag) { - StringBuffer sb= new StringBuffer(); + + public void printTag(String name, HashMap parameters, boolean insertTab, + boolean insertNewLine, boolean closeTag) { + StringBuffer sb = new StringBuffer(); sb.append("<"); //$NON-NLS-1$ sb.append(name); if (parameters != null) { - for (Enumeration en = Collections.enumeration(parameters.keySet()); en.hasMoreElements();) { + for (Enumeration en = Collections.enumeration(parameters.keySet()); en + .hasMoreElements();) { sb.append(" "); //$NON-NLS-1$ - String key= (String) en.nextElement(); + String key = (String) en.nextElement(); sb.append(key); sb.append("=\""); //$NON-NLS-1$ sb.append(getEscaped(String.valueOf(parameters.get(key)))); @@ -95,6 +108,7 @@ class XMLWriter extends PrintWriter { print(sb.toString()); } } + public void startTag(String name, boolean insertTab) { printTag(name, null, insertTab, true, false); tab++; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/AbortIncrementalBuildException.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/AbortIncrementalBuildException.java index 5b6a28e..7420960 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/AbortIncrementalBuildException.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/AbortIncrementalBuildException.java @@ -11,15 +11,15 @@ package net.sourceforge.phpdt.internal.core.builder; /** - * Exception thrown when an incremental builder cannot find a .class file. - * Its possible the type can no longer be found because it was renamed inside its existing - * source file. + * Exception thrown when an incremental builder cannot find a .class file. Its + * possible the type can no longer be found because it was renamed inside its + * existing source file. */ public class AbortIncrementalBuildException extends RuntimeException { -protected String qualifiedTypeName; + protected String qualifiedTypeName; -public AbortIncrementalBuildException(String qualifiedTypeName) { - this.qualifiedTypeName = qualifiedTypeName; -} + public AbortIncrementalBuildException(String qualifiedTypeName) { + this.qualifiedTypeName = qualifiedTypeName; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/AbstractImageBuilder.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/AbstractImageBuilder.java index e1858c7..cab6a3f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/AbstractImageBuilder.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/AbstractImageBuilder.java @@ -31,439 +31,522 @@ import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; /** - * The abstract superclass of Java builders. Provides the building and compilation mechanism in common with the batch and - * incremental builders. + * The abstract superclass of Java builders. Provides the building and + * compilation mechanism in common with the batch and incremental builders. */ public abstract class AbstractImageBuilder implements ICompilerRequestor { - protected PHPBuilder javaBuilder; - - protected State newState; - - // local copies - protected NameEnvironment nameEnvironment; - - protected ClasspathMultiDirectory[] sourceLocations; - - protected BuildNotifier notifier; - - protected String encoding; - - protected Compiler compiler; - - protected WorkQueue workQueue; - - protected ArrayList problemSourceFiles; - - protected boolean compiledAllAtOnce; - - private boolean inCompiler; - - public static int MAX_AT_ONCE = 1000; - - protected AbstractImageBuilder(PHPBuilder javaBuilder) { - this.javaBuilder = javaBuilder; - this.newState = new State(javaBuilder); - - // local copies - this.nameEnvironment = javaBuilder.nameEnvironment; - this.sourceLocations = this.nameEnvironment.sourceLocations; - this.notifier = javaBuilder.notifier; - - this.encoding = javaBuilder.javaProject.getOption(JavaCore.CORE_ENCODING, true); - this.compiler = newCompiler(); - this.workQueue = new WorkQueue(); - this.problemSourceFiles = new ArrayList(3); - } - - public void acceptResult(CompilationResult result) { - // In Batch mode, we write out the class files, hold onto the dependency info - // & additional types and report problems. - - // In Incremental mode, when writing out a class file we need to compare it - // against the previous file, remembering if structural changes occured. - // Before reporting the new problems, we need to update the problem count & - // remove the old problems. Plus delete additional class files that no longer exist. - - SourceFile compilationUnit = (SourceFile) result.getCompilationUnit(); // go directly back to the sourceFile - if (!workQueue.isCompiled(compilationUnit)) { - // try { - workQueue.finished(compilationUnit); - try { - updateProblemsFor(compilationUnit, result); // record compilation problems before potentially adding duplicate errors - updateTasksFor(compilationUnit, result); // record tasks - } catch (CoreException e) { - throw internalException(e); - } - - // String typeLocator = compilationUnit.typeLocator(); - // ClassFile[] classFiles = result.getClassFiles(); - // int length = classFiles.length; - // ArrayList duplicateTypeNames = null; - // ArrayList definedTypeNames = new ArrayList(length); - // for (int i = 0; i < length; i++) { - // ClassFile classFile = classFiles[i]; - // char[][] compoundName = classFile.getCompoundName(); - // char[] typeName = compoundName[compoundName.length - 1]; - // boolean isNestedType = CharOperation.contains('$', typeName); - // - // // Look for a possible collision, if one exists, report an error but do not write the class file - // if (isNestedType) { - // String qualifiedTypeName = new String(classFile.outerMostEnclosingClassFile().fileName()); - // if (newState.isDuplicateLocator(qualifiedTypeName, typeLocator)) - // continue; - // } else { - // String qualifiedTypeName = new String(classFile.fileName()); // the qualified type name "p1/p2/A" - // if (newState.isDuplicateLocator(qualifiedTypeName, typeLocator)) { - // if (duplicateTypeNames == null) - // duplicateTypeNames = new ArrayList(); - // duplicateTypeNames.add(compoundName); - // createErrorFor(compilationUnit.resource, ProjectPrefUtil.bind("build.duplicateClassFile", new String(typeName))); - // //$NON-NLS-1$ - // continue; - // } - // newState.recordLocatorForType(qualifiedTypeName, typeLocator); - // } - // definedTypeNames.add(writeClassFile(classFile, compilationUnit.sourceLocation.binaryFolder, !isNestedType)); - // } - - // finishedWith(typeLocator, result, compilationUnit.getMainTypeName(), definedTypeNames, duplicateTypeNames); - notifier.compiled(compilationUnit); - // } catch (CoreException e) { - // Util.log(e, "JavaBuilder handling CoreException"); //$NON-NLS-1$ - // createErrorFor(compilationUnit.resource, Util.bind("build.inconsistentClassFile")); //$NON-NLS-1$ - // } - } - } - - protected void cleanUp() { - this.nameEnvironment.cleanup(); - - this.javaBuilder = null; - this.nameEnvironment = null; - this.sourceLocations = null; - this.notifier = null; - this.compiler = null; - this.workQueue = null; - this.problemSourceFiles = null; - } - - /* - * Compile the given elements, adding more elements to the work queue if they are affected by the changes. - */ - protected void compile(SourceFile[] units) { - int toDo = units.length; - if (this.compiledAllAtOnce = toDo <= MAX_AT_ONCE) { - // do them all now - if (PHPBuilder.DEBUG) - for (int i = 0; i < toDo; i++) - System.out.println("About to compile " + units[i].typeLocator()); //$NON-NLS-1$ - compile(units, null); - } else { - int i = 0; - boolean compilingFirstGroup = true; - while (i < toDo) { - int doNow = toDo < MAX_AT_ONCE ? toDo : MAX_AT_ONCE; - int index = 0; - SourceFile[] toCompile = new SourceFile[doNow]; - while (i < toDo && index < doNow) { - // Although it needed compiling when this method was called, it may have - // already been compiled when it was referenced by another unit. - SourceFile unit = units[i++]; - if (compilingFirstGroup || workQueue.isWaiting(unit)) { - if (PHPBuilder.DEBUG) - System.out.println("About to compile " + unit.typeLocator()); //$NON-NLS-1$ - toCompile[index++] = unit; - } - } - if (index < doNow) - System.arraycopy(toCompile, 0, toCompile = new SourceFile[index], 0, index); - SourceFile[] additionalUnits = new SourceFile[toDo - i]; - System.arraycopy(units, i, additionalUnits, 0, additionalUnits.length); - compilingFirstGroup = false; - compile(toCompile, additionalUnits); - } - } - } - - void compile(SourceFile[] units, SourceFile[] additionalUnits) { - if (units.length == 0) - return; - notifier.aboutToCompile(units[0]); // just to change the message - - // extend additionalFilenames with all hierarchical problem types found during this entire build - if (!problemSourceFiles.isEmpty()) { - int toAdd = problemSourceFiles.size(); - int length = additionalUnits == null ? 0 : additionalUnits.length; - if (length == 0) - additionalUnits = new SourceFile[toAdd]; - else - System.arraycopy(additionalUnits, 0, additionalUnits = new SourceFile[length + toAdd], 0, length); - for (int i = 0; i < toAdd; i++) - additionalUnits[length + i] = (SourceFile) problemSourceFiles.get(i); - } - String[] initialTypeNames = new String[units.length]; - for (int i = 0, l = units.length; i < l; i++) - initialTypeNames[i] = units[i].initialTypeName; - nameEnvironment.setNames(initialTypeNames, additionalUnits); - notifier.checkCancel(); - try { - inCompiler = true; - compiler.compile(units); - } catch (AbortCompilation ignored) { - // ignore the AbortCompilcation coming from BuildNotifier.checkCancelWithinCompiler() - // the Compiler failed after the user has chose to cancel... likely due to an OutOfMemory error - } finally { - inCompiler = false; - } - // Check for cancel immediately after a compile, because the compiler may - // have been cancelled but without propagating the correct exception - notifier.checkCancel(); - } - - protected void createErrorFor(IResource resource, String message) { - try { - IMarker marker = resource.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); - int severity = IMarker.SEVERITY_ERROR; - if (message.equals(Util.bind("build.duplicateResource"))) //$NON-NLS-1$ - if (JavaCore.WARNING.equals(javaBuilder.javaProject.getOption(JavaCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE, true))) - severity = IMarker.SEVERITY_WARNING; - marker.setAttributes(new String[] { IMarker.MESSAGE, IMarker.SEVERITY, IMarker.CHAR_START, IMarker.CHAR_END }, new Object[] { - message, - new Integer(severity), - new Integer(0), - new Integer(1) }); - } catch (CoreException e) { - throw internalException(e); - } - } - - //protected void finishedWith(String sourceLocator, CompilationResult result, char[] mainTypeName) throws CoreException {//, - // ArrayList definedTypeNames, ArrayList duplicateTypeNames) throws CoreException { - // if (duplicateTypeNames == null) { - // newState.record(sourceLocator, result.qualifiedReferences, result.simpleNameReferences, mainTypeName, definedTypeNames); - // return; - // } - // - // char[][][] qualifiedRefs = result.qualifiedReferences; - // char[][] simpleRefs = result.simpleNameReferences; - // // for each duplicate type p1.p2.A, add the type name A (package was already added) - // next : for (int i = 0, l = duplicateTypeNames.size(); i < l; i++) { - // char[][] compoundName = (char[][]) duplicateTypeNames.get(i); - // char[] typeName = compoundName[compoundName.length - 1]; - // int sLength = simpleRefs.length; - // for (int j = 0; j < sLength; j++) - // if (CharOperation.equals(simpleRefs[j], typeName)) - // continue next; - // System.arraycopy(simpleRefs, 0, simpleRefs = new char[sLength + 1][], 0, sLength); - // simpleRefs[sLength] = typeName; - // } - // newState.record(sourceLocator, qualifiedRefs, simpleRefs, mainTypeName, definedTypeNames); - //} - - //protected IContainer createFolder(IPath packagePath, IContainer outputFolder) throws CoreException { - // if (packagePath.isEmpty()) return outputFolder; - // IFolder folder = outputFolder.getFolder(packagePath); - // if (!folder.exists()) { - // createFolder(packagePath.removeLastSegments(1), outputFolder); - // folder.create(true, true, null); - // folder.setDerived(true); - // } - // return folder; - //} - - protected RuntimeException internalException(CoreException t) { - ImageBuilderInternalException imageBuilderException = new ImageBuilderInternalException(t); - if (inCompiler) - return new AbortCompilation(true, imageBuilderException); - return imageBuilderException; - } - - protected Compiler newCompiler() { - // called once when the builder is initialized... can override if needed - return new Compiler(nameEnvironment, DefaultErrorHandlingPolicies.proceedWithAllProblems(), javaBuilder.javaProject - .getOptions(true), this, ProblemFactory.getProblemFactory(Locale.getDefault())); - } - - protected boolean isExcludedFromProject(IPath childPath) throws JavaModelException { - // answer whether the folder should be ignored when walking the project as a source folder - if (childPath.segmentCount() > 2) - return false; // is a subfolder of a package - - for (int j = 0, k = sourceLocations.length; j < k; j++) { - // if (childPath.equals(sourceLocations[j].binaryFolder.getFullPath())) return true; - if (childPath.equals(sourceLocations[j].sourceFolder.getFullPath())) - return true; - } - // skip default output folder which may not be used by any source folder - return false; //childPath.equals(javaBuilder.javaProject.getOutputLocation()); - } - - /** - * Creates a marker from each problem and adds it to the resource. The marker is as follows: - its type is T_PROBLEM - its plugin - * ID is the JavaBuilder's plugin ID - its message is the problem's message - its priority reflects the severity of the problem - - * its range is the problem's range - it has an extra attribute "ID" which holds the problem's id - */ - protected void storeProblemsFor(SourceFile sourceFile, IProblem[] problems) throws CoreException { - if (sourceFile == null || problems == null || problems.length == 0) - return; - - // String missingClassFile = null; - IResource resource = sourceFile.resource; - for (int i = 0, l = problems.length; i < l; i++) { - IProblem problem = problems[i]; - int id = problem.getID(); - switch (id) { - case IProblem.IsClassPathCorrect: - // PHPBuilder.removeProblemsAndTasksFor(javaBuilder.currentProject); // make this the only problem for this project - // String[] args = problem.getArguments(); - // missingClassFile = args[0]; - break; - case IProblem.SuperclassMustBeAClass: - case IProblem.SuperInterfaceMustBeAnInterface: - case IProblem.HierarchyCircularitySelfReference: - case IProblem.HierarchyCircularity: - case IProblem.HierarchyHasProblems: - case IProblem.SuperclassNotFound: - case IProblem.SuperclassNotVisible: - case IProblem.SuperclassAmbiguous: - case IProblem.SuperclassInternalNameProvided: - case IProblem.SuperclassInheritedNameHidesEnclosingName: - case IProblem.InterfaceNotFound: - case IProblem.InterfaceNotVisible: - case IProblem.InterfaceAmbiguous: - case IProblem.InterfaceInternalNameProvided: - case IProblem.InterfaceInheritedNameHidesEnclosingName: - // ensure that this file is always retrieved from source for the rest of the build - if (!problemSourceFiles.contains(sourceFile)) - problemSourceFiles.add(sourceFile); - break; - } - - if (id != IProblem.Task) { - IMarker marker = resource.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); - marker.setAttributes(new String[] { - IMarker.MESSAGE, - IMarker.SEVERITY, - IJavaModelMarker.ID, - IMarker.CHAR_START, - IMarker.CHAR_END, - IMarker.LINE_NUMBER, - IJavaModelMarker.ARGUMENTS }, new Object[] { - problem.getMessage(), - new Integer(problem.isError() ? IMarker.SEVERITY_ERROR : IMarker.SEVERITY_WARNING), - new Integer(id), - new Integer(problem.getSourceStart()), - new Integer(problem.getSourceEnd() + 1), - new Integer(problem.getSourceLineNumber()), - Util.getProblemArgumentsForMarker(problem.getArguments()) }); - } - - /* - * Do NOT want to populate the Java Model just to find the matching Java element. Also cannot query compilation units located - * in folders with invalid package names such as 'a/b.c.d/e'. // compute a user-friendly location IJavaElement element = - * JavaCore.create(resource); if (element instanceof net.sourceforge.phpdt.core.ICompilationUnit) { // try to find a finer - * grain element net.sourceforge.phpdt.core.ICompilationUnit unit = (net.sourceforge.phpdt.core.ICompilationUnit) element; - * IJavaElement fragment = unit.getElementAt(problem.getSourceStart()); if (fragment != null) element = fragment; } String - * location = null; if (element instanceof JavaElement) location = ((JavaElement) element).readableName(); if (location != - * null) marker.setAttribute(IMarker.LOCATION, location); - */ - - // if (missingClassFile != null) - // throw new MissingClassFileException(missingClassFile); - } - } - - protected void storeTasksFor(SourceFile sourceFile, IProblem[] tasks) throws CoreException { - if (sourceFile == null || tasks == null || tasks.length == 0) - return; - - IResource resource = sourceFile.resource; - for (int i = 0, l = tasks.length; i < l; i++) { - IProblem task = tasks[i]; - if (task.getID() == IProblem.Task) { - IMarker marker = resource.createMarker(IJavaModelMarker.TASK_MARKER); - int priority = IMarker.PRIORITY_NORMAL; - String compilerPriority = task.getArguments()[2]; - if (JavaCore.COMPILER_TASK_PRIORITY_HIGH.equals(compilerPriority)) - priority = IMarker.PRIORITY_HIGH; - else if (JavaCore.COMPILER_TASK_PRIORITY_LOW.equals(compilerPriority)) - priority = IMarker.PRIORITY_LOW; - marker.setAttributes(new String[] { - IMarker.MESSAGE, - IMarker.PRIORITY, - IMarker.DONE, - IMarker.CHAR_START, - IMarker.CHAR_END, - IMarker.LINE_NUMBER, - IMarker.USER_EDITABLE, }, new Object[] { - task.getMessage(), - new Integer(priority), - new Boolean(false), - new Integer(task.getSourceStart()), - new Integer(task.getSourceEnd() + 1), - new Integer(task.getSourceLineNumber()), - new Boolean(false), }); - } - } - } - - protected void updateProblemsFor(SourceFile sourceFile, CompilationResult result) throws CoreException { - IProblem[] problems = result.getProblems(); - if (problems == null || problems.length == 0) - return; - //axelcl start insert - calculate line numbers - if (problems != null) { - for (int i = 0; i < problems.length; i++) { - if (problems[i].getSourceLineNumber() == 1) { - problems[i].setSourceLineNumber(ProblemHandler.searchLineNumber(result.lineSeparatorPositions, problems[i] - .getSourceStart())); - } - } - } - //axelcl end insert - notifier.updateProblemCounts(problems); - storeProblemsFor(sourceFile, problems); - } - - protected void updateTasksFor(SourceFile sourceFile, CompilationResult result) throws CoreException { - IProblem[] tasks = result.getTasks(); - if (tasks == null || tasks.length == 0) - return; - - storeTasksFor(sourceFile, tasks); - } - - //protected char[] writeClassFile(ClassFile classFile, IContainer outputFolder, boolean isSecondaryType) throws CoreException { - // String fileName = new String(classFile.fileName()); // the qualified type name "p1/p2/A" - // IPath filePath = new Path(fileName); - // IContainer container = outputFolder; - // if (filePath.segmentCount() > 1) { - // container = createFolder(filePath.removeLastSegments(1), outputFolder); - // filePath = new Path(filePath.lastSegment()); - // } - // - // IFile file = container.getFile(filePath.addFileExtension(JavaBuilder.CLASS_EXTENSION)); - // writeClassFileBytes(classFile.getBytes(), file, fileName, isSecondaryType); - // // answer the name of the class file as in Y or Y$M - // return filePath.lastSegment().toCharArray(); - //} - // - //protected void writeClassFileBytes(byte[] bytes, IFile file, String qualifiedFileName, boolean isSecondaryType) throws - // CoreException { - // if (file.exists()) { - // // Deal with shared output folders... last one wins... no collision cases detected - // if (JavaBuilder.DEBUG) - // System.out.println("Writing changed class file " + file.getName());//$NON-NLS-1$ - // file.setContents(new ByteArrayInputStream(bytes), true, false, null); - // if (!file.isDerived()) - // file.setDerived(true); - // } else { - // // Default implementation just writes out the bytes for the new class file... - // if (JavaBuilder.DEBUG) - // System.out.println("Writing new class file " + file.getName());//$NON-NLS-1$ - // file.create(new ByteArrayInputStream(bytes), IResource.FORCE, null); - // file.setDerived(true); - // } - //} + protected PHPBuilder javaBuilder; + + protected State newState; + + // local copies + protected NameEnvironment nameEnvironment; + + protected ClasspathMultiDirectory[] sourceLocations; + + protected BuildNotifier notifier; + + protected String encoding; + + protected Compiler compiler; + + protected WorkQueue workQueue; + + protected ArrayList problemSourceFiles; + + protected boolean compiledAllAtOnce; + + private boolean inCompiler; + + public static int MAX_AT_ONCE = 1000; + + protected AbstractImageBuilder(PHPBuilder javaBuilder) { + this.javaBuilder = javaBuilder; + this.newState = new State(javaBuilder); + + // local copies + this.nameEnvironment = javaBuilder.nameEnvironment; + this.sourceLocations = this.nameEnvironment.sourceLocations; + this.notifier = javaBuilder.notifier; + + this.encoding = javaBuilder.javaProject.getOption( + JavaCore.CORE_ENCODING, true); + this.compiler = newCompiler(); + this.workQueue = new WorkQueue(); + this.problemSourceFiles = new ArrayList(3); + } + + public void acceptResult(CompilationResult result) { + // In Batch mode, we write out the class files, hold onto the dependency + // info + // & additional types and report problems. + + // In Incremental mode, when writing out a class file we need to compare + // it + // against the previous file, remembering if structural changes occured. + // Before reporting the new problems, we need to update the problem + // count & + // remove the old problems. Plus delete additional class files that no + // longer exist. + + SourceFile compilationUnit = (SourceFile) result.getCompilationUnit(); // go + // directly + // back + // to + // the + // sourceFile + if (!workQueue.isCompiled(compilationUnit)) { + // try { + workQueue.finished(compilationUnit); + try { + updateProblemsFor(compilationUnit, result); // record + // compilation + // problems before + // potentially + // adding duplicate + // errors + updateTasksFor(compilationUnit, result); // record tasks + } catch (CoreException e) { + throw internalException(e); + } + + // String typeLocator = compilationUnit.typeLocator(); + // ClassFile[] classFiles = result.getClassFiles(); + // int length = classFiles.length; + // ArrayList duplicateTypeNames = null; + // ArrayList definedTypeNames = new ArrayList(length); + // for (int i = 0; i < length; i++) { + // ClassFile classFile = classFiles[i]; + // char[][] compoundName = classFile.getCompoundName(); + // char[] typeName = compoundName[compoundName.length - 1]; + // boolean isNestedType = CharOperation.contains('$', typeName); + // + // // Look for a possible collision, if one exists, report an error + // but do not write the class file + // if (isNestedType) { + // String qualifiedTypeName = new + // String(classFile.outerMostEnclosingClassFile().fileName()); + // if (newState.isDuplicateLocator(qualifiedTypeName, typeLocator)) + // continue; + // } else { + // String qualifiedTypeName = new String(classFile.fileName()); // + // the qualified type name "p1/p2/A" + // if (newState.isDuplicateLocator(qualifiedTypeName, typeLocator)) + // { + // if (duplicateTypeNames == null) + // duplicateTypeNames = new ArrayList(); + // duplicateTypeNames.add(compoundName); + // createErrorFor(compilationUnit.resource, + // ProjectPrefUtil.bind("build.duplicateClassFile", new + // String(typeName))); + // //$NON-NLS-1$ + // continue; + // } + // newState.recordLocatorForType(qualifiedTypeName, typeLocator); + // } + // definedTypeNames.add(writeClassFile(classFile, + // compilationUnit.sourceLocation.binaryFolder, !isNestedType)); + // } + + // finishedWith(typeLocator, result, + // compilationUnit.getMainTypeName(), definedTypeNames, + // duplicateTypeNames); + notifier.compiled(compilationUnit); + // } catch (CoreException e) { + // Util.log(e, "JavaBuilder handling CoreException"); //$NON-NLS-1$ + // createErrorFor(compilationUnit.resource, + // Util.bind("build.inconsistentClassFile")); //$NON-NLS-1$ + // } + } + } + + protected void cleanUp() { + this.nameEnvironment.cleanup(); + + this.javaBuilder = null; + this.nameEnvironment = null; + this.sourceLocations = null; + this.notifier = null; + this.compiler = null; + this.workQueue = null; + this.problemSourceFiles = null; + } + + /* + * Compile the given elements, adding more elements to the work queue if + * they are affected by the changes. + */ + protected void compile(SourceFile[] units) { + int toDo = units.length; + if (this.compiledAllAtOnce = toDo <= MAX_AT_ONCE) { + // do them all now + if (PHPBuilder.DEBUG) + for (int i = 0; i < toDo; i++) + System.out + .println("About to compile " + units[i].typeLocator()); //$NON-NLS-1$ + compile(units, null); + } else { + int i = 0; + boolean compilingFirstGroup = true; + while (i < toDo) { + int doNow = toDo < MAX_AT_ONCE ? toDo : MAX_AT_ONCE; + int index = 0; + SourceFile[] toCompile = new SourceFile[doNow]; + while (i < toDo && index < doNow) { + // Although it needed compiling when this method was called, + // it may have + // already been compiled when it was referenced by another + // unit. + SourceFile unit = units[i++]; + if (compilingFirstGroup || workQueue.isWaiting(unit)) { + if (PHPBuilder.DEBUG) + System.out + .println("About to compile " + unit.typeLocator()); //$NON-NLS-1$ + toCompile[index++] = unit; + } + } + if (index < doNow) + System.arraycopy(toCompile, 0, + toCompile = new SourceFile[index], 0, index); + SourceFile[] additionalUnits = new SourceFile[toDo - i]; + System.arraycopy(units, i, additionalUnits, 0, + additionalUnits.length); + compilingFirstGroup = false; + compile(toCompile, additionalUnits); + } + } + } + + void compile(SourceFile[] units, SourceFile[] additionalUnits) { + if (units.length == 0) + return; + notifier.aboutToCompile(units[0]); // just to change the message + + // extend additionalFilenames with all hierarchical problem types found + // during this entire build + if (!problemSourceFiles.isEmpty()) { + int toAdd = problemSourceFiles.size(); + int length = additionalUnits == null ? 0 : additionalUnits.length; + if (length == 0) + additionalUnits = new SourceFile[toAdd]; + else + System.arraycopy(additionalUnits, 0, + additionalUnits = new SourceFile[length + toAdd], 0, + length); + for (int i = 0; i < toAdd; i++) + additionalUnits[length + i] = (SourceFile) problemSourceFiles + .get(i); + } + String[] initialTypeNames = new String[units.length]; + for (int i = 0, l = units.length; i < l; i++) + initialTypeNames[i] = units[i].initialTypeName; + nameEnvironment.setNames(initialTypeNames, additionalUnits); + notifier.checkCancel(); + try { + inCompiler = true; + compiler.compile(units); + } catch (AbortCompilation ignored) { + // ignore the AbortCompilcation coming from + // BuildNotifier.checkCancelWithinCompiler() + // the Compiler failed after the user has chose to cancel... likely + // due to an OutOfMemory error + } finally { + inCompiler = false; + } + // Check for cancel immediately after a compile, because the compiler + // may + // have been cancelled but without propagating the correct exception + notifier.checkCancel(); + } + + protected void createErrorFor(IResource resource, String message) { + try { + IMarker marker = resource + .createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); + int severity = IMarker.SEVERITY_ERROR; + if (message.equals(Util.bind("build.duplicateResource"))) //$NON-NLS-1$ + if (JavaCore.WARNING.equals(javaBuilder.javaProject.getOption( + JavaCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE, true))) + severity = IMarker.SEVERITY_WARNING; + marker.setAttributes(new String[] { IMarker.MESSAGE, + IMarker.SEVERITY, IMarker.CHAR_START, IMarker.CHAR_END }, + new Object[] { message, new Integer(severity), + new Integer(0), new Integer(1) }); + } catch (CoreException e) { + throw internalException(e); + } + } + + // protected void finishedWith(String sourceLocator, CompilationResult + // result, char[] mainTypeName) throws CoreException {//, + // ArrayList definedTypeNames, ArrayList duplicateTypeNames) throws + // CoreException { + // if (duplicateTypeNames == null) { + // newState.record(sourceLocator, result.qualifiedReferences, + // result.simpleNameReferences, mainTypeName, definedTypeNames); + // return; + // } + // + // char[][][] qualifiedRefs = result.qualifiedReferences; + // char[][] simpleRefs = result.simpleNameReferences; + // // for each duplicate type p1.p2.A, add the type name A (package was + // already added) + // next : for (int i = 0, l = duplicateTypeNames.size(); i < l; i++) { + // char[][] compoundName = (char[][]) duplicateTypeNames.get(i); + // char[] typeName = compoundName[compoundName.length - 1]; + // int sLength = simpleRefs.length; + // for (int j = 0; j < sLength; j++) + // if (CharOperation.equals(simpleRefs[j], typeName)) + // continue next; + // System.arraycopy(simpleRefs, 0, simpleRefs = new char[sLength + 1][], 0, + // sLength); + // simpleRefs[sLength] = typeName; + // } + // newState.record(sourceLocator, qualifiedRefs, simpleRefs, mainTypeName, + // definedTypeNames); + // } + + // protected IContainer createFolder(IPath packagePath, IContainer + // outputFolder) throws CoreException { + // if (packagePath.isEmpty()) return outputFolder; + // IFolder folder = outputFolder.getFolder(packagePath); + // if (!folder.exists()) { + // createFolder(packagePath.removeLastSegments(1), outputFolder); + // folder.create(true, true, null); + // folder.setDerived(true); + // } + // return folder; + // } + + protected RuntimeException internalException(CoreException t) { + ImageBuilderInternalException imageBuilderException = new ImageBuilderInternalException( + t); + if (inCompiler) + return new AbortCompilation(true, imageBuilderException); + return imageBuilderException; + } + + protected Compiler newCompiler() { + // called once when the builder is initialized... can override if needed + return new Compiler(nameEnvironment, DefaultErrorHandlingPolicies + .proceedWithAllProblems(), javaBuilder.javaProject + .getOptions(true), this, ProblemFactory + .getProblemFactory(Locale.getDefault())); + } + + protected boolean isExcludedFromProject(IPath childPath) + throws JavaModelException { + // answer whether the folder should be ignored when walking the project + // as a source folder + if (childPath.segmentCount() > 2) + return false; // is a subfolder of a package + + for (int j = 0, k = sourceLocations.length; j < k; j++) { + // if + // (childPath.equals(sourceLocations[j].binaryFolder.getFullPath())) + // return true; + if (childPath.equals(sourceLocations[j].sourceFolder.getFullPath())) + return true; + } + // skip default output folder which may not be used by any source folder + return false; // childPath.equals(javaBuilder.javaProject.getOutputLocation()); + } + + /** + * Creates a marker from each problem and adds it to the resource. The + * marker is as follows: - its type is T_PROBLEM - its plugin ID is the + * JavaBuilder's plugin ID - its message is the problem's message - its + * priority reflects the severity of the problem - its range is the + * problem's range - it has an extra attribute "ID" which holds the + * problem's id + */ + protected void storeProblemsFor(SourceFile sourceFile, IProblem[] problems) + throws CoreException { + if (sourceFile == null || problems == null || problems.length == 0) + return; + + // String missingClassFile = null; + IResource resource = sourceFile.resource; + for (int i = 0, l = problems.length; i < l; i++) { + IProblem problem = problems[i]; + int id = problem.getID(); + switch (id) { + case IProblem.IsClassPathCorrect: + // PHPBuilder.removeProblemsAndTasksFor(javaBuilder.currentProject); + // // make this the only problem for this project + // String[] args = problem.getArguments(); + // missingClassFile = args[0]; + break; + case IProblem.SuperclassMustBeAClass: + case IProblem.SuperInterfaceMustBeAnInterface: + case IProblem.HierarchyCircularitySelfReference: + case IProblem.HierarchyCircularity: + case IProblem.HierarchyHasProblems: + case IProblem.SuperclassNotFound: + case IProblem.SuperclassNotVisible: + case IProblem.SuperclassAmbiguous: + case IProblem.SuperclassInternalNameProvided: + case IProblem.SuperclassInheritedNameHidesEnclosingName: + case IProblem.InterfaceNotFound: + case IProblem.InterfaceNotVisible: + case IProblem.InterfaceAmbiguous: + case IProblem.InterfaceInternalNameProvided: + case IProblem.InterfaceInheritedNameHidesEnclosingName: + // ensure that this file is always retrieved from source for the + // rest of the build + if (!problemSourceFiles.contains(sourceFile)) + problemSourceFiles.add(sourceFile); + break; + } + + if (id != IProblem.Task) { + IMarker marker = resource + .createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); + marker + .setAttributes( + new String[] { IMarker.MESSAGE, + IMarker.SEVERITY, IJavaModelMarker.ID, + IMarker.CHAR_START, IMarker.CHAR_END, + IMarker.LINE_NUMBER, + IJavaModelMarker.ARGUMENTS }, + new Object[] { + problem.getMessage(), + new Integer( + problem.isError() ? IMarker.SEVERITY_ERROR + : IMarker.SEVERITY_WARNING), + new Integer(id), + new Integer(problem.getSourceStart()), + new Integer(problem.getSourceEnd() + 1), + new Integer(problem + .getSourceLineNumber()), + Util + .getProblemArgumentsForMarker(problem + .getArguments()) }); + } + + /* + * Do NOT want to populate the Java Model just to find the matching + * Java element. Also cannot query compilation units located in + * folders with invalid package names such as 'a/b.c.d/e'. // + * compute a user-friendly location IJavaElement element = + * JavaCore.create(resource); if (element instanceof + * net.sourceforge.phpdt.core.ICompilationUnit) { // try to find a + * finer grain element net.sourceforge.phpdt.core.ICompilationUnit + * unit = (net.sourceforge.phpdt.core.ICompilationUnit) element; + * IJavaElement fragment = + * unit.getElementAt(problem.getSourceStart()); if (fragment != + * null) element = fragment; } String location = null; if (element + * instanceof JavaElement) location = ((JavaElement) + * element).readableName(); if (location != null) + * marker.setAttribute(IMarker.LOCATION, location); + */ + + // if (missingClassFile != null) + // throw new MissingClassFileException(missingClassFile); + } + } + + protected void storeTasksFor(SourceFile sourceFile, IProblem[] tasks) + throws CoreException { + if (sourceFile == null || tasks == null || tasks.length == 0) + return; + + IResource resource = sourceFile.resource; + for (int i = 0, l = tasks.length; i < l; i++) { + IProblem task = tasks[i]; + if (task.getID() == IProblem.Task) { + IMarker marker = resource + .createMarker(IJavaModelMarker.TASK_MARKER); + int priority = IMarker.PRIORITY_NORMAL; + String compilerPriority = task.getArguments()[2]; + if (JavaCore.COMPILER_TASK_PRIORITY_HIGH + .equals(compilerPriority)) + priority = IMarker.PRIORITY_HIGH; + else if (JavaCore.COMPILER_TASK_PRIORITY_LOW + .equals(compilerPriority)) + priority = IMarker.PRIORITY_LOW; + marker.setAttributes(new String[] { IMarker.MESSAGE, + IMarker.PRIORITY, IMarker.DONE, IMarker.CHAR_START, + IMarker.CHAR_END, IMarker.LINE_NUMBER, + IMarker.USER_EDITABLE, }, new Object[] { + task.getMessage(), new Integer(priority), + new Boolean(false), new Integer(task.getSourceStart()), + new Integer(task.getSourceEnd() + 1), + new Integer(task.getSourceLineNumber()), + new Boolean(false), }); + } + } + } + + protected void updateProblemsFor(SourceFile sourceFile, + CompilationResult result) throws CoreException { + IProblem[] problems = result.getProblems(); + if (problems == null || problems.length == 0) + return; + // axelcl start insert - calculate line numbers + if (problems != null) { + for (int i = 0; i < problems.length; i++) { + if (problems[i].getSourceLineNumber() == 1) { + problems[i].setSourceLineNumber(ProblemHandler + .searchLineNumber(result.lineSeparatorPositions, + problems[i].getSourceStart())); + } + } + } + // axelcl end insert + notifier.updateProblemCounts(problems); + storeProblemsFor(sourceFile, problems); + } + + protected void updateTasksFor(SourceFile sourceFile, + CompilationResult result) throws CoreException { + IProblem[] tasks = result.getTasks(); + if (tasks == null || tasks.length == 0) + return; + + storeTasksFor(sourceFile, tasks); + } + + // protected char[] writeClassFile(ClassFile classFile, IContainer + // outputFolder, boolean isSecondaryType) throws CoreException { + // String fileName = new String(classFile.fileName()); // the qualified type + // name "p1/p2/A" + // IPath filePath = new Path(fileName); + // IContainer container = outputFolder; + // if (filePath.segmentCount() > 1) { + // container = createFolder(filePath.removeLastSegments(1), outputFolder); + // filePath = new Path(filePath.lastSegment()); + // } + // + // IFile file = + // container.getFile(filePath.addFileExtension(JavaBuilder.CLASS_EXTENSION)); + // writeClassFileBytes(classFile.getBytes(), file, fileName, + // isSecondaryType); + // // answer the name of the class file as in Y or Y$M + // return filePath.lastSegment().toCharArray(); + // } + // + // protected void writeClassFileBytes(byte[] bytes, IFile file, String + // qualifiedFileName, boolean isSecondaryType) throws + // CoreException { + // if (file.exists()) { + // // Deal with shared output folders... last one wins... no collision cases + // detected + // if (JavaBuilder.DEBUG) + // System.out.println("Writing changed class file " + + // file.getName());//$NON-NLS-1$ + // file.setContents(new ByteArrayInputStream(bytes), true, false, null); + // if (!file.isDerived()) + // file.setDerived(true); + // } else { + // // Default implementation just writes out the bytes for the new class + // file... + // if (JavaBuilder.DEBUG) + // System.out.println("Writing new class file " + + // file.getName());//$NON-NLS-1$ + // file.create(new ByteArrayInputStream(bytes), IResource.FORCE, null); + // file.setDerived(true); + // } + // } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/BatchImageBuilder.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/BatchImageBuilder.java index d29be84..6669d85 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/BatchImageBuilder.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/BatchImageBuilder.java @@ -25,224 +25,260 @@ import org.eclipse.core.runtime.IPath; public class BatchImageBuilder extends AbstractImageBuilder { -protected BatchImageBuilder(PHPBuilder javaBuilder) { - super(javaBuilder); - this.nameEnvironment.isIncrementalBuild = false; -} + protected BatchImageBuilder(PHPBuilder javaBuilder) { + super(javaBuilder); + this.nameEnvironment.isIncrementalBuild = false; + } -public void build() { - if (PHPBuilder.DEBUG) - System.out.println("FULL build"); //$NON-NLS-1$ + public void build() { + if (PHPBuilder.DEBUG) + System.out.println("FULL build"); //$NON-NLS-1$ - try { - notifier.subTask(Util.bind("build.cleaningOutput")); //$NON-NLS-1$ - PHPBuilder.removeProblemsAndTasksFor(javaBuilder.currentProject); -// cleanOutputFolders(true); - notifier.updateProgressDelta(0.1f); + try { + notifier.subTask(Util.bind("build.cleaningOutput")); //$NON-NLS-1$ + PHPBuilder.removeProblemsAndTasksFor(javaBuilder.currentProject); + // cleanOutputFolders(true); + notifier.updateProgressDelta(0.1f); - notifier.subTask(Util.bind("build.analyzingSources")); //$NON-NLS-1$ - ArrayList sourceFiles = new ArrayList(33); - addAllSourceFiles(sourceFiles); - notifier.updateProgressDelta(0.15f); + notifier.subTask(Util.bind("build.analyzingSources")); //$NON-NLS-1$ + ArrayList sourceFiles = new ArrayList(33); + addAllSourceFiles(sourceFiles); + notifier.updateProgressDelta(0.15f); - if (sourceFiles.size() > 0) { - SourceFile[] allSourceFiles = new SourceFile[sourceFiles.size()]; - sourceFiles.toArray(allSourceFiles); + if (sourceFiles.size() > 0) { + SourceFile[] allSourceFiles = new SourceFile[sourceFiles.size()]; + sourceFiles.toArray(allSourceFiles); - notifier.setProgressPerCompilationUnit(0.75f / allSourceFiles.length); - workQueue.addAll(allSourceFiles); - compile(allSourceFiles); - } + notifier + .setProgressPerCompilationUnit(0.75f / allSourceFiles.length); + workQueue.addAll(allSourceFiles); + compile(allSourceFiles); + } + + if (javaBuilder.javaProject.hasCycleMarker()) + javaBuilder.mustPropagateStructuralChanges(); - if (javaBuilder.javaProject.hasCycleMarker()) - javaBuilder.mustPropagateStructuralChanges(); - - } catch (CoreException e) { - throw internalException(e); - } finally { - cleanUp(); + } catch (CoreException e) { + throw internalException(e); + } finally { + cleanUp(); + } } -} -protected void addAllSourceFiles(final ArrayList sourceFiles) throws CoreException { - - for (int i = 0, l = sourceLocations.length; i < l; i++) { - final ClasspathMultiDirectory sourceLocation = sourceLocations[i]; - final char[][] exclusionPatterns = sourceLocation.exclusionPatterns; - final boolean isAlsoProject = sourceLocation.sourceFolder.equals(javaBuilder.currentProject); - sourceLocation.sourceFolder.accept( - new IResourceProxyVisitor() { + protected void addAllSourceFiles(final ArrayList sourceFiles) + throws CoreException { + + for (int i = 0, l = sourceLocations.length; i < l; i++) { + final ClasspathMultiDirectory sourceLocation = sourceLocations[i]; + final char[][] exclusionPatterns = sourceLocation.exclusionPatterns; + final boolean isAlsoProject = sourceLocation.sourceFolder + .equals(javaBuilder.currentProject); + sourceLocation.sourceFolder.accept(new IResourceProxyVisitor() { public boolean visit(IResourceProxy proxy) throws CoreException { IResource resource = null; if (exclusionPatterns != null) { resource = proxy.requestResource(); - if (Util.isExcluded(resource, exclusionPatterns)) return false; + if (Util.isExcluded(resource, exclusionPatterns)) + return false; } - switch(proxy.getType()) { - case IResource.FILE : - if (net.sourceforge.phpdt.internal.compiler.util.Util.isJavaFileName(proxy.getName())) { - if (resource == null) - resource = proxy.requestResource(); - sourceFiles.add(new SourceFile((IFile) resource, sourceLocation, encoding)); - } + switch (proxy.getType()) { + case IResource.FILE: + if (net.sourceforge.phpdt.internal.compiler.util.Util + .isJavaFileName(proxy.getName())) { + if (resource == null) + resource = proxy.requestResource(); + sourceFiles.add(new SourceFile((IFile) resource, + sourceLocation, encoding)); + } + return false; + case IResource.FOLDER: + if (isAlsoProject + && isExcludedFromProject(proxy + .requestFullPath())) return false; - case IResource.FOLDER : - if (isAlsoProject && isExcludedFromProject(proxy.requestFullPath())) return false; } return true; } - }, - IResource.NONE - ); - notifier.checkCancel(); + }, IResource.NONE); + notifier.checkCancel(); + } } -} -protected void cleanOutputFolders() throws CoreException { - boolean deleteAll = JavaCore.CLEAN.equals( - javaBuilder.javaProject.getOption(JavaCore.CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER, true)); - if (deleteAll) { - ArrayList visited = new ArrayList(sourceLocations.length); - for (int i = 0, l = sourceLocations.length; i < l; i++) { - notifier.subTask(Util.bind("build.cleaningOutput")); //$NON-NLS-1$ - ClasspathMultiDirectory sourceLocation = sourceLocations[i]; - if (sourceLocation.hasIndependentOutputFolder) { - IContainer outputFolder = sourceLocation.binaryFolder; - if (!visited.contains(outputFolder)) { - visited.add(outputFolder); - IResource[] members = outputFolder.members(); - for (int j = 0, m = members.length; j < m; j++) - members[j].delete(IResource.FORCE, null); - } - notifier.checkCancel(); - copyExtraResourcesBack(sourceLocation, deleteAll); - } else { - boolean isOutputFolder = sourceLocation.sourceFolder.equals(sourceLocation.binaryFolder); - final char[][] exclusionPatterns = - isOutputFolder - ? sourceLocation.exclusionPatterns - : null; // ignore exclusionPatterns if output folder == another source folder... not this one - sourceLocation.binaryFolder.accept( - new IResourceProxyVisitor() { - public boolean visit(IResourceProxy proxy) throws CoreException { - IResource resource = null; - if (exclusionPatterns != null) { - resource = proxy.requestResource(); - if (Util.isExcluded(resource, exclusionPatterns)) return false; - } - if (proxy.getType() == IResource.FILE) { -// if (ProjectPrefUtil.isClassFileName(proxy.getName())) { -// if (resource == null) -// resource = proxy.requestResource(); -// resource.delete(IResource.FORCE, null); -// } - return false; - } - notifier.checkCancel(); - return true; - } - }, - IResource.NONE - ); - if (!isOutputFolder) { + protected void cleanOutputFolders() throws CoreException { + boolean deleteAll = JavaCore.CLEAN.equals(javaBuilder.javaProject + .getOption(JavaCore.CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER, true)); + if (deleteAll) { + ArrayList visited = new ArrayList(sourceLocations.length); + for (int i = 0, l = sourceLocations.length; i < l; i++) { + notifier.subTask(Util.bind("build.cleaningOutput")); //$NON-NLS-1$ + ClasspathMultiDirectory sourceLocation = sourceLocations[i]; + if (sourceLocation.hasIndependentOutputFolder) { + IContainer outputFolder = sourceLocation.binaryFolder; + if (!visited.contains(outputFolder)) { + visited.add(outputFolder); + IResource[] members = outputFolder.members(); + for (int j = 0, m = members.length; j < m; j++) + members[j].delete(IResource.FORCE, null); + } notifier.checkCancel(); - copyPackages(sourceLocation); + copyExtraResourcesBack(sourceLocation, deleteAll); + } else { + boolean isOutputFolder = sourceLocation.sourceFolder + .equals(sourceLocation.binaryFolder); + final char[][] exclusionPatterns = isOutputFolder ? sourceLocation.exclusionPatterns + : null; // ignore exclusionPatterns if output folder + // == another source folder... not this one + sourceLocation.binaryFolder.accept( + new IResourceProxyVisitor() { + public boolean visit(IResourceProxy proxy) + throws CoreException { + IResource resource = null; + if (exclusionPatterns != null) { + resource = proxy.requestResource(); + if (Util.isExcluded(resource, + exclusionPatterns)) + return false; + } + if (proxy.getType() == IResource.FILE) { + // if + // (ProjectPrefUtil.isClassFileName(proxy.getName())) + // { + // if (resource == null) + // resource = proxy.requestResource(); + // resource.delete(IResource.FORCE, + // null); + // } + return false; + } + notifier.checkCancel(); + return true; + } + }, IResource.NONE); + if (!isOutputFolder) { + notifier.checkCancel(); + copyPackages(sourceLocation); + } } + notifier.checkCancel(); + } + } else { + for (int i = 0, l = sourceLocations.length; i < l; i++) { + ClasspathMultiDirectory sourceLocation = sourceLocations[i]; + if (sourceLocation.hasIndependentOutputFolder) + copyExtraResourcesBack(sourceLocation, deleteAll); + else if (!sourceLocation.sourceFolder + .equals(sourceLocation.binaryFolder)) + copyPackages(sourceLocation); // output folder is + // different from source + // folder + notifier.checkCancel(); } - notifier.checkCancel(); - } - } else { - for (int i = 0, l = sourceLocations.length; i < l; i++) { - ClasspathMultiDirectory sourceLocation = sourceLocations[i]; - if (sourceLocation.hasIndependentOutputFolder) - copyExtraResourcesBack(sourceLocation, deleteAll); - else if (!sourceLocation.sourceFolder.equals(sourceLocation.binaryFolder)) - copyPackages(sourceLocation); // output folder is different from source folder - notifier.checkCancel(); } } -} -protected void copyExtraResourcesBack(ClasspathMultiDirectory sourceLocation, final boolean deletedAll) throws CoreException { - // When, if ever, does a builder need to copy resources files (not .java or .class) into the output folder? - // If we wipe the output folder at the beginning of the build then all 'extra' resources must be copied to the output folder. - - notifier.subTask(Util.bind("build.copyingResources")); //$NON-NLS-1$ - final int segmentCount = sourceLocation.sourceFolder.getFullPath().segmentCount(); - final char[][] exclusionPatterns = sourceLocation.exclusionPatterns; - final IContainer outputFolder = sourceLocation.binaryFolder; - final boolean isAlsoProject = sourceLocation.sourceFolder.equals(javaBuilder.currentProject); - sourceLocation.sourceFolder.accept( - new IResourceProxyVisitor() { + protected void copyExtraResourcesBack( + ClasspathMultiDirectory sourceLocation, final boolean deletedAll) + throws CoreException { + // When, if ever, does a builder need to copy resources files (not .java + // or .class) into the output folder? + // If we wipe the output folder at the beginning of the build then all + // 'extra' resources must be copied to the output folder. + + notifier.subTask(Util.bind("build.copyingResources")); //$NON-NLS-1$ + final int segmentCount = sourceLocation.sourceFolder.getFullPath() + .segmentCount(); + final char[][] exclusionPatterns = sourceLocation.exclusionPatterns; + final IContainer outputFolder = sourceLocation.binaryFolder; + final boolean isAlsoProject = sourceLocation.sourceFolder + .equals(javaBuilder.currentProject); + sourceLocation.sourceFolder.accept(new IResourceProxyVisitor() { public boolean visit(IResourceProxy proxy) throws CoreException { IResource resource = null; - switch(proxy.getType()) { - case IResource.FILE : - if (net.sourceforge.phpdt.internal.compiler.util.Util.isJavaFileName(proxy.getName())) return false;// || ProjectPrefUtil.isClassFileName(proxy.getName())) return false; + switch (proxy.getType()) { + case IResource.FILE: + if (net.sourceforge.phpdt.internal.compiler.util.Util + .isJavaFileName(proxy.getName())) + return false;// || + // ProjectPrefUtil.isClassFileName(proxy.getName())) + // return false; - resource = proxy.requestResource(); - if (javaBuilder.filterExtraResource(resource)) return false; - if (exclusionPatterns != null && Util.isExcluded(resource, exclusionPatterns)) - return false; + resource = proxy.requestResource(); + if (javaBuilder.filterExtraResource(resource)) + return false; + if (exclusionPatterns != null + && Util.isExcluded(resource, exclusionPatterns)) + return false; - IPath partialPath = resource.getFullPath().removeFirstSegments(segmentCount); - IResource copiedResource = outputFolder.getFile(partialPath); - if (copiedResource.exists()) { - if (deletedAll) { - createErrorFor(resource, Util.bind("build.duplicateResource")); //$NON-NLS-1$ - return false; - } - copiedResource.delete(IResource.FORCE, null); // last one wins + IPath partialPath = resource.getFullPath() + .removeFirstSegments(segmentCount); + IResource copiedResource = outputFolder + .getFile(partialPath); + if (copiedResource.exists()) { + if (deletedAll) { + createErrorFor(resource, Util + .bind("build.duplicateResource")); //$NON-NLS-1$ + return false; } - resource.copy(copiedResource.getFullPath(), IResource.FORCE, null); - copiedResource.setDerived(true); + copiedResource.delete(IResource.FORCE, null); // last + // one + // wins + } + resource.copy(copiedResource.getFullPath(), + IResource.FORCE, null); + copiedResource.setDerived(true); + return false; + case IResource.FOLDER: + resource = proxy.requestResource(); + if (javaBuilder.filterExtraResource(resource)) + return false; + if (exclusionPatterns != null + && Util.isExcluded(resource, exclusionPatterns)) return false; - case IResource.FOLDER : - resource = proxy.requestResource(); - if (javaBuilder.filterExtraResource(resource)) return false; - if (exclusionPatterns != null && Util.isExcluded(resource, exclusionPatterns)) - return false; - IPath folderPath = resource.getFullPath(); - if (isAlsoProject && isExcludedFromProject(folderPath)) return false; // the sourceFolder == project -// createFolder(folderPath.removeFirstSegments(segmentCount), outputFolder); + IPath folderPath = resource.getFullPath(); + if (isAlsoProject && isExcludedFromProject(folderPath)) + return false; // the sourceFolder == project + // createFolder(folderPath.removeFirstSegments(segmentCount), + // outputFolder); } return true; } - }, - IResource.NONE - ); -} + }, IResource.NONE); + } -protected void copyPackages(ClasspathMultiDirectory sourceLocation) throws CoreException { - final int segmentCount = sourceLocation.sourceFolder.getFullPath().segmentCount(); - final char[][] exclusionPatterns = sourceLocation.exclusionPatterns; - final IContainer outputFolder = sourceLocation.binaryFolder; - final boolean isAlsoProject = sourceLocation.sourceFolder.equals(javaBuilder.currentProject); - sourceLocation.sourceFolder.accept( - new IResourceProxyVisitor() { + protected void copyPackages(ClasspathMultiDirectory sourceLocation) + throws CoreException { + final int segmentCount = sourceLocation.sourceFolder.getFullPath() + .segmentCount(); + final char[][] exclusionPatterns = sourceLocation.exclusionPatterns; + final IContainer outputFolder = sourceLocation.binaryFolder; + final boolean isAlsoProject = sourceLocation.sourceFolder + .equals(javaBuilder.currentProject); + sourceLocation.sourceFolder.accept(new IResourceProxyVisitor() { public boolean visit(IResourceProxy proxy) throws CoreException { - switch(proxy.getType()) { - case IResource.FILE : + switch (proxy.getType()) { + case IResource.FILE: + return false; + case IResource.FOLDER: + IResource resource = proxy.requestResource(); + if (javaBuilder.filterExtraResource(resource)) + return false; + if (exclusionPatterns != null + && Util.isExcluded(resource, exclusionPatterns)) return false; - case IResource.FOLDER : - IResource resource = proxy.requestResource(); - if (javaBuilder.filterExtraResource(resource)) return false; - if (exclusionPatterns != null && Util.isExcluded(resource, exclusionPatterns)) - return false; - IPath folderPath = resource.getFullPath(); - if (isAlsoProject && isExcludedFromProject(folderPath)) return false; // the sourceFolder == project -// createFolder(folderPath.removeFirstSegments(segmentCount), outputFolder); + IPath folderPath = resource.getFullPath(); + if (isAlsoProject && isExcludedFromProject(folderPath)) + return false; // the sourceFolder == project + // createFolder(folderPath.removeFirstSegments(segmentCount), + // outputFolder); } return true; } - }, - IResource.NONE - ); -} + }, IResource.NONE); + } -public String toString() { - return "batch image builder for:\n\tnew state: " + newState; //$NON-NLS-1$ -} + public String toString() { + return "batch image builder for:\n\tnew state: " + newState; //$NON-NLS-1$ + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/BuildNotifier.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/BuildNotifier.java index 5af28e4..4ccbfeb 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/BuildNotifier.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/BuildNotifier.java @@ -21,258 +21,310 @@ import org.eclipse.core.runtime.OperationCanceledException; public class BuildNotifier { -protected IProgressMonitor monitor; -protected boolean cancelling; -protected float percentComplete; -protected float progressPerCompilationUnit; -protected int newErrorCount; -protected int fixedErrorCount; -protected int newWarningCount; -protected int fixedWarningCount; -protected int workDone; -protected int totalWork; -protected String previousSubtask; - -public static int NewErrorCount = 0; -public static int FixedErrorCount = 0; -public static int NewWarningCount = 0; -public static int FixedWarningCount = 0; - -public static void resetProblemCounters() { - NewErrorCount = 0; - FixedErrorCount = 0; - NewWarningCount = 0; - FixedWarningCount = 0; -} + protected IProgressMonitor monitor; -public BuildNotifier(IProgressMonitor monitor, IProject project) { - this.monitor = monitor; - this.cancelling = false; - this.newErrorCount = NewErrorCount; - this.fixedErrorCount = FixedErrorCount; - this.newWarningCount = NewWarningCount; - this.fixedWarningCount = FixedWarningCount; - this.workDone = 0; - this.totalWork = 1000000; -} + protected boolean cancelling; -/** - * Notification before a compile that a unit is about to be compiled. - */ -public void aboutToCompile(SourceFile unit) { - String message = Util.bind("build.compiling", unit.resource.getFullPath().removeLastSegments(1).makeRelative().toString()); //$NON-NLS-1$ - subTask(message); -} + protected float percentComplete; -public void begin() { - if (monitor != null) - monitor.beginTask("", totalWork); //$NON-NLS-1$ - this.previousSubtask = null; -} + protected float progressPerCompilationUnit; -/** - * Check whether the build has been canceled. - */ -public void checkCancel() { - if (monitor != null && monitor.isCanceled()) - throw new OperationCanceledException(); -} + protected int newErrorCount; + + protected int fixedErrorCount; + + protected int newWarningCount; + + protected int fixedWarningCount; -/** - * Check whether the build has been canceled. - * Must use this call instead of checkCancel() when within the compiler. - */ -public void checkCancelWithinCompiler() { - if (monitor != null && monitor.isCanceled() && !cancelling) { - // Once the compiler has been canceled, don't check again. - setCancelling(true); - // Only AbortCompilation can stop the compiler cleanly. - // We check cancelation again following the call to compile. - throw new AbortCompilation(true, null); + protected int workDone; + + protected int totalWork; + + protected String previousSubtask; + + public static int NewErrorCount = 0; + + public static int FixedErrorCount = 0; + + public static int NewWarningCount = 0; + + public static int FixedWarningCount = 0; + + public static void resetProblemCounters() { + NewErrorCount = 0; + FixedErrorCount = 0; + NewWarningCount = 0; + FixedWarningCount = 0; } -} -/** - * Notification while within a compile that a unit has finished being compiled. - */ -public void compiled(SourceFile unit) { - String message = Util.bind("build.compiling", unit.resource.getFullPath().removeLastSegments(1).makeRelative().toString()); //$NON-NLS-1$ - subTask(message); - updateProgressDelta(progressPerCompilationUnit); - checkCancelWithinCompiler(); -} + public BuildNotifier(IProgressMonitor monitor, IProject project) { + this.monitor = monitor; + this.cancelling = false; + this.newErrorCount = NewErrorCount; + this.fixedErrorCount = FixedErrorCount; + this.newWarningCount = NewWarningCount; + this.fixedWarningCount = FixedWarningCount; + this.workDone = 0; + this.totalWork = 1000000; + } -public void done() { - NewErrorCount = this.newErrorCount; - FixedErrorCount = this.fixedErrorCount; - NewWarningCount = this.newWarningCount; - FixedWarningCount = this.fixedWarningCount; - - updateProgress(1.0f); - subTask(Util.bind("build.done")); //$NON-NLS-1$ - if (monitor != null) - monitor.done(); - this.previousSubtask = null; -} + /** + * Notification before a compile that a unit is about to be compiled. + */ + public void aboutToCompile(SourceFile unit) { + String message = Util + .bind( + "build.compiling", unit.resource.getFullPath().removeLastSegments(1).makeRelative().toString()); //$NON-NLS-1$ + subTask(message); + } -/** - * Returns a string describing the problems. - */ -protected String problemsMessage() { - int numNew = newErrorCount + newWarningCount; - int numFixed = fixedErrorCount + fixedWarningCount; - if (numNew == 0 && numFixed == 0) return ""; //$NON-NLS-1$ - - boolean displayBoth = numNew > 0 && numFixed > 0; - StringBuffer buffer = new StringBuffer(); - buffer.append('('); - if (numNew > 0) { - // (Found x errors + y warnings) - buffer.append(Util.bind("build.foundHeader")); //$NON-NLS-1$ - buffer.append(' '); - if (displayBoth || newErrorCount > 0) { - if (newErrorCount == 1) - buffer.append(Util.bind("build.oneError")); //$NON-NLS-1$ - else - buffer.append(Util.bind("build.multipleErrors", String.valueOf(newErrorCount))); //$NON-NLS-1$ - if (displayBoth || newWarningCount > 0) - buffer.append(" + "); //$NON-NLS-1$ - } - if (displayBoth || newWarningCount > 0) { - if (newWarningCount == 1) - buffer.append(Util.bind("build.oneWarning")); //$NON-NLS-1$ - else - buffer.append(Util.bind("build.multipleWarnings", String.valueOf(newWarningCount))); //$NON-NLS-1$ + public void begin() { + if (monitor != null) + monitor.beginTask("", totalWork); //$NON-NLS-1$ + this.previousSubtask = null; + } + + /** + * Check whether the build has been canceled. + */ + public void checkCancel() { + if (monitor != null && monitor.isCanceled()) + throw new OperationCanceledException(); + } + + /** + * Check whether the build has been canceled. Must use this call instead of + * checkCancel() when within the compiler. + */ + public void checkCancelWithinCompiler() { + if (monitor != null && monitor.isCanceled() && !cancelling) { + // Once the compiler has been canceled, don't check again. + setCancelling(true); + // Only AbortCompilation can stop the compiler cleanly. + // We check cancelation again following the call to compile. + throw new AbortCompilation(true, null); } - if (numFixed > 0) - buffer.append(", "); //$NON-NLS-1$ } - if (numFixed > 0) { - // (Fixed x errors + y warnings) or (Found x errors + y warnings, Fixed x + y) - buffer.append(Util.bind("build.fixedHeader")); //$NON-NLS-1$ - buffer.append(' '); - if (displayBoth) { - buffer.append(String.valueOf(fixedErrorCount)); - buffer.append(" + "); //$NON-NLS-1$ - buffer.append(String.valueOf(fixedWarningCount)); - } else { - if (fixedErrorCount > 0) { - if (fixedErrorCount == 1) + + /** + * Notification while within a compile that a unit has finished being + * compiled. + */ + public void compiled(SourceFile unit) { + String message = Util + .bind( + "build.compiling", unit.resource.getFullPath().removeLastSegments(1).makeRelative().toString()); //$NON-NLS-1$ + subTask(message); + updateProgressDelta(progressPerCompilationUnit); + checkCancelWithinCompiler(); + } + + public void done() { + NewErrorCount = this.newErrorCount; + FixedErrorCount = this.fixedErrorCount; + NewWarningCount = this.newWarningCount; + FixedWarningCount = this.fixedWarningCount; + + updateProgress(1.0f); + subTask(Util.bind("build.done")); //$NON-NLS-1$ + if (monitor != null) + monitor.done(); + this.previousSubtask = null; + } + + /** + * Returns a string describing the problems. + */ + protected String problemsMessage() { + int numNew = newErrorCount + newWarningCount; + int numFixed = fixedErrorCount + fixedWarningCount; + if (numNew == 0 && numFixed == 0) + return ""; //$NON-NLS-1$ + + boolean displayBoth = numNew > 0 && numFixed > 0; + StringBuffer buffer = new StringBuffer(); + buffer.append('('); + if (numNew > 0) { + // (Found x errors + y warnings) + buffer.append(Util.bind("build.foundHeader")); //$NON-NLS-1$ + buffer.append(' '); + if (displayBoth || newErrorCount > 0) { + if (newErrorCount == 1) buffer.append(Util.bind("build.oneError")); //$NON-NLS-1$ else - buffer.append(Util.bind("build.multipleErrors", String.valueOf(fixedErrorCount))); //$NON-NLS-1$ - if (fixedWarningCount > 0) + buffer + .append(Util + .bind( + "build.multipleErrors", String.valueOf(newErrorCount))); //$NON-NLS-1$ + if (displayBoth || newWarningCount > 0) buffer.append(" + "); //$NON-NLS-1$ } - if (fixedWarningCount > 0) { - if (fixedWarningCount == 1) + if (displayBoth || newWarningCount > 0) { + if (newWarningCount == 1) buffer.append(Util.bind("build.oneWarning")); //$NON-NLS-1$ else - buffer.append(Util.bind("build.multipleWarnings", String.valueOf(fixedWarningCount))); //$NON-NLS-1$ + buffer + .append(Util + .bind( + "build.multipleWarnings", String.valueOf(newWarningCount))); //$NON-NLS-1$ } + if (numFixed > 0) + buffer.append(", "); //$NON-NLS-1$ } + if (numFixed > 0) { + // (Fixed x errors + y warnings) or (Found x errors + y warnings, + // Fixed x + y) + buffer.append(Util.bind("build.fixedHeader")); //$NON-NLS-1$ + buffer.append(' '); + if (displayBoth) { + buffer.append(String.valueOf(fixedErrorCount)); + buffer.append(" + "); //$NON-NLS-1$ + buffer.append(String.valueOf(fixedWarningCount)); + } else { + if (fixedErrorCount > 0) { + if (fixedErrorCount == 1) + buffer.append(Util.bind("build.oneError")); //$NON-NLS-1$ + else + buffer + .append(Util + .bind( + "build.multipleErrors", String.valueOf(fixedErrorCount))); //$NON-NLS-1$ + if (fixedWarningCount > 0) + buffer.append(" + "); //$NON-NLS-1$ + } + if (fixedWarningCount > 0) { + if (fixedWarningCount == 1) + buffer.append(Util.bind("build.oneWarning")); //$NON-NLS-1$ + else + buffer + .append(Util + .bind( + "build.multipleWarnings", String.valueOf(fixedWarningCount))); //$NON-NLS-1$ + } + } + } + buffer.append(')'); + return buffer.toString(); } - buffer.append(')'); - return buffer.toString(); -} -/** - * Sets the cancelling flag, which indicates we are in the middle - * of being cancelled. Certain places (those callable indirectly from the compiler) - * should not check cancel again while this is true, to avoid OperationCanceledException - * being thrown at an inopportune time. - */ -public void setCancelling(boolean cancelling) { - this.cancelling = cancelling; -} + /** + * Sets the cancelling flag, which indicates we are in the middle of being + * cancelled. Certain places (those callable indirectly from the compiler) + * should not check cancel again while this is true, to avoid + * OperationCanceledException being thrown at an inopportune time. + */ + public void setCancelling(boolean cancelling) { + this.cancelling = cancelling; + } -/** - * Sets the amount of progress to report for compiling each compilation unit. - */ -public void setProgressPerCompilationUnit(float progress) { - this.progressPerCompilationUnit = progress; -} + /** + * Sets the amount of progress to report for compiling each compilation + * unit. + */ + public void setProgressPerCompilationUnit(float progress) { + this.progressPerCompilationUnit = progress; + } -public void subTask(String message) { - String pm = problemsMessage(); - String msg = pm.length() == 0 ? message : pm + " " + message; //$NON-NLS-1$ + public void subTask(String message) { + String pm = problemsMessage(); + String msg = pm.length() == 0 ? message : pm + " " + message; //$NON-NLS-1$ - if (msg.equals(this.previousSubtask)) return; // avoid refreshing with same one - //if (JavaBuilder.DEBUG) System.out.println(msg); - if (monitor != null) - monitor.subTask(msg); + if (msg.equals(this.previousSubtask)) + return; // avoid refreshing with same one + // if (JavaBuilder.DEBUG) System.out.println(msg); + if (monitor != null) + monitor.subTask(msg); - this.previousSubtask = msg; -} + this.previousSubtask = msg; + } -protected void updateProblemCounts(IProblem[] newProblems) { - for (int i = 0, l = newProblems.length; i < l; i++) - if (newProblems[i].isError()) newErrorCount++; else newWarningCount++; -} + protected void updateProblemCounts(IProblem[] newProblems) { + for (int i = 0, l = newProblems.length; i < l; i++) + if (newProblems[i].isError()) + newErrorCount++; + else + newWarningCount++; + } -/** - * Update the problem counts from one compilation result given the old and new problems, - * either of which may be null. - */ -protected void updateProblemCounts(IMarker[] oldProblems, IProblem[] newProblems) { - if (newProblems != null) { - next : for (int i = 0, l = newProblems.length; i < l; i++) { - IProblem newProblem = newProblems[i]; - if (newProblem.getID() == IProblem.Task) continue; // skip task - boolean isError = newProblem.isError(); - String message = newProblem.getMessage(); - - if (oldProblems != null) { - for (int j = 0, m = oldProblems.length; j < m; j++) { - IMarker pb = oldProblems[j]; - if (pb == null) continue; // already matched up with a new problem - boolean wasError = IMarker.SEVERITY_ERROR - == pb.getAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); - if (isError == wasError && message.equals(pb.getAttribute(IMarker.MESSAGE, ""))) { //$NON-NLS-1$ - oldProblems[j] = null; - continue next; + /** + * Update the problem counts from one compilation result given the old and + * new problems, either of which may be null. + */ + protected void updateProblemCounts(IMarker[] oldProblems, + IProblem[] newProblems) { + if (newProblems != null) { + next: for (int i = 0, l = newProblems.length; i < l; i++) { + IProblem newProblem = newProblems[i]; + if (newProblem.getID() == IProblem.Task) + continue; // skip task + boolean isError = newProblem.isError(); + String message = newProblem.getMessage(); + + if (oldProblems != null) { + for (int j = 0, m = oldProblems.length; j < m; j++) { + IMarker pb = oldProblems[j]; + if (pb == null) + continue; // already matched up with a new problem + boolean wasError = IMarker.SEVERITY_ERROR == pb + .getAttribute(IMarker.SEVERITY, + IMarker.SEVERITY_ERROR); + if (isError == wasError + && message.equals(pb.getAttribute( + IMarker.MESSAGE, ""))) { //$NON-NLS-1$ + oldProblems[j] = null; + continue next; + } } } + if (isError) + newErrorCount++; + else + newWarningCount++; } - if (isError) newErrorCount++; else newWarningCount++; } - } - if (oldProblems != null) { - next : for (int i = 0, l = oldProblems.length; i < l; i++) { - IMarker oldProblem = oldProblems[i]; - if (oldProblem == null) continue next; // already matched up with a new problem - boolean wasError = IMarker.SEVERITY_ERROR - == oldProblem.getAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); - String message = oldProblem.getAttribute(IMarker.MESSAGE, ""); //$NON-NLS-1$ - - if (newProblems != null) { - for (int j = 0, m = newProblems.length; j < m; j++) { - IProblem pb = newProblems[j]; - if (pb.getID() == IProblem.Task) continue; // skip task - if (wasError == pb.isError() && message.equals(pb.getMessage())) - continue next; + if (oldProblems != null) { + next: for (int i = 0, l = oldProblems.length; i < l; i++) { + IMarker oldProblem = oldProblems[i]; + if (oldProblem == null) + continue next; // already matched up with a new problem + boolean wasError = IMarker.SEVERITY_ERROR == oldProblem + .getAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); + String message = oldProblem.getAttribute(IMarker.MESSAGE, ""); //$NON-NLS-1$ + + if (newProblems != null) { + for (int j = 0, m = newProblems.length; j < m; j++) { + IProblem pb = newProblems[j]; + if (pb.getID() == IProblem.Task) + continue; // skip task + if (wasError == pb.isError() + && message.equals(pb.getMessage())) + continue next; + } } + if (wasError) + fixedErrorCount++; + else + fixedWarningCount++; } - if (wasError) fixedErrorCount++; else fixedWarningCount++; } } -} -public void updateProgress(float percentComplete) { - if (percentComplete > this.percentComplete) { - this.percentComplete = Math.min(percentComplete, 1.0f); - int work = Math.round(this.percentComplete * this.totalWork); - if (work > this.workDone) { - if (monitor != null) - monitor.worked(work - this.workDone); - //if (JavaBuilder.DEBUG) - //System.out.println(java.text.NumberFormat.getPercentInstance().format(this.percentComplete)); - this.workDone = work; + public void updateProgress(float percentComplete) { + if (percentComplete > this.percentComplete) { + this.percentComplete = Math.min(percentComplete, 1.0f); + int work = Math.round(this.percentComplete * this.totalWork); + if (work > this.workDone) { + if (monitor != null) + monitor.worked(work - this.workDone); + // if (JavaBuilder.DEBUG) + // System.out.println(java.text.NumberFormat.getPercentInstance().format(this.percentComplete)); + this.workDone = work; + } } } -} -public void updateProgressDelta(float percentWorked) { - updateProgress(percentComplete + percentWorked); -} + public void updateProgressDelta(float percentWorked) { + updateProgress(percentComplete + percentWorked); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ClasspathDirectory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ClasspathDirectory.java index 30a42a8..d99d121 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ClasspathDirectory.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ClasspathDirectory.java @@ -20,97 +20,119 @@ import org.eclipse.core.runtime.IPath; class ClasspathDirectory extends ClasspathLocation { -IContainer binaryFolder; // includes .class files for a single directory -boolean isOutputFolder; -String binaryLocation; -SimpleLookupTable directoryCache; -String[] missingPackageHolder = new String[1]; - -ClasspathDirectory(IContainer binaryFolder, boolean isOutputFolder) { - this.binaryFolder = binaryFolder; - this.isOutputFolder = isOutputFolder; -// IPath location = binaryFolder.getLocation(); -// this.binaryLocation = location != null ? location.addTrailingSeparator().toString() : ""; //$NON-NLS-1$ - this.binaryLocation = ""; - this.directoryCache = new SimpleLookupTable(5); -} + IContainer binaryFolder; // includes .class files for a single directory -public void cleanup() { - this.directoryCache = null; -} + boolean isOutputFolder; -String[] directoryList(String qualifiedPackageName) { - String[] dirList = (String[]) directoryCache.get(qualifiedPackageName); - if (dirList == missingPackageHolder) return null; // package exists in another classpath directory or jar - if (dirList != null) return dirList; - - try { - IResource container = binaryFolder.findMember(qualifiedPackageName); // this is a case-sensitive check - if (container instanceof IContainer) { - IResource[] members = ((IContainer) container).members(); - dirList = new String[members.length]; - int index = 0; - for (int i = 0, l = members.length; i < l; i++) { - IResource m = members[i]; -// if (m.getType() == IResource.FILE && ProjectPrefUtil.isClassFileName(m.getName())) -// // add exclusion pattern check here if we want to hide .class files -// dirList[index++] = m.getName(); - } - if (index < dirList.length) - System.arraycopy(dirList, 0, dirList = new String[index], 0, index); - directoryCache.put(qualifiedPackageName, dirList); + String binaryLocation; + + SimpleLookupTable directoryCache; + + String[] missingPackageHolder = new String[1]; + + ClasspathDirectory(IContainer binaryFolder, boolean isOutputFolder) { + this.binaryFolder = binaryFolder; + this.isOutputFolder = isOutputFolder; + // IPath location = binaryFolder.getLocation(); + // this.binaryLocation = location != null ? + // location.addTrailingSeparator().toString() : ""; //$NON-NLS-1$ + this.binaryLocation = ""; + this.directoryCache = new SimpleLookupTable(5); + } + + public void cleanup() { + this.directoryCache = null; + } + + String[] directoryList(String qualifiedPackageName) { + String[] dirList = (String[]) directoryCache.get(qualifiedPackageName); + if (dirList == missingPackageHolder) + return null; // package exists in another classpath directory or + // jar + if (dirList != null) return dirList; + + try { + IResource container = binaryFolder.findMember(qualifiedPackageName); // this + // is a + // case-sensitive + // check + if (container instanceof IContainer) { + IResource[] members = ((IContainer) container).members(); + dirList = new String[members.length]; + int index = 0; + for (int i = 0, l = members.length; i < l; i++) { + IResource m = members[i]; + // if (m.getType() == IResource.FILE && + // ProjectPrefUtil.isClassFileName(m.getName())) + // // add exclusion pattern check here if we want to hide + // .class files + // dirList[index++] = m.getName(); + } + if (index < dirList.length) + System.arraycopy(dirList, 0, dirList = new String[index], + 0, index); + directoryCache.put(qualifiedPackageName, dirList); + return dirList; + } + } catch (CoreException ignored) { } - } catch(CoreException ignored) { + directoryCache.put(qualifiedPackageName, missingPackageHolder); + return null; } - directoryCache.put(qualifiedPackageName, missingPackageHolder); - return null; -} - -boolean doesFileExist(String fileName, String qualifiedPackageName, String qualifiedFullName) { - String[] dirList = directoryList(qualifiedPackageName); - if (dirList == null) return false; // most common case - for (int i = dirList.length; --i >= 0;) - if (fileName.equals(dirList[i])) - return true; - return false; -} + boolean doesFileExist(String fileName, String qualifiedPackageName, + String qualifiedFullName) { + String[] dirList = directoryList(qualifiedPackageName); + if (dirList == null) + return false; // most common case -public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ClasspathDirectory)) return false; + for (int i = dirList.length; --i >= 0;) + if (fileName.equals(dirList[i])) + return true; + return false; + } - return binaryFolder.equals(((ClasspathDirectory) o).binaryFolder); -} + public boolean equals(Object o) { + if (this == o) + return true; + if (!(o instanceof ClasspathDirectory)) + return false; -public NameEnvironmentAnswer findClass(String binaryFileName, String qualifiedPackageName, String qualifiedBinaryFileName) { - if (!doesFileExist(binaryFileName, qualifiedPackageName, qualifiedBinaryFileName)) return null; // most common case + return binaryFolder.equals(((ClasspathDirectory) o).binaryFolder); + } -// try { -// ClassFileReader reader = ClassFileReader.read(binaryLocation + qualifiedBinaryFileName); -// if (reader != null) return new NameEnvironmentAnswer(reader); -// } catch (Exception e) {} // treat as if class file is missing - return null; -} + public NameEnvironmentAnswer findClass(String binaryFileName, + String qualifiedPackageName, String qualifiedBinaryFileName) { + if (!doesFileExist(binaryFileName, qualifiedPackageName, + qualifiedBinaryFileName)) + return null; // most common case + + // try { + // ClassFileReader reader = ClassFileReader.read(binaryLocation + + // qualifiedBinaryFileName); + // if (reader != null) return new NameEnvironmentAnswer(reader); + // } catch (Exception e) {} // treat as if class file is missing + return null; + } -public IPath getProjectRelativePath() { - return binaryFolder.getProjectRelativePath(); -} + public IPath getProjectRelativePath() { + return binaryFolder.getProjectRelativePath(); + } -public boolean isOutputFolder() { - return isOutputFolder; -} + public boolean isOutputFolder() { + return isOutputFolder; + } -public boolean isPackage(String qualifiedPackageName) { - return directoryList(qualifiedPackageName) != null; -} + public boolean isPackage(String qualifiedPackageName) { + return directoryList(qualifiedPackageName) != null; + } -public void reset() { - this.directoryCache = new SimpleLookupTable(5); -} + public void reset() { + this.directoryCache = new SimpleLookupTable(5); + } -public String toString() { - return "Binary classpath directory " + binaryFolder.getFullPath().toString(); //$NON-NLS-1$ -} + public String toString() { + return "Binary classpath directory " + binaryFolder.getFullPath().toString(); //$NON-NLS-1$ + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ClasspathLocation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ClasspathLocation.java index 993422d..81e2a2d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ClasspathLocation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ClasspathLocation.java @@ -17,36 +17,41 @@ import org.eclipse.core.runtime.IPath; public abstract class ClasspathLocation { -static ClasspathLocation forSourceFolder(IContainer sourceFolder, IContainer outputFolder, char[][] exclusionPatterns) { - return new ClasspathMultiDirectory(sourceFolder, outputFolder, exclusionPatterns); -} + static ClasspathLocation forSourceFolder(IContainer sourceFolder, + IContainer outputFolder, char[][] exclusionPatterns) { + return new ClasspathMultiDirectory(sourceFolder, outputFolder, + exclusionPatterns); + } -public static ClasspathLocation forBinaryFolder(IContainer binaryFolder, boolean isOutputFolder) { - return new ClasspathDirectory(binaryFolder, isOutputFolder); -} + public static ClasspathLocation forBinaryFolder(IContainer binaryFolder, + boolean isOutputFolder) { + return new ClasspathDirectory(binaryFolder, isOutputFolder); + } -//static ClasspathLocation forLibrary(String libraryPathname) { -// return new ClasspathJar(libraryPathname); -//} + // static ClasspathLocation forLibrary(String libraryPathname) { + // return new ClasspathJar(libraryPathname); + // } -//static ClasspathLocation forLibrary(IFile library) { -// return new ClasspathJar(library); -//} + // static ClasspathLocation forLibrary(IFile library) { + // return new ClasspathJar(library); + // } -public abstract NameEnvironmentAnswer findClass(String binaryFileName, String qualifiedPackageName, String qualifiedBinaryFileName); + public abstract NameEnvironmentAnswer findClass(String binaryFileName, + String qualifiedPackageName, String qualifiedBinaryFileName); -public abstract IPath getProjectRelativePath(); + public abstract IPath getProjectRelativePath(); -public boolean isOutputFolder() { - return false; -} + public boolean isOutputFolder() { + return false; + } -public abstract boolean isPackage(String qualifiedPackageName); + public abstract boolean isPackage(String qualifiedPackageName); -// free anything which is not required when the state is saved -public void cleanup() { -} -// reset any internal caches before another compile loop starts -public void reset() { -} + // free anything which is not required when the state is saved + public void cleanup() { + } + + // reset any internal caches before another compile loop starts + public void reset() { + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ClasspathMultiDirectory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ClasspathMultiDirectory.java index 077fa45..90e765a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ClasspathMultiDirectory.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ClasspathMultiDirectory.java @@ -16,33 +16,43 @@ import org.eclipse.core.resources.IContainer; class ClasspathMultiDirectory extends ClasspathDirectory { -IContainer sourceFolder; -char[][] exclusionPatterns; // used by builders when walking source folders -boolean hasIndependentOutputFolder; // if output folder is not equal to any of the source folders - -ClasspathMultiDirectory(IContainer sourceFolder, IContainer binaryFolder, char[][] exclusionPatterns) { - super(binaryFolder, true); - - this.sourceFolder = sourceFolder; - this.exclusionPatterns = exclusionPatterns; - this.hasIndependentOutputFolder = false; - - // handle the case when a state rebuilds a source folder - if (this.exclusionPatterns != null && this.exclusionPatterns.length == 0) - this.exclusionPatterns = null; -} - -public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ClasspathMultiDirectory)) return false; - - ClasspathMultiDirectory md = (ClasspathMultiDirectory) o; - return sourceFolder.equals(md.sourceFolder) && binaryFolder.equals(md.binaryFolder) - && CharOperation.equals(exclusionPatterns, md.exclusionPatterns); -} - -public String toString() { - return "Source classpath directory " + sourceFolder.getFullPath().toString() + //$NON-NLS-1$ - " with binary directory " + binaryFolder.getFullPath().toString(); //$NON-NLS-1$ -} + IContainer sourceFolder; + + char[][] exclusionPatterns; // used by builders when walking source folders + + boolean hasIndependentOutputFolder; // if output folder is not equal to any + // of the source folders + + ClasspathMultiDirectory(IContainer sourceFolder, IContainer binaryFolder, + char[][] exclusionPatterns) { + super(binaryFolder, true); + + this.sourceFolder = sourceFolder; + this.exclusionPatterns = exclusionPatterns; + this.hasIndependentOutputFolder = false; + + // handle the case when a state rebuilds a source folder + if (this.exclusionPatterns != null + && this.exclusionPatterns.length == 0) + this.exclusionPatterns = null; + } + + public boolean equals(Object o) { + if (this == o) + return true; + if (!(o instanceof ClasspathMultiDirectory)) + return false; + + ClasspathMultiDirectory md = (ClasspathMultiDirectory) o; + return sourceFolder.equals(md.sourceFolder) + && binaryFolder.equals(md.binaryFolder) + && CharOperation + .equals(exclusionPatterns, md.exclusionPatterns); + } + + public String toString() { + return "Source classpath directory " + sourceFolder.getFullPath().toString() + //$NON-NLS-1$ + " with binary directory " + + binaryFolder.getFullPath().toString(); //$NON-NLS-1$ + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ImageBuilderInternalException.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ImageBuilderInternalException.java index 8de3250..5c1c6bb 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ImageBuilderInternalException.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ImageBuilderInternalException.java @@ -13,28 +13,28 @@ package net.sourceforge.phpdt.internal.core.builder; import org.eclipse.core.runtime.CoreException; /** - * Exception thrown when there is an internal error in the image builder. - * May wrapper another exception. + * Exception thrown when there is an internal error in the image builder. May + * wrapper another exception. */ public class ImageBuilderInternalException extends RuntimeException { -protected CoreException coreException; + protected CoreException coreException; -public ImageBuilderInternalException(CoreException e) { - this.coreException = e; -} + public ImageBuilderInternalException(CoreException e) { + this.coreException = e; + } -public CoreException getThrowable() { - return coreException; -} + public CoreException getThrowable() { + return coreException; + } -public void printStackTrace() { - if (coreException != null) { - System.err.println(this); - System.err.println("Stack trace of embedded core exception:"); //$NON-NLS-1$ - coreException.printStackTrace(); - } else { - super.printStackTrace(); + public void printStackTrace() { + if (coreException != null) { + System.err.println(this); + System.err.println("Stack trace of embedded core exception:"); //$NON-NLS-1$ + coreException.printStackTrace(); + } else { + super.printStackTrace(); + } } } -} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/IncrementalImageBuilder.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/IncrementalImageBuilder.java index fb7a43a..260c29f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/IncrementalImageBuilder.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/IncrementalImageBuilder.java @@ -29,720 +29,797 @@ import org.eclipse.core.runtime.IPath; * The incremental image builder */ public class IncrementalImageBuilder extends AbstractImageBuilder { - protected ArrayList sourceFiles; + protected ArrayList sourceFiles; - protected ArrayList previousSourceFiles; + protected ArrayList previousSourceFiles; - protected ArrayList qualifiedStrings; + protected ArrayList qualifiedStrings; - protected ArrayList simpleStrings; + protected ArrayList simpleStrings; - protected SimpleLookupTable secondaryTypesToRemove; + protected SimpleLookupTable secondaryTypesToRemove; - protected boolean hasStructuralChanges; + protected boolean hasStructuralChanges; - protected int compileLoop; + protected int compileLoop; - public static int MaxCompileLoop = 5; // perform a full build if it takes + public static int MaxCompileLoop = 5; // perform a full build if it takes - // more than ? incremental compile - // loops - protected IncrementalImageBuilder(PHPBuilder javaBuilder) { - super(javaBuilder); - this.nameEnvironment.isIncrementalBuild = true; - this.newState.copyFrom(javaBuilder.lastState); - this.sourceFiles = new ArrayList(33); - this.previousSourceFiles = null; - this.qualifiedStrings = new ArrayList(33); - this.simpleStrings = new ArrayList(33); - this.hasStructuralChanges = false; - this.compileLoop = 0; - } + // more than ? incremental compile + // loops + protected IncrementalImageBuilder(PHPBuilder javaBuilder) { + super(javaBuilder); + this.nameEnvironment.isIncrementalBuild = true; + this.newState.copyFrom(javaBuilder.lastState); + this.sourceFiles = new ArrayList(33); + this.previousSourceFiles = null; + this.qualifiedStrings = new ArrayList(33); + this.simpleStrings = new ArrayList(33); + this.hasStructuralChanges = false; + this.compileLoop = 0; + } - public boolean build(SimpleLookupTable deltas) { - // initialize builder - // walk this project's deltas, find changed source files - // walk prereq projects' deltas, find changed class files & add affected - // source files - // use the build state # to skip the deltas for certain prereq projects - // ignore changed zip/jar files since they caused a full build - // compile the source files & acceptResult() - // compare the produced class files against the existing ones on disk - // recompile all dependent source files of any type with structural changes - // or new/removed secondary type - // keep a loop counter to abort & perform a full build - if (PHPBuilder.DEBUG) - System.out.println("INCREMENTAL build"); //$NON-NLS-1$ - try { - resetCollections(); - notifier.subTask(Util.bind("build.analyzingDeltas")); //$NON-NLS-1$ - IResourceDelta sourceDelta = (IResourceDelta) deltas.get(javaBuilder.currentProject); - if (sourceDelta != null) { - sourceDelta.accept(new ParserVisitor(javaBuilder.currentProject, notifier.monitor)); + public boolean build(SimpleLookupTable deltas) { + // initialize builder + // walk this project's deltas, find changed source files + // walk prereq projects' deltas, find changed class files & add affected + // source files + // use the build state # to skip the deltas for certain prereq projects + // ignore changed zip/jar files since they caused a full build + // compile the source files & acceptResult() + // compare the produced class files against the existing ones on disk + // recompile all dependent source files of any type with structural + // changes + // or new/removed secondary type + // keep a loop counter to abort & perform a full build + if (PHPBuilder.DEBUG) + System.out.println("INCREMENTAL build"); //$NON-NLS-1$ + try { + resetCollections(); + notifier.subTask(Util.bind("build.analyzingDeltas")); //$NON-NLS-1$ + IResourceDelta sourceDelta = (IResourceDelta) deltas + .get(javaBuilder.currentProject); + if (sourceDelta != null) { + sourceDelta.accept(new ParserVisitor( + javaBuilder.currentProject, notifier.monitor)); - if (!findSourceFiles(sourceDelta)) - return false; - } - notifier.updateProgressDelta(0.10f); - // Object[] keyTable = deltas.keyTable; - // Object[] valueTable = deltas.valueTable; - //// final IdentifierIndexManager indexManager = PHPeclipsePlugin.getDefault() - //// .getIndexManager(javaBuilder.currentProject); - // for (int i = 0, l = valueTable.length; i < l; i++) { - // IResourceDelta delta = (IResourceDelta) valueTable[i]; - // if (delta != null) { - // IResource resource = delta.getResource(); - // int resourceType = resource.getType(); - // if (resourceType == IResource.FILE) { - // switch (delta.getKind()) { - // case IResourceDelta.ADDED : - // if ((resource.getFileExtension() != null) - // && PHPFileUtil.isPHPFile((IFile) resource)) { - // // update indexfile for the project: - //// indexManager.addFile((IFile) resource); - // } - // break; - // case IResourceDelta.CHANGED : - // if ((resource.getFileExtension() != null) - // && PHPFileUtil.isPHPFile((IFile) resource)) { - // // update indexfile for the project: - //// indexManager.changeFile((IFile) resource); - // } - // break; - // case IResourceDelta.REMOVED : - // if ((resource.getFileExtension() != null) - // && PHPFileUtil.isPHPFile((IFile) resource)) { - // // update indexfile for the project: - //// indexManager.removeFile((IFile) resource); - // } - // break; - // } - // } - // // ClasspathLocation[] classFoldersAndJars = (ClasspathLocation[]) - // // javaBuilder.binaryLocationsPerProject.get(keyTable[i]); - // // if (classFoldersAndJars != null) - // // if (!findAffectedSourceFiles(delta, classFoldersAndJars)) return - // // false; - // } - // } - notifier.updateProgressDelta(0.10f); - notifier.subTask(Util.bind("build.analyzingSources")); //$NON-NLS-1$ - addAffectedSourceFiles(); - notifier.updateProgressDelta(0.05f); - this.compileLoop = 0; - float increment = 0.40f; - while (sourceFiles.size() > 0) { // added to in acceptResult - if (++this.compileLoop > MaxCompileLoop) { - if (PHPBuilder.DEBUG) - System.out.println("ABORTING incremental build... exceeded loop count"); //$NON-NLS-1$ - return false; - } - notifier.checkCancel(); - SourceFile[] allSourceFiles = new SourceFile[sourceFiles.size()]; - sourceFiles.toArray(allSourceFiles); - resetCollections(); - workQueue.addAll(allSourceFiles); - notifier.setProgressPerCompilationUnit(increment / allSourceFiles.length); - increment = increment / 2; - compile(allSourceFiles); - // removeSecondaryTypes(); - addAffectedSourceFiles(); - } - if (this.hasStructuralChanges && javaBuilder.javaProject.hasCycleMarker()) - javaBuilder.mustPropagateStructuralChanges(); - } catch (AbortIncrementalBuildException e) { - // abort the incremental build and let the batch builder handle the - // problem - if (PHPBuilder.DEBUG) - System.out.println("ABORTING incremental build... cannot find " + e.qualifiedTypeName + //$NON-NLS-1$ - ". Could have been renamed inside its existing source file."); //$NON-NLS-1$ - return false; - } catch (CoreException e) { - throw internalException(e); - } finally { - cleanUp(); - } - return true; - } + if (!findSourceFiles(sourceDelta)) + return false; + } + notifier.updateProgressDelta(0.10f); + // Object[] keyTable = deltas.keyTable; + // Object[] valueTable = deltas.valueTable; + // // final IdentifierIndexManager indexManager = + // PHPeclipsePlugin.getDefault() + // // .getIndexManager(javaBuilder.currentProject); + // for (int i = 0, l = valueTable.length; i < l; i++) { + // IResourceDelta delta = (IResourceDelta) valueTable[i]; + // if (delta != null) { + // IResource resource = delta.getResource(); + // int resourceType = resource.getType(); + // if (resourceType == IResource.FILE) { + // switch (delta.getKind()) { + // case IResourceDelta.ADDED : + // if ((resource.getFileExtension() != null) + // && PHPFileUtil.isPHPFile((IFile) resource)) { + // // update indexfile for the project: + // // indexManager.addFile((IFile) resource); + // } + // break; + // case IResourceDelta.CHANGED : + // if ((resource.getFileExtension() != null) + // && PHPFileUtil.isPHPFile((IFile) resource)) { + // // update indexfile for the project: + // // indexManager.changeFile((IFile) resource); + // } + // break; + // case IResourceDelta.REMOVED : + // if ((resource.getFileExtension() != null) + // && PHPFileUtil.isPHPFile((IFile) resource)) { + // // update indexfile for the project: + // // indexManager.removeFile((IFile) resource); + // } + // break; + // } + // } + // // ClasspathLocation[] classFoldersAndJars = + // (ClasspathLocation[]) + // // javaBuilder.binaryLocationsPerProject.get(keyTable[i]); + // // if (classFoldersAndJars != null) + // // if (!findAffectedSourceFiles(delta, classFoldersAndJars)) + // return + // // false; + // } + // } + notifier.updateProgressDelta(0.10f); + notifier.subTask(Util.bind("build.analyzingSources")); //$NON-NLS-1$ + addAffectedSourceFiles(); + notifier.updateProgressDelta(0.05f); + this.compileLoop = 0; + float increment = 0.40f; + while (sourceFiles.size() > 0) { // added to in acceptResult + if (++this.compileLoop > MaxCompileLoop) { + if (PHPBuilder.DEBUG) + System.out + .println("ABORTING incremental build... exceeded loop count"); //$NON-NLS-1$ + return false; + } + notifier.checkCancel(); + SourceFile[] allSourceFiles = new SourceFile[sourceFiles.size()]; + sourceFiles.toArray(allSourceFiles); + resetCollections(); + workQueue.addAll(allSourceFiles); + notifier.setProgressPerCompilationUnit(increment + / allSourceFiles.length); + increment = increment / 2; + compile(allSourceFiles); + // removeSecondaryTypes(); + addAffectedSourceFiles(); + } + if (this.hasStructuralChanges + && javaBuilder.javaProject.hasCycleMarker()) + javaBuilder.mustPropagateStructuralChanges(); + } catch (AbortIncrementalBuildException e) { + // abort the incremental build and let the batch builder handle the + // problem + if (PHPBuilder.DEBUG) + System.out + .println("ABORTING incremental build... cannot find " + e.qualifiedTypeName + //$NON-NLS-1$ + ". Could have been renamed inside its existing source file."); //$NON-NLS-1$ + return false; + } catch (CoreException e) { + throw internalException(e); + } finally { + cleanUp(); + } + return true; + } - protected void addAffectedSourceFiles() { - if (qualifiedStrings.isEmpty() && simpleStrings.isEmpty()) - return; - // the qualifiedStrings are of the form 'p1/p2' & the simpleStrings are - // just 'X' - // char[][][] qualifiedNames = ReferenceCollection - // .internQualifiedNames(qualifiedStrings); - // if a well known qualified name was found then we can skip over these - // if (qualifiedNames.length < qualifiedStrings.size()) - // qualifiedNames = null; - // char[][] simpleNames = ReferenceCollection.internSimpleNames(simpleStrings); - // if a well known name was found then we can skip over these - // if (simpleNames.length < simpleStrings.size()) - // simpleNames = null; - // Object[] keyTable = newState.references.keyTable; - // Object[] valueTable = newState.references.valueTable; - // next : for (int i = 0, l = valueTable.length; i < l; i++) { - // ReferenceCollection refs = (ReferenceCollection) valueTable[i]; - // if (refs != null && refs.includes(qualifiedNames, simpleNames)) { - // String typeLocator = (String) keyTable[i]; - // IFile file = javaBuilder.currentProject.getFile(typeLocator); - // if (file.exists()) { - // ClasspathMultiDirectory md = sourceLocations[0]; - // if (sourceLocations.length > 1) { - // IPath sourceFileFullPath = file.getFullPath(); - // for (int j = 0, m = sourceLocations.length; j < m; j++) { - // if (sourceLocations[j].sourceFolder.getFullPath().isPrefixOf( - // sourceFileFullPath)) { - // md = sourceLocations[j]; - // if (md.exclusionPatterns == null - // || !ProjectPrefUtil.isExcluded(file, md.exclusionPatterns)) - // break; - // } - // } - // } - // SourceFile sourceFile = new SourceFile(file, md, encoding); - // if (sourceFiles.contains(sourceFile)) - // continue next; - // if (compiledAllAtOnce && previousSourceFiles != null - // && previousSourceFiles.contains(sourceFile)) - // continue next; // can skip previously compiled files since already - // // saw hierarchy related problems - // if (PHPBuilder.DEBUG) - // System.out.println(" adding affected source file " + typeLocator); //$NON-NLS-1$ - // // // update indexfile for the project: - // sourceFiles.add(sourceFile); - // } - // } - // } - } + protected void addAffectedSourceFiles() { + if (qualifiedStrings.isEmpty() && simpleStrings.isEmpty()) + return; + // the qualifiedStrings are of the form 'p1/p2' & the simpleStrings are + // just 'X' + // char[][][] qualifiedNames = ReferenceCollection + // .internQualifiedNames(qualifiedStrings); + // if a well known qualified name was found then we can skip over these + // if (qualifiedNames.length < qualifiedStrings.size()) + // qualifiedNames = null; + // char[][] simpleNames = + // ReferenceCollection.internSimpleNames(simpleStrings); + // if a well known name was found then we can skip over these + // if (simpleNames.length < simpleStrings.size()) + // simpleNames = null; + // Object[] keyTable = newState.references.keyTable; + // Object[] valueTable = newState.references.valueTable; + // next : for (int i = 0, l = valueTable.length; i < l; i++) { + // ReferenceCollection refs = (ReferenceCollection) valueTable[i]; + // if (refs != null && refs.includes(qualifiedNames, simpleNames)) { + // String typeLocator = (String) keyTable[i]; + // IFile file = javaBuilder.currentProject.getFile(typeLocator); + // if (file.exists()) { + // ClasspathMultiDirectory md = sourceLocations[0]; + // if (sourceLocations.length > 1) { + // IPath sourceFileFullPath = file.getFullPath(); + // for (int j = 0, m = sourceLocations.length; j < m; j++) { + // if (sourceLocations[j].sourceFolder.getFullPath().isPrefixOf( + // sourceFileFullPath)) { + // md = sourceLocations[j]; + // if (md.exclusionPatterns == null + // || !ProjectPrefUtil.isExcluded(file, md.exclusionPatterns)) + // break; + // } + // } + // } + // SourceFile sourceFile = new SourceFile(file, md, encoding); + // if (sourceFiles.contains(sourceFile)) + // continue next; + // if (compiledAllAtOnce && previousSourceFiles != null + // && previousSourceFiles.contains(sourceFile)) + // continue next; // can skip previously compiled files since already + // // saw hierarchy related problems + // if (PHPBuilder.DEBUG) + // System.out.println(" adding affected source file " + typeLocator); + // //$NON-NLS-1$ + // // // update indexfile for the project: + // sourceFiles.add(sourceFile); + // } + // } + // } + } - protected void addDependentsOf(IPath path, boolean hasStructuralChanges) { - if (hasStructuralChanges) { - newState.tagAsStructurallyChanged(); - this.hasStructuralChanges = true; - } - // the qualifiedStrings are of the form 'p1/p2' & the simpleStrings are - // just 'X' - path = path.setDevice(null); - String packageName = path.removeLastSegments(1).toString(); - if (!qualifiedStrings.contains(packageName)) - qualifiedStrings.add(packageName); - String typeName = path.lastSegment(); - int memberIndex = typeName.indexOf('$'); - if (memberIndex > 0) - typeName = typeName.substring(0, memberIndex); - if (!simpleStrings.contains(typeName)) { - if (PHPBuilder.DEBUG) - System.out.println(" will look for dependents of " //$NON-NLS-1$ - + typeName + " in " + packageName); //$NON-NLS-1$ - simpleStrings.add(typeName); - } - } + protected void addDependentsOf(IPath path, boolean hasStructuralChanges) { + if (hasStructuralChanges) { + newState.tagAsStructurallyChanged(); + this.hasStructuralChanges = true; + } + // the qualifiedStrings are of the form 'p1/p2' & the simpleStrings are + // just 'X' + path = path.setDevice(null); + String packageName = path.removeLastSegments(1).toString(); + if (!qualifiedStrings.contains(packageName)) + qualifiedStrings.add(packageName); + String typeName = path.lastSegment(); + int memberIndex = typeName.indexOf('$'); + if (memberIndex > 0) + typeName = typeName.substring(0, memberIndex); + if (!simpleStrings.contains(typeName)) { + if (PHPBuilder.DEBUG) + System.out.println(" will look for dependents of " //$NON-NLS-1$ + + typeName + " in " + packageName); //$NON-NLS-1$ + simpleStrings.add(typeName); + } + } - protected void cleanUp() { - super.cleanUp(); - this.sourceFiles = null; - this.previousSourceFiles = null; - this.qualifiedStrings = null; - this.simpleStrings = null; - this.secondaryTypesToRemove = null; - this.hasStructuralChanges = false; - this.compileLoop = 0; - } + protected void cleanUp() { + super.cleanUp(); + this.sourceFiles = null; + this.previousSourceFiles = null; + this.qualifiedStrings = null; + this.simpleStrings = null; + this.secondaryTypesToRemove = null; + this.hasStructuralChanges = false; + this.compileLoop = 0; + } - //protected boolean findAffectedSourceFiles(IResourceDelta delta, - // ClasspathLocation[] classFoldersAndJars) { - // for (int i = 0, l = classFoldersAndJars.length; i < l; i++) { - // ClasspathLocation bLocation = classFoldersAndJars[i]; - // // either a .class file folder or a zip/jar file - // if (bLocation != null) { // skip unchanged output folder - // IPath p = bLocation.getProjectRelativePath(); - // if (p != null) { - // IResourceDelta binaryDelta = delta.findMember(p); - // if (binaryDelta != null) { - // if (bLocation instanceof ClasspathJar) { - // if (JavaBuilder.DEBUG) - // System.out.println("ABORTING incremental build... found delta to jar/zip - // file"); //$NON-NLS-1$ - // return false; // do full build since jar file was changed (added/removed - // were caught as classpath change) - // } - // if (binaryDelta.getKind() == IResourceDelta.ADDED || binaryDelta.getKind() - // == IResourceDelta.REMOVED) { - // if (JavaBuilder.DEBUG) - // System.out.println("ABORTING incremental build... found added/removed - // binary folder"); //$NON-NLS-1$ - // return false; // added/removed binary folder should not make it here - // (classpath change), but handle anyways - // } - // int segmentCount = binaryDelta.getFullPath().segmentCount(); - // IResourceDelta[] children = binaryDelta.getAffectedChildren(); // .class - // files from class folder - // for (int j = 0, m = children.length; j < m; j++) - // findAffectedSourceFiles(children[j], segmentCount); - // notifier.checkCancel(); - // } - // } - // } - // } - // return true; - //} - protected void findAffectedSourceFiles(IResourceDelta binaryDelta, int segmentCount) { - // When a package becomes a type or vice versa, expect 2 deltas, - // one on the folder & one on the class file - IResource resource = binaryDelta.getResource(); - switch (resource.getType()) { - case IResource.FOLDER: - switch (binaryDelta.getKind()) { - case IResourceDelta.ADDED: - case IResourceDelta.REMOVED: - IPath packagePath = resource.getFullPath().removeFirstSegments(segmentCount); - String packageName = packagePath.toString(); - if (binaryDelta.getKind() == IResourceDelta.ADDED) { - // see if any known source file is from the same package... - // classpath already includes new package - // if (!newState.isKnownPackage(packageName)) { - // if (PHPBuilder.DEBUG) - // System.out.println("Found added package " + packageName); //$NON-NLS-1$ - // addDependentsOf(packagePath, false); - // return; - // } - if (PHPBuilder.DEBUG) - System.out.println("Skipped dependents of added package " + packageName); //$NON-NLS-1$ - } else { - // see if the package still exists on the classpath - // if (!nameEnvironment.isPackage(packageName)) { - // if (JavaBuilder.DEBUG) - // System.out.println("Found removed package " + packageName); - // //$NON-NLS-1$ - // addDependentsOf(packagePath, false); - // return; - // } - if (PHPBuilder.DEBUG) - System.out.println("Skipped dependents of removed package " + packageName); //$NON-NLS-1$ - } - // fall thru & traverse the sub-packages and .class files - case IResourceDelta.CHANGED: - IResourceDelta[] children = binaryDelta.getAffectedChildren(); - for (int i = 0, l = children.length; i < l; i++) - findAffectedSourceFiles(children[i], segmentCount); - } - return; - case IResource.FILE: - // if (ProjectPrefUtil.isClassFileName(resource.getName())) { - // IPath typePath = - // resource.getFullPath().removeFirstSegments(segmentCount).removeFileExtension(); - // switch (binaryDelta.getKind()) { - // case IResourceDelta.ADDED : - // case IResourceDelta.REMOVED : - // if (JavaBuilder.DEBUG) - // System.out.println("Found added/removed class file " + typePath); - // //$NON-NLS-1$ - // addDependentsOf(typePath, false); - // return; - // case IResourceDelta.CHANGED : - // if ((binaryDelta.getFlags() & IResourceDelta.CONTENT) == 0) - // return; // skip it since it really isn't changed - // if (JavaBuilder.DEBUG) - // System.out.println("Found changed class file " + typePath); - // //$NON-NLS-1$ - // addDependentsOf(typePath, false); - // } - // return; - // } - } - } + // protected boolean findAffectedSourceFiles(IResourceDelta delta, + // ClasspathLocation[] classFoldersAndJars) { + // for (int i = 0, l = classFoldersAndJars.length; i < l; i++) { + // ClasspathLocation bLocation = classFoldersAndJars[i]; + // // either a .class file folder or a zip/jar file + // if (bLocation != null) { // skip unchanged output folder + // IPath p = bLocation.getProjectRelativePath(); + // if (p != null) { + // IResourceDelta binaryDelta = delta.findMember(p); + // if (binaryDelta != null) { + // if (bLocation instanceof ClasspathJar) { + // if (JavaBuilder.DEBUG) + // System.out.println("ABORTING incremental build... found delta to jar/zip + // file"); //$NON-NLS-1$ + // return false; // do full build since jar file was changed (added/removed + // were caught as classpath change) + // } + // if (binaryDelta.getKind() == IResourceDelta.ADDED || + // binaryDelta.getKind() + // == IResourceDelta.REMOVED) { + // if (JavaBuilder.DEBUG) + // System.out.println("ABORTING incremental build... found added/removed + // binary folder"); //$NON-NLS-1$ + // return false; // added/removed binary folder should not make it here + // (classpath change), but handle anyways + // } + // int segmentCount = binaryDelta.getFullPath().segmentCount(); + // IResourceDelta[] children = binaryDelta.getAffectedChildren(); // .class + // files from class folder + // for (int j = 0, m = children.length; j < m; j++) + // findAffectedSourceFiles(children[j], segmentCount); + // notifier.checkCancel(); + // } + // } + // } + // } + // return true; + // } + protected void findAffectedSourceFiles(IResourceDelta binaryDelta, + int segmentCount) { + // When a package becomes a type or vice versa, expect 2 deltas, + // one on the folder & one on the class file + IResource resource = binaryDelta.getResource(); + switch (resource.getType()) { + case IResource.FOLDER: + switch (binaryDelta.getKind()) { + case IResourceDelta.ADDED: + case IResourceDelta.REMOVED: + IPath packagePath = resource.getFullPath().removeFirstSegments( + segmentCount); + String packageName = packagePath.toString(); + if (binaryDelta.getKind() == IResourceDelta.ADDED) { + // see if any known source file is from the same package... + // classpath already includes new package + // if (!newState.isKnownPackage(packageName)) { + // if (PHPBuilder.DEBUG) + // System.out.println("Found added package " + packageName); + // //$NON-NLS-1$ + // addDependentsOf(packagePath, false); + // return; + // } + if (PHPBuilder.DEBUG) + System.out + .println("Skipped dependents of added package " + packageName); //$NON-NLS-1$ + } else { + // see if the package still exists on the classpath + // if (!nameEnvironment.isPackage(packageName)) { + // if (JavaBuilder.DEBUG) + // System.out.println("Found removed package " + + // packageName); + // //$NON-NLS-1$ + // addDependentsOf(packagePath, false); + // return; + // } + if (PHPBuilder.DEBUG) + System.out + .println("Skipped dependents of removed package " + packageName); //$NON-NLS-1$ + } + // fall thru & traverse the sub-packages and .class files + case IResourceDelta.CHANGED: + IResourceDelta[] children = binaryDelta.getAffectedChildren(); + for (int i = 0, l = children.length; i < l; i++) + findAffectedSourceFiles(children[i], segmentCount); + } + return; + case IResource.FILE: + // if (ProjectPrefUtil.isClassFileName(resource.getName())) { + // IPath typePath = + // resource.getFullPath().removeFirstSegments(segmentCount).removeFileExtension(); + // switch (binaryDelta.getKind()) { + // case IResourceDelta.ADDED : + // case IResourceDelta.REMOVED : + // if (JavaBuilder.DEBUG) + // System.out.println("Found added/removed class file " + typePath); + // //$NON-NLS-1$ + // addDependentsOf(typePath, false); + // return; + // case IResourceDelta.CHANGED : + // if ((binaryDelta.getFlags() & IResourceDelta.CONTENT) == 0) + // return; // skip it since it really isn't changed + // if (JavaBuilder.DEBUG) + // System.out.println("Found changed class file " + typePath); + // //$NON-NLS-1$ + // addDependentsOf(typePath, false); + // } + // return; + // } + } + } - protected boolean findSourceFiles(IResourceDelta delta) throws CoreException { - for (int i = 0, l = sourceLocations.length; i < l; i++) { - ClasspathMultiDirectory md = sourceLocations[i]; - if (md.sourceFolder.equals(javaBuilder.currentProject)) { - // skip nested source & output folders when the project is a source - // folder - int segmentCount = delta.getFullPath().segmentCount(); - IResourceDelta[] children = delta.getAffectedChildren(); - for (int j = 0, m = children.length; j < m; j++) - if (!isExcludedFromProject(children[j].getFullPath())) - findSourceFiles(children[j], md, segmentCount); - } else { - IResourceDelta sourceDelta = delta.findMember(md.sourceFolder.getProjectRelativePath()); - if (sourceDelta != null) { - if (sourceDelta.getKind() == IResourceDelta.REMOVED) { - if (PHPBuilder.DEBUG) - System.out.println("ABORTING incremental build... found removed source folder"); //$NON-NLS-1$ - return false; // removed source folder should not make it here, but - // handle anyways (ADDED is supported) - } - int segmentCount = sourceDelta.getFullPath().segmentCount(); - IResourceDelta[] children = sourceDelta.getAffectedChildren(); - for (int j = 0, m = children.length; j < m; j++) - findSourceFiles(children[j], md, segmentCount); - } - } - notifier.checkCancel(); - } - return true; - } + protected boolean findSourceFiles(IResourceDelta delta) + throws CoreException { + for (int i = 0, l = sourceLocations.length; i < l; i++) { + ClasspathMultiDirectory md = sourceLocations[i]; + if (md.sourceFolder.equals(javaBuilder.currentProject)) { + // skip nested source & output folders when the project is a + // source + // folder + int segmentCount = delta.getFullPath().segmentCount(); + IResourceDelta[] children = delta.getAffectedChildren(); + for (int j = 0, m = children.length; j < m; j++) + if (!isExcludedFromProject(children[j].getFullPath())) + findSourceFiles(children[j], md, segmentCount); + } else { + IResourceDelta sourceDelta = delta.findMember(md.sourceFolder + .getProjectRelativePath()); + if (sourceDelta != null) { + if (sourceDelta.getKind() == IResourceDelta.REMOVED) { + if (PHPBuilder.DEBUG) + System.out + .println("ABORTING incremental build... found removed source folder"); //$NON-NLS-1$ + return false; // removed source folder should not make + // it here, but + // handle anyways (ADDED is supported) + } + int segmentCount = sourceDelta.getFullPath().segmentCount(); + IResourceDelta[] children = sourceDelta + .getAffectedChildren(); + for (int j = 0, m = children.length; j < m; j++) + findSourceFiles(children[j], md, segmentCount); + } + } + notifier.checkCancel(); + } + return true; + } - protected void findSourceFiles(IResourceDelta sourceDelta, ClasspathMultiDirectory md, int segmentCount) throws CoreException { - // When a package becomes a type or vice versa, expect 2 deltas, - // one on the folder & one on the source file - IResource resource = sourceDelta.getResource(); - if (md.exclusionPatterns != null && Util.isExcluded(resource, md.exclusionPatterns)) - return; - switch (resource.getType()) { - case IResource.FOLDER: - switch (sourceDelta.getKind()) { - case IResourceDelta.ADDED: - IPath addedPackagePath = resource.getFullPath().removeFirstSegments(segmentCount); - // createFolder(addedPackagePath, md.binaryFolder); // ensure package - // exists in the - // output folder - // add dependents even when the package thinks it exists to be on - // the safe side - if (PHPBuilder.DEBUG) - System.out.println("Found added package " + addedPackagePath); //$NON-NLS-1$ - addDependentsOf(addedPackagePath, true); - // fall thru & collect all the source files - case IResourceDelta.CHANGED: - IResourceDelta[] children = sourceDelta.getAffectedChildren(); - for (int i = 0, l = children.length; i < l; i++) - findSourceFiles(children[i], md, segmentCount); - return; - case IResourceDelta.REMOVED: - IPath removedPackagePath = resource.getFullPath().removeFirstSegments(segmentCount); - if (sourceLocations.length > 1) { - for (int i = 0, l = sourceLocations.length; i < l; i++) { - if (sourceLocations[i].sourceFolder.getFolder(removedPackagePath).exists()) { - // only a package fragment was removed, same as removing - // multiple source files - // createFolder(removedPackagePath, md.binaryFolder); // ensure - // package - // exists - // in the - // output - // folder - IResourceDelta[] removedChildren = sourceDelta.getAffectedChildren(); - for (int j = 0, m = removedChildren.length; j < m; j++) - findSourceFiles(removedChildren[j], md, segmentCount); - return; - } - } - } - // IFolder removedPackageFolder = md.binaryFolder - // .getFolder(removedPackagePath); - // if (removedPackageFolder.exists()) - // removedPackageFolder.delete(IResource.FORCE, null); - // add dependents even when the package thinks it does not exist to - // be on the safe side - if (PHPBuilder.DEBUG) - System.out.println("Found removed package " + removedPackagePath); //$NON-NLS-1$ - addDependentsOf(removedPackagePath, true); - newState.removePackage(sourceDelta); - } - return; - case IResource.FILE: - String resourceName = resource.getName(); - if (net.sourceforge.phpdt.internal.compiler.util.Util.isJavaFileName(resourceName)) { - IPath typePath = resource.getFullPath().removeFirstSegments(segmentCount).removeFileExtension(); - String typeLocator = resource.getProjectRelativePath().toString(); - switch (sourceDelta.getKind()) { - case IResourceDelta.ADDED: - if (PHPBuilder.DEBUG) - System.out.println("Compile this added source file " + typeLocator); //$NON-NLS-1$ - sourceFiles.add(new SourceFile((IFile) resource, md, encoding)); - String typeName = typePath.toString(); - // if (!newState.isDuplicateLocator(typeName, typeLocator)) { // adding - // // dependents - // // results - // // in - // // 2 - // // duplicate - // // errors - // if (PHPBuilder.DEBUG) - // System.out.println("Found added source file " + typeName); //$NON-NLS-1$ - // addDependentsOf(typePath, true); - // } - return; - case IResourceDelta.REMOVED: - // char[][] definedTypeNames = newState - // .getDefinedTypeNamesFor(typeLocator); - // if (definedTypeNames == null) { // defined a single type matching - // // typePath - // removeClassFile(typePath, md.binaryFolder); - // if ((sourceDelta.getFlags() & IResourceDelta.MOVED_TO) != 0) { - // // remove problems and tasks for a compilation unit that is - // // being moved (to another package or renamed) - // // if the target file is a compilation unit, the new cu will - // // be recompiled - // // if the target file is a non-java resource, then markers - // // are removed - // // see bug 2857 - // IResource movedFile = javaBuilder.workspaceRoot - // .getFile(sourceDelta.getMovedToPath()); - // PHPBuilder.removeProblemsAndTasksFor(movedFile); - // } - // } else { - if (PHPBuilder.DEBUG) - System.out.println("Found removed source file " + typePath.toString()); //$NON-NLS-1$ - addDependentsOf(typePath, true); // add dependents of the - // source file since it may be - // involved in a name - // collision - // if (definedTypeNames.length > 0) { // skip it if it failed to - // // successfully define a - // // type - // IPath packagePath = typePath.removeLastSegments(1); - // for (int i = 0, l = definedTypeNames.length; i < l; i++) - // removeClassFile(packagePath.append(new String( - // definedTypeNames[i])), md.binaryFolder); - // } - // } - // newState.removeLocator(typeLocator); - return; - case IResourceDelta.CHANGED: - if ((sourceDelta.getFlags() & IResourceDelta.CONTENT) == 0) - return; // skip it since it really isn't changed - if (PHPBuilder.DEBUG) - System.out.println("Compile this changed source file " + typeLocator); //$NON-NLS-1$ - sourceFiles.add(new SourceFile((IFile) resource, md, encoding)); - } - return; - // } else if (ProjectPrefUtil.isClassFileName(resourceName)) { - // return; // skip class files - } else if (md.hasIndependentOutputFolder) { - if (javaBuilder.filterExtraResource(resource)) - return; - // copy all other resource deltas to the output folder - IPath resourcePath = resource.getFullPath().removeFirstSegments(segmentCount); - // IResource outputFile = md.binaryFolder.getFile(resourcePath); - switch (sourceDelta.getKind()) { - case IResourceDelta.ADDED: - // if (outputFile.exists()) { - // if (PHPBuilder.DEBUG) - // System.out.println("Deleting existing file " + resourcePath); //$NON-NLS-1$ - // outputFile.delete(IResource.FORCE, null); - // } - if (PHPBuilder.DEBUG) - System.out.println("Copying added file " + resourcePath); //$NON-NLS-1$ - // createFolder(resourcePath.removeLastSegments(1), md.binaryFolder); // ensure - // package - // exists - // in - // the - // output - // folder - // resource.copy(outputFile.getFullPath(), IResource.FORCE, null); - // outputFile.setDerived(true); - return; - case IResourceDelta.REMOVED: - // if (outputFile.exists()) { - // if (PHPBuilder.DEBUG) - // System.out.println("Deleting removed file " + resourcePath); //$NON-NLS-1$ - // outputFile.delete(IResource.FORCE, null); - // } - return; - case IResourceDelta.CHANGED: - if ((sourceDelta.getFlags() & IResourceDelta.CONTENT) == 0) - return; // skip it since it really isn't changed - // if (outputFile.exists()) { - // if (PHPBuilder.DEBUG) - // System.out.println("Deleting existing file " + resourcePath); //$NON-NLS-1$ - // outputFile.delete(IResource.FORCE, null); - // } - if (PHPBuilder.DEBUG) - System.out.println("Copying changed file " + resourcePath); //$NON-NLS-1$ - // createFolder(resourcePath.removeLastSegments(1), md.binaryFolder); // ensure - // package - // exists - // in - // the - // output - // folder - // resource.copy(outputFile.getFullPath(), IResource.FORCE, null); - // outputFile.setDerived(true); - } - return; - } - } - } + protected void findSourceFiles(IResourceDelta sourceDelta, + ClasspathMultiDirectory md, int segmentCount) throws CoreException { + // When a package becomes a type or vice versa, expect 2 deltas, + // one on the folder & one on the source file + IResource resource = sourceDelta.getResource(); + if (md.exclusionPatterns != null + && Util.isExcluded(resource, md.exclusionPatterns)) + return; + switch (resource.getType()) { + case IResource.FOLDER: + switch (sourceDelta.getKind()) { + case IResourceDelta.ADDED: + IPath addedPackagePath = resource.getFullPath() + .removeFirstSegments(segmentCount); + // createFolder(addedPackagePath, md.binaryFolder); // ensure + // package + // exists in the + // output folder + // add dependents even when the package thinks it exists to be + // on + // the safe side + if (PHPBuilder.DEBUG) + System.out + .println("Found added package " + addedPackagePath); //$NON-NLS-1$ + addDependentsOf(addedPackagePath, true); + // fall thru & collect all the source files + case IResourceDelta.CHANGED: + IResourceDelta[] children = sourceDelta.getAffectedChildren(); + for (int i = 0, l = children.length; i < l; i++) + findSourceFiles(children[i], md, segmentCount); + return; + case IResourceDelta.REMOVED: + IPath removedPackagePath = resource.getFullPath() + .removeFirstSegments(segmentCount); + if (sourceLocations.length > 1) { + for (int i = 0, l = sourceLocations.length; i < l; i++) { + if (sourceLocations[i].sourceFolder.getFolder( + removedPackagePath).exists()) { + // only a package fragment was removed, same as + // removing + // multiple source files + // createFolder(removedPackagePath, + // md.binaryFolder); // ensure + // package + // exists + // in the + // output + // folder + IResourceDelta[] removedChildren = sourceDelta + .getAffectedChildren(); + for (int j = 0, m = removedChildren.length; j < m; j++) + findSourceFiles(removedChildren[j], md, + segmentCount); + return; + } + } + } + // IFolder removedPackageFolder = md.binaryFolder + // .getFolder(removedPackagePath); + // if (removedPackageFolder.exists()) + // removedPackageFolder.delete(IResource.FORCE, null); + // add dependents even when the package thinks it does not exist + // to + // be on the safe side + if (PHPBuilder.DEBUG) + System.out + .println("Found removed package " + removedPackagePath); //$NON-NLS-1$ + addDependentsOf(removedPackagePath, true); + newState.removePackage(sourceDelta); + } + return; + case IResource.FILE: + String resourceName = resource.getName(); + if (net.sourceforge.phpdt.internal.compiler.util.Util + .isJavaFileName(resourceName)) { + IPath typePath = resource.getFullPath().removeFirstSegments( + segmentCount).removeFileExtension(); + String typeLocator = resource.getProjectRelativePath() + .toString(); + switch (sourceDelta.getKind()) { + case IResourceDelta.ADDED: + if (PHPBuilder.DEBUG) + System.out + .println("Compile this added source file " + typeLocator); //$NON-NLS-1$ + sourceFiles.add(new SourceFile((IFile) resource, md, + encoding)); + String typeName = typePath.toString(); + // if (!newState.isDuplicateLocator(typeName, typeLocator)) + // { // adding + // // dependents + // // results + // // in + // // 2 + // // duplicate + // // errors + // if (PHPBuilder.DEBUG) + // System.out.println("Found added source file " + + // typeName); //$NON-NLS-1$ + // addDependentsOf(typePath, true); + // } + return; + case IResourceDelta.REMOVED: + // char[][] definedTypeNames = newState + // .getDefinedTypeNamesFor(typeLocator); + // if (definedTypeNames == null) { // defined a single type + // matching + // // typePath + // removeClassFile(typePath, md.binaryFolder); + // if ((sourceDelta.getFlags() & IResourceDelta.MOVED_TO) != + // 0) { + // // remove problems and tasks for a compilation unit that + // is + // // being moved (to another package or renamed) + // // if the target file is a compilation unit, the new cu + // will + // // be recompiled + // // if the target file is a non-java resource, then + // markers + // // are removed + // // see bug 2857 + // IResource movedFile = javaBuilder.workspaceRoot + // .getFile(sourceDelta.getMovedToPath()); + // PHPBuilder.removeProblemsAndTasksFor(movedFile); + // } + // } else { + if (PHPBuilder.DEBUG) + System.out + .println("Found removed source file " + typePath.toString()); //$NON-NLS-1$ + addDependentsOf(typePath, true); // add dependents of the + // source file since it may be + // involved in a name + // collision + // if (definedTypeNames.length > 0) { // skip it if it + // failed to + // // successfully define a + // // type + // IPath packagePath = typePath.removeLastSegments(1); + // for (int i = 0, l = definedTypeNames.length; i < l; i++) + // removeClassFile(packagePath.append(new String( + // definedTypeNames[i])), md.binaryFolder); + // } + // } + // newState.removeLocator(typeLocator); + return; + case IResourceDelta.CHANGED: + if ((sourceDelta.getFlags() & IResourceDelta.CONTENT) == 0) + return; // skip it since it really isn't changed + if (PHPBuilder.DEBUG) + System.out + .println("Compile this changed source file " + typeLocator); //$NON-NLS-1$ + sourceFiles.add(new SourceFile((IFile) resource, md, + encoding)); + } + return; + // } else if (ProjectPrefUtil.isClassFileName(resourceName)) { + // return; // skip class files + } else if (md.hasIndependentOutputFolder) { + if (javaBuilder.filterExtraResource(resource)) + return; + // copy all other resource deltas to the output folder + IPath resourcePath = resource.getFullPath() + .removeFirstSegments(segmentCount); + // IResource outputFile = md.binaryFolder.getFile(resourcePath); + switch (sourceDelta.getKind()) { + case IResourceDelta.ADDED: + // if (outputFile.exists()) { + // if (PHPBuilder.DEBUG) + // System.out.println("Deleting existing file " + + // resourcePath); //$NON-NLS-1$ + // outputFile.delete(IResource.FORCE, null); + // } + if (PHPBuilder.DEBUG) + System.out + .println("Copying added file " + resourcePath); //$NON-NLS-1$ + // createFolder(resourcePath.removeLastSegments(1), + // md.binaryFolder); // ensure + // package + // exists + // in + // the + // output + // folder + // resource.copy(outputFile.getFullPath(), IResource.FORCE, + // null); + // outputFile.setDerived(true); + return; + case IResourceDelta.REMOVED: + // if (outputFile.exists()) { + // if (PHPBuilder.DEBUG) + // System.out.println("Deleting removed file " + + // resourcePath); //$NON-NLS-1$ + // outputFile.delete(IResource.FORCE, null); + // } + return; + case IResourceDelta.CHANGED: + if ((sourceDelta.getFlags() & IResourceDelta.CONTENT) == 0) + return; // skip it since it really isn't changed + // if (outputFile.exists()) { + // if (PHPBuilder.DEBUG) + // System.out.println("Deleting existing file " + + // resourcePath); //$NON-NLS-1$ + // outputFile.delete(IResource.FORCE, null); + // } + if (PHPBuilder.DEBUG) + System.out + .println("Copying changed file " + resourcePath); //$NON-NLS-1$ + // createFolder(resourcePath.removeLastSegments(1), + // md.binaryFolder); // ensure + // package + // exists + // in + // the + // output + // folder + // resource.copy(outputFile.getFullPath(), IResource.FORCE, + // null); + // outputFile.setDerived(true); + } + return; + } + } + } - protected void finishedWith(String sourceLocator, CompilationResult result, char[] mainTypeName, ArrayList definedTypeNames, - ArrayList duplicateTypeNames) throws CoreException { - // char[][] previousTypeNames = newState.getDefinedTypeNamesFor(sourceLocator); - // if (previousTypeNames == null) - // previousTypeNames = new char[][]{mainTypeName}; - // IPath packagePath = null; - // next : for (int i = 0, l = previousTypeNames.length; i < l; i++) { - // char[] previous = previousTypeNames[i]; - // for (int j = 0, m = definedTypeNames.size(); j < m; j++) - // if (CharOperation.equals(previous, (char[]) definedTypeNames.get(j))) - // continue next; - // SourceFile sourceFile = (SourceFile) result.getCompilationUnit(); - // if (packagePath == null) { - // int count = sourceFile.sourceLocation.sourceFolder.getFullPath() - // .segmentCount(); - // packagePath = sourceFile.resource.getFullPath().removeFirstSegments( - // count).removeLastSegments(1); - // } - // if (secondaryTypesToRemove == null) - // this.secondaryTypesToRemove = new SimpleLookupTable(); - // ArrayList types = (ArrayList) secondaryTypesToRemove - // .get(sourceFile.sourceLocation.binaryFolder); - // if (types == null) - // types = new ArrayList(definedTypeNames.size()); - // types.add(packagePath.append(new String(previous))); - // secondaryTypesToRemove.put(sourceFile.sourceLocation.binaryFolder, types); - // } - // super.finishedWith(sourceLocator, result, mainTypeName, - // definedTypeNames, duplicateTypeNames); - } + protected void finishedWith(String sourceLocator, CompilationResult result, + char[] mainTypeName, ArrayList definedTypeNames, + ArrayList duplicateTypeNames) throws CoreException { + // char[][] previousTypeNames = + // newState.getDefinedTypeNamesFor(sourceLocator); + // if (previousTypeNames == null) + // previousTypeNames = new char[][]{mainTypeName}; + // IPath packagePath = null; + // next : for (int i = 0, l = previousTypeNames.length; i < l; i++) { + // char[] previous = previousTypeNames[i]; + // for (int j = 0, m = definedTypeNames.size(); j < m; j++) + // if (CharOperation.equals(previous, (char[]) definedTypeNames.get(j))) + // continue next; + // SourceFile sourceFile = (SourceFile) result.getCompilationUnit(); + // if (packagePath == null) { + // int count = sourceFile.sourceLocation.sourceFolder.getFullPath() + // .segmentCount(); + // packagePath = sourceFile.resource.getFullPath().removeFirstSegments( + // count).removeLastSegments(1); + // } + // if (secondaryTypesToRemove == null) + // this.secondaryTypesToRemove = new SimpleLookupTable(); + // ArrayList types = (ArrayList) secondaryTypesToRemove + // .get(sourceFile.sourceLocation.binaryFolder); + // if (types == null) + // types = new ArrayList(definedTypeNames.size()); + // types.add(packagePath.append(new String(previous))); + // secondaryTypesToRemove.put(sourceFile.sourceLocation.binaryFolder, + // types); + // } + // super.finishedWith(sourceLocator, result, mainTypeName, + // definedTypeNames, duplicateTypeNames); + } - // protected void removeClassFile(IPath typePath, IContainer outputFolder) - // throws CoreException { - // if (typePath.lastSegment().indexOf('$') == -1) { // is not a nested type - // newState.removeQualifiedTypeName(typePath.toString()); - // // add dependents even when the type thinks it does not exist to be on - // // the safe side - // if (PHPBuilder.DEBUG) - // System.out.println("Found removed type " + typePath); //$NON-NLS-1$ - // addDependentsOf(typePath, true); // when member types are removed, their - // // enclosing type is structurally - // // changed - // } - // IFile classFile = outputFolder.getFile(typePath - // .addFileExtension(PHPBuilder.CLASS_EXTENSION)); - // if (classFile.exists()) { - // if (PHPBuilder.DEBUG) - // System.out.println("Deleting class file of removed type " + typePath); //$NON-NLS-1$ - // classFile.delete(IResource.FORCE, null); - // } - // } - // protected void removeSecondaryTypes() throws CoreException { - // if (secondaryTypesToRemove != null) { // delayed deleting secondary types - // // until the end of the compile loop - // Object[] keyTable = secondaryTypesToRemove.keyTable; - // Object[] valueTable = secondaryTypesToRemove.valueTable; - // for (int i = 0, l = keyTable.length; i < l; i++) { - // IContainer outputFolder = (IContainer) keyTable[i]; - // if (outputFolder != null) { - // ArrayList paths = (ArrayList) valueTable[i]; - // for (int j = 0, m = paths.size(); j < m; j++) - // removeClassFile((IPath) paths.get(j), outputFolder); - // } - // } - // this.secondaryTypesToRemove = null; - // if (previousSourceFiles != null && previousSourceFiles.size() > 1) - // this.previousSourceFiles = null; // cannot optimize recompile case when - // // a secondary type is deleted - // } - // } - protected void resetCollections() { - previousSourceFiles = sourceFiles.isEmpty() ? null : (ArrayList) sourceFiles.clone(); - sourceFiles.clear(); - qualifiedStrings.clear(); - simpleStrings.clear(); - workQueue.clear(); - } + // protected void removeClassFile(IPath typePath, IContainer outputFolder) + // throws CoreException { + // if (typePath.lastSegment().indexOf('$') == -1) { // is not a nested type + // newState.removeQualifiedTypeName(typePath.toString()); + // // add dependents even when the type thinks it does not exist to be on + // // the safe side + // if (PHPBuilder.DEBUG) + // System.out.println("Found removed type " + typePath); //$NON-NLS-1$ + // addDependentsOf(typePath, true); // when member types are removed, their + // // enclosing type is structurally + // // changed + // } + // IFile classFile = outputFolder.getFile(typePath + // .addFileExtension(PHPBuilder.CLASS_EXTENSION)); + // if (classFile.exists()) { + // if (PHPBuilder.DEBUG) + // System.out.println("Deleting class file of removed type " + typePath); + // //$NON-NLS-1$ + // classFile.delete(IResource.FORCE, null); + // } + // } + // protected void removeSecondaryTypes() throws CoreException { + // if (secondaryTypesToRemove != null) { // delayed deleting secondary types + // // until the end of the compile loop + // Object[] keyTable = secondaryTypesToRemove.keyTable; + // Object[] valueTable = secondaryTypesToRemove.valueTable; + // for (int i = 0, l = keyTable.length; i < l; i++) { + // IContainer outputFolder = (IContainer) keyTable[i]; + // if (outputFolder != null) { + // ArrayList paths = (ArrayList) valueTable[i]; + // for (int j = 0, m = paths.size(); j < m; j++) + // removeClassFile((IPath) paths.get(j), outputFolder); + // } + // } + // this.secondaryTypesToRemove = null; + // if (previousSourceFiles != null && previousSourceFiles.size() > 1) + // this.previousSourceFiles = null; // cannot optimize recompile case when + // // a secondary type is deleted + // } + // } + protected void resetCollections() { + previousSourceFiles = sourceFiles.isEmpty() ? null + : (ArrayList) sourceFiles.clone(); + sourceFiles.clear(); + qualifiedStrings.clear(); + simpleStrings.clear(); + workQueue.clear(); + } - protected void updateProblemsFor(SourceFile sourceFile, CompilationResult result) throws CoreException { - IMarker[] markers = PHPBuilder.getProblemsFor(sourceFile.resource); - IProblem[] problems = result.getProblems(); - if (problems == null && markers.length == 0) - return; + protected void updateProblemsFor(SourceFile sourceFile, + CompilationResult result) throws CoreException { + IMarker[] markers = PHPBuilder.getProblemsFor(sourceFile.resource); + IProblem[] problems = result.getProblems(); + if (problems == null && markers.length == 0) + return; - // axelcl start insert - calculate line numbers - if (problems != null) { - for (int i = 0; i < problems.length; i++) { - if (problems[i].getSourceLineNumber() == 1) { - problems[i].setSourceLineNumber(ProblemHandler.searchLineNumber(result.lineSeparatorPositions, problems[i] - .getSourceStart())); - } - } - } - //axelcl end insert + // axelcl start insert - calculate line numbers + if (problems != null) { + for (int i = 0; i < problems.length; i++) { + if (problems[i].getSourceLineNumber() == 1) { + problems[i].setSourceLineNumber(ProblemHandler + .searchLineNumber(result.lineSeparatorPositions, + problems[i].getSourceStart())); + } + } + } + // axelcl end insert - notifier.updateProblemCounts(markers, problems); - PHPBuilder.removeProblemsFor(sourceFile.resource); - storeProblemsFor(sourceFile, problems); - } + notifier.updateProblemCounts(markers, problems); + PHPBuilder.removeProblemsFor(sourceFile.resource); + storeProblemsFor(sourceFile, problems); + } - protected void updateTasksFor(SourceFile sourceFile, CompilationResult result) throws CoreException { - IMarker[] markers = PHPBuilder.getTasksFor(sourceFile.resource); - IProblem[] tasks = result.getTasks(); - if (tasks == null && markers.length == 0) - return; - PHPBuilder.removeTasksFor(sourceFile.resource); - storeTasksFor(sourceFile, tasks); - } + protected void updateTasksFor(SourceFile sourceFile, + CompilationResult result) throws CoreException { + IMarker[] markers = PHPBuilder.getTasksFor(sourceFile.resource); + IProblem[] tasks = result.getTasks(); + if (tasks == null && markers.length == 0) + return; + PHPBuilder.removeTasksFor(sourceFile.resource); + storeTasksFor(sourceFile, tasks); + } - //protected void writeClassFileBytes(byte[] bytes, IFile file, String - // qualifiedFileName, boolean isSecondaryType) throws CoreException { - // // Before writing out the class file, compare it to the previous file - // // If structural changes occured then add dependent source files - // if (file.exists()) { - // if (writeClassFileCheck(file, qualifiedFileName, bytes)) { - // if (JavaBuilder.DEBUG) - // System.out.println("Writing changed class file " + - // file.getName());//$NON-NLS-1$ - // file.setContents(new ByteArrayInputStream(bytes), true, false, null); - // if (!file.isDerived()) - // file.setDerived(true); - // } else if (JavaBuilder.DEBUG) { - // System.out.println("Skipped over unchanged class file " + - // file.getName());//$NON-NLS-1$ - // } - // } else { - // if (isSecondaryType) - // addDependentsOf(new Path(qualifiedFileName), true); // new secondary type - // if (JavaBuilder.DEBUG) - // System.out.println("Writing new class file " + - // file.getName());//$NON-NLS-1$ - // file.create(new ByteArrayInputStream(bytes), IResource.FORCE, null); - // file.setDerived(true); - // } - //} - //protected boolean writeClassFileCheck(IFile file, String fileName, byte[] - // newBytes) throws CoreException { - // try { - // byte[] oldBytes = ProjectPrefUtil.getResourceContentsAsByteArray(file); - // if (this.compileLoop > 1) { // only optimize files which were recompiled - // during the dependent pass, see 33990 - // notEqual : if (newBytes.length == oldBytes.length) { - // for (int i = newBytes.length; --i >= 0;) - // if (newBytes[i] != oldBytes[i]) break notEqual; - // return false; // bytes are identical so skip them - // } - // } - // IPath location = file.getLocation(); - // if (location == null) return false; // unable to determine location of - // this class file - // ClassFileReader reader = new ClassFileReader(oldBytes, - // location.toString().toCharArray()); - // // ignore local types since they're only visible inside a single method - // if (!(reader.isLocal() || reader.isAnonymous()) && - // reader.hasStructuralChanges(newBytes)) { - // if (JavaBuilder.DEBUG) - // System.out.println("Type has structural changes " + fileName); - // //$NON-NLS-1$ - // addDependentsOf(new Path(fileName), true); - // } - // } catch (ClassFormatException e) { - // addDependentsOf(new Path(fileName), true); - // } - // return true; - //} - public String toString() { - return "incremental image builder for:\n\tnew state: " + newState; //$NON-NLS-1$ - } - /* - * Debug helper - * - * static void dump(IResourceDelta delta) { StringBuffer buffer = new StringBuffer(); IPath path = delta.getFullPath(); for (int i = - * path.segmentCount(); --i > 0;) buffer.append(" "); switch (delta.getKind()) { case IResourceDelta.ADDED: buffer.append('+'); - * break; case IResourceDelta.REMOVED: buffer.append('-'); break; case IResourceDelta.CHANGED: '); break; case - * IResourceDelta.NO_CHANGE: buffer.append('='); break; default: buffer.append('?'); break; } buffer.append(path); - * System.out.println(buffer.toString()); IResourceDelta[] children = delta.getAffectedChildren(); for (int i = 0, l = - * children.length; i < l; i++) dump(children[i]); } - */ + // protected void writeClassFileBytes(byte[] bytes, IFile file, String + // qualifiedFileName, boolean isSecondaryType) throws CoreException { + // // Before writing out the class file, compare it to the previous file + // // If structural changes occured then add dependent source files + // if (file.exists()) { + // if (writeClassFileCheck(file, qualifiedFileName, bytes)) { + // if (JavaBuilder.DEBUG) + // System.out.println("Writing changed class file " + + // file.getName());//$NON-NLS-1$ + // file.setContents(new ByteArrayInputStream(bytes), true, false, null); + // if (!file.isDerived()) + // file.setDerived(true); + // } else if (JavaBuilder.DEBUG) { + // System.out.println("Skipped over unchanged class file " + + // file.getName());//$NON-NLS-1$ + // } + // } else { + // if (isSecondaryType) + // addDependentsOf(new Path(qualifiedFileName), true); // new secondary type + // if (JavaBuilder.DEBUG) + // System.out.println("Writing new class file " + + // file.getName());//$NON-NLS-1$ + // file.create(new ByteArrayInputStream(bytes), IResource.FORCE, null); + // file.setDerived(true); + // } + // } + // protected boolean writeClassFileCheck(IFile file, String fileName, byte[] + // newBytes) throws CoreException { + // try { + // byte[] oldBytes = ProjectPrefUtil.getResourceContentsAsByteArray(file); + // if (this.compileLoop > 1) { // only optimize files which were recompiled + // during the dependent pass, see 33990 + // notEqual : if (newBytes.length == oldBytes.length) { + // for (int i = newBytes.length; --i >= 0;) + // if (newBytes[i] != oldBytes[i]) break notEqual; + // return false; // bytes are identical so skip them + // } + // } + // IPath location = file.getLocation(); + // if (location == null) return false; // unable to determine location of + // this class file + // ClassFileReader reader = new ClassFileReader(oldBytes, + // location.toString().toCharArray()); + // // ignore local types since they're only visible inside a single method + // if (!(reader.isLocal() || reader.isAnonymous()) && + // reader.hasStructuralChanges(newBytes)) { + // if (JavaBuilder.DEBUG) + // System.out.println("Type has structural changes " + fileName); + // //$NON-NLS-1$ + // addDependentsOf(new Path(fileName), true); + // } + // } catch (ClassFormatException e) { + // addDependentsOf(new Path(fileName), true); + // } + // return true; + // } + public String toString() { + return "incremental image builder for:\n\tnew state: " + newState; //$NON-NLS-1$ + } + /* + * Debug helper + * + * static void dump(IResourceDelta delta) { StringBuffer buffer = new + * StringBuffer(); IPath path = delta.getFullPath(); for (int i = + * path.segmentCount(); --i > 0;) buffer.append(" "); switch + * (delta.getKind()) { case IResourceDelta.ADDED: buffer.append('+'); break; + * case IResourceDelta.REMOVED: buffer.append('-'); break; case + * IResourceDelta.CHANGED: '); break; case IResourceDelta.NO_CHANGE: + * buffer.append('='); break; default: buffer.append('?'); break; } + * buffer.append(path); System.out.println(buffer.toString()); + * IResourceDelta[] children = delta.getAffectedChildren(); for (int i = 0, + * l = children.length; i < l; i++) dump(children[i]); } + */ } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/MissingClassFileException.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/MissingClassFileException.java index 4099502..bc3aaf3 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/MissingClassFileException.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/MissingClassFileException.java @@ -11,14 +11,14 @@ package net.sourceforge.phpdt.internal.core.builder; /** - * Exception thrown when the build should be aborted because a referenced - * class file cannot be found. + * Exception thrown when the build should be aborted because a referenced class + * file cannot be found. */ public class MissingClassFileException extends RuntimeException { -protected String missingClassFile; + protected String missingClassFile; -public MissingClassFileException(String missingClassFile) { - this.missingClassFile = missingClassFile; -} + public MissingClassFileException(String missingClassFile) { + this.missingClassFile = missingClassFile; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/MissingSourceFileException.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/MissingSourceFileException.java index 4c5bf91..bb5848b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/MissingSourceFileException.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/MissingSourceFileException.java @@ -11,13 +11,14 @@ package net.sourceforge.phpdt.internal.core.builder; /** - * Exception thrown when the build should be aborted because a source file is missing/empty. + * Exception thrown when the build should be aborted because a source file is + * missing/empty. */ public class MissingSourceFileException extends RuntimeException { -protected String missingSourceFile; + protected String missingSourceFile; -public MissingSourceFileException(String missingSourceFile) { - this.missingSourceFile = missingSourceFile; -} + public MissingSourceFileException(String missingSourceFile) { + this.missingSourceFile = missingSourceFile; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/NameEnvironment.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/NameEnvironment.java index ffdbaf0..c8f6dd3 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/NameEnvironment.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/NameEnvironment.java @@ -35,299 +35,365 @@ import org.eclipse.core.runtime.Path; public class NameEnvironment implements INameEnvironment { - boolean isIncrementalBuild; - ClasspathMultiDirectory[] sourceLocations; - //ClasspathLocation[] binaryLocations; - - String[] initialTypeNames; // assumed that each name is of the form "a/b/ClassName" - SourceFile[] additionalUnits; - - NameEnvironment(IWorkspaceRoot root, JavaProject javaProject, SimpleLookupTable binaryLocationsPerProject) throws CoreException { - this.isIncrementalBuild = false; -// this.sourceLocations = new ClasspathMultiDirectory[0]; - computeClasspathLocations(root, javaProject, binaryLocationsPerProject); - setNames(null, null); - } - - public NameEnvironment(IJavaProject javaProject) { - this.isIncrementalBuild = false; - try { - computeClasspathLocations(javaProject.getProject().getWorkspace().getRoot(), (JavaProject) javaProject, null); - } catch(CoreException e) { -// this.sourceLocations = new ClasspathMultiDirectory[0]; - // this.binaryLocations = new ClasspathLocation[0]; - } - setNames(null, null); - } - - /* Some examples of resolved class path entries. - * Remember to search class path in the order that it was defined. - * - * 1a. typical project with no source folders: - * /Test[CPE_SOURCE][K_SOURCE] -> D:/eclipse.test/Test - * 1b. project with source folders: - * /Test/src1[CPE_SOURCE][K_SOURCE] -> D:/eclipse.test/Test/src1 - * /Test/src2[CPE_SOURCE][K_SOURCE] -> D:/eclipse.test/Test/src2 - * NOTE: These can be in any order & separated by prereq projects or libraries - * 1c. project external to workspace (only detectable using getLocation()): - * /Test/src[CPE_SOURCE][K_SOURCE] -> d:/eclipse.zzz/src - * Need to search source folder & output folder - * - * 2. zip files: - * D:/j9/lib/jclMax/classes.zip[CPE_LIBRARY][K_BINARY][sourcePath:d:/j9/lib/jclMax/source/source.zip] - * -> D:/j9/lib/jclMax/classes.zip - * ALWAYS want to take the library path as is - * - * 3a. prereq project (regardless of whether it has a source or output folder): - * /Test[CPE_PROJECT][K_SOURCE] -> D:/eclipse.test/Test - * ALWAYS want to append the output folder & ONLY search for .class files - */ - private void computeClasspathLocations( - IWorkspaceRoot root, - JavaProject javaProject, - SimpleLookupTable binaryLocationsPerProject) throws CoreException { - - /* Update cycle marker */ - IMarker cycleMarker = javaProject.getCycleMarker(); - if (cycleMarker != null) { - int severity = JavaCore.ERROR.equals(javaProject.getOption(JavaCore.CORE_CIRCULAR_CLASSPATH, true)) - ? IMarker.SEVERITY_ERROR - : IMarker.SEVERITY_WARNING; - if (severity != ((Integer) cycleMarker.getAttribute(IMarker.SEVERITY)).intValue()) - cycleMarker.setAttribute(IMarker.SEVERITY, severity); + boolean isIncrementalBuild; + + ClasspathMultiDirectory[] sourceLocations; + + // ClasspathLocation[] binaryLocations; + + String[] initialTypeNames; // assumed that each name is of the form + // "a/b/ClassName" + + SourceFile[] additionalUnits; + + NameEnvironment(IWorkspaceRoot root, JavaProject javaProject, + SimpleLookupTable binaryLocationsPerProject) throws CoreException { + this.isIncrementalBuild = false; + // this.sourceLocations = new ClasspathMultiDirectory[0]; + computeClasspathLocations(root, javaProject, binaryLocationsPerProject); + setNames(null, null); + } + + public NameEnvironment(IJavaProject javaProject) { + this.isIncrementalBuild = false; + try { + computeClasspathLocations(javaProject.getProject().getWorkspace() + .getRoot(), (JavaProject) javaProject, null); + } catch (CoreException e) { + // this.sourceLocations = new ClasspathMultiDirectory[0]; + // this.binaryLocations = new ClasspathLocation[0]; + } + setNames(null, null); + } + + /* + * Some examples of resolved class path entries. Remember to search class + * path in the order that it was defined. + * + * 1a. typical project with no source folders: /Test[CPE_SOURCE][K_SOURCE] -> + * D:/eclipse.test/Test 1b. project with source folders: + * /Test/src1[CPE_SOURCE][K_SOURCE] -> D:/eclipse.test/Test/src1 + * /Test/src2[CPE_SOURCE][K_SOURCE] -> D:/eclipse.test/Test/src2 NOTE: These + * can be in any order & separated by prereq projects or libraries 1c. + * project external to workspace (only detectable using getLocation()): + * /Test/src[CPE_SOURCE][K_SOURCE] -> d:/eclipse.zzz/src Need to search + * source folder & output folder + * + * 2. zip files: + * D:/j9/lib/jclMax/classes.zip[CPE_LIBRARY][K_BINARY][sourcePath:d:/j9/lib/jclMax/source/source.zip] -> + * D:/j9/lib/jclMax/classes.zip ALWAYS want to take the library path as is + * + * 3a. prereq project (regardless of whether it has a source or output + * folder): /Test[CPE_PROJECT][K_SOURCE] -> D:/eclipse.test/Test ALWAYS want + * to append the output folder & ONLY search for .class files + */ + private void computeClasspathLocations(IWorkspaceRoot root, + JavaProject javaProject, SimpleLookupTable binaryLocationsPerProject) + throws CoreException { + + /* Update cycle marker */ + IMarker cycleMarker = javaProject.getCycleMarker(); + if (cycleMarker != null) { + int severity = JavaCore.ERROR.equals(javaProject.getOption( + JavaCore.CORE_CIRCULAR_CLASSPATH, true)) ? IMarker.SEVERITY_ERROR + : IMarker.SEVERITY_WARNING; + if (severity != ((Integer) cycleMarker + .getAttribute(IMarker.SEVERITY)).intValue()) + cycleMarker.setAttribute(IMarker.SEVERITY, severity); + } + + /* Update incomplete classpath marker */ + // IClasspathEntry[] classpathEntries = + // javaProject.getExpandedClasspath(true, true); + IClasspathEntry[] classpathEntries = javaProject + .getExpandedClasspath(true/* ignore unresolved variable */, + false/* don't create markers */, null/* preferred cp */, + null/* preferred output */); + + ArrayList sLocations = new ArrayList(classpathEntries.length); + ArrayList bLocations = new ArrayList(classpathEntries.length); + nextEntry: for (int i = 0, l = classpathEntries.length; i < l; i++) { + ClasspathEntry entry = (ClasspathEntry) classpathEntries[i]; + IPath path = entry.getPath(); + Object target = JavaModel.getTarget(root, path, true); + if (target == null) + continue nextEntry; + + switch (entry.getEntryKind()) { + case IClasspathEntry.CPE_SOURCE: + if (!(target instanceof IContainer)) + continue nextEntry; + // IPath outputPath = entry.getOutputLocation() != null + // ? entry.getOutputLocation() + // : javaProject.getOutputLocation(); + IContainer outputFolder = null; + // if (outputPath.segmentCount() == 1) { + // outputFolder = javaProject.getProject(); + // } else { + // outputFolder = root.getFolder(outputPath); + // if (!outputFolder.exists()) + // createFolder(outputFolder); + // } + sLocations.add(ClasspathLocation.forSourceFolder( + (IContainer) target, outputFolder, entry + .fullExclusionPatternChars())); + continue nextEntry; + + case IClasspathEntry.CPE_PROJECT: + if (!(target instanceof IProject)) + continue nextEntry; + IProject prereqProject = (IProject) target; + if (!JavaProject.hasJavaNature(prereqProject)) + continue nextEntry; // if project doesn't have java nature + // or is not accessible + + JavaProject prereqJavaProject = (JavaProject) JavaCore + .create(prereqProject); + IClasspathEntry[] prereqClasspathEntries = prereqJavaProject + .getRawClasspath(); + ArrayList seen = new ArrayList(); + nextPrereqEntry: for (int j = 0, m = prereqClasspathEntries.length; j < m; j++) { + IClasspathEntry prereqEntry = (IClasspathEntry) prereqClasspathEntries[j]; + if (prereqEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) { + Object prereqTarget = JavaModel.getTarget(root, + prereqEntry.getPath(), true); + if (!(prereqTarget instanceof IContainer)) + continue nextPrereqEntry; + IPath prereqOutputPath = prereqEntry + .getOutputLocation() != null ? prereqEntry + .getOutputLocation() : prereqJavaProject + .getOutputLocation(); + IContainer binaryFolder = prereqOutputPath + .segmentCount() == 1 ? (IContainer) prereqProject + : (IContainer) root.getFolder(prereqOutputPath); + if (binaryFolder.exists() + && !seen.contains(binaryFolder)) { + seen.add(binaryFolder); + ClasspathLocation bLocation = ClasspathLocation + .forBinaryFolder(binaryFolder, true); + bLocations.add(bLocation); + if (binaryLocationsPerProject != null) { // normal + // builder + // mode + ClasspathLocation[] existingLocations = (ClasspathLocation[]) binaryLocationsPerProject + .get(prereqProject); + if (existingLocations == null) { + existingLocations = new ClasspathLocation[] { bLocation }; + } else { + int size = existingLocations.length; + System + .arraycopy( + existingLocations, + 0, + existingLocations = new ClasspathLocation[size + 1], + 0, size); + existingLocations[size] = bLocation; + } + binaryLocationsPerProject.put(prereqProject, + existingLocations); + } + } + } + } + continue nextEntry; + + // case IClasspathEntry.CPE_LIBRARY : + // if (target instanceof IResource) { + // IResource resource = (IResource) target; + // ClasspathLocation bLocation = null; + // if (resource instanceof IFile) { + // if (!(ProjectPrefUtil.isArchiveFileName(path.lastSegment()))) + // continue nextEntry; + // bLocation = ClasspathLocation.forLibrary((IFile) resource); + // } else if (resource instanceof IContainer) { + // bLocation = ClasspathLocation.forBinaryFolder((IContainer) + // target, false); // is library folder not output folder + // } + // bLocations.add(bLocation); + // if (binaryLocationsPerProject != null) { // normal builder + // mode + // IProject p = resource.getProject(); // can be the project + // being built + // ClasspathLocation[] existingLocations = (ClasspathLocation[]) + // binaryLocationsPerProject.get(p); + // if (existingLocations == null) { + // existingLocations = new ClasspathLocation[] {bLocation}; + // } else { + // int size = existingLocations.length; + // System.arraycopy(existingLocations, 0, existingLocations = + // new ClasspathLocation[size + 1], 0, size); + // existingLocations[size] = bLocation; + // } + // binaryLocationsPerProject.put(p, existingLocations); + // } + // } else if (target instanceof File) { + // if (!(ProjectPrefUtil.isArchiveFileName(path.lastSegment()))) + // continue nextEntry; + // bLocations.add(ClasspathLocation.forLibrary(path.toString())); + // } + // continue nextEntry; + } + } + + // now split the classpath locations... place the output folders ahead + // of the other .class file folders & jars + ArrayList outputFolders = new ArrayList(1); + this.sourceLocations = new ClasspathMultiDirectory[sLocations.size()]; + if (!sLocations.isEmpty()) { + sLocations.toArray(this.sourceLocations); + + // collect the output folders, skipping duplicates + next: for (int i = 0, l = sourceLocations.length; i < l; i++) { + ClasspathMultiDirectory md = sourceLocations[i]; + // IPath outputPath = md.binaryFolder.getFullPath(); + // for (int j = 0; j < i; j++) { // compare against previously + // walked source folders + // if + // (outputPath.equals(sourceLocations[j].binaryFolder.getFullPath())) + // { + // md.hasIndependentOutputFolder = + // sourceLocations[j].hasIndependentOutputFolder; + // continue next; + // } + // } + outputFolders.add(md); + + // also tag each source folder whose output folder is an + // independent folder & is not also a source folder + // for (int j = 0, m = sourceLocations.length; j < m; j++) + // if + // (outputPath.equals(sourceLocations[j].sourceFolder.getFullPath())) + // continue next; + md.hasIndependentOutputFolder = true; + } + } + + // combine the output folders with the binary folders & jars... place + // the output folders before other .class file folders & jars + // this.binaryLocations = new ClasspathLocation[outputFolders.size() + + // bLocations.size()]; + // int index = 0; + // for (int i = 0, l = outputFolders.size(); i < l; i++) + // this.binaryLocations[index++] = (ClasspathLocation) + // outputFolders.get(i); + // for (int i = 0, l = bLocations.size(); i < l; i++) + // this.binaryLocations[index++] = (ClasspathLocation) + // bLocations.get(i); + } + + public void cleanup() { + this.initialTypeNames = null; + this.additionalUnits = null; + for (int i = 0, l = sourceLocations.length; i < l; i++) + sourceLocations[i].cleanup(); + // for (int i = 0, l = binaryLocations.length; i < l; i++) + // binaryLocations[i].cleanup(); + } + + private void createFolder(IContainer folder) throws CoreException { + if (!folder.exists()) { + createFolder(folder.getParent()); + ((IFolder) folder).create(true, true, null); + } + } + + private NameEnvironmentAnswer findClass(String qualifiedTypeName, + char[] typeName) { + if (initialTypeNames != null) { + for (int i = 0, l = initialTypeNames.length; i < l; i++) { + if (qualifiedTypeName.equals(initialTypeNames[i])) { + if (isIncrementalBuild) + // catch the case that a type inside a source file has + // been renamed but other class files are looking for it + throw new AbortCompilation(true, + new AbortIncrementalBuildException( + qualifiedTypeName)); + return null; // looking for a file which we know was + // provided at the beginning of the + // compilation + } + } + } + + if (additionalUnits != null && sourceLocations.length > 0) { + // if an additional source file is waiting to be compiled, answer it + // BUT not if this is a secondary type search + // if we answer X.java & it no longer defines Y then the binary type + // looking for Y will think the class path is wrong + // let the recompile loop fix up dependents when the secondary type + // Y has been deleted from X.java + IPath qSourceFilePath = new Path(qualifiedTypeName + ".java"); //$NON-NLS-1$ + int qSegmentCount = qSourceFilePath.segmentCount(); + next: for (int i = 0, l = additionalUnits.length; i < l; i++) { + SourceFile additionalUnit = additionalUnits[i]; + IPath fullPath = additionalUnit.resource.getFullPath(); + int prefixCount = additionalUnit.sourceLocation.sourceFolder + .getFullPath().segmentCount(); + if (qSegmentCount == fullPath.segmentCount() - prefixCount) { + for (int j = 0; j < qSegmentCount; j++) + if (!qSourceFilePath.segment(j).equals( + fullPath.segment(j + prefixCount))) + continue next; + return new NameEnvironmentAnswer(additionalUnit); + } + } + } + + // String qBinaryFileName = qualifiedTypeName + ".class"; //$NON-NLS-1$ + // String binaryFileName = qBinaryFileName; + // String qPackageName = ""; //$NON-NLS-1$ + // if (qualifiedTypeName.length() > typeName.length) { + // int typeNameStart = qBinaryFileName.length() - typeName.length - 6; + // // size of ".class" + // qPackageName = qBinaryFileName.substring(0, typeNameStart - 1); + // binaryFileName = qBinaryFileName.substring(typeNameStart); + // } + // + // // NOTE: the output folders are added at the beginning of the + // binaryLocations + // for (int i = 0, l = binaryLocations.length; i < l; i++) { + // NameEnvironmentAnswer answer = + // binaryLocations[i].findClass(binaryFileName, qPackageName, + // qBinaryFileName); + // if (answer != null) return answer; + // } + return null; + } + + public NameEnvironmentAnswer findType(char[][] compoundName) { + if (compoundName != null) + return findClass(new String(CharOperation.concatWith(compoundName, + '/')), compoundName[compoundName.length - 1]); + return null; + } + + public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) { + if (typeName != null) + return findClass(new String(CharOperation.concatWith(packageName, + typeName, '/')), typeName); + return null; + } + + public boolean isPackage(char[][] compoundName, char[] packageName) { + return isPackage(new String(CharOperation.concatWith(compoundName, + packageName, '/'))); + } + + public boolean isPackage(String qualifiedPackageName) { + // NOTE: the output folders are added at the beginning of the + // binaryLocations + // for (int i = 0, l = binaryLocations.length; i < l; i++) + // if (binaryLocations[i].isPackage(qualifiedPackageName)) + // return true; + return false; + } + + void setNames(String[] initialTypeNames, SourceFile[] additionalUnits) { + this.initialTypeNames = initialTypeNames; + this.additionalUnits = additionalUnits; + for (int i = 0, l = sourceLocations.length; i < l; i++) + sourceLocations[i].reset(); + // for (int i = 0, l = binaryLocations.length; i < l; i++) + // binaryLocations[i].reset(); } - - /* Update incomplete classpath marker */ -// IClasspathEntry[] classpathEntries = javaProject.getExpandedClasspath(true, true); - IClasspathEntry[] classpathEntries = javaProject.getExpandedClasspath(true/*ignore unresolved variable*/, false/*don't create markers*/, null/*preferred cp*/, null/*preferred output*/); - - ArrayList sLocations = new ArrayList(classpathEntries.length); - ArrayList bLocations = new ArrayList(classpathEntries.length); - nextEntry : for (int i = 0, l = classpathEntries.length; i < l; i++) { - ClasspathEntry entry = (ClasspathEntry) classpathEntries[i]; - IPath path = entry.getPath(); - Object target = JavaModel.getTarget(root, path, true); - if (target == null) continue nextEntry; - - switch(entry.getEntryKind()) { - case IClasspathEntry.CPE_SOURCE : - if (!(target instanceof IContainer)) continue nextEntry; -// IPath outputPath = entry.getOutputLocation() != null -// ? entry.getOutputLocation() -// : javaProject.getOutputLocation(); - IContainer outputFolder = null; -// if (outputPath.segmentCount() == 1) { -// outputFolder = javaProject.getProject(); -// } else { -// outputFolder = root.getFolder(outputPath); -// if (!outputFolder.exists()) -// createFolder(outputFolder); -// } - sLocations.add( - ClasspathLocation.forSourceFolder((IContainer) target, outputFolder, entry.fullExclusionPatternChars())); - continue nextEntry; - - case IClasspathEntry.CPE_PROJECT : - if (!(target instanceof IProject)) continue nextEntry; - IProject prereqProject = (IProject) target; - if (!JavaProject.hasJavaNature(prereqProject)) continue nextEntry; // if project doesn't have java nature or is not accessible - - JavaProject prereqJavaProject = (JavaProject) JavaCore.create(prereqProject); - IClasspathEntry[] prereqClasspathEntries = prereqJavaProject.getRawClasspath(); - ArrayList seen = new ArrayList(); - nextPrereqEntry: for (int j = 0, m = prereqClasspathEntries.length; j < m; j++) { - IClasspathEntry prereqEntry = (IClasspathEntry) prereqClasspathEntries[j]; - if (prereqEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) { - Object prereqTarget = JavaModel.getTarget(root, prereqEntry.getPath(), true); - if (!(prereqTarget instanceof IContainer)) continue nextPrereqEntry; - IPath prereqOutputPath = prereqEntry.getOutputLocation() != null - ? prereqEntry.getOutputLocation() - : prereqJavaProject.getOutputLocation(); - IContainer binaryFolder = prereqOutputPath.segmentCount() == 1 - ? (IContainer) prereqProject - : (IContainer) root.getFolder(prereqOutputPath); - if (binaryFolder.exists() && !seen.contains(binaryFolder)) { - seen.add(binaryFolder); - ClasspathLocation bLocation = ClasspathLocation.forBinaryFolder(binaryFolder, true); - bLocations.add(bLocation); - if (binaryLocationsPerProject != null) { // normal builder mode - ClasspathLocation[] existingLocations = (ClasspathLocation[]) binaryLocationsPerProject.get(prereqProject); - if (existingLocations == null) { - existingLocations = new ClasspathLocation[] {bLocation}; - } else { - int size = existingLocations.length; - System.arraycopy(existingLocations, 0, existingLocations = new ClasspathLocation[size + 1], 0, size); - existingLocations[size] = bLocation; - } - binaryLocationsPerProject.put(prereqProject, existingLocations); - } - } - } - } - continue nextEntry; - -// case IClasspathEntry.CPE_LIBRARY : -// if (target instanceof IResource) { -// IResource resource = (IResource) target; -// ClasspathLocation bLocation = null; -// if (resource instanceof IFile) { -// if (!(ProjectPrefUtil.isArchiveFileName(path.lastSegment()))) -// continue nextEntry; -// bLocation = ClasspathLocation.forLibrary((IFile) resource); -// } else if (resource instanceof IContainer) { -// bLocation = ClasspathLocation.forBinaryFolder((IContainer) target, false); // is library folder not output folder -// } -// bLocations.add(bLocation); -// if (binaryLocationsPerProject != null) { // normal builder mode -// IProject p = resource.getProject(); // can be the project being built -// ClasspathLocation[] existingLocations = (ClasspathLocation[]) binaryLocationsPerProject.get(p); -// if (existingLocations == null) { -// existingLocations = new ClasspathLocation[] {bLocation}; -// } else { -// int size = existingLocations.length; -// System.arraycopy(existingLocations, 0, existingLocations = new ClasspathLocation[size + 1], 0, size); -// existingLocations[size] = bLocation; -// } -// binaryLocationsPerProject.put(p, existingLocations); -// } -// } else if (target instanceof File) { -// if (!(ProjectPrefUtil.isArchiveFileName(path.lastSegment()))) -// continue nextEntry; -// bLocations.add(ClasspathLocation.forLibrary(path.toString())); -// } -// continue nextEntry; - } - } - - // now split the classpath locations... place the output folders ahead of the other .class file folders & jars - ArrayList outputFolders = new ArrayList(1); - this.sourceLocations = new ClasspathMultiDirectory[sLocations.size()]; - if (!sLocations.isEmpty()) { - sLocations.toArray(this.sourceLocations); - - // collect the output folders, skipping duplicates - next : for (int i = 0, l = sourceLocations.length; i < l; i++) { - ClasspathMultiDirectory md = sourceLocations[i]; -// IPath outputPath = md.binaryFolder.getFullPath(); -// for (int j = 0; j < i; j++) { // compare against previously walked source folders -// if (outputPath.equals(sourceLocations[j].binaryFolder.getFullPath())) { -// md.hasIndependentOutputFolder = sourceLocations[j].hasIndependentOutputFolder; -// continue next; -// } -// } - outputFolders.add(md); - - // also tag each source folder whose output folder is an independent folder & is not also a source folder -// for (int j = 0, m = sourceLocations.length; j < m; j++) -// if (outputPath.equals(sourceLocations[j].sourceFolder.getFullPath())) -// continue next; - md.hasIndependentOutputFolder = true; - } - } - -// combine the output folders with the binary folders & jars... place the output folders before other .class file folders & jars -// this.binaryLocations = new ClasspathLocation[outputFolders.size() + bLocations.size()]; -// int index = 0; -// for (int i = 0, l = outputFolders.size(); i < l; i++) -// this.binaryLocations[index++] = (ClasspathLocation) outputFolders.get(i); -// for (int i = 0, l = bLocations.size(); i < l; i++) -// this.binaryLocations[index++] = (ClasspathLocation) bLocations.get(i); - } - - public void cleanup() { - this.initialTypeNames = null; - this.additionalUnits = null; - for (int i = 0, l = sourceLocations.length; i < l; i++) - sourceLocations[i].cleanup(); - // for (int i = 0, l = binaryLocations.length; i < l; i++) - // binaryLocations[i].cleanup(); - } - - private void createFolder(IContainer folder) throws CoreException { - if (!folder.exists()) { - createFolder(folder.getParent()); - ((IFolder) folder).create(true, true, null); - } - } - - private NameEnvironmentAnswer findClass(String qualifiedTypeName, char[] typeName) { - if (initialTypeNames != null) { - for (int i = 0, l = initialTypeNames.length; i < l; i++) { - if (qualifiedTypeName.equals(initialTypeNames[i])) { - if (isIncrementalBuild) - // catch the case that a type inside a source file has been renamed but other class files are looking for it - throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedTypeName)); - return null; // looking for a file which we know was provided at the beginning of the compilation - } - } - } - - if (additionalUnits != null && sourceLocations.length > 0) { - // if an additional source file is waiting to be compiled, answer it BUT not if this is a secondary type search - // if we answer X.java & it no longer defines Y then the binary type looking for Y will think the class path is wrong - // let the recompile loop fix up dependents when the secondary type Y has been deleted from X.java - IPath qSourceFilePath = new Path(qualifiedTypeName + ".java"); //$NON-NLS-1$ - int qSegmentCount = qSourceFilePath.segmentCount(); - next : for (int i = 0, l = additionalUnits.length; i < l; i++) { - SourceFile additionalUnit = additionalUnits[i]; - IPath fullPath = additionalUnit.resource.getFullPath(); - int prefixCount = additionalUnit.sourceLocation.sourceFolder.getFullPath().segmentCount(); - if (qSegmentCount == fullPath.segmentCount() - prefixCount) { - for (int j = 0; j < qSegmentCount; j++) - if (!qSourceFilePath.segment(j).equals(fullPath.segment(j + prefixCount))) - continue next; - return new NameEnvironmentAnswer(additionalUnit); - } - } - } - - // String qBinaryFileName = qualifiedTypeName + ".class"; //$NON-NLS-1$ - // String binaryFileName = qBinaryFileName; - // String qPackageName = ""; //$NON-NLS-1$ - // if (qualifiedTypeName.length() > typeName.length) { - // int typeNameStart = qBinaryFileName.length() - typeName.length - 6; // size of ".class" - // qPackageName = qBinaryFileName.substring(0, typeNameStart - 1); - // binaryFileName = qBinaryFileName.substring(typeNameStart); - // } - // - // // NOTE: the output folders are added at the beginning of the binaryLocations - // for (int i = 0, l = binaryLocations.length; i < l; i++) { - // NameEnvironmentAnswer answer = binaryLocations[i].findClass(binaryFileName, qPackageName, qBinaryFileName); - // if (answer != null) return answer; - // } - return null; - } - - public NameEnvironmentAnswer findType(char[][] compoundName) { - if (compoundName != null) - return findClass(new String(CharOperation.concatWith(compoundName, '/')), compoundName[compoundName.length - 1]); - return null; - } - - public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) { - if (typeName != null) - return findClass(new String(CharOperation.concatWith(packageName, typeName, '/')), typeName); - return null; - } - - public boolean isPackage(char[][] compoundName, char[] packageName) { - return isPackage(new String(CharOperation.concatWith(compoundName, packageName, '/'))); - } - - public boolean isPackage(String qualifiedPackageName) { - // NOTE: the output folders are added at the beginning of the binaryLocations - // for (int i = 0, l = binaryLocations.length; i < l; i++) - // if (binaryLocations[i].isPackage(qualifiedPackageName)) - // return true; - return false; - } - - void setNames(String[] initialTypeNames, SourceFile[] additionalUnits) { - this.initialTypeNames = initialTypeNames; - this.additionalUnits = additionalUnits; - for (int i = 0, l = sourceLocations.length; i < l; i++) - sourceLocations[i].reset(); - // for (int i = 0, l = binaryLocations.length; i < l; i++) - // binaryLocations[i].reset(); - } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/PHPBuilder.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/PHPBuilder.java index 81fd788..62fb231 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/PHPBuilder.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/PHPBuilder.java @@ -9,6 +9,7 @@ * IBM Corporation - initial API and implementation *******************************************************************************/ package net.sourceforge.phpdt.internal.core.builder; + import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; @@ -47,669 +48,752 @@ import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; public class PHPBuilder extends IncrementalProjectBuilder { - IProject currentProject; - JavaProject javaProject; - IWorkspaceRoot workspaceRoot; - NameEnvironment nameEnvironment; - SimpleLookupTable binaryLocationsPerProject; // maps a project to its binary - // resources (output folders, - // class folders, zip/jar files) - State lastState; - BuildNotifier notifier; - char[][] extraResourceFileFilters; - String[] extraResourceFolderFilters; - public static final String CLASS_EXTENSION = "class"; //$NON-NLS-1$ - public static boolean DEBUG = false; - /** - * A list of project names that have been built. This list is used to reset - * the JavaModel.existingExternalFiles cache when a build cycle begins so - * that deleted external jars are discovered. - */ - static ArrayList builtProjects = null; - public static IMarker[] getProblemsFor(IResource resource) { - try { - if (resource != null && resource.exists()) - return resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, - false, IResource.DEPTH_INFINITE); - } catch (CoreException e) { - } // assume there are no problems - return new IMarker[0]; - } - public static IMarker[] getTasksFor(IResource resource) { - try { - if (resource != null && resource.exists()) - return resource.findMarkers(IJavaModelMarker.TASK_MARKER, false, - IResource.DEPTH_INFINITE); - } catch (CoreException e) { - } // assume there are no tasks - return new IMarker[0]; - } - public static void finishedBuilding(IResourceChangeEvent event) { - BuildNotifier.resetProblemCounters(); - } - /** - * Hook allowing to initialize some static state before a complete build iteration. - * This hook is invoked during PRE_AUTO_BUILD notification - */ - public static void buildStarting() { - // do nothing - // TODO (philippe) is it still needed? - } - - /** - * Hook allowing to reset some static state after a complete build iteration. - * This hook is invoked during POST_AUTO_BUILD notification - */ - public static void buildFinished() { - BuildNotifier.resetProblemCounters(); - } - public static void removeProblemsFor(IResource resource) { - try { - if (resource != null && resource.exists()) - resource.deleteMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, - false, IResource.DEPTH_INFINITE); - } catch (CoreException e) { - } // assume there were no problems - } - public static void removeTasksFor(IResource resource) { - try { - if (resource != null && resource.exists()) - resource.deleteMarkers(IJavaModelMarker.TASK_MARKER, false, - IResource.DEPTH_INFINITE); - } catch (CoreException e) { - } // assume there were no problems - } - public static void removeProblemsAndTasksFor(IResource resource) { - try { - if (resource != null && resource.exists()) { - resource.deleteMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, - false, IResource.DEPTH_INFINITE); - resource.deleteMarkers(IJavaModelMarker.TASK_MARKER, false, - IResource.DEPTH_INFINITE); - } - } catch (CoreException e) { - } // assume there were no problems - } - public static State readState(IProject project, DataInputStream in) - throws IOException { - return State.read(project, in); - } - public static void writeState(Object state, DataOutputStream out) - throws IOException { - ((State) state).write(out); - } - public PHPBuilder() { - } - protected IProject[] build(int kind, Map ignored, IProgressMonitor monitor) - throws CoreException { - this.currentProject = getProject(); - if (currentProject == null || !currentProject.isAccessible()) - return new IProject[0]; - if (DEBUG) - System.out.println("\nStarting build of " + currentProject.getName() //$NON-NLS-1$ - + " @ " + new Date(System.currentTimeMillis())); //$NON-NLS-1$ - this.notifier = new BuildNotifier(monitor, currentProject); - notifier.begin(); - boolean ok = false; - try { - notifier.checkCancel(); - initializeBuilder(); - if (isWorthBuilding()) { - if (kind == FULL_BUILD) { - processFullPHPIndex(currentProject, monitor); - buildAll(); - } else { - if ((this.lastState = getLastState(currentProject)) == null) { - if (DEBUG) - System.out - .println("Performing full build since last saved state was not found"); //$NON-NLS-1$ - processFullPHPIndex(currentProject, monitor); - buildAll(); -// } else if (hasClasspathChanged()) { -// // if the output location changes, do not delete the binary files -// // from old location -// // the user may be trying something -// buildAll(); - } else if (nameEnvironment.sourceLocations.length > 0) { - // if there is no source to compile & no classpath changes then we - // are done - SimpleLookupTable deltas = findDeltas(); - if (deltas == null) - buildAll(); - else if (deltas.elementSize > 0) - buildDeltas(deltas); - else if (DEBUG) - System.out.println("Nothing to build since deltas were empty"); //$NON-NLS-1$ - } else { - if (hasStructuralDelta()) { // double check that a jar file didn't - // get replaced in a binary project - processFullPHPIndex(currentProject, monitor); - buildAll(); - } else { - if (DEBUG) - System.out - .println("Nothing to build since there are no source folders and no deltas"); //$NON-NLS-1$ - lastState.tagAsNoopBuild(); - } - } - } - ok = true; - } - } catch (CoreException e) { - Util.log(e, "JavaBuilder handling CoreException"); //$NON-NLS-1$ - IMarker marker = currentProject - .createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); - marker.setAttribute(IMarker.MESSAGE, Util.bind( - "build.inconsistentProject", e.getLocalizedMessage())); //$NON-NLS-1$ - marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); - } catch (ImageBuilderInternalException e) { - Util.log(e.getThrowable(), - "JavaBuilder handling ImageBuilderInternalException"); //$NON-NLS-1$ - IMarker marker = currentProject - .createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); - marker.setAttribute(IMarker.MESSAGE, Util.bind( - "build.inconsistentProject", e.coreException.getLocalizedMessage())); //$NON-NLS-1$ - marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); - } catch (MissingClassFileException e) { - // do not log this exception since its thrown to handle aborted compiles - // because of missing class files - if (DEBUG) - System.out.println(Util.bind("build.incompleteClassPath", - e.missingClassFile)); //$NON-NLS-1$ - IMarker marker = currentProject - .createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); - marker.setAttribute(IMarker.MESSAGE, Util.bind( - "build.incompleteClassPath", e.missingClassFile)); //$NON-NLS-1$ - marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); - } catch (MissingSourceFileException e) { - // do not log this exception since its thrown to handle aborted compiles - // because of missing source files - if (DEBUG) - System.out.println(Util.bind("build.missingSourceFile", - e.missingSourceFile)); //$NON-NLS-1$ - removeProblemsAndTasksFor(currentProject); // make this the only problem - // for this project - IMarker marker = currentProject - .createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); - marker.setAttribute(IMarker.MESSAGE, Util.bind("build.missingSourceFile", - e.missingSourceFile)); //$NON-NLS-1$ - marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (!ok) - // If the build failed, clear the previously built state, forcing a - // full build next time. - clearLastState(); - notifier.done(); - cleanup(); - } - IProject[] requiredProjects = getRequiredProjects(true); - if (DEBUG) - System.out.println("Finished build of " + currentProject.getName() //$NON-NLS-1$ - + " @ " + new Date(System.currentTimeMillis())); //$NON-NLS-1$ - return requiredProjects; - } - /** - * Performs a FULL_BUILD by visiting all nodes in the resource - * tree under the specified project. - * - * @param iProject - */ - private void processFullPHPIndex(final IProject iProject, - final IProgressMonitor monitor) { - final IdentifierIndexManager indexManager = PHPeclipsePlugin.getDefault() - .getIndexManager(iProject); - // Create resource visitor logic - IResourceVisitor myVisitor = new IResourceVisitor() { - public boolean visit(IResource resource) throws CoreException { - if (resource.getType() == IResource.FILE) { - if (monitor.isCanceled()) { - throw new OperationCanceledException(); - } - if ((resource.getFileExtension() != null) - && PHPFileUtil.isPHPFile((IFile) resource)) { - monitor.worked(1); - monitor.subTask("Parsing: " + resource.getFullPath()); - // update indexfile for the project: -// PHPProject nature = (PHPProject) iProject -// .getNature(PHPeclipsePlugin.PHP_NATURE_ID); - indexManager.addFile((IFile) resource); - } - } - return true; - } - }; - // Process the project using the visitor just created - try { - // if (iProject.hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) { - // thePHPProject = new PHPProject(); - // thePHPProject.setProject(iProject); - // } - indexManager.initialize(); - iProject.accept(myVisitor); - indexManager.writeFile(); - } catch (CoreException e) { - e.printStackTrace(); - } - } - private void buildAll() { - notifier.checkCancel(); - notifier.subTask(Util.bind("build.preparingBuild")); //$NON-NLS-1$ - if (DEBUG && lastState != null) - System.out.println("Clearing last state : " + lastState); //$NON-NLS-1$ - clearLastState(); - BatchImageBuilder imageBuilder = new BatchImageBuilder(this); - imageBuilder.build(); - recordNewState(imageBuilder.newState); - } - private void buildDeltas(SimpleLookupTable deltas) { - notifier.checkCancel(); - notifier.subTask(Util.bind("build.preparingBuild")); //$NON-NLS-1$ - if (DEBUG && lastState != null) - System.out.println("Clearing last state : " + lastState); //$NON-NLS-1$ - clearLastState(); // clear the previously built state so if the build - // fails, a full build will occur next time - IncrementalImageBuilder imageBuilder = new IncrementalImageBuilder(this); - if (imageBuilder.build(deltas)) - recordNewState(imageBuilder.newState); - else { - processFullPHPIndex(currentProject, notifier.monitor); - buildAll(); - } - } - private void cleanup() { - this.nameEnvironment = null; - this.binaryLocationsPerProject = null; - this.lastState = null; - this.notifier = null; - this.extraResourceFileFilters = null; - this.extraResourceFolderFilters = null; - } - private void clearLastState() { - JavaModelManager.getJavaModelManager().setLastBuiltState(currentProject, - null); - } - boolean filterExtraResource(IResource resource) { - if (extraResourceFileFilters != null) { - char[] name = resource.getName().toCharArray(); - for (int i = 0, l = extraResourceFileFilters.length; i < l; i++) - if (CharOperation.match(extraResourceFileFilters[i], name, true)) - return true; - } - if (extraResourceFolderFilters != null) { - IPath path = resource.getProjectRelativePath(); - String pathName = path.toString(); - int count = path.segmentCount(); - if (resource.getType() == IResource.FILE) - count--; - for (int i = 0, l = extraResourceFolderFilters.length; i < l; i++) - if (pathName.indexOf(extraResourceFolderFilters[i]) != -1) - for (int j = 0; j < count; j++) - if (extraResourceFolderFilters[i].equals(path.segment(j))) - return true; - } - return false; - } - private SimpleLookupTable findDeltas() { - notifier.subTask(Util.bind("build.readingDelta", currentProject.getName())); //$NON-NLS-1$ - IResourceDelta delta = getDelta(currentProject); - SimpleLookupTable deltas = new SimpleLookupTable(3); - if (delta != null) { - if (delta.getKind() != IResourceDelta.NO_CHANGE) { - if (DEBUG) - System.out.println("Found source delta for: " - + currentProject.getName()); //$NON-NLS-1$ - deltas.put(currentProject, delta); - } - } else { - if (DEBUG) - System.out.println("Missing delta for: " + currentProject.getName()); //$NON-NLS-1$ - notifier.subTask(""); //$NON-NLS-1$ - return null; - } - Object[] keyTable = binaryLocationsPerProject.keyTable; - Object[] valueTable = binaryLocationsPerProject.valueTable; - nextProject : for (int i = 0, l = keyTable.length; i < l; i++) { - IProject p = (IProject) keyTable[i]; - if (p != null && p != currentProject) { - State s = getLastState(p); - if (!lastState.wasStructurallyChanged(p, s)) { // see if we can skip - // its delta - if (s.wasNoopBuild()) - continue nextProject; // project has no source folders and can be - // skipped - // ClasspathLocation[] classFoldersAndJars = (ClasspathLocation[]) - // valueTable[i]; - boolean canSkip = true; - // for (int j = 0, m = classFoldersAndJars.length; j < m; j++) { - // if (classFoldersAndJars[j].isOutputFolder()) - // classFoldersAndJars[j] = null; // can ignore output folder since - // project was not structurally changed - // else - // canSkip = false; - // } - if (canSkip) - continue nextProject; // project has no structural changes in its - // output folders - } - notifier.subTask(Util.bind("build.readingDelta", p.getName())); //$NON-NLS-1$ - delta = getDelta(p); - if (delta != null) { - if (delta.getKind() != IResourceDelta.NO_CHANGE) { - if (DEBUG) - System.out.println("Found binary delta for: " + p.getName()); //$NON-NLS-1$ - deltas.put(p, delta); - } - } else { - if (DEBUG) - System.out.println("Missing delta for: " + p.getName()); //$NON-NLS-1$ - notifier.subTask(""); //$NON-NLS-1$ - return null; - } - } - } - notifier.subTask(""); //$NON-NLS-1$ - return deltas; - } - private State getLastState(IProject project) { - return (State) JavaModelManager.getJavaModelManager().getLastBuiltState( - project, notifier.monitor); - } - /* - * Return the list of projects for which it requires a resource delta. This - * builder's project is implicitly included and need not be specified. - * Builders must re-specify the list of interesting projects every time they - * are run as this is not carried forward beyond the next build. Missing - * projects should be specified but will be ignored until they are added to - * the workspace. - */ - private IProject[] getRequiredProjects(boolean includeBinaryPrerequisites) { - if (javaProject == null || workspaceRoot == null) - return new IProject[0]; - ArrayList projects = new ArrayList(); - try { - IClasspathEntry[] entries = javaProject.getExpandedClasspath(true); - for (int i = 0, l = entries.length; i < l; i++) { - IClasspathEntry entry = entries[i]; - IPath path = entry.getPath(); - IProject p = null; - switch (entry.getEntryKind()) { - case IClasspathEntry.CPE_PROJECT : - p = workspaceRoot.getProject(path.lastSegment()); // missing - // projects are - // considered too - break; - case IClasspathEntry.CPE_LIBRARY : - if (includeBinaryPrerequisites && path.segmentCount() > 1) { - // some binary resources on the class path can come from projects - // that are not included in the project references - IResource resource = workspaceRoot.findMember(path.segment(0)); - if (resource instanceof IProject) - p = (IProject) resource; - } - } - if (p != null && !projects.contains(p)) - projects.add(p); - } - } catch (JavaModelException e) { - return new IProject[0]; - } - IProject[] result = new IProject[projects.size()]; - projects.toArray(result); - return result; - } -// private boolean hasClasspathChanged() { -// ClasspathMultiDirectory[] newSourceLocations = nameEnvironment.sourceLocations; -// ClasspathMultiDirectory[] oldSourceLocations = lastState.sourceLocations; -// int newLength = newSourceLocations.length; -// int oldLength = oldSourceLocations.length; -// int n, o; -// for (n = o = 0; n < newLength && o < oldLength; n++, o++) { -// if (newSourceLocations[n].equals(oldSourceLocations[o])) -// continue; // checks source & output folders -// try { -// if (newSourceLocations[n].sourceFolder.members().length == 0) { // added -// // new -// // empty -// // source -// // folder -// o--; -// continue; -// } -// } catch (CoreException ignore) { -// } -// if (DEBUG) -// System.out.println(newSourceLocations[n] + " != " -// + oldSourceLocations[o]); //$NON-NLS-1$ -// return true; -// } -// while (n < newLength) { -// try { -// if (newSourceLocations[n].sourceFolder.members().length == 0) { // added -// // new -// // empty -// // source -// // folder -// n++; -// continue; -// } -// } catch (CoreException ignore) { -// } -// if (DEBUG) -// System.out.println("Added non-empty source folder"); //$NON-NLS-1$ -// return true; -// } -// if (o < oldLength) { -// if (DEBUG) -// System.out.println("Removed source folder"); //$NON-NLS-1$ -// return true; -// } -// // ClasspathLocation[] newBinaryLocations = -// // nameEnvironment.binaryLocations; -// // ClasspathLocation[] oldBinaryLocations = lastState.binaryLocations; -// // newLength = newBinaryLocations.length; -// // oldLength = oldBinaryLocations.length; -// // for (n = o = 0; n < newLength && o < oldLength; n++, o++) { -// // if (newBinaryLocations[n].equals(oldBinaryLocations[o])) continue; -// // if (DEBUG) -// // System.out.println(newBinaryLocations[n] + " != " + -// // oldBinaryLocations[o]); //$NON-NLS-1$ -// // return true; -// // } -// // if (n < newLength || o < oldLength) { -// // if (DEBUG) -// // System.out.println("Number of binary folders/jar files has changed"); -// // //$NON-NLS-1$ -// // return true; -// // } -// return false; -// } - private boolean hasStructuralDelta() { - // handle case when currentProject has only .class file folders and/or jar - // files... no source/output folders - IResourceDelta delta = getDelta(currentProject); - if (delta != null && delta.getKind() != IResourceDelta.NO_CHANGE) { - // ClasspathLocation[] classFoldersAndJars = (ClasspathLocation[]) - // binaryLocationsPerProject.get(currentProject); - // if (classFoldersAndJars != null) { - // for (int i = 0, l = classFoldersAndJars.length; i < l; i++) { - // ClasspathLocation classFolderOrJar = classFoldersAndJars[i]; // either - // a .class file folder or a zip/jar file - // if (classFolderOrJar != null) { - // IPath p = classFolderOrJar.getProjectRelativePath(); - // if (p != null) { - // IResourceDelta binaryDelta = delta.findMember(p); - // if (binaryDelta != null && binaryDelta.getKind() != - // IResourceDelta.NO_CHANGE) - // return true; - // } - // } - // } - // } - } - return false; - } - private void initializeBuilder() throws CoreException { - this.javaProject = (JavaProject) JavaCore.create(currentProject); - this.workspaceRoot = currentProject.getWorkspace().getRoot(); - // Flush the existing external files cache if this is the beginning of a - // build cycle - String projectName = currentProject.getName(); - if (builtProjects == null || builtProjects.contains(projectName)) { - JavaModel.flushExternalFileCache(); - builtProjects = new ArrayList(); - } - builtProjects.add(projectName); - this.binaryLocationsPerProject = new SimpleLookupTable(3); - this.nameEnvironment = new NameEnvironment(workspaceRoot, javaProject, - binaryLocationsPerProject); - String filterSequence = javaProject.getOption( - JavaCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER, true); - char[][] filters = filterSequence != null && filterSequence.length() > 0 - ? CharOperation.splitAndTrimOn(',', filterSequence.toCharArray()) - : null; - if (filters == null) { - this.extraResourceFileFilters = null; - this.extraResourceFolderFilters = null; - } else { - int fileCount = 0, folderCount = 0; - for (int i = 0, l = filters.length; i < l; i++) { - char[] f = filters[i]; - if (f.length == 0) - continue; - if (f[f.length - 1] == '/') - folderCount++; - else - fileCount++; - } - this.extraResourceFileFilters = new char[fileCount][]; - this.extraResourceFolderFilters = new String[folderCount]; - for (int i = 0, l = filters.length; i < l; i++) { - char[] f = filters[i]; - if (f.length == 0) - continue; - if (f[f.length - 1] == '/') - extraResourceFolderFilters[--folderCount] = new String(CharOperation - .subarray(f, 0, f.length - 1)); - else - extraResourceFileFilters[--fileCount] = f; - } - } - } - private boolean isClasspathBroken(IClasspathEntry[] classpath, IProject p) - throws CoreException { - if (classpath == JavaProject.INVALID_CLASSPATH) // the .classpath file - // could not be read - return true; - IMarker[] markers = p.findMarkers( - IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, false, IResource.DEPTH_ZERO); - for (int i = 0, l = markers.length; i < l; i++) - if (((Integer) markers[i].getAttribute(IMarker.SEVERITY)).intValue() == IMarker.SEVERITY_ERROR) - return true; - return false; - } - private boolean isWorthBuilding() throws CoreException { - boolean abortBuilds = JavaCore.ABORT.equals(javaProject.getOption( - JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH, true)); - if (!abortBuilds) - return true; - // Abort build only if there are classpath errors - // if (isClasspathBroken(javaProject.getRawClasspath(), currentProject)) { - // if (DEBUG) - // System.out.println("Aborted build because project has classpath errors - // (incomplete or involved in cycle)"); //$NON-NLS-1$ - // - // JavaModelManager.getJavaModelManager().deltaProcessor.addForRefresh(javaProject); - // - // removeProblemsAndTasksFor(currentProject); // remove all compilation - // problems - // - // IMarker marker = - // currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); - // marker.setAttribute(IMarker.MESSAGE, - // ProjectPrefUtil.bind("build.abortDueToClasspathProblems")); //$NON-NLS-1$ - // marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); - // return false; - // } - // make sure all prereq projects have valid build states... only when - // aborting builds since projects in cycles do not have build states - // except for projects involved in a 'warning' cycle (see below) - IProject[] requiredProjects = getRequiredProjects(false); - next : for (int i = 0, l = requiredProjects.length; i < l; i++) { - IProject p = requiredProjects[i]; - if (getLastState(p) == null) { - // The prereq project has no build state: if this prereq project has a - // 'warning' cycle marker then allow build (see bug id 23357) - JavaProject prereq = (JavaProject) JavaCore.create(p); - if (prereq.hasCycleMarker() - && JavaCore.WARNING.equals(javaProject.getOption( - JavaCore.CORE_CIRCULAR_CLASSPATH, true))) - continue; - if (DEBUG) - System.out.println("Aborted build because prereq project " - + p.getName() //$NON-NLS-1$ - + " was not built"); //$NON-NLS-1$ - removeProblemsAndTasksFor(currentProject); // make this the only - // problem for this project - IMarker marker = currentProject - .createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); - marker.setAttribute(IMarker.MESSAGE, isClasspathBroken(prereq - .getRawClasspath(), p) ? Util.bind( - "build.prereqProjectHasClasspathProblems", p.getName()) //$NON-NLS-1$ - : Util.bind("build.prereqProjectMustBeRebuilt", p.getName())); //$NON-NLS-1$ - marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); - return false; - } - } - return true; - } - /* - * Instruct the build manager that this project is involved in a cycle and - * needs to propagate structural changes to the other projects in the cycle. - */ - void mustPropagateStructuralChanges() { - HashSet cycleParticipants = new HashSet(3); - javaProject.updateCycleParticipants(null, new ArrayList(), - cycleParticipants, workspaceRoot, new HashSet(3)); - IPath currentPath = javaProject.getPath(); - Iterator i = cycleParticipants.iterator(); - while (i.hasNext()) { - IPath participantPath = (IPath) i.next(); - if (participantPath != currentPath) { - IProject project = this.workspaceRoot.getProject(participantPath - .segment(0)); - if (hasBeenBuilt(project)) { - if (DEBUG) - System.out - .println("Requesting another build iteration since cycle participant " - + project.getName() //$NON-NLS-1$ - + " has not yet seen some structural changes"); //$NON-NLS-1$ - needRebuild(); - return; - } - } - } - } - private void recordNewState(State state) { - Object[] keyTable = binaryLocationsPerProject.keyTable; - for (int i = 0, l = keyTable.length; i < l; i++) { - IProject prereqProject = (IProject) keyTable[i]; - if (prereqProject != null && prereqProject != currentProject) - state.recordStructuralDependency(prereqProject, - getLastState(prereqProject)); - } - if (DEBUG) - System.out.println("Recording new state : " + state); //$NON-NLS-1$ - // state.dump(); - JavaModelManager.getJavaModelManager().setLastBuiltState(currentProject, - state); - } - /** - * String representation for debugging purposes - */ - public String toString() { - return currentProject == null ? "JavaBuilder for unknown project" //$NON-NLS-1$ - : "JavaBuilder for " + currentProject.getName(); //$NON-NLS-1$ - } + IProject currentProject; + + JavaProject javaProject; + + IWorkspaceRoot workspaceRoot; + + NameEnvironment nameEnvironment; + + SimpleLookupTable binaryLocationsPerProject; // maps a project to its + // binary + + // resources (output folders, + // class folders, zip/jar files) + State lastState; + + BuildNotifier notifier; + + char[][] extraResourceFileFilters; + + String[] extraResourceFolderFilters; + + public static final String CLASS_EXTENSION = "class"; //$NON-NLS-1$ + + public static boolean DEBUG = false; + + /** + * A list of project names that have been built. This list is used to reset + * the JavaModel.existingExternalFiles cache when a build cycle begins so + * that deleted external jars are discovered. + */ + static ArrayList builtProjects = null; + + public static IMarker[] getProblemsFor(IResource resource) { + try { + if (resource != null && resource.exists()) + return resource.findMarkers( + IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, false, + IResource.DEPTH_INFINITE); + } catch (CoreException e) { + } // assume there are no problems + return new IMarker[0]; + } + + public static IMarker[] getTasksFor(IResource resource) { + try { + if (resource != null && resource.exists()) + return resource.findMarkers(IJavaModelMarker.TASK_MARKER, + false, IResource.DEPTH_INFINITE); + } catch (CoreException e) { + } // assume there are no tasks + return new IMarker[0]; + } + + public static void finishedBuilding(IResourceChangeEvent event) { + BuildNotifier.resetProblemCounters(); + } + + /** + * Hook allowing to initialize some static state before a complete build + * iteration. This hook is invoked during PRE_AUTO_BUILD notification + */ + public static void buildStarting() { + // do nothing + // TODO (philippe) is it still needed? + } + + /** + * Hook allowing to reset some static state after a complete build + * iteration. This hook is invoked during POST_AUTO_BUILD notification + */ + public static void buildFinished() { + BuildNotifier.resetProblemCounters(); + } + + public static void removeProblemsFor(IResource resource) { + try { + if (resource != null && resource.exists()) + resource.deleteMarkers( + IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, false, + IResource.DEPTH_INFINITE); + } catch (CoreException e) { + } // assume there were no problems + } + + public static void removeTasksFor(IResource resource) { + try { + if (resource != null && resource.exists()) + resource.deleteMarkers(IJavaModelMarker.TASK_MARKER, false, + IResource.DEPTH_INFINITE); + } catch (CoreException e) { + } // assume there were no problems + } + + public static void removeProblemsAndTasksFor(IResource resource) { + try { + if (resource != null && resource.exists()) { + resource.deleteMarkers( + IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, false, + IResource.DEPTH_INFINITE); + resource.deleteMarkers(IJavaModelMarker.TASK_MARKER, false, + IResource.DEPTH_INFINITE); + } + } catch (CoreException e) { + } // assume there were no problems + } + + public static State readState(IProject project, DataInputStream in) + throws IOException { + return State.read(project, in); + } + + public static void writeState(Object state, DataOutputStream out) + throws IOException { + ((State) state).write(out); + } + + public PHPBuilder() { + } + + protected IProject[] build(int kind, Map ignored, IProgressMonitor monitor) + throws CoreException { + this.currentProject = getProject(); + if (currentProject == null || !currentProject.isAccessible()) + return new IProject[0]; + if (DEBUG) + System.out + .println("\nStarting build of " + currentProject.getName() //$NON-NLS-1$ + + " @ " + new Date(System.currentTimeMillis())); //$NON-NLS-1$ + this.notifier = new BuildNotifier(monitor, currentProject); + notifier.begin(); + boolean ok = false; + try { + notifier.checkCancel(); + initializeBuilder(); + if (isWorthBuilding()) { + if (kind == FULL_BUILD) { + processFullPHPIndex(currentProject, monitor); + buildAll(); + } else { + if ((this.lastState = getLastState(currentProject)) == null) { + if (DEBUG) + System.out + .println("Performing full build since last saved state was not found"); //$NON-NLS-1$ + processFullPHPIndex(currentProject, monitor); + buildAll(); + // } else if (hasClasspathChanged()) { + // // if the output location changes, do not delete the + // binary files + // // from old location + // // the user may be trying something + // buildAll(); + } else if (nameEnvironment.sourceLocations.length > 0) { + // if there is no source to compile & no classpath + // changes then we + // are done + SimpleLookupTable deltas = findDeltas(); + if (deltas == null) + buildAll(); + else if (deltas.elementSize > 0) + buildDeltas(deltas); + else if (DEBUG) + System.out + .println("Nothing to build since deltas were empty"); //$NON-NLS-1$ + } else { + if (hasStructuralDelta()) { // double check that a jar + // file didn't + // get replaced in a binary project + processFullPHPIndex(currentProject, monitor); + buildAll(); + } else { + if (DEBUG) + System.out + .println("Nothing to build since there are no source folders and no deltas"); //$NON-NLS-1$ + lastState.tagAsNoopBuild(); + } + } + } + ok = true; + } + } catch (CoreException e) { + Util.log(e, "JavaBuilder handling CoreException"); //$NON-NLS-1$ + IMarker marker = currentProject + .createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); + marker.setAttribute(IMarker.MESSAGE, Util.bind( + "build.inconsistentProject", e.getLocalizedMessage())); //$NON-NLS-1$ + marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); + } catch (ImageBuilderInternalException e) { + Util.log(e.getThrowable(), + "JavaBuilder handling ImageBuilderInternalException"); //$NON-NLS-1$ + IMarker marker = currentProject + .createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); + marker + .setAttribute( + IMarker.MESSAGE, + Util + .bind( + "build.inconsistentProject", e.coreException.getLocalizedMessage())); //$NON-NLS-1$ + marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); + } catch (MissingClassFileException e) { + // do not log this exception since its thrown to handle aborted + // compiles + // because of missing class files + if (DEBUG) + System.out.println(Util.bind("build.incompleteClassPath", + e.missingClassFile)); //$NON-NLS-1$ + IMarker marker = currentProject + .createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); + marker.setAttribute(IMarker.MESSAGE, Util.bind( + "build.incompleteClassPath", e.missingClassFile)); //$NON-NLS-1$ + marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); + } catch (MissingSourceFileException e) { + // do not log this exception since its thrown to handle aborted + // compiles + // because of missing source files + if (DEBUG) + System.out.println(Util.bind("build.missingSourceFile", + e.missingSourceFile)); //$NON-NLS-1$ + removeProblemsAndTasksFor(currentProject); // make this the only + // problem + // for this project + IMarker marker = currentProject + .createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); + marker.setAttribute(IMarker.MESSAGE, Util.bind( + "build.missingSourceFile", e.missingSourceFile)); //$NON-NLS-1$ + marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (!ok) + // If the build failed, clear the previously built state, + // forcing a + // full build next time. + clearLastState(); + notifier.done(); + cleanup(); + } + IProject[] requiredProjects = getRequiredProjects(true); + if (DEBUG) + System.out.println("Finished build of " + currentProject.getName() //$NON-NLS-1$ + + " @ " + new Date(System.currentTimeMillis())); //$NON-NLS-1$ + return requiredProjects; + } + + /** + * Performs a FULL_BUILD by visiting all nodes in the + * resource tree under the specified project. + * + * @param iProject + */ + private void processFullPHPIndex(final IProject iProject, + final IProgressMonitor monitor) { + final IdentifierIndexManager indexManager = PHPeclipsePlugin + .getDefault().getIndexManager(iProject); + // Create resource visitor logic + IResourceVisitor myVisitor = new IResourceVisitor() { + public boolean visit(IResource resource) throws CoreException { + if (resource.getType() == IResource.FILE) { + if (monitor.isCanceled()) { + throw new OperationCanceledException(); + } + if ((resource.getFileExtension() != null) + && PHPFileUtil.isPHPFile((IFile) resource)) { + monitor.worked(1); + monitor.subTask("Parsing: " + resource.getFullPath()); + // update indexfile for the project: + // PHPProject nature = (PHPProject) iProject + // .getNature(PHPeclipsePlugin.PHP_NATURE_ID); + indexManager.addFile((IFile) resource); + } + } + return true; + } + }; + // Process the project using the visitor just created + try { + // if (iProject.hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) { + // thePHPProject = new PHPProject(); + // thePHPProject.setProject(iProject); + // } + indexManager.initialize(); + iProject.accept(myVisitor); + indexManager.writeFile(); + } catch (CoreException e) { + e.printStackTrace(); + } + } + + private void buildAll() { + notifier.checkCancel(); + notifier.subTask(Util.bind("build.preparingBuild")); //$NON-NLS-1$ + if (DEBUG && lastState != null) + System.out.println("Clearing last state : " + lastState); //$NON-NLS-1$ + clearLastState(); + BatchImageBuilder imageBuilder = new BatchImageBuilder(this); + imageBuilder.build(); + recordNewState(imageBuilder.newState); + } + + private void buildDeltas(SimpleLookupTable deltas) { + notifier.checkCancel(); + notifier.subTask(Util.bind("build.preparingBuild")); //$NON-NLS-1$ + if (DEBUG && lastState != null) + System.out.println("Clearing last state : " + lastState); //$NON-NLS-1$ + clearLastState(); // clear the previously built state so if the build + // fails, a full build will occur next time + IncrementalImageBuilder imageBuilder = new IncrementalImageBuilder(this); + if (imageBuilder.build(deltas)) + recordNewState(imageBuilder.newState); + else { + processFullPHPIndex(currentProject, notifier.monitor); + buildAll(); + } + } + + private void cleanup() { + this.nameEnvironment = null; + this.binaryLocationsPerProject = null; + this.lastState = null; + this.notifier = null; + this.extraResourceFileFilters = null; + this.extraResourceFolderFilters = null; + } + + private void clearLastState() { + JavaModelManager.getJavaModelManager().setLastBuiltState( + currentProject, null); + } + + boolean filterExtraResource(IResource resource) { + if (extraResourceFileFilters != null) { + char[] name = resource.getName().toCharArray(); + for (int i = 0, l = extraResourceFileFilters.length; i < l; i++) + if (CharOperation + .match(extraResourceFileFilters[i], name, true)) + return true; + } + if (extraResourceFolderFilters != null) { + IPath path = resource.getProjectRelativePath(); + String pathName = path.toString(); + int count = path.segmentCount(); + if (resource.getType() == IResource.FILE) + count--; + for (int i = 0, l = extraResourceFolderFilters.length; i < l; i++) + if (pathName.indexOf(extraResourceFolderFilters[i]) != -1) + for (int j = 0; j < count; j++) + if (extraResourceFolderFilters[i].equals(path + .segment(j))) + return true; + } + return false; + } + + private SimpleLookupTable findDeltas() { + notifier.subTask(Util.bind( + "build.readingDelta", currentProject.getName())); //$NON-NLS-1$ + IResourceDelta delta = getDelta(currentProject); + SimpleLookupTable deltas = new SimpleLookupTable(3); + if (delta != null) { + if (delta.getKind() != IResourceDelta.NO_CHANGE) { + if (DEBUG) + System.out.println("Found source delta for: " + + currentProject.getName()); //$NON-NLS-1$ + deltas.put(currentProject, delta); + } + } else { + if (DEBUG) + System.out + .println("Missing delta for: " + currentProject.getName()); //$NON-NLS-1$ + notifier.subTask(""); //$NON-NLS-1$ + return null; + } + Object[] keyTable = binaryLocationsPerProject.keyTable; + Object[] valueTable = binaryLocationsPerProject.valueTable; + nextProject: for (int i = 0, l = keyTable.length; i < l; i++) { + IProject p = (IProject) keyTable[i]; + if (p != null && p != currentProject) { + State s = getLastState(p); + if (!lastState.wasStructurallyChanged(p, s)) { // see if we can + // skip + // its delta + if (s.wasNoopBuild()) + continue nextProject; // project has no source folders + // and can be + // skipped + // ClasspathLocation[] classFoldersAndJars = + // (ClasspathLocation[]) + // valueTable[i]; + boolean canSkip = true; + // for (int j = 0, m = classFoldersAndJars.length; j < m; + // j++) { + // if (classFoldersAndJars[j].isOutputFolder()) + // classFoldersAndJars[j] = null; // can ignore output + // folder since + // project was not structurally changed + // else + // canSkip = false; + // } + if (canSkip) + continue nextProject; // project has no structural + // changes in its + // output folders + } + notifier.subTask(Util.bind("build.readingDelta", p.getName())); //$NON-NLS-1$ + delta = getDelta(p); + if (delta != null) { + if (delta.getKind() != IResourceDelta.NO_CHANGE) { + if (DEBUG) + System.out + .println("Found binary delta for: " + p.getName()); //$NON-NLS-1$ + deltas.put(p, delta); + } + } else { + if (DEBUG) + System.out.println("Missing delta for: " + p.getName()); //$NON-NLS-1$ + notifier.subTask(""); //$NON-NLS-1$ + return null; + } + } + } + notifier.subTask(""); //$NON-NLS-1$ + return deltas; + } + + private State getLastState(IProject project) { + return (State) JavaModelManager.getJavaModelManager() + .getLastBuiltState(project, notifier.monitor); + } + + /* + * Return the list of projects for which it requires a resource delta. This + * builder's project is implicitly included and need not be specified. + * Builders must re-specify the list of interesting projects every time they + * are run as this is not carried forward beyond the next build. Missing + * projects should be specified but will be ignored until they are added to + * the workspace. + */ + private IProject[] getRequiredProjects(boolean includeBinaryPrerequisites) { + if (javaProject == null || workspaceRoot == null) + return new IProject[0]; + ArrayList projects = new ArrayList(); + try { + IClasspathEntry[] entries = javaProject.getExpandedClasspath(true); + for (int i = 0, l = entries.length; i < l; i++) { + IClasspathEntry entry = entries[i]; + IPath path = entry.getPath(); + IProject p = null; + switch (entry.getEntryKind()) { + case IClasspathEntry.CPE_PROJECT: + p = workspaceRoot.getProject(path.lastSegment()); // missing + // projects are + // considered too + break; + case IClasspathEntry.CPE_LIBRARY: + if (includeBinaryPrerequisites && path.segmentCount() > 1) { + // some binary resources on the class path can come from + // projects + // that are not included in the project references + IResource resource = workspaceRoot.findMember(path + .segment(0)); + if (resource instanceof IProject) + p = (IProject) resource; + } + } + if (p != null && !projects.contains(p)) + projects.add(p); + } + } catch (JavaModelException e) { + return new IProject[0]; + } + IProject[] result = new IProject[projects.size()]; + projects.toArray(result); + return result; + } + + // private boolean hasClasspathChanged() { + // ClasspathMultiDirectory[] newSourceLocations = + // nameEnvironment.sourceLocations; + // ClasspathMultiDirectory[] oldSourceLocations = lastState.sourceLocations; + // int newLength = newSourceLocations.length; + // int oldLength = oldSourceLocations.length; + // int n, o; + // for (n = o = 0; n < newLength && o < oldLength; n++, o++) { + // if (newSourceLocations[n].equals(oldSourceLocations[o])) + // continue; // checks source & output folders + // try { + // if (newSourceLocations[n].sourceFolder.members().length == 0) { // added + // // new + // // empty + // // source + // // folder + // o--; + // continue; + // } + // } catch (CoreException ignore) { + // } + // if (DEBUG) + // System.out.println(newSourceLocations[n] + " != " + // + oldSourceLocations[o]); //$NON-NLS-1$ + // return true; + // } + // while (n < newLength) { + // try { + // if (newSourceLocations[n].sourceFolder.members().length == 0) { // added + // // new + // // empty + // // source + // // folder + // n++; + // continue; + // } + // } catch (CoreException ignore) { + // } + // if (DEBUG) + // System.out.println("Added non-empty source folder"); //$NON-NLS-1$ + // return true; + // } + // if (o < oldLength) { + // if (DEBUG) + // System.out.println("Removed source folder"); //$NON-NLS-1$ + // return true; + // } + // // ClasspathLocation[] newBinaryLocations = + // // nameEnvironment.binaryLocations; + // // ClasspathLocation[] oldBinaryLocations = lastState.binaryLocations; + // // newLength = newBinaryLocations.length; + // // oldLength = oldBinaryLocations.length; + // // for (n = o = 0; n < newLength && o < oldLength; n++, o++) { + // // if (newBinaryLocations[n].equals(oldBinaryLocations[o])) continue; + // // if (DEBUG) + // // System.out.println(newBinaryLocations[n] + " != " + + // // oldBinaryLocations[o]); //$NON-NLS-1$ + // // return true; + // // } + // // if (n < newLength || o < oldLength) { + // // if (DEBUG) + // // System.out.println("Number of binary folders/jar files has changed"); + // // //$NON-NLS-1$ + // // return true; + // // } + // return false; + // } + private boolean hasStructuralDelta() { + // handle case when currentProject has only .class file folders and/or + // jar + // files... no source/output folders + IResourceDelta delta = getDelta(currentProject); + if (delta != null && delta.getKind() != IResourceDelta.NO_CHANGE) { + // ClasspathLocation[] classFoldersAndJars = (ClasspathLocation[]) + // binaryLocationsPerProject.get(currentProject); + // if (classFoldersAndJars != null) { + // for (int i = 0, l = classFoldersAndJars.length; i < l; i++) { + // ClasspathLocation classFolderOrJar = classFoldersAndJars[i]; // + // either + // a .class file folder or a zip/jar file + // if (classFolderOrJar != null) { + // IPath p = classFolderOrJar.getProjectRelativePath(); + // if (p != null) { + // IResourceDelta binaryDelta = delta.findMember(p); + // if (binaryDelta != null && binaryDelta.getKind() != + // IResourceDelta.NO_CHANGE) + // return true; + // } + // } + // } + // } + } + return false; + } + + private void initializeBuilder() throws CoreException { + this.javaProject = (JavaProject) JavaCore.create(currentProject); + this.workspaceRoot = currentProject.getWorkspace().getRoot(); + // Flush the existing external files cache if this is the beginning of a + // build cycle + String projectName = currentProject.getName(); + if (builtProjects == null || builtProjects.contains(projectName)) { + JavaModel.flushExternalFileCache(); + builtProjects = new ArrayList(); + } + builtProjects.add(projectName); + this.binaryLocationsPerProject = new SimpleLookupTable(3); + this.nameEnvironment = new NameEnvironment(workspaceRoot, javaProject, + binaryLocationsPerProject); + String filterSequence = javaProject.getOption( + JavaCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER, true); + char[][] filters = filterSequence != null + && filterSequence.length() > 0 ? CharOperation.splitAndTrimOn( + ',', filterSequence.toCharArray()) : null; + if (filters == null) { + this.extraResourceFileFilters = null; + this.extraResourceFolderFilters = null; + } else { + int fileCount = 0, folderCount = 0; + for (int i = 0, l = filters.length; i < l; i++) { + char[] f = filters[i]; + if (f.length == 0) + continue; + if (f[f.length - 1] == '/') + folderCount++; + else + fileCount++; + } + this.extraResourceFileFilters = new char[fileCount][]; + this.extraResourceFolderFilters = new String[folderCount]; + for (int i = 0, l = filters.length; i < l; i++) { + char[] f = filters[i]; + if (f.length == 0) + continue; + if (f[f.length - 1] == '/') + extraResourceFolderFilters[--folderCount] = new String( + CharOperation.subarray(f, 0, f.length - 1)); + else + extraResourceFileFilters[--fileCount] = f; + } + } + } + + private boolean isClasspathBroken(IClasspathEntry[] classpath, IProject p) + throws CoreException { + if (classpath == JavaProject.INVALID_CLASSPATH) // the .classpath file + // could not be read + return true; + IMarker[] markers = p.findMarkers( + IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, false, + IResource.DEPTH_ZERO); + for (int i = 0, l = markers.length; i < l; i++) + if (((Integer) markers[i].getAttribute(IMarker.SEVERITY)) + .intValue() == IMarker.SEVERITY_ERROR) + return true; + return false; + } + + private boolean isWorthBuilding() throws CoreException { + boolean abortBuilds = JavaCore.ABORT.equals(javaProject.getOption( + JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH, true)); + if (!abortBuilds) + return true; + // Abort build only if there are classpath errors + // if (isClasspathBroken(javaProject.getRawClasspath(), currentProject)) + // { + // if (DEBUG) + // System.out.println("Aborted build because project has classpath + // errors + // (incomplete or involved in cycle)"); //$NON-NLS-1$ + // + // JavaModelManager.getJavaModelManager().deltaProcessor.addForRefresh(javaProject); + // + // removeProblemsAndTasksFor(currentProject); // remove all compilation + // problems + // + // IMarker marker = + // currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); + // marker.setAttribute(IMarker.MESSAGE, + // ProjectPrefUtil.bind("build.abortDueToClasspathProblems")); + // //$NON-NLS-1$ + // marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); + // return false; + // } + // make sure all prereq projects have valid build states... only when + // aborting builds since projects in cycles do not have build states + // except for projects involved in a 'warning' cycle (see below) + IProject[] requiredProjects = getRequiredProjects(false); + next: for (int i = 0, l = requiredProjects.length; i < l; i++) { + IProject p = requiredProjects[i]; + if (getLastState(p) == null) { + // The prereq project has no build state: if this prereq project + // has a + // 'warning' cycle marker then allow build (see bug id 23357) + JavaProject prereq = (JavaProject) JavaCore.create(p); + if (prereq.hasCycleMarker() + && JavaCore.WARNING.equals(javaProject.getOption( + JavaCore.CORE_CIRCULAR_CLASSPATH, true))) + continue; + if (DEBUG) + System.out.println("Aborted build because prereq project " + + p.getName() //$NON-NLS-1$ + + " was not built"); //$NON-NLS-1$ + removeProblemsAndTasksFor(currentProject); // make this the + // only + // problem for this project + IMarker marker = currentProject + .createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); + marker + .setAttribute( + IMarker.MESSAGE, + isClasspathBroken(prereq.getRawClasspath(), p) ? Util + .bind( + "build.prereqProjectHasClasspathProblems", p.getName()) //$NON-NLS-1$ + : Util + .bind( + "build.prereqProjectMustBeRebuilt", p.getName())); //$NON-NLS-1$ + marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); + return false; + } + } + return true; + } + + /* + * Instruct the build manager that this project is involved in a cycle and + * needs to propagate structural changes to the other projects in the cycle. + */ + void mustPropagateStructuralChanges() { + HashSet cycleParticipants = new HashSet(3); + javaProject.updateCycleParticipants(null, new ArrayList(), + cycleParticipants, workspaceRoot, new HashSet(3)); + IPath currentPath = javaProject.getPath(); + Iterator i = cycleParticipants.iterator(); + while (i.hasNext()) { + IPath participantPath = (IPath) i.next(); + if (participantPath != currentPath) { + IProject project = this.workspaceRoot + .getProject(participantPath.segment(0)); + if (hasBeenBuilt(project)) { + if (DEBUG) + System.out + .println("Requesting another build iteration since cycle participant " + + project.getName() //$NON-NLS-1$ + + " has not yet seen some structural changes"); //$NON-NLS-1$ + needRebuild(); + return; + } + } + } + } + + private void recordNewState(State state) { + Object[] keyTable = binaryLocationsPerProject.keyTable; + for (int i = 0, l = keyTable.length; i < l; i++) { + IProject prereqProject = (IProject) keyTable[i]; + if (prereqProject != null && prereqProject != currentProject) + state.recordStructuralDependency(prereqProject, + getLastState(prereqProject)); + } + if (DEBUG) + System.out.println("Recording new state : " + state); //$NON-NLS-1$ + // state.dump(); + JavaModelManager.getJavaModelManager().setLastBuiltState( + currentProject, state); + } + + /** + * String representation for debugging purposes + */ + public String toString() { + return currentProject == null ? "JavaBuilder for unknown project" //$NON-NLS-1$ + : "JavaBuilder for " + currentProject.getName(); //$NON-NLS-1$ + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ParserVisitor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ParserVisitor.java index ef6491d..b34f40a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ParserVisitor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ParserVisitor.java @@ -14,81 +14,88 @@ import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; /** - * + * * @see org.eclipse.core.resources.IResourceDelta * @see org.eclipse.core.resources.IResourceDeltaVisitor */ public class ParserVisitor implements IResourceDeltaVisitor { - final IProgressMonitor fMonitor; - final IProject fProject; - public ParserVisitor(IProject iProject, IProgressMonitor monitor) { - fMonitor = monitor; - fProject = iProject; - } - - protected void checkCancel() { - if (fMonitor.isCanceled()) { - throw new OperationCanceledException(); - } - } - - /** - * Visits the given resource delta. - * - * @return true if the resource delta's children should - * be visited; false if they should be skipped. - * @exception CoreException if the visit fails for some reason. - */ - public boolean visit(IResourceDelta delta) throws CoreException { - - IResource resource = delta.getResource(); - int resourceType = resource.getType(); - checkCancel(); - - final IdentifierIndexManager indexManager = PHPeclipsePlugin.getDefault().getIndexManager(fProject); - - switch (delta.getKind()) { - case IResourceDelta.ADDED : - if (resourceType == IResource.FILE) { - if ((resource.getFileExtension() != null) && PHPFileUtil.isPHPFile((IFile) resource)) { - fMonitor.worked(1); - fMonitor.subTask("Adding: " + resource.getFullPath()); - - // check for parsing errors - //PHPParserAction.parseFile((IFile) resource); - // update indexfile for the project: - indexManager.addFile((IFile) resource); - } - } - break; - - case IResourceDelta.CHANGED : - if (resourceType == IResource.FILE) { - if ((resource.getFileExtension() != null) && PHPFileUtil.isPHPFile((IFile) resource)) { - fMonitor.worked(1); - fMonitor.subTask("Changing: " + resource.getFullPath()); - - //check for parsing errors - //PHPParserAction.parseFile((IFile) resource); - // update indexfile for the project: - indexManager.changeFile((IFile) resource); - } - } - break; - - case IResourceDelta.REMOVED : - if (resourceType == IResource.FILE) { - if ((resource.getFileExtension() != null) && PHPFileUtil.isPHPFile((IFile) resource)) { - fMonitor.worked(1); - fMonitor.subTask("Removing: " + resource.getFullPath()); - - // update indexfile for the project: - indexManager.removeFile((IFile) resource); - } - } - break; - } - return true; // carry on - } + final IProgressMonitor fMonitor; + + final IProject fProject; + + public ParserVisitor(IProject iProject, IProgressMonitor monitor) { + fMonitor = monitor; + fProject = iProject; + } + + protected void checkCancel() { + if (fMonitor.isCanceled()) { + throw new OperationCanceledException(); + } + } + + /** + * Visits the given resource delta. + * + * @return true if the resource delta's children should be + * visited; false if they should be skipped. + * @exception CoreException + * if the visit fails for some reason. + */ + public boolean visit(IResourceDelta delta) throws CoreException { + + IResource resource = delta.getResource(); + int resourceType = resource.getType(); + checkCancel(); + + final IdentifierIndexManager indexManager = PHPeclipsePlugin + .getDefault().getIndexManager(fProject); + + switch (delta.getKind()) { + case IResourceDelta.ADDED: + if (resourceType == IResource.FILE) { + if ((resource.getFileExtension() != null) + && PHPFileUtil.isPHPFile((IFile) resource)) { + fMonitor.worked(1); + fMonitor.subTask("Adding: " + resource.getFullPath()); + + // check for parsing errors + // PHPParserAction.parseFile((IFile) resource); + // update indexfile for the project: + indexManager.addFile((IFile) resource); + } + } + break; + + case IResourceDelta.CHANGED: + if (resourceType == IResource.FILE) { + if ((resource.getFileExtension() != null) + && PHPFileUtil.isPHPFile((IFile) resource)) { + fMonitor.worked(1); + fMonitor.subTask("Changing: " + resource.getFullPath()); + + // check for parsing errors + // PHPParserAction.parseFile((IFile) resource); + // update indexfile for the project: + indexManager.changeFile((IFile) resource); + } + } + break; + + case IResourceDelta.REMOVED: + if (resourceType == IResource.FILE) { + if ((resource.getFileExtension() != null) + && PHPFileUtil.isPHPFile((IFile) resource)) { + fMonitor.worked(1); + fMonitor.subTask("Removing: " + resource.getFullPath()); + + // update indexfile for the project: + indexManager.removeFile((IFile) resource); + } + } + break; + } + return true; // carry on + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ProblemFactory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ProblemFactory.java index e3124ae..3e7cf39 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ProblemFactory.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ProblemFactory.java @@ -17,16 +17,16 @@ import net.sourceforge.phpdt.internal.core.util.SimpleLookupTable; public class ProblemFactory extends DefaultProblemFactory { -static SimpleLookupTable factories = new SimpleLookupTable(5); + static SimpleLookupTable factories = new SimpleLookupTable(5); -private ProblemFactory(Locale locale) { - super(locale); -} + private ProblemFactory(Locale locale) { + super(locale); + } -public static ProblemFactory getProblemFactory(Locale locale) { - ProblemFactory factory = (ProblemFactory) factories.get(locale); - if (factory == null) - factories.put(locale, factory = new ProblemFactory(locale)); - return factory; -} + public static ProblemFactory getProblemFactory(Locale locale) { + ProblemFactory factory = (ProblemFactory) factories.get(locale); + if (factory == null) + factories.put(locale, factory = new ProblemFactory(locale)); + return factory; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/SourceFile.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/SourceFile.java index cac68c2..9299455 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/SourceFile.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/SourceFile.java @@ -30,7 +30,8 @@ public class SourceFile implements ICompilationUnit { String encoding; - public SourceFile(IFile resource, ClasspathMultiDirectory sourceLocation, String encoding) { + public SourceFile(IFile resource, ClasspathMultiDirectory sourceLocation, + String encoding) { this.resource = resource; this.sourceLocation = sourceLocation; this.initialTypeName = extractTypeName(); @@ -44,20 +45,24 @@ public class SourceFile implements ICompilationUnit { return false; SourceFile f = (SourceFile) o; - return sourceLocation == f.sourceLocation && resource.getFullPath().equals(f.resource.getFullPath()); + return sourceLocation == f.sourceLocation + && resource.getFullPath().equals(f.resource.getFullPath()); } String extractTypeName() { - // answer a String with the qualified type name for the source file in the + // answer a String with the qualified type name for the source file in + // the // form: 'p1/p2/A' IPath fullPath = resource.getFullPath(); int resourceSegmentCount = fullPath.segmentCount(); - int sourceFolderSegmentCount = sourceLocation.sourceFolder.getFullPath().segmentCount(); + int sourceFolderSegmentCount = sourceLocation.sourceFolder + .getFullPath().segmentCount(); String extension = fullPath.getFileExtension(); int ext_length = extension == null ? 0 : extension.length() + 1; - int charCount = (resourceSegmentCount - sourceFolderSegmentCount - 1) - ext_length; // length - // of - // ".php" + int charCount = (resourceSegmentCount - sourceFolderSegmentCount - 1) + - ext_length; // length + // of + // ".php" for (int i = sourceFolderSegmentCount; i < resourceSegmentCount; i++) charCount += fullPath.segment(i).length(); @@ -82,14 +87,16 @@ public class SourceFile implements ICompilationUnit { try { return Util.getResourceContentsAsCharArray(resource, this.encoding); } catch (CoreException e) { - throw new AbortCompilation(true, new MissingSourceFileException(resource.getFullPath().toString())); + throw new AbortCompilation(true, new MissingSourceFileException( + resource.getFullPath().toString())); } } public char[] getFileName() { - return resource.getFullPath().toString().toCharArray(); // do not know what - // you want to - // return here + return resource.getFullPath().toString().toCharArray(); // do not know + // what + // you want to + // return here } public char[] getMainTypeName() { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/State.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/State.java index 1e0fe32..4d60110 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/State.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/State.java @@ -23,534 +23,596 @@ import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.runtime.IPath; public class State { - // NOTE: this state cannot contain types that are not defined in this project - - String javaProjectName; - ClasspathMultiDirectory[] sourceLocations; - //ClasspathLocation[] binaryLocations; - // keyed by the project relative path of the type (ie. "src1/p1/p2/A.java"), value is a ReferenceCollection or an - // AdditionalTypeCollection -// SimpleLookupTable references; - // keyed by qualified type name "p1/p2/A", value is the project relative path which defines this type "src1/p1/p2/A.java" -// SimpleLookupTable typeLocators; - - int buildNumber; - long lastStructuralBuildTime; - SimpleLookupTable structuralBuildTimes; - - private String[] knownPackageNames; // of the form "p1/p2" - - static final byte VERSION = 0x0007; - - static final byte SOURCE_FOLDER = 1; -// static final byte BINARY_FOLDER = 2; -// static final byte EXTERNAL_JAR = 3; -// static final byte INTERNAL_JAR = 4; - - State() { - } - - protected State(PHPBuilder javaBuilder) { - this.knownPackageNames = null; - this.javaProjectName = javaBuilder.currentProject.getName(); - this.sourceLocations = javaBuilder.nameEnvironment.sourceLocations; - // this.binaryLocations = javaBuilder.nameEnvironment.binaryLocations; -// this.references = new SimpleLookupTable(7); -// this.typeLocators = new SimpleLookupTable(7); - - this.buildNumber = 0; // indicates a full build - this.lastStructuralBuildTime = System.currentTimeMillis(); - this.structuralBuildTimes = new SimpleLookupTable(3); - } - - void copyFrom(State lastState) { -// try { - this.knownPackageNames = null; - this.buildNumber = lastState.buildNumber + 1; - this.lastStructuralBuildTime = lastState.lastStructuralBuildTime; -// this.references = (SimpleLookupTable) lastState.references.clone(); -// this.typeLocators = (SimpleLookupTable) lastState.typeLocators.clone(); -// } catch (CloneNotSupportedException e) { -// this.references = new SimpleLookupTable(lastState.references.elementSize); -// Object[] keyTable = lastState.references.keyTable; -// Object[] valueTable = lastState.references.valueTable; -// for (int i = 0, l = keyTable.length; i < l; i++) -// if (keyTable[i] != null) -// this.references.put(keyTable[i], valueTable[i]); -// -// this.typeLocators = new SimpleLookupTable(lastState.typeLocators.elementSize); -// keyTable = lastState.typeLocators.keyTable; -// valueTable = lastState.typeLocators.valueTable; -// for (int i = 0, l = keyTable.length; i < l; i++) -// if (keyTable[i] != null) -// this.typeLocators.put(keyTable[i], valueTable[i]); -// } - } - -// char[][] getDefinedTypeNamesFor(String typeLocator) { -// Object c = references.get(typeLocator); -// if (c instanceof AdditionalTypeCollection) -// return ((AdditionalTypeCollection) c).definedTypeNames; -// return null; // means only one type is defined with the same name as the file... saves space -// } - -// boolean isDuplicateLocator(String qualifiedTypeName, String typeLocator) { -// String existing = (String) typeLocators.get(qualifiedTypeName); -// return existing != null && !existing.equals(typeLocator); -// } - -// boolean isKnownPackage(String qualifiedPackageName) { -// if (knownPackageNames == null) { -// ArrayList names = new ArrayList(typeLocators.elementSize); -// Object[] keyTable = typeLocators.keyTable; -// for (int i = 0, l = keyTable.length; i < l; i++) { -// if (keyTable[i] != null) { -// String packageName = (String) keyTable[i]; // is a type name of the form p1/p2/A -// int last = packageName.lastIndexOf('/'); -// packageName = last == -1 ? null : packageName.substring(0, last); -// while (packageName != null && !names.contains(packageName)) { -// names.add(packageName); -// last = packageName.lastIndexOf('/'); -// packageName = last == -1 ? null : packageName.substring(0, last); -// } -// } -// } -// knownPackageNames = new String[names.size()]; -// names.toArray(knownPackageNames); -// } -// for (int i = 0, l = knownPackageNames.length; i < l; i++) -// if (knownPackageNames[i].equals(qualifiedPackageName)) -// return true; -// return false; -// } - -// void record(String typeLocator, char[][][] qualifiedRefs, char[][] simpleRefs, char[] mainTypeName, ArrayList typeNames) { -// if (typeNames.size() == 1 && CharOperation.equals(mainTypeName, (char[]) typeNames.get(0))) { -// references.put(typeLocator, new ReferenceCollection(qualifiedRefs, simpleRefs)); -// } else { -// char[][] definedTypeNames = new char[typeNames.size()][]; // can be empty when no types are defined -// typeNames.toArray(definedTypeNames); -// references.put(typeLocator, new AdditionalTypeCollection(definedTypeNames, qualifiedRefs, simpleRefs)); -// } -// } -// -// void recordLocatorForType(String qualifiedTypeName, String typeLocator) { -// this.knownPackageNames = null; -// typeLocators.put(qualifiedTypeName, typeLocator); -// } - - void recordStructuralDependency(IProject prereqProject, State prereqState) { - if (prereqState != null) - structuralBuildTimes.put(prereqProject.getName(), new Long(prereqState.lastStructuralBuildTime)); - } - -// void removeLocator(String typeLocatorToRemove) { -// this.knownPackageNames = null; -// references.removeKey(typeLocatorToRemove); -// typeLocators.removeValue(typeLocatorToRemove); -// } - - void removePackage(IResourceDelta sourceDelta) { - IResource resource = sourceDelta.getResource(); - switch (resource.getType()) { - case IResource.FOLDER : - IResourceDelta[] children = sourceDelta.getAffectedChildren(); - for (int i = 0, l = children.length; i < l; i++) - removePackage(children[i]); - return; - case IResource.FILE : - IPath typeLocatorPath = resource.getProjectRelativePath(); -// if (ProjectPrefUtil.isJavaFileName(typeLocatorPath.lastSegment())) -// removeLocator(typeLocatorPath.toString()); - } - } - -// void removeQualifiedTypeName(String qualifiedTypeNameToRemove) { -// this.knownPackageNames = null; -// typeLocators.removeKey(qualifiedTypeNameToRemove); -// } - - static State read(IProject project, DataInputStream in) throws IOException { - if (PHPBuilder.DEBUG) - System.out.println("About to read state..."); //$NON-NLS-1$ - if (VERSION != in.readByte()) { - if (PHPBuilder.DEBUG) - System.out.println("Found non-compatible state version... answered null"); //$NON-NLS-1$ - return null; - } - - State newState = new State(); - newState.javaProjectName = in.readUTF(); - if (!project.getName().equals(newState.javaProjectName)) { - if (PHPBuilder.DEBUG) - System.out.println("Project's name does not match... answered null"); //$NON-NLS-1$ - return null; - } - newState.buildNumber = in.readInt(); - newState.lastStructuralBuildTime = in.readLong(); - - int length; -// int length = in.readInt(); -// newState.sourceLocations = new ClasspathMultiDirectory[0]; - // newState.sourceLocations = new ClasspathMultiDirectory[length]; - // for (int i = 0; i < length; i++) { - // IContainer sourceFolder = project, outputFolder = project; - // String folderName; - // if ((folderName = in.readUTF()).length() > 0) sourceFolder = project.getFolder(folderName); - // if ((folderName = in.readUTF()).length() > 0) outputFolder = project.getFolder(folderName); - // ClasspathMultiDirectory md = - // (ClasspathMultiDirectory) ClasspathLocation.forSourceFolder(sourceFolder, outputFolder, readNames(in)); - // if (in.readBoolean()) - // md.hasIndependentOutputFolder = true; - // newState.sourceLocations[i] = md; - // } - -// length = in.readInt(); - // newState.binaryLocations = new ClasspathLocation[length]; - // IWorkspaceRoot root = project.getWorkspace().getRoot(); - // for (int i = 0; i < length; i++) { - // switch (in.readByte()) { - // case SOURCE_FOLDER : - // newState.binaryLocations[i] = newState.sourceLocations[in.readInt()]; - // break; - // case BINARY_FOLDER : - // IPath path = new Path(in.readUTF()); - // IContainer outputFolder = path.segmentCount() == 1 - // ? (IContainer) root.getProject(path.toString()) - // : (IContainer) root.getFolder(path); - // newState.binaryLocations[i] = ClasspathLocation.forBinaryFolder(outputFolder, in.readBoolean()); - // break; - // case EXTERNAL_JAR : - // newState.binaryLocations[i] = ClasspathLocation.forLibrary(in.readUTF()); - // break; - // case INTERNAL_JAR : - // newState.binaryLocations[i] = ClasspathLocation.forLibrary(root.getFile(new Path(in.readUTF()))); - // } - // } - - newState.structuralBuildTimes = new SimpleLookupTable(length = in.readInt()); - for (int i = 0; i < length; i++) - newState.structuralBuildTimes.put(in.readUTF(), new Long(in.readLong())); - -// String[] internedTypeLocators = new String[length = in.readInt()]; -// for (int i = 0; i < length; i++) -// internedTypeLocators[i] = in.readUTF(); - -// newState.typeLocators = new SimpleLookupTable(length = in.readInt()); -// for (int i = 0; i < length; i++) -// newState.typeLocators.put(in.readUTF(), internedTypeLocators[in.readInt()]); - -// char[][] internedSimpleNames = ReferenceCollection.internSimpleNames(readNames(in), false); -// char[][][] internedQualifiedNames = new char[length = in.readInt()][][]; -// for (int i = 0; i < length; i++) { -// int qLength = in.readInt(); -// char[][] qName = new char[qLength][]; -// for (int j = 0; j < qLength; j++) -// qName[j] = internedSimpleNames[in.readInt()]; -// internedQualifiedNames[i] = qName; -// } -// internedQualifiedNames = ReferenceCollection.internQualifiedNames(internedQualifiedNames); -// -// newState.references = new SimpleLookupTable(length = in.readInt()); -// for (int i = 0; i < length; i++) { -// String typeLocator = internedTypeLocators[in.readInt()]; -// ReferenceCollection collection = null; -// switch (in.readByte()) { -// case 1 : -// char[][] additionalTypeNames = readNames(in); -// char[][][] qualifiedNames = new char[in.readInt()][][]; -// for (int j = 0, m = qualifiedNames.length; j < m; j++) -// qualifiedNames[j] = internedQualifiedNames[in.readInt()]; -// char[][] simpleNames = new char[in.readInt()][]; -// for (int j = 0, m = simpleNames.length; j < m; j++) -// simpleNames[j] = internedSimpleNames[in.readInt()]; -// collection = new AdditionalTypeCollection(additionalTypeNames, qualifiedNames, simpleNames); -// break; -// case 2 : -// char[][][] qNames = new char[in.readInt()][][]; -// for (int j = 0, m = qNames.length; j < m; j++) -// qNames[j] = internedQualifiedNames[in.readInt()]; -// char[][] sNames = new char[in.readInt()][]; -// for (int j = 0, m = sNames.length; j < m; j++) -// sNames[j] = internedSimpleNames[in.readInt()]; -// collection = new ReferenceCollection(qNames, sNames); -// } -// newState.references.put(typeLocator, collection); -// } - if (PHPBuilder.DEBUG) - System.out.println("Successfully read state for " + newState.javaProjectName); //$NON-NLS-1$ - return newState; - } - - private static char[][] readNames(DataInputStream in) throws IOException { - int length = in.readInt(); - char[][] names = new char[length][]; - for (int i = 0; i < length; i++) { - int nLength = in.readInt(); - char[] name = new char[nLength]; - for (int j = 0; j < nLength; j++) - name[j] = in.readChar(); - names[i] = name; - } - return names; - } - - void tagAsNoopBuild() { - this.buildNumber = -1; // tag the project since it has no source folders and can be skipped - } - - boolean wasNoopBuild() { - return buildNumber == -1; - } - - void tagAsStructurallyChanged() { - this.lastStructuralBuildTime = System.currentTimeMillis(); - } - - boolean wasStructurallyChanged(IProject prereqProject, State prereqState) { - if (prereqState != null) { - Object o = structuralBuildTimes.get(prereqProject.getName()); - long previous = o == null ? 0 : ((Long) o).longValue(); - if (previous == prereqState.lastStructuralBuildTime) - return false; - } - return true; - } - - void write(DataOutputStream out) throws IOException { - int length; - Object[] keyTable; - Object[] valueTable; - - /* - * byte VERSION String project name int build number int last structural build number + // NOTE: this state cannot contain types that are not defined in this + // project + + String javaProjectName; + + ClasspathMultiDirectory[] sourceLocations; + + // ClasspathLocation[] binaryLocations; + // keyed by the project relative path of the type (ie. "src1/p1/p2/A.java"), + // value is a ReferenceCollection or an + // AdditionalTypeCollection + // SimpleLookupTable references; + // keyed by qualified type name "p1/p2/A", value is the project relative + // path which defines this type "src1/p1/p2/A.java" + // SimpleLookupTable typeLocators; + + int buildNumber; + + long lastStructuralBuildTime; + + SimpleLookupTable structuralBuildTimes; + + private String[] knownPackageNames; // of the form "p1/p2" + + static final byte VERSION = 0x0007; + + static final byte SOURCE_FOLDER = 1; + + // static final byte BINARY_FOLDER = 2; + // static final byte EXTERNAL_JAR = 3; + // static final byte INTERNAL_JAR = 4; + + State() { + } + + protected State(PHPBuilder javaBuilder) { + this.knownPackageNames = null; + this.javaProjectName = javaBuilder.currentProject.getName(); + this.sourceLocations = javaBuilder.nameEnvironment.sourceLocations; + // this.binaryLocations = javaBuilder.nameEnvironment.binaryLocations; + // this.references = new SimpleLookupTable(7); + // this.typeLocators = new SimpleLookupTable(7); + + this.buildNumber = 0; // indicates a full build + this.lastStructuralBuildTime = System.currentTimeMillis(); + this.structuralBuildTimes = new SimpleLookupTable(3); + } + + void copyFrom(State lastState) { + // try { + this.knownPackageNames = null; + this.buildNumber = lastState.buildNumber + 1; + this.lastStructuralBuildTime = lastState.lastStructuralBuildTime; + // this.references = (SimpleLookupTable) lastState.references.clone(); + // this.typeLocators = (SimpleLookupTable) + // lastState.typeLocators.clone(); + // } catch (CloneNotSupportedException e) { + // this.references = new + // SimpleLookupTable(lastState.references.elementSize); + // Object[] keyTable = lastState.references.keyTable; + // Object[] valueTable = lastState.references.valueTable; + // for (int i = 0, l = keyTable.length; i < l; i++) + // if (keyTable[i] != null) + // this.references.put(keyTable[i], valueTable[i]); + // + // this.typeLocators = new + // SimpleLookupTable(lastState.typeLocators.elementSize); + // keyTable = lastState.typeLocators.keyTable; + // valueTable = lastState.typeLocators.valueTable; + // for (int i = 0, l = keyTable.length; i < l; i++) + // if (keyTable[i] != null) + // this.typeLocators.put(keyTable[i], valueTable[i]); + // } + } + + // char[][] getDefinedTypeNamesFor(String typeLocator) { + // Object c = references.get(typeLocator); + // if (c instanceof AdditionalTypeCollection) + // return ((AdditionalTypeCollection) c).definedTypeNames; + // return null; // means only one type is defined with the same name as the + // file... saves space + // } + + // boolean isDuplicateLocator(String qualifiedTypeName, String typeLocator) + // { + // String existing = (String) typeLocators.get(qualifiedTypeName); + // return existing != null && !existing.equals(typeLocator); + // } + + // boolean isKnownPackage(String qualifiedPackageName) { + // if (knownPackageNames == null) { + // ArrayList names = new ArrayList(typeLocators.elementSize); + // Object[] keyTable = typeLocators.keyTable; + // for (int i = 0, l = keyTable.length; i < l; i++) { + // if (keyTable[i] != null) { + // String packageName = (String) keyTable[i]; // is a type name of the form + // p1/p2/A + // int last = packageName.lastIndexOf('/'); + // packageName = last == -1 ? null : packageName.substring(0, last); + // while (packageName != null && !names.contains(packageName)) { + // names.add(packageName); + // last = packageName.lastIndexOf('/'); + // packageName = last == -1 ? null : packageName.substring(0, last); + // } + // } + // } + // knownPackageNames = new String[names.size()]; + // names.toArray(knownPackageNames); + // } + // for (int i = 0, l = knownPackageNames.length; i < l; i++) + // if (knownPackageNames[i].equals(qualifiedPackageName)) + // return true; + // return false; + // } + + // void record(String typeLocator, char[][][] qualifiedRefs, char[][] + // simpleRefs, char[] mainTypeName, ArrayList typeNames) { + // if (typeNames.size() == 1 && CharOperation.equals(mainTypeName, (char[]) + // typeNames.get(0))) { + // references.put(typeLocator, new ReferenceCollection(qualifiedRefs, + // simpleRefs)); + // } else { + // char[][] definedTypeNames = new char[typeNames.size()][]; // can be empty + // when no types are defined + // typeNames.toArray(definedTypeNames); + // references.put(typeLocator, new + // AdditionalTypeCollection(definedTypeNames, qualifiedRefs, simpleRefs)); + // } + // } + // + // void recordLocatorForType(String qualifiedTypeName, String typeLocator) { + // this.knownPackageNames = null; + // typeLocators.put(qualifiedTypeName, typeLocator); + // } + + void recordStructuralDependency(IProject prereqProject, State prereqState) { + if (prereqState != null) + structuralBuildTimes.put(prereqProject.getName(), new Long( + prereqState.lastStructuralBuildTime)); + } + + // void removeLocator(String typeLocatorToRemove) { + // this.knownPackageNames = null; + // references.removeKey(typeLocatorToRemove); + // typeLocators.removeValue(typeLocatorToRemove); + // } + + void removePackage(IResourceDelta sourceDelta) { + IResource resource = sourceDelta.getResource(); + switch (resource.getType()) { + case IResource.FOLDER: + IResourceDelta[] children = sourceDelta.getAffectedChildren(); + for (int i = 0, l = children.length; i < l; i++) + removePackage(children[i]); + return; + case IResource.FILE: + IPath typeLocatorPath = resource.getProjectRelativePath(); + // if + // (ProjectPrefUtil.isJavaFileName(typeLocatorPath.lastSegment())) + // removeLocator(typeLocatorPath.toString()); + } + } + + // void removeQualifiedTypeName(String qualifiedTypeNameToRemove) { + // this.knownPackageNames = null; + // typeLocators.removeKey(qualifiedTypeNameToRemove); + // } + + static State read(IProject project, DataInputStream in) throws IOException { + if (PHPBuilder.DEBUG) + System.out.println("About to read state..."); //$NON-NLS-1$ + if (VERSION != in.readByte()) { + if (PHPBuilder.DEBUG) + System.out + .println("Found non-compatible state version... answered null"); //$NON-NLS-1$ + return null; + } + + State newState = new State(); + newState.javaProjectName = in.readUTF(); + if (!project.getName().equals(newState.javaProjectName)) { + if (PHPBuilder.DEBUG) + System.out + .println("Project's name does not match... answered null"); //$NON-NLS-1$ + return null; + } + newState.buildNumber = in.readInt(); + newState.lastStructuralBuildTime = in.readLong(); + + int length; + // int length = in.readInt(); + // newState.sourceLocations = new ClasspathMultiDirectory[0]; + // newState.sourceLocations = new ClasspathMultiDirectory[length]; + // for (int i = 0; i < length; i++) { + // IContainer sourceFolder = project, outputFolder = project; + // String folderName; + // if ((folderName = in.readUTF()).length() > 0) sourceFolder = + // project.getFolder(folderName); + // if ((folderName = in.readUTF()).length() > 0) outputFolder = + // project.getFolder(folderName); + // ClasspathMultiDirectory md = + // (ClasspathMultiDirectory) + // ClasspathLocation.forSourceFolder(sourceFolder, outputFolder, + // readNames(in)); + // if (in.readBoolean()) + // md.hasIndependentOutputFolder = true; + // newState.sourceLocations[i] = md; + // } + + // length = in.readInt(); + // newState.binaryLocations = new ClasspathLocation[length]; + // IWorkspaceRoot root = project.getWorkspace().getRoot(); + // for (int i = 0; i < length; i++) { + // switch (in.readByte()) { + // case SOURCE_FOLDER : + // newState.binaryLocations[i] = newState.sourceLocations[in.readInt()]; + // break; + // case BINARY_FOLDER : + // IPath path = new Path(in.readUTF()); + // IContainer outputFolder = path.segmentCount() == 1 + // ? (IContainer) root.getProject(path.toString()) + // : (IContainer) root.getFolder(path); + // newState.binaryLocations[i] = + // ClasspathLocation.forBinaryFolder(outputFolder, in.readBoolean()); + // break; + // case EXTERNAL_JAR : + // newState.binaryLocations[i] = + // ClasspathLocation.forLibrary(in.readUTF()); + // break; + // case INTERNAL_JAR : + // newState.binaryLocations[i] = + // ClasspathLocation.forLibrary(root.getFile(new Path(in.readUTF()))); + // } + // } + + newState.structuralBuildTimes = new SimpleLookupTable(length = in + .readInt()); + for (int i = 0; i < length; i++) + newState.structuralBuildTimes.put(in.readUTF(), new Long(in + .readLong())); + + // String[] internedTypeLocators = new String[length = in.readInt()]; + // for (int i = 0; i < length; i++) + // internedTypeLocators[i] = in.readUTF(); + + // newState.typeLocators = new SimpleLookupTable(length = in.readInt()); + // for (int i = 0; i < length; i++) + // newState.typeLocators.put(in.readUTF(), + // internedTypeLocators[in.readInt()]); + + // char[][] internedSimpleNames = + // ReferenceCollection.internSimpleNames(readNames(in), false); + // char[][][] internedQualifiedNames = new char[length = + // in.readInt()][][]; + // for (int i = 0; i < length; i++) { + // int qLength = in.readInt(); + // char[][] qName = new char[qLength][]; + // for (int j = 0; j < qLength; j++) + // qName[j] = internedSimpleNames[in.readInt()]; + // internedQualifiedNames[i] = qName; + // } + // internedQualifiedNames = + // ReferenceCollection.internQualifiedNames(internedQualifiedNames); + // + // newState.references = new SimpleLookupTable(length = in.readInt()); + // for (int i = 0; i < length; i++) { + // String typeLocator = internedTypeLocators[in.readInt()]; + // ReferenceCollection collection = null; + // switch (in.readByte()) { + // case 1 : + // char[][] additionalTypeNames = readNames(in); + // char[][][] qualifiedNames = new char[in.readInt()][][]; + // for (int j = 0, m = qualifiedNames.length; j < m; j++) + // qualifiedNames[j] = internedQualifiedNames[in.readInt()]; + // char[][] simpleNames = new char[in.readInt()][]; + // for (int j = 0, m = simpleNames.length; j < m; j++) + // simpleNames[j] = internedSimpleNames[in.readInt()]; + // collection = new AdditionalTypeCollection(additionalTypeNames, + // qualifiedNames, simpleNames); + // break; + // case 2 : + // char[][][] qNames = new char[in.readInt()][][]; + // for (int j = 0, m = qNames.length; j < m; j++) + // qNames[j] = internedQualifiedNames[in.readInt()]; + // char[][] sNames = new char[in.readInt()][]; + // for (int j = 0, m = sNames.length; j < m; j++) + // sNames[j] = internedSimpleNames[in.readInt()]; + // collection = new ReferenceCollection(qNames, sNames); + // } + // newState.references.put(typeLocator, collection); + // } + if (PHPBuilder.DEBUG) + System.out + .println("Successfully read state for " + newState.javaProjectName); //$NON-NLS-1$ + return newState; + } + + private static char[][] readNames(DataInputStream in) throws IOException { + int length = in.readInt(); + char[][] names = new char[length][]; + for (int i = 0; i < length; i++) { + int nLength = in.readInt(); + char[] name = new char[nLength]; + for (int j = 0; j < nLength; j++) + name[j] = in.readChar(); + names[i] = name; + } + return names; + } + + void tagAsNoopBuild() { + this.buildNumber = -1; // tag the project since it has no source + // folders and can be skipped + } + + boolean wasNoopBuild() { + return buildNumber == -1; + } + + void tagAsStructurallyChanged() { + this.lastStructuralBuildTime = System.currentTimeMillis(); + } + + boolean wasStructurallyChanged(IProject prereqProject, State prereqState) { + if (prereqState != null) { + Object o = structuralBuildTimes.get(prereqProject.getName()); + long previous = o == null ? 0 : ((Long) o).longValue(); + if (previous == prereqState.lastStructuralBuildTime) + return false; + } + return true; + } + + void write(DataOutputStream out) throws IOException { + int length; + Object[] keyTable; + Object[] valueTable; + + /* + * byte VERSION String project name int build number int last structural + * build number + */ + out.writeByte(VERSION); + out.writeUTF(javaProjectName); + out.writeInt(buildNumber); + out.writeLong(lastStructuralBuildTime); + + /* + * ClasspathMultiDirectory[] int id String path(s) + */ + // out.writeInt(length = sourceLocations.length); + // for (int i = 0; i < length; i++) { + // ClasspathMultiDirectory md = sourceLocations[i]; + // out.writeUTF(md.sourceFolder.getProjectRelativePath().toString()); + // out.writeUTF(md.binaryFolder.getProjectRelativePath().toString()); + // writeNames(md.exclusionPatterns, out); + // out.writeBoolean(md.hasIndependentOutputFolder); + // } + /* + * ClasspathLocation[] int id String path(s) + */ + // out.writeInt(length = binaryLocations.length); + // next : for (int i = 0; i < length; i++) { + // ClasspathLocation c = binaryLocations[i]; + // if (c instanceof ClasspathMultiDirectory) { + // out.writeByte(SOURCE_FOLDER); + // for (int j = 0, m = sourceLocations.length; j < m; j++) { + // if (sourceLocations[j] == c) { + // out.writeInt(j); + // continue next; + // } + // } + // } else if (c instanceof ClasspathDirectory) { + // out.writeByte(BINARY_FOLDER); + // ClasspathDirectory cd = (ClasspathDirectory) c; + // out.writeUTF(cd.binaryFolder.getFullPath().toString()); + // out.writeBoolean(cd.isOutputFolder); + // } else { + // ClasspathJar jar = (ClasspathJar) c; + // if (jar.resource == null) { + // out.writeByte(EXTERNAL_JAR); + // out.writeUTF(jar.zipFilename); + // } else { + // out.writeByte(INTERNAL_JAR); + // out.writeUTF(jar.resource.getFullPath().toString()); + // } + // } + // } + /* + * Structural build numbers table String prereq project name int last + * structural build number + */ + out.writeInt(length = structuralBuildTimes.elementSize); + if (length > 0) { + keyTable = structuralBuildTimes.keyTable; + valueTable = structuralBuildTimes.valueTable; + for (int i = 0, l = keyTable.length; i < l; i++) { + if (keyTable[i] != null) { + length--; + out.writeUTF((String) keyTable[i]); + out.writeLong(((Long) valueTable[i]).longValue()); + } + } + if (PHPBuilder.DEBUG && length != 0) + System.out + .println("structuralBuildNumbers table is inconsistent"); //$NON-NLS-1$ + } + + /* + * String[] Interned type locators + */ + // out.writeInt(length = references.elementSize); + // ArrayList internedTypeLocators = new ArrayList(length); + // if (length > 0) { + // keyTable = references.keyTable; + // for (int i = 0, l = keyTable.length; i < l; i++) { + // if (keyTable[i] != null) { + // length--; + // String key = (String) keyTable[i]; + // out.writeUTF(key); + // internedTypeLocators.add(key); + // } + // } + // if (PHPBuilder.DEBUG && length != 0) + // System.out.println("references table is inconsistent"); //$NON-NLS-1$ + // } + /* + * Type locators table String type name int interned locator id + */ + // out.writeInt(length = typeLocators.elementSize); + // if (length > 0) { + // keyTable = typeLocators.keyTable; + // valueTable = typeLocators.valueTable; + // for (int i = 0, l = keyTable.length; i < l; i++) { + // if (keyTable[i] != null) { + // length--; + // out.writeUTF((String) keyTable[i]); + // out.writeInt(internedTypeLocators.indexOf((String) valueTable[i])); + // } + // } + // if (PHPBuilder.DEBUG && length != 0) + // System.out.println("typeLocators table is inconsistent"); + // //$NON-NLS-1$ + // } + /* + * char[][][] Interned qualified names char[][] Interned simple names + */ + // ArrayList internedQualifiedNames = new ArrayList(31); + // ArrayList internedSimpleNames = new ArrayList(31); + // valueTable = references.valueTable; + // for (int i = 0, l = valueTable.length; i < l; i++) { + // if (valueTable[i] != null) { + // ReferenceCollection collection = (ReferenceCollection) valueTable[i]; + // char[][][] qNames = collection.qualifiedNameReferences; + // for (int j = 0, m = qNames.length; j < m; j++) { + // char[][] qName = qNames[j]; + // if (!internedQualifiedNames.contains(qName)) { // remember the names + // have been interned + // internedQualifiedNames.add(qName); + // for (int k = 0, n = qName.length; k < n; k++) { + // char[] sName = qName[k]; + // if (!internedSimpleNames.contains(sName)) // remember the names have + // been interned + // internedSimpleNames.add(sName); + // } + // } + // } + // char[][] sNames = collection.simpleNameReferences; + // for (int j = 0, m = sNames.length; j < m; j++) { + // char[] sName = sNames[j]; + // if (!internedSimpleNames.contains(sName)) // remember the names have + // been interned + // internedSimpleNames.add(sName); + // } + // } + // } + // char[][] internedArray = new char[internedSimpleNames.size()][]; + // internedSimpleNames.toArray(internedArray); + // writeNames(internedArray, out); + // // now write the interned qualified names as arrays of interned + // simple names + // out.writeInt(length = internedQualifiedNames.size()); + // for (int i = 0; i < length; i++) { + // char[][] qName = (char[][]) internedQualifiedNames.get(i); + // int qLength = qName.length; + // out.writeInt(qLength); + // for (int j = 0; j < qLength; j++) + // out.writeInt(internedSimpleNames.indexOf(qName[j])); + // } + // + // /* + // * References table int interned locator id ReferenceCollection + // */ + // out.writeInt(length = references.elementSize); + // if (length > 0) { + // keyTable = references.keyTable; + // for (int i = 0, l = keyTable.length; i < l; i++) { + // if (keyTable[i] != null) { + // length--; + // out.writeInt(internedTypeLocators.indexOf((String) keyTable[i])); + // ReferenceCollection collection = (ReferenceCollection) valueTable[i]; + // if (collection instanceof AdditionalTypeCollection) { + // out.writeByte(1); + // AdditionalTypeCollection atc = (AdditionalTypeCollection) collection; + // writeNames(atc.definedTypeNames, out); + // } else { + // out.writeByte(2); + // } + // char[][][] qNames = collection.qualifiedNameReferences; + // int qLength = qNames.length; + // out.writeInt(qLength); + // for (int j = 0; j < qLength; j++) + // out.writeInt(internedQualifiedNames.indexOf(qNames[j])); + // char[][] sNames = collection.simpleNameReferences; + // int sLength = sNames.length; + // out.writeInt(sLength); + // for (int j = 0; j < sLength; j++) + // out.writeInt(internedSimpleNames.indexOf(sNames[j])); + // } + // } + // if (PHPBuilder.DEBUG && length != 0) + // System.out.println("references table is inconsistent"); //$NON-NLS-1$ + // } + } + + private void writeNames(char[][] names, DataOutputStream out) + throws IOException { + int length = names == null ? 0 : names.length; + out.writeInt(length); + for (int i = 0; i < length; i++) { + char[] name = names[i]; + int nLength = name.length; + out.writeInt(nLength); + for (int j = 0; j < nLength; j++) + out.writeChar(name[j]); + } + } + + /** + * Returns a string representation of the receiver. */ - out.writeByte(VERSION); - out.writeUTF(javaProjectName); - out.writeInt(buildNumber); - out.writeLong(lastStructuralBuildTime); - - /* - * ClasspathMultiDirectory[] int id String path(s) - */ -// out.writeInt(length = sourceLocations.length); -// for (int i = 0; i < length; i++) { -// ClasspathMultiDirectory md = sourceLocations[i]; -// out.writeUTF(md.sourceFolder.getProjectRelativePath().toString()); -// out.writeUTF(md.binaryFolder.getProjectRelativePath().toString()); -// writeNames(md.exclusionPatterns, out); -// out.writeBoolean(md.hasIndependentOutputFolder); -// } - - /* - * ClasspathLocation[] int id String path(s) - */ - // out.writeInt(length = binaryLocations.length); - // next : for (int i = 0; i < length; i++) { - // ClasspathLocation c = binaryLocations[i]; - // if (c instanceof ClasspathMultiDirectory) { - // out.writeByte(SOURCE_FOLDER); - // for (int j = 0, m = sourceLocations.length; j < m; j++) { - // if (sourceLocations[j] == c) { - // out.writeInt(j); - // continue next; - // } - // } - // } else if (c instanceof ClasspathDirectory) { - // out.writeByte(BINARY_FOLDER); - // ClasspathDirectory cd = (ClasspathDirectory) c; - // out.writeUTF(cd.binaryFolder.getFullPath().toString()); - // out.writeBoolean(cd.isOutputFolder); - // } else { - // ClasspathJar jar = (ClasspathJar) c; - // if (jar.resource == null) { - // out.writeByte(EXTERNAL_JAR); - // out.writeUTF(jar.zipFilename); - // } else { - // out.writeByte(INTERNAL_JAR); - // out.writeUTF(jar.resource.getFullPath().toString()); - // } - // } - // } - - /* - * Structural build numbers table String prereq project name int last structural build number - */ - out.writeInt(length = structuralBuildTimes.elementSize); - if (length > 0) { - keyTable = structuralBuildTimes.keyTable; - valueTable = structuralBuildTimes.valueTable; - for (int i = 0, l = keyTable.length; i < l; i++) { - if (keyTable[i] != null) { - length--; - out.writeUTF((String) keyTable[i]); - out.writeLong(((Long) valueTable[i]).longValue()); - } - } - if (PHPBuilder.DEBUG && length != 0) - System.out.println("structuralBuildNumbers table is inconsistent"); //$NON-NLS-1$ - } - - /* - * String[] Interned type locators - */ -// out.writeInt(length = references.elementSize); -// ArrayList internedTypeLocators = new ArrayList(length); -// if (length > 0) { -// keyTable = references.keyTable; -// for (int i = 0, l = keyTable.length; i < l; i++) { -// if (keyTable[i] != null) { -// length--; -// String key = (String) keyTable[i]; -// out.writeUTF(key); -// internedTypeLocators.add(key); -// } -// } -// if (PHPBuilder.DEBUG && length != 0) -// System.out.println("references table is inconsistent"); //$NON-NLS-1$ -// } - - /* - * Type locators table String type name int interned locator id - */ -// out.writeInt(length = typeLocators.elementSize); -// if (length > 0) { -// keyTable = typeLocators.keyTable; -// valueTable = typeLocators.valueTable; -// for (int i = 0, l = keyTable.length; i < l; i++) { -// if (keyTable[i] != null) { -// length--; -// out.writeUTF((String) keyTable[i]); -// out.writeInt(internedTypeLocators.indexOf((String) valueTable[i])); -// } -// } -// if (PHPBuilder.DEBUG && length != 0) -// System.out.println("typeLocators table is inconsistent"); //$NON-NLS-1$ -// } - - /* - * char[][][] Interned qualified names char[][] Interned simple names + public String toString() { + return "State for " + javaProjectName //$NON-NLS-1$ + + " (#" + buildNumber //$NON-NLS-1$ + + " @ " + new Date(lastStructuralBuildTime) //$NON-NLS-1$ + + ")"; //$NON-NLS-1$ + } + + /* + * Debug helper void dump() { System.out.println("State for " + + * javaProjectName + " (" + buildNumber + " @ " + new + * Date(lastStructuralBuildTime) + ")"); System.out.println("\tClass path + * source locations:"); for (int i = 0, l = sourceLocations.length; i < l; + * i++) System.out.println("\t\t" + sourceLocations[i]); + * System.out.println("\tClass path binary locations:"); for (int i = 0, l = + * binaryLocations.length; i < l; i++) System.out.println("\t\t" + + * binaryLocations[i]); + * + * System.out.print("\tStructural build numbers table:"); if + * (structuralBuildTimes.elementSize == 0) { System.out.print(" "); } + * else { Object[] keyTable = structuralBuildTimes.keyTable; Object[] + * valueTable = structuralBuildTimes.valueTable; for (int i = 0, l = + * keyTable.length; i < l; i++) if (keyTable[i] != null) + * System.out.print("\n\t\t" + keyTable[i].toString() + " -> " + + * valueTable[i].toString()); } + * + * System.out.print("\tType locators table:"); if (typeLocators.elementSize == + * 0) { System.out.print(" "); } else { Object[] keyTable = + * typeLocators.keyTable; Object[] valueTable = typeLocators.valueTable; for + * (int i = 0, l = keyTable.length; i < l; i++) if (keyTable[i] != null) + * System.out.print("\n\t\t" + keyTable[i].toString() + " -> " + + * valueTable[i].toString()); } + * + * System.out.print("\n\tReferences table:"); if (references.elementSize == + * 0) { System.out.print(" "); } else { Object[] keyTable = + * references.keyTable; Object[] valueTable = references.valueTable; for + * (int i = 0, l = keyTable.length; i < l; i++) { if (keyTable[i] != null) { + * System.out.print("\n\t\t" + keyTable[i].toString()); ReferenceCollection + * c = (ReferenceCollection) valueTable[i]; char[][][] qRefs = + * c.qualifiedNameReferences; System.out.print("\n\t\t\tqualified:"); if + * (qRefs.length == 0) System.out.print(" "); else for (int j = 0, m = + * qRefs.length; j < m; j++) System.out.print(" '" + + * CharOperation.toString(qRefs[j]) + "'"); char[][] sRefs = + * c.simpleNameReferences; System.out.print("\n\t\t\tsimple:"); if + * (sRefs.length == 0) System.out.print(" "); else for (int j = 0, m = + * sRefs.length; j < m; j++) System.out.print(" " + new String(sRefs[j])); + * if (c instanceof AdditionalTypeCollection) { char[][] names = + * ((AdditionalTypeCollection) c).definedTypeNames; + * System.out.print("\n\t\t\tadditional type names:"); for (int j = 0, m = + * names.length; j < m; j++) System.out.print(" " + new String(names[j])); } } } } + * System.out.print("\n\n"); } */ -// ArrayList internedQualifiedNames = new ArrayList(31); -// ArrayList internedSimpleNames = new ArrayList(31); -// valueTable = references.valueTable; -// for (int i = 0, l = valueTable.length; i < l; i++) { -// if (valueTable[i] != null) { -// ReferenceCollection collection = (ReferenceCollection) valueTable[i]; -// char[][][] qNames = collection.qualifiedNameReferences; -// for (int j = 0, m = qNames.length; j < m; j++) { -// char[][] qName = qNames[j]; -// if (!internedQualifiedNames.contains(qName)) { // remember the names have been interned -// internedQualifiedNames.add(qName); -// for (int k = 0, n = qName.length; k < n; k++) { -// char[] sName = qName[k]; -// if (!internedSimpleNames.contains(sName)) // remember the names have been interned -// internedSimpleNames.add(sName); -// } -// } -// } -// char[][] sNames = collection.simpleNameReferences; -// for (int j = 0, m = sNames.length; j < m; j++) { -// char[] sName = sNames[j]; -// if (!internedSimpleNames.contains(sName)) // remember the names have been interned -// internedSimpleNames.add(sName); -// } -// } -// } -// char[][] internedArray = new char[internedSimpleNames.size()][]; -// internedSimpleNames.toArray(internedArray); -// writeNames(internedArray, out); -// // now write the interned qualified names as arrays of interned simple names -// out.writeInt(length = internedQualifiedNames.size()); -// for (int i = 0; i < length; i++) { -// char[][] qName = (char[][]) internedQualifiedNames.get(i); -// int qLength = qName.length; -// out.writeInt(qLength); -// for (int j = 0; j < qLength; j++) -// out.writeInt(internedSimpleNames.indexOf(qName[j])); -// } -// -// /* -// * References table int interned locator id ReferenceCollection -// */ -// out.writeInt(length = references.elementSize); -// if (length > 0) { -// keyTable = references.keyTable; -// for (int i = 0, l = keyTable.length; i < l; i++) { -// if (keyTable[i] != null) { -// length--; -// out.writeInt(internedTypeLocators.indexOf((String) keyTable[i])); -// ReferenceCollection collection = (ReferenceCollection) valueTable[i]; -// if (collection instanceof AdditionalTypeCollection) { -// out.writeByte(1); -// AdditionalTypeCollection atc = (AdditionalTypeCollection) collection; -// writeNames(atc.definedTypeNames, out); -// } else { -// out.writeByte(2); -// } -// char[][][] qNames = collection.qualifiedNameReferences; -// int qLength = qNames.length; -// out.writeInt(qLength); -// for (int j = 0; j < qLength; j++) -// out.writeInt(internedQualifiedNames.indexOf(qNames[j])); -// char[][] sNames = collection.simpleNameReferences; -// int sLength = sNames.length; -// out.writeInt(sLength); -// for (int j = 0; j < sLength; j++) -// out.writeInt(internedSimpleNames.indexOf(sNames[j])); -// } -// } -// if (PHPBuilder.DEBUG && length != 0) -// System.out.println("references table is inconsistent"); //$NON-NLS-1$ -// } - } - - private void writeNames(char[][] names, DataOutputStream out) throws IOException { - int length = names == null ? 0 : names.length; - out.writeInt(length); - for (int i = 0; i < length; i++) { - char[] name = names[i]; - int nLength = name.length; - out.writeInt(nLength); - for (int j = 0; j < nLength; j++) - out.writeChar(name[j]); - } - } - - /** - * Returns a string representation of the receiver. - */ - public String toString() { - return "State for " + javaProjectName //$NON-NLS-1$ - +" (#" + buildNumber //$NON-NLS-1$ - +" @ " + new Date(lastStructuralBuildTime) //$NON-NLS-1$ - +")"; //$NON-NLS-1$ - } - - /* - * Debug helper void dump() { System.out.println("State for " + javaProjectName + " (" + buildNumber + " @ " + new - * Date(lastStructuralBuildTime) + ")"); System.out.println("\tClass path source locations:"); for (int i = 0, l = - * sourceLocations.length; i < l; i++) System.out.println("\t\t" + sourceLocations[i]); System.out.println("\tClass path binary - * locations:"); for (int i = 0, l = binaryLocations.length; i < l; i++) System.out.println("\t\t" + binaryLocations[i]); - * - * System.out.print("\tStructural build numbers table:"); if (structuralBuildTimes.elementSize == 0) { System.out.print(" - * "); } else { Object[] keyTable = structuralBuildTimes.keyTable; Object[] valueTable = structuralBuildTimes.valueTable; for - * (int i = 0, l = keyTable.length; i < l; i++) if (keyTable[i] != null) System.out.print("\n\t\t" + keyTable[i].toString() + " -> " + - * valueTable[i].toString()); } - * - * System.out.print("\tType locators table:"); if (typeLocators.elementSize == 0) { System.out.print(" "); } else { - * Object[] keyTable = typeLocators.keyTable; Object[] valueTable = typeLocators.valueTable; for (int i = 0, l = keyTable.length; - * i < l; i++) if (keyTable[i] != null) System.out.print("\n\t\t" + keyTable[i].toString() + " -> " + valueTable[i].toString()); } - * - * System.out.print("\n\tReferences table:"); if (references.elementSize == 0) { System.out.print(" "); } else { Object[] - * keyTable = references.keyTable; Object[] valueTable = references.valueTable; for (int i = 0, l = keyTable.length; i - * < l; i++) { if (keyTable[i] != null) { System.out.print("\n\t\t" + keyTable[i].toString()); ReferenceCollection c = - * (ReferenceCollection) valueTable[i]; char[][][] qRefs = c.qualifiedNameReferences; System.out.print("\n\t\t\tqualified:"); if - * (qRefs.length == 0) System.out.print(" "); else for (int j = 0, m = qRefs.length; j < m; j++) System.out.print(" '" + - * CharOperation.toString(qRefs[j]) + "'"); char[][] sRefs = c.simpleNameReferences; System.out.print("\n\t\t\tsimple:"); if - * (sRefs.length == 0) System.out.print(" "); else for (int j = 0, m = sRefs.length; j < m; j++) System.out.print(" " + - * new String(sRefs[j])); if (c instanceof AdditionalTypeCollection) { char[][] names = ((AdditionalTypeCollection) - * c).definedTypeNames; System.out.print("\n\t\t\tadditional type names:"); for (int j = 0, m = names.length; j < m; j++) - * System.out.print(" " + new String(names[j])); } } } } System.out.print("\n\n"); } - */ } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/WorkQueue.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/WorkQueue.java index 04abe87..37046d7 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/WorkQueue.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/WorkQueue.java @@ -14,42 +14,43 @@ import java.util.ArrayList; public class WorkQueue { -ArrayList needsCompileList; -ArrayList compiledList; + ArrayList needsCompileList; -public WorkQueue() { - this.needsCompileList = new ArrayList(11); - this.compiledList = new ArrayList(11); -} + ArrayList compiledList; -public void add(SourceFile element) { - needsCompileList.add(element); -} + public WorkQueue() { + this.needsCompileList = new ArrayList(11); + this.compiledList = new ArrayList(11); + } -public void addAll(SourceFile[] elements) { - for (int i = 0, l = elements.length; i < l; i++) - add(elements[i]); -} + public void add(SourceFile element) { + needsCompileList.add(element); + } -public void clear() { - this.needsCompileList.clear(); - this.compiledList.clear(); -} + public void addAll(SourceFile[] elements) { + for (int i = 0, l = elements.length; i < l; i++) + add(elements[i]); + } -public void finished(SourceFile element) { - needsCompileList.remove(element); - compiledList.add(element); -} + public void clear() { + this.needsCompileList.clear(); + this.compiledList.clear(); + } -public boolean isCompiled(SourceFile element) { - return compiledList.contains(element); -} + public void finished(SourceFile element) { + needsCompileList.remove(element); + compiledList.add(element); + } -public boolean isWaiting(SourceFile element) { - return needsCompileList.contains(element); -} + public boolean isCompiled(SourceFile element) { + return compiledList.contains(element); + } -public String toString() { - return "WorkQueue: " + needsCompileList; //$NON-NLS-1$ -} + public boolean isWaiting(SourceFile element) { + return needsCompileList.contains(element); + } + + public String toString() { + return "WorkQueue: " + needsCompileList; //$NON-NLS-1$ + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/AbstractDOMBuilder.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/AbstractDOMBuilder.java index 2c9a0dd..9f84e77 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/AbstractDOMBuilder.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/AbstractDOMBuilder.java @@ -21,50 +21,48 @@ import net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit; import net.sourceforge.phpdt.internal.core.util.ReferenceInfoAdapter; /** - * An abstract DOM builder that contains shared functionality of DOMBuilder and SimpleDOMBuilder. + * An abstract DOM builder that contains shared functionality of DOMBuilder and + * SimpleDOMBuilder. */ -public class AbstractDOMBuilder extends ReferenceInfoAdapter implements ILineStartFinder { +public class AbstractDOMBuilder extends ReferenceInfoAdapter implements + ILineStartFinder { /** - * Set to true when an error is encounterd while - * fuzzy parsing + * Set to true when an error is encounterd while fuzzy parsing */ protected boolean fAbort; - + /** - * True when a compilation unit is being constructed. - * False when any other type of document fragment is - * being constructed. + * True when a compilation unit is being constructed. False when any other + * type of document fragment is being constructed. */ protected boolean fBuildingCU = false; /** - * True when a compilation unit or type is being - * constructed. False when any other type of document - * fragment is being constructed. + * True when a compilation unit or type is being constructed. False when any + * other type of document fragment is being constructed. */ - protected boolean fBuildingType= false; + protected boolean fBuildingType = false; /** * The String on which the JDOM is being created. */ - protected char[] fDocument= null; - + protected char[] fDocument = null; + /** * The source positions of all of the line separators in the document. */ protected int[] fLineStartPositions = new int[] { 0 }; /** - * A stack of enclosing scopes used when constructing - * a compilation unit or type. The top of the stack - * is the document fragment that children are added to. + * A stack of enclosing scopes used when constructing a compilation unit or + * type. The top of the stack is the document fragment that children are + * added to. */ - protected Stack fStack = null; + protected Stack fStack = null; /** - * The number of fields constructed in the current - * document. This is used when building a single - * field document fragment, since the DOMBuilder only + * The number of fields constructed in the current document. This is used + * when building a single field document fragment, since the DOMBuilder only * accepts documents with one field declaration. */ protected int fFieldCount; @@ -73,145 +71,172 @@ public class AbstractDOMBuilder extends ReferenceInfoAdapter implements ILineSta * The current node being constructed. */ protected DOMNode fNode; -/** - * AbstractDOMBuilder constructor. - */ -public AbstractDOMBuilder() { - super(); -} -/** - * Accepts the line separator table and converts it into a line start table. - * - *

                                                      A line separator might corresponds to several characters in the source. - * - * @see IDocumentElementRequestor#acceptLineSeparatorPositions(int[]) - */ -public void acceptLineSeparatorPositions(int[] positions) { - if (positions != null) { - int length = positions.length; - if (length > 0) { - fLineStartPositions = new int[length + 1]; - fLineStartPositions[0] = 0; - int documentLength = fDocument.length; - for (int i = 0; i < length; i++) { - int iPlusOne = i + 1; - int positionPlusOne = positions[i] + 1; - if (positionPlusOne < documentLength) { - if (iPlusOne < length) { - // more separators - fLineStartPositions[iPlusOne] = positionPlusOne; - } else { - // no more separators - if (fDocument[positionPlusOne] == '\n') { - fLineStartPositions[iPlusOne] = positionPlusOne + 1; - } else { + + /** + * AbstractDOMBuilder constructor. + */ + public AbstractDOMBuilder() { + super(); + } + + /** + * Accepts the line separator table and converts it into a line start table. + * + *

                                                      + * A line separator might corresponds to several characters in the source. + * + * @see IDocumentElementRequestor#acceptLineSeparatorPositions(int[]) + */ + public void acceptLineSeparatorPositions(int[] positions) { + if (positions != null) { + int length = positions.length; + if (length > 0) { + fLineStartPositions = new int[length + 1]; + fLineStartPositions[0] = 0; + int documentLength = fDocument.length; + for (int i = 0; i < length; i++) { + int iPlusOne = i + 1; + int positionPlusOne = positions[i] + 1; + if (positionPlusOne < documentLength) { + if (iPlusOne < length) { + // more separators fLineStartPositions[iPlusOne] = positionPlusOne; + } else { + // no more separators + if (fDocument[positionPlusOne] == '\n') { + fLineStartPositions[iPlusOne] = positionPlusOne + 1; + } else { + fLineStartPositions[iPlusOne] = positionPlusOne; + } } + } else { + fLineStartPositions[iPlusOne] = positionPlusOne; } - } else { - fLineStartPositions[iPlusOne] = positionPlusOne; } } } } -} -/** - * Does nothing. - */ -public void acceptProblem(IProblem problem) {} //TODO: (olivier) unused? -/** - * Adds the given node to the current enclosing scope, building the JDOM - * tree. Nodes are only added to an enclosing scope when a compilation unit or type - * is being built (since those are the only nodes that have children). - * - *

                                                      NOTE: nodes are added to the JDOM via the method #basicAddChild such that - * the nodes in the newly created JDOM are not fragmented. - */ -protected void addChild(IDOMNode child) { - if (fStack.size() > 0) { - DOMNode parent = (DOMNode) fStack.peek(); - if (fBuildingCU || fBuildingType) { - parent.basicAddChild(child); + + /** + * Does nothing. + */ + public void acceptProblem(IProblem problem) { + } // TODO: (olivier) unused? + + /** + * Adds the given node to the current enclosing scope, building the JDOM + * tree. Nodes are only added to an enclosing scope when a compilation unit + * or type is being built (since those are the only nodes that have + * children). + * + *

                                                      + * NOTE: nodes are added to the JDOM via the method #basicAddChild such that + * the nodes in the newly created JDOM are not fragmented. + */ + protected void addChild(IDOMNode child) { + if (fStack.size() > 0) { + DOMNode parent = (DOMNode) fStack.peek(); + if (fBuildingCU || fBuildingType) { + parent.basicAddChild(child); + } } } -} -/** - * @see IDOMFactory#createCompilationUnit(String, String) - */ -public IDOMCompilationUnit createCompilationUnit(char[] contents, char[] name) { - return createCompilationUnit(new CompilationUnit(contents, name)); -} -/** - * @see IDOMFactory#createCompilationUnit(String, String) - */ -public IDOMCompilationUnit createCompilationUnit(ICompilationUnit compilationUnit) { - if (fAbort) { - return null; + + /** + * @see IDOMFactory#createCompilationUnit(String, String) + */ + public IDOMCompilationUnit createCompilationUnit(char[] contents, + char[] name) { + return createCompilationUnit(new CompilationUnit(contents, name)); } - fNode.normalize(this); - return (IDOMCompilationUnit)fNode; -} -/** - * @see IDocumentElementRequestor#enterClass(int, int[], int, int, int, char[], int, int, char[], int, int, char[][], int[], int[], int) - */ -public void enterCompilationUnit() { - if (fBuildingCU) { - IDOMCompilationUnit cu= new DOMCompilationUnit(fDocument, new int[] {0, fDocument.length - 1}); - fStack.push(cu); - } -} -/** - * Finishes the configuration of the compilation unit DOM object which - * was created by a previous enterCompilationUnit call. - * - * @see IDocumentElementRequestor#exitCompilationUnit(int) - */ -public void exitCompilationUnit(int declarationEnd) { - DOMCompilationUnit cu = (DOMCompilationUnit) fStack.pop(); - cu.setSourceRangeEnd(declarationEnd); - fNode = cu; -} -/** - * Finishes the configuration of the class and interface DOM objects. - * - * @param bodyEnd - a source position corresponding to the closing bracket of the class - * @param declarationEnd - a source position corresponding to the end of the class - * declaration. This can include whitespace and comments following the closing bracket. - */ -protected void exitType(int bodyEnd, int declarationEnd) { - DOMType type = (DOMType)fStack.pop(); - type.setSourceRangeEnd(declarationEnd); - type.setCloseBodyRangeStart(bodyEnd); - type.setCloseBodyRangeEnd(bodyEnd); - fNode = type; -} -/** - * @see ILineStartFinder#getLineStart(int) - */ -public int getLineStart(int position) { - int lineSeparatorCount = fLineStartPositions.length; - // reverse traversal intentional. - for(int i = lineSeparatorCount - 1; i >= 0; i--) { - if (fLineStartPositions[i] <= position) - return fLineStartPositions[i]; + + /** + * @see IDOMFactory#createCompilationUnit(String, String) + */ + public IDOMCompilationUnit createCompilationUnit( + ICompilationUnit compilationUnit) { + if (fAbort) { + return null; + } + fNode.normalize(this); + return (IDOMCompilationUnit) fNode; + } + + /** + * @see IDocumentElementRequestor#enterClass(int, int[], int, int, int, + * char[], int, int, char[], int, int, char[][], int[], int[], int) + */ + public void enterCompilationUnit() { + if (fBuildingCU) { + IDOMCompilationUnit cu = new DOMCompilationUnit(fDocument, + new int[] { 0, fDocument.length - 1 }); + fStack.push(cu); + } + } + + /** + * Finishes the configuration of the compilation unit DOM object which was + * created by a previous enterCompilationUnit call. + * + * @see IDocumentElementRequestor#exitCompilationUnit(int) + */ + public void exitCompilationUnit(int declarationEnd) { + DOMCompilationUnit cu = (DOMCompilationUnit) fStack.pop(); + cu.setSourceRangeEnd(declarationEnd); + fNode = cu; + } + + /** + * Finishes the configuration of the class and interface DOM objects. + * + * @param bodyEnd - + * a source position corresponding to the closing bracket of the + * class + * @param declarationEnd - + * a source position corresponding to the end of the class + * declaration. This can include whitespace and comments + * following the closing bracket. + */ + protected void exitType(int bodyEnd, int declarationEnd) { + DOMType type = (DOMType) fStack.pop(); + type.setSourceRangeEnd(declarationEnd); + type.setCloseBodyRangeStart(bodyEnd); + type.setCloseBodyRangeEnd(bodyEnd); + fNode = type; + } + + /** + * @see ILineStartFinder#getLineStart(int) + */ + public int getLineStart(int position) { + int lineSeparatorCount = fLineStartPositions.length; + // reverse traversal intentional. + for (int i = lineSeparatorCount - 1; i >= 0; i--) { + if (fLineStartPositions[i] <= position) + return fLineStartPositions[i]; + } + return 0; + } + + /** + * Initializes the builder to create a document fragment. + * + * @param sourceCode - + * the document containing the source code to be analyzed + * @param buildingCompilationUnit - + * true if a the document is being analyzed to create a + * compilation unit, otherwise false + * @param buildingType - + * true if the document is being analyzed to create a type or + * compilation unit + */ + protected void initializeBuild(char[] sourceCode, + boolean buildingCompilationUnit, boolean buildingType) { + fBuildingCU = buildingCompilationUnit; + fBuildingType = buildingType; + fStack = new Stack(); + fDocument = sourceCode; + fFieldCount = 0; + fAbort = false; } - return 0; -} -/** - * Initializes the builder to create a document fragment. - * - * @param sourceCode - the document containing the source code to be analyzed - * @param buildingCompilationUnit - true if a the document is being analyzed to - * create a compilation unit, otherwise false - * @param buildingType - true if the document is being analyzed to create a - * type or compilation unit - */ -protected void initializeBuild(char[] sourceCode, boolean buildingCompilationUnit, boolean buildingType) { - fBuildingCU = buildingCompilationUnit; - fBuildingType = buildingType; - fStack = new Stack(); - fDocument = sourceCode; - fFieldCount = 0; - fAbort = false; -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/CompilationUnit.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/CompilationUnit.java index d372be1..c3a3d86 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/CompilationUnit.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/CompilationUnit.java @@ -22,54 +22,54 @@ import org.eclipse.core.resources.IResource; *

                                                      */ public class CompilationUnit implements ICompilationUnit { - protected char[] fContents; + protected char[] fContents; - protected char[] fFileName; + protected char[] fFileName; - protected char[] fMainTypeName; + protected char[] fMainTypeName; - public CompilationUnit(char[] contents, char[] filename) { - fContents = contents; - fFileName = filename; + public CompilationUnit(char[] contents, char[] filename) { + fContents = contents; + fFileName = filename; - String file = new String(filename); - int start = file.lastIndexOf("/") + 1; //$NON-NLS-1$ - if (start == 0 || start < file.lastIndexOf("\\")) //$NON-NLS-1$ - start = file.lastIndexOf("\\") + 1; //$NON-NLS-1$ + String file = new String(filename); + int start = file.lastIndexOf("/") + 1; //$NON-NLS-1$ + if (start == 0 || start < file.lastIndexOf("\\")) //$NON-NLS-1$ + start = file.lastIndexOf("\\") + 1; //$NON-NLS-1$ - int end = file.lastIndexOf("."); //$NON-NLS-1$ - if (end == -1) - end = file.length(); + int end = file.lastIndexOf("."); //$NON-NLS-1$ + if (end == -1) + end = file.length(); - fMainTypeName = file.substring(start, end).toCharArray(); - } + fMainTypeName = file.substring(start, end).toCharArray(); + } - public char[] getContents() { - return fContents; - } + public char[] getContents() { + return fContents; + } - public char[] getFileName() { - return fFileName; - } + public char[] getFileName() { + return fFileName; + } - public char[] getMainTypeName() { - return fMainTypeName; - } + public char[] getMainTypeName() { + return fMainTypeName; + } - public char[][] getPackageName() { - return null; - } + public char[][] getPackageName() { + return null; + } - public String toString() { - return "CompilationUnit[" + new String(fFileName) + "]"; //$NON-NLS-2$ //$NON-NLS-1$ - } + public String toString() { + return "CompilationUnit[" + new String(fFileName) + "]"; //$NON-NLS-2$ //$NON-NLS-1$ + } - /* - * (non-Javadoc) - * - * @see net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit#getResource() - */ - public IResource getResource() { - return null; - } + /* + * (non-Javadoc) + * + * @see net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit#getResource() + */ + public IResource getResource() { + return null; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMBuilder.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMBuilder.java index 737400a..dd89b13 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMBuilder.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMBuilder.java @@ -27,26 +27,25 @@ import net.sourceforge.phpdt.internal.compiler.problem.DefaultProblemFactory; import net.sourceforge.phpdt.internal.core.util.CharArrayOps; /** - * The DOMBuilder constructs each type of JDOM document fragment, - * for the DOMFactory. The DOMBuilder has been separated from the - * DOMFactory to hide the implmentation of node creation and the - * public Requestor API methods. + * The DOMBuilder constructs each type of JDOM document fragment, for the + * DOMFactory. The DOMBuilder has been separated from the DOMFactory to hide the + * implmentation of node creation and the public Requestor API methods. * */ -public class DOMBuilder extends AbstractDOMBuilder implements IDocumentElementRequestor { - +public class DOMBuilder extends AbstractDOMBuilder implements + IDocumentElementRequestor { + /** - * True when parsing a single member - ignore any problems - * encountered after the member. + * True when parsing a single member - ignore any problems encountered after + * the member. */ - protected boolean fBuildingSingleMember= false; - + protected boolean fBuildingSingleMember = false; + /** - * True when the single member being built has been - * exited. + * True when the single member being built has been exited. */ - protected boolean fFinishedSingleMember = false; + protected boolean fFinishedSingleMember = false; /** * Collection of multiple fields in one declaration @@ -55,656 +54,701 @@ public class DOMBuilder extends AbstractDOMBuilder implements IDocumentElementRe Map options = JavaCore.getOptions(); -/** - * Creates a new DOMBuilder - */ -public DOMBuilder() {} -/** - * @see IDocumentElementRequestor#acceptImport(int declarationStart, int declarationEnd, int[] javaDocPositions, char[] name, int nameStartPosition, boolean onDemand) - */ -public void acceptImport(int declarationStart, int declarationEnd, int[] javaDocPositions, char[] name, - int nameStart, boolean onDemand) { - int[] sourceRange = {declarationStart, declarationEnd}; - int[] nameRange = {nameStart, declarationEnd - 1}; - - /* See 1FVII1P */ - String importName = CharArrayOps.substring(fDocument, nameRange[0], nameRange[1] + 1 - nameRange[0]); - - fNode= new DOMImport(fDocument, sourceRange, importName, nameRange, onDemand); - addChild(fNode); - if (fBuildingSingleMember) { - fFinishedSingleMember= true; - } -} -/** - * @see IDocumentElementRequestor#acceptInitializer(int declarationStart, int declarationEnd, int[] javaDocPositions, int modifiers, int modifiersStart, int bodyStart, int bodyEnd) - */ -public void acceptInitializer(int declarationStart, int declarationEnd, int[] javaDocPositions, int modifiers, - int modifiersStart, int bodyStart, int bodyEnd) { - int[] sourceRange = {declarationStart, declarationEnd}; - int[] commentRange = {-1, -1}; - if (javaDocPositions != null) { - int length = javaDocPositions.length; - commentRange[0] = javaDocPositions[length - 2]; - commentRange[1] = javaDocPositions[length - 1]; + /** + * Creates a new DOMBuilder + */ + public DOMBuilder() { } - int[] modifiersRange = {-1, -1}; - if (modifiersStart > declarationStart) { - modifiersRange[0] = modifiersStart; - modifiersRange[1] = bodyStart - 1; - } - fNode = new DOMInitializer(fDocument, sourceRange, commentRange, modifiers, - modifiersRange, bodyStart); - addChild(fNode); - if (fBuildingSingleMember) { - fFinishedSingleMember= true; - } -} -/** - * @see IDocumentElementRequestor#acceptPackage(int declarationStart, int declarationEnd, int[] javaDocPositions, char[] name, int nameStartPosition) - */ -public void acceptPackage(int declarationStart, int declarationEnd, int[] javaDocPositions, char[] name, - int nameStartPosition) { - int[] sourceRange = {declarationStart, declarationEnd}; - int[] nameRange = {nameStartPosition, declarationEnd - 1}; - fNode= new DOMPackage(fDocument, sourceRange, CharArrayOps.charToString(name), nameRange); - addChild(fNode); - if (fBuildingSingleMember) { - fFinishedSingleMember= true; + /** + * @see IDocumentElementRequestor#acceptImport(int declarationStart, int + * declarationEnd, int[] javaDocPositions, char[] name, int + * nameStartPosition, boolean onDemand) + */ + public void acceptImport(int declarationStart, int declarationEnd, + int[] javaDocPositions, char[] name, int nameStart, boolean onDemand) { + int[] sourceRange = { declarationStart, declarationEnd }; + int[] nameRange = { nameStart, declarationEnd - 1 }; + + /* See 1FVII1P */ + String importName = CharArrayOps.substring(fDocument, nameRange[0], + nameRange[1] + 1 - nameRange[0]); + + fNode = new DOMImport(fDocument, sourceRange, importName, nameRange, + onDemand); + addChild(fNode); + if (fBuildingSingleMember) { + fFinishedSingleMember = true; + } } -} -/** - * Sets the abort flag to true. The parser has encountered an error - * in the current document. If we are only building a single member, and - * we are done with the member - don't worry about the error. - * - * @see IDocumentElementRequestor - */ -public void acceptProblem(IProblem problem){ - if (fBuildingSingleMember && fFinishedSingleMember) { - return; + + /** + * @see IDocumentElementRequestor#acceptInitializer(int declarationStart, + * int declarationEnd, int[] javaDocPositions, int modifiers, int + * modifiersStart, int bodyStart, int bodyEnd) + */ + public void acceptInitializer(int declarationStart, int declarationEnd, + int[] javaDocPositions, int modifiers, int modifiersStart, + int bodyStart, int bodyEnd) { + int[] sourceRange = { declarationStart, declarationEnd }; + int[] commentRange = { -1, -1 }; + if (javaDocPositions != null) { + int length = javaDocPositions.length; + commentRange[0] = javaDocPositions[length - 2]; + commentRange[1] = javaDocPositions[length - 1]; + } + + int[] modifiersRange = { -1, -1 }; + if (modifiersStart > declarationStart) { + modifiersRange[0] = modifiersStart; + modifiersRange[1] = bodyStart - 1; + } + fNode = new DOMInitializer(fDocument, sourceRange, commentRange, + modifiers, modifiersRange, bodyStart); + addChild(fNode); + if (fBuildingSingleMember) { + fFinishedSingleMember = true; + } } - fAbort= true; -} -/** - * Adds the given node to the current enclosing scope, building the JDOM - * tree. Nodes are only added to an enclosing scope when a compilation unit or type - * is being built (since those are the only nodes that have children). - * - *

                                                      NOTE: nodes are added to the JDOM via the method #basicAddChild such that - * the nodes in the newly created JDOM are not fragmented. - */ -protected void addChild(IDOMNode child) { - super.addChild(child); - if (fStack.isEmpty() && fFields != null) { - fFields.add(child); + + /** + * @see IDocumentElementRequestor#acceptPackage(int declarationStart, int + * declarationEnd, int[] javaDocPositions, char[] name, int + * nameStartPosition) + */ + public void acceptPackage(int declarationStart, int declarationEnd, + int[] javaDocPositions, char[] name, int nameStartPosition) { + int[] sourceRange = { declarationStart, declarationEnd }; + int[] nameRange = { nameStartPosition, declarationEnd - 1 }; + fNode = new DOMPackage(fDocument, sourceRange, CharArrayOps + .charToString(name), nameRange); + addChild(fNode); + if (fBuildingSingleMember) { + fFinishedSingleMember = true; + } } -} -/** - * @see IDOMFactory#createCompilationUnit() - */ -public IDOMCompilationUnit createCompilationUnit() { - return new DOMCompilationUnit(); -} -/** - * @see IDOMFactory#createCompilationUnit(String, String) - */ -public IDOMCompilationUnit createCompilationUnit(ICompilationUnit compilationUnit) { - initializeBuild(compilationUnit.getContents(), true, true, false); - getParser(options).parseCompilationUnit(compilationUnit); - return super.createCompilationUnit(compilationUnit); -} -/** - * @see IDOMFactory#createField(String) - */ -//public IDOMField createField(char[] sourceCode) { -// initializeBuild(sourceCode, false, false, true); -// getParser(options).parseField(sourceCode); -// if (fAbort || fNode == null) { -// return null; -// } -// -// // we only accept field declarations with one field -// if (fFieldCount > 1) { -// return null; -// } -// -// fNode.normalize(this); -// return (IDOMField)fNode; -//} -/** - * - */ -//public IDOMField[] createFields(char[] sourceCode) { -// initializeBuild(sourceCode, false, false, false); -// fFields= new ArrayList(); -// getParser(options).parseField(sourceCode); -// if (fAbort) { -// return null; -// } -// IDOMField[] fields= new IDOMField[fFields.size()]; -// fFields.toArray(fields); -// for (int i= 0; i < fields.length; i++) { -// DOMNode node= (DOMNode)fields[i]; -// if (i < (fields.length - 1)) { -// DOMNode next= (DOMNode)fields[i + 1]; -// node.fNextNode= next; -// next.fPreviousNode= node; -// } -// ((DOMNode)fields[i]).normalize(this); -// } -// return fields; -//} -/** - * @see IDOMFactory#createImport() - */ -//public IDOMImport createImport() { -// return new DOMImport(); -//} -/** - * @see IDOMFactory#createImport(String) - */ -//public IDOMImport createImport(char[] sourceCode) { -// initializeBuild(sourceCode, false, false, true); -// getParser(options).parseImport(sourceCode); -// if (fAbort || fNode == null) { -// return null; -// } -// fNode.normalize(this); -// return (IDOMImport)fNode; -//} -/** - * Creates an INITIALIZER document fragment from the given source. - * - * @see IDOMFactory#createInitializer(String) - */ -//public IDOMInitializer createInitializer(char[] sourceCode) { -// initializeBuild(sourceCode, false, false, true); -// getParser(options).parseInitializer(sourceCode); -// if (fAbort || fNode == null || !(fNode instanceof IDOMInitializer)) { -// return null; -// } -// fNode.normalize(this); -// return (IDOMInitializer)fNode; -//} -/** - * @see IDOMFactory#createMethod(String) - */ -//public IDOMMethod createMethod(char[] sourceCode) { -// initializeBuild(sourceCode, false, false, true); -// getParser(options).parseMethod(sourceCode); -// if (fAbort || fNode == null) { -// return null; -// } -// fNode.normalize(this); -// return (IDOMMethod)fNode; -//} -/** - * @see IDOMFactory#createPackage() - */ -public IDOMPackage createPackage() { - return new DOMPackage(); -} -/** - * @see IDOMFactory#createPackage(String) - */ -//public IDOMPackage createPackage(char[] sourceCode) { -// initializeBuild(sourceCode, false, false, true); -// getParser(options).parsePackage(sourceCode); -// if (fAbort || fNode == null) { -// return null; -// } -// fNode.normalize(this); -// return (IDOMPackage)fNode; -//} -/** - * @see IDOMFactory#createType(String) - */ -//public IDOMType createType(char[] sourceCode) { -// initializeBuild(sourceCode, false, true, false); -// getParser(options).parseType(sourceCode); -// if (fAbort) { -// return null; -// } -// if (fNode != null) fNode.normalize(this); -// return (IDOMType)fNode; -//} -/** - * Creates a new DOMMethod and inizializes. - * - * @param declarationStart - a source position corresponding to the first character - * of this constructor declaration - * @param modifiers - the modifiers for this constructor converted to a flag - * @param modifiersStart - a source position corresponding to the first character of the - * textual modifiers - * @param returnType - the name of the return type - * @param returnTypeStart - a source position corresponding to the first character - * of the return type - * @param returnTypeEnd - a source position corresponding to the last character - * of the return type - * @param returnTypeDimensionCount - the array dimension count as supplied on the - * return type (for instance, 'public int[] foo() {}') - * @param name - the name of this constructor - * @param nameStart - a source position corresponding to the first character of the name - * @param nameEnd - a source position corresponding to the last character of the name - * @param parameterTypes - a list of parameter type names - * @param parameterTypeStarts - a list of source positions corresponding to the - * first character of each parameter type name - * @param parameterTypeEnds - a list of source positions corresponding to the - * last character of each parameter type name - * @param parameterNames - a list of the names of the parameters - * @param parametersEnd - a source position corresponding to the last character of the - * parameter list - * @extendedReturnTypeDimensionCount - the array dimension count as supplied on the - * end of the parameter list (for instance, 'public int foo()[] {}') - * @extendedReturnTypeDimensionEnd - a source position corresponding to the last character - * of the extended return type dimension - * @param exceptionTypes - a list of the exception types - * @param exceptionTypeStarts - a list of source positions corresponding to the first - * character of the respective exception types - * @param exceptionTypeEnds - a list of source positions corresponding to the last - * character of the respective exception types - * @param bodyStart - a source position corresponding to the start of this - * constructor's body - */ -protected void enterAbstractMethod(int declarationStart, int[] javaDocPositions, int modifiers, int modifiersStart, - char[] returnType, int returnTypeStart, int returnTypeEnd, int returnTypeDimensionCount, - char[] name, int nameStart, int nameEnd, char[][] parameterTypes, int[] parameterTypeStarts, - int[] parameterTypeEnds, char[][] parameterNames, int[] parameterNameStarts, - int[] parameterNameEnds, int parametersEnd, int extendedReturnTypeDimensionCount, - int extendedReturnTypeDimensionEnd, char[][] exceptionTypes, int[] exceptionTypeStarts, - int[] exceptionTypeEnds, int bodyStart, boolean isConstructor) { - int[] sourceRange = {declarationStart, -1}; // will be fixed up on exit - int[] nameRange = {nameStart, nameEnd}; - int[] commentRange = {-1, -1}; - if (javaDocPositions != null) { - int length = javaDocPositions.length; - commentRange[0] = javaDocPositions[0]; - commentRange[1] = javaDocPositions[length - 1]; + + /** + * Sets the abort flag to true. The parser has encountered an error in the + * current document. If we are only building a single member, and we are + * done with the member - don't worry about the error. + * + * @see IDocumentElementRequestor + */ + public void acceptProblem(IProblem problem) { + if (fBuildingSingleMember && fFinishedSingleMember) { + return; + } + fAbort = true; } - int[] modifiersRange = {-1, -1}; - if (modifiersStart > -1) { - modifiersRange[0] = modifiersStart; - if (isConstructor) { - modifiersRange[1] = nameStart - 1; - } else { - modifiersRange[1] = returnTypeStart - 1; + + /** + * Adds the given node to the current enclosing scope, building the JDOM + * tree. Nodes are only added to an enclosing scope when a compilation unit + * or type is being built (since those are the only nodes that have + * children). + * + *

                                                      + * NOTE: nodes are added to the JDOM via the method #basicAddChild such that + * the nodes in the newly created JDOM are not fragmented. + */ + protected void addChild(IDOMNode child) { + super.addChild(child); + if (fStack.isEmpty() && fFields != null) { + fFields.add(child); } } - int[] returnTypeRange = null; - - if (extendedReturnTypeDimensionCount > 0) - returnTypeRange = new int[] {returnTypeStart, returnTypeEnd, - parametersEnd + 1, extendedReturnTypeDimensionEnd}; - else - returnTypeRange = new int[] {returnTypeStart, returnTypeEnd}; - int[] parameterRange = {nameEnd + 1, parametersEnd}; - int[] exceptionRange = {-1, -1}; - if (exceptionTypes != null && exceptionTypes.length > 0) { - int exceptionCount = exceptionTypes.length; - exceptionRange[0] = exceptionTypeStarts[0]; - exceptionRange[1] = exceptionTypeEnds[exceptionCount - 1]; + + /** + * @see IDOMFactory#createCompilationUnit() + */ + public IDOMCompilationUnit createCompilationUnit() { + return new DOMCompilationUnit(); } - int[] bodyRange = null; - if (exceptionRange[1] > -1) { - bodyRange = new int[] {exceptionRange[1] + 1, -1}; // will be fixed up on exit - } else { - bodyRange = new int[] {parametersEnd + 1, -1}; + + /** + * @see IDOMFactory#createCompilationUnit(String, String) + */ + public IDOMCompilationUnit createCompilationUnit( + ICompilationUnit compilationUnit) { + initializeBuild(compilationUnit.getContents(), true, true, false); + getParser(options).parseCompilationUnit(compilationUnit); + return super.createCompilationUnit(compilationUnit); } - fNode = new DOMMethod(fDocument, sourceRange, CharArrayOps.charToString(name), nameRange, commentRange, modifiers, - modifiersRange, isConstructor, CharArrayOps.charToString(returnType), returnTypeRange, - CharArrayOps.charcharToString(parameterTypes), - CharArrayOps.charcharToString(parameterNames), - parameterRange, CharArrayOps.charcharToString(exceptionTypes), exceptionRange, bodyRange); - addChild(fNode); - fStack.push(fNode); -} -/** - * @see IDocumentElementRequestor#enterClass( - int declarationStart, - int[] javaDocPositions, - int modifiers, - int modifiersStart, - int classStart, - char[] name, - int nameStart, - int nameEnd, - char[] superclass, - int superclassStart, - int superclassEnd, - char[][] superinterfaces, - int[] superinterfaceStarts, - int[] superinterfaceEnds, - int bodyStart) - */ -public void enterClass(int declarationStart, int[] javaDocPositions, int modifiers, int modifiersStart, int keywordStart, - char[] name, int nameStart, int nameEnd, char[] superclass, int superclassStart, - int superclassEnd, char[][] superinterfaces, int[] superinterfaceStarts, - int[] superinterfaceEnds, int bodyStart) { - - enterType(declarationStart, javaDocPositions, modifiers, modifiersStart, keywordStart, - name, nameStart, nameEnd, superclass, superclassStart, - superclassEnd, superinterfaces, superinterfaceStarts, - superinterfaceEnds, bodyStart, true); -} -/** - * @see IDocumentElementRequestor#enterConstructor( - int declarationStart, - int[] javaDocPositions, - int modifiers, - int modifiersStart, - char[] name, - int nameStart, - int nameEnd, - char[][] parameterTypes, - int [] parameterTypeStarts, - int [] parameterTypeEnds, - char[][] parameterNames, - int [] parameterNameStarts, - int [] parameterNameEnds, - int parametersEnd, - char[][] exceptionTypes, - int [] exceptionTypeStarts, - int [] exceptionTypeEnds, - int bodyStart) - */ -public void enterConstructor(int declarationStart, int[] javaDocPositions, int modifiers, int modifiersStart, - char[] name, int nameStart, int nameEnd, char[][] parameterTypes, - int[] parameterTypeStarts, int[] parameterTypeEnds, char[][] parameterNames, - int[] parameterNameStarts, int[] parameterNameEnds, int parametersEnd, - char[][] exceptionTypes, int[] exceptionTypeStarts, int[] exceptionTypeEnds, - int bodyStart) { - - /* see 1FVIIQZ */ - String nameString = new String(fDocument, nameStart, nameEnd - nameStart); - int openParenPosition = nameString.indexOf('('); - if (openParenPosition > -1) - nameEnd = nameStart + openParenPosition - 1; - - enterAbstractMethod(declarationStart, javaDocPositions, modifiers, modifiersStart, - null, -1, -1, 0, - name, nameStart, nameEnd, parameterTypes, parameterTypeStarts, - parameterTypeEnds, parameterNames, parameterNameStarts, - parameterNameEnds, parametersEnd, 0, - -1, exceptionTypes, exceptionTypeStarts, - exceptionTypeEnds, bodyStart,true); -} -/** - * @see IDocumentElementRequestor#enterField( - int declarationStart, - int[] javaDocPositions, - int modifiers, - int modifiersStart, - char[] type, - int typeStart, - int typeEnd, - int typeDimensionCount, - char[] name, - int nameStart, - int nameEnd, - int extendedTypeDimensionCount, - int extendedTypeDimensionEnd) - */ -public void enterField(int declarationStart, int[] javaDocPositions, int modifiers, int modifiersStart, - char[] type, int typeStart, int typeEnd, int typeDimensionCount, char[] name, - int nameStart, int nameEnd, int extendedTypeDimensionCount, - int extendedTypeDimensionEnd) { - int[] sourceRange = {declarationStart, - (extendedTypeDimensionEnd > nameEnd) ? extendedTypeDimensionEnd : nameEnd}; - int[] nameRange = {nameStart, nameEnd}; - int[] commentRange = {-1, -1}; + + /** + * @see IDOMFactory#createField(String) + */ + // public IDOMField createField(char[] sourceCode) { + // initializeBuild(sourceCode, false, false, true); + // getParser(options).parseField(sourceCode); + // if (fAbort || fNode == null) { + // return null; + // } + // + // // we only accept field declarations with one field + // if (fFieldCount > 1) { + // return null; + // } + // + // fNode.normalize(this); + // return (IDOMField)fNode; + // } + /** + * + */ + // public IDOMField[] createFields(char[] sourceCode) { + // initializeBuild(sourceCode, false, false, false); + // fFields= new ArrayList(); + // getParser(options).parseField(sourceCode); + // if (fAbort) { + // return null; + // } + // IDOMField[] fields= new IDOMField[fFields.size()]; + // fFields.toArray(fields); + // for (int i= 0; i < fields.length; i++) { + // DOMNode node= (DOMNode)fields[i]; + // if (i < (fields.length - 1)) { + // DOMNode next= (DOMNode)fields[i + 1]; + // node.fNextNode= next; + // next.fPreviousNode= node; + // } + // ((DOMNode)fields[i]).normalize(this); + // } + // return fields; + // } + /** + * @see IDOMFactory#createImport() + */ + // public IDOMImport createImport() { + // return new DOMImport(); + // } + /** + * @see IDOMFactory#createImport(String) + */ + // public IDOMImport createImport(char[] sourceCode) { + // initializeBuild(sourceCode, false, false, true); + // getParser(options).parseImport(sourceCode); + // if (fAbort || fNode == null) { + // return null; + // } + // fNode.normalize(this); + // return (IDOMImport)fNode; + // } + /** + * Creates an INITIALIZER document fragment from the given source. + * + * @see IDOMFactory#createInitializer(String) + */ + // public IDOMInitializer createInitializer(char[] sourceCode) { + // initializeBuild(sourceCode, false, false, true); + // getParser(options).parseInitializer(sourceCode); + // if (fAbort || fNode == null || !(fNode instanceof IDOMInitializer)) { + // return null; + // } + // fNode.normalize(this); + // return (IDOMInitializer)fNode; + // } + /** + * @see IDOMFactory#createMethod(String) + */ + // public IDOMMethod createMethod(char[] sourceCode) { + // initializeBuild(sourceCode, false, false, true); + // getParser(options).parseMethod(sourceCode); + // if (fAbort || fNode == null) { + // return null; + // } + // fNode.normalize(this); + // return (IDOMMethod)fNode; + // } + /** + * @see IDOMFactory#createPackage() + */ + public IDOMPackage createPackage() { + return new DOMPackage(); + } + + /** + * @see IDOMFactory#createPackage(String) + */ + // public IDOMPackage createPackage(char[] sourceCode) { + // initializeBuild(sourceCode, false, false, true); + // getParser(options).parsePackage(sourceCode); + // if (fAbort || fNode == null) { + // return null; + // } + // fNode.normalize(this); + // return (IDOMPackage)fNode; + // } + /** + * @see IDOMFactory#createType(String) + */ + // public IDOMType createType(char[] sourceCode) { + // initializeBuild(sourceCode, false, true, false); + // getParser(options).parseType(sourceCode); + // if (fAbort) { + // return null; + // } + // if (fNode != null) fNode.normalize(this); + // return (IDOMType)fNode; + // } + /** + * Creates a new DOMMethod and inizializes. + * + * @param declarationStart - + * a source position corresponding to the first character of this + * constructor declaration + * @param modifiers - + * the modifiers for this constructor converted to a flag + * @param modifiersStart - + * a source position corresponding to the first character of the + * textual modifiers + * @param returnType - + * the name of the return type + * @param returnTypeStart - + * a source position corresponding to the first character of the + * return type + * @param returnTypeEnd - + * a source position corresponding to the last character of the + * return type + * @param returnTypeDimensionCount - + * the array dimension count as supplied on the return type (for + * instance, 'public int[] foo() {}') + * @param name - + * the name of this constructor + * @param nameStart - + * a source position corresponding to the first character of the + * name + * @param nameEnd - + * a source position corresponding to the last character of the + * name + * @param parameterTypes - + * a list of parameter type names + * @param parameterTypeStarts - + * a list of source positions corresponding to the first + * character of each parameter type name + * @param parameterTypeEnds - + * a list of source positions corresponding to the last character + * of each parameter type name + * @param parameterNames - + * a list of the names of the parameters + * @param parametersEnd - + * a source position corresponding to the last character of the + * parameter list + * @extendedReturnTypeDimensionCount - the array dimension count as supplied + * on the end of the parameter list (for + * instance, 'public int foo()[] {}') + * @extendedReturnTypeDimensionEnd - a source position corresponding to the + * last character of the extended return + * type dimension + * @param exceptionTypes - + * a list of the exception types + * @param exceptionTypeStarts - + * a list of source positions corresponding to the first + * character of the respective exception types + * @param exceptionTypeEnds - + * a list of source positions corresponding to the last character + * of the respective exception types + * @param bodyStart - + * a source position corresponding to the start of this + * constructor's body + */ + protected void enterAbstractMethod(int declarationStart, + int[] javaDocPositions, int modifiers, int modifiersStart, + char[] returnType, int returnTypeStart, int returnTypeEnd, + int returnTypeDimensionCount, char[] name, int nameStart, + int nameEnd, char[][] parameterTypes, int[] parameterTypeStarts, + int[] parameterTypeEnds, char[][] parameterNames, + int[] parameterNameStarts, int[] parameterNameEnds, + int parametersEnd, int extendedReturnTypeDimensionCount, + int extendedReturnTypeDimensionEnd, char[][] exceptionTypes, + int[] exceptionTypeStarts, int[] exceptionTypeEnds, int bodyStart, + boolean isConstructor) { + int[] sourceRange = { declarationStart, -1 }; // will be fixed up on + // exit + int[] nameRange = { nameStart, nameEnd }; + int[] commentRange = { -1, -1 }; if (javaDocPositions != null) { int length = javaDocPositions.length; commentRange[0] = javaDocPositions[0]; commentRange[1] = javaDocPositions[length - 1]; } - int[] modifiersRange = {-1, -1}; - if (modifiersStart > -1) { - modifiersRange[0] = modifiersStart; - modifiersRange[1] = typeStart - 1; + int[] modifiersRange = { -1, -1 }; + if (modifiersStart > -1) { + modifiersRange[0] = modifiersStart; + if (isConstructor) { + modifiersRange[1] = nameStart - 1; + } else { + modifiersRange[1] = returnTypeStart - 1; + } + } + int[] returnTypeRange = null; + + if (extendedReturnTypeDimensionCount > 0) + returnTypeRange = new int[] { returnTypeStart, returnTypeEnd, + parametersEnd + 1, extendedReturnTypeDimensionEnd }; + else + returnTypeRange = new int[] { returnTypeStart, returnTypeEnd }; + int[] parameterRange = { nameEnd + 1, parametersEnd }; + int[] exceptionRange = { -1, -1 }; + if (exceptionTypes != null && exceptionTypes.length > 0) { + int exceptionCount = exceptionTypes.length; + exceptionRange[0] = exceptionTypeStarts[0]; + exceptionRange[1] = exceptionTypeEnds[exceptionCount - 1]; + } + int[] bodyRange = null; + if (exceptionRange[1] > -1) { + bodyRange = new int[] { exceptionRange[1] + 1, -1 }; // will be + // fixed up + // on exit + } else { + bodyRange = new int[] { parametersEnd + 1, -1 }; + } + fNode = new DOMMethod(fDocument, sourceRange, CharArrayOps + .charToString(name), nameRange, commentRange, modifiers, + modifiersRange, isConstructor, CharArrayOps + .charToString(returnType), returnTypeRange, + CharArrayOps.charcharToString(parameterTypes), CharArrayOps + .charcharToString(parameterNames), parameterRange, + CharArrayOps.charcharToString(exceptionTypes), exceptionRange, + bodyRange); + addChild(fNode); + fStack.push(fNode); } - int[] typeRange = {typeStart, typeEnd}; - boolean hasInitializer = false; // fixed on exitField - int[] initializerRange = {-1, -1}; // fixed on exitField - boolean isVariableDeclarator = false; - if (fNode instanceof DOMField) { - DOMField field = (DOMField)fNode; - if (field.fTypeRange[0] == typeStart) - isVariableDeclarator = true; - } - fNode = new DOMField(fDocument, sourceRange, CharArrayOps.charToString(name), nameRange, commentRange, - modifiers, modifiersRange, typeRange, CharArrayOps.charToString(type), hasInitializer, - initializerRange, isVariableDeclarator); - addChild(fNode); - fStack.push(fNode); -} -/** - * @see IDocumentElementRequestor#enterInterface( - int declarationStart, - int[] javaDocPositions, - int modifiers, - int modifiersStart, - int interfaceStart, - char[] name, - int nameStart, - int nameEnd, - char[][] superinterfaces, - int[] superinterfaceStarts, - int[] superinterfaceEnds, - int bodyStart) - */ -public void enterInterface(int declarationStart, int[] javaDocPositions, int modifiers, int modifiersStart, int keywordStart, - char[] name, int nameStart, int nameEnd, char[][] superinterfaces, - int[] superinterfaceStarts, int[] superinterfaceEnds, int bodyStart) { - enterType(declarationStart, javaDocPositions, modifiers, modifiersStart, keywordStart, - name, nameStart, nameEnd, null, -1, -1, superinterfaces, - superinterfaceStarts, superinterfaceEnds, bodyStart, false); -} -/** - * @see IDocumentElementRequestor#enterMethod( - int declarationStart, - int[] javaDocPositions, - int modifiers, - int modifiersStart, - char[] returnType, - int returnTypeStart, - int returnTypeEnd, - int returnTypeDimensionCount, - char[] name, - int nameStart, - int nameEnd, - char[][] parameterTypes, - int [] parameterTypeStarts, - int [] parameterTypeEnds, - char[][] parameterNames, - int [] parameterNameStarts, - int [] parameterNameEnds, - int parametersEnd, - int extendedReturnTypeDimensionCount, - int extendedReturnTypeDimensionEnd, - char[][] exceptionTypes, - int [] exceptionTypeStarts, - int [] exceptionTypeEnds, - int bodyStart) - */ -public void enterMethod(int declarationStart, int[] javaDocPositions, int modifiers, int modifiersStart, - char[] returnType, int returnTypeStart, int returnTypeEnd, int returnTypeDimensionCount, - char[] name, int nameStart, int nameEnd, char[][] parameterTypes, int[] parameterTypeStarts, - int[] parameterTypeEnds, char[][] parameterNames, int[] parameterNameStarts, - int[] parameterNameEnds, int parametersEnd, int extendedReturnTypeDimensionCount, - int extendedReturnTypeDimensionEnd, char[][] exceptionTypes, int[] exceptionTypeStarts, - int[] exceptionTypeEnds, int bodyStart) { - enterAbstractMethod(declarationStart, javaDocPositions, modifiers, modifiersStart, - returnType, returnTypeStart, returnTypeEnd, returnTypeDimensionCount, - name, nameStart, nameEnd, parameterTypes, parameterTypeStarts, - parameterTypeEnds, parameterNames, parameterNameStarts, - parameterNameEnds, parametersEnd, extendedReturnTypeDimensionCount, - extendedReturnTypeDimensionEnd, exceptionTypes, exceptionTypeStarts, - exceptionTypeEnds, bodyStart,false); -} + /** + * @see IDocumentElementRequestor#enterClass( int declarationStart, int[] + * javaDocPositions, int modifiers, int modifiersStart, int classStart, + * char[] name, int nameStart, int nameEnd, char[] superclass, int + * superclassStart, int superclassEnd, char[][] superinterfaces, int[] + * superinterfaceStarts, int[] superinterfaceEnds, int bodyStart) + */ + public void enterClass(int declarationStart, int[] javaDocPositions, + int modifiers, int modifiersStart, int keywordStart, char[] name, + int nameStart, int nameEnd, char[] superclass, int superclassStart, + int superclassEnd, char[][] superinterfaces, + int[] superinterfaceStarts, int[] superinterfaceEnds, int bodyStart) { -protected void enterType(int declarationStart, int[] javaDocPositions, - int modifiers, int modifiersStart, int keywordStart, char[] name, - int nameStart, int nameEnd, char[] superclass, int superclassStart, - int superclassEnd, char[][] superinterfaces, int[] superinterfaceStarts, - int[] superinterfaceEnds, int bodyStart, boolean isClass) { - if (fBuildingType) { - int[] sourceRange = {declarationStart, -1}; // will be fixed in the exit - int[] commentRange = {-1, -1}; + enterType(declarationStart, javaDocPositions, modifiers, + modifiersStart, keywordStart, name, nameStart, nameEnd, + superclass, superclassStart, superclassEnd, superinterfaces, + superinterfaceStarts, superinterfaceEnds, bodyStart, true); + } + + /** + * @see IDocumentElementRequestor#enterConstructor( int declarationStart, + * int[] javaDocPositions, int modifiers, int modifiersStart, char[] + * name, int nameStart, int nameEnd, char[][] parameterTypes, int [] + * parameterTypeStarts, int [] parameterTypeEnds, char[][] + * parameterNames, int [] parameterNameStarts, int [] + * parameterNameEnds, int parametersEnd, char[][] exceptionTypes, int [] + * exceptionTypeStarts, int [] exceptionTypeEnds, int bodyStart) + */ + public void enterConstructor(int declarationStart, int[] javaDocPositions, + int modifiers, int modifiersStart, char[] name, int nameStart, + int nameEnd, char[][] parameterTypes, int[] parameterTypeStarts, + int[] parameterTypeEnds, char[][] parameterNames, + int[] parameterNameStarts, int[] parameterNameEnds, + int parametersEnd, char[][] exceptionTypes, + int[] exceptionTypeStarts, int[] exceptionTypeEnds, int bodyStart) { + + /* see 1FVIIQZ */ + String nameString = new String(fDocument, nameStart, nameEnd + - nameStart); + int openParenPosition = nameString.indexOf('('); + if (openParenPosition > -1) + nameEnd = nameStart + openParenPosition - 1; + + enterAbstractMethod(declarationStart, javaDocPositions, modifiers, + modifiersStart, null, -1, -1, 0, name, nameStart, nameEnd, + parameterTypes, parameterTypeStarts, parameterTypeEnds, + parameterNames, parameterNameStarts, parameterNameEnds, + parametersEnd, 0, -1, exceptionTypes, exceptionTypeStarts, + exceptionTypeEnds, bodyStart, true); + } + + /** + * @see IDocumentElementRequestor#enterField( int declarationStart, int[] + * javaDocPositions, int modifiers, int modifiersStart, char[] type, + * int typeStart, int typeEnd, int typeDimensionCount, char[] name, int + * nameStart, int nameEnd, int extendedTypeDimensionCount, int + * extendedTypeDimensionEnd) + */ + public void enterField(int declarationStart, int[] javaDocPositions, + int modifiers, int modifiersStart, char[] type, int typeStart, + int typeEnd, int typeDimensionCount, char[] name, int nameStart, + int nameEnd, int extendedTypeDimensionCount, + int extendedTypeDimensionEnd) { + int[] sourceRange = { + declarationStart, + (extendedTypeDimensionEnd > nameEnd) ? extendedTypeDimensionEnd + : nameEnd }; + int[] nameRange = { nameStart, nameEnd }; + int[] commentRange = { -1, -1 }; if (javaDocPositions != null) { int length = javaDocPositions.length; commentRange[0] = javaDocPositions[0]; commentRange[1] = javaDocPositions[length - 1]; } - int[] modifiersRange = {-1, -1}; + int[] modifiersRange = { -1, -1 }; if (modifiersStart > -1) { modifiersRange[0] = modifiersStart; - modifiersRange[1] = (modifiersStart > -1) ? keywordStart - 1 : -1; + modifiersRange[1] = typeStart - 1; } - int[] typeKeywordRange = {keywordStart, nameStart - 1}; - int[] nameRange = new int[] {nameStart, nameEnd}; - int[] extendsKeywordRange = {-1, -1}; - int[] superclassRange = {-1, -1}; - int[] implementsKeywordRange = {-1, -1}; - int[] interfacesRange = {-1, -1}; - if (isClass) { - if (superclass != null) { - extendsKeywordRange[0] = nameEnd + 1; - extendsKeywordRange[1] = superclassStart - 1; - superclassRange[0] = superclassStart; - superclassRange[1] = bodyStart - 1; + int[] typeRange = { typeStart, typeEnd }; + boolean hasInitializer = false; // fixed on exitField + int[] initializerRange = { -1, -1 }; // fixed on exitField + boolean isVariableDeclarator = false; + if (fNode instanceof DOMField) { + DOMField field = (DOMField) fNode; + if (field.fTypeRange[0] == typeStart) + isVariableDeclarator = true; + } + fNode = new DOMField(fDocument, sourceRange, CharArrayOps + .charToString(name), nameRange, commentRange, modifiers, + modifiersRange, typeRange, CharArrayOps.charToString(type), + hasInitializer, initializerRange, isVariableDeclarator); + addChild(fNode); + fStack.push(fNode); + } + + /** + * @see IDocumentElementRequestor#enterInterface( int declarationStart, + * int[] javaDocPositions, int modifiers, int modifiersStart, int + * interfaceStart, char[] name, int nameStart, int nameEnd, char[][] + * superinterfaces, int[] superinterfaceStarts, int[] + * superinterfaceEnds, int bodyStart) + */ + public void enterInterface(int declarationStart, int[] javaDocPositions, + int modifiers, int modifiersStart, int keywordStart, char[] name, + int nameStart, int nameEnd, char[][] superinterfaces, + int[] superinterfaceStarts, int[] superinterfaceEnds, int bodyStart) { + + enterType(declarationStart, javaDocPositions, modifiers, + modifiersStart, keywordStart, name, nameStart, nameEnd, null, + -1, -1, superinterfaces, superinterfaceStarts, + superinterfaceEnds, bodyStart, false); + } + + /** + * @see IDocumentElementRequestor#enterMethod( int declarationStart, int[] + * javaDocPositions, int modifiers, int modifiersStart, char[] + * returnType, int returnTypeStart, int returnTypeEnd, int + * returnTypeDimensionCount, char[] name, int nameStart, int nameEnd, + * char[][] parameterTypes, int [] parameterTypeStarts, int [] + * parameterTypeEnds, char[][] parameterNames, int [] + * parameterNameStarts, int [] parameterNameEnds, int parametersEnd, + * int extendedReturnTypeDimensionCount, int + * extendedReturnTypeDimensionEnd, char[][] exceptionTypes, int [] + * exceptionTypeStarts, int [] exceptionTypeEnds, int bodyStart) + */ + public void enterMethod(int declarationStart, int[] javaDocPositions, + int modifiers, int modifiersStart, char[] returnType, + int returnTypeStart, int returnTypeEnd, + int returnTypeDimensionCount, char[] name, int nameStart, + int nameEnd, char[][] parameterTypes, int[] parameterTypeStarts, + int[] parameterTypeEnds, char[][] parameterNames, + int[] parameterNameStarts, int[] parameterNameEnds, + int parametersEnd, int extendedReturnTypeDimensionCount, + int extendedReturnTypeDimensionEnd, char[][] exceptionTypes, + int[] exceptionTypeStarts, int[] exceptionTypeEnds, int bodyStart) { + enterAbstractMethod(declarationStart, javaDocPositions, modifiers, + modifiersStart, returnType, returnTypeStart, returnTypeEnd, + returnTypeDimensionCount, name, nameStart, nameEnd, + parameterTypes, parameterTypeStarts, parameterTypeEnds, + parameterNames, parameterNameStarts, parameterNameEnds, + parametersEnd, extendedReturnTypeDimensionCount, + extendedReturnTypeDimensionEnd, exceptionTypes, + exceptionTypeStarts, exceptionTypeEnds, bodyStart, false); + } + + protected void enterType(int declarationStart, int[] javaDocPositions, + int modifiers, int modifiersStart, int keywordStart, char[] name, + int nameStart, int nameEnd, char[] superclass, int superclassStart, + int superclassEnd, char[][] superinterfaces, + int[] superinterfaceStarts, int[] superinterfaceEnds, + int bodyStart, boolean isClass) { + if (fBuildingType) { + int[] sourceRange = { declarationStart, -1 }; // will be fixed in + // the exit + int[] commentRange = { -1, -1 }; + if (javaDocPositions != null) { + int length = javaDocPositions.length; + commentRange[0] = javaDocPositions[0]; + commentRange[1] = javaDocPositions[length - 1]; } - if (superinterfaces != null && superinterfaces.length > 0) { - superclassRange[1] = superclassEnd; - if (superclassEnd > -1) { - implementsKeywordRange[0] = superclassEnd + 1; - } else { - implementsKeywordRange[0] = nameEnd + 1; - } - implementsKeywordRange[1] = superinterfaceStarts[0] - 1; - interfacesRange[0] = superinterfaceStarts[0]; - interfacesRange[1] = superinterfaceEnds[superinterfaces.length - 1]; + int[] modifiersRange = { -1, -1 }; + if (modifiersStart > -1) { + modifiersRange[0] = modifiersStart; + modifiersRange[1] = (modifiersStart > -1) ? keywordStart - 1 + : -1; } - } else { - if (superinterfaces != null && superinterfaces.length > 0) { - extendsKeywordRange[0] = nameEnd + 1; - extendsKeywordRange[1] = superinterfaceStarts[0] - 1; - interfacesRange[0] = superinterfaceStarts[0]; - interfacesRange[1] = superinterfaceEnds[superinterfaces.length - 1]; + int[] typeKeywordRange = { keywordStart, nameStart - 1 }; + int[] nameRange = new int[] { nameStart, nameEnd }; + int[] extendsKeywordRange = { -1, -1 }; + int[] superclassRange = { -1, -1 }; + int[] implementsKeywordRange = { -1, -1 }; + int[] interfacesRange = { -1, -1 }; + if (isClass) { + if (superclass != null) { + extendsKeywordRange[0] = nameEnd + 1; + extendsKeywordRange[1] = superclassStart - 1; + superclassRange[0] = superclassStart; + superclassRange[1] = bodyStart - 1; + } + if (superinterfaces != null && superinterfaces.length > 0) { + superclassRange[1] = superclassEnd; + if (superclassEnd > -1) { + implementsKeywordRange[0] = superclassEnd + 1; + } else { + implementsKeywordRange[0] = nameEnd + 1; + } + implementsKeywordRange[1] = superinterfaceStarts[0] - 1; + interfacesRange[0] = superinterfaceStarts[0]; + interfacesRange[1] = superinterfaceEnds[superinterfaces.length - 1]; + } + } else { + if (superinterfaces != null && superinterfaces.length > 0) { + extendsKeywordRange[0] = nameEnd + 1; + extendsKeywordRange[1] = superinterfaceStarts[0] - 1; + interfacesRange[0] = superinterfaceStarts[0]; + interfacesRange[1] = superinterfaceEnds[superinterfaces.length - 1]; + } } + int[] openBodyRange = { bodyStart, -1 }; // fixed by + // setTypeRanges(DOMNode) + int[] closeBodyRange = { -1, -1 }; // will be fixed in exit + fNode = new DOMType(fDocument, sourceRange, new String(name), + nameRange, commentRange, modifiers, modifiersRange, + typeKeywordRange, superclassRange, extendsKeywordRange, + CharArrayOps.charcharToString(superinterfaces), + interfacesRange, implementsKeywordRange, openBodyRange, + closeBodyRange, isClass); + addChild(fNode); + fStack.push(fNode); } - int[] openBodyRange = {bodyStart, -1}; // fixed by setTypeRanges(DOMNode) - int[] closeBodyRange = {-1, -1}; // will be fixed in exit - fNode = new DOMType(fDocument, sourceRange, new String(name), nameRange, commentRange, - modifiers, modifiersRange, typeKeywordRange, superclassRange, extendsKeywordRange, - CharArrayOps.charcharToString(superinterfaces), interfacesRange, - implementsKeywordRange, openBodyRange, - closeBodyRange, isClass); - addChild(fNode); - fStack.push(fNode); } -} -/** - * Finishes the configuration of the constructors and methods. - * - * @param bodyEnd - a source position corresponding to the closing bracket of the method - * @param declarationEnd - a source position corresponding to the end of the method - * declaration. This can include whitespace and comments following the closing bracket. - */ -protected void exitAbstractMethod(int bodyEnd, int declarationEnd) { - DOMMethod method = (DOMMethod) fStack.pop(); - method.setSourceRangeEnd(declarationEnd); - method.setBodyRangeEnd(bodyEnd + 1); - fNode = method; - if (fBuildingSingleMember) { - fFinishedSingleMember= true; + + /** + * Finishes the configuration of the constructors and methods. + * + * @param bodyEnd - + * a source position corresponding to the closing bracket of the + * method + * @param declarationEnd - + * a source position corresponding to the end of the method + * declaration. This can include whitespace and comments + * following the closing bracket. + */ + protected void exitAbstractMethod(int bodyEnd, int declarationEnd) { + DOMMethod method = (DOMMethod) fStack.pop(); + method.setSourceRangeEnd(declarationEnd); + method.setBodyRangeEnd(bodyEnd + 1); + fNode = method; + if (fBuildingSingleMember) { + fFinishedSingleMember = true; + } } -} -/** - * Finishes the configuration of the class DOM object which - * was created by a previous enterClass call. - * - * @see IDocumentElementRequestor#exitClass(int, int) - */ -public void exitClass(int bodyEnd, int declarationEnd) { - exitType(bodyEnd, declarationEnd); -} -/** - * Finishes the configuration of the method DOM object which - * was created by a previous enterConstructor call. - * - * @see IDocumentElementRequestor#exitConstructor(int, int) - */ -public void exitConstructor(int bodyEnd, int declarationEnd) { - exitAbstractMethod(bodyEnd, declarationEnd); -} -/** - * Finishes the configuration of the field DOM object which - * was created by a previous enterField call. - * - * @see IDocumentElementRequestor#exitField(int, int) - */ -public void exitField(int bodyEnd, int declarationEnd) { - DOMField field = (DOMField)fStack.pop(); - if (field.getEndPosition() < declarationEnd) { - field.setSourceRangeEnd(declarationEnd); - int nameEnd = field.fNameRange[1]; - if (nameEnd < bodyEnd) { - /* see 1FVIIV8 - obtain initializer range */ - String initializer = new String(fDocument, nameEnd + 1, bodyEnd - nameEnd); - int index = initializer.indexOf('='); - if (index > -1) { - field.setHasInitializer(true); - field.setInitializerRange(nameEnd + index + 2, bodyEnd); + + /** + * Finishes the configuration of the class DOM object which was created by a + * previous enterClass call. + * + * @see IDocumentElementRequestor#exitClass(int, int) + */ + public void exitClass(int bodyEnd, int declarationEnd) { + exitType(bodyEnd, declarationEnd); + } + + /** + * Finishes the configuration of the method DOM object which was created by + * a previous enterConstructor call. + * + * @see IDocumentElementRequestor#exitConstructor(int, int) + */ + public void exitConstructor(int bodyEnd, int declarationEnd) { + exitAbstractMethod(bodyEnd, declarationEnd); + } + + /** + * Finishes the configuration of the field DOM object which was created by a + * previous enterField call. + * + * @see IDocumentElementRequestor#exitField(int, int) + */ + public void exitField(int bodyEnd, int declarationEnd) { + DOMField field = (DOMField) fStack.pop(); + if (field.getEndPosition() < declarationEnd) { + field.setSourceRangeEnd(declarationEnd); + int nameEnd = field.fNameRange[1]; + if (nameEnd < bodyEnd) { + /* see 1FVIIV8 - obtain initializer range */ + String initializer = new String(fDocument, nameEnd + 1, bodyEnd + - nameEnd); + int index = initializer.indexOf('='); + if (index > -1) { + field.setHasInitializer(true); + field.setInitializerRange(nameEnd + index + 2, bodyEnd); + } } } + fFieldCount++; + fNode = field; + if (fBuildingSingleMember) { + fFinishedSingleMember = true; + } } - fFieldCount++; - fNode = field; - if (fBuildingSingleMember) { - fFinishedSingleMember= true; + + /** + * Finishes the configuration of the interface DOM object which was created + * by a previous enterInterface call. + * + * @see IDocumentElementRequestor#exitInterface(int, int) + */ + public void exitInterface(int bodyEnd, int declarationEnd) { + exitType(bodyEnd, declarationEnd); } -} -/** - * Finishes the configuration of the interface DOM object which - * was created by a previous enterInterface call. - * - * @see IDocumentElementRequestor#exitInterface(int, int) - */ -public void exitInterface(int bodyEnd, int declarationEnd) { - exitType(bodyEnd, declarationEnd); -} -/** - * Finishes the configuration of the method DOM object which - * was created by a previous enterMethod call. - * - * @see IDocumentElementRequestor#exitMethod(int, int) - */ -public void exitMethod(int bodyEnd, int declarationEnd) { - exitAbstractMethod(bodyEnd, declarationEnd); -} -/** - * Creates a new parser. - */ -protected DocumentElementParser getParser(Map settings) { - return new DocumentElementParser(this, new DefaultProblemFactory(), new CompilerOptions(settings)); -} -/** - * Initializes the builder to create a document fragment. - * - * @param sourceCode - the document containing the source code to be analyzed - * @param buildingCompilationUnit - true if a the document is being analyzed to - * create a compilation unit, otherwise false - * @param buildingType - true if the document is being analyzed to create a - * type or compilation unit - * @param singleMember - true if building a single member - */ -protected void initializeBuild(char[] sourceCode, boolean buildingCompilationUnit, boolean buildingType, boolean singleMember) { - super.initializeBuild(sourceCode, buildingCompilationUnit, buildingType); - fBuildingSingleMember= singleMember; - fFinishedSingleMember= false; -} + /** + * Finishes the configuration of the method DOM object which was created by + * a previous enterMethod call. + * + * @see IDocumentElementRequestor#exitMethod(int, int) + */ + public void exitMethod(int bodyEnd, int declarationEnd) { + exitAbstractMethod(bodyEnd, declarationEnd); + } + + /** + * Creates a new parser. + */ + protected DocumentElementParser getParser(Map settings) { + return new DocumentElementParser(this, new DefaultProblemFactory(), + new CompilerOptions(settings)); + } + + /** + * Initializes the builder to create a document fragment. + * + * @param sourceCode - + * the document containing the source code to be analyzed + * @param buildingCompilationUnit - + * true if a the document is being analyzed to create a + * compilation unit, otherwise false + * @param buildingType - + * true if the document is being analyzed to create a type or + * compilation unit + * @param singleMember - + * true if building a single member + */ + protected void initializeBuild(char[] sourceCode, + boolean buildingCompilationUnit, boolean buildingType, + boolean singleMember) { + super + .initializeBuild(sourceCode, buildingCompilationUnit, + buildingType); + fBuildingSingleMember = singleMember; + fFinishedSingleMember = false; + + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMCompilationUnit.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMCompilationUnit.java index 10c07ef..4df8033 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMCompilationUnit.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMCompilationUnit.java @@ -22,163 +22,184 @@ import net.sourceforge.phpdt.internal.core.util.CharArrayOps; /** * DOMCompilation unit provides an implementation of IDOMCompilationUnit. - * + * * @see IDOMCompilationUnit * @see DOMNode */ class DOMCompilationUnit extends DOMNode implements IDOMCompilationUnit { /** - * The comment and/or whitespace preceding the - * first document fragment in this compilation - * unit. + * The comment and/or whitespace preceding the first document fragment in + * this compilation unit. */ protected String fHeader; -/** - * Creates a new empty COMPILATION_UNIT document fragment. - */ -DOMCompilationUnit() { - fHeader=""; //$NON-NLS-1$ -} -/** - * Creates a new COMPILATION_UNIT on the given range of the document. - * - * @param document - the document containing this node's original contents - * @param sourceRange - a two element array of integers describing the - * entire inclusive source range of this node within its document. - * A compilation unit's source range is the entire document - - * the first integer is zero, and the second integer is the position - * of the last character in the document. - */ -DOMCompilationUnit(char[] document, int[] sourceRange) { - super(document, sourceRange, null, new int[]{-1, -1}); - fHeader = ""; //$NON-NLS-1$ -} -/** - * @see DOMNode#appendContents(CharArrayBuffer) - */ -protected void appendFragmentedContents(CharArrayBuffer buffer) { - buffer.append(getHeader()); - appendContentsOfChildren(buffer); -} -/** - * @see IDOMNode#canHaveChildren() - */ -public boolean canHaveChildren() { - return true; -} -/** - * @see IDOMCompilationUnit#getHeader() - */ -public String getHeader() { - return fHeader; -} -/** - * @see IDOMNode#getJavaElement - */ -public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { - if (parent.getElementType() == IJavaElement.PACKAGE_FRAGMENT) { - return ((IPackageFragment)parent).getCompilationUnit(getName()); - } else { - throw new IllegalArgumentException(Util.bind("element.illegalParent")); //$NON-NLS-1$ + + /** + * Creates a new empty COMPILATION_UNIT document fragment. + */ + DOMCompilationUnit() { + fHeader = ""; //$NON-NLS-1$ } -} -/** - * @see IDOMCompilationUnit#getName() - */ -public String getName() { - IDOMType topLevelType= null; - IDOMType firstType= null; - IDOMNode child= fFirstChild; - while (child != null) { - if (child.getNodeType() == IDOMNode.TYPE) { - IDOMType type= (IDOMType)child; - if (firstType == null) { - firstType= type; - } - if (Flags.isPublic(type.getFlags())) { - topLevelType= type; - break; + + /** + * Creates a new COMPILATION_UNIT on the given range of the document. + * + * @param document - + * the document containing this node's original contents + * @param sourceRange - + * a two element array of integers describing the entire + * inclusive source range of this node within its document. A + * compilation unit's source range is the entire document - the + * first integer is zero, and the second integer is the position + * of the last character in the document. + */ + DOMCompilationUnit(char[] document, int[] sourceRange) { + super(document, sourceRange, null, new int[] { -1, -1 }); + fHeader = ""; //$NON-NLS-1$ + } + + /** + * @see DOMNode#appendContents(CharArrayBuffer) + */ + protected void appendFragmentedContents(CharArrayBuffer buffer) { + buffer.append(getHeader()); + appendContentsOfChildren(buffer); + } + + /** + * @see IDOMNode#canHaveChildren() + */ + public boolean canHaveChildren() { + return true; + } + + /** + * @see IDOMCompilationUnit#getHeader() + */ + public String getHeader() { + return fHeader; + } + + /** + * @see IDOMNode#getJavaElement + */ + public IJavaElement getJavaElement(IJavaElement parent) + throws IllegalArgumentException { + if (parent.getElementType() == IJavaElement.PACKAGE_FRAGMENT) { + return ((IPackageFragment) parent).getCompilationUnit(getName()); + } else { + throw new IllegalArgumentException(Util + .bind("element.illegalParent")); //$NON-NLS-1$ + } + } + + /** + * @see IDOMCompilationUnit#getName() + */ + public String getName() { + IDOMType topLevelType = null; + IDOMType firstType = null; + IDOMNode child = fFirstChild; + while (child != null) { + if (child.getNodeType() == IDOMNode.TYPE) { + IDOMType type = (IDOMType) child; + if (firstType == null) { + firstType = type; + } + if (Flags.isPublic(type.getFlags())) { + topLevelType = type; + break; + } } + child = child.getNextNode(); + } + if (topLevelType == null) { + topLevelType = firstType; + } + if (topLevelType != null) { + return topLevelType.getName() + ".java"; //$NON-NLS-1$ + } else { + return null; } - child= child.getNextNode(); } - if (topLevelType == null) { - topLevelType= firstType; + + /** + * @see IDOMNode#getNodeType() + */ + public int getNodeType() { + return IDOMNode.COMPILATION_UNIT; } - if (topLevelType != null) { - return topLevelType.getName() + ".java"; //$NON-NLS-1$ - } else { - return null; + + /** + * Sets the header + */ + protected void initalizeHeader() { + DOMNode child = (DOMNode) getFirstChild(); + if (child != null) { + int childStart = child.getStartPosition(); + if (childStart > 1) { + setHeader(CharArrayOps.substring(fDocument, 0, childStart)); + } + } } -} -/** - * @see IDOMNode#getNodeType() - */ -public int getNodeType() { - return IDOMNode.COMPILATION_UNIT; -} -/** - * Sets the header - */ -protected void initalizeHeader() { - DOMNode child = (DOMNode)getFirstChild(); - if (child != null) { - int childStart = child.getStartPosition(); - if (childStart > 1) { - setHeader(CharArrayOps.substring(fDocument, 0, childStart)); + + /** + * @see IDOMNode#isAllowableChild(IDOMNode) + */ + public boolean isAllowableChild(IDOMNode node) { + if (node != null) { + int type = node.getNodeType(); + return type == IDOMNode.PACKAGE || type == IDOMNode.IMPORT + || type == IDOMNode.TYPE; + } else { + return false; } + + } + + /** + * @see DOMNode + */ + protected DOMNode newDOMNode() { + return new DOMCompilationUnit(); + } + + /** + * Normalizes this DOMNode's source positions to include + * whitespace preceeding the node on the line on which the node starts, and + * all whitespace after the node up to the next node's start + */ + void normalize(ILineStartFinder finder) { + super.normalize(finder); + initalizeHeader(); + } + + /** + * @see IDOMCompilationUnit@setHeader(String) + */ + public void setHeader(String comment) { + fHeader = comment; + fragment(); + } + + /** + * @see IDOMCompilationUnit#setName(String) + */ + public void setName(String name) { + } + + /** + * @see DOMNode#shareContents(DOMNode) + */ + protected void shareContents(DOMNode node) { + super.shareContents(node); + fHeader = ((DOMCompilationUnit) node).fHeader; + } + + /** + * @see IDOMNode#toString() + */ + public String toString() { + return "COMPILATION_UNIT: " + getName(); //$NON-NLS-1$ } -} -/** - * @see IDOMNode#isAllowableChild(IDOMNode) - */ -public boolean isAllowableChild(IDOMNode node) { - if (node != null) { - int type= node.getNodeType(); - return type == IDOMNode.PACKAGE || type == IDOMNode.IMPORT || type == IDOMNode.TYPE; - } else { - return false; - } - -} -/** - * @see DOMNode - */ -protected DOMNode newDOMNode() { - return new DOMCompilationUnit(); -} -/** - * Normalizes this DOMNode's source positions to include whitespace preceeding - * the node on the line on which the node starts, and all whitespace after the node up to - * the next node's start - */ -void normalize(ILineStartFinder finder) { - super.normalize(finder); - initalizeHeader(); -} -/** - * @see IDOMCompilationUnit@setHeader(String) - */ -public void setHeader(String comment) { - fHeader= comment; - fragment(); -} -/** - * @see IDOMCompilationUnit#setName(String) - */ -public void setName(String name) {} -/** - * @see DOMNode#shareContents(DOMNode) - */ -protected void shareContents(DOMNode node) { - super.shareContents(node); - fHeader= ((DOMCompilationUnit)node).fHeader; -} -/** - * @see IDOMNode#toString() - */ -public String toString() { - return "COMPILATION_UNIT: " + getName(); //$NON-NLS-1$ -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMField.java index a1e3280..f40cff6 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMField.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMField.java @@ -24,596 +24,682 @@ import net.sourceforge.phpdt.internal.core.util.CharArrayOps; /** * DOMField provides an implementation of IDOMField. - * + * * @see IDOMField * @see DOMNode */ class DOMField extends DOMMember implements IDOMField { - + /** - * Contains the type of the field when the type - * has been altered from the contents in the - * document, otherwise null. + * Contains the type of the field when the type has been altered from the + * contents in the document, otherwise null. */ protected String fType; /** - * The original inclusive source range of the - * field's type in the document. + * The original inclusive source range of the field's type in the document. */ protected int[] fTypeRange; - + /** - * The contents of the initializer when the - * initializer has been altered from the - * original state in the document, otherwise - * null. + * The contents of the initializer when the initializer has been altered + * from the original state in the document, otherwise null. */ protected String fInitializer; /** - * The original inclusive source range of the - * initializer in the document. + * The original inclusive source range of the initializer in the document. */ protected int[] fInitializerRange; -/** - * Constructs an empty field node. - */ -DOMField() { -} -/** - * Creates a new detailed FIELD document fragment on the given range of the document. - * - * @param document - the document containing this node's original contents - * @param sourceRange - a two element array of integers describing the - * entire inclusive source range of this node within its document. - * Contents start on and include the character at the first position. - * Contents end on and include the character at the last position. - * An array of -1's indicates this node's contents do not exist - * in the document. - * @param name - the identifier portion of the name of this field, - * corresponding to VariableDeclaratorId (JLS 8.3). - * @param nameRange - a two element array of integers describing the - * entire inclusive source range of this node's name within its document, - * including any array qualifiers that might follow the name. - * @param commentRange - a two element array describing the comments that precede - * the member declaration. The first matches the start of this node's - * sourceRange, and the second is the new-line or first non-whitespace - * character following the last comment. If no comments are present, - * this array contains two -1's. - * @param flags - an integer representing the modifiers for this member. The - * integer can be analyzed with net.sourceforge.phpdt.core.Flags - * @param modifierRange - a two element array describing the location of - * modifiers for this member within its source range. The first integer - * is the first character of the first modifier for this member, and - * the second integer is the last whitespace character preceeding the - * next part of this member declaration. If there are no modifiers present - * in this node's source code (that is, package default visibility), this array - * contains two -1's. - * @param typeRange- a two element array describing the location of the - * typeName in the document - the positions of the first and last characters - * of the typeName. - * @param type - the type of the field, in normalized form, as defined in - * Type in Field Declaration (JLS 8.3) - * @param hasInitializer - true if this field declaration includes an initializer, - * otherwise false - * @param initRange - a two element array describing the location of the initializer - * in the declaration. The first integer is the position of the character - * following the equals sign, and the position of the last character is the last - * in the initializer. If this field has no initializer, this array contains - * two -1's. - * @param isVariableDeclarator - true if the field is a seconday variable declarator - * for a previous field declaration. - */ -DOMField(char[] document, int[] sourceRange, String name, int[] nameRange, int[] commentRange, int flags, int[] modifierRange, int[] typeRange, String type, boolean hasInitializer, int[] initRange, boolean isVariableDeclarator) { - super(document, sourceRange, name, nameRange, commentRange, flags, modifierRange); + /** + * Constructs an empty field node. + */ + DOMField() { + } - fType= type; - fTypeRange= typeRange; - setHasInitializer(hasInitializer); - fInitializerRange= initRange; - setIsVariableDeclarator(isVariableDeclarator); - setMask(MASK_DETAILED_SOURCE_INDEXES, true); + /** + * Creates a new detailed FIELD document fragment on the given range of the + * document. + * + * @param document - + * the document containing this node's original contents + * @param sourceRange - + * a two element array of integers describing the entire + * inclusive source range of this node within its document. + * Contents start on and include the character at the first + * position. Contents end on and include the character at the + * last position. An array of -1's indicates this node's contents + * do not exist in the document. + * @param name - + * the identifier portion of the name of this field, + * corresponding to VariableDeclaratorId (JLS 8.3). + * @param nameRange - + * a two element array of integers describing the entire + * inclusive source range of this node's name within its + * document, including any array qualifiers that might follow the + * name. + * @param commentRange - + * a two element array describing the comments that precede the + * member declaration. The first matches the start of this node's + * sourceRange, and the second is the new-line or first + * non-whitespace character following the last comment. If no + * comments are present, this array contains two -1's. + * @param flags - + * an integer representing the modifiers for this member. The + * integer can be analyzed with net.sourceforge.phpdt.core.Flags + * @param modifierRange - + * a two element array describing the location of modifiers for + * this member within its source range. The first integer is the + * first character of the first modifier for this member, and the + * second integer is the last whitespace character preceeding the + * next part of this member declaration. If there are no + * modifiers present in this node's source code (that is, package + * default visibility), this array contains two -1's. + * @param typeRange- + * a two element array describing the location of the typeName in + * the document - the positions of the first and last characters + * of the typeName. + * @param type - + * the type of the field, in normalized form, as defined in Type + * in Field Declaration (JLS 8.3) + * @param hasInitializer - + * true if this field declaration includes an initializer, + * otherwise false + * @param initRange - + * a two element array describing the location of the initializer + * in the declaration. The first integer is the position of the + * character following the equals sign, and the position of the + * last character is the last in the initializer. If this field + * has no initializer, this array contains two -1's. + * @param isVariableDeclarator - + * true if the field is a seconday variable declarator for a + * previous field declaration. + */ + DOMField(char[] document, int[] sourceRange, String name, int[] nameRange, + int[] commentRange, int flags, int[] modifierRange, + int[] typeRange, String type, boolean hasInitializer, + int[] initRange, boolean isVariableDeclarator) { + super(document, sourceRange, name, nameRange, commentRange, flags, + modifierRange); -} -/** - * Creates a new simple FIELD document fragment on the given range of the document. - * - * @param document - the document containing this node's original contents - * @param sourceRange - a two element array of integers describing the - * entire inclusive source range of this node within its document. - * Contents start on and include the character at the first position. - * Contents end on and include the character at the last position. - * An array of -1's indicates this node's contents do not exist - * in the document. - * @param name - the identifier portion of the name of this field, - * corresponding to VariableDeclaratorId (JLS 8.3). - * @param nameRange - a two element array of integers describing the - * entire inclusive source range of this node's name within its document, - * including any array qualifiers that might follow the name. - * @param flags - an integer representing the modifiers for this member. The - * integer can be analyzed with net.sourceforge.phpdt.core.Flags - * @param type - the type of the field, in normalized form, as defined in - * Type in Field Declaration (JLS 8.3) - * @param isVariableDeclarator - true if the field is a seconday variable declarator - * for a previous field declaration. - */ -DOMField(char[] document, int[] sourceRange, String name, int[] nameRange, int flags, String type, boolean isVariableDeclarator) { - this(document, sourceRange, name, nameRange, new int[] {-1, -1}, flags, new int[] {-1, -1}, new int[] {-1, -1}, type, false, new int[] {-1, -1}, isVariableDeclarator); - setMask(MASK_DETAILED_SOURCE_INDEXES, false); -} -/** - * Appends this member's body contents to the given CharArrayBuffer. - * Body contents include the member body and any trailing whitespace. - * - *

                                                      A field does not have a body. - * - * @see DOMMember#appendMemberBodyContents(CharArrayBuffer) - */ -protected void appendMemberBodyContents(CharArrayBuffer buffer) {} -/** - * @see DOMMember#appendMemberDeclarationContents(CharArrayBuffer) - */ -protected void appendMemberDeclarationContents(CharArrayBuffer buffer) { - - if (isVariableDeclarator()) { - buffer.append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0]); - } else { - buffer - .append(getTypeContents()) - .append(fDocument, fTypeRange[1] + 1, fNameRange[0] - fTypeRange[1] - 1); - } - - buffer.append(getNameContents()); - if (hasInitializer()) { - if (fInitializerRange[0] < 0) { - buffer - .append('=') - .append(fInitializer) - .append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]); + fType = type; + fTypeRange = typeRange; + setHasInitializer(hasInitializer); + fInitializerRange = initRange; + setIsVariableDeclarator(isVariableDeclarator); + setMask(MASK_DETAILED_SOURCE_INDEXES, true); + + } + + /** + * Creates a new simple FIELD document fragment on the given range of the + * document. + * + * @param document - + * the document containing this node's original contents + * @param sourceRange - + * a two element array of integers describing the entire + * inclusive source range of this node within its document. + * Contents start on and include the character at the first + * position. Contents end on and include the character at the + * last position. An array of -1's indicates this node's contents + * do not exist in the document. + * @param name - + * the identifier portion of the name of this field, + * corresponding to VariableDeclaratorId (JLS 8.3). + * @param nameRange - + * a two element array of integers describing the entire + * inclusive source range of this node's name within its + * document, including any array qualifiers that might follow the + * name. + * @param flags - + * an integer representing the modifiers for this member. The + * integer can be analyzed with net.sourceforge.phpdt.core.Flags + * @param type - + * the type of the field, in normalized form, as defined in Type + * in Field Declaration (JLS 8.3) + * @param isVariableDeclarator - + * true if the field is a seconday variable declarator for a + * previous field declaration. + */ + DOMField(char[] document, int[] sourceRange, String name, int[] nameRange, + int flags, String type, boolean isVariableDeclarator) { + this(document, sourceRange, name, nameRange, new int[] { -1, -1 }, + flags, new int[] { -1, -1 }, new int[] { -1, -1 }, type, false, + new int[] { -1, -1 }, isVariableDeclarator); + setMask(MASK_DETAILED_SOURCE_INDEXES, false); + } + + /** + * Appends this member's body contents to the given CharArrayBuffer. Body + * contents include the member body and any trailing whitespace. + * + *

                                                      + * A field does not have a body. + * + * @see DOMMember#appendMemberBodyContents(CharArrayBuffer) + */ + protected void appendMemberBodyContents(CharArrayBuffer buffer) { + } + + /** + * @see DOMMember#appendMemberDeclarationContents(CharArrayBuffer) + */ + protected void appendMemberDeclarationContents(CharArrayBuffer buffer) { + + if (isVariableDeclarator()) { + buffer.append(fDocument, fSourceRange[0], fNameRange[0] + - fSourceRange[0]); } else { - buffer - .append(fDocument, fNameRange[1] + 1, fInitializerRange[0] - fNameRange[1] - 1) - .append(getInitializer()) - .append(fDocument, fInitializerRange[1] + 1, fSourceRange[1] - fInitializerRange[1]); + buffer.append(getTypeContents()).append(fDocument, + fTypeRange[1] + 1, fNameRange[0] - fTypeRange[1] - 1); } - } else { - if (fInitializerRange[0] < 0) { - buffer.append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]); + + buffer.append(getNameContents()); + if (hasInitializer()) { + if (fInitializerRange[0] < 0) { + buffer.append('=').append(fInitializer).append(fDocument, + fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]); + } else { + buffer.append(fDocument, fNameRange[1] + 1, + fInitializerRange[0] - fNameRange[1] - 1).append( + getInitializer()).append(fDocument, + fInitializerRange[1] + 1, + fSourceRange[1] - fInitializerRange[1]); + } } else { - buffer.append(fDocument, fInitializerRange[1] + 1, fSourceRange[1] - fInitializerRange[1]); + if (fInitializerRange[0] < 0) { + buffer.append(fDocument, fNameRange[1] + 1, fSourceRange[1] + - fNameRange[1]); + } else { + buffer.append(fDocument, fInitializerRange[1] + 1, + fSourceRange[1] - fInitializerRange[1]); + } } + } -} -/** - * Appends this member's header contents to the given CharArrayBuffer. - * Header contents include any preceding comments and modifiers. - * - *

                                                      If this field is a secondary variable declarator, there is no header. - * - * @see DOMMember#appendMemberHeaderFragment(CharArrayBuffer) - */ -protected void appendMemberHeaderFragment(CharArrayBuffer buffer) { + /** + * Appends this member's header contents to the given CharArrayBuffer. + * Header contents include any preceding comments and modifiers. + * + *

                                                      + * If this field is a secondary variable declarator, there is no header. + * + * @see DOMMember#appendMemberHeaderFragment(CharArrayBuffer) + */ + protected void appendMemberHeaderFragment(CharArrayBuffer buffer) { + + if (isVariableDeclarator()) { + return; + } else { + super.appendMemberHeaderFragment(buffer); + } - if (isVariableDeclarator()) { - return; - } else { - super.appendMemberHeaderFragment(buffer); } -} -/** - * @see DOMMember#appendSimpleContents(CharArrayBuffer) - */ -protected void appendSimpleContents(CharArrayBuffer buffer) { - // append eveything before my name - buffer.append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0]); - // append my name - buffer.append(fName); - // append everything after my name - buffer.append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]); -} -/** - * Generates detailed source indexes for this node if possible. - * - * @exception DOMException if unable to generate detailed source indexes - * for this node - */ -//protected void becomeDetailed() throws DOMException { -// if (!isDetailed()) { -// if (isVariableDeclarator() || hasMultipleVariableDeclarators()) { -// DOMNode first = getFirstFieldDeclaration(); -// DOMNode last = getLastFieldDeclaration(); -// DOMNode node= first; -// String source= first.getContents(); -// while (node != last) { -// node= node.fNextNode; -// source+=node.getContents(); -// } -// DOMBuilder builder = new DOMBuilder(); -// IDOMField[] details= builder.createFields(source.toCharArray()); -// if (details.length == 0) { -// throw new DOMException(ProjectPrefUtil.bind("dom.cannotDetail")); //$NON-NLS-1$ -// } else { -// node= this; -// for (int i= 0; i < details.length; i++) { -// node.shareContents((DOMNode)details[i]); -// node= node.fNextNode; -// } -// } -// } else { -// super.becomeDetailed(); -// } -// -// } -//} -/** - * @see IDOMNode#clone() - */ -public Object clone() { -// if (isVariableDeclarator() || hasMultipleVariableDeclarators()) { -// return getFactory().createField(new String(getSingleVariableDeclaratorContents())); -// } else { + /** + * @see DOMMember#appendSimpleContents(CharArrayBuffer) + */ + protected void appendSimpleContents(CharArrayBuffer buffer) { + // append eveything before my name + buffer.append(fDocument, fSourceRange[0], fNameRange[0] + - fSourceRange[0]); + // append my name + buffer.append(fName); + // append everything after my name + buffer.append(fDocument, fNameRange[1] + 1, fSourceRange[1] + - fNameRange[1]); + } + + /** + * Generates detailed source indexes for this node if possible. + * + * @exception DOMException + * if unable to generate detailed source indexes for this + * node + */ + // protected void becomeDetailed() throws DOMException { + // if (!isDetailed()) { + // if (isVariableDeclarator() || hasMultipleVariableDeclarators()) { + // DOMNode first = getFirstFieldDeclaration(); + // DOMNode last = getLastFieldDeclaration(); + // DOMNode node= first; + // String source= first.getContents(); + // while (node != last) { + // node= node.fNextNode; + // source+=node.getContents(); + // } + // DOMBuilder builder = new DOMBuilder(); + // IDOMField[] details= builder.createFields(source.toCharArray()); + // if (details.length == 0) { + // throw new DOMException(ProjectPrefUtil.bind("dom.cannotDetail")); + // //$NON-NLS-1$ + // } else { + // node= this; + // for (int i= 0; i < details.length; i++) { + // node.shareContents((DOMNode)details[i]); + // node= node.fNextNode; + // } + // } + // } else { + // super.becomeDetailed(); + // } + // + // } + // } + /** + * @see IDOMNode#clone() + */ + public Object clone() { + // if (isVariableDeclarator() || hasMultipleVariableDeclarators()) { + // return getFactory().createField(new + // String(getSingleVariableDeclaratorContents())); + // } else { return super.clone(); -// } -} -/** - * Expands all variable declarators in this field declaration into - * stand-alone field declarations. - */ -protected void expand() { - if (isVariableDeclarator() || hasMultipleVariableDeclarators()) { - Enumeration siblings= new SiblingEnumeration(getFirstFieldDeclaration()); - DOMField field= (DOMField)siblings.nextElement(); - DOMNode next= field.fNextNode; - while (siblings.hasMoreElements() && (next instanceof DOMField) && (((DOMField)next).isVariableDeclarator())) { + // } + } + + /** + * Expands all variable declarators in this field declaration into + * stand-alone field declarations. + */ + protected void expand() { + if (isVariableDeclarator() || hasMultipleVariableDeclarators()) { + Enumeration siblings = new SiblingEnumeration( + getFirstFieldDeclaration()); + DOMField field = (DOMField) siblings.nextElement(); + DOMNode next = field.fNextNode; + while (siblings.hasMoreElements() && (next instanceof DOMField) + && (((DOMField) next).isVariableDeclarator())) { + field.localizeContents(); + if (field.fParent != null) { + field.fParent.fragment(); + } + field = (DOMField) siblings.nextElement(); + next = field.fNextNode; + } field.localizeContents(); - if (field.fParent != null) { - field.fParent.fragment(); + } + } + + /** + * @see DOMNode#getDetailedNode() + */ + // protected DOMNode getDetailedNode() { + // if (isVariableDeclarator() || hasMultipleVariableDeclarators()) { + // return (DOMNode)getFactory().createField(new + // String(getSingleVariableDeclaratorContents())); + // } else { + // return (DOMNode)getFactory().createField(getContents()); + // } + // } + /** + * Returns the first field document fragment that defines the type for this + * variable declarator. + */ + protected DOMField getFirstFieldDeclaration() { + if (isVariableDeclarator()) { + return ((DOMField) fPreviousNode).getFirstFieldDeclaration(); + } else { + return this; + } + } + + /** + * @see IDOMField#getInitializer() + */ + public String getInitializer() { + becomeDetailed(); + if (hasInitializer()) { + if (fInitializer != null) { + return fInitializer; + } else { + return CharArrayOps.substring(fDocument, fInitializerRange[0], + fInitializerRange[1] + 1 - fInitializerRange[0]); } - field= (DOMField)siblings.nextElement(); - next= field.fNextNode; + } else { + return null; } - field.localizeContents(); } -} -/** - * @see DOMNode#getDetailedNode() - */ -//protected DOMNode getDetailedNode() { -// if (isVariableDeclarator() || hasMultipleVariableDeclarators()) { -// return (DOMNode)getFactory().createField(new String(getSingleVariableDeclaratorContents())); -// } else { -// return (DOMNode)getFactory().createField(getContents()); -// } -//} -/** - * Returns the first field document fragment that defines - * the type for this variable declarator. - */ -protected DOMField getFirstFieldDeclaration() { - if (isVariableDeclarator()) { - return ((DOMField)fPreviousNode).getFirstFieldDeclaration(); - } else { - return this; + + /** + * @see IDOMNode#getJavaElement + */ + public IJavaElement getJavaElement(IJavaElement parent) + throws IllegalArgumentException { + if (parent.getElementType() == IJavaElement.TYPE) { + return ((IType) parent).getField(getName()); + } else { + throw new IllegalArgumentException(Util + .bind("element.illegalParent")); //$NON-NLS-1$ + } } -} -/** - * @see IDOMField#getInitializer() - */ -public String getInitializer() { - becomeDetailed(); - if (hasInitializer()) { - if (fInitializer != null) { - return fInitializer; + + /** + * Returns the last field document fragment in this muli-declarator + * statement. + */ + protected DOMField getLastFieldDeclaration() { + DOMField field = this; + while (field.isVariableDeclarator() + || field.hasMultipleVariableDeclarators()) { + if (field.fNextNode instanceof DOMField + && ((DOMField) field.fNextNode).isVariableDeclarator()) { + field = (DOMField) field.fNextNode; + } else { + break; + } + } + return field; + } + + /** + * @see DOMMember#getMemberDeclarationStartPosition() + */ + protected int getMemberDeclarationStartPosition() { + return fTypeRange[0]; + } + + /** + * @see IDOMNode#getNodeType() + */ + public int getNodeType() { + return IDOMNode.FIELD; + } + + /** + * Returns a String representing this field declaration as a field + * declaration with one variable declarator. + */ + protected char[] getSingleVariableDeclaratorContents() { + + CharArrayBuffer buffer = new CharArrayBuffer(); + DOMField first = getFirstFieldDeclaration(); + if (first.isDetailed()) { + first.appendMemberHeaderFragment(buffer); + buffer.append(getType()); + if (isVariableDeclarator()) { + buffer.append(' '); + } else { + buffer.append(fDocument, fTypeRange[1] + 1, fNameRange[0] + - fTypeRange[1] - 1); + } + } else { + buffer.append(first.fDocument, first.fSourceRange[0], + first.fNameRange[0] - first.fSourceRange[0]); + } + + buffer.append(getName()); + if (hasInitializer()) { + if (fInitializerRange[0] < 0) { + buffer.append('=').append(fInitializer).append(';').append( + Util.LINE_SEPARATOR); + } else { + buffer.append(fDocument, fNameRange[1] + 1, + fInitializerRange[0] - fNameRange[1] - 1).append( + getInitializer()).append(';').append( + Util.LINE_SEPARATOR); + } } else { - return CharArrayOps.substring(fDocument, fInitializerRange[0], fInitializerRange[1] + 1 - fInitializerRange[0]); + buffer.append(';').append(Util.LINE_SEPARATOR); } - } else { - return null; + return buffer.getContents(); } -} -/** - * @see IDOMNode#getJavaElement - */ -public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { - if (parent.getElementType() == IJavaElement.TYPE) { - return ((IType)parent).getField(getName()); - } else { - throw new IllegalArgumentException(Util.bind("element.illegalParent")); //$NON-NLS-1$ + + /** + * @see IDOMField#getType() + */ + public String getType() { + return fType; } -} -/** - * Returns the last field document fragment in this muli-declarator statement. - */ -protected DOMField getLastFieldDeclaration() { - DOMField field = this; - while (field.isVariableDeclarator() || field.hasMultipleVariableDeclarators()) { - if (field.fNextNode instanceof DOMField && ((DOMField)field.fNextNode).isVariableDeclarator()) { - field= (DOMField)field.fNextNode; + + /** + * Returns the souce code to be used for this field's type. + */ + protected char[] getTypeContents() { + if (isTypeAltered()) { + return fType.toCharArray(); } else { - break; + return CharArrayOps.subarray(fDocument, fTypeRange[0], + fTypeRange[1] + 1 - fTypeRange[0]); } } - return field; -} -/** - * @see DOMMember#getMemberDeclarationStartPosition() - */ -protected int getMemberDeclarationStartPosition() { - return fTypeRange[0]; -} -/** - * @see IDOMNode#getNodeType() - */ -public int getNodeType() { - return IDOMNode.FIELD; -} -/** - * Returns a String representing this field declaration as a field - * declaration with one variable declarator. - */ -protected char[] getSingleVariableDeclaratorContents() { + /** + * Returns true if this field has an initializer expression, otherwise + * false. + */ + protected boolean hasInitializer() { + return getMask(MASK_FIELD_HAS_INITIALIZER); + } + + /** + * Returns true is this field declarations has more than one variable + * declarator, otherwise false; + */ + protected boolean hasMultipleVariableDeclarators() { + return fNextNode != null && (fNextNode instanceof DOMField) + && ((DOMField) fNextNode).isVariableDeclarator(); + } - CharArrayBuffer buffer= new CharArrayBuffer(); - DOMField first= getFirstFieldDeclaration(); - if (first.isDetailed()) { - first.appendMemberHeaderFragment(buffer); - buffer.append(getType()); + /** + * Inserts the given un-parented node as a sibling of this node, immediately + * before this node. Once inserted, the sibling is only dependent on this + * document fragment. + * + *

                                                      + * When a sibling is inserted before a variable declarator, it must first be + * expanded. + * + * @see IDOMNode#insertSibling(IDOMNode) + */ + public void insertSibling(IDOMNode sibling) + throws IllegalArgumentException, DOMException { if (isVariableDeclarator()) { - buffer.append(' '); + expand(); + } + super.insertSibling(sibling); + } + + /** + * Returns true if this field's type has been altered from the original + * document contents. + */ + protected boolean isTypeAltered() { + return getMask(MASK_FIELD_TYPE_ALTERED); + } + + /** + * Returns true if this field is declared as a secondary variable declarator + * for a previous field declaration. + */ + protected boolean isVariableDeclarator() { + return getMask(MASK_FIELD_IS_VARIABLE_DECLARATOR); + } + + /** + * @see DOMNode + */ + protected DOMNode newDOMNode() { + return new DOMField(); + } + + /** + * Normalizes this DOMNode's end position. + */ + void normalizeEndPosition(ILineStartFinder finder, DOMNode next) { + if (next == null) { + // this node's end position includes all of the characters up + // to the end of the enclosing node + DOMNode parent = (DOMNode) getParent(); + if (parent == null || parent instanceof DOMCompilationUnit) { + setSourceRangeEnd(fDocument.length - 1); + } else { + // parent is a type + int temp = ((DOMType) parent).getCloseBodyPosition() - 1; + setSourceRangeEnd(temp); + fInsertionPosition = Math.max(finder.getLineStart(temp + 1), + getEndPosition()); + } } else { - buffer.append(fDocument, fTypeRange[1] + 1, fNameRange[0] - fTypeRange[1] - 1); + // this node's end position is just before the start of the next + // node + // unless the next node is a field that is declared along with this + // one + int temp = next.getStartPosition() - 1; + fInsertionPosition = Math.max(finder.getLineStart(temp + 1), + getEndPosition()); + + next.normalizeStartPosition(getEndPosition(), finder); + if (next instanceof DOMField) { + DOMField field = (DOMField) next; + if (field.isVariableDeclarator() + && fTypeRange[0] == field.fTypeRange[0]) + return; + } + setSourceRangeEnd(next.getStartPosition() - 1); } - } else { - buffer.append(first.fDocument, first.fSourceRange[0], first.fNameRange[0] - first.fSourceRange[0]); - } - - buffer.append(getName()); - if (hasInitializer()) { - if (fInitializerRange[0] < 0) { - buffer - .append('=') - .append(fInitializer) - .append(';') - .append(Util.LINE_SEPARATOR); + } + + /** + * Normalizes this DOMNode's start position. + */ + void normalizeStartPosition(int endPosition, ILineStartFinder finder) { + if (isVariableDeclarator()) { + // start position is end of last element + setStartPosition(fPreviousNode.getEndPosition() + 1); } else { - buffer - .append(fDocument, fNameRange[1] + 1, fInitializerRange[0] - fNameRange[1] - 1) - .append(getInitializer()) - .append(';') - .append(Util.LINE_SEPARATOR); + super.normalizeStartPosition(endPosition, finder); } - } else { - buffer.append(';').append(Util.LINE_SEPARATOR); } - return buffer.getContents(); -} -/** - * @see IDOMField#getType() - */ -public String getType() { - return fType; -} -/** - * Returns the souce code to be used for this - * field's type. - */ -protected char[] getTypeContents() { - if (isTypeAltered()) { - return fType.toCharArray(); - } else { - return CharArrayOps.subarray(fDocument, fTypeRange[0], fTypeRange[1] + 1 - fTypeRange[0]); + + /** + * Offsets all the source indexes in this node by the given amount. + */ + protected void offset(int offset) { + super.offset(offset); + offsetRange(fInitializerRange, offset); + offsetRange(fTypeRange, offset); } -} -/** - * Returns true if this field has an initializer expression, - * otherwise false. - */ -protected boolean hasInitializer() { - return getMask(MASK_FIELD_HAS_INITIALIZER); -} -/** - * Returns true is this field declarations has more than one - * variable declarator, otherwise false; - */ -protected boolean hasMultipleVariableDeclarators() { - return fNextNode != null && (fNextNode instanceof DOMField) && - ((DOMField)fNextNode).isVariableDeclarator(); -} -/** - * Inserts the given un-parented node as a sibling of this node, immediately before - * this node. Once inserted, the sibling is only dependent on this document fragment. - * - *

                                                      When a sibling is inserted before a variable declarator, it must first - * be expanded. - * - * @see IDOMNode#insertSibling(IDOMNode) - */ -public void insertSibling(IDOMNode sibling) throws IllegalArgumentException, DOMException { - if (isVariableDeclarator()) { + + /** + * Separates this node from its parent and siblings, maintaining any ties + * that this node has to the underlying document fragment. + * + *

                                                      + * When a field with multiple declarators is removed, its declaration must + * first be expanded. + * + * @see IDOMNode#remove() + */ + public void remove() { expand(); - } - super.insertSibling(sibling); -} -/** - * Returns true if this field's type has been altered - * from the original document contents. - */ -protected boolean isTypeAltered() { - return getMask(MASK_FIELD_TYPE_ALTERED); -} -/** - * Returns true if this field is declared as a secondary variable - * declarator for a previous field declaration. - */ -protected boolean isVariableDeclarator() { - return getMask(MASK_FIELD_IS_VARIABLE_DECLARATOR); -} -/** - * @see DOMNode - */ -protected DOMNode newDOMNode() { - return new DOMField(); -} -/** - * Normalizes this DOMNode's end position. - */ -void normalizeEndPosition(ILineStartFinder finder, DOMNode next) { - if (next == null) { - // this node's end position includes all of the characters up - // to the end of the enclosing node - DOMNode parent = (DOMNode) getParent(); - if (parent == null || parent instanceof DOMCompilationUnit) { - setSourceRangeEnd(fDocument.length - 1); + super.remove(); + } + + /** + * @see IDOMMember#setComment(String) + */ + public void setComment(String comment) { + expand(); + super.setComment(comment); + } + + /** + * @see IDOMMember#setFlags(int) + */ + public void setFlags(int flags) { + expand(); + super.setFlags(flags); + } + + /** + * Sets the state of this field declaration as having an initializer + * expression. + */ + protected void setHasInitializer(boolean hasInitializer) { + setMask(MASK_FIELD_HAS_INITIALIZER, hasInitializer); + } + + /** + * @see IDOMField#setInitializer(char[]) + */ + public void setInitializer(String initializer) { + becomeDetailed(); + fragment(); + setHasInitializer(initializer != null); + fInitializer = initializer; + } + + /** + * Sets the initializer range. + */ + void setInitializerRange(int start, int end) { + fInitializerRange[0] = start; + fInitializerRange[1] = end; + } + + /** + * Sets the state of this field declaration as being a secondary variable + * declarator for a previous field declaration. + */ + protected void setIsVariableDeclarator(boolean isVariableDeclarator) { + setMask(MASK_FIELD_IS_VARIABLE_DECLARATOR, isVariableDeclarator); + } + + /** + * @see IDOMField#setName(char[]) + */ + public void setName(String name) throws IllegalArgumentException { + if (name == null) { + throw new IllegalArgumentException(Util.bind("element.nullName")); //$NON-NLS-1$ } else { - // parent is a type - int temp = ((DOMType)parent).getCloseBodyPosition() - 1; - setSourceRangeEnd(temp); - fInsertionPosition = Math.max(finder.getLineStart(temp + 1), getEndPosition()); + super.setName(name); + setTypeAltered(true); } - } else { - // this node's end position is just before the start of the next node - // unless the next node is a field that is declared along with this one - int temp = next.getStartPosition() - 1; - fInsertionPosition = Math.max(finder.getLineStart(temp + 1), getEndPosition()); - - next.normalizeStartPosition(getEndPosition(), finder); - if (next instanceof DOMField) { - DOMField field = (DOMField) next; - if (field.isVariableDeclarator() && fTypeRange[0] == field.fTypeRange[0]) - return; + } + + /** + * @see IDOMField#setType(char[]) + */ + public void setType(String typeName) throws IllegalArgumentException { + if (typeName == null) { + throw new IllegalArgumentException(Util.bind("element.nullType")); //$NON-NLS-1$ } - setSourceRangeEnd(next.getStartPosition() - 1); + becomeDetailed(); + expand(); + fragment(); + setTypeAltered(true); + setNameAltered(true); + fType = typeName; } -} -/** - * Normalizes this DOMNode's start position. - */ -void normalizeStartPosition(int endPosition, ILineStartFinder finder) { - if (isVariableDeclarator()) { - // start position is end of last element - setStartPosition(fPreviousNode.getEndPosition() + 1); - } else { - super.normalizeStartPosition(endPosition, finder); + + /** + * Sets the state of this field declaration as having the field type altered + * from the original document. + */ + protected void setTypeAltered(boolean typeAltered) { + setMask(MASK_FIELD_TYPE_ALTERED, typeAltered); } -} -/** - * Offsets all the source indexes in this node by the given amount. - */ -protected void offset(int offset) { - super.offset(offset); - offsetRange(fInitializerRange, offset); - offsetRange(fTypeRange, offset); -} -/** - * Separates this node from its parent and siblings, maintaining any ties that - * this node has to the underlying document fragment. - * - *

                                                      When a field with multiple declarators is removed, its declaration - * must first be expanded. - * - * @see IDOMNode#remove() - */ -public void remove() { - expand(); - super.remove(); -} -/** - * @see IDOMMember#setComment(String) - */ -public void setComment(String comment) { - expand(); - super.setComment(comment); -} -/** - * @see IDOMMember#setFlags(int) - */ -public void setFlags(int flags) { - expand(); - super.setFlags(flags); -} -/** - * Sets the state of this field declaration as having - * an initializer expression. - */ -protected void setHasInitializer(boolean hasInitializer) { - setMask(MASK_FIELD_HAS_INITIALIZER, hasInitializer); -} -/** - * @see IDOMField#setInitializer(char[]) - */ -public void setInitializer(String initializer) { - becomeDetailed(); - fragment(); - setHasInitializer(initializer != null); - fInitializer= initializer; -} -/** - * Sets the initializer range. - */ -void setInitializerRange(int start, int end) { - fInitializerRange[0] = start; - fInitializerRange[1] = end; -} -/** - * Sets the state of this field declaration as being a - * secondary variable declarator for a previous field - * declaration. - */ -protected void setIsVariableDeclarator(boolean isVariableDeclarator) { - setMask(MASK_FIELD_IS_VARIABLE_DECLARATOR, isVariableDeclarator); -} -/** - * @see IDOMField#setName(char[]) - */ -public void setName(String name) throws IllegalArgumentException { - if (name == null) { - throw new IllegalArgumentException(Util.bind("element.nullName")); //$NON-NLS-1$ - } else { - super.setName(name); - setTypeAltered(true); + + /** + * @see DOMNode#shareContents(DOMNode) + */ + protected void shareContents(DOMNode node) { + super.shareContents(node); + DOMField field = (DOMField) node; + fInitializer = field.fInitializer; + fInitializerRange = rangeCopy(field.fInitializerRange); + fType = field.fType; + fTypeRange = rangeCopy(field.fTypeRange); + } + + /** + * @see IDOMNode#toString() + */ + public String toString() { + return "FIELD: " + getName(); //$NON-NLS-1$ } -} -/** - * @see IDOMField#setType(char[]) - */ -public void setType(String typeName) throws IllegalArgumentException { - if (typeName == null) { - throw new IllegalArgumentException(Util.bind("element.nullType")); //$NON-NLS-1$ - } - becomeDetailed(); - expand(); - fragment(); - setTypeAltered(true); - setNameAltered(true); - fType= typeName; -} -/** - * Sets the state of this field declaration as having - * the field type altered from the original document. - */ -protected void setTypeAltered(boolean typeAltered) { - setMask(MASK_FIELD_TYPE_ALTERED, typeAltered); -} -/** - * @see DOMNode#shareContents(DOMNode) - */ -protected void shareContents(DOMNode node) { - super.shareContents(node); - DOMField field= (DOMField)node; - fInitializer= field.fInitializer; - fInitializerRange= rangeCopy(field.fInitializerRange); - fType= field.fType; - fTypeRange= rangeCopy(field.fTypeRange); -} -/** - * @see IDOMNode#toString() - */ -public String toString() { - return "FIELD: " + getName(); //$NON-NLS-1$ -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMImport.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMImport.java index d835805..11db17f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMImport.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMImport.java @@ -18,7 +18,7 @@ import net.sourceforge.phpdt.internal.core.util.CharArrayBuffer; /** * DOMImport provides an implementation of IDOMImport. - * + * * @see IDOMImport * @see DOMNode */ @@ -27,131 +27,156 @@ class DOMImport extends DOMNode implements IDOMImport { * Indicates if this import is an on demand type import */ protected boolean fOnDemand; -/** - * Creates a new empty IMPORT node. - */ -DOMImport() { - fName = "java.lang.*"; //$NON-NLS-1$ - setMask(MASK_DETAILED_SOURCE_INDEXES, true); -} -/** - * Creates a new detailed IMPORT document fragment on the given range of the document. - * - * @param document - the document containing this node's original contents - * @param sourceRange - a two element array of integers describing the - * entire inclusive source range of this node within its document. - * Contents start on and include the character at the first position. - * Contents end on and include the character at the last position. - * An array of -1's indicates this node's contents do not exist - * in the document. - * @param name - the identifier portion of the name of this node, or - * null if this node does not have a name - * @param nameRange - a two element array of integers describing the - * entire inclusive source range of this node's name within its document, - * including any array qualifiers that might immediately follow the name - * or -1's if this node does not have a name. - * @param onDemand - indicates if this import is an on demand style import - */ -DOMImport(char[] document, int[] sourceRange, String name, int[] nameRange, boolean onDemand) { - super(document, sourceRange, name, nameRange); - fOnDemand = onDemand; - setMask(MASK_DETAILED_SOURCE_INDEXES, true); -} -/** - * Creates a new simple IMPORT document fragment on the given range of the document. - * - * @param document - the document containing this node's original contents - * @param sourceRange - a two element array of integers describing the - * entire inclusive source range of this node within its document. - * Contents start on and include the character at the first position. - * Contents end on and include the character at the last position. - * An array of -1's indicates this node's contents do not exist - * in the document. - * @param name - the identifier portion of the name of this node, or - * null if this node does not have a name - * @param onDemand - indicates if this import is an on demand style import - */ -DOMImport(char[] document, int[] sourceRange, String name, boolean onDemand) { - this(document, sourceRange, name, new int[] {-1, -1}, onDemand); - fOnDemand = onDemand; - setMask(MASK_DETAILED_SOURCE_INDEXES, false); -} -/** - * @see DOMNode#appendFragmentedContents(CharArrayBuffer) - */ -protected void appendFragmentedContents(CharArrayBuffer buffer) { - if (fNameRange[0] < 0) { - buffer - .append("include ") //$NON-NLS-1$ - .append(fName) - .append(';') - .append(Util.LINE_SEPARATOR); - } else { - buffer.append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0]); - //buffer.append(fDocument, fNameRange[0], fNameRange[1] - fNameRange[0] + 1); - buffer.append(fName); - buffer.append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]); + + /** + * Creates a new empty IMPORT node. + */ + DOMImport() { + fName = "java.lang.*"; //$NON-NLS-1$ + setMask(MASK_DETAILED_SOURCE_INDEXES, true); } -} -/** - * @see IDOMNode#getContents() - */ -public String getContents() { - if (fName == null) { - return null; - } else { - return super.getContents(); + + /** + * Creates a new detailed IMPORT document fragment on the given range of the + * document. + * + * @param document - + * the document containing this node's original contents + * @param sourceRange - + * a two element array of integers describing the entire + * inclusive source range of this node within its document. + * Contents start on and include the character at the first + * position. Contents end on and include the character at the + * last position. An array of -1's indicates this node's contents + * do not exist in the document. + * @param name - + * the identifier portion of the name of this node, or + * null if this node does not have a name + * @param nameRange - + * a two element array of integers describing the entire + * inclusive source range of this node's name within its + * document, including any array qualifiers that might + * immediately follow the name or -1's if this node does not have + * a name. + * @param onDemand - + * indicates if this import is an on demand style import + */ + DOMImport(char[] document, int[] sourceRange, String name, int[] nameRange, + boolean onDemand) { + super(document, sourceRange, name, nameRange); + fOnDemand = onDemand; + setMask(MASK_DETAILED_SOURCE_INDEXES, true); } -} -/** - * @see DOMNode#getDetailedNode() - */ -//protected DOMNode getDetailedNode() { -// return (DOMNode)getFactory().createImport(getContents()); -//} -/** - * @see IDOMNode#getJavaElement - */ -public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { -// if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) { -// return ((ICompilationUnit)parent).getImport(getName()); -// } else { + + /** + * Creates a new simple IMPORT document fragment on the given range of the + * document. + * + * @param document - + * the document containing this node's original contents + * @param sourceRange - + * a two element array of integers describing the entire + * inclusive source range of this node within its document. + * Contents start on and include the character at the first + * position. Contents end on and include the character at the + * last position. An array of -1's indicates this node's contents + * do not exist in the document. + * @param name - + * the identifier portion of the name of this node, or + * null if this node does not have a name + * @param onDemand - + * indicates if this import is an on demand style import + */ + DOMImport(char[] document, int[] sourceRange, String name, boolean onDemand) { + this(document, sourceRange, name, new int[] { -1, -1 }, onDemand); + fOnDemand = onDemand; + setMask(MASK_DETAILED_SOURCE_INDEXES, false); + } + + /** + * @see DOMNode#appendFragmentedContents(CharArrayBuffer) + */ + protected void appendFragmentedContents(CharArrayBuffer buffer) { + if (fNameRange[0] < 0) { + buffer.append("include ") //$NON-NLS-1$ + .append(fName).append(';').append(Util.LINE_SEPARATOR); + } else { + buffer.append(fDocument, fSourceRange[0], fNameRange[0] + - fSourceRange[0]); + // buffer.append(fDocument, fNameRange[0], fNameRange[1] - + // fNameRange[0] + 1); + buffer.append(fName); + buffer.append(fDocument, fNameRange[1] + 1, fSourceRange[1] + - fNameRange[1]); + } + } + + /** + * @see IDOMNode#getContents() + */ + public String getContents() { + if (fName == null) { + return null; + } else { + return super.getContents(); + } + } + + /** + * @see DOMNode#getDetailedNode() + */ + // protected DOMNode getDetailedNode() { + // return (DOMNode)getFactory().createImport(getContents()); + // } + /** + * @see IDOMNode#getJavaElement + */ + public IJavaElement getJavaElement(IJavaElement parent) + throws IllegalArgumentException { + // if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) { + // return ((ICompilationUnit)parent).getImport(getName()); + // } else { throw new IllegalArgumentException(Util.bind("element.illegalParent")); //$NON-NLS-1$ -// } -} -/** - * @see IDOMNode#getNodeType() - */ -public int getNodeType() { - return IDOMNode.IMPORT; -} -/** - * @see IDOMImport#isOnDemand() - */ -public boolean isOnDemand() { - return fOnDemand; -} -/** - * @see DOMNode - */ -protected DOMNode newDOMNode() { - return new DOMImport(); -} -/** - * @see IDOMNode#setName(char[]) - */ -public void setName(String name) { - if (name == null) { - throw new IllegalArgumentException(Util.bind("element.nullName")); //$NON-NLS-1$ + // } + } + + /** + * @see IDOMNode#getNodeType() + */ + public int getNodeType() { + return IDOMNode.IMPORT; + } + + /** + * @see IDOMImport#isOnDemand() + */ + public boolean isOnDemand() { + return fOnDemand; + } + + /** + * @see DOMNode + */ + protected DOMNode newDOMNode() { + return new DOMImport(); + } + + /** + * @see IDOMNode#setName(char[]) + */ + public void setName(String name) { + if (name == null) { + throw new IllegalArgumentException(Util.bind("element.nullName")); //$NON-NLS-1$ + } + becomeDetailed(); + super.setName(name); + fOnDemand = name.endsWith(".*"); //$NON-NLS-1$ + } + + /** + * @see IDOMNode#toString() + */ + public String toString() { + return "IMPORT: " + getName(); //$NON-NLS-1$ } - becomeDetailed(); - super.setName(name); - fOnDemand = name.endsWith(".*"); //$NON-NLS-1$ -} -/** - * @see IDOMNode#toString() - */ -public String toString() { - return "IMPORT: " + getName(); //$NON-NLS-1$ -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMInitializer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMInitializer.java index d52d796..6b8ae95 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMInitializer.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMInitializer.java @@ -19,210 +19,243 @@ import net.sourceforge.phpdt.internal.core.util.CharArrayOps; /** * DOMInitializer provides an implementation of IDOMInitializer. - * + * * @see IDOMInitializer * @see DOMNode */ class DOMInitializer extends DOMMember implements IDOMInitializer { /** - * The contents of the initializer's body when the - * body has been altered from the contents in the - * document, otherwise null. + * The contents of the initializer's body when the body has been altered + * from the contents in the document, otherwise null. */ protected String fBody; /** - * The original inclusive source range of the - * body in the document. + * The original inclusive source range of the body in the document. */ - protected int[] fBodyRange; + protected int[] fBodyRange; -/** - * Constructs an empty initializer node. - */ -DOMInitializer() { + /** + * Constructs an empty initializer node. + */ + DOMInitializer() { -} -/** - * Creates a new detailed INITIALIZER document fragment on the given range of the document. - * - * @param document - the document containing this node's original contents - * @param sourceRange - a two element array of integers describing the - * entire inclusive source range of this node within its document. - * Contents start on and include the character at the first position. - * Contents end on and include the character at the last position. - * An array of -1's indicates this node's contents do not exist - * in the document. - * @param commentRange - a two element array describing the comments that precede - * the member declaration. The first matches the start of this node's - * sourceRange, and the second is the new-line or first non-whitespace - * character following the last comment. If no comments are present, - * this array contains two -1's. - * @param flags - an integer representing the modifiers for this member. The - * integer can be analyzed with net.sourceforge.phpdt.core.Flags - * @param modifierRange - a two element array describing the location of - * modifiers for this member within its source range. The first integer - * is the first character of the first modifier for this member, and - * the second integer is the last whitespace character preceeding the - * next part of this member declaration. If there are no modifiers present - * in this node's source code (that is, package default visibility), this array - * contains two -1's. - * @param bodyStartPosition - the position of the open brace of the body - * of this initialzer. - */ -DOMInitializer(char[] document, int[] sourceRange, int[] commentRange, int flags, int[] modifierRange, int bodyStartPosition) { - super(document, sourceRange, null, new int[]{-1, -1}, commentRange, flags, modifierRange); - fBodyRange= new int[2]; - fBodyRange[0]= bodyStartPosition; - fBodyRange[1]= sourceRange[1]; - setHasBody(true); - setMask(MASK_DETAILED_SOURCE_INDEXES, true); -} -/** - * Creates a new simple INITIALIZER document fragment on the given range of the document. - * - * @param document - the document containing this node's original contents - * @param sourceRange - a two element array of integers describing the - * entire inclusive source range of this node within its document. - * Contents start on and include the character at the first position. - * Contents end on and include the character at the last position. - * An array of -1's indicates this node's contents do not exist - * in the document. - * @param flags - an integer representing the modifiers for this member. The - * integer can be analyzed with net.sourceforge.phpdt.core.Flags - */ -DOMInitializer(char[] document, int[] sourceRange, int flags) { - this(document, sourceRange, new int[] {-1, -1}, flags, new int[] {-1, -1}, -1); - setMask(MASK_DETAILED_SOURCE_INDEXES, false); - -} -/** - * @see DOMMember#appendMemberBodyContents(CharArrayBuffer) - */ -protected void appendMemberBodyContents(CharArrayBuffer buffer) { - if (hasBody()) { - buffer - .append(getBody()) - .append(fDocument, fBodyRange[1] + 1, fSourceRange[1] - fBodyRange[1]); - } else { - buffer.append("{}").append(Util.LINE_SEPARATOR); //$NON-NLS-1$ } -} -/** - * @see DOMMember#appendMemberDeclarationContents(CharArrayBuffer) - */ -protected void appendMemberDeclarationContents(CharArrayBuffer buffer) {} -/** - * @see DOMNode#appendSimpleContents(CharArrayBuffer) - */ -protected void appendSimpleContents(CharArrayBuffer buffer) { - // append eveything before my name - buffer.append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0]); - // append my name - buffer.append(fName); - // append everything after my name - buffer.append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]); -} -/** - * @see IDOMInitializer#getBody() - */ -public String getBody() { - becomeDetailed(); - if (hasBody()) { - if (fBody != null) { - return fBody; + + /** + * Creates a new detailed INITIALIZER document fragment on the given range + * of the document. + * + * @param document - + * the document containing this node's original contents + * @param sourceRange - + * a two element array of integers describing the entire + * inclusive source range of this node within its document. + * Contents start on and include the character at the first + * position. Contents end on and include the character at the + * last position. An array of -1's indicates this node's contents + * do not exist in the document. + * @param commentRange - + * a two element array describing the comments that precede the + * member declaration. The first matches the start of this node's + * sourceRange, and the second is the new-line or first + * non-whitespace character following the last comment. If no + * comments are present, this array contains two -1's. + * @param flags - + * an integer representing the modifiers for this member. The + * integer can be analyzed with net.sourceforge.phpdt.core.Flags + * @param modifierRange - + * a two element array describing the location of modifiers for + * this member within its source range. The first integer is the + * first character of the first modifier for this member, and the + * second integer is the last whitespace character preceeding the + * next part of this member declaration. If there are no + * modifiers present in this node's source code (that is, package + * default visibility), this array contains two -1's. + * @param bodyStartPosition - + * the position of the open brace of the body of this initialzer. + */ + DOMInitializer(char[] document, int[] sourceRange, int[] commentRange, + int flags, int[] modifierRange, int bodyStartPosition) { + super(document, sourceRange, null, new int[] { -1, -1 }, commentRange, + flags, modifierRange); + fBodyRange = new int[2]; + fBodyRange[0] = bodyStartPosition; + fBodyRange[1] = sourceRange[1]; + setHasBody(true); + setMask(MASK_DETAILED_SOURCE_INDEXES, true); + } + + /** + * Creates a new simple INITIALIZER document fragment on the given range of + * the document. + * + * @param document - + * the document containing this node's original contents + * @param sourceRange - + * a two element array of integers describing the entire + * inclusive source range of this node within its document. + * Contents start on and include the character at the first + * position. Contents end on and include the character at the + * last position. An array of -1's indicates this node's contents + * do not exist in the document. + * @param flags - + * an integer representing the modifiers for this member. The + * integer can be analyzed with net.sourceforge.phpdt.core.Flags + */ + DOMInitializer(char[] document, int[] sourceRange, int flags) { + this(document, sourceRange, new int[] { -1, -1 }, flags, new int[] { + -1, -1 }, -1); + setMask(MASK_DETAILED_SOURCE_INDEXES, false); + + } + + /** + * @see DOMMember#appendMemberBodyContents(CharArrayBuffer) + */ + protected void appendMemberBodyContents(CharArrayBuffer buffer) { + if (hasBody()) { + buffer.append(getBody()).append(fDocument, fBodyRange[1] + 1, + fSourceRange[1] - fBodyRange[1]); } else { - return CharArrayOps.substring(fDocument, fBodyRange[0], fBodyRange[1] + 1 - fBodyRange[0]); + buffer.append("{}").append(Util.LINE_SEPARATOR); //$NON-NLS-1$ } - } else { - return null; } -} -/** - * @see DOMNode#getDetailedNode() - */ -//protected DOMNode getDetailedNode() { -// return (DOMNode)getFactory().createInitializer(getContents()); -//} -/** - * @see IDOMNode#getJavaElement - */ -public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { -// if (parent.getElementType() == IJavaElement.TYPE) { -// int count = 1; -// IDOMNode previousNode = getPreviousNode(); -// while (previousNode != null) { -// if (previousNode instanceof DOMInitializer) { -// count++; -// } -// previousNode = previousNode.getPreviousNode(); -// } -// return ((IType) parent).getInitializer(count); -// } else { + + /** + * @see DOMMember#appendMemberDeclarationContents(CharArrayBuffer) + */ + protected void appendMemberDeclarationContents(CharArrayBuffer buffer) { + } + + /** + * @see DOMNode#appendSimpleContents(CharArrayBuffer) + */ + protected void appendSimpleContents(CharArrayBuffer buffer) { + // append eveything before my name + buffer.append(fDocument, fSourceRange[0], fNameRange[0] + - fSourceRange[0]); + // append my name + buffer.append(fName); + // append everything after my name + buffer.append(fDocument, fNameRange[1] + 1, fSourceRange[1] + - fNameRange[1]); + } + + /** + * @see IDOMInitializer#getBody() + */ + public String getBody() { + becomeDetailed(); + if (hasBody()) { + if (fBody != null) { + return fBody; + } else { + return CharArrayOps.substring(fDocument, fBodyRange[0], + fBodyRange[1] + 1 - fBodyRange[0]); + } + } else { + return null; + } + } + + /** + * @see DOMNode#getDetailedNode() + */ + // protected DOMNode getDetailedNode() { + // return (DOMNode)getFactory().createInitializer(getContents()); + // } + /** + * @see IDOMNode#getJavaElement + */ + public IJavaElement getJavaElement(IJavaElement parent) + throws IllegalArgumentException { + // if (parent.getElementType() == IJavaElement.TYPE) { + // int count = 1; + // IDOMNode previousNode = getPreviousNode(); + // while (previousNode != null) { + // if (previousNode instanceof DOMInitializer) { + // count++; + // } + // previousNode = previousNode.getPreviousNode(); + // } + // return ((IType) parent).getInitializer(count); + // } else { throw new IllegalArgumentException(Util.bind("element.illegalParent")); //$NON-NLS-1$ -// } -} -/** - * @see DOMMember#getMemberDeclarationStartPosition() - */ -protected int getMemberDeclarationStartPosition() { - return fBodyRange[0]; -} -/** - * @see IDOMNode#getNodeType() - */ -public int getNodeType() { - return IDOMNode.INITIALIZER; -} -/** - * @see IDOMNode#isSigantureEqual(IDOMNode). - * - *

                                                      This method always answers false since an initializer - * does not have a signature. - */ -public boolean isSignatureEqual(IDOMNode node) { - return false; -} -/** - * @see DOMNode - */ -protected DOMNode newDOMNode() { - return new DOMInitializer(); -} -/** - * Offsets all the source indexes in this node by the given amount. - */ -protected void offset(int offset) { - super.offset(offset); - offsetRange(fBodyRange, offset); -} -/** - * @see IDOMInitializer#setBody(char[]) - */ -public void setBody(String body) { - becomeDetailed(); - fBody= body; - setHasBody(body != null); - fragment(); -} -/** - * @see IDOMInitializer#setName(String) - */ -public void setName(String name) {} -/** - * @see DOMNode#shareContents(DOMNode) - */ -protected void shareContents(DOMNode node) { - super.shareContents(node); - DOMInitializer init= (DOMInitializer)node; - fBody= init.fBody; - fBodyRange= rangeCopy(init.fBodyRange); -} -/** - * @see IDOMNode#toString() - */ -public String toString() { - return "INITIALIZER"; //$NON-NLS-1$ -} + // } + } + + /** + * @see DOMMember#getMemberDeclarationStartPosition() + */ + protected int getMemberDeclarationStartPosition() { + return fBodyRange[0]; + } + + /** + * @see IDOMNode#getNodeType() + */ + public int getNodeType() { + return IDOMNode.INITIALIZER; + } + + /** + * @see IDOMNode#isSigantureEqual(IDOMNode). + * + *

                                                      + * This method always answers false since an initializer does not have a + * signature. + */ + public boolean isSignatureEqual(IDOMNode node) { + return false; + } + + /** + * @see DOMNode + */ + protected DOMNode newDOMNode() { + return new DOMInitializer(); + } + + /** + * Offsets all the source indexes in this node by the given amount. + */ + protected void offset(int offset) { + super.offset(offset); + offsetRange(fBodyRange, offset); + } + + /** + * @see IDOMInitializer#setBody(char[]) + */ + public void setBody(String body) { + becomeDetailed(); + fBody = body; + setHasBody(body != null); + fragment(); + } + + /** + * @see IDOMInitializer#setName(String) + */ + public void setName(String name) { + } + + /** + * @see DOMNode#shareContents(DOMNode) + */ + protected void shareContents(DOMNode node) { + super.shareContents(node); + DOMInitializer init = (DOMInitializer) node; + fBody = init.fBody; + fBodyRange = rangeCopy(init.fBodyRange); + } + + /** + * @see IDOMNode#toString() + */ + public String toString() { + return "INITIALIZER"; //$NON-NLS-1$ + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMMember.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMMember.java index fe42621..22ee3bb 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMMember.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMMember.java @@ -18,7 +18,7 @@ import net.sourceforge.phpdt.internal.core.util.CharArrayOps; /** * DOMMember provides an implementation of IDOMMember. - * + * * @see IDOMMember * @see DOMNode */ @@ -26,326 +26,354 @@ import net.sourceforge.phpdt.internal.core.util.CharArrayOps; abstract class DOMMember extends DOMNode implements IDOMMember { /** - * The modifier flags for this member that can be - * analyzed with net.sourceforge.phpdt.core.Flags + * The modifier flags for this member that can be analyzed with + * net.sourceforge.phpdt.core.Flags */ - protected int fFlags= 0; + protected int fFlags = 0; /** - * The member's comments when it has been altered from - * the contents in the document, otherwise null. + * The member's comments when it has been altered from the contents in the + * document, otherwise null. */ - protected String fComment= null; + protected String fComment = null; /** - * The original inclusive source range of the - * member's preceding comments in the document, - * or -1's if the member did not originally have a - * comment. + * The original inclusive source range of the member's preceding comments in + * the document, or -1's if the member did not originally have a comment. */ - protected int[] fCommentRange; - + protected int[] fCommentRange; /** - * The member's modifiers textual representation when - * the modifiers (flags) have been altered from - * their original contents, otherwise null. + * The member's modifiers textual representation when the modifiers (flags) + * have been altered from their original contents, otherwise + * null. */ - protected char[] fModifiers= null; + protected char[] fModifiers = null; /** - * The original inclusive source range of the - * member's modifiers in the document, or -1's if - * the member did not originally have modifiers in - * the source code (that is, package default visibility). + * The original inclusive source range of the member's modifiers in the + * document, or -1's if the member did not originally have modifiers in the + * source code (that is, package default visibility). */ - protected int[] fModifierRange; + protected int[] fModifierRange; -/** - * Constructs an empty member node. - */ -DOMMember() { + /** + * Constructs an empty member node. + */ + DOMMember() { -} -/** - * Creates a new member document fragment on the given range of the document. - * - * @param document - the document containing this node's original contents - * @param sourceRange - a two element array of integers describing the - * entire inclusive source range of this node within its document. - * Contents start on and include the character at the first position. - * Contents end on and include the character at the last position. - * An array of -1's indicates this node's contents do not exist - * in the document. - * @param name - the identifier portion of the name of this node, or - * null if this node does not have a name - * @param nameRange - a two element array of integers describing the - * entire inclusive source range of this node's name within its document, - * including any array qualifiers that might immediately follow the name. - * @param commentRange - a two element array describing the comments that precede - * the member declaration. The first matches the start of this node's - * sourceRange, and the second is the new-line or first non-whitespace - * character following the last comment. If no comments are present, - * this array contains two -1's. - * @param flags - an integer representing the modifiers for this member. The - * integer can be analyzed with net.sourceforge.phpdt.core.Flags - * @param modifierRange - a two element array describing the location of - * modifiers for this member within its source range. The first integer - * is the first character of the first modifier for this member, and - * the second integer is the last whitespace character preceeding the - * next part of this member declaration. If there are no modifiers present - * in this node's source code (that is, package default visibility), this array - * contains two -1's. - */ -DOMMember(char[] document, int[] sourceRange, String name, int[] nameRange, int[] commentRange, int flags, int[] modifierRange) { - super(document, sourceRange, name, nameRange); - fFlags= flags; - fComment= null; - fCommentRange= commentRange; - fModifierRange= modifierRange; - setHasComment(commentRange[0] >= 0); -} -/** - * Appends the contents of this node to the given CharArrayBuffer, using - * the original document and indicies as a form for the current attribute values - * of this node. - * - *

                                                      To facilitate the implementation of generating contents for members, - * the content of members is split into three sections - the header, - * declaration, and body sections. The header section includes any preceding - * comments and modifiers. The declaration section includes the portion of - * the member declaration that follows any modifiers and precedes the - * member body. The body section includes the member body and any trailing - * whitespace. - * - * @see DOMNode#appendFragmentedContents(CharArrayBuffer) - */ -protected void appendFragmentedContents(CharArrayBuffer buffer) { - if (isDetailed()) { - appendMemberHeaderFragment(buffer); - appendMemberDeclarationContents(buffer); - appendMemberBodyContents(buffer); - } else { - appendSimpleContents(buffer); } -} -/** - * Appends this member's body contents to the given CharArrayBuffer. - * Body contents include the member body and any trailing whitespace. - */ -protected abstract void appendMemberBodyContents(CharArrayBuffer buffer); -/** - * Appends this member's declaration contents to the given CharArrayBuffer. - * The declaration contents includes the portion of this member that - * appears after any modifiers and precedes the body. - */ -protected abstract void appendMemberDeclarationContents(CharArrayBuffer buffer); -/** - * Appends this member's header contents to the given CharArrayBuffer. - * Header contents include any preceding comments and modifiers. - */ -protected void appendMemberHeaderFragment(CharArrayBuffer buffer) { - int spaceStart, spaceEnd; + /** + * Creates a new member document fragment on the given range of the + * document. + * + * @param document - + * the document containing this node's original contents + * @param sourceRange - + * a two element array of integers describing the entire + * inclusive source range of this node within its document. + * Contents start on and include the character at the first + * position. Contents end on and include the character at the + * last position. An array of -1's indicates this node's contents + * do not exist in the document. + * @param name - + * the identifier portion of the name of this node, or + * null if this node does not have a name + * @param nameRange - + * a two element array of integers describing the entire + * inclusive source range of this node's name within its + * document, including any array qualifiers that might + * immediately follow the name. + * @param commentRange - + * a two element array describing the comments that precede the + * member declaration. The first matches the start of this node's + * sourceRange, and the second is the new-line or first + * non-whitespace character following the last comment. If no + * comments are present, this array contains two -1's. + * @param flags - + * an integer representing the modifiers for this member. The + * integer can be analyzed with net.sourceforge.phpdt.core.Flags + * @param modifierRange - + * a two element array describing the location of modifiers for + * this member within its source range. The first integer is the + * first character of the first modifier for this member, and the + * second integer is the last whitespace character preceeding the + * next part of this member declaration. If there are no + * modifiers present in this node's source code (that is, package + * default visibility), this array contains two -1's. + */ + DOMMember(char[] document, int[] sourceRange, String name, int[] nameRange, + int[] commentRange, int flags, int[] modifierRange) { + super(document, sourceRange, name, nameRange); + fFlags = flags; + fComment = null; + fCommentRange = commentRange; + fModifierRange = modifierRange; + setHasComment(commentRange[0] >= 0); + } - // space before comment - if (hasComment()) { - spaceStart= fSourceRange[0]; - spaceEnd= fCommentRange[0]; - if (spaceEnd > 0) { - buffer.append(fDocument, spaceStart, spaceEnd - spaceStart); + /** + * Appends the contents of this node to the given CharArrayBuffer, using the + * original document and indicies as a form for the current attribute values + * of this node. + * + *

                                                      + * To facilitate the implementation of generating contents for members, the + * content of members is split into three sections - the header, + * declaration, and body sections. The header section includes any preceding + * comments and modifiers. The declaration section includes the portion of + * the member declaration that follows any modifiers and precedes the member + * body. The body section includes the member body and any trailing + * whitespace. + * + * @see DOMNode#appendFragmentedContents(CharArrayBuffer) + */ + protected void appendFragmentedContents(CharArrayBuffer buffer) { + if (isDetailed()) { + appendMemberHeaderFragment(buffer); + appendMemberDeclarationContents(buffer); + appendMemberBodyContents(buffer); + } else { + appendSimpleContents(buffer); } } - - String fragment= getComment(); - if (fragment != null) { - buffer.append(fragment); + + /** + * Appends this member's body contents to the given CharArrayBuffer. Body + * contents include the member body and any trailing whitespace. + */ + protected abstract void appendMemberBodyContents(CharArrayBuffer buffer); + + /** + * Appends this member's declaration contents to the given CharArrayBuffer. + * The declaration contents includes the portion of this member that appears + * after any modifiers and precedes the body. + */ + protected abstract void appendMemberDeclarationContents( + CharArrayBuffer buffer); + + /** + * Appends this member's header contents to the given CharArrayBuffer. + * Header contents include any preceding comments and modifiers. + */ + protected void appendMemberHeaderFragment(CharArrayBuffer buffer) { + + int spaceStart, spaceEnd; + + // space before comment + if (hasComment()) { + spaceStart = fSourceRange[0]; + spaceEnd = fCommentRange[0]; + if (spaceEnd > 0) { + buffer.append(fDocument, spaceStart, spaceEnd - spaceStart); + } + } + + String fragment = getComment(); + if (fragment != null) { + buffer.append(fragment); + } + + if (fCommentRange[1] >= 0) { + spaceStart = fCommentRange[1] + 1; + } else { + spaceStart = fSourceRange[0]; + } + if (fModifierRange[0] >= 0) { + spaceEnd = fModifierRange[0] - 1; + } else { + spaceEnd = getMemberDeclarationStartPosition() - 1; + } + + if (spaceEnd >= spaceStart) { + buffer.append(fDocument, spaceStart, spaceEnd + 1 - spaceStart); + } + buffer.append(getModifiersText()); + } - if (fCommentRange[1] >= 0) { - spaceStart= fCommentRange[1] + 1; - } else { - spaceStart= fSourceRange[0]; + /** + * Appends the contents of this node to the given CharArrayBuffer, using the + * original document and indicies as a form for the current attribute values + * of this node. This method is called when this node is know not to have + * detailed source indexes. + */ + protected abstract void appendSimpleContents(CharArrayBuffer buffer); + + /** + * Returns a copy of the given array with the new element appended to the + * end of the array. + */ + protected String[] appendString(String[] list, String element) { + String[] copy = new String[list.length + 1]; + System.arraycopy(list, 0, copy, 0, list.length); + copy[list.length] = element; + return copy; } - if (fModifierRange[0] >= 0) { - spaceEnd= fModifierRange[0] - 1; - } else { - spaceEnd= getMemberDeclarationStartPosition() - 1; + + /** + * Returns a String describing the modifiers for this member, + * ending with whitespace (if not empty). This value serves as a replacement + * value for the member's modifier range when the modifiers have been + * altered from their original contents. + */ + protected char[] generateFlags() { + char[] flags = Flags.toString(getFlags()).toCharArray(); + if (flags.length == 0) { + return flags; + } else { + return CharArrayOps.concat(flags, new char[] { ' ' }); + } } - if (spaceEnd >= spaceStart) { - buffer.append(fDocument, spaceStart, spaceEnd + 1 - spaceStart); + /** + * @see IDOMMember#getComment() + */ + public String getComment() { + becomeDetailed(); + if (hasComment()) { + if (fComment != null) { + return fComment; + } else { + return CharArrayOps.substring(fDocument, fCommentRange[0], + fCommentRange[1] + 1 - fCommentRange[0]); + } + } else { + return null; + } } - buffer.append(getModifiersText()); -} -/** - * Appends the contents of this node to the given CharArrayBuffer, using - * the original document and indicies as a form for the current attribute values - * of this node. This method is called when this node is know not to have - * detailed source indexes. - */ -protected abstract void appendSimpleContents(CharArrayBuffer buffer); -/** - * Returns a copy of the given array with the new element appended - * to the end of the array. - */ -protected String[] appendString(String[] list, String element) { - String[] copy= new String[list.length + 1]; - System.arraycopy(list, 0, copy, 0, list.length); - copy[list.length]= element; - return copy; -} -/** - * Returns a String describing the modifiers for this member, - * ending with whitespace (if not empty). This value serves as a replacement - * value for the member's modifier range when the modifiers have been altered - * from their original contents. - */ -protected char[] generateFlags() { - char[] flags= Flags.toString(getFlags()).toCharArray(); - if (flags.length == 0) { - return flags; - } else { - return CharArrayOps.concat(flags, new char[] {' '}); + /** + * @see IDOMMember#getFlags() + */ + public int getFlags() { + return fFlags; } -} -/** - * @see IDOMMember#getComment() - */ -public String getComment() { - becomeDetailed(); - if (hasComment()) { - if (fComment != null) { - return fComment; + + /** + * Returns the location of the first character in the member's declaration + * section. + * + * @see DOMMember#getMemberDeclarationContents() + * @see DOMMember#getFragmentedContents() + */ + protected abstract int getMemberDeclarationStartPosition(); + + /** + * Returns the String to be used for this member's flags when generating + * contents - either the original contents in the document or the + * replacement value. + */ + protected char[] getModifiersText() { + if (fModifiers == null) { + if (fModifierRange[0] < 0) { + return null; + } else { + return CharArrayOps.subarray(fDocument, fModifierRange[0], + fModifierRange[1] + 1 - fModifierRange[0]); + } } else { - return CharArrayOps.substring(fDocument, fCommentRange[0], fCommentRange[1] + 1 - fCommentRange[0]); + return fModifiers; } - } else { - return null; } -} -/** - * @see IDOMMember#getFlags() - */ -public int getFlags() { - return fFlags; -} -/** - * Returns the location of the first character in the member's declaration - * section. - * - * @see DOMMember#getMemberDeclarationContents() - * @see DOMMember#getFragmentedContents() - */ -protected abstract int getMemberDeclarationStartPosition(); -/** - * Returns the String to be used for this member's flags when - * generating contents - either the original contents in the document - * or the replacement value. - */ -protected char[] getModifiersText() { - if (fModifiers == null) { - if (fModifierRange[0] < 0) { - return null; - } else { - return CharArrayOps.subarray(fDocument, fModifierRange[0], fModifierRange[1] + 1 - fModifierRange[0]); + + /** + * Returns true if this member currently has a body. + */ + protected boolean hasBody() { + return getMask(MASK_HAS_BODY); + } + + /** + * Returns true if this member currently has a comment. + */ + protected boolean hasComment() { + return getMask(MASK_HAS_COMMENT); + } + + /** + * Offsets all the source indexes in this node by the given amount. + */ + protected void offset(int offset) { + super.offset(offset); + offsetRange(fCommentRange, offset); + offsetRange(fModifierRange, offset); + } + + /** + * @see IDOMMember#setComment(String) + */ + public void setComment(String comment) { + becomeDetailed(); + fComment = comment; + fragment(); + setHasComment(comment != null); + /* see 1FVIJAH */ + if (comment != null) { + String commentString = new String(comment); + if (commentString.indexOf("@deprecated") >= 0) { //$NON-NLS-1$ + fFlags = fFlags | IConstants.AccDeprecated; + return; + } + } - } else { - return fModifiers; + fFlags = fFlags & (~IConstants.AccDeprecated); + } -} -/** - * Returns true if this member currently has a body. - */ -protected boolean hasBody() { - return getMask(MASK_HAS_BODY); -} -/** - * Returns true if this member currently has a comment. - */ -protected boolean hasComment() { - return getMask(MASK_HAS_COMMENT); -} -/** - * Offsets all the source indexes in this node by the given amount. - */ -protected void offset(int offset) { - super.offset(offset); - offsetRange(fCommentRange, offset); - offsetRange(fModifierRange, offset); -} -/** - * @see IDOMMember#setComment(String) - */ -public void setComment(String comment) { - becomeDetailed(); - fComment= comment; - fragment(); - setHasComment(comment != null); - /* see 1FVIJAH */ - if (comment != null) { - String commentString = new String(comment); - if (commentString.indexOf("@deprecated") >= 0) { //$NON-NLS-1$ - fFlags= fFlags | IConstants.AccDeprecated; - return; + + /** + * @see IDOMMember#setFlags(int) + */ + public void setFlags(int flags) { + becomeDetailed(); + if (Flags.isDeprecated(fFlags)) { + fFlags = flags | IConstants.AccDeprecated; + } else { + fFlags = flags & (~IConstants.AccDeprecated); } + fragment(); + fModifiers = generateFlags(); + } + /** + * Sets the state of this member declaration as having a body. + */ + protected void setHasBody(boolean hasBody) { + setMask(MASK_HAS_BODY, hasBody); } - fFlags= fFlags & (~IConstants.AccDeprecated); -} -/** - * @see IDOMMember#setFlags(int) - */ -public void setFlags(int flags) { - becomeDetailed(); - if (Flags.isDeprecated(fFlags)) { - fFlags= flags | IConstants.AccDeprecated; - } else { - fFlags= flags & (~IConstants.AccDeprecated); + /** + * Sets the state of this member declaration as having a preceding comment. + */ + protected void setHasComment(boolean hasComment) { + setMask(MASK_HAS_COMMENT, hasComment); } - fragment(); - fModifiers= generateFlags(); -} -/** - * Sets the state of this member declaration as having - * a body. - */ -protected void setHasBody(boolean hasBody) { - setMask(MASK_HAS_BODY, hasBody); -} -/** - * Sets the state of this member declaration as having - * a preceding comment. - */ -protected void setHasComment(boolean hasComment) { - setMask(MASK_HAS_COMMENT, hasComment); -} -/** - * Sets the original position of the first character of this node's contents - * in its document. This method is only used during DOM creation while - * normalizing the source range of each node. - * - * Synchronize the start of the comment position with the start of the - * node. - */ -protected void setStartPosition(int start) { - if (fCommentRange[0] >= 0) { - fCommentRange[0]= start; + + /** + * Sets the original position of the first character of this node's contents + * in its document. This method is only used during DOM creation while + * normalizing the source range of each node. + * + * Synchronize the start of the comment position with the start of the node. + */ + protected void setStartPosition(int start) { + if (fCommentRange[0] >= 0) { + fCommentRange[0] = start; + } + super.setStartPosition(start); + } + + /** + * @see DOMNode#shareContents(DOMNode) + */ + protected void shareContents(DOMNode node) { + super.shareContents(node); + DOMMember member = (DOMMember) node; + fComment = member.fComment; + fCommentRange = rangeCopy(member.fCommentRange); + fFlags = member.fFlags; + fModifiers = member.fModifiers; + fModifierRange = rangeCopy(member.fModifierRange); } - super.setStartPosition(start); -} -/** - * @see DOMNode#shareContents(DOMNode) - */ -protected void shareContents(DOMNode node) { - super.shareContents(node); - DOMMember member= (DOMMember)node; - fComment= member.fComment; - fCommentRange= rangeCopy(member.fCommentRange); - fFlags= member.fFlags; - fModifiers= member.fModifiers; - fModifierRange= rangeCopy(member.fModifierRange); -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMMethod.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMMethod.java index bb30eb3..bb5a2e0 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMMethod.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMMethod.java @@ -21,698 +21,783 @@ import net.sourceforge.phpdt.internal.core.util.CharArrayOps; /** * DOMMethod provides an implementation of IDOMMethod. - * + * * @see IDOMMethod * @see DOMNode */ - + class DOMMethod extends DOMMember implements IDOMMethod { /** - * Contains the return type of the method when the - * return type has been altered from the contents - * in the document, otherwise null. + * Contains the return type of the method when the return type has been + * altered from the contents in the document, otherwise null. */ protected String fReturnType; /** - * The original inclusive source range of the - * method's return type in the document, or -1's - * if no return type is present in the document. - * If the return type of this method is qualified with - * '[]' following the parameter list, this array has - * four entries. In this case, the last two entries - * of the array are the inclusive source range of - * the array qualifiers. + * The original inclusive source range of the method's return type in the + * document, or -1's if no return type is present in the document. If the + * return type of this method is qualified with '[]' following the parameter + * list, this array has four entries. In this case, the last two entries of + * the array are the inclusive source range of the array qualifiers. */ - protected int[] fReturnTypeRange; + protected int[] fReturnTypeRange; /** - * Contains the textual representation of the method's - * parameter list, including open and closing parentheses - * when the parameters had been altered from the contents - * in the document, otherwise null. + * Contains the textual representation of the method's parameter list, + * including open and closing parentheses when the parameters had been + * altered from the contents in the document, otherwise null. */ protected char[] fParameterList; /** - * The original inclusive source range of the - * method's parameter list in the document. + * The original inclusive source range of the method's parameter list in the + * document. */ - protected int[] fParameterRange; + protected int[] fParameterRange; /** - * Contains the textual representation of the method's - * exception list when the exceptions had been altered - * from the contents in the document, otherwise - * null. The exception list is a comment - * delimited list of exceptions, not including the "throws" - * keyword. + * Contains the textual representation of the method's exception list when + * the exceptions had been altered from the contents in the document, + * otherwise null. The exception list is a comment delimited + * list of exceptions, not including the "throws" keyword. */ protected char[] fExceptionList; /** - * The original inclusive source range of the - * method's exception list in the document. + * The original inclusive source range of the method's exception list in the + * document. */ - protected int[] fExceptionRange; - + protected int[] fExceptionRange; + /** - * Contains the method's body when the body has - * been altered from the contents in the document, - * otherwise null. The body includes everything - * between and including the enclosing braces, and trailing - * whitespace. + * Contains the method's body when the body has been altered from the + * contents in the document, otherwise null. The body + * includes everything between and including the enclosing braces, and + * trailing whitespace. */ protected String fBody; /** - * The original inclusive source range of the - * method's body. + * The original inclusive source range of the method's body. */ - protected int[] fBodyRange; - + protected int[] fBodyRange; /** - * Names of parameters in the method parameter list, - * or null if the method has no parameters. + * Names of parameters in the method parameter list, or null + * if the method has no parameters. */ protected String[] fParameterNames; /** - * Types of parameters in the method parameter list, - * or null if the method has no parameters. + * Types of parameters in the method parameter list, or null + * if the method has no parameters. */ protected String[] fParameterTypes; /** - * The exceptions the method throws, or null - * if the method throws no exceptions. + * The exceptions the method throws, or null if the method + * throws no exceptions. */ protected String[] fExceptions; - -/** - * Constructs an empty method node. - */ -DOMMethod() { + /** + * Constructs an empty method node. + */ + DOMMethod() { -} -/** - * Creates a new detailed METHOD document fragment on the given range of the document. - * - * @param document - the document containing this node's original contents - * @param sourceRange - a two element array of integers describing the - * entire inclusive source range of this node within its document. - * Contents start on and include the character at the first position. - * Contents end on and include the character at the last position. - * An array of -1's indicates this node's contents do not exist - * in the document. - * @param name - the identifier portion of the name of this node, or - * null if this node does not have a name - * @param nameRange - a two element array of integers describing the - * entire inclusive source range of this node's name within its document, - * including any array qualifiers that might immediately follow the name - * or -1's if this node does not have a name. - * @param commentRange - a two element array describing the comments that precede - * the member declaration. The first matches the start of this node's - * sourceRange, and the second is the new-line or first non-whitespace - * character following the last comment. If no comments are present, - * this array contains two -1's. - * @param flags - an integer representing the modifiers for this member. The - * integer can be analyzed with net.sourceforge.phpdt.core.Flags - * @param modifierRange - a two element array describing the location of - * modifiers for this member within its source range. The first integer - * is the first character of the first modifier for this member, and - * the second integer is the last whitespace character preceeding the - * next part of this member declaration. If there are no modifiers present - * in this node's source code (that is, package default visibility), this array - * contains two -1's. - * @param isConstructor - true if the method is a contructor, otherwise false - * @param returnType - the normalized return type of this method - * @param returnTypeRange - a two element array describing the location of the - * return type within the method's source range. The first integer is is - * the position of the first character in the return type, and the second - * integer is the position of the last character in the return type. - * For constructors, the contents of this array are -1's. - * If the return type of this method is qualified with '[]' following the - * parameter list, this array has four entries. In this case, the last - * two entries of the array are the inclusive source range of the array - * qualifiers. - * @param parameterTypes - an array of parameter types in the method declaration - * or null if the method has no parameters - * @param parameterNames - an array of parameter names in the method declaration - * or null if the method has no parameters - * @param parameterRange - a two element array describing the location of the - * parameter list in the method. The first integer is the location of the - * open parenthesis and the second integer is the location of the closing - * parenthesis. - * @param exceptions - an array of the names of exceptions thrown by this method - * or null if the method throws no exceptions - * @param exceptionRange - a two element array describing the location of the - * exception list in the method declaration. The first integer is the position - * of the first character in the first exception the method throws, and the - * second integer is the position of the last character of the last exception - * this method throws. - * @param bodyRange - a two element array describing the location of the method's body. - * The first integer is the first character following the method's - * parameter list, or exception list (if present). The second integer is the location - * of the last character in the method's source range. - */ -DOMMethod(char[] document, int[] sourceRange, String name, int[] nameRange, int[] commentRange, int flags, int[] modifierRange, boolean isConstructor, String returnType, int[] returnTypeRange, String[] parameterTypes, String[] parameterNames, int[] parameterRange, String[] exceptions, int[] exceptionRange, int[] bodyRange) { - super(document, sourceRange, name, nameRange, commentRange, flags, modifierRange); - - setMask(MASK_IS_CONSTRUCTOR, isConstructor); - fReturnType= returnType; - fReturnTypeRange= returnTypeRange; - fParameterTypes= parameterTypes; - fParameterNames= parameterNames; - fParameterRange= parameterRange; - fExceptionRange= exceptionRange; - fExceptions= exceptions; - setHasBody(true); - fBodyRange= bodyRange; - setMask(MASK_DETAILED_SOURCE_INDEXES, true); - -} -/** - * Creates a new simple METHOD document fragment on the given range of the document. - * - * @param document - the document containing this node's original contents - * @param sourceRange - a two element array of integers describing the - * entire inclusive source range of this node within its document. - * Contents start on and include the character at the first position. - * Contents end on and include the character at the last position. - * An array of -1's indicates this node's contents do not exist - * in the document. - * @param name - the identifier portion of the name of this node, or - * null if this node does not have a name - * @param nameRange - a two element array of integers describing the - * entire inclusive source range of this node's name within its document, - * including any array qualifiers that might immediately follow the name - * or -1's if this node does not have a name. - * @param flags - an integer representing the modifiers for this member. The - * integer can be analyzed with net.sourceforge.phpdt.core.Flags - * @param isConstructor - true if the method is a contructor, otherwise false - * @param returnType - the normalized return type of this method - * @param parameterTypes - an array of parameter types in the method declaration - * or null if the method has no parameters - * @param parameterNames - an array of parameter names in the method declaration - * or null if the method has no parameters - * @param exceptions - an array of the names of exceptions thrown by this method - * or null if the method throws no exceptions - */ -DOMMethod(char[] document, int[] sourceRange, String name, int[] nameRange, int flags, boolean isConstructor, String returnType, String[] parameterTypes, String[] parameterNames, String[] exceptions) { - this(document, sourceRange, name, nameRange, new int[] {-1, -1}, flags, new int[] {-1, -1}, isConstructor, returnType, new int[] {-1, -1}, parameterTypes, parameterNames, new int[] {-1, -1}, exceptions, new int[] {-1, -1}, new int[] {-1, -1}); - setMask(MASK_DETAILED_SOURCE_INDEXES, false); -} -/** - * @see IDOMMethod#addException(String) - */ -public void addException(String name) throws IllegalArgumentException { - if (name == null) { - throw new IllegalArgumentException(Util.bind("dom.nullExceptionType")); //$NON-NLS-1$ } - if (fExceptions == null) { - fExceptions= new String[1]; - fExceptions[0]= name; - } else { - fExceptions= appendString(fExceptions, name); + + /** + * Creates a new detailed METHOD document fragment on the given range of the + * document. + * + * @param document - + * the document containing this node's original contents + * @param sourceRange - + * a two element array of integers describing the entire + * inclusive source range of this node within its document. + * Contents start on and include the character at the first + * position. Contents end on and include the character at the + * last position. An array of -1's indicates this node's contents + * do not exist in the document. + * @param name - + * the identifier portion of the name of this node, or + * null if this node does not have a name + * @param nameRange - + * a two element array of integers describing the entire + * inclusive source range of this node's name within its + * document, including any array qualifiers that might + * immediately follow the name or -1's if this node does not have + * a name. + * @param commentRange - + * a two element array describing the comments that precede the + * member declaration. The first matches the start of this node's + * sourceRange, and the second is the new-line or first + * non-whitespace character following the last comment. If no + * comments are present, this array contains two -1's. + * @param flags - + * an integer representing the modifiers for this member. The + * integer can be analyzed with net.sourceforge.phpdt.core.Flags + * @param modifierRange - + * a two element array describing the location of modifiers for + * this member within its source range. The first integer is the + * first character of the first modifier for this member, and the + * second integer is the last whitespace character preceeding the + * next part of this member declaration. If there are no + * modifiers present in this node's source code (that is, package + * default visibility), this array contains two -1's. + * @param isConstructor - + * true if the method is a contructor, otherwise false + * @param returnType - + * the normalized return type of this method + * @param returnTypeRange - + * a two element array describing the location of the return type + * within the method's source range. The first integer is is the + * position of the first character in the return type, and the + * second integer is the position of the last character in the + * return type. For constructors, the contents of this array are + * -1's. If the return type of this method is qualified with '[]' + * following the parameter list, this array has four entries. In + * this case, the last two entries of the array are the inclusive + * source range of the array qualifiers. + * @param parameterTypes - + * an array of parameter types in the method declaration or + * null if the method has no parameters + * @param parameterNames - + * an array of parameter names in the method declaration or + * null if the method has no parameters + * @param parameterRange - + * a two element array describing the location of the parameter + * list in the method. The first integer is the location of the + * open parenthesis and the second integer is the location of the + * closing parenthesis. + * @param exceptions - + * an array of the names of exceptions thrown by this method or + * null if the method throws no exceptions + * @param exceptionRange - + * a two element array describing the location of the exception + * list in the method declaration. The first integer is the + * position of the first character in the first exception the + * method throws, and the second integer is the position of the + * last character of the last exception this method throws. + * @param bodyRange - + * a two element array describing the location of the method's + * body. The first integer is the first character following the + * method's parameter list, or exception list (if present). The + * second integer is the location of the last character in the + * method's source range. + */ + DOMMethod(char[] document, int[] sourceRange, String name, int[] nameRange, + int[] commentRange, int flags, int[] modifierRange, + boolean isConstructor, String returnType, int[] returnTypeRange, + String[] parameterTypes, String[] parameterNames, + int[] parameterRange, String[] exceptions, int[] exceptionRange, + int[] bodyRange) { + super(document, sourceRange, name, nameRange, commentRange, flags, + modifierRange); + + setMask(MASK_IS_CONSTRUCTOR, isConstructor); + fReturnType = returnType; + fReturnTypeRange = returnTypeRange; + fParameterTypes = parameterTypes; + fParameterNames = parameterNames; + fParameterRange = parameterRange; + fExceptionRange = exceptionRange; + fExceptions = exceptions; + setHasBody(true); + fBodyRange = bodyRange; + setMask(MASK_DETAILED_SOURCE_INDEXES, true); + } - setExceptions(fExceptions); -} -/** - * @see IDOMMethod#addParameter(String, String) - */ -public void addParameter(String type, String name) throws IllegalArgumentException { - if (type == null) { - throw new IllegalArgumentException(Util.bind("dom.nullTypeParameter")); //$NON-NLS-1$ - } - if (name == null) { - throw new IllegalArgumentException(Util.bind("dom.nullNameParameter")); //$NON-NLS-1$ - } - if (fParameterNames == null) { - fParameterNames= new String[1]; - fParameterNames[0]= name; - } else { - fParameterNames= appendString(fParameterNames, name); - } - if (fParameterTypes == null) { - fParameterTypes= new String[1]; - fParameterTypes[0]= type; - } else { - fParameterTypes= appendString(fParameterTypes, type); - } - setParameters(fParameterTypes, fParameterNames); -} -/** - * @see DOMMember#appendMemberBodyContents(CharArrayBuffer) - */ -protected void appendMemberBodyContents(CharArrayBuffer buffer) { - if (fBody != null) { - buffer.append(fBody); - } else { - buffer.append(fDocument, fBodyRange[0], fBodyRange[1] + 1 - fBodyRange[0]); + + /** + * Creates a new simple METHOD document fragment on the given range of the + * document. + * + * @param document - + * the document containing this node's original contents + * @param sourceRange - + * a two element array of integers describing the entire + * inclusive source range of this node within its document. + * Contents start on and include the character at the first + * position. Contents end on and include the character at the + * last position. An array of -1's indicates this node's contents + * do not exist in the document. + * @param name - + * the identifier portion of the name of this node, or + * null if this node does not have a name + * @param nameRange - + * a two element array of integers describing the entire + * inclusive source range of this node's name within its + * document, including any array qualifiers that might + * immediately follow the name or -1's if this node does not have + * a name. + * @param flags - + * an integer representing the modifiers for this member. The + * integer can be analyzed with net.sourceforge.phpdt.core.Flags + * @param isConstructor - + * true if the method is a contructor, otherwise false + * @param returnType - + * the normalized return type of this method + * @param parameterTypes - + * an array of parameter types in the method declaration or + * null if the method has no parameters + * @param parameterNames - + * an array of parameter names in the method declaration or + * null if the method has no parameters + * @param exceptions - + * an array of the names of exceptions thrown by this method or + * null if the method throws no exceptions + */ + DOMMethod(char[] document, int[] sourceRange, String name, int[] nameRange, + int flags, boolean isConstructor, String returnType, + String[] parameterTypes, String[] parameterNames, + String[] exceptions) { + this(document, sourceRange, name, nameRange, new int[] { -1, -1 }, + flags, new int[] { -1, -1 }, isConstructor, returnType, + new int[] { -1, -1 }, parameterTypes, parameterNames, + new int[] { -1, -1 }, exceptions, new int[] { -1, -1 }, + new int[] { -1, -1 }); + setMask(MASK_DETAILED_SOURCE_INDEXES, false); } -} -/** - * @see DOMMember#appendMemberDeclarationContents(CharArrayBuffer) - */ -protected void appendMemberDeclarationContents(CharArrayBuffer buffer) { - - if (isConstructor()) { - buffer - .append(getConstructorName()) - .append(fDocument, fNameRange[1] + 1, fParameterRange[0] - fNameRange[1] - 1); - } else { - buffer.append(getReturnTypeContents()); - if (fReturnTypeRange[0] >= 0) { - buffer.append(fDocument, fReturnTypeRange[1] + 1, fNameRange[0] - fReturnTypeRange[1] - 1); + + /** + * @see IDOMMethod#addException(String) + */ + public void addException(String name) throws IllegalArgumentException { + if (name == null) { + throw new IllegalArgumentException(Util + .bind("dom.nullExceptionType")); //$NON-NLS-1$ + } + if (fExceptions == null) { + fExceptions = new String[1]; + fExceptions[0] = name; + } else { + fExceptions = appendString(fExceptions, name); + } + setExceptions(fExceptions); + } + + /** + * @see IDOMMethod#addParameter(String, String) + */ + public void addParameter(String type, String name) + throws IllegalArgumentException { + if (type == null) { + throw new IllegalArgumentException(Util + .bind("dom.nullTypeParameter")); //$NON-NLS-1$ + } + if (name == null) { + throw new IllegalArgumentException(Util + .bind("dom.nullNameParameter")); //$NON-NLS-1$ + } + if (fParameterNames == null) { + fParameterNames = new String[1]; + fParameterNames[0] = name; } else { - buffer.append(' '); + fParameterNames = appendString(fParameterNames, name); } - buffer - .append(getNameContents()) - .append(fDocument, fNameRange[1] + 1, fParameterRange[0] - fNameRange[1] - 1); - } - if (fParameterList != null) { - buffer.append(fParameterList); - } else { - buffer.append(fDocument, fParameterRange[0], fParameterRange[1] + 1 - fParameterRange[0]); - } - int start; - if (hasTrailingArrayQualifier() && isReturnTypeAltered()) { - start= fReturnTypeRange[3] + 1; - } else { - start= fParameterRange[1] + 1; - } - if (fExceptions != null) { - // add 'throws' keyword - if (fExceptionRange[0] >= 0) { - buffer.append(fDocument, start, fExceptionRange[0] - start); + if (fParameterTypes == null) { + fParameterTypes = new String[1]; + fParameterTypes[0] = type; } else { - buffer.append(" throws "); //$NON-NLS-1$ + fParameterTypes = appendString(fParameterTypes, type); } - // add exception list - if (fExceptionList != null) { - buffer.append(fExceptionList); - // add space before body - if (fExceptionRange[0] >= 0) { - buffer.append(fDocument, fExceptionRange[1] + 1, fBodyRange[0] - fExceptionRange[1] - 1); + setParameters(fParameterTypes, fParameterNames); + } + + /** + * @see DOMMember#appendMemberBodyContents(CharArrayBuffer) + */ + protected void appendMemberBodyContents(CharArrayBuffer buffer) { + if (fBody != null) { + buffer.append(fBody); + } else { + buffer.append(fDocument, fBodyRange[0], fBodyRange[1] + 1 + - fBodyRange[0]); + } + } + + /** + * @see DOMMember#appendMemberDeclarationContents(CharArrayBuffer) + */ + protected void appendMemberDeclarationContents(CharArrayBuffer buffer) { + + if (isConstructor()) { + buffer.append(getConstructorName()).append(fDocument, + fNameRange[1] + 1, fParameterRange[0] - fNameRange[1] - 1); + } else { + buffer.append(getReturnTypeContents()); + if (fReturnTypeRange[0] >= 0) { + buffer.append(fDocument, fReturnTypeRange[1] + 1, fNameRange[0] + - fReturnTypeRange[1] - 1); } else { - buffer.append(fDocument, fParameterRange[1] + 1, fBodyRange[0] - fParameterRange[1] - 1); + buffer.append(' '); } + buffer.append(getNameContents()).append(fDocument, + fNameRange[1] + 1, fParameterRange[0] - fNameRange[1] - 1); + } + if (fParameterList != null) { + buffer.append(fParameterList); } else { - // add list and space before body - buffer.append(fDocument, fExceptionRange[0], fBodyRange[0] - fExceptionRange[0]); + buffer.append(fDocument, fParameterRange[0], fParameterRange[1] + 1 + - fParameterRange[0]); } - } else { - // add space before body - if (fExceptionRange[0] >= 0) { - buffer.append(fDocument, fExceptionRange[1] + 1, fBodyRange[0] - fExceptionRange[1] - 1); + int start; + if (hasTrailingArrayQualifier() && isReturnTypeAltered()) { + start = fReturnTypeRange[3] + 1; } else { - buffer.append(fDocument, start, fBodyRange[0] - start); + start = fParameterRange[1] + 1; } - } - -} -/** - * @see DOMNode#appendSimpleContents(CharArrayBuffer) - */ -protected void appendSimpleContents(CharArrayBuffer buffer) { - // append eveything before my name - buffer.append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0]); - // append my name - if (isConstructor()) { - buffer.append(getConstructorName()); - } else { - buffer.append(fName); - } - // append everything after my name - buffer.append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]); -} -/** - * @see IDOMMethod#getBody() - */ -public String getBody() { - becomeDetailed(); - if (hasBody()) { - if (fBody != null) { - return fBody; + if (fExceptions != null) { + // add 'throws' keyword + if (fExceptionRange[0] >= 0) { + buffer.append(fDocument, start, fExceptionRange[0] - start); + } else { + buffer.append(" throws "); //$NON-NLS-1$ + } + // add exception list + if (fExceptionList != null) { + buffer.append(fExceptionList); + // add space before body + if (fExceptionRange[0] >= 0) { + buffer.append(fDocument, fExceptionRange[1] + 1, + fBodyRange[0] - fExceptionRange[1] - 1); + } else { + buffer.append(fDocument, fParameterRange[1] + 1, + fBodyRange[0] - fParameterRange[1] - 1); + } + } else { + // add list and space before body + buffer.append(fDocument, fExceptionRange[0], fBodyRange[0] + - fExceptionRange[0]); + } } else { - return CharArrayOps.substring(fDocument, fBodyRange[0], fBodyRange[1] + 1 - fBodyRange[0]); + // add space before body + if (fExceptionRange[0] >= 0) { + buffer.append(fDocument, fExceptionRange[1] + 1, fBodyRange[0] + - fExceptionRange[1] - 1); + } else { + buffer.append(fDocument, start, fBodyRange[0] - start); + } } - } else { - return null; + } -} -/** - * Returns the simple name of the enclsoing type for this constructor. - * If the constuctor is not currently enclosed in a type, the original - * name of the constructor as found in the documnent is returned. - */ -protected String getConstructorName() { - if (isConstructor()) { - if (getParent() != null) { - return getParent().getName(); + /** + * @see DOMNode#appendSimpleContents(CharArrayBuffer) + */ + protected void appendSimpleContents(CharArrayBuffer buffer) { + // append eveything before my name + buffer.append(fDocument, fSourceRange[0], fNameRange[0] + - fSourceRange[0]); + // append my name + if (isConstructor()) { + buffer.append(getConstructorName()); } else { - // If there is no parent use the original name - return new String(getNameContents()); + buffer.append(fName); } - } else { - return null; + // append everything after my name + buffer.append(fDocument, fNameRange[1] + 1, fSourceRange[1] + - fNameRange[1]); } - -} -/** - * @see DOMNode#getDetailedNode() - */ -//protected DOMNode getDetailedNode() { -// return (DOMNode)getFactory().createMethod(getContents()); -//} -/** - * @see IDOMMethod#getExceptions() - */ -public String[] getExceptions() { - return fExceptions; -} -/** - * @see IDOMNode#getJavaElement - */ -public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { - if (parent.getElementType() == IJavaElement.TYPE) { - // translate parameter types to signatures - String[] sigs= null; - if (fParameterTypes != null) { - sigs= new String[fParameterTypes.length]; - int i; - for (i= 0; i < fParameterTypes.length; i++) { - sigs[i]= Signature.createTypeSignature(fParameterTypes[i].toCharArray(), false); + + /** + * @see IDOMMethod#getBody() + */ + public String getBody() { + becomeDetailed(); + if (hasBody()) { + if (fBody != null) { + return fBody; + } else { + return CharArrayOps.substring(fDocument, fBodyRange[0], + fBodyRange[1] + 1 - fBodyRange[0]); } + } else { + return null; } - String name= null; + } + + /** + * Returns the simple name of the enclsoing type for this constructor. If + * the constuctor is not currently enclosed in a type, the original name of + * the constructor as found in the documnent is returned. + */ + protected String getConstructorName() { + if (isConstructor()) { - name= getConstructorName(); + if (getParent() != null) { + return getParent().getName(); + } else { + // If there is no parent use the original name + return new String(getNameContents()); + } } else { - name= getName(); + return null; } - return ((IType)parent).getMethod(name, sigs); - } else { - throw new IllegalArgumentException(Util.bind("element.illegalParent")); //$NON-NLS-1$ + } -} -/** - * @see DOMMember#getMemberDeclarationStartPosition() - */ -protected int getMemberDeclarationStartPosition() { - if (fReturnTypeRange[0] >= 0) { - return fReturnTypeRange[0]; - } else { - return fNameRange[0]; + + /** + * @see DOMNode#getDetailedNode() + */ + // protected DOMNode getDetailedNode() { + // return (DOMNode)getFactory().createMethod(getContents()); + // } + /** + * @see IDOMMethod#getExceptions() + */ + public String[] getExceptions() { + return fExceptions; } -} -/** - * @see IDOMNode#getName() - */ -public String getName() { - if (isConstructor()) { - return null; - } else { - return super.getName(); + + /** + * @see IDOMNode#getJavaElement + */ + public IJavaElement getJavaElement(IJavaElement parent) + throws IllegalArgumentException { + if (parent.getElementType() == IJavaElement.TYPE) { + // translate parameter types to signatures + String[] sigs = null; + if (fParameterTypes != null) { + sigs = new String[fParameterTypes.length]; + int i; + for (i = 0; i < fParameterTypes.length; i++) { + sigs[i] = Signature.createTypeSignature(fParameterTypes[i] + .toCharArray(), false); + } + } + String name = null; + if (isConstructor()) { + name = getConstructorName(); + } else { + name = getName(); + } + return ((IType) parent).getMethod(name, sigs); + } else { + throw new IllegalArgumentException(Util + .bind("element.illegalParent")); //$NON-NLS-1$ + } } -} -/** - * @see IDOMNode#getNodeType() - */ -public int getNodeType() { - return IDOMNode.METHOD; -} -/** - * @see IDOMMethod#getParameterNames() - */ -public String[] getParameterNames() { - return fParameterNames; -} -/** - * @see IDOMMethod#getParameterTypes() - */ -public String[] getParameterTypes() { - return fParameterTypes; -} -/** - * @see IDOMMethod#getReturnType() - */ -public String getReturnType() { - if (isConstructor()) { - return null; - } else { - return fReturnType; + + /** + * @see DOMMember#getMemberDeclarationStartPosition() + */ + protected int getMemberDeclarationStartPosition() { + if (fReturnTypeRange[0] >= 0) { + return fReturnTypeRange[0]; + } else { + return fNameRange[0]; + } } -} -/** - * Returns the source code to be used for this method's return type - */ -protected char[] getReturnTypeContents() { - if (isConstructor()) { - return null; - } else { - if (isReturnTypeAltered()) { - return fReturnType.toCharArray(); + + /** + * @see IDOMNode#getName() + */ + public String getName() { + if (isConstructor()) { + return null; } else { - return CharArrayOps.subarray(fDocument, fReturnTypeRange[0], fReturnTypeRange[1] + 1 - fReturnTypeRange[0]); + return super.getName(); } + } + /** + * @see IDOMNode#getNodeType() + */ + public int getNodeType() { + return IDOMNode.METHOD; } -} -/** - * Returns true if this method's return type has - * array qualifiers ('[]') following the parameter list. - */ -protected boolean hasTrailingArrayQualifier() { - return fReturnTypeRange.length > 2; -} -/** - * @see IDOMMethod#isConstructor() - */ -public boolean isConstructor() { - return getMask(MASK_IS_CONSTRUCTOR); -} -/** - * Returns true if this method's return type has been altered - * from the original document contents. - */ -protected boolean isReturnTypeAltered() { - return getMask(MASK_RETURN_TYPE_ALTERED); -} -/** - * @see IDOMNode#isSigantureEqual(IDOMNode). - * - *

                                                      Two methods have equal signatures if there names are the same - * and their parameter types are the same. - */ -public boolean isSignatureEqual(IDOMNode node) { - boolean ok= node.getNodeType() == getNodeType(); - if (ok) { - IDOMMethod method= (IDOMMethod)node; - ok = (isConstructor() && method.isConstructor()) || - (!isConstructor() && !method.isConstructor()); - if (ok && !isConstructor()) { - ok= getName().equals(method.getName()); - } - if (!ok) { - return false; + + /** + * @see IDOMMethod#getParameterNames() + */ + public String[] getParameterNames() { + return fParameterNames; + } + + /** + * @see IDOMMethod#getParameterTypes() + */ + public String[] getParameterTypes() { + return fParameterTypes; + } + + /** + * @see IDOMMethod#getReturnType() + */ + public String getReturnType() { + if (isConstructor()) { + return null; + } else { + return fReturnType; } - - String[] types= method.getParameterTypes(); - if (fParameterTypes == null || fParameterTypes.length == 0) { - // this method has no parameters - if (types == null || types.length == 0) { - // the other method has no parameters either - return true; - } + } + + /** + * Returns the source code to be used for this method's return type + */ + protected char[] getReturnTypeContents() { + if (isConstructor()) { + return null; } else { - // this method has parameters - if (types == null || types.length == 0) { - // the other method has no parameters - return false; + if (isReturnTypeAltered()) { + return fReturnType.toCharArray(); + } else { + return CharArrayOps.subarray(fDocument, fReturnTypeRange[0], + fReturnTypeRange[1] + 1 - fReturnTypeRange[0]); + } + + } + } + + /** + * Returns true if this method's return type has array qualifiers ('[]') + * following the parameter list. + */ + protected boolean hasTrailingArrayQualifier() { + return fReturnTypeRange.length > 2; + } + + /** + * @see IDOMMethod#isConstructor() + */ + public boolean isConstructor() { + return getMask(MASK_IS_CONSTRUCTOR); + } + + /** + * Returns true if this method's return type has been altered from the + * original document contents. + */ + protected boolean isReturnTypeAltered() { + return getMask(MASK_RETURN_TYPE_ALTERED); + } + + /** + * @see IDOMNode#isSigantureEqual(IDOMNode). + * + *

                                                      + * Two methods have equal signatures if there names are the same and their + * parameter types are the same. + */ + public boolean isSignatureEqual(IDOMNode node) { + boolean ok = node.getNodeType() == getNodeType(); + if (ok) { + IDOMMethod method = (IDOMMethod) node; + ok = (isConstructor() && method.isConstructor()) + || (!isConstructor() && !method.isConstructor()); + if (ok && !isConstructor()) { + ok = getName().equals(method.getName()); } - if (fParameterTypes.length != types.length) { - // the methods have a different number of parameters + if (!ok) { return false; } - int i; - for (i= 0; i < types.length; i++) { - if (!fParameterTypes[i].equals(types[i])) { + + String[] types = method.getParameterTypes(); + if (fParameterTypes == null || fParameterTypes.length == 0) { + // this method has no parameters + if (types == null || types.length == 0) { + // the other method has no parameters either + return true; + } + } else { + // this method has parameters + if (types == null || types.length == 0) { + // the other method has no parameters return false; } + if (fParameterTypes.length != types.length) { + // the methods have a different number of parameters + return false; + } + int i; + for (i = 0; i < types.length; i++) { + if (!fParameterTypes[i].equals(types[i])) { + return false; + } + } + return true; } - return true; } + return false; + } - return false; - -} -/** - * @see DOMNode - */ -protected DOMNode newDOMNode() { - return new DOMMethod(); -} -/** - * Offsets all the source indexes in this node by the given amount. - */ -protected void offset(int offset) { - super.offset(offset); - offsetRange(fBodyRange, offset); - offsetRange(fExceptionRange, offset); - offsetRange(fParameterRange, offset); - offsetRange(fReturnTypeRange, offset); -} -/** - * @see IDOMMethod#setBody - */ -public void setBody(String body) { - becomeDetailed(); - fragment(); - fBody= body; - setHasBody(body != null); - if (!hasBody()) { - fBody= ";"+Util.LINE_SEPARATOR; //$NON-NLS-1$ + + /** + * @see DOMNode + */ + protected DOMNode newDOMNode() { + return new DOMMethod(); } -} -/** - * Sets the end of the body range - */ -void setBodyRangeEnd(int end) { - fBodyRange[1] = end; -} -/** - * @see IDOMMethod#setConstructor(boolean) - */ -public void setConstructor(boolean b) { - becomeDetailed(); - setMask(MASK_IS_CONSTRUCTOR, b); - fragment(); -} -/** - * @see IDOMMethod#setExceptions(char[][]) - */ -public void setExceptions(String[] names) { - becomeDetailed(); - if (names == null || names.length == 0) { - fExceptions= null; - } else { - fExceptions= names; - CharArrayBuffer buffer = new CharArrayBuffer(); - char[] comma = new char[] {',', ' '}; - for (int i = 0, length = names.length; i < length; i++) { - if (i > 0) - buffer.append(comma); - buffer.append(names[i]); + + /** + * Offsets all the source indexes in this node by the given amount. + */ + protected void offset(int offset) { + super.offset(offset); + offsetRange(fBodyRange, offset); + offsetRange(fExceptionRange, offset); + offsetRange(fParameterRange, offset); + offsetRange(fReturnTypeRange, offset); + } + + /** + * @see IDOMMethod#setBody + */ + public void setBody(String body) { + becomeDetailed(); + fragment(); + fBody = body; + setHasBody(body != null); + if (!hasBody()) { + fBody = ";" + Util.LINE_SEPARATOR; //$NON-NLS-1$ } - fExceptionList= buffer.getContents(); } - fragment(); -} -/** - * @see IDOMMethod#setName - */ -public void setName(String name) { - if (name == null) { - throw new IllegalArgumentException(Util.bind("element.nullName")); //$NON-NLS-1$ - } else { - super.setName(name); + + /** + * Sets the end of the body range + */ + void setBodyRangeEnd(int end) { + fBodyRange[1] = end; } -} -/** - * @see IDOMMethod#setParameters(char[][], char[][]) - */ -public void setParameters(String[] types, String[] names) throws IllegalArgumentException { - becomeDetailed(); - if (types== null || names == null) { - if (types == null && names == null) { - fParameterTypes= null; - fParameterNames= null; - fParameterList= new char[] {'(',')'}; + + /** + * @see IDOMMethod#setConstructor(boolean) + */ + public void setConstructor(boolean b) { + becomeDetailed(); + setMask(MASK_IS_CONSTRUCTOR, b); + fragment(); + } + + /** + * @see IDOMMethod#setExceptions(char[][]) + */ + public void setExceptions(String[] names) { + becomeDetailed(); + if (names == null || names.length == 0) { + fExceptions = null; + } else { + fExceptions = names; + CharArrayBuffer buffer = new CharArrayBuffer(); + char[] comma = new char[] { ',', ' ' }; + for (int i = 0, length = names.length; i < length; i++) { + if (i > 0) + buffer.append(comma); + buffer.append(names[i]); + } + fExceptionList = buffer.getContents(); + } + fragment(); + } + + /** + * @see IDOMMethod#setName + */ + public void setName(String name) { + if (name == null) { + throw new IllegalArgumentException(Util.bind("element.nullName")); //$NON-NLS-1$ } else { - throw new IllegalArgumentException(Util.bind("dom.mismatchArgNamesAndTypes")); //$NON-NLS-1$ + super.setName(name); } - } else if (names.length != types.length) { - throw new IllegalArgumentException(Util.bind("dom.mismatchArgNamesAndTypes")); //$NON-NLS-1$ - } else if (names.length == 0) { - setParameters(null, null); - } else { - fParameterNames= names; - fParameterTypes= types; - CharArrayBuffer parametersBuffer = new CharArrayBuffer(); - parametersBuffer.append("("); //$NON-NLS-1$ - char[] comma = new char[] {',', ' '}; - for (int i = 0; i < names.length; i++) { - if (i > 0) { - parametersBuffer.append(comma); + } + + /** + * @see IDOMMethod#setParameters(char[][], char[][]) + */ + public void setParameters(String[] types, String[] names) + throws IllegalArgumentException { + becomeDetailed(); + if (types == null || names == null) { + if (types == null && names == null) { + fParameterTypes = null; + fParameterNames = null; + fParameterList = new char[] { '(', ')' }; + } else { + throw new IllegalArgumentException(Util + .bind("dom.mismatchArgNamesAndTypes")); //$NON-NLS-1$ + } + } else if (names.length != types.length) { + throw new IllegalArgumentException(Util + .bind("dom.mismatchArgNamesAndTypes")); //$NON-NLS-1$ + } else if (names.length == 0) { + setParameters(null, null); + } else { + fParameterNames = names; + fParameterTypes = types; + CharArrayBuffer parametersBuffer = new CharArrayBuffer(); + parametersBuffer.append("("); //$NON-NLS-1$ + char[] comma = new char[] { ',', ' ' }; + for (int i = 0; i < names.length; i++) { + if (i > 0) { + parametersBuffer.append(comma); + } + parametersBuffer.append(types[i]).append(' ').append(names[i]); } - parametersBuffer - .append(types[i]) - .append(' ') - .append(names[i]); + parametersBuffer.append(')'); + fParameterList = parametersBuffer.getContents(); } - parametersBuffer.append(')'); - fParameterList= parametersBuffer.getContents(); + fragment(); } - fragment(); -} -/** - * @see IDOMMethod#setReturnType(char[]) - */ -public void setReturnType(String name) throws IllegalArgumentException { - if (name == null) { - throw new IllegalArgumentException(Util.bind("dom.nullReturnType")); //$NON-NLS-1$ - } - becomeDetailed(); - fragment(); - setReturnTypeAltered(true); - fReturnType= name; -} -/** - * Sets the state of this method declaration as having - * the return type altered from the original document. - */ -protected void setReturnTypeAltered(boolean typeAltered) { - setMask(MASK_RETURN_TYPE_ALTERED, typeAltered); -} -/** - */ -protected void setSourceRangeEnd(int end) { - super.setSourceRangeEnd(end); - fBodyRange[1]= end; -} -/** - * @see DOMNode#shareContents(DOMNode) - */ -protected void shareContents(DOMNode node) { - super.shareContents(node); - DOMMethod method= (DOMMethod)node; - fBody= method.fBody; - fBodyRange= rangeCopy(method.fBodyRange); - fExceptionList= method.fExceptionList; - fExceptionRange= rangeCopy(method.fExceptionRange); - fExceptions= method.fExceptions; - fParameterList= method.fParameterList; - fParameterNames= method.fParameterNames; - fParameterRange= rangeCopy(method.fParameterRange); - fParameterTypes= method.fParameterTypes; - fReturnType= method.fReturnType; - fReturnTypeRange= rangeCopy(method.fReturnTypeRange); -} -/** - * @see IDOMNode#toString() - */ -public String toString() { - if (isConstructor()) { - return "CONSTRUCTOR"; //$NON-NLS-1$ - } else { - return "METHOD: " + getName(); //$NON-NLS-1$ + + /** + * @see IDOMMethod#setReturnType(char[]) + */ + public void setReturnType(String name) throws IllegalArgumentException { + if (name == null) { + throw new IllegalArgumentException(Util.bind("dom.nullReturnType")); //$NON-NLS-1$ + } + becomeDetailed(); + fragment(); + setReturnTypeAltered(true); + fReturnType = name; + } + + /** + * Sets the state of this method declaration as having the return type + * altered from the original document. + */ + protected void setReturnTypeAltered(boolean typeAltered) { + setMask(MASK_RETURN_TYPE_ALTERED, typeAltered); + } + + /** + */ + protected void setSourceRangeEnd(int end) { + super.setSourceRangeEnd(end); + fBodyRange[1] = end; + } + + /** + * @see DOMNode#shareContents(DOMNode) + */ + protected void shareContents(DOMNode node) { + super.shareContents(node); + DOMMethod method = (DOMMethod) node; + fBody = method.fBody; + fBodyRange = rangeCopy(method.fBodyRange); + fExceptionList = method.fExceptionList; + fExceptionRange = rangeCopy(method.fExceptionRange); + fExceptions = method.fExceptions; + fParameterList = method.fParameterList; + fParameterNames = method.fParameterNames; + fParameterRange = rangeCopy(method.fParameterRange); + fParameterTypes = method.fParameterTypes; + fReturnType = method.fReturnType; + fReturnTypeRange = rangeCopy(method.fReturnTypeRange); + } + + /** + * @see IDOMNode#toString() + */ + public String toString() { + if (isConstructor()) { + return "CONSTRUCTOR"; //$NON-NLS-1$ + } else { + return "METHOD: " + getName(); //$NON-NLS-1$ + } } -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMNode.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMNode.java index 833adf9..9634486 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMNode.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMNode.java @@ -23,949 +23,1024 @@ import net.sourceforge.phpdt.internal.core.util.CharArrayBuffer; /** * DOMNode provides an implementation for IDOMNode. - * - *

                                                      A node represents a document fragment. When a node is created, its - * contents are located in a contiguous range of a shared document. A shared - * document is a char array, and is shared in the sense that the contents of other - * document fragments may also be contained in the array. * - *

                                                      A node maintains indicies of relevant portions of its contents - * in the shared document. Thus the original document and indicies create a - * form from which to generate the contents of the document fragment. As attributes - * of a node are changed, the node attempts to maintain the original formatting - * by only replacing relevant portions of the shared document with the value - * of new attributes (that is, filling in the form with replacement values). - * - *

                                                      When a node is first created, it is considered unfragmented. When any - * attribute of the node is altered, the node is then considered fragmented - * from that point on. A node is also considered fragmented if any of its - * descendants are fragmented. When a node is unfragmented, the contents of the - * node can be efficiently generated from the original shared document. When - * a node is fragmented, the contents of the node must be created using the - * original document and indicies as a form, filling in replacement values - * as required. - * - *

                                                      Generally, a node's contents consists of complete lines in a shared document. + *

                                                      + * A node represents a document fragment. When a node is created, its contents + * are located in a contiguous range of a shared document. A shared document is + * a char array, and is shared in the sense that the contents of other document + * fragments may also be contained in the array. + * + *

                                                      + * A node maintains indicies of relevant portions of its contents in the shared + * document. Thus the original document and indicies create a form from which to + * generate the contents of the document fragment. As attributes of a node are + * changed, the node attempts to maintain the original formatting by only + * replacing relevant portions of the shared document with the value of new + * attributes (that is, filling in the form with replacement values). + * + *

                                                      + * When a node is first created, it is considered unfragmented. When any + * attribute of the node is altered, the node is then considered fragmented from + * that point on. A node is also considered fragmented if any of its descendants + * are fragmented. When a node is unfragmented, the contents of the node can be + * efficiently generated from the original shared document. When a node is + * fragmented, the contents of the node must be created using the original + * document and indicies as a form, filling in replacement values as required. + * + *

                                                      + * Generally, a node's contents consists of complete lines in a shared document. * The contents of the node are normalized on creation to include any whitespace - * preceding the node on the line where the node begins, and to include and trailing - * whitespace up to the line where the next node begins. Any trailing // comments - * that begin on the line where the current node ends, are considered part of that - * node. - * + * preceding the node on the line where the node begins, and to include and + * trailing whitespace up to the line where the next node begins. Any trailing // + * comments that begin on the line where the current node ends, are considered + * part of that node. + * * @see IDOMNode */ public abstract class DOMNode implements IDOMNode { /** - * The first child of this node - null - * when this node has no children. (Children of a node - * are implemented as a doubly linked list). + * The first child of this node - null when this node has no + * children. (Children of a node are implemented as a doubly linked list). */ - protected DOMNode fFirstChild= null; + protected DOMNode fFirstChild = null; /** - * The last child of this node - null - * when this node has no children. Used for efficient - * access to the last child when adding new children - * at the end of the linked list of children. + * The last child of this node - null when this node has no + * children. Used for efficient access to the last child when adding new + * children at the end of the linked list of children. */ - protected DOMNode fLastChild= null; + protected DOMNode fLastChild = null; /** - * The sibling node following this node - null - * for the last node in the sibling list. + * The sibling node following this node - null for the last + * node in the sibling list. */ - protected DOMNode fNextNode= null; + protected DOMNode fNextNode = null; /** - * The parent of this node. A null - * parent indicates that this node is a root - * node of a document fragment. + * The parent of this node. A null parent indicates that this + * node is a root node of a document fragment. */ - protected DOMNode fParent= null; + protected DOMNode fParent = null; /** - * The sibling node preceding this node - null - * for the first node in the sibling list. + * The sibling node preceding this node - null for the first + * node in the sibling list. */ - protected DOMNode fPreviousNode= null; + protected DOMNode fPreviousNode = null; /** - * True when this node has attributes that have - * been altered from their original state in the - * shared document, or when the attributes of a - * descendant have been altered. False when the - * contents of this node and all descendants are - * consistent with the content of the shared - * document. + * True when this node has attributes that have been altered from their + * original state in the shared document, or when the attributes of a + * descendant have been altered. False when the contents of this node and + * all descendants are consistent with the content of the shared document. */ - protected boolean fIsFragmented= false; + protected boolean fIsFragmented = false; /** - * The name of this node. For efficiency, the - * name of a node is duplicated in this variable - * on creation, rather than always having to fetch - * the name from the shared document. + * The name of this node. For efficiency, the name of a node is duplicated + * in this variable on creation, rather than always having to fetch the name + * from the shared document. */ - protected String fName= null; + protected String fName = null; /** - * The original inclusive indicies of this node's name in - * the shared document. Values of -1 indiciate the name - * does not exist in the document. + * The original inclusive indicies of this node's name in the shared + * document. Values of -1 indiciate the name does not exist in the document. */ - protected int[] fNameRange; + protected int[] fNameRange; /** - * The shared document that the contents for this node - * are contained in. Attribute indicies are positions - * in this character array. + * The shared document that the contents for this node are contained in. + * Attribute indicies are positions in this character array. */ - protected char[] fDocument= null; + protected char[] fDocument = null; /** - * The original entire inclusive range of this node's contents - * within its document. Values of -1 indicate the contents - * of this node do not exist in the document. + * The original entire inclusive range of this node's contents within its + * document. Values of -1 indicate the contents of this node do not exist in + * the document. */ protected int[] fSourceRange; /** - * The current state of bit masks defined by this node. - * Initially all bit flags are turned off. All bit masks - * are defined by this class to avoid overlap, although - * bit masks are node type specific. - * + * The current state of bit masks defined by this node. Initially all bit + * flags are turned off. All bit masks are defined by this class to avoid + * overlap, although bit masks are node type specific. + * * @see #setMask * @see #getMask */ - protected int fStateMask= 0; + protected int fStateMask = 0; /** - * This position is the position of the end of the last line separator before the closing brace starting - * position of the receiver. + * This position is the position of the end of the last line separator + * before the closing brace starting position of the receiver. */ protected int fInsertionPosition; /** - * A bit mask indicating this field has an initializer - * expression + * A bit mask indicating this field has an initializer expression */ - protected static final int MASK_FIELD_HAS_INITIALIZER= 0x00000001; - + protected static final int MASK_FIELD_HAS_INITIALIZER = 0x00000001; + /** - * A bit mask indicating this field is a secondary variable - * declarator for a previous field declaration. + * A bit mask indicating this field is a secondary variable declarator for a + * previous field declaration. */ - protected static final int MASK_FIELD_IS_VARIABLE_DECLARATOR= 0x00000002; + protected static final int MASK_FIELD_IS_VARIABLE_DECLARATOR = 0x00000002; /** - * A bit mask indicating this field's type has been - * altered from its original contents in the document. + * A bit mask indicating this field's type has been altered from its + * original contents in the document. */ - protected static final int MASK_FIELD_TYPE_ALTERED= 0x00000004; + protected static final int MASK_FIELD_TYPE_ALTERED = 0x00000004; /** - * A bit mask indicating this node's name has been - * altered from its original contents in the document. + * A bit mask indicating this node's name has been altered from its original + * contents in the document. */ - protected static final int MASK_NAME_ALTERED= 0x00000008; + protected static final int MASK_NAME_ALTERED = 0x00000008; /** - * A bit mask indicating this node currently has a - * body. + * A bit mask indicating this node currently has a body. */ - protected static final int MASK_HAS_BODY= 0x00000010; - + protected static final int MASK_HAS_BODY = 0x00000010; + /** - * A bit mask indicating this node currently has a - * preceding comment. + * A bit mask indicating this node currently has a preceding comment. */ - protected static final int MASK_HAS_COMMENT= 0x00000020; + protected static final int MASK_HAS_COMMENT = 0x00000020; /** * A bit mask indicating this method is a constructor. */ - protected static final int MASK_IS_CONSTRUCTOR= 0x00000040; + protected static final int MASK_IS_CONSTRUCTOR = 0x00000040; /** * A bit mask indicating this type is a class. */ - protected static final int MASK_TYPE_IS_CLASS= 0x00000080; + protected static final int MASK_TYPE_IS_CLASS = 0x00000080; /** - * A bit mask indicating this type has a superclass - * (requires or has an 'extends' clause). + * A bit mask indicating this type has a superclass (requires or has an + * 'extends' clause). */ - protected static final int MASK_TYPE_HAS_SUPERCLASS= 0x00000100; + protected static final int MASK_TYPE_HAS_SUPERCLASS = 0x00000100; /** - * A bit mask indicating this type implements - * or extends some interfaces + * A bit mask indicating this type implements or extends some interfaces */ - protected static final int MASK_TYPE_HAS_INTERFACES= 0x00000200; + protected static final int MASK_TYPE_HAS_INTERFACES = 0x00000200; /** - * A bit mask indicating this return type of this method has - * been altered from the original contents. + * A bit mask indicating this return type of this method has been altered + * from the original contents. */ - protected static final int MASK_RETURN_TYPE_ALTERED= 0x00000400; + protected static final int MASK_RETURN_TYPE_ALTERED = 0x00000400; /** * A bit mask indicating this node has detailed source indexes */ protected static final int MASK_DETAILED_SOURCE_INDEXES = 0x00000800; -/** - * Creates a new empty document fragment. - */ -DOMNode() { - fName= null; - fDocument= null; - fSourceRange= new int[]{-1, -1}; - fNameRange= new int[]{-1, -1}; - fragment(); -} -/** - * Creates a new document fragment on the given range of the document. - * - * @param document - the document containing this node's original contents - * @param sourceRange - a two element array of integers describing the - * entire inclusive source range of this node within its document. - * Contents start on and include the character at the first position. - * Contents end on and include the character at the last position. - * An array of -1's indicates this node's contents do not exist - * in the document. - * @param name - the identifier portion of the name of this node, or - * null if this node does not have a name - * @param nameRange - a two element array of integers describing the - * entire inclusive source range of this node's name within its document, - * including any array qualifiers that might immediately follow the name - * or -1's if this node does not have a name. - */ -DOMNode(char[] document, int[] sourceRange, String name, int[] nameRange) { - super(); - fDocument= document; - fSourceRange= sourceRange; - fName= name; - fNameRange= nameRange; - -} -/** - * Adds the given un-parented node (document fragment) as the last child of - * this node. - * - *

                                                      When a child is added, this node must be considered fragmented such that - * the contents of this node are properly generated. - * - * @see IDOMNode#addChild(IDOMNode) - */ -public void addChild(IDOMNode child) throws IllegalArgumentException, DOMException { - basicAddChild(child); - - // if the node is a constructor, it must also be fragmented to update the constructor's name - if (child.getNodeType() == IDOMNode.METHOD && ((IDOMMethod)child).isConstructor()) { - ((DOMNode)child).fragment(); - } else { + /** + * Creates a new empty document fragment. + */ + DOMNode() { + fName = null; + fDocument = null; + fSourceRange = new int[] { -1, -1 }; + fNameRange = new int[] { -1, -1 }; fragment(); } -} -/** - * Appends the current contents of this document fragment - * to the given CharArrayBuffer. - * - *

                                                      If this node is fragmented, contents must be generated by - * using the original document and indicies as a form for the current - * attribute values of this node. If this node not fragmented, the - * contents can be obtained from the document. - * - */ -protected void appendContents(CharArrayBuffer buffer) { - if (isFragmented()) { - appendFragmentedContents(buffer); - } else { - buffer.append(fDocument, fSourceRange[0], fSourceRange[1] + 1 - fSourceRange[0]); + + /** + * Creates a new document fragment on the given range of the document. + * + * @param document - + * the document containing this node's original contents + * @param sourceRange - + * a two element array of integers describing the entire + * inclusive source range of this node within its document. + * Contents start on and include the character at the first + * position. Contents end on and include the character at the + * last position. An array of -1's indicates this node's contents + * do not exist in the document. + * @param name - + * the identifier portion of the name of this node, or + * null if this node does not have a name + * @param nameRange - + * a two element array of integers describing the entire + * inclusive source range of this node's name within its + * document, including any array qualifiers that might + * immediately follow the name or -1's if this node does not have + * a name. + */ + DOMNode(char[] document, int[] sourceRange, String name, int[] nameRange) { + super(); + fDocument = document; + fSourceRange = sourceRange; + fName = name; + fNameRange = nameRange; + } -} -/** - * Appends the contents of all children of this node to the - * given CharArrayBuffer. - * - *

                                                      This algorithm used minimizes String generation by merging - * adjacent unfragmented children into one substring operation. - * - */ -protected void appendContentsOfChildren(CharArrayBuffer buffer) { - DOMNode child= fFirstChild; - DOMNode sibling; - - int start= 0, end= 0; - if (child != null) { - start= child.getStartPosition(); - end= child.getEndPosition(); - } - while (child != null) { - sibling= child.fNextNode; - if (sibling != null) { - if (sibling.isContentMergableWith(child)) { - end= sibling.getEndPosition(); + + /** + * Adds the given un-parented node (document fragment) as the last child of + * this node. + * + *

                                                      + * When a child is added, this node must be considered fragmented such that + * the contents of this node are properly generated. + * + * @see IDOMNode#addChild(IDOMNode) + */ + public void addChild(IDOMNode child) throws IllegalArgumentException, + DOMException { + basicAddChild(child); + + // if the node is a constructor, it must also be fragmented to update + // the constructor's name + if (child.getNodeType() == IDOMNode.METHOD + && ((IDOMMethod) child).isConstructor()) { + ((DOMNode) child).fragment(); + } else { + fragment(); + } + } + + /** + * Appends the current contents of this document fragment to the given + * CharArrayBuffer. + * + *

                                                      + * If this node is fragmented, contents must be generated by using the + * original document and indicies as a form for the current attribute values + * of this node. If this node not fragmented, the contents can be obtained + * from the document. + * + */ + protected void appendContents(CharArrayBuffer buffer) { + if (isFragmented()) { + appendFragmentedContents(buffer); + } else { + buffer.append(fDocument, fSourceRange[0], fSourceRange[1] + 1 + - fSourceRange[0]); + } + } + + /** + * Appends the contents of all children of this node to the given + * CharArrayBuffer. + * + *

                                                      + * This algorithm used minimizes String generation by merging adjacent + * unfragmented children into one substring operation. + * + */ + protected void appendContentsOfChildren(CharArrayBuffer buffer) { + DOMNode child = fFirstChild; + DOMNode sibling; + + int start = 0, end = 0; + if (child != null) { + start = child.getStartPosition(); + end = child.getEndPosition(); + } + while (child != null) { + sibling = child.fNextNode; + if (sibling != null) { + if (sibling.isContentMergableWith(child)) { + end = sibling.getEndPosition(); + } else { + if (child.isFragmented()) { + child.appendContents(buffer); + } else { + buffer.append(child.getDocument(), start, end + 1 + - start); + } + start = sibling.getStartPosition(); + end = sibling.getEndPosition(); + } } else { if (child.isFragmented()) { child.appendContents(buffer); } else { buffer.append(child.getDocument(), start, end + 1 - start); } - start= sibling.getStartPosition(); - end= sibling.getEndPosition(); } + child = sibling; + } + } + + /** + * Appends the contents of this node to the given + * CharArrayBufer, using the original document and indicies + * as a form for the current attribute values of this node. + */ + protected abstract void appendFragmentedContents(CharArrayBuffer buffer); + + /** + * Adds the given un-parented node (document fragment) as the last child of + * this node without setting this node's 'fragmented' flag. This method is + * only used by the DOMBuilder when creating a new DOM such + * that a new DOM is unfragmented. + */ + void basicAddChild(IDOMNode child) throws IllegalArgumentException, + DOMException { + // verify child may be added + if (!canHaveChildren()) { + throw new DOMException(Util.bind("dom.unableAddChild")); //$NON-NLS-1$ + } + if (child == null) { + throw new IllegalArgumentException(Util.bind("dom.addNullChild")); //$NON-NLS-1$ + } + if (!isAllowableChild(child)) { + throw new DOMException(Util.bind("dom.addIncompatibleChild")); //$NON-NLS-1$ + } + if (child.getParent() != null) { + throw new DOMException(Util.bind("dom.addChildWithParent")); //$NON-NLS-1$ + } + /* + * NOTE: To test if the child is an ancestor of this node, we need only + * test if the root of this node is the child (the child is already a + * root since we have just guarenteed it has no parent). + */ + if (child == getRoot()) { + throw new DOMException(Util.bind("dom.addAncestorAsChild")); //$NON-NLS-1$ + } + + DOMNode node = (DOMNode) child; + + // if the child is not already part of this document, localize its + // contents + // before adding it to the tree + if (node.getDocument() != getDocument()) { + node.localizeContents(); + } + + // add the child last + if (fFirstChild == null) { + // this is the first and only child + fFirstChild = node; } else { - if (child.isFragmented()) { - child.appendContents(buffer); - } else { - buffer.append(child.getDocument(), start, end + 1 - start); + fLastChild.fNextNode = node; + node.fPreviousNode = fLastChild; + } + fLastChild = node; + node.fParent = this; + } + + /** + * Generates detailed source indexes for this node if possible. + * + * @exception DOMException + * if unable to generate detailed source indexes for this + * node + */ + protected void becomeDetailed() throws DOMException { + if (!isDetailed()) { + DOMNode detailed = getDetailedNode(); + if (detailed == null) { + throw new DOMException(Util.bind("dom.cannotDetail")); //$NON-NLS-1$ + } + if (detailed != this) { + shareContents(detailed); } } - child= sibling; } -} -/** - * Appends the contents of this node to the given CharArrayBufer, using - * the original document and indicies as a form for the current attribute - * values of this node. - */ -protected abstract void appendFragmentedContents(CharArrayBuffer buffer); -/** - * Adds the given un-parented node (document fragment) as the last child of - * this node without setting this node's 'fragmented' flag. This - * method is only used by the DOMBuilder when creating a new DOM such - * that a new DOM is unfragmented. - */ -void basicAddChild(IDOMNode child) throws IllegalArgumentException, DOMException { - // verify child may be added - if (!canHaveChildren()) { - throw new DOMException(Util.bind("dom.unableAddChild")); //$NON-NLS-1$ - } - if (child == null) { - throw new IllegalArgumentException(Util.bind("dom.addNullChild")); //$NON-NLS-1$ - } - if (!isAllowableChild(child)) { - throw new DOMException(Util.bind("dom.addIncompatibleChild")); //$NON-NLS-1$ - } - if (child.getParent() != null) { - throw new DOMException(Util.bind("dom.addChildWithParent")); //$NON-NLS-1$ - } - /* NOTE: To test if the child is an ancestor of this node, we - * need only test if the root of this node is the child (the child - * is already a root since we have just guarenteed it has no parent). - */ - if (child == getRoot()) { - throw new DOMException(Util.bind("dom.addAncestorAsChild")); //$NON-NLS-1$ - } - - DOMNode node= (DOMNode)child; - - // if the child is not already part of this document, localize its contents - // before adding it to the tree - if (node.getDocument() != getDocument()) { - node.localizeContents(); - } - - // add the child last - if (fFirstChild == null) { - // this is the first and only child - fFirstChild= node; - } else { - fLastChild.fNextNode= node; - node.fPreviousNode= fLastChild; - } - fLastChild= node; - node.fParent= this; -} -/** - * Generates detailed source indexes for this node if possible. - * - * @exception DOMException if unable to generate detailed source indexes - * for this node - */ -protected void becomeDetailed() throws DOMException { - if (!isDetailed()) { - DOMNode detailed= getDetailedNode(); - if (detailed == null) { - throw new DOMException(Util.bind("dom.cannotDetail")); //$NON-NLS-1$ + + /** + * Returns true if this node is allowed to have children, otherwise false. + * + *

                                                      + * Default implementation of IDOMNode interface method + * returns false; this method must be overridden by subclasses that + * implement nodes that allow children. + * + * @see IDOMNode#canHaveChildren() + */ + public boolean canHaveChildren() { + return false; + } + + /** + * @see IDOMNode#clone() + */ + public Object clone() { + + // create a new buffer with all my contents and children contents + int length = 0; + char[] buffer = null; + int offset = fSourceRange[0]; + + if (offset >= 0) { + length = fSourceRange[1] - offset + 1; + buffer = new char[length]; + System.arraycopy(fDocument, offset, buffer, 0, length); } - if (detailed != this) { - shareContents(detailed); + DOMNode clone = newDOMNode(); + clone.shareContents(this); + clone.fDocument = buffer; + + if (offset > 0) { + clone.offset(0 - offset); } - } -} -/** - * Returns true if this node is allowed to have children, otherwise false. - * - *

                                                      Default implementation of IDOMNode interface method returns false; this - * method must be overridden by subclasses that implement nodes that allow - * children. - * - * @see IDOMNode#canHaveChildren() - */ -public boolean canHaveChildren() { - return false; -} -/** - * @see IDOMNode#clone() - */ -public Object clone() { - - // create a new buffer with all my contents and children contents - int length= 0; - char[] buffer= null; - int offset= fSourceRange[0]; - - if (offset >= 0) { - length= fSourceRange[1] - offset + 1; - buffer= new char[length]; - System.arraycopy(fDocument, offset, buffer, 0, length); - } - DOMNode clone= newDOMNode(); - clone.shareContents(this); - clone.fDocument = buffer; - - if (offset > 0) { - clone.offset(0 - offset); - } - - // clone my children - if (canHaveChildren()) { - Enumeration children= getChildren(); - while (children.hasMoreElements()) { - DOMNode child= (DOMNode)children.nextElement(); - if (child.fDocument == fDocument) { - DOMNode childClone= child.cloneSharingDocument(buffer, offset); - clone.basicAddChild(childClone); - } else { - DOMNode childClone= (DOMNode)child.clone(); - clone.addChild(childClone); + + // clone my children + if (canHaveChildren()) { + Enumeration children = getChildren(); + while (children.hasMoreElements()) { + DOMNode child = (DOMNode) children.nextElement(); + if (child.fDocument == fDocument) { + DOMNode childClone = child.cloneSharingDocument(buffer, + offset); + clone.basicAddChild(childClone); + } else { + DOMNode childClone = (DOMNode) child.clone(); + clone.addChild(childClone); + } + } - } + + return clone; } - - return clone; -} -private DOMNode cloneSharingDocument(char[] document, int rootOffset) { - - DOMNode clone = newDOMNode(); - clone.shareContents(this); - clone.fDocument = document; - if (rootOffset > 0) { - clone.offset(0 - rootOffset); - } - - if (canHaveChildren()) { - Enumeration children = getChildren(); - while (children.hasMoreElements()) { - DOMNode child = (DOMNode) children.nextElement(); - if (child.fDocument == fDocument) { - DOMNode childClone= child.cloneSharingDocument(document, rootOffset); - clone.basicAddChild(childClone); - } else { - DOMNode childClone= (DOMNode)child.clone(); - clone.addChild(childClone); + + private DOMNode cloneSharingDocument(char[] document, int rootOffset) { + + DOMNode clone = newDOMNode(); + clone.shareContents(this); + clone.fDocument = document; + if (rootOffset > 0) { + clone.offset(0 - rootOffset); + } + + if (canHaveChildren()) { + Enumeration children = getChildren(); + while (children.hasMoreElements()) { + DOMNode child = (DOMNode) children.nextElement(); + if (child.fDocument == fDocument) { + DOMNode childClone = child.cloneSharingDocument(document, + rootOffset); + clone.basicAddChild(childClone); + } else { + DOMNode childClone = (DOMNode) child.clone(); + clone.addChild(childClone); + } } } + return clone; } - return clone; -} -/** - * Sets this node's fragmented flag and all ancestor fragmented flags - * to true. This happens when an attribute of this node or a descendant - * node has been altered. When a node is fragmented, its contents must - * be generated from its attributes and original "form" rather than - * from the original contents in the document. - */ -protected void fragment() { - if (!isFragmented()) { - fIsFragmented= true; - if (fParent != null) { - fParent.fragment(); + + /** + * Sets this node's fragmented flag and all ancestor fragmented flags to + * true. This happens when an attribute of this node or a descendant + * node has been altered. When a node is fragmented, its contents must + * be generated from its attributes and original "form" rather than + * from the original contents in the document. + */ + protected void fragment() { + if (!isFragmented()) { + fIsFragmented = true; + if (fParent != null) { + fParent.fragment(); + } } } -} -/** - * @see IDOMNode#getCharacters() - */ -public char[] getCharacters() { - CharArrayBuffer buffer= new CharArrayBuffer(); - appendContents(buffer); - return buffer.getContents(); -} -/** - * @see IDOMNode#getChild(String) - */ -public IDOMNode getChild(String name) { - DOMNode child = fFirstChild; - while (child != null) { - String n = child.getName(); - if (name == null) { - if (n == null) { - return child; + + /** + * @see IDOMNode#getCharacters() + */ + public char[] getCharacters() { + CharArrayBuffer buffer = new CharArrayBuffer(); + appendContents(buffer); + return buffer.getContents(); + } + + /** + * @see IDOMNode#getChild(String) + */ + public IDOMNode getChild(String name) { + DOMNode child = fFirstChild; + while (child != null) { + String n = child.getName(); + if (name == null) { + if (n == null) { + return child; + } + } else { + if (name.equals(n)) { + return child; + } } + child = child.fNextNode; + } + return null; + } + + /** + * @see IDOMNode#getChildren() + */ + public Enumeration getChildren() { + return new SiblingEnumeration(fFirstChild); + } + + /** + * Returns the current contents of this document fragment, or + * null if this node has no contents. + * + *

                                                      + * If this node is fragmented, contents must be generated by using the + * original document and indicies as a form for the current attribute values + * of this node. If this node not fragmented, the contents can be obtained + * from the document. + * + * @see IDOMNode#getContents() + */ + public String getContents() { + CharArrayBuffer buffer = new CharArrayBuffer(); + appendContents(buffer); + return buffer.toString(); + } + + /** + * Returns a new document fragment representing this node with detailed + * source indexes. Subclasses that provide a detailed implementation must + * override this method. + */ + protected DOMNode getDetailedNode() { + return this; + } + + /** + * Returns the document containing this node's original contents. The + * document may be shared by other nodes. + */ + protected char[] getDocument() { + return fDocument; + } + + /** + * Returns the original position of the last character of this node's + * contents in its document. + */ + public int getEndPosition() { + return fSourceRange[1]; + } + + /** + * Returns a factory with which to create new document fragments. + */ + protected IDOMFactory getFactory() { + return new DOMFactory(); + } + + /** + * @see IDOMNode#getFirstChild() + */ + public IDOMNode getFirstChild() { + return fFirstChild; + } + + /** + * Returns the position at which the first child of this node should be + * inserted. + */ + public int getInsertionPosition() { + return fInsertionPosition; + } + + /** + * Returns true if the given mask of this node's state flag + * is turned on, otherwise false. + */ + protected boolean getMask(int mask) { + return (fStateMask & mask) > 0; + } + + /** + * @see IDOMNode#getName() + */ + public String getName() { + return fName; + } + + /** + * Returns the source code to be used for this node's name. + */ + protected char[] getNameContents() { + if (isNameAltered()) { + return fName.toCharArray(); } else { - if (name.equals(n)) { - return child; + if (fName == null || fNameRange[0] < 0) { + return null; + } else { + int length = fNameRange[1] + 1 - fNameRange[0]; + char[] result = new char[length]; + System.arraycopy(fDocument, fNameRange[0], result, 0, length); + return result; } } - child = child.fNextNode; } - return null; -} -/** - * @see IDOMNode#getChildren() - */ -public Enumeration getChildren() { - return new SiblingEnumeration(fFirstChild); -} -/** - * Returns the current contents of this document fragment, - * or null if this node has no contents. - * - *

                                                      If this node is fragmented, contents must be generated by - * using the original document and indicies as a form for the current - * attribute values of this node. If this node not fragmented, the - * contents can be obtained from the document. - * - * @see IDOMNode#getContents() - */ -public String getContents() { - CharArrayBuffer buffer= new CharArrayBuffer(); - appendContents(buffer); - return buffer.toString(); -} -/** - * Returns a new document fragment representing this node with - * detailed source indexes. Subclasses that provide a detailed - * implementation must override this method. - */ -protected DOMNode getDetailedNode() { - return this; -} -/** - * Returns the document containing this node's original contents. - * The document may be shared by other nodes. - */ -protected char[] getDocument() { - return fDocument; -} -/** - * Returns the original position of the last character of this - * node's contents in its document. - */ -public int getEndPosition() { - return fSourceRange[1]; -} -/** - * Returns a factory with which to create new document fragments. - */ -protected IDOMFactory getFactory() { - return new DOMFactory(); -} -/** - * @see IDOMNode#getFirstChild() - */ -public IDOMNode getFirstChild() { - return fFirstChild; -} -/** - * Returns the position at which the first child of this node should be inserted. - */ -public int getInsertionPosition() { - return fInsertionPosition; -} -/** - * Returns true if the given mask of this node's state flag - * is turned on, otherwise false. - */ -protected boolean getMask(int mask) { - return (fStateMask & mask) > 0; -} -/** - * @see IDOMNode#getName() - */ -public String getName() { - return fName; -} -/** - * Returns the source code to be used for this node's name. - */ -protected char[] getNameContents() { - if (isNameAltered()) { - return fName.toCharArray(); - } else { - if (fName == null || fNameRange[0] < 0) { - return null; + + /** + * @see IDOMNode#getNextNode() + */ + public IDOMNode getNextNode() { + return fNextNode; + } + + /** + * @see IDOMNode#getParent() + */ + public IDOMNode getParent() { + return fParent; + } + + /** + * Answers a source position which corresponds to the end of the parent + * element's declaration. + */ + protected int getParentEndDeclaration() { + IDOMNode parent = getParent(); + if (parent == null) { + return 0; } else { - int length = fNameRange[1] + 1 - fNameRange[0]; - char[] result = new char[length]; - System.arraycopy(fDocument, fNameRange[0], result, 0, length); - return result; + if (parent instanceof IDOMCompilationUnit) { + return 0; + } else { + return ((DOMType) parent).getOpenBodyEnd(); + } } } -} -/** - * @see IDOMNode#getNextNode() - */ -public IDOMNode getNextNode() { - return fNextNode; -} -/** - * @see IDOMNode#getParent() - */ -public IDOMNode getParent() { - return fParent; -} -/** - * Answers a source position which corresponds to the end of the parent - * element's declaration. - */ -protected int getParentEndDeclaration() { - IDOMNode parent = getParent(); - if (parent == null) { - return 0; - } else { - if (parent instanceof IDOMCompilationUnit) { - return 0; + + /** + * @see IDOMNode#getPreviousNode() + */ + public IDOMNode getPreviousNode() { + return fPreviousNode; + } + + /** + * Returns the root node of this document fragment. + */ + protected IDOMNode getRoot() { + if (fParent == null) { + return this; } else { - return ((DOMType)parent).getOpenBodyEnd(); + return fParent.getRoot(); } } -} -/** - * @see IDOMNode#getPreviousNode() - */ -public IDOMNode getPreviousNode() { - return fPreviousNode; -} -/** - * Returns the root node of this document fragment. - */ -protected IDOMNode getRoot() { - if (fParent == null) { - return this; - } else { - return fParent.getRoot(); + + /** + * Returns the original position of the first character of this node's + * contents in its document. + */ + public int getStartPosition() { + return fSourceRange[0]; } -} -/** - * Returns the original position of the first character of this - * node's contents in its document. - */ -public int getStartPosition() { - return fSourceRange[0]; -} -/** - * @see IDOMNode#insertSibling(IDOMNode) - */ -public void insertSibling(IDOMNode sibling) throws IllegalArgumentException, DOMException { - // verify sibling may be added - if (sibling == null) { - throw new IllegalArgumentException(Util.bind("dom.addNullSibling")); //$NON-NLS-1$ + + /** + * @see IDOMNode#insertSibling(IDOMNode) + */ + public void insertSibling(IDOMNode sibling) + throws IllegalArgumentException, DOMException { + // verify sibling may be added + if (sibling == null) { + throw new IllegalArgumentException(Util.bind("dom.addNullSibling")); //$NON-NLS-1$ + } + if (fParent == null) { + throw new DOMException(Util.bind("dom.addSiblingBeforeRoot")); //$NON-NLS-1$ + } + if (!fParent.isAllowableChild(sibling)) { + throw new DOMException(Util.bind("dom.addIncompatibleSibling")); //$NON-NLS-1$ + } + if (sibling.getParent() != null) { + throw new DOMException(Util.bind("dom.addSiblingWithParent")); //$NON-NLS-1$ + } + /* + * NOTE: To test if the sibling is an ancestor of this node, we need + * only test if the root of this node is the child (the sibling is + * already a root since we have just guaranteed it has no parent). + */ + if (sibling == getRoot()) { + throw new DOMException(Util.bind("dom.addAncestorAsSibling")); //$NON-NLS-1$ + } + + DOMNode node = (DOMNode) sibling; + + // if the sibling is not already part of this document, localize its + // contents + // before inserting it into the tree + if (node.getDocument() != getDocument()) { + node.localizeContents(); + } + + // insert the node + if (fPreviousNode == null) { + fParent.fFirstChild = node; + } else { + fPreviousNode.fNextNode = node; + } + node.fParent = fParent; + node.fPreviousNode = fPreviousNode; + node.fNextNode = this; + fPreviousNode = node; + + // if the node is a constructor, it must also be fragmented to update + // the constructor's name + if (node.getNodeType() == IDOMNode.METHOD + && ((IDOMMethod) node).isConstructor()) { + node.fragment(); + } else { + fParent.fragment(); + } } - if (fParent == null) { - throw new DOMException(Util.bind("dom.addSiblingBeforeRoot")); //$NON-NLS-1$ + + /** + * @see IDOMNode + */ + public boolean isAllowableChild(IDOMNode node) { + return false; } - if (!fParent.isAllowableChild(sibling)) { - throw new DOMException(Util.bind("dom.addIncompatibleSibling")); //$NON-NLS-1$ + + /** + * Returns true if the contents of this node are from the + * same document as the given node, the contents of this node immediately + * follow the contents of the given node, and neither this node or the given + * node are fragmented - otherwise false. + */ + protected boolean isContentMergableWith(DOMNode node) { + return !node.isFragmented() && !isFragmented() + && node.getDocument() == getDocument() + && node.getEndPosition() + 1 == getStartPosition(); } - if (sibling.getParent() != null) { - throw new DOMException(Util.bind("dom.addSiblingWithParent")); //$NON-NLS-1$ + + /** + * Returns true if this node has detailed source index + * information, or false if this node has limited source + * index information. To perform some manipulations, detailed indexes are + * required. + */ + protected boolean isDetailed() { + return getMask(MASK_DETAILED_SOURCE_INDEXES); } - /* NOTE: To test if the sibling is an ancestor of this node, we - * need only test if the root of this node is the child (the sibling - * is already a root since we have just guaranteed it has no parent). + + /** + * Returns true if this node's or a descendant node's + * contents have been altered since this node was created. This indicates + * that the contents of this node are no longer consistent with the contents + * of this node's document. */ - if (sibling == getRoot()) { - throw new DOMException(Util.bind("dom.addAncestorAsSibling")); //$NON-NLS-1$ + protected boolean isFragmented() { + return fIsFragmented; } - DOMNode node= (DOMNode)sibling; - - // if the sibling is not already part of this document, localize its contents - // before inserting it into the tree - if (node.getDocument() != getDocument()) { - node.localizeContents(); + /** + * Returns true if this noed's name has been altered from the + * original document contents. + */ + protected boolean isNameAltered() { + return getMask(MASK_NAME_ALTERED); } - // insert the node - if (fPreviousNode == null) { - fParent.fFirstChild= node; - } else { - fPreviousNode.fNextNode= node; + /** + * @see IDOMNode#isSignatureEqual(IDOMNode). + * + *

                                                      + * By default, the signatures of two nodes are equal if their type and names + * are equal. Node types that have other requirements for equality must + * override this method. + */ + public boolean isSignatureEqual(IDOMNode node) { + return getNodeType() == node.getNodeType() + && getName().equals(node.getName()); } - node.fParent= fParent; - node.fPreviousNode= fPreviousNode; - node.fNextNode= this; - fPreviousNode= node; - // if the node is a constructor, it must also be fragmented to update the constructor's name - if (node.getNodeType() == IDOMNode.METHOD && ((IDOMMethod)node).isConstructor()) { - node.fragment(); - } else { - fParent.fragment(); + /** + * Localizes the contents of this node and all descendant nodes, such that + * this node is no longer dependent on its original document in order to + * generate its contents. This node and all descendant nodes become + * unfragmented and share a new document. + */ + protected void localizeContents() { + + DOMNode clone = (DOMNode) clone(); + shareContents(clone); + } -} -/** - * @see IDOMNode - */ -public boolean isAllowableChild(IDOMNode node) { - return false; -} -/** - * Returns true if the contents of this node are from the same document as - * the given node, the contents of this node immediately follow the contents - * of the given node, and neither this node or the given node are fragmented - - * otherwise false. - */ -protected boolean isContentMergableWith(DOMNode node) { - return !node.isFragmented() && !isFragmented() && node.getDocument() == getDocument() && - node.getEndPosition() + 1 == getStartPosition(); -} -/** - * Returns true if this node has detailed source index information, - * or false if this node has limited source index information. To - * perform some manipulations, detailed indexes are required. - */ -protected boolean isDetailed() { - return getMask(MASK_DETAILED_SOURCE_INDEXES); -} -/** - * Returns true if this node's or a descendant node's contents - * have been altered since this node was created. This indicates - * that the contents of this node are no longer consistent with - * the contents of this node's document. - */ -protected boolean isFragmented() { - return fIsFragmented; -} -/** - * Returns true if this noed's name has been altered - * from the original document contents. - */ -protected boolean isNameAltered() { - return getMask(MASK_NAME_ALTERED); -} -/** - * @see IDOMNode#isSignatureEqual(IDOMNode). - * - *

                                                      By default, the signatures of two nodes are equal if their - * type and names are equal. Node types that have other requirements - * for equality must override this method. - */ -public boolean isSignatureEqual(IDOMNode node) { - return getNodeType() == node.getNodeType() && getName().equals(node.getName()); -} -/** - * Localizes the contents of this node and all descendant nodes, - * such that this node is no longer dependent on its original - * document in order to generate its contents. This node and all - * descendant nodes become unfragmented and share a new - * document. - */ -protected void localizeContents() { - DOMNode clone= (DOMNode)clone(); - shareContents(clone); + /** + * Returns a new empty DOMNode for this instance. + */ + protected abstract DOMNode newDOMNode(); -} -/** - * Returns a new empty DOMNode for this instance. - */ -protected abstract DOMNode newDOMNode(); -/** - * Normalizes this DOMNode's source positions to include whitespace preceeding - * the node on the line on which the node starts, and all whitespace after the node up to - * the next node's start - */ -void normalize(ILineStartFinder finder) { - if (getPreviousNode() == null) - normalizeStartPosition(getParentEndDeclaration(), finder); + /** + * Normalizes this DOMNode's source positions to include + * whitespace preceeding the node on the line on which the node starts, and + * all whitespace after the node up to the next node's start + */ + void normalize(ILineStartFinder finder) { + if (getPreviousNode() == null) + normalizeStartPosition(getParentEndDeclaration(), finder); + + // Set the children's position + if (canHaveChildren()) { + Enumeration children = getChildren(); + while (children.hasMoreElements()) + ((DOMNode) children.nextElement()).normalize(finder); + } - // Set the children's position - if (canHaveChildren()) { - Enumeration children = getChildren(); - while(children.hasMoreElements()) - ((DOMNode)children.nextElement()).normalize(finder); + normalizeEndPosition(finder, (DOMNode) getNextNode()); } - normalizeEndPosition(finder, (DOMNode)getNextNode()); -} -/** - * Normalizes this DOMNode's end position. - */ -void normalizeEndPosition(ILineStartFinder finder, DOMNode next) { - if (next == null) { - // this node's end position includes all of the characters up - // to the end of the enclosing node - DOMNode parent = (DOMNode) getParent(); - if (parent == null || parent instanceof DOMCompilationUnit) { - setSourceRangeEnd(fDocument.length - 1); + /** + * Normalizes this DOMNode's end position. + */ + void normalizeEndPosition(ILineStartFinder finder, DOMNode next) { + if (next == null) { + // this node's end position includes all of the characters up + // to the end of the enclosing node + DOMNode parent = (DOMNode) getParent(); + if (parent == null || parent instanceof DOMCompilationUnit) { + setSourceRangeEnd(fDocument.length - 1); + } else { + // parent is a type + int temp = ((DOMType) parent).getCloseBodyPosition() - 1; + setSourceRangeEnd(temp); + fInsertionPosition = Math.max(finder.getLineStart(temp + 1), + getEndPosition()); + } } else { - // parent is a type - int temp = ((DOMType)parent).getCloseBodyPosition() - 1; - setSourceRangeEnd(temp); - fInsertionPosition = Math.max(finder.getLineStart(temp + 1), getEndPosition()); - } - } else { - // this node's end position is just before the start of the next node - int temp = next.getStartPosition() - 1; - fInsertionPosition = Math.max(finder.getLineStart(temp + 1), getEndPosition()); - next.normalizeStartPosition(getEndPosition(), finder); - setSourceRangeEnd(next.getStartPosition() - 1); - } -} -/** - * Normalizes this DOMNode's start position. - */ -void normalizeStartPosition(int previousEnd, ILineStartFinder finder) { - int nodeStart = getStartPosition(); - int lineStart = finder.getLineStart(nodeStart); - if (nodeStart > lineStart && (lineStart > previousEnd || (previousEnd == 0 && lineStart == 0))) - setStartPosition(lineStart); -} -/** - * Offsets all the source indexes in this node by the given amount. - */ -protected void offset(int offset) { - offsetRange(fNameRange, offset); - offsetRange(fSourceRange, offset); -} -/** - * Offsets the source range by the given amount - */ -protected void offsetRange(int[] range, int offset) { - for (int i= 0; i < range.length; i++) { - range[i]+=offset; - if (range[i] < 0) { - range[i]= -1; + // this node's end position is just before the start of the next + // node + int temp = next.getStartPosition() - 1; + fInsertionPosition = Math.max(finder.getLineStart(temp + 1), + getEndPosition()); + next.normalizeStartPosition(getEndPosition(), finder); + setSourceRangeEnd(next.getStartPosition() - 1); } } -} -/** - * Returns a copy of the given range. - */ -protected int[] rangeCopy(int[] range) { - int[] copy= new int[range.length]; - for (int i= 0; i < range.length; i++) { - copy[i]= range[i]; + + /** + * Normalizes this DOMNode's start position. + */ + void normalizeStartPosition(int previousEnd, ILineStartFinder finder) { + int nodeStart = getStartPosition(); + int lineStart = finder.getLineStart(nodeStart); + if (nodeStart > lineStart + && (lineStart > previousEnd || (previousEnd == 0 && lineStart == 0))) + setStartPosition(lineStart); } - return copy; -} -/** - * Separates this node from its parent and siblings, maintaining any ties that - * this node has to the underlying document fragment. - * - *

                                                      When a child is removed, its parent is fragmented such that it properly - * generates its contents. - * - * @see IDOMNode#remove() - */ -public void remove() { - if (fParent != null) { - fParent.fragment(); + /** + * Offsets all the source indexes in this node by the given amount. + */ + protected void offset(int offset) { + offsetRange(fNameRange, offset); + offsetRange(fSourceRange, offset); } - - // link siblings - if (fNextNode != null) { - fNextNode.fPreviousNode= fPreviousNode; + + /** + * Offsets the source range by the given amount + */ + protected void offsetRange(int[] range, int offset) { + for (int i = 0; i < range.length; i++) { + range[i] += offset; + if (range[i] < 0) { + range[i] = -1; + } + } } - if (fPreviousNode != null) { - fPreviousNode.fNextNode= fNextNode; + + /** + * Returns a copy of the given range. + */ + protected int[] rangeCopy(int[] range) { + int[] copy = new int[range.length]; + for (int i = 0; i < range.length; i++) { + copy[i] = range[i]; + } + return copy; } - // fix parent's pointers - if (fParent != null) { - if (fParent.fFirstChild == this) { - fParent.fFirstChild= fNextNode; + + /** + * Separates this node from its parent and siblings, maintaining any ties + * that this node has to the underlying document fragment. + * + *

                                                      + * When a child is removed, its parent is fragmented such that it properly + * generates its contents. + * + * @see IDOMNode#remove() + */ + public void remove() { + + if (fParent != null) { + fParent.fragment(); + } + + // link siblings + if (fNextNode != null) { + fNextNode.fPreviousNode = fPreviousNode; + } + if (fPreviousNode != null) { + fPreviousNode.fNextNode = fNextNode; } - if (fParent.fLastChild == this) { - fParent.fLastChild= fPreviousNode; + // fix parent's pointers + if (fParent != null) { + if (fParent.fFirstChild == this) { + fParent.fFirstChild = fNextNode; + } + if (fParent.fLastChild == this) { + fParent.fLastChild = fPreviousNode; + } } + // remove myself + fParent = null; + fNextNode = null; + fPreviousNode = null; } - // remove myself - fParent= null; - fNextNode= null; - fPreviousNode= null; -} -/** - * Sets the specified mask of this node's state mask on or off - * based on the boolean value - true -> on, false -> off. - */ -protected void setMask(int mask, boolean on) { - if (on) { - fStateMask |= mask; - } else { - fStateMask &= ~mask; + + /** + * Sets the specified mask of this node's state mask on or off based on the + * boolean value - true -> on, false -> off. + */ + protected void setMask(int mask, boolean on) { + if (on) { + fStateMask |= mask; + } else { + fStateMask &= ~mask; + } } -} -/** - * @see IDOMNode#setName - */ -public void setName(String name) { - fName= name; - setNameAltered(true); - fragment(); -} -/** - * Sets the state of this node as having - * its name attribute altered from the original - * document contents. - */ -protected void setNameAltered(boolean altered) { - setMask(MASK_NAME_ALTERED, altered); -} -/** - * Sets the original position of the last character of this node's contents - * in its document. This method is only used during DOM creation while - * normalizing the source range of each node. - */ -protected void setSourceRangeEnd(int end) { - fSourceRange[1]= end; -} -/** - * Sets the original position of the first character of this node's contents - * in its document. This method is only used during DOM creation while - * normalizing the source range of each node. - */ -protected void setStartPosition(int start) { - fSourceRange[0]= start; -} -/** - * Sets the contents of this node and descendant nodes to be the - * (identical) contents of the given node and its descendants. This - * does not effect this node's parent and sibling configuration, - * only the contents of this node. This is used only to localize - * the contents of this node. - */ -protected void shareContents(DOMNode node) { - fDocument= node.fDocument; - fIsFragmented= node.fIsFragmented; - fName= node.fName; - fNameRange= rangeCopy(node.fNameRange); - fSourceRange= rangeCopy(node.fSourceRange); - fStateMask= node.fStateMask; - - - if (canHaveChildren()) { - Enumeration myChildren= getChildren(); - Enumeration otherChildren= node.getChildren(); - DOMNode myChild, otherChild; - while (myChildren.hasMoreElements()) { - myChild= (DOMNode)myChildren.nextElement(); - otherChild= (DOMNode)otherChildren.nextElement(); - myChild.shareContents(otherChild); + + /** + * @see IDOMNode#setName + */ + public void setName(String name) { + fName = name; + setNameAltered(true); + fragment(); + } + + /** + * Sets the state of this node as having its name attribute altered from the + * original document contents. + */ + protected void setNameAltered(boolean altered) { + setMask(MASK_NAME_ALTERED, altered); + } + + /** + * Sets the original position of the last character of this node's contents + * in its document. This method is only used during DOM creation while + * normalizing the source range of each node. + */ + protected void setSourceRangeEnd(int end) { + fSourceRange[1] = end; + } + + /** + * Sets the original position of the first character of this node's contents + * in its document. This method is only used during DOM creation while + * normalizing the source range of each node. + */ + protected void setStartPosition(int start) { + fSourceRange[0] = start; + } + + /** + * Sets the contents of this node and descendant nodes to be the (identical) + * contents of the given node and its descendants. This does not effect this + * node's parent and sibling configuration, only the contents of this node. + * This is used only to localize the contents of this node. + */ + protected void shareContents(DOMNode node) { + fDocument = node.fDocument; + fIsFragmented = node.fIsFragmented; + fName = node.fName; + fNameRange = rangeCopy(node.fNameRange); + fSourceRange = rangeCopy(node.fSourceRange); + fStateMask = node.fStateMask; + + if (canHaveChildren()) { + Enumeration myChildren = getChildren(); + Enumeration otherChildren = node.getChildren(); + DOMNode myChild, otherChild; + while (myChildren.hasMoreElements()) { + myChild = (DOMNode) myChildren.nextElement(); + otherChild = (DOMNode) otherChildren.nextElement(); + myChild.shareContents(otherChild); + } } } -} -/** - * Returns a String representing this node - for Debug purposes only. - */ -public abstract String toString(); + + /** + * Returns a String representing this node - for Debug + * purposes only. + */ + public abstract String toString(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMPackage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMPackage.java index 0b80fc7..53e5d24 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMPackage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMPackage.java @@ -19,123 +19,141 @@ import net.sourceforge.phpdt.internal.core.util.CharArrayBuffer; /** * DOMPackage provides an implementation of IDOMPackage. - * + * * @see IDOMPackage * @see DOMNode */ class DOMPackage extends DOMNode implements IDOMPackage { -/** - * Creates an empty PACKAGE node. - */ -DOMPackage() { - setMask(MASK_DETAILED_SOURCE_INDEXES, true); -} -/** - * Creates a new simple PACKAGE document fragment on the given range of the document. - * - * @param document - the document containing this node's original contents - * @param sourceRange - a two element array of integers describing the - * entire inclusive source range of this node within its document. - * Contents start on and include the character at the first position. - * Contents end on and include the character at the last position. - * An array of -1's indicates this node's contents do not exist - * in the document. - * @param name - the identifier portion of the name of this node, or - * null if this node does not have a name - */ -DOMPackage(char[] document, int[] sourceRange, String name) { - super(document, sourceRange, name, new int[] {-1, -1}); - setMask(MASK_DETAILED_SOURCE_INDEXES, false); -} -/** - * Creates a new detailed PACKAGE document fragment on the given range of the document. - * - * @param document - the document containing this node's original contents - * @param sourceRange - a two element array of integers describing the - * entire inclusive source range of this node within its document. - * Contents start on and include the character at the first position. - * Contents end on and include the character at the last position. - * An array of -1's indicates this node's contents do not exist - * in the document. - * @param name - the identifier portion of the name of this node, or - * null if this node does not have a name - * @param nameRange - a two element array of integers describing the - * entire inclusive source range of this node's name within its document, - * including any array qualifiers that might immediately follow the name - * or -1's if this node does not have a name. - */ -DOMPackage(char[] document, int[] sourceRange, String name, int[] nameRange) { - super(document, sourceRange, name, nameRange); - setMask(MASK_DETAILED_SOURCE_INDEXES, true); -} -/** - * @see DOMNode#appendFragmentedContents(CharArrayBuffer) - */ -protected void appendFragmentedContents(CharArrayBuffer buffer) { - if (fNameRange[0] < 0) { - buffer - .append("package ") //$NON-NLS-1$ - .append(fName) - .append(';') - .append(Util.LINE_SEPARATOR) - .append(Util.LINE_SEPARATOR); - } else { - buffer - .append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0]) - .append(fName) - .append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]); + /** + * Creates an empty PACKAGE node. + */ + DOMPackage() { + setMask(MASK_DETAILED_SOURCE_INDEXES, true); } -} -/** - * @see IDOMNode#getContents() - */ -public String getContents() { - if (fName == null) { - return null; - } else { - return super.getContents(); + + /** + * Creates a new simple PACKAGE document fragment on the given range of the + * document. + * + * @param document - + * the document containing this node's original contents + * @param sourceRange - + * a two element array of integers describing the entire + * inclusive source range of this node within its document. + * Contents start on and include the character at the first + * position. Contents end on and include the character at the + * last position. An array of -1's indicates this node's contents + * do not exist in the document. + * @param name - + * the identifier portion of the name of this node, or + * null if this node does not have a name + */ + DOMPackage(char[] document, int[] sourceRange, String name) { + super(document, sourceRange, name, new int[] { -1, -1 }); + setMask(MASK_DETAILED_SOURCE_INDEXES, false); } -} -/** - * @see DOMNode#getDetailedNode() - */ -//protected DOMNode getDetailedNode() { -// return (DOMNode)getFactory().createPackage(getContents()); -//} -/** - * @see IDOMNode#getJavaElement - */ -public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { - if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) { - return ((ICompilationUnit)parent).getPackageDeclaration(getName()); - } else { - throw new IllegalArgumentException(Util.bind("element.illegalParent")); //$NON-NLS-1$ + + /** + * Creates a new detailed PACKAGE document fragment on the given range of + * the document. + * + * @param document - + * the document containing this node's original contents + * @param sourceRange - + * a two element array of integers describing the entire + * inclusive source range of this node within its document. + * Contents start on and include the character at the first + * position. Contents end on and include the character at the + * last position. An array of -1's indicates this node's contents + * do not exist in the document. + * @param name - + * the identifier portion of the name of this node, or + * null if this node does not have a name + * @param nameRange - + * a two element array of integers describing the entire + * inclusive source range of this node's name within its + * document, including any array qualifiers that might + * immediately follow the name or -1's if this node does not have + * a name. + */ + DOMPackage(char[] document, int[] sourceRange, String name, int[] nameRange) { + super(document, sourceRange, name, nameRange); + setMask(MASK_DETAILED_SOURCE_INDEXES, true); + } + + /** + * @see DOMNode#appendFragmentedContents(CharArrayBuffer) + */ + protected void appendFragmentedContents(CharArrayBuffer buffer) { + if (fNameRange[0] < 0) { + buffer.append("package ") //$NON-NLS-1$ + .append(fName).append(';').append(Util.LINE_SEPARATOR) + .append(Util.LINE_SEPARATOR); + } else { + buffer.append(fDocument, fSourceRange[0], + fNameRange[0] - fSourceRange[0]).append(fName).append( + fDocument, fNameRange[1] + 1, + fSourceRange[1] - fNameRange[1]); + } + } + + /** + * @see IDOMNode#getContents() + */ + public String getContents() { + if (fName == null) { + return null; + } else { + return super.getContents(); + } + } + + /** + * @see DOMNode#getDetailedNode() + */ + // protected DOMNode getDetailedNode() { + // return (DOMNode)getFactory().createPackage(getContents()); + // } + /** + * @see IDOMNode#getJavaElement + */ + public IJavaElement getJavaElement(IJavaElement parent) + throws IllegalArgumentException { + if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) { + return ((ICompilationUnit) parent).getPackageDeclaration(getName()); + } else { + throw new IllegalArgumentException(Util + .bind("element.illegalParent")); //$NON-NLS-1$ + } + } + + /** + * @see IDOMNode#getNodeType() + */ + public int getNodeType() { + return IDOMNode.PACKAGE; + } + + /** + * @see DOMNode + */ + protected DOMNode newDOMNode() { + return new DOMPackage(); + } + + /** + * @see IDOMNode#setName + */ + public void setName(String name) { + becomeDetailed(); + super.setName(name); + } + + /** + * @see IDOMNode#toString() + */ + public String toString() { + return "PACKAGE: " + getName(); //$NON-NLS-1$ } -} -/** - * @see IDOMNode#getNodeType() - */ -public int getNodeType() { - return IDOMNode.PACKAGE; -} -/** - * @see DOMNode - */ -protected DOMNode newDOMNode() { - return new DOMPackage(); -} -/** - * @see IDOMNode#setName - */ -public void setName(String name) { - becomeDetailed(); - super.setName(name); -} -/** - * @see IDOMNode#toString() - */ -public String toString() { - return "PACKAGE: " + getName(); //$NON-NLS-1$ -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMType.java index 710eb59..cc587d8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMType.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMType.java @@ -27,695 +27,782 @@ import net.sourceforge.phpdt.internal.core.util.CharArrayOps; /** * DOMType provides an implementation of IDOMType. - * + * * @see IDOMType * @see DOMNode */ - -/* package */ class DOMType extends DOMMember implements IDOMType { + +/* package */class DOMType extends DOMMember implements IDOMType { /** - * The 'class' or 'interface' keyword if altered - * from the documents contents, otherwise null. + * The 'class' or 'interface' keyword if altered from the documents + * contents, otherwise null. */ protected String fTypeKeyword; /** - * The original inclusive source range of the 'class' - * or 'interface' keyword in the document. + * The original inclusive source range of the 'class' or 'interface' keyword + * in the document. */ - protected int[] fTypeRange; + protected int[] fTypeRange; /** - * The superclass name for the class declaration - * if altered from the document's contents, otherwise - * null. Also null when this - * type represents an interface. + * The superclass name for the class declaration if altered from the + * document's contents, otherwise null. Also + * null when this type represents an interface. */ protected String fSuperclass; /** - * The original inclusive source range of the superclass - * name in the document, or -1's of no superclass was - * specified in the document. + * The original inclusive source range of the superclass name in the + * document, or -1's of no superclass was specified in the document. */ - protected int[] fSuperclassRange; - + protected int[] fSuperclassRange; /** - * The original inclusive souce range of the 'extends' keyword - * in the document, including surrounding whitespace, or -1's if - * the keyword was not present in the document. + * The original inclusive souce range of the 'extends' keyword in the + * document, including surrounding whitespace, or -1's if the keyword was + * not present in the document. */ - protected int[] fExtendsRange; + protected int[] fExtendsRange; /** - * The original inclusive souce range of the 'implements' keyword - * in the document, including surrounding whitespace, or -1's if - * the keyword was not present in the document. - */ - protected int[] fImplementsRange; + * The original inclusive souce range of the 'implements' keyword in the + * document, including surrounding whitespace, or -1's if the keyword was + * not present in the document. + */ + protected int[] fImplementsRange; /** - * The comma delimited list of interfaces this type implements - * or extends, if altered from the document's contents, otherwise - * null. Also null if this type does - * not implement or extend any interfaces. + * The comma delimited list of interfaces this type implements or extends, + * if altered from the document's contents, otherwise null. + * Also null if this type does not implement or extend any + * interfaces. */ protected char[] fInterfaces; /** - * The original inclusive source range of the list of interfaces this - * type implements or extends, not including any surrouding whitespace. - * If the document did not specify interfaces, this array contains -1's. + * The original inclusive source range of the list of interfaces this type + * implements or extends, not including any surrouding whitespace. If the + * document did not specify interfaces, this array contains -1's. */ - protected int[] fInterfacesRange; - - + protected int[] fInterfacesRange; - /** - * The original source range of the first character following the - * type name superclass name, or interface list, up to and including - * the first character before the first type member. - */ - protected int[] fOpenBodyRange; + /** + * The original source range of the first character following the type name + * superclass name, or interface list, up to and including the first + * character before the first type member. + */ + protected int[] fOpenBodyRange; - /** + /** * The original source range of the first new line or non whitespace - * character preceding the close brace of the type's body, up to the - * and including the first character before the next node (if there are - * no following nodes, the range ends at the position of the last - * character in the document). - */ - protected int[] fCloseBodyRange; + * character preceding the close brace of the type's body, up to the and + * including the first character before the next node (if there are no + * following nodes, the range ends at the position of the last character in + * the document). + */ + protected int[] fCloseBodyRange; + + /** + * A list of interfaces this type extends or implements. null + * when this type does not extend or implement any interfaces. + */ + protected String[] fSuperInterfaces = new String[0]; /** - * A list of interfaces this type extends or implements. - * null when this type does not extend - * or implement any interfaces. + * This position is the position of the end of the last line separator + * before the closing brace starting position of the receiver. */ - protected String[] fSuperInterfaces= new String[0]; - + // protected int fInsertionPosition; /** - * This position is the position of the end of the last line separator before the closing brace starting - * position of the receiver. + * Constructs an empty type node. */ -// protected int fInsertionPosition; + DOMType() { -/** - * Constructs an empty type node. - */ -DOMType() { + } -} -/** - * Creates a new detailed TYPE document fragment on the given range of the document. - * - * @param document - the document containing this node's original contents - * @param sourceRange - a two element array of integers describing the - * entire inclusive source range of this node within its document. - * Contents start on and include the character at the first position. - * Contents end on and include the character at the last position. - * An array of -1's indicates this node's contents do not exist - * in the document. - * @param name - the identifier portion of the name of this node, or - * null if this node does not have a name - * @param nameRange - a two element array of integers describing the - * entire inclusive source range of this node's name within its document, - * including any array qualifiers that might immediately follow the name - * or -1's if this node does not have a name. - * @param commentRange - a two element array describing the comments that precede - * the member declaration. The first matches the start of this node's - * sourceRange, and the second is the new-line or first non-whitespace - * character following the last comment. If no comments are present, - * this array contains two -1's. - * @param flags - an integer representing the modifiers for this member. The - * integer can be analyzed with net.sourceforge.phpdt.core.Flags - * @param modifierRange - a two element array describing the location of - * modifiers for this member within its source range. The first integer - * is the first character of the first modifier for this member, and - * the second integer is the last whitespace character preceeding the - * next part of this member declaration. If there are no modifiers present - * in this node's source code (that is, package default visibility), this array - * contains two -1's. - * @param typeRange - a two element array describing the location of the 'class' - * or 'interface' keyword in the type declaration - first and last character - * positions. - * @param superclassRange - a two element array describing the location of the - * superclass name in the type declaration - first and last character - * positions or two -1's if a superclass is not present in the document. - * @param extendsRange - a two element array describing the location of the - * 'extends' keyword in the type declaration, including any surrounding - * whitespace, or -1's if the 'extends' keyword is not present in the document. - * @param implementsList - an array of names of the interfaces this type implements - * or extends, or null if this type does not implement or extend - * any interfaces. - * @param implementsRange - a two element array describing the location of the - * comment delimited list of interfaces this type implements or extends, - * not including any surrounding whitespace, or -1's if no interface list - * is present in the document. - * @param implementsKeywordRange - a two element array describing the location of the - * 'implements' keyword, including any surrounding whitespace, or -1's if no - * 'implements' keyword is present in the document. - * @param openBodyRange - a two element array describing the location of the - * open brace of the type's body and whitespace following the type declaration - * and preceeding the first member in the type. - * @param closeBodyRange - a two element array describing the source range of the - * first new line or non whitespace character preceeding the close brace of the - * type's body, up to the close brace - * @param isClass - true is the type is a class, false if it is an interface - */ -DOMType(char[] document, int[] sourceRange, String name, int[] nameRange, int[] commentRange, int flags, int[] modifierRange, int[] typeRange, int[] superclassRange, int[] extendsRange, String[] implementsList, int[] implementsRange, int[] implementsKeywordRange, int[] openBodyRange, int[] closeBodyRange, boolean isClass) { - super(document, sourceRange, name, nameRange, commentRange, flags, modifierRange); - - fTypeRange= typeRange; - setMask(MASK_TYPE_IS_CLASS, isClass); - - fExtendsRange= extendsRange; - fImplementsRange= implementsKeywordRange; - fSuperclassRange= superclassRange; - fInterfacesRange= implementsRange; - fCloseBodyRange= closeBodyRange; - setMask(MASK_TYPE_HAS_SUPERCLASS, superclassRange[0] > 0); - setMask(MASK_TYPE_HAS_INTERFACES, implementsList != null); - fSuperInterfaces= implementsList; - fOpenBodyRange= openBodyRange; - fCloseBodyRange= closeBodyRange; - setMask(MASK_DETAILED_SOURCE_INDEXES, true); + /** + * Creates a new detailed TYPE document fragment on the given range of the + * document. + * + * @param document - + * the document containing this node's original contents + * @param sourceRange - + * a two element array of integers describing the entire + * inclusive source range of this node within its document. + * Contents start on and include the character at the first + * position. Contents end on and include the character at the + * last position. An array of -1's indicates this node's contents + * do not exist in the document. + * @param name - + * the identifier portion of the name of this node, or + * null if this node does not have a name + * @param nameRange - + * a two element array of integers describing the entire + * inclusive source range of this node's name within its + * document, including any array qualifiers that might + * immediately follow the name or -1's if this node does not have + * a name. + * @param commentRange - + * a two element array describing the comments that precede the + * member declaration. The first matches the start of this node's + * sourceRange, and the second is the new-line or first + * non-whitespace character following the last comment. If no + * comments are present, this array contains two -1's. + * @param flags - + * an integer representing the modifiers for this member. The + * integer can be analyzed with net.sourceforge.phpdt.core.Flags + * @param modifierRange - + * a two element array describing the location of modifiers for + * this member within its source range. The first integer is the + * first character of the first modifier for this member, and the + * second integer is the last whitespace character preceeding the + * next part of this member declaration. If there are no + * modifiers present in this node's source code (that is, package + * default visibility), this array contains two -1's. + * @param typeRange - + * a two element array describing the location of the 'class' or + * 'interface' keyword in the type declaration - first and last + * character positions. + * @param superclassRange - + * a two element array describing the location of the superclass + * name in the type declaration - first and last character + * positions or two -1's if a superclass is not present in the + * document. + * @param extendsRange - + * a two element array describing the location of the 'extends' + * keyword in the type declaration, including any surrounding + * whitespace, or -1's if the 'extends' keyword is not present in + * the document. + * @param implementsList - + * an array of names of the interfaces this type implements or + * extends, or null if this type does not + * implement or extend any interfaces. + * @param implementsRange - + * a two element array describing the location of the comment + * delimited list of interfaces this type implements or extends, + * not including any surrounding whitespace, or -1's if no + * interface list is present in the document. + * @param implementsKeywordRange - + * a two element array describing the location of the + * 'implements' keyword, including any surrounding whitespace, or + * -1's if no 'implements' keyword is present in the document. + * @param openBodyRange - + * a two element array describing the location of the open brace + * of the type's body and whitespace following the type + * declaration and preceeding the first member in the type. + * @param closeBodyRange - + * a two element array describing the source range of the first + * new line or non whitespace character preceeding the close + * brace of the type's body, up to the close brace + * @param isClass - + * true is the type is a class, false if it is an interface + */ + DOMType(char[] document, int[] sourceRange, String name, int[] nameRange, + int[] commentRange, int flags, int[] modifierRange, + int[] typeRange, int[] superclassRange, int[] extendsRange, + String[] implementsList, int[] implementsRange, + int[] implementsKeywordRange, int[] openBodyRange, + int[] closeBodyRange, boolean isClass) { + super(document, sourceRange, name, nameRange, commentRange, flags, + modifierRange); + + fTypeRange = typeRange; + setMask(MASK_TYPE_IS_CLASS, isClass); + + fExtendsRange = extendsRange; + fImplementsRange = implementsKeywordRange; + fSuperclassRange = superclassRange; + fInterfacesRange = implementsRange; + fCloseBodyRange = closeBodyRange; + setMask(MASK_TYPE_HAS_SUPERCLASS, superclassRange[0] > 0); + setMask(MASK_TYPE_HAS_INTERFACES, implementsList != null); + fSuperInterfaces = implementsList; + fOpenBodyRange = openBodyRange; + fCloseBodyRange = closeBodyRange; + setMask(MASK_DETAILED_SOURCE_INDEXES, true); -} -/** - * Creates a new simple TYPE document fragment on the given range of the document. - * - * @param document - the document containing this node's original contents - * @param sourceRange - a two element array of integers describing the - * entire inclusive source range of this node within its document. - * Contents start on and include the character at the first position. - * Contents end on and include the character at the last position. - * An array of -1's indicates this node's contents do not exist - * in the document. - * @param name - the identifier portion of the name of this node, or - * null if this node does not have a name - * @param nameRange - a two element array of integers describing the - * entire inclusive source range of this node's name within its document, - * including any array qualifiers that might immediately follow the name - * or -1's if this node does not have a name. - * @param flags - an integer representing the modifiers for this member. The - * integer can be analyzed with net.sourceforge.phpdt.core.Flags - * @param implementsList - an array of names of the interfaces this type implements - * or extends, or null if this type does not implement or extend - * any interfaces. - * @param isClass - true is the type is a class, false if it is an interface - */ -DOMType(char[] document, int[] sourceRange, String name, int[] nameRange, int flags, String[] implementsList, boolean isClass) { - this(document, sourceRange, name, nameRange, new int[] {-1, -1}, flags, - new int[] {-1, -1}, new int[] {-1, -1}, new int[] {-1, -1}, new int[] {-1, -1}, - implementsList, new int[] {-1, -1}, new int[] {-1, -1}, new int[] {-1, -1}, new int[] {sourceRange[1], sourceRange[1]}, isClass); - setMask(MASK_DETAILED_SOURCE_INDEXES, false); -} -/** - * @see IDOMType#addSuperInterface(String) - */ -public void addSuperInterface(String name) throws IllegalArgumentException { - if (name == null) { - throw new IllegalArgumentException(Util.bind("dom.addNullInterface")); //$NON-NLS-1$ } - if (fSuperInterfaces == null) { - fSuperInterfaces= new String[1]; - fSuperInterfaces[0]= name; - } else { - fSuperInterfaces= appendString(fSuperInterfaces, name); + + /** + * Creates a new simple TYPE document fragment on the given range of the + * document. + * + * @param document - + * the document containing this node's original contents + * @param sourceRange - + * a two element array of integers describing the entire + * inclusive source range of this node within its document. + * Contents start on and include the character at the first + * position. Contents end on and include the character at the + * last position. An array of -1's indicates this node's contents + * do not exist in the document. + * @param name - + * the identifier portion of the name of this node, or + * null if this node does not have a name + * @param nameRange - + * a two element array of integers describing the entire + * inclusive source range of this node's name within its + * document, including any array qualifiers that might + * immediately follow the name or -1's if this node does not have + * a name. + * @param flags - + * an integer representing the modifiers for this member. The + * integer can be analyzed with net.sourceforge.phpdt.core.Flags + * @param implementsList - + * an array of names of the interfaces this type implements or + * extends, or null if this type does not + * implement or extend any interfaces. + * @param isClass - + * true is the type is a class, false if it is an interface + */ + DOMType(char[] document, int[] sourceRange, String name, int[] nameRange, + int flags, String[] implementsList, boolean isClass) { + this(document, sourceRange, name, nameRange, new int[] { -1, -1 }, + flags, new int[] { -1, -1 }, new int[] { -1, -1 }, new int[] { + -1, -1 }, new int[] { -1, -1 }, implementsList, + new int[] { -1, -1 }, new int[] { -1, -1 }, + new int[] { -1, -1 }, new int[] { sourceRange[1], + sourceRange[1] }, isClass); + setMask(MASK_DETAILED_SOURCE_INDEXES, false); } - setSuperInterfaces(fSuperInterfaces); -} -/** - * @see DOMMember#appendMemberBodyContents(CharArrayBuffer) - */ -protected void appendMemberBodyContents(CharArrayBuffer buffer) { - buffer.append(fDocument, fOpenBodyRange[0], fOpenBodyRange[1] + 1 - fOpenBodyRange[0]); - appendContentsOfChildren(buffer); - buffer.append(fDocument, fCloseBodyRange[0], fCloseBodyRange[1] + 1 - fCloseBodyRange[0]); - buffer.append(fDocument, fCloseBodyRange[1] + 1, fSourceRange[1] - fCloseBodyRange[1]); -} -/** - * @see DOMMember#appendMemberDeclarationContents(CharArrayBuffer ) - */ -protected void appendMemberDeclarationContents(CharArrayBuffer buffer) { - - if (fTypeKeyword != null) { - buffer.append(fTypeKeyword); - buffer.append(fDocument, fTypeRange[1], fNameRange[0] - fTypeRange[1] ); - } else { - buffer.append(fDocument, fTypeRange[0], fTypeRange[1] + 1 - fTypeRange[0]); + + /** + * @see IDOMType#addSuperInterface(String) + */ + public void addSuperInterface(String name) throws IllegalArgumentException { + if (name == null) { + throw new IllegalArgumentException(Util + .bind("dom.addNullInterface")); //$NON-NLS-1$ + } + if (fSuperInterfaces == null) { + fSuperInterfaces = new String[1]; + fSuperInterfaces[0] = name; + } else { + fSuperInterfaces = appendString(fSuperInterfaces, name); + } + setSuperInterfaces(fSuperInterfaces); } - buffer.append(getName()); + /** + * @see DOMMember#appendMemberBodyContents(CharArrayBuffer) + */ + protected void appendMemberBodyContents(CharArrayBuffer buffer) { + buffer.append(fDocument, fOpenBodyRange[0], fOpenBodyRange[1] + 1 + - fOpenBodyRange[0]); + appendContentsOfChildren(buffer); + buffer.append(fDocument, fCloseBodyRange[0], fCloseBodyRange[1] + 1 + - fCloseBodyRange[0]); + buffer.append(fDocument, fCloseBodyRange[1] + 1, fSourceRange[1] + - fCloseBodyRange[1]); + } - if (isClass()) { - boolean hasSuperclass = false, hasInterfaces = false; - if (getMask(MASK_TYPE_HAS_SUPERCLASS)) { - hasSuperclass = true; - if (fExtendsRange[0] < 0) { - buffer.append(" extends "); //$NON-NLS-1$ - } else { - buffer.append(fDocument, fExtendsRange[0], fExtendsRange[1] + 1 - fExtendsRange[0]); - } - if (fSuperclass != null) { - buffer.append(fSuperclass); - } else { - buffer.append(fDocument, fSuperclassRange[0], fSuperclassRange[1] + 1 - fSuperclassRange[0]); - } + /** + * @see DOMMember#appendMemberDeclarationContents(CharArrayBuffer ) + */ + protected void appendMemberDeclarationContents(CharArrayBuffer buffer) { + + if (fTypeKeyword != null) { + buffer.append(fTypeKeyword); + buffer.append(fDocument, fTypeRange[1], fNameRange[0] + - fTypeRange[1]); + } else { + buffer.append(fDocument, fTypeRange[0], fTypeRange[1] + 1 + - fTypeRange[0]); } - if (getMask(MASK_TYPE_HAS_INTERFACES)) { - hasInterfaces = true; - if (fImplementsRange[0] < 0) { - buffer.append(" implements "); //$NON-NLS-1$ - } else { - buffer.append(fDocument, fImplementsRange[0], fImplementsRange[1] + 1 - fImplementsRange[0]); + + buffer.append(getName()); + + if (isClass()) { + boolean hasSuperclass = false, hasInterfaces = false; + if (getMask(MASK_TYPE_HAS_SUPERCLASS)) { + hasSuperclass = true; + if (fExtendsRange[0] < 0) { + buffer.append(" extends "); //$NON-NLS-1$ + } else { + buffer.append(fDocument, fExtendsRange[0], fExtendsRange[1] + + 1 - fExtendsRange[0]); + } + if (fSuperclass != null) { + buffer.append(fSuperclass); + } else { + buffer.append(fDocument, fSuperclassRange[0], + fSuperclassRange[1] + 1 - fSuperclassRange[0]); + } } - if (fInterfaces != null) { - buffer.append(fInterfaces); - } else { - buffer.append(fDocument, fInterfacesRange[0], fInterfacesRange[1] + 1 - fInterfacesRange[0]); + if (getMask(MASK_TYPE_HAS_INTERFACES)) { + hasInterfaces = true; + if (fImplementsRange[0] < 0) { + buffer.append(" implements "); //$NON-NLS-1$ + } else { + buffer.append(fDocument, fImplementsRange[0], + fImplementsRange[1] + 1 - fImplementsRange[0]); + } + if (fInterfaces != null) { + buffer.append(fInterfaces); + } else { + buffer.append(fDocument, fInterfacesRange[0], + fInterfacesRange[1] + 1 - fInterfacesRange[0]); + } } - } - if (hasInterfaces) { - if (fImplementsRange[0] < 0) { - buffer.append(' '); + if (hasInterfaces) { + if (fImplementsRange[0] < 0) { + buffer.append(' '); + } else { + buffer.append(fDocument, fInterfacesRange[1] + 1, + fOpenBodyRange[0] - fInterfacesRange[1] - 1); + } } else { - buffer.append(fDocument, fInterfacesRange[1] + 1, fOpenBodyRange[0] - fInterfacesRange[1] - 1); + if (hasSuperclass) { + if (fSuperclassRange[0] < 0) { + buffer.append(' '); + } else { + buffer.append(fDocument, fSuperclassRange[1] + 1, + fOpenBodyRange[0] - fSuperclassRange[1] - 1); + } + } else { + buffer.append(fDocument, fNameRange[1] + 1, + fOpenBodyRange[0] - fNameRange[1] - 1); + } } } else { - if (hasSuperclass) { - if (fSuperclassRange[0] < 0) { + if (getMask(MASK_TYPE_HAS_INTERFACES)) { + if (fExtendsRange[0] < 0) { + buffer.append(" extends "); //$NON-NLS-1$ + } else { + buffer.append(fDocument, fExtendsRange[0], fExtendsRange[1] + + 1 - fExtendsRange[0]); + } + if (fInterfaces != null) { + buffer.append(fInterfaces); buffer.append(' '); } else { - buffer.append(fDocument, fSuperclassRange[1] + 1, fOpenBodyRange[0] - fSuperclassRange[1] - 1); + buffer.append(fDocument, fInterfacesRange[0], + fInterfacesRange[1] + 1 - fInterfacesRange[0]); } } else { - buffer.append(fDocument, fNameRange[1] + 1, fOpenBodyRange[0] - fNameRange[1] - 1); - } - } - } else { - if (getMask(MASK_TYPE_HAS_INTERFACES)) { - if (fExtendsRange[0] < 0) { - buffer.append(" extends "); //$NON-NLS-1$ - } else { - buffer.append(fDocument, fExtendsRange[0], fExtendsRange[1] + 1 - fExtendsRange[0]); + buffer.append(fDocument, fNameRange[1] + 1, fOpenBodyRange[0] + - fNameRange[1] - 1); } - if (fInterfaces != null) { - buffer.append(fInterfaces); - buffer.append(' '); - } else { - buffer.append(fDocument, fInterfacesRange[0], fInterfacesRange[1] + 1 - fInterfacesRange[0]); - } - } else { - buffer.append(fDocument, fNameRange[1] + 1, fOpenBodyRange[0] - fNameRange[1] - 1); } + } - -} -/** - * @see DOMNode#appendSimpleContents(CharArrayBuffer) - */ -protected void appendSimpleContents(CharArrayBuffer buffer) { - // append eveything before my name - buffer.append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0]); - // append my name - buffer.append(fName); - - // append everything after my name and before my first child - buffer.append(fDocument, fNameRange[1] + 1, fOpenBodyRange[1] - fNameRange[1]); - // append my children - appendContentsOfChildren(buffer); - // append from my last child to my end - buffer.append(fDocument, fCloseBodyRange[0], fSourceRange[1] - fCloseBodyRange[0] + 1); + /** + * @see DOMNode#appendSimpleContents(CharArrayBuffer) + */ + protected void appendSimpleContents(CharArrayBuffer buffer) { + // append eveything before my name + buffer.append(fDocument, fSourceRange[0], fNameRange[0] + - fSourceRange[0]); + // append my name + buffer.append(fName); + // append everything after my name and before my first child + buffer.append(fDocument, fNameRange[1] + 1, fOpenBodyRange[1] + - fNameRange[1]); + // append my children + appendContentsOfChildren(buffer); + // append from my last child to my end + buffer.append(fDocument, fCloseBodyRange[0], fSourceRange[1] + - fCloseBodyRange[0] + 1); -} -/** - * @see IDOMNode#canHaveChildren() - */ -public boolean canHaveChildren() { - return true; -} -/** - * Returns the position of the closing brace for the body of this type. - * This value this method returns is only valid before the type has - * been normalized and is present only for normalization. - */ -int getCloseBodyPosition() { - return fCloseBodyRange[0]; -} -/** - * @see DOMNode#getDetailedNode() - */ -//protected DOMNode getDetailedNode() { -// return (DOMNode)getFactory().createType(getContents()); -//} -/** - * @see DOMNode#getInsertionPosition() - */ -public int getInsertionPosition() { - // this should return the position of the end of the last line separator before the closing brace of the type - // See PR 1GELSDQ: ITPJUI:WINNT - JDOM: IType.createMethod does not insert nicely for inner types - return fInsertionPosition; -} -/** - * @see IDOMNode#getJavaElement - */ -public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { - if (parent.getElementType() == IJavaElement.TYPE) { - return ((IType)parent).getType(getName()); - } else if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) { - return ((ICompilationUnit)parent).getType(getName()); - } else { - throw new IllegalArgumentException(Util.bind("element.illegalParent")); //$NON-NLS-1$ } -} -/** - * @see DOMMember#getMemberDeclarationStartPosition() - */ -protected int getMemberDeclarationStartPosition() { - return fTypeRange[0]; -} -/** - * @see IDOMNode#getNodeType() - */ -public int getNodeType() { - return IDOMNode.TYPE; -} -/** - * Answers the open body range end position. - */ -int getOpenBodyEnd() { - return fOpenBodyRange[1]; -} -/** - * @see IDOMType#getSuperclass() - */ -public String getSuperclass() { - becomeDetailed(); - if (getMask(MASK_TYPE_HAS_SUPERCLASS)) { - if (fSuperclass != null) { - return fSuperclass; + + /** + * @see IDOMNode#canHaveChildren() + */ + public boolean canHaveChildren() { + return true; + } + + /** + * Returns the position of the closing brace for the body of this type. This + * value this method returns is only valid before the type has been + * normalized and is present only for normalization. + */ + int getCloseBodyPosition() { + return fCloseBodyRange[0]; + } + + /** + * @see DOMNode#getDetailedNode() + */ + // protected DOMNode getDetailedNode() { + // return (DOMNode)getFactory().createType(getContents()); + // } + /** + * @see DOMNode#getInsertionPosition() + */ + public int getInsertionPosition() { + // this should return the position of the end of the last line separator + // before the closing brace of the type + // See PR 1GELSDQ: ITPJUI:WINNT - JDOM: IType.createMethod does not + // insert nicely for inner types + return fInsertionPosition; + } + + /** + * @see IDOMNode#getJavaElement + */ + public IJavaElement getJavaElement(IJavaElement parent) + throws IllegalArgumentException { + if (parent.getElementType() == IJavaElement.TYPE) { + return ((IType) parent).getType(getName()); + } else if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) { + return ((ICompilationUnit) parent).getType(getName()); } else { - return CharArrayOps.substring(fDocument, fSuperclassRange[0], fSuperclassRange[1] + 1 - fSuperclassRange[0]); + throw new IllegalArgumentException(Util + .bind("element.illegalParent")); //$NON-NLS-1$ } - } else { - return null; } -} -/** - * @see IDOMType#getSuperInterfaces() - */ -public String[] getSuperInterfaces() { - return fSuperInterfaces; -} -/** - * @see IDOMNode - */ -public boolean isAllowableChild(IDOMNode node) { - if (node != null) { - int type= node.getNodeType(); - return type == IDOMNode.TYPE || type == IDOMNode.FIELD|| type == IDOMNode.METHOD || - type == IDOMNode.INITIALIZER; - } else { - return false; - } - -} -/** - * @see IDOMType#isClass() - */ -public boolean isClass() { - return getMask(MASK_TYPE_IS_CLASS); -} -/** - * @see DOMNode - */ -protected DOMNode newDOMNode() { - return new DOMType(); -} -/** - * Normalizes this DOMNode's source positions to include whitespace preceeding - * the node on the line on which the node starts, and all whitespace after the node up to - * the next node's start - */ -void normalize(ILineStartFinder finder) { - // perform final changes to the open and close body ranges - int openBodyEnd, openBodyStart, closeBodyStart, closeBodyEnd; - DOMNode first = (DOMNode) getFirstChild(); - DOMNode lastNode = null; - // look for the open body - Scanner scanner = new Scanner(); - scanner.setSource(fDocument); - scanner.resetTo(fNameRange[1] + 1, fDocument.length); - - try { - int currentToken = scanner.getNextToken(); - while(currentToken != ITerminalSymbols.TokenNameLBRACE && - currentToken != ITerminalSymbols.TokenNameEOF) { - currentToken = scanner.getNextToken(); - } - if(currentToken == ITerminalSymbols.TokenNameLBRACE) { - openBodyEnd = scanner.currentPosition - 1; - openBodyStart = scanner.startPosition; + + /** + * @see DOMMember#getMemberDeclarationStartPosition() + */ + protected int getMemberDeclarationStartPosition() { + return fTypeRange[0]; + } + + /** + * @see IDOMNode#getNodeType() + */ + public int getNodeType() { + return IDOMNode.TYPE; + } + + /** + * Answers the open body range end position. + */ + int getOpenBodyEnd() { + return fOpenBodyRange[1]; + } + + /** + * @see IDOMType#getSuperclass() + */ + public String getSuperclass() { + becomeDetailed(); + if (getMask(MASK_TYPE_HAS_SUPERCLASS)) { + if (fSuperclass != null) { + return fSuperclass; + } else { + return CharArrayOps.substring(fDocument, fSuperclassRange[0], + fSuperclassRange[1] + 1 - fSuperclassRange[0]); + } } else { - openBodyEnd = fDocument.length; - openBodyStart = fDocument.length; + return null; } - } catch(InvalidInputException e) { - openBodyEnd = fDocument.length; - openBodyStart = fDocument.length; - } - if (first != null) { - int lineStart = finder.getLineStart(first.getStartPosition()); - if (lineStart > openBodyEnd) { - openBodyEnd = lineStart - 1; - } else { - openBodyEnd = first.getStartPosition() - 1; - } - lastNode = (DOMNode) first.getNextNode(); - if (lastNode == null) { - lastNode = first; + } + + /** + * @see IDOMType#getSuperInterfaces() + */ + public String[] getSuperInterfaces() { + return fSuperInterfaces; + } + + /** + * @see IDOMNode + */ + public boolean isAllowableChild(IDOMNode node) { + if (node != null) { + int type = node.getNodeType(); + return type == IDOMNode.TYPE || type == IDOMNode.FIELD + || type == IDOMNode.METHOD || type == IDOMNode.INITIALIZER; } else { - while (lastNode.getNextNode() != null) { - lastNode = (DOMNode) lastNode.getNextNode(); - } + return false; } + + } + + /** + * @see IDOMType#isClass() + */ + public boolean isClass() { + return getMask(MASK_TYPE_IS_CLASS); + } + + /** + * @see DOMNode + */ + protected DOMNode newDOMNode() { + return new DOMType(); + } + + /** + * Normalizes this DOMNode's source positions to include + * whitespace preceeding the node on the line on which the node starts, and + * all whitespace after the node up to the next node's start + */ + void normalize(ILineStartFinder finder) { + // perform final changes to the open and close body ranges + int openBodyEnd, openBodyStart, closeBodyStart, closeBodyEnd; + DOMNode first = (DOMNode) getFirstChild(); + DOMNode lastNode = null; + // look for the open body + Scanner scanner = new Scanner(); scanner.setSource(fDocument); - scanner.resetTo(lastNode.getEndPosition() + 1, fDocument.length); + scanner.resetTo(fNameRange[1] + 1, fDocument.length); + try { int currentToken = scanner.getNextToken(); - while(currentToken != ITerminalSymbols.TokenNameRBRACE && - currentToken != ITerminalSymbols.TokenNameEOF) { + while (currentToken != ITerminalSymbols.TokenNameLBRACE + && currentToken != ITerminalSymbols.TokenNameEOF) { currentToken = scanner.getNextToken(); } - if(currentToken == ITerminalSymbols.TokenNameRBRACE) { - closeBodyStart = scanner.startPosition; - closeBodyEnd = scanner.currentPosition - 1; + if (currentToken == ITerminalSymbols.TokenNameLBRACE) { + openBodyEnd = scanner.currentPosition - 1; + openBodyStart = scanner.startPosition; } else { - closeBodyStart = fDocument.length; - closeBodyEnd = fDocument.length; + openBodyEnd = fDocument.length; + openBodyStart = fDocument.length; } - } catch(InvalidInputException e) { - closeBodyStart = fDocument.length; - closeBodyEnd = fDocument.length; + } catch (InvalidInputException e) { + openBodyEnd = fDocument.length; + openBodyStart = fDocument.length; } - } else { - scanner.resetTo(openBodyEnd, fDocument.length); - try { - int currentToken = scanner.getNextToken(); - while(currentToken != ITerminalSymbols.TokenNameRBRACE && - currentToken != ITerminalSymbols.TokenNameEOF) { - currentToken = scanner.getNextToken(); + if (first != null) { + int lineStart = finder.getLineStart(first.getStartPosition()); + if (lineStart > openBodyEnd) { + openBodyEnd = lineStart - 1; + } else { + openBodyEnd = first.getStartPosition() - 1; } - if(currentToken == ITerminalSymbols.TokenNameRBRACE) { - closeBodyStart = scanner.startPosition; - closeBodyEnd = scanner.currentPosition - 1; + lastNode = (DOMNode) first.getNextNode(); + if (lastNode == null) { + lastNode = first; } else { + while (lastNode.getNextNode() != null) { + lastNode = (DOMNode) lastNode.getNextNode(); + } + } + scanner.setSource(fDocument); + scanner.resetTo(lastNode.getEndPosition() + 1, fDocument.length); + try { + int currentToken = scanner.getNextToken(); + while (currentToken != ITerminalSymbols.TokenNameRBRACE + && currentToken != ITerminalSymbols.TokenNameEOF) { + currentToken = scanner.getNextToken(); + } + if (currentToken == ITerminalSymbols.TokenNameRBRACE) { + closeBodyStart = scanner.startPosition; + closeBodyEnd = scanner.currentPosition - 1; + } else { + closeBodyStart = fDocument.length; + closeBodyEnd = fDocument.length; + } + } catch (InvalidInputException e) { + closeBodyStart = fDocument.length; + closeBodyEnd = fDocument.length; + } + } else { + scanner.resetTo(openBodyEnd, fDocument.length); + try { + int currentToken = scanner.getNextToken(); + while (currentToken != ITerminalSymbols.TokenNameRBRACE + && currentToken != ITerminalSymbols.TokenNameEOF) { + currentToken = scanner.getNextToken(); + } + if (currentToken == ITerminalSymbols.TokenNameRBRACE) { + closeBodyStart = scanner.startPosition; + closeBodyEnd = scanner.currentPosition - 1; + } else { + closeBodyStart = fDocument.length; + closeBodyEnd = fDocument.length; + } + } catch (InvalidInputException e) { closeBodyStart = fDocument.length; closeBodyEnd = fDocument.length; } - } catch(InvalidInputException e) { - closeBodyStart = fDocument.length; - closeBodyEnd = fDocument.length; + openBodyEnd = closeBodyEnd - 1; + } + setOpenBodyRangeEnd(openBodyEnd); + setOpenBodyRangeStart(openBodyStart); + setCloseBodyRangeStart(closeBodyStart); + setCloseBodyRangeEnd(closeBodyEnd); + fInsertionPosition = finder.getLineStart(closeBodyStart); + if (lastNode != null && fInsertionPosition < lastNode.getEndPosition()) { + fInsertionPosition = getCloseBodyPosition(); + } + if (fInsertionPosition <= openBodyEnd) { + fInsertionPosition = getCloseBodyPosition(); } - openBodyEnd = closeBodyEnd - 1; + super.normalize(finder); } - setOpenBodyRangeEnd(openBodyEnd); - setOpenBodyRangeStart(openBodyStart); - setCloseBodyRangeStart(closeBodyStart); - setCloseBodyRangeEnd(closeBodyEnd); - fInsertionPosition = finder.getLineStart(closeBodyStart); - if (lastNode != null && fInsertionPosition < lastNode.getEndPosition()) { - fInsertionPosition = getCloseBodyPosition(); + + /** + * Normalizes this DOMNode's end position. + */ + void normalizeEndPosition(ILineStartFinder finder, DOMNode next) { + if (next == null) { + // this node's end position includes all of the characters up + // to the end of the enclosing node + DOMNode parent = (DOMNode) getParent(); + if (parent == null || parent instanceof DOMCompilationUnit) { + setSourceRangeEnd(fDocument.length - 1); + } else { + // parent is a type + setSourceRangeEnd(((DOMType) parent).getCloseBodyPosition() - 1); + } + } else { + // this node's end position is just before the start of the next + // node + next.normalizeStartPosition(getEndPosition(), finder); + setSourceRangeEnd(next.getStartPosition() - 1); + } } - if (fInsertionPosition <= openBodyEnd) { - fInsertionPosition = getCloseBodyPosition(); + + /** + * Offsets all the source indexes in this node by the given amount. + */ + protected void offset(int offset) { + super.offset(offset); + offsetRange(fCloseBodyRange, offset); + offsetRange(fExtendsRange, offset); + offsetRange(fImplementsRange, offset); + offsetRange(fInterfacesRange, offset); + offsetRange(fOpenBodyRange, offset); + offsetRange(fSuperclassRange, offset); + offsetRange(fTypeRange, offset); } - super.normalize(finder); -} -/** - * Normalizes this DOMNode's end position. - */ -void normalizeEndPosition(ILineStartFinder finder, DOMNode next) { - if (next == null) { - // this node's end position includes all of the characters up - // to the end of the enclosing node - DOMNode parent = (DOMNode) getParent(); - if (parent == null || parent instanceof DOMCompilationUnit) { - setSourceRangeEnd(fDocument.length - 1); + /** + * @see IDOMType#setClass(boolean) + */ + public void setClass(boolean b) { + becomeDetailed(); + fragment(); + setMask(MASK_TYPE_IS_CLASS, b); + if (b) { + fTypeKeyword = "class"; //$NON-NLS-1$ } else { - // parent is a type - setSourceRangeEnd(((DOMType)parent).getCloseBodyPosition() - 1); + fTypeKeyword = "interface"; //$NON-NLS-1$ + setSuperclass(null); } - } else { - // this node's end position is just before the start of the next node - next.normalizeStartPosition(getEndPosition(), finder); - setSourceRangeEnd(next.getStartPosition() - 1); } -} -/** - * Offsets all the source indexes in this node by the given amount. - */ -protected void offset(int offset) { - super.offset(offset); - offsetRange(fCloseBodyRange, offset); - offsetRange(fExtendsRange, offset); - offsetRange(fImplementsRange, offset); - offsetRange(fInterfacesRange, offset); - offsetRange(fOpenBodyRange, offset); - offsetRange(fSuperclassRange, offset); - offsetRange(fTypeRange, offset); -} -/** - * @see IDOMType#setClass(boolean) - */ -public void setClass(boolean b) { - becomeDetailed(); - fragment(); - setMask(MASK_TYPE_IS_CLASS, b); - if (b) { - fTypeKeyword= "class"; //$NON-NLS-1$ - } else { - fTypeKeyword= "interface"; //$NON-NLS-1$ - setSuperclass(null); + /** + * Sets the end of the close body range + */ + void setCloseBodyRangeEnd(int end) { + fCloseBodyRange[1] = end; } -} -/** - * Sets the end of the close body range - */ -void setCloseBodyRangeEnd(int end) { - fCloseBodyRange[1] = end; -} -/** - * Sets the start of the close body range - */ -void setCloseBodyRangeStart(int start) { - fCloseBodyRange[0] = start; -} -/** - * Sets the name of this node. - * - *

                                                      When the name of a type is set, all of its constructors must be marked - * as fragmented, since the names of the constructors must reflect the name - * of this type. - * - * @see IDOMNode#setName(char[]) - */ -public void setName(String name) throws IllegalArgumentException { - if (name == null) { - throw new IllegalArgumentException(Util.bind("element.nullName")); //$NON-NLS-1$ - } - super.setName(name); - Enumeration children= getChildren(); - while (children.hasMoreElements()) { - IDOMNode child= (IDOMNode)children.nextElement(); - if (child.getNodeType() == IDOMNode.METHOD && ((IDOMMethod)child).isConstructor()) { - ((DOMNode)child).fragment(); + + /** + * Sets the start of the close body range + */ + void setCloseBodyRangeStart(int start) { + fCloseBodyRange[0] = start; + } + + /** + * Sets the name of this node. + * + *

                                                      + * When the name of a type is set, all of its constructors must be marked as + * fragmented, since the names of the constructors must reflect the name of + * this type. + * + * @see IDOMNode#setName(char[]) + */ + public void setName(String name) throws IllegalArgumentException { + if (name == null) { + throw new IllegalArgumentException(Util.bind("element.nullName")); //$NON-NLS-1$ + } + super.setName(name); + Enumeration children = getChildren(); + while (children.hasMoreElements()) { + IDOMNode child = (IDOMNode) children.nextElement(); + if (child.getNodeType() == IDOMNode.METHOD + && ((IDOMMethod) child).isConstructor()) { + ((DOMNode) child).fragment(); + } } } -} -/** - * Sets the end of the open body range - */ -void setOpenBodyRangeEnd(int end) { - fOpenBodyRange[1] = end; -} -/** - * Sets the start of the open body range - */ -void setOpenBodyRangeStart(int start) { - fOpenBodyRange[0] = start; -} -/** - * @see IDOMType#setSuperclass(char[]) - */ -public void setSuperclass(String superclassName) { - becomeDetailed(); - fragment(); - fSuperclass= superclassName; - setMask(MASK_TYPE_HAS_SUPERCLASS, superclassName != null); -} -/** - * @see IDOMType#setSuperInterfaces(String[]) - */ -public void setSuperInterfaces(String[] names) { - becomeDetailed(); - if (names == null) { - throw new IllegalArgumentException(Util.bind("dom.nullInterfaces")); //$NON-NLS-1$ - } - fragment(); - fSuperInterfaces= names; - if (names == null || names.length == 0) { - fInterfaces= null; - fSuperInterfaces= null; - setMask(MASK_TYPE_HAS_INTERFACES, false); - } else { - setMask(MASK_TYPE_HAS_INTERFACES, true); - CharArrayBuffer buffer = new CharArrayBuffer(); - for (int i = 0; i < names.length; i++) { - if (i > 0) { - buffer.append(", "); //$NON-NLS-1$ + + /** + * Sets the end of the open body range + */ + void setOpenBodyRangeEnd(int end) { + fOpenBodyRange[1] = end; + } + + /** + * Sets the start of the open body range + */ + void setOpenBodyRangeStart(int start) { + fOpenBodyRange[0] = start; + } + + /** + * @see IDOMType#setSuperclass(char[]) + */ + public void setSuperclass(String superclassName) { + becomeDetailed(); + fragment(); + fSuperclass = superclassName; + setMask(MASK_TYPE_HAS_SUPERCLASS, superclassName != null); + } + + /** + * @see IDOMType#setSuperInterfaces(String[]) + */ + public void setSuperInterfaces(String[] names) { + becomeDetailed(); + if (names == null) { + throw new IllegalArgumentException(Util.bind("dom.nullInterfaces")); //$NON-NLS-1$ + } + fragment(); + fSuperInterfaces = names; + if (names == null || names.length == 0) { + fInterfaces = null; + fSuperInterfaces = null; + setMask(MASK_TYPE_HAS_INTERFACES, false); + } else { + setMask(MASK_TYPE_HAS_INTERFACES, true); + CharArrayBuffer buffer = new CharArrayBuffer(); + for (int i = 0; i < names.length; i++) { + if (i > 0) { + buffer.append(", "); //$NON-NLS-1$ + } + buffer.append(names[i]); } - buffer.append(names[i]); + fInterfaces = buffer.getContents(); } - fInterfaces = buffer.getContents(); } -} -/** - * Sets the type keyword - */ -void setTypeKeyword(String keyword) { - fTypeKeyword = keyword; -} -/** - * @see DOMNode#shareContents(DOMNode) - */ -protected void shareContents(DOMNode node) { - super.shareContents(node); - DOMType type= (DOMType)node; - fCloseBodyRange= rangeCopy(type.fCloseBodyRange); - fExtendsRange= type.fExtendsRange; - fImplementsRange= rangeCopy(type.fImplementsRange); - fInterfaces= type.fInterfaces; - fInterfacesRange= rangeCopy(type.fInterfacesRange); - fOpenBodyRange= rangeCopy(type.fOpenBodyRange); - fSuperclass= type.fSuperclass; - fSuperclassRange= rangeCopy(type.fSuperclassRange); - fSuperInterfaces= type.fSuperInterfaces; - fTypeKeyword= type.fTypeKeyword; - fTypeRange= rangeCopy(type.fTypeRange); -} -/** - * @see IDOMNode#toString() - */ -public String toString() { - return "TYPE: " + getName(); //$NON-NLS-1$ -} + + /** + * Sets the type keyword + */ + void setTypeKeyword(String keyword) { + fTypeKeyword = keyword; + } + + /** + * @see DOMNode#shareContents(DOMNode) + */ + protected void shareContents(DOMNode node) { + super.shareContents(node); + DOMType type = (DOMType) node; + fCloseBodyRange = rangeCopy(type.fCloseBodyRange); + fExtendsRange = type.fExtendsRange; + fImplementsRange = rangeCopy(type.fImplementsRange); + fInterfaces = type.fInterfaces; + fInterfacesRange = rangeCopy(type.fInterfacesRange); + fOpenBodyRange = rangeCopy(type.fOpenBodyRange); + fSuperclass = type.fSuperclass; + fSuperclassRange = rangeCopy(type.fSuperclassRange); + fSuperInterfaces = type.fSuperInterfaces; + fTypeKeyword = type.fTypeKeyword; + fTypeRange = rangeCopy(type.fTypeRange); + } + + /** + * @see IDOMNode#toString() + */ + public String toString() { + return "TYPE: " + getName(); //$NON-NLS-1$ + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/ILineStartFinder.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/ILineStartFinder.java index 8dda4de..a3bc28f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/ILineStartFinder.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/ILineStartFinder.java @@ -15,11 +15,13 @@ package net.sourceforge.phpdt.internal.core.jdom; * in source. */ public interface ILineStartFinder { -/** - * Returns the position of the start of the line at or before the given source position. - * - *

                                                      This defaults to zero if the position corresponds to a position on the first line - * of the source. - */ -public int getLineStart(int position); + /** + * Returns the position of the start of the line at or before the given + * source position. + * + *

                                                      + * This defaults to zero if the position corresponds to a position on the + * first line of the source. + */ + public int getLineStart(int position); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/SiblingEnumeration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/SiblingEnumeration.java index 167ce0e..6640746 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/SiblingEnumeration.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/SiblingEnumeration.java @@ -15,40 +15,42 @@ import java.util.Enumeration; import net.sourceforge.phpdt.core.jdom.IDOMNode; /** - * SiblingEnumeration provides an enumeration on a linked list - * of sibling DOM nodes. - * + * SiblingEnumeration provides an enumeration on a linked list of sibling DOM + * nodes. + * * @see java.util.Enumeration */ -/* package */ class SiblingEnumeration implements Enumeration { +/* package */class SiblingEnumeration implements Enumeration { /** - * The current location in the linked list - * of DOM nodes. + * The current location in the linked list of DOM nodes. */ protected IDOMNode fCurrentElement; -/** - * Creates an enumeration of silbings starting at the given node. - * If the given node is null the enumeration is empty. - */ -SiblingEnumeration(IDOMNode child) { - fCurrentElement= child; -} -/** - * @see java.util.Enumeration#hasMoreElements() - */ -public boolean hasMoreElements() { - return fCurrentElement != null; -} -/** - * @see java.util.Enumeration#nextElement() - */ -public Object nextElement() { - IDOMNode curr= fCurrentElement; - if (curr != null) { - fCurrentElement= fCurrentElement.getNextNode(); + + /** + * Creates an enumeration of silbings starting at the given node. If the + * given node is null the enumeration is empty. + */ + SiblingEnumeration(IDOMNode child) { + fCurrentElement = child; + } + + /** + * @see java.util.Enumeration#hasMoreElements() + */ + public boolean hasMoreElements() { + return fCurrentElement != null; + } + + /** + * @see java.util.Enumeration#nextElement() + */ + public Object nextElement() { + IDOMNode curr = fCurrentElement; + if (curr != null) { + fCurrentElement = fCurrentElement.getNextNode(); + } + return curr; } - return curr; -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/SimpleDOMBuilder.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/SimpleDOMBuilder.java index a308317..90bcd3d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/SimpleDOMBuilder.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/SimpleDOMBuilder.java @@ -25,220 +25,257 @@ import net.sourceforge.phpdt.internal.core.util.CharArrayOps; /** * A DOM builder that uses the SourceElementParser */ -public class SimpleDOMBuilder extends AbstractDOMBuilder implements ISourceElementRequestor { - - public void acceptImport(int declarationStart, int declarationEnd, char[] name, boolean onDemand) { - int[] sourceRange = { declarationStart, declarationEnd }; - String importName = new String(name); - /** name is set to contain the '*' */ - if (onDemand) { - importName += ".*"; //$NON-NLS-1$ - } - fNode = new DOMImport(fDocument, sourceRange, importName, onDemand); - addChild(fNode); - } - - public void acceptPackage(int declarationStart, int declarationEnd, char[] name) { - int[] sourceRange = new int[] { declarationStart, declarationEnd }; - fNode = new DOMPackage(fDocument, sourceRange, CharArrayOps.charToString(name)); - addChild(fNode); - } - - /** - * @see IDOMFactory#createCompilationUnit(String, String) - */ - public IDOMCompilationUnit createCompilationUnit(String sourceCode, String name) { - return createCompilationUnit(sourceCode.toCharArray(), name.toCharArray()); - } - - /** - * @see IDOMFactory#createCompilationUnit(String, String) - */ - public IDOMCompilationUnit createCompilationUnit(ICompilationUnit compilationUnit) { - initializeBuild(compilationUnit.getContents(), true, true); - getParser(JavaCore.getOptions()).parseCompilationUnit(compilationUnit, false); - return super.createCompilationUnit(compilationUnit); - } - - /** - * Creates a new DOMMethod and inizializes. - * - * @param declarationStart - - * a source position corresponding to the first character of this constructor declaration - * @param modifiers - - * the modifiers for this constructor converted to a flag - * @param returnType - - * the name of the return type - * @param name - - * the name of this constructor - * @param nameStart - - * a source position corresponding to the first character of the name - * @param nameEnd - - * a source position corresponding to the last character of the name - * @param parameterTypes - - * a list of parameter type names - * @param parameterNames - - * a list of the names of the parameters - * @param exceptionTypes - - * a list of the exception types - */ - protected void enterAbstractMethod(int declarationStart, int modifiers, char[] returnType, char[] name, int nameStart, - int nameEnd, char[][] parameterTypes, char[][] parameterNames, char[][] exceptionTypes, boolean isConstructor) { - - int[] sourceRange = { declarationStart, -1 }; // will be fixed up on exit - int[] nameRange = { nameStart, nameEnd }; - fNode = new DOMMethod(fDocument, sourceRange, CharArrayOps.charToString(name), nameRange, modifiers, isConstructor, - CharArrayOps.charToString(returnType), CharArrayOps.charcharToString(parameterTypes), CharArrayOps - .charcharToString(parameterNames), CharArrayOps.charcharToString(exceptionTypes)); - addChild(fNode); - fStack.push(fNode); - } - - /** - */ - public void enterClass(int declarationStart, int modifiers, char[] name, int nameStart, int nameEnd, char[] superclass, - char[][] superinterfaces) { - enterType(declarationStart, modifiers, name, nameStart, nameEnd, superclass, superinterfaces, true); - } - - /** - */ - public void enterConstructor(int declarationStart, int modifiers, char[] name, int nameStart, int nameEnd, - char[][] parameterTypes, char[][] parameterNames, char[][] exceptionTypes) { - /* see 1FVIIQZ */ - String nameString = new String(fDocument, nameStart, nameEnd - nameStart); - int openParenPosition = nameString.indexOf('('); - if (openParenPosition > -1) - nameEnd = nameStart + openParenPosition - 1; - - enterAbstractMethod(declarationStart, modifiers, null, name, nameStart, nameEnd, parameterTypes, parameterNames, - exceptionTypes, true); - } - - /** - */ - public void enterField(int declarationStart, int modifiers, char[] type, char[] name, int nameStart, int nameEnd) { - - int[] sourceRange = { declarationStart, -1 }; - int[] nameRange = { nameStart, nameEnd }; - boolean isSecondary = false; - if (fNode instanceof DOMField) { - isSecondary = declarationStart == fNode.fSourceRange[0]; - } - fNode = new DOMField(fDocument, sourceRange, CharArrayOps.charToString(name), nameRange, modifiers, CharArrayOps - .charToString(type), isSecondary); - addChild(fNode); - fStack.push(fNode); - } - - /** - * - */ - public void enterInitializer(int declarationSourceStart, int modifiers) { - int[] sourceRange = { declarationSourceStart, -1 }; - fNode = new DOMInitializer(fDocument, sourceRange, modifiers); - addChild(fNode); - fStack.push(fNode); - } - - /** - */ - public void enterInterface(int declarationStart, int modifiers, char[] name, int nameStart, int nameEnd, char[][] superinterfaces) { - enterType(declarationStart, modifiers, name, nameStart, nameEnd, null, superinterfaces, false); - } - - /** - */ - public void enterMethod(int declarationStart, int modifiers, char[] returnType, char[] name, int nameStart, int nameEnd, - char[][] parameterTypes, char[][] parameterNames, char[][] exceptionTypes) { - enterAbstractMethod(declarationStart, modifiers, returnType, name, nameStart, nameEnd, parameterTypes, parameterNames, - exceptionTypes, false); - } - - /** - */ - protected void enterType(int declarationStart, int modifiers, char[] name, int nameStart, int nameEnd, char[] superclass, - char[][] superinterfaces, boolean isClass) { - if (fBuildingType) { - int[] sourceRange = { declarationStart, -1 }; // will be fixed in the exit - int[] nameRange = new int[] { nameStart, nameEnd }; - fNode = new DOMType(fDocument, sourceRange, new String(name), nameRange, modifiers, CharArrayOps - .charcharToString(superinterfaces), isClass); - addChild(fNode); - fStack.push(fNode); - } - } - - /** - * Finishes the configuration of the class DOM object which was created by a previous enterClass call. - * - * @see ISourceElementRequestor#exitClass(int) - */ - public void exitClass(int declarationEnd) { - exitType(declarationEnd); - } - - /** - * Finishes the configuration of the method DOM object which was created by a previous enterConstructor call. - * - * @see ISourceElementRequestor#exitConstructor(int) - */ - public void exitConstructor(int declarationEnd) { - exitMember(declarationEnd); - } - - /** - */ - public void exitField(int initializationStart, int declarationEnd, int declarationSourceEnd) { - exitMember(declarationEnd); - } - - /** - */ - public void exitInitializer(int declarationEnd) { - exitMember(declarationEnd); - } - - /** - */ - public void exitInterface(int declarationEnd) { - exitType(declarationEnd); - } - - /** - * Finishes the configuration of the member. - * - * @param declarationEnd - - * a source position corresponding to the end of the method declaration. This can include whitespace and comments - * following the closing bracket. - */ - protected void exitMember(int declarationEnd) { - DOMMember m = (DOMMember) fStack.pop(); - m.setSourceRangeEnd(declarationEnd); - fNode = m; - } - - /** - */ - public void exitMethod(int declarationEnd) { - exitMember(declarationEnd); - } - - /** - * @see AbstractDOMBuilder#exitType - * - * @param declarationEnd - - * a source position corresponding to the end of the class declaration. This can include whitespace and comments - * following the closing bracket. - */ - protected void exitType(int declarationEnd) { - exitType(declarationEnd, declarationEnd); - } - - /** - * Creates a new parser. - */ - protected SourceElementParser getParser(Map settings) { - return new SourceElementParser(this, new DefaultProblemFactory(), new CompilerOptions(settings)); - } +public class SimpleDOMBuilder extends AbstractDOMBuilder implements + ISourceElementRequestor { + + public void acceptImport(int declarationStart, int declarationEnd, + char[] name, boolean onDemand) { + int[] sourceRange = { declarationStart, declarationEnd }; + String importName = new String(name); + /** name is set to contain the '*' */ + if (onDemand) { + importName += ".*"; //$NON-NLS-1$ + } + fNode = new DOMImport(fDocument, sourceRange, importName, onDemand); + addChild(fNode); + } + + public void acceptPackage(int declarationStart, int declarationEnd, + char[] name) { + int[] sourceRange = new int[] { declarationStart, declarationEnd }; + fNode = new DOMPackage(fDocument, sourceRange, CharArrayOps + .charToString(name)); + addChild(fNode); + } + + /** + * @see IDOMFactory#createCompilationUnit(String, String) + */ + public IDOMCompilationUnit createCompilationUnit(String sourceCode, + String name) { + return createCompilationUnit(sourceCode.toCharArray(), name + .toCharArray()); + } + + /** + * @see IDOMFactory#createCompilationUnit(String, String) + */ + public IDOMCompilationUnit createCompilationUnit( + ICompilationUnit compilationUnit) { + initializeBuild(compilationUnit.getContents(), true, true); + getParser(JavaCore.getOptions()).parseCompilationUnit(compilationUnit, + false); + return super.createCompilationUnit(compilationUnit); + } + + /** + * Creates a new DOMMethod and inizializes. + * + * @param declarationStart - + * a source position corresponding to the first character of this + * constructor declaration + * @param modifiers - + * the modifiers for this constructor converted to a flag + * @param returnType - + * the name of the return type + * @param name - + * the name of this constructor + * @param nameStart - + * a source position corresponding to the first character of the + * name + * @param nameEnd - + * a source position corresponding to the last character of the + * name + * @param parameterTypes - + * a list of parameter type names + * @param parameterNames - + * a list of the names of the parameters + * @param exceptionTypes - + * a list of the exception types + */ + protected void enterAbstractMethod(int declarationStart, int modifiers, + char[] returnType, char[] name, int nameStart, int nameEnd, + char[][] parameterTypes, char[][] parameterNames, + char[][] exceptionTypes, boolean isConstructor) { + + int[] sourceRange = { declarationStart, -1 }; // will be fixed up on + // exit + int[] nameRange = { nameStart, nameEnd }; + fNode = new DOMMethod(fDocument, sourceRange, CharArrayOps + .charToString(name), nameRange, modifiers, isConstructor, + CharArrayOps.charToString(returnType), CharArrayOps + .charcharToString(parameterTypes), CharArrayOps + .charcharToString(parameterNames), CharArrayOps + .charcharToString(exceptionTypes)); + addChild(fNode); + fStack.push(fNode); + } + + /** + */ + public void enterClass(int declarationStart, int modifiers, char[] name, + int nameStart, int nameEnd, char[] superclass, + char[][] superinterfaces) { + enterType(declarationStart, modifiers, name, nameStart, nameEnd, + superclass, superinterfaces, true); + } + + /** + */ + public void enterConstructor(int declarationStart, int modifiers, + char[] name, int nameStart, int nameEnd, char[][] parameterTypes, + char[][] parameterNames, char[][] exceptionTypes) { + /* see 1FVIIQZ */ + String nameString = new String(fDocument, nameStart, nameEnd + - nameStart); + int openParenPosition = nameString.indexOf('('); + if (openParenPosition > -1) + nameEnd = nameStart + openParenPosition - 1; + + enterAbstractMethod(declarationStart, modifiers, null, name, nameStart, + nameEnd, parameterTypes, parameterNames, exceptionTypes, true); + } + + /** + */ + public void enterField(int declarationStart, int modifiers, char[] type, + char[] name, int nameStart, int nameEnd) { + + int[] sourceRange = { declarationStart, -1 }; + int[] nameRange = { nameStart, nameEnd }; + boolean isSecondary = false; + if (fNode instanceof DOMField) { + isSecondary = declarationStart == fNode.fSourceRange[0]; + } + fNode = new DOMField(fDocument, sourceRange, CharArrayOps + .charToString(name), nameRange, modifiers, CharArrayOps + .charToString(type), isSecondary); + addChild(fNode); + fStack.push(fNode); + } + + /** + * + */ + public void enterInitializer(int declarationSourceStart, int modifiers) { + int[] sourceRange = { declarationSourceStart, -1 }; + fNode = new DOMInitializer(fDocument, sourceRange, modifiers); + addChild(fNode); + fStack.push(fNode); + } + + /** + */ + public void enterInterface(int declarationStart, int modifiers, + char[] name, int nameStart, int nameEnd, char[][] superinterfaces) { + enterType(declarationStart, modifiers, name, nameStart, nameEnd, null, + superinterfaces, false); + } + + /** + */ + public void enterMethod(int declarationStart, int modifiers, + char[] returnType, char[] name, int nameStart, int nameEnd, + char[][] parameterTypes, char[][] parameterNames, + char[][] exceptionTypes) { + enterAbstractMethod(declarationStart, modifiers, returnType, name, + nameStart, nameEnd, parameterTypes, parameterNames, + exceptionTypes, false); + } + + /** + */ + protected void enterType(int declarationStart, int modifiers, char[] name, + int nameStart, int nameEnd, char[] superclass, + char[][] superinterfaces, boolean isClass) { + if (fBuildingType) { + int[] sourceRange = { declarationStart, -1 }; // will be fixed in + // the exit + int[] nameRange = new int[] { nameStart, nameEnd }; + fNode = new DOMType(fDocument, sourceRange, new String(name), + nameRange, modifiers, CharArrayOps + .charcharToString(superinterfaces), isClass); + addChild(fNode); + fStack.push(fNode); + } + } + + /** + * Finishes the configuration of the class DOM object which was created by a + * previous enterClass call. + * + * @see ISourceElementRequestor#exitClass(int) + */ + public void exitClass(int declarationEnd) { + exitType(declarationEnd); + } + + /** + * Finishes the configuration of the method DOM object which was created by + * a previous enterConstructor call. + * + * @see ISourceElementRequestor#exitConstructor(int) + */ + public void exitConstructor(int declarationEnd) { + exitMember(declarationEnd); + } + + /** + */ + public void exitField(int initializationStart, int declarationEnd, + int declarationSourceEnd) { + exitMember(declarationEnd); + } + + /** + */ + public void exitInitializer(int declarationEnd) { + exitMember(declarationEnd); + } + + /** + */ + public void exitInterface(int declarationEnd) { + exitType(declarationEnd); + } + + /** + * Finishes the configuration of the member. + * + * @param declarationEnd - + * a source position corresponding to the end of the method + * declaration. This can include whitespace and comments + * following the closing bracket. + */ + protected void exitMember(int declarationEnd) { + DOMMember m = (DOMMember) fStack.pop(); + m.setSourceRangeEnd(declarationEnd); + fNode = m; + } + + /** + */ + public void exitMethod(int declarationEnd) { + exitMember(declarationEnd); + } + + /** + * @see AbstractDOMBuilder#exitType + * + * @param declarationEnd - + * a source position corresponding to the end of the class + * declaration. This can include whitespace and comments + * following the closing bracket. + */ + protected void exitType(int declarationEnd) { + exitType(declarationEnd, declarationEnd); + } + + /** + * Creates a new parser. + */ + protected SourceElementParser getParser(Map settings) { + return new SourceElementParser(this, new DefaultProblemFactory(), + new CompilerOptions(settings)); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ASTNodeFinder.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ASTNodeFinder.java index 571ced2..4c10a87 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ASTNodeFinder.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ASTNodeFinder.java @@ -38,12 +38,13 @@ public class ASTNodeFinder { } /* - * Finds the FieldDeclaration in the given ast corresponding to the given field handle. - * Returns null if not found. + * Finds the FieldDeclaration in the given ast corresponding to the given + * field handle. Returns null if not found. */ public FieldDeclaration findField(IField fieldHandle) { - TypeDeclaration typeDecl = findType((IType)fieldHandle.getParent()); - if (typeDecl == null) return null; + TypeDeclaration typeDecl = findType((IType) fieldHandle.getParent()); + if (typeDecl == null) + return null; FieldDeclaration[] fields = typeDecl.fields; if (fields != null) { char[] fieldName = fieldHandle.getElementName().toCharArray(); @@ -58,32 +59,33 @@ public class ASTNodeFinder { } /* - * Finds the Initializer in the given ast corresponding to the given initializer handle. - * Returns null if not found. + * Finds the Initializer in the given ast corresponding to the given + * initializer handle. Returns null if not found. */ -// public Initializer findInitializer(IInitializer initializerHandle) { -// TypeDeclaration typeDecl = findType((IType)initializerHandle.getParent()); -// if (typeDecl == null) return null; -// FieldDeclaration[] fields = typeDecl.fields; -// if (fields != null) { -// int occurenceCount = ((JavaElement)initializerHandle).occurrenceCount; -// for (int i = 0, length = fields.length; i < length; i++) { -// FieldDeclaration field = fields[i]; -// if (field instanceof Initializer && --occurenceCount == 0) { -// return (Initializer)field; -// } -// } -// } -// return null; -// } - + // public Initializer findInitializer(IInitializer initializerHandle) { + // TypeDeclaration typeDecl = + // findType((IType)initializerHandle.getParent()); + // if (typeDecl == null) return null; + // FieldDeclaration[] fields = typeDecl.fields; + // if (fields != null) { + // int occurenceCount = ((JavaElement)initializerHandle).occurrenceCount; + // for (int i = 0, length = fields.length; i < length; i++) { + // FieldDeclaration field = fields[i]; + // if (field instanceof Initializer && --occurenceCount == 0) { + // return (Initializer)field; + // } + // } + // } + // return null; + // } /* - * Finds the AbstractMethodDeclaration in the given ast corresponding to the given method handle. - * Returns null if not found. + * Finds the AbstractMethodDeclaration in the given ast corresponding to the + * given method handle. Returns null if not found. */ public AbstractMethodDeclaration findMethod(IMethod methodHandle) { - TypeDeclaration typeDecl = findType((IType)methodHandle.getParent()); - if (typeDecl == null) return null; + TypeDeclaration typeDecl = findType((IType) methodHandle.getParent()); + if (typeDecl == null) + return null; AbstractMethodDeclaration[] methods = typeDecl.methods; if (methods != null) { char[] selector = methodHandle.getElementName().toCharArray(); @@ -111,74 +113,83 @@ public class ASTNodeFinder { } /* - * Finds the TypeDeclaration in the given ast corresponding to the given type handle. - * Returns null if not found. + * Finds the TypeDeclaration in the given ast corresponding to the given + * type handle. Returns null if not found. */ public TypeDeclaration findType(IType typeHandle) { IJavaElement parent = typeHandle.getParent(); final char[] typeName = typeHandle.getElementName().toCharArray(); -// final int occurenceCount = ((SourceType)typeHandle).occurrenceCount; + // final int occurenceCount = ((SourceType)typeHandle).occurrenceCount; final boolean findAnonymous = typeName.length == 0; class Visitor extends ASTVisitor { TypeDeclaration result; + int count = 0; - public boolean visit(TypeDeclaration typeDeclaration, BlockScope scope) { - if (result != null) return false; -// if ((typeDeclaration.bits & ASTNode.IsAnonymousTypeMASK) != 0) { -// if (findAnonymous && ++count == occurenceCount) { -// result = typeDeclaration; -// } -// } else { - if (!findAnonymous && CharOperation.equals(typeName, typeDeclaration.name)) { - result = typeDeclaration; - } -// } + + public boolean visit(TypeDeclaration typeDeclaration, + BlockScope scope) { + if (result != null) + return false; + // if ((typeDeclaration.bits & ASTNode.IsAnonymousTypeMASK) != + // 0) { + // if (findAnonymous && ++count == occurenceCount) { + // result = typeDeclaration; + // } + // } else { + if (!findAnonymous + && CharOperation.equals(typeName, typeDeclaration.name)) { + result = typeDeclaration; + } + // } return false; // visit only one level } } switch (parent.getElementType()) { - case IJavaElement.COMPILATION_UNIT: - ArrayList types = this.unit.types; - if (types != null) { - for (int i = 0, length = types.size(); i < length; i++) { - TypeDeclaration type = (TypeDeclaration)types.get(i);//[i]; - if (CharOperation.equals(typeName, type.name)) { - return type; - } + case IJavaElement.COMPILATION_UNIT: + ArrayList types = this.unit.types; + if (types != null) { + for (int i = 0, length = types.size(); i < length; i++) { + TypeDeclaration type = (TypeDeclaration) types.get(i);// [i]; + if (CharOperation.equals(typeName, type.name)) { + return type; } } - break; - case IJavaElement.TYPE: - TypeDeclaration parentDecl = findType((IType)parent); - if (parentDecl == null) return null; -// types = parentDecl.memberTypes; -// if (types != null) { -// for (int i = 0, length = types.length; i < length; i++) { -// TypeDeclaration type = types[i]; -// if (CharOperation.equals(typeName, type.name)) { -// return type; -// } -// } -// } - break; - case IJavaElement.FIELD: - FieldDeclaration fieldDecl = findField((IField)parent); - if (fieldDecl == null) return null; - Visitor visitor = new Visitor(); - fieldDecl.traverse(visitor, null); - return visitor.result; -// case IJavaElement.INITIALIZER: -// Initializer initializer = findInitializer((IInitializer)parent); -// if (initializer == null) return null; -// visitor = new Visitor(); -// initializer.traverse(visitor, null); -// return visitor.result; - case IJavaElement.METHOD: - AbstractMethodDeclaration methodDecl = findMethod((IMethod)parent); - if (methodDecl == null) return null; - visitor = new Visitor(); - methodDecl.traverse(visitor, (ClassScope)null); - return visitor.result; + } + break; + case IJavaElement.TYPE: + TypeDeclaration parentDecl = findType((IType) parent); + if (parentDecl == null) + return null; + // types = parentDecl.memberTypes; + // if (types != null) { + // for (int i = 0, length = types.length; i < length; i++) { + // TypeDeclaration type = types[i]; + // if (CharOperation.equals(typeName, type.name)) { + // return type; + // } + // } + // } + break; + case IJavaElement.FIELD: + FieldDeclaration fieldDecl = findField((IField) parent); + if (fieldDecl == null) + return null; + Visitor visitor = new Visitor(); + fieldDecl.traverse(visitor, null); + return visitor.result; + // case IJavaElement.INITIALIZER: + // Initializer initializer = findInitializer((IInitializer)parent); + // if (initializer == null) return null; + // visitor = new Visitor(); + // initializer.traverse(visitor, null); + // return visitor.result; + case IJavaElement.METHOD: + AbstractMethodDeclaration methodDecl = findMethod((IMethod) parent); + if (methodDecl == null) + return null; + visitor = new Visitor(); + methodDecl.traverse(visitor, (ClassScope) null); + return visitor.result; } return null; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/CharArrayBuffer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/CharArrayBuffer.java index 38be3f8..8aecc50 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/CharArrayBuffer.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/CharArrayBuffer.java @@ -11,25 +11,28 @@ package net.sourceforge.phpdt.internal.core.util; /** - * The CharArrayBuffer is intended as a lightweight partial implementation - * of the StringBuffer class, but using char[]'s instead of Strings. - * - *

                                                      The CharArrayBuffer maintains a list of char[]'s - * which don't get appended until the user asks for them. The following - * code illustrates how to use the class. - * + * The CharArrayBuffer is intended as a lightweight partial + * implementation of the StringBuffer class, but using char[]'s + * instead of Strings. + * + *

                                                      + * The CharArrayBuffer maintains a list of char[]'s + * which don't get appended until the user asks for them. The following code + * illustrates how to use the class. + * * * CharArrayBuffer buffer = new CharArrayBuffer(myCharArray); * buffer.append(moreBytes, 0, someLength); * myCharArray = buffer.getContents(); * - * - *

                                                      NOTE: This class is not Thread safe! + * + *

                                                      + * NOTE: This class is not Thread safe! */ public class CharArrayBuffer { /** - * This is the buffer of char arrays which must be appended together - * during the getContents method. + * This is the buffer of char arrays which must be appended together during + * the getContents method. */ protected char[][] fBuffer; @@ -49,143 +52,173 @@ public class CharArrayBuffer { protected int fSize; /** - * A buffer of ranges which is maintained along with - * the buffer. Ranges are of the form {start, length}. - * Enables append(char[] array, int start, int end). + * A buffer of ranges which is maintained along with the buffer. Ranges are + * of the form {start, length}. Enables append(char[] array, int start, int + * end). */ protected int[][] fRanges; -/** - * Creates a CharArrayBuffer with the default buffer size (10). - */ -public CharArrayBuffer() { - this(null, DEFAULT_BUFFER_SIZE); -} -/** - * Creates a CharArrayBuffer with the default buffer size, - * and sets the first element in the buffer to be the given char[]. - * - * @param first - the first element to be placed in the buffer, ignored if null - */ -public CharArrayBuffer(char[] first) { - this(first, DEFAULT_BUFFER_SIZE); -} -/** - * Creates a CharArrayBuffer with the given buffer size, - * and sets the first element in the buffer to be the given char array. - * - * @param first - the first element of the buffer, ignored if null. - * @param size - the buffer size, if less than 1, set to the DEFAULT_BUFFER_SIZE. - */ -public CharArrayBuffer(char[] first, int size) { - fSize = (size > 0) ? size : DEFAULT_BUFFER_SIZE; - fBuffer = new char[fSize][]; - fRanges = new int[fSize][]; - fEnd = 0; - if (first != null) - append(first, 0, first.length); -} -/** - * Creates a CharArrayBuffer with the given buffer size. - * - * @param size - the size of the buffer. - */ -public CharArrayBuffer(int size) { - this(null, size); -} -/** - * Appends the entire given char array. Given for convenience. - * - * @param src - a char array which is appended to the end of the buffer. - */ -public CharArrayBuffer append(char[] src) { - if (src != null) - append(src, 0, src.length); - return this; -} -/** - * Appends a sub array of the given array to the buffer. - * - * @param src - the next array of characters to be appended to the buffer, ignored if null - * @param start - the start index in the src array. - * @param length - the number of characters from start to be appended - * - * @throws ArrayIndexOutOfBoundsException - if arguments specify an array index out of bounds. - */ -public CharArrayBuffer append(char[] src, int start, int length) { - if (start < 0) throw new ArrayIndexOutOfBoundsException(); - if (length < 0) throw new ArrayIndexOutOfBoundsException(); - if (src != null) { - int srcLength = src.length; - if (start > srcLength) throw new ArrayIndexOutOfBoundsException(); - if (length + start > srcLength) throw new ArrayIndexOutOfBoundsException(); - /** do length check here to allow exceptions to be thrown */ - if (length > 0) { - if (fEnd == fSize) { - int size2 = fSize * 2; - System.arraycopy(fBuffer, 0, (fBuffer = new char[size2][]), 0, fSize); - System.arraycopy(fRanges, 0, (fRanges = new int[size2][]), 0, fSize); - fSize *= 2; + + /** + * Creates a CharArrayBuffer with the default buffer size + * (10). + */ + public CharArrayBuffer() { + this(null, DEFAULT_BUFFER_SIZE); + } + + /** + * Creates a CharArrayBuffer with the default buffer size, + * and sets the first element in the buffer to be the given char[]. + * + * @param first - + * the first element to be placed in the buffer, ignored if null + */ + public CharArrayBuffer(char[] first) { + this(first, DEFAULT_BUFFER_SIZE); + } + + /** + * Creates a CharArrayBuffer with the given buffer size, and + * sets the first element in the buffer to be the given char array. + * + * @param first - + * the first element of the buffer, ignored if null. + * @param size - + * the buffer size, if less than 1, set to the + * DEFAULT_BUFFER_SIZE. + */ + public CharArrayBuffer(char[] first, int size) { + fSize = (size > 0) ? size : DEFAULT_BUFFER_SIZE; + fBuffer = new char[fSize][]; + fRanges = new int[fSize][]; + fEnd = 0; + if (first != null) + append(first, 0, first.length); + } + + /** + * Creates a CharArrayBuffer with the given buffer size. + * + * @param size - + * the size of the buffer. + */ + public CharArrayBuffer(int size) { + this(null, size); + } + + /** + * Appends the entire given char array. Given for convenience. + * + * @param src - + * a char array which is appended to the end of the buffer. + */ + public CharArrayBuffer append(char[] src) { + if (src != null) + append(src, 0, src.length); + return this; + } + + /** + * Appends a sub array of the given array to the buffer. + * + * @param src - + * the next array of characters to be appended to the buffer, + * ignored if null + * @param start - + * the start index in the src array. + * @param length - + * the number of characters from start to be appended + * + * @throws ArrayIndexOutOfBoundsException - + * if arguments specify an array index out of bounds. + */ + public CharArrayBuffer append(char[] src, int start, int length) { + if (start < 0) + throw new ArrayIndexOutOfBoundsException(); + if (length < 0) + throw new ArrayIndexOutOfBoundsException(); + if (src != null) { + int srcLength = src.length; + if (start > srcLength) + throw new ArrayIndexOutOfBoundsException(); + if (length + start > srcLength) + throw new ArrayIndexOutOfBoundsException(); + /** do length check here to allow exceptions to be thrown */ + if (length > 0) { + if (fEnd == fSize) { + int size2 = fSize * 2; + System.arraycopy(fBuffer, 0, (fBuffer = new char[size2][]), + 0, fSize); + System.arraycopy(fRanges, 0, (fRanges = new int[size2][]), + 0, fSize); + fSize *= 2; + } + fBuffer[fEnd] = src; + fRanges[fEnd] = new int[] { start, length }; + fEnd++; } - fBuffer[fEnd] = src; - fRanges[fEnd] = new int[] {start, length}; - fEnd++; } + return this; + } + + /** + * Appends the given char. Given for convenience. + * + * @param src - + * a char which is appended to the end of the buffer. + */ + public CharArrayBuffer append(char c) { + append(new char[] { c }, 0, 1); + return this; } - return this; -} -/** - * Appends the given char. Given for convenience. - * - * @param src - a char which is appended to the end of the buffer. - */ -public CharArrayBuffer append(char c) { - append(new char[] {c}, 0, 1); - return this; -} -/** - * Appends the given String to the buffer. Given for convenience, use - * #append(char[]) if possible - * - * @param src - a char array which is appended to the end of the buffer. - */ -public CharArrayBuffer append(String src) { - if (src != null) - append(src.toCharArray(), 0, src.length()); - return this; -} -/** - * Returns the entire contents of the buffer as one - * char[] or null if nothing has been put in the buffer. - */ -public char[] getContents() { - if (fEnd == 0) - return null; - // determine the size of the array - int size = 0; - for (int i = 0; i < fEnd; i++) - size += fRanges[i][1]; - - if (size > 0) { - char[] result = new char[size]; - int current = 0; - // copy the results - for(int i = 0; i < fEnd; i++) { - int[] range = fRanges[i]; - int length = range[1]; - System.arraycopy(fBuffer[i], range[0], result, current, length); - current += length; + /** + * Appends the given String to the buffer. Given for convenience, use + * #append(char[]) if possible + * + * @param src - + * a char array which is appended to the end of the buffer. + */ + public CharArrayBuffer append(String src) { + if (src != null) + append(src.toCharArray(), 0, src.length()); + return this; + } + + /** + * Returns the entire contents of the buffer as one char[] or null if + * nothing has been put in the buffer. + */ + public char[] getContents() { + if (fEnd == 0) + return null; + + // determine the size of the array + int size = 0; + for (int i = 0; i < fEnd; i++) + size += fRanges[i][1]; + + if (size > 0) { + char[] result = new char[size]; + int current = 0; + // copy the results + for (int i = 0; i < fEnd; i++) { + int[] range = fRanges[i]; + int length = range[1]; + System.arraycopy(fBuffer[i], range[0], result, current, length); + current += length; + } + return result; } - return result; + return null; + } + + /** + * Returns the contents of the buffer as a String, or null if + * the buffer is empty. + */ + public String toString() { + char[] contents = getContents(); + return (contents != null) ? new String(contents) : null; } - return null; -} -/** - * Returns the contents of the buffer as a String, or - * null if the buffer is empty. - */ -public String toString() { - char[] contents = getContents(); - return (contents != null) ? new String(contents) : null; -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/CharArrayOps.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/CharArrayOps.java index 7041eb4..119b1f6 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/CharArrayOps.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/CharArrayOps.java @@ -11,135 +11,147 @@ package net.sourceforge.phpdt.internal.core.util; /** - * A class to do characters operations so that we can use - * char arrays more effectively. + * A class to do characters operations so that we can use char arrays more + * effectively. */ public class CharArrayOps { // TODO: should promote to CharOperation -/** - * Returns the char arrays as an array of Strings - */ -public static String[] charcharToString(char[][] charchar) { - if (charchar == null) { - return null; + /** + * Returns the char arrays as an array of Strings + */ + public static String[] charcharToString(char[][] charchar) { + if (charchar == null) { + return null; + } + String[] strings = new String[charchar.length]; + for (int i = 0; i < charchar.length; i++) { + strings[i] = new String(charchar[i]); + } + return strings; } - String[] strings= new String[charchar.length]; - for (int i= 0; i < charchar.length; i++) { - strings[i]= new String(charchar[i]); + + /** + * Returns the char array as a String + */ + public static String charToString(char[] chars) { + if (chars == null) { + return null; + } else { + return new String(chars); + } } - return strings; -} -/** - * Returns the char array as a String - */ -public static String charToString(char[] chars) { - if (chars == null) { - return null; - } else { - return new String(chars); + + /** + * Concatinates the two arrays into one big array. If the first array is + * null, returns the second array. If the second array is null, returns the + * first array. + * + * @param first - + * the array which the other array is concatinated onto + * @param second - + * the array which is to be concatinated onto the first array + */ + public static char[] concat(char[] first, char[] second) { + if (first == null) + return second; + if (second == null) + return first; + + int length1 = first.length; + int length2 = second.length; + char[] result = new char[length1 + length2]; + System.arraycopy(first, 0, result, 0, length1); + System.arraycopy(second, 0, result, length1, length2); + return result; } -} -/** - * Concatinates the two arrays into one big array. - * If the first array is null, returns the second array. - * If the second array is null, returns the first array. - * - * @param first - the array which the other array is concatinated onto - * @param second - the array which is to be concatinated onto the first array - */ -public static char[] concat(char[] first, char[] second) { - if (first == null) - return second; - if (second == null) - return first; - int length1 = first.length; - int length2 = second.length; - char[] result = new char[length1 + length2]; - System.arraycopy(first, 0, result, 0, length1); - System.arraycopy(second, 0, result, length1, length2); - return result; -} -/** - * Checks the two character arrays for equality. - * - * @param first - one of the arrays to be compared - * @param second - the other array which is to be compared - */ -public static boolean equals(char[] first, char[] second) { - if (first == second) + /** + * Checks the two character arrays for equality. + * + * @param first - + * one of the arrays to be compared + * @param second - + * the other array which is to be compared + */ + public static boolean equals(char[] first, char[] second) { + if (first == second) + return true; + if (first == null || second == null) + return false; + if (first.length != second.length) + return false; + + for (int i = 0, length = first.length; i < length; i++) + if (first[i] != second[i]) + return false; return true; - if (first == null || second == null) - return false; - if (first.length != second.length) - return false; + } - for (int i = 0, length = first.length; i < length; i++) - if (first[i] != second[i]) - return false; - return true; -} -/** - * Returns the index of the first occurrence of character in buffer, - * starting from offset, or -1 if not found. - */ -public static int indexOf(char character, char[] buffer, int offset) { - for (int i= offset; i < buffer.length; i++) { - if (buffer[i] == character) { - return i; + /** + * Returns the index of the first occurrence of character in buffer, + * starting from offset, or -1 if not found. + */ + public static int indexOf(char character, char[] buffer, int offset) { + for (int i = offset; i < buffer.length; i++) { + if (buffer[i] == character) { + return i; + } } + return -1; } - return -1; -} -/** - * Extracts a sub-array from the given array, starting - * at the given startIndex and proceeding for length characters. - * Returns null if: - * 1. the src array is null - * 2. the start index is out of bounds - * 3. the length parameter specifies a end point which is out of bounds - * Does not return a copy of the array if possible, in other words, if start is zero - * and length equals the length of the src array. - * - * @param src - the array from which elements need to be copied - * @param start - the start index in the src array - * @param length - the number of characters to copy - */ -public static char[] subarray(char[] src, int start, int length) { - if (src == null) - return null; - int srcLength = src.length; - if (start < 0 || start >= srcLength) - return null; - if (length < 0 || start + length > srcLength) - return null; - if (srcLength == length && start == 0) - return src; - - char[] result = new char[length]; - if (length > 0) - System.arraycopy(src, start, result, 0, length); - return result; -} -/** - * Extracts a substring from the given array, starting - * at the given startIndex and proceeding for length characters. - * Returns null if: - * 1. the src array is null - * 2. the start index is out of bounds - * 3. the length parameter specifies a end point which is out of bounds - * Does not return a copy of the array if possible (if start is zero - * and length equals the length of the src array). - * - * @param src - the array from which elements need to be copied - * @param start - the start index in the src array - * @param length - the number of characters to copy - */ -public static String substring(char[] src, int start, int length) { - char[] chars= subarray(src, start, length); - if (chars != null) { - return new String(chars); - } else { - return null; + + /** + * Extracts a sub-array from the given array, starting at the given + * startIndex and proceeding for length characters. Returns null if: 1. the + * src array is null 2. the start index is out of bounds 3. the length + * parameter specifies a end point which is out of bounds Does not return a + * copy of the array if possible, in other words, if start is zero and + * length equals the length of the src array. + * + * @param src - + * the array from which elements need to be copied + * @param start - + * the start index in the src array + * @param length - + * the number of characters to copy + */ + public static char[] subarray(char[] src, int start, int length) { + if (src == null) + return null; + int srcLength = src.length; + if (start < 0 || start >= srcLength) + return null; + if (length < 0 || start + length > srcLength) + return null; + if (srcLength == length && start == 0) + return src; + + char[] result = new char[length]; + if (length > 0) + System.arraycopy(src, start, result, 0, length); + return result; + } + + /** + * Extracts a substring from the given array, starting at the given + * startIndex and proceeding for length characters. Returns null if: 1. the + * src array is null 2. the start index is out of bounds 3. the length + * parameter specifies a end point which is out of bounds Does not return a + * copy of the array if possible (if start is zero and length equals the + * length of the src array). + * + * @param src - + * the array from which elements need to be copied + * @param start - + * the start index in the src array + * @param length - + * the number of characters to copy + */ + public static String substring(char[] src, int start, int length) { + char[] chars = subarray(src, start, length); + if (chars != null) { + return new String(chars); + } else { + return null; + } } -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/CommentRecorderParser.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/CommentRecorderParser.java index 25ff589..a3bee75 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/CommentRecorderParser.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/CommentRecorderParser.java @@ -22,97 +22,115 @@ import net.sourceforge.phpdt.internal.compiler.problem.ProblemSeverities; * @since 3.0 */ public class CommentRecorderParser extends UnitParser { - + // support for comments int[] commentStops = new int[10]; + int[] commentStarts = new int[10]; + int commentPtr = -1; // no comment test with commentPtr value -1 + protected final static int CommentIncrement = 100; /** * @param problemReporter * @param optimizeStringLiterals */ - public CommentRecorderParser(ProblemReporter problemReporter) { // , boolean optimizeStringLiterals) { - super(problemReporter); //, optimizeStringLiterals); + public CommentRecorderParser(ProblemReporter problemReporter) { // , boolean + // optimizeStringLiterals) + // { + super(problemReporter); // , optimizeStringLiterals); } - // old javadoc style check which doesn't include all leading comments into declaration - // for backward compatibility with 2.1 DOM -// public void checkComment() { -// -// if (this.currentElement != null && this.scanner.commentPtr >= 0) { -// flushCommentsDefinedPriorTo(this.endStatementPosition); // discard obsolete comments -// } -// boolean deprecated = false; -// boolean checkDeprecated = false; -// int lastCommentIndex = -1; -// -// // -// -// //since jdk1.2 look only in the last java doc comment... -// nextComment : for (lastCommentIndex = this.scanner.commentPtr; lastCommentIndex >= 0; lastCommentIndex--){ -// //look for @deprecated into the first javadoc comment preceeding the declaration -// int commentSourceStart = this.scanner.commentStarts[lastCommentIndex]; -// // javadoc only (non javadoc comment have negative end positions.) -// if ((commentSourceStart < 0) || -// (this.modifiersSourceStart != -1 && this.modifiersSourceStart < commentSourceStart) || -// (this.scanner.commentStops[lastCommentIndex] < 0)) -// { -// continue nextComment; -// } -// checkDeprecated = true; -// int commentSourceEnd = this.scanner.commentStops[lastCommentIndex] - 1; //stop is one over -// -// deprecated = this.javadocParser.checkDeprecation(commentSourceStart, commentSourceEnd); -// this.javadoc = this.javadocParser.docComment; -// break nextComment; -// } -// if (deprecated) { -// checkAndSetModifiers(AccDeprecated); -// } -// // modify the modifier source start to point at the first comment -// if (lastCommentIndex >= 0 && checkDeprecated) { -// this.modifiersSourceStart = this.scanner.commentStarts[lastCommentIndex]; -// if (this.modifiersSourceStart < 0) { -// this.modifiersSourceStart = -this.modifiersSourceStart; -// } -// } -// -// } + // old javadoc style check which doesn't include all leading comments into + // declaration + // for backward compatibility with 2.1 DOM + // public void checkComment() { + // + // if (this.currentElement != null && this.scanner.commentPtr >= 0) { + // flushCommentsDefinedPriorTo(this.endStatementPosition); // discard + // obsolete comments + // } + // boolean deprecated = false; + // boolean checkDeprecated = false; + // int lastCommentIndex = -1; + // + // // + // + // //since jdk1.2 look only in the last java doc comment... + // nextComment : for (lastCommentIndex = this.scanner.commentPtr; + // lastCommentIndex >= 0; lastCommentIndex--){ + // //look for @deprecated into the first javadoc comment preceeding the + // declaration + // int commentSourceStart = this.scanner.commentStarts[lastCommentIndex]; + // // javadoc only (non javadoc comment have negative end positions.) + // if ((commentSourceStart < 0) || + // (this.modifiersSourceStart != -1 && this.modifiersSourceStart < + // commentSourceStart) || + // (this.scanner.commentStops[lastCommentIndex] < 0)) + // { + // continue nextComment; + // } + // checkDeprecated = true; + // int commentSourceEnd = this.scanner.commentStops[lastCommentIndex] - 1; + // //stop is one over + // + // deprecated = this.javadocParser.checkDeprecation(commentSourceStart, + // commentSourceEnd); + // this.javadoc = this.javadocParser.docComment; + // break nextComment; + // } + // if (deprecated) { + // checkAndSetModifiers(AccDeprecated); + // } + // // modify the modifier source start to point at the first comment + // if (lastCommentIndex >= 0 && checkDeprecated) { + // this.modifiersSourceStart = this.scanner.commentStarts[lastCommentIndex]; + // if (this.modifiersSourceStart < 0) { + // this.modifiersSourceStart = -this.modifiersSourceStart; + // } + // } + // + // } -// /* (non-Javadoc) -// * @see net.sourceforge.phpdt.internal.compiler.parser.Parser#consumeClassHeader() -// */ -// protected void consumeClassHeader() { -// pushOnCommentsStack(0, this.scanner.commentPtr); -// super.consumeClassHeader(); -// } -// /* (non-Javadoc) -// * @see net.sourceforge.phpdt.internal.compiler.parser.Parser#consumeEmptyClassMemberDeclaration() -// */ -// protected void consumeEmptyClassMemberDeclaration() { -// pushOnCommentsStack(0, this.scanner.commentPtr); -// super.consumeEmptyClassMemberDeclaration(); -// } -// /* (non-Javadoc) -// * @see net.sourceforge.phpdt.internal.compiler.parser.Parser#consumeEmptyTypeDeclaration() -// */ -// protected void consumeEmptyTypeDeclaration() { -// pushOnCommentsStack(0, this.scanner.commentPtr); -// super.consumeEmptyTypeDeclaration(); -// } -// /* (non-Javadoc) -// * @see net.sourceforge.phpdt.internal.compiler.parser.Parser#consumeInterfaceHeader() -// */ -// protected void consumeInterfaceHeader() { -// pushOnCommentsStack(0, this.scanner.commentPtr); -// super.consumeInterfaceHeader(); -// } + // /* (non-Javadoc) + // * @see + // net.sourceforge.phpdt.internal.compiler.parser.Parser#consumeClassHeader() + // */ + // protected void consumeClassHeader() { + // pushOnCommentsStack(0, this.scanner.commentPtr); + // super.consumeClassHeader(); + // } + // /* (non-Javadoc) + // * @see + // net.sourceforge.phpdt.internal.compiler.parser.Parser#consumeEmptyClassMemberDeclaration() + // */ + // protected void consumeEmptyClassMemberDeclaration() { + // pushOnCommentsStack(0, this.scanner.commentPtr); + // super.consumeEmptyClassMemberDeclaration(); + // } + // /* (non-Javadoc) + // * @see + // net.sourceforge.phpdt.internal.compiler.parser.Parser#consumeEmptyTypeDeclaration() + // */ + // protected void consumeEmptyTypeDeclaration() { + // pushOnCommentsStack(0, this.scanner.commentPtr); + // super.consumeEmptyTypeDeclaration(); + // } + // /* (non-Javadoc) + // * @see + // net.sourceforge.phpdt.internal.compiler.parser.Parser#consumeInterfaceHeader() + // */ + // protected void consumeInterfaceHeader() { + // pushOnCommentsStack(0, this.scanner.commentPtr); + // super.consumeInterfaceHeader(); + // } /** * Insure that start position is always positive. - * @see net.sourceforge.phpdt.internal.compiler.parser.Parser#containsComment(int, int) + * + * @see net.sourceforge.phpdt.internal.compiler.parser.Parser#containsComment(int, + * int) */ public boolean containsComment(int sourceStart, int sourceEnd) { int iComment = this.scanner.commentPtr; @@ -122,15 +140,19 @@ public class CommentRecorderParser extends UnitParser { commentStart = -commentStart; } // ignore comments before start - if (commentStart < sourceStart) continue; + if (commentStart < sourceStart) + continue; // ignore comments after end - if (commentStart > sourceEnd) continue; + if (commentStart > sourceEnd) + continue; return true; } return false; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpdt.internal.compiler.parser.Parser#endParse(int) */ protected CompilationUnitDeclaration endParse(int act) { @@ -142,119 +164,154 @@ public class CommentRecorderParser extends UnitParser { return unit; } - /* (non-Javadoc) - * Save all source comments currently stored before flushing them. + /* + * (non-Javadoc) Save all source comments currently stored before flushing + * them. + * * @see net.sourceforge.phpdt.internal.compiler.parser.Parser#flushCommentsDefinedPriorTo(int) */ public int flushCommentsDefinedPriorTo(int position) { int lastCommentIndex = this.scanner.commentPtr; - if (lastCommentIndex < 0) return position; // no comment - + if (lastCommentIndex < 0) + return position; // no comment + // compute the index of the first obsolete comment int index = lastCommentIndex; int validCount = 0; - while (index >= 0){ + while (index >= 0) { int commentEnd = this.scanner.commentStops[index]; - if (commentEnd < 0) commentEnd = -commentEnd; // negative end position for non-javadoc comments - if (commentEnd <= position){ + if (commentEnd < 0) + commentEnd = -commentEnd; // negative end position for + // non-javadoc comments + if (commentEnd <= position) { break; } index--; validCount++; } - // if the source at is immediately followed by a line comment, then + // if the source at is immediately followed by a line + // comment, then // flush this comment and shift to the comment end. - if (validCount > 0){ + if (validCount > 0) { int immediateCommentEnd = 0; - while (index 0){ // only tolerating non-javadoc comments (non-javadoc comment end positions are negative) - // is there any line break until the end of the immediate comment ? (thus only tolerating line comment) + while (index < lastCommentIndex + && (immediateCommentEnd = -this.scanner.commentStops[index + 1]) > 0) { // only + // tolerating + // non-javadoc + // comments + // (non-javadoc + // comment + // end + // positions + // are + // negative) + // is there any line break until the end of the immediate + // comment ? (thus only tolerating line comment) immediateCommentEnd--; // comment end in one char too far - if (this.scanner.getLineNumber(position) != this.scanner.getLineNumber(immediateCommentEnd)) break; + if (this.scanner.getLineNumber(position) != this.scanner + .getLineNumber(immediateCommentEnd)) + break; position = immediateCommentEnd; validCount--; // flush this comment index++; } } - - if (index < 0) return position; // no obsolete comment + + if (index < 0) + return position; // no obsolete comment pushOnCommentsStack(0, index); // store comment before flushing them - if (validCount > 0){ // move valid comment infos, overriding obsolete comment infos - System.arraycopy(this.scanner.commentStarts, index + 1, this.scanner.commentStarts, 0, validCount); - System.arraycopy(this.scanner.commentStops, index + 1, this.scanner.commentStops, 0, validCount); + if (validCount > 0) { // move valid comment infos, overriding obsolete + // comment infos + System.arraycopy(this.scanner.commentStarts, index + 1, + this.scanner.commentStarts, 0, validCount); + System.arraycopy(this.scanner.commentStops, index + 1, + this.scanner.commentStops, 0, validCount); } this.scanner.commentPtr = validCount - 1; return position; } /* - * Build a n*2 matrix of comments positions. - * For each position, 0 is for start position and 1 for end position of the comment. + * Build a n*2 matrix of comments positions. For each position, 0 is for + * start position and 1 for end position of the comment. */ public int[][] getCommentsPositions() { - int[][] positions = new int[this.commentPtr+1][2]; - for (int i = 0, max = this.commentPtr; i <= max; i++){ + int[][] positions = new int[this.commentPtr + 1][2]; + for (int i = 0, max = this.commentPtr; i <= max; i++) { positions[i][0] = this.commentStarts[i]; positions[i][1] = this.commentStops[i]; } return positions; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpdt.internal.compiler.parser.Parser#initialize() */ public void initialize(boolean phpMode) { super.initialize(phpMode); this.commentPtr = -1; } - - /* (non-Javadoc) - * Create and store a specific comment recorder scanner. + + /* + * (non-Javadoc) Create and store a specific comment recorder scanner. + * * @see net.sourceforge.phpdt.internal.compiler.parser.Parser#initializeScanner() */ public void initializeScanner() { this.scanner = new CommentRecorderScanner( - false /*comment*/, - false /*whitespace*/, - this.options.getSeverity(CompilerOptions.NonExternalizedString) != ProblemSeverities.Ignore /*nls*/, -// this.options.sourceLevel /*sourceLevel*/, - this.options.taskTags/*taskTags*/, - this.options.taskPriorites);/*taskPriorities*/ -// this.options.isTaskCaseSensitive/*taskCaseSensitive*/); + false /* comment */, + false /* whitespace */, + this.options.getSeverity(CompilerOptions.NonExternalizedString) != ProblemSeverities.Ignore /* nls */, + // this.options.sourceLevel /*sourceLevel*/, + this.options.taskTags/* taskTags */, this.options.taskPriorites);/* taskPriorities */ + // this.options.isTaskCaseSensitive/*taskCaseSensitive*/); } /* * Push all stored comments in stack. */ private void pushOnCommentsStack(int start, int end) { - - for (int i=start; i<=end; i++) { + + for (int i = start; i <= end; i++) { // First see if comment hasn't been already stored - int scannerStart = this.scanner.commentStarts[i]<0 ? -this.scanner.commentStarts[i] : this.scanner.commentStarts[i]; - int commentStart = this.commentPtr == -1 ? -1 : (this.commentStarts[this.commentPtr]<0 ? -this.commentStarts[this.commentPtr] : this.commentStarts[this.commentPtr]); - if (commentStart == -1 || scannerStart > commentStart) { + int scannerStart = this.scanner.commentStarts[i] < 0 ? -this.scanner.commentStarts[i] + : this.scanner.commentStarts[i]; + int commentStart = this.commentPtr == -1 ? -1 + : (this.commentStarts[this.commentPtr] < 0 ? -this.commentStarts[this.commentPtr] + : this.commentStarts[this.commentPtr]); + if (commentStart == -1 || scannerStart > commentStart) { try { this.commentPtr++; this.commentStarts[this.commentPtr] = this.scanner.commentStarts[i]; this.commentStops[this.commentPtr] = this.scanner.commentStops[i]; } catch (IndexOutOfBoundsException e) { - // this.commentPtr is still correct + // this.commentPtr is still correct int oldStackLength = this.commentStarts.length; int oldCommentStarts[] = this.commentStarts; - this.commentStarts = new int[oldStackLength + CommentIncrement]; - System.arraycopy(oldCommentStarts, 0, this.commentStarts, 0, oldStackLength); + this.commentStarts = new int[oldStackLength + + CommentIncrement]; + System.arraycopy(oldCommentStarts, 0, this.commentStarts, + 0, oldStackLength); this.commentStarts[this.commentPtr] = this.scanner.commentStarts[i]; int oldCommentStops[] = this.commentStops; - this.commentStops = new int[oldStackLength + CommentIncrement]; - System.arraycopy(oldCommentStops, 0, this.commentStops, 0, oldStackLength); + this.commentStops = new int[oldStackLength + + CommentIncrement]; + System.arraycopy(oldCommentStops, 0, this.commentStops, 0, + oldStackLength); this.commentStops[this.commentPtr] = this.scanner.commentStops[i]; } } } } - /* (non-Javadoc) - * Save all source comments currently stored before flushing them. + + /* + * (non-Javadoc) Save all source comments currently stored before flushing + * them. + * * @see net.sourceforge.phpdt.internal.compiler.parser.Parser#resetModifiers() */ protected void resetModifiers() { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/CommentRecorderScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/CommentRecorderScanner.java index 6abef12..fc68d4f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/CommentRecorderScanner.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/CommentRecorderScanner.java @@ -19,25 +19,24 @@ import net.sourceforge.phpdt.internal.compiler.parser.Scanner; */ public class CommentRecorderScanner extends Scanner { - public CommentRecorderScanner( - boolean tokenizeComments, - boolean tokenizeWhiteSpace, - boolean checkNonExternalizedStringLiterals, -// long sourceLevel, - char[][] taskTags, - char[][] taskPriorities) { -// boolean isTaskCaseSensitive) { -// super(tokenizeComments, tokenizeWhiteSpace, -// checkNonExternalizedStringLiterals, -// sourceLevel, -// taskTags, taskPriorities, isTaskCaseSensitive); - super(tokenizeComments, tokenizeWhiteSpace, - checkNonExternalizedStringLiterals, false, false, - taskTags, taskPriorities, true /*taskCaseSensitive*/); + public CommentRecorderScanner(boolean tokenizeComments, + boolean tokenizeWhiteSpace, + boolean checkNonExternalizedStringLiterals, + // long sourceLevel, + char[][] taskTags, char[][] taskPriorities) { + // boolean isTaskCaseSensitive) { + // super(tokenizeComments, tokenizeWhiteSpace, + // checkNonExternalizedStringLiterals, + // sourceLevel, + // taskTags, taskPriorities, isTaskCaseSensitive); + super(tokenizeComments, tokenizeWhiteSpace, + checkNonExternalizedStringLiterals, false, false, taskTags, + taskPriorities, true /* taskCaseSensitive */); } - + /** * Set start position negative for line comments. + * * @see net.sourceforge.phpdt.internal.compiler.parser.Scanner#recordComment(int) */ public void recordComment(int token) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ICacheEnumeration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ICacheEnumeration.java index 1c77c5e..a170c32 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ICacheEnumeration.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ICacheEnumeration.java @@ -13,26 +13,29 @@ package net.sourceforge.phpdt.internal.core.util; import java.util.Enumeration; /** - * The ICacheEnumeration is used to iterate over both the keys - * and values in an LRUCache. The getValue() method returns the - * value of the last key to be retrieved using nextElement(). - * The nextElement() method must be called before the + * The ICacheEnumeration is used to iterate over both the keys + * and values in an LRUCache. The getValue() method returns the + * value of the last key to be retrieved using nextElement(). + * The nextElement() method must be called before the * getValue() method. - * - *

                                                      The iteration can be made efficient by making use of the fact that values in - * the cache (instances of LRUCacheEntry), know their key. For this reason, - * Hashtable lookups don't have to be made at each step of the iteration. - * - *

                                                      Modifications to the cache must not be performed while using the - * enumeration. Doing so will lead to an illegal state. - * + * + *

                                                      + * The iteration can be made efficient by making use of the fact that values in + * the cache (instances of LRUCacheEntry), know their key. For + * this reason, Hashtable lookups don't have to be made at each step of the + * iteration. + * + *

                                                      + * Modifications to the cache must not be performed while using the enumeration. + * Doing so will lead to an illegal state. + * * @see LRUCache */ public interface ICacheEnumeration extends Enumeration { /** - * Returns the value of the previously accessed key in the enumeration. - * Must be called after a call to nextElement(). - * + * Returns the value of the previously accessed key in the enumeration. Must + * be called after a call to nextElement(). + * * @return Value of current cache entry */ public Object getValue(); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ILRUCacheable.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ILRUCacheable.java index 6c5662f..3d138bc 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ILRUCacheable.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ILRUCacheable.java @@ -11,17 +11,17 @@ package net.sourceforge.phpdt.internal.core.util; /** - * Types implementing this interface can occupy a variable amount of space - * in an LRUCache. Cached items that do not implement this interface are - * considered to occupy one unit of space. - * + * Types implementing this interface can occupy a variable amount of space in an + * LRUCache. Cached items that do not implement this interface are considered to + * occupy one unit of space. + * * @see LRUCache */ public interface ILRUCacheable { /** - * Returns the space the receiver consumes in an LRU Cache. The default space - * value is 1. - * + * Returns the space the receiver consumes in an LRU Cache. The default + * space value is 1. + * * @return int Amount of cache space taken by the receiver */ public int getCacheFootprint(); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/LRUCache.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/LRUCache.java index 9bc14b9..9f80e04 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/LRUCache.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/LRUCache.java @@ -14,67 +14,70 @@ import java.util.Enumeration; import java.util.Hashtable; /** - * The LRUCache is a hashtable that stores a finite number of elements. - * When an attempt is made to add values to a full cache, the least recently used values - * in the cache are discarded to make room for the new values as necessary. + * The LRUCache is a hashtable that stores a finite number of + * elements. When an attempt is made to add values to a full cache, the least + * recently used values in the cache are discarded to make room for the new + * values as necessary. * - *

                                                      The data structure is based on the LRU virtual memory paging scheme. + *

                                                      + * The data structure is based on the LRU virtual memory paging scheme. + * + *

                                                      + * Objects can take up a variable amount of cache space by implementing the + * ILRUCacheable interface. + * + *

                                                      + * This implementation is NOT thread-safe. Synchronization wrappers would have + * to be added to ensure atomic insertions and deletions from the cache. * - *

                                                      Objects can take up a variable amount of cache space by implementing - * the ILRUCacheable interface. - * - *

                                                      This implementation is NOT thread-safe. Synchronization wrappers would - * have to be added to ensure atomic insertions and deletions from the cache. - * * @see net.sourceforge.phpdt.internal.core.util.ILRUCacheable */ public class LRUCache implements Cloneable { /** - * This type is used internally by the LRUCache to represent entries - * stored in the cache. - * It is static because it does not require a pointer to the cache - * which contains it. - * + * This type is used internally by the LRUCache to represent entries stored + * in the cache. It is static because it does not require a pointer to the + * cache which contains it. + * * @see LRUCache */ protected static class LRUCacheEntry { - + /** * Hash table key */ public Object _fKey; - + /** * Hash table value (an LRUCacheEntry object) */ - public Object _fValue; + public Object _fValue; /** * Time value for queue sorting */ public int _fTimestamp; - + /** * Cache footprint of this entry */ public int _fSpace; - + /** * Previous entry in queue */ public LRUCacheEntry _fPrevious; - + /** * Next entry in queue */ public LRUCacheEntry _fNext; - + /** - * Creates a new instance of the receiver with the provided values - * for key, value, and space. + * Creates a new instance of the receiver with the provided values for + * key, value, and space. */ - public LRUCacheEntry (Object key, Object value, int space) { + public LRUCacheEntry(Object key, Object value, int space) { _fKey = key; _fValue = value; _fSpace = space; @@ -87,79 +90,85 @@ public class LRUCache implements Cloneable { return "LRUCacheEntry [" + _fKey + "-->" + _fValue + "]"; //$NON-NLS-3$ //$NON-NLS-1$ //$NON-NLS-2$ } - } + } /** * Amount of cache space used so far */ protected int fCurrentSpace; - + /** * Maximum space allowed in cache */ protected int fSpaceLimit; - + /** * Counter for handing out sequential timestamps */ - protected int fTimestampCounter; - + protected int fTimestampCounter; + /** * Hash table for fast random access to cache entries */ protected Hashtable fEntryTable; /** - * Start of queue (most recently used entry) - */ + * Start of queue (most recently used entry) + */ protected LRUCacheEntry fEntryQueue; /** * End of queue (least recently used entry) - */ + */ protected LRUCacheEntry fEntryQueueTail; - + /** * Default amount of space in the cache */ protected static final int DEFAULT_SPACELIMIT = 100; + /** - * Creates a new cache. Size of cache is defined by + * Creates a new cache. Size of cache is defined by * DEFAULT_SPACELIMIT. */ public LRUCache() { - + this(DEFAULT_SPACELIMIT); } + /** * Creates a new cache. - * @param size Size of Cache + * + * @param size + * Size of Cache */ public LRUCache(int size) { - + fTimestampCounter = fCurrentSpace = 0; fEntryQueue = fEntryQueueTail = null; fEntryTable = new Hashtable(size); fSpaceLimit = size; } + /** * Returns a new cache containing the same contents. - * + * * @return New copy of object. */ public Object clone() { - + LRUCache newCache = newInstance(fSpaceLimit); LRUCacheEntry qEntry; - + /* Preserve order of entries by copying from oldest to newest */ qEntry = this.fEntryQueueTail; while (qEntry != null) { - newCache.privateAdd (qEntry._fKey, qEntry._fValue, qEntry._fSpace); + newCache.privateAdd(qEntry._fKey, qEntry._fValue, qEntry._fSpace); qEntry = qEntry._fPrevious; } return newCache; } + /** * Flushes all entries from the cache. */ @@ -167,85 +176,95 @@ public class LRUCache implements Cloneable { fCurrentSpace = 0; LRUCacheEntry entry = fEntryQueueTail; // Remember last entry - fEntryTable = new Hashtable(); // Clear it out - fEntryQueue = fEntryQueueTail = null; - while (entry != null) { // send deletion notifications in LRU order + fEntryTable = new Hashtable(); // Clear it out + fEntryQueue = fEntryQueueTail = null; + while (entry != null) { // send deletion notifications in LRU order privateNotifyDeletionFromCache(entry); entry = entry._fPrevious; } } + /** - * Flushes the given entry from the cache. Does nothing if entry does not + * Flushes the given entry from the cache. Does nothing if entry does not * exist in cache. - * - * @param key Key of object to flush + * + * @param key + * Key of object to flush */ - public void flush (Object key) { - + public void flush(Object key) { + LRUCacheEntry entry; - + entry = (LRUCacheEntry) fEntryTable.get(key); /* If entry does not exist, return */ - if (entry == null) return; + if (entry == null) + return; - this.privateRemoveEntry (entry, false); + this.privateRemoveEntry(entry, false); } + /** - * Answers the value in the cache at the given key. - * If the value is not in the cache, returns null - * - * @param key Hash table key of object to retrieve + * Answers the value in the cache at the given key. If the value is not in + * the cache, returns null + * + * @param key + * Hash table key of object to retrieve * @return Retreived object, or null if object does not exist */ public Object get(Object key) { - + LRUCacheEntry entry = (LRUCacheEntry) fEntryTable.get(key); if (entry == null) { return null; } - - this.updateTimestamp (entry); + + this.updateTimestamp(entry); return entry._fValue; } + /** * Returns the amount of space that is current used in the cache. */ public int getCurrentSpace() { return fCurrentSpace; } + /** * Returns the maximum amount of space available in the cache. */ public int getSpaceLimit() { return fSpaceLimit; } + /** * Returns an Enumeration of the keys currently in the cache. */ public Enumeration keys() { - + return fEntryTable.keys(); } + /** - * Returns an enumeration that iterates over all the keys and values + * Returns an enumeration that iterates over all the keys and values * currently in the cache. */ public ICacheEnumeration keysAndValues() { return new ICacheEnumeration() { - + Enumeration fValues = fEntryTable.elements(); + LRUCacheEntry fEntry; - + public boolean hasMoreElements() { return fValues.hasMoreElements(); } - + public Object nextElement() { fEntry = (LRUCacheEntry) fValues.nextElement(); return fEntry._fKey; } - + public Object getValue() { if (fEntry == null) { throw new java.util.NoSuchElementException(); @@ -254,96 +273,107 @@ public class LRUCache implements Cloneable { } }; } + /** - * Ensures there is the specified amount of free space in the receiver, - * by removing old entries if necessary. Returns true if the requested space was - * made available, false otherwise. - * - * @param space Amount of space to free up + * Ensures there is the specified amount of free space in the receiver, by + * removing old entries if necessary. Returns true if the requested space + * was made available, false otherwise. + * + * @param space + * Amount of space to free up */ - protected boolean makeSpace (int space) { - + protected boolean makeSpace(int space) { + int limit; - + limit = this.getSpaceLimit(); - + /* if space is already available */ if (fCurrentSpace + space <= limit) { return true; } - + /* if entry is too big for cache */ if (space > limit) { return false; } - + /* Free up space by removing oldest entries */ while (fCurrentSpace + space > limit && fEntryQueueTail != null) { - this.privateRemoveEntry (fEntryQueueTail, false); + this.privateRemoveEntry(fEntryQueueTail, false); } return true; } + /** * Returns a new LRUCache instance */ protected LRUCache newInstance(int size) { return new LRUCache(size); } + /** * Adds an entry for the given key/value/space. */ - protected void privateAdd (Object key, Object value, int space) { - + protected void privateAdd(Object key, Object value, int space) { + LRUCacheEntry entry; - + entry = new LRUCacheEntry(key, value, space); - this.privateAddEntry (entry, false); + this.privateAddEntry(entry, false); } + /** * Adds the given entry from the receiver. - * @param shuffle Indicates whether we are just shuffling the queue - * (in which case, the entry table is not modified). + * + * @param shuffle + * Indicates whether we are just shuffling the queue (in which + * case, the entry table is not modified). */ - protected void privateAddEntry (LRUCacheEntry entry, boolean shuffle) { - + protected void privateAddEntry(LRUCacheEntry entry, boolean shuffle) { + if (!shuffle) { - fEntryTable.put (entry._fKey, entry); + fEntryTable.put(entry._fKey, entry); fCurrentSpace += entry._fSpace; } - + entry._fTimestamp = fTimestampCounter++; entry._fNext = this.fEntryQueue; entry._fPrevious = null; - + if (fEntryQueue == null) { /* this is the first and last entry */ fEntryQueueTail = entry; } else { fEntryQueue._fPrevious = entry; } - + fEntryQueue = entry; } + /** - * An entry has been removed from the cache, for example because it has - * fallen off the bottom of the LRU queue. - * Subclasses could over-ride this to implement a persistent cache below the LRU cache. + * An entry has been removed from the cache, for example because it has + * fallen off the bottom of the LRU queue. Subclasses could over-ride this + * to implement a persistent cache below the LRU cache. */ protected void privateNotifyDeletionFromCache(LRUCacheEntry entry) { // Default is NOP. } + /** - * Removes the entry from the entry queue. - * @param shuffle indicates whether we are just shuffling the queue - * (in which case, the entry table is not modified). + * Removes the entry from the entry queue. + * + * @param shuffle + * indicates whether we are just shuffling the queue (in which + * case, the entry table is not modified). */ - protected void privateRemoveEntry (LRUCacheEntry entry, boolean shuffle) { - + protected void privateRemoveEntry(LRUCacheEntry entry, boolean shuffle) { + LRUCacheEntry previous, next; - + previous = entry._fPrevious; next = entry._fNext; - + if (!shuffle) { fEntryTable.remove(entry._fKey); fCurrentSpace -= entry._fSpace; @@ -364,67 +394,74 @@ public class LRUCache implements Cloneable { next._fPrevious = previous; } } + /** * Sets the value in the cache at the given key. Returns the value. - * - * @param key Key of object to add. - * @param value Value of object to add. + * + * @param key + * Key of object to add. + * @param value + * Value of object to add. * @return added value. */ public Object put(Object key, Object value) { - + int newSpace, oldSpace, newTotal; LRUCacheEntry entry; - + /* Check whether there's an entry in the cache */ - newSpace = spaceFor (key, value); - entry = (LRUCacheEntry) fEntryTable.get (key); - + newSpace = spaceFor(key, value); + entry = (LRUCacheEntry) fEntryTable.get(key); + if (entry != null) { - + /** - * Replace the entry in the cache if it would not overflow - * the cache. Otherwise flush the entry and re-add it so as - * to keep cache within budget + * Replace the entry in the cache if it would not overflow the + * cache. Otherwise flush the entry and re-add it so as to keep + * cache within budget */ oldSpace = entry._fSpace; newTotal = getCurrentSpace() - oldSpace + newSpace; if (newTotal <= getSpaceLimit()) { - updateTimestamp (entry); + updateTimestamp(entry); entry._fValue = value; entry._fSpace = newSpace; this.fCurrentSpace = newTotal; return value; } else { - privateRemoveEntry (entry, false); + privateRemoveEntry(entry, false); } } if (makeSpace(newSpace)) { - privateAdd (key, value, newSpace); + privateAdd(key, value, newSpace); } return value; } + /** - * Removes and returns the value in the cache for the given key. - * If the key is not in the cache, returns null. - * - * @param key Key of object to remove from cache. + * Removes and returns the value in the cache for the given key. If the key + * is not in the cache, returns null. + * + * @param key + * Key of object to remove from cache. * @return Value removed from cache. */ - public Object removeKey (Object key) { - + public Object removeKey(Object key) { + LRUCacheEntry entry = (LRUCacheEntry) fEntryTable.get(key); if (entry == null) { return null; } Object value = entry._fValue; - this.privateRemoveEntry (entry, false); + this.privateRemoveEntry(entry, false); return value; } + /** * Sets the maximum amount of space that the cache can store - * - * @param limit Number of units of cache space + * + * @param limit + * Number of units of cache space */ public void setSpaceLimit(int limit) { if (limit < fSpaceLimit) { @@ -432,66 +469,68 @@ public class LRUCache implements Cloneable { } fSpaceLimit = limit; } + /** * Returns the space taken by the given key and value. */ - protected int spaceFor (Object key, Object value) { - + protected int spaceFor(Object key, Object value) { + if (value instanceof ILRUCacheable) { return ((ILRUCacheable) value).getCacheFootprint(); } else { return 1; } } -/** - * Returns a String that represents the value of this object. This method - * is for debugging purposes only. - */ -public String toString() { - return - "LRUCache " + (fCurrentSpace * 100.0 / fSpaceLimit) + "% full\n" + //$NON-NLS-1$ //$NON-NLS-2$ - this.toStringContents(); -} -/** - * Returns a String that represents the contents of this object. This method - * is for debugging purposes only. - */ -protected String toStringContents() { - StringBuffer result = new StringBuffer(); - int length = fEntryTable.size(); - Object[] unsortedKeys = new Object[length]; - String[] unsortedToStrings = new String[length]; - Enumeration e = this.keys(); - for (int i = 0; i < length; i++) { - Object key = e.nextElement(); - unsortedKeys[i] = key; - unsortedToStrings[i] = - (key instanceof net.sourceforge.phpdt.internal.core.JavaElement) ? - ((net.sourceforge.phpdt.internal.core.JavaElement)key).getElementName() : - key.toString(); + + /** + * Returns a String that represents the value of this object. This method is + * for debugging purposes only. + */ + public String toString() { + return "LRUCache " + (fCurrentSpace * 100.0 / fSpaceLimit) + "% full\n" + //$NON-NLS-1$ //$NON-NLS-2$ + this.toStringContents(); } - ToStringSorter sorter = new ToStringSorter(); - sorter.sort(unsortedKeys, unsortedToStrings); - for (int i = 0; i < length; i++) { - String toString = sorter.sortedStrings[i]; - Object value = this.get(sorter.sortedObjects[i]); - result.append(toString); - result.append(" -> "); //$NON-NLS-1$ - result.append(value); - result.append("\n"); //$NON-NLS-1$ + + /** + * Returns a String that represents the contents of this object. This method + * is for debugging purposes only. + */ + protected String toStringContents() { + StringBuffer result = new StringBuffer(); + int length = fEntryTable.size(); + Object[] unsortedKeys = new Object[length]; + String[] unsortedToStrings = new String[length]; + Enumeration e = this.keys(); + for (int i = 0; i < length; i++) { + Object key = e.nextElement(); + unsortedKeys[i] = key; + unsortedToStrings[i] = (key instanceof net.sourceforge.phpdt.internal.core.JavaElement) ? ((net.sourceforge.phpdt.internal.core.JavaElement) key) + .getElementName() + : key.toString(); + } + ToStringSorter sorter = new ToStringSorter(); + sorter.sort(unsortedKeys, unsortedToStrings); + for (int i = 0; i < length; i++) { + String toString = sorter.sortedStrings[i]; + Object value = this.get(sorter.sortedObjects[i]); + result.append(toString); + result.append(" -> "); //$NON-NLS-1$ + result.append(value); + result.append("\n"); //$NON-NLS-1$ + } + return result.toString(); } - return result.toString(); -} + /** - * Updates the timestamp for the given entry, ensuring that the queue is - * kept in correct order. The entry must exist + * Updates the timestamp for the given entry, ensuring that the queue is + * kept in correct order. The entry must exist */ - protected void updateTimestamp (LRUCacheEntry entry) { - + protected void updateTimestamp(LRUCacheEntry entry) { + entry._fTimestamp = fTimestampCounter++; if (fEntryQueue != entry) { - this.privateRemoveEntry (entry, true); - this.privateAddEntry (entry, true); + this.privateRemoveEntry(entry, true); + this.privateAddEntry(entry, true); } return; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/MementoTokenizer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/MementoTokenizer.java index 92cc164..e1e9ac5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/MementoTokenizer.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/MementoTokenizer.java @@ -14,99 +14,128 @@ import net.sourceforge.phpdt.core.compiler.CharOperation; import net.sourceforge.phpdt.internal.core.JavaElement; public class MementoTokenizer { - private static final String COUNT = Character.toString(JavaElement.JEM_COUNT); - private static final String JAVAPROJECT = Character.toString(JavaElement.JEM_JAVAPROJECT); - private static final String PACKAGEFRAGMENTROOT = Character.toString(JavaElement.JEM_PACKAGEFRAGMENTROOT); - private static final String PACKAGEFRAGMENT = Character.toString(JavaElement.JEM_PACKAGEFRAGMENT); - private static final String FIELD = Character.toString(JavaElement.JEM_FIELD); - private static final String METHOD = Character.toString(JavaElement.JEM_METHOD); - private static final String INITIALIZER = Character.toString(JavaElement.JEM_INITIALIZER); - private static final String COMPILATIONUNIT = Character.toString(JavaElement.JEM_COMPILATIONUNIT); -// private static final String CLASSFILE = Character.toString(JavaElement.JEM_CLASSFILE); + private static final String COUNT = Character + .toString(JavaElement.JEM_COUNT); + + private static final String JAVAPROJECT = Character + .toString(JavaElement.JEM_JAVAPROJECT); + + private static final String PACKAGEFRAGMENTROOT = Character + .toString(JavaElement.JEM_PACKAGEFRAGMENTROOT); + + private static final String PACKAGEFRAGMENT = Character + .toString(JavaElement.JEM_PACKAGEFRAGMENT); + + private static final String FIELD = Character + .toString(JavaElement.JEM_FIELD); + + private static final String METHOD = Character + .toString(JavaElement.JEM_METHOD); + + private static final String INITIALIZER = Character + .toString(JavaElement.JEM_INITIALIZER); + + private static final String COMPILATIONUNIT = Character + .toString(JavaElement.JEM_COMPILATIONUNIT); + + // private static final String CLASSFILE = + // Character.toString(JavaElement.JEM_CLASSFILE); private static final String TYPE = Character.toString(JavaElement.JEM_TYPE); - private static final String PACKAGEDECLARATION = Character.toString(JavaElement.JEM_PACKAGEDECLARATION); - private static final String IMPORTDECLARATION = Character.toString(JavaElement.JEM_IMPORTDECLARATION); - private static final String LOCALVARIABLE = Character.toString(JavaElement.JEM_LOCALVARIABLE); + + private static final String PACKAGEDECLARATION = Character + .toString(JavaElement.JEM_PACKAGEDECLARATION); + + private static final String IMPORTDECLARATION = Character + .toString(JavaElement.JEM_IMPORTDECLARATION); + + private static final String LOCALVARIABLE = Character + .toString(JavaElement.JEM_LOCALVARIABLE); private final char[] memento; + private final int length; + private int index = 0; - + public MementoTokenizer(String memento) { this.memento = memento.toCharArray(); this.length = this.memento.length; } - + public boolean hasMoreTokens() { return this.index < this.length; } - + public String nextToken() { int start = this.index; StringBuffer buffer = null; switch (this.memento[this.index++]) { + case JavaElement.JEM_ESCAPE: + buffer = new StringBuffer(); + buffer.append(this.memento[this.index]); + start = ++this.index; + break; + case JavaElement.JEM_COUNT: + return COUNT; + case JavaElement.JEM_JAVAPROJECT: + return JAVAPROJECT; + case JavaElement.JEM_PACKAGEFRAGMENTROOT: + return PACKAGEFRAGMENTROOT; + case JavaElement.JEM_PACKAGEFRAGMENT: + return PACKAGEFRAGMENT; + case JavaElement.JEM_FIELD: + return FIELD; + case JavaElement.JEM_METHOD: + return METHOD; + case JavaElement.JEM_INITIALIZER: + return INITIALIZER; + case JavaElement.JEM_COMPILATIONUNIT: + return COMPILATIONUNIT; + // case JavaElement.JEM_CLASSFILE: + // return CLASSFILE; + case JavaElement.JEM_TYPE: + return TYPE; + case JavaElement.JEM_PACKAGEDECLARATION: + return PACKAGEDECLARATION; + case JavaElement.JEM_IMPORTDECLARATION: + return IMPORTDECLARATION; + case JavaElement.JEM_LOCALVARIABLE: + return LOCALVARIABLE; + } + loop: while (this.index < this.length) { + switch (this.memento[this.index]) { case JavaElement.JEM_ESCAPE: - buffer = new StringBuffer(); - buffer.append(this.memento[this.index]); + if (buffer == null) + buffer = new StringBuffer(); + buffer.append(CharOperation.subarray(this.memento, start, + this.index)); start = ++this.index; break; case JavaElement.JEM_COUNT: - return COUNT; case JavaElement.JEM_JAVAPROJECT: - return JAVAPROJECT; case JavaElement.JEM_PACKAGEFRAGMENTROOT: - return PACKAGEFRAGMENTROOT; case JavaElement.JEM_PACKAGEFRAGMENT: - return PACKAGEFRAGMENT; case JavaElement.JEM_FIELD: - return FIELD; case JavaElement.JEM_METHOD: - return METHOD; case JavaElement.JEM_INITIALIZER: - return INITIALIZER; case JavaElement.JEM_COMPILATIONUNIT: - return COMPILATIONUNIT; -// case JavaElement.JEM_CLASSFILE: -// return CLASSFILE; + // case JavaElement.JEM_CLASSFILE: case JavaElement.JEM_TYPE: - return TYPE; case JavaElement.JEM_PACKAGEDECLARATION: - return PACKAGEDECLARATION; case JavaElement.JEM_IMPORTDECLARATION: - return IMPORTDECLARATION; case JavaElement.JEM_LOCALVARIABLE: - return LOCALVARIABLE; - } - loop: while (this.index < this.length) { - switch (this.memento[this.index]) { - case JavaElement.JEM_ESCAPE: - if (buffer == null) buffer = new StringBuffer(); - buffer.append(CharOperation.subarray(this.memento, start, this.index)); - start = ++this.index; - break; - case JavaElement.JEM_COUNT: - case JavaElement.JEM_JAVAPROJECT: - case JavaElement.JEM_PACKAGEFRAGMENTROOT: - case JavaElement.JEM_PACKAGEFRAGMENT: - case JavaElement.JEM_FIELD: - case JavaElement.JEM_METHOD: - case JavaElement.JEM_INITIALIZER: - case JavaElement.JEM_COMPILATIONUNIT: -// case JavaElement.JEM_CLASSFILE: - case JavaElement.JEM_TYPE: - case JavaElement.JEM_PACKAGEDECLARATION: - case JavaElement.JEM_IMPORTDECLARATION: - case JavaElement.JEM_LOCALVARIABLE: - break loop; + break loop; } this.index++; } if (buffer != null) { - buffer.append(CharOperation.subarray(this.memento, start, this.index)); + buffer.append(CharOperation.subarray(this.memento, start, + this.index)); return buffer.toString(); } else { - return new String(CharOperation.subarray(this.memento, start, this.index)); + return new String(CharOperation.subarray(this.memento, start, + this.index)); } } - + } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/PerThreadObject.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/PerThreadObject.java index 0114c8c..3cc5e59 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/PerThreadObject.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/PerThreadObject.java @@ -13,29 +13,30 @@ package net.sourceforge.phpdt.internal.core.util; import java.util.Hashtable; /** - * Implementation of data structure remembering an Object value by thread. Its purpose is to ease - * writing multi-threaded algorithms by providing a per thread data structure. + * Implementation of data structure remembering an Object value by thread. Its + * purpose is to ease writing multi-threaded algorithms by providing a per + * thread data structure. */ public class PerThreadObject { private Hashtable internalMap = new Hashtable(3); // synchronized map - + /** * Answer the current map for this thread */ - public Object getCurrent(){ + public Object getCurrent() { return this.internalMap.get(Thread.currentThread()); } - + /** - * Set the map for this current thread - setting to null is equivalent to removing it + * Set the map for this current thread - setting to null is equivalent to + * removing it */ - public void setCurrent(Object current){ - if (current == null){ - this.internalMap.remove(Thread.currentThread()); + public void setCurrent(Object current) { + if (current == null) { + this.internalMap.remove(Thread.currentThread()); } else { this.internalMap.put(Thread.currentThread(), current); } } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ReferenceInfoAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ReferenceInfoAdapter.java index a53bebd..672b490 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ReferenceInfoAdapter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ReferenceInfoAdapter.java @@ -11,36 +11,53 @@ package net.sourceforge.phpdt.internal.core.util; /** - * An adapter which implements the methods for handling - * reference information from the parser. + * An adapter which implements the methods for handling reference information + * from the parser. */ public abstract class ReferenceInfoAdapter { -/** - * Does nothing. - */ -public void acceptConstructorReference(char[] typeName, int argCount, int sourcePosition) {} -/** - * Does nothing. - */ -public void acceptFieldReference(char[] fieldName, int sourcePosition) {} -/** - * Does nothing. - */ -public void acceptMethodReference(char[] methodName, int argCount, int sourcePosition) {} -/** - * Does nothing. - */ -public void acceptTypeReference(char[][] typeName, int sourceStart, int sourceEnd) {} -/** - * Does nothing. - */ -public void acceptTypeReference(char[] typeName, int sourcePosition) {} -/** - * Does nothing. - */ -public void acceptUnknownReference(char[][] name, int sourceStart, int sourceEnd) {} -/** - * Does nothing. - */ -public void acceptUnknownReference(char[] name, int sourcePosition) {} + /** + * Does nothing. + */ + public void acceptConstructorReference(char[] typeName, int argCount, + int sourcePosition) { + } + + /** + * Does nothing. + */ + public void acceptFieldReference(char[] fieldName, int sourcePosition) { + } + + /** + * Does nothing. + */ + public void acceptMethodReference(char[] methodName, int argCount, + int sourcePosition) { + } + + /** + * Does nothing. + */ + public void acceptTypeReference(char[][] typeName, int sourceStart, + int sourceEnd) { + } + + /** + * Does nothing. + */ + public void acceptTypeReference(char[] typeName, int sourcePosition) { + } + + /** + * Does nothing. + */ + public void acceptUnknownReference(char[][] name, int sourceStart, + int sourceEnd) { + } + + /** + * Does nothing. + */ + public void acceptUnknownReference(char[] name, int sourcePosition) { + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/SimpleDocument.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/SimpleDocument.java index bccd2f0..78b3dd2 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/SimpleDocument.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/SimpleDocument.java @@ -23,100 +23,126 @@ import org.eclipse.jface.text.Position; * Minimal implementation of IDocument to apply text edit onto a string. */ public class SimpleDocument implements IDocument { - + private StringBuffer buffer; - public SimpleDocument(String source) { this.buffer = new StringBuffer(source); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#getChar(int) */ public char getChar(int offset) { return 0; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#getLength() */ public int getLength() { return this.buffer.length(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#get() */ public String get() { return this.buffer.toString(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#get(int, int) */ public String get(int offset, int length) { return this.buffer.substring(offset, offset + length); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#set(java.lang.String) */ public void set(String text) { // defining interface method } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#replace(int, int, java.lang.String) */ public void replace(int offset, int length, String text) { - + this.buffer.replace(offset, offset + length, text); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#addDocumentListener(org.eclipse.jface.text.IDocumentListener) */ public void addDocumentListener(IDocumentListener listener) { // defining interface method } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#removeDocumentListener(org.eclipse.jface.text.IDocumentListener) */ public void removeDocumentListener(IDocumentListener listener) { // defining interface method } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#addPrenotifiedDocumentListener(org.eclipse.jface.text.IDocumentListener) */ public void addPrenotifiedDocumentListener(IDocumentListener documentAdapter) { // defining interface method } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#removePrenotifiedDocumentListener(org.eclipse.jface.text.IDocumentListener) */ - public void removePrenotifiedDocumentListener(IDocumentListener documentAdapter) { + public void removePrenotifiedDocumentListener( + IDocumentListener documentAdapter) { // defining interface method } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#addPositionCategory(java.lang.String) */ public void addPositionCategory(String category) { // defining interface method } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#removePositionCategory(java.lang.String) */ public void removePositionCategory(String category) { - // defining interface method + // defining interface method } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#getPositionCategories() */ public String[] getPositionCategories() { @@ -124,7 +150,9 @@ public class SimpleDocument implements IDocument { return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#containsPositionCategory(java.lang.String) */ public boolean containsPositionCategory(String category) { @@ -132,35 +160,47 @@ public class SimpleDocument implements IDocument { return false; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#addPosition(org.eclipse.jface.text.Position) */ public void addPosition(Position position) { // defining interface method } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#removePosition(org.eclipse.jface.text.Position) */ public void removePosition(Position position) { // defining interface method } - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#addPosition(java.lang.String, org.eclipse.jface.text.Position) + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#addPosition(java.lang.String, + * org.eclipse.jface.text.Position) */ public void addPosition(String category, Position position) { // defining interface method } - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#removePosition(java.lang.String, org.eclipse.jface.text.Position) + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#removePosition(java.lang.String, + * org.eclipse.jface.text.Position) */ public void removePosition(String category, Position position) { // defining interface method } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#getPositions(java.lang.String) */ public Position[] getPositions(String category) { @@ -168,44 +208,59 @@ public class SimpleDocument implements IDocument { return null; } - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#containsPosition(java.lang.String, int, int) + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#containsPosition(java.lang.String, + * int, int) */ public boolean containsPosition(String category, int offset, int length) { // defining interface method return false; } - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#computeIndexInCategory(java.lang.String, int) + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#computeIndexInCategory(java.lang.String, + * int) */ public int computeIndexInCategory(String category, int offset) { // defining interface method return 0; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#addPositionUpdater(org.eclipse.jface.text.IPositionUpdater) */ public void addPositionUpdater(IPositionUpdater updater) { // defining interface method } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#removePositionUpdater(org.eclipse.jface.text.IPositionUpdater) */ public void removePositionUpdater(IPositionUpdater updater) { // defining interface method } - /* (non-Javadoc) - * @see org.eclipse.jface.text.IDocument#insertPositionUpdater(org.eclipse.jface.text.IPositionUpdater, int) + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.IDocument#insertPositionUpdater(org.eclipse.jface.text.IPositionUpdater, + * int) */ public void insertPositionUpdater(IPositionUpdater updater, int index) { // defining interface method } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#getPositionUpdaters() */ public IPositionUpdater[] getPositionUpdaters() { @@ -213,7 +268,9 @@ public class SimpleDocument implements IDocument { return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#getLegalContentTypes() */ public String[] getLegalContentTypes() { @@ -221,7 +278,9 @@ public class SimpleDocument implements IDocument { return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#getContentType(int) */ public String getContentType(int offset) { @@ -229,7 +288,9 @@ public class SimpleDocument implements IDocument { return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#getPartition(int) */ public ITypedRegion getPartition(int offset) { @@ -237,7 +298,9 @@ public class SimpleDocument implements IDocument { return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#computePartitioning(int, int) */ public ITypedRegion[] computePartitioning(int offset, int length) { @@ -245,28 +308,38 @@ public class SimpleDocument implements IDocument { return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#addDocumentPartitioningListener(org.eclipse.jface.text.IDocumentPartitioningListener) */ - public void addDocumentPartitioningListener(IDocumentPartitioningListener listener) { + public void addDocumentPartitioningListener( + IDocumentPartitioningListener listener) { // defining interface method } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#removeDocumentPartitioningListener(org.eclipse.jface.text.IDocumentPartitioningListener) */ - public void removeDocumentPartitioningListener(IDocumentPartitioningListener listener) { + public void removeDocumentPartitioningListener( + IDocumentPartitioningListener listener) { // defining interface method } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#setDocumentPartitioner(org.eclipse.jface.text.IDocumentPartitioner) */ public void setDocumentPartitioner(IDocumentPartitioner partitioner) { // defining interface method } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#getDocumentPartitioner() */ public IDocumentPartitioner getDocumentPartitioner() { @@ -274,7 +347,9 @@ public class SimpleDocument implements IDocument { return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#getLineLength(int) */ public int getLineLength(int line) { @@ -282,7 +357,9 @@ public class SimpleDocument implements IDocument { return 0; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#getLineOfOffset(int) */ public int getLineOfOffset(int offset) { @@ -290,7 +367,9 @@ public class SimpleDocument implements IDocument { return 0; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#getLineOffset(int) */ public int getLineOffset(int line) { @@ -298,7 +377,9 @@ public class SimpleDocument implements IDocument { return 0; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#getLineInformation(int) */ public IRegion getLineInformation(int line) { @@ -306,7 +387,9 @@ public class SimpleDocument implements IDocument { return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#getLineInformationOfOffset(int) */ public IRegion getLineInformationOfOffset(int offset) { @@ -314,7 +397,9 @@ public class SimpleDocument implements IDocument { return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#getNumberOfLines() */ public int getNumberOfLines() { @@ -322,7 +407,9 @@ public class SimpleDocument implements IDocument { return 0; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#getNumberOfLines(int, int) */ public int getNumberOfLines(int offset, int length) { @@ -330,7 +417,9 @@ public class SimpleDocument implements IDocument { return 0; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#computeNumberOfLines(java.lang.String) */ public int computeNumberOfLines(String text) { @@ -338,7 +427,9 @@ public class SimpleDocument implements IDocument { return 0; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#getLegalLineDelimiters() */ public String[] getLegalLineDelimiters() { @@ -346,7 +437,9 @@ public class SimpleDocument implements IDocument { return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.text.IDocument#getLineDelimiter(int) */ public String getLineDelimiter(int line) { @@ -355,15 +448,12 @@ public class SimpleDocument implements IDocument { } /** - * @see org.eclipse.jface.text.IDocument#search(int, java.lang.String, boolean, boolean, boolean) + * @see org.eclipse.jface.text.IDocument#search(int, java.lang.String, + * boolean, boolean, boolean) * @deprecated */ - public int search( - int startOffset, - String findString, - boolean forwardSearch, - boolean caseSensitive, - boolean wholeWord) { + public int search(int startOffset, String findString, + boolean forwardSearch, boolean caseSensitive, boolean wholeWord) { // defining interface method return 0; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/SimpleLookupTable.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/SimpleLookupTable.java index a0819d4..0caafdd 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/SimpleLookupTable.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/SimpleLookupTable.java @@ -11,145 +11,160 @@ package net.sourceforge.phpdt.internal.core.util; /** - * A simple lookup table is a non-synchronized Hashtable, whose keys - * and values are Objects. It also uses linear probing to resolve collisions - * rather than a linked list of hash table entries. + * A simple lookup table is a non-synchronized Hashtable, whose keys and values + * are Objects. It also uses linear probing to resolve collisions rather than a + * linked list of hash table entries. */ public final class SimpleLookupTable implements Cloneable { -// to avoid using Enumerations, walk the individual tables skipping nulls -public Object[] keyTable; -public Object[] valueTable; -public int elementSize; // number of elements in the table -public int threshold; + // to avoid using Enumerations, walk the individual tables skipping nulls + public Object[] keyTable; -public SimpleLookupTable() { - this(13); -} + public Object[] valueTable; -public SimpleLookupTable(int size) { - if (size < 3) size = 3; - this.elementSize = 0; - this.threshold = size + 1; // size is the expected number of elements - int tableLength = 2 * size + 1; - this.keyTable = new Object[tableLength]; - this.valueTable = new Object[tableLength]; -} + public int elementSize; // number of elements in the table -public Object clone() throws CloneNotSupportedException { - SimpleLookupTable result = (SimpleLookupTable) super.clone(); - result.elementSize = this.elementSize; - result.threshold = this.threshold; + public int threshold; - int length = this.keyTable.length; - result.keyTable = new Object[length]; - System.arraycopy(this.keyTable, 0, result.keyTable, 0, length); + public SimpleLookupTable() { + this(13); + } - length = this.valueTable.length; - result.valueTable = new Object[length]; - System.arraycopy(this.valueTable, 0, result.valueTable, 0, length); - return result; -} + public SimpleLookupTable(int size) { + if (size < 3) + size = 3; + this.elementSize = 0; + this.threshold = size + 1; // size is the expected number of elements + int tableLength = 2 * size + 1; + this.keyTable = new Object[tableLength]; + this.valueTable = new Object[tableLength]; + } + + public Object clone() throws CloneNotSupportedException { + SimpleLookupTable result = (SimpleLookupTable) super.clone(); + result.elementSize = this.elementSize; + result.threshold = this.threshold; + + int length = this.keyTable.length; + result.keyTable = new Object[length]; + System.arraycopy(this.keyTable, 0, result.keyTable, 0, length); -public boolean containsKey(Object key) { - int length = keyTable.length; - int index = (key.hashCode() & 0x7FFFFFFF) % length; - Object currentKey; - while ((currentKey = keyTable[index]) != null) { - if (currentKey.equals(key)) return true; - if (++index == length) index = 0; + length = this.valueTable.length; + result.valueTable = new Object[length]; + System.arraycopy(this.valueTable, 0, result.valueTable, 0, length); + return result; } - return false; -} -public Object get(Object key) { - int length = keyTable.length; - int index = (key.hashCode() & 0x7FFFFFFF) % length; - Object currentKey; - while ((currentKey = keyTable[index]) != null) { - if (currentKey.equals(key)) return valueTable[index]; - if (++index == length) index = 0; + public boolean containsKey(Object key) { + int length = keyTable.length; + int index = (key.hashCode() & 0x7FFFFFFF) % length; + Object currentKey; + while ((currentKey = keyTable[index]) != null) { + if (currentKey.equals(key)) + return true; + if (++index == length) + index = 0; + } + return false; } - return null; -} -public Object keyForValue(Object valueToMatch) { - if (valueToMatch != null) - for (int i = 0, l = valueTable.length; i < l; i++) - if (valueToMatch.equals(valueTable[i])) - return keyTable[i]; - return null; -} + public Object get(Object key) { + int length = keyTable.length; + int index = (key.hashCode() & 0x7FFFFFFF) % length; + Object currentKey; + while ((currentKey = keyTable[index]) != null) { + if (currentKey.equals(key)) + return valueTable[index]; + if (++index == length) + index = 0; + } + return null; + } -public Object put(Object key, Object value) { - int length = keyTable.length; - int index = (key.hashCode() & 0x7FFFFFFF) % length; - Object currentKey; - while ((currentKey = keyTable[index]) != null) { - if (currentKey.equals(key)) return valueTable[index] = value; - if (++index == length) index = 0; + public Object keyForValue(Object valueToMatch) { + if (valueToMatch != null) + for (int i = 0, l = valueTable.length; i < l; i++) + if (valueToMatch.equals(valueTable[i])) + return keyTable[i]; + return null; } - keyTable[index] = key; - valueTable[index] = value; - // assumes the threshold is never equal to the size of the table - if (++elementSize > threshold) rehash(); - return value; -} + public Object put(Object key, Object value) { + int length = keyTable.length; + int index = (key.hashCode() & 0x7FFFFFFF) % length; + Object currentKey; + while ((currentKey = keyTable[index]) != null) { + if (currentKey.equals(key)) + return valueTable[index] = value; + if (++index == length) + index = 0; + } + keyTable[index] = key; + valueTable[index] = value; -public Object removeKey(Object key) { - int length = keyTable.length; - int index = (key.hashCode() & 0x7FFFFFFF) % length; - Object currentKey; - while ((currentKey = keyTable[index]) != null) { - if (currentKey.equals(key)) { - elementSize--; - Object oldValue = valueTable[index]; - keyTable[index] = null; - valueTable[index] = null; - if (keyTable[index + 1 == length ? 0 : index + 1] != null) - rehash(); // only needed if a possible collision existed - return oldValue; + // assumes the threshold is never equal to the size of the table + if (++elementSize > threshold) + rehash(); + return value; + } + + public Object removeKey(Object key) { + int length = keyTable.length; + int index = (key.hashCode() & 0x7FFFFFFF) % length; + Object currentKey; + while ((currentKey = keyTable[index]) != null) { + if (currentKey.equals(key)) { + elementSize--; + Object oldValue = valueTable[index]; + keyTable[index] = null; + valueTable[index] = null; + if (keyTable[index + 1 == length ? 0 : index + 1] != null) + rehash(); // only needed if a possible collision existed + return oldValue; + } + if (++index == length) + index = 0; } - if (++index == length) index = 0; + return null; } - return null; -} -public void removeValue(Object valueToRemove) { - boolean rehash = false; - for (int i = 0, l = valueTable.length; i < l; i++) { - Object value = valueTable[i]; - if (value != null && value.equals(valueToRemove)) { - elementSize--; - keyTable[i] = null; - valueTable[i] = null; - if (!rehash && keyTable[i + 1 == l ? 0 : i + 1] != null) - rehash = true; // only needed if a possible collision existed + public void removeValue(Object valueToRemove) { + boolean rehash = false; + for (int i = 0, l = valueTable.length; i < l; i++) { + Object value = valueTable[i]; + if (value != null && value.equals(valueToRemove)) { + elementSize--; + keyTable[i] = null; + valueTable[i] = null; + if (!rehash && keyTable[i + 1 == l ? 0 : i + 1] != null) + rehash = true; // only needed if a possible collision + // existed + } } + if (rehash) + rehash(); } - if (rehash) rehash(); -} -private void rehash() { - SimpleLookupTable newLookupTable = new SimpleLookupTable(elementSize * 2); // double the number of expected elements - Object currentKey; - for (int i = keyTable.length; --i >= 0;) - if ((currentKey = keyTable[i]) != null) - newLookupTable.put(currentKey, valueTable[i]); - - this.keyTable = newLookupTable.keyTable; - this.valueTable = newLookupTable.valueTable; - this.elementSize = newLookupTable.elementSize; - this.threshold = newLookupTable.threshold; -} + private void rehash() { + SimpleLookupTable newLookupTable = new SimpleLookupTable( + elementSize * 2); // double the number of expected elements + Object currentKey; + for (int i = keyTable.length; --i >= 0;) + if ((currentKey = keyTable[i]) != null) + newLookupTable.put(currentKey, valueTable[i]); + + this.keyTable = newLookupTable.keyTable; + this.valueTable = newLookupTable.valueTable; + this.elementSize = newLookupTable.elementSize; + this.threshold = newLookupTable.threshold; + } -public String toString() { - String s = ""; //$NON-NLS-1$ - Object object; - for (int i = 0, l = valueTable.length; i < l; i++) - if ((object = valueTable[i]) != null) - s += keyTable[i].toString() + " -> " + object.toString() + "\n"; //$NON-NLS-2$ //$NON-NLS-1$ - return s; -} + public String toString() { + String s = ""; //$NON-NLS-1$ + Object object; + for (int i = 0, l = valueTable.length; i < l; i++) + if ((object = valueTable[i]) != null) + s += keyTable[i].toString() + " -> " + object.toString() + "\n"; //$NON-NLS-2$ //$NON-NLS-1$ + return s; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/SimpleSet.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/SimpleSet.java index 3e1544f..d5d20f5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/SimpleSet.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/SimpleSet.java @@ -11,101 +11,112 @@ package net.sourceforge.phpdt.internal.core.util; /** - * A simple lookup table is a non-synchronized Hashtable, whose keys - * and values are Objects. It also uses linear probing to resolve collisions - * rather than a linked list of hash table entries. + * A simple lookup table is a non-synchronized Hashtable, whose keys and values + * are Objects. It also uses linear probing to resolve collisions rather than a + * linked list of hash table entries. */ public final class SimpleSet implements Cloneable { -// to avoid using Enumerations, walk the individual values skipping nulls -public Object[] values; -public int elementSize; // number of elements in the table -public int threshold; + // to avoid using Enumerations, walk the individual values skipping nulls + public Object[] values; -public SimpleSet() { - this(13); -} + public int elementSize; // number of elements in the table -public SimpleSet(int size) { - if (size < 3) size = 3; - this.elementSize = 0; - this.threshold = size + 1; // size is the expected number of elements - this.values = new Object[2 * size + 1]; -} + public int threshold; -public Object add(Object object) { - int length = values.length; - int index = (object.hashCode() & 0x7FFFFFFF) % length; - Object current; - while ((current = values[index]) != null) { - if (current.equals(object)) return values[index] = object; - if (++index == length) index = 0; + public SimpleSet() { + this(13); } - values[index] = object; - // assumes the threshold is never equal to the size of the table - if (++elementSize > threshold) rehash(); - return object; -} + public SimpleSet(int size) { + if (size < 3) + size = 3; + this.elementSize = 0; + this.threshold = size + 1; // size is the expected number of elements + this.values = new Object[2 * size + 1]; + } -public Object clone() throws CloneNotSupportedException { - SimpleSet result = (SimpleSet) super.clone(); - result.elementSize = this.elementSize; - result.threshold = this.threshold; + public Object add(Object object) { + int length = values.length; + int index = (object.hashCode() & 0x7FFFFFFF) % length; + Object current; + while ((current = values[index]) != null) { + if (current.equals(object)) + return values[index] = object; + if (++index == length) + index = 0; + } + values[index] = object; - int length = this.values.length; - result.values = new Object[length]; - System.arraycopy(this.values, 0, result.values, 0, length); - return result; -} + // assumes the threshold is never equal to the size of the table + if (++elementSize > threshold) + rehash(); + return object; + } -public boolean includes(Object object) { - int length = values.length; - int index = (object.hashCode() & 0x7FFFFFFF) % length; - Object current; - while ((current = values[index]) != null) { - if (current.equals(object)) return true; - if (++index == length) index = 0; + public Object clone() throws CloneNotSupportedException { + SimpleSet result = (SimpleSet) super.clone(); + result.elementSize = this.elementSize; + result.threshold = this.threshold; + + int length = this.values.length; + result.values = new Object[length]; + System.arraycopy(this.values, 0, result.values, 0, length); + return result; } - return false; -} -public Object remove(Object object) { - int length = values.length; - int index = (object.hashCode() & 0x7FFFFFFF) % length; - Object current; - while ((current = values[index]) != null) { - if (current.equals(object)) { - elementSize--; - Object oldValue = values[index]; - values[index] = null; - if (values[index + 1 == length ? 0 : index + 1] != null) - rehash(); // only needed if a possible collision existed - return oldValue; + public boolean includes(Object object) { + int length = values.length; + int index = (object.hashCode() & 0x7FFFFFFF) % length; + Object current; + while ((current = values[index]) != null) { + if (current.equals(object)) + return true; + if (++index == length) + index = 0; } - if (++index == length) index = 0; + return false; } - return null; -} -private void rehash() { - SimpleSet newSet = new SimpleSet(elementSize * 2); // double the number of expected elements - Object current; - for (int i = values.length; --i >= 0;) - if ((current = values[i]) != null) - newSet.add(current); + public Object remove(Object object) { + int length = values.length; + int index = (object.hashCode() & 0x7FFFFFFF) % length; + Object current; + while ((current = values[index]) != null) { + if (current.equals(object)) { + elementSize--; + Object oldValue = values[index]; + values[index] = null; + if (values[index + 1 == length ? 0 : index + 1] != null) + rehash(); // only needed if a possible collision existed + return oldValue; + } + if (++index == length) + index = 0; + } + return null; + } - this.values = newSet.values; - this.elementSize = newSet.elementSize; - this.threshold = newSet.threshold; -} + private void rehash() { + SimpleSet newSet = new SimpleSet(elementSize * 2); // double the number + // of expected + // elements + Object current; + for (int i = values.length; --i >= 0;) + if ((current = values[i]) != null) + newSet.add(current); -public String toString() { - String s = ""; //$NON-NLS-1$ - Object object; - for (int i = 0, l = values.length; i < l; i++) - if ((object = values[i]) != null) - s += object.toString() + "\n"; //$NON-NLS-1$ - return s; -} + this.values = newSet.values; + this.elementSize = newSet.elementSize; + this.threshold = newSet.threshold; + } + + public String toString() { + String s = ""; //$NON-NLS-1$ + Object object; + for (int i = 0, l = values.length; i < l; i++) + if ((object = values[i]) != null) + s += object.toString() + "\n"; //$NON-NLS-1$ + return s; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/SimpleWordSet.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/SimpleWordSet.java index ab69d75..7ed0065 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/SimpleWordSet.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/SimpleWordSet.java @@ -14,55 +14,67 @@ import net.sourceforge.phpdt.core.compiler.CharOperation; public final class SimpleWordSet { -// to avoid using Enumerations, walk the individual values skipping nulls -public char[][] words; -public int elementSize; // number of elements in the table -public int threshold; + // to avoid using Enumerations, walk the individual values skipping nulls + public char[][] words; -public SimpleWordSet(int size) { - this.elementSize = 0; - this.threshold = size; // size represents the expected number of elements - int extraRoom = (int) (size * 1.5f); - if (this.threshold == extraRoom) - extraRoom++; - this.words = new char[extraRoom][]; -} + public int elementSize; // number of elements in the table -public char[] add(char[] word) { - int length = this.words.length; - int index = CharOperation.hashCode(word) % length; - char[] current; - while ((current = words[index]) != null) { - if (CharOperation.equals(current, word)) return current; - if (++index == length) index = 0; + public int threshold; + + public SimpleWordSet(int size) { + this.elementSize = 0; + this.threshold = size; // size represents the expected number of + // elements + int extraRoom = (int) (size * 1.5f); + if (this.threshold == extraRoom) + extraRoom++; + this.words = new char[extraRoom][]; } - words[index] = word; - // assumes the threshold is never equal to the size of the table - if (++elementSize > threshold) rehash(); - return word; -} + public char[] add(char[] word) { + int length = this.words.length; + int index = CharOperation.hashCode(word) % length; + char[] current; + while ((current = words[index]) != null) { + if (CharOperation.equals(current, word)) + return current; + if (++index == length) + index = 0; + } + words[index] = word; + + // assumes the threshold is never equal to the size of the table + if (++elementSize > threshold) + rehash(); + return word; + } -public boolean includes(char[] word) { - int length = this.words.length; - int index = CharOperation.hashCode(word) % length; - char[] current; - while ((current = words[index]) != null) { - if (CharOperation.equals(current, word)) return true; - if (++index == length) index = 0; + public boolean includes(char[] word) { + int length = this.words.length; + int index = CharOperation.hashCode(word) % length; + char[] current; + while ((current = words[index]) != null) { + if (CharOperation.equals(current, word)) + return true; + if (++index == length) + index = 0; + } + return false; } - return false; -} -private void rehash() { - SimpleWordSet newSet = new SimpleWordSet(elementSize * 2); // double the number of expected elements - char[] current; - for (int i = words.length; --i >= 0;) - if ((current = words[i]) != null) - newSet.add(current); + private void rehash() { + SimpleWordSet newSet = new SimpleWordSet(elementSize * 2); // double + // the + // number of + // expected + // elements + char[] current; + for (int i = words.length; --i >= 0;) + if ((current = words[i]) != null) + newSet.add(current); - this.words = newSet.words; - this.elementSize = newSet.elementSize; - this.threshold = newSet.threshold; -} + this.words = newSet.words; + this.elementSize = newSet.elementSize; + this.threshold = newSet.threshold; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ToStringSorter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ToStringSorter.java index e2632f3..61f1298 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ToStringSorter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ToStringSorter.java @@ -11,65 +11,68 @@ package net.sourceforge.phpdt.internal.core.util; /** - * The SortOperation takes a collection of objects and returns - * a sorted collection of these objects. The sorting of these - * objects is based on their toString(). They are sorted in - * alphabetical order. + * The SortOperation takes a collection of objects and returns a sorted + * collection of these objects. The sorting of these objects is based on their + * toString(). They are sorted in alphabetical order. */ public class ToStringSorter { Object[] sortedObjects; + String[] sortedStrings; -/** - * Returns true if stringTwo is 'greater than' stringOne - * This is the 'ordering' method of the sort operation. - */ -public boolean compare(String stringOne, String stringTwo) { - return stringOne.compareTo(stringTwo) < 0; -} -/** - * Sort the objects in sorted collection and return that collection. - */ -private void quickSort(int left, int right) { - int originalLeft = left; - int originalRight = right; - int midIndex = (left + right) / 2; - String midToString = this.sortedStrings[midIndex]; - - do { - while (compare(this.sortedStrings[left], midToString)) - left++; - while (compare(midToString, this.sortedStrings[right])) - right--; - if (left <= right) { - Object tmp = this.sortedObjects[left]; - this.sortedObjects[left] = this.sortedObjects[right]; - this.sortedObjects[right] = tmp; - String tmpToString = this.sortedStrings[left]; - this.sortedStrings[left] = this.sortedStrings[right]; - this.sortedStrings[right] = tmpToString; - left++; - right--; - } - } while (left <= right); - - if (originalLeft < right) - quickSort(originalLeft, right); - if (left < originalRight) - quickSort(left, originalRight); -} -/** - * Return a new sorted collection from this unsorted collection. - * Sort using quick sort. - */ -public void sort(Object[] unSortedObjects, String[] unsortedStrings) { - int size = unSortedObjects.length; - this.sortedObjects = new Object[size]; - this.sortedStrings = new String[size]; - - //copy the array so can return a new sorted collection - System.arraycopy(unSortedObjects, 0, this.sortedObjects, 0, size); - System.arraycopy(unsortedStrings, 0, this.sortedStrings, 0, size); - if (size > 1) - quickSort(0, size - 1); -} + + /** + * Returns true if stringTwo is 'greater than' stringOne This is the + * 'ordering' method of the sort operation. + */ + public boolean compare(String stringOne, String stringTwo) { + return stringOne.compareTo(stringTwo) < 0; + } + + /** + * Sort the objects in sorted collection and return that collection. + */ + private void quickSort(int left, int right) { + int originalLeft = left; + int originalRight = right; + int midIndex = (left + right) / 2; + String midToString = this.sortedStrings[midIndex]; + + do { + while (compare(this.sortedStrings[left], midToString)) + left++; + while (compare(midToString, this.sortedStrings[right])) + right--; + if (left <= right) { + Object tmp = this.sortedObjects[left]; + this.sortedObjects[left] = this.sortedObjects[right]; + this.sortedObjects[right] = tmp; + String tmpToString = this.sortedStrings[left]; + this.sortedStrings[left] = this.sortedStrings[right]; + this.sortedStrings[right] = tmpToString; + left++; + right--; + } + } while (left <= right); + + if (originalLeft < right) + quickSort(originalLeft, right); + if (left < originalRight) + quickSort(left, originalRight); + } + + /** + * Return a new sorted collection from this unsorted collection. Sort using + * quick sort. + */ + public void sort(Object[] unSortedObjects, String[] unsortedStrings) { + int size = unSortedObjects.length; + this.sortedObjects = new Object[size]; + this.sortedStrings = new String[size]; + + // copy the array so can return a new sorted collection + System.arraycopy(unSortedObjects, 0, this.sortedObjects, 0, size); + System.arraycopy(unsortedStrings, 0, this.sortedStrings, 0, size); + if (size > 1) + quickSort(0, size - 1); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/Util.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/Util.java index ccfbc90..96a21b0 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/Util.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/Util.java @@ -51,1742 +51,1887 @@ import org.eclipse.text.edits.TextEdit; */ public class Util { - public interface Comparable { - /** - * Returns 0 if this and c are equal, >0 if this is greater than c, or <0 if this is less than c. - */ - int compareTo(Comparable c); - } - - public interface Comparer { - /** - * Returns 0 if a and b are equal, >0 if a is greater than b, or <0 if a is less than b. - */ - int compare(Object a, Object b); - } - - private static final String ARGUMENTS_DELIMITER = "#"; //$NON-NLS-1$ - - /* Bundle containing messages */ - protected static ResourceBundle bundle; - - private final static String bundleName = "net.sourceforge.phpdt.internal.core.util.messages"; //$NON-NLS-1$ - - private final static char[] DOUBLE_QUOTES = "''".toCharArray(); //$NON-NLS-1$ - - private static final String EMPTY_ARGUMENT = " "; //$NON-NLS-1$ - - public static final String[] fgEmptyStringArray = new String[0]; - - private final static char[] SINGLE_QUOTE = "'".toCharArray(); //$NON-NLS-1$ - - static { - relocalize(); - } - - private Util() { - // cannot be instantiated - } - - /** - * Lookup the message with the given ID in this catalog - */ - public static String bind(String id) { - return bind(id, (String[]) null); - } - - /** - * Lookup the message with the given ID in this catalog and bind its substitution locations with the given string. - */ - public static String bind(String id, String binding) { - return bind(id, new String[] { binding }); - } - - /** - * Lookup the message with the given ID in this catalog and bind its substitution locations with the given strings. - */ - public static String bind(String id, String binding1, String binding2) { - return bind(id, new String[] { binding1, binding2 }); - } - - /** - * Lookup the message with the given ID in this catalog and bind its substitution locations with the given string values. - */ - public static String bind(String id, String[] bindings) { - if (id == null) - return "No message available"; //$NON-NLS-1$ - String message = null; - try { - message = bundle.getString(id); - } catch (MissingResourceException e) { - // If we got an exception looking for the message, fail gracefully by just returning - // the id we were looking for. In most cases this is semi-informative so is not too bad. - return "Missing message: " + id + " in: " + bundleName; //$NON-NLS-2$ //$NON-NLS-1$ - } - // for compatibility with MessageFormat which eliminates double quotes in original message - char[] messageWithNoDoubleQuotes = CharOperation.replace(message.toCharArray(), DOUBLE_QUOTES, SINGLE_QUOTE); - - if (bindings == null) - return new String(messageWithNoDoubleQuotes); - - int length = messageWithNoDoubleQuotes.length; - int start = 0; - int end = length; - StringBuffer output = null; - while (true) { - if ((end = CharOperation.indexOf('{', messageWithNoDoubleQuotes, start)) > -1) { - if (output == null) - output = new StringBuffer(length + bindings.length * 20); - output.append(messageWithNoDoubleQuotes, start, end - start); - if ((start = CharOperation.indexOf('}', messageWithNoDoubleQuotes, end + 1)) > -1) { - int index = -1; - String argId = new String(messageWithNoDoubleQuotes, end + 1, start - end - 1); - try { - index = Integer.parseInt(argId); - output.append(bindings[index]); - } catch (NumberFormatException nfe) { // could be nested message ID {compiler.name} - boolean done = false; - if (!id.equals(argId)) { - String argMessage = null; - try { - argMessage = bundle.getString(argId); - output.append(argMessage); - done = true; - } catch (MissingResourceException e) { - // unable to bind argument, ignore (will leave argument in) - } - } - if (!done) - output.append(messageWithNoDoubleQuotes, end + 1, start - end); - } catch (ArrayIndexOutOfBoundsException e) { - output.append("{missing " + Integer.toString(index) + "}"); //$NON-NLS-2$ //$NON-NLS-1$ - } - start++; - } else { - output.append(messageWithNoDoubleQuotes, end, length); - break; - } - } else { - if (output == null) - return new String(messageWithNoDoubleQuotes); - output.append(messageWithNoDoubleQuotes, start, length - start); - break; - } - } - return output.toString(); - } - - /** - * Checks the type signature in String sig, starting at start and ending before end (end is not included). Returns the index of - * the character immediately after the signature if valid, or -1 if not valid. - */ - private static int checkTypeSignature(String sig, int start, int end, boolean allowVoid) { - if (start >= end) - return -1; - int i = start; - char c = sig.charAt(i++); - int nestingDepth = 0; - while (c == '[') { - ++nestingDepth; - if (i >= end) - return -1; - c = sig.charAt(i++); - } - switch (c) { - case 'B': - case 'C': - case 'D': - case 'F': - case 'I': - case 'J': - case 'S': - case 'Z': - break; - case 'V': - if (!allowVoid) - return -1; - // array of void is not allowed - if (nestingDepth != 0) - return -1; - break; - case 'L': - int semicolon = sig.indexOf(';', i); - // Must have at least one character between L and ; - if (semicolon <= i || semicolon >= end) - return -1; - i = semicolon + 1; - break; - default: - return -1; - } - return i; - } - - /** - * Combines two hash codes to make a new one. - */ - public static int combineHashCodes(int hashCode1, int hashCode2) { - return hashCode1 * 17 + hashCode2; - } - - /** - * Compares two byte arrays. Returns <0 if a byte in a is less than the corresponding byte in b, or if a is shorter, or if a is - * null. Returns >0 if a byte in a is greater than the corresponding byte in b, or if a is longer, or if b is null. Returns 0 if - * they are equal or both null. - */ - public static int compare(byte[] a, byte[] b) { - if (a == b) - return 0; - if (a == null) - return -1; - if (b == null) - return 1; - int len = Math.min(a.length, b.length); - for (int i = 0; i < len; ++i) { - int diff = a[i] - b[i]; - if (diff != 0) - return diff; - } - if (a.length > len) - return 1; - if (b.length > len) - return -1; - return 0; - } - - /** - * Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. - * - * @return the value 0 if the str1 is equal to str2; a value less than 0 if str1 is - * lexicographically less than str2; and a value greater than 0 if str1 is lexicographically greater than - * str2. - */ - public static int compare(char[] str1, char[] str2) { - int len1 = str1.length; - int len2 = str2.length; - int n = Math.min(len1, len2); - int i = 0; - while (n-- != 0) { - char c1 = str1[i]; - char c2 = str2[i++]; - if (c1 != c2) { - return c1 - c2; - } - } - return len1 - len2; - } - - /** - * Concatenate two strings with a char in between. - * - * @see #concat(String, String) - */ - public static String concat(String s1, char c, String s2) { - if (s1 == null) - s1 = "null"; //$NON-NLS-1$ - if (s2 == null) - s2 = "null"; //$NON-NLS-1$ - int l1 = s1.length(); - int l2 = s2.length(); - char[] buf = new char[l1 + 1 + l2]; - s1.getChars(0, l1, buf, 0); - buf[l1] = c; - s2.getChars(0, l2, buf, l1 + 1); - return new String(buf); - } - - /** - * Concatenate two strings. Much faster than using +, which: - creates a StringBuffer, - which is synchronized, - of default size, - * so the resulting char array is often larger than needed. This implementation creates an extra char array, since the String - * constructor copies its argument, but there's no way around this. - */ - public static String concat(String s1, String s2) { - if (s1 == null) - s1 = "null"; //$NON-NLS-1$ - if (s2 == null) - s2 = "null"; //$NON-NLS-1$ - int l1 = s1.length(); - int l2 = s2.length(); - char[] buf = new char[l1 + l2]; - s1.getChars(0, l1, buf, 0); - s2.getChars(0, l2, buf, l1); - return new String(buf); - } - - /** - * Concatenate three strings. - * - * @see #concat(String, String) - */ - public static String concat(String s1, String s2, String s3) { - if (s1 == null) - s1 = "null"; //$NON-NLS-1$ - if (s2 == null) - s2 = "null"; //$NON-NLS-1$ - if (s3 == null) - s3 = "null"; //$NON-NLS-1$ - int l1 = s1.length(); - int l2 = s2.length(); - int l3 = s3.length(); - char[] buf = new char[l1 + l2 + l3]; - s1.getChars(0, l1, buf, 0); - s2.getChars(0, l2, buf, l1); - s3.getChars(0, l3, buf, l1 + l2); - return new String(buf); - } - - /** - * Converts a type signature from the IBinaryType representation to the DC representation. - */ - public static String convertTypeSignature(char[] sig) { - return new String(sig).replace('/', '.'); - } - - /** - * Apply the given edit on the given string and return the updated string. Return the given string if anything wrong happen while - * applying the edit. - * - * @param original - * the given string - * @param edit - * the given edit - * - * @return the updated string - */ - public final static String editedString(String original, TextEdit edit) { - if (edit == null) { - return original; - } - SimpleDocument document = new SimpleDocument(original); - try { - edit.apply(document, TextEdit.NONE); - return document.get(); - } catch (MalformedTreeException e) { - e.printStackTrace(); - } catch (BadLocationException e) { - e.printStackTrace(); - } - return original; - } - - /** - * Returns true iff str.toLowerCase().endsWith(end.toLowerCase()) implementation is not creating extra strings. - */ - public final static boolean endsWithIgnoreCase(String str, String end) { - - int strLength = str == null ? 0 : str.length(); - int endLength = end == null ? 0 : end.length(); - - // return false if the string is smaller than the end. - if (endLength > strLength) - return false; - - // return false if any character of the end are - // not the same in lower case. - for (int i = 1; i <= endLength; i++) { - if (Character.toLowerCase(end.charAt(endLength - i)) != Character.toLowerCase(str.charAt(strLength - i))) - return false; - } - - return true; - } - - /** - * Compares two arrays using equals() on the elements. Either or both arrays may be null. Returns true if both are null. Returns - * false if only one is null. If both are arrays, returns true iff they have the same length and all elements are equal. - */ - public static boolean equalArraysOrNull(int[] a, int[] b) { - if (a == b) - return true; - if (a == null || b == null) - return false; - int len = a.length; - if (len != b.length) - return false; - for (int i = 0; i < len; ++i) { - if (a[i] != b[i]) - return false; - } - return true; - } - - /** - * Compares two arrays using equals() on the elements. Either or both arrays may be null. Returns true if both are null. Returns - * false if only one is null. If both are arrays, returns true iff they have the same length and all elements compare true with - * equals. - */ - public static boolean equalArraysOrNull(Object[] a, Object[] b) { - if (a == b) - return true; - if (a == null || b == null) - return false; - - int len = a.length; - if (len != b.length) - return false; - for (int i = 0; i < len; ++i) { - if (a[i] == null) { - if (b[i] != null) - return false; - } else { - if (!a[i].equals(b[i])) - return false; - } - } - return true; - } - - /** - * Compares two arrays using equals() on the elements. The arrays are first sorted. Either or both arrays may be null. Returns - * true if both are null. Returns false if only one is null. If both are arrays, returns true iff they have the same length and - * iff, after sorting both arrays, all elements compare true with equals. The original arrays are left untouched. - */ - public static boolean equalArraysOrNullSortFirst(Comparable[] a, Comparable[] b) { - if (a == b) - return true; - if (a == null || b == null) - return false; - int len = a.length; - if (len != b.length) - return false; - if (len >= 2) { // only need to sort if more than two items - a = sortCopy(a); - b = sortCopy(b); - } - for (int i = 0; i < len; ++i) { - if (!a[i].equals(b[i])) - return false; - } - return true; - } - - /** - * Compares two String arrays using equals() on the elements. The arrays are first sorted. Either or both arrays may be null. - * Returns true if both are null. Returns false if only one is null. If both are arrays, returns true iff they have the same - * length and iff, after sorting both arrays, all elements compare true with equals. The original arrays are left untouched. - */ - public static boolean equalArraysOrNullSortFirst(String[] a, String[] b) { - if (a == b) - return true; - if (a == null || b == null) - return false; - int len = a.length; - if (len != b.length) - return false; - if (len >= 2) { // only need to sort if more than two items - a = sortCopy(a); - b = sortCopy(b); - } - for (int i = 0; i < len; ++i) { - if (!a[i].equals(b[i])) - return false; - } - return true; - } - - /** - * Compares two objects using equals(). Either or both array may be null. Returns true if both are null. Returns false if only one - * is null. Otherwise, return the result of comparing with equals(). - */ - public static boolean equalOrNull(Object a, Object b) { - if (a == b) { - return true; - } - if (a == null || b == null) { - return false; - } - return a.equals(b); - } - - /** - * Given a qualified name, extract the last component. If the input is not qualified, the same string is answered. - */ - public static String extractLastName(String qualifiedName) { - int i = qualifiedName.lastIndexOf('.'); - if (i == -1) - return qualifiedName; - return qualifiedName.substring(i + 1); - } - - /** - * Extracts the parameter types from a method signature. - */ - public static String[] extractParameterTypes(char[] sig) { - int count = getParameterCount(sig); - String[] result = new String[count]; - if (count == 0) - return result; - int i = CharOperation.indexOf('(', sig) + 1; - count = 0; - int len = sig.length; - int start = i; - for (;;) { - if (i == len) - break; - char c = sig[i]; - if (c == ')') - break; - if (c == '[') { - ++i; - } else if (c == 'L') { - i = CharOperation.indexOf(';', sig, i + 1) + 1; - Assert.isTrue(i != 0); - result[count++] = convertTypeSignature(CharOperation.subarray(sig, start, i)); - start = i; - } else { - ++i; - result[count++] = convertTypeSignature(CharOperation.subarray(sig, start, i)); - start = i; - } - } - return result; - } - - /** - * Extracts the return type from a method signature. - */ - public static String extractReturnType(String sig) { - int i = sig.lastIndexOf(')'); - Assert.isTrue(i != -1); - return sig.substring(i + 1); - } - - private static IFile findFirstClassFile(IFolder folder) { - try { - IResource[] members = folder.members(); - for (int i = 0, max = members.length; i < max; i++) { - IResource member = members[i]; - if (member.getType() == IResource.FOLDER) { - return findFirstClassFile((IFolder) member); -// } else if (net.sourceforge.phpdt.internal.compiler.util.Util.isClassFileName(member.getName())) { -// return (IFile) member; - } - } - } catch (CoreException e) { - // ignore - } - return null; - } - - /** - * Finds the first line separator used by the given text. - * - * @return "\n" or "\r" or "\r\n", or null if none found - */ - public static String findLineSeparator(char[] text) { - // find the first line separator - int length = text.length; - if (length > 0) { - char nextChar = text[0]; - for (int i = 0; i < length; i++) { - char currentChar = nextChar; - nextChar = i < length - 1 ? text[i + 1] : ' '; - switch (currentChar) { - case '\n': - return "\n"; //$NON-NLS-1$ - case '\r': - return nextChar == '\n' ? "\r\n" : "\r"; //$NON-NLS-1$ //$NON-NLS-2$ - } - } - } - // not found - return null; - } - - // public static IClassFileAttribute getAttribute(IClassFileReader classFileReader, char[] attributeName) { - // IClassFileAttribute[] attributes = classFileReader.getAttributes(); - // for (int i = 0, max = attributes.length; i < max; i++) { - // if (CharOperation.equals(attributes[i].getAttributeName(), attributeName)) { - // return attributes[i]; - // } - // } - // return null; - // } - // - // public static IClassFileAttribute getAttribute(ICodeAttribute codeAttribute, char[] attributeName) { - // IClassFileAttribute[] attributes = codeAttribute.getAttributes(); - // for (int i = 0, max = attributes.length; i < max; i++) { - // if (CharOperation.equals(attributes[i].getAttributeName(), attributeName)) { - // return attributes[i]; - // } - // } - // return null; - // } - - // public static IClassFileAttribute getAttribute(IFieldInfo fieldInfo, char[] attributeName) { - // IClassFileAttribute[] attributes = fieldInfo.getAttributes(); - // for (int i = 0, max = attributes.length; i < max; i++) { - // if (CharOperation.equals(attributes[i].getAttributeName(), attributeName)) { - // return attributes[i]; - // } - // } - // return null; - // } - // - // public static IClassFileAttribute getAttribute(IMethodInfo methodInfo, char[] attributeName) { - // IClassFileAttribute[] attributes = methodInfo.getAttributes(); - // for (int i = 0, max = attributes.length; i < max; i++) { - // if (CharOperation.equals(attributes[i].getAttributeName(), attributeName)) { - // return attributes[i]; - // } - // } - // return null; - // } - /** - * Get the jdk level of this root. The value can be: - *

                                                        - *
                                                      • major < <16 + minor : see predefined constants on ClassFileConstants
                                                      • - *
                                                      • 0 if the root is a source package fragment root or if a Java model exception occured
                                                      • - *
                                                      - * Returns the jdk level - */ - // public static long getJdkLevel(Object targetLibrary) { - // try { - // ClassFileReader reader = null; - // if (targetLibrary instanceof IFolder) { - // IFile classFile = findFirstClassFile((IFolder) targetLibrary); // only internal classfolders are allowed - // if (classFile != null) { - // byte[] bytes = Util.getResourceContentsAsByteArray(classFile); - // IPath location = classFile.getLocation(); - // reader = new ClassFileReader(bytes, location == null ? null : location.toString().toCharArray()); - // } - // } else { - // // root is a jar file or a zip file - // ZipFile jar = null; - // try { - // IPath path = null; - // if (targetLibrary instanceof IResource) { - // path = ((IResource)targetLibrary).getLocation(); - // } else if (targetLibrary instanceof File){ - // File f = (File) targetLibrary; - // if (!f.isDirectory()) { - // path = new Path(((File)targetLibrary).getPath()); - // } - // } - // if (path != null) { - // jar = JavaModelManager.getJavaModelManager().getZipFile(path); - // for (Enumeration e= jar.entries(); e.hasMoreElements();) { - // ZipEntry member= (ZipEntry) e.nextElement(); - // String entryName= member.getName(); - // if (net.sourceforge.phpdt.internal.compiler.util.Util.isClassFileName(entryName)) { - // reader = ClassFileReader.read(jar, entryName); - // break; - // } - // } - // } - // } catch (CoreException e) { - // // ignore - // } finally { - // JavaModelManager.getJavaModelManager().closeZipFile(jar); - // } - // } - // if (reader != null) { - // return reader.getVersion(); - // } - // } catch(JavaModelException e) { - // // ignore - // } catch(ClassFormatException e) { - // // ignore - // } catch(IOException e) { - // // ignore - // } - // return 0; - // } - /** - * Returns the line separator used by the given buffer. Uses the given text if none found. - * - * @return "\n" or "\r" or "\r\n" - */ - private static String getLineSeparator(char[] text, char[] buffer) { - // search in this buffer's contents first - String lineSeparator = findLineSeparator(buffer); - if (lineSeparator == null) { - // search in the given text - lineSeparator = findLineSeparator(text); - if (lineSeparator == null) { - // default to system line separator - return net.sourceforge.phpdt.internal.compiler.util.Util.LINE_SEPARATOR; - } - } - return lineSeparator; - } - - /** - * Returns the number of parameter types in a method signature. - */ - public static int getParameterCount(char[] sig) { - int i = CharOperation.indexOf('(', sig) + 1; - Assert.isTrue(i != 0); - int count = 0; - int len = sig.length; - for (;;) { - if (i == len) - break; - char c = sig[i]; - if (c == ')') - break; - if (c == '[') { - ++i; - } else if (c == 'L') { - ++count; - i = CharOperation.indexOf(';', sig, i + 1) + 1; - Assert.isTrue(i != 0); - } else { - ++count; - ++i; - } - } - return count; - } - - /** - * Put all the arguments in one String. - */ - public static String getProblemArgumentsForMarker(String[] arguments) { - StringBuffer args = new StringBuffer(10); - - args.append(arguments.length); - args.append(':'); - - for (int j = 0; j < arguments.length; j++) { - if (j != 0) - args.append(ARGUMENTS_DELIMITER); - - if (arguments[j].length() == 0) { - args.append(EMPTY_ARGUMENT); - } else { - args.append(arguments[j]); - } - } - - return args.toString(); - } - - /** - * Separate all the arguments of a String made by getProblemArgumentsForMarker - */ - public static String[] getProblemArgumentsFromMarker(String argumentsString) { - if (argumentsString == null) - return null; - int index = argumentsString.indexOf(':'); - if (index == -1) - return null; - - int length = argumentsString.length(); - int numberOfArg; - try { - numberOfArg = Integer.parseInt(argumentsString.substring(0, index)); - } catch (NumberFormatException e) { - return null; - } - argumentsString = argumentsString.substring(index + 1, length); - - String[] args = new String[length]; - int count = 0; - - StringTokenizer tokenizer = new StringTokenizer(argumentsString, ARGUMENTS_DELIMITER); - while (tokenizer.hasMoreTokens()) { - String argument = tokenizer.nextToken(); - if (argument.equals(EMPTY_ARGUMENT)) - argument = ""; //$NON-NLS-1$ - args[count++] = argument; - } - - if (count != numberOfArg) - return null; - - System.arraycopy(args, 0, args = new String[count], 0, count); - return args; - } - - /** - * Returns the given file's contents as a byte array. - */ - public static byte[] getResourceContentsAsByteArray(IFile file) throws JavaModelException { - InputStream stream = null; - try { - stream = new BufferedInputStream(file.getContents(true)); - } catch (CoreException e) { - throw new JavaModelException(e); - } - try { - return net.sourceforge.phpdt.internal.compiler.util.Util.getInputStreamAsByteArray(stream, -1); - } catch (IOException e) { - throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); - } finally { - try { - stream.close(); - } catch (IOException e) { - // ignore - } - } - } - - /** - * Returns the given file's contents as a character array. - */ - public static char[] getResourceContentsAsCharArray(IFile file) throws JavaModelException { - // Get encoding from file - String encoding = null; - try { - encoding = file.getCharset(); - } catch (CoreException ce) { - // do not use any encoding - } - return getResourceContentsAsCharArray(file, encoding); - } - - public static char[] getResourceContentsAsCharArray(IFile file, String encoding) throws JavaModelException { - // Get resource contents - InputStream stream = null; - try { - stream = new BufferedInputStream(file.getContents(true)); - } catch (CoreException e) { - throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); - } - try { - return net.sourceforge.phpdt.internal.compiler.util.Util.getInputStreamAsCharArray(stream, -1, encoding); - } catch (IOException e) { - throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); - } finally { - try { - stream.close(); - } catch (IOException e) { - // ignore - } - } - } - - /** - * Returns a trimmed version the simples names returned by Signature. - */ - public static String[] getTrimmedSimpleNames(String name) { - String[] result = Signature.getSimpleNames(name); - if (result == null) - return null; - for (int i = 0, length = result.length; i < length; i++) { - result[i] = result[i].trim(); - } - return result; - } - - /* - * Returns the index of the most specific argument paths which is strictly enclosing the path to check - */ - public static int indexOfEnclosingPath(IPath checkedPath, IPath[] paths, int pathCount) { - - int bestMatch = -1, bestLength = -1; - for (int i = 0; i < pathCount; i++) { - if (paths[i].equals(checkedPath)) - continue; - if (paths[i].isPrefixOf(checkedPath)) { - int currentLength = paths[i].segmentCount(); - if (currentLength > bestLength) { - bestLength = currentLength; - bestMatch = i; - } - } - } - return bestMatch; - } - - /* - * Returns the index of the first argument paths which is equal to the path to check - */ - public static int indexOfMatchingPath(IPath checkedPath, IPath[] paths, int pathCount) { - - for (int i = 0; i < pathCount; i++) { - if (paths[i].equals(checkedPath)) - return i; - } - return -1; - } - - /* - * Returns the index of the first argument paths which is strictly nested inside the path to check - */ - public static int indexOfNestedPath(IPath checkedPath, IPath[] paths, int pathCount) { - - for (int i = 0; i < pathCount; i++) { - if (checkedPath.equals(paths[i])) - continue; - if (checkedPath.isPrefixOf(paths[i])) - return i; - } - return -1; - } - - /* - * Returns whether the given java element is exluded from its root's classpath. It doesn't check whether the root itself is on the - * classpath or not - */ - public static final boolean isExcluded(IJavaElement element) { - int elementType = element.getElementType(); - PackageFragmentRoot root = null; - IResource resource = null; - switch (elementType) { - case IJavaElement.JAVA_MODEL: - case IJavaElement.JAVA_PROJECT: - case IJavaElement.PACKAGE_FRAGMENT_ROOT: - return false; - - // case IJavaElement.PACKAGE_FRAGMENT: - // PackageFragmentRoot root = (PackageFragmentRoot)element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); - // IResource resource = element.getResource(); - // return resource != null && isExcluded(resource, root.fullInclusionPatternChars(), root.fullExclusionPatternChars()); - - case IJavaElement.COMPILATION_UNIT: - root = (PackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); - resource = element.getResource(); - // if (resource != null && isExcluded(resource, root.fullInclusionPatternChars(), root.fullExclusionPatternChars())) - // return true; - return isExcluded(element.getParent()); - - default: - IJavaElement cu = element.getAncestor(IJavaElement.COMPILATION_UNIT); - return cu != null && isExcluded(cu); - } - } - - /* - * Returns whether the given resource path matches one of the inclusion/exclusion patterns. NOTE: should not be asked directly - * using pkg root pathes - * - * @see IClasspathEntry#getInclusionPatterns - * @see IClasspathEntry#getExclusionPatterns - */ - public final static boolean isExcluded(IPath resourcePath, char[][] inclusionPatterns, char[][] exclusionPatterns, - boolean isFolderPath) { - if (inclusionPatterns == null && exclusionPatterns == null) - return false; - char[] path = resourcePath.toString().toCharArray(); - - inclusionCheck: if (inclusionPatterns != null) { - for (int i = 0, length = inclusionPatterns.length; i < length; i++) { - char[] pattern = inclusionPatterns[i]; - char[] folderPattern = pattern; - if (isFolderPath) { - int lastSlash = CharOperation.lastIndexOf('/', pattern); - if (lastSlash != -1 && lastSlash != pattern.length - 1) { // trailing slash -> adds '**' for free (see - // http://ant.apache.org/manual/dirtasks.html) - int star = CharOperation.indexOf('*', pattern, lastSlash); - if ((star == -1 || star >= pattern.length - 1 || pattern[star + 1] != '*')) { - folderPattern = CharOperation.subarray(pattern, 0, lastSlash); - } - } - } - if (CharOperation.pathMatch(folderPattern, path, true, '/')) { - break inclusionCheck; - } - } - return true; // never included - } - if (isFolderPath) { - path = CharOperation.concat(path, new char[] { '*' }, '/'); - } - exclusionCheck: if (exclusionPatterns != null) { - for (int i = 0, length = exclusionPatterns.length; i < length; i++) { - if (CharOperation.pathMatch(exclusionPatterns[i], path, true, '/')) { - return true; - } - } - } - return false; - } - - public final static boolean isExcluded(IResource resource, char[][] exclusionPatterns) { - IPath path = resource.getFullPath(); - // ensure that folders are only excluded if all of their children are excluded - return isExcluded(path, null, exclusionPatterns, resource.getType() == IResource.FOLDER); - } - - /* - * Returns whether the given resource matches one of the exclusion patterns. NOTE: should not be asked directly using pkg root - * pathes - * - * @see IClasspathEntry#getExclusionPatterns - */ - public final static boolean isExcluded(IResource resource, char[][] inclusionPatterns, char[][] exclusionPatterns) { - IPath path = resource.getFullPath(); - // ensure that folders are only excluded if all of their children are excluded - return isExcluded(path, inclusionPatterns, exclusionPatterns, resource.getType() == IResource.FOLDER); - } - - /** - * Validate the given .class file name. A .class file name must obey the following rules: - *
                                                        - *
                                                      • it must not be null - *
                                                      • it must include the ".class" suffix - *
                                                      • its prefix must be a valid identifier - *
                                                      - *

                                                      - * - * @param name - * the name of a .class file - * @return a status object with code IStatus.OK if the given name is valid as a .class file name, otherwise a - * status object indicating what is wrong with the name - */ - // public static boolean isValidClassFileName(String name) { - // return JavaConventions.validateClassFileName(name).getSeverity() != IStatus.ERROR; - // } - /** - * Validate the given compilation unit name. A compilation unit name must obey the following rules: - *
                                                        - *
                                                      • it must not be null - *
                                                      • it must include the ".java" suffix - *
                                                      • its prefix must be a valid identifier - *
                                                      - *

                                                      - * - * @param name - * the name of a compilation unit - * @return a status object with code IStatus.OK if the given name is valid as a compilation unit name, otherwise a - * status object indicating what is wrong with the name - */ - public static boolean isValidCompilationUnitName(String name) { - return PHPFileUtil.isPHPFileName(name); - // return JavaConventions.validateCompilationUnitName(name).getSeverity() != IStatus.ERROR; - } - - /** - * Returns true if the given folder name is valid for a package, false if it is not. - */ - public static boolean isValidFolderNameForPackage(String folderName) { - // return JavaConventions.validateIdentifier(folderName).getSeverity() != IStatus.ERROR; - return true; - } - /** - * Returns true if the given method signature is valid, false if it is not. - */ - public static boolean isValidMethodSignature(String sig) { - int len = sig.length(); - if (len == 0) - return false; - int i = 0; - char c = sig.charAt(i++); - if (c != '(') - return false; - if (i >= len) - return false; - while (sig.charAt(i) != ')') { - // Void is not allowed as a parameter type. - i = checkTypeSignature(sig, i, len, false); - if (i == -1) - return false; - if (i >= len) - return false; - } - ++i; - i = checkTypeSignature(sig, i, len, true); - return i == len; - } - - /** - * Returns true if the given type signature is valid, false if it is not. - */ - public static boolean isValidTypeSignature(String sig, boolean allowVoid) { - int len = sig.length(); - return checkTypeSignature(sig, 0, len, allowVoid) == len; - } - - /* - * Add a log entry - */ - public static void log(Throwable e, String message) { - Throwable nestedException; - if (e instanceof JavaModelException && (nestedException = ((JavaModelException) e).getException()) != null) { - e = nestedException; - } - IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, message, e); - JavaCore.getPlugin().getLog().log(status); - } - - /** - * Normalizes the cariage returns in the given text. They are all changed to use the given buffer's line separator. - */ - public static char[] normalizeCRs(char[] text, char[] buffer) { - CharArrayBuffer result = new CharArrayBuffer(); - int lineStart = 0; - int length = text.length; - if (length == 0) - return text; - String lineSeparator = getLineSeparator(text, buffer); - char nextChar = text[0]; - for (int i = 0; i < length; i++) { - char currentChar = nextChar; - nextChar = i < length - 1 ? text[i + 1] : ' '; - switch (currentChar) { - case '\n': - int lineLength = i - lineStart; - char[] line = new char[lineLength]; - System.arraycopy(text, lineStart, line, 0, lineLength); - result.append(line); - result.append(lineSeparator); - lineStart = i + 1; - break; - case '\r': - lineLength = i - lineStart; - if (lineLength >= 0) { - line = new char[lineLength]; - System.arraycopy(text, lineStart, line, 0, lineLength); - result.append(line); - result.append(lineSeparator); - if (nextChar == '\n') { - nextChar = ' '; - lineStart = i + 2; - } else { - // when line separator are mixed in the same file - // \r might not be followed by a \n. If not, we should increment - // lineStart by one and not by two. - lineStart = i + 1; - } - } else { - // when line separator are mixed in the same file - // we need to prevent NegativeArraySizeException - lineStart = i + 1; - } - break; - } - } - char[] lastLine; - if (lineStart > 0) { - int lastLineLength = length - lineStart; - if (lastLineLength > 0) { - lastLine = new char[lastLineLength]; - System.arraycopy(text, lineStart, lastLine, 0, lastLineLength); - result.append(lastLine); - } - return result.getContents(); - } - return text; - } - - /** - * Normalizes the cariage returns in the given text. They are all changed to use given buffer's line sepatator. - */ - public static String normalizeCRs(String text, String buffer) { - return new String(normalizeCRs(text.toCharArray(), buffer.toCharArray())); - } - - /** - * Converts the given relative path into a package name. Returns null if the path is not a valid package name. - */ - public static String packageName(IPath pkgPath) { - StringBuffer pkgName = new StringBuffer(IPackageFragment.DEFAULT_PACKAGE_NAME); - for (int j = 0, max = pkgPath.segmentCount(); j < max; j++) { - String segment = pkgPath.segment(j); - // if (!isValidFolderNameForPackage(segment)) { - // return null; - // } - pkgName.append(segment); - if (j < pkgPath.segmentCount() - 1) { - pkgName.append("."); //$NON-NLS-1$ - } - } - return pkgName.toString(); - } - - /** - * Returns the length of the common prefix between s1 and s2. - */ - public static int prefixLength(char[] s1, char[] s2) { - int len = 0; - int max = Math.min(s1.length, s2.length); - for (int i = 0; i < max && s1[i] == s2[i]; ++i) - ++len; - return len; - } - - /** - * Returns the length of the common prefix between s1 and s2. - */ - public static int prefixLength(String s1, String s2) { - int len = 0; - int max = Math.min(s1.length(), s2.length()); - for (int i = 0; i < max && s1.charAt(i) == s2.charAt(i); ++i) - ++len; - return len; - } - - private static void quickSort(char[][] list, int left, int right) { - int original_left = left; - int original_right = right; - char[] mid = list[(left + right) / 2]; - do { - while (compare(list[left], mid) < 0) { - left++; - } - while (compare(mid, list[right]) < 0) { - right--; - } - if (left <= right) { - char[] tmp = list[left]; - list[left] = list[right]; - list[right] = tmp; - left++; - right--; - } - } while (left <= right); - if (original_left < right) { - quickSort(list, original_left, right); - } - if (left < original_right) { - quickSort(list, left, original_right); - } - } - - /** - * Sort the comparable objects in the given collection. - */ - private static void quickSort(Comparable[] sortedCollection, int left, int right) { - int original_left = left; - int original_right = right; - Comparable mid = sortedCollection[(left + right) / 2]; - do { - while (sortedCollection[left].compareTo(mid) < 0) { - left++; - } - while (mid.compareTo(sortedCollection[right]) < 0) { - right--; - } - if (left <= right) { - Comparable tmp = sortedCollection[left]; - sortedCollection[left] = sortedCollection[right]; - sortedCollection[right] = tmp; - left++; - right--; - } - } while (left <= right); - if (original_left < right) { - quickSort(sortedCollection, original_left, right); - } - if (left < original_right) { - quickSort(sortedCollection, left, original_right); - } - } - - private static void quickSort(int[] list, int left, int right) { - int original_left = left; - int original_right = right; - int mid = list[(left + right) / 2]; - do { - while (list[left] < mid) { - left++; - } - while (mid < list[right]) { - right--; - } - if (left <= right) { - int tmp = list[left]; - list[left] = list[right]; - list[right] = tmp; - left++; - right--; - } - } while (left <= right); - if (original_left < right) { - quickSort(list, original_left, right); - } - if (left < original_right) { - quickSort(list, left, original_right); - } - } - - /** - * Sort the objects in the given collection using the given comparer. - */ - private static void quickSort(Object[] sortedCollection, int left, int right, Comparer comparer) { - int original_left = left; - int original_right = right; - Object mid = sortedCollection[(left + right) / 2]; - do { - while (comparer.compare(sortedCollection[left], mid) < 0) { - left++; - } - while (comparer.compare(mid, sortedCollection[right]) < 0) { - right--; - } - if (left <= right) { - Object tmp = sortedCollection[left]; - sortedCollection[left] = sortedCollection[right]; - sortedCollection[right] = tmp; - left++; - right--; - } - } while (left <= right); - if (original_left < right) { - quickSort(sortedCollection, original_left, right, comparer); - } - if (left < original_right) { - quickSort(sortedCollection, left, original_right, comparer); - } - } - - /** - * Sort the objects in the given collection using the given sort order. - */ - private static void quickSort(Object[] sortedCollection, int left, int right, int[] sortOrder) { - int original_left = left; - int original_right = right; - int mid = sortOrder[(left + right) / 2]; - do { - while (sortOrder[left] < mid) { - left++; - } - while (mid < sortOrder[right]) { - right--; - } - if (left <= right) { - Object tmp = sortedCollection[left]; - sortedCollection[left] = sortedCollection[right]; - sortedCollection[right] = tmp; - int tmp2 = sortOrder[left]; - sortOrder[left] = sortOrder[right]; - sortOrder[right] = tmp2; - left++; - right--; - } - } while (left <= right); - if (original_left < right) { - quickSort(sortedCollection, original_left, right, sortOrder); - } - if (left < original_right) { - quickSort(sortedCollection, left, original_right, sortOrder); - } - } - - /** - * Sort the strings in the given collection. - */ - private static void quickSort(String[] sortedCollection, int left, int right) { - int original_left = left; - int original_right = right; - String mid = sortedCollection[(left + right) / 2]; - do { - while (sortedCollection[left].compareTo(mid) < 0) { - left++; - } - while (mid.compareTo(sortedCollection[right]) < 0) { - right--; - } - if (left <= right) { - String tmp = sortedCollection[left]; - sortedCollection[left] = sortedCollection[right]; - sortedCollection[right] = tmp; - left++; - right--; - } - } while (left <= right); - if (original_left < right) { - quickSort(sortedCollection, original_left, right); - } - if (left < original_right) { - quickSort(sortedCollection, left, original_right); - } - } - - /** - * Sort the strings in the given collection in reverse alphabetical order. - */ - private static void quickSortReverse(String[] sortedCollection, int left, int right) { - int original_left = left; - int original_right = right; - String mid = sortedCollection[(left + right) / 2]; - do { - while (sortedCollection[left].compareTo(mid) > 0) { - left++; - } - while (mid.compareTo(sortedCollection[right]) > 0) { - right--; - } - if (left <= right) { - String tmp = sortedCollection[left]; - sortedCollection[left] = sortedCollection[right]; - sortedCollection[right] = tmp; - left++; - right--; - } - } while (left <= right); - if (original_left < right) { - quickSortReverse(sortedCollection, original_left, right); - } - if (left < original_right) { - quickSortReverse(sortedCollection, left, original_right); - } - } - - /** - * Reads in a string from the specified data input stream. The string has been encoded using a modified UTF-8 format. - *

                                                      - * The first two bytes are read as if by readUnsignedShort. This value gives the number of following bytes that - * are in the encoded string, not the length of the resulting string. The following bytes are then interpreted as bytes encoding - * characters in the UTF-8 format and are converted into characters. - *

                                                      - * This method blocks until all the bytes are read, the end of the stream is detected, or an exception is thrown. - * - * @param in - * a data input stream. - * @return a Unicode string. - * @exception EOFException - * if the input stream reaches the end before all the bytes. - * @exception IOException - * if an I/O error occurs. - * @exception UTFDataFormatException - * if the bytes do not represent a valid UTF-8 encoding of a Unicode string. - * @see java.io.DataInputStream#readUnsignedShort() - */ - public final static char[] readUTF(DataInput in) throws IOException { - int utflen = in.readUnsignedShort(); - char str[] = new char[utflen]; - int count = 0; - int strlen = 0; - while (count < utflen) { - int c = in.readUnsignedByte(); - int char2, char3; - switch (c >> 4) { - case 0: - case 1: - case 2: - case 3: - case 4: - case 5: - case 6: - case 7: - // 0xxxxxxx - count++; - str[strlen++] = (char) c; - break; - case 12: - case 13: - // 110x xxxx 10xx xxxx - count += 2; - if (count > utflen) - throw new UTFDataFormatException(); - char2 = in.readUnsignedByte(); - if ((char2 & 0xC0) != 0x80) - throw new UTFDataFormatException(); - str[strlen++] = (char) (((c & 0x1F) << 6) | (char2 & 0x3F)); - break; - case 14: - // 1110 xxxx 10xx xxxx 10xx xxxx - count += 3; - if (count > utflen) - throw new UTFDataFormatException(); - char2 = in.readUnsignedByte(); - char3 = in.readUnsignedByte(); - if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) - throw new UTFDataFormatException(); - str[strlen++] = (char) (((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)); - break; - default: - // 10xx xxxx, 1111 xxxx - throw new UTFDataFormatException(); - } - } - if (strlen < utflen) { - System.arraycopy(str, 0, str = new char[strlen], 0, strlen); - } - return str; - } - - /** - * Creates a NLS catalog for the given locale. - */ - public static void relocalize() { - try { - bundle = ResourceBundle.getBundle(bundleName, Locale.getDefault()); - } catch (MissingResourceException e) { - System.out.println("Missing resource : " + bundleName.replace('.', '/') + ".properties for locale " + Locale.getDefault()); //$NON-NLS-1$//$NON-NLS-2$ - throw e; - } - } - - public static void sort(char[][] list) { - if (list.length > 1) - quickSort(list, 0, list.length - 1); - } - - /** - * Sorts an array of Comparable objects in place. - */ - public static void sort(Comparable[] objects) { - if (objects.length > 1) - quickSort(objects, 0, objects.length - 1); - } - - public static void sort(int[] list) { - if (list.length > 1) - quickSort(list, 0, list.length - 1); - } - - /** - * Sorts an array of objects in place. The given comparer compares pairs of items. - */ - public static void sort(Object[] objects, Comparer comparer) { - if (objects.length > 1) - quickSort(objects, 0, objects.length - 1, comparer); - } - - /** - * Sorts an array of objects in place, using the sort order given for each item. - */ - public static void sort(Object[] objects, int[] sortOrder) { - if (objects.length > 1) - quickSort(objects, 0, objects.length - 1, sortOrder); - } - - /** - * Sorts an array of strings in place using quicksort. - */ - public static void sort(String[] strings) { - if (strings.length > 1) - quickSort(strings, 0, strings.length - 1); - } - - /** - * Sorts an array of Comparable objects, returning a new array with the sorted items. The original array is left untouched. - */ - public static Comparable[] sortCopy(Comparable[] objects) { - int len = objects.length; - Comparable[] copy = new Comparable[len]; - System.arraycopy(objects, 0, copy, 0, len); - sort(copy); - return copy; - } - - /** - * Sorts an array of Strings, returning a new array with the sorted items. The original array is left untouched. - */ - public static Object[] sortCopy(Object[] objects, Comparer comparer) { - int len = objects.length; - Object[] copy = new Object[len]; - System.arraycopy(objects, 0, copy, 0, len); - sort(copy, comparer); - return copy; - } - - /** - * Sorts an array of Strings, returning a new array with the sorted items. The original array is left untouched. - */ - public static String[] sortCopy(String[] objects) { - int len = objects.length; - String[] copy = new String[len]; - System.arraycopy(objects, 0, copy, 0, len); - sort(copy); - return copy; - } - - /** - * Sorts an array of strings in place using quicksort in reverse alphabetical order. - */ - public static void sortReverseOrder(String[] strings) { - if (strings.length > 1) - quickSortReverse(strings, 0, strings.length - 1); - } - - /** - * Converts a String[] to char[][]. - */ - public static char[][] toCharArrays(String[] a) { - int len = a.length; - char[][] result = new char[len][]; - for (int i = 0; i < len; ++i) { - result[i] = toChars(a[i]); - } - return result; - } - - /** - * Converts a String to char[]. - */ - public static char[] toChars(String s) { - int len = s.length(); - char[] chars = new char[len]; - s.getChars(0, len, chars, 0); - return chars; - } - - /** - * Converts a String to char[][], where segments are separate by '.'. - */ - public static char[][] toCompoundChars(String s) { - int len = s.length(); - if (len == 0) { - return CharOperation.NO_CHAR_CHAR; - } - int segCount = 1; - for (int off = s.indexOf('.'); off != -1; off = s.indexOf('.', off + 1)) { - ++segCount; - } - char[][] segs = new char[segCount][]; - int start = 0; - for (int i = 0; i < segCount; ++i) { - int dot = s.indexOf('.', start); - int end = (dot == -1 ? s.length() : dot); - segs[i] = new char[end - start]; - s.getChars(start, end, segs[i], 0); - start = end + 1; - } - return segs; - } - - /** - * Converts a char[] to String. - */ - public static String toString(char[] c) { - return new String(c); - } - - /** - * Converts a char[][] to String, where segments are separated by '.'. - */ - public static String toString(char[][] c) { - StringBuffer sb = new StringBuffer(); - for (int i = 0, max = c.length; i < max; ++i) { - if (i != 0) - sb.append('.'); - sb.append(c[i]); - } - return sb.toString(); - } - - /** - * Converts a char[][] and a char[] to String, where segments are separated by '.'. - */ - public static String toString(char[][] c, char[] d) { - if (c == null) - return new String(d); - StringBuffer sb = new StringBuffer(); - for (int i = 0, max = c.length; i < max; ++i) { - sb.append(c[i]); - sb.append('.'); - } - sb.append(d); - return sb.toString(); - } - - /* - * Returns the unresolved type parameter signatures of the given method e.g. {"QString;", "[int", "[[Qjava.util.Vector;"} - */ - // public static String[] typeParameterSignatures(AbstractMethodDeclaration method) { - // Argument[] args = method.arguments; - // if (args != null) { - // int length = args.length; - // String[] signatures = new String[length]; - // for (int i = 0; i < args.length; i++) { - // Argument arg = args[i]; - // signatures[i] = typeSignature(arg.type); - // } - // return signatures; - // } - // return new String[0]; - // } - /* - * Returns the unresolved type signature of the given type reference, e.g. "QString;", "[int", "[[Qjava.util.Vector;" - */ - // public static String typeSignature(TypeReference type) { - // char[][] compoundName = type.getTypeName(); - // char[] typeName =CharOperation.concatWith(compoundName, '.'); - // String signature = Signature.createTypeSignature(typeName, false/*don't resolve*/); - // int dimensions = type.dimensions(); - // if (dimensions > 0) { - // signature = Signature.createArraySignature(signature, dimensions); - // } - // return signature; - // } - /* - * Returns the unresolved type signature of the given type reference, - * e.g. "QString;", "[int", "[[Qjava.util.Vector;" + public interface Comparable { + /** + * Returns 0 if this and c are equal, >0 if this is greater than c, or + * <0 if this is less than c. + */ + int compareTo(Comparable c); + } + + public interface Comparer { + /** + * Returns 0 if a and b are equal, >0 if a is greater than b, or <0 if a + * is less than b. + */ + int compare(Object a, Object b); + } + + private static final String ARGUMENTS_DELIMITER = "#"; //$NON-NLS-1$ + + /* Bundle containing messages */ + protected static ResourceBundle bundle; + + private final static String bundleName = "net.sourceforge.phpdt.internal.core.util.messages"; //$NON-NLS-1$ + + private final static char[] DOUBLE_QUOTES = "''".toCharArray(); //$NON-NLS-1$ + + private static final String EMPTY_ARGUMENT = " "; //$NON-NLS-1$ + + public static final String[] fgEmptyStringArray = new String[0]; + + private final static char[] SINGLE_QUOTE = "'".toCharArray(); //$NON-NLS-1$ + + static { + relocalize(); + } + + private Util() { + // cannot be instantiated + } + + /** + * Lookup the message with the given ID in this catalog + */ + public static String bind(String id) { + return bind(id, (String[]) null); + } + + /** + * Lookup the message with the given ID in this catalog and bind its + * substitution locations with the given string. + */ + public static String bind(String id, String binding) { + return bind(id, new String[] { binding }); + } + + /** + * Lookup the message with the given ID in this catalog and bind its + * substitution locations with the given strings. + */ + public static String bind(String id, String binding1, String binding2) { + return bind(id, new String[] { binding1, binding2 }); + } + + /** + * Lookup the message with the given ID in this catalog and bind its + * substitution locations with the given string values. + */ + public static String bind(String id, String[] bindings) { + if (id == null) + return "No message available"; //$NON-NLS-1$ + String message = null; + try { + message = bundle.getString(id); + } catch (MissingResourceException e) { + // If we got an exception looking for the message, fail gracefully + // by just returning + // the id we were looking for. In most cases this is + // semi-informative so is not too bad. + return "Missing message: " + id + " in: " + bundleName; //$NON-NLS-2$ //$NON-NLS-1$ + } + // for compatibility with MessageFormat which eliminates double quotes + // in original message + char[] messageWithNoDoubleQuotes = CharOperation.replace(message + .toCharArray(), DOUBLE_QUOTES, SINGLE_QUOTE); + + if (bindings == null) + return new String(messageWithNoDoubleQuotes); + + int length = messageWithNoDoubleQuotes.length; + int start = 0; + int end = length; + StringBuffer output = null; + while (true) { + if ((end = CharOperation.indexOf('{', messageWithNoDoubleQuotes, + start)) > -1) { + if (output == null) + output = new StringBuffer(length + bindings.length * 20); + output.append(messageWithNoDoubleQuotes, start, end - start); + if ((start = CharOperation.indexOf('}', + messageWithNoDoubleQuotes, end + 1)) > -1) { + int index = -1; + String argId = new String(messageWithNoDoubleQuotes, + end + 1, start - end - 1); + try { + index = Integer.parseInt(argId); + output.append(bindings[index]); + } catch (NumberFormatException nfe) { // could be nested + // message ID + // {compiler.name} + boolean done = false; + if (!id.equals(argId)) { + String argMessage = null; + try { + argMessage = bundle.getString(argId); + output.append(argMessage); + done = true; + } catch (MissingResourceException e) { + // unable to bind argument, ignore (will leave + // argument in) + } + } + if (!done) + output.append(messageWithNoDoubleQuotes, end + 1, + start - end); + } catch (ArrayIndexOutOfBoundsException e) { + output + .append("{missing " + Integer.toString(index) + "}"); //$NON-NLS-2$ //$NON-NLS-1$ + } + start++; + } else { + output.append(messageWithNoDoubleQuotes, end, length); + break; + } + } else { + if (output == null) + return new String(messageWithNoDoubleQuotes); + output.append(messageWithNoDoubleQuotes, start, length - start); + break; + } + } + return output.toString(); + } + + /** + * Checks the type signature in String sig, starting at start and ending + * before end (end is not included). Returns the index of the character + * immediately after the signature if valid, or -1 if not valid. + */ + private static int checkTypeSignature(String sig, int start, int end, + boolean allowVoid) { + if (start >= end) + return -1; + int i = start; + char c = sig.charAt(i++); + int nestingDepth = 0; + while (c == '[') { + ++nestingDepth; + if (i >= end) + return -1; + c = sig.charAt(i++); + } + switch (c) { + case 'B': + case 'C': + case 'D': + case 'F': + case 'I': + case 'J': + case 'S': + case 'Z': + break; + case 'V': + if (!allowVoid) + return -1; + // array of void is not allowed + if (nestingDepth != 0) + return -1; + break; + case 'L': + int semicolon = sig.indexOf(';', i); + // Must have at least one character between L and ; + if (semicolon <= i || semicolon >= end) + return -1; + i = semicolon + 1; + break; + default: + return -1; + } + return i; + } + + /** + * Combines two hash codes to make a new one. + */ + public static int combineHashCodes(int hashCode1, int hashCode2) { + return hashCode1 * 17 + hashCode2; + } + + /** + * Compares two byte arrays. Returns <0 if a byte in a is less than the + * corresponding byte in b, or if a is shorter, or if a is null. Returns >0 + * if a byte in a is greater than the corresponding byte in b, or if a is + * longer, or if b is null. Returns 0 if they are equal or both null. + */ + public static int compare(byte[] a, byte[] b) { + if (a == b) + return 0; + if (a == null) + return -1; + if (b == null) + return 1; + int len = Math.min(a.length, b.length); + for (int i = 0; i < len; ++i) { + int diff = a[i] - b[i]; + if (diff != 0) + return diff; + } + if (a.length > len) + return 1; + if (b.length > len) + return -1; + return 0; + } + + /** + * Compares two strings lexicographically. The comparison is based on the + * Unicode value of each character in the strings. + * + * @return the value 0 if the str1 is equal to str2; a value + * less than 0 if str1 is lexicographically less than + * str2; and a value greater than 0 if str1 is + * lexicographically greater than str2. + */ + public static int compare(char[] str1, char[] str2) { + int len1 = str1.length; + int len2 = str2.length; + int n = Math.min(len1, len2); + int i = 0; + while (n-- != 0) { + char c1 = str1[i]; + char c2 = str2[i++]; + if (c1 != c2) { + return c1 - c2; + } + } + return len1 - len2; + } + + /** + * Concatenate two strings with a char in between. + * + * @see #concat(String, String) + */ + public static String concat(String s1, char c, String s2) { + if (s1 == null) + s1 = "null"; //$NON-NLS-1$ + if (s2 == null) + s2 = "null"; //$NON-NLS-1$ + int l1 = s1.length(); + int l2 = s2.length(); + char[] buf = new char[l1 + 1 + l2]; + s1.getChars(0, l1, buf, 0); + buf[l1] = c; + s2.getChars(0, l2, buf, l1 + 1); + return new String(buf); + } + + /** + * Concatenate two strings. Much faster than using +, which: - creates a + * StringBuffer, - which is synchronized, - of default size, so the + * resulting char array is often larger than needed. This implementation + * creates an extra char array, since the String constructor copies its + * argument, but there's no way around this. + */ + public static String concat(String s1, String s2) { + if (s1 == null) + s1 = "null"; //$NON-NLS-1$ + if (s2 == null) + s2 = "null"; //$NON-NLS-1$ + int l1 = s1.length(); + int l2 = s2.length(); + char[] buf = new char[l1 + l2]; + s1.getChars(0, l1, buf, 0); + s2.getChars(0, l2, buf, l1); + return new String(buf); + } + + /** + * Concatenate three strings. + * + * @see #concat(String, String) + */ + public static String concat(String s1, String s2, String s3) { + if (s1 == null) + s1 = "null"; //$NON-NLS-1$ + if (s2 == null) + s2 = "null"; //$NON-NLS-1$ + if (s3 == null) + s3 = "null"; //$NON-NLS-1$ + int l1 = s1.length(); + int l2 = s2.length(); + int l3 = s3.length(); + char[] buf = new char[l1 + l2 + l3]; + s1.getChars(0, l1, buf, 0); + s2.getChars(0, l2, buf, l1); + s3.getChars(0, l3, buf, l1 + l2); + return new String(buf); + } + + /** + * Converts a type signature from the IBinaryType representation to the DC + * representation. + */ + public static String convertTypeSignature(char[] sig) { + return new String(sig).replace('/', '.'); + } + + /** + * Apply the given edit on the given string and return the updated string. + * Return the given string if anything wrong happen while applying the edit. + * + * @param original + * the given string + * @param edit + * the given edit + * + * @return the updated string + */ + public final static String editedString(String original, TextEdit edit) { + if (edit == null) { + return original; + } + SimpleDocument document = new SimpleDocument(original); + try { + edit.apply(document, TextEdit.NONE); + return document.get(); + } catch (MalformedTreeException e) { + e.printStackTrace(); + } catch (BadLocationException e) { + e.printStackTrace(); + } + return original; + } + + /** + * Returns true iff str.toLowerCase().endsWith(end.toLowerCase()) + * implementation is not creating extra strings. + */ + public final static boolean endsWithIgnoreCase(String str, String end) { + + int strLength = str == null ? 0 : str.length(); + int endLength = end == null ? 0 : end.length(); + + // return false if the string is smaller than the end. + if (endLength > strLength) + return false; + + // return false if any character of the end are + // not the same in lower case. + for (int i = 1; i <= endLength; i++) { + if (Character.toLowerCase(end.charAt(endLength - i)) != Character + .toLowerCase(str.charAt(strLength - i))) + return false; + } + + return true; + } + + /** + * Compares two arrays using equals() on the elements. Either or both arrays + * may be null. Returns true if both are null. Returns false if only one is + * null. If both are arrays, returns true iff they have the same length and + * all elements are equal. + */ + public static boolean equalArraysOrNull(int[] a, int[] b) { + if (a == b) + return true; + if (a == null || b == null) + return false; + int len = a.length; + if (len != b.length) + return false; + for (int i = 0; i < len; ++i) { + if (a[i] != b[i]) + return false; + } + return true; + } + + /** + * Compares two arrays using equals() on the elements. Either or both arrays + * may be null. Returns true if both are null. Returns false if only one is + * null. If both are arrays, returns true iff they have the same length and + * all elements compare true with equals. + */ + public static boolean equalArraysOrNull(Object[] a, Object[] b) { + if (a == b) + return true; + if (a == null || b == null) + return false; + + int len = a.length; + if (len != b.length) + return false; + for (int i = 0; i < len; ++i) { + if (a[i] == null) { + if (b[i] != null) + return false; + } else { + if (!a[i].equals(b[i])) + return false; + } + } + return true; + } + + /** + * Compares two arrays using equals() on the elements. The arrays are first + * sorted. Either or both arrays may be null. Returns true if both are null. + * Returns false if only one is null. If both are arrays, returns true iff + * they have the same length and iff, after sorting both arrays, all + * elements compare true with equals. The original arrays are left + * untouched. + */ + public static boolean equalArraysOrNullSortFirst(Comparable[] a, + Comparable[] b) { + if (a == b) + return true; + if (a == null || b == null) + return false; + int len = a.length; + if (len != b.length) + return false; + if (len >= 2) { // only need to sort if more than two items + a = sortCopy(a); + b = sortCopy(b); + } + for (int i = 0; i < len; ++i) { + if (!a[i].equals(b[i])) + return false; + } + return true; + } + + /** + * Compares two String arrays using equals() on the elements. The arrays are + * first sorted. Either or both arrays may be null. Returns true if both are + * null. Returns false if only one is null. If both are arrays, returns true + * iff they have the same length and iff, after sorting both arrays, all + * elements compare true with equals. The original arrays are left + * untouched. + */ + public static boolean equalArraysOrNullSortFirst(String[] a, String[] b) { + if (a == b) + return true; + if (a == null || b == null) + return false; + int len = a.length; + if (len != b.length) + return false; + if (len >= 2) { // only need to sort if more than two items + a = sortCopy(a); + b = sortCopy(b); + } + for (int i = 0; i < len; ++i) { + if (!a[i].equals(b[i])) + return false; + } + return true; + } + + /** + * Compares two objects using equals(). Either or both array may be null. + * Returns true if both are null. Returns false if only one is null. + * Otherwise, return the result of comparing with equals(). + */ + public static boolean equalOrNull(Object a, Object b) { + if (a == b) { + return true; + } + if (a == null || b == null) { + return false; + } + return a.equals(b); + } + + /** + * Given a qualified name, extract the last component. If the input is not + * qualified, the same string is answered. + */ + public static String extractLastName(String qualifiedName) { + int i = qualifiedName.lastIndexOf('.'); + if (i == -1) + return qualifiedName; + return qualifiedName.substring(i + 1); + } + + /** + * Extracts the parameter types from a method signature. + */ + public static String[] extractParameterTypes(char[] sig) { + int count = getParameterCount(sig); + String[] result = new String[count]; + if (count == 0) + return result; + int i = CharOperation.indexOf('(', sig) + 1; + count = 0; + int len = sig.length; + int start = i; + for (;;) { + if (i == len) + break; + char c = sig[i]; + if (c == ')') + break; + if (c == '[') { + ++i; + } else if (c == 'L') { + i = CharOperation.indexOf(';', sig, i + 1) + 1; + Assert.isTrue(i != 0); + result[count++] = convertTypeSignature(CharOperation.subarray( + sig, start, i)); + start = i; + } else { + ++i; + result[count++] = convertTypeSignature(CharOperation.subarray( + sig, start, i)); + start = i; + } + } + return result; + } + + /** + * Extracts the return type from a method signature. + */ + public static String extractReturnType(String sig) { + int i = sig.lastIndexOf(')'); + Assert.isTrue(i != -1); + return sig.substring(i + 1); + } + + private static IFile findFirstClassFile(IFolder folder) { + try { + IResource[] members = folder.members(); + for (int i = 0, max = members.length; i < max; i++) { + IResource member = members[i]; + if (member.getType() == IResource.FOLDER) { + return findFirstClassFile((IFolder) member); + // } else if + // (net.sourceforge.phpdt.internal.compiler.util.Util.isClassFileName(member.getName())) + // { + // return (IFile) member; + } + } + } catch (CoreException e) { + // ignore + } + return null; + } + + /** + * Finds the first line separator used by the given text. + * + * @return "\n" or "\r" or "\r\n", + * or null if none found + */ + public static String findLineSeparator(char[] text) { + // find the first line separator + int length = text.length; + if (length > 0) { + char nextChar = text[0]; + for (int i = 0; i < length; i++) { + char currentChar = nextChar; + nextChar = i < length - 1 ? text[i + 1] : ' '; + switch (currentChar) { + case '\n': + return "\n"; //$NON-NLS-1$ + case '\r': + return nextChar == '\n' ? "\r\n" : "\r"; //$NON-NLS-1$ //$NON-NLS-2$ + } + } + } + // not found + return null; + } + + // public static IClassFileAttribute getAttribute(IClassFileReader + // classFileReader, char[] attributeName) { + // IClassFileAttribute[] attributes = classFileReader.getAttributes(); + // for (int i = 0, max = attributes.length; i < max; i++) { + // if (CharOperation.equals(attributes[i].getAttributeName(), + // attributeName)) { + // return attributes[i]; + // } + // } + // return null; + // } + // + // public static IClassFileAttribute getAttribute(ICodeAttribute + // codeAttribute, char[] attributeName) { + // IClassFileAttribute[] attributes = codeAttribute.getAttributes(); + // for (int i = 0, max = attributes.length; i < max; i++) { + // if (CharOperation.equals(attributes[i].getAttributeName(), + // attributeName)) { + // return attributes[i]; + // } + // } + // return null; + // } + + // public static IClassFileAttribute getAttribute(IFieldInfo fieldInfo, + // char[] attributeName) { + // IClassFileAttribute[] attributes = fieldInfo.getAttributes(); + // for (int i = 0, max = attributes.length; i < max; i++) { + // if (CharOperation.equals(attributes[i].getAttributeName(), + // attributeName)) { + // return attributes[i]; + // } + // } + // return null; + // } + // + // public static IClassFileAttribute getAttribute(IMethodInfo methodInfo, + // char[] attributeName) { + // IClassFileAttribute[] attributes = methodInfo.getAttributes(); + // for (int i = 0, max = attributes.length; i < max; i++) { + // if (CharOperation.equals(attributes[i].getAttributeName(), + // attributeName)) { + // return attributes[i]; + // } + // } + // return null; + // } + /** + * Get the jdk level of this root. The value can be: + *

                                                        + *
                                                      • major < <16 + minor : see predefined constants on ClassFileConstants
                                                      • + *
                                                      • 0 if the root is a source package fragment root or if a Java model exception occured
                                                      • + *
                                                      + * Returns the jdk level + */ + // public static long getJdkLevel(Object targetLibrary) { + // try { + // ClassFileReader reader = null; + // if (targetLibrary instanceof IFolder) { + // IFile classFile = findFirstClassFile((IFolder) targetLibrary); // only + // internal classfolders are allowed + // if (classFile != null) { + // byte[] bytes = Util.getResourceContentsAsByteArray(classFile); + // IPath location = classFile.getLocation(); + // reader = new ClassFileReader(bytes, location == null ? null : + // location.toString().toCharArray()); + // } + // } else { + // // root is a jar file or a zip file + // ZipFile jar = null; + // try { + // IPath path = null; + // if (targetLibrary instanceof IResource) { + // path = ((IResource)targetLibrary).getLocation(); + // } else if (targetLibrary instanceof File){ + // File f = (File) targetLibrary; + // if (!f.isDirectory()) { + // path = new Path(((File)targetLibrary).getPath()); + // } + // } + // if (path != null) { + // jar = JavaModelManager.getJavaModelManager().getZipFile(path); + // for (Enumeration e= jar.entries(); e.hasMoreElements();) { + // ZipEntry member= (ZipEntry) e.nextElement(); + // String entryName= member.getName(); + // if + // (net.sourceforge.phpdt.internal.compiler.util.Util.isClassFileName(entryName)) + // { + // reader = ClassFileReader.read(jar, entryName); + // break; + // } + // } + // } + // } catch (CoreException e) { + // // ignore + // } finally { + // JavaModelManager.getJavaModelManager().closeZipFile(jar); + // } + // } + // if (reader != null) { + // return reader.getVersion(); + // } + // } catch(JavaModelException e) { + // // ignore + // } catch(ClassFormatException e) { + // // ignore + // } catch(IOException e) { + // // ignore + // } + // return 0; + // } + /** + * Returns the line separator used by the given buffer. Uses the given text + * if none found. + * + * @return "\n" or "\r" or "\r\n" + */ + private static String getLineSeparator(char[] text, char[] buffer) { + // search in this buffer's contents first + String lineSeparator = findLineSeparator(buffer); + if (lineSeparator == null) { + // search in the given text + lineSeparator = findLineSeparator(text); + if (lineSeparator == null) { + // default to system line separator + return net.sourceforge.phpdt.internal.compiler.util.Util.LINE_SEPARATOR; + } + } + return lineSeparator; + } + + /** + * Returns the number of parameter types in a method signature. + */ + public static int getParameterCount(char[] sig) { + int i = CharOperation.indexOf('(', sig) + 1; + Assert.isTrue(i != 0); + int count = 0; + int len = sig.length; + for (;;) { + if (i == len) + break; + char c = sig[i]; + if (c == ')') + break; + if (c == '[') { + ++i; + } else if (c == 'L') { + ++count; + i = CharOperation.indexOf(';', sig, i + 1) + 1; + Assert.isTrue(i != 0); + } else { + ++count; + ++i; + } + } + return count; + } + + /** + * Put all the arguments in one String. + */ + public static String getProblemArgumentsForMarker(String[] arguments) { + StringBuffer args = new StringBuffer(10); + + args.append(arguments.length); + args.append(':'); + + for (int j = 0; j < arguments.length; j++) { + if (j != 0) + args.append(ARGUMENTS_DELIMITER); + + if (arguments[j].length() == 0) { + args.append(EMPTY_ARGUMENT); + } else { + args.append(arguments[j]); + } + } + + return args.toString(); + } + + /** + * Separate all the arguments of a String made by + * getProblemArgumentsForMarker + */ + public static String[] getProblemArgumentsFromMarker(String argumentsString) { + if (argumentsString == null) + return null; + int index = argumentsString.indexOf(':'); + if (index == -1) + return null; + + int length = argumentsString.length(); + int numberOfArg; + try { + numberOfArg = Integer.parseInt(argumentsString.substring(0, index)); + } catch (NumberFormatException e) { + return null; + } + argumentsString = argumentsString.substring(index + 1, length); + + String[] args = new String[length]; + int count = 0; + + StringTokenizer tokenizer = new StringTokenizer(argumentsString, + ARGUMENTS_DELIMITER); + while (tokenizer.hasMoreTokens()) { + String argument = tokenizer.nextToken(); + if (argument.equals(EMPTY_ARGUMENT)) + argument = ""; //$NON-NLS-1$ + args[count++] = argument; + } + + if (count != numberOfArg) + return null; + + System.arraycopy(args, 0, args = new String[count], 0, count); + return args; + } + + /** + * Returns the given file's contents as a byte array. + */ + public static byte[] getResourceContentsAsByteArray(IFile file) + throws JavaModelException { + InputStream stream = null; + try { + stream = new BufferedInputStream(file.getContents(true)); + } catch (CoreException e) { + throw new JavaModelException(e); + } + try { + return net.sourceforge.phpdt.internal.compiler.util.Util + .getInputStreamAsByteArray(stream, -1); + } catch (IOException e) { + throw new JavaModelException(e, + IJavaModelStatusConstants.IO_EXCEPTION); + } finally { + try { + stream.close(); + } catch (IOException e) { + // ignore + } + } + } + + /** + * Returns the given file's contents as a character array. + */ + public static char[] getResourceContentsAsCharArray(IFile file) + throws JavaModelException { + // Get encoding from file + String encoding = null; + try { + encoding = file.getCharset(); + } catch (CoreException ce) { + // do not use any encoding + } + return getResourceContentsAsCharArray(file, encoding); + } + + public static char[] getResourceContentsAsCharArray(IFile file, + String encoding) throws JavaModelException { + // Get resource contents + InputStream stream = null; + try { + stream = new BufferedInputStream(file.getContents(true)); + } catch (CoreException e) { + throw new JavaModelException(e, + IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); + } + try { + return net.sourceforge.phpdt.internal.compiler.util.Util + .getInputStreamAsCharArray(stream, -1, encoding); + } catch (IOException e) { + throw new JavaModelException(e, + IJavaModelStatusConstants.IO_EXCEPTION); + } finally { + try { + stream.close(); + } catch (IOException e) { + // ignore + } + } + } + + /** + * Returns a trimmed version the simples names returned by Signature. + */ + public static String[] getTrimmedSimpleNames(String name) { + String[] result = Signature.getSimpleNames(name); + if (result == null) + return null; + for (int i = 0, length = result.length; i < length; i++) { + result[i] = result[i].trim(); + } + return result; + } + + /* + * Returns the index of the most specific argument paths which is strictly + * enclosing the path to check + */ + public static int indexOfEnclosingPath(IPath checkedPath, IPath[] paths, + int pathCount) { + + int bestMatch = -1, bestLength = -1; + for (int i = 0; i < pathCount; i++) { + if (paths[i].equals(checkedPath)) + continue; + if (paths[i].isPrefixOf(checkedPath)) { + int currentLength = paths[i].segmentCount(); + if (currentLength > bestLength) { + bestLength = currentLength; + bestMatch = i; + } + } + } + return bestMatch; + } + + /* + * Returns the index of the first argument paths which is equal to the path + * to check + */ + public static int indexOfMatchingPath(IPath checkedPath, IPath[] paths, + int pathCount) { + + for (int i = 0; i < pathCount; i++) { + if (paths[i].equals(checkedPath)) + return i; + } + return -1; + } + + /* + * Returns the index of the first argument paths which is strictly nested + * inside the path to check + */ + public static int indexOfNestedPath(IPath checkedPath, IPath[] paths, + int pathCount) { + + for (int i = 0; i < pathCount; i++) { + if (checkedPath.equals(paths[i])) + continue; + if (checkedPath.isPrefixOf(paths[i])) + return i; + } + return -1; + } + + /* + * Returns whether the given java element is exluded from its root's + * classpath. It doesn't check whether the root itself is on the classpath + * or not + */ + public static final boolean isExcluded(IJavaElement element) { + int elementType = element.getElementType(); + PackageFragmentRoot root = null; + IResource resource = null; + switch (elementType) { + case IJavaElement.JAVA_MODEL: + case IJavaElement.JAVA_PROJECT: + case IJavaElement.PACKAGE_FRAGMENT_ROOT: + return false; + + // case IJavaElement.PACKAGE_FRAGMENT: + // PackageFragmentRoot root = + // (PackageFragmentRoot)element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); + // IResource resource = element.getResource(); + // return resource != null && isExcluded(resource, + // root.fullInclusionPatternChars(), + // root.fullExclusionPatternChars()); + + case IJavaElement.COMPILATION_UNIT: + root = (PackageFragmentRoot) element + .getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); + resource = element.getResource(); + // if (resource != null && isExcluded(resource, + // root.fullInclusionPatternChars(), + // root.fullExclusionPatternChars())) + // return true; + return isExcluded(element.getParent()); + + default: + IJavaElement cu = element + .getAncestor(IJavaElement.COMPILATION_UNIT); + return cu != null && isExcluded(cu); + } + } + + /* + * Returns whether the given resource path matches one of the + * inclusion/exclusion patterns. NOTE: should not be asked directly using + * pkg root pathes + * + * @see IClasspathEntry#getInclusionPatterns + * @see IClasspathEntry#getExclusionPatterns + */ + public final static boolean isExcluded(IPath resourcePath, + char[][] inclusionPatterns, char[][] exclusionPatterns, + boolean isFolderPath) { + if (inclusionPatterns == null && exclusionPatterns == null) + return false; + char[] path = resourcePath.toString().toCharArray(); + + inclusionCheck: if (inclusionPatterns != null) { + for (int i = 0, length = inclusionPatterns.length; i < length; i++) { + char[] pattern = inclusionPatterns[i]; + char[] folderPattern = pattern; + if (isFolderPath) { + int lastSlash = CharOperation.lastIndexOf('/', pattern); + if (lastSlash != -1 && lastSlash != pattern.length - 1) { // trailing + // slash + // -> + // adds + // '**' + // for + // free + // (see + // http://ant.apache.org/manual/dirtasks.html) + int star = CharOperation.indexOf('*', pattern, + lastSlash); + if ((star == -1 || star >= pattern.length - 1 || pattern[star + 1] != '*')) { + folderPattern = CharOperation.subarray(pattern, 0, + lastSlash); + } + } + } + if (CharOperation.pathMatch(folderPattern, path, true, '/')) { + break inclusionCheck; + } + } + return true; // never included + } + if (isFolderPath) { + path = CharOperation.concat(path, new char[] { '*' }, '/'); + } + exclusionCheck: if (exclusionPatterns != null) { + for (int i = 0, length = exclusionPatterns.length; i < length; i++) { + if (CharOperation.pathMatch(exclusionPatterns[i], path, true, + '/')) { + return true; + } + } + } + return false; + } + + public final static boolean isExcluded(IResource resource, + char[][] exclusionPatterns) { + IPath path = resource.getFullPath(); + // ensure that folders are only excluded if all of their children are + // excluded + return isExcluded(path, null, exclusionPatterns, + resource.getType() == IResource.FOLDER); + } + + /* + * Returns whether the given resource matches one of the exclusion patterns. + * NOTE: should not be asked directly using pkg root pathes + * + * @see IClasspathEntry#getExclusionPatterns + */ + public final static boolean isExcluded(IResource resource, + char[][] inclusionPatterns, char[][] exclusionPatterns) { + IPath path = resource.getFullPath(); + // ensure that folders are only excluded if all of their children are + // excluded + return isExcluded(path, inclusionPatterns, exclusionPatterns, resource + .getType() == IResource.FOLDER); + } + + /** + * Validate the given .class file name. A .class file name must obey the + * following rules: + *
                                                        + *
                                                      • it must not be null + *
                                                      • it must include the ".class" suffix + *
                                                      • its prefix must be a valid identifier + *
                                                      + *

                                                      + * + * @param name + * the name of a .class file + * @return a status object with code IStatus.OK if the given + * name is valid as a .class file name, otherwise a status object + * indicating what is wrong with the name + */ + // public static boolean isValidClassFileName(String name) { + // return JavaConventions.validateClassFileName(name).getSeverity() != + // IStatus.ERROR; + // } + /** + * Validate the given compilation unit name. A compilation unit name must + * obey the following rules: + *
                                                        + *
                                                      • it must not be null + *
                                                      • it must include the ".java" suffix + *
                                                      • its prefix must be a valid identifier + *
                                                      + *

                                                      + * + * @param name + * the name of a compilation unit + * @return a status object with code IStatus.OK if the given + * name is valid as a compilation unit name, otherwise a status + * object indicating what is wrong with the name + */ + public static boolean isValidCompilationUnitName(String name) { + return PHPFileUtil.isPHPFileName(name); + // return + // JavaConventions.validateCompilationUnitName(name).getSeverity() != + // IStatus.ERROR; + } + + /** + * Returns true if the given folder name is valid for a package, false if it + * is not. + */ + public static boolean isValidFolderNameForPackage(String folderName) { + // return JavaConventions.validateIdentifier(folderName).getSeverity() + // != IStatus.ERROR; + return true; + } + + /** + * Returns true if the given method signature is valid, false if it is not. + */ + public static boolean isValidMethodSignature(String sig) { + int len = sig.length(); + if (len == 0) + return false; + int i = 0; + char c = sig.charAt(i++); + if (c != '(') + return false; + if (i >= len) + return false; + while (sig.charAt(i) != ')') { + // Void is not allowed as a parameter type. + i = checkTypeSignature(sig, i, len, false); + if (i == -1) + return false; + if (i >= len) + return false; + } + ++i; + i = checkTypeSignature(sig, i, len, true); + return i == len; + } + + /** + * Returns true if the given type signature is valid, false if it is not. + */ + public static boolean isValidTypeSignature(String sig, boolean allowVoid) { + int len = sig.length(); + return checkTypeSignature(sig, 0, len, allowVoid) == len; + } + + /* + * Add a log entry + */ + public static void log(Throwable e, String message) { + Throwable nestedException; + if (e instanceof JavaModelException + && (nestedException = ((JavaModelException) e).getException()) != null) { + e = nestedException; + } + IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, + IStatus.ERROR, message, e); + JavaCore.getPlugin().getLog().log(status); + } + + /** + * Normalizes the cariage returns in the given text. They are all changed to + * use the given buffer's line separator. + */ + public static char[] normalizeCRs(char[] text, char[] buffer) { + CharArrayBuffer result = new CharArrayBuffer(); + int lineStart = 0; + int length = text.length; + if (length == 0) + return text; + String lineSeparator = getLineSeparator(text, buffer); + char nextChar = text[0]; + for (int i = 0; i < length; i++) { + char currentChar = nextChar; + nextChar = i < length - 1 ? text[i + 1] : ' '; + switch (currentChar) { + case '\n': + int lineLength = i - lineStart; + char[] line = new char[lineLength]; + System.arraycopy(text, lineStart, line, 0, lineLength); + result.append(line); + result.append(lineSeparator); + lineStart = i + 1; + break; + case '\r': + lineLength = i - lineStart; + if (lineLength >= 0) { + line = new char[lineLength]; + System.arraycopy(text, lineStart, line, 0, lineLength); + result.append(line); + result.append(lineSeparator); + if (nextChar == '\n') { + nextChar = ' '; + lineStart = i + 2; + } else { + // when line separator are mixed in the same file + // \r might not be followed by a \n. If not, we should + // increment + // lineStart by one and not by two. + lineStart = i + 1; + } + } else { + // when line separator are mixed in the same file + // we need to prevent NegativeArraySizeException + lineStart = i + 1; + } + break; + } + } + char[] lastLine; + if (lineStart > 0) { + int lastLineLength = length - lineStart; + if (lastLineLength > 0) { + lastLine = new char[lastLineLength]; + System.arraycopy(text, lineStart, lastLine, 0, lastLineLength); + result.append(lastLine); + } + return result.getContents(); + } + return text; + } + + /** + * Normalizes the cariage returns in the given text. They are all changed to + * use given buffer's line sepatator. + */ + public static String normalizeCRs(String text, String buffer) { + return new String( + normalizeCRs(text.toCharArray(), buffer.toCharArray())); + } + + /** + * Converts the given relative path into a package name. Returns null if the + * path is not a valid package name. + */ + public static String packageName(IPath pkgPath) { + StringBuffer pkgName = new StringBuffer( + IPackageFragment.DEFAULT_PACKAGE_NAME); + for (int j = 0, max = pkgPath.segmentCount(); j < max; j++) { + String segment = pkgPath.segment(j); + // if (!isValidFolderNameForPackage(segment)) { + // return null; + // } + pkgName.append(segment); + if (j < pkgPath.segmentCount() - 1) { + pkgName.append("."); //$NON-NLS-1$ + } + } + return pkgName.toString(); + } + + /** + * Returns the length of the common prefix between s1 and s2. + */ + public static int prefixLength(char[] s1, char[] s2) { + int len = 0; + int max = Math.min(s1.length, s2.length); + for (int i = 0; i < max && s1[i] == s2[i]; ++i) + ++len; + return len; + } + + /** + * Returns the length of the common prefix between s1 and s2. + */ + public static int prefixLength(String s1, String s2) { + int len = 0; + int max = Math.min(s1.length(), s2.length()); + for (int i = 0; i < max && s1.charAt(i) == s2.charAt(i); ++i) + ++len; + return len; + } + + private static void quickSort(char[][] list, int left, int right) { + int original_left = left; + int original_right = right; + char[] mid = list[(left + right) / 2]; + do { + while (compare(list[left], mid) < 0) { + left++; + } + while (compare(mid, list[right]) < 0) { + right--; + } + if (left <= right) { + char[] tmp = list[left]; + list[left] = list[right]; + list[right] = tmp; + left++; + right--; + } + } while (left <= right); + if (original_left < right) { + quickSort(list, original_left, right); + } + if (left < original_right) { + quickSort(list, left, original_right); + } + } + + /** + * Sort the comparable objects in the given collection. + */ + private static void quickSort(Comparable[] sortedCollection, int left, + int right) { + int original_left = left; + int original_right = right; + Comparable mid = sortedCollection[(left + right) / 2]; + do { + while (sortedCollection[left].compareTo(mid) < 0) { + left++; + } + while (mid.compareTo(sortedCollection[right]) < 0) { + right--; + } + if (left <= right) { + Comparable tmp = sortedCollection[left]; + sortedCollection[left] = sortedCollection[right]; + sortedCollection[right] = tmp; + left++; + right--; + } + } while (left <= right); + if (original_left < right) { + quickSort(sortedCollection, original_left, right); + } + if (left < original_right) { + quickSort(sortedCollection, left, original_right); + } + } + + private static void quickSort(int[] list, int left, int right) { + int original_left = left; + int original_right = right; + int mid = list[(left + right) / 2]; + do { + while (list[left] < mid) { + left++; + } + while (mid < list[right]) { + right--; + } + if (left <= right) { + int tmp = list[left]; + list[left] = list[right]; + list[right] = tmp; + left++; + right--; + } + } while (left <= right); + if (original_left < right) { + quickSort(list, original_left, right); + } + if (left < original_right) { + quickSort(list, left, original_right); + } + } + + /** + * Sort the objects in the given collection using the given comparer. + */ + private static void quickSort(Object[] sortedCollection, int left, + int right, Comparer comparer) { + int original_left = left; + int original_right = right; + Object mid = sortedCollection[(left + right) / 2]; + do { + while (comparer.compare(sortedCollection[left], mid) < 0) { + left++; + } + while (comparer.compare(mid, sortedCollection[right]) < 0) { + right--; + } + if (left <= right) { + Object tmp = sortedCollection[left]; + sortedCollection[left] = sortedCollection[right]; + sortedCollection[right] = tmp; + left++; + right--; + } + } while (left <= right); + if (original_left < right) { + quickSort(sortedCollection, original_left, right, comparer); + } + if (left < original_right) { + quickSort(sortedCollection, left, original_right, comparer); + } + } + + /** + * Sort the objects in the given collection using the given sort order. + */ + private static void quickSort(Object[] sortedCollection, int left, + int right, int[] sortOrder) { + int original_left = left; + int original_right = right; + int mid = sortOrder[(left + right) / 2]; + do { + while (sortOrder[left] < mid) { + left++; + } + while (mid < sortOrder[right]) { + right--; + } + if (left <= right) { + Object tmp = sortedCollection[left]; + sortedCollection[left] = sortedCollection[right]; + sortedCollection[right] = tmp; + int tmp2 = sortOrder[left]; + sortOrder[left] = sortOrder[right]; + sortOrder[right] = tmp2; + left++; + right--; + } + } while (left <= right); + if (original_left < right) { + quickSort(sortedCollection, original_left, right, sortOrder); + } + if (left < original_right) { + quickSort(sortedCollection, left, original_right, sortOrder); + } + } + + /** + * Sort the strings in the given collection. + */ + private static void quickSort(String[] sortedCollection, int left, int right) { + int original_left = left; + int original_right = right; + String mid = sortedCollection[(left + right) / 2]; + do { + while (sortedCollection[left].compareTo(mid) < 0) { + left++; + } + while (mid.compareTo(sortedCollection[right]) < 0) { + right--; + } + if (left <= right) { + String tmp = sortedCollection[left]; + sortedCollection[left] = sortedCollection[right]; + sortedCollection[right] = tmp; + left++; + right--; + } + } while (left <= right); + if (original_left < right) { + quickSort(sortedCollection, original_left, right); + } + if (left < original_right) { + quickSort(sortedCollection, left, original_right); + } + } + + /** + * Sort the strings in the given collection in reverse alphabetical order. + */ + private static void quickSortReverse(String[] sortedCollection, int left, + int right) { + int original_left = left; + int original_right = right; + String mid = sortedCollection[(left + right) / 2]; + do { + while (sortedCollection[left].compareTo(mid) > 0) { + left++; + } + while (mid.compareTo(sortedCollection[right]) > 0) { + right--; + } + if (left <= right) { + String tmp = sortedCollection[left]; + sortedCollection[left] = sortedCollection[right]; + sortedCollection[right] = tmp; + left++; + right--; + } + } while (left <= right); + if (original_left < right) { + quickSortReverse(sortedCollection, original_left, right); + } + if (left < original_right) { + quickSortReverse(sortedCollection, left, original_right); + } + } + + /** + * Reads in a string from the specified data input stream. The string has + * been encoded using a modified UTF-8 format. + *

                                                      + * The first two bytes are read as if by readUnsignedShort. + * This value gives the number of following bytes that are in the encoded + * string, not the length of the resulting string. The following bytes are + * then interpreted as bytes encoding characters in the UTF-8 format and are + * converted into characters. + *

                                                      + * This method blocks until all the bytes are read, the end of the stream is + * detected, or an exception is thrown. + * + * @param in + * a data input stream. + * @return a Unicode string. + * @exception EOFException + * if the input stream reaches the end before all the bytes. + * @exception IOException + * if an I/O error occurs. + * @exception UTFDataFormatException + * if the bytes do not represent a valid UTF-8 encoding of a + * Unicode string. + * @see java.io.DataInputStream#readUnsignedShort() + */ + public final static char[] readUTF(DataInput in) throws IOException { + int utflen = in.readUnsignedShort(); + char str[] = new char[utflen]; + int count = 0; + int strlen = 0; + while (count < utflen) { + int c = in.readUnsignedByte(); + int char2, char3; + switch (c >> 4) { + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + // 0xxxxxxx + count++; + str[strlen++] = (char) c; + break; + case 12: + case 13: + // 110x xxxx 10xx xxxx + count += 2; + if (count > utflen) + throw new UTFDataFormatException(); + char2 = in.readUnsignedByte(); + if ((char2 & 0xC0) != 0x80) + throw new UTFDataFormatException(); + str[strlen++] = (char) (((c & 0x1F) << 6) | (char2 & 0x3F)); + break; + case 14: + // 1110 xxxx 10xx xxxx 10xx xxxx + count += 3; + if (count > utflen) + throw new UTFDataFormatException(); + char2 = in.readUnsignedByte(); + char3 = in.readUnsignedByte(); + if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) + throw new UTFDataFormatException(); + str[strlen++] = (char) (((c & 0x0F) << 12) + | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)); + break; + default: + // 10xx xxxx, 1111 xxxx + throw new UTFDataFormatException(); + } + } + if (strlen < utflen) { + System.arraycopy(str, 0, str = new char[strlen], 0, strlen); + } + return str; + } + + /** + * Creates a NLS catalog for the given locale. + */ + public static void relocalize() { + try { + bundle = ResourceBundle.getBundle(bundleName, Locale.getDefault()); + } catch (MissingResourceException e) { + System.out + .println("Missing resource : " + bundleName.replace('.', '/') + ".properties for locale " + Locale.getDefault()); //$NON-NLS-1$//$NON-NLS-2$ + throw e; + } + } + + public static void sort(char[][] list) { + if (list.length > 1) + quickSort(list, 0, list.length - 1); + } + + /** + * Sorts an array of Comparable objects in place. + */ + public static void sort(Comparable[] objects) { + if (objects.length > 1) + quickSort(objects, 0, objects.length - 1); + } + + public static void sort(int[] list) { + if (list.length > 1) + quickSort(list, 0, list.length - 1); + } + + /** + * Sorts an array of objects in place. The given comparer compares pairs of + * items. + */ + public static void sort(Object[] objects, Comparer comparer) { + if (objects.length > 1) + quickSort(objects, 0, objects.length - 1, comparer); + } + + /** + * Sorts an array of objects in place, using the sort order given for each + * item. + */ + public static void sort(Object[] objects, int[] sortOrder) { + if (objects.length > 1) + quickSort(objects, 0, objects.length - 1, sortOrder); + } + + /** + * Sorts an array of strings in place using quicksort. + */ + public static void sort(String[] strings) { + if (strings.length > 1) + quickSort(strings, 0, strings.length - 1); + } + + /** + * Sorts an array of Comparable objects, returning a new array with the + * sorted items. The original array is left untouched. + */ + public static Comparable[] sortCopy(Comparable[] objects) { + int len = objects.length; + Comparable[] copy = new Comparable[len]; + System.arraycopy(objects, 0, copy, 0, len); + sort(copy); + return copy; + } + + /** + * Sorts an array of Strings, returning a new array with the sorted items. + * The original array is left untouched. + */ + public static Object[] sortCopy(Object[] objects, Comparer comparer) { + int len = objects.length; + Object[] copy = new Object[len]; + System.arraycopy(objects, 0, copy, 0, len); + sort(copy, comparer); + return copy; + } + + /** + * Sorts an array of Strings, returning a new array with the sorted items. + * The original array is left untouched. + */ + public static String[] sortCopy(String[] objects) { + int len = objects.length; + String[] copy = new String[len]; + System.arraycopy(objects, 0, copy, 0, len); + sort(copy); + return copy; + } + + /** + * Sorts an array of strings in place using quicksort in reverse + * alphabetical order. + */ + public static void sortReverseOrder(String[] strings) { + if (strings.length > 1) + quickSortReverse(strings, 0, strings.length - 1); + } + + /** + * Converts a String[] to char[][]. + */ + public static char[][] toCharArrays(String[] a) { + int len = a.length; + char[][] result = new char[len][]; + for (int i = 0; i < len; ++i) { + result[i] = toChars(a[i]); + } + return result; + } + + /** + * Converts a String to char[]. + */ + public static char[] toChars(String s) { + int len = s.length(); + char[] chars = new char[len]; + s.getChars(0, len, chars, 0); + return chars; + } + + /** + * Converts a String to char[][], where segments are separate by '.'. + */ + public static char[][] toCompoundChars(String s) { + int len = s.length(); + if (len == 0) { + return CharOperation.NO_CHAR_CHAR; + } + int segCount = 1; + for (int off = s.indexOf('.'); off != -1; off = s.indexOf('.', off + 1)) { + ++segCount; + } + char[][] segs = new char[segCount][]; + int start = 0; + for (int i = 0; i < segCount; ++i) { + int dot = s.indexOf('.', start); + int end = (dot == -1 ? s.length() : dot); + segs[i] = new char[end - start]; + s.getChars(start, end, segs[i], 0); + start = end + 1; + } + return segs; + } + + /** + * Converts a char[] to String. + */ + public static String toString(char[] c) { + return new String(c); + } + + /** + * Converts a char[][] to String, where segments are separated by '.'. + */ + public static String toString(char[][] c) { + StringBuffer sb = new StringBuffer(); + for (int i = 0, max = c.length; i < max; ++i) { + if (i != 0) + sb.append('.'); + sb.append(c[i]); + } + return sb.toString(); + } + + /** + * Converts a char[][] and a char[] to String, where segments are separated + * by '.'. + */ + public static String toString(char[][] c, char[] d) { + if (c == null) + return new String(d); + StringBuffer sb = new StringBuffer(); + for (int i = 0, max = c.length; i < max; ++i) { + sb.append(c[i]); + sb.append('.'); + } + sb.append(d); + return sb.toString(); + } + + /* + * Returns the unresolved type parameter signatures of the given method e.g. + * {"QString;", "[int", "[[Qjava.util.Vector;"} + */ + // public static String[] typeParameterSignatures(AbstractMethodDeclaration + // method) { + // Argument[] args = method.arguments; + // if (args != null) { + // int length = args.length; + // String[] signatures = new String[length]; + // for (int i = 0; i < args.length; i++) { + // Argument arg = args[i]; + // signatures[i] = typeSignature(arg.type); + // } + // return signatures; + // } + // return new String[0]; + // } + /* + * Returns the unresolved type signature of the given type reference, e.g. + * "QString;", "[int", "[[Qjava.util.Vector;" + */ + // public static String typeSignature(TypeReference type) { + // char[][] compoundName = type.getTypeName(); + // char[] typeName =CharOperation.concatWith(compoundName, '.'); + // String signature = Signature.createTypeSignature(typeName, false/*don't + // resolve*/); + // int dimensions = type.dimensions(); + // if (dimensions > 0) { + // signature = Signature.createArraySignature(signature, dimensions); + // } + // return signature; + // } + /* + * Returns the unresolved type signature of the given type reference, e.g. + * "QString;", "[int", "[[Qjava.util.Vector;" */ public static String typeSignature(TypeReference type) { char[][] compoundName = type.getTypeName(); - char[] typeName =CharOperation.concatWith(compoundName, '.'); - String signature = Signature.createTypeSignature(typeName, false/*don't resolve*/); + char[] typeName = CharOperation.concatWith(compoundName, '.'); + String signature = Signature + .createTypeSignature(typeName, false/* don't resolve */); int dimensions = type.dimensions(); if (dimensions > 0) { - signature = Signature.createArraySignature(signature, dimensions); + signature = Signature.createArraySignature(signature, dimensions); } return signature; } - /** - * Asserts that the given method signature is valid. - */ - public static void validateMethodSignature(String sig) { - Assert.isTrue(isValidMethodSignature(sig)); - } - - /** - * Asserts that the given type signature is valid. - */ - public static void validateTypeSignature(String sig, boolean allowVoid) { - Assert.isTrue(isValidTypeSignature(sig, allowVoid)); - } - - public static void verbose(String log) { - verbose(log, System.out); - } - - public static synchronized void verbose(String log, PrintStream printStream) { - int start = 0; - do { - int end = log.indexOf('\n', start); - printStream.print(Thread.currentThread()); - printStream.print(" "); //$NON-NLS-1$ - printStream.print(log.substring(start, end == -1 ? log.length() : end + 1)); - start = end + 1; - } while (start != 0); - printStream.println(); - } - - /** - * Writes a string to the given output stream using UTF-8 encoding in a machine-independent manner. - *

                                                      - * First, two bytes are written to the output stream as if by the writeShort method giving the number of bytes to - * follow. This value is the number of bytes actually written out, not the length of the string. Following the length, each - * character of the string is output, in sequence, using the UTF-8 encoding for the character. - * - * @param str - * a string to be written. - * @return the number of bytes written to the stream. - * @exception IOException - * if an I/O error occurs. - * @since JDK1.0 - */ - public static int writeUTF(OutputStream out, char[] str) throws IOException { - int strlen = str.length; - int utflen = 0; - for (int i = 0; i < strlen; i++) { - int c = str[i]; - if ((c >= 0x0001) && (c <= 0x007F)) { - utflen++; - } else if (c > 0x07FF) { - utflen += 3; - } else { - utflen += 2; - } - } - if (utflen > 65535) - throw new UTFDataFormatException(); - out.write((utflen >>> 8) & 0xFF); - out.write((utflen >>> 0) & 0xFF); - if (strlen == utflen) { - for (int i = 0; i < strlen; i++) - out.write(str[i]); - } else { - for (int i = 0; i < strlen; i++) { - int c = str[i]; - if ((c >= 0x0001) && (c <= 0x007F)) { - out.write(c); - } else if (c > 0x07FF) { - out.write(0xE0 | ((c >> 12) & 0x0F)); - out.write(0x80 | ((c >> 6) & 0x3F)); - out.write(0x80 | ((c >> 0) & 0x3F)); - } else { - out.write(0xC0 | ((c >> 6) & 0x1F)); - out.write(0x80 | ((c >> 0) & 0x3F)); - } - } - } - return utflen + 2; // the number of bytes written to the stream - } + + /** + * Asserts that the given method signature is valid. + */ + public static void validateMethodSignature(String sig) { + Assert.isTrue(isValidMethodSignature(sig)); + } + + /** + * Asserts that the given type signature is valid. + */ + public static void validateTypeSignature(String sig, boolean allowVoid) { + Assert.isTrue(isValidTypeSignature(sig, allowVoid)); + } + + public static void verbose(String log) { + verbose(log, System.out); + } + + public static synchronized void verbose(String log, PrintStream printStream) { + int start = 0; + do { + int end = log.indexOf('\n', start); + printStream.print(Thread.currentThread()); + printStream.print(" "); //$NON-NLS-1$ + printStream.print(log.substring(start, end == -1 ? log.length() + : end + 1)); + start = end + 1; + } while (start != 0); + printStream.println(); + } + + /** + * Writes a string to the given output stream using UTF-8 encoding in a + * machine-independent manner. + *

                                                      + * First, two bytes are written to the output stream as if by the + * writeShort method giving the number of bytes to follow. + * This value is the number of bytes actually written out, not the length of + * the string. Following the length, each character of the string is output, + * in sequence, using the UTF-8 encoding for the character. + * + * @param str + * a string to be written. + * @return the number of bytes written to the stream. + * @exception IOException + * if an I/O error occurs. + * @since JDK1.0 + */ + public static int writeUTF(OutputStream out, char[] str) throws IOException { + int strlen = str.length; + int utflen = 0; + for (int i = 0; i < strlen; i++) { + int c = str[i]; + if ((c >= 0x0001) && (c <= 0x007F)) { + utflen++; + } else if (c > 0x07FF) { + utflen += 3; + } else { + utflen += 2; + } + } + if (utflen > 65535) + throw new UTFDataFormatException(); + out.write((utflen >>> 8) & 0xFF); + out.write((utflen >>> 0) & 0xFF); + if (strlen == utflen) { + for (int i = 0; i < strlen; i++) + out.write(str[i]); + } else { + for (int i = 0; i < strlen; i++) { + int c = str[i]; + if ((c >= 0x0001) && (c <= 0x007F)) { + out.write(c); + } else if (c > 0x07FF) { + out.write(0xE0 | ((c >> 12) & 0x0F)); + out.write(0x80 | ((c >> 6) & 0x3F)); + out.write(0x80 | ((c >> 0) & 0x3F)); + } else { + out.write(0xC0 | ((c >> 6) & 0x1F)); + out.write(0x80 | ((c >> 0) & 0x3F)); + } + } + } + return utflen + 2; // the number of bytes written to the stream + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/Assert.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/Assert.java index 8b3356a..662ccdc 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/Assert.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/Assert.java @@ -4,19 +4,20 @@ */ package net.sourceforge.phpdt.internal.corext; -//import org.phpeclipse.phpdt.internal.corext.refactoring.RefactoringCoreMessages; +// import +// org.phpeclipse.phpdt.internal.corext.refactoring.RefactoringCoreMessages; /** - * Assert is useful for for embedding runtime sanity checks - * in code. The static predicate methods all test a condition and throw some - * type of unchecked exception if the condition does not hold. + * Assert is useful for for embedding runtime sanity checks in + * code. The static predicate methods all test a condition and throw some type + * of unchecked exception if the condition does not hold. *

                                                      - * Assertion failure exceptions, like most runtime exceptions, are - * thrown when something is misbehaving. Assertion failures are invariably - * unspecified behavior; consequently, clients should never rely on - * these being thrown (or not thrown). If you find yourself in the - * position where you need to catch an assertion failure, you have most - * certainly written your program incorrectly. + * Assertion failure exceptions, like most runtime exceptions, are thrown when + * something is misbehaving. Assertion failures are invariably unspecified + * behavior; consequently, clients should never rely on these being thrown (or + * not thrown). If you find yourself in the position where you need to catch + * an assertion failure, you have most certainly written your program + * incorrectly. *

                                                      *

                                                      * Note that an assert statement is slated to be added to the @@ -26,12 +27,12 @@ package net.sourceforge.phpdt.internal.corext; public final class Assert { /** - * AssertionFailedException is a runtime exception thrown - * by some of the methods in Assert. + * AssertionFailedException is a runtime exception thrown by + * some of the methods in Assert. *

                                                      - * This class is not declared public to prevent some misuses; programs that catch - * or otherwise depend on assertion failures are susceptible to unexpected - * breakage when assertions in the code are added or removed. + * This class is not declared public to prevent some misuses; programs that + * catch or otherwise depend on assertion failures are susceptible to + * unexpected breakage when assertions in the code are added or removed. *

                                                      */ public static class AssertionFailedException extends RuntimeException { @@ -55,19 +56,20 @@ public final class Assert { } /** - * Asserts that the given object is not null. If this - * is not the case, some kind of unchecked exception is thrown. + * Asserts that the given object is not null. If this is not + * the case, some kind of unchecked exception is thrown. *

                                                      * As a general rule, parameters passed to API methods must not be * null unless explicitly allowed in the method's * specification. Similarly, results returned from API methods are never * null unless explicitly allowed in the method's - * specification. Implementations are encouraged to make regular use of - * Assert.isNotNull to ensure that null + * specification. Implementations are encouraged to make regular use of + * Assert.isNotNull to ensure that null * parameters are detected as early as possible. *

                                                      * - * @param object the value to test + * @param object + * the value to test */ public static void isNotNull(Object object) { // succeed as quickly as possible @@ -78,34 +80,37 @@ public final class Assert { } /** - * Asserts that the given object is not null. If this - * is not the case, some kind of unchecked exception is thrown. - * The given message is included in that exception, to aid debugging. + * Asserts that the given object is not null. If this is not + * the case, some kind of unchecked exception is thrown. The given message + * is included in that exception, to aid debugging. *

                                                      * As a general rule, parameters passed to API methods must not be * null unless explicitly allowed in the method's * specification. Similarly, results returned from API methods are never * null unless explicitly allowed in the method's - * specification. Implementations are encouraged to make regular use of - * Assert.isNotNull to ensure that null + * specification. Implementations are encouraged to make regular use of + * Assert.isNotNull to ensure that null * parameters are detected as early as possible. *

                                                      * - * @param object the value to test - * @param message the message to include in the exception + * @param object + * the value to test + * @param message + * the message to include in the exception */ - public static void isNotNull(Object object, String message) { + public static void isNotNull(Object object, String message) { if (object == null) throw new AssertionFailedException("nullargument" + message); //$NON-NLS-1$ } /** - * Asserts that the given boolean is true. If this - * is not the case, some kind of unchecked exception is thrown. - * - * @param expression the outcome of the check - * @return true if the check passes (does not return - * if the check fails) + * Asserts that the given boolean is true. If this is not + * the case, some kind of unchecked exception is thrown. + * + * @param expression + * the outcome of the check + * @return true if the check passes (does not return if the + * check fails) */ public static boolean isTrue(boolean expression) { // succeed as quickly as possible @@ -116,14 +121,16 @@ public final class Assert { } /** - * Asserts that the given boolean is true. If this - * is not the case, some kind of unchecked exception is thrown. - * The given message is included in that exception, to aid debugging. - * - * @param expression the outcome of the check - * @param message the message to include in the exception - * @return true if the check passes (does not return - * if the check fails) + * Asserts that the given boolean is true. If this is not + * the case, some kind of unchecked exception is thrown. The given message + * is included in that exception, to aid debugging. + * + * @param expression + * the outcome of the check + * @param message + * the message to include in the exception + * @return true if the check passes (does not return if the + * check fails) */ public static boolean isTrue(boolean expression, String message) { if (!expression) diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/CorextMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/CorextMessages.java index 67c52f3..57d11f5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/CorextMessages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/CorextMessages.java @@ -16,10 +16,10 @@ import java.util.ResourceBundle; public class CorextMessages { - private static final String BUNDLE_NAME= CorextMessages.class.getName(); + private static final String BUNDLE_NAME = CorextMessages.class.getName(); - private static final ResourceBundle RESOURCE_BUNDLE = - ResourceBundle.getBundle(BUNDLE_NAME); + private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle + .getBundle(BUNDLE_NAME); private CorextMessages() { } @@ -31,12 +31,12 @@ public class CorextMessages { return '!' + key + '!'; } } - + public static String getFormattedString(String key, Object arg) { return getFormattedString(key, new Object[] { arg }); } - + public static String getFormattedString(String key, Object[] args) { - return MessageFormat.format(getString(key), args); - } + return MessageFormat.format(getString(key), args); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/CodeGenerationMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/CodeGenerationMessages.java index f1b2e7a..b308d22 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/CodeGenerationMessages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/CodeGenerationMessages.java @@ -16,8 +16,11 @@ import java.util.ResourceBundle; public class CodeGenerationMessages { - private static final String RESOURCE_BUNDLE= CodeGenerationMessages.class.getName(); - private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); + private static final String RESOURCE_BUNDLE = CodeGenerationMessages.class + .getName(); + + private static ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); private CodeGenerationMessages() { } @@ -29,23 +32,22 @@ public class CodeGenerationMessages { return '!' + key + '!'; } } - + /** * Gets a string from the resource bundle and formats it with the argument * - * @param key the string used to get the bundle value, must not be null + * @param key + * the string used to get the bundle value, must not be null */ public static String getFormattedString(String key, Object arg) { return MessageFormat.format(getString(key), new Object[] { arg }); } - /** * Gets a string from the resource bundle and formats it with arguments - */ + */ public static String getFormattedString(String key, Object[] args) { return MessageFormat.format(getString(key), args); } - } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/CodeGenerationSettings.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/CodeGenerationSettings.java index 62883f6..8206056 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/CodeGenerationSettings.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/CodeGenerationSettings.java @@ -11,34 +11,32 @@ package net.sourceforge.phpdt.internal.corext.codemanipulation; public class CodeGenerationSettings { - + /** * @deprecated */ - public boolean createFileComments= true; + public boolean createFileComments = true; + + public boolean createComments = true; + + public boolean useKeywordThis = false; - public boolean createComments= true; - - public boolean useKeywordThis= false; - /** * @deprecated */ - public boolean createNonJavadocComments= true; - -// public String[] importOrder= new String[0]; - public int importThreshold= 99; - + public boolean createNonJavadocComments = true; + + // public String[] importOrder= new String[0]; + public int importThreshold = 99; + public int tabWidth; - + public void setSettings(CodeGenerationSettings settings) { - settings.createComments= createComments; - settings.useKeywordThis= useKeywordThis; -// settings.importOrder= importOrder; - settings.importThreshold= importThreshold; - settings.tabWidth= tabWidth; + settings.createComments = createComments; + settings.useKeywordThis = useKeywordThis; + // settings.importOrder= importOrder; + settings.importThreshold = importThreshold; + settings.tabWidth = tabWidth; } - } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/GetterSetterUtil.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/GetterSetterUtil.java index f2dc5db..2ac2194 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/GetterSetterUtil.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/GetterSetterUtil.java @@ -26,178 +26,228 @@ import net.sourceforge.phpdt.ui.PreferenceConstants; import org.eclipse.core.runtime.CoreException; public class GetterSetterUtil { - - private static final String[] EMPTY= new String[0]; - - //no instances - private GetterSetterUtil(){ + + private static final String[] EMPTY = new String[0]; + + // no instances + private GetterSetterUtil() { } - - public static String getGetterName(IField field, String[] excludedNames) throws JavaModelException { - boolean useIs= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEGEN_IS_FOR_GETTERS); + + public static String getGetterName(IField field, String[] excludedNames) + throws JavaModelException { + boolean useIs = PreferenceConstants.getPreferenceStore().getBoolean( + PreferenceConstants.CODEGEN_IS_FOR_GETTERS); return getGetterName(field, excludedNames, useIs); } - - private static String getGetterName(IField field, String[] excludedNames, boolean useIsForBoolGetters) throws JavaModelException { + + private static String getGetterName(IField field, String[] excludedNames, + boolean useIsForBoolGetters) throws JavaModelException { if (excludedNames == null) { - excludedNames= EMPTY; + excludedNames = EMPTY; } - return getGetterName(field.getJavaProject(), field.getElementName(), field.getFlags(), useIsForBoolGetters && JavaModelUtil.isBoolean(field), excludedNames); - } - - public static String getGetterName(IJavaProject project, String fieldName, int flags, boolean isBoolean, String[] excludedNames){ - return NamingConventions.suggestGetterName(project, fieldName, flags, isBoolean, excludedNames); + return getGetterName(field.getJavaProject(), field.getElementName(), + field.getFlags(), useIsForBoolGetters + && JavaModelUtil.isBoolean(field), excludedNames); } - public static String getSetterName(IJavaProject project, String fieldName, int flags, boolean isBoolean, String[] excludedNames){ - return NamingConventions.suggestSetterName(project, fieldName, flags, isBoolean, excludedNames); + public static String getGetterName(IJavaProject project, String fieldName, + int flags, boolean isBoolean, String[] excludedNames) { + return NamingConventions.suggestGetterName(project, fieldName, flags, + isBoolean, excludedNames); } - public static String getSetterName(IField field, String[] excludedNames) throws JavaModelException { + public static String getSetterName(IJavaProject project, String fieldName, + int flags, boolean isBoolean, String[] excludedNames) { + return NamingConventions.suggestSetterName(project, fieldName, flags, + isBoolean, excludedNames); + } + + public static String getSetterName(IField field, String[] excludedNames) + throws JavaModelException { if (excludedNames == null) { - excludedNames= EMPTY; - } - return NamingConventions.suggestSetterName(field.getJavaProject(), field.getElementName(), field.getFlags(), JavaModelUtil.isBoolean(field), excludedNames); - } - - public static IMethod getGetter(IField field) throws JavaModelException{ - IMethod primaryCandidate= JavaModelUtil.findMethod(getGetterName(field, EMPTY, true), new String[0], false, field.getDeclaringType()); - if (! JavaModelUtil.isBoolean(field) || (primaryCandidate != null && primaryCandidate.exists())) + excludedNames = EMPTY; + } + return NamingConventions.suggestSetterName(field.getJavaProject(), + field.getElementName(), field.getFlags(), JavaModelUtil + .isBoolean(field), excludedNames); + } + + public static IMethod getGetter(IField field) throws JavaModelException { + IMethod primaryCandidate = JavaModelUtil.findMethod(getGetterName( + field, EMPTY, true), new String[0], false, field + .getDeclaringType()); + if (!JavaModelUtil.isBoolean(field) + || (primaryCandidate != null && primaryCandidate.exists())) return primaryCandidate; - //bug 30906 describes why we need to look for other alternatives here - String secondCandidateName= getGetterName(field, EMPTY, false); - return JavaModelUtil.findMethod(secondCandidateName, new String[0], false, field.getDeclaringType()); + // bug 30906 describes why we need to look for other alternatives here + String secondCandidateName = getGetterName(field, EMPTY, false); + return JavaModelUtil.findMethod(secondCandidateName, new String[0], + false, field.getDeclaringType()); } - - public static IMethod getSetter(IField field) throws JavaModelException{ - String[] args= new String[] { field.getTypeSignature() }; - return JavaModelUtil.findMethod(getSetterName(field, EMPTY), args, false, field.getDeclaringType()); + + public static IMethod getSetter(IField field) throws JavaModelException { + String[] args = new String[] { field.getTypeSignature() }; + return JavaModelUtil.findMethod(getSetterName(field, EMPTY), args, + false, field.getDeclaringType()); } - + /** - * Create a stub for a getter of the given field using getter/setter templates. The resulting code - * has to be formatted and indented. - * @param field The field to create a getter for - * @param setterName The chosen name for the setter - * @param addComments If true, comments will be added. - * @param flags The flags signaling visibility, if static, synchronized or final + * Create a stub for a getter of the given field using getter/setter + * templates. The resulting code has to be formatted and indented. + * + * @param field + * The field to create a getter for + * @param setterName + * The chosen name for the setter + * @param addComments + * If true, comments will be added. + * @param flags + * The flags signaling visibility, if static, synchronized or + * final * @return Returns the generated stub. * @throws CoreException */ - public static String getSetterStub(IField field, String setterName, boolean addComments, int flags) throws CoreException { - - String fieldName= field.getElementName(); - IType parentType= field.getDeclaringType(); - - String returnSig= field.getTypeSignature(); - String typeName= Signature.toString(returnSig); - - IJavaProject project= field.getJavaProject(); - - String accessorName = NamingConventions.removePrefixAndSuffixForFieldName(project, fieldName, field.getFlags()); - String argname= StubUtility.suggestArgumentName(project, accessorName, EMPTY); - - boolean isStatic= Flags.isStatic(flags); -// boolean isSync= Flags.isSynchronized(flags); - boolean isFinal= Flags.isFinal(flags); - + public static String getSetterStub(IField field, String setterName, + boolean addComments, int flags) throws CoreException { + + String fieldName = field.getElementName(); + IType parentType = field.getDeclaringType(); + + String returnSig = field.getTypeSignature(); + String typeName = Signature.toString(returnSig); + + IJavaProject project = field.getJavaProject(); + + String accessorName = NamingConventions + .removePrefixAndSuffixForFieldName(project, fieldName, field + .getFlags()); + String argname = StubUtility.suggestArgumentName(project, accessorName, + EMPTY); + + boolean isStatic = Flags.isStatic(flags); + // boolean isSync= Flags.isSynchronized(flags); + boolean isFinal = Flags.isFinal(flags); + // create the setter stub - StringBuffer buf= new StringBuffer(); + StringBuffer buf = new StringBuffer(); if (addComments) { - String comment= CodeGeneration.getSetterComment(field.getCompilationUnit(), parentType.getTypeQualifiedName('.'), setterName, field.getElementName(), typeName, argname, accessorName, String.valueOf('\n')); + String comment = CodeGeneration.getSetterComment(field + .getCompilationUnit(), + parentType.getTypeQualifiedName('.'), setterName, field + .getElementName(), typeName, argname, accessorName, + String.valueOf('\n')); if (comment != null) { buf.append(comment); buf.append('\n'); } } buf.append(JdtFlags.getVisibilityString(flags)); - buf.append(' '); + buf.append(' '); if (isStatic) buf.append("static "); //$NON-NLS-1$ -// if (isSync) -// buf.append("synchronized "); //$NON-NLS-1$ + // if (isSync) + // buf.append("synchronized "); //$NON-NLS-1$ if (isFinal) buf.append("final "); //$NON-NLS-1$ - + buf.append("void "); //$NON-NLS-1$ buf.append(setterName); - buf.append('('); - buf.append(typeName); - buf.append(' '); - buf.append(argname); + buf.append('('); + buf.append(typeName); + buf.append(' '); + buf.append(argname); buf.append(") {\n"); //$NON-NLS-1$ - - boolean useThis= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEGEN_KEYWORD_THIS); + + boolean useThis = PreferenceConstants.getPreferenceStore().getBoolean( + PreferenceConstants.CODEGEN_KEYWORD_THIS); if (argname.equals(fieldName) || (useThis && !isStatic)) { if (isStatic) - fieldName= parentType.getElementName() + '.' + fieldName; + fieldName = parentType.getElementName() + '.' + fieldName; else - fieldName= "this." + fieldName; //$NON-NLS-1$ + fieldName = "this." + fieldName; //$NON-NLS-1$ } - String body= CodeGeneration.getSetterMethodBodyContent(field.getCompilationUnit(), parentType.getTypeQualifiedName('.'), setterName, fieldName, argname, String.valueOf('\n')); + String body = CodeGeneration.getSetterMethodBodyContent(field + .getCompilationUnit(), parentType.getTypeQualifiedName('.'), + setterName, fieldName, argname, String.valueOf('\n')); if (body != null) { buf.append(body); } buf.append("}\n"); //$NON-NLS-1$ return buf.toString(); } - + /** - * Create a stub for a getter of the given field using getter/setter templates. The resulting code - * has to be formatted and indented. - * @param field The field to create a getter for - * @param getterName The chosen name for the getter - * @param addComments If true, comments will be added. - * @param flags The flags signaling visibility, if static, synchronized or final + * Create a stub for a getter of the given field using getter/setter + * templates. The resulting code has to be formatted and indented. + * + * @param field + * The field to create a getter for + * @param getterName + * The chosen name for the getter + * @param addComments + * If true, comments will be added. + * @param flags + * The flags signaling visibility, if static, synchronized or + * final * @return Returns the generated stub. * @throws CoreException */ - public static String getGetterStub(IField field, String getterName, boolean addComments, int flags) throws CoreException { - String fieldName= field.getElementName(); - IType parentType= field.getDeclaringType(); - - boolean isStatic= Flags.isStatic(flags); -// boolean isSync= Flags.isSynchronized(flags); - boolean isFinal= Flags.isFinal(flags); - - String typeName= Signature.toString(field.getTypeSignature()); - String accessorName = NamingConventions.removePrefixAndSuffixForFieldName(field.getJavaProject(), fieldName, field.getFlags()); + public static String getGetterStub(IField field, String getterName, + boolean addComments, int flags) throws CoreException { + String fieldName = field.getElementName(); + IType parentType = field.getDeclaringType(); + + boolean isStatic = Flags.isStatic(flags); + // boolean isSync= Flags.isSynchronized(flags); + boolean isFinal = Flags.isFinal(flags); + + String typeName = Signature.toString(field.getTypeSignature()); + String accessorName = NamingConventions + .removePrefixAndSuffixForFieldName(field.getJavaProject(), + fieldName, field.getFlags()); // create the getter stub - StringBuffer buf= new StringBuffer(); + StringBuffer buf = new StringBuffer(); if (addComments) { - String comment= CodeGeneration.getGetterComment(field.getCompilationUnit(), parentType.getTypeQualifiedName('.'), getterName, field.getElementName(), typeName, accessorName, String.valueOf('\n')); + String comment = CodeGeneration.getGetterComment(field + .getCompilationUnit(), + parentType.getTypeQualifiedName('.'), getterName, field + .getElementName(), typeName, accessorName, String + .valueOf('\n')); if (comment != null) { buf.append(comment); buf.append('\n'); - } + } } - + buf.append(JdtFlags.getVisibilityString(flags)); - buf.append(' '); + buf.append(' '); if (isStatic) buf.append("static "); //$NON-NLS-1$ -// if (isSync) -// buf.append("synchronized "); //$NON-NLS-1$ + // if (isSync) + // buf.append("synchronized "); //$NON-NLS-1$ if (isFinal) buf.append("final "); //$NON-NLS-1$ - + buf.append(typeName); buf.append(' '); buf.append(getterName); buf.append("() {\n"); //$NON-NLS-1$ - - boolean useThis= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEGEN_KEYWORD_THIS); + + boolean useThis = PreferenceConstants.getPreferenceStore().getBoolean( + PreferenceConstants.CODEGEN_KEYWORD_THIS); if (useThis && !isStatic) { - fieldName= "this." + fieldName; //$NON-NLS-1$ + fieldName = "this." + fieldName; //$NON-NLS-1$ } - - String body= CodeGeneration.getGetterMethodBodyContent(field.getCompilationUnit(), parentType.getTypeQualifiedName('.'), getterName, fieldName, String.valueOf('\n')); + + String body = CodeGeneration.getGetterMethodBodyContent(field + .getCompilationUnit(), parentType.getTypeQualifiedName('.'), + getterName, fieldName, String.valueOf('\n')); if (body != null) { buf.append(body); } buf.append("}\n"); //$NON-NLS-1$ - return buf.toString(); + return buf.toString(); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/IRequestQuery.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/IRequestQuery.java index 3f24fa1..a7b9989 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/IRequestQuery.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/IRequestQuery.java @@ -12,19 +12,21 @@ package net.sourceforge.phpdt.internal.corext.codemanipulation; import net.sourceforge.phpdt.core.IMember; - /** - * Query object to let operations callback the actions. - * Example is a callback to ask if a existing method should be replaced. + * Query object to let operations callback the actions. Example is a callback to + * ask if a existing method should be replaced. */ public interface IRequestQuery { - + // return codes - public static final int CANCEL= 0; - public static final int NO= 1; - public static final int YES= 2; - public static final int YES_ALL= 3; - + public static final int CANCEL = 0; + + public static final int NO = 1; + + public static final int YES = 2; + + public static final int YES_ALL = 3; + /** * Do the callback. Returns YES, NO, YES_ALL or CANCEL */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/StubUtility.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/StubUtility.java index 4e0f8f8..10b0b08 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/StubUtility.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/StubUtility.java @@ -43,1027 +43,1262 @@ import org.eclipse.jface.text.templates.TemplateVariable; import org.eclipse.swt.SWT; public class StubUtility { - - + public static class GenStubSettings extends CodeGenerationSettings { - - public boolean callSuper; - public boolean methodOverwrites; - public boolean noBody; - public int methodModifiers; - - public GenStubSettings(CodeGenerationSettings settings) { - settings.setSettings(this); - methodModifiers= -1; - } - - } - - private static final String[] EMPTY= new String[0]; - - /** - * Generates a method stub including the method comment. Given a template - * method, a stub with the same signature will be constructed so it can be - * added to a type. The method body will be empty or contain a return or - * super call. - * @param destTypeName The name of the type to which the method will be - * added to - * @param method A method template (method belongs to different type than the parent) - * @param definingType The type that defines the method. - * @param settings Options as defined above (GenStubSettings) - * @param imports Imports required by the stub are added to the imports structure. If imports structure is null - * all type names are qualified. - * @throws JavaModelException - */ - public static String genStub(ICompilationUnit cu, String destTypeName, IMethod method, IType definingType, GenStubSettings settings) throws CoreException { - //IImportsStructure imports) throws CoreException { - String methName= method.getElementName(); - String[] paramNames= suggestArgumentNames(method.getJavaProject(), method.getParameterNames()); - String returnType= method.isConstructor() ? null : method.getReturnType(); - String lineDelimiter= String.valueOf('\n'); // reformatting required - - - StringBuffer buf= new StringBuffer(); - // add method comment - if (settings.createComments && cu != null) { - IMethod overridden= null; - if (settings.methodOverwrites && returnType != null) { - overridden= JavaModelUtil.findMethod(methName, method.getParameterTypes(), false, definingType.getMethods()); - } - String comment= getMethodComment(cu, destTypeName, methName, paramNames, method.getExceptionTypes(), returnType, overridden, lineDelimiter); - if (comment != null) { - buf.append(comment); - } else { - buf.append("/**").append(lineDelimiter); //$NON-NLS-1$ - buf.append(" *").append(lineDelimiter); //$NON-NLS-1$ - buf.append(" */").append(lineDelimiter); //$NON-NLS-1$ - } - buf.append(lineDelimiter); - } - // add method declaration - String bodyContent= null; - if (!settings.noBody) { - String bodyStatement= getDefaultMethodBodyStatement(methName, paramNames, returnType, settings.callSuper); - bodyContent= getMethodBodyContent(returnType == null, method.getJavaProject(), destTypeName, methName, bodyStatement, lineDelimiter); - if (bodyContent == null) { - bodyContent= ""; //$NON-NLS-1$ - } - } - int flags= settings.methodModifiers; - if (flags == -1) { - flags= method.getFlags(); - } - - genMethodDeclaration(destTypeName, method, flags, bodyContent, buf); // imports, buf); - return buf.toString(); - } - /** - * Generates a method stub not including the method comment. Given a - * template method and the body content, a stub with the same signature will - * be constructed so it can be added to a type. - * @param destTypeName The name of the type to which the method will be - * added to - * @param method A method template (method belongs to different type than the parent) - * @param bodyContent Content of the body - * @param imports Imports required by the stub are added to the imports - * structure. If imports structure is null all type names are - * qualified. - * @param buf The buffer to append the gerenated code. - * @throws JavaModelException - */ - public static void genMethodDeclaration(String destTypeName, IMethod method, String bodyContent, StringBuffer buf) throws CoreException { // IImportsStructure imports, StringBuffer buf) throws CoreException { - genMethodDeclaration(destTypeName, method, method.getFlags(), bodyContent, buf); + public boolean callSuper; + + public boolean methodOverwrites; + + public boolean noBody; + + public int methodModifiers; + + public GenStubSettings(CodeGenerationSettings settings) { + settings.setSettings(this); + methodModifiers = -1; } - - /** - * Generates a method stub not including the method comment. Given a - * template method and the body content, a stub with the same signature will - * be constructed so it can be added to a type. - * @param destTypeName The name of the type to which the method will be - * added to - * @param method A method template (method belongs to different type than the parent) - * @param bodyContent Content of the body - * @param imports Imports required by the stub are added to the imports - * structure. If imports structure is null all type names are - * qualified. - * @param buf The buffer to append the gerenated code. - * @throws JavaModelException - */ - public static void genMethodDeclaration(String destTypeName, IMethod method, int flags, String bodyContent, StringBuffer buf) throws CoreException { - //IImportsStructure imports, StringBuffer buf) throws CoreException { - IType parentType= method.getDeclaringType(); - String methodName= method.getElementName(); - String[] paramTypes= method.getParameterTypes(); - String[] paramNames= suggestArgumentNames(parentType.getJavaProject(), method.getParameterNames()); - - String[] excTypes= method.getExceptionTypes(); - - boolean isConstructor= method.isConstructor(); - String retTypeSig= isConstructor ? null : method.getReturnType(); - - int lastParam= paramTypes.length -1; - - if (Flags.isPublic(flags) || (parentType.isInterface() && bodyContent != null)) { - buf.append("public "); //$NON-NLS-1$ - } else if (Flags.isProtected(flags)) { - buf.append("protected "); //$NON-NLS-1$ - } else if (Flags.isPrivate(flags)) { - buf.append("private "); //$NON-NLS-1$ + + } + + private static final String[] EMPTY = new String[0]; + + /** + * Generates a method stub including the method comment. Given a template + * method, a stub with the same signature will be constructed so it can be + * added to a type. The method body will be empty or contain a return or + * super call. + * + * @param destTypeName + * The name of the type to which the method will be added to + * @param method + * A method template (method belongs to different type than the + * parent) + * @param definingType + * The type that defines the method. + * @param settings + * Options as defined above (GenStubSettings) + * @param imports + * Imports required by the stub are added to the imports + * structure. If imports structure is null all + * type names are qualified. + * @throws JavaModelException + */ + public static String genStub(ICompilationUnit cu, String destTypeName, + IMethod method, IType definingType, GenStubSettings settings) + throws CoreException { + // IImportsStructure imports) throws CoreException { + String methName = method.getElementName(); + String[] paramNames = suggestArgumentNames(method.getJavaProject(), + method.getParameterNames()); + String returnType = method.isConstructor() ? null : method + .getReturnType(); + String lineDelimiter = String.valueOf('\n'); // reformatting required + + StringBuffer buf = new StringBuffer(); + // add method comment + if (settings.createComments && cu != null) { + IMethod overridden = null; + if (settings.methodOverwrites && returnType != null) { + overridden = JavaModelUtil.findMethod(methName, method + .getParameterTypes(), false, definingType.getMethods()); } -// if (Flags.isSynchronized(flags)) { -// buf.append("synchronized "); //$NON-NLS-1$ -// } -// if (Flags.isVolatile(flags)) { -// buf.append("volatile "); //$NON-NLS-1$ -// } -// if (Flags.isStrictfp(flags)) { -// buf.append("strictfp "); //$NON-NLS-1$ -// } - if (Flags.isStatic(flags)) { - buf.append("static "); //$NON-NLS-1$ - } - - if (isConstructor) { - buf.append(destTypeName); + String comment = getMethodComment(cu, destTypeName, methName, + paramNames, method.getExceptionTypes(), returnType, + overridden, lineDelimiter); + if (comment != null) { + buf.append(comment); } else { - String retTypeFrm; - if (!isPrimitiveType(retTypeSig)) { - retTypeFrm= resolveAndAdd(retTypeSig, parentType); - } else { - retTypeFrm= Signature.toString(retTypeSig); - } - buf.append(retTypeFrm); - buf.append(' '); - buf.append(methodName); - } - buf.append('('); - for (int i= 0; i <= lastParam; i++) { - String paramTypeSig= paramTypes[i]; - String paramTypeFrm; - - if (!isPrimitiveType(paramTypeSig)) { - paramTypeFrm= resolveAndAdd(paramTypeSig, parentType); - } else { - paramTypeFrm= Signature.toString(paramTypeSig); - } - buf.append(paramTypeFrm); - buf.append(' '); - buf.append(paramNames[i]); - if (i < lastParam) { - buf.append(", "); //$NON-NLS-1$ - } - } - buf.append(')'); - - int lastExc= excTypes.length - 1; - if (lastExc >= 0) { - buf.append(" throws "); //$NON-NLS-1$ - for (int i= 0; i <= lastExc; i++) { - String excTypeSig= excTypes[i]; - String excTypeFrm= resolveAndAdd(excTypeSig, parentType); - buf.append(excTypeFrm); - if (i < lastExc) { - buf.append(", "); //$NON-NLS-1$ - } - } + buf.append("/**").append(lineDelimiter); //$NON-NLS-1$ + buf.append(" *").append(lineDelimiter); //$NON-NLS-1$ + buf.append(" */").append(lineDelimiter); //$NON-NLS-1$ } + buf.append(lineDelimiter); + } + // add method declaration + String bodyContent = null; + if (!settings.noBody) { + String bodyStatement = getDefaultMethodBodyStatement(methName, + paramNames, returnType, settings.callSuper); + bodyContent = getMethodBodyContent(returnType == null, method + .getJavaProject(), destTypeName, methName, bodyStatement, + lineDelimiter); if (bodyContent == null) { - buf.append(";\n\n"); //$NON-NLS-1$ - } else { - buf.append(" {\n\t"); //$NON-NLS-1$ - if ((bodyContent != null) && (bodyContent.length() > 0)) { - buf.append(bodyContent); - buf.append('\n'); - } - buf.append("}\n"); //$NON-NLS-1$ + bodyContent = ""; //$NON-NLS-1$ } } - - public static String getDefaultMethodBodyStatement(String methodName, String[] paramNames, String retTypeSig, boolean callSuper) { - StringBuffer buf= new StringBuffer(); - if (callSuper) { - if (retTypeSig != null) { - if (!Signature.SIG_VOID.equals(retTypeSig)) { - buf.append("return "); //$NON-NLS-1$ - } - buf.append("super."); //$NON-NLS-1$ - buf.append(methodName); - } else { - buf.append("super"); //$NON-NLS-1$ - } - buf.append('('); - for (int i= 0; i < paramNames.length; i++) { - if (i > 0) { - buf.append(", "); //$NON-NLS-1$ - } - buf.append(paramNames[i]); - } - buf.append(");"); //$NON-NLS-1$ - } else { - if (retTypeSig != null && !retTypeSig.equals(Signature.SIG_VOID)) { - if (!isPrimitiveType(retTypeSig) || Signature.getArrayCount(retTypeSig) > 0) { - buf.append("return null;"); //$NON-NLS-1$ - } else if (retTypeSig.equals(Signature.SIG_BOOLEAN)) { - buf.append("return false;"); //$NON-NLS-1$ - } else { - buf.append("return 0;"); //$NON-NLS-1$ - } - } - } - return buf.toString(); - } + int flags = settings.methodModifiers; + if (flags == -1) { + flags = method.getFlags(); + } - public static String getMethodBodyContent(boolean isConstructor, IJavaProject project, String destTypeName, String methodName, String bodyStatement, String lineDelimiter) throws CoreException { - String templateName= isConstructor ? CodeTemplateContextType.CONSTRUCTORSTUB : CodeTemplateContextType.METHODSTUB; - Template template= PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(templateName); - if (template == null) { - return bodyStatement; - } - CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), project, lineDelimiter); - context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName); - context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, destTypeName); - context.setVariable(CodeTemplateContextType.BODY_STATEMENT, bodyStatement); - String str= evaluateTemplate(context, template); - if (str == null && !Strings.containsOnlyWhitespaces(bodyStatement)) { - return bodyStatement; - } - return str; + genMethodDeclaration(destTypeName, method, flags, bodyContent, buf); // imports, + // buf); + return buf.toString(); + } + + /** + * Generates a method stub not including the method comment. Given a + * template method and the body content, a stub with the same signature will + * be constructed so it can be added to a type. + * + * @param destTypeName + * The name of the type to which the method will be added to + * @param method + * A method template (method belongs to different type than the + * parent) + * @param bodyContent + * Content of the body + * @param imports + * Imports required by the stub are added to the imports + * structure. If imports structure is null all + * type names are qualified. + * @param buf + * The buffer to append the gerenated code. + * @throws JavaModelException + */ + public static void genMethodDeclaration(String destTypeName, + IMethod method, String bodyContent, StringBuffer buf) + throws CoreException { // IImportsStructure imports, StringBuffer + // buf) throws CoreException { + genMethodDeclaration(destTypeName, method, method.getFlags(), + bodyContent, buf); + } + + /** + * Generates a method stub not including the method comment. Given a + * template method and the body content, a stub with the same signature will + * be constructed so it can be added to a type. + * + * @param destTypeName + * The name of the type to which the method will be added to + * @param method + * A method template (method belongs to different type than the + * parent) + * @param bodyContent + * Content of the body + * @param imports + * Imports required by the stub are added to the imports + * structure. If imports structure is null all + * type names are qualified. + * @param buf + * The buffer to append the gerenated code. + * @throws JavaModelException + */ + public static void genMethodDeclaration(String destTypeName, + IMethod method, int flags, String bodyContent, StringBuffer buf) + throws CoreException { + // IImportsStructure imports, StringBuffer buf) throws CoreException { + IType parentType = method.getDeclaringType(); + String methodName = method.getElementName(); + String[] paramTypes = method.getParameterTypes(); + String[] paramNames = suggestArgumentNames(parentType.getJavaProject(), + method.getParameterNames()); + + String[] excTypes = method.getExceptionTypes(); + + boolean isConstructor = method.isConstructor(); + String retTypeSig = isConstructor ? null : method.getReturnType(); + + int lastParam = paramTypes.length - 1; + + if (Flags.isPublic(flags) + || (parentType.isInterface() && bodyContent != null)) { + buf.append("public "); //$NON-NLS-1$ + } else if (Flags.isProtected(flags)) { + buf.append("protected "); //$NON-NLS-1$ + } else if (Flags.isPrivate(flags)) { + buf.append("private "); //$NON-NLS-1$ } - - public static String getGetterMethodBodyContent(IJavaProject project, String destTypeName, String methodName, String fieldName, String lineDelimiter) throws CoreException { - String templateName= CodeTemplateContextType.GETTERSTUB; - Template template= PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(templateName); - if (template == null) { - return null; - } - CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), project, lineDelimiter); - context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName); - context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, destTypeName); - context.setVariable(CodeTemplateContextType.FIELD, fieldName); - - return evaluateTemplate(context, template); + // if (Flags.isSynchronized(flags)) { + // buf.append("synchronized "); //$NON-NLS-1$ + // } + // if (Flags.isVolatile(flags)) { + // buf.append("volatile "); //$NON-NLS-1$ + // } + // if (Flags.isStrictfp(flags)) { + // buf.append("strictfp "); //$NON-NLS-1$ + // } + if (Flags.isStatic(flags)) { + buf.append("static "); //$NON-NLS-1$ } - - public static String getSetterMethodBodyContent(IJavaProject project, String destTypeName, String methodName, String fieldName, String paramName, String lineDelimiter) throws CoreException { - String templateName= CodeTemplateContextType.SETTERSTUB; - Template template= PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(templateName); - if (template == null) { - return null; + + if (isConstructor) { + buf.append(destTypeName); + } else { + String retTypeFrm; + if (!isPrimitiveType(retTypeSig)) { + retTypeFrm = resolveAndAdd(retTypeSig, parentType); + } else { + retTypeFrm = Signature.toString(retTypeSig); } - CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), project, lineDelimiter); - context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName); - context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, destTypeName); - context.setVariable(CodeTemplateContextType.FIELD, fieldName); - context.setVariable(CodeTemplateContextType.FIELD_TYPE, fieldName); - context.setVariable(CodeTemplateContextType.PARAM, paramName); - - return evaluateTemplate(context, template); + buf.append(retTypeFrm); + buf.append(' '); + buf.append(methodName); } - - public static String getCatchBodyContent(ICompilationUnit cu, String exceptionType, String variableName, String lineDelimiter) throws CoreException { - Template template= PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(CodeTemplateContextType.CATCHBLOCK); - if (template == null) { - return null; - } + buf.append('('); + for (int i = 0; i <= lastParam; i++) { + String paramTypeSig = paramTypes[i]; + String paramTypeFrm; - CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelimiter); - context.setVariable(CodeTemplateContextType.EXCEPTION_TYPE, exceptionType); - context.setVariable(CodeTemplateContextType.EXCEPTION_VAR, variableName); //$NON-NLS-1$ - return evaluateTemplate(context, template); - } - - /** - * @see net.sourceforge.phpdt.ui.CodeGeneration#getTypeComment(ICompilationUnit, String, String) - */ - public static String getCompilationUnitContent(ICompilationUnit cu, String typeComment, String typeContent, String lineDelimiter) throws CoreException { - IPackageFragment pack= (IPackageFragment) cu.getParent(); - String packDecl= pack.isDefaultPackage() ? "" : "package " + pack.getElementName() + ';'; //$NON-NLS-1$ //$NON-NLS-2$ - - Template template= PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(CodeTemplateContextType.NEWTYPE); - if (template == null) { - return null; + if (!isPrimitiveType(paramTypeSig)) { + paramTypeFrm = resolveAndAdd(paramTypeSig, parentType); + } else { + paramTypeFrm = Signature.toString(paramTypeSig); } - - IJavaProject project= cu.getJavaProject(); - CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), project, lineDelimiter); - context.setCompilationUnitVariables(cu); - context.setVariable(CodeTemplateContextType.PACKAGE_DECLARATION, packDecl); - context.setVariable(CodeTemplateContextType.TYPE_COMMENT, typeComment != null ? typeComment : ""); //$NON-NLS-1$ - context.setVariable(CodeTemplateContextType.TYPE_DECLARATION, typeContent); - context.setVariable(CodeTemplateContextType.TYPENAME, Signature.getQualifier(cu.getElementName())); - return evaluateTemplate(context, template); - } - - /* - * @see net.sourceforge.phpdt.ui.CodeGeneration#getTypeComment(ICompilationUnit, String, String) - */ - public static String getTypeComment(ICompilationUnit cu, String typeQualifiedName, String lineDelim) throws CoreException { - Template template= PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(CodeTemplateContextType.TYPECOMMENT); - if (template == null) { - return null; + buf.append(paramTypeFrm); + buf.append(' '); + buf.append(paramNames[i]); + if (i < lastParam) { + buf.append(", "); //$NON-NLS-1$ } - CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelim); - context.setCompilationUnitVariables(cu); - context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, Signature.getQualifier(typeQualifiedName)); - context.setVariable(CodeTemplateContextType.TYPENAME, Signature.getSimpleName(typeQualifiedName)); - return evaluateTemplate(context, template); } + buf.append(')'); -// private static String[] getParameterTypesQualifiedNames(IMethodBinding binding) { -// ITypeBinding[] typeBindings= binding.getParameterTypes(); -// String[] result= new String[typeBindings.length]; -// for (int i= 0; i < result.length; i++) { -// result[i]= typeBindings[i].getQualifiedName(); -// } -// return result; -// } - - private static String getSeeTag(String declaringClassQualifiedName, String methodName, String[] parameterTypesQualifiedNames) { - StringBuffer buf= new StringBuffer(); - buf.append("@see "); //$NON-NLS-1$ - buf.append(declaringClassQualifiedName); - buf.append('#'); - buf.append(methodName); - buf.append('('); - for (int i= 0; i < parameterTypesQualifiedNames.length; i++) { - if (i > 0) { + int lastExc = excTypes.length - 1; + if (lastExc >= 0) { + buf.append(" throws "); //$NON-NLS-1$ + for (int i = 0; i <= lastExc; i++) { + String excTypeSig = excTypes[i]; + String excTypeFrm = resolveAndAdd(excTypeSig, parentType); + buf.append(excTypeFrm); + if (i < lastExc) { buf.append(", "); //$NON-NLS-1$ } - buf.append(parameterTypesQualifiedNames[i]); } - buf.append(')'); - return buf.toString(); } - - private static String getSeeTag(IMethod overridden) throws JavaModelException { - IType declaringType= overridden.getDeclaringType(); - StringBuffer buf= new StringBuffer(); - buf.append("@see "); //$NON-NLS-1$ - buf.append(declaringType.getFullyQualifiedName('.')); - buf.append('#'); - buf.append(overridden.getElementName()); + if (bodyContent == null) { + buf.append(";\n\n"); //$NON-NLS-1$ + } else { + buf.append(" {\n\t"); //$NON-NLS-1$ + if ((bodyContent != null) && (bodyContent.length() > 0)) { + buf.append(bodyContent); + buf.append('\n'); + } + buf.append("}\n"); //$NON-NLS-1$ + } + } + + public static String getDefaultMethodBodyStatement(String methodName, + String[] paramNames, String retTypeSig, boolean callSuper) { + StringBuffer buf = new StringBuffer(); + if (callSuper) { + if (retTypeSig != null) { + if (!Signature.SIG_VOID.equals(retTypeSig)) { + buf.append("return "); //$NON-NLS-1$ + } + buf.append("super."); //$NON-NLS-1$ + buf.append(methodName); + } else { + buf.append("super"); //$NON-NLS-1$ + } buf.append('('); - String[] paramTypes= overridden.getParameterTypes(); - for (int i= 0; i < paramTypes.length; i++) { + for (int i = 0; i < paramNames.length; i++) { if (i > 0) { buf.append(", "); //$NON-NLS-1$ } - String curr= paramTypes[i]; - buf.append(JavaModelUtil.getResolvedTypeName(curr, declaringType)); - int arrayCount= Signature.getArrayCount(curr); - while (arrayCount > 0) { - buf.append("[]"); //$NON-NLS-1$ - arrayCount--; + buf.append(paramNames[i]); + } + buf.append(");"); //$NON-NLS-1$ + } else { + if (retTypeSig != null && !retTypeSig.equals(Signature.SIG_VOID)) { + if (!isPrimitiveType(retTypeSig) + || Signature.getArrayCount(retTypeSig) > 0) { + buf.append("return null;"); //$NON-NLS-1$ + } else if (retTypeSig.equals(Signature.SIG_BOOLEAN)) { + buf.append("return false;"); //$NON-NLS-1$ + } else { + buf.append("return 0;"); //$NON-NLS-1$ } } - buf.append(')'); - return buf.toString(); } - - /** - * @see net.sourceforge.phpdt.ui.CodeGeneration#getMethodComment(IMethod,IMethod,String) - */ - public static String getMethodComment(IMethod method, IMethod overridden, String lineDelimiter) throws CoreException { - String retType= method.isConstructor() ? null : method.getReturnType(); - String[] paramNames= method.getParameterNames(); - - return getMethodComment(method.getCompilationUnit(), method.getDeclaringType().getElementName(), - method.getElementName(), paramNames, method.getExceptionTypes(), retType, overridden, lineDelimiter); + return buf.toString(); + } + + public static String getMethodBodyContent(boolean isConstructor, + IJavaProject project, String destTypeName, String methodName, + String bodyStatement, String lineDelimiter) throws CoreException { + String templateName = isConstructor ? CodeTemplateContextType.CONSTRUCTORSTUB + : CodeTemplateContextType.METHODSTUB; + Template template = PHPeclipsePlugin.getDefault() + .getCodeTemplateStore().findTemplate(templateName); + if (template == null) { + return bodyStatement; } + CodeTemplateContext context = new CodeTemplateContext(template + .getContextTypeId(), project, lineDelimiter); + context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, + methodName); + context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, + destTypeName); + context.setVariable(CodeTemplateContextType.BODY_STATEMENT, + bodyStatement); + String str = evaluateTemplate(context, template); + if (str == null && !Strings.containsOnlyWhitespaces(bodyStatement)) { + return bodyStatement; + } + return str; + } - /** - * @see net.sourceforge.phpdt.ui.CodeGeneration#getMethodComment(ICompilationUnit, String, String, String[], String[], String, IMethod, String) - */ - public static String getMethodComment(ICompilationUnit cu, String typeName, String methodName, String[] paramNames, String[] excTypeSig, String retTypeSig, IMethod overridden, String lineDelimiter) throws CoreException { - String templateName= CodeTemplateContextType.METHODCOMMENT; - if (retTypeSig == null) { - templateName= CodeTemplateContextType.CONSTRUCTORCOMMENT; - } else if (overridden != null) { - templateName= CodeTemplateContextType.OVERRIDECOMMENT; - } - Template template= PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(templateName); - if (template == null) { - return null; - } - CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelimiter); - context.setCompilationUnitVariables(cu); - context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName); - context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName); - - if (retTypeSig != null) { - context.setVariable(CodeTemplateContextType.RETURN_TYPE, Signature.toString(retTypeSig)); - } - if (overridden != null) { - context.setVariable(CodeTemplateContextType.SEE_TAG, getSeeTag(overridden)); - } - TemplateBuffer buffer; - try { - buffer= context.evaluate(template); - } catch (BadLocationException e) { - throw new CoreException(Status.CANCEL_STATUS); - } catch (TemplateException e) { - throw new CoreException(Status.CANCEL_STATUS); - } - if (buffer == null) { - return null; - } - - String str= buffer.getString(); - if (Strings.containsOnlyWhitespaces(str)) { - return null; - } - TemplateVariable position= findTagVariable(buffer); // look if Javadoc tags have to be added - if (position == null) { - return str; - } - - IDocument textBuffer= new Document(str); - String[] exceptionNames= new String[excTypeSig.length]; - for (int i= 0; i < excTypeSig.length; i++) { - exceptionNames[i]= Signature.toString(excTypeSig[i]); - } - String returnType= retTypeSig != null ? Signature.toString(retTypeSig) : null; - int[] tagOffsets= position.getOffsets(); - for (int i= tagOffsets.length - 1; i >= 0; i--) { // from last to first - try { - insertTag(textBuffer, tagOffsets[i], position.getLength(), paramNames, exceptionNames, returnType, false, lineDelimiter); - } catch (BadLocationException e) { - throw new CoreException(PHPUIStatus.createError(IStatus.ERROR, e)); - } + public static String getGetterMethodBodyContent(IJavaProject project, + String destTypeName, String methodName, String fieldName, + String lineDelimiter) throws CoreException { + String templateName = CodeTemplateContextType.GETTERSTUB; + Template template = PHPeclipsePlugin.getDefault() + .getCodeTemplateStore().findTemplate(templateName); + if (template == null) { + return null; + } + CodeTemplateContext context = new CodeTemplateContext(template + .getContextTypeId(), project, lineDelimiter); + context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, + methodName); + context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, + destTypeName); + context.setVariable(CodeTemplateContextType.FIELD, fieldName); + + return evaluateTemplate(context, template); + } + + public static String getSetterMethodBodyContent(IJavaProject project, + String destTypeName, String methodName, String fieldName, + String paramName, String lineDelimiter) throws CoreException { + String templateName = CodeTemplateContextType.SETTERSTUB; + Template template = PHPeclipsePlugin.getDefault() + .getCodeTemplateStore().findTemplate(templateName); + if (template == null) { + return null; + } + CodeTemplateContext context = new CodeTemplateContext(template + .getContextTypeId(), project, lineDelimiter); + context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, + methodName); + context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, + destTypeName); + context.setVariable(CodeTemplateContextType.FIELD, fieldName); + context.setVariable(CodeTemplateContextType.FIELD_TYPE, fieldName); + context.setVariable(CodeTemplateContextType.PARAM, paramName); + + return evaluateTemplate(context, template); + } + + public static String getCatchBodyContent(ICompilationUnit cu, + String exceptionType, String variableName, String lineDelimiter) + throws CoreException { + Template template = PHPeclipsePlugin.getDefault() + .getCodeTemplateStore().findTemplate( + CodeTemplateContextType.CATCHBLOCK); + if (template == null) { + return null; + } + + CodeTemplateContext context = new CodeTemplateContext(template + .getContextTypeId(), cu.getJavaProject(), lineDelimiter); + context.setVariable(CodeTemplateContextType.EXCEPTION_TYPE, + exceptionType); + context + .setVariable(CodeTemplateContextType.EXCEPTION_VAR, + variableName); //$NON-NLS-1$ + return evaluateTemplate(context, template); + } + + /** + * @see net.sourceforge.phpdt.ui.CodeGeneration#getTypeComment(ICompilationUnit, + * String, String) + */ + public static String getCompilationUnitContent(ICompilationUnit cu, + String typeComment, String typeContent, String lineDelimiter) + throws CoreException { + IPackageFragment pack = (IPackageFragment) cu.getParent(); + String packDecl = pack.isDefaultPackage() ? "" : "package " + pack.getElementName() + ';'; //$NON-NLS-1$ //$NON-NLS-2$ + + Template template = PHPeclipsePlugin.getDefault() + .getCodeTemplateStore().findTemplate( + CodeTemplateContextType.NEWTYPE); + if (template == null) { + return null; + } + + IJavaProject project = cu.getJavaProject(); + CodeTemplateContext context = new CodeTemplateContext(template + .getContextTypeId(), project, lineDelimiter); + context.setCompilationUnitVariables(cu); + context.setVariable(CodeTemplateContextType.PACKAGE_DECLARATION, + packDecl); + context.setVariable(CodeTemplateContextType.TYPE_COMMENT, + typeComment != null ? typeComment : ""); //$NON-NLS-1$ + context.setVariable(CodeTemplateContextType.TYPE_DECLARATION, + typeContent); + context.setVariable(CodeTemplateContextType.TYPENAME, Signature + .getQualifier(cu.getElementName())); + return evaluateTemplate(context, template); + } + + /* + * @see net.sourceforge.phpdt.ui.CodeGeneration#getTypeComment(ICompilationUnit, + * String, String) + */ + public static String getTypeComment(ICompilationUnit cu, + String typeQualifiedName, String lineDelim) throws CoreException { + Template template = PHPeclipsePlugin.getDefault() + .getCodeTemplateStore().findTemplate( + CodeTemplateContextType.TYPECOMMENT); + if (template == null) { + return null; + } + CodeTemplateContext context = new CodeTemplateContext(template + .getContextTypeId(), cu.getJavaProject(), lineDelim); + context.setCompilationUnitVariables(cu); + context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, Signature + .getQualifier(typeQualifiedName)); + context.setVariable(CodeTemplateContextType.TYPENAME, Signature + .getSimpleName(typeQualifiedName)); + return evaluateTemplate(context, template); + } + + // private static String[] getParameterTypesQualifiedNames(IMethodBinding + // binding) { + // ITypeBinding[] typeBindings= binding.getParameterTypes(); + // String[] result= new String[typeBindings.length]; + // for (int i= 0; i < result.length; i++) { + // result[i]= typeBindings[i].getQualifiedName(); + // } + // return result; + // } + + private static String getSeeTag(String declaringClassQualifiedName, + String methodName, String[] parameterTypesQualifiedNames) { + StringBuffer buf = new StringBuffer(); + buf.append("@see "); //$NON-NLS-1$ + buf.append(declaringClassQualifiedName); + buf.append('#'); + buf.append(methodName); + buf.append('('); + for (int i = 0; i < parameterTypesQualifiedNames.length; i++) { + if (i > 0) { + buf.append(", "); //$NON-NLS-1$ } - return textBuffer.get(); + buf.append(parameterTypesQualifiedNames[i]); } + buf.append(')'); + return buf.toString(); + } - public static String getFieldComment(ICompilationUnit cu, String typeName, String fieldName, String lineDelimiter) throws CoreException { - Template template= PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(CodeTemplateContextType.FIELDCOMMENT); - if (template == null) { - return null; + private static String getSeeTag(IMethod overridden) + throws JavaModelException { + IType declaringType = overridden.getDeclaringType(); + StringBuffer buf = new StringBuffer(); + buf.append("@see "); //$NON-NLS-1$ + buf.append(declaringType.getFullyQualifiedName('.')); + buf.append('#'); + buf.append(overridden.getElementName()); + buf.append('('); + String[] paramTypes = overridden.getParameterTypes(); + for (int i = 0; i < paramTypes.length; i++) { + if (i > 0) { + buf.append(", "); //$NON-NLS-1$ } - CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelimiter); - context.setCompilationUnitVariables(cu); - context.setVariable(CodeTemplateContextType.FIELD_TYPE, typeName); - context.setVariable(CodeTemplateContextType.FIELD, fieldName); - - return evaluateTemplate(context, template); - } - - - /** - * @see net.sourceforge.phpdt.ui.CodeGeneration#getSetterComment(ICompilationUnit, String, String, String, String, String, String, String) - */ - public static String getSetterComment(ICompilationUnit cu, String typeName, String methodName, String fieldName, String fieldType, String paramName, String bareFieldName, String lineDelimiter) throws CoreException { - String templateName= CodeTemplateContextType.SETTERCOMMENT; - Template template= PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(templateName); - if (template == null) { - return null; + String curr = paramTypes[i]; + buf.append(JavaModelUtil.getResolvedTypeName(curr, declaringType)); + int arrayCount = Signature.getArrayCount(curr); + while (arrayCount > 0) { + buf.append("[]"); //$NON-NLS-1$ + arrayCount--; } - - CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelimiter); - context.setCompilationUnitVariables(cu); - context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName); - context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName); - context.setVariable(CodeTemplateContextType.FIELD, fieldName); - context.setVariable(CodeTemplateContextType.FIELD_TYPE, fieldType); - context.setVariable(CodeTemplateContextType.BARE_FIELD_NAME, bareFieldName); - context.setVariable(CodeTemplateContextType.PARAM, paramName); - - return evaluateTemplate(context, template); - } - - /** - * @see net.sourceforge.phpdt.ui.CodeGeneration#getGetterComment(ICompilationUnit, String, String, String, String, String, String) - */ - public static String getGetterComment(ICompilationUnit cu, String typeName, String methodName, String fieldName, String fieldType, String bareFieldName, String lineDelimiter) throws CoreException { - String templateName= CodeTemplateContextType.GETTERCOMMENT; - Template template= PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(templateName); - if (template == null) { - return null; - } - CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelimiter); - context.setCompilationUnitVariables(cu); - context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName); - context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName); - context.setVariable(CodeTemplateContextType.FIELD, fieldName); - context.setVariable(CodeTemplateContextType.FIELD_TYPE, fieldType); - context.setVariable(CodeTemplateContextType.BARE_FIELD_NAME, bareFieldName); - - return evaluateTemplate(context, template); } - - public static String evaluateTemplate(CodeTemplateContext context, Template template) throws CoreException { - TemplateBuffer buffer; + buf.append(')'); + return buf.toString(); + } + + /** + * @see net.sourceforge.phpdt.ui.CodeGeneration#getMethodComment(IMethod,IMethod,String) + */ + public static String getMethodComment(IMethod method, IMethod overridden, + String lineDelimiter) throws CoreException { + String retType = method.isConstructor() ? null : method.getReturnType(); + String[] paramNames = method.getParameterNames(); + + return getMethodComment(method.getCompilationUnit(), method + .getDeclaringType().getElementName(), method.getElementName(), + paramNames, method.getExceptionTypes(), retType, overridden, + lineDelimiter); + } + + /** + * @see net.sourceforge.phpdt.ui.CodeGeneration#getMethodComment(ICompilationUnit, + * String, String, String[], String[], String, IMethod, String) + */ + public static String getMethodComment(ICompilationUnit cu, String typeName, + String methodName, String[] paramNames, String[] excTypeSig, + String retTypeSig, IMethod overridden, String lineDelimiter) + throws CoreException { + String templateName = CodeTemplateContextType.METHODCOMMENT; + if (retTypeSig == null) { + templateName = CodeTemplateContextType.CONSTRUCTORCOMMENT; + } else if (overridden != null) { + templateName = CodeTemplateContextType.OVERRIDECOMMENT; + } + Template template = PHPeclipsePlugin.getDefault() + .getCodeTemplateStore().findTemplate(templateName); + if (template == null) { + return null; + } + CodeTemplateContext context = new CodeTemplateContext(template + .getContextTypeId(), cu.getJavaProject(), lineDelimiter); + context.setCompilationUnitVariables(cu); + context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName); + context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, + methodName); + + if (retTypeSig != null) { + context.setVariable(CodeTemplateContextType.RETURN_TYPE, Signature + .toString(retTypeSig)); + } + if (overridden != null) { + context.setVariable(CodeTemplateContextType.SEE_TAG, + getSeeTag(overridden)); + } + TemplateBuffer buffer; + try { + buffer = context.evaluate(template); + } catch (BadLocationException e) { + throw new CoreException(Status.CANCEL_STATUS); + } catch (TemplateException e) { + throw new CoreException(Status.CANCEL_STATUS); + } + if (buffer == null) { + return null; + } + + String str = buffer.getString(); + if (Strings.containsOnlyWhitespaces(str)) { + return null; + } + TemplateVariable position = findTagVariable(buffer); // look if + // Javadoc tags + // have to be + // added + if (position == null) { + return str; + } + + IDocument textBuffer = new Document(str); + String[] exceptionNames = new String[excTypeSig.length]; + for (int i = 0; i < excTypeSig.length; i++) { + exceptionNames[i] = Signature.toString(excTypeSig[i]); + } + String returnType = retTypeSig != null ? Signature.toString(retTypeSig) + : null; + int[] tagOffsets = position.getOffsets(); + for (int i = tagOffsets.length - 1; i >= 0; i--) { // from last to + // first try { - buffer= context.evaluate(template); + insertTag(textBuffer, tagOffsets[i], position.getLength(), + paramNames, exceptionNames, returnType, false, + lineDelimiter); } catch (BadLocationException e) { - throw new CoreException(Status.CANCEL_STATUS); - } catch (TemplateException e) { - throw new CoreException(Status.CANCEL_STATUS); + throw new CoreException(PHPUIStatus.createError(IStatus.ERROR, + e)); } - if (buffer == null) - return null; - String str= buffer.getString(); - if (Strings.containsOnlyWhitespaces(str)) { - return null; - } - return str; } + return textBuffer.get(); + } - /** - * @see net.sourceforge.phpdt.ui.CodeGeneration#getMethodComment(ICompilationUnit, String, MethodDeclaration, IMethodBinding, String) - */ -// public static String getMethodComment(ICompilationUnit cu, String typeName, IMethodBinding overridden, String lineDelimiter) throws CoreException { -// if (overridden != null) { -// String declaringClassQualifiedName= overridden.getDeclaringClass().getQualifiedName(); -// String[] parameterTypesQualifiedNames= getParameterTypesQualifiedNames(overridden); -// return getMethodComment(cu, typeName, decl, true, overridden.isDeprecated(), declaringClassQualifiedName, parameterTypesQualifiedNames, lineDelimiter); -// } else { -// return getMethodComment(cu, typeName, decl, false, false, null, null, lineDelimiter); -// } -// } - - /** - * Returns the comment for a method using the comment code templates. - * null is returned if the template is empty. - * @param cu The compilation unit to which the method belongs - * @param typeName Name of the type to which the method belongs. - * @param decl The AST MethodDeclaration node that will be added as new - * method. - * @param isOverridden true iff decl overrides another method - * @param isDeprecated true iff the method that decl overrides is deprecated. - * Note: it must not be true if isOverridden is false. - * @param declaringClassQualifiedName Fully qualified name of the type in which the overriddden - * method (if any exists) in declared. If isOverridden is false, this is ignored. - * @param parameterTypesQualifiedNames Fully qualified names of parameter types of the type in which the overriddden - * method (if any exists) in declared. If isOverridden is false, this is ignored. - * @return String Returns the method comment or null if the - * configured template is empty. - * (formatting required) - * @throws CoreException - */ -// public static String getMethodComment(ICompilationUnit cu, String typeName, MethodDeclaration decl, boolean isOverridden, boolean isDeprecated, String declaringClassQualifiedName, String[] parameterTypesQualifiedNames, String lineDelimiter) throws CoreException { -// String templateName= CodeTemplateContextType.METHODCOMMENT; -// if (decl.isConstructor()) { -// templateName= CodeTemplateContextType.CONSTRUCTORCOMMENT; -// } else if (isOverridden) { -// templateName= CodeTemplateContextType.OVERRIDECOMMENT; -// } -// Template template= PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(templateName); -// if (template == null) { -// return null; -// } -// CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelimiter); -// context.setCompilationUnitVariables(cu); -// context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName); -// context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, decl.getName().getIdentifier()); -// if (!decl.isConstructor()) { -// context.setVariable(CodeTemplateContextType.RETURN_TYPE, ASTNodes.asString(decl.getReturnType())); -// } -// if (isOverridden) { -// String methodName= decl.getName().getIdentifier(); -// context.setVariable(CodeTemplateContextType.SEE_TAG, getSeeTag(declaringClassQualifiedName, methodName, parameterTypesQualifiedNames)); -// } -// -// TemplateBuffer buffer; -// try { -// buffer= context.evaluate(template); -// } catch (BadLocationException e) { -// throw new CoreException(Status.CANCEL_STATUS); -// } catch (TemplateException e) { -// throw new CoreException(Status.CANCEL_STATUS); -// } -// if (buffer == null) -// return null; -// String str= buffer.getString(); -// if (Strings.containsOnlyWhitespaces(str)) { -// return null; -// } -// TemplateVariable position= findTagVariable(buffer); // look if Javadoc tags have to be added -// if (position == null) { -// return str; -// } -// -// IDocument textBuffer= new Document(str); -// List params= decl.parameters(); -// String[] paramNames= new String[params.size()]; -// for (int i= 0; i < params.size(); i++) { -// SingleVariableDeclaration elem= (SingleVariableDeclaration) params.get(i); -// paramNames[i]= elem.getName().getIdentifier(); -// } -// List exceptions= decl.thrownExceptions(); -// String[] exceptionNames= new String[exceptions.size()]; -// for (int i= 0; i < exceptions.size(); i++) { -// exceptionNames[i]= ASTNodes.getSimpleNameIdentifier((Name) exceptions.get(i)); -// } -// String returnType= !decl.isConstructor() ? ASTNodes.asString(decl.getReturnType()) : null; -// int[] tagOffsets= position.getOffsets(); -// for (int i= tagOffsets.length - 1; i >= 0; i--) { // from last to first -// try { -// insertTag(textBuffer, tagOffsets[i], position.getLength(), paramNames, exceptionNames, returnType, isDeprecated, lineDelimiter); -// } catch (BadLocationException e) { -// throw new CoreException(PHPUIStatus.createError(IStatus.ERROR, e)); -// } -// } -// return textBuffer.get(); -// } - - private static TemplateVariable findTagVariable(TemplateBuffer buffer) { - TemplateVariable[] positions= buffer.getVariables(); - for (int i= 0; i < positions.length; i++) { - TemplateVariable curr= positions[i]; - if (CodeTemplateContextType.TAGS.equals(curr.getType())) { - return curr; - } - } - return null; - } - - private static void insertTag(IDocument textBuffer, int offset, int length, String[] paramNames, String[] exceptionNames, String returnType, boolean isDeprecated, String lineDelimiter) throws BadLocationException { - IRegion region= textBuffer.getLineInformationOfOffset(offset); - if (region == null) { - return; + public static String getFieldComment(ICompilationUnit cu, String typeName, + String fieldName, String lineDelimiter) throws CoreException { + Template template = PHPeclipsePlugin.getDefault() + .getCodeTemplateStore().findTemplate( + CodeTemplateContextType.FIELDCOMMENT); + if (template == null) { + return null; + } + CodeTemplateContext context = new CodeTemplateContext(template + .getContextTypeId(), cu.getJavaProject(), lineDelimiter); + context.setCompilationUnitVariables(cu); + context.setVariable(CodeTemplateContextType.FIELD_TYPE, typeName); + context.setVariable(CodeTemplateContextType.FIELD, fieldName); + + return evaluateTemplate(context, template); + } + + /** + * @see net.sourceforge.phpdt.ui.CodeGeneration#getSetterComment(ICompilationUnit, + * String, String, String, String, String, String, String) + */ + public static String getSetterComment(ICompilationUnit cu, String typeName, + String methodName, String fieldName, String fieldType, + String paramName, String bareFieldName, String lineDelimiter) + throws CoreException { + String templateName = CodeTemplateContextType.SETTERCOMMENT; + Template template = PHPeclipsePlugin.getDefault() + .getCodeTemplateStore().findTemplate(templateName); + if (template == null) { + return null; + } + + CodeTemplateContext context = new CodeTemplateContext(template + .getContextTypeId(), cu.getJavaProject(), lineDelimiter); + context.setCompilationUnitVariables(cu); + context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName); + context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, + methodName); + context.setVariable(CodeTemplateContextType.FIELD, fieldName); + context.setVariable(CodeTemplateContextType.FIELD_TYPE, fieldType); + context.setVariable(CodeTemplateContextType.BARE_FIELD_NAME, + bareFieldName); + context.setVariable(CodeTemplateContextType.PARAM, paramName); + + return evaluateTemplate(context, template); + } + + /** + * @see net.sourceforge.phpdt.ui.CodeGeneration#getGetterComment(ICompilationUnit, + * String, String, String, String, String, String) + */ + public static String getGetterComment(ICompilationUnit cu, String typeName, + String methodName, String fieldName, String fieldType, + String bareFieldName, String lineDelimiter) throws CoreException { + String templateName = CodeTemplateContextType.GETTERCOMMENT; + Template template = PHPeclipsePlugin.getDefault() + .getCodeTemplateStore().findTemplate(templateName); + if (template == null) { + return null; + } + CodeTemplateContext context = new CodeTemplateContext(template + .getContextTypeId(), cu.getJavaProject(), lineDelimiter); + context.setCompilationUnitVariables(cu); + context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName); + context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, + methodName); + context.setVariable(CodeTemplateContextType.FIELD, fieldName); + context.setVariable(CodeTemplateContextType.FIELD_TYPE, fieldType); + context.setVariable(CodeTemplateContextType.BARE_FIELD_NAME, + bareFieldName); + + return evaluateTemplate(context, template); + } + + public static String evaluateTemplate(CodeTemplateContext context, + Template template) throws CoreException { + TemplateBuffer buffer; + try { + buffer = context.evaluate(template); + } catch (BadLocationException e) { + throw new CoreException(Status.CANCEL_STATUS); + } catch (TemplateException e) { + throw new CoreException(Status.CANCEL_STATUS); + } + if (buffer == null) + return null; + String str = buffer.getString(); + if (Strings.containsOnlyWhitespaces(str)) { + return null; + } + return str; + } + + /** + * @see net.sourceforge.phpdt.ui.CodeGeneration#getMethodComment(ICompilationUnit, + * String, MethodDeclaration, IMethodBinding, String) + */ + // public static String getMethodComment(ICompilationUnit cu, String + // typeName, IMethodBinding overridden, String lineDelimiter) throws + // CoreException { + // if (overridden != null) { + // String declaringClassQualifiedName= + // overridden.getDeclaringClass().getQualifiedName(); + // String[] parameterTypesQualifiedNames= + // getParameterTypesQualifiedNames(overridden); + // return getMethodComment(cu, typeName, decl, true, + // overridden.isDeprecated(), declaringClassQualifiedName, + // parameterTypesQualifiedNames, lineDelimiter); + // } else { + // return getMethodComment(cu, typeName, decl, false, false, null, null, + // lineDelimiter); + // } + // } + /** + * Returns the comment for a method using the comment code templates. + * null is returned if the template is empty. + * + * @param cu + * The compilation unit to which the method belongs + * @param typeName + * Name of the type to which the method belongs. + * @param decl + * The AST MethodDeclaration node that will be added as new + * method. + * @param isOverridden + * true iff decl overrides another method + * @param isDeprecated + * true iff the method that decl overrides is + * deprecated. Note: it must not be true if + * isOverridden is false. + * @param declaringClassQualifiedName + * Fully qualified name of the type in which the overriddden + * method (if any exists) in declared. If isOverridden is + * false, this is ignored. + * @param parameterTypesQualifiedNames + * Fully qualified names of parameter types of the type in which + * the overriddden method (if any exists) in declared. If + * isOverridden is false, this is ignored. + * @return String Returns the method comment or null if the + * configured template is empty. (formatting required) + * @throws CoreException + */ + // public static String getMethodComment(ICompilationUnit cu, String + // typeName, MethodDeclaration decl, boolean isOverridden, boolean + // isDeprecated, String declaringClassQualifiedName, String[] + // parameterTypesQualifiedNames, String lineDelimiter) throws CoreException + // { + // String templateName= CodeTemplateContextType.METHODCOMMENT; + // if (decl.isConstructor()) { + // templateName= CodeTemplateContextType.CONSTRUCTORCOMMENT; + // } else if (isOverridden) { + // templateName= CodeTemplateContextType.OVERRIDECOMMENT; + // } + // Template template= + // PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(templateName); + // if (template == null) { + // return null; + // } + // CodeTemplateContext context= new + // CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), + // lineDelimiter); + // context.setCompilationUnitVariables(cu); + // context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName); + // context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, + // decl.getName().getIdentifier()); + // if (!decl.isConstructor()) { + // context.setVariable(CodeTemplateContextType.RETURN_TYPE, + // ASTNodes.asString(decl.getReturnType())); + // } + // if (isOverridden) { + // String methodName= decl.getName().getIdentifier(); + // context.setVariable(CodeTemplateContextType.SEE_TAG, + // getSeeTag(declaringClassQualifiedName, methodName, + // parameterTypesQualifiedNames)); + // } + // + // TemplateBuffer buffer; + // try { + // buffer= context.evaluate(template); + // } catch (BadLocationException e) { + // throw new CoreException(Status.CANCEL_STATUS); + // } catch (TemplateException e) { + // throw new CoreException(Status.CANCEL_STATUS); + // } + // if (buffer == null) + // return null; + // String str= buffer.getString(); + // if (Strings.containsOnlyWhitespaces(str)) { + // return null; + // } + // TemplateVariable position= findTagVariable(buffer); // look if Javadoc + // tags have to be added + // if (position == null) { + // return str; + // } + // + // IDocument textBuffer= new Document(str); + // List params= decl.parameters(); + // String[] paramNames= new String[params.size()]; + // for (int i= 0; i < params.size(); i++) { + // SingleVariableDeclaration elem= (SingleVariableDeclaration) + // params.get(i); + // paramNames[i]= elem.getName().getIdentifier(); + // } + // List exceptions= decl.thrownExceptions(); + // String[] exceptionNames= new String[exceptions.size()]; + // for (int i= 0; i < exceptions.size(); i++) { + // exceptionNames[i]= ASTNodes.getSimpleNameIdentifier((Name) + // exceptions.get(i)); + // } + // String returnType= !decl.isConstructor() ? + // ASTNodes.asString(decl.getReturnType()) : null; + // int[] tagOffsets= position.getOffsets(); + // for (int i= tagOffsets.length - 1; i >= 0; i--) { // from last to first + // try { + // insertTag(textBuffer, tagOffsets[i], position.getLength(), paramNames, + // exceptionNames, returnType, isDeprecated, lineDelimiter); + // } catch (BadLocationException e) { + // throw new CoreException(PHPUIStatus.createError(IStatus.ERROR, e)); + // } + // } + // return textBuffer.get(); + // } + private static TemplateVariable findTagVariable(TemplateBuffer buffer) { + TemplateVariable[] positions = buffer.getVariables(); + for (int i = 0; i < positions.length; i++) { + TemplateVariable curr = positions[i]; + if (CodeTemplateContextType.TAGS.equals(curr.getType())) { + return curr; } - String lineStart= textBuffer.get(region.getOffset(), offset - region.getOffset()); - - StringBuffer buf= new StringBuffer(); - for (int i= 0; i < paramNames.length; i++) { - if (buf.length() > 0) { - buf.append(lineDelimiter); buf.append(lineStart); - } - buf.append("@param "); buf.append(paramNames[i]); //$NON-NLS-1$ + } + return null; + } + + private static void insertTag(IDocument textBuffer, int offset, int length, + String[] paramNames, String[] exceptionNames, String returnType, + boolean isDeprecated, String lineDelimiter) + throws BadLocationException { + IRegion region = textBuffer.getLineInformationOfOffset(offset); + if (region == null) { + return; + } + String lineStart = textBuffer.get(region.getOffset(), offset + - region.getOffset()); + + StringBuffer buf = new StringBuffer(); + for (int i = 0; i < paramNames.length; i++) { + if (buf.length() > 0) { + buf.append(lineDelimiter); + buf.append(lineStart); } - if (returnType != null && !returnType.equals("void")) { //$NON-NLS-1$ - if (buf.length() > 0) { - buf.append(lineDelimiter); buf.append(lineStart); - } - buf.append("@return"); //$NON-NLS-1$ + buf.append("@param ");buf.append(paramNames[i]); //$NON-NLS-1$ + } + if (returnType != null && !returnType.equals("void")) { //$NON-NLS-1$ + if (buf.length() > 0) { + buf.append(lineDelimiter); + buf.append(lineStart); } - if (exceptionNames != null) { - for (int i= 0; i < exceptionNames.length; i++) { - if (buf.length() > 0) { - buf.append(lineDelimiter); buf.append(lineStart); - } - buf.append("@throws "); buf.append(exceptionNames[i]); //$NON-NLS-1$ - } - } - if (isDeprecated) { + buf.append("@return"); //$NON-NLS-1$ + } + if (exceptionNames != null) { + for (int i = 0; i < exceptionNames.length; i++) { if (buf.length() > 0) { - buf.append(lineDelimiter); buf.append(lineStart); + buf.append(lineDelimiter); + buf.append(lineStart); } - buf.append("@deprecated"); //$NON-NLS-1$ + buf.append("@throws ");buf.append(exceptionNames[i]); //$NON-NLS-1$ } - textBuffer.replace(offset, length, buf.toString()); } - - private static boolean isPrimitiveType(String typeName) { - char first= Signature.getElementType(typeName).charAt(0); - return (first != Signature.C_RESOLVED && first != Signature.C_UNRESOLVED); + if (isDeprecated) { + if (buf.length() > 0) { + buf.append(lineDelimiter); + buf.append(lineStart); + } + buf.append("@deprecated"); //$NON-NLS-1$ } + textBuffer.replace(offset, length, buf.toString()); + } - private static String resolveAndAdd(String refTypeSig, IType declaringType) throws JavaModelException {//, IImportsStructure imports) throws JavaModelException { - String resolvedTypeName= JavaModelUtil.getResolvedTypeName(refTypeSig, declaringType); - if (resolvedTypeName != null) { - StringBuffer buf= new StringBuffer(); -// if (imports != null) { -// buf.append(imports.addImport(resolvedTypeName)); -// } else { - buf.append(resolvedTypeName); -// } - int arrayCount= Signature.getArrayCount(refTypeSig); - for (int i= 0; i < arrayCount; i++) { - buf.append("[]"); //$NON-NLS-1$ - } - return buf.toString(); + private static boolean isPrimitiveType(String typeName) { + char first = Signature.getElementType(typeName).charAt(0); + return (first != Signature.C_RESOLVED && first != Signature.C_UNRESOLVED); + } + + private static String resolveAndAdd(String refTypeSig, IType declaringType) + throws JavaModelException {// , IImportsStructure imports) throws + // JavaModelException { + String resolvedTypeName = JavaModelUtil.getResolvedTypeName(refTypeSig, + declaringType); + if (resolvedTypeName != null) { + StringBuffer buf = new StringBuffer(); + // if (imports != null) { + // buf.append(imports.addImport(resolvedTypeName)); + // } else { + buf.append(resolvedTypeName); + // } + int arrayCount = Signature.getArrayCount(refTypeSig); + for (int i = 0; i < arrayCount; i++) { + buf.append("[]"); //$NON-NLS-1$ } - return Signature.toString(refTypeSig); + return buf.toString(); } - - /** - * Finds a method in a list of methods. - * @return The found method or null, if nothing found - */ - private static IMethod findMethod(IMethod method, List allMethods) throws JavaModelException { - String name= method.getElementName(); - String[] paramTypes= method.getParameterTypes(); - boolean isConstructor= method.isConstructor(); - - for (int i= allMethods.size() - 1; i >= 0; i--) { - IMethod curr= (IMethod) allMethods.get(i); - if (JavaModelUtil.isSameMethodSignature(name, paramTypes, isConstructor, curr)) { - return curr; - } + return Signature.toString(refTypeSig); + } + + /** + * Finds a method in a list of methods. + * + * @return The found method or null, if nothing found + */ + private static IMethod findMethod(IMethod method, List allMethods) + throws JavaModelException { + String name = method.getElementName(); + String[] paramTypes = method.getParameterTypes(); + boolean isConstructor = method.isConstructor(); + + for (int i = allMethods.size() - 1; i >= 0; i--) { + IMethod curr = (IMethod) allMethods.get(i); + if (JavaModelUtil.isSameMethodSignature(name, paramTypes, + isConstructor, curr)) { + return curr; } - return null; } + return null; + } - /** - * Creates needed constructors for a type. - * @param type The type to create constructors for - * @param supertype The type's super type - * @param settings Options for comment generation - * @param imports Required imports are added to the import structure. Structure can be null, types are qualified then. - * @return Returns the generated stubs or null if the creation has been canceled - */ -// public static String[] evalConstructors(IType type, IType supertype, IImportsStructure imports) throws CoreException { -// IMethod[] superMethods= supertype.getMethods(); -// String typeName= type.getElementName(); -// ICompilationUnit cu= type.getCompilationUnit(); -// IMethod[] methods= type.getMethods(); -// GenStubSettings genStubSettings= new GenStubSettings(settings); -// genStubSettings.callSuper= true; -// -// ArrayList newMethods= new ArrayList(superMethods.length); -// for (int i= 0; i < superMethods.length; i++) { -// IMethod curr= superMethods[i]; -// if (curr.isConstructor() && (JavaModelUtil.isVisibleInHierarchy(curr, type.getPackageFragment()))) { -// if (JavaModelUtil.findMethod(typeName, curr.getParameterTypes(), true, methods) == null) { -// genStubSettings.methodModifiers= Flags.AccPublic | JdtFlags.clearAccessModifiers(curr.getFlags()); -// String newStub= genStub(cu, typeName, curr, curr.getDeclaringType(), genStubSettings, imports); -// newMethods.add(newStub); -// } -// } -// } -// return (String[]) newMethods.toArray(new String[newMethods.size()]); -// } - - /** - * Returns all unimplemented constructors of a type including root type default - * constructors if there are no other superclass constructors unimplemented. - * @param type The type to create constructors for - * @return Returns the generated stubs or null if the creation has been canceled - */ -// public static IMethod[] getOverridableConstructors(IType type) throws CoreException { -// List constructorMethods= new ArrayList(); -// ITypeHierarchy hierarchy= type.newSupertypeHierarchy(null); -// IType supertype= hierarchy.getSuperclass(type); -// if (supertype == null) -// return (new IMethod[0]); -// -// IMethod[] superMethods= supertype.getMethods(); -// boolean constuctorFound= false; -// String typeName= type.getElementName(); -// IMethod[] methods= type.getMethods(); -// for (int i= 0; i < superMethods.length; i++) { -// IMethod curr= superMethods[i]; -// if (curr.isConstructor()) { -// constuctorFound= true; -// if (JavaModelUtil.isVisibleInHierarchy(curr, type.getPackageFragment())) -// if (JavaModelUtil.findMethod(typeName, curr.getParameterTypes(), true, methods) == null) -// constructorMethods.add(curr); -// -// } -// } -// -// // http://bugs.eclipse.org/bugs/show_bug.cgi?id=38487 -// if (!constuctorFound) { -// IType objectType= type.getJavaProject().findType("java.lang.Object"); //$NON-NLS-1$ -// IMethod curr= objectType.getMethod("Object", EMPTY); //$NON-NLS-1$ -// if (JavaModelUtil.findMethod(typeName, curr.getParameterTypes(), true, methods) == null) { -// constructorMethods.add(curr); -// } -// } -// return (IMethod[]) constructorMethods.toArray(new IMethod[constructorMethods.size()]); -// } - - /** - * Returns all overridable methods of a type - * @param type The type to search the overridable methods for - * @param hierarchy The type hierarchy of the type - * @param isSubType If set, the result can include methods of the passed type, if not only methods from super - * types are considered - * @return Returns the all methods that can be overridden - */ -// public static IMethod[] getOverridableMethods(IType type, ITypeHierarchy hierarchy, boolean isSubType) throws JavaModelException { -// List allMethods= new ArrayList(); -// -// IMethod[] typeMethods= type.getMethods(); -// for (int i= 0; i < typeMethods.length; i++) { -// IMethod curr= typeMethods[i]; -// if (!curr.isConstructor() && !Flags.isStatic(curr.getFlags()) && !Flags.isPrivate(curr.getFlags())) { -// allMethods.add(curr); -// } -// } -// -// IType[] superTypes= hierarchy.getAllSuperclasses(type); -// for (int i= 0; i < superTypes.length; i++) { -// IMethod[] methods= superTypes[i].getMethods(); -// for (int k= 0; k < methods.length; k++) { -// IMethod curr= methods[k]; -// if (!curr.isConstructor() && !Flags.isStatic(curr.getFlags()) && !Flags.isPrivate(curr.getFlags())) { -// if (findMethod(curr, allMethods) == null) { -// allMethods.add(curr); -// } -// } -// } -// } -// -// IType[] superInterfaces= hierarchy.getAllSuperInterfaces(type); -// for (int i= 0; i < superInterfaces.length; i++) { -// IMethod[] methods= superInterfaces[i].getMethods(); -// for (int k= 0; k < methods.length; k++) { -// IMethod curr= methods[k]; -// -// // binary interfaces can contain static initializers (variable intializations) -// // 1G4CKUS -// if (!Flags.isStatic(curr.getFlags())) { -// IMethod impl= findMethod(curr, allMethods); -// if (impl == null || !JavaModelUtil.isVisibleInHierarchy(impl, type.getPackageFragment()) || prefereInterfaceMethod(hierarchy, curr, impl)) { -// if (impl != null) { -// allMethods.remove(impl); -// } -// // implement an interface method when it does not exist in the hierarchy -// // or when it throws less exceptions that the implemented -// allMethods.add(curr); -// } -// } -// } -// } -// if (!isSubType) { -// allMethods.removeAll(Arrays.asList(typeMethods)); -// } -// // remove finals -// for (int i= allMethods.size() - 1; i >= 0; i--) { -// IMethod curr= (IMethod) allMethods.get(i); -// if (Flags.isFinal(curr.getFlags())) { -// allMethods.remove(i); -// } -// } -// return (IMethod[]) allMethods.toArray(new IMethod[allMethods.size()]); -// } - -// private static boolean prefereInterfaceMethod(ITypeHierarchy hierarchy, IMethod interfaceMethod, IMethod curr) throws JavaModelException { -// if (Flags.isFinal(curr.getFlags())) { -// return false; -// } -// IType interfaceType= interfaceMethod.getDeclaringType(); -// IType[] interfaces= hierarchy.getAllSuperInterfaces(curr.getDeclaringType()); -// for (int i= 0; i < interfaces.length; i++) { -// if (interfaces[i] == interfaceType) { -// return false; -// } -// } -// return curr.getExceptionTypes().length > interfaceMethod.getExceptionTypes().length; -// } - - /** - * Generate method stubs for methods to overrride - * @param type The type to search the overridable methods for - * @param hierarchy The type hierarchy of the type - * @param methodsToImplement Methods to override or implement - * @param settings Options for comment generation - * @param imports Required imports are added to the import structure. Structure can be null, types are qualified then. - * @return Returns the generated stubs - */ -// public static String[] genOverrideStubs(IMethod[] methodsToImplement, IType type, ITypeHierarchy hierarchy, CodeGenerationSettings settings, IImportsStructure imports) throws CoreException { -// GenStubSettings genStubSettings= new GenStubSettings(settings); -// genStubSettings.methodOverwrites= true; -// ICompilationUnit cu= type.getCompilationUnit(); -// String[] result= new String[methodsToImplement.length]; -// for (int i= 0; i < methodsToImplement.length; i++) { -// IMethod curr= methodsToImplement[i]; -// IMethod overrides= JavaModelUtil.findMethodImplementationInHierarchy(hierarchy, type, curr.getElementName(), curr.getParameterTypes(), curr.isConstructor()); -// if (overrides != null) { -// genStubSettings.callSuper= true; -// curr= overrides; -// } -// genStubSettings.methodModifiers= curr.getFlags(); -// IMethod desc= JavaModelUtil.findMethodDeclarationInHierarchy(hierarchy, type, curr.getElementName(), curr.getParameterTypes(), curr.isConstructor()); -// if (desc == null) { -// desc= curr; -// } -// result[i]= genStub(cu, type.getElementName(), curr, desc.getDeclaringType(), genStubSettings, imports); -// } -// return result; -// } - /** - * Searches for unimplemented methods of a type. - * @param isSubType If set, the evaluation is for a subtype of the given type. If not set, the - * evaluation is for the type itself. - * @param settings Options for comment generation - * @param imports Required imports are added to the import structure. Structure can be null, types are qualified then. - * @return Returns the generated stubs or null if the creation has been canceled - */ -// public static String[] evalUnimplementedMethods(IType type, ITypeHierarchy hierarchy, boolean isSubType, CodeGenerationSettings settings, -// IImportsStructure imports) throws CoreException { -// -// IMethod[] inheritedMethods= getOverridableMethods(type, hierarchy, isSubType); -// -// List toImplement= new ArrayList(); -// for (int i= 0; i < inheritedMethods.length; i++) { -// IMethod curr= inheritedMethods[i]; -// if (JdtFlags.isAbstract(curr)) { -// toImplement.add(curr); -// } -// } -// IMethod[] toImplementArray= (IMethod[]) toImplement.toArray(new IMethod[toImplement.size()]); -// return genOverrideStubs(toImplementArray, type, hierarchy, settings, imports); -// } - - /** - * Examines a string and returns the first line delimiter found. - */ - public static String getLineDelimiterUsed(IJavaElement elem) throws JavaModelException { - ICompilationUnit cu= (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT); - if (cu != null && cu.exists()) { - IBuffer buf= cu.getBuffer(); - int length= buf.getLength(); - for (int i= 0; i < length; i++) { - char ch= buf.getChar(i); - if (ch == SWT.CR) { - if (i + 1 < length) { - if (buf.getChar(i + 1) == SWT.LF) { - return "\r\n"; //$NON-NLS-1$ - } + /** + * Creates needed constructors for a type. + * + * @param type + * The type to create constructors for + * @param supertype + * The type's super type + * @param settings + * Options for comment generation + * @param imports + * Required imports are added to the import structure. Structure + * can be null, types are qualified then. + * @return Returns the generated stubs or null if the + * creation has been canceled + */ + // public static String[] evalConstructors(IType type, IType supertype, + // IImportsStructure imports) throws CoreException { + // IMethod[] superMethods= supertype.getMethods(); + // String typeName= type.getElementName(); + // ICompilationUnit cu= type.getCompilationUnit(); + // IMethod[] methods= type.getMethods(); + // GenStubSettings genStubSettings= new GenStubSettings(settings); + // genStubSettings.callSuper= true; + // + // ArrayList newMethods= new ArrayList(superMethods.length); + // for (int i= 0; i < superMethods.length; i++) { + // IMethod curr= superMethods[i]; + // if (curr.isConstructor() && (JavaModelUtil.isVisibleInHierarchy(curr, + // type.getPackageFragment()))) { + // if (JavaModelUtil.findMethod(typeName, curr.getParameterTypes(), true, + // methods) == null) { + // genStubSettings.methodModifiers= Flags.AccPublic | + // JdtFlags.clearAccessModifiers(curr.getFlags()); + // String newStub= genStub(cu, typeName, curr, curr.getDeclaringType(), + // genStubSettings, imports); + // newMethods.add(newStub); + // } + // } + // } + // return (String[]) newMethods.toArray(new String[newMethods.size()]); + // } + /** + * Returns all unimplemented constructors of a type including root type + * default constructors if there are no other superclass constructors + * unimplemented. + * + * @param type + * The type to create constructors for + * @return Returns the generated stubs or null if the + * creation has been canceled + */ + // public static IMethod[] getOverridableConstructors(IType type) throws + // CoreException { + // List constructorMethods= new ArrayList(); + // ITypeHierarchy hierarchy= type.newSupertypeHierarchy(null); + // IType supertype= hierarchy.getSuperclass(type); + // if (supertype == null) + // return (new IMethod[0]); + // + // IMethod[] superMethods= supertype.getMethods(); + // boolean constuctorFound= false; + // String typeName= type.getElementName(); + // IMethod[] methods= type.getMethods(); + // for (int i= 0; i < superMethods.length; i++) { + // IMethod curr= superMethods[i]; + // if (curr.isConstructor()) { + // constuctorFound= true; + // if (JavaModelUtil.isVisibleInHierarchy(curr, type.getPackageFragment())) + // if (JavaModelUtil.findMethod(typeName, curr.getParameterTypes(), true, + // methods) == null) + // constructorMethods.add(curr); + // + // } + // } + // + // // http://bugs.eclipse.org/bugs/show_bug.cgi?id=38487 + // if (!constuctorFound) { + // IType objectType= type.getJavaProject().findType("java.lang.Object"); + // //$NON-NLS-1$ + // IMethod curr= objectType.getMethod("Object", EMPTY); //$NON-NLS-1$ + // if (JavaModelUtil.findMethod(typeName, curr.getParameterTypes(), true, + // methods) == null) { + // constructorMethods.add(curr); + // } + // } + // return (IMethod[]) constructorMethods.toArray(new + // IMethod[constructorMethods.size()]); + // } + /** + * Returns all overridable methods of a type + * + * @param type + * The type to search the overridable methods for + * @param hierarchy + * The type hierarchy of the type + * @param isSubType + * If set, the result can include methods of the passed type, if + * not only methods from super types are considered + * @return Returns the all methods that can be overridden + */ + // public static IMethod[] getOverridableMethods(IType type, ITypeHierarchy + // hierarchy, boolean isSubType) throws JavaModelException { + // List allMethods= new ArrayList(); + // + // IMethod[] typeMethods= type.getMethods(); + // for (int i= 0; i < typeMethods.length; i++) { + // IMethod curr= typeMethods[i]; + // if (!curr.isConstructor() && !Flags.isStatic(curr.getFlags()) && + // !Flags.isPrivate(curr.getFlags())) { + // allMethods.add(curr); + // } + // } + // + // IType[] superTypes= hierarchy.getAllSuperclasses(type); + // for (int i= 0; i < superTypes.length; i++) { + // IMethod[] methods= superTypes[i].getMethods(); + // for (int k= 0; k < methods.length; k++) { + // IMethod curr= methods[k]; + // if (!curr.isConstructor() && !Flags.isStatic(curr.getFlags()) && + // !Flags.isPrivate(curr.getFlags())) { + // if (findMethod(curr, allMethods) == null) { + // allMethods.add(curr); + // } + // } + // } + // } + // + // IType[] superInterfaces= hierarchy.getAllSuperInterfaces(type); + // for (int i= 0; i < superInterfaces.length; i++) { + // IMethod[] methods= superInterfaces[i].getMethods(); + // for (int k= 0; k < methods.length; k++) { + // IMethod curr= methods[k]; + // + // // binary interfaces can contain static initializers (variable + // intializations) + // // 1G4CKUS + // if (!Flags.isStatic(curr.getFlags())) { + // IMethod impl= findMethod(curr, allMethods); + // if (impl == null || !JavaModelUtil.isVisibleInHierarchy(impl, + // type.getPackageFragment()) || prefereInterfaceMethod(hierarchy, curr, + // impl)) { + // if (impl != null) { + // allMethods.remove(impl); + // } + // // implement an interface method when it does not exist in the hierarchy + // // or when it throws less exceptions that the implemented + // allMethods.add(curr); + // } + // } + // } + // } + // if (!isSubType) { + // allMethods.removeAll(Arrays.asList(typeMethods)); + // } + // // remove finals + // for (int i= allMethods.size() - 1; i >= 0; i--) { + // IMethod curr= (IMethod) allMethods.get(i); + // if (Flags.isFinal(curr.getFlags())) { + // allMethods.remove(i); + // } + // } + // return (IMethod[]) allMethods.toArray(new IMethod[allMethods.size()]); + // } + // private static boolean prefereInterfaceMethod(ITypeHierarchy hierarchy, + // IMethod interfaceMethod, IMethod curr) throws JavaModelException { + // if (Flags.isFinal(curr.getFlags())) { + // return false; + // } + // IType interfaceType= interfaceMethod.getDeclaringType(); + // IType[] interfaces= + // hierarchy.getAllSuperInterfaces(curr.getDeclaringType()); + // for (int i= 0; i < interfaces.length; i++) { + // if (interfaces[i] == interfaceType) { + // return false; + // } + // } + // return curr.getExceptionTypes().length > + // interfaceMethod.getExceptionTypes().length; + // } + /** + * Generate method stubs for methods to overrride + * + * @param type + * The type to search the overridable methods for + * @param hierarchy + * The type hierarchy of the type + * @param methodsToImplement + * Methods to override or implement + * @param settings + * Options for comment generation + * @param imports + * Required imports are added to the import structure. Structure + * can be null, types are qualified then. + * @return Returns the generated stubs + */ + // public static String[] genOverrideStubs(IMethod[] methodsToImplement, + // IType type, ITypeHierarchy hierarchy, CodeGenerationSettings settings, + // IImportsStructure imports) throws CoreException { + // GenStubSettings genStubSettings= new GenStubSettings(settings); + // genStubSettings.methodOverwrites= true; + // ICompilationUnit cu= type.getCompilationUnit(); + // String[] result= new String[methodsToImplement.length]; + // for (int i= 0; i < methodsToImplement.length; i++) { + // IMethod curr= methodsToImplement[i]; + // IMethod overrides= + // JavaModelUtil.findMethodImplementationInHierarchy(hierarchy, type, + // curr.getElementName(), curr.getParameterTypes(), curr.isConstructor()); + // if (overrides != null) { + // genStubSettings.callSuper= true; + // curr= overrides; + // } + // genStubSettings.methodModifiers= curr.getFlags(); + // IMethod desc= JavaModelUtil.findMethodDeclarationInHierarchy(hierarchy, + // type, curr.getElementName(), curr.getParameterTypes(), + // curr.isConstructor()); + // if (desc == null) { + // desc= curr; + // } + // result[i]= genStub(cu, type.getElementName(), curr, + // desc.getDeclaringType(), genStubSettings, imports); + // } + // return result; + // } + /** + * Searches for unimplemented methods of a type. + * + * @param isSubType + * If set, the evaluation is for a subtype of the given type. If + * not set, the evaluation is for the type itself. + * @param settings + * Options for comment generation + * @param imports + * Required imports are added to the import structure. Structure + * can be null, types are qualified then. + * @return Returns the generated stubs or null if the + * creation has been canceled + */ + // public static String[] evalUnimplementedMethods(IType type, + // ITypeHierarchy hierarchy, boolean isSubType, CodeGenerationSettings + // settings, + // IImportsStructure imports) throws CoreException { + // + // IMethod[] inheritedMethods= getOverridableMethods(type, hierarchy, + // isSubType); + // + // List toImplement= new ArrayList(); + // for (int i= 0; i < inheritedMethods.length; i++) { + // IMethod curr= inheritedMethods[i]; + // if (JdtFlags.isAbstract(curr)) { + // toImplement.add(curr); + // } + // } + // IMethod[] toImplementArray= (IMethod[]) toImplement.toArray(new + // IMethod[toImplement.size()]); + // return genOverrideStubs(toImplementArray, type, hierarchy, settings, + // imports); + // } + /** + * Examines a string and returns the first line delimiter found. + */ + public static String getLineDelimiterUsed(IJavaElement elem) + throws JavaModelException { + ICompilationUnit cu = (ICompilationUnit) elem + .getAncestor(IJavaElement.COMPILATION_UNIT); + if (cu != null && cu.exists()) { + IBuffer buf = cu.getBuffer(); + int length = buf.getLength(); + for (int i = 0; i < length; i++) { + char ch = buf.getChar(i); + if (ch == SWT.CR) { + if (i + 1 < length) { + if (buf.getChar(i + 1) == SWT.LF) { + return "\r\n"; //$NON-NLS-1$ } - return "\r"; //$NON-NLS-1$ - } else if (ch == SWT.LF) { - return "\n"; //$NON-NLS-1$ } + return "\r"; //$NON-NLS-1$ + } else if (ch == SWT.LF) { + return "\n"; //$NON-NLS-1$ } } - return System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ } - + return System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ + } /** - * Embodies the policy which line delimiter to use when inserting into - * a document. - */ + * Embodies the policy which line delimiter to use when inserting into a + * document. + */ public static String getLineDelimiterFor(IDocument doc) { - // new for: 1GF5UU0: ITPJUI:WIN2000 - "Organize Imports" in php editor inserts lines in wrong format - String lineDelim= null; + // new for: 1GF5UU0: ITPJUI:WIN2000 - "Organize Imports" in php editor + // inserts lines in wrong format + String lineDelim = null; try { - lineDelim= doc.getLineDelimiter(0); + lineDelim = doc.getLineDelimiter(0); } catch (BadLocationException e) { } if (lineDelim == null) { - String systemDelimiter= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ - String[] lineDelims= doc.getLegalLineDelimiters(); - for (int i= 0; i < lineDelims.length; i++) { + String systemDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ + String[] lineDelims = doc.getLegalLineDelimiters(); + for (int i = 0; i < lineDelims.length; i++) { if (lineDelims[i].equals(systemDelimiter)) { - lineDelim= systemDelimiter; + lineDelim = systemDelimiter; break; } } if (lineDelim == null) { - lineDelim= lineDelims.length > 0 ? lineDelims[0] : systemDelimiter; + lineDelim = lineDelims.length > 0 ? lineDelims[0] + : systemDelimiter; } } return lineDelim; } - /** * Evaluates the indention used by a Java element. (in tabulators) - */ -// public static int getIndentUsed(IJavaElement elem) throws JavaModelException { -// if (elem instanceof ISourceReference) { -// ICompilationUnit cu= (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT); -// if (cu != null) { -// IBuffer buf= cu.getBuffer(); -// int offset= ((ISourceReference)elem).getSourceRange().getOffset(); -// int i= offset; -// // find beginning of line -// while (i > 0 && !Strings.isLineDelimiterChar(buf.getChar(i - 1)) ){ -// i--; -// } -// return Strings.computeIndent(buf.getText(i, offset - i), CodeFormatterUtil.getTabWidth()); -// } -// } -// return 0; -// } - - public static String codeFormat(String sourceString, int initialIndentationLevel, String lineDelim) { - ICodeFormatter formatter= ToolFactory.createDefaultCodeFormatter(null); - return formatter.format(sourceString, initialIndentationLevel, null, lineDelim); + */ + // public static int getIndentUsed(IJavaElement elem) throws + // JavaModelException { + // if (elem instanceof ISourceReference) { + // ICompilationUnit cu= (ICompilationUnit) + // elem.getAncestor(IJavaElement.COMPILATION_UNIT); + // if (cu != null) { + // IBuffer buf= cu.getBuffer(); + // int offset= ((ISourceReference)elem).getSourceRange().getOffset(); + // int i= offset; + // // find beginning of line + // while (i > 0 && !Strings.isLineDelimiterChar(buf.getChar(i - 1)) ){ + // i--; + // } + // return Strings.computeIndent(buf.getText(i, offset - i), + // CodeFormatterUtil.getTabWidth()); + // } + // } + // return 0; + // } + public static String codeFormat(String sourceString, + int initialIndentationLevel, String lineDelim) { + ICodeFormatter formatter = ToolFactory.createDefaultCodeFormatter(null); + return formatter.format(sourceString, initialIndentationLevel, null, + lineDelim); } - + /** * Returns the element after the give element. */ -// public static IJavaElement findNextSibling(IJavaElement member) throws JavaModelException { -// IJavaElement parent= member.getParent(); -// if (parent instanceof IParent) { -// IJavaElement[] elements= ((IParent)parent).getChildren(); -// for (int i= elements.length - 2; i >= 0 ; i--) { -// if (member.equals(elements[i])) { -// return elements[i+1]; -// } -// } -// } -// return null; -// } -// + // public static IJavaElement findNextSibling(IJavaElement member) throws + // JavaModelException { + // IJavaElement parent= member.getParent(); + // if (parent instanceof IParent) { + // IJavaElement[] elements= ((IParent)parent).getChildren(); + // for (int i= elements.length - 2; i >= 0 ; i--) { + // if (member.equals(elements[i])) { + // return elements[i+1]; + // } + // } + // } + // return null; + // } + // public static String getTodoTaskTag(IJavaProject project) { - String markers= null; + String markers = null; if (project == null) { - markers= JavaCore.getOption(JavaCore.COMPILER_TASK_TAGS); + markers = JavaCore.getOption(JavaCore.COMPILER_TASK_TAGS); } else { - markers= project.getOption(JavaCore.COMPILER_TASK_TAGS, true); + markers = project.getOption(JavaCore.COMPILER_TASK_TAGS, true); } - + if (markers != null && markers.length() > 0) { - int idx= markers.indexOf(','); + int idx = markers.indexOf(','); if (idx == -1) { return markers; } else { @@ -1072,27 +1307,33 @@ public class StubUtility { } return null; } + /* * Workarounds for bug 38111 */ -// public static String[] getArgumentNameSuggestions(IJavaProject project, String baseName, int dimensions, String[] excluded) { -// String name= workaround38111(baseName); -// String[] res= NamingConventions.suggestArgumentNames(project, "", name, dimensions, excluded); //$NON-NLS-1$ -// return sortByLength(res); // longest first -// } -// -// public static String[] getFieldNameSuggestions(IJavaProject project, String baseName, int dimensions, int modifiers, String[] excluded) { -// String name= workaround38111(baseName); -// String[] res= NamingConventions.suggestFieldNames(project, "", name, dimensions, modifiers, excluded); //$NON-NLS-1$ -// return sortByLength(res); // longest first -// } -// -// public static String[] getLocalNameSuggestions(IJavaProject project, String baseName, int dimensions, String[] excluded) { -// String name= workaround38111(baseName); -// String[] res= NamingConventions.suggestLocalVariableNames(project, "", name, dimensions, excluded); //$NON-NLS-1$ -// return sortByLength(res); // longest first -// } - + // public static String[] getArgumentNameSuggestions(IJavaProject project, + // String baseName, int dimensions, String[] excluded) { + // String name= workaround38111(baseName); + // String[] res= NamingConventions.suggestArgumentNames(project, "", name, + // dimensions, excluded); //$NON-NLS-1$ + // return sortByLength(res); // longest first + // } + // + // public static String[] getFieldNameSuggestions(IJavaProject project, + // String baseName, int dimensions, int modifiers, String[] excluded) { + // String name= workaround38111(baseName); + // String[] res= NamingConventions.suggestFieldNames(project, "", name, + // dimensions, modifiers, excluded); //$NON-NLS-1$ + // return sortByLength(res); // longest first + // } + // + // public static String[] getLocalNameSuggestions(IJavaProject project, + // String baseName, int dimensions, String[] excluded) { + // String name= workaround38111(baseName); + // String[] res= NamingConventions.suggestLocalVariableNames(project, "", + // name, dimensions, excluded); //$NON-NLS-1$ + // return sortByLength(res); // longest first + // } private static String[] sortByLength(String[] proposals) { Arrays.sort(proposals, new Comparator() { public int compare(Object o1, Object o2) { @@ -1101,86 +1342,100 @@ public class StubUtility { }); return proposals; } - + private static String workaround38111(String baseName) { if (BASE_TYPES.contains(baseName)) return baseName; - return Character.toUpperCase(baseName.charAt(0)) + baseName.substring(1); + return Character.toUpperCase(baseName.charAt(0)) + + baseName.substring(1); } - - private static final List BASE_TYPES= Arrays.asList( - new String[] {"boolean", "byte", "char", "double", "float", "int", "long", "short"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ - - public static String suggestArgumentName(IJavaProject project, String baseName, String[] excluded) { -// String[] argnames= getArgumentNameSuggestions(project, baseName, 0, excluded); -// if (argnames.length > 0) { -// return argnames[0]; -// } + + private static final List BASE_TYPES = Arrays + .asList(new String[] { + "boolean", "byte", "char", "double", "float", "int", "long", "short" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ + + public static String suggestArgumentName(IJavaProject project, + String baseName, String[] excluded) { + // String[] argnames= getArgumentNameSuggestions(project, baseName, 0, + // excluded); + // if (argnames.length > 0) { + // return argnames[0]; + // } return baseName; } - - public static String[] suggestArgumentNames(IJavaProject project, String[] paramNames) { - String prefixes= project.getOption(JavaCore.CODEASSIST_ARGUMENT_PREFIXES, true); - String suffixes= project.getOption(JavaCore.CODEASSIST_ARGUMENT_SUFFIXES, true); + + public static String[] suggestArgumentNames(IJavaProject project, + String[] paramNames) { + String prefixes = project.getOption( + JavaCore.CODEASSIST_ARGUMENT_PREFIXES, true); + String suffixes = project.getOption( + JavaCore.CODEASSIST_ARGUMENT_SUFFIXES, true); if (prefixes.length() + suffixes.length() == 0) { return paramNames; } - - String[] newNames= new String[paramNames.length]; + + String[] newNames = new String[paramNames.length]; // Ensure that the codegeneration preferences are respected - for (int i= 0; i < paramNames.length; i++) { - String curr= paramNames[i]; + for (int i = 0; i < paramNames.length; i++) { + String curr = paramNames[i]; if (!hasPrefixOrSuffix(prefixes, suffixes, curr)) { - newNames[i]= suggestArgumentName(project, paramNames[i], null); + newNames[i] = suggestArgumentName(project, paramNames[i], null); } else { - newNames[i]= curr; + newNames[i] = curr; } } return newNames; } - + public static boolean hasFieldName(IJavaProject project, String name) { - String prefixes= project.getOption(JavaCore.CODEASSIST_FIELD_PREFIXES, true); - String suffixes= project.getOption(JavaCore.CODEASSIST_FIELD_SUFFIXES, true); - String staticPrefixes= project.getOption(JavaCore.CODEASSIST_STATIC_FIELD_PREFIXES, true); - String staticSuffixes= project.getOption(JavaCore.CODEASSIST_STATIC_FIELD_SUFFIXES, true); - - - return hasPrefixOrSuffix(prefixes, suffixes, name) - || hasPrefixOrSuffix(staticPrefixes, staticSuffixes, name); + String prefixes = project.getOption(JavaCore.CODEASSIST_FIELD_PREFIXES, + true); + String suffixes = project.getOption(JavaCore.CODEASSIST_FIELD_SUFFIXES, + true); + String staticPrefixes = project.getOption( + JavaCore.CODEASSIST_STATIC_FIELD_PREFIXES, true); + String staticSuffixes = project.getOption( + JavaCore.CODEASSIST_STATIC_FIELD_SUFFIXES, true); + + return hasPrefixOrSuffix(prefixes, suffixes, name) + || hasPrefixOrSuffix(staticPrefixes, staticSuffixes, name); } - + public static boolean hasParameterName(IJavaProject project, String name) { - String prefixes= project.getOption(JavaCore.CODEASSIST_ARGUMENT_PREFIXES, true); - String suffixes= project.getOption(JavaCore.CODEASSIST_ARGUMENT_SUFFIXES, true); + String prefixes = project.getOption( + JavaCore.CODEASSIST_ARGUMENT_PREFIXES, true); + String suffixes = project.getOption( + JavaCore.CODEASSIST_ARGUMENT_SUFFIXES, true); return hasPrefixOrSuffix(prefixes, suffixes, name); } - + public static boolean hasLocalVariableName(IJavaProject project, String name) { - String prefixes= project.getOption(JavaCore.CODEASSIST_LOCAL_PREFIXES, true); - String suffixes= project.getOption(JavaCore.CODEASSIST_LOCAL_SUFFIXES, true); + String prefixes = project.getOption(JavaCore.CODEASSIST_LOCAL_PREFIXES, + true); + String suffixes = project.getOption(JavaCore.CODEASSIST_LOCAL_SUFFIXES, + true); return hasPrefixOrSuffix(prefixes, suffixes, name); } - + public static boolean hasConstantName(String name) { return Character.isUpperCase(name.charAt(0)); } - - - private static boolean hasPrefixOrSuffix(String prefixes, String suffixes, String name) { - final String listSeparartor= ","; //$NON-NLS-1$ - StringTokenizer tok= new StringTokenizer(prefixes, listSeparartor); + private static boolean hasPrefixOrSuffix(String prefixes, String suffixes, + String name) { + final String listSeparartor = ","; //$NON-NLS-1$ + + StringTokenizer tok = new StringTokenizer(prefixes, listSeparartor); while (tok.hasMoreTokens()) { - String curr= tok.nextToken(); + String curr = tok.nextToken(); if (name.startsWith(curr)) { return true; } } - tok= new StringTokenizer(suffixes, listSeparartor); + tok = new StringTokenizer(suffixes, listSeparartor); while (tok.hasMoreTokens()) { - String curr= tok.nextToken(); + String curr = tok.nextToken(); if (name.endsWith(curr)) { return true; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/phpdoc/PHPDocBufferCommentReader.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/phpdoc/PHPDocBufferCommentReader.java index 845ff0d..1e5ccc2 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/phpdoc/PHPDocBufferCommentReader.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/phpdoc/PHPDocBufferCommentReader.java @@ -13,29 +13,30 @@ package net.sourceforge.phpdt.internal.corext.phpdoc; import net.sourceforge.phpdt.core.IBuffer; import net.sourceforge.phpdt.internal.corext.util.Strings; - /** - * Reads a phpdoc comment from a phpdoc comment. Skips star-character - * on begin of line + * Reads a phpdoc comment from a phpdoc comment. Skips star-character on begin + * of line */ public class PHPDocBufferCommentReader extends SingleCharReader { private IBuffer fBuffer; - + private int fCurrPos; + private int fStartPos; + private int fEndPos; - + private boolean fWasNewLine; - + public PHPDocBufferCommentReader(IBuffer buf, int start, int end) { - fBuffer= buf; - fStartPos= start + 3; - fEndPos= end - 2; - + fBuffer = buf; + fStartPos = start + 3; + fEndPos = end - 2; + reset(); } - + /** * @see java.io.Reader#read() */ @@ -44,41 +45,40 @@ public class PHPDocBufferCommentReader extends SingleCharReader { char ch; if (fWasNewLine) { do { - ch= fBuffer.getChar(fCurrPos++); + ch = fBuffer.getChar(fCurrPos++); } while (fCurrPos < fEndPos && Character.isWhitespace(ch)); if (ch == '*') { if (fCurrPos < fEndPos) { do { - ch= fBuffer.getChar(fCurrPos++); + ch = fBuffer.getChar(fCurrPos++); } while (ch == '*'); } else { return -1; } } } else { - ch= fBuffer.getChar(fCurrPos++); + ch = fBuffer.getChar(fCurrPos++); } - fWasNewLine= Strings.isLineDelimiterChar(ch); - + fWasNewLine = Strings.isLineDelimiterChar(ch); + return ch; } return -1; } - + /** * @see java.io.Reader#close() - */ + */ public void close() { - fBuffer= null; + fBuffer = null; } - + /** * @see java.io.Reader#reset() - */ + */ public void reset() { - fCurrPos= fStartPos; - fWasNewLine= true; - } - - + fCurrPos = fStartPos; + fWasNewLine = true; + } + } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/phpdoc/PHPDocCharArrayCommentReader.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/phpdoc/PHPDocCharArrayCommentReader.java index 5a06b54..193e967 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/phpdoc/PHPDocCharArrayCommentReader.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/phpdoc/PHPDocCharArrayCommentReader.java @@ -13,72 +13,75 @@ package net.sourceforge.phpdt.internal.corext.phpdoc; import net.sourceforge.phpdt.internal.corext.util.Strings; /** - * Reads a phpdoc comment from a phpdoc comment. Skips star-character - * on begin of line + * Reads a phpdoc comment from a phpdoc comment. Skips star-character on begin + * of line */ public class PHPDocCharArrayCommentReader extends SingleCharReader { - private char[] fCharArray; - private int fCurrPos; - private int fStartPos; - private int fEndPos; + private char[] fCharArray; - private boolean fWasNewLine; + private int fCurrPos; + + private int fStartPos; + + private int fEndPos; + + private boolean fWasNewLine; public PHPDocCharArrayCommentReader(char[] buf) { this(buf, 0, buf.length); } - - public PHPDocCharArrayCommentReader(char[] buf, int start, int end) { - fCharArray = buf; - fStartPos= start + 3; - fEndPos= end - 2; - reset(); - } + public PHPDocCharArrayCommentReader(char[] buf, int start, int end) { + fCharArray = buf; + fStartPos = start + 3; + fEndPos = end - 2; + + reset(); + } - /** - * @see java.io.Reader#read() - */ - public int read() { - if (fCurrPos < fEndPos) { - char ch; - if (fWasNewLine) { - do { - ch = fCharArray[fCurrPos++]; - } while (fCurrPos < fEndPos &&Character.isWhitespace(ch)); - if (ch == '*') { - if (fCurrPos < fEndPos) { - do { - ch = fCharArray[fCurrPos++]; - } while (ch == '*'); - } else { - return -1; - } - } - } else { - ch = fCharArray[fCurrPos++]; - } - fWasNewLine = Strings.isLineDelimiterChar(ch); + /** + * @see java.io.Reader#read() + */ + public int read() { + if (fCurrPos < fEndPos) { + char ch; + if (fWasNewLine) { + do { + ch = fCharArray[fCurrPos++]; + } while (fCurrPos < fEndPos && Character.isWhitespace(ch)); + if (ch == '*') { + if (fCurrPos < fEndPos) { + do { + ch = fCharArray[fCurrPos++]; + } while (ch == '*'); + } else { + return -1; + } + } + } else { + ch = fCharArray[fCurrPos++]; + } + fWasNewLine = Strings.isLineDelimiterChar(ch); - return ch; - } - return -1; - } + return ch; + } + return -1; + } - /** - * @see java.io.Reader#close() - */ - public void close() { - fCharArray = null; - } + /** + * @see java.io.Reader#close() + */ + public void close() { + fCharArray = null; + } - /** - * @see java.io.Reader#reset() - */ - public void reset() { - fCurrPos = fStartPos; - fWasNewLine = true; - } + /** + * @see java.io.Reader#reset() + */ + public void reset() { + fCurrPos = fStartPos; + fWasNewLine = true; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/phpdoc/PHPDocUtil.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/phpdoc/PHPDocUtil.java index 1ef819f..0d477e1 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/phpdoc/PHPDocUtil.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/phpdoc/PHPDocUtil.java @@ -10,75 +10,84 @@ import net.sourceforge.phpeclipse.builder.PHPIdentifierLocation; */ public class PHPDocUtil { - /** - * Generate a PHPDoc hover text if possible - * - * @param hoverInfoBuffer - * @param filename - * @param location - */ - public static void appendPHPDoc(StringBuffer hoverInfoBuffer, String filename, PHPIdentifierLocation location) { - FileReader phpFileReader; - hoverInfoBuffer.append(location.toString()); - hoverInfoBuffer.append(" - "); - try { - hoverInfoBuffer.append( getUsage(filename, location) ); + /** + * Generate a PHPDoc hover text if possible + * + * @param hoverInfoBuffer + * @param filename + * @param location + */ + public static void appendPHPDoc(StringBuffer hoverInfoBuffer, + String filename, PHPIdentifierLocation location) { + FileReader phpFileReader; + hoverInfoBuffer.append(location.toString()); + hoverInfoBuffer.append(" - "); + try { + hoverInfoBuffer.append(getUsage(filename, location)); hoverInfoBuffer.append("
                                                      "); - // read the phpdoc for the function - if (location.getPHPDocOffset() >= 0) { - phpFileReader = new FileReader(filename); - char[] phpDocDeclarationCharArray = new char[location.getPHPDocLength()]; - phpFileReader.skip(location.getPHPDocOffset()); - phpFileReader.read(phpDocDeclarationCharArray, 0, location.getPHPDocLength()); - PHPDocCharArrayCommentReader phpdocConverter = new PHPDocCharArrayCommentReader(phpDocDeclarationCharArray); - hoverInfoBuffer.append(phpdocConverter.getString()); -// hoverInfoBuffer.append("

                                                      "); - phpFileReader.close(); - } + // read the phpdoc for the function + if (location.getPHPDocOffset() >= 0) { + phpFileReader = new FileReader(filename); + char[] phpDocDeclarationCharArray = new char[location + .getPHPDocLength()]; + phpFileReader.skip(location.getPHPDocOffset()); + phpFileReader.read(phpDocDeclarationCharArray, 0, location + .getPHPDocLength()); + PHPDocCharArrayCommentReader phpdocConverter = new PHPDocCharArrayCommentReader( + phpDocDeclarationCharArray); + hoverInfoBuffer.append(phpdocConverter.getString()); + // hoverInfoBuffer.append("

                                                      "); + phpFileReader.close(); + } - } catch (IOException e) { - return; - } - } + } catch (IOException e) { + return; + } + } - public static String getUsage(String filename, PHPIdentifierLocation location) { - FileReader phpFileReader; - String usage = location.getUsage(); - if (usage!=null) { - return usage; - } - usage = ""; - try { - - phpFileReader = new FileReader(filename); - // read the function declaration - if (location.getOffset() >= 0 && (location.isMethod() || location.isConstructor() || location.isFunction() || location.isDefine())) { - char[] functionDeclarationCharArray = new char[256]; - int offset = location.getOffset(); - phpFileReader.skip(offset); - int length = phpFileReader.read(functionDeclarationCharArray, 0, 256); - if (length == -1) { - length = 256; - } - for (int i = 0; i < length; i++) { - if (functionDeclarationCharArray[i] == ')') { - length = i + 1; - break; - } - if (functionDeclarationCharArray[i] == '{' || functionDeclarationCharArray[i] == '}') { - length = i; - break; - } - } + public static String getUsage(String filename, + PHPIdentifierLocation location) { + FileReader phpFileReader; + String usage = location.getUsage(); + if (usage != null) { + return usage; + } + usage = ""; + try { + + phpFileReader = new FileReader(filename); + // read the function declaration + if (location.getOffset() >= 0 + && (location.isMethod() || location.isConstructor() + || location.isFunction() || location.isDefine())) { + char[] functionDeclarationCharArray = new char[256]; + int offset = location.getOffset(); + phpFileReader.skip(offset); + int length = phpFileReader.read(functionDeclarationCharArray, + 0, 256); + if (length == -1) { + length = 256; + } + for (int i = 0; i < length; i++) { + if (functionDeclarationCharArray[i] == ')') { + length = i + 1; + break; + } + if (functionDeclarationCharArray[i] == '{' + || functionDeclarationCharArray[i] == '}') { + length = i; + break; + } + } usage = new String(functionDeclarationCharArray, 0, length); - } - phpFileReader.close(); - } catch (IOException e) { - // do nothing - } - // cache the usage string: + } + phpFileReader.close(); + } catch (IOException e) { + // do nothing + } + // cache the usage string: location.setUsage(usage); - return usage; - } + return usage; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/phpdoc/SingleCharReader.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/phpdoc/SingleCharReader.java index 6bd996e..858cc75 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/phpdoc/SingleCharReader.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/phpdoc/SingleCharReader.java @@ -10,12 +10,11 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.corext.phpdoc; - import java.io.IOException; import java.io.Reader; public abstract class SingleCharReader extends Reader { - + /** * @see Reader#read() */ @@ -25,9 +24,9 @@ public abstract class SingleCharReader extends Reader { * @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(); + int end = off + len; + for (int i = off; i < end; i++) { + int ch = read(); if (ch == -1) { if (i == off) { return -1; @@ -35,30 +34,30 @@ public abstract class SingleCharReader extends Reader { return i - off; } } - cbuf[i]= (char)ch; + cbuf[i] = (char) ch; } return len; - } - + } + /** * @see Reader#ready() - */ - public boolean ready() throws IOException { + */ + public boolean ready() throws IOException { return true; } - + /** * Gets the content as a String */ public String getString() throws IOException { - StringBuffer buf= new StringBuffer(); + StringBuffer buf = new StringBuffer(); int ch; - while ((ch= read()) != -1) { - if (ch=='\n'||ch=='\r') { - buf.append("
                                                      "); - } else { - buf.append((char)ch); - } + while ((ch = read()) != -1) { + if (ch == '\n' || ch == '\r') { + buf.append("
                                                      "); + } else { + buf.append((char) ch); + } } return buf.toString(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/refactoring/util/ResourceUtil.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/refactoring/util/ResourceUtil.java index fec6cc2..2983884 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/refactoring/util/ResourceUtil.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/refactoring/util/ResourceUtil.java @@ -23,14 +23,14 @@ import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; public class ResourceUtil { - - private ResourceUtil(){ + + private ResourceUtil() { } - + public static IFile[] getFiles(ICompilationUnit[] cus) { - List files= new ArrayList(cus.length); - for (int i= 0; i < cus.length; i++) { - IResource resource= ResourceUtil.getResource(cus[i]); + List files = new ArrayList(cus.length); + for (int i = 0; i < cus.length; i++) { + IResource resource = ResourceUtil.getResource(cus[i]); if (resource != null && resource.getType() == IResource.FILE) files.add(resource); } @@ -38,27 +38,28 @@ public class ResourceUtil { } public static IFile getFile(ICompilationUnit cu) { - IResource resource= ResourceUtil.getResource(cu); + IResource resource = ResourceUtil.getResource(cu); if (resource != null && resource.getType() == IResource.FILE) - return (IFile)resource; + return (IFile) resource; else return null; } - //----- other ------------------------------ - + // ----- other ------------------------------ + /** - * Finds an IResource for a given ICompilationUnit. - * If the parameter is a working copy then the IResource for - * the original element is returned. + * Finds an IResource for a given + * ICompilationUnit. If the parameter is a working copy then + * the IResource for the original element is returned. */ public static IResource getResource(ICompilationUnit cu) { return cu.getResource(); } - /** - * Returns the IResource that the given IMember is defined in. + * Returns the IResource that the given IMember + * is defined in. + * * @see #getResource */ public static IResource getResource(IMember member) { @@ -66,20 +67,20 @@ public class ResourceUtil { return getResource(member.getCompilationUnit()); } - public static IResource getResource(Object o){ + public static IResource getResource(Object o) { if (o instanceof IResource) - return (IResource)o; + return (IResource) o; if (o instanceof IJavaElement) - return getResource((IJavaElement)o); - return null; + return getResource((IJavaElement) o); + return null; } - private static IResource getResource(IJavaElement element){ - if (element.getElementType() == IJavaElement.COMPILATION_UNIT) + private static IResource getResource(IJavaElement element) { + if (element.getElementType() == IJavaElement.COMPILATION_UNIT) return getResource((ICompilationUnit) element); - else if (element instanceof IOpenable) + else if (element instanceof IOpenable) return element.getResource(); - else - return null; + else + return null; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/TemplateMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/TemplateMessages.java index 032c5ce..36af986 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/TemplateMessages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/TemplateMessages.java @@ -16,8 +16,11 @@ import java.util.ResourceBundle; public class TemplateMessages { - private static final String RESOURCE_BUNDLE= TemplateMessages.class.getName(); - private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); + private static final String RESOURCE_BUNDLE = TemplateMessages.class + .getName(); + + private static ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); private TemplateMessages() { } @@ -29,20 +32,20 @@ public class TemplateMessages { return '!' + key + '!'; } } - + /** * Gets a string from the resource bundle and formats it with the argument * - * @param key the string used to get the bundle value, must not be null + * @param key + * the string used to get the bundle value, must not be null */ public static String getFormattedString(String key, Object arg) { return MessageFormat.format(getString(key), new Object[] { arg }); } - /** * Gets a string from the resource bundle and formats it with arguments - */ + */ public static String getFormattedString(String key, Object[] args) { return MessageFormat.format(getString(key), args); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContext.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContext.java index 196da16..07b4032 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContext.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContext.java @@ -30,12 +30,15 @@ import org.eclipse.jface.text.templates.TemplateVariableResolver; public class CodeTemplateContext extends TemplateContext { private String fLineDelimiter; + private IJavaProject fProject; - public CodeTemplateContext(String contextTypeName, IJavaProject project, String lineDelim) { - super(PHPeclipsePlugin.getDefault().getCodeTemplateContextRegistry().getContextType(contextTypeName)); - fLineDelimiter= lineDelim; - fProject= project; + public CodeTemplateContext(String contextTypeName, IJavaProject project, + String lineDelim) { + super(PHPeclipsePlugin.getDefault().getCodeTemplateContextRegistry() + .getContextType(contextTypeName)); + fLineDelimiter = lineDelim; + fProject = project; } public IJavaProject getJavaProject() { @@ -45,23 +48,27 @@ public class CodeTemplateContext extends TemplateContext { /* * @see net.sourceforge.phpdt.internal.corext.template.TemplateContext#evaluate(net.sourceforge.phpdt.internal.corext.template.Template) */ - public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException { + public TemplateBuffer evaluate(Template template) + throws BadLocationException, TemplateException { // test that all variables are defined - Iterator iterator= getContextType().resolvers(); + Iterator iterator = getContextType().resolvers(); while (iterator.hasNext()) { - TemplateVariableResolver var= (TemplateVariableResolver) iterator.next(); + TemplateVariableResolver var = (TemplateVariableResolver) iterator + .next(); if (var instanceof CodeTemplateContextType.CodeTemplateVariableResolver) { - // Assert.isNotNull(getVariable(var.getType()), "Variable " + var.getType() + "not defined"); //$NON-NLS-1$ //$NON-NLS-2$ + // Assert.isNotNull(getVariable(var.getType()), "Variable " + + // var.getType() + "not defined"); //$NON-NLS-1$ //$NON-NLS-2$ } } if (!canEvaluate(template)) return null; - String pattern= changeLineDelimiter(template.getPattern(), fLineDelimiter); + String pattern = changeLineDelimiter(template.getPattern(), + fLineDelimiter); - TemplateTranslator translator= new TemplateTranslator(); - TemplateBuffer buffer= translator.translate(pattern); + TemplateTranslator translator = new TemplateTranslator(); + TemplateBuffer buffer = translator.translate(pattern); getContextType().resolve(buffer, this); return buffer; @@ -69,20 +76,22 @@ public class CodeTemplateContext extends TemplateContext { private static String changeLineDelimiter(String code, String lineDelim) { try { - ILineTracker tracker= new DefaultLineTracker(); + ILineTracker tracker = new DefaultLineTracker(); tracker.set(code); - int nLines= tracker.getNumberOfLines(); + int nLines = tracker.getNumberOfLines(); if (nLines == 1) { return code; } - StringBuffer buf= new StringBuffer(); - for (int i= 0; i < nLines; i++) { + StringBuffer buf = new StringBuffer(); + for (int i = 0; i < nLines; i++) { if (i != 0) { buf.append(lineDelim); } IRegion region = tracker.getLineInformation(i); - String line= code.substring(region.getOffset(), region.getOffset() + region.getLength()); + String line = code.substring(region.getOffset(), region + .getOffset() + + region.getLength()); buf.append(line); } return buf.toString(); @@ -92,7 +101,9 @@ public class CodeTemplateContext extends TemplateContext { } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpdt.internal.corext.template.TemplateContext#canEvaluate(net.sourceforge.phpdt.internal.corext.template.Template) */ public boolean canEvaluate(Template template) { @@ -101,8 +112,10 @@ public class CodeTemplateContext extends TemplateContext { public void setCompilationUnitVariables(ICompilationUnit cu) { setVariable(CodeTemplateContextType.FILENAME, cu.getElementName()); - setVariable(CodeTemplateContextType.PACKAGENAME, cu.getParent().getElementName()); - setVariable(CodeTemplateContextType.PROJECTNAME, cu.getJavaProject().getElementName()); + setVariable(CodeTemplateContextType.PACKAGENAME, cu.getParent() + .getElementName()); + setVariable(CodeTemplateContextType.PROJECTNAME, cu.getJavaProject() + .getElementName()); } public void setFileNameVariable(String filename, String projectname) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContextType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContextType.java index cc9be0e..94dd363 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContextType.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContextType.java @@ -27,119 +27,166 @@ import org.eclipse.jface.text.templates.TemplateVariable; import org.eclipse.jface.text.templates.TemplateVariableResolver; /** - */ + */ public class CodeTemplateContextType extends TemplateContextType { - + /* context types */ - public static final String CATCHBLOCK_CONTEXTTYPE= "php_catchblock_context"; //$NON-NLS-1$ - public static final String METHODBODY_CONTEXTTYPE= "php_methodbody_context"; //$NON-NLS-1$ - public static final String CONSTRUCTORBODY_CONTEXTTYPE= "php_constructorbody_context"; //$NON-NLS-1$ - public static final String GETTERBODY_CONTEXTTYPE= "php_getterbody_context"; //$NON-NLS-1$ - public static final String SETTERBODY_CONTEXTTYPE= "php_setterbody_context"; //$NON-NLS-1$ - public static final String NEWTYPE_CONTEXTTYPE= "php_newtype_context"; //$NON-NLS-1$ - public static final String NEWHTML_CONTEXTTYPE= "php_newhtml_context"; //$NON-NLS-1$ - public static final String TYPECOMMENT_CONTEXTTYPE= "php_typecomment_context"; //$NON-NLS-1$ - public static final String FIELDCOMMENT_CONTEXTTYPE= "php_fieldcomment_context"; //$NON-NLS-1$ - public static final String METHODCOMMENT_CONTEXTTYPE= "php_methodcomment_context"; //$NON-NLS-1$ - public static final String CONSTRUCTORCOMMENT_CONTEXTTYPE= "php_constructorcomment_context"; //$NON-NLS-1$ - public static final String OVERRIDECOMMENT_CONTEXTTYPE= "php_overridecomment_context"; //$NON-NLS-1$ - public static final String GETTERCOMMENT_CONTEXTTYPE= "php_gettercomment_context"; //$NON-NLS-1$ - public static final String SETTERCOMMENT_CONTEXTTYPE= "php_settercomment_context"; //$NON-NLS-1$ + public static final String CATCHBLOCK_CONTEXTTYPE = "php_catchblock_context"; //$NON-NLS-1$ + + public static final String METHODBODY_CONTEXTTYPE = "php_methodbody_context"; //$NON-NLS-1$ + + public static final String CONSTRUCTORBODY_CONTEXTTYPE = "php_constructorbody_context"; //$NON-NLS-1$ + + public static final String GETTERBODY_CONTEXTTYPE = "php_getterbody_context"; //$NON-NLS-1$ + + public static final String SETTERBODY_CONTEXTTYPE = "php_setterbody_context"; //$NON-NLS-1$ + + public static final String NEWTYPE_CONTEXTTYPE = "php_newtype_context"; //$NON-NLS-1$ + + public static final String NEWHTML_CONTEXTTYPE = "php_newhtml_context"; //$NON-NLS-1$ + + public static final String TYPECOMMENT_CONTEXTTYPE = "php_typecomment_context"; //$NON-NLS-1$ + + public static final String FIELDCOMMENT_CONTEXTTYPE = "php_fieldcomment_context"; //$NON-NLS-1$ + + public static final String METHODCOMMENT_CONTEXTTYPE = "php_methodcomment_context"; //$NON-NLS-1$ + + public static final String CONSTRUCTORCOMMENT_CONTEXTTYPE = "php_constructorcomment_context"; //$NON-NLS-1$ + + public static final String OVERRIDECOMMENT_CONTEXTTYPE = "php_overridecomment_context"; //$NON-NLS-1$ + + public static final String GETTERCOMMENT_CONTEXTTYPE = "php_gettercomment_context"; //$NON-NLS-1$ + + public static final String SETTERCOMMENT_CONTEXTTYPE = "php_settercomment_context"; //$NON-NLS-1$ /* templates */ - public static final String COMMENT_SUFFIX= "comment"; //$NON-NLS-1$ - public static final String CATCHBLOCK= "catchblock"; //$NON-NLS-1$ - public static final String METHODSTUB= "methodbody"; //$NON-NLS-1$ - public static final String NEWTYPE= "newtype"; //$NON-NLS-1$ - public static final String NEWHTML= "newhtml"; //$NON-NLS-1$ - public static final String CONSTRUCTORSTUB= "constructorbody"; //$NON-NLS-1$ - public static final String GETTERSTUB= "getterbody"; //$NON-NLS-1$ - public static final String SETTERSTUB= "setterbody"; //$NON-NLS-1$ - public static final String TYPECOMMENT= "type" + COMMENT_SUFFIX; //$NON-NLS-1$ - public static final String FIELDCOMMENT= "field" + COMMENT_SUFFIX; //$NON-NLS-1$ - public static final String METHODCOMMENT= "method" + COMMENT_SUFFIX; //$NON-NLS-1$ - public static final String CONSTRUCTORCOMMENT= "constructor" + COMMENT_SUFFIX; //$NON-NLS-1$ - public static final String OVERRIDECOMMENT= "override" + COMMENT_SUFFIX; //$NON-NLS-1$ - public static final String GETTERCOMMENT= "getter" + COMMENT_SUFFIX; //$NON-NLS-1$ - public static final String SETTERCOMMENT= "setter" + COMMENT_SUFFIX; //$NON-NLS-1$ - + public static final String COMMENT_SUFFIX = "comment"; //$NON-NLS-1$ + + public static final String CATCHBLOCK = "catchblock"; //$NON-NLS-1$ + + public static final String METHODSTUB = "methodbody"; //$NON-NLS-1$ + + public static final String NEWTYPE = "newtype"; //$NON-NLS-1$ + + public static final String NEWHTML = "newhtml"; //$NON-NLS-1$ + + public static final String CONSTRUCTORSTUB = "constructorbody"; //$NON-NLS-1$ + + public static final String GETTERSTUB = "getterbody"; //$NON-NLS-1$ + + public static final String SETTERSTUB = "setterbody"; //$NON-NLS-1$ + + public static final String TYPECOMMENT = "type" + COMMENT_SUFFIX; //$NON-NLS-1$ + + public static final String FIELDCOMMENT = "field" + COMMENT_SUFFIX; //$NON-NLS-1$ + + public static final String METHODCOMMENT = "method" + COMMENT_SUFFIX; //$NON-NLS-1$ + + public static final String CONSTRUCTORCOMMENT = "constructor" + COMMENT_SUFFIX; //$NON-NLS-1$ + + public static final String OVERRIDECOMMENT = "override" + COMMENT_SUFFIX; //$NON-NLS-1$ + + public static final String GETTERCOMMENT = "getter" + COMMENT_SUFFIX; //$NON-NLS-1$ + + public static final String SETTERCOMMENT = "setter" + COMMENT_SUFFIX; //$NON-NLS-1$ + /* resolver types */ - public static final String EXCEPTION_TYPE= "exception_type"; //$NON-NLS-1$ - public static final String EXCEPTION_VAR= "exception_var"; //$NON-NLS-1$ - public static final String ENCLOSING_METHOD= "enclosing_method"; //$NON-NLS-1$ - public static final String ENCLOSING_TYPE= "enclosing_type"; //$NON-NLS-1$ - public static final String BODY_STATEMENT= "body_statement"; //$NON-NLS-1$ - public static final String FIELD= "field"; //$NON-NLS-1$ - public static final String FIELD_TYPE= "field_type"; //$NON-NLS-1$ - public static final String BARE_FIELD_NAME= "bare_field_name"; //$NON-NLS-1$ - - public static final String PARAM= "param"; //$NON-NLS-1$ - public static final String RETURN_TYPE= "return_type"; //$NON-NLS-1$ - public static final String SEE_TAG= "see_to_overridden"; //$NON-NLS-1$ - - public static final String TAGS= "tags"; //$NON-NLS-1$ - - public static final String TYPENAME= "type_name"; //$NON-NLS-1$ - public static final String FILENAME= "file_name"; //$NON-NLS-1$ - public static final String PACKAGENAME= "package_name"; //$NON-NLS-1$ - public static final String PROJECTNAME= "project_name"; //$NON-NLS-1$ - - public static final String PACKAGE_DECLARATION= "package_declaration"; //$NON-NLS-1$ - public static final String TYPE_DECLARATION= "type_declaration"; //$NON-NLS-1$ - public static final String TYPE_COMMENT= "typecomment"; //$NON-NLS-1$ - - + public static final String EXCEPTION_TYPE = "exception_type"; //$NON-NLS-1$ + + public static final String EXCEPTION_VAR = "exception_var"; //$NON-NLS-1$ + + public static final String ENCLOSING_METHOD = "enclosing_method"; //$NON-NLS-1$ + + public static final String ENCLOSING_TYPE = "enclosing_type"; //$NON-NLS-1$ + + public static final String BODY_STATEMENT = "body_statement"; //$NON-NLS-1$ + + public static final String FIELD = "field"; //$NON-NLS-1$ + + public static final String FIELD_TYPE = "field_type"; //$NON-NLS-1$ + + public static final String BARE_FIELD_NAME = "bare_field_name"; //$NON-NLS-1$ + + public static final String PARAM = "param"; //$NON-NLS-1$ + + public static final String RETURN_TYPE = "return_type"; //$NON-NLS-1$ + + public static final String SEE_TAG = "see_to_overridden"; //$NON-NLS-1$ + + public static final String TAGS = "tags"; //$NON-NLS-1$ + + public static final String TYPENAME = "type_name"; //$NON-NLS-1$ + + public static final String FILENAME = "file_name"; //$NON-NLS-1$ + + public static final String PACKAGENAME = "package_name"; //$NON-NLS-1$ + + public static final String PROJECTNAME = "project_name"; //$NON-NLS-1$ + + public static final String PACKAGE_DECLARATION = "package_declaration"; //$NON-NLS-1$ + + public static final String TYPE_DECLARATION = "type_declaration"; //$NON-NLS-1$ + + public static final String TYPE_COMMENT = "typecomment"; //$NON-NLS-1$ + /** * Resolver that resolves to the variable defined in the context. */ - public static class CodeTemplateVariableResolver extends TemplateVariableResolver { + public static class CodeTemplateVariableResolver extends + TemplateVariableResolver { public CodeTemplateVariableResolver(String type, String description) { super(type, description); } - + protected String resolve(TemplateContext context) { return context.getVariable(getType()); } } - + /** * Resolver for javadoc tags. */ public static class TagsVariableResolver extends TemplateVariableResolver { public TagsVariableResolver() { - super(TAGS, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.tags")); //$NON-NLS-1$ + super( + TAGS, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.tags")); //$NON-NLS-1$ } - + protected String resolve(TemplateContext context) { return "@"; //$NON-NLS-1$ } - } - + } + /** * Resolver for todo tags. */ protected static class Todo extends TemplateVariableResolver { public Todo() { - super("todo", JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.todo")); //$NON-NLS-1$ //$NON-NLS-2$ + super( + "todo", JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.todo")); //$NON-NLS-1$ //$NON-NLS-2$ } - + protected String resolve(TemplateContext context) { - String todoTaskTag= StubUtility.getTodoTaskTag(((CodeTemplateContext) context).getJavaProject()); + String todoTaskTag = StubUtility + .getTodoTaskTag(((CodeTemplateContext) context) + .getJavaProject()); if (todoTaskTag == null) return "XXX"; //$NON-NLS-1$ - + return todoTaskTag; } } - + private boolean fIsComment; - + public CodeTemplateContextType(String contextName) { super(contextName); - - fIsComment= false; - + + fIsComment = false; + // global addResolver(new GlobalTemplateVariables.Dollar()); addResolver(new GlobalTemplateVariables.Date()); @@ -147,121 +194,269 @@ public class CodeTemplateContextType extends TemplateContextType { addResolver(new GlobalTemplateVariables.Time()); addResolver(new GlobalTemplateVariables.User()); addResolver(new Todo()); - + if (CATCHBLOCK_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver(EXCEPTION_TYPE, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.exceptiontype"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(EXCEPTION_VAR, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.exceptionvar"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + EXCEPTION_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.exceptiontype"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + EXCEPTION_VAR, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.exceptionvar"))); //$NON-NLS-1$ } else if (METHODBODY_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver(ENCLOSING_TYPE, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(ENCLOSING_METHOD, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(BODY_STATEMENT, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.bodystatement"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_METHOD, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + BODY_STATEMENT, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.bodystatement"))); //$NON-NLS-1$ } else if (CONSTRUCTORBODY_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver(ENCLOSING_TYPE, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(BODY_STATEMENT, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.bodystatement"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + BODY_STATEMENT, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.bodystatement"))); //$NON-NLS-1$ } else if (GETTERBODY_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver(ENCLOSING_TYPE, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(ENCLOSING_METHOD, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(FIELD, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.getterfieldname"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_METHOD, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + FIELD, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.getterfieldname"))); //$NON-NLS-1$ } else if (SETTERBODY_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver(ENCLOSING_TYPE, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(ENCLOSING_METHOD, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(FIELD, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.getterfieldname"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(PARAM, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.param"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_METHOD, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + FIELD, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.getterfieldname"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + PARAM, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.param"))); //$NON-NLS-1$ } else if (NEWTYPE_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver(TYPENAME, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.typename"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(PACKAGE_DECLARATION, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.packdeclaration"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(TYPE_DECLARATION, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.typedeclaration"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(TYPE_COMMENT, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.typecomment"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + TYPENAME, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.typename"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + PACKAGE_DECLARATION, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.packdeclaration"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + TYPE_DECLARATION, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.typedeclaration"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + TYPE_COMMENT, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.typecomment"))); //$NON-NLS-1$ addCompilationUnitVariables(); } else if (NEWHTML_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver(TYPENAME, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.typename"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(PACKAGE_DECLARATION, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.packdeclaration"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(TYPE_DECLARATION, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.typedeclaration"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(TYPE_COMMENT, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.typecomment"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + TYPENAME, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.typename"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + PACKAGE_DECLARATION, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.packdeclaration"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + TYPE_DECLARATION, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.typedeclaration"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + TYPE_COMMENT, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.typecomment"))); //$NON-NLS-1$ addCompilationUnitVariables(); - }else if (TYPECOMMENT_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver(TYPENAME, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.typename"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(ENCLOSING_TYPE, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ + } else if (TYPECOMMENT_CONTEXTTYPE.equals(contextName)) { + addResolver(new CodeTemplateVariableResolver( + TYPENAME, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.typename"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ addResolver(new TagsVariableResolver()); addCompilationUnitVariables(); - fIsComment= true; + fIsComment = true; } else if (FIELDCOMMENT_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver(FIELD_TYPE, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.fieldtype"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(FIELD, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.fieldname"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + FIELD_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.fieldtype"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + FIELD, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.fieldname"))); //$NON-NLS-1$ addCompilationUnitVariables(); - fIsComment= true; + fIsComment = true; } else if (METHODCOMMENT_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver(ENCLOSING_TYPE, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(ENCLOSING_METHOD, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(RETURN_TYPE, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.returntype"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_METHOD, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + RETURN_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.returntype"))); //$NON-NLS-1$ addResolver(new TagsVariableResolver()); addCompilationUnitVariables(); - fIsComment= true; + fIsComment = true; } else if (OVERRIDECOMMENT_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver(ENCLOSING_TYPE, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(ENCLOSING_METHOD, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(SEE_TAG, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.seetag"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_METHOD, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + SEE_TAG, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.seetag"))); //$NON-NLS-1$ addResolver(new TagsVariableResolver()); addCompilationUnitVariables(); - fIsComment= true; + fIsComment = true; } else if (CONSTRUCTORCOMMENT_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver(ENCLOSING_TYPE, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ addResolver(new TagsVariableResolver()); addCompilationUnitVariables(); - fIsComment= true; + fIsComment = true; } else if (GETTERCOMMENT_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver(ENCLOSING_TYPE, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(FIELD_TYPE, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.getterfieldtype"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(FIELD, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.getterfieldname"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(ENCLOSING_METHOD, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(BARE_FIELD_NAME, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.barefieldname"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + FIELD_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.getterfieldtype"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + FIELD, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.getterfieldname"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_METHOD, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + BARE_FIELD_NAME, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.barefieldname"))); //$NON-NLS-1$ addCompilationUnitVariables(); - fIsComment= true; + fIsComment = true; } else if (SETTERCOMMENT_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver(ENCLOSING_TYPE, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(FIELD_TYPE, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.getterfieldtype"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(FIELD, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.getterfieldname"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(ENCLOSING_METHOD, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(PARAM, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.param"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(BARE_FIELD_NAME, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.barefieldname"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + FIELD_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.getterfieldtype"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + FIELD, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.getterfieldname"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_METHOD, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + PARAM, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.param"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + BARE_FIELD_NAME, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.barefieldname"))); //$NON-NLS-1$ addCompilationUnitVariables(); - fIsComment= true; + fIsComment = true; } } - + private void addCompilationUnitVariables() { - addResolver(new CodeTemplateVariableResolver(FILENAME, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.filename"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(PACKAGENAME, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.packagename"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver(PROJECTNAME, JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.projectname"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + FILENAME, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.filename"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + PACKAGENAME, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.packagename"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + PROJECTNAME, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.projectname"))); //$NON-NLS-1$ } - + /* * @see net.sourceforge.phpdt.internal.corext.template.ContextType#validateVariables(net.sourceforge.phpdt.internal.corext.template.TemplateVariable[]) */ - protected void validateVariables(TemplateVariable[] variables) throws TemplateException { - ArrayList required= new ArrayList(5); - String contextName= getId(); -// if (NEWTYPE_CONTEXTTYPE.equals(contextName)) { -// required.add(PACKAGE_DECLARATION); -// required.add(TYPE_DECLARATION); -// } - for (int i= 0; i < variables.length; i++) { - String type= variables[i].getType(); + protected void validateVariables(TemplateVariable[] variables) + throws TemplateException { + ArrayList required = new ArrayList(5); + String contextName = getId(); + // if (NEWTYPE_CONTEXTTYPE.equals(contextName)) { + // required.add(PACKAGE_DECLARATION); + // required.add(TYPE_DECLARATION); + // } + for (int i = 0; i < variables.length; i++) { + String type = variables[i].getType(); if (getResolver(type) == null) { - throw new TemplateException(JavaTemplateMessages.getFormattedString("CodeTemplateContextType.validate.unknownvariable", type)); //$NON-NLS-1$ + throw new TemplateException( + JavaTemplateMessages + .getFormattedString( + "CodeTemplateContextType.validate.unknownvariable", type)); //$NON-NLS-1$ } required.remove(type); } if (!required.isEmpty()) { - String missing= (String) required.get(0); - throw new TemplateException(JavaTemplateMessages.getFormattedString("CodeTemplateContextType.validate.missingvariable", missing)); //$NON-NLS-1$ + String missing = (String) required.get(0); + throw new TemplateException( + JavaTemplateMessages + .getFormattedString( + "CodeTemplateContextType.validate.missingvariable", missing)); //$NON-NLS-1$ } super.validateVariables(variables); - } - - + } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpdt.internal.corext.template.ContextType#createContext() */ public TemplateContext createContext() { @@ -269,24 +464,36 @@ public class CodeTemplateContextType extends TemplateContextType { } public static void registerContextTypes(ContextTypeRegistry registry) { - registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.CATCHBLOCK_CONTEXTTYPE)); - registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.METHODBODY_CONTEXTTYPE)); - registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.CONSTRUCTORBODY_CONTEXTTYPE)); - registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.GETTERBODY_CONTEXTTYPE)); - registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.SETTERBODY_CONTEXTTYPE)); - registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.NEWTYPE_CONTEXTTYPE)); - registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.NEWHTML_CONTEXTTYPE)); - - registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.TYPECOMMENT_CONTEXTTYPE)); - registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.FIELDCOMMENT_CONTEXTTYPE)); - registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.METHODCOMMENT_CONTEXTTYPE)); - registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.CONSTRUCTORCOMMENT_CONTEXTTYPE)); - registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.OVERRIDECOMMENT_CONTEXTTYPE)); - registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.GETTERCOMMENT_CONTEXTTYPE)); - registry.addContextType(new CodeTemplateContextType(CodeTemplateContextType.SETTERCOMMENT_CONTEXTTYPE)); + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.CATCHBLOCK_CONTEXTTYPE)); + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.METHODBODY_CONTEXTTYPE)); + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.CONSTRUCTORBODY_CONTEXTTYPE)); + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.GETTERBODY_CONTEXTTYPE)); + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.SETTERBODY_CONTEXTTYPE)); + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.NEWTYPE_CONTEXTTYPE)); + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.NEWHTML_CONTEXTTYPE)); + + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.TYPECOMMENT_CONTEXTTYPE)); + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.FIELDCOMMENT_CONTEXTTYPE)); + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.METHODCOMMENT_CONTEXTTYPE)); + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.CONSTRUCTORCOMMENT_CONTEXTTYPE)); + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.OVERRIDECOMMENT_CONTEXTTYPE)); + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.GETTERCOMMENT_CONTEXTTYPE)); + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.SETTERCOMMENT_CONTEXTTYPE)); } - - /* * @see net.sourceforge.phpdt.internal.corext.template.ContextType#validate(java.lang.String) @@ -295,24 +502,27 @@ public class CodeTemplateContextType extends TemplateContextType { super.validate(pattern); if (fIsComment) { if (!isValidComment(pattern)) { - throw new TemplateException(JavaTemplateMessages.getString("CodeTemplateContextType.validate.invalidcomment")); //$NON-NLS-1$ + throw new TemplateException( + JavaTemplateMessages + .getString("CodeTemplateContextType.validate.invalidcomment")); //$NON-NLS-1$ } } } - - + private boolean isValidComment(String template) { - IScanner scanner= ToolFactory.createScanner(true, false, false, true);// false); + IScanner scanner = ToolFactory.createScanner(true, false, false, true);// false); scanner.setSource(template.toCharArray()); try { - int next= scanner.getNextToken(); - while (next == ITerminalSymbols.TokenNameCOMMENT_LINE || next == ITerminalSymbols.TokenNameCOMMENT_PHPDOC || next == ITerminalSymbols.TokenNameCOMMENT_BLOCK) { - next= scanner.getNextToken(); + int next = scanner.getNextToken(); + while (next == ITerminalSymbols.TokenNameCOMMENT_LINE + || next == ITerminalSymbols.TokenNameCOMMENT_PHPDOC + || next == ITerminalSymbols.TokenNameCOMMENT_BLOCK) { + next = scanner.getNextToken(); } return next == ITerminalSymbols.TokenNameEOF; } catch (InvalidInputException e) { } return false; - } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplates.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplates.java index 5e8a298..f26c477 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplates.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplates.java @@ -22,14 +22,21 @@ import org.eclipse.jface.text.templates.Template; /** * CodeTemplates gives access to the available code templates. + * * @since 3.0 - * @deprecated use {@link net.sourceforge.phpdt.internal.ui.JavaPlugin#getCodeTemplateStore()} instead + * @deprecated use + * {@link net.sourceforge.phpdt.internal.ui.JavaPlugin#getCodeTemplateStore()} + * instead */ -public class CodeTemplates extends net.sourceforge.phpdt.internal.corext.template.php.TemplateSet { +public class CodeTemplates extends + net.sourceforge.phpdt.internal.corext.template.php.TemplateSet { + + private static final String DEFAULT_FILE = "default-codetemplates.xml"; //$NON-NLS-1$ + + private static final String TEMPLATE_FILE = "codetemplates.xml"; //$NON-NLS-1$ - private static final String DEFAULT_FILE= "default-codetemplates.xml"; //$NON-NLS-1$ - private static final String TEMPLATE_FILE= "codetemplates.xml"; //$NON-NLS-1$ - private static final ResourceBundle fgResourceBundle= ResourceBundle.getBundle(JavaTemplateMessages.class.getName()); + private static final ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(JavaTemplateMessages.class.getName()); /** Singleton. */ private static CodeTemplates fgTemplates; @@ -43,33 +50,34 @@ public class CodeTemplates extends net.sourceforge.phpdt.internal.corext.templat */ public static CodeTemplates getInstance() { if (fgTemplates == null) - fgTemplates= new CodeTemplates(); - + fgTemplates = new CodeTemplates(); + return fgTemplates; } - + private CodeTemplates() { - super("codetemplate", PHPeclipsePlugin.getDefault().getCodeTemplateContextRegistry()); //$NON-NLS-1$ + super( + "codetemplate", PHPeclipsePlugin.getDefault().getCodeTemplateContextRegistry()); //$NON-NLS-1$ create(); } - + private void create() { - + try { addFromStream(getDefaultsAsStream(), false, true, fgResourceBundle); - File templateFile= getTemplateFile(); + File templateFile = getTemplateFile(); if (templateFile.exists()) { addFromFile(templateFile, false, fgResourceBundle); } saveToFile(templateFile); } catch (CoreException e) { - PHPeclipsePlugin.log(e); + PHPeclipsePlugin.log(e); clear(); } - } - + } + /** * Resets the template set. */ @@ -89,7 +97,7 @@ public class CodeTemplates extends net.sourceforge.phpdt.internal.corext.templat /** * Saves the template set. */ - public void save() throws CoreException { + public void save() throws CoreException { saveToFile(getTemplateFile()); } @@ -98,9 +106,9 @@ public class CodeTemplates extends net.sourceforge.phpdt.internal.corext.templat } private static File getTemplateFile() { - IPath path= PHPeclipsePlugin.getDefault().getStateLocation(); - path= path.append(TEMPLATE_FILE); - + IPath path = PHPeclipsePlugin.getDefault().getStateLocation(); + path = path.append(TEMPLATE_FILE); + return path.toFile(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CompilationUnitCompletion.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CompilationUnitCompletion.java index cf9649b..7684b9d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CompilationUnitCompletion.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CompilationUnitCompletion.java @@ -22,73 +22,75 @@ import net.sourceforge.phpdt.core.ICompilationUnit; import net.sourceforge.phpdt.core.compiler.IProblem; /** - * A completion requestor to collect informations on local variables. - * This class is used for guessing variable names like arrays, collections, etc. + * A completion requestor to collect informations on local variables. This class + * is used for guessing variable names like arrays, collections, etc. */ class CompilationUnitCompletion extends CompletionRequestorAdapter { static class LocalVariable { String name; + String typePackageName; + String typeName; - + LocalVariable(String name, String typePackageName, String typeName) { - this.name= name; - this.typePackageName= typePackageName; - this.typeName= typeName; + this.name = name; + this.typePackageName = typePackageName; + this.typeName = typeName; } } private ICompilationUnit fUnit; - private List fLocalVariables= new ArrayList(); - private Map fTypes= new HashMap(); + private List fLocalVariables = new ArrayList(); + private Map fTypes = new HashMap(); private boolean fError; /** * Creates a compilation unit completion. * - * @param unit the compilation unit, may be null. + * @param unit + * the compilation unit, may be null. */ public CompilationUnitCompletion(ICompilationUnit unit) { reset(unit); } - + /** * Resets the completion requestor. * - * @param unit the compilation unit, may be null. + * @param unit + * the compilation unit, may be null. */ public void reset(ICompilationUnit unit) { - fUnit= unit; - + fUnit = unit; + fLocalVariables.clear(); fTypes.clear(); - - fError= false; + + fError = false; } /* * @see ICompletionRequestor#acceptError(IProblem) */ public void acceptError(IProblem error) { - fError= true; + fError = true; } - /* * @see ICodeCompletionRequestor#acceptLocalVariable */ - public void acceptLocalVariable(char[] name, char[] typePackageName, char[] typeName, - int modifiers, int completionStart, int completionEnd, int relevance) - { - fLocalVariables.add(new LocalVariable( - new String(name), new String(typePackageName), new String(typeName))); + public void acceptLocalVariable(char[] name, char[] typePackageName, + char[] typeName, int modifiers, int completionStart, + int completionEnd, int relevance) { + fLocalVariables.add(new LocalVariable(new String(name), new String( + typePackageName), new String(typeName))); } - // --- /** @@ -97,7 +99,6 @@ class CompilationUnitCompletion extends CompletionRequestorAdapter { public boolean hasErrors() { return fError; } - boolean existsLocalName(String name) { for (Iterator iterator = fLocalVariables.iterator(); iterator.hasNext();) { @@ -109,133 +110,141 @@ class CompilationUnitCompletion extends CompletionRequestorAdapter { return false; } - + String[] getLocalVariableNames() { - String[] res= new String[fLocalVariables.size()]; - int i= 0; + String[] res = new String[fLocalVariables.size()]; + int i = 0; for (Iterator iterator = fLocalVariables.iterator(); iterator.hasNext();) { LocalVariable localVariable = (LocalVariable) iterator.next(); - res[i++]= localVariable.name; - } + res[i++] = localVariable.name; + } return res; - } + } LocalVariable[] findLocalArrays() { - Vector vector= new Vector(); + Vector vector = new Vector(); - for (Iterator iterator= fLocalVariables.iterator(); iterator.hasNext();) { - LocalVariable localVariable= (LocalVariable) iterator.next(); + for (Iterator iterator = fLocalVariables.iterator(); iterator.hasNext();) { + LocalVariable localVariable = (LocalVariable) iterator.next(); if (isArray(localVariable.typeName)) vector.add(localVariable); } - return (LocalVariable[]) vector.toArray(new LocalVariable[vector.size()]); + return (LocalVariable[]) vector + .toArray(new LocalVariable[vector.size()]); } - -// LocalVariable[] findLocalCollections() throws JavaModelException { -// Vector vector= new Vector(); -// -// for (Iterator iterator= fLocalVariables.iterator(); iterator.hasNext();) { -// LocalVariable localVariable= (LocalVariable) iterator.next(); -// -// String typeName= qualify(localVariable.typeName); -// -// if (typeName == null) -// continue; -// -// if (isSubclassOf(typeName, "java.util.Collection")) //$NON-NLS-1$ -// vector.add(localVariable); -// } -// -// return (LocalVariable[]) vector.toArray(new LocalVariable[vector.size()]); -// } + + // LocalVariable[] findLocalCollections() throws JavaModelException { + // Vector vector= new Vector(); + // + // for (Iterator iterator= fLocalVariables.iterator(); iterator.hasNext();) + // { + // LocalVariable localVariable= (LocalVariable) iterator.next(); + // + // String typeName= qualify(localVariable.typeName); + // + // if (typeName == null) + // continue; + // + // if (isSubclassOf(typeName, "java.util.Collection")) //$NON-NLS-1$ + // vector.add(localVariable); + // } + // + // return (LocalVariable[]) vector.toArray(new + // LocalVariable[vector.size()]); + // } String simplifyTypeName(String qualifiedName) { - return (String) fTypes.get(qualifiedName); + return (String) fTypes.get(qualifiedName); } private static boolean isArray(String type) { return type.endsWith("[]"); //$NON-NLS-1$ } - + // returns fully qualified name if successful -// private String qualify(String typeName) throws JavaModelException { -// if (fUnit == null) -// return null; -// -// IType[] types= fUnit.getTypes(); -// -// if (types.length == 0) -// return null; -// -// String[][] resolvedTypeNames= types[0].resolveType(typeName); -// -// if (resolvedTypeNames == null) -// return null; -// -// return resolvedTypeNames[0][0] + '.' + resolvedTypeNames[0][1]; -// } - + // private String qualify(String typeName) throws JavaModelException { + // if (fUnit == null) + // return null; + // + // IType[] types= fUnit.getTypes(); + // + // if (types.length == 0) + // return null; + // + // String[][] resolvedTypeNames= types[0].resolveType(typeName); + // + // if (resolvedTypeNames == null) + // return null; + // + // return resolvedTypeNames[0][0] + '.' + resolvedTypeNames[0][1]; + // } + // type names must be fully qualified -// private boolean isSubclassOf(String typeName0, String typeName1) throws JavaModelException { -// if (typeName0.equals(typeName1)) -// return true; -// -// if (fUnit == null) -// return false; -// -// IJavaProject project= fUnit.getJavaProject(); -// -// IType type0= project.findType(typeName0); -// if (type0 == null) -// return false; -// -// IType type1= project.findType(typeName1); -// if (type1 == null) -// return false; -// -// ITypeHierarchy hierarchy= type0.newSupertypeHierarchy(null); -// IType[] superTypes= hierarchy.getAllSupertypes(type0); -// -// for (int i= 0; i < superTypes.length; i++) -// if (superTypes[i].equals(type1)) -// return true; -// -// return false; -// } + // private boolean isSubclassOf(String typeName0, String typeName1) throws + // JavaModelException { + // if (typeName0.equals(typeName1)) + // return true; + // + // if (fUnit == null) + // return false; + // + // IJavaProject project= fUnit.getJavaProject(); + // + // IType type0= project.findType(typeName0); + // if (type0 == null) + // return false; + // + // IType type1= project.findType(typeName1); + // if (type1 == null) + // return false; + // + // ITypeHierarchy hierarchy= type0.newSupertypeHierarchy(null); + // IType[] superTypes= hierarchy.getAllSupertypes(type0); + // + // for (int i= 0; i < superTypes.length; i++) + // if (superTypes[i].equals(type1)) + // return true; + // + // return false; + // } /* - * @see net.sourceforge.phpdt.core.ICompletionRequestor#acceptClass(char[], char[], char[], int, int, int, int) + * @see net.sourceforge.phpdt.core.ICompletionRequestor#acceptClass(char[], + * char[], char[], int, int, int, int) */ - public void acceptClass(char[] packageName, char[] className, char[] completionName, int modifiers, - int completionStart, int completionEnd, int relevance) - { - final String qualifiedName= createQualifiedTypeName(packageName, className); + public void acceptClass(char[] packageName, char[] className, + char[] completionName, int modifiers, int completionStart, + int completionEnd, int relevance) { + final String qualifiedName = createQualifiedTypeName(packageName, + className); fTypes.put(qualifiedName, String.valueOf(completionName)); } /* - * @see net.sourceforge.phpdt.core.ICompletionRequestor#acceptInterface(char[], char[], char[], int, int, int, int) + * @see net.sourceforge.phpdt.core.ICompletionRequestor#acceptInterface(char[], + * char[], char[], int, int, int, int) */ - public void acceptInterface(char[] packageName, char[] interfaceName, char[] completionName, - int modifiers, int completionStart, int completionEnd, int relevance) - { - final String qualifiedName= createQualifiedTypeName(packageName, interfaceName); + public void acceptInterface(char[] packageName, char[] interfaceName, + char[] completionName, int modifiers, int completionStart, + int completionEnd, int relevance) { + final String qualifiedName = createQualifiedTypeName(packageName, + interfaceName); fTypes.put(qualifiedName, String.valueOf(completionName)); } - private static String createQualifiedTypeName(char[] packageName, char[] className) { - StringBuffer buffer= new StringBuffer(); + private static String createQualifiedTypeName(char[] packageName, + char[] className) { + StringBuffer buffer = new StringBuffer(); if (packageName.length != 0) { buffer.append(packageName); buffer.append('.'); } buffer.append(className); - + return buffer.toString(); } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CompilationUnitContext.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CompilationUnitContext.java index dc3d508..a7defad 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CompilationUnitContext.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CompilationUnitContext.java @@ -19,8 +19,8 @@ import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.templates.DocumentTemplateContext; import org.eclipse.jface.text.templates.TemplateContextType; -//import net.sourceforge.phpdt.internal.ui.text.template.contentassist.MultiVariableGuess; - +// import +// net.sourceforge.phpdt.internal.ui.text.template.contentassist.MultiVariableGuess; /** * A compilation unit context. @@ -29,74 +29,84 @@ public abstract class CompilationUnitContext extends DocumentTemplateContext { /** The compilation unit, may be null. */ private final ICompilationUnit fCompilationUnit; + /** A flag to force evaluation in head-less mode. */ protected boolean fForceEvaluation; + /** A global state for proposals that change if a master proposal changes. */ protected MultiVariableGuess fMultiVariableGuess; /** * Creates a compilation unit context. * - * @param type the context type - * @param document the document - * @param completionOffset the completion position within the document - * @param completionLength the completion length within the document - * @param compilationUnit the compilation unit (may be null) + * @param type + * the context type + * @param document + * the document + * @param completionOffset + * the completion position within the document + * @param completionLength + * the completion length within the document + * @param compilationUnit + * the compilation unit (may be null) */ - protected CompilationUnitContext(TemplateContextType type, IDocument document, int completionOffset, - int completionLength, ICompilationUnit compilationUnit) - { + protected CompilationUnitContext(TemplateContextType type, + IDocument document, int completionOffset, int completionLength, + ICompilationUnit compilationUnit) { super(type, document, completionOffset, completionLength); - fCompilationUnit= compilationUnit; + fCompilationUnit = compilationUnit; } - + /** - * Returns the compilation unit if one is associated with this context, null otherwise. + * Returns the compilation unit if one is associated with this context, + * null otherwise. */ public final ICompilationUnit getCompilationUnit() { return fCompilationUnit; } /** - * Returns the enclosing element of a particular element type, null - * if no enclosing element of that type exists. + * Returns the enclosing element of a particular element type, + * null if no enclosing element of that type exists. */ public IJavaElement findEnclosingElement(int elementType) { if (fCompilationUnit == null) return null; try { - IJavaElement element= fCompilationUnit.getElementAt(getStart()); + IJavaElement element = fCompilationUnit.getElementAt(getStart()); if (element == null) { - element= fCompilationUnit; + element = fCompilationUnit; } - + return element.getAncestor(elementType); } catch (JavaModelException e) { return null; - } + } } /** * Forces evaluation. */ public void setForceEvaluation(boolean evaluate) { - fForceEvaluation= evaluate; + fForceEvaluation = evaluate; } - + /** * Returns the multivariable guess - state + * * @return */ public MultiVariableGuess getMultiVariableGuess() { return fMultiVariableGuess; - } + } /** - * @param multiVariableGuess The multiVariableGuess to set. + * @param multiVariableGuess + * The multiVariableGuess to set. */ public void setMultiVariableGuess(MultiVariableGuess multiVariableGuess) { - fMultiVariableGuess= multiVariableGuess; + fMultiVariableGuess = multiVariableGuess; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CompilationUnitContextType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CompilationUnitContextType.java index d06498d..085d382 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CompilationUnitContextType.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CompilationUnitContextType.java @@ -24,18 +24,20 @@ import org.eclipse.jface.text.templates.TemplateException; import org.eclipse.jface.text.templates.TemplateVariable; import org.eclipse.jface.text.templates.TemplateVariableResolver; - /** * Compilation unit context type. */ public abstract class CompilationUnitContextType extends TemplateContextType { - + protected static class ReturnType extends TemplateVariableResolver { - public ReturnType() { - super("return_type", JavaTemplateMessages.getString("CompilationUnitContextType.variable.description.return.type")); //$NON-NLS-1$ //$NON-NLS-2$ - } - protected String resolve(TemplateContext context) { - IJavaElement element= ((CompilationUnitContext) context).findEnclosingElement(IJavaElement.METHOD); + public ReturnType() { + super( + "return_type", JavaTemplateMessages.getString("CompilationUnitContextType.variable.description.return.type")); //$NON-NLS-1$ //$NON-NLS-2$ + } + + protected String resolve(TemplateContext context) { + IJavaElement element = ((CompilationUnitContext) context) + .findEnclosingElement(IJavaElement.METHOD); if (element == null) return null; @@ -49,14 +51,17 @@ public abstract class CompilationUnitContextType extends TemplateContextType { protected static class File extends TemplateVariableResolver { public File() { - super("file", JavaTemplateMessages.getString("CompilationUnitContextType.variable.description.file")); //$NON-NLS-1$ //$NON-NLS-2$ + super( + "file", JavaTemplateMessages.getString("CompilationUnitContextType.variable.description.file")); //$NON-NLS-1$ //$NON-NLS-2$ } + protected String resolve(TemplateContext context) { - ICompilationUnit unit= ((CompilationUnitContext) context).getCompilationUnit(); - + ICompilationUnit unit = ((CompilationUnitContext) context) + .getCompilationUnit(); + return (unit == null) ? null : unit.getElementName(); } - + /* * @see org.eclipse.jface.text.templates.TemplateVariableResolver#isUnambiguous(org.eclipse.jface.text.templates.TemplateContext) */ @@ -64,20 +69,23 @@ public abstract class CompilationUnitContextType extends TemplateContextType { return resolve(context) != null; } } - + protected static class PrimaryTypeName extends TemplateVariableResolver { public PrimaryTypeName() { - super("primary_type_name", JavaTemplateMessages.getString("CompilationUnitContextType.variable.description.primary.type.name")); //$NON-NLS-1$ //$NON-NLS-2$ - + super( + "primary_type_name", JavaTemplateMessages.getString("CompilationUnitContextType.variable.description.primary.type.name")); //$NON-NLS-1$ //$NON-NLS-2$ + } + protected String resolve(TemplateContext context) { - ICompilationUnit unit= ((CompilationUnitContext) context).getCompilationUnit(); - if (unit == null) + ICompilationUnit unit = ((CompilationUnitContext) context) + .getCompilationUnit(); + if (unit == null) return null; - String elementName= unit.getElementName(); + String elementName = unit.getElementName(); return elementName.substring(0, elementName.lastIndexOf('.')); } - + /* * @see org.eclipse.jface.text.templates.TemplateVariableResolver#isUnambiguous(org.eclipse.jface.text.templates.TemplateContext) */ @@ -86,18 +94,22 @@ public abstract class CompilationUnitContextType extends TemplateContextType { } } - protected static class EnclosingJavaElement extends TemplateVariableResolver { + protected static class EnclosingJavaElement extends + TemplateVariableResolver { protected final int fElementType; - - public EnclosingJavaElement(String name, String description, int elementType) { + + public EnclosingJavaElement(String name, String description, + int elementType) { super(name, description); - fElementType= elementType; + fElementType = elementType; } + protected String resolve(TemplateContext context) { - IJavaElement element= ((CompilationUnitContext) context).findEnclosingElement(fElementType); - return (element == null) ? null : element.getElementName(); + IJavaElement element = ((CompilationUnitContext) context) + .findEnclosingElement(fElementType); + return (element == null) ? null : element.getElementName(); } - + /* * @see org.eclipse.jface.text.templates.TemplateVariableResolver#isUnambiguous(org.eclipse.jface.text.templates.TemplateContext) */ @@ -105,68 +117,73 @@ public abstract class CompilationUnitContextType extends TemplateContextType { return resolve(context) != null; } } - + protected static class Method extends EnclosingJavaElement { public Method() { - super("enclosing_method", JavaTemplateMessages.getString("CompilationUnitContextType.variable.description.enclosing.method"), IJavaElement.METHOD); //$NON-NLS-1$ //$NON-NLS-2$ + super( + "enclosing_method", JavaTemplateMessages.getString("CompilationUnitContextType.variable.description.enclosing.method"), IJavaElement.METHOD); //$NON-NLS-1$ //$NON-NLS-2$ } } protected static class Type extends EnclosingJavaElement { public Type() { - super("enclosing_type", JavaTemplateMessages.getString("CompilationUnitContextType.variable.description.enclosing.type"), IJavaElement.TYPE); //$NON-NLS-1$ //$NON-NLS-2$ + super( + "enclosing_type", JavaTemplateMessages.getString("CompilationUnitContextType.variable.description.enclosing.type"), IJavaElement.TYPE); //$NON-NLS-1$ //$NON-NLS-2$ } } -/* - protected static class SuperClass extends EnclosingJavaElement { - public Type() { - super("super_class", TemplateMessages.getString("JavaContextType.variable.description.type"), IJavaElement.TYPE); - } - } -*/ + + /* + * protected static class SuperClass extends EnclosingJavaElement { public + * Type() { super("super_class", + * TemplateMessages.getString("JavaContextType.variable.description.type"), + * IJavaElement.TYPE); } } + */ protected static class Package extends EnclosingJavaElement { public Package() { - super("enclosing_package", JavaTemplateMessages.getString("CompilationUnitContextType.variable.description.enclosing.package"), IJavaElement.PACKAGE_FRAGMENT); //$NON-NLS-1$ //$NON-NLS-2$ + super( + "enclosing_package", JavaTemplateMessages.getString("CompilationUnitContextType.variable.description.enclosing.package"), IJavaElement.PACKAGE_FRAGMENT); //$NON-NLS-1$ //$NON-NLS-2$ } - } + } protected static class Project extends EnclosingJavaElement { public Project() { - super("enclosing_project", JavaTemplateMessages.getString("CompilationUnitContextType.variable.description.enclosing.project"), IJavaElement.JAVA_PROJECT); //$NON-NLS-1$ //$NON-NLS-2$ - } - } -/* - protected static class Project2 extends TemplateVariableResolver { - public Project2() { - super("project", TemplateMessages.getString("JavaContextType.variable.description.project")); + super( + "enclosing_project", JavaTemplateMessages.getString("CompilationUnitContextType.variable.description.enclosing.project"), IJavaElement.JAVA_PROJECT); //$NON-NLS-1$ //$NON-NLS-2$ } - public String evaluate(TemplateContext context) { - ICompilationUnit unit= ((JavaContext) context).getUnit(); - return (unit == null) ? null : unit.getJavaProject().getElementName(); - } - } -*/ + } + + /* + * protected static class Project2 extends TemplateVariableResolver { public + * Project2() { super("project", + * TemplateMessages.getString("JavaContextType.variable.description.project")); } + * public String evaluate(TemplateContext context) { ICompilationUnit unit= + * ((JavaContext) context).getUnit(); return (unit == null) ? null : + * unit.getJavaProject().getElementName(); } } + */ protected static class Arguments extends TemplateVariableResolver { public Arguments() { - super("enclosing_method_arguments", JavaTemplateMessages.getString("CompilationUnitContextType.variable.description.enclosing.method.arguments")); //$NON-NLS-1$ //$NON-NLS-2$ + super( + "enclosing_method_arguments", JavaTemplateMessages.getString("CompilationUnitContextType.variable.description.enclosing.method.arguments")); //$NON-NLS-1$ //$NON-NLS-2$ } + protected String resolve(TemplateContext context) { - IJavaElement element= ((CompilationUnitContext) context).findEnclosingElement(IJavaElement.METHOD); + IJavaElement element = ((CompilationUnitContext) context) + .findEnclosingElement(IJavaElement.METHOD); if (element == null) return null; - - IMethod method= (IMethod) element; - + + IMethod method = (IMethod) element; + try { - String[] arguments= method.getParameterNames(); - StringBuffer buffer= new StringBuffer(); - - for (int i= 0; i < arguments.length; i++) { + String[] arguments = method.getParameterNames(); + StringBuffer buffer = new StringBuffer(); + + for (int i = 0; i < arguments.length; i++) { if (i > 0) buffer.append(", "); //$NON-NLS-1$ - buffer.append(arguments[i]); + buffer.append(arguments[i]); } - + return buffer.toString(); } catch (JavaModelException e) { @@ -175,37 +192,39 @@ public abstract class CompilationUnitContextType extends TemplateContextType { } } -/* - protected static class Line extends TemplateVariableResolver { - public Line() { - super("line", TemplateMessages.getString("CompilationUnitContextType.variable.description.line")); - } - public String evaluate(TemplateContext context) { - return ((JavaTemplateContext) context).guessLineNumber(); - } - } -*/ + /* + * protected static class Line extends TemplateVariableResolver { public + * Line() { super("line", + * TemplateMessages.getString("CompilationUnitContextType.variable.description.line")); } + * public String evaluate(TemplateContext context) { return + * ((JavaTemplateContext) context).guessLineNumber(); } } + */ /* * @see ContextType#ContextType(String) */ public CompilationUnitContextType(String name) { - super(name); + super(name); } - public abstract CompilationUnitContext createContext(IDocument document, int completionPosition, int length, ICompilationUnit compilationUnit); + public abstract CompilationUnitContext createContext(IDocument document, + int completionPosition, int length, ICompilationUnit compilationUnit); - - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpdt.internal.corext.template.ContextType#validateVariables(net.sourceforge.phpdt.internal.corext.template.TemplateVariable[]) */ - protected void validateVariables(TemplateVariable[] variables) throws TemplateException { - // check for multiple cursor variables - for (int i= 0; i < variables.length; i++) { - TemplateVariable var= variables[i]; + protected void validateVariables(TemplateVariable[] variables) + throws TemplateException { + // check for multiple cursor variables + for (int i = 0; i < variables.length; i++) { + TemplateVariable var = variables[i]; if (var.getType().equals(GlobalTemplateVariables.Cursor.NAME)) { if (var.getOffsets().length > 1) { - throw new TemplateException(JavaTemplateMessages.getString("ContextType.error.multiple.cursor.variables")); //$NON-NLS-1$ + throw new TemplateException( + JavaTemplateMessages + .getString("ContextType.error.multiple.cursor.variables")); //$NON-NLS-1$ } } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/HTMLContextType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/HTMLContextType.java index 82be502..b187c3d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/HTMLContextType.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/HTMLContextType.java @@ -4,9 +4,10 @@ */ package net.sourceforge.phpdt.internal.corext.template.php; -//import net.sourceforge.phpdt.core.ICompilationUnit; +// import net.sourceforge.phpdt.core.ICompilationUnit; import net.sourceforge.phpdt.core.ICompilationUnit; + import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.templates.GlobalTemplateVariables; import org.eclipse.jface.text.templates.TemplateException; @@ -39,25 +40,38 @@ public class HTMLContextType extends CompilationUnitContextType { /* * @see ContextType#createContext() */ - public CompilationUnitContext createContext(IDocument document, int offset, int length, ICompilationUnit compilationUnit) { - return new HTMLUnitContext(this, document, offset, length, compilationUnit); + public CompilationUnitContext createContext(IDocument document, int offset, + int length, ICompilationUnit compilationUnit) { + return new HTMLUnitContext(this, document, offset, length, + compilationUnit); } - /* (non-Javadoc) - * @see net.sourceforge.phpdt.internal.corext.template.java.CompilationUnitContextType#createContext(org.eclipse.jface.text.IDocument, int, int, net.sourceforge.phpdt.core.ICompilationUnit) + + /* + * (non-Javadoc) + * + * @see net.sourceforge.phpdt.internal.corext.template.java.CompilationUnitContextType#createContext(org.eclipse.jface.text.IDocument, + * int, int, net.sourceforge.phpdt.core.ICompilationUnit) */ -// public CompilationUnitContext createContext(IDocument document, int offset, int length, ICompilationUnit compilationUnit) { -// return new JavaDocContext(this, document, offset, length, compilationUnit); -// } - /* (non-Javadoc) + // public CompilationUnitContext createContext(IDocument document, int + // offset, int length, ICompilationUnit compilationUnit) { + // return new JavaDocContext(this, document, offset, length, + // compilationUnit); + // } + /* + * (non-Javadoc) + * * @see net.sourceforge.phpdt.internal.corext.template.ContextType#validateVariables(net.sourceforge.phpdt.internal.corext.template.TemplateVariable[]) */ - protected void validateVariables(TemplateVariable[] variables) throws TemplateException { + protected void validateVariables(TemplateVariable[] variables) + throws TemplateException { // check for multiple cursor variables - for (int i= 0; i < variables.length; i++) { - TemplateVariable var= variables[i]; + for (int i = 0; i < variables.length; i++) { + TemplateVariable var = variables[i]; if (var.getType().equals(GlobalTemplateVariables.Cursor.NAME)) { if (var.getOffsets().length > 1) { - throw new TemplateException(JavaTemplateMessages.getString("ContextType.error.multiple.cursor.variables")); //$NON-NLS-1$ + throw new TemplateException( + JavaTemplateMessages + .getString("ContextType.error.multiple.cursor.variables")); //$NON-NLS-1$ } } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/HTMLUnitContext.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/HTMLUnitContext.java index ba9e346..bbd35b7 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/HTMLUnitContext.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/HTMLUnitContext.java @@ -15,150 +15,161 @@ import org.eclipse.jface.text.templates.TemplateTranslator; */ public class HTMLUnitContext extends CompilationUnitContext { - // tags - // private static final char HTML_TAG_BEGIN= '<'; - // private static final char HTML_TAG_END= '>'; - // private static final char JAVADOC_TAG_BEGIN= '@'; - /** - * special characters '&' for the start of HTML entities '<' for the start of HTML tags '#' for the start of colour attributes - * '{' for the start of smarty partitions inside HTML code - */ - private static final String specialChars = "&<#{"; - - /** - * Creates a javadoc template context. - * - * @param type - * the context type. - * @param document - * the document. - * @param completionOffset - * the completion offset within the document. - * @param completionLength - * the completion length within the document. - * @param compilationUnit - * the compilation unit (may be null). - */ - public HTMLUnitContext(TemplateContextType type, IDocument document, int completionOffset, int completionLength, - ICompilationUnit compilationUnit) { - super(type, document, completionOffset, completionLength, compilationUnit); - } - - /* - * @see TemplateContext#canEvaluate(Template templates) - */ - public boolean canEvaluate(Template template) { - String key = getKey(); - - if (fForceEvaluation) - return true; - - return template.matches(key, getContextType().getId()) && (key.length() != 0) - && template.getName().toLowerCase().startsWith(key.toLowerCase()); - } - - /* - * @see DocumentTemplateContext#getCompletionPosition(); - */ - public int getStart() { - IDocument document = getDocument(); - try { - int start = getCompletionOffset(); - char ch = ' '; - while (start != 0) { - ch = document.getChar(start - 1); - if (specialChars.indexOf(ch) != (-1)) { - return --start; - } - if (Character.isUnicodeIdentifierPart(ch)) { - start--; - } else { - break; - } - } - if ((start != 0) && Character.isUnicodeIdentifierStart(document.getChar(start - 1))) { - start--; - if ((start != 0) && specialChars.indexOf(document.getChar(start - 1)) != (-1)) { - start--; - } - } - - // while (((start != 0) - // && Character.isUnicodeIdentifierPart(document.getChar(start - 1))) - // || ((start != 0) - // && specialChars.indexOf(document.getChar(start - 1)) != (-1))) { - // start--; - // } - // - //if (((start != 0) - // && Character.isUnicodeIdentifierStart(document.getChar(start - 1))) - // || ((start != 0) - // && specialChars.indexOf(document.getChar(start - 1)) != (-1))) { - // start--; - //} - - return start; - - } catch (BadLocationException e) { - return getCompletionOffset(); - } - } - - /* - * @see net.sourceforge.phpdt.internal.corext.template.DocumentTemplateContext#getEnd() - */ - public int getEnd() { - - if (getCompletionLength() == 0) - return super.getEnd(); - - try { - IDocument document = getDocument(); - - int start = getCompletionOffset(); - int end = getCompletionOffset() + getCompletionLength(); - - while (start != end && Character.isWhitespace(document.getChar(end - 1))) - end--; - - return end; - - } catch (BadLocationException e) { - return super.getEnd(); - } - } - - /* - * @see net.sourceforge.phpdt.internal.corext.template.DocumentTemplateContext#getKey() - */ - public String getKey() { - - if (getCompletionLength() == 0) - return super.getKey(); - - try { - IDocument document = getDocument(); - - int start = getStart(); - int end = getCompletionOffset(); - return start <= end ? document.get(start, end - start) : ""; //$NON-NLS-1$ - - } catch (BadLocationException e) { - return super.getKey(); - } - } - - /* - * @see TemplateContext#evaluate(Template) - */ - public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException { - TemplateTranslator translator = new TemplateTranslator(); - TemplateBuffer buffer = translator.translate(template); - - getContextType().resolve(buffer, this); - - return buffer; - } + // tags + // private static final char HTML_TAG_BEGIN= '<'; + // private static final char HTML_TAG_END= '>'; + // private static final char JAVADOC_TAG_BEGIN= '@'; + /** + * special characters '&' for the start of HTML entities '<' for the start + * of HTML tags '#' for the start of colour attributes '{' for the start of + * smarty partitions inside HTML code + */ + private static final String specialChars = "&<#{"; + + /** + * Creates a javadoc template context. + * + * @param type + * the context type. + * @param document + * the document. + * @param completionOffset + * the completion offset within the document. + * @param completionLength + * the completion length within the document. + * @param compilationUnit + * the compilation unit (may be null). + */ + public HTMLUnitContext(TemplateContextType type, IDocument document, + int completionOffset, int completionLength, + ICompilationUnit compilationUnit) { + super(type, document, completionOffset, completionLength, + compilationUnit); + } + + /* + * @see TemplateContext#canEvaluate(Template templates) + */ + public boolean canEvaluate(Template template) { + String key = getKey(); + + if (fForceEvaluation) + return true; + + return template.matches(key, getContextType().getId()) + && (key.length() != 0) + && template.getName().toLowerCase().startsWith( + key.toLowerCase()); + } + + /* + * @see DocumentTemplateContext#getCompletionPosition(); + */ + public int getStart() { + IDocument document = getDocument(); + try { + int start = getCompletionOffset(); + char ch = ' '; + while (start != 0) { + ch = document.getChar(start - 1); + if (specialChars.indexOf(ch) != (-1)) { + return --start; + } + if (Character.isUnicodeIdentifierPart(ch)) { + start--; + } else { + break; + } + } + if ((start != 0) + && Character.isUnicodeIdentifierStart(document + .getChar(start - 1))) { + start--; + if ((start != 0) + && specialChars.indexOf(document.getChar(start - 1)) != (-1)) { + start--; + } + } + + // while (((start != 0) + // && Character.isUnicodeIdentifierPart(document.getChar(start - + // 1))) + // || ((start != 0) + // && specialChars.indexOf(document.getChar(start - 1)) != (-1))) { + // start--; + // } + // + // if (((start != 0) + // && Character.isUnicodeIdentifierStart(document.getChar(start - + // 1))) + // || ((start != 0) + // && specialChars.indexOf(document.getChar(start - 1)) != (-1))) { + // start--; + // } + + return start; + + } catch (BadLocationException e) { + return getCompletionOffset(); + } + } + + /* + * @see net.sourceforge.phpdt.internal.corext.template.DocumentTemplateContext#getEnd() + */ + public int getEnd() { + + if (getCompletionLength() == 0) + return super.getEnd(); + + try { + IDocument document = getDocument(); + + int start = getCompletionOffset(); + int end = getCompletionOffset() + getCompletionLength(); + + while (start != end + && Character.isWhitespace(document.getChar(end - 1))) + end--; + + return end; + + } catch (BadLocationException e) { + return super.getEnd(); + } + } + + /* + * @see net.sourceforge.phpdt.internal.corext.template.DocumentTemplateContext#getKey() + */ + public String getKey() { + + if (getCompletionLength() == 0) + return super.getKey(); + + try { + IDocument document = getDocument(); + + int start = getStart(); + int end = getCompletionOffset(); + return start <= end ? document.get(start, end - start) : ""; //$NON-NLS-1$ + + } catch (BadLocationException e) { + return super.getKey(); + } + } + + /* + * @see TemplateContext#evaluate(Template) + */ + public TemplateBuffer evaluate(Template template) + throws BadLocationException, TemplateException { + TemplateTranslator translator = new TemplateTranslator(); + TemplateBuffer buffer = translator.translate(template); + + getContextType().resolve(buffer, this); + + return buffer; + } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaContext.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaContext.java index e2315a7..5db1928 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaContext.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaContext.java @@ -43,559 +43,621 @@ import org.eclipse.swt.widgets.Shell; */ public class JavaContext extends CompilationUnitContext { - /** The platform default line delimiter. */ - private static final String PLATFORM_LINE_DELIMITER = System.getProperty("line.separator"); //$NON-NLS-1$ - - /** A code completion requestor for guessing local variable names. */ - private CompilationUnitCompletion fCompletion; - - /** - * Creates a java template context. - * - * @param type - * the context type. - * @param document - * the document. - * @param completionOffset - * the completion offset within the document. - * @param completionLength - * the completion length. - * @param compilationUnit - * the compilation unit (may be null). - */ - public JavaContext(TemplateContextType type, IDocument document, int completionOffset, int completionLength, - ICompilationUnit compilationUnit) { - super(type, document, completionOffset, completionLength, compilationUnit); - } - - /** - * Returns the indentation level at the position of code completion. - */ - private int getIndentation() { - int start = getStart(); - IDocument document = getDocument(); - try { - IRegion region = document.getLineInformationOfOffset(start); - String lineContent = document.get(region.getOffset(), region.getLength()); - return Strings.computeIndent(lineContent, CodeFormatterPreferencePage.getTabSize()); - // return Strings.computeIndent(lineContent, CodeFormatterUtil.getTabWidth()); - } catch (BadLocationException e) { - return 0; - } - } - - /* - * @see TemplateContext#evaluate(Template template) - */ - public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException { - - if (!canEvaluate(template)) - throw new TemplateException(JavaTemplateMessages.getString("Context.error.cannot.evaluate")); //$NON-NLS-1$ - - TemplateTranslator translator = new TemplateTranslator() { - /* - * @see org.eclipse.jface.text.templates.TemplateTranslator#createVariable(java.lang.String, java.lang.String, int[]) - */ - protected TemplateVariable createVariable(String type, String name, int[] offsets) { - return new MultiVariable(type, name, offsets); - } - }; - TemplateBuffer buffer = translator.translate(template); - - getContextType().resolve(buffer, this); - String lineDelimiter = null; - try { - lineDelimiter = getDocument().getLineDelimiter(0); - } catch (BadLocationException e) { - } - - if (lineDelimiter == null) - lineDelimiter = PLATFORM_LINE_DELIMITER; - IPreferenceStore prefs = PHPeclipsePlugin.getDefault().getPreferenceStore(); - // axelcl start - // boolean useCodeFormatter = prefs.getBoolean(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER); - boolean useCodeFormatter = false; - // axelcl end - - JavaFormatter formatter = new JavaFormatter(lineDelimiter, getIndentation(), useCodeFormatter); - formatter.format(buffer, this); - // debug start - // String res = buffer.getString(); - // res = res.replaceAll("\n","/n"); - // res = res.replaceAll("\t","/t"); - // System.out.println(res); - // debug end - return buffer; - } - - /* - * @see TemplateContext#canEvaluate(Template templates) - */ - public boolean canEvaluate(Template template) { - String key = getKey(); - - if (fForceEvaluation) - return true; - - return template.matches(key, getContextType().getId()) && key.length() != 0 - && template.getName().toLowerCase().startsWith(key.toLowerCase()); - } - - public boolean canEvaluate(String identifier) { - String prefix = getKey(); - return identifier.toLowerCase().startsWith(prefix.toLowerCase()); - } - - /* - * @see DocumentTemplateContext#getCompletionPosition(); - */ - public int getStart() { - - try { - IDocument document = getDocument(); - - if (getCompletionLength() == 0) { - - int start = getCompletionOffset(); - while ((start != 0) && Character.isUnicodeIdentifierPart(document.getChar(start - 1))) - start--; - - if ((start != 0) && (Character.isUnicodeIdentifierStart(document.getChar(start - 1))||(document.getChar(start - 1)=='$') )) - start--; - - return start; - - } else { - - int start = getCompletionOffset(); - int end = getCompletionOffset() + getCompletionLength(); - - while (start != 0 && Character.isUnicodeIdentifierPart(document.getChar(start - 1))) - start--; - if ((start != 0) && (Character.isUnicodeIdentifierStart(document.getChar(start - 1))||(document.getChar(start - 1)=='$') )) - start--; - while (start != end && Character.isWhitespace(document.getChar(start))) - start++; - - if (start == end) - start = getCompletionOffset(); - - return start; - } - - } catch (BadLocationException e) { - return super.getStart(); - } - } - - /* - * @see net.sourceforge.phpdt.internal.corext.template.DocumentTemplateContext#getEnd() - */ - public int getEnd() { - - if (getCompletionLength() == 0) - return super.getEnd(); - - try { - IDocument document = getDocument(); - - int start = getCompletionOffset(); - int end = getCompletionOffset() + getCompletionLength(); - - while (start != end && Character.isWhitespace(document.getChar(end - 1))) - end--; - - return end; - - } catch (BadLocationException e) { - return super.getEnd(); - } - } - - /* - * @see net.sourceforge.phpdt.internal.corext.template.DocumentTemplateContext#getKey() - */ - public String getKey() { - -// if (getCompletionLength() == 0) { -// return super.getKey(); -// } - - try { - IDocument document = getDocument(); - - int start = getStart(); - int end = getCompletionOffset(); - return start <= end ? document.get(start, end - start) : ""; //$NON-NLS-1$ - - } catch (BadLocationException e) { - return super.getKey(); - } - } - - /** - * Returns the character before start position of completion. - */ - public char getCharacterBeforeStart() { - int start = getStart(); - - try { - return start == 0 ? ' ' : getDocument().getChar(start - 1); - - } catch (BadLocationException e) { - return ' '; - } - } - - private static void handleException(Shell shell, Exception e) { - String title = JavaTemplateMessages.getString("JavaContext.error.title"); //$NON-NLS-1$ - if (e instanceof CoreException) - ExceptionHandler.handle((CoreException) e, shell, title, null); - else if (e instanceof InvocationTargetException) - ExceptionHandler.handle((InvocationTargetException) e, shell, title, null); - else { - PHPeclipsePlugin.log(e); - MessageDialog.openError(shell, title, e.getMessage()); - } - } - - // private CompilationUnitCompletion getCompletion() { - // ICompilationUnit compilationUnit= getCompilationUnit(); - // if (fCompletion == null) { - // fCompletion= new CompilationUnitCompletion(compilationUnit); - // - // if (compilationUnit != null) { - // try { - // compilationUnit.codeComplete(getStart(), fCompletion); - // } catch (JavaModelException e) { - // // ignore - // } - // } - // } - // - // return fCompletion; - // } - - /** - * Returns the name of a guessed local array, null if no local array exists. - */ - // public String guessArray() { - // return firstOrNull(guessArrays()); - // } - /** - * Returns the name of a guessed local array, null if no local array exists. - */ - // public String[] guessArrays() { - // CompilationUnitCompletion completion= getCompletion(); - // LocalVariable[] localArrays= completion.findLocalArrays(); - // - // String[] ret= new String[localArrays.length]; - // for (int i= 0; i < ret.length; i++) { - // ret[ret.length - i - 1]= localArrays[i].name; - // } - // return ret; - // } - /** - * Returns the name of the type of a local array, null if no local array exists. - */ - // public String guessArrayType() { - // return firstOrNull(guessArrayTypes()); - // } - private String firstOrNull(String[] strings) { - if (strings.length > 0) - return strings[0]; - else - return null; - } - - /** - * Returns the name of the type of a local array, null if no local array exists. - */ - // public String[][] guessGroupedArrayTypes() { - // CompilationUnitCompletion completion= getCompletion(); - // LocalVariable[] localArrays= completion.findLocalArrays(); - // - // String[][] ret= new String[localArrays.length][]; - // - // for (int i= 0; i < localArrays.length; i++) { - // String type= getArrayTypeFromLocalArray(completion, localArrays[localArrays.length - i - 1]); - // ret[i]= new String[] {type}; - // } - // - // return ret; - // } - /** - * Returns the name of the type of a local array, null if no local array exists. - */ - // public String[] guessArrayTypes() { - // CompilationUnitCompletion completion= getCompletion(); - // LocalVariable[] localArrays= completion.findLocalArrays(); - // - // List ret= new ArrayList(); - // - // for (int i= 0; i < localArrays.length; i++) { - // String type= getArrayTypeFromLocalArray(completion, localArrays[localArrays.length - i - 1]); - // if (!ret.contains(type)) - // ret.add(type); - // } - // - // return (String[]) ret.toArray(new String[ret.size()]); - // } - private String getArrayTypeFromLocalArray(CompilationUnitCompletion completion, LocalVariable array) { - String arrayTypeName = array.typeName; - String typeName = getScalarType(arrayTypeName); - int dimension = getArrayDimension(arrayTypeName) - 1; - Assert.isTrue(dimension >= 0); - - String qualifiedName = createQualifiedTypeName(array.typePackageName, typeName); - String innerTypeName = completion.simplifyTypeName(qualifiedName); - - return innerTypeName == null ? createArray(typeName, dimension) : createArray(innerTypeName, dimension); - } - - private static String createArray(String type, int dimension) { - StringBuffer buffer = new StringBuffer(type); - for (int i = 0; i < dimension; i++) - buffer.append("[]"); //$NON-NLS-1$ - return buffer.toString(); - } - - private static String getScalarType(String type) { - return type.substring(0, type.indexOf('[')); - } - - private static int getArrayDimension(String type) { - - int dimension = 0; - int index = type.indexOf('['); - - while (index != -1) { - dimension++; - index = type.indexOf('[', index + 1); - } - - return dimension; - } - - private static String createQualifiedTypeName(String packageName, String className) { - StringBuffer buffer = new StringBuffer(); - - if (packageName.length() != 0) { - buffer.append(packageName); - buffer.append('.'); - } - buffer.append(className); - - return buffer.toString(); - } - - /** - * Returns a proposal for a variable name of a local array element, null if no local array exists. - */ - // public String guessArrayElement() { - // return firstOrNull(guessArrayElements()); - // } - /** - * Returns a proposal for a variable name of a local array element, null if no local array exists. - */ - // public String[] guessArrayElements() { - // ICompilationUnit cu= getCompilationUnit(); - // if (cu == null) { - // return new String[0]; - // } - // - // CompilationUnitCompletion completion= getCompletion(); - // LocalVariable[] localArrays= completion.findLocalArrays(); - // - // List ret= new ArrayList(); - // - // for (int i= 0; i < localArrays.length; i++) { - // int idx= localArrays.length - i - 1; - // - // LocalVariable var= localArrays[idx]; - // - // IJavaProject project= cu.getJavaProject(); - // String typeName= var.typeName; - // String baseTypeName= typeName.substring(0, typeName.lastIndexOf('[')); - // - // String indexName= getIndex(); - // String[] excludedNames= completion.getLocalVariableNames(); - // if (indexName != null) { - // ArrayList excludedNamesList= new ArrayList(Arrays.asList(excludedNames)); - // excludedNamesList.add(indexName); - // excludedNames= (String[])excludedNamesList.toArray(new String[excludedNamesList.size()]); - // } - // String[] proposals= NamingConventions.suggestLocalVariableNames(project, var.typePackageName, baseTypeName, 0, excludedNames); - // for (int j= 0; j < proposals.length; j++) { - // if (!ret.contains(proposals[j])) - // ret.add(proposals[j]); - // } - // } - // - // return (String[]) ret.toArray(new String[ret.size()]); - // } - /** - * Returns a proposal for a variable name of a local array element, null if no local array exists. - */ - // public String[][] guessGroupedArrayElements() { - // ICompilationUnit cu= getCompilationUnit(); - // if (cu == null) { - // return new String[0][]; - // } - // - // CompilationUnitCompletion completion= getCompletion(); - // LocalVariable[] localArrays= completion.findLocalArrays(); - // - // String[][] ret= new String[localArrays.length][]; - // - // for (int i= 0; i < localArrays.length; i++) { - // int idx= localArrays.length - i - 1; - // - // LocalVariable var= localArrays[idx]; - // - // IJavaProject project= cu.getJavaProject(); - // String typeName= var.typeName; - // int dim= -1; // we expect at least one array - // int lastIndex= typeName.length(); - // int bracket= typeName.lastIndexOf('['); - // while (bracket != -1) { - // lastIndex= bracket; - // dim++; - // bracket= typeName.lastIndexOf('[', bracket - 1); - // } - // typeName= typeName.substring(0, lastIndex); - // - // String indexName= getIndex(); - // String[] excludedNames= completion.getLocalVariableNames(); - // if (indexName != null) { - // ArrayList excludedNamesList= new ArrayList(Arrays.asList(excludedNames)); - // excludedNamesList.add(indexName); - // excludedNames= (String[])excludedNamesList.toArray(new String[excludedNamesList.size()]); - // } - // String[] proposals= NamingConventions.suggestLocalVariableNames(project, var.typePackageName, typeName, dim, excludedNames); - // - // ret[i]= proposals; - // } - // - // return ret; - // } - /** - * Returns an array index name. 'i', 'j', 'k' are tried until no name collision with an existing local variable occurs. If all - * names collide, null is returned. - */ - // public String getIndex() { - // CompilationUnitCompletion completion= getCompletion(); - // String[] proposals= {"i", "j", "k"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - // - // for (int i= 0; i != proposals.length; i++) { - // String proposal = proposals[i]; - // - // if (!completion.existsLocalName(proposal)) - // return proposal; - // } - // - // return null; - // } - /** - * Returns the name of a local collection, null if no local collection exists. - */ - // public String guessCollection() { - // return firstOrNull(guessCollections()); - // } - /** - * Returns the names of local collections. - */ - // public String[] guessCollections() { - // CompilationUnitCompletion completion= getCompletion(); - // try { - // LocalVariable[] localCollections= completion.findLocalCollections(); - // String[] ret= new String[localCollections.length]; - // for (int i= 0; i < ret.length; i++) { - // ret[ret.length - i - 1]= localCollections[i].name; - // } - // - // return ret; - // - // } catch (JavaModelException e) { - // JavaPlugin.log(e); - // } - // - // return new String[0]; - // } - /** - * Returns an iterator name ('iter'). If 'iter' already exists as local variable, null is returned. - */ - // public String getIterator() { - // CompilationUnitCompletion completion= getCompletion(); - // String[] proposals= {"iter"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - // - // for (int i= 0; i != proposals.length; i++) { - // String proposal = proposals[i]; - // - // if (!completion.existsLocalName(proposal)) - // return proposal; - // } - // - // return null; - // } - // public void addIteratorImport() { - // ICompilationUnit cu= getCompilationUnit(); - // if (cu == null) { - // return; - // } - // - // try { - // Position position= new Position(getCompletionOffset(), getCompletionLength()); - // IDocument document= getDocument(); - // final String category= "__template_position_importer" + System.currentTimeMillis(); //$NON-NLS-1$ - // IPositionUpdater updater= new DefaultPositionUpdater(category); - // document.addPositionCategory(category); - // document.addPositionUpdater(updater); - // document.addPosition(position); - // - // CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); - // ImportsStructure structure= new ImportsStructure(cu, settings.importOrder, settings.importThreshold, true); - // structure.addImport("java.util.Iterator"); //$NON-NLS-1$ - // structure.create(false, null); - // - // document.removePosition(position); - // document.removePositionUpdater(updater); - // document.removePositionCategory(category); - // - // setCompletionOffset(position.getOffset()); - // setCompletionLength(position.getLength()); - // - // } catch (CoreException e) { - // handleException(null, e); - // } catch (BadLocationException e) { - // handleException(null, e); - // } catch (BadPositionCategoryException e) { - // handleException(null, e); - // } - // } - /** - * Evaluates a 'java' template in thecontext of a compilation unit - */ - public static String evaluateTemplate(Template template, ICompilationUnit compilationUnit, int position) throws CoreException, - BadLocationException, TemplateException { - - TemplateContextType contextType = PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType("java"); //$NON-NLS-1$ - if (contextType == null) - throw new CoreException(new Status(IStatus.ERROR, PHPeclipsePlugin.PLUGIN_ID, IStatus.ERROR, JavaTemplateMessages - .getString("JavaContext.error.message"), null)); //$NON-NLS-1$ - - IDocument document = new Document(); - if (compilationUnit != null && compilationUnit.exists()) - document.set(compilationUnit.getSource()); - - JavaContext context = new JavaContext(contextType, document, position, 0, compilationUnit); - context.setForceEvaluation(true); - - TemplateBuffer buffer = context.evaluate(template); - if (buffer == null) - return null; - return buffer.getString(); - } + /** The platform default line delimiter. */ + private static final String PLATFORM_LINE_DELIMITER = System + .getProperty("line.separator"); //$NON-NLS-1$ + + /** A code completion requestor for guessing local variable names. */ + private CompilationUnitCompletion fCompletion; + + /** + * Creates a java template context. + * + * @param type + * the context type. + * @param document + * the document. + * @param completionOffset + * the completion offset within the document. + * @param completionLength + * the completion length. + * @param compilationUnit + * the compilation unit (may be null). + */ + public JavaContext(TemplateContextType type, IDocument document, + int completionOffset, int completionLength, + ICompilationUnit compilationUnit) { + super(type, document, completionOffset, completionLength, + compilationUnit); + } + + /** + * Returns the indentation level at the position of code completion. + */ + private int getIndentation() { + int start = getStart(); + IDocument document = getDocument(); + try { + IRegion region = document.getLineInformationOfOffset(start); + String lineContent = document.get(region.getOffset(), region + .getLength()); + return Strings.computeIndent(lineContent, + CodeFormatterPreferencePage.getTabSize()); + // return Strings.computeIndent(lineContent, + // CodeFormatterUtil.getTabWidth()); + } catch (BadLocationException e) { + return 0; + } + } + + /* + * @see TemplateContext#evaluate(Template template) + */ + public TemplateBuffer evaluate(Template template) + throws BadLocationException, TemplateException { + + if (!canEvaluate(template)) + throw new TemplateException(JavaTemplateMessages + .getString("Context.error.cannot.evaluate")); //$NON-NLS-1$ + + TemplateTranslator translator = new TemplateTranslator() { + /* + * @see org.eclipse.jface.text.templates.TemplateTranslator#createVariable(java.lang.String, + * java.lang.String, int[]) + */ + protected TemplateVariable createVariable(String type, String name, + int[] offsets) { + return new MultiVariable(type, name, offsets); + } + }; + TemplateBuffer buffer = translator.translate(template); + + getContextType().resolve(buffer, this); + String lineDelimiter = null; + try { + lineDelimiter = getDocument().getLineDelimiter(0); + } catch (BadLocationException e) { + } + + if (lineDelimiter == null) + lineDelimiter = PLATFORM_LINE_DELIMITER; + IPreferenceStore prefs = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + // axelcl start + // boolean useCodeFormatter = + // prefs.getBoolean(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER); + boolean useCodeFormatter = false; + // axelcl end + + JavaFormatter formatter = new JavaFormatter(lineDelimiter, + getIndentation(), useCodeFormatter); + formatter.format(buffer, this); + // debug start + // String res = buffer.getString(); + // res = res.replaceAll("\n","/n"); + // res = res.replaceAll("\t","/t"); + // System.out.println(res); + // debug end + return buffer; + } + + /* + * @see TemplateContext#canEvaluate(Template templates) + */ + public boolean canEvaluate(Template template) { + String key = getKey(); + + if (fForceEvaluation) + return true; + + return template.matches(key, getContextType().getId()) + && key.length() != 0 + && template.getName().toLowerCase().startsWith( + key.toLowerCase()); + } + + public boolean canEvaluate(String identifier) { + String prefix = getKey(); + return identifier.toLowerCase().startsWith(prefix.toLowerCase()); + } + + /* + * @see DocumentTemplateContext#getCompletionPosition(); + */ + public int getStart() { + + try { + IDocument document = getDocument(); + + if (getCompletionLength() == 0) { + + int start = getCompletionOffset(); + while ((start != 0) + && Character.isUnicodeIdentifierPart(document + .getChar(start - 1))) + start--; + + if ((start != 0) + && (Character.isUnicodeIdentifierStart(document + .getChar(start - 1)) || (document + .getChar(start - 1) == '$'))) + start--; + + return start; + + } else { + + int start = getCompletionOffset(); + int end = getCompletionOffset() + getCompletionLength(); + + while (start != 0 + && Character.isUnicodeIdentifierPart(document + .getChar(start - 1))) + start--; + if ((start != 0) + && (Character.isUnicodeIdentifierStart(document + .getChar(start - 1)) || (document + .getChar(start - 1) == '$'))) + start--; + while (start != end + && Character.isWhitespace(document.getChar(start))) + start++; + + if (start == end) + start = getCompletionOffset(); + + return start; + } + + } catch (BadLocationException e) { + return super.getStart(); + } + } + + /* + * @see net.sourceforge.phpdt.internal.corext.template.DocumentTemplateContext#getEnd() + */ + public int getEnd() { + + if (getCompletionLength() == 0) + return super.getEnd(); + + try { + IDocument document = getDocument(); + + int start = getCompletionOffset(); + int end = getCompletionOffset() + getCompletionLength(); + + while (start != end + && Character.isWhitespace(document.getChar(end - 1))) + end--; + + return end; + + } catch (BadLocationException e) { + return super.getEnd(); + } + } + + /* + * @see net.sourceforge.phpdt.internal.corext.template.DocumentTemplateContext#getKey() + */ + public String getKey() { + + // if (getCompletionLength() == 0) { + // return super.getKey(); + // } + + try { + IDocument document = getDocument(); + + int start = getStart(); + int end = getCompletionOffset(); + return start <= end ? document.get(start, end - start) : ""; //$NON-NLS-1$ + + } catch (BadLocationException e) { + return super.getKey(); + } + } + + /** + * Returns the character before start position of completion. + */ + public char getCharacterBeforeStart() { + int start = getStart(); + + try { + return start == 0 ? ' ' : getDocument().getChar(start - 1); + + } catch (BadLocationException e) { + return ' '; + } + } + + private static void handleException(Shell shell, Exception e) { + String title = JavaTemplateMessages + .getString("JavaContext.error.title"); //$NON-NLS-1$ + if (e instanceof CoreException) + ExceptionHandler.handle((CoreException) e, shell, title, null); + else if (e instanceof InvocationTargetException) + ExceptionHandler.handle((InvocationTargetException) e, shell, + title, null); + else { + PHPeclipsePlugin.log(e); + MessageDialog.openError(shell, title, e.getMessage()); + } + } + + // private CompilationUnitCompletion getCompletion() { + // ICompilationUnit compilationUnit= getCompilationUnit(); + // if (fCompletion == null) { + // fCompletion= new CompilationUnitCompletion(compilationUnit); + // + // if (compilationUnit != null) { + // try { + // compilationUnit.codeComplete(getStart(), fCompletion); + // } catch (JavaModelException e) { + // // ignore + // } + // } + // } + // + // return fCompletion; + // } + + /** + * Returns the name of a guessed local array, null if no + * local array exists. + */ + // public String guessArray() { + // return firstOrNull(guessArrays()); + // } + /** + * Returns the name of a guessed local array, null if no + * local array exists. + */ + // public String[] guessArrays() { + // CompilationUnitCompletion completion= getCompletion(); + // LocalVariable[] localArrays= completion.findLocalArrays(); + // + // String[] ret= new String[localArrays.length]; + // for (int i= 0; i < ret.length; i++) { + // ret[ret.length - i - 1]= localArrays[i].name; + // } + // return ret; + // } + /** + * Returns the name of the type of a local array, null if no + * local array exists. + */ + // public String guessArrayType() { + // return firstOrNull(guessArrayTypes()); + // } + private String firstOrNull(String[] strings) { + if (strings.length > 0) + return strings[0]; + else + return null; + } + + /** + * Returns the name of the type of a local array, null if no + * local array exists. + */ + // public String[][] guessGroupedArrayTypes() { + // CompilationUnitCompletion completion= getCompletion(); + // LocalVariable[] localArrays= completion.findLocalArrays(); + // + // String[][] ret= new String[localArrays.length][]; + // + // for (int i= 0; i < localArrays.length; i++) { + // String type= getArrayTypeFromLocalArray(completion, + // localArrays[localArrays.length - i - 1]); + // ret[i]= new String[] {type}; + // } + // + // return ret; + // } + /** + * Returns the name of the type of a local array, null if no + * local array exists. + */ + // public String[] guessArrayTypes() { + // CompilationUnitCompletion completion= getCompletion(); + // LocalVariable[] localArrays= completion.findLocalArrays(); + // + // List ret= new ArrayList(); + // + // for (int i= 0; i < localArrays.length; i++) { + // String type= getArrayTypeFromLocalArray(completion, + // localArrays[localArrays.length - i - 1]); + // if (!ret.contains(type)) + // ret.add(type); + // } + // + // return (String[]) ret.toArray(new String[ret.size()]); + // } + private String getArrayTypeFromLocalArray( + CompilationUnitCompletion completion, LocalVariable array) { + String arrayTypeName = array.typeName; + String typeName = getScalarType(arrayTypeName); + int dimension = getArrayDimension(arrayTypeName) - 1; + Assert.isTrue(dimension >= 0); + + String qualifiedName = createQualifiedTypeName(array.typePackageName, + typeName); + String innerTypeName = completion.simplifyTypeName(qualifiedName); + + return innerTypeName == null ? createArray(typeName, dimension) + : createArray(innerTypeName, dimension); + } + + private static String createArray(String type, int dimension) { + StringBuffer buffer = new StringBuffer(type); + for (int i = 0; i < dimension; i++) + buffer.append("[]"); //$NON-NLS-1$ + return buffer.toString(); + } + + private static String getScalarType(String type) { + return type.substring(0, type.indexOf('[')); + } + + private static int getArrayDimension(String type) { + + int dimension = 0; + int index = type.indexOf('['); + + while (index != -1) { + dimension++; + index = type.indexOf('[', index + 1); + } + + return dimension; + } + + private static String createQualifiedTypeName(String packageName, + String className) { + StringBuffer buffer = new StringBuffer(); + + if (packageName.length() != 0) { + buffer.append(packageName); + buffer.append('.'); + } + buffer.append(className); + + return buffer.toString(); + } + + /** + * Returns a proposal for a variable name of a local array element, + * null if no local array exists. + */ + // public String guessArrayElement() { + // return firstOrNull(guessArrayElements()); + // } + /** + * Returns a proposal for a variable name of a local array element, + * null if no local array exists. + */ + // public String[] guessArrayElements() { + // ICompilationUnit cu= getCompilationUnit(); + // if (cu == null) { + // return new String[0]; + // } + // + // CompilationUnitCompletion completion= getCompletion(); + // LocalVariable[] localArrays= completion.findLocalArrays(); + // + // List ret= new ArrayList(); + // + // for (int i= 0; i < localArrays.length; i++) { + // int idx= localArrays.length - i - 1; + // + // LocalVariable var= localArrays[idx]; + // + // IJavaProject project= cu.getJavaProject(); + // String typeName= var.typeName; + // String baseTypeName= typeName.substring(0, typeName.lastIndexOf('[')); + // + // String indexName= getIndex(); + // String[] excludedNames= completion.getLocalVariableNames(); + // if (indexName != null) { + // ArrayList excludedNamesList= new ArrayList(Arrays.asList(excludedNames)); + // excludedNamesList.add(indexName); + // excludedNames= (String[])excludedNamesList.toArray(new + // String[excludedNamesList.size()]); + // } + // String[] proposals= NamingConventions.suggestLocalVariableNames(project, + // var.typePackageName, baseTypeName, 0, excludedNames); + // for (int j= 0; j < proposals.length; j++) { + // if (!ret.contains(proposals[j])) + // ret.add(proposals[j]); + // } + // } + // + // return (String[]) ret.toArray(new String[ret.size()]); + // } + /** + * Returns a proposal for a variable name of a local array element, + * null if no local array exists. + */ + // public String[][] guessGroupedArrayElements() { + // ICompilationUnit cu= getCompilationUnit(); + // if (cu == null) { + // return new String[0][]; + // } + // + // CompilationUnitCompletion completion= getCompletion(); + // LocalVariable[] localArrays= completion.findLocalArrays(); + // + // String[][] ret= new String[localArrays.length][]; + // + // for (int i= 0; i < localArrays.length; i++) { + // int idx= localArrays.length - i - 1; + // + // LocalVariable var= localArrays[idx]; + // + // IJavaProject project= cu.getJavaProject(); + // String typeName= var.typeName; + // int dim= -1; // we expect at least one array + // int lastIndex= typeName.length(); + // int bracket= typeName.lastIndexOf('['); + // while (bracket != -1) { + // lastIndex= bracket; + // dim++; + // bracket= typeName.lastIndexOf('[', bracket - 1); + // } + // typeName= typeName.substring(0, lastIndex); + // + // String indexName= getIndex(); + // String[] excludedNames= completion.getLocalVariableNames(); + // if (indexName != null) { + // ArrayList excludedNamesList= new ArrayList(Arrays.asList(excludedNames)); + // excludedNamesList.add(indexName); + // excludedNames= (String[])excludedNamesList.toArray(new + // String[excludedNamesList.size()]); + // } + // String[] proposals= NamingConventions.suggestLocalVariableNames(project, + // var.typePackageName, typeName, dim, excludedNames); + // + // ret[i]= proposals; + // } + // + // return ret; + // } + /** + * Returns an array index name. 'i', 'j', 'k' are tried until no name + * collision with an existing local variable occurs. If all names collide, + * null is returned. + */ + // public String getIndex() { + // CompilationUnitCompletion completion= getCompletion(); + // String[] proposals= {"i", "j", "k"}; //$NON-NLS-1$ //$NON-NLS-2$ + // //$NON-NLS-3$ + // + // for (int i= 0; i != proposals.length; i++) { + // String proposal = proposals[i]; + // + // if (!completion.existsLocalName(proposal)) + // return proposal; + // } + // + // return null; + // } + /** + * Returns the name of a local collection, null if no local + * collection exists. + */ + // public String guessCollection() { + // return firstOrNull(guessCollections()); + // } + /** + * Returns the names of local collections. + */ + // public String[] guessCollections() { + // CompilationUnitCompletion completion= getCompletion(); + // try { + // LocalVariable[] localCollections= completion.findLocalCollections(); + // String[] ret= new String[localCollections.length]; + // for (int i= 0; i < ret.length; i++) { + // ret[ret.length - i - 1]= localCollections[i].name; + // } + // + // return ret; + // + // } catch (JavaModelException e) { + // JavaPlugin.log(e); + // } + // + // return new String[0]; + // } + /** + * Returns an iterator name ('iter'). If 'iter' already exists as local + * variable, null is returned. + */ + // public String getIterator() { + // CompilationUnitCompletion completion= getCompletion(); + // String[] proposals= {"iter"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + // + // for (int i= 0; i != proposals.length; i++) { + // String proposal = proposals[i]; + // + // if (!completion.existsLocalName(proposal)) + // return proposal; + // } + // + // return null; + // } + // public void addIteratorImport() { + // ICompilationUnit cu= getCompilationUnit(); + // if (cu == null) { + // return; + // } + // + // try { + // Position position= new Position(getCompletionOffset(), + // getCompletionLength()); + // IDocument document= getDocument(); + // final String category= "__template_position_importer" + + // System.currentTimeMillis(); //$NON-NLS-1$ + // IPositionUpdater updater= new DefaultPositionUpdater(category); + // document.addPositionCategory(category); + // document.addPositionUpdater(updater); + // document.addPosition(position); + // + // CodeGenerationSettings settings= + // JavaPreferencesSettings.getCodeGenerationSettings(); + // ImportsStructure structure= new ImportsStructure(cu, + // settings.importOrder, settings.importThreshold, true); + // structure.addImport("java.util.Iterator"); //$NON-NLS-1$ + // structure.create(false, null); + // + // document.removePosition(position); + // document.removePositionUpdater(updater); + // document.removePositionCategory(category); + // + // setCompletionOffset(position.getOffset()); + // setCompletionLength(position.getLength()); + // + // } catch (CoreException e) { + // handleException(null, e); + // } catch (BadLocationException e) { + // handleException(null, e); + // } catch (BadPositionCategoryException e) { + // handleException(null, e); + // } + // } + /** + * Evaluates a 'java' template in thecontext of a compilation unit + */ + public static String evaluateTemplate(Template template, + ICompilationUnit compilationUnit, int position) + throws CoreException, BadLocationException, TemplateException { + + TemplateContextType contextType = PHPeclipsePlugin.getDefault() + .getTemplateContextRegistry().getContextType("java"); //$NON-NLS-1$ + if (contextType == null) + throw new CoreException( + new Status( + IStatus.ERROR, + PHPeclipsePlugin.PLUGIN_ID, + IStatus.ERROR, + JavaTemplateMessages + .getString("JavaContext.error.message"), null)); //$NON-NLS-1$ + + IDocument document = new Document(); + if (compilationUnit != null && compilationUnit.exists()) + document.set(compilationUnit.getSource()); + + JavaContext context = new JavaContext(contextType, document, position, + 0, compilationUnit); + context.setForceEvaluation(true); + + TemplateBuffer buffer = context.evaluate(template); + if (buffer == null) + return null; + return buffer.getString(); + } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaContextType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaContextType.java index db516f7..f121bdf 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaContextType.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaContextType.java @@ -19,187 +19,204 @@ import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.templates.GlobalTemplateVariables; import org.eclipse.jface.text.templates.TemplateContext; import org.eclipse.jface.text.templates.TemplateVariableResolver; -//import net.sourceforge.phpdt.internal.ui.text.template.contentassist.*; -//import net.sourceforge.phpdt.internal.ui.text.template.contentassist.MultiVariableGuess; /** * A context type for java code. */ public class JavaContextType extends CompilationUnitContextType { - public static final String NAME= "php"; //$NON-NLS-1$ - -// protected static class Array extends TemplateVariableResolver { -// public Array() { -// super("array", TemplateMessages.getString("JavaContextType.variable.description.array")); //$NON-NLS-1$ //$NON-NLS-2$ -// } -// protected String[] resolveAll(TemplateContext context) { -// return ((JavaContext) context).guessArrays(); -// } -// /* -// * @see org.eclipse.jface.text.templates.TemplateVariableResolver#resolve(org.eclipse.jface.text.templates.TemplateVariable, org.eclipse.jface.text.templates.TemplateContext) -// */ -// public void resolve(TemplateVariable variable, TemplateContext context) { -// if (variable instanceof MultiVariable) { -// JavaContext jc= (JavaContext) context; -// MultiVariable mv= (MultiVariable) variable; -// String[] bindings= resolveAll(context); -// if (bindings.length > 0) { -// mv.setValues(bindings); -// MultiVariableGuess guess= jc.getMultiVariableGuess(); -// if (guess == null) { -// guess= new MultiVariableGuess(mv); -// jc.setMultiVariableGuess(guess); -// } -// } -// if (bindings.length > 1) -// variable.setUnambiguous(false); -// else -// variable.setUnambiguous(isUnambiguous(context)); -// } else -// super.resolve(variable, context); -// } -// } -// -// protected static class ArrayType extends TemplateVariableResolver { -// public ArrayType() { -// super("array_type", TemplateMessages.getString("JavaContextType.variable.description.array.type")); //$NON-NLS-1$ //$NON-NLS-2$ -// } -// protected String[] resolveAll(TemplateContext context) { -// -// String[] arrayTypes= ((JavaContext) context).guessArrayTypes(); -// if (arrayTypes != null) -// return arrayTypes; -// else -// return super.resolveAll(context); -// } -// -// /* -// * @see org.eclipse.jface.text.templates.TemplateVariableResolver#resolve(org.eclipse.jface.text.templates.TemplateVariable, org.eclipse.jface.text.templates.TemplateContext) -// */ -// public void resolve(TemplateVariable variable, TemplateContext context) { -// if (variable instanceof MultiVariable) { -// MultiVariable mv= (MultiVariable) variable; -// String[] arrays= ((JavaContext) context).guessArrays(); -// String[][] types= ((JavaContext) context).guessGroupedArrayTypes(); -// -// for (int i= 0; i < arrays.length; i++) { -// mv.setValues(arrays[i], types[i]); -// } -// -// if (arrays.length > 1 || types.length == 1 && types[0].length > 1) -// variable.setUnambiguous(false); -// else -// variable.setUnambiguous(isUnambiguous(context)); -// -// } else -// super.resolve(variable, context); -// } -// } -// -// protected static class ArrayElement extends TemplateVariableResolver { -// public ArrayElement() { -// super("array_element", TemplateMessages.getString("JavaContextType.variable.description.array.element")); //$NON-NLS-1$ //$NON-NLS-2$ -// } -// protected String[] resolveAll(TemplateContext context) { -// return ((JavaContext) context).guessArrayElements(); -// } -// -// /* -// * @see org.eclipse.jface.text.templates.TemplateVariableResolver#resolve(org.eclipse.jface.text.templates.TemplateVariable, org.eclipse.jface.text.templates.TemplateContext) -// */ -// public void resolve(TemplateVariable variable, TemplateContext context) { -// if (variable instanceof MultiVariable) { -// MultiVariable mv= (MultiVariable) variable; -// String[] arrays= ((JavaContext) context).guessArrays(); -// String[][] elems= ((JavaContext) context).guessGroupedArrayElements(); -// -// for (int i= 0; i < arrays.length; i++) { -// mv.setValues(arrays[i], elems[i]); -// } -// -// if (arrays.length > 1 || elems.length == 1 && elems[0].length > 1) -// variable.setUnambiguous(false); -// else -// variable.setUnambiguous(isUnambiguous(context)); -// -// } else -// super.resolve(variable, context); -// } -// } -// -// protected static class Index extends TemplateVariableResolver { -// public Index() { -// super("index", TemplateMessages.getString("JavaContextType.variable.description.index")); //$NON-NLS-1$ //$NON-NLS-2$ -// } -// protected String resolve(TemplateContext context) { -// return ((JavaContext) context).getIndex(); -// } -// } -// -// protected static class Collection extends TemplateVariableResolver { -// public Collection() { -// super("collection", TemplateMessages.getString("JavaContextType.variable.description.collection")); //$NON-NLS-1$ //$NON-NLS-2$ -// } -// -// protected String[] resolveAll(TemplateContext context) { -// String[] collections= ((JavaContext) context).guessCollections(); -// if (collections.length > 0) -// return collections; -// else -// return super.resolveAll(context); -// } -// } -// -// protected static class Iterator extends TemplateVariableResolver { -// -// public Iterator() { -// super("iterator", TemplateMessages.getString("JavaContextType.variable.description.iterator")); //$NON-NLS-1$ //$NON-NLS-2$ -// } -// protected String resolve(TemplateContext context) { -// JavaContext javaContext= (JavaContext) context; -// -// if (!context.isReadOnly()) -// javaContext.addIteratorImport(); -// -// return javaContext.getIterator(); -// } -// } -// + public static final String NAME = "php"; //$NON-NLS-1$ + + // protected static class Array extends TemplateVariableResolver { + // public Array() { + // super("array", + // TemplateMessages.getString("JavaContextType.variable.description.array")); + // //$NON-NLS-1$ //$NON-NLS-2$ + // } + // protected String[] resolveAll(TemplateContext context) { + // return ((JavaContext) context).guessArrays(); + // } + // /* + // * @see + // org.eclipse.jface.text.templates.TemplateVariableResolver#resolve(org.eclipse.jface.text.templates.TemplateVariable, + // org.eclipse.jface.text.templates.TemplateContext) + // */ + // public void resolve(TemplateVariable variable, TemplateContext context) { + // if (variable instanceof MultiVariable) { + // JavaContext jc= (JavaContext) context; + // MultiVariable mv= (MultiVariable) variable; + // String[] bindings= resolveAll(context); + // if (bindings.length > 0) { + // mv.setValues(bindings); + // MultiVariableGuess guess= jc.getMultiVariableGuess(); + // if (guess == null) { + // guess= new MultiVariableGuess(mv); + // jc.setMultiVariableGuess(guess); + // } + // } + // if (bindings.length > 1) + // variable.setUnambiguous(false); + // else + // variable.setUnambiguous(isUnambiguous(context)); + // } else + // super.resolve(variable, context); + // } + // } + // + // protected static class ArrayType extends TemplateVariableResolver { + // public ArrayType() { + // super("array_type", + // TemplateMessages.getString("JavaContextType.variable.description.array.type")); + // //$NON-NLS-1$ //$NON-NLS-2$ + // } + // protected String[] resolveAll(TemplateContext context) { + // + // String[] arrayTypes= ((JavaContext) context).guessArrayTypes(); + // if (arrayTypes != null) + // return arrayTypes; + // else + // return super.resolveAll(context); + // } + // + // /* + // * @see + // org.eclipse.jface.text.templates.TemplateVariableResolver#resolve(org.eclipse.jface.text.templates.TemplateVariable, + // org.eclipse.jface.text.templates.TemplateContext) + // */ + // public void resolve(TemplateVariable variable, TemplateContext context) { + // if (variable instanceof MultiVariable) { + // MultiVariable mv= (MultiVariable) variable; + // String[] arrays= ((JavaContext) context).guessArrays(); + // String[][] types= ((JavaContext) context).guessGroupedArrayTypes(); + // + // for (int i= 0; i < arrays.length; i++) { + // mv.setValues(arrays[i], types[i]); + // } + // + // if (arrays.length > 1 || types.length == 1 && types[0].length > 1) + // variable.setUnambiguous(false); + // else + // variable.setUnambiguous(isUnambiguous(context)); + // + // } else + // super.resolve(variable, context); + // } + // } + // + // protected static class ArrayElement extends TemplateVariableResolver { + // public ArrayElement() { + // super("array_element", + // TemplateMessages.getString("JavaContextType.variable.description.array.element")); + // //$NON-NLS-1$ //$NON-NLS-2$ + // } + // protected String[] resolveAll(TemplateContext context) { + // return ((JavaContext) context).guessArrayElements(); + // } + // + // /* + // * @see + // org.eclipse.jface.text.templates.TemplateVariableResolver#resolve(org.eclipse.jface.text.templates.TemplateVariable, + // org.eclipse.jface.text.templates.TemplateContext) + // */ + // public void resolve(TemplateVariable variable, TemplateContext context) { + // if (variable instanceof MultiVariable) { + // MultiVariable mv= (MultiVariable) variable; + // String[] arrays= ((JavaContext) context).guessArrays(); + // String[][] elems= ((JavaContext) context).guessGroupedArrayElements(); + // + // for (int i= 0; i < arrays.length; i++) { + // mv.setValues(arrays[i], elems[i]); + // } + // + // if (arrays.length > 1 || elems.length == 1 && elems[0].length > 1) + // variable.setUnambiguous(false); + // else + // variable.setUnambiguous(isUnambiguous(context)); + // + // } else + // super.resolve(variable, context); + // } + // } + // + // protected static class Index extends TemplateVariableResolver { + // public Index() { + // super("index", + // TemplateMessages.getString("JavaContextType.variable.description.index")); + // //$NON-NLS-1$ //$NON-NLS-2$ + // } + // protected String resolve(TemplateContext context) { + // return ((JavaContext) context).getIndex(); + // } + // } + // + // protected static class Collection extends TemplateVariableResolver { + // public Collection() { + // super("collection", + // TemplateMessages.getString("JavaContextType.variable.description.collection")); + // //$NON-NLS-1$ //$NON-NLS-2$ + // } + // + // protected String[] resolveAll(TemplateContext context) { + // String[] collections= ((JavaContext) context).guessCollections(); + // if (collections.length > 0) + // return collections; + // else + // return super.resolveAll(context); + // } + // } + // + // protected static class Iterator extends TemplateVariableResolver { + // + // public Iterator() { + // super("iterator", + // TemplateMessages.getString("JavaContextType.variable.description.iterator")); + // //$NON-NLS-1$ //$NON-NLS-2$ + // } + // protected String resolve(TemplateContext context) { + // JavaContext javaContext= (JavaContext) context; + // + // if (!context.isReadOnly()) + // javaContext.addIteratorImport(); + // + // return javaContext.getIterator(); + // } + // } + // protected static class Todo extends TemplateVariableResolver { public Todo() { - super("todo", JavaTemplateMessages.getString("JavaContextType.variable.description.todo")); //$NON-NLS-1$ //$NON-NLS-2$ + super( + "todo", JavaTemplateMessages.getString("JavaContextType.variable.description.todo")); //$NON-NLS-1$ //$NON-NLS-2$ } + protected String resolve(TemplateContext context) { - JavaContext javaContext= (JavaContext) context; - ICompilationUnit compilationUnit= javaContext.getCompilationUnit(); + JavaContext javaContext = (JavaContext) context; + ICompilationUnit compilationUnit = javaContext.getCompilationUnit(); if (compilationUnit == null) return "XXX"; //$NON-NLS-1$ - - IJavaProject javaProject= compilationUnit.getJavaProject(); - String todoTaskTag= StubUtility.getTodoTaskTag(javaProject); + + IJavaProject javaProject = compilationUnit.getJavaProject(); + String todoTaskTag = StubUtility.getTodoTaskTag(javaProject); if (todoTaskTag == null) return "XXX"; //$NON-NLS-1$ return todoTaskTag; } - } -/* - protected static class Arguments extends SimpleVariableResolver { - public Arguments() { - super("arguments", TemplateMessages.getString("JavaContextType.variable.description.arguments"), ""); - } } -*/ + /* + * protected static class Arguments extends SimpleVariableResolver { public + * Arguments() { super("arguments", + * TemplateMessages.getString("JavaContextType.variable.description.arguments"), + * ""); } } + */ /** * Creates a java context type. */ public JavaContextType() { super(NAME); - + // global addResolver(new GlobalTemplateVariables.Cursor()); addResolver(new GlobalTemplateVariables.WordSelection()); @@ -209,7 +226,7 @@ public class JavaContextType extends CompilationUnitContextType { addResolver(new GlobalTemplateVariables.Year()); addResolver(new GlobalTemplateVariables.Time()); addResolver(new GlobalTemplateVariables.User()); - + // compilation unit addResolver(new File()); addResolver(new PrimaryTypeName()); @@ -221,20 +238,23 @@ public class JavaContextType extends CompilationUnitContextType { addResolver(new Arguments()); // java -// addResolver(new Array()); -// addResolver(new ArrayType()); -// addResolver(new ArrayElement()); -// addResolver(new Index()); -// addResolver(new Iterator()); -// addResolver(new Collection()); + // addResolver(new Array()); + // addResolver(new ArrayType()); + // addResolver(new ArrayElement()); + // addResolver(new Index()); + // addResolver(new Iterator()); + // addResolver(new Collection()); addResolver(new Todo()); } - - /* (non-Javadoc) - * @see net.sourceforge.phpdt.internal.corext.template.java.CompilationUnitContextType#createContext(org.eclipse.jface.text.IDocument, int, int, net.sourceforge.phpdt.core.ICompilationUnit) + /* + * (non-Javadoc) + * + * @see net.sourceforge.phpdt.internal.corext.template.java.CompilationUnitContextType#createContext(org.eclipse.jface.text.IDocument, + * int, int, net.sourceforge.phpdt.core.ICompilationUnit) */ - public CompilationUnitContext createContext(IDocument document, int offset, int length, ICompilationUnit compilationUnit) { + public CompilationUnitContext createContext(IDocument document, int offset, + int length, ICompilationUnit compilationUnit) { return new JavaContext(this, document, offset, length, compilationUnit); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaDocContext.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaDocContext.java index 5f07c83..9377103 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaDocContext.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaDocContext.java @@ -20,94 +20,109 @@ import org.eclipse.jface.text.templates.TemplateContextType; import org.eclipse.jface.text.templates.TemplateException; import org.eclipse.jface.text.templates.TemplateTranslator; - /** * A context for javadoc. */ public class JavaDocContext extends CompilationUnitContext { // tags - private static final char HTML_TAG_BEGIN= '<'; - private static final char HTML_TAG_END= '>'; - private static final char JAVADOC_TAG_BEGIN= '@'; + private static final char HTML_TAG_BEGIN = '<'; + + private static final char HTML_TAG_END = '>'; + + private static final char JAVADOC_TAG_BEGIN = '@'; /** * Creates a javadoc template context. * - * @param type the context type. - * @param document the document. - * @param completionOffset the completion offset within the document. - * @param completionLength the completion length within the document. - * @param compilationUnit the compilation unit (may be null). + * @param type + * the context type. + * @param document + * the document. + * @param completionOffset + * the completion offset within the document. + * @param completionLength + * the completion length within the document. + * @param compilationUnit + * the compilation unit (may be null). */ - public JavaDocContext(TemplateContextType type, IDocument document, int completionOffset, int completionLength, - ICompilationUnit compilationUnit) - { - super(type, document, completionOffset, completionLength, compilationUnit); + public JavaDocContext(TemplateContextType type, IDocument document, + int completionOffset, int completionLength, + ICompilationUnit compilationUnit) { + super(type, document, completionOffset, completionLength, + compilationUnit); } /* * @see TemplateContext#canEvaluate(Template templates) */ public boolean canEvaluate(Template template) { - String key= getKey(); - + String key = getKey(); + if (fForceEvaluation) return true; - return - template.matches(key, getContextType().getId()) && - (key.length() != 0) && template.getName().toLowerCase().startsWith(key.toLowerCase()); + return template.matches(key, getContextType().getId()) + && (key.length() != 0) + && template.getName().toLowerCase().startsWith( + key.toLowerCase()); } /* * @see DocumentTemplateContext#getStart() - */ + */ public int getStart() { try { - IDocument document= getDocument(); + IDocument document = getDocument(); if (getCompletionLength() == 0) { - int start= getCompletionOffset(); - - if ((start != 0) && (document.getChar(start - 1) == HTML_TAG_END)) + int start = getCompletionOffset(); + + if ((start != 0) + && (document.getChar(start - 1) == HTML_TAG_END)) start--; - - while ((start != 0) && Character.isUnicodeIdentifierPart(document.getChar(start - 1))) + + while ((start != 0) + && Character.isUnicodeIdentifierPart(document + .getChar(start - 1))) start--; - - if ((start != 0) && Character.isUnicodeIdentifierStart(document.getChar(start - 1))) + + if ((start != 0) + && Character.isUnicodeIdentifierStart(document + .getChar(start - 1))) start--; - + // include html and javadoc tags - if ((start != 0) && ( - (document.getChar(start - 1) == HTML_TAG_BEGIN) || - (document.getChar(start - 1) == JAVADOC_TAG_BEGIN))) - { + if ((start != 0) + && ((document.getChar(start - 1) == HTML_TAG_BEGIN) || (document + .getChar(start - 1) == JAVADOC_TAG_BEGIN))) { start--; - } - + } + return start; - + } else { - int start= getCompletionOffset(); - int end= getCompletionOffset() + getCompletionLength(); + int start = getCompletionOffset(); + int end = getCompletionOffset() + getCompletionLength(); - while (start != 0 && Character.isUnicodeIdentifierPart(document.getChar(start - 1))) + while (start != 0 + && Character.isUnicodeIdentifierPart(document + .getChar(start - 1))) start--; - - while (start != end && Character.isWhitespace(document.getChar(start))) + + while (start != end + && Character.isWhitespace(document.getChar(start))) start++; - + if (start == end) - start= getCompletionOffset(); - - return start; + start = getCompletionOffset(); + + return start; } } catch (BadLocationException e) { - return getCompletionOffset(); + return getCompletionOffset(); } } @@ -115,24 +130,25 @@ public class JavaDocContext extends CompilationUnitContext { * @see net.sourceforge.phpdt.internal.corext.template.DocumentTemplateContext#getEnd() */ public int getEnd() { - - if (getCompletionLength() == 0) + + if (getCompletionLength() == 0) return super.getEnd(); - try { - IDocument document= getDocument(); + try { + IDocument document = getDocument(); + + int start = getCompletionOffset(); + int end = getCompletionOffset() + getCompletionLength(); - int start= getCompletionOffset(); - int end= getCompletionOffset() + getCompletionLength(); - - while (start != end && Character.isWhitespace(document.getChar(end - 1))) + while (start != end + && Character.isWhitespace(document.getChar(end - 1))) end--; - - return end; + + return end; } catch (BadLocationException e) { return super.getEnd(); - } + } } /* @@ -140,34 +156,32 @@ public class JavaDocContext extends CompilationUnitContext { */ public String getKey() { - if (getCompletionLength() == 0) + if (getCompletionLength() == 0) return super.getKey(); try { - IDocument document= getDocument(); - - int start= getStart(); - int end= getCompletionOffset(); - return start <= end - ? document.get(start, end - start) - : ""; //$NON-NLS-1$ - + IDocument document = getDocument(); + + int start = getStart(); + int end = getCompletionOffset(); + return start <= end ? document.get(start, end - start) : ""; //$NON-NLS-1$ + } catch (BadLocationException e) { - return super.getKey(); + return super.getKey(); } } /* * @see TemplateContext#evaluate(Template) */ - public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException { - TemplateTranslator translator= new TemplateTranslator(); - TemplateBuffer buffer= translator.translate(template); + public TemplateBuffer evaluate(Template template) + throws BadLocationException, TemplateException { + TemplateTranslator translator = new TemplateTranslator(); + TemplateBuffer buffer = translator.translate(template); getContextType().resolve(buffer, this); - + return buffer; } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaDocContextType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaDocContextType.java index a09574e..e41fcc8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaDocContextType.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaDocContextType.java @@ -15,20 +15,19 @@ import net.sourceforge.phpdt.core.ICompilationUnit; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.templates.GlobalTemplateVariables; - /** * A context type for javadoc. */ public class JavaDocContextType extends CompilationUnitContextType { - public static final String NAME= "phpdoc"; //$NON-NLS-1$ + public static final String NAME = "phpdoc"; //$NON-NLS-1$ /** * Creates a java context type. */ public JavaDocContextType() { super(NAME); - + // global addResolver(new GlobalTemplateVariables.Cursor()); addResolver(new GlobalTemplateVariables.LineSelection()); @@ -38,7 +37,7 @@ public class JavaDocContextType extends CompilationUnitContextType { addResolver(new GlobalTemplateVariables.Year()); addResolver(new GlobalTemplateVariables.Time()); addResolver(new GlobalTemplateVariables.User()); - + // compilation unit addResolver(new File()); addResolver(new PrimaryTypeName()); @@ -49,12 +48,17 @@ public class JavaDocContextType extends CompilationUnitContextType { addResolver(new Package()); addResolver(new Project()); } - - /* (non-Javadoc) - * @see net.sourceforge.phpdt.internal.corext.template.java.CompilationUnitContextType#createContext(org.eclipse.jface.text.IDocument, int, int, net.sourceforge.phpdt.core.ICompilationUnit) + + /* + * (non-Javadoc) + * + * @see net.sourceforge.phpdt.internal.corext.template.java.CompilationUnitContextType#createContext(org.eclipse.jface.text.IDocument, + * int, int, net.sourceforge.phpdt.core.ICompilationUnit) */ - public CompilationUnitContext createContext(IDocument document, int offset, int length, ICompilationUnit compilationUnit) { - return new JavaDocContext(this, document, offset, length, compilationUnit); - } - + public CompilationUnitContext createContext(IDocument document, int offset, + int length, ICompilationUnit compilationUnit) { + return new JavaDocContext(this, document, offset, length, + compilationUnit); + } + } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaFormatter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaFormatter.java index 3b5456f..d1cd8bc 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaFormatter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaFormatter.java @@ -44,312 +44,349 @@ import org.eclipse.text.edits.TextEdit; */ public class JavaFormatter { - private static final String MARKER = "/*${" + GlobalTemplateVariables.Cursor.NAME + "}*/"; //$NON-NLS-1$ //$NON-NLS-2$ - - /** The line delimiter to use if code formatter is not used. */ - private final String fLineDelimiter; - - /** The initial indent level */ - private final int fInitialIndentLevel; - - /** The java partitioner */ - private boolean fUseCodeFormatter; - - /** - * Creates a JavaFormatter with the target line delimiter. - * - * @param lineDelimiter - * the line delimiter to use - * @param initialIndentLevel - * the initial indentation level - * @param useCodeFormatter - * true if the core code formatter should be used - */ - public JavaFormatter(String lineDelimiter, int initialIndentLevel, boolean useCodeFormatter) { - fLineDelimiter = lineDelimiter; - fUseCodeFormatter = useCodeFormatter; - fInitialIndentLevel = initialIndentLevel; - } - - /** - * Formats the template buffer. - * - * @param buffer - * @param context - * @throws BadLocationException - */ - public void format(TemplateBuffer buffer, TemplateContext context) throws BadLocationException { - try { - if (fUseCodeFormatter) - // try to format and fall back to indenting - try { - format(buffer, (JavaContext) context); - } catch (BadLocationException e) { - indent(buffer); - } catch (MalformedTreeException e) { - indent(buffer); - } - else - indent(buffer); - - // don't trim the buffer if the replacement area is empty - // case: surrounding empty lines with block - if (context instanceof DocumentTemplateContext) { - DocumentTemplateContext dtc = (DocumentTemplateContext) context; - if (dtc.getStart() == dtc.getCompletionOffset()) - if (dtc.getDocument().get(dtc.getStart(), dtc.getEnd() - dtc.getEnd()).trim().length() == 0) - return; - } - - trimBegin(buffer); - } catch (MalformedTreeException e) { - throw new BadLocationException(); - } - } - - private static int getCaretOffset(TemplateVariable[] variables) { - for (int i = 0; i != variables.length; i++) { - TemplateVariable variable = variables[i]; - - if (variable.getType().equals(GlobalTemplateVariables.Cursor.NAME)) - return variable.getOffsets()[0]; - } - - return -1; - } - - private boolean isInsideCommentOrString(String string, int offset) { - - IDocument document = new Document(string); - PHPeclipsePlugin.getDefault().getJavaTextTools().setupJavaDocumentPartitioner(document); - - try { - ITypedRegion partition = document.getPartition(offset); - String partitionType = partition.getType(); - - return partitionType != null - && (partitionType.equals(IPHPPartitions.PHP_MULTILINE_COMMENT) - || partitionType.equals(IPHPPartitions.PHP_SINGLELINE_COMMENT) || partitionType.equals(IPHPPartitions.PHP_STRING_DQ) - || partitionType.equals(IPHPPartitions.PHP_STRING_SQ) || partitionType.equals(IPHPPartitions.PHP_STRING_HEREDOC) || partitionType.equals(IPHPPartitions.PHP_PHPDOC_COMMENT)); - - } catch (BadLocationException e) { - return false; - } - } - - private void format(TemplateBuffer templateBuffer, JavaContext context) throws BadLocationException { - // XXX 4360, 15247 - // workaround for code formatter limitations - // handle a special case where cursor position is surrounded by whitespaces - - String string = templateBuffer.getString(); - TemplateVariable[] variables = templateBuffer.getVariables(); - - int caretOffset = getCaretOffset(variables); - if ((caretOffset > 0) && Character.isWhitespace(string.charAt(caretOffset - 1)) && (caretOffset < string.length()) - && Character.isWhitespace(string.charAt(caretOffset)) && !isInsideCommentOrString(string, caretOffset)) { - List positions = variablesToPositions(variables); - - TextEdit insert = new InsertEdit(caretOffset, MARKER); - string = edit(string, positions, insert); - positionsToVariables(positions, variables); - templateBuffer.setContent(string, variables); - - plainFormat(templateBuffer, context); - - string = templateBuffer.getString(); - variables = templateBuffer.getVariables(); - caretOffset = getCaretOffset(variables); - - positions = variablesToPositions(variables); - TextEdit delete = new DeleteEdit(caretOffset, MARKER.length()); - string = edit(string, positions, delete); - positionsToVariables(positions, variables); - templateBuffer.setContent(string, variables); - - } else { - plainFormat(templateBuffer, context); - } - } - - private void plainFormat(TemplateBuffer templateBuffer, JavaContext context) throws BadLocationException { - } - - // private void plainFormat(TemplateBuffer templateBuffer, JavaContext context) throws BadLocationException { - // - // IDocument doc= new Document(templateBuffer.getString()); - // - // TemplateVariable[] variables= templateBuffer.getVariables(); - // - // List offsets= variablesToPositions(variables); - // - // Map options; - // if (context.getCompilationUnit() != null) - // options= context.getCompilationUnit().getJavaProject().getOptions(true); - // else - // options= JavaCore.getOptions(); - // - // TextEdit edit= CodeFormatterUtil.format2(CodeFormatter.K_UNKNOWN, doc.get(), fInitialIndentLevel, fLineDelimiter, options); - // if (edit == null) - // throw new BadLocationException(); // fall back to indenting - // - // MultiTextEdit root; - // if (edit instanceof MultiTextEdit) - // root= (MultiTextEdit) edit; - // else { - // root= new MultiTextEdit(0, doc.getLength()); - // root.addChild(edit); - // } - // for (Iterator it= offsets.iterator(); it.hasNext();) { - // TextEdit position= (TextEdit) it.next(); - // try { - // root.addChild(position); - // } catch (MalformedTreeException e) { - // // position conflicts with formatter edit - // // ignore this position - // } - // } - // - // root.apply(doc, TextEdit.UPDATE_REGIONS); - // - // positionsToVariables(offsets, variables); - // - // templateBuffer.setContent(doc.get(), variables); - // } - - private void indent(TemplateBuffer templateBuffer) throws BadLocationException, MalformedTreeException { - - TemplateVariable[] variables = templateBuffer.getVariables(); - List positions = variablesToPositions(variables); - - IDocument document = new Document(templateBuffer.getString()); - MultiTextEdit root = new MultiTextEdit(0, document.getLength()); - root.addChildren((TextEdit[]) positions.toArray(new TextEdit[positions.size()])); - - JavaHeuristicScanner scanner = new JavaHeuristicScanner(document); - JavaIndenter indenter = new JavaIndenter(document, scanner); - - // first line - int offset = document.getLineOffset(0); - TextEdit edit = new InsertEdit(offset, CodeFormatterUtil.createIndentString(fInitialIndentLevel)); - root.addChild(edit); - root.apply(document, TextEdit.UPDATE_REGIONS); - root.removeChild(edit); - - formatDelimiter(document, root, 0); - - // following lines - int lineCount = document.getNumberOfLines(); - - for (int line = 1; line < lineCount; line++) { - IRegion region = document.getLineInformation(line); - offset = region.getOffset(); - StringBuffer indent = indenter.computeIndentation(offset); - if (indent == null) - continue; - // axelcl delete start -// int nonWS = scanner.findNonWhitespaceForwardInAnyPartition(offset, offset + region.getLength()); -// if (nonWS == JavaHeuristicScanner.NOT_FOUND) -// continue; -// edit = new ReplaceEdit(offset, nonWS - offset, indent.toString()); -// axelcl delete end -// axelcl insert start - int nonWS = offset; - edit = new ReplaceEdit(offset, nonWS - offset, CodeFormatterUtil.createIndentString(fInitialIndentLevel)); - // axelcl insert end - root.addChild(edit); - root.apply(document, TextEdit.UPDATE_REGIONS); - root.removeChild(edit); - - formatDelimiter(document, root, line); - } - - positionsToVariables(positions, variables); - templateBuffer.setContent(document.get(), variables); - } - - /** - * Changes the delimiter to the configured line delimiter. - * - * @param document - * the temporary document being edited - * @param root - * the root edit containing all positions that will be updated along the way - * @param line - * the line to format - * @throws BadLocationException - * if applying the changes fails - */ - private void formatDelimiter(IDocument document, MultiTextEdit root, int line) throws BadLocationException { - IRegion region = document.getLineInformation(line); - String lineDelimiter = document.getLineDelimiter(line); - if (lineDelimiter != null) { - TextEdit edit = new ReplaceEdit(region.getOffset() + region.getLength(), lineDelimiter.length(), fLineDelimiter); - root.addChild(edit); - root.apply(document, TextEdit.UPDATE_REGIONS); - root.removeChild(edit); - } - } - - private static void trimBegin(TemplateBuffer templateBuffer) throws BadLocationException { - String string = templateBuffer.getString(); - TemplateVariable[] variables = templateBuffer.getVariables(); - - List positions = variablesToPositions(variables); - - int i = 0; - while ((i != string.length()) && Character.isWhitespace(string.charAt(i))) - i++; - - string = edit(string, positions, new DeleteEdit(0, i)); - positionsToVariables(positions, variables); - - templateBuffer.setContent(string, variables); - } - - private static String edit(String string, List positions, TextEdit edit) throws BadLocationException { - MultiTextEdit root = new MultiTextEdit(0, string.length()); - root.addChildren((TextEdit[]) positions.toArray(new TextEdit[positions.size()])); - root.addChild(edit); - IDocument document = new Document(string); - root.apply(document); - - return document.get(); - } - - private static List variablesToPositions(TemplateVariable[] variables) { - List positions = new ArrayList(5); - for (int i = 0; i != variables.length; i++) { - int[] offsets = variables[i].getOffsets(); - - // trim positions off whitespace - String value = variables[i].getDefaultValue(); - int wsStart = 0; - while (wsStart < value.length() && Character.isWhitespace(value.charAt(wsStart)) - && !Strings.isLineDelimiterChar(value.charAt(wsStart))) - wsStart++; - - variables[i].getValues()[0] = value.substring(wsStart); - - for (int j = 0; j != offsets.length; j++) { - offsets[j] += wsStart; - positions.add(new RangeMarker(offsets[j], 0)); - } - } - return positions; - } - - private static void positionsToVariables(List positions, TemplateVariable[] variables) { - Iterator iterator = positions.iterator(); - - for (int i = 0; i != variables.length; i++) { - TemplateVariable variable = variables[i]; - - int[] offsets = new int[variable.getOffsets().length]; - for (int j = 0; j != offsets.length; j++) - offsets[j] = ((TextEdit) iterator.next()).getOffset(); - - variable.setOffsets(offsets); - } - } + private static final String MARKER = "/*${" + GlobalTemplateVariables.Cursor.NAME + "}*/"; //$NON-NLS-1$ //$NON-NLS-2$ + + /** The line delimiter to use if code formatter is not used. */ + private final String fLineDelimiter; + + /** The initial indent level */ + private final int fInitialIndentLevel; + + /** The java partitioner */ + private boolean fUseCodeFormatter; + + /** + * Creates a JavaFormatter with the target line delimiter. + * + * @param lineDelimiter + * the line delimiter to use + * @param initialIndentLevel + * the initial indentation level + * @param useCodeFormatter + * true if the core code formatter should be used + */ + public JavaFormatter(String lineDelimiter, int initialIndentLevel, + boolean useCodeFormatter) { + fLineDelimiter = lineDelimiter; + fUseCodeFormatter = useCodeFormatter; + fInitialIndentLevel = initialIndentLevel; + } + + /** + * Formats the template buffer. + * + * @param buffer + * @param context + * @throws BadLocationException + */ + public void format(TemplateBuffer buffer, TemplateContext context) + throws BadLocationException { + try { + if (fUseCodeFormatter) + // try to format and fall back to indenting + try { + format(buffer, (JavaContext) context); + } catch (BadLocationException e) { + indent(buffer); + } catch (MalformedTreeException e) { + indent(buffer); + } + else + indent(buffer); + + // don't trim the buffer if the replacement area is empty + // case: surrounding empty lines with block + if (context instanceof DocumentTemplateContext) { + DocumentTemplateContext dtc = (DocumentTemplateContext) context; + if (dtc.getStart() == dtc.getCompletionOffset()) + if (dtc.getDocument().get(dtc.getStart(), + dtc.getEnd() - dtc.getEnd()).trim().length() == 0) + return; + } + + trimBegin(buffer); + } catch (MalformedTreeException e) { + throw new BadLocationException(); + } + } + + private static int getCaretOffset(TemplateVariable[] variables) { + for (int i = 0; i != variables.length; i++) { + TemplateVariable variable = variables[i]; + + if (variable.getType().equals(GlobalTemplateVariables.Cursor.NAME)) + return variable.getOffsets()[0]; + } + + return -1; + } + + private boolean isInsideCommentOrString(String string, int offset) { + + IDocument document = new Document(string); + PHPeclipsePlugin.getDefault().getJavaTextTools() + .setupJavaDocumentPartitioner(document); + + try { + ITypedRegion partition = document.getPartition(offset); + String partitionType = partition.getType(); + + return partitionType != null + && (partitionType + .equals(IPHPPartitions.PHP_MULTILINE_COMMENT) + || partitionType + .equals(IPHPPartitions.PHP_SINGLELINE_COMMENT) + || partitionType + .equals(IPHPPartitions.PHP_STRING_DQ) + || partitionType + .equals(IPHPPartitions.PHP_STRING_SQ) + || partitionType + .equals(IPHPPartitions.PHP_STRING_HEREDOC) || partitionType + .equals(IPHPPartitions.PHP_PHPDOC_COMMENT)); + + } catch (BadLocationException e) { + return false; + } + } + + private void format(TemplateBuffer templateBuffer, JavaContext context) + throws BadLocationException { + // XXX 4360, 15247 + // workaround for code formatter limitations + // handle a special case where cursor position is surrounded by + // whitespaces + + String string = templateBuffer.getString(); + TemplateVariable[] variables = templateBuffer.getVariables(); + + int caretOffset = getCaretOffset(variables); + if ((caretOffset > 0) + && Character.isWhitespace(string.charAt(caretOffset - 1)) + && (caretOffset < string.length()) + && Character.isWhitespace(string.charAt(caretOffset)) + && !isInsideCommentOrString(string, caretOffset)) { + List positions = variablesToPositions(variables); + + TextEdit insert = new InsertEdit(caretOffset, MARKER); + string = edit(string, positions, insert); + positionsToVariables(positions, variables); + templateBuffer.setContent(string, variables); + + plainFormat(templateBuffer, context); + + string = templateBuffer.getString(); + variables = templateBuffer.getVariables(); + caretOffset = getCaretOffset(variables); + + positions = variablesToPositions(variables); + TextEdit delete = new DeleteEdit(caretOffset, MARKER.length()); + string = edit(string, positions, delete); + positionsToVariables(positions, variables); + templateBuffer.setContent(string, variables); + + } else { + plainFormat(templateBuffer, context); + } + } + + private void plainFormat(TemplateBuffer templateBuffer, JavaContext context) + throws BadLocationException { + } + + // private void plainFormat(TemplateBuffer templateBuffer, JavaContext + // context) throws BadLocationException { + // + // IDocument doc= new Document(templateBuffer.getString()); + // + // TemplateVariable[] variables= templateBuffer.getVariables(); + // + // List offsets= variablesToPositions(variables); + // + // Map options; + // if (context.getCompilationUnit() != null) + // options= context.getCompilationUnit().getJavaProject().getOptions(true); + // else + // options= JavaCore.getOptions(); + // + // TextEdit edit= CodeFormatterUtil.format2(CodeFormatter.K_UNKNOWN, + // doc.get(), fInitialIndentLevel, fLineDelimiter, options); + // if (edit == null) + // throw new BadLocationException(); // fall back to indenting + // + // MultiTextEdit root; + // if (edit instanceof MultiTextEdit) + // root= (MultiTextEdit) edit; + // else { + // root= new MultiTextEdit(0, doc.getLength()); + // root.addChild(edit); + // } + // for (Iterator it= offsets.iterator(); it.hasNext();) { + // TextEdit position= (TextEdit) it.next(); + // try { + // root.addChild(position); + // } catch (MalformedTreeException e) { + // // position conflicts with formatter edit + // // ignore this position + // } + // } + // + // root.apply(doc, TextEdit.UPDATE_REGIONS); + // + // positionsToVariables(offsets, variables); + // + // templateBuffer.setContent(doc.get(), variables); + // } + + private void indent(TemplateBuffer templateBuffer) + throws BadLocationException, MalformedTreeException { + + TemplateVariable[] variables = templateBuffer.getVariables(); + List positions = variablesToPositions(variables); + + IDocument document = new Document(templateBuffer.getString()); + MultiTextEdit root = new MultiTextEdit(0, document.getLength()); + root.addChildren((TextEdit[]) positions.toArray(new TextEdit[positions + .size()])); + + JavaHeuristicScanner scanner = new JavaHeuristicScanner(document); + JavaIndenter indenter = new JavaIndenter(document, scanner); + + // first line + int offset = document.getLineOffset(0); + TextEdit edit = new InsertEdit(offset, CodeFormatterUtil + .createIndentString(fInitialIndentLevel)); + root.addChild(edit); + root.apply(document, TextEdit.UPDATE_REGIONS); + root.removeChild(edit); + + formatDelimiter(document, root, 0); + + // following lines + int lineCount = document.getNumberOfLines(); + + for (int line = 1; line < lineCount; line++) { + IRegion region = document.getLineInformation(line); + offset = region.getOffset(); + StringBuffer indent = indenter.computeIndentation(offset); + if (indent == null) + continue; + // axelcl delete start + // int nonWS = + // scanner.findNonWhitespaceForwardInAnyPartition(offset, offset + + // region.getLength()); + // if (nonWS == JavaHeuristicScanner.NOT_FOUND) + // continue; + // edit = new ReplaceEdit(offset, nonWS - offset, + // indent.toString()); + // axelcl delete end + // axelcl insert start + int nonWS = offset; + edit = new ReplaceEdit(offset, nonWS - offset, CodeFormatterUtil + .createIndentString(fInitialIndentLevel)); + // axelcl insert end + root.addChild(edit); + root.apply(document, TextEdit.UPDATE_REGIONS); + root.removeChild(edit); + + formatDelimiter(document, root, line); + } + + positionsToVariables(positions, variables); + templateBuffer.setContent(document.get(), variables); + } + + /** + * Changes the delimiter to the configured line delimiter. + * + * @param document + * the temporary document being edited + * @param root + * the root edit containing all positions that will be updated + * along the way + * @param line + * the line to format + * @throws BadLocationException + * if applying the changes fails + */ + private void formatDelimiter(IDocument document, MultiTextEdit root, + int line) throws BadLocationException { + IRegion region = document.getLineInformation(line); + String lineDelimiter = document.getLineDelimiter(line); + if (lineDelimiter != null) { + TextEdit edit = new ReplaceEdit(region.getOffset() + + region.getLength(), lineDelimiter.length(), + fLineDelimiter); + root.addChild(edit); + root.apply(document, TextEdit.UPDATE_REGIONS); + root.removeChild(edit); + } + } + + private static void trimBegin(TemplateBuffer templateBuffer) + throws BadLocationException { + String string = templateBuffer.getString(); + TemplateVariable[] variables = templateBuffer.getVariables(); + + List positions = variablesToPositions(variables); + + int i = 0; + while ((i != string.length()) + && Character.isWhitespace(string.charAt(i))) + i++; + + string = edit(string, positions, new DeleteEdit(0, i)); + positionsToVariables(positions, variables); + + templateBuffer.setContent(string, variables); + } + + private static String edit(String string, List positions, TextEdit edit) + throws BadLocationException { + MultiTextEdit root = new MultiTextEdit(0, string.length()); + root.addChildren((TextEdit[]) positions.toArray(new TextEdit[positions + .size()])); + root.addChild(edit); + IDocument document = new Document(string); + root.apply(document); + + return document.get(); + } + + private static List variablesToPositions(TemplateVariable[] variables) { + List positions = new ArrayList(5); + for (int i = 0; i != variables.length; i++) { + int[] offsets = variables[i].getOffsets(); + + // trim positions off whitespace + String value = variables[i].getDefaultValue(); + int wsStart = 0; + while (wsStart < value.length() + && Character.isWhitespace(value.charAt(wsStart)) + && !Strings.isLineDelimiterChar(value.charAt(wsStart))) + wsStart++; + + variables[i].getValues()[0] = value.substring(wsStart); + + for (int j = 0; j != offsets.length; j++) { + offsets[j] += wsStart; + positions.add(new RangeMarker(offsets[j], 0)); + } + } + return positions; + } + + private static void positionsToVariables(List positions, + TemplateVariable[] variables) { + Iterator iterator = positions.iterator(); + + for (int i = 0; i != variables.length; i++) { + TemplateVariable variable = variables[i]; + + int[] offsets = new int[variable.getOffsets().length]; + for (int j = 0; j != offsets.length; j++) + offsets[j] = ((TextEdit) iterator.next()).getOffset(); + + variable.setOffsets(offsets); + } + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaTemplateMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaTemplateMessages.java index b4846af..7756536 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaTemplateMessages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaTemplateMessages.java @@ -16,8 +16,11 @@ import java.util.ResourceBundle; class JavaTemplateMessages { - private static final String RESOURCE_BUNDLE= JavaTemplateMessages.class.getName(); - private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); + private static final String RESOURCE_BUNDLE = JavaTemplateMessages.class + .getName(); + + private static ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); private JavaTemplateMessages() { } @@ -29,20 +32,20 @@ class JavaTemplateMessages { return '!' + key + '!'; } } - + /** * Gets a string from the resource bundle and formats it with the argument * - * @param key the string used to get the bundle value, must not be null + * @param key + * the string used to get the bundle value, must not be null */ public static String getFormattedString(String key, Object arg) { return MessageFormat.format(getString(key), new Object[] { arg }); } - /** * Gets a string from the resource bundle and formats it with arguments - */ + */ public static String getFormattedString(String key, Object[] args) { return MessageFormat.format(getString(key), args); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/TemplateSet.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/TemplateSet.java index 3476386..a0d83fa 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/TemplateSet.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/TemplateSet.java @@ -57,22 +57,27 @@ import org.xml.sax.SAXException; */ public class TemplateSet { - private static final String NAME_ATTRIBUTE= "name"; //$NON-NLS-1$ - private static final String DESCRIPTION_ATTRIBUTE= "description"; //$NON-NLS-1$ - private static final String CONTEXT_ATTRIBUTE= "context"; //$NON-NLS-1$ + private static final String NAME_ATTRIBUTE = "name"; //$NON-NLS-1$ + + private static final String DESCRIPTION_ATTRIBUTE = "description"; //$NON-NLS-1$ + + private static final String CONTEXT_ATTRIBUTE = "context"; //$NON-NLS-1$ + + private List fTemplates = new ArrayList(); - private List fTemplates= new ArrayList(); private String fTemplateTag; - - private static final int TEMPLATE_PARSE_EXCEPTION= 10002; - private static final int TEMPLATE_IO_EXCEPTION= 10005; + + private static final int TEMPLATE_PARSE_EXCEPTION = 10002; + + private static final int TEMPLATE_IO_EXCEPTION = 10005; + private ContextTypeRegistry fRegistry; - + public TemplateSet(String templateTag, ContextTypeRegistry registry) { - fTemplateTag= templateTag; - fRegistry= registry; + fTemplateTag = templateTag; + fRegistry = registry; } - + /** * Convenience method for reading templates from a file. * @@ -82,11 +87,12 @@ public class TemplateSet { * @see #addFromStream(InputStream, boolean, boolean, ResourceBundle) * @throws CoreException */ - public void addFromFile(File file, boolean allowDuplicates, ResourceBundle bundle) throws CoreException { - InputStream stream= null; + public void addFromFile(File file, boolean allowDuplicates, + ResourceBundle bundle) throws CoreException { + InputStream stream = null; try { - stream= new FileInputStream(file); + stream = new FileInputStream(file); addFromStream(stream, allowDuplicates, false, bundle); } catch (IOException e) { @@ -96,14 +102,14 @@ public class TemplateSet { try { if (stream != null) stream.close(); - } catch (IOException e) {} - } + } catch (IOException e) { + } + } } - + public String getTemplateTag() { return fTemplateTag; } - /** * Reads templates from a XML stream and adds them to the templates @@ -114,59 +120,65 @@ public class TemplateSet { * @param doTranslations * @see #addFromStream(InputStream, boolean, boolean, ResourceBundle) * @throws CoreException - */ - public void addFromStream(InputStream stream, boolean allowDuplicates, boolean doTranslations, ResourceBundle bundle) throws CoreException { + */ + public void addFromStream(InputStream stream, boolean allowDuplicates, + boolean doTranslations, ResourceBundle bundle) throws CoreException { try { - DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance(); - DocumentBuilder parser= factory.newDocumentBuilder(); - Document document= parser.parse(new InputSource(stream)); - - NodeList elements= document.getElementsByTagName(getTemplateTag()); - - int count= elements.getLength(); - for (int i= 0; i != count; i++) { - Node node= elements.item(i); - NamedNodeMap attributes= node.getAttributes(); + DocumentBuilderFactory factory = DocumentBuilderFactory + .newInstance(); + DocumentBuilder parser = factory.newDocumentBuilder(); + Document document = parser.parse(new InputSource(stream)); + + NodeList elements = document.getElementsByTagName(getTemplateTag()); + + int count = elements.getLength(); + for (int i = 0; i != count; i++) { + Node node = elements.item(i); + NamedNodeMap attributes = node.getAttributes(); if (attributes == null) continue; - String name= getAttributeValue(attributes, NAME_ATTRIBUTE); - String description= getAttributeValue(attributes, DESCRIPTION_ATTRIBUTE); + String name = getAttributeValue(attributes, NAME_ATTRIBUTE); + String description = getAttributeValue(attributes, + DESCRIPTION_ATTRIBUTE); if (name == null || description == null) continue; - + if (doTranslations) { - description= translateString(description, bundle); - } - String context= getAttributeValue(attributes, CONTEXT_ATTRIBUTE); + description = translateString(description, bundle); + } + String context = getAttributeValue(attributes, + CONTEXT_ATTRIBUTE); if (name == null || description == null || context == null) - throw new SAXException(JavaTemplateMessages.getString("TemplateSet.error.missing.attribute")); //$NON-NLS-1$ + throw new SAXException(JavaTemplateMessages + .getString("TemplateSet.error.missing.attribute")); //$NON-NLS-1$ - StringBuffer buffer= new StringBuffer(); - NodeList children= node.getChildNodes(); - for (int j= 0; j != children.getLength(); j++) { - String value= children.item(j).getNodeValue(); + StringBuffer buffer = new StringBuffer(); + NodeList children = node.getChildNodes(); + for (int j = 0; j != children.getLength(); j++) { + String value = children.item(j).getNodeValue(); if (value != null) buffer.append(value); } - String pattern= buffer.toString().trim(); + String pattern = buffer.toString().trim(); if (doTranslations) { - pattern= translateString(pattern, bundle); - } + pattern = translateString(pattern, bundle); + } + + Template template = new Template(name, description, context, + pattern); - Template template= new Template(name, description, context, pattern); - - String message= validateTemplate(template); + String message = validateTemplate(template); if (message == null) { if (!allowDuplicates) { - Template[] templates= getTemplates(name); - for (int k= 0; k < templates.length; k++) { + Template[] templates = getTemplates(name); + for (int k = 0; k < templates.length; k++) { remove(templates[k]); } } - add(template); + add(template); } else { throwReadException(null); } @@ -179,27 +191,28 @@ public class TemplateSet { throwReadException(e); } } - + private String translateString(String str, ResourceBundle bundle) { - int idx= str.indexOf('%'); + int idx = str.indexOf('%'); if (idx == -1) { return str; } - StringBuffer buf= new StringBuffer(); - int k= 0; + StringBuffer buf = new StringBuffer(); + int k = 0; while (idx != -1) { buf.append(str.substring(k, idx)); - for (k= idx + 1; k < str.length() && !Character.isWhitespace(str.charAt(k)); k++) { + for (k = idx + 1; k < str.length() + && !Character.isWhitespace(str.charAt(k)); k++) { // loop } - String key= str.substring(idx + 1, k); + String key = str.substring(idx + 1, k); buf.append(getBundleString(key, bundle)); - idx= str.indexOf('%', k); + idx = str.indexOf('%', k); } buf.append(str.substring(k)); return buf.toString(); } - + private String getBundleString(String key, ResourceBundle bundle) { if (bundle != null) { try { @@ -212,7 +225,8 @@ public class TemplateSet { } protected String validateTemplate(Template template) { - TemplateContextType type= fRegistry.getContextType(template.getContextTypeId()); + TemplateContextType type = fRegistry.getContextType(template + .getContextTypeId()); if (type == null) { return "Unknown context type: " + template.getContextTypeId(); //$NON-NLS-1$ } @@ -223,13 +237,11 @@ public class TemplateSet { return e.getMessage(); } } - + private String getAttributeValue(NamedNodeMap attributes, String name) { - Node node= attributes.getNamedItem(name); + Node node = attributes.getNamedItem(name); - return node == null - ? null - : node.getNodeValue(); + return node == null ? null : node.getNodeValue(); } /** @@ -238,10 +250,10 @@ public class TemplateSet { * @see #saveToStream(OutputStream) */ public void saveToFile(File file) throws CoreException { - OutputStream stream= null; + OutputStream stream = null; try { - stream= new FileOutputStream(file); + stream = new FileOutputStream(file); saveToStream(stream); } catch (IOException e) { @@ -251,48 +263,51 @@ public class TemplateSet { try { if (stream != null) stream.close(); - } catch (IOException e) {} + } catch (IOException e) { + } } } - + /** * Saves the template set as XML. */ public void saveToStream(OutputStream stream) throws CoreException { try { - DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance(); - DocumentBuilder builder= factory.newDocumentBuilder(); - Document document= builder.newDocument(); + DocumentBuilderFactory factory = DocumentBuilderFactory + .newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document document = builder.newDocument(); - Node root= document.createElement("templates"); //$NON-NLS-1$ + Node root = document.createElement("templates"); //$NON-NLS-1$ document.appendChild(root); - - for (int i= 0; i != fTemplates.size(); i++) { - Template template= (Template) fTemplates.get(i); - - Node node= document.createElement(getTemplateTag()); + + for (int i = 0; i != fTemplates.size(); i++) { + Template template = (Template) fTemplates.get(i); + + Node node = document.createElement(getTemplateTag()); root.appendChild(node); - - NamedNodeMap attributes= node.getAttributes(); - - Attr name= document.createAttribute(NAME_ATTRIBUTE); + + NamedNodeMap attributes = node.getAttributes(); + + Attr name = document.createAttribute(NAME_ATTRIBUTE); name.setValue(template.getName()); attributes.setNamedItem(name); - - Attr description= document.createAttribute(DESCRIPTION_ATTRIBUTE); + + Attr description = document + .createAttribute(DESCRIPTION_ATTRIBUTE); description.setValue(template.getDescription()); attributes.setNamedItem(description); - - Attr context= document.createAttribute(CONTEXT_ATTRIBUTE); + + Attr context = document.createAttribute(CONTEXT_ATTRIBUTE); context.setValue(template.getContextTypeId()); - attributes.setNamedItem(context); - - Text pattern= document.createTextNode(template.getPattern()); - node.appendChild(pattern); - } - - - Transformer transformer=TransformerFactory.newInstance().newTransformer(); + attributes.setNamedItem(context); + + Text pattern = document.createTextNode(template.getPattern()); + node.appendChild(pattern); + } + + Transformer transformer = TransformerFactory.newInstance() + .newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$ transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$ DOMSource source = new DOMSource(document); @@ -304,25 +319,35 @@ public class TemplateSet { throwWriteException(e); } catch (TransformerException e) { throwWriteException(e); - } + } } private static void throwReadException(Throwable t) throws CoreException { int code; if (t instanceof SAXException) - code= TEMPLATE_PARSE_EXCEPTION; + code = TEMPLATE_PARSE_EXCEPTION; else - code= TEMPLATE_IO_EXCEPTION; -// IStatus status= JavaUIStatus.createError(code, TemplateMessages.getString("TemplateSet.error.read"), t); //$NON-NLS-1$ -// throw new JavaUIException(status); - throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.jface.text", code, JavaTemplateMessages.getString("TemplateSet.error.read"), t)); //$NON-NLS-1$ //$NON-NLS-2$ + code = TEMPLATE_IO_EXCEPTION; + // IStatus status= JavaUIStatus.createError(code, + // TemplateMessages.getString("TemplateSet.error.read"), t); + // //$NON-NLS-1$ + // throw new JavaUIException(status); + throw new CoreException( + new Status( + IStatus.ERROR, + "org.eclipse.jface.text", code, JavaTemplateMessages.getString("TemplateSet.error.read"), t)); //$NON-NLS-1$ //$NON-NLS-2$ } - + private static void throwWriteException(Throwable t) throws CoreException { -// IStatus status= JavaUIStatus.createError(IJavaStatusConstants.TEMPLATE_IO_EXCEPTION, -// TemplateMessages.getString("TemplateSet.error.write"), t); //$NON-NLS-1$ -// throw new JavaUIException(status); - throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.jface.text", TEMPLATE_IO_EXCEPTION, JavaTemplateMessages.getString("TemplateSet.error.write"), t)); //$NON-NLS-1$ //$NON-NLS-2$ + // IStatus status= + // JavaUIStatus.createError(IJavaStatusConstants.TEMPLATE_IO_EXCEPTION, + // TemplateMessages.getString("TemplateSet.error.write"), t); + // //$NON-NLS-1$ + // throw new JavaUIException(status); + throw new CoreException( + new Status( + IStatus.ERROR, + "org.eclipse.jface.text", TEMPLATE_IO_EXCEPTION, JavaTemplateMessages.getString("TemplateSet.error.write"), t)); //$NON-NLS-1$ //$NON-NLS-2$ } /** @@ -331,7 +356,7 @@ public class TemplateSet { public void add(Template template) { if (exists(template)) return; // ignore duplicate - + fTemplates.add(template); } @@ -342,57 +367,56 @@ public class TemplateSet { if (template.equals(anotherTemplate)) return true; } - + return false; } - + /** * Removes a template to the set. - */ + */ public void remove(Template template) { fTemplates.remove(template); } /** * Empties the set. - */ + */ public void clear() { fTemplates.clear(); } - + /** * Returns all templates. */ public Template[] getTemplates() { return (Template[]) fTemplates.toArray(new Template[fTemplates.size()]); } - + /** * Returns all templates with a given name. */ public Template[] getTemplates(String name) { - ArrayList res= new ArrayList(); - for (Iterator iterator= fTemplates.iterator(); iterator.hasNext();) { - Template curr= (Template) iterator.next(); + ArrayList res = new ArrayList(); + for (Iterator iterator = fTemplates.iterator(); iterator.hasNext();) { + Template curr = (Template) iterator.next(); if (curr.getName().equals(name)) { res.add(curr); } } return (Template[]) res.toArray(new Template[res.size()]); } - + /** * Returns the first templates with the given name. */ public Template getFirstTemplate(String name) { - for (Iterator iterator= fTemplates.iterator(); iterator.hasNext();) { - Template curr= (Template) iterator.next(); + for (Iterator iterator = fTemplates.iterator(); iterator.hasNext();) { + Template curr = (Template) iterator.next(); if (curr.getName().equals(name)) { return curr; } } return null; - } - -} + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/Templates.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/Templates.java index e316f14..3ea7c66 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/Templates.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/Templates.java @@ -19,17 +19,21 @@ import net.sourceforge.phpeclipse.PHPeclipsePlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; - /** * Templates gives access to the available templates. * - * @deprecated As of 3.0, replaced by {@link org.eclipse.jface.text.templates.persistence.TemplateStore} + * @deprecated As of 3.0, replaced by + * {@link org.eclipse.jface.text.templates.persistence.TemplateStore} */ -public class Templates extends net.sourceforge.phpdt.internal.corext.template.php.TemplateSet { +public class Templates extends + net.sourceforge.phpdt.internal.corext.template.php.TemplateSet { + + private static final String DEFAULT_FILE = "default-templates.xml"; //$NON-NLS-1$ + + private static final String TEMPLATE_FILE = "templates.xml"; //$NON-NLS-1$ - private static final String DEFAULT_FILE= "default-templates.xml"; //$NON-NLS-1$ - private static final String TEMPLATE_FILE= "templates.xml"; //$NON-NLS-1$ - private static final ResourceBundle fgResourceBundle= ResourceBundle.getBundle(JavaTemplateMessages.class.getName()); + private static final ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(JavaTemplateMessages.class.getName()); /** Singleton. */ private static Templates fgTemplates; @@ -37,36 +41,37 @@ public class Templates extends net.sourceforge.phpdt.internal.corext.template.ph /** * Returns an instance of templates. * - * @deprecated As of 3.0, replaced by {@link net.sourceforge.phpdt.internal.ui.JavaPlugin#getTemplateStore()} + * @deprecated As of 3.0, replaced by + * {@link net.sourceforge.phpdt.internal.ui.JavaPlugin#getTemplateStore()} */ public static Templates getInstance() { if (fgTemplates == null) - fgTemplates= new Templates(); - + fgTemplates = new Templates(); + return fgTemplates; } - + public Templates() { - super("template", PHPeclipsePlugin.getDefault().getTemplateContextRegistry()); //$NON-NLS-1$ + super( + "template", PHPeclipsePlugin.getDefault().getTemplateContextRegistry()); //$NON-NLS-1$ create(); } - private void create() { try { - File templateFile= getTemplateFile(); + File templateFile = getTemplateFile(); if (templateFile.exists()) { addFromFile(templateFile, true, fgResourceBundle); } } catch (CoreException e) { - PHPeclipsePlugin.log(e); + PHPeclipsePlugin.log(e); clear(); } - } - + } + /** * Resets the template set. */ @@ -86,7 +91,7 @@ public class Templates extends net.sourceforge.phpdt.internal.corext.template.ph /** * Saves the template set. */ - public void save() throws CoreException { + public void save() throws CoreException { saveToFile(getTemplateFile()); } @@ -95,10 +100,9 @@ public class Templates extends net.sourceforge.phpdt.internal.corext.template.ph } private static File getTemplateFile() { - IPath path= PHPeclipsePlugin.getDefault().getStateLocation(); - path= path.append(TEMPLATE_FILE); - + IPath path = PHPeclipsePlugin.getDefault().getStateLocation(); + path = path.append(TEMPLATE_FILE); + return path.toFile(); } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/MoveTextEdit.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/MoveTextEdit.java index de964c9..d41ef60 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/MoveTextEdit.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/MoveTextEdit.java @@ -6,73 +6,87 @@ package net.sourceforge.phpdt.internal.corext.textmanipulation; import org.eclipse.core.runtime.CoreException; - -//import net.sourceforge.phpdt.internal.corext.Assert; +// import net.sourceforge.phpdt.internal.corext.Assert; /** * A text edit that moves text inside a text buffer. */ public final class MoveTextEdit extends TextEdit { - - /* package */ static class TargetMark extends NopTextEdit { + + /* package */static class TargetMark extends NopTextEdit { private MoveTextEdit fMoveTextEdit; + public TargetMark(TextRange range, MoveTextEdit edit) { super(range); - fMoveTextEdit= edit; + fMoveTextEdit = edit; } - /* package */ MoveTextEdit getMoveTextEdit() { + + /* package */MoveTextEdit getMoveTextEdit() { return fMoveTextEdit; } + public TextEdit perform(TextBuffer buffer) throws CoreException { fMoveTextEdit.internalPerform(buffer); return super.perform(buffer); } + public TextEdit copy() { - // Assert.isTrue(false, "This should never happen"); //$NON-NLS-1$ + // Assert.isTrue(false, "This should never happen"); //$NON-NLS-1$ return super.copy(); } } private TextRange fTarget; + private TextRange fSource; + private int fPerformCounter; /** * Creates a new MoveTextEdit. The text edit doesn't support - * overlapping moves. So for a MoveTextEdit destination <= offset && - * offset + length - 1 <= destination must be true. + * overlapping moves. So for a + * MoveTextEdit destination <= offset && + * offset + length - 1 <= destination + * must be true. * - * @param offset the offset of the text to be moved - * @param length the text length to be moved - * @param destination the destination offset + * @param offset + * the offset of the text to be moved + * @param length + * the text length to be moved + * @param destination + * the destination offset */ public MoveTextEdit(int offset, int length, int destination) { - // Assert.isTrue(destination <= offset || offset + length <= destination); - fSource= new TextRange(offset, length); - fTarget= new TextRange(destination); + // Assert.isTrue(destination <= offset || offset + length <= + // destination); + fSource = new TextRange(offset, length); + fTarget = new TextRange(destination); } /** - * Creates a new MoveTextEdit with the given source and target range. + * Creates a new MoveTextEdit with the given source and + * target range. * - * @param source the source - * @param target the target + * @param source + * the source + * @param target + * the target */ - private MoveTextEdit(TextRange source,TextRange target) { - fSource= source; - fTarget= target; + private MoveTextEdit(TextRange source, TextRange target) { + fSource = source; + fTarget = target; } - + /** - * Returns the move text edit's source range. This method returns the same range - * as TextEdit#getTextRange() + * Returns the move text edit's source range. This method returns the same + * range as TextEdit#getTextRange() * * @return the edit's source range */ public TextRange getSourceRange() { return fSource; } - + /** * Returns the move text edit's target range. * @@ -81,22 +95,28 @@ public final class MoveTextEdit extends TextEdit { public TextRange getTargetRange() { return fTarget; } - - /* non Java-doc + + /* + * non Java-doc + * * @see TextEdit#getTextRange() */ public TextRange getTextRange() { return fSource; } - /* non Java-doc + /* + * non Java-doc + * * @see TextEdit#connect(TextBufferEditor) */ public void connect(TextBufferEditor editor) throws CoreException { editor.add(new TargetMark(fTarget, this)); } - - /* non Java-doc + + /* + * non Java-doc + * * @see TextEdit#perform(TextBuffer) */ public TextEdit perform(TextBuffer buffer) throws CoreException { @@ -104,44 +124,46 @@ public final class MoveTextEdit extends TextEdit { return new MoveTextEdit(fTarget, fSource); } - /* non Java-doc + /* + * non Java-doc + * * @see TextEdit#copy() */ public TextEdit copy() { - TextRange source= getSourceRange(); - TextRange target= getTargetRange(); + TextRange source = getSourceRange(); + TextRange target = getTargetRange(); return new MoveTextEdit(source.fOffset, source.fLength, target.fOffset); } - - //---- Helper method --------------------------------------------------------------------------------- - + + // ---- Helper method + // --------------------------------------------------------------------------------- + private void internalPerform(TextBuffer buffer) throws CoreException { -// Assert.isTrue(fPerformCounter < 2); + // Assert.isTrue(fPerformCounter < 2); if (++fPerformCounter == 2) { - TextRange source= getSourceRange(); - TextRange target= getTargetRange(); - String current= buffer.getContent(source.fOffset, source.fLength); + TextRange source = getSourceRange(); + TextRange target = getTargetRange(); + String current = buffer.getContent(source.fOffset, source.fLength); buffer.replace(source, ""); //$NON-NLS-1$ buffer.replace(target, current); } } - - /* package */ boolean isUpMove() { + + /* package */boolean isUpMove() { return fSource.fOffset < fTarget.fOffset; } - - /* package */ boolean isDownMove() { + + /* package */boolean isDownMove() { return fSource.fOffset > fTarget.fOffset; } - - /* package */ TextRange getChildRange() { - int offset= fSource.fOffset; - int length= fSource.fLength; - int destination= fTarget.fOffset; + + /* package */TextRange getChildRange() { + int offset = fSource.fOffset; + int length = fSource.fLength; + int destination = fTarget.fOffset; if (destination <= offset) return new TextRange(destination, offset + length - destination); else return new TextRange(offset, destination - offset); - } + } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/MultiTextEdit.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/MultiTextEdit.java index a416650..5973efd 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/MultiTextEdit.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/MultiTextEdit.java @@ -11,7 +11,6 @@ import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.util.Assert; - public class MultiTextEdit { private List fChildren; @@ -20,13 +19,13 @@ public class MultiTextEdit { * Creates a new composite text edit. */ public MultiTextEdit() { - fChildren= new ArrayList(3); + fChildren = new ArrayList(3); } protected MultiTextEdit(List children) throws CoreException { - fChildren= new ArrayList(children.size()); - for (Iterator iter= children.iterator(); iter.hasNext();) { - fChildren.add(((TextEdit)iter.next()).copy()); + fChildren = new ArrayList(children.size()); + for (Iterator iter = children.iterator(); iter.hasNext();) { + fChildren.add(((TextEdit) iter.next()).copy()); } } @@ -37,7 +36,8 @@ public class MultiTextEdit { /** * Adds all TextEdits managed by the given multt text edit. * - * @param edit the multi text edit to be added. + * @param edit + * the multi text edit to be added. */ public void add(MultiTextEdit edit) { Assert.isNotNull(edit); @@ -47,7 +47,8 @@ public class MultiTextEdit { /** * Adds a text edit. * - * @param edit the text edit to be added + * @param edit + * the text edit to be added */ public void add(TextEdit edit) { Assert.isNotNull(edit); @@ -64,31 +65,33 @@ public class MultiTextEdit { } /** - * Connects this text edit to the given TextBufferEditor. + * Connects this text edit to the given TextBufferEditor. * Note that this method should only be called by a * TextBufferEditor. - *

                                                      - * This default implementation does nothing. Subclasses may override - * if needed. - * - * @param editor the text buffer editor this text edit has been added to + *

                                                      + * This default implementation does nothing. Subclasses may override if + * needed. + * + * @param editor + * the text buffer editor this text edit has been added to */ public void connect(TextBufferEditor editor) throws CoreException { - for (Iterator iter= fChildren.iterator(); iter.hasNext();) { - Object element= iter.next(); + for (Iterator iter = fChildren.iterator(); iter.hasNext();) { + Object element = iter.next(); if (element instanceof TextEdit) - editor.add((TextEdit)element); + editor.add((TextEdit) element); else - editor.add((MultiTextEdit)element); + editor.add((MultiTextEdit) element); } } /** - * Creates and returns a copy of this text edit collection. The copy method should - * be implemented in a way so that the copy can be added to a different - * TextBuffer without causing any harm to the object from which the copy - * has been created. - * + * Creates and returns a copy of this text edit collection. The copy method + * should be implemented in a way so that the copy can be added to a + * different + * TextBuffer without causing any harm to the + * object from which the copy has been created. + * * @return a copy of this object. */ public MultiTextEdit copy() throws CoreException { @@ -97,33 +100,34 @@ public class MultiTextEdit { /** * Returns the TextRange that this text edit is going to - * manipulate. If this method is called before the MultiTextEdit - * has been added to a TextBufferEditor it may return - * null to indicate this situation. + * manipulate. If this method is called before the + * MultiTextEdit has been added to a + * TextBufferEditor it may return + * null to + * indicate this situation. * * @return the TextRanges this TextEdit is going * to manipulate */ public TextRange getTextRange() { - int size= fChildren.size(); + int size = fChildren.size(); if (size == 0) - return new TextRange(0,0); - TextRange range= ((TextEdit)fChildren.get(0)).getTextRange(); - int start= range.getOffset(); - int end= range.getInclusiveEnd(); - for (int i= 1; i < size; i++) { - range= ((TextEdit)fChildren.get(i)).getTextRange(); - start= Math.min(start, range.getOffset()); - end= Math.max(end, range.getInclusiveEnd()); + return new TextRange(0, 0); + TextRange range = ((TextEdit) fChildren.get(0)).getTextRange(); + int start = range.getOffset(); + int end = range.getInclusiveEnd(); + for (int i = 1; i < size; i++) { + range = ((TextEdit) fChildren.get(i)).getTextRange(); + start = Math.min(start, range.getOffset()); + end = Math.max(end, range.getInclusiveEnd()); } return new TextRange(start, end - start + 1); } /** - * Returns the element modified by this text edit. The method - * may return null if the modification isn't related to a - * element or if the content of the modified text buffer doesn't - * follow any syntax. + * Returns the element modified by this text edit. The method may return + * null if the modification isn't related to a element or if + * the content of the modified text buffer doesn't follow any syntax. *

                                                      * This default implementation returns null * @@ -133,4 +137,3 @@ public class MultiTextEdit { return null; } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/NopTextEdit.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/NopTextEdit.java index 083fe0b..1994ef2 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/NopTextEdit.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/NopTextEdit.java @@ -7,54 +7,61 @@ package net.sourceforge.phpdt.internal.corext.textmanipulation; import org.eclipse.core.runtime.CoreException; /** - * A text edit that does nothing. A NopTextEdit can be used to track - * positions when executing TextEdits associated with a + * A text edit that does nothing. A NopTextEdit can be used to + * track positions when executing TextEdits associated with a + * * TextBufferEditor. */ public class NopTextEdit extends TextEdit { - + private TextRange fTextRange; - + /** - * Creates a new NopTextEdit for the given - * offset and length. + * Creates a new NopTextEdit for the given offset and length. * - * @param offset the starting offset this text edit is "working on" - * @param length the length this text edit is "working on" + * @param offset + * the starting offset this text edit is "working on" + * @param length + * the length this text edit is "working on" */ public NopTextEdit(int offset, int length) { this(new TextRange(offset, length)); } - + /** - * Creates a new NopTextEdit for the given - * range. + * Creates a new NopTextEdit for the given range. * - * @param range the TextRange this text edit is "working on" + * @param range + * the TextRange this text edit is "working on" */ public NopTextEdit(TextRange range) { - fTextRange= range; + fTextRange = range; } - /* non Java-doc + /* + * non Java-doc + * * @see TextEdit#getTextRange - */ + */ public TextRange getTextRange() { return fTextRange; } - /* non Java-doc + /* + * non Java-doc + * * @see TextEdit#perform - */ + */ public TextEdit perform(TextBuffer buffer) throws CoreException { return new NopTextEdit(fTextRange); } - - /* non Java-doc + + /* + * non Java-doc + * * @see TextEdit#perform - */ + */ public TextEdit copy() { return new NopTextEdit(fTextRange.copy()); - } + } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/SimpleTextEdit.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/SimpleTextEdit.java index 9072f2e..e5a19be 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/SimpleTextEdit.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/SimpleTextEdit.java @@ -6,51 +6,56 @@ package net.sourceforge.phpdt.internal.corext.textmanipulation; import org.eclipse.core.runtime.CoreException; -//import net.sourceforge.phpdt.internal.corext.Assert; +// import net.sourceforge.phpdt.internal.corext.Assert; public abstract class SimpleTextEdit extends TextEdit { private TextRange fRange; + private String fText; - public static SimpleTextEdit createReplace(int offset, int length, String text) { + public static SimpleTextEdit createReplace(int offset, int length, + String text) { return new SimpleTextEditImpl(offset, length, text); } public static SimpleTextEdit createInsert(int offset, String text) { return new SimpleTextEditImpl(offset, 0, text); } - + public static SimpleTextEdit createDelete(int offset, int length) { return new SimpleTextEditImpl(offset, length, ""); //$NON-NLS-1$ } - + private final static class SimpleTextEditImpl extends SimpleTextEdit { protected SimpleTextEditImpl(TextRange range, String text) { super(range, text); } + protected SimpleTextEditImpl(int offset, int length, String text) { super(offset, length, text); } + public TextEdit copy() { return new SimpleTextEditImpl(getTextRange().copy(), getText()); - } + } } - + protected SimpleTextEdit() { this(TextRange.UNDEFINED, ""); //$NON-NLS-1$ } - + protected SimpleTextEdit(int offset, int length, String text) { this(new TextRange(offset, length), text); } + protected SimpleTextEdit(TextRange range, String text) { - // Assert.isNotNull(range); - // Assert.isNotNull(text); - fRange= range; - fText= text; + // Assert.isNotNull(range); + // Assert.isNotNull(text); + fRange = range; + fText = text; } - + /** * Returns the text edit's text * @@ -59,47 +64,54 @@ public abstract class SimpleTextEdit extends TextEdit { public String getText() { return fText; } - + /** * Sets the text edit's text *

                                                      * This method should only be called from within the - * connect method. + * connect + * method. * - * @param text the text edit's text - */ + * @param text + * the text edit's text + */ protected final void setText(String text) { - fText= text; -// Assert.isNotNull(fText); + fText = text; + // Assert.isNotNull(fText); } - + /** * Sets the text edit's range. *

                                                      * This method should only be called from within the - * connect method. + * connect + * method. * - * @param range the text edit's range. - */ + * @param range + * the text edit's range. + */ protected void setTextRange(TextRange range) { - fRange= range; - // Assert.isNotNull(fRange); + fRange = range; + // Assert.isNotNull(fRange); } - - /* non Java-doc + + /* + * non Java-doc + * * @see TextEdit#getTextRange */ public TextRange getTextRange() { return fRange; } - - /* non Java-doc + + /* + * non Java-doc + * * @see TextEdit#doPerform */ public final TextEdit perform(TextBuffer buffer) throws CoreException { - String current= buffer.getContent(fRange.fOffset, fRange.fLength); + String current = buffer.getContent(fRange.fOffset, fRange.fLength); buffer.replace(fRange, fText); return new SimpleTextEditImpl(fRange, current); - } + } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/SwapTextEdit.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/SwapTextEdit.java index eb0d247..02105a0 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/SwapTextEdit.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/SwapTextEdit.java @@ -4,7 +4,6 @@ */ package net.sourceforge.phpdt.internal.corext.textmanipulation; - /** * A SwapTextEdit exchanges to text ranges. */ @@ -12,14 +11,17 @@ public class SwapTextEdit extends MultiTextEdit { /** * Create a new SwapTextEdit * - * @param offset1 the offset of the first text range - * @param length1 the length of the first text range - * @param offset2 the offset of the second text range - * @param length2 the length of the second text range + * @param offset1 + * the offset of the first text range + * @param length1 + * the length of the first text range + * @param offset2 + * the offset of the second text range + * @param length2 + * the length of the second text range */ public SwapTextEdit(int offset1, int length1, int offset2, int length2) { add(new MoveTextEdit(offset1, length1, offset2)); add(new MoveTextEdit(offset2, length2, offset1)); } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextBuffer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextBuffer.java index 8f8a79d..464d5bb 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextBuffer.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextBuffer.java @@ -24,51 +24,55 @@ import org.eclipse.jface.text.ILineTracker; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.util.Assert; -//import net.sourceforge.phpdt.internal.ui.JavaPlugin; -//import net.sourceforge.phpdt.internal.ui.JavaStatusConstants; +// import net.sourceforge.phpdt.internal.ui.JavaPlugin; +// import net.sourceforge.phpdt.internal.ui.JavaStatusConstants; /** - * An implementation of a TextBuffer that is based on ITextSelection - * and IDocument. + * An implementation of a TextBuffer that is based on + * ITextSelection and IDocument. */ public class TextBuffer { private static class DocumentRegion extends TextRegion { IRegion fRegion; + public DocumentRegion(IRegion region) { - fRegion= region; + fRegion = region; } + public int getOffset() { return fRegion.getOffset(); } + public int getLength() { return fRegion.getLength(); } } - + public class Block { public String content; + public int offsetDelta; } - + private IDocument fDocument; - - private static final TextBufferFactory fgFactory= new TextBufferFactory(); - + + private static final TextBufferFactory fgFactory = new TextBufferFactory(); + TextBuffer(IDocument document) { - fDocument= document; + fDocument = document; Assert.isNotNull(fDocument); } - + /** * Returns the number of characters in this text buffer. - * + * * @return the number of characters in this text buffer */ public int getLength() { return fDocument.getLength(); } - + /** * Returns the number of lines in this text buffer. * @@ -77,14 +81,16 @@ public class TextBuffer { public int getNumberOfLines() { return fDocument.getNumberOfLines(); } - + /** * Returns the character at the given offset in this text buffer. - * - * @param offset a text buffer offset + * + * @param offset + * a text buffer offset * @return the character at the offset - * @exception IndexOutOfBoundsException if the offset - * argument is negative or not less than the length of this text buffer. + * @exception IndexOutOfBoundsException + * if the offset argument is negative or not + * less than the length of this text buffer. */ public char getChar(int offset) { try { @@ -93,21 +99,22 @@ public class TextBuffer { throw new ArrayIndexOutOfBoundsException(e.getMessage()); } } - + /** * Returns the whole content of the text buffer. - * + * * @return the whole content of the text buffer */ public String getContent() { return fDocument.get(); } - + /** * Returns length characters starting from the specified position. - * + * * @return the characters specified by the given text region. Returns - * null if text range is illegal + * null + * if text range is illegal */ public String getContent(int start, int length) { try { @@ -116,129 +123,134 @@ public class TextBuffer { return null; } } - + public Block getBlockContent(int start, int length, int tabWidth) { - Block result= new Block(); - StringBuffer buffer= new StringBuffer(); - int lineOffset= getLineInformationOfOffset(start).getOffset(); + Block result = new Block(); + StringBuffer buffer = new StringBuffer(); + int lineOffset = getLineInformationOfOffset(start).getOffset(); if (start > lineOffset) { - String line= getContent(lineOffset, start - lineOffset); - String indent= Strings.getIndentString(line, tabWidth); - result.offsetDelta= -indent.length(); + String line = getContent(lineOffset, start - lineOffset); + String indent = Strings.getIndentString(line, tabWidth); + result.offsetDelta = -indent.length(); buffer.append(indent); } - final int end= start + length; - TextRegion region= getLineInformationOfOffset(end); - lineOffset= region.getOffset(); + final int end = start + length; + TextRegion region = getLineInformationOfOffset(end); + lineOffset = region.getOffset(); // Cursor is at beginning of next line if (lineOffset == end) { - int lineNumber= getLineOfOffset(lineOffset); + int lineNumber = getLineOfOffset(lineOffset); if (lineNumber > 0) { - length= length - getLineDelimiter(lineNumber - 1).length(); + length = length - getLineDelimiter(lineNumber - 1).length(); } } if (buffer.length() == 0) { - result.content= getContent(start, length); + result.content = getContent(start, length); } else { buffer.append(getContent(start, length)); - result.content= buffer.toString(); + result.content = buffer.toString(); } return result; } - + /** * Returns the preferred line delimiter to be used for this text buffer. * * @return the preferred line delimiter */ public String getLineDelimiter() { - String lineDelimiter= getLineDelimiter(0); + String lineDelimiter = getLineDelimiter(0); if (lineDelimiter == null) - lineDelimiter= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ + lineDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ return lineDelimiter; } - + /** * Returns the line delimiter used for the given line number. Returns - * null if the line number is out of range. - * - * @return the line delimiter used by the given line number or null + * null + * if the line number is out of range. + * + * @return the line delimiter used by the given line number or + * null */ public String getLineDelimiter(int line) { try { return fDocument.getLineDelimiter(line); } catch (BadLocationException e) { return null; - } + } } - + /** * Returns the line for the given line number. If there isn't any line for * the given line number, null is returned. - * + * * @return the line for the given line number or null */ public String getLineContent(int line) { try { - IRegion region= fDocument.getLineInformation(line); + IRegion region = fDocument.getLineInformation(line); return fDocument.get(region.getOffset(), region.getLength()); } catch (BadLocationException e) { return null; } } - + /** - * Returns the line indent for the given line. If there isn't any line for the - * given line number, -1 is returned. + * Returns the line indent for the given line. If there isn't any line for + * the given line number, -1 is returned. * * @return the line indent for the given line number of -1 */ public int getLineIndent(int lineNumber, int tabWidth) { return Strings.computeIndent(getLineContent(lineNumber), tabWidth); } - + /** - * Returns a region of the specified line. The region contains the offset and the - * length of the line excluding the line's delimiter. Returns null - * if the line doesn't exist. - * - * @param line the line of interest - * @return a line description or null if the given line doesn't - * exist + * Returns a region of the specified line. The region contains the offset + * and the length of the line excluding the line's delimiter. Returns + * null if the line doesn't exist. + * + * @param line + * the line of interest + * @return a line description or null if the given line + * doesn't exist */ public TextRegion getLineInformation(int line) { try { return new DocumentRegion(fDocument.getLineInformation(line)); } catch (BadLocationException e) { return null; - } + } } - + /** - * Returns a line region of the specified offset. The region contains the offset and - * the length of the line excluding the line's delimiter. Returns null - * if the line doesn't exist. - * - * @param offset an offset into a line - * @return a line description or null if the given line doesn't - * exist - */ + * Returns a line region of the specified offset. The region contains the + * offset and the length of the line excluding the line's delimiter. Returns + * null if the line doesn't exist. + * + * @param offset + * an offset into a line + * @return a line description or null if the given line + * doesn't exist + */ public TextRegion getLineInformationOfOffset(int offset) { try { - return new DocumentRegion(fDocument.getLineInformationOfOffset(offset)); + return new DocumentRegion(fDocument + .getLineInformationOfOffset(offset)); } catch (BadLocationException e) { return null; - } + } } - + /** - * Returns the line number that contains the given position. If there isn't any - * line that contains the position, null is returned. The returned - * string is a copy and doesn't contain the line delimiter. - * - * @return the line that contains the given offset or null if line - * doesn't exist - */ + * Returns the line number that contains the given position. If there isn't + * any line that contains the position, null is returned. The + * returned string is a copy and doesn't contain the line delimiter. + * + * @return the line that contains the given offset or null if + * line doesn't exist + */ public int getLineOfOffset(int offset) { try { return fDocument.getLineOfOffset(offset); @@ -249,15 +261,15 @@ public class TextBuffer { /** * Returns the line that contains the given position. If there isn't any - * line that contains the position, null is returned. The returned - * string is a copy and doesn't contain the line delimiter. - * - * @return the line that contains the given offset or null if line - * doesn't exist - */ + * line that contains the position, null is returned. The + * returned string is a copy and doesn't contain the line delimiter. + * + * @return the line that contains the given offset or null if + * line doesn't exist + */ public String getLineContentOfOffset(int offset) { try { - IRegion region= fDocument.getLineInformationOfOffset(offset); + IRegion region = fDocument.getLineInformationOfOffset(offset); return fDocument.get(region.getOffset(), region.getLength()); } catch (BadLocationException e) { return null; @@ -265,25 +277,28 @@ public class TextBuffer { } /** - * Converts the text determined by the region [offset, length] into an array of lines. - * The lines are copies of the original lines and don't contain any line delimiter - * characters. - * - * @return the text converted into an array of strings. Returns null if the - * region lies outside the source. + * Converts the text determined by the region [offset, length] into an array + * of lines. The lines are copies of the original lines and don't contain + * any line delimiter characters. + * + * @return the text converted into an array of strings. Returns + * null if the region lies outside the source. */ - public String[] convertIntoLines(int offset, int length, boolean lastNewLineCreateEmptyLine) { + public String[] convertIntoLines(int offset, int length, + boolean lastNewLineCreateEmptyLine) { try { - String text= fDocument.get(offset, length); - ILineTracker tracker= new DefaultLineTracker(); + String text = fDocument.get(offset, length); + ILineTracker tracker = new DefaultLineTracker(); tracker.set(text); - int size= tracker.getNumberOfLines(); - int lastLine= size - 1; - List result= new ArrayList(size); - for (int i= 0; i < size; i++) { - IRegion region= tracker.getLineInformation(i); - String line= getContent(offset + region.getOffset(), region.getLength()); - if (i < lastLine || !"".equals(line) || lastNewLineCreateEmptyLine) //$NON-NLS-1$ + int size = tracker.getNumberOfLines(); + int lastLine = size - 1; + List result = new ArrayList(size); + for (int i = 0; i < size; i++) { + IRegion region = tracker.getLineInformation(i); + String line = getContent(offset + region.getOffset(), region + .getLength()); + if (i < lastLine + || !"".equals(line) || lastNewLineCreateEmptyLine) //$NON-NLS-1$ result.add(line); } return (String[]) result.toArray(new String[result.size()]); @@ -291,66 +306,76 @@ public class TextBuffer { return null; } } - + /** * Subsitutes the given text for the specified text position - * - * @param offset the starting offset of the text to be replaced - * @param length the length of the text to be replaced - * @param text the substitution text - * @exception CoreException if the text position [offset, length] is invalid. + * + * @param offset + * the starting offset of the text to be replaced + * @param length + * the length of the text to be replaced + * @param text + * the substitution text + * @exception CoreException + * if the text position [offset, length] is invalid. */ - public void replace(int offset, int length, String text) throws CoreException { + public void replace(int offset, int length, String text) + throws CoreException { try { fDocument.replace(offset, length, text); } catch (BadLocationException e) { - IStatus s = new Status(IStatus.ERROR, PHPeclipsePlugin.getPluginId(), PHPStatusConstants.INTERNAL_ERROR, - TextManipulationMessages.getFormattedString( - "TextBuffer.wrongRange", //$NON-NLS-1$ - new Object[] {new Integer(offset), new Integer(length) } ), e); + IStatus s = new Status(IStatus.ERROR, PHPeclipsePlugin + .getPluginId(), PHPStatusConstants.INTERNAL_ERROR, + TextManipulationMessages.getFormattedString( + "TextBuffer.wrongRange", //$NON-NLS-1$ + new Object[] { new Integer(offset), + new Integer(length) }), e); throw new CoreException(s); - } + } } - + public void replace(TextRange range, String text) throws CoreException { replace(range.fOffset, range.fLength, text); } - //---- Special methods used by the TextBufferEditor - + // ---- Special methods used by the TextBufferEditor + /** * Releases this text buffer. */ - /* package */ void release() { + /* package */void release() { } - - /* package */ void registerUpdater(IDocumentListener listener) { + + /* package */void registerUpdater(IDocumentListener listener) { fDocument.addDocumentListener(listener); } - - /* package */ void unregisterUpdater(IDocumentListener listener) { + + /* package */void unregisterUpdater(IDocumentListener listener) { fDocument.removeDocumentListener(listener); } - - //---- Factory methods ---------------------------------------------------------------- - + + // ---- Factory methods + // ---------------------------------------------------------------- + /** * Acquires a text buffer for the given file. If a text buffer for the given * file already exists, then that one is returned. * - * @param file the file for which a text buffer is requested + * @param file + * the file for which a text buffer is requested * @return a managed text buffer for the given file - * @exception CoreException if it was not possible to acquire the - * text buffer + * @exception CoreException + * if it was not possible to acquire the text buffer */ public static TextBuffer acquire(IFile file) throws CoreException { return fgFactory.acquire(file); } - + /** * Releases the given text buffer. * - * @param buffer the text buffer to be released + * @param buffer + * the text buffer to be released */ public static void release(TextBuffer buffer) { fgFactory.release(buffer); @@ -360,60 +385,70 @@ public class TextBuffer { * Commits the changes made to the given text buffer to the underlying * storage system. * - * @param buffer the text buffer containing the changes to be committed. - * @param force if true the text buffer is committed in any case. - * If false the text buffer is ONLY committed if the client - * is the last one that holds a reference to the text buffer. Clients of this - * method must make sure that they don't call this method from within an + * @param buffer + * the text buffer containing the changes to be committed. + * @param force + * if true the text buffer is committed in any + * case. If false the text buffer is ONLY + * committed if the client is the last one that holds a reference + * to the text buffer. Clients of this method must make sure that + * they don't call this method from within an * IWorkspaceRunnable. - * @param pm the progress monitor used to report progress if committing is - * necessary + * @param pm + * the progress monitor used to report progress if committing is + * necessary */ - public static void commitChanges(TextBuffer buffer, boolean force, IProgressMonitor pm) throws CoreException { + public static void commitChanges(TextBuffer buffer, boolean force, + IProgressMonitor pm) throws CoreException { fgFactory.commitChanges(buffer, force, pm); } - + /** * Creates a new TextBuffer for the given file. The returned * buffer will not be managed. Any subsequent call to create * with the same file will return a different text buffer. *

                                                      - * If the file is currently open in a text editor, the editors content is copied into - * the returned TextBuffer. Otherwise the content is read from - * disk. + * If the file is currently open in a text editor, the editors content is + * copied into the returned TextBuffer. Otherwise the + * content is read from disk. * - * @param file the file for which a text buffer is to be created + * @param file + * the file for which a text buffer is to be created * @return a new unmanaged text buffer - * @exception CoreException if it was not possible to create the text buffer + * @exception CoreException + * if it was not possible to create the text buffer */ public static TextBuffer create(IFile file) throws CoreException { return fgFactory.create(file); } - + /** * Creates a new TextBuffer for the string. The returned * buffer will not be managed. Any subsequent call to create * with the identical string will return a different text buffer. * - * @param content the text buffer's content + * @param content + * the text buffer's content * @return a new unmanaged text buffer */ public static TextBuffer create(String content) { return fgFactory.create(content); } - - // Unclear which methods are needed if we get the new save model. If optimal no + + // Unclear which methods are needed if we get the new save model. If optimal + // no // save is needed at all. - - public static void save(TextBuffer buffer, IProgressMonitor pm) throws CoreException { + + public static void save(TextBuffer buffer, IProgressMonitor pm) + throws CoreException { fgFactory.save(buffer, pm); } - + public static void aboutToChange(TextBuffer buffer) throws CoreException { fgFactory.aboutToChange(buffer); } - + public static void changed(TextBuffer buffer) throws CoreException { fgFactory.changed(buffer); - } + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextBufferEditor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextBufferEditor.java index d622569..3ea69bc 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextBufferEditor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextBufferEditor.java @@ -14,48 +14,58 @@ import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; -//import net.sourceforge.phpdt.core.IJavaModelStatusConstants; -//import net.sourceforge.phpdt.core.JavaModelException; +// import net.sourceforge.phpdt.core.IJavaModelStatusConstants; +// import net.sourceforge.phpdt.core.JavaModelException; // -//import net.sourceforge.phpdt.internal.corext.Assert; - +// import net.sourceforge.phpdt.internal.corext.Assert; /** - * A TextBufferEditor manages a set of TextEdits and applies - * them as a whole to a TextBuffer. Added TextEdits must - * not overlap. The only exception from this rule are insertion point. There can be more than - * one insert point at the same text position. Clients should use the method - * canPerformEdits to validate if all added text edits follow these rules. + * A TextBufferEditor manages a set of TextEdits + * and applies them as a whole to a TextBuffer. Added + * TextEdits must not overlap. The only exception from this rule + * are insertion point. There can be more than one insert point at the same text + * position. Clients should use the method + * canPerformEdits to + * validate if all added text edits follow these rules. *

                                                      - * Clients can attach more than one TextBufferEditor to a single - * TextBuffer. If so canPerformEdits validates all text edits from - * all text buffer editors working on the same text buffer. + * Clients can attach more than one TextBufferEditor to a single + * + * TextBuffer. If so canPerformEdits validates + * all text edits from all text buffer editors working on the same text buffer. */ public class TextBufferEditor { - + private TextBuffer fBuffer; + private List fEdits; + private RootNode fRootNode; + private int fNumberOfNodes; + private int fConnectCount; + private int fMode; - /* package */ static final int UNDEFINED= 0; - /* package */ static final int REDO= 1; - /* package */ static final int UNDO= 2; + /* package */static final int UNDEFINED = 0; + + /* package */static final int REDO = 1; + + /* package */static final int UNDO = 2; /** - * Creates a new TextBufferEditor for the given + * Creates a new TextBufferEditor for the given * TextBuffer. * - * @param the text buffer this editor is working on. + * @param the + * text buffer this editor is working on. */ public TextBufferEditor(TextBuffer buffer) { - fBuffer= buffer; - // Assert.isNotNull(fBuffer); - fEdits= new ArrayList(); + fBuffer = buffer; + // Assert.isNotNull(fBuffer); + fEdits = new ArrayList(); } - + /** * Returns the text buffer this editor is working on. * @@ -64,119 +74,134 @@ public class TextBufferEditor { public TextBuffer getTextBuffer() { return fBuffer; } - + /** - * Adds a TextEdit to this text editor. Adding a TextEdit - * to a TextBufferEditor transfers ownership of the edit to the editor. So - * after a edit has been added to a editor the creator of that edit must not continue - * modifing it. + * Adds a TextEdit to this text editor. Adding a + * TextEdit to a TextBufferEditor transfers + * ownership of the edit to the editor. So after a edit has been added to a + * editor the creator of that edit must not continue modifing it. * - * @param edit the text edit to be added - * @exception CoreException if the text edit can not be added - * to this text buffer editor + * @param edit + * the text edit to be added + * @exception CoreException + * if the text edit can not be added to this text buffer + * editor */ public void add(TextEdit edit) throws CoreException { - // Assert.isTrue(fMode == UNDEFINED || fMode == REDO); + // Assert.isTrue(fMode == UNDEFINED || fMode == REDO); internalAdd(edit); - fMode= REDO; + fMode = REDO; } - + /** - * Adds a MultiTextEdit to this text editor. Adding a MultiTextEdit - * to a TextBufferEditor transfers ownership of the edit to the editor. So - * after a edit has been added to a editor the creator of that edit must not continue + * Adds a MultiTextEdit to this text editor. Adding a + * MultiTextEdit to a TextBufferEditor + * transfers ownership of the edit to the editor. So after a edit has been + * added to a editor the creator of that edit must not continue * modifing it. * - * @param edit the multi text edit to be added - * @exception CoreException if the multi text edit can not be added - * to this text buffer editor + * @param edit + * the multi text edit to be added + * @exception CoreException + * if the multi text edit can not be added to this text + * buffer editor */ public void add(MultiTextEdit edit) throws CoreException { - // Assert.isTrue(fMode == UNDEFINED || fMode == REDO); + // Assert.isTrue(fMode == UNDEFINED || fMode == REDO); edit.connect(this); - fMode= REDO; + fMode = REDO; } /** - * Adds a UndoMemento to this text editor. Adding a UndoMemento - * to a TextBufferEditor transfers ownership of the memento to the editor. So - * after a memento has been added to a editor the creator of that memento must not continue + * Adds a UndoMemento to this text editor. Adding a + * UndoMemento to a TextBufferEditor transfers + * ownership of the memento to the editor. So after a memento has been added + * to a editor the creator of that memento must not continue * modifing it. * - * @param undo the undo memento to be added - * @exception CoreException if the undo memento can not be added - * to this text buffer editor + * @param undo + * the undo memento to be added + * @exception CoreException + * if the undo memento can not be added to this text buffer + * editor */ public void add(UndoMemento undo) throws CoreException { - // Assert.isTrue(fMode == UNDEFINED); - List list= undo.fEdits; + // Assert.isTrue(fMode == UNDEFINED); + List list = undo.fEdits; // Add them reverse since we are adding undos. - for (int i= list.size() - 1; i >= 0; i--) { - internalAdd((TextEdit)list.get(i)); + for (int i = list.size() - 1; i >= 0; i--) { + internalAdd((TextEdit) list.get(i)); } - fMode= undo.fMode; + fMode = undo.fMode; } - + /** - * Checks if the TextEdit added to this text editor can be executed. + * Checks if the TextEdit added to this text editor can be + * executed. * - * @return true if the edits can be executed. Return false - * otherwise. One major reason why text edits cannot be executed - * is a wrong offset or length value of a TextEdit. + * @return true if the edits can be executed. Return + * false + * otherwise. One major reason why text edits + * cannot be executed is a wrong offset or length value of a + * TextEdit. */ public boolean canPerformEdits() { if (fRootNode != null) return true; - fRootNode= buildTree(); + fRootNode = buildTree(); if (fRootNode == null) return false; if (fRootNode.validate(fBuffer.getLength())) return true; - - fRootNode= null; + + fRootNode = null; return false; } - + /** * Clears the text buffer editor. */ public void clear() { - fRootNode= null; - fMode= UNDEFINED; + fRootNode = null; + fMode = UNDEFINED; fEdits.clear(); } - + /** - * Executes the text edits added to this text buffer editor and clears all added - * text edits. + * Executes the text edits added to this text buffer editor and clears all + * added text edits. * - * @param pm a progress monitor to report progress or null if - * no progress is desired. - * @return an object representing the undo of the executed TextEdits - * @exception CoreException if the edits cannot be executed + * @param pm + * a progress monitor to report progress or null + * if no progress is desired. + * @return an object representing the undo of the executed + * TextEdits + * @exception CoreException + * if the edits cannot be executed */ public UndoMemento performEdits(IProgressMonitor pm) throws CoreException { if (pm == null) - pm= new NullProgressMonitor(); - - int size= fEdits.size(); + pm = new NullProgressMonitor(); + + int size = fEdits.size(); if (size == 0) return new UndoMemento(fMode == UNDO ? REDO : UNDO); - + if (fRootNode == null) { - fRootNode= buildTree(); + fRootNode = buildTree(); if (fRootNode == null || !fRootNode.validate(fBuffer.getLength())) { - // throw new JavaModelException(null, IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS); - } + // throw new JavaModelException(null, + // IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS); + } } try { pm.beginTask("", fNumberOfNodes + 10); //$NON-NLS-1$ - UndoMemento undo= null; + UndoMemento undo = null; if (fMode == REDO) { - undo= fRootNode.performDo(fBuffer, pm); + undo = fRootNode.performDo(fBuffer, pm); fRootNode.performedDo(); } else { - undo= fRootNode.performUndo(fBuffer, pm); + undo = fRootNode.performUndo(fBuffer, pm); fRootNode.performedUndo(); } pm.worked(10); @@ -186,26 +211,27 @@ public class TextBufferEditor { clear(); } } - - //---- Helper methods ------------------------------------------------------------ - + + // ---- Helper methods + // ------------------------------------------------------------ + private RootNode buildTree() { - TextEditNode[] nodes= new TextEditNode[fEdits.size()]; - for (int i= fEdits.size() - 1; i >= 0; i--) { - nodes[i]= TextEditNode.create((TextEdit)fEdits.get(i)); + TextEditNode[] nodes = new TextEditNode[fEdits.size()]; + for (int i = fEdits.size() - 1; i >= 0; i--) { + nodes[i] = TextEditNode.create((TextEdit) fEdits.get(i)); } - fNumberOfNodes= nodes.length; + fNumberOfNodes = nodes.length; Arrays.sort(nodes, new TextEditNodeComparator()); - RootNode root= new RootNode(fBuffer.getLength()); - for (int i= 0; i < nodes.length; i++) { + RootNode root = new RootNode(fBuffer.getLength()); + for (int i = 0; i < nodes.length; i++) { root.add(nodes[i]); } return root; } - + private void internalAdd(TextEdit edit) throws CoreException { - edit.index= fEdits.size(); - edit.isSynthetic= fConnectCount > 0; + edit.index = fEdits.size(); + edit.isSynthetic = fConnectCount > 0; try { fConnectCount++; edit.connect(this); @@ -213,6 +239,5 @@ public class TextBufferEditor { fConnectCount--; } fEdits.add(edit); - } + } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextBufferFactory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextBufferFactory.java index 5ce09f9..b78e53a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextBufferFactory.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextBufferFactory.java @@ -29,85 +29,98 @@ import org.eclipse.jface.util.Assert; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.texteditor.IDocumentProvider; -/* package */ class TextBufferFactory { +/* package */class TextBufferFactory { private IDocumentProvider fDocumentProvider; + private Map fFileValueMap; + private Map fBufferValueMap; - + private static class Value { TextBuffer buffer; + FileEditorInput input; + IDocument document; + IAnnotationModel annotationModel; + int references; - public Value(TextBuffer b, FileEditorInput i, IDocument d, IAnnotationModel m) { - buffer= b; - input= i; - document= d; - annotationModel= m; + + public Value(TextBuffer b, FileEditorInput i, IDocument d, + IAnnotationModel m) { + buffer = b; + input = i; + document = d; + annotationModel = m; } } public TextBufferFactory() { // XXX http://dev.eclipse.org/bugs/show_bug.cgi?id=5170 - // Need way to map a file to a document without knowing any kind of document provider. + // Need way to map a file to a document without knowing any kind of + // document provider. this(PHPeclipsePlugin.getDefault().getCompilationUnitDocumentProvider()); } - + public TextBufferFactory(IDocumentProvider provider) { - fDocumentProvider= provider; + fDocumentProvider = provider; Assert.isNotNull(fDocumentProvider); - fFileValueMap= new HashMap(5); - fBufferValueMap= new HashMap(5); + fFileValueMap = new HashMap(5); + fBufferValueMap = new HashMap(5); } public TextBuffer acquire(IFile file) throws CoreException { - FileEditorInput input= new FileEditorInput(file); - - Value value= (Value)fFileValueMap.get(input); + FileEditorInput input = new FileEditorInput(file); + + Value value = (Value) fFileValueMap.get(input); if (value != null) { value.references++; return value.buffer; } - + fDocumentProvider.connect(input); - IDocument document= fDocumentProvider.getDocument(input); - IAnnotationModel annotationModel= fDocumentProvider.getAnnotationModel(input); + IDocument document = fDocumentProvider.getDocument(input); + IAnnotationModel annotationModel = fDocumentProvider + .getAnnotationModel(input); annotationModel.connect(document); - value= new Value(new TextBuffer(document), input, document, annotationModel); + value = new Value(new TextBuffer(document), input, document, + annotationModel); fFileValueMap.put(input, value); fBufferValueMap.put(value.buffer, value); value.references++; return value.buffer; } - + public void release(TextBuffer buffer) { - final Value value= (Value)fBufferValueMap.get(buffer); + final Value value = (Value) fBufferValueMap.get(buffer); if (value == null) return; - + value.references--; if (value.references == 0) { - buffer.release(); + buffer.release(); value.annotationModel.disconnect(value.document); fDocumentProvider.disconnect(value.input); fFileValueMap.remove(value.input); fBufferValueMap.remove(buffer); } } - - public void commitChanges(TextBuffer buffer, boolean force, IProgressMonitor pm) throws CoreException { - final Value value= (Value)fBufferValueMap.get(buffer); + + public void commitChanges(TextBuffer buffer, boolean force, + IProgressMonitor pm) throws CoreException { + final Value value = (Value) fBufferValueMap.get(buffer); if (value == null) return; - - boolean save= force || fDocumentProvider.mustSaveDocument(value.input); + + boolean save = force || fDocumentProvider.mustSaveDocument(value.input); if (save) { - IWorkspaceRunnable action= new IWorkspaceRunnable() { + IWorkspaceRunnable action = new IWorkspaceRunnable() { public void run(IProgressMonitor pm) throws CoreException { fDocumentProvider.aboutToChange(value.input); - fDocumentProvider.saveDocument(pm, value.input, value.document, true); + fDocumentProvider.saveDocument(pm, value.input, + value.document, true); } }; try { @@ -117,10 +130,10 @@ import org.eclipse.ui.texteditor.IDocumentProvider; } } } - + public TextBuffer create(IFile file) throws CoreException { - FileEditorInput input= new FileEditorInput(file); - IDocument document= fDocumentProvider.getDocument(input); + FileEditorInput input = new FileEditorInput(file); + IDocument document = fDocumentProvider.getDocument(input); if (document != null) { return new TextBuffer(new Document(document.get())); } else { @@ -131,57 +144,61 @@ import org.eclipse.ui.texteditor.IDocumentProvider; private TextBuffer createFromFile(IFile file) throws CoreException { IDocument document; // Fix for http://dev.eclipse.org/bugs/show_bug.cgi?id=19319 - InputStream stream= file.getContents(); - InputStreamReader in= null; - try { - document= new Document(); - in= new InputStreamReader(new BufferedInputStream(stream), ResourcesPlugin.getEncoding()); - StringBuffer buffer= new StringBuffer(); - char[] readBuffer= new char[2048]; - int n= in.read(readBuffer); + InputStream stream = file.getContents(); + InputStreamReader in = null; + try { + document = new Document(); + in = new InputStreamReader(new BufferedInputStream(stream), + ResourcesPlugin.getEncoding()); + StringBuffer buffer = new StringBuffer(); + char[] readBuffer = new char[2048]; + int n = in.read(readBuffer); while (n > 0) { buffer.append(readBuffer, 0, n); - n= in.read(readBuffer); + n = in.read(readBuffer); } document.set(buffer.toString()); return new TextBuffer(document); } catch (IOException x) { - IStatus s= new Status(IStatus.ERROR, PHPeclipsePlugin.getPluginId(), PHPStatusConstants.INTERNAL_ERROR, x.getMessage(), x); + IStatus s = new Status(IStatus.ERROR, PHPeclipsePlugin + .getPluginId(), PHPStatusConstants.INTERNAL_ERROR, x + .getMessage(), x); throw new CoreException(s); } finally { IOCloser.perform(in, stream); } } - + public TextBuffer create(String content) { return new TextBuffer(new Document(content)); } - - public void save(TextBuffer buffer, IProgressMonitor pm) throws CoreException { - Value value= (Value)fBufferValueMap.get(buffer); + + public void save(TextBuffer buffer, IProgressMonitor pm) + throws CoreException { + Value value = (Value) fBufferValueMap.get(buffer); if (value == null) throwNotManaged(); fDocumentProvider.saveDocument(pm, value.input, value.document, true); } public void aboutToChange(TextBuffer buffer) throws CoreException { - Value value= (Value)fBufferValueMap.get(buffer); + Value value = (Value) fBufferValueMap.get(buffer); if (value == null) throwNotManaged(); fDocumentProvider.aboutToChange(value.input); } - + public void changed(TextBuffer buffer) throws CoreException { - Value value= (Value)fBufferValueMap.get(buffer); + Value value = (Value) fBufferValueMap.get(buffer); if (value == null) throwNotManaged(); fDocumentProvider.changed(value.input); } - + private void throwNotManaged() throws CoreException { - IStatus s= new Status(IStatus.ERROR, PHPeclipsePlugin.getPluginId(), - PHPStatusConstants.INTERNAL_ERROR, TextManipulationMessages.getString("TextBufferFactory.bufferNotManaged"), null); //$NON-NLS-1$ + IStatus s = new Status(IStatus.ERROR, PHPeclipsePlugin.getPluginId(), + PHPStatusConstants.INTERNAL_ERROR, TextManipulationMessages + .getString("TextBufferFactory.bufferNotManaged"), null); //$NON-NLS-1$ throw new CoreException(s); } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextEdit.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextEdit.java index 933aad4..2b975af 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextEdit.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextEdit.java @@ -11,23 +11,26 @@ import org.eclipse.core.runtime.CoreException; * are executed by adding them to a TextBufferEditor and then * calling perform on the TextBufferEditor. *

                                                      - * After a TextEdit has been added to a TextBufferEditor - * the method connect is sent to the text edit. A TextEdit - * is allowed to do some adjustments of the text range it is going to manipulate while inside - * the hook connect. + * After a TextEdit has been added to a + * TextBufferEditor the method connect is sent to + * the text edit. A TextEdit is allowed to do some adjustments of + * the text range it is going to manipulate while inside the hook + * connect. * * @see TextBufferEditor */ public abstract class TextEdit { - + // index that determines the insertion order into a text buffer - /* package */ int index; - /* package */ boolean isSynthetic; - + /* package */int index; + + /* package */boolean isSynthetic; + /** - * Connects this text edit to the given TextBufferEditor. A text edit - * must not keep a reference to the passed text buffer editor. It is guaranteed that - * the buffer passed to perform is equal to the buffer managed by + * Connects this text edit to the given TextBufferEditor. A + * text edit must not keep a reference to the passed text buffer editor. It + * is guaranteed that the buffer passed to + * perform is equal to the buffer managed by * the given text buffer editor. But they don't have to be identical. *

                                                      * Note that this method should only be called by a @@ -41,53 +44,54 @@ public abstract class TextEdit { public void connect(TextBufferEditor editor) throws CoreException { // does nothing } - + /** * Returns the TextRange that this text edit is going to * manipulate. If this method is called before the TextEdit * has been added to a TextBufferEditor it may return - * null or TextRange.UNDEFINED to indicate this situation. + * null + * or TextRange.UNDEFINED to indicate this situation. * * @return the TextRanges this TextEdit is going * to manipulate */ public abstract TextRange getTextRange(); - + /** - * Performs the text edit. Note that this method should only be called - * by a TextBufferEditor. + * Performs the text edit. Note that this method should only be called + * by a TextBufferEditor. * - * @param buffer the actual buffer to manipulate + * @param buffer + * the actual buffer to manipulate * @return a text edit that can undo this text edit */ public abstract TextEdit perform(TextBuffer buffer) throws CoreException; - + /** - * This method gets called after all TextEdits added to a text buffer - * editor are executed. Implementors of this method can do some clean-up or can - * release allocated resources that are now longer needed. + * This method gets called after all TextEdits added to a + * text buffer editor are executed. Implementors of this method can do some + * clean-up or can release allocated resources that are now longer needed. *

                                                      * This default implementation does nothing. */ public void performed() { // do nothing } - + /** - * Creates and returns a copy of this object. The copy method should - * be implemented in a way so that the copy can be added to a different - * TextBufferEditor without causing any harm to the object - * from which the copy has been created. - * - * @return a copy of this object. - */ - public abstract TextEdit copy() throws CoreException; - + * Creates and returns a copy of this object. The copy method should be + * implemented in a way so that the copy can be added to a different + * TextBufferEditor without causing any harm to the object + * from which the copy has been created. + * + * @return a copy of this object. + */ + public abstract TextEdit copy() throws CoreException; + /** - * Returns the element modified by this text edit. The method - * may return null if the modification isn't related to a - * element or if the content of the modified text buffer doesn't - * follow any syntax. + * Returns the element modified by this text edit. The method may return + * null if the modification isn't related to a element or if + * the content of the modified text buffer doesn't follow any syntax. *

                                                      * This default implementation returns null * @@ -95,6 +99,5 @@ public abstract class TextEdit { */ public Object getModifiedElement() { return null; - } + } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextEditNode.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextEditNode.java index 7cfaa70..b8e11fb 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextEditNode.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextEditNode.java @@ -13,35 +13,40 @@ import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocumentListener; - /** - * A helper class to arrange TextEdits into a tree to optimize their - * execution. + * A helper class to arrange TextEdits into a tree to optimize + * their execution. */ -/* package */ abstract class TextEditNode { +/* package */abstract class TextEditNode { + + /* package */TextEditNode fParent; + + /* package */List fChildren; - /* package */ TextEditNode fParent; - /* package */ List fChildren; - /* package */ TextEdit fEdit; - - /* package */ static class DefaultNode extends TextEditNode { + /* package */TextEdit fEdit; + + /* package */static class DefaultNode extends TextEditNode { public DefaultNode(TextEdit edit) { super(edit); } } - - /* package */ static class RootNode extends TextEditNode { + + /* package */static class RootNode extends TextEditNode { private int fUndoIndex; + public RootNode(int length) { super(new NopTextEdit(new TextRange(0, length))); - fEdit.isSynthetic= true; + fEdit.isSynthetic = true; } + public boolean covers(TextEditNode node) { return true; } - public UndoMemento performDo(TextBuffer buffer, IProgressMonitor pm) throws CoreException { - DoRangeUpdater updater= new DoRangeUpdater(); - UndoMemento undo= new UndoMemento(TextBufferEditor.UNDO); + + public UndoMemento performDo(TextBuffer buffer, IProgressMonitor pm) + throws CoreException { + DoRangeUpdater updater = new DoRangeUpdater(); + UndoMemento undo = new UndoMemento(TextBufferEditor.UNDO); try { buffer.registerUpdater(updater); performDo(buffer, updater, undo, pm); @@ -51,9 +56,11 @@ import org.eclipse.jface.text.IDocumentListener; } return undo; } - public UndoMemento performUndo(TextBuffer buffer, IProgressMonitor pm) throws CoreException { - UndoRangeUpdater updater= new UndoRangeUpdater(this); - UndoMemento undo= new UndoMemento(TextBufferEditor.REDO); + + public UndoMemento performUndo(TextBuffer buffer, IProgressMonitor pm) + throws CoreException { + UndoRangeUpdater updater = new UndoRangeUpdater(this); + UndoMemento undo = new UndoMemento(TextBufferEditor.REDO); try { buffer.registerUpdater(updater); performUndo(buffer, updater, undo, pm); @@ -63,239 +70,286 @@ import org.eclipse.jface.text.IDocumentListener; } return undo; } - + protected void setUndoIndex(int index) { - fUndoIndex= index; + fUndoIndex = index; } - + protected int getUndoIndex() { return fUndoIndex; } } - - /* package */ abstract static class AbstractMoveNode extends TextEditNode { - private int state; - + + /* package */abstract static class AbstractMoveNode extends TextEditNode { + private int state; + private int fTargetIndex; + private int fSourceIndex; - + private List fAffectedChildren; - + public AbstractMoveNode(TextEdit edit) { super(edit); reset(); } + protected abstract TextRange getSourceRange(); + protected abstract TextRange getTargetRange(); + protected abstract boolean isUpMove(); + protected boolean isDownMove() { return !isUpMove(); } + public boolean isMove() { return true; } + protected void checkRange(DocumentEvent event) { - TextRange range= getChildRange(); - int eventOffset= event.getOffset(); - int eventLength= event.getLength(); + TextRange range = getChildRange(); + int eventOffset = event.getOffset(); + int eventLength = event.getLength(); int eventEnd = eventOffset + eventLength - 1; // "Edit changes text that lies outside its defined range" - // Assert.isTrue(range.fOffset <= eventOffset && eventEnd <= range.getInclusiveEnd()); + // Assert.isTrue(range.fOffset <= eventOffset && eventEnd <= + // range.getInclusiveEnd()); } + protected boolean activeNodeChanged(int delta) { - TextRange targetRange= getTargetRange(); - TextRange sourceRange= getSourceRange(); + TextRange targetRange = getTargetRange(); + TextRange sourceRange = getSourceRange(); switch (state) { - case 0: // the move delete - init(); - // Assert.isTrue(Math.abs(delta) == sourceRange.fLength); - if (isUpMove()) { - updateOffset(fAffectedChildren, delta); - targetRange.fOffset+= delta; - } - sourceRange.fLength= 0; - state= 1; - break; - case 1: - TextEditNode target= (TextEditNode)fParent.fChildren.get(fTargetIndex); - TextEditNode source= (TextEditNode)fParent.fChildren.get(fSourceIndex); - updateOffset(source.fChildren, targetRange.fOffset - sourceRange.fOffset); - target.fChildren= source.fChildren; - if (target.fChildren != null) { - for (Iterator iter= target.fChildren.iterator(); iter.hasNext();) { - ((TextEditNode)iter.next()).fParent= target; - } - } - source.fChildren= null; - if (isDownMove()) { - updateOffset(fAffectedChildren, delta); - sourceRange.fOffset+= delta; + case 0: // the move delete + init(); + // Assert.isTrue(Math.abs(delta) == sourceRange.fLength); + if (isUpMove()) { + updateOffset(fAffectedChildren, delta); + targetRange.fOffset += delta; + } + sourceRange.fLength = 0; + state = 1; + break; + case 1: + TextEditNode target = (TextEditNode) fParent.fChildren + .get(fTargetIndex); + TextEditNode source = (TextEditNode) fParent.fChildren + .get(fSourceIndex); + updateOffset(source.fChildren, targetRange.fOffset + - sourceRange.fOffset); + target.fChildren = source.fChildren; + if (target.fChildren != null) { + for (Iterator iter = target.fChildren.iterator(); iter + .hasNext();) { + ((TextEditNode) iter.next()).fParent = target; } - targetRange.fLength= delta; - reset(); - break; + } + source.fChildren = null; + if (isDownMove()) { + updateOffset(fAffectedChildren, delta); + sourceRange.fOffset += delta; + } + targetRange.fLength = delta; + reset(); + break; } return true; } + private static void updateOffset(List nodes, int delta) { if (nodes == null) return; - for (int i= nodes.size() - 1; i >= 0; i--) { - TextEditNode node= (TextEditNode)nodes.get(i); - TextRange range= node.getTextRange(); - range.fOffset+= delta; + for (int i = nodes.size() - 1; i >= 0; i--) { + TextEditNode node = (TextEditNode) nodes.get(i); + TextRange range = node.getTextRange(); + range.fOffset += delta; updateOffset(node.fChildren, delta); } } + private void init() { - TextRange source= getSourceRange(); - TextRange target= getTargetRange(); - List children= fParent.fChildren; - for (int i= children.size() - 1; i >= 0; i--) { - TextEditNode child= (TextEditNode)children.get(i); - TextRange range= child.fEdit.getTextRange(); + TextRange source = getSourceRange(); + TextRange target = getTargetRange(); + List children = fParent.fChildren; + for (int i = children.size() - 1; i >= 0; i--) { + TextEditNode child = (TextEditNode) children.get(i); + TextRange range = child.fEdit.getTextRange(); if (range == source) - fSourceIndex= i; + fSourceIndex = i; else if (range == target) - fTargetIndex= i; + fTargetIndex = i; } - int start= Math.min(fTargetIndex, fSourceIndex); - int end= Math.max(fTargetIndex, fSourceIndex); - fAffectedChildren= new ArrayList(3); - for (int i= start + 1; i < end; i++) { + int start = Math.min(fTargetIndex, fSourceIndex); + int end = Math.max(fTargetIndex, fSourceIndex); + fAffectedChildren = new ArrayList(3); + for (int i = start + 1; i < end; i++) { fAffectedChildren.add(children.get(i)); } } + private void reset() { - state= 0; - fSourceIndex= -1; - fTargetIndex= -1; + state = 0; + fSourceIndex = -1; + fTargetIndex = -1; } } - - /* package */ static class MoveNode extends AbstractMoveNode { + + /* package */static class MoveNode extends AbstractMoveNode { public MoveNode(TextEdit edit) { super(edit); } + protected TextRange getChildRange() { - return ((MoveTextEdit)fEdit).getChildRange(); + return ((MoveTextEdit) fEdit).getChildRange(); } + protected TextRange getSourceRange() { - return ((MoveTextEdit)fEdit).getSourceRange(); + return ((MoveTextEdit) fEdit).getSourceRange(); } + protected TextRange getTargetRange() { - return ((MoveTextEdit)fEdit).getTargetRange(); + return ((MoveTextEdit) fEdit).getTargetRange(); } + protected boolean isUpMove() { - return ((MoveTextEdit)fEdit).isUpMove(); + return ((MoveTextEdit) fEdit).isUpMove(); } + public boolean isMovePartner(TextEditNode other) { if (!(other instanceof TargetMarkNode)) return false; - return fEdit == ((MoveTextEdit.TargetMark)other.fEdit).getMoveTextEdit(); + return fEdit == ((MoveTextEdit.TargetMark) other.fEdit) + .getMoveTextEdit(); } + public boolean covers(TextEditNode node) { if (node instanceof TargetMarkNode) { - MoveTextEdit.TargetMark edit= (MoveTextEdit.TargetMark)node.fEdit; + MoveTextEdit.TargetMark edit = (MoveTextEdit.TargetMark) node.fEdit; if (edit.getMoveTextEdit() == fEdit) return false; } return getParentRange().covers(node.getChildRange()); } } - - /* package */ static class TargetMarkNode extends AbstractMoveNode { + + /* package */static class TargetMarkNode extends AbstractMoveNode { public TargetMarkNode(TextEdit edit) { super(edit); } + protected TextRange getChildRange() { - return ((MoveTextEdit.TargetMark)fEdit).getMoveTextEdit().getChildRange(); + return ((MoveTextEdit.TargetMark) fEdit).getMoveTextEdit() + .getChildRange(); } + protected TextRange getSourceRange() { - return ((MoveTextEdit.TargetMark)fEdit).getMoveTextEdit().getSourceRange(); + return ((MoveTextEdit.TargetMark) fEdit).getMoveTextEdit() + .getSourceRange(); } + protected TextRange getTargetRange() { - return ((MoveTextEdit.TargetMark)fEdit).getMoveTextEdit().getTargetRange(); + return ((MoveTextEdit.TargetMark) fEdit).getMoveTextEdit() + .getTargetRange(); } + protected boolean isUpMove() { - return ((MoveTextEdit.TargetMark)fEdit).getMoveTextEdit().isUpMove(); + return ((MoveTextEdit.TargetMark) fEdit).getMoveTextEdit() + .isUpMove(); } + public boolean isMovePartner(TextEditNode other) { - return ((MoveTextEdit.TargetMark)fEdit).getMoveTextEdit() == other.fEdit; + return ((MoveTextEdit.TargetMark) fEdit).getMoveTextEdit() == other.fEdit; } } - //---- Range updating --------------------------------------------------------------------------- + // ---- Range updating + // --------------------------------------------------------------------------- private static abstract class RangeUpdater implements IDocumentListener { protected TextEditNode fActiveNode; + public void documentAboutToBeChanged(DocumentEvent event) { } + public void setActiveNode(TextEditNode node) { - fActiveNode= node; + fActiveNode = node; } + public void updateParents(int delta) { - TextEditNode node= fActiveNode.fParent; + TextEditNode node = fActiveNode.fParent; while (node != null) { node.childNodeChanged(delta); - node= node.fParent; + node = node.fParent; } } + public static int getDelta(DocumentEvent event) { - return (event.getText() == null ? 0 : event.getText().length()) - event.getLength(); + return (event.getText() == null ? 0 : event.getText().length()) + - event.getLength(); } } + private static class DoRangeUpdater extends RangeUpdater { - private List fProcessedNodes= new ArrayList(10); + private List fProcessedNodes = new ArrayList(10); + public void setActiveNode(TextEditNode node) { if (fActiveNode != null) fProcessedNodes.add(fActiveNode); super.setActiveNode(node); } + public void documentChanged(DocumentEvent event) { fActiveNode.checkRange(event); - int delta= getDelta(event); + int delta = getDelta(event); if (!fActiveNode.activeNodeChanged(delta)) { - for (Iterator iter= fProcessedNodes.iterator(); iter.hasNext();) { - ((TextEditNode)iter.next()).previousNodeChanged(delta); + for (Iterator iter = fProcessedNodes.iterator(); iter.hasNext();) { + ((TextEditNode) iter.next()).previousNodeChanged(delta); } } updateParents(delta); } } - private static class UndoRangeUpdater extends RangeUpdater { + + private static class UndoRangeUpdater extends RangeUpdater { private RootNode fRootNode; + public UndoRangeUpdater(RootNode root) { - fRootNode= root; + fRootNode = root; } + public void setActiveNode(TextEditNode node) { super.setActiveNode(node); } + public void documentChanged(DocumentEvent event) { fActiveNode.checkRange(event); - int delta= getDelta(event); + int delta = getDelta(event); if (!fActiveNode.activeNodeChanged(delta)) { - int start= fRootNode.getUndoIndex() + 1; - List children= fRootNode.fChildren; - int size= children != null ? children.size() : 0; - for (int i= start; i < size; i++) { - updateUndo((TextEditNode)children.get(i), delta); + int start = fRootNode.getUndoIndex() + 1; + List children = fRootNode.fChildren; + int size = children != null ? children.size() : 0; + for (int i = start; i < size; i++) { + updateUndo((TextEditNode) children.get(i), delta); } } updateParents(delta); } + private void updateUndo(TextEditNode node, int delta) { node.previousNodeChanged(delta); - List children= node.fChildren; - int size= children != null ? children.size() : 0; - for (int i= 0; i < size; i++) { - updateUndo((TextEditNode)children.get(i), delta); + List children = node.fChildren; + int size = children != null ? children.size() : 0; + for (int i = 0; i < size; i++) { + updateUndo((TextEditNode) children.get(i), delta); } } } - - //---- Creating instances --------------------------------------------------------------------------- - + + // ---- Creating instances + // --------------------------------------------------------------------------- + static TextEditNode create(TextEdit edit) { if (edit instanceof MoveTextEdit) return new MoveNode(edit); @@ -303,34 +357,35 @@ import org.eclipse.jface.text.IDocumentListener; return new TargetMarkNode(edit); return new DefaultNode(edit); } - + static RootNode createRoot(int length) { return new RootNode(length); } - + private TextEditNode(TextEdit edit) { - fEdit= edit; + fEdit = edit; } - - //---- Adding children --------------------------------------------------------------------------- - + + // ---- Adding children + // --------------------------------------------------------------------------- + protected void add(TextEditNode node) { if (fChildren == null) { - fChildren= new ArrayList(1); - node.fParent= this; + fChildren = new ArrayList(1); + node.fParent = this; fChildren.add(node); return; } // Optimize using binary search - for (Iterator iter= fChildren.iterator(); iter.hasNext();) { - TextEditNode child= (TextEditNode)iter.next(); + for (Iterator iter = fChildren.iterator(); iter.hasNext();) { + TextEditNode child = (TextEditNode) iter.next(); if (child.covers(node)) { child.add(node); return; } } - for (int i= 0; i < fChildren.size(); ) { - TextEditNode child= (TextEditNode)fChildren.get(i); + for (int i = 0; i < fChildren.size();) { + TextEditNode child = (TextEditNode) fChildren.get(i); if (node.covers(child)) { fChildren.remove(i); node.add(child); @@ -338,101 +393,111 @@ import org.eclipse.jface.text.IDocumentListener; i++; } } - node.fParent= this; + node.fParent = this; fChildren.add(node); } - + public boolean covers(TextEditNode node) { - return false; + return false; } - - //---- Accessing -------------------------------------------------------------------------------------- - + + // ---- Accessing + // -------------------------------------------------------------------------------------- + protected RootNode getRoot() { - TextEditNode candidate= this; - while(candidate.fParent != null) - candidate= candidate.fParent; - return (RootNode)candidate; + TextEditNode candidate = this; + while (candidate.fParent != null) + candidate = candidate.fParent; + return (RootNode) candidate; } - - //---- Query interface -------------------------------------------------------------------------------- - + + // ---- Query interface + // -------------------------------------------------------------------------------- + protected boolean isSynthetic() { return fEdit.isSynthetic; } - + public boolean isMove() { return false; } - - //---- Accessing Ranges ------------------------------------------------------------------------------ - + + // ---- Accessing Ranges + // ------------------------------------------------------------------------------ + protected void checkRange(DocumentEvent event) { - TextRange range= getTextRange(); - int eventOffset= event.getOffset(); - int eventLength= event.getLength(); + TextRange range = getTextRange(); + int eventOffset = event.getOffset(); + int eventLength = event.getLength(); int eventEnd = eventOffset + eventLength - 1; // "Edit changes text that lies outside its defined range" - // Assert.isTrue(range.fOffset <= eventOffset && eventEnd <= range.getInclusiveEnd()); + // Assert.isTrue(range.fOffset <= eventOffset && eventEnd <= + // range.getInclusiveEnd()); } - + protected TextRange getTextRange() { return fEdit.getTextRange(); } - + protected TextRange getChildRange() { return getTextRange(); } - + protected TextRange getParentRange() { return getTextRange(); } - + public boolean validate(int bufferLength) { if (fChildren == null) return true; - // Only Moves and Nops can be parents + // Only Moves and Nops can be parents if (!(fEdit instanceof MoveTextEdit || fEdit instanceof NopTextEdit)) return false; - TextRange lastRange= null; - for (Iterator iter= fChildren.iterator(); iter.hasNext(); ) { - TextEditNode node= (TextEditNode)iter.next(); + TextRange lastRange = null; + for (Iterator iter = fChildren.iterator(); iter.hasNext();) { + TextEditNode node = (TextEditNode) iter.next(); if (!node.validate(bufferLength)) return false; - TextRange range= node.fEdit.getTextRange(); - if (!range.isValid() || range.fOffset + range.fLength > bufferLength) + TextRange range = node.fEdit.getTextRange(); + if (!range.isValid() + || range.fOffset + range.fLength > bufferLength) return false; - if (lastRange != null && !(range.isInsertionPointAt(lastRange.fOffset) || range.liesBehind(lastRange))) + if (lastRange != null + && !(range.isInsertionPointAt(lastRange.fOffset) || range + .liesBehind(lastRange))) return false; - lastRange= range; + lastRange = range; } return true; } - //---- Updating ---------------------------------------------------------------------------------------- - + // ---- Updating + // ---------------------------------------------------------------------------------------- + protected boolean activeNodeChanged(int delta) { - TextRange range= getTextRange(); - range.fLength+= delta; + TextRange range = getTextRange(); + range.fLength += delta; // we didn't adjust any processed nodes. return false; } - + protected void previousNodeChanged(int delta) { - TextRange range= getTextRange(); - range.fOffset+= delta; + TextRange range = getTextRange(); + range.fOffset += delta; } - + protected void childNodeChanged(int delta) { - getTextRange().fLength+= delta; + getTextRange().fLength += delta; } - //---- Do it --------------------------------------------------------------------------------------------- - - protected void performDo(TextBuffer buffer, RangeUpdater updater, UndoMemento undo, IProgressMonitor pm) throws CoreException { - int size= fChildren != null ? fChildren.size() : 0; - for (int i= size - 1; i >= 0; i--) { - TextEditNode child= (TextEditNode)fChildren.get(i); + // ---- Do it + // --------------------------------------------------------------------------------------------- + + protected void performDo(TextBuffer buffer, RangeUpdater updater, + UndoMemento undo, IProgressMonitor pm) throws CoreException { + int size = fChildren != null ? fChildren.size() : 0; + for (int i = size - 1; i >= 0; i--) { + TextEditNode child = (TextEditNode) fChildren.get(i); child.performDo(buffer, updater, undo, pm); } updater.setActiveNode(this); @@ -442,23 +507,25 @@ import org.eclipse.jface.text.IDocumentListener; undo.add(fEdit.perform(buffer)); pm.worked(1); } - - public void performedDo() { - int size= fChildren != null ? fChildren.size() : 0; - for (int i= size - 1; i >= 0; i--) { - TextEditNode child= (TextEditNode)fChildren.get(i); + + public void performedDo() { + int size = fChildren != null ? fChildren.size() : 0; + for (int i = size - 1; i >= 0; i--) { + TextEditNode child = (TextEditNode) fChildren.get(i); child.performedDo(); } fEdit.performed(); } - - //---- Undo it ------------------------------------------------------------------------------------------- - - protected void performUndo(TextBuffer buffer, RangeUpdater updater, UndoMemento undo, IProgressMonitor pm) throws CoreException { - int size= fChildren != null ? fChildren.size() : 0; - for (int i= 0; i < size; i++) { + + // ---- Undo it + // ------------------------------------------------------------------------------------------- + + protected void performUndo(TextBuffer buffer, RangeUpdater updater, + UndoMemento undo, IProgressMonitor pm) throws CoreException { + int size = fChildren != null ? fChildren.size() : 0; + for (int i = 0; i < size; i++) { setUndoIndex(i); - TextEditNode child= (TextEditNode)fChildren.get(i); + TextEditNode child = (TextEditNode) fChildren.get(i); child.performUndo(buffer, updater, undo, pm); } updater.setActiveNode(this); @@ -468,26 +535,25 @@ import org.eclipse.jface.text.IDocumentListener; undo.add(fEdit.perform(buffer)); pm.worked(1); } - + protected void setUndoIndex(int index) { } - - public void performedUndo() { - int size= fChildren != null ? fChildren.size() : 0; - for (int i= 0; i < size; i++) { - TextEditNode child= (TextEditNode)fChildren.get(i); + + public void performedUndo() { + int size = fChildren != null ? fChildren.size() : 0; + for (int i = 0; i < size; i++) { + TextEditNode child = (TextEditNode) fChildren.get(i); child.performedUndo(); } fEdit.performed(); } - -// protected void createUndoList(List list) { -// int size= fChildren != null ? fChildren.size() : 0; -// for (int i= 0; i < size; i++) { -// TextEditNode child= (TextEditNode)fChildren.get(i); -// child.createUndoList(list); -// } -// list.add(this); -// } -} + // protected void createUndoList(List list) { + // int size= fChildren != null ? fChildren.size() : 0; + // for (int i= 0; i < size; i++) { + // TextEditNode child= (TextEditNode)fChildren.get(i); + // child.createUndoList(list); + // } + // list.add(this); + // } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextEditNodeComparator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextEditNodeComparator.java index 849078e..b579263 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextEditNodeComparator.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextEditNodeComparator.java @@ -6,43 +6,41 @@ package net.sourceforge.phpdt.internal.corext.textmanipulation; import java.util.Comparator; - /** * A special comparator to comapre TextRanges. */ -/* package */ class TextEditNodeComparator implements Comparator { +/* package */class TextEditNodeComparator implements Comparator { public int compare(Object o1, Object o2) { - TextEditNode node1= (TextEditNode)o1; - TextEditNode node2= (TextEditNode)o2; - TextRange pos1= node1.getTextRange(); - TextRange pos2= node2.getTextRange(); - - int offset1= pos1.fOffset; - int offset2= pos2.fOffset; + TextEditNode node1 = (TextEditNode) o1; + TextEditNode node2 = (TextEditNode) o2; + TextRange pos1 = node1.getTextRange(); + TextRange pos2 = node2.getTextRange(); + + int offset1 = pos1.fOffset; + int offset2 = pos2.fOffset; if (offset1 < offset2) return -1; if (offset1 > offset2) return 1; // same offset - int length1= pos1.fLength; - int length2= pos2.fLength; - + int length1 = pos1.fLength; + int length2 = pos2.fLength; + // insertion points come before anything else at the same position. if (length1 == 0 && length2 != 0) return -1; if (length1 != 0 && length2 == 0) return 1; - + // Longer edits come before shorter edits - if (length1 < length2) + if (length1 < length2) return 1; if (length1 > length2) return -1; - + if (node1.fEdit.index < node2.fEdit.index) return -1; - return 1; - } + return 1; + } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextManipulationMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextManipulationMessages.java index 3857db1..49242d6 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextManipulationMessages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextManipulationMessages.java @@ -16,9 +16,10 @@ import java.util.ResourceBundle; public class TextManipulationMessages { - private static final String BUNDLE_NAME= "net.sourceforge.phpdt.internal.corext.textmanipulation.Messages"; //$NON-NLS-1$ + private static final String BUNDLE_NAME = "net.sourceforge.phpdt.internal.corext.textmanipulation.Messages"; //$NON-NLS-1$ - private static final ResourceBundle RESOURCE_BUNDLE= ResourceBundle.getBundle(BUNDLE_NAME); + private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle + .getBundle(BUNDLE_NAME); private TextManipulationMessages() { } @@ -30,12 +31,12 @@ public class TextManipulationMessages { return '!' + key + '!'; } } - + public static String getFormattedString(String key, Object arg) { return getFormattedString(key, new Object[] { arg }); } - + public static String getFormattedString(String key, Object[] args) { - return MessageFormat.format(getString(key), args); - } + return MessageFormat.format(getString(key), args); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextRange.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextRange.java index 9694ddb..3a07839 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextRange.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextRange.java @@ -4,106 +4,109 @@ */ package net.sourceforge.phpdt.internal.corext.textmanipulation; -//import net.sourceforge.phpdt.core.ISourceRange; +// import net.sourceforge.phpdt.core.ISourceRange; // -//import net.sourceforge.phpdt.internal.corext.Assert; +// import net.sourceforge.phpdt.internal.corext.Assert; public final class TextRange { - /* package */ int fOffset; - /* package */ int fLength; - - public static final TextRange UNDEFINED= new TextRange((TextRange)null); + /* package */int fOffset; + + /* package */int fLength; + + public static final TextRange UNDEFINED = new TextRange((TextRange) null); /** * Creates a insert position with the given offset. - * - * @param offset the position offset, must be >= 0 + * + * @param offset + * the position offset, must be >= 0 */ public TextRange(int offset) { this(offset, 0); } - + /** * Creates a new range with the given offset and length. - * - * @param offset the position offset, must be >= 0 - * @param length the position length, must be >= 0 + * + * @param offset + * the position offset, must be >= 0 + * @param length + * the position length, must be >= 0 */ public TextRange(int offset, int length) { - fOffset= offset; -// Assert.isTrue(fOffset >= 0); - fLength= length; -// Assert.isTrue(fLength >= 0); + fOffset = offset; + // Assert.isTrue(fOffset >= 0); + fLength = length; + // Assert.isTrue(fLength >= 0); } - + /** * Constructor for the undefined text range. */ private TextRange(TextRange dummy) { - fOffset= -1; - fLength= -1; + fOffset = -1; + fLength = -1; } - + public static TextRange createFromStartAndLength(int start, int length) { return new TextRange(start, length); } - + public static TextRange createFromStartAndInclusiveEnd(int start, int end) { return new TextRange(start, end - start + 1); } - + public static TextRange createFromStartAndExclusiveEnd(int start, int end) { return new TextRange(start, end - start); } - + /** * Creates a new range from the given source range. * * @range the source range denoting offset and length */ -// public TextRange(ISourceRange range) { -// this(range.getOffset(), range.getLength()); -// } - + // public TextRange(ISourceRange range) { + // this(range.getOffset(), range.getLength()); + // } /** * Returns the offset of this range. - * + * * @return the length of this range */ public int getOffset() { return fOffset; } - + /** * Returns the length of this range. - * + * * @return the length of this range */ public int getLength() { return fLength; } - + /** - * Returns the inclusive end position of this range. That means that the end position - * denotes the last character of this range. + * Returns the inclusive end position of this range. That means that the end + * position denotes the last character of this range. * * @return the inclusive end position */ public int getInclusiveEnd() { return fOffset + fLength - 1; } - + /** - * Returns the exclusive end position of this range. That means that the end position - * denotes the first character after this range. + * Returns the exclusive end position of this range. That means that the end + * position denotes the first character after this range. * * @return the exclusive end position */ public int getExclusiveEnd() { return fOffset + fLength; } - + /** * Creates a copy of this TextRange. * @@ -114,65 +117,72 @@ public final class TextRange { return this; return new TextRange(fOffset, fLength); } - + /** - * Returns true if this text range is the UNDEFINED - * text range. Otherwise false is returned. + * Returns true if this text range is the + * UNDEFINED text range. Otherwise false is + * returned. */ public boolean isUndefined() { return UNDEFINED == this; } - + /** - * Checks if this TextRange is valid. For valid text range the following - * expression evaluates to true: + * Checks if this TextRange is valid. For valid text range + * the following expression evaluates to true: + * *

                                                      -	 * 	getOffset() >= 0 && getLength() >= 0
                                                      +	 * getOffset() >= 0 && getLength() >= 0
                                                       	 * 
                                                      * - * @return true if this text range is a valid range. Otherwise + * @return true if this text range is a valid range. + * Otherwise * false */ public boolean isValid() { return fOffset >= 0 && fLength >= 0; } - - /* package */ boolean isInsertionPoint() { + + /* package */boolean isInsertionPoint() { return fLength == 0; } - - /* package */ boolean equals(TextRange range) { + + /* package */boolean equals(TextRange range) { return fOffset == range.fOffset && fLength == range.fLength; } - /* package */ boolean isEqualInsertionPoint(TextRange range) { + /* package */boolean isEqualInsertionPoint(TextRange range) { return fLength == 0 && range.fLength == 0 && fOffset == range.fOffset; } - /* package */ boolean liesBehind(TextRange range) { + /* package */boolean liesBehind(TextRange range) { return fOffset >= range.fOffset + range.fLength; } - /* package */ boolean isInsertionPointAt(int o) { + /* package */boolean isInsertionPointAt(int o) { return fOffset == o && fLength == 0; } - - /* package */ boolean covers(TextRange other) { - if (fLength == 0) { // an insertion point can't cover anything + + /* package */boolean covers(TextRange other) { + if (fLength == 0) { // an insertion point can't cover anything return false; } else if (other.fLength == 0) { - int otherOffset= other.fOffset; + int otherOffset = other.fOffset; return fOffset < otherOffset && otherOffset < fOffset + fLength; } else { - int otherOffset= other.fOffset; - return fOffset <= otherOffset && otherOffset + other.fLength <= fOffset + fLength; + int otherOffset = other.fOffset; + return fOffset <= otherOffset + && otherOffset + other.fLength <= fOffset + fLength; } } - /* non Java-doc + + /* + * non Java-doc + * * @see Object#toString() */ public String toString() { - StringBuffer buffer= new StringBuffer(); + StringBuffer buffer = new StringBuffer(); buffer.append(TextManipulationMessages.getString("TextRange.offset")); //$NON-NLS-1$ buffer.append(fOffset); buffer.append(TextManipulationMessages.getString("TextRange.length")); //$NON-NLS-1$ @@ -181,9 +191,9 @@ public final class TextRange { } public boolean equals(Object obj) { - if (! (obj instanceof TextRange)) + if (!(obj instanceof TextRange)) return false; - TextRange other= (TextRange)obj; + TextRange other = (TextRange) obj; return fOffset == other.getOffset() && fLength == other.getLength(); } @@ -192,4 +202,3 @@ public final class TextRange { } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextRegion.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextRegion.java index 69919c6..ef008ad 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextRegion.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/TextRegion.java @@ -4,34 +4,37 @@ */ package net.sourceforge.phpdt.internal.corext.textmanipulation; - /** - * A text region describes a certain range in an ITextBuffer. A region is defined by - * its offset into the text buffer and its length. + * A text region describes a certain range in an ITextBuffer. A + * region is defined by its offset into the text buffer and its length. *

                                                      - * A region is considered a value object. Its offset or length do not change over time.

                                                      + * A region is considered a value object. Its offset or length do not change + * over time. + *

                                                      *

                                                      - * NOTE: This class/interface is part of an interim API that is still under development - * and expected to change significantly before reaching stability. It is being made available at - * this early stage to solicit feedback from pioneering adopters on the understanding that any - * code that uses this API will almost certainly be broken (repeatedly) as the API evolves.

                                                      + * NOTE: This class/interface is part of an interim API that is still + * under development and expected to change significantly before reaching + * stability. It is being made available at this early stage to solicit feedback + * from pioneering adopters on the understanding that any code that uses this + * API will almost certainly be broken (repeatedly) as the API evolves. + *

                                                      */ // This class avoids contamination of clients with wrong imports. - public abstract class TextRegion { - + /** * Returns the offset of the region. - * + * * @return the offset of the region */ public abstract int getOffset(); + /** * Returns the length of the region. - * + * * @return the length of the region */ public abstract int getLength(); - + } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/UndoMemento.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/UndoMemento.java index 8817d5d..4f1b893 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/UndoMemento.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/textmanipulation/UndoMemento.java @@ -7,23 +7,22 @@ package net.sourceforge.phpdt.internal.corext.textmanipulation; import java.util.ArrayList; import java.util.List; - /** - * This class encapsulates the reverse change of a number of TextEdits - * executed on a TextBufferEditor + * This class encapsulates the reverse change of a number of + * TextEdits executed on a TextBufferEditor */ public final class UndoMemento { - /* package */ int fMode; - /* package */ List fEdits; + /* package */int fMode; + + /* package */List fEdits; - /* package */ UndoMemento(int mode) { - fMode= mode; - fEdits= new ArrayList(10); + /* package */UndoMemento(int mode) { + fMode = mode; + fEdits = new ArrayList(10); } - - /* package */ void add(TextEdit edit) { + + /* package */void add(TextEdit edit) { fEdits.add(edit); - } + } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/CodeFormatterUtil.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/CodeFormatterUtil.java index f9c116b..bd39503 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/CodeFormatterUtil.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/CodeFormatterUtil.java @@ -30,255 +30,311 @@ import org.eclipse.text.edits.ReplaceEdit; import org.eclipse.text.edits.TextEdit; public class CodeFormatterUtil { - + /** - * Creates a string that represents the given number of indents (can be spaces or tabs..) + * Creates a string that represents the given number of indents (can be + * spaces or tabs..) */ public static String createIndentString(int indent) { - // axelcl change start -// String str= format(CodeFormatter.K_EXPRESSION, "x", indent, null, "", (Map) null); //$NON-NLS-1$ //$NON-NLS-2$ - String str = ToolFactory.createCodeFormatter().format("x", indent, null, ""); + // axelcl change start + // String str= format(CodeFormatter.K_EXPRESSION, "x", indent, null, "", + // (Map) null); //$NON-NLS-1$ //$NON-NLS-2$ + String str = ToolFactory.createCodeFormatter().format("x", indent, + null, ""); return str.substring(0, str.indexOf('x')); // axelcl change end - } - + } + public static int getTabWidth() { - Preferences preferences= PHPeclipsePlugin.getDefault().getPluginPreferences(); - return preferences.getInt(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE); + Preferences preferences = PHPeclipsePlugin.getDefault() + .getPluginPreferences(); + return preferences + .getInt(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE); } // transition code /** * Old API. Consider to use format2 (TextEdit) - */ -// public static String format(int kind, String string, int indentationLevel, int[] positions, String lineSeparator, Map options) { -// return format(kind, string, 0, string.length(), indentationLevel, positions, lineSeparator, options); -// } -// -// public static String format(int kind, String string, int indentationLevel, int[] positions, String lineSeparator, IJavaProject project) { -// Map options= project != null ? project.getOptions(true) : null; -// return format(kind, string, 0, string.length(), indentationLevel, positions, lineSeparator, options); -// } - + */ + // public static String format(int kind, String string, int + // indentationLevel, int[] positions, String lineSeparator, Map options) { + // return format(kind, string, 0, string.length(), indentationLevel, + // positions, lineSeparator, options); + // } + // + // public static String format(int kind, String string, int + // indentationLevel, int[] positions, String lineSeparator, IJavaProject + // project) { + // Map options= project != null ? project.getOptions(true) : null; + // return format(kind, string, 0, string.length(), indentationLevel, + // positions, lineSeparator, options); + // } /** * Old API. Consider to use format2 (TextEdit) - */ -// public static String format(int kind, String string, int offset, int length, int indentationLevel, int[] positions, String lineSeparator, Map options) { -// TextEdit edit= format2(kind, string, offset, length, indentationLevel, lineSeparator, options); -// if (edit == null) { -// //JavaPlugin.logErrorMessage("formatter failed to format (no edit returned). Will use unformatted text instead. kind: " + kind + ", string: " + string); //$NON-NLS-1$ //$NON-NLS-2$ -// return string.substring(offset, offset + length); -// } -// String formatted= getOldAPICompatibleResult(string, edit, indentationLevel, positions, lineSeparator, options); -// return formatted.substring(offset, formatted.length() - (string.length() - (offset + length))); -// } - + */ + // public static String format(int kind, String string, int offset, int + // length, int indentationLevel, int[] positions, String lineSeparator, Map + // options) { + // TextEdit edit= format2(kind, string, offset, length, indentationLevel, + // lineSeparator, options); + // if (edit == null) { + // //JavaPlugin.logErrorMessage("formatter failed to format (no edit + // returned). Will use unformatted text instead. kind: " + kind + ", string: + // " + string); //$NON-NLS-1$ //$NON-NLS-2$ + // return string.substring(offset, offset + length); + // } + // String formatted= getOldAPICompatibleResult(string, edit, + // indentationLevel, positions, lineSeparator, options); + // return formatted.substring(offset, formatted.length() - (string.length() + // - (offset + length))); + // } /** * Old API. Consider to use format2 (TextEdit) - */ -// public static String format(ASTNode node, String string, int indentationLevel, int[] positions, String lineSeparator, Map options) { -// -// TextEdit edit= format2(node, string, indentationLevel, lineSeparator, options); -// if (edit == null) { -// //JavaPlugin.logErrorMessage("formatter failed to format (no edit returned). Will use unformatted text instead. node: " + node.getNodeType() + ", string: " + string); //$NON-NLS-1$ //$NON-NLS-2$ -// return string; -// } -// return getOldAPICompatibleResult(string, edit, indentationLevel, positions, lineSeparator, options); -// } - - private static String getOldAPICompatibleResult(String string, TextEdit edit, int indentationLevel, int[] positions, String lineSeparator, Map options) { - Position[] p= null; - + */ + // public static String format(ASTNode node, String string, int + // indentationLevel, int[] positions, String lineSeparator, Map options) { + // + // TextEdit edit= format2(node, string, indentationLevel, lineSeparator, + // options); + // if (edit == null) { + // //JavaPlugin.logErrorMessage("formatter failed to format (no edit + // returned). Will use unformatted text instead. node: " + + // node.getNodeType() + ", string: " + string); //$NON-NLS-1$ //$NON-NLS-2$ + // return string; + // } + // return getOldAPICompatibleResult(string, edit, indentationLevel, + // positions, lineSeparator, options); + // } + private static String getOldAPICompatibleResult(String string, + TextEdit edit, int indentationLevel, int[] positions, + String lineSeparator, Map options) { + Position[] p = null; + if (positions != null) { - p= new Position[positions.length]; - for (int i= 0; i < positions.length; i++) { - p[i]= new Position(positions[i], 0); + p = new Position[positions.length]; + for (int i = 0; i < positions.length; i++) { + p[i] = new Position(positions[i], 0); } } - String res= evaluateFormatterEdit(string, edit, p); - + String res = evaluateFormatterEdit(string, edit, p); + if (positions != null) { - for (int i= 0; i < positions.length; i++) { - Position curr= p[i]; - positions[i]= curr.getOffset(); + for (int i = 0; i < positions.length; i++) { + Position curr = p[i]; + positions[i] = curr.getOffset(); } - } + } return res; } - + /** * Evaluates the edit on the given string. - * @throws IllegalArgumentException If the positions are not inside the string, a - * IllegalArgumentException is thrown. + * + * @throws IllegalArgumentException + * If the positions are not inside the string, a + * IllegalArgumentException is thrown. */ - public static String evaluateFormatterEdit(String string, TextEdit edit, Position[] positions) { + public static String evaluateFormatterEdit(String string, TextEdit edit, + Position[] positions) { try { - Document doc= createDocument(string, positions); + Document doc = createDocument(string, positions); edit.apply(doc, 0); if (positions != null) { - for (int i= 0; i < positions.length; i++) { - Assert.isTrue(!positions[i].isDeleted, "Position got deleted"); //$NON-NLS-1$ + for (int i = 0; i < positions.length; i++) { + Assert.isTrue(!positions[i].isDeleted, + "Position got deleted"); //$NON-NLS-1$ } } return doc.get(); } catch (BadLocationException e) { PHPeclipsePlugin.log(e); // bug in the formatter - Assert.isTrue(false, "Fromatter created edits with wrong positions: " + e.getMessage()); //$NON-NLS-1$ + Assert + .isTrue( + false, + "Fromatter created edits with wrong positions: " + e.getMessage()); //$NON-NLS-1$ } return null; } - + /** - * Creates edits that describe how to format the given string. Returns null if the code could not be formatted for the given kind. - * @throws IllegalArgumentException If the offset and length are not inside the string, a - * IllegalArgumentException is thrown. + * Creates edits that describe how to format the given string. Returns + * null if the code could not be formatted for the given + * kind. + * + * @throws IllegalArgumentException + * If the offset and length are not inside the string, a + * IllegalArgumentException is thrown. */ -// public static TextEdit format2(int kind, String string, int offset, int length, int indentationLevel, String lineSeparator, Map options) { -// if (offset < 0 || length < 0 || offset + length > string.length()) { -// throw new IllegalArgumentException("offset or length outside of string. offset: " + offset + ", length: " + length + ", string size: " + string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ -// } -// -// return createCodeFormatter(options).format(kind, string, offset, length, indentationLevel, lineSeparator); -// -// } - -// public static TextEdit format2(int kind, String string, int indentationLevel, String lineSeparator, Map options) { -// return format2(kind, string, 0, string.length(), indentationLevel, lineSeparator, options); -// } - + // public static TextEdit format2(int kind, String string, int offset, int + // length, int indentationLevel, String lineSeparator, Map options) { + // if (offset < 0 || length < 0 || offset + length > string.length()) { + // throw new IllegalArgumentException("offset or length outside of string. + // offset: " + offset + ", length: " + length + ", string size: " + + // string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ + // } + // + // return createCodeFormatter(options).format(kind, string, offset, length, + // indentationLevel, lineSeparator); + // + // } + // public static TextEdit format2(int kind, String string, int + // indentationLevel, String lineSeparator, Map options) { + // return format2(kind, string, 0, string.length(), indentationLevel, + // lineSeparator, options); + // } /** - * Creates edits that describe how to format the given string. Returns null if the code could not be formatted for the given kind. - * @throws IllegalArgumentException If the offset and length are not inside the string, a - * IllegalArgumentException is thrown. + * Creates edits that describe how to format the given string. Returns + * null if the code could not be formatted for the given + * kind. + * + * @throws IllegalArgumentException + * If the offset and length are not inside the string, a + * IllegalArgumentException is thrown. */ -// public static TextEdit format2(ASTNode node, String str, int indentationLevel, String lineSeparator, Map options) { -// int code; -// String prefix= ""; //$NON-NLS-1$ -// String suffix= ""; //$NON-NLS-1$ -// if (node instanceof Statement) { -// code= CodeFormatter.K_STATEMENTS; -// if (node.getNodeType() == ASTNode.SWITCH_CASE) { -// prefix= "switch(1) {"; //$NON-NLS-1$ -// suffix= "}"; //$NON-NLS-1$ -// code= CodeFormatter.K_STATEMENTS; -// } -// } else if (node instanceof Expression && node.getNodeType() != ASTNode.VARIABLE_DECLARATION_EXPRESSION) { -// code= CodeFormatter.K_EXPRESSION; -// } else { -// switch (node.getNodeType()) { -// case ASTNode.METHOD_DECLARATION: -// case ASTNode.TYPE_DECLARATION: -// case ASTNode.FIELD_DECLARATION: -// case ASTNode.INITIALIZER: -// code= CodeFormatter.K_CLASS_BODY_DECLARATIONS; -// break; -// case ASTNode.ARRAY_TYPE: -// case ASTNode.PRIMITIVE_TYPE: -// case ASTNode.SIMPLE_TYPE: -// suffix= " x;"; //$NON-NLS-1$ -// code= CodeFormatter.K_EXPRESSION; -// break; -// case ASTNode.COMPILATION_UNIT: -// code= CodeFormatter.K_COMPILATION_UNIT; -// break; -// case ASTNode.VARIABLE_DECLARATION_EXPRESSION: -// case ASTNode.SINGLE_VARIABLE_DECLARATION: -// suffix= ";"; //$NON-NLS-1$ -// code= CodeFormatter.K_STATEMENTS; -// break; -// case ASTNode.VARIABLE_DECLARATION_FRAGMENT: -// prefix= "A "; //$NON-NLS-1$ -// suffix= ";"; //$NON-NLS-1$ -// code= CodeFormatter.K_STATEMENTS; -// break; -// case ASTNode.PACKAGE_DECLARATION: -// case ASTNode.IMPORT_DECLARATION: -// suffix= "\nclass A {}"; //$NON-NLS-1$ -// code= CodeFormatter.K_COMPILATION_UNIT; -// break; -// case ASTNode.JAVADOC: -// suffix= "void foo();"; //$NON-NLS-1$ -// code= CodeFormatter.K_CLASS_BODY_DECLARATIONS; -// break; -// case ASTNode.CATCH_CLAUSE: -// prefix= "try {}"; //$NON-NLS-1$ -// code= CodeFormatter.K_STATEMENTS; -// break; -// case ASTNode.ANONYMOUS_CLASS_DECLARATION: -// prefix= "new A()"; //$NON-NLS-1$ -// suffix= ";"; //$NON-NLS-1$ -// code= CodeFormatter.K_STATEMENTS; -// break; -// case ASTNode.MEMBER_REF: -// case ASTNode.METHOD_REF: -// case ASTNode.METHOD_REF_PARAMETER: -// case ASTNode.TAG_ELEMENT: -// case ASTNode.TEXT_ELEMENT: -// // not yet supported -// return null; -// default: -// Assert.isTrue(false, "Node type not covered: " + node.getClass().getName()); //$NON-NLS-1$ -// return null; -// } -// } -// -// String concatStr= prefix + str + suffix; -// TextEdit edit= format2(code, concatStr, prefix.length(), str.length(), indentationLevel, lineSeparator, options); -// if (prefix.length() > 0) { -// edit= shifEdit(edit, prefix.length()); -// } -// return edit; -// } - + // public static TextEdit format2(ASTNode node, String str, int + // indentationLevel, String lineSeparator, Map options) { + // int code; + // String prefix= ""; //$NON-NLS-1$ + // String suffix= ""; //$NON-NLS-1$ + // if (node instanceof Statement) { + // code= CodeFormatter.K_STATEMENTS; + // if (node.getNodeType() == ASTNode.SWITCH_CASE) { + // prefix= "switch(1) {"; //$NON-NLS-1$ + // suffix= "}"; //$NON-NLS-1$ + // code= CodeFormatter.K_STATEMENTS; + // } + // } else if (node instanceof Expression && node.getNodeType() != + // ASTNode.VARIABLE_DECLARATION_EXPRESSION) { + // code= CodeFormatter.K_EXPRESSION; + // } else { + // switch (node.getNodeType()) { + // case ASTNode.METHOD_DECLARATION: + // case ASTNode.TYPE_DECLARATION: + // case ASTNode.FIELD_DECLARATION: + // case ASTNode.INITIALIZER: + // code= CodeFormatter.K_CLASS_BODY_DECLARATIONS; + // break; + // case ASTNode.ARRAY_TYPE: + // case ASTNode.PRIMITIVE_TYPE: + // case ASTNode.SIMPLE_TYPE: + // suffix= " x;"; //$NON-NLS-1$ + // code= CodeFormatter.K_EXPRESSION; + // break; + // case ASTNode.COMPILATION_UNIT: + // code= CodeFormatter.K_COMPILATION_UNIT; + // break; + // case ASTNode.VARIABLE_DECLARATION_EXPRESSION: + // case ASTNode.SINGLE_VARIABLE_DECLARATION: + // suffix= ";"; //$NON-NLS-1$ + // code= CodeFormatter.K_STATEMENTS; + // break; + // case ASTNode.VARIABLE_DECLARATION_FRAGMENT: + // prefix= "A "; //$NON-NLS-1$ + // suffix= ";"; //$NON-NLS-1$ + // code= CodeFormatter.K_STATEMENTS; + // break; + // case ASTNode.PACKAGE_DECLARATION: + // case ASTNode.IMPORT_DECLARATION: + // suffix= "\nclass A {}"; //$NON-NLS-1$ + // code= CodeFormatter.K_COMPILATION_UNIT; + // break; + // case ASTNode.JAVADOC: + // suffix= "void foo();"; //$NON-NLS-1$ + // code= CodeFormatter.K_CLASS_BODY_DECLARATIONS; + // break; + // case ASTNode.CATCH_CLAUSE: + // prefix= "try {}"; //$NON-NLS-1$ + // code= CodeFormatter.K_STATEMENTS; + // break; + // case ASTNode.ANONYMOUS_CLASS_DECLARATION: + // prefix= "new A()"; //$NON-NLS-1$ + // suffix= ";"; //$NON-NLS-1$ + // code= CodeFormatter.K_STATEMENTS; + // break; + // case ASTNode.MEMBER_REF: + // case ASTNode.METHOD_REF: + // case ASTNode.METHOD_REF_PARAMETER: + // case ASTNode.TAG_ELEMENT: + // case ASTNode.TEXT_ELEMENT: + // // not yet supported + // return null; + // default: + // Assert.isTrue(false, "Node type not covered: " + + // node.getClass().getName()); //$NON-NLS-1$ + // return null; + // } + // } + // + // String concatStr= prefix + str + suffix; + // TextEdit edit= format2(code, concatStr, prefix.length(), str.length(), + // indentationLevel, lineSeparator, options); + // if (prefix.length() > 0) { + // edit= shifEdit(edit, prefix.length()); + // } + // return edit; + // } private static TextEdit shifEdit(TextEdit oldEdit, int diff) { TextEdit newEdit; if (oldEdit instanceof ReplaceEdit) { - ReplaceEdit edit= (ReplaceEdit) oldEdit; - newEdit= new ReplaceEdit(edit.getOffset() - diff, edit.getLength(), edit.getText()); + ReplaceEdit edit = (ReplaceEdit) oldEdit; + newEdit = new ReplaceEdit(edit.getOffset() - diff, + edit.getLength(), edit.getText()); } else if (oldEdit instanceof InsertEdit) { - InsertEdit edit= (InsertEdit) oldEdit; - newEdit= new InsertEdit(edit.getOffset() - diff, edit.getText()); + InsertEdit edit = (InsertEdit) oldEdit; + newEdit = new InsertEdit(edit.getOffset() - diff, edit.getText()); } else if (oldEdit instanceof DeleteEdit) { - DeleteEdit edit= (DeleteEdit) oldEdit; - newEdit= new DeleteEdit(edit.getOffset() - diff, edit.getLength()); + DeleteEdit edit = (DeleteEdit) oldEdit; + newEdit = new DeleteEdit(edit.getOffset() - diff, edit.getLength()); } else if (oldEdit instanceof MultiTextEdit) { - newEdit= new MultiTextEdit(); + newEdit = new MultiTextEdit(); } else { return null; // not supported } - TextEdit[] children= oldEdit.getChildren(); - for (int i= 0; i < children.length; i++) { - TextEdit shifted= shifEdit(children[i], diff); + TextEdit[] children = oldEdit.getChildren(); + for (int i = 0; i < children.length; i++) { + TextEdit shifted = shifEdit(children[i], diff); if (shifted != null) { newEdit.addChild(shifted); } } return newEdit; } - - private static Document createDocument(String string, Position[] positions) throws IllegalArgumentException { - Document doc= new Document(string); + + private static Document createDocument(String string, Position[] positions) + throws IllegalArgumentException { + Document doc = new Document(string); try { if (positions != null) { - final String POS_CATEGORY= "myCategory"; //$NON-NLS-1$ - + final String POS_CATEGORY = "myCategory"; //$NON-NLS-1$ + doc.addPositionCategory(POS_CATEGORY); - doc.addPositionUpdater(new DefaultPositionUpdater(POS_CATEGORY) { - protected boolean notDeleted() { - if (fOffset < fPosition.offset && (fPosition.offset + fPosition.length < fOffset + fLength)) { - fPosition.offset= fOffset + fLength; // deleted positions: set to end of remove - return false; - } - return true; - } - }); - for (int i= 0; i < positions.length; i++) { + doc + .addPositionUpdater(new DefaultPositionUpdater( + POS_CATEGORY) { + protected boolean notDeleted() { + if (fOffset < fPosition.offset + && (fPosition.offset + fPosition.length < fOffset + + fLength)) { + fPosition.offset = fOffset + fLength; // deleted + // positions: + // set + // to + // end + // of + // remove + return false; + } + return true; + } + }); + for (int i = 0; i < positions.length; i++) { try { doc.addPosition(POS_CATEGORY, positions[i]); } catch (BadLocationException e) { - throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ + throw new IllegalArgumentException( + "Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ } } } @@ -287,5 +343,5 @@ public class CodeFormatterUtil { } return doc; } - + } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/IOCloser.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/IOCloser.java index 1e16693..c985574 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/IOCloser.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/IOCloser.java @@ -16,7 +16,7 @@ import java.io.Reader; import net.sourceforge.phpeclipse.PHPeclipsePlugin; -//import net.sourceforge.phpdt.internal.ui.JavaPlugin; +// import net.sourceforge.phpdt.internal.ui.JavaPlugin; public class IOCloser { public static void perform(Reader reader, InputStream stream) { @@ -26,8 +26,9 @@ public class IOCloser { PHPeclipsePlugin.log(e); } } - - public static void rethrows(Reader reader, InputStream stream) throws IOException { + + public static void rethrows(Reader reader, InputStream stream) + throws IOException { if (reader != null) { reader.close(); return; @@ -36,6 +37,5 @@ public class IOCloser { stream.close(); return; } - } + } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/JavaModelUtil.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/JavaModelUtil.java index d3b4949..bfa0f51 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/JavaModelUtil.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/JavaModelUtil.java @@ -30,8 +30,6 @@ import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; - - /** * Utility methods for the Java Model. */ @@ -39,25 +37,29 @@ public class JavaModelUtil { /** * Finds a type by its qualified type name (dot separated). - * @param jproject The java project to search in - * @param str The fully qualified name (type name with enclosing type names and package (all separated by dots)) + * + * @param jproject + * The java project to search in + * @param str + * The fully qualified name (type name with enclosing type names + * and package (all separated by dots)) * @return The type found, or null if not existing */ -// public static IType findType(IJavaProject jproject, String fullyQualifiedName) throws JavaModelException { -// //workaround for bug 22883 -// IType type= jproject.findType(fullyQualifiedName); -// if (type != null) -// return type; -// IPackageFragmentRoot[] roots= jproject.getPackageFragmentRoots(); -// for (int i= 0; i < roots.length; i++) { -// IPackageFragmentRoot root= roots[i]; -// type= findType(root, fullyQualifiedName); -// if (type != null && type.exists()) -// return type; -// } -// return null; -// } - + // public static IType findType(IJavaProject jproject, String + // fullyQualifiedName) throws JavaModelException { + // //workaround for bug 22883 + // IType type= jproject.findType(fullyQualifiedName); + // if (type != null) + // return type; + // IPackageFragmentRoot[] roots= jproject.getPackageFragmentRoots(); + // for (int i= 0; i < roots.length; i++) { + // IPackageFragmentRoot root= roots[i]; + // type= findType(root, fullyQualifiedName); + // if (type != null && type.exists()) + // return type; + // } + // return null; + // } /** * Returns true if the given package fragment root is * referenced. This means it is own by a different project but is referenced @@ -65,99 +67,115 @@ public class JavaModelUtil { * doesn't have an underlying resource. */ public static boolean isReferenced(IPackageFragmentRoot root) { -// IResource resource= root.getResource(); -// if (resource != null) { -// IProject jarProject= resource.getProject(); -// IProject container= root.getJavaProject().getProject(); -// return !container.equals(jarProject); -// } + // IResource resource= root.getResource(); + // if (resource != null) { + // IProject jarProject= resource.getProject(); + // IProject container= root.getJavaProject().getProject(); + // return !container.equals(jarProject); + // } return false; } -// private static IType findType(IPackageFragmentRoot root, String fullyQualifiedName) throws JavaModelException{ -// IJavaElement[] children= root.getChildren(); -// for (int i= 0; i < children.length; i++) { -// IJavaElement element= children[i]; -// if (element.getElementType() == IJavaElement.PACKAGE_FRAGMENT){ -// IPackageFragment pack= (IPackageFragment)element; -// if (! fullyQualifiedName.startsWith(pack.getElementName())) -// continue; -// IType type= findType(pack, fullyQualifiedName); -// if (type != null && type.exists()) -// return type; -// } -// } -// return null; -// } - -// private static IType findType(IPackageFragment pack, String fullyQualifiedName) throws JavaModelException{ -// ICompilationUnit[] cus= pack.getCompilationUnits(); -// for (int i= 0; i < cus.length; i++) { -// ICompilationUnit unit= cus[i]; -// ICompilationUnit wc= WorkingCopyUtil.getWorkingCopyIfExists(unit); -// IType type= findType(wc, fullyQualifiedName); -// if (type != null && type.exists()) -// return type; -// } -// return null; -// } - -// private static IType findType(ICompilationUnit cu, String fullyQualifiedName) throws JavaModelException{ -// IType[] types= cu.getAllTypes(); -// for (int i= 0; i < types.length; i++) { -// IType type= types[i]; -// if (getFullyQualifiedName(type).equals(fullyQualifiedName)) -// return type; -// } -// return null; -// } + // private static IType findType(IPackageFragmentRoot root, String + // fullyQualifiedName) throws JavaModelException{ + // IJavaElement[] children= root.getChildren(); + // for (int i= 0; i < children.length; i++) { + // IJavaElement element= children[i]; + // if (element.getElementType() == IJavaElement.PACKAGE_FRAGMENT){ + // IPackageFragment pack= (IPackageFragment)element; + // if (! fullyQualifiedName.startsWith(pack.getElementName())) + // continue; + // IType type= findType(pack, fullyQualifiedName); + // if (type != null && type.exists()) + // return type; + // } + // } + // return null; + // } + + // private static IType findType(IPackageFragment pack, String + // fullyQualifiedName) throws JavaModelException{ + // ICompilationUnit[] cus= pack.getCompilationUnits(); + // for (int i= 0; i < cus.length; i++) { + // ICompilationUnit unit= cus[i]; + // ICompilationUnit wc= WorkingCopyUtil.getWorkingCopyIfExists(unit); + // IType type= findType(wc, fullyQualifiedName); + // if (type != null && type.exists()) + // return type; + // } + // return null; + // } + + // private static IType findType(ICompilationUnit cu, String + // fullyQualifiedName) throws JavaModelException{ + // IType[] types= cu.getAllTypes(); + // for (int i= 0; i < types.length; i++) { + // IType type= types[i]; + // if (getFullyQualifiedName(type).equals(fullyQualifiedName)) + // return type; + // } + // return null; + // } /** * Finds a type by package and type name. - * @param jproject the java project to search in - * @param pack The package name - * @param typeQualifiedName the type qualified name (type name with enclosing type names (separated by dots)) + * + * @param jproject + * the java project to search in + * @param pack + * The package name + * @param typeQualifiedName + * the type qualified name (type name with enclosing type names + * (separated by dots)) * @return the type found, or null if not existing * @deprecated Use IJavaProject.findType(String, String) instead */ -// public static IType findType(IJavaProject jproject, String pack, String typeQualifiedName) throws JavaModelException { -// return jproject.findType(pack, typeQualifiedName); -// } - + // public static IType findType(IJavaProject jproject, String pack, String + // typeQualifiedName) throws JavaModelException { + // return jproject.findType(pack, typeQualifiedName); + // } /** - * Finds a type container by container name. - * The returned element will be of type IType or a IPackageFragment. + * Finds a type container by container name. The returned element will be of + * type IType or a IPackageFragment. * null is returned if the type container could not be found. - * @param jproject The Java project defining the context to search - * @param typeContainerName A dot separarted name of the type container + * + * @param jproject + * The Java project defining the context to search + * @param typeContainerName + * A dot separarted name of the type container * @see #getTypeContainerName(IType) */ -// public static IJavaElement findTypeContainer(IJavaProject jproject, String typeContainerName) throws JavaModelException { -// // try to find it as type -// IJavaElement result= jproject.findType(typeContainerName); -// if (result == null) { -// // find it as package -// IPath path= new Path(typeContainerName.replace('.', '/')); -// result= jproject.findElement(path); -// if (!(result instanceof IPackageFragment)) { -// result= null; -// } -// -// } -// return result; -// } - - /** - * Finds a type in a compilation unit. Typical usage is to find the corresponding - * type in a working copy. - * @param cu the compilation unit to search in - * @param typeQualifiedName the type qualified name (type name with enclosing type names (separated by dots)) + // public static IJavaElement findTypeContainer(IJavaProject jproject, + // String typeContainerName) throws JavaModelException { + // // try to find it as type + // IJavaElement result= jproject.findType(typeContainerName); + // if (result == null) { + // // find it as package + // IPath path= new Path(typeContainerName.replace('.', '/')); + // result= jproject.findElement(path); + // if (!(result instanceof IPackageFragment)) { + // result= null; + // } + // + // } + // return result; + // } + /** + * Finds a type in a compilation unit. Typical usage is to find the + * corresponding type in a working copy. + * + * @param cu + * the compilation unit to search in + * @param typeQualifiedName + * the type qualified name (type name with enclosing type names + * (separated by dots)) * @return the type found, or null if not existing */ - public static IType findTypeInCompilationUnit(ICompilationUnit cu, String typeQualifiedName) throws JavaModelException { - IType[] types= cu.getAllTypes(); - for (int i= 0; i < types.length; i++) { - String currName= getTypeQualifiedName(types[i]); + public static IType findTypeInCompilationUnit(ICompilationUnit cu, + String typeQualifiedName) throws JavaModelException { + IType[] types = cu.getAllTypes(); + for (int i = 0; i < types.length; i++) { + String currName = getTypeQualifiedName(types[i]); if (typeQualifiedName.equals(currName)) { return types[i]; } @@ -166,32 +184,38 @@ public class JavaModelUtil { } /** - * Finds a a member in a compilation unit. Typical usage is to find the corresponding - * member in a working copy. - * @param cu the compilation unit (eg. working copy) to search in - * @param member the member (eg. from the original) + * Finds a a member in a compilation unit. Typical usage is to find the + * corresponding member in a working copy. + * + * @param cu + * the compilation unit (eg. working copy) to search in + * @param member + * the member (eg. from the original) * @return the member found, or null if not existing */ - public static IMember findMemberInCompilationUnit(ICompilationUnit cu, IMember member) throws JavaModelException { - IJavaElement[] elements= cu.findElements(member); + public static IMember findMemberInCompilationUnit(ICompilationUnit cu, + IMember member) throws JavaModelException { + IJavaElement[] elements = cu.findElements(member); if (elements != null && elements.length > 0) { return (IMember) elements[0]; } return null; } - /** * Returns the element of the given compilation unit which is "equal" to the * given element. Note that the given element usually has a parent different * from the given compilation unit. - * - * @param cu the cu to search in - * @param element the element to look for + * + * @param cu + * the cu to search in + * @param element + * the element to look for * @return an element of the given cu "equal" to the given element */ - public static IJavaElement findInCompilationUnit(ICompilationUnit cu, IJavaElement element) throws JavaModelException { - IJavaElement[] elements= cu.findElements(element); + public static IJavaElement findInCompilationUnit(ICompilationUnit cu, + IJavaElement element) throws JavaModelException { + IJavaElement[] elements = cu.findElements(element); if (elements != null && elements.length > 0) { return elements[0]; } @@ -199,17 +223,17 @@ public class JavaModelUtil { } /** - * Returns the qualified type name of the given type using '.' as separators. - * This is a replace for IType.getTypeQualifiedName() - * which uses '$' as separators. As '$' is also a valid character in an id - * this is ambiguous. JavaCore PR: 1GCFUNT + * Returns the qualified type name of the given type using '.' as + * separators. This is a replace for IType.getTypeQualifiedName() which uses + * '$' as separators. As '$' is also a valid character in an id this is + * ambiguous. JavaCore PR: 1GCFUNT */ public static String getTypeQualifiedName(IType type) { return type.getTypeQualifiedName('.'); } private static void getTypeQualifiedName(IType type, StringBuffer buf) { - IType outerType= type.getDeclaringType(); + IType outerType = type.getDeclaringType(); if (outerType != null) { getTypeQualifiedName(outerType, buf); buf.append('.'); @@ -218,20 +242,21 @@ public class JavaModelUtil { } /** - * Returns the fully qualified name of the given type using '.' as separators. - * This is a replace for IType.getFullyQualifiedTypeName - * which uses '$' as separators. As '$' is also a valid character in an id - * this is ambiguous. JavaCore PR: 1GCFUNT + * Returns the fully qualified name of the given type using '.' as + * separators. This is a replace for IType.getFullyQualifiedTypeName which + * uses '$' as separators. As '$' is also a valid character in an id this is + * ambiguous. JavaCore PR: 1GCFUNT */ public static String getFullyQualifiedName(IType type) { return type.getFullyQualifiedName('.'); } /** - * Returns the fully qualified name of a type's container. (package name or enclosing type name) + * Returns the fully qualified name of a type's container. (package name or + * enclosing type name) */ public static String getTypeContainerName(IType type) { - IType outerType= type.getDeclaringType(); + IType outerType = type.getDeclaringType(); if (outerType != null) { return outerType.getFullyQualifiedName('.'); } else { @@ -239,13 +264,12 @@ public class JavaModelUtil { } } - /** - * Concatenates two names. Uses a dot for separation. - * Both strings can be empty or null. + * Concatenates two names. Uses a dot for separation. Both strings can be + * empty or null. */ public static String concatenateName(String name1, String name2) { - StringBuffer buf= new StringBuffer(); + StringBuffer buf = new StringBuffer(); if (name1 != null && name1.length() > 0) { buf.append(name1); } @@ -259,11 +283,11 @@ public class JavaModelUtil { } /** - * Concatenates two names. Uses a dot for separation. - * Both strings can be empty or null. + * Concatenates two names. Uses a dot for separation. Both strings can be + * empty or null. */ public static String concatenateName(char[] name1, char[] name2) { - StringBuffer buf= new StringBuffer(); + StringBuffer buf = new StringBuffer(); if (name1 != null && name1.length > 0) { buf.append(name1); } @@ -279,11 +303,15 @@ public class JavaModelUtil { /** * Evaluates if a member (possible from another package) is visible from * elements in a package. - * @param member The member to test the visibility for - * @param pack The package in focus + * + * @param member + * The member to test the visibility for + * @param pack + * The package in focus */ - public static boolean isVisible(IMember member, IPackageFragment pack) throws JavaModelException { - int otherflags= member.getFlags(); + public static boolean isVisible(IMember member, IPackageFragment pack) + throws JavaModelException { + int otherflags = member.getFlags(); if (Flags.isPublic(otherflags)) { return true; @@ -291,21 +319,26 @@ public class JavaModelUtil { return false; } - IPackageFragment otherpack= (IPackageFragment) findParentOfKind(member, IJavaElement.PACKAGE_FRAGMENT); + IPackageFragment otherpack = (IPackageFragment) findParentOfKind( + member, IJavaElement.PACKAGE_FRAGMENT); return (pack != null && pack.equals(otherpack)); } /** - * Returns the package fragment root of IJavaElement. If the given - * element is already a package fragment root, the element itself is returned. + * Returns the package fragment root of IJavaElement. If the + * given element is already a package fragment root, the element itself is + * returned. */ - public static IPackageFragmentRoot getPackageFragmentRoot(IJavaElement element) { - return (IPackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); + public static IPackageFragmentRoot getPackageFragmentRoot( + IJavaElement element) { + return (IPackageFragmentRoot) element + .getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); } /** - * Returns the parent of the supplied java element that conforms to the given - * parent type or null, if such a parent doesn't exit. + * Returns the parent of the supplied java element that conforms to the + * given parent type or null, if such a parent doesn't exit. + * * @deprecated Use element.getParent().getAncestor(kind); */ public static IJavaElement findParentOfKind(IJavaElement element, int kind) { @@ -316,112 +349,154 @@ public class 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. {"QString;","I"} - * @param isConstructor If the method is a constructor + * 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. + * {"QString;","I"} + * @param isConstructor + * If the method is a constructor * @return The first found method or null, if nothing found */ - public static IMethod findMethod(String name, String[] paramTypes, boolean isConstructor, IType type) throws JavaModelException { + public static IMethod findMethod(String name, String[] paramTypes, + boolean isConstructor, IType type) throws JavaModelException { return findMethod(name, paramTypes, isConstructor, type.getMethods()); } /** - * 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. {"QString;","I"} - * @param isConstructor If the method is a constructor - * @param methods The methods to search in + * 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. + * {"QString;","I"} + * @param isConstructor + * If the method is a constructor + * @param methods + * The methods to search in * @return The found method or null, if nothing found */ - public static IMethod findMethod(String name, String[] paramTypes, boolean isConstructor, IMethod[] methods) throws JavaModelException { - for (int i= methods.length - 1; i >= 0; i--) { - if (isSameMethodSignature(name, paramTypes, isConstructor, methods[i])) { + public static IMethod findMethod(String name, String[] paramTypes, + boolean isConstructor, IMethod[] methods) throws JavaModelException { + for (int i = methods.length - 1; i >= 0; i--) { + if (isSameMethodSignature(name, paramTypes, isConstructor, + methods[i])) { return methods[i]; } } return null; } - /** - * Finds a method declararion in a type's hierarchy. The search is top down, so this - * returns the first declaration of the method in the hierarchy. - * 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 type Searches in this type's supertypes. - * @param name The name of the method to find - * @param paramTypes The type signatures of the parameters e.g. {"QString;","I"} - * @param isConstructor If the method is a constructor + * Finds a method declararion in a type's hierarchy. The search is top down, + * so this returns the first declaration of the method in the hierarchy. + * 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 type + * Searches in this type's supertypes. + * @param name + * The name of the method to find + * @param paramTypes + * The type signatures of the parameters e.g. + * {"QString;","I"} + * @param isConstructor + * If the method is a constructor * @return The first method found or null, if nothing found */ -// public static IMethod findMethodDeclarationInHierarchy(ITypeHierarchy hierarchy, IType type, String name, String[] paramTypes, boolean isConstructor) throws JavaModelException { -// IType[] superTypes= hierarchy.getAllSupertypes(type); -// for (int i= superTypes.length - 1; i >= 0; i--) { -// IMethod first= findMethod(name, paramTypes, isConstructor, superTypes[i]); -// if (first != null && !Flags.isPrivate(first.getFlags())) { -// // the order getAllSupertypes does make assumptions of the order of inner elements -> search recursivly -// IMethod res= findMethodDeclarationInHierarchy(hierarchy, first.getDeclaringType(), name, paramTypes, isConstructor); -// if (res != null) { -// return res; -// } -// return first; -// } -// } -// return null; -// } - - /** - * Finds a method implementation in a type's classhierarchy. The search is bottom-up, so this - * returns the nearest overridden method. Does not find methods in interfaces or abstract methods. - * 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. + // public static IMethod findMethodDeclarationInHierarchy(ITypeHierarchy + // hierarchy, IType type, String name, String[] paramTypes, boolean + // isConstructor) throws JavaModelException { + // IType[] superTypes= hierarchy.getAllSupertypes(type); + // for (int i= superTypes.length - 1; i >= 0; i--) { + // IMethod first= findMethod(name, paramTypes, isConstructor, + // superTypes[i]); + // if (first != null && !Flags.isPrivate(first.getFlags())) { + // // the order getAllSupertypes does make assumptions of the order of inner + // elements -> search recursivly + // IMethod res= findMethodDeclarationInHierarchy(hierarchy, + // first.getDeclaringType(), name, paramTypes, isConstructor); + // if (res != null) { + // return res; + // } + // return first; + // } + // } + // return null; + // } + /** + * Finds a method implementation in a type's classhierarchy. The search is + * bottom-up, so this returns the nearest overridden method. Does not find + * methods in interfaces or abstract methods. 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 type Type to search the superclasses - * @param name The name of the method to find - * @param paramTypes The type signatures of the parameters e.g. {"QString;","I"} - * @param isConstructor If the method is a constructor + * + * @param type + * Type to search the superclasses + * @param name + * The name of the method to find + * @param paramTypes + * The type signatures of the parameters e.g. + * {"QString;","I"} + * @param isConstructor + * If the method is a constructor * @return The first method found or null, if nothing found */ -// public static IMethod findMethodImplementationInHierarchy(ITypeHierarchy hierarchy, IType type, String name, String[] paramTypes, boolean isConstructor) throws JavaModelException { -// IType[] superTypes= hierarchy.getAllSuperclasses(type); -// for (int i= 0; i < superTypes.length; i++) { -// IMethod found= findMethod(name, paramTypes, isConstructor, superTypes[i]); -// if (found != null) { -// if (Flags.isAbstract(found.getFlags())) { -// return null; -// } -// return found; -// } -// } -// return null; -// } - - /** - * 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 of the method - * @param The type signatures of the parameters e.g. {"QString;","I"} - * @param Specifies if the method is a constructor - * @return Returns true if the method has the given name and parameter types and constructor state. - */ - public static boolean isSameMethodSignature(String name, String[] paramTypes, boolean isConstructor, IMethod curr) throws JavaModelException { + // public static IMethod findMethodImplementationInHierarchy(ITypeHierarchy + // hierarchy, IType type, String name, String[] paramTypes, boolean + // isConstructor) throws JavaModelException { + // IType[] superTypes= hierarchy.getAllSuperclasses(type); + // for (int i= 0; i < superTypes.length; i++) { + // IMethod found= findMethod(name, paramTypes, isConstructor, + // superTypes[i]); + // if (found != null) { + // if (Flags.isAbstract(found.getFlags())) { + // return null; + // } + // return found; + // } + // } + // return null; + // } + /** + * 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 + * of the method + * @param The + * type signatures of the parameters e.g. + * {"QString;","I"} + * @param Specifies + * if the method is a constructor + * @return Returns true if the method has the given name and + * parameter types and constructor state. + */ + public static boolean isSameMethodSignature(String name, + String[] paramTypes, boolean isConstructor, IMethod curr) + throws JavaModelException { if (isConstructor || name.equals(curr.getElementName())) { if (isConstructor == curr.isConstructor()) { - String[] currParamTypes= curr.getParameterTypes(); + String[] currParamTypes = curr.getParameterTypes(); if (paramTypes.length == currParamTypes.length) { - for (int i= 0; i < paramTypes.length; i++) { - String t1= Signature.getSimpleName(Signature.toString(paramTypes[i])); - String t2= Signature.getSimpleName(Signature.toString(currParamTypes[i])); + for (int i = 0; i < paramTypes.length; i++) { + String t1 = Signature.getSimpleName(Signature + .toString(paramTypes[i])); + String t2 = Signature.getSimpleName(Signature + .toString(currParamTypes[i])); if (!t1.equals(t2)) { return false; } @@ -437,8 +512,8 @@ public class JavaModelUtil { * Checks whether the given type has a valid main method or not. */ public static boolean hasMainMethod(IType type) throws JavaModelException { - IMethod[] methods= type.getMethods(); - for (int i= 0; i < methods.length; i++) { + IMethod[] methods = type.getMethods(); + for (int i = 0; i < methods.length; i++) { if (methods[i].isMainMethod()) { return true; } @@ -449,51 +524,60 @@ public class JavaModelUtil { /** * Checks if the field is boolean. */ - public static boolean isBoolean(IField field) throws JavaModelException{ + public static boolean isBoolean(IField field) throws JavaModelException { return field.getTypeSignature().equals(Signature.SIG_BOOLEAN); } /** * Returns true if the element is on the build path of the given project + * * @deprecated Use jproject.isOnClasspath(element); */ -// public static boolean isOnBuildPath(IJavaProject jproject, IJavaElement element) throws JavaModelException { -// return jproject.isOnClasspath(element); -// } - + // public static boolean isOnBuildPath(IJavaProject jproject, IJavaElement + // element) throws JavaModelException { + // return jproject.isOnClasspath(element); + // } /** - * Tests if the given element is on the class path of its containing project. Handles the case - * that the containing project isn't a Java project. + * Tests if the given element is on the class path of its containing + * project. Handles the case that the containing project isn't a Java + * project. */ -// public static boolean isOnClasspath(IJavaElement element) { -// IJavaProject project= element.getJavaProject(); -// if (!project.exists()) -// return false; -// return project.isOnClasspath(element); -// } - + // public static boolean isOnClasspath(IJavaElement element) { + // IJavaProject project= element.getJavaProject(); + // if (!project.exists()) + // return false; + // return project.isOnClasspath(element); + // } /** * Resolves a type name in the context of the declaring type. - * @param refTypeSig the type name in signature notation (for example 'QVector') - * this can also be an array type, but dimensions will be ignored. - * @param declaringType the context for resolving (type where the reference was made in) - * @return returns the fully qualified type name or build-in-type name. - * if a unresoved type couldn't be resolved null is returned - */ - public static String getResolvedTypeName(String refTypeSig, IType declaringType) throws JavaModelException { - int arrayCount= Signature.getArrayCount(refTypeSig); - char type= refTypeSig.charAt(arrayCount); + * + * @param refTypeSig + * the type name in signature notation (for example 'QVector') + * this can also be an array type, but dimensions will be + * ignored. + * @param declaringType + * the context for resolving (type where the reference was made + * in) + * @return returns the fully qualified type name or build-in-type name. if a + * unresoved type couldn't be resolved null is returned + */ + public static String getResolvedTypeName(String refTypeSig, + IType declaringType) throws JavaModelException { + int arrayCount = Signature.getArrayCount(refTypeSig); + char type = refTypeSig.charAt(arrayCount); if (type == Signature.C_UNRESOLVED) { - int semi= refTypeSig.indexOf(Signature.C_SEMICOLON, arrayCount + 1); + int semi = refTypeSig + .indexOf(Signature.C_SEMICOLON, arrayCount + 1); if (semi == -1) { throw new IllegalArgumentException(); } - String name= refTypeSig.substring(arrayCount + 1, semi); + String name = refTypeSig.substring(arrayCount + 1, semi); -// String[][] resolvedNames= declaringType.resolveType(name); -// if (resolvedNames != null && resolvedNames.length > 0) { -// return JavaModelUtil.concatenateName(resolvedNames[0][0], resolvedNames[0][1]); -// } + // String[][] resolvedNames= declaringType.resolveType(name); + // if (resolvedNames != null && resolvedNames.length > 0) { + // return JavaModelUtil.concatenateName(resolvedNames[0][0], + // resolvedNames[0][1]); + // } return null; } else { return Signature.toString(refTypeSig.substring(arrayCount)); @@ -503,74 +587,76 @@ public class JavaModelUtil { /** * Returns if a CU can be edited. */ - public static boolean isEditable(ICompilationUnit cu) { + public static boolean isEditable(ICompilationUnit cu) { if (cu.isWorkingCopy()) { - cu= (ICompilationUnit) cu.getOriginalElement(); + cu = (ICompilationUnit) cu.getOriginalElement(); } - IResource resource= cu.getResource(); - return (resource.exists() && !resource.getResourceAttributes().isReadOnly()); + IResource resource = cu.getResource(); + return (resource.exists() && !resource.getResourceAttributes() + .isReadOnly()); } /** * Finds a qualified import for a type name. */ -// public static IImportDeclaration findImport(ICompilationUnit cu, String simpleName) throws JavaModelException { -// IImportDeclaration[] existing= cu.getImports(); -// for (int i= 0; i < existing.length; i++) { -// String curr= existing[i].getElementName(); -// if (curr.endsWith(simpleName)) { -// int dotPos= curr.length() - simpleName.length() - 1; -// if ((dotPos == -1) || (dotPos > 0 && curr.charAt(dotPos) == '.')) { -// return existing[i]; -// } -// } -// } -// return null; -// } - - /** - * Returns the original if the given member. If the member is already - * an original the input is returned. The returned member must not exist + // public static IImportDeclaration findImport(ICompilationUnit cu, String + // simpleName) throws JavaModelException { + // IImportDeclaration[] existing= cu.getImports(); + // for (int i= 0; i < existing.length; i++) { + // String curr= existing[i].getElementName(); + // if (curr.endsWith(simpleName)) { + // int dotPos= curr.length() - simpleName.length() - 1; + // if ((dotPos == -1) || (dotPos > 0 && curr.charAt(dotPos) == '.')) { + // return existing[i]; + // } + // } + // } + // return null; + // } + /** + * Returns the original if the given member. If the member is already an + * original the input is returned. The returned member must not exist */ public static IMember toOriginal(IMember member) { if (member instanceof IMethod) - return toOriginalMethod((IMethod)member); - ICompilationUnit cu= member.getCompilationUnit(); + return toOriginalMethod((IMethod) member); + ICompilationUnit cu = member.getCompilationUnit(); if (cu != null && cu.isWorkingCopy()) - return (IMember)cu.getOriginal(member); + return (IMember) cu.getOriginal(member); return member; } /* * XXX workaround for bug 18568 - * http://bugs.eclipse.org/bugs/show_bug.cgi?id=18568 - * to be removed once the bug is fixed + * http://bugs.eclipse.org/bugs/show_bug.cgi?id=18568 to be removed once the + * bug is fixed */ private static IMethod toOriginalMethod(IMethod method) { - try{ - ICompilationUnit cu= method.getCompilationUnit(); - if (cu == null || ! cu.isWorkingCopy()) + try { + ICompilationUnit cu = method.getCompilationUnit(); + if (cu == null || !cu.isWorkingCopy()) return method; - //use the workaround only if needed - if (! method.getElementName().equals(method.getDeclaringType().getElementName())) - return (IMethod)cu.getOriginal(method); + // use the workaround only if needed + if (!method.getElementName().equals( + method.getDeclaringType().getElementName())) + return (IMethod) cu.getOriginal(method); - IType originalType = (IType)toOriginal(method.getDeclaringType()); + IType originalType = (IType) toOriginal(method.getDeclaringType()); IMethod[] methods = originalType.findMethods(method); boolean isConstructor = method.isConstructor(); - for (int i=0; i < methods.length; i++) { - if (methods[i].isConstructor() == isConstructor) - return methods[i]; + for (int i = 0; i < methods.length; i++) { + if (methods[i].isConstructor() == isConstructor) + return methods[i]; } return null; - } catch(JavaModelException e){ + } catch (JavaModelException e) { return null; } } /** - * Returns the original cu if the given cu. If the cu is already - * an original the input cu is returned. The returned cu must not exist + * Returns the original cu if the given cu. If the cu is already an original + * the input cu is returned. The returned cu must not exist */ public static ICompilationUnit toOriginal(ICompilationUnit cu) { if (cu != null && cu.isWorkingCopy()) @@ -579,15 +665,16 @@ public class JavaModelUtil { } /** - * Returns the working copy of the given member. If the member is already in a - * working copy or the member does not exist in the working copy the input is returned. + * Returns the working copy of the given member. If the member is already in + * a working copy or the member does not exist in the working copy the input + * is returned. */ public static IMember toWorkingCopy(IMember member) { - ICompilationUnit cu= member.getCompilationUnit(); + ICompilationUnit cu = member.getCompilationUnit(); if (cu != null && !cu.isWorkingCopy()) { - ICompilationUnit workingCopy= EditorUtility.getWorkingCopy(cu); + ICompilationUnit workingCopy = EditorUtility.getWorkingCopy(cu); if (workingCopy != null) { - IJavaElement[] members= workingCopy.findElements(member); + IJavaElement[] members = workingCopy.findElements(member); if (members != null && members.length > 0) { return (IMember) members[0]; } @@ -596,14 +683,13 @@ public class JavaModelUtil { return member; } - /** * Returns the working copy CU of the given CU. If the CU is already a * working copy or the CU has no working copy the input CU is returned. */ public static ICompilationUnit toWorkingCopy(ICompilationUnit cu) { if (!cu.isWorkingCopy()) { - ICompilationUnit workingCopy= EditorUtility.getWorkingCopy(cu); + ICompilationUnit workingCopy = EditorUtility.getWorkingCopy(cu); if (workingCopy != null) { return workingCopy; } @@ -613,21 +699,23 @@ public class JavaModelUtil { /* * http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253 - * - * Reconciling happens in a separate thread. This can cause a situation where the - * Java element gets disposed after an exists test has been done. So we should not - * log not present exceptions when they happen in working copies. + * + * Reconciling happens in a separate thread. This can cause a situation + * where the Java element gets disposed after an exists test has been done. + * So we should not log not present exceptions when they happen in working + * copies. */ public static boolean filterNotPresentException(CoreException exception) { if (!(exception instanceof JavaModelException)) return true; - JavaModelException je= (JavaModelException)exception; + JavaModelException je = (JavaModelException) exception; if (!je.isDoesNotExist()) return true; - IJavaElement[] elements= je.getJavaModelStatus().getElements(); - for (int i= 0; i < elements.length; i++) { - IJavaElement element= elements[i]; - ICompilationUnit unit= (ICompilationUnit)element.getAncestor(IJavaElement.COMPILATION_UNIT); + IJavaElement[] elements = je.getJavaModelStatus().getElements(); + for (int i = 0; i < elements.length; i++) { + IJavaElement element = elements[i]; + ICompilationUnit unit = (ICompilationUnit) element + .getAncestor(IJavaElement.COMPILATION_UNIT); if (unit == null) return true; if (!unit.isWorkingCopy()) @@ -636,34 +724,37 @@ public class JavaModelUtil { return false; } -// public static IType[] getAllSuperTypes(IType type, IProgressMonitor pm) throws JavaModelException { -// //workaround for bugs 23644 and 23656 -// try{ -// pm.beginTask("", 3); //$NON-NLS-1$ -// ITypeHierarchy hierarchy= type.newSupertypeHierarchy(new SubProgressMonitor(pm, 1)); -// -// IProgressMonitor subPm= new SubProgressMonitor(pm, 2); -// List typeList= Arrays.asList(hierarchy.getAllSupertypes(type)); -// subPm.beginTask("", typeList.size()); //$NON-NLS-1$ -// Set types= new HashSet(typeList); -// for (Iterator iter= typeList.iterator(); iter.hasNext();) { -// IType superType= (IType)iter.next(); -// IType[] superTypes= getAllSuperTypes(superType, new SubProgressMonitor(subPm, 1)); -// types.addAll(Arrays.asList(superTypes)); -// } -// types.add(type.getJavaProject().findType("java.lang.Object"));//$NON-NLS-1$ -// subPm.done(); -// return (IType[]) types.toArray(new IType[types.size()]); -// } finally { -// pm.done(); -// } -// } - - - public static boolean isExcludedPath(IPath resourcePath, IPath[] exclusionPatterns) { + // public static IType[] getAllSuperTypes(IType type, IProgressMonitor pm) + // throws JavaModelException { + // //workaround for bugs 23644 and 23656 + // try{ + // pm.beginTask("", 3); //$NON-NLS-1$ + // ITypeHierarchy hierarchy= type.newSupertypeHierarchy(new + // SubProgressMonitor(pm, 1)); + // + // IProgressMonitor subPm= new SubProgressMonitor(pm, 2); + // List typeList= Arrays.asList(hierarchy.getAllSupertypes(type)); + // subPm.beginTask("", typeList.size()); //$NON-NLS-1$ + // Set types= new HashSet(typeList); + // for (Iterator iter= typeList.iterator(); iter.hasNext();) { + // IType superType= (IType)iter.next(); + // IType[] superTypes= getAllSuperTypes(superType, new + // SubProgressMonitor(subPm, 1)); + // types.addAll(Arrays.asList(superTypes)); + // } + // types.add(type.getJavaProject().findType("java.lang.Object"));//$NON-NLS-1$ + // subPm.done(); + // return (IType[]) types.toArray(new IType[types.size()]); + // } finally { + // pm.done(); + // } + // } + + public static boolean isExcludedPath(IPath resourcePath, + IPath[] exclusionPatterns) { char[] path = resourcePath.toString().toCharArray(); for (int i = 0, length = exclusionPatterns.length; i < length; i++) { - char[] pattern= exclusionPatterns[i].toString().toCharArray(); + char[] pattern = exclusionPatterns[i].toString().toCharArray(); if (CharOperation.pathMatch(pattern, path, true, '/')) { return true; } @@ -671,15 +762,16 @@ public class JavaModelUtil { return false; } - /* * Returns whether the given resource path matches one of the exclusion * patterns. - * + * * @see IClasspathEntry#getExclusionPatterns */ - public final static boolean isExcluded(IPath resourcePath, char[][] exclusionPatterns) { - if (exclusionPatterns == null) return false; + public final static boolean isExcluded(IPath resourcePath, + char[][] exclusionPatterns) { + if (exclusionPatterns == null) + return false; char[] path = resourcePath.toString().toCharArray(); for (int i = 0, length = exclusionPatterns.length; i < length; i++) if (CharOperation.pathMatch(exclusionPatterns[i], path, true, '/')) @@ -687,23 +779,24 @@ public class JavaModelUtil { return false; } - private static final String ARGUMENTS_DELIMITER = "#"; //$NON-NLS-1$ + private static final String EMPTY_ARGUMENT = " "; //$NON-NLS-1$ /** * Copied from net.sourceforge.phpdt.internal.core.ProjectPrefUtil; */ - public static String[] getProblemArgumentsFromMarker(String argumentsString){ - if (argumentsString == null) return null; + public static String[] getProblemArgumentsFromMarker(String argumentsString) { + if (argumentsString == null) + return null; int index = argumentsString.indexOf(':'); - if(index == -1) + if (index == -1) return null; int length = argumentsString.length(); int numberOfArg; - try{ - numberOfArg = Integer.parseInt(argumentsString.substring(0 , index)); + try { + numberOfArg = Integer.parseInt(argumentsString.substring(0, index)); } catch (NumberFormatException e) { return null; } @@ -712,15 +805,16 @@ public class JavaModelUtil { String[] args = new String[length]; int count = 0; - StringTokenizer tokenizer = new StringTokenizer(argumentsString, ARGUMENTS_DELIMITER); - while(tokenizer.hasMoreTokens()) { + StringTokenizer tokenizer = new StringTokenizer(argumentsString, + ARGUMENTS_DELIMITER); + while (tokenizer.hasMoreTokens()) { String argument = tokenizer.nextToken(); - if(argument.equals(EMPTY_ARGUMENT)) - argument = ""; //$NON-NLS-1$ + if (argument.equals(EMPTY_ARGUMENT)) + argument = ""; //$NON-NLS-1$ args[count++] = argument; } - if(count != numberOfArg) + if (count != numberOfArg) return null; System.arraycopy(args, 0, args = new String[count], 0, count); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/JdtFlags.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/JdtFlags.java index 6e753e7..cdb35a0 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/JdtFlags.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/JdtFlags.java @@ -20,220 +20,241 @@ import net.sourceforge.phpdt.core.JavaModelException; import net.sourceforge.phpdt.internal.corext.Assert; public class JdtFlags { - private JdtFlags(){ + private JdtFlags() { } - - public static final String VISIBILITY_STRING_PRIVATE= "private"; //$NON-NLS-1$ - public static final String VISIBILITY_STRING_PACKAGE= ""; //$NON-NLS-1$ - public static final String VISIBILITY_STRING_PROTECTED= "protected"; //$NON-NLS-1$ - public static final String VISIBILITY_STRING_PUBLIC= "public"; //$NON-NLS-1$ - - public static final int VISIBILITY_CODE_INVALID= -1; + public static final String VISIBILITY_STRING_PRIVATE = "private"; //$NON-NLS-1$ - public static boolean isAbstract(IMember member) throws JavaModelException{ + public static final String VISIBILITY_STRING_PACKAGE = ""; //$NON-NLS-1$ + + public static final String VISIBILITY_STRING_PROTECTED = "protected"; //$NON-NLS-1$ + + public static final String VISIBILITY_STRING_PUBLIC = "public"; //$NON-NLS-1$ + + public static final int VISIBILITY_CODE_INVALID = -1; + + public static boolean isAbstract(IMember member) throws JavaModelException { if (isInterfaceMethod(member)) return true; - return Flags.isAbstract(member.getFlags()); + return Flags.isAbstract(member.getFlags()); } - -// public static boolean isAbstract(IMethodBinding member) { -// if (isInterfaceMember(member)) -// return true; -// return Modifier.isAbstract(member.getModifiers()); -// } - - public static boolean isDeprecated(IMember member) throws JavaModelException{ + + // public static boolean isAbstract(IMethodBinding member) { + // if (isInterfaceMember(member)) + // return true; + // return Modifier.isAbstract(member.getModifiers()); + // } + + public static boolean isDeprecated(IMember member) + throws JavaModelException { return Flags.isDeprecated(member.getFlags()); } - public static boolean isFinal(IMember member) throws JavaModelException{ + public static boolean isFinal(IMember member) throws JavaModelException { if (isInterfaceField(member)) return true; - if (isAnonymousType(member)) + if (isAnonymousType(member)) return true; return Flags.isFinal(member.getFlags()); } -// public static boolean isNative(IMember member) throws JavaModelException{ -// return Flags.isNative(member.getFlags()); -// } + // public static boolean isNative(IMember member) throws JavaModelException{ + // return Flags.isNative(member.getFlags()); + // } - public static boolean isPackageVisible(IMember member) throws JavaModelException{ - return (! isPrivate(member) && ! isProtected(member) && ! isPublic(member)); + public static boolean isPackageVisible(IMember member) + throws JavaModelException { + return (!isPrivate(member) && !isProtected(member) && !isPublic(member)); } -// public static boolean isPackageVisible(BodyDeclaration bodyDeclaration) { -// return (! isPrivate(bodyDeclaration) && ! isProtected(bodyDeclaration) && ! isPublic(bodyDeclaration)); -// } -// -// public static boolean isPackageVisible(IBinding binding) { -// return (! isPrivate(binding) && ! isProtected(binding) && ! isPublic(binding)); -// } - - public static boolean isPrivate(IMember member) throws JavaModelException{ + // public static boolean isPackageVisible(BodyDeclaration bodyDeclaration) { + // return (! isPrivate(bodyDeclaration) && ! isProtected(bodyDeclaration) && + // ! isPublic(bodyDeclaration)); + // } + // + // public static boolean isPackageVisible(IBinding binding) { + // return (! isPrivate(binding) && ! isProtected(binding) && ! + // isPublic(binding)); + // } + + public static boolean isPrivate(IMember member) throws JavaModelException { return Flags.isPrivate(member.getFlags()); } -// public static boolean isPrivate(BodyDeclaration bodyDeclaration) { -// return Modifier.isPrivate(bodyDeclaration.getModifiers()); -// } -// -// public static boolean isPrivate(IBinding binding) { -// return Modifier.isPrivate(binding.getModifiers()); -// } + // public static boolean isPrivate(BodyDeclaration bodyDeclaration) { + // return Modifier.isPrivate(bodyDeclaration.getModifiers()); + // } + // + // public static boolean isPrivate(IBinding binding) { + // return Modifier.isPrivate(binding.getModifiers()); + // } - public static boolean isProtected(IMember member) throws JavaModelException{ + public static boolean isProtected(IMember member) throws JavaModelException { return Flags.isProtected(member.getFlags()); } -// public static boolean isProtected(BodyDeclaration bodyDeclaration) { -// return Modifier.isProtected(bodyDeclaration.getModifiers()); -// } -// -// public static boolean isProtected(IBinding binding) { -// return Modifier.isProtected(binding.getModifiers()); -// } + // public static boolean isProtected(BodyDeclaration bodyDeclaration) { + // return Modifier.isProtected(bodyDeclaration.getModifiers()); + // } + // + // public static boolean isProtected(IBinding binding) { + // return Modifier.isProtected(binding.getModifiers()); + // } - public static boolean isPublic(IMember member) throws JavaModelException{ + public static boolean isPublic(IMember member) throws JavaModelException { if (isInterfaceMember(member)) return true; return Flags.isPublic(member.getFlags()); } - -// public static boolean isPublic(IBinding binding) { -// if (isInterfaceMember(binding)) -// return true; -// return Modifier.isPublic(binding.getModifiers()); -// } -// -// -// public static boolean isPublic(BodyDeclaration bodyDeclaration) { -// if (isInterfaceMember(bodyDeclaration)) -// return true; -// return Modifier.isPublic(bodyDeclaration.getModifiers()); -// } - - public static boolean isStatic(IMember member) throws JavaModelException{ + + // public static boolean isPublic(IBinding binding) { + // if (isInterfaceMember(binding)) + // return true; + // return Modifier.isPublic(binding.getModifiers()); + // } + // + // + // public static boolean isPublic(BodyDeclaration bodyDeclaration) { + // if (isInterfaceMember(bodyDeclaration)) + // return true; + // return Modifier.isPublic(bodyDeclaration.getModifiers()); + // } + + public static boolean isStatic(IMember member) throws JavaModelException { if (isNestedInterface(member)) return true; - if (member.getElementType() != IJavaElement.METHOD && isInterfaceMember(member)) + if (member.getElementType() != IJavaElement.METHOD + && isInterfaceMember(member)) return true; return Flags.isStatic(member.getFlags()); } -// public static boolean isStatic(IMethodBinding methodBinding){ -// return Modifier.isStatic(methodBinding.getModifiers()); -// } -// -// public static boolean isStatic(IVariableBinding variableBinding){ -// if (isInterfaceMember(variableBinding)) -// return true; -// return Modifier.isStatic(variableBinding.getModifiers()); -// } - -// public static boolean isStrictfp(IMember member) throws JavaModelException{ -// return Flags.isStrictfp(member.getFlags()); -// } -// -// public static boolean isSynchronized(IMember member) throws JavaModelException{ -// return Flags.isSynchronized(member.getFlags()); -// } -// -// public static boolean isSynthetic(IMember member) throws JavaModelException{ -// return Flags.isSynthetic(member.getFlags()); -// } -// -// public static boolean isTransient(IMember member) throws JavaModelException{ -// return Flags.isTransient(member.getFlags()); -// } - -// public static boolean isVolatile(IMember member) throws JavaModelException{ -// return Flags.isVolatile(member.getFlags()); -// } - - private static boolean isInterfaceMethod(IMember member) throws JavaModelException { - return member.getElementType() == IJavaElement.METHOD && isInterfaceMember(member); + // public static boolean isStatic(IMethodBinding methodBinding){ + // return Modifier.isStatic(methodBinding.getModifiers()); + // } + // + // public static boolean isStatic(IVariableBinding variableBinding){ + // if (isInterfaceMember(variableBinding)) + // return true; + // return Modifier.isStatic(variableBinding.getModifiers()); + // } + + // public static boolean isStrictfp(IMember member) throws + // JavaModelException{ + // return Flags.isStrictfp(member.getFlags()); + // } + // + // public static boolean isSynchronized(IMember member) throws + // JavaModelException{ + // return Flags.isSynchronized(member.getFlags()); + // } + // + // public static boolean isSynthetic(IMember member) throws + // JavaModelException{ + // return Flags.isSynthetic(member.getFlags()); + // } + // + // public static boolean isTransient(IMember member) throws + // JavaModelException{ + // return Flags.isTransient(member.getFlags()); + // } + + // public static boolean isVolatile(IMember member) throws + // JavaModelException{ + // return Flags.isVolatile(member.getFlags()); + // } + + private static boolean isInterfaceMethod(IMember member) + throws JavaModelException { + return member.getElementType() == IJavaElement.METHOD + && isInterfaceMember(member); } - private static boolean isInterfaceField(IMember member) throws JavaModelException { - return member.getElementType() == IJavaElement.FIELD && isInterfaceMember(member); + private static boolean isInterfaceField(IMember member) + throws JavaModelException { + return member.getElementType() == IJavaElement.FIELD + && isInterfaceMember(member); } - private static boolean isInterfaceMember(IMember member) throws JavaModelException { - return member.getDeclaringType() != null && member.getDeclaringType().isInterface(); + private static boolean isInterfaceMember(IMember member) + throws JavaModelException { + return member.getDeclaringType() != null + && member.getDeclaringType().isInterface(); } - -// private static boolean isInterfaceMember(IBinding binding) { -// ITypeBinding declaringType= null; -// if (binding instanceof IVariableBinding) { -// declaringType= ((IVariableBinding) binding).getDeclaringClass(); -// } else if (binding instanceof IMethodBinding) { -// declaringType= ((IMethodBinding) binding).getDeclaringClass(); -// } else if (binding instanceof ITypeBinding) { -// declaringType= ((ITypeBinding) binding).getDeclaringClass(); -// } -// return declaringType != null && declaringType.isInterface(); -// } - -// private static boolean isInterfaceMember(BodyDeclaration bodyDeclaration) { -// return (bodyDeclaration.getParent() instanceof TypeDeclaration) && -// ((TypeDeclaration)bodyDeclaration.getParent()).isInterface(); -// } - - private static boolean isNestedInterface(IMember member) throws JavaModelException{ - return member.getElementType() == IJavaElement.TYPE && - member.getDeclaringType() != null && - ((IType)member).isInterface(); + + // private static boolean isInterfaceMember(IBinding binding) { + // ITypeBinding declaringType= null; + // if (binding instanceof IVariableBinding) { + // declaringType= ((IVariableBinding) binding).getDeclaringClass(); + // } else if (binding instanceof IMethodBinding) { + // declaringType= ((IMethodBinding) binding).getDeclaringClass(); + // } else if (binding instanceof ITypeBinding) { + // declaringType= ((ITypeBinding) binding).getDeclaringClass(); + // } + // return declaringType != null && declaringType.isInterface(); + // } + + // private static boolean isInterfaceMember(BodyDeclaration bodyDeclaration) + // { + // return (bodyDeclaration.getParent() instanceof TypeDeclaration) && + // ((TypeDeclaration)bodyDeclaration.getParent()).isInterface(); + // } + + private static boolean isNestedInterface(IMember member) + throws JavaModelException { + return member.getElementType() == IJavaElement.TYPE + && member.getDeclaringType() != null + && ((IType) member).isInterface(); } - private static boolean isAnonymousType(IMember member) throws JavaModelException { - return member.getElementType() == IJavaElement.TYPE && - ((IType)member).isAnonymous(); + private static boolean isAnonymousType(IMember member) + throws JavaModelException { + return member.getElementType() == IJavaElement.TYPE + && ((IType) member).isAnonymous(); } - public static int getVisibilityCode(IMember member) throws JavaModelException { + public static int getVisibilityCode(IMember member) + throws JavaModelException { if (isPublic(member)) return Modifier.PUBLIC; else if (isProtected(member)) return Modifier.PROTECTED; -// else if (isPackageVisible(member)) -// return Modifier.NONE; + // else if (isPackageVisible(member)) + // return Modifier.NONE; else if (isPrivate(member)) return Modifier.PRIVATE; -// Assert.isTrue(false); -// return VISIBILITY_CODE_INVALID; + // Assert.isTrue(false); + // return VISIBILITY_CODE_INVALID; return Modifier.PUBLIC; } - -// public static int getVisibilityCode(BodyDeclaration bodyDeclaration) { -// if (isPublic(bodyDeclaration)) -// return Modifier.PUBLIC; -// else if (isProtected(bodyDeclaration)) -// return Modifier.PROTECTED; -// else if (isPackageVisible(bodyDeclaration)) -// return Modifier.NONE; -// else if (isPrivate(bodyDeclaration)) -// return Modifier.PRIVATE; -// Assert.isTrue(false); -// return VISIBILITY_CODE_INVALID; -// } - -// public static int getVisibilityCode(IBinding binding) { -// if (isPublic(binding)) -// return Modifier.PUBLIC; -// else if (isProtected(binding)) -// return Modifier.PROTECTED; -// else if (isPackageVisible(binding)) -// return Modifier.NONE; -// else if (isPrivate(binding)) -// return Modifier.PRIVATE; -// Assert.isTrue(false); -// return VISIBILITY_CODE_INVALID; -// } - - - public static String getVisibilityString(int visibilityCode){ + + // public static int getVisibilityCode(BodyDeclaration bodyDeclaration) { + // if (isPublic(bodyDeclaration)) + // return Modifier.PUBLIC; + // else if (isProtected(bodyDeclaration)) + // return Modifier.PROTECTED; + // else if (isPackageVisible(bodyDeclaration)) + // return Modifier.NONE; + // else if (isPrivate(bodyDeclaration)) + // return Modifier.PRIVATE; + // Assert.isTrue(false); + // return VISIBILITY_CODE_INVALID; + // } + + // public static int getVisibilityCode(IBinding binding) { + // if (isPublic(binding)) + // return Modifier.PUBLIC; + // else if (isProtected(binding)) + // return Modifier.PROTECTED; + // else if (isPackageVisible(binding)) + // return Modifier.NONE; + // else if (isPrivate(binding)) + // return Modifier.PRIVATE; + // Assert.isTrue(false); + // return VISIBILITY_CODE_INVALID; + // } + + public static String getVisibilityString(int visibilityCode) { if (Modifier.isPublic(visibilityCode)) return VISIBILITY_STRING_PUBLIC; if (Modifier.isProtected(visibilityCode)) @@ -242,49 +263,51 @@ public class JdtFlags { return VISIBILITY_STRING_PRIVATE; return VISIBILITY_STRING_PACKAGE; } - - public static void assertVisibility(int visibility){ - Assert.isTrue( visibility == Modifier.PUBLIC || - visibility == Modifier.PROTECTED || -// visibility == Modifier.NONE || - visibility == Modifier.PRIVATE); + + public static void assertVisibility(int visibility) { + Assert.isTrue(visibility == Modifier.PUBLIC + || visibility == Modifier.PROTECTED || + // visibility == Modifier.NONE || + visibility == Modifier.PRIVATE); } - - public static boolean isHigherVisibility(int newVisibility, int oldVisibility){ + + public static boolean isHigherVisibility(int newVisibility, + int oldVisibility) { assertVisibility(oldVisibility); assertVisibility(newVisibility); switch (oldVisibility) { - case Modifier.PRIVATE : - return //newVisibility == Modifier.NONE || - newVisibility == Modifier.PUBLIC - || newVisibility == Modifier.PROTECTED; -// case Modifier.NONE : -// return newVisibility == Modifier.PUBLIC -// || newVisibility == Modifier.PROTECTED; - - case Modifier.PROTECTED : - return newVisibility == Modifier.PUBLIC; - - case Modifier.PUBLIC : - return false; - default: -// Assert.isTrue(false); - return false; + case Modifier.PRIVATE: + return // newVisibility == Modifier.NONE || + newVisibility == Modifier.PUBLIC + || newVisibility == Modifier.PROTECTED; + // case Modifier.NONE : + // return newVisibility == Modifier.PUBLIC + // || newVisibility == Modifier.PROTECTED; + + case Modifier.PROTECTED: + return newVisibility == Modifier.PUBLIC; + + case Modifier.PUBLIC: + return false; + default: + // Assert.isTrue(false); + return false; } } - + public static int getLowerVisibility(int visibility1, int visibility2) { if (isHigherVisibility(visibility1, visibility2)) return visibility2; else return visibility1; } - + public static int clearAccessModifiers(int flags) { - return clearFlag(Modifier.PROTECTED | Modifier.PUBLIC | Modifier.PRIVATE, flags); + return clearFlag(Modifier.PROTECTED | Modifier.PUBLIC + | Modifier.PRIVATE, flags); } - public static int clearFlag(int flag, int flags){ - return flags & ~ flag; + public static int clearFlag(int flag, int flags) { + return flags & ~flag; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/Resources.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/Resources.java index 709a80a..d03b7b3 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/Resources.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/Resources.java @@ -37,46 +37,56 @@ public class Resources { /** * Checks if the given resource is in sync with the underlying file system. - * - * @param resource the resource to be checked + * + * @param resource + * the resource to be checked * @return IStatus status describing the check's result. If status. - * isOK() returns true then the resource is in sync + * isOK()
                                                      + * returns true then the resource is in sync */ public static IStatus checkInSync(IResource resource) { - return checkInSync(new IResource[] {resource}); + return checkInSync(new IResource[] { resource }); } /** * Checks if the given resources are in sync with the underlying file * system. - * - * @param resources the resources to be checked + * + * @param resources + * the resources to be checked * @return IStatus status describing the check's result. If status. - * isOK() returns true then the resources are in sync + * isOK()
                                                      + * returns true then the resources are in sync */ public static IStatus checkInSync(IResource[] resources) { - IStatus result= null; - for (int i= 0; i < resources.length; i++) { - IResource resource= resources[i]; + IStatus result = null; + for (int i = 0; i < resources.length; i++) { + IResource resource = resources[i]; if (!resource.isSynchronized(IResource.DEPTH_INFINITE)) { - result= addOutOfSync(result, resource); + result = addOutOfSync(result, resource); } } if (result != null) return result; - return new Status(IStatus.OK, PHPeclipsePlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$ + return new Status(IStatus.OK, PHPeclipsePlugin.getPluginId(), + IStatus.OK, "", null); //$NON-NLS-1$ } /** * Makes the given resource committable. Committable means that it is * writeable and that its content hasn't changed by calling * validateEdit for the given resource on IWorkspace. - * - * @param resource the resource to be checked - * @param context the context passed to validateEdit - * @return status describing the method's result. If status.isOK() returns true then the resources are committable. - * - * @see org.eclipse.core.resources.IWorkspace#validateEdit(org.eclipse.core.resources.IFile[], java.lang.Object) + * + * @param resource + * the resource to be checked + * @param context + * the context passed to validateEdit + * @return status describing the method's result. If + * status.isOK() returns true then the + * resources are committable. + * + * @see org.eclipse.core.resources.IWorkspace#validateEdit(org.eclipse.core.resources.IFile[], + * java.lang.Object) */ public static IStatus makeCommittable(IResource resource, Object context) { return makeCommittable(new IResource[] { resource }, context); @@ -87,66 +97,78 @@ public class Resources { * resources are writeable and that the content of the resources hasn't * changed by calling validateEdit for a given file on * IWorkspace. - * - * @param resources the resources to be checked - * @param context the context passed to validateEdit + * + * @param resources + * the resources to be checked + * @param context + * the context passed to validateEdit * @return IStatus status describing the method's result. If status. - * isOK() returns true then the add resources are - * committable - * - * @see org.eclipse.core.resources.IWorkspace#validateEdit(org.eclipse.core.resources.IFile[], java.lang.Object) + * isOK()
                                                      + * returns true then the add resources are + * committable + * + * @see org.eclipse.core.resources.IWorkspace#validateEdit(org.eclipse.core.resources.IFile[], + * java.lang.Object) */ public static IStatus makeCommittable(IResource[] resources, Object context) { - List readOnlyFiles= new ArrayList(); - for (int i= 0; i < resources.length; i++) { - IResource resource= resources[i]; - if (resource.getType() == IResource.FILE && resource.getResourceAttributes().isReadOnly()) + List readOnlyFiles = new ArrayList(); + for (int i = 0; i < resources.length; i++) { + IResource resource = resources[i]; + if (resource.getType() == IResource.FILE + && resource.getResourceAttributes().isReadOnly()) readOnlyFiles.add(resource); } if (readOnlyFiles.size() == 0) - return new Status(IStatus.OK, PHPeclipsePlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$ + return new Status(IStatus.OK, PHPeclipsePlugin.getPluginId(), + IStatus.OK, "", null); //$NON-NLS-1$ - Map oldTimeStamps= createModificationStampMap(readOnlyFiles); - IStatus status= ResourcesPlugin.getWorkspace().validateEdit( - (IFile[]) readOnlyFiles.toArray(new IFile[readOnlyFiles.size()]), context); + Map oldTimeStamps = createModificationStampMap(readOnlyFiles); + IStatus status = ResourcesPlugin.getWorkspace().validateEdit( + (IFile[]) readOnlyFiles + .toArray(new IFile[readOnlyFiles.size()]), context); if (!status.isOK()) return status; - IStatus modified= null; - Map newTimeStamps= createModificationStampMap(readOnlyFiles); - for (Iterator iter= oldTimeStamps.keySet().iterator(); iter.hasNext();) { - IFile file= (IFile) iter.next(); + IStatus modified = null; + Map newTimeStamps = createModificationStampMap(readOnlyFiles); + for (Iterator iter = oldTimeStamps.keySet().iterator(); iter.hasNext();) { + IFile file = (IFile) iter.next(); if (!oldTimeStamps.get(file).equals(newTimeStamps.get(file))) - modified= addModified(modified, file); + modified = addModified(modified, file); } if (modified != null) return modified; - return new Status(IStatus.OK, PHPeclipsePlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$ + return new Status(IStatus.OK, PHPeclipsePlugin.getPluginId(), + IStatus.OK, "", null); //$NON-NLS-1$ } - private static Map createModificationStampMap(List files){ - Map map= new HashMap(); - for (Iterator iter= files.iterator(); iter.hasNext(); ) { - IFile file= (IFile)iter.next(); + private static Map createModificationStampMap(List files) { + Map map = new HashMap(); + for (Iterator iter = files.iterator(); iter.hasNext();) { + IFile file = (IFile) iter.next(); map.put(file, new Long(file.getModificationStamp())); } return map; } private static IStatus addModified(IStatus status, IFile file) { - IStatus entry= PHPUIStatus.createError( - IJavaStatusConstants.VALIDATE_EDIT_CHANGED_CONTENT, - CorextMessages.getFormattedString("Resources.fileModified", file.getFullPath().toString()), //$NON-NLS-1$ - null); + IStatus entry = PHPUIStatus + .createError( + IJavaStatusConstants.VALIDATE_EDIT_CHANGED_CONTENT, + CorextMessages + .getFormattedString( + "Resources.fileModified", file.getFullPath().toString()), //$NON-NLS-1$ + null); if (status == null) { return entry; } else if (status.isMultiStatus()) { - ((MultiStatus)status).add(entry); + ((MultiStatus) status).add(entry); return status; } else { - MultiStatus result= new MultiStatus(PHPeclipsePlugin.getPluginId(), - IJavaStatusConstants.VALIDATE_EDIT_CHANGED_CONTENT, - CorextMessages.getString("Resources.modifiedResources"), null); //$NON-NLS-1$ + MultiStatus result = new MultiStatus( + PHPeclipsePlugin.getPluginId(), + IJavaStatusConstants.VALIDATE_EDIT_CHANGED_CONTENT, + CorextMessages.getString("Resources.modifiedResources"), null); //$NON-NLS-1$ result.add(status); result.add(entry); return result; @@ -154,22 +176,23 @@ public class Resources { } private static IStatus addOutOfSync(IStatus status, IResource resource) { - IStatus entry= new Status( - IStatus.ERROR, - ResourcesPlugin.PI_RESOURCES, - IResourceStatus.OUT_OF_SYNC_LOCAL, - CorextMessages.getFormattedString("Resources.outOfSync", resource.getFullPath().toString()), //$NON-NLS-1$ - null); + IStatus entry = new Status( + IStatus.ERROR, + ResourcesPlugin.PI_RESOURCES, + IResourceStatus.OUT_OF_SYNC_LOCAL, + CorextMessages + .getFormattedString( + "Resources.outOfSync", resource.getFullPath().toString()), //$NON-NLS-1$ + null); if (status == null) { return entry; } else if (status.isMultiStatus()) { - ((MultiStatus)status).add(entry); + ((MultiStatus) status).add(entry); return status; } else { - MultiStatus result= new MultiStatus( - ResourcesPlugin.PI_RESOURCES, - IResourceStatus.OUT_OF_SYNC_LOCAL, - CorextMessages.getString("Resources.outOfSyncResources"), null); //$NON-NLS-1$ + MultiStatus result = new MultiStatus(ResourcesPlugin.PI_RESOURCES, + IResourceStatus.OUT_OF_SYNC_LOCAL, CorextMessages + .getString("Resources.outOfSyncResources"), null); //$NON-NLS-1$ result.add(status); result.add(entry); return result; @@ -177,9 +200,9 @@ public class Resources { } public static String[] getLocationOSStrings(IResource[] resources) { - List result= new ArrayList(resources.length); - for (int i= 0; i < resources.length; i++) { - IPath location= resources[i].getLocation(); + List result = new ArrayList(resources.length); + for (int i = 0; i < resources.length; i++) { + IPath location = resources[i].getLocation(); if (location != null) result.add(location.toOSString()); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/Strings.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/Strings.java index 22052c4..5012eb7 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/Strings.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/Strings.java @@ -16,10 +16,11 @@ import org.eclipse.jface.text.ILineTracker; import org.eclipse.jface.text.IRegion; /** - * Helper class to provide String manipulation functions not available in standard JDK. + * Helper class to provide String manipulation functions not available in + * standard JDK. */ public class Strings { - + /** * Indent char is a space char but not a line delimiters. * == Character.isWhitespace(ch) && ch != '\n' && ch != '\r' @@ -27,53 +28,55 @@ public class Strings { public static boolean isIndentChar(char ch) { return Character.isWhitespace(ch) && !isLineDelimiterChar(ch); } - + /** - * tests if a char is lower case. Fix for 26529 + * tests if a char is lower case. Fix for 26529 */ public static boolean isLowerCase(char ch) { return Character.toLowerCase(ch) == ch; - } - + } + /** - * Line delimiter chars are '\n' and '\r'. + * Line delimiter chars are '\n' and '\r'. */ public static boolean isLineDelimiterChar(char ch) { return ch == '\n' || ch == '\r'; - } + } public static String removeNewLine(String message) { - StringBuffer result= new StringBuffer(); - int current= 0; - int index= message.indexOf('\n', 0); + StringBuffer result = new StringBuffer(); + int current = 0; + int index = message.indexOf('\n', 0); while (index != -1) { result.append(message.substring(current, index)); if (current < index && index != 0) result.append(' '); - current= index + 1; - index= message.indexOf('\n', current); + current = index + 1; + index = message.indexOf('\n', current); } result.append(message.substring(current)); return result.toString(); } /** - * Converts the given string into an array of lines. The lines - * don't contain any line delimiter characters. - * + * Converts the given string into an array of lines. The lines don't contain + * any line delimiter characters. + * * @return the string converted into an array of strings. Returns - * null if the input string can't be converted in an array of lines. + * null + * if the input string can't be converted in an array of lines. */ public static String[] convertIntoLines(String input) { try { - ILineTracker tracker= new DefaultLineTracker(); + ILineTracker tracker = new DefaultLineTracker(); tracker.set(input); - int size= tracker.getNumberOfLines(); - String result[]= new String[size]; - for (int i= 0; i < size; i++) { - IRegion region= tracker.getLineInformation(i); - int offset= region.getOffset(); - result[i]= input.substring(offset, offset + region.getLength()); + int size = tracker.getNumberOfLines(); + String result[] = new String[size]; + for (int i = 0; i < size; i++) { + IRegion region = tracker.getLineInformation(i); + int offset = region.getOffset(); + result[i] = input + .substring(offset, offset + region.getLength()); } return result; } catch (BadLocationException e) { @@ -82,36 +85,37 @@ public class Strings { } /** - * Returns true if the given string only consists of - * white spaces according to Java. If the string is empty, true - * is returned. + * Returns true if the given string only consists of white + * spaces according to Java. If the string is empty, true + * is + * returned. * - * @return true if the string only consists of white - * spaces; otherwise false is returned + * @return true if the string only consists of white spaces; + * otherwise false is returned * * @see java.lang.Character#isWhitespace(char) */ public static boolean containsOnlyWhitespaces(String s) { - int size= s.length(); - for (int i= 0; i < size; i++) { + int size = s.length(); + for (int i = 0; i < size; i++) { if (!Character.isWhitespace(s.charAt(i))) return false; } return true; } - + /** * Removes leading tabs and spaces from the given string. If the string - * doesn't contain any leading tabs or spaces then the string itself is + * doesn't contain any leading tabs or spaces then the string itself is * returned. */ public static String trimLeadingTabsAndSpaces(String line) { - int size= line.length(); - int start= size; - for (int i= 0; i < size; i++) { - char c= line.charAt(i); + int size = line.length(); + int start = size; + for (int i = 0; i < size; i++) { + char c = line.charAt(i); if (!isIndentChar(c)) { - start= i; + start = i; break; } } @@ -122,14 +126,14 @@ public class Strings { else return line.substring(start); } - + public static String trimTrailingTabsAndSpaces(String line) { - int size= line.length(); - int end= size; - for (int i= size - 1; i >= 0; i--) { - char c= line.charAt(i); + int size = line.length(); + int end = size; + for (int i = size - 1; i >= 0; i--) { + char c = line.charAt(i); if (isIndentChar(c)) { - end= i; + end = i; } else { break; } @@ -141,27 +145,29 @@ public class Strings { else return line.substring(0, end); } - + /** * Returns the indent of the given string. * - * @param line the text line - * @param tabWidth the width of the '\t' character. + * @param line + * the text line + * @param tabWidth + * the width of the '\t' character. */ public static int computeIndent(String line, int tabWidth) { - int result= 0; - int blanks= 0; - int size= line.length(); - for (int i= 0; i < size; i++) { - char c= line.charAt(i); + int result = 0; + int blanks = 0; + int size = line.length(); + for (int i = 0; i < size; i++) { + char c = line.charAt(i); if (c == '\t') { result++; - blanks= 0; + blanks = 0; } else if (isIndentChar(c)) { blanks++; if (blanks == tabWidth) { result++; - blanks= 0; + blanks = 0; } } else { return result; @@ -169,118 +175,122 @@ public class Strings { } return result; } - + /** - * Removes the given number of idents from the line. Asserts that the given line - * has the requested number of indents. If indentsToRemove <= 0 - * the line is returned. + * Removes the given number of idents from the line. Asserts that the given + * line has the requested number of indents. If + * indentsToRemove <= 0 the line is returned. */ - public static String trimIndent(String line, int indentsToRemove, int tabWidth) { + public static String trimIndent(String line, int indentsToRemove, + int tabWidth) { if (line == null || indentsToRemove <= 0) return line; - - int start= 0; - int indents= 0; - int blanks= 0; - int size= line.length(); - for (int i= 0; i < size; i++) { - char c= line.charAt(i); + + int start = 0; + int indents = 0; + int blanks = 0; + int size = line.length(); + for (int i = 0; i < size; i++) { + char c = line.charAt(i); if (c == '\t') { indents++; - blanks= 0; + blanks = 0; } else if (isIndentChar(c)) { - blanks++; - if (blanks == tabWidth) { - indents++; - blanks= 0; - } + blanks++; + if (blanks == tabWidth) { + indents++; + blanks = 0; + } } else { - // Assert.isTrue(false, "Line does not have requested number of indents"); //$NON-NLS-1$ - start= i + 1; - break; + // Assert.isTrue(false, "Line does not have requested number of + // indents"); //$NON-NLS-1$ + start = i + 1; + break; } if (indents == indentsToRemove) { - start= i + 1; + start = i + 1; break; - } + } } if (start == size) return ""; //$NON-NLS-1$ else return line.substring(start); } - + /** - * Removes all leading indents from the given line. If the line doesn't contain - * any indents the line itself is returned. + * Removes all leading indents from the given line. If the line doesn't + * contain any indents the line itself is returned. */ public static String trimIndents(String s, int tabWidth) { - int indent= computeIndent(s, tabWidth); + int indent = computeIndent(s, tabWidth); if (indent == 0) return s; return trimIndent(s, indent, tabWidth); } - + /** - * Removes the common number of indents from all lines. If a line - * only consists out of white space it is ignored. + * Removes the common number of indents from all lines. If a line only + * consists out of white space it is ignored. */ public static void trimIndentation(String[] lines, int tabWidth) { trimIndentation(lines, tabWidth, true); } - + /** - * Removes the common number of indents from all lines. If a line - * only consists out of white space it is ignored. If - * considerFirstLine is false the first line will be ignored. + * Removes the common number of indents from all lines. If a line only + * consists out of white space it is ignored. If + * considerFirstLine + * is false the first line will be ignored. */ - public static void trimIndentation(String[] lines, int tabWidth, boolean considerFirstLine) { - String[] toDo= new String[lines.length]; + public static void trimIndentation(String[] lines, int tabWidth, + boolean considerFirstLine) { + String[] toDo = new String[lines.length]; // find indentation common to all lines - int minIndent= Integer.MAX_VALUE; // very large - for (int i= considerFirstLine ? 0 : 1; i < lines.length; i++) { - String line= lines[i]; + int minIndent = Integer.MAX_VALUE; // very large + for (int i = considerFirstLine ? 0 : 1; i < lines.length; i++) { + String line = lines[i]; if (containsOnlyWhitespaces(line)) continue; - toDo[i]= line; - int indent= computeIndent(line, tabWidth); + toDo[i] = line; + int indent = computeIndent(line, tabWidth); if (indent < minIndent) { - minIndent= indent; + minIndent = indent; } } - + if (minIndent > 0) { // remove this indent from all lines - for (int i= considerFirstLine ? 0 : 1; i < toDo.length; i++) { - String s= toDo[i]; + for (int i = considerFirstLine ? 0 : 1; i < toDo.length; i++) { + String s = toDo[i]; if (s != null) - lines[i]= trimIndent(s, minIndent, tabWidth); + lines[i] = trimIndent(s, minIndent, tabWidth); else { - String line= lines[i]; - int indent= computeIndent(line, tabWidth); + String line = lines[i]; + int indent = computeIndent(line, tabWidth); if (indent > minIndent) - lines[i]= trimIndent(line, minIndent, tabWidth); + lines[i] = trimIndent(line, minIndent, tabWidth); else - lines[i]= trimLeadingTabsAndSpaces(line); + lines[i] = trimLeadingTabsAndSpaces(line); } } } } - + public static String getIndentString(String line, int tabWidth) { - int size= line.length(); - int end= 0; - int blanks= 0; - for (int i= 0; i < size; i++) { - char c= line.charAt(i); + int size = line.length(); + int end = 0; + int blanks = 0; + for (int i = 0; i < size; i++) { + char c = line.charAt(i); if (c == '\t') { - end= i + 1; - blanks= 0; + end = i + 1; + blanks = 0; } else if (isIndentChar(c)) { blanks++; if (blanks == tabWidth) { - end= i + 1; - blanks= 0; + end = i + 1; + blanks = 0; } } else { break; @@ -293,51 +303,54 @@ public class Strings { else return line.substring(0, end); } - + public static String[] removeTrailingEmptyLines(String[] sourceLines) { - int lastNonEmpty= findLastNonEmptyLineIndex(sourceLines); - String[] result= new String[lastNonEmpty + 1]; - for (int i= 0; i < result.length; i++) { - result[i]= sourceLines[i]; + int lastNonEmpty = findLastNonEmptyLineIndex(sourceLines); + String[] result = new String[lastNonEmpty + 1]; + for (int i = 0; i < result.length; i++) { + result[i] = sourceLines[i]; } return result; } private static int findLastNonEmptyLineIndex(String[] sourceLines) { - for (int i= sourceLines.length - 1; i >= 0; i--) { - if (! sourceLines[i].trim().equals(""))//$NON-NLS-1$ + for (int i = sourceLines.length - 1; i >= 0; i--) { + if (!sourceLines[i].trim().equals(""))//$NON-NLS-1$ return i; } return -1; } - + /** - * Change the indent of, possible muti-line, code range. The current indent is removed, a new indent added. - * The first line of the code will not be changed. (It is considered to have no indent as it might start in - * the middle of a line) + * Change the indent of, possible muti-line, code range. The current indent + * is removed, a new indent added. The first line of the code will not be + * changed. (It is considered to have no indent as it might start in the + * middle of a line) */ - public static String changeIndent(String code, int codeIndentLevel, int tabWidth, String newIndent, String lineDelim) { + public static String changeIndent(String code, int codeIndentLevel, + int tabWidth, String newIndent, String lineDelim) { try { - ILineTracker tracker= new DefaultLineTracker(); + ILineTracker tracker = new DefaultLineTracker(); tracker.set(code); - int nLines= tracker.getNumberOfLines(); + int nLines = tracker.getNumberOfLines(); if (nLines == 1) { return code; } - - StringBuffer buf= new StringBuffer(); - - for (int i= 0; i < nLines; i++) { - IRegion region= tracker.getLineInformation(i); - int start= region.getOffset(); - int end= start + region.getLength(); - String line= code.substring(start, end); - - if (i == 0) { // no indent for first line (contained in the formatted string) + + StringBuffer buf = new StringBuffer(); + + for (int i = 0; i < nLines; i++) { + IRegion region = tracker.getLineInformation(i); + int start = region.getOffset(); + int end = start + region.getLength(); + String line = code.substring(start, end); + + if (i == 0) { // no indent for first line (contained in the + // formatted string) buf.append(line); } else { // no new line after last line buf.append(lineDelim); - buf.append(newIndent); + buf.append(newIndent); buf.append(trimIndent(line, codeIndentLevel, tabWidth)); } } @@ -346,22 +359,22 @@ public class Strings { // can not happen return code; } - } - + } + /** - * Concatenate the given strings into one strings using the passed line delimiter as a - * delimiter. No delimiter is added to the last line. + * Concatenate the given strings into one strings using the passed line + * delimiter as a delimiter. No delimiter is added to the last line. */ public static String concatenate(String[] lines, String delimiter) { - StringBuffer buffer= new StringBuffer(); - for (int i= 0; i < lines.length; i++) { + StringBuffer buffer = new StringBuffer(); + for (int i = 0; i < lines.length; i++) { if (i > 0) buffer.append(delimiter); buffer.append(lines[i]); } return buffer.toString(); } - + public static boolean equals(String s, char[] c) { if (s.length() != c.length) return false; @@ -372,4 +385,3 @@ public class Strings { return true; } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/AbortFormatting.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/AbortFormatting.java index c92546d..b598ccc 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/AbortFormatting.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/AbortFormatting.java @@ -12,17 +12,18 @@ package net.sourceforge.phpdt.internal.formatter; /** * Unchecked exception wrapping invalid input checked exception which may occur - * when scanning original formatted source. + * when scanning original formatted source. * * @since 2.1 */ public class AbortFormatting extends RuntimeException { Throwable nestedException; - + public AbortFormatting(String message) { super(message); } + public AbortFormatting(Throwable nestedException) { super(nestedException.getMessage()); this.nestedException = nestedException; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/CodeFormatter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/CodeFormatter.java index f5d3ea3..986398f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/CodeFormatter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/CodeFormatter.java @@ -31,2530 +31,2790 @@ import net.sourceforge.phpdt.internal.formatter.impl.SplitLine; *

                                                      How to format a piece of code ?

                                                      *
                                                        *
                                                      • Create an instance of CodeFormatter - *
                                                      • Use the method void format(aString) on this instance to format aString. It will return the - * formatted string. + *
                                                      • Use the method void format(aString) on this instance to + * format aString. It will return the formatted string. *
                                                      */ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { - // IContentFormatterExtension { - public FormatterOptions options; + // IContentFormatterExtension { + public FormatterOptions options; - /** - * Represents a block in the constructions stack. - */ - public static final int BLOCK = ITerminalSymbols.TokenNameLBRACE; - - /** - * Represents a block following a control statement in the constructions stack. - */ - public static final int NONINDENT_BLOCK = -100; - - /** - * Contains the formatted output. - */ - StringBuffer formattedSource; - - /** - * Contains the current line.
                                                      - * Will be dumped at the next "newline" - */ - StringBuffer currentLineBuffer; - - /** - * Used during the formatting to get each token. - */ - Scanner scanner; - - /** - * Contains the tokens responsible for the current indentation level and the blocks not closed yet. - */ - private int[] constructions; - - /** - * Index in the constructions array. - */ - private int constructionsCount; - - /** - * Level of indentation of the current token (number of tab char put in front of it). - */ - private int indentationLevel; - - /** - * Regular level of indentation of all the lines - */ - private int initialIndentationLevel; - - /** - * Used to split a line. - */ - Scanner splitScanner; - - /** - * To remember the offset between the beginning of the line and the beginning of the comment. - */ - int currentCommentOffset; - - int currentLineIndentationLevel; - - int maxLineSize = 30; - - private boolean containsOpenCloseBraces; - - private int indentationLevelForOpenCloseBraces; - - /** - * Collections of positions to map - */ - private int[] positionsToMap; - - /** - * Collections of mapped positions - */ - private int[] mappedPositions; - - private int indexToMap; - - private int indexInMap; - - private int globalDelta; - - private int lineDelta; - - private int splitDelta; - - private int beginningOfLineIndex; - - private int multipleLineCommentCounter; - - /** - * Creates a new instance of Code Formatter using the given settings. - * - * @deprecated backport 1.0 internal functionality - */ - public CodeFormatter(ConfigurableOption[] settings) { - this(convertConfigurableOptions(settings)); - } - - /** - * Creates a new instance of Code Formatter using the FormattingOptions object given as argument - * - * @deprecated Use CodeFormatter(ConfigurableOption[]) instead - */ - public CodeFormatter() { - this((Map) null); - } - - /** - * Creates a new instance of Code Formatter using the given settings. - */ - public CodeFormatter(Map settings) { - // initialize internal state - constructionsCount = 0; - constructions = new int[10]; - currentLineIndentationLevel = indentationLevel = initialIndentationLevel; - currentCommentOffset = -1; - // initialize primary and secondary scanners - scanner = new Scanner(true /* comment */ - , true /* whitespace */ - , false /* nls */ - , false /* assert */ - , true, /* tokenizeStrings */ - null, null, true /*taskCaseSensitive*/); // regular scanner for forming lines - scanner.recordLineSeparator = true; - scanner.ignorePHPOneLiner = true; - // to remind of the position of the beginning of the line. - splitScanner = new Scanner(true /* comment */ - , true /* whitespace */ - , false /* nls */ - , false /* assert */ - , true, /* tokenizeStrings */ - null, null, true /*taskCaseSensitive*/); - splitScanner.ignorePHPOneLiner = true; - // secondary scanner to split long lines formed by primary scanning - // initialize current line buffer - currentLineBuffer = new StringBuffer(); - this.options = new FormatterOptions(settings); - } - - /** - * Returns true if a lineSeparator has to be inserted before operator false otherwise. - */ - private static boolean breakLineBeforeOperator(int operator) { - switch (operator) { - case TokenNameCOMMA: - case TokenNameSEMICOLON: - case TokenNameEQUAL: - return false; - default: - return true; - } - } - - /** - * @deprecated backport 1.0 internal functionality - */ - private static Map convertConfigurableOptions(ConfigurableOption[] settings) { - Hashtable options = new Hashtable(10); - for (int i = 0; i < settings.length; i++) { - if (settings[i].getComponentName().equals(CodeFormatter.class.getName())) { - String optionName = settings[i].getOptionName(); - int valueIndex = settings[i].getCurrentValueIndex(); - if (optionName.equals("newline.openingBrace")) { //$NON-NLS-1$ - options.put("net.sourceforge.phpdt.core.formatter.newline.openingBrace", valueIndex == 0 ? "insert" : "do not insert"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } else if (optionName.equals("newline.controlStatement")) { //$NON-NLS-1$ - options - .put("net.sourceforge.phpdt.core.formatter.newline.controlStatement", valueIndex == 0 ? "insert" : "do not insert"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } else if (optionName.equals("newline.clearAll")) { //$NON-NLS-1$ - options.put("net.sourceforge.phpdt.core.formatter.newline.clearAll", valueIndex == 0 ? "clear all" : "preserve one"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } else if (optionName.equals("newline.elseIf")) { //$NON-NLS-1$ - options.put("net.sourceforge.phpdt.core.formatter.newline.elseIf", valueIndex == 0 ? "do not insert" : "insert"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } else if (optionName.equals("newline.emptyBlock")) { //$NON-NLS-1$ - options.put("net.sourceforge.phpdt.core.formatter.newline.emptyBlock", valueIndex == 0 ? "insert" : "do not insert"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } else if (optionName.equals("lineSplit")) { //$NON-NLS-1$ - options.put("net.sourceforge.phpdt.core.formatter.lineSplit", String.valueOf(valueIndex)); //$NON-NLS-1$ //$NON-NLS-2$ - } else if (optionName.equals("style.assignment")) { //$NON-NLS-1$ - options.put("net.sourceforge.phpdt.core.formatter.style.assignment", valueIndex == 0 ? "compact" : "normal"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } else if (optionName.equals("tabulation.char")) { //$NON-NLS-1$ - options.put("net.sourceforge.phpdt.core.formatter.tabulation.char", valueIndex == 0 ? "tab" : "space"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } else if (optionName.equals("tabulation.size")) { //$NON-NLS-1$ - options.put("net.sourceforge.phpdt.core.formatter.tabulation.size", String.valueOf(valueIndex)); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - } - return options; - } - - /** - * Returns the end of the source code. - */ - private final String copyRemainingSource() { - char str[] = scanner.source; - int startPosition = scanner.startPosition; - int length = str.length - startPosition; - StringBuffer bufr = new StringBuffer(length); - if (startPosition < str.length) { - bufr.append(str, startPosition, length); - } - return (bufr.toString()); - } - - /** - * Inserts tabCount tab character or their equivalent number of spaces. - */ - private void dumpTab(int tabCount) { - if (options.indentWithTab) { - for (int j = 0; j < tabCount; j++) { - formattedSource.append('\t'); - increaseSplitDelta(1); - } - } else { - for (int i = 0, max = options.tabSize * tabCount; i < max; i++) { - formattedSource.append(' '); - increaseSplitDelta(1); - } - } - } - - /** - * Dumps currentLineBuffer into the formatted string. - */ - private void flushBuffer() { - String currentString = currentLineBuffer.toString(); - splitDelta = 0; - beginningOfLineIndex = formattedSource.length(); - if (containsOpenCloseBraces) { - containsOpenCloseBraces = false; - outputLine(currentString, false, indentationLevelForOpenCloseBraces, 0, -1, null, 0); - indentationLevelForOpenCloseBraces = currentLineIndentationLevel; - } else { - outputLine(currentString, false, currentLineIndentationLevel, 0, -1, null, 0); - } - int scannerSourceLength = scanner.source.length; - if ((scannerSourceLength > 2) && (scanner.startPosition < scannerSourceLength)) { - if (scanner.source[scannerSourceLength - 1] == '\n' && scanner.source[scannerSourceLength - 2] == '\r') { - formattedSource.append(options.lineSeparatorSequence); - increaseGlobalDelta(options.lineSeparatorSequence.length - 2); - } else if (scanner.source[scannerSourceLength - 1] == '\n') { - formattedSource.append(options.lineSeparatorSequence); - increaseGlobalDelta(options.lineSeparatorSequence.length - 1); - } else if (scanner.source[scannerSourceLength - 1] == '\r') { - formattedSource.append(options.lineSeparatorSequence); - increaseGlobalDelta(options.lineSeparatorSequence.length - 1); - } - } - updateMappedPositions(scanner.startPosition); - } - - /** - * Formats the input string. - */ - private void format() { - int token = 0; - int previousToken = 0; - int previousCompilableToken = 0; - int indentationOffset = 0; - int newLinesInWhitespace = 0; - // number of new lines in the previous whitespace token - // (used to leave blank lines before comments) - int pendingNewLines = 0; - boolean expectingOpenBrace = false; - boolean clearNonBlockIndents = false; - // true if all indentations till the 1st { (usefull after } or ;) - boolean pendingSpace = true; - boolean pendingNewlineAfterParen = false; - // true when a cr is to be put after a ) (in conditional statements) - boolean inAssignment = false; - boolean inArrayAssignment = false; - boolean inThrowsClause = false; - boolean inClassOrInterfaceHeader = false; - int dollarBraceCount = 0; - // openBracketCount is used to count the number of open brackets not closed - // yet. - int openBracketCount = 0; - int unarySignModifier = 0; - // openParenthesis[0] is used to count the parenthesis not belonging to a - // condition - // (eg foo();). parenthesis in for (...) are count elsewhere in the array. - int openParenthesisCount = 1; - int[] openParenthesis = new int[10]; - // tokenBeforeColon is used to know what token goes along with the current - // : - // it can be case or ? - int tokenBeforeColonCount = 0; - int[] tokenBeforeColon = new int[10]; - constructionsCount = 0; // initializes the constructions count. - // contains DO if in a DO..WHILE statement, UNITIALIZED otherwise. - int nlicsToken = 0; - // fix for 1FF17XY: LFCOM:ALL - Format problem on not matching } and else - boolean specialElse = false; - // OPTION (IndentationLevel): initial indentation level may be non-zero. - currentLineIndentationLevel += constructionsCount; - // An InvalidInputException exception might cause the termination of this - // loop. - int arrayDeclarationCount=0; - int[] arrayDeclarationParenthesis=new int[10]; - try { - while (true) { - // Get the next token. Catch invalid input and output it - // with minimal formatting, also catch end of input and - // exit the loop. - try { - token = scanner.getNextToken(); - if (Scanner.DEBUG) { - int currentEndPosition = scanner.getCurrentTokenEndPosition(); - int currentStartPosition = scanner.getCurrentTokenStartPosition(); - System.out.print(currentStartPosition + "," + currentEndPosition + ": "); - System.out.println(scanner.toStringAction(token)); - } - // Patch for line comment - // See PR http://dev.eclipse.org/bugs/show_bug.cgi?id=23096 - if (token == ITerminalSymbols.TokenNameCOMMENT_LINE) { - int length = scanner.currentPosition; - loop: for (int index = length - 1; index >= 0; index--) { - switch (scanner.source[index]) { - case '\r': - case '\n': - scanner.currentPosition--; - break; - default: - break loop; - } - } - } - } catch (InvalidInputException e) { - if (!handleInvalidToken(e)) { - throw e; - } - token = 0; - } - if (token == Scanner.TokenNameEOF) { - break; - } else if (token == Scanner.TokenNameHEREDOC) { - // no indentation for heredocs and HTML ! - outputCurrentTokenWithoutIndent(Scanner.TokenNameHEREDOC, 0); - continue; - } else if (token == Scanner.TokenNameINLINE_HTML) { - // no indentation for heredocs and HTML ! - int newLineCount = 1; - if (scanner.startPosition==0) { - newLineCount = 0; - } - outputCurrentTokenWithoutIndent(Scanner.TokenNameINLINE_HTML, newLineCount); - int srcLen = scanner.source.length; - if (scanner.currentPosition < srcLen-1) { - newLine(1); - } - continue; - } - /* - * ## MODIFYING the indentation level before generating new lines and indentation in the output string - */ - // Removes all the indentations made by statements not followed by a - // block - // except if the current token is ELSE, CATCH or if we are in a - // switch/case - if (clearNonBlockIndents && (token != Scanner.TokenNameWHITESPACE)) { - switch (token) { - case TokenNameelse: - if (constructionsCount > 0 && constructions[constructionsCount - 1] == TokenNameelse) { - pendingNewLines = 1; - specialElse = true; - } - indentationLevel += popInclusiveUntil(TokenNameif); - break; - // case TokenNamecatch : - // indentationLevel += popInclusiveUntil(TokenNamecatch); - // break; - // case TokenNamefinally : - // indentationLevel += popInclusiveUntil(TokenNamecatch); - // break; - case TokenNamewhile: - if (nlicsToken == TokenNamedo) { - indentationLevel += pop(TokenNamedo); - break; - } - default: - indentationLevel += popExclusiveUntilBlockOrCase(); - // clear until a CASE, DEFAULT or BLOCK is encountered. - // Thus, the indentationLevel is correctly cleared either - // in a switch/case statement or in any other situation. - } - clearNonBlockIndents = false; - } - // returns to the indentation level created by the SWITCH keyword - // if the current token is a CASE or a DEFAULT - if (token == TokenNamecase || token == TokenNamedefault) { - indentationLevel += pop(TokenNamecase); - } - // if (token == Scanner.TokenNamethrows) { - // inThrowsClause = true; - // } - if ((token == Scanner.TokenNameclass || token == Scanner.TokenNameinterface) && previousToken != Scanner.TokenNameDOT) { - inClassOrInterfaceHeader = true; - } - /* - * ## APPEND newlines and indentations to the output string - */ - // Do not add a new line between ELSE and IF, if the option - // elseIfOnSameLine is true. - // Fix for 1ETLWPZ: IVJCOM:ALL - incorrect "else if" formatting - // if (pendingNewlineAfterParen - // && previousCompilableToken == TokenNameelse - // && token == TokenNameif - // && options.compactElseIfMode) { - // pendingNewlineAfterParen = false; - // pendingNewLines = 0; - // indentationLevel += pop(TokenNameelse); - // // because else if is now one single statement, - // // the indentation level after it is increased by one and not by 2 - // // (else = 1 indent, if = 1 indent, but else if = 1 indent, not 2). - // } - // Add a newline & indent to the formatted source string if - // a for/if-else/while statement was scanned and there is no block - // following it. - pendingNewlineAfterParen = pendingNewlineAfterParen - || (previousCompilableToken == TokenNameRPAREN && token == TokenNameLBRACE); - if (pendingNewlineAfterParen && token != Scanner.TokenNameWHITESPACE) { - pendingNewlineAfterParen = false; - // Do to add a newline & indent sequence if the current token is an - // open brace or a period or if the current token is a semi-colon and - // the - // previous token is a close paren. - // add a new line if a parenthesis belonging to a for() statement - // has been closed and the current token is not an opening brace - if (token != TokenNameLBRACE && !isComment(token) - // to avoid adding new line between else and a comment - && token != TokenNameDOT && !(previousCompilableToken == TokenNameRPAREN && token == TokenNameSEMICOLON)) { - newLine(1); - currentLineIndentationLevel = indentationLevel; - pendingNewLines = 0; - pendingSpace = false; - } else { - if (token == TokenNameLBRACE && options.newLineBeforeOpeningBraceMode) { - newLine(1); - if (constructionsCount > 0 && constructions[constructionsCount - 1] != BLOCK - && constructions[constructionsCount - 1] != NONINDENT_BLOCK) { - currentLineIndentationLevel = indentationLevel - 1; - } else { - currentLineIndentationLevel = indentationLevel; - } - pendingNewLines = 0; - pendingSpace = false; - } - } - } - if (token == TokenNameLBRACE && options.newLineBeforeOpeningBraceMode && constructionsCount > 0 - && constructions[constructionsCount - 1] == TokenNamedo) { - newLine(1); - currentLineIndentationLevel = indentationLevel - 1; - pendingNewLines = 0; - pendingSpace = false; - } - // see PR 1G5G8EC - if (token == TokenNameLBRACE && inThrowsClause) { - inThrowsClause = false; - if (options.newLineBeforeOpeningBraceMode) { - newLine(1); - currentLineIndentationLevel = indentationLevel; - pendingNewLines = 0; - pendingSpace = false; - } - } - // see PR 1G5G82G - if (token == TokenNameLBRACE && inClassOrInterfaceHeader) { - inClassOrInterfaceHeader = false; - if (options.newLineBeforeOpeningBraceMode) { - newLine(1); - currentLineIndentationLevel = indentationLevel; - pendingNewLines = 0; - pendingSpace = false; - } - } - // don't linebreak empty array declarations - if (token == TokenNameRPAREN && arrayDeclarationCount > 0) { - if (previousCompilableToken == TokenNameLPAREN) { - pendingNewLines = 0; - } - } - // Add pending new lines to the formatted source string. - // Note: pending new lines are not added if the current token - // is a single line comment or whitespace. - // if the comment is between parenthesis, there is no blank line - // preservation - // (if it's a one-line comment, a blank line is added after it). - if (( - (pendingNewLines > 0 && (!isComment(token))) - || (newLinesInWhitespace > 0 && (openParenthesisCount <= 1 && isComment(token))) - || (previousCompilableToken == TokenNameLBRACE && token == TokenNameRBRACE) - || (newLinesInWhitespace > 0 && previousCompilableToken == TokenNameDOT) - ) - && token != Scanner.TokenNameWHITESPACE) { - // Do not add newline & indent between an adjoining close brace and - // close paren. Anonymous inner classes may use this form. - boolean closeBraceAndCloseParen = previousToken == TokenNameRBRACE && token == TokenNameRPAREN; - // OPTION (NewLineInCompoundStatement): do not add newline & indent - // between close brace and else, (do) while, catch, and finally if - // newlineInCompoundStatement is true. - boolean nlicsOption = previousToken == TokenNameRBRACE - && !options.newlineInControlStatementMode - && (token == TokenNameelse || (token == TokenNamewhile && nlicsToken == TokenNamedo) || token == TokenNamecatch || token == TokenNamefinally); - // Do not add a newline & indent between a close brace and - // semi-colon. - boolean semiColonAndCloseBrace = previousToken == TokenNameRBRACE && token == TokenNameSEMICOLON; - // Do not add a new line & indent between a multiline comment and a - // opening brace - boolean commentAndOpenBrace = previousToken == Scanner.TokenNameCOMMENT_BLOCK && token == TokenNameLBRACE; - // Do not add a newline & indent between a close brace and a colon - // (in array assignments, for example). - boolean commaAndCloseBrace = previousToken == TokenNameRBRACE && token == TokenNameCOMMA; - // Add a newline and indent, if appropriate. - if (specialElse - || (!commentAndOpenBrace && !closeBraceAndCloseParen && !nlicsOption && !semiColonAndCloseBrace && !commaAndCloseBrace)) { - // if clearAllBlankLinesMode=false, leaves the blank lines - // inserted by the user - // if clearAllBlankLinesMode=true, removes all of then - // and insert only blank lines required by the formatting. - if (!options.clearAllBlankLinesMode) { - // (isComment(token)) - pendingNewLines = (pendingNewLines < newLinesInWhitespace) ? newLinesInWhitespace : pendingNewLines; - pendingNewLines = (pendingNewLines > 2) ? 2 : pendingNewLines; - } - if (previousCompilableToken == TokenNameLBRACE && token == TokenNameRBRACE) { - containsOpenCloseBraces = true; - indentationLevelForOpenCloseBraces = currentLineIndentationLevel; - if (isComment(previousToken)) { - newLine(pendingNewLines); - } else { - /* - * if (!(constructionsCount > 1 && constructions[constructionsCount-1] == NONINDENT_BLOCK && - * (constructions[constructionsCount-2] == TokenNamefor - */ - if (options.newLineInEmptyBlockMode) { - if (inArrayAssignment) { - newLine(1); // array assigment with an empty block - } else { - newLine(pendingNewLines); - } - } - // } - } - } else { - // see PR 1FKKC3U: LFCOM:WINNT - Format problem with a comment - // before the ';' - if (!((previousToken == Scanner.TokenNameCOMMENT_BLOCK || previousToken == Scanner.TokenNameCOMMENT_PHPDOC) && token == TokenNameSEMICOLON)) { - newLine(pendingNewLines); - } - } - if (((previousCompilableToken == TokenNameSEMICOLON) || (previousCompilableToken == TokenNameLBRACE) - || (previousCompilableToken == TokenNameRBRACE) || (isComment(previousToken))) - && (token == TokenNameRBRACE)) { - indentationOffset = -1; - indentationLevel += popExclusiveUntilBlock(); - } - if (previousToken == Scanner.TokenNameCOMMENT_LINE && inAssignment) { - // PR 1FI5IPO - currentLineIndentationLevel++; - } else { - currentLineIndentationLevel = indentationLevel + indentationOffset; - } - pendingSpace = false; - indentationOffset = 0; - } - pendingNewLines = 0; - newLinesInWhitespace = 0; - specialElse = false; - if (nlicsToken == TokenNamedo && token == TokenNamewhile) { - nlicsToken = 0; - } - } - boolean phpTagAndWhitespace = previousToken == TokenNameINLINE_HTML && token == TokenNameWHITESPACE; - switch (token) { - // case TokenNameDOLLAR : - // dollarBraceCount++; - // break; - case TokenNameelse: - // case TokenNamefinally : - expectingOpenBrace = true; - pendingNewlineAfterParen = true; - indentationLevel += pushControlStatement(token); - break; - case TokenNamecase: - case TokenNamedefault: - if (tokenBeforeColonCount == tokenBeforeColon.length) { - System - .arraycopy(tokenBeforeColon, 0, (tokenBeforeColon = new int[tokenBeforeColonCount * 2]), 0, tokenBeforeColonCount); - } - tokenBeforeColon[tokenBeforeColonCount++] = TokenNamecase; - indentationLevel += pushControlStatement(TokenNamecase); - break; - case TokenNameQUESTION: - if (tokenBeforeColonCount == tokenBeforeColon.length) { - System - .arraycopy(tokenBeforeColon, 0, (tokenBeforeColon = new int[tokenBeforeColonCount * 2]), 0, tokenBeforeColonCount); - } - tokenBeforeColon[tokenBeforeColonCount++] = token; - break; - case TokenNameswitch: - case TokenNamefor: - case TokenNameforeach: - case TokenNameif: - case TokenNamewhile: - if (openParenthesisCount == openParenthesis.length) { - System.arraycopy(openParenthesis, 0, (openParenthesis = new int[openParenthesisCount * 2]), 0, openParenthesisCount); - } - openParenthesis[openParenthesisCount++] = 0; - expectingOpenBrace = true; - indentationLevel += pushControlStatement(token); - break; - case TokenNametry: - pendingNewlineAfterParen = true; - case TokenNamecatch: - // several CATCH statements can be contiguous. - // a CATCH is encountered pop until first CATCH (if a CATCH - // follows a TRY it works the same way, - // as CATCH and TRY are the same token in the stack). - expectingOpenBrace = true; - indentationLevel += pushControlStatement(TokenNamecatch); - break; - case TokenNamedo: - expectingOpenBrace = true; - indentationLevel += pushControlStatement(token); - nlicsToken = token; - break; - case TokenNamenew: - break; - case TokenNameLPAREN: - // if (previousToken == TokenNamesynchronized) { - // indentationLevel += pushControlStatement(previousToken); - // } else { - // Put a space between the previous and current token if the - // previous token was not a keyword, open paren, logical - // compliment (eg: !), semi-colon, open brace, close brace, - // super, or this. - if (previousCompilableToken != TokenNameLBRACKET && previousToken != TokenNameIdentifier && previousToken != 0 - && previousToken != TokenNameNOT && previousToken != TokenNameLPAREN && previousToken != TokenNameTWIDDLE - && previousToken != TokenNameSEMICOLON && previousToken != TokenNameLBRACE && previousToken != TokenNameRBRACE - && previousToken != TokenNamesuper) { - // && previousToken != TokenNamethis) { - space(); - } - // If in a for/if/while statement, increase the parenthesis count - // for the current openParenthesisCount - // else increase the count for stand alone parenthesis. - if (openParenthesisCount > 0) - openParenthesis[openParenthesisCount - 1]++; - else - openParenthesis[0]++; - pendingSpace = false; - // recognize array declaration for nice output - if (previousCompilableToken == TokenNamearray) { - arrayDeclarationCount++; - arrayDeclarationParenthesis[arrayDeclarationCount]=openParenthesis[openParenthesisCount]; - indentationLevel++; - pendingNewLines=1; - } - //S } - break; - case TokenNameRPAREN: - // check for closing array declaration - if (arrayDeclarationCount>0) { - if (arrayDeclarationParenthesis[arrayDeclarationCount]==openParenthesis[openParenthesisCount]) { - if (previousCompilableToken != TokenNameLPAREN) { - newLine(1); - } - indentationLevel--; - currentLineIndentationLevel = indentationLevel; - pendingNewLines = 0; - arrayDeclarationCount--; - } - } - // Decrease the parenthesis count - // if there is no more unclosed parenthesis, - // a new line and indent may be append (depending on the next - // token). - if ((openParenthesisCount > 1) && (openParenthesis[openParenthesisCount - 1] > 0)) { - openParenthesis[openParenthesisCount - 1]--; - if (openParenthesis[openParenthesisCount - 1] <= 0) { - pendingNewlineAfterParen = true; - inAssignment = false; - openParenthesisCount--; - } - } else { - openParenthesis[0]--; - } - pendingSpace = false; - break; - case TokenNameLBRACE: - if (previousCompilableToken == TokenNameDOLLAR) { - dollarBraceCount++; - } else { - if ((previousCompilableToken == TokenNameRBRACKET) || (previousCompilableToken == TokenNameEQUAL)) { - // if (previousCompilableToken == TokenNameRBRACKET) { - inArrayAssignment = true; - inAssignment = false; - } - if (inArrayAssignment) { - indentationLevel += pushBlock(); - } else { - // Add new line and increase indentation level after open brace. - pendingNewLines = 1; - indentationLevel += pushBlock(); - inAssignment = false; - } - } - break; - case TokenNameRBRACE: - if (dollarBraceCount > 0) { - dollarBraceCount--; - break; - } - if (previousCompilableToken == TokenNameRPAREN) { - pendingSpace = false; - } - if (inArrayAssignment) { - inArrayAssignment = false; - pendingNewLines = 1; - indentationLevel += popInclusiveUntilBlock(); - } else { - pendingNewLines = 1; - indentationLevel += popInclusiveUntilBlock(); - if (previousCompilableToken == TokenNameRPAREN) { - // fix for 1FGDDV6: LFCOM:WIN98 - Weird splitting on message - // expression - currentLineBuffer.append(options.lineSeparatorSequence); - increaseLineDelta(options.lineSeparatorSequence.length); - } - if (constructionsCount > 0) { - switch (constructions[constructionsCount - 1]) { - case TokenNamefor: - case TokenNameforeach: - //indentationLevel += popExclusiveUntilBlock(); - //break; - case TokenNameswitch: - case TokenNameif: - case TokenNameelse: - case TokenNametry: - case TokenNamecatch: - case TokenNamefinally: - case TokenNamewhile: - case TokenNamedo: - // case TokenNamesynchronized : - clearNonBlockIndents = true; - default: - break; - } - } - } - break; - case TokenNameLBRACKET: - openBracketCount++; - pendingSpace = false; - break; - case TokenNameRBRACKET: - openBracketCount -= (openBracketCount > 0) ? 1 : 0; - // if there is no left bracket to close, the right bracket is - // ignored. - pendingSpace = false; - break; - case TokenNameCOMMA: - pendingSpace = false; - if (arrayDeclarationCount>0) { - pendingNewLines=1; - } - break; - case TokenNameDOT: - space(); - pendingSpace = false; - break; - case TokenNameSEMICOLON: - // Do not generate line terminators in the definition of - // the for statement. - // if not in this case, jump a line and reduce indentation after - // the brace - // if the block it closes belongs to a conditional statement (if, - // while, do...). - if (openParenthesisCount <= 1) { - pendingNewLines = 1; - if (expectingOpenBrace) { - clearNonBlockIndents = true; - expectingOpenBrace = false; - } - } - inAssignment = false; - pendingSpace = false; - break; - case TokenNamePLUS_PLUS: - case TokenNameMINUS_MINUS: - // Do not put a space between a post-increment/decrement - // and the identifier being modified. - if (previousToken == TokenNameIdentifier || previousToken == TokenNameRBRACKET || previousToken == TokenNameVariable) { - pendingSpace = false; - } - break; - case TokenNamePLUS: - // previously ADDITION - case TokenNameMINUS: - // Handle the unary operators plus and minus via a flag - if (!isLiteralToken(previousToken) && previousToken != TokenNameIdentifier && previousToken != TokenNameRPAREN - && previousToken != TokenNameRBRACKET) { - unarySignModifier = 1; - } - break; - case TokenNameCOLON: - // In a switch/case statement, add a newline & indent - // when a colon is encountered. - if (tokenBeforeColonCount > 0) { - if (tokenBeforeColon[tokenBeforeColonCount - 1] == TokenNamecase) { - pendingNewLines = 1; - } - tokenBeforeColonCount--; - } - break; - case TokenNameEQUAL: - inAssignment = true; - break; - case Scanner.TokenNameCOMMENT_LINE: - pendingNewLines = 1; - if (inAssignment) { - currentLineIndentationLevel++; - } - break; // a line is always inserted after a one-line comment - case Scanner.TokenNameCOMMENT_PHPDOC: - case Scanner.TokenNameCOMMENT_BLOCK: - currentCommentOffset = getCurrentCommentOffset(); - pendingNewLines = 1; - break; - case Scanner.TokenNameWHITESPACE: - if (!phpTagAndWhitespace) { - // Count the number of line terminators in the whitespace so - // line spacing can be preserved near comments. - char[] source = scanner.source; - newLinesInWhitespace = 0; - for (int i = scanner.startPosition, max = scanner.currentPosition; i < max; i++) { - if (source[i] == '\r') { - if (i < max - 1) { - if (source[++i] == '\n') { - newLinesInWhitespace++; - } else { - newLinesInWhitespace++; - } - } else { - newLinesInWhitespace++; - } - } else if (source[i] == '\n') { - newLinesInWhitespace++; - } - } - increaseLineDelta(scanner.startPosition - scanner.currentPosition); - break; - } - // case TokenNameHTML : - // // Add the next token to the formatted source string. - // // outputCurrentToken(token); - // int startPosition = scanner.startPosition; - // flushBuffer(); - // for (int i = startPosition, max = scanner.currentPosition; i < - // max; i++) { - // char currentCharacter = scanner.source[i]; - // updateMappedPositions(i); - // currentLineBuffer.append(currentCharacter); - // } - // break; - default: - if ((token == TokenNameIdentifier) || isLiteralToken(token) || token == TokenNamesuper) { - // || token == TokenNamethis) { - // Do not put a space between a unary operator - // (eg: ++, --, +, -) and the identifier being modified. - if (previousToken == TokenNamePLUS_PLUS || previousToken == TokenNameMINUS_MINUS - || (previousToken == TokenNameMINUS_GREATER && options.compactDereferencingMode) // -> - || (previousToken == TokenNamePLUS && unarySignModifier > 0) - || (previousToken == TokenNameMINUS && unarySignModifier > 0)) { - pendingSpace = false; - } - unarySignModifier = 0; - } - break; - } - // Do not output whitespace tokens. - if (token != Scanner.TokenNameWHITESPACE || phpTagAndWhitespace) { - /* - * Add pending space to the formatted source string. Do not output a space under the following circumstances: 1) this is - * the first pass 2) previous token is an open paren 3) previous token is a period 4) previous token is the logical - * compliment (eg: !) 5) previous token is the bitwise compliment (eg: ~) 6) previous token is the open bracket (eg: [) 7) - * in an assignment statement, if the previous token is an open brace or the current token is a close brace 8) previous - * token is a single line comment 9) current token is a '->' - */ - if (token == TokenNameMINUS_GREATER && options.compactDereferencingMode) - pendingSpace = false; - - boolean openAndCloseBrace = previousCompilableToken == TokenNameLBRACE && token == TokenNameRBRACE; - if (pendingSpace && insertSpaceAfter(previousToken) - && !(inAssignment && (previousToken == TokenNameLBRACE || token == TokenNameRBRACE)) - && previousToken != Scanner.TokenNameCOMMENT_LINE) { - if ((!(options.compactAssignmentMode && token == TokenNameEQUAL)) && !openAndCloseBrace) - space(); - } - // Add the next token to the formatted source string. - outputCurrentToken(token); - if (token == Scanner.TokenNameCOMMENT_LINE && openParenthesisCount > 1) { - pendingNewLines = 0; - currentLineBuffer.append(options.lineSeparatorSequence); - increaseLineDelta(options.lineSeparatorSequence.length); - } - pendingSpace = true; - } - // Whitespace tokens do not need to be remembered. - if (token != Scanner.TokenNameWHITESPACE || phpTagAndWhitespace) { - previousToken = token; - if (token != Scanner.TokenNameCOMMENT_BLOCK && token != Scanner.TokenNameCOMMENT_LINE - && token != Scanner.TokenNameCOMMENT_PHPDOC) { - previousCompilableToken = token; - } - } - } - output(copyRemainingSource()); - flushBuffer(); - // dump the last token of the source in the formatted output. - } catch (InvalidInputException e) { - output(copyRemainingSource()); - flushBuffer(); - // dump the last token of the source in the formatted output. - } - } - - /** - * Formats the char array sourceString, and returns a string containing the formatted version. - * - * @return the formatted ouput. - */ - public String formatSourceString(String sourceString) { - char[] sourceChars = sourceString.toCharArray(); - formattedSource = new StringBuffer(sourceChars.length); - scanner.setSource(sourceChars); - format(); - return formattedSource.toString(); - } - - /** - * Formats the char array sourceString, and returns a string containing the formatted version. - * - * @param string - * the string to format - * @param indentationLevel - * the initial indentation level - * @return the formatted ouput. - */ - public String format(String string, int indentationLevel) { - return format(string, indentationLevel, (int[]) null); - } - - /** - * Formats the char array sourceString, and returns a string containing the formatted version. The positions array - * is modified to contain the mapped positions. - * - * @param string - * the string to format - * @param indentationLevel - * the initial indentation level - * @param positions - * the array of positions to map - * @return the formatted ouput. - */ - public String format(String string, int indentationLevel, int[] positions) { - return this.format(string, indentationLevel, positions, null); - } - - public String format(String string, int indentationLevel, int[] positions, String lineSeparator) { - if (lineSeparator != null) { - this.options.setLineSeparator(lineSeparator); - } - if (positions != null) { - this.setPositionsToMap(positions); - this.setInitialIndentationLevel(indentationLevel); - String formattedString = this.formatSourceString(string); - int[] mappedPositions = this.getMappedPositions(); - System.arraycopy(mappedPositions, 0, positions, 0, positions.length); - return formattedString; - } else { - this.setInitialIndentationLevel(indentationLevel); - return this.formatSourceString(string); - } - } - - /** - * Formats the char array sourceString, and returns a string containing the formatted version. The initial - * indentation level is 0. - * - * @param string - * the string to format - * @return the formatted ouput. - */ - public String format(String string) { - return this.format(string, 0, (int[]) null); - } - - /** - * Formats a given source string, starting indenting it at a particular depth and using the given options - * - * @deprecated backport 1.0 internal functionality - */ - public static String format(String sourceString, int initialIndentationLevel, ConfigurableOption[] options) { - CodeFormatter formatter = new CodeFormatter(options); - formatter.setInitialIndentationLevel(initialIndentationLevel); - return formatter.formatSourceString(sourceString); - } - - /** - * Returns the number of characters and tab char between the beginning of the line and the beginning of the comment. - */ - private int getCurrentCommentOffset() { - int linePtr = scanner.linePtr; - // if there is no beginning of line, return 0. - if (linePtr < 0) - return 0; - int offset = 0; - int beginningOfLine = scanner.lineEnds[linePtr]; - int currentStartPosition = scanner.startPosition; - char[] source = scanner.source; - // find the position of the beginning of the line containing the comment - while (beginningOfLine > currentStartPosition) { - if (linePtr > 0) { - beginningOfLine = scanner.lineEnds[--linePtr]; - } else { - beginningOfLine = 0; - break; - } - } - for (int i = currentStartPosition - 1; i >= beginningOfLine; i--) { - char currentCharacter = source[i]; - switch (currentCharacter) { - case '\t': - offset += options.tabSize; - break; - case ' ': - offset++; - break; - case '\r': - case '\n': - break; - default: - return offset; - } - } - return offset; - } - - /** - * Returns an array of descriptions for the configurable options. The descriptions may be changed and passed back to a different - * compiler. - * - * @deprecated backport 1.0 internal functionality - */ - public static ConfigurableOption[] getDefaultOptions(Locale locale) { - String componentName = CodeFormatter.class.getName(); - FormatterOptions options = new FormatterOptions(); - return new ConfigurableOption[] { - new ConfigurableOption(componentName, "newline.openingBrace", locale, options.newLineBeforeOpeningBraceMode ? 0 : 1), - //$NON-NLS-1$ - new ConfigurableOption(componentName, "newline.controlStatement", locale, options.newlineInControlStatementMode ? 0 : 1), - //$NON-NLS-1$ - new ConfigurableOption(componentName, "newline.clearAll", locale, options.clearAllBlankLinesMode ? 0 : 1), - //$NON-NLS-1$ - // new ConfigurableOption(componentName, "newline.elseIf", locale, - // options.compactElseIfMode ? 0 : 1), //$NON-NLS-1$ - new ConfigurableOption(componentName, "newline.emptyBlock", locale, options.newLineInEmptyBlockMode ? 0 : 1), - //$NON-NLS-1$ - new ConfigurableOption(componentName, "line.split", locale, options.maxLineLength), - //$NON-NLS-1$ - new ConfigurableOption(componentName, "style.compactAssignment", locale, options.compactAssignmentMode ? 0 : 1), - //$NON-NLS-1$ - new ConfigurableOption(componentName, "tabulation.char", locale, options.indentWithTab ? 0 : 1), - //$NON-NLS-1$ - new ConfigurableOption(componentName, "tabulation.size", locale, options.tabSize) //$NON-NLS-1$ - }; - } - - /** - * Returns the array of mapped positions. Returns null is no positions have been set. - * - * @return int[] - * @deprecated There is no need to retrieve the mapped positions anymore. - */ - public int[] getMappedPositions() { - if (null!=mappedPositions) { - for (int i=0;i=formattedSource.length()) { - mappedPositions[i]=formattedSource.length()-1; + /** + * Represents a block in the constructions stack. + */ + public static final int BLOCK = ITerminalSymbols.TokenNameLBRACE; + + /** + * Represents a block following a control statement in the + * constructions stack. + */ + public static final int NONINDENT_BLOCK = -100; + + /** + * Contains the formatted output. + */ + StringBuffer formattedSource; + + /** + * Contains the current line.
                                                      + * Will be dumped at the next "newline" + */ + StringBuffer currentLineBuffer; + + /** + * Used during the formatting to get each token. + */ + Scanner scanner; + + /** + * Contains the tokens responsible for the current indentation level and the + * blocks not closed yet. + */ + private int[] constructions; + + /** + * Index in the constructions array. + */ + private int constructionsCount; + + /** + * Level of indentation of the current token (number of tab char put in + * front of it). + */ + private int indentationLevel; + + /** + * Regular level of indentation of all the lines + */ + private int initialIndentationLevel; + + /** + * Used to split a line. + */ + Scanner splitScanner; + + /** + * To remember the offset between the beginning of the line and the + * beginning of the comment. + */ + int currentCommentOffset; + + int currentLineIndentationLevel; + + int maxLineSize = 30; + + private boolean containsOpenCloseBraces; + + private int indentationLevelForOpenCloseBraces; + + /** + * Collections of positions to map + */ + private int[] positionsToMap; + + /** + * Collections of mapped positions + */ + private int[] mappedPositions; + + private int indexToMap; + + private int indexInMap; + + private int globalDelta; + + private int lineDelta; + + private int splitDelta; + + private int beginningOfLineIndex; + + private int multipleLineCommentCounter; + + /** + * Creates a new instance of Code Formatter using the given settings. + * + * @deprecated backport 1.0 internal functionality + */ + public CodeFormatter(ConfigurableOption[] settings) { + this(convertConfigurableOptions(settings)); + } + + /** + * Creates a new instance of Code Formatter using the FormattingOptions + * object given as argument + * + * @deprecated Use CodeFormatter(ConfigurableOption[]) instead + */ + public CodeFormatter() { + this((Map) null); + } + + /** + * Creates a new instance of Code Formatter using the given settings. + */ + public CodeFormatter(Map settings) { + // initialize internal state + constructionsCount = 0; + constructions = new int[10]; + currentLineIndentationLevel = indentationLevel = initialIndentationLevel; + currentCommentOffset = -1; + // initialize primary and secondary scanners + scanner = new Scanner(true /* comment */ + , true /* whitespace */ + , false /* nls */ + , false /* assert */ + , true, /* tokenizeStrings */ + null, null, true /* taskCaseSensitive */); // regular scanner for + // forming lines + scanner.recordLineSeparator = true; + scanner.ignorePHPOneLiner = true; + // to remind of the position of the beginning of the line. + splitScanner = new Scanner(true /* comment */ + , true /* whitespace */ + , false /* nls */ + , false /* assert */ + , true, /* tokenizeStrings */ + null, null, true /* taskCaseSensitive */); + splitScanner.ignorePHPOneLiner = true; + // secondary scanner to split long lines formed by primary scanning + // initialize current line buffer + currentLineBuffer = new StringBuffer(); + this.options = new FormatterOptions(settings); + } + + /** + * Returns true if a lineSeparator has to be inserted before + * operator false otherwise. + */ + private static boolean breakLineBeforeOperator(int operator) { + switch (operator) { + case TokenNameCOMMA: + case TokenNameSEMICOLON: + case TokenNameEQUAL: + return false; + default: + return true; + } + } + + /** + * @deprecated backport 1.0 internal functionality + */ + private static Map convertConfigurableOptions(ConfigurableOption[] settings) { + Hashtable options = new Hashtable(10); + for (int i = 0; i < settings.length; i++) { + if (settings[i].getComponentName().equals( + CodeFormatter.class.getName())) { + String optionName = settings[i].getOptionName(); + int valueIndex = settings[i].getCurrentValueIndex(); + if (optionName.equals("newline.openingBrace")) { //$NON-NLS-1$ + options + .put( + "net.sourceforge.phpdt.core.formatter.newline.openingBrace", valueIndex == 0 ? "insert" : "do not insert"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } else if (optionName.equals("newline.controlStatement")) { //$NON-NLS-1$ + options + .put( + "net.sourceforge.phpdt.core.formatter.newline.controlStatement", valueIndex == 0 ? "insert" : "do not insert"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } else if (optionName.equals("newline.clearAll")) { //$NON-NLS-1$ + options + .put( + "net.sourceforge.phpdt.core.formatter.newline.clearAll", valueIndex == 0 ? "clear all" : "preserve one"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } else if (optionName.equals("newline.elseIf")) { //$NON-NLS-1$ + options + .put( + "net.sourceforge.phpdt.core.formatter.newline.elseIf", valueIndex == 0 ? "do not insert" : "insert"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } else if (optionName.equals("newline.emptyBlock")) { //$NON-NLS-1$ + options + .put( + "net.sourceforge.phpdt.core.formatter.newline.emptyBlock", valueIndex == 0 ? "insert" : "do not insert"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } else if (optionName.equals("lineSplit")) { //$NON-NLS-1$ + options + .put( + "net.sourceforge.phpdt.core.formatter.lineSplit", String.valueOf(valueIndex)); //$NON-NLS-1$ //$NON-NLS-2$ + } else if (optionName.equals("style.assignment")) { //$NON-NLS-1$ + options + .put( + "net.sourceforge.phpdt.core.formatter.style.assignment", valueIndex == 0 ? "compact" : "normal"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } else if (optionName.equals("tabulation.char")) { //$NON-NLS-1$ + options + .put( + "net.sourceforge.phpdt.core.formatter.tabulation.char", valueIndex == 0 ? "tab" : "space"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } else if (optionName.equals("tabulation.size")) { //$NON-NLS-1$ + options + .put( + "net.sourceforge.phpdt.core.formatter.tabulation.size", String.valueOf(valueIndex)); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + } + return options; + } + + /** + * Returns the end of the source code. + */ + private final String copyRemainingSource() { + char str[] = scanner.source; + int startPosition = scanner.startPosition; + int length = str.length - startPosition; + StringBuffer bufr = new StringBuffer(length); + if (startPosition < str.length) { + bufr.append(str, startPosition, length); + } + return (bufr.toString()); + } + + /** + * Inserts tabCount tab character or their equivalent number + * of spaces. + */ + private void dumpTab(int tabCount) { + if (options.indentWithTab) { + for (int j = 0; j < tabCount; j++) { + formattedSource.append('\t'); + increaseSplitDelta(1); + } + } else { + for (int i = 0, max = options.tabSize * tabCount; i < max; i++) { + formattedSource.append(' '); + increaseSplitDelta(1); + } + } + } + + /** + * Dumps currentLineBuffer into the formatted string. + */ + private void flushBuffer() { + String currentString = currentLineBuffer.toString(); + splitDelta = 0; + beginningOfLineIndex = formattedSource.length(); + if (containsOpenCloseBraces) { + containsOpenCloseBraces = false; + outputLine(currentString, false, + indentationLevelForOpenCloseBraces, 0, -1, null, 0); + indentationLevelForOpenCloseBraces = currentLineIndentationLevel; + } else { + outputLine(currentString, false, currentLineIndentationLevel, 0, + -1, null, 0); + } + int scannerSourceLength = scanner.source.length; + if ((scannerSourceLength > 2) + && (scanner.startPosition < scannerSourceLength)) { + if (scanner.source[scannerSourceLength - 1] == '\n' + && scanner.source[scannerSourceLength - 2] == '\r') { + formattedSource.append(options.lineSeparatorSequence); + increaseGlobalDelta(options.lineSeparatorSequence.length - 2); + } else if (scanner.source[scannerSourceLength - 1] == '\n') { + formattedSource.append(options.lineSeparatorSequence); + increaseGlobalDelta(options.lineSeparatorSequence.length - 1); + } else if (scanner.source[scannerSourceLength - 1] == '\r') { + formattedSource.append(options.lineSeparatorSequence); + increaseGlobalDelta(options.lineSeparatorSequence.length - 1); + } + } + updateMappedPositions(scanner.startPosition); + } + + /** + * Formats the input string. + */ + private void format() { + int token = 0; + int previousToken = 0; + int previousCompilableToken = 0; + int indentationOffset = 0; + int newLinesInWhitespace = 0; + // number of new lines in the previous whitespace token + // (used to leave blank lines before comments) + int pendingNewLines = 0; + boolean expectingOpenBrace = false; + boolean clearNonBlockIndents = false; + // true if all indentations till the 1st { (usefull after } or ;) + boolean pendingSpace = true; + boolean pendingNewlineAfterParen = false; + // true when a cr is to be put after a ) (in conditional statements) + boolean inAssignment = false; + boolean inArrayAssignment = false; + boolean inThrowsClause = false; + boolean inClassOrInterfaceHeader = false; + int dollarBraceCount = 0; + // openBracketCount is used to count the number of open brackets not + // closed + // yet. + int openBracketCount = 0; + int unarySignModifier = 0; + // openParenthesis[0] is used to count the parenthesis not belonging to + // a + // condition + // (eg foo();). parenthesis in for (...) are count elsewhere in the + // array. + int openParenthesisCount = 1; + int[] openParenthesis = new int[10]; + // tokenBeforeColon is used to know what token goes along with the + // current + // : + // it can be case or ? + int tokenBeforeColonCount = 0; + int[] tokenBeforeColon = new int[10]; + constructionsCount = 0; // initializes the constructions count. + // contains DO if in a DO..WHILE statement, UNITIALIZED otherwise. + int nlicsToken = 0; + // fix for 1FF17XY: LFCOM:ALL - Format problem on not matching } and + // else + boolean specialElse = false; + // OPTION (IndentationLevel): initial indentation level may be non-zero. + currentLineIndentationLevel += constructionsCount; + // An InvalidInputException exception might cause the termination of + // this + // loop. + int arrayDeclarationCount = 0; + int[] arrayDeclarationParenthesis = new int[10]; + try { + while (true) { + // Get the next token. Catch invalid input and output it + // with minimal formatting, also catch end of input and + // exit the loop. + try { + token = scanner.getNextToken(); + if (Scanner.DEBUG) { + int currentEndPosition = scanner + .getCurrentTokenEndPosition(); + int currentStartPosition = scanner + .getCurrentTokenStartPosition(); + System.out.print(currentStartPosition + "," + + currentEndPosition + ": "); + System.out.println(scanner.toStringAction(token)); + } + // Patch for line comment + // See PR http://dev.eclipse.org/bugs/show_bug.cgi?id=23096 + if (token == ITerminalSymbols.TokenNameCOMMENT_LINE) { + int length = scanner.currentPosition; + loop: for (int index = length - 1; index >= 0; index--) { + switch (scanner.source[index]) { + case '\r': + case '\n': + scanner.currentPosition--; + break; + default: + break loop; + } + } + } + } catch (InvalidInputException e) { + if (!handleInvalidToken(e)) { + throw e; + } + token = 0; + } + if (token == Scanner.TokenNameEOF) { + break; + } else if (token == Scanner.TokenNameHEREDOC) { + // no indentation for heredocs and HTML ! + outputCurrentTokenWithoutIndent(Scanner.TokenNameHEREDOC, 0); + continue; + } else if (token == Scanner.TokenNameINLINE_HTML) { + // no indentation for heredocs and HTML ! + int newLineCount = 1; + if (scanner.startPosition == 0) { + newLineCount = 0; + } + outputCurrentTokenWithoutIndent( + Scanner.TokenNameINLINE_HTML, newLineCount); + int srcLen = scanner.source.length; + if (scanner.currentPosition < srcLen - 1) { + newLine(1); + } + continue; + } + /* + * ## MODIFYING the indentation level before generating new + * lines and indentation in the output string + */ + // Removes all the indentations made by statements not followed + // by a + // block + // except if the current token is ELSE, CATCH or if we are in a + // switch/case + if (clearNonBlockIndents + && (token != Scanner.TokenNameWHITESPACE)) { + switch (token) { + case TokenNameelse: + if (constructionsCount > 0 + && constructions[constructionsCount - 1] == TokenNameelse) { + pendingNewLines = 1; + specialElse = true; + } + indentationLevel += popInclusiveUntil(TokenNameif); + break; + // case TokenNamecatch : + // indentationLevel += popInclusiveUntil(TokenNamecatch); + // break; + // case TokenNamefinally : + // indentationLevel += popInclusiveUntil(TokenNamecatch); + // break; + case TokenNamewhile: + if (nlicsToken == TokenNamedo) { + indentationLevel += pop(TokenNamedo); + break; + } + default: + indentationLevel += popExclusiveUntilBlockOrCase(); + // clear until a CASE, DEFAULT or BLOCK is encountered. + // Thus, the indentationLevel is correctly cleared + // either + // in a switch/case statement or in any other situation. + } + clearNonBlockIndents = false; + } + // returns to the indentation level created by the SWITCH + // keyword + // if the current token is a CASE or a DEFAULT + if (token == TokenNamecase || token == TokenNamedefault) { + indentationLevel += pop(TokenNamecase); + } + // if (token == Scanner.TokenNamethrows) { + // inThrowsClause = true; + // } + if ((token == Scanner.TokenNameclass || token == Scanner.TokenNameinterface) + && previousToken != Scanner.TokenNameDOT) { + inClassOrInterfaceHeader = true; + } + /* + * ## APPEND newlines and indentations to the output string + */ + // Do not add a new line between ELSE and IF, if the option + // elseIfOnSameLine is true. + // Fix for 1ETLWPZ: IVJCOM:ALL - incorrect "else if" formatting + // if (pendingNewlineAfterParen + // && previousCompilableToken == TokenNameelse + // && token == TokenNameif + // && options.compactElseIfMode) { + // pendingNewlineAfterParen = false; + // pendingNewLines = 0; + // indentationLevel += pop(TokenNameelse); + // // because else if is now one single statement, + // // the indentation level after it is increased by one and not + // by 2 + // // (else = 1 indent, if = 1 indent, but else if = 1 indent, + // not 2). + // } + // Add a newline & indent to the formatted source string if + // a for/if-else/while statement was scanned and there is no + // block + // following it. + pendingNewlineAfterParen = pendingNewlineAfterParen + || (previousCompilableToken == TokenNameRPAREN && token == TokenNameLBRACE); + if (pendingNewlineAfterParen + && token != Scanner.TokenNameWHITESPACE) { + pendingNewlineAfterParen = false; + // Do to add a newline & indent sequence if the current + // token is an + // open brace or a period or if the current token is a + // semi-colon and + // the + // previous token is a close paren. + // add a new line if a parenthesis belonging to a for() + // statement + // has been closed and the current token is not an opening + // brace + if (token != TokenNameLBRACE && !isComment(token) + // to avoid adding new line between else and a + // comment + && token != TokenNameDOT + && !(previousCompilableToken == TokenNameRPAREN && token == TokenNameSEMICOLON)) { + newLine(1); + currentLineIndentationLevel = indentationLevel; + pendingNewLines = 0; + pendingSpace = false; + } else { + if (token == TokenNameLBRACE + && options.newLineBeforeOpeningBraceMode) { + newLine(1); + if (constructionsCount > 0 + && constructions[constructionsCount - 1] != BLOCK + && constructions[constructionsCount - 1] != NONINDENT_BLOCK) { + currentLineIndentationLevel = indentationLevel - 1; + } else { + currentLineIndentationLevel = indentationLevel; + } + pendingNewLines = 0; + pendingSpace = false; + } + } + } + if (token == TokenNameLBRACE + && options.newLineBeforeOpeningBraceMode + && constructionsCount > 0 + && constructions[constructionsCount - 1] == TokenNamedo) { + newLine(1); + currentLineIndentationLevel = indentationLevel - 1; + pendingNewLines = 0; + pendingSpace = false; + } + // see PR 1G5G8EC + if (token == TokenNameLBRACE && inThrowsClause) { + inThrowsClause = false; + if (options.newLineBeforeOpeningBraceMode) { + newLine(1); + currentLineIndentationLevel = indentationLevel; + pendingNewLines = 0; + pendingSpace = false; + } + } + // see PR 1G5G82G + if (token == TokenNameLBRACE && inClassOrInterfaceHeader) { + inClassOrInterfaceHeader = false; + if (options.newLineBeforeOpeningBraceMode) { + newLine(1); + currentLineIndentationLevel = indentationLevel; + pendingNewLines = 0; + pendingSpace = false; + } + } + // don't linebreak empty array declarations + if (token == TokenNameRPAREN && arrayDeclarationCount > 0) { + if (previousCompilableToken == TokenNameLPAREN) { + pendingNewLines = 0; + } + } + // Add pending new lines to the formatted source string. + // Note: pending new lines are not added if the current token + // is a single line comment or whitespace. + // if the comment is between parenthesis, there is no blank line + // preservation + // (if it's a one-line comment, a blank line is added after it). + if (((pendingNewLines > 0 && (!isComment(token))) + || (newLinesInWhitespace > 0 && (openParenthesisCount <= 1 && isComment(token))) + || (previousCompilableToken == TokenNameLBRACE && token == TokenNameRBRACE) || (newLinesInWhitespace > 0 && previousCompilableToken == TokenNameDOT)) + && token != Scanner.TokenNameWHITESPACE) { + // Do not add newline & indent between an adjoining close + // brace and + // close paren. Anonymous inner classes may use this form. + boolean closeBraceAndCloseParen = previousToken == TokenNameRBRACE + && token == TokenNameRPAREN; + // OPTION (NewLineInCompoundStatement): do not add newline & + // indent + // between close brace and else, (do) while, catch, and + // finally if + // newlineInCompoundStatement is true. + boolean nlicsOption = previousToken == TokenNameRBRACE + && !options.newlineInControlStatementMode + && (token == TokenNameelse + || (token == TokenNamewhile && nlicsToken == TokenNamedo) + || token == TokenNamecatch || token == TokenNamefinally); + // Do not add a newline & indent between a close brace and + // semi-colon. + boolean semiColonAndCloseBrace = previousToken == TokenNameRBRACE + && token == TokenNameSEMICOLON; + // Do not add a new line & indent between a multiline + // comment and a + // opening brace + boolean commentAndOpenBrace = previousToken == Scanner.TokenNameCOMMENT_BLOCK + && token == TokenNameLBRACE; + // Do not add a newline & indent between a close brace and a + // colon + // (in array assignments, for example). + boolean commaAndCloseBrace = previousToken == TokenNameRBRACE + && token == TokenNameCOMMA; + // Add a newline and indent, if appropriate. + if (specialElse + || (!commentAndOpenBrace + && !closeBraceAndCloseParen && !nlicsOption + && !semiColonAndCloseBrace && !commaAndCloseBrace)) { + // if clearAllBlankLinesMode=false, leaves the blank + // lines + // inserted by the user + // if clearAllBlankLinesMode=true, removes all of then + // and insert only blank lines required by the + // formatting. + if (!options.clearAllBlankLinesMode) { + // (isComment(token)) + pendingNewLines = (pendingNewLines < newLinesInWhitespace) ? newLinesInWhitespace + : pendingNewLines; + pendingNewLines = (pendingNewLines > 2) ? 2 + : pendingNewLines; + } + if (previousCompilableToken == TokenNameLBRACE + && token == TokenNameRBRACE) { + containsOpenCloseBraces = true; + indentationLevelForOpenCloseBraces = currentLineIndentationLevel; + if (isComment(previousToken)) { + newLine(pendingNewLines); + } else { + /* + * if (!(constructionsCount > 1 && + * constructions[constructionsCount-1] == + * NONINDENT_BLOCK && + * (constructions[constructionsCount-2] == + * TokenNamefor + */ + if (options.newLineInEmptyBlockMode) { + if (inArrayAssignment) { + newLine(1); // array assigment with an + // empty block + } else { + newLine(pendingNewLines); + } + } + // } + } + } else { + // see PR 1FKKC3U: LFCOM:WINNT - Format problem with + // a comment + // before the ';' + if (!((previousToken == Scanner.TokenNameCOMMENT_BLOCK || previousToken == Scanner.TokenNameCOMMENT_PHPDOC) && token == TokenNameSEMICOLON)) { + newLine(pendingNewLines); + } + } + if (((previousCompilableToken == TokenNameSEMICOLON) + || (previousCompilableToken == TokenNameLBRACE) + || (previousCompilableToken == TokenNameRBRACE) || (isComment(previousToken))) + && (token == TokenNameRBRACE)) { + indentationOffset = -1; + indentationLevel += popExclusiveUntilBlock(); + } + if (previousToken == Scanner.TokenNameCOMMENT_LINE + && inAssignment) { + // PR 1FI5IPO + currentLineIndentationLevel++; + } else { + currentLineIndentationLevel = indentationLevel + + indentationOffset; + } + pendingSpace = false; + indentationOffset = 0; + } + pendingNewLines = 0; + newLinesInWhitespace = 0; + specialElse = false; + if (nlicsToken == TokenNamedo && token == TokenNamewhile) { + nlicsToken = 0; + } + } + boolean phpTagAndWhitespace = previousToken == TokenNameINLINE_HTML + && token == TokenNameWHITESPACE; + switch (token) { + // case TokenNameDOLLAR : + // dollarBraceCount++; + // break; + case TokenNameelse: + // case TokenNamefinally : + expectingOpenBrace = true; + pendingNewlineAfterParen = true; + indentationLevel += pushControlStatement(token); + break; + case TokenNamecase: + case TokenNamedefault: + if (tokenBeforeColonCount == tokenBeforeColon.length) { + System + .arraycopy( + tokenBeforeColon, + 0, + (tokenBeforeColon = new int[tokenBeforeColonCount * 2]), + 0, tokenBeforeColonCount); + } + tokenBeforeColon[tokenBeforeColonCount++] = TokenNamecase; + indentationLevel += pushControlStatement(TokenNamecase); + break; + case TokenNameQUESTION: + if (tokenBeforeColonCount == tokenBeforeColon.length) { + System + .arraycopy( + tokenBeforeColon, + 0, + (tokenBeforeColon = new int[tokenBeforeColonCount * 2]), + 0, tokenBeforeColonCount); + } + tokenBeforeColon[tokenBeforeColonCount++] = token; + break; + case TokenNameswitch: + case TokenNamefor: + case TokenNameforeach: + case TokenNameif: + case TokenNamewhile: + if (openParenthesisCount == openParenthesis.length) { + System + .arraycopy( + openParenthesis, + 0, + (openParenthesis = new int[openParenthesisCount * 2]), + 0, openParenthesisCount); + } + openParenthesis[openParenthesisCount++] = 0; + expectingOpenBrace = true; + indentationLevel += pushControlStatement(token); + break; + case TokenNametry: + pendingNewlineAfterParen = true; + case TokenNamecatch: + // several CATCH statements can be contiguous. + // a CATCH is encountered pop until first CATCH (if a CATCH + // follows a TRY it works the same way, + // as CATCH and TRY are the same token in the stack). + expectingOpenBrace = true; + indentationLevel += pushControlStatement(TokenNamecatch); + break; + case TokenNamedo: + expectingOpenBrace = true; + indentationLevel += pushControlStatement(token); + nlicsToken = token; + break; + case TokenNamenew: + break; + case TokenNameLPAREN: + // if (previousToken == TokenNamesynchronized) { + // indentationLevel += pushControlStatement(previousToken); + // } else { + // Put a space between the previous and current token if the + // previous token was not a keyword, open paren, logical + // compliment (eg: !), semi-colon, open brace, close brace, + // super, or this. + if (previousCompilableToken != TokenNameLBRACKET + && previousToken != TokenNameIdentifier + && previousToken != 0 + && previousToken != TokenNameNOT + && previousToken != TokenNameLPAREN + && previousToken != TokenNameTWIDDLE + && previousToken != TokenNameSEMICOLON + && previousToken != TokenNameLBRACE + && previousToken != TokenNameRBRACE + && previousToken != TokenNamesuper) { + // && previousToken != TokenNamethis) { + space(); + } + // If in a for/if/while statement, increase the parenthesis + // count + // for the current openParenthesisCount + // else increase the count for stand alone parenthesis. + if (openParenthesisCount > 0) + openParenthesis[openParenthesisCount - 1]++; + else + openParenthesis[0]++; + pendingSpace = false; + // recognize array declaration for nice output + if (previousCompilableToken == TokenNamearray) { + arrayDeclarationCount++; + arrayDeclarationParenthesis[arrayDeclarationCount] = openParenthesis[openParenthesisCount]; + indentationLevel++; + pendingNewLines = 1; + } + // S } + break; + case TokenNameRPAREN: + // check for closing array declaration + if (arrayDeclarationCount > 0) { + if (arrayDeclarationParenthesis[arrayDeclarationCount] == openParenthesis[openParenthesisCount]) { + if (previousCompilableToken != TokenNameLPAREN) { + newLine(1); + } + indentationLevel--; + currentLineIndentationLevel = indentationLevel; + pendingNewLines = 0; + arrayDeclarationCount--; + } + } + // Decrease the parenthesis count + // if there is no more unclosed parenthesis, + // a new line and indent may be append (depending on the + // next + // token). + if ((openParenthesisCount > 1) + && (openParenthesis[openParenthesisCount - 1] > 0)) { + openParenthesis[openParenthesisCount - 1]--; + if (openParenthesis[openParenthesisCount - 1] <= 0) { + pendingNewlineAfterParen = true; + inAssignment = false; + openParenthesisCount--; + } + } else { + openParenthesis[0]--; + } + pendingSpace = false; + break; + case TokenNameLBRACE: + if (previousCompilableToken == TokenNameDOLLAR) { + dollarBraceCount++; + } else { + if ((previousCompilableToken == TokenNameRBRACKET) + || (previousCompilableToken == TokenNameEQUAL)) { + // if (previousCompilableToken == TokenNameRBRACKET) + // { + inArrayAssignment = true; + inAssignment = false; + } + if (inArrayAssignment) { + indentationLevel += pushBlock(); + } else { + // Add new line and increase indentation level after + // open brace. + pendingNewLines = 1; + indentationLevel += pushBlock(); + inAssignment = false; + } + } + break; + case TokenNameRBRACE: + if (dollarBraceCount > 0) { + dollarBraceCount--; + break; + } + if (previousCompilableToken == TokenNameRPAREN) { + pendingSpace = false; + } + if (inArrayAssignment) { + inArrayAssignment = false; + pendingNewLines = 1; + indentationLevel += popInclusiveUntilBlock(); + } else { + pendingNewLines = 1; + indentationLevel += popInclusiveUntilBlock(); + if (previousCompilableToken == TokenNameRPAREN) { + // fix for 1FGDDV6: LFCOM:WIN98 - Weird splitting on + // message + // expression + currentLineBuffer + .append(options.lineSeparatorSequence); + increaseLineDelta(options.lineSeparatorSequence.length); + } + if (constructionsCount > 0) { + switch (constructions[constructionsCount - 1]) { + case TokenNamefor: + case TokenNameforeach: + // indentationLevel += popExclusiveUntilBlock(); + // break; + case TokenNameswitch: + case TokenNameif: + case TokenNameelse: + case TokenNametry: + case TokenNamecatch: + case TokenNamefinally: + case TokenNamewhile: + case TokenNamedo: + // case TokenNamesynchronized : + clearNonBlockIndents = true; + default: + break; + } + } + } + break; + case TokenNameLBRACKET: + openBracketCount++; + pendingSpace = false; + break; + case TokenNameRBRACKET: + openBracketCount -= (openBracketCount > 0) ? 1 : 0; + // if there is no left bracket to close, the right bracket + // is + // ignored. + pendingSpace = false; + break; + case TokenNameCOMMA: + pendingSpace = false; + if (arrayDeclarationCount > 0) { + pendingNewLines = 1; + } + break; + case TokenNameDOT: + space(); + pendingSpace = false; + break; + case TokenNameSEMICOLON: + // Do not generate line terminators in the definition of + // the for statement. + // if not in this case, jump a line and reduce indentation + // after + // the brace + // if the block it closes belongs to a conditional statement + // (if, + // while, do...). + if (openParenthesisCount <= 1) { + pendingNewLines = 1; + if (expectingOpenBrace) { + clearNonBlockIndents = true; + expectingOpenBrace = false; + } + } + inAssignment = false; + pendingSpace = false; + break; + case TokenNamePLUS_PLUS: + case TokenNameMINUS_MINUS: + // Do not put a space between a post-increment/decrement + // and the identifier being modified. + if (previousToken == TokenNameIdentifier + || previousToken == TokenNameRBRACKET + || previousToken == TokenNameVariable) { + pendingSpace = false; + } + break; + case TokenNamePLUS: + // previously ADDITION + case TokenNameMINUS: + // Handle the unary operators plus and minus via a flag + if (!isLiteralToken(previousToken) + && previousToken != TokenNameIdentifier + && previousToken != TokenNameRPAREN + && previousToken != TokenNameRBRACKET) { + unarySignModifier = 1; + } + break; + case TokenNameCOLON: + // In a switch/case statement, add a newline & indent + // when a colon is encountered. + if (tokenBeforeColonCount > 0) { + if (tokenBeforeColon[tokenBeforeColonCount - 1] == TokenNamecase) { + pendingNewLines = 1; + } + tokenBeforeColonCount--; + } + break; + case TokenNameEQUAL: + inAssignment = true; + break; + case Scanner.TokenNameCOMMENT_LINE: + pendingNewLines = 1; + if (inAssignment) { + currentLineIndentationLevel++; + } + break; // a line is always inserted after a one-line + // comment + case Scanner.TokenNameCOMMENT_PHPDOC: + case Scanner.TokenNameCOMMENT_BLOCK: + currentCommentOffset = getCurrentCommentOffset(); + pendingNewLines = 1; + break; + case Scanner.TokenNameWHITESPACE: + if (!phpTagAndWhitespace) { + // Count the number of line terminators in the + // whitespace so + // line spacing can be preserved near comments. + char[] source = scanner.source; + newLinesInWhitespace = 0; + for (int i = scanner.startPosition, max = scanner.currentPosition; i < max; i++) { + if (source[i] == '\r') { + if (i < max - 1) { + if (source[++i] == '\n') { + newLinesInWhitespace++; + } else { + newLinesInWhitespace++; + } + } else { + newLinesInWhitespace++; + } + } else if (source[i] == '\n') { + newLinesInWhitespace++; + } + } + increaseLineDelta(scanner.startPosition + - scanner.currentPosition); + break; + } + // case TokenNameHTML : + // // Add the next token to the formatted source string. + // // outputCurrentToken(token); + // int startPosition = scanner.startPosition; + // flushBuffer(); + // for (int i = startPosition, max = + // scanner.currentPosition; i < + // max; i++) { + // char currentCharacter = scanner.source[i]; + // updateMappedPositions(i); + // currentLineBuffer.append(currentCharacter); + // } + // break; + default: + if ((token == TokenNameIdentifier) || isLiteralToken(token) + || token == TokenNamesuper) { + // || token == TokenNamethis) { + // Do not put a space between a unary operator + // (eg: ++, --, +, -) and the identifier being modified. + if (previousToken == TokenNamePLUS_PLUS + || previousToken == TokenNameMINUS_MINUS + || (previousToken == TokenNameMINUS_GREATER && options.compactDereferencingMode) // -> + || (previousToken == TokenNamePLUS && unarySignModifier > 0) + || (previousToken == TokenNameMINUS && unarySignModifier > 0)) { + pendingSpace = false; + } + unarySignModifier = 0; + } + break; + } + // Do not output whitespace tokens. + if (token != Scanner.TokenNameWHITESPACE || phpTagAndWhitespace) { + /* + * Add pending space to the formatted source string. Do not + * output a space under the following circumstances: 1) this + * is the first pass 2) previous token is an open paren 3) + * previous token is a period 4) previous token is the + * logical compliment (eg: !) 5) previous token is the + * bitwise compliment (eg: ~) 6) previous token is the open + * bracket (eg: [) 7) in an assignment statement, if the + * previous token is an open brace or the current token is a + * close brace 8) previous token is a single line comment 9) + * current token is a '->' + */ + if (token == TokenNameMINUS_GREATER + && options.compactDereferencingMode) + pendingSpace = false; + + boolean openAndCloseBrace = previousCompilableToken == TokenNameLBRACE + && token == TokenNameRBRACE; + if (pendingSpace + && insertSpaceAfter(previousToken) + && !(inAssignment && (previousToken == TokenNameLBRACE || token == TokenNameRBRACE)) + && previousToken != Scanner.TokenNameCOMMENT_LINE) { + if ((!(options.compactAssignmentMode && token == TokenNameEQUAL)) + && !openAndCloseBrace) + space(); + } + // Add the next token to the formatted source string. + outputCurrentToken(token); + if (token == Scanner.TokenNameCOMMENT_LINE + && openParenthesisCount > 1) { + pendingNewLines = 0; + currentLineBuffer.append(options.lineSeparatorSequence); + increaseLineDelta(options.lineSeparatorSequence.length); + } + pendingSpace = true; + } + // Whitespace tokens do not need to be remembered. + if (token != Scanner.TokenNameWHITESPACE || phpTagAndWhitespace) { + previousToken = token; + if (token != Scanner.TokenNameCOMMENT_BLOCK + && token != Scanner.TokenNameCOMMENT_LINE + && token != Scanner.TokenNameCOMMENT_PHPDOC) { + previousCompilableToken = token; + } + } + } + output(copyRemainingSource()); + flushBuffer(); + // dump the last token of the source in the formatted output. + } catch (InvalidInputException e) { + output(copyRemainingSource()); + flushBuffer(); + // dump the last token of the source in the formatted output. + } + } + + /** + * Formats the char array sourceString, and returns a string + * containing the formatted version. + * + * @return the formatted ouput. + */ + public String formatSourceString(String sourceString) { + char[] sourceChars = sourceString.toCharArray(); + formattedSource = new StringBuffer(sourceChars.length); + scanner.setSource(sourceChars); + format(); + return formattedSource.toString(); + } + + /** + * Formats the char array sourceString, and returns a string + * containing the formatted version. + * + * @param string + * the string to format + * @param indentationLevel + * the initial indentation level + * @return the formatted ouput. + */ + public String format(String string, int indentationLevel) { + return format(string, indentationLevel, (int[]) null); + } + + /** + * Formats the char array sourceString, and returns a string + * containing the formatted version. The positions array is modified to + * contain the mapped positions. + * + * @param string + * the string to format + * @param indentationLevel + * the initial indentation level + * @param positions + * the array of positions to map + * @return the formatted ouput. + */ + public String format(String string, int indentationLevel, int[] positions) { + return this.format(string, indentationLevel, positions, null); + } + + public String format(String string, int indentationLevel, int[] positions, + String lineSeparator) { + if (lineSeparator != null) { + this.options.setLineSeparator(lineSeparator); + } + if (positions != null) { + this.setPositionsToMap(positions); + this.setInitialIndentationLevel(indentationLevel); + String formattedString = this.formatSourceString(string); + int[] mappedPositions = this.getMappedPositions(); + System + .arraycopy(mappedPositions, 0, positions, 0, + positions.length); + return formattedString; + } else { + this.setInitialIndentationLevel(indentationLevel); + return this.formatSourceString(string); + } + } + + /** + * Formats the char array sourceString, and returns a string + * containing the formatted version. The initial indentation level is 0. + * + * @param string + * the string to format + * @return the formatted ouput. + */ + public String format(String string) { + return this.format(string, 0, (int[]) null); + } + + /** + * Formats a given source string, starting indenting it at a particular + * depth and using the given options + * + * @deprecated backport 1.0 internal functionality + */ + public static String format(String sourceString, + int initialIndentationLevel, ConfigurableOption[] options) { + CodeFormatter formatter = new CodeFormatter(options); + formatter.setInitialIndentationLevel(initialIndentationLevel); + return formatter.formatSourceString(sourceString); + } + + /** + * Returns the number of characters and tab char between the beginning of + * the line and the beginning of the comment. + */ + private int getCurrentCommentOffset() { + int linePtr = scanner.linePtr; + // if there is no beginning of line, return 0. + if (linePtr < 0) + return 0; + int offset = 0; + int beginningOfLine = scanner.lineEnds[linePtr]; + int currentStartPosition = scanner.startPosition; + char[] source = scanner.source; + // find the position of the beginning of the line containing the comment + while (beginningOfLine > currentStartPosition) { + if (linePtr > 0) { + beginningOfLine = scanner.lineEnds[--linePtr]; + } else { + beginningOfLine = 0; + break; + } + } + for (int i = currentStartPosition - 1; i >= beginningOfLine; i--) { + char currentCharacter = source[i]; + switch (currentCharacter) { + case '\t': + offset += options.tabSize; + break; + case ' ': + offset++; + break; + case '\r': + case '\n': + break; + default: + return offset; + } + } + return offset; + } + + /** + * Returns an array of descriptions for the configurable options. The + * descriptions may be changed and passed back to a different compiler. + * + * @deprecated backport 1.0 internal functionality + */ + public static ConfigurableOption[] getDefaultOptions(Locale locale) { + String componentName = CodeFormatter.class.getName(); + FormatterOptions options = new FormatterOptions(); + return new ConfigurableOption[] { + new ConfigurableOption(componentName, "newline.openingBrace", + locale, options.newLineBeforeOpeningBraceMode ? 0 : 1), + //$NON-NLS-1$ + new ConfigurableOption(componentName, + "newline.controlStatement", locale, + options.newlineInControlStatementMode ? 0 : 1), + //$NON-NLS-1$ + new ConfigurableOption(componentName, "newline.clearAll", + locale, options.clearAllBlankLinesMode ? 0 : 1), + //$NON-NLS-1$ + // new ConfigurableOption(componentName, "newline.elseIf", + // locale, + // options.compactElseIfMode ? 0 : 1), //$NON-NLS-1$ + new ConfigurableOption(componentName, "newline.emptyBlock", + locale, options.newLineInEmptyBlockMode ? 0 : 1), + //$NON-NLS-1$ + new ConfigurableOption(componentName, "line.split", locale, + options.maxLineLength), + //$NON-NLS-1$ + new ConfigurableOption(componentName, + "style.compactAssignment", locale, + options.compactAssignmentMode ? 0 : 1), + //$NON-NLS-1$ + new ConfigurableOption(componentName, "tabulation.char", + locale, options.indentWithTab ? 0 : 1), + //$NON-NLS-1$ + new ConfigurableOption(componentName, + "tabulation.size", locale, options.tabSize) //$NON-NLS-1$ + }; + } + + /** + * Returns the array of mapped positions. Returns null is no positions have + * been set. + * + * @return int[] + * @deprecated There is no need to retrieve the mapped positions anymore. + */ + public int[] getMappedPositions() { + if (null != mappedPositions) { + for (int i = 0; i < mappedPositions.length; i++) { + if (mappedPositions[i] >= formattedSource.length()) { + mappedPositions[i] = formattedSource.length() - 1; + } } } + return mappedPositions; + } + + /** + * Returns the priority of the token given as argument
                                                      + * The most prioritary the token is, the smallest the return value is. + * + * @return the priority of token + * @param token + * the token of which the priority is requested + */ + private static int getTokenPriority(int token) { + switch (token) { + case TokenNameextends: + // case TokenNameimplements : + // case TokenNamethrows : + return 10; + case TokenNameSEMICOLON: + // ; + return 20; + case TokenNameCOMMA: + // , + return 25; + case TokenNameEQUAL: + // = + return 30; + case TokenNameAND_AND: + // && + case TokenNameOR_OR: + // || + return 40; + case TokenNameQUESTION: + // ? + case TokenNameCOLON: + // : + return 50; // it's better cutting on ?: than on ; + case TokenNameEQUAL_EQUAL: + // == + case TokenNameEQUAL_EQUAL_EQUAL: + // === + case TokenNameNOT_EQUAL: + // != + case TokenNameNOT_EQUAL_EQUAL: + // != + return 60; + case TokenNameLESS: + // < + case TokenNameLESS_EQUAL: + // <= + case TokenNameGREATER: + // > + case TokenNameGREATER_EQUAL: + // >= + // case TokenNameinstanceof : // instanceof + return 70; + case TokenNamePLUS: + // + + case TokenNameMINUS: + // - + return 80; + case TokenNameMULTIPLY: + // * + case TokenNameDIVIDE: + // / + case TokenNameREMAINDER: + // % + return 90; + case TokenNameLEFT_SHIFT: + // << + case TokenNameRIGHT_SHIFT: + // >> + // case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> + return 100; + case TokenNameAND: + // & + case TokenNameOR: + // | + case TokenNameXOR: + // ^ + return 110; + case TokenNameMULTIPLY_EQUAL: + // *= + case TokenNameDIVIDE_EQUAL: + // /= + case TokenNameREMAINDER_EQUAL: + // %= + case TokenNamePLUS_EQUAL: + // += + case TokenNameMINUS_EQUAL: + // -= + case TokenNameLEFT_SHIFT_EQUAL: + // <<= + case TokenNameRIGHT_SHIFT_EQUAL: + // >>= + // case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= + case TokenNameAND_EQUAL: + // &= + case TokenNameXOR_EQUAL: + // ^= + case TokenNameOR_EQUAL: + // .= + case TokenNameDOT_EQUAL: + // |= + return 120; + case TokenNameDOT: + // . + return 130; + default: + return Integer.MAX_VALUE; + } + } + + /** + * Handles the exception raised when an invalid token is encountered. + * Returns true if the exception has been handled, false otherwise. + */ + private boolean handleInvalidToken(Exception e) { + if (e.getMessage().equals(Scanner.INVALID_CHARACTER_CONSTANT) + || e.getMessage().equals(Scanner.INVALID_CHAR_IN_STRING) + || e.getMessage().equals(Scanner.INVALID_ESCAPE)) { + return true; + } + return false; + } + + private final void increaseGlobalDelta(int offset) { + globalDelta += offset; + } + + private final void increaseLineDelta(int offset) { + lineDelta += offset; + } + + private final void increaseSplitDelta(int offset) { + splitDelta += offset; + } + + /** + * Returns true if a space has to be inserted after operator + * false otherwise. + */ + private boolean insertSpaceAfter(int token) { + switch (token) { + case TokenNameLPAREN: + case TokenNameNOT: + case TokenNameTWIDDLE: + case 0: + // no token + case TokenNameWHITESPACE: + case TokenNameLBRACKET: + case TokenNameDOLLAR: + case Scanner.TokenNameCOMMENT_LINE: + return false; + default: + return true; + } + } + + /** + * Returns true if a space has to be inserted before operator + * false otherwise.
                                                      + * Cannot be static as it uses the code formatter options (to know if the + * compact assignment mode is on). + */ + private boolean insertSpaceBefore(int token) { + switch (token) { + case TokenNameEQUAL: + return (!options.compactAssignmentMode); + default: + return false; + } + } + + private static boolean isComment(int token) { + boolean result = token == Scanner.TokenNameCOMMENT_BLOCK + || token == Scanner.TokenNameCOMMENT_LINE + || token == Scanner.TokenNameCOMMENT_PHPDOC; + return result; + } + + private static boolean isLiteralToken(int token) { + boolean result = token == TokenNameIntegerLiteral + // || token == TokenNameLongLiteral + // || token == TokenNameFloatingPointLiteral + || token == TokenNameDoubleLiteral + // || token == TokenNameCharacterLiteral + || token == TokenNameStringDoubleQuote; + return result; + } + + /** + * If the length of oneLineBuffer exceeds + * maxLineLength, it is split and the result is dumped in + * formattedSource + * + * @param newLineCount + * the number of new lines to append + */ + private void newLine(int newLineCount) { + // format current line + splitDelta = 0; + beginningOfLineIndex = formattedSource.length(); + String currentLine = currentLineBuffer.toString(); + if (containsOpenCloseBraces) { + containsOpenCloseBraces = false; + outputLine(currentLine, false, indentationLevelForOpenCloseBraces, + 0, -1, null, 0); + indentationLevelForOpenCloseBraces = currentLineIndentationLevel; + } else { + outputLine(currentLine, false, currentLineIndentationLevel, 0, -1, + null, 0); + } + // dump line break(s) + for (int i = 0; i < newLineCount; i++) { + formattedSource.append(options.lineSeparatorSequence); + increaseSplitDelta(options.lineSeparatorSequence.length); + } + // reset formatter for next line + int currentLength = currentLine.length(); + currentLineBuffer = new StringBuffer( + currentLength > maxLineSize ? maxLineSize = currentLength + : maxLineSize); + increaseGlobalDelta(splitDelta); + increaseGlobalDelta(lineDelta); + lineDelta = 0; + currentLineIndentationLevel = initialIndentationLevel; + } + + private String operatorString(int operator) { + switch (operator) { + case TokenNameextends: + return "extends"; //$NON-NLS-1$ + // case TokenNameimplements : + // return "implements"; //$NON-NLS-1$ + // + // case TokenNamethrows : + // return "throws"; //$NON-NLS-1$ + case TokenNameSEMICOLON: + // ; + return ";"; //$NON-NLS-1$ + case TokenNameCOMMA: + // , + return ","; //$NON-NLS-1$ + case TokenNameEQUAL: + // = + return "="; //$NON-NLS-1$ + case TokenNameAND_AND: + // && (15.22) + return "&&"; //$NON-NLS-1$ + case TokenNameOR_OR: + // || (15.23) + return "||"; //$NON-NLS-1$ + case TokenNameQUESTION: + // ? (15.24) + return "?"; //$NON-NLS-1$ + case TokenNameCOLON: + // : (15.24) + return ":"; //$NON-NLS-1$ + case TokenNamePAAMAYIM_NEKUDOTAYIM: + // : (15.24) + return "::"; //$NON-NLS-1$ + case TokenNameEQUAL_EQUAL: + // == (15.20, 15.20.1, 15.20.2, 15.20.3) + return "=="; //$NON-NLS-1$ + case TokenNameEQUAL_EQUAL_EQUAL: + // == (15.20, 15.20.1, 15.20.2, 15.20.3) + return "==="; //$NON-NLS-1$ + case TokenNameEQUAL_GREATER: + // -= (15.25.2) + return "=>"; //$NON-NLS-1$ + case TokenNameNOT_EQUAL: + // != (15.20, 15.20.1, 15.20.2, 15.20.3) + return "!="; //$NON-NLS-1$ + case TokenNameNOT_EQUAL_EQUAL: + // != (15.20, 15.20.1, 15.20.2, 15.20.3) + return "!=="; //$NON-NLS-1$ + case TokenNameLESS: + // < (15.19.1) + return "<"; //$NON-NLS-1$ + case TokenNameLESS_EQUAL: + // <= (15.19.1) + return "<="; //$NON-NLS-1$ + case TokenNameGREATER: + // > (15.19.1) + return ">"; //$NON-NLS-1$ + case TokenNameGREATER_EQUAL: + // >= (15.19.1) + return ">="; //$NON-NLS-1$ + // case TokenNameinstanceof : // instanceof + // return "instanceof"; //$NON-NLS-1$ + case TokenNamePLUS: + // + (15.17, 15.17.2) + return "+"; //$NON-NLS-1$ + case TokenNameMINUS: + // - (15.17.2) + return "-"; //$NON-NLS-1$ + case TokenNameMULTIPLY: + // * (15.16.1) + return "*"; //$NON-NLS-1$ + case TokenNameDIVIDE: + // / (15.16.2) + return "/"; //$NON-NLS-1$ + case TokenNameREMAINDER: + // % (15.16.3) + return "%"; //$NON-NLS-1$ + case TokenNameLEFT_SHIFT: + // << (15.18) + return "<<"; //$NON-NLS-1$ + case TokenNameRIGHT_SHIFT: + // >> (15.18) + return ">>"; //$NON-NLS-1$ + // case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18) + // return ">>>"; //$NON-NLS-1$ + case TokenNameAND: + // & (15.21, 15.21.1, 15.21.2) + return "&"; //$NON-NLS-1$ + case TokenNameOR: + // | (15.21, 15.21.1, 15.21.2) + return "|"; //$NON-NLS-1$ + case TokenNameXOR: + // ^ (15.21, 15.21.1, 15.21.2) + return "^"; //$NON-NLS-1$ + case TokenNameMULTIPLY_EQUAL: + // *= (15.25.2) + return "*="; //$NON-NLS-1$ + case TokenNameDIVIDE_EQUAL: + // /= (15.25.2) + return "/="; //$NON-NLS-1$ + case TokenNameREMAINDER_EQUAL: + // %= (15.25.2) + return "%="; //$NON-NLS-1$ + case TokenNamePLUS_EQUAL: + // += (15.25.2) + return "+="; //$NON-NLS-1$ + case TokenNameMINUS_EQUAL: + // -= (15.25.2) + return "-="; //$NON-NLS-1$ + case TokenNameMINUS_GREATER: + // -= (15.25.2) + return "->"; //$NON-NLS-1$ + case TokenNameLEFT_SHIFT_EQUAL: + // <<= (15.25.2) + return "<<="; //$NON-NLS-1$ + case TokenNameRIGHT_SHIFT_EQUAL: + // >>= (15.25.2) + return ">>="; //$NON-NLS-1$ + // case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2) + // return ">>>="; //$NON-NLS-1$ + case TokenNameAND_EQUAL: + // &= (15.25.2) + return "&="; //$NON-NLS-1$ + case TokenNameXOR_EQUAL: + // ^= (15.25.2) + return "^="; //$NON-NLS-1$ + case TokenNameOR_EQUAL: + // |= (15.25.2) + return "|="; //$NON-NLS-1$ + case TokenNameDOT_EQUAL: + // .= + return ".="; //$NON-NLS-1$ + case TokenNameDOT: + // . + return "."; //$NON-NLS-1$ + default: + return ""; //$NON-NLS-1$ + } + } + + /** + * Appends stringToOutput to the formatted output.
                                                      + * If it contains \n, append a LINE_SEPARATOR and indent after it. + */ + private void output(String stringToOutput) { + char currentCharacter; + for (int i = 0, max = stringToOutput.length(); i < max; i++) { + currentCharacter = stringToOutput.charAt(i); + if (currentCharacter != '\t') { + currentLineBuffer.append(currentCharacter); + } + } + } + + private void outputCurrentTokenWithoutIndent(int token, int newLineCount) { + newLine(newLineCount); + formattedSource.append(scanner.source, scanner.startPosition, + scanner.currentPosition - scanner.startPosition); + } + + /** + * Appends token to the formatted output.
                                                      + * If it contains \n, append a LINE_SEPARATOR and indent + * after it. + */ + private void outputCurrentToken(int token) { + char[] source = scanner.source; + int startPosition = scanner.startPosition; + switch (token) { + case Scanner.TokenNameCOMMENT_PHPDOC: + case Scanner.TokenNameCOMMENT_BLOCK: + case Scanner.TokenNameCOMMENT_LINE: + boolean endOfLine = false; + int currentCommentOffset = getCurrentCommentOffset(); + int beginningOfLineSpaces = 0; + endOfLine = false; + currentCommentOffset = getCurrentCommentOffset(); + beginningOfLineSpaces = 0; + boolean pendingCarriageReturn = false; + for (int i = startPosition, max = scanner.currentPosition; i < max; i++) { + char currentCharacter = source[i]; + updateMappedPositions(i); + switch (currentCharacter) { + case '\r': + pendingCarriageReturn = true; + endOfLine = true; + break; + case '\n': + if (pendingCarriageReturn) { + increaseGlobalDelta(options.lineSeparatorSequence.length - 2); + } else { + increaseGlobalDelta(options.lineSeparatorSequence.length - 1); + } + pendingCarriageReturn = false; + currentLineBuffer.append(options.lineSeparatorSequence); + beginningOfLineSpaces = 0; + endOfLine = true; + break; + case '\t': + if (pendingCarriageReturn) { + pendingCarriageReturn = false; + increaseGlobalDelta(options.lineSeparatorSequence.length - 1); + currentLineBuffer.append(options.lineSeparatorSequence); + beginningOfLineSpaces = 0; + endOfLine = true; + } + if (endOfLine) { + // we remove a maximum of currentCommentOffset + // characters (tabs + // are converted to space numbers). + beginningOfLineSpaces += options.tabSize; + if (beginningOfLineSpaces > currentCommentOffset) { + currentLineBuffer.append(currentCharacter); + } else { + increaseGlobalDelta(-1); + } + } else { + currentLineBuffer.append(currentCharacter); + } + break; + case ' ': + if (pendingCarriageReturn) { + pendingCarriageReturn = false; + increaseGlobalDelta(options.lineSeparatorSequence.length - 1); + currentLineBuffer.append(options.lineSeparatorSequence); + beginningOfLineSpaces = 0; + endOfLine = true; + } + if (endOfLine) { + // we remove a maximum of currentCommentOffset + // characters (tabs + // are converted to space numbers). + beginningOfLineSpaces++; + if (beginningOfLineSpaces > currentCommentOffset) { + currentLineBuffer.append(currentCharacter); + } else { + increaseGlobalDelta(-1); + } + } else { + currentLineBuffer.append(currentCharacter); + } + break; + default: + if (pendingCarriageReturn) { + pendingCarriageReturn = false; + increaseGlobalDelta(options.lineSeparatorSequence.length - 1); + currentLineBuffer.append(options.lineSeparatorSequence); + beginningOfLineSpaces = 0; + endOfLine = true; + } else { + beginningOfLineSpaces = 0; + currentLineBuffer.append(currentCharacter); + endOfLine = false; + } + } + } + updateMappedPositions(scanner.currentPosition - 1); + multipleLineCommentCounter++; + break; + default: + for (int i = startPosition, max = scanner.currentPosition; i < max; i++) { + char currentCharacter = source[i]; + updateMappedPositions(i); + currentLineBuffer.append(currentCharacter); + } + } + } + + /** + * Outputs currentString:
                                                      + *
                                                        + *
                                                      • If its length is < maxLineLength, output + *
                                                      • Otherwise it is split. + *
                                                      + * + * @param currentString + * string to output + * @param preIndented + * whether the string to output was pre-indented + * @param depth + * number of indentation to put in front of + * currentString + * @param operator + * value of the operator belonging to currentString. + */ + private void outputLine(String currentString, boolean preIndented, + int depth, int operator, int substringIndex, + int[] startSubstringIndexes, int offsetInGlobalLine) { + boolean emptyFirstSubString = false; + String operatorString = operatorString(operator); + boolean placeOperatorBehind = !breakLineBeforeOperator(operator); + boolean placeOperatorAhead = !placeOperatorBehind; + // dump prefix operator? + if (placeOperatorAhead) { + if (!preIndented) { + dumpTab(depth); + preIndented = true; + } + if (operator != 0) { + if (insertSpaceBefore(operator)) { + formattedSource.append(' '); + increaseSplitDelta(1); + } + formattedSource.append(operatorString); + increaseSplitDelta(operatorString.length()); + if (insertSpaceAfter(operator) + && operator != TokenNameimplements + && operator != TokenNameextends) { + // && operator != TokenNamethrows) { + formattedSource.append(' '); + increaseSplitDelta(1); + } + } + } + SplitLine splitLine = null; + if (options.maxLineLength == 0 + || getLength(currentString, depth) < options.maxLineLength + || (splitLine = split(currentString, offsetInGlobalLine)) == null) { + // depending on the type of operator, outputs new line before of + // after + // dumping it + // indent before postfix operator + // indent also when the line cannot be split + if (operator == TokenNameextends || operator == TokenNameimplements) { + // || operator == TokenNamethrows) { + formattedSource.append(' '); + increaseSplitDelta(1); + } + if (placeOperatorBehind) { + if (!preIndented) { + dumpTab(depth); + } + } + int max = currentString.length(); + if (multipleLineCommentCounter != 0) { + try { + BufferedReader reader = new BufferedReader( + new StringReader(currentString)); + String line = reader.readLine(); + while (line != null) { + updateMappedPositionsWhileSplitting( + beginningOfLineIndex, beginningOfLineIndex + + line.length() + + options.lineSeparatorSequence.length); + formattedSource.append(line); + beginningOfLineIndex = beginningOfLineIndex + + line.length(); + if ((line = reader.readLine()) != null) { + formattedSource + .append(options.lineSeparatorSequence); + beginningOfLineIndex += options.lineSeparatorSequence.length; + dumpTab(currentLineIndentationLevel); + } + } + reader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } else { + updateMappedPositionsWhileSplitting(beginningOfLineIndex, + beginningOfLineIndex + max); + for (int i = 0; i < max; i++) { + char currentChar = currentString.charAt(i); + switch (currentChar) { + case '\r': + break; + case '\n': + if (i != max - 1) { + // fix for 1FFYL5C: LFCOM:ALL - Incorrect + // indentation when + // split with a comment inside a condition + // a substring cannot end with a + // lineSeparatorSequence, + // except if it has been added by format() after a + // one-line + // comment + formattedSource + .append(options.lineSeparatorSequence); + // 1FGDDV6: LFCOM:WIN98 - Weird splitting on message + // expression + dumpTab(depth - 1); + } + break; + default: + formattedSource.append(currentChar); + } + } + } + // update positions inside the mappedPositions table + if (substringIndex != -1) { + if (multipleLineCommentCounter == 0) { + int startPosition = beginningOfLineIndex + + startSubstringIndexes[substringIndex]; + updateMappedPositionsWhileSplitting(startPosition, + startPosition + max); + } + // compute the splitDelta resulting with the operator and blank + // removal + if (substringIndex + 1 != startSubstringIndexes.length) { + increaseSplitDelta(startSubstringIndexes[substringIndex] + + max - startSubstringIndexes[substringIndex + 1]); + } + } + // dump postfix operator? + if (placeOperatorBehind) { + if (insertSpaceBefore(operator)) { + formattedSource.append(' '); + if (operator != 0) { + increaseSplitDelta(1); + } + } + formattedSource.append(operatorString); + if (operator != 0) { + increaseSplitDelta(operatorString.length()); + } + } + return; + } + // fix for 1FG0BA3: LFCOM:WIN98 - Weird splitting on interfaces + // extends has to stand alone on a line when currentString has been + // split. + if (options.maxLineLength != 0 && splitLine != null + && (operator == TokenNameextends)) { + // || operator == TokenNameimplements + // || operator == TokenNamethrows)) { + formattedSource.append(options.lineSeparatorSequence); + increaseSplitDelta(options.lineSeparatorSequence.length); + dumpTab(depth + 1); + } else { + if (operator == TokenNameextends) { + // || operator == TokenNameimplements + // || operator == TokenNamethrows) { + formattedSource.append(' '); + increaseSplitDelta(1); + } + } + // perform actual splitting + String result[] = splitLine.substrings; + int[] splitOperators = splitLine.operators; + if (result[0].length() == 0) { + // when the substring 0 is null, the substring 1 is correctly + // indented. + depth--; + emptyFirstSubString = true; + } + // the operator going in front of the result[0] string is the operator + // parameter + for (int i = 0, max = result.length; i < max; i++) { + // the new depth is the current one if this is the first substring, + // the current one + 1 otherwise. + // if the substring is a comment, use the current indentation Level + // instead of the depth + // (-1 because the ouputline increases depth). + // (fix for 1FFC72R: LFCOM:ALL - Incorrect line split in presence of + // line + // comments) + String currentResult = result[i]; + if (currentResult.length() != 0 || splitOperators[i] != 0) { + int newDepth = (currentResult.startsWith("/*") //$NON-NLS-1$ + || currentResult.startsWith("//")) //$NON-NLS-1$ + ? indentationLevel - 1 + : depth; + outputLine(currentResult, i == 0 + || (i == 1 && emptyFirstSubString) ? preIndented + : false, i == 0 ? newDepth : newDepth + 1, + splitOperators[i], i, splitLine.startSubstringsIndexes, + currentString.indexOf(currentResult)); + if (i != max - 1) { + formattedSource.append(options.lineSeparatorSequence); + increaseSplitDelta(options.lineSeparatorSequence.length); + } + } + } + if (result.length == splitOperators.length - 1) { + int lastOperator = splitOperators[result.length]; + String lastOperatorString = operatorString(lastOperator); + formattedSource.append(options.lineSeparatorSequence); + increaseSplitDelta(options.lineSeparatorSequence.length); + if (breakLineBeforeOperator(lastOperator)) { + dumpTab(depth + 1); + if (lastOperator != 0) { + if (insertSpaceBefore(lastOperator)) { + formattedSource.append(' '); + increaseSplitDelta(1); + } + formattedSource.append(lastOperatorString); + increaseSplitDelta(lastOperatorString.length()); + if (insertSpaceAfter(lastOperator) + && lastOperator != TokenNameimplements + && lastOperator != TokenNameextends) { + // && lastOperator != TokenNamethrows) { + formattedSource.append(' '); + increaseSplitDelta(1); + } + } + } + } + if (placeOperatorBehind) { + if (insertSpaceBefore(operator)) { + formattedSource.append(' '); + increaseSplitDelta(1); + } + formattedSource.append(operatorString); + // increaseSplitDelta(operatorString.length()); + } + } + + /** + * Pops the top statement of the stack if it is token + */ + private int pop(int token) { + int delta = 0; + if ((constructionsCount > 0) + && (constructions[constructionsCount - 1] == token)) { + delta--; + constructionsCount--; + } + return delta; + } + + /** + * Pops the top statement of the stack if it is a BLOCK or a + * NONINDENT_BLOCK. + */ + private int popBlock() { + int delta = 0; + if ((constructionsCount > 0) + && ((constructions[constructionsCount - 1] == BLOCK) || (constructions[constructionsCount - 1] == NONINDENT_BLOCK))) { + if (constructions[constructionsCount - 1] == BLOCK) + delta--; + constructionsCount--; + } + return delta; + } + + /** + * Pops elements until the stack is empty or the top element is + * token.
                                                      + * Does not remove token from the stack. + * + * @param token + * the token to be left as the top of the stack + */ + private int popExclusiveUntil(int token) { + int delta = 0; + int startCount = constructionsCount; + for (int i = startCount - 1; i >= 0 && constructions[i] != token; i--) { + if (constructions[i] != NONINDENT_BLOCK) + delta--; + constructionsCount--; + } + return delta; + } + + /** + * Pops elements until the stack is empty or the top element is a + * BLOCK or a NONINDENT_BLOCK.
                                                      + * Does not remove it from the stack. + */ + private int popExclusiveUntilBlock() { + int startCount = constructionsCount; + int delta = 0; + for (int i = startCount - 1; i >= 0 && constructions[i] != BLOCK + && constructions[i] != NONINDENT_BLOCK; i--) { + constructionsCount--; + delta--; + } + return delta; + } + + /** + * Pops elements until the stack is empty or the top element is a + * BLOCK, a NONINDENT_BLOCK or a + * CASE.
                                                      + * Does not remove it from the stack. + */ + private int popExclusiveUntilBlockOrCase() { + int startCount = constructionsCount; + int delta = 0; + for (int i = startCount - 1; i >= 0 && constructions[i] != BLOCK + && constructions[i] != NONINDENT_BLOCK + && constructions[i] != TokenNamecase; i--) { + constructionsCount--; + delta--; + } + return delta; + } + + /** + * Pops elements until the stack is empty or the top element is + * token.
                                                      + * Removes token from the stack too. + * + * @param token + * the token to remove from the stack + */ + private int popInclusiveUntil(int token) { + int startCount = constructionsCount; + int delta = 0; + for (int i = startCount - 1; i >= 0 && constructions[i] != token; i--) { + if (constructions[i] != NONINDENT_BLOCK) + delta--; + constructionsCount--; + } + if (constructionsCount > 0) { + if (constructions[constructionsCount - 1] != NONINDENT_BLOCK) + delta--; + constructionsCount--; + } + return delta; + } + + /** + * Pops elements until the stack is empty or the top element is a + * BLOCK or a NONINDENT_BLOCK.
                                                      + * Does not remove it from the stack. + */ + private int popInclusiveUntilBlock() { + int startCount = constructionsCount; + int delta = 0; + for (int i = startCount - 1; i >= 0 + && (constructions[i] != BLOCK && constructions[i] != NONINDENT_BLOCK); i--) { + delta--; + constructionsCount--; + } + if (constructionsCount > 0) { + if (constructions[constructionsCount - 1] == BLOCK) + delta--; + constructionsCount--; + } + return delta; + } + + /** + * Pushes a block in the stack.
                                                      + * Pushes a BLOCK if the stack is empty or if the top element + * is a BLOCK, pushes NONINDENT_BLOCK + * otherwise. Creates a new bigger array if the current one is full. + */ + private int pushBlock() { + int delta = 0; + if (constructionsCount == constructions.length) + System.arraycopy(constructions, 0, + (constructions = new int[constructionsCount * 2]), 0, + constructionsCount); + if ((constructionsCount == 0) + || (constructions[constructionsCount - 1] == BLOCK) + || (constructions[constructionsCount - 1] == NONINDENT_BLOCK) + || (constructions[constructionsCount - 1] == TokenNamecase)) { + delta++; + constructions[constructionsCount++] = BLOCK; + } else { + constructions[constructionsCount++] = NONINDENT_BLOCK; + } + return delta; + } + + /** + * Pushes token.
                                                      + * Creates a new bigger array if the current one is full. + */ + private int pushControlStatement(int token) { + if (constructionsCount == constructions.length) + System.arraycopy(constructions, 0, + (constructions = new int[constructionsCount * 2]), 0, + constructionsCount); + constructions[constructionsCount++] = token; + return 1; + } + + private static boolean separateFirstArgumentOn(int currentToken) { + // return (currentToken == TokenNameCOMMA || currentToken == + // TokenNameSEMICOLON); + return currentToken != TokenNameif && currentToken != TokenNameLPAREN + && currentToken != TokenNameNOT + && currentToken != TokenNamewhile + && currentToken != TokenNamefor + && currentToken != TokenNameforeach + && currentToken != TokenNameswitch; + } + + /** + * Set the positions to map. The mapped positions should be retrieved using + * the getMappedPositions() method. + * + * @param positions + * int[] + * @deprecated Set the positions to map using the format(String, int, int[]) + * method. + * + * @see #getMappedPositions() + */ + public void setPositionsToMap(int[] positions) { + positionsToMap = positions; + lineDelta = 0; + globalDelta = 0; + mappedPositions = new int[positions.length]; + } + + /** + * Appends a space character to the current line buffer. + */ + private void space() { + currentLineBuffer.append(' '); + increaseLineDelta(1); + } + + /** + * Splits stringToSplit on the top level token
                                                      + * If there are several identical token at the same level, the string is cut + * into many pieces. + * + * @return an object containing the operator and all the substrings or null + * if the string cannot be split + */ + public SplitLine split(String stringToSplit) { + return split(stringToSplit, 0); + } + + /** + * Splits stringToSplit on the top level token
                                                      + * If there are several identical token at the same level, the string is cut + * into many pieces. + * + * @return an object containing the operator and all the substrings or null + * if the string cannot be split + */ + public SplitLine split(String stringToSplit, int offsetInGlobalLine) { + /* + * See http://dev.eclipse.org/bugs/show_bug.cgi?id=12540 and + * http://dev.eclipse.org/bugs/show_bug.cgi?id=14387 + */ + if (stringToSplit.indexOf("//$NON-NLS") != -1) { //$NON-NLS-1$ + return null; + } + // split doesn't work correct for PHP + return null; + // local variables + // int currentToken = 0; + // int splitTokenType = 0; + // int splitTokenDepth = Integer.MAX_VALUE; + // int splitTokenPriority = Integer.MAX_VALUE; + // int[] substringsStartPositions = new int[10]; + // // contains the start position of substrings + // int[] substringsEndPositions = new int[10]; + // // contains the start position of substrings + // int substringsCount = 1; // index in the substringsStartPosition + // array + // int[] splitOperators = new int[10]; + // // contains the start position of substrings + // int splitOperatorsCount = 0; // index in the substringsStartPosition + // array + // int[] openParenthesisPosition = new int[10]; + // int openParenthesisPositionCount = 0; + // int position = 0; + // int lastOpenParenthesisPosition = -1; + // // used to remember the position of the 1st open parenthesis + // // needed for a pattern like: A.B(C); we want formatted like A.B( + // split C); + // // setup the scanner with a new source + // int lastCommentStartPosition = -1; + // // to remember the start position of the last comment + // int firstTokenOnLine = -1; + // // to remember the first token of the line + // int previousToken = -1; + // // to remember the previous token. + // splitScanner.setSource(stringToSplit.toCharArray()); + // try { + // // start the loop + // while (true) { + // // takes the next token + // try { + // if (currentToken != Scanner.TokenNameWHITESPACE) + // previousToken = currentToken; + // currentToken = splitScanner.getNextToken(); + // if (Scanner.DEBUG) { + // int currentEndPosition = splitScanner.getCurrentTokenEndPosition(); + // int currentStartPosition = splitScanner + // .getCurrentTokenStartPosition(); + // System.out.print(currentStartPosition + "," + currentEndPosition + // + ": "); + // System.out.println(scanner.toStringAction(currentToken)); + // } + // } catch (InvalidInputException e) { + // if (!handleInvalidToken(e)) + // throw e; + // currentToken = 0; + // // this value is not modify when an exception is raised. + // } + // if (currentToken == TokenNameEOF) + // break; + // if (firstTokenOnLine == -1) { + // firstTokenOnLine = currentToken; + // } + // switch (currentToken) { + // case TokenNameRBRACE : + // case TokenNameRPAREN : + // if (openParenthesisPositionCount > 0) { + // if (openParenthesisPositionCount == 1 + // && lastOpenParenthesisPosition < openParenthesisPosition[0]) { + // lastOpenParenthesisPosition = openParenthesisPosition[0]; + // } else if ((splitTokenDepth == Integer.MAX_VALUE) + // || (splitTokenDepth > openParenthesisPositionCount && + // openParenthesisPositionCount == 1)) { + // splitTokenType = 0; + // splitTokenDepth = openParenthesisPositionCount; + // splitTokenPriority = Integer.MAX_VALUE; + // substringsStartPositions[0] = 0; + // // better token means the whole line until now is the first + // // substring + // substringsCount = 1; // resets the count of substrings + // substringsEndPositions[0] = openParenthesisPosition[0]; + // // substring ends on operator start + // position = openParenthesisPosition[0]; + // // the string mustn't be cut before the closing parenthesis but + // // after the opening one. + // splitOperatorsCount = 1; // resets the count of split operators + // splitOperators[0] = 0; + // } + // openParenthesisPositionCount--; + // } + // break; + // case TokenNameLBRACE : + // case TokenNameLPAREN : + // if (openParenthesisPositionCount == openParenthesisPosition.length) { + // System + // .arraycopy( + // openParenthesisPosition, + // 0, + // (openParenthesisPosition = new int[openParenthesisPositionCount * + // 2]), + // 0, openParenthesisPositionCount); + // } + // openParenthesisPosition[openParenthesisPositionCount++] = + // splitScanner.currentPosition; + // if (currentToken == TokenNameLPAREN + // && previousToken == TokenNameRPAREN) { + // openParenthesisPosition[openParenthesisPositionCount - 1] = + // splitScanner.startPosition; + // } + // break; + // case TokenNameSEMICOLON : + // // ; + // case TokenNameCOMMA : + // // , + // case TokenNameEQUAL : + // // = + // if (openParenthesisPositionCount < splitTokenDepth + // || (openParenthesisPositionCount == splitTokenDepth && + // splitTokenPriority > getTokenPriority(currentToken))) { + // // the current token is better than the one we currently have + // // (in level or in priority if same level) + // // reset the substringsCount + // splitTokenDepth = openParenthesisPositionCount; + // splitTokenType = currentToken; + // splitTokenPriority = getTokenPriority(currentToken); + // substringsStartPositions[0] = 0; + // // better token means the whole line until now is the first + // // substring + // if (separateFirstArgumentOn(firstTokenOnLine) + // && openParenthesisPositionCount > 0) { + // substringsCount = 2; // resets the count of substrings + // substringsEndPositions[0] = openParenthesisPosition[splitTokenDepth - + // 1]; + // substringsStartPositions[1] = openParenthesisPosition[splitTokenDepth + // - 1]; + // substringsEndPositions[1] = splitScanner.startPosition; + // splitOperatorsCount = 2; // resets the count of split operators + // splitOperators[0] = 0; + // splitOperators[1] = currentToken; + // position = splitScanner.currentPosition; + // // next substring will start from operator end + // } else { + // substringsCount = 1; // resets the count of substrings + // substringsEndPositions[0] = splitScanner.startPosition; + // // substring ends on operator start + // position = splitScanner.currentPosition; + // // next substring will start from operator end + // splitOperatorsCount = 1; // resets the count of split operators + // splitOperators[0] = currentToken; + // } + // } else { + // if ((openParenthesisPositionCount == splitTokenDepth && + // splitTokenPriority == getTokenPriority(currentToken)) + // && splitTokenType != TokenNameEQUAL + // && currentToken != TokenNameEQUAL) { + // // fix for 1FG0BCN: LFCOM:WIN98 - Missing one indentation after + // // split + // // take only the 1st = into account. + // // if another token with the same priority is found, + // // push the start position of the substring and + // // push the token into the stack. + // // create a new array object if the current one is full. + // if (substringsCount == substringsStartPositions.length) { + // System + // .arraycopy( + // substringsStartPositions, + // 0, + // (substringsStartPositions = new int[substringsCount * 2]), + // 0, substringsCount); + // System.arraycopy(substringsEndPositions, 0, + // (substringsEndPositions = new int[substringsCount * 2]), + // 0, substringsCount); + // } + // if (splitOperatorsCount == splitOperators.length) { + // System.arraycopy(splitOperators, 0, + // (splitOperators = new int[splitOperatorsCount * 2]), 0, + // splitOperatorsCount); + // } + // substringsStartPositions[substringsCount] = position; + // substringsEndPositions[substringsCount++] = + // splitScanner.startPosition; + // // substring ends on operator start + // position = splitScanner.currentPosition; + // // next substring will start from operator end + // splitOperators[splitOperatorsCount++] = currentToken; + // } + // } + // break; + // case TokenNameCOLON : + // // : (15.24) + // // see 1FK7C5R, we only split on a colon, when it is associated + // // with a question-mark. + // // indeed it might appear also behind a case statement, and we do + // // not to break at this point. + // if ((splitOperatorsCount == 0) + // || splitOperators[splitOperatorsCount - 1] != TokenNameQUESTION) { + // break; + // } + // case TokenNameextends : + // case TokenNameimplements : + // //case TokenNamethrows : + // case TokenNameDOT : + // // . + // case TokenNameMULTIPLY : + // // * (15.16.1) + // case TokenNameDIVIDE : + // // / (15.16.2) + // case TokenNameREMAINDER : + // // % (15.16.3) + // case TokenNamePLUS : + // // + (15.17, 15.17.2) + // case TokenNameMINUS : + // // - (15.17.2) + // case TokenNameLEFT_SHIFT : + // // << (15.18) + // case TokenNameRIGHT_SHIFT : + // // >> (15.18) + // // case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18) + // case TokenNameLESS : + // // < (15.19.1) + // case TokenNameLESS_EQUAL : + // // <= (15.19.1) + // case TokenNameGREATER : + // // > (15.19.1) + // case TokenNameGREATER_EQUAL : + // // >= (15.19.1) + // // case TokenNameinstanceof : // instanceof + // case TokenNameEQUAL_EQUAL : + // // == (15.20, 15.20.1, 15.20.2, 15.20.3) + // case TokenNameEQUAL_EQUAL_EQUAL : + // // == (15.20, 15.20.1, 15.20.2, 15.20.3) + // case TokenNameNOT_EQUAL : + // // != (15.20, 15.20.1, 15.20.2, 15.20.3) + // case TokenNameNOT_EQUAL_EQUAL : + // // != (15.20, 15.20.1, 15.20.2, 15.20.3) + // case TokenNameAND : + // // & (15.21, 15.21.1, 15.21.2) + // case TokenNameOR : + // // | (15.21, 15.21.1, 15.21.2) + // case TokenNameXOR : + // // ^ (15.21, 15.21.1, 15.21.2) + // case TokenNameAND_AND : + // // && (15.22) + // case TokenNameOR_OR : + // // || (15.23) + // case TokenNameQUESTION : + // // ? (15.24) + // case TokenNameMULTIPLY_EQUAL : + // // *= (15.25.2) + // case TokenNameDIVIDE_EQUAL : + // // /= (15.25.2) + // case TokenNameREMAINDER_EQUAL : + // // %= (15.25.2) + // case TokenNamePLUS_EQUAL : + // // += (15.25.2) + // case TokenNameMINUS_EQUAL : + // // -= (15.25.2) + // case TokenNameLEFT_SHIFT_EQUAL : + // // <<= (15.25.2) + // case TokenNameRIGHT_SHIFT_EQUAL : + // // >>= (15.25.2) + // // case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2) + // case TokenNameAND_EQUAL : + // // &= (15.25.2) + // case TokenNameXOR_EQUAL : + // // ^= (15.25.2) + // case TokenNameOR_EQUAL : + // // |= (15.25.2) + // if ((openParenthesisPositionCount < splitTokenDepth || + // (openParenthesisPositionCount == splitTokenDepth && + // splitTokenPriority + // > getTokenPriority(currentToken))) + // && !((currentToken == TokenNamePLUS || currentToken == + // TokenNameMINUS) && (previousToken == TokenNameLBRACE + // || previousToken == TokenNameLBRACKET || splitScanner.startPosition + // == 0))) { + // // the current token is better than the one we currently have + // // (in level or in priority if same level) + // // reset the substringsCount + // splitTokenDepth = openParenthesisPositionCount; + // splitTokenType = currentToken; + // splitTokenPriority = getTokenPriority(currentToken); + // substringsStartPositions[0] = 0; + // // better token means the whole line until now is the first + // // substring + // if (separateFirstArgumentOn(firstTokenOnLine) + // && openParenthesisPositionCount > 0) { + // substringsCount = 2; // resets the count of substrings + // substringsEndPositions[0] = openParenthesisPosition[splitTokenDepth - + // 1]; + // substringsStartPositions[1] = openParenthesisPosition[splitTokenDepth + // - 1]; + // substringsEndPositions[1] = splitScanner.startPosition; + // splitOperatorsCount = 3; // resets the count of split operators + // splitOperators[0] = 0; + // splitOperators[1] = 0; + // splitOperators[2] = currentToken; + // position = splitScanner.currentPosition; + // // next substring will start from operator end + // } else { + // substringsCount = 1; // resets the count of substrings + // substringsEndPositions[0] = splitScanner.startPosition; + // // substring ends on operator start + // position = splitScanner.currentPosition; + // // next substring will start from operator end + // splitOperatorsCount = 2; // resets the count of split operators + // splitOperators[0] = 0; + // // nothing for first operand since operator will be inserted in + // // front of the second operand + // splitOperators[1] = currentToken; + // } + // } else { + // if (openParenthesisPositionCount == splitTokenDepth + // && splitTokenPriority == getTokenPriority(currentToken)) { + // // if another token with the same priority is found, + // // push the start position of the substring and + // // push the token into the stack. + // // create a new array object if the current one is full. + // if (substringsCount == substringsStartPositions.length) { + // System + // .arraycopy( + // substringsStartPositions, + // 0, + // (substringsStartPositions = new int[substringsCount * 2]), + // 0, substringsCount); + // System.arraycopy(substringsEndPositions, 0, + // (substringsEndPositions = new int[substringsCount * 2]), + // 0, substringsCount); + // } + // if (splitOperatorsCount == splitOperators.length) { + // System.arraycopy(splitOperators, 0, + // (splitOperators = new int[splitOperatorsCount * 2]), 0, + // splitOperatorsCount); + // } + // substringsStartPositions[substringsCount] = position; + // substringsEndPositions[substringsCount++] = + // splitScanner.startPosition; + // // substring ends on operator start + // position = splitScanner.currentPosition; + // // next substring will start from operator end + // splitOperators[splitOperatorsCount++] = currentToken; + // } + // } + // default : + // break; + // } + // if (isComment(currentToken)) { + // lastCommentStartPosition = splitScanner.startPosition; + // } else { + // lastCommentStartPosition = -1; + // } + // } + // } catch (InvalidInputException e) { + // return null; + // } + // // if the string cannot be split, return null. + // if (splitOperatorsCount == 0) + // return null; + // // ## SPECIAL CASES BEGIN + // if (((splitOperatorsCount == 2 && splitOperators[1] == TokenNameDOT + // && splitTokenDepth == 0 && lastOpenParenthesisPosition > -1) + // || (splitOperatorsCount > 2 && splitOperators[1] == TokenNameDOT + // && splitTokenDepth == 0 && lastOpenParenthesisPosition > -1 && + // lastOpenParenthesisPosition <= options.maxLineLength) || + // (separateFirstArgumentOn(firstTokenOnLine) + // && splitTokenDepth > 0 && lastOpenParenthesisPosition > -1)) + // && (lastOpenParenthesisPosition < splitScanner.source.length && + // splitScanner.source[lastOpenParenthesisPosition] != ')')) { + // // fix for 1FH4J2H: LFCOM:WINNT - Formatter - Empty parenthesis + // should + // // not be broken on two lines + // // only one split on a top level . + // // or more than one split on . and substring before open parenthesis + // fits + // // one line. + // // or split inside parenthesis and first token is not a for/while/if + // SplitLine sl = split( + // stringToSplit.substring(lastOpenParenthesisPosition), + // lastOpenParenthesisPosition); + // if (sl == null || sl.operators[0] != TokenNameCOMMA) { + // // trim() is used to remove the extra blanks at the end of the + // // substring. See PR 1FGYPI1 + // return new SplitLine(new int[]{0, 0}, new String[]{ + // stringToSplit.substring(0, lastOpenParenthesisPosition).trim(), + // stringToSplit.substring(lastOpenParenthesisPosition)}, new int[]{ + // offsetInGlobalLine, + // lastOpenParenthesisPosition + offsetInGlobalLine}); + // } else { + // // right substring can be split and is split on comma + // // copy substrings and operators + // // except if the 1st string is empty. + // int startIndex = (sl.substrings[0].length() == 0) ? 1 : 0; + // int subStringsLength = sl.substrings.length + 1 - startIndex; + // String[] result = new String[subStringsLength]; + // int[] startIndexes = new int[subStringsLength]; + // int operatorsLength = sl.operators.length + 1 - startIndex; + // int[] operators = new int[operatorsLength]; + // result[0] = stringToSplit.substring(0, lastOpenParenthesisPosition); + // operators[0] = 0; + // System.arraycopy(sl.startSubstringsIndexes, startIndex, startIndexes, + // 1, subStringsLength - 1); + // for (int i = subStringsLength - 1; i >= 0; i--) { + // startIndexes[i] += offsetInGlobalLine; + // } + // System.arraycopy(sl.substrings, startIndex, result, 1, + // subStringsLength - 1); + // System.arraycopy(sl.operators, startIndex, operators, 1, + // operatorsLength - 1); + // return new SplitLine(operators, result, startIndexes); + // } + // } + // // if the last token is a comment and the substring before the + // comment fits + // // on a line, + // // split before the comment and return the result. + // if (lastCommentStartPosition > -1 + // && lastCommentStartPosition < options.maxLineLength + // && splitTokenPriority > 50) { + // int end = lastCommentStartPosition; + // int start = lastCommentStartPosition; + // if (stringToSplit.charAt(end - 1) == ' ') { + // end--; + // } + // if (start != end && stringToSplit.charAt(start) == ' ') { + // start++; + // } + // return new SplitLine(new int[]{0, 0}, new String[]{ + // stringToSplit.substring(0, end), stringToSplit.substring(start)}, + // new int[]{0, start}); + // } + // if (position != stringToSplit.length()) { + // if (substringsCount == substringsStartPositions.length) { + // System.arraycopy(substringsStartPositions, 0, + // (substringsStartPositions = new int[substringsCount * 2]), 0, + // substringsCount); + // System.arraycopy(substringsEndPositions, 0, + // (substringsEndPositions = new int[substringsCount * 2]), 0, + // substringsCount); + // } + // // avoid empty extra substring, e.g. line terminated with a + // semi-colon + // substringsStartPositions[substringsCount] = position; + // substringsEndPositions[substringsCount++] = stringToSplit.length(); + // } + // if (splitOperatorsCount == splitOperators.length) { + // System.arraycopy(splitOperators, 0, + // (splitOperators = new int[splitOperatorsCount * 2]), 0, + // splitOperatorsCount); + // } + // splitOperators[splitOperatorsCount] = 0; + // // the last element of the stack is the position of the end of + // // StringToSPlit + // // +1 because the substring method excludes the last character + // String[] result = new String[substringsCount]; + // for (int i = 0; i < substringsCount; i++) { + // int start = substringsStartPositions[i]; + // int end = substringsEndPositions[i]; + // if (stringToSplit.charAt(start) == ' ') { + // start++; + // substringsStartPositions[i]++; + // } + // if (end != start && stringToSplit.charAt(end - 1) == ' ') { + // end--; + // } + // result[i] = stringToSplit.substring(start, end); + // substringsStartPositions[i] += offsetInGlobalLine; + // } + // if (splitOperatorsCount > substringsCount) { + // System.arraycopy(substringsStartPositions, 0, + // (substringsStartPositions = new int[splitOperatorsCount]), 0, + // substringsCount); + // System.arraycopy(substringsEndPositions, 0, + // (substringsEndPositions = new int[splitOperatorsCount]), 0, + // substringsCount); + // for (int i = substringsCount; i < splitOperatorsCount; i++) { + // substringsStartPositions[i] = position; + // substringsEndPositions[i] = position; + // } + // System.arraycopy(splitOperators, 0, + // (splitOperators = new int[splitOperatorsCount]), 0, + // splitOperatorsCount); + // } else { + // System.arraycopy(substringsStartPositions, 0, + // (substringsStartPositions = new int[substringsCount]), 0, + // substringsCount); + // System.arraycopy(substringsEndPositions, 0, + // (substringsEndPositions = new int[substringsCount]), 0, + // substringsCount); + // System.arraycopy(splitOperators, 0, + // (splitOperators = new int[substringsCount]), 0, substringsCount); + // } + // SplitLine splitLine = new SplitLine(splitOperators, result, + // substringsStartPositions); + // return splitLine; + } + + private void updateMappedPositions(int startPosition) { + if (positionsToMap == null) { + return; + } + char[] source = scanner.source; + int sourceLength = source.length; + while (indexToMap < positionsToMap.length + && positionsToMap[indexToMap] <= startPosition) { + int posToMap = positionsToMap[indexToMap]; + if (posToMap < 0 || posToMap >= sourceLength) { + // protection against out of bounds position + if (posToMap == sourceLength) { + mappedPositions[indexToMap] = formattedSource.length(); + } + indexToMap = positionsToMap.length; // no more mapping + return; + } + if (CharOperation.isWhitespace(source[posToMap])) { + mappedPositions[indexToMap] = startPosition + globalDelta + + lineDelta; + } else { + if (posToMap == sourceLength - 1) { + mappedPositions[indexToMap] = startPosition + globalDelta + + lineDelta; + } else { + mappedPositions[indexToMap] = posToMap + globalDelta + + lineDelta; + } + } + indexToMap++; + } + } + + private void updateMappedPositionsWhileSplitting(int startPosition, + int endPosition) { + if (mappedPositions == null || mappedPositions.length == indexInMap) + return; + while (indexInMap < mappedPositions.length + && startPosition <= mappedPositions[indexInMap] + && mappedPositions[indexInMap] < endPosition + && indexInMap < indexToMap) { + mappedPositions[indexInMap] += splitDelta; + indexInMap++; + } + } + + private int getLength(String s, int tabDepth) { + int length = 0; + for (int i = 0; i < tabDepth; i++) { + length += options.tabSize; + } + for (int i = 0, max = s.length(); i < max; i++) { + char currentChar = s.charAt(i); + switch (currentChar) { + case '\t': + length += options.tabSize; + break; + default: + length++; + } + } + return length; + } + + /** + * Sets the initial indentation level + * + * @param indentationLevel + * new indentation level + * + * @deprecated + */ + public void setInitialIndentationLevel(int newIndentationLevel) { + this.initialIndentationLevel = currentLineIndentationLevel = indentationLevel = newIndentationLevel; } - return mappedPositions; - } - - /** - * Returns the priority of the token given as argument
                                                      - * The most prioritary the token is, the smallest the return value is. - * - * @return the priority of token - * @param token - * the token of which the priority is requested - */ - private static int getTokenPriority(int token) { - switch (token) { - case TokenNameextends: - // case TokenNameimplements : - // case TokenNamethrows : - return 10; - case TokenNameSEMICOLON: - // ; - return 20; - case TokenNameCOMMA: - // , - return 25; - case TokenNameEQUAL: - // = - return 30; - case TokenNameAND_AND: - // && - case TokenNameOR_OR: - // || - return 40; - case TokenNameQUESTION: - // ? - case TokenNameCOLON: - // : - return 50; // it's better cutting on ?: than on ; - case TokenNameEQUAL_EQUAL: - // == - case TokenNameEQUAL_EQUAL_EQUAL: - // === - case TokenNameNOT_EQUAL: - // != - case TokenNameNOT_EQUAL_EQUAL: - // != - return 60; - case TokenNameLESS: - // < - case TokenNameLESS_EQUAL: - // <= - case TokenNameGREATER: - // > - case TokenNameGREATER_EQUAL: - // >= - // case TokenNameinstanceof : // instanceof - return 70; - case TokenNamePLUS: - // + - case TokenNameMINUS: - // - - return 80; - case TokenNameMULTIPLY: - // * - case TokenNameDIVIDE: - // / - case TokenNameREMAINDER: - // % - return 90; - case TokenNameLEFT_SHIFT: - // << - case TokenNameRIGHT_SHIFT: - // >> - // case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> - return 100; - case TokenNameAND: - // & - case TokenNameOR: - // | - case TokenNameXOR: - // ^ - return 110; - case TokenNameMULTIPLY_EQUAL: - // *= - case TokenNameDIVIDE_EQUAL: - // /= - case TokenNameREMAINDER_EQUAL: - // %= - case TokenNamePLUS_EQUAL: - // += - case TokenNameMINUS_EQUAL: - // -= - case TokenNameLEFT_SHIFT_EQUAL: - // <<= - case TokenNameRIGHT_SHIFT_EQUAL: - // >>= - // case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= - case TokenNameAND_EQUAL: - // &= - case TokenNameXOR_EQUAL: - // ^= - case TokenNameOR_EQUAL: - // .= - case TokenNameDOT_EQUAL: - // |= - return 120; - case TokenNameDOT: - // . - return 130; - default: - return Integer.MAX_VALUE; - } - } - - /** - * Handles the exception raised when an invalid token is encountered. Returns true if the exception has been handled, false - * otherwise. - */ - private boolean handleInvalidToken(Exception e) { - if (e.getMessage().equals(Scanner.INVALID_CHARACTER_CONSTANT) || e.getMessage().equals(Scanner.INVALID_CHAR_IN_STRING) - || e.getMessage().equals(Scanner.INVALID_ESCAPE)) { - return true; - } - return false; - } - - private final void increaseGlobalDelta(int offset) { - globalDelta += offset; - } - - private final void increaseLineDelta(int offset) { - lineDelta += offset; - } - - private final void increaseSplitDelta(int offset) { - splitDelta += offset; - } - - /** - * Returns true if a space has to be inserted after operator false otherwise. - */ - private boolean insertSpaceAfter(int token) { - switch (token) { - case TokenNameLPAREN: - case TokenNameNOT: - case TokenNameTWIDDLE: - case 0: - // no token - case TokenNameWHITESPACE: - case TokenNameLBRACKET: - case TokenNameDOLLAR: - case Scanner.TokenNameCOMMENT_LINE: - return false; - default: - return true; - } - } - - /** - * Returns true if a space has to be inserted before operator false otherwise.
                                                      - * Cannot be static as it uses the code formatter options (to know if the compact assignment mode is on). - */ - private boolean insertSpaceBefore(int token) { - switch (token) { - case TokenNameEQUAL: - return (!options.compactAssignmentMode); - default: - return false; - } - } - - private static boolean isComment(int token) { - boolean result = token == Scanner.TokenNameCOMMENT_BLOCK || token == Scanner.TokenNameCOMMENT_LINE - || token == Scanner.TokenNameCOMMENT_PHPDOC; - return result; - } - - private static boolean isLiteralToken(int token) { - boolean result = token == TokenNameIntegerLiteral - // || token == TokenNameLongLiteral - // || token == TokenNameFloatingPointLiteral - || token == TokenNameDoubleLiteral - // || token == TokenNameCharacterLiteral - || token == TokenNameStringDoubleQuote; - return result; - } - - /** - * If the length of oneLineBuffer exceeds maxLineLength, it is split and the result is dumped in - * formattedSource - * - * @param newLineCount - * the number of new lines to append - */ - private void newLine(int newLineCount) { - // format current line - splitDelta = 0; - beginningOfLineIndex = formattedSource.length(); - String currentLine = currentLineBuffer.toString(); - if (containsOpenCloseBraces) { - containsOpenCloseBraces = false; - outputLine(currentLine, false, indentationLevelForOpenCloseBraces, 0, -1, null, 0); - indentationLevelForOpenCloseBraces = currentLineIndentationLevel; - } else { - outputLine(currentLine, false, currentLineIndentationLevel, 0, -1, null, 0); - } - // dump line break(s) - for (int i = 0; i < newLineCount; i++) { - formattedSource.append(options.lineSeparatorSequence); - increaseSplitDelta(options.lineSeparatorSequence.length); - } - // reset formatter for next line - int currentLength = currentLine.length(); - currentLineBuffer = new StringBuffer(currentLength > maxLineSize ? maxLineSize = currentLength : maxLineSize); - increaseGlobalDelta(splitDelta); - increaseGlobalDelta(lineDelta); - lineDelta = 0; - currentLineIndentationLevel = initialIndentationLevel; - } - - private String operatorString(int operator) { - switch (operator) { - case TokenNameextends: - return "extends"; //$NON-NLS-1$ - // case TokenNameimplements : - // return "implements"; //$NON-NLS-1$ - // - // case TokenNamethrows : - // return "throws"; //$NON-NLS-1$ - case TokenNameSEMICOLON: - // ; - return ";"; //$NON-NLS-1$ - case TokenNameCOMMA: - // , - return ","; //$NON-NLS-1$ - case TokenNameEQUAL: - // = - return "="; //$NON-NLS-1$ - case TokenNameAND_AND: - // && (15.22) - return "&&"; //$NON-NLS-1$ - case TokenNameOR_OR: - // || (15.23) - return "||"; //$NON-NLS-1$ - case TokenNameQUESTION: - // ? (15.24) - return "?"; //$NON-NLS-1$ - case TokenNameCOLON: - // : (15.24) - return ":"; //$NON-NLS-1$ - case TokenNamePAAMAYIM_NEKUDOTAYIM: - // : (15.24) - return "::"; //$NON-NLS-1$ - case TokenNameEQUAL_EQUAL: - // == (15.20, 15.20.1, 15.20.2, 15.20.3) - return "=="; //$NON-NLS-1$ - case TokenNameEQUAL_EQUAL_EQUAL: - // == (15.20, 15.20.1, 15.20.2, 15.20.3) - return "==="; //$NON-NLS-1$ - case TokenNameEQUAL_GREATER: - // -= (15.25.2) - return "=>"; //$NON-NLS-1$ - case TokenNameNOT_EQUAL: - // != (15.20, 15.20.1, 15.20.2, 15.20.3) - return "!="; //$NON-NLS-1$ - case TokenNameNOT_EQUAL_EQUAL: - // != (15.20, 15.20.1, 15.20.2, 15.20.3) - return "!=="; //$NON-NLS-1$ - case TokenNameLESS: - // < (15.19.1) - return "<"; //$NON-NLS-1$ - case TokenNameLESS_EQUAL: - // <= (15.19.1) - return "<="; //$NON-NLS-1$ - case TokenNameGREATER: - // > (15.19.1) - return ">"; //$NON-NLS-1$ - case TokenNameGREATER_EQUAL: - // >= (15.19.1) - return ">="; //$NON-NLS-1$ - // case TokenNameinstanceof : // instanceof - // return "instanceof"; //$NON-NLS-1$ - case TokenNamePLUS: - // + (15.17, 15.17.2) - return "+"; //$NON-NLS-1$ - case TokenNameMINUS: - // - (15.17.2) - return "-"; //$NON-NLS-1$ - case TokenNameMULTIPLY: - // * (15.16.1) - return "*"; //$NON-NLS-1$ - case TokenNameDIVIDE: - // / (15.16.2) - return "/"; //$NON-NLS-1$ - case TokenNameREMAINDER: - // % (15.16.3) - return "%"; //$NON-NLS-1$ - case TokenNameLEFT_SHIFT: - // << (15.18) - return "<<"; //$NON-NLS-1$ - case TokenNameRIGHT_SHIFT: - // >> (15.18) - return ">>"; //$NON-NLS-1$ - // case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18) - // return ">>>"; //$NON-NLS-1$ - case TokenNameAND: - // & (15.21, 15.21.1, 15.21.2) - return "&"; //$NON-NLS-1$ - case TokenNameOR: - // | (15.21, 15.21.1, 15.21.2) - return "|"; //$NON-NLS-1$ - case TokenNameXOR: - // ^ (15.21, 15.21.1, 15.21.2) - return "^"; //$NON-NLS-1$ - case TokenNameMULTIPLY_EQUAL: - // *= (15.25.2) - return "*="; //$NON-NLS-1$ - case TokenNameDIVIDE_EQUAL: - // /= (15.25.2) - return "/="; //$NON-NLS-1$ - case TokenNameREMAINDER_EQUAL: - // %= (15.25.2) - return "%="; //$NON-NLS-1$ - case TokenNamePLUS_EQUAL: - // += (15.25.2) - return "+="; //$NON-NLS-1$ - case TokenNameMINUS_EQUAL: - // -= (15.25.2) - return "-="; //$NON-NLS-1$ - case TokenNameMINUS_GREATER: - // -= (15.25.2) - return "->"; //$NON-NLS-1$ - case TokenNameLEFT_SHIFT_EQUAL: - // <<= (15.25.2) - return "<<="; //$NON-NLS-1$ - case TokenNameRIGHT_SHIFT_EQUAL: - // >>= (15.25.2) - return ">>="; //$NON-NLS-1$ - // case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2) - // return ">>>="; //$NON-NLS-1$ - case TokenNameAND_EQUAL: - // &= (15.25.2) - return "&="; //$NON-NLS-1$ - case TokenNameXOR_EQUAL: - // ^= (15.25.2) - return "^="; //$NON-NLS-1$ - case TokenNameOR_EQUAL: - // |= (15.25.2) - return "|="; //$NON-NLS-1$ - case TokenNameDOT_EQUAL: - // .= - return ".="; //$NON-NLS-1$ - case TokenNameDOT: - // . - return "."; //$NON-NLS-1$ - default: - return ""; //$NON-NLS-1$ - } - } - - /** - * Appends stringToOutput to the formatted output.
                                                      - * If it contains \n, append a LINE_SEPARATOR and indent after it. - */ - private void output(String stringToOutput) { - char currentCharacter; - for (int i = 0, max = stringToOutput.length(); i < max; i++) { - currentCharacter = stringToOutput.charAt(i); - if (currentCharacter != '\t') { - currentLineBuffer.append(currentCharacter); - } - } - } - - private void outputCurrentTokenWithoutIndent(int token, int newLineCount) { - newLine(newLineCount); - formattedSource.append(scanner.source, scanner.startPosition, scanner.currentPosition - scanner.startPosition); - } - - /** - * Appends token to the formatted output.
                                                      - * If it contains \n, append a LINE_SEPARATOR and indent after it. - */ - private void outputCurrentToken(int token) { - char[] source = scanner.source; - int startPosition = scanner.startPosition; - switch (token) { - case Scanner.TokenNameCOMMENT_PHPDOC: - case Scanner.TokenNameCOMMENT_BLOCK: - case Scanner.TokenNameCOMMENT_LINE: - boolean endOfLine = false; - int currentCommentOffset = getCurrentCommentOffset(); - int beginningOfLineSpaces = 0; - endOfLine = false; - currentCommentOffset = getCurrentCommentOffset(); - beginningOfLineSpaces = 0; - boolean pendingCarriageReturn = false; - for (int i = startPosition, max = scanner.currentPosition; i < max; i++) { - char currentCharacter = source[i]; - updateMappedPositions(i); - switch (currentCharacter) { - case '\r': - pendingCarriageReturn = true; - endOfLine = true; - break; - case '\n': - if (pendingCarriageReturn) { - increaseGlobalDelta(options.lineSeparatorSequence.length - 2); - } else { - increaseGlobalDelta(options.lineSeparatorSequence.length - 1); - } - pendingCarriageReturn = false; - currentLineBuffer.append(options.lineSeparatorSequence); - beginningOfLineSpaces = 0; - endOfLine = true; - break; - case '\t': - if (pendingCarriageReturn) { - pendingCarriageReturn = false; - increaseGlobalDelta(options.lineSeparatorSequence.length - 1); - currentLineBuffer.append(options.lineSeparatorSequence); - beginningOfLineSpaces = 0; - endOfLine = true; - } - if (endOfLine) { - // we remove a maximum of currentCommentOffset characters (tabs - // are converted to space numbers). - beginningOfLineSpaces += options.tabSize; - if (beginningOfLineSpaces > currentCommentOffset) { - currentLineBuffer.append(currentCharacter); - } else { - increaseGlobalDelta(-1); - } - } else { - currentLineBuffer.append(currentCharacter); - } - break; - case ' ': - if (pendingCarriageReturn) { - pendingCarriageReturn = false; - increaseGlobalDelta(options.lineSeparatorSequence.length - 1); - currentLineBuffer.append(options.lineSeparatorSequence); - beginningOfLineSpaces = 0; - endOfLine = true; - } - if (endOfLine) { - // we remove a maximum of currentCommentOffset characters (tabs - // are converted to space numbers). - beginningOfLineSpaces++; - if (beginningOfLineSpaces > currentCommentOffset) { - currentLineBuffer.append(currentCharacter); - } else { - increaseGlobalDelta(-1); - } - } else { - currentLineBuffer.append(currentCharacter); - } - break; - default: - if (pendingCarriageReturn) { - pendingCarriageReturn = false; - increaseGlobalDelta(options.lineSeparatorSequence.length - 1); - currentLineBuffer.append(options.lineSeparatorSequence); - beginningOfLineSpaces = 0; - endOfLine = true; - } else { - beginningOfLineSpaces = 0; - currentLineBuffer.append(currentCharacter); - endOfLine = false; - } - } - } - updateMappedPositions(scanner.currentPosition - 1); - multipleLineCommentCounter++; - break; - default: - for (int i = startPosition, max = scanner.currentPosition; i < max; i++) { - char currentCharacter = source[i]; - updateMappedPositions(i); - currentLineBuffer.append(currentCharacter); - } - } - } - - /** - * Outputs currentString:
                                                      - *
                                                        - *
                                                      • If its length is < maxLineLength, output - *
                                                      • Otherwise it is split. - *
                                                      - * - * @param currentString - * string to output - * @param preIndented - * whether the string to output was pre-indented - * @param depth - * number of indentation to put in front of currentString - * @param operator - * value of the operator belonging to currentString. - */ - private void outputLine(String currentString, boolean preIndented, int depth, int operator, int substringIndex, - int[] startSubstringIndexes, int offsetInGlobalLine) { - boolean emptyFirstSubString = false; - String operatorString = operatorString(operator); - boolean placeOperatorBehind = !breakLineBeforeOperator(operator); - boolean placeOperatorAhead = !placeOperatorBehind; - // dump prefix operator? - if (placeOperatorAhead) { - if (!preIndented) { - dumpTab(depth); - preIndented = true; - } - if (operator != 0) { - if (insertSpaceBefore(operator)) { - formattedSource.append(' '); - increaseSplitDelta(1); - } - formattedSource.append(operatorString); - increaseSplitDelta(operatorString.length()); - if (insertSpaceAfter(operator) && operator != TokenNameimplements && operator != TokenNameextends) { - // && operator != TokenNamethrows) { - formattedSource.append(' '); - increaseSplitDelta(1); - } - } - } - SplitLine splitLine = null; - if (options.maxLineLength == 0 || getLength(currentString, depth) < options.maxLineLength - || (splitLine = split(currentString, offsetInGlobalLine)) == null) { - // depending on the type of operator, outputs new line before of after - // dumping it - // indent before postfix operator - // indent also when the line cannot be split - if (operator == TokenNameextends || operator == TokenNameimplements) { - // || operator == TokenNamethrows) { - formattedSource.append(' '); - increaseSplitDelta(1); - } - if (placeOperatorBehind) { - if (!preIndented) { - dumpTab(depth); - } - } - int max = currentString.length(); - if (multipleLineCommentCounter != 0) { - try { - BufferedReader reader = new BufferedReader(new StringReader(currentString)); - String line = reader.readLine(); - while (line != null) { - updateMappedPositionsWhileSplitting(beginningOfLineIndex, beginningOfLineIndex + line.length() - + options.lineSeparatorSequence.length); - formattedSource.append(line); - beginningOfLineIndex = beginningOfLineIndex + line.length(); - if ((line = reader.readLine()) != null) { - formattedSource.append(options.lineSeparatorSequence); - beginningOfLineIndex += options.lineSeparatorSequence.length; - dumpTab(currentLineIndentationLevel); - } - } - reader.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } else { - updateMappedPositionsWhileSplitting(beginningOfLineIndex, beginningOfLineIndex + max); - for (int i = 0; i < max; i++) { - char currentChar = currentString.charAt(i); - switch (currentChar) { - case '\r': - break; - case '\n': - if (i != max - 1) { - // fix for 1FFYL5C: LFCOM:ALL - Incorrect indentation when - // split with a comment inside a condition - // a substring cannot end with a lineSeparatorSequence, - // except if it has been added by format() after a one-line - // comment - formattedSource.append(options.lineSeparatorSequence); - // 1FGDDV6: LFCOM:WIN98 - Weird splitting on message expression - dumpTab(depth - 1); - } - break; - default: - formattedSource.append(currentChar); - } - } - } - // update positions inside the mappedPositions table - if (substringIndex != -1) { - if (multipleLineCommentCounter == 0) { - int startPosition = beginningOfLineIndex + startSubstringIndexes[substringIndex]; - updateMappedPositionsWhileSplitting(startPosition, startPosition + max); - } - // compute the splitDelta resulting with the operator and blank removal - if (substringIndex + 1 != startSubstringIndexes.length) { - increaseSplitDelta(startSubstringIndexes[substringIndex] + max - startSubstringIndexes[substringIndex + 1]); - } - } - // dump postfix operator? - if (placeOperatorBehind) { - if (insertSpaceBefore(operator)) { - formattedSource.append(' '); - if (operator != 0) { - increaseSplitDelta(1); - } - } - formattedSource.append(operatorString); - if (operator != 0) { - increaseSplitDelta(operatorString.length()); - } - } - return; - } - // fix for 1FG0BA3: LFCOM:WIN98 - Weird splitting on interfaces - // extends has to stand alone on a line when currentString has been split. - if (options.maxLineLength != 0 && splitLine != null && (operator == TokenNameextends)) { - // || operator == TokenNameimplements - // || operator == TokenNamethrows)) { - formattedSource.append(options.lineSeparatorSequence); - increaseSplitDelta(options.lineSeparatorSequence.length); - dumpTab(depth + 1); - } else { - if (operator == TokenNameextends) { - // || operator == TokenNameimplements - // || operator == TokenNamethrows) { - formattedSource.append(' '); - increaseSplitDelta(1); - } - } - // perform actual splitting - String result[] = splitLine.substrings; - int[] splitOperators = splitLine.operators; - if (result[0].length() == 0) { - // when the substring 0 is null, the substring 1 is correctly indented. - depth--; - emptyFirstSubString = true; - } - // the operator going in front of the result[0] string is the operator - // parameter - for (int i = 0, max = result.length; i < max; i++) { - // the new depth is the current one if this is the first substring, - // the current one + 1 otherwise. - // if the substring is a comment, use the current indentation Level - // instead of the depth - // (-1 because the ouputline increases depth). - // (fix for 1FFC72R: LFCOM:ALL - Incorrect line split in presence of line - // comments) - String currentResult = result[i]; - if (currentResult.length() != 0 || splitOperators[i] != 0) { - int newDepth = (currentResult.startsWith("/*") //$NON-NLS-1$ - || currentResult.startsWith("//")) //$NON-NLS-1$ - ? indentationLevel - 1 : depth; - outputLine(currentResult, i == 0 || (i == 1 && emptyFirstSubString) ? preIndented : false, - i == 0 ? newDepth : newDepth + 1, splitOperators[i], i, splitLine.startSubstringsIndexes, currentString - .indexOf(currentResult)); - if (i != max - 1) { - formattedSource.append(options.lineSeparatorSequence); - increaseSplitDelta(options.lineSeparatorSequence.length); - } - } - } - if (result.length == splitOperators.length - 1) { - int lastOperator = splitOperators[result.length]; - String lastOperatorString = operatorString(lastOperator); - formattedSource.append(options.lineSeparatorSequence); - increaseSplitDelta(options.lineSeparatorSequence.length); - if (breakLineBeforeOperator(lastOperator)) { - dumpTab(depth + 1); - if (lastOperator != 0) { - if (insertSpaceBefore(lastOperator)) { - formattedSource.append(' '); - increaseSplitDelta(1); - } - formattedSource.append(lastOperatorString); - increaseSplitDelta(lastOperatorString.length()); - if (insertSpaceAfter(lastOperator) && lastOperator != TokenNameimplements && lastOperator != TokenNameextends) { - // && lastOperator != TokenNamethrows) { - formattedSource.append(' '); - increaseSplitDelta(1); - } - } - } - } - if (placeOperatorBehind) { - if (insertSpaceBefore(operator)) { - formattedSource.append(' '); - increaseSplitDelta(1); - } - formattedSource.append(operatorString); - //increaseSplitDelta(operatorString.length()); - } - } - - /** - * Pops the top statement of the stack if it is token - */ - private int pop(int token) { - int delta = 0; - if ((constructionsCount > 0) && (constructions[constructionsCount - 1] == token)) { - delta--; - constructionsCount--; - } - return delta; - } - - /** - * Pops the top statement of the stack if it is a BLOCK or a NONINDENT_BLOCK. - */ - private int popBlock() { - int delta = 0; - if ((constructionsCount > 0) - && ((constructions[constructionsCount - 1] == BLOCK) || (constructions[constructionsCount - 1] == NONINDENT_BLOCK))) { - if (constructions[constructionsCount - 1] == BLOCK) - delta--; - constructionsCount--; - } - return delta; - } - - /** - * Pops elements until the stack is empty or the top element is token.
                                                      - * Does not remove token from the stack. - * - * @param token - * the token to be left as the top of the stack - */ - private int popExclusiveUntil(int token) { - int delta = 0; - int startCount = constructionsCount; - for (int i = startCount - 1; i >= 0 && constructions[i] != token; i--) { - if (constructions[i] != NONINDENT_BLOCK) - delta--; - constructionsCount--; - } - return delta; - } - - /** - * Pops elements until the stack is empty or the top element is a BLOCK or a NONINDENT_BLOCK.
                                                      - * Does not remove it from the stack. - */ - private int popExclusiveUntilBlock() { - int startCount = constructionsCount; - int delta = 0; - for (int i = startCount - 1; i >= 0 && constructions[i] != BLOCK && constructions[i] != NONINDENT_BLOCK; i--) { - constructionsCount--; - delta--; - } - return delta; - } - - /** - * Pops elements until the stack is empty or the top element is a BLOCK, a NONINDENT_BLOCK or a - * CASE.
                                                      - * Does not remove it from the stack. - */ - private int popExclusiveUntilBlockOrCase() { - int startCount = constructionsCount; - int delta = 0; - for (int i = startCount - 1; i >= 0 && constructions[i] != BLOCK && constructions[i] != NONINDENT_BLOCK - && constructions[i] != TokenNamecase; i--) { - constructionsCount--; - delta--; - } - return delta; - } - - /** - * Pops elements until the stack is empty or the top element is token.
                                                      - * Removes token from the stack too. - * - * @param token - * the token to remove from the stack - */ - private int popInclusiveUntil(int token) { - int startCount = constructionsCount; - int delta = 0; - for (int i = startCount - 1; i >= 0 && constructions[i] != token; i--) { - if (constructions[i] != NONINDENT_BLOCK) - delta--; - constructionsCount--; - } - if (constructionsCount > 0) { - if (constructions[constructionsCount - 1] != NONINDENT_BLOCK) - delta--; - constructionsCount--; - } - return delta; - } - - /** - * Pops elements until the stack is empty or the top element is a BLOCK or a NONINDENT_BLOCK.
                                                      - * Does not remove it from the stack. - */ - private int popInclusiveUntilBlock() { - int startCount = constructionsCount; - int delta = 0; - for (int i = startCount - 1; i >= 0 && (constructions[i] != BLOCK && constructions[i] != NONINDENT_BLOCK); i--) { - delta--; - constructionsCount--; - } - if (constructionsCount > 0) { - if (constructions[constructionsCount - 1] == BLOCK) - delta--; - constructionsCount--; - } - return delta; - } - - /** - * Pushes a block in the stack.
                                                      - * Pushes a BLOCK if the stack is empty or if the top element is a BLOCK, pushes - * NONINDENT_BLOCK otherwise. Creates a new bigger array if the current one is full. - */ - private int pushBlock() { - int delta = 0; - if (constructionsCount == constructions.length) - System.arraycopy(constructions, 0, (constructions = new int[constructionsCount * 2]), 0, constructionsCount); - if ((constructionsCount == 0) || (constructions[constructionsCount - 1] == BLOCK) - || (constructions[constructionsCount - 1] == NONINDENT_BLOCK) || (constructions[constructionsCount - 1] == TokenNamecase)) { - delta++; - constructions[constructionsCount++] = BLOCK; - } else { - constructions[constructionsCount++] = NONINDENT_BLOCK; - } - return delta; - } - - /** - * Pushes token.
                                                      - * Creates a new bigger array if the current one is full. - */ - private int pushControlStatement(int token) { - if (constructionsCount == constructions.length) - System.arraycopy(constructions, 0, (constructions = new int[constructionsCount * 2]), 0, constructionsCount); - constructions[constructionsCount++] = token; - return 1; - } - - private static boolean separateFirstArgumentOn(int currentToken) { - //return (currentToken == TokenNameCOMMA || currentToken == - // TokenNameSEMICOLON); - return currentToken != TokenNameif && currentToken != TokenNameLPAREN && currentToken != TokenNameNOT - && currentToken != TokenNamewhile && currentToken != TokenNamefor && currentToken != TokenNameforeach - && currentToken != TokenNameswitch; - } - - /** - * Set the positions to map. The mapped positions should be retrieved using the getMappedPositions() method. - * - * @param positions - * int[] - * @deprecated Set the positions to map using the format(String, int, int[]) method. - * - * @see #getMappedPositions() - */ - public void setPositionsToMap(int[] positions) { - positionsToMap = positions; - lineDelta = 0; - globalDelta = 0; - mappedPositions = new int[positions.length]; - } - - /** - * Appends a space character to the current line buffer. - */ - private void space() { - currentLineBuffer.append(' '); - increaseLineDelta(1); - } - - /** - * Splits stringToSplit on the top level token
                                                      - * If there are several identical token at the same level, the string is cut into many pieces. - * - * @return an object containing the operator and all the substrings or null if the string cannot be split - */ - public SplitLine split(String stringToSplit) { - return split(stringToSplit, 0); - } - - /** - * Splits stringToSplit on the top level token
                                                      - * If there are several identical token at the same level, the string is cut into many pieces. - * - * @return an object containing the operator and all the substrings or null if the string cannot be split - */ - public SplitLine split(String stringToSplit, int offsetInGlobalLine) { - /* - * See http://dev.eclipse.org/bugs/show_bug.cgi?id=12540 and http://dev.eclipse.org/bugs/show_bug.cgi?id=14387 - */ - if (stringToSplit.indexOf("//$NON-NLS") != -1) { //$NON-NLS-1$ - return null; - } - // split doesn't work correct for PHP - return null; - // local variables - // int currentToken = 0; - // int splitTokenType = 0; - // int splitTokenDepth = Integer.MAX_VALUE; - // int splitTokenPriority = Integer.MAX_VALUE; - // int[] substringsStartPositions = new int[10]; - // // contains the start position of substrings - // int[] substringsEndPositions = new int[10]; - // // contains the start position of substrings - // int substringsCount = 1; // index in the substringsStartPosition array - // int[] splitOperators = new int[10]; - // // contains the start position of substrings - // int splitOperatorsCount = 0; // index in the substringsStartPosition array - // int[] openParenthesisPosition = new int[10]; - // int openParenthesisPositionCount = 0; - // int position = 0; - // int lastOpenParenthesisPosition = -1; - // // used to remember the position of the 1st open parenthesis - // // needed for a pattern like: A.B(C); we want formatted like A.B( split C); - // // setup the scanner with a new source - // int lastCommentStartPosition = -1; - // // to remember the start position of the last comment - // int firstTokenOnLine = -1; - // // to remember the first token of the line - // int previousToken = -1; - // // to remember the previous token. - // splitScanner.setSource(stringToSplit.toCharArray()); - // try { - // // start the loop - // while (true) { - // // takes the next token - // try { - // if (currentToken != Scanner.TokenNameWHITESPACE) - // previousToken = currentToken; - // currentToken = splitScanner.getNextToken(); - // if (Scanner.DEBUG) { - // int currentEndPosition = splitScanner.getCurrentTokenEndPosition(); - // int currentStartPosition = splitScanner - // .getCurrentTokenStartPosition(); - // System.out.print(currentStartPosition + "," + currentEndPosition - // + ": "); - // System.out.println(scanner.toStringAction(currentToken)); - // } - // } catch (InvalidInputException e) { - // if (!handleInvalidToken(e)) - // throw e; - // currentToken = 0; - // // this value is not modify when an exception is raised. - // } - // if (currentToken == TokenNameEOF) - // break; - // if (firstTokenOnLine == -1) { - // firstTokenOnLine = currentToken; - // } - // switch (currentToken) { - // case TokenNameRBRACE : - // case TokenNameRPAREN : - // if (openParenthesisPositionCount > 0) { - // if (openParenthesisPositionCount == 1 - // && lastOpenParenthesisPosition < openParenthesisPosition[0]) { - // lastOpenParenthesisPosition = openParenthesisPosition[0]; - // } else if ((splitTokenDepth == Integer.MAX_VALUE) - // || (splitTokenDepth > openParenthesisPositionCount && openParenthesisPositionCount == 1)) { - // splitTokenType = 0; - // splitTokenDepth = openParenthesisPositionCount; - // splitTokenPriority = Integer.MAX_VALUE; - // substringsStartPositions[0] = 0; - // // better token means the whole line until now is the first - // // substring - // substringsCount = 1; // resets the count of substrings - // substringsEndPositions[0] = openParenthesisPosition[0]; - // // substring ends on operator start - // position = openParenthesisPosition[0]; - // // the string mustn't be cut before the closing parenthesis but - // // after the opening one. - // splitOperatorsCount = 1; // resets the count of split operators - // splitOperators[0] = 0; - // } - // openParenthesisPositionCount--; - // } - // break; - // case TokenNameLBRACE : - // case TokenNameLPAREN : - // if (openParenthesisPositionCount == openParenthesisPosition.length) { - // System - // .arraycopy( - // openParenthesisPosition, - // 0, - // (openParenthesisPosition = new int[openParenthesisPositionCount * 2]), - // 0, openParenthesisPositionCount); - // } - // openParenthesisPosition[openParenthesisPositionCount++] = splitScanner.currentPosition; - // if (currentToken == TokenNameLPAREN - // && previousToken == TokenNameRPAREN) { - // openParenthesisPosition[openParenthesisPositionCount - 1] = splitScanner.startPosition; - // } - // break; - // case TokenNameSEMICOLON : - // // ; - // case TokenNameCOMMA : - // // , - // case TokenNameEQUAL : - // // = - // if (openParenthesisPositionCount < splitTokenDepth - // || (openParenthesisPositionCount == splitTokenDepth && splitTokenPriority > getTokenPriority(currentToken))) { - // // the current token is better than the one we currently have - // // (in level or in priority if same level) - // // reset the substringsCount - // splitTokenDepth = openParenthesisPositionCount; - // splitTokenType = currentToken; - // splitTokenPriority = getTokenPriority(currentToken); - // substringsStartPositions[0] = 0; - // // better token means the whole line until now is the first - // // substring - // if (separateFirstArgumentOn(firstTokenOnLine) - // && openParenthesisPositionCount > 0) { - // substringsCount = 2; // resets the count of substrings - // substringsEndPositions[0] = openParenthesisPosition[splitTokenDepth - 1]; - // substringsStartPositions[1] = openParenthesisPosition[splitTokenDepth - 1]; - // substringsEndPositions[1] = splitScanner.startPosition; - // splitOperatorsCount = 2; // resets the count of split operators - // splitOperators[0] = 0; - // splitOperators[1] = currentToken; - // position = splitScanner.currentPosition; - // // next substring will start from operator end - // } else { - // substringsCount = 1; // resets the count of substrings - // substringsEndPositions[0] = splitScanner.startPosition; - // // substring ends on operator start - // position = splitScanner.currentPosition; - // // next substring will start from operator end - // splitOperatorsCount = 1; // resets the count of split operators - // splitOperators[0] = currentToken; - // } - // } else { - // if ((openParenthesisPositionCount == splitTokenDepth && splitTokenPriority == getTokenPriority(currentToken)) - // && splitTokenType != TokenNameEQUAL - // && currentToken != TokenNameEQUAL) { - // // fix for 1FG0BCN: LFCOM:WIN98 - Missing one indentation after - // // split - // // take only the 1st = into account. - // // if another token with the same priority is found, - // // push the start position of the substring and - // // push the token into the stack. - // // create a new array object if the current one is full. - // if (substringsCount == substringsStartPositions.length) { - // System - // .arraycopy( - // substringsStartPositions, - // 0, - // (substringsStartPositions = new int[substringsCount * 2]), - // 0, substringsCount); - // System.arraycopy(substringsEndPositions, 0, - // (substringsEndPositions = new int[substringsCount * 2]), - // 0, substringsCount); - // } - // if (splitOperatorsCount == splitOperators.length) { - // System.arraycopy(splitOperators, 0, - // (splitOperators = new int[splitOperatorsCount * 2]), 0, - // splitOperatorsCount); - // } - // substringsStartPositions[substringsCount] = position; - // substringsEndPositions[substringsCount++] = splitScanner.startPosition; - // // substring ends on operator start - // position = splitScanner.currentPosition; - // // next substring will start from operator end - // splitOperators[splitOperatorsCount++] = currentToken; - // } - // } - // break; - // case TokenNameCOLON : - // // : (15.24) - // // see 1FK7C5R, we only split on a colon, when it is associated - // // with a question-mark. - // // indeed it might appear also behind a case statement, and we do - // // not to break at this point. - // if ((splitOperatorsCount == 0) - // || splitOperators[splitOperatorsCount - 1] != TokenNameQUESTION) { - // break; - // } - // case TokenNameextends : - // case TokenNameimplements : - // //case TokenNamethrows : - // case TokenNameDOT : - // // . - // case TokenNameMULTIPLY : - // // * (15.16.1) - // case TokenNameDIVIDE : - // // / (15.16.2) - // case TokenNameREMAINDER : - // // % (15.16.3) - // case TokenNamePLUS : - // // + (15.17, 15.17.2) - // case TokenNameMINUS : - // // - (15.17.2) - // case TokenNameLEFT_SHIFT : - // // << (15.18) - // case TokenNameRIGHT_SHIFT : - // // >> (15.18) - // // case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18) - // case TokenNameLESS : - // // < (15.19.1) - // case TokenNameLESS_EQUAL : - // // <= (15.19.1) - // case TokenNameGREATER : - // // > (15.19.1) - // case TokenNameGREATER_EQUAL : - // // >= (15.19.1) - // // case TokenNameinstanceof : // instanceof - // case TokenNameEQUAL_EQUAL : - // // == (15.20, 15.20.1, 15.20.2, 15.20.3) - // case TokenNameEQUAL_EQUAL_EQUAL : - // // == (15.20, 15.20.1, 15.20.2, 15.20.3) - // case TokenNameNOT_EQUAL : - // // != (15.20, 15.20.1, 15.20.2, 15.20.3) - // case TokenNameNOT_EQUAL_EQUAL : - // // != (15.20, 15.20.1, 15.20.2, 15.20.3) - // case TokenNameAND : - // // & (15.21, 15.21.1, 15.21.2) - // case TokenNameOR : - // // | (15.21, 15.21.1, 15.21.2) - // case TokenNameXOR : - // // ^ (15.21, 15.21.1, 15.21.2) - // case TokenNameAND_AND : - // // && (15.22) - // case TokenNameOR_OR : - // // || (15.23) - // case TokenNameQUESTION : - // // ? (15.24) - // case TokenNameMULTIPLY_EQUAL : - // // *= (15.25.2) - // case TokenNameDIVIDE_EQUAL : - // // /= (15.25.2) - // case TokenNameREMAINDER_EQUAL : - // // %= (15.25.2) - // case TokenNamePLUS_EQUAL : - // // += (15.25.2) - // case TokenNameMINUS_EQUAL : - // // -= (15.25.2) - // case TokenNameLEFT_SHIFT_EQUAL : - // // <<= (15.25.2) - // case TokenNameRIGHT_SHIFT_EQUAL : - // // >>= (15.25.2) - // // case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2) - // case TokenNameAND_EQUAL : - // // &= (15.25.2) - // case TokenNameXOR_EQUAL : - // // ^= (15.25.2) - // case TokenNameOR_EQUAL : - // // |= (15.25.2) - // if ((openParenthesisPositionCount < splitTokenDepth || (openParenthesisPositionCount == splitTokenDepth && splitTokenPriority - // > getTokenPriority(currentToken))) - // && !((currentToken == TokenNamePLUS || currentToken == TokenNameMINUS) && (previousToken == TokenNameLBRACE - // || previousToken == TokenNameLBRACKET || splitScanner.startPosition == 0))) { - // // the current token is better than the one we currently have - // // (in level or in priority if same level) - // // reset the substringsCount - // splitTokenDepth = openParenthesisPositionCount; - // splitTokenType = currentToken; - // splitTokenPriority = getTokenPriority(currentToken); - // substringsStartPositions[0] = 0; - // // better token means the whole line until now is the first - // // substring - // if (separateFirstArgumentOn(firstTokenOnLine) - // && openParenthesisPositionCount > 0) { - // substringsCount = 2; // resets the count of substrings - // substringsEndPositions[0] = openParenthesisPosition[splitTokenDepth - 1]; - // substringsStartPositions[1] = openParenthesisPosition[splitTokenDepth - 1]; - // substringsEndPositions[1] = splitScanner.startPosition; - // splitOperatorsCount = 3; // resets the count of split operators - // splitOperators[0] = 0; - // splitOperators[1] = 0; - // splitOperators[2] = currentToken; - // position = splitScanner.currentPosition; - // // next substring will start from operator end - // } else { - // substringsCount = 1; // resets the count of substrings - // substringsEndPositions[0] = splitScanner.startPosition; - // // substring ends on operator start - // position = splitScanner.currentPosition; - // // next substring will start from operator end - // splitOperatorsCount = 2; // resets the count of split operators - // splitOperators[0] = 0; - // // nothing for first operand since operator will be inserted in - // // front of the second operand - // splitOperators[1] = currentToken; - // } - // } else { - // if (openParenthesisPositionCount == splitTokenDepth - // && splitTokenPriority == getTokenPriority(currentToken)) { - // // if another token with the same priority is found, - // // push the start position of the substring and - // // push the token into the stack. - // // create a new array object if the current one is full. - // if (substringsCount == substringsStartPositions.length) { - // System - // .arraycopy( - // substringsStartPositions, - // 0, - // (substringsStartPositions = new int[substringsCount * 2]), - // 0, substringsCount); - // System.arraycopy(substringsEndPositions, 0, - // (substringsEndPositions = new int[substringsCount * 2]), - // 0, substringsCount); - // } - // if (splitOperatorsCount == splitOperators.length) { - // System.arraycopy(splitOperators, 0, - // (splitOperators = new int[splitOperatorsCount * 2]), 0, - // splitOperatorsCount); - // } - // substringsStartPositions[substringsCount] = position; - // substringsEndPositions[substringsCount++] = splitScanner.startPosition; - // // substring ends on operator start - // position = splitScanner.currentPosition; - // // next substring will start from operator end - // splitOperators[splitOperatorsCount++] = currentToken; - // } - // } - // default : - // break; - // } - // if (isComment(currentToken)) { - // lastCommentStartPosition = splitScanner.startPosition; - // } else { - // lastCommentStartPosition = -1; - // } - // } - // } catch (InvalidInputException e) { - // return null; - // } - // // if the string cannot be split, return null. - // if (splitOperatorsCount == 0) - // return null; - // // ## SPECIAL CASES BEGIN - // if (((splitOperatorsCount == 2 && splitOperators[1] == TokenNameDOT - // && splitTokenDepth == 0 && lastOpenParenthesisPosition > -1) - // || (splitOperatorsCount > 2 && splitOperators[1] == TokenNameDOT - // && splitTokenDepth == 0 && lastOpenParenthesisPosition > -1 && lastOpenParenthesisPosition <= options.maxLineLength) || - // (separateFirstArgumentOn(firstTokenOnLine) - // && splitTokenDepth > 0 && lastOpenParenthesisPosition > -1)) - // && (lastOpenParenthesisPosition < splitScanner.source.length && splitScanner.source[lastOpenParenthesisPosition] != ')')) { - // // fix for 1FH4J2H: LFCOM:WINNT - Formatter - Empty parenthesis should - // // not be broken on two lines - // // only one split on a top level . - // // or more than one split on . and substring before open parenthesis fits - // // one line. - // // or split inside parenthesis and first token is not a for/while/if - // SplitLine sl = split( - // stringToSplit.substring(lastOpenParenthesisPosition), - // lastOpenParenthesisPosition); - // if (sl == null || sl.operators[0] != TokenNameCOMMA) { - // // trim() is used to remove the extra blanks at the end of the - // // substring. See PR 1FGYPI1 - // return new SplitLine(new int[]{0, 0}, new String[]{ - // stringToSplit.substring(0, lastOpenParenthesisPosition).trim(), - // stringToSplit.substring(lastOpenParenthesisPosition)}, new int[]{ - // offsetInGlobalLine, - // lastOpenParenthesisPosition + offsetInGlobalLine}); - // } else { - // // right substring can be split and is split on comma - // // copy substrings and operators - // // except if the 1st string is empty. - // int startIndex = (sl.substrings[0].length() == 0) ? 1 : 0; - // int subStringsLength = sl.substrings.length + 1 - startIndex; - // String[] result = new String[subStringsLength]; - // int[] startIndexes = new int[subStringsLength]; - // int operatorsLength = sl.operators.length + 1 - startIndex; - // int[] operators = new int[operatorsLength]; - // result[0] = stringToSplit.substring(0, lastOpenParenthesisPosition); - // operators[0] = 0; - // System.arraycopy(sl.startSubstringsIndexes, startIndex, startIndexes, - // 1, subStringsLength - 1); - // for (int i = subStringsLength - 1; i >= 0; i--) { - // startIndexes[i] += offsetInGlobalLine; - // } - // System.arraycopy(sl.substrings, startIndex, result, 1, - // subStringsLength - 1); - // System.arraycopy(sl.operators, startIndex, operators, 1, - // operatorsLength - 1); - // return new SplitLine(operators, result, startIndexes); - // } - // } - // // if the last token is a comment and the substring before the comment fits - // // on a line, - // // split before the comment and return the result. - // if (lastCommentStartPosition > -1 - // && lastCommentStartPosition < options.maxLineLength - // && splitTokenPriority > 50) { - // int end = lastCommentStartPosition; - // int start = lastCommentStartPosition; - // if (stringToSplit.charAt(end - 1) == ' ') { - // end--; - // } - // if (start != end && stringToSplit.charAt(start) == ' ') { - // start++; - // } - // return new SplitLine(new int[]{0, 0}, new String[]{ - // stringToSplit.substring(0, end), stringToSplit.substring(start)}, - // new int[]{0, start}); - // } - // if (position != stringToSplit.length()) { - // if (substringsCount == substringsStartPositions.length) { - // System.arraycopy(substringsStartPositions, 0, - // (substringsStartPositions = new int[substringsCount * 2]), 0, - // substringsCount); - // System.arraycopy(substringsEndPositions, 0, - // (substringsEndPositions = new int[substringsCount * 2]), 0, - // substringsCount); - // } - // // avoid empty extra substring, e.g. line terminated with a semi-colon - // substringsStartPositions[substringsCount] = position; - // substringsEndPositions[substringsCount++] = stringToSplit.length(); - // } - // if (splitOperatorsCount == splitOperators.length) { - // System.arraycopy(splitOperators, 0, - // (splitOperators = new int[splitOperatorsCount * 2]), 0, - // splitOperatorsCount); - // } - // splitOperators[splitOperatorsCount] = 0; - // // the last element of the stack is the position of the end of - // // StringToSPlit - // // +1 because the substring method excludes the last character - // String[] result = new String[substringsCount]; - // for (int i = 0; i < substringsCount; i++) { - // int start = substringsStartPositions[i]; - // int end = substringsEndPositions[i]; - // if (stringToSplit.charAt(start) == ' ') { - // start++; - // substringsStartPositions[i]++; - // } - // if (end != start && stringToSplit.charAt(end - 1) == ' ') { - // end--; - // } - // result[i] = stringToSplit.substring(start, end); - // substringsStartPositions[i] += offsetInGlobalLine; - // } - // if (splitOperatorsCount > substringsCount) { - // System.arraycopy(substringsStartPositions, 0, - // (substringsStartPositions = new int[splitOperatorsCount]), 0, - // substringsCount); - // System.arraycopy(substringsEndPositions, 0, - // (substringsEndPositions = new int[splitOperatorsCount]), 0, - // substringsCount); - // for (int i = substringsCount; i < splitOperatorsCount; i++) { - // substringsStartPositions[i] = position; - // substringsEndPositions[i] = position; - // } - // System.arraycopy(splitOperators, 0, - // (splitOperators = new int[splitOperatorsCount]), 0, - // splitOperatorsCount); - // } else { - // System.arraycopy(substringsStartPositions, 0, - // (substringsStartPositions = new int[substringsCount]), 0, - // substringsCount); - // System.arraycopy(substringsEndPositions, 0, - // (substringsEndPositions = new int[substringsCount]), 0, - // substringsCount); - // System.arraycopy(splitOperators, 0, - // (splitOperators = new int[substringsCount]), 0, substringsCount); - // } - // SplitLine splitLine = new SplitLine(splitOperators, result, - // substringsStartPositions); - // return splitLine; - } - - private void updateMappedPositions(int startPosition) { - if (positionsToMap == null) { - return; - } - char[] source = scanner.source; - int sourceLength = source.length; - while (indexToMap < positionsToMap.length && positionsToMap[indexToMap] <= startPosition) { - int posToMap = positionsToMap[indexToMap]; - if (posToMap < 0 || posToMap >= sourceLength) { - // protection against out of bounds position - if (posToMap == sourceLength) { - mappedPositions[indexToMap] = formattedSource.length(); - } - indexToMap = positionsToMap.length; // no more mapping - return; - } - if (CharOperation.isWhitespace(source[posToMap])) { - mappedPositions[indexToMap] = startPosition + globalDelta + lineDelta; - } else { - if (posToMap == sourceLength - 1) { - mappedPositions[indexToMap] = startPosition + globalDelta + lineDelta; - } else { - mappedPositions[indexToMap] = posToMap + globalDelta + lineDelta; - } - } - indexToMap++; - } - } - - private void updateMappedPositionsWhileSplitting(int startPosition, int endPosition) { - if (mappedPositions == null || mappedPositions.length == indexInMap) - return; - while (indexInMap < mappedPositions.length && startPosition <= mappedPositions[indexInMap] - && mappedPositions[indexInMap] < endPosition && indexInMap < indexToMap) { - mappedPositions[indexInMap] += splitDelta; - indexInMap++; - } - } - - private int getLength(String s, int tabDepth) { - int length = 0; - for (int i = 0; i < tabDepth; i++) { - length += options.tabSize; - } - for (int i = 0, max = s.length(); i < max; i++) { - char currentChar = s.charAt(i); - switch (currentChar) { - case '\t': - length += options.tabSize; - break; - default: - length++; - } - } - return length; - } - - /** - * Sets the initial indentation level - * - * @param indentationLevel - * new indentation level - * - * @deprecated - */ - public void setInitialIndentationLevel(int newIndentationLevel) { - this.initialIndentationLevel = currentLineIndentationLevel = indentationLevel = newIndentationLevel; - } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/OptimizedReplaceEdit.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/OptimizedReplaceEdit.java index f745158..4429d74 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/OptimizedReplaceEdit.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/OptimizedReplaceEdit.java @@ -11,17 +11,19 @@ package net.sourceforge.phpdt.internal.formatter; class OptimizedReplaceEdit { - + int offset; + int length; + String replacement; - + OptimizedReplaceEdit(int offset, int length, String replacement) { this.offset = offset; this.length = length; this.replacement = replacement; } - + public String toString() { return "(" + this.offset + ", length " + this.length + " :>" + this.replacement + "<"; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$ } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/align/AlignmentException.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/align/AlignmentException.java index 5b4b667..82adfab 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/align/AlignmentException.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/align/AlignmentException.java @@ -11,20 +11,23 @@ package net.sourceforge.phpdt.internal.formatter.align; /** - * Exception used to backtrack and break available alignments - * When the exception is thrown, it is assumed that some alignment will be changed. - * + * Exception used to backtrack and break available alignments When the exception + * is thrown, it is assumed that some alignment will be changed. + * * @since 2.1 */ public class AlignmentException extends RuntimeException { - + public static final int LINE_TOO_LONG = 1; + public static final int ALIGN_TOO_SMALL = 2; - + int reason; + int value; + public int relativeDepth; - + public AlignmentException(int reason, int relativeDepth) { this(reason, 0, relativeDepth); } @@ -34,21 +37,19 @@ public class AlignmentException extends RuntimeException { this.value = value; this.relativeDepth = relativeDepth; } - - public String toString(){ + + public String toString() { StringBuffer buffer = new StringBuffer(10); - switch(this.reason){ - case LINE_TOO_LONG : - buffer.append("LINE_TOO_LONG"); //$NON-NLS-1$ - break; - case ALIGN_TOO_SMALL : - buffer.append("ALIGN_TOO_SMALL"); //$NON-NLS-1$ - break; + switch (this.reason) { + case LINE_TOO_LONG: + buffer.append("LINE_TOO_LONG"); //$NON-NLS-1$ + break; + case ALIGN_TOO_SMALL: + buffer.append("ALIGN_TOO_SMALL"); //$NON-NLS-1$ + break; } - buffer - .append("\n"); //$NON-NLS-1$ + buffer.append("\n"); //$NON-NLS-1$ return buffer.toString(); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/impl/FormatterOptions.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/impl/FormatterOptions.java index 8784cce..b379e6a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/impl/FormatterOptions.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/impl/FormatterOptions.java @@ -14,203 +14,238 @@ import java.util.Map; public class FormatterOptions { - /** - * Option IDs - */ - public static final String OPTION_InsertNewlineBeforeOpeningBrace = "net.sourceforge.phpeclipse.formatter.newline.openingBrace"; //$NON-NLS-1$ - public static final String OPTION_InsertNewlineInControlStatement = "net.sourceforge.phpeclipse.formatter.newline.controlStatement"; //$NON-NLS-1$ - // public static final String OPTION_InsertNewLineBetweenElseAndIf = "net.sourceforge.phpeclipse.formatter.newline.elseIf"; //$NON-NLS-1$ - public static final String OPTION_InsertNewLineInEmptyBlock = "net.sourceforge.phpeclipse.formatter.newline.emptyBlock"; //$NON-NLS-1$ - public static final String OPTION_ClearAllBlankLines = "net.sourceforge.phpeclipse.formatter.newline.clearAll"; //$NON-NLS-1$ - public static final String OPTION_SplitLineExceedingLength = "net.sourceforge.phpeclipse.formatter.lineSplit"; //$NON-NLS-1$ - public static final String OPTION_CompactAssignment = "net.sourceforge.phpeclipse.formatter.style.assignment"; //$NON-NLS-1$ - public static final String OPTION_TabulationChar = "net.sourceforge.phpeclipse.formatter.tabulation.char"; //$NON-NLS-1$ - public static final String OPTION_TabulationSize = "net.sourceforge.phpeclipse.formatter.tabulation.size"; //$NON-NLS-1$ - public static final String OPTION_CompactDereferencing = "net.sourceforge.phpeclipse.formatter.style.assignment"; - // TODO: add the checkbox in the preferences panel ; load/save - - public static final String INSERT = "insert"; //$NON-NLS-1$ - public static final String DO_NOT_INSERT = "do not insert"; //$NON-NLS-1$ - public static final String PRESERVE_ONE = "preserve one"; //$NON-NLS-1$ - public static final String CLEAR_ALL = "clear all"; //$NON-NLS-1$ - public static final String NORMAL = "normal"; //$NON-NLS-1$ - public static final String COMPACT = "compact"; //$NON-NLS-1$ - public static final String TAB = "tab"; //$NON-NLS-1$ - public static final String SPACE = "space"; //$NON-NLS-1$ - - // by default, do not insert blank line before opening brace - public boolean newLineBeforeOpeningBraceMode = false; - - // by default, do not insert blank line behind keywords (ELSE, CATCH, FINALLY,...) in control statements - public boolean newlineInControlStatementMode = false; - - // by default, preserve one blank line per sequence of blank lines - public boolean clearAllBlankLinesMode = false; - - // line splitting will occur when line exceeds this length - public int maxLineLength = 80; - - public boolean compactAssignmentMode = false; - // if isTrue, assignments look like x= 12 (not like x = 12); - public boolean compactDereferencingMode = true; - // if isTrue, dereferencing look like $obj->method (not like $obj -> method); - - //number of consecutive spaces used to replace the tab char - public int tabSize = 4; // n spaces for one tab - public boolean indentWithTab = true; - - //public boolean compactElseIfMode = true; - // if true, else and if are kept on the same line. - public boolean newLineInEmptyBlockMode = true; - // if false, no new line in {} if it's empty. - - public char[] lineSeparatorSequence = System.getProperty("line.separator").toCharArray(); //$NON-NLS-1$ - /** - * Initializing the formatter options with default settings - */ - public FormatterOptions() { - } - /** - * Initializing the formatter options with external settings - */ - public FormatterOptions(Map settings) { - if (settings == null) - return; - - // filter options which are related to the assist component - Object[] entries = settings.entrySet().toArray(); - for (int i = 0, max = entries.length; i < max; i++) { - Map.Entry entry = (Map.Entry) entries[i]; - if (!(entry.getKey() instanceof String)) - continue; - if (!(entry.getValue() instanceof String)) - continue; - String optionID = (String) entry.getKey(); - String optionValue = (String) entry.getValue(); - - if (optionID.equals(OPTION_InsertNewlineBeforeOpeningBrace)) { - if (optionValue.equals(INSERT)) { - this.newLineBeforeOpeningBraceMode = true; - } else if (optionValue.equals(DO_NOT_INSERT)) { - this.newLineBeforeOpeningBraceMode = false; - } - continue; - } - if (optionID.equals(OPTION_InsertNewlineInControlStatement)) { - if (optionValue.equals(INSERT)) { - this.newlineInControlStatementMode = true; - } else if (optionValue.equals(DO_NOT_INSERT)) { - this.newlineInControlStatementMode = false; - } - continue; - } - if (optionID.equals(OPTION_ClearAllBlankLines)) { - if (optionValue.equals(CLEAR_ALL)) { - this.clearAllBlankLinesMode = true; - } else if (optionValue.equals(PRESERVE_ONE)) { - this.clearAllBlankLinesMode = false; - } - continue; - } -// if (optionID.equals(OPTION_InsertNewLineBetweenElseAndIf)) { -// if (optionValue.equals(INSERT)) { -// this.compactElseIfMode = false; -// } else if (optionValue.equals(DO_NOT_INSERT)) { -// this.compactElseIfMode = true; -// } -// continue; -// } - if (optionID.equals(OPTION_InsertNewLineInEmptyBlock)) { - if (optionValue.equals(INSERT)) { - this.newLineInEmptyBlockMode = true; - } else if (optionValue.equals(DO_NOT_INSERT)) { - this.newLineInEmptyBlockMode = false; - } - continue; - } - if (optionID.equals(OPTION_SplitLineExceedingLength)) { - try { - int val = Integer.parseInt(optionValue); - if (val >= 0) - this.maxLineLength = val; - } catch (NumberFormatException e) { - } - } - if (optionID.equals(OPTION_CompactAssignment)) { - if (optionValue.equals(COMPACT)) { - this.compactAssignmentMode = true; - } else if (optionValue.equals(NORMAL)) { - this.compactAssignmentMode = false; - } - continue; - } - if (optionID.equals(OPTION_TabulationChar)) { - if (optionValue.equals(TAB)) { - this.indentWithTab = true; - } else if (optionValue.equals(SPACE)) { - this.indentWithTab = false; - } - continue; - } - if (optionID.equals(OPTION_TabulationSize)) { - try { - int val = Integer.parseInt(optionValue); - if (val > 0) - this.tabSize = val; - } catch (NumberFormatException e) { - } - } - } - } - - /** - * - * @return int - */ - public int getMaxLineLength() { - return maxLineLength; - } - public int getTabSize() { - return tabSize; - } - public boolean isAddingNewLineBeforeOpeningBrace() { - return newLineBeforeOpeningBraceMode; - } - public boolean isAddingNewLineInControlStatement() { - return newlineInControlStatementMode; - } - public boolean isAddingNewLineInEmptyBlock() { - return newLineInEmptyBlockMode; - } - public boolean isClearingAllBlankLines() { - return clearAllBlankLinesMode; - } - public boolean isCompactingAssignment() { - return compactAssignmentMode; - } - public boolean isCompactingDereferencing() { - return compactDereferencingMode; - } -// public boolean isCompactingElseIf() { -// return compactElseIfMode; -// } - public boolean isUsingTabForIndenting() { - return indentWithTab; - } - public void setLineSeparator(String lineSeparator) { - lineSeparatorSequence = lineSeparator.toCharArray(); - } - /** - * @deprecated - should use a Map when creating the options. - */ - public void setMaxLineLength(int maxLineLength) { - this.maxLineLength = maxLineLength; - } - /** - * @deprecated - should use a Map when creating the options. - */ -// public void setCompactElseIfMode(boolean flag) { -// compactElseIfMode = flag; -// } + /** + * Option IDs + */ + public static final String OPTION_InsertNewlineBeforeOpeningBrace = "net.sourceforge.phpeclipse.formatter.newline.openingBrace"; //$NON-NLS-1$ + public static final String OPTION_InsertNewlineInControlStatement = "net.sourceforge.phpeclipse.formatter.newline.controlStatement"; //$NON-NLS-1$ + + // public static final String OPTION_InsertNewLineBetweenElseAndIf = + // "net.sourceforge.phpeclipse.formatter.newline.elseIf"; //$NON-NLS-1$ + public static final String OPTION_InsertNewLineInEmptyBlock = "net.sourceforge.phpeclipse.formatter.newline.emptyBlock"; //$NON-NLS-1$ + + public static final String OPTION_ClearAllBlankLines = "net.sourceforge.phpeclipse.formatter.newline.clearAll"; //$NON-NLS-1$ + + public static final String OPTION_SplitLineExceedingLength = "net.sourceforge.phpeclipse.formatter.lineSplit"; //$NON-NLS-1$ + + public static final String OPTION_CompactAssignment = "net.sourceforge.phpeclipse.formatter.style.assignment"; //$NON-NLS-1$ + + public static final String OPTION_TabulationChar = "net.sourceforge.phpeclipse.formatter.tabulation.char"; //$NON-NLS-1$ + + public static final String OPTION_TabulationSize = "net.sourceforge.phpeclipse.formatter.tabulation.size"; //$NON-NLS-1$ + + public static final String OPTION_CompactDereferencing = "net.sourceforge.phpeclipse.formatter.style.assignment"; + + // TODO: add the checkbox in the preferences panel ; load/save + + public static final String INSERT = "insert"; //$NON-NLS-1$ + + public static final String DO_NOT_INSERT = "do not insert"; //$NON-NLS-1$ + + public static final String PRESERVE_ONE = "preserve one"; //$NON-NLS-1$ + + public static final String CLEAR_ALL = "clear all"; //$NON-NLS-1$ + + public static final String NORMAL = "normal"; //$NON-NLS-1$ + + public static final String COMPACT = "compact"; //$NON-NLS-1$ + + public static final String TAB = "tab"; //$NON-NLS-1$ + + public static final String SPACE = "space"; //$NON-NLS-1$ + + // by default, do not insert blank line before opening brace + public boolean newLineBeforeOpeningBraceMode = false; + + // by default, do not insert blank line behind keywords (ELSE, CATCH, + // FINALLY,...) in control statements + public boolean newlineInControlStatementMode = false; + + // by default, preserve one blank line per sequence of blank lines + public boolean clearAllBlankLinesMode = false; + + // line splitting will occur when line exceeds this length + public int maxLineLength = 80; + + public boolean compactAssignmentMode = false; + + // if isTrue, assignments look like x= 12 (not like x = 12); + public boolean compactDereferencingMode = true; + + // if isTrue, dereferencing look like $obj->method (not like $obj -> + // method); + + // number of consecutive spaces used to replace the tab char + public int tabSize = 4; // n spaces for one tab + + public boolean indentWithTab = true; + + // public boolean compactElseIfMode = true; + // if true, else and if are kept on the same line. + public boolean newLineInEmptyBlockMode = true; + + // if false, no new line in {} if it's empty. + + public char[] lineSeparatorSequence = System + .getProperty("line.separator").toCharArray(); //$NON-NLS-1$ + + /** + * Initializing the formatter options with default settings + */ + public FormatterOptions() { + } + + /** + * Initializing the formatter options with external settings + */ + public FormatterOptions(Map settings) { + if (settings == null) + return; + + // filter options which are related to the assist component + Object[] entries = settings.entrySet().toArray(); + for (int i = 0, max = entries.length; i < max; i++) { + Map.Entry entry = (Map.Entry) entries[i]; + if (!(entry.getKey() instanceof String)) + continue; + if (!(entry.getValue() instanceof String)) + continue; + String optionID = (String) entry.getKey(); + String optionValue = (String) entry.getValue(); + + if (optionID.equals(OPTION_InsertNewlineBeforeOpeningBrace)) { + if (optionValue.equals(INSERT)) { + this.newLineBeforeOpeningBraceMode = true; + } else if (optionValue.equals(DO_NOT_INSERT)) { + this.newLineBeforeOpeningBraceMode = false; + } + continue; + } + if (optionID.equals(OPTION_InsertNewlineInControlStatement)) { + if (optionValue.equals(INSERT)) { + this.newlineInControlStatementMode = true; + } else if (optionValue.equals(DO_NOT_INSERT)) { + this.newlineInControlStatementMode = false; + } + continue; + } + if (optionID.equals(OPTION_ClearAllBlankLines)) { + if (optionValue.equals(CLEAR_ALL)) { + this.clearAllBlankLinesMode = true; + } else if (optionValue.equals(PRESERVE_ONE)) { + this.clearAllBlankLinesMode = false; + } + continue; + } + // if (optionID.equals(OPTION_InsertNewLineBetweenElseAndIf)) { + // if (optionValue.equals(INSERT)) { + // this.compactElseIfMode = false; + // } else if (optionValue.equals(DO_NOT_INSERT)) { + // this.compactElseIfMode = true; + // } + // continue; + // } + if (optionID.equals(OPTION_InsertNewLineInEmptyBlock)) { + if (optionValue.equals(INSERT)) { + this.newLineInEmptyBlockMode = true; + } else if (optionValue.equals(DO_NOT_INSERT)) { + this.newLineInEmptyBlockMode = false; + } + continue; + } + if (optionID.equals(OPTION_SplitLineExceedingLength)) { + try { + int val = Integer.parseInt(optionValue); + if (val >= 0) + this.maxLineLength = val; + } catch (NumberFormatException e) { + } + } + if (optionID.equals(OPTION_CompactAssignment)) { + if (optionValue.equals(COMPACT)) { + this.compactAssignmentMode = true; + } else if (optionValue.equals(NORMAL)) { + this.compactAssignmentMode = false; + } + continue; + } + if (optionID.equals(OPTION_TabulationChar)) { + if (optionValue.equals(TAB)) { + this.indentWithTab = true; + } else if (optionValue.equals(SPACE)) { + this.indentWithTab = false; + } + continue; + } + if (optionID.equals(OPTION_TabulationSize)) { + try { + int val = Integer.parseInt(optionValue); + if (val > 0) + this.tabSize = val; + } catch (NumberFormatException e) { + } + } + } + } + + /** + * + * @return int + */ + public int getMaxLineLength() { + return maxLineLength; + } + + public int getTabSize() { + return tabSize; + } + + public boolean isAddingNewLineBeforeOpeningBrace() { + return newLineBeforeOpeningBraceMode; + } + + public boolean isAddingNewLineInControlStatement() { + return newlineInControlStatementMode; + } + + public boolean isAddingNewLineInEmptyBlock() { + return newLineInEmptyBlockMode; + } + + public boolean isClearingAllBlankLines() { + return clearAllBlankLinesMode; + } + + public boolean isCompactingAssignment() { + return compactAssignmentMode; + } + + public boolean isCompactingDereferencing() { + return compactDereferencingMode; + } + + // public boolean isCompactingElseIf() { + // return compactElseIfMode; + // } + public boolean isUsingTabForIndenting() { + return indentWithTab; + } + + public void setLineSeparator(String lineSeparator) { + lineSeparatorSequence = lineSeparator.toCharArray(); + } + + /** + * @deprecated - should use a Map when creating the options. + */ + public void setMaxLineLength(int maxLineLength) { + this.maxLineLength = maxLineLength; + } + /** + * @deprecated - should use a Map when creating the options. + */ + // public void setCompactElseIfMode(boolean flag) { + // compactElseIfMode = flag; + // } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/impl/SplitLine.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/impl/SplitLine.java index 745aaa3..90297d7 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/impl/SplitLine.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/impl/SplitLine.java @@ -12,205 +12,210 @@ package net.sourceforge.phpdt.internal.formatter.impl; import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; -/** Represents a split line: contains an operator and all substrings -*/ +/** + * Represents a split line: contains an operator and all substrings + */ public class SplitLine implements ITerminalSymbols { - public int[] operators; // the operator on which the string was split. - public String[] substrings; - public int[] startSubstringsIndexes; - /** - * SplitLine constructor comment. - */ - public SplitLine(int[] operators, String[] substrings) { - this(operators, substrings, null); - } - /** - * SplitLine constructor comment. - */ - public SplitLine(int[] operators, String[] substrings, int[] startIndexes) { - super(); - this.operators = operators; - this.substrings = substrings; - this.startSubstringsIndexes = startIndexes; - } - /** - * Prints a nice representation of the receiver - * @return java.lang.String - */ - public String toString() { - StringBuffer result = new StringBuffer(); - String operatorString = new String(); - - for (int i = 0, max = substrings.length; i < max; i++) { - int currentOperator = operators[i]; - String currentString = substrings[i]; - boolean placeOperatorAhead = - currentOperator != TokenNameCOMMA - && currentOperator != TokenNameSEMICOLON; - boolean placeOperatorBehind = - currentOperator == TokenNameCOMMA - || currentOperator == TokenNameSEMICOLON; - - switch (currentOperator) { - case TokenNameextends : - operatorString = "extends"; //$NON-NLS-1$ - break; - // case TokenNameimplements: - // operatorString="implements"; //$NON-NLS-1$ - // break; - // case TokenNamethrows: - // operatorString="throws"; //$NON-NLS-1$ - // break; - case TokenNameSEMICOLON : // ; - operatorString = ";"; //$NON-NLS-1$ - break; - case TokenNameCOMMA : // , - operatorString = ","; //$NON-NLS-1$ - break; - case TokenNameEQUAL : // = - operatorString = "="; //$NON-NLS-1$ - break; - case TokenNameAND_AND : // && (15.22) - operatorString = "&&"; //$NON-NLS-1$ - break; - case TokenNameOR_OR : // || (15.23) - operatorString = "||"; //$NON-NLS-1$ - break; - case TokenNameQUESTION : // ? (15.24) - operatorString = "?"; //$NON-NLS-1$ - break; - - case TokenNameCOLON : // : (15.24) - operatorString = ":"; //$NON-NLS-1$ - break; - case TokenNameEQUAL_EQUAL : // == (15.20, 15.20.1, 15.20.2, 15.20.3) - operatorString = "=="; //$NON-NLS-1$ - break; - - case TokenNameNOT_EQUAL : // != (15.20, 15.20.1, 15.20.2, 15.20.3) - operatorString = "!="; //$NON-NLS-1$ - break; - - case TokenNameLESS : // < (15.19.1) - operatorString = "<"; //$NON-NLS-1$ - break; - - case TokenNameLESS_EQUAL : // <= (15.19.1) - operatorString = "<="; //$NON-NLS-1$ - break; - - case TokenNameGREATER : // > (15.19.1) - operatorString = ">"; //$NON-NLS-1$ - break; - - case TokenNameGREATER_EQUAL : // >= (15.19.1) - operatorString = ">="; //$NON-NLS-1$ - break; - - // case TokenNameinstanceof : // instanceof - // operatorString="instanceof"; //$NON-NLS-1$ - // break; - case TokenNamePLUS : // + (15.17, 15.17.2) - operatorString = "+"; //$NON-NLS-1$ - break; - - case TokenNameMINUS : // - (15.17.2) - operatorString = "-"; //$NON-NLS-1$ - break; - case TokenNameMULTIPLY : // * (15.16.1) - operatorString = "*"; //$NON-NLS-1$ - break; - - case TokenNameDIVIDE : // / (15.16.2) - operatorString = "/"; //$NON-NLS-1$ - break; - - case TokenNameREMAINDER : // % (15.16.3) - operatorString = "%"; //$NON-NLS-1$ - break; - case TokenNameLEFT_SHIFT : // << (15.18) - operatorString = "<<"; //$NON-NLS-1$ - break; - - case TokenNameRIGHT_SHIFT : // >> (15.18) - operatorString = ">>"; //$NON-NLS-1$ - break; - - // case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18) - // operatorString=">>>"; //$NON-NLS-1$ - // break; - case TokenNameAND : // & (15.21, 15.21.1, 15.21.2) - operatorString = "&"; //$NON-NLS-1$ - break; - - case TokenNameOR : // | (15.21, 15.21.1, 15.21.2) - operatorString = "|"; //$NON-NLS-1$ - break; - - case TokenNameXOR : // ^ (15.21, 15.21.1, 15.21.2) - operatorString = "^"; //$NON-NLS-1$ - break; - case TokenNameMULTIPLY_EQUAL : // *= (15.25.2) - operatorString = "*="; //$NON-NLS-1$ - break; - - case TokenNameDIVIDE_EQUAL : // /= (15.25.2) - operatorString = "/="; //$NON-NLS-1$ - break; - case TokenNameREMAINDER_EQUAL : // %= (15.25.2) - operatorString = "%="; //$NON-NLS-1$ - break; - - case TokenNamePLUS_EQUAL : // += (15.25.2) - operatorString = "+="; //$NON-NLS-1$ - break; - - case TokenNameMINUS_EQUAL : // -= (15.25.2) - operatorString = "-="; //$NON-NLS-1$ - break; - - case TokenNameLEFT_SHIFT_EQUAL : // <<= (15.25.2) - operatorString = "<<="; //$NON-NLS-1$ - break; - - case TokenNameRIGHT_SHIFT_EQUAL : // >>= (15.25.2) - operatorString = ">>="; //$NON-NLS-1$ - break; - - // case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2) - // operatorString=">>>="; //$NON-NLS-1$ - // break; - - case TokenNameAND_EQUAL : // &= (15.25.2) - operatorString = "&="; //$NON-NLS-1$ - break; - - case TokenNameXOR_EQUAL : // ^= (15.25.2) - operatorString = "^="; //$NON-NLS-1$ - break; - - case TokenNameOR_EQUAL : // |= (15.25.2) - operatorString = "|="; //$NON-NLS-1$ - break; - case TokenNameDOT_EQUAL : // .= - operatorString = ".="; //$NON-NLS-1$ - break; - case TokenNameDOT : // . - operatorString = "."; //$NON-NLS-1$ - break; - - default : - operatorString = ""; //$NON-NLS-1$ - } - if (placeOperatorAhead) { - result.append(operatorString); - } - result.append(currentString); - if (placeOperatorBehind) { - result.append(operatorString); - } - result.append('\n'); - } - return ""; //$NON-NLS-1$ - } + public int[] operators; // the operator on which the string was split. + + public String[] substrings; + + public int[] startSubstringsIndexes; + + /** + * SplitLine constructor comment. + */ + public SplitLine(int[] operators, String[] substrings) { + this(operators, substrings, null); + } + + /** + * SplitLine constructor comment. + */ + public SplitLine(int[] operators, String[] substrings, int[] startIndexes) { + super(); + this.operators = operators; + this.substrings = substrings; + this.startSubstringsIndexes = startIndexes; + } + + /** + * Prints a nice representation of the receiver + * + * @return java.lang.String + */ + public String toString() { + StringBuffer result = new StringBuffer(); + String operatorString = new String(); + + for (int i = 0, max = substrings.length; i < max; i++) { + int currentOperator = operators[i]; + String currentString = substrings[i]; + boolean placeOperatorAhead = currentOperator != TokenNameCOMMA + && currentOperator != TokenNameSEMICOLON; + boolean placeOperatorBehind = currentOperator == TokenNameCOMMA + || currentOperator == TokenNameSEMICOLON; + + switch (currentOperator) { + case TokenNameextends: + operatorString = "extends"; //$NON-NLS-1$ + break; + // case TokenNameimplements: + // operatorString="implements"; //$NON-NLS-1$ + // break; + // case TokenNamethrows: + // operatorString="throws"; //$NON-NLS-1$ + // break; + case TokenNameSEMICOLON: // ; + operatorString = ";"; //$NON-NLS-1$ + break; + case TokenNameCOMMA: // , + operatorString = ","; //$NON-NLS-1$ + break; + case TokenNameEQUAL: // = + operatorString = "="; //$NON-NLS-1$ + break; + case TokenNameAND_AND: // && (15.22) + operatorString = "&&"; //$NON-NLS-1$ + break; + case TokenNameOR_OR: // || (15.23) + operatorString = "||"; //$NON-NLS-1$ + break; + case TokenNameQUESTION: // ? (15.24) + operatorString = "?"; //$NON-NLS-1$ + break; + + case TokenNameCOLON: // : (15.24) + operatorString = ":"; //$NON-NLS-1$ + break; + case TokenNameEQUAL_EQUAL: // == (15.20, 15.20.1, 15.20.2, 15.20.3) + operatorString = "=="; //$NON-NLS-1$ + break; + + case TokenNameNOT_EQUAL: // != (15.20, 15.20.1, 15.20.2, 15.20.3) + operatorString = "!="; //$NON-NLS-1$ + break; + + case TokenNameLESS: // < (15.19.1) + operatorString = "<"; //$NON-NLS-1$ + break; + + case TokenNameLESS_EQUAL: // <= (15.19.1) + operatorString = "<="; //$NON-NLS-1$ + break; + + case TokenNameGREATER: // > (15.19.1) + operatorString = ">"; //$NON-NLS-1$ + break; + + case TokenNameGREATER_EQUAL: // >= (15.19.1) + operatorString = ">="; //$NON-NLS-1$ + break; + + // case TokenNameinstanceof : // instanceof + // operatorString="instanceof"; //$NON-NLS-1$ + // break; + case TokenNamePLUS: // + (15.17, 15.17.2) + operatorString = "+"; //$NON-NLS-1$ + break; + + case TokenNameMINUS: // - (15.17.2) + operatorString = "-"; //$NON-NLS-1$ + break; + case TokenNameMULTIPLY: // * (15.16.1) + operatorString = "*"; //$NON-NLS-1$ + break; + + case TokenNameDIVIDE: // / (15.16.2) + operatorString = "/"; //$NON-NLS-1$ + break; + + case TokenNameREMAINDER: // % (15.16.3) + operatorString = "%"; //$NON-NLS-1$ + break; + case TokenNameLEFT_SHIFT: // << (15.18) + operatorString = "<<"; //$NON-NLS-1$ + break; + + case TokenNameRIGHT_SHIFT: // >> (15.18) + operatorString = ">>"; //$NON-NLS-1$ + break; + + // case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18) + // operatorString=">>>"; //$NON-NLS-1$ + // break; + case TokenNameAND: // & (15.21, 15.21.1, 15.21.2) + operatorString = "&"; //$NON-NLS-1$ + break; + + case TokenNameOR: // | (15.21, 15.21.1, 15.21.2) + operatorString = "|"; //$NON-NLS-1$ + break; + + case TokenNameXOR: // ^ (15.21, 15.21.1, 15.21.2) + operatorString = "^"; //$NON-NLS-1$ + break; + case TokenNameMULTIPLY_EQUAL: // *= (15.25.2) + operatorString = "*="; //$NON-NLS-1$ + break; + + case TokenNameDIVIDE_EQUAL: // /= (15.25.2) + operatorString = "/="; //$NON-NLS-1$ + break; + case TokenNameREMAINDER_EQUAL: // %= (15.25.2) + operatorString = "%="; //$NON-NLS-1$ + break; + + case TokenNamePLUS_EQUAL: // += (15.25.2) + operatorString = "+="; //$NON-NLS-1$ + break; + + case TokenNameMINUS_EQUAL: // -= (15.25.2) + operatorString = "-="; //$NON-NLS-1$ + break; + + case TokenNameLEFT_SHIFT_EQUAL: // <<= (15.25.2) + operatorString = "<<="; //$NON-NLS-1$ + break; + + case TokenNameRIGHT_SHIFT_EQUAL: // >>= (15.25.2) + operatorString = ">>="; //$NON-NLS-1$ + break; + + // case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2) + // operatorString=">>>="; //$NON-NLS-1$ + // break; + + case TokenNameAND_EQUAL: // &= (15.25.2) + operatorString = "&="; //$NON-NLS-1$ + break; + + case TokenNameXOR_EQUAL: // ^= (15.25.2) + operatorString = "^="; //$NON-NLS-1$ + break; + + case TokenNameOR_EQUAL: // |= (15.25.2) + operatorString = "|="; //$NON-NLS-1$ + break; + case TokenNameDOT_EQUAL: // .= + operatorString = ".="; //$NON-NLS-1$ + break; + case TokenNameDOT: // . + operatorString = "."; //$NON-NLS-1$ + break; + + default: + operatorString = ""; //$NON-NLS-1$ + } + if (placeOperatorAhead) { + result.append(operatorString); + } + result.append(currentString); + if (placeOperatorBehind) { + result.append(operatorString); + } + result.append('\n'); + } + return ""; //$NON-NLS-1$ + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/IJavaHelpContextIds.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/IJavaHelpContextIds.java index cc130f4..c9da1a5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/IJavaHelpContextIds.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/IJavaHelpContextIds.java @@ -12,8 +12,6 @@ package net.sourceforge.phpdt.internal.ui; import net.sourceforge.phpeclipse.PHPeclipsePlugin; - - /** * Help context ids for the Java UI. *

                                                      @@ -23,282 +21,742 @@ import net.sourceforge.phpeclipse.PHPeclipsePlugin; * */ public interface IJavaHelpContextIds { - public static final String PREFIX= PHPeclipsePlugin.PLUGIN_ID + '.'; + public static final String PREFIX = PHPeclipsePlugin.PLUGIN_ID + '.'; // Actions - public static final String GETTERSETTER_ACTION= PREFIX + "getter_setter_action_context"; //$NON-NLS-1$ - public static final String ADD_METHODSTUB_ACTION= PREFIX + "add_methodstub_action_context"; //$NON-NLS-1$ - public static final String ADD_UNIMPLEMENTED_METHODS_ACTION= PREFIX + "add_unimplemented_methods_action_context"; //$NON-NLS-1$ - public static final String ADD_UNIMPLEMENTED_CONSTRUCTORS_ACTION= PREFIX + "add_unimplemented_constructors_action_context"; //$NON-NLS-1$ - public static final String SHOW_IN_PACKAGEVIEW_ACTION= PREFIX + "show_in_packageview_action_context"; //$NON-NLS-1$ - public static final String SHOW_IN_HIERARCHYVIEW_ACTION= PREFIX + "show_in_hierarchyview_action_context"; //$NON-NLS-1$ - public static final String FOCUS_ON_SELECTION_ACTION= PREFIX + "focus_on_selection_action"; //$NON-NLS-1$ - public static final String FOCUS_ON_TYPE_ACTION= PREFIX + "focus_on_type_action"; //$NON-NLS-1$ - - public static final String TYPEHIERARCHY_HISTORY_ACTION= PREFIX + "typehierarchy_history_action"; //$NON-NLS-1$ - public static final String FILTER_PUBLIC_ACTION= PREFIX + "filter_public_action"; //$NON-NLS-1$ - public static final String FILTER_FIELDS_ACTION= PREFIX + "filter_fields_action"; //$NON-NLS-1$ - public static final String FILTER_STATIC_ACTION= PREFIX + "filter_static_action"; //$NON-NLS-1$ - public static final String SHOW_INHERITED_ACTION= PREFIX + "show_inherited_action"; //$NON-NLS-1$ - public static final String SHOW_SUPERTYPES= PREFIX + "show_supertypes_action"; //$NON-NLS-1$ - public static final String SHOW_SUBTYPES= PREFIX + "show_subtypes_action"; //$NON-NLS-1$ - public static final String SHOW_HIERARCHY= PREFIX + "show_hierarchy_action"; //$NON-NLS-1$ - public static final String ENABLE_METHODFILTER_ACTION= PREFIX + "enable_methodfilter_action"; //$NON-NLS-1$ - public static final String ADD_IMPORT_ON_SELECTION_ACTION= PREFIX + "add_imports_on_selection_action_context"; //$NON-NLS-1$ - public static final String ORGANIZE_IMPORTS_ACTION= PREFIX + "organize_imports_action_context"; //$NON-NLS-1$ - public static final String ADD_TO_CLASSPATH_ACTION= PREFIX + "addjtoclasspath_action_context"; //$NON-NLS-1$ - public static final String REMOVE_FROM_CLASSPATH_ACTION= PREFIX + "removefromclasspath_action_context"; //$NON-NLS-1$ - - public static final String TOGGLE_PRESENTATION_ACTION= PREFIX + "toggle_presentation_action_context"; //$NON-NLS-1$ - public static final String TOGGLE_TEXTHOVER_ACTION= PREFIX + "toggle_texthover_action_context"; //$NON-NLS-1$ - - public static final String OPEN_CLASS_WIZARD_ACTION= PREFIX + "open_class_wizard_action"; //$NON-NLS-1$ - public static final String OPEN_INTERFACE_WIZARD_ACTION= PREFIX + "open_interface_wizard_action"; //$NON-NLS-1$ - public static final String SORT_MEMBERS_ACTION= PREFIX + "sort_members_action"; //$NON-NLS-1$ - - public static final String OPEN_PACKAGE_WIZARD_ACTION= PREFIX + "open_package_wizard_action"; //$NON-NLS-1$ - public static final String OPEN_PROJECT_WIZARD_ACTION= PREFIX + "open_project_wizard_action"; //$NON-NLS-1$ - public static final String OPEN_SNIPPET_WIZARD_ACTION= PREFIX + "open_snippet_wizard_action"; //$NON-NLS-1$ - public static final String EDIT_WORKING_SET_ACTION= PREFIX + "edit_working_set_action"; //$NON-NLS-1$ - public static final String CLEAR_WORKING_SET_ACTION= PREFIX + "clear_working_set_action"; //$NON-NLS-1$ - public static final String GOTO_MARKER_ACTION= PREFIX + "goto_marker_action"; //$NON-NLS-1$ - public static final String GOTO_PACKAGE_ACTION= PREFIX + "goto_package_action"; //$NON-NLS-1$ - public static final String GOTO_TYPE_ACTION= PREFIX + "goto_type_action"; //$NON-NLS-1$ - public static final String GOTO_MATCHING_BRACKET_ACTION= PREFIX + "goto_matching_bracket_action"; //$NON-NLS-1$ - public static final String GOTO_NEXT_MEMBER_ACTION= PREFIX + "goto_next_member_action"; //$NON-NLS-1$ - public static final String GOTO_PREVIOUS_MEMBER_ACTION= PREFIX + "goto_previous_member_action"; //$NON-NLS-1$ - public static final String HISTORY_ACTION= PREFIX + "history_action"; //$NON-NLS-1$ - public static final String HISTORY_LIST_ACTION= PREFIX + "history_list_action"; //$NON-NLS-1$ - public static final String LEXICAL_SORTING_OUTLINE_ACTION= PREFIX + "lexical_sorting_outline_action"; //$NON-NLS-1$ - public static final String LEXICAL_SORTING_BROWSING_ACTION= PREFIX + "lexical_sorting_browsing_action"; //$NON-NLS-1$ - public static final String OPEN_JAVA_PERSPECTIVE_ACTION= PREFIX + "open_java_perspective_action"; //$NON-NLS-1$ - public static final String ADD_DELEGATE_METHODS_ACTION= PREFIX + "add_delegate_methods_action"; //$NON-NLS-1$ - - public static final String OPEN_JAVA_BROWSING_PERSPECTIVE_ACTION= PREFIX + "open_java_browsing_perspective_action"; //$NON-NLS-1$ - public static final String OPEN_PROJECT_ACTION= PREFIX + "open_project_action"; //$NON-NLS-1$ - public static final String OPEN_TYPE_ACTION= PREFIX + "open_type_action"; //$NON-NLS-1$ - public static final String OPEN_TYPE_IN_HIERARCHY_ACTION= PREFIX + "open_type_in_hierarchy_action"; //$NON-NLS-1$ - public static final String ADD_JAVADOC_STUB_ACTION= PREFIX + "add_javadoc_stub_action"; //$NON-NLS-1$ - public static final String ADD_TASK_ACTION= PREFIX + "add_task_action"; //$NON-NLS-1$ - public static final String EXTERNALIZE_STRINGS_ACTION= PREFIX + "externalize_strings_action"; //$NON-NLS-1$ - public static final String EXTRACT_METHOD_ACTION= PREFIX + "extract_method_action"; //$NON-NLS-1$ - public static final String EXTRACT_TEMP_ACTION= PREFIX + "extract_temp_action"; //$NON-NLS-1$ - public static final String PROMOTE_TEMP_TO_FIELD_ACTION= PREFIX + "promote_temp_to_field_action"; //$NON-NLS-1$ - public static final String CONVERT_ANONYMOUS_TO_NESTED_ACTION= PREFIX + "convert_anonymous_to_nested_action"; //$NON-NLS-1$ - public static final String EXTRACT_CONSTANT_ACTION= PREFIX + "extract_constant_action"; //$NON-NLS-1$ - public static final String EXTRACT_INTERFACE_ACTION= PREFIX + "extract_interface_action"; //$NON-NLS-1$ - public static final String MOVE_INNER_TO_TOP_ACTION= PREFIX + "move_inner_to_top_level_action"; //$NON-NLS-1$ - public static final String USE_SUPERTYPE_ACTION= PREFIX + "use_supertype_action"; //$NON-NLS-1$ - public static final String FIND_DECLARATIONS_IN_WORKSPACE_ACTION= PREFIX + "find_declarations_in_workspace_action"; //$NON-NLS-1$ - public static final String FIND_DECLARATIONS_IN_HIERARCHY_ACTION= PREFIX + "find_declarations_in_hierarchy_action"; //$NON-NLS-1$ - public static final String FIND_DECLARATIONS_IN_WORKING_SET_ACTION= PREFIX + "find_declarations_in_working_set_action"; //$NON-NLS-1$ - public static final String FIND_IMPLEMENTORS_IN_WORKSPACE_ACTION= PREFIX + "find_implementors_in_workspace_action"; //$NON-NLS-1$ - public static final String FIND_IMPLEMENTORS_IN_WORKING_SET_ACTION= PREFIX + "find_implementors_in_working_set_action"; //$NON-NLS-1$ - public static final String FIND_REFERENCES_IN_WORKSPACE_ACTION= PREFIX + "find_references_in_workspace_action"; //$NON-NLS-1$ - public static final String FIND_REFERENCES_IN_HIERARCHY_ACTION= PREFIX + "find_references_in_hierarchy_action"; //$NON-NLS-1$ - public static final String FIND_REFERENCES_IN_WORKING_SET_ACTION= PREFIX + "find_references_in_working_set_action"; //$NON-NLS-1$ - public static final String FIND_READ_REFERENCES_IN_WORKSPACE_ACTION= PREFIX + "find_read_references_in_workspace_action"; //$NON-NLS-1$ - public static final String FIND_READ_REFERENCES_IN_HIERARCHY_ACTION= PREFIX + "find_read_references_in_hierarchy_action"; //$NON-NLS-1$ - public static final String FIND_READ_REFERENCES_IN_WORKING_SET_ACTION= PREFIX + "find_read_references_in_working_set_action"; //$NON-NLS-1$ - public static final String FIND_WRITE_REFERENCES_IN_HIERARCHY_ACTION= PREFIX + "find_write_references_in_hierarchy_action"; //$NON-NLS-1$ - public static final String FIND_WRITE_REFERENCES_IN_WORKING_SET_ACTION= PREFIX + "find_write_references_in_working_set_action"; //$NON-NLS-1$ - public static final String FIND_WRITE_REFERENCES_IN_WORKSPACE_ACTION= PREFIX + "find_write_references_in_workspace_action"; //$NON-NLS-1$ - public static final String FIND_OCCURRENCES_IN_FILE_ACTION= PREFIX + "find_occurrences_in_file_action"; //$NON-NLS-1$ - public static final String WORKING_SET_FIND_ACTION= PREFIX + "working_set_find_action"; //$NON-NLS-1$ - public static final String FIND_STRINGS_TO_EXTERNALIZE_ACTION= PREFIX + "find_strings_to_externalize_action"; //$NON-NLS-1$ - public static final String INLINE_ACTION= PREFIX + "inline_action"; //$NON-NLS-1$ - public static final String MODIFY_PARAMETERS_ACTION= PREFIX + "modify_parameters_action"; //$NON-NLS-1$ - public static final String MOVE_ACTION= PREFIX + "move_action"; //$NON-NLS-1$ - public static final String OPEN_ACTION= PREFIX + "open_action"; //$NON-NLS-1$ - public static final String OPEN_EXTERNAL_JAVADOC_ACTION= PREFIX + "open_external_javadoc_action"; //$NON-NLS-1$ - public static final String OPEN_SUPER_IMPLEMENTATION_ACTION= PREFIX + "open_super_implementation_action"; //$NON-NLS-1$ - public static final String PULL_UP_ACTION= PREFIX + "pull_up_action"; //$NON-NLS-1$ - public static final String PUSH_DOWN_ACTION= PREFIX + "push_down_action"; //$NON-NLS-1$ - public static final String REFRESH_ACTION= PREFIX + "refresh_action"; //$NON-NLS-1$ - public static final String RENAME_ACTION= PREFIX + "rename_action"; //$NON-NLS-1$ - public static final String SELF_ENCAPSULATE_ACTION= PREFIX + "self_encapsulate_action"; //$NON-NLS-1$ - public static final String SHOW_IN_NAVIGATOR_VIEW_ACTION= PREFIX + "show_in_navigator_action"; //$NON-NLS-1$ - public static final String SURROUND_WITH_TRY_CATCH_ACTION= PREFIX + "surround_with_try_catch_action"; //$NON-NLS-1$ - public static final String OPEN_RESOURCE_ACTION= PREFIX + "open_resource_action"; //$NON-NLS-1$ - public static final String SELECT_WORKING_SET_ACTION= PREFIX + "select_working_set_action"; //$NON-NLS-1$ - public static final String STRUCTURED_SELECTION_HISTORY_ACTION= PREFIX + "structured_selection_history_action"; //$NON-NLS-1$ - public static final String STRUCTURED_SELECT_ENCLOSING_ACTION= PREFIX + "structured_select_enclosing_action"; //$NON-NLS-1$ - public static final String STRUCTURED_SELECT_NEXT_ACTION= PREFIX + "structured_select_next_action"; //$NON-NLS-1$ - public static final String STRUCTURED_SELECT_PREVIOUS_ACTION= PREFIX + "structured_select_previous_action"; //$NON-NLS-1$ - public static final String TOGGLE_ORIENTATION_ACTION= PREFIX + "toggle_orientations_action"; //$NON-NLS-1$ - public static final String CUT_ACTION= PREFIX + "cut_action"; //$NON-NLS-1$ - public static final String COPY_ACTION= PREFIX + "copy_action"; //$NON-NLS-1$ - public static final String PASTE_ACTION= PREFIX + "paste_action"; //$NON-NLS-1$ - public static final String DELETE_ACTION= PREFIX + "delete_action"; //$NON-NLS-1$ - public static final String SELECT_ALL_ACTION= PREFIX + "select_all_action"; //$NON-NLS-1$ - public static final String OPEN_TYPE_HIERARCHY_ACTION= PREFIX + "open_type_hierarchy_action"; //$NON-NLS-1$ - public static final String COLLAPSE_ALL_ACTION= PREFIX + "open_type_hierarchy_action"; //$NON-NLS-1$ - public static final String GOTO_RESOURCE_ACTION= PREFIX + "goto_resource_action"; //$NON-NLS-1$ - public static final String LINK_EDITOR_ACTION= PREFIX + "link_editor_action"; //$NON-NLS-1$ - public static final String GO_INTO_TOP_LEVEL_TYPE_ACTION= PREFIX + "go_into_top_level_type_action"; //$NON-NLS-1$ - public static final String COMPARE_WITH_HISTORY_ACTION= PREFIX + "compare_with_history_action"; //$NON-NLS-1$ - public static final String REPLACE_WITH_PREVIOUS_FROM_HISTORY_ACTION= PREFIX + "replace_with_previous_from_history_action"; //$NON-NLS-1$ - public static final String REPLACE_WITH_HISTORY_ACTION= PREFIX + "replace_with_history_action"; //$NON-NLS-1$ - public static final String ADD_FROM_HISTORY_ACTION= PREFIX + "add_from_history_action"; //$NON-NLS-1$ - public static final String LAYOUT_FLAT_ACTION= PREFIX + "layout_flat_action"; //$NON-NLS-1$ - public static final String LAYOUT_HIERARCHICAL_ACTION= PREFIX + "layout_hierarchical_action"; //$NON-NLS-1$ - public static final String NEXT_CHANGE_ACTION= PREFIX + "next_change_action"; //$NON-NLS-1$ - public static final String PREVIOUS_CHANGE_ACTION= PREFIX + "previous_change_action"; //$NON-NLS-1$ - public static final String NEXT_PROBLEM_ACTION= PREFIX + "next_problem_action"; //$NON-NLS-1$ - public static final String PREVIOUS_PROBLEM_ACTION= PREFIX + "previous_problem_action"; //$NON-NLS-1$ - public static final String JAVA_SELECT_MARKER_RULER_ACTION= PREFIX + "java_select_marker_ruler_action"; //$NON-NLS-1$ - public static final String GOTO_NEXT_ERROR_ACTION= PREFIX + "goto_next_error_action"; //$NON-NLS-1$ - public static final String GOTO_PREVIOUS_ERROR_ACTION= PREFIX + "goto_previous_error_action"; //$NON-NLS-1$ - public static final String SHOW_QUALIFIED_NAMES_ACTION= PREFIX + "show_qualified_names_action"; //$NON-NLS-1$ - public static final String SORT_BY_DEFINING_TYPE_ACTION= PREFIX + "sort_by_defining_type_action"; //$NON-NLS-1$ - public static final String FORMAT_ACTION= PREFIX + "format_action"; //$NON-NLS-1$ - public static final String COMMENT_ACTION= PREFIX + "comment_action"; //$NON-NLS-1$ - public static final String UNCOMMENT_ACTION= PREFIX + "uncomment_action"; //$NON-NLS-1$ - public static final String QUICK_FIX_ACTION= PREFIX + "quick_fix_action"; //$NON-NLS-1$ - public static final String CONTENT_ASSIST_ACTION= PREFIX + "content_assist_action"; //$NON-NLS-1$ - public static final String PARAMETER_HINTS_ACTION= PREFIX + "parameter_hints_action"; //$NON-NLS-1$ - public static final String SHOW_JAVADOC_ACTION= PREFIX + "show_javadoc_action"; //$NON-NLS-1$ - public static final String SHOW_OUTLINE_ACTION= PREFIX + "show_outline_action"; //$NON-NLS-1$ - public static final String OPEN_STRUCTURE_ACTION= PREFIX + "open_structure_action"; //$NON-NLS-1$ + public static final String GETTERSETTER_ACTION = PREFIX + + "getter_setter_action_context"; //$NON-NLS-1$ + + public static final String ADD_METHODSTUB_ACTION = PREFIX + + "add_methodstub_action_context"; //$NON-NLS-1$ + + public static final String ADD_UNIMPLEMENTED_METHODS_ACTION = PREFIX + + "add_unimplemented_methods_action_context"; //$NON-NLS-1$ + + public static final String ADD_UNIMPLEMENTED_CONSTRUCTORS_ACTION = PREFIX + + "add_unimplemented_constructors_action_context"; //$NON-NLS-1$ + + public static final String SHOW_IN_PACKAGEVIEW_ACTION = PREFIX + + "show_in_packageview_action_context"; //$NON-NLS-1$ + + public static final String SHOW_IN_HIERARCHYVIEW_ACTION = PREFIX + + "show_in_hierarchyview_action_context"; //$NON-NLS-1$ + + public static final String FOCUS_ON_SELECTION_ACTION = PREFIX + + "focus_on_selection_action"; //$NON-NLS-1$ + + public static final String FOCUS_ON_TYPE_ACTION = PREFIX + + "focus_on_type_action"; //$NON-NLS-1$ + + public static final String TYPEHIERARCHY_HISTORY_ACTION = PREFIX + + "typehierarchy_history_action"; //$NON-NLS-1$ + + public static final String FILTER_PUBLIC_ACTION = PREFIX + + "filter_public_action"; //$NON-NLS-1$ + + public static final String FILTER_FIELDS_ACTION = PREFIX + + "filter_fields_action"; //$NON-NLS-1$ + + public static final String FILTER_STATIC_ACTION = PREFIX + + "filter_static_action"; //$NON-NLS-1$ + + public static final String SHOW_INHERITED_ACTION = PREFIX + + "show_inherited_action"; //$NON-NLS-1$ + + public static final String SHOW_SUPERTYPES = PREFIX + + "show_supertypes_action"; //$NON-NLS-1$ + + public static final String SHOW_SUBTYPES = PREFIX + "show_subtypes_action"; //$NON-NLS-1$ + + public static final String SHOW_HIERARCHY = PREFIX + + "show_hierarchy_action"; //$NON-NLS-1$ + + public static final String ENABLE_METHODFILTER_ACTION = PREFIX + + "enable_methodfilter_action"; //$NON-NLS-1$ + + public static final String ADD_IMPORT_ON_SELECTION_ACTION = PREFIX + + "add_imports_on_selection_action_context"; //$NON-NLS-1$ + + public static final String ORGANIZE_IMPORTS_ACTION = PREFIX + + "organize_imports_action_context"; //$NON-NLS-1$ + + public static final String ADD_TO_CLASSPATH_ACTION = PREFIX + + "addjtoclasspath_action_context"; //$NON-NLS-1$ + + public static final String REMOVE_FROM_CLASSPATH_ACTION = PREFIX + + "removefromclasspath_action_context"; //$NON-NLS-1$ + + public static final String TOGGLE_PRESENTATION_ACTION = PREFIX + + "toggle_presentation_action_context"; //$NON-NLS-1$ + + public static final String TOGGLE_TEXTHOVER_ACTION = PREFIX + + "toggle_texthover_action_context"; //$NON-NLS-1$ + + public static final String OPEN_CLASS_WIZARD_ACTION = PREFIX + + "open_class_wizard_action"; //$NON-NLS-1$ + + public static final String OPEN_INTERFACE_WIZARD_ACTION = PREFIX + + "open_interface_wizard_action"; //$NON-NLS-1$ + + public static final String SORT_MEMBERS_ACTION = PREFIX + + "sort_members_action"; //$NON-NLS-1$ + + public static final String OPEN_PACKAGE_WIZARD_ACTION = PREFIX + + "open_package_wizard_action"; //$NON-NLS-1$ + + public static final String OPEN_PROJECT_WIZARD_ACTION = PREFIX + + "open_project_wizard_action"; //$NON-NLS-1$ + + public static final String OPEN_SNIPPET_WIZARD_ACTION = PREFIX + + "open_snippet_wizard_action"; //$NON-NLS-1$ + + public static final String EDIT_WORKING_SET_ACTION = PREFIX + + "edit_working_set_action"; //$NON-NLS-1$ + + public static final String CLEAR_WORKING_SET_ACTION = PREFIX + + "clear_working_set_action"; //$NON-NLS-1$ + + public static final String GOTO_MARKER_ACTION = PREFIX + + "goto_marker_action"; //$NON-NLS-1$ + + public static final String GOTO_PACKAGE_ACTION = PREFIX + + "goto_package_action"; //$NON-NLS-1$ + + public static final String GOTO_TYPE_ACTION = PREFIX + "goto_type_action"; //$NON-NLS-1$ + + public static final String GOTO_MATCHING_BRACKET_ACTION = PREFIX + + "goto_matching_bracket_action"; //$NON-NLS-1$ + + public static final String GOTO_NEXT_MEMBER_ACTION = PREFIX + + "goto_next_member_action"; //$NON-NLS-1$ + + public static final String GOTO_PREVIOUS_MEMBER_ACTION = PREFIX + + "goto_previous_member_action"; //$NON-NLS-1$ + + public static final String HISTORY_ACTION = PREFIX + "history_action"; //$NON-NLS-1$ + + public static final String HISTORY_LIST_ACTION = PREFIX + + "history_list_action"; //$NON-NLS-1$ + + public static final String LEXICAL_SORTING_OUTLINE_ACTION = PREFIX + + "lexical_sorting_outline_action"; //$NON-NLS-1$ + + public static final String LEXICAL_SORTING_BROWSING_ACTION = PREFIX + + "lexical_sorting_browsing_action"; //$NON-NLS-1$ + + public static final String OPEN_JAVA_PERSPECTIVE_ACTION = PREFIX + + "open_java_perspective_action"; //$NON-NLS-1$ + + public static final String ADD_DELEGATE_METHODS_ACTION = PREFIX + + "add_delegate_methods_action"; //$NON-NLS-1$ + + public static final String OPEN_JAVA_BROWSING_PERSPECTIVE_ACTION = PREFIX + + "open_java_browsing_perspective_action"; //$NON-NLS-1$ + + public static final String OPEN_PROJECT_ACTION = PREFIX + + "open_project_action"; //$NON-NLS-1$ + + public static final String OPEN_TYPE_ACTION = PREFIX + "open_type_action"; //$NON-NLS-1$ + + public static final String OPEN_TYPE_IN_HIERARCHY_ACTION = PREFIX + + "open_type_in_hierarchy_action"; //$NON-NLS-1$ + + public static final String ADD_JAVADOC_STUB_ACTION = PREFIX + + "add_javadoc_stub_action"; //$NON-NLS-1$ + + public static final String ADD_TASK_ACTION = PREFIX + "add_task_action"; //$NON-NLS-1$ + + public static final String EXTERNALIZE_STRINGS_ACTION = PREFIX + + "externalize_strings_action"; //$NON-NLS-1$ + + public static final String EXTRACT_METHOD_ACTION = PREFIX + + "extract_method_action"; //$NON-NLS-1$ + + public static final String EXTRACT_TEMP_ACTION = PREFIX + + "extract_temp_action"; //$NON-NLS-1$ + + public static final String PROMOTE_TEMP_TO_FIELD_ACTION = PREFIX + + "promote_temp_to_field_action"; //$NON-NLS-1$ + + public static final String CONVERT_ANONYMOUS_TO_NESTED_ACTION = PREFIX + + "convert_anonymous_to_nested_action"; //$NON-NLS-1$ + + public static final String EXTRACT_CONSTANT_ACTION = PREFIX + + "extract_constant_action"; //$NON-NLS-1$ + + public static final String EXTRACT_INTERFACE_ACTION = PREFIX + + "extract_interface_action"; //$NON-NLS-1$ + + public static final String MOVE_INNER_TO_TOP_ACTION = PREFIX + + "move_inner_to_top_level_action"; //$NON-NLS-1$ + + public static final String USE_SUPERTYPE_ACTION = PREFIX + + "use_supertype_action"; //$NON-NLS-1$ + + public static final String FIND_DECLARATIONS_IN_WORKSPACE_ACTION = PREFIX + + "find_declarations_in_workspace_action"; //$NON-NLS-1$ + + public static final String FIND_DECLARATIONS_IN_HIERARCHY_ACTION = PREFIX + + "find_declarations_in_hierarchy_action"; //$NON-NLS-1$ + + public static final String FIND_DECLARATIONS_IN_WORKING_SET_ACTION = PREFIX + + "find_declarations_in_working_set_action"; //$NON-NLS-1$ + + public static final String FIND_IMPLEMENTORS_IN_WORKSPACE_ACTION = PREFIX + + "find_implementors_in_workspace_action"; //$NON-NLS-1$ + + public static final String FIND_IMPLEMENTORS_IN_WORKING_SET_ACTION = PREFIX + + "find_implementors_in_working_set_action"; //$NON-NLS-1$ + + public static final String FIND_REFERENCES_IN_WORKSPACE_ACTION = PREFIX + + "find_references_in_workspace_action"; //$NON-NLS-1$ + + public static final String FIND_REFERENCES_IN_HIERARCHY_ACTION = PREFIX + + "find_references_in_hierarchy_action"; //$NON-NLS-1$ + + public static final String FIND_REFERENCES_IN_WORKING_SET_ACTION = PREFIX + + "find_references_in_working_set_action"; //$NON-NLS-1$ + + public static final String FIND_READ_REFERENCES_IN_WORKSPACE_ACTION = PREFIX + + "find_read_references_in_workspace_action"; //$NON-NLS-1$ + + public static final String FIND_READ_REFERENCES_IN_HIERARCHY_ACTION = PREFIX + + "find_read_references_in_hierarchy_action"; //$NON-NLS-1$ + + public static final String FIND_READ_REFERENCES_IN_WORKING_SET_ACTION = PREFIX + + "find_read_references_in_working_set_action"; //$NON-NLS-1$ + + public static final String FIND_WRITE_REFERENCES_IN_HIERARCHY_ACTION = PREFIX + + "find_write_references_in_hierarchy_action"; //$NON-NLS-1$ + + public static final String FIND_WRITE_REFERENCES_IN_WORKING_SET_ACTION = PREFIX + + "find_write_references_in_working_set_action"; //$NON-NLS-1$ + + public static final String FIND_WRITE_REFERENCES_IN_WORKSPACE_ACTION = PREFIX + + "find_write_references_in_workspace_action"; //$NON-NLS-1$ + + public static final String FIND_OCCURRENCES_IN_FILE_ACTION = PREFIX + + "find_occurrences_in_file_action"; //$NON-NLS-1$ + + public static final String WORKING_SET_FIND_ACTION = PREFIX + + "working_set_find_action"; //$NON-NLS-1$ + + public static final String FIND_STRINGS_TO_EXTERNALIZE_ACTION = PREFIX + + "find_strings_to_externalize_action"; //$NON-NLS-1$ + + public static final String INLINE_ACTION = PREFIX + "inline_action"; //$NON-NLS-1$ + + public static final String MODIFY_PARAMETERS_ACTION = PREFIX + + "modify_parameters_action"; //$NON-NLS-1$ + + public static final String MOVE_ACTION = PREFIX + "move_action"; //$NON-NLS-1$ + + public static final String OPEN_ACTION = PREFIX + "open_action"; //$NON-NLS-1$ + + public static final String OPEN_EXTERNAL_JAVADOC_ACTION = PREFIX + + "open_external_javadoc_action"; //$NON-NLS-1$ + + public static final String OPEN_SUPER_IMPLEMENTATION_ACTION = PREFIX + + "open_super_implementation_action"; //$NON-NLS-1$ + + public static final String PULL_UP_ACTION = PREFIX + "pull_up_action"; //$NON-NLS-1$ + + public static final String PUSH_DOWN_ACTION = PREFIX + "push_down_action"; //$NON-NLS-1$ + + public static final String REFRESH_ACTION = PREFIX + "refresh_action"; //$NON-NLS-1$ + + public static final String RENAME_ACTION = PREFIX + "rename_action"; //$NON-NLS-1$ + + public static final String SELF_ENCAPSULATE_ACTION = PREFIX + + "self_encapsulate_action"; //$NON-NLS-1$ + + public static final String SHOW_IN_NAVIGATOR_VIEW_ACTION = PREFIX + + "show_in_navigator_action"; //$NON-NLS-1$ + + public static final String SURROUND_WITH_TRY_CATCH_ACTION = PREFIX + + "surround_with_try_catch_action"; //$NON-NLS-1$ + + public static final String OPEN_RESOURCE_ACTION = PREFIX + + "open_resource_action"; //$NON-NLS-1$ + + public static final String SELECT_WORKING_SET_ACTION = PREFIX + + "select_working_set_action"; //$NON-NLS-1$ + + public static final String STRUCTURED_SELECTION_HISTORY_ACTION = PREFIX + + "structured_selection_history_action"; //$NON-NLS-1$ + + public static final String STRUCTURED_SELECT_ENCLOSING_ACTION = PREFIX + + "structured_select_enclosing_action"; //$NON-NLS-1$ + + public static final String STRUCTURED_SELECT_NEXT_ACTION = PREFIX + + "structured_select_next_action"; //$NON-NLS-1$ + + public static final String STRUCTURED_SELECT_PREVIOUS_ACTION = PREFIX + + "structured_select_previous_action"; //$NON-NLS-1$ + + public static final String TOGGLE_ORIENTATION_ACTION = PREFIX + + "toggle_orientations_action"; //$NON-NLS-1$ + + public static final String CUT_ACTION = PREFIX + "cut_action"; //$NON-NLS-1$ + + public static final String COPY_ACTION = PREFIX + "copy_action"; //$NON-NLS-1$ + + public static final String PASTE_ACTION = PREFIX + "paste_action"; //$NON-NLS-1$ + + public static final String DELETE_ACTION = PREFIX + "delete_action"; //$NON-NLS-1$ + + public static final String SELECT_ALL_ACTION = PREFIX + "select_all_action"; //$NON-NLS-1$ + + public static final String OPEN_TYPE_HIERARCHY_ACTION = PREFIX + + "open_type_hierarchy_action"; //$NON-NLS-1$ + + public static final String COLLAPSE_ALL_ACTION = PREFIX + + "open_type_hierarchy_action"; //$NON-NLS-1$ + + public static final String GOTO_RESOURCE_ACTION = PREFIX + + "goto_resource_action"; //$NON-NLS-1$ + + public static final String LINK_EDITOR_ACTION = PREFIX + + "link_editor_action"; //$NON-NLS-1$ + + public static final String GO_INTO_TOP_LEVEL_TYPE_ACTION = PREFIX + + "go_into_top_level_type_action"; //$NON-NLS-1$ + + public static final String COMPARE_WITH_HISTORY_ACTION = PREFIX + + "compare_with_history_action"; //$NON-NLS-1$ + + public static final String REPLACE_WITH_PREVIOUS_FROM_HISTORY_ACTION = PREFIX + + "replace_with_previous_from_history_action"; //$NON-NLS-1$ + + public static final String REPLACE_WITH_HISTORY_ACTION = PREFIX + + "replace_with_history_action"; //$NON-NLS-1$ + + public static final String ADD_FROM_HISTORY_ACTION = PREFIX + + "add_from_history_action"; //$NON-NLS-1$ + + public static final String LAYOUT_FLAT_ACTION = PREFIX + + "layout_flat_action"; //$NON-NLS-1$ + + public static final String LAYOUT_HIERARCHICAL_ACTION = PREFIX + + "layout_hierarchical_action"; //$NON-NLS-1$ + + public static final String NEXT_CHANGE_ACTION = PREFIX + + "next_change_action"; //$NON-NLS-1$ + + public static final String PREVIOUS_CHANGE_ACTION = PREFIX + + "previous_change_action"; //$NON-NLS-1$ + + public static final String NEXT_PROBLEM_ACTION = PREFIX + + "next_problem_action"; //$NON-NLS-1$ + + public static final String PREVIOUS_PROBLEM_ACTION = PREFIX + + "previous_problem_action"; //$NON-NLS-1$ + + public static final String JAVA_SELECT_MARKER_RULER_ACTION = PREFIX + + "java_select_marker_ruler_action"; //$NON-NLS-1$ + + public static final String GOTO_NEXT_ERROR_ACTION = PREFIX + + "goto_next_error_action"; //$NON-NLS-1$ + + public static final String GOTO_PREVIOUS_ERROR_ACTION = PREFIX + + "goto_previous_error_action"; //$NON-NLS-1$ + + public static final String SHOW_QUALIFIED_NAMES_ACTION = PREFIX + + "show_qualified_names_action"; //$NON-NLS-1$ + + public static final String SORT_BY_DEFINING_TYPE_ACTION = PREFIX + + "sort_by_defining_type_action"; //$NON-NLS-1$ + + public static final String FORMAT_ACTION = PREFIX + "format_action"; //$NON-NLS-1$ + + public static final String COMMENT_ACTION = PREFIX + "comment_action"; //$NON-NLS-1$ + + public static final String UNCOMMENT_ACTION = PREFIX + "uncomment_action"; //$NON-NLS-1$ + + public static final String QUICK_FIX_ACTION = PREFIX + "quick_fix_action"; //$NON-NLS-1$ + + public static final String CONTENT_ASSIST_ACTION = PREFIX + + "content_assist_action"; //$NON-NLS-1$ + + public static final String PARAMETER_HINTS_ACTION = PREFIX + + "parameter_hints_action"; //$NON-NLS-1$ + + public static final String SHOW_JAVADOC_ACTION = PREFIX + + "show_javadoc_action"; //$NON-NLS-1$ + + public static final String SHOW_OUTLINE_ACTION = PREFIX + + "show_outline_action"; //$NON-NLS-1$ + + public static final String OPEN_STRUCTURE_ACTION = PREFIX + + "open_structure_action"; //$NON-NLS-1$ // Dialogs - public static final String MAINTYPE_SELECTION_DIALOG= PREFIX + "maintype_selection_dialog_context"; //$NON-NLS-1$ - public static final String OPEN_TYPE_DIALOG= PREFIX + "open_type_dialog_context"; //$NON-NLS-1$ - public static final String SOURCE_ATTACHMENT_DIALOG= PREFIX + "source_attachment_dialog_context"; //$NON-NLS-1$ - public static final String LIBRARIES_WORKBOOK_PAGE_ADVANCED_DIALOG= PREFIX + "advanced_dialog_context"; //$NON-NLS-1$ - public static final String CONFIRM_SAVE_MODIFIED_RESOURCES_DIALOG= PREFIX + "confirm_save_modified_resources_dialog_context"; //$NON-NLS-1$ - public static final String NEW_VARIABLE_ENTRY_DIALOG= PREFIX + "new_variable_dialog_context"; //$NON-NLS-1$ - public static final String NONNLS_DIALOG= PREFIX + "nonnls_dialog_context"; //$NON-NLS-1$ - public static final String MULTI_MAIN_TYPE_SELECTION_DIALOG= PREFIX + "multi_main_type_selection_dialog_context"; //$NON-NLS-1$ - public static final String MULTI_TYPE_SELECTION_DIALOG= PREFIX + "multi_type_selection_dialog_context"; //$NON-NLS-1$ - public static final String SUPER_INTERFACE_SELECTION_DIALOG= PREFIX + "super_interface_selection_dialog_context"; //$NON-NLS-1$ - public static final String OVERRIDE_TREE_SELECTION_DIALOG= PREFIX + "override_tree_selection_dialog_context"; //$NON-NLS-1$ - public static final String MOVE_DESTINATION_DIALOG= PREFIX + "move_destination_dialog_context"; //$NON-NLS-1$ - public static final String CHOOSE_VARIABLE_DIALOG= PREFIX + "choose_variable_dialog_context"; //$NON-NLS-1$ - public static final String EDIT_TEMPLATE_DIALOG= PREFIX + "edit_template_dialog_context"; //$NON-NLS-1$ - public static final String HISTORY_LIST_DIALOG= PREFIX + "history_list_dialog_context"; //$NON-NLS-1$ - public static final String IMPORT_ORGANIZE_INPUT_DIALOG= PREFIX + "import_organize_input_dialog_context"; //$NON-NLS-1$ - public static final String TODO_TASK_INPUT_DIALOG= PREFIX + "todo_task_input_dialog_context"; //$NON-NLS-1$ - public static final String JAVADOC_PROPERTY_DIALOG= PREFIX + "javadoc_property_dialog_context"; //$NON-NLS-1$ - public static final String NEW_CONTAINER_DIALOG= PREFIX + "new_container_dialog_context"; //$NON-NLS-1$ - public static final String EXCLUSION_PATTERN_DIALOG= PREFIX + "exclusion_pattern_dialog_context"; //$NON-NLS-1$ - public static final String OUTPUT_LOCATION_DIALOG= PREFIX + "output_location_dialog_context"; //$NON-NLS-1$ - public static final String VARIABLE_CREATION_DIALOG= PREFIX + "variable_creation_dialog_context"; //$NON-NLS-1$ - public static final String JAVA_SEARCH_PAGE= PREFIX + "java_search_page_context"; //$NON-NLS-1$ - public static final String NLS_SEARCH_PAGE= PREFIX + "nls_search_page_context"; //$NON-NLS-1$ - public static final String JAVA_EDITOR= PREFIX + "java_editor_context"; //$NON-NLS-1$ - public static final String GOTO_RESOURCE_DIALOG= PREFIX + "goto_resource_dialog"; //$NON-NLS-1$ - - public static final String COMPARE_DIALOG= PREFIX + "compare_dialog_context"; //$NON-NLS-1$ - public static final String ADD_ELEMENT_FROM_HISTORY_DIALOG= PREFIX + "add_element_from_history_dialog_context"; //$NON-NLS-1$ - public static final String COMPARE_ELEMENT_WITH_HISTORY_DIALOG= PREFIX + "compare_element_with_history_dialog_context"; //$NON-NLS-1$ - public static final String REPLACE_ELEMENT_WITH_HISTORY_DIALOG= PREFIX + "replace_element_with_history_dialog_context"; //$NON-NLS-1$ - + public static final String MAINTYPE_SELECTION_DIALOG = PREFIX + + "maintype_selection_dialog_context"; //$NON-NLS-1$ + + public static final String OPEN_TYPE_DIALOG = PREFIX + + "open_type_dialog_context"; //$NON-NLS-1$ + + public static final String SOURCE_ATTACHMENT_DIALOG = PREFIX + + "source_attachment_dialog_context"; //$NON-NLS-1$ + + public static final String LIBRARIES_WORKBOOK_PAGE_ADVANCED_DIALOG = PREFIX + + "advanced_dialog_context"; //$NON-NLS-1$ + + public static final String CONFIRM_SAVE_MODIFIED_RESOURCES_DIALOG = PREFIX + + "confirm_save_modified_resources_dialog_context"; //$NON-NLS-1$ + + public static final String NEW_VARIABLE_ENTRY_DIALOG = PREFIX + + "new_variable_dialog_context"; //$NON-NLS-1$ + + public static final String NONNLS_DIALOG = PREFIX + "nonnls_dialog_context"; //$NON-NLS-1$ + + public static final String MULTI_MAIN_TYPE_SELECTION_DIALOG = PREFIX + + "multi_main_type_selection_dialog_context"; //$NON-NLS-1$ + + public static final String MULTI_TYPE_SELECTION_DIALOG = PREFIX + + "multi_type_selection_dialog_context"; //$NON-NLS-1$ + + public static final String SUPER_INTERFACE_SELECTION_DIALOG = PREFIX + + "super_interface_selection_dialog_context"; //$NON-NLS-1$ + + public static final String OVERRIDE_TREE_SELECTION_DIALOG = PREFIX + + "override_tree_selection_dialog_context"; //$NON-NLS-1$ + + public static final String MOVE_DESTINATION_DIALOG = PREFIX + + "move_destination_dialog_context"; //$NON-NLS-1$ + + public static final String CHOOSE_VARIABLE_DIALOG = PREFIX + + "choose_variable_dialog_context"; //$NON-NLS-1$ + + public static final String EDIT_TEMPLATE_DIALOG = PREFIX + + "edit_template_dialog_context"; //$NON-NLS-1$ + + public static final String HISTORY_LIST_DIALOG = PREFIX + + "history_list_dialog_context"; //$NON-NLS-1$ + + public static final String IMPORT_ORGANIZE_INPUT_DIALOG = PREFIX + + "import_organize_input_dialog_context"; //$NON-NLS-1$ + + public static final String TODO_TASK_INPUT_DIALOG = PREFIX + + "todo_task_input_dialog_context"; //$NON-NLS-1$ + + public static final String JAVADOC_PROPERTY_DIALOG = PREFIX + + "javadoc_property_dialog_context"; //$NON-NLS-1$ + + public static final String NEW_CONTAINER_DIALOG = PREFIX + + "new_container_dialog_context"; //$NON-NLS-1$ + + public static final String EXCLUSION_PATTERN_DIALOG = PREFIX + + "exclusion_pattern_dialog_context"; //$NON-NLS-1$ + + public static final String OUTPUT_LOCATION_DIALOG = PREFIX + + "output_location_dialog_context"; //$NON-NLS-1$ + + public static final String VARIABLE_CREATION_DIALOG = PREFIX + + "variable_creation_dialog_context"; //$NON-NLS-1$ + + public static final String JAVA_SEARCH_PAGE = PREFIX + + "java_search_page_context"; //$NON-NLS-1$ + + public static final String NLS_SEARCH_PAGE = PREFIX + + "nls_search_page_context"; //$NON-NLS-1$ + + public static final String JAVA_EDITOR = PREFIX + "java_editor_context"; //$NON-NLS-1$ + + public static final String GOTO_RESOURCE_DIALOG = PREFIX + + "goto_resource_dialog"; //$NON-NLS-1$ + + public static final String COMPARE_DIALOG = PREFIX + + "compare_dialog_context"; //$NON-NLS-1$ + + public static final String ADD_ELEMENT_FROM_HISTORY_DIALOG = PREFIX + + "add_element_from_history_dialog_context"; //$NON-NLS-1$ + + public static final String COMPARE_ELEMENT_WITH_HISTORY_DIALOG = PREFIX + + "compare_element_with_history_dialog_context"; //$NON-NLS-1$ + + public static final String REPLACE_ELEMENT_WITH_HISTORY_DIALOG = PREFIX + + "replace_element_with_history_dialog_context"; //$NON-NLS-1$ + // view parts - public static final String TYPE_HIERARCHY_VIEW= PREFIX + "type_hierarchy_view_context"; //$NON-NLS-1$ - public static final String PACKAGES_VIEW= PREFIX + "package_view_context"; //$NON-NLS-1$ - public static final String PROJECTS_VIEW= PREFIX + "projects_view_context"; //$NON-NLS-1$ - public static final String PACKAGES_BROWSING_VIEW= PREFIX + "packages_browsing_view_context"; //$NON-NLS-1$ - public static final String TYPES_VIEW= PREFIX + "types_view_context"; //$NON-NLS-1$ - public static final String MEMBERS_VIEW= PREFIX + "members_view_context"; //$NON-NLS-1$ + public static final String TYPE_HIERARCHY_VIEW = PREFIX + + "type_hierarchy_view_context"; //$NON-NLS-1$ + + public static final String PACKAGES_VIEW = PREFIX + "package_view_context"; //$NON-NLS-1$ + + public static final String PROJECTS_VIEW = PREFIX + "projects_view_context"; //$NON-NLS-1$ + + public static final String PACKAGES_BROWSING_VIEW = PREFIX + + "packages_browsing_view_context"; //$NON-NLS-1$ + + public static final String TYPES_VIEW = PREFIX + "types_view_context"; //$NON-NLS-1$ + + public static final String MEMBERS_VIEW = PREFIX + "members_view_context"; //$NON-NLS-1$ // Preference/Property pages - public static final String APPEARANCE_PREFERENCE_PAGE= PREFIX + "appearance_preference_page_context"; //$NON-NLS-1$ - public static final String SORT_ORDER_PREFERENCE_PAGE= PREFIX + "sort_order_preference_page_context"; //$NON-NLS-1$ - public static final String BUILD_PATH_PROPERTY_PAGE= PREFIX + "build_path_property_page_context"; //$NON-NLS-1$ - public static final String CP_VARIABLES_PREFERENCE_PAGE= PREFIX + "cp_variables_preference_page_context"; //$NON-NLS-1$ - public static final String CODEFORMATTER_PREFERENCE_PAGE= PREFIX + "codeformatter_preference_page_context"; //$NON-NLS-1$ - public static final String SOURCE_ATTACHMENT_PROPERTY_PAGE= PREFIX + "source_attachment_property_page_context"; //$NON-NLS-1$ - public static final String COMPILER_PROPERTY_PAGE= PREFIX + "compiler_property_page_context"; //$NON-NLS-1$ - public static final String TODOTASK_PROPERTY_PAGE= PREFIX + "tasktags_property_page_context"; //$NON-NLS-1$ - - public static final String CODE_MANIPULATION_PREFERENCE_PAGE= PREFIX + "code_manipulation_preference_context"; //$NON-NLS-1$ - public static final String ORGANIZE_IMPORTS_PREFERENCE_PAGE= PREFIX + "organizeimports_preference_page_context"; //$NON-NLS-1$ - public static final String JAVA_BASE_PREFERENCE_PAGE= PREFIX + "java_base_preference_page_context"; //$NON-NLS-1$ - public static final String REFACTORING_PREFERENCE_PAGE= PREFIX + "refactoring_preference_page_context"; //$NON-NLS-1$ - public static final String JAVA_EDITOR_PREFERENCE_PAGE= PREFIX + "java_editor_preference_page_context"; //$NON-NLS-1$ - public static final String COMPILER_PREFERENCE_PAGE= PREFIX + "compiler_preference_page_context"; //$NON-NLS-1$ - public static final String TODOTASK_PREFERENCE_PAGE= PREFIX + "tasktags_preference_page_context"; //$NON-NLS-1$ - - public static final String TEMPLATE_PREFERENCE_PAGE= PREFIX + "template_preference_page_context"; //$NON-NLS-1$ - public static final String JAVADOC_PREFERENCE_PAGE= PREFIX + "javadoc_preference_page_context"; //$NON-NLS-1$ - public static final String NEW_JAVA_PROJECT_PREFERENCE_PAGE= PREFIX + "new_java_project_preference_page_context"; //$NON-NLS-1$ - public static final String JAVADOC_CONFIGURATION_PROPERTY_PAGE= PREFIX + "new_java_project_preference_page_context"; //$NON-NLS-1$ - public static final String JAVA_ELEMENT_INFO_PAGE= PREFIX + "java_element_info_page_context"; //$NON-NLS-1$ - + public static final String APPEARANCE_PREFERENCE_PAGE = PREFIX + + "appearance_preference_page_context"; //$NON-NLS-1$ + + public static final String SORT_ORDER_PREFERENCE_PAGE = PREFIX + + "sort_order_preference_page_context"; //$NON-NLS-1$ + + public static final String BUILD_PATH_PROPERTY_PAGE = PREFIX + + "build_path_property_page_context"; //$NON-NLS-1$ + + public static final String CP_VARIABLES_PREFERENCE_PAGE = PREFIX + + "cp_variables_preference_page_context"; //$NON-NLS-1$ + + public static final String CODEFORMATTER_PREFERENCE_PAGE = PREFIX + + "codeformatter_preference_page_context"; //$NON-NLS-1$ + + public static final String SOURCE_ATTACHMENT_PROPERTY_PAGE = PREFIX + + "source_attachment_property_page_context"; //$NON-NLS-1$ + + public static final String COMPILER_PROPERTY_PAGE = PREFIX + + "compiler_property_page_context"; //$NON-NLS-1$ + + public static final String TODOTASK_PROPERTY_PAGE = PREFIX + + "tasktags_property_page_context"; //$NON-NLS-1$ + + public static final String CODE_MANIPULATION_PREFERENCE_PAGE = PREFIX + + "code_manipulation_preference_context"; //$NON-NLS-1$ + + public static final String ORGANIZE_IMPORTS_PREFERENCE_PAGE = PREFIX + + "organizeimports_preference_page_context"; //$NON-NLS-1$ + + public static final String JAVA_BASE_PREFERENCE_PAGE = PREFIX + + "java_base_preference_page_context"; //$NON-NLS-1$ + + public static final String REFACTORING_PREFERENCE_PAGE = PREFIX + + "refactoring_preference_page_context"; //$NON-NLS-1$ + + public static final String JAVA_EDITOR_PREFERENCE_PAGE = PREFIX + + "java_editor_preference_page_context"; //$NON-NLS-1$ + + public static final String COMPILER_PREFERENCE_PAGE = PREFIX + + "compiler_preference_page_context"; //$NON-NLS-1$ + + public static final String TODOTASK_PREFERENCE_PAGE = PREFIX + + "tasktags_preference_page_context"; //$NON-NLS-1$ + + public static final String TEMPLATE_PREFERENCE_PAGE = PREFIX + + "template_preference_page_context"; //$NON-NLS-1$ + + public static final String JAVADOC_PREFERENCE_PAGE = PREFIX + + "javadoc_preference_page_context"; //$NON-NLS-1$ + + public static final String NEW_JAVA_PROJECT_PREFERENCE_PAGE = PREFIX + + "new_java_project_preference_page_context"; //$NON-NLS-1$ + + public static final String JAVADOC_CONFIGURATION_PROPERTY_PAGE = PREFIX + + "new_java_project_preference_page_context"; //$NON-NLS-1$ + + public static final String JAVA_ELEMENT_INFO_PAGE = PREFIX + + "java_element_info_page_context"; //$NON-NLS-1$ + // Wizard pages - public static final String NEW_JAVAPROJECT_WIZARD_PAGE= PREFIX + "new_javaproject_wizard_page_context"; //$NON-NLS-1$ - public static final String NEW_SNIPPET_WIZARD_PAGE= PREFIX + "new_snippet_wizard_page_context"; //$NON-NLS-1$ - public static final String NEW_PACKAGE_WIZARD_PAGE= PREFIX + "new_package_wizard_page_context"; //$NON-NLS-1$ - public static final String NEW_CLASS_WIZARD_PAGE= PREFIX + "new_class_wizard_page_context"; //$NON-NLS-1$ - public static final String NEW_INTERFACE_WIZARD_PAGE= PREFIX + "new_interface_wizard_page_context"; //$NON-NLS-1$ - public static final String NEW_PACKAGEROOT_WIZARD_PAGE= PREFIX + "new_packageroot_wizard_page_context"; //$NON-NLS-1$ - public static final String JARPACKAGER_WIZARD_PAGE= PREFIX + "jar_packager_wizard_page_context"; //$NON-NLS-1$ - public static final String JARMANIFEST_WIZARD_PAGE= PREFIX + "jar_manifest_wizard_page_context"; //$NON-NLS-1$ - public static final String JAROPTIONS_WIZARD_PAGE= PREFIX + "jar_options_wizard_page_context"; //$NON-NLS-1$ - public static final String JAVA_WORKING_SET_PAGE= PREFIX + "java_working_set_page_context"; //$NON-NLS-1$ - public static final String CLASSPATH_CONTAINER_DEFAULT_PAGE= PREFIX + "classpath_container_default_page_context"; //$NON-NLS-1$ - public static final String JAVADOC_STANDARD_PAGE= PREFIX + "javadoc_standard_page_context"; //$NON-NLS-1$ - public static final String JAVADOC_SPECIFICS_PAGE= PREFIX + "javadoc_specifics_page_context"; //$NON-NLS-1$ - public static final String JAVADOC_TREE_PAGE= PREFIX + "javadoc_tree_page_context"; //$NON-NLS-1$ - + public static final String NEW_JAVAPROJECT_WIZARD_PAGE = PREFIX + + "new_javaproject_wizard_page_context"; //$NON-NLS-1$ + + public static final String NEW_SNIPPET_WIZARD_PAGE = PREFIX + + "new_snippet_wizard_page_context"; //$NON-NLS-1$ + + public static final String NEW_PACKAGE_WIZARD_PAGE = PREFIX + + "new_package_wizard_page_context"; //$NON-NLS-1$ + + public static final String NEW_CLASS_WIZARD_PAGE = PREFIX + + "new_class_wizard_page_context"; //$NON-NLS-1$ + + public static final String NEW_INTERFACE_WIZARD_PAGE = PREFIX + + "new_interface_wizard_page_context"; //$NON-NLS-1$ + + public static final String NEW_PACKAGEROOT_WIZARD_PAGE = PREFIX + + "new_packageroot_wizard_page_context"; //$NON-NLS-1$ + + public static final String JARPACKAGER_WIZARD_PAGE = PREFIX + + "jar_packager_wizard_page_context"; //$NON-NLS-1$ + + public static final String JARMANIFEST_WIZARD_PAGE = PREFIX + + "jar_manifest_wizard_page_context"; //$NON-NLS-1$ + + public static final String JAROPTIONS_WIZARD_PAGE = PREFIX + + "jar_options_wizard_page_context"; //$NON-NLS-1$ + + public static final String JAVA_WORKING_SET_PAGE = PREFIX + + "java_working_set_page_context"; //$NON-NLS-1$ + + public static final String CLASSPATH_CONTAINER_DEFAULT_PAGE = PREFIX + + "classpath_container_default_page_context"; //$NON-NLS-1$ + + public static final String JAVADOC_STANDARD_PAGE = PREFIX + + "javadoc_standard_page_context"; //$NON-NLS-1$ + + public static final String JAVADOC_SPECIFICS_PAGE = PREFIX + + "javadoc_specifics_page_context"; //$NON-NLS-1$ + + public static final String JAVADOC_TREE_PAGE = PREFIX + + "javadoc_tree_page_context"; //$NON-NLS-1$ + // same help for all refactoring preview pages - public static final String REFACTORING_PREVIEW_WIZARD_PAGE= PREFIX + "refactoring_preview_wizard_page_context"; //$NON-NLS-1$ - - public static final String MOVE_CU_ERROR_WIZARD_PAGE= PREFIX + "move_cu_error_wizard_page_context"; //$NON-NLS-1$ - public static final String RENAME_PARAMS_WIZARD_PAGE= PREFIX + "rename_params_wizard_page"; //$NON-NLS-1$ - public static final String RENAME_PARAMS_ERROR_WIZARD_PAGE= PREFIX + "rename_params_error_wizard_page"; //$NON-NLS-1$ - public static final String EXTERNALIZE_WIZARD_KEYVALUE_PAGE= PREFIX + "externalize_wizard_keyvalue_page_context"; //$NON-NLS-1$ - public static final String EXTERNALIZE_WIZARD_PROPERTIES_FILE_PAGE= PREFIX + "externalize_wizard_properties_file_page_context"; //$NON-NLS-1$ - public static final String EXTERNALIZE_ERROR_WIZARD_PAGE= PREFIX + "externalize_error_wizard_page_context"; //$NON-NLS-1$ - public static final String EXTRACT_INTERFACE_WIZARD_PAGE= PREFIX + "extract_interface_temp_page_context"; //$NON-NLS-1$ - public static final String EXTRACT_INTERFACE_ERROR_WIZARD_PAGE= PREFIX + "extract_interface_error_wizard_page_context"; //$NON-NLS-1$ - public static final String EXTRACT_METHOD_WIZARD_PAGE= PREFIX + "extract_method_wizard_page_context"; //$NON-NLS-1$ - public static final String EXTRACT_METHOD_ERROR_WIZARD_PAGE= PREFIX + "extract_method_error_wizard_page_context"; //$NON-NLS-1$ - public static final String EXTRACT_TEMP_WIZARD_PAGE= PREFIX + "extract_temp_page_context"; //$NON-NLS-1$ - public static final String EXTRACT_TEMP_ERROR_WIZARD_PAGE= PREFIX + "extract_temp_error_wizard_page_context"; //$NON-NLS-1$ - public static final String EXTRACT_CONSTANT_WIZARD_PAGE= PREFIX + "extract_constant_page_context"; //$NON-NLS-1$ - public static final String EXTRACT_CONSTANT_ERROR_WIZARD_PAGE= PREFIX + "extract_constant_error_wizard_page_context"; //$NON-NLS-1$ - public static final String PROMOTE_TEMP_TO_FIELD_WIZARD_PAGE= PREFIX + "promote_temp_to_field_page_context"; //$NON-NLS-1$ - public static final String PROMOTE_TEMP_TO_FIELD_ERROR_WIZARD_PAGE= PREFIX + "promote_temp_to_field_error_wizard_page_context"; //$NON-NLS-1$ - public static final String CONVERT_ANONYMOUS_TO_NESTED_WIZARD_PAGE= PREFIX + "convert_anonymous_to_nested_page_context"; //$NON-NLS-1$ - public static final String CONVERT_ANONYMOUS_TO_NESTED_ERROR_WIZARD_PAGE= PREFIX + "convert_anonymous_to_nested_error_wizard_page_context"; //$NON-NLS-1$ - public static final String MODIFY_PARAMETERS_WIZARD_PAGE= PREFIX + "modify_parameters_wizard_page_context"; //$NON-NLS-1$ - public static final String MODIFY_PARAMETERS_ERROR_WIZARD_PAGE= PREFIX + "modify_parameters_error_wizard_page_context"; //$NON-NLS-1$ - public static final String MOVE_MEMBERS_WIZARD_PAGE= PREFIX + "move_members_wizard_page_context"; //$NON-NLS-1$ - public static final String MOVE_MEMBERS_ERROR_WIZARD_PAGE= PREFIX + "move_members_error_error_wizard_page_context"; //$NON-NLS-1$ - public static final String MOVE_INNER_TO_TOP_WIZARD_PAGE= PREFIX + "move_inner_to_top_wizard_page_context"; //$NON-NLS-1$ - public static final String MOVE_INNER_TO_TOP_ERROR_WIZARD_PAGE= PREFIX + "move_inner_to_top_error_error_wizard_page_context"; //$NON-NLS-1$ - public static final String PULL_UP_WIZARD_PAGE= PREFIX + "pull_up_wizard_page_context"; //$NON-NLS-1$ - public static final String PULL_UP_ERROR_WIZARD_PAGE= PREFIX + "pull_up_error_error_wizard_page_context"; //$NON-NLS-1$ - public static final String PUSH_DOWN_WIZARD_PAGE= PREFIX + "push_down_wizard_page_context"; //$NON-NLS-1$ - public static final String PUSH_DOWN_ERROR_WIZARD_PAGE= PREFIX + "push_down_error_error_wizard_page_context"; //$NON-NLS-1$ - public static final String RENAME_PACKAGE_WIZARD_PAGE= PREFIX + "rename_package_wizard_page_context"; //$NON-NLS-1$ - public static final String RENAME_PACKAGE_ERROR_WIZARD_PAGE= PREFIX + "rename_package_error_wizard_page_context"; //$NON-NLS-1$ - public static final String RENAME_TEMP_WIZARD_PAGE= PREFIX + "rename_local_variable_wizard_page_context"; //$NON-NLS-1$ - public static final String RENAME_TEMP_ERROR_WIZARD_PAGE= PREFIX + "rename_local_variable_error_wizard_page_context"; //$NON-NLS-1$ - public static final String RENAME_CU_WIZARD_PAGE= PREFIX + "rename_cu_wizard_page_context"; //$NON-NLS-1$ - public static final String RENAME_CU_ERROR_WIZARD_PAGE= PREFIX + "rename_cu_error_wizard_page_context"; //$NON-NLS-1$ - public static final String RENAME_METHOD_WIZARD_PAGE= PREFIX + "rename_method_wizard_page_context"; //$NON-NLS-1$ - public static final String RENAME_METHOD_ERROR_WIZARD_PAGE= PREFIX + "rename_method_error_wizard_page_context"; //$NON-NLS-1$ - public static final String RENAME_TYPE_WIZARD_PAGE= PREFIX + "rename_type_wizard_page_context"; //$NON-NLS-1$ - public static final String RENAME_TYPE_ERROR_WIZARD_PAGE= PREFIX + "rename_type_error_wizard_page_context"; //$NON-NLS-1$ - public static final String RENAME_FIELD_WIZARD_PAGE= PREFIX + "rename_field_wizard_page_context"; //$NON-NLS-1$ - public static final String RENAME_FIELD_ERROR_WIZARD_PAGE= PREFIX + "rename_field_error_wizard_page_context"; //$NON-NLS-1$ - public static final String SEF_WIZARD_PAGE= PREFIX + "self_encapsulate_field_wizard_page_context"; //$NON-NLS-1$ - public static final String SEF_ERROR_WIZARD_PAGE= PREFIX + "self_encapsulate_field_error_wizard_page_context"; //$NON-NLS-1$ - public static final String USE_SUPERTYPE_WIZARD_PAGE= PREFIX + "use_supertype_wizard_page_context"; //$NON-NLS-1$ - public static final String USE_SUPERTYPE_ERROR_WIZARD_PAGE= PREFIX + "use_supertype_error_wizard_page_context"; //$NON-NLS-1$ - public static final String INLINE_METHOD_WIZARD_PAGE= PREFIX + "inline_method_wizard_page_context"; //$NON-NLS-1$ - public static final String INLINE_METHOD_ERROR_WIZARD_PAGE= PREFIX + "inline_method_error_wizard_page_context"; //$NON-NLS-1$ - public static final String INLINE_CONSTANT_WIZARD_PAGE= PREFIX + "inline_constant_wizard_page_context"; //$NON-NLS-1$ - public static final String INLINE_CONSTANT_ERROR_WIZARD_PAGE= PREFIX + "inline_constant_error_wizard_page_context"; //$NON-NLS-1$ - public static final String INLINE_TEMP_ERROR_WIZARD_PAGE= PREFIX + "inline_temp_error_wizard_page_context"; //$NON-NLS-1$ - + public static final String REFACTORING_PREVIEW_WIZARD_PAGE = PREFIX + + "refactoring_preview_wizard_page_context"; //$NON-NLS-1$ + + public static final String MOVE_CU_ERROR_WIZARD_PAGE = PREFIX + + "move_cu_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String RENAME_PARAMS_WIZARD_PAGE = PREFIX + + "rename_params_wizard_page"; //$NON-NLS-1$ + + public static final String RENAME_PARAMS_ERROR_WIZARD_PAGE = PREFIX + + "rename_params_error_wizard_page"; //$NON-NLS-1$ + + public static final String EXTERNALIZE_WIZARD_KEYVALUE_PAGE = PREFIX + + "externalize_wizard_keyvalue_page_context"; //$NON-NLS-1$ + + public static final String EXTERNALIZE_WIZARD_PROPERTIES_FILE_PAGE = PREFIX + + "externalize_wizard_properties_file_page_context"; //$NON-NLS-1$ + + public static final String EXTERNALIZE_ERROR_WIZARD_PAGE = PREFIX + + "externalize_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String EXTRACT_INTERFACE_WIZARD_PAGE = PREFIX + + "extract_interface_temp_page_context"; //$NON-NLS-1$ + + public static final String EXTRACT_INTERFACE_ERROR_WIZARD_PAGE = PREFIX + + "extract_interface_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String EXTRACT_METHOD_WIZARD_PAGE = PREFIX + + "extract_method_wizard_page_context"; //$NON-NLS-1$ + + public static final String EXTRACT_METHOD_ERROR_WIZARD_PAGE = PREFIX + + "extract_method_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String EXTRACT_TEMP_WIZARD_PAGE = PREFIX + + "extract_temp_page_context"; //$NON-NLS-1$ + + public static final String EXTRACT_TEMP_ERROR_WIZARD_PAGE = PREFIX + + "extract_temp_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String EXTRACT_CONSTANT_WIZARD_PAGE = PREFIX + + "extract_constant_page_context"; //$NON-NLS-1$ + + public static final String EXTRACT_CONSTANT_ERROR_WIZARD_PAGE = PREFIX + + "extract_constant_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String PROMOTE_TEMP_TO_FIELD_WIZARD_PAGE = PREFIX + + "promote_temp_to_field_page_context"; //$NON-NLS-1$ + + public static final String PROMOTE_TEMP_TO_FIELD_ERROR_WIZARD_PAGE = PREFIX + + "promote_temp_to_field_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String CONVERT_ANONYMOUS_TO_NESTED_WIZARD_PAGE = PREFIX + + "convert_anonymous_to_nested_page_context"; //$NON-NLS-1$ + + public static final String CONVERT_ANONYMOUS_TO_NESTED_ERROR_WIZARD_PAGE = PREFIX + + "convert_anonymous_to_nested_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String MODIFY_PARAMETERS_WIZARD_PAGE = PREFIX + + "modify_parameters_wizard_page_context"; //$NON-NLS-1$ + + public static final String MODIFY_PARAMETERS_ERROR_WIZARD_PAGE = PREFIX + + "modify_parameters_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String MOVE_MEMBERS_WIZARD_PAGE = PREFIX + + "move_members_wizard_page_context"; //$NON-NLS-1$ + + public static final String MOVE_MEMBERS_ERROR_WIZARD_PAGE = PREFIX + + "move_members_error_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String MOVE_INNER_TO_TOP_WIZARD_PAGE = PREFIX + + "move_inner_to_top_wizard_page_context"; //$NON-NLS-1$ + + public static final String MOVE_INNER_TO_TOP_ERROR_WIZARD_PAGE = PREFIX + + "move_inner_to_top_error_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String PULL_UP_WIZARD_PAGE = PREFIX + + "pull_up_wizard_page_context"; //$NON-NLS-1$ + + public static final String PULL_UP_ERROR_WIZARD_PAGE = PREFIX + + "pull_up_error_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String PUSH_DOWN_WIZARD_PAGE = PREFIX + + "push_down_wizard_page_context"; //$NON-NLS-1$ + + public static final String PUSH_DOWN_ERROR_WIZARD_PAGE = PREFIX + + "push_down_error_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String RENAME_PACKAGE_WIZARD_PAGE = PREFIX + + "rename_package_wizard_page_context"; //$NON-NLS-1$ + + public static final String RENAME_PACKAGE_ERROR_WIZARD_PAGE = PREFIX + + "rename_package_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String RENAME_TEMP_WIZARD_PAGE = PREFIX + + "rename_local_variable_wizard_page_context"; //$NON-NLS-1$ + + public static final String RENAME_TEMP_ERROR_WIZARD_PAGE = PREFIX + + "rename_local_variable_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String RENAME_CU_WIZARD_PAGE = PREFIX + + "rename_cu_wizard_page_context"; //$NON-NLS-1$ + + public static final String RENAME_CU_ERROR_WIZARD_PAGE = PREFIX + + "rename_cu_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String RENAME_METHOD_WIZARD_PAGE = PREFIX + + "rename_method_wizard_page_context"; //$NON-NLS-1$ + + public static final String RENAME_METHOD_ERROR_WIZARD_PAGE = PREFIX + + "rename_method_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String RENAME_TYPE_WIZARD_PAGE = PREFIX + + "rename_type_wizard_page_context"; //$NON-NLS-1$ + + public static final String RENAME_TYPE_ERROR_WIZARD_PAGE = PREFIX + + "rename_type_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String RENAME_FIELD_WIZARD_PAGE = PREFIX + + "rename_field_wizard_page_context"; //$NON-NLS-1$ + + public static final String RENAME_FIELD_ERROR_WIZARD_PAGE = PREFIX + + "rename_field_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String SEF_WIZARD_PAGE = PREFIX + + "self_encapsulate_field_wizard_page_context"; //$NON-NLS-1$ + + public static final String SEF_ERROR_WIZARD_PAGE = PREFIX + + "self_encapsulate_field_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String USE_SUPERTYPE_WIZARD_PAGE = PREFIX + + "use_supertype_wizard_page_context"; //$NON-NLS-1$ + + public static final String USE_SUPERTYPE_ERROR_WIZARD_PAGE = PREFIX + + "use_supertype_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String INLINE_METHOD_WIZARD_PAGE = PREFIX + + "inline_method_wizard_page_context"; //$NON-NLS-1$ + + public static final String INLINE_METHOD_ERROR_WIZARD_PAGE = PREFIX + + "inline_method_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String INLINE_CONSTANT_WIZARD_PAGE = PREFIX + + "inline_constant_wizard_page_context"; //$NON-NLS-1$ + + public static final String INLINE_CONSTANT_ERROR_WIZARD_PAGE = PREFIX + + "inline_constant_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String INLINE_TEMP_ERROR_WIZARD_PAGE = PREFIX + + "inline_temp_error_wizard_page_context"; //$NON-NLS-1$ + // reused ui-blocks - public static final String BUILD_PATH_BLOCK= PREFIX + "build_paths_context"; //$NON-NLS-1$ - public static final String SOURCE_ATTACHMENT_BLOCK= PREFIX + "source_attachment_context"; //$NON-NLS-1$ - + public static final String BUILD_PATH_BLOCK = PREFIX + + "build_paths_context"; //$NON-NLS-1$ + + public static final String SOURCE_ATTACHMENT_BLOCK = PREFIX + + "source_attachment_context"; //$NON-NLS-1$ + // Custom Filters - public static final String CUSTOM_FILTERS_DIALOG= PREFIX + "open_custom_filters_dialog_context"; //$NON-NLS-1$ + public static final String CUSTOM_FILTERS_DIALOG = PREFIX + + "open_custom_filters_dialog_context"; //$NON-NLS-1$ } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/IJavaStatusConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/IJavaStatusConstants.java index 157fff5..a5c7fbd 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/IJavaStatusConstants.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/IJavaStatusConstants.java @@ -11,21 +11,21 @@ package net.sourceforge.phpdt.internal.ui; /** - * Defines status codes relevant to the Java UI plug-in. When a - * Core exception is thrown, it contain a status object describing - * the cause of the exception. The status objects originating from the - * Java UI plug-in use the codes defined in this interface. - */ + * Defines status codes relevant to the Java UI plug-in. When a Core exception + * is thrown, it contain a status object describing the cause of the exception. + * The status objects originating from the Java UI plug-in use the codes defined + * in this interface. + */ public interface IJavaStatusConstants { // Java UI status constants start at 10000 to make sure that we don't // collide with resource and java model constants. - - public static final int INTERNAL_ERROR= 10001; - + + public static final int INTERNAL_ERROR = 10001; + /** - * Status constant indicating that an exception occurred on - * storing or loading templates. + * Status constant indicating that an exception occurred on storing or + * loading templates. */ public static final int TEMPLATE_IO_EXCEPTION = 10002; @@ -33,17 +33,17 @@ public interface IJavaStatusConstants { * Status constant indicating that an validateEdit call has changed the * content of a file on disk. */ - public static final int VALIDATE_EDIT_CHANGED_CONTENT= 10003; - + public static final int VALIDATE_EDIT_CHANGED_CONTENT = 10003; + /** - * Status constant indicating that a ChangeAbortException has been - * caught. - */ - public static final int CHANGE_ABORTED= 10004; + * Status constant indicating that a ChangeAbortException has + * been caught. + */ + public static final int CHANGE_ABORTED = 10004; /** - * Status constant indicating that an exception occurred while - * parsing template file. + * Status constant indicating that an exception occurred while parsing + * template file. */ public static final int TEMPLATE_PARSE_EXCEPTION = 10005; - } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/JavaElementAdapterFactory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/JavaElementAdapterFactory.java index fedb725..b1ae566 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/JavaElementAdapterFactory.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/JavaElementAdapterFactory.java @@ -11,7 +11,6 @@ package net.sourceforge.phpdt.internal.ui; - import net.sourceforge.phpdt.core.ICompilationUnit; import net.sourceforge.phpdt.core.IJavaElement; import net.sourceforge.phpdt.core.IPackageFragmentRoot; @@ -27,109 +26,118 @@ import org.eclipse.ui.IPersistableElement; import org.eclipse.ui.views.properties.FilePropertySource; import org.eclipse.ui.views.properties.IPropertySource; import org.eclipse.ui.views.properties.ResourcePropertySource; -//import net.sourceforge.phpdt.internal.ui.search.JavaSearchPageScoreComputer; -//import net.sourceforge.phpdt.internal.ui.search.SearchUtil; /** - * Implements basic UI support for Java elements. - * Implements handle to persistent support for Java elements. + * Implements basic UI support for Java elements. Implements handle to + * persistent support for Java elements. */ -public class JavaElementAdapterFactory implements IAdapterFactory, IContributorResourceAdapter{ - - private static Class[] PROPERTIES= new Class[] { - IPropertySource.class, - IResource.class, -// IWorkbenchAdapter.class, -// IResourceLocator.class, - IPersistableElement.class, - IProject.class, - IContributorResourceAdapter.class, -// ITaskListResourceAdapter.class, -// IContainmentAdapter.class +public class JavaElementAdapterFactory implements IAdapterFactory, + IContributorResourceAdapter { + + private static Class[] PROPERTIES = new Class[] { + IPropertySource.class, + IResource.class, + // IWorkbenchAdapter.class, + // IResourceLocator.class, + IPersistableElement.class, IProject.class, + IContributorResourceAdapter.class, + // ITaskListResourceAdapter.class, + // IContainmentAdapter.class }; - -// private Object fSearchPageScoreComputer; -// private static IResourceLocator fgResourceLocator= new ResourceLocator(); -// private static JavaWorkbenchAdapter fgJavaWorkbenchAdapter= new JavaWorkbenchAdapter(); -// private static ITaskListResourceAdapter fgTaskListAdapter= new JavaTaskListAdapter(); -// private static JavaElementContainmentAdapter fgJavaElementContainmentAdapter= new JavaElementContainmentAdapter(); - + + // private Object fSearchPageScoreComputer; + // private static IResourceLocator fgResourceLocator= new ResourceLocator(); + // private static JavaWorkbenchAdapter fgJavaWorkbenchAdapter= new + // JavaWorkbenchAdapter(); + // private static ITaskListResourceAdapter fgTaskListAdapter= new + // JavaTaskListAdapter(); + // private static JavaElementContainmentAdapter + // fgJavaElementContainmentAdapter= new JavaElementContainmentAdapter(); + public Class[] getAdapterList() { -// updateLazyLoadedAdapters(); + // updateLazyLoadedAdapters(); return PROPERTIES; } - + public Object getAdapter(Object element, Class key) { -// updateLazyLoadedAdapters(); - IJavaElement java= (IJavaElement) element; - + // updateLazyLoadedAdapters(); + IJavaElement java = (IJavaElement) element; + if (IPropertySource.class.equals(key)) { return getProperties(java); - } if (IResource.class.equals(key)) { + } + if (IResource.class.equals(key)) { return getResource(java); - } if (IProject.class.equals(key)) { + } + if (IProject.class.equals(key)) { return getProject(java); -// } if (fSearchPageScoreComputer != null && ISearchPageScoreComputer.class.equals(key)) { -// return fSearchPageScoreComputer; -// } if (IWorkbenchAdapter.class.equals(key)) { -// return fgJavaWorkbenchAdapter; -// } if (IResourceLocator.class.equals(key)) { -// return fgResourceLocator; -// } if (IPersistableElement.class.equals(key)) { -// return new PersistableJavaElementFactory(java); - } if (IContributorResourceAdapter.class.equals(key)) { + // } if (fSearchPageScoreComputer != null && + // ISearchPageScoreComputer.class.equals(key)) { + // return fSearchPageScoreComputer; + // } if (IWorkbenchAdapter.class.equals(key)) { + // return fgJavaWorkbenchAdapter; + // } if (IResourceLocator.class.equals(key)) { + // return fgResourceLocator; + // } if (IPersistableElement.class.equals(key)) { + // return new PersistableJavaElementFactory(java); + } + if (IContributorResourceAdapter.class.equals(key)) { return this; -// } if (ITaskListResourceAdapter.class.equals(key)) { -// return fgTaskListAdapter; -// } if (IContainmentAdapter.class.equals(key)) { -// return fgJavaElementContainmentAdapter; + // } if (ITaskListResourceAdapter.class.equals(key)) { + // return fgTaskListAdapter; + // } if (IContainmentAdapter.class.equals(key)) { + // return fgJavaElementContainmentAdapter; } - return null; + return null; } - + private IResource getResource(IJavaElement element) { - // can't use IJavaElement.getResource directly as we are interrested in the + // can't use IJavaElement.getResource directly as we are interrested in + // the // corresponding resource switch (element.getElementType()) { - case IJavaElement.TYPE: - // top level types behave like the CU - IJavaElement parent= element.getParent(); - if (parent instanceof ICompilationUnit) { - return JavaModelUtil.toOriginal((ICompilationUnit) parent).getResource(); - } - return null; - case IJavaElement.COMPILATION_UNIT: - return JavaModelUtil.toOriginal((ICompilationUnit) element).getResource(); - case IJavaElement.CLASS_FILE: - case IJavaElement.PACKAGE_FRAGMENT: - // test if in a archive - IPackageFragmentRoot root= (IPackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); - if (!root.isArchive()) { - return element.getResource(); - } - return null; - case IJavaElement.PACKAGE_FRAGMENT_ROOT: - case IJavaElement.JAVA_PROJECT: - case IJavaElement.JAVA_MODEL: + case IJavaElement.TYPE: + // top level types behave like the CU + IJavaElement parent = element.getParent(); + if (parent instanceof ICompilationUnit) { + return JavaModelUtil.toOriginal((ICompilationUnit) parent) + .getResource(); + } + return null; + case IJavaElement.COMPILATION_UNIT: + return JavaModelUtil.toOriginal((ICompilationUnit) element) + .getResource(); + case IJavaElement.CLASS_FILE: + case IJavaElement.PACKAGE_FRAGMENT: + // test if in a archive + IPackageFragmentRoot root = (IPackageFragmentRoot) element + .getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); + if (!root.isArchive()) { return element.getResource(); - default: - return null; - } - } + } + return null; + case IJavaElement.PACKAGE_FRAGMENT_ROOT: + case IJavaElement.JAVA_PROJECT: + case IJavaElement.JAVA_MODEL: + return element.getResource(); + default: + return null; + } + } + + /* + * @see org.eclipse.ui.IContributorResourceAdapter#getAdaptedResource(org.eclipse.core.runtime.IAdaptable) + */ + public IResource getAdaptedResource(IAdaptable adaptable) { + return getResource((IJavaElement) adaptable); + } - /* - * @see org.eclipse.ui.IContributorResourceAdapter#getAdaptedResource(org.eclipse.core.runtime.IAdaptable) - */ - public IResource getAdaptedResource(IAdaptable adaptable) { - return getResource((IJavaElement)adaptable); - } - private IResource getProject(IJavaElement element) { return element.getJavaProject().getProject(); } private IPropertySource getProperties(IJavaElement element) { - IResource resource= getResource(element); + IResource resource = getResource(element); if (resource == null) return new JavaElementProperties(element); if (resource.getType() == IResource.FILE) @@ -137,24 +145,25 @@ public class JavaElementAdapterFactory implements IAdapterFactory, IContributorR return new ResourcePropertySource(resource); } -// private void updateLazyLoadedAdapters() { -// if (fSearchPageScoreComputer == null && SearchUtil.isSearchPlugInActivated()) -// createSearchPageScoreComputer(); -// } + // private void updateLazyLoadedAdapters() { + // if (fSearchPageScoreComputer == null && + // SearchUtil.isSearchPlugInActivated()) + // createSearchPageScoreComputer(); + // } -// private void createSearchPageScoreComputer() { -// fSearchPageScoreComputer= new JavaSearchPageScoreComputer(); -// PROPERTIES= new Class[] { -// IPropertySource.class, -// IResource.class, -// ISearchPageScoreComputer.class, -// IWorkbenchAdapter.class, -// IResourceLocator.class, -// IPersistableElement.class, -// IProject.class, -// IContributorResourceAdapter.class, -// ITaskListResourceAdapter.class, -// IContainmentAdapter.class -// }; -// } + // private void createSearchPageScoreComputer() { + // fSearchPageScoreComputer= new JavaSearchPageScoreComputer(); + // PROPERTIES= new Class[] { + // IPropertySource.class, + // IResource.class, + // ISearchPageScoreComputer.class, + // IWorkbenchAdapter.class, + // IResourceLocator.class, + // IPersistableElement.class, + // IProject.class, + // IContributorResourceAdapter.class, + // ITaskListResourceAdapter.class, + // IContainmentAdapter.class + // }; + // } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/JavaElementProperties.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/JavaElementProperties.java index bbb86bd..e6e3d0c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/JavaElementProperties.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/JavaElementProperties.java @@ -11,7 +11,6 @@ package net.sourceforge.phpdt.internal.ui; - import net.sourceforge.phpdt.core.IJavaElement; import org.eclipse.jface.viewers.IBasicPropertyConstants; @@ -20,46 +19,47 @@ import org.eclipse.ui.views.properties.IPropertySource; import org.eclipse.ui.views.properties.PropertyDescriptor; public class JavaElementProperties implements IPropertySource { - + private IJavaElement fSource; - + // Property Descriptors - static private IPropertyDescriptor[] fgPropertyDescriptors= new IPropertyDescriptor[1]; + static private IPropertyDescriptor[] fgPropertyDescriptors = new IPropertyDescriptor[1]; { PropertyDescriptor descriptor; // resource name - descriptor= new PropertyDescriptor(IBasicPropertyConstants.P_TEXT, PHPUIMessages.getString("JavaElementProperties.name")); //$NON-NLS-1$ + descriptor = new PropertyDescriptor(IBasicPropertyConstants.P_TEXT, + PHPUIMessages.getString("JavaElementProperties.name")); //$NON-NLS-1$ descriptor.setAlwaysIncompatible(true); - fgPropertyDescriptors[0]= descriptor; + fgPropertyDescriptors[0] = descriptor; } - + public JavaElementProperties(IJavaElement source) { - fSource= source; + fSource = source; } - + public IPropertyDescriptor[] getPropertyDescriptors() { return fgPropertyDescriptors; } - + public Object getPropertyValue(Object name) { if (name.equals(IBasicPropertyConstants.P_TEXT)) { return fSource.getElementName(); } return null; } - + public void setPropertyValue(Object name, Object value) { } - + public Object getEditableValue() { return this; } - + public boolean isPropertySet(Object property) { return false; } - + public void resetPropertyValue(Object property) { } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPStatusConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPStatusConstants.java index 48a007c..ef07e95 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPStatusConstants.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPStatusConstants.java @@ -5,24 +5,24 @@ package net.sourceforge.phpdt.internal.ui; /** - * Defines status codes relevant to the PHP UI plug-in. When a - * Core exception is thrown, it contain a status object describing - * the cause of the exception. The status objects originating from the - * PHP UI plug-in use the codes defined in this interface. - */ + * Defines status codes relevant to the PHP UI plug-in. When a Core exception is + * thrown, it contain a status object describing the cause of the exception. The + * status objects originating from the PHP UI plug-in use the codes defined in + * this interface. + */ public class PHPStatusConstants { - + // Prevent instantiation private PHPStatusConstants() { } /** Status code describing an internal error */ - public static final int INTERNAL_ERROR= 1; - + public static final int INTERNAL_ERROR = 1; + /** - * Status constant indicating that an exception occured on - * storing or loading templates. + * Status constant indicating that an exception occured on storing or + * loading templates. */ public static final int TEMPLATE_IO_EXCEPTION = 2; - + } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUIException.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUIException.java index 1a9be67..4db626b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUIException.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUIException.java @@ -4,18 +4,17 @@ */ package net.sourceforge.phpdt.internal.ui; - import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; /** - * An exception to wrap a status. This is necessary to use the core's IRunnableWithProgress - * support + * An exception to wrap a status. This is necessary to use the core's + * IRunnableWithProgress support */ public class PHPUIException extends CoreException { - + public PHPUIException(IStatus status) { super(status); - } + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUIMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUIMessages.java index 230c36a..76a0bd8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUIMessages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUIMessages.java @@ -12,7 +12,8 @@ public class PHPUIMessages { private static final String RESOURCE_BUNDLE = PHPUIMessages.class.getName();//$NON-NLS-1$ - private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); + private static ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); private PHPUIMessages() { } @@ -24,13 +25,13 @@ public class PHPUIMessages { return '!' + key + '!'; } } - + public static String getFormattedString(String key, String arg) { return getFormattedString(key, new String[] { arg }); } - + public static String getFormattedString(String key, String[] args) { - return MessageFormat.format(getString(key), args); - } - + return MessageFormat.format(getString(key), args); + } + } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUIStatus.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUIStatus.java index 4fcf12a..bdb4b78 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUIStatus.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUIStatus.java @@ -14,39 +14,45 @@ import org.eclipse.core.runtime.Status; */ public class PHPUIStatus extends Status { - public PHPUIStatus(int code) { - this(code, ""); //$NON-NLS-1$ - } - - private PHPUIStatus(int severity, int code, String message, Throwable throwable) { - super(severity, PHPeclipsePlugin.getPluginId(), code, message, throwable); - } - - public PHPUIStatus(int code, String message) { - this(code, message, null); - } - - public PHPUIStatus(int code, String message, Throwable throwable) { - super(IStatus.ERROR, PHPeclipsePlugin.getPluginId(), code, message, throwable); - } - - public static IStatus createError(int code, Throwable throwable) { - String message= throwable.getMessage(); - if (message == null) { - message= throwable.getClass().getName(); - } - return new PHPUIStatus(IStatus.ERROR, code, message, throwable); - } - - public static IStatus createError(int code, String message, Throwable throwable) { - return new PHPUIStatus(IStatus.ERROR, code, message, throwable); - } - - public static IStatus createInfo(int code, String message, Throwable throwable) { - return new PHPUIStatus(IStatus.INFO, code, message, throwable); - } - - public static IStatus createWarning(int code, String message, Throwable throwable) { - return new PHPUIStatus(IStatus.WARNING, code, message, throwable); - } + public PHPUIStatus(int code) { + this(code, ""); //$NON-NLS-1$ + } + + private PHPUIStatus(int severity, int code, String message, + Throwable throwable) { + super(severity, PHPeclipsePlugin.getPluginId(), code, message, + throwable); + } + + public PHPUIStatus(int code, String message) { + this(code, message, null); + } + + public PHPUIStatus(int code, String message, Throwable throwable) { + super(IStatus.ERROR, PHPeclipsePlugin.getPluginId(), code, message, + throwable); + } + + public static IStatus createError(int code, Throwable throwable) { + String message = throwable.getMessage(); + if (message == null) { + message = throwable.getClass().getName(); + } + return new PHPUIStatus(IStatus.ERROR, code, message, throwable); + } + + public static IStatus createError(int code, String message, + Throwable throwable) { + return new PHPUIStatus(IStatus.ERROR, code, message, throwable); + } + + public static IStatus createInfo(int code, String message, + Throwable throwable) { + return new PHPUIStatus(IStatus.INFO, code, message, throwable); + } + + public static IStatus createWarning(int code, String message, + Throwable throwable) { + return new PHPUIStatus(IStatus.WARNING, code, message, throwable); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUiImages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUiImages.java index 924c998..25a8c66 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUiImages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUiImages.java @@ -14,365 +14,760 @@ import org.eclipse.swt.graphics.Image; public class PHPUiImages { - protected static final String NAME_PREFIX = - "net.sourceforge.phpdt.internal.ui."; + protected static final String NAME_PREFIX = "net.sourceforge.phpdt.internal.ui."; + protected static final int NAME_PREFIX_LENGTH = NAME_PREFIX.length(); - protected static URL fgIconBaseURL=null; - -// static { -// String pathSuffix = "icons/"; -// try { -// fgIconBaseURL = -// new URL( -// PHPeclipsePlugin -// .getDefault() -// .getDescriptor() -// .getInstallURL(), -// pathSuffix); -// } catch (MalformedURLException e) { -// PHPeclipsePlugin.log(e); -// } -// } - -// Determine display depth. If depth > 4 then we use high color images. Otherwise low color + protected static URL fgIconBaseURL = null; + + // static { + // String pathSuffix = "icons/"; + // try { + // fgIconBaseURL = + // new URL( + // PHPeclipsePlugin + // .getDefault() + // .getDescriptor() + // .getInstallURL(), + // pathSuffix); + // } catch (MalformedURLException e) { + // PHPeclipsePlugin.log(e); + // } + // } + + // Determine display depth. If depth > 4 then we use high color images. + // Otherwise low color // images are used static { - fgIconBaseURL= PHPeclipsePlugin.getDefault().getBundle().getEntry("/icons/"); //$NON-NLS-1$ + fgIconBaseURL = PHPeclipsePlugin.getDefault().getBundle().getEntry( + "/icons/"); //$NON-NLS-1$ } - private static ImageRegistry fgImageRegistry= null; - private static HashMap fgAvoidSWTErrorMap= null; + + private static ImageRegistry fgImageRegistry = null; + + private static HashMap fgAvoidSWTErrorMap = null; protected static final String OBJ_PREFIX = "obj16"; + protected static final String OVR_PREFIX = "ovr16"; + protected static final String CTOOL_PREFIX = "ctool16"; - public static final String IMG_CLASS = NAME_PREFIX + "class_default_obj.gif"; + public static final String IMG_CLASS = NAME_PREFIX + + "class_default_obj.gif"; + public static final String IMG_DEFINE = NAME_PREFIX + "define_obj.gif"; + public static final String IMG_BUILTIN = NAME_PREFIX + "builtin_obj.gif"; + public static final String IMG_FUN = NAME_PREFIX + "fun_obj.gif"; + public static final String IMG_INC = NAME_PREFIX + "impc_obj.gif"; + public static final String IMG_VAR = NAME_PREFIX + "var_obj.gif"; public static final String IMG_TABLE = NAME_PREFIX + "table_obj.gif"; + public static final String IMG_COLUMN = NAME_PREFIX + "column_obj.gif"; - public static final String IMG_OBJS_WARNING = - NAME_PREFIX + "warning_obj.gif"; + public static final String IMG_OBJS_WARNING = NAME_PREFIX + + "warning_obj.gif"; + public static final String IMG_OBJS_INFO = NAME_PREFIX + "info_obj.gif"; - public static final String IMG_CTOOLS_PHP_PAGE = - NAME_PREFIX + "php_page.gif"; + + public static final String IMG_CTOOLS_PHP_PAGE = NAME_PREFIX + + "php_page.gif"; + public static final String IMG_CTOOLS_PHP = NAME_PREFIX + "php.gif"; public static final String IMG_CLEAR = NAME_PREFIX + "clear.gif"; - public static final ImageDescriptor DESC_CLASS = - createManaged(OBJ_PREFIX, IMG_CLASS); - public static final ImageDescriptor DESC_DEFINE = - createManaged(OBJ_PREFIX, IMG_DEFINE); - public static final ImageDescriptor DESC_BUILTIN = - createManaged(OBJ_PREFIX, IMG_BUILTIN); - public static final ImageDescriptor DESC_FUN = - createManaged(OBJ_PREFIX, IMG_FUN); - public static final ImageDescriptor DESC_INC = - createManaged(OBJ_PREFIX, IMG_INC); - public static final ImageDescriptor DESC_VAR = - createManaged(OBJ_PREFIX, IMG_VAR); - - public static final ImageDescriptor DESC_TABLE = - createManaged(OBJ_PREFIX, IMG_TABLE); - public static final ImageDescriptor DESC_COLUMN = - createManaged(OBJ_PREFIX, IMG_COLUMN); - - public static final ImageDescriptor DESC_OBJS_WARNING = - createManaged(OBJ_PREFIX, IMG_OBJS_WARNING); - public static final ImageDescriptor DESC_OBJS_INFO = - createManaged(OBJ_PREFIX, IMG_OBJS_INFO); - public static final ImageDescriptor DESC_CTOOL_PHP_PAGE = - createManaged(CTOOL_PREFIX, IMG_CTOOLS_PHP_PAGE); - public static final ImageDescriptor DESC_CTOOL_PHP = - createManaged(CTOOL_PREFIX, IMG_CTOOLS_PHP); - - - public static final ImageDescriptor DESC_CLEAR = - createManaged(OBJ_PREFIX, IMG_CLEAR); + public static final ImageDescriptor DESC_CLASS = createManaged(OBJ_PREFIX, + IMG_CLASS); + + public static final ImageDescriptor DESC_DEFINE = createManaged(OBJ_PREFIX, + IMG_DEFINE); + + public static final ImageDescriptor DESC_BUILTIN = createManaged( + OBJ_PREFIX, IMG_BUILTIN); + + public static final ImageDescriptor DESC_FUN = createManaged(OBJ_PREFIX, + IMG_FUN); + + public static final ImageDescriptor DESC_INC = createManaged(OBJ_PREFIX, + IMG_INC); + + public static final ImageDescriptor DESC_VAR = createManaged(OBJ_PREFIX, + IMG_VAR); + + public static final ImageDescriptor DESC_TABLE = createManaged(OBJ_PREFIX, + IMG_TABLE); + + public static final ImageDescriptor DESC_COLUMN = createManaged(OBJ_PREFIX, + IMG_COLUMN); + + public static final ImageDescriptor DESC_OBJS_WARNING = createManaged( + OBJ_PREFIX, IMG_OBJS_WARNING); + + public static final ImageDescriptor DESC_OBJS_INFO = createManaged( + OBJ_PREFIX, IMG_OBJS_INFO); + + public static final ImageDescriptor DESC_CTOOL_PHP_PAGE = createManaged( + CTOOL_PREFIX, IMG_CTOOLS_PHP_PAGE); + + public static final ImageDescriptor DESC_CTOOL_PHP = createManaged( + CTOOL_PREFIX, IMG_CTOOLS_PHP); + + public static final ImageDescriptor DESC_CLEAR = createManaged(OBJ_PREFIX, + IMG_CLEAR); /* - * Set of predefined Image Descriptors. - */ - private static final String T_OBJ= "obj16"; //$NON-NLS-1$ - private static final String T_OVR= "ovr16"; //$NON-NLS-1$ - private static final String T_WIZBAN= "wizban"; //$NON-NLS-1$ - private static final String T_CLCL= "clcl16"; //$NON-NLS-1$ - private static final String T_DLCL= "dlcl16"; //$NON-NLS-1$ - private static final String T_ELCL= "elcl16"; //$NON-NLS-1$ - private static final String T_CTOOL= "ctool16"; //$NON-NLS-1$ - private static final String T_CVIEW= "cview16"; //$NON-NLS-1$ - - public static final ImageDescriptor DESC_WIZBAN_NEWCLASS= create(T_WIZBAN, "newclass_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_ELCL_FILTER= create(T_ELCL, "filter_ps.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_DLCL_FILTER= create(T_DLCL, "filter_ps.gif"); //$NON-NLS-1$ + * Set of predefined Image Descriptors. + */ + private static final String T_OBJ = "obj16"; //$NON-NLS-1$ + + private static final String T_OVR = "ovr16"; //$NON-NLS-1$ + + private static final String T_WIZBAN = "wizban"; //$NON-NLS-1$ + + private static final String T_CLCL = "clcl16"; //$NON-NLS-1$ + + private static final String T_DLCL = "dlcl16"; //$NON-NLS-1$ + + private static final String T_ELCL = "elcl16"; //$NON-NLS-1$ + + private static final String T_CTOOL = "ctool16"; //$NON-NLS-1$ + + private static final String T_CVIEW = "cview16"; //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_NEWCLASS = create(T_WIZBAN, + "newclass_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_ELCL_FILTER = create(T_ELCL, + "filter_ps.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_DLCL_FILTER = create(T_DLCL, + "filter_ps.gif"); //$NON-NLS-1$ /* * Available cached Images in the Java plugin image registry. */ - public static final String IMG_MISC_PUBLIC= NAME_PREFIX + "methpub_obj.gif"; //$NON-NLS-1$ - public static final String IMG_MISC_PROTECTED= NAME_PREFIX + "methpro_obj.gif"; //$NON-NLS-1$ - public static final String IMG_MISC_PRIVATE= NAME_PREFIX + "methpri_obj.gif"; //$NON-NLS-1$ - public static final String IMG_MISC_DEFAULT= NAME_PREFIX + "methdef_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_FIELD_PUBLIC= NAME_PREFIX + "field_public_obj.gif"; //$NON-NLS-1$ - public static final String IMG_FIELD_PROTECTED= NAME_PREFIX + "field_protected_obj.gif"; //$NON-NLS-1$ - public static final String IMG_FIELD_PRIVATE= NAME_PREFIX + "field_private_obj.gif"; //$NON-NLS-1$ - public static final String IMG_FIELD_DEFAULT= NAME_PREFIX + "field_default_obj.gif"; //$NON-NLS-1$ - - - public static final String IMG_OBJS_GHOST= NAME_PREFIX + "ghost.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_SEARCH_TSK= NAME_PREFIX + "search_tsk.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_PACKDECL= NAME_PREFIX + "packd_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_IMPDECL= NAME_PREFIX + "imp_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_IMPCONT= NAME_PREFIX + "impc_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_JSEARCH= NAME_PREFIX + "jsearch_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_SEARCH_DECL= NAME_PREFIX + "search_decl_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_SEARCH_REF= NAME_PREFIX + "search_ref_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_CLASS= NAME_PREFIX + "class_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_CLASSALT= NAME_PREFIX + "classfo_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_CLASS_DEFAULT= NAME_PREFIX + "class_default_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_INTERFACE= NAME_PREFIX + "int_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_INTERFACEALT= NAME_PREFIX + "intf_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_INTERFACE_DEFAULT= NAME_PREFIX + "int_default_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_CUNIT= NAME_PREFIX + "phpedit.png"; //$NON-NLS-1$ - public static final String IMG_OBJS_CUNIT_RESOURCE= NAME_PREFIX + "jcu_resource_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_CFILE= NAME_PREFIX + "classf_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_CFILECLASS= NAME_PREFIX + "class_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_CFILEINT= NAME_PREFIX + "int_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_LOGICAL_PACKAGE= NAME_PREFIX + "logical_package_obj.gif";//$NON-NLS-1$ - public static final String IMG_OJS_EMPTY_LOGICAL_PACKAGE= NAME_PREFIX + "empty_logical_package_obj.gif";//$NON-NLS-1$ - public static final String IMG_OBJS_PACKAGE= NAME_PREFIX + "package_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_EMPTY_PACK_RESOURCE= NAME_PREFIX + "empty_pack_fldr_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_EMPTY_PACKAGE= NAME_PREFIX + "empty_pack_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_PACKFRAG_ROOT= NAME_PREFIX + "packagefolder_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_MISSING_PACKFRAG_ROOT= NAME_PREFIX + "packagefolder_nonexist_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_MISSING_JAR= NAME_PREFIX + "jar_nonexist_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_JAR= NAME_PREFIX + "jar_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_EXTJAR= NAME_PREFIX + "jar_l_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_JAR_WSRC= NAME_PREFIX + "jar_src_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_EXTJAR_WSRC= NAME_PREFIX + "jar_lsrc_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_ENV_VAR= NAME_PREFIX + "envvar_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_MISSING_ENV_VAR= NAME_PREFIX + "envvar_nonexist_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_JAVA_MODEL= NAME_PREFIX + "java_model_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_UNKNOWN= NAME_PREFIX + "unknown_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_LIBRARY= NAME_PREFIX + "library_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_JAVADOCTAG= NAME_PREFIX + "jdoc_tag_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_HTMLTAG= NAME_PREFIX + "html_tag_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_TEMPLATE= NAME_PREFIX + "template_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_EXCEPTION= NAME_PREFIX + "jexception_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_ERROR= NAME_PREFIX + "jrtexception_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_BREAKPOINT_INSTALLED= NAME_PREFIX + "brkpi_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_FIXABLE_PROBLEM= NAME_PREFIX + "quickfix_warning_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_FIXABLE_ERROR= NAME_PREFIX + "quickfix_error_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_SNIPPET_EVALUATING= NAME_PREFIX + "jsbook_run_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_REFACTORING_FATAL= NAME_PREFIX + "fatalerror_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_REFACTORING_ERROR= NAME_PREFIX + "error_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_REFACTORING_WARNING= NAME_PREFIX + "warning_obj.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_REFACTORING_INFO= NAME_PREFIX + "info_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_NLS_TRANSLATE= NAME_PREFIX + "translate.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_NLS_NEVER_TRANSLATE= NAME_PREFIX + "never_translate.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_NLS_SKIP= NAME_PREFIX + "skip.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_SEARCH_READACCESS= NAME_PREFIX + "occ_read.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_SEARCH_WRITEACCESS= NAME_PREFIX + "occ_write.gif"; //$NON-NLS-1$ - public static final String IMG_OBJS_SEARCH_OCCURRENCE= NAME_PREFIX + "occ_match.gif"; //$NON-NLS-1$ - - public static final ImageDescriptor DESC_VIEW_ERRORWARNING_TAB= create(T_CVIEW, "errorwarning_tab.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_VIEW_CLASSFILEGENERATION_TAB= create(T_CVIEW, "classfilegeneration_tab.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_VIEW_JDKCOMPLIANCE_TAB= create(T_CVIEW, "jdkcompliance_tab.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_CLCL_FILTER= create(T_CLCL, "filter_ps.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_CLCL_CODE_ASSIST= create(T_CLCL, "metharg_obj.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_DLCL_CODE_ASSIST= create(T_DLCL, "metharg_obj.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_MISC_PUBLIC= createManaged(T_OBJ, IMG_MISC_PUBLIC); - public static final ImageDescriptor DESC_MISC_PROTECTED= createManaged(T_OBJ, IMG_MISC_PROTECTED); - public static final ImageDescriptor DESC_MISC_PRIVATE= createManaged(T_OBJ, IMG_MISC_PRIVATE); - public static final ImageDescriptor DESC_MISC_DEFAULT= createManaged(T_OBJ, IMG_MISC_DEFAULT); - - public static final ImageDescriptor DESC_FIELD_PUBLIC= createManaged(T_OBJ, IMG_FIELD_PUBLIC); //$NON-NLS-1$ - public static final ImageDescriptor DESC_FIELD_PROTECTED= createManaged(T_OBJ, IMG_FIELD_PROTECTED); //$NON-NLS-1$ - public static final ImageDescriptor DESC_FIELD_PRIVATE= createManaged(T_OBJ, IMG_FIELD_PRIVATE); //$NON-NLS-1$ - public static final ImageDescriptor DESC_FIELD_DEFAULT= createManaged(T_OBJ, IMG_FIELD_DEFAULT); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_MENU_SHIFT_RIGHT= create(T_CTOOL, "shift_r_edit.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_MENU_SHIFT_LEFT= create(T_CTOOL, "shift_l_edit.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OBJS_GHOST= createManaged(T_OBJ, IMG_OBJS_GHOST); - public static final ImageDescriptor DESC_OBJS_PACKDECL= createManaged(T_OBJ, IMG_OBJS_PACKDECL); - public static final ImageDescriptor DESC_OBJS_IMPDECL= createManaged(T_OBJ, IMG_OBJS_IMPDECL); - public static final ImageDescriptor DESC_OBJS_IMPCONT= createManaged(T_OBJ, IMG_OBJS_IMPCONT); - public static final ImageDescriptor DESC_OBJS_JSEARCH= createManaged(T_OBJ, IMG_OBJS_JSEARCH); - public static final ImageDescriptor DESC_OBJS_SEARCH_DECL= createManaged(T_OBJ, IMG_OBJS_SEARCH_DECL); - public static final ImageDescriptor DESC_OBJS_SEARCH_REF= createManaged(T_OBJ, IMG_OBJS_SEARCH_REF); - public static final ImageDescriptor DESC_OBJS_CUNIT= createManaged(T_OBJ, IMG_OBJS_CUNIT); - public static final ImageDescriptor DESC_OBJS_CUNIT_RESOURCE= createManaged(T_OBJ, IMG_OBJS_CUNIT_RESOURCE); - public static final ImageDescriptor DESC_OBJS_CFILE= createManaged(T_OBJ, IMG_OBJS_CFILE); - public static final ImageDescriptor DESC_OBJS_CFILECLASS= createManaged(T_OBJ, IMG_OBJS_CFILECLASS); - public static final ImageDescriptor DESC_OBJS_CFILEINT= createManaged(T_OBJ, IMG_OBJS_CFILEINT); - public static final ImageDescriptor DESC_OBJS_PACKAGE= createManaged(T_OBJ, IMG_OBJS_PACKAGE); - public static final ImageDescriptor DESC_OBJS_EMPTY_LOGICAL_PACKAGE= createManaged(T_OBJ, IMG_OJS_EMPTY_LOGICAL_PACKAGE); - public static final ImageDescriptor DESC_OBJS_LOGICAL_PACKAGE= createManaged(T_OBJ, IMG_OBJS_LOGICAL_PACKAGE); - public static final ImageDescriptor DESC_OBJS_EMPTY_PACKAGE_RESOURCES= createManaged(T_OBJ, IMG_OBJS_EMPTY_PACK_RESOURCE); - public static final ImageDescriptor DESC_OBJS_EMPTY_PACKAGE= createManaged(T_OBJ, IMG_OBJS_EMPTY_PACKAGE); - public static final ImageDescriptor DESC_OBJS_PACKFRAG_ROOT= createManaged(T_OBJ, IMG_OBJS_PACKFRAG_ROOT); - public static final ImageDescriptor DESC_OBJS_MISSING_PACKFRAG_ROOT= createManaged(T_OBJ, IMG_OBJS_MISSING_PACKFRAG_ROOT); - public static final ImageDescriptor DESC_OBJS_JAVA_MODEL= createManaged(T_OBJ, IMG_OBJS_JAVA_MODEL); - - public static final ImageDescriptor DESC_OBJS_CLASS= createManaged(T_OBJ, IMG_OBJS_CLASS); - public static final ImageDescriptor DESC_OBJS_CLASS_DEFAULT= createManaged(T_OBJ, IMG_OBJS_CLASS_DEFAULT); - - public static final ImageDescriptor DESC_OBJS_INNER_CLASS_PUBLIC= create(T_OBJ, "innerclass_public_obj.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_OBJS_INNER_CLASS_DEFAULT= create(T_OBJ, "innerclass_default_obj.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_OBJS_INNER_CLASS_PROTECTED= create(T_OBJ, "innerclass_protected_obj.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_OBJS_INNER_CLASS_PRIVATE= create(T_OBJ, "innerclass_private_obj.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OBJS_CLASSALT= createManaged(T_OBJ, IMG_OBJS_CLASSALT); - - public static final ImageDescriptor DESC_OBJS_INTERFACE= createManaged(T_OBJ, IMG_OBJS_INTERFACE); - public static final ImageDescriptor DESC_OBJS_INTERFACE_DEFAULT= createManaged(T_OBJ, IMG_OBJS_INTERFACE_DEFAULT); - - public static final ImageDescriptor DESC_OBJS_INNER_INTERFACE_PUBLIC= create(T_OBJ, "innerinterface_public_obj.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_OBJS_INNER_INTERFACE_DEFAULT= create(T_OBJ, "innerinterface_default_obj.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_OBJS_INNER_INTERFACE_PROTECTED= create(T_OBJ, "innerinterface_protected_obj.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_OBJS_INNER_INTERFACE_PRIVATE= create(T_OBJ, "innerinterface_private_obj.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OBJS_INTERFACEALT= createManaged(T_OBJ, IMG_OBJS_INTERFACEALT); - - public static final ImageDescriptor DESC_OBJS_JAR= createManaged(T_OBJ, IMG_OBJS_JAR); - public static final ImageDescriptor DESC_OBJS_MISSING_JAR= createManaged(T_OBJ, IMG_OBJS_MISSING_JAR); - public static final ImageDescriptor DESC_OBJS_EXTJAR= createManaged(T_OBJ, IMG_OBJS_EXTJAR); - public static final ImageDescriptor DESC_OBJS_JAR_WSRC= createManaged(T_OBJ, IMG_OBJS_JAR_WSRC); - public static final ImageDescriptor DESC_OBJS_EXTJAR_WSRC= createManaged(T_OBJ, IMG_OBJS_EXTJAR_WSRC); - public static final ImageDescriptor DESC_OBJS_ENV_VAR= createManaged(T_OBJ, IMG_OBJS_ENV_VAR); - public static final ImageDescriptor DESC_OBJS_MISSING_ENV_VAR= createManaged(T_OBJ, IMG_OBJS_MISSING_ENV_VAR); - - public static final ImageDescriptor DESC_OBJS_LIBRARY= createManaged(T_OBJ, IMG_OBJS_LIBRARY); - - public static final ImageDescriptor DESC_OBJS_JAVADOCTAG= createManaged(T_OBJ, IMG_OBJS_JAVADOCTAG); - public static final ImageDescriptor DESC_OBJS_HTMLTAG= createManaged(T_OBJ, IMG_OBJS_HTMLTAG); - - public static final ImageDescriptor DESC_OBJS_TEMPLATE= createManaged(T_OBJ, IMG_OBJS_TEMPLATE); - - public static final ImageDescriptor DESC_OBJS_EXCEPTION= createManaged(T_OBJ, IMG_OBJS_EXCEPTION); - public static final ImageDescriptor DESC_OBJS_BREAKPOINT_INSTALLED= createManaged(T_OBJ, IMG_OBJS_BREAKPOINT_INSTALLED); - public static final ImageDescriptor DESC_OBJS_ERROR= createManaged(T_OBJ, IMG_OBJS_ERROR); - public static final ImageDescriptor DESC_OBJS_FIXABLE_PROBLEM= createManaged(T_OBJ, IMG_OBJS_FIXABLE_PROBLEM); - public static final ImageDescriptor DESC_OBJS_FIXABLE_ERROR= createManaged(T_OBJ, IMG_OBJS_FIXABLE_ERROR); - - public static final ImageDescriptor DESC_OBJS_SNIPPET_EVALUATING= createManaged(T_OBJ, IMG_OBJS_SNIPPET_EVALUATING); - - public static final ImageDescriptor DESC_OBJS_DEFAULT_CHANGE= create(T_OBJ, "change.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_OBJS_COMPOSITE_CHANGE= create(T_OBJ, "composite_change.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_OBJS_CU_CHANGE= create(T_OBJ, "cu_change.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_OBJS_FILE_CHANGE= create(T_OBJ, "file_change.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_OBJS_TEXT_EDIT= create(T_OBJ, "text_edit.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OBJS_EXCLUSION_FILTER_ATTRIB= create(T_OBJ, "exclusion_filter_attrib.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_OBJS_OUTPUT_FOLDER_ATTRIB= create(T_OBJ, "output_folder_attrib.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_OBJS_SOURCE_ATTACH_ATTRIB= create(T_OBJ, "source_attach_attrib.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_OBJS_JAVADOC_LOCATION_ATTRIB= create(T_OBJ, "javadoc_location_attrib.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OBJS_REFACTORING_FATAL= createManaged(T_OBJ, IMG_OBJS_REFACTORING_FATAL); - public static final ImageDescriptor DESC_OBJS_REFACTORING_ERROR= createManaged(T_OBJ, IMG_OBJS_REFACTORING_ERROR); - public static final ImageDescriptor DESC_OBJS_REFACTORING_WARNING= createManaged(T_OBJ, IMG_OBJS_REFACTORING_WARNING); - public static final ImageDescriptor DESC_OBJS_REFACTORING_INFO= createManaged(T_OBJ, IMG_OBJS_REFACTORING_INFO); - - public static final ImageDescriptor DESC_OBJS_NLS_TRANSLATE= createManaged(T_OBJ, IMG_OBJS_NLS_TRANSLATE); - public static final ImageDescriptor DESC_OBJS_NLS_NEVER_TRANSLATE= createManaged(T_OBJ, IMG_OBJS_NLS_NEVER_TRANSLATE); - public static final ImageDescriptor DESC_OBJS_NLS_SKIP= createManaged(T_OBJ, IMG_OBJS_NLS_SKIP); - - public static final ImageDescriptor DESC_OBJS_UNKNOWN= createManaged(T_OBJ, IMG_OBJS_UNKNOWN); - - public static final ImageDescriptor DESC_OBJS_SEARCH_READACCESS= createManaged(T_OBJ, IMG_OBJS_SEARCH_READACCESS); - public static final ImageDescriptor DESC_OBJS_SEARCH_WRITEACCESS= createManaged(T_OBJ, IMG_OBJS_SEARCH_WRITEACCESS); - public static final ImageDescriptor DESC_OBJS_SEARCH_OCCURRENCE= createManaged(T_OBJ, IMG_OBJS_SEARCH_OCCURRENCE); - - public static final ImageDescriptor DESC_OBJS_LOCAL_VARIABLE= create(T_OBJ, "localvariable_obj.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OVR_STATIC= create(T_OVR, "static_co.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_OVR_FINAL= create(T_OVR, "final_co.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_OVR_ABSTRACT= create(T_OVR, "abstract_co.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_OVR_SYNCH= create(T_OVR, "synch_co.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_OVR_RUN= create(T_OVR, "run_co.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_OVR_WARNING= create(T_OVR, "warning_co.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_OVR_ERROR= create(T_OVR, "error_co.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_OVR_OVERRIDES= create(T_OVR, "over_co.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_OVR_IMPLEMENTS= create(T_OVR, "implm_co.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_OVR_CONSTRUCTOR= create(T_OVR, "constr_ovr.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_OVR_FOCUS= create(T_OVR, "focus_ovr.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_WIZBAN_NEWFIELD= create(T_WIZBAN, "newfield_wiz.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_WIZBAN_NEWINT= create(T_WIZBAN, "newint_wiz.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_WIZBAN_NEWJPRJ= create(T_WIZBAN, "newjprj_wiz.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_WIZBAN_NEWSRCFOLDR= create(T_WIZBAN, "newsrcfldr_wiz.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_WIZBAN_NEWMETH= create(T_WIZBAN, "newmeth_wiz.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_WIZBAN_NEWPACK= create(T_WIZBAN, "newpack_wiz.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_WIZBAN_NEWSCRAPPAGE= create(T_WIZBAN, "newsbook_wiz.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_WIZBAN_JAVA_LAUNCH= create(T_WIZBAN, "java_app_wiz.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_WIZBAN_JAVA_ATTACH= create(T_WIZBAN, "java_attach_wiz.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_WIZBAN_REFACTOR= create(T_WIZBAN, "refactor_wiz.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_WIZBAN_REFACTOR_FIELD= create(T_WIZBAN, "fieldrefact_wiz.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_WIZBAN_REFACTOR_METHOD= create(T_WIZBAN, "methrefact_wiz.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_WIZBAN_REFACTOR_TYPE= create(T_WIZBAN, "typerefact_wiz.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_WIZBAN_REFACTOR_PACKAGE= create(T_WIZBAN, "packrefact_wiz.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_WIZBAN_REFACTOR_CODE= create(T_WIZBAN, "coderefact_wiz.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_WIZBAN_REFACTOR_CU= create(T_WIZBAN, "compunitrefact_wiz.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_WIZBAN_REFACTOR_PULL_UP= create(T_WIZBAN, "pullup_wiz.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_WIZBAN_JAR_PACKAGER= create(T_WIZBAN, "jar_pack_wiz.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_WIZBAN_JAVA_WORKINGSET= create(T_WIZBAN, "java_workingset_wiz.gif");//$NON-NLS-1$ - public static final ImageDescriptor DESC_WIZBAN_EXPORT_JAVADOC= create(T_WIZBAN, "export_javadoc_wiz.gif");//$NON-NLS-1$ - public static final ImageDescriptor DESC_WIZBAN_EXTERNALIZE_STRINGS= create(T_WIZBAN, "extstr_wiz.gif");//$NON-NLS-1$ - public static final ImageDescriptor DESC_WIZBAN_ADD_LIBRARY= create(T_WIZBAN, "addlibrary_wiz.gif");//$NON-NLS-1$ - - - public static final ImageDescriptor DESC_TOOL_DISPLAYSNIPPET= create(T_CTOOL, "disp_sbook.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_TOOL_RUNSNIPPET= create(T_CTOOL, "run_sbook.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_TOOL_INSPSNIPPET= create(T_CTOOL, "insp_sbook.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_TOOL_PACKSNIPPET= create(T_CTOOL, "pack_sbook.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_TOOL_TERMSNIPPET= create(T_CTOOL, "term_sbook.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_TOOL_SHOW_EMPTY_PKG= create(T_CTOOL, "show_empty_pkg.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_TOOL_SHOW_SEGMENTS= create(T_CTOOL, "segment_edit.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_TOOL_GOTO_NEXT_ERROR= create(T_CTOOL, "next_error_nav.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_TOOL_GOTO_PREV_ERROR= create(T_CTOOL, "prev_error_nav.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_TOOL_OPENTYPE= create(T_CTOOL, "opentype.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_TOOL_NEWPROJECT= create(T_CTOOL, "newjprj_wiz.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_TOOL_NEWPACKAGE= create(T_CTOOL, "newpack_wiz.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_TOOL_NEWCLASS= create(T_CTOOL, "newclass_wiz.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_TOOL_NEWINTERFACE= create(T_CTOOL, "newint_wiz.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_TOOL_NEWSNIPPET= create(T_CTOOL, "newsbook_wiz.gif"); //$NON-NLS-1$ - public static final ImageDescriptor DESC_TOOL_NEWPACKROOT= create(T_CTOOL, "newpackfolder_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_TOOL_CLASSPATH_ORDER= create(T_OBJ, "cp_order_obj.gif"); //$NON-NLS-1$ - - // Keys for correction proposal. We have to put the image into the registry since "code assist" doesn't + public static final String IMG_MISC_PUBLIC = NAME_PREFIX + + "methpub_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_MISC_PROTECTED = NAME_PREFIX + + "methpro_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_MISC_PRIVATE = NAME_PREFIX + + "methpri_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_MISC_DEFAULT = NAME_PREFIX + + "methdef_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_FIELD_PUBLIC = NAME_PREFIX + + "field_public_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_FIELD_PROTECTED = NAME_PREFIX + + "field_protected_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_FIELD_PRIVATE = NAME_PREFIX + + "field_private_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_FIELD_DEFAULT = NAME_PREFIX + + "field_default_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_GHOST = NAME_PREFIX + "ghost.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_SEARCH_TSK = NAME_PREFIX + + "search_tsk.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_PACKDECL = NAME_PREFIX + + "packd_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_IMPDECL = NAME_PREFIX + "imp_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_IMPCONT = NAME_PREFIX + "impc_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_JSEARCH = NAME_PREFIX + + "jsearch_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_SEARCH_DECL = NAME_PREFIX + + "search_decl_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_SEARCH_REF = NAME_PREFIX + + "search_ref_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_CLASS = NAME_PREFIX + "class_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_CLASSALT = NAME_PREFIX + + "classfo_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_CLASS_DEFAULT = NAME_PREFIX + + "class_default_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_INTERFACE = NAME_PREFIX + "int_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_INTERFACEALT = NAME_PREFIX + + "intf_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_INTERFACE_DEFAULT = NAME_PREFIX + + "int_default_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_CUNIT = NAME_PREFIX + "phpedit.png"; //$NON-NLS-1$ + + public static final String IMG_OBJS_CUNIT_RESOURCE = NAME_PREFIX + + "jcu_resource_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_CFILE = NAME_PREFIX + "classf_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_CFILECLASS = NAME_PREFIX + + "class_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_CFILEINT = NAME_PREFIX + "int_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_LOGICAL_PACKAGE = NAME_PREFIX + + "logical_package_obj.gif";//$NON-NLS-1$ + + public static final String IMG_OJS_EMPTY_LOGICAL_PACKAGE = NAME_PREFIX + + "empty_logical_package_obj.gif";//$NON-NLS-1$ + + public static final String IMG_OBJS_PACKAGE = NAME_PREFIX + + "package_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_EMPTY_PACK_RESOURCE = NAME_PREFIX + + "empty_pack_fldr_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_EMPTY_PACKAGE = NAME_PREFIX + + "empty_pack_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_PACKFRAG_ROOT = NAME_PREFIX + + "packagefolder_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_MISSING_PACKFRAG_ROOT = NAME_PREFIX + + "packagefolder_nonexist_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_MISSING_JAR = NAME_PREFIX + + "jar_nonexist_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_JAR = NAME_PREFIX + "jar_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_EXTJAR = NAME_PREFIX + "jar_l_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_JAR_WSRC = NAME_PREFIX + + "jar_src_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_EXTJAR_WSRC = NAME_PREFIX + + "jar_lsrc_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_ENV_VAR = NAME_PREFIX + + "envvar_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_MISSING_ENV_VAR = NAME_PREFIX + + "envvar_nonexist_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_JAVA_MODEL = NAME_PREFIX + + "java_model_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_UNKNOWN = NAME_PREFIX + + "unknown_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_LIBRARY = NAME_PREFIX + + "library_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_JAVADOCTAG = NAME_PREFIX + + "jdoc_tag_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_HTMLTAG = NAME_PREFIX + + "html_tag_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_TEMPLATE = NAME_PREFIX + + "template_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_EXCEPTION = NAME_PREFIX + + "jexception_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_ERROR = NAME_PREFIX + + "jrtexception_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_BREAKPOINT_INSTALLED = NAME_PREFIX + + "brkpi_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_FIXABLE_PROBLEM = NAME_PREFIX + + "quickfix_warning_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_FIXABLE_ERROR = NAME_PREFIX + + "quickfix_error_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_SNIPPET_EVALUATING = NAME_PREFIX + + "jsbook_run_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_REFACTORING_FATAL = NAME_PREFIX + + "fatalerror_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_REFACTORING_ERROR = NAME_PREFIX + + "error_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_REFACTORING_WARNING = NAME_PREFIX + + "warning_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_REFACTORING_INFO = NAME_PREFIX + + "info_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_NLS_TRANSLATE = NAME_PREFIX + + "translate.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_NLS_NEVER_TRANSLATE = NAME_PREFIX + + "never_translate.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_NLS_SKIP = NAME_PREFIX + "skip.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_SEARCH_READACCESS = NAME_PREFIX + + "occ_read.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_SEARCH_WRITEACCESS = NAME_PREFIX + + "occ_write.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_SEARCH_OCCURRENCE = NAME_PREFIX + + "occ_match.gif"; //$NON-NLS-1$ + + public static final ImageDescriptor DESC_VIEW_ERRORWARNING_TAB = create( + T_CVIEW, "errorwarning_tab.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_VIEW_CLASSFILEGENERATION_TAB = create( + T_CVIEW, "classfilegeneration_tab.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_VIEW_JDKCOMPLIANCE_TAB = create( + T_CVIEW, "jdkcompliance_tab.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_CLCL_FILTER = create(T_CLCL, + "filter_ps.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_CLCL_CODE_ASSIST = create(T_CLCL, + "metharg_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_DLCL_CODE_ASSIST = create(T_DLCL, + "metharg_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_MISC_PUBLIC = createManaged(T_OBJ, + IMG_MISC_PUBLIC); + + public static final ImageDescriptor DESC_MISC_PROTECTED = createManaged( + T_OBJ, IMG_MISC_PROTECTED); + + public static final ImageDescriptor DESC_MISC_PRIVATE = createManaged( + T_OBJ, IMG_MISC_PRIVATE); + + public static final ImageDescriptor DESC_MISC_DEFAULT = createManaged( + T_OBJ, IMG_MISC_DEFAULT); + + public static final ImageDescriptor DESC_FIELD_PUBLIC = createManaged( + T_OBJ, IMG_FIELD_PUBLIC); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_FIELD_PROTECTED = createManaged( + T_OBJ, IMG_FIELD_PROTECTED); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_FIELD_PRIVATE = createManaged( + T_OBJ, IMG_FIELD_PRIVATE); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_FIELD_DEFAULT = createManaged( + T_OBJ, IMG_FIELD_DEFAULT); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_MENU_SHIFT_RIGHT = create(T_CTOOL, + "shift_r_edit.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_MENU_SHIFT_LEFT = create(T_CTOOL, + "shift_l_edit.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_GHOST = createManaged(T_OBJ, + IMG_OBJS_GHOST); + + public static final ImageDescriptor DESC_OBJS_PACKDECL = createManaged( + T_OBJ, IMG_OBJS_PACKDECL); + + public static final ImageDescriptor DESC_OBJS_IMPDECL = createManaged( + T_OBJ, IMG_OBJS_IMPDECL); + + public static final ImageDescriptor DESC_OBJS_IMPCONT = createManaged( + T_OBJ, IMG_OBJS_IMPCONT); + + public static final ImageDescriptor DESC_OBJS_JSEARCH = createManaged( + T_OBJ, IMG_OBJS_JSEARCH); + + public static final ImageDescriptor DESC_OBJS_SEARCH_DECL = createManaged( + T_OBJ, IMG_OBJS_SEARCH_DECL); + + public static final ImageDescriptor DESC_OBJS_SEARCH_REF = createManaged( + T_OBJ, IMG_OBJS_SEARCH_REF); + + public static final ImageDescriptor DESC_OBJS_CUNIT = createManaged(T_OBJ, + IMG_OBJS_CUNIT); + + public static final ImageDescriptor DESC_OBJS_CUNIT_RESOURCE = createManaged( + T_OBJ, IMG_OBJS_CUNIT_RESOURCE); + + public static final ImageDescriptor DESC_OBJS_CFILE = createManaged(T_OBJ, + IMG_OBJS_CFILE); + + public static final ImageDescriptor DESC_OBJS_CFILECLASS = createManaged( + T_OBJ, IMG_OBJS_CFILECLASS); + + public static final ImageDescriptor DESC_OBJS_CFILEINT = createManaged( + T_OBJ, IMG_OBJS_CFILEINT); + + public static final ImageDescriptor DESC_OBJS_PACKAGE = createManaged( + T_OBJ, IMG_OBJS_PACKAGE); + + public static final ImageDescriptor DESC_OBJS_EMPTY_LOGICAL_PACKAGE = createManaged( + T_OBJ, IMG_OJS_EMPTY_LOGICAL_PACKAGE); + + public static final ImageDescriptor DESC_OBJS_LOGICAL_PACKAGE = createManaged( + T_OBJ, IMG_OBJS_LOGICAL_PACKAGE); + + public static final ImageDescriptor DESC_OBJS_EMPTY_PACKAGE_RESOURCES = createManaged( + T_OBJ, IMG_OBJS_EMPTY_PACK_RESOURCE); + + public static final ImageDescriptor DESC_OBJS_EMPTY_PACKAGE = createManaged( + T_OBJ, IMG_OBJS_EMPTY_PACKAGE); + + public static final ImageDescriptor DESC_OBJS_PACKFRAG_ROOT = createManaged( + T_OBJ, IMG_OBJS_PACKFRAG_ROOT); + + public static final ImageDescriptor DESC_OBJS_MISSING_PACKFRAG_ROOT = createManaged( + T_OBJ, IMG_OBJS_MISSING_PACKFRAG_ROOT); + + public static final ImageDescriptor DESC_OBJS_JAVA_MODEL = createManaged( + T_OBJ, IMG_OBJS_JAVA_MODEL); + + public static final ImageDescriptor DESC_OBJS_CLASS = createManaged(T_OBJ, + IMG_OBJS_CLASS); + + public static final ImageDescriptor DESC_OBJS_CLASS_DEFAULT = createManaged( + T_OBJ, IMG_OBJS_CLASS_DEFAULT); + + public static final ImageDescriptor DESC_OBJS_INNER_CLASS_PUBLIC = create( + T_OBJ, "innerclass_public_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_INNER_CLASS_DEFAULT = create( + T_OBJ, "innerclass_default_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_INNER_CLASS_PROTECTED = create( + T_OBJ, "innerclass_protected_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_INNER_CLASS_PRIVATE = create( + T_OBJ, "innerclass_private_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_CLASSALT = createManaged( + T_OBJ, IMG_OBJS_CLASSALT); + + public static final ImageDescriptor DESC_OBJS_INTERFACE = createManaged( + T_OBJ, IMG_OBJS_INTERFACE); + + public static final ImageDescriptor DESC_OBJS_INTERFACE_DEFAULT = createManaged( + T_OBJ, IMG_OBJS_INTERFACE_DEFAULT); + + public static final ImageDescriptor DESC_OBJS_INNER_INTERFACE_PUBLIC = create( + T_OBJ, "innerinterface_public_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_INNER_INTERFACE_DEFAULT = create( + T_OBJ, "innerinterface_default_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_INNER_INTERFACE_PROTECTED = create( + T_OBJ, "innerinterface_protected_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_INNER_INTERFACE_PRIVATE = create( + T_OBJ, "innerinterface_private_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_INTERFACEALT = createManaged( + T_OBJ, IMG_OBJS_INTERFACEALT); + + public static final ImageDescriptor DESC_OBJS_JAR = createManaged(T_OBJ, + IMG_OBJS_JAR); + + public static final ImageDescriptor DESC_OBJS_MISSING_JAR = createManaged( + T_OBJ, IMG_OBJS_MISSING_JAR); + + public static final ImageDescriptor DESC_OBJS_EXTJAR = createManaged(T_OBJ, + IMG_OBJS_EXTJAR); + + public static final ImageDescriptor DESC_OBJS_JAR_WSRC = createManaged( + T_OBJ, IMG_OBJS_JAR_WSRC); + + public static final ImageDescriptor DESC_OBJS_EXTJAR_WSRC = createManaged( + T_OBJ, IMG_OBJS_EXTJAR_WSRC); + + public static final ImageDescriptor DESC_OBJS_ENV_VAR = createManaged( + T_OBJ, IMG_OBJS_ENV_VAR); + + public static final ImageDescriptor DESC_OBJS_MISSING_ENV_VAR = createManaged( + T_OBJ, IMG_OBJS_MISSING_ENV_VAR); + + public static final ImageDescriptor DESC_OBJS_LIBRARY = createManaged( + T_OBJ, IMG_OBJS_LIBRARY); + + public static final ImageDescriptor DESC_OBJS_JAVADOCTAG = createManaged( + T_OBJ, IMG_OBJS_JAVADOCTAG); + + public static final ImageDescriptor DESC_OBJS_HTMLTAG = createManaged( + T_OBJ, IMG_OBJS_HTMLTAG); + + public static final ImageDescriptor DESC_OBJS_TEMPLATE = createManaged( + T_OBJ, IMG_OBJS_TEMPLATE); + + public static final ImageDescriptor DESC_OBJS_EXCEPTION = createManaged( + T_OBJ, IMG_OBJS_EXCEPTION); + + public static final ImageDescriptor DESC_OBJS_BREAKPOINT_INSTALLED = createManaged( + T_OBJ, IMG_OBJS_BREAKPOINT_INSTALLED); + + public static final ImageDescriptor DESC_OBJS_ERROR = createManaged(T_OBJ, + IMG_OBJS_ERROR); + + public static final ImageDescriptor DESC_OBJS_FIXABLE_PROBLEM = createManaged( + T_OBJ, IMG_OBJS_FIXABLE_PROBLEM); + + public static final ImageDescriptor DESC_OBJS_FIXABLE_ERROR = createManaged( + T_OBJ, IMG_OBJS_FIXABLE_ERROR); + + public static final ImageDescriptor DESC_OBJS_SNIPPET_EVALUATING = createManaged( + T_OBJ, IMG_OBJS_SNIPPET_EVALUATING); + + public static final ImageDescriptor DESC_OBJS_DEFAULT_CHANGE = create( + T_OBJ, "change.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_COMPOSITE_CHANGE = create( + T_OBJ, "composite_change.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_CU_CHANGE = create(T_OBJ, + "cu_change.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_FILE_CHANGE = create(T_OBJ, + "file_change.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_TEXT_EDIT = create(T_OBJ, + "text_edit.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_EXCLUSION_FILTER_ATTRIB = create( + T_OBJ, "exclusion_filter_attrib.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_OUTPUT_FOLDER_ATTRIB = create( + T_OBJ, "output_folder_attrib.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_SOURCE_ATTACH_ATTRIB = create( + T_OBJ, "source_attach_attrib.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_JAVADOC_LOCATION_ATTRIB = create( + T_OBJ, "javadoc_location_attrib.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_REFACTORING_FATAL = createManaged( + T_OBJ, IMG_OBJS_REFACTORING_FATAL); + + public static final ImageDescriptor DESC_OBJS_REFACTORING_ERROR = createManaged( + T_OBJ, IMG_OBJS_REFACTORING_ERROR); + + public static final ImageDescriptor DESC_OBJS_REFACTORING_WARNING = createManaged( + T_OBJ, IMG_OBJS_REFACTORING_WARNING); + + public static final ImageDescriptor DESC_OBJS_REFACTORING_INFO = createManaged( + T_OBJ, IMG_OBJS_REFACTORING_INFO); + + public static final ImageDescriptor DESC_OBJS_NLS_TRANSLATE = createManaged( + T_OBJ, IMG_OBJS_NLS_TRANSLATE); + + public static final ImageDescriptor DESC_OBJS_NLS_NEVER_TRANSLATE = createManaged( + T_OBJ, IMG_OBJS_NLS_NEVER_TRANSLATE); + + public static final ImageDescriptor DESC_OBJS_NLS_SKIP = createManaged( + T_OBJ, IMG_OBJS_NLS_SKIP); + + public static final ImageDescriptor DESC_OBJS_UNKNOWN = createManaged( + T_OBJ, IMG_OBJS_UNKNOWN); + + public static final ImageDescriptor DESC_OBJS_SEARCH_READACCESS = createManaged( + T_OBJ, IMG_OBJS_SEARCH_READACCESS); + + public static final ImageDescriptor DESC_OBJS_SEARCH_WRITEACCESS = createManaged( + T_OBJ, IMG_OBJS_SEARCH_WRITEACCESS); + + public static final ImageDescriptor DESC_OBJS_SEARCH_OCCURRENCE = createManaged( + T_OBJ, IMG_OBJS_SEARCH_OCCURRENCE); + + public static final ImageDescriptor DESC_OBJS_LOCAL_VARIABLE = create( + T_OBJ, "localvariable_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OVR_STATIC = create(T_OVR, + "static_co.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OVR_FINAL = create(T_OVR, + "final_co.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OVR_ABSTRACT = create(T_OVR, + "abstract_co.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OVR_SYNCH = create(T_OVR, + "synch_co.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OVR_RUN = create(T_OVR, + "run_co.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OVR_WARNING = create(T_OVR, + "warning_co.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OVR_ERROR = create(T_OVR, + "error_co.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OVR_OVERRIDES = create(T_OVR, + "over_co.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OVR_IMPLEMENTS = create(T_OVR, + "implm_co.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OVR_CONSTRUCTOR = create(T_OVR, + "constr_ovr.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OVR_FOCUS = create(T_OVR, + "focus_ovr.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_NEWFIELD = create(T_WIZBAN, + "newfield_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_NEWINT = create(T_WIZBAN, + "newint_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_NEWJPRJ = create(T_WIZBAN, + "newjprj_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_NEWSRCFOLDR = create( + T_WIZBAN, "newsrcfldr_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_NEWMETH = create(T_WIZBAN, + "newmeth_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_NEWPACK = create(T_WIZBAN, + "newpack_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_NEWSCRAPPAGE = create( + T_WIZBAN, "newsbook_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_JAVA_LAUNCH = create( + T_WIZBAN, "java_app_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_JAVA_ATTACH = create( + T_WIZBAN, "java_attach_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_REFACTOR = create(T_WIZBAN, + "refactor_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_REFACTOR_FIELD = create( + T_WIZBAN, "fieldrefact_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_REFACTOR_METHOD = create( + T_WIZBAN, "methrefact_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_REFACTOR_TYPE = create( + T_WIZBAN, "typerefact_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_REFACTOR_PACKAGE = create( + T_WIZBAN, "packrefact_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_REFACTOR_CODE = create( + T_WIZBAN, "coderefact_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_REFACTOR_CU = create( + T_WIZBAN, "compunitrefact_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_REFACTOR_PULL_UP = create( + T_WIZBAN, "pullup_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_JAR_PACKAGER = create( + T_WIZBAN, "jar_pack_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_JAVA_WORKINGSET = create( + T_WIZBAN, "java_workingset_wiz.gif");//$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_EXPORT_JAVADOC = create( + T_WIZBAN, "export_javadoc_wiz.gif");//$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_EXTERNALIZE_STRINGS = create( + T_WIZBAN, "extstr_wiz.gif");//$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_ADD_LIBRARY = create( + T_WIZBAN, "addlibrary_wiz.gif");//$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_DISPLAYSNIPPET = create( + T_CTOOL, "disp_sbook.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_RUNSNIPPET = create(T_CTOOL, + "run_sbook.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_INSPSNIPPET = create(T_CTOOL, + "insp_sbook.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_PACKSNIPPET = create(T_CTOOL, + "pack_sbook.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_TERMSNIPPET = create(T_CTOOL, + "term_sbook.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_SHOW_EMPTY_PKG = create( + T_CTOOL, "show_empty_pkg.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_SHOW_SEGMENTS = create( + T_CTOOL, "segment_edit.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_GOTO_NEXT_ERROR = create( + T_CTOOL, "next_error_nav.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_GOTO_PREV_ERROR = create( + T_CTOOL, "prev_error_nav.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_OPENTYPE = create(T_CTOOL, + "opentype.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_NEWPROJECT = create(T_CTOOL, + "newjprj_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_NEWPACKAGE = create(T_CTOOL, + "newpack_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_NEWCLASS = create(T_CTOOL, + "newclass_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_NEWINTERFACE = create( + T_CTOOL, "newint_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_NEWSNIPPET = create(T_CTOOL, + "newsbook_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_NEWPACKROOT = create(T_CTOOL, + "newpackfolder_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_CLASSPATH_ORDER = create( + T_OBJ, "cp_order_obj.gif"); //$NON-NLS-1$ + + // Keys for correction proposal. We have to put the image into the registry + // since "code assist" doesn't // have a life cycle. So no change to dispose icons. - public static final String IMG_CORRECTION_CHANGE= NAME_PREFIX + "correction_change.gif"; //$NON-NLS-1$ - public static final String IMG_CORRECTION_MOVE= NAME_PREFIX + "correction_move.gif"; //$NON-NLS-1$ - public static final String IMG_CORRECTION_RENAME= NAME_PREFIX + "correction_rename.gif"; //$NON-NLS-1$ - public static final String IMG_CORRECTION_DELETE_IMPORT= NAME_PREFIX + "correction_delete_import.gif"; //$NON-NLS-1$ - public static final String IMG_CORRECTION_LOCAL= NAME_PREFIX + "localvariable_obj.gif"; //$NON-NLS-1$ - public static final String IMG_CORRECTION_REMOVE= NAME_PREFIX + "remove_correction.gif"; //$NON-NLS-1$ - public static final String IMG_CORRECTION_ADD= NAME_PREFIX + "add_correction.gif"; //$NON-NLS-1$ + public static final String IMG_CORRECTION_CHANGE = NAME_PREFIX + + "correction_change.gif"; //$NON-NLS-1$ + + public static final String IMG_CORRECTION_MOVE = NAME_PREFIX + + "correction_move.gif"; //$NON-NLS-1$ + + public static final String IMG_CORRECTION_RENAME = NAME_PREFIX + + "correction_rename.gif"; //$NON-NLS-1$ + + public static final String IMG_CORRECTION_DELETE_IMPORT = NAME_PREFIX + + "correction_delete_import.gif"; //$NON-NLS-1$ + + public static final String IMG_CORRECTION_LOCAL = NAME_PREFIX + + "localvariable_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_CORRECTION_REMOVE = NAME_PREFIX + + "remove_correction.gif"; //$NON-NLS-1$ + + public static final String IMG_CORRECTION_ADD = NAME_PREFIX + + "add_correction.gif"; //$NON-NLS-1$ static { createManaged(T_OBJ, IMG_CORRECTION_CHANGE); @@ -386,8 +781,9 @@ public class PHPUiImages { /** * Returns the image managed under the given key in this registry. - * - * @param key the image's key + * + * @param key + * the image's key * @return the image managed under the given key */ public static Image get(String key) { @@ -395,9 +791,11 @@ public class PHPUiImages { } /** - * Returns the image descriptor for the given key in this registry. Might be called in a non-UI thread. - * - * @param key the image's key + * Returns the image descriptor for the given key in this registry. Might be + * called in a non-UI thread. + * + * @param key + * the image's key * @return the image descriptor for the given key */ public static ImageDescriptor getDescriptor(String key) { @@ -408,60 +806,55 @@ public class PHPUiImages { } /** - * Sets the three image descriptors for enabled, disabled, and hovered to an action. The actions - * are retrieved from the *tool16 folders. + * Sets the three image descriptors for enabled, disabled, and hovered to an + * action. The actions are retrieved from the *tool16 folders. */ - public static void setToolImageDescriptors( - IAction action, - String iconName) { + public static void setToolImageDescriptors(IAction action, String iconName) { setImageDescriptors(action, "tool16", iconName); } /** - * Sets the three image descriptors for enabled, disabled, and hovered to an action. The actions - * are retrieved from the *lcl16 folders. + * Sets the three image descriptors for enabled, disabled, and hovered to an + * action. The actions are retrieved from the *lcl16 folders. */ - public static void setLocalImageDescriptors( - IAction action, - String iconName) { + public static void setLocalImageDescriptors(IAction action, String iconName) { setImageDescriptors(action, "lcl16", iconName); } /* * Helper method to access the image registry from the JavaPlugin class. */ - /* package */ static ImageRegistry getImageRegistry() { + /* package */static ImageRegistry getImageRegistry() { if (fgImageRegistry == null) { - fgImageRegistry= new ImageRegistry(); - for (Iterator iter= fgAvoidSWTErrorMap.keySet().iterator(); iter.hasNext();) { - String key= (String) iter.next(); - fgImageRegistry.put(key, (ImageDescriptor) fgAvoidSWTErrorMap.get(key)); + fgImageRegistry = new ImageRegistry(); + for (Iterator iter = fgAvoidSWTErrorMap.keySet().iterator(); iter + .hasNext();) { + String key = (String) iter.next(); + fgImageRegistry.put(key, (ImageDescriptor) fgAvoidSWTErrorMap + .get(key)); } - fgAvoidSWTErrorMap= null; + fgAvoidSWTErrorMap = null; } return fgImageRegistry; } - //---- Helper methods to access icons on the file system -------------------------------------- + // ---- Helper methods to access icons on the file system + // -------------------------------------- - protected static void setImageDescriptors( - IAction action, - String type, - String relPath) { + protected static void setImageDescriptors(IAction action, String type, + String relPath) { try { - ImageDescriptor id = - ImageDescriptor.createFromURL( - makeIconFileURL("d" + type, relPath)); + ImageDescriptor id = ImageDescriptor.createFromURL(makeIconFileURL( + "d" + type, relPath)); if (id != null) action.setDisabledImageDescriptor(id); } catch (MalformedURLException e) { } try { - ImageDescriptor id = - ImageDescriptor.createFromURL( - makeIconFileURL("c" + type, relPath)); + ImageDescriptor id = ImageDescriptor.createFromURL(makeIconFileURL( + "c" + type, relPath)); if (id != null) action.setHoverImageDescriptor(id); } catch (MalformedURLException e) { @@ -472,13 +865,16 @@ public class PHPUiImages { private static ImageDescriptor createManaged(String prefix, String name) { try { - ImageDescriptor result= ImageDescriptor.createFromURL(makeIconFileURL(prefix, name.substring(NAME_PREFIX_LENGTH))); + ImageDescriptor result = ImageDescriptor + .createFromURL(makeIconFileURL(prefix, name + .substring(NAME_PREFIX_LENGTH))); if (fgAvoidSWTErrorMap == null) { - fgAvoidSWTErrorMap= new HashMap(); + fgAvoidSWTErrorMap = new HashMap(); } fgAvoidSWTErrorMap.put(name, result); if (fgImageRegistry != null) { - PHPeclipsePlugin.logErrorMessage("Image registry already defined"); //$NON-NLS-1$ + PHPeclipsePlugin + .logErrorMessage("Image registry already defined"); //$NON-NLS-1$ } return result; } catch (MalformedURLException e) { @@ -486,15 +882,19 @@ public class PHPUiImages { } } - private static ImageDescriptor createManaged(String prefix, String name, String key) { + private static ImageDescriptor createManaged(String prefix, String name, + String key) { try { - ImageDescriptor result= ImageDescriptor.createFromURL(makeIconFileURL(prefix, name.substring(NAME_PREFIX_LENGTH))); + ImageDescriptor result = ImageDescriptor + .createFromURL(makeIconFileURL(prefix, name + .substring(NAME_PREFIX_LENGTH))); if (fgAvoidSWTErrorMap == null) { - fgAvoidSWTErrorMap= new HashMap(); + fgAvoidSWTErrorMap = new HashMap(); } fgAvoidSWTErrorMap.put(key, result); if (fgImageRegistry != null) { - PHPeclipsePlugin.logErrorMessage("Image registry already defined"); //$NON-NLS-1$ + PHPeclipsePlugin + .logErrorMessage("Image registry already defined"); //$NON-NLS-1$ } return result; } catch (MalformedURLException e) { @@ -511,7 +911,7 @@ public class PHPUiImages { } protected static URL makeIconFileURL(String prefix, String name) - throws MalformedURLException { + throws MalformedURLException { if (fgIconBaseURL == null) throw new MalformedURLException(); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/ResourceAdapterFactory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/ResourceAdapterFactory.java index 661aea3..4e07b27 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/ResourceAdapterFactory.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/ResourceAdapterFactory.java @@ -10,7 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.ui; - import net.sourceforge.phpdt.core.IJavaElement; import net.sourceforge.phpdt.core.JavaCore; @@ -19,18 +18,16 @@ import org.eclipse.core.runtime.IAdapterFactory; public class ResourceAdapterFactory implements IAdapterFactory { - private static Class[] PROPERTIES= new Class[] { - IJavaElement.class - }; - + private static Class[] PROPERTIES = new Class[] { IJavaElement.class }; + public Class[] getAdapterList() { return PROPERTIES; } - + public Object getAdapter(Object element, Class key) { if (IJavaElement.class.equals(key)) { - return JavaCore.create((IResource)element); + return JavaCore.create((IResource) element); } return null; - } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/AbstractToggleLinkingAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/AbstractToggleLinkingAction.java index faf7d0d..db98033 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/AbstractToggleLinkingAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/AbstractToggleLinkingAction.java @@ -16,11 +16,10 @@ import net.sourceforge.phpdt.internal.ui.PHPUiImages; import org.eclipse.jface.action.Action; import org.eclipse.ui.PlatformUI; - /** - * This is an action template for actions that toggle whether - * it links its selection to the active editor. - * + * This is an action template for actions that toggle whether it links its + * selection to the active editor. + * * @since 3.0 */ public abstract class AbstractToggleLinkingAction extends Action { @@ -30,10 +29,12 @@ public abstract class AbstractToggleLinkingAction extends Action { */ public AbstractToggleLinkingAction() { super(ActionMessages.getString("ToggleLinkingAction.label")); //$NON-NLS-1$ - setDescription(ActionMessages.getString("ToggleLinkingAction.description")); //$NON-NLS-1$ + setDescription(ActionMessages + .getString("ToggleLinkingAction.description")); //$NON-NLS-1$ setToolTipText(ActionMessages.getString("ToggleLinkingAction.tooltip")); //$NON-NLS-1$ PHPUiImages.setLocalImageDescriptors(this, "synced.gif"); //$NON-NLS-1$ - PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.LINK_EDITOR_ACTION); + PlatformUI.getWorkbench().getHelpSystem().setHelp(this, + IJavaHelpContextIds.LINK_EDITOR_ACTION); } /** diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/ActionMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/ActionMessages.java index 3a0465f..91d8132 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/ActionMessages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/ActionMessages.java @@ -19,21 +19,24 @@ import java.util.ResourceBundle; */ public class ActionMessages { - private static final String BUNDLE_NAME= "net.sourceforge.phpdt.internal.ui.actions.ActionMessages"; //$NON-NLS-1$ + private static final String BUNDLE_NAME = "net.sourceforge.phpdt.internal.ui.actions.ActionMessages"; //$NON-NLS-1$ - private static final ResourceBundle RESOURCE_BUNDLE= ResourceBundle.getBundle(BUNDLE_NAME); + private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle + .getBundle(BUNDLE_NAME); private ActionMessages() { // no instance } /** - * Returns the resource string associated with the given key in the resource bundle. If there isn't - * any value under the given key, the key is returned. - * - * @param key the resource key + * Returns the resource string associated with the given key in the resource + * bundle. If there isn't any value under the given key, the key is + * returned. + * + * @param key + * the resource key * @return the string - */ + */ public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); @@ -41,6 +44,7 @@ public class ActionMessages { return '!' + key + '!'; } } + /** * Returns the resource bundle managed by the receiver. * @@ -50,29 +54,36 @@ public class ActionMessages { public static ResourceBundle getResourceBundle() { return RESOURCE_BUNDLE; } + /** - * Returns the formatted resource string associated with the given key in the resource bundle. - * MessageFormat is used to format the message. If there isn't any value - * under the given key, the key is returned. - * - * @param key the resource key - * @param arg the message argument + * Returns the formatted resource string associated with the given key in + * the resource bundle. MessageFormat is used to format the + * message. If there isn't any value under the given key, the key is + * returned. + * + * @param key + * the resource key + * @param arg + * the message argument * @return the string - */ + */ public static String getFormattedString(String key, Object arg) { return getFormattedString(key, new Object[] { arg }); } - + /** - * Returns the formatted resource string associated with the given key in the resource bundle. - * MessageFormat is used to format the message. If there isn't any value - * under the given key, the key is returned. - * - * @param key the resource key - * @param args the message arguments + * Returns the formatted resource string associated with the given key in + * the resource bundle. MessageFormat is used to format the + * message. If there isn't any value under the given key, the key is + * returned. + * + * @param key + * the resource key + * @param args + * the message arguments * @return the string - */ + */ public static String getFormattedString(String key, Object[] args) { - return MessageFormat.format(getString(key), args); - } + return MessageFormat.format(getString(key), args); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/ActionUtil.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/ActionUtil.java index d526b77..67e4919 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/ActionUtil.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/ActionUtil.java @@ -30,62 +30,69 @@ import org.eclipse.swt.widgets.Shell; * http://dev.eclipse.org/bugs/show_bug.cgi?id=19104 */ public class ActionUtil { - - private ActionUtil(){ + + private ActionUtil() { } - //bug 31998 we will have to disable renaming of linked packages (and cus) + // bug 31998 we will have to disable renaming of linked packages (and cus) public static boolean mustDisableJavaModelAction(Shell shell, Object element) { - if (!(element instanceof IPackageFragment) && !(element instanceof IPackageFragmentRoot)) + if (!(element instanceof IPackageFragment) + && !(element instanceof IPackageFragmentRoot)) return false; - - IResource resource= ResourceUtil.getResource(element); - if ((resource == null) || (! (resource instanceof IFolder)) || (! resource.isLinked())) + + IResource resource = ResourceUtil.getResource(element); + if ((resource == null) || (!(resource instanceof IFolder)) + || (!resource.isLinked())) return false; - - MessageDialog.openInformation(shell, ActionMessages.getString("ActionUtil.not_possible"), ActionMessages.getString("ActionUtil.no_linked")); //$NON-NLS-1$ //$NON-NLS-2$ + + MessageDialog + .openInformation( + shell, + ActionMessages.getString("ActionUtil.not_possible"), ActionMessages.getString("ActionUtil.no_linked")); //$NON-NLS-1$ //$NON-NLS-2$ return true; } - + public static boolean isProcessable(Shell shell, PHPEditor editor) { if (editor == null) return true; - IJavaElement input= SelectionConverter.getInput(editor); + IJavaElement input = SelectionConverter.getInput(editor); // if a Java editor doesn't have an input of type Java element // then it is for sure not on the build path if (input == null) { - MessageDialog.openInformation(shell, - ActionMessages.getString("ActionUtil.notOnBuildPath.title"), //$NON-NLS-1$ - ActionMessages.getString("ActionUtil.notOnBuildPath.message")); //$NON-NLS-1$ + MessageDialog.openInformation(shell, ActionMessages + .getString("ActionUtil.notOnBuildPath.title"), //$NON-NLS-1$ + ActionMessages + .getString("ActionUtil.notOnBuildPath.message")); //$NON-NLS-1$ return false; } return isProcessable(shell, input); } - + public static boolean isProcessable(Shell shell, Object element) { if (!(element instanceof IJavaElement)) return true; - - if (isOnBuildPath((IJavaElement)element)) + + if (isOnBuildPath((IJavaElement) element)) return true; - MessageDialog.openInformation(shell, - ActionMessages.getString("ActionUtil.notOnBuildPath.title"), //$NON-NLS-1$ - ActionMessages.getString("ActionUtil.notOnBuildPath.message")); //$NON-NLS-1$ + MessageDialog.openInformation(shell, ActionMessages + .getString("ActionUtil.notOnBuildPath.title"), //$NON-NLS-1$ + ActionMessages.getString("ActionUtil.notOnBuildPath.message")); //$NON-NLS-1$ return false; } - public static boolean isOnBuildPath(IJavaElement element) { - //fix for bug http://dev.eclipse.org/bugs/show_bug.cgi?id=20051 - if (element.getElementType() == IJavaElement.JAVA_PROJECT) - return true; - IJavaProject project= element.getJavaProject(); + public static boolean isOnBuildPath(IJavaElement element) { + // fix for bug http://dev.eclipse.org/bugs/show_bug.cgi?id=20051 + if (element.getElementType() == IJavaElement.JAVA_PROJECT) + return true; + IJavaProject project = element.getJavaProject(); try { -// if (!project.isOnClasspath(element)) -// return false; - IProject resourceProject= project.getProject(); + // if (!project.isOnClasspath(element)) + // return false; + IProject resourceProject = project.getProject(); if (resourceProject == null) return false; - IProjectNature nature= resourceProject.getNature(PHPeclipsePlugin.PHP_NATURE_ID); + IProjectNature nature = resourceProject + .getNature(PHPeclipsePlugin.PHP_NATURE_ID); // We have a Java project if (nature != null) return true; @@ -94,4 +101,3 @@ public class ActionUtil { return false; } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/AddBlockCommentAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/AddBlockCommentAction.java index 9977be9..1d2f1c7 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/AddBlockCommentAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/AddBlockCommentAction.java @@ -27,181 +27,203 @@ import org.eclipse.jface.text.ITypedRegion; import org.eclipse.ui.texteditor.ITextEditor; /** - * Action that encloses the editor's current selection with Java block comment terminators (/* and - * */). - * + * Action that encloses the editor's current selection with Java block comment + * terminators (/* and */). + * * @since 3.0 */ public class AddBlockCommentAction extends BlockCommentAction { - /** - * Creates a new instance. - * - * @param bundle - * the resource bundle - * @param prefix - * a prefix to be prepended to the various resource keys (described in ResourceAction constructor), or - * null if none - * @param editor - * the text editor - */ - public AddBlockCommentAction(ResourceBundle bundle, String prefix, ITextEditor editor) { - super(bundle, prefix, editor); - } - - /* - * @see net.sourceforge.phpdt.internal.ui.actions.BlockCommentAction#runInternal(org.eclipse.jface.text.ITextSelection, - * org.eclipse.jface.text.IDocumentExtension3, net.sourceforge.phpdt.internal.ui.actions.BlockCommentAction.Edit.EditFactory) - */ - protected void runInternal(ITextSelection selection, IDocumentExtension3 docExtension, Edit.EditFactory factory) - throws BadLocationException, BadPartitioningException { - int selectionOffset = selection.getOffset(); - int selectionEndOffset = selectionOffset + selection.getLength(); - List edits = new LinkedList(); - ITypedRegion partition = docExtension.getPartition(IPHPPartitions.PHP_PARTITIONING, selectionOffset, false); - - handleFirstPartition(partition, edits, factory, selectionOffset); - - while (partition.getOffset() + partition.getLength() < selectionEndOffset) { - partition = handleInteriorPartition(partition, edits, factory, docExtension); - } - - handleLastPartition(partition, edits, factory, selectionEndOffset); - - executeEdits(edits); - } - - /** - * Handle the first partition of the selected text. - * - * @param partition - * @param edits - * @param factory - * @param offset - */ - private void handleFirstPartition(ITypedRegion partition, List edits, Edit.EditFactory factory, int offset) - throws BadLocationException { - - int partOffset = partition.getOffset(); - String partType = partition.getType(); - - Assert.isTrue(partOffset <= offset, "illegal partition"); //$NON-NLS-1$ - - // first partition: mark start of comment - if (partType == IDocument.DEFAULT_CONTENT_TYPE || - partType == PHPDocumentPartitioner.PHP_SCRIPT_CODE) { - // Java code: right where selection starts - edits.add(factory.createEdit(offset, 0, getCommentStart())); - } else if (isSpecialPartition(partType)) { - // special types: include the entire partition - edits.add(factory.createEdit(partOffset, 0, getCommentStart())); - } // javadoc: no mark, will only start after comment - - } - - /** - * Handles the end of the given partition and the start of the next partition, which is returned. - * - * @param partition - * @param edits - * @param factory - * @param docExtension - * @return - * @throws BadLocationException - * @throws BadPartitioningException - */ - private ITypedRegion handleInteriorPartition(ITypedRegion partition, List edits, Edit.EditFactory factory, - IDocumentExtension3 docExtension) throws BadPartitioningException, BadLocationException { - - // end of previous partition - String partType = partition.getType(); - int partEndOffset = partition.getOffset() + partition.getLength(); - int tokenLength = getCommentStart().length(); - - boolean wasJavadoc = false; // true if the previous partition is javadoc - - if (partType == IPHPPartitions.PHP_PHPDOC_COMMENT) { - - wasJavadoc = true; - - } else if (partType == IPHPPartitions.PHP_MULTILINE_COMMENT) { - - // already in a comment - remove ending mark - edits.add(factory.createEdit(partEndOffset - tokenLength, tokenLength, "")); //$NON-NLS-1$ - - } - - // advance to next partition - partition = docExtension.getPartition(IPHPPartitions.PHP_PARTITIONING, partEndOffset, false); - partType = partition.getType(); - - // start of next partition - if (wasJavadoc) { - - // if previous was javadoc, and the current one is not, then add block comment start - if (partType == IDocument.DEFAULT_CONTENT_TYPE || - partType == PHPDocumentPartitioner.PHP_SCRIPT_CODE || - isSpecialPartition(partType)) { - edits.add(factory.createEdit(partition.getOffset(), 0, getCommentStart())); - } - - } else { // !wasJavadoc - - if (partType == IPHPPartitions.PHP_PHPDOC_COMMENT) { - // if next is javadoc, end block comment before - edits.add(factory.createEdit(partition.getOffset(), 0, getCommentEnd())); - } else if (partType == IPHPPartitions.PHP_MULTILINE_COMMENT) { - // already in a comment - remove startToken - edits.add(factory.createEdit(partition.getOffset(), getCommentStart().length(), "")); //$NON-NLS-1$ - } - } - - return partition; - } - - /** - * Handles the end of the last partition. - * - * @param partition - * @param edits - * @param factory - * @param endOffset - */ - private void handleLastPartition(ITypedRegion partition, List edits, Edit.EditFactory factory, int endOffset) - throws BadLocationException { - - String partType = partition.getType(); - - if (partType == IDocument.DEFAULT_CONTENT_TYPE || - partType == PHPDocumentPartitioner.PHP_SCRIPT_CODE) { - // normal java: end comment where selection ends - edits.add(factory.createEdit(endOffset, 0, getCommentEnd())); - } else if (isSpecialPartition(partType)) { - // special types: consume entire partition - edits.add(factory.createEdit(partition.getOffset() + partition.getLength(), 0, getCommentEnd())); - } - - } - - /** - * Returns whether partType is special, i.e. a Java String,Character, or - * Line End Comment partition. - * - * @param partType - * the partition type to check - * @return true if partType is special, false otherwise - */ - private boolean isSpecialPartition(String partType) { - // return partType == IJavaPartitions.JAVA_CHARACTER - return partType == IPHPPartitions.PHP_STRING_DQ || partType == IPHPPartitions.PHP_STRING_SQ || partType == IPHPPartitions.PHP_STRING_HEREDOC - || partType == IPHPPartitions.PHP_SINGLELINE_COMMENT; - } - - /* - * @see net.sourceforge.phpdt.internal.ui.actions.BlockCommentAction#validSelection(org.eclipse.jface.text.ITextSelection) - */ - protected boolean isValidSelection(ITextSelection selection) { - return selection != null && !selection.isEmpty() && selection.getLength() > 0; - } + /** + * Creates a new instance. + * + * @param bundle + * the resource bundle + * @param prefix + * a prefix to be prepended to the various resource keys + * (described in ResourceAction constructor), or + * null if none + * @param editor + * the text editor + */ + public AddBlockCommentAction(ResourceBundle bundle, String prefix, + ITextEditor editor) { + super(bundle, prefix, editor); + } + + /* + * @see net.sourceforge.phpdt.internal.ui.actions.BlockCommentAction#runInternal(org.eclipse.jface.text.ITextSelection, + * org.eclipse.jface.text.IDocumentExtension3, + * net.sourceforge.phpdt.internal.ui.actions.BlockCommentAction.Edit.EditFactory) + */ + protected void runInternal(ITextSelection selection, + IDocumentExtension3 docExtension, Edit.EditFactory factory) + throws BadLocationException, BadPartitioningException { + int selectionOffset = selection.getOffset(); + int selectionEndOffset = selectionOffset + selection.getLength(); + List edits = new LinkedList(); + ITypedRegion partition = docExtension.getPartition( + IPHPPartitions.PHP_PARTITIONING, selectionOffset, false); + + handleFirstPartition(partition, edits, factory, selectionOffset); + + while (partition.getOffset() + partition.getLength() < selectionEndOffset) { + partition = handleInteriorPartition(partition, edits, factory, + docExtension); + } + + handleLastPartition(partition, edits, factory, selectionEndOffset); + + executeEdits(edits); + } + + /** + * Handle the first partition of the selected text. + * + * @param partition + * @param edits + * @param factory + * @param offset + */ + private void handleFirstPartition(ITypedRegion partition, List edits, + Edit.EditFactory factory, int offset) throws BadLocationException { + + int partOffset = partition.getOffset(); + String partType = partition.getType(); + + Assert.isTrue(partOffset <= offset, "illegal partition"); //$NON-NLS-1$ + + // first partition: mark start of comment + if (partType == IDocument.DEFAULT_CONTENT_TYPE + || partType == PHPDocumentPartitioner.PHP_SCRIPT_CODE) { + // Java code: right where selection starts + edits.add(factory.createEdit(offset, 0, getCommentStart())); + } else if (isSpecialPartition(partType)) { + // special types: include the entire partition + edits.add(factory.createEdit(partOffset, 0, getCommentStart())); + } // javadoc: no mark, will only start after comment + + } + + /** + * Handles the end of the given partition and the start of the next + * partition, which is returned. + * + * @param partition + * @param edits + * @param factory + * @param docExtension + * @return + * @throws BadLocationException + * @throws BadPartitioningException + */ + private ITypedRegion handleInteriorPartition(ITypedRegion partition, + List edits, Edit.EditFactory factory, + IDocumentExtension3 docExtension) throws BadPartitioningException, + BadLocationException { + + // end of previous partition + String partType = partition.getType(); + int partEndOffset = partition.getOffset() + partition.getLength(); + int tokenLength = getCommentStart().length(); + + boolean wasJavadoc = false; // true if the previous partition is javadoc + + if (partType == IPHPPartitions.PHP_PHPDOC_COMMENT) { + + wasJavadoc = true; + + } else if (partType == IPHPPartitions.PHP_MULTILINE_COMMENT) { + + // already in a comment - remove ending mark + edits.add(factory.createEdit(partEndOffset - tokenLength, + tokenLength, "")); //$NON-NLS-1$ + + } + + // advance to next partition + partition = docExtension.getPartition(IPHPPartitions.PHP_PARTITIONING, + partEndOffset, false); + partType = partition.getType(); + + // start of next partition + if (wasJavadoc) { + + // if previous was javadoc, and the current one is not, then add + // block comment start + if (partType == IDocument.DEFAULT_CONTENT_TYPE + || partType == PHPDocumentPartitioner.PHP_SCRIPT_CODE + || isSpecialPartition(partType)) { + edits.add(factory.createEdit(partition.getOffset(), 0, + getCommentStart())); + } + + } else { // !wasJavadoc + + if (partType == IPHPPartitions.PHP_PHPDOC_COMMENT) { + // if next is javadoc, end block comment before + edits.add(factory.createEdit(partition.getOffset(), 0, + getCommentEnd())); + } else if (partType == IPHPPartitions.PHP_MULTILINE_COMMENT) { + // already in a comment - remove startToken + edits.add(factory.createEdit(partition.getOffset(), + getCommentStart().length(), "")); //$NON-NLS-1$ + } + } + + return partition; + } + + /** + * Handles the end of the last partition. + * + * @param partition + * @param edits + * @param factory + * @param endOffset + */ + private void handleLastPartition(ITypedRegion partition, List edits, + Edit.EditFactory factory, int endOffset) + throws BadLocationException { + + String partType = partition.getType(); + + if (partType == IDocument.DEFAULT_CONTENT_TYPE + || partType == PHPDocumentPartitioner.PHP_SCRIPT_CODE) { + // normal java: end comment where selection ends + edits.add(factory.createEdit(endOffset, 0, getCommentEnd())); + } else if (isSpecialPartition(partType)) { + // special types: consume entire partition + edits.add(factory.createEdit(partition.getOffset() + + partition.getLength(), 0, getCommentEnd())); + } + + } + + /** + * Returns whether partType is special, i.e. a Java + * String,Character, or + * Line End Comment partition. + * + * @param partType + * the partition type to check + * @return true if partType is special, + * false otherwise + */ + private boolean isSpecialPartition(String partType) { + // return partType == IJavaPartitions.JAVA_CHARACTER + return partType == IPHPPartitions.PHP_STRING_DQ + || partType == IPHPPartitions.PHP_STRING_SQ + || partType == IPHPPartitions.PHP_STRING_HEREDOC + || partType == IPHPPartitions.PHP_SINGLELINE_COMMENT; + } + + /* + * @see net.sourceforge.phpdt.internal.ui.actions.BlockCommentAction#validSelection(org.eclipse.jface.text.ITextSelection) + */ + protected boolean isValidSelection(ITextSelection selection) { + return selection != null && !selection.isEmpty() + && selection.getLength() > 0; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/AddTaskAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/AddTaskAction.java index 245e581..b885182 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/AddTaskAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/AddTaskAction.java @@ -23,7 +23,7 @@ public class AddTaskAction extends SelectionDispatchAction { public AddTaskAction(IWorkbenchSite site) { super(site); setEnabled(false); - // WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ADD_TASK_ACTION); + // WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ADD_TASK_ACTION); } protected void selectionChanged(IStructuredSelection selection) { @@ -31,22 +31,22 @@ public class AddTaskAction extends SelectionDispatchAction { } protected void run(IStructuredSelection selection) { - IResource resource= getElement(selection); + IResource resource = getElement(selection); if (resource == null) return; - TaskPropertiesDialog dialog= new TaskPropertiesDialog(getShell()); + TaskPropertiesDialog dialog = new TaskPropertiesDialog(getShell()); dialog.setResource(resource); dialog.open(); } - + private IResource getElement(IStructuredSelection selection) { if (selection.size() != 1) return null; - Object element= selection.getFirstElement(); + Object element = selection.getFirstElement(); if (!(element instanceof IAdaptable)) return null; - return (IResource)((IAdaptable)element).getAdapter(IResource.class); - } + return (IResource) ((IAdaptable) element).getAdapter(IResource.class); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/BlockCommentAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/BlockCommentAction.java index c3e6bde..1f037a8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/BlockCommentAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/BlockCommentAction.java @@ -34,7 +34,6 @@ import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.ITextEditorExtension2; import org.eclipse.ui.texteditor.TextEditorAction; - /** * Common block comment code. * @@ -44,69 +43,88 @@ public abstract class BlockCommentAction extends TextEditorAction { /** * Creates a new instance. + * * @param bundle * @param prefix * @param editor */ - public BlockCommentAction(ResourceBundle bundle, String prefix, ITextEditor editor) { + public BlockCommentAction(ResourceBundle bundle, String prefix, + ITextEditor editor) { super(bundle, prefix, editor); } /** - * An edit is a kind of DocumentEvent, in this case an edit instruction, that is - * affilitated with a Position on a document. The offset of the document event is - * not stored statically, but taken from the affiliated Position, which gets - * updated when other edits occurr. + * An edit is a kind of DocumentEvent, in this case an edit + * instruction, that is affilitated with a Position on a + * document. The offset of the document event is not stored statically, but + * taken from the affiliated Position, which gets updated + * when other edits occurr. */ static class Edit extends DocumentEvent { - + /** - * Factory for edits which manages the creation, installation and destruction of - * position categories, position updaters etc. on a certain document. Once a factory has - * been obtained, Edit objects can be obtained from it which will be linked to - * the document by positions of one position category. - *

                                                      Clients are required to call release once the Edits are not - * used any more, so the positions can be discarded.

                                                      + * Factory for edits which manages the creation, installation and + * destruction of position categories, position updaters etc. on a + * certain document. Once a factory has been obtained, Edit + * objects can be obtained from it which will be linked to the document + * by positions of one position category. + *

                                                      + * Clients are required to call release once the + * Edits are not used any more, so the positions can be + * discarded. + *

                                                      */ public static class EditFactory { - + /** The position category basename for this edits. */ - private static final String CATEGORY= "__positionalEditPositionCategory"; //$NON-NLS-1$ - + private static final String CATEGORY = "__positionalEditPositionCategory"; //$NON-NLS-1$ + /** The count of factories. */ - private static int fgCount= 0; - + private static int fgCount = 0; + /** This factory's category. */ private final String fCategory; + private IDocument fDocument; + private IPositionUpdater fUpdater; - + /** - * Creates a new EditFactory with an unambiguous position category name. - * @param document the document that is being edited. + * Creates a new EditFactory with an unambiguous + * position category name. + * + * @param document + * the document that is being edited. */ public EditFactory(IDocument document) { - fCategory= CATEGORY + fgCount++; - fDocument= document; + fCategory = CATEGORY + fgCount++; + fDocument = document; } - + /** * Creates a new edition on the document of this factory. * - * @param offset the offset of the edition at the point when is created. - * @param length the length of the edition (not updated via the position update mechanism) - * @param text the text to be replaced on the document - * @return an Edit reflecting the edition on the document + * @param offset + * the offset of the edition at the point when is + * created. + * @param length + * the length of the edition (not updated via the + * position update mechanism) + * @param text + * the text to be replaced on the document + * @return an Edit reflecting the edition on the + * document */ - public Edit createEdit(int offset, int length, String text) throws BadLocationException { - + public Edit createEdit(int offset, int length, String text) + throws BadLocationException { + if (!fDocument.containsPositionCategory(fCategory)) { fDocument.addPositionCategory(fCategory); - fUpdater= new DefaultPositionUpdater(fCategory); + fUpdater = new DefaultPositionUpdater(fCategory); fDocument.addPositionUpdater(fUpdater); } - - Position position= new Position(offset); + + Position position = new Position(offset); try { fDocument.addPosition(fCategory, position); } catch (BadPositionCategoryException e) { @@ -114,108 +132,120 @@ public abstract class BlockCommentAction extends TextEditorAction { } return new Edit(fDocument, length, text, position); } - + /** - * Releases the position category on the document and uninstalls the position updater. - * Edits managed by this factory are not updated after this call. + * Releases the position category on the document and uninstalls the + * position updater. Edits managed by this factory + * are not updated after this call. */ public void release() { - if (fDocument != null && fDocument.containsPositionCategory(fCategory)) { + if (fDocument != null + && fDocument.containsPositionCategory(fCategory)) { fDocument.removePositionUpdater(fUpdater); try { fDocument.removePositionCategory(fCategory); } catch (BadPositionCategoryException e) { Assert.isTrue(false); } - fDocument= null; - fUpdater= null; + fDocument = null; + fUpdater = null; } } } - + /** The position in the document where this edit be executed. */ private Position fPosition; - + /** - * Creates a new edition on document, taking its offset from position. + * Creates a new edition on document, taking its offset + * from position. * - * @param document the document being edited - * @param length the length of the edition - * @param text the replacement text of the edition - * @param position the position keeping the edition's offset + * @param document + * the document being edited + * @param length + * the length of the edition + * @param text + * the replacement text of the edition + * @param position + * the position keeping the edition's offset */ - protected Edit(IDocument document, int length, String text, Position position) { + protected Edit(IDocument document, int length, String text, + Position position) { super(document, 0, length, text); - fPosition= position; + fPosition = position; } - + /* * @see org.eclipse.jface.text.DocumentEvent#getOffset() */ public int getOffset() { return fPosition.getOffset(); } - + /** - * Executes the edition on document. The offset is taken from the position. + * Executes the edition on document. The offset is taken from the + * position. * - * @throws BadLocationException if the execution of the document fails. + * @throws BadLocationException + * if the execution of the document fails. */ public void perform() throws BadLocationException { getDocument().replace(getOffset(), getLength(), getText()); } - + } public void run() { if (!isEnabled()) return; - - ITextEditor editor= getTextEditor(); + + ITextEditor editor = getTextEditor(); if (editor == null || !ensureEditable(editor)) return; - - ITextSelection selection= getCurrentSelection(); + + ITextSelection selection = getCurrentSelection(); if (!isValidSelection(selection)) return; - + if (!validateEditorInputState()) return; - - IDocumentProvider docProvider= editor.getDocumentProvider(); - IEditorInput input= editor.getEditorInput(); + + IDocumentProvider docProvider = editor.getDocumentProvider(); + IEditorInput input = editor.getEditorInput(); if (docProvider == null || input == null) return; - - IDocument document= docProvider.getDocument(input); + + IDocument document = docProvider.getDocument(input); if (document == null) return; - + IDocumentExtension3 docExtension; if (document instanceof IDocumentExtension3) - docExtension= (IDocumentExtension3) document; + docExtension = (IDocumentExtension3) document; else return; - - IRewriteTarget target= (IRewriteTarget)editor.getAdapter(IRewriteTarget.class); + + IRewriteTarget target = (IRewriteTarget) editor + .getAdapter(IRewriteTarget.class); if (target != null) { target.beginCompoundChange(); } - - Edit.EditFactory factory= new Edit.EditFactory(document); - + + Edit.EditFactory factory = new Edit.EditFactory(document); + try { runInternal(selection, docExtension, factory); - + } catch (BadLocationException e) { - // can happen on concurrent modification, deletion etc. of the document + // can happen on concurrent modification, deletion etc. of the + // document // -> don't complain, just bail out } catch (BadPartitioningException e) { // should not happen - Assert.isTrue(false, "bad partitioning"); //$NON-NLS-1$ + Assert.isTrue(false, "bad partitioning"); //$NON-NLS-1$ } finally { factory.release(); - + if (target != null) { target.endCompoundChange(); } @@ -223,34 +253,40 @@ public abstract class BlockCommentAction extends TextEditorAction { } /** - * Calls perform on all Edits in edits. + * Calls perform on all Edits in + * edits. * - * @param edits a list of Edits - * @throws BadLocationException if an Edit threw such an exception. + * @param edits + * a list of Edits + * @throws BadLocationException + * if an Edit threw such an exception. */ protected void executeEdits(List edits) throws BadLocationException { - for (Iterator it= edits.iterator(); it.hasNext();) { - Edit edit= (Edit) it.next(); + for (Iterator it = edits.iterator(); it.hasNext();) { + Edit edit = (Edit) it.next(); edit.perform(); } } /** * Ensures that the editor is modifyable. If the editor is an instance of - * ITextEditorExtension2, its validateEditorInputState method - * is called, otherwise, the result of isEditable is returned. + * ITextEditorExtension2, its + * validateEditorInputState method is called, otherwise, the + * result of isEditable is returned. * - * @param editor the editor to be checked - * @return true if the editor is editable, false otherwise + * @param editor + * the editor to be checked + * @return true if the editor is editable, false + * otherwise */ protected boolean ensureEditable(ITextEditor editor) { Assert.isNotNull(editor); - + if (editor instanceof ITextEditorExtension2) { - ITextEditorExtension2 ext= (ITextEditorExtension2) editor; + ITextEditorExtension2 ext = (ITextEditorExtension2) editor; return ext.validateEditorInputState(); } - + return editor.isEditable(); } @@ -259,7 +295,7 @@ public abstract class BlockCommentAction extends TextEditorAction { */ public void update() { super.update(); - + if (isEnabled()) { if (!canModifyEditor() || !isValidSelection(getCurrentSelection())) setEnabled(false); @@ -267,18 +303,18 @@ public abstract class BlockCommentAction extends TextEditorAction { } /** - * Returns the editor's selection, or null if no selection can be obtained or the - * editor is null. + * Returns the editor's selection, or null if no selection + * can be obtained or the editor is null. * * @return the selection of the action's editor, or null */ protected ITextSelection getCurrentSelection() { - ITextEditor editor= getTextEditor(); + ITextEditor editor = getTextEditor(); if (editor != null) { - ISelectionProvider provider= editor.getSelectionProvider(); + ISelectionProvider provider = editor.getSelectionProvider(); if (provider != null) { - ISelection selection= provider.getSelection(); - if (selection instanceof ITextSelection) + ISelection selection = provider.getSelection(); + if (selection instanceof ITextSelection) return (ITextSelection) selection; } } @@ -286,21 +322,31 @@ public abstract class BlockCommentAction extends TextEditorAction { } /** - * Runs the real command once all the editor, document, and selection checks have succeeded. + * Runs the real command once all the editor, document, and selection checks + * have succeeded. * - * @param selection the current selection we are being called for - * @param docExtension the document extension where we get the partitioning from - * @param factory the edit factory we can use to create Edits - * @throws BadLocationException if an edition fails - * @throws BadPartitioningException if a partitioning call fails + * @param selection + * the current selection we are being called for + * @param docExtension + * the document extension where we get the partitioning from + * @param factory + * the edit factory we can use to create Edits + * @throws BadLocationException + * if an edition fails + * @throws BadPartitioningException + * if a partitioning call fails */ - protected abstract void runInternal(ITextSelection selection, IDocumentExtension3 docExtension, Edit.EditFactory factory) throws BadLocationException, BadPartitioningException; + protected abstract void runInternal(ITextSelection selection, + IDocumentExtension3 docExtension, Edit.EditFactory factory) + throws BadLocationException, BadPartitioningException; /** * Checks whether selection is valid. * - * @param selection the selection to check - * @return true if the selection is valid, false otherwise + * @param selection + * the selection to check + * @return true if the selection is valid, false + * otherwise */ protected abstract boolean isValidSelection(ITextSelection selection); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/CompositeActionGroup.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/CompositeActionGroup.java index baacca8..ab643ef 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/CompositeActionGroup.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/CompositeActionGroup.java @@ -19,10 +19,10 @@ import org.eclipse.ui.actions.ActionGroup; public class CompositeActionGroup extends ActionGroup { private ActionGroup[] fGroups; - + public CompositeActionGroup() { } - + public CompositeActionGroup(ActionGroup[] groups) { setGroups(groups); } @@ -30,31 +30,31 @@ public class CompositeActionGroup extends ActionGroup { protected void setGroups(ActionGroup[] groups) { Assert.isTrue(fGroups == null); Assert.isNotNull(groups); - fGroups= groups; + fGroups = groups; } - + public ActionGroup get(int index) { if (fGroups == null) return null; return fGroups[index]; } - + public void addGroup(ActionGroup group) { if (fGroups == null) { - fGroups= new ActionGroup[] { group }; + fGroups = new ActionGroup[] { group }; } else { - ActionGroup[] newGroups= new ActionGroup[fGroups.length + 1]; + ActionGroup[] newGroups = new ActionGroup[fGroups.length + 1]; System.arraycopy(fGroups, 0, newGroups, 0, fGroups.length); - newGroups[fGroups.length]= group; - fGroups= newGroups; + newGroups[fGroups.length] = group; + fGroups = newGroups; } } - + public void dispose() { super.dispose(); if (fGroups == null) return; - for (int i= 0; i < fGroups.length; i++) { + for (int i = 0; i < fGroups.length; i++) { fGroups[i].dispose(); } } @@ -63,7 +63,7 @@ public class CompositeActionGroup extends ActionGroup { super.fillActionBars(actionBars); if (fGroups == null) return; - for (int i= 0; i < fGroups.length; i++) { + for (int i = 0; i < fGroups.length; i++) { fGroups[i].fillActionBars(actionBars); } } @@ -72,7 +72,7 @@ public class CompositeActionGroup extends ActionGroup { super.fillContextMenu(menu); if (fGroups == null) return; - for (int i= 0; i < fGroups.length; i++) { + for (int i = 0; i < fGroups.length; i++) { fGroups[i].fillContextMenu(menu); } } @@ -81,7 +81,7 @@ public class CompositeActionGroup extends ActionGroup { super.setContext(context); if (fGroups == null) return; - for (int i= 0; i < fGroups.length; i++) { + for (int i = 0; i < fGroups.length; i++) { fGroups[i].setContext(context); } } @@ -90,7 +90,7 @@ public class CompositeActionGroup extends ActionGroup { super.updateActionBars(); if (fGroups == null) return; - for (int i= 0; i < fGroups.length; i++) { + for (int i = 0; i < fGroups.length; i++) { fGroups[i].updateActionBars(); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/FoldingActionGroup.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/FoldingActionGroup.java index 836cc53..844fe84 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/FoldingActionGroup.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/FoldingActionGroup.java @@ -19,35 +19,39 @@ import org.eclipse.ui.editors.text.IFoldingCommandIds; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.TextOperationAction; - /** * Groups the JDT folding actions. - * + * * @since 3.0 */ public class FoldingActionGroup extends ActionGroup { private ProjectionViewer fViewer; - + private TextOperationAction fToggle; + private TextOperationAction fExpand; + private TextOperationAction fCollapse; + private TextOperationAction fExpandAll; private IProjectionListener fProjectionListener; - + /** * Creates a new projection action group for editor. If the - * supplied viewer is not an instance of ProjectionViewer, the - * action group is disabled. + * supplied viewer is not an instance of ProjectionViewer, + * the action group is disabled. * - * @param editor the text editor to operate on - * @param viewer the viewer of the editor + * @param editor + * the text editor to operate on + * @param viewer + * the viewer of the editor */ public FoldingActionGroup(ITextEditor editor, ITextViewer viewer) { if (viewer instanceof ProjectionViewer) { - fViewer= (ProjectionViewer) viewer; - - fProjectionListener= new IProjectionListener() { + fViewer = (ProjectionViewer) viewer; + + fProjectionListener = new IProjectionListener() { public void projectionEnabled() { update(); @@ -57,32 +61,43 @@ public class FoldingActionGroup extends ActionGroup { update(); } }; - + fViewer.addProjectionListener(fProjectionListener); - - fToggle= new TextOperationAction(ActionMessages.getResourceBundle(), "Projection.Toggle.", editor, ProjectionViewer.TOGGLE, true); //$NON-NLS-1$ + + fToggle = new TextOperationAction(ActionMessages + .getResourceBundle(), + "Projection.Toggle.", editor, ProjectionViewer.TOGGLE, true); //$NON-NLS-1$ fToggle.setChecked(true); fToggle.setActionDefinitionId(IFoldingCommandIds.FOLDING_TOGGLE); editor.setAction("FoldingToggle", fToggle); //$NON-NLS-1$ - - fExpandAll= new TextOperationAction(ActionMessages.getResourceBundle(), "Projection.ExpandAll.", editor, ProjectionViewer.EXPAND_ALL, true); //$NON-NLS-1$ - fExpandAll.setActionDefinitionId(IFoldingCommandIds.FOLDING_EXPAND_ALL); + + fExpandAll = new TextOperationAction( + ActionMessages.getResourceBundle(), + "Projection.ExpandAll.", editor, ProjectionViewer.EXPAND_ALL, true); //$NON-NLS-1$ + fExpandAll + .setActionDefinitionId(IFoldingCommandIds.FOLDING_EXPAND_ALL); editor.setAction("FoldingExpandAll", fExpandAll); //$NON-NLS-1$ - - fExpand= new TextOperationAction(ActionMessages.getResourceBundle(), "Projection.Expand.", editor, ProjectionViewer.EXPAND, true); //$NON-NLS-1$ + + fExpand = new TextOperationAction(ActionMessages + .getResourceBundle(), + "Projection.Expand.", editor, ProjectionViewer.EXPAND, true); //$NON-NLS-1$ fExpand.setActionDefinitionId(IFoldingCommandIds.FOLDING_EXPAND); editor.setAction("FoldingExpand", fExpand); //$NON-NLS-1$ - - fCollapse= new TextOperationAction(ActionMessages.getResourceBundle(), "Projection.Collapse.", editor, ProjectionViewer.COLLAPSE, true); //$NON-NLS-1$ - fCollapse.setActionDefinitionId(IFoldingCommandIds.FOLDING_COLLAPSE); + + fCollapse = new TextOperationAction( + ActionMessages.getResourceBundle(), + "Projection.Collapse.", editor, ProjectionViewer.COLLAPSE, true); //$NON-NLS-1$ + fCollapse + .setActionDefinitionId(IFoldingCommandIds.FOLDING_COLLAPSE); editor.setAction("FoldingCollapse", fCollapse); //$NON-NLS-1$ } } - + /** - * Returns true if the group is enabled. + * Returns true if the group is enabled. + * *
                                                      -	 * Invariant: isEnabled() <=> fViewer and all actions are != null.
                                                      +	 *  Invariant: isEnabled() <=> fViewer and all actions are != null.
                                                       	 * 
                                                      * * @return true if the group is enabled @@ -90,18 +105,18 @@ public class FoldingActionGroup extends ActionGroup { protected boolean isEnabled() { return fViewer != null; } - + /* * @see org.eclipse.ui.actions.ActionGroup#dispose() */ public void dispose() { if (isEnabled()) { fViewer.removeProjectionListener(fProjectionListener); - fViewer= null; + fViewer = null; } super.dispose(); } - + /** * Updates the actions. */ @@ -114,11 +129,12 @@ public class FoldingActionGroup extends ActionGroup { fCollapse.update(); } } - + /** * Fills the menu with all folding actions. * - * @param manager the menu manager for the folding submenu + * @param manager + * the menu manager for the folding submenu */ public void fillMenu(IMenuManager manager) { if (isEnabled()) { @@ -129,7 +145,7 @@ public class FoldingActionGroup extends ActionGroup { manager.add(fCollapse); } } - + /* * @see org.eclipse.ui.actions.ActionGroup#updateActionBars() */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/FoldingExpandAllRulerAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/FoldingExpandAllRulerAction.java index e2765ba..9cbd454 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/FoldingExpandAllRulerAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/FoldingExpandAllRulerAction.java @@ -18,19 +18,22 @@ import org.eclipse.ui.texteditor.AbstractRulerActionDelegate; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.TextOperationAction; - /** * Groups the JDT folding actions. - * + * * @since 3.0 */ public class FoldingExpandAllRulerAction extends AbstractRulerActionDelegate { /* - * @see org.eclipse.ui.texteditor.AbstractRulerActionDelegate#createAction(org.eclipse.ui.texteditor.ITextEditor, org.eclipse.jface.text.source.IVerticalRulerInfo) + * @see org.eclipse.ui.texteditor.AbstractRulerActionDelegate#createAction(org.eclipse.ui.texteditor.ITextEditor, + * org.eclipse.jface.text.source.IVerticalRulerInfo) */ - protected IAction createAction(ITextEditor editor, IVerticalRulerInfo rulerInfo) { - TextOperationAction action= new TextOperationAction(ActionMessages.getResourceBundle(), "Projection.ExpandAll.", editor, ProjectionViewer.EXPAND_ALL, true); //$NON-NLS-1$ + protected IAction createAction(ITextEditor editor, + IVerticalRulerInfo rulerInfo) { + TextOperationAction action = new TextOperationAction( + ActionMessages.getResourceBundle(), + "Projection.ExpandAll.", editor, ProjectionViewer.EXPAND_ALL, true); //$NON-NLS-1$ action.setActionDefinitionId(IFoldingCommandIds.FOLDING_EXPAND_ALL); return action; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/FoldingToggleRulerAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/FoldingToggleRulerAction.java index 21f8a1b..49502ea 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/FoldingToggleRulerAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/FoldingToggleRulerAction.java @@ -23,37 +23,42 @@ import org.eclipse.ui.texteditor.AbstractRulerActionDelegate; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.TextOperationAction; - /** * Groups the JDT folding actions. - * + * * @since 3.0 */ public class FoldingToggleRulerAction extends AbstractRulerActionDelegate { private IAction fUIAction; + private TextOperationAction fAction; + private ITextEditor fTextEditor; /* - * @see org.eclipse.ui.texteditor.AbstractRulerActionDelegate#createAction(org.eclipse.ui.texteditor.ITextEditor, org.eclipse.jface.text.source.IVerticalRulerInfo) + * @see org.eclipse.ui.texteditor.AbstractRulerActionDelegate#createAction(org.eclipse.ui.texteditor.ITextEditor, + * org.eclipse.jface.text.source.IVerticalRulerInfo) */ - protected IAction createAction(ITextEditor editor, IVerticalRulerInfo rulerInfo) { - fTextEditor= editor; - fAction= new TextOperationAction(ActionMessages.getResourceBundle(), "Projection.Toggle.", editor, ProjectionViewer.TOGGLE, true); //$NON-NLS-1$ + protected IAction createAction(ITextEditor editor, + IVerticalRulerInfo rulerInfo) { + fTextEditor = editor; + fAction = new TextOperationAction(ActionMessages.getResourceBundle(), + "Projection.Toggle.", editor, ProjectionViewer.TOGGLE, true); //$NON-NLS-1$ fAction.setActionDefinitionId(IFoldingCommandIds.FOLDING_TOGGLE); return fAction; } - + /* - * @see org.eclipse.ui.texteditor.AbstractRulerActionDelegate#setActiveEditor(org.eclipse.jface.action.IAction, org.eclipse.ui.IEditorPart) + * @see org.eclipse.ui.texteditor.AbstractRulerActionDelegate#setActiveEditor(org.eclipse.jface.action.IAction, + * org.eclipse.ui.IEditorPart) */ public void setActiveEditor(IAction callerAction, IEditorPart targetEditor) { - fUIAction= callerAction; + fUIAction = callerAction; super.setActiveEditor(callerAction, targetEditor); } - + /* * @see org.eclipse.ui.texteditor.AbstractRulerActionDelegate#menuAboutToShow(org.eclipse.jface.action.IMenuManager) */ @@ -61,12 +66,13 @@ public class FoldingToggleRulerAction extends AbstractRulerActionDelegate { update(); super.menuAboutToShow(manager); } - + private void update() { if (fTextEditor instanceof PHPEditor) { - ISourceViewer viewer= ((PHPEditor) fTextEditor).getViewer(); + ISourceViewer viewer = ((PHPEditor) fTextEditor).getViewer(); if (viewer instanceof ProjectionViewer) { - boolean enabled= ((ProjectionViewer) viewer).getProjectionAnnotationModel() != null; + boolean enabled = ((ProjectionViewer) viewer) + .getProjectionAnnotationModel() != null; fUIAction.setChecked(enabled); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/IndentAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/IndentAction.java index 7700f37..44cfdb5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/IndentAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/IndentAction.java @@ -53,41 +53,45 @@ import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.ITextEditorExtension3; import org.eclipse.ui.texteditor.TextEditorAction; - /** - * Indents a line or range of lines in a Java document to its correct position. No complete - * AST must be present, the indentation is computed using heuristics. The algorith used is fast for - * single lines, but does not store any information and therefore not so efficient for large line - * ranges. + * Indents a line or range of lines in a Java document to its correct position. + * No complete AST must be present, the indentation is computed using + * heuristics. The algorith used is fast for single lines, but does not store + * any information and therefore not so efficient for large line ranges. * * @see net.sourceforge.phpdt.internal.ui.text.JavaHeuristicScanner * @see net.sourceforge.phpdt.internal.ui.text.JavaIndenter * @since 3.0 */ public class IndentAction extends TextEditorAction { - + /** The caret offset after an indent operation. */ private int fCaretOffset; - - /** - * Whether this is the action invoked by TAB. When true, indentation behaves - * differently to accomodate normal TAB operation. + + /** + * Whether this is the action invoked by TAB. When true, + * indentation behaves differently to accomodate normal TAB operation. */ private final boolean fIsTabAction; - + /** * Creates a new instance. * - * @param bundle the resource bundle - * @param prefix the prefix to use for keys in bundle - * @param editor the text editor - * @param isTabAction whether the action should insert tabs if over the indentation + * @param bundle + * the resource bundle + * @param prefix + * the prefix to use for keys in bundle + * @param editor + * the text editor + * @param isTabAction + * whether the action should insert tabs if over the indentation */ - public IndentAction(ResourceBundle bundle, String prefix, ITextEditor editor, boolean isTabAction) { + public IndentAction(ResourceBundle bundle, String prefix, + ITextEditor editor, boolean isTabAction) { super(bundle, prefix, editor); - fIsTabAction= isTabAction; + fIsTabAction = isTabAction; } - + /* * @see org.eclipse.jface.action.Action#run() */ @@ -95,72 +99,82 @@ public class IndentAction extends TextEditorAction { // update has been called by the framework if (!isEnabled() || !validateEditorInputState()) return; - - ITextSelection selection= getSelection(); - final IDocument document= getDocument(); - + + ITextSelection selection = getSelection(); + final IDocument document = getDocument(); + if (document != null) { - - final int offset= selection.getOffset(); - final int length= selection.getLength(); - final Position end= new Position(offset + length); + + final int offset = selection.getOffset(); + final int length = selection.getLength(); + final Position end = new Position(offset + length); final int firstLine, nLines; - fCaretOffset= -1; - + fCaretOffset = -1; + try { document.addPosition(end); - firstLine= document.getLineOfOffset(offset); + firstLine = document.getLineOfOffset(offset); // check for marginal (zero-length) lines - int minusOne= length == 0 ? 0 : 1; - nLines= document.getLineOfOffset(offset + length - minusOne) - firstLine + 1; + int minusOne = length == 0 ? 0 : 1; + nLines = document.getLineOfOffset(offset + length - minusOne) + - firstLine + 1; } catch (BadLocationException e) { // will only happen on concurrent modification - PHPeclipsePlugin.log(new Status(IStatus.ERROR, PHPeclipsePlugin.getPluginId(), IStatus.OK, "", e)); //$NON-NLS-1$ + PHPeclipsePlugin.log(new Status(IStatus.ERROR, PHPeclipsePlugin + .getPluginId(), IStatus.OK, "", e)); //$NON-NLS-1$ return; } - - Runnable runnable= new Runnable() { + + Runnable runnable = new Runnable() { public void run() { - IRewriteTarget target= (IRewriteTarget)getTextEditor().getAdapter(IRewriteTarget.class); + IRewriteTarget target = (IRewriteTarget) getTextEditor() + .getAdapter(IRewriteTarget.class); if (target != null) { target.beginCompoundChange(); target.setRedraw(false); } - + try { - JavaHeuristicScanner scanner= new JavaHeuristicScanner(document); - JavaIndenter indenter= new JavaIndenter(document, scanner); - boolean hasChanged= false; - for (int i= 0; i < nLines; i++) { - hasChanged |= indentLine(document, firstLine + i, offset, indenter, scanner); + JavaHeuristicScanner scanner = new JavaHeuristicScanner( + document); + JavaIndenter indenter = new JavaIndenter(document, + scanner); + boolean hasChanged = false; + for (int i = 0; i < nLines; i++) { + hasChanged |= indentLine(document, firstLine + i, + offset, indenter, scanner); } - - // update caret position: move to new position when indenting just one line + + // update caret position: move to new position when + // indenting just one line // keep selection when indenting multiple int newOffset, newLength; if (fIsTabAction) { - newOffset= fCaretOffset; - newLength= 0; + newOffset = fCaretOffset; + newLength = 0; } else if (nLines > 1) { - newOffset= offset; - newLength= end.getOffset() - offset; + newOffset = offset; + newLength = end.getOffset() - offset; } else { - newOffset= fCaretOffset; - newLength= 0; + newOffset = fCaretOffset; + newLength = 0; } - + // always reset the selection if anything was replaced // but not when we had a singleline nontab invocation - if (newOffset != -1 && (hasChanged || newOffset != offset || newLength != length)) + if (newOffset != -1 + && (hasChanged || newOffset != offset || newLength != length)) selectAndReveal(newOffset, newLength); - + document.removePosition(end); } catch (BadLocationException e) { // will only happen on concurrent modification - PHPeclipsePlugin.log(new Status(IStatus.ERROR, PHPeclipsePlugin.getPluginId(), IStatus.OK, "ConcurrentModification in IndentAction", e)); //$NON-NLS-1$ - + PHPeclipsePlugin.log(new Status(IStatus.ERROR, + PHPeclipsePlugin.getPluginId(), IStatus.OK, + "ConcurrentModification in IndentAction", e)); //$NON-NLS-1$ + } finally { - + if (target != null) { target.endCompoundChange(); target.setRedraw(true); @@ -168,216 +182,259 @@ public class IndentAction extends TextEditorAction { } } }; - + if (nLines > 50) { - Display display= getTextEditor().getEditorSite().getWorkbenchWindow().getShell().getDisplay(); + Display display = getTextEditor().getEditorSite() + .getWorkbenchWindow().getShell().getDisplay(); BusyIndicator.showWhile(display, runnable); } else runnable.run(); - + } } - + /** * Selects the given range on the editor. * - * @param newOffset the selection offset - * @param newLength the selection range + * @param newOffset + * the selection offset + * @param newLength + * the selection range */ private void selectAndReveal(int newOffset, int newLength) { - Assert.isTrue(newOffset >= 0); - Assert.isTrue(newLength >= 0); - ITextEditor editor= getTextEditor(); + Assert.isTrue(newOffset >= 0); + Assert.isTrue(newLength >= 0); + ITextEditor editor = getTextEditor(); if (editor instanceof PHPEditor) { - ISourceViewer viewer= ((PHPEditor)editor).getViewer(); + ISourceViewer viewer = ((PHPEditor) editor).getViewer(); if (viewer != null) viewer.setSelectedRange(newOffset, newLength); } else // this is too intrusive, but will never get called anyway getTextEditor().selectAndReveal(newOffset, newLength); - + } /** - * Indents a single line using the java heuristic scanner. Javadoc and multiline comments are - * indented as specified by the JavaDocAutoIndentStrategy. + * Indents a single line using the java heuristic scanner. Javadoc and + * multiline comments are indented as specified by the + * JavaDocAutoIndentStrategy. * - * @param document the document - * @param line the line to be indented - * @param caret the caret position - * @param indenter the java indenter - * @param scanner the heuristic scanner - * @return true if document was modified, false otherwise - * @throws BadLocationException if the document got changed concurrently + * @param document + * the document + * @param line + * the line to be indented + * @param caret + * the caret position + * @param indenter + * the java indenter + * @param scanner + * the heuristic scanner + * @return true if document was modified, + * false otherwise + * @throws BadLocationException + * if the document got changed concurrently */ - private boolean indentLine(IDocument document, int line, int caret, JavaIndenter indenter, JavaHeuristicScanner scanner) throws BadLocationException { - IRegion currentLine= document.getLineInformation(line); - int offset= currentLine.getOffset(); - int wsStart= offset; // where we start searching for non-WS; after the "//" in single line comments - - String indent= null; + private boolean indentLine(IDocument document, int line, int caret, + JavaIndenter indenter, JavaHeuristicScanner scanner) + throws BadLocationException { + IRegion currentLine = document.getLineInformation(line); + int offset = currentLine.getOffset(); + int wsStart = offset; // where we start searching for non-WS; after + // the "//" in single line comments + + String indent = null; if (offset < document.getLength()) { - ITypedRegion partition= TextUtilities.getPartition(document, IPHPPartitions.PHP_PARTITIONING, offset, true); - String type= partition.getType(); - if (type.equals(IPHPPartitions.PHP_PHPDOC_COMMENT) || type.equals(IPHPPartitions.PHP_MULTILINE_COMMENT)) { - + ITypedRegion partition = TextUtilities.getPartition(document, + IPHPPartitions.PHP_PARTITIONING, offset, true); + String type = partition.getType(); + if (type.equals(IPHPPartitions.PHP_PHPDOC_COMMENT) + || type.equals(IPHPPartitions.PHP_MULTILINE_COMMENT)) { + // TODO this is a hack // what I want to do -// new JavaDocAutoIndentStrategy().indentLineAtOffset(document, offset); -// return; + // new JavaDocAutoIndentStrategy().indentLineAtOffset(document, + // offset); + // return; - int start= 0; + int start = 0; if (line > 0) { - IRegion previousLine= document.getLineInformation(line - 1); - start= previousLine.getOffset() + previousLine.getLength(); + IRegion previousLine = document + .getLineInformation(line - 1); + start = previousLine.getOffset() + previousLine.getLength(); } - DocumentCommand command= new DocumentCommand() {}; - command.text= "\n"; //$NON-NLS-1$ - command.offset= start; - new JavaDocAutoIndentStrategy(IPHPPartitions.PHP_PARTITIONING).customizeDocumentCommand(document, command); - int to= 1; - while (to < command.text.length() && Character.isWhitespace(command.text.charAt(to))) + DocumentCommand command = new DocumentCommand() { + }; + command.text = "\n"; //$NON-NLS-1$ + command.offset = start; + new JavaDocAutoIndentStrategy(IPHPPartitions.PHP_PARTITIONING) + .customizeDocumentCommand(document, command); + int to = 1; + while (to < command.text.length() + && Character.isWhitespace(command.text.charAt(to))) to++; - indent= command.text.substring(1, to); - - } else if (!fIsTabAction && partition.getOffset() == offset && type.equals(IPHPPartitions.PHP_SINGLELINE_COMMENT)) { - + indent = command.text.substring(1, to); + + } else if (!fIsTabAction && partition.getOffset() == offset + && type.equals(IPHPPartitions.PHP_SINGLELINE_COMMENT)) { + // line comment starting at position 0 -> indent inside - int slashes= 2; - while (slashes < document.getLength() - 1 && document.get(offset + slashes, 2).equals("//")) //$NON-NLS-1$ - slashes+= 2; - - wsStart= offset + slashes; - - StringBuffer computed= indenter.computeIndentation(offset); - int tabSize= PHPeclipsePlugin.getDefault().getPreferenceStore().getInt(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH); + int slashes = 2; + while (slashes < document.getLength() - 1 + && document.get(offset + slashes, 2).equals("//")) //$NON-NLS-1$ + slashes += 2; + + wsStart = offset + slashes; + + StringBuffer computed = indenter.computeIndentation(offset); + int tabSize = PHPeclipsePlugin + .getDefault() + .getPreferenceStore() + .getInt( + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH); while (slashes > 0 && computed.length() > 0) { - char c= computed.charAt(0); + char c = computed.charAt(0); if (c == '\t') if (slashes > tabSize) - slashes-= tabSize; + slashes -= tabSize; else break; else if (c == ' ') slashes--; - else break; - + else + break; + computed.deleteCharAt(0); } - - indent= document.get(offset, wsStart - offset) + computed; - + + indent = document.get(offset, wsStart - offset) + computed; + } - } - + } + // standard java indentation if (indent == null) { - StringBuffer computed= indenter.computeIndentation(offset); + StringBuffer computed = indenter.computeIndentation(offset); if (computed != null) - indent= computed.toString(); + indent = computed.toString(); else - indent= new String(); + indent = new String(); } - + // change document: // get current white space - int lineLength= currentLine.getLength(); - int end= scanner.findNonWhitespaceForwardInAnyPartition(wsStart, offset + lineLength); + int lineLength = currentLine.getLength(); + int end = scanner.findNonWhitespaceForwardInAnyPartition(wsStart, + offset + lineLength); if (end == JavaHeuristicScanner.NOT_FOUND) - end= offset + lineLength; - int length= end - offset; - String currentIndent= document.get(offset, length); - - // if we are right before the text start / line end, and already after the insertion point + end = offset + lineLength; + int length = end - offset; + String currentIndent = document.get(offset, length); + + // if we are right before the text start / line end, and already after + // the insertion point // then just insert a tab. - if (fIsTabAction && caret == end && whiteSpaceLength(currentIndent) >= whiteSpaceLength(indent)) { - String tab= getTabEquivalent(); + if (fIsTabAction && caret == end + && whiteSpaceLength(currentIndent) >= whiteSpaceLength(indent)) { + String tab = getTabEquivalent(); document.replace(caret, 0, tab); - fCaretOffset= caret + tab.length(); + fCaretOffset = caret + tab.length(); return true; } - + // set the caret offset so it can be used when setting the selection if (caret >= offset && caret <= end) - fCaretOffset= offset + indent.length(); + fCaretOffset = offset + indent.length(); else - fCaretOffset= -1; - + fCaretOffset = -1; + // only change the document if it is a real change if (!indent.equals(currentIndent)) { - String deletedText= document.get(offset, length); + String deletedText = document.get(offset, length); document.replace(offset, length, indent); - - if (fIsTabAction && indent.length() > currentIndent.length() && PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_BACKSPACE)) { - ITextEditor editor= getTextEditor(); + + if (fIsTabAction + && indent.length() > currentIndent.length() + && PHPeclipsePlugin.getDefault().getPreferenceStore() + .getBoolean( + PreferenceConstants.EDITOR_SMART_BACKSPACE)) { + ITextEditor editor = getTextEditor(); if (editor != null) { - final SmartBackspaceManager manager= (SmartBackspaceManager) editor.getAdapter(SmartBackspaceManager.class); + final SmartBackspaceManager manager = (SmartBackspaceManager) editor + .getAdapter(SmartBackspaceManager.class); if (manager != null) { try { // restore smart portion - ReplaceEdit smart= new ReplaceEdit(offset, indent.length(), deletedText); - - final UndoSpec spec= new UndoSpec( - offset + indent.length(), - new Region(caret, 0), - new TextEdit[] { smart }, - 2, - null); + ReplaceEdit smart = new ReplaceEdit(offset, indent + .length(), deletedText); + + final UndoSpec spec = new UndoSpec(offset + + indent.length(), new Region(caret, 0), + new TextEdit[] { smart }, 2, null); manager.register(spec); } catch (MalformedTreeException e) { // log & ignore - PHPeclipsePlugin.log(new Status(IStatus.ERROR, PHPeclipsePlugin.getPluginId(), IStatus.OK, "Illegal smart backspace action", e)); //$NON-NLS-1$ + PHPeclipsePlugin.log(new Status(IStatus.ERROR, + PHPeclipsePlugin.getPluginId(), IStatus.OK, + "Illegal smart backspace action", e)); //$NON-NLS-1$ } } } } - return true; } else return false; } - + /** - * Returns the size in characters of a string. All characters count one, tabs count the editor's - * preference for the tab display + * Returns the size in characters of a string. All characters count one, + * tabs count the editor's preference for the tab display * - * @param indent the string to be measured. + * @param indent + * the string to be measured. * @return */ private int whiteSpaceLength(String indent) { if (indent == null) return 0; else { - int size= 0; - int l= indent.length(); - int tabSize= PHPeclipsePlugin.getDefault().getPreferenceStore().getInt(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH); - - for (int i= 0; i < l; i++) + int size = 0; + int l = indent.length(); + int tabSize = PHPeclipsePlugin + .getDefault() + .getPreferenceStore() + .getInt( + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH); + + for (int i = 0; i < l; i++) size += indent.charAt(i) == '\t' ? tabSize : 1; return size; } } /** - * Returns a tab equivalent, either as a tab character or as spaces, depending on the editor and - * formatter preferences. + * Returns a tab equivalent, either as a tab character or as spaces, + * depending on the editor and formatter preferences. * - * @return a string representing one tab in the editor, never null + * @return a string representing one tab in the editor, never + * null */ private String getTabEquivalent() { String tab; - if (PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SPACES_FOR_TABS)) { - int size= JavaCore.getPlugin().getPluginPreferences().getInt(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE); - StringBuffer buf= new StringBuffer(); - for (int i= 0; i< size; i++) + if (PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean( + PreferenceConstants.EDITOR_SPACES_FOR_TABS)) { + int size = JavaCore.getPlugin().getPluginPreferences().getInt( + DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE); + StringBuffer buf = new StringBuffer(); + for (int i = 0; i < size; i++) buf.append(' '); - tab= buf.toString(); + tab = buf.toString(); } else - tab= "\t"; //$NON-NLS-1$ - + tab = "\t"; //$NON-NLS-1$ + return tab; } @@ -387,113 +444,119 @@ public class IndentAction extends TextEditorAction { * @return the editor's selection provider or null */ private ISelectionProvider getSelectionProvider() { - ITextEditor editor= getTextEditor(); + ITextEditor editor = getTextEditor(); if (editor != null) { return editor.getSelectionProvider(); } return null; } - + /* * @see org.eclipse.ui.texteditor.IUpdate#update() */ public void update() { super.update(); - + if (isEnabled()) if (fIsTabAction) - setEnabled(canModifyEditor() && isSmartMode() && isValidSelection()); + setEnabled(canModifyEditor() && isSmartMode() + && isValidSelection()); else setEnabled(canModifyEditor() && !getSelection().isEmpty()); } - + /** - * Returns if the current selection is valid, i.e. whether it is empty and the caret in the - * whitespace at the start of a line, or covers multiple lines. + * Returns if the current selection is valid, i.e. whether it is empty and + * the caret in the whitespace at the start of a line, or covers multiple + * lines. * - * @return true if the selection is valid for an indent operation + * @return true if the selection is valid for an indent + * operation */ private boolean isValidSelection() { - ITextSelection selection= getSelection(); + ITextSelection selection = getSelection(); if (selection.isEmpty()) return false; - - int offset= selection.getOffset(); - int length= selection.getLength(); - - IDocument document= getDocument(); + + int offset = selection.getOffset(); + int length = selection.getLength(); + + IDocument document = getDocument(); if (document == null) return false; - + try { - IRegion firstLine= document.getLineInformationOfOffset(offset); - int lineOffset= firstLine.getOffset(); - - // either the selection has to be empty and the caret in the WS at the line start + IRegion firstLine = document.getLineInformationOfOffset(offset); + int lineOffset = firstLine.getOffset(); + + // either the selection has to be empty and the caret in the WS at + // the line start // or the selection has to extend over multiple lines if (length == 0) - return document.get(lineOffset, offset - lineOffset).trim().length() == 0; + return document.get(lineOffset, offset - lineOffset).trim() + .length() == 0; else -// return lineOffset + firstLine.getLength() < offset + length; + // return lineOffset + firstLine.getLength() < offset + length; return false; // only enable for empty selections for now - + } catch (BadLocationException e) { } - + return false; } - + /** * Returns the smart preference state. * - * @return true if smart mode is on, false otherwise + * @return true if smart mode is on, false + * otherwise */ private boolean isSmartMode() { - ITextEditor editor= getTextEditor(); - + ITextEditor editor = getTextEditor(); + if (editor instanceof ITextEditorExtension3) return ((ITextEditorExtension3) editor).getInsertMode() == ITextEditorExtension3.SMART_INSERT; - + return false; } - + /** - * Returns the document currently displayed in the editor, or null if none can be - * obtained. + * Returns the document currently displayed in the editor, or + * null if none can be obtained. * * @return the current document or null */ private IDocument getDocument() { - - ITextEditor editor= getTextEditor(); + + ITextEditor editor = getTextEditor(); if (editor != null) { - - IDocumentProvider provider= editor.getDocumentProvider(); - IEditorInput input= editor.getEditorInput(); + + IDocumentProvider provider = editor.getDocumentProvider(); + IEditorInput input = editor.getEditorInput(); if (provider != null && input != null) return provider.getDocument(input); - + } return null; } - + /** - * Returns the selection on the editor or an invalid selection if none can be obtained. Returns - * never null. + * Returns the selection on the editor or an invalid selection if none can + * be obtained. Returns never null. * * @return the current selection, never null */ private ITextSelection getSelection() { - ISelectionProvider provider= getSelectionProvider(); + ISelectionProvider provider = getSelectionProvider(); if (provider != null) { - - ISelection selection= provider.getSelection(); + + ISelection selection = provider.getSelection(); if (selection instanceof ITextSelection) return (ITextSelection) selection; } - + // null object return TextSelection.emptySelection(); } - + } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/OpenActionUtil.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/OpenActionUtil.java index 272cf01..02c7b6b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/OpenActionUtil.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/OpenActionUtil.java @@ -25,75 +25,79 @@ import org.eclipse.ui.PartInitException; import org.eclipse.ui.dialogs.ElementListSelectionDialog; public class OpenActionUtil { - + private OpenActionUtil() { // no instance. } - + /** * Opens the editor on the given element and subsequently selects it. */ - public static void open(Object element) throws JavaModelException, PartInitException { + public static void open(Object element) throws JavaModelException, + PartInitException { open(element, true); } - + /** * Opens the editor on the given element and subsequently selects it. */ - public static void open(Object element, boolean activate) throws JavaModelException, PartInitException { - IEditorPart part= EditorUtility.openInEditor(element, activate); + public static void open(Object element, boolean activate) + throws JavaModelException, PartInitException { + IEditorPart part = EditorUtility.openInEditor(element, activate); if (element instanceof IJavaElement) - EditorUtility.revealInEditor(part, (IJavaElement)element); + EditorUtility.revealInEditor(part, (IJavaElement) element); } - + /** - * Filters out source references from the given code resolve results. - * A utility method that can be called by subclassers. + * Filters out source references from the given code resolve results. A + * utility method that can be called by subclassers. */ public static List filterResolveResults(IJavaElement[] codeResolveResults) { - int nResults= codeResolveResults.length; - List refs= new ArrayList(nResults); - for (int i= 0; i < nResults; i++) { + int nResults = codeResolveResults.length; + List refs = new ArrayList(nResults); + for (int i = 0; i < nResults; i++) { if (codeResolveResults[i] instanceof ISourceReference) refs.add(codeResolveResults[i]); } return refs; } - + /** - * Shows a dialog for resolving an ambigous java element. - * Utility method that can be called by subclassers. + * Shows a dialog for resolving an ambigous java element. Utility method + * that can be called by subclassers. */ - public static IJavaElement selectJavaElement(IJavaElement[] elements, Shell shell, String title, String message) { - - int nResults= elements.length; - + public static IJavaElement selectJavaElement(IJavaElement[] elements, + Shell shell, String title, String message) { + + int nResults = elements.length; + if (nResults == 0) return null; - + if (nResults == 1) return elements[0]; - - int flags= JavaElementLabelProvider.SHOW_DEFAULT - | JavaElementLabelProvider.SHOW_QUALIFIED - | JavaElementLabelProvider.SHOW_ROOT; - - ElementListSelectionDialog dialog= new ElementListSelectionDialog(shell, new JavaElementLabelProvider(flags)); + + int flags = JavaElementLabelProvider.SHOW_DEFAULT + | JavaElementLabelProvider.SHOW_QUALIFIED + | JavaElementLabelProvider.SHOW_ROOT; + + ElementListSelectionDialog dialog = new ElementListSelectionDialog( + shell, new JavaElementLabelProvider(flags)); dialog.setTitle(title); dialog.setMessage(message); dialog.setElements(elements); - + if (dialog.open() == ElementListSelectionDialog.OK) { - Object[] selection= dialog.getResult(); + Object[] selection = dialog.getResult(); if (selection != null && selection.length > 0) { - nResults= selection.length; - for (int i= 0; i < nResults; i++) { - Object current= selection[i]; + nResults = selection.length; + for (int i = 0; i < nResults; i++) { + Object current = selection[i]; if (current instanceof IJavaElement) return (IJavaElement) current; } } - } + } return null; - } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/RemoveBlockCommentAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/RemoveBlockCommentAction.java index 821e4a2..f1709fc 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/RemoveBlockCommentAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/RemoveBlockCommentAction.java @@ -33,45 +33,57 @@ public class RemoveBlockCommentAction extends BlockCommentAction { /** * Creates a new instance. * - * @param bundle the resource bundle - * @param prefix a prefix to be prepended to the various resource keys - * (described in ResourceAction constructor), or - * null if none - * @param editor the text editor + * @param bundle + * the resource bundle + * @param prefix + * a prefix to be prepended to the various resource keys + * (described in ResourceAction constructor), or + * null if none + * @param editor + * the text editor */ - public RemoveBlockCommentAction(ResourceBundle bundle, String prefix, ITextEditor editor) { + public RemoveBlockCommentAction(ResourceBundle bundle, String prefix, + ITextEditor editor) { super(bundle, prefix, editor); } - + /* - * @see net.sourceforge.phpdt.internal.ui.actions.AddBlockCommentAction#runInternal(org.eclipse.jface.text.ITextSelection, org.eclipse.jface.text.IDocumentExtension3, net.sourceforge.phpdt.internal.ui.actions.AddBlockCommentAction.Edit.EditFactory) + * @see net.sourceforge.phpdt.internal.ui.actions.AddBlockCommentAction#runInternal(org.eclipse.jface.text.ITextSelection, + * org.eclipse.jface.text.IDocumentExtension3, + * net.sourceforge.phpdt.internal.ui.actions.AddBlockCommentAction.Edit.EditFactory) */ - protected void runInternal(ITextSelection selection, IDocumentExtension3 docExtension, Edit.EditFactory factory) throws BadPartitioningException, BadLocationException { - List edits= new LinkedList(); - int tokenLength= getCommentStart().length(); - - int offset= selection.getOffset(); - int endOffset= offset + selection.getLength(); + protected void runInternal(ITextSelection selection, + IDocumentExtension3 docExtension, Edit.EditFactory factory) + throws BadPartitioningException, BadLocationException { + List edits = new LinkedList(); + int tokenLength = getCommentStart().length(); + + int offset = selection.getOffset(); + int endOffset = offset + selection.getLength(); + + ITypedRegion partition = docExtension.getPartition( + IPHPPartitions.PHP_PARTITIONING, offset, false); + int partOffset = partition.getOffset(); + int partEndOffset = partOffset + partition.getLength(); - ITypedRegion partition= docExtension.getPartition(IPHPPartitions.PHP_PARTITIONING, offset, false); - int partOffset= partition.getOffset(); - int partEndOffset= partOffset + partition.getLength(); - while (partEndOffset < endOffset) { - + if (partition.getType() == IPHPPartitions.PHP_MULTILINE_COMMENT) { edits.add(factory.createEdit(partOffset, tokenLength, "")); //$NON-NLS-1$ - edits.add(factory.createEdit(partEndOffset - tokenLength, tokenLength, "")); //$NON-NLS-1$ + edits.add(factory.createEdit(partEndOffset - tokenLength, + tokenLength, "")); //$NON-NLS-1$ } - - partition= docExtension.getPartition(IPHPPartitions.PHP_PARTITIONING, partEndOffset, false); - partOffset= partition.getOffset(); - partEndOffset= partOffset + partition.getLength(); + + partition = docExtension.getPartition( + IPHPPartitions.PHP_PARTITIONING, partEndOffset, false); + partOffset = partition.getOffset(); + partEndOffset = partOffset + partition.getLength(); } if (partition.getType() == IPHPPartitions.PHP_MULTILINE_COMMENT) { edits.add(factory.createEdit(partOffset, tokenLength, "")); //$NON-NLS-1$ - edits.add(factory.createEdit(partEndOffset - tokenLength, tokenLength, "")); //$NON-NLS-1$ + edits.add(factory.createEdit(partEndOffset - tokenLength, + tokenLength, "")); //$NON-NLS-1$ } executeEdits(edits); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/SelectionConverter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/SelectionConverter.java index 605980e..dbcb732 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/SelectionConverter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/SelectionConverter.java @@ -32,50 +32,50 @@ import org.eclipse.ui.IWorkbenchPart; public class SelectionConverter { - private static final IJavaElement[] EMPTY_RESULT= new IJavaElement[0]; - + private static final IJavaElement[] EMPTY_RESULT = new IJavaElement[0]; + private SelectionConverter() { // no instance } /** - * Converts the selection provided by the given part into a structured selection. - * The following conversion rules are used: + * Converts the selection provided by the given part into a structured + * selection. The following conversion rules are used: *
                                                        - *
                                                      • part instanceof PHPEditor: returns a structured selection - * using code resolve to convert the editor's text selection.
                                                      • - *
                                                      • part instanceof IWorkbenchPart: returns the part's selection - * if it is a structured selection.
                                                      • + *
                                                      • part instanceof PHPEditor: returns a structured + * selection using code resolve to convert the editor's text selection.
                                                      • + *
                                                      • part instanceof IWorkbenchPart: returns the part's + * selection if it is a structured selection.
                                                      • *
                                                      • default: returns an empty structured selection.
                                                      • *
                                                      */ - public static IStructuredSelection getStructuredSelection(IWorkbenchPart part) throws JavaModelException { + public static IStructuredSelection getStructuredSelection( + IWorkbenchPart part) throws JavaModelException { if (part instanceof PHPEditor) - return new StructuredSelection(codeResolve((PHPEditor)part)); - ISelectionProvider provider= part.getSite().getSelectionProvider(); + return new StructuredSelection(codeResolve((PHPEditor) part)); + ISelectionProvider provider = part.getSite().getSelectionProvider(); if (provider != null) { - ISelection selection= provider.getSelection(); + ISelection selection = provider.getSelection(); if (selection instanceof IStructuredSelection) - return (IStructuredSelection)selection; + return (IStructuredSelection) selection; } return StructuredSelection.EMPTY; } - /** * Converts the given structured selection into an array of Java elements. - * An empty array is returned if one of the elements stored in the structured - * selection is not of tupe IJavaElement + * An empty array is returned if one of the elements stored in the + * structured selection is not of tupe IJavaElement */ public static IJavaElement[] getElements(IStructuredSelection selection) { if (!selection.isEmpty()) { - IJavaElement[] result= new IJavaElement[selection.size()]; - int i= 0; - for (Iterator iter= selection.iterator(); iter.hasNext(); i++) { - Object element= (Object) iter.next(); + IJavaElement[] result = new IJavaElement[selection.size()]; + int i = 0; + for (Iterator iter = selection.iterator(); iter.hasNext(); i++) { + Object element = (Object) iter.next(); if (!(element instanceof IJavaElement)) return EMPTY_RESULT; - result[i]= (IJavaElement)element; + result[i] = (IJavaElement) element; } return result; } @@ -86,151 +86,177 @@ public class SelectionConverter { if (editor == null) return false; return getInput(editor) != null; - + } - + /** * Converts the text selection provided by the given editor into an array of - * Java elements. If the selection doesn't cover a Java element and the selection's - * length is greater than 0 the methods returns the editor's input element. + * Java elements. If the selection doesn't cover a Java element and the + * selection's length is greater than 0 the methods returns the editor's + * input element. */ - public static IJavaElement[] codeResolveOrInput(PHPEditor editor) throws JavaModelException { - IJavaElement input= getInput(editor); - ITextSelection selection= (ITextSelection)editor.getSelectionProvider().getSelection(); - IJavaElement[] result= codeResolve(input, selection); + public static IJavaElement[] codeResolveOrInput(PHPEditor editor) + throws JavaModelException { + IJavaElement input = getInput(editor); + ITextSelection selection = (ITextSelection) editor + .getSelectionProvider().getSelection(); + IJavaElement[] result = codeResolve(input, selection); if (result.length == 0) { - result= new IJavaElement[] {input}; + result = new IJavaElement[] { input }; } return result; } - - public static IJavaElement[] codeResolveOrInputHandled(PHPEditor editor, Shell shell, String title) { + + public static IJavaElement[] codeResolveOrInputHandled(PHPEditor editor, + Shell shell, String title) { try { return codeResolveOrInput(editor); - } catch(JavaModelException e) { - ExceptionHandler.handle(e, shell, title, ActionMessages.getString("SelectionConverter.codeResolve_failed")); //$NON-NLS-1$ + } catch (JavaModelException e) { + ExceptionHandler.handle(e, shell, title, ActionMessages + .getString("SelectionConverter.codeResolve_failed")); //$NON-NLS-1$ } return null; } - + /** - * Converts the text selection provided by the given editor a Java element by - * asking the user if code reolve returned more than one result. If the selection - * doesn't cover a Java element and the selection's length is greater than 0 the - * methods returns the editor's input element. + * Converts the text selection provided by the given editor a Java element + * by asking the user if code reolve returned more than one result. If the + * selection doesn't cover a Java element and the selection's length is + * greater than 0 the methods returns the editor's input element. */ - public static IJavaElement codeResolveOrInput(PHPEditor editor, Shell shell, String title, String message) throws JavaModelException { - IJavaElement[] elements= codeResolveOrInput(editor); + public static IJavaElement codeResolveOrInput(PHPEditor editor, + Shell shell, String title, String message) + throws JavaModelException { + IJavaElement[] elements = codeResolveOrInput(editor); if (elements == null || elements.length == 0) return null; - IJavaElement candidate= elements[0]; + IJavaElement candidate = elements[0]; if (elements.length > 1) { - candidate= OpenActionUtil.selectJavaElement(elements, shell, title, message); + candidate = OpenActionUtil.selectJavaElement(elements, shell, + title, message); } return candidate; } - - public static IJavaElement codeResolveOrInputHandled(PHPEditor editor, Shell shell, String title, String message) { + + public static IJavaElement codeResolveOrInputHandled(PHPEditor editor, + Shell shell, String title, String message) { try { return codeResolveOrInput(editor, shell, title, message); } catch (JavaModelException e) { - ExceptionHandler.handle(e, shell, title, ActionMessages.getString("SelectionConverter.codeResolveOrInput_failed")); //$NON-NLS-1$ + ExceptionHandler.handle(e, shell, title, ActionMessages + .getString("SelectionConverter.codeResolveOrInput_failed")); //$NON-NLS-1$ } return null; } - - public static IJavaElement[] codeResolve(PHPEditor editor) throws JavaModelException { - return codeResolve(getInput(editor), (ITextSelection)editor.getSelectionProvider().getSelection()); + + public static IJavaElement[] codeResolve(PHPEditor editor) + throws JavaModelException { + return codeResolve(getInput(editor), (ITextSelection) editor + .getSelectionProvider().getSelection()); } /** - * Converts the text selection provided by the given editor a Java element by - * asking the user if code reolve returned more than one result. If the selection - * doesn't cover a Java element null is returned. + * Converts the text selection provided by the given editor a Java element + * by asking the user if code reolve returned more than one result. If the + * selection doesn't cover a Java element null is returned. */ - public static IJavaElement codeResolve(PHPEditor editor, Shell shell, String title, String message) throws JavaModelException { - IJavaElement[] elements= codeResolve(editor); + public static IJavaElement codeResolve(PHPEditor editor, Shell shell, + String title, String message) throws JavaModelException { + IJavaElement[] elements = codeResolve(editor); if (elements == null || elements.length == 0) return null; - IJavaElement candidate= elements[0]; + IJavaElement candidate = elements[0]; if (elements.length > 1) { - candidate= OpenActionUtil.selectJavaElement(elements, shell, title, message); + candidate = OpenActionUtil.selectJavaElement(elements, shell, + title, message); } return candidate; } - - public static IJavaElement[] codeResolveHandled(PHPEditor editor, Shell shell, String title) { + + public static IJavaElement[] codeResolveHandled(PHPEditor editor, + Shell shell, String title) { try { return codeResolve(editor); } catch (JavaModelException e) { - ExceptionHandler.handle(e, shell, title, ActionMessages.getString("SelectionConverter.codeResolve_failed")); //$NON-NLS-1$ + ExceptionHandler.handle(e, shell, title, ActionMessages + .getString("SelectionConverter.codeResolve_failed")); //$NON-NLS-1$ } return null; } - - public static IJavaElement getElementAtOffset(PHPEditor editor) throws JavaModelException { - return getElementAtOffset(getInput(editor), (ITextSelection)editor.getSelectionProvider().getSelection()); + + public static IJavaElement getElementAtOffset(PHPEditor editor) + throws JavaModelException { + return getElementAtOffset(getInput(editor), (ITextSelection) editor + .getSelectionProvider().getSelection()); } - - public static IType getTypeAtOffset(PHPEditor editor) throws JavaModelException { - IJavaElement element= SelectionConverter.getElementAtOffset(editor); - IType type= (IType)element.getAncestor(IJavaElement.TYPE); + + public static IType getTypeAtOffset(PHPEditor editor) + throws JavaModelException { + IJavaElement element = SelectionConverter.getElementAtOffset(editor); + IType type = (IType) element.getAncestor(IJavaElement.TYPE); if (type == null) { - ICompilationUnit unit= SelectionConverter.getInputAsCompilationUnit(editor); + ICompilationUnit unit = SelectionConverter + .getInputAsCompilationUnit(editor); if (unit != null) - type= unit.findPrimaryType(); + type = unit.findPrimaryType(); } return type; } - + public static IJavaElement getInput(PHPEditor editor) { if (editor == null) return null; - IEditorInput input= editor.getEditorInput(); -// if (input instanceof IClassFileEditorInput) -// return ((IClassFileEditorInput)input).getClassFile(); - IWorkingCopyManager manager= PHPeclipsePlugin.getDefault().getWorkingCopyManager(); - return manager.getWorkingCopy(input); + IEditorInput input = editor.getEditorInput(); + // if (input instanceof IClassFileEditorInput) + // return ((IClassFileEditorInput)input).getClassFile(); + IWorkingCopyManager manager = PHPeclipsePlugin.getDefault() + .getWorkingCopyManager(); + return manager.getWorkingCopy(input); } - + public static ICompilationUnit getInputAsCompilationUnit(PHPEditor editor) { - Object editorInput= SelectionConverter.getInput(editor); + Object editorInput = SelectionConverter.getInput(editor); if (editorInput instanceof ICompilationUnit) - return (ICompilationUnit)editorInput; + return (ICompilationUnit) editorInput; else return null; } - private static IJavaElement[] codeResolve(IJavaElement input, ITextSelection selection) throws JavaModelException { -// if (input instanceof ICodeAssist) { -// IJavaElement[] elements= ((ICodeAssist)input).codeSelect(selection.getOffset(), selection.getLength()); -// if (elements != null && elements.length > 0) -// return elements; -// } - return EMPTY_RESULT; + private static IJavaElement[] codeResolve(IJavaElement input, + ITextSelection selection) throws JavaModelException { + // if (input instanceof ICodeAssist) { + // IJavaElement[] elements= + // ((ICodeAssist)input).codeSelect(selection.getOffset(), + // selection.getLength()); + // if (elements != null && elements.length > 0) + // return elements; + // } + return EMPTY_RESULT; } - - private static IJavaElement getElementAtOffset(IJavaElement input, ITextSelection selection) throws JavaModelException { + + private static IJavaElement getElementAtOffset(IJavaElement input, + ITextSelection selection) throws JavaModelException { if (input instanceof ICompilationUnit) { - ICompilationUnit cunit= (ICompilationUnit)input; + ICompilationUnit cunit = (ICompilationUnit) input; if (cunit.isWorkingCopy()) { synchronized (cunit) { cunit.reconcile(); } } - IJavaElement ref= cunit.getElementAt(selection.getOffset()); + IJavaElement ref = cunit.getElementAt(selection.getOffset()); if (ref == null) return input; else return ref; - } -// else if (input instanceof IClassFile) { -// IJavaElement ref= ((IClassFile)input).getElementAt(selection.getOffset()); -// if (ref == null) -// return input; -// else -// return ref; -// } + } + // else if (input instanceof IClassFile) { + // IJavaElement ref= + // ((IClassFile)input).getElementAt(selection.getOffset()); + // if (ref == null) + // return input; + // else + // return ref; + // } return null; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/SelectionDispatchAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/SelectionDispatchAction.java index e43d264..6f71be1 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/SelectionDispatchAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/SelectionDispatchAction.java @@ -22,18 +22,19 @@ import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IWorkbenchSite; /** - * Action that dispatches the IAction#run() and the - * ISelectionChangedListener#selectionChanged - * according to the type of the selection. + * Action that dispatches the IAction#run() and the + * ISelectionChangedListener#selectionChanged according to the + * type of the selection. * *
                                                        - *
                                                      • if selection is of type ITextSelection then - * run(ITextSelection) and selectionChanged(ITextSelection) - * is called.
                                                      • - *
                                                      • if selection is of type IStructuredSelection then - * run(IStructuredSelection) and - * selectionChanged(IStructuredSelection) is called.
                                                      • - *
                                                      • default is to call run(ISelection) and + *
                                                      • if selection is of type ITextSelection then + * run(ITextSelection) and + * selectionChanged(ITextSelection) is called.
                                                      • + *
                                                      • if selection is of type IStructuredSelection then + * run(IStructuredSelection) and + * selectionChanged(IStructuredSelection) + * is called.
                                                      • + *
                                                      • default is to call run(ISelection) and * selectionChanged(ISelection).
                                                      • *
                                                      * @@ -43,21 +44,23 @@ import org.eclipse.ui.IWorkbenchSite; * * @since 2.0 */ -public abstract class SelectionDispatchAction extends Action implements ISelectionChangedListener { - +public abstract class SelectionDispatchAction extends Action implements + ISelectionChangedListener { + private IWorkbenchSite fSite; - + /** * Creates a new action with no text and no image. *

                                                      * Configure the action later using the set methods. *

                                                      * - * @param site the site this action is working on + * @param site + * the site this action is working on */ protected SelectionDispatchAction(IWorkbenchSite site) { Assert.isNotNull(site); - fSite= site; + fSite = site; } /** @@ -73,7 +76,7 @@ public abstract class SelectionDispatchAction extends Action implements ISelecti * Returns the selection provided by the site owning this action. * * @return the site's selection - */ + */ public ISelection getSelection() { return getSelectionProvider().getSelection(); } @@ -81,94 +84,101 @@ public abstract class SelectionDispatchAction extends Action implements ISelecti /** * Returns the shell provided by the site owning this action. * - * @return the site's shell + * @return the site's shell */ - public Shell getShell() { + public Shell getShell() { return fSite.getShell(); } - + /** * Returns the selection provider managed by the site owning this action. * - * @return the site's selection provider + * @return the site's selection provider */ public ISelectionProvider getSelectionProvider() { return fSite.getSelectionProvider(); } /** - * Updates the action's enablement state according to the given selection. This - * default implementation calls one of the selectionChanged - * methods depending on the type of the passed selection. + * Updates the action's enablement state according to the given selection. + * This default implementation calls one of the + * selectionChanged methods depending on the type of the + * passed selection. * - * @param selection the selection this action is working on + * @param selection + * the selection this action is working on */ public void update(ISelection selection) { dispatchSelectionChanged(selection); } /** - * Notifies this action that the given structured selection has changed. This default - * implementation calls selectionChanged(ISelection selection). + * Notifies this action that the given structured selection has changed. + * This default implementation calls + * selectionChanged(ISelection selection). * - * @param selection the new selection - */ + * @param selection + * the new selection + */ protected void selectionChanged(IStructuredSelection selection) { - selectionChanged((ISelection)selection); + selectionChanged((ISelection) selection); } /** - * Executes this actions with the given structured selection. This default implementation - * calls run(ISelection selection). + * Executes this actions with the given structured selection. This default + * implementation calls run(ISelection selection). */ protected void run(IStructuredSelection selection) { - run((ISelection)selection); + run((ISelection) selection); } - + /** - * Notifies this action that the given text selection has changed. This default - * implementation calls selectionChanged(ISelection selection). + * Notifies this action that the given text selection has changed. This + * default implementation calls + * selectionChanged(ISelection selection). * - * @param selection the new selection - */ + * @param selection + * the new selection + */ protected void selectionChanged(ITextSelection selection) { - selectionChanged((ISelection)selection); + selectionChanged((ISelection) selection); } - + /** - * Executes this actions with the given text selection. This default implementation - * calls run(ISelection selection). + * Executes this actions with the given text selection. This default + * implementation calls run(ISelection selection). */ protected void run(ITextSelection selection) { - run((ISelection)selection); + run((ISelection) selection); } - + /** - * Notifies this action that the given selection has changed. This default + * Notifies this action that the given selection has changed. This default * implementation sets the action's enablement state to false. * - * @param selection the new selection - */ + * @param selection + * the new selection + */ protected void selectionChanged(ISelection selection) { setEnabled(false); } - + /** - * Executes this actions with the given selection. This default implementation - * does nothing. + * Executes this actions with the given selection. This default + * implementation does nothing. */ protected void run(ISelection selection) { } - /* (non-Javadoc) - * Method declared on IAction. + /* + * (non-Javadoc) Method declared on IAction. */ public void run() { dispatchRun(getSelection()); } - - /* (non-Javadoc) - * Method declared on ISelectionChangedListener. + + /* + * (non-Javadoc) Method declared on ISelectionChangedListener. */ public void selectionChanged(SelectionChangedEvent event) { dispatchSelectionChanged(event.getSelection()); @@ -176,9 +186,9 @@ public abstract class SelectionDispatchAction extends Action implements ISelecti private void dispatchSelectionChanged(ISelection selection) { if (selection instanceof IStructuredSelection) { - selectionChanged((IStructuredSelection)selection); + selectionChanged((IStructuredSelection) selection); } else if (selection instanceof ITextSelection) { - selectionChanged((ITextSelection)selection); + selectionChanged((ITextSelection) selection); } else { selectionChanged(selection); } @@ -186,9 +196,9 @@ public abstract class SelectionDispatchAction extends Action implements ISelecti private void dispatchRun(ISelection selection) { if (selection instanceof IStructuredSelection) { - run((IStructuredSelection)selection); + run((IStructuredSelection) selection); } else if (selection instanceof ITextSelection) { - run((ITextSelection)selection); + run((ITextSelection) selection); } else { run(selection); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/WorkbenchRunnableAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/WorkbenchRunnableAdapter.java index bd68861..88a0d3e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/WorkbenchRunnableAdapter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/WorkbenchRunnableAdapter.java @@ -20,24 +20,26 @@ import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.jface.operation.IRunnableWithProgress; - /** - * An IRunnableWithProgress that adapts and IWorkspaceRunnable - * so that is can be executed inside IRunnableContext. OperationCanceledException - * thrown by the apapted runnabled are cought and rethrown as a InterruptedException. + * An IRunnableWithProgress that adapts and + * IWorkspaceRunnable so that is can be executed inside + * IRunnableContext. OperationCanceledException + * thrown by the apapted runnabled are cought and rethrown as a + * InterruptedException. */ public class WorkbenchRunnableAdapter implements IRunnableWithProgress { - + private IWorkspaceRunnable fWorkspaceRunnable; - + public WorkbenchRunnableAdapter(IWorkspaceRunnable runnable) { - fWorkspaceRunnable= runnable; + fWorkspaceRunnable = runnable; } /* * @see IRunnableWithProgress#run(IProgressMonitor) */ - public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { + public void run(IProgressMonitor monitor) throws InvocationTargetException, + InterruptedException { try { PHPeclipsePlugin.run(fWorkspaceRunnable, monitor); } catch (OperationCanceledException e) { @@ -48,4 +50,3 @@ public class WorkbenchRunnableAdapter implements IRunnableWithProgress { } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/AbstractElementListSelectionDialog.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/AbstractElementListSelectionDialog.java index ecc06af..103f5e5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/AbstractElementListSelectionDialog.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/AbstractElementListSelectionDialog.java @@ -23,129 +23,152 @@ import org.eclipse.swt.widgets.Text; /** * An abstract class to select elements out of a list of elements. */ -public abstract class AbstractElementListSelectionDialog extends SelectionStatusDialog { - +public abstract class AbstractElementListSelectionDialog extends + SelectionStatusDialog { + private ILabelProvider fRenderer; - private boolean fIgnoreCase= true; - private boolean fIsMultipleSelection= false; - private boolean fMatchEmptyString= true; - private boolean fAllowDuplicates= true; - + + private boolean fIgnoreCase = true; + + private boolean fIsMultipleSelection = false; + + private boolean fMatchEmptyString = true; + + private boolean fAllowDuplicates = true; + private Label fMessage; protected FilteredList fFilteredList; + private Text fFilterText; - - private ISelectionValidator fValidator; - private String fFilter= null; - - private String fEmptyListMessage= ""; //$NON-NLS-1$ - private String fEmptySelectionMessage= ""; //$NON-NLS-1$ - - private int fWidth= 60; - private int fHeight= 18; - - private Object[] fSelection= new Object[0]; - + + private ISelectionValidator fValidator; + + private String fFilter = null; + + private String fEmptyListMessage = ""; //$NON-NLS-1$ + + private String fEmptySelectionMessage = ""; //$NON-NLS-1$ + + private int fWidth = 60; + + private int fHeight = 18; + + private Object[] fSelection = new Object[0]; + /** * Constructs a list selection dialog. - * @param renderer The label renderer used - * @param ignoreCase Decides if the match string ignores lower/upppr case - * @param multipleSelection Allow multiple selection + * + * @param renderer + * The label renderer used + * @param ignoreCase + * Decides if the match string ignores lower/upppr case + * @param multipleSelection + * Allow multiple selection */ - protected AbstractElementListSelectionDialog(Shell parent, ILabelProvider renderer) - { - super(parent); - fRenderer= renderer; - - int shellStyle= getShellStyle(); + protected AbstractElementListSelectionDialog(Shell parent, + ILabelProvider renderer) { + super(parent); + fRenderer = renderer; + + int shellStyle = getShellStyle(); setShellStyle(shellStyle | SWT.MAX | SWT.RESIZE); } /** - * Handles default selection (double click). - * By default, the OK button is pressed. - */ + * Handles default selection (double click). By default, the OK button is + * pressed. + */ protected void handleDefaultSelected() { if (validateCurrentSelection()) buttonPressed(IDialogConstants.OK_ID); } - + /** * Specifies if sorting, filtering and folding is case sensitive. */ public void setIgnoreCase(boolean ignoreCase) { - fIgnoreCase= ignoreCase; + fIgnoreCase = ignoreCase; } - + /** * Returns if sorting, filtering and folding is case sensitive. */ public boolean isCaseIgnored() { return fIgnoreCase; } - + /** - * Specifies whether everything or nothing should be filtered on - * empty filter string. + * Specifies whether everything or nothing should be filtered on empty + * filter string. */ public void setMatchEmptyString(boolean matchEmptyString) { - fMatchEmptyString= matchEmptyString; + fMatchEmptyString = matchEmptyString; } - + /** * Specifies if multiple selection is allowed. */ public void setMultipleSelection(boolean multipleSelection) { - fIsMultipleSelection= multipleSelection; + fIsMultipleSelection = multipleSelection; } /** * Specifies whether duplicate entries are displayed or not. */ public void setAllowDuplicates(boolean allowDuplicates) { - fAllowDuplicates= allowDuplicates; + fAllowDuplicates = allowDuplicates; } - + /** * Sets the list size in unit of characters. - * @param width the width of the list. - * @param height the height of the list. + * + * @param width + * the width of the list. + * @param height + * the height of the list. */ public void setSize(int width, int height) { - fWidth= width; - fHeight= height; + fWidth = width; + fHeight = height; } - + /** * Sets the message to be displayed if the list is empty. - * @param message the message to be displayed. + * + * @param message + * the message to be displayed. */ public void setEmptyListMessage(String message) { - fEmptyListMessage= message; + fEmptyListMessage = message; } /** * Sets the message to be displayed if the selection is empty. - * @param message the message to be displayed. + * + * @param message + * the message to be displayed. */ public void setEmptySelectionMessage(String message) { - fEmptySelectionMessage= message; + fEmptySelectionMessage = message; } - + /** - * Sets an optional validator to check if the selection is valid. - * The validator is invoked whenever the selection changes. - * @param validator the validator to validate the selection. + * Sets an optional validator to check if the selection is valid. The + * validator is invoked whenever the selection changes. + * + * @param validator + * the validator to validate the selection. */ public void setValidator(ISelectionValidator validator) { - fValidator= validator; - } - + fValidator = validator; + } + /** - * Sets the elements of the list (widget). - * To be called within open(). - * @param elements the elements of the list. + * Sets the elements of the list (widget). To be called within open(). + * + * @param elements + * the elements of the list. */ protected void setListElements(Object[] elements) { Assert.isNotNull(fFilteredList); @@ -154,18 +177,22 @@ public abstract class AbstractElementListSelectionDialog extends SelectionStatus /** * Sets the filter pattern. - * @param filter the filter pattern. + * + * @param filter + * the filter pattern. */ public void setFilter(String filter) { if (fFilterText == null) - fFilter= filter; + fFilter = filter; else fFilterText.setText(filter); - } - + } + /** * Returns the current filter pattern. - * @return returns the current filter pattern or null if filter was not set. + * + * @return returns the current filter pattern or + * null if filter was not set. */ public String getFilter() { if (fFilteredList == null) @@ -175,8 +202,9 @@ public abstract class AbstractElementListSelectionDialog extends SelectionStatus } /** - * Returns the indices referring the current selection. - * To be called within open(). + * Returns the indices referring the current selection. To be called within + * open(). + * * @return returns the indices of the current selection. */ protected int[] getSelectionIndices() { @@ -185,30 +213,34 @@ public abstract class AbstractElementListSelectionDialog extends SelectionStatus } /** - * Returns an index referring the first current selection. - * To be called within open(). + * Returns an index referring the first current selection. To be called + * within open(). + * * @return returns the indices of the current selection. */ protected int getSelectionIndex() { Assert.isNotNull(fFilteredList); return fFilteredList.getSelectionIndex(); } - + /** - * Sets the selection referenced by an array of elements. - * To be called within open(). - * @param selection the indices of the selection. + * Sets the selection referenced by an array of elements. To be called + * within open(). + * + * @param selection + * the indices of the selection. */ protected void setSelection(Object[] selection) { Assert.isNotNull(fFilteredList); fFilteredList.setSelection(selection); } - + /** - * Returns an array of the currently selected elements. - * To be called within or after open(). + * Returns an array of the currently selected elements. To be called within + * or after open(). + * * @return returns an array of the currently selected elements. - */ + */ protected Object[] getSelectedElements() { Assert.isNotNull(fFilteredList); return fFilteredList.getSelection(); @@ -216,67 +248,70 @@ public abstract class AbstractElementListSelectionDialog extends SelectionStatus /** * Returns all elements which are folded together to one entry in the list. - * @param index the index selecting the entry in the list. + * + * @param index + * the index selecting the entry in the list. * @return returns an array of elements folded together. */ public Object[] getFoldedElements(int index) { Assert.isNotNull(fFilteredList); return fFilteredList.getFoldedElements(index); } - + /** * Creates the message text widget and sets layout data. - * @param composite the parent composite of the message area. + * + * @param composite + * the parent composite of the message area. */ protected Label createMessageArea(Composite composite) { - Label label= super.createMessageArea(composite); + Label label = super.createMessageArea(composite); - GridData data= new GridData(); - data.grabExcessVerticalSpace= false; - data.grabExcessHorizontalSpace= true; - data.horizontalAlignment= GridData.FILL; - data.verticalAlignment= GridData.BEGINNING; + GridData data = new GridData(); + data.grabExcessVerticalSpace = false; + data.grabExcessHorizontalSpace = true; + data.horizontalAlignment = GridData.FILL; + data.verticalAlignment = GridData.BEGINNING; label.setLayoutData(data); - - fMessage= label; - + + fMessage = label; + return label; - } + } /** - * Handles a selection changed event. - * By default, the current selection is validated. + * Handles a selection changed event. By default, the current selection is + * validated. */ protected void handleSelectionChanged() { validateCurrentSelection(); } - + /** - * Validates the current selection and updates the status line - * accordingly. + * Validates the current selection and updates the status line accordingly. */ protected boolean validateCurrentSelection() { Assert.isNotNull(fFilteredList); IStatus status; - Object[] elements= getSelectedElements(); + Object[] elements = getSelectedElements(); if (elements.length > 0) { if (fValidator != null) { - status= fValidator.validate(elements); + status = fValidator.validate(elements); } else { - status= new StatusInfo(); + status = new StatusInfo(); } - } else { + } else { if (fFilteredList.isEmpty()) { - status= new StatusInfo(IStatus.ERROR, fEmptyListMessage); + status = new StatusInfo(IStatus.ERROR, fEmptyListMessage); } else { - status= new StatusInfo(IStatus.ERROR, fEmptySelectionMessage); + status = new StatusInfo(IStatus.ERROR, fEmptySelectionMessage); } } updateStatus(status); - + return status.isOK(); } @@ -286,80 +321,83 @@ public abstract class AbstractElementListSelectionDialog extends SelectionStatus protected void cancelPressed() { setResult(null); super.cancelPressed(); - } + } /** * Creates a filtered list. - * @param parent the parent composite. + * + * @param parent + * the parent composite. * @return returns the filtered list widget. */ protected FilteredList createFilteredList(Composite parent) { - int flags= SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | - (fIsMultipleSelection ? SWT.MULTI : SWT.SINGLE); - - FilteredList list= new FilteredList(parent, flags, fRenderer, - fIgnoreCase, fAllowDuplicates, fMatchEmptyString); - - GridData data= new GridData(); - data.widthHint= convertWidthInCharsToPixels(fWidth); - data.heightHint= convertHeightInCharsToPixels(fHeight); - data.grabExcessVerticalSpace= true; - data.grabExcessHorizontalSpace= true; - data.horizontalAlignment= GridData.FILL; - data.verticalAlignment= GridData.FILL; + int flags = SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL + | (fIsMultipleSelection ? SWT.MULTI : SWT.SINGLE); + + FilteredList list = new FilteredList(parent, flags, fRenderer, + fIgnoreCase, fAllowDuplicates, fMatchEmptyString); + + GridData data = new GridData(); + data.widthHint = convertWidthInCharsToPixels(fWidth); + data.heightHint = convertHeightInCharsToPixels(fHeight); + data.grabExcessVerticalSpace = true; + data.grabExcessHorizontalSpace = true; + data.horizontalAlignment = GridData.FILL; + data.verticalAlignment = GridData.FILL; list.setLayoutData(data); - + list.setFilter((fFilter == null ? "" : fFilter)); //$NON-NLS-1$ list.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { handleDefaultSelected(); } + public void widgetSelected(SelectionEvent e) { handleWidgetSelected(); } }); - fFilteredList= list; + fFilteredList = list; - return list; + return list; } - // 3515 + // 3515 private void handleWidgetSelected() { - Object[] newSelection= fFilteredList.getSelection(); - + Object[] newSelection = fFilteredList.getSelection(); + if (newSelection.length != fSelection.length) { - fSelection= newSelection; + fSelection = newSelection; handleSelectionChanged(); } else { - for (int i= 0; i != newSelection.length; i++) { + for (int i = 0; i != newSelection.length; i++) { if (!newSelection[i].equals(fSelection[i])) { - fSelection= newSelection; + fSelection = newSelection; handleSelectionChanged(); break; } } - } + } } protected Text createFilterText(Composite parent) { - Text text= new Text(parent, SWT.BORDER); + Text text = new Text(parent, SWT.BORDER); - GridData data= new GridData(); - data.grabExcessVerticalSpace= false; - data.grabExcessHorizontalSpace= true; - data.horizontalAlignment= GridData.FILL; - data.verticalAlignment= GridData.BEGINNING; + GridData data = new GridData(); + data.grabExcessVerticalSpace = false; + data.grabExcessHorizontalSpace = true; + data.horizontalAlignment = GridData.FILL; + data.verticalAlignment = GridData.BEGINNING; text.setLayoutData(data); text.setText((fFilter == null ? "" : fFilter)); //$NON-NLS-1$ - - Listener listener= new Listener() { + + Listener listener = new Listener() { public void handleEvent(Event e) { fFilteredList.setFilter(fFilterText.getText()); } - }; + }; text.addListener(SWT.Modify, listener); text.addKeyListener(new KeyListener() { @@ -367,12 +405,13 @@ public abstract class AbstractElementListSelectionDialog extends SelectionStatus if (e.keyCode == SWT.ARROW_DOWN) fFilteredList.setFocus(); } - - public void keyReleased(KeyEvent e) {} + + public void keyReleased(KeyEvent e) { + } }); - fFilterText= text; - + fFilterText = text; + return text; } @@ -387,11 +426,11 @@ public abstract class AbstractElementListSelectionDialog extends SelectionStatus }); return getReturnCode(); } - + private void access$superOpen() { super.open(); - } - + } + /* * @see Window#create(Shell) */ @@ -400,22 +439,22 @@ public abstract class AbstractElementListSelectionDialog extends SelectionStatus Assert.isNotNull(fFilteredList); - if (fFilteredList.isEmpty()) { - handleEmptyList(); - } else { - validateCurrentSelection(); + if (fFilteredList.isEmpty()) { + handleEmptyList(); + } else { + validateCurrentSelection(); fFilterText.selectAll(); fFilterText.setFocus(); - } + } } - + /** * Handles empty list by disabling widgets. */ protected void handleEmptyList() { - fMessage.setEnabled(false); - fFilterText.setEnabled(false); - fFilteredList.setEnabled(false); + fMessage.setEnabled(false); + fFilterText.setEnabled(false); + fFilteredList.setEnabled(false); } - + } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/CheckedTreeSelectionDialog.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/CheckedTreeSelectionDialog.java index 08dc378..deb47fc 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/CheckedTreeSelectionDialog.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/CheckedTreeSelectionDialog.java @@ -37,29 +37,41 @@ public class CheckedTreeSelectionDialog extends SelectionStatusDialog { private CheckboxTreeViewer fViewer; private ILabelProvider fLabelProvider; + private ITreeContentProvider fContentProvider; private ISelectionValidator fValidator = null; + private ViewerSorter fSorter; + private String fEmptyListMessage = "No entries available"; private IStatus fCurrStatus = new StatusInfo(); + private List fFilters; + private Object fInput; + private boolean fIsEmpty; private int fWidth = 60; + private int fHeight = 18; private boolean fContainerMode; + private Object[] fExpandedElements; /** * Constructs an instance of ElementTreeSelectionDialog. - * @param labelProvider the label provider to render the entries - * @param contentProvider the content provider to evaluate the tree structure + * + * @param labelProvider + * the label provider to render the entries + * @param contentProvider + * the content provider to evaluate the tree structure */ - public CheckedTreeSelectionDialog(Shell parent, ILabelProvider labelProvider, ITreeContentProvider contentProvider) { + public CheckedTreeSelectionDialog(Shell parent, + ILabelProvider labelProvider, ITreeContentProvider contentProvider) { super(parent); fLabelProvider = labelProvider; @@ -76,18 +88,21 @@ public class CheckedTreeSelectionDialog extends SelectionStatusDialog { } /** - * If set, the checked /gray state of containers (inner nodes) is derived from the checked state of its - * leaf nodes. - * @param containerMode The containerMode to set + * If set, the checked /gray state of containers (inner nodes) is derived + * from the checked state of its leaf nodes. + * + * @param containerMode + * The containerMode to set */ public void setContainerMode(boolean containerMode) { fContainerMode = containerMode; } /** - * Sets the initial selection. - * Convenience method. - * @param selection the initial selection. + * Sets the initial selection. Convenience method. + * + * @param selection + * the initial selection. */ public void setInitialSelection(Object selection) { setInitialSelections(new Object[] { selection }); @@ -95,7 +110,9 @@ public class CheckedTreeSelectionDialog extends SelectionStatusDialog { /** * Sets the message to be displayed if the list is empty. - * @param message the message to be displayed. + * + * @param message + * the message to be displayed. */ public void setEmptyListMessage(String message) { fEmptyListMessage = message; @@ -110,7 +127,9 @@ public class CheckedTreeSelectionDialog extends SelectionStatusDialog { /** * Adds a filter to the tree viewer. - * @param filter a filter. + * + * @param filter + * a filter. */ public void addFilter(ViewerFilter filter) { if (fFilters == null) @@ -120,9 +139,11 @@ public class CheckedTreeSelectionDialog extends SelectionStatusDialog { } /** - * Sets an optional validator to check if the selection is valid. - * The validator is invoked whenever the selection changes. - * @param validator the validator to validate the selection. + * Sets an optional validator to check if the selection is valid. The + * validator is invoked whenever the selection changes. + * + * @param validator + * the validator to validate the selection. */ public void setValidator(ISelectionValidator validator) { fValidator = validator; @@ -130,7 +151,9 @@ public class CheckedTreeSelectionDialog extends SelectionStatusDialog { /** * Sets the tree input. - * @param input the tree input. + * + * @param input + * the tree input. */ public void setInput(Object input) { fInput = input; @@ -145,8 +168,11 @@ public class CheckedTreeSelectionDialog extends SelectionStatusDialog { /** * Sets the size of the tree in unit of characters. - * @param width the width of the tree. - * @param height the height of the tree. + * + * @param width + * the width of the tree. + * @param height + * the height of the tree. */ public void setSize(int width, int height) { fWidth = width; @@ -270,7 +296,9 @@ public class CheckedTreeSelectionDialog extends SelectionStatusDialog { /** * Add the selection and deselection buttons to the dialog. - * @param composite org.eclipse.swt.widgets.Composite + * + * @param composite + * org.eclipse.swt.widgets.Composite */ private Composite createSelectionButtons(Composite composite) { @@ -278,21 +306,26 @@ public class CheckedTreeSelectionDialog extends SelectionStatusDialog { GridLayout layout = new GridLayout(); layout.numColumns = 2; buttonComposite.setLayout(layout); - GridData data = new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.GRAB_HORIZONTAL); + GridData data = new GridData(GridData.HORIZONTAL_ALIGN_END + | GridData.GRAB_HORIZONTAL); data.grabExcessHorizontalSpace = true; composite.setData(data); - Button selectButton = createButton(buttonComposite, IDialogConstants.SELECT_ALL_ID, "Select &All", false); + Button selectButton = createButton(buttonComposite, + IDialogConstants.SELECT_ALL_ID, "Select &All", false); SelectionListener listener = new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { - fViewer.setCheckedElements(fContentProvider.getElements(fInput)); + fViewer + .setCheckedElements(fContentProvider + .getElements(fInput)); updateOKStatus(); } }; selectButton.addSelectionListener(listener); - Button deselectButton = createButton(buttonComposite, IDialogConstants.DESELECT_ALL_ID, "&Deselect All", false); + Button deselectButton = createButton(buttonComposite, + IDialogConstants.DESELECT_ALL_ID, "&Deselect All", false); listener = new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/ElementListSelectionDialog.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/ElementListSelectionDialog.java index cee2d5c..e8588c5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/ElementListSelectionDialog.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/ElementListSelectionDialog.java @@ -11,25 +11,31 @@ import org.eclipse.swt.widgets.Shell; /** * A class to select elements out of a list of elements. */ -public class ElementListSelectionDialog extends AbstractElementListSelectionDialog { +public class ElementListSelectionDialog extends + AbstractElementListSelectionDialog { private Object[] fElements; /** * Creates a list selection dialog. - * @param parent the parent widget. - * @param renderer the label renderer. + * + * @param parent + * the parent widget. + * @param renderer + * the label renderer. */ - public ElementListSelectionDialog(Shell parent, ILabelProvider renderer) { + public ElementListSelectionDialog(Shell parent, ILabelProvider renderer) { super(parent, renderer); } /** * Sets the elements of the list. - * @param elements the elements of the list. + * + * @param elements + * the elements of the list. */ public void setElements(Object[] elements) { - fElements= elements; + fElements = elements; } /* @@ -43,7 +49,7 @@ public class ElementListSelectionDialog extends AbstractElementListSelectionDial * @see Dialog#createDialogArea(Composite) */ protected Control createDialogArea(Composite parent) { - Composite contents= (Composite) super.createDialogArea(parent); + Composite contents = (Composite) super.createDialogArea(parent); createMessageArea(contents); createFilterText(contents); @@ -51,7 +57,7 @@ public class ElementListSelectionDialog extends AbstractElementListSelectionDial setListElements(fElements); - List initialSelections= getInitialElementSelections(); + List initialSelections = getInitialElementSelections(); if (initialSelections != null) setSelection(initialSelections.toArray()); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/MessageLine.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/MessageLine.java index 71577cf..dc9ac8d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/MessageLine.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/MessageLine.java @@ -14,10 +14,11 @@ import org.eclipse.swt.widgets.Composite; * A message line displaying a status. */ public class MessageLine extends CLabel { - + private static final RGB ERROR_BACKGROUND_RGB = new RGB(230, 226, 221); - + private Color fNormalMsgAreaBackground; + private Color fErrorMsgAreaBackground; /** @@ -28,15 +29,15 @@ public class MessageLine extends CLabel { } /** - * Creates a new message line as a child of the parent and with the given SWT stylebits. + * Creates a new message line as a child of the parent and with the given + * SWT stylebits. */ public MessageLine(Composite parent, int style) { super(parent, style); - fNormalMsgAreaBackground= getBackground(); - fErrorMsgAreaBackground= null; + fNormalMsgAreaBackground = getBackground(); + fErrorMsgAreaBackground = null; } - private Image findImage(IStatus status) { if (status.isOK()) { return null; @@ -51,34 +52,35 @@ public class MessageLine extends CLabel { } /** - * Sets the message and image to the given status. - * null is a valid argument and will set the empty text and no image + * Sets the message and image to the given status. null is a + * valid argument and will set the empty text and no image */ public void setErrorStatus(IStatus status) { if (status != null) { - String message= status.getMessage(); + String message = status.getMessage(); if (message != null && message.length() > 0) { setText(message); setImage(findImage(status)); if (fErrorMsgAreaBackground == null) { - fErrorMsgAreaBackground= new Color(getDisplay(), ERROR_BACKGROUND_RGB); + fErrorMsgAreaBackground = new Color(getDisplay(), + ERROR_BACKGROUND_RGB); } setBackground(fErrorMsgAreaBackground); return; } - } + } setText(""); setImage(null); - setBackground(fNormalMsgAreaBackground); + setBackground(fNormalMsgAreaBackground); } - + /* * @see Widget#dispose() */ public void dispose() { if (fErrorMsgAreaBackground != null) { fErrorMsgAreaBackground.dispose(); - fErrorMsgAreaBackground= null; + fErrorMsgAreaBackground = null; } super.dispose(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/SelectionStatusDialog.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/SelectionStatusDialog.java index 2e27822..eb6514f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/SelectionStatusDialog.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/SelectionStatusDialog.java @@ -13,66 +13,71 @@ import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.dialogs.SelectionDialog; - /** * An abstract base class for dialogs with a status bar and ok/cancel buttons. - * The status message must be passed over as StatusInfo object and can be - * an error, warning or ok. The OK button is enabled or disabled depending - * on the status. - */ -public abstract class SelectionStatusDialog extends SelectionDialog { - + * The status message must be passed over as StatusInfo object and can be an + * error, warning or ok. The OK button is enabled or disabled depending on the + * status. + */ +public abstract class SelectionStatusDialog extends SelectionDialog { + private MessageLine fStatusLine; + private IStatus fLastStatus; + private Image fImage; - private boolean fStatusLineAboveButtons= false; + + private boolean fStatusLineAboveButtons = false; /** * Creates an instance of a SelectionStatusDialog. - */ + */ public SelectionStatusDialog(Shell parent) { super(parent); } - + /** * Controls whether status line appears to the left of the buttons (default) * or above them. - * - * @param aboveButtons if true status line is placed above buttons; if - * false to the right + * + * @param aboveButtons + * if true status line is placed above buttons; if + * false to the right */ public void setStatusLineAboveButtons(boolean aboveButtons) { - fStatusLineAboveButtons= aboveButtons; + fStatusLineAboveButtons = aboveButtons; } - + /** * Sets the image for this dialog. - * @param image the image. + * + * @param image + * the image. */ public void setImage(Image image) { - fImage= image; + fImage = image; } - + /** - * Returns the first element from the list of results. Returns null - * if no element has been selected. - * - * @return the first result element if one exists. Otherwise null is - * returned. - */ + * Returns the first element from the list of results. Returns + * null if no element has been selected. + * + * @return the first result element if one exists. Otherwise + * null is returned. + */ public Object getFirstResult() { - Object[] result= getResult(); + Object[] result = getResult(); if (result == null || result.length == 0) return null; - return result[0]; + return result[0]; } - + /** * Sets a result element at the given position. */ protected void setResult(int position, Object element) { - Object[] result= getResult(); - result[position]= element; + Object[] result = getResult(); + result[position] = element; setResult(Arrays.asList(result)); } @@ -80,35 +85,35 @@ public abstract class SelectionStatusDialog extends SelectionDialog { * Compute the result and return it. */ protected abstract void computeResult(); - + protected void configureShell(Shell shell) { super.configureShell(shell); if (fImage != null) shell.setImage(fImage); } - + /** - * Update the dialog's status line to reflect the given status. It is safe to call - * this method before the dialog has been opened. + * Update the dialog's status line to reflect the given status. It is safe + * to call this method before the dialog has been opened. */ protected void updateStatus(IStatus status) { - fLastStatus= status; + fLastStatus = status; if (fStatusLine != null && !fStatusLine.isDisposed()) { - updateButtonsEnableState(status); - fStatusLine.setErrorStatus(status); + updateButtonsEnableState(status); + fStatusLine.setErrorStatus(status); } - } + } /** - * Update the status of the ok button to reflect the given status. Subclasses - * may override this method to update additional buttons. + * Update the status of the ok button to reflect the given status. + * Subclasses may override this method to update additional buttons. */ protected void updateButtonsEnableState(IStatus status) { - Button okButton= getOkButton(); + Button okButton = getOkButton(); if (okButton != null && !okButton.isDisposed()) okButton.setEnabled(!status.matches(IStatus.ERROR)); } - + protected void okPressed() { computeResult(); super.okPressed(); @@ -121,28 +126,29 @@ public abstract class SelectionStatusDialog extends SelectionDialog { } protected Control createButtonBar(Composite parent) { - Composite composite= new Composite(parent, SWT.NULL); - GridLayout layout= new GridLayout(); + Composite composite = new Composite(parent, SWT.NULL); + GridLayout layout = new GridLayout(); if (fStatusLineAboveButtons) { - layout.marginWidth= 5; + layout.marginWidth = 5; } else { - layout.numColumns= 2; + layout.numColumns = 2; } - layout.marginHeight= 0; layout.marginWidth= 0; + layout.marginHeight = 0; + layout.marginWidth = 0; composite.setLayout(layout); composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - - fStatusLine= new MessageLine(composite); + + fStatusLine = new MessageLine(composite); fStatusLine.setAlignment(SWT.LEFT); fStatusLine.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fStatusLine.setErrorStatus(null); - - GridData gd= new GridData(GridData.FILL_HORIZONTAL); - gd.horizontalIndent= convertWidthInCharsToPixels(1); + + GridData gd = new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalIndent = convertWidthInCharsToPixels(1); fStatusLine.setLayoutData(gd); - + super.createButtonBar(composite); return composite; } - + } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/StatusDialog.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/StatusDialog.java index a8a90ea..b58b7fb 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/StatusDialog.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/StatusDialog.java @@ -14,51 +14,56 @@ import org.eclipse.swt.widgets.Shell; /** * An abstract base class for dialogs with a status bar and ok/cancel buttons. - * The status message must be passed over as StatusInfo object and can be - * an error, warning or ok. The OK button is enabled or disabled depending - * on the status. - */ -public abstract class StatusDialog extends Dialog { - + * The status message must be passed over as StatusInfo object and can be an + * error, warning or ok. The OK button is enabled or disabled depending on the + * status. + */ +public abstract class StatusDialog extends Dialog { + private Button fOkButton; + private MessageLine fStatusLine; + private IStatus fLastStatus; + private String fTitle; + private Image fImage; - + private boolean fStatusLineAboveButtons; - + /** * Creates an instane of a status dialog. */ public StatusDialog(Shell parent) { super(parent); - fStatusLineAboveButtons= false; + fStatusLineAboveButtons = false; } - + /** - * Specifies whether status line appears to the left of the buttons (default) - * or above them. - * - * @param aboveButtons if true status line is placed above buttons; if - * false to the right + * Specifies whether status line appears to the left of the buttons + * (default) or above them. + * + * @param aboveButtons + * if true status line is placed above buttons; if + * false to the right */ public void setStatusLineAboveButtons(boolean aboveButtons) { - fStatusLineAboveButtons= aboveButtons; - } - + fStatusLineAboveButtons = aboveButtons; + } + /** - * Update the dialog's status line to reflect the given status. - * It is save to call this method before the dialog has been opened. + * Update the dialog's status line to reflect the given status. It is save + * to call this method before the dialog has been opened. */ protected void updateStatus(IStatus status) { - fLastStatus= status; + fLastStatus = status; if (fStatusLine != null && !fStatusLine.isDisposed()) { updateButtonsEnableState(status); fStatusLine.setErrorStatus(status); } } - + /** * Returns the last status. */ @@ -69,14 +74,16 @@ public abstract class StatusDialog extends Dialog { /** * Updates the status of the ok button to reflect the given status. * Subclasses may override this method to update additional buttons. - * @param status the status. + * + * @param status + * the status. */ protected void updateButtonsEnableState(IStatus status) { if (fOkButton != null && !fOkButton.isDisposed()) fOkButton.setEnabled(!status.matches(IStatus.ERROR)); } - - /* + + /* * @see Window#create(Shell) */ protected void configureShell(Shell shell) { @@ -87,15 +94,15 @@ public abstract class StatusDialog extends Dialog { /* * @see Window#create() - */ + */ public void create() { super.create(); if (fLastStatus != null) { // policy: dialogs are not allowed to come up with an error message if (fLastStatus.matches(IStatus.ERROR)) { - StatusInfo status= new StatusInfo(); + StatusInfo status = new StatusInfo(); status.setError(""); //$NON-NLS-1$ - fLastStatus= status; + fLastStatus = status; } updateStatus(fLastStatus); } @@ -105,23 +112,25 @@ public abstract class StatusDialog extends Dialog { * @see Dialog#createButtonsForButtonBar(Composite) */ protected void createButtonsForButtonBar(Composite parent) { - fOkButton= createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); - createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); + fOkButton = createButton(parent, IDialogConstants.OK_ID, + IDialogConstants.OK_LABEL, true); + createButton(parent, IDialogConstants.CANCEL_ID, + IDialogConstants.CANCEL_LABEL, false); } - + /* * @see Dialog#createButtonBar(Composite) - */ + */ protected Control createButtonBar(Composite parent) { - Composite composite= new Composite(parent, SWT.NULL); - GridLayout layout= new GridLayout(); - layout.numColumns= 1; - layout.marginHeight= 0; - layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); + Composite composite = new Composite(parent, SWT.NULL); + GridLayout layout = new GridLayout(); + layout.numColumns = 1; + layout.marginHeight = 0; + layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); composite.setLayout(layout); composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - - fStatusLine= new MessageLine(composite); + + fStatusLine = new MessageLine(composite); fStatusLine.setAlignment(SWT.LEFT); fStatusLine.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fStatusLine.setErrorStatus(null); //$NON-NLS-1$ @@ -129,27 +138,31 @@ public abstract class StatusDialog extends Dialog { super.createButtonBar(composite); return composite; } - + /** * Sets the title for this dialog. - * @param title the title. + * + * @param title + * the title. */ public void setTitle(String title) { - fTitle= title != null ? title : ""; //$NON-NLS-1$ - Shell shell= getShell(); + fTitle = title != null ? title : ""; //$NON-NLS-1$ + Shell shell = getShell(); if ((shell != null) && !shell.isDisposed()) shell.setText(fTitle); } /** * Sets the image for this dialog. - * @param image the image. + * + * @param image + * the image. */ public void setImage(Image image) { - fImage= image; - Shell shell= getShell(); + fImage = image; + Shell shell = getShell(); if ((shell != null) && !shell.isDisposed()) shell.setImage(fImage); - } - + } + } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/StatusInfo.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/StatusInfo.java index 6d52c5b..10c7efb 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/StatusInfo.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/StatusInfo.java @@ -6,13 +6,13 @@ import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.util.Assert; /** - * A settable IStatus. - * Can be an error, warning, info or ok. For error, info and warning states, - * a message describes the problem. + * A settable IStatus. Can be an error, warning, info or ok. For error, info and + * warning states, a message describes the problem. */ public class StatusInfo implements IStatus { private String fStatusMessage; + private int fSeverity; /** @@ -24,9 +24,12 @@ public class StatusInfo implements IStatus { /** * Creates a status . - * @param severity The status severity: ERROR, WARNING, INFO and OK. - * @param message The message of the status. Applies only for ERROR, - * WARNING and INFO. + * + * @param severity + * The status severity: ERROR, WARNING, INFO and OK. + * @param message + * The message of the status. Applies only for ERROR, WARNING and + * INFO. */ public StatusInfo(int severity, String message) { fStatusMessage = message; @@ -34,28 +37,28 @@ public class StatusInfo implements IStatus { } /** - * Returns if the status' severity is OK. + * Returns if the status' severity is OK. */ public boolean isOK() { return fSeverity == IStatus.OK; } /** - * Returns if the status' severity is WARNING. + * Returns if the status' severity is WARNING. */ public boolean isWarning() { return fSeverity == IStatus.WARNING; } /** - * Returns if the status' severity is INFO. + * Returns if the status' severity is INFO. */ public boolean isInfo() { return fSeverity == IStatus.INFO; } /** - * Returns if the status' severity is ERROR. + * Returns if the status' severity is ERROR. */ public boolean isError() { return fSeverity == IStatus.ERROR; @@ -70,7 +73,9 @@ public class StatusInfo implements IStatus { /** * Sets the status to ERROR. - * @param The error message (can be empty, but not null) + * + * @param The + * error message (can be empty, but not null) */ public void setError(String errorMessage) { Assert.isNotNull(errorMessage); @@ -80,7 +85,9 @@ public class StatusInfo implements IStatus { /** * Sets the status to WARNING. - * @param The warning message (can be empty, but not null) + * + * @param The + * warning message (can be empty, but not null) */ public void setWarning(String warningMessage) { Assert.isNotNull(warningMessage); @@ -90,7 +97,9 @@ public class StatusInfo implements IStatus { /** * Sets the status to INFO. - * @param The info message (can be empty, but not null) + * + * @param The + * info message (can be empty, but not null) */ public void setInfo(String infoMessage) { Assert.isNotNull(infoMessage); @@ -115,6 +124,7 @@ public class StatusInfo implements IStatus { /** * Returns always false. + * * @see IStatus#isMultiStatus() */ public boolean isMultiStatus() { @@ -137,6 +147,7 @@ public class StatusInfo implements IStatus { /** * Returns always null. + * * @see IStatus#getException() */ public Throwable getException() { @@ -145,6 +156,7 @@ public class StatusInfo implements IStatus { /** * Returns always the error severity. + * * @see IStatus#getCode() */ public int getCode() { @@ -153,6 +165,7 @@ public class StatusInfo implements IStatus { /** * Returns always null. + * * @see IStatus#getChildren() */ public IStatus[] getChildren() { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/StatusUtil.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/StatusUtil.java index f6f91d9..f87adf0 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/StatusUtil.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/StatusUtil.java @@ -13,9 +13,10 @@ import org.eclipse.jface.dialogs.DialogPage; public class StatusUtil { /** - * Compares two instances of IStatus. The more severe is returned: - * An error is more severe than a warning, and a warning is more severe - * than ok. If the two stati have the same severity, the second is returned. + * Compares two instances of IStatus. The more severe is + * returned: An error is more severe than a warning, and a warning is more + * severe than ok. If the two stati have the same severity, the second is + * returned. */ public static IStatus getMoreSevere(IStatus s1, IStatus s2) { if (s1.getSeverity() > s2.getSeverity()) { @@ -26,49 +27,48 @@ public class StatusUtil { } /** - * Finds the most severe status from a array of stati. - * An error is more severe than a warning, and a warning is more severe - * than ok. + * Finds the most severe status from a array of stati. An error is more + * severe than a warning, and a warning is more severe than ok. */ public static IStatus getMostSevere(IStatus[] status) { - IStatus max= null; - for (int i= 0; i < status.length; i++) { - IStatus curr= status[i]; + IStatus max = null; + for (int i = 0; i < status.length; i++) { + IStatus curr = status[i]; if (curr.matches(IStatus.ERROR)) { return curr; } if (max == null || curr.getSeverity() > max.getSeverity()) { - max= curr; + max = curr; } } return max; } - + /** * Applies the status to the status line of a dialog page. */ public static void applyToStatusLine(DialogPage page, IStatus status) { - String message= status.getMessage(); + String message = status.getMessage(); switch (status.getSeverity()) { - case IStatus.OK: - page.setMessage(message, DialogPage.NONE); - page.setErrorMessage(null); - break; - case IStatus.WARNING: - page.setMessage(message, DialogPage.WARNING); - page.setErrorMessage(null); - break; - case IStatus.INFO: - page.setMessage(message, DialogPage.INFORMATION); - page.setErrorMessage(null); - break; - default: - if (message.length() == 0) { - message= null; - } - page.setMessage(null); - page.setErrorMessage(message); - break; + case IStatus.OK: + page.setMessage(message, DialogPage.NONE); + page.setErrorMessage(null); + break; + case IStatus.WARNING: + page.setMessage(message, DialogPage.WARNING); + page.setErrorMessage(null); + break; + case IStatus.INFO: + page.setMessage(message, DialogPage.INFORMATION); + page.setErrorMessage(null); + break; + default: + if (message.length() == 0) { + message = null; + } + page.setMessage(null); + page.setErrorMessage(message); + break; } } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/BasicSelectionTransferDragAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/BasicSelectionTransferDragAdapter.java index e4d4ff9..866f69a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/BasicSelectionTransferDragAdapter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/BasicSelectionTransferDragAdapter.java @@ -18,13 +18,14 @@ import org.eclipse.swt.dnd.DragSourceAdapter; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.swt.dnd.Transfer; -public class BasicSelectionTransferDragAdapter extends DragSourceAdapter implements TransferDragSourceListener { - +public class BasicSelectionTransferDragAdapter extends DragSourceAdapter + implements TransferDragSourceListener { + private ISelectionProvider fProvider; - + public BasicSelectionTransferDragAdapter(ISelectionProvider provider) { Assert.isNotNull(provider); - fProvider= provider; + fProvider = provider; } /** @@ -33,49 +34,53 @@ public class BasicSelectionTransferDragAdapter extends DragSourceAdapter impleme public Transfer getTransfer() { return LocalSelectionTransfer.getInstance(); } - - /* non Java-doc + + /* + * non Java-doc + * * @see org.eclipse.swt.dnd.DragSourceListener#dragStart */ public void dragStart(DragSourceEvent event) { - ISelection selection= fProvider.getSelection(); + ISelection selection = fProvider.getSelection(); LocalSelectionTransfer.getInstance().setSelection(selection); LocalSelectionTransfer.getInstance().setSelectionSetTime(event.time); - event.doit= isDragable(selection); + event.doit = isDragable(selection); } - + /** - * Checks if the elements contained in the given selection can - * be dragged. + * Checks if the elements contained in the given selection can be dragged. *

                                                      * Subclasses may override. * - * @param selection containing the elements to be dragged + * @param selection + * containing the elements to be dragged */ protected boolean isDragable(ISelection selection) { return true; } - - /* non Java-doc + /* + * non Java-doc + * * @see org.eclipse.swt.dnd.DragSourceListener#dragSetData - */ + */ public void dragSetData(DragSourceEvent event) { // For consistency set the data to the selection even though // the selection is provided by the LocalSelectionTransfer // to the drop target adapter. - event.data= LocalSelectionTransfer.getInstance().getSelection(); + event.data = LocalSelectionTransfer.getInstance().getSelection(); } - - /* non Java-doc + /* + * non Java-doc + * * @see org.eclipse.swt.dnd.DragSourceListener#dragFinished - */ + */ public void dragFinished(DragSourceEvent event) { // We assume that the drop target listener has done all // the work. Assert.isTrue(event.detail == DND.DROP_NONE); LocalSelectionTransfer.getInstance().setSelection(null); LocalSelectionTransfer.getInstance().setSelectionSetTime(0); - } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/DelegatingDragAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/DelegatingDragAdapter.java index d8fbbde..df9c40a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/DelegatingDragAdapter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/DelegatingDragAdapter.java @@ -22,93 +22,106 @@ import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.dnd.TransferData; /** - * A delegating drag adapter negotiates between a set of TransferDragSourceListeners - * On dragStart the adapter determines the listener to be used for any further - * drag* callback. + * A delegating drag adapter negotiates between a set of + * TransferDragSourceListeners On dragStart the + * adapter determines the listener to be used for any further drag* + * callback. */ public class DelegatingDragAdapter implements DragSourceListener { private TransferDragSourceListener[] fPossibleListeners; + private List fActiveListeners; + private TransferDragSourceListener fFinishListener; - + public DelegatingDragAdapter(TransferDragSourceListener[] listeners) { setPossibleListeners(listeners); } - + protected void setPossibleListeners(TransferDragSourceListener[] listeners) { Assert.isNotNull(listeners); - Assert.isTrue(fActiveListeners == null, "Can only set possible listeners before drag operation has started"); //$NON-NLS-1$ - fPossibleListeners= listeners; + Assert + .isTrue(fActiveListeners == null, + "Can only set possible listeners before drag operation has started"); //$NON-NLS-1$ + fPossibleListeners = listeners; } - - /* non Java-doc + + /* + * non Java-doc + * * @see DragSourceListener */ public void dragStart(DragSourceEvent event) { - fFinishListener= null; - boolean saveDoit= event.doit; - Object saveData= event.data; - boolean doIt= false; - List transfers= new ArrayList(fPossibleListeners.length); - fActiveListeners= new ArrayList(fPossibleListeners.length); - - for (int i= 0; i < fPossibleListeners.length; i++) { - TransferDragSourceListener listener= fPossibleListeners[i]; - event.doit= saveDoit; + fFinishListener = null; + boolean saveDoit = event.doit; + Object saveData = event.data; + boolean doIt = false; + List transfers = new ArrayList(fPossibleListeners.length); + fActiveListeners = new ArrayList(fPossibleListeners.length); + + for (int i = 0; i < fPossibleListeners.length; i++) { + TransferDragSourceListener listener = fPossibleListeners[i]; + event.doit = saveDoit; listener.dragStart(event); if (event.doit) { transfers.add(listener.getTransfer()); fActiveListeners.add(listener); } - doIt= doIt || event.doit; + doIt = doIt || event.doit; } if (doIt) { - ((DragSource)event.widget).setTransfer((Transfer[])transfers.toArray(new Transfer[transfers.size()])); + ((DragSource) event.widget).setTransfer((Transfer[]) transfers + .toArray(new Transfer[transfers.size()])); } - event.data= saveData; - event.doit= doIt; + event.data = saveData; + event.doit = doIt; } - /* non Java-doc + /* + * non Java-doc + * * @see DragSourceListener */ public void dragSetData(DragSourceEvent event) { - fFinishListener= getListener(event.dataType); + fFinishListener = getListener(event.dataType); if (fFinishListener != null) fFinishListener.dragSetData(event); } - - /* non Java-doc + + /* + * non Java-doc + * * @see DragSourceListener */ public void dragFinished(DragSourceEvent event) { - try{ + try { if (fFinishListener != null) { fFinishListener.dragFinished(event); } else { // If the user presses Escape then we get a dragFinished without // getting a dragSetData before. - fFinishListener= getListener(event.dataType); + fFinishListener = getListener(event.dataType); if (fFinishListener != null) fFinishListener.dragFinished(event); } - } finally{ - fFinishListener= null; - fActiveListeners= null; - } + } finally { + fFinishListener = null; + fActiveListeners = null; + } } - + private TransferDragSourceListener getListener(TransferData type) { if (type == null) return null; - - for (Iterator iter= fActiveListeners.iterator(); iter.hasNext();) { - TransferDragSourceListener listener= (TransferDragSourceListener)iter.next(); + + for (Iterator iter = fActiveListeners.iterator(); iter.hasNext();) { + TransferDragSourceListener listener = (TransferDragSourceListener) iter + .next(); if (listener.getTransfer().isSupportedType(type)) { return listener; } } return null; - } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/DelegatingDropAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/DelegatingDropAdapter.java index c3cddac..4424f34 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/DelegatingDropAdapter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/DelegatingDropAdapter.java @@ -16,93 +16,108 @@ import org.eclipse.swt.dnd.DropTargetListener; import org.eclipse.swt.dnd.TransferData; /** - * A delegating drop adapter negotiates between a set of TransferDropTargetListeners - * On dragEnter the adapter determines the listener to be used for any further - * drag* callback. + * A delegating drop adapter negotiates between a set of + * TransferDropTargetListeners On dragEnter the + * adapter determines the listener to be used for any further drag* + * callback. */ public class DelegatingDropAdapter implements DropTargetListener { private TransferDropTargetListener[] fListeners; - + private TransferDropTargetListener fChosenListener; /** * Creates a new delegating drop adapter. * - * @param listeners an array of potential listeners - */ + * @param listeners + * an array of potential listeners + */ public DelegatingDropAdapter(TransferDropTargetListener[] listeners) { - fListeners= listeners; + fListeners = listeners; Assert.isNotNull(listeners); } - /* non Java-doc + /* + * non Java-doc + * * @see DropTargetListener */ public void dragEnter(DropTargetEvent event) { - fChosenListener= null; - event.currentDataType= selectPreferredListener(event.dataTypes); + fChosenListener = null; + event.currentDataType = selectPreferredListener(event.dataTypes); if (fChosenListener != null) fChosenListener.dragEnter(event); } - - /* non Java-doc + + /* + * non Java-doc + * * @see DropTargetListener */ - public void dragLeave(DropTargetEvent event){ + public void dragLeave(DropTargetEvent event) { if (fChosenListener != null) fChosenListener.dragLeave(event); } - - /* non Java-doc + + /* + * non Java-doc + * * @see DropTargetListener */ - public void dragOperationChanged(DropTargetEvent event){ + public void dragOperationChanged(DropTargetEvent event) { if (fChosenListener != null) fChosenListener.dragOperationChanged(event); } - - /* non Java-doc + + /* + * non Java-doc + * * @see DropTargetListener */ - public void dragOver(DropTargetEvent event){ + public void dragOver(DropTargetEvent event) { if (fChosenListener != null) fChosenListener.dragOver(event); } - - /* non Java-doc + + /* + * non Java-doc + * * @see DropTargetListener */ - public void drop(DropTargetEvent event){ + public void drop(DropTargetEvent event) { if (fChosenListener != null) fChosenListener.drop(event); - fChosenListener= null; + fChosenListener = null; } - - /* non Java-doc + + /* + * non Java-doc + * * @see DropTargetListener */ - public void dropAccept(DropTargetEvent event){ + public void dropAccept(DropTargetEvent event) { if (fChosenListener != null) fChosenListener.dropAccept(event); } - + private TransferData selectPreferredListener(TransferData[] dataTypes) { - for (int i= 0; i < fListeners.length; i++) { - TransferData data= computeTransferData(dataTypes, fListeners[i]); + for (int i = 0; i < fListeners.length; i++) { + TransferData data = computeTransferData(dataTypes, fListeners[i]); if (data != null) return data; } return null; } - - private TransferData computeTransferData(TransferData[] dataTypes, TransferDropTargetListener listener) { - for (int i= 0; i < dataTypes.length; i++) { + + private TransferData computeTransferData(TransferData[] dataTypes, + TransferDropTargetListener listener) { + for (int i = 0; i < dataTypes.length; i++) { if (listener.getTransfer().isSupportedType(dataTypes[i])) { - fChosenListener= listener; + fChosenListener = listener; return dataTypes[i]; } } return null; - } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/JdtViewerDragAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/JdtViewerDragAdapter.java index 20226b0..63351c2 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/JdtViewerDragAdapter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/JdtViewerDragAdapter.java @@ -19,17 +19,19 @@ public class JdtViewerDragAdapter extends DelegatingDragAdapter { private StructuredViewer fViewer; - public JdtViewerDragAdapter(StructuredViewer viewer, TransferDragSourceListener[] listeners) { + public JdtViewerDragAdapter(StructuredViewer viewer, + TransferDragSourceListener[] listeners) { super(listeners); Assert.isNotNull(viewer); - fViewer= viewer; + fViewer = viewer; } - + public void dragStart(DragSourceEvent event) { - IStructuredSelection selection= (IStructuredSelection)fViewer.getSelection(); + IStructuredSelection selection = (IStructuredSelection) fViewer + .getSelection(); if (selection.isEmpty()) { - event.doit= false; - return; + event.doit = false; + return; } super.dragStart(event); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/JdtViewerDropAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/JdtViewerDropAdapter.java index 99dc11f..7e2143b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/JdtViewerDropAdapter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/JdtViewerDropAdapter.java @@ -22,103 +22,115 @@ import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.TreeItem; /** - * A drag and drop adapter to be used together with structured viewers. - * The adapater delegates the dragEnter, dragOperationChanged - * , dragOver and dropAccept method to the + * A drag and drop adapter to be used together with structured viewers. The + * adapater delegates the dragEnter, dragOperationChanged + * , + * dragOver and dropAccept method to the * validateDrop method. Furthermore it adds location feedback. */ public class JdtViewerDropAdapter implements DropTargetListener { /** - * Constant describing the position of the mouse cursor relative - * to the target object. This means the mouse is positioned - * slightly before the target. + * Constant describing the position of the mouse cursor relative to the + * target object. This means the mouse is positioned slightly before the + * target. */ - protected static final int LOCATION_BEFORE= 1; - + protected static final int LOCATION_BEFORE = 1; + /** - * Constant describing the position of the mouse cursor relative - * to the target object. This means the mouse is positioned - * slightly after the target. + * Constant describing the position of the mouse cursor relative to the + * target object. This means the mouse is positioned slightly after the + * target. */ - protected static final int LOCATION_AFTER= 2; - + protected static final int LOCATION_AFTER = 2; + /** - * Constant describing the position of the mouse cursor relative - * to the target object. This means the mouse is positioned - * directly on the target. + * Constant describing the position of the mouse cursor relative to the + * target object. This means the mouse is positioned directly on the target. */ - protected static final int LOCATION_ON= 3; - + protected static final int LOCATION_ON = 3; + /** - * Constant describing the position of the mouse cursor relative - * to the target object. This means the mouse is not positioned - * over or near any valid target. + * Constant describing the position of the mouse cursor relative to the + * target object. This means the mouse is not positioned over or near any + * valid target. */ - protected static final int LOCATION_NONE= 4; - + protected static final int LOCATION_NONE = 4; + /** - * The threshold used to determine if the mouse is before or after - * an item. + * The threshold used to determine if the mouse is before or after an item. */ - private static final int LOCATION_EPSILON= 5; - + private static final int LOCATION_EPSILON = 5; + /** * Style to enable location feedback. */ - public static final int INSERTION_FEEDBACK= 1 << 1; + public static final int INSERTION_FEEDBACK = 1 << 1; private StructuredViewer fViewer; + private int fFeedback; + private boolean fShowInsertionFeedback; + private int fRequestedOperation; + private int fLastOperation; + protected int fLocation; + protected Object fTarget; public JdtViewerDropAdapter(StructuredViewer viewer, int feedback) { - fViewer= viewer; + fViewer = viewer; Assert.isNotNull(fViewer); - fFeedback= feedback; - fLastOperation= -1; + fFeedback = feedback; + fLastOperation = -1; } /** * Controls whether the drop adapter shows insertion feedback or not. * - * @param showInsertionFeedback true if the drop adapter is supposed - * to show insertion feedback. Otherwise false + * @param showInsertionFeedback + * true if the drop adapter is supposed to show + * insertion feedback. Otherwise false */ public void showInsertionFeedback(boolean showInsertionFeedback) { - fShowInsertionFeedback= showInsertionFeedback; + fShowInsertionFeedback = showInsertionFeedback; } - + /** * Returns the viewer this adapter is working on. */ protected StructuredViewer getViewer() { return fViewer; - } - - //---- Hooks to override ----------------------------------------------------- - + } + + // ---- Hooks to override + // ----------------------------------------------------- + /** - * The actual drop has occurred. Calls drop(Object target, DropTargetEvent event) + * The actual drop has occurred. Calls + * drop(Object target, DropTargetEvent event) * . + * * @see DropTargetListener#drop(org.eclipse.swt.dnd.DropTargetEvent) - */ + */ public void drop(DropTargetEvent event) { drop(fTarget, event); } - + /** * The actual drop has occurred. - * @param target the drop target in form of a domain element. - * @param event the drop traget event - */ + * + * @param target + * the drop target in form of a domain element. + * @param event + * the drop traget event + */ public void drop(Object target, DropTargetEvent event) { } - + /** * Checks if the drop is valid. The method calls validateDrop * (Object target, DropTargetEvent event). Implementors can alter the @@ -128,79 +140,86 @@ public class JdtViewerDropAdapter implements DropTargetListener { public void validateDrop(DropTargetEvent event) { validateDrop(fTarget, event, fRequestedOperation); } - + /** - * Checks if the drop on the current target is valid. The method - * can alter the currentDataType field and the - * detail field to give feedback about drop acceptence. - * @param target the drop target in form of a domain element. - * @param event the drop traget event - * @param operation the operation requested by the user. + * Checks if the drop on the current target is valid. The method can alter + * the currentDataType field and the + * detail + * field to give feedback about drop acceptence. + * + * @param target + * the drop target in form of a domain element. + * @param event + * the drop traget event + * @param operation + * the operation requested by the user. */ public void validateDrop(Object target, DropTargetEvent event, int operation) { } - + public void dragEnter(DropTargetEvent event) { dragOperationChanged(event); } - + public void dragLeave(DropTargetEvent event) { - fTarget= null; - fLocation= LOCATION_NONE; + fTarget = null; + fLocation = LOCATION_NONE; } - + public void dragOperationChanged(DropTargetEvent event) { - fRequestedOperation= event.detail; - fTarget= computeTarget(event); - fLocation= computeLocation(event); + fRequestedOperation = event.detail; + fTarget = computeTarget(event); + fLocation = computeLocation(event); validateDrop(event); - fLastOperation= event.detail; + fLastOperation = event.detail; computeFeedback(event); } - + public void dragOver(DropTargetEvent event) { - Object oldTarget= fTarget; - fTarget= computeTarget(event); - - //set the location feedback - int oldLocation= fLocation; - fLocation= computeLocation(event); - if (oldLocation != fLocation || oldTarget != fTarget || fLastOperation != event.detail) { + Object oldTarget = fTarget; + fTarget = computeTarget(event); + + // set the location feedback + int oldLocation = fLocation; + fLocation = computeLocation(event); + if (oldLocation != fLocation || oldTarget != fTarget + || fLastOperation != event.detail) { validateDrop(event); - fLastOperation= event.detail; + fLastOperation = event.detail; } else { - event.detail= fLastOperation; + event.detail = fLastOperation; } computeFeedback(event); } - + public void dropAccept(DropTargetEvent event) { - fTarget= computeTarget(event); + fTarget = computeTarget(event); validateDrop(event); - fLastOperation= event.detail; + fLastOperation = event.detail; } - + /** - * Returns the data held by event.item. Inside a viewer - * this corresponds to the items data model element. + * Returns the data held by event.item. Inside a viewer this + * corresponds to the items data model element. */ protected Object computeTarget(DropTargetEvent event) { return event.item == null ? null : event.item.getData(); } - + /** - * Returns the position of the given coordinates relative to the given target. - * The position is determined to be before, after, or on the item, based on - * some threshold value. The return value is one of the LOCATION_* constants - * defined in this class. + * Returns the position of the given coordinates relative to the given + * target. The position is determined to be before, after, or on the item, + * based on some threshold value. The return value is one of the LOCATION_* + * constants defined in this class. */ final protected int computeLocation(DropTargetEvent event) { if (!(event.item instanceof Item)) return LOCATION_NONE; - - Item item= (Item) event.item; - Point coordinates= fViewer.getControl().toControl(new Point(event.x, event.y)); - Rectangle bounds= getBounds(item); + + Item item = (Item) event.item; + Point coordinates = fViewer.getControl().toControl( + new Point(event.x, event.y)); + Rectangle bounds = getBounds(item); if (bounds == null) { return LOCATION_NONE; } @@ -214,47 +233,48 @@ public class JdtViewerDropAdapter implements DropTargetListener { } /** - * Returns the bounds of the given item, or null if it is not a - * valid type of item. + * Returns the bounds of the given item, or null if it is not + * a valid type of item. */ private Rectangle getBounds(Item item) { if (item instanceof TreeItem) return ((TreeItem) item).getBounds(); - + if (item instanceof TableItem) return ((TableItem) item).getBounds(0); - + return null; } /** - * Sets the drag under feedback corresponding to the value of fLocation - * and the INSERTION_FEEDBACK style bit. + * Sets the drag under feedback corresponding to the value of + * fLocation and the INSERTION_FEEDBACK style + * bit. */ protected void computeFeedback(DropTargetEvent event) { if (!fShowInsertionFeedback && fLocation != LOCATION_NONE) { - event.feedback= DND.FEEDBACK_SELECT; + event.feedback = DND.FEEDBACK_SELECT; } else { if (fLocation == LOCATION_BEFORE) { - event.feedback= DND.FEEDBACK_INSERT_BEFORE; + event.feedback = DND.FEEDBACK_INSERT_BEFORE; } else if (fLocation == LOCATION_AFTER) { - event.feedback= DND.FEEDBACK_INSERT_AFTER; + event.feedback = DND.FEEDBACK_INSERT_AFTER; } } - event.feedback|= fFeedback; + event.feedback |= fFeedback; } - + /** * Sets the drop operation to DROP_NODE. */ protected void clearDropOperation(DropTargetEvent event) { - event.detail= DND.DROP_NONE; + event.detail = DND.DROP_NONE; } - + /** * Returns the requested drop operation. */ protected int getRequestedOperation() { return fRequestedOperation; - } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/LocalSelectionTransfer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/LocalSelectionTransfer.java index 408c2f5..6a870fd 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/LocalSelectionTransfer.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/LocalSelectionTransfer.java @@ -18,82 +18,87 @@ import org.eclipse.jface.viewers.ISelection; import org.eclipse.swt.dnd.ByteArrayTransfer; import org.eclipse.swt.dnd.TransferData; - public class LocalSelectionTransfer extends ByteArrayTransfer { // First attempt to create a UUID for the type name to make sure that // different Eclipse applications use different "types" of // LocalSelectionTransfer - private static final String TYPE_NAME= "local-selection-transfer-format" + (new Long(System.currentTimeMillis())).toString(); //$NON-NLS-1$; - private static final int TYPEID= registerType(TYPE_NAME); - - private static final LocalSelectionTransfer INSTANCE= new LocalSelectionTransfer(); - + private static final String TYPE_NAME = "local-selection-transfer-format" + (new Long(System.currentTimeMillis())).toString(); //$NON-NLS-1$; + + private static final int TYPEID = registerType(TYPE_NAME); + + private static final LocalSelectionTransfer INSTANCE = new LocalSelectionTransfer(); + private ISelection fSelection; + private int fSelectionSetTime; - + private LocalSelectionTransfer() { } - + /** * Returns the singleton. */ public static LocalSelectionTransfer getInstance() { return INSTANCE; } - + /** * Sets the transfer data for local use. - */ + */ public void setSelection(ISelection s) { - fSelection= s; + fSelection = s; } - + /** * Returns the local transfer data. */ public ISelection getSelection() { return fSelection; } - + public void javaToNative(Object object, TransferData transferData) { - // No encoding needed since this is a hardcoded string read and written in the same process. + // No encoding needed since this is a hardcoded string read and written + // in the same process. // See nativeToJava below - byte[] check= TYPE_NAME.getBytes(); + byte[] check = TYPE_NAME.getBytes(); super.javaToNative(check, transferData); } public Object nativeToJava(TransferData transferData) { - Object result= super.nativeToJava(transferData); + Object result = super.nativeToJava(transferData); if (isInvalidNativeType(result)) { - PHPeclipsePlugin.log(IStatus.ERROR, PHPUIMessages.getString("LocalSelectionTransfer.errorMessage")); //$NON-NLS-1$ + PHPeclipsePlugin.log(IStatus.ERROR, PHPUIMessages + .getString("LocalSelectionTransfer.errorMessage")); //$NON-NLS-1$ } return fSelection; } private boolean isInvalidNativeType(Object result) { - // No encoding needed since this is a hardcoded string read and written in the same process. + // No encoding needed since this is a hardcoded string read and written + // in the same process. // See javaToNative above - return !(result instanceof byte[]) || !TYPE_NAME.equals(new String((byte[])result)); + return !(result instanceof byte[]) + || !TYPE_NAME.equals(new String((byte[]) result)); } - + /** * The type id used to identify this transfer. */ protected int[] getTypeIds() { - return new int[] {TYPEID}; + return new int[] { TYPEID }; } - - protected String[] getTypeNames(){ - return new String[] {TYPE_NAME}; - } - + + protected String[] getTypeNames() { + return new String[] { TYPE_NAME }; + } + public int getSelectionSetTime() { return fSelectionSetTime; } public void setSelectionSetTime(int time) { - fSelectionSetTime= time; + fSelectionSetTime = time; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/ResourceTransferDragAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/ResourceTransferDragAdapter.java index 876bb0c..370b251 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/ResourceTransferDragAdapter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/ResourceTransferDragAdapter.java @@ -36,79 +36,82 @@ import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.part.ResourceTransfer; - /** - * A drag adapter that transfers the current selection as - * IResource. Only those elements in the selection are part - * of the transfer which can be converted into an IResource - * . + * A drag adapter that transfers the current selection as IResource. + * Only those elements in the selection are part of the transfer which can be + * converted into an IResource . */ -public class ResourceTransferDragAdapter extends DragSourceAdapter implements TransferDragSourceListener { +public class ResourceTransferDragAdapter extends DragSourceAdapter implements + TransferDragSourceListener { private ISelectionProvider fProvider; - private static final List EMPTY_LIST= new ArrayList(0); + private static final List EMPTY_LIST = new ArrayList(0); /** * Creates a new ResourceTransferDragAdapter for the given selection * provider. * - * @param provider the selection provider to access the viewer's selection + * @param provider + * the selection provider to access the viewer's selection */ public ResourceTransferDragAdapter(ISelectionProvider provider) { - fProvider= provider; + fProvider = provider; Assert.isNotNull(fProvider); } - + public Transfer getTransfer() { return ResourceTransfer.getInstance(); } - + public void dragStart(DragSourceEvent event) { - event.doit= convertSelection().size() > 0; + event.doit = convertSelection().size() > 0; } - + public void dragSetData(DragSourceEvent event) { - List resources= convertSelection(); - event.data= (IResource[]) resources.toArray(new IResource[resources.size()]); + List resources = convertSelection(); + event.data = (IResource[]) resources.toArray(new IResource[resources + .size()]); } - + public void dragFinished(DragSourceEvent event) { if (!event.doit) return; if (event.detail == DND.DROP_MOVE) { handleFinishedDropMove(event); - } + } } - + private List convertSelection() { - ISelection s= fProvider.getSelection(); + ISelection s = fProvider.getSelection(); if (!(s instanceof IStructuredSelection)) return EMPTY_LIST; - IStructuredSelection selection= (IStructuredSelection)s; - List result= new ArrayList(selection.size()); - for (Iterator iter= selection.iterator(); iter.hasNext();) { - Object element= iter.next(); + IStructuredSelection selection = (IStructuredSelection) s; + List result = new ArrayList(selection.size()); + for (Iterator iter = selection.iterator(); iter.hasNext();) { + Object element = iter.next(); if (element instanceof IAdaptable) { - IAdaptable adaptable= (IAdaptable)element; - IResource resource= (IResource)adaptable.getAdapter(IResource.class); + IAdaptable adaptable = (IAdaptable) element; + IResource resource = (IResource) adaptable + .getAdapter(IResource.class); if (resource != null) result.add(resource); } } return result; } - + private void handleFinishedDropMove(DragSourceEvent event) { - MultiStatus status= new MultiStatus( - PHPeclipsePlugin.getPluginId(), - IJavaStatusConstants.INTERNAL_ERROR, - PHPUIMessages.getString("ResourceTransferDragAdapter.cannot_delete_resource"), //$NON-NLS-1$ - null); - List resources= convertSelection(); - for (Iterator iter= resources.iterator(); iter.hasNext();) { - IResource resource= (IResource) iter.next(); + MultiStatus status = new MultiStatus( + PHPeclipsePlugin.getPluginId(), + IJavaStatusConstants.INTERNAL_ERROR, + PHPUIMessages + .getString("ResourceTransferDragAdapter.cannot_delete_resource"), //$NON-NLS-1$ + null); + List resources = convertSelection(); + for (Iterator iter = resources.iterator(); iter.hasNext();) { + IResource resource = (IResource) iter.next(); try { resource.delete(true, null); } catch (CoreException e) { @@ -116,13 +119,15 @@ public class ResourceTransferDragAdapter extends DragSourceAdapter implements Tr } } if (status.getChildren().length > 0) { - Shell parent= SWTUtil.getShell(event.widget); - ErrorDialog error= new ErrorDialog(parent, - PHPUIMessages.getString("ResourceTransferDragAdapter.moving_resource"), //$NON-NLS-1$ - PHPUIMessages.getString("ResourceTransferDragAdapter.cannot_delete_files"), //$NON-NLS-1$ - status, IStatus.ERROR); + Shell parent = SWTUtil.getShell(event.widget); + ErrorDialog error = new ErrorDialog( + parent, + PHPUIMessages + .getString("ResourceTransferDragAdapter.moving_resource"), //$NON-NLS-1$ + PHPUIMessages + .getString("ResourceTransferDragAdapter.cannot_delete_files"), //$NON-NLS-1$ + status, IStatus.ERROR); error.open(); } } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/TransferDragSourceListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/TransferDragSourceListener.java index b4f7ecb..dbe83c8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/TransferDragSourceListener.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/TransferDragSourceListener.java @@ -14,7 +14,8 @@ import org.eclipse.swt.dnd.DragSourceListener; import org.eclipse.swt.dnd.Transfer; /** - * A special drag source listener which is typed with a TransferData. + * A special drag source listener which is typed with a + * TransferData. */ public interface TransferDragSourceListener extends DragSourceListener { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/TransferDropTargetListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/TransferDropTargetListener.java index f642ae8..abea4ab 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/TransferDropTargetListener.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/TransferDropTargetListener.java @@ -14,7 +14,8 @@ import org.eclipse.swt.dnd.DropTargetListener; import org.eclipse.swt.dnd.Transfer; /** - * A special drop target listener which is typed with a TransferData. + * A special drop target listener which is typed with a + * TransferData. */ public interface TransferDropTargetListener extends DropTargetListener { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/ClassFilter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/ClassFilter.java index 4960bed..850db3b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/ClassFilter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/ClassFilter.java @@ -10,14 +10,12 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.ui.filters; - import net.sourceforge.phpdt.core.IType; import net.sourceforge.phpdt.core.JavaModelException; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; - /** * Filters classes */ @@ -29,7 +27,7 @@ public class ClassFilter extends ViewerFilter { public boolean select(Viewer viewer, Object parent, Object element) { if (element instanceof IType) { try { - return ((IType)element).isInterface(); + return ((IType) element).isInterface(); } catch (JavaModelException ex) { return true; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/ClosedProjectFilter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/ClosedProjectFilter.java index dc1becf..2ac29b1 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/ClosedProjectFilter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/ClosedProjectFilter.java @@ -10,7 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.ui.filters; - import net.sourceforge.phpdt.core.IJavaElement; import org.eclipse.core.resources.IResource; @@ -26,10 +25,11 @@ public class ClosedProjectFilter extends ViewerFilter { * @see ViewerFilter */ public boolean select(Viewer viewer, Object parent, Object element) { - if (element instanceof IJavaElement) - return ((IJavaElement)element).getJavaProject().getProject().isOpen(); + if (element instanceof IJavaElement) + return ((IJavaElement) element).getJavaProject().getProject() + .isOpen(); if (element instanceof IResource) - return ((IResource)element).getProject().isOpen(); + return ((IResource) element).getProject().isOpen(); return true; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/CustomFiltersDialog.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/CustomFiltersDialog.java index 3c20939..8060d76 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/CustomFiltersDialog.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/CustomFiltersDialog.java @@ -52,95 +52,105 @@ import org.eclipse.ui.dialogs.SelectionDialog; public class CustomFiltersDialog extends SelectionDialog { - private static final String SEPARATOR= ","; //$NON-NLS-1$ + private static final String SEPARATOR = ","; //$NON-NLS-1$ private String fViewId; + private boolean fEnablePatterns; + private String[] fPatterns; + private String[] fEnabledFilterIds; private FilterDescriptor[] fBuiltInFilters; private CheckboxTableViewer fCheckBoxList; + private Button fEnableUserDefinedPatterns; + private Text fUserDefinedPatterns; private Stack fFilterDescriptorChangeHistory; - /** * Creates a dialog to customize Java element filters. - * - * @param shell the parent shell - * @param viewId the id of the view - * @param enablePatterns true if pattern filters are enabled - * @param patterns the filter patterns - * @param enabledFilterIds the Ids of the enabled filters + * + * @param shell + * the parent shell + * @param viewId + * the id of the view + * @param enablePatterns + * true if pattern filters are enabled + * @param patterns + * the filter patterns + * @param enabledFilterIds + * the Ids of the enabled filters */ - public CustomFiltersDialog( - Shell shell, - String viewId, - boolean enablePatterns, - String[] patterns, - String[] enabledFilterIds) { + public CustomFiltersDialog(Shell shell, String viewId, + boolean enablePatterns, String[] patterns, String[] enabledFilterIds) { super(shell); Assert.isNotNull(viewId); Assert.isNotNull(patterns); Assert.isNotNull(enabledFilterIds); - fViewId= viewId; - fPatterns= patterns; - fEnablePatterns= enablePatterns; - fEnabledFilterIds= enabledFilterIds; + fViewId = viewId; + fPatterns = patterns; + fEnablePatterns = enablePatterns; + fEnabledFilterIds = enabledFilterIds; - fBuiltInFilters= FilterDescriptor.getFilterDescriptors(fViewId); - fFilterDescriptorChangeHistory= new Stack(); + fBuiltInFilters = FilterDescriptor.getFilterDescriptors(fViewId); + fFilterDescriptorChangeHistory = new Stack(); setShellStyle(getShellStyle() | SWT.RESIZE); } protected void configureShell(Shell shell) { - setTitle(FilterMessages.getString("CustomFiltersDialog.title")); //$NON-NLS-1$ - setMessage(FilterMessages.getString("CustomFiltersDialog.filterList.label")); //$NON-NLS-1$ + setTitle(FilterMessages.getString("CustomFiltersDialog.title")); //$NON-NLS-1$ + setMessage(FilterMessages + .getString("CustomFiltersDialog.filterList.label")); //$NON-NLS-1$ super.configureShell(shell); - PlatformUI.getWorkbench().getHelpSystem().setHelp(shell, IJavaHelpContextIds.CUSTOM_FILTERS_DIALOG); + PlatformUI.getWorkbench().getHelpSystem().setHelp(shell, + IJavaHelpContextIds.CUSTOM_FILTERS_DIALOG); } /** * Overrides method in Dialog - * + * * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(Composite) */ protected Control createDialogArea(Composite parent) { initializeDialogUnits(parent); // create a composite with standard margins and spacing - Composite composite= new Composite(parent, SWT.NONE); - GridLayout layout= new GridLayout(); - layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); - layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); - layout.verticalSpacing= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); - layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); + layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); + layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); + layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); composite.setLayout(layout); composite.setLayoutData(new GridData(GridData.FILL_BOTH)); composite.setFont(parent.getFont()); - Composite group= composite; + Composite group = composite; // Checkbox - fEnableUserDefinedPatterns= new Button(group, SWT.CHECK); + fEnableUserDefinedPatterns = new Button(group, SWT.CHECK); fEnableUserDefinedPatterns.setFocus(); - fEnableUserDefinedPatterns.setText(FilterMessages.getString("CustomFiltersDialog.enableUserDefinedPattern")); //$NON-NLS-1$ - - // Pattern field - fUserDefinedPatterns= new Text(group, SWT.SINGLE | SWT.BORDER); - GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL); - data.widthHint= convertWidthInCharsToPixels(59); + fEnableUserDefinedPatterns.setText(FilterMessages + .getString("CustomFiltersDialog.enableUserDefinedPattern")); //$NON-NLS-1$ + + // Pattern field + fUserDefinedPatterns = new Text(group, SWT.SINGLE | SWT.BORDER); + GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL + | GridData.GRAB_HORIZONTAL); + data.widthHint = convertWidthInCharsToPixels(59); fUserDefinedPatterns.setLayoutData(data); - String patterns= convertToString(fPatterns, SEPARATOR); + String patterns = convertToString(fPatterns, SEPARATOR); fUserDefinedPatterns.setText(patterns); // Info text - final Label info= new Label(group, SWT.LEFT); - info.setText(FilterMessages.getString("CustomFiltersDialog.patternInfo")); //$NON-NLS-1$ + final Label info = new Label(group, SWT.LEFT); + info.setText(FilterMessages + .getString("CustomFiltersDialog.patternInfo")); //$NON-NLS-1$ // Enabling / disabling of pattern group fEnableUserDefinedPatterns.setSelection(fEnablePatterns); @@ -148,7 +158,7 @@ public class CustomFiltersDialog extends SelectionDialog { info.setEnabled(fEnablePatterns); fEnableUserDefinedPatterns.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { - boolean state= fEnableUserDefinedPatterns.getSelection(); + boolean state = fEnableUserDefinedPatterns.getSelection(); fUserDefinedPatterns.setEnabled(state); info.setEnabled(fEnableUserDefinedPatterns.getSelection()); if (state) @@ -168,12 +178,13 @@ public class CustomFiltersDialog extends SelectionDialog { // Filler new Label(parent, SWT.NONE); - Label info= new Label(parent, SWT.LEFT); - info.setText(FilterMessages.getString("CustomFiltersDialog.filterList.label")); //$NON-NLS-1$ + Label info = new Label(parent, SWT.LEFT); + info.setText(FilterMessages + .getString("CustomFiltersDialog.filterList.label")); //$NON-NLS-1$ - fCheckBoxList= CheckboxTableViewer.newCheckList(parent, SWT.BORDER); - GridData data= new GridData(GridData.FILL_BOTH); - data.heightHint= fCheckBoxList.getTable().getItemHeight() * 10; + fCheckBoxList = CheckboxTableViewer.newCheckList(parent, SWT.BORDER); + GridData data = new GridData(GridData.FILL_BOTH); + data.heightHint = fCheckBoxList.getTable().getItemHeight() * 10; fCheckBoxList.getTable().setLayoutData(data); fCheckBoxList.setLabelProvider(createLabelPrivder()); @@ -182,76 +193,88 @@ public class CustomFiltersDialog extends SelectionDialog { fCheckBoxList.setInput(fBuiltInFilters); setInitialSelections(getEnabledFilterDescriptors()); - List initialSelection= getInitialElementSelections(); + List initialSelection = getInitialElementSelections(); if (initialSelection != null && !initialSelection.isEmpty()) checkInitialSelections(); // Description - info= new Label(parent, SWT.LEFT); - info.setText(FilterMessages.getString("CustomFiltersDialog.description.label")); //$NON-NLS-1$ - final Text description= new Text(parent, SWT.LEFT | SWT.WRAP | SWT.MULTI | SWT.READ_ONLY | SWT.BORDER | SWT.V_SCROLL); + info = new Label(parent, SWT.LEFT); + info.setText(FilterMessages + .getString("CustomFiltersDialog.description.label")); //$NON-NLS-1$ + final Text description = new Text(parent, SWT.LEFT | SWT.WRAP + | SWT.MULTI | SWT.READ_ONLY | SWT.BORDER | SWT.V_SCROLL); data = new GridData(GridData.FILL_HORIZONTAL); - data.heightHint= convertHeightInCharsToPixels(3); + data.heightHint = convertHeightInCharsToPixels(3); description.setLayoutData(data); - fCheckBoxList.addSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - ISelection selection= event.getSelection(); - if (selection instanceof IStructuredSelection) { - Object selectedElement= ((IStructuredSelection)selection).getFirstElement(); - if (selectedElement instanceof FilterDescriptor) - description.setText(((FilterDescriptor)selectedElement).getDescription()); - } - } - }); + fCheckBoxList + .addSelectionChangedListener(new ISelectionChangedListener() { + public void selectionChanged(SelectionChangedEvent event) { + ISelection selection = event.getSelection(); + if (selection instanceof IStructuredSelection) { + Object selectedElement = ((IStructuredSelection) selection) + .getFirstElement(); + if (selectedElement instanceof FilterDescriptor) + description + .setText(((FilterDescriptor) selectedElement) + .getDescription()); + } + } + }); fCheckBoxList.addCheckStateListener(new ICheckStateListener() { /* * @see org.eclipse.jface.viewers.ICheckStateListener#checkStateChanged(org.eclipse.jface.viewers.CheckStateChangedEvent) */ public void checkStateChanged(CheckStateChangedEvent event) { - Object element= event.getElement(); + Object element = event.getElement(); if (element instanceof FilterDescriptor) { // renew if already touched if (fFilterDescriptorChangeHistory.contains(element)) fFilterDescriptorChangeHistory.remove(element); fFilterDescriptorChangeHistory.push(element); } - }}); + } + }); addSelectionButtons(parent); } private void addSelectionButtons(Composite composite) { - Composite buttonComposite= new Composite(composite, SWT.RIGHT); - GridLayout layout= new GridLayout(); - layout.numColumns= 2; + Composite buttonComposite = new Composite(composite, SWT.RIGHT); + GridLayout layout = new GridLayout(); + layout.numColumns = 2; buttonComposite.setLayout(layout); - GridData data= new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.GRAB_HORIZONTAL); - data.grabExcessHorizontalSpace= true; + GridData data = new GridData(GridData.HORIZONTAL_ALIGN_END + | GridData.GRAB_HORIZONTAL); + data.grabExcessHorizontalSpace = true; composite.setData(data); // Select All button - String label= FilterMessages.getString("CustomFiltersDialog.SelectAllButton.label"); //$NON-NLS-1$ - Button selectButton= createButton(buttonComposite, IDialogConstants.SELECT_ALL_ID, label, false); + String label = FilterMessages + .getString("CustomFiltersDialog.SelectAllButton.label"); //$NON-NLS-1$ + Button selectButton = createButton(buttonComposite, + IDialogConstants.SELECT_ALL_ID, label, false); SWTUtil.setButtonDimensionHint(selectButton); - SelectionListener listener= new SelectionAdapter() { + SelectionListener listener = new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { fCheckBoxList.setAllChecked(true); fFilterDescriptorChangeHistory.clear(); - for (int i= 0; i < fBuiltInFilters.length; i++) + for (int i = 0; i < fBuiltInFilters.length; i++) fFilterDescriptorChangeHistory.push(fBuiltInFilters[i]); } }; selectButton.addSelectionListener(listener); // De-select All button - label= FilterMessages.getString("CustomFiltersDialog.DeselectAllButton.label"); //$NON-NLS-1$ - Button deselectButton= createButton(buttonComposite, IDialogConstants.DESELECT_ALL_ID, label, false); + label = FilterMessages + .getString("CustomFiltersDialog.DeselectAllButton.label"); //$NON-NLS-1$ + Button deselectButton = createButton(buttonComposite, + IDialogConstants.DESELECT_ALL_ID, label, false); SWTUtil.setButtonDimensionHint(deselectButton); - listener= new SelectionAdapter() { + listener = new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { fCheckBoxList.setAllChecked(false); fFilterDescriptorChangeHistory.clear(); - for (int i= 0; i < fBuiltInFilters.length; i++) + for (int i = 0; i < fBuiltInFilters.length; i++) fFilterDescriptorChangeHistory.push(fBuiltInFilters[i]); } }; @@ -259,15 +282,15 @@ public class CustomFiltersDialog extends SelectionDialog { } private void checkInitialSelections() { - Iterator itemsToCheck= getInitialElementSelections().iterator(); + Iterator itemsToCheck = getInitialElementSelections().iterator(); while (itemsToCheck.hasNext()) - fCheckBoxList.setChecked(itemsToCheck.next(),true); + fCheckBoxList.setChecked(itemsToCheck.next(), true); } protected void okPressed() { if (fBuiltInFilters != null) { - ArrayList result= new ArrayList(); - for (int i= 0; i < fBuiltInFilters.length; ++i) { + ArrayList result = new ArrayList(); + for (int i = 0; i < fBuiltInFilters.length; ++i) { if (fCheckBoxList.getChecked(fBuiltInFilters[i])) result.add(fBuiltInFilters[i]); } @@ -277,18 +300,18 @@ public class CustomFiltersDialog extends SelectionDialog { } private ILabelProvider createLabelPrivder() { - return - new LabelProvider() { - public Image getImage(Object element) { + return new LabelProvider() { + public Image getImage(Object element) { + return null; + } + + public String getText(Object element) { + if (element instanceof FilterDescriptor) + return ((FilterDescriptor) element).getName(); + else return null; - } - public String getText(Object element) { - if (element instanceof FilterDescriptor) - return ((FilterDescriptor)element).getName(); - else - return null; - } - }; + } + }; } // ---------- result handling ---------- @@ -296,15 +319,15 @@ public class CustomFiltersDialog extends SelectionDialog { protected void setResult(List newResult) { super.setResult(newResult); if (fUserDefinedPatterns.getText().length() > 0) { - fEnablePatterns= fEnableUserDefinedPatterns.getSelection(); - fPatterns= convertFromString(fUserDefinedPatterns.getText(), SEPARATOR); + fEnablePatterns = fEnableUserDefinedPatterns.getSelection(); + fPatterns = convertFromString(fUserDefinedPatterns.getText(), + SEPARATOR); } else { - fEnablePatterns= false; - fPatterns= new String[0]; + fEnablePatterns = false; + fPatterns = new String[0]; } } - /** * @return the patterns which have been entered by the user */ @@ -316,10 +339,10 @@ public class CustomFiltersDialog extends SelectionDialog { * @return the Ids of the enabled built-in filters */ public String[] getEnabledFilterIds() { - Object[] result= getResult(); - Set enabledIds= new HashSet(result.length); - for (int i= 0; i < result.length; i++) - enabledIds.add(((FilterDescriptor)result[i]).getId()); + Object[] result = getResult(); + Set enabledIds = new HashSet(result.length); + for (int i = 0; i < result.length; i++) + enabledIds.add(((FilterDescriptor) result[i]).getId()); return (String[]) enabledIds.toArray(new String[enabledIds.size()]); } @@ -339,62 +362,63 @@ public class CustomFiltersDialog extends SelectionDialog { } private FilterDescriptor[] getEnabledFilterDescriptors() { - FilterDescriptor[] filterDescs= fBuiltInFilters; - List result= new ArrayList(filterDescs.length); - List enabledFilterIds= Arrays.asList(fEnabledFilterIds); - for (int i= 0; i < filterDescs.length; i++) { - String id= filterDescs[i].getId(); + FilterDescriptor[] filterDescs = fBuiltInFilters; + List result = new ArrayList(filterDescs.length); + List enabledFilterIds = Arrays.asList(fEnabledFilterIds); + for (int i = 0; i < filterDescs.length; i++) { + String id = filterDescs[i].getId(); if (enabledFilterIds.contains(id)) result.add(filterDescs[i]); } - return (FilterDescriptor[])result.toArray(new FilterDescriptor[result.size()]); + return (FilterDescriptor[]) result.toArray(new FilterDescriptor[result + .size()]); } - public static String[] convertFromString(String patterns, String separator) { - StringTokenizer tokenizer= new StringTokenizer(patterns, separator, true); - int tokenCount= tokenizer.countTokens(); - List result= new ArrayList(tokenCount); - boolean escape= false; - boolean append= false; + StringTokenizer tokenizer = new StringTokenizer(patterns, separator, + true); + int tokenCount = tokenizer.countTokens(); + List result = new ArrayList(tokenCount); + boolean escape = false; + boolean append = false; while (tokenizer.hasMoreTokens()) { - String token= tokenizer.nextToken().trim(); + String token = tokenizer.nextToken().trim(); if (separator.equals(token)) { if (!escape) - escape= true; + escape = true; else { addPattern(result, separator); - append= true; + append = true; } - } else { + } else { if (!append) - result.add(token); + result.add(token); else addPattern(result, token); - append= false; - escape= false; + append = false; + escape = false; } } - return (String[])result.toArray(new String[result.size()]); + return (String[]) result.toArray(new String[result.size()]); } private static void addPattern(List list, String pattern) { if (list.isEmpty()) list.add(pattern); else { - int index= list.size() - 1; - list.set(index, ((String)list.get(index)) + pattern); + int index = list.size() - 1; + list.set(index, ((String) list.get(index)) + pattern); } } public static String convertToString(String[] patterns, String separator) { - int length= patterns.length; - StringBuffer strBuf= new StringBuffer(); + int length = patterns.length; + StringBuffer strBuf = new StringBuffer(); if (length > 0) strBuf.append(escapeSeparator(patterns[0], separator)); else return ""; //$NON-NLS-1$ - int i= 1; + int i = 1; while (i < length) { strBuf.append(separator); strBuf.append(" "); //$NON-NLS-1$ @@ -404,10 +428,10 @@ public class CustomFiltersDialog extends SelectionDialog { } private static String escapeSeparator(String pattern, String separator) { - int length= pattern.length(); - StringBuffer buf= new StringBuffer(length); - for (int i= 0; i < length; i++) { - char ch= pattern.charAt(i); //$NON-NLS-1$ + int length = pattern.length(); + StringBuffer buf = new StringBuffer(length); + for (int i = 0; i < length; i++) { + char ch = pattern.charAt(i); //$NON-NLS-1$ if (separator.equals(String.valueOf(ch))) buf.append(ch); buf.append(ch); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/FilterDescriptor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/FilterDescriptor.java index 2d21450..86e4830 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/FilterDescriptor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/FilterDescriptor.java @@ -37,32 +37,38 @@ import org.eclipse.ui.activities.WorkbenchActivityHelper; */ public class FilterDescriptor implements Comparable, IPluginContribution { - private static String PATTERN_FILTER_ID_PREFIX= "_patternFilterId_"; //$NON-NLS-1$ + private static String PATTERN_FILTER_ID_PREFIX = "_patternFilterId_"; //$NON-NLS-1$ + private static final String EXTENSION_POINT_NAME = "phpElementFilters"; //$NON-NLS-1$ - private static final String EXTENSION_POINT_NAME= "phpElementFilters"; //$NON-NLS-1$ + private static final String FILTER_TAG = "filter"; //$NON-NLS-1$ - private static final String FILTER_TAG= "filter"; //$NON-NLS-1$ + private static final String PATTERN_ATTRIBUTE = "pattern"; //$NON-NLS-1$ + + private static final String ID_ATTRIBUTE = "id"; //$NON-NLS-1$ - private static final String PATTERN_ATTRIBUTE= "pattern"; //$NON-NLS-1$ - private static final String ID_ATTRIBUTE= "id"; //$NON-NLS-1$ /** * @deprecated as of 3.0 use {@link FilterDescriptor#TARGET_ID_ATTRIBUTE} */ - private static final String VIEW_ID_ATTRIBUTE= "viewId"; //$NON-NLS-1$ - private static final String TARGET_ID_ATTRIBUTE= "targetId"; //$NON-NLS-1$ - private static final String CLASS_ATTRIBUTE= "class"; //$NON-NLS-1$ - private static final String NAME_ATTRIBUTE= "name"; //$NON-NLS-1$ - private static final String ENABLED_ATTRIBUTE= "enabled"; //$NON-NLS-1$ - private static final String DESCRIPTION_ATTRIBUTE= "description"; //$NON-NLS-1$ + private static final String VIEW_ID_ATTRIBUTE = "viewId"; //$NON-NLS-1$ + + private static final String TARGET_ID_ATTRIBUTE = "targetId"; //$NON-NLS-1$ + + private static final String CLASS_ATTRIBUTE = "class"; //$NON-NLS-1$ + + private static final String NAME_ATTRIBUTE = "name"; //$NON-NLS-1$ + + private static final String ENABLED_ATTRIBUTE = "enabled"; //$NON-NLS-1$ + + private static final String DESCRIPTION_ATTRIBUTE = "description"; //$NON-NLS-1$ + /** - * @deprecated use "enabled" instead + * @deprecated use "enabled" instead */ - private static final String SELECTED_ATTRIBUTE= "selected"; //$NON-NLS-1$ + private static final String SELECTED_ATTRIBUTE = "selected"; //$NON-NLS-1$ private static FilterDescriptor[] fgFilterDescriptors; - private IConfigurationElement fElement; /** @@ -70,76 +76,91 @@ public class FilterDescriptor implements Comparable, IPluginContribution { */ public static FilterDescriptor[] getFilterDescriptors() { if (fgFilterDescriptors == null) { - IExtensionRegistry registry= Platform.getExtensionRegistry(); - IConfigurationElement[] elements= registry.getConfigurationElementsFor(PHPeclipsePlugin.PLUGIN_ID, EXTENSION_POINT_NAME); - fgFilterDescriptors= createFilterDescriptors(elements); - } + IExtensionRegistry registry = Platform.getExtensionRegistry(); + IConfigurationElement[] elements = registry + .getConfigurationElementsFor(PHPeclipsePlugin.PLUGIN_ID, + EXTENSION_POINT_NAME); + fgFilterDescriptors = createFilterDescriptors(elements); + } return fgFilterDescriptors; - } + } + /** - * Returns all Java element filters which - * are contributed to the given view. + * Returns all Java element filters which are contributed to the given view. */ public static FilterDescriptor[] getFilterDescriptors(String targetId) { - FilterDescriptor[] filterDescs= FilterDescriptor.getFilterDescriptors(); - List result= new ArrayList(filterDescs.length); - for (int i= 0; i < filterDescs.length; i++) { - String tid= filterDescs[i].getTargetId(); + FilterDescriptor[] filterDescs = FilterDescriptor + .getFilterDescriptors(); + List result = new ArrayList(filterDescs.length); + for (int i = 0; i < filterDescs.length; i++) { + String tid = filterDescs[i].getTargetId(); if (WorkbenchActivityHelper.filterItem(filterDescs[i])) continue; if (tid == null || tid.equals(targetId)) result.add(filterDescs[i]); } - return (FilterDescriptor[])result.toArray(new FilterDescriptor[result.size()]); + return (FilterDescriptor[]) result.toArray(new FilterDescriptor[result + .size()]); } - + /** * Creates a new filter descriptor for the given configuration element. */ private FilterDescriptor(IConfigurationElement element) { - fElement= element; + fElement = element; // it is either a pattern filter or a custom filter - Assert.isTrue(isPatternFilter() ^ isCustomFilter(), "An extension for extension-point net.sourceforge.phpdt.ui.javaElementFilters does not specify a correct filter"); //$NON-NLS-1$ - Assert.isNotNull(getId(), "An extension for extension-point net.sourceforge.phpdt.ui.javaElementFilters does not provide a valid ID"); //$NON-NLS-1$ - Assert.isNotNull(getName(), "An extension for extension-point net.sourceforge.phpdt.ui.javaElementFilters does not provide a valid name"); //$NON-NLS-1$ + Assert + .isTrue( + isPatternFilter() ^ isCustomFilter(), + "An extension for extension-point net.sourceforge.phpdt.ui.javaElementFilters does not specify a correct filter"); //$NON-NLS-1$ + Assert + .isNotNull( + getId(), + "An extension for extension-point net.sourceforge.phpdt.ui.javaElementFilters does not provide a valid ID"); //$NON-NLS-1$ + Assert + .isNotNull( + getName(), + "An extension for extension-point net.sourceforge.phpdt.ui.javaElementFilters does not provide a valid name"); //$NON-NLS-1$ } /** - * Creates a new ViewerFilter. - * This method is only valid for viewer filters. + * Creates a new ViewerFilter. This method is only valid for + * viewer filters. */ public ViewerFilter createViewerFilter() { if (!isCustomFilter()) return null; - - final ViewerFilter[] result= new ViewerFilter[1]; - String message= FilterMessages.getFormattedString("FilterDescriptor.filterCreationError.message", getId()); //$NON-NLS-1$ - ISafeRunnable code= new SafeRunnable(message) { + + final ViewerFilter[] result = new ViewerFilter[1]; + String message = FilterMessages.getFormattedString( + "FilterDescriptor.filterCreationError.message", getId()); //$NON-NLS-1$ + ISafeRunnable code = new SafeRunnable(message) { /* * @see org.eclipse.core.runtime.ISafeRunnable#run() */ public void run() throws Exception { - result[0]= (ViewerFilter)fElement.createExecutableExtension(CLASS_ATTRIBUTE); + result[0] = (ViewerFilter) fElement + .createExecutableExtension(CLASS_ATTRIBUTE); } - + }; Platform.run(code); return result[0]; } - - //---- XML Attribute accessors --------------------------------------------- - + + // ---- XML Attribute accessors + // --------------------------------------------- + /** * Returns the filter's id. *

                                                      - * This attribute is mandatory for custom filters. - * The ID for pattern filters is - * PATTERN_FILTER_ID_PREFIX plus the pattern itself. + * This attribute is mandatory for custom filters. The ID for pattern + * filters is PATTERN_FILTER_ID_PREFIX plus the pattern itself. *

                                                      */ public String getId() { if (isPatternFilter()) { - String targetId= getTargetId(); + String targetId = getTargetId(); if (targetId == null) return PATTERN_FILTER_ID_PREFIX + getPattern(); else @@ -147,25 +168,26 @@ public class FilterDescriptor implements Comparable, IPluginContribution { } else return fElement.getAttribute(ID_ATTRIBUTE); } - + /** * Returns the filter's name. *

                                                      - * If the name of a pattern filter is missing - * then the pattern is used as its name. + * If the name of a pattern filter is missing then the pattern is used as + * its name. *

                                                      */ public String getName() { - String name= fElement.getAttribute(NAME_ATTRIBUTE); + String name = fElement.getAttribute(NAME_ATTRIBUTE); if (name == null && isPatternFilter()) - name= getPattern(); + name = getPattern(); return name; } /** * Returns the filter's pattern. * - * @return the pattern string or null if it's not a pattern filter + * @return the pattern string or null if it's not a pattern + * filter */ public String getPattern() { return fElement.getAttribute(PATTERN_ATTRIBUTE); @@ -178,25 +200,26 @@ public class FilterDescriptor implements Comparable, IPluginContribution { * @since 3.0 */ public String getTargetId() { - String tid= fElement.getAttribute(TARGET_ID_ATTRIBUTE); - + String tid = fElement.getAttribute(TARGET_ID_ATTRIBUTE); + if (tid != null) return tid; - + // Backwards compatibility code return fElement.getAttribute(VIEW_ID_ATTRIBUTE); - + } /** * Returns the filter's description. * - * @return the description or null if no description is provided + * @return the description or null if no description is + * provided */ public String getDescription() { - String description= fElement.getAttribute(DESCRIPTION_ATTRIBUTE); + String description = fElement.getAttribute(DESCRIPTION_ATTRIBUTE); if (description == null) - description= ""; //$NON-NLS-1$ + description = ""; //$NON-NLS-1$ return description; } @@ -215,47 +238,51 @@ public class FilterDescriptor implements Comparable, IPluginContribution { } /** - * Returns true if the filter - * is initially enabled. + * Returns true if the filter is initially enabled. * * This attribute is optional and defaults to true. */ public boolean isEnabled() { - String strVal= fElement.getAttribute(ENABLED_ATTRIBUTE); + String strVal = fElement.getAttribute(ENABLED_ATTRIBUTE); if (strVal == null) // backward compatibility - strVal= fElement.getAttribute(SELECTED_ATTRIBUTE); + strVal = fElement.getAttribute(SELECTED_ATTRIBUTE); return strVal == null || Boolean.valueOf(strVal).booleanValue(); } - /* - * Implements a method from IComparable - */ + /* + * Implements a method from IComparable + */ public int compareTo(Object o) { if (o instanceof FilterDescriptor) - return Collator.getInstance().compare(getName(), ((FilterDescriptor)o).getName()); + return Collator.getInstance().compare(getName(), + ((FilterDescriptor) o).getName()); else return Integer.MIN_VALUE; } - //---- initialization --------------------------------------------------- - + // ---- initialization --------------------------------------------------- + /** * Creates the filter descriptors. */ - private static FilterDescriptor[] createFilterDescriptors(IConfigurationElement[] elements) { - List result= new ArrayList(5); - Set descIds= new HashSet(5); - for (int i= 0; i < elements.length; i++) { - final IConfigurationElement element= elements[i]; + private static FilterDescriptor[] createFilterDescriptors( + IConfigurationElement[] elements) { + List result = new ArrayList(5); + Set descIds = new HashSet(5); + for (int i = 0; i < elements.length; i++) { + final IConfigurationElement element = elements[i]; if (FILTER_TAG.equals(element.getName())) { - final FilterDescriptor[] desc= new FilterDescriptor[1]; - Platform.run(new SafeRunnable(FilterMessages.getString("FilterDescriptor.filterDescriptionCreationError.message")) { //$NON-NLS-1$ - public void run() throws Exception { - desc[0]= new FilterDescriptor(element); - } - }); + final FilterDescriptor[] desc = new FilterDescriptor[1]; + Platform + .run(new SafeRunnable( + FilterMessages + .getString("FilterDescriptor.filterDescriptionCreationError.message")) { //$NON-NLS-1$ + public void run() throws Exception { + desc[0] = new FilterDescriptor(element); + } + }); if (desc[0] != null && !descIds.contains(desc[0].getId())) { result.add(desc[0]); @@ -264,15 +291,16 @@ public class FilterDescriptor implements Comparable, IPluginContribution { } } Collections.sort(result); - return (FilterDescriptor[])result.toArray(new FilterDescriptor[result.size()]); + return (FilterDescriptor[]) result.toArray(new FilterDescriptor[result + .size()]); } - + public String getLocalId() { return fElement.getAttribute(ID_ATTRIBUTE); } - public String getPluginId() { - return fElement.getDeclaringExtension().getNamespace(); - } + public String getPluginId() { + return fElement.getDeclaringExtension().getNamespace(); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/FilterMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/FilterMessages.java index df8ba85..7ed3444 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/FilterMessages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/FilterMessages.java @@ -16,9 +16,11 @@ import java.util.ResourceBundle; public class FilterMessages { - private static final String RESOURCE_BUNDLE= FilterMessages.class.getName(); + private static final String RESOURCE_BUNDLE = FilterMessages.class + .getName(); - private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); + private static ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); private FilterMessages() { } @@ -30,15 +32,17 @@ public class FilterMessages { return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$ } } + /** * Gets a string from the resource bundle and formats it with the argument * - * @param key the string used to get the bundle value, must not be null + * @param key + * the string used to get the bundle value, must not be null */ public static String getFormattedString(String key, Object[] args) { - String format= null; + String format = null; try { - format= fgResourceBundle.getString(key); + format = fgResourceBundle.getString(key); } catch (MissingResourceException e) { return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$ } @@ -48,17 +52,18 @@ public class FilterMessages { /** * Gets a string from the resource bundle and formats it with the argument * - * @param key the string used to get the bundle value, must not be null + * @param key + * the string used to get the bundle value, must not be null */ public static String getFormattedString(String key, Object arg) { - String format= null; + String format = null; try { - format= fgResourceBundle.getString(key); + format = fgResourceBundle.getString(key); } catch (MissingResourceException e) { return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$ } if (arg == null) - arg= ""; //$NON-NLS-1$ + arg = ""; //$NON-NLS-1$ return MessageFormat.format(format, new Object[] { arg }); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/ImportDeclarationFilter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/ImportDeclarationFilter.java index 32c0168..c317b54 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/ImportDeclarationFilter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/ImportDeclarationFilter.java @@ -10,14 +10,12 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.ui.filters; - import net.sourceforge.phpdt.core.IImportContainer; import net.sourceforge.phpdt.core.IImportDeclaration; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; - /** * Filters import declarations */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/InterfaceFilter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/InterfaceFilter.java index c222a2b..cfe35e1 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/InterfaceFilter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/InterfaceFilter.java @@ -10,14 +10,12 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.ui.filters; - import net.sourceforge.phpdt.core.IType; import net.sourceforge.phpdt.core.JavaModelException; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; - /** * Filters interfaces */ @@ -29,7 +27,7 @@ public class InterfaceFilter extends ViewerFilter { public boolean select(Viewer viewer, Object parent, Object element) { if (element instanceof IType) { try { - return !((IType)element).isInterface(); + return !((IType) element).isInterface(); } catch (JavaModelException ex) { return true; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/JavaFileFilter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/JavaFileFilter.java index c26c244..d406dc8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/JavaFileFilter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/JavaFileFilter.java @@ -15,31 +15,30 @@ import net.sourceforge.phpdt.core.ICompilationUnit; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; - /** * Filters out all compilation units and class files elements. */ -public class JavaFileFilter extends ViewerFilter { - +public class JavaFileFilter extends ViewerFilter { + /** - * Returns the result of this filter, when applied to the - * given inputs. - * - * @param inputs the set of elements to + * Returns the result of this filter, when applied to the given inputs. + * + * @param inputs + * the set of elements to * @return Returns true if element should be included in filtered set */ public boolean select(Viewer viewer, Object parent, Object element) { if (element instanceof ICompilationUnit) return false; -// if (element instanceof IClassFile) -// return false; - -// if (element instanceof IPackageFragment) -// try { -// return ((IPackageFragment)element).getNonJavaResources().length > 0; -// } catch (JavaModelException ex) { -// return true; -// } - return true; + // if (element instanceof IClassFile) + // return false; + + // if (element instanceof IPackageFragment) + // try { + // return ((IPackageFragment)element).getNonJavaResources().length > 0; + // } catch (JavaModelException ex) { + // return true; + // } + return true; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/NamePatternFilter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/NamePatternFilter.java index 8b7fdfa..f1dc30a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/NamePatternFilter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/NamePatternFilter.java @@ -19,55 +19,56 @@ import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; /** - * The NamePatternFilter selects the elements which - * match the given string patterns. + * The NamePatternFilter selects the elements which match the given string + * patterns. *

                                                      - * The following characters have special meaning: - * ? => any character - * * => any string + * The following characters have special meaning: ? => any character * => any + * string *

                                                      * * @since 2.0 */ public class NamePatternFilter extends ViewerFilter { private String[] fPatterns; + private StringMatcher[] fMatchers; - + /** * Return the currently configured StringMatchers. */ private StringMatcher[] getMatchers() { return fMatchers; } - + /** * Gets the patterns for the receiver. */ public String[] getPatterns() { return fPatterns; } - - - /* (non-Javadoc) - * Method declared on ViewerFilter. + + /* + * (non-Javadoc) Method declared on ViewerFilter. */ public boolean select(Viewer viewer, Object parentElement, Object element) { - String matchName= null; + String matchName = null; if (element instanceof IJavaElement) { - matchName= ((IJavaElement) element).getElementName(); + matchName = ((IJavaElement) element).getElementName(); } else if (element instanceof IAdaptable) { - IAdaptable adaptable= (IAdaptable) element; - IJavaElement javaElement= (IJavaElement)adaptable.getAdapter(IJavaElement.class); + IAdaptable adaptable = (IAdaptable) element; + IJavaElement javaElement = (IJavaElement) adaptable + .getAdapter(IJavaElement.class); if (javaElement != null) - matchName= javaElement.getElementName(); + matchName = javaElement.getElementName(); else { - IResource resource= (IResource)adaptable.getAdapter(IResource.class); + IResource resource = (IResource) adaptable + .getAdapter(IResource.class); if (resource != null) - matchName= resource.getName(); + matchName = resource.getName(); } } if (matchName != null) { - StringMatcher[] testMatchers= getMatchers(); + StringMatcher[] testMatchers = getMatchers(); for (int i = 0; i < testMatchers.length; i++) { if (testMatchers[i].match(matchName)) return false; @@ -76,21 +77,20 @@ public class NamePatternFilter extends ViewerFilter { } return true; } - + /** * Sets the patterns to filter out for the receiver. *

                                                      - * The following characters have special meaning: - * ? => any character - * * => any string + * The following characters have special meaning: ? => any character * => + * any string *

                                                      */ public void setPatterns(String[] newPatterns) { fPatterns = newPatterns; fMatchers = new StringMatcher[newPatterns.length]; for (int i = 0; i < newPatterns.length; i++) { - //Reset the matchers to prevent constructor overhead - fMatchers[i]= new StringMatcher(newPatterns[i], true, false); + // Reset the matchers to prevent constructor overhead + fMatchers[i] = new StringMatcher(newPatterns[i], true, false); } } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/NonJavaElementFilter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/NonJavaElementFilter.java index 14abb23..90c9fdf 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/NonJavaElementFilter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/NonJavaElementFilter.java @@ -18,32 +18,32 @@ import org.eclipse.core.resources.IStorage; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; - /** * Filters out all non-Java elements. */ -public class NonJavaElementFilter extends ViewerFilter { - +public class NonJavaElementFilter extends ViewerFilter { + /** - * Returns the result of this filter, when applied to the - * given inputs. - * - * @param inputs the set of elements to + * Returns the result of this filter, when applied to the given inputs. + * + * @param inputs + * the set of elements to * @return Returns true if element should be included in filtered set */ public boolean select(Viewer viewer, Object parent, Object element) { if (element instanceof IJavaElement) return true; - + if (element instanceof IResource) { - IProject project= ((IResource)element).getProject(); + IProject project = ((IResource) element).getProject(); return project == null || !project.isOpen(); } - // Exclude all IStorage elements which are neither Java elements nor resources + // Exclude all IStorage elements which are neither Java elements nor + // resources if (element instanceof IStorage) return false; - + return true; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/NonJavaProjectsFilter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/NonJavaProjectsFilter.java index a7eedde..2d3c49a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/NonJavaProjectsFilter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/NonJavaProjectsFilter.java @@ -10,7 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.ui.filters; - import net.sourceforge.phpdt.core.IJavaProject; import org.eclipse.core.resources.IProject; @@ -29,8 +28,8 @@ public class NonJavaProjectsFilter extends ViewerFilter { if (element instanceof IJavaProject) return true; else if (element instanceof IProject) - return !((IProject)element).isOpen(); + return !((IProject) element).isOpen(); - return true; + return true; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/NonPublicTypeFilter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/NonPublicTypeFilter.java index fdfe038..28706d9 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/NonPublicTypeFilter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/NonPublicTypeFilter.java @@ -10,7 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.ui.filters; - import net.sourceforge.phpdt.core.Flags; import net.sourceforge.phpdt.core.IType; import net.sourceforge.phpdt.core.JavaModelException; @@ -18,7 +17,6 @@ import net.sourceforge.phpdt.core.JavaModelException; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; - /** * Filters non-public types */ @@ -29,7 +27,7 @@ public class NonPublicTypeFilter extends ViewerFilter { */ public boolean select(Viewer viewer, Object parent, Object element) { if (element instanceof IType) { - IType type= (IType)element; + IType type = (IType) element; try { return Flags.isPublic(type.getFlags()); } catch (JavaModelException ex) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/NonSharedProjectFilter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/NonSharedProjectFilter.java index f824df1..f9a78e3 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/NonSharedProjectFilter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/NonSharedProjectFilter.java @@ -10,7 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.ui.filters; - import net.sourceforge.phpdt.core.IJavaProject; import org.eclipse.core.resources.IProject; @@ -31,14 +30,14 @@ public class NonSharedProjectFilter extends ViewerFilter { */ public boolean select(Viewer viewer, Object parent, Object element) { if (element instanceof IProject) - return isSharedProject((IProject)element); - + return isSharedProject((IProject) element); + if (element instanceof IJavaProject) - return isSharedProject(((IJavaProject)element).getProject()); + return isSharedProject(((IJavaProject) element).getProject()); return true; } - + private boolean isSharedProject(IProject project) { return !project.isAccessible() || RepositoryProvider.isShared(project); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/OutputFolderFilter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/OutputFolderFilter.java index c9c4781..579511f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/OutputFolderFilter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/OutputFolderFilter.java @@ -10,7 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.ui.filters; - import net.sourceforge.phpdt.core.IClasspathEntry; import net.sourceforge.phpdt.core.IJavaProject; import net.sourceforge.phpdt.core.JavaCore; @@ -23,49 +22,50 @@ import org.eclipse.core.runtime.IPath; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; - -/** +/** * Filters out all output folders. *

                                                      - * Note: Folder which are direct children of a Java element - * are already filtered by the Java Model. + * Note: Folder which are direct children of a Java element are already filtered + * by the Java Model. *

                                                      * * @since 3.0 */ public class OutputFolderFilter extends ViewerFilter { - + /** - * Returns the result of this filter, when applied to the - * given element. - * - * @param element the element to test + * Returns the result of this filter, when applied to the given element. + * + * @param element + * the element to test * @return true if element should be included * @since 3.0 */ public boolean select(Viewer viewer, Object parent, Object element) { if (element instanceof IFolder) { - IFolder folder= (IFolder)element; - IProject proj= folder.getProject(); + IFolder folder = (IFolder) element; + IProject proj = folder.getProject(); try { if (!proj.hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) return true; - - IJavaProject jProject= JavaCore.create(folder.getProject()); + + IJavaProject jProject = JavaCore.create(folder.getProject()); if (jProject == null || !jProject.exists()) return true; - + // Check default output location - IPath defaultOutputLocation= jProject.getOutputLocation(); - IPath folderPath= folder.getFullPath(); - if (defaultOutputLocation != null && defaultOutputLocation.equals(folderPath)) + IPath defaultOutputLocation = jProject.getOutputLocation(); + IPath folderPath = folder.getFullPath(); + if (defaultOutputLocation != null + && defaultOutputLocation.equals(folderPath)) return false; - + // Check output location for each class path entry - IClasspathEntry[] cpEntries= jProject.getRawClasspath(); - for (int i= 0, length= cpEntries.length; i < length; i++) { - IPath outputLocation= cpEntries[i].getOutputLocation(); - if (outputLocation != null && outputLocation.equals(folderPath)) + IClasspathEntry[] cpEntries = jProject.getRawClasspath(); + for (int i = 0, length = cpEntries.length; i < length; i++) { + IPath outputLocation = cpEntries[i].getOutputLocation(); + if (outputLocation != null + && outputLocation.equals(folderPath)) return false; } } catch (CoreException ex) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/phpdocexport/JavadocExportMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/phpdocexport/JavadocExportMessages.java index 56212a8..b6a785b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/phpdocexport/JavadocExportMessages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/phpdocexport/JavadocExportMessages.java @@ -16,8 +16,11 @@ import java.util.ResourceBundle; public class JavadocExportMessages { - private static final String RESOURCE_BUNDLE= JavadocExportMessages.class.getName(); - private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); + private static final String RESOURCE_BUNDLE = JavadocExportMessages.class + .getName(); + + private static ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); private JavadocExportMessages() { } @@ -29,23 +32,22 @@ public class JavadocExportMessages { return '!' + key + '!'; } } - + /** * Gets a string from the resource bundle and formats it with the argument * - * @param key the string used to get the bundle value, must not be null + * @param key + * the string used to get the bundle value, must not be null */ public static String getFormattedString(String key, Object arg) { return MessageFormat.format(getString(key), new Object[] { arg }); } - /** * Gets a string from the resource bundle and formats it with arguments - */ + */ public static String getFormattedString(String key, Object[] args) { return MessageFormat.format(getString(key), args); } - } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/AbstractConfigurationBlockPreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/AbstractConfigurationBlockPreferencePage.java index a290827..2746a17 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/AbstractConfigurationBlockPreferencePage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/AbstractConfigurationBlockPreferencePage.java @@ -21,20 +21,18 @@ import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.PlatformUI; - - /** * Abstract preference page which is used to wrap a * {@link net.sourceforge.phpdt.internal.ui.preferences.IPreferenceConfigurationBlock}. - * + * * @since 3.0 */ -public abstract class AbstractConfigurationBlockPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { - +public abstract class AbstractConfigurationBlockPreferencePage extends + PreferencePage implements IWorkbenchPreferencePage { private IPreferenceConfigurationBlock fConfigurationBlock; - private OverlayPreferenceStore fOverlayStore; + private OverlayPreferenceStore fOverlayStore; /** * Creates a new preference page. @@ -42,13 +40,18 @@ public abstract class AbstractConfigurationBlockPreferencePage extends Preferenc public AbstractConfigurationBlockPreferencePage() { setDescription(); setPreferenceStore(); - fOverlayStore= new OverlayPreferenceStore(getPreferenceStore(), new OverlayPreferenceStore.OverlayKey[] {}); - fConfigurationBlock= createConfigurationBlock(fOverlayStore); + fOverlayStore = new OverlayPreferenceStore(getPreferenceStore(), + new OverlayPreferenceStore.OverlayKey[] {}); + fConfigurationBlock = createConfigurationBlock(fOverlayStore); } - protected abstract IPreferenceConfigurationBlock createConfigurationBlock(OverlayPreferenceStore overlayPreferenceStore); + protected abstract IPreferenceConfigurationBlock createConfigurationBlock( + OverlayPreferenceStore overlayPreferenceStore); + protected abstract String getHelpId(); + protected abstract void setDescription(); + protected abstract void setPreferenceStore(); /* @@ -62,7 +65,8 @@ public abstract class AbstractConfigurationBlockPreferencePage extends Preferenc */ public void createControl(Composite parent) { super.createControl(parent); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), getHelpId()); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), + getHelpId()); } /* @@ -85,7 +89,7 @@ public abstract class AbstractConfigurationBlockPreferencePage extends Preferenc fConfigurationBlock.initialize(); } - /* + /* * @see PreferencePage#performOk() */ public boolean performOk() { @@ -119,7 +123,7 @@ public abstract class AbstractConfigurationBlockPreferencePage extends Preferenc if (fOverlayStore != null) { fOverlayStore.stop(); - fOverlayStore= null; + fOverlayStore = null; } super.dispose(); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeAssistConfigurationBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeAssistConfigurationBlock.java index f51f0da..1a116f6 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeAssistConfigurationBlock.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeAssistConfigurationBlock.java @@ -48,101 +48,168 @@ import org.eclipse.swt.widgets.Text; */ class CodeAssistConfigurationBlock implements IPreferenceConfigurationBlock { - private OverlayPreferenceStore fStore; + private PreferencePage fMainPreferencePage; - + private List fContentAssistColorList; + private ColorEditor fContentAssistColorEditor; - private Control fAutoInsertDelayText; - private Control fAutoInsertJavaTriggerText; - private Control fAutoInsertJavaDocTriggerText; - private Control fAutoInsertHTMLTriggerText; + + private Control fAutoInsertDelayText; + + private Control fAutoInsertJavaTriggerText; + + private Control fAutoInsertJavaDocTriggerText; + + private Control fAutoInsertHTMLTriggerText; + private Label fAutoInsertDelayLabel; + private Label fAutoInsertJavaTriggerLabel; + private Label fAutoInsertJavaDocTriggerLabel; + private Label fAutoInsertHTMLTriggerLabel; -// private Button fCompletionInsertsRadioButton; -// private Button fCompletionOverwritesRadioButton; + + // private Button fCompletionInsertsRadioButton; + // private Button fCompletionOverwritesRadioButton; /** * List of master/slave listeners when there's a dependency. * * @see #createDependency(Button, String, Control) * @since 3.0 */ - private ArrayList fMasterSlaveListeners= new ArrayList(); - - private final String[][] fContentAssistColorListModel= new String[][] { - {PreferencesMessages.getString("JavaEditorPreferencePage.backgroundForCompletionProposals"), PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND }, //$NON-NLS-1$ - {PreferencesMessages.getString("JavaEditorPreferencePage.foregroundForCompletionProposals"), PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND }, //$NON-NLS-1$ -// {PreferencesMessages.getString("JavaEditorPreferencePage.backgroundForMethodParameters"), PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND }, //$NON-NLS-1$ -// {PreferencesMessages.getString("JavaEditorPreferencePage.foregroundForMethodParameters"), PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND }, //$NON-NLS-1$ -// {PreferencesMessages.getString("JavaEditorPreferencePage.backgroundForCompletionReplacement"), PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND }, //$NON-NLS-1$ -// {PreferencesMessages.getString("JavaEditorPreferencePage.foregroundForCompletionReplacement"), PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND } //$NON-NLS-1$ - }; + private ArrayList fMasterSlaveListeners = new ArrayList(); - - private Map fCheckBoxes= new HashMap(); - private SelectionListener fCheckBoxListener= new SelectionListener() { + private final String[][] fContentAssistColorListModel = new String[][] { + { + PreferencesMessages + .getString("JavaEditorPreferencePage.backgroundForCompletionProposals"), PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND }, //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.foregroundForCompletionProposals"), PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND }, //$NON-NLS-1$ + // {PreferencesMessages.getString("JavaEditorPreferencePage.backgroundForMethodParameters"), + // PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND }, + // //$NON-NLS-1$ + // {PreferencesMessages.getString("JavaEditorPreferencePage.foregroundForMethodParameters"), + // PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND }, + // //$NON-NLS-1$ + // {PreferencesMessages.getString("JavaEditorPreferencePage.backgroundForCompletionReplacement"), + // PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND }, + // //$NON-NLS-1$ + // {PreferencesMessages.getString("JavaEditorPreferencePage.foregroundForCompletionReplacement"), + // PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND } + // //$NON-NLS-1$ + }; + + private Map fCheckBoxes = new HashMap(); + + private SelectionListener fCheckBoxListener = new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { } + public void widgetSelected(SelectionEvent e) { - Button button= (Button) e.widget; - fStore.setValue((String) fCheckBoxes.get(button), button.getSelection()); + Button button = (Button) e.widget; + fStore.setValue((String) fCheckBoxes.get(button), button + .getSelection()); } }; - - private Map fTextFields= new HashMap(); - private ModifyListener fTextFieldListener= new ModifyListener() { + + private Map fTextFields = new HashMap(); + + private ModifyListener fTextFieldListener = new ModifyListener() { public void modifyText(ModifyEvent e) { - Text text= (Text) e.widget; + Text text = (Text) e.widget; fStore.setValue((String) fTextFields.get(text), text.getText()); } }; - private ArrayList fNumberFields= new ArrayList(); - private ModifyListener fNumberFieldListener= new ModifyListener() { + private ArrayList fNumberFields = new ArrayList(); + + private ModifyListener fNumberFieldListener = new ModifyListener() { public void modifyText(ModifyEvent e) { numberFieldChanged((Text) e.widget); } }; - - - public CodeAssistConfigurationBlock(PreferencePage mainPreferencePage, OverlayPreferenceStore store) { + + public CodeAssistConfigurationBlock(PreferencePage mainPreferencePage, + OverlayPreferenceStore store) { Assert.isNotNull(mainPreferencePage); Assert.isNotNull(store); - fStore= store; + fStore = store; fStore.addKeys(createOverlayStoreKeys()); - fMainPreferencePage= mainPreferencePage; + fMainPreferencePage = mainPreferencePage; } - private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys() { - - ArrayList overlayKeys= new ArrayList(); - - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_AUTOACTIVATION)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_AUTOINSERT)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_HTML)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_ORDER_PROPOSALS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_CASE_SENSITIVITY)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_ADDIMPORT)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_INSERT_COMPLETION)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_PREFIX_COMPLETION)); - - OverlayPreferenceStore.OverlayKey[] keys= new OverlayPreferenceStore.OverlayKey[overlayKeys.size()]; + + ArrayList overlayKeys = new ArrayList(); + + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_AUTOACTIVATION)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.INT, + PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_AUTOINSERT)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA)); + overlayKeys + .add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_HTML)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_ORDER_PROPOSALS)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_CASE_SENSITIVITY)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_ADDIMPORT)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_INSERT_COMPLETION)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_PREFIX_COMPLETION)); + + OverlayPreferenceStore.OverlayKey[] keys = new OverlayPreferenceStore.OverlayKey[overlayKeys + .size()]; overlayKeys.toArray(keys); return keys; } @@ -150,118 +217,161 @@ class CodeAssistConfigurationBlock implements IPreferenceConfigurationBlock { /** * Creates page for hover preferences. * - * @param parent the parent composite + * @param parent + * the parent composite * @return the control for the preference page */ public Control createControl(Composite parent) { - - PixelConverter pixelConverter= new PixelConverter(parent); - Composite contentAssistComposite= new Composite(parent, SWT.NONE); + PixelConverter pixelConverter = new PixelConverter(parent); + + Composite contentAssistComposite = new Composite(parent, SWT.NONE); contentAssistComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); - GridLayout layout= new GridLayout(); - layout.numColumns= 2; + GridLayout layout = new GridLayout(); + layout.numColumns = 2; contentAssistComposite.setLayout(layout); - -// addCompletionRadioButtons(contentAssistComposite); - - String label; -// label= PreferencesMessages.getString("JavaEditorPreferencePage.insertSingleProposalsAutomatically"); //$NON-NLS-1$ -// addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOINSERT, 0); -// -// label= PreferencesMessages.getString("JavaEditorPreferencePage.completePrefixes"); //$NON-NLS-1$ -// addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_PREFIX_COMPLETION, 0); -// -// label= PreferencesMessages.getString("JavaEditorPreferencePage.showOnlyProposalsVisibleInTheInvocationContext"); //$NON-NLS-1$ -// addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS, 0); -// -// label= PreferencesMessages.getString("JavaEditorPreferencePage.presentProposalsInAlphabeticalOrder"); //$NON-NLS-1$ -// addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_ORDER_PROPOSALS, 0); -// -// label= PreferencesMessages.getString("JavaEditorPreferencePage.automaticallyAddImportInsteadOfQualifiedName"); //$NON-NLS-1$ -// addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_ADDIMPORT, 0); -// -// label= PreferencesMessages.getString("JavaEditorPreferencePage.fillArgumentNamesOnMethodCompletion"); //$NON-NLS-1$ -// Button master= addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES, 0); -// -// label= PreferencesMessages.getString("JavaEditorPreferencePage.guessArgumentNamesOnMethodCompletion"); //$NON-NLS-1$ -// Button slave= addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS, 0); -// createDependency(master, PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES, slave); -// - label= PreferencesMessages.getString("JavaEditorPreferencePage.enableAutoActivation"); //$NON-NLS-1$ - final Button autoactivation= addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOACTIVATION, 0); - autoactivation.addSelectionListener(new SelectionAdapter(){ + + // addCompletionRadioButtons(contentAssistComposite); + + String label; + // label= + // PreferencesMessages.getString("JavaEditorPreferencePage.insertSingleProposalsAutomatically"); + // //$NON-NLS-1$ + // addCheckBox(contentAssistComposite, label, + // PreferenceConstants.CODEASSIST_AUTOINSERT, 0); + // + // label= + // PreferencesMessages.getString("JavaEditorPreferencePage.completePrefixes"); + // //$NON-NLS-1$ + // addCheckBox(contentAssistComposite, label, + // PreferenceConstants.CODEASSIST_PREFIX_COMPLETION, 0); + // + // label= + // PreferencesMessages.getString("JavaEditorPreferencePage.showOnlyProposalsVisibleInTheInvocationContext"); + // //$NON-NLS-1$ + // addCheckBox(contentAssistComposite, label, + // PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS, 0); + // + // label= + // PreferencesMessages.getString("JavaEditorPreferencePage.presentProposalsInAlphabeticalOrder"); + // //$NON-NLS-1$ + // addCheckBox(contentAssistComposite, label, + // PreferenceConstants.CODEASSIST_ORDER_PROPOSALS, 0); + // + // label= + // PreferencesMessages.getString("JavaEditorPreferencePage.automaticallyAddImportInsteadOfQualifiedName"); + // //$NON-NLS-1$ + // addCheckBox(contentAssistComposite, label, + // PreferenceConstants.CODEASSIST_ADDIMPORT, 0); + // + // label= + // PreferencesMessages.getString("JavaEditorPreferencePage.fillArgumentNamesOnMethodCompletion"); + // //$NON-NLS-1$ + // Button master= addCheckBox(contentAssistComposite, label, + // PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES, 0); + // + // label= + // PreferencesMessages.getString("JavaEditorPreferencePage.guessArgumentNamesOnMethodCompletion"); + // //$NON-NLS-1$ + // Button slave= addCheckBox(contentAssistComposite, label, + // PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS, 0); + // createDependency(master, + // PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES, slave); + // + label = PreferencesMessages + .getString("JavaEditorPreferencePage.enableAutoActivation"); //$NON-NLS-1$ + final Button autoactivation = addCheckBox(contentAssistComposite, + label, PreferenceConstants.CODEASSIST_AUTOACTIVATION, 0); + autoactivation.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { updateAutoactivationControls(); } - }); - + }); + Control[] labelledTextField; - label= PreferencesMessages.getString("JavaEditorPreferencePage.autoActivationDelay"); //$NON-NLS-1$ - labelledTextField= addLabelledTextField(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY, 4, 0, true); - fAutoInsertDelayLabel= getLabelControl(labelledTextField); - fAutoInsertDelayText= getTextControl(labelledTextField); - - label= PreferencesMessages.getString("JavaEditorPreferencePage.autoActivationTriggersForJava"); //$NON-NLS-1$ - labelledTextField= addLabelledTextField(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA, 4, 0, false); - fAutoInsertJavaTriggerLabel= getLabelControl(labelledTextField); - fAutoInsertJavaTriggerText= getTextControl(labelledTextField); - - label= PreferencesMessages.getString("JavaEditorPreferencePage.autoActivationTriggersForJavaDoc"); //$NON-NLS-1$ - labelledTextField= addLabelledTextField(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC, 4, 0, false); - fAutoInsertJavaDocTriggerLabel= getLabelControl(labelledTextField); - fAutoInsertJavaDocTriggerText= getTextControl(labelledTextField); - - label= PreferencesMessages.getString("JavaEditorPreferencePage.autoActivationTriggersForHTML"); //$NON-NLS-1$ - labelledTextField= addLabelledTextField(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_HTML, 4, 0, false); - fAutoInsertHTMLTriggerLabel= getLabelControl(labelledTextField); - fAutoInsertHTMLTriggerText= getTextControl(labelledTextField); - - Label l= new Label(contentAssistComposite, SWT.LEFT); - l.setText(PreferencesMessages.getString("JavaEditorPreferencePage.codeAssist.colorOptions")); //$NON-NLS-1$ - GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); - gd.horizontalSpan= 2; + label = PreferencesMessages + .getString("JavaEditorPreferencePage.autoActivationDelay"); //$NON-NLS-1$ + labelledTextField = addLabelledTextField(contentAssistComposite, label, + PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY, 4, 0, true); + fAutoInsertDelayLabel = getLabelControl(labelledTextField); + fAutoInsertDelayText = getTextControl(labelledTextField); + + label = PreferencesMessages + .getString("JavaEditorPreferencePage.autoActivationTriggersForJava"); //$NON-NLS-1$ + labelledTextField = addLabelledTextField(contentAssistComposite, label, + PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA, 4, + 0, false); + fAutoInsertJavaTriggerLabel = getLabelControl(labelledTextField); + fAutoInsertJavaTriggerText = getTextControl(labelledTextField); + + label = PreferencesMessages + .getString("JavaEditorPreferencePage.autoActivationTriggersForJavaDoc"); //$NON-NLS-1$ + labelledTextField = addLabelledTextField(contentAssistComposite, label, + PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC, + 4, 0, false); + fAutoInsertJavaDocTriggerLabel = getLabelControl(labelledTextField); + fAutoInsertJavaDocTriggerText = getTextControl(labelledTextField); + + label = PreferencesMessages + .getString("JavaEditorPreferencePage.autoActivationTriggersForHTML"); //$NON-NLS-1$ + labelledTextField = addLabelledTextField(contentAssistComposite, label, + PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_HTML, 4, + 0, false); + fAutoInsertHTMLTriggerLabel = getLabelControl(labelledTextField); + fAutoInsertHTMLTriggerText = getTextControl(labelledTextField); + + Label l = new Label(contentAssistComposite, SWT.LEFT); + l.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.codeAssist.colorOptions")); //$NON-NLS-1$ + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + gd.horizontalSpan = 2; l.setLayoutData(gd); - - Composite editorComposite= new Composite(contentAssistComposite, SWT.NONE); - layout= new GridLayout(); - layout.numColumns= 2; - layout.marginHeight= 0; - layout.marginWidth= 0; + + Composite editorComposite = new Composite(contentAssistComposite, + SWT.NONE); + layout = new GridLayout(); + layout.numColumns = 2; + layout.marginHeight = 0; + layout.marginWidth = 0; editorComposite.setLayout(layout); - gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL); - gd.horizontalSpan= 2; - editorComposite.setLayoutData(gd); - - fContentAssistColorList= new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); - gd= new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL); - gd.heightHint= pixelConverter.convertHeightInCharsToPixels(8); + gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL + | GridData.FILL_VERTICAL); + gd.horizontalSpan = 2; + editorComposite.setLayoutData(gd); + + fContentAssistColorList = new List(editorComposite, SWT.SINGLE + | SWT.V_SCROLL | SWT.BORDER); + gd = new GridData(GridData.VERTICAL_ALIGN_BEGINNING + | GridData.FILL_HORIZONTAL); + gd.heightHint = pixelConverter.convertHeightInCharsToPixels(8); fContentAssistColorList.setLayoutData(gd); - - Composite stylesComposite= new Composite(editorComposite, SWT.NONE); - layout= new GridLayout(); - layout.marginHeight= 0; - layout.marginWidth= 0; - layout.numColumns= 2; + + Composite stylesComposite = new Composite(editorComposite, SWT.NONE); + layout = new GridLayout(); + layout.marginHeight = 0; + layout.marginWidth = 0; + layout.numColumns = 2; stylesComposite.setLayout(layout); stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); - - l= new Label(stylesComposite, SWT.LEFT); - l.setText(PreferencesMessages.getString("JavaEditorPreferencePage.codeAssist.color")); //$NON-NLS-1$ - gd= new GridData(); - gd.horizontalAlignment= GridData.BEGINNING; + + l = new Label(stylesComposite, SWT.LEFT); + l.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.codeAssist.color")); //$NON-NLS-1$ + gd = new GridData(); + gd.horizontalAlignment = GridData.BEGINNING; l.setLayoutData(gd); - - fContentAssistColorEditor= new ColorEditor(stylesComposite); - Button colorButton= fContentAssistColorEditor.getButton(); - gd= new GridData(GridData.FILL_HORIZONTAL); - gd.horizontalAlignment= GridData.BEGINNING; + + fContentAssistColorEditor = new ColorEditor(stylesComposite); + Button colorButton = fContentAssistColorEditor.getButton(); + gd = new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalAlignment = GridData.BEGINNING; colorButton.setLayoutData(gd); - + fContentAssistColorList.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } + public void widgetSelected(SelectionEvent e) { handleContentAssistColorListSelection(); } @@ -270,73 +380,86 @@ class CodeAssistConfigurationBlock implements IPreferenceConfigurationBlock { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } + public void widgetSelected(SelectionEvent e) { - int i= fContentAssistColorList.getSelectionIndex(); - String key= fContentAssistColorListModel[i][1]; - - PreferenceConverter.setValue(fStore, key, fContentAssistColorEditor.getColorValue()); + int i = fContentAssistColorList.getSelectionIndex(); + String key = fContentAssistColorListModel[i][1]; + + PreferenceConverter.setValue(fStore, key, + fContentAssistColorEditor.getColorValue()); } }); - + return contentAssistComposite; } - - private void createDependency(final Button master, String masterKey, final Control slave) { + + private void createDependency(final Button master, String masterKey, + final Control slave) { indent(slave); - boolean masterState= fStore.getBoolean(masterKey); + boolean masterState = fStore.getBoolean(masterKey); slave.setEnabled(masterState); - SelectionListener listener= new SelectionListener() { + SelectionListener listener = new SelectionListener() { public void widgetSelected(SelectionEvent e) { slave.setEnabled(master.getSelection()); } - public void widgetDefaultSelected(SelectionEvent e) {} + public void widgetDefaultSelected(SelectionEvent e) { + } }; master.addSelectionListener(listener); fMasterSlaveListeners.add(listener); } private static void indent(Control control) { - GridData gridData= new GridData(); - gridData.horizontalIndent= 20; - control.setLayoutData(gridData); + GridData gridData = new GridData(); + gridData.horizontalIndent = 20; + control.setLayoutData(gridData); } - - private static Text getTextControl(Control[] labelledTextField){ - return (Text)labelledTextField[1]; + + private static Text getTextControl(Control[] labelledTextField) { + return (Text) labelledTextField[1]; } - private static Label getLabelControl(Control[] labelledTextField){ - return (Label)labelledTextField[0]; + private static Label getLabelControl(Control[] labelledTextField) { + return (Label) labelledTextField[0]; } /** - * Returns an array of size 2: - * - first element is of type Label - * - second element is of type Text - * Use getLabelControl and getTextControl to get the 2 controls. + * Returns an array of size 2: - first element is of type Label - + * second element is of type Text Use + * getLabelControl and getTextControl to get + * the 2 controls. * - * @param composite the parent composite - * @param label the text field's label - * @param key the preference key - * @param textLimit the text limit - * @param indentation the field's indentation - * @param isNumber true iff this text field is used to e4dit a number + * @param composite + * the parent composite + * @param label + * the text field's label + * @param key + * the preference key + * @param textLimit + * the text limit + * @param indentation + * the field's indentation + * @param isNumber + * true iff this text field is used to e4dit a + * number * @return */ - private Control[] addLabelledTextField(Composite composite, String label, String key, int textLimit, int indentation, boolean isNumber) { - - PixelConverter pixelConverter= new PixelConverter(composite); - - Label labelControl= new Label(composite, SWT.NONE); + private Control[] addLabelledTextField(Composite composite, String label, + String key, int textLimit, int indentation, boolean isNumber) { + + PixelConverter pixelConverter = new PixelConverter(composite); + + Label labelControl = new Label(composite, SWT.NONE); labelControl.setText(label); - GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - gd.horizontalIndent= indentation; + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.horizontalIndent = indentation; labelControl.setLayoutData(gd); - - Text textControl= new Text(composite, SWT.BORDER | SWT.SINGLE); - gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - gd.widthHint= pixelConverter.convertWidthInCharsToPixels(textLimit + 1); + + Text textControl = new Text(composite, SWT.BORDER | SWT.SINGLE); + gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.widthHint = pixelConverter + .convertWidthInCharsToPixels(textLimit + 1); textControl.setLayoutData(gd); textControl.setTextLimit(textLimit); fTextFields.put(textControl, key); @@ -346,159 +469,173 @@ class CodeAssistConfigurationBlock implements IPreferenceConfigurationBlock { } else { textControl.addModifyListener(fTextFieldListener); } - - return new Control[]{labelControl, textControl}; + + return new Control[] { labelControl, textControl }; } private void addCompletionRadioButtons(Composite contentAssistComposite) { - Composite completionComposite= new Composite(contentAssistComposite, SWT.NONE); - GridData ccgd= new GridData(); - ccgd.horizontalSpan= 2; + Composite completionComposite = new Composite(contentAssistComposite, + SWT.NONE); + GridData ccgd = new GridData(); + ccgd.horizontalSpan = 2; completionComposite.setLayoutData(ccgd); - GridLayout ccgl= new GridLayout(); - ccgl.marginWidth= 0; - ccgl.numColumns= 2; + GridLayout ccgl = new GridLayout(); + ccgl.marginWidth = 0; + ccgl.numColumns = 2; completionComposite.setLayout(ccgl); - -// SelectionListener completionSelectionListener= new SelectionAdapter() { -// public void widgetSelected(SelectionEvent e) { -// boolean insert= fCompletionInsertsRadioButton.getSelection(); -// fStore.setValue(PreferenceConstants.CODEASSIST_INSERT_COMPLETION, insert); -// } -// }; -// -// fCompletionInsertsRadioButton= new Button(completionComposite, SWT.RADIO | SWT.LEFT); -// fCompletionInsertsRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.completionInserts")); //$NON-NLS-1$ -// fCompletionInsertsRadioButton.setLayoutData(new GridData()); -// fCompletionInsertsRadioButton.addSelectionListener(completionSelectionListener); -// -// fCompletionOverwritesRadioButton= new Button(completionComposite, SWT.RADIO | SWT.LEFT); -// fCompletionOverwritesRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.completionOverwrites")); //$NON-NLS-1$ -// fCompletionOverwritesRadioButton.setLayoutData(new GridData()); -// fCompletionOverwritesRadioButton.addSelectionListener(completionSelectionListener); + + // SelectionListener completionSelectionListener= new SelectionAdapter() + // { + // public void widgetSelected(SelectionEvent e) { + // boolean insert= fCompletionInsertsRadioButton.getSelection(); + // fStore.setValue(PreferenceConstants.CODEASSIST_INSERT_COMPLETION, + // insert); + // } + // }; + // + // fCompletionInsertsRadioButton= new Button(completionComposite, + // SWT.RADIO | SWT.LEFT); + // fCompletionInsertsRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.completionInserts")); + // //$NON-NLS-1$ + // fCompletionInsertsRadioButton.setLayoutData(new GridData()); + // fCompletionInsertsRadioButton.addSelectionListener(completionSelectionListener); + // + // fCompletionOverwritesRadioButton= new Button(completionComposite, + // SWT.RADIO | SWT.LEFT); + // fCompletionOverwritesRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.completionOverwrites")); + // //$NON-NLS-1$ + // fCompletionOverwritesRadioButton.setLayoutData(new GridData()); + // fCompletionOverwritesRadioButton.addSelectionListener(completionSelectionListener); } - + public void initialize() { initializeFields(); - - for (int i= 0; i < fContentAssistColorListModel.length; i++) + + for (int i = 0; i < fContentAssistColorListModel.length; i++) fContentAssistColorList.add(fContentAssistColorListModel[i][0]); fContentAssistColorList.getDisplay().asyncExec(new Runnable() { public void run() { - if (fContentAssistColorList != null && !fContentAssistColorList.isDisposed()) { + if (fContentAssistColorList != null + && !fContentAssistColorList.isDisposed()) { fContentAssistColorList.select(0); handleContentAssistColorListSelection(); } } }); - + } void initializeFields() { - Iterator e= fCheckBoxes.keySet().iterator(); + Iterator e = fCheckBoxes.keySet().iterator(); while (e.hasNext()) { - Button b= (Button) e.next(); - String key= (String) fCheckBoxes.get(b); + Button b = (Button) e.next(); + String key = (String) fCheckBoxes.get(b); b.setSelection(fStore.getBoolean(key)); } - - e= fTextFields.keySet().iterator(); + + e = fTextFields.keySet().iterator(); while (e.hasNext()) { - Text t= (Text) e.next(); - String key= (String) fTextFields.get(t); + Text t = (Text) e.next(); + String key = (String) fTextFields.get(t); t.setText(fStore.getString(key)); } - -// boolean completionInserts= fStore.getBoolean(PreferenceConstants.CODEASSIST_INSERT_COMPLETION); -// fCompletionInsertsRadioButton.setSelection(completionInserts); -// fCompletionOverwritesRadioButton.setSelection(! completionInserts); - + + // boolean completionInserts= + // fStore.getBoolean(PreferenceConstants.CODEASSIST_INSERT_COMPLETION); + // fCompletionInsertsRadioButton.setSelection(completionInserts); + // fCompletionOverwritesRadioButton.setSelection(! completionInserts); + updateAutoactivationControls(); - - updateStatus(validatePositiveNumber("0")); //$NON-NLS-1$ - - // Update slaves - Iterator iter= fMasterSlaveListeners.iterator(); - while (iter.hasNext()) { - SelectionListener listener= (SelectionListener)iter.next(); - listener.widgetSelected(null); - } + + updateStatus(validatePositiveNumber("0")); //$NON-NLS-1$ + + // Update slaves + Iterator iter = fMasterSlaveListeners.iterator(); + while (iter.hasNext()) { + SelectionListener listener = (SelectionListener) iter.next(); + listener.widgetSelected(null); + } } - - private void updateAutoactivationControls() { - boolean autoactivation= fStore.getBoolean(PreferenceConstants.CODEASSIST_AUTOACTIVATION); - fAutoInsertDelayText.setEnabled(autoactivation); + + private void updateAutoactivationControls() { + boolean autoactivation = fStore + .getBoolean(PreferenceConstants.CODEASSIST_AUTOACTIVATION); + fAutoInsertDelayText.setEnabled(autoactivation); fAutoInsertDelayLabel.setEnabled(autoactivation); - fAutoInsertJavaTriggerText.setEnabled(autoactivation); + fAutoInsertJavaTriggerText.setEnabled(autoactivation); fAutoInsertJavaTriggerLabel.setEnabled(autoactivation); - - fAutoInsertJavaDocTriggerText.setEnabled(autoactivation); + + fAutoInsertJavaDocTriggerText.setEnabled(autoactivation); fAutoInsertJavaDocTriggerLabel.setEnabled(autoactivation); - + fAutoInsertHTMLTriggerText.setEnabled(autoactivation); fAutoInsertHTMLTriggerLabel.setEnabled(autoactivation); - } + } public void performOk() { } - public void performDefaults() { + public void performDefaults() { handleContentAssistColorListSelection(); initializeFields(); } - - private void handleContentAssistColorListSelection() { - int i= fContentAssistColorList.getSelectionIndex(); - String key= fContentAssistColorListModel[i][1]; - RGB rgb= PreferenceConverter.getColor(fStore, key); + + private void handleContentAssistColorListSelection() { + int i = fContentAssistColorList.getSelectionIndex(); + String key = fContentAssistColorListModel[i][1]; + RGB rgb = PreferenceConverter.getColor(fStore, key); fContentAssistColorEditor.setColorValue(rgb); } - + private void numberFieldChanged(Text textControl) { - String number= textControl.getText(); - IStatus status= validatePositiveNumber(number); + String number = textControl.getText(); + IStatus status = validatePositiveNumber(number); if (!status.matches(IStatus.ERROR)) fStore.setValue((String) fTextFields.get(textControl), number); updateStatus(status); } - + private IStatus validatePositiveNumber(String number) { - StatusInfo status= new StatusInfo(); + StatusInfo status = new StatusInfo(); if (number.length() == 0) { - status.setError(PreferencesMessages.getString("JavaEditorPreferencePage.empty_input")); //$NON-NLS-1$ + status.setError(PreferencesMessages + .getString("JavaEditorPreferencePage.empty_input")); //$NON-NLS-1$ } else { try { - int value= Integer.parseInt(number); + int value = Integer.parseInt(number); if (value < 0) - status.setError(PreferencesMessages.getFormattedString("JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$ + status.setError(PreferencesMessages.getFormattedString( + "JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$ } catch (NumberFormatException e) { - status.setError(PreferencesMessages.getFormattedString("JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$ + status.setError(PreferencesMessages.getFormattedString( + "JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$ } } return status; } - + private void updateStatus(IStatus status) { fMainPreferencePage.setValid(status.isOK()); StatusUtil.applyToStatusLine(fMainPreferencePage, status); } - - private Button addCheckBox(Composite parent, String label, String key, int indentation) { - Button checkBox= new Button(parent, SWT.CHECK); + + private Button addCheckBox(Composite parent, String label, String key, + int indentation) { + Button checkBox = new Button(parent, SWT.CHECK); checkBox.setText(label); - - GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - gd.horizontalIndent= indentation; - gd.horizontalSpan= 2; + + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.horizontalIndent = indentation; + gd.horizontalSpan = 2; checkBox.setLayoutData(gd); checkBox.addSelectionListener(fCheckBoxListener); - + fCheckBoxes.put(checkBox, key); - + return checkBox; } - + /* * @see DialogPage#dispose() */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeAssistPreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeAssistPreferencePage.java index 3409f64..d471983 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeAssistPreferencePage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeAssistPreferencePage.java @@ -13,8 +13,6 @@ package net.sourceforge.phpdt.internal.ui.preferences; import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; import net.sourceforge.phpeclipse.PHPeclipsePlugin; - - /** * Code Assist preference page. @@ -24,7 +22,8 @@ import net.sourceforge.phpeclipse.PHPeclipsePlugin; * * @since 3.0 */ -public class CodeAssistPreferencePage extends AbstractConfigurationBlockPreferencePage { +public class CodeAssistPreferencePage extends + AbstractConfigurationBlockPreferencePage { /* * @see net.sourceforge.phpdt.internal.ui.preferences.AbstractConfigureationBlockPreferencePage#getHelpId() @@ -39,7 +38,7 @@ public class CodeAssistPreferencePage extends AbstractConfigurationBlockPreferen protected void setDescription() { // This page has no description } - + /* * @see net.sourceforge.phpdt.internal.ui.preferences.AbstractConfigurationBlockPreferencePage#setPreferenceStore() */ @@ -50,7 +49,8 @@ public class CodeAssistPreferencePage extends AbstractConfigurationBlockPreferen /* * @see net.sourceforge.phpdt.internal.ui.preferences.AbstractConfigureationBlockPreferencePage#createConfigurationBlock(net.sourceforge.phpdt.internal.ui.preferences.OverlayPreferenceStore) */ - protected IPreferenceConfigurationBlock createConfigurationBlock(OverlayPreferenceStore overlayPreferenceStore) { + protected IPreferenceConfigurationBlock createConfigurationBlock( + OverlayPreferenceStore overlayPreferenceStore) { return new CodeAssistConfigurationBlock(this, overlayPreferenceStore); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeFormatterPreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeFormatterPreferencePage.java index 5513ffa..f448ac6 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeFormatterPreferencePage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeFormatterPreferencePage.java @@ -43,103 +43,118 @@ import org.eclipse.ui.IWorkbenchPreferencePage; /* * The page for setting code formatter options */ -public class CodeFormatterPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { +public class CodeFormatterPreferencePage extends PreferencePage implements + IWorkbenchPreferencePage { // Preference store keys, see PHPCore.getOptions - private static final String PREF_NEWLINE_OPENING_BRACES= JavaCore.FORMATTER_NEWLINE_OPENING_BRACE; - private static final String PREF_NEWLINE_CONTROL_STATEMENT= JavaCore.FORMATTER_NEWLINE_CONTROL; - private static final String PREF_NEWLINE_CLEAR_ALL= JavaCore.FORMATTER_CLEAR_BLANK_LINES; - // private static final String PREF_NEWLINE_ELSE_IF= PHPCore.FORMATTER_NEWLINE_ELSE_IF; - private static final String PREF_NEWLINE_EMPTY_BLOCK= JavaCore.FORMATTER_NEWLINE_EMPTY_BLOCK; - private static final String PREF_LINE_SPLIT= JavaCore.FORMATTER_LINE_SPLIT; - private static final String PREF_STYLE_COMPACT_ASSIGNEMENT= JavaCore.FORMATTER_COMPACT_ASSIGNMENT; - private static final String PREF_TAB_CHAR= JavaCore.FORMATTER_TAB_CHAR; - private static final String PREF_TAB_SIZE= JavaCore.FORMATTER_TAB_SIZE; + private static final String PREF_NEWLINE_OPENING_BRACES = JavaCore.FORMATTER_NEWLINE_OPENING_BRACE; + + private static final String PREF_NEWLINE_CONTROL_STATEMENT = JavaCore.FORMATTER_NEWLINE_CONTROL; + + private static final String PREF_NEWLINE_CLEAR_ALL = JavaCore.FORMATTER_CLEAR_BLANK_LINES; + + // private static final String PREF_NEWLINE_ELSE_IF= + // PHPCore.FORMATTER_NEWLINE_ELSE_IF; + private static final String PREF_NEWLINE_EMPTY_BLOCK = JavaCore.FORMATTER_NEWLINE_EMPTY_BLOCK; + + private static final String PREF_LINE_SPLIT = JavaCore.FORMATTER_LINE_SPLIT; + + private static final String PREF_STYLE_COMPACT_ASSIGNEMENT = JavaCore.FORMATTER_COMPACT_ASSIGNMENT; + + private static final String PREF_TAB_CHAR = JavaCore.FORMATTER_TAB_CHAR; + + private static final String PREF_TAB_SIZE = JavaCore.FORMATTER_TAB_SIZE; // values - private static final String INSERT= JavaCore.INSERT; - private static final String DO_NOT_INSERT= JavaCore.DO_NOT_INSERT; - - private static final String COMPACT= JavaCore.COMPACT; - private static final String NORMAL= JavaCore.NORMAL; - - private static final String TAB= JavaCore.TAB; - private static final String SPACE= JavaCore.SPACE; - - private static final String CLEAR_ALL= JavaCore.CLEAR_ALL; - private static final String PRESERVE_ONE= JavaCore.PRESERVE_ONE; - + private static final String INSERT = JavaCore.INSERT; + + private static final String DO_NOT_INSERT = JavaCore.DO_NOT_INSERT; + + private static final String COMPACT = JavaCore.COMPACT; + + private static final String NORMAL = JavaCore.NORMAL; + + private static final String TAB = JavaCore.TAB; + + private static final String SPACE = JavaCore.SPACE; + + private static final String CLEAR_ALL = JavaCore.CLEAR_ALL; + + private static final String PRESERVE_ONE = JavaCore.PRESERVE_ONE; private static String[] getAllKeys() { - return new String[] { - PREF_NEWLINE_OPENING_BRACES, PREF_NEWLINE_CONTROL_STATEMENT, PREF_NEWLINE_CLEAR_ALL, - // PREF_NEWLINE_ELSE_IF, - PREF_NEWLINE_EMPTY_BLOCK, PREF_LINE_SPLIT, - PREF_STYLE_COMPACT_ASSIGNEMENT, PREF_TAB_CHAR, PREF_TAB_SIZE - }; + return new String[] { PREF_NEWLINE_OPENING_BRACES, + PREF_NEWLINE_CONTROL_STATEMENT, PREF_NEWLINE_CLEAR_ALL, + // PREF_NEWLINE_ELSE_IF, + PREF_NEWLINE_EMPTY_BLOCK, PREF_LINE_SPLIT, + PREF_STYLE_COMPACT_ASSIGNEMENT, PREF_TAB_CHAR, PREF_TAB_SIZE }; } - + /** * Gets the currently configured tab size + * * @deprecated Inline to avoid reference to preference page */ public static int getTabSize() { - String string= (String) JavaCore.getOptions().get(PREF_TAB_SIZE); + String string = (String) JavaCore.getOptions().get(PREF_TAB_SIZE); return getPositiveIntValue(string, 4); } - + /** * Gets the current compating assignement configuration + * * @deprecated Inline to avoid reference to preference page - */ + */ public static boolean isCompactingAssignment() { - return COMPACT.equals(JavaCore.getOptions().get(PREF_STYLE_COMPACT_ASSIGNEMENT)); + return COMPACT.equals(JavaCore.getOptions().get( + PREF_STYLE_COMPACT_ASSIGNEMENT)); } - + /** * Gets the current compating assignement configuration + * * @deprecated Inline to avoid reference to preference page - */ + */ public static boolean useSpaces() { return SPACE.equals(JavaCore.getOptions().get(PREF_TAB_CHAR)); - } - - + } + private static int getPositiveIntValue(String string, int dflt) { try { - int i= Integer.parseInt(string); + int i = Integer.parseInt(string); if (i >= 0) { return i; } } catch (NumberFormatException e) { } return dflt; - } - + } + private static class ControlData { private String fKey; + private String[] fValues; - + public ControlData(String key, String[] values) { - fKey= key; - fValues= values; + fKey = key; + fValues = values; } - + public String getKey() { return fKey; } - + public String getValue(boolean selection) { - int index= selection ? 0 : 1; + int index = selection ? 0 : 1; return fValues[index]; } - + public String getValue(int index) { return fValues[index]; - } - + } + public int getSelection(String value) { - for (int i= 0; i < fValues.length; i++) { + for (int i = 0; i < fValues.length; i++) { if (value.equals(fValues[i])) { return i; } @@ -147,32 +162,37 @@ public class CodeFormatterPreferencePage extends PreferencePage implements IWork throw new IllegalArgumentException(); } } - + private Hashtable fWorkingValues; private ArrayList fCheckBoxes; + private ArrayList fTextBoxes; - + private SelectionListener fButtonSelectionListener; + private ModifyListener fTextModifyListener; - + private String fPreviewText; + private IDocument fPreviewDocument; - + private Text fTabSizeTextBox; - // private SourceViewer fSourceViewer; - + + // private SourceViewer fSourceViewer; public CodeFormatterPreferencePage() { - setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); - setDescription(PHPUIMessages.getString("CodeFormatterPreferencePage.description")); //$NON-NLS-1$ - - fWorkingValues= JavaCore.getOptions(); - fCheckBoxes= new ArrayList(); - fTextBoxes= new ArrayList(); - - fButtonSelectionListener= new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) {} + setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); + setDescription(PHPUIMessages + .getString("CodeFormatterPreferencePage.description")); //$NON-NLS-1$ + + fWorkingValues = JavaCore.getOptions(); + fCheckBoxes = new ArrayList(); + fTextBoxes = new ArrayList(); + + fButtonSelectionListener = new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + } public void widgetSelected(SelectionEvent e) { if (!e.widget.isDisposed()) { @@ -180,22 +200,22 @@ public class CodeFormatterPreferencePage extends PreferencePage implements IWork } } }; - - fTextModifyListener= new ModifyListener() { + + fTextModifyListener = new ModifyListener() { public void modifyText(ModifyEvent e) { if (!e.widget.isDisposed()) { textChanged((Text) e.widget); } } }; - - fPreviewDocument= new Document(); - fPreviewText= loadPreviewFile("CodeFormatterPreviewCode.txt"); //$NON-NLS-1$ + + fPreviewDocument = new Document(); + fPreviewText = loadPreviewFile("CodeFormatterPreviewCode.txt"); //$NON-NLS-1$ } /* * @see IWorkbenchPreferencePage#init() - */ + */ public void init(IWorkbench workbench) { } @@ -204,215 +224,240 @@ public class CodeFormatterPreferencePage extends PreferencePage implements IWork */ public void createControl(Composite parent) { super.createControl(parent); -// WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.CODEFORMATTER_PREFERENCE_PAGE); - } + // WorkbenchHelp.setHelp(getControl(), + // IJavaHelpContextIds.CODEFORMATTER_PREFERENCE_PAGE); + } /* * @see PreferencePage#createContents(Composite) */ protected Control createContents(Composite parent) { - - GridLayout layout= new GridLayout(); - layout.marginHeight= 0; - layout.marginWidth= 0; - - Composite composite= new Composite(parent, SWT.NONE); + + GridLayout layout = new GridLayout(); + layout.marginHeight = 0; + layout.marginWidth = 0; + + Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(layout); - - - TabFolder folder= new TabFolder(composite, SWT.NONE); - folder.setLayout(new TabFolderLayout()); + + TabFolder folder = new TabFolder(composite, SWT.NONE); + folder.setLayout(new TabFolderLayout()); folder.setLayoutData(new GridData(GridData.FILL_BOTH)); - - String[] insertNotInsert= new String[] { INSERT, DO_NOT_INSERT }; - - layout= new GridLayout(); - layout.numColumns= 2; - - Composite newlineComposite= new Composite(folder, SWT.NULL); + + String[] insertNotInsert = new String[] { INSERT, DO_NOT_INSERT }; + + layout = new GridLayout(); + layout.numColumns = 2; + + Composite newlineComposite = new Composite(folder, SWT.NULL); newlineComposite.setLayout(layout); - String label= PHPUIMessages.getString("CodeFormatterPreferencePage.newline_opening_braces.label"); //$NON-NLS-1$ - addCheckBox(newlineComposite, label, PREF_NEWLINE_OPENING_BRACES, insertNotInsert); - - label= PHPUIMessages.getString("CodeFormatterPreferencePage.newline_control_statement.label"); //$NON-NLS-1$ - addCheckBox(newlineComposite, label, PREF_NEWLINE_CONTROL_STATEMENT, insertNotInsert); - - label= PHPUIMessages.getString("CodeFormatterPreferencePage.newline_clear_lines"); //$NON-NLS-1$ - addCheckBox(newlineComposite, label, PREF_NEWLINE_CLEAR_ALL, new String[] { CLEAR_ALL, PRESERVE_ONE } ); - -// label= PHPUIMessages.getString("CodeFormatterPreferencePage.newline_else_if.label"); //$NON-NLS-1$ -// addCheckBox(newlineComposite, label, PREF_NEWLINE_ELSE_IF, insertNotInsert); - - label= PHPUIMessages.getString("CodeFormatterPreferencePage.newline_empty_block.label"); //$NON-NLS-1$ - addCheckBox(newlineComposite, label, PREF_NEWLINE_EMPTY_BLOCK, insertNotInsert); - - layout= new GridLayout(); - layout.numColumns= 2; - - Composite lineSplittingComposite= new Composite(folder, SWT.NULL); + String label = PHPUIMessages + .getString("CodeFormatterPreferencePage.newline_opening_braces.label"); //$NON-NLS-1$ + addCheckBox(newlineComposite, label, PREF_NEWLINE_OPENING_BRACES, + insertNotInsert); + + label = PHPUIMessages + .getString("CodeFormatterPreferencePage.newline_control_statement.label"); //$NON-NLS-1$ + addCheckBox(newlineComposite, label, PREF_NEWLINE_CONTROL_STATEMENT, + insertNotInsert); + + label = PHPUIMessages + .getString("CodeFormatterPreferencePage.newline_clear_lines"); //$NON-NLS-1$ + addCheckBox(newlineComposite, label, PREF_NEWLINE_CLEAR_ALL, + new String[] { CLEAR_ALL, PRESERVE_ONE }); + + // label= + // PHPUIMessages.getString("CodeFormatterPreferencePage.newline_else_if.label"); + // //$NON-NLS-1$ + // addCheckBox(newlineComposite, label, PREF_NEWLINE_ELSE_IF, + // insertNotInsert); + + label = PHPUIMessages + .getString("CodeFormatterPreferencePage.newline_empty_block.label"); //$NON-NLS-1$ + addCheckBox(newlineComposite, label, PREF_NEWLINE_EMPTY_BLOCK, + insertNotInsert); + + layout = new GridLayout(); + layout.numColumns = 2; + + Composite lineSplittingComposite = new Composite(folder, SWT.NULL); lineSplittingComposite.setLayout(layout); - label= PHPUIMessages.getString("CodeFormatterPreferencePage.split_line.label"); //$NON-NLS-1$ + label = PHPUIMessages + .getString("CodeFormatterPreferencePage.split_line.label"); //$NON-NLS-1$ addTextField(lineSplittingComposite, label, PREF_LINE_SPLIT); - layout= new GridLayout(); - layout.numColumns= 2; - - Composite styleComposite= new Composite(folder, SWT.NULL); + layout = new GridLayout(); + layout.numColumns = 2; + + Composite styleComposite = new Composite(folder, SWT.NULL); styleComposite.setLayout(layout); - - label= PHPUIMessages.getString("CodeFormatterPreferencePage.style_compact_assignement.label"); //$NON-NLS-1$ - addCheckBox(styleComposite, label, PREF_STYLE_COMPACT_ASSIGNEMENT, new String[] { COMPACT, NORMAL } ); - label= PHPUIMessages.getString("CodeFormatterPreferencePage.tab_char.label"); //$NON-NLS-1$ - addCheckBox(styleComposite, label, PREF_TAB_CHAR, new String[] { TAB, SPACE } ); + label = PHPUIMessages + .getString("CodeFormatterPreferencePage.style_compact_assignement.label"); //$NON-NLS-1$ + addCheckBox(styleComposite, label, PREF_STYLE_COMPACT_ASSIGNEMENT, + new String[] { COMPACT, NORMAL }); - label= PHPUIMessages.getString("CodeFormatterPreferencePage.tab_size.label"); //$NON-NLS-1$ - fTabSizeTextBox= addTextField(styleComposite, label, PREF_TAB_SIZE); + label = PHPUIMessages + .getString("CodeFormatterPreferencePage.tab_char.label"); //$NON-NLS-1$ + addCheckBox(styleComposite, label, PREF_TAB_CHAR, new String[] { TAB, + SPACE }); - TabItem item= new TabItem(folder, SWT.NONE); - item.setText(PHPUIMessages.getString("CodeFormatterPreferencePage.tab.newline.tabtitle")); //$NON-NLS-1$ + label = PHPUIMessages + .getString("CodeFormatterPreferencePage.tab_size.label"); //$NON-NLS-1$ + fTabSizeTextBox = addTextField(styleComposite, label, PREF_TAB_SIZE); + + TabItem item = new TabItem(folder, SWT.NONE); + item.setText(PHPUIMessages + .getString("CodeFormatterPreferencePage.tab.newline.tabtitle")); //$NON-NLS-1$ item.setControl(newlineComposite); - item= new TabItem(folder, SWT.NONE); - item.setText(PHPUIMessages.getString("CodeFormatterPreferencePage.tab.linesplit.tabtitle")); //$NON-NLS-1$ + item = new TabItem(folder, SWT.NONE); + item + .setText(PHPUIMessages + .getString("CodeFormatterPreferencePage.tab.linesplit.tabtitle")); //$NON-NLS-1$ item.setControl(lineSplittingComposite); - - item= new TabItem(folder, SWT.NONE); - item.setText(PHPUIMessages.getString("CodeFormatterPreferencePage.tab.style.tabtitle")); //$NON-NLS-1$ - item.setControl(styleComposite); - -// fSourceViewer= createPreview(parent); - + + item = new TabItem(folder, SWT.NONE); + item.setText(PHPUIMessages + .getString("CodeFormatterPreferencePage.tab.style.tabtitle")); //$NON-NLS-1$ + item.setControl(styleComposite); + + // fSourceViewer= createPreview(parent); + updatePreview(); - + return composite; } - -// private SourceViewer createPreview(Composite parent) { -// SourceViewer previewViewer= new SourceViewer(parent, null, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER); -// JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools(); -// previewViewer.configure(new PHPSourceViewerConfiguration(tools, null)); -// previewViewer.getTextWidget().setFont(JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT)); -// previewViewer.getTextWidget().setTabs(getPositiveIntValue((String) fWorkingValues.get(PREF_TAB_SIZE), 0)); -// previewViewer.setEditable(false); -// previewViewer.setDocument(fPreviewDocument); -// Control control= previewViewer.getControl(); -// GridData gdata= new GridData(GridData.FILL_BOTH); -// gdata.widthHint= convertWidthInCharsToPixels(30); -// gdata.heightHint= convertHeightInCharsToPixels(5); -// control.setLayoutData(gdata); -// return previewViewer; -// } - - - private Button addCheckBox(Composite parent, String label, String key, String[] values) { - ControlData data= new ControlData(key, values); - - GridData gd= new GridData(GridData.FILL_HORIZONTAL); - gd.horizontalSpan= 2; - - Button checkBox= new Button(parent, SWT.CHECK); + + // private SourceViewer createPreview(Composite parent) { + // SourceViewer previewViewer= new SourceViewer(parent, null, SWT.V_SCROLL | + // SWT.H_SCROLL | SWT.BORDER); + // JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools(); + // previewViewer.configure(new PHPSourceViewerConfiguration(tools, null)); + // previewViewer.getTextWidget().setFont(JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT)); + // previewViewer.getTextWidget().setTabs(getPositiveIntValue((String) + // fWorkingValues.get(PREF_TAB_SIZE), 0)); + // previewViewer.setEditable(false); + // previewViewer.setDocument(fPreviewDocument); + // Control control= previewViewer.getControl(); + // GridData gdata= new GridData(GridData.FILL_BOTH); + // gdata.widthHint= convertWidthInCharsToPixels(30); + // gdata.heightHint= convertHeightInCharsToPixels(5); + // control.setLayoutData(gdata); + // return previewViewer; + // } + + private Button addCheckBox(Composite parent, String label, String key, + String[] values) { + ControlData data = new ControlData(key, values); + + GridData gd = new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalSpan = 2; + + Button checkBox = new Button(parent, SWT.CHECK); checkBox.setText(label); checkBox.setData(data); checkBox.setLayoutData(gd); - - String currValue= (String)fWorkingValues.get(key); + + String currValue = (String) fWorkingValues.get(key); checkBox.setSelection(data.getSelection(currValue) == 0); checkBox.addSelectionListener(fButtonSelectionListener); - + fCheckBoxes.add(checkBox); return checkBox; } - - private Text addTextField(Composite parent, String label, String key) { - Label labelControl= new Label(parent, SWT.NONE); + + private Text addTextField(Composite parent, String label, String key) { + Label labelControl = new Label(parent, SWT.NONE); labelControl.setText(label); labelControl.setLayoutData(new GridData()); - - Text textBox= new Text(parent, SWT.BORDER | SWT.SINGLE); + + Text textBox = new Text(parent, SWT.BORDER | SWT.SINGLE); textBox.setData(key); textBox.setLayoutData(new GridData()); - - String currValue= (String)fWorkingValues.get(key); + + String currValue = (String) fWorkingValues.get(key); textBox.setText(String.valueOf(getPositiveIntValue(currValue, 1))); textBox.setTextLimit(3); textBox.addModifyListener(fTextModifyListener); - GridData gd= new GridData(); - gd.widthHint= convertWidthInCharsToPixels(5); + GridData gd = new GridData(); + gd.widthHint = convertWidthInCharsToPixels(5); textBox.setLayoutData(gd); fTextBoxes.add(textBox); return textBox; - } - + } + private void controlChanged(Button button) { - ControlData data= (ControlData) button.getData(); - boolean selection= button.getSelection(); - String newValue= data.getValue(selection); + ControlData data = (ControlData) button.getData(); + boolean selection = button.getSelection(); + String newValue = data.getValue(selection); fWorkingValues.put(data.getKey(), newValue); updatePreview(); - + if (PREF_TAB_CHAR.equals(data.getKey())) { updateStatus(new StatusInfo()); if (selection) { - fTabSizeTextBox.setText((String)fWorkingValues.get(PREF_TAB_SIZE)); + fTabSizeTextBox.setText((String) fWorkingValues + .get(PREF_TAB_SIZE)); } } } - + private void textChanged(Text textControl) { - String key= (String) textControl.getData(); - String number= textControl.getText(); - IStatus status= validatePositiveNumber(number); + String key = (String) textControl.getData(); + String number = textControl.getText(); + IStatus status = validatePositiveNumber(number); if (!status.matches(IStatus.ERROR)) { fWorkingValues.put(key, number); } -// if (PREF_TAB_SIZE.equals(key)) { -// fSourceViewer.getTextWidget().setTabs(getPositiveIntValue(number, 0)); -// } + // if (PREF_TAB_SIZE.equals(key)) { + // fSourceViewer.getTextWidget().setTabs(getPositiveIntValue(number, + // 0)); + // } updateStatus(status); updatePreview(); } - - + /* * @see IPreferencePage#performOk() */ public boolean performOk() { - String[] allKeys= getAllKeys(); + String[] allKeys = getAllKeys(); // preserve other options // store in JCore - Hashtable actualOptions= JavaCore.getOptions(); - for (int i= 0; i < allKeys.length; i++) { - String key= allKeys[i]; - String val= (String) fWorkingValues.get(key); + Hashtable actualOptions = JavaCore.getOptions(); + for (int i = 0; i < allKeys.length; i++) { + String key = allKeys[i]; + String val = (String) fWorkingValues.get(key); actualOptions.put(key, val); } JavaCore.setOptions(actualOptions); PHPeclipsePlugin.getDefault().savePluginPreferences(); return super.performOk(); - } - + } + /* * @see PreferencePage#performDefaults() */ protected void performDefaults() { - fWorkingValues= JavaCore.getDefaultOptions(); + fWorkingValues = JavaCore.getDefaultOptions(); updateControls(); super.performDefaults(); } private String loadPreviewFile(String filename) { - String separator= System.getProperty("line.separator"); //$NON-NLS-1$ - StringBuffer btxt= new StringBuffer(512); - BufferedReader rin= null; + String separator = System.getProperty("line.separator"); //$NON-NLS-1$ + StringBuffer btxt = new StringBuffer(512); + BufferedReader rin = null; try { - rin= new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(filename))); + rin = new BufferedReader(new InputStreamReader(getClass() + .getResourceAsStream(filename))); String line; - while ((line= rin.readLine()) != null) { + while ((line = rin.readLine()) != null) { btxt.append(line); btxt.append(separator); } @@ -420,73 +465,77 @@ public class CodeFormatterPreferencePage extends PreferencePage implements IWork PHPeclipsePlugin.log(io); } finally { if (rin != null) { - try { rin.close(); } catch (IOException e) {} + try { + rin.close(); + } catch (IOException e) { + } } } return btxt.toString(); } - private void updatePreview() { - ICodeFormatter formatter= ToolFactory.createDefaultCodeFormatter(fWorkingValues); + ICodeFormatter formatter = ToolFactory + .createDefaultCodeFormatter(fWorkingValues); fPreviewDocument.set(formatter.format(fPreviewText, 0, null, "\n")); //$NON-NLS-1$ - } - + } + private void updateControls() { // update the UI - for (int i= fCheckBoxes.size() - 1; i >= 0; i--) { - Button curr= (Button) fCheckBoxes.get(i); - ControlData data= (ControlData) curr.getData(); - - String currValue= (String) fWorkingValues.get(data.getKey()); - curr.setSelection(data.getSelection(currValue) == 0); + for (int i = fCheckBoxes.size() - 1; i >= 0; i--) { + Button curr = (Button) fCheckBoxes.get(i); + ControlData data = (ControlData) curr.getData(); + + String currValue = (String) fWorkingValues.get(data.getKey()); + curr.setSelection(data.getSelection(currValue) == 0); } - for (int i= fTextBoxes.size() - 1; i >= 0; i--) { - Text curr= (Text) fTextBoxes.get(i); - String key= (String) curr.getData(); - String currValue= (String) fWorkingValues.get(key); + for (int i = fTextBoxes.size() - 1; i >= 0; i--) { + Text curr = (Text) fTextBoxes.get(i); + String key = (String) curr.getData(); + String currValue = (String) fWorkingValues.get(key); curr.setText(currValue); } } - + private IStatus validatePositiveNumber(String number) { - StatusInfo status= new StatusInfo(); + StatusInfo status = new StatusInfo(); if (number.length() == 0) { - status.setError(PHPUIMessages.getString("CodeFormatterPreferencePage.empty_input")); //$NON-NLS-1$ + status.setError(PHPUIMessages + .getString("CodeFormatterPreferencePage.empty_input")); //$NON-NLS-1$ } else { try { - int value= Integer.parseInt(number); + int value = Integer.parseInt(number); if (value < 0) { - status.setError(PHPUIMessages.getFormattedString("CodeFormatterPreferencePage.invalid_input", number)); //$NON-NLS-1$ + status + .setError(PHPUIMessages + .getFormattedString( + "CodeFormatterPreferencePage.invalid_input", number)); //$NON-NLS-1$ } } catch (NumberFormatException e) { - status.setError(PHPUIMessages.getFormattedString("CodeFormatterPreferencePage.invalid_input", number)); //$NON-NLS-1$ + status.setError(PHPUIMessages.getFormattedString( + "CodeFormatterPreferencePage.invalid_input", number)); //$NON-NLS-1$ } } return status; } - - + private void updateStatus(IStatus status) { if (!status.matches(IStatus.ERROR)) { // look if there are more severe errors - for (int i= 0; i < fTextBoxes.size(); i++) { - Text curr= (Text) fTextBoxes.get(i); + for (int i = 0; i < fTextBoxes.size(); i++) { + Text curr = (Text) fTextBoxes.get(i); if (!(curr == fTabSizeTextBox && usesTabs())) { - IStatus currStatus= validatePositiveNumber(curr.getText()); - status= StatusUtil.getMoreSevere(currStatus, status); + IStatus currStatus = validatePositiveNumber(curr.getText()); + status = StatusUtil.getMoreSevere(currStatus, status); } } - } + } setValid(!status.matches(IStatus.ERROR)); StatusUtil.applyToStatusLine(this, status); } - + private boolean usesTabs() { return TAB.equals(fWorkingValues.get(PREF_TAB_CHAR)); } - } - - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplateBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplateBlock.java index a1e4f67..d8dc004 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplateBlock.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplateBlock.java @@ -68,447 +68,519 @@ import org.eclipse.swt.widgets.Shell; */ public class CodeTemplateBlock { - private class CodeTemplateAdapter implements ITreeListAdapter, IDialogFieldListener { - - private final Object[] NO_CHILDREN = new Object[0]; - - public void customButtonPressed(TreeListDialogField field, int index) { - doButtonPressed(index, field.getSelectedElements()); - } - - public void selectionChanged(TreeListDialogField field) { - List selected = field.getSelectedElements(); - field.enableButton(IDX_EDIT, canEdit(selected)); - field.enableButton(IDX_EXPORT, !selected.isEmpty()); - - updateSourceViewerInput(selected); - } - - public void doubleClicked(TreeListDialogField field) { - List selected = field.getSelectedElements(); - if (canEdit(selected)) { - doButtonPressed(IDX_EDIT, selected); - } - } - - public Object[] getChildren(TreeListDialogField field, Object element) { - if (element == COMMENT_NODE || element == CODE_NODE) { - return getTemplateOfCategory(element == COMMENT_NODE); - } - return NO_CHILDREN; - } - - public Object getParent(TreeListDialogField field, Object element) { - if (element instanceof TemplatePersistenceData) { - TemplatePersistenceData data = (TemplatePersistenceData) element; - if (data.getTemplate().getName().endsWith(CodeTemplateContextType.COMMENT_SUFFIX)) { - return COMMENT_NODE; - } - return CODE_NODE; - } - return null; - } - - public boolean hasChildren(TreeListDialogField field, Object element) { - return (element == COMMENT_NODE || element == CODE_NODE); - } - - public void dialogFieldChanged(DialogField field) { - } - - public void keyPressed(TreeListDialogField field, KeyEvent event) { - } - - } - - private static class CodeTemplateLabelProvider extends LabelProvider { - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object) - */ - public Image getImage(Object element) { - return null; - - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object) - */ - public String getText(Object element) { - if (element == COMMENT_NODE || element == CODE_NODE) { - return (String) element; - } - TemplatePersistenceData data = (TemplatePersistenceData) element; - Template template = data.getTemplate(); - String name = template.getName(); - if (CodeTemplateContextType.CATCHBLOCK.equals(name)) { - return PreferencesMessages.getString("CodeTemplateBlock.catchblock.label"); //$NON-NLS-1$ - } else if (CodeTemplateContextType.METHODSTUB.equals(name)) { - return PreferencesMessages.getString("CodeTemplateBlock.methodstub.label"); //$NON-NLS-1$ - } else if (CodeTemplateContextType.CONSTRUCTORSTUB.equals(name)) { - return PreferencesMessages.getString("CodeTemplateBlock.constructorstub.label"); //$NON-NLS-1$ - } else if (CodeTemplateContextType.GETTERSTUB.equals(name)) { - return PreferencesMessages.getString("CodeTemplateBlock.getterstub.label"); //$NON-NLS-1$ - } else if (CodeTemplateContextType.SETTERSTUB.equals(name)) { - return PreferencesMessages.getString("CodeTemplateBlock.setterstub.label"); //$NON-NLS-1$ - } else if (CodeTemplateContextType.NEWTYPE.equals(name)) { - return PreferencesMessages.getString("CodeTemplateBlock.newtype.label"); //$NON-NLS-1$ - } else if (CodeTemplateContextType.TYPECOMMENT.equals(name)) { - return PreferencesMessages.getString("CodeTemplateBlock.typecomment.label"); //$NON-NLS-1$ - } else if (CodeTemplateContextType.FIELDCOMMENT.equals(name)) { - return PreferencesMessages.getString("CodeTemplateBlock.fieldcomment.label"); //$NON-NLS-1$ - } else if (CodeTemplateContextType.METHODCOMMENT.equals(name)) { - return PreferencesMessages.getString("CodeTemplateBlock.methodcomment.label"); //$NON-NLS-1$ - } else if (CodeTemplateContextType.OVERRIDECOMMENT.equals(name)) { - return PreferencesMessages.getString("CodeTemplateBlock.overridecomment.label"); //$NON-NLS-1$ - } else if (CodeTemplateContextType.CONSTRUCTORCOMMENT.equals(name)) { - return PreferencesMessages.getString("CodeTemplateBlock.constructorcomment.label"); //$NON-NLS-1$ - } else if (CodeTemplateContextType.GETTERCOMMENT.equals(name)) { - return PreferencesMessages.getString("CodeTemplateBlock.gettercomment.label"); //$NON-NLS-1$ - } else if (CodeTemplateContextType.SETTERCOMMENT.equals(name)) { - return PreferencesMessages.getString("CodeTemplateBlock.settercomment.label"); //$NON-NLS-1$ - } - return template.getDescription(); - } - - } - - private final static int IDX_EDIT = 0; - - private final static int IDX_IMPORT = 2; - - private final static int IDX_EXPORT = 3; - - private final static int IDX_EXPORTALL = 4; - - protected final static Object COMMENT_NODE = PreferencesMessages.getString("CodeTemplateBlock.templates.comment.node"); //$NON-NLS-1$ - - protected final static Object CODE_NODE = PreferencesMessages.getString("CodeTemplateBlock.templates.code.node"); //$NON-NLS-1$ - - private static final String PREF_JAVADOC_STUBS = PreferenceConstants.CODEGEN_ADD_COMMENTS; - - private TreeListDialogField fCodeTemplateTree; - - private SelectionButtonDialogField fCreateJavaDocComments; - - protected TemplateStore fTemplates; - - private PixelConverter fPixelConverter; - - private SourceViewer fPatternViewer; - - private Control fSWTWidget; - - private TemplateVariableProcessor fTemplateProcessor; - - public CodeTemplateBlock() { - - fTemplates = PHPeclipsePlugin.getDefault().getCodeTemplateStore(); - fTemplateProcessor = new TemplateVariableProcessor(); - - CodeTemplateAdapter adapter = new CodeTemplateAdapter(); - - String[] buttonLabels = new String[] { - /* IDX_EDIT */PreferencesMessages.getString("CodeTemplateBlock.templates.edit.button"), //$NON-NLS-1$ - /* */null, - /* IDX_IMPORT */PreferencesMessages.getString("CodeTemplateBlock.templates.import.button"), //$NON-NLS-1$ - /* IDX_EXPORT */PreferencesMessages.getString("CodeTemplateBlock.templates.export.button"), //$NON-NLS-1$ - /* IDX_EXPORTALL */PreferencesMessages.getString("CodeTemplateBlock.templates.exportall.button") //$NON-NLS-1$ - - }; - fCodeTemplateTree = new TreeListDialogField(adapter, buttonLabels, new CodeTemplateLabelProvider()); - fCodeTemplateTree.setDialogFieldListener(adapter); - fCodeTemplateTree.setLabelText(PreferencesMessages.getString("CodeTemplateBlock.templates.label")); //$NON-NLS-1$ - - fCodeTemplateTree.enableButton(IDX_EXPORT, false); - fCodeTemplateTree.enableButton(IDX_EDIT, false); - - fCodeTemplateTree.addElement(COMMENT_NODE); - fCodeTemplateTree.addElement(CODE_NODE); - - fCreateJavaDocComments = new SelectionButtonDialogField(SWT.CHECK | SWT.WRAP); - fCreateJavaDocComments.setLabelText(PreferencesMessages.getString("CodeTemplateBlock.createcomment.label")); //$NON-NLS-1$ - fCreateJavaDocComments.setSelection(PreferenceConstants.getPreferenceStore().getBoolean(PREF_JAVADOC_STUBS)); - - fCodeTemplateTree.selectFirstElement(); - } - - protected Control createContents(Composite parent) { - fPixelConverter = new PixelConverter(parent); - fSWTWidget = parent; - - Composite composite = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.marginHeight = 0; - layout.marginWidth = 0; - layout.numColumns = 2; - composite.setLayout(layout); - - fCodeTemplateTree.doFillIntoGrid(composite, 3); - LayoutUtil.setHorizontalSpan(fCodeTemplateTree.getLabelControl(null), 2); - LayoutUtil.setHorizontalGrabbing(fCodeTemplateTree.getTreeControl(null)); - - fPatternViewer = createViewer(composite, 2); - - fCreateJavaDocComments.doFillIntoGrid(composite, 2); - - DialogField label = new DialogField(); - label.setLabelText(PreferencesMessages.getString("CodeTemplateBlock.createcomment.description")); //$NON-NLS-1$ - label.doFillIntoGrid(composite, 2); - - return composite; - - } - - private Shell getShell() { - if (fSWTWidget != null) { - return fSWTWidget.getShell(); - } - return PHPeclipsePlugin.getActiveWorkbenchShell(); - } - - private SourceViewer createViewer(Composite parent, int nColumns) { - Label label = new Label(parent, SWT.NONE); - label.setText(PreferencesMessages.getString("CodeTemplateBlock.preview")); //$NON-NLS-1$ - GridData data = new GridData(); - data.horizontalSpan = nColumns; - label.setLayoutData(data); - - IDocument document = new Document(); - JavaTextTools tools = PHPeclipsePlugin.getDefault().getJavaTextTools(); - tools.setupJavaDocumentPartitioner(document, IPHPPartitions.PHP_PARTITIONING); - IPreferenceStore store = PHPeclipsePlugin.getDefault().getCombinedPreferenceStore(); - SourceViewer viewer = new JavaSourceViewer(parent, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL, store); - TemplateEditorSourceViewerConfiguration configuration = new TemplateEditorSourceViewerConfiguration(tools.getColorManager(), - store, null, fTemplateProcessor); - viewer.configure(configuration); - viewer.setEditable(false); - viewer.setDocument(document); - - Font font = JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT); - viewer.getTextWidget().setFont(font); - new JavaSourcePreviewerUpdater(viewer, configuration, store); - - Control control = viewer.getControl(); - data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL); - data.horizontalSpan = nColumns; - data.heightHint = fPixelConverter.convertHeightInCharsToPixels(5); - control.setLayoutData(data); - - return viewer; - } - - protected TemplatePersistenceData[] getTemplateOfCategory(boolean isComment) { - ArrayList res = new ArrayList(); - TemplatePersistenceData[] templates = fTemplates.getTemplateData(false); - for (int i = 0; i < templates.length; i++) { - TemplatePersistenceData curr = templates[i]; - if (isComment == curr.getTemplate().getName().endsWith(CodeTemplateContextType.COMMENT_SUFFIX)) { - res.add(curr); - } - } - return (TemplatePersistenceData[]) res.toArray(new TemplatePersistenceData[res.size()]); - } - - protected static boolean canEdit(List selected) { - return selected.size() == 1 && (selected.get(0) instanceof TemplatePersistenceData); - } - - protected void updateSourceViewerInput(List selection) { - if (fPatternViewer == null || fPatternViewer.getTextWidget().isDisposed()) { - return; - } - if (selection.size() == 1 && selection.get(0) instanceof TemplatePersistenceData) { - TemplatePersistenceData data = (TemplatePersistenceData) selection.get(0); - Template template = data.getTemplate(); - TemplateContextType type = PHPeclipsePlugin.getDefault().getCodeTemplateContextRegistry().getContextType( - template.getContextTypeId()); - fTemplateProcessor.setContextType(type); - fPatternViewer.getDocument().set(template.getPattern()); - } else { - fPatternViewer.getDocument().set(""); //$NON-NLS-1$ - } - } - - protected void doButtonPressed(int buttonIndex, List selected) { - if (buttonIndex == IDX_EDIT) { - edit((TemplatePersistenceData) selected.get(0)); - } else if (buttonIndex == IDX_EXPORT) { - export(selected); - } else if (buttonIndex == IDX_EXPORTALL) { - exportAll(); - } else if (buttonIndex == IDX_IMPORT) { - import_(); - } - } - - private void edit(TemplatePersistenceData data) { - Template newTemplate = new Template(data.getTemplate()); - EditTemplateDialog dialog = new EditTemplateDialog(getShell(), newTemplate, true, false, PHPeclipsePlugin.getDefault() - .getCodeTemplateContextRegistry()); - if (dialog.open() == Window.OK) { - // changed - data.setTemplate(newTemplate); - fCodeTemplateTree.refresh(data); - fCodeTemplateTree.selectElements(new StructuredSelection(data)); - } - } - - private void import_() { - FileDialog dialog = new FileDialog(getShell()); - dialog.setText(PreferencesMessages.getString("CodeTemplateBlock.import.title")); //$NON-NLS-1$ - dialog.setFilterExtensions(new String[] { PreferencesMessages.getString("CodeTemplateBlock.import.extension") }); //$NON-NLS-1$ - String path = dialog.open(); - - if (path == null) - return; - - try { - TemplateReaderWriter reader = new TemplateReaderWriter(); - File file = new File(path); - if (file.exists()) { - InputStream input = new BufferedInputStream(new FileInputStream(file)); - TemplatePersistenceData[] datas = reader.read(input, null); - for (int i = 0; i < datas.length; i++) { - updateTemplate(datas[i]); - } - } - - fCodeTemplateTree.refresh(); - updateSourceViewerInput(fCodeTemplateTree.getSelectedElements()); - - } catch (FileNotFoundException e) { - openReadErrorDialog(e); - } catch (IOException e) { - openReadErrorDialog(e); - } - - } - - private void updateTemplate(TemplatePersistenceData data) { - TemplatePersistenceData[] datas = fTemplates.getTemplateData(true); - for (int i = 0; i < datas.length; i++) { - String id = datas[i].getId(); - if (id != null && id.equals(data.getId())) { - datas[i].setTemplate(data.getTemplate()); - break; - } - } - } - - private void exportAll() { - export(fTemplates.getTemplateData(false)); - } - - private void export(List selected) { - List datas = new ArrayList(); - for (int i = 0; i < selected.size(); i++) { - Object curr = selected.get(i); - if (curr instanceof TemplatePersistenceData) { - datas.add(curr); - } else { - TemplatePersistenceData[] cat = getTemplateOfCategory(curr == COMMENT_NODE); - datas.addAll(Arrays.asList(cat)); - } - } - export((TemplatePersistenceData[]) datas.toArray(new TemplatePersistenceData[datas.size()])); - } - - private void export(TemplatePersistenceData[] templates) { - FileDialog dialog = new FileDialog(getShell(), SWT.SAVE); - dialog.setText(PreferencesMessages.getFormattedString("CodeTemplateBlock.export.title", String.valueOf(templates.length))); //$NON-NLS-1$ - dialog.setFilterExtensions(new String[] { PreferencesMessages.getString("CodeTemplateBlock.export.extension") }); //$NON-NLS-1$ - dialog.setFileName(PreferencesMessages.getString("CodeTemplateBlock.export.filename")); //$NON-NLS-1$ - String path = dialog.open(); - - if (path == null) - return; - - File file = new File(path); - - if (file.isHidden()) { - String title = PreferencesMessages.getString("CodeTemplateBlock.export.error.title"); //$NON-NLS-1$ - String message = PreferencesMessages.getFormattedString("CodeTemplateBlock.export.error.hidden", file.getAbsolutePath()); //$NON-NLS-1$ - MessageDialog.openError(getShell(), title, message); - return; - } - - if (file.exists() && !file.canWrite()) { - String title = PreferencesMessages.getString("CodeTemplateBlock.export.error.title"); //$NON-NLS-1$ - String message = PreferencesMessages.getFormattedString("CodeTemplateBlock.export.error.canNotWrite", file.getAbsolutePath()); //$NON-NLS-1$ - MessageDialog.openError(getShell(), title, message); - return; - } - - if (!file.exists() || confirmOverwrite(file)) { - try { - OutputStream output = new BufferedOutputStream(new FileOutputStream(file)); - TemplateReaderWriter writer = new TemplateReaderWriter(); - writer.save(templates, output); - } catch (IOException e) { - openWriteErrorDialog(e); - } - } - - } - - private boolean confirmOverwrite(File file) { - return MessageDialog.openQuestion(getShell(), PreferencesMessages.getString("CodeTemplateBlock.export.exists.title"), //$NON-NLS-1$ - PreferencesMessages.getFormattedString("CodeTemplateBlock.export.exists.message", file.getAbsolutePath())); //$NON-NLS-1$ - } - - public void performDefaults() { - IPreferenceStore prefs = PHPeclipsePlugin.getDefault().getPreferenceStore(); - fCreateJavaDocComments.setSelection(prefs.getDefaultBoolean(PREF_JAVADOC_STUBS)); - - fTemplates.restoreDefaults(); - - // refresh - fCodeTemplateTree.refresh(); - updateSourceViewerInput(fCodeTemplateTree.getSelectedElements()); - } - - public boolean performOk(boolean enabled) { - IPreferenceStore prefs = PreferenceConstants.getPreferenceStore(); - prefs.setValue(PREF_JAVADOC_STUBS, fCreateJavaDocComments.isSelected()); - PHPeclipsePlugin.getDefault().savePluginPreferences(); - - try { - fTemplates.save(); - } catch (IOException e) { - PHPeclipsePlugin.log(e); - openWriteErrorDialog(e); - } - return true; - } - - public void performCancel() { - try { - fTemplates.load(); - } catch (IOException e) { - openReadErrorDialog(e); - } - } - - private void openReadErrorDialog(Exception e) { - String title = PreferencesMessages.getString("CodeTemplateBlock.error.read.title"); //$NON-NLS-1$ - - String message = e.getLocalizedMessage(); - if (message != null) - message = PreferencesMessages.getFormattedString("CodeTemplateBlock.error.parse.message", message); //$NON-NLS-1$ - else - message = PreferencesMessages.getString("CodeTemplateBlock.error.read.message"); //$NON-NLS-1$ - MessageDialog.openError(getShell(), title, message); - } - - private void openWriteErrorDialog(Exception e) { - String title = PreferencesMessages.getString("CodeTemplateBlock.error.write.title"); //$NON-NLS-1$ - String message = PreferencesMessages.getString("CodeTemplateBlock.error.write.message"); //$NON-NLS-1$ - MessageDialog.openError(getShell(), title, message); - } + private class CodeTemplateAdapter implements ITreeListAdapter, + IDialogFieldListener { + + private final Object[] NO_CHILDREN = new Object[0]; + + public void customButtonPressed(TreeListDialogField field, int index) { + doButtonPressed(index, field.getSelectedElements()); + } + + public void selectionChanged(TreeListDialogField field) { + List selected = field.getSelectedElements(); + field.enableButton(IDX_EDIT, canEdit(selected)); + field.enableButton(IDX_EXPORT, !selected.isEmpty()); + + updateSourceViewerInput(selected); + } + + public void doubleClicked(TreeListDialogField field) { + List selected = field.getSelectedElements(); + if (canEdit(selected)) { + doButtonPressed(IDX_EDIT, selected); + } + } + + public Object[] getChildren(TreeListDialogField field, Object element) { + if (element == COMMENT_NODE || element == CODE_NODE) { + return getTemplateOfCategory(element == COMMENT_NODE); + } + return NO_CHILDREN; + } + + public Object getParent(TreeListDialogField field, Object element) { + if (element instanceof TemplatePersistenceData) { + TemplatePersistenceData data = (TemplatePersistenceData) element; + if (data.getTemplate().getName().endsWith( + CodeTemplateContextType.COMMENT_SUFFIX)) { + return COMMENT_NODE; + } + return CODE_NODE; + } + return null; + } + + public boolean hasChildren(TreeListDialogField field, Object element) { + return (element == COMMENT_NODE || element == CODE_NODE); + } + + public void dialogFieldChanged(DialogField field) { + } + + public void keyPressed(TreeListDialogField field, KeyEvent event) { + } + + } + + private static class CodeTemplateLabelProvider extends LabelProvider { + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object) + */ + public Image getImage(Object element) { + return null; + + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object) + */ + public String getText(Object element) { + if (element == COMMENT_NODE || element == CODE_NODE) { + return (String) element; + } + TemplatePersistenceData data = (TemplatePersistenceData) element; + Template template = data.getTemplate(); + String name = template.getName(); + if (CodeTemplateContextType.CATCHBLOCK.equals(name)) { + return PreferencesMessages + .getString("CodeTemplateBlock.catchblock.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.METHODSTUB.equals(name)) { + return PreferencesMessages + .getString("CodeTemplateBlock.methodstub.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.CONSTRUCTORSTUB.equals(name)) { + return PreferencesMessages + .getString("CodeTemplateBlock.constructorstub.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.GETTERSTUB.equals(name)) { + return PreferencesMessages + .getString("CodeTemplateBlock.getterstub.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.SETTERSTUB.equals(name)) { + return PreferencesMessages + .getString("CodeTemplateBlock.setterstub.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.NEWTYPE.equals(name)) { + return PreferencesMessages + .getString("CodeTemplateBlock.newtype.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.TYPECOMMENT.equals(name)) { + return PreferencesMessages + .getString("CodeTemplateBlock.typecomment.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.FIELDCOMMENT.equals(name)) { + return PreferencesMessages + .getString("CodeTemplateBlock.fieldcomment.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.METHODCOMMENT.equals(name)) { + return PreferencesMessages + .getString("CodeTemplateBlock.methodcomment.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.OVERRIDECOMMENT.equals(name)) { + return PreferencesMessages + .getString("CodeTemplateBlock.overridecomment.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.CONSTRUCTORCOMMENT.equals(name)) { + return PreferencesMessages + .getString("CodeTemplateBlock.constructorcomment.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.GETTERCOMMENT.equals(name)) { + return PreferencesMessages + .getString("CodeTemplateBlock.gettercomment.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.SETTERCOMMENT.equals(name)) { + return PreferencesMessages + .getString("CodeTemplateBlock.settercomment.label"); //$NON-NLS-1$ + } + return template.getDescription(); + } + + } + + private final static int IDX_EDIT = 0; + + private final static int IDX_IMPORT = 2; + + private final static int IDX_EXPORT = 3; + + private final static int IDX_EXPORTALL = 4; + + protected final static Object COMMENT_NODE = PreferencesMessages + .getString("CodeTemplateBlock.templates.comment.node"); //$NON-NLS-1$ + + protected final static Object CODE_NODE = PreferencesMessages + .getString("CodeTemplateBlock.templates.code.node"); //$NON-NLS-1$ + + private static final String PREF_JAVADOC_STUBS = PreferenceConstants.CODEGEN_ADD_COMMENTS; + + private TreeListDialogField fCodeTemplateTree; + + private SelectionButtonDialogField fCreateJavaDocComments; + + protected TemplateStore fTemplates; + + private PixelConverter fPixelConverter; + + private SourceViewer fPatternViewer; + + private Control fSWTWidget; + + private TemplateVariableProcessor fTemplateProcessor; + + public CodeTemplateBlock() { + + fTemplates = PHPeclipsePlugin.getDefault().getCodeTemplateStore(); + fTemplateProcessor = new TemplateVariableProcessor(); + + CodeTemplateAdapter adapter = new CodeTemplateAdapter(); + + String[] buttonLabels = new String[] { + /* IDX_EDIT */PreferencesMessages + .getString("CodeTemplateBlock.templates.edit.button"), //$NON-NLS-1$ + /* */null, + /* IDX_IMPORT */PreferencesMessages + .getString("CodeTemplateBlock.templates.import.button"), //$NON-NLS-1$ + /* IDX_EXPORT */PreferencesMessages + .getString("CodeTemplateBlock.templates.export.button"), //$NON-NLS-1$ + /* IDX_EXPORTALL */PreferencesMessages + .getString("CodeTemplateBlock.templates.exportall.button") //$NON-NLS-1$ + + }; + fCodeTemplateTree = new TreeListDialogField(adapter, buttonLabels, + new CodeTemplateLabelProvider()); + fCodeTemplateTree.setDialogFieldListener(adapter); + fCodeTemplateTree.setLabelText(PreferencesMessages + .getString("CodeTemplateBlock.templates.label")); //$NON-NLS-1$ + + fCodeTemplateTree.enableButton(IDX_EXPORT, false); + fCodeTemplateTree.enableButton(IDX_EDIT, false); + + fCodeTemplateTree.addElement(COMMENT_NODE); + fCodeTemplateTree.addElement(CODE_NODE); + + fCreateJavaDocComments = new SelectionButtonDialogField(SWT.CHECK + | SWT.WRAP); + fCreateJavaDocComments.setLabelText(PreferencesMessages + .getString("CodeTemplateBlock.createcomment.label")); //$NON-NLS-1$ + fCreateJavaDocComments.setSelection(PreferenceConstants + .getPreferenceStore().getBoolean(PREF_JAVADOC_STUBS)); + + fCodeTemplateTree.selectFirstElement(); + } + + protected Control createContents(Composite parent) { + fPixelConverter = new PixelConverter(parent); + fSWTWidget = parent; + + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginHeight = 0; + layout.marginWidth = 0; + layout.numColumns = 2; + composite.setLayout(layout); + + fCodeTemplateTree.doFillIntoGrid(composite, 3); + LayoutUtil + .setHorizontalSpan(fCodeTemplateTree.getLabelControl(null), 2); + LayoutUtil + .setHorizontalGrabbing(fCodeTemplateTree.getTreeControl(null)); + + fPatternViewer = createViewer(composite, 2); + + fCreateJavaDocComments.doFillIntoGrid(composite, 2); + + DialogField label = new DialogField(); + label.setLabelText(PreferencesMessages + .getString("CodeTemplateBlock.createcomment.description")); //$NON-NLS-1$ + label.doFillIntoGrid(composite, 2); + + return composite; + + } + + private Shell getShell() { + if (fSWTWidget != null) { + return fSWTWidget.getShell(); + } + return PHPeclipsePlugin.getActiveWorkbenchShell(); + } + + private SourceViewer createViewer(Composite parent, int nColumns) { + Label label = new Label(parent, SWT.NONE); + label.setText(PreferencesMessages + .getString("CodeTemplateBlock.preview")); //$NON-NLS-1$ + GridData data = new GridData(); + data.horizontalSpan = nColumns; + label.setLayoutData(data); + + IDocument document = new Document(); + JavaTextTools tools = PHPeclipsePlugin.getDefault().getJavaTextTools(); + tools.setupJavaDocumentPartitioner(document, + IPHPPartitions.PHP_PARTITIONING); + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getCombinedPreferenceStore(); + SourceViewer viewer = new JavaSourceViewer(parent, null, null, false, + SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL, store); + TemplateEditorSourceViewerConfiguration configuration = new TemplateEditorSourceViewerConfiguration( + tools.getColorManager(), store, null, fTemplateProcessor); + viewer.configure(configuration); + viewer.setEditable(false); + viewer.setDocument(document); + + Font font = JFaceResources + .getFont(PreferenceConstants.EDITOR_TEXT_FONT); + viewer.getTextWidget().setFont(font); + new JavaSourcePreviewerUpdater(viewer, configuration, store); + + Control control = viewer.getControl(); + data = new GridData(GridData.HORIZONTAL_ALIGN_FILL + | GridData.FILL_VERTICAL); + data.horizontalSpan = nColumns; + data.heightHint = fPixelConverter.convertHeightInCharsToPixels(5); + control.setLayoutData(data); + + return viewer; + } + + protected TemplatePersistenceData[] getTemplateOfCategory(boolean isComment) { + ArrayList res = new ArrayList(); + TemplatePersistenceData[] templates = fTemplates.getTemplateData(false); + for (int i = 0; i < templates.length; i++) { + TemplatePersistenceData curr = templates[i]; + if (isComment == curr.getTemplate().getName().endsWith( + CodeTemplateContextType.COMMENT_SUFFIX)) { + res.add(curr); + } + } + return (TemplatePersistenceData[]) res + .toArray(new TemplatePersistenceData[res.size()]); + } + + protected static boolean canEdit(List selected) { + return selected.size() == 1 + && (selected.get(0) instanceof TemplatePersistenceData); + } + + protected void updateSourceViewerInput(List selection) { + if (fPatternViewer == null + || fPatternViewer.getTextWidget().isDisposed()) { + return; + } + if (selection.size() == 1 + && selection.get(0) instanceof TemplatePersistenceData) { + TemplatePersistenceData data = (TemplatePersistenceData) selection + .get(0); + Template template = data.getTemplate(); + TemplateContextType type = PHPeclipsePlugin.getDefault() + .getCodeTemplateContextRegistry().getContextType( + template.getContextTypeId()); + fTemplateProcessor.setContextType(type); + fPatternViewer.getDocument().set(template.getPattern()); + } else { + fPatternViewer.getDocument().set(""); //$NON-NLS-1$ + } + } + + protected void doButtonPressed(int buttonIndex, List selected) { + if (buttonIndex == IDX_EDIT) { + edit((TemplatePersistenceData) selected.get(0)); + } else if (buttonIndex == IDX_EXPORT) { + export(selected); + } else if (buttonIndex == IDX_EXPORTALL) { + exportAll(); + } else if (buttonIndex == IDX_IMPORT) { + import_(); + } + } + + private void edit(TemplatePersistenceData data) { + Template newTemplate = new Template(data.getTemplate()); + EditTemplateDialog dialog = new EditTemplateDialog(getShell(), + newTemplate, true, false, PHPeclipsePlugin.getDefault() + .getCodeTemplateContextRegistry()); + if (dialog.open() == Window.OK) { + // changed + data.setTemplate(newTemplate); + fCodeTemplateTree.refresh(data); + fCodeTemplateTree.selectElements(new StructuredSelection(data)); + } + } + + private void import_() { + FileDialog dialog = new FileDialog(getShell()); + dialog.setText(PreferencesMessages + .getString("CodeTemplateBlock.import.title")); //$NON-NLS-1$ + dialog.setFilterExtensions(new String[] { PreferencesMessages + .getString("CodeTemplateBlock.import.extension") }); //$NON-NLS-1$ + String path = dialog.open(); + + if (path == null) + return; + + try { + TemplateReaderWriter reader = new TemplateReaderWriter(); + File file = new File(path); + if (file.exists()) { + InputStream input = new BufferedInputStream( + new FileInputStream(file)); + TemplatePersistenceData[] datas = reader.read(input, null); + for (int i = 0; i < datas.length; i++) { + updateTemplate(datas[i]); + } + } + + fCodeTemplateTree.refresh(); + updateSourceViewerInput(fCodeTemplateTree.getSelectedElements()); + + } catch (FileNotFoundException e) { + openReadErrorDialog(e); + } catch (IOException e) { + openReadErrorDialog(e); + } + + } + + private void updateTemplate(TemplatePersistenceData data) { + TemplatePersistenceData[] datas = fTemplates.getTemplateData(true); + for (int i = 0; i < datas.length; i++) { + String id = datas[i].getId(); + if (id != null && id.equals(data.getId())) { + datas[i].setTemplate(data.getTemplate()); + break; + } + } + } + + private void exportAll() { + export(fTemplates.getTemplateData(false)); + } + + private void export(List selected) { + List datas = new ArrayList(); + for (int i = 0; i < selected.size(); i++) { + Object curr = selected.get(i); + if (curr instanceof TemplatePersistenceData) { + datas.add(curr); + } else { + TemplatePersistenceData[] cat = getTemplateOfCategory(curr == COMMENT_NODE); + datas.addAll(Arrays.asList(cat)); + } + } + export((TemplatePersistenceData[]) datas + .toArray(new TemplatePersistenceData[datas.size()])); + } + + private void export(TemplatePersistenceData[] templates) { + FileDialog dialog = new FileDialog(getShell(), SWT.SAVE); + dialog + .setText(PreferencesMessages + .getFormattedString( + "CodeTemplateBlock.export.title", String.valueOf(templates.length))); //$NON-NLS-1$ + dialog.setFilterExtensions(new String[] { PreferencesMessages + .getString("CodeTemplateBlock.export.extension") }); //$NON-NLS-1$ + dialog.setFileName(PreferencesMessages + .getString("CodeTemplateBlock.export.filename")); //$NON-NLS-1$ + String path = dialog.open(); + + if (path == null) + return; + + File file = new File(path); + + if (file.isHidden()) { + String title = PreferencesMessages + .getString("CodeTemplateBlock.export.error.title"); //$NON-NLS-1$ + String message = PreferencesMessages + .getFormattedString( + "CodeTemplateBlock.export.error.hidden", file.getAbsolutePath()); //$NON-NLS-1$ + MessageDialog.openError(getShell(), title, message); + return; + } + + if (file.exists() && !file.canWrite()) { + String title = PreferencesMessages + .getString("CodeTemplateBlock.export.error.title"); //$NON-NLS-1$ + String message = PreferencesMessages + .getFormattedString( + "CodeTemplateBlock.export.error.canNotWrite", file.getAbsolutePath()); //$NON-NLS-1$ + MessageDialog.openError(getShell(), title, message); + return; + } + + if (!file.exists() || confirmOverwrite(file)) { + try { + OutputStream output = new BufferedOutputStream( + new FileOutputStream(file)); + TemplateReaderWriter writer = new TemplateReaderWriter(); + writer.save(templates, output); + } catch (IOException e) { + openWriteErrorDialog(e); + } + } + + } + + private boolean confirmOverwrite(File file) { + return MessageDialog + .openQuestion( + getShell(), + PreferencesMessages + .getString("CodeTemplateBlock.export.exists.title"), //$NON-NLS-1$ + PreferencesMessages + .getFormattedString( + "CodeTemplateBlock.export.exists.message", file.getAbsolutePath())); //$NON-NLS-1$ + } + + public void performDefaults() { + IPreferenceStore prefs = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + fCreateJavaDocComments.setSelection(prefs + .getDefaultBoolean(PREF_JAVADOC_STUBS)); + + fTemplates.restoreDefaults(); + + // refresh + fCodeTemplateTree.refresh(); + updateSourceViewerInput(fCodeTemplateTree.getSelectedElements()); + } + + public boolean performOk(boolean enabled) { + IPreferenceStore prefs = PreferenceConstants.getPreferenceStore(); + prefs.setValue(PREF_JAVADOC_STUBS, fCreateJavaDocComments.isSelected()); + PHPeclipsePlugin.getDefault().savePluginPreferences(); + + try { + fTemplates.save(); + } catch (IOException e) { + PHPeclipsePlugin.log(e); + openWriteErrorDialog(e); + } + return true; + } + + public void performCancel() { + try { + fTemplates.load(); + } catch (IOException e) { + openReadErrorDialog(e); + } + } + + private void openReadErrorDialog(Exception e) { + String title = PreferencesMessages + .getString("CodeTemplateBlock.error.read.title"); //$NON-NLS-1$ + + String message = e.getLocalizedMessage(); + if (message != null) + message = PreferencesMessages.getFormattedString( + "CodeTemplateBlock.error.parse.message", message); //$NON-NLS-1$ + else + message = PreferencesMessages + .getString("CodeTemplateBlock.error.read.message"); //$NON-NLS-1$ + MessageDialog.openError(getShell(), title, message); + } + + private void openWriteErrorDialog(Exception e) { + String title = PreferencesMessages + .getString("CodeTemplateBlock.error.write.title"); //$NON-NLS-1$ + String message = PreferencesMessages + .getString("CodeTemplateBlock.error.write.message"); //$NON-NLS-1$ + MessageDialog.openError(getShell(), title, message); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplatePreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplatePreferencePage.java index 2c122ff..822f445 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplatePreferencePage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplatePreferencePage.java @@ -27,18 +27,21 @@ import org.eclipse.ui.PlatformUI; /* * The page to configure the code formatter options. */ -public class CodeTemplatePreferencePage extends PreferencePage implements IWorkbenchPreferencePage, IStatusChangeListener { +public class CodeTemplatePreferencePage extends PreferencePage implements + IWorkbenchPreferencePage, IStatusChangeListener { private CodeTemplateBlock fCodeTemplateConfigurationBlock; public CodeTemplatePreferencePage() { setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); - //setDescription(PreferencesMessages.getString("CodeTemplatesPreferencePage.description")); //$NON-NLS-1$ + // setDescription(PreferencesMessages.getString("CodeTemplatesPreferencePage.description")); + // //$NON-NLS-1$ // only used when page is shown programatically - setTitle(PreferencesMessages.getString("CodeTemplatesPreferencePage.title")); //$NON-NLS-1$ + setTitle(PreferencesMessages + .getString("CodeTemplatesPreferencePage.title")); //$NON-NLS-1$ - fCodeTemplateConfigurationBlock= new CodeTemplateBlock(); + fCodeTemplateConfigurationBlock = new CodeTemplateBlock(); } /* @@ -52,14 +55,16 @@ public class CodeTemplatePreferencePage extends PreferencePage implements IWorkb */ public void createControl(Composite parent) { super.createControl(parent); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.CODE_MANIPULATION_PREFERENCE_PAGE); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), + IJavaHelpContextIds.CODE_MANIPULATION_PREFERENCE_PAGE); } /* * @see PreferencePage#createContents(Composite) */ protected Control createContents(Composite parent) { - Control composite= fCodeTemplateConfigurationBlock.createContents(parent); + Control composite = fCodeTemplateConfigurationBlock + .createContents(parent); Dialog.applyDialogFont(composite); return composite; } @@ -82,7 +87,9 @@ public class CodeTemplatePreferencePage extends PreferencePage implements IWorkb super.performDefaults(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener#statusChanged(org.eclipse.core.runtime.IStatus) */ public void statusChanged(IStatus status) { @@ -90,7 +97,9 @@ public class CodeTemplatePreferencePage extends PreferencePage implements IWorkb StatusUtil.applyToStatusLine(this, status); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.preference.IPreferencePage#performCancel() */ public boolean performCancel() { @@ -100,6 +109,3 @@ public class CodeTemplatePreferencePage extends PreferencePage implements IWorkb } } - - - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/ColorEditor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/ColorEditor.java index 00b011b..a4c4761 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/ColorEditor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/ColorEditor.java @@ -32,90 +32,95 @@ import org.eclipse.swt.widgets.Display; * A "button" of a certain color determined by the color picker. */ public class ColorEditor { - + private Point fExtent; + private Image fImage; + private RGB fColorValue; + private Color fColor; + private Button fButton; - + public ColorEditor(Composite parent) { - - fButton= new Button(parent, SWT.PUSH); - fExtent= computeImageSize(parent); - fImage= new Image(parent.getDisplay(), fExtent.x, fExtent.y); - - GC gc= new GC(fImage); + + fButton = new Button(parent, SWT.PUSH); + fExtent = computeImageSize(parent); + fImage = new Image(parent.getDisplay(), fExtent.x, fExtent.y); + + GC gc = new GC(fImage); gc.setBackground(fButton.getBackground()); gc.fillRectangle(0, 0, fExtent.x, fExtent.y); gc.dispose(); - + fButton.setImage(fImage); fButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { - ColorDialog colorDialog= new ColorDialog(fButton.getShell()); + ColorDialog colorDialog = new ColorDialog(fButton.getShell()); colorDialog.setRGB(fColorValue); RGB newColor = colorDialog.open(); if (newColor != null) { - fColorValue= newColor; + fColorValue = newColor; updateColorImage(); } } }); - + fButton.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent event) { - if (fImage != null) { + if (fImage != null) { fImage.dispose(); - fImage= null; + fImage = null; } if (fColor != null) { fColor.dispose(); - fColor= null; + fColor = null; } } }); } - + public RGB getColorValue() { return fColorValue; } - + public void setColorValue(RGB rgb) { - fColorValue= rgb; + fColorValue = rgb; updateColorImage(); } - + public Button getButton() { return fButton; } - + protected void updateColorImage() { - - Display display= fButton.getDisplay(); - - GC gc= new GC(fImage); + + Display display = fButton.getDisplay(); + + GC gc = new GC(fImage); gc.setForeground(display.getSystemColor(SWT.COLOR_BLACK)); gc.drawRectangle(0, 2, fExtent.x - 1, fExtent.y - 4); - + if (fColor != null) fColor.dispose(); - - fColor= new Color(display, fColorValue); + + fColor = new Color(display, fColorValue); gc.setBackground(fColor); gc.fillRectangle(1, 3, fExtent.x - 2, fExtent.y - 5); gc.dispose(); - + fButton.setImage(fImage); } - + protected Point computeImageSize(Control window) { - GC gc= new GC(window); - Font f= JFaceResources.getFontRegistry().get(JFaceResources.DEFAULT_FONT); + GC gc = new GC(window); + Font f = JFaceResources.getFontRegistry().get( + JFaceResources.DEFAULT_FONT); gc.setFont(f); - int height= gc.getFontMetrics().getHeight(); + int height = gc.getFontMetrics().getHeight(); gc.dispose(); - Point p= new Point(height * 3 - 6, height); + Point p = new Point(height * 3 - 6, height); return p; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CompilerConfigurationBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CompilerConfigurationBlock.java index 8ebb7da..05e76f8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CompilerConfigurationBlock.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CompilerConfigurationBlock.java @@ -33,550 +33,740 @@ import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Text; /** - */ + */ public class CompilerConfigurationBlock extends OptionsConfigurationBlock { // Preference store keys, see JavaCore.getOptions - private static final String PREF_PB_PHP_VAR_DEPRECATED= JavaCore.COMPILER_PB_PHP_VAR_DEPRECATED; - private static final String PREF_PB_PHP_KEYWORD= JavaCore.COMPILER_PB_PHP_KEYWORD; - private static final String PREF_PB_PHP_UPPERCASE_IDENTIFIER= JavaCore.COMPILER_PB_PHP_UPPERCASE_IDENTIFIER; - private static final String PREF_PB_PHP_FILE_NOT_EXIST= JavaCore.COMPILER_PB_PHP_FILE_NOT_EXIST; - private static final String PREF_PB_UNREACHABLE_CODE= JavaCore.COMPILER_PB_UNREACHABLE_CODE; - private static final String PREF_PB_UNINITIALIZED_LOCAL_VARIABLE= JavaCore.COMPILER_PB_UNINITIALIZED_LOCAL_VARIABLE; -// private static final String PREF_LOCAL_VARIABLE_ATTR= JavaCore.COMPILER_LOCAL_VARIABLE_ATTR; -// private static final String PREF_LINE_NUMBER_ATTR= JavaCore.COMPILER_LINE_NUMBER_ATTR; -// private static final String PREF_SOURCE_FILE_ATTR= JavaCore.COMPILER_SOURCE_FILE_ATTR; -// private static final String PREF_CODEGEN_UNUSED_LOCAL= JavaCore.COMPILER_CODEGEN_UNUSED_LOCAL; -// private static final String PREF_CODEGEN_TARGET_PLATFORM= JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM; - //private static final String PREF_PB_UNREACHABLE_CODE= JavaCore.COMPILER_PB_UNREACHABLE_CODE; - //private static final String PREF_PB_INVALID_IMPORT= JavaCore.COMPILER_PB_INVALID_IMPORT; -// private static final String PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD= JavaCore.COMPILER_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD; -// private static final String PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME= JavaCore.COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME; -// private static final String PREF_PB_DEPRECATION= JavaCore.COMPILER_PB_DEPRECATION; -// private static final String PREF_PB_DEPRECATION_WHEN_OVERRIDING= JavaCore.COMPILER_PB_DEPRECATION_WHEN_OVERRIDING_DEPRECATED_METHOD; - -// private static final String PREF_PB_HIDDEN_CATCH_BLOCK= JavaCore.COMPILER_PB_HIDDEN_CATCH_BLOCK; -// private static final String PREF_PB_UNUSED_LOCAL= JavaCore.COMPILER_PB_UNUSED_LOCAL; -// private static final String PREF_PB_UNUSED_PARAMETER= JavaCore.COMPILER_PB_UNUSED_PARAMETER; -// private static final String PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING= JavaCore.COMPILER_PB_UNUSED_PARAMETER_WHEN_OVERRIDING_CONCRETE; -// private static final String PREF_PB_SIGNAL_PARAMETER_IN_ABSTRACT= JavaCore.COMPILER_PB_UNUSED_PARAMETER_WHEN_IMPLEMENTING_ABSTRACT; -// private static final String PREF_PB_SYNTHETIC_ACCESS_EMULATION= JavaCore.COMPILER_PB_SYNTHETIC_ACCESS_EMULATION; -// private static final String PREF_PB_NON_EXTERNALIZED_STRINGS= JavaCore.COMPILER_PB_NON_NLS_STRING_LITERAL; -// private static final String PREF_PB_ASSERT_AS_IDENTIFIER= JavaCore.COMPILER_PB_ASSERT_IDENTIFIER; - private static final String PREF_PB_MAX_PER_UNIT= JavaCore.COMPILER_PB_MAX_PER_UNIT; -// private static final String PREF_PB_UNUSED_IMPORT= JavaCore.COMPILER_PB_UNUSED_IMPORT; -// private static final String PREF_PB_UNUSED_PRIVATE= JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER; -// private static final String PREF_PB_STATIC_ACCESS_RECEIVER= JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER; -// private static final String PREF_PB_NO_EFFECT_ASSIGNMENT= JavaCore.COMPILER_PB_NO_EFFECT_ASSIGNMENT; -// private static final String PREF_PB_CHAR_ARRAY_IN_CONCAT= JavaCore.COMPILER_PB_CHAR_ARRAY_IN_STRING_CONCATENATION; -// private static final String PREF_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT= JavaCore.COMPILER_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT; -// private static final String PREF_PB_LOCAL_VARIABLE_HIDING= JavaCore.COMPILER_PB_LOCAL_VARIABLE_HIDING; -// private static final String PREF_PB_FIELD_HIDING= JavaCore.COMPILER_PB_FIELD_HIDING; -// private static final String PREF_PB_SPECIAL_PARAMETER_HIDING_FIELD= JavaCore.COMPILER_PB_SPECIAL_PARAMETER_HIDING_FIELD; -// private static final String PREF_PB_INDIRECT_STATIC_ACCESS= JavaCore.COMPILER_PB_INDIRECT_STATIC_ACCESS; -// private static final String PREF_PB_SUPERFLUOUS_SEMICOLON= JavaCore.COMPILER_PB_SUPERFLUOUS_SEMICOLON; -// private static final String PREF_PB_UNNECESSARY_TYPE_CHECK= JavaCore.COMPILER_PB_UNNECESSARY_TYPE_CHECK; - -// private static final String PREF_PB_INVALID_JAVADOC= JavaCore.COMPILER_PB_INVALID_JAVADOC; -// private static final String PREF_PB_INVALID_JAVADOC_TAGS= JavaCore.COMPILER_PB_INVALID_JAVADOC_TAGS; -// private static final String PREF_PB_INVALID_JAVADOC_TAGS_VISIBILITY= JavaCore.COMPILER_PB_INVALID_JAVADOC_TAGS_VISIBILITY; -// -// private static final String PREF_PB_MISSING_JAVADOC_TAGS= JavaCore.COMPILER_PB_MISSING_JAVADOC_TAGS; -// private static final String PREF_PB_MISSING_JAVADOC_TAGS_VISIBILITY= JavaCore.COMPILER_PB_MISSING_JAVADOC_TAGS_VISIBILITY; -// private static final String PREF_PB_MISSING_JAVADOC_TAGS_OVERRIDING= JavaCore.COMPILER_PB_MISSING_JAVADOC_TAGS_OVERRIDING; -// -// private static final String PREF_PB_MISSING_JAVADOC_COMMENTS= JavaCore.COMPILER_PB_MISSING_JAVADOC_COMMENTS; -// private static final String PREF_PB_MISSING_JAVADOC_COMMENTS_VISIBILITY= JavaCore.COMPILER_PB_MISSING_JAVADOC_COMMENTS_VISIBILITY; -// private static final String PREF_PB_MISSING_JAVADOC_COMMENTS_OVERRIDING= JavaCore.COMPILER_PB_MISSING_JAVADOC_COMMENTS_OVERRIDING; -// -// private static final String PREF_SOURCE_COMPATIBILITY= JavaCore.COMPILER_SOURCE; -// private static final String PREF_COMPLIANCE= JavaCore.COMPILER_COMPLIANCE; -// -// private static final String PREF_RESOURCE_FILTER= JavaCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER; -// private static final String PREF_BUILD_INVALID_CLASSPATH= JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH; -// private static final String PREF_BUILD_CLEAN_OUTPUT_FOLDER= JavaCore.CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER; -// private static final String PREF_ENABLE_EXCLUSION_PATTERNS= JavaCore.CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS; -// private static final String PREF_ENABLE_MULTIPLE_OUTPUT_LOCATIONS= JavaCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS; -// -// private static final String PREF_PB_INCOMPLETE_BUILDPATH= JavaCore.CORE_INCOMPLETE_CLASSPATH; -// private static final String PREF_PB_CIRCULAR_BUILDPATH= JavaCore.CORE_CIRCULAR_CLASSPATH; -//// private static final String PREF_PB_INCOMPATIBLE_JDK_LEVEL= JavaCore.CORE_INCOMPATIBLE_JDK_LEVEL; -// private static final String PREF_PB_DEPRECATION_IN_DEPRECATED_CODE= JavaCore.COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE; -// private static final String PREF_PB_DUPLICATE_RESOURCE= JavaCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE; -// private static final String PREF_PB_INCOMPATIBLE_INTERFACE_METHOD= JavaCore.COMPILER_PB_INCOMPATIBLE_NON_INHERITED_INTERFACE_METHOD; - -// private static final String PREF_PB_UNDOCUMENTED_EMPTY_BLOCK= JavaCore.COMPILER_PB_UNDOCUMENTED_EMPTY_BLOCK; -// private static final String PREF_PB_FINALLY_BLOCK_NOT_COMPLETING= JavaCore.COMPILER_PB_FINALLY_BLOCK_NOT_COMPLETING; -// private static final String PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION= JavaCore.COMPILER_PB_UNUSED_DECLARED_THROWN_EXCEPTION; -// private static final String PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION_WHEN_OVERRIDING= JavaCore.COMPILER_PB_UNUSED_DECLARED_THROWN_EXCEPTION_WHEN_OVERRIDING; -// private static final String PREF_PB_UNQUALIFIED_FIELD_ACCESS= JavaCore.COMPILER_PB_UNQUALIFIED_FIELD_ACCESS; - -// private static final String INTR_DEFAULT_COMPLIANCE= "internal.default.compliance"; //$NON-NLS-1$ + private static final String PREF_PB_PHP_VAR_DEPRECATED = JavaCore.COMPILER_PB_PHP_VAR_DEPRECATED; + + private static final String PREF_PB_PHP_KEYWORD = JavaCore.COMPILER_PB_PHP_KEYWORD; + + private static final String PREF_PB_PHP_UPPERCASE_IDENTIFIER = JavaCore.COMPILER_PB_PHP_UPPERCASE_IDENTIFIER; + + private static final String PREF_PB_PHP_FILE_NOT_EXIST = JavaCore.COMPILER_PB_PHP_FILE_NOT_EXIST; + + private static final String PREF_PB_UNREACHABLE_CODE = JavaCore.COMPILER_PB_UNREACHABLE_CODE; + + private static final String PREF_PB_UNINITIALIZED_LOCAL_VARIABLE = JavaCore.COMPILER_PB_UNINITIALIZED_LOCAL_VARIABLE; + + // private static final String PREF_LOCAL_VARIABLE_ATTR= + // JavaCore.COMPILER_LOCAL_VARIABLE_ATTR; + // private static final String PREF_LINE_NUMBER_ATTR= + // JavaCore.COMPILER_LINE_NUMBER_ATTR; + // private static final String PREF_SOURCE_FILE_ATTR= + // JavaCore.COMPILER_SOURCE_FILE_ATTR; + // private static final String PREF_CODEGEN_UNUSED_LOCAL= + // JavaCore.COMPILER_CODEGEN_UNUSED_LOCAL; + // private static final String PREF_CODEGEN_TARGET_PLATFORM= + // JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM; + // private static final String PREF_PB_UNREACHABLE_CODE= + // JavaCore.COMPILER_PB_UNREACHABLE_CODE; + // private static final String PREF_PB_INVALID_IMPORT= + // JavaCore.COMPILER_PB_INVALID_IMPORT; + // private static final String PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD= + // JavaCore.COMPILER_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD; + // private static final String PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME= + // JavaCore.COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME; + // private static final String PREF_PB_DEPRECATION= + // JavaCore.COMPILER_PB_DEPRECATION; + // private static final String PREF_PB_DEPRECATION_WHEN_OVERRIDING= + // JavaCore.COMPILER_PB_DEPRECATION_WHEN_OVERRIDING_DEPRECATED_METHOD; + + // private static final String PREF_PB_HIDDEN_CATCH_BLOCK= + // JavaCore.COMPILER_PB_HIDDEN_CATCH_BLOCK; + // private static final String PREF_PB_UNUSED_LOCAL= + // JavaCore.COMPILER_PB_UNUSED_LOCAL; + // private static final String PREF_PB_UNUSED_PARAMETER= + // JavaCore.COMPILER_PB_UNUSED_PARAMETER; + // private static final String PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING= + // JavaCore.COMPILER_PB_UNUSED_PARAMETER_WHEN_OVERRIDING_CONCRETE; + // private static final String PREF_PB_SIGNAL_PARAMETER_IN_ABSTRACT= + // JavaCore.COMPILER_PB_UNUSED_PARAMETER_WHEN_IMPLEMENTING_ABSTRACT; + // private static final String PREF_PB_SYNTHETIC_ACCESS_EMULATION= + // JavaCore.COMPILER_PB_SYNTHETIC_ACCESS_EMULATION; + // private static final String PREF_PB_NON_EXTERNALIZED_STRINGS= + // JavaCore.COMPILER_PB_NON_NLS_STRING_LITERAL; + // private static final String PREF_PB_ASSERT_AS_IDENTIFIER= + // JavaCore.COMPILER_PB_ASSERT_IDENTIFIER; + private static final String PREF_PB_MAX_PER_UNIT = JavaCore.COMPILER_PB_MAX_PER_UNIT; + + // private static final String PREF_PB_UNUSED_IMPORT= + // JavaCore.COMPILER_PB_UNUSED_IMPORT; + // private static final String PREF_PB_UNUSED_PRIVATE= + // JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER; + // private static final String PREF_PB_STATIC_ACCESS_RECEIVER= + // JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER; + // private static final String PREF_PB_NO_EFFECT_ASSIGNMENT= + // JavaCore.COMPILER_PB_NO_EFFECT_ASSIGNMENT; + // private static final String PREF_PB_CHAR_ARRAY_IN_CONCAT= + // JavaCore.COMPILER_PB_CHAR_ARRAY_IN_STRING_CONCATENATION; + // private static final String + // PREF_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT= + // JavaCore.COMPILER_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT; + // private static final String PREF_PB_LOCAL_VARIABLE_HIDING= + // JavaCore.COMPILER_PB_LOCAL_VARIABLE_HIDING; + // private static final String PREF_PB_FIELD_HIDING= + // JavaCore.COMPILER_PB_FIELD_HIDING; + // private static final String PREF_PB_SPECIAL_PARAMETER_HIDING_FIELD= + // JavaCore.COMPILER_PB_SPECIAL_PARAMETER_HIDING_FIELD; + // private static final String PREF_PB_INDIRECT_STATIC_ACCESS= + // JavaCore.COMPILER_PB_INDIRECT_STATIC_ACCESS; + // private static final String PREF_PB_SUPERFLUOUS_SEMICOLON= + // JavaCore.COMPILER_PB_SUPERFLUOUS_SEMICOLON; + // private static final String PREF_PB_UNNECESSARY_TYPE_CHECK= + // JavaCore.COMPILER_PB_UNNECESSARY_TYPE_CHECK; + + // private static final String PREF_PB_INVALID_JAVADOC= + // JavaCore.COMPILER_PB_INVALID_JAVADOC; + // private static final String PREF_PB_INVALID_JAVADOC_TAGS= + // JavaCore.COMPILER_PB_INVALID_JAVADOC_TAGS; + // private static final String PREF_PB_INVALID_JAVADOC_TAGS_VISIBILITY= + // JavaCore.COMPILER_PB_INVALID_JAVADOC_TAGS_VISIBILITY; + // + // private static final String PREF_PB_MISSING_JAVADOC_TAGS= + // JavaCore.COMPILER_PB_MISSING_JAVADOC_TAGS; + // private static final String PREF_PB_MISSING_JAVADOC_TAGS_VISIBILITY= + // JavaCore.COMPILER_PB_MISSING_JAVADOC_TAGS_VISIBILITY; + // private static final String PREF_PB_MISSING_JAVADOC_TAGS_OVERRIDING= + // JavaCore.COMPILER_PB_MISSING_JAVADOC_TAGS_OVERRIDING; + // + // private static final String PREF_PB_MISSING_JAVADOC_COMMENTS= + // JavaCore.COMPILER_PB_MISSING_JAVADOC_COMMENTS; + // private static final String PREF_PB_MISSING_JAVADOC_COMMENTS_VISIBILITY= + // JavaCore.COMPILER_PB_MISSING_JAVADOC_COMMENTS_VISIBILITY; + // private static final String PREF_PB_MISSING_JAVADOC_COMMENTS_OVERRIDING= + // JavaCore.COMPILER_PB_MISSING_JAVADOC_COMMENTS_OVERRIDING; + // + // private static final String PREF_SOURCE_COMPATIBILITY= + // JavaCore.COMPILER_SOURCE; + // private static final String PREF_COMPLIANCE= + // JavaCore.COMPILER_COMPLIANCE; + // + // private static final String PREF_RESOURCE_FILTER= + // JavaCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER; + // private static final String PREF_BUILD_INVALID_CLASSPATH= + // JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH; + // private static final String PREF_BUILD_CLEAN_OUTPUT_FOLDER= + // JavaCore.CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER; + // private static final String PREF_ENABLE_EXCLUSION_PATTERNS= + // JavaCore.CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS; + // private static final String PREF_ENABLE_MULTIPLE_OUTPUT_LOCATIONS= + // JavaCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS; + // + // private static final String PREF_PB_INCOMPLETE_BUILDPATH= + // JavaCore.CORE_INCOMPLETE_CLASSPATH; + // private static final String PREF_PB_CIRCULAR_BUILDPATH= + // JavaCore.CORE_CIRCULAR_CLASSPATH; + // // private static final String PREF_PB_INCOMPATIBLE_JDK_LEVEL= + // JavaCore.CORE_INCOMPATIBLE_JDK_LEVEL; + // private static final String PREF_PB_DEPRECATION_IN_DEPRECATED_CODE= + // JavaCore.COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE; + // private static final String PREF_PB_DUPLICATE_RESOURCE= + // JavaCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE; + // private static final String PREF_PB_INCOMPATIBLE_INTERFACE_METHOD= + // JavaCore.COMPILER_PB_INCOMPATIBLE_NON_INHERITED_INTERFACE_METHOD; + + // private static final String PREF_PB_UNDOCUMENTED_EMPTY_BLOCK= + // JavaCore.COMPILER_PB_UNDOCUMENTED_EMPTY_BLOCK; + // private static final String PREF_PB_FINALLY_BLOCK_NOT_COMPLETING= + // JavaCore.COMPILER_PB_FINALLY_BLOCK_NOT_COMPLETING; + // private static final String PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION= + // JavaCore.COMPILER_PB_UNUSED_DECLARED_THROWN_EXCEPTION; + // private static final String + // PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION_WHEN_OVERRIDING= + // JavaCore.COMPILER_PB_UNUSED_DECLARED_THROWN_EXCEPTION_WHEN_OVERRIDING; + // private static final String PREF_PB_UNQUALIFIED_FIELD_ACCESS= + // JavaCore.COMPILER_PB_UNQUALIFIED_FIELD_ACCESS; + + // private static final String INTR_DEFAULT_COMPLIANCE= + // "internal.default.compliance"; //$NON-NLS-1$ // values - private static final String GENERATE= JavaCore.GENERATE; - private static final String DO_NOT_GENERATE= JavaCore.DO_NOT_GENERATE; - - private static final String PRESERVE= JavaCore.PRESERVE; - private static final String OPTIMIZE_OUT= JavaCore.OPTIMIZE_OUT; - - private static final String VERSION_1_1= JavaCore.VERSION_1_1; - private static final String VERSION_1_2= JavaCore.VERSION_1_2; - private static final String VERSION_1_3= JavaCore.VERSION_1_3; - private static final String VERSION_1_4= JavaCore.VERSION_1_4; - - private static final String ERROR= JavaCore.ERROR; - private static final String WARNING= JavaCore.WARNING; - private static final String IGNORE= JavaCore.IGNORE; - private static final String ABORT= JavaCore.ABORT; - - private static final String CLEAN= JavaCore.CLEAN; - - private static final String ENABLED= JavaCore.ENABLED; - private static final String DISABLED= JavaCore.DISABLED; - -// private static final String PUBLIC= JavaCore.PUBLIC; -// private static final String PROTECTED= JavaCore.PROTECTED; -// private static final String DEFAULT= JavaCore.DEFAULT; -// private static final String PRIVATE= JavaCore.PRIVATE; - - private static final String DEFAULT_CONF= "default"; //$NON-NLS-1$ - private static final String USER_CONF= "user"; //$NON-NLS-1$ + private static final String GENERATE = JavaCore.GENERATE; + + private static final String DO_NOT_GENERATE = JavaCore.DO_NOT_GENERATE; + + private static final String PRESERVE = JavaCore.PRESERVE; + + private static final String OPTIMIZE_OUT = JavaCore.OPTIMIZE_OUT; + + private static final String VERSION_1_1 = JavaCore.VERSION_1_1; + + private static final String VERSION_1_2 = JavaCore.VERSION_1_2; + + private static final String VERSION_1_3 = JavaCore.VERSION_1_3; + + private static final String VERSION_1_4 = JavaCore.VERSION_1_4; + + private static final String ERROR = JavaCore.ERROR; + + private static final String WARNING = JavaCore.WARNING; + + private static final String IGNORE = JavaCore.IGNORE; + + private static final String ABORT = JavaCore.ABORT; + + private static final String CLEAN = JavaCore.CLEAN; + + private static final String ENABLED = JavaCore.ENABLED; + + private static final String DISABLED = JavaCore.DISABLED; + + // private static final String PUBLIC= JavaCore.PUBLIC; + // private static final String PROTECTED= JavaCore.PROTECTED; + // private static final String DEFAULT= JavaCore.DEFAULT; + // private static final String PRIVATE= JavaCore.PRIVATE; + + private static final String DEFAULT_CONF = "default"; //$NON-NLS-1$ + + private static final String USER_CONF = "user"; //$NON-NLS-1$ private ArrayList fComplianceControls; + private PixelConverter fPixelConverter; private IStatus fMaxNumberProblemsStatus; -// private IStatus fComplianceStatus, fMaxNumberProblemsStatus, fResourceFilterStatus; - public CompilerConfigurationBlock(IStatusChangeListener context, IJavaProject project) { + // private IStatus fComplianceStatus, fMaxNumberProblemsStatus, + // fResourceFilterStatus; + + public CompilerConfigurationBlock(IStatusChangeListener context, + IJavaProject project) { super(context, project, getKeys()); - - fComplianceControls= new ArrayList(); - -// fComplianceStatus= new StatusInfo(); - fMaxNumberProblemsStatus= new StatusInfo(); -// fResourceFilterStatus= new StatusInfo(); - - // compatibilty code for the merge of the two option PB_SIGNAL_PARAMETER: -// if (ENABLED.equals(fWorkingValues.get(PREF_PB_SIGNAL_PARAMETER_IN_ABSTRACT))) { -// fWorkingValues.put(PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING, ENABLED); -// } - + + fComplianceControls = new ArrayList(); + + // fComplianceStatus= new StatusInfo(); + fMaxNumberProblemsStatus = new StatusInfo(); + // fResourceFilterStatus= new StatusInfo(); + + // compatibilty code for the merge of the two option + // PB_SIGNAL_PARAMETER: + // if + // (ENABLED.equals(fWorkingValues.get(PREF_PB_SIGNAL_PARAMETER_IN_ABSTRACT))) + // { + // fWorkingValues.put(PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING, ENABLED); + // } + } - - private final static String[] KEYS= new String[] { - PREF_PB_PHP_FILE_NOT_EXIST, - PREF_PB_PHP_VAR_DEPRECATED, - PREF_PB_PHP_KEYWORD, - PREF_PB_PHP_UPPERCASE_IDENTIFIER, - PREF_PB_UNREACHABLE_CODE, - PREF_PB_UNINITIALIZED_LOCAL_VARIABLE, -// PREF_LOCAL_VARIABLE_ATTR, -// PREF_LINE_NUMBER_ATTR, PREF_SOURCE_FILE_ATTR, PREF_CODEGEN_UNUSED_LOCAL, -// PREF_CODEGEN_TARGET_PLATFORM, -// PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD, -// PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME, -// PREF_PB_DEPRECATION, -// PREF_PB_HIDDEN_CATCH_BLOCK, PREF_PB_UNUSED_LOCAL, -// PREF_PB_UNUSED_PARAMETER, -// PREF_PB_SYNTHETIC_ACCESS_EMULATION, PREF_PB_NON_EXTERNALIZED_STRINGS, -// PREF_PB_ASSERT_AS_IDENTIFIER, -// PREF_PB_UNUSED_IMPORT, - PREF_PB_MAX_PER_UNIT, -// PREF_SOURCE_COMPATIBILITY, -// PREF_COMPLIANCE, -// PREF_RESOURCE_FILTER, PREF_BUILD_INVALID_CLASSPATH, PREF_PB_STATIC_ACCESS_RECEIVER, PREF_PB_INCOMPLETE_BUILDPATH, -// PREF_PB_CIRCULAR_BUILDPATH, PREF_PB_DEPRECATION_IN_DEPRECATED_CODE, PREF_BUILD_CLEAN_OUTPUT_FOLDER, -// PREF_PB_DUPLICATE_RESOURCE, PREF_PB_NO_EFFECT_ASSIGNMENT, PREF_PB_INCOMPATIBLE_INTERFACE_METHOD, -// PREF_PB_UNUSED_PRIVATE, PREF_PB_CHAR_ARRAY_IN_CONCAT, PREF_ENABLE_EXCLUSION_PATTERNS, PREF_ENABLE_MULTIPLE_OUTPUT_LOCATIONS, -// PREF_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT, -// PREF_PB_LOCAL_VARIABLE_HIDING, -// PREF_PB_FIELD_HIDING, -// PREF_PB_SPECIAL_PARAMETER_HIDING_FIELD, -// PREF_PB_INCOMPATIBLE_JDK_LEVEL, -// PREF_PB_INDIRECT_STATIC_ACCESS, -// PREF_PB_SUPERFLUOUS_SEMICOLON, -// PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING, -// PREF_PB_SIGNAL_PARAMETER_IN_ABSTRACT, -// PREF_PB_UNNECESSARY_TYPE_CHECK, -// PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION, -// PREF_PB_UNQUALIFIED_FIELD_ACCESS, -// PREF_PB_UNDOCUMENTED_EMPTY_BLOCK, -// PREF_PB_FINALLY_BLOCK_NOT_COMPLETING, -// PREF_PB_DEPRECATION_WHEN_OVERRIDING, -// PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION_WHEN_OVERRIDING, - -// PREF_PB_INVALID_JAVADOC, -// PREF_PB_INVALID_JAVADOC_TAGS_VISIBILITY, -// PREF_PB_INVALID_JAVADOC_TAGS_VISIBILITY, -// PREF_PB_MISSING_JAVADOC_TAGS, -// PREF_PB_MISSING_JAVADOC_TAGS_VISIBILITY, -// PREF_PB_MISSING_JAVADOC_TAGS_OVERRIDING, -// PREF_PB_MISSING_JAVADOC_COMMENTS, -// PREF_PB_MISSING_JAVADOC_COMMENTS_VISIBILITY, -// PREF_PB_MISSING_JAVADOC_COMMENTS_OVERRIDING - }; - - private static String[] getKeys() { - return KEYS; + + private final static String[] KEYS = new String[] { + PREF_PB_PHP_FILE_NOT_EXIST, PREF_PB_PHP_VAR_DEPRECATED, + PREF_PB_PHP_KEYWORD, PREF_PB_PHP_UPPERCASE_IDENTIFIER, + PREF_PB_UNREACHABLE_CODE, PREF_PB_UNINITIALIZED_LOCAL_VARIABLE, + // PREF_LOCAL_VARIABLE_ATTR, + // PREF_LINE_NUMBER_ATTR, PREF_SOURCE_FILE_ATTR, + // PREF_CODEGEN_UNUSED_LOCAL, + // PREF_CODEGEN_TARGET_PLATFORM, + // PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD, + // PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME, + // PREF_PB_DEPRECATION, + // PREF_PB_HIDDEN_CATCH_BLOCK, PREF_PB_UNUSED_LOCAL, + // PREF_PB_UNUSED_PARAMETER, + // PREF_PB_SYNTHETIC_ACCESS_EMULATION, + // PREF_PB_NON_EXTERNALIZED_STRINGS, + // PREF_PB_ASSERT_AS_IDENTIFIER, + // PREF_PB_UNUSED_IMPORT, + PREF_PB_MAX_PER_UNIT, + // PREF_SOURCE_COMPATIBILITY, + // PREF_COMPLIANCE, + // PREF_RESOURCE_FILTER, PREF_BUILD_INVALID_CLASSPATH, + // PREF_PB_STATIC_ACCESS_RECEIVER, PREF_PB_INCOMPLETE_BUILDPATH, + // PREF_PB_CIRCULAR_BUILDPATH, PREF_PB_DEPRECATION_IN_DEPRECATED_CODE, + // PREF_BUILD_CLEAN_OUTPUT_FOLDER, + // PREF_PB_DUPLICATE_RESOURCE, PREF_PB_NO_EFFECT_ASSIGNMENT, + // PREF_PB_INCOMPATIBLE_INTERFACE_METHOD, + // PREF_PB_UNUSED_PRIVATE, PREF_PB_CHAR_ARRAY_IN_CONCAT, + // PREF_ENABLE_EXCLUSION_PATTERNS, PREF_ENABLE_MULTIPLE_OUTPUT_LOCATIONS, + // PREF_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT, + // PREF_PB_LOCAL_VARIABLE_HIDING, + // PREF_PB_FIELD_HIDING, + // PREF_PB_SPECIAL_PARAMETER_HIDING_FIELD, + // PREF_PB_INCOMPATIBLE_JDK_LEVEL, + // PREF_PB_INDIRECT_STATIC_ACCESS, + // PREF_PB_SUPERFLUOUS_SEMICOLON, + // PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING, + // PREF_PB_SIGNAL_PARAMETER_IN_ABSTRACT, + // PREF_PB_UNNECESSARY_TYPE_CHECK, + // PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION, + // PREF_PB_UNQUALIFIED_FIELD_ACCESS, + // PREF_PB_UNDOCUMENTED_EMPTY_BLOCK, + // PREF_PB_FINALLY_BLOCK_NOT_COMPLETING, + // PREF_PB_DEPRECATION_WHEN_OVERRIDING, + // PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION_WHEN_OVERRIDING, + + // PREF_PB_INVALID_JAVADOC, + // PREF_PB_INVALID_JAVADOC_TAGS_VISIBILITY, + // PREF_PB_INVALID_JAVADOC_TAGS_VISIBILITY, + // PREF_PB_MISSING_JAVADOC_TAGS, + // PREF_PB_MISSING_JAVADOC_TAGS_VISIBILITY, + // PREF_PB_MISSING_JAVADOC_TAGS_OVERRIDING, + // PREF_PB_MISSING_JAVADOC_COMMENTS, + // PREF_PB_MISSING_JAVADOC_COMMENTS_VISIBILITY, + // PREF_PB_MISSING_JAVADOC_COMMENTS_OVERRIDING + }; + + private static String[] getKeys() { + return KEYS; } - + protected final Map getOptions(boolean inheritJavaCoreOptions) { - Map map= super.getOptions(inheritJavaCoreOptions); - // map.put(INTR_DEFAULT_COMPLIANCE, getCurrentCompliance(map)); + Map map = super.getOptions(inheritJavaCoreOptions); + // map.put(INTR_DEFAULT_COMPLIANCE, getCurrentCompliance(map)); return map; } - + protected final Map getDefaultOptions() { - Map map= super.getDefaultOptions(); - // map.put(INTR_DEFAULT_COMPLIANCE, getCurrentCompliance(map)); + Map map = super.getDefaultOptions(); + // map.put(INTR_DEFAULT_COMPLIANCE, getCurrentCompliance(map)); return map; - } - - + } + /* * @see org.eclipse.jface.preference.PreferencePage#createContents(Composite) */ protected Control createContents(Composite parent) { - fPixelConverter= new PixelConverter(parent); + fPixelConverter = new PixelConverter(parent); setShell(parent.getShell()); - - TabFolder folder= new TabFolder(parent, SWT.NONE); - folder.setLayout(new TabFolderLayout()); + + TabFolder folder = new TabFolder(parent, SWT.NONE); + folder.setLayout(new TabFolderLayout()); folder.setLayoutData(new GridData(GridData.FILL_BOTH)); - - Composite commonComposite= createStyleTabContent(folder); -// Composite unusedComposite= createUnusedCodeTabContent(folder); - Composite advancedComposite= createAdvancedTabContent(folder); -// Composite javadocComposite= createJavadocTabContent(folder); -// Composite complianceComposite= createComplianceTabContent(folder); -// Composite othersComposite= createBuildPathTabContent(folder); - - TabItem item= new TabItem(folder, SWT.NONE); - item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.common.tabtitle")); //$NON-NLS-1$ + + Composite commonComposite = createStyleTabContent(folder); + // Composite unusedComposite= createUnusedCodeTabContent(folder); + Composite advancedComposite = createAdvancedTabContent(folder); + // Composite javadocComposite= createJavadocTabContent(folder); + // Composite complianceComposite= createComplianceTabContent(folder); + // Composite othersComposite= createBuildPathTabContent(folder); + + TabItem item = new TabItem(folder, SWT.NONE); + item.setText(PreferencesMessages + .getString("CompilerConfigurationBlock.common.tabtitle")); //$NON-NLS-1$ item.setControl(commonComposite); - item= new TabItem(folder, SWT.NONE); - item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.advanced.tabtitle")); //$NON-NLS-1$ + item = new TabItem(folder, SWT.NONE); + item.setText(PreferencesMessages + .getString("CompilerConfigurationBlock.advanced.tabtitle")); //$NON-NLS-1$ item.setControl(advancedComposite); -// item= new TabItem(folder, SWT.NONE); -// item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.unused.tabtitle")); //$NON-NLS-1$ -// item.setControl(unusedComposite); - -// item= new TabItem(folder, SWT.NONE); -// item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.javadoc.tabtitle")); //$NON-NLS-1$ -// item.setControl(javadocComposite); - -// item= new TabItem(folder, SWT.NONE); -// item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.compliance.tabtitle")); //$NON-NLS-1$ -// item.setControl(complianceComposite); - -// item= new TabItem(folder, SWT.NONE); -// item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.others.tabtitle")); //$NON-NLS-1$ -// item.setControl(othersComposite); - + // item= new TabItem(folder, SWT.NONE); + // item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.unused.tabtitle")); + // //$NON-NLS-1$ + // item.setControl(unusedComposite); + + // item= new TabItem(folder, SWT.NONE); + // item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.javadoc.tabtitle")); + // //$NON-NLS-1$ + // item.setControl(javadocComposite); + + // item= new TabItem(folder, SWT.NONE); + // item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.compliance.tabtitle")); + // //$NON-NLS-1$ + // item.setControl(complianceComposite); + + // item= new TabItem(folder, SWT.NONE); + // item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.others.tabtitle")); + // //$NON-NLS-1$ + // item.setControl(othersComposite); + validateSettings(null, null); - + return folder; } private Composite createStyleTabContent(Composite folder) { - String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE }; - - String[] errorWarningIgnoreLabels= new String[] { - PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$ - PreferencesMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$ - PreferencesMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$ + String[] errorWarningIgnore = new String[] { ERROR, WARNING, IGNORE }; + + String[] errorWarningIgnoreLabels = new String[] { + PreferencesMessages + .getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$ + PreferencesMessages + .getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$ + PreferencesMessages + .getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$ }; - - int nColumns= 3; - - GridLayout layout= new GridLayout(); - layout.numColumns= nColumns; - Composite composite= new Composite(folder, SWT.NULL); + int nColumns = 3; + + GridLayout layout = new GridLayout(); + layout.numColumns = nColumns; + + Composite composite = new Composite(folder, SWT.NULL); composite.setLayout(layout); - - Label description= new Label(composite, SWT.WRAP); - description.setText(PreferencesMessages.getString("CompilerConfigurationBlock.common.description")); //$NON-NLS-1$ - GridData gd= new GridData(); - gd.horizontalSpan= nColumns; - gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(50); - description.setLayoutData(gd); - - String label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_file_not_exist.label"); //$NON-NLS-1$ - addComboBox(composite, label, PREF_PB_PHP_FILE_NOT_EXIST, errorWarningIgnore, errorWarningIgnoreLabels, 0); - - label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_var_deprecated.label"); //$NON-NLS-1$ - addComboBox(composite, label, PREF_PB_PHP_VAR_DEPRECATED, errorWarningIgnore, errorWarningIgnoreLabels, 0); - - label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_keyword.label"); //$NON-NLS-1$ - addComboBox(composite, label, PREF_PB_PHP_KEYWORD, errorWarningIgnore, errorWarningIgnoreLabels, 0); - - label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_uppercase_identifier.label"); //$NON-NLS-1$ - addComboBox(composite, label, PREF_PB_PHP_UPPERCASE_IDENTIFIER, errorWarningIgnore, errorWarningIgnoreLabels, 0); - - label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unreachable_code.label"); //$NON-NLS-1$ - addComboBox(composite, label, PREF_PB_UNREACHABLE_CODE, errorWarningIgnore, errorWarningIgnoreLabels, 0); - - label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unitialized_local_variable.label"); //$NON-NLS-1$ - addComboBox(composite, label, PREF_PB_UNINITIALIZED_LOCAL_VARIABLE, errorWarningIgnore, errorWarningIgnoreLabels, 0); - - label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_overriding_pkg_dflt.label"); //$NON-NLS-1$ -// addComboBox(composite, label, PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD, errorWarningIgnore, errorWarningIgnoreLabels, 0); - -// label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_method_naming.label"); //$NON-NLS-1$ -// addComboBox(composite, label, PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME, errorWarningIgnore, errorWarningIgnoreLabels, 0); -// -// label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_hidden_catchblock.label"); //$NON-NLS-1$ -// addComboBox(composite, label, PREF_PB_HIDDEN_CATCH_BLOCK, errorWarningIgnore, errorWarningIgnoreLabels, 0); -// -// label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_static_access_receiver.label"); //$NON-NLS-1$ -// addComboBox(composite, label, PREF_PB_STATIC_ACCESS_RECEIVER, errorWarningIgnore, errorWarningIgnoreLabels, 0); -// -// label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_no_effect_assignment.label"); //$NON-NLS-1$ -// addComboBox(composite, label, PREF_PB_NO_EFFECT_ASSIGNMENT, errorWarningIgnore, errorWarningIgnoreLabels, 0); - -// label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_indirect_access_to_static.label"); //$NON-NLS-1$ -// addComboBox(composite, label, PREF_PB_INDIRECT_STATIC_ACCESS, errorWarningIgnore, errorWarningIgnoreLabels, 0); -// -// label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_accidential_assignement.label"); //$NON-NLS-1$ -// addComboBox(composite, label, PREF_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT, errorWarningIgnore, errorWarningIgnoreLabels, 0); -// -// label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_finally_block_not_completing.label"); //$NON-NLS-1$ -// addComboBox(composite, label, PREF_PB_FINALLY_BLOCK_NOT_COMPLETING, errorWarningIgnore, errorWarningIgnoreLabels, 0); -// -// label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_undocumented_empty_block.label"); //$NON-NLS-1$ -// addComboBox(composite, label, PREF_PB_UNDOCUMENTED_EMPTY_BLOCK, errorWarningIgnore, errorWarningIgnoreLabels, 0); - - + + Label description = new Label(composite, SWT.WRAP); + description.setText(PreferencesMessages + .getString("CompilerConfigurationBlock.common.description")); //$NON-NLS-1$ + GridData gd = new GridData(); + gd.horizontalSpan = nColumns; + gd.widthHint = fPixelConverter.convertWidthInCharsToPixels(50); + description.setLayoutData(gd); + + String label = PreferencesMessages + .getString("CompilerConfigurationBlock.pb_file_not_exist.label"); //$NON-NLS-1$ + addComboBox(composite, label, PREF_PB_PHP_FILE_NOT_EXIST, + errorWarningIgnore, errorWarningIgnoreLabels, 0); + + label = PreferencesMessages + .getString("CompilerConfigurationBlock.pb_var_deprecated.label"); //$NON-NLS-1$ + addComboBox(composite, label, PREF_PB_PHP_VAR_DEPRECATED, + errorWarningIgnore, errorWarningIgnoreLabels, 0); + + label = PreferencesMessages + .getString("CompilerConfigurationBlock.pb_keyword.label"); //$NON-NLS-1$ + addComboBox(composite, label, PREF_PB_PHP_KEYWORD, errorWarningIgnore, + errorWarningIgnoreLabels, 0); + + label = PreferencesMessages + .getString("CompilerConfigurationBlock.pb_uppercase_identifier.label"); //$NON-NLS-1$ + addComboBox(composite, label, PREF_PB_PHP_UPPERCASE_IDENTIFIER, + errorWarningIgnore, errorWarningIgnoreLabels, 0); + + label = PreferencesMessages + .getString("CompilerConfigurationBlock.pb_unreachable_code.label"); //$NON-NLS-1$ + addComboBox(composite, label, PREF_PB_UNREACHABLE_CODE, + errorWarningIgnore, errorWarningIgnoreLabels, 0); + + label = PreferencesMessages + .getString("CompilerConfigurationBlock.pb_unitialized_local_variable.label"); //$NON-NLS-1$ + addComboBox(composite, label, PREF_PB_UNINITIALIZED_LOCAL_VARIABLE, + errorWarningIgnore, errorWarningIgnoreLabels, 0); + + label = PreferencesMessages + .getString("CompilerConfigurationBlock.pb_overriding_pkg_dflt.label"); //$NON-NLS-1$ + // addComboBox(composite, label, + // PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD, errorWarningIgnore, + // errorWarningIgnoreLabels, 0); + + // label= + // PreferencesMessages.getString("CompilerConfigurationBlock.pb_method_naming.label"); + // //$NON-NLS-1$ + // addComboBox(composite, label, PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME, + // errorWarningIgnore, errorWarningIgnoreLabels, 0); + // + // label= + // PreferencesMessages.getString("CompilerConfigurationBlock.pb_hidden_catchblock.label"); + // //$NON-NLS-1$ + // addComboBox(composite, label, PREF_PB_HIDDEN_CATCH_BLOCK, + // errorWarningIgnore, errorWarningIgnoreLabels, 0); + // + // label= + // PreferencesMessages.getString("CompilerConfigurationBlock.pb_static_access_receiver.label"); + // //$NON-NLS-1$ + // addComboBox(composite, label, PREF_PB_STATIC_ACCESS_RECEIVER, + // errorWarningIgnore, errorWarningIgnoreLabels, 0); + // + // label= + // PreferencesMessages.getString("CompilerConfigurationBlock.pb_no_effect_assignment.label"); + // //$NON-NLS-1$ + // addComboBox(composite, label, PREF_PB_NO_EFFECT_ASSIGNMENT, + // errorWarningIgnore, errorWarningIgnoreLabels, 0); + + // label= + // PreferencesMessages.getString("CompilerConfigurationBlock.pb_indirect_access_to_static.label"); + // //$NON-NLS-1$ + // addComboBox(composite, label, PREF_PB_INDIRECT_STATIC_ACCESS, + // errorWarningIgnore, errorWarningIgnoreLabels, 0); + // + // label= + // PreferencesMessages.getString("CompilerConfigurationBlock.pb_accidential_assignement.label"); + // //$NON-NLS-1$ + // addComboBox(composite, label, + // PREF_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT, errorWarningIgnore, + // errorWarningIgnoreLabels, 0); + // + // label= + // PreferencesMessages.getString("CompilerConfigurationBlock.pb_finally_block_not_completing.label"); + // //$NON-NLS-1$ + // addComboBox(composite, label, PREF_PB_FINALLY_BLOCK_NOT_COMPLETING, + // errorWarningIgnore, errorWarningIgnoreLabels, 0); + // + // label= + // PreferencesMessages.getString("CompilerConfigurationBlock.pb_undocumented_empty_block.label"); + // //$NON-NLS-1$ + // addComboBox(composite, label, PREF_PB_UNDOCUMENTED_EMPTY_BLOCK, + // errorWarningIgnore, errorWarningIgnoreLabels, 0); + return composite; } private Composite createAdvancedTabContent(TabFolder folder) { - String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE }; - - String[] errorWarningIgnoreLabels= new String[] { - PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$ - PreferencesMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$ - PreferencesMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$ + String[] errorWarningIgnore = new String[] { ERROR, WARNING, IGNORE }; + + String[] errorWarningIgnoreLabels = new String[] { + PreferencesMessages + .getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$ + PreferencesMessages + .getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$ + PreferencesMessages + .getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$ }; - - String[] enabledDisabled= new String[] { ENABLED, DISABLED }; - - int nColumns= 3; - - GridLayout layout= new GridLayout(); - layout.numColumns= nColumns; - - Composite composite= new Composite(folder, SWT.NULL); + + String[] enabledDisabled = new String[] { ENABLED, DISABLED }; + + int nColumns = 3; + + GridLayout layout = new GridLayout(); + layout.numColumns = nColumns; + + Composite composite = new Composite(folder, SWT.NULL); composite.setLayout(layout); - Label description= new Label(composite, SWT.WRAP); - description.setText(PreferencesMessages.getString("CompilerConfigurationBlock.advanced.description")); //$NON-NLS-1$ - GridData gd= new GridData(); - gd.horizontalSpan= nColumns; - gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(50); + Label description = new Label(composite, SWT.WRAP); + description.setText(PreferencesMessages + .getString("CompilerConfigurationBlock.advanced.description")); //$NON-NLS-1$ + GridData gd = new GridData(); + gd.horizontalSpan = nColumns; + gd.widthHint = fPixelConverter.convertWidthInCharsToPixels(50); description.setLayoutData(gd); - -// String label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_synth_access_emul.label"); //$NON-NLS-1$ -// addComboBox(composite, label, PREF_PB_SYNTHETIC_ACCESS_EMULATION, errorWarningIgnore, errorWarningIgnoreLabels, 0); - -// label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_local_variable_hiding.label"); //$NON-NLS-1$ -// addComboBox(composite, label, PREF_PB_LOCAL_VARIABLE_HIDING, errorWarningIgnore, errorWarningIgnoreLabels, 0); - -// int indent= fPixelConverter.convertWidthInCharsToPixels(2); -// label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_special_param_hiding.label"); //$NON-NLS-1$ -// addCheckBox(composite, label, PREF_PB_SPECIAL_PARAMETER_HIDING_FIELD, enabledDisabled, indent); - -// label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_field_hiding.label"); //$NON-NLS-1$ -// addComboBox(composite, label, PREF_PB_FIELD_HIDING, errorWarningIgnore, errorWarningIgnoreLabels, 0); - -// label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_non_externalized_strings.label"); //$NON-NLS-1$ -// addComboBox(composite, label, PREF_PB_NON_EXTERNALIZED_STRINGS, errorWarningIgnore, errorWarningIgnoreLabels, 0); -// -// label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_incompatible_interface_method.label"); //$NON-NLS-1$ -// addComboBox(composite, label, PREF_PB_INCOMPATIBLE_INTERFACE_METHOD, errorWarningIgnore, errorWarningIgnoreLabels, 0); -// -// label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_char_array_in_concat.label"); //$NON-NLS-1$ -// addComboBox(composite, label, PREF_PB_CHAR_ARRAY_IN_CONCAT, errorWarningIgnore, errorWarningIgnoreLabels, 0); - -// label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unqualified_field_access.label"); //$NON-NLS-1$ -// addComboBox(composite, label, PREF_PB_UNQUALIFIED_FIELD_ACCESS, errorWarningIgnore, errorWarningIgnoreLabels, 0); - - gd= new GridData(); - gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(6); - - String label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_max_per_unit.label"); //$NON-NLS-1$ - Text text= addTextField(composite, label, PREF_PB_MAX_PER_UNIT, 0, 0); + + // String label= + // PreferencesMessages.getString("CompilerConfigurationBlock.pb_synth_access_emul.label"); + // //$NON-NLS-1$ + // addComboBox(composite, label, PREF_PB_SYNTHETIC_ACCESS_EMULATION, + // errorWarningIgnore, errorWarningIgnoreLabels, 0); + + // label= + // PreferencesMessages.getString("CompilerConfigurationBlock.pb_local_variable_hiding.label"); + // //$NON-NLS-1$ + // addComboBox(composite, label, PREF_PB_LOCAL_VARIABLE_HIDING, + // errorWarningIgnore, errorWarningIgnoreLabels, 0); + + // int indent= fPixelConverter.convertWidthInCharsToPixels(2); + // label= + // PreferencesMessages.getString("CompilerConfigurationBlock.pb_special_param_hiding.label"); + // //$NON-NLS-1$ + // addCheckBox(composite, label, PREF_PB_SPECIAL_PARAMETER_HIDING_FIELD, + // enabledDisabled, indent); + + // label= + // PreferencesMessages.getString("CompilerConfigurationBlock.pb_field_hiding.label"); + // //$NON-NLS-1$ + // addComboBox(composite, label, PREF_PB_FIELD_HIDING, + // errorWarningIgnore, errorWarningIgnoreLabels, 0); + + // label= + // PreferencesMessages.getString("CompilerConfigurationBlock.pb_non_externalized_strings.label"); + // //$NON-NLS-1$ + // addComboBox(composite, label, PREF_PB_NON_EXTERNALIZED_STRINGS, + // errorWarningIgnore, errorWarningIgnoreLabels, 0); + // + // label= + // PreferencesMessages.getString("CompilerConfigurationBlock.pb_incompatible_interface_method.label"); + // //$NON-NLS-1$ + // addComboBox(composite, label, PREF_PB_INCOMPATIBLE_INTERFACE_METHOD, + // errorWarningIgnore, errorWarningIgnoreLabels, 0); + // + // label= + // PreferencesMessages.getString("CompilerConfigurationBlock.pb_char_array_in_concat.label"); + // //$NON-NLS-1$ + // addComboBox(composite, label, PREF_PB_CHAR_ARRAY_IN_CONCAT, + // errorWarningIgnore, errorWarningIgnoreLabels, 0); + + // label= + // PreferencesMessages.getString("CompilerConfigurationBlock.pb_unqualified_field_access.label"); + // //$NON-NLS-1$ + // addComboBox(composite, label, PREF_PB_UNQUALIFIED_FIELD_ACCESS, + // errorWarningIgnore, errorWarningIgnoreLabels, 0); + + gd = new GridData(); + gd.widthHint = fPixelConverter.convertWidthInCharsToPixels(6); + + String label = PreferencesMessages + .getString("CompilerConfigurationBlock.pb_max_per_unit.label"); //$NON-NLS-1$ + Text text = addTextField(composite, label, PREF_PB_MAX_PER_UNIT, 0, 0); text.setTextLimit(6); text.setLayoutData(gd); return composite; } - - - - - /* (non-javadoc) - * Update fields and validate. - * @param changedKey Key that changed, or null, if all changed. - */ + /* + * (non-javadoc) Update fields and validate. @param changedKey Key that + * changed, or null, if all changed. + */ protected void validateSettings(String changedKey, String newValue) { - + if (changedKey != null) { -// if (INTR_DEFAULT_COMPLIANCE.equals(changedKey)) { -// updateComplianceEnableState(); -// if (DEFAULT_CONF.equals(newValue)) { -// updateComplianceDefaultSettings(); -// } -// fComplianceStatus= validateCompliance(); -// } else if (PREF_COMPLIANCE.equals(changedKey)) { -// if (checkValue(INTR_DEFAULT_COMPLIANCE, DEFAULT_CONF)) { -// updateComplianceDefaultSettings(); -// } -// fComplianceStatus= validateCompliance(); -// } else if (PREF_SOURCE_COMPATIBILITY.equals(changedKey) || -// PREF_CODEGEN_TARGET_PLATFORM.equals(changedKey) || -// PREF_PB_ASSERT_AS_IDENTIFIER.equals(changedKey)) { -// fComplianceStatus= validateCompliance(); -// } else - if (PREF_PB_MAX_PER_UNIT.equals(changedKey)) { - fMaxNumberProblemsStatus= validateMaxNumberProblems(); -// } else if (PREF_RESOURCE_FILTER.equals(changedKey)) { -// fResourceFilterStatus= validateResourceFilters(); -// } else if (S.equals(changedKey) || -// PREF_PB_DEPRECATION.equals(changedKey) ) { // || -//// PREF_PB_INVALID_JAVADOC.equals(changedKey) || -//// PREF_PB_MISSING_JAVADOC_TAGS.equals(changedKey) || -//// PREF_PB_MISSING_JAVADOC_COMMENTS.equals(changedKey) || -//// PREF_PB_MISSING_JAVADOC_COMMENTS.equals(changedKey) || -//// PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION.equals(changedKey)) { -// updateEnableStates(); -// } else if (PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING.equals(changedKey)) { -// // merging the two options -// fWorkingValues.put(PREF_PB_SIGNAL_PARAMETER_IN_ABSTRACT, newValue); + // if (INTR_DEFAULT_COMPLIANCE.equals(changedKey)) { + // updateComplianceEnableState(); + // if (DEFAULT_CONF.equals(newValue)) { + // updateComplianceDefaultSettings(); + // } + // fComplianceStatus= validateCompliance(); + // } else if (PREF_COMPLIANCE.equals(changedKey)) { + // if (checkValue(INTR_DEFAULT_COMPLIANCE, DEFAULT_CONF)) { + // updateComplianceDefaultSettings(); + // } + // fComplianceStatus= validateCompliance(); + // } else if (PREF_SOURCE_COMPATIBILITY.equals(changedKey) || + // PREF_CODEGEN_TARGET_PLATFORM.equals(changedKey) || + // PREF_PB_ASSERT_AS_IDENTIFIER.equals(changedKey)) { + // fComplianceStatus= validateCompliance(); + // } else + if (PREF_PB_MAX_PER_UNIT.equals(changedKey)) { + fMaxNumberProblemsStatus = validateMaxNumberProblems(); + // } else if (PREF_RESOURCE_FILTER.equals(changedKey)) { + // fResourceFilterStatus= validateResourceFilters(); + // } else if (S.equals(changedKey) || + // PREF_PB_DEPRECATION.equals(changedKey) ) { // || + // // PREF_PB_INVALID_JAVADOC.equals(changedKey) || + // // PREF_PB_MISSING_JAVADOC_TAGS.equals(changedKey) || + // // PREF_PB_MISSING_JAVADOC_COMMENTS.equals(changedKey) || + // // PREF_PB_MISSING_JAVADOC_COMMENTS.equals(changedKey) || + // // + // PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION.equals(changedKey)) + // { + // updateEnableStates(); + // } else if + // (PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING.equals(changedKey)) { + // // merging the two options + // fWorkingValues.put(PREF_PB_SIGNAL_PARAMETER_IN_ABSTRACT, + // newValue); } else { return; } } else { -// updateEnableStates(); -// updateComplianceEnableState(); -// fComplianceStatus= validateCompliance(); - fMaxNumberProblemsStatus= validateMaxNumberProblems(); -// fResourceFilterStatus= validateResourceFilters(); - } -// IStatus status= StatusUtil.getMostSevere(new IStatus[] { fComplianceStatus, fMaxNumberProblemsStatus, fResourceFilterStatus }); - IStatus status= StatusUtil.getMostSevere(new IStatus[] { fMaxNumberProblemsStatus }); + // updateEnableStates(); + // updateComplianceEnableState(); + // fComplianceStatus= validateCompliance(); + fMaxNumberProblemsStatus = validateMaxNumberProblems(); + // fResourceFilterStatus= validateResourceFilters(); + } + // IStatus status= StatusUtil.getMostSevere(new IStatus[] { + // fComplianceStatus, fMaxNumberProblemsStatus, fResourceFilterStatus + // }); + IStatus status = StatusUtil + .getMostSevere(new IStatus[] { fMaxNumberProblemsStatus }); fContext.statusChanged(status); } - -// private void updateEnableStates() { -// boolean enableUnusedParams= !checkValue(PREF_PB_UNUSED_PARAMETER, IGNORE); -// getCheckBox(PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING).setEnabled(enableUnusedParams); - -// boolean enableDeprecation= !checkValue(PREF_PB_DEPRECATION, IGNORE); -// getCheckBox(PREF_PB_DEPRECATION_IN_DEPRECATED_CODE).setEnabled(enableDeprecation); -// getCheckBox(PREF_PB_DEPRECATION_WHEN_OVERRIDING).setEnabled(enableDeprecation); -// -// boolean enableThrownExceptions= !checkValue(PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION, IGNORE); -// getCheckBox(PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION_WHEN_OVERRIDING).setEnabled(enableThrownExceptions); -// -// boolean enableHiding= !checkValue(PREF_PB_LOCAL_VARIABLE_HIDING, IGNORE); -// getCheckBox(PREF_PB_SPECIAL_PARAMETER_HIDING_FIELD).setEnabled(enableHiding); -// -// boolean enableInvalidTagsErrors= !checkValue(PREF_PB_INVALID_JAVADOC, IGNORE); -// getCheckBox(PREF_PB_INVALID_JAVADOC_TAGS).setEnabled(enableInvalidTagsErrors); -// setComboEnabled(PREF_PB_INVALID_JAVADOC_TAGS_VISIBILITY, enableInvalidTagsErrors); -// -// boolean enableMissingTagsErrors= !checkValue(PREF_PB_MISSING_JAVADOC_TAGS, IGNORE); -// getCheckBox(PREF_PB_MISSING_JAVADOC_TAGS_OVERRIDING).setEnabled(enableMissingTagsErrors); -// setComboEnabled(PREF_PB_MISSING_JAVADOC_TAGS_VISIBILITY, enableMissingTagsErrors); -// -// boolean enableMissingCommentsErrors= !checkValue(PREF_PB_MISSING_JAVADOC_COMMENTS, IGNORE); -// getCheckBox(PREF_PB_MISSING_JAVADOC_COMMENTS_OVERRIDING).setEnabled(enableMissingCommentsErrors); -// setComboEnabled(PREF_PB_MISSING_JAVADOC_COMMENTS_VISIBILITY, enableMissingCommentsErrors); -// } - -// private IStatus validateCompliance() { -// StatusInfo status= new StatusInfo(); -// if (checkValue(PREF_COMPLIANCE, VERSION_1_3)) { -// if (checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) { -// status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.cpl13src14.error")); //$NON-NLS-1$ -// return status; -// } else if (checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4)) { -// status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.cpl13trg14.error")); //$NON-NLS-1$ -// return status; -// } -// } -// if (checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) { -// if (!checkValue(PREF_PB_ASSERT_AS_IDENTIFIER, ERROR)) { -// status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.src14asrterr.error")); //$NON-NLS-1$ -// return status; -// } -// } -// if (checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) { -// if (!checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4)) { -// status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.src14tgt14.error")); //$NON-NLS-1$ -// return status; -// } -// } -// return status; -// } - + + // private void updateEnableStates() { + // boolean enableUnusedParams= !checkValue(PREF_PB_UNUSED_PARAMETER, + // IGNORE); + // getCheckBox(PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING).setEnabled(enableUnusedParams); + + // boolean enableDeprecation= !checkValue(PREF_PB_DEPRECATION, IGNORE); + // getCheckBox(PREF_PB_DEPRECATION_IN_DEPRECATED_CODE).setEnabled(enableDeprecation); + // getCheckBox(PREF_PB_DEPRECATION_WHEN_OVERRIDING).setEnabled(enableDeprecation); + // + // boolean enableThrownExceptions= + // !checkValue(PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION, IGNORE); + // getCheckBox(PREF_PB_UNUSED_DECLARED_THROWN_EXCEPTION_WHEN_OVERRIDING).setEnabled(enableThrownExceptions); + // + // boolean enableHiding= !checkValue(PREF_PB_LOCAL_VARIABLE_HIDING, IGNORE); + // getCheckBox(PREF_PB_SPECIAL_PARAMETER_HIDING_FIELD).setEnabled(enableHiding); + // + // boolean enableInvalidTagsErrors= !checkValue(PREF_PB_INVALID_JAVADOC, + // IGNORE); + // getCheckBox(PREF_PB_INVALID_JAVADOC_TAGS).setEnabled(enableInvalidTagsErrors); + // setComboEnabled(PREF_PB_INVALID_JAVADOC_TAGS_VISIBILITY, + // enableInvalidTagsErrors); + // + // boolean enableMissingTagsErrors= + // !checkValue(PREF_PB_MISSING_JAVADOC_TAGS, IGNORE); + // getCheckBox(PREF_PB_MISSING_JAVADOC_TAGS_OVERRIDING).setEnabled(enableMissingTagsErrors); + // setComboEnabled(PREF_PB_MISSING_JAVADOC_TAGS_VISIBILITY, + // enableMissingTagsErrors); + // + // boolean enableMissingCommentsErrors= + // !checkValue(PREF_PB_MISSING_JAVADOC_COMMENTS, IGNORE); + // getCheckBox(PREF_PB_MISSING_JAVADOC_COMMENTS_OVERRIDING).setEnabled(enableMissingCommentsErrors); + // setComboEnabled(PREF_PB_MISSING_JAVADOC_COMMENTS_VISIBILITY, + // enableMissingCommentsErrors); + // } + + // private IStatus validateCompliance() { + // StatusInfo status= new StatusInfo(); + // if (checkValue(PREF_COMPLIANCE, VERSION_1_3)) { + // if (checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) { + // status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.cpl13src14.error")); + // //$NON-NLS-1$ + // return status; + // } else if (checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4)) { + // status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.cpl13trg14.error")); + // //$NON-NLS-1$ + // return status; + // } + // } + // if (checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) { + // if (!checkValue(PREF_PB_ASSERT_AS_IDENTIFIER, ERROR)) { + // status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.src14asrterr.error")); + // //$NON-NLS-1$ + // return status; + // } + // } + // if (checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) { + // if (!checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4)) { + // status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.src14tgt14.error")); + // //$NON-NLS-1$ + // return status; + // } + // } + // return status; + // } + private IStatus validateMaxNumberProblems() { - String number= (String) fWorkingValues.get(PREF_PB_MAX_PER_UNIT); - StatusInfo status= new StatusInfo(); + String number = (String) fWorkingValues.get(PREF_PB_MAX_PER_UNIT); + StatusInfo status = new StatusInfo(); if (number.length() == 0) { - status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.empty_input")); //$NON-NLS-1$ + status.setError(PreferencesMessages + .getString("CompilerConfigurationBlock.empty_input")); //$NON-NLS-1$ } else { try { - int value= Integer.parseInt(number); + int value = Integer.parseInt(number); if (value <= 0) { - status.setError(PreferencesMessages.getFormattedString("CompilerConfigurationBlock.invalid_input", number)); //$NON-NLS-1$ + status + .setError(PreferencesMessages + .getFormattedString( + "CompilerConfigurationBlock.invalid_input", number)); //$NON-NLS-1$ } } catch (NumberFormatException e) { - status.setError(PreferencesMessages.getFormattedString("CompilerConfigurationBlock.invalid_input", number)); //$NON-NLS-1$ + status.setError(PreferencesMessages.getFormattedString( + "CompilerConfigurationBlock.invalid_input", number)); //$NON-NLS-1$ } } return status; } - -// private IStatus validateResourceFilters() { -// String text= (String) fWorkingValues.get(PREF_RESOURCE_FILTER); -// -// IWorkspace workspace= ResourcesPlugin.getWorkspace(); -// -// String[] filters= getTokens(text, ","); //$NON-NLS-1$ -// for (int i= 0; i < filters.length; i++) { -// String fileName= filters[i].replace('*', 'x'); -// int resourceType= IResource.FILE; -// int lastCharacter= fileName.length() - 1; -// if (lastCharacter >= 0 && fileName.charAt(lastCharacter) == '/') { -// fileName= fileName.substring(0, lastCharacter); -// resourceType= IResource.FOLDER; -// } -// IStatus status= workspace.validateName(fileName, resourceType); -// if (status.matches(IStatus.ERROR)) { -// String message= PreferencesMessages.getFormattedString("CompilerConfigurationBlock.filter.invalidsegment.error", status.getMessage()); //$NON-NLS-1$ -// return new StatusInfo(IStatus.ERROR, message); -// } -// } -// return new StatusInfo(); -// } - + + // private IStatus validateResourceFilters() { + // String text= (String) fWorkingValues.get(PREF_RESOURCE_FILTER); + // + // IWorkspace workspace= ResourcesPlugin.getWorkspace(); + // + // String[] filters= getTokens(text, ","); //$NON-NLS-1$ + // for (int i= 0; i < filters.length; i++) { + // String fileName= filters[i].replace('*', 'x'); + // int resourceType= IResource.FILE; + // int lastCharacter= fileName.length() - 1; + // if (lastCharacter >= 0 && fileName.charAt(lastCharacter) == '/') { + // fileName= fileName.substring(0, lastCharacter); + // resourceType= IResource.FOLDER; + // } + // IStatus status= workspace.validateName(fileName, resourceType); + // if (status.matches(IStatus.ERROR)) { + // String message= + // PreferencesMessages.getFormattedString("CompilerConfigurationBlock.filter.invalidsegment.error", + // status.getMessage()); //$NON-NLS-1$ + // return new StatusInfo(IStatus.ERROR, message); + // } + // } + // return new StatusInfo(); + // } + protected String[] getFullBuildDialogStrings(boolean workspaceSettings) { - String title= PreferencesMessages.getString("CompilerConfigurationBlock.needsbuild.title"); //$NON-NLS-1$ + String title = PreferencesMessages + .getString("CompilerConfigurationBlock.needsbuild.title"); //$NON-NLS-1$ String message; if (workspaceSettings) { - message= PreferencesMessages.getString("CompilerConfigurationBlock.needsfullbuild.message"); //$NON-NLS-1$ + message = PreferencesMessages + .getString("CompilerConfigurationBlock.needsfullbuild.message"); //$NON-NLS-1$ } else { - message= PreferencesMessages.getString("CompilerConfigurationBlock.needsprojectbuild.message"); //$NON-NLS-1$ + message = PreferencesMessages + .getString("CompilerConfigurationBlock.needsprojectbuild.message"); //$NON-NLS-1$ } return new String[] { title, message }; - } - + } + } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CompilerPreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CompilerPreferencePage.java index 0356e01..bcc2c91 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CompilerPreferencePage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CompilerPreferencePage.java @@ -27,18 +27,20 @@ import org.eclipse.ui.PlatformUI; /* * The page to configure the compiler options. */ -public class CompilerPreferencePage extends PreferencePage implements IWorkbenchPreferencePage, IStatusChangeListener { +public class CompilerPreferencePage extends PreferencePage implements + IWorkbenchPreferencePage, IStatusChangeListener { private CompilerConfigurationBlock fConfigurationBlock; public CompilerPreferencePage() { setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); - setDescription(PreferencesMessages.getString("CompilerPreferencePage.description")); //$NON-NLS-1$ + setDescription(PreferencesMessages + .getString("CompilerPreferencePage.description")); //$NON-NLS-1$ // only used when page is shown programatically - setTitle(PreferencesMessages.getString("CompilerPreferencePage.title")); //$NON-NLS-1$ + setTitle(PreferencesMessages.getString("CompilerPreferencePage.title")); //$NON-NLS-1$ - fConfigurationBlock= new CompilerConfigurationBlock(this, null); + fConfigurationBlock = new CompilerConfigurationBlock(this, null); } /* @@ -52,15 +54,15 @@ public class CompilerPreferencePage extends PreferencePage implements IWorkbench */ public void createControl(Composite parent) { super.createControl(parent); - PlatformUI.getWorkbench().getHelpSystem(). - setHelp(getControl(), IJavaHelpContextIds.COMPILER_PREFERENCE_PAGE); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), + IJavaHelpContextIds.COMPILER_PREFERENCE_PAGE); } /* * @see PreferencePage#createContents(Composite) */ protected Control createContents(Composite parent) { - Control result= fConfigurationBlock.createContents(parent); + Control result = fConfigurationBlock.createContents(parent); Dialog.applyDialogFont(result); return result; } @@ -83,7 +85,9 @@ public class CompilerPreferencePage extends PreferencePage implements IWorkbench super.performDefaults(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener#statusChanged(org.eclipse.core.runtime.IStatus) */ public void statusChanged(IStatus status) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CompilerPropertyPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CompilerPropertyPage.java index c0cb607..377710b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CompilerPropertyPage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CompilerPropertyPage.java @@ -45,37 +45,45 @@ import org.eclipse.ui.dialogs.PropertyPage; public class CompilerPropertyPage extends PropertyPage { private CompilerConfigurationBlock fConfigurationBlock; + private Control fConfigurationBlockControl; + private ControlEnableState fBlockEnableState; + private SelectionButtonDialogField fUseWorkspaceSettings; + private SelectionButtonDialogField fChangeWorkspaceSettings; + private SelectionButtonDialogField fUseProjectSettings; - private IStatus fBlockStatus; + private IStatus fBlockStatus; public CompilerPropertyPage() { - fBlockStatus= new StatusInfo(); - fBlockEnableState= null; + fBlockStatus = new StatusInfo(); + fBlockEnableState = null; - IDialogFieldListener listener= new IDialogFieldListener() { + IDialogFieldListener listener = new IDialogFieldListener() { public void dialogFieldChanged(DialogField field) { doDialogFieldChanged(field); } }; - fUseWorkspaceSettings= new SelectionButtonDialogField(SWT.RADIO); + fUseWorkspaceSettings = new SelectionButtonDialogField(SWT.RADIO); fUseWorkspaceSettings.setDialogFieldListener(listener); - fUseWorkspaceSettings.setLabelText(PreferencesMessages.getString("CompilerPropertyPage.useworkspacesettings.label")); //$NON-NLS-1$ + fUseWorkspaceSettings.setLabelText(PreferencesMessages + .getString("CompilerPropertyPage.useworkspacesettings.label")); //$NON-NLS-1$ - fChangeWorkspaceSettings= new SelectionButtonDialogField(SWT.PUSH); - fChangeWorkspaceSettings.setLabelText(PreferencesMessages.getString("CompilerPropertyPage.useworkspacesettings.change")); //$NON-NLS-1$ + fChangeWorkspaceSettings = new SelectionButtonDialogField(SWT.PUSH); + fChangeWorkspaceSettings.setLabelText(PreferencesMessages + .getString("CompilerPropertyPage.useworkspacesettings.change")); //$NON-NLS-1$ fChangeWorkspaceSettings.setDialogFieldListener(listener); fUseWorkspaceSettings.attachDialogField(fChangeWorkspaceSettings); - fUseProjectSettings= new SelectionButtonDialogField(SWT.RADIO); + fUseProjectSettings = new SelectionButtonDialogField(SWT.RADIO); fUseProjectSettings.setDialogFieldListener(listener); - fUseProjectSettings.setLabelText(PreferencesMessages.getString("CompilerPropertyPage.useprojectsettings.label")); //$NON-NLS-1$ + fUseProjectSettings.setLabelText(PreferencesMessages + .getString("CompilerPropertyPage.useprojectsettings.label")); //$NON-NLS-1$ } /* @@ -83,42 +91,48 @@ public class CompilerPropertyPage extends PropertyPage { */ public void createControl(Composite parent) { super.createControl(parent); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.COMPILER_PROPERTY_PAGE); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), + IJavaHelpContextIds.COMPILER_PROPERTY_PAGE); } /* * @see org.eclipse.jface.preference.IPreferencePage#createContents(Composite) */ protected Control createContents(Composite parent) { - IStatusChangeListener listener= new IStatusChangeListener() { + IStatusChangeListener listener = new IStatusChangeListener() { public void statusChanged(IStatus status) { - fBlockStatus= status; + fBlockStatus = status; doStatusChanged(); } }; - fConfigurationBlock= new CompilerConfigurationBlock(listener, getProject()); - - Composite composite= new Composite(parent, SWT.NONE); - GridLayout layout= new GridLayout(); - layout.marginHeight= 0; - layout.marginWidth= 0; - layout.numColumns= 2; + fConfigurationBlock = new CompilerConfigurationBlock(listener, + getProject()); + + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginHeight = 0; + layout.marginWidth = 0; + layout.numColumns = 2; composite.setLayout(layout); fUseWorkspaceSettings.doFillIntoGrid(composite, 1); - LayoutUtil.setHorizontalGrabbing(fUseWorkspaceSettings.getSelectionButton(null)); + LayoutUtil.setHorizontalGrabbing(fUseWorkspaceSettings + .getSelectionButton(null)); fChangeWorkspaceSettings.doFillIntoGrid(composite, 1); fUseProjectSettings.doFillIntoGrid(composite, 2); - GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL ); - data.horizontalSpan= 2; + GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL + | GridData.VERTICAL_ALIGN_FILL); + data.horizontalSpan = 2; - fConfigurationBlockControl= fConfigurationBlock.createContents(composite); + fConfigurationBlockControl = fConfigurationBlock + .createContents(composite); fConfigurationBlockControl.setLayoutData(data); - boolean useProjectSettings= fConfigurationBlock.hasProjectSpecificOptions(); + boolean useProjectSettings = fConfigurationBlock + .hasProjectSpecificOptions(); fUseProjectSettings.setSelection(useProjectSettings); fUseWorkspaceSettings.setSelection(!useProjectSettings); @@ -134,14 +148,15 @@ public class CompilerPropertyPage extends PropertyPage { private void doDialogFieldChanged(DialogField field) { if (field == fChangeWorkspaceSettings) { - String id= "net.sourceforge.phpdt.ui.preferences.CompilerPreferencePage"; //$NON-NLS-1$ - CompilerPreferencePage page= new CompilerPreferencePage(); + String id = "net.sourceforge.phpdt.ui.preferences.CompilerPreferencePage"; //$NON-NLS-1$ + CompilerPreferencePage page = new CompilerPreferencePage(); showPreferencePage(id, page); } else { updateEnableState(); doStatusChanged(); } } + /** * Method statusChanged. */ @@ -160,11 +175,12 @@ public class CompilerPropertyPage extends PropertyPage { if (useProjectSettings()) { if (fBlockEnableState != null) { fBlockEnableState.restore(); - fBlockEnableState= null; + fBlockEnableState = null; } } else { if (fBlockEnableState == null) { - fBlockEnableState= ControlEnableState.disable(fConfigurationBlockControl); + fBlockEnableState = ControlEnableState + .disable(fConfigurationBlockControl); } } } @@ -198,13 +214,14 @@ public class CompilerPropertyPage extends PropertyPage { PreferenceManager manager = new PreferenceManager(); manager.addToRoot(targetNode); - final PreferenceDialog dialog = new PreferenceDialog(getControl().getShell(), manager); - final boolean [] result = new boolean[] { false }; + final PreferenceDialog dialog = new PreferenceDialog(getControl() + .getShell(), manager); + final boolean[] result = new boolean[] { false }; BusyIndicator.showWhile(getControl().getDisplay(), new Runnable() { public void run() { dialog.create(); dialog.setMessage(targetNode.getLabelText()); - result[0]= (dialog.open() == Window.OK); + result[0] = (dialog.open() == Window.OK); } }); return result[0]; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/EditTemplateDialog.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/EditTemplateDialog.java index 5bd6980..d8e8299 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/EditTemplateDialog.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/EditTemplateDialog.java @@ -84,35 +84,41 @@ public class EditTemplateDialog extends StatusDialog { private static class TextViewerAction extends Action implements IUpdate { - private int fOperationCode= -1; + private int fOperationCode = -1; + private ITextOperationTarget fOperationTarget; /** * Creates a new action. - * - * @param viewer the viewer - * @param operationCode the opcode + * + * @param viewer + * the viewer + * @param operationCode + * the opcode */ public TextViewerAction(ITextViewer viewer, int operationCode) { - fOperationCode= operationCode; - fOperationTarget= viewer.getTextOperationTarget(); + fOperationCode = operationCode; + fOperationTarget = viewer.getTextOperationTarget(); update(); } /** - * Updates the enabled state of the action. - * Fires a property change if the enabled state changes. - * + * Updates the enabled state of the action. Fires a property change if + * the enabled state changes. + * * @see Action#firePropertyChange(String, Object, Object) */ public void update() { - boolean wasEnabled= isEnabled(); - boolean isEnabled= (fOperationTarget != null && fOperationTarget.canDoOperation(fOperationCode)); + boolean wasEnabled = isEnabled(); + boolean isEnabled = (fOperationTarget != null && fOperationTarget + .canDoOperation(fOperationCode)); setEnabled(isEnabled); if (wasEnabled != isEnabled) { - firePropertyChange(ENABLED, wasEnabled ? Boolean.TRUE : Boolean.FALSE, isEnabled ? Boolean.TRUE : Boolean.FALSE); + firePropertyChange(ENABLED, wasEnabled ? Boolean.TRUE + : Boolean.FALSE, isEnabled ? Boolean.TRUE + : Boolean.FALSE); } } @@ -129,62 +135,80 @@ public class EditTemplateDialog extends StatusDialog { private final Template fTemplate; private Text fNameText; + private Text fDescriptionText; + private Combo fContextCombo; + private SourceViewer fPatternEditor; + private Button fInsertVariableButton; + private boolean fIsNameModifiable; private StatusInfo fValidationStatus; - private boolean fSuppressError= true; // #4354 - private Map fGlobalActions= new HashMap(10); + + private boolean fSuppressError = true; // #4354 + + private Map fGlobalActions = new HashMap(10); + private List fSelectionActions = new ArrayList(3); + private String[][] fContextTypes; private ContextTypeRegistry fContextTypeRegistry; - private final TemplateVariableProcessor fTemplateProcessor= new TemplateVariableProcessor(); + private final TemplateVariableProcessor fTemplateProcessor = new TemplateVariableProcessor(); /** * Creates a new dialog. - * - * @param parent the shell parent of the dialog - * @param template the template to edit - * @param edit whether this is a new template or an existing being edited - * @param isNameModifiable whether the name of the template may be modified - * @param registry the context type registry to use + * + * @param parent + * the shell parent of the dialog + * @param template + * the template to edit + * @param edit + * whether this is a new template or an existing being edited + * @param isNameModifiable + * whether the name of the template may be modified + * @param registry + * the context type registry to use */ - public EditTemplateDialog(Shell parent, Template template, boolean edit, boolean isNameModifiable, ContextTypeRegistry registry) { + public EditTemplateDialog(Shell parent, Template template, boolean edit, + boolean isNameModifiable, ContextTypeRegistry registry) { super(parent); setShellStyle(getShellStyle() | SWT.MAX | SWT.RESIZE); - String title= edit - ? PreferencesMessages.getString("EditTemplateDialog.title.edit") //$NON-NLS-1$ - : PreferencesMessages.getString("EditTemplateDialog.title.new"); //$NON-NLS-1$ + String title = edit ? PreferencesMessages + .getString("EditTemplateDialog.title.edit") //$NON-NLS-1$ + : PreferencesMessages.getString("EditTemplateDialog.title.new"); //$NON-NLS-1$ setTitle(title); - fTemplate= template; - fIsNameModifiable= isNameModifiable; + fTemplate = template; + fIsNameModifiable = isNameModifiable; // XXX workaround for bug 63313 - disabling prefix until fixed. -// String delim= new Document().getLegalLineDelimiters()[0]; - - List contexts= new ArrayList(); - for (Iterator it= registry.contextTypes(); it.hasNext();) { - TemplateContextType type= (TemplateContextType) it.next(); -// if (type.getId().equals("javadoc")) //$NON-NLS-1$ -// contexts.add(new String[] { type.getId(), type.getName(), "/**" + delim }); //$NON-NLS-1$ -// else - contexts.add(new String[] { type.getId(), type.getName(), "" }); //$NON-NLS-1$ + // String delim= new Document().getLegalLineDelimiters()[0]; + + List contexts = new ArrayList(); + for (Iterator it = registry.contextTypes(); it.hasNext();) { + TemplateContextType type = (TemplateContextType) it.next(); + // if (type.getId().equals("javadoc")) //$NON-NLS-1$ + // contexts.add(new String[] { type.getId(), type.getName(), "/**" + + // delim }); //$NON-NLS-1$ + // else + contexts.add(new String[] { type.getId(), type.getName(), "" }); //$NON-NLS-1$ } - fContextTypes= (String[][]) contexts.toArray(new String[contexts.size()][]); + fContextTypes = (String[][]) contexts.toArray(new String[contexts + .size()][]); - fValidationStatus= new StatusInfo(); + fValidationStatus = new StatusInfo(); - fContextTypeRegistry= registry; + fContextTypeRegistry = registry; - TemplateContextType type= fContextTypeRegistry.getContextType(template.getContextTypeId()); + TemplateContextType type = fContextTypeRegistry.getContextType(template + .getContextTypeId()); fTemplateProcessor.setContextType(type); } @@ -194,42 +218,45 @@ public class EditTemplateDialog extends StatusDialog { public void create() { super.create(); // update initial ok button to be disabled for new templates - boolean valid= fNameText == null || fNameText.getText().trim().length() != 0; + boolean valid = fNameText == null + || fNameText.getText().trim().length() != 0; if (!valid) { StatusInfo status = new StatusInfo(); - status.setError(PreferencesMessages.getString("EditTemplateDialog.error.noname")); //$NON-NLS-1$ + status.setError(PreferencesMessages + .getString("EditTemplateDialog.error.noname")); //$NON-NLS-1$ updateButtonsEnableState(status); - } + } } /* * @see Dialog#createDialogArea(Composite) */ protected Control createDialogArea(Composite ancestor) { - Composite parent= new Composite(ancestor, SWT.NONE); - GridLayout layout= new GridLayout(); - layout.numColumns= 2; + Composite parent = new Composite(ancestor, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.numColumns = 2; parent.setLayout(layout); parent.setLayoutData(new GridData(GridData.FILL_BOTH)); - ModifyListener listener= new ModifyListener() { + ModifyListener listener = new ModifyListener() { public void modifyText(ModifyEvent e) { doTextWidgetChanged(e.widget); } }; if (fIsNameModifiable) { - createLabel(parent, PreferencesMessages.getString("EditTemplateDialog.name")); //$NON-NLS-1$ + createLabel(parent, PreferencesMessages + .getString("EditTemplateDialog.name")); //$NON-NLS-1$ - Composite composite= new Composite(parent, SWT.NONE); + Composite composite = new Composite(parent, SWT.NONE); composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - layout= new GridLayout(); - layout.numColumns= 3; - layout.marginWidth= 0; - layout.marginHeight= 0; + layout = new GridLayout(); + layout.numColumns = 3; + layout.marginWidth = 0; + layout.marginHeight = 0; composite.setLayout(layout); - fNameText= createText(composite); + fNameText = createText(composite); fNameText.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { @@ -237,54 +264,63 @@ public class EditTemplateDialog extends StatusDialog { public void focusLost(FocusEvent e) { if (fSuppressError) { - fSuppressError= false; + fSuppressError = false; updateButtons(); } } }); - createLabel(composite, PreferencesMessages.getString("EditTemplateDialog.context")); //$NON-NLS-1$ - fContextCombo= new Combo(composite, SWT.READ_ONLY); + createLabel(composite, PreferencesMessages + .getString("EditTemplateDialog.context")); //$NON-NLS-1$ + fContextCombo = new Combo(composite, SWT.READ_ONLY); - for (int i= 0; i < fContextTypes.length; i++) { + for (int i = 0; i < fContextTypes.length; i++) { fContextCombo.add(fContextTypes[i][1]); } fContextCombo.addModifyListener(listener); } - createLabel(parent, PreferencesMessages.getString("EditTemplateDialog.description")); //$NON-NLS-1$ + createLabel(parent, PreferencesMessages + .getString("EditTemplateDialog.description")); //$NON-NLS-1$ - int descFlags= fIsNameModifiable ? SWT.BORDER : SWT.BORDER | SWT.READ_ONLY; - fDescriptionText= new Text(parent, descFlags ); + int descFlags = fIsNameModifiable ? SWT.BORDER : SWT.BORDER + | SWT.READ_ONLY; + fDescriptionText = new Text(parent, descFlags); fDescriptionText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fDescriptionText.addModifyListener(listener); - Label patternLabel= createLabel(parent, PreferencesMessages.getString("EditTemplateDialog.pattern")); //$NON-NLS-1$ - patternLabel.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING)); - fPatternEditor= createEditor(parent); + Label patternLabel = createLabel(parent, PreferencesMessages + .getString("EditTemplateDialog.pattern")); //$NON-NLS-1$ + patternLabel.setLayoutData(new GridData( + GridData.VERTICAL_ALIGN_BEGINNING)); + fPatternEditor = createEditor(parent); - Label filler= new Label(parent, SWT.NONE); + Label filler = new Label(parent, SWT.NONE); filler.setLayoutData(new GridData()); - Composite composite= new Composite(parent, SWT.NONE); - layout= new GridLayout(); - layout.marginWidth= 0; - layout.marginHeight= 0; + Composite composite = new Composite(parent, SWT.NONE); + layout = new GridLayout(); + layout.marginWidth = 0; + layout.marginHeight = 0; composite.setLayout(layout); composite.setLayoutData(new GridData()); - fInsertVariableButton= new Button(composite, SWT.NONE); - fInsertVariableButton.setLayoutData(getButtonGridData(fInsertVariableButton)); - fInsertVariableButton.setText(PreferencesMessages.getString("EditTemplateDialog.insert.variable")); //$NON-NLS-1$ + fInsertVariableButton = new Button(composite, SWT.NONE); + fInsertVariableButton + .setLayoutData(getButtonGridData(fInsertVariableButton)); + fInsertVariableButton.setText(PreferencesMessages + .getString("EditTemplateDialog.insert.variable")); //$NON-NLS-1$ fInsertVariableButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { fPatternEditor.getTextWidget().setFocus(); - fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS); + fPatternEditor + .doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS); } - public void widgetDefaultSelected(SelectionEvent e) {} + public void widgetDefaultSelected(SelectionEvent e) { + } }); fDescriptionText.setText(fTemplate.getDescription()); @@ -303,17 +339,18 @@ public class EditTemplateDialog extends StatusDialog { protected void doTextWidgetChanged(Widget w) { if (w == fNameText) { - fSuppressError= false; - String name= fNameText.getText(); + fSuppressError = false; + String name = fNameText.getText(); fTemplate.setName(name); updateButtons(); } else if (w == fContextCombo) { - String name= fContextCombo.getText(); - String contextId= getContextId(name); + String name = fContextCombo.getText(); + String contextId = getContextId(name); fTemplate.setContextTypeId(contextId); - fTemplateProcessor.setContextType(fContextTypeRegistry.getContextType(contextId)); + fTemplateProcessor.setContextType(fContextTypeRegistry + .getContextType(contextId)); } else if (w == fDescriptionText) { - String desc= fDescriptionText.getText(); + String desc = fDescriptionText.getText(); fTemplate.setDescription(desc); } } @@ -322,7 +359,7 @@ public class EditTemplateDialog extends StatusDialog { if (name == null) return name; - for (int i= 0; i < fContextTypes.length; i++) { + for (int i = 0; i < fContextTypes.length; i++) { if (name.equals(fContextTypes[i][1])) { return fContextTypes[i][0]; } @@ -331,11 +368,12 @@ public class EditTemplateDialog extends StatusDialog { } protected void doSourceChanged(IDocument document) { - String text= document.get(); - String prefix= getPrefix(); + String text = document.get(); + String prefix = getPrefix(); fTemplate.setPattern(text.substring(prefix.length(), text.length())); fValidationStatus.setOK(); - TemplateContextType contextType= fContextTypeRegistry.getContextType(fTemplate.getContextTypeId()); + TemplateContextType contextType = fContextTypeRegistry + .getContextType(fTemplate.getContextTypeId()); if (contextType != null) { try { contextType.validate(text); @@ -349,14 +387,14 @@ public class EditTemplateDialog extends StatusDialog { } private static GridData getButtonGridData(Button button) { - GridData data= new GridData(GridData.FILL_HORIZONTAL); - data.heightHint= SWTUtil.getButtonHeightHint(button); + GridData data = new GridData(GridData.FILL_HORIZONTAL); + data.heightHint = SWTUtil.getButtonHeightHint(button); return data; } private static Label createLabel(Composite parent, String name) { - Label label= new Label(parent, SWT.NULL); + Label label = new Label(parent, SWT.NULL); label.setText(name); label.setLayoutData(new GridData()); @@ -364,46 +402,52 @@ public class EditTemplateDialog extends StatusDialog { } private static Text createText(Composite parent) { - Text text= new Text(parent, SWT.BORDER); + Text text = new Text(parent, SWT.BORDER); text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); return text; } private SourceViewer createEditor(Composite parent) { - String prefix= getPrefix(); - IDocument document= new Document(prefix + fTemplate.getPattern()); - JavaTextTools tools= PHPeclipsePlugin.getDefault().getJavaTextTools(); - tools.setupJavaDocumentPartitioner(document, IPHPPartitions.PHP_PARTITIONING); - IPreferenceStore store= PHPeclipsePlugin.getDefault().getCombinedPreferenceStore(); - SourceViewer viewer= new JavaSourceViewer(parent, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL, store); - TemplateEditorSourceViewerConfiguration configuration= new TemplateEditorSourceViewerConfiguration(tools.getColorManager(), store, null, fTemplateProcessor); + String prefix = getPrefix(); + IDocument document = new Document(prefix + fTemplate.getPattern()); + JavaTextTools tools = PHPeclipsePlugin.getDefault().getJavaTextTools(); + tools.setupJavaDocumentPartitioner(document, + IPHPPartitions.PHP_PARTITIONING); + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getCombinedPreferenceStore(); + SourceViewer viewer = new JavaSourceViewer(parent, null, null, false, + SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL, store); + TemplateEditorSourceViewerConfiguration configuration = new TemplateEditorSourceViewerConfiguration( + tools.getColorManager(), store, null, fTemplateProcessor); viewer.configure(configuration); viewer.setEditable(true); // XXX workaround for bug 63313 - disabling prefix until fixed. -// viewer.setDocument(document, prefix.length(), document.getLength() - prefix.length()); + // viewer.setDocument(document, prefix.length(), document.getLength() - + // prefix.length()); viewer.setDocument(document); - Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT); + Font font = JFaceResources + .getFont(PreferenceConstants.EDITOR_TEXT_FONT); viewer.getTextWidget().setFont(font); new JavaSourcePreviewerUpdater(viewer, configuration, store); - int nLines= document.getNumberOfLines(); + int nLines = document.getNumberOfLines(); if (nLines < 5) { - nLines= 5; + nLines = 5; } else if (nLines > 12) { - nLines= 12; + nLines = 12; } - Control control= viewer.getControl(); - GridData data= new GridData(GridData.FILL_BOTH); - data.widthHint= convertWidthInCharsToPixels(80); - data.heightHint= convertHeightInCharsToPixels(nLines); + Control control = viewer.getControl(); + GridData data = new GridData(GridData.FILL_BOTH); + data.widthHint = convertWidthInCharsToPixels(80); + data.heightHint = convertHeightInCharsToPixels(nLines); control.setLayoutData(data); viewer.addTextListener(new ITextListener() { public void textChanged(TextEvent event) { - if (event .getDocumentEvent() != null) + if (event.getDocumentEvent() != null) doSourceChanged(event.getDocumentEvent().getDocument()); } }); @@ -425,11 +469,11 @@ public class EditTemplateDialog extends StatusDialog { private String getPrefix() { String prefix; - int idx= getIndex(fTemplate.getContextTypeId()); + int idx = getIndex(fTemplate.getContextTypeId()); if (idx != -1) - prefix= fContextTypes[idx][2]; + prefix = fContextTypes[idx][2]; else - prefix= ""; //$NON-NLS-1$ + prefix = ""; //$NON-NLS-1$ return prefix; } @@ -442,42 +486,51 @@ public class EditTemplateDialog extends StatusDialog { return; switch (event.character) { - case ' ': - fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS); - event.doit= false; - break; - - // CTRL-Z - case 'z' - 'a' + 1: - fPatternEditor.doOperation(ITextOperationTarget.UNDO); - event.doit= false; - break; + case ' ': + fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS); + event.doit = false; + break; + + // CTRL-Z + case 'z' - 'a' + 1: + fPatternEditor.doOperation(ITextOperationTarget.UNDO); + event.doit = false; + break; } } private void initializeActions() { - TextViewerAction action= new TextViewerAction(fPatternEditor, SourceViewer.UNDO); - action.setText(PreferencesMessages.getString("EditTemplateDialog.undo")); //$NON-NLS-1$ + TextViewerAction action = new TextViewerAction(fPatternEditor, + SourceViewer.UNDO); + action + .setText(PreferencesMessages + .getString("EditTemplateDialog.undo")); //$NON-NLS-1$ fGlobalActions.put(ITextEditorActionConstants.UNDO, action); - action= new TextViewerAction(fPatternEditor, SourceViewer.CUT); + action = new TextViewerAction(fPatternEditor, SourceViewer.CUT); action.setText(PreferencesMessages.getString("EditTemplateDialog.cut")); //$NON-NLS-1$ fGlobalActions.put(ITextEditorActionConstants.CUT, action); - action= new TextViewerAction(fPatternEditor, SourceViewer.COPY); - action.setText(PreferencesMessages.getString("EditTemplateDialog.copy")); //$NON-NLS-1$ + action = new TextViewerAction(fPatternEditor, SourceViewer.COPY); + action + .setText(PreferencesMessages + .getString("EditTemplateDialog.copy")); //$NON-NLS-1$ fGlobalActions.put(ITextEditorActionConstants.COPY, action); - action= new TextViewerAction(fPatternEditor, SourceViewer.PASTE); - action.setText(PreferencesMessages.getString("EditTemplateDialog.paste")); //$NON-NLS-1$ + action = new TextViewerAction(fPatternEditor, SourceViewer.PASTE); + action.setText(PreferencesMessages + .getString("EditTemplateDialog.paste")); //$NON-NLS-1$ fGlobalActions.put(ITextEditorActionConstants.PASTE, action); - action= new TextViewerAction(fPatternEditor, SourceViewer.SELECT_ALL); - action.setText(PreferencesMessages.getString("EditTemplateDialog.select.all")); //$NON-NLS-1$ + action = new TextViewerAction(fPatternEditor, SourceViewer.SELECT_ALL); + action.setText(PreferencesMessages + .getString("EditTemplateDialog.select.all")); //$NON-NLS-1$ fGlobalActions.put(ITextEditorActionConstants.SELECT_ALL, action); - action= new TextViewerAction(fPatternEditor, SourceViewer.CONTENTASSIST_PROPOSALS); - action.setText(PreferencesMessages.getString("EditTemplateDialog.content.assist")); //$NON-NLS-1$ + action = new TextViewerAction(fPatternEditor, + SourceViewer.CONTENTASSIST_PROPOSALS); + action.setText(PreferencesMessages + .getString("EditTemplateDialog.content.assist")); //$NON-NLS-1$ fGlobalActions.put("ContentAssistProposal", action); //$NON-NLS-1$ fSelectionActions.add(ITextEditorActionConstants.CUT); @@ -485,7 +538,7 @@ public class EditTemplateDialog extends StatusDialog { fSelectionActions.add(ITextEditorActionConstants.PASTE); // create context menu - MenuManager manager= new MenuManager(null, null); + MenuManager manager = new MenuManager(null, null); manager.setRemoveAllWhenShown(true); manager.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager mgr) { @@ -493,39 +546,47 @@ public class EditTemplateDialog extends StatusDialog { } }); - StyledText text= fPatternEditor.getTextWidget(); - Menu menu= manager.createContextMenu(text); + StyledText text = fPatternEditor.getTextWidget(); + Menu menu = manager.createContextMenu(text); text.setMenu(menu); } private void fillContextMenu(IMenuManager menu) { menu.add(new GroupMarker(ITextEditorActionConstants.GROUP_UNDO)); - menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO)); + menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, + (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO)); menu.add(new Separator(ITextEditorActionConstants.GROUP_EDIT)); - menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.CUT)); - menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.COPY)); - menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.PASTE)); - menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.SELECT_ALL)); + menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, + (IAction) fGlobalActions.get(ITextEditorActionConstants.CUT)); + menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, + (IAction) fGlobalActions.get(ITextEditorActionConstants.COPY)); + menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, + (IAction) fGlobalActions.get(ITextEditorActionConstants.PASTE)); + menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, + (IAction) fGlobalActions + .get(ITextEditorActionConstants.SELECT_ALL)); menu.add(new Separator(IContextMenuConstants.GROUP_GENERATE)); - menu.appendToGroup(IContextMenuConstants.GROUP_GENERATE, (IAction) fGlobalActions.get("ContentAssistProposal")); //$NON-NLS-1$ + menu.appendToGroup(IContextMenuConstants.GROUP_GENERATE, + (IAction) fGlobalActions.get("ContentAssistProposal")); //$NON-NLS-1$ } protected void updateSelectionDependentActions() { - Iterator iterator= fSelectionActions.iterator(); + Iterator iterator = fSelectionActions.iterator(); while (iterator.hasNext()) - updateAction((String)iterator.next()); + updateAction((String) iterator.next()); } protected void updateUndoAction() { - IAction action= (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO); + IAction action = (IAction) fGlobalActions + .get(ITextEditorActionConstants.UNDO); if (action instanceof IUpdate) ((IUpdate) action).update(); } protected void updateAction(String actionId) { - IAction action= (IAction) fGlobalActions.get(actionId); + IAction action = (IAction) fGlobalActions.get(actionId); if (action instanceof IUpdate) ((IUpdate) action).update(); } @@ -535,7 +596,7 @@ public class EditTemplateDialog extends StatusDialog { if (contextid == null) return -1; - for (int i= 0; i < fContextTypes.length; i++) { + for (int i = 0; i < fContextTypes.length; i++) { if (contextid.equals(fContextTypes[i][0])) { return i; } @@ -550,15 +611,17 @@ public class EditTemplateDialog extends StatusDialog { private void updateButtons() { StatusInfo status; - boolean valid= fNameText == null || fNameText.getText().trim().length() != 0; + boolean valid = fNameText == null + || fNameText.getText().trim().length() != 0; if (!valid) { status = new StatusInfo(); if (!fSuppressError) { - status.setError(PreferencesMessages.getString("EditTemplateDialog.error.noname")); //$NON-NLS-1$ + status.setError(PreferencesMessages + .getString("EditTemplateDialog.error.noname")); //$NON-NLS-1$ } - } else { - status= fValidationStatus; - } + } else { + status = fValidationStatus; + } updateStatus(status); } @@ -567,8 +630,8 @@ public class EditTemplateDialog extends StatusDialog { */ protected void configureShell(Shell newShell) { super.configureShell(newShell); - PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.EDIT_TEMPLATE_DIALOG); + PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, + IJavaHelpContextIds.EDIT_TEMPLATE_DIALOG); } - } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/FoldingConfigurationBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/FoldingConfigurationBlock.java index a1dfb5d..bafbeb7 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/FoldingConfigurationBlock.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/FoldingConfigurationBlock.java @@ -55,24 +55,25 @@ import org.eclipse.swt.widgets.Label; * @since 3.0 */ class FoldingConfigurationBlock { - - private static class ErrorPreferences implements IJavaFoldingPreferenceBlock { + + private static class ErrorPreferences implements + IJavaFoldingPreferenceBlock { private String fMessage; - + protected ErrorPreferences(String message) { - fMessage= message; + fMessage = message; } - + /* * @see net.sourceforge.phpdt.internal.ui.text.folding.IJavaFoldingPreferences#createControl(org.eclipse.swt.widgets.Group) */ public Control createControl(Composite composite) { - Composite inner= new Composite(composite, SWT.NONE); + Composite inner = new Composite(composite, SWT.NONE); inner.setLayout(new FillLayout(SWT.VERTICAL)); - Label label= new Label(inner, SWT.CENTER); + Label label = new Label(inner, SWT.CENTER); label.setText(fMessage); - + return inner; } @@ -87,51 +88,64 @@ class FoldingConfigurationBlock { public void dispose() { } - + } /** The overlay preference store. */ private final OverlayPreferenceStore fStore; - + /* The controls */ private Combo fProviderCombo; + private Button fFoldingCheckbox; + private ComboViewer fProviderViewer; + private Map fProviderDescriptors; + private Composite fGroup; + private Map fProviderPreferences; + private Map fProviderControls; + private StackLayout fStackLayout; - public FoldingConfigurationBlock(OverlayPreferenceStore store) { Assert.isNotNull(store); - fStore= store; + fStore = store; fStore.addKeys(createOverlayStoreKeys()); - fProviderDescriptors= createListModel(); - fProviderPreferences= new HashMap(); - fProviderControls= new HashMap(); + fProviderDescriptors = createListModel(); + fProviderPreferences = new HashMap(); + fProviderControls = new HashMap(); } private Map createListModel() { - JavaFoldingStructureProviderRegistry reg= PHPeclipsePlugin.getDefault().getFoldingStructureProviderRegistry(); + JavaFoldingStructureProviderRegistry reg = PHPeclipsePlugin + .getDefault().getFoldingStructureProviderRegistry(); reg.reloadExtensions(); - JavaFoldingStructureProviderDescriptor[] descs= reg.getFoldingProviderDescriptors(); - Map map= new HashMap(); - for (int i= 0; i < descs.length; i++) { + JavaFoldingStructureProviderDescriptor[] descs = reg + .getFoldingProviderDescriptors(); + Map map = new HashMap(); + for (int i = 0; i < descs.length; i++) { map.put(descs[i].getId(), descs[i]); } return map; } private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys() { - - ArrayList overlayKeys= new ArrayList(); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FOLDING_ENABLED)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_FOLDING_PROVIDER)); - - OverlayPreferenceStore.OverlayKey[] keys= new OverlayPreferenceStore.OverlayKey[overlayKeys.size()]; + ArrayList overlayKeys = new ArrayList(); + + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_FOLDING_ENABLED)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_FOLDING_PROVIDER)); + + OverlayPreferenceStore.OverlayKey[] keys = new OverlayPreferenceStore.OverlayKey[overlayKeys + .size()]; overlayKeys.toArray(keys); return keys; } @@ -139,64 +153,74 @@ class FoldingConfigurationBlock { /** * Creates page for folding preferences. * - * @param parent the parent composite + * @param parent + * the parent composite * @return the control for the preference page */ Control createControl(Composite parent) { - Composite composite= new Composite(parent, SWT.NULL); + Composite composite = new Composite(parent, SWT.NULL); // assume parent page uses griddata - GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_CENTER | GridData.VERTICAL_ALIGN_FILL); + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_CENTER + | GridData.VERTICAL_ALIGN_FILL); composite.setLayoutData(gd); - GridLayout layout= new GridLayout(); - layout.numColumns= 2; - PixelConverter pc= new PixelConverter(composite); - layout.verticalSpacing= pc.convertHeightInCharsToPixels(1) / 2; + GridLayout layout = new GridLayout(); + layout.numColumns = 2; + PixelConverter pc = new PixelConverter(composite); + layout.verticalSpacing = pc.convertHeightInCharsToPixels(1) / 2; composite.setLayout(layout); - - + /* check box for new editors */ - fFoldingCheckbox= new Button(composite, SWT.CHECK); - fFoldingCheckbox.setText(PreferencesMessages.getString("FoldingConfigurationBlock.enable")); //$NON-NLS-1$ - gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_BEGINNING); + fFoldingCheckbox = new Button(composite, SWT.CHECK); + fFoldingCheckbox.setText(PreferencesMessages + .getString("FoldingConfigurationBlock.enable")); //$NON-NLS-1$ + gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING + | GridData.VERTICAL_ALIGN_BEGINNING); fFoldingCheckbox.setLayoutData(gd); fFoldingCheckbox.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { - boolean enabled= fFoldingCheckbox.getSelection(); - fStore.setValue(PreferenceConstants.EDITOR_FOLDING_ENABLED, enabled); + boolean enabled = fFoldingCheckbox.getSelection(); + fStore.setValue(PreferenceConstants.EDITOR_FOLDING_ENABLED, + enabled); updateCheckboxDependencies(); } public void widgetDefaultSelected(SelectionEvent e) { } }); - - Label label= new Label(composite, SWT.CENTER); - gd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); + + Label label = new Label(composite, SWT.CENTER); + gd = new GridData(GridData.FILL_HORIZONTAL + | GridData.VERTICAL_ALIGN_BEGINNING); label.setLayoutData(gd); /* list */ - Composite comboComp= new Composite(composite, SWT.NONE); - gd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); - GridLayout gridLayout= new GridLayout(2, false); - gridLayout.marginWidth= 0; + Composite comboComp = new Composite(composite, SWT.NONE); + gd = new GridData(GridData.FILL_HORIZONTAL + | GridData.VERTICAL_ALIGN_BEGINNING); + GridLayout gridLayout = new GridLayout(2, false); + gridLayout.marginWidth = 0; comboComp.setLayout(gridLayout); - - Label comboLabel= new Label(comboComp, SWT.CENTER); - gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_CENTER); + + Label comboLabel = new Label(comboComp, SWT.CENTER); + gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING + | GridData.VERTICAL_ALIGN_CENTER); comboLabel.setLayoutData(gd); - comboLabel.setText(PreferencesMessages.getString("FoldingConfigurationBlock.combo_caption")); //$NON-NLS-1$ - - label= new Label(composite, SWT.CENTER); - gd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING); + comboLabel.setText(PreferencesMessages + .getString("FoldingConfigurationBlock.combo_caption")); //$NON-NLS-1$ + + label = new Label(composite, SWT.CENTER); + gd = new GridData(GridData.FILL_HORIZONTAL + | GridData.VERTICAL_ALIGN_BEGINNING); label.setLayoutData(gd); - fProviderCombo= new Combo(comboComp, SWT.READ_ONLY | SWT.DROP_DOWN); - gd= new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.VERTICAL_ALIGN_CENTER); + fProviderCombo = new Combo(comboComp, SWT.READ_ONLY | SWT.DROP_DOWN); + gd = new GridData(GridData.HORIZONTAL_ALIGN_END + | GridData.VERTICAL_ALIGN_CENTER); fProviderCombo.setLayoutData(gd); /* list viewer */ - fProviderViewer= new ComboViewer(fProviderCombo); + fProviderViewer = new ComboViewer(fProviderCombo); fProviderViewer.setContentProvider(new IStructuredContentProvider() { /* @@ -206,9 +230,11 @@ class FoldingConfigurationBlock { } /* - * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object) + * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, + * java.lang.Object, java.lang.Object) */ - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + public void inputChanged(Viewer viewer, Object oldInput, + Object newInput) { } /* @@ -225,42 +251,50 @@ class FoldingConfigurationBlock { public Image getImage(Object element) { return null; } - + /* * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object) */ public String getText(Object element) { - return ((JavaFoldingStructureProviderDescriptor) element).getName(); + return ((JavaFoldingStructureProviderDescriptor) element) + .getName(); } }); - fProviderViewer.addSelectionChangedListener(new ISelectionChangedListener() { + fProviderViewer + .addSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - IStructuredSelection sel= (IStructuredSelection) event.getSelection(); - if (!sel.isEmpty()) { - fStore.setValue(PreferenceConstants.EDITOR_FOLDING_PROVIDER, ((JavaFoldingStructureProviderDescriptor) sel.getFirstElement()).getId()); - updateListDependencies(); - } - } - }); + public void selectionChanged(SelectionChangedEvent event) { + IStructuredSelection sel = (IStructuredSelection) event + .getSelection(); + if (!sel.isEmpty()) { + fStore + .setValue( + PreferenceConstants.EDITOR_FOLDING_PROVIDER, + ((JavaFoldingStructureProviderDescriptor) sel + .getFirstElement()).getId()); + updateListDependencies(); + } + } + }); fProviderViewer.setInput(fProviderDescriptors); fProviderViewer.refresh(); - - Composite groupComp= new Composite(composite, SWT.NONE); - gd= new GridData(GridData.FILL_BOTH); - gd.horizontalSpan= 2; + + Composite groupComp = new Composite(composite, SWT.NONE); + gd = new GridData(GridData.FILL_BOTH); + gd.horizontalSpan = 2; groupComp.setLayoutData(gd); - gridLayout= new GridLayout(1, false); - gridLayout.marginWidth= 0; + gridLayout = new GridLayout(1, false); + gridLayout.marginWidth = 0; groupComp.setLayout(gridLayout); - + /* contributed provider preferences. */ - fGroup= new Composite(groupComp, SWT.NONE); - gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_BEGINNING); + fGroup = new Composite(groupComp, SWT.NONE); + gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING + | GridData.VERTICAL_ALIGN_BEGINNING); fGroup.setLayoutData(gd); - fStackLayout= new StackLayout(); + fStackLayout = new StackLayout(); fGroup.setLayout(fStackLayout); - + return composite; } @@ -268,43 +302,48 @@ class FoldingConfigurationBlock { } void updateListDependencies() { - String id= fStore.getString(PreferenceConstants.EDITOR_FOLDING_PROVIDER); - JavaFoldingStructureProviderDescriptor desc= (JavaFoldingStructureProviderDescriptor) fProviderDescriptors.get(id); + String id = fStore + .getString(PreferenceConstants.EDITOR_FOLDING_PROVIDER); + JavaFoldingStructureProviderDescriptor desc = (JavaFoldingStructureProviderDescriptor) fProviderDescriptors + .get(id); IJavaFoldingPreferenceBlock prefs; - + if (desc == null) { // safety in case there is no such descriptor - String message= PreferencesMessages.getString("FoldingConfigurationBlock.error.not_exist"); //$NON-NLS-1$ - PHPeclipsePlugin.log(new Status(IStatus.WARNING, PHPeclipsePlugin.getPluginId(), IStatus.OK, message, null)); - prefs= new ErrorPreferences(message); + String message = PreferencesMessages + .getString("FoldingConfigurationBlock.error.not_exist"); //$NON-NLS-1$ + PHPeclipsePlugin.log(new Status(IStatus.WARNING, PHPeclipsePlugin + .getPluginId(), IStatus.OK, message, null)); + prefs = new ErrorPreferences(message); } else { - prefs= (IJavaFoldingPreferenceBlock) fProviderPreferences.get(id); + prefs = (IJavaFoldingPreferenceBlock) fProviderPreferences.get(id); if (prefs == null) { try { - prefs= desc.createPreferences(); + prefs = desc.createPreferences(); fProviderPreferences.put(id, prefs); } catch (CoreException e) { PHPeclipsePlugin.log(e); - prefs= new ErrorPreferences(e.getLocalizedMessage()); + prefs = new ErrorPreferences(e.getLocalizedMessage()); } } } - - Control control= (Control) fProviderControls.get(id); + + Control control = (Control) fProviderControls.get(id); if (control == null) { - control= prefs.createControl(fGroup); + control = prefs.createControl(fGroup); if (control == null) { - String message= PreferencesMessages.getString("FoldingConfigurationBlock.info.no_preferences"); //$NON-NLS-1$ - control= new ErrorPreferences(message).createControl(fGroup); + String message = PreferencesMessages + .getString("FoldingConfigurationBlock.info.no_preferences"); //$NON-NLS-1$ + control = new ErrorPreferences(message).createControl(fGroup); } else { fProviderControls.put(id, control); } } - fStackLayout.topControl= control; + fStackLayout.topControl = control; control.pack(); fGroup.layout(); fGroup.getParent().layout(); - + prefs.initialize(); } @@ -313,36 +352,45 @@ class FoldingConfigurationBlock { } void performOk() { - for (Iterator it= fProviderPreferences.values().iterator(); it.hasNext();) { - IJavaFoldingPreferenceBlock prefs= (IJavaFoldingPreferenceBlock) it.next(); + for (Iterator it = fProviderPreferences.values().iterator(); it + .hasNext();) { + IJavaFoldingPreferenceBlock prefs = (IJavaFoldingPreferenceBlock) it + .next(); prefs.performOk(); } } - + void performDefaults() { restoreFromPreferences(); - for (Iterator it= fProviderPreferences.values().iterator(); it.hasNext();) { - IJavaFoldingPreferenceBlock prefs= (IJavaFoldingPreferenceBlock) it.next(); + for (Iterator it = fProviderPreferences.values().iterator(); it + .hasNext();) { + IJavaFoldingPreferenceBlock prefs = (IJavaFoldingPreferenceBlock) it + .next(); prefs.performDefaults(); } } - + void dispose() { - for (Iterator it= fProviderPreferences.values().iterator(); it.hasNext();) { - IJavaFoldingPreferenceBlock prefs= (IJavaFoldingPreferenceBlock) it.next(); + for (Iterator it = fProviderPreferences.values().iterator(); it + .hasNext();) { + IJavaFoldingPreferenceBlock prefs = (IJavaFoldingPreferenceBlock) it + .next(); prefs.dispose(); } } private void restoreFromPreferences() { - boolean enabled= fStore.getBoolean(PreferenceConstants.EDITOR_FOLDING_ENABLED); + boolean enabled = fStore + .getBoolean(PreferenceConstants.EDITOR_FOLDING_ENABLED); fFoldingCheckbox.setSelection(enabled); updateCheckboxDependencies(); - - String id= fStore.getString(PreferenceConstants.EDITOR_FOLDING_PROVIDER); - Object provider= fProviderDescriptors.get(id); + + String id = fStore + .getString(PreferenceConstants.EDITOR_FOLDING_PROVIDER); + Object provider = fProviderDescriptors.get(id); if (provider != null) { - fProviderViewer.setSelection(new StructuredSelection(provider), true); + fProviderViewer.setSelection(new StructuredSelection(provider), + true); updateListDependencies(); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/IPreferenceConfigurationBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/IPreferenceConfigurationBlock.java index 5690e85..10f856d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/IPreferenceConfigurationBlock.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/IPreferenceConfigurationBlock.java @@ -14,10 +14,10 @@ package net.sourceforge.phpdt.internal.ui.preferences; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; - /** - * Interface for preference configuration blocks which can either be - * wrapped by a {@link net.sourceforge.phpdt.internal.ui.preferences.AbstractConfigurationBlockPreferencePage} + * Interface for preference configuration blocks which can either be wrapped by + * a + * {@link net.sourceforge.phpdt.internal.ui.preferences.AbstractConfigurationBlockPreferencePage} * or be included some preference page. *

                                                      * Clients may implement this interface. @@ -26,35 +26,36 @@ import org.eclipse.swt.widgets.Control; * @since 3.0 */ public interface IPreferenceConfigurationBlock { - + /** * Creates the preference control. * - * @param parent the parent composite to which to add the preferences control - * @return the control that was added to parent + * @param parent + * the parent composite to which to add the preferences control + * @return the control that was added to parent */ Control createControl(Composite parent); - + /** - * Called after creating the control. Implementations should load the + * Called after creating the control. Implementations should load the * preferences values and update the controls accordingly. */ void initialize(); - + /** * Called when the OK button is pressed on the preference * page. Implementations should commit the configured preference settings * into their form of preference storage. */ void performOk(); - + /** * Called when the Defaults button is pressed on the * preference page. Implementation should reset any preference settings to * their default values and adjust the controls accordingly. */ void performDefaults(); - + /** * Called when the preference page is being disposed. Implementations should * free any resources they are holding on to. diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaEditorHoverConfigurationBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaEditorHoverConfigurationBlock.java index d5b0fb5..d0aefce 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaEditorHoverConfigurationBlock.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaEditorHoverConfigurationBlock.java @@ -50,39 +50,49 @@ import org.eclipse.swt.widgets.Text; */ class JavaEditorHoverConfigurationBlock { - private static final String DELIMITER= PreferencesMessages.getString("JavaEditorHoverConfigurationBlock.delimiter"); //$NON-NLS-1$ + private static final String DELIMITER = PreferencesMessages + .getString("JavaEditorHoverConfigurationBlock.delimiter"); //$NON-NLS-1$ // Data structure to hold the values which are edited by the user private static class HoverConfig { - + private String fModifierString; + private boolean fIsEnabled; + private int fStateMask; private HoverConfig(String modifier, int stateMask, boolean enabled) { - fModifierString= modifier; - fIsEnabled= enabled; - fStateMask= stateMask; + fModifierString = modifier; + fIsEnabled = enabled; + fStateMask = stateMask; } } private IPreferenceStore fStore; + private HoverConfig[] fHoverConfigs; + private Text fModifierEditor; + private Button fEnableField; + private List fHoverList; + private Text fDescription; + private Button fShowHoverAffordanceCheckbox; - + private JavaEditorPreferencePage fMainPreferencePage; private StatusInfo fStatus; - public JavaEditorHoverConfigurationBlock(JavaEditorPreferencePage mainPreferencePage, IPreferenceStore store) { + public JavaEditorHoverConfigurationBlock( + JavaEditorPreferencePage mainPreferencePage, IPreferenceStore store) { Assert.isNotNull(mainPreferencePage); Assert.isNotNull(store); - fMainPreferencePage= mainPreferencePage; - fStore= store; + fMainPreferencePage = mainPreferencePage; + fStore = store; } /** @@ -90,106 +100,134 @@ class JavaEditorHoverConfigurationBlock { */ public Control createControl(Composite parent) { - PixelConverter pixelConverter= new PixelConverter(parent); + PixelConverter pixelConverter = new PixelConverter(parent); - Composite hoverComposite= new Composite(parent, SWT.NULL); - GridLayout layout= new GridLayout(); - layout.numColumns= 2; + Composite hoverComposite = new Composite(parent, SWT.NULL); + GridLayout layout = new GridLayout(); + layout.numColumns = 2; hoverComposite.setLayout(layout); - GridData gd= new GridData(GridData.GRAB_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL); + GridData gd = new GridData(GridData.GRAB_HORIZONTAL + | GridData.VERTICAL_ALIGN_FILL); hoverComposite.setLayoutData(gd); - Label label= new Label(hoverComposite, SWT.NONE); - label.setText(PreferencesMessages.getString("JavaEditorHoverConfigurationBlock.hoverPreferences")); //$NON-NLS-1$ - gd= new GridData(GridData.FILL_HORIZONTAL); - gd.horizontalAlignment= GridData.BEGINNING; - gd.horizontalSpan= 2; + Label label = new Label(hoverComposite, SWT.NONE); + label + .setText(PreferencesMessages + .getString("JavaEditorHoverConfigurationBlock.hoverPreferences")); //$NON-NLS-1$ + gd = new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalAlignment = GridData.BEGINNING; + gd.horizontalSpan = 2; label.setLayoutData(gd); - gd= new GridData(GridData.GRAB_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL); + gd = new GridData(GridData.GRAB_HORIZONTAL + | GridData.VERTICAL_ALIGN_FILL); // Hover list - fHoverList= new List(hoverComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); - gd= new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL); - int listHeight= 10 * fHoverList.getItemHeight(); - gd.heightHint= listHeight; + fHoverList = new List(hoverComposite, SWT.SINGLE | SWT.V_SCROLL + | SWT.BORDER); + gd = new GridData(GridData.VERTICAL_ALIGN_BEGINNING + | GridData.FILL_HORIZONTAL); + int listHeight = 10 * fHoverList.getItemHeight(); + gd.heightHint = listHeight; fHoverList.setLayoutData(gd); fHoverList.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { handleHoverListSelection(); } + public void widgetDefaultSelected(SelectionEvent e) { } }); - - Composite stylesComposite= new Composite(hoverComposite, SWT.NONE); - layout= new GridLayout(); - layout.marginHeight= 0; - layout.marginWidth= 0; - layout.numColumns= 2; + Composite stylesComposite = new Composite(hoverComposite, SWT.NONE); + layout = new GridLayout(); + layout.marginHeight = 0; + layout.marginWidth = 0; + layout.numColumns = 2; stylesComposite.setLayout(layout); - gd= new GridData(GridData.FILL_HORIZONTAL); - gd.heightHint= listHeight + (2 * fHoverList.getBorderWidth()); + gd = new GridData(GridData.FILL_HORIZONTAL); + gd.heightHint = listHeight + (2 * fHoverList.getBorderWidth()); stylesComposite.setLayoutData(gd); - // Enabled checkbox - fEnableField= new Button(stylesComposite, SWT.CHECK); - fEnableField.setText(PreferencesMessages.getString("JavaEditorHoverConfigurationBlock.enabled")); //$NON-NLS-1$ - gd= new GridData(GridData.FILL_HORIZONTAL); - gd.horizontalAlignment= GridData.BEGINNING; - gd.horizontalSpan= 2; + // Enabled checkbox + fEnableField = new Button(stylesComposite, SWT.CHECK); + fEnableField.setText(PreferencesMessages + .getString("JavaEditorHoverConfigurationBlock.enabled")); //$NON-NLS-1$ + gd = new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalAlignment = GridData.BEGINNING; + gd.horizontalSpan = 2; fEnableField.setLayoutData(gd); fEnableField.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { - int i= fHoverList.getSelectionIndex(); - boolean state= fEnableField.getSelection(); + int i = fHoverList.getSelectionIndex(); + boolean state = fEnableField.getSelection(); fModifierEditor.setEnabled(state); - fHoverConfigs[i].fIsEnabled= state; + fHoverConfigs[i].fIsEnabled = state; handleModifierModified(); } + public void widgetDefaultSelected(SelectionEvent e) { } }); // Text field for modifier string - label= new Label(stylesComposite, SWT.LEFT); - label.setText(PreferencesMessages.getString("JavaEditorHoverConfigurationBlock.keyModifier")); //$NON-NLS-1$ - fModifierEditor= new Text(stylesComposite, SWT.BORDER); - gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); + label = new Label(stylesComposite, SWT.LEFT); + label.setText(PreferencesMessages + .getString("JavaEditorHoverConfigurationBlock.keyModifier")); //$NON-NLS-1$ + fModifierEditor = new Text(stylesComposite, SWT.BORDER); + gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); fModifierEditor.setLayoutData(gd); fModifierEditor.addKeyListener(new KeyListener() { private boolean isModifierCandidate; + public void keyPressed(KeyEvent e) { - isModifierCandidate= e.keyCode > 0 && e.character == 0 && e.stateMask == 0; + isModifierCandidate = e.keyCode > 0 && e.character == 0 + && e.stateMask == 0; } - + public void keyReleased(KeyEvent e) { - if (isModifierCandidate && e.stateMask > 0 && e.stateMask == e.stateMask && e.character == 0) {// && e.time -time < 1000) { - String text= fModifierEditor.getText(); - Point selection= fModifierEditor.getSelection(); - int i= selection.x - 1; + if (isModifierCandidate && e.stateMask > 0 + && e.stateMask == e.stateMask && e.character == 0) {// && + // e.time + // -time + // < + // 1000) + // { + String text = fModifierEditor.getText(); + Point selection = fModifierEditor.getSelection(); + int i = selection.x - 1; while (i > -1 && Character.isWhitespace(text.charAt(i))) { i--; } - boolean needsPrefixDelimiter= i > -1 && !String.valueOf(text.charAt(i)).equals(DELIMITER); + boolean needsPrefixDelimiter = i > -1 + && !String.valueOf(text.charAt(i)) + .equals(DELIMITER); - i= selection.y; - while (i < text.length() && Character.isWhitespace(text.charAt(i))) { + i = selection.y; + while (i < text.length() + && Character.isWhitespace(text.charAt(i))) { i++; } - boolean needsPostfixDelimiter= i < text.length() && !String.valueOf(text.charAt(i)).equals(DELIMITER); + boolean needsPostfixDelimiter = i < text.length() + && !String.valueOf(text.charAt(i)) + .equals(DELIMITER); String insertString; if (needsPrefixDelimiter && needsPostfixDelimiter) - insertString= PreferencesMessages.getFormattedString("JavaEditorHoverConfigurationBlock.insertDelimiterAndModifierAndDelimiter", new String[] {Action.findModifierString(e.stateMask)}); //$NON-NLS-1$ + insertString = PreferencesMessages + .getFormattedString( + "JavaEditorHoverConfigurationBlock.insertDelimiterAndModifierAndDelimiter", new String[] { Action.findModifierString(e.stateMask) }); //$NON-NLS-1$ else if (needsPrefixDelimiter) - insertString= PreferencesMessages.getFormattedString("JavaEditorHoverConfigurationBlock.insertDelimiterAndModifier", new String[] {Action.findModifierString(e.stateMask)}); //$NON-NLS-1$ + insertString = PreferencesMessages + .getFormattedString( + "JavaEditorHoverConfigurationBlock.insertDelimiterAndModifier", new String[] { Action.findModifierString(e.stateMask) }); //$NON-NLS-1$ else if (needsPostfixDelimiter) - insertString= PreferencesMessages.getFormattedString("JavaEditorHoverConfigurationBlock.insertModifierAndDelimiter", new String[] {Action.findModifierString(e.stateMask)}); //$NON-NLS-1$ + insertString = PreferencesMessages + .getFormattedString( + "JavaEditorHoverConfigurationBlock.insertModifierAndDelimiter", new String[] { Action.findModifierString(e.stateMask) }); //$NON-NLS-1$ else - insertString= Action.findModifierString(e.stateMask); + insertString = Action.findModifierString(e.stateMask); if (insertString != null) fModifierEditor.insert(insertString); @@ -204,28 +242,31 @@ class JavaEditorHoverConfigurationBlock { }); // Description - Label descriptionLabel= new Label(stylesComposite, SWT.LEFT); - descriptionLabel.setText(PreferencesMessages.getString("JavaEditorHoverConfigurationBlock.description")); //$NON-NLS-1$ - gd= new GridData(GridData.VERTICAL_ALIGN_BEGINNING); - gd.horizontalSpan= 2; + Label descriptionLabel = new Label(stylesComposite, SWT.LEFT); + descriptionLabel.setText(PreferencesMessages + .getString("JavaEditorHoverConfigurationBlock.description")); //$NON-NLS-1$ + gd = new GridData(GridData.VERTICAL_ALIGN_BEGINNING); + gd.horizontalSpan = 2; descriptionLabel.setLayoutData(gd); - fDescription= new Text(stylesComposite, SWT.LEFT | SWT.WRAP | SWT.MULTI | SWT.READ_ONLY | SWT.BORDER); - gd= new GridData(GridData.FILL_BOTH); - gd.horizontalSpan= 2; + fDescription = new Text(stylesComposite, SWT.LEFT | SWT.WRAP + | SWT.MULTI | SWT.READ_ONLY | SWT.BORDER); + gd = new GridData(GridData.FILL_BOTH); + gd.horizontalSpan = 2; fDescription.setLayoutData(gd); // Vertical filler - Label filler= new Label(hoverComposite, SWT.LEFT); - gd= new GridData(GridData.BEGINNING | GridData.VERTICAL_ALIGN_FILL); - gd.heightHint= pixelConverter.convertHeightInCharsToPixels(1) / 3; + Label filler = new Label(hoverComposite, SWT.LEFT); + gd = new GridData(GridData.BEGINNING | GridData.VERTICAL_ALIGN_FILL); + gd.heightHint = pixelConverter.convertHeightInCharsToPixels(1) / 3; filler.setLayoutData(gd); // Affordance checkbox - fShowHoverAffordanceCheckbox= new Button(hoverComposite, SWT.CHECK); - fShowHoverAffordanceCheckbox.setText(PreferencesMessages.getString("JavaEditorHoverConfigurationBlock.showAffordance")); //$NON-NLS-1$ - gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - gd.horizontalIndent= 0; - gd.horizontalSpan= 2; + fShowHoverAffordanceCheckbox = new Button(hoverComposite, SWT.CHECK); + fShowHoverAffordanceCheckbox.setText(PreferencesMessages + .getString("JavaEditorHoverConfigurationBlock.showAffordance")); //$NON-NLS-1$ + gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.horizontalIndent = 0; + gd.horizontalSpan = 2; fShowHoverAffordanceCheckbox.setLayoutData(gd); initialize(); @@ -235,14 +276,17 @@ class JavaEditorHoverConfigurationBlock { } private JavaEditorTextHoverDescriptor[] getContributedHovers() { - return PHPeclipsePlugin.getDefault().getJavaEditorTextHoverDescriptors(); + return PHPeclipsePlugin.getDefault() + .getJavaEditorTextHoverDescriptors(); } void initialize() { - JavaEditorTextHoverDescriptor[] hoverDescs= getContributedHovers(); - fHoverConfigs= new HoverConfig[hoverDescs.length]; - for (int i= 0; i < hoverDescs.length; i++) { - fHoverConfigs[i]= new HoverConfig(hoverDescs[i].getModifierString(), hoverDescs[i].getStateMask(), hoverDescs[i].isEnabled()); + JavaEditorTextHoverDescriptor[] hoverDescs = getContributedHovers(); + fHoverConfigs = new HoverConfig[hoverDescs.length]; + for (int i = 0; i < hoverDescs.length; i++) { + fHoverConfigs[i] = new HoverConfig(hoverDescs[i] + .getModifierString(), hoverDescs[i].getStateMask(), + hoverDescs[i].isEnabled()); fHoverList.add(hoverDescs[i].getLabel()); } initializeFields(); @@ -257,33 +301,38 @@ class JavaEditorHoverConfigurationBlock { } } }); - fShowHoverAffordanceCheckbox.setSelection(fStore.getBoolean(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE)); + fShowHoverAffordanceCheckbox + .setSelection(fStore + .getBoolean(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE)); } void performOk() { - StringBuffer buf= new StringBuffer(); - StringBuffer maskBuf= new StringBuffer(); - for (int i= 0; i < fHoverConfigs.length; i++) { + StringBuffer buf = new StringBuffer(); + StringBuffer maskBuf = new StringBuffer(); + for (int i = 0; i < fHoverConfigs.length; i++) { buf.append(getContributedHovers()[i].getId()); buf.append(JavaEditorTextHoverDescriptor.VALUE_SEPARATOR); if (!fHoverConfigs[i].fIsEnabled) buf.append(JavaEditorTextHoverDescriptor.DISABLED_TAG); - String modifier= fHoverConfigs[i].fModifierString; + String modifier = fHoverConfigs[i].fModifierString; if (modifier == null || modifier.length() == 0) - modifier= JavaEditorTextHoverDescriptor.NO_MODIFIER; + modifier = JavaEditorTextHoverDescriptor.NO_MODIFIER; buf.append(modifier); buf.append(JavaEditorTextHoverDescriptor.VALUE_SEPARATOR); - + maskBuf.append(getContributedHovers()[i].getId()); maskBuf.append(JavaEditorTextHoverDescriptor.VALUE_SEPARATOR); maskBuf.append(fHoverConfigs[i].fStateMask); maskBuf.append(JavaEditorTextHoverDescriptor.VALUE_SEPARATOR); } - fStore.setValue(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS, buf.toString()); - fStore.setValue(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS, maskBuf.toString()); - - fStore.setValue(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE, fShowHoverAffordanceCheckbox.getSelection()); - + fStore.setValue(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS, buf + .toString()); + fStore.setValue(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS, + maskBuf.toString()); + + fStore.setValue(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE, + fShowHoverAffordanceCheckbox.getSelection()); + PHPeclipsePlugin.getDefault().resetJavaEditorTextHoverDescriptors(); } @@ -294,99 +343,126 @@ class JavaEditorHoverConfigurationBlock { private void restoreFromPreferences() { - fShowHoverAffordanceCheckbox.setSelection(fStore.getBoolean(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE)); + fShowHoverAffordanceCheckbox + .setSelection(fStore + .getBoolean(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE)); - String compiledTextHoverModifiers= fStore.getString(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS); - - StringTokenizer tokenizer= new StringTokenizer(compiledTextHoverModifiers, JavaEditorTextHoverDescriptor.VALUE_SEPARATOR); - HashMap idToModifier= new HashMap(tokenizer.countTokens() / 2); + String compiledTextHoverModifiers = fStore + .getString(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS); + + StringTokenizer tokenizer = new StringTokenizer( + compiledTextHoverModifiers, + JavaEditorTextHoverDescriptor.VALUE_SEPARATOR); + HashMap idToModifier = new HashMap(tokenizer.countTokens() / 2); while (tokenizer.hasMoreTokens()) { - String id= tokenizer.nextToken(); + String id = tokenizer.nextToken(); if (tokenizer.hasMoreTokens()) idToModifier.put(id, tokenizer.nextToken()); } - String compiledTextHoverModifierMasks= PHPeclipsePlugin.getDefault().getPreferenceStore().getString(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS); + String compiledTextHoverModifierMasks = PHPeclipsePlugin.getDefault() + .getPreferenceStore().getString( + PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS); - tokenizer= new StringTokenizer(compiledTextHoverModifierMasks, JavaEditorTextHoverDescriptor.VALUE_SEPARATOR); - HashMap idToModifierMask= new HashMap(tokenizer.countTokens() / 2); + tokenizer = new StringTokenizer(compiledTextHoverModifierMasks, + JavaEditorTextHoverDescriptor.VALUE_SEPARATOR); + HashMap idToModifierMask = new HashMap(tokenizer.countTokens() / 2); while (tokenizer.hasMoreTokens()) { - String id= tokenizer.nextToken(); + String id = tokenizer.nextToken(); if (tokenizer.hasMoreTokens()) idToModifierMask.put(id, tokenizer.nextToken()); } - for (int i= 0; i < fHoverConfigs.length; i++) { - String modifierString= (String)idToModifier.get(getContributedHovers()[i].getId()); - boolean enabled= true; + for (int i = 0; i < fHoverConfigs.length; i++) { + String modifierString = (String) idToModifier + .get(getContributedHovers()[i].getId()); + boolean enabled = true; if (modifierString == null) - modifierString= JavaEditorTextHoverDescriptor.DISABLED_TAG; - - if (modifierString.startsWith(JavaEditorTextHoverDescriptor.DISABLED_TAG)) { - enabled= false; - modifierString= modifierString.substring(1); + modifierString = JavaEditorTextHoverDescriptor.DISABLED_TAG; + + if (modifierString + .startsWith(JavaEditorTextHoverDescriptor.DISABLED_TAG)) { + enabled = false; + modifierString = modifierString.substring(1); } - if (modifierString.equals(JavaEditorTextHoverDescriptor.NO_MODIFIER)) - modifierString= ""; //$NON-NLS-1$ + if (modifierString + .equals(JavaEditorTextHoverDescriptor.NO_MODIFIER)) + modifierString = ""; //$NON-NLS-1$ - fHoverConfigs[i].fModifierString= modifierString; - fHoverConfigs[i].fIsEnabled= enabled; - fHoverConfigs[i].fStateMask= JavaEditorTextHoverDescriptor.computeStateMask(modifierString); + fHoverConfigs[i].fModifierString = modifierString; + fHoverConfigs[i].fIsEnabled = enabled; + fHoverConfigs[i].fStateMask = JavaEditorTextHoverDescriptor + .computeStateMask(modifierString); if (fHoverConfigs[i].fStateMask == -1) { try { - fHoverConfigs[i].fStateMask= Integer.parseInt((String)idToModifierMask.get(getContributedHovers()[i].getId())); + fHoverConfigs[i].fStateMask = Integer + .parseInt((String) idToModifierMask + .get(getContributedHovers()[i].getId())); } catch (NumberFormatException ex) { - fHoverConfigs[i].fStateMask= -1; + fHoverConfigs[i].fStateMask = -1; } } } } private void handleModifierModified() { - int i= fHoverList.getSelectionIndex(); - String modifiers= fModifierEditor.getText(); - fHoverConfigs[i].fModifierString= modifiers; - fHoverConfigs[i].fStateMask= JavaEditorTextHoverDescriptor.computeStateMask(modifiers); + int i = fHoverList.getSelectionIndex(); + String modifiers = fModifierEditor.getText(); + fHoverConfigs[i].fModifierString = modifiers; + fHoverConfigs[i].fStateMask = JavaEditorTextHoverDescriptor + .computeStateMask(modifiers); if (fHoverConfigs[i].fIsEnabled && fHoverConfigs[i].fStateMask == -1) - fStatus= new StatusInfo(IStatus.ERROR, PreferencesMessages.getFormattedString("JavaEditorHoverConfigurationBlock.modifierIsNotValid", fHoverConfigs[i].fModifierString)); //$NON-NLS-1$ + fStatus = new StatusInfo( + IStatus.ERROR, + PreferencesMessages + .getFormattedString( + "JavaEditorHoverConfigurationBlock.modifierIsNotValid", fHoverConfigs[i].fModifierString)); //$NON-NLS-1$ else - fStatus= new StatusInfo(); + fStatus = new StatusInfo(); updateStatus(); } - private void handleHoverListSelection() { - int i= fHoverList.getSelectionIndex(); - boolean enabled= fHoverConfigs[i].fIsEnabled; + private void handleHoverListSelection() { + int i = fHoverList.getSelectionIndex(); + boolean enabled = fHoverConfigs[i].fIsEnabled; fEnableField.setSelection(enabled); fModifierEditor.setEnabled(enabled); fModifierEditor.setText(fHoverConfigs[i].fModifierString); - String description= getContributedHovers()[i].getDescription(); + String description = getContributedHovers()[i].getDescription(); if (description == null) - description= ""; //$NON-NLS-1$ + description = ""; //$NON-NLS-1$ fDescription.setText(description); } IStatus getStatus() { if (fStatus == null) - fStatus= new StatusInfo(); + fStatus = new StatusInfo(); return fStatus; } private void updateStatus() { - int i= 0; - HashMap stateMasks= new HashMap(fHoverConfigs.length); + int i = 0; + HashMap stateMasks = new HashMap(fHoverConfigs.length); while (fStatus.isOK() && i < fHoverConfigs.length) { if (fHoverConfigs[i].fIsEnabled) { - String label= getContributedHovers()[i].getLabel(); - Integer stateMask= new Integer(fHoverConfigs[i].fStateMask); + String label = getContributedHovers()[i].getLabel(); + Integer stateMask = new Integer(fHoverConfigs[i].fStateMask); if (fHoverConfigs[i].fStateMask == -1) - fStatus= new StatusInfo(IStatus.ERROR, PreferencesMessages.getFormattedString("JavaEditorHoverConfigurationBlock.modifierIsNotValidForHover", new String[] {fHoverConfigs[i].fModifierString, label})); //$NON-NLS-1$ + fStatus = new StatusInfo( + IStatus.ERROR, + PreferencesMessages + .getFormattedString( + "JavaEditorHoverConfigurationBlock.modifierIsNotValidForHover", new String[] { fHoverConfigs[i].fModifierString, label })); //$NON-NLS-1$ else if (stateMasks.containsKey(stateMask)) - fStatus= new StatusInfo(IStatus.ERROR, PreferencesMessages.getFormattedString("JavaEditorHoverConfigurationBlock.duplicateModifier", new String[] {label, (String)stateMasks.get(stateMask)})); //$NON-NLS-1$ + fStatus = new StatusInfo( + IStatus.ERROR, + PreferencesMessages + .getFormattedString( + "JavaEditorHoverConfigurationBlock.duplicateModifier", new String[] { label, (String) stateMasks.get(stateMask) })); //$NON-NLS-1$ else stateMasks.put(stateMask, label); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaEditorPreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaEditorPreferencePage.java index be4add7..bfe24b5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaEditorPreferencePage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaEditorPreferencePage.java @@ -85,1602 +85,1963 @@ import org.eclipse.ui.texteditor.MarkerAnnotationPreferences; /** * The page for setting the editor options. */ -public class JavaEditorPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { - private static final String BOLD = PreferenceConstants.EDITOR_BOLD_SUFFIX; - - private static final String COMPILER_TASK_TAGS = JavaCore.COMPILER_TASK_TAGS; - - private static final String DELIMITER = PreferencesMessages.getString("JavaEditorPreferencePage.navigation.delimiter"); //$NON-NLS-1$ - - /** The keys of the overlay store. */ - public final OverlayPreferenceStore.OverlayKey[] fKeys; - - private final String[][] fSyntaxColorListModel = new String[][] { - { - PreferencesMessages.getString("JavaEditorPreferencePage.multiLineComment"), - PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR }, - //$NON-NLS-1$ - { - PreferencesMessages.getString("JavaEditorPreferencePage.singleLineComment"), - PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR }, - //$NON-NLS-1$ - { PreferencesMessages.getString("JavaEditorPreferencePage.tags"), PreferenceConstants.EDITOR_PHP_TAG_COLOR }, - //$NON-NLS-1$ - { PreferencesMessages.getString("JavaEditorPreferencePage.keywords"), PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR }, - { PreferencesMessages.getString("JavaEditorPreferencePage.functionNames"), PreferenceConstants.EDITOR_PHP_FUNCTIONNAME_COLOR }, - //$NON-NLS-1$ - { PreferencesMessages.getString("JavaEditorPreferencePage.variables"), PreferenceConstants.EDITOR_PHP_VARIABLE_COLOR }, - //$NON-NLS-1$ - { PreferencesMessages.getString("JavaEditorPreferencePage.variables_dollar"), PreferenceConstants.EDITOR_PHP_VARIABLE_DOLLAR_COLOR }, - //$NON-NLS-1$ - { PreferencesMessages.getString("JavaEditorPreferencePage.constants"), PreferenceConstants.EDITOR_PHP_CONSTANT_COLOR }, - //$NON-NLS-1$ - { PreferencesMessages.getString("JavaEditorPreferencePage.types"), PreferenceConstants.EDITOR_PHP_TYPE_COLOR }, - //$NON-NLS-1$ - { PreferencesMessages.getString("JavaEditorPreferencePage.strings_dq"), PreferenceConstants.EDITOR_STRING_COLOR_DQ }, - { PreferencesMessages.getString("JavaEditorPreferencePage.strings_sq"), PreferenceConstants.EDITOR_STRING_COLOR_SQ }, - //$NON-NLS-1$ - { PreferencesMessages.getString("JavaEditorPreferencePage.others"), PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR }, //$NON-NLS-1$ - { PreferencesMessages.getString("JavaEditorPreferencePage.operators"), PreferenceConstants.EDITOR_PHP_OPERATOR_COLOR }, - //$NON-NLS-1$ - { - PreferencesMessages.getString("JavaEditorPreferencePage.returnKeyword"), - PreferenceConstants.EDITOR_PHP_KEYWORD_RETURN_COLOR }, - { PreferencesMessages.getString("JavaEditorPreferencePage.braces"), PreferenceConstants.EDITOR_PHP_BRACE_OPERATOR_COLOR }, - //$NON-NLS-1$ - { PreferencesMessages.getString("JavaEditorPreferencePage.phpDocKeywords"), PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR }, - //$NON-NLS-1$ - { PreferencesMessages.getString("JavaEditorPreferencePage.phpDocHtmlTags"), PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR }, - //$NON-NLS-1$ - { PreferencesMessages.getString("JavaEditorPreferencePage.phpDocLinks"), PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR }, - //$NON-NLS-1$ - { PreferencesMessages.getString("JavaEditorPreferencePage.phpDocOthers"), PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR } //$NON-NLS-1$ - }; - - private final String[][] fAppearanceColorListModel = new String[][] { - { - PreferencesMessages.getString("JavaEditorPreferencePage.lineNumberForegroundColor"), - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR }, - //$NON-NLS-1$ - { - PreferencesMessages.getString("JavaEditorPreferencePage.matchingBracketsHighlightColor2"), - PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR }, - //$NON-NLS-1$ - { - PreferencesMessages.getString("JavaEditorPreferencePage.currentLineHighlighColor"), - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE_COLOR }, - //$NON-NLS-1$ - { - PreferencesMessages.getString("JavaEditorPreferencePage.printMarginColor2"), - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR }, - //$NON-NLS-1$ - { PreferencesMessages.getString("JavaEditorPreferencePage.findScopeColor2"), PreferenceConstants.EDITOR_FIND_SCOPE_COLOR }, - //$NON-NLS-1$ - { PreferencesMessages.getString("JavaEditorPreferencePage.linkColor2"), PreferenceConstants.EDITOR_LINK_COLOR }, //$NON-NLS-1$ - }; - - // private final String[][] fAnnotationColorListModel; - - // private final String[][] fAnnotationDecorationListModel = new String[][]{ - // { - // PreferencesMessages - // .getString("JavaEditorPreferencePage.AnnotationDecoration.NONE"), - // AnnotationPreference.STYLE_NONE}, - // //$NON-NLS-1$ - // { - // PreferencesMessages - // .getString("JavaEditorPreferencePage.AnnotationDecoration.SQUIGGLIES"), - // AnnotationPreference.STYLE_SQUIGGLIES}, - // //$NON-NLS-1$ - // { - // PreferencesMessages - // .getString("JavaEditorPreferencePage.AnnotationDecoration.UNDERLINE"), - // AnnotationPreference.STYLE_UNDERLINE}, - // //$NON-NLS-1$ - // { - // PreferencesMessages - // .getString("JavaEditorPreferencePage.AnnotationDecoration.BOX"), - // AnnotationPreference.STYLE_BOX}, - // //$NON-NLS-1$ - // { - // PreferencesMessages - // .getString("JavaEditorPreferencePage.AnnotationDecoration.IBEAM"), - // AnnotationPreference.STYLE_IBEAM} //$NON-NLS-1$ - // }; - private OverlayPreferenceStore fOverlayStore; - - private JavaTextTools fJavaTextTools; - - private JavaEditorHoverConfigurationBlock fJavaEditorHoverConfigurationBlock; - - private FoldingConfigurationBlock fFoldingConfigurationBlock; - - private Map fColorButtons = new HashMap(); - - 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()); - } - }; - - private Map fTextFields = new HashMap(); - - private ModifyListener fTextFieldListener = new ModifyListener() { - public void modifyText(ModifyEvent e) { - Text text = (Text) e.widget; - fOverlayStore.setValue((String) fTextFields.get(text), text.getText()); - } - }; - - private ArrayList fNumberFields = new ArrayList(); - - private ModifyListener fNumberFieldListener = new ModifyListener() { - public void modifyText(ModifyEvent e) { - numberFieldChanged((Text) e.widget); - } - }; - - private List fSyntaxColorList; - - private List fAppearanceColorList; - - // private List fContentAssistColorList; - private List fAnnotationList; - - private ColorEditor fSyntaxForegroundColorEditor; - - private ColorEditor fAppearanceColorEditor; - - private ColorEditor fAnnotationForegroundColorEditor; - - private ColorEditor fContentAssistColorEditor; - - private ColorEditor fBackgroundColorEditor; - - private Button fBackgroundDefaultRadioButton; - - private Button fBackgroundCustomRadioButton; - - private Button fBackgroundColorButton; - - private Button fBoldCheckBox; - - // private Button fAddJavaDocTagsButton; - - private Button fEscapeStringsButtonDQ; - - private Button fEscapeStringsButtonSQ; - - // private Button fGuessMethodArgumentsButton; - private SourceViewer fPreviewViewer; - - private Color fBackgroundColor; - - private Control fAutoInsertDelayText; - - private Control fAutoInsertJavaTriggerText; - - private Control fAutoInsertJavaDocTriggerText; - - private Label fAutoInsertDelayLabel; - - private Label fAutoInsertJavaTriggerLabel; - - private Label fAutoInsertJavaDocTriggerLabel; - - private Button fShowInTextCheckBox; - - private Combo fDecorationStyleCombo; - - private Button fHighlightInTextCheckBox; - - private Button fShowInOverviewRulerCheckBox; - - private Button fShowInVerticalRulerCheckBox; - - private Text fBrowserLikeLinksKeyModifierText; - - private Button fBrowserLikeLinksCheckBox; - - private StatusInfo fBrowserLikeLinksKeyModifierStatus; - - // private Button fCompletionInsertsRadioButton; - // private Button fCompletionOverwritesRadioButton; - // private Button fStickyOccurrencesButton; - /** - * Creates a new preference page. - */ - public JavaEditorPreferencePage() { - setDescription(PreferencesMessages.getString("JavaEditorPreferencePage.description")); //$NON-NLS-1$ - setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); - MarkerAnnotationPreferences markerAnnotationPreferences = new MarkerAnnotationPreferences(); - fKeys = createOverlayStoreKeys(markerAnnotationPreferences); - fOverlayStore = new OverlayPreferenceStore(getPreferenceStore(), fKeys); - // fAnnotationColorListModel = - // createAnnotationTypeListModel(markerAnnotationPreferences); - } - - private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys(MarkerAnnotationPreferences preferences) { - ArrayList overlayKeys = new ArrayList(); - Iterator e = preferences.getAnnotationPreferences().iterator(); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_FOREGROUND_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_BACKGROUND_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, PreferenceConstants.EDITOR_TAB_WIDTH)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_JAVA_KEYWORD_BOLD)); - - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_PHP_TAG_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_PHP_TAG_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_PHP_FUNCTIONNAME_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_PHP_FUNCTIONNAME_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_PHP_VARIABLE_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_PHP_VARIABLE_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_PHP_VARIABLE_DOLLAR_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_PHP_VARIABLE_DOLLAR_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_PHP_CONSTANT_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_PHP_CONSTANT_BOLD)); - overlayKeys - .add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_PHP_TYPE_COLOR)); - overlayKeys - .add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_PHP_TYPE_BOLD)); - - overlayKeys - .add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_STRING_COLOR_DQ)); - overlayKeys - .add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_STRING_BOLD_DQ)); - overlayKeys - .add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_STRING_COLOR_SQ)); - overlayKeys - .add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_STRING_BOLD_SQ)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_JAVA_DEFAULT_BOLD)); - overlayKeys - .add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_TASK_TAG_COLOR)); - overlayKeys - .add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_TASK_TAG_BOLD)); - // overlayKeys.add(new - // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING_DQ, - // PreferenceConstants.EDITOR_JAVA_METHOD_NAME_COLOR)); - // overlayKeys.add(new - // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - // PreferenceConstants.EDITOR_JAVA_METHOD_NAME_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_PHP_OPERATOR_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_PHP_OPERATOR_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_PHP_KEYWORD_RETURN_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_PHP_KEYWORD_RETURN_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_PHP_BRACE_OPERATOR_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_PHP_BRACE_OPERATOR_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_JAVADOC_KEYWORD_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_JAVADOC_TAG_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_JAVADOC_LINKS_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_JAVADOC_DEFAULT_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_MATCHING_BRACKETS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN)); - // overlayKeys.add(new - // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - // PreferenceConstants.EDITOR_MARK_OCCURRENCES)); - // overlayKeys.add(new - // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - // PreferenceConstants.EDITOR_STICKY_OCCURRENCES)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_FIND_SCOPE_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_LINK_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_CORRECTION_INDICATION)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_OVERVIEW_RULER)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_SPACES_FOR_TABS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.CODEASSIST_AUTOACTIVATION)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, - PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY)); - overlayKeys - .add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_AUTOINSERT)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.CODEASSIST_ORDER_PROPOSALS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.CODEASSIST_CASE_SENSITIVITY)); - overlayKeys - .add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_ADDIMPORT)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.CODEASSIST_INSERT_COMPLETION)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_PASTE)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_CLOSE_STRINGS_DQ_PHP)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_CLOSE_STRINGS_SQ_PHP)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP)); - // overlayKeys - // .add(new OverlayPreferenceStore.OverlayKey( - // OverlayPreferenceStore.BOOLEAN, - // PreferenceConstants.EDITOR_CLOSE_BRACES)); - overlayKeys - .add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_JAVADOCS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_WRAP_WORDS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_WRAP_STRINGS_DQ)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_ESCAPE_STRINGS_DQ)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_WRAP_STRINGS_SQ)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_ESCAPE_STRINGS_SQ)); - - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_FORMAT_JAVADOCS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_P_RTRIM_ON_SAVE)); - - overlayKeys - .add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_HOME_END)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE)); - // overlayKeys.add(new - // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - // PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK)); - while (e.hasNext()) { - AnnotationPreference info = (AnnotationPreference) e.next(); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, info.getColorPreferenceKey())); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, info.getTextPreferenceKey())); - if (info.getHighlightPreferenceKey() != null) - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, info.getHighlightPreferenceKey())); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, info.getOverviewRulerPreferenceKey())); - if (info.getVerticalRulerPreferenceKey() != null) - overlayKeys - .add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, info.getVerticalRulerPreferenceKey())); - if (info.getTextStylePreferenceKey() != null) - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, info.getTextStylePreferenceKey())); - } - OverlayPreferenceStore.OverlayKey[] keys = new OverlayPreferenceStore.OverlayKey[overlayKeys.size()]; - overlayKeys.toArray(keys); - return keys; - } /* - * @see IWorkbenchPreferencePage#init() - */ - - public void init(IWorkbench workbench) { - } - - /* - * @see PreferencePage#createControl(Composite) - */ - public void createControl(Composite parent) { - super.createControl(parent); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE); - } - - private void handleSyntaxColorListSelection() { - int i = fSyntaxColorList.getSelectionIndex(); - String key = fSyntaxColorListModel[i][1]; - RGB rgb = PreferenceConverter.getColor(fOverlayStore, key); - fSyntaxForegroundColorEditor.setColorValue(rgb); - fBoldCheckBox.setSelection(fOverlayStore.getBoolean(key + BOLD)); - } - - private void handleAppearanceColorListSelection() { - int i = fAppearanceColorList.getSelectionIndex(); - String key = fAppearanceColorListModel[i][1]; - RGB rgb = PreferenceConverter.getColor(fOverlayStore, key); - fAppearanceColorEditor.setColorValue(rgb); - } - - // private void handleAnnotationListSelection() { - // int i = fAnnotationList.getSelectionIndex(); - // String key = fAnnotationColorListModel[i][1]; - // RGB rgb = PreferenceConverter.getColor(fOverlayStore, key); - // fAnnotationForegroundColorEditor.setColorValue(rgb); - // key = fAnnotationColorListModel[i][2]; - // boolean showInText = fOverlayStore.getBoolean(key); - // fShowInTextCheckBox.setSelection(showInText); - // key = fAnnotationColorListModel[i][6]; - // if (key != null) { - // fDecorationStyleCombo.setEnabled(showInText); - // for (int j = 0; j < fAnnotationDecorationListModel.length; j++) { - // String value = fOverlayStore.getString(key); - // if (fAnnotationDecorationListModel[j][1].equals(value)) { - // fDecorationStyleCombo.setText(fAnnotationDecorationListModel[j][0]); - // break; - // } - // } - // } else { - // fDecorationStyleCombo.setEnabled(false); - // fDecorationStyleCombo.setText(fAnnotationDecorationListModel[1][0]); // set - // // selection - // // to - // // squigglies - // // if - // // the - // // key - // // is - // // not - // // there - // // (legacy - // // support) - // } - // key = fAnnotationColorListModel[i][3]; - // fShowInOverviewRulerCheckBox.setSelection(fOverlayStore.getBoolean(key)); - // key = fAnnotationColorListModel[i][4]; - // if (key != null) { - // fHighlightInTextCheckBox.setSelection(fOverlayStore.getBoolean(key)); - // fHighlightInTextCheckBox.setEnabled(true); - // } else - // fHighlightInTextCheckBox.setEnabled(false); - // key = fAnnotationColorListModel[i][5]; - // if (key != null) { - // fShowInVerticalRulerCheckBox.setSelection(fOverlayStore.getBoolean(key)); - // fShowInVerticalRulerCheckBox.setEnabled(true); - // } else { - // fShowInVerticalRulerCheckBox.setSelection(true); - // fShowInVerticalRulerCheckBox.setEnabled(false); - // } - // } - private Control createSyntaxPage(Composite parent) { - Composite colorComposite = new Composite(parent, SWT.NULL); - colorComposite.setLayout(new GridLayout()); - Group backgroundComposite = new Group(colorComposite, SWT.SHADOW_ETCHED_IN); - backgroundComposite.setLayout(new RowLayout()); - backgroundComposite.setText(PreferencesMessages.getString("JavaEditorPreferencePage.backgroundColor"));//$NON-NLS-1$ - SelectionListener backgroundSelectionListener = new SelectionListener() { - public void widgetSelected(SelectionEvent e) { - boolean custom = fBackgroundCustomRadioButton.getSelection(); - fBackgroundColorButton.setEnabled(custom); - fOverlayStore.setValue(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR, !custom); - } - - public void widgetDefaultSelected(SelectionEvent e) { - } - }; - fBackgroundDefaultRadioButton = new Button(backgroundComposite, SWT.RADIO | SWT.LEFT); - fBackgroundDefaultRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.systemDefault")); //$NON-NLS-1$ - fBackgroundDefaultRadioButton.addSelectionListener(backgroundSelectionListener); - fBackgroundCustomRadioButton = new Button(backgroundComposite, SWT.RADIO | SWT.LEFT); - fBackgroundCustomRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.custom")); //$NON-NLS-1$ - fBackgroundCustomRadioButton.addSelectionListener(backgroundSelectionListener); - fBackgroundColorEditor = new ColorEditor(backgroundComposite); - fBackgroundColorButton = fBackgroundColorEditor.getButton(); - Label label = new Label(colorComposite, SWT.LEFT); - label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.foreground")); //$NON-NLS-1$ - label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - Composite editorComposite = new Composite(colorComposite, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.numColumns = 2; - layout.marginHeight = 0; - layout.marginWidth = 0; - editorComposite.setLayout(layout); - GridData gd = new GridData(GridData.FILL_BOTH); - editorComposite.setLayoutData(gd); - fSyntaxColorList = new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); - gd = new GridData(GridData.FILL_BOTH); - gd.heightHint = convertHeightInCharsToPixels(5); - fSyntaxColorList.setLayoutData(gd); - Composite stylesComposite = new Composite(editorComposite, SWT.NONE); - layout = new GridLayout(); - layout.marginHeight = 0; - layout.marginWidth = 0; - layout.numColumns = 2; - stylesComposite.setLayout(layout); - stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); - label = new Label(stylesComposite, SWT.LEFT); - label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.color")); //$NON-NLS-1$ - gd = new GridData(); - gd.horizontalAlignment = GridData.BEGINNING; - label.setLayoutData(gd); - fSyntaxForegroundColorEditor = new ColorEditor(stylesComposite); - Button foregroundColorButton = fSyntaxForegroundColorEditor.getButton(); - gd = new GridData(GridData.FILL_HORIZONTAL); - gd.horizontalAlignment = GridData.BEGINNING; - foregroundColorButton.setLayoutData(gd); - fBoldCheckBox = new Button(stylesComposite, SWT.CHECK); - fBoldCheckBox.setText(PreferencesMessages.getString("JavaEditorPreferencePage.bold")); //$NON-NLS-1$ - gd = new GridData(GridData.FILL_HORIZONTAL); - gd.horizontalAlignment = GridData.BEGINNING; - gd.horizontalSpan = 2; - fBoldCheckBox.setLayoutData(gd); - label = new Label(colorComposite, SWT.LEFT); - label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.preview")); //$NON-NLS-1$ - label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - Control previewer = createPreviewer(colorComposite); - gd = new GridData(GridData.FILL_BOTH); - gd.widthHint = convertWidthInCharsToPixels(20); - gd.heightHint = convertHeightInCharsToPixels(5); - previewer.setLayoutData(gd); - fSyntaxColorList.addSelectionListener(new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - // do nothing - } - - public void widgetSelected(SelectionEvent e) { - handleSyntaxColorListSelection(); - } - }); - foregroundColorButton.addSelectionListener(new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - // do nothing - } - - public void widgetSelected(SelectionEvent e) { - int i = fSyntaxColorList.getSelectionIndex(); - String key = fSyntaxColorListModel[i][1]; - PreferenceConverter.setValue(fOverlayStore, key, fSyntaxForegroundColorEditor.getColorValue()); - } - }); - fBackgroundColorButton.addSelectionListener(new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - // do nothing - } - - public void widgetSelected(SelectionEvent e) { - PreferenceConverter.setValue(fOverlayStore, PreferenceConstants.EDITOR_BACKGROUND_COLOR, fBackgroundColorEditor - .getColorValue()); - } - }); - fBoldCheckBox.addSelectionListener(new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - // do nothing - } - - public void widgetSelected(SelectionEvent e) { - int i = fSyntaxColorList.getSelectionIndex(); - String key = fSyntaxColorListModel[i][1]; - fOverlayStore.setValue(key + BOLD, fBoldCheckBox.getSelection()); - } - }); - return colorComposite; - } - - private Control createPreviewer(Composite parent) { - Preferences coreStore = createTemporaryCorePreferenceStore(); - fJavaTextTools = new JavaTextTools(fOverlayStore, coreStore, false); - IPreferenceStore generalTextStore = EditorsUI.getPreferenceStore(); - IPreferenceStore store = new ChainedPreferenceStore(new IPreferenceStore[] { - fOverlayStore, - new PreferencesAdapter(createTemporaryCorePreferenceStore()), - generalTextStore }); - - fPreviewViewer = new JavaSourceViewer(parent, null, null, false, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER, store); - JavaTextTools tools = PHPeclipsePlugin.getDefault().getJavaTextTools(); - PHPSourceViewerConfiguration configuration = new PHPSourceViewerConfiguration(tools.getColorManager(), store, null, - IPHPPartitions.PHP_PARTITIONING); - // PHPSourceViewerConfiguration configuration =new PHPSourceViewerConfiguration(fJavaTextTools, null, - // IPHPPartitions.PHP_PARTITIONING); - fPreviewViewer.configure(configuration); - - Font font = JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT); - fPreviewViewer.getTextWidget().setFont(font); - new JavaSourcePreviewerUpdater(fPreviewViewer, configuration, store); - fPreviewViewer.setEditable(false); - String content = loadPreviewContentFromFile("ColorSettingPreviewCode.txt"); //$NON-NLS-1$ - IDocument document = new Document(content); - fJavaTextTools.setupJavaDocumentPartitioner(document, IPHPPartitions.PHP_PARTITIONING); - fPreviewViewer.setDocument(document); - return fPreviewViewer.getControl(); - } - - private Preferences createTemporaryCorePreferenceStore() { - Preferences result = new Preferences(); - result.setValue(COMPILER_TASK_TAGS, "TASK"); //$NON-NLS-1$ - return result; - } - - private Control createAppearancePage(Composite parent) { - Composite appearanceComposite = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.numColumns = 2; - appearanceComposite.setLayout(layout); - String label = PreferencesMessages.getString("JavaEditorPreferencePage.displayedTabWidth"); //$NON-NLS-1$ - addTextField(appearanceComposite, label, PreferenceConstants.EDITOR_TAB_WIDTH, 3, 0, true); - label = PreferencesMessages.getString("JavaEditorPreferencePage.printMarginColumn"); //$NON-NLS-1$ - addTextField(appearanceComposite, label, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN, 3, 0, true); - label = PreferencesMessages.getString("JavaEditorPreferencePage.showOverviewRuler"); //$NON-NLS-1$ - addCheckBox(appearanceComposite, label, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_OVERVIEW_RULER, 0); - label = PreferencesMessages.getString("JavaEditorPreferencePage.showLineNumbers"); //$NON-NLS-1$ - addCheckBox(appearanceComposite, label, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER, 0); - label = PreferencesMessages.getString("JavaEditorPreferencePage.highlightMatchingBrackets"); //$NON-NLS-1$ - addCheckBox(appearanceComposite, label, PreferenceConstants.EDITOR_MATCHING_BRACKETS, 0); - label = PreferencesMessages.getString("JavaEditorPreferencePage.highlightCurrentLine"); //$NON-NLS-1$ - addCheckBox(appearanceComposite, label, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE, 0); - label = PreferencesMessages.getString("JavaEditorPreferencePage.showPrintMargin"); //$NON-NLS-1$ - addCheckBox(appearanceComposite, label, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN, 0); - label = PreferencesMessages.getString("JavaEditorPreferencePage.markOccurrences"); //$NON-NLS-1$ - // Button master= addCheckBox(appearanceComposite, label, - // PreferenceConstants.EDITOR_MARK_OCCURRENCES, 0); //$NON-NLS-1$ - label = PreferencesMessages.getString("JavaEditorPreferencePage.stickyOccurrences"); //$NON-NLS-1$ - // fStickyOccurrencesButton= addCheckBox(appearanceComposite, label, - // PreferenceConstants.EDITOR_STICKY_OCCURRENCES, 0); //$NON-NLS-1$ - // createDependency(master, fStickyOccurrencesButton); - Label l = new Label(appearanceComposite, SWT.LEFT); - GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - gd.horizontalSpan = 2; - gd.heightHint = convertHeightInCharsToPixels(1) / 2; - l.setLayoutData(gd); - l = new Label(appearanceComposite, SWT.LEFT); - l.setText(PreferencesMessages.getString("JavaEditorPreferencePage.appearanceOptions")); //$NON-NLS-1$ - gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - gd.horizontalSpan = 2; - l.setLayoutData(gd); - Composite editorComposite = new Composite(appearanceComposite, SWT.NONE); - layout = new GridLayout(); - layout.numColumns = 2; - layout.marginHeight = 0; - layout.marginWidth = 0; - editorComposite.setLayout(layout); - gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL); - gd.horizontalSpan = 2; - editorComposite.setLayoutData(gd); - fAppearanceColorList = new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); - gd = new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL); - gd.heightHint = convertHeightInCharsToPixels(8); - fAppearanceColorList.setLayoutData(gd); - Composite stylesComposite = new Composite(editorComposite, SWT.NONE); - layout = new GridLayout(); - layout.marginHeight = 0; - layout.marginWidth = 0; - layout.numColumns = 2; - stylesComposite.setLayout(layout); - stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); - l = new Label(stylesComposite, SWT.LEFT); - l.setText(PreferencesMessages.getString("JavaEditorPreferencePage.color")); //$NON-NLS-1$ - gd = new GridData(); - gd.horizontalAlignment = GridData.BEGINNING; - l.setLayoutData(gd); - fAppearanceColorEditor = new ColorEditor(stylesComposite); - Button foregroundColorButton = fAppearanceColorEditor.getButton(); - gd = new GridData(GridData.FILL_HORIZONTAL); - gd.horizontalAlignment = GridData.BEGINNING; - foregroundColorButton.setLayoutData(gd); - fAppearanceColorList.addSelectionListener(new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - // do nothing - } - - public void widgetSelected(SelectionEvent e) { - handleAppearanceColorListSelection(); - } - }); - foregroundColorButton.addSelectionListener(new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - // do nothing - } - - public void widgetSelected(SelectionEvent e) { - int i = fAppearanceColorList.getSelectionIndex(); - String key = fAppearanceColorListModel[i][1]; - PreferenceConverter.setValue(fOverlayStore, key, fAppearanceColorEditor.getColorValue()); - } - }); - return appearanceComposite; - } - - // private Control createAnnotationsPage(Composite parent) { - // Composite composite = new Composite(parent, SWT.NULL); - // GridLayout layout = new GridLayout(); - // layout.numColumns = 2; - // composite.setLayout(layout); - // String text = PreferencesMessages - // .getString("JavaEditorPreferencePage.analyseAnnotationsWhileTyping"); - // //$NON-NLS-1$ - // addCheckBox(composite, text, - // PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, 0); - // text = PreferencesMessages - // .getString("JavaEditorPreferencePage.showQuickFixables"); //$NON-NLS-1$ - // addCheckBox(composite, text, - // PreferenceConstants.EDITOR_CORRECTION_INDICATION, 0); - // addFiller(composite); - // Label label = new Label(composite, SWT.LEFT); - // label.setText(PreferencesMessages - // .getString("JavaEditorPreferencePage.annotationPresentationOptions")); - // //$NON-NLS-1$ - // GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - // gd.horizontalSpan = 2; - // label.setLayoutData(gd); - // Composite editorComposite = new Composite(composite, SWT.NONE); - // layout = new GridLayout(); - // layout.numColumns = 2; - // layout.marginHeight = 0; - // layout.marginWidth = 0; - // editorComposite.setLayout(layout); - // gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL); - // gd.horizontalSpan = 2; - // editorComposite.setLayoutData(gd); - // fAnnotationList = new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL - // | SWT.BORDER); - // gd = new GridData(GridData.VERTICAL_ALIGN_BEGINNING - // | GridData.FILL_HORIZONTAL); - // gd.heightHint = convertHeightInCharsToPixels(10); - // fAnnotationList.setLayoutData(gd); - // Composite optionsComposite = new Composite(editorComposite, SWT.NONE); - // layout = new GridLayout(); - // layout.marginHeight = 0; - // layout.marginWidth = 0; - // layout.numColumns = 2; - // optionsComposite.setLayout(layout); - // optionsComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); - // fShowInTextCheckBox = new Button(optionsComposite, SWT.CHECK); - // fShowInTextCheckBox.setText(PreferencesMessages - // .getString("JavaEditorPreferencePage.annotations.showInText")); - // //$NON-NLS-1$ - // gd = new GridData(GridData.FILL_HORIZONTAL); - // gd.horizontalAlignment = GridData.BEGINNING; - // gd.horizontalSpan = 2; - // fShowInTextCheckBox.setLayoutData(gd); - // fDecorationStyleCombo = new Combo(optionsComposite, SWT.READ_ONLY); - // for (int i = 0; i < fAnnotationDecorationListModel.length; i++) - // fDecorationStyleCombo.add(fAnnotationDecorationListModel[i][0]); - // gd = new GridData(GridData.FILL_HORIZONTAL); - // gd.horizontalAlignment = GridData.BEGINNING; - // gd.horizontalSpan = 2; - // gd.horizontalIndent = 20; - // fDecorationStyleCombo.setLayoutData(gd); - // fHighlightInTextCheckBox = new Button(optionsComposite, SWT.CHECK); - // fHighlightInTextCheckBox.setText(PreferencesMessages - // .getString("TextEditorPreferencePage.annotations.highlightInText")); - // //$NON-NLS-1$ - // gd = new GridData(GridData.FILL_HORIZONTAL); - // gd.horizontalAlignment = GridData.BEGINNING; - // gd.horizontalSpan = 2; - // fHighlightInTextCheckBox.setLayoutData(gd); - // fShowInOverviewRulerCheckBox = new Button(optionsComposite, SWT.CHECK); - // fShowInOverviewRulerCheckBox.setText(PreferencesMessages - // .getString("JavaEditorPreferencePage.annotations.showInOverviewRuler")); - // //$NON-NLS-1$ - // gd = new GridData(GridData.FILL_HORIZONTAL); - // gd.horizontalAlignment = GridData.BEGINNING; - // gd.horizontalSpan = 2; - // fShowInOverviewRulerCheckBox.setLayoutData(gd); - // fShowInVerticalRulerCheckBox = new Button(optionsComposite, SWT.CHECK); - // fShowInVerticalRulerCheckBox.setText(PreferencesMessages - // .getString("JavaEditorPreferencePage.annotations.showInVerticalRuler")); - // //$NON-NLS-1$ - // gd = new GridData(GridData.FILL_HORIZONTAL); - // gd.horizontalAlignment = GridData.BEGINNING; - // gd.horizontalSpan = 2; - // fShowInVerticalRulerCheckBox.setLayoutData(gd); - // label = new Label(optionsComposite, SWT.LEFT); - // label.setText(PreferencesMessages - // .getString("JavaEditorPreferencePage.annotations.color")); //$NON-NLS-1$ - // gd = new GridData(); - // gd.horizontalAlignment = GridData.BEGINNING; - // label.setLayoutData(gd); - // fAnnotationForegroundColorEditor = new ColorEditor(optionsComposite); - // Button foregroundColorButton = - // fAnnotationForegroundColorEditor.getButton(); - // gd = new GridData(GridData.FILL_HORIZONTAL); - // gd.horizontalAlignment = GridData.BEGINNING; - // foregroundColorButton.setLayoutData(gd); - // fAnnotationList.addSelectionListener(new SelectionListener() { - // public void widgetDefaultSelected(SelectionEvent e) { - // // do nothing - // } - // public void widgetSelected(SelectionEvent e) { - // handleAnnotationListSelection(); - // } - // }); - // fShowInTextCheckBox.addSelectionListener(new SelectionListener() { - // public void widgetDefaultSelected(SelectionEvent e) { - // // do nothing - // } - // public void widgetSelected(SelectionEvent e) { - // int i = fAnnotationList.getSelectionIndex(); - // String key = fAnnotationColorListModel[i][2]; - // fOverlayStore.setValue(key, fShowInTextCheckBox.getSelection()); - // String decorationKey = fAnnotationColorListModel[i][6]; - // fDecorationStyleCombo.setEnabled(decorationKey != null - // && fShowInTextCheckBox.getSelection()); - // } - // }); - // fHighlightInTextCheckBox.addSelectionListener(new SelectionListener() { - // public void widgetDefaultSelected(SelectionEvent e) { - // // do nothing - // } - // public void widgetSelected(SelectionEvent e) { - // int i = fAnnotationList.getSelectionIndex(); - // String key = fAnnotationColorListModel[i][4]; - // fOverlayStore.setValue(key, fHighlightInTextCheckBox.getSelection()); - // } - // }); - // fShowInOverviewRulerCheckBox.addSelectionListener(new SelectionListener() { - // public void widgetDefaultSelected(SelectionEvent e) { - // // do nothing - // } - // public void widgetSelected(SelectionEvent e) { - // int i = fAnnotationList.getSelectionIndex(); - // String key = fAnnotationColorListModel[i][3]; - // fOverlayStore - // .setValue(key, fShowInOverviewRulerCheckBox.getSelection()); - // } - // }); - // fShowInVerticalRulerCheckBox.addSelectionListener(new SelectionListener() { - // public void widgetDefaultSelected(SelectionEvent e) { - // // do nothing - // } - // public void widgetSelected(SelectionEvent e) { - // int i = fAnnotationList.getSelectionIndex(); - // String key = fAnnotationColorListModel[i][5]; - // fOverlayStore - // .setValue(key, fShowInVerticalRulerCheckBox.getSelection()); - // } - // }); - // foregroundColorButton.addSelectionListener(new SelectionListener() { - // public void widgetDefaultSelected(SelectionEvent e) { - // // do nothing - // } - // public void widgetSelected(SelectionEvent e) { - // int i = fAnnotationList.getSelectionIndex(); - // String key = fAnnotationColorListModel[i][1]; - // PreferenceConverter.setValue(fOverlayStore, key, - // fAnnotationForegroundColorEditor.getColorValue()); - // } - // }); - // fDecorationStyleCombo.addSelectionListener(new SelectionListener() { - // /** - // * {@inheritdoc} - // */ - // public void widgetDefaultSelected(SelectionEvent e) { - // // do nothing - // } - // /** - // * {@inheritdoc} - // */ - // public void widgetSelected(SelectionEvent e) { - // int i = fAnnotationList.getSelectionIndex(); - // String key = fAnnotationColorListModel[i][6]; - // if (key != null) { - // for (int j = 0; j < fAnnotationDecorationListModel.length; j++) { - // if (fAnnotationDecorationListModel[j][0] - // .equals(fDecorationStyleCombo.getText())) { - // fOverlayStore.setValue(key, fAnnotationDecorationListModel[j][1]); - // break; - // } - // } - // } - // } - // }); - // return composite; - // } - private String[][] createAnnotationTypeListModel(MarkerAnnotationPreferences preferences) { - ArrayList listModelItems = new ArrayList(); - SortedSet sortedPreferences = new TreeSet(new Comparator() { - /* - * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) - */ - public int compare(Object o1, Object o2) { - if (!(o2 instanceof AnnotationPreference)) - return -1; - if (!(o1 instanceof AnnotationPreference)) - return 1; - AnnotationPreference a1 = (AnnotationPreference) o1; - AnnotationPreference a2 = (AnnotationPreference) o2; - return Collator.getInstance().compare(a1.getPreferenceLabel(), a2.getPreferenceLabel()); - } - }); - sortedPreferences.addAll(preferences.getAnnotationPreferences()); - Iterator e = sortedPreferences.iterator(); - while (e.hasNext()) { - AnnotationPreference info = (AnnotationPreference) e.next(); - listModelItems.add(new String[] { - info.getPreferenceLabel(), - info.getColorPreferenceKey(), - info.getTextPreferenceKey(), - info.getOverviewRulerPreferenceKey(), - info.getHighlightPreferenceKey(), - info.getVerticalRulerPreferenceKey(), - info.getTextStylePreferenceKey() }); - } - String[][] items = new String[listModelItems.size()][]; - listModelItems.toArray(items); - return items; - } - - private Control createTypingPage(Composite parent) { - Composite composite = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.numColumns = 1; - composite.setLayout(layout); - String label; - // label = PreferencesMessages - // .getString("JavaEditorPreferencePage.overwriteMode"); - // //$NON-NLS-1$ - // addCheckBox(composite, label, - // PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE, 1); - // addFiller(composite); - // - // label = PreferencesMessages - // .getString("JavaEditorPreferencePage.smartHomeEnd"); - // //$NON-NLS-1$ - // addCheckBox(composite, label, PreferenceConstants.EDITOR_SMART_HOME_END, 1); - // - // label = PreferencesMessages - // .getString("JavaEditorPreferencePage.subWordNavigation"); - // //$NON-NLS-1$ - // addCheckBox(composite, label, - // PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION, 1); - // addFiller(composite); - Group group = new Group(composite, SWT.NONE); - layout = new GridLayout(); - layout.numColumns = 2; - group.setLayout(layout); - group.setText(PreferencesMessages.getString("JavaEditorPreferencePage.typing.description")); //$NON-NLS-1$ - - label = PreferencesMessages.getString("JavaEditorPreferencePage.wrapWords");//$NON-NLS-1$ - addCheckBox(group, label, PreferenceConstants.EDITOR_WRAP_WORDS, 1); - - label = PreferencesMessages.getString("JavaEditorPreferencePage.wrapStringsDQ");//$NON-NLS-1$ - Button button = addCheckBox(group, label, PreferenceConstants.EDITOR_WRAP_STRINGS_DQ, 1); - - label = PreferencesMessages.getString("JavaEditorPreferencePage.escapeStringsDQ");//$NON-NLS-1$ - fEscapeStringsButtonDQ = addCheckBox(group, label, PreferenceConstants.EDITOR_ESCAPE_STRINGS_DQ, 1); - createDependency(button, fEscapeStringsButtonDQ); - - label = PreferencesMessages.getString("JavaEditorPreferencePage.wrapStringsSQ");//$NON-NLS-1$ - addCheckBox(group, label, PreferenceConstants.EDITOR_WRAP_STRINGS_SQ, 1); - - label = PreferencesMessages.getString("JavaEditorPreferencePage.escapeStringsSQ"); - //$NON-NLS-1$ - fEscapeStringsButtonSQ = addCheckBox(group, label, PreferenceConstants.EDITOR_ESCAPE_STRINGS_SQ, 1); - createDependency(button, fEscapeStringsButtonSQ); - - label = PreferencesMessages.getString("JavaEditorPreferencePage.smartPaste"); - //$NON-NLS-1$ - addCheckBox(group, label, PreferenceConstants.EDITOR_SMART_PASTE, 1); - - label = PreferencesMessages.getString("JavaEditorPreferencePage.insertSpaceForTabs"); - //$NON-NLS-1$ - addCheckBox(group, label, PreferenceConstants.EDITOR_SPACES_FOR_TABS, 1); - - label = PreferencesMessages.getString("JavaEditorPreferencePage.closeStringsDQ"); - //$NON-NLS-1$ - addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_STRINGS_DQ_PHP, 1); - label = PreferencesMessages.getString("JavaEditorPreferencePage.closeStringsSQ"); - //$NON-NLS-1$ - addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_STRINGS_SQ_PHP, 1); - - label = PreferencesMessages.getString("JavaEditorPreferencePage.closeBrackets"); - //$NON-NLS-1$ - addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP, 1); - - // label = PreferencesMessages - // .getString("JavaEditorPreferencePage.closeBraces"); - // //$NON-NLS-1$ - // addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_BRACES, 1); - - label = PreferencesMessages.getString("JavaEditorPreferencePage.closeJavaDocs"); - //$NON-NLS-1$ - button = addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_JAVADOCS, 1); - label = PreferencesMessages.getString("JavaEditorPreferencePage.formatJavaDocs"); - //$NON-NLS-1$ - button = addCheckBox(group, label, PreferenceConstants.EDITOR_FORMAT_JAVADOCS, 1); - - label = PreferencesMessages.getString("JavaEditorPreferencePage.p_rtrim_on_save"); - addCheckBox(group, label, PreferenceConstants.EDITOR_P_RTRIM_ON_SAVE, 1); - // - // label = PreferencesMessages - // .getString("JavaEditorPreferencePage.addJavaDocTags"); - // //$NON-NLS-1$ - // fAddJavaDocTagsButton = addCheckBox(group, label, - // PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, 1); - // createDependency(button, fAddJavaDocTagsButton); - return composite; - } - - private void addFiller(Composite composite) { - Label filler = new Label(composite, SWT.LEFT); - GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - gd.horizontalSpan = 2; - gd.heightHint = convertHeightInCharsToPixels(1) / 2; - filler.setLayoutData(gd); - } - - private static void indent(Control control) { - GridData gridData = new GridData(); - gridData.horizontalIndent = 20; - control.setLayoutData(gridData); - } - - private static void createDependency(final Button master, final Control slave) { - indent(slave); - master.addSelectionListener(new SelectionListener() { - public void widgetSelected(SelectionEvent e) { - slave.setEnabled(master.getSelection()); - } - - public void widgetDefaultSelected(SelectionEvent e) { - } - }); - } - - private void addCompletionRadioButtons(Composite contentAssistComposite) { - Composite completionComposite = new Composite(contentAssistComposite, SWT.NONE); - GridData ccgd = new GridData(); - ccgd.horizontalSpan = 2; - completionComposite.setLayoutData(ccgd); - GridLayout ccgl = new GridLayout(); - ccgl.marginWidth = 0; - ccgl.numColumns = 2; - completionComposite.setLayout(ccgl); - // SelectionListener completionSelectionListener= new SelectionAdapter() { - // public void widgetSelected(SelectionEvent e) { - // boolean insert= fCompletionInsertsRadioButton.getSelection(); - // fOverlayStore.setValue(PreferenceConstants.CODEASSIST_INSERT_COMPLETION, - // insert); - // } - // }; - // - // fCompletionInsertsRadioButton= new Button(completionComposite, SWT.RADIO - // | SWT.LEFT); - // fCompletionInsertsRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.completionInserts")); - // //$NON-NLS-1$ - // fCompletionInsertsRadioButton.setLayoutData(new GridData()); - // fCompletionInsertsRadioButton.addSelectionListener(completionSelectionListener); - // - // fCompletionOverwritesRadioButton= new Button(completionComposite, - // SWT.RADIO | SWT.LEFT); - // fCompletionOverwritesRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.completionOverwrites")); - // //$NON-NLS-1$ - // fCompletionOverwritesRadioButton.setLayoutData(new GridData()); - // fCompletionOverwritesRadioButton.addSelectionListener(completionSelectionListener); - } - - private Control createNavigationPage(Composite parent) { - Composite composite = new Composite(parent, SWT.NULL); - GridLayout layout = new GridLayout(); - layout.numColumns = 2; - composite.setLayout(layout); - String text = PreferencesMessages.getString("JavaEditorPreferencePage.navigation.browserLikeLinks"); - //$NON-NLS-1$ - fBrowserLikeLinksCheckBox = addCheckBox(composite, text, PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS, 0); - fBrowserLikeLinksCheckBox.addSelectionListener(new SelectionListener() { - public void widgetSelected(SelectionEvent e) { - boolean state = fBrowserLikeLinksCheckBox.getSelection(); - fBrowserLikeLinksKeyModifierText.setEnabled(state); - handleBrowserLikeLinksKeyModifierModified(); - } - - public void widgetDefaultSelected(SelectionEvent e) { - } - }); - // Text field for modifier string - text = PreferencesMessages.getString("JavaEditorPreferencePage.navigation.browserLikeLinksKeyModifier"); - //$NON-NLS-1$ - fBrowserLikeLinksKeyModifierText = addTextField(composite, text, PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER, - 20, 0, false); - fBrowserLikeLinksKeyModifierText.setTextLimit(Text.LIMIT); - - if (computeStateMask(fOverlayStore.getString(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER)) == -1) { - // Fix possible illegal modifier string - int stateMask = fOverlayStore.getInt(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK); - if (stateMask == -1) - fBrowserLikeLinksKeyModifierText.setText(""); //$NON-NLS-1$ - else - fBrowserLikeLinksKeyModifierText.setText(EditorUtility.getModifierString(stateMask)); - } - fBrowserLikeLinksKeyModifierText.addKeyListener(new KeyListener() { - private boolean isModifierCandidate; - - public void keyPressed(KeyEvent e) { - isModifierCandidate = e.keyCode > 0 && e.character == 0 && e.stateMask == 0; - } - - public void keyReleased(KeyEvent e) { - if (isModifierCandidate && e.stateMask > 0 && e.stateMask == e.stateMask && e.character == 0) {// && e.time -time < 1000) { - String modifierString = fBrowserLikeLinksKeyModifierText.getText(); - Point selection = fBrowserLikeLinksKeyModifierText.getSelection(); - int i = selection.x - 1; - while (i > -1 && Character.isWhitespace(modifierString.charAt(i))) { - i--; - } - boolean needsPrefixDelimiter = i > -1 && !String.valueOf(modifierString.charAt(i)).equals(DELIMITER); - - i = selection.y; - while (i < modifierString.length() && Character.isWhitespace(modifierString.charAt(i))) { - i++; - } - boolean needsPostfixDelimiter = i < modifierString.length() - && !String.valueOf(modifierString.charAt(i)).equals(DELIMITER); - - String insertString; - - if (needsPrefixDelimiter && needsPostfixDelimiter) - insertString = PreferencesMessages.getFormattedString( - "JavaEditorPreferencePage.navigation.insertDelimiterAndModifierAndDelimiter", new String[] { Action - .findModifierString(e.stateMask) }); //$NON-NLS-1$ - else if (needsPrefixDelimiter) - insertString = PreferencesMessages.getFormattedString("JavaEditorPreferencePage.navigation.insertDelimiterAndModifier", - new String[] { Action.findModifierString(e.stateMask) }); //$NON-NLS-1$ - else if (needsPostfixDelimiter) - insertString = PreferencesMessages.getFormattedString("JavaEditorPreferencePage.navigation.insertModifierAndDelimiter", - new String[] { Action.findModifierString(e.stateMask) }); //$NON-NLS-1$ - else - insertString = Action.findModifierString(e.stateMask); - - fBrowserLikeLinksKeyModifierText.insert(insertString); - } - } - }); - - fBrowserLikeLinksKeyModifierText.addModifyListener(new ModifyListener() { - public void modifyText(ModifyEvent e) { - handleBrowserLikeLinksKeyModifierModified(); - } - }); - return composite; - } - - private void handleBrowserLikeLinksKeyModifierModified() { - String modifiers = fBrowserLikeLinksKeyModifierText.getText(); - int stateMask = computeStateMask(modifiers); - if (fBrowserLikeLinksCheckBox.getSelection() && (stateMask == -1 || (stateMask & SWT.SHIFT) != 0)) { - if (stateMask == -1) - fBrowserLikeLinksKeyModifierStatus = new StatusInfo(IStatus.ERROR, PreferencesMessages.getFormattedString( - "JavaEditorPreferencePage.navigation.modifierIsNotValid", modifiers)); //$NON-NLS-1$ - else - fBrowserLikeLinksKeyModifierStatus = new StatusInfo(IStatus.ERROR, PreferencesMessages - .getString("JavaEditorPreferencePage.navigation.shiftIsDisabled")); - //$NON-NLS-1$ - setValid(false); - StatusUtil.applyToStatusLine(this, fBrowserLikeLinksKeyModifierStatus); - } else { - fBrowserLikeLinksKeyModifierStatus = new StatusInfo(); - updateStatus(fBrowserLikeLinksKeyModifierStatus); - } - } - - private IStatus getBrowserLikeLinksKeyModifierStatus() { - if (fBrowserLikeLinksKeyModifierStatus == null) - fBrowserLikeLinksKeyModifierStatus = new StatusInfo(); - return fBrowserLikeLinksKeyModifierStatus; - } - - /** - * 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 - */ - private 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; - } - - /* - * @see PreferencePage#createContents(Composite) - */ - protected Control createContents(Composite parent) { - initializeDefaultColors(); - fFoldingConfigurationBlock = new FoldingConfigurationBlock(fOverlayStore); - fOverlayStore.load(); - fOverlayStore.start(); - TabFolder folder = new TabFolder(parent, SWT.NONE); - folder.setLayout(new TabFolderLayout()); - folder.setLayoutData(new GridData(GridData.FILL_BOTH)); - TabItem item = new TabItem(folder, SWT.NONE); - item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.general")); //$NON-NLS-1$ - item.setControl(createAppearancePage(folder)); - item = new TabItem(folder, SWT.NONE); - item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.colors")); //$NON-NLS-1$ - item.setControl(createSyntaxPage(folder)); - - // item = new TabItem(folder, SWT.NONE); - // item.setText(PreferencesMessages - // .getString("JavaEditorPreferencePage.annotationsTab.title")); - // //$NON-NLS-1$ - // item.setControl(createAnnotationsPage(folder)); - item = new TabItem(folder, SWT.NONE); - item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.typing.tabTitle")); - //$NON-NLS-1$ - item.setControl(createTypingPage(folder)); - - item = new TabItem(folder, SWT.NONE); - item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.hoverTab.title")); - //$NON-NLS-1$ - fJavaEditorHoverConfigurationBlock = new JavaEditorHoverConfigurationBlock(this, fOverlayStore); - item.setControl(fJavaEditorHoverConfigurationBlock.createControl(folder)); - item = new TabItem(folder, SWT.NONE); - item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.navigationTab.title")); - // //$NON-NLS-1$ - item.setControl(createNavigationPage(folder)); - item = new TabItem(folder, SWT.NONE); - item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.folding.title")); //$NON-NLS-1$ - item.setControl(fFoldingConfigurationBlock.createControl(folder)); - - initialize(); - Dialog.applyDialogFont(folder); - return folder; - } - - private void initialize() { - initializeFields(); - for (int i = 0; i < fSyntaxColorListModel.length; i++) - fSyntaxColorList.add(fSyntaxColorListModel[i][0]); - fSyntaxColorList.getDisplay().asyncExec(new Runnable() { - public void run() { - if (fSyntaxColorList != null && !fSyntaxColorList.isDisposed()) { - fSyntaxColorList.select(0); - handleSyntaxColorListSelection(); - } - } - }); - for (int i = 0; i < fAppearanceColorListModel.length; i++) - fAppearanceColorList.add(fAppearanceColorListModel[i][0]); - fAppearanceColorList.getDisplay().asyncExec(new Runnable() { - public void run() { - if (fAppearanceColorList != null && !fAppearanceColorList.isDisposed()) { - fAppearanceColorList.select(0); - handleAppearanceColorListSelection(); - } - } - }); - // for (int i = 0; i < fAnnotationColorListModel.length; i++) - // fAnnotationList.add(fAnnotationColorListModel[i][0]); - // fAnnotationList.getDisplay().asyncExec(new Runnable() { - // public void run() { - // if (fAnnotationList != null && !fAnnotationList.isDisposed()) { - // fAnnotationList.select(0); - // handleAnnotationListSelection(); - // } - // } - // }); - // for (int i= 0; i < fContentAssistColorListModel.length; i++) - // fContentAssistColorList.add(fContentAssistColorListModel[i][0]); - // fContentAssistColorList.getDisplay().asyncExec(new Runnable() { - // public void run() { - // if (fContentAssistColorList != null && - // !fContentAssistColorList.isDisposed()) { - // fContentAssistColorList.select(0); - // handleContentAssistColorListSelection(); - // } - // } - // }); - fFoldingConfigurationBlock.initialize(); - } - - private void initializeFields() { - Iterator e = fColorButtons.keySet().iterator(); - while (e.hasNext()) { - ColorEditor c = (ColorEditor) e.next(); - String key = (String) fColorButtons.get(c); - RGB rgb = PreferenceConverter.getColor(fOverlayStore, key); - c.setColorValue(rgb); - } - e = fCheckBoxes.keySet().iterator(); - while (e.hasNext()) { - Button b = (Button) e.next(); - String key = (String) fCheckBoxes.get(b); - b.setSelection(fOverlayStore.getBoolean(key)); - } - e = fTextFields.keySet().iterator(); - while (e.hasNext()) { - Text t = (Text) e.next(); - String key = (String) fTextFields.get(t); - t.setText(fOverlayStore.getString(key)); - } - RGB rgb = PreferenceConverter.getColor(fOverlayStore, PreferenceConstants.EDITOR_BACKGROUND_COLOR); - fBackgroundColorEditor.setColorValue(rgb); - boolean default_ = fOverlayStore.getBoolean(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR); - fBackgroundDefaultRadioButton.setSelection(default_); - fBackgroundCustomRadioButton.setSelection(!default_); - fBackgroundColorButton.setEnabled(!default_); - boolean closeJavaDocs = fOverlayStore.getBoolean(PreferenceConstants.EDITOR_CLOSE_JAVADOCS); - // fAddJavaDocTagsButton.setEnabled(closeJavaDocs); - fEscapeStringsButtonDQ.setEnabled(fOverlayStore.getBoolean(PreferenceConstants.EDITOR_WRAP_STRINGS_DQ)); - fEscapeStringsButtonSQ.setEnabled(fOverlayStore.getBoolean(PreferenceConstants.EDITOR_WRAP_STRINGS_SQ)); - // boolean fillMethodArguments= - // fOverlayStore.getBoolean(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES); - // fGuessMethodArgumentsButton.setEnabled(fillMethodArguments); - // boolean completionInserts= - // fOverlayStore.getBoolean(PreferenceConstants.CODEASSIST_INSERT_COMPLETION); - // fCompletionInsertsRadioButton.setSelection(completionInserts); - // fCompletionOverwritesRadioButton.setSelection(! completionInserts); - // - fBrowserLikeLinksKeyModifierText.setEnabled(fBrowserLikeLinksCheckBox.getSelection()); - // boolean markOccurrences= - // fOverlayStore.getBoolean(PreferenceConstants.EDITOR_MARK_OCCURRENCES); - // fStickyOccurrencesButton.setEnabled(markOccurrences); - updateAutoactivationControls(); - } - - private void initializeDefaultColors() { - if (!getPreferenceStore().contains(PreferenceConstants.EDITOR_BACKGROUND_COLOR)) { - RGB rgb = getControl().getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND).getRGB(); - PreferenceConverter.setDefault(fOverlayStore, PreferenceConstants.EDITOR_BACKGROUND_COLOR, rgb); - PreferenceConverter.setDefault(getPreferenceStore(), PreferenceConstants.EDITOR_BACKGROUND_COLOR, rgb); - } - if (!getPreferenceStore().contains(PreferenceConstants.EDITOR_FOREGROUND_COLOR)) { - RGB rgb = getControl().getDisplay().getSystemColor(SWT.COLOR_LIST_FOREGROUND).getRGB(); - PreferenceConverter.setDefault(fOverlayStore, PreferenceConstants.EDITOR_FOREGROUND_COLOR, rgb); - PreferenceConverter.setDefault(getPreferenceStore(), PreferenceConstants.EDITOR_FOREGROUND_COLOR, rgb); - } - } - - private void updateAutoactivationControls() { - // boolean autoactivation= - // fOverlayStore.getBoolean(PreferenceConstants.CODEASSIST_AUTOACTIVATION); - // fAutoInsertDelayText.setEnabled(autoactivation); - // fAutoInsertDelayLabel.setEnabled(autoactivation); - // fAutoInsertJavaTriggerText.setEnabled(autoactivation); - // fAutoInsertJavaTriggerLabel.setEnabled(autoactivation); - // - // fAutoInsertJavaDocTriggerText.setEnabled(autoactivation); - // fAutoInsertJavaDocTriggerLabel.setEnabled(autoactivation); - } - - /* - * @see PreferencePage#performOk() - */ - public boolean performOk() { - // fJavaEditorHoverConfigurationBlock.performOk(); - fFoldingConfigurationBlock.performOk(); - fOverlayStore.setValue(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK, - computeStateMask(fBrowserLikeLinksKeyModifierText.getText())); - fOverlayStore.propagate(); - PHPeclipsePlugin.getDefault().savePluginPreferences(); - return true; - } - - /* - * @see PreferencePage#performDefaults() - */ - protected void performDefaults() { - fOverlayStore.loadDefaults(); - initializeFields(); - handleSyntaxColorListSelection(); - handleAppearanceColorListSelection(); - // handleAnnotationListSelection(); - // handleContentAssistColorListSelection(); - // fJavaEditorHoverConfigurationBlock.performDefaults(); - fFoldingConfigurationBlock.performDefaults(); - super.performDefaults(); - fPreviewViewer.invalidateTextPresentation(); - } - - /* - * @see DialogPage#dispose() - */ - public void dispose() { - fFoldingConfigurationBlock.dispose(); - - if (fJavaTextTools != null) { - fJavaTextTools.dispose(); - fJavaTextTools = null; - } - if (fOverlayStore != null) { - fOverlayStore.stop(); - fOverlayStore = null; - } - if (fBackgroundColor != null && !fBackgroundColor.isDisposed()) - fBackgroundColor.dispose(); - super.dispose(); - } - - private Button addCheckBox(Composite parent, String label, String key, int indentation) { - Button checkBox = new Button(parent, SWT.CHECK); - checkBox.setText(label); - GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - gd.horizontalIndent = indentation; - gd.horizontalSpan = 2; - checkBox.setLayoutData(gd); - checkBox.addSelectionListener(fCheckBoxListener); - fCheckBoxes.put(checkBox, key); - return checkBox; - } - - private Text addTextField(Composite composite, String label, String key, int textLimit, int indentation, boolean isNumber) { - return getTextControl(addLabelledTextField(composite, label, key, textLimit, indentation, isNumber)); - } - - private static Label getLabelControl(Control[] labelledTextField) { - return (Label) labelledTextField[0]; - } - - private static Text getTextControl(Control[] labelledTextField) { - return (Text) labelledTextField[1]; - } - - /** - * Returns an array of size 2: - first element is of type Label- second element is of type Text Use - * getLabelControl and getTextControl to get the 2 controls. - */ - private Control[] addLabelledTextField(Composite composite, String label, String key, int textLimit, int indentation, - boolean isNumber) { - Label labelControl = new Label(composite, SWT.NONE); - labelControl.setText(label); - GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - gd.horizontalIndent = indentation; - labelControl.setLayoutData(gd); - Text textControl = new Text(composite, SWT.BORDER | SWT.SINGLE); - gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - gd.widthHint = convertWidthInCharsToPixels(textLimit + 1); - textControl.setLayoutData(gd); - textControl.setTextLimit(textLimit); - fTextFields.put(textControl, key); - if (isNumber) { - fNumberFields.add(textControl); - textControl.addModifyListener(fNumberFieldListener); - } else { - textControl.addModifyListener(fTextFieldListener); - } - return new Control[] { labelControl, textControl }; - } - - private String loadPreviewContentFromFile(String filename) { - String line; - String separator = System.getProperty("line.separator"); //$NON-NLS-1$ - StringBuffer buffer = new StringBuffer(512); - BufferedReader reader = null; - try { - reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(filename))); - while ((line = reader.readLine()) != null) { - buffer.append(line); - buffer.append(separator); - } - } catch (IOException io) { - PHPeclipsePlugin.log(io); - } finally { - if (reader != null) { - try { - reader.close(); - } catch (IOException e) { - } - } - } - return buffer.toString(); - } - - private void numberFieldChanged(Text textControl) { - String number = textControl.getText(); - IStatus status = validatePositiveNumber(number); - if (!status.matches(IStatus.ERROR)) - fOverlayStore.setValue((String) fTextFields.get(textControl), number); - updateStatus(status); - } - - private IStatus validatePositiveNumber(String number) { - StatusInfo status = new StatusInfo(); - if (number.length() == 0) { - status.setError(PreferencesMessages.getString("JavaEditorPreferencePage.empty_input")); //$NON-NLS-1$ - } else { - try { - int value = Integer.parseInt(number); - if (value < 0) - status.setError(PreferencesMessages.getFormattedString("JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$ - } catch (NumberFormatException e) { - status.setError(PreferencesMessages.getFormattedString("JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$ - } - } - return status; - } - - void updateStatus(IStatus status) { - if (!status.matches(IStatus.ERROR)) { - for (int i = 0; i < fNumberFields.size(); i++) { - Text text = (Text) fNumberFields.get(i); - IStatus s = validatePositiveNumber(text.getText()); - status = StatusUtil.getMoreSevere(s, status); - } - } - // status= - // StatusUtil.getMoreSevere(fJavaEditorHoverConfigurationBlock.getStatus(), - // status); - // status= StatusUtil.getMoreSevere(getBrowserLikeLinksKeyModifierStatus(), - // status); - setValid(!status.matches(IStatus.ERROR)); - StatusUtil.applyToStatusLine(this, status); - } +public class JavaEditorPreferencePage extends PreferencePage implements + IWorkbenchPreferencePage { + private static final String BOLD = PreferenceConstants.EDITOR_BOLD_SUFFIX; + + private static final String COMPILER_TASK_TAGS = JavaCore.COMPILER_TASK_TAGS; + + private static final String DELIMITER = PreferencesMessages + .getString("JavaEditorPreferencePage.navigation.delimiter"); //$NON-NLS-1$ + + /** The keys of the overlay store. */ + public final OverlayPreferenceStore.OverlayKey[] fKeys; + + private final String[][] fSyntaxColorListModel = new String[][] { + { + PreferencesMessages + .getString("JavaEditorPreferencePage.multiLineComment"), + PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.singleLineComment"), + PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR }, + //$NON-NLS-1$ + { PreferencesMessages.getString("JavaEditorPreferencePage.tags"), + PreferenceConstants.EDITOR_PHP_TAG_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.keywords"), + PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR }, + { + PreferencesMessages + .getString("JavaEditorPreferencePage.functionNames"), + PreferenceConstants.EDITOR_PHP_FUNCTIONNAME_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.variables"), + PreferenceConstants.EDITOR_PHP_VARIABLE_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.variables_dollar"), + PreferenceConstants.EDITOR_PHP_VARIABLE_DOLLAR_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.constants"), + PreferenceConstants.EDITOR_PHP_CONSTANT_COLOR }, + //$NON-NLS-1$ + { PreferencesMessages.getString("JavaEditorPreferencePage.types"), + PreferenceConstants.EDITOR_PHP_TYPE_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.strings_dq"), + PreferenceConstants.EDITOR_STRING_COLOR_DQ }, + { + PreferencesMessages + .getString("JavaEditorPreferencePage.strings_sq"), + PreferenceConstants.EDITOR_STRING_COLOR_SQ }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.others"), PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR }, //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.operators"), + PreferenceConstants.EDITOR_PHP_OPERATOR_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.returnKeyword"), + PreferenceConstants.EDITOR_PHP_KEYWORD_RETURN_COLOR }, + { PreferencesMessages.getString("JavaEditorPreferencePage.braces"), + PreferenceConstants.EDITOR_PHP_BRACE_OPERATOR_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.phpDocKeywords"), + PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.phpDocHtmlTags"), + PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.phpDocLinks"), + PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.phpDocOthers"), PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR } //$NON-NLS-1$ + }; + + private final String[][] fAppearanceColorListModel = new String[][] { + { + PreferencesMessages + .getString("JavaEditorPreferencePage.lineNumberForegroundColor"), + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.matchingBracketsHighlightColor2"), + PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.currentLineHighlighColor"), + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.printMarginColor2"), + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.findScopeColor2"), + PreferenceConstants.EDITOR_FIND_SCOPE_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.linkColor2"), PreferenceConstants.EDITOR_LINK_COLOR }, //$NON-NLS-1$ + }; + + // private final String[][] fAnnotationColorListModel; + + // private final String[][] fAnnotationDecorationListModel = new String[][]{ + // { + // PreferencesMessages + // .getString("JavaEditorPreferencePage.AnnotationDecoration.NONE"), + // AnnotationPreference.STYLE_NONE}, + // //$NON-NLS-1$ + // { + // PreferencesMessages + // .getString("JavaEditorPreferencePage.AnnotationDecoration.SQUIGGLIES"), + // AnnotationPreference.STYLE_SQUIGGLIES}, + // //$NON-NLS-1$ + // { + // PreferencesMessages + // .getString("JavaEditorPreferencePage.AnnotationDecoration.UNDERLINE"), + // AnnotationPreference.STYLE_UNDERLINE}, + // //$NON-NLS-1$ + // { + // PreferencesMessages + // .getString("JavaEditorPreferencePage.AnnotationDecoration.BOX"), + // AnnotationPreference.STYLE_BOX}, + // //$NON-NLS-1$ + // { + // PreferencesMessages + // .getString("JavaEditorPreferencePage.AnnotationDecoration.IBEAM"), + // AnnotationPreference.STYLE_IBEAM} //$NON-NLS-1$ + // }; + private OverlayPreferenceStore fOverlayStore; + + private JavaTextTools fJavaTextTools; + + private JavaEditorHoverConfigurationBlock fJavaEditorHoverConfigurationBlock; + + private FoldingConfigurationBlock fFoldingConfigurationBlock; + + private Map fColorButtons = new HashMap(); + + 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()); + } + }; + + private Map fTextFields = new HashMap(); + + private ModifyListener fTextFieldListener = new ModifyListener() { + public void modifyText(ModifyEvent e) { + Text text = (Text) e.widget; + fOverlayStore.setValue((String) fTextFields.get(text), text + .getText()); + } + }; + + private ArrayList fNumberFields = new ArrayList(); + + private ModifyListener fNumberFieldListener = new ModifyListener() { + public void modifyText(ModifyEvent e) { + numberFieldChanged((Text) e.widget); + } + }; + + private List fSyntaxColorList; + + private List fAppearanceColorList; + + // private List fContentAssistColorList; + private List fAnnotationList; + + private ColorEditor fSyntaxForegroundColorEditor; + + private ColorEditor fAppearanceColorEditor; + + private ColorEditor fAnnotationForegroundColorEditor; + + private ColorEditor fContentAssistColorEditor; + + private ColorEditor fBackgroundColorEditor; + + private Button fBackgroundDefaultRadioButton; + + private Button fBackgroundCustomRadioButton; + + private Button fBackgroundColorButton; + + private Button fBoldCheckBox; + + // private Button fAddJavaDocTagsButton; + + private Button fEscapeStringsButtonDQ; + + private Button fEscapeStringsButtonSQ; + + // private Button fGuessMethodArgumentsButton; + private SourceViewer fPreviewViewer; + + private Color fBackgroundColor; + + private Control fAutoInsertDelayText; + + private Control fAutoInsertJavaTriggerText; + + private Control fAutoInsertJavaDocTriggerText; + + private Label fAutoInsertDelayLabel; + + private Label fAutoInsertJavaTriggerLabel; + + private Label fAutoInsertJavaDocTriggerLabel; + + private Button fShowInTextCheckBox; + + private Combo fDecorationStyleCombo; + + private Button fHighlightInTextCheckBox; + + private Button fShowInOverviewRulerCheckBox; + + private Button fShowInVerticalRulerCheckBox; + + private Text fBrowserLikeLinksKeyModifierText; + + private Button fBrowserLikeLinksCheckBox; + + private StatusInfo fBrowserLikeLinksKeyModifierStatus; + + // private Button fCompletionInsertsRadioButton; + // private Button fCompletionOverwritesRadioButton; + // private Button fStickyOccurrencesButton; + /** + * Creates a new preference page. + */ + public JavaEditorPreferencePage() { + setDescription(PreferencesMessages + .getString("JavaEditorPreferencePage.description")); //$NON-NLS-1$ + setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); + MarkerAnnotationPreferences markerAnnotationPreferences = new MarkerAnnotationPreferences(); + fKeys = createOverlayStoreKeys(markerAnnotationPreferences); + fOverlayStore = new OverlayPreferenceStore(getPreferenceStore(), fKeys); + // fAnnotationColorListModel = + // createAnnotationTypeListModel(markerAnnotationPreferences); + } + + private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys( + MarkerAnnotationPreferences preferences) { + ArrayList overlayKeys = new ArrayList(); + Iterator e = preferences.getAnnotationPreferences().iterator(); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_FOREGROUND_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_BACKGROUND_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.INT, + PreferenceConstants.EDITOR_TAB_WIDTH)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_JAVA_KEYWORD_BOLD)); + + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_PHP_TAG_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_PHP_TAG_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_PHP_FUNCTIONNAME_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_PHP_FUNCTIONNAME_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_PHP_VARIABLE_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_PHP_VARIABLE_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_PHP_VARIABLE_DOLLAR_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_PHP_VARIABLE_DOLLAR_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_PHP_CONSTANT_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_PHP_CONSTANT_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_PHP_TYPE_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_PHP_TYPE_BOLD)); + + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_STRING_COLOR_DQ)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_STRING_BOLD_DQ)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_STRING_COLOR_SQ)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_STRING_BOLD_SQ)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_JAVA_DEFAULT_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_TASK_TAG_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_TASK_TAG_BOLD)); + // overlayKeys.add(new + // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING_DQ, + // PreferenceConstants.EDITOR_JAVA_METHOD_NAME_COLOR)); + // overlayKeys.add(new + // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, + // PreferenceConstants.EDITOR_JAVA_METHOD_NAME_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_PHP_OPERATOR_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_PHP_OPERATOR_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_PHP_KEYWORD_RETURN_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_PHP_KEYWORD_RETURN_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_PHP_BRACE_OPERATOR_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_PHP_BRACE_OPERATOR_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_JAVADOC_KEYWORD_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_JAVADOC_TAG_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_JAVADOC_LINKS_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_JAVADOC_DEFAULT_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_MATCHING_BRACKETS)); + overlayKeys + .add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE_COLOR)); + overlayKeys + .add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE)); + overlayKeys + .add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR)); + overlayKeys + .add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.INT, + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN)); + overlayKeys + .add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN)); + // overlayKeys.add(new + // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, + // PreferenceConstants.EDITOR_MARK_OCCURRENCES)); + // overlayKeys.add(new + // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, + // PreferenceConstants.EDITOR_STICKY_OCCURRENCES)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_FIND_SCOPE_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_LINK_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_CORRECTION_INDICATION)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS)); + overlayKeys + .add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_OVERVIEW_RULER)); + overlayKeys + .add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR)); + overlayKeys + .add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_SPACES_FOR_TABS)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_AUTOACTIVATION)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.INT, + PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_AUTOINSERT)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA)); + overlayKeys + .add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_ORDER_PROPOSALS)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_CASE_SENSITIVITY)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_ADDIMPORT)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_INSERT_COMPLETION)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_SMART_PASTE)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_CLOSE_STRINGS_DQ_PHP)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_CLOSE_STRINGS_SQ_PHP)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP)); + // overlayKeys + // .add(new OverlayPreferenceStore.OverlayKey( + // OverlayPreferenceStore.BOOLEAN, + // PreferenceConstants.EDITOR_CLOSE_BRACES)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_CLOSE_JAVADOCS)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_WRAP_WORDS)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_WRAP_STRINGS_DQ)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_ESCAPE_STRINGS_DQ)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_WRAP_STRINGS_SQ)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_ESCAPE_STRINGS_SQ)); + + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_FORMAT_JAVADOCS)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_P_RTRIM_ON_SAVE)); + + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_SMART_HOME_END)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE)); + // overlayKeys.add(new + // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, + // PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER)); + overlayKeys + .add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK)); + while (e.hasNext()) { + AnnotationPreference info = (AnnotationPreference) e.next(); + overlayKeys + .add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, info + .getColorPreferenceKey())); + overlayKeys + .add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, info + .getTextPreferenceKey())); + if (info.getHighlightPreferenceKey() != null) + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, info + .getHighlightPreferenceKey())); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, info + .getOverviewRulerPreferenceKey())); + if (info.getVerticalRulerPreferenceKey() != null) + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, info + .getVerticalRulerPreferenceKey())); + if (info.getTextStylePreferenceKey() != null) + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, info + .getTextStylePreferenceKey())); + } + OverlayPreferenceStore.OverlayKey[] keys = new OverlayPreferenceStore.OverlayKey[overlayKeys + .size()]; + overlayKeys.toArray(keys); + return keys; + } /* + * @see IWorkbenchPreferencePage#init() + */ + + public void init(IWorkbench workbench) { + } + + /* + * @see PreferencePage#createControl(Composite) + */ + public void createControl(Composite parent) { + super.createControl(parent); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), + IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE); + } + + private void handleSyntaxColorListSelection() { + int i = fSyntaxColorList.getSelectionIndex(); + String key = fSyntaxColorListModel[i][1]; + RGB rgb = PreferenceConverter.getColor(fOverlayStore, key); + fSyntaxForegroundColorEditor.setColorValue(rgb); + fBoldCheckBox.setSelection(fOverlayStore.getBoolean(key + BOLD)); + } + + private void handleAppearanceColorListSelection() { + int i = fAppearanceColorList.getSelectionIndex(); + String key = fAppearanceColorListModel[i][1]; + RGB rgb = PreferenceConverter.getColor(fOverlayStore, key); + fAppearanceColorEditor.setColorValue(rgb); + } + + // private void handleAnnotationListSelection() { + // int i = fAnnotationList.getSelectionIndex(); + // String key = fAnnotationColorListModel[i][1]; + // RGB rgb = PreferenceConverter.getColor(fOverlayStore, key); + // fAnnotationForegroundColorEditor.setColorValue(rgb); + // key = fAnnotationColorListModel[i][2]; + // boolean showInText = fOverlayStore.getBoolean(key); + // fShowInTextCheckBox.setSelection(showInText); + // key = fAnnotationColorListModel[i][6]; + // if (key != null) { + // fDecorationStyleCombo.setEnabled(showInText); + // for (int j = 0; j < fAnnotationDecorationListModel.length; j++) { + // String value = fOverlayStore.getString(key); + // if (fAnnotationDecorationListModel[j][1].equals(value)) { + // fDecorationStyleCombo.setText(fAnnotationDecorationListModel[j][0]); + // break; + // } + // } + // } else { + // fDecorationStyleCombo.setEnabled(false); + // fDecorationStyleCombo.setText(fAnnotationDecorationListModel[1][0]); // + // set + // // selection + // // to + // // squigglies + // // if + // // the + // // key + // // is + // // not + // // there + // // (legacy + // // support) + // } + // key = fAnnotationColorListModel[i][3]; + // fShowInOverviewRulerCheckBox.setSelection(fOverlayStore.getBoolean(key)); + // key = fAnnotationColorListModel[i][4]; + // if (key != null) { + // fHighlightInTextCheckBox.setSelection(fOverlayStore.getBoolean(key)); + // fHighlightInTextCheckBox.setEnabled(true); + // } else + // fHighlightInTextCheckBox.setEnabled(false); + // key = fAnnotationColorListModel[i][5]; + // if (key != null) { + // fShowInVerticalRulerCheckBox.setSelection(fOverlayStore.getBoolean(key)); + // fShowInVerticalRulerCheckBox.setEnabled(true); + // } else { + // fShowInVerticalRulerCheckBox.setSelection(true); + // fShowInVerticalRulerCheckBox.setEnabled(false); + // } + // } + private Control createSyntaxPage(Composite parent) { + Composite colorComposite = new Composite(parent, SWT.NULL); + colorComposite.setLayout(new GridLayout()); + Group backgroundComposite = new Group(colorComposite, + SWT.SHADOW_ETCHED_IN); + backgroundComposite.setLayout(new RowLayout()); + backgroundComposite.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.backgroundColor"));//$NON-NLS-1$ + SelectionListener backgroundSelectionListener = new SelectionListener() { + public void widgetSelected(SelectionEvent e) { + boolean custom = fBackgroundCustomRadioButton.getSelection(); + fBackgroundColorButton.setEnabled(custom); + fOverlayStore.setValue( + PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR, + !custom); + } + + public void widgetDefaultSelected(SelectionEvent e) { + } + }; + fBackgroundDefaultRadioButton = new Button(backgroundComposite, + SWT.RADIO | SWT.LEFT); + fBackgroundDefaultRadioButton.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.systemDefault")); //$NON-NLS-1$ + fBackgroundDefaultRadioButton + .addSelectionListener(backgroundSelectionListener); + fBackgroundCustomRadioButton = new Button(backgroundComposite, + SWT.RADIO | SWT.LEFT); + fBackgroundCustomRadioButton.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.custom")); //$NON-NLS-1$ + fBackgroundCustomRadioButton + .addSelectionListener(backgroundSelectionListener); + fBackgroundColorEditor = new ColorEditor(backgroundComposite); + fBackgroundColorButton = fBackgroundColorEditor.getButton(); + Label label = new Label(colorComposite, SWT.LEFT); + label.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.foreground")); //$NON-NLS-1$ + label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + Composite editorComposite = new Composite(colorComposite, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.numColumns = 2; + layout.marginHeight = 0; + layout.marginWidth = 0; + editorComposite.setLayout(layout); + GridData gd = new GridData(GridData.FILL_BOTH); + editorComposite.setLayoutData(gd); + fSyntaxColorList = new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL + | SWT.BORDER); + gd = new GridData(GridData.FILL_BOTH); + gd.heightHint = convertHeightInCharsToPixels(5); + fSyntaxColorList.setLayoutData(gd); + Composite stylesComposite = new Composite(editorComposite, SWT.NONE); + layout = new GridLayout(); + layout.marginHeight = 0; + layout.marginWidth = 0; + layout.numColumns = 2; + stylesComposite.setLayout(layout); + stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); + label = new Label(stylesComposite, SWT.LEFT); + label.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.color")); //$NON-NLS-1$ + gd = new GridData(); + gd.horizontalAlignment = GridData.BEGINNING; + label.setLayoutData(gd); + fSyntaxForegroundColorEditor = new ColorEditor(stylesComposite); + Button foregroundColorButton = fSyntaxForegroundColorEditor.getButton(); + gd = new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalAlignment = GridData.BEGINNING; + foregroundColorButton.setLayoutData(gd); + fBoldCheckBox = new Button(stylesComposite, SWT.CHECK); + fBoldCheckBox.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.bold")); //$NON-NLS-1$ + gd = new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalAlignment = GridData.BEGINNING; + gd.horizontalSpan = 2; + fBoldCheckBox.setLayoutData(gd); + label = new Label(colorComposite, SWT.LEFT); + label.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.preview")); //$NON-NLS-1$ + label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + Control previewer = createPreviewer(colorComposite); + gd = new GridData(GridData.FILL_BOTH); + gd.widthHint = convertWidthInCharsToPixels(20); + gd.heightHint = convertHeightInCharsToPixels(5); + previewer.setLayoutData(gd); + fSyntaxColorList.addSelectionListener(new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + // do nothing + } + + public void widgetSelected(SelectionEvent e) { + handleSyntaxColorListSelection(); + } + }); + foregroundColorButton.addSelectionListener(new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + // do nothing + } + + public void widgetSelected(SelectionEvent e) { + int i = fSyntaxColorList.getSelectionIndex(); + String key = fSyntaxColorListModel[i][1]; + PreferenceConverter.setValue(fOverlayStore, key, + fSyntaxForegroundColorEditor.getColorValue()); + } + }); + fBackgroundColorButton.addSelectionListener(new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + // do nothing + } + + public void widgetSelected(SelectionEvent e) { + PreferenceConverter.setValue(fOverlayStore, + PreferenceConstants.EDITOR_BACKGROUND_COLOR, + fBackgroundColorEditor.getColorValue()); + } + }); + fBoldCheckBox.addSelectionListener(new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + // do nothing + } + + public void widgetSelected(SelectionEvent e) { + int i = fSyntaxColorList.getSelectionIndex(); + String key = fSyntaxColorListModel[i][1]; + fOverlayStore + .setValue(key + BOLD, fBoldCheckBox.getSelection()); + } + }); + return colorComposite; + } + + private Control createPreviewer(Composite parent) { + Preferences coreStore = createTemporaryCorePreferenceStore(); + fJavaTextTools = new JavaTextTools(fOverlayStore, coreStore, false); + IPreferenceStore generalTextStore = EditorsUI.getPreferenceStore(); + IPreferenceStore store = new ChainedPreferenceStore( + new IPreferenceStore[] { + fOverlayStore, + new PreferencesAdapter( + createTemporaryCorePreferenceStore()), + generalTextStore }); + + fPreviewViewer = new JavaSourceViewer(parent, null, null, false, + SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER, store); + JavaTextTools tools = PHPeclipsePlugin.getDefault().getJavaTextTools(); + PHPSourceViewerConfiguration configuration = new PHPSourceViewerConfiguration( + tools.getColorManager(), store, null, + IPHPPartitions.PHP_PARTITIONING); + // PHPSourceViewerConfiguration configuration =new + // PHPSourceViewerConfiguration(fJavaTextTools, null, + // IPHPPartitions.PHP_PARTITIONING); + fPreviewViewer.configure(configuration); + + Font font = JFaceResources + .getFont(PreferenceConstants.EDITOR_TEXT_FONT); + fPreviewViewer.getTextWidget().setFont(font); + new JavaSourcePreviewerUpdater(fPreviewViewer, configuration, store); + fPreviewViewer.setEditable(false); + String content = loadPreviewContentFromFile("ColorSettingPreviewCode.txt"); //$NON-NLS-1$ + IDocument document = new Document(content); + fJavaTextTools.setupJavaDocumentPartitioner(document, + IPHPPartitions.PHP_PARTITIONING); + fPreviewViewer.setDocument(document); + return fPreviewViewer.getControl(); + } + + private Preferences createTemporaryCorePreferenceStore() { + Preferences result = new Preferences(); + result.setValue(COMPILER_TASK_TAGS, "TASK"); //$NON-NLS-1$ + return result; + } + + private Control createAppearancePage(Composite parent) { + Composite appearanceComposite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.numColumns = 2; + appearanceComposite.setLayout(layout); + String label = PreferencesMessages + .getString("JavaEditorPreferencePage.displayedTabWidth"); //$NON-NLS-1$ + addTextField(appearanceComposite, label, + PreferenceConstants.EDITOR_TAB_WIDTH, 3, 0, true); + label = PreferencesMessages + .getString("JavaEditorPreferencePage.printMarginColumn"); //$NON-NLS-1$ + addTextField( + appearanceComposite, + label, + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN, + 3, 0, true); + label = PreferencesMessages + .getString("JavaEditorPreferencePage.showOverviewRuler"); //$NON-NLS-1$ + addCheckBox( + appearanceComposite, + label, + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_OVERVIEW_RULER, + 0); + label = PreferencesMessages + .getString("JavaEditorPreferencePage.showLineNumbers"); //$NON-NLS-1$ + addCheckBox( + appearanceComposite, + label, + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER, + 0); + label = PreferencesMessages + .getString("JavaEditorPreferencePage.highlightMatchingBrackets"); //$NON-NLS-1$ + addCheckBox(appearanceComposite, label, + PreferenceConstants.EDITOR_MATCHING_BRACKETS, 0); + label = PreferencesMessages + .getString("JavaEditorPreferencePage.highlightCurrentLine"); //$NON-NLS-1$ + addCheckBox( + appearanceComposite, + label, + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE, + 0); + label = PreferencesMessages + .getString("JavaEditorPreferencePage.showPrintMargin"); //$NON-NLS-1$ + addCheckBox( + appearanceComposite, + label, + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN, + 0); + label = PreferencesMessages + .getString("JavaEditorPreferencePage.markOccurrences"); //$NON-NLS-1$ + // Button master= addCheckBox(appearanceComposite, label, + // PreferenceConstants.EDITOR_MARK_OCCURRENCES, 0); //$NON-NLS-1$ + label = PreferencesMessages + .getString("JavaEditorPreferencePage.stickyOccurrences"); //$NON-NLS-1$ + // fStickyOccurrencesButton= addCheckBox(appearanceComposite, label, + // PreferenceConstants.EDITOR_STICKY_OCCURRENCES, 0); //$NON-NLS-1$ + // createDependency(master, fStickyOccurrencesButton); + Label l = new Label(appearanceComposite, SWT.LEFT); + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + gd.horizontalSpan = 2; + gd.heightHint = convertHeightInCharsToPixels(1) / 2; + l.setLayoutData(gd); + l = new Label(appearanceComposite, SWT.LEFT); + l.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.appearanceOptions")); //$NON-NLS-1$ + gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + gd.horizontalSpan = 2; + l.setLayoutData(gd); + Composite editorComposite = new Composite(appearanceComposite, SWT.NONE); + layout = new GridLayout(); + layout.numColumns = 2; + layout.marginHeight = 0; + layout.marginWidth = 0; + editorComposite.setLayout(layout); + gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL + | GridData.FILL_VERTICAL); + gd.horizontalSpan = 2; + editorComposite.setLayoutData(gd); + fAppearanceColorList = new List(editorComposite, SWT.SINGLE + | SWT.V_SCROLL | SWT.BORDER); + gd = new GridData(GridData.VERTICAL_ALIGN_BEGINNING + | GridData.FILL_HORIZONTAL); + gd.heightHint = convertHeightInCharsToPixels(8); + fAppearanceColorList.setLayoutData(gd); + Composite stylesComposite = new Composite(editorComposite, SWT.NONE); + layout = new GridLayout(); + layout.marginHeight = 0; + layout.marginWidth = 0; + layout.numColumns = 2; + stylesComposite.setLayout(layout); + stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); + l = new Label(stylesComposite, SWT.LEFT); + l.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.color")); //$NON-NLS-1$ + gd = new GridData(); + gd.horizontalAlignment = GridData.BEGINNING; + l.setLayoutData(gd); + fAppearanceColorEditor = new ColorEditor(stylesComposite); + Button foregroundColorButton = fAppearanceColorEditor.getButton(); + gd = new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalAlignment = GridData.BEGINNING; + foregroundColorButton.setLayoutData(gd); + fAppearanceColorList.addSelectionListener(new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + // do nothing + } + + public void widgetSelected(SelectionEvent e) { + handleAppearanceColorListSelection(); + } + }); + foregroundColorButton.addSelectionListener(new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + // do nothing + } + + public void widgetSelected(SelectionEvent e) { + int i = fAppearanceColorList.getSelectionIndex(); + String key = fAppearanceColorListModel[i][1]; + PreferenceConverter.setValue(fOverlayStore, key, + fAppearanceColorEditor.getColorValue()); + } + }); + return appearanceComposite; + } + + // private Control createAnnotationsPage(Composite parent) { + // Composite composite = new Composite(parent, SWT.NULL); + // GridLayout layout = new GridLayout(); + // layout.numColumns = 2; + // composite.setLayout(layout); + // String text = PreferencesMessages + // .getString("JavaEditorPreferencePage.analyseAnnotationsWhileTyping"); + // //$NON-NLS-1$ + // addCheckBox(composite, text, + // PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, 0); + // text = PreferencesMessages + // .getString("JavaEditorPreferencePage.showQuickFixables"); //$NON-NLS-1$ + // addCheckBox(composite, text, + // PreferenceConstants.EDITOR_CORRECTION_INDICATION, 0); + // addFiller(composite); + // Label label = new Label(composite, SWT.LEFT); + // label.setText(PreferencesMessages + // .getString("JavaEditorPreferencePage.annotationPresentationOptions")); + // //$NON-NLS-1$ + // GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + // gd.horizontalSpan = 2; + // label.setLayoutData(gd); + // Composite editorComposite = new Composite(composite, SWT.NONE); + // layout = new GridLayout(); + // layout.numColumns = 2; + // layout.marginHeight = 0; + // layout.marginWidth = 0; + // editorComposite.setLayout(layout); + // gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL | + // GridData.FILL_VERTICAL); + // gd.horizontalSpan = 2; + // editorComposite.setLayoutData(gd); + // fAnnotationList = new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL + // | SWT.BORDER); + // gd = new GridData(GridData.VERTICAL_ALIGN_BEGINNING + // | GridData.FILL_HORIZONTAL); + // gd.heightHint = convertHeightInCharsToPixels(10); + // fAnnotationList.setLayoutData(gd); + // Composite optionsComposite = new Composite(editorComposite, SWT.NONE); + // layout = new GridLayout(); + // layout.marginHeight = 0; + // layout.marginWidth = 0; + // layout.numColumns = 2; + // optionsComposite.setLayout(layout); + // optionsComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); + // fShowInTextCheckBox = new Button(optionsComposite, SWT.CHECK); + // fShowInTextCheckBox.setText(PreferencesMessages + // .getString("JavaEditorPreferencePage.annotations.showInText")); + // //$NON-NLS-1$ + // gd = new GridData(GridData.FILL_HORIZONTAL); + // gd.horizontalAlignment = GridData.BEGINNING; + // gd.horizontalSpan = 2; + // fShowInTextCheckBox.setLayoutData(gd); + // fDecorationStyleCombo = new Combo(optionsComposite, SWT.READ_ONLY); + // for (int i = 0; i < fAnnotationDecorationListModel.length; i++) + // fDecorationStyleCombo.add(fAnnotationDecorationListModel[i][0]); + // gd = new GridData(GridData.FILL_HORIZONTAL); + // gd.horizontalAlignment = GridData.BEGINNING; + // gd.horizontalSpan = 2; + // gd.horizontalIndent = 20; + // fDecorationStyleCombo.setLayoutData(gd); + // fHighlightInTextCheckBox = new Button(optionsComposite, SWT.CHECK); + // fHighlightInTextCheckBox.setText(PreferencesMessages + // .getString("TextEditorPreferencePage.annotations.highlightInText")); + // //$NON-NLS-1$ + // gd = new GridData(GridData.FILL_HORIZONTAL); + // gd.horizontalAlignment = GridData.BEGINNING; + // gd.horizontalSpan = 2; + // fHighlightInTextCheckBox.setLayoutData(gd); + // fShowInOverviewRulerCheckBox = new Button(optionsComposite, SWT.CHECK); + // fShowInOverviewRulerCheckBox.setText(PreferencesMessages + // .getString("JavaEditorPreferencePage.annotations.showInOverviewRuler")); + // //$NON-NLS-1$ + // gd = new GridData(GridData.FILL_HORIZONTAL); + // gd.horizontalAlignment = GridData.BEGINNING; + // gd.horizontalSpan = 2; + // fShowInOverviewRulerCheckBox.setLayoutData(gd); + // fShowInVerticalRulerCheckBox = new Button(optionsComposite, SWT.CHECK); + // fShowInVerticalRulerCheckBox.setText(PreferencesMessages + // .getString("JavaEditorPreferencePage.annotations.showInVerticalRuler")); + // //$NON-NLS-1$ + // gd = new GridData(GridData.FILL_HORIZONTAL); + // gd.horizontalAlignment = GridData.BEGINNING; + // gd.horizontalSpan = 2; + // fShowInVerticalRulerCheckBox.setLayoutData(gd); + // label = new Label(optionsComposite, SWT.LEFT); + // label.setText(PreferencesMessages + // .getString("JavaEditorPreferencePage.annotations.color")); //$NON-NLS-1$ + // gd = new GridData(); + // gd.horizontalAlignment = GridData.BEGINNING; + // label.setLayoutData(gd); + // fAnnotationForegroundColorEditor = new ColorEditor(optionsComposite); + // Button foregroundColorButton = + // fAnnotationForegroundColorEditor.getButton(); + // gd = new GridData(GridData.FILL_HORIZONTAL); + // gd.horizontalAlignment = GridData.BEGINNING; + // foregroundColorButton.setLayoutData(gd); + // fAnnotationList.addSelectionListener(new SelectionListener() { + // public void widgetDefaultSelected(SelectionEvent e) { + // // do nothing + // } + // public void widgetSelected(SelectionEvent e) { + // handleAnnotationListSelection(); + // } + // }); + // fShowInTextCheckBox.addSelectionListener(new SelectionListener() { + // public void widgetDefaultSelected(SelectionEvent e) { + // // do nothing + // } + // public void widgetSelected(SelectionEvent e) { + // int i = fAnnotationList.getSelectionIndex(); + // String key = fAnnotationColorListModel[i][2]; + // fOverlayStore.setValue(key, fShowInTextCheckBox.getSelection()); + // String decorationKey = fAnnotationColorListModel[i][6]; + // fDecorationStyleCombo.setEnabled(decorationKey != null + // && fShowInTextCheckBox.getSelection()); + // } + // }); + // fHighlightInTextCheckBox.addSelectionListener(new SelectionListener() { + // public void widgetDefaultSelected(SelectionEvent e) { + // // do nothing + // } + // public void widgetSelected(SelectionEvent e) { + // int i = fAnnotationList.getSelectionIndex(); + // String key = fAnnotationColorListModel[i][4]; + // fOverlayStore.setValue(key, fHighlightInTextCheckBox.getSelection()); + // } + // }); + // fShowInOverviewRulerCheckBox.addSelectionListener(new SelectionListener() + // { + // public void widgetDefaultSelected(SelectionEvent e) { + // // do nothing + // } + // public void widgetSelected(SelectionEvent e) { + // int i = fAnnotationList.getSelectionIndex(); + // String key = fAnnotationColorListModel[i][3]; + // fOverlayStore + // .setValue(key, fShowInOverviewRulerCheckBox.getSelection()); + // } + // }); + // fShowInVerticalRulerCheckBox.addSelectionListener(new SelectionListener() + // { + // public void widgetDefaultSelected(SelectionEvent e) { + // // do nothing + // } + // public void widgetSelected(SelectionEvent e) { + // int i = fAnnotationList.getSelectionIndex(); + // String key = fAnnotationColorListModel[i][5]; + // fOverlayStore + // .setValue(key, fShowInVerticalRulerCheckBox.getSelection()); + // } + // }); + // foregroundColorButton.addSelectionListener(new SelectionListener() { + // public void widgetDefaultSelected(SelectionEvent e) { + // // do nothing + // } + // public void widgetSelected(SelectionEvent e) { + // int i = fAnnotationList.getSelectionIndex(); + // String key = fAnnotationColorListModel[i][1]; + // PreferenceConverter.setValue(fOverlayStore, key, + // fAnnotationForegroundColorEditor.getColorValue()); + // } + // }); + // fDecorationStyleCombo.addSelectionListener(new SelectionListener() { + // /** + // * {@inheritdoc} + // */ + // public void widgetDefaultSelected(SelectionEvent e) { + // // do nothing + // } + // /** + // * {@inheritdoc} + // */ + // public void widgetSelected(SelectionEvent e) { + // int i = fAnnotationList.getSelectionIndex(); + // String key = fAnnotationColorListModel[i][6]; + // if (key != null) { + // for (int j = 0; j < fAnnotationDecorationListModel.length; j++) { + // if (fAnnotationDecorationListModel[j][0] + // .equals(fDecorationStyleCombo.getText())) { + // fOverlayStore.setValue(key, fAnnotationDecorationListModel[j][1]); + // break; + // } + // } + // } + // } + // }); + // return composite; + // } + private String[][] createAnnotationTypeListModel( + MarkerAnnotationPreferences preferences) { + ArrayList listModelItems = new ArrayList(); + SortedSet sortedPreferences = new TreeSet(new Comparator() { + /* + * @see java.util.Comparator#compare(java.lang.Object, + * java.lang.Object) + */ + public int compare(Object o1, Object o2) { + if (!(o2 instanceof AnnotationPreference)) + return -1; + if (!(o1 instanceof AnnotationPreference)) + return 1; + AnnotationPreference a1 = (AnnotationPreference) o1; + AnnotationPreference a2 = (AnnotationPreference) o2; + return Collator.getInstance().compare(a1.getPreferenceLabel(), + a2.getPreferenceLabel()); + } + }); + sortedPreferences.addAll(preferences.getAnnotationPreferences()); + Iterator e = sortedPreferences.iterator(); + while (e.hasNext()) { + AnnotationPreference info = (AnnotationPreference) e.next(); + listModelItems.add(new String[] { info.getPreferenceLabel(), + info.getColorPreferenceKey(), info.getTextPreferenceKey(), + info.getOverviewRulerPreferenceKey(), + info.getHighlightPreferenceKey(), + info.getVerticalRulerPreferenceKey(), + info.getTextStylePreferenceKey() }); + } + String[][] items = new String[listModelItems.size()][]; + listModelItems.toArray(items); + return items; + } + + private Control createTypingPage(Composite parent) { + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.numColumns = 1; + composite.setLayout(layout); + String label; + // label = PreferencesMessages + // .getString("JavaEditorPreferencePage.overwriteMode"); + // //$NON-NLS-1$ + // addCheckBox(composite, label, + // PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE, 1); + // addFiller(composite); + // + // label = PreferencesMessages + // .getString("JavaEditorPreferencePage.smartHomeEnd"); + // //$NON-NLS-1$ + // addCheckBox(composite, label, + // PreferenceConstants.EDITOR_SMART_HOME_END, 1); + // + // label = PreferencesMessages + // .getString("JavaEditorPreferencePage.subWordNavigation"); + // //$NON-NLS-1$ + // addCheckBox(composite, label, + // PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION, 1); + // addFiller(composite); + Group group = new Group(composite, SWT.NONE); + layout = new GridLayout(); + layout.numColumns = 2; + group.setLayout(layout); + group.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.typing.description")); //$NON-NLS-1$ + + label = PreferencesMessages + .getString("JavaEditorPreferencePage.wrapWords");//$NON-NLS-1$ + addCheckBox(group, label, PreferenceConstants.EDITOR_WRAP_WORDS, 1); + + label = PreferencesMessages + .getString("JavaEditorPreferencePage.wrapStringsDQ");//$NON-NLS-1$ + Button button = addCheckBox(group, label, + PreferenceConstants.EDITOR_WRAP_STRINGS_DQ, 1); + + label = PreferencesMessages + .getString("JavaEditorPreferencePage.escapeStringsDQ");//$NON-NLS-1$ + fEscapeStringsButtonDQ = addCheckBox(group, label, + PreferenceConstants.EDITOR_ESCAPE_STRINGS_DQ, 1); + createDependency(button, fEscapeStringsButtonDQ); + + label = PreferencesMessages + .getString("JavaEditorPreferencePage.wrapStringsSQ");//$NON-NLS-1$ + addCheckBox(group, label, PreferenceConstants.EDITOR_WRAP_STRINGS_SQ, 1); + + label = PreferencesMessages + .getString("JavaEditorPreferencePage.escapeStringsSQ"); + //$NON-NLS-1$ + fEscapeStringsButtonSQ = addCheckBox(group, label, + PreferenceConstants.EDITOR_ESCAPE_STRINGS_SQ, 1); + createDependency(button, fEscapeStringsButtonSQ); + + label = PreferencesMessages + .getString("JavaEditorPreferencePage.smartPaste"); + //$NON-NLS-1$ + addCheckBox(group, label, PreferenceConstants.EDITOR_SMART_PASTE, 1); + + label = PreferencesMessages + .getString("JavaEditorPreferencePage.insertSpaceForTabs"); + //$NON-NLS-1$ + addCheckBox(group, label, PreferenceConstants.EDITOR_SPACES_FOR_TABS, 1); + + label = PreferencesMessages + .getString("JavaEditorPreferencePage.closeStringsDQ"); + //$NON-NLS-1$ + addCheckBox(group, label, + PreferenceConstants.EDITOR_CLOSE_STRINGS_DQ_PHP, 1); + label = PreferencesMessages + .getString("JavaEditorPreferencePage.closeStringsSQ"); + //$NON-NLS-1$ + addCheckBox(group, label, + PreferenceConstants.EDITOR_CLOSE_STRINGS_SQ_PHP, 1); + + label = PreferencesMessages + .getString("JavaEditorPreferencePage.closeBrackets"); + //$NON-NLS-1$ + addCheckBox(group, label, + PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP, 1); + + // label = PreferencesMessages + // .getString("JavaEditorPreferencePage.closeBraces"); + // //$NON-NLS-1$ + // addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_BRACES, + // 1); + + label = PreferencesMessages + .getString("JavaEditorPreferencePage.closeJavaDocs"); + //$NON-NLS-1$ + button = addCheckBox(group, label, + PreferenceConstants.EDITOR_CLOSE_JAVADOCS, 1); + label = PreferencesMessages + .getString("JavaEditorPreferencePage.formatJavaDocs"); + //$NON-NLS-1$ + button = addCheckBox(group, label, + PreferenceConstants.EDITOR_FORMAT_JAVADOCS, 1); + + label = PreferencesMessages + .getString("JavaEditorPreferencePage.p_rtrim_on_save"); + addCheckBox(group, label, PreferenceConstants.EDITOR_P_RTRIM_ON_SAVE, 1); + // + // label = PreferencesMessages + // .getString("JavaEditorPreferencePage.addJavaDocTags"); + // //$NON-NLS-1$ + // fAddJavaDocTagsButton = addCheckBox(group, label, + // PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, 1); + // createDependency(button, fAddJavaDocTagsButton); + return composite; + } + + private void addFiller(Composite composite) { + Label filler = new Label(composite, SWT.LEFT); + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + gd.horizontalSpan = 2; + gd.heightHint = convertHeightInCharsToPixels(1) / 2; + filler.setLayoutData(gd); + } + + private static void indent(Control control) { + GridData gridData = new GridData(); + gridData.horizontalIndent = 20; + control.setLayoutData(gridData); + } + + private static void createDependency(final Button master, + final Control slave) { + indent(slave); + master.addSelectionListener(new SelectionListener() { + public void widgetSelected(SelectionEvent e) { + slave.setEnabled(master.getSelection()); + } + + public void widgetDefaultSelected(SelectionEvent e) { + } + }); + } + + private void addCompletionRadioButtons(Composite contentAssistComposite) { + Composite completionComposite = new Composite(contentAssistComposite, + SWT.NONE); + GridData ccgd = new GridData(); + ccgd.horizontalSpan = 2; + completionComposite.setLayoutData(ccgd); + GridLayout ccgl = new GridLayout(); + ccgl.marginWidth = 0; + ccgl.numColumns = 2; + completionComposite.setLayout(ccgl); + // SelectionListener completionSelectionListener= new SelectionAdapter() + // { + // public void widgetSelected(SelectionEvent e) { + // boolean insert= fCompletionInsertsRadioButton.getSelection(); + // fOverlayStore.setValue(PreferenceConstants.CODEASSIST_INSERT_COMPLETION, + // insert); + // } + // }; + // + // fCompletionInsertsRadioButton= new Button(completionComposite, + // SWT.RADIO + // | SWT.LEFT); + // fCompletionInsertsRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.completionInserts")); + // //$NON-NLS-1$ + // fCompletionInsertsRadioButton.setLayoutData(new GridData()); + // fCompletionInsertsRadioButton.addSelectionListener(completionSelectionListener); + // + // fCompletionOverwritesRadioButton= new Button(completionComposite, + // SWT.RADIO | SWT.LEFT); + // fCompletionOverwritesRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.completionOverwrites")); + // //$NON-NLS-1$ + // fCompletionOverwritesRadioButton.setLayoutData(new GridData()); + // fCompletionOverwritesRadioButton.addSelectionListener(completionSelectionListener); + } + + private Control createNavigationPage(Composite parent) { + Composite composite = new Composite(parent, SWT.NULL); + GridLayout layout = new GridLayout(); + layout.numColumns = 2; + composite.setLayout(layout); + String text = PreferencesMessages + .getString("JavaEditorPreferencePage.navigation.browserLikeLinks"); + //$NON-NLS-1$ + fBrowserLikeLinksCheckBox = addCheckBox(composite, text, + PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS, 0); + fBrowserLikeLinksCheckBox.addSelectionListener(new SelectionListener() { + public void widgetSelected(SelectionEvent e) { + boolean state = fBrowserLikeLinksCheckBox.getSelection(); + fBrowserLikeLinksKeyModifierText.setEnabled(state); + handleBrowserLikeLinksKeyModifierModified(); + } + + public void widgetDefaultSelected(SelectionEvent e) { + } + }); + // Text field for modifier string + text = PreferencesMessages + .getString("JavaEditorPreferencePage.navigation.browserLikeLinksKeyModifier"); + //$NON-NLS-1$ + fBrowserLikeLinksKeyModifierText = addTextField(composite, text, + PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER, 20, + 0, false); + fBrowserLikeLinksKeyModifierText.setTextLimit(Text.LIMIT); + + if (computeStateMask(fOverlayStore + .getString(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER)) == -1) { + // Fix possible illegal modifier string + int stateMask = fOverlayStore + .getInt(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK); + if (stateMask == -1) + fBrowserLikeLinksKeyModifierText.setText(""); //$NON-NLS-1$ + else + fBrowserLikeLinksKeyModifierText.setText(EditorUtility + .getModifierString(stateMask)); + } + fBrowserLikeLinksKeyModifierText.addKeyListener(new KeyListener() { + private boolean isModifierCandidate; + + public void keyPressed(KeyEvent e) { + isModifierCandidate = e.keyCode > 0 && e.character == 0 + && e.stateMask == 0; + } + + public void keyReleased(KeyEvent e) { + if (isModifierCandidate && e.stateMask > 0 + && e.stateMask == e.stateMask && e.character == 0) {// && + // e.time + // -time + // < + // 1000) + // { + String modifierString = fBrowserLikeLinksKeyModifierText + .getText(); + Point selection = fBrowserLikeLinksKeyModifierText + .getSelection(); + int i = selection.x - 1; + while (i > -1 + && Character.isWhitespace(modifierString.charAt(i))) { + i--; + } + boolean needsPrefixDelimiter = i > -1 + && !String.valueOf(modifierString.charAt(i)) + .equals(DELIMITER); + + i = selection.y; + while (i < modifierString.length() + && Character.isWhitespace(modifierString.charAt(i))) { + i++; + } + boolean needsPostfixDelimiter = i < modifierString.length() + && !String.valueOf(modifierString.charAt(i)) + .equals(DELIMITER); + + String insertString; + + if (needsPrefixDelimiter && needsPostfixDelimiter) + insertString = PreferencesMessages + .getFormattedString( + "JavaEditorPreferencePage.navigation.insertDelimiterAndModifierAndDelimiter", + new String[] { Action + .findModifierString(e.stateMask) }); //$NON-NLS-1$ + else if (needsPrefixDelimiter) + insertString = PreferencesMessages + .getFormattedString( + "JavaEditorPreferencePage.navigation.insertDelimiterAndModifier", + new String[] { Action + .findModifierString(e.stateMask) }); //$NON-NLS-1$ + else if (needsPostfixDelimiter) + insertString = PreferencesMessages + .getFormattedString( + "JavaEditorPreferencePage.navigation.insertModifierAndDelimiter", + new String[] { Action + .findModifierString(e.stateMask) }); //$NON-NLS-1$ + else + insertString = Action.findModifierString(e.stateMask); + + fBrowserLikeLinksKeyModifierText.insert(insertString); + } + } + }); + + fBrowserLikeLinksKeyModifierText + .addModifyListener(new ModifyListener() { + public void modifyText(ModifyEvent e) { + handleBrowserLikeLinksKeyModifierModified(); + } + }); + return composite; + } + + private void handleBrowserLikeLinksKeyModifierModified() { + String modifiers = fBrowserLikeLinksKeyModifierText.getText(); + int stateMask = computeStateMask(modifiers); + if (fBrowserLikeLinksCheckBox.getSelection() + && (stateMask == -1 || (stateMask & SWT.SHIFT) != 0)) { + if (stateMask == -1) + fBrowserLikeLinksKeyModifierStatus = new StatusInfo( + IStatus.ERROR, + PreferencesMessages + .getFormattedString( + "JavaEditorPreferencePage.navigation.modifierIsNotValid", modifiers)); //$NON-NLS-1$ + else + fBrowserLikeLinksKeyModifierStatus = new StatusInfo( + IStatus.ERROR, + PreferencesMessages + .getString("JavaEditorPreferencePage.navigation.shiftIsDisabled")); + //$NON-NLS-1$ + setValid(false); + StatusUtil.applyToStatusLine(this, + fBrowserLikeLinksKeyModifierStatus); + } else { + fBrowserLikeLinksKeyModifierStatus = new StatusInfo(); + updateStatus(fBrowserLikeLinksKeyModifierStatus); + } + } + + private IStatus getBrowserLikeLinksKeyModifierStatus() { + if (fBrowserLikeLinksKeyModifierStatus == null) + fBrowserLikeLinksKeyModifierStatus = new StatusInfo(); + return fBrowserLikeLinksKeyModifierStatus; + } + + /** + * 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 + */ + private 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; + } + + /* + * @see PreferencePage#createContents(Composite) + */ + protected Control createContents(Composite parent) { + initializeDefaultColors(); + fFoldingConfigurationBlock = new FoldingConfigurationBlock( + fOverlayStore); + fOverlayStore.load(); + fOverlayStore.start(); + TabFolder folder = new TabFolder(parent, SWT.NONE); + folder.setLayout(new TabFolderLayout()); + folder.setLayoutData(new GridData(GridData.FILL_BOTH)); + TabItem item = new TabItem(folder, SWT.NONE); + item.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.general")); //$NON-NLS-1$ + item.setControl(createAppearancePage(folder)); + item = new TabItem(folder, SWT.NONE); + item.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.colors")); //$NON-NLS-1$ + item.setControl(createSyntaxPage(folder)); + + // item = new TabItem(folder, SWT.NONE); + // item.setText(PreferencesMessages + // .getString("JavaEditorPreferencePage.annotationsTab.title")); + // //$NON-NLS-1$ + // item.setControl(createAnnotationsPage(folder)); + item = new TabItem(folder, SWT.NONE); + item.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.typing.tabTitle")); + //$NON-NLS-1$ + item.setControl(createTypingPage(folder)); + + item = new TabItem(folder, SWT.NONE); + item.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.hoverTab.title")); + //$NON-NLS-1$ + fJavaEditorHoverConfigurationBlock = new JavaEditorHoverConfigurationBlock( + this, fOverlayStore); + item.setControl(fJavaEditorHoverConfigurationBlock + .createControl(folder)); + item = new TabItem(folder, SWT.NONE); + item.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.navigationTab.title")); + // //$NON-NLS-1$ + item.setControl(createNavigationPage(folder)); + item = new TabItem(folder, SWT.NONE); + item.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.folding.title")); //$NON-NLS-1$ + item.setControl(fFoldingConfigurationBlock.createControl(folder)); + + initialize(); + Dialog.applyDialogFont(folder); + return folder; + } + + private void initialize() { + initializeFields(); + for (int i = 0; i < fSyntaxColorListModel.length; i++) + fSyntaxColorList.add(fSyntaxColorListModel[i][0]); + fSyntaxColorList.getDisplay().asyncExec(new Runnable() { + public void run() { + if (fSyntaxColorList != null && !fSyntaxColorList.isDisposed()) { + fSyntaxColorList.select(0); + handleSyntaxColorListSelection(); + } + } + }); + for (int i = 0; i < fAppearanceColorListModel.length; i++) + fAppearanceColorList.add(fAppearanceColorListModel[i][0]); + fAppearanceColorList.getDisplay().asyncExec(new Runnable() { + public void run() { + if (fAppearanceColorList != null + && !fAppearanceColorList.isDisposed()) { + fAppearanceColorList.select(0); + handleAppearanceColorListSelection(); + } + } + }); + // for (int i = 0; i < fAnnotationColorListModel.length; i++) + // fAnnotationList.add(fAnnotationColorListModel[i][0]); + // fAnnotationList.getDisplay().asyncExec(new Runnable() { + // public void run() { + // if (fAnnotationList != null && !fAnnotationList.isDisposed()) { + // fAnnotationList.select(0); + // handleAnnotationListSelection(); + // } + // } + // }); + // for (int i= 0; i < fContentAssistColorListModel.length; i++) + // fContentAssistColorList.add(fContentAssistColorListModel[i][0]); + // fContentAssistColorList.getDisplay().asyncExec(new Runnable() { + // public void run() { + // if (fContentAssistColorList != null && + // !fContentAssistColorList.isDisposed()) { + // fContentAssistColorList.select(0); + // handleContentAssistColorListSelection(); + // } + // } + // }); + fFoldingConfigurationBlock.initialize(); + } + + private void initializeFields() { + Iterator e = fColorButtons.keySet().iterator(); + while (e.hasNext()) { + ColorEditor c = (ColorEditor) e.next(); + String key = (String) fColorButtons.get(c); + RGB rgb = PreferenceConverter.getColor(fOverlayStore, key); + c.setColorValue(rgb); + } + e = fCheckBoxes.keySet().iterator(); + while (e.hasNext()) { + Button b = (Button) e.next(); + String key = (String) fCheckBoxes.get(b); + b.setSelection(fOverlayStore.getBoolean(key)); + } + e = fTextFields.keySet().iterator(); + while (e.hasNext()) { + Text t = (Text) e.next(); + String key = (String) fTextFields.get(t); + t.setText(fOverlayStore.getString(key)); + } + RGB rgb = PreferenceConverter.getColor(fOverlayStore, + PreferenceConstants.EDITOR_BACKGROUND_COLOR); + fBackgroundColorEditor.setColorValue(rgb); + boolean default_ = fOverlayStore + .getBoolean(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR); + fBackgroundDefaultRadioButton.setSelection(default_); + fBackgroundCustomRadioButton.setSelection(!default_); + fBackgroundColorButton.setEnabled(!default_); + boolean closeJavaDocs = fOverlayStore + .getBoolean(PreferenceConstants.EDITOR_CLOSE_JAVADOCS); + // fAddJavaDocTagsButton.setEnabled(closeJavaDocs); + fEscapeStringsButtonDQ.setEnabled(fOverlayStore + .getBoolean(PreferenceConstants.EDITOR_WRAP_STRINGS_DQ)); + fEscapeStringsButtonSQ.setEnabled(fOverlayStore + .getBoolean(PreferenceConstants.EDITOR_WRAP_STRINGS_SQ)); + // boolean fillMethodArguments= + // fOverlayStore.getBoolean(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES); + // fGuessMethodArgumentsButton.setEnabled(fillMethodArguments); + // boolean completionInserts= + // fOverlayStore.getBoolean(PreferenceConstants.CODEASSIST_INSERT_COMPLETION); + // fCompletionInsertsRadioButton.setSelection(completionInserts); + // fCompletionOverwritesRadioButton.setSelection(! completionInserts); + // + fBrowserLikeLinksKeyModifierText.setEnabled(fBrowserLikeLinksCheckBox + .getSelection()); + // boolean markOccurrences= + // fOverlayStore.getBoolean(PreferenceConstants.EDITOR_MARK_OCCURRENCES); + // fStickyOccurrencesButton.setEnabled(markOccurrences); + updateAutoactivationControls(); + } + + private void initializeDefaultColors() { + if (!getPreferenceStore().contains( + PreferenceConstants.EDITOR_BACKGROUND_COLOR)) { + RGB rgb = getControl().getDisplay().getSystemColor( + SWT.COLOR_LIST_BACKGROUND).getRGB(); + PreferenceConverter.setDefault(fOverlayStore, + PreferenceConstants.EDITOR_BACKGROUND_COLOR, rgb); + PreferenceConverter.setDefault(getPreferenceStore(), + PreferenceConstants.EDITOR_BACKGROUND_COLOR, rgb); + } + if (!getPreferenceStore().contains( + PreferenceConstants.EDITOR_FOREGROUND_COLOR)) { + RGB rgb = getControl().getDisplay().getSystemColor( + SWT.COLOR_LIST_FOREGROUND).getRGB(); + PreferenceConverter.setDefault(fOverlayStore, + PreferenceConstants.EDITOR_FOREGROUND_COLOR, rgb); + PreferenceConverter.setDefault(getPreferenceStore(), + PreferenceConstants.EDITOR_FOREGROUND_COLOR, rgb); + } + } + + private void updateAutoactivationControls() { + // boolean autoactivation= + // fOverlayStore.getBoolean(PreferenceConstants.CODEASSIST_AUTOACTIVATION); + // fAutoInsertDelayText.setEnabled(autoactivation); + // fAutoInsertDelayLabel.setEnabled(autoactivation); + // fAutoInsertJavaTriggerText.setEnabled(autoactivation); + // fAutoInsertJavaTriggerLabel.setEnabled(autoactivation); + // + // fAutoInsertJavaDocTriggerText.setEnabled(autoactivation); + // fAutoInsertJavaDocTriggerLabel.setEnabled(autoactivation); + } + + /* + * @see PreferencePage#performOk() + */ + public boolean performOk() { + // fJavaEditorHoverConfigurationBlock.performOk(); + fFoldingConfigurationBlock.performOk(); + fOverlayStore + .setValue( + PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK, + computeStateMask(fBrowserLikeLinksKeyModifierText + .getText())); + fOverlayStore.propagate(); + PHPeclipsePlugin.getDefault().savePluginPreferences(); + return true; + } + + /* + * @see PreferencePage#performDefaults() + */ + protected void performDefaults() { + fOverlayStore.loadDefaults(); + initializeFields(); + handleSyntaxColorListSelection(); + handleAppearanceColorListSelection(); + // handleAnnotationListSelection(); + // handleContentAssistColorListSelection(); + // fJavaEditorHoverConfigurationBlock.performDefaults(); + fFoldingConfigurationBlock.performDefaults(); + super.performDefaults(); + fPreviewViewer.invalidateTextPresentation(); + } + + /* + * @see DialogPage#dispose() + */ + public void dispose() { + fFoldingConfigurationBlock.dispose(); + + if (fJavaTextTools != null) { + fJavaTextTools.dispose(); + fJavaTextTools = null; + } + if (fOverlayStore != null) { + fOverlayStore.stop(); + fOverlayStore = null; + } + if (fBackgroundColor != null && !fBackgroundColor.isDisposed()) + fBackgroundColor.dispose(); + super.dispose(); + } + + private Button addCheckBox(Composite parent, String label, String key, + int indentation) { + Button checkBox = new Button(parent, SWT.CHECK); + checkBox.setText(label); + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.horizontalIndent = indentation; + gd.horizontalSpan = 2; + checkBox.setLayoutData(gd); + checkBox.addSelectionListener(fCheckBoxListener); + fCheckBoxes.put(checkBox, key); + return checkBox; + } + + private Text addTextField(Composite composite, String label, String key, + int textLimit, int indentation, boolean isNumber) { + return getTextControl(addLabelledTextField(composite, label, key, + textLimit, indentation, isNumber)); + } + + private static Label getLabelControl(Control[] labelledTextField) { + return (Label) labelledTextField[0]; + } + + private static Text getTextControl(Control[] labelledTextField) { + return (Text) labelledTextField[1]; + } + + /** + * Returns an array of size 2: - first element is of type Label- + * second element is of type Text Use + * getLabelControl and getTextControl to get + * the 2 controls. + */ + private Control[] addLabelledTextField(Composite composite, String label, + String key, int textLimit, int indentation, boolean isNumber) { + Label labelControl = new Label(composite, SWT.NONE); + labelControl.setText(label); + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.horizontalIndent = indentation; + labelControl.setLayoutData(gd); + Text textControl = new Text(composite, SWT.BORDER | SWT.SINGLE); + gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.widthHint = convertWidthInCharsToPixels(textLimit + 1); + textControl.setLayoutData(gd); + textControl.setTextLimit(textLimit); + fTextFields.put(textControl, key); + if (isNumber) { + fNumberFields.add(textControl); + textControl.addModifyListener(fNumberFieldListener); + } else { + textControl.addModifyListener(fTextFieldListener); + } + return new Control[] { labelControl, textControl }; + } + + private String loadPreviewContentFromFile(String filename) { + String line; + String separator = System.getProperty("line.separator"); //$NON-NLS-1$ + StringBuffer buffer = new StringBuffer(512); + BufferedReader reader = null; + try { + reader = new BufferedReader(new InputStreamReader(getClass() + .getResourceAsStream(filename))); + while ((line = reader.readLine()) != null) { + buffer.append(line); + buffer.append(separator); + } + } catch (IOException io) { + PHPeclipsePlugin.log(io); + } finally { + if (reader != null) { + try { + reader.close(); + } catch (IOException e) { + } + } + } + return buffer.toString(); + } + + private void numberFieldChanged(Text textControl) { + String number = textControl.getText(); + IStatus status = validatePositiveNumber(number); + if (!status.matches(IStatus.ERROR)) + fOverlayStore.setValue((String) fTextFields.get(textControl), + number); + updateStatus(status); + } + + private IStatus validatePositiveNumber(String number) { + StatusInfo status = new StatusInfo(); + if (number.length() == 0) { + status.setError(PreferencesMessages + .getString("JavaEditorPreferencePage.empty_input")); //$NON-NLS-1$ + } else { + try { + int value = Integer.parseInt(number); + if (value < 0) + status.setError(PreferencesMessages.getFormattedString( + "JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$ + } catch (NumberFormatException e) { + status.setError(PreferencesMessages.getFormattedString( + "JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$ + } + } + return status; + } + + void updateStatus(IStatus status) { + if (!status.matches(IStatus.ERROR)) { + for (int i = 0; i < fNumberFields.size(); i++) { + Text text = (Text) fNumberFields.get(i); + IStatus s = validatePositiveNumber(text.getText()); + status = StatusUtil.getMoreSevere(s, status); + } + } + // status= + // StatusUtil.getMoreSevere(fJavaEditorHoverConfigurationBlock.getStatus(), + // status); + // status= + // StatusUtil.getMoreSevere(getBrowserLikeLinksKeyModifierStatus(), + // status); + setValid(!status.matches(IStatus.ERROR)); + StatusUtil.applyToStatusLine(this, status); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaPreferencesSettings.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaPreferencesSettings.java index 7f9f5ca..bbb7687 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaPreferencesSettings.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaPreferencesSettings.java @@ -17,48 +17,48 @@ import net.sourceforge.phpdt.internal.corext.util.CodeFormatterUtil; import net.sourceforge.phpdt.ui.PreferenceConstants; import org.eclipse.jface.preference.IPreferenceStore; - -public class JavaPreferencesSettings { - + +public class JavaPreferencesSettings { + public static CodeGenerationSettings getCodeGenerationSettings() { - IPreferenceStore store= PreferenceConstants.getPreferenceStore(); - - CodeGenerationSettings res= new CodeGenerationSettings(); - res.createComments= store.getBoolean(PreferenceConstants.CODEGEN_ADD_COMMENTS); - res.useKeywordThis= store.getBoolean(PreferenceConstants.CODEGEN_KEYWORD_THIS); -// res.importOrder= getImportOrderPreference(store); - res.importThreshold= getImportNumberThreshold(store); - res.tabWidth= CodeFormatterUtil.getTabWidth(); + IPreferenceStore store = PreferenceConstants.getPreferenceStore(); + + CodeGenerationSettings res = new CodeGenerationSettings(); + res.createComments = store + .getBoolean(PreferenceConstants.CODEGEN_ADD_COMMENTS); + res.useKeywordThis = store + .getBoolean(PreferenceConstants.CODEGEN_KEYWORD_THIS); + // res.importOrder= getImportOrderPreference(store); + res.importThreshold = getImportNumberThreshold(store); + res.tabWidth = CodeFormatterUtil.getTabWidth(); return res; } public static int getImportNumberThreshold(IPreferenceStore prefs) { - int threshold= prefs.getInt(PreferenceConstants.ORGIMPORTS_ONDEMANDTHRESHOLD); + int threshold = prefs + .getInt(PreferenceConstants.ORGIMPORTS_ONDEMANDTHRESHOLD); if (threshold < 0) { - threshold= Integer.MAX_VALUE; + threshold = Integer.MAX_VALUE; } return threshold; } + // public static String[] getImportOrderPreference(IPreferenceStore prefs) { + // String str= prefs.getString(PreferenceConstants.ORGIMPORTS_IMPORTORDER); + // if (str != null) { + // return unpackList(str, ";"); //$NON-NLS-1$ + // } + // return new String[0]; + // } -// public static String[] getImportOrderPreference(IPreferenceStore prefs) { -// String str= prefs.getString(PreferenceConstants.ORGIMPORTS_IMPORTORDER); -// if (str != null) { -// return unpackList(str, ";"); //$NON-NLS-1$ -// } -// return new String[0]; -// } - private static String[] unpackList(String str, String separator) { - StringTokenizer tok= new StringTokenizer(str, separator); //$NON-NLS-1$ - int nTokens= tok.countTokens(); - String[] res= new String[nTokens]; - for (int i= 0; i < nTokens; i++) { - res[i]= tok.nextToken().trim(); + StringTokenizer tok = new StringTokenizer(str, separator); //$NON-NLS-1$ + int nTokens = tok.countTokens(); + String[] res = new String[nTokens]; + for (int i = 0; i < nTokens; i++) { + res[i] = tok.nextToken().trim(); } return res; } - - -} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaSourcePreviewerUpdater.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaSourcePreviewerUpdater.java index c462288..5fedc3a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaSourcePreviewerUpdater.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaSourcePreviewerUpdater.java @@ -23,7 +23,6 @@ import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.graphics.Font; -//import net.sourceforge.phpdt.ui.text.JavaSourceViewerConfiguration; /** * Handles Java editor font changes for Java source preview viewers. @@ -31,30 +30,38 @@ import org.eclipse.swt.graphics.Font; * @since 3.0 */ class JavaSourcePreviewerUpdater { - + /** - * Creates a Java source preview updater for the given viewer, configuration and preference store. - * - * @param viewer the viewer - * @param configuration the configuration - * @param preferenceStore the preference store + * Creates a Java source preview updater for the given viewer, configuration + * and preference store. + * + * @param viewer + * the viewer + * @param configuration + * the configuration + * @param preferenceStore + * the preference store */ - JavaSourcePreviewerUpdater(final SourceViewer viewer, final PHPSourceViewerConfiguration configuration, final IPreferenceStore preferenceStore) { + JavaSourcePreviewerUpdater(final SourceViewer viewer, + final PHPSourceViewerConfiguration configuration, + final IPreferenceStore preferenceStore) { Assert.isNotNull(viewer); Assert.isNotNull(configuration); Assert.isNotNull(preferenceStore); - final IPropertyChangeListener fontChangeListener= new IPropertyChangeListener() { + final IPropertyChangeListener fontChangeListener = new IPropertyChangeListener() { /* * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { - if (event.getProperty().equals(PreferenceConstants.EDITOR_TEXT_FONT)) { - Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT); + if (event.getProperty().equals( + PreferenceConstants.EDITOR_TEXT_FONT)) { + Font font = JFaceResources + .getFont(PreferenceConstants.EDITOR_TEXT_FONT); viewer.getTextWidget().setFont(font); } } }; - final IPropertyChangeListener propertyChangeListener= new IPropertyChangeListener() { + final IPropertyChangeListener propertyChangeListener = new IPropertyChangeListener() { /* * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent) */ @@ -70,8 +77,10 @@ class JavaSourcePreviewerUpdater { * @see org.eclipse.swt.events.DisposeListener#widgetDisposed(org.eclipse.swt.events.DisposeEvent) */ public void widgetDisposed(DisposeEvent e) { - preferenceStore.removePropertyChangeListener(propertyChangeListener); - JFaceResources.getFontRegistry().removeListener(fontChangeListener); + preferenceStore + .removePropertyChangeListener(propertyChangeListener); + JFaceResources.getFontRegistry().removeListener( + fontChangeListener); } }); JFaceResources.getFontRegistry().addListener(fontChangeListener); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MarkOccurrencesConfigurationBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MarkOccurrencesConfigurationBlock.java index dab1aa8..cd88ab4 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MarkOccurrencesConfigurationBlock.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MarkOccurrencesConfigurationBlock.java @@ -16,8 +16,12 @@ import java.util.HashMap; import java.util.Iterator; import java.util.Map; -import org.eclipse.core.runtime.IStatus; +import net.sourceforge.phpdt.internal.ui.dialogs.StatusInfo; +import net.sourceforge.phpdt.internal.ui.util.PixelConverter; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.jface.text.Assert; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; @@ -28,146 +32,197 @@ import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; -import org.eclipse.jface.text.Assert; - -import net.sourceforge.phpdt.ui.PreferenceConstants; - -import net.sourceforge.phpdt.internal.ui.dialogs.StatusInfo; -import net.sourceforge.phpdt.internal.ui.util.PixelConverter; - /** * Configures Java Editor hover preferences. - * + * * @since 2.1 */ -class MarkOccurrencesConfigurationBlock implements IPreferenceConfigurationBlock { +class MarkOccurrencesConfigurationBlock implements + IPreferenceConfigurationBlock { private OverlayPreferenceStore fStore; + private Map fCheckBoxes = new HashMap(); - private Map fCheckBoxes= new HashMap(); - private SelectionListener fCheckBoxListener= new SelectionListener() { + private SelectionListener fCheckBoxListener = new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { } + public void widgetSelected(SelectionEvent e) { - Button button= (Button) e.widget; - fStore.setValue((String) fCheckBoxes.get(button), button.getSelection()); + Button button = (Button) e.widget; + fStore.setValue((String) fCheckBoxes.get(button), button + .getSelection()); } }; /** * List of master/slave listeners when there's a dependency. - * + * * @see #createDependency(Button, String, Control) * @since 3.0 */ - private ArrayList fMasterSlaveListeners= new ArrayList(); + private ArrayList fMasterSlaveListeners = new ArrayList(); private StatusInfo fStatus; public MarkOccurrencesConfigurationBlock(OverlayPreferenceStore store) { Assert.isNotNull(store); - fStore= store; + fStore = store; fStore.addKeys(createOverlayStoreKeys()); } private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys() { - ArrayList overlayKeys= new ArrayList(); - - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MARK_OCCURRENCES)); -// overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES)); -// overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES)); -// overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES)); -// overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES)); -// overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES)); -// overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES)); -// overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS)); -// overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MARK_IMPLEMENTORS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_STICKY_OCCURRENCES)); - - OverlayPreferenceStore.OverlayKey[] keys= new OverlayPreferenceStore.OverlayKey[overlayKeys.size()]; + ArrayList overlayKeys = new ArrayList(); + + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_MARK_OCCURRENCES)); + // overlayKeys.add(new + // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, + // PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES)); + // overlayKeys.add(new + // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, + // PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES)); + // overlayKeys.add(new + // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, + // PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES)); + // overlayKeys.add(new + // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, + // PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES)); + // overlayKeys.add(new + // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, + // PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES)); + // overlayKeys.add(new + // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, + // PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES)); + // overlayKeys.add(new + // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, + // PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS)); + // overlayKeys.add(new + // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, + // PreferenceConstants.EDITOR_MARK_IMPLEMENTORS)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_STICKY_OCCURRENCES)); + + OverlayPreferenceStore.OverlayKey[] keys = new OverlayPreferenceStore.OverlayKey[overlayKeys + .size()]; overlayKeys.toArray(keys); return keys; } /** * Creates page for mark occurrences preferences. - * - * @param parent the parent composite + * + * @param parent + * the parent composite * @return the control for the preference page */ public Control createControl(Composite parent) { - Composite composite= new Composite(parent, SWT.NONE); - GridLayout layout= new GridLayout(); - layout.numColumns= 1; + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.numColumns = 1; composite.setLayout(layout); String label; - label= PreferencesMessages.getString("JavaEditorPreferencePage.markOccurrences"); - Button master= addCheckBox(composite, label, PreferenceConstants.EDITOR_MARK_OCCURRENCES, 0); //$NON-NLS-1$ - -// label= PreferencesMessages.MarkOccurrencesConfigurationBlock_markTypeOccurrences; -// Button slave= addCheckBox(composite, label, PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES, 0); //$NON-NLS-1$ -// createDependency(master, PreferenceConstants.EDITOR_STICKY_OCCURRENCES, slave); -// -// label= PreferencesMessages.MarkOccurrencesConfigurationBlock_markMethodOccurrences; -// slave= addCheckBox(composite, label, PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES, 0); //$NON-NLS-1$ -// createDependency(master, PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES, slave); -// -// label= PreferencesMessages.MarkOccurrencesConfigurationBlock_markConstantOccurrences; -// slave= addCheckBox(composite, label, PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES, 0); //$NON-NLS-1$ -// createDependency(master, PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES, slave); -// -// label= PreferencesMessages.MarkOccurrencesConfigurationBlock_markFieldOccurrences; -// slave= addCheckBox(composite, label, PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES, 0); //$NON-NLS-1$ -// createDependency(master, PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES, slave); -// -// label= PreferencesMessages.MarkOccurrencesConfigurationBlock_markLocalVariableOccurrences; -// slave= addCheckBox(composite, label, PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES, 0); //$NON-NLS-1$ -// createDependency(master, PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES, slave); -// -// label= PreferencesMessages.MarkOccurrencesConfigurationBlock_markExceptionOccurrences; -// slave= addCheckBox(composite, label, PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES, 0); //$NON-NLS-1$ -// createDependency(master, PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES, slave); -// -// label= PreferencesMessages.MarkOccurrencesConfigurationBlock_markMethodExitPoints; -// slave= addCheckBox(composite, label, PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS, 0); //$NON-NLS-1$ -// createDependency(master, PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS, slave); -// -// label= PreferencesMessages.MarkOccurrencesConfigurationBlock_markImplementors; -// slave= addCheckBox(composite, label, PreferenceConstants.EDITOR_MARK_IMPLEMENTORS, 0); //$NON-NLS-1$ -// createDependency(master, PreferenceConstants.EDITOR_MARK_IMPLEMENTORS, slave); + label = PreferencesMessages + .getString("JavaEditorPreferencePage.markOccurrences"); + Button master = addCheckBox(composite, label, + PreferenceConstants.EDITOR_MARK_OCCURRENCES, 0); //$NON-NLS-1$ + + // label= + // PreferencesMessages.MarkOccurrencesConfigurationBlock_markTypeOccurrences; + // Button slave= addCheckBox(composite, label, + // PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES, 0); //$NON-NLS-1$ + // createDependency(master, + // PreferenceConstants.EDITOR_STICKY_OCCURRENCES, slave); + // + // label= + // PreferencesMessages.MarkOccurrencesConfigurationBlock_markMethodOccurrences; + // slave= addCheckBox(composite, label, + // PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES, 0); //$NON-NLS-1$ + // createDependency(master, + // PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES, slave); + // + // label= + // PreferencesMessages.MarkOccurrencesConfigurationBlock_markConstantOccurrences; + // slave= addCheckBox(composite, label, + // PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES, 0); + // //$NON-NLS-1$ + // createDependency(master, + // PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES, slave); + // + // label= + // PreferencesMessages.MarkOccurrencesConfigurationBlock_markFieldOccurrences; + // slave= addCheckBox(composite, label, + // PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES, 0); //$NON-NLS-1$ + // createDependency(master, + // PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES, slave); + // + // label= + // PreferencesMessages.MarkOccurrencesConfigurationBlock_markLocalVariableOccurrences; + // slave= addCheckBox(composite, label, + // PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES, 0); + // //$NON-NLS-1$ + // createDependency(master, + // PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES, slave); + // + // label= + // PreferencesMessages.MarkOccurrencesConfigurationBlock_markExceptionOccurrences; + // slave= addCheckBox(composite, label, + // PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES, 0); + // //$NON-NLS-1$ + // createDependency(master, + // PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES, slave); + // + // label= + // PreferencesMessages.MarkOccurrencesConfigurationBlock_markMethodExitPoints; + // slave= addCheckBox(composite, label, + // PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS, 0); //$NON-NLS-1$ + // createDependency(master, + // PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS, slave); + // + // label= + // PreferencesMessages.MarkOccurrencesConfigurationBlock_markImplementors; + // slave= addCheckBox(composite, label, + // PreferenceConstants.EDITOR_MARK_IMPLEMENTORS, 0); //$NON-NLS-1$ + // createDependency(master, + // PreferenceConstants.EDITOR_MARK_IMPLEMENTORS, slave); addFiller(composite); - label= PreferencesMessages.getString("JavaEditorPreferencePage.stickyOccurrences"); - Button slave= addCheckBox(composite, label, PreferenceConstants.EDITOR_STICKY_OCCURRENCES, 0); //$NON-NLS-1$ - createDependency(master, PreferenceConstants.EDITOR_STICKY_OCCURRENCES, slave); + label = PreferencesMessages + .getString("JavaEditorPreferencePage.stickyOccurrences"); + Button slave = addCheckBox(composite, label, + PreferenceConstants.EDITOR_STICKY_OCCURRENCES, 0); //$NON-NLS-1$ + createDependency(master, PreferenceConstants.EDITOR_STICKY_OCCURRENCES, + slave); return composite; } private void addFiller(Composite composite) { - PixelConverter pixelConverter= new PixelConverter(composite); + PixelConverter pixelConverter = new PixelConverter(composite); - Label filler= new Label(composite, SWT.LEFT ); - GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); - gd.horizontalSpan= 2; - gd.heightHint= pixelConverter.convertHeightInCharsToPixels(1) / 2; + Label filler = new Label(composite, SWT.LEFT); + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + gd.horizontalSpan = 2; + gd.heightHint = pixelConverter.convertHeightInCharsToPixels(1) / 2; filler.setLayoutData(gd); } - private Button addCheckBox(Composite parent, String label, String key, int indentation) { - Button checkBox= new Button(parent, SWT.CHECK); + private Button addCheckBox(Composite parent, String label, String key, + int indentation) { + Button checkBox = new Button(parent, SWT.CHECK); checkBox.setText(label); - GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - gd.horizontalIndent= indentation; - gd.horizontalSpan= 2; + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.horizontalIndent = indentation; + gd.horizontalSpan = 2; checkBox.setLayoutData(gd); checkBox.addSelectionListener(fCheckBoxListener); @@ -176,24 +231,26 @@ class MarkOccurrencesConfigurationBlock implements IPreferenceConfigurationBlock return checkBox; } - private void createDependency(final Button master, String masterKey, final Control slave) { + private void createDependency(final Button master, String masterKey, + final Control slave) { indent(slave); - boolean masterState= fStore.getBoolean(masterKey); + boolean masterState = fStore.getBoolean(masterKey); slave.setEnabled(masterState); - SelectionListener listener= new SelectionListener() { + SelectionListener listener = new SelectionListener() { public void widgetSelected(SelectionEvent e) { slave.setEnabled(master.getSelection()); } - public void widgetDefaultSelected(SelectionEvent e) {} + public void widgetDefaultSelected(SelectionEvent e) { + } }; master.addSelectionListener(listener); fMasterSlaveListeners.add(listener); } private static void indent(Control control) { - GridData gridData= new GridData(); - gridData.horizontalIndent= 20; + GridData gridData = new GridData(); + gridData.horizontalIndent = 20; control.setLayoutData(gridData); } @@ -203,19 +260,19 @@ class MarkOccurrencesConfigurationBlock implements IPreferenceConfigurationBlock void initializeFields() { - Iterator iter= fCheckBoxes.keySet().iterator(); + Iterator iter = fCheckBoxes.keySet().iterator(); while (iter.hasNext()) { - Button b= (Button) iter.next(); - String key= (String) fCheckBoxes.get(b); + Button b = (Button) iter.next(); + String key = (String) fCheckBoxes.get(b); b.setSelection(fStore.getBoolean(key)); } - // Update slaves - iter= fMasterSlaveListeners.iterator(); - while (iter.hasNext()) { - SelectionListener listener= (SelectionListener)iter.next(); - listener.widgetSelected(null); - } + // Update slaves + iter = fMasterSlaveListeners.iterator(); + while (iter.hasNext()) { + SelectionListener listener = (SelectionListener) iter.next(); + listener.widgetSelected(null); + } } @@ -233,7 +290,7 @@ class MarkOccurrencesConfigurationBlock implements IPreferenceConfigurationBlock IStatus getStatus() { if (fStatus == null) - fStatus= new StatusInfo(); + fStatus = new StatusInfo(); return fStatus; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MarkOccurrencesPreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MarkOccurrencesPreferencePage.java index 07fbfd4..af8ee82 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MarkOccurrencesPreferencePage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MarkOccurrencesPreferencePage.java @@ -11,7 +11,6 @@ package net.sourceforge.phpdt.internal.ui.preferences; - import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; import net.sourceforge.phpeclipse.PHPeclipsePlugin; @@ -21,7 +20,8 @@ import org.eclipse.swt.widgets.Label; /** * The page for setting the editor options. */ -public final class MarkOccurrencesPreferencePage extends AbstractConfigurationBlockPreferencePage { +public final class MarkOccurrencesPreferencePage extends + AbstractConfigurationBlockPreferencePage { /* * @see org.eclipse.ui.internal.editors.text.AbstractConfigureationBlockPreferencePage#getHelpId() @@ -34,7 +34,8 @@ public final class MarkOccurrencesPreferencePage extends AbstractConfigurationBl * @see org.eclipse.ui.internal.editors.text.AbstractConfigurationBlockPreferencePage#setDescription() */ protected void setDescription() { - String description= PreferencesMessages.getString("MarkOccurrencesConfigurationBlock.title"); + String description = PreferencesMessages + .getString("MarkOccurrencesConfigurationBlock.title"); setDescription(description); } @@ -45,7 +46,6 @@ public final class MarkOccurrencesPreferencePage extends AbstractConfigurationBl setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); } - protected Label createDescriptionLabel(Composite parent) { return null; // no description for new look. } @@ -53,7 +53,8 @@ public final class MarkOccurrencesPreferencePage extends AbstractConfigurationBl /* * @see org.eclipse.ui.internal.editors.text.AbstractConfigureationBlockPreferencePage#createConfigurationBlock(org.eclipse.ui.internal.editors.text.OverlayPreferenceStore) */ - protected IPreferenceConfigurationBlock createConfigurationBlock(OverlayPreferenceStore overlayPreferenceStore) { + protected IPreferenceConfigurationBlock createConfigurationBlock( + OverlayPreferenceStore overlayPreferenceStore) { return new MarkOccurrencesConfigurationBlock(overlayPreferenceStore); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MembersOrderPreferenceCache.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MembersOrderPreferenceCache.java index 5dab2f0..cf34946 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MembersOrderPreferenceCache.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MembersOrderPreferenceCache.java @@ -20,149 +20,177 @@ import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; /** - */ + */ public class MembersOrderPreferenceCache implements IPropertyChangeListener { - - public static final int TYPE_INDEX= 0; - public static final int CONSTRUCTORS_INDEX= 1; - public static final int METHOD_INDEX= 2; - public static final int FIELDS_INDEX= 3; - public static final int INIT_INDEX= 4; - public static final int STATIC_FIELDS_INDEX= 5; - public static final int STATIC_INIT_INDEX= 6; - public static final int STATIC_METHODS_INDEX= 7; - public static final int N_CATEGORIES= STATIC_METHODS_INDEX + 1; - - private static final int PUBLIC_INDEX= 0; - private static final int PRIVATE_INDEX= 1; - private static final int PROTECTED_INDEX= 2; - private static final int DEFAULT_INDEX= 3; - private static final int N_VISIBILITIES= DEFAULT_INDEX + 1; - - private int[] fCategoryOffsets= null; - + + public static final int TYPE_INDEX = 0; + + public static final int CONSTRUCTORS_INDEX = 1; + + public static final int METHOD_INDEX = 2; + + public static final int FIELDS_INDEX = 3; + + public static final int INIT_INDEX = 4; + + public static final int STATIC_FIELDS_INDEX = 5; + + public static final int STATIC_INIT_INDEX = 6; + + public static final int STATIC_METHODS_INDEX = 7; + + public static final int N_CATEGORIES = STATIC_METHODS_INDEX + 1; + + private static final int PUBLIC_INDEX = 0; + + private static final int PRIVATE_INDEX = 1; + + private static final int PROTECTED_INDEX = 2; + + private static final int DEFAULT_INDEX = 3; + + private static final int N_VISIBILITIES = DEFAULT_INDEX + 1; + + private int[] fCategoryOffsets = null; + private boolean fSortByVisibility; - private int[] fVisibilityOffsets= null; - + + private int[] fVisibilityOffsets = null; + public MembersOrderPreferenceCache() { - fCategoryOffsets= null; - fSortByVisibility= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER); - fVisibilityOffsets= null; + fCategoryOffsets = null; + fSortByVisibility = PreferenceConstants + .getPreferenceStore() + .getBoolean( + PreferenceConstants.APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER); + fVisibilityOffsets = null; } - + public static boolean isMemberOrderProperty(String property) { - return PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(property) - || PreferenceConstants.APPEARANCE_VISIBILITY_SORT_ORDER.equals(property) - || PreferenceConstants.APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER.equals(property); + return PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER + .equals(property) + || PreferenceConstants.APPEARANCE_VISIBILITY_SORT_ORDER + .equals(property) + || PreferenceConstants.APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER + .equals(property); } public void propertyChange(PropertyChangeEvent event) { - String property= event.getProperty(); - + String property = event.getProperty(); + if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(property)) { - fCategoryOffsets= null; - } else if (PreferenceConstants.APPEARANCE_VISIBILITY_SORT_ORDER.equals(property)) { - fVisibilityOffsets= null; - } else if (PreferenceConstants.APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER.equals(property)) { - fSortByVisibility= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER); + fCategoryOffsets = null; + } else if (PreferenceConstants.APPEARANCE_VISIBILITY_SORT_ORDER + .equals(property)) { + fVisibilityOffsets = null; + } else if (PreferenceConstants.APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER + .equals(property)) { + fSortByVisibility = PreferenceConstants + .getPreferenceStore() + .getBoolean( + PreferenceConstants.APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER); } } public int getCategoryIndex(int kind) { if (fCategoryOffsets == null) { - fCategoryOffsets= getCategoryOffsets(); + fCategoryOffsets = getCategoryOffsets(); } return fCategoryOffsets[kind]; } - + private int[] getCategoryOffsets() { - int[] offsets= new int[N_CATEGORIES]; - IPreferenceStore store= PreferenceConstants.getPreferenceStore(); - String key= PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER; - boolean success= fillCategoryOffsetsFromPreferenceString(store.getString(key), offsets); + int[] offsets = new int[N_CATEGORIES]; + IPreferenceStore store = PreferenceConstants.getPreferenceStore(); + String key = PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER; + boolean success = fillCategoryOffsetsFromPreferenceString(store + .getString(key), offsets); if (!success) { store.setToDefault(key); - fillCategoryOffsetsFromPreferenceString(store.getDefaultString(key), offsets); + fillCategoryOffsetsFromPreferenceString( + store.getDefaultString(key), offsets); } return offsets; } - - private boolean fillCategoryOffsetsFromPreferenceString(String str, int[] offsets) { - StringTokenizer tokenizer= new StringTokenizer(str, ","); //$NON-NLS-1$ - int i= 0; + + private boolean fillCategoryOffsetsFromPreferenceString(String str, + int[] offsets) { + StringTokenizer tokenizer = new StringTokenizer(str, ","); //$NON-NLS-1$ + int i = 0; while (tokenizer.hasMoreTokens()) { - String token= tokenizer.nextToken().trim(); + String token = tokenizer.nextToken().trim(); if ("T".equals(token)) { //$NON-NLS-1$ - offsets[TYPE_INDEX]= i++; + offsets[TYPE_INDEX] = i++; } else if ("M".equals(token)) { //$NON-NLS-1$ - offsets[METHOD_INDEX]= i++; + offsets[METHOD_INDEX] = i++; } else if ("F".equals(token)) { //$NON-NLS-1$ - offsets[FIELDS_INDEX]= i++; + offsets[FIELDS_INDEX] = i++; } else if ("I".equals(token)) { //$NON-NLS-1$ - offsets[INIT_INDEX]= i++; + offsets[INIT_INDEX] = i++; } else if ("SF".equals(token)) { //$NON-NLS-1$ - offsets[STATIC_FIELDS_INDEX]= i++; + offsets[STATIC_FIELDS_INDEX] = i++; } else if ("SI".equals(token)) { //$NON-NLS-1$ - offsets[STATIC_INIT_INDEX]= i++; + offsets[STATIC_INIT_INDEX] = i++; } else if ("SM".equals(token)) { //$NON-NLS-1$ - offsets[STATIC_METHODS_INDEX]= i++; + offsets[STATIC_METHODS_INDEX] = i++; } else if ("C".equals(token)) { //$NON-NLS-1$ - offsets[CONSTRUCTORS_INDEX]= i++; + offsets[CONSTRUCTORS_INDEX] = i++; } } return i == N_CATEGORIES; } - + public boolean isSortByVisibility() { return fSortByVisibility; } - - + public int getVisibilityIndex(int modifierFlags) { if (fVisibilityOffsets == null) { - fVisibilityOffsets= getVisibilityOffsets(); + fVisibilityOffsets = getVisibilityOffsets(); } - int kind= DEFAULT_INDEX; + int kind = DEFAULT_INDEX; if (Flags.isPublic(modifierFlags)) { - kind= PUBLIC_INDEX; + kind = PUBLIC_INDEX; } else if (Flags.isProtected(modifierFlags)) { - kind= PROTECTED_INDEX; + kind = PROTECTED_INDEX; } else if (Flags.isPrivate(modifierFlags)) { - kind= PRIVATE_INDEX; + kind = PRIVATE_INDEX; } - + return fVisibilityOffsets[kind]; } - + private int[] getVisibilityOffsets() { - int[] offsets= new int[N_VISIBILITIES]; - IPreferenceStore store= PreferenceConstants.getPreferenceStore(); - String key= PreferenceConstants.APPEARANCE_VISIBILITY_SORT_ORDER; - boolean success= fillVisibilityOffsetsFromPreferenceString(store.getString(key), offsets); + int[] offsets = new int[N_VISIBILITIES]; + IPreferenceStore store = PreferenceConstants.getPreferenceStore(); + String key = PreferenceConstants.APPEARANCE_VISIBILITY_SORT_ORDER; + boolean success = fillVisibilityOffsetsFromPreferenceString(store + .getString(key), offsets); if (!success) { store.setToDefault(key); - fillVisibilityOffsetsFromPreferenceString(store.getDefaultString(key), offsets); + fillVisibilityOffsetsFromPreferenceString(store + .getDefaultString(key), offsets); } return offsets; - } - - private boolean fillVisibilityOffsetsFromPreferenceString(String str, int[] offsets) { - StringTokenizer tokenizer= new StringTokenizer(str, ","); //$NON-NLS-1$ - int i= 0; + } + + private boolean fillVisibilityOffsetsFromPreferenceString(String str, + int[] offsets) { + StringTokenizer tokenizer = new StringTokenizer(str, ","); //$NON-NLS-1$ + int i = 0; while (tokenizer.hasMoreTokens()) { - String token= tokenizer.nextToken().trim(); + String token = tokenizer.nextToken().trim(); if ("B".equals(token)) { //$NON-NLS-1$ - offsets[PUBLIC_INDEX]= i++; + offsets[PUBLIC_INDEX] = i++; } else if ("V".equals(token)) { //$NON-NLS-1$ - offsets[PRIVATE_INDEX]= i++; + offsets[PRIVATE_INDEX] = i++; } else if ("R".equals(token)) { //$NON-NLS-1$ - offsets[PROTECTED_INDEX]= i++; + offsets[PROTECTED_INDEX] = i++; } else if ("D".equals(token)) { //$NON-NLS-1$ - offsets[DEFAULT_INDEX]= i++; + offsets[DEFAULT_INDEX] = i++; } } return i == N_VISIBILITIES; } - } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MembersOrderPreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MembersOrderPreferencePage.java index a7225ff..74e8649 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MembersOrderPreferencePage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MembersOrderPreferencePage.java @@ -39,37 +39,46 @@ import org.eclipse.swt.widgets.Control; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; -public class MembersOrderPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { +public class MembersOrderPreferencePage extends PreferencePage implements + IWorkbenchPreferencePage { - private static final String ALL_ENTRIES= "T,SI,SF,SM,I,F,C,M"; //$NON-NLS-1$ - private static final String PREF_OUTLINE_SORT_OPTION= PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER; + private static final String ALL_ENTRIES = "T,SI,SF,SM,I,F,C,M"; //$NON-NLS-1$ - public static final String CONSTRUCTORS= "C"; //$NON-NLS-1$ - public static final String FIELDS= "F"; //$NON-NLS-1$ - public static final String METHODS= "M"; //$NON-NLS-1$ - public static final String STATIC_METHODS= "SM"; //$NON-NLS-1$ - public static final String STATIC_FIELDS= "SF"; //$NON-NLS-1$ - public static final String INIT= "I"; //$NON-NLS-1$ - public static final String STATIC_INIT= "SI"; //$NON-NLS-1$ - public static final String TYPES= "T"; //$NON-NLS-1$ + private static final String PREF_OUTLINE_SORT_OPTION = PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER; + + public static final String CONSTRUCTORS = "C"; //$NON-NLS-1$ + + public static final String FIELDS = "F"; //$NON-NLS-1$ + + public static final String METHODS = "M"; //$NON-NLS-1$ + + public static final String STATIC_METHODS = "SM"; //$NON-NLS-1$ + + public static final String STATIC_FIELDS = "SF"; //$NON-NLS-1$ + + public static final String INIT = "I"; //$NON-NLS-1$ + + public static final String STATIC_INIT = "SI"; //$NON-NLS-1$ + + public static final String TYPES = "T"; //$NON-NLS-1$ private ListDialogField fSortOrderList; private static List getSortOrderList(String string) { - StringTokenizer tokenizer= new StringTokenizer(string, ","); //$NON-NLS-1$ - List entries= new ArrayList(); - for (int i= 0; tokenizer.hasMoreTokens(); i++) { - String token= tokenizer.nextToken(); + StringTokenizer tokenizer = new StringTokenizer(string, ","); //$NON-NLS-1$ + List entries = new ArrayList(); + for (int i = 0; tokenizer.hasMoreTokens(); i++) { + String token = tokenizer.nextToken(); entries.add(token); } return entries; } private static boolean isValidEntries(List entries) { - StringTokenizer tokenizer= new StringTokenizer(ALL_ENTRIES, ","); //$NON-NLS-1$ - int i= 0; + StringTokenizer tokenizer = new StringTokenizer(ALL_ENTRIES, ","); //$NON-NLS-1$ + int i = 0; for (; tokenizer.hasMoreTokens(); i++) { - String token= tokenizer.nextToken(); + String token = tokenizer.nextToken(); if (!entries.contains(token)) return false; } @@ -77,26 +86,32 @@ public class MembersOrderPreferencePage extends PreferencePage implements IWorkb } public MembersOrderPreferencePage() { - //set the preference store + // set the preference store setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); - - setDescription(PreferencesMessages.getString("MembersOrderPreferencePage.label.description")); //$NON-NLS-1$ - String string= getPreferenceStore().getString(PREF_OUTLINE_SORT_OPTION); + setDescription(PreferencesMessages + .getString("MembersOrderPreferencePage.label.description")); //$NON-NLS-1$ - String upLabel= PreferencesMessages.getString("MembersOrderPreferencePage.button.up"); //$NON-NLS-1$ - String downLabel= PreferencesMessages.getString("MembersOrderPreferencePage.button.down"); //$NON-NLS-1$ - String[] buttonlabels= new String[] { upLabel, downLabel }; + String string = getPreferenceStore() + .getString(PREF_OUTLINE_SORT_OPTION); - fSortOrderList= new ListDialogField(null, buttonlabels, new MemberSortLabelProvider()); + String upLabel = PreferencesMessages + .getString("MembersOrderPreferencePage.button.up"); //$NON-NLS-1$ + String downLabel = PreferencesMessages + .getString("MembersOrderPreferencePage.button.down"); //$NON-NLS-1$ + String[] buttonlabels = new String[] { upLabel, downLabel }; + + fSortOrderList = new ListDialogField(null, buttonlabels, + new MemberSortLabelProvider()); fSortOrderList.setDownButtonIndex(1); fSortOrderList.setUpButtonIndex(0); - //validate entries stored in store, false get defaults - List entries= getSortOrderList(string); + // validate entries stored in store, false get defaults + List entries = getSortOrderList(string); if (!isValidEntries(entries)) { - string= PHPeclipsePlugin.getDefault().getPreferenceStore().getDefaultString(PREF_OUTLINE_SORT_OPTION); - entries= getSortOrderList(string); + string = PHPeclipsePlugin.getDefault().getPreferenceStore() + .getDefaultString(PREF_OUTLINE_SORT_OPTION); + entries = getSortOrderList(string); } fSortOrderList.setElements(entries); @@ -107,26 +122,26 @@ public class MembersOrderPreferencePage extends PreferencePage implements IWorkb */ public void createControl(Composite parent) { super.createControl(parent); -// WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.SORT_ORDER_PREFERENCE_PAGE); + // WorkbenchHelp.setHelp(getControl(), + // IJavaHelpContextIds.SORT_ORDER_PREFERENCE_PAGE); } /* * @see org.eclipse.jface.preference.PreferencePage#createContents(Composite) */ protected Control createContents(Composite parent) { - - - Composite composite= new Composite(parent, SWT.NONE); - - GridLayout layout= new GridLayout(); - layout.numColumns= 3; - layout.marginWidth= 0; - layout.marginHeight= 0; + + Composite composite = new Composite(parent, SWT.NONE); + + GridLayout layout = new GridLayout(); + layout.numColumns = 3; + layout.marginWidth = 0; + layout.marginHeight = 0; composite.setLayout(layout); - GridData data= new GridData(); - data.verticalAlignment= GridData.FILL; - data.horizontalAlignment= GridData.FILL_HORIZONTAL; + GridData data = new GridData(); + data.verticalAlignment = GridData.FILL; + data.horizontalAlignment = GridData.FILL_HORIZONTAL; composite.setLayoutData(data); createSortOrderListDialogField(composite, 3); @@ -136,13 +151,15 @@ public class MembersOrderPreferencePage extends PreferencePage implements IWorkb private void createSortOrderListDialogField(Composite composite, int span) { fSortOrderList.doFillIntoGrid(composite, span); - + fSortOrderList.getLabelControl(null).dispose(); - - GridData data= (GridData) fSortOrderList.getListControl(null).getLayoutData(); - data.grabExcessHorizontalSpace= true; - data.verticalAlignment= 0; - data.heightHint= SWTUtil.getTableHeightHint(fSortOrderList.getTableViewer().getTable(), 8); + + GridData data = (GridData) fSortOrderList.getListControl(null) + .getLayoutData(); + data.grabExcessHorizontalSpace = true; + data.verticalAlignment = 0; + data.heightHint = SWTUtil.getTableHeightHint(fSortOrderList + .getTableViewer().getTable(), 8); } /* @@ -155,24 +172,25 @@ public class MembersOrderPreferencePage extends PreferencePage implements IWorkb * @see org.eclipse.jface.preference.PreferencePage#performDefaults() */ protected void performDefaults() { - String string= getPreferenceStore().getDefaultString(PREF_OUTLINE_SORT_OPTION); + String string = getPreferenceStore().getDefaultString( + PREF_OUTLINE_SORT_OPTION); fSortOrderList.setElements(getSortOrderList(string)); } /* * @see org.eclipse.jface.preference.IPreferencePage#performOk() */ - //reorders elements in the Outline based on selection + // reorders elements in the Outline based on selection public boolean performOk() { - //update outline view + // update outline view - //save preferences - IPreferenceStore store= getPreferenceStore(); + // save preferences + IPreferenceStore store = getPreferenceStore(); - StringBuffer buf= new StringBuffer(); - List curr= fSortOrderList.getElements(); - for (Iterator iter= curr.iterator(); iter.hasNext();) { - String s= (String) iter.next(); + StringBuffer buf = new StringBuffer(); + List curr = fSortOrderList.getElements(); + for (Iterator iter = curr.iterator(); iter.hasNext();) { + String s = (String) iter.next(); buf.append(s); buf.append(','); } @@ -185,72 +203,99 @@ public class MembersOrderPreferencePage extends PreferencePage implements IWorkb public MemberSortLabelProvider() { } - + /* * @see org.eclipse.jface.viewers.ILabelProvider#getText(Object) */ public String getText(Object element) { if (element instanceof String) { - String s= (String) element; + String s = (String) element; if (s.equals(FIELDS)) { - return PreferencesMessages.getString("MembersOrderPreferencePage.fields.label"); //$NON-NLS-1$ + return PreferencesMessages + .getString("MembersOrderPreferencePage.fields.label"); //$NON-NLS-1$ } else if (s.equals(CONSTRUCTORS)) { - return PreferencesMessages.getString("MembersOrderPreferencePage.constructors.label"); //$NON-NLS-1$ + return PreferencesMessages + .getString("MembersOrderPreferencePage.constructors.label"); //$NON-NLS-1$ } else if (s.equals(METHODS)) { - return PreferencesMessages.getString("MembersOrderPreferencePage.methods.label"); //$NON-NLS-1$ + return PreferencesMessages + .getString("MembersOrderPreferencePage.methods.label"); //$NON-NLS-1$ } else if (s.equals(STATIC_FIELDS)) { - return PreferencesMessages.getString("MembersOrderPreferencePage.staticfields.label"); //$NON-NLS-1$ + return PreferencesMessages + .getString("MembersOrderPreferencePage.staticfields.label"); //$NON-NLS-1$ } else if (s.equals(STATIC_METHODS)) { - return PreferencesMessages.getString("MembersOrderPreferencePage.staticmethods.label"); //$NON-NLS-1$ + return PreferencesMessages + .getString("MembersOrderPreferencePage.staticmethods.label"); //$NON-NLS-1$ } else if (s.equals(INIT)) { - return PreferencesMessages.getString("MembersOrderPreferencePage.initialisers.label"); //$NON-NLS-1$ + return PreferencesMessages + .getString("MembersOrderPreferencePage.initialisers.label"); //$NON-NLS-1$ } else if (s.equals(STATIC_INIT)) { - return PreferencesMessages.getString("MembersOrderPreferencePage.staticinitialisers.label"); //$NON-NLS-1$ + return PreferencesMessages + .getString("MembersOrderPreferencePage.staticinitialisers.label"); //$NON-NLS-1$ } else if (s.equals(TYPES)) { - return PreferencesMessages.getString("MembersOrderPreferencePage.types.label"); //$NON-NLS-1$ + return PreferencesMessages + .getString("MembersOrderPreferencePage.types.label"); //$NON-NLS-1$ } } return ""; //$NON-NLS-1$ } /* - * @see org.eclipse.jface.viewers.ILabelProvider#getImage(Object) - */ + * @see org.eclipse.jface.viewers.ILabelProvider#getImage(Object) + */ public Image getImage(Object element) { - //access to image registry - ImageDescriptorRegistry registry= PHPeclipsePlugin.getImageDescriptorRegistry(); - ImageDescriptor descriptor= null; + // access to image registry + ImageDescriptorRegistry registry = PHPeclipsePlugin + .getImageDescriptorRegistry(); + ImageDescriptor descriptor = null; if (element instanceof String) { - int visibility= Flags.AccPublic; - String s= (String) element; + int visibility = Flags.AccPublic; + String s = (String) element; if (s.equals(FIELDS)) { - //0 will give the default field image - descriptor= JavaElementImageProvider.getFieldImageDescriptor(false, visibility); + // 0 will give the default field image + descriptor = JavaElementImageProvider + .getFieldImageDescriptor(false, visibility); } else if (s.equals(CONSTRUCTORS)) { - descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, visibility); - //add a constructor adornment to the image descriptor - descriptor= new JavaElementImageDescriptor(descriptor, JavaElementImageDescriptor.CONSTRUCTOR, JavaElementImageProvider.SMALL_SIZE); + descriptor = JavaElementImageProvider + .getMethodImageDescriptor(false, visibility); + // add a constructor adornment to the image descriptor + descriptor = new JavaElementImageDescriptor(descriptor, + JavaElementImageDescriptor.CONSTRUCTOR, + JavaElementImageProvider.SMALL_SIZE); } else if (s.equals(METHODS)) { - descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, visibility); + descriptor = JavaElementImageProvider + .getMethodImageDescriptor(false, visibility); } else if (s.equals(STATIC_FIELDS)) { - descriptor= JavaElementImageProvider.getFieldImageDescriptor(false, visibility); - //add a constructor adornment to the image descriptor - descriptor= new JavaElementImageDescriptor(descriptor, JavaElementImageDescriptor.STATIC, JavaElementImageProvider.SMALL_SIZE); + descriptor = JavaElementImageProvider + .getFieldImageDescriptor(false, visibility); + // add a constructor adornment to the image descriptor + descriptor = new JavaElementImageDescriptor(descriptor, + JavaElementImageDescriptor.STATIC, + JavaElementImageProvider.SMALL_SIZE); } else if (s.equals(STATIC_METHODS)) { - descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, visibility); - //add a constructor adornment to the image descriptor - descriptor= new JavaElementImageDescriptor(descriptor, JavaElementImageDescriptor.STATIC, JavaElementImageProvider.SMALL_SIZE); + descriptor = JavaElementImageProvider + .getMethodImageDescriptor(false, visibility); + // add a constructor adornment to the image descriptor + descriptor = new JavaElementImageDescriptor(descriptor, + JavaElementImageDescriptor.STATIC, + JavaElementImageProvider.SMALL_SIZE); } else if (s.equals(INIT)) { - descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, visibility); + descriptor = JavaElementImageProvider + .getMethodImageDescriptor(false, visibility); } else if (s.equals(STATIC_INIT)) { - descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, visibility); - descriptor= new JavaElementImageDescriptor(descriptor, JavaElementImageDescriptor.STATIC, JavaElementImageProvider.SMALL_SIZE); + descriptor = JavaElementImageProvider + .getMethodImageDescriptor(false, visibility); + descriptor = new JavaElementImageDescriptor(descriptor, + JavaElementImageDescriptor.STATIC, + JavaElementImageProvider.SMALL_SIZE); } else if (s.equals(TYPES)) { - descriptor= JavaElementImageProvider.getTypeImageDescriptor(false, true, Flags.AccPublic); + descriptor = JavaElementImageProvider + .getTypeImageDescriptor(false, true, + Flags.AccPublic); } else { - descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, Flags.AccPublic); + descriptor = JavaElementImageProvider + .getMethodImageDescriptor(false, Flags.AccPublic); } return registry.get(descriptor); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MockupPreferenceStore.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MockupPreferenceStore.java index 9ebfdcb..bb54cd6 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MockupPreferenceStore.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MockupPreferenceStore.java @@ -17,11 +17,11 @@ import org.eclipse.jface.util.ListenerList; import org.eclipse.jface.util.PropertyChangeEvent; /** - * Mockup preference store, for registering listeners and firing events, - * without being an actual store. + * Mockup preference store, for registering listeners and firing events, without + * being an actual store. *

                                                      - * All methods except firing, adding and removing listeners throw - * an {@link java.lang.UnsupportedOperationException}. + * All methods except firing, adding and removing listeners throw an + * {@link java.lang.UnsupportedOperationException}. *

                                                      * * @since 3.0 @@ -29,7 +29,7 @@ import org.eclipse.jface.util.PropertyChangeEvent; public class MockupPreferenceStore implements IPreferenceStore { /** Listeners on this store */ - private ListenerList fListeners= new ListenerList(); + private ListenerList fListeners = new ListenerList(); /** * {@inheritDoc} @@ -55,22 +55,31 @@ public class MockupPreferenceStore implements IPreferenceStore { /** * {@inheritDoc} */ - public void firePropertyChangeEvent(String name, Object oldValue, Object newValue) { + public void firePropertyChangeEvent(String name, Object oldValue, + Object newValue) { firePropertyChangeEvent(this, name, oldValue, newValue); } /** - * Fires a property change event with the given source, property name, old and new value. Used - * when the event source should be different from this mockup preference store. - * @param source The event source - * @param name The property name - * @param oldValue The property's old value - * @param newValue The property's new value - */ - public void firePropertyChangeEvent(Object source, String name, Object oldValue, Object newValue) { - PropertyChangeEvent event= new PropertyChangeEvent(source, name, oldValue, newValue); - Object[] listeners= fListeners.getListeners(); - for (int i= 0; i < listeners.length; i++) + * Fires a property change event with the given source, property name, old + * and new value. Used when the event source should be different from this + * mockup preference store. + * + * @param source + * The event source + * @param name + * The property name + * @param oldValue + * The property's old value + * @param newValue + * The property's new value + */ + public void firePropertyChangeEvent(Object source, String name, + Object oldValue, Object newValue) { + PropertyChangeEvent event = new PropertyChangeEvent(source, name, + oldValue, newValue); + Object[] listeners = fListeners.getListeners(); + for (int i = 0; i < listeners.length; i++) ((IPropertyChangeListener) listeners[i]).propertyChange(event); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/OptionsConfigurationBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/OptionsConfigurationBlock.java index 2e4ce5d..ebf9ed3 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/OptionsConfigurationBlock.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/OptionsConfigurationBlock.java @@ -51,8 +51,8 @@ import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Widget; /** - * Abstract options configuration block providing a general implementation for setting up - * an options configuration page. + * Abstract options configuration block providing a general implementation for + * setting up an options configuration page. * * @since 2.1 */ @@ -60,73 +60,82 @@ public abstract class OptionsConfigurationBlock { protected static class ControlData { private String fKey; + private String[] fValues; - + public ControlData(String key, String[] values) { - fKey= key; - fValues= values; + fKey = key; + fValues = values; } - + public String getKey() { return fKey; } - + public String getValue(boolean selection) { - int index= selection ? 0 : 1; + int index = selection ? 0 : 1; return fValues[index]; } - + public String getValue(int index) { return fValues[index]; - } - + } + public int getSelection(String value) { if (value != null) { - for (int i= 0; i < fValues.length; i++) { + for (int i = 0; i < fValues.length; i++) { if (value.equals(fValues[i])) { return i; } } } - return fValues.length -1; // assume the last option is the least severe + return fValues.length - 1; // assume the last option is the least + // severe } } - - + protected Map fWorkingValues; protected ArrayList fCheckBoxes; + protected ArrayList fComboBoxes; + protected ArrayList fTextBoxes; + protected HashMap fLabels; - + private SelectionListener fSelectionListener; + private ModifyListener fTextModifyListener; protected IStatusChangeListener fContext; + protected IJavaProject fProject; // project or null + protected String[] fAllKeys; - + private Shell fShell; - public OptionsConfigurationBlock(IStatusChangeListener context, IJavaProject project, String[] allKeys) { - fContext= context; - fProject= project; - fAllKeys= allKeys; - - fWorkingValues= getOptions(true); + public OptionsConfigurationBlock(IStatusChangeListener context, + IJavaProject project, String[] allKeys) { + fContext = context; + fProject = project; + fAllKeys = allKeys; + + fWorkingValues = getOptions(true); testIfOptionsComplete(fWorkingValues, allKeys); - - fCheckBoxes= new ArrayList(); - fComboBoxes= new ArrayList(); - fTextBoxes= new ArrayList(2); - fLabels= new HashMap(); + + fCheckBoxes = new ArrayList(); + fComboBoxes = new ArrayList(); + fTextBoxes = new ArrayList(2); + fLabels = new HashMap(); } - + private void testIfOptionsComplete(Map workingValues, String[] allKeys) { - for (int i= 0; i < allKeys.length; i++) { + for (int i = 0; i < allKeys.length; i++) { if (workingValues.get(allKeys[i]) == null) { - PHPeclipsePlugin.logErrorMessage("preference option missing: " + allKeys[i] + " (" + this.getClass().getName() +')'); //$NON-NLS-1$//$NON-NLS-2$ + PHPeclipsePlugin + .logErrorMessage("preference option missing: " + allKeys[i] + " (" + this.getClass().getName() + ')'); //$NON-NLS-1$//$NON-NLS-2$ } } } @@ -136,192 +145,204 @@ public abstract class OptionsConfigurationBlock { return fProject.getOptions(inheritJavaCoreOptions); } else { return JavaCore.getOptions(); - } + } } - + protected Map getDefaultOptions() { return JavaCore.getDefaultOptions(); - } - + } + public final boolean hasProjectSpecificOptions() { if (fProject != null) { - Map settings= fProject.getOptions(false); - String[] allKeys= fAllKeys; - for (int i= 0; i < allKeys.length; i++) { + Map settings = fProject.getOptions(false); + String[] allKeys = fAllKeys; + for (int i = 0; i < allKeys.length; i++) { if (settings.get(allKeys[i]) != null) { return true; } } } return false; - } - + } + protected void setOptions(Map map) { if (fProject != null) { - Map oldOptions= fProject.getOptions(false); + Map oldOptions = fProject.getOptions(false); fProject.setOptions(map); firePropertyChangeEvents(oldOptions, map); } else { JavaCore.setOptions((Hashtable) map); - } - } - + } + } + /** - * Computes the differences between the given old and new options and fires corresponding - * property change events on the Java plugin's mockup preference store. - * @param oldOptions The old options - * @param newOptions The new options + * Computes the differences between the given old and new options and fires + * corresponding property change events on the Java plugin's mockup + * preference store. + * + * @param oldOptions + * The old options + * @param newOptions + * The new options */ private void firePropertyChangeEvents(Map oldOptions, Map newOptions) { - oldOptions= new HashMap(oldOptions); - Object source= fProject.getProject(); - MockupPreferenceStore store= PHPeclipsePlugin.getDefault().getMockupPreferenceStore(); - Iterator iter= newOptions.entrySet().iterator(); + oldOptions = new HashMap(oldOptions); + Object source = fProject.getProject(); + MockupPreferenceStore store = PHPeclipsePlugin.getDefault() + .getMockupPreferenceStore(); + Iterator iter = newOptions.entrySet().iterator(); while (iter.hasNext()) { - Entry entry= (Entry) iter.next(); - - String name= (String) entry.getKey(); - Object oldValue= oldOptions.get(name); - Object newValue= entry.getValue(); - - if ((oldValue != null && !oldValue.equals(newValue)) || (oldValue == null && newValue != null)) + Entry entry = (Entry) iter.next(); + + String name = (String) entry.getKey(); + Object oldValue = oldOptions.get(name); + Object newValue = entry.getValue(); + + if ((oldValue != null && !oldValue.equals(newValue)) + || (oldValue == null && newValue != null)) store.firePropertyChangeEvent(source, name, oldValue, newValue); oldOptions.remove(name); } - - iter= oldOptions.entrySet().iterator(); + + iter = oldOptions.entrySet().iterator(); while (iter.hasNext()) { - Entry entry= (Entry) iter.next(); - store.firePropertyChangeEvent(source, (String) entry.getKey(), entry.getValue(), null); + Entry entry = (Entry) iter.next(); + store.firePropertyChangeEvent(source, (String) entry.getKey(), + entry.getValue(), null); } } protected Shell getShell() { return fShell; } - + protected void setShell(Shell shell) { - fShell= shell; - } - + fShell = shell; + } + protected abstract Control createContents(Composite parent); - - protected Button addCheckBox(Composite parent, String label, String key, String[] values, int indent) { - ControlData data= new ControlData(key, values); - - GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); - gd.horizontalSpan= 3; - gd.horizontalIndent= indent; - - Button checkBox= new Button(parent, SWT.CHECK); + + protected Button addCheckBox(Composite parent, String label, String key, + String[] values, int indent) { + ControlData data = new ControlData(key, values); + + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + gd.horizontalSpan = 3; + gd.horizontalIndent = indent; + + Button checkBox = new Button(parent, SWT.CHECK); checkBox.setText(label); checkBox.setData(data); checkBox.setLayoutData(gd); checkBox.addSelectionListener(getSelectionListener()); - - String currValue= (String)fWorkingValues.get(key); + + String currValue = (String) fWorkingValues.get(key); checkBox.setSelection(data.getSelection(currValue) == 0); - + fCheckBoxes.add(checkBox); - + return checkBox; } - - protected Combo addComboBox(Composite parent, String label, String key, String[] values, String[] valueLabels, int indent) { - ControlData data= new ControlData(key, values); - - GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - gd.horizontalIndent= indent; - - Label labelControl= new Label(parent, SWT.LEFT | SWT.WRAP); + + protected Combo addComboBox(Composite parent, String label, String key, + String[] values, String[] valueLabels, int indent) { + ControlData data = new ControlData(key, values); + + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.horizontalIndent = indent; + + Label labelControl = new Label(parent, SWT.LEFT | SWT.WRAP); labelControl.setText(label); labelControl.setLayoutData(gd); - - Combo comboBox= new Combo(parent, SWT.READ_ONLY); + + Combo comboBox = new Combo(parent, SWT.READ_ONLY); comboBox.setItems(valueLabels); comboBox.setData(data); comboBox.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); comboBox.addSelectionListener(getSelectionListener()); - + fLabels.put(comboBox, labelControl); - - Label placeHolder= new Label(parent, SWT.NONE); + + Label placeHolder = new Label(parent, SWT.NONE); placeHolder.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - - String currValue= (String)fWorkingValues.get(key); + + String currValue = (String) fWorkingValues.get(key); comboBox.select(data.getSelection(currValue)); - + fComboBoxes.add(comboBox); return comboBox; } - - protected void addInversedComboBox(Composite parent, String label, String key, String[] values, String[] valueLabels, int indent) { - ControlData data= new ControlData(key, values); - - GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - gd.horizontalIndent= indent; - gd.horizontalSpan= 3; - - Composite composite= new Composite(parent, SWT.NONE); - GridLayout layout= new GridLayout(); - layout.marginHeight= 0; - layout.marginWidth= 0; - layout.numColumns= 2; + + protected void addInversedComboBox(Composite parent, String label, + String key, String[] values, String[] valueLabels, int indent) { + ControlData data = new ControlData(key, values); + + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.horizontalIndent = indent; + gd.horizontalSpan = 3; + + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginHeight = 0; + layout.marginWidth = 0; + layout.numColumns = 2; composite.setLayout(layout); composite.setLayoutData(gd); - - Combo comboBox= new Combo(composite, SWT.READ_ONLY); + + Combo comboBox = new Combo(composite, SWT.READ_ONLY); comboBox.setItems(valueLabels); comboBox.setData(data); comboBox.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); comboBox.addSelectionListener(getSelectionListener()); - - Label labelControl= new Label(composite, SWT.LEFT | SWT.WRAP); + + Label labelControl = new Label(composite, SWT.LEFT | SWT.WRAP); labelControl.setText(label); labelControl.setLayoutData(new GridData()); - + fLabels.put(comboBox, labelControl); - - String currValue= (String)fWorkingValues.get(key); + + String currValue = (String) fWorkingValues.get(key); comboBox.select(data.getSelection(currValue)); - + fComboBoxes.add(comboBox); } - - protected Text addTextField(Composite parent, String label, String key, int indent, int widthHint) { - Label labelControl= new Label(parent, SWT.NONE); + + protected Text addTextField(Composite parent, String label, String key, + int indent, int widthHint) { + Label labelControl = new Label(parent, SWT.NONE); labelControl.setText(label); labelControl.setLayoutData(new GridData()); - - Text textBox= new Text(parent, SWT.BORDER | SWT.SINGLE); + + Text textBox = new Text(parent, SWT.BORDER | SWT.SINGLE); textBox.setData(key); textBox.setLayoutData(new GridData()); - + fLabels.put(textBox, labelControl); - - String currValue= (String) fWorkingValues.get(key); + + String currValue = (String) fWorkingValues.get(key); if (currValue != null) { textBox.setText(currValue); } textBox.addModifyListener(getTextModifyListener()); - GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL); + GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); if (widthHint != 0) { - data.widthHint= widthHint; + data.widthHint = widthHint; } - data.horizontalIndent= indent; - data.horizontalSpan= 2; + data.horizontalIndent = indent; + data.horizontalSpan = 2; textBox.setLayoutData(data); fTextBoxes.add(textBox); return textBox; - } + } protected SelectionListener getSelectionListener() { if (fSelectionListener == null) { - fSelectionListener= new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) {} - + fSelectionListener = new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + } + public void widgetSelected(SelectionEvent e) { controlChanged(e.widget); } @@ -329,102 +350,103 @@ public abstract class OptionsConfigurationBlock { } return fSelectionListener; } - + protected ModifyListener getTextModifyListener() { if (fTextModifyListener == null) { - fTextModifyListener= new ModifyListener() { + fTextModifyListener = new ModifyListener() { public void modifyText(ModifyEvent e) { textChanged((Text) e.widget); } }; } return fTextModifyListener; - } - + } + protected void controlChanged(Widget widget) { - ControlData data= (ControlData) widget.getData(); - String newValue= null; + ControlData data = (ControlData) widget.getData(); + String newValue = null; if (widget instanceof Button) { - newValue= data.getValue(((Button)widget).getSelection()); + newValue = data.getValue(((Button) widget).getSelection()); } else if (widget instanceof Combo) { - newValue= data.getValue(((Combo)widget).getSelectionIndex()); + newValue = data.getValue(((Combo) widget).getSelectionIndex()); } else { return; } fWorkingValues.put(data.getKey(), newValue); - + validateSettings(data.getKey(), newValue); } - + protected void textChanged(Text textControl) { - String key= (String) textControl.getData(); - String number= textControl.getText(); + String key = (String) textControl.getData(); + String number = textControl.getText(); fWorkingValues.put(key, number); validateSettings(key, number); - } + } protected boolean checkValue(String key, String value) { return value.equals(fWorkingValues.get(key)); } - - /* (non-javadoc) - * Update fields and validate. - * @param changedKey Key that changed, or null, if all changed. - */ + + /* + * (non-javadoc) Update fields and validate. @param changedKey Key that + * changed, or null, if all changed. + */ protected abstract void validateSettings(String changedKey, String newValue); - - + protected String[] getTokens(String text, String separator) { - StringTokenizer tok= new StringTokenizer(text, separator); //$NON-NLS-1$ - int nTokens= tok.countTokens(); - String[] res= new String[nTokens]; - for (int i= 0; i < res.length; i++) { - res[i]= tok.nextToken().trim(); + StringTokenizer tok = new StringTokenizer(text, separator); //$NON-NLS-1$ + int nTokens = tok.countTokens(); + String[] res = new String[nTokens]; + for (int i = 0; i < res.length; i++) { + res[i] = tok.nextToken().trim(); } return res; - } + } - public boolean performOk(boolean enabled) { - String[] allKeys= fAllKeys; - Map actualOptions= getOptions(false); - + String[] allKeys = fAllKeys; + Map actualOptions = getOptions(false); + // preserve other options - boolean hasChanges= false; - for (int i= 0; i < allKeys.length; i++) { - String key= allKeys[i]; - String oldVal= (String) actualOptions.get(key); - String val= null; + boolean hasChanges = false; + for (int i = 0; i < allKeys.length; i++) { + String key = allKeys[i]; + String oldVal = (String) actualOptions.get(key); + String val = null; if (enabled) { - val= (String) fWorkingValues.get(key); + val = (String) fWorkingValues.get(key); if (val != null && !val.equals(oldVal)) { - hasChanges= true; + hasChanges = true; actualOptions.put(key, val); } } else { if (oldVal != null) { actualOptions.remove(key); - hasChanges= true; + hasChanges = true; } } } - - + if (hasChanges) { - boolean doBuild= false; - String[] strings= getFullBuildDialogStrings(fProject == null); + boolean doBuild = false; + String[] strings = getFullBuildDialogStrings(fProject == null); if (strings != null) { - MessageDialog dialog= new MessageDialog(getShell(), strings[0], null, strings[1], MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 2); - int res= dialog.open(); + MessageDialog dialog = new MessageDialog(getShell(), + strings[0], null, strings[1], MessageDialog.QUESTION, + new String[] { IDialogConstants.YES_LABEL, + IDialogConstants.NO_LABEL, + IDialogConstants.CANCEL_LABEL }, 2); + int res = dialog.open(); if (res == 0) { - doBuild= true; + doBuild = true; } else if (res != 1) { return false; // cancel pressed } } setOptions(actualOptions); if (doBuild) { - boolean res= doFullBuild(); + boolean res = doFullBuild(); if (!res) { return false; } @@ -432,117 +454,131 @@ public abstract class OptionsConfigurationBlock { } return true; } - - protected abstract String[] getFullBuildDialogStrings(boolean workspaceSettings); - + + protected abstract String[] getFullBuildDialogStrings( + boolean workspaceSettings); + protected boolean doFullBuild() { - - Job buildJob = new Job(PreferencesMessages.getString("OptionsConfigurationBlock.job.title")){ //$NON-NLS-1$ - /* (non-Javadoc) + + Job buildJob = new Job(PreferencesMessages + .getString("OptionsConfigurationBlock.job.title")) { //$NON-NLS-1$ + /* + * (non-Javadoc) + * * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor) */ protected IStatus run(IProgressMonitor monitor) { try { if (fProject != null) { - monitor.setTaskName(PreferencesMessages.getFormattedString("OptionsConfigurationBlock.buildproject.taskname", fProject.getElementName())); //$NON-NLS-1$ - fProject.getProject().build(IncrementalProjectBuilder.FULL_BUILD, new SubProgressMonitor(monitor,1)); - PHPeclipsePlugin.getWorkspace().build(IncrementalProjectBuilder.INCREMENTAL_BUILD, new SubProgressMonitor(monitor,1)); + monitor + .setTaskName(PreferencesMessages + .getFormattedString( + "OptionsConfigurationBlock.buildproject.taskname", fProject.getElementName())); //$NON-NLS-1$ + fProject.getProject().build( + IncrementalProjectBuilder.FULL_BUILD, + new SubProgressMonitor(monitor, 1)); + PHPeclipsePlugin.getWorkspace().build( + IncrementalProjectBuilder.INCREMENTAL_BUILD, + new SubProgressMonitor(monitor, 1)); } else { - monitor.setTaskName(PreferencesMessages.getString("OptionsConfigurationBlock.buildall.taskname")); //$NON-NLS-1$ - PHPeclipsePlugin.getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, new SubProgressMonitor(monitor, 2)); + monitor + .setTaskName(PreferencesMessages + .getString("OptionsConfigurationBlock.buildall.taskname")); //$NON-NLS-1$ + PHPeclipsePlugin.getWorkspace().build( + IncrementalProjectBuilder.FULL_BUILD, + new SubProgressMonitor(monitor, 2)); } } catch (CoreException e) { return e.getStatus(); } catch (OperationCanceledException e) { return Status.CANCEL_STATUS; - } - finally { + } finally { monitor.done(); } return Status.OK_STATUS; } + public boolean belongsTo(Object family) { return ResourcesPlugin.FAMILY_MANUAL_BUILD == family; } }; - - buildJob.setRule(ResourcesPlugin.getWorkspace().getRuleFactory().buildRule()); - buildJob.setUser(true); + + buildJob.setRule(ResourcesPlugin.getWorkspace().getRuleFactory() + .buildRule()); + buildJob.setUser(true); buildJob.schedule(); return true; - } - + } + public void performDefaults() { - fWorkingValues= getDefaultOptions(); + fWorkingValues = getDefaultOptions(); updateControls(); validateSettings(null, null); } - + protected void updateControls() { // update the UI - for (int i= fCheckBoxes.size() - 1; i >= 0; i--) { + for (int i = fCheckBoxes.size() - 1; i >= 0; i--) { updateCheckBox((Button) fCheckBoxes.get(i)); } - for (int i= fComboBoxes.size() - 1; i >= 0; i--) { + for (int i = fComboBoxes.size() - 1; i >= 0; i--) { updateCombo((Combo) fComboBoxes.get(i)); } - for (int i= fTextBoxes.size() - 1; i >= 0; i--) { + for (int i = fTextBoxes.size() - 1; i >= 0; i--) { updateText((Text) fTextBoxes.get(i)); } } - + protected void updateCombo(Combo curr) { - ControlData data= (ControlData) curr.getData(); - - String currValue= (String) fWorkingValues.get(data.getKey()); - curr.select(data.getSelection(currValue)); + ControlData data = (ControlData) curr.getData(); + + String currValue = (String) fWorkingValues.get(data.getKey()); + curr.select(data.getSelection(currValue)); } - + protected void updateCheckBox(Button curr) { - ControlData data= (ControlData) curr.getData(); - - String currValue= (String) fWorkingValues.get(data.getKey()); - curr.setSelection(data.getSelection(currValue) == 0); + ControlData data = (ControlData) curr.getData(); + + String currValue = (String) fWorkingValues.get(data.getKey()); + curr.setSelection(data.getSelection(currValue) == 0); } - + protected void updateText(Text curr) { - String key= (String) curr.getData(); - - String currValue= (String) fWorkingValues.get(key); + String key = (String) curr.getData(); + + String currValue = (String) fWorkingValues.get(key); if (currValue != null) { curr.setText(currValue); } } - + protected Button getCheckBox(String key) { - for (int i= fCheckBoxes.size() - 1; i >= 0; i--) { - Button curr= (Button) fCheckBoxes.get(i); - ControlData data= (ControlData) curr.getData(); + for (int i = fCheckBoxes.size() - 1; i >= 0; i--) { + Button curr = (Button) fCheckBoxes.get(i); + ControlData data = (ControlData) curr.getData(); if (key.equals(data.getKey())) { return curr; } } - return null; + return null; } - + protected Combo getComboBox(String key) { - for (int i= fComboBoxes.size() - 1; i >= 0; i--) { - Combo curr= (Combo) fComboBoxes.get(i); - ControlData data= (ControlData) curr.getData(); + for (int i = fComboBoxes.size() - 1; i >= 0; i--) { + Combo curr = (Combo) fComboBoxes.get(i); + ControlData data = (ControlData) curr.getData(); if (key.equals(data.getKey())) { return curr; } } - return null; + return null; } - + protected void setComboEnabled(String key, boolean enabled) { - Combo combo= getComboBox(key); - Label label= (Label) fLabels.get(combo); + Combo combo = getComboBox(key); + Label label = (Label) fLabels.get(combo); combo.setEnabled(enabled); label.setEnabled(enabled); } - - - + } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/OverlayPreferenceStore.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/OverlayPreferenceStore.java index acea1f5..e33b313 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/OverlayPreferenceStore.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/OverlayPreferenceStore.java @@ -8,7 +8,7 @@ * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ - + package net.sourceforge.phpdt.internal.ui.preferences; import org.eclipse.jface.preference.IPreferenceStore; @@ -20,222 +20,233 @@ import org.eclipse.jface.util.PropertyChangeEvent; /** * An overlaying preference store. */ -public class OverlayPreferenceStore implements IPreferenceStore { - - +public class OverlayPreferenceStore implements IPreferenceStore { + public static final class TypeDescriptor { private TypeDescriptor() { } } - - public static final TypeDescriptor BOOLEAN= new TypeDescriptor(); - public static final TypeDescriptor DOUBLE= new TypeDescriptor(); - public static final TypeDescriptor FLOAT= new TypeDescriptor(); - public static final TypeDescriptor INT= new TypeDescriptor(); - public static final TypeDescriptor LONG= new TypeDescriptor(); - public static final TypeDescriptor STRING= new TypeDescriptor(); - + + public static final TypeDescriptor BOOLEAN = new TypeDescriptor(); + + public static final TypeDescriptor DOUBLE = new TypeDescriptor(); + + public static final TypeDescriptor FLOAT = new TypeDescriptor(); + + public static final TypeDescriptor INT = new TypeDescriptor(); + + public static final TypeDescriptor LONG = new TypeDescriptor(); + + public static final TypeDescriptor STRING = new TypeDescriptor(); + public static class OverlayKey { - + TypeDescriptor fDescriptor; + String fKey; - + public OverlayKey(TypeDescriptor descriptor, String key) { - fDescriptor= descriptor; - fKey= key; + fDescriptor = descriptor; + fKey = key; } } - + private class PropertyListener implements IPropertyChangeListener { - + /* * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { - OverlayKey key= findOverlayKey(event.getProperty()); + OverlayKey key = findOverlayKey(event.getProperty()); if (key != null) - propagateProperty(fParent, key, fStore); + propagateProperty(fParent, key, fStore); } } - - + private IPreferenceStore fParent; + private IPreferenceStore fStore; + private OverlayKey[] fOverlayKeys; - + private PropertyListener fPropertyListener; + private boolean fLoaded; - - - public OverlayPreferenceStore(IPreferenceStore parent, OverlayKey[] overlayKeys) { - fParent= parent; - fOverlayKeys= overlayKeys; - fStore= new PreferenceStore(); - } - + + public OverlayPreferenceStore(IPreferenceStore parent, + OverlayKey[] overlayKeys) { + fParent = parent; + fOverlayKeys = overlayKeys; + fStore = new PreferenceStore(); + } + private OverlayKey findOverlayKey(String key) { - for (int i= 0; i < fOverlayKeys.length; i++) { + for (int i = 0; i < fOverlayKeys.length; i++) { if (fOverlayKeys[i].fKey.equals(key)) return fOverlayKeys[i]; } return null; } - + private boolean covers(String key) { return (findOverlayKey(key) != null); } - - private void propagateProperty(IPreferenceStore orgin, OverlayKey key, IPreferenceStore target) { - + + private void propagateProperty(IPreferenceStore orgin, OverlayKey key, + IPreferenceStore target) { + if (orgin.isDefault(key.fKey)) { if (!target.isDefault(key.fKey)) target.setToDefault(key.fKey); return; } - - TypeDescriptor d= key.fDescriptor; + + TypeDescriptor d = key.fDescriptor; if (BOOLEAN == d) { - - boolean originValue= orgin.getBoolean(key.fKey); - boolean targetValue= target.getBoolean(key.fKey); + + boolean originValue = orgin.getBoolean(key.fKey); + boolean targetValue = target.getBoolean(key.fKey); if (targetValue != originValue) target.setValue(key.fKey, originValue); - + } else if (DOUBLE == d) { - - double originValue= orgin.getDouble(key.fKey); - double targetValue= target.getDouble(key.fKey); + + double originValue = orgin.getDouble(key.fKey); + double targetValue = target.getDouble(key.fKey); if (targetValue != originValue) target.setValue(key.fKey, originValue); - + } else if (FLOAT == d) { - - float originValue= orgin.getFloat(key.fKey); - float targetValue= target.getFloat(key.fKey); + + float originValue = orgin.getFloat(key.fKey); + float targetValue = target.getFloat(key.fKey); if (targetValue != originValue) target.setValue(key.fKey, originValue); - + } else if (INT == d) { - int originValue= orgin.getInt(key.fKey); - int targetValue= target.getInt(key.fKey); + int originValue = orgin.getInt(key.fKey); + int targetValue = target.getInt(key.fKey); if (targetValue != originValue) target.setValue(key.fKey, originValue); } else if (LONG == d) { - long originValue= orgin.getLong(key.fKey); - long targetValue= target.getLong(key.fKey); + long originValue = orgin.getLong(key.fKey); + long targetValue = target.getLong(key.fKey); if (targetValue != originValue) target.setValue(key.fKey, originValue); } else if (STRING == d) { - String originValue= orgin.getString(key.fKey); - String targetValue= target.getString(key.fKey); - if (targetValue != null && originValue != null && !targetValue.equals(originValue)) + String originValue = orgin.getString(key.fKey); + String targetValue = target.getString(key.fKey); + if (targetValue != null && originValue != null + && !targetValue.equals(originValue)) target.setValue(key.fKey, originValue); } } - + public void propagate() { - for (int i= 0; i < fOverlayKeys.length; i++) + for (int i = 0; i < fOverlayKeys.length; i++) propagateProperty(fStore, fOverlayKeys[i], fParent); } - - private void loadProperty(IPreferenceStore orgin, OverlayKey key, IPreferenceStore target, boolean forceInitialization) { - TypeDescriptor d= key.fDescriptor; + + private void loadProperty(IPreferenceStore orgin, OverlayKey key, + IPreferenceStore target, boolean forceInitialization) { + TypeDescriptor d = key.fDescriptor; if (BOOLEAN == d) { - + if (forceInitialization) target.setValue(key.fKey, true); target.setValue(key.fKey, orgin.getBoolean(key.fKey)); target.setDefault(key.fKey, orgin.getDefaultBoolean(key.fKey)); - + } else if (DOUBLE == d) { - + if (forceInitialization) target.setValue(key.fKey, 1.0D); target.setValue(key.fKey, orgin.getDouble(key.fKey)); target.setDefault(key.fKey, orgin.getDefaultDouble(key.fKey)); - + } else if (FLOAT == d) { - + if (forceInitialization) target.setValue(key.fKey, 1.0F); target.setValue(key.fKey, orgin.getFloat(key.fKey)); target.setDefault(key.fKey, orgin.getDefaultFloat(key.fKey)); - + } else if (INT == d) { - + if (forceInitialization) target.setValue(key.fKey, 1); target.setValue(key.fKey, orgin.getInt(key.fKey)); target.setDefault(key.fKey, orgin.getDefaultInt(key.fKey)); - + } else if (LONG == d) { - + if (forceInitialization) target.setValue(key.fKey, 1L); target.setValue(key.fKey, orgin.getLong(key.fKey)); target.setDefault(key.fKey, orgin.getDefaultLong(key.fKey)); - + } else if (STRING == d) { - + if (forceInitialization) target.setValue(key.fKey, "1"); //$NON-NLS-1$ target.setValue(key.fKey, orgin.getString(key.fKey)); target.setDefault(key.fKey, orgin.getDefaultString(key.fKey)); - + } } - + public void load() { - for (int i= 0; i < fOverlayKeys.length; i++) + for (int i = 0; i < fOverlayKeys.length; i++) loadProperty(fParent, fOverlayKeys[i], fStore, true); - - fLoaded= true; - + + fLoaded = true; + } - + public void loadDefaults() { - for (int i= 0; i < fOverlayKeys.length; i++) + for (int i = 0; i < fOverlayKeys.length; i++) setToDefault(fOverlayKeys[i].fKey); } - + public void start() { if (fPropertyListener == null) { - fPropertyListener= new PropertyListener(); + fPropertyListener = new PropertyListener(); fParent.addPropertyChangeListener(fPropertyListener); } } - + public void stop() { - if (fPropertyListener != null) { + if (fPropertyListener != null) { fParent.removePropertyChangeListener(fPropertyListener); - fPropertyListener= null; + fPropertyListener = null; } } - + /* * @see IPreferenceStore#addPropertyChangeListener(IPropertyChangeListener) */ public void addPropertyChangeListener(IPropertyChangeListener listener) { fStore.addPropertyChangeListener(listener); } - + /* * @see IPreferenceStore#removePropertyChangeListener(IPropertyChangeListener) */ public void removePropertyChangeListener(IPropertyChangeListener listener) { fStore.removePropertyChangeListener(listener); } - + /* * @see IPreferenceStore#firePropertyChangeEvent(String, Object, Object) */ - public void firePropertyChangeEvent(String name, Object oldValue, Object newValue) { + public void firePropertyChangeEvent(String name, Object oldValue, + Object newValue) { fStore.firePropertyChangeEvent(name, oldValue, newValue); } @@ -245,7 +256,7 @@ public class OverlayPreferenceStore implements IPreferenceStore { public boolean contains(String name) { return fStore.contains(name); } - + /* * @see IPreferenceStore#getBoolean(String) */ @@ -458,7 +469,7 @@ public class OverlayPreferenceStore implements IPreferenceStore { /** * The keys to add to the list of overlay keys. *

                                                      - * Note: This method must be called before {@link #load()} is called. + * Note: This method must be called before {@link #load()} is called. *

                                                      * * @param keys @@ -467,18 +478,18 @@ public class OverlayPreferenceStore implements IPreferenceStore { public void addKeys(OverlayKey[] keys) { Assert.isTrue(!fLoaded); Assert.isNotNull(keys); - - int overlayKeysLength= fOverlayKeys.length; - OverlayKey[] result= new OverlayKey[keys.length + overlayKeysLength]; - - for (int i= 0, length= overlayKeysLength; i < length; i++) - result[i]= fOverlayKeys[i]; - - for (int i= 0, length= keys.length; i < length; i++) - result[overlayKeysLength + i]= keys[i]; - - fOverlayKeys= result; - + + int overlayKeysLength = fOverlayKeys.length; + OverlayKey[] result = new OverlayKey[keys.length + overlayKeysLength]; + + for (int i = 0, length = overlayKeysLength; i < length; i++) + result[i] = fOverlayKeys[i]; + + for (int i = 0, length = keys.length; i < length; i++) + result[overlayKeysLength + i] = keys[i]; + + fOverlayKeys = result; + if (fLoaded) load(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/PreferencesMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/PreferencesMessages.java index 00526df..2356ede 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/PreferencesMessages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/PreferencesMessages.java @@ -16,9 +16,10 @@ import java.util.ResourceBundle; public class PreferencesMessages { - private static final String RESOURCE_BUNDLE= "net.sourceforge.phpdt.internal.ui.preferences.PreferencesMessages";//$NON-NLS-1$ + private static final String RESOURCE_BUNDLE = "net.sourceforge.phpdt.internal.ui.preferences.PreferencesMessages";//$NON-NLS-1$ - private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); + private static ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); private PreferencesMessages() { } @@ -30,13 +31,13 @@ public class PreferencesMessages { return '!' + key + '!'; } } - + public static String getFormattedString(String key, String arg) { return getFormattedString(key, new String[] { arg }); } - + public static String getFormattedString(String key, String[] args) { - return MessageFormat.format(getString(key), args); - } - + return MessageFormat.format(getString(key), args); + } + } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/SpellingConfigurationBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/SpellingConfigurationBlock.java index c1973a8..f676e4f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/SpellingConfigurationBlock.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/SpellingConfigurationBlock.java @@ -52,27 +52,37 @@ import org.eclipse.swt.widgets.Text; public class SpellingConfigurationBlock extends OptionsConfigurationBlock { /** Preference keys for the preferences in this block */ - private static final String PREF_SPELLING_CHECK_SPELLING= PreferenceConstants.SPELLING_CHECK_SPELLING; - private static final String PREF_SPELLING_IGNORE_DIGITS= PreferenceConstants.SPELLING_IGNORE_DIGITS; - private static final String PREF_SPELLING_IGNORE_MIXED= PreferenceConstants.SPELLING_IGNORE_MIXED; - private static final String PREF_SPELLING_IGNORE_SENTENCE= PreferenceConstants.SPELLING_IGNORE_SENTENCE; - private static final String PREF_SPELLING_IGNORE_UPPER= PreferenceConstants.SPELLING_IGNORE_UPPER; - private static final String PREF_SPELLING_IGNORE_URLS= PreferenceConstants.SPELLING_IGNORE_URLS; - private static final String PREF_SPELLING_LOCALE= PreferenceConstants.SPELLING_LOCALE; - private static final String PREF_SPELLING_PROPOSAL_THRESHOLD= PreferenceConstants.SPELLING_PROPOSAL_THRESHOLD; - private static final String PREF_SPELLING_USER_DICTIONARY= PreferenceConstants.SPELLING_USER_DICTIONARY; - private static final String PREF_SPELLING_ENABLE_CONTENTASSIST= PreferenceConstants.SPELLING_ENABLE_CONTENTASSIST; + private static final String PREF_SPELLING_CHECK_SPELLING = PreferenceConstants.SPELLING_CHECK_SPELLING; + + private static final String PREF_SPELLING_IGNORE_DIGITS = PreferenceConstants.SPELLING_IGNORE_DIGITS; + + private static final String PREF_SPELLING_IGNORE_MIXED = PreferenceConstants.SPELLING_IGNORE_MIXED; + + private static final String PREF_SPELLING_IGNORE_SENTENCE = PreferenceConstants.SPELLING_IGNORE_SENTENCE; + + private static final String PREF_SPELLING_IGNORE_UPPER = PreferenceConstants.SPELLING_IGNORE_UPPER; + + private static final String PREF_SPELLING_IGNORE_URLS = PreferenceConstants.SPELLING_IGNORE_URLS; + + private static final String PREF_SPELLING_LOCALE = PreferenceConstants.SPELLING_LOCALE; + + private static final String PREF_SPELLING_PROPOSAL_THRESHOLD = PreferenceConstants.SPELLING_PROPOSAL_THRESHOLD; + + private static final String PREF_SPELLING_USER_DICTIONARY = PreferenceConstants.SPELLING_USER_DICTIONARY; + + private static final String PREF_SPELLING_ENABLE_CONTENTASSIST = PreferenceConstants.SPELLING_ENABLE_CONTENTASSIST; /** * Creates a selection dependency between a master and a slave control. * * @param master - * The master button that controls the state of the slave + * The master button that controls the state of the slave * @param slave - * The slave control that is enabled only if the master is - * selected + * The slave control that is enabled only if the master is + * selected */ - protected static void createSelectionDependency(final Button master, final Control slave) { + protected static void createSelectionDependency(final Button master, + final Control slave) { master.addSelectionListener(new SelectionListener() { @@ -91,19 +101,19 @@ public class SpellingConfigurationBlock extends OptionsConfigurationBlock { * Returns the locale codes for the locale list. * * @param locales - * The list of locales + * The list of locales * @return Array of locale codes for the list */ protected static String[] getDictionaryCodes(final Set locales) { - int index= 0; - Locale locale= null; + int index = 0; + Locale locale = null; - final String[] codes= new String[locales.size()]; - for (final Iterator iterator= locales.iterator(); iterator.hasNext();) { + final String[] codes = new String[locales.size()]; + for (final Iterator iterator = locales.iterator(); iterator.hasNext();) { - locale= (Locale)iterator.next(); - codes[index++]= locale.toString(); + locale = (Locale) iterator.next(); + codes[index++] = locale.toString(); } return codes; } @@ -112,19 +122,20 @@ public class SpellingConfigurationBlock extends OptionsConfigurationBlock { * Returns the display labels for the locale list. * * @param locales - * The list of locales + * The list of locales * @return Array of display labels for the list */ protected static String[] getDictionaryLabels(final Set locales) { - int index= 0; - Locale locale= null; + int index = 0; + Locale locale = null; - final String[] labels= new String[locales.size()]; - for (final Iterator iterator= locales.iterator(); iterator.hasNext();) { + final String[] labels = new String[locales.size()]; + for (final Iterator iterator = locales.iterator(); iterator.hasNext();) { - locale= (Locale)iterator.next(); - labels[index++]= locale.getDisplayName(SpellCheckEngine.getDefaultLocale()); + locale = (Locale) iterator.next(); + labels[index++] = locale.getDisplayName(SpellCheckEngine + .getDefaultLocale()); } return labels; } @@ -134,18 +145,20 @@ public class SpellingConfigurationBlock extends OptionsConfigurationBlock { * be opened. * * @param path - * The path of the file to validate + * The path of the file to validate * @return true iff the file exists and can be opened, - * false otherwise + * false otherwise */ protected static IStatus validateAbsoluteFilePath(final String path) { - final StatusInfo status= new StatusInfo(); + final StatusInfo status = new StatusInfo(); if (path.length() > 0) { - final File file= new File(path); - if (!file.isFile() || !file.isAbsolute() || !file.exists() || !file.canRead() || !file.canWrite()) - status.setError(PreferencesMessages.getString("SpellingPreferencePage.dictionary.error")); //$NON-NLS-1$ + final File file = new File(path); + if (!file.isFile() || !file.isAbsolute() || !file.exists() + || !file.canRead() || !file.canWrite()) + status.setError(PreferencesMessages + .getString("SpellingPreferencePage.dictionary.error")); //$NON-NLS-1$ } return status; @@ -155,18 +168,20 @@ public class SpellingConfigurationBlock extends OptionsConfigurationBlock { * Validates that the specified locale is available. * * @param locale - * The locale to validate + * The locale to validate * @return The status of the validation */ protected static IStatus validateLocale(final String locale) { - final StatusInfo status= new StatusInfo(IStatus.ERROR, PreferencesMessages.getString("SpellingPreferencePage.locale.error")); //$NON-NLS-1$ - final Set locales= SpellCheckEngine.getAvailableLocales(); + final StatusInfo status = new StatusInfo(IStatus.ERROR, + PreferencesMessages + .getString("SpellingPreferencePage.locale.error")); //$NON-NLS-1$ + final Set locales = SpellCheckEngine.getAvailableLocales(); - Locale current= null; - for (final Iterator iterator= locales.iterator(); iterator.hasNext();) { + Locale current = null; + for (final Iterator iterator = locales.iterator(); iterator.hasNext();) { - current= (Locale)iterator.next(); + current = (Locale) iterator.next(); if (current.toString().equals(locale)) return new StatusInfo(); } @@ -177,82 +192,92 @@ public class SpellingConfigurationBlock extends OptionsConfigurationBlock { * Validates that the specified number is positive. * * @param number - * The number to validate + * The number to validate * @return The status of the validation */ protected static IStatus validatePositiveNumber(final String number) { - final StatusInfo status= new StatusInfo(); + final StatusInfo status = new StatusInfo(); if (number.length() == 0) { - status.setError(PreferencesMessages.getString("SpellingPreferencePage.empty_threshold")); //$NON-NLS-1$ + status.setError(PreferencesMessages + .getString("SpellingPreferencePage.empty_threshold")); //$NON-NLS-1$ } else { try { - final int value= Integer.parseInt(number); + final int value = Integer.parseInt(number); if (value < 0) { - status.setError(PreferencesMessages.getFormattedString("SpellingPreferencePage.invalid_threshold", number)); //$NON-NLS-1$ + status + .setError(PreferencesMessages + .getFormattedString( + "SpellingPreferencePage.invalid_threshold", number)); //$NON-NLS-1$ } } catch (NumberFormatException exception) { - status.setError(PreferencesMessages.getFormattedString("SpellingPreferencePage.invalid_threshold", number)); //$NON-NLS-1$ + status.setError(PreferencesMessages.getFormattedString( + "SpellingPreferencePage.invalid_threshold", number)); //$NON-NLS-1$ } } return status; } /** The dictionary path field */ - private Text fDictionaryPath= null; + private Text fDictionaryPath = null; /** The status for the workspace dictionary file */ - private IStatus fFileStatus= new StatusInfo(); + private IStatus fFileStatus = new StatusInfo(); /** The status for the platform locale */ - private IStatus fLocaleStatus= new StatusInfo(); + private IStatus fLocaleStatus = new StatusInfo(); /** The status for the proposal threshold */ - private IStatus fThresholdStatus= new StatusInfo(); + private IStatus fThresholdStatus = new StatusInfo(); /** * Creates a new spelling configuration block. * * @param context - * The status change listener + * The status change listener * @param project - * The Java project + * The Java project */ - public SpellingConfigurationBlock(final IStatusChangeListener context, final IJavaProject project) { + public SpellingConfigurationBlock(final IStatusChangeListener context, + final IJavaProject project) { super(context, project, getAllKeys()); - - IStatus status= validateAbsoluteFilePath((String)fWorkingValues.get(PREF_SPELLING_USER_DICTIONARY)); + + IStatus status = validateAbsoluteFilePath((String) fWorkingValues + .get(PREF_SPELLING_USER_DICTIONARY)); if (status.getSeverity() != IStatus.OK) fWorkingValues.put(PREF_SPELLING_USER_DICTIONARY, ""); //$NON-NLS-1$ - status= validateLocale((String)fWorkingValues.get(PREF_SPELLING_LOCALE)); + status = validateLocale((String) fWorkingValues + .get(PREF_SPELLING_LOCALE)); if (status.getSeverity() != IStatus.OK) - fWorkingValues.put(PREF_SPELLING_LOCALE, SpellCheckEngine.getDefaultLocale().toString()); + fWorkingValues.put(PREF_SPELLING_LOCALE, SpellCheckEngine + .getDefaultLocale().toString()); } - protected Combo addComboBox(Composite parent, String label, String key, String[] values, String[] valueLabels, int indent) { - ControlData data= new ControlData(key, values); - - GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - gd.horizontalIndent= indent; - - Label labelControl= new Label(parent, SWT.LEFT | SWT.WRAP); + protected Combo addComboBox(Composite parent, String label, String key, + String[] values, String[] valueLabels, int indent) { + ControlData data = new ControlData(key, values); + + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.horizontalIndent = indent; + + Label labelControl = new Label(parent, SWT.LEFT | SWT.WRAP); labelControl.setText(label); labelControl.setLayoutData(gd); - - Combo comboBox= new Combo(parent, SWT.READ_ONLY); + + Combo comboBox = new Combo(parent, SWT.READ_ONLY); comboBox.setItems(valueLabels); comboBox.setData(data); - gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); - gd.horizontalSpan= 2; + gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + gd.horizontalSpan = 2; comboBox.setLayoutData(gd); comboBox.addSelectionListener(getSelectionListener()); - + fLabels.put(comboBox, labelControl); - - String currValue= (String)fWorkingValues.get(key); + + String currValue = (String) fWorkingValues.get(key); comboBox.select(data.getSelection(currValue)); - + fComboBoxes.add(comboBox); return comboBox; } @@ -262,66 +287,86 @@ public class SpellingConfigurationBlock extends OptionsConfigurationBlock { */ protected Control createContents(final Composite parent) { - Composite composite= new Composite(parent, SWT.NONE); - GridLayout layout= new GridLayout(); layout.numColumns= 1; + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.numColumns = 1; composite.setLayout(layout); - final PixelConverter converter= new PixelConverter(parent); + final PixelConverter converter = new PixelConverter(parent); - layout= new GridLayout(); - layout.numColumns= 3; + layout = new GridLayout(); + layout.numColumns = 3; - final String[] trueFalse= new String[] { IPreferenceStore.TRUE, IPreferenceStore.FALSE }; + final String[] trueFalse = new String[] { IPreferenceStore.TRUE, + IPreferenceStore.FALSE }; - Group user= new Group(composite, SWT.NONE); - user.setText(PreferencesMessages.getString("SpellingPreferencePage.preferences.user")); //$NON-NLS-1$ - user.setLayout(new GridLayout()); + Group user = new Group(composite, SWT.NONE); + user.setText(PreferencesMessages + .getString("SpellingPreferencePage.preferences.user")); //$NON-NLS-1$ + user.setLayout(new GridLayout()); user.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - String label= PreferencesMessages.getString("SpellingPreferencePage.enable.label"); //$NON-NLS-1$ - final Button master= addCheckBox(user, label, PREF_SPELLING_CHECK_SPELLING, trueFalse, 0); + String label = PreferencesMessages + .getString("SpellingPreferencePage.enable.label"); //$NON-NLS-1$ + final Button master = addCheckBox(user, label, + PREF_SPELLING_CHECK_SPELLING, trueFalse, 0); - label= PreferencesMessages.getString("SpellingPreferencePage.ignore.digits.label"); //$NON-NLS-1$ - Control slave= addCheckBox(user, label, PREF_SPELLING_IGNORE_DIGITS, trueFalse, 20); + label = PreferencesMessages + .getString("SpellingPreferencePage.ignore.digits.label"); //$NON-NLS-1$ + Control slave = addCheckBox(user, label, PREF_SPELLING_IGNORE_DIGITS, + trueFalse, 20); createSelectionDependency(master, slave); - label= PreferencesMessages.getString("SpellingPreferencePage.ignore.mixed.label"); //$NON-NLS-1$ - slave= addCheckBox(user, label, PREF_SPELLING_IGNORE_MIXED, trueFalse, 20); + label = PreferencesMessages + .getString("SpellingPreferencePage.ignore.mixed.label"); //$NON-NLS-1$ + slave = addCheckBox(user, label, PREF_SPELLING_IGNORE_MIXED, trueFalse, + 20); createSelectionDependency(master, slave); - label= PreferencesMessages.getString("SpellingPreferencePage.ignore.sentence.label"); //$NON-NLS-1$ - slave= addCheckBox(user, label, PREF_SPELLING_IGNORE_SENTENCE, trueFalse, 20); + label = PreferencesMessages + .getString("SpellingPreferencePage.ignore.sentence.label"); //$NON-NLS-1$ + slave = addCheckBox(user, label, PREF_SPELLING_IGNORE_SENTENCE, + trueFalse, 20); createSelectionDependency(master, slave); - label= PreferencesMessages.getString("SpellingPreferencePage.ignore.upper.label"); //$NON-NLS-1$ - slave= addCheckBox(user, label, PREF_SPELLING_IGNORE_UPPER, trueFalse, 20); + label = PreferencesMessages + .getString("SpellingPreferencePage.ignore.upper.label"); //$NON-NLS-1$ + slave = addCheckBox(user, label, PREF_SPELLING_IGNORE_UPPER, trueFalse, + 20); createSelectionDependency(master, slave); - label= PreferencesMessages.getString("SpellingPreferencePage.ignore.url.label"); //$NON-NLS-1$ - slave= addCheckBox(user, label, PREF_SPELLING_IGNORE_URLS, trueFalse, 20); + label = PreferencesMessages + .getString("SpellingPreferencePage.ignore.url.label"); //$NON-NLS-1$ + slave = addCheckBox(user, label, PREF_SPELLING_IGNORE_URLS, trueFalse, + 20); createSelectionDependency(master, slave); - final Group engine= new Group(composite, SWT.NONE); - engine.setText(PreferencesMessages.getString("SpellingPreferencePage.preferences.engine")); //$NON-NLS-1$ - layout= new GridLayout(); - layout.numColumns= 4; + final Group engine = new Group(composite, SWT.NONE); + engine.setText(PreferencesMessages + .getString("SpellingPreferencePage.preferences.engine")); //$NON-NLS-1$ + layout = new GridLayout(); + layout.numColumns = 4; engine.setLayout(layout); engine.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - label= PreferencesMessages.getString("SpellingPreferencePage.dictionary.label"); //$NON-NLS-1$ - final Set locales= SpellCheckEngine.getAvailableLocales(); + label = PreferencesMessages + .getString("SpellingPreferencePage.dictionary.label"); //$NON-NLS-1$ + final Set locales = SpellCheckEngine.getAvailableLocales(); - Combo combo= addComboBox(engine, label, PREF_SPELLING_LOCALE, getDictionaryCodes(locales), getDictionaryLabels(locales), 0); + Combo combo = addComboBox(engine, label, PREF_SPELLING_LOCALE, + getDictionaryCodes(locales), getDictionaryLabels(locales), 0); combo.setEnabled(locales.size() > 1); - + new Label(engine, SWT.NONE); // placeholder - label= PreferencesMessages.getString("SpellingPreferencePage.workspace.dictionary.label"); //$NON-NLS-1$ - fDictionaryPath= addTextField(engine, label, PREF_SPELLING_USER_DICTIONARY, 0, 0); + label = PreferencesMessages + .getString("SpellingPreferencePage.workspace.dictionary.label"); //$NON-NLS-1$ + fDictionaryPath = addTextField(engine, label, + PREF_SPELLING_USER_DICTIONARY, 0, 0); - - Button button= new Button(engine, SWT.PUSH); - button.setText(PreferencesMessages.getString("SpellingPreferencePage.browse.label")); //$NON-NLS-1$ + Button button = new Button(engine, SWT.PUSH); + button.setText(PreferencesMessages + .getString("SpellingPreferencePage.browse.label")); //$NON-NLS-1$ button.addSelectionListener(new SelectionAdapter() { public void widgetSelected(final SelectionEvent event) { @@ -330,32 +375,42 @@ public class SpellingConfigurationBlock extends OptionsConfigurationBlock { }); button.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); SWTUtil.setButtonDimensionHint(button); - - layout= new GridLayout(); - layout.numColumns= 3; - - Group advanced= new Group(composite, SWT.NONE); - advanced.setText(PreferencesMessages.getString("SpellingPreferencePage.preferences.advanced")); //$NON-NLS-1$ - layout= new GridLayout(); - layout.numColumns= 3; - advanced.setLayout(layout); + + layout = new GridLayout(); + layout.numColumns = 3; + + Group advanced = new Group(composite, SWT.NONE); + advanced.setText(PreferencesMessages + .getString("SpellingPreferencePage.preferences.advanced")); //$NON-NLS-1$ + layout = new GridLayout(); + layout.numColumns = 3; + advanced.setLayout(layout); advanced.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - - label= PreferencesMessages.getString("SpellingPreferencePage.proposals.threshold"); //$NON-NLS-1$ - Text text= addTextField(advanced, label, PREF_SPELLING_PROPOSAL_THRESHOLD, 0, 0); + + label = PreferencesMessages + .getString("SpellingPreferencePage.proposals.threshold"); //$NON-NLS-1$ + Text text = addTextField(advanced, label, + PREF_SPELLING_PROPOSAL_THRESHOLD, 0, 0); text.setTextLimit(3); - GridData data= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - data.widthHint= converter.convertWidthInCharsToPixels(4); + GridData data = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + data.widthHint = converter.convertWidthInCharsToPixels(4); text.setLayoutData(data); - - label= PreferencesMessages.getString("SpellingPreferencePage.enable.contentassist.label"); //$NON-NLS-1$ - addCheckBox(advanced, label, PREF_SPELLING_ENABLE_CONTENTASSIST, trueFalse, 0); + + label = PreferencesMessages + .getString("SpellingPreferencePage.enable.contentassist.label"); //$NON-NLS-1$ + addCheckBox(advanced, label, PREF_SPELLING_ENABLE_CONTENTASSIST, + trueFalse, 0); return composite; } private static String[] getAllKeys() { - return new String[] { PREF_SPELLING_USER_DICTIONARY, PREF_SPELLING_CHECK_SPELLING, PREF_SPELLING_IGNORE_DIGITS, PREF_SPELLING_IGNORE_MIXED, PREF_SPELLING_IGNORE_SENTENCE, PREF_SPELLING_IGNORE_UPPER, PREF_SPELLING_IGNORE_URLS, PREF_SPELLING_LOCALE, PREF_SPELLING_PROPOSAL_THRESHOLD, PREF_SPELLING_ENABLE_CONTENTASSIST }; + return new String[] { PREF_SPELLING_USER_DICTIONARY, + PREF_SPELLING_CHECK_SPELLING, PREF_SPELLING_IGNORE_DIGITS, + PREF_SPELLING_IGNORE_MIXED, PREF_SPELLING_IGNORE_SENTENCE, + PREF_SPELLING_IGNORE_UPPER, PREF_SPELLING_IGNORE_URLS, + PREF_SPELLING_LOCALE, PREF_SPELLING_PROPOSAL_THRESHOLD, + PREF_SPELLING_ENABLE_CONTENTASSIST }; } /* @@ -363,11 +418,11 @@ public class SpellingConfigurationBlock extends OptionsConfigurationBlock { */ protected Map getDefaultOptions() { - final String[] keys= fAllKeys; - final Map options= new HashMap(); - final IPreferenceStore store= PreferenceConstants.getPreferenceStore(); + final String[] keys = fAllKeys; + final Map options = new HashMap(); + final IPreferenceStore store = PreferenceConstants.getPreferenceStore(); - for (int index= 0; index < keys.length; index++) + for (int index = 0; index < keys.length; index++) options.put(keys[index], store.getDefaultString(keys[index])); return options; @@ -385,11 +440,11 @@ public class SpellingConfigurationBlock extends OptionsConfigurationBlock { */ protected Map getOptions(final boolean inherit) { - final String[] keys= fAllKeys; - final Map options= new HashMap(); - final IPreferenceStore store= PreferenceConstants.getPreferenceStore(); + final String[] keys = fAllKeys; + final Map options = new HashMap(); + final IPreferenceStore store = PreferenceConstants.getPreferenceStore(); - for (int index= 0; index < keys.length; index++) + for (int index = 0; index < keys.length; index++) options.put(keys[index], store.getString(keys[index])); return options; @@ -400,12 +455,20 @@ public class SpellingConfigurationBlock extends OptionsConfigurationBlock { */ protected void handleBrowseButtonSelected() { - final FileDialog dialog= new FileDialog(fDictionaryPath.getShell(), SWT.OPEN); - dialog.setText(PreferencesMessages.getString("SpellingPreferencePage.filedialog.title")); //$NON-NLS-1$ - dialog.setFilterExtensions(new String[] { PreferencesMessages.getString("SpellingPreferencePage.filter.dictionary.extension"), PreferencesMessages.getString("SpellingPreferencePage.filter.all.extension") }); //$NON-NLS-1$ //$NON-NLS-2$ - dialog.setFilterNames(new String[] { PreferencesMessages.getString("SpellingPreferencePage.filter.dictionary.label"), PreferencesMessages.getString("SpellingPreferencePage.filter.all.label") }); //$NON-NLS-1$ //$NON-NLS-2$ - - final String path= dialog.open(); + final FileDialog dialog = new FileDialog(fDictionaryPath.getShell(), + SWT.OPEN); + dialog.setText(PreferencesMessages + .getString("SpellingPreferencePage.filedialog.title")); //$NON-NLS-1$ + dialog + .setFilterExtensions(new String[] { + PreferencesMessages + .getString("SpellingPreferencePage.filter.dictionary.extension"), PreferencesMessages.getString("SpellingPreferencePage.filter.all.extension") }); //$NON-NLS-1$ //$NON-NLS-2$ + dialog + .setFilterNames(new String[] { + PreferencesMessages + .getString("SpellingPreferencePage.filter.dictionary.label"), PreferencesMessages.getString("SpellingPreferencePage.filter.all.label") }); //$NON-NLS-1$ //$NON-NLS-2$ + + final String path = dialog.open(); if (path != null) fDictionaryPath.setText(path); } @@ -415,11 +478,12 @@ public class SpellingConfigurationBlock extends OptionsConfigurationBlock { */ protected void setOptions(final Map options) { - final String[] keys= fAllKeys; - final IPreferenceStore store= PreferenceConstants.getPreferenceStore(); + final String[] keys = fAllKeys; + final IPreferenceStore store = PreferenceConstants.getPreferenceStore(); - for (int index= 0; index < keys.length; index++) - store.setValue(keys[index], (String)fWorkingValues.get(keys[index])); + for (int index = 0; index < keys.length; index++) + store.setValue(keys[index], (String) fWorkingValues + .get(keys[index])); } /* @@ -428,14 +492,18 @@ public class SpellingConfigurationBlock extends OptionsConfigurationBlock { protected void validateSettings(final String key, final String value) { if (key == null || PREF_SPELLING_PROPOSAL_THRESHOLD.equals(key)) - fThresholdStatus= validatePositiveNumber((String)fWorkingValues.get(PREF_SPELLING_PROPOSAL_THRESHOLD)); + fThresholdStatus = validatePositiveNumber((String) fWorkingValues + .get(PREF_SPELLING_PROPOSAL_THRESHOLD)); if (key == null || PREF_SPELLING_USER_DICTIONARY.equals(key)) - fFileStatus= validateAbsoluteFilePath((String)fWorkingValues.get(PREF_SPELLING_USER_DICTIONARY)); + fFileStatus = validateAbsoluteFilePath((String) fWorkingValues + .get(PREF_SPELLING_USER_DICTIONARY)); if (key == null || PREF_SPELLING_LOCALE.equals(key)) - fLocaleStatus= validateLocale((String)fWorkingValues.get(PREF_SPELLING_LOCALE)); + fLocaleStatus = validateLocale((String) fWorkingValues + .get(PREF_SPELLING_LOCALE)); - fContext.statusChanged(StatusUtil.getMostSevere(new IStatus[] { fThresholdStatus, fFileStatus, fLocaleStatus })); + fContext.statusChanged(StatusUtil.getMostSevere(new IStatus[] { + fThresholdStatus, fFileStatus, fLocaleStatus })); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/SpellingPreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/SpellingPreferencePage.java index 4a25a0d..fdb8eb8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/SpellingPreferencePage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/SpellingPreferencePage.java @@ -27,13 +27,15 @@ import org.eclipse.ui.PlatformUI; /** * Preference page for spell checking preferences. - * + * * @since 3.0 */ -public class SpellingPreferencePage extends PreferencePage implements IWorkbenchPreferencePage, IStatusChangeListener { +public class SpellingPreferencePage extends PreferencePage implements + IWorkbenchPreferencePage, IStatusChangeListener { /** The spelling configuration block */ - private final SpellingConfigurationBlock fBlock= new SpellingConfigurationBlock(this, null); + private final SpellingConfigurationBlock fBlock = new SpellingConfigurationBlock( + this, null); /** * Creates a new spelling preference page. @@ -41,7 +43,8 @@ public class SpellingPreferencePage extends PreferencePage implements IWorkbench public SpellingPreferencePage() { setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); - setDescription(PreferencesMessages.getString("SpellingPreferencePage.description")); //$NON-NLS-1$ + setDescription(PreferencesMessages + .getString("SpellingPreferencePage.description")); //$NON-NLS-1$ setTitle(PreferencesMessages.getString("SpellingPreferencePage.title")); //$NON-NLS-1$ } @@ -50,7 +53,7 @@ public class SpellingPreferencePage extends PreferencePage implements IWorkbench */ protected Control createContents(final Composite parent) { - final Control control= fBlock.createContents(parent); + final Control control = fBlock.createContents(parent); Dialog.applyDialogFont(control); return control; @@ -61,7 +64,8 @@ public class SpellingPreferencePage extends PreferencePage implements IWorkbench */ public void createControl(final Composite parent) { super.createControl(parent); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), + IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE); } /* diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TemplateEditorSourceViewerConfiguration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TemplateEditorSourceViewerConfiguration.java index 7b94aa7..f16ecab 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TemplateEditorSourceViewerConfiguration.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TemplateEditorSourceViewerConfiguration.java @@ -37,8 +37,8 @@ import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.RGB; import org.eclipse.ui.texteditor.ITextEditor; - -public class TemplateEditorSourceViewerConfiguration extends PHPSourceViewerConfiguration { +public class TemplateEditorSourceViewerConfiguration extends + PHPSourceViewerConfiguration { private static class TemplateVariableTextHover implements ITextHover { @@ -48,23 +48,28 @@ public class TemplateEditorSourceViewerConfiguration extends PHPSourceViewerConf * @param type */ public TemplateVariableTextHover(TemplateVariableProcessor processor) { - fProcessor= processor; + fProcessor = processor; } - /* (non-Javadoc) - * @see org.eclipse.jface.text.ITextHover#getHoverInfo(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion) + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.ITextHover#getHoverInfo(org.eclipse.jface.text.ITextViewer, + * org.eclipse.jface.text.IRegion) */ public String getHoverInfo(ITextViewer textViewer, IRegion subject) { try { - IDocument doc= textViewer.getDocument(); - int offset= subject.getOffset(); - if (offset >= 2 && "${".equals(doc.get(offset-2, 2))) { //$NON-NLS-1$ - String varName= doc.get(offset, subject.getLength()); - TemplateContextType contextType= fProcessor.getContextType(); + IDocument doc = textViewer.getDocument(); + int offset = subject.getOffset(); + if (offset >= 2 && "${".equals(doc.get(offset - 2, 2))) { //$NON-NLS-1$ + String varName = doc.get(offset, subject.getLength()); + TemplateContextType contextType = fProcessor + .getContextType(); if (contextType != null) { - Iterator iter= contextType.resolvers(); + Iterator iter = contextType.resolvers(); while (iter.hasNext()) { - TemplateVariableResolver var= (TemplateVariableResolver) iter.next(); + TemplateVariableResolver var = (TemplateVariableResolver) iter + .next(); if (varName.equals(var.getType())) { return var.getDescription(); } @@ -76,12 +81,16 @@ public class TemplateEditorSourceViewerConfiguration extends PHPSourceViewerConf return null; } - /* (non-Javadoc) - * @see org.eclipse.jface.text.ITextHover#getHoverRegion(org.eclipse.jface.text.ITextViewer, int) + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.ITextHover#getHoverRegion(org.eclipse.jface.text.ITextViewer, + * int) */ public IRegion getHoverRegion(ITextViewer textViewer, int offset) { if (textViewer != null) { - return JavaWordFinder.findWord(textViewer.getDocument(), offset); + return JavaWordFinder + .findWord(textViewer.getDocument(), offset); } return null; } @@ -90,9 +99,11 @@ public class TemplateEditorSourceViewerConfiguration extends PHPSourceViewerConf private final TemplateVariableProcessor fProcessor; - public TemplateEditorSourceViewerConfiguration(IColorManager colorManager, IPreferenceStore store, ITextEditor editor, TemplateVariableProcessor processor) { + public TemplateEditorSourceViewerConfiguration(IColorManager colorManager, + IPreferenceStore store, ITextEditor editor, + TemplateVariableProcessor processor) { super(colorManager, store, editor, IPHPPartitions.PHP_PARTITIONING); - fProcessor= processor; + fProcessor = processor; } /* @@ -100,34 +111,51 @@ public class TemplateEditorSourceViewerConfiguration extends PHPSourceViewerConf */ public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { - IPreferenceStore store= PHPeclipsePlugin.getDefault().getPreferenceStore(); - JavaTextTools textTools= PHPeclipsePlugin.getDefault().getJavaTextTools(); - IColorManager manager= textTools.getColorManager(); - - - ContentAssistant assistant= new ContentAssistant(); - assistant.setContentAssistProcessor(fProcessor, IDocument.DEFAULT_CONTENT_TYPE); - // Register the same processor for strings and single line comments to get code completion at the start of those partitions. - assistant.setContentAssistProcessor(fProcessor, IPHPPartitions.PHP_STRING_DQ); - assistant.setContentAssistProcessor(fProcessor, IPHPPartitions.PHP_STRING_SQ); - assistant.setContentAssistProcessor(fProcessor, IPHPPartitions.PHP_STRING_HEREDOC); - assistant.setContentAssistProcessor(fProcessor, IPHPPartitions.PHP_SINGLELINE_COMMENT); - assistant.setContentAssistProcessor(fProcessor, IPHPPartitions.PHP_MULTILINE_COMMENT); - assistant.setContentAssistProcessor(fProcessor, IPHPPartitions.PHP_PHPDOC_COMMENT); - - assistant.enableAutoInsert(store.getBoolean(PreferenceConstants.CODEASSIST_AUTOINSERT)); - assistant.enableAutoActivation(store.getBoolean(PreferenceConstants.CODEASSIST_AUTOACTIVATION)); - assistant.setAutoActivationDelay(store.getInt(PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY)); - assistant.setProposalPopupOrientation(ContentAssistant.PROPOSAL_OVERLAY); - assistant.setContextInformationPopupOrientation(ContentAssistant.CONTEXT_INFO_ABOVE); - assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer)); - - Color background= getColor(store, PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND, manager); + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + JavaTextTools textTools = PHPeclipsePlugin.getDefault() + .getJavaTextTools(); + IColorManager manager = textTools.getColorManager(); + + ContentAssistant assistant = new ContentAssistant(); + assistant.setContentAssistProcessor(fProcessor, + IDocument.DEFAULT_CONTENT_TYPE); + // Register the same processor for strings and single line comments to + // get code completion at the start of those partitions. + assistant.setContentAssistProcessor(fProcessor, + IPHPPartitions.PHP_STRING_DQ); + assistant.setContentAssistProcessor(fProcessor, + IPHPPartitions.PHP_STRING_SQ); + assistant.setContentAssistProcessor(fProcessor, + IPHPPartitions.PHP_STRING_HEREDOC); + assistant.setContentAssistProcessor(fProcessor, + IPHPPartitions.PHP_SINGLELINE_COMMENT); + assistant.setContentAssistProcessor(fProcessor, + IPHPPartitions.PHP_MULTILINE_COMMENT); + assistant.setContentAssistProcessor(fProcessor, + IPHPPartitions.PHP_PHPDOC_COMMENT); + + assistant.enableAutoInsert(store + .getBoolean(PreferenceConstants.CODEASSIST_AUTOINSERT)); + assistant.enableAutoActivation(store + .getBoolean(PreferenceConstants.CODEASSIST_AUTOACTIVATION)); + assistant.setAutoActivationDelay(store + .getInt(PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY)); + assistant + .setProposalPopupOrientation(ContentAssistant.PROPOSAL_OVERLAY); + assistant + .setContextInformationPopupOrientation(ContentAssistant.CONTEXT_INFO_ABOVE); + assistant + .setInformationControlCreator(getInformationControlCreator(sourceViewer)); + + Color background = getColor(store, + PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND, manager); assistant.setContextInformationPopupBackground(background); assistant.setContextSelectorBackground(background); assistant.setProposalSelectorBackground(background); - Color foreground= getColor(store, PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND, manager); + Color foreground = getColor(store, + PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND, manager); assistant.setContextInformationPopupForeground(foreground); assistant.setContextSelectorForeground(foreground); assistant.setProposalSelectorForeground(foreground); @@ -135,8 +163,9 @@ public class TemplateEditorSourceViewerConfiguration extends PHPSourceViewerConf return assistant; } - private Color getColor(IPreferenceStore store, String key, IColorManager manager) { - RGB rgb= PreferenceConverter.getColor(store, key); + private Color getColor(IPreferenceStore store, String key, + IColorManager manager) { + RGB rgb = PreferenceConverter.getColor(store, key); return manager.getColor(rgb); } @@ -144,7 +173,8 @@ public class TemplateEditorSourceViewerConfiguration extends PHPSourceViewerConf * @see SourceViewerConfiguration#getTextHover(ISourceViewer, String, int) * @since 2.1 */ - public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType, int stateMask) { + public ITextHover getTextHover(ISourceViewer sourceViewer, + String contentType, int stateMask) { return new TemplateVariableTextHover(fProcessor); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskConfigurationBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskConfigurationBlock.java index 8512c55..e487226 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskConfigurationBlock.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskConfigurationBlock.java @@ -35,108 +35,138 @@ import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; /** - */ + */ public class TodoTaskConfigurationBlock extends OptionsConfigurationBlock { - private static final String PREF_COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS; - private static final String PREF_COMPILER_TASK_PRIORITIES= JavaCore.COMPILER_TASK_PRIORITIES; - - private static final String PRIORITY_HIGH= JavaCore.COMPILER_TASK_PRIORITY_HIGH; - private static final String PRIORITY_NORMAL= JavaCore.COMPILER_TASK_PRIORITY_NORMAL; - private static final String PRIORITY_LOW= JavaCore.COMPILER_TASK_PRIORITY_LOW; - + private static final String PREF_COMPILER_TASK_TAGS = JavaCore.COMPILER_TASK_TAGS; + + private static final String PREF_COMPILER_TASK_PRIORITIES = JavaCore.COMPILER_TASK_PRIORITIES; + + private static final String PRIORITY_HIGH = JavaCore.COMPILER_TASK_PRIORITY_HIGH; + + private static final String PRIORITY_NORMAL = JavaCore.COMPILER_TASK_PRIORITY_NORMAL; + + private static final String PRIORITY_LOW = JavaCore.COMPILER_TASK_PRIORITY_LOW; + public static class TodoTask { public String name; + public String priority; } - - private static class TodoTaskLabelProvider extends LabelProvider implements ITableLabelProvider { - - /* (non-Javadoc) + + private static class TodoTaskLabelProvider extends LabelProvider implements + ITableLabelProvider { + + /* + * (non-Javadoc) + * * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object) */ public Image getImage(Object element) { return null; // JavaPluginImages.get(JavaPluginImages.IMG_OBJS_REFACTORING_INFO); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object) */ public String getText(Object element) { return getColumnText(element, 0); } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int) + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, + * int) */ public Image getColumnImage(Object element, int columnIndex) { return null; } - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int) + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, + * int) */ public String getColumnText(Object element, int columnIndex) { - TodoTask task= (TodoTask) element; + TodoTask task = (TodoTask) element; if (columnIndex == 0) { return task.name; } else { if (PRIORITY_HIGH.equals(task.priority)) { - return PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.high.priority"); //$NON-NLS-1$ + return PreferencesMessages + .getString("TodoTaskConfigurationBlock.markers.tasks.high.priority"); //$NON-NLS-1$ } else if (PRIORITY_NORMAL.equals(task.priority)) { - return PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.normal.priority"); //$NON-NLS-1$ + return PreferencesMessages + .getString("TodoTaskConfigurationBlock.markers.tasks.normal.priority"); //$NON-NLS-1$ } else if (PRIORITY_LOW.equals(task.priority)) { - return PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.low.priority"); //$NON-NLS-1$ + return PreferencesMessages + .getString("TodoTaskConfigurationBlock.markers.tasks.low.priority"); //$NON-NLS-1$ } return ""; //$NON-NLS-1$ - } + } } } - - private static final int IDX_ADD= 0; - private static final int IDX_EDIT= 1; - private static final int IDX_REMOVE= 2; - + + private static final int IDX_ADD = 0; + + private static final int IDX_EDIT = 1; + + private static final int IDX_REMOVE = 2; + private IStatus fTaskTagsStatus; + private ListDialogField fTodoTasksList; - public TodoTaskConfigurationBlock(IStatusChangeListener context, IJavaProject project) { + public TodoTaskConfigurationBlock(IStatusChangeListener context, + IJavaProject project) { super(context, project, getKeys()); - - TaskTagAdapter adapter= new TaskTagAdapter(); - String[] buttons= new String[] { - /* 0 */ PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.add.button"), //$NON-NLS-1$ - /* 1 */ PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.edit.button"), //$NON-NLS-1$ - /* 2 */ PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.remove.button"), //$NON-NLS-1$ - + + TaskTagAdapter adapter = new TaskTagAdapter(); + String[] buttons = new String[] { + /* 0 */PreferencesMessages + .getString("TodoTaskConfigurationBlock.markers.tasks.add.button"), //$NON-NLS-1$ + /* 1 */PreferencesMessages + .getString("TodoTaskConfigurationBlock.markers.tasks.edit.button"), //$NON-NLS-1$ + /* 2 */PreferencesMessages + .getString("TodoTaskConfigurationBlock.markers.tasks.remove.button"), //$NON-NLS-1$ + }; - fTodoTasksList= new ListDialogField(adapter, buttons, new TodoTaskLabelProvider()); + fTodoTasksList = new ListDialogField(adapter, buttons, + new TodoTaskLabelProvider()); fTodoTasksList.setDialogFieldListener(adapter); - fTodoTasksList.setLabelText(PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.label")); //$NON-NLS-1$ + fTodoTasksList.setLabelText(PreferencesMessages + .getString("TodoTaskConfigurationBlock.markers.tasks.label")); //$NON-NLS-1$ fTodoTasksList.setRemoveButtonIndex(IDX_REMOVE); - - String[] columnsHeaders= new String[] { - PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.name.column"), //$NON-NLS-1$ - PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.priority.column"), //$NON-NLS-1$ + + String[] columnsHeaders = new String[] { + PreferencesMessages + .getString("TodoTaskConfigurationBlock.markers.tasks.name.column"), //$NON-NLS-1$ + PreferencesMessages + .getString("TodoTaskConfigurationBlock.markers.tasks.priority.column"), //$NON-NLS-1$ }; - - fTodoTasksList.setTableColumns(new ListDialogField.ColumnsDescription(columnsHeaders, true)); + + fTodoTasksList.setTableColumns(new ListDialogField.ColumnsDescription( + columnsHeaders, true)); unpackTodoTasks(); if (fTodoTasksList.getSize() > 0) { fTodoTasksList.selectFirstElement(); } else { fTodoTasksList.enableButton(IDX_EDIT, false); } - - fTaskTagsStatus= new StatusInfo(); + + fTaskTagsStatus = new StatusInfo(); } - + private final static String[] getKeys() { - return new String[] { - PREF_COMPILER_TASK_TAGS, PREF_COMPILER_TASK_PRIORITIES - }; - } - + return new String[] { PREF_COMPILER_TASK_TAGS, + PREF_COMPILER_TASK_PRIORITIES }; + } + public class TaskTagAdapter implements IListAdapter, IDialogFieldListener { private boolean canEdit(ListDialogField field) { @@ -150,7 +180,7 @@ public class TodoTaskConfigurationBlock extends OptionsConfigurationBlock { public void selectionChanged(ListDialogField field) { field.enableButton(IDX_EDIT, canEdit(field)); } - + public void doubleClicked(ListDialogField field) { if (canEdit(field)) { doTodoButtonPressed(IDX_EDIT); @@ -159,38 +189,39 @@ public class TodoTaskConfigurationBlock extends OptionsConfigurationBlock { public void dialogFieldChanged(DialogField field) { validateSettings(PREF_COMPILER_TASK_TAGS, null); - } - + } + } - + protected Control createContents(Composite parent) { setShell(parent.getShell()); - - Composite markersComposite= createMarkersTabContent(parent); - + + Composite markersComposite = createMarkersTabContent(parent); + validateSettings(null, null); - + return markersComposite; } private Composite createMarkersTabContent(Composite folder) { - - GridLayout layout= new GridLayout(); - layout.marginHeight= 0; - layout.marginWidth= 0; - layout.numColumns= 2; - - Composite markersComposite= new Composite(folder, SWT.NULL); + + GridLayout layout = new GridLayout(); + layout.marginHeight = 0; + layout.marginWidth = 0; + layout.numColumns = 2; + + Composite markersComposite = new Composite(folder, SWT.NULL); markersComposite.setLayout(layout); - + fTodoTasksList.doFillIntoGrid(markersComposite, 3); LayoutUtil.setHorizontalSpan(fTodoTasksList.getLabelControl(null), 2); - - GridData data= (GridData)fTodoTasksList.getListControl(null).getLayoutData(); - data.grabExcessHorizontalSpace= true; - data.grabExcessVerticalSpace= true; - data.verticalAlignment= GridData.FILL; - //data.heightHint= SWTUtil.getTableHeightHint(table, 6); + + GridData data = (GridData) fTodoTasksList.getListControl(null) + .getLayoutData(); + data.grabExcessHorizontalSpace = true; + data.grabExcessVerticalSpace = true; + data.verticalAlignment = GridData.FILL; + // data.heightHint= SWTUtil.getTableHeightHint(table, 6); return markersComposite; } @@ -198,22 +229,25 @@ public class TodoTaskConfigurationBlock extends OptionsConfigurationBlock { protected void validateSettings(String changedKey, String newValue) { if (changedKey != null) { if (PREF_COMPILER_TASK_TAGS.equals(changedKey)) { - fTaskTagsStatus= validateTaskTags(); + fTaskTagsStatus = validateTaskTags(); } else { return; } } else { - fTaskTagsStatus= validateTaskTags(); - } - IStatus status= fTaskTagsStatus; //StatusUtil.getMostSevere(new IStatus[] { fTaskTagsStatus }); + fTaskTagsStatus = validateTaskTags(); + } + IStatus status = fTaskTagsStatus; // StatusUtil.getMostSevere(new + // IStatus[] { fTaskTagsStatus }); fContext.statusChanged(status); } - + private IStatus validateTaskTags() { return new StatusInfo(); - } + } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpdt.internal.ui.preferences.OptionsConfigurationBlock#performOk(boolean) */ public boolean performOk(boolean enabled) { @@ -221,64 +255,70 @@ public class TodoTaskConfigurationBlock extends OptionsConfigurationBlock { return super.performOk(enabled); } - protected String[] getFullBuildDialogStrings(boolean workspaceSettings) { - String title= PreferencesMessages.getString("TodoTaskConfigurationBlock.needsbuild.title"); //$NON-NLS-1$ + String title = PreferencesMessages + .getString("TodoTaskConfigurationBlock.needsbuild.title"); //$NON-NLS-1$ String message; if (fProject == null) { - message= PreferencesMessages.getString("TodoTaskConfigurationBlock.needsfullbuild.message"); //$NON-NLS-1$ + message = PreferencesMessages + .getString("TodoTaskConfigurationBlock.needsfullbuild.message"); //$NON-NLS-1$ } else { - message= PreferencesMessages.getString("TodoTaskConfigurationBlock.needsprojectbuild.message"); //$NON-NLS-1$ - } + message = PreferencesMessages + .getString("TodoTaskConfigurationBlock.needsprojectbuild.message"); //$NON-NLS-1$ + } return new String[] { title, message }; - } - - /* (non-Javadoc) + } + + /* + * (non-Javadoc) + * * @see net.sourceforge.phpdt.internal.ui.preferences.OptionsConfigurationBlock#updateControls() */ protected void updateControls() { unpackTodoTasks(); } - + private void unpackTodoTasks() { - String currTags= (String) fWorkingValues.get(PREF_COMPILER_TASK_TAGS); - String currPrios= (String) fWorkingValues.get(PREF_COMPILER_TASK_PRIORITIES); - String[] tags= getTokens(currTags, ","); //$NON-NLS-1$ - String[] prios= getTokens(currPrios, ","); //$NON-NLS-1$ - ArrayList elements= new ArrayList(tags.length); - for (int i= 0; i < tags.length; i++) { - TodoTask task= new TodoTask(); - task.name= tags[i].trim(); - task.priority= (i < prios.length) ? prios[i] : PRIORITY_NORMAL; + String currTags = (String) fWorkingValues.get(PREF_COMPILER_TASK_TAGS); + String currPrios = (String) fWorkingValues + .get(PREF_COMPILER_TASK_PRIORITIES); + String[] tags = getTokens(currTags, ","); //$NON-NLS-1$ + String[] prios = getTokens(currPrios, ","); //$NON-NLS-1$ + ArrayList elements = new ArrayList(tags.length); + for (int i = 0; i < tags.length; i++) { + TodoTask task = new TodoTask(); + task.name = tags[i].trim(); + task.priority = (i < prios.length) ? prios[i] : PRIORITY_NORMAL; elements.add(task); } fTodoTasksList.setElements(elements); } - + private void packTodoTasks() { - StringBuffer tags= new StringBuffer(); - StringBuffer prios= new StringBuffer(); - List list= fTodoTasksList.getElements(); - for (int i= 0; i < list.size(); i++) { + StringBuffer tags = new StringBuffer(); + StringBuffer prios = new StringBuffer(); + List list = fTodoTasksList.getElements(); + for (int i = 0; i < list.size(); i++) { if (i > 0) { tags.append(','); prios.append(','); } - TodoTask elem= (TodoTask) list.get(i); + TodoTask elem = (TodoTask) list.get(i); tags.append(elem.name); prios.append(elem.priority); } fWorkingValues.put(PREF_COMPILER_TASK_TAGS, tags.toString()); fWorkingValues.put(PREF_COMPILER_TASK_PRIORITIES, prios.toString()); } - + private void doTodoButtonPressed(int index) { - TodoTask edited= null; + TodoTask edited = null; if (index != IDX_ADD) { - edited= (TodoTask) fTodoTasksList.getSelectedElements().get(0); + edited = (TodoTask) fTodoTasksList.getSelectedElements().get(0); } - - TodoTaskInputDialog dialog= new TodoTaskInputDialog(getShell(), edited, fTodoTasksList.getElements()); + + TodoTaskInputDialog dialog = new TodoTaskInputDialog(getShell(), + edited, fTodoTasksList.getElements()); if (dialog.open() == Window.OK) { if (edited != null) { fTodoTasksList.replaceElement(edited, dialog.getResult()); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskInputDialog.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskInputDialog.java index b95f478..0d6effb 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskInputDialog.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskInputDialog.java @@ -43,6 +43,7 @@ public class TodoTaskInputDialog extends StatusDialog { } private StringDialogField fNameDialogField; + private ComboDialogField fPriorityDialogField; private List fExistingNames; @@ -50,41 +51,49 @@ public class TodoTaskInputDialog extends StatusDialog { public TodoTaskInputDialog(Shell parent, TodoTask task, List existingEntries) { super(parent); - fExistingNames= new ArrayList(existingEntries.size()); - for (int i= 0; i < existingEntries.size(); i++) { - TodoTask curr= (TodoTask) existingEntries.get(i); + fExistingNames = new ArrayList(existingEntries.size()); + for (int i = 0; i < existingEntries.size(); i++) { + TodoTask curr = (TodoTask) existingEntries.get(i); if (!curr.equals(task)) { fExistingNames.add(curr.name); } } if (task == null) { - setTitle(PreferencesMessages.getString("TodoTaskInputDialog.new.title")); //$NON-NLS-1$ + setTitle(PreferencesMessages + .getString("TodoTaskInputDialog.new.title")); //$NON-NLS-1$ } else { - setTitle(PreferencesMessages.getString("TodoTaskInputDialog.edit.title")); //$NON-NLS-1$ + setTitle(PreferencesMessages + .getString("TodoTaskInputDialog.edit.title")); //$NON-NLS-1$ } - CompilerTodoTaskInputAdapter adapter= new CompilerTodoTaskInputAdapter(); + CompilerTodoTaskInputAdapter adapter = new CompilerTodoTaskInputAdapter(); - fNameDialogField= new StringDialogField(); - fNameDialogField.setLabelText(PreferencesMessages.getString("TodoTaskInputDialog.name.label")); //$NON-NLS-1$ + fNameDialogField = new StringDialogField(); + fNameDialogField.setLabelText(PreferencesMessages + .getString("TodoTaskInputDialog.name.label")); //$NON-NLS-1$ fNameDialogField.setDialogFieldListener(adapter); fNameDialogField.setText((task != null) ? task.name : ""); //$NON-NLS-1$ - String[] items= new String[] { - PreferencesMessages.getString("TodoTaskInputDialog.priority.high"), //$NON-NLS-1$ - PreferencesMessages.getString("TodoTaskInputDialog.priority.normal"), //$NON-NLS-1$ - PreferencesMessages.getString("TodoTaskInputDialog.priority.low") //$NON-NLS-1$ + String[] items = new String[] { + PreferencesMessages + .getString("TodoTaskInputDialog.priority.high"), //$NON-NLS-1$ + PreferencesMessages + .getString("TodoTaskInputDialog.priority.normal"), //$NON-NLS-1$ + PreferencesMessages + .getString("TodoTaskInputDialog.priority.low") //$NON-NLS-1$ }; - fPriorityDialogField= new ComboDialogField(SWT.READ_ONLY); - fPriorityDialogField.setLabelText(PreferencesMessages.getString("TodoTaskInputDialog.priority.label")); //$NON-NLS-1$ + fPriorityDialogField = new ComboDialogField(SWT.READ_ONLY); + fPriorityDialogField.setLabelText(PreferencesMessages + .getString("TodoTaskInputDialog.priority.label")); //$NON-NLS-1$ fPriorityDialogField.setItems(items); if (task != null) { if (JavaCore.COMPILER_TASK_PRIORITY_HIGH.equals(task.priority)) { fPriorityDialogField.selectItem(0); - } else if (JavaCore.COMPILER_TASK_PRIORITY_NORMAL.equals(task.priority)) { + } else if (JavaCore.COMPILER_TASK_PRIORITY_NORMAL + .equals(task.priority)) { fPriorityDialogField.selectItem(1); } else { fPriorityDialogField.selectItem(2); @@ -95,37 +104,38 @@ public class TodoTaskInputDialog extends StatusDialog { } public TodoTask getResult() { - TodoTask task= new TodoTask(); - task.name= fNameDialogField.getText().trim(); + TodoTask task = new TodoTask(); + task.name = fNameDialogField.getText().trim(); switch (fPriorityDialogField.getSelectionIndex()) { - case 0 : - task.priority= JavaCore.COMPILER_TASK_PRIORITY_HIGH; - break; - case 1 : - task.priority= JavaCore.COMPILER_TASK_PRIORITY_NORMAL; - break; - default : - task.priority= JavaCore.COMPILER_TASK_PRIORITY_LOW; - break; + case 0: + task.priority = JavaCore.COMPILER_TASK_PRIORITY_HIGH; + break; + case 1: + task.priority = JavaCore.COMPILER_TASK_PRIORITY_NORMAL; + break; + default: + task.priority = JavaCore.COMPILER_TASK_PRIORITY_LOW; + break; } return task; } protected Control createDialogArea(Composite parent) { - Composite composite= (Composite) super.createDialogArea(parent); + Composite composite = (Composite) super.createDialogArea(parent); - Composite inner= new Composite(composite, SWT.NONE); - GridLayout layout= new GridLayout(); - layout.marginHeight= 0; - layout.marginWidth= 0; - layout.numColumns= 2; + Composite inner = new Composite(composite, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginHeight = 0; + layout.marginWidth = 0; + layout.numColumns = 2; inner.setLayout(layout); fNameDialogField.doFillIntoGrid(inner, 2); fPriorityDialogField.doFillIntoGrid(inner, 2); LayoutUtil.setHorizontalGrabbing(fNameDialogField.getTextControl(null)); - LayoutUtil.setWidthHint(fNameDialogField.getTextControl(null), convertWidthInCharsToPixels(45)); + LayoutUtil.setWidthHint(fNameDialogField.getTextControl(null), + convertWidthInCharsToPixels(45)); fNameDialogField.postSetFocusOnDialogField(parent.getDisplay()); @@ -134,17 +144,23 @@ public class TodoTaskInputDialog extends StatusDialog { } private void doValidation() { - StatusInfo status= new StatusInfo(); - String newText= fNameDialogField.getText(); + StatusInfo status = new StatusInfo(); + String newText = fNameDialogField.getText(); if (newText.length() == 0) { - status.setError(PreferencesMessages.getString("TodoTaskInputDialog.error.enterName")); //$NON-NLS-1$ + status.setError(PreferencesMessages + .getString("TodoTaskInputDialog.error.enterName")); //$NON-NLS-1$ } else { if (newText.indexOf(',') != -1) { - status.setError(PreferencesMessages.getString("TodoTaskInputDialog.error.comma")); //$NON-NLS-1$ + status.setError(PreferencesMessages + .getString("TodoTaskInputDialog.error.comma")); //$NON-NLS-1$ } else if (fExistingNames.contains(newText)) { - status.setError(PreferencesMessages.getString("TodoTaskInputDialog.error.entryExists")); //$NON-NLS-1$ - } else if (Character.isWhitespace(newText.charAt(0)) || Character.isWhitespace(newText.charAt(newText.length() - 1))) { - status.setError(PreferencesMessages.getString("TodoTaskInputDialog.error.noSpace")); //$NON-NLS-1$ + status.setError(PreferencesMessages + .getString("TodoTaskInputDialog.error.entryExists")); //$NON-NLS-1$ + } else if (Character.isWhitespace(newText.charAt(0)) + || Character.isWhitespace(newText + .charAt(newText.length() - 1))) { + status.setError(PreferencesMessages + .getString("TodoTaskInputDialog.error.noSpace")); //$NON-NLS-1$ } } updateStatus(status); @@ -155,6 +171,7 @@ public class TodoTaskInputDialog extends StatusDialog { */ protected void configureShell(Shell newShell) { super.configureShell(newShell); - PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IJavaHelpContextIds.TODO_TASK_INPUT_DIALOG); + PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, + IJavaHelpContextIds.TODO_TASK_INPUT_DIALOG); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskPreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskPreferencePage.java index e8f0fe9..69613cf 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskPreferencePage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskPreferencePage.java @@ -27,20 +27,22 @@ import org.eclipse.ui.PlatformUI; /* * The page to configure the compiler options. */ -public class TodoTaskPreferencePage extends PreferencePage implements IWorkbenchPreferencePage, IStatusChangeListener { +public class TodoTaskPreferencePage extends PreferencePage implements + IWorkbenchPreferencePage, IStatusChangeListener { - public static final String ID= "net.sourceforge.phpdt.ui.preferences.TodoTaskPreferencePage"; //$NON-NLS-1$ + public static final String ID = "net.sourceforge.phpdt.ui.preferences.TodoTaskPreferencePage"; //$NON-NLS-1$ private TodoTaskConfigurationBlock fConfigurationBlock; public TodoTaskPreferencePage() { setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); - //setDescription(PreferencesMessages.getString("TodoTaskPreferencePage.description")); //$NON-NLS-1$ + // setDescription(PreferencesMessages.getString("TodoTaskPreferencePage.description")); + // //$NON-NLS-1$ // only used when page is shown programatically setTitle(PreferencesMessages.getString("TodoTaskPreferencePage.title")); //$NON-NLS-1$ - fConfigurationBlock= new TodoTaskConfigurationBlock(this, null); + fConfigurationBlock = new TodoTaskConfigurationBlock(this, null); } /* @@ -53,16 +55,18 @@ public class TodoTaskPreferencePage extends PreferencePage implements IWorkbench * @see PreferencePage#createControl(Composite) */ public void createControl(Composite parent) { - // added for 1GEUGE6: ITPJUI:WIN2000 - Help is the same on all preference pages + // added for 1GEUGE6: ITPJUI:WIN2000 - Help is the same on all + // preference pages super.createControl(parent); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.TODOTASK_PREFERENCE_PAGE); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), + IJavaHelpContextIds.TODOTASK_PREFERENCE_PAGE); } /* * @see PreferencePage#createContents(Composite) */ protected Control createContents(Composite parent) { - Control result= fConfigurationBlock.createContents(parent); + Control result = fConfigurationBlock.createContents(parent); Dialog.applyDialogFont(result); return result; } @@ -85,7 +89,9 @@ public class TodoTaskPreferencePage extends PreferencePage implements IWorkbench super.performDefaults(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener#statusChanged(org.eclipse.core.runtime.IStatus) */ public void statusChanged(IStatus status) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskPropertyPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskPropertyPage.java index aab8245..b9395f4 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskPropertyPage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskPropertyPage.java @@ -45,37 +45,45 @@ import org.eclipse.ui.dialogs.PropertyPage; public class TodoTaskPropertyPage extends PropertyPage { private TodoTaskConfigurationBlock fConfigurationBlock; + private Control fConfigurationBlockControl; + private ControlEnableState fBlockEnableState; + private SelectionButtonDialogField fUseWorkspaceSettings; + private SelectionButtonDialogField fChangeWorkspaceSettings; + private SelectionButtonDialogField fUseProjectSettings; - private IStatus fBlockStatus; + private IStatus fBlockStatus; public TodoTaskPropertyPage() { - fBlockStatus= new StatusInfo(); - fBlockEnableState= null; + fBlockStatus = new StatusInfo(); + fBlockEnableState = null; - IDialogFieldListener listener= new IDialogFieldListener() { + IDialogFieldListener listener = new IDialogFieldListener() { public void dialogFieldChanged(DialogField field) { doDialogFieldChanged(field); } }; - fUseWorkspaceSettings= new SelectionButtonDialogField(SWT.RADIO); + fUseWorkspaceSettings = new SelectionButtonDialogField(SWT.RADIO); fUseWorkspaceSettings.setDialogFieldListener(listener); - fUseWorkspaceSettings.setLabelText(PreferencesMessages.getString("TodoTaskPropertyPage.useworkspacesettings.label")); //$NON-NLS-1$ + fUseWorkspaceSettings.setLabelText(PreferencesMessages + .getString("TodoTaskPropertyPage.useworkspacesettings.label")); //$NON-NLS-1$ - fChangeWorkspaceSettings= new SelectionButtonDialogField(SWT.PUSH); - fChangeWorkspaceSettings.setLabelText(PreferencesMessages.getString("TodoTaskPropertyPage.useworkspacesettings.change")); //$NON-NLS-1$ + fChangeWorkspaceSettings = new SelectionButtonDialogField(SWT.PUSH); + fChangeWorkspaceSettings.setLabelText(PreferencesMessages + .getString("TodoTaskPropertyPage.useworkspacesettings.change")); //$NON-NLS-1$ fChangeWorkspaceSettings.setDialogFieldListener(listener); fUseWorkspaceSettings.attachDialogField(fChangeWorkspaceSettings); - fUseProjectSettings= new SelectionButtonDialogField(SWT.RADIO); + fUseProjectSettings = new SelectionButtonDialogField(SWT.RADIO); fUseProjectSettings.setDialogFieldListener(listener); - fUseProjectSettings.setLabelText(PreferencesMessages.getString("TodoTaskPropertyPage.useprojectsettings.label")); //$NON-NLS-1$ + fUseProjectSettings.setLabelText(PreferencesMessages + .getString("TodoTaskPropertyPage.useprojectsettings.label")); //$NON-NLS-1$ } /* @@ -83,46 +91,53 @@ public class TodoTaskPropertyPage extends PropertyPage { */ public void createControl(Composite parent) { super.createControl(parent); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.TODOTASK_PROPERTY_PAGE); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), + IJavaHelpContextIds.TODOTASK_PROPERTY_PAGE); } /* * @see org.eclipse.jface.preference.IPreferencePage#createContents(Composite) */ protected Control createContents(Composite parent) { - IStatusChangeListener listener= new IStatusChangeListener() { + IStatusChangeListener listener = new IStatusChangeListener() { public void statusChanged(IStatus status) { - fBlockStatus= status; + fBlockStatus = status; doStatusChanged(); } }; - fConfigurationBlock= new TodoTaskConfigurationBlock(listener, getProject()); - - Composite composite= new Composite(parent, SWT.NONE); - GridLayout layout= new GridLayout(); - layout.marginHeight= 0; - layout.marginWidth= 0; - layout.numColumns= 1; + fConfigurationBlock = new TodoTaskConfigurationBlock(listener, + getProject()); + + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginHeight = 0; + layout.marginWidth = 0; + layout.numColumns = 1; composite.setLayout(layout); fUseWorkspaceSettings.doFillIntoGrid(composite, 1); - LayoutUtil.setHorizontalGrabbing(fUseWorkspaceSettings.getSelectionButton(null)); + LayoutUtil.setHorizontalGrabbing(fUseWorkspaceSettings + .getSelectionButton(null)); fChangeWorkspaceSettings.doFillIntoGrid(composite, 1); - GridData data= (GridData) fChangeWorkspaceSettings.getSelectionButton(null).getLayoutData(); - data.horizontalIndent= convertWidthInCharsToPixels(3); - data.horizontalAlignment= GridData.BEGINNING; + GridData data = (GridData) fChangeWorkspaceSettings.getSelectionButton( + null).getLayoutData(); + data.horizontalIndent = convertWidthInCharsToPixels(3); + data.horizontalAlignment = GridData.BEGINNING; fUseProjectSettings.doFillIntoGrid(composite, 1); - data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL ); - data.horizontalSpan= 1; - data.horizontalIndent= convertWidthInCharsToPixels(2); + data = new GridData(GridData.HORIZONTAL_ALIGN_FILL + | GridData.VERTICAL_ALIGN_FILL); + data.horizontalSpan = 1; + data.horizontalIndent = convertWidthInCharsToPixels(2); - fConfigurationBlockControl= fConfigurationBlock.createContents(composite); + fConfigurationBlockControl = fConfigurationBlock + .createContents(composite); fConfigurationBlockControl.setLayoutData(data); - boolean useProjectSettings= fConfigurationBlock.hasProjectSpecificOptions(); + boolean useProjectSettings = fConfigurationBlock + .hasProjectSpecificOptions(); fUseProjectSettings.setSelection(useProjectSettings); fUseWorkspaceSettings.setSelection(!useProjectSettings); @@ -138,13 +153,14 @@ public class TodoTaskPropertyPage extends PropertyPage { private void doDialogFieldChanged(DialogField field) { if (field == fChangeWorkspaceSettings) { - TodoTaskPreferencePage page= new TodoTaskPreferencePage(); + TodoTaskPreferencePage page = new TodoTaskPreferencePage(); showPreferencePage(TodoTaskPreferencePage.ID, page); } else { updateEnableState(); doStatusChanged(); } } + /** * Method statusChanged. */ @@ -163,11 +179,12 @@ public class TodoTaskPropertyPage extends PropertyPage { if (useProjectSettings()) { if (fBlockEnableState != null) { fBlockEnableState.restore(); - fBlockEnableState= null; + fBlockEnableState = null; } } else { if (fBlockEnableState == null) { - fBlockEnableState= ControlEnableState.disable(fConfigurationBlockControl); + fBlockEnableState = ControlEnableState + .disable(fConfigurationBlockControl); } } } @@ -201,13 +218,14 @@ public class TodoTaskPropertyPage extends PropertyPage { PreferenceManager manager = new PreferenceManager(); manager.addToRoot(targetNode); - final PreferenceDialog dialog = new PreferenceDialog(getShell(), manager); - final boolean [] result = new boolean[] { false }; + final PreferenceDialog dialog = new PreferenceDialog(getShell(), + manager); + final boolean[] result = new boolean[] { false }; BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() { public void run() { dialog.create(); dialog.setMessage(targetNode.getLabelText()); - result[0]= (dialog.open() == Window.OK); + result[0] = (dialog.open() == Window.OK); } }); return result[0]; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/AbstractJavaScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/AbstractJavaScanner.java index 8d65144..0aa214b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/AbstractJavaScanner.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/AbstractJavaScanner.java @@ -23,156 +23,161 @@ import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.RGB; - /** * Initialized with a color manager and a preference store, its subclasses are - * only responsible for providing a list of preference keys based on which tokens - * are generated and to use this tokens to define the rules controlling this scanner. + * only responsible for providing a list of preference keys based on which + * tokens are generated and to use this tokens to define the rules controlling + * this scanner. */ public abstract class AbstractJavaScanner extends BufferedRuleBasedScanner { - - + private IColorManager fColorManager; + private IPreferenceStore fPreferenceStore; - - private Map fTokenMap= new HashMap(); + + private Map fTokenMap = new HashMap(); + private String[] fPropertyNamesColor; + private String[] fPropertyNamesStyle; - - - /** - * Returns the list of preference keys which define the tokens - * used in the rules of this scanner. + + /** + * Returns the list of preference keys which define the tokens used in the + * rules of this scanner. */ 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; + fColorManager = manager; + fPreferenceStore = store; } - + /** * Must be called after the constructor has been called. */ public final void initialize() { - - fPropertyNamesColor= getTokenProperties(); - int length= fPropertyNamesColor.length; - fPropertyNamesStyle= new String[length]; - for (int i= 0; i < length; i++) { - fPropertyNamesStyle[i]= fPropertyNamesColor[i] + "_bold"; //$NON-NLS-1$ + + fPropertyNamesColor = getTokenProperties(); + int length = fPropertyNamesColor.length; + fPropertyNamesStyle = new String[length]; + for (int i = 0; i < length; i++) { + fPropertyNamesStyle[i] = fPropertyNamesColor[i] + "_bold"; //$NON-NLS-1$ addToken(fPropertyNamesColor[i], fPropertyNamesStyle[i]); } - + initializeRules(); } - + private void addToken(String colorKey, String styleKey) { - RGB rgb= PreferenceConverter.getColor(fPreferenceStore, colorKey); + RGB rgb = PreferenceConverter.getColor(fPreferenceStore, colorKey); if (fColorManager instanceof IColorManagerExtension) { - IColorManagerExtension ext= (IColorManagerExtension) fColorManager; + IColorManagerExtension ext = (IColorManagerExtension) fColorManager; ext.unbindColor(colorKey); ext.bindColor(colorKey, rgb); } - - boolean bold= fPreferenceStore.getBoolean(styleKey); - fTokenMap.put(colorKey, new Token(new TextAttribute(fColorManager.getColor(colorKey), null, bold ? SWT.BOLD : SWT.NORMAL))); + + boolean bold = fPreferenceStore.getBoolean(styleKey); + fTokenMap.put(colorKey, new Token(new TextAttribute(fColorManager + .getColor(colorKey), null, bold ? SWT.BOLD : SWT.NORMAL))); } - + protected Token getToken(String key) { return (Token) fTokenMap.get(key); } - + private void initializeRules() { - List rules= createRules(); + List rules = createRules(); if (rules != null) { - IRule[] result= new IRule[rules.size()]; + 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(fPropertyNamesStyle[i])) + int length = fPropertyNamesColor.length; + for (int i = 0; i < length; i++) { + if (property.equals(fPropertyNamesColor[i]) + || property.equals(fPropertyNamesStyle[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]); + String p = event.getProperty(); + int index = indexOf(p); + Token token = getToken(fPropertyNamesColor[index]); if (fPropertyNamesColor[index].equals(p)) adaptToColorChange(token, event); else adaptToStyleChange(token, event); } - + private void adaptToColorChange(Token token, PropertyChangeEvent event) { - RGB rgb= null; - - Object value= event.getNewValue(); + RGB rgb = null; + + Object value = event.getNewValue(); if (value instanceof RGB) - rgb= (RGB) value; + rgb = (RGB) value; else if (value instanceof String) - rgb= StringConverter.asRGB((String) value); - + rgb = StringConverter.asRGB((String) value); + if (rgb != null) { - - String property= event.getProperty(); - + + String property = event.getProperty(); + if (fColorManager instanceof IColorManagerExtension) { - IColorManagerExtension ext= (IColorManagerExtension) fColorManager; + IColorManagerExtension ext = (IColorManagerExtension) fColorManager; ext.unbindColor(property); ext.bindColor(property, rgb); } - - Object data= token.getData(); + + Object data = token.getData(); if (data instanceof TextAttribute) { - TextAttribute oldAttr= (TextAttribute) data; - token.setData(new TextAttribute(fColorManager.getColor(property), oldAttr.getBackground(), oldAttr.getStyle())); + TextAttribute oldAttr = (TextAttribute) data; + token.setData(new TextAttribute(fColorManager + .getColor(property), oldAttr.getBackground(), oldAttr + .getStyle())); } } } - + private void adaptToStyleChange(Token token, PropertyChangeEvent event) { - boolean bold= false; - Object value= event.getNewValue(); + boolean bold = false; + Object value = event.getNewValue(); if (value instanceof Boolean) - bold= ((Boolean) value).booleanValue(); + bold = ((Boolean) value).booleanValue(); else if (value instanceof String) { - String s= (String) value; + String s = (String) value; if (IPreferenceStore.TRUE.equals(s)) - bold= true; + bold = true; else if (IPreferenceStore.FALSE.equals(s)) - bold= false; + bold = false; } - - Object data= token.getData(); + + Object data = token.getData(); if (data instanceof TextAttribute) { - TextAttribute oldAttr= (TextAttribute) data; - boolean isBold= (oldAttr.getStyle() == SWT.BOLD); - if (isBold != bold) - token.setData(new TextAttribute(oldAttr.getForeground(), oldAttr.getBackground(), bold ? SWT.BOLD : SWT.NORMAL)); + TextAttribute oldAttr = (TextAttribute) data; + boolean isBold = (oldAttr.getStyle() == SWT.BOLD); + if (isBold != bold) + token.setData(new TextAttribute(oldAttr.getForeground(), + oldAttr.getBackground(), bold ? SWT.BOLD : SWT.NORMAL)); } } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/BufferedDocumentScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/BufferedDocumentScanner.java index b4fe57d..cd6833f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/BufferedDocumentScanner.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/BufferedDocumentScanner.java @@ -10,94 +10,103 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.ui.text; - import org.eclipse.jface.text.Assert; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.rules.ICharacterScanner; - - /** - * A buffered document scanner. The buffer always contains a section - * of a fixed size of the document to be scanned. + * 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 + * 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]; + fBuffer = new char[size]; } /** - * Fills the buffer with the contens of the document starting at the given offset. - * - * @param offset the document offset at which the buffer starts + * Fills the buffer with the contens 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; + fBufferOffset = offset; if (fBufferOffset + fBuffer.length > fRangeOffset + fRangeLength) - fBufferLength= fRangeLength - (fBufferOffset - fRangeOffset); + fBufferLength = fRangeLength - (fBufferOffset - fRangeOffset); else - fBufferLength= fBuffer.length; + fBufferLength = fBuffer.length; try { - final String content= fDocument.get(fBufferOffset, fBufferLength); - if (content!=null) { - content.getChars(0, fBufferLength, fBuffer, 0); + final String content = fDocument.get(fBufferOffset, fBufferLength); + if (content != null) { + 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 + * 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; + 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(); + 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; + fOffset = 0; } /* @@ -110,16 +119,16 @@ public final class BufferedDocumentScanner implements ICharacterScanner { return EOF; else { updateBuffer(fBufferOffset + fBufferLength); - fOffset= 0; + fOffset = 0; } } - try { - return fBuffer[fOffset++]; - } catch (ArrayIndexOutOfBoundsException e) { - System.out.println("Offset:"+fOffset); - System.out.println("Buffer:"+fBuffer.toString()); - throw e; - } + try { + return fBuffer[fOffset++]; + } catch (ArrayIndexOutOfBoundsException e) { + System.out.println("Offset:" + fOffset); + System.out.println("Buffer:" + fBuffer.toString()); + throw e; + } } /* @@ -132,7 +141,7 @@ public final class BufferedDocumentScanner implements ICharacterScanner { // error: BOF } else { updateBuffer(fBufferOffset - fBuffer.length); - fOffset= fBuffer.length - 1; + fOffset = fBuffer.length - 1; } } else { --fOffset; @@ -145,9 +154,9 @@ public final class BufferedDocumentScanner implements ICharacterScanner { public final int getColumn() { try { - final int offset= fBufferOffset + fOffset; - final int line= fDocument.getLineOfOffset(offset); - final int start= fDocument.getLineOffset(line); + final int offset = fBufferOffset + fOffset; + final int line = fDocument.getLineOfOffset(offset); + final int start = fDocument.getLineOffset(line); return offset - start; } catch (BadLocationException e) { } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/CombinedWordRule.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/CombinedWordRule.java index f6f5b6f..dedad70 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/CombinedWordRule.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/CombinedWordRule.java @@ -10,7 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.ui.text; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -23,60 +22,67 @@ import org.eclipse.jface.text.rules.IToken; import org.eclipse.jface.text.rules.IWordDetector; import org.eclipse.jface.text.rules.Token; - /** * An implementation of IRule capable of detecting words. *

                                                      - * 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.

                                                      + * 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. + *

                                                      *

                                                      - * 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. + * 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. *

                                                      * * @see IWordDetector * @since 3.0 */ 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(); + 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 null - * @param token the token to be returned if the word has been found, may not be null + * + * @param word + * the word this rule will search for, may not be + * null + * @param token + * the token to be returned if the word has been found, may + * not be null */ public void addWord(String word, IToken token) { Assert.isNotNull(word); - Assert.isNotNull(token); - + 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 null if none is associated by this matcher + * @param scanner + * the scanner + * @param word + * the word + * @return the token or null if none is associated by + * this matcher */ public IToken evaluate(ICharacterScanner scanner, CharacterBuffer word) { - IToken token= (IToken) fWords.get(word); + IToken token = (IToken) fWords.get(word); if (token != null) return token; return Token.UNDEFINED; } - + /** * Removes all words. */ @@ -84,64 +90,70 @@ public class CombinedWordRule implements IRule { fWords.clear(); } } - + /** - * Character buffer, mutable or suitable for use as key in hash maps. + * Character buffer, mutable or suitable for use as key in hash + * maps. */ public static class CharacterBuffer { - + /** Buffer content */ private char[] fContent; + /** Buffer content size */ - private int fLength= 0; - + private int fLength = 0; + /** Is hash code cached? */ - private boolean fIsHashCached= false; + private boolean fIsHashCached = false; + /** The hash code */ private int fHashCode; - + /** * Initialize with the given capacity. - * - * @param capacity the initial capacity + * + * @param capacity + * the initial capacity */ public CharacterBuffer(int capacity) { - fContent= new char[capacity]; + fContent = new char[capacity]; } - + /** * Initialize with the given content. - * - * @param string the initial content + * + * @param string + * the initial content */ public CharacterBuffer(String content) { - fContent= content.toCharArray(); - fLength= content.length(); + fContent = content.toCharArray(); + fLength = content.length(); } - + /** * Empties this buffer. */ public void clear() { - fIsHashCached= false; - fLength= 0; + fIsHashCached = false; + fLength = 0; } - + /** * Appends the given character to the buffer. * - * @param c the character + * @param c + * the character */ public void append(char c) { - fIsHashCached= false; + fIsHashCached = false; if (fLength == fContent.length) { - char[] old= fContent; - fContent= new char[old.length << 1]; + char[] old = fContent; + fContent = new char[old.length << 1]; System.arraycopy(old, 0, fContent, 0, old.length); } - fContent[fLength++]= c; + fContent[fLength++] = c; } - + /** * Returns the length of the content. * @@ -150,7 +162,7 @@ public class CombinedWordRule implements IRule { public int length() { return fLength; } - + /** * Returns the content as string. * @@ -159,33 +171,33 @@ public class CombinedWordRule implements IRule { public String toString() { return new String(fContent, 0, fLength); } - + /** * Returns the character at the given position. * - * @param i the position + * @param i + * the position * @return the character at position i */ 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; + + 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) */ @@ -194,27 +206,29 @@ public class CombinedWordRule implements IRule { return true; if (!(obj instanceof CharacterBuffer)) return false; - CharacterBuffer buffer= (CharacterBuffer) obj; - int length= buffer.length(); + CharacterBuffer buffer = (CharacterBuffer) obj; + int length = buffer.length(); if (length != fLength) return false; - for (int i= 0; i < length; i++) + 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 true iff the content is the same character sequence as in the string + * @param string + * the string + * @return true iff the content is the same character + * sequence as in the string */ public boolean equals(String string) { - int length= string.length(); + int length = string.length(); if (length != fLength) return false; - for (int i= 0; i < length; i++) + for (int i = 0; i < length; i++) if (string.charAt(i) != fContent[i]) return false; return true; @@ -222,28 +236,36 @@ public class CombinedWordRule implements IRule { } /** Internal setting for the uninitialized column constraint */ - private static final int UNDEFINED= -1; - + 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. */ + + /** + * 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; + private int fColumn = UNDEFINED; + /** Buffer used for pattern detection */ - private CharacterBuffer fBuffer= new CharacterBuffer(16); - + private CharacterBuffer fBuffer = new CharacterBuffer(16); + /** List of word matchers */ - private List fMatchers= new ArrayList(); + 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 null - * + * 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 + * null + * * @see #addWord(String, IToken) */ public CombinedWordRule(IWordDetector detector) { @@ -251,14 +273,17 @@ public class CombinedWordRule implements IRule { } /** - * 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 null - * @param defaultToken the default token to be returned on success - * if nothing else is specified, may not be null - * + * 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 + * null + * @param defaultToken + * the default token to be returned on success if nothing else is + * specified, may not be null + * * @see #addWord(String, IToken) */ public CombinedWordRule(IWordDetector detector, IToken defaultToken) { @@ -266,14 +291,17 @@ public class CombinedWordRule implements IRule { } /** - * 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 null - * @param matcher the initial word matcher - * + * 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 + * null + * @param matcher + * the initial word matcher + * * @see #addWord(String, IToken) */ public CombinedWordRule(IWordDetector detector, WordMatcher matcher) { @@ -281,91 +309,100 @@ public class CombinedWordRule implements IRule { } /** - * 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 null - * @param matcher the initial word matcher - * @param defaultToken the default token to be returned on success - * if nothing else is specified, may not be null - * + * 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 + * null + * @param matcher + * the initial word matcher + * @param defaultToken + * the default token to be returned on success if nothing else is + * specified, may not be null + * * @see #addWord(String, IToken) */ - public CombinedWordRule(IWordDetector detector, WordMatcher matcher, IToken defaultToken) { - + public CombinedWordRule(IWordDetector detector, WordMatcher matcher, + IToken defaultToken) { + Assert.isNotNull(detector); Assert.isNotNull(defaultToken); - - fDetector= detector; - fDefaultToken= defaultToken; + + fDetector = detector; + fDefaultToken = defaultToken; if (matcher != null) addWordMatcher(matcher); } - /** * Adds the given matcher. * - * @param matcher the 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 + * 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; + column = UNDEFINED; + fColumn = column; } - + /* * @see IRule#evaluate(ICharacterScanner) */ public IToken evaluate(ICharacterScanner scanner) { - int c= scanner.read(); + 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)); + 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); + + 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 + * + * @param scanner + * the scanner to be used */ private void unreadBuffer(ICharacterScanner scanner) { - for (int i= fBuffer.length() - 1; i >= 0; i--) + for (int i = fBuffer.length() - 1; i >= 0; i--) scanner.unread(); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/CompositeReconcilingStrategy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/CompositeReconcilingStrategy.java index 855290c..5733b4f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/CompositeReconcilingStrategy.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/CompositeReconcilingStrategy.java @@ -18,31 +18,34 @@ 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. + * A reconciling strategy consisting of a sequence of internal reconciling + * strategies. By default, all requests are passed on to the contained + * strategies. * * @since 3.0 */ -public class CompositeReconcilingStrategy implements IReconcilingStrategy, IReconcilingStrategyExtension { - +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 null + * @param strategies + * the strategies to be set or null */ public void setReconcilingStrategies(IReconcilingStrategy[] strategies) { - fStrategies= strategies; + fStrategies = strategies; } - + /** * Returns the previously set stratgies or null. * @@ -58,19 +61,20 @@ public class CompositeReconcilingStrategy implements IReconcilingStrategy, IRec public void setDocument(IDocument document) { if (fStrategies == null) return; - - for (int i= 0; i < fStrategies.length; i++) + + 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) + * @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++) + + for (int i = 0; i < fStrategies.length; i++) fStrategies[i].reconcile(dirtyRegion, subRegion); } @@ -80,8 +84,8 @@ public class CompositeReconcilingStrategy implements IReconcilingStrategy, IRec public void reconcile(IRegion partition) { if (fStrategies == null) return; - - for (int i= 0; i < fStrategies.length; i++) + + for (int i = 0; i < fStrategies.length; i++) fStrategies[i].reconcile(partition); } @@ -91,10 +95,10 @@ public class CompositeReconcilingStrategy implements IReconcilingStrategy, IRec public void setProgressMonitor(IProgressMonitor monitor) { if (fStrategies == null) return; - - for (int i=0; i < fStrategies.length; i++) { + + for (int i = 0; i < fStrategies.length; i++) { if (fStrategies[i] instanceof IReconcilingStrategyExtension) { - IReconcilingStrategyExtension extension= (IReconcilingStrategyExtension) fStrategies[i]; + IReconcilingStrategyExtension extension = (IReconcilingStrategyExtension) fStrategies[i]; extension.setProgressMonitor(monitor); } } @@ -106,10 +110,10 @@ public class CompositeReconcilingStrategy implements IReconcilingStrategy, IRec public void initialReconcile() { if (fStrategies == null) return; - - for (int i=0; i < fStrategies.length; i++) { + + for (int i = 0; i < fStrategies.length; i++) { if (fStrategies[i] instanceof IReconcilingStrategyExtension) { - IReconcilingStrategyExtension extension= (IReconcilingStrategyExtension) fStrategies[i]; + IReconcilingStrategyExtension extension = (IReconcilingStrategyExtension) fStrategies[i]; extension.initialReconcile(); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/ContentAssistPreference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/ContentAssistPreference.java index 68e60ec..af56b46 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/ContentAssistPreference.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/ContentAssistPreference.java @@ -22,267 +22,308 @@ import org.eclipse.swt.graphics.RGB; 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 completion replacement color */ - private final static String COMPLETION_REPLACEMENT_FOREGROUND = PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND; - /** Preference key for content assist completion replacement color */ - private final static String COMPLETION_REPLACEMENT_BACKGROUND = PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND; - /** Preference key for content assist auto insert */ - private final static String AUTOINSERT = PreferenceConstants.CODEASSIST_AUTOINSERT; - - /** Preference key for php content assist auto activation triggers */ - private final static String AUTOACTIVATION_TRIGGERS_JAVA = PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA; - /** Preference key for phpdoc content assist auto activation triggers */ - private final static String AUTOACTIVATION_TRIGGERS_JAVADOC = PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC; - /** Preference key for html content assist auto activation triggers */ - private final static String AUTOACTIVATION_TRIGGERS_HTML = PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_HTML; - - /** Preference key for visibility of proposals */ - private final static String SHOW_VISIBLE_PROPOSALS = PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS; - /** Preference key for alphabetic ordering of proposals */ - private final static String ORDER_PROPOSALS = PreferenceConstants.CODEASSIST_ORDER_PROPOSALS; - /** Preference key for case sensitivity of propsals */ - private final static String CASE_SENSITIVITY = PreferenceConstants.CODEASSIST_CASE_SENSITIVITY; - /** Preference key for adding imports on code assist */ - private final static String ADD_IMPORT = PreferenceConstants.CODEASSIST_ADDIMPORT; - /** Preference key for inserting content assist */ - private static final String INSERT_COMPLETION = PreferenceConstants.CODEASSIST_INSERT_COMPLETION; - /** Preference key for filling argument names on method completion */ - private static final String FILL_METHOD_ARGUMENTS = PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES; - /** Preference key for guessing argument names on method completion */ - private static final String GUESS_METHOD_ARGUMENTS = PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS; - - 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) { - JavaTextTools textTools = PHPeclipsePlugin.getDefault().getJavaTextTools(); - return getColor(store, key, textTools.getColorManager()); - } - - private static PHPCompletionProcessor getJavaProcessor(ContentAssistant assistant) { - IContentAssistProcessor p = assistant.getContentAssistProcessor(IPHPPartitions.PHP_PARTITIONING); - if (p instanceof PHPCompletionProcessor) - return (PHPCompletionProcessor) p; - return null; - } - - private static PHPDocCompletionProcessor getJavaDocProcessor(ContentAssistant assistant) { - IContentAssistProcessor p = assistant.getContentAssistProcessor(IPHPPartitions.PHP_PHPDOC_COMMENT); - if (p instanceof PHPDocCompletionProcessor) - return (PHPDocCompletionProcessor) p; - return null; - } - - private static HTMLCompletionProcessor getHTMLProcessor(ContentAssistant assistant) { - IContentAssistProcessor p = assistant.getContentAssistProcessor(IPHPPartitions.HTML); - if (p instanceof HTMLCompletionProcessor) - return (HTMLCompletionProcessor) p; - return null; - } - - private static void configureJavaProcessor(ContentAssistant assistant, IPreferenceStore store) { - PHPCompletionProcessor pcp = getJavaProcessor(assistant); - if (pcp == null) - return; - - String triggers = store.getString(AUTOACTIVATION_TRIGGERS_JAVA); - if (triggers != null) - pcp.setCompletionProposalAutoActivationCharacters(triggers.toCharArray()); - boolean enabled; - // boolean enabled= store.getBoolean(SHOW_VISIBLE_PROPOSALS); - // jcp.restrictProposalsToVisibility(enabled); - // - // enabled= store.getBoolean(CASE_SENSITIVITY); - // jcp.restrictProposalsToMatchingCases(enabled); - // - enabled = store.getBoolean(ORDER_PROPOSALS); - pcp.orderProposalsAlphabetically(enabled); - // - // enabled= store.getBoolean(ADD_IMPORT); - // jcp.allowAddingImports(enabled); - } - - private static void configureJavaDocProcessor(ContentAssistant assistant, IPreferenceStore store) { - PHPDocCompletionProcessor pdcp = getJavaDocProcessor(assistant); - if (pdcp == null) - return; - - String triggers = store.getString(AUTOACTIVATION_TRIGGERS_JAVADOC); - if (triggers != null) - pdcp.setCompletionProposalAutoActivationCharacters(triggers.toCharArray()); - - boolean enabled = store.getBoolean(CASE_SENSITIVITY); - pdcp.restrictProposalsToMatchingCases(enabled); - - enabled = store.getBoolean(ORDER_PROPOSALS); - pdcp.orderProposalsAlphabetically(enabled); - } - - private static void configureHTMLProcessor(ContentAssistant assistant, IPreferenceStore store) { - HTMLCompletionProcessor hcp = getHTMLProcessor(assistant); - if (hcp == null) - return; - - String triggers = store.getString(AUTOACTIVATION_TRIGGERS_HTML); - if (triggers != null) - hcp.setCompletionProposalAutoActivationCharacters(triggers.toCharArray()); - - boolean enabled; - // boolean enabled = store.getBoolean(CASE_SENSITIVITY); - // jdcp.restrictProposalsToMatchingCases(enabled); - - enabled = store.getBoolean(ORDER_PROPOSALS); - hcp.orderProposalsAlphabetically(enabled); - } - /** - * Configure the given content assistant from the given store. - */ - public static void configure(ContentAssistant assistant, IPreferenceStore store) { - - JavaTextTools textTools = PHPeclipsePlugin.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); - - configureJavaProcessor(assistant, store); - configureJavaDocProcessor(assistant, store); - configureHTMLProcessor(assistant, store); - } - - private static void changeJavaProcessor(ContentAssistant assistant, IPreferenceStore store, String key) { - PHPCompletionProcessor 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); } - else if (ORDER_PROPOSALS.equals(key)) { - boolean enable = store.getBoolean(ORDER_PROPOSALS); - jcp.orderProposalsAlphabetically(enable); - // } else if (ADD_IMPORT.equals(key)) { - // boolean enabled= store.getBoolean(ADD_IMPORT); - // jcp.allowAddingImports(enabled); - } - } - - private static void changeJavaDocProcessor(ContentAssistant assistant, IPreferenceStore store, String key) { - PHPDocCompletionProcessor 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); - } else if (ORDER_PROPOSALS.equals(key)) { - boolean enable = store.getBoolean(ORDER_PROPOSALS); - jdcp.orderProposalsAlphabetically(enable); - } - } - - private static void changeHTMLProcessor(ContentAssistant assistant, IPreferenceStore store, String key) { - HTMLCompletionProcessor jdcp = getHTMLProcessor(assistant); - if (jdcp == null) - return; - - if (AUTOACTIVATION_TRIGGERS_HTML.equals(key)) { - String triggers = store.getString(AUTOACTIVATION_TRIGGERS_HTML); - if (triggers != null) - jdcp.setCompletionProposalAutoActivationCharacters(triggers.toCharArray()); - // } else if (CASE_SENSITIVITY.equals(key)) { - // boolean enabled = store.getBoolean(CASE_SENSITIVITY); - // jdcp.restrictProposalsToMatchingCases(enabled); - } else if (ORDER_PROPOSALS.equals(key)) { - boolean enable = store.getBoolean(ORDER_PROPOSALS); - jdcp.orderProposalsAlphabetically(enable); - } - } - /** - * 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); - } - - changeJavaProcessor(assistant, store, p); - changeJavaDocProcessor(assistant, store, p); - changeHTMLProcessor(assistant, store, p); - } - - public static boolean fillArgumentsOnMethodCompletion(IPreferenceStore store) { - return store.getBoolean(FILL_METHOD_ARGUMENTS); - } + /** 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 completion replacement color */ + private final static String COMPLETION_REPLACEMENT_FOREGROUND = PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND; + + /** Preference key for content assist completion replacement color */ + private final static String COMPLETION_REPLACEMENT_BACKGROUND = PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND; + + /** Preference key for content assist auto insert */ + private final static String AUTOINSERT = PreferenceConstants.CODEASSIST_AUTOINSERT; + + /** Preference key for php content assist auto activation triggers */ + private final static String AUTOACTIVATION_TRIGGERS_JAVA = PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA; + + /** Preference key for phpdoc content assist auto activation triggers */ + private final static String AUTOACTIVATION_TRIGGERS_JAVADOC = PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC; + + /** Preference key for html content assist auto activation triggers */ + private final static String AUTOACTIVATION_TRIGGERS_HTML = PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_HTML; + + /** Preference key for visibility of proposals */ + private final static String SHOW_VISIBLE_PROPOSALS = PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS; + + /** Preference key for alphabetic ordering of proposals */ + private final static String ORDER_PROPOSALS = PreferenceConstants.CODEASSIST_ORDER_PROPOSALS; + + /** Preference key for case sensitivity of propsals */ + private final static String CASE_SENSITIVITY = PreferenceConstants.CODEASSIST_CASE_SENSITIVITY; + + /** Preference key for adding imports on code assist */ + private final static String ADD_IMPORT = PreferenceConstants.CODEASSIST_ADDIMPORT; + + /** Preference key for inserting content assist */ + private static final String INSERT_COMPLETION = PreferenceConstants.CODEASSIST_INSERT_COMPLETION; + + /** Preference key for filling argument names on method completion */ + private static final String FILL_METHOD_ARGUMENTS = PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES; + + /** Preference key for guessing argument names on method completion */ + private static final String GUESS_METHOD_ARGUMENTS = PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS; + + 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) { + JavaTextTools textTools = PHPeclipsePlugin.getDefault() + .getJavaTextTools(); + return getColor(store, key, textTools.getColorManager()); + } + + private static PHPCompletionProcessor getJavaProcessor( + ContentAssistant assistant) { + IContentAssistProcessor p = assistant + .getContentAssistProcessor(IPHPPartitions.PHP_PARTITIONING); + if (p instanceof PHPCompletionProcessor) + return (PHPCompletionProcessor) p; + return null; + } + + private static PHPDocCompletionProcessor getJavaDocProcessor( + ContentAssistant assistant) { + IContentAssistProcessor p = assistant + .getContentAssistProcessor(IPHPPartitions.PHP_PHPDOC_COMMENT); + if (p instanceof PHPDocCompletionProcessor) + return (PHPDocCompletionProcessor) p; + return null; + } + + private static HTMLCompletionProcessor getHTMLProcessor( + ContentAssistant assistant) { + IContentAssistProcessor p = assistant + .getContentAssistProcessor(IPHPPartitions.HTML); + if (p instanceof HTMLCompletionProcessor) + return (HTMLCompletionProcessor) p; + return null; + } + + private static void configureJavaProcessor(ContentAssistant assistant, + IPreferenceStore store) { + PHPCompletionProcessor pcp = getJavaProcessor(assistant); + if (pcp == null) + return; + + String triggers = store.getString(AUTOACTIVATION_TRIGGERS_JAVA); + if (triggers != null) + pcp.setCompletionProposalAutoActivationCharacters(triggers + .toCharArray()); + boolean enabled; + // boolean enabled= store.getBoolean(SHOW_VISIBLE_PROPOSALS); + // jcp.restrictProposalsToVisibility(enabled); + // + // enabled= store.getBoolean(CASE_SENSITIVITY); + // jcp.restrictProposalsToMatchingCases(enabled); + // + enabled = store.getBoolean(ORDER_PROPOSALS); + pcp.orderProposalsAlphabetically(enabled); + // + // enabled= store.getBoolean(ADD_IMPORT); + // jcp.allowAddingImports(enabled); + } + + private static void configureJavaDocProcessor(ContentAssistant assistant, + IPreferenceStore store) { + PHPDocCompletionProcessor pdcp = getJavaDocProcessor(assistant); + if (pdcp == null) + return; + + String triggers = store.getString(AUTOACTIVATION_TRIGGERS_JAVADOC); + if (triggers != null) + pdcp.setCompletionProposalAutoActivationCharacters(triggers + .toCharArray()); + + boolean enabled = store.getBoolean(CASE_SENSITIVITY); + pdcp.restrictProposalsToMatchingCases(enabled); + + enabled = store.getBoolean(ORDER_PROPOSALS); + pdcp.orderProposalsAlphabetically(enabled); + } + + private static void configureHTMLProcessor(ContentAssistant assistant, + IPreferenceStore store) { + HTMLCompletionProcessor hcp = getHTMLProcessor(assistant); + if (hcp == null) + return; + + String triggers = store.getString(AUTOACTIVATION_TRIGGERS_HTML); + if (triggers != null) + hcp.setCompletionProposalAutoActivationCharacters(triggers + .toCharArray()); + + boolean enabled; + // boolean enabled = store.getBoolean(CASE_SENSITIVITY); + // jdcp.restrictProposalsToMatchingCases(enabled); + + enabled = store.getBoolean(ORDER_PROPOSALS); + hcp.orderProposalsAlphabetically(enabled); + } + + /** + * Configure the given content assistant from the given store. + */ + public static void configure(ContentAssistant assistant, + IPreferenceStore store) { + + JavaTextTools textTools = PHPeclipsePlugin.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); + + configureJavaProcessor(assistant, store); + configureJavaDocProcessor(assistant, store); + configureHTMLProcessor(assistant, store); + } + + private static void changeJavaProcessor(ContentAssistant assistant, + IPreferenceStore store, String key) { + PHPCompletionProcessor 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); } + else if (ORDER_PROPOSALS.equals(key)) { + boolean enable = store.getBoolean(ORDER_PROPOSALS); + jcp.orderProposalsAlphabetically(enable); + // } else if (ADD_IMPORT.equals(key)) { + // boolean enabled= store.getBoolean(ADD_IMPORT); + // jcp.allowAddingImports(enabled); + } + } + + private static void changeJavaDocProcessor(ContentAssistant assistant, + IPreferenceStore store, String key) { + PHPDocCompletionProcessor 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); + } else if (ORDER_PROPOSALS.equals(key)) { + boolean enable = store.getBoolean(ORDER_PROPOSALS); + jdcp.orderProposalsAlphabetically(enable); + } + } + + private static void changeHTMLProcessor(ContentAssistant assistant, + IPreferenceStore store, String key) { + HTMLCompletionProcessor jdcp = getHTMLProcessor(assistant); + if (jdcp == null) + return; + + if (AUTOACTIVATION_TRIGGERS_HTML.equals(key)) { + String triggers = store.getString(AUTOACTIVATION_TRIGGERS_HTML); + if (triggers != null) + jdcp.setCompletionProposalAutoActivationCharacters(triggers + .toCharArray()); + // } else if (CASE_SENSITIVITY.equals(key)) { + // boolean enabled = store.getBoolean(CASE_SENSITIVITY); + // jdcp.restrictProposalsToMatchingCases(enabled); + } else if (ORDER_PROPOSALS.equals(key)) { + boolean enable = store.getBoolean(ORDER_PROPOSALS); + jdcp.orderProposalsAlphabetically(enable); + } + } + + /** + * 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); + } + + changeJavaProcessor(assistant, store, p); + changeJavaDocProcessor(assistant, store, p); + changeHTMLProcessor(assistant, store, p); + } + + public static boolean fillArgumentsOnMethodCompletion(IPreferenceStore store) { + return store.getBoolean(FILL_METHOD_ARGUMENTS); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/CustomSourceInformationControl.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/CustomSourceInformationControl.java index 245aaf3..3f3c40a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/CustomSourceInformationControl.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/CustomSourceInformationControl.java @@ -31,48 +31,64 @@ import org.eclipse.swt.widgets.Shell; * * @since 3.0 */ -public class CustomSourceInformationControl extends SourceViewerInformationControl { +public class CustomSourceInformationControl extends + SourceViewerInformationControl { /** The font name for the viewer font - the same as the java editor's. */ - private static final String SYMBOLIC_FONT_NAME= "net.sourceforge.phpdt.ui.editors.textfont"; //$NON-NLS-1$ - - /** The maximum width of the control, set in setSizeConstraints(int, int). */ - int fMaxWidth= Integer.MAX_VALUE; - /** The maximum height of the control, set in setSizeConstraints(int, int). */ - int fMaxHeight= Integer.MAX_VALUE; - - /** The partition type to be used as the starting partition type by the paritition scanner. */ + private static final String SYMBOLIC_FONT_NAME = "net.sourceforge.phpdt.ui.editors.textfont"; //$NON-NLS-1$ + + /** + * The maximum width of the control, set in + * setSizeConstraints(int, int). + */ + int fMaxWidth = Integer.MAX_VALUE; + + /** + * The maximum height of the control, set in + * setSizeConstraints(int, int). + */ + int fMaxHeight = Integer.MAX_VALUE; + + /** + * The partition type to be used as the starting partition type by the + * paritition scanner. + */ private String fPartition; + /** The horizontal scroll index. */ private int fHorizontalScrollPixel; - + /* - * @see org.eclipse.jface.text.IInformationControl#setSizeConstraints(int, int) + * @see org.eclipse.jface.text.IInformationControl#setSizeConstraints(int, + * int) */ public void setSizeConstraints(int maxWidth, int maxHeight) { - fMaxWidth= maxWidth; - fMaxHeight= maxHeight; + fMaxWidth = maxWidth; + fMaxHeight = maxHeight; } /** * Creates a new information control. * - * @param parent the shell that is the parent of this hover / control - * @param partition the initial partition type to be used for the underlying viewer + * @param parent + * the shell that is the parent of this hover / control + * @param partition + * the initial partition type to be used for the underlying + * viewer */ public CustomSourceInformationControl(Shell parent, String partition) { super(parent); 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); + Point size = super.computeSizeHint(); + size.x = Math.min(size.x, fMaxWidth); + size.y = Math.min(size.y, fMaxHeight); return size; } @@ -80,81 +96,83 @@ public class CustomSourceInformationControl extends SourceViewerInformationContr * Sets the font for this viewer sustaining selection and scroll position. */ private void setViewerFont() { - Font font= JFaceResources.getFont(SYMBOLIC_FONT_NAME); + 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; + 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(); + ITextViewerExtension extension = (ITextViewerExtension) getViewer(); + parent = extension.getControl(); } - + parent.setRedraw(false); - + styledText.setFont(font); - - getViewer().setSelectedRange(selection.x , selection.y); + + getViewer().setSelectedRange(selection.x, selection.y); getViewer().setTopIndex(topIndex); - + if (parent instanceof Composite) { - Composite composite= (Composite) parent; + Composite composite = (Composite) parent; composite.layout(true); } - + parent.setRedraw(true); - + } else { - StyledText styledText= getViewer().getTextWidget(); + StyledText styledText = getViewer().getTextWidget(); styledText.setFont(font); - } + } } /** * Sets the initial partition for the underlying source viewer. * - * @param partition the partition type + * @param partition + * the partition type */ public void setStartingPartitionType(String partition) { if (partition == null) - fPartition= IDocument.DEFAULT_CONTENT_TYPE; + fPartition = IDocument.DEFAULT_CONTENT_TYPE; else - fPartition= partition; + fPartition = partition; } - + /* * @see org.eclipse.jface.text.IInformationControl#setInformation(java.lang.String) */ public void setInformation(String content) { super.setInformation(content); - IDocument doc= getViewer().getDocument(); + IDocument doc = getViewer().getDocument(); if (doc == null) return; - + // ensure that we can scroll enough ensureScrollable(); - - String start= null; + + String start = null; if (IPHPPartitions.PHP_PHPDOC_COMMENT.equals(fPartition)) { - start= "/**" + doc.getLegalLineDelimiters()[0]; //$NON-NLS-1$ + start = "/**" + doc.getLegalLineDelimiters()[0]; //$NON-NLS-1$ } else if (IPHPPartitions.PHP_MULTILINE_COMMENT.equals(fPartition)) { - start= "/*" + doc.getLegalLineDelimiters()[0]; //$NON-NLS-1$ + 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); + int startLen = start.length(); + getViewer().setDocument(doc, startLen, + doc.getLength() - startLen); } catch (BadLocationException e) { // impossible Assert.isTrue(false); } } - + getViewer().getTextWidget().setHorizontalPixel(fHorizontalScrollPixel); } @@ -164,28 +182,28 @@ public class CustomSourceInformationControl extends SourceViewerInformationContr * accordingly. */ private void ensureScrollable() { - IDocument doc= getViewer().getDocument(); + IDocument doc = getViewer().getDocument(); if (doc == null) return; - - StyledText widget= getViewer().getTextWidget(); + + StyledText widget = getViewer().getTextWidget(); if (widget == null || widget.isDisposed()) return; - - int last= doc.getNumberOfLines() - 1; - GC gc= new GC(widget); + + int last = doc.getNumberOfLines() - 1; + GC gc = new GC(widget); gc.setFont(widget.getFont()); - int maxWidth= 0; - String content= new String(); + int maxWidth = 0; + String content = new String(); try { - for (int i= 0; i <= last; i++) { + 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; + line = doc.getLineInformation(i); + content = doc.get(line.getOffset(), line.getLength()); + int width = gc.textExtent(content).x; if (width > maxWidth) { - maxWidth= width; + maxWidth = width; } } } catch (BadLocationException e) { @@ -193,26 +211,28 @@ public class CustomSourceInformationControl extends SourceViewerInformationContr } 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)); + fMaxWidth = Math.max(0, Math.min(fMaxWidth, maxWidth + - fHorizontalScrollPixel + 8)); } - + /* * @see net.sourceforge.phpdt.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 + * + * @param scrollIndex + * the new horizontal scroll index */ public void setHorizontalScrollPixel(int scrollIndex) { - scrollIndex= Math.max(0, scrollIndex); - fHorizontalScrollPixel= scrollIndex; + scrollIndex = Math.max(0, scrollIndex); + fHorizontalScrollPixel = scrollIndex; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/DocumentCharacterIterator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/DocumentCharacterIterator.java index ea30c7a..416ddaf 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/DocumentCharacterIterator.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/DocumentCharacterIterator.java @@ -16,7 +16,6 @@ import org.eclipse.jface.text.Assert; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; - /** * An IDocument based implementation of * CharacterIterator and CharSequence. Note that @@ -26,14 +25,18 @@ import org.eclipse.jface.text.IDocument; * accessing the document fails with a {@link BadLocationException}, any of * CharacterIterator methods as well as charAtmay * return {@link CharacterIterator#DONE}. - * + * * @since 3.0 */ -public class DocumentCharacterIterator implements CharacterIterator, CharSequence { +public class DocumentCharacterIterator implements CharacterIterator, + CharSequence { + + private int fIndex = -1; - private int fIndex= -1; private final IDocument fDocument; + private final int fFirst; + private final int fLast; private void invariant() { @@ -43,8 +46,9 @@ public class DocumentCharacterIterator implements CharacterIterator, CharSequenc /** * Creates an iterator for the entire document. - * - * @param document the document backing this iterator + * + * @param document + * the document backing this iterator */ public DocumentCharacterIterator(IDocument document) { this(document, 0); @@ -52,35 +56,44 @@ public class DocumentCharacterIterator implements CharacterIterator, CharSequenc /** * Creates an iterator, starting at offset first. - * - * @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 { + * + * @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 first * (inclusive) to last (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 { + * + * @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; + fDocument = document; + fFirst = first; + fLast = last; + fIndex = first; invariant(); } @@ -137,7 +150,7 @@ public class DocumentCharacterIterator implements CharacterIterator, CharSequenc */ public char setIndex(int position) { if (position >= getBeginIndex() && position <= getEndIndex()) - fIndex= position; + fIndex = position; else throw new IllegalArgumentException(); @@ -191,8 +204,9 @@ public class DocumentCharacterIterator implements CharacterIterator, CharSequenc * return {@link CharacterIterator#DONE} if a {@link BadLocationException} * was thrown when accessing the backing document. *

                                                      - * - * @param index {@inheritDoc} + * + * @param index + * {@inheritDoc} * @return {@inheritDoc} */ public char charAt(int index) { @@ -217,6 +231,7 @@ public class DocumentCharacterIterator implements CharacterIterator, CharSequenc throw new IndexOutOfBoundsException(); if (end > length()) throw new IndexOutOfBoundsException(); - return new DocumentCharacterIterator(fDocument, getBeginIndex() + start, getBeginIndex() + end); + return new DocumentCharacterIterator(fDocument, + getBeginIndex() + start, getBeginIndex() + end); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/FastJavaPartitionScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/FastJavaPartitionScanner.java index d9e8c7f..8653b77 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/FastJavaPartitionScanner.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/FastJavaPartitionScanner.java @@ -23,7 +23,8 @@ import org.eclipse.jface.text.rules.Token; * This scanner recognizes the JavaDoc comments, Java multi line comments, Java * single line comments, Java strings. */ -public class FastJavaPartitionScanner implements IPartitionTokenScanner, IPHPPartitions { +public class FastJavaPartitionScanner implements IPartitionTokenScanner, + IPHPPartitions { // states private static final int PHP = 0; @@ -43,29 +44,40 @@ public class FastJavaPartitionScanner implements IPartitionTokenScanner, IPHPPar // beginning of prefixes and postfixes private static final int NONE = 0; - private static final int BACKSLASH = 1; // postfix for STRING_DQ and CHARACTER + private static final int BACKSLASH = 1; // postfix for STRING_DQ and + // CHARACTER - private static final int SLASH = 2; // prefix for SINGLE_LINE or MULTI_LINE or - // JAVADOC + private static final int SLASH = 2; // prefix for SINGLE_LINE or MULTI_LINE + // or - private static final int SLASH_STAR = 3; // prefix for MULTI_LINE_COMMENT or - // JAVADOC + // JAVADOC - private static final int SLASH_STAR_STAR = 4; // prefix for MULTI_LINE_COMMENT - // or JAVADOC + private static final int SLASH_STAR = 3; // prefix for MULTI_LINE_COMMENT + // or + + // JAVADOC + + private static final int SLASH_STAR_STAR = 4; // prefix for + // MULTI_LINE_COMMENT + + // or JAVADOC private static final int STAR = 5; // postfix for MULTI_LINE_COMMENT or - // JAVADOC + + // JAVADOC private static final int CARRIAGE_RETURN = 6; // postfix for STRING_DQ, - // CHARACTER and - // SINGLE_LINE_COMMENT + + // CHARACTER and + // SINGLE_LINE_COMMENT // private static final int HEREDOC = 7; /** The scanner. */ - private final BufferedDocumentScanner fScanner = new BufferedDocumentScanner(1000); // faster - // implementation + private final BufferedDocumentScanner fScanner = new BufferedDocumentScanner( + 1000); // faster + + // implementation /** The offset of the last returned token. */ private int fTokenOffset; @@ -89,8 +101,10 @@ public class FastJavaPartitionScanner implements IPartitionTokenScanner, IPHPPar private int fJavaLength; - private final IToken[] fTokens = new IToken[] { new Token(null), new Token(PHP_SINGLELINE_COMMENT), - new Token(PHP_MULTILINE_COMMENT), new Token(PHP_PHPDOC_COMMENT), new Token(PHP_STRING_DQ), new Token(PHP_STRING_SQ), + private final IToken[] fTokens = new IToken[] { new Token(null), + new Token(PHP_SINGLELINE_COMMENT), + new Token(PHP_MULTILINE_COMMENT), new Token(PHP_PHPDOC_COMMENT), + new Token(PHP_STRING_DQ), new Token(PHP_STRING_SQ), new Token(PHP_STRING_HEREDOC) }; public FastJavaPartitionScanner(boolean emulate) { @@ -108,7 +122,8 @@ public class FastJavaPartitionScanner implements IPartitionTokenScanner, IPHPPar // emulate JavaPartitionScanner if (fEmulate) { - if (fJavaOffset != -1 && fTokenOffset + fTokenLength != fJavaOffset + fJavaLength) { + if (fJavaOffset != -1 + && fTokenOffset + fTokenLength != fJavaOffset + fJavaLength) { fTokenOffset += fTokenLength; return fTokens[PHP]; } else { @@ -200,10 +215,9 @@ public class FastJavaPartitionScanner implements IPartitionTokenScanner, IPHPPar fScanner.unread(); fScanner.unread(); return postFix(fState); - } - else { + } else { // bug #1404228: Crash on - if (nextch!=ICharacterScanner.EOF) { + if (nextch != ICharacterScanner.EOF) { fScanner.unread(); } } @@ -297,7 +311,8 @@ public class FastJavaPartitionScanner implements IPartitionTokenScanner, IPHPPar case '*': if (fLast == SLASH) { if (fTokenLength - getLastLength(fLast) > 0) - return preFix(PHP, MULTI_LINE_COMMENT, SLASH_STAR, 2); + return preFix(PHP, MULTI_LINE_COMMENT, SLASH_STAR, + 2); else { preFix(PHP, MULTI_LINE_COMMENT, SLASH_STAR, 2); fTokenOffset += fTokenLength; @@ -498,9 +513,11 @@ public class FastJavaPartitionScanner implements IPartitionTokenScanner, IPHPPar return fTokens[state]; } - private final IToken preFix(int state, int newState, int last, int prefixLength) { + private final IToken preFix(int state, int newState, int last, + int prefixLength) { // emulate JavaPartitionScanner - if (fEmulate && state == PHP && (fTokenLength - getLastLength(fLast) > 0)) { + if (fEmulate && state == PHP + && (fTokenLength - getLastLength(fLast) > 0)) { fTokenLength -= getLastLength(fLast); fJavaOffset = fTokenOffset; fJavaLength = fTokenLength; @@ -554,7 +571,8 @@ public class FastJavaPartitionScanner implements IPartitionTokenScanner, IPHPPar * @see IPartitionTokenScanner#setPartialRange(IDocument, int, int, String, * int) */ - public void setPartialRange(IDocument document, int offset, int length, String contentType, int partitionOffset) { + public void setPartialRange(IDocument document, int offset, int length, + String contentType, int partitionOffset) { fScanner.setRange(document, offset, length); setRange(document, offset, length); fTokenOffset = partitionOffset; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/HTML2TextReader.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/HTML2TextReader.java index e9cb748..1fe8811 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/HTML2TextReader.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/HTML2TextReader.java @@ -1,12 +1,10 @@ package net.sourceforge.phpdt.internal.ui.text; - /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ - import java.io.IOException; import java.io.PushbackReader; import java.io.Reader; @@ -21,24 +19,24 @@ import org.eclipse.jface.text.TextPresentation; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyleRange; - - - /** - * Reads the text contents from a reader of HTML contents and translates - * the tags or cut them out. + * Reads the text contents from a reader of HTML contents and translates the + * tags or cut them out. */ public class HTML2TextReader extends SubstitutionTextReader { - - - private static final String LINE_DELIM= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ - private static final String EMPTY_STRING= ""; //$NON-NLS-1$ + + private static final String LINE_DELIM = System.getProperty( + "line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ + + private static final String EMPTY_STRING = ""; //$NON-NLS-1$ + private static final Map fgEntityLookup; + private static final Set fgTags; - + static { - - fgTags= new HashSet(); + + fgTags = new HashSet(); fgTags.add("b"); //$NON-NLS-1$ fgTags.add("br"); //$NON-NLS-1$ fgTags.add("h5"); //$NON-NLS-1$ @@ -49,92 +47,99 @@ public class HTML2TextReader extends SubstitutionTextReader { fgTags.add("li"); //$NON-NLS-1$ fgTags.add("ul"); //$NON-NLS-1$ fgTags.add("pre"); //$NON-NLS-1$ - - fgEntityLookup= new HashMap(7); + + 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$ + fgEntityLookup.put("quot", "\""); //$NON-NLS-1$ //$NON-NLS-2$ } - - private int fCounter= 0; + + private int fCounter = 0; + private TextPresentation fTextPresentation; - private int fBold= 0; - private int fStartOffset= -1; - private boolean fInParagraph= false; - private boolean fIsPreformattedText= false; - + + private int fBold = 0; + + private int fStartOffset = -1; + + private boolean fInParagraph = false; + + private boolean fIsPreformattedText = false; + /** * Transforms the html text from the reader to formatted text. - * @param presentation If not null, formattings will be applied to - * the presentation. - */ + * + * @param presentation + * If not null, formattings will be applied to + * the presentation. + */ public HTML2TextReader(Reader reader, TextPresentation presentation) { super(new PushbackReader(reader)); - fTextPresentation= presentation; + fTextPresentation = presentation; } - + public int read() throws IOException { - int c= super.read(); + int c = super.read(); if (c != -1) - ++ fCounter; + ++fCounter; return c; } - + protected void startBold() { if (fBold == 0) - fStartOffset= fCounter; - ++ fBold; + fStartOffset = fCounter; + ++fBold; } protected void startPreformattedText() { - fIsPreformattedText= true; + fIsPreformattedText = true; setSkipWhitespace(false); } protected void stopPreformattedText() { - fIsPreformattedText= false; + fIsPreformattedText = false; setSkipWhitespace(true); } - + protected void stopBold() { - -- fBold; + --fBold; if (fBold == 0) { if (fTextPresentation != null) { - fTextPresentation.addStyleRange(new StyleRange(fStartOffset, fCounter - fStartOffset, null, null, SWT.BOLD)); + fTextPresentation.addStyleRange(new StyleRange(fStartOffset, + fCounter - fStartOffset, null, null, SWT.BOLD)); } - fStartOffset= -1; + fStartOffset = -1; } } - + /** * @see SubstitutionTextReader#computeSubstitution(char) */ protected String computeSubstitution(int c) throws IOException { - + if (c == '<') - return processHTMLTag(); + return processHTMLTag(); else if (c == '&') return processEntity(); else if (fIsPreformattedText) return processPreformattedText(c); - + return null; } private String html2Text(String html) { - - String tag= html; + + String tag = html; if ('/' == tag.charAt(0)) - tag= tag.substring(1); - + tag = tag.substring(1); + if (!fgTags.contains(tag)) return EMPTY_STRING; - if ("pre".equals(html)) { //$NON-NLS-1$ startPreformattedText(); return EMPTY_STRING; @@ -152,142 +157,142 @@ public class HTML2TextReader extends SubstitutionTextReader { startBold(); return EMPTY_STRING; } - + if ("h5".equals(html) || "dt".equals(html)) { //$NON-NLS-1$ //$NON-NLS-2$ 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$ - return LINE_DELIM + "\t" + PHPUIMessages.getString("HTML2TextReader.dash"); //$NON-NLS-1$ //$NON-NLS-2$ - + return LINE_DELIM + + "\t" + PHPUIMessages.getString("HTML2TextReader.dash"); //$NON-NLS-1$ //$NON-NLS-2$ + if ("/b".equals(html)) { //$NON-NLS-1$ stopBold(); return EMPTY_STRING; } - if ("p".equals(html)) { //$NON-NLS-1$ - fInParagraph= true; + if ("p".equals(html)) { //$NON-NLS-1$ + fInParagraph = true; return LINE_DELIM; } if ("br".equals(html)) //$NON-NLS-1$ return LINE_DELIM; - - if ("/p".equals(html)) { //$NON-NLS-1$ - boolean inParagraph= fInParagraph; - fInParagraph= false; + + if ("/p".equals(html)) { //$NON-NLS-1$ + boolean inParagraph = fInParagraph; + fInParagraph = false; return inParagraph ? EMPTY_STRING : LINE_DELIM; } - + if ("/h5".equals(html) || "/dt".equals(html)) { //$NON-NLS-1$ //$NON-NLS-2$ stopBold(); return LINE_DELIM; } - + if ("/dd".equals(html)) //$NON-NLS-1$ return LINE_DELIM; - + return EMPTY_STRING; } - + /* * A '<' has been read. Process a html tag - */ + */ private String processHTMLTag() throws IOException { - - StringBuffer buf= new StringBuffer(); + + StringBuffer buf = new StringBuffer(); int ch; - do { - - ch= nextChar(); - + do { + + ch = nextChar(); + while (ch != -1 && ch != '>') { buf.append(Character.toLowerCase((char) ch)); - ch= nextChar(); - if (ch == '"'){ + ch = nextChar(); + if (ch == '"') { buf.append(Character.toLowerCase((char) ch)); - ch= nextChar(); - while (ch != -1 && ch != '"'){ + ch = nextChar(); + while (ch != -1 && ch != '"') { buf.append(Character.toLowerCase((char) ch)); - ch= nextChar(); - } + ch = nextChar(); + } } - if (ch == '<'){ + if (ch == '<') { unread(ch); return '<' + buf.toString(); - } + } } - + if (ch == -1) return null; - - int tagLen= buf.length(); - // needs special treatment for comments + + 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 - 3)))) { //$NON-NLS-1$ + && !(tagLen >= 5 && "--!".equals(buf.substring(tagLen - 3)))) { //$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') + 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); + ch = Integer.parseInt(symbol.substring(2), 16); } else { - ch= Integer.parseInt(symbol.substring(1), 10); + ch = Integer.parseInt(symbol.substring(1), 10); } - return EMPTY_STRING + (char)ch; + return EMPTY_STRING + (char) ch; } catch (NumberFormatException e) { } } else { - String str= (String) fgEntityLookup.get(symbol); + 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 == '#') { + StringBuffer buf = new StringBuffer(); + int ch = nextChar(); + while (Character.isLetterOrDigit((char) ch) || ch == '#') { buf.append((char) ch); - ch= nextChar(); + ch = nextChar(); } - - if (ch == ';') + + if (ch == ';') return entity2Text(buf.toString()); - + buf.insert(0, '&'); if (ch != -1) buf.append((char) ch); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/HTMLPrinter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/HTMLPrinter.java index f17bd7f..47484da 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/HTMLPrinter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/HTMLPrinter.java @@ -10,7 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.ui.text; - import java.io.IOException; import java.io.Reader; @@ -20,70 +19,70 @@ import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; - /** * Provides a set of convenience methods for creating HTML pages. */ public class HTMLPrinter { - + private HTMLPrinter() { } - + private static String replace(String text, char c, String s) { - - int previous= 0; - int current= text.indexOf(c, previous); - + + int previous = 0; + int current = text.indexOf(c, previous); + if (current == -1) return text; - - StringBuffer buffer= new StringBuffer(); + + StringBuffer buffer = new StringBuffer(); while (current > -1) { buffer.append(text.substring(previous, current)); buffer.append(s); - previous= current + 1; - current= text.indexOf(c, previous); + 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, '<', "<"); //$NON-NLS-1$ + content = replace(content, '<', "<"); //$NON-NLS-1$ return replace(content, '>', ">"); //$NON-NLS-1$ } - + public static String read(Reader rd) { - - StringBuffer buffer= new StringBuffer(); - char[] readBuffer= new char[2048]; - + + StringBuffer buffer = new StringBuffer(); + char[] readBuffer = new char[2048]; + try { - int n= rd.read(readBuffer); + int n = rd.read(readBuffer); while (n > 0) { buffer.append(readBuffer, 0, n); - n= rd.read(readBuffer); + n = rd.read(readBuffer); } return buffer.toString(); } catch (IOException x) { } - + return null; } - public static void insertPageProlog(StringBuffer buffer, int position, RGB bgRGB) { + public static void insertPageProlog(StringBuffer buffer, int position, + RGB bgRGB) { if (bgRGB == null) insertPageProlog(buffer, position); else { - StringBuffer pageProlog= new StringBuffer(60); + StringBuffer pageProlog = new StringBuffer(60); pageProlog.append(""); //$NON-NLS-1$ - buffer.insert(position, pageProlog.toString()); + buffer.insert(position, pageProlog.toString()); } } - + private static void appendColor(StringBuffer buffer, RGB rgb) { buffer.append('#'); buffer.append(Integer.toHexString(rgb.red)); @@ -92,35 +91,38 @@ public class HTMLPrinter { } public static void insertPageProlog(StringBuffer buffer, int position) { - RGB bgColor= null; - IWorkbenchWindow window= PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + RGB bgColor = null; + IWorkbenchWindow window = PlatformUI.getWorkbench() + .getActiveWorkbenchWindow(); if (window != null) { - Display display= window.getShell().getDisplay(); + Display display = window.getShell().getDisplay(); if (display != null && !display.isDisposed()) - bgColor= display.getSystemColor(SWT.COLOR_INFO_BACKGROUND).getRGB(); + bgColor = display.getSystemColor(SWT.COLOR_INFO_BACKGROUND) + .getRGB(); } if (bgColor == null) - bgColor= new RGB(255,255, 225); // RGB value of info bg color on WindowsXP - + bgColor = new RGB(255, 255, 225); // RGB value of info bg color on + // WindowsXP + insertPageProlog(buffer, position, bgColor); //$NON-NLS-1$ } - + public static void addPageProlog(StringBuffer buffer) { insertPageProlog(buffer, buffer.length()); } - + public static void addPageEpilog(StringBuffer buffer) { buffer.append(""); //$NON-NLS-1$ } - + public static void startBulletList(StringBuffer buffer) { buffer.append("
                                                        "); //$NON-NLS-1$ } - + public static void endBulletList(StringBuffer buffer) { buffer.append("
                                                      "); //$NON-NLS-1$ } - + public static void addBullet(StringBuffer buffer, String bullet) { if (bullet != null) { buffer.append("
                                                    • "); //$NON-NLS-1$ @@ -128,7 +130,7 @@ public class HTMLPrinter { buffer.append("
                                                    • "); //$NON-NLS-1$ } } - + public static void addSmallHeader(StringBuffer buffer, String header) { if (header != null) { buffer.append("
                                                      "); //$NON-NLS-1$ @@ -136,14 +138,14 @@ public class HTMLPrinter { buffer.append("
                                                      "); //$NON-NLS-1$ } } - + public static void addParagraph(StringBuffer buffer, String paragraph) { if (paragraph != null) { buffer.append("

                                                      "); //$NON-NLS-1$ buffer.append(paragraph); } } - + public static void addParagraph(StringBuffer buffer, Reader paragraphReader) { if (paragraphReader != null) addParagraph(buffer, read(paragraphReader)); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/HTMLTextPresenter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/HTMLTextPresenter.java index dc9587a..9cef2f5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/HTMLTextPresenter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/HTMLTextPresenter.java @@ -5,7 +5,6 @@ package net.sourceforge.phpdt.internal.ui.text; * All Rights Reserved. */ - import java.io.IOException; import java.io.Reader; import java.io.StringReader; @@ -21,103 +20,111 @@ import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.widgets.Display; +public class HTMLTextPresenter implements + DefaultInformationControl.IInformationPresenter { + private static final String LINE_DELIM = System.getProperty( + "line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ - -public class HTMLTextPresenter implements DefaultInformationControl.IInformationPresenter { - - 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; + fEnforceUpperLineLimit = enforceUpperLineLimit; } - + public HTMLTextPresenter() { this(true); } - - protected Reader createReader(String hoverInfo, TextPresentation presentation) { + + 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(); + + 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); - + + 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(); + + 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; - + 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) + * @see IHoverInformationPresenter#updatePresentation(Display display, + * String, TextPresentation, int, int) */ - public String updatePresentation(Display display, String hoverInfo, TextPresentation presentation, int maxWidth, int maxHeight) { - + public String updatePresentation(Display display, String hoverInfo, + TextPresentation presentation, int maxWidth, int maxHeight) { + if (hoverInfo == null) return null; - - GC gc= new GC(display); + + GC gc = new GC(display); 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; - + + 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); @@ -127,62 +134,62 @@ public class HTMLTextPresenter implements DefaultInformationControl.IInformation append(buffer, lastLineIndent, presentation); } } - + append(buffer, line, null); - firstLineProcessed= true; - - lastLineFormatted= lineFormatted; + firstLineProcessed = true; + + lastLineFormatted = lineFormatted; if (!lineFormatted) - lastLineIndent= null; + lastLineIndent = null; else if (lastLineIndent == null) - lastLineIndent= getIndent(line); - - line= reader.readLine(); - lineFormatted= reader.isFormattedLine(); - + lastLineIndent = getIndent(line); + + line = reader.readLine(); + lineFormatted = reader.isFormattedLine(); + maxNumberOfLines--; } - + if (line != null) { append(buffer, LINE_DELIM, lineFormatted ? presentation : null); - append(buffer, PHPUIMessages.getString("HTMLTextPresenter.ellipsis"), presentation); //$NON-NLS-1$ + append(buffer, PHPUIMessages + .getString("HTMLTextPresenter.ellipsis"), presentation); //$NON-NLS-1$ } - + return trim(buffer, presentation); - + } catch (IOException e) { - + PHPeclipsePlugin.log(e); return null; - + } finally { gc.dispose(); } } - + private String trim(StringBuffer buffer, TextPresentation presentation) { - - int length= buffer.length(); - - int end= length -1; + + int length = buffer.length(); + + int end = length - 1; while (end >= 0 && Character.isWhitespace(buffer.charAt(end))) - -- end; - + --end; + if (end == -1) return ""; //$NON-NLS-1$ - - if (end < length -1) + + if (end < length - 1) buffer.delete(end + 1, length); else - end= length; - - int start= 0; + end = length; + + int start = 0; while (start < end && Character.isWhitespace(buffer.charAt(start))) - ++ start; - + ++start; + buffer.delete(0, start); presentation.setResultWindow(new Region(start, buffer.length())); return buffer.toString(); } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/IPHPPartitions.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/IPHPPartitions.java index 82fd098..18b2e2a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/IPHPPartitions.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/IPHPPartitions.java @@ -6,30 +6,44 @@ package net.sourceforge.phpdt.internal.ui.text; /** * @author Stefan Langer (musk) - * + * */ -public interface IPHPPartitions -{ +public interface IPHPPartitions { public final static String PHP_PARTITIONING = "___php_partitioning"; //$NON-NLS-1$ public final static String PHP_PHPDOC_COMMENT = "__php_phpdoc_comment"; //$NON-NLS-1$ + public final static String PHP_SINGLELINE_COMMENT = "__php_singleline_comment"; //$NON-NLS-1$ + public final static String PHP_MULTILINE_COMMENT = "__php_multiline_comment"; //$NON-NLS-1$ + public final static String PHP_STRING_DQ = "__php_string"; //$NON-NLS-1$ + public final static String PHP_STRING_SQ = "__php_string_sq"; //$NON-NLS-1$ + public final static String PHP_STRING_HEREDOC = "__php_string_heredoc"; //$NON-NLS-1$ + public final static String JAVASCRIPT = "__javascript"; //$NON-NLS-1$ + public final static String JS_MULTILINE_COMMENT = "__js_multiline_comment"; //$NON-NLS-1$ + public final static String CSS = "__css"; //$NON-NLS-1$ + public final static String CSS_MULTILINE_COMMENT = "__css_multiline_comment"; //$NON-NLS-1$ + public final static String HTML = "__html"; //$NON-NLS-1$ + public final static String HTML_MULTILINE_COMMENT = "__html_multiline_comment"; //$NON-NLS-1$ public final static String SMARTY = "__smarty"; //$NON-NLS-1$ + public final static String SMARTY_MULTILINE_COMMENT = "__smarty_multiline_comment"; //$NON-NLS-1$ public final static int PHP_FILE = 1; + public final static int HTML_FILE = 2; + public final static int XML_FILE = 3; + public final static int SMARTY_FILE = 4; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/ITypingRunListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/ITypingRunListener.java index 0d79e10..a1e35a5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/ITypingRunListener.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/ITypingRunListener.java @@ -12,7 +12,6 @@ package net.sourceforge.phpdt.internal.ui.text; import net.sourceforge.phpdt.internal.ui.text.TypingRun.ChangeType; - /** * Listener for TypingRun events. * @@ -22,15 +21,18 @@ public interface ITypingRunListener { /** * Called when a new TypingRun is started. * - * @param run the newly started run + * @param run + * the newly started run */ void typingRunStarted(TypingRun run); - + /** * Called whenever a TypingRun is ended. * - * @param run the ended run - * @param reason the type of change that caused the end of the run + * @param run + * the ended run + * @param reason + * the type of change that caused the end of the run */ void typingRunEnded(TypingRun run, ChangeType reason); } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaAnnotationHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaAnnotationHover.java index bdecc4a..f845fe3 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaAnnotationHover.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaAnnotationHover.java @@ -33,45 +33,55 @@ import org.eclipse.ui.texteditor.AnnotationPreference; // TODO: delete this class ? we use PHPAnnotationHover instead ! /** - * Determines all markers for the given line and collects, concatenates, and formates - * their messages. + * Determines all markers for the given line and collects, concatenates, and + * formates their messages. */ public class JavaAnnotationHover implements IAnnotationHover { private static class JavaAnnotationHoverType { } - - public static final JavaAnnotationHoverType OVERVIEW_RULER_HOVER= new JavaAnnotationHoverType(); - public static final JavaAnnotationHoverType TEXT_RULER_HOVER= new JavaAnnotationHoverType(); - public static final JavaAnnotationHoverType VERTICAL_RULER_HOVER= new JavaAnnotationHoverType(); - - private IPreferenceStore fStore= PHPeclipsePlugin.getDefault().getPreferenceStore(); - + + public static final JavaAnnotationHoverType OVERVIEW_RULER_HOVER = new JavaAnnotationHoverType(); + + public static final JavaAnnotationHoverType TEXT_RULER_HOVER = new JavaAnnotationHoverType(); + + public static final JavaAnnotationHoverType VERTICAL_RULER_HOVER = new JavaAnnotationHoverType(); + + private IPreferenceStore fStore = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + private JavaAnnotationHoverType fType; - + public JavaAnnotationHover(JavaAnnotationHoverType type) { - Assert.isTrue(OVERVIEW_RULER_HOVER.equals(type) || TEXT_RULER_HOVER.equals(type) || VERTICAL_RULER_HOVER.equals(type)); - fType= type; + Assert.isTrue(OVERVIEW_RULER_HOVER.equals(type) + || TEXT_RULER_HOVER.equals(type) + || VERTICAL_RULER_HOVER.equals(type)); + fType = type; } - + /** - * Returns the distance to the ruler line. + * Returns the distance to the ruler line. */ - protected int compareRulerLine(Position position, IDocument document, int line) { - + protected int compareRulerLine(Position position, IDocument document, + int line) { + if (position.getOffset() > -1 && position.getLength() > -1) { try { - int javaAnnotationLine= document.getLineOfOffset(position.getOffset()); + int javaAnnotationLine = document.getLineOfOffset(position + .getOffset()); if (line == javaAnnotationLine) return 1; - if (javaAnnotationLine <= line && line <= document.getLineOfOffset(position.getOffset() + position.getLength())) + if (javaAnnotationLine <= line + && line <= document.getLineOfOffset(position + .getOffset() + + position.getLength())) return 2; } catch (BadLocationException x) { } } - + return 0; } - + /** * Selects a set of markers from the two lists. By default, it just returns * the set of exact matches. @@ -79,60 +89,62 @@ public class JavaAnnotationHover implements IAnnotationHover { protected List select(List exactMatch, List including) { return exactMatch; } + /** * Returns one marker which includes the ruler's line of activity. */ protected List getJavaAnnotationsForLine(ISourceViewer viewer, int line) { - - IDocument document= viewer.getDocument(); - IAnnotationModel model= viewer.getAnnotationModel(); - + + IDocument document = viewer.getDocument(); + IAnnotationModel model = viewer.getAnnotationModel(); + if (model == null) return null; - - List exact= new ArrayList(); - List including= new ArrayList(); - - Iterator e= model.getAnnotationIterator(); - HashMap messagesAtPosition= new HashMap(); + + List exact = new ArrayList(); + List including = new ArrayList(); + + Iterator e = model.getAnnotationIterator(); + HashMap messagesAtPosition = new HashMap(); while (e.hasNext()) { - Annotation annotation= (Annotation) e.next(); + Annotation annotation = (Annotation) e.next(); if (annotation.getText() == null) continue; - - Position position= model.getPosition(annotation); + + Position position = model.getPosition(annotation); if (position == null) continue; - - AnnotationPreference preference= getAnnotationPreference(annotation); + + AnnotationPreference preference = getAnnotationPreference(annotation); if (preference == null) continue; - - if (OVERVIEW_RULER_HOVER.equals(fType)) { - String key= preference.getOverviewRulerPreferenceKey(); + + if (OVERVIEW_RULER_HOVER.equals(fType)) { + String key = preference.getOverviewRulerPreferenceKey(); if (key == null || !fStore.getBoolean(key)) continue; } else if (TEXT_RULER_HOVER.equals(fType)) { - String key= preference.getTextPreferenceKey(); + String key = preference.getTextPreferenceKey(); if (key != null) { if (!fStore.getBoolean(key)) continue; } else { - key= preference.getHighlightPreferenceKey(); + key = preference.getHighlightPreferenceKey(); if (key == null || !fStore.getBoolean(key)) continue; } } else if (VERTICAL_RULER_HOVER.equals(fType)) { - String key= preference.getVerticalRulerPreferenceKey(); + String key = preference.getVerticalRulerPreferenceKey(); // backward compatibility if (key != null && !fStore.getBoolean(key)) continue; } - - if (isDuplicateJavaAnnotation(messagesAtPosition, position, annotation.getText())) + + if (isDuplicateJavaAnnotation(messagesAtPosition, position, + annotation.getText())) continue; - + switch (compareRulerLine(position, document, line)) { case 1: exact.add(annotation); @@ -142,66 +154,70 @@ public class JavaAnnotationHover implements IAnnotationHover { break; } } - + return select(exact, including); } -// /** -// * Returns one marker which includes the ruler's line of activity. -// */ -// protected List getJavaAnnotationsForLine(ISourceViewer viewer, int line) { -// -// IDocument document= viewer.getDocument(); -// IAnnotationModel model= viewer.getAnnotationModel(); -// -// if (model == null) -// return null; -// -// List exact= new ArrayList(); -// List including= new ArrayList(); -// -// Iterator e= model.getAnnotationIterator(); -// HashMap messagesAtPosition= new HashMap(); -// while (e.hasNext()) { -// Object o= e.next(); -// if (o instanceof IJavaAnnotation) { -// IJavaAnnotation a= (IJavaAnnotation)o; -// if (!a.hasOverlay()) { -// Position position= model.getPosition((Annotation)a); -// if (position == null) -// continue; -// -// if (isDuplicateJavaAnnotation(messagesAtPosition, position, a.getMessage())) -// continue; -// -// switch (compareRulerLine(position, document, line)) { -// case 1: -// exact.add(a); -// break; -// case 2: -// including.add(a); -// break; -// } -// } -// } -// } -// -// return select(exact, including); -// } - - private boolean isDuplicateJavaAnnotation(Map messagesAtPosition, Position position, String message) { + + // /** + // * Returns one marker which includes the ruler's line of activity. + // */ + // protected List getJavaAnnotationsForLine(ISourceViewer viewer, int line) + // { + // + // IDocument document= viewer.getDocument(); + // IAnnotationModel model= viewer.getAnnotationModel(); + // + // if (model == null) + // return null; + // + // List exact= new ArrayList(); + // List including= new ArrayList(); + // + // Iterator e= model.getAnnotationIterator(); + // HashMap messagesAtPosition= new HashMap(); + // while (e.hasNext()) { + // Object o= e.next(); + // if (o instanceof IJavaAnnotation) { + // IJavaAnnotation a= (IJavaAnnotation)o; + // if (!a.hasOverlay()) { + // Position position= model.getPosition((Annotation)a); + // if (position == null) + // continue; + // + // if (isDuplicateJavaAnnotation(messagesAtPosition, position, + // a.getMessage())) + // continue; + // + // switch (compareRulerLine(position, document, line)) { + // case 1: + // exact.add(a); + // break; + // case 2: + // including.add(a); + // break; + // } + // } + // } + // } + // + // return select(exact, including); + // } + + private boolean isDuplicateJavaAnnotation(Map messagesAtPosition, + Position position, String message) { if (messagesAtPosition.containsKey(position)) { - Object value= messagesAtPosition.get(position); + Object value = messagesAtPosition.get(position); if (message.equals(value)) return true; if (value instanceof List) { - List messages= (List)value; - if (messages.contains(message)) + List messages = (List) value; + if (messages.contains(message)) return true; else messages.add(message); } else { - ArrayList messages= new ArrayList(); + ArrayList messages = new ArrayList(); messages.add(value); messages.add(message); messagesAtPosition.put(position, messages); @@ -210,118 +226,129 @@ public class JavaAnnotationHover implements IAnnotationHover { messagesAtPosition.put(position, message); return false; } - + /* * @see IVerticalRulerHover#getHoverInfo(ISourceViewer, int) */ public String getHoverInfo(ISourceViewer sourceViewer, int lineNumber) { - List javaAnnotations= getJavaAnnotationsForLine(sourceViewer, lineNumber); + List javaAnnotations = getJavaAnnotationsForLine(sourceViewer, + lineNumber); if (javaAnnotations != null) { - + if (javaAnnotations.size() == 1) { - + // optimization - Annotation annotation= (Annotation) javaAnnotations.get(0); - String message= annotation.getText(); + Annotation annotation = (Annotation) javaAnnotations.get(0); + String message = annotation.getText(); if (message != null && message.trim().length() > 0) return formatSingleMessage(message); - + } else { - - List messages= new ArrayList(); - - Iterator e= javaAnnotations.iterator(); + + List messages = new ArrayList(); + + Iterator e = javaAnnotations.iterator(); while (e.hasNext()) { - Annotation annotation= (Annotation) e.next(); - String message= annotation.getText(); + Annotation annotation = (Annotation) e.next(); + String message = annotation.getText(); if (message != null && message.trim().length() > 0) messages.add(message.trim()); } - + if (messages.size() == 1) return formatSingleMessage((String) messages.get(0)); - + if (messages.size() > 1) return formatMultipleMessages(messages); } } - + return null; } + /* * @see IVerticalRulerHover#getHoverInfo(ISourceViewer, int) */ -// public String getHoverInfo(ISourceViewer sourceViewer, int lineNumber) { -// List javaAnnotations= getJavaAnnotationsForLine(sourceViewer, lineNumber); -// if (javaAnnotations != null) { -// -// if (javaAnnotations.size() == 1) { -// -// // optimization -// IJavaAnnotation javaAnnotation= (IJavaAnnotation) javaAnnotations.get(0); -// String message= javaAnnotation.getMessage(); -// if (message != null && message.trim().length() > 0) -// return formatSingleMessage(message); -// -// } else { -// -// List messages= new ArrayList(); -// -// Iterator e= javaAnnotations.iterator(); -// while (e.hasNext()) { -// IJavaAnnotation javaAnnotation= (IJavaAnnotation) e.next(); -// String message= javaAnnotation.getMessage(); -// if (message != null && message.trim().length() > 0) -// messages.add(message.trim()); -// } -// -// if (messages.size() == 1) -// return formatSingleMessage((String) messages.get(0)); -// -// if (messages.size() > 1) -// return formatMultipleMessages(messages); -// } -// } -// -// return null; -// } - + // public String getHoverInfo(ISourceViewer sourceViewer, int lineNumber) { + // List javaAnnotations= getJavaAnnotationsForLine(sourceViewer, + // lineNumber); + // if (javaAnnotations != null) { + // + // if (javaAnnotations.size() == 1) { + // + // // optimization + // IJavaAnnotation javaAnnotation= (IJavaAnnotation) javaAnnotations.get(0); + // String message= javaAnnotation.getMessage(); + // if (message != null && message.trim().length() > 0) + // return formatSingleMessage(message); + // + // } else { + // + // List messages= new ArrayList(); + // + // Iterator e= javaAnnotations.iterator(); + // while (e.hasNext()) { + // IJavaAnnotation javaAnnotation= (IJavaAnnotation) e.next(); + // String message= javaAnnotation.getMessage(); + // if (message != null && message.trim().length() > 0) + // messages.add(message.trim()); + // } + // + // if (messages.size() == 1) + // return formatSingleMessage((String) messages.get(0)); + // + // if (messages.size() > 1) + // return formatMultipleMessages(messages); + // } + // } + // + // return null; + // } /* * Formats a message as HTML text. */ private String formatSingleMessage(String message) { - StringBuffer buffer= new StringBuffer(); + StringBuffer buffer = new StringBuffer(); HTMLPrinter.addPageProlog(buffer); - HTMLPrinter.addParagraph(buffer, HTMLPrinter.convertToHTMLContent(message)); + HTMLPrinter.addParagraph(buffer, HTMLPrinter + .convertToHTMLContent(message)); HTMLPrinter.addPageEpilog(buffer); return buffer.toString(); } - + /* * Formats several message as HTML text. */ private String formatMultipleMessages(List messages) { - StringBuffer buffer= new StringBuffer(); + StringBuffer buffer = new StringBuffer(); HTMLPrinter.addPageProlog(buffer); - HTMLPrinter.addParagraph(buffer, HTMLPrinter.convertToHTMLContent(PHPUIMessages.getString("JavaAnnotationHover.multipleMarkersAtThisLine"))); //$NON-NLS-1$ - + HTMLPrinter + .addParagraph( + buffer, + HTMLPrinter + .convertToHTMLContent(PHPUIMessages + .getString("JavaAnnotationHover.multipleMarkersAtThisLine"))); //$NON-NLS-1$ + HTMLPrinter.startBulletList(buffer); - Iterator e= messages.iterator(); + Iterator e = messages.iterator(); while (e.hasNext()) - HTMLPrinter.addBullet(buffer, HTMLPrinter.convertToHTMLContent((String) e.next())); - HTMLPrinter.endBulletList(buffer); - + HTMLPrinter.addBullet(buffer, HTMLPrinter + .convertToHTMLContent((String) e.next())); + HTMLPrinter.endBulletList(buffer); + HTMLPrinter.addPageEpilog(buffer); return buffer.toString(); } - + /** * Returns the annotation preference for the given annotation. * - * @param annotation the annotation + * @param annotation + * the annotation * @return the annotation preference or null if none - */ + */ private AnnotationPreference getAnnotationPreference(Annotation annotation) { - return EditorsUI.getAnnotationPreferenceLookup().getAnnotationPreference(annotation); + return EditorsUI.getAnnotationPreferenceLookup() + .getAnnotationPreference(annotation); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaBreakIterator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaBreakIterator.java index eb4067f..f80d88a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaBreakIterator.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaBreakIterator.java @@ -17,9 +17,8 @@ import net.sourceforge.phpdt.internal.compiler.parser.Scanner; import org.eclipse.jface.text.Assert; - /** - * A java break iterator. It returns all breaks, including before and after + * A java break iterator. It returns all breaks, including before and after * whitespace, and it returns all camelcase breaks. *

                                                      * A line break may be any of "\n", "\r", "\r\n", "\n\r". @@ -35,17 +34,18 @@ public class JavaBreakIterator extends BreakIterator { protected static abstract class Run { /** The length of this run. */ protected int length; - + public Run() { init(); } - + /** * Returns true if this run consumes ch, * false otherwise. If true is returned, * the length of the receiver is adjusted accordingly. * - * @param ch the character to test + * @param ch + * the character to test * @return true if ch was consumed */ protected boolean consume(char ch) { @@ -55,69 +55,72 @@ public class JavaBreakIterator extends BreakIterator { } return false; } - + /** - * Whether this run accepts that character; does not update state. Called - * from the default implementation of consume. + * Whether this run accepts that character; does not update state. + * Called from the default implementation of consume. * - * @param ch the character to test + * @param ch + * the character to test * @return true if ch is accepted */ protected abstract boolean isValid(char ch); - + /** * Resets this run to the initial state. */ protected void init() { - length= 0; + 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'; - + + private static final char INIT = '\0'; + + private static final char EXIT = '\1'; + /* * @see net.sourceforge.phpdt.internal.ui.text.JavaBreakIterator.Run#init() */ protected void init() { super.init(); - fState= INIT; + fState = INIT; } - + /* * @see net.sourceforge.phpdt.internal.ui.text.JavaBreakIterator.Run#consume(char) */ protected boolean consume(char ch) { if (!isValid(ch) || fState == EXIT) return false; - + if (fState == INIT) { - fState= ch; + fState = ch; length++; return true; } else if (fState != ch) { - fState= EXIT; + 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 net.sourceforge.phpdt.internal.ui.text.JavaBreakIterator.Run#isValid(char) @@ -126,67 +129,76 @@ public class JavaBreakIterator extends BreakIterator { return Scanner.isPHPIdentifierPart(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; + 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 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 + + 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 net.sourceforge.phpdt.internal.ui.text.JavaBreakIterator.Run#init() */ protected void init() { super.init(); - fState= S_INIT; + fState = S_INIT; } - + /* * @see net.sourceforge.phpdt.internal.ui.text.JavaBreakIterator.Run#consumes(char) */ protected boolean consume(char ch) { - int kind= getKind(ch); - fState= MATRIX[fState][kind]; + 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; + 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 + * @param ch + * the character to test */ private int getKind(char ch) { if (Character.isUpperCase(ch)) @@ -211,29 +223,35 @@ public class JavaBreakIterator extends BreakIterator { * @see net.sourceforge.phpdt.internal.ui.text.JavaBreakIterator.Run#isValid(char) */ protected boolean isValid(char ch) { - return !Character.isWhitespace(ch) && !Scanner.isPHPIdentifierPart(ch); + return !Character.isWhitespace(ch) + && !Scanner.isPHPIdentifierPart(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. */ + + 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(); + fIterator = BreakIterator.getWordInstance(); + fIndex = fIterator.current(); } /* @@ -247,7 +265,7 @@ public class JavaBreakIterator extends BreakIterator { * @see java.text.BreakIterator#first() */ public int first() { - fIndex= fIterator.first(); + fIndex = fIterator.first(); return fIndex; } @@ -258,64 +276,67 @@ public class JavaBreakIterator extends BreakIterator { // work around too eager IAEs in standard impl if (offset == getText().getEndIndex()) return DONE; - - int next= fIterator.following(offset); + + 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 wordinstance considers _ as boundaries // seems to work fine, however - Run run= consumeRun(offset); + 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 + * + * @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); + + 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); + ch = fText.charAt(offset); } - + return run; } /** * Retunrs a run based on a character. * - * @param ch the character to test + * @param ch + * the character to test * @return the correct character given ch */ private Run getRun(char ch) { Run run; if (WHITESPACE.isValid(ch)) - run= WHITESPACE; + run = WHITESPACE; else if (DELIMITER.isValid(ch)) - run= DELIMITER; + run = DELIMITER; else if (CAMELCASE.isValid(ch)) - run= CAMELCASE; + run = CAMELCASE; else if (OTHER.isValid(ch)) - run= OTHER; + run = OTHER; else { Assert.isTrue(false); return null; } - + run.init(); return run; } - + /* * @see java.text.BreakIterator#getText() */ @@ -327,17 +348,17 @@ public class JavaBreakIterator extends BreakIterator { * @see java.text.BreakIterator#isBoundary(int) */ public boolean isBoundary(int offset) { - if (offset == getText().getBeginIndex()) - return true; - else - return following(offset - 1) == offset; + if (offset == getText().getBeginIndex()) + return true; + else + return following(offset - 1) == offset; } /* * @see java.text.BreakIterator#last() */ public int last() { - fIndex= fIterator.last(); + fIndex = fIterator.last(); return fIndex; } @@ -345,7 +366,7 @@ public class JavaBreakIterator extends BreakIterator { * @see java.text.BreakIterator#next() */ public int next() { - fIndex= following(fIndex); + fIndex = following(fIndex); return fIndex; } @@ -355,28 +376,28 @@ public class JavaBreakIterator extends BreakIterator { 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; + int previous = offset - 1; do { - previous= fIterator.preceding(previous); + previous = fIterator.preceding(previous); } while (!isBoundary(previous)); - - int last= DONE; + + int last = DONE; while (previous < offset) { - last= previous; - previous= following(previous); + last = previous; + previous = following(previous); } - + return last; } @@ -384,7 +405,7 @@ public class JavaBreakIterator extends BreakIterator { * @see java.text.BreakIterator#previous() */ public int previous() { - fIndex= preceding(fIndex); + fIndex = preceding(fIndex); return fIndex; } @@ -397,10 +418,12 @@ public class JavaBreakIterator extends BreakIterator { /** * Creates a break iterator given a char sequence. - * @param newText the new text + * + * @param newText + * the new text */ public void setText(CharSequence newText) { - fText= newText; + fText = newText; fIterator.setText(new SequenceCharacterIterator(newText)); first(); } @@ -410,11 +433,12 @@ public class JavaBreakIterator extends BreakIterator { */ public void setText(CharacterIterator newText) { if (newText instanceof CharSequence) { - fText= (CharSequence) newText; + fText = (CharSequence) newText; fIterator.setText(newText); first(); } else { - throw new UnsupportedOperationException("CharacterIterator not supported"); //$NON-NLS-1$ + throw new UnsupportedOperationException( + "CharacterIterator not supported"); //$NON-NLS-1$ } } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaColorManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaColorManager.java index 3c57e1d..7578353 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaColorManager.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaColorManager.java @@ -4,7 +4,7 @@ package net.sourceforge.phpdt.internal.ui.text; * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ - + import java.util.HashMap; import java.util.Iterator; import java.util.Map; @@ -20,21 +20,20 @@ import org.eclipse.swt.widgets.Display; * Java color manager. */ public class JavaColorManager implements IColorManager, IColorManagerExtension { - protected Map fKeyTable= new HashMap(10); - protected Map fDisplayTable= new HashMap(2); + 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. + /** + * 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. - */ + * Creates a new Java color manager which automatically disposes the + * allocated colors when the current display gets disposed. + */ public JavaColorManager() { this(true); } @@ -42,40 +41,43 @@ public class JavaColorManager implements IColorManager, IColorManagerExtension { /** * Creates a new Java color manager. * - * @param autoDisposeOnDisplayDispose if true 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. + * @param autoDisposeOnDisplayDispose + * if true 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. * * @since 2.1 */ public JavaColorManager(boolean autoDisposeOnDisplayDispose) { - fAutoDisposeOnDisplayDispose= autoDisposeOnDisplayDispose; + fAutoDisposeOnDisplayDispose = autoDisposeOnDisplayDispose; } - + public void dispose(Display display) { - Map colorTable= (Map) fDisplayTable.get(display); + Map colorTable = (Map) fDisplayTable.get(display); if (colorTable != null) { - Iterator e= colorTable.values().iterator(); + Iterator e = colorTable.values().iterator(); while (e.hasNext()) { - Color color= (Color)e.next(); + 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); + + final Display display = Display.getCurrent(); + Map colorTable = (Map) fDisplayTable.get(display); if (colorTable == null) { - colorTable= new HashMap(10); + colorTable = new HashMap(10); fDisplayTable.put(display, colorTable); if (fAutoDisposeOnDisplayDispose) { display.disposeExec(new Runnable() { @@ -85,16 +87,16 @@ public class JavaColorManager implements IColorManager, IColorManagerExtension { }); } } - - Color color= (Color) colorTable.get(rgb); + + Color color = (Color) colorTable.get(rgb); if (color == null) { - color= new Color(Display.getCurrent(), rgb); + color = new Color(Display.getCurrent(), rgb); colorTable.put(rgb, color); } - + return color; } - + /* * @see IColorManager#dispose */ @@ -102,27 +104,27 @@ public class JavaColorManager implements IColorManager, IColorManagerExtension { 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); + + 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); + Object value = fKeyTable.get(key); if (value != null) throw new UnsupportedOperationException(); - + fKeyTable.put(key, rgb); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaCompositeReconcilingStrategy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaCompositeReconcilingStrategy.java index 74ae99f..bdbe486 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaCompositeReconcilingStrategy.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaCompositeReconcilingStrategy.java @@ -24,122 +24,128 @@ import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.ITextEditor; /** - * Reconciling strategy for Java code. This is a composite strategy containing the regular java model reconciler and the comment - * spell checking strategy. + * Reconciling strategy for Java code. This is a composite strategy containing + * the regular java model reconciler and the comment spell checking strategy. * * @since 3.0 */ -public class JavaCompositeReconcilingStrategy extends CompositeReconcilingStrategy { +public class JavaCompositeReconcilingStrategy extends + CompositeReconcilingStrategy { - private ITextEditor fEditor; + private ITextEditor fEditor; - private JavaReconcilingStrategy fJavaStrategy; + private JavaReconcilingStrategy fJavaStrategy; - /** - * Creates a new Java reconciling strategy. - * - * @param editor - * the editor of the strategy's reconciler - * @param documentPartitioning - * the document partitioning this strategy uses for configuration - */ - public JavaCompositeReconcilingStrategy(ITextEditor editor, String documentPartitioning) { - fEditor = editor; - fJavaStrategy = new JavaReconcilingStrategy(editor); - setReconcilingStrategies(new IReconcilingStrategy[] { fJavaStrategy, - new SpellReconcileStrategy(editor, documentPartitioning, PreferenceConstants.getPreferenceStore()) }); - } + /** + * Creates a new Java reconciling strategy. + * + * @param editor + * the editor of the strategy's reconciler + * @param documentPartitioning + * the document partitioning this strategy uses for configuration + */ + public JavaCompositeReconcilingStrategy(ITextEditor editor, + String documentPartitioning) { + fEditor = editor; + fJavaStrategy = new JavaReconcilingStrategy(editor); + setReconcilingStrategies(new IReconcilingStrategy[] { + fJavaStrategy, + new SpellReconcileStrategy(editor, documentPartitioning, + PreferenceConstants.getPreferenceStore()) }); + } - /** - * 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) { - try { - // work around for https://bugs.eclipse.org/bugs/show_bug.cgi?id=51522 - p = PHPeclipsePlugin.getDefault().getCompilationUnitDocumentProvider(); - } catch (NullPointerException npe) { - return null; - } - } - IAnnotationModel m = p.getAnnotationModel(fEditor.getEditorInput()); - if (m instanceof IProblemRequestorExtension) - return (IProblemRequestorExtension) m; - return null; - } + /** + * 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) { + try { + // work around for + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=51522 + p = PHPeclipsePlugin.getDefault() + .getCompilationUnitDocumentProvider(); + } catch (NullPointerException npe) { + return null; + } + } + 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.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); - } - } + /* + * @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 - * true if listeners should be notified - */ - public void notifyListeners(boolean notify) { - fJavaStrategy.notifyListeners(notify); - } + /** + * Tells this strategy whether to inform its listeners. + * + * @param notify + * true 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(); - } - } + /* + * @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. - * - * @since 3.0 - */ - public void aboutToBeReconciled() { - fJavaStrategy.aboutToBeReconciled(); + /** + * Called before reconciling is started. + * + * @since 3.0 + */ + public void aboutToBeReconciled() { + fJavaStrategy.aboutToBeReconciled(); - } + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaElementProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaElementProvider.java index ed4d33a..db4ef87 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaElementProvider.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaElementProvider.java @@ -10,7 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.ui.text; - import net.sourceforge.phpdt.core.IJavaElement; import net.sourceforge.phpdt.core.JavaModelException; import net.sourceforge.phpdt.internal.ui.actions.SelectionConverter; @@ -24,39 +23,40 @@ import org.eclipse.jface.text.information.IInformationProviderExtension; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IEditorPart; - - /** * Provides a Java element to be displayed in by an information presenter. */ -public class JavaElementProvider implements IInformationProvider, IInformationProviderExtension { +public class JavaElementProvider implements IInformationProvider, + IInformationProviderExtension { private PHPEditor fEditor; + private boolean fUseCodeResolve; public JavaElementProvider(IEditorPart editor) { - fUseCodeResolve= false; + fUseCodeResolve = false; if (editor instanceof PHPEditor) - fEditor= (PHPEditor)editor; + fEditor = (PHPEditor) editor; } public JavaElementProvider(IEditorPart editor, boolean useCodeResolve) { this(editor); - fUseCodeResolve= useCodeResolve; + 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); + IRegion region = JavaWordFinder.findWord(textViewer.getDocument(), + offset); if (region != null) return region; else return new Region(offset, 0); } - return null; + return null; } /* @@ -72,14 +72,16 @@ public class JavaElementProvider implements IInformationProvider, IInformationPr public Object getInformation2(ITextViewer textViewer, IRegion subject) { if (fEditor == null) return null; - + try { if (fUseCodeResolve) { - IStructuredSelection sel= SelectionConverter.getStructuredSelection(fEditor); + IStructuredSelection sel = SelectionConverter + .getStructuredSelection(fEditor); if (!sel.isEmpty()) return sel.getFirstElement(); } - IJavaElement element= SelectionConverter.getElementAtOffset(fEditor); + IJavaElement element = SelectionConverter + .getElementAtOffset(fEditor); if (element != null) return element; return SelectionConverter.getInput(fEditor); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaHeuristicScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaHeuristicScanner.java index d7ef909..6bea251 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaHeuristicScanner.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaHeuristicScanner.java @@ -23,57 +23,75 @@ import org.eclipse.jface.text.Region; import org.eclipse.jface.text.TextUtilities; /** - * Utility methods for heuristic based Java manipulations in an incomplete Java source file. + * Utility methods for heuristic based Java manipulations in an incomplete Java + * source file. * - *

                                                      An instance holds some internal position in the document and is therefore not threadsafe.

                                                      + *

                                                      + * An instance holds some internal position in the document and is therefore not + * threadsafe. + *

                                                      * * @since 3.0 */ public 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. + /** + * 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; + public static final int NOT_FOUND = -1; - /** - * Special bound parameter that means either -1 (backward scanning) or + /** + * Special bound parameter that means either -1 (backward scanning) or * fDocument.getLength() (forward scanning). */ - public static final int UNBOUND= -2; - + 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 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 = '='; /** - * Specifies the stop condition, upon which the scanXXX methods will decide whether - * to keep scanning or not. This interface may implemented by clients. + * Specifies the stop condition, upon which the scanXXX + * methods will decide whether to keep scanning or not. This interface may + * implemented by clients. */ public interface 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 + * @param ch + * the char at the current position + * @param position + * the current position + * @param forward + * the iteration direction * @return true if the stop condition is met. */ boolean stop(char ch, int position, boolean forward); } - + /** - * Stops upon a non-whitespace (as defined by {@link Character#isWhitespace(char)}) character. + * Stops upon a non-whitespace (as defined by + * {@link Character#isWhitespace(char)}) character. */ private static class NonWhitespace implements StopCondition { /* @@ -83,23 +101,25 @@ public class JavaHeuristicScanner implements Symbols { return !Character.isWhitespace(ch); } } - + /** * Stops upon a non-whitespace character in the default partition. * - * @see NonWhitespace + * @see NonWhitespace */ private class NonWhitespaceDefaultPartition extends NonWhitespace { /* * @see net.sourceforge.phpdt.internal.ui.text.JavaHeuristicScanner.StopCondition#stop(char) */ public boolean stop(char ch, int position, boolean forward) { - return super.stop(ch, position, true) && isDefaultPartition(position); + return super.stop(ch, position, true) + && isDefaultPartition(position); } } - + /** - * Stops upon a non-java identifier (as defined by {@link Scanner#isPHPIdentifierPart(char)}) character. + * Stops upon a non-java identifier (as defined by + * {@link Scanner#isPHPIdentifierPart(char)}) character. */ private static class NonJavaIdentifierPart implements StopCondition { /* @@ -109,83 +129,98 @@ public class JavaHeuristicScanner implements Symbols { return !Scanner.isPHPIdentifierPart(ch); } } - + /** * Stops upon a non-java identifier character in the default partition. * - * @see NonJavaIdentifierPart + * @see NonJavaIdentifierPart */ - private class NonJavaIdentifierPartDefaultPartition extends NonJavaIdentifierPart { + private class NonJavaIdentifierPartDefaultPartition extends + NonJavaIdentifierPart { /* * @see net.sourceforge.phpdt.internal.ui.text.JavaHeuristicScanner.StopCondition#stop(char) */ public boolean stop(char ch, int position, boolean forward) { - return super.stop(ch, position, true) || !isDefaultPartition(position); + return super.stop(ch, position, true) + || !isDefaultPartition(position); } } - + /** - * Stops upon a character in the default partition that matches the given character list. + * Stops upon a character in the default partition that matches the given + * character list. */ private class CharacterMatch implements StopCondition { private final char[] fChars; - + /** * Creates a new instance. - * @param ch the single character to match + * + * @param ch + * the single character to match */ public CharacterMatch(char ch) { - this(new char[] {ch}); + this(new char[] { ch }); } - + /** * Creates a new instance. - * @param chars the chars to match. + * + * @param chars + * the chars to match. */ public CharacterMatch(char[] chars) { Assert.isNotNull(chars); Assert.isTrue(chars.length > 0); - fChars= chars; + fChars = chars; Arrays.sort(chars); } - + /* - * @see net.sourceforge.phpdt.internal.ui.text.JavaHeuristicScanner.StopCondition#stop(char, int) + * @see net.sourceforge.phpdt.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); + return Arrays.binarySearch(fChars, ch) >= 0 + && isDefaultPartition(position); } } - + /** - * Acts like character match, but skips all scopes introduced by parenthesis, brackets, and - * braces. + * Acts like character match, but skips all scopes introduced by + * parenthesis, brackets, and braces. */ protected class SkippingScopeMatch extends CharacterMatch { private char fOpening, fClosing; - private int fDepth= 0; - + + private int fDepth = 0; + /** * Creates a new instance. - * @param ch the single character to match + * + * @param ch + * the single character to match */ public SkippingScopeMatch(char ch) { super(ch); } - + /** * Creates a new instance. - * @param chars the chars to match. + * + * @param chars + * the chars to match. */ public SkippingScopeMatch(char[] chars) { super(chars); } /* - * @see net.sourceforge.phpdt.internal.ui.text.JavaHeuristicScanner.StopCondition#stop(char, int) + * @see net.sourceforge.phpdt.internal.ui.text.JavaHeuristicScanner.StopCondition#stop(char, + * int) */ public boolean stop(char ch, int position, boolean forward) { - + if (fDepth == 0 && super.stop(ch, position, true)) return true; else if (ch == fOpening) @@ -193,97 +228,109 @@ public class JavaHeuristicScanner implements Symbols { else if (ch == fClosing) { fDepth--; if (fDepth == 0) { - fOpening= 0; - fClosing= 0; + fOpening = 0; + fClosing = 0; } } else if (fDepth == 0) { - fDepth= 1; + fDepth = 1; if (forward) { - + switch (ch) { - case LBRACE: - fOpening= LBRACE; - fClosing= RBRACE; - break; - case LPAREN: - fOpening= LPAREN; - fClosing= RPAREN; - break; - case LBRACKET: - fOpening= LBRACKET; - fClosing= RBRACKET; - break; + case LBRACE: + fOpening = LBRACE; + fClosing = RBRACE; + break; + case LPAREN: + fOpening = LPAREN; + fClosing = RPAREN; + break; + case LBRACKET: + fOpening = LBRACKET; + fClosing = RBRACKET; + break; } - + } else { switch (ch) { - case RBRACE: - fOpening= RBRACE; - fClosing= LBRACE; - break; - case RPAREN: - fOpening= RPAREN; - fClosing= LPAREN; - break; - case RBRACKET: - fOpening= RBRACKET; - fClosing= LBRACKET; - break; + case RBRACE: + fOpening = RBRACE; + fClosing = LBRACE; + break; + case RPAREN: + fOpening = RPAREN; + fClosing = LPAREN; + break; + case RBRACKET: + fOpening = RBRACKET; + fClosing = LBRACKET; + break; } - + } } - + return false; - + } } - + /** The document being scanned. */ private IDocument fDocument; + /** The partitioning being used for scanning. */ private String fPartitioning; + /** The partition to scan in. */ private String fPartition; - /* internal scan state */ - + /* internal scan state */ + /** the most recently read character. */ private char fChar; + /** the most recently read position. */ private int fPos; - + /* preset stop conditions */ - private final StopCondition fNonWSDefaultPart= new NonWhitespaceDefaultPartition(); - private final static StopCondition fNonWS= new NonWhitespace(); - private final StopCondition fNonIdent= new NonJavaIdentifierPartDefaultPartition(); + 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 + * @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) { + public JavaHeuristicScanner(IDocument document, String partitioning, + String partition) { Assert.isNotNull(document); Assert.isNotNull(partitioning); Assert.isNotNull(partition); - fDocument= document; - fPartitioning= partitioning; - fPartition= partition; + fDocument = document; + fPartitioning = partitioning; + fPartition = partition; } - + /** - * Calls this(document, IJavaPartitions.JAVA_PARTITIONING, IDocument.DEFAULT_CONTENT_TYPE). + * Calls + * this(document, IJavaPartitions.JAVA_PARTITIONING, IDocument.DEFAULT_CONTENT_TYPE). * - * @param document the document to scan. + * @param document + * the document to scan. */ public JavaHeuristicScanner(IDocument document) { - this(document, IPHPPartitions.PHP_PARTITIONING, IDocument.DEFAULT_CONTENT_TYPE); + this(document, IPHPPartitions.PHP_PARTITIONING, + IDocument.DEFAULT_CONTENT_TYPE); } - + /** * Returns the most recent internal scan position. * @@ -292,233 +339,247 @@ public class JavaHeuristicScanner implements Symbols { public int getPosition() { return fPos; } - + /** - * Returns the next token in forward direction, starting at start, and not extending - * further than bound. 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). + * Returns the next token in forward direction, starting at + * start, and not extending further than bound. + * 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 + * @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); + 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 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; } - + // else if (Scanner.isPHPIdentifierPart(fChar)) { // assume an ident or keyword - int from= pos, to; - pos= scanForward(pos + 1, bound, fNonIdent); + int from = pos, to; + pos = scanForward(pos + 1, bound, fNonIdent); if (pos == NOT_FOUND) - to= bound == UNBOUND ? fDocument.getLength() : bound; + to = bound == UNBOUND ? fDocument.getLength() : bound; else - to= pos; - + to = pos; + String identOrKeyword; try { - identOrKeyword= fDocument.get(from, to - from); + 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 start, and not extending - * further than bound. 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). + * Returns the next token in backward direction, starting at + * start, and not extending further than bound. + * 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 + * @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); + 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 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; } - + // else if (Scanner.isPHPIdentifierPart(fChar)) { // assume an ident or keyword - int from, to= pos + 1; - pos= scanBackward(pos - 1, bound, fNonIdent); + int from, to = pos + 1; + pos = scanBackward(pos - 1, bound, fNonIdent); if (pos == NOT_FOUND) - from= bound == UNBOUND ? 0 : bound + 1; + from = bound == UNBOUND ? 0 : bound + 1; else - from= pos + 1; - + from = pos + 1; + String identOrKeyword; try { - identOrKeyword= fDocument.get(from, to - from); + 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 TokenIDENT for a scanned identifier. + * Returns one of the keyword constants or TokenIDENT for a + * scanned identifier. * - * @param s 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 ("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 ("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 12: - if ("synchronized".equals(s)) //$NON-NLS-1$ - return TokenSYNCHRONIZED; - break; + 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 ("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 ("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 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. + * 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. * - *

                                                      Note that start must not point to the opening peer, but to the first - * character being searched.

                                                      + *

                                                      + * Note that start must not point to the opening peer, but to + * the first character being searched. + *

                                                      * - * @param start the start position - * @param openingPeer the opening peer character (e.g. '{') - * @param closingPeer the closing peer character (e.g. '}') + * @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 NOT_FOUND */ - public int findClosingPeer(int start, final char openingPeer, final char closingPeer) { + public int findClosingPeer(int start, final char openingPeer, + final char closingPeer) { Assert.isNotNull(fDocument); Assert.isTrue(start >= 0); - + try { - int depth= 1; + int depth = 1; start -= 1; while (true) { - start= scanForward(start + 1, UNBOUND, new CharacterMatch(new char[] {openingPeer, closingPeer})); + start = scanForward(start + 1, UNBOUND, new CharacterMatch( + new char[] { openingPeer, closingPeer })); if (start == NOT_FOUND) return NOT_FOUND; - + if (fDocument.getChar(start) == openingPeer) depth++; else depth--; - + if (depth == 0) return start; } @@ -529,33 +590,40 @@ public class JavaHeuristicScanner implements Symbols { } /** - * 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. + * 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. * - *

                                                      Note that start must not point to the closing peer, but to the first - * character being searched.

                                                      + *

                                                      + * Note that start must not point to the closing peer, but to + * the first character being searched. + *

                                                      * - * @param start the start position - * @param openingPeer the opening peer character (e.g. '{') - * @param closingPeer the closing peer character (e.g. '}') + * @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 NOT_FOUND */ public int findOpeningPeer(int start, char openingPeer, char closingPeer) { Assert.isTrue(start < fDocument.getLength()); try { - int depth= 1; + int depth = 1; start += 1; while (true) { - start= scanBackward(start - 1, UNBOUND, new CharacterMatch(new char[] {openingPeer, closingPeer})); + start = scanBackward(start - 1, UNBOUND, new CharacterMatch( + new char[] { openingPeer, closingPeer })); if (start == NOT_FOUND) return NOT_FOUND; - + if (fDocument.getChar(start) == closingPeer) depth++; else depth--; - + if (depth == 0) return start; } @@ -566,84 +634,124 @@ public class JavaHeuristicScanner implements Symbols { } /** - * Computes the surrounding block around offset. The search is started at the - * beginning of offset, i.e. an opening brace at offset will not be - * part of the surrounding block, but a closing brace will. + * Computes the surrounding block around offset. The search + * is started at the beginning of offset, i.e. an opening + * brace at offset 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 null if none can be found + * @param offset + * the offset for which the surrounding block is computed + * @return a region describing the surrounding block, or null + * 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); + + 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 fDocument such that the position is >= position - * and < bound and Character.isWhitespace(fDocument.getChar(pos)) evaluates to false - * and the position is in the default partition. + * Finds the smallest position in fDocument such that the + * position is >= position and < bound + * and Character.isWhitespace(fDocument.getChar(pos)) + * evaluates to false and the position is in the default + * partition. * - * @param position the first character position in fDocument to be considered - * @param bound the first position in fDocument to not consider any more, with bound > position, or UNBOUND - * @return the smallest position of a non-whitespace character in [position, bound) that resides in a Java partition, or NOT_FOUND if none can be found + * @param position + * the first character position in fDocument to be + * considered + * @param bound + * the first position in fDocument to not consider + * any more, with bound > position, + * or UNBOUND + * @return the smallest position of a non-whitespace character in [position, + * bound) that resides in a Java partition, or + * NOT_FOUND if none can be found */ public int findNonWhitespaceForward(int position, int bound) { return scanForward(position, bound, fNonWSDefaultPart); } /** - * Finds the smallest position in fDocument such that the position is >= position - * and < bound and Character.isWhitespace(fDocument.getChar(pos)) evaluates to false. + * Finds the smallest position in fDocument such that the + * position is >= position and < bound + * and Character.isWhitespace(fDocument.getChar(pos)) + * evaluates to false. * - * @param position the first character position in fDocument to be considered - * @param bound the first position in fDocument to not consider any more, with bound > position, or UNBOUND - * @return the smallest position of a non-whitespace character in [position, bound), or NOT_FOUND if none can be found + * @param position + * the first character position in fDocument to be + * considered + * @param bound + * the first position in fDocument to not consider + * any more, with bound > position, + * or UNBOUND + * @return the smallest position of a non-whitespace character in [position, + * bound), or NOT_FOUND if none can + * be found */ public int findNonWhitespaceForwardInAnyPartition(int position, int bound) { return scanForward(position, bound, fNonWS); } /** - * Finds the highest position in fDocument such that the position is <= position - * and > bound and Character.isWhitespace(fDocument.getChar(pos)) evaluates to false - * and the position is in the default partition. + * Finds the highest position in fDocument such that the + * position is <= position and > bound + * and Character.isWhitespace(fDocument.getChar(pos)) + * evaluates to false and the position is in the default + * partition. * - * @param position the first character position in fDocument to be considered - * @param bound the first position in fDocument to not consider any more, with bound < position, or UNBOUND - * @return the highest position of a non-whitespace character in (bound, position] that resides in a Java partition, or NOT_FOUND if none can be found + * @param position + * the first character position in fDocument to be + * considered + * @param bound + * the first position in fDocument to not consider + * any more, with bound < position, + * or UNBOUND + * @return the highest position of a non-whitespace character in (bound, + * position] that resides in a Java partition, or + * NOT_FOUND if none can be found */ - public int findNonWhitespaceBackward(int position, int bound) { + public int findNonWhitespaceBackward(int position, int bound) { return scanBackward(position, bound, fNonWSDefaultPart); } /** - * Finds the lowest position p in fDocument such that start <= p < - * bound and condition.stop(fDocument.getChar(p), p) evaluates to true. + * Finds the lowest position p in fDocument + * such that start <= p < bound and + * condition.stop(fDocument.getChar(p), p) evaluates to + * true. * - * @param start the first character position in fDocument to be considered - * @param bound the first position in fDocument to not consider any more, with bound > start, or UNBOUND - * @param condition the StopCondition to check - * @return the lowest position in [start, bound) for which condition holds, or NOT_FOUND if none can be found + * @param start + * the first character position in fDocument to be + * considered + * @param bound + * the first position in fDocument to not consider + * any more, with bound > start, + * or UNBOUND + * @param condition + * the StopCondition to check + * @return the lowest position in [start, + * bound) for which condition holds, + * or NOT_FOUND if none can be found */ public int scanForward(int start, int bound, StopCondition condition) { Assert.isTrue(start >= 0); if (bound == UNBOUND) - bound= fDocument.getLength(); - + bound = fDocument.getLength(); + Assert.isTrue(bound <= fDocument.getLength()); - + try { - fPos= start; + fPos = start; while (fPos < bound) { - fChar= fDocument.getChar(fPos); + fChar = fDocument.getChar(fPos); if (condition.stop(fChar, fPos, true)) return fPos; @@ -653,57 +761,86 @@ public class JavaHeuristicScanner implements Symbols { } return NOT_FOUND; } - /** - * Finds the lowest position in fDocument such that the position is >= position - * and < bound and fDocument.getChar(position) == ch evaluates to true - * and the position is in the default partition. + * Finds the lowest position in fDocument such that the + * position is >= position and < bound + * and fDocument.getChar(position) == ch evaluates to + * true and the position is in the default partition. * - * @param position the first character position in fDocument to be considered - * @param bound the first position in fDocument to not consider any more, with bound > position, or UNBOUND - * @param ch the char to search for - * @return the lowest position of ch in (bound, position] that resides in a Java partition, or NOT_FOUND if none can be found + * @param position + * the first character position in fDocument to be + * considered + * @param bound + * the first position in fDocument to not consider + * any more, with bound > position, + * or UNBOUND + * @param ch + * the char to search for + * @return the lowest position of ch in (bound, + * position] that resides in a Java partition, or + * NOT_FOUND 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 fDocument such that the position is >= position - * and < bound and fDocument.getChar(position) == ch evaluates to true for at least one - * ch in chars and the position is in the default partition. + * Finds the lowest position in fDocument such that the + * position is >= position and < bound + * and fDocument.getChar(position) == ch evaluates to + * true for at least one ch in chars and the + * position is in the default partition. * - * @param position the first character position in fDocument to be considered - * @param bound the first position in fDocument to not consider any more, with bound > position, or UNBOUND - * @param chars an array of char to search for - * @return the lowest position of a non-whitespace character in [position, bound) that resides in a Java partition, or NOT_FOUND if none can be found + * @param position + * the first character position in fDocument to be + * considered + * @param bound + * the first position in fDocument to not consider + * any more, with bound > position, + * or UNBOUND + * @param chars + * an array of char to search for + * @return the lowest position of a non-whitespace character in [position, + * bound) that resides in a Java partition, or + * NOT_FOUND 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 p in fDocument such that bound < p <= start - * and condition.stop(fDocument.getChar(p), p) evaluates to true. + * Finds the highest position p in fDocument + * such that bound < p <= + * start and + * condition.stop(fDocument.getChar(p), p) evaluates to + * true. * - * @param start the first character position in fDocument to be considered - * @param bound the first position in fDocument to not consider any more, with bound < start, or UNBOUND - * @param condition the StopCondition to check - * @return the highest position in (bound, start for which condition holds, or NOT_FOUND if none can be found + * @param start + * the first character position in fDocument to be + * considered + * @param bound + * the first position in fDocument to not consider + * any more, with bound < start, + * or UNBOUND + * @param condition + * the StopCondition to check + * @return the highest position in (bound, + * start for which condition holds, or + * NOT_FOUND if none can be found */ public int scanBackward(int start, int bound, StopCondition condition) { if (bound == UNBOUND) - bound= -1; - + bound = -1; + Assert.isTrue(bound >= -1); - Assert.isTrue(start < fDocument.getLength() ); - + Assert.isTrue(start < fDocument.getLength()); + try { - fPos= start; + fPos = start; while (fPos > bound) { - - fChar= fDocument.getChar(fPos); + + fChar = fDocument.getChar(fPos); if (condition.stop(fChar, fPos, false)) return fPos; @@ -713,91 +850,123 @@ public class JavaHeuristicScanner implements Symbols { } return NOT_FOUND; } - + /** - * Finds the highest position in fDocument such that the position is <= position - * and > bound and fDocument.getChar(position) == ch evaluates to true for at least one - * ch in chars and the position is in the default partition. + * Finds the highest position in fDocument such that the + * position is <= position and > bound + * and fDocument.getChar(position) == ch evaluates to + * true for at least one ch in chars and the + * position is in the default partition. * - * @param position the first character position in fDocument to be considered - * @param bound the first position in fDocument to not consider any more, with bound < position, or UNBOUND - * @param ch the char to search for - * @return the highest position of one element in chars in (bound, position] that resides in a Java partition, or NOT_FOUND if none can be found + * @param position + * the first character position in fDocument to be + * considered + * @param bound + * the first position in fDocument to not consider + * any more, with bound < position, + * or UNBOUND + * @param ch + * the char to search for + * @return the highest position of one element in chars in (bound, + * position] that resides in a Java partition, or + * NOT_FOUND 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 fDocument such that the position is <= position - * and > bound and fDocument.getChar(position) == ch evaluates to true for at least one - * ch in chars and the position is in the default partition. + * Finds the highest position in fDocument such that the + * position is <= position and > bound + * and fDocument.getChar(position) == ch evaluates to + * true for at least one ch in chars and the + * position is in the default partition. * - * @param position the first character position in fDocument to be considered - * @param bound the first position in fDocument to not consider any more, with bound < position, or UNBOUND - * @param chars an array of char to search for - * @return the highest position of one element in chars in (bound, position] that resides in a Java partition, or NOT_FOUND if none can be found + * @param position + * the first character position in fDocument to be + * considered + * @param bound + * the first position in fDocument to not consider + * any more, with bound < position, + * or UNBOUND + * @param chars + * an array of char to search for + * @return the highest position of one element in chars in (bound, + * position] that resides in a Java partition, or + * NOT_FOUND if none can be found */ public int scanBackward(int position, int bound, char[] chars) { return scanBackward(position, bound, new CharacterMatch(chars)); } - + /** - * Checks whether position resides in a default (Java) partition of fDocument. + * Checks whether position resides in a default (Java) + * partition of fDocument. * - * @param position the position to be checked - * @return true if position is in the default partition of fDocument, false otherwise + * @param position + * the position to be checked + * @return true if position is in the default + * partition of fDocument, false + * otherwise */ public boolean isDefaultPartition(int position) { Assert.isTrue(position >= 0); Assert.isTrue(position <= fDocument.getLength()); - + try { - ITypedRegion region= TextUtilities.getPartition(fDocument, fPartitioning, position, false); + ITypedRegion region = TextUtilities.getPartition(fDocument, + fPartitioning, position, false); return region.getType().equals(fPartition); - + } catch (BadLocationException e) { } - + return false; } /** - * 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). + * 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). * *
                                                       	 * if (condition)
                                                      -	 *     doStuff();
                                                      +	 * 	doStuff();
                                                       	 * 
                                                      * - *

                                                      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

                                                      + *

                                                      + * 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 + *

                                                      * - * @param position the insert position of the new character - * @param bound the lowest position to consider - * @return true if the code is a conditional statement or loop without a block, false otherwise + * @param position + * the insert position of the new character + * @param bound + * the lowest position to consider + * @return true if the code is a conditional statement or + * loop without a block, false 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; - } + 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; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaIndenter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaIndenter.java index bf374ff..fa4715c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaIndenter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaIndenter.java @@ -21,14 +21,13 @@ import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; - /** * Uses the {@link net.sourceforge.phpdt.internal.ui.text.JavaHeuristicScanner}to * get the indentation level for a certain position in a document. * *

                                                      - * An instance holds some internal position in the document and is therefore - * not threadsafe. + * An instance holds some internal position in the document and is therefore not + * threadsafe. *

                                                      * * @since 3.0 @@ -37,48 +36,59 @@ public class JavaIndenter { /** The document being scanned. */ private IDocument fDocument; + /** The indentation accumulated by findPreviousIndenationUnit. */ 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 fPosition. */ 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. + * The scanner we will use to scan the document. It has to be installed on + * the same document as the one we get. */ private JavaHeuristicScanner fScanner; /** * 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 IDocument. + * @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 + * IDocument. */ public JavaIndenter(IDocument document, JavaHeuristicScanner scanner) { Assert.isNotNull(document); Assert.isNotNull(scanner); - fDocument= document; - fScanner= scanner; + fDocument = document; + fScanner = scanner; } /** * Computes the indentation at the reference point of position. * - * @param offset the offset in the document + * @param offset + * the offset in the document * @return a String which reflects the indentation at the line in which the - * reference position to offset resides, or null - * if it cannot be determined + * reference position to offset resides, or + * null if it cannot be determined */ public StringBuffer getReferenceIndentation(int offset) { return getReferenceIndentation(offset, false); @@ -87,19 +97,22 @@ public class JavaIndenter { /** * Computes the indentation at the reference point of position. * - * @param offset the offset in the document - * @param assumeOpeningBrace true if an opening brace should be assumed + * @param offset + * the offset in the document + * @param assumeOpeningBrace + * true if an opening brace should be assumed * @return a String which reflects the indentation at the line in which the - * reference position to offset resides, or null - * if it cannot be determined + * reference position to offset resides, or + * null if it cannot be determined */ - private StringBuffer getReferenceIndentation(int offset, boolean assumeOpeningBrace) { + private StringBuffer getReferenceIndentation(int offset, + boolean assumeOpeningBrace) { int unit; if (assumeOpeningBrace) - unit= findReferencePosition(offset, Symbols.TokenLBRACE); + unit = findReferencePosition(offset, Symbols.TokenLBRACE); else - unit= findReferencePosition(offset, peekChar(offset)); + unit = findReferencePosition(offset, peekChar(offset)); // if we were unable to find anything, return null if (unit == JavaHeuristicScanner.NOT_FOUND) @@ -112,7 +125,8 @@ public class JavaIndenter { /** * Computes the indentation at offset. * - * @param offset the offset in the document + * @param offset + * the offset in the document * @return a String which reflects the correct indentation for the line in * which offset resides, or null if it cannot be * determined @@ -124,22 +138,26 @@ public class JavaIndenter { /** * Computes the indentation at offset. * - * @param offset the offset in the document - * @param assumeOpeningBrace true if an opening brace should be assumed + * @param offset + * the offset in the document + * @param assumeOpeningBrace + * true if an opening brace should be assumed * @return a String which reflects the correct indentation for the line in * which offset resides, or null if it cannot be * determined */ - public StringBuffer computeIndentation(int offset, boolean assumeOpeningBrace) { + public StringBuffer computeIndentation(int offset, + boolean assumeOpeningBrace) { - StringBuffer indent= getReferenceIndentation(offset, assumeOpeningBrace); + StringBuffer indent = 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(); + IRegion line = fDocument.getLineInformationOfOffset(fAlign); + int lineOffset = line.getOffset(); return createIndent(lineOffset, fAlign); } catch (BadLocationException e) { return null; @@ -159,19 +177,21 @@ public class JavaIndenter { /** * Returns the indentation of the line at offset as a - * StringBuffer. If the offset is not valid, the empty string - * is returned. + * StringBuffer. If the offset is not valid, the empty + * string is returned. * - * @param offset the offset in the document + * @param offset + * the offset in the document * @return the indentation (leading whitespace) of the line in which - * offset is located + * offset is located */ private StringBuffer getLeadingWhitespace(int offset) { - StringBuffer indent= new StringBuffer(); + StringBuffer indent = new StringBuffer(); try { - IRegion line= fDocument.getLineInformationOfOffset(offset); - int lineOffset= line.getOffset(); - int nonWS= fScanner.findNonWhitespaceForwardInAnyPartition(lineOffset, lineOffset + line.getLength()); + 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) { @@ -182,11 +202,12 @@ public class JavaIndenter { /** * Reduces indentation in indent by one indentation unit. * - * @param indent the indentation to be modified + * @param indent + * the indentation to be modified */ private void unindent(StringBuffer indent) { - CharSequence oneIndent= createIndent(); - int i= indent.lastIndexOf(oneIndent.toString()); //$NON-NLS-1$ + CharSequence oneIndent = createIndent(); + int i = indent.lastIndexOf(oneIndent.toString()); //$NON-NLS-1$ if (i != -1) { indent.delete(i, i + oneIndent.length()); } @@ -198,30 +219,32 @@ public class JavaIndenter { * [start, indent), with every character replaced by a space except for * tabs, which are kept as such. * - *

                                                      Every run of the number of spaces that make up a tab are replaced - * by a tab character.

                                                      + *

                                                      + * Every run of the number of spaces that make up a tab are replaced by a + * tab character. + *

                                                      * * @return the indentation corresponding to the document content specified * by start and indent */ private StringBuffer createIndent(int start, int indent) { - final int tabLen= prefTabLength(); - StringBuffer ret= new StringBuffer(); + final int tabLen = prefTabLength(); + StringBuffer ret = new StringBuffer(); try { - int spaces= 0; + int spaces = 0; while (start < indent) { - char ch= fDocument.getChar(start); + char ch = fDocument.getChar(start); if (ch == '\t') { ret.append('\t'); - spaces= 0; - } else if (tabLen == -1){ + spaces = 0; + } else if (tabLen == -1) { ret.append(' '); } else { spaces++; if (spaces == tabLen) { ret.append('\t'); - spaces= 0; + spaces = 0; } } @@ -244,14 +267,15 @@ public class JavaIndenter { * Creates a string that represents the given number of indents (can be * spaces or tabs..) * - * @param indent the requested indentation level. + * @param indent + * the requested indentation level. * * @return the indentation specified by indent */ public StringBuffer createIndent(int indent) { - StringBuffer oneIndent= createIndent(); + StringBuffer oneIndent = createIndent(); - StringBuffer ret= new StringBuffer(); + StringBuffer ret = new StringBuffer(); while (indent-- > 0) ret.append(oneIndent); @@ -259,24 +283,30 @@ public class JavaIndenter { } /** - * Creates a string that represents one indent (can be - * spaces or tabs..) + * Creates a string that represents one indent (can be spaces or tabs..) * * @return one indentation */ private StringBuffer createIndent() { - // get a sensible default when running without the infrastructure for testing - StringBuffer oneIndent= new StringBuffer(); -// JavaCore plugin= JavaCore.getJavaCore(); + // get a sensible default when running without the infrastructure for + // testing + StringBuffer oneIndent = new StringBuffer(); + // JavaCore plugin= JavaCore.getJavaCore(); PHPeclipsePlugin plugin = PHPeclipsePlugin.getDefault(); if (plugin == null) { oneIndent.append('\t'); } else { - if (JavaCore.SPACE.equals(JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR))) { - int tabLen= Integer.parseInt(JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE)); - for (int i= 0; i < tabLen; i++) + if (JavaCore.SPACE + .equals(JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR))) { + int tabLen = Integer + .parseInt(JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE)); + for (int i = 0; i < tabLen; i++) oneIndent.append(' '); - } else if (JavaCore.TAB.equals(JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR))) + } else if (JavaCore.TAB + .equals(JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR))) oneIndent.append('\t'); else oneIndent.append('\t'); // default @@ -285,12 +315,14 @@ public class JavaIndenter { } /** - * Returns the reference position regarding to indentation for offset, - * or NOT_FOUND. This method calls - * {@link #findReferencePosition(int, int) findReferencePosition(offset, nextChar)} where - * nextChar is the next character after offset. + * Returns the reference position regarding to indentation for + * offset, or NOT_FOUND. This method calls + * {@link #findReferencePosition(int, int) findReferencePosition(offset, nextChar)} + * where nextChar is the next character after + * offset. * - * @param offset the offset for which the reference is computed + * @param offset + * the offset for which the reference is computed * @return the reference statement relative to which offset * should be indented, or {@link JavaHeuristicScanner#NOT_FOUND} */ @@ -302,15 +334,18 @@ public class JavaIndenter { * Peeks the next char in the document that comes after offset * on the same line as offset. * - * @param offset the offset into document - * @return the token symbol of the next element, or TokenEOF if there is none + * @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()); + IRegion line = fDocument.getLineInformationOfOffset(offset); + int lineOffset = line.getOffset(); + int next = fScanner.nextToken(offset, lineOffset + + line.getLength()); return next; } catch (BadLocationException e) { } @@ -319,95 +354,110 @@ public class JavaIndenter { } /** - * Returns the reference position regarding to indentation for position, - * or NOT_FOUND. + * Returns the reference position regarding to indentation for + * position, or NOT_FOUND. * - *

                                                      If peekNextChar is true, the next token after - * offset 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: + *

                                                      + * If peekNextChar is true, the next token + * after offset 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: *

                                                        - *
                                                      • switch labels are indented relative to the switch block
                                                      • - *
                                                      • opening curly braces are aligned correctly with the introducing code
                                                      • - *
                                                      • closing curly braces are aligned properly with the introducing code of - * the matching opening brace
                                                      • - *
                                                      • closing parenthesis' are aligned with their opening peer
                                                      • - *
                                                      • the else keyword is aligned with its if, anything - * else is aligned normally (i.e. with the base of any introducing statements).
                                                      • - *
                                                      • if there is no token on the same line after offset, the indentation - * is the same as for an else keyword
                                                      • + *
                                                      • switch labels are indented relative to the switch + * block
                                                      • + *
                                                      • opening curly braces are aligned correctly with the introducing code
                                                      • + *
                                                      • closing curly braces are aligned properly with the introducing code + * of the matching opening brace
                                                      • + *
                                                      • closing parenthesis' are aligned with their opening peer
                                                      • + *
                                                      • the else keyword is aligned with its if, + * anything else is aligned normally (i.e. with the base of any introducing + * statements).
                                                      • + *
                                                      • if there is no token on the same line after offset, + * the indentation is the same as for an else keyword
                                                      • *
                                                      * - * @param offset the offset for which the reference is computed - * @param nextToken the next token to assume in the document + * @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 offset * 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 unindenation characters already typed in, but after position + boolean danglingElse = false; + boolean unindent = false; + boolean indent = false; + boolean matchBrace = false; + boolean matchParen = false; + boolean matchCase = false; + + // account for unindenation 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); + 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.TokenEOF: - 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 && !prefIndentBracesForBlocks()) -// unindent= true; -// else if ((prevToken == Symbols.TokenCOLON || prevToken == Symbols.TokenEQUAL || prevToken == Symbols.TokenRBRACKET) && !prefIndentBracesForArrays()) -// unindent= true; -// else if (!bracelessBlockStart && prefIndentBracesForMethods()) -// indent= true; -// break; - if (bracelessBlockStart ) - unindent= true; - else if ((prevToken == Symbols.TokenCOLON || prevToken == Symbols.TokenEQUAL || prevToken == Symbols.TokenRBRACKET) ) - unindent= true; - else if (!bracelessBlockStart) - indent= true; - break; - case Symbols.TokenRBRACE: // closing braces get unindented - if (isFirstTokenOnLine) - matchBrace= true; - break; - case Symbols.TokenRPAREN: - if (isFirstTokenOnLine) - matchParen= true; - break; - } + case Symbols.TokenEOF: + 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 && !prefIndentBracesForBlocks()) + // unindent= true; + // else if ((prevToken == Symbols.TokenCOLON || prevToken == + // Symbols.TokenEQUAL || prevToken == Symbols.TokenRBRACKET) && + // !prefIndentBracesForArrays()) + // unindent= true; + // else if (!bracelessBlockStart && + // prefIndentBracesForMethods()) + // indent= true; + // break; + if (bracelessBlockStart) + unindent = true; + else if ((prevToken == Symbols.TokenCOLON + || prevToken == Symbols.TokenEQUAL || prevToken == Symbols.TokenRBRACKET)) + unindent = true; + else if (!bracelessBlockStart) + 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 { // assume an else could come if we are at the end of file - danglingElse= true; + danglingElse = true; } - int ref= findReferencePosition(offset, danglingElse, matchBrace, matchParen, matchCase); + int ref = findReferencePosition(offset, danglingElse, matchBrace, + matchParen, matchCase); if (unindent) fIndent--; if (indent) @@ -416,155 +466,177 @@ public class JavaIndenter { } /** - * Returns the reference position regarding to indentation for position, - * or NOT_FOUND.fIndent 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), fAlign will contain - * the absolute position of the alignment reference in fDocument, - * otherwise fAlign is set to JavaHeuristicScanner.NOT_FOUND. + * Returns the reference position regarding to indentation for + * position, or NOT_FOUND.fIndent + * 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), + * fAlign will contain the absolute position of the alignment + * reference in fDocument, otherwise fAlign + * is set to JavaHeuristicScanner.NOT_FOUND. * - * @param offset the offset for which the reference is computed - * @param danglingElse whether a dangling else should be assumed at position - * @param matchBrace whether the position of the matching brace should be + * @param offset + * the offset for which the reference is computed + * @param danglingElse + * whether a dangling else should be assumed at + * position + * @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 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) + * @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 position * 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; + 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 + // 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; -// } -// } + // 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 + // 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); + 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) + // 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(); -// } + // if (matchCase) { + // return matchCaseAlignment(); + // } nextToken(); switch (fToken) { - 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; - 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); + 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; + 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 0; - - case Symbols.TokenEQUAL: - // indent assignments - fIndent= prefAssignmentIndent(); + case Symbols.TokenLPAREN: + case Symbols.TokenLBRACE: + case Symbols.TokenLBRACKET: + return handleScopeIntroduction(offset + 1); + + case Symbols.TokenEOF: + // trap when hitting start of document + return 0; + + case Symbols.TokenEQUAL: + // indent assignments + fIndent = prefAssignmentIndent(); + return fPosition; + + case Symbols.TokenCOLON: + // TODO handle ternary deep indentation + fIndent = prefCaseBlockIndent(); + return fPosition; + + case Symbols.TokenQUESTIONMARK: + if (prefTernaryDeepAlign()) { + setFirstElementAlignment(fPosition, offset + 1); return fPosition; - - case Symbols.TokenCOLON: - // TODO handle ternary deep indentation - fIndent= prefCaseBlockIndent(); + } else { + fIndent = prefTernaryIndent(); return fPosition; + } - case Symbols.TokenQUESTIONMARK: - if (prefTernaryDeepAlign()) { - setFirstElementAlignment(fPosition, offset + 1); - return fPosition; - } else { - fIndent= prefTernaryIndent(); + // indentation for blockless introducers: + case Symbols.TokenDO: + case Symbols.TokenWHILE: + case Symbols.TokenELSE: + fIndent = prefSimpleIndent(); + return fPosition; + 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 = prefSimpleIndent(); return fPosition; } - - // indentation for blockless introducers: - case Symbols.TokenDO: - case Symbols.TokenWHILE: - case Symbols.TokenELSE: - fIndent= prefSimpleIndent(); - return fPosition; - 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= prefSimpleIndent(); - return fPosition; - } - fPosition= scope; - if (looksLikeMethodDecl()) { - return skipToStatementStart(danglingElse, false); - } + fPosition = scope; + if (looksLikeMethodDecl()) { + return skipToStatementStart(danglingElse, false); } - // restore - fPosition= offset; - fLine= line; - // else: fall through to default - - 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(); + } + // restore + fPosition = offset; + fLine = line; + // else: fall through to default + + 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(); } } @@ -572,9 +644,12 @@ public class JavaIndenter { /** * Skips to the start of a statement that ends at the current position. * - * @param danglingElse whether to indent aligned with the last if - * @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 + * @param danglingElse + * whether to indent aligned with the last if + * @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) { while (true) { @@ -582,95 +657,98 @@ public class JavaIndenter { if (isInBlock) { switch (fToken) { - // exit on all block introducers - case Symbols.TokenIF: - case Symbols.TokenELSE: - case Symbols.TokenSYNCHRONIZED: - case Symbols.TokenCOLON: - case Symbols.TokenSTATIC: - case Symbols.TokenCATCH: - case Symbols.TokenDO: - case Symbols.TokenWHILE: - case Symbols.TokenFINALLY: - case Symbols.TokenFOR: - case Symbols.TokenTRY: - return fPosition; - - case Symbols.TokenSWITCH: - fIndent= prefCaseIndent(); - return fPosition; + // exit on all block introducers + case Symbols.TokenIF: + case Symbols.TokenELSE: + case Symbols.TokenSYNCHRONIZED: + case Symbols.TokenCOLON: + case Symbols.TokenSTATIC: + case Symbols.TokenCATCH: + case Symbols.TokenDO: + case Symbols.TokenWHILE: + case Symbols.TokenFINALLY: + case Symbols.TokenFOR: + case Symbols.TokenTRY: + return fPosition; + + case Symbols.TokenSWITCH: + fIndent = 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: - return fPreviousPos; + // 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: + return fPreviousPos; - case Symbols.TokenCOLON: - int pos= fPreviousPos; - if (!isConditional()) - return pos; - break; + 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 - return pos; // it's not - do as with all the above + 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 + return pos; // it's not - do as with all the above // scopes: skip them - case Symbols.TokenRPAREN: - case Symbols.TokenRBRACKET: - pos= fPreviousPos; - if (skipScope()) - break; - else - return pos; + case Symbols.TokenRPAREN: + case Symbols.TokenRBRACKET: + pos = fPreviousPos; + if (skipScope()) + break; + else + return pos; - // IF / ELSE: align the position after the conditional block with the if + // 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 + 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.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; - } - default: - // keep searching + 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; + } + default: + // keep searching } @@ -678,94 +756,98 @@ public class JavaIndenter { } /** - * Returns true if the colon at the current position is part of a conditional - * (ternary) expression, false otherwise. + * 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 + * @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, otherwise return true - case Symbols.TokenIDENT: - continue; - case Symbols.TokenCASE: - return false; + // search for case, otherwise return true + case Symbols.TokenIDENT: + continue; + case Symbols.TokenCASE: + return false; - default: - return true; + default: + return true; } } } /** * Returns as a reference any previous switch labels (case - * or default) or the offset of the brace that scopes the switch - * statement. Sets fIndent to prefCaseIndent upon - * a match. - * + * or default) or the offset of the brace that scopes the + * switch statement. Sets fIndent to + * prefCaseIndent upon a match. + * * @return the reference offset for a switch 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= 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: -// skipScope(); -// break; -// -// default: -// // keep searching -// continue; -// -// } -// } -// } - + // 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= 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: + // 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: + * 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)}. + * 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. + * @return the reference position for a list item: either a previous list + * item that has its own indentation, or the list introduction + * start. */ private int skipToPreviousListItemOrListStart() { - int startLine= fLine; - int startPosition= fPosition; + int 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); + 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 } @@ -773,166 +855,179 @@ public class JavaIndenter { } switch (fToken) { - // scopes: skip them - case Symbols.TokenRPAREN: - case Symbols.TokenRBRACKET: - case Symbols.TokenRBRACE: - skipScope(); - break; + // scopes: skip them + case Symbols.TokenRPAREN: + case Symbols.TokenRBRACKET: + case Symbols.TokenRBRACE: + skipScope(); + break; - // scope introduction: special treat who special is - case Symbols.TokenLPAREN: - case Symbols.TokenLBRACE: - case Symbols.TokenLBRACKET: - return handleScopeIntroduction(startPosition + 1); + // scope introduction: special treat who special is + case Symbols.TokenLPAREN: + case Symbols.TokenLBRACE: + case Symbols.TokenLBRACKET: + return handleScopeIntroduction(startPosition + 1); - case Symbols.TokenSEMICOLON: + case Symbols.TokenSEMICOLON: + return fPosition; + case Symbols.TokenQUESTIONMARK: + if (prefTernaryDeepAlign()) { + setFirstElementAlignment(fPosition - 1, fPosition + 1); return fPosition; - case Symbols.TokenQUESTIONMARK: - if (prefTernaryDeepAlign()) { - setFirstElementAlignment(fPosition - 1, fPosition + 1); - return fPosition; - } else { - fIndent= prefTernaryIndent(); - return fPosition; - } - case Symbols.TokenEOF: - return 0; + } else { + fIndent = prefTernaryIndent(); + return fPosition; + } + case Symbols.TokenEOF: + return 0; } } } /** - * Skips a scope and positions the cursor (fPosition) on the - * token that opens the scope. Returns true if a matching peer - * could be found, false otherwise. The current token when calling - * must be one out of Symbols.TokenRPAREN, Symbols.TokenRBRACE, - * and Symbols.TokenRBRACKET. + * Skips a scope and positions the cursor (fPosition) on + * the token that opens the scope. Returns true if a matching + * peer could be found, false otherwise. The current token + * when calling must be one out of Symbols.TokenRPAREN, + * Symbols.TokenRBRACE, and + * Symbols.TokenRBRACKET. * - * @return true if a matching peer was found, false otherwise + * @return true if a matching peer was found, + * false 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); - default: - Assert.isTrue(false); - return false; + 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); + default: + Assert.isTrue(false); + return false; } } /** - * Handles the introduction of a new scope. The current token must be one out - * of Symbols.TokenLPAREN, Symbols.TokenLBRACE, - * and Symbols.TokenLBRACKET. Returns as the reference position - * either the token introducing the scope or - if available - the first - * java token after that. + * Handles the introduction of a new scope. The current token must be one + * out of Symbols.TokenLPAREN, + * Symbols.TokenLBRACE, and + * Symbols.TokenLBRACKET. Returns as the reference position + * either the token introducing the scope or - if available - the first java + * token after that. * - *

                                                      Depending on the type of scope introduction, the indentation will align - * (deep indenting) with the reference position (fAlign will be - * set to the reference position) or fIndent will be set to - * the number of indentation units. + *

                                                      + * Depending on the type of scope introduction, the indentation will align + * (deep indenting) with the reference position (fAlign will + * be set to the reference position) or fIndent will be set + * to the number of indentation units. *

                                                      * - * @param bound the bound for the search for the first token after the scope - * introduction. + * @param bound + * the bound for the search for the first token after the scope + * introduction. * @return */ private int handleScopeIntroduction(int bound) { switch (fToken) { - // scope introduction: special treat who special is - case Symbols.TokenLPAREN: - int pos= fPosition; // store + // scope introduction: special treat who special is + case Symbols.TokenLPAREN: + int pos = fPosition; // store - // special: method declaration deep indentation - if (looksLikeMethodDecl()) { - if (prefMethodDeclDeepIndent()) + // special: method declaration deep indentation + if (looksLikeMethodDecl()) { + if (prefMethodDeclDeepIndent()) + return setFirstElementAlignment(pos, bound); + else { + fIndent = prefMethodDeclIndent(); + return pos; + } + } else { + fPosition = pos; + if (looksLikeMethodCall()) { + if (prefMethodCallDeepIndent()) return setFirstElementAlignment(pos, bound); else { - fIndent= prefMethodDeclIndent(); + fIndent = prefMethodCallIndent(); return pos; } - } else { - fPosition= pos; - if (looksLikeMethodCall()) { - if (prefMethodCallDeepIndent()) - return setFirstElementAlignment(pos, bound); - else { - fIndent= prefMethodCallIndent(); - return pos; - } - } else if (prefParenthesisDeepIndent()) - return setFirstElementAlignment(pos, bound); - } + } else if (prefParenthesisDeepIndent()) + return setFirstElementAlignment(pos, bound); + } - // normal: return the parenthesis as reference - fIndent= prefParenthesisIndent(); - return pos; + // normal: return the parenthesis as reference + fIndent = prefParenthesisIndent(); + return pos; - case Symbols.TokenLBRACE: - pos= fPosition; // store + case Symbols.TokenLBRACE: + pos = fPosition; // store - // special: array initializer - if (looksLikeArrayInitializerIntro()) - if (prefArrayDeepIndent()) - return setFirstElementAlignment(pos, bound); - else - fIndent= prefArrayIndent(); + // special: array initializer + if (looksLikeArrayInitializerIntro()) + if (prefArrayDeepIndent()) + return setFirstElementAlignment(pos, bound); else - fIndent= prefBlockIndent(); + fIndent = prefArrayIndent(); + else + fIndent = 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 - fPosition= pos; // restore - return skipToStatementStart(true, true); // set to true to match the first if + // normal: skip to the statement start before the scope introducer + // opening braces are often on differently ending indents than e.g. + // a method definition + fPosition = pos; // restore + return skipToStatementStart(true, true); // set to true to match + // the first if - case Symbols.TokenLBRACKET: - pos= fPosition; // store + case Symbols.TokenLBRACKET: + pos = fPosition; // store - // special: method declaration deep indentation - if (prefArrayDimensionsDeepIndent()) { - return setFirstElementAlignment(pos, bound); - } + // special: method declaration deep indentation + if (prefArrayDimensionsDeepIndent()) { + return setFirstElementAlignment(pos, bound); + } - // normal: return the bracket as reference - fIndent= prefBracketIndent(); - return pos; // restore + // normal: return the bracket as reference + fIndent = prefBracketIndent(); + return pos; // restore - default: - Assert.isTrue(false); - return -1; // dummy + default: + Assert.isTrue(false); + return -1; // dummy } } /** - * Sets the deep indent offset (fAlign) to either the offset - * right after scopeIntroducerOffset or - if available - the - * first Java token after scopeIntroducerOffset, but before - * bound. + * Sets the deep indent offset (fAlign) to either the + * offset right after scopeIntroducerOffset or - if available - + * the first Java token after scopeIntroducerOffset, but + * before bound. * - * @param scopeIntroducerOffset the offset of the scope introducer - * @param bound the bound for the search for another element + * @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); + 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; + fAlign = firstPossible; return fAlign; } - /** * Returns true if the next token received after calling - * nextToken is either an equal sign or an array designator ('[]'). + * nextToken is either an equal sign or an array designator + * ('[]'). * - * @return true if the next elements look like the start of an array definition + * @return true if the next elements look like the start of + * an array definition */ private boolean looksLikeArrayInitializerIntro() { nextToken(); @@ -943,13 +1038,14 @@ public class JavaIndenter { } /** - * Skips over the next if keyword. The current token when calling - * this method must be an else keyword. Returns true - * if a matching if could be found, false otherwise. - * The cursor (fPosition) is set to the offset of the if - * token. + * Skips over the next if keyword. The current token when + * calling this method must be an else keyword. Returns + * true if a matching if could be found, + * false otherwise. The cursor (fPosition) + * is set to the offset of the if token. * - * @return true if a matching if token was found, false otherwise + * @return true if a matching if token was + * found, false otherwise */ private boolean skipNextIF() { Assert.isTrue(fToken == Symbols.TokenELSE); @@ -957,37 +1053,36 @@ public class JavaIndenter { while (true) { nextToken(); switch (fToken) { - // scopes: skip them - case Symbols.TokenRPAREN: - case Symbols.TokenRBRACKET: - case Symbols.TokenRBRACE: - skipScope(); - break; + // scopes: skip them + case Symbols.TokenRPAREN: + case Symbols.TokenRBRACKET: + case Symbols.TokenRBRACE: + skipScope(); + break; - case Symbols.TokenIF: - // found it, return - return true; - case Symbols.TokenELSE: - // recursively skip else-if blocks - skipNextIF(); - 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; - } + // 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 do can either be separated from the while by a - * block, or by a single statement, which limits our search distance. + * statement by its own, so we have to check whether there is a matching do. + * A do can either be separated from the while by a block, or + * by a single statement, which limits our search distance. * * @return true if the while currently in * fToken has a matching do. @@ -996,18 +1091,19 @@ public class JavaIndenter { Assert.isTrue(fToken == Symbols.TokenWHILE); nextToken(); switch (fToken) { - case Symbols.TokenRBRACE: - skipScope(); // and fall thru - case Symbols.TokenSEMICOLON: - skipToStatementStart(false, false); - return fToken == Symbols.TokenDO; + case Symbols.TokenRBRACE: + skipScope(); // and fall thru + 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 [] elements. + * but whitespace in between, this is only to be used for [] + * elements. * * @return true if a [] could be scanned, the * current token is left at the LBRACKET. @@ -1023,9 +1119,9 @@ public class JavaIndenter { } /** - * Reads the next token in backward direction from the heuristic scanner - * and sets the fields fToken, fPreviousPosition and fPosition - * accordingly. + * Reads the next token in backward direction from the heuristic scanner and + * sets the fields fToken, fPreviousPosition and + * fPosition accordingly. */ private void nextToken() { nextToken(fPosition); @@ -1033,17 +1129,19 @@ public class JavaIndenter { /** * Reads the next token in backward direction of start from - * the heuristic scanner and sets the fields fToken, fPreviousPosition - * and fPosition accordingly. + * the heuristic scanner and sets the fields + * fToken, fPreviousPosition and fPosition + * accordingly. */ private void nextToken(int start) { - fToken= fScanner.previousToken(start - 1, JavaHeuristicScanner.UNBOUND); - fPreviousPos= start; - fPosition= fScanner.getPosition() + 1; + fToken = fScanner + .previousToken(start - 1, JavaHeuristicScanner.UNBOUND); + fPreviousPos = start; + fPosition = fScanner.getPosition() + 1; try { - fLine= fDocument.getLineOfOffset(fPosition); + fLine = fDocument.getLineOfOffset(fPosition); } catch (BadLocationException e) { - fLine= -1; + fLine = -1; } } @@ -1051,9 +1149,9 @@ public class JavaIndenter { * Returns true if the current tokens look like a method * declaration header (i.e. only the return type and method name). The * heuristic calls nextToken and expects an identifier - * (method name) and a type declaration (an identifier with optional + * (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. + * does not recognize package visible constructors. * * @return true if the current position looks like a method * declaration header. @@ -1061,15 +1159,17 @@ public class JavaIndenter { 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 - hard to do without an AST... + * 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 - hard to do without an AST... */ nextToken(); if (fToken == Symbols.TokenIDENT) { // method name - do nextToken(); - while (skipBrackets()); // optional brackets for array valued return types + do + nextToken(); + while (skipBrackets()); // optional brackets for array valued return + // types return fToken == Symbols.TokenIDENT; // type name } @@ -1077,14 +1177,15 @@ public class JavaIndenter { } /** - * Returns true if the current tokens look like a method - * call header (i.e. an identifier as opposed to a keyword taking parenthesized + * Returns true if the current tokens look like a method call + * header (i.e. an identifier as opposed to a keyword taking parenthesized * parameters such as if). - *

                                                      The heuristic calls nextToken and expects an identifier + *

                                                      + * The heuristic calls nextToken and expects an identifier * (method name). * - * @return true if the current position looks like a method call - * header. + * @return true if the current position looks like a method + * call header. */ private boolean looksLikeMethodCall() { nextToken(); @@ -1092,15 +1193,15 @@ public class JavaIndenter { } /** - * Scans tokens for the matching opening peer. The internal cursor - * (fPosition) is set to the offset of the opening peer if found. + * Scans tokens for the matching opening peer. The internal cursor (fPosition) + * is set to the offset of the opening peer if found. * - * @return true if a matching token was found, false - * otherwise + * @return true if a matching token was found, + * false otherwise */ private boolean skipScope(int openToken, int closeToken) { - int depth= 1; + int depth = 1; while (true) { nextToken(); @@ -1112,7 +1213,7 @@ public class JavaIndenter { if (depth == 0) return true; } else if (fToken == Symbols.TokenEOF) { - return false; + return false; } } } @@ -1121,19 +1222,27 @@ public class JavaIndenter { private int prefTabLength() { int tabLen; -// JavaCore core= JavaCore.getJavaCore(); - PHPeclipsePlugin plugin= PHPeclipsePlugin.getDefault(); -// if (core != null && plugin != null) - if (plugin != null) - if (JavaCore.SPACE.equals(JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR))) - // if the formatter uses chars to mark indentation, then don't substitute any chars - tabLen= -1; // results in no tabs being substituted for space runs + // JavaCore core= JavaCore.getJavaCore(); + PHPeclipsePlugin plugin = PHPeclipsePlugin.getDefault(); + // if (core != null && plugin != null) + if (plugin != null) + if (JavaCore.SPACE + .equals(JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR))) + // if the formatter uses chars to mark indentation, then don't + // substitute any chars + tabLen = -1; // results in no tabs being substituted for + // space runs else - // if the formatter uses tabs to mark indentations, use the visual setting from the editor + // if the formatter uses tabs to mark indentations, use the + // visual setting from the editor // to get nicely aligned indentations - tabLen= plugin.getPreferenceStore().getInt(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH); + tabLen = plugin + .getPreferenceStore() + .getInt( + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH); else - tabLen= 4; // sensible default for testing + tabLen = 4; // sensible default for testing return tabLen; } @@ -1143,9 +1252,10 @@ public class JavaIndenter { } private int prefArrayIndent() { - Plugin plugin= JavaCore.getPlugin(); + Plugin plugin = JavaCore.getPlugin(); if (plugin != null) { - String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER); + String option = JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER); try { if (DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_BY_ONE) return 1; @@ -1158,9 +1268,10 @@ public class JavaIndenter { } private boolean prefArrayDeepIndent() { - Plugin plugin= JavaCore.getPlugin(); + Plugin plugin = JavaCore.getPlugin(); if (plugin != null) { - String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER); + String option = JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER); try { return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN; } catch (IllegalArgumentException e) { @@ -1172,9 +1283,10 @@ public class JavaIndenter { } private boolean prefTernaryDeepAlign() { - Plugin plugin= JavaCore.getPlugin(); + Plugin plugin = JavaCore.getPlugin(); if (plugin != null) { - String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION); + String option = JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION); try { return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN; } catch (IllegalArgumentException e) { @@ -1185,9 +1297,10 @@ public class JavaIndenter { } private int prefTernaryIndent() { - Plugin plugin= JavaCore.getPlugin(); + Plugin plugin = JavaCore.getPlugin(); if (plugin != null) { - String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION); + String option = JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION); try { if (DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_BY_ONE) return 1; @@ -1202,9 +1315,11 @@ public class JavaIndenter { } private int prefCaseIndent() { - Plugin plugin= JavaCore.getPlugin(); + Plugin plugin = JavaCore.getPlugin(); if (plugin != null) { - if (DefaultCodeFormatterConstants.TRUE.equals(JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH))) + if (DefaultCodeFormatterConstants.TRUE + .equals(JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH))) return prefBlockIndent(); else return 0; @@ -1221,9 +1336,11 @@ public class JavaIndenter { if (true) return prefBlockIndent(); - Plugin plugin= JavaCore.getPlugin(); + Plugin plugin = JavaCore.getPlugin(); if (plugin != null) { - if (DefaultCodeFormatterConstants.TRUE.equals(JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES))) + if (DefaultCodeFormatterConstants.TRUE + .equals(JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES))) return prefBlockIndent(); else return 0; @@ -1240,9 +1357,10 @@ public class JavaIndenter { } private boolean prefMethodDeclDeepIndent() { - Plugin plugin= JavaCore.getPlugin(); + Plugin plugin = JavaCore.getPlugin(); if (plugin != null) { - String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION); + String option = JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION); try { return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN; } catch (IllegalArgumentException e) { @@ -1254,9 +1372,10 @@ public class JavaIndenter { } private int prefMethodDeclIndent() { - Plugin plugin= JavaCore.getPlugin(); + Plugin plugin = JavaCore.getPlugin(); if (plugin != null) { - String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION); + String option = JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION); try { if (DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_BY_ONE) return 1; @@ -1270,9 +1389,10 @@ public class JavaIndenter { } private boolean prefMethodCallDeepIndent() { - Plugin plugin= JavaCore.getPlugin(); + Plugin plugin = JavaCore.getPlugin(); if (plugin != null) { - String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION); + String option = JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION); try { return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN; } catch (IllegalArgumentException e) { @@ -1283,9 +1403,10 @@ public class JavaIndenter { } private int prefMethodCallIndent() { - Plugin plugin= JavaCore.getPlugin(); + Plugin plugin = JavaCore.getPlugin(); if (plugin != null) { - String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION); + String option = JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION); try { if (DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_BY_ONE) return 1; @@ -1304,9 +1425,10 @@ public class JavaIndenter { if (true) // don't do parenthesis deep indentation return false; - Plugin plugin= JavaCore.getPlugin(); + Plugin plugin = JavaCore.getPlugin(); if (plugin != null) { - String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION); + String option = JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION); try { return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN; } catch (IllegalArgumentException e) { @@ -1326,39 +1448,46 @@ public class JavaIndenter { } private boolean prefIndentBracesForBlocks() { - Plugin plugin= JavaCore.getPlugin(); + Plugin plugin = JavaCore.getPlugin(); if (plugin != null) { - String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK); - return option.equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED); + String option = JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK); + return option + .equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED); } return false; // sensible default } private boolean prefIndentBracesForArrays() { - Plugin plugin= JavaCore.getPlugin(); + Plugin plugin = JavaCore.getPlugin(); if (plugin != null) { - String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER); - return option.equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED); + String option = JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER); + return option + .equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED); } return false; // sensible default } private boolean prefIndentBracesForMethods() { - Plugin plugin= JavaCore.getPlugin(); + Plugin plugin = JavaCore.getPlugin(); if (plugin != null) { - String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION); - return option.equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED); + String option = JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION); + return option + .equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED); } return false; // sensible default } private int prefContinuationIndent() { - Plugin plugin= JavaCore.getPlugin(); + Plugin plugin = JavaCore.getPlugin(); if (plugin != null) { - String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION); + String option = JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION); try { return Integer.parseInt(option); } catch (NumberFormatException e) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaOutlineInformationControl.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaOutlineInformationControl.java index 68db9b5..31cdf12 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaOutlineInformationControl.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaOutlineInformationControl.java @@ -64,51 +64,52 @@ import org.eclipse.swt.widgets.TreeItem; /** * @author dmegert - * + * * To change this generated comment edit the template variable "typecomment": - * Window>Preferences>Java>Templates. - * To enable and disable the creation of type comments go to - * Window>Preferences>Java>Code Generation. + * Window>Preferences>Java>Templates. To enable and disable the creation of type + * comments go to Window>Preferences>Java>Code Generation. */ -public class JavaOutlineInformationControl implements IInformationControl, IInformationControlExtension, IInformationControlExtension2 { - +public class JavaOutlineInformationControl implements IInformationControl, + IInformationControlExtension, IInformationControlExtension2 { /** - * The NamePatternFilter selects the elements which - * match the given string patterns. + * The NamePatternFilter selects the elements which match the given string + * patterns. *

                                                      - * The following characters have special meaning: - * ? => any character - * * => any string + * The following characters have special meaning: ? => any character * => + * any string *

                                                      - * + * * @since 2.0 */ private static class NamePatternFilter extends ViewerFilter { private String fPattern; + private StringMatcher fMatcher; + private ILabelProvider fLabelProvider; + private Viewer fViewer; private StringMatcher getMatcher() { return fMatcher; } - - /* (non-Javadoc) - * Method declared on ViewerFilter. + /* + * (non-Javadoc) Method declared on ViewerFilter. */ - public boolean select(Viewer viewer, Object parentElement, Object element) { + public boolean select(Viewer viewer, Object parentElement, + Object element) { if (fMatcher == null) return true; - ILabelProvider labelProvider= getLabelProvider(viewer); + ILabelProvider labelProvider = getLabelProvider(viewer); - String matchName= null; + String matchName = null; if (labelProvider != null) - matchName= ((ILabelProvider)labelProvider).getText(element); + matchName = ((ILabelProvider) labelProvider).getText(element); else if (element instanceof IJavaElement) - matchName= ((IJavaElement) element).getElementName(); + matchName = ((IJavaElement) element).getElementName(); if (matchName != null && fMatcher.match(matchName)) return true; @@ -120,13 +121,14 @@ public class JavaOutlineInformationControl implements IInformationControl, IInfo if (fViewer == viewer) return fLabelProvider; - fLabelProvider= null; - IBaseLabelProvider baseLabelProvider= null; + fLabelProvider = null; + IBaseLabelProvider baseLabelProvider = null; if (viewer instanceof StructuredViewer) - baseLabelProvider= ((StructuredViewer)viewer).getLabelProvider(); + baseLabelProvider = ((StructuredViewer) viewer) + .getLabelProvider(); if (baseLabelProvider instanceof ILabelProvider) - fLabelProvider= (ILabelProvider)baseLabelProvider; + fLabelProvider = (ILabelProvider) baseLabelProvider; return fLabelProvider; } @@ -135,11 +137,11 @@ public class JavaOutlineInformationControl implements IInformationControl, IInfo IJavaElement[] children; if (element instanceof IParent) { try { - children= ((IParent)element).getChildren(); + children = ((IParent) element).getChildren(); } catch (JavaModelException ex) { return false; } - for (int i= 0; i < children.length; i++) + for (int i = 0; i < children.length; i++) if (select(viewer, element, children[i])) return true; } @@ -149,23 +151,21 @@ public class JavaOutlineInformationControl implements IInformationControl, IInfo /** * Sets the patterns to filter out for the receiver. *

                                                      - * The following characters have special meaning: - * ? => any character - * * => any string + * The following characters have special meaning: ? => any character * => + * any string *

                                                      */ public void setPattern(String pattern) { - fPattern= pattern; + fPattern = pattern; if (fPattern == null) { - fMatcher= null; + fMatcher = null; return; } - boolean ignoreCase= pattern.toLowerCase().equals(pattern); - fMatcher= new StringMatcher(pattern, ignoreCase, false); + boolean ignoreCase = pattern.toLowerCase().equals(pattern); + fMatcher = new StringMatcher(pattern, ignoreCase, false); } } - private static class BorderFillLayout extends Layout { /** The border widths. */ @@ -177,7 +177,7 @@ public class JavaOutlineInformationControl implements IInformationControl, IInfo public BorderFillLayout(int borderSize) { if (borderSize < 0) throw new IllegalArgumentException(); - fBorderSize= borderSize; + fBorderSize = borderSize; } /** @@ -188,18 +188,21 @@ public class JavaOutlineInformationControl implements IInformationControl, IInfo } /* - * @see org.eclipse.swt.widgets.Layout#computeSize(org.eclipse.swt.widgets.Composite, int, int, boolean) + * @see org.eclipse.swt.widgets.Layout#computeSize(org.eclipse.swt.widgets.Composite, + * int, int, boolean) */ - protected Point computeSize(Composite composite, int wHint, int hHint, boolean flushCache) { + protected Point computeSize(Composite composite, int wHint, int hHint, + boolean flushCache) { - Control[] children= composite.getChildren(); - Point minSize= new Point(0, 0); + Control[] children = composite.getChildren(); + Point minSize = new Point(0, 0); if (children != null) { - for (int i= 0; i < children.length; i++) { - Point size= children[i].computeSize(wHint, hHint, flushCache); - minSize.x= Math.max(minSize.x, size.x); - minSize.y= Math.max(minSize.y, size.y); + for (int i = 0; i < children.length; i++) { + Point size = children[i].computeSize(wHint, hHint, + flushCache); + minSize.x = Math.max(minSize.x, size.x); + minSize.y = Math.max(minSize.y, size.y); } } @@ -208,125 +211,144 @@ public class JavaOutlineInformationControl implements IInformationControl, IInfo return minSize; } + /* - * @see org.eclipse.swt.widgets.Layout#layout(org.eclipse.swt.widgets.Composite, boolean) + * @see org.eclipse.swt.widgets.Layout#layout(org.eclipse.swt.widgets.Composite, + * boolean) */ protected void layout(Composite composite, boolean flushCache) { - Control[] children= composite.getChildren(); - Point minSize= new Point(composite.getClientArea().width, composite.getClientArea().height); + Control[] children = composite.getChildren(); + Point minSize = new Point(composite.getClientArea().width, + composite.getClientArea().height); if (children != null) { - for (int i= 0; i < children.length; i++) { - Control child= children[i]; - child.setSize(minSize.x - fBorderSize * 2, minSize.y - fBorderSize * 2); + for (int i = 0; i < children.length; i++) { + Control child = children[i]; + child.setSize(minSize.x - fBorderSize * 2, minSize.y + - fBorderSize * 2); child.setLocation(fBorderSize, fBorderSize); } } } } - /** Border thickness in pixels. */ - private static final int BORDER= 1; + private static final int BORDER = 1; + /** Right margin in pixels. */ - private static final int RIGHT_MARGIN= 3; + private static final int RIGHT_MARGIN = 3; /** The control's shell */ private Shell fShell; + /** The composite */ Composite fComposite; + /** The control's text widget */ private Text fFilterText; + /** The control's tree widget */ private TreeViewer fTreeViewer; + /** The control width constraint */ - private int fMaxWidth= -1; + private int fMaxWidth = -1; + /** The control height constraint */ - private int fMaxHeight= -1; + private int fMaxHeight = -1; private StringMatcher fStringMatcher; - /** - * Creates a tree information control with the given shell as parent. The given - * style is applied to the tree widget. - * - * @param parent the parent shell - * @param style the additional styles for the tree widget + * Creates a tree information control with the given shell as parent. The + * given style is applied to the tree widget. + * + * @param parent + * the parent shell + * @param style + * the additional styles for the tree widget */ public JavaOutlineInformationControl(Shell parent, int style) { this(parent, SWT.RESIZE, style); } /** - * Creates a tree information control with the given shell as parent. - * No additional styles are applied. - * - * @param parent the parent shell + * Creates a tree information control with the given shell as parent. No + * additional styles are applied. + * + * @param parent + * the parent shell */ public JavaOutlineInformationControl(Shell parent) { this(parent, SWT.NONE); } /** - * 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 + * 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 JavaOutlineInformationControl(Shell parent, int shellStyle, int treeStyle) { - fShell= new Shell(parent, shellStyle); - Display display= fShell.getDisplay(); + public JavaOutlineInformationControl(Shell parent, int shellStyle, + int treeStyle) { + fShell = new Shell(parent, shellStyle); + Display display = fShell.getDisplay(); fShell.setBackground(display.getSystemColor(SWT.COLOR_BLACK)); // Composite for filter text and tree - fComposite= new Composite(fShell,SWT.RESIZE); - GridLayout layout= new GridLayout(1, false); + fComposite = new Composite(fShell, SWT.RESIZE); + GridLayout layout = new GridLayout(1, false); fComposite.setLayout(layout); fComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - + createFilterText(fComposite); createTreeViewer(fComposite, treeStyle); - int border= ((shellStyle & SWT.NO_TRIM) == 0) ? 0 : BORDER; + int border = ((shellStyle & SWT.NO_TRIM) == 0) ? 0 : BORDER; fShell.setLayout(new BorderFillLayout(border)); - + setInfoSystemColor(); installFilter(); } private void createTreeViewer(Composite parent, int style) { - Tree tree= new Tree(parent, SWT.SINGLE | (style & ~SWT.MULTI)); - GridData data= new GridData(GridData.FILL_BOTH); + Tree tree = new Tree(parent, SWT.SINGLE | (style & ~SWT.MULTI)); + GridData data = new GridData(GridData.FILL_BOTH); tree.setLayoutData(data); - fTreeViewer= new TreeViewer(tree); + fTreeViewer = new TreeViewer(tree); // Hide import declartions but show the container -// fTreeViewer.addFilter(new ViewerFilter() { -// public boolean select(Viewer viewer, Object parentElement, Object element) { -// return !(element instanceof IImportDeclaration); -// } -// }); - - fTreeViewer.setContentProvider(new StandardJavaElementContentProvider(true, true)); + // fTreeViewer.addFilter(new ViewerFilter() { + // public boolean select(Viewer viewer, Object parentElement, Object + // element) { + // return !(element instanceof IImportDeclaration); + // } + // }); + + fTreeViewer.setContentProvider(new StandardJavaElementContentProvider( + true, true)); fTreeViewer.setSorter(new JavaElementSorter()); fTreeViewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS); - - AppearanceAwareLabelProvider lprovider= new AppearanceAwareLabelProvider( - AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.F_APP_TYPE_SIGNATURE, - AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS - ); - fTreeViewer.setLabelProvider(new DecoratingJavaLabelProvider(lprovider)); + + AppearanceAwareLabelProvider lprovider = new AppearanceAwareLabelProvider( + AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS + | JavaElementLabels.F_APP_TYPE_SIGNATURE, + AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS); + fTreeViewer + .setLabelProvider(new DecoratingJavaLabelProvider(lprovider)); fTreeViewer.getTree().addKeyListener(new KeyListener() { - public void keyPressed(KeyEvent e) { + public void keyPressed(KeyEvent e) { if (e.character == 0x1B) // ESC dispose(); } + public void keyReleased(KeyEvent e) { // do nothing } @@ -336,6 +358,7 @@ public class JavaOutlineInformationControl implements IInformationControl, IInfo public void widgetSelected(SelectionEvent e) { // do nothing } + public void widgetDefaultSelected(SelectionEvent e) { gotoSelectedElement(); } @@ -343,19 +366,20 @@ public class JavaOutlineInformationControl implements IInformationControl, IInfo } private Text createFilterText(Composite parent) { - fFilterText= new Text(parent, SWT.FLAT); + fFilterText = new Text(parent, SWT.FLAT); - GridData data= new GridData(); - GC gc= new GC(parent); + GridData data = new GridData(); + GC gc = new GC(parent); gc.setFont(parent.getFont()); - FontMetrics fontMetrics= gc.getFontMetrics(); + FontMetrics fontMetrics = gc.getFontMetrics(); gc.dispose(); - data.heightHint= org.eclipse.jface.dialogs.Dialog.convertHeightInCharsToPixels(fontMetrics, 1); - data.horizontalAlignment= GridData.FILL; - data.verticalAlignment= GridData.BEGINNING; + data.heightHint = org.eclipse.jface.dialogs.Dialog + .convertHeightInCharsToPixels(fontMetrics, 1); + data.horizontalAlignment = GridData.FILL; + data.verticalAlignment = GridData.BEGINNING; fFilterText.setLayoutData(data); - + fFilterText.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { if (e.keyCode == 0x0D) // return @@ -367,42 +391,44 @@ public class JavaOutlineInformationControl implements IInformationControl, IInfo if (e.character == 0x1B) // ESC dispose(); } + public void keyReleased(KeyEvent e) { // do nothing } }); // Horizonral separator line - Label separator= new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.LINE_DOT); + Label separator = new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL + | SWT.LINE_DOT); separator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); return fFilterText; } - + private void setInfoSystemColor() { - Display display= fShell.getDisplay(); + Display display = fShell.getDisplay(); setForegroundColor(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); setBackgroundColor(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); } private void installFilter() { - final NamePatternFilter viewerFilter= new NamePatternFilter(); + final NamePatternFilter viewerFilter = new NamePatternFilter(); fTreeViewer.addFilter(viewerFilter); fFilterText.setText(""); //$NON-NLS-1$ fFilterText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { - String pattern= fFilterText.getText(); + String pattern = fFilterText.getText(); if (pattern != null) { - int length= pattern.length(); + int length = pattern.length(); if (length == 0) - pattern= null; - else if (pattern.charAt(length -1 ) != '*') - pattern= pattern + '*'; + pattern = null; + else if (pattern.charAt(length - 1) != '*') + pattern = pattern + '*'; } else - pattern= null; + pattern = null; viewerFilter.setPattern(pattern); - fStringMatcher= viewerFilter.getMatcher(); + fStringMatcher = viewerFilter.getMatcher(); fTreeViewer.getControl().setRedraw(false); fTreeViewer.refresh(); fTreeViewer.expandAll(); @@ -413,7 +439,8 @@ public class JavaOutlineInformationControl implements IInformationControl, IInfo } private void gotoSelectedElement() { - Object selectedElement= ((IStructuredSelection)fTreeViewer.getSelection()).getFirstElement(); + Object selectedElement = ((IStructuredSelection) fTreeViewer + .getSelection()).getFirstElement(); if (selectedElement != null) { try { dispose(); @@ -425,12 +452,12 @@ public class JavaOutlineInformationControl implements IInformationControl, IInfo } /** - * Selects the first element in the tree which - * matches the current filter pattern. + * Selects the first element in the tree which matches the current filter + * pattern. */ private void selectFirstMatch() { - Tree tree= fTreeViewer.getTree(); - Object element= findElement(tree.getItems()); + Tree tree = fTreeViewer.getTree(); + Object element = findElement(tree.getItems()); if (element != null) fTreeViewer.setSelection(new StructuredSelection(element), true); else @@ -438,19 +465,20 @@ public class JavaOutlineInformationControl implements IInformationControl, IInfo } private IJavaElement findElement(TreeItem[] items) { - ILabelProvider labelProvider= (ILabelProvider)fTreeViewer.getLabelProvider(); - for (int i= 0; i < items.length; i++) { - IJavaElement element= (IJavaElement)items[i].getData(); + ILabelProvider labelProvider = (ILabelProvider) fTreeViewer + .getLabelProvider(); + for (int i = 0; i < items.length; i++) { + IJavaElement element = (IJavaElement) items[i].getData(); if (fStringMatcher == null) return element; - + if (element != null) { - String label= labelProvider.getText(element); + String label = labelProvider.getText(element); if (fStringMatcher.match(label)) return element; } - element= findElement(items[i].getItems()); + element = findElement(items[i].getItems()); if (element != null) return element; } @@ -463,7 +491,7 @@ public class JavaOutlineInformationControl implements IInformationControl, IInfo public void setInformation(String information) { // this method is ignored, see IInformationControlExtension2 } - + /* * @see IInformationControlExtension2#setInput(Object) */ @@ -473,13 +501,14 @@ public class JavaOutlineInformationControl implements IInformationControl, IInfo setInput(null); return; } - IJavaElement je= (IJavaElement)information; - IJavaElement sel= null; - ICompilationUnit cu= (ICompilationUnit)je.getAncestor(IJavaElement.COMPILATION_UNIT); + IJavaElement je = (IJavaElement) information; + IJavaElement sel = null; + ICompilationUnit cu = (ICompilationUnit) je + .getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) - sel= cu; + sel = cu; else - sel= je.getAncestor(IJavaElement.CLASS_FILE); + sel = je.getAncestor(IJavaElement.CLASS_FILE); fTreeViewer.setInput(sel); fTreeViewer.setSelection(new StructuredSelection(information)); } @@ -488,7 +517,7 @@ public class JavaOutlineInformationControl implements IInformationControl, IInfo * @see IInformationControl#setVisible(boolean) */ public void setVisible(boolean visible) { - fShell.setVisible(visible); + fShell.setVisible(visible); } /* @@ -498,29 +527,30 @@ public class JavaOutlineInformationControl implements IInformationControl, IInfo if (fShell != null) { if (!fShell.isDisposed()) fShell.dispose(); - fShell= null; - fTreeViewer= null; - fComposite= null; - fFilterText= null; + fShell = null; + fTreeViewer = null; + fComposite = null; + fFilterText = null; } } - /* + /* * @see org.eclipse.jface.text.IInformationControlExtension#hasContents() */ public boolean hasContents() { return fTreeViewer != null && fTreeViewer.getInput() != null; } - /* - * @see org.eclipse.jface.text.IInformationControl#setSizeConstraints(int, int) + /* + * @see org.eclipse.jface.text.IInformationControl#setSizeConstraints(int, + * int) */ public void setSizeConstraints(int maxWidth, int maxHeight) { - fMaxWidth= maxWidth; - fMaxHeight= maxHeight; + fMaxWidth = maxWidth; + fMaxHeight = maxHeight; } - /* + /* * @see org.eclipse.jface.text.IInformationControl#computeSizeHint() */ public Point computeSizeHint() { @@ -531,11 +561,11 @@ public class JavaOutlineInformationControl implements IInformationControl, IInfo * @see IInformationControl#setLocation(Point) */ public void setLocation(Point location) { - Rectangle trim= fShell.computeTrim(0, 0, 0, 0); - Point textLocation= fComposite.getLocation(); - location.x += trim.x - textLocation.x; - location.y += trim.y - textLocation.y; - fShell.setLocation(location); + Rectangle trim = fShell.computeTrim(0, 0, 0, 0); + Point textLocation = fComposite.getLocation(); + location.x += trim.x - textLocation.x; + location.y += trim.y - textLocation.y; + fShell.setLocation(location); } /* @@ -581,7 +611,8 @@ public class JavaOutlineInformationControl implements IInformationControl, IInfo * @see IInformationControl#isFocusControl() */ public boolean isFocusControl() { - return fTreeViewer.getControl().isFocusControl() || fFilterText.isFocusControl(); + return fTreeViewer.getControl().isFocusControl() + || fFilterText.isFocusControl(); } /* diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaPresentationReconciler.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaPresentationReconciler.java index 67b0c5e..0b608f9 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaPresentationReconciler.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaPresentationReconciler.java @@ -16,29 +16,31 @@ 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. * * @since 3.0 */ 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. + * Constructs a "repair description" for the given damage and returns this + * description as a text presentation. *

                                                      * NOTE: Should not be used if this reconciler is installed on a viewer. *

                                                      - * - * @param damage the damage to be repaired - * @param document the document whose presentation must be repaired + * + * @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) { + public TextPresentation createRepairDescription(IRegion damage, + IDocument document) { if (document != fLastDocument) { setDocumentToDamagers(document); setDocumentToRepairers(document); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaReconciler.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaReconciler.java index 8dfb26f..11bf1c3 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaReconciler.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaReconciler.java @@ -11,7 +11,6 @@ package net.sourceforge.phpdt.internal.ui.text; - import net.sourceforge.phpdt.core.ElementChangedEvent; import net.sourceforge.phpdt.core.IElementChangedListener; import net.sourceforge.phpdt.core.JavaCore; @@ -41,17 +40,16 @@ import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.texteditor.ITextEditor; - /** * 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) */ @@ -86,26 +84,27 @@ public class JavaReconciler extends MonoReconciler { 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) { - fControl= 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() && hasJavaModelChanged()) + if (!fControl.isDisposed() && fControl.isVisible() + && hasJavaModelChanged()) JavaReconciler.this.forceReconciling(); } - + /* * @see org.eclipse.swt.events.ShellListener#shellDeactivated(org.eclipse.swt.events.ShellEvent) */ @@ -113,7 +112,7 @@ public class JavaReconciler extends MonoReconciler { setJavaModelChanged(false); } } - + /** * Internal Java element changed listener * @@ -127,112 +126,128 @@ public class JavaReconciler extends MonoReconciler { setJavaModelChanged(true); } } - + /** * Internal resource change listener. * * @since 3.0 */ class ResourceChangeListener implements IResourceChangeListener { - + private IResource getResource() { - IEditorInput input= fTextEditor.getEditorInput(); + IEditorInput input = fTextEditor.getEditorInput(); if (input instanceof IFileEditorInput) { - IFileEditorInput fileInput= (IFileEditorInput) input; + 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(); + IResourceDelta delta = e.getDelta(); + IResource resource = getResource(); if (delta != null && resource != null) { - IResourceDelta child= delta.findMember(resource.getFullPath()); + IResourceDelta child = delta.findMember(resource.getFullPath()); if (child != null) { - IMarkerDelta[] deltas= child.getMarkerDeltas(); + IMarkerDelta[] deltas = child.getMarkerDeltas(); if (deltas.length > 0) forceReconciling(); } } } } - - + /** 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. - * TODO remove once we have ensured that there is only one reconciler per editor. + * TODO remove once we have ensured that there is only one reconciler per + * editor. */ private Object fMutex; + /** * The Java element changed listener. + * * @since 3.0 */ private IElementChangedListener fJavaElementChangedListener; + /** * Tells whether the Java model sent out a changed event. + * * @since 3.0 */ - private volatile boolean fHasJavaModelChanged= true; + private volatile boolean fHasJavaModelChanged = true; + /** * The resource change listener. + * * @since 3.0 */ private IResourceChangeListener fResourceChangeListener; - private boolean fIninitalProcessDone= false; - + + private boolean fIninitalProcessDone = false; + /** * Creates a new reconciler. */ - public JavaReconciler(ITextEditor editor, JavaCompositeReconcilingStrategy strategy, boolean isIncremental) { + public JavaReconciler(ITextEditor editor, + JavaCompositeReconcilingStrategy strategy, boolean isIncremental) { super(strategy, isIncremental); - fTextEditor= editor; - + 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 + // 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, + // 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 + // 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. + // TODO remove once we have ensured that there is only one reconciler + // per editor. if (editor instanceof PHPUnitEditor) - fMutex= ((PHPUnitEditor) editor).getReconcilerLock(); + fMutex = ((PHPUnitEditor) editor).getReconcilerLock(); else - fMutex= new Object(); // Null Object + 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(); + + fPartListener = new PartListener(); + IWorkbenchPartSite site = fTextEditor.getSite(); + IWorkbenchWindow window = site.getWorkbenchWindow(); window.getPartService().addPartListener(fPartListener); - - fActivationListener= new ActivationListener(textViewer.getTextWidget()); - Shell shell= window.getShell(); + + fActivationListener = new ActivationListener(textViewer.getTextWidget()); + Shell shell = window.getShell(); shell.addShellListener(fActivationListener); - - fJavaElementChangedListener= new ElementChangedListener(); + + fJavaElementChangedListener = new ElementChangedListener(); JavaCore.addElementChangedListener(fJavaElementChangedListener); - - fResourceChangeListener= new ResourceChangeListener(); - IWorkspace workspace= PHPeclipsePlugin.getWorkspace(); + + fResourceChangeListener = new ResourceChangeListener(); + IWorkspace workspace = PHPeclipsePlugin.getWorkspace(); workspace.addResourceChangeListener(fResourceChangeListener); } @@ -240,78 +255,80 @@ public class JavaReconciler extends MonoReconciler { * @see org.eclipse.jface.text.reconciler.IReconciler#uninstall() */ public void uninstall() { - - IWorkbenchPartSite site= fTextEditor.getSite(); - IWorkbenchWindow window= site.getWorkbenchWindow(); + + IWorkbenchPartSite site = fTextEditor.getSite(); + IWorkbenchWindow window = site.getWorkbenchWindow(); window.getPartService().removePartListener(fPartListener); - fPartListener= null; - - Shell shell= window.getShell(); + fPartListener = null; + + Shell shell = window.getShell(); if (shell != null && !shell.isDisposed()) shell.removeShellListener(fActivationListener); - fActivationListener= null; - + fActivationListener = null; + JavaCore.removeElementChangedListener(fJavaElementChangedListener); - fJavaElementChangedListener= null; - - IWorkspace workspace= PHPeclipsePlugin.getWorkspace(); + fJavaElementChangedListener = null; + + IWorkspace workspace = PHPeclipsePlugin.getWorkspace(); workspace.removeResourceChangeListener(fResourceChangeListener); - fResourceChangeListener= null; - + fResourceChangeListener = 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); + JavaCompositeReconcilingStrategy strategy = (JavaCompositeReconcilingStrategy) getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE); strategy.notifyListeners(false); } - + /* * @see org.eclipse.jface.text.reconciler.AbstractReconciler#aboutToReconcile() * @since 3.0 */ protected void aboutToBeReconciled() { - JavaCompositeReconcilingStrategy strategy= (JavaCompositeReconcilingStrategy) getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE); + 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); + JavaCompositeReconcilingStrategy strategy = (JavaCompositeReconcilingStrategy) getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE); strategy.notifyListeners(true); } - + /* * @see org.eclipse.jface.text.reconciler.MonoReconciler#initialProcess() */ protected void initialProcess() { - // TODO remove once we have ensured that there is only one reconciler per editor. + // TODO remove once we have ensured that there is only one reconciler + // per editor. synchronized (fMutex) { super.initialProcess(); } - fIninitalProcessDone= true; + fIninitalProcessDone = true; } - + /* * @see org.eclipse.jface.text.reconciler.MonoReconciler#process(org.eclipse.jface.text.reconciler.DirtyRegion) */ protected void process(DirtyRegion dirtyRegion) { - // TODO remove once we have ensured that there is only one reconciler per editor. - synchronized (fMutex) { + // TODO remove once we have ensured that there is only one reconciler + // per editor. + synchronized (fMutex) { super.process(dirtyRegion); } } - + /** * Tells whether the Java Model has changed or not. * @@ -321,121 +338,125 @@ public class JavaReconciler extends MonoReconciler { private synchronized boolean hasJavaModelChanged() { return fHasJavaModelChanged; } - + /** * Sets whether the Java Model has changed or not. * - * @param state true iff the java model has changed + * @param state + * true iff the java model has changed * @since 3.0 */ private synchronized void setJavaModelChanged(boolean state) { - fHasJavaModelChanged= state; + fHasJavaModelChanged = state; } } -///** +// /** // * A reconciler that is also activated on editor activation. // */ -//public class JavaReconciler extends MonoReconciler { +// public class JavaReconciler extends MonoReconciler { // -// /** -// * Internal part listener for activating the reconciler. -// */ -// class PartListener implements IPartListener { +// /** +// * Internal part listener for activating the reconciler. +// */ +// class PartListener implements IPartListener { // -// /* -// * @see IPartListener#partActivated(IWorkbenchPart) -// */ -// public void partActivated(IWorkbenchPart part) { -// if (part == fTextEditor) -// JavaReconciler.this.forceReconciling(); -// } +// /* +// * @see IPartListener#partActivated(IWorkbenchPart) +// */ +// public void partActivated(IWorkbenchPart part) { +// if (part == fTextEditor) +// JavaReconciler.this.forceReconciling(); +// } // -// /* -// * @see IPartListener#partBroughtToTop(IWorkbenchPart) -// */ -// public void partBroughtToTop(IWorkbenchPart part) { -// } +// /* +// * @see IPartListener#partBroughtToTop(IWorkbenchPart) +// */ +// public void partBroughtToTop(IWorkbenchPart part) { +// } // -// /* -// * @see IPartListener#partClosed(IWorkbenchPart) -// */ -// public void partClosed(IWorkbenchPart part) { -// } +// /* +// * @see IPartListener#partClosed(IWorkbenchPart) +// */ +// public void partClosed(IWorkbenchPart part) { +// } // -// /* -// * @see IPartListener#partDeactivated(IWorkbenchPart) -// */ -// public void partDeactivated(IWorkbenchPart part) { -// } +// /* +// * @see IPartListener#partDeactivated(IWorkbenchPart) +// */ +// public void partDeactivated(IWorkbenchPart part) { +// } // -// /* -// * @see IPartListener#partOpened(IWorkbenchPart) -// */ -// public void partOpened(IWorkbenchPart part) { -// } -// }; +// /* +// * @see IPartListener#partOpened(IWorkbenchPart) +// */ +// public void partOpened(IWorkbenchPart part) { +// } +// }; // // -// /** The reconciler's editor */ -// private ITextEditor fTextEditor; -// /** The part listener */ -// private IPartListener fPartListener; +// /** The reconciler's editor */ +// private ITextEditor fTextEditor; +// /** The part listener */ +// private IPartListener fPartListener; // // -// /** -// * Creates a new reconciler. -// */ -// public JavaReconciler(ITextEditor editor, IReconcilingStrategy strategy, boolean isIncremental) { -// super(strategy, isIncremental); -// fTextEditor= editor; -// } +// /** +// * Creates a new reconciler. +// */ +// public JavaReconciler(ITextEditor editor, IReconcilingStrategy strategy, +// boolean isIncremental) { +// super(strategy, isIncremental); +// fTextEditor= editor; +// } // -// /* -// * @see IReconciler#install(ITextViewer) -// */ -// public void install(ITextViewer textViewer) { -// super.install(textViewer); +// /* +// * @see IReconciler#install(ITextViewer) +// */ +// public void install(ITextViewer textViewer) { +// super.install(textViewer); // -// fPartListener= new PartListener(); -// IWorkbenchPartSite site= fTextEditor.getSite(); -// IWorkbenchWindow window= site.getWorkbenchWindow(); -// window.getPartService().addPartListener(fPartListener); -// } +// fPartListener= new PartListener(); +// IWorkbenchPartSite site= fTextEditor.getSite(); +// IWorkbenchWindow window= site.getWorkbenchWindow(); +// window.getPartService().addPartListener(fPartListener); +// } // -// /* -// * @see IReconciler#uninstall() -// */ -// public void uninstall() { +// /* +// * @see IReconciler#uninstall() +// */ +// public void uninstall() { // -// IWorkbenchPartSite site= fTextEditor.getSite(); -// IWorkbenchWindow window= site.getWorkbenchWindow(); -// window.getPartService().removePartListener(fPartListener); -// fPartListener= null; +// IWorkbenchPartSite site= fTextEditor.getSite(); +// IWorkbenchWindow window= site.getWorkbenchWindow(); +// window.getPartService().removePartListener(fPartListener); +// fPartListener= null; // -// super.uninstall(); -// } +// super.uninstall(); +// } // -// /* -// * @see AbstractReconciler#forceReconciling() -// */ -// protected void forceReconciling() { -// super.forceReconciling(); -// IReconcilingStrategy strategy= getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE); -// if (strategy instanceof JavaReconcilingStrategy) { -// JavaReconcilingStrategy java= (JavaReconcilingStrategy) strategy; -// java.notifyParticipants(false); -// } -// } +// /* +// * @see AbstractReconciler#forceReconciling() +// */ +// protected void forceReconciling() { +// super.forceReconciling(); +// IReconcilingStrategy strategy= +// getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE); +// if (strategy instanceof JavaReconcilingStrategy) { +// JavaReconcilingStrategy java= (JavaReconcilingStrategy) strategy; +// java.notifyParticipants(false); +// } +// } // -// /* -// * @see AbstractReconciler#reconcilerReset() -// */ -// protected void reconcilerReset() { -// super.reconcilerReset(); -// IReconcilingStrategy strategy= getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE); -// if (strategy instanceof JavaReconcilingStrategy) { -// JavaReconcilingStrategy java= (JavaReconcilingStrategy) strategy; -// java.notifyParticipants(true); -// } -// } -//} +// /* +// * @see AbstractReconciler#reconcilerReset() +// */ +// protected void reconcilerReset() { +// super.reconcilerReset(); +// IReconcilingStrategy strategy= +// getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE); +// if (strategy instanceof JavaReconcilingStrategy) { +// JavaReconcilingStrategy java= (JavaReconcilingStrategy) strategy; +// java.notifyParticipants(true); +// } +// } +// } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaWordIterator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaWordIterator.java index cca37ca..1c55ba9 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaWordIterator.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaWordIterator.java @@ -15,28 +15,28 @@ import java.text.CharacterIterator; import org.eclipse.jface.text.Assert; - /** - * Breaks java text into word starts, also stops at line start and end. No + * Breaks java text into word starts, also stops at line start and end. No * direction dependency. - * + * * @since 3.0 */ 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(); + fIterator = new JavaBreakIterator(); first(); } @@ -44,7 +44,7 @@ public class JavaWordIterator extends BreakIterator { * @see java.text.BreakIterator#first() */ public int first() { - fIndex= fIterator.first(); + fIndex = fIterator.first(); return fIndex; } @@ -52,7 +52,7 @@ public class JavaWordIterator extends BreakIterator { * @see java.text.BreakIterator#last() */ public int last() { - fIndex= fIterator.last(); + fIndex = fIterator.last(); return fIndex; } @@ -60,9 +60,9 @@ public class JavaWordIterator extends BreakIterator { * @see java.text.BreakIterator#next(int) */ public int next(int n) { - int next= 0; + int next = 0; while (--n > 0 && next != DONE) { - next= next(); + next = next(); } return next; } @@ -71,7 +71,7 @@ public class JavaWordIterator extends BreakIterator { * @see java.text.BreakIterator#next() */ public int next() { - fIndex= following(fIndex); + fIndex = following(fIndex); return fIndex; } @@ -79,18 +79,17 @@ public class JavaWordIterator extends BreakIterator { * @see java.text.BreakIterator#previous() */ public int previous() { - fIndex= preceding(fIndex); + fIndex = preceding(fIndex); return fIndex; } - - + /* * @see java.text.BreakIterator#preceding(int) */ public int preceding(int offset) { - int first= fIterator.preceding(offset); + int first = fIterator.preceding(offset); if (isWhitespace(first, offset)) { - int second= fIterator.preceding(first); + int second = fIterator.preceding(first); if (second != DONE && !isDelimiter(second, first)) return second; } @@ -101,82 +100,87 @@ public class JavaWordIterator extends BreakIterator { * @see java.text.BreakIterator#following(int) */ public int following(int offset) { - int first= fIterator.following(offset); + int first = fIterator.following(offset); if (eatFollowingWhitespace(offset, first)) { - int second= fIterator.following(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 true if the given sequence into the underlying text - * represents a delimiter, false otherwise. + * Returns true if the given sequence into the underlying + * text represents a delimiter, false otherwise. * - * @param offset the offset - * @param exclusiveEnd the end offset + * @param offset + * the offset + * @param exclusiveEnd + * the end offset * @return true 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; - + + CharSequence seq = fIterator.fText; + while (offset < exclusiveEnd) { - char ch= seq.charAt(offset); + char ch = seq.charAt(offset); if (ch != '\n' && ch != '\r') return false; offset++; } - + return true; } /** - * Returns true if the given sequence into the underlying text - * represents whitespace, but not a delimiter, false otherwise. + * Returns true if the given sequence into the underlying + * text represents whitespace, but not a delimiter, false + * otherwise. * - * @param offset the offset - * @param exclusiveEnd the end offset + * @param offset + * the offset + * @param exclusiveEnd + * the end offset * @return true 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; - + + CharSequence seq = fIterator.fText; + while (offset < exclusiveEnd) { - char ch= seq.charAt(offset); + char ch = seq.charAt(offset); if (!Character.isWhitespace(ch)) return false; if (ch == '\n' || ch == '\r') return false; offset++; } - + return true; } @@ -193,10 +197,12 @@ public class JavaWordIterator extends BreakIterator { public CharacterIterator getText() { return fIterator.getText(); } - + /** * Sets the text as CharSequence. - * @param newText the new text + * + * @param newText + * the new text */ public void setText(CharSequence newText) { fIterator.setText(newText); @@ -210,7 +216,7 @@ public class JavaWordIterator extends BreakIterator { fIterator.setText(newText); first(); } - + /* * @see java.text.BreakIterator#setText(java.lang.String) */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/LineBreakingReader.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/LineBreakingReader.java index 4b27afe..c69c0c8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/LineBreakingReader.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/LineBreakingReader.java @@ -4,7 +4,7 @@ package net.sourceforge.phpdt.internal.ui.text; * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ - + import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; @@ -16,75 +16,82 @@ import org.eclipse.swt.graphics.GC; * 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; /** * 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 (pixes) where the text has to fit in + * + * @param reader + * Reader of the input text + * @param gc + * The graphic context that defines the currently used font sizes + * @param maxLineWidth + * The max width (pixes) 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(); + fReader = new BufferedReader(reader); + fGC = gc; + fMaxWidth = maxLineWidth; + fOffset = 0; + fLine = null; + fLineBreakIterator = BreakIterator.getLineInstance(); } - + public boolean isFormattedLine() { return fLine != null; } - + /** - * Reads the next line. The lengths of the line will not exceed the gived maximum - * width. + * Reads the next line. The lengths of the line will not exceed the gived + * maximum width. */ public String readLine() throws IOException { if (fLine == null) { - String line= fReader.readLine(); + String line = fReader.readLine(); if (line == null) return null; - - int lineLen= fGC.textExtent(line).x; + + int lineLen = fGC.textExtent(line).x; if (lineLen < fMaxWidth) { return line; } - fLine= line; + fLine = line; fLineBreakIterator.setText(line); - fOffset= 0; + fOffset = 0; } - int breakOffset= findNextBreakOffset(fOffset); + int breakOffset = findNextBreakOffset(fOffset); String res; if (breakOffset != BreakIterator.DONE) { - res= fLine.substring(fOffset, breakOffset); - fOffset= findWordBegin(breakOffset); + res = fLine.substring(fOffset, breakOffset); + fOffset = findWordBegin(breakOffset); if (fOffset == fLine.length()) { - fLine= null; + fLine = null; } } else { - res= fLine.substring(fOffset); - fLine= null; + res = fLine.substring(fOffset); + fLine = null; } return res; } - + private int findNextBreakOffset(int currOffset) { - int currWidth= 0; - int nextOffset= fLineBreakIterator.following(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; + String word = fLine.substring(currOffset, nextOffset); + int wordWidth = fGC.textExtent(word).x; + int nextWidth = wordWidth + currWidth; if (nextWidth > fMaxWidth) { if (currWidth > 0) { return currOffset; @@ -92,17 +99,18 @@ public class LineBreakingReader { return nextOffset; } } - currWidth= nextWidth; - currOffset= nextOffset; - nextOffset= fLineBreakIterator.next(); + currWidth = nextWidth; + currOffset = nextOffset; + nextOffset = fLineBreakIterator.next(); } return nextOffset; } - + private int findWordBegin(int idx) { - while (idx < fLine.length() && Character.isWhitespace(fLine.charAt(idx))) { + while (idx < fLine.length() + && Character.isWhitespace(fLine.charAt(idx))) { idx++; } return idx; - } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/PHPCodeReader.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/PHPCodeReader.java index 1b16749..fffffda 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/PHPCodeReader.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/PHPCodeReader.java @@ -13,239 +13,244 @@ 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. + * Reads from a document either forwards or backwards. May be configured to skip + * comments and strings. */ public class PHPCodeReader 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 PHPCodeReader() { - } - - /** - * 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 '"': - case '\'': - - if (fSkipStrings) { - gotoStringEnd(current); - continue; - } - - return current; - case '#': - - if (fSkipComments && fOffset < fEnd) { - gotoLineEnd(); - continue; - } - - return 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; - - } - - 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; - } - - if (current == '#' && fCachedLineOffset <= 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; - } + /** 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 PHPCodeReader() { + } + + /** + * 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 '"': + case '\'': + + if (fSkipStrings) { + gotoStringEnd(current); + continue; + } + + return current; + case '#': + + if (fSkipComments && fOffset < fEnd) { + gotoLineEnd(); + continue; + } + + return 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; + + } + + 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; + } + + if (current == '#' && fCachedLineOffset <= 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/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/PHPPairMatcher.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/PHPPairMatcher.java index d82629e..ab9abd5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/PHPPairMatcher.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/PHPPairMatcher.java @@ -17,167 +17,172 @@ import org.eclipse.jface.text.source.ICharacterPairMatcher; * Helper class for match pairs of characters. */ public class PHPPairMatcher implements ICharacterPairMatcher { - protected char[] fPairs; - - protected IDocument fDocument; - - protected int fOffset; - - protected int fStartPos; - - protected int fEndPos; - - protected int fAnchor; - - protected PHPCodeReader fReader = new PHPCodeReader(); - - public PHPPairMatcher(char[] pairs) { - fPairs = pairs; - } - - /* - * @see org.eclipse.jface.text.source.ICharacterPairMatcher#clear() - */ - public void clear() { - if (fReader != null) { - try { - fReader.close(); - } catch (IOException x) { - // ignore - } - } - } - - public IRegion match(IDocument document, int offset) { - - fOffset = offset; - - if (fOffset < 0) - return null; - - fDocument = document; - - if (matchPairsAt() && fStartPos != fEndPos) - return new Region(fStartPos, fEndPos - fStartPos + 1); - - return null; - } - - public int getAnchor() { - return fAnchor; - } - - public void dispose() { - fDocument = null; - if (fReader != null) { - try { - fReader.close(); - } catch (IOException x) { - // ignore - } - fReader = null; - } - } - - protected boolean matchPairsAt() { - - int i; - int pairIndex1 = fPairs.length; - int pairIndex2 = fPairs.length; - - fStartPos = -1; - fEndPos = -1; - - // get the chars preceding and following the start position - try { - - char prevChar = fDocument.getChar(Math.max(fOffset - 1, 0)); - char nextChar = fDocument.getChar(fOffset); - - // search for opening peer character next to the activation point - for (i = 0; i < fPairs.length; i = i + 2) { - if (nextChar == fPairs[i]) { - fStartPos = fOffset; - pairIndex1 = i; - } else if (prevChar == fPairs[i]) { - fStartPos = fOffset - 1; - pairIndex1 = i; - } - } - - // search for closing peer character next to the activation point - for (i = 1; i < fPairs.length; i = i + 2) { - if (prevChar == fPairs[i]) { - fEndPos = fOffset - 1; - pairIndex2 = i; - } else if (nextChar == fPairs[i]) { - fEndPos = fOffset; - pairIndex2 = i; - } - } - - if (fEndPos > -1) { - fAnchor = RIGHT; - fStartPos = searchForOpeningPeer(fEndPos, fPairs[pairIndex2 - 1], fPairs[pairIndex2], fDocument); - if (fStartPos > -1) - return true; - else - fEndPos = -1; - } else if (fStartPos > -1) { - fAnchor = LEFT; - fEndPos = searchForClosingPeer(fStartPos, fPairs[pairIndex1], fPairs[pairIndex1 + 1], fDocument); - if (fEndPos > -1) - return true; - else - fStartPos = -1; - } - - } catch (BadLocationException x) { - } catch (IOException x) { - } - - return false; - } - - protected int searchForClosingPeer(int offset, int openingPeer, int closingPeer, IDocument document) throws IOException { - - fReader.configureForwardReader(document, offset + 1, document.getLength(), true, true); - - int stack = 1; - int c = fReader.read(); - while (c != PHPCodeReader.EOF) { - if (c == openingPeer && c != closingPeer) - stack++; - else if (c == closingPeer) - stack--; - - if (stack == 0) - return fReader.getOffset(); - - c = fReader.read(); - } - - return -1; - } - - protected int searchForOpeningPeer(int offset, int openingPeer, int closingPeer, IDocument document) throws IOException { - - fReader.configureBackwardReader(document, offset, true, true); - - int stack = 1; - int c = fReader.read(); - while (c != PHPCodeReader.EOF) { - if (c == closingPeer && c != openingPeer) - stack++; - else if (c == openingPeer) - stack--; - - if (stack == 0) - return fReader.getOffset(); - - c = fReader.read(); - } - - return -1; - } + protected char[] fPairs; + + protected IDocument fDocument; + + protected int fOffset; + + protected int fStartPos; + + protected int fEndPos; + + protected int fAnchor; + + protected PHPCodeReader fReader = new PHPCodeReader(); + + public PHPPairMatcher(char[] pairs) { + fPairs = pairs; + } + + /* + * @see org.eclipse.jface.text.source.ICharacterPairMatcher#clear() + */ + public void clear() { + if (fReader != null) { + try { + fReader.close(); + } catch (IOException x) { + // ignore + } + } + } + + public IRegion match(IDocument document, int offset) { + + fOffset = offset; + + if (fOffset < 0) + return null; + + fDocument = document; + + if (matchPairsAt() && fStartPos != fEndPos) + return new Region(fStartPos, fEndPos - fStartPos + 1); + + return null; + } + + public int getAnchor() { + return fAnchor; + } + + public void dispose() { + fDocument = null; + if (fReader != null) { + try { + fReader.close(); + } catch (IOException x) { + // ignore + } + fReader = null; + } + } + + protected boolean matchPairsAt() { + + int i; + int pairIndex1 = fPairs.length; + int pairIndex2 = fPairs.length; + + fStartPos = -1; + fEndPos = -1; + + // get the chars preceding and following the start position + try { + + char prevChar = fDocument.getChar(Math.max(fOffset - 1, 0)); + char nextChar = fDocument.getChar(fOffset); + + // search for opening peer character next to the activation point + for (i = 0; i < fPairs.length; i = i + 2) { + if (nextChar == fPairs[i]) { + fStartPos = fOffset; + pairIndex1 = i; + } else if (prevChar == fPairs[i]) { + fStartPos = fOffset - 1; + pairIndex1 = i; + } + } + + // search for closing peer character next to the activation point + for (i = 1; i < fPairs.length; i = i + 2) { + if (prevChar == fPairs[i]) { + fEndPos = fOffset - 1; + pairIndex2 = i; + } else if (nextChar == fPairs[i]) { + fEndPos = fOffset; + pairIndex2 = i; + } + } + + if (fEndPos > -1) { + fAnchor = RIGHT; + fStartPos = searchForOpeningPeer(fEndPos, + fPairs[pairIndex2 - 1], fPairs[pairIndex2], fDocument); + if (fStartPos > -1) + return true; + else + fEndPos = -1; + } else if (fStartPos > -1) { + fAnchor = LEFT; + fEndPos = searchForClosingPeer(fStartPos, fPairs[pairIndex1], + fPairs[pairIndex1 + 1], fDocument); + if (fEndPos > -1) + return true; + else + fStartPos = -1; + } + + } catch (BadLocationException x) { + } catch (IOException x) { + } + + return false; + } + + protected int searchForClosingPeer(int offset, int openingPeer, + int closingPeer, IDocument document) throws IOException { + + fReader.configureForwardReader(document, offset + 1, document + .getLength(), true, true); + + int stack = 1; + int c = fReader.read(); + while (c != PHPCodeReader.EOF) { + if (c == openingPeer && c != closingPeer) + stack++; + else if (c == closingPeer) + stack--; + + if (stack == 0) + return fReader.getOffset(); + + c = fReader.read(); + } + + return -1; + } + + protected int searchForOpeningPeer(int offset, int openingPeer, + int closingPeer, IDocument document) throws IOException { + + fReader.configureBackwardReader(document, offset, true, true); + + int stack = 1; + int c = fReader.read(); + while (c != PHPCodeReader.EOF) { + if (c == closingPeer && c != openingPeer) + stack++; + else if (c == openingPeer) + stack--; + + if (stack == 0) + return fReader.getOffset(); + + c = fReader.read(); + } + + return -1; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/PreferencesAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/PreferencesAdapter.java index 84500dc..acc8643 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/PreferencesAdapter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/PreferencesAdapter.java @@ -27,47 +27,51 @@ 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. + * {@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 { + 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()); + firePropertyChangeEvent(event.getProperty(), event.getOldValue(), + event.getNewValue()); } } - + /** Listeners on the adapter */ - private ListenerList fListeners= new ListenerList(); - + private ListenerList fListeners = new ListenerList(); + /** Listener on the adapted Preferences */ - private PropertyChangeListener fListener= new PropertyChangeListener(); - + 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. + * @param preferences + * The preferences to wrap. */ public PreferencesAdapter(Preferences preferences) { - fPreferences= preferences; + fPreferences = preferences; } - + /** * {@inheritDoc} */ @@ -96,11 +100,13 @@ public class PreferencesAdapter implements IPreferenceStore { /** * {@inheritDoc} */ - public void firePropertyChangeEvent(String name, Object oldValue, Object newValue) { + public void firePropertyChangeEvent(String name, Object oldValue, + Object newValue) { if (!fSilent) { - PropertyChangeEvent event= new PropertyChangeEvent(this, name, oldValue, newValue); - Object[] listeners= fListeners.getListeners(); - for (int i= 0; i < listeners.length; i++) + PropertyChangeEvent event = new PropertyChangeEvent(this, name, + oldValue, newValue); + Object[] listeners = fListeners.getListeners(); + for (int i = 0; i < listeners.length; i++) ((IPropertyChangeListener) listeners[i]).propertyChange(event); } } @@ -208,10 +214,10 @@ public class PreferencesAdapter implements IPreferenceStore { */ public void putValue(String name, String value) { try { - fSilent= true; + fSilent = true; fPreferences.setValue(name, value); } finally { - fSilent= false; + fSilent = false; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/SequenceCharacterIterator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/SequenceCharacterIterator.java index 7613b77..33a9906 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/SequenceCharacterIterator.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/SequenceCharacterIterator.java @@ -14,63 +14,76 @@ import java.text.CharacterIterator; import org.eclipse.jface.text.Assert; - /** - * A CharSequence based implementation of CharacterIterator. + * A CharSequence based implementation of + * CharacterIterator. * * @since 3.0 */ public class SequenceCharacterIterator implements CharacterIterator { - private int fIndex= -1; + 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 + * @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 + * @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 { + 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 + * @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 { + 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; + fSequence = sequence; + fFirst = first; + fLast = last; + fIndex = first; invariant(); } @@ -124,10 +137,10 @@ public class SequenceCharacterIterator implements CharacterIterator { */ public char setIndex(int position) { if (position >= getBeginIndex() && position <= getEndIndex()) - fIndex= position; + fIndex = position; else throw new IllegalArgumentException(); - + invariant(); return current(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/SmartBackspaceManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/SmartBackspaceManager.java index 5661707..9f74ae9 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/SmartBackspaceManager.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/SmartBackspaceManager.java @@ -30,18 +30,17 @@ import org.eclipse.swt.graphics.Point; import org.eclipse.text.edits.MalformedTreeException; import org.eclipse.text.edits.TextEdit; - - /** - * Installs as a verify key listener on a viewer and overwrites the behaviour - * of the backspace key. Clients may register undo specifications for certain - * offsets in a document. The SmartBackspaceManager will manage the - * specfications and execute the contained TextEdits when backspace - * is pressed at the given offset and the specification is still valid. + * Installs as a verify key listener on a viewer and overwrites the behaviour of + * the backspace key. Clients may register undo specifications for certain + * offsets in a document. The SmartBackspaceManager will manage + * the specfications and execute the contained TextEdits when + * backspace is pressed at the given offset and the specification is still + * valid. *

                                                      * Undo specifications are removed after a number of typing runs. *

                                                      - * + * * @since 3.0 */ public class SmartBackspaceManager { @@ -50,57 +49,67 @@ public class SmartBackspaceManager { /** * An undo specification describes the change that should be executed if * backspace is pressed at its trigger offset. - * + * * @since 3.0 */ 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 * TextEdit s that will be executed when backspace is * pressed at triggerOffset. The spec will be removed * when it is executed, or if more than lives - * TypingRuns have ended after registering the spec. + * TypingRuns + * have ended after registering the spec. *

                                                      * 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 UndoSpecs that will be executed upon - * repeated pressing of backspace. + * the spec, the child spec will be registered with the manager. This + * allows to create chains of UndoSpecs that will be + * executed upon repeated pressing of backspace. *

                                                      * - * @param triggerOffset the offset where this spec is active - * @param selection the selection after executing the undo spec - * @param edits the TextEdit s to perform when executing - * the spec - * @param lives the number of TypingRun s before removing - * the spec - * @param child a child specification that will be registered after - * executing this spec, or null + * @param triggerOffset + * the offset where this spec is active + * @param selection + * the selection after executing the undo spec + * @param edits + * the TextEdit s to perform when executing + * the spec + * @param lives + * the number of TypingRun s before removing + * the spec + * @param child + * a child specification that will be registered after + * executing this spec, or null */ - public UndoSpec(int triggerOffset, IRegion selection, TextEdit[] edits, int lives, UndoSpec child) { + 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++) { + 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; + + this.triggerOffset = triggerOffset; + this.selection = selection; + this.undoEdits = edits; + this.lives = lives; + this.child = child; } } - private class BackspaceListener implements VerifyKeyListener { /* @@ -108,15 +117,17 @@ public class SmartBackspaceManager { */ public void verifyKey(VerifyEvent event) { if (fViewer != null && isBackspace(event)) { - int offset= getCaretOffset(); - UndoSpec spec= removeEdit(offset); + 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); + 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()); + fViewer.setSelectedRange(spec.selection.getOffset(), + spec.selection.getLength()); if (spec.child != null) register(spec.child); } catch (MalformedTreeException e) { @@ -128,79 +139,87 @@ public class SmartBackspaceManager { } finally { endChange(); } - event.doit= false; + event.doit = false; } - + } } private void beginChange() { - ITextViewer viewer= fViewer; + ITextViewer viewer = fViewer; if (viewer instanceof TextViewer) { - TextViewer v= (TextViewer) viewer; + TextViewer v = (TextViewer) viewer; v.getRewriteTarget().beginCompoundChange(); v.setRedraw(false); } } private void endChange() { - ITextViewer viewer= fViewer; + ITextViewer viewer = fViewer; if (viewer instanceof TextViewer) { - TextViewer v= (TextViewer) viewer; + TextViewer v = (TextViewer) viewer; v.getRewriteTarget().endCompoundChange(); v.setRedraw(true); } } private boolean isBackspace(VerifyEvent event) { - return event.doit == true && event.character == SWT.BS && event.stateMask == 0; + return event.doit == true && event.character == SWT.BS + && event.stateMask == 0; } private int getCaretOffset() { - ITextViewer viewer= fViewer; - Point point= viewer.getSelectedRange(); + 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 + * @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); + 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); + 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; + fBackspaceListener = new BackspaceListener(); + ITextViewer viewer = fViewer; if (viewer instanceof ITextViewerExtension) - ((ITextViewerExtension) viewer).prependVerifyKeyListener(fBackspaceListener); + ((ITextViewerExtension) viewer) + .prependVerifyKeyListener(fBackspaceListener); else viewer.getTextWidget().addVerifyKeyListener(fBackspaceListener); } @@ -208,12 +227,14 @@ public class SmartBackspaceManager { private void ensureListenerRemoved() { if (fBackspaceListener != null) { - ITextViewer viewer= fViewer; + ITextViewer viewer = fViewer; if (viewer instanceof ITextViewerExtension) - ((ITextViewerExtension) viewer).removeVerifyKeyListener(fBackspaceListener); + ((ITextViewerExtension) viewer) + .removeVerifyKeyListener(fBackspaceListener); else - viewer.getTextWidget().removeVerifyKeyListener(fBackspaceListener); - fBackspaceListener= null; + viewer.getTextWidget().removeVerifyKeyListener( + fBackspaceListener); + fBackspaceListener = null; } } @@ -228,12 +249,12 @@ public class SmartBackspaceManager { */ public void install(ITextViewer viewer) { Assert.isLegal(viewer != null); - - fViewer= viewer; - fSpecs= new HashMap(); - fRunDetector= new TypingRunDetector(); + + fViewer = viewer; + fSpecs = new HashMap(); + fRunDetector = new TypingRunDetector(); fRunDetector.install(viewer); - fRunListener= new ITypingRunListener() { + fRunListener = new ITypingRunListener() { /* * @see org.eclipse.jface.text.TypingRunDetector.ITypingRunListener#typingRunStarted(org.eclipse.jface.text.TypingRunDetector.TypingRun) @@ -253,15 +274,15 @@ public class SmartBackspaceManager { }; fRunDetector.addTypingRunListener(fRunListener); } - + private void prune() { - for (Iterator it= fSpecs.values().iterator(); it.hasNext();) { - UndoSpec spec= (UndoSpec) it.next(); + 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. @@ -270,9 +291,9 @@ public class SmartBackspaceManager { if (fViewer != null) { fRunDetector.removeTypingRunListener(fRunListener); fRunDetector.uninstall(); - fRunDetector= null; + fRunDetector = null; ensureListenerRemoved(); - fViewer= null; + fViewer = null; } } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/SmartSemicolonAutoEditStrategy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/SmartSemicolonAutoEditStrategy.java index 5dfea87..4f133c3 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/SmartSemicolonAutoEditStrategy.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/SmartSemicolonAutoEditStrategy.java @@ -40,93 +40,113 @@ import org.eclipse.ui.texteditor.ITextEditorExtension2; import org.eclipse.ui.texteditor.ITextEditorExtension3; /** - * Modifies DocumentCommands 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. - * - *

                                                      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 for statements definition. If the line contains a semicolon - * or brace after the current caret position, the cursor is moved after it.

                                                      - * + * Modifies DocumentCommands 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. + * + *

                                                      + * 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 + * for statements definition. If the line contains a semicolon or + * brace after the current caret position, the cursor is moved after it. + *

                                                      + * * @see org.eclipse.jface.text.DocumentCommand * @since 3.0 */ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { /** String representation of a semicolon. */ - private static final String SEMICOLON= ";"; //$NON-NLS-1$ + private static final String SEMICOLON = ";"; //$NON-NLS-1$ + /** Char representation of a semicolon. */ - private static final char SEMICHAR= ';'; + private static final char SEMICHAR = ';'; + /** String represenattion of a opening brace. */ - private static final String BRACE= "{"; //$NON-NLS-1$ + private static final String BRACE = "{"; //$NON-NLS-1$ + /** Char representation of a opening brace */ - private static final char BRACECHAR= '{'; + private static final char BRACECHAR = '{'; private char fCharacter; + private String fPartitioning; /** * Creates a new SmartSemicolonAutoEditStrategy. - * - * @param partitioning the document partitioning + * + * @param partitioning + * the document partitioning */ public SmartSemicolonAutoEditStrategy(String partitioning) { - fPartitioning= partitioning; + fPartitioning = partitioning; } /* - * @see org.eclipse.jface.text.IAutoEditStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.DocumentCommand) + * @see org.eclipse.jface.text.IAutoEditStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, + * org.eclipse.jface.text.DocumentCommand) */ - public void customizeDocumentCommand(IDocument document, DocumentCommand command) { + public void customizeDocumentCommand(IDocument document, + DocumentCommand command) { // 0: early pruning - // also customize if doit is false (so it works in code completion situations) - // if (!command.doit) - // return; + // also customize if doit 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; + fCharacter = SEMICHAR; else if (command.text.equals(BRACE)) - fCharacter= BRACECHAR; + fCharacter = BRACECHAR; else return; - IPreferenceStore store= PHPeclipsePlugin.getDefault().getPreferenceStore(); - if (fCharacter == SEMICHAR && !store.getBoolean(PreferenceConstants.EDITOR_SMART_SEMICOLON)) + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + if (fCharacter == SEMICHAR + && !store + .getBoolean(PreferenceConstants.EDITOR_SMART_SEMICOLON)) return; - if (fCharacter == BRACECHAR && !store.getBoolean(PreferenceConstants.EDITOR_SMART_OPENING_BRACE)) + if (fCharacter == BRACECHAR + && !store + .getBoolean(PreferenceConstants.EDITOR_SMART_OPENING_BRACE)) return; - IWorkbenchPage page= PHPeclipsePlugin.getActivePage(); + IWorkbenchPage page = PHPeclipsePlugin.getActivePage(); if (page == null) return; - IEditorPart part= page.getActiveEditor(); + IEditorPart part = page.getActiveEditor(); if (!(part instanceof PHPUnitEditor)) return; - PHPUnitEditor editor= (PHPUnitEditor)part; - if (editor.getInsertMode() != ITextEditorExtension3.SMART_INSERT || !editor.isEditable()) + PHPUnitEditor editor = (PHPUnitEditor) part; + if (editor.getInsertMode() != ITextEditorExtension3.SMART_INSERT + || !editor.isEditable()) return; - ITextEditorExtension2 extension= (ITextEditorExtension2)editor.getAdapter(ITextEditorExtension2.class); + 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; + int pos = command.offset; ITextSelection line; try { - IRegion l= document.getLineInformationOfOffset(pos); - line= new TextSelection(document, l.getOffset(), l.getLength()); + 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(); + int positionInLine = computeCharacterPosition(document, line, pos + - line.getOffset(), fCharacter, fPartitioning); + int position = positionInLine + line.getOffset(); // never position before the current position! if (position < pos) @@ -136,57 +156,63 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { 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); + // 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 && PHPeclipsePlugin.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(), + final SmartBackspaceManager manager = (SmartBackspaceManager) editor + .getAdapter(SmartBackspaceManager.class); + if (manager != null + && PHPeclipsePlugin.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); + 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; + command.offset = position; + command.length = 0; + command.caretOffset = position; + command.text = insertion; + command.doit = true; + command.owner = null; } catch (MalformedTreeException e) { PHPeclipsePlugin.log(e); } catch (BadLocationException e) { - PHPeclipsePlugin.log(e); + PHPeclipsePlugin.log(e); } - } /** * Returns true if the document command is applied on a multi * line selection, false otherwise. - * - * @param document the document - * @param command the command - * @return true if command is a multiline command + * + * @param document + * the document + * @param command + * the command + * @return true if command is a multiline + * command */ - private boolean isMultilineSelection(IDocument document, DocumentCommand command) { + private boolean isMultilineSelection(IDocument document, + DocumentCommand command) { try { return document.getNumberOfLines(command.offset, command.length) > 1; } catch (BadLocationException e) { @@ -196,27 +222,31 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { } /** - * Adds a space before a brace if it is inserted after a parenthesis, equal sign, or one - * of the keywords try, else, do. - * - * @param document the document we are working on - * @param position the insert position of character - * @param character the character to be inserted - * @return a String consisting of character plus any additional spacing + * Adds a space before a brace if it is inserted after a parenthesis, equal + * sign, or one of the keywords try, else, do. + * + * @param document + * the document we are working on + * @param position + * the insert position of character + * @param character + * the character to be inserted + * @return a String consisting of character + * 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; + 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$ + || 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 }); } } @@ -225,16 +255,22 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { } /** - * Checks whether a character to be inserted is already present at the insert location (perhaps - * separated by some whitespace from position. - * - * @param document the document we are working on - * @param position the insert position of ch - * @param character the character to be inserted - * @return true if ch is already present at location, false otherwise + * Checks whether a character to be inserted is already present at the + * insert location (perhaps separated by some whitespace from + * position. + * + * @param document + * the document we are working on + * @param position + * the insert position of ch + * @param character + * the character to be inserted + * @return true if ch is already present at + * location, false otherwise */ private boolean alreadyPresent(IDocument document, char ch, int position) { - int pos= firstNonWhitespaceForward(document, position, fPartitioning, document.getLength()); + int pos = firstNonWhitespaceForward(document, position, fPartitioning, + document.getLength()); try { if (pos != -1 && document.getChar(pos) == ch) return true; @@ -245,43 +281,58 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { } /** - * 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 character was typed - * @param character the character to look for - * @param partitioning the document partitioning - * @return the position where character should be inserted / replaced + * 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 + * character was typed + * @param character + * the character to look for + * @param partitioning + * the document partitioning + * @return the position where character should be inserted / + * replaced */ - protected static int computeCharacterPosition(IDocument document, ITextSelection line, int offset, char character, String partitioning) { - String text= line.getText(); + 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); + insertPos = computeArrayInitializationPos(document, line, offset, + partitioning); if (insertPos == -1) { - insertPos= computeAfterTryDoElse(document, line, offset); + insertPos = computeAfterTryDoElse(document, line, offset); } if (insertPos == -1) { - insertPos= computeAfterParenthesis(document, line, offset, partitioning); + 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 + 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. + 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; + insertPos = insertPos - 1; } } else { @@ -293,41 +344,50 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { } /** - * Computes an insert position for an opening brace if offset maps to a position in - * document 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 line looks like being an array initialization at offset, -1 otherwise + * Computes an insert position for an opening brace if offset + * maps to a position in document 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 + * line looks like being an array initialization at + * offset, -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(); + 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); + int p = firstNonWhitespaceBackward(document, pos - 1, partitioning, -1); if (p == -1) return -1; try { - char ch= document.getChar(p); + char ch = document.getChar(p); if (ch != '=' && ch != ']') return -1; if (p == 0) return offset; - p= firstNonWhitespaceBackward(document, p - 1, partitioning, -1); + p = firstNonWhitespaceBackward(document, p - 1, partitioning, -1); if (p == -1) return -1; - ch= document.getChar(p); + ch = document.getChar(p); if (Scanner.isPHPIdentifierPart(ch) || ch == ']' || ch == '[') return offset; @@ -337,76 +397,101 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { } /** - * Computes an insert position for an opening brace if offset maps to a position in - * document involving a keyword taking a block after it. These are: try, - * do, synchronized, static, finally, or else. - * - * @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. - * @return an insert position relative to the line start if line contains one of the above keywords at or before offset, -1 otherwise + * Computes an insert position for an opening brace if offset + * maps to a position in document involving a keyword taking + * a block after it. These are: try, do, + * synchronized, static, + * finally, or else. + * + * @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. + * @return an insert position relative to the line start if + * line contains one of the above keywords at or + * before offset, -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); + 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$ + || 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 offset maps to a position in - * document 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 line contains a parenthesized expression that can be followed by a block, -1 otherwise + * Computes an insert position for an opening brace if offset + * maps to a position in document 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 + * line 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 + 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, '}'); + int pos = offset + line.getOffset(); + int length = line.getOffset() + line.getLength(); + int scanTo = scanForward(document, pos, partitioning, length, '}'); if (scanTo == -1) - scanTo= length; + scanTo = length; - int closingParen= findClosingParenToLeft(document, pos, partitioning) - 1; + int closingParen = findClosingParenToLeft(document, pos, partitioning) - 1; while (true) { - int startScan= closingParen + 1; - closingParen= scanForward(document, startScan, partitioning, scanTo, ')'); + int startScan = closingParen + 1; + closingParen = scanForward(document, startScan, partitioning, + scanTo, ')'); if (closingParen == -1) break; - int openingParen= findOpeningParenMatch(document, closingParen, partitioning); + int openingParen = findOpeningParenMatch(document, closingParen, + partitioning); - // no way an expression at the beginning of the document can mean anything + // 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 + // only select insert positions for parenthesis currently embracing + // the caret if (openingParen > pos) continue; - if (looksLikeAnonymousClassDef(document, openingParen - 1, partitioning)) + if (looksLikeAnonymousClassDef(document, openingParen - 1, + partitioning)) return closingParen + 1 - line.getOffset(); - if (looksLikeIfWhileForCatch(document, openingParen - 1, partitioning)) + if (looksLikeIfWhileForCatch(document, openingParen - 1, + partitioning)) return closingParen + 1 - line.getOffset(); if (looksLikeMethodDecl(document, openingParen - 1, partitioning)) @@ -418,21 +503,31 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { } /** - * Finds a closing parenthesis to the left of position in document, where that parenthesis is only - * separated by whitespace from position. If no such parenthesis can be found, position is returned. - * - * @param document the document being modified - * @param position the first character position in document to be considered - * @param partitioning the document partitioning - * @return the position of a closing parenthesis left to position separated only by whitespace, or position if no parenthesis can be found + * Finds a closing parenthesis to the left of position in + * document, where that parenthesis is only separated by whitespace from + * position. If no such parenthesis can be found, + * position is returned. + * + * @param document + * the document being modified + * @param position + * the first character position in document to be + * considered + * @param partitioning + * the document partitioning + * @return the position of a closing parenthesis left to + * position separated only by whitespace, or + * position if no parenthesis can be found */ - private static int findClosingParenToLeft(IDocument document, int position, String partitioning) { - final char CLOSING_PAREN= ')'; + 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); + int nonWS = firstNonWhitespaceBackward(document, position - 1, + partitioning, -1); if (nonWS != -1 && document.getChar(nonWS) == CLOSING_PAREN) return nonWS; } catch (BadLocationException e1) { @@ -441,20 +536,26 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { } /** - * Finds the first whitespace character position to the right of (and including) position. - * - * @param document the document being modified - * @param position the first character position in document to be considered - * @return the position of a whitespace character greater or equal than position separated only by whitespace, or -1 if none found + * Finds the first whitespace character position to the right of (and + * including) position. + * + * @param document + * the document being modified + * @param position + * the first character position in document to be + * considered + * @return the position of a whitespace character greater or equal than + * position separated only by whitespace, or -1 if + * none found */ private static int firstWhitespaceToRight(IDocument document, int position) { - int length= document.getLength(); + int length = document.getLength(); Assert.isTrue(position >= 0); Assert.isTrue(position <= length); try { while (position < length) { - char ch= document.getChar(position); + char ch = document.getChar(position); if (Character.isWhitespace(ch)) return position; position++; @@ -466,24 +567,36 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { } /** - * Finds the highest position in document such that the position is <= position - * and > bound and Character.isWhitespace(document.getChar(pos)) evaluates to false - * and the position is in the default partition. - * - * @param document the document being modified - * @param position the first character position in document to be considered - * @param partitioning the document partitioning - * @param bound the first position in document to not consider any more, with bound > position - * @return the highest position of one element in chars in [position, scanTo) that resides in a Java partition, or -1 if none can be found + * Finds the highest position in document such that the + * position is <= position and > bound + * and Character.isWhitespace(document.getChar(pos)) + * evaluates to false and the position is in the default + * partition. + * + * @param document + * the document being modified + * @param position + * the first character position in document to be + * considered + * @param partitioning + * the document partitioning + * @param bound + * the first position in document to not consider + * any more, with bound > position + * @return the highest position of one element in chars in [position, + * scanTo) that resides in a Java partition, or + * -1 if none can be found */ - private static int firstNonWhitespaceBackward(IDocument document, int position, String partitioning, int bound) { + 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)) + char ch = document.getChar(position); + if (!Character.isWhitespace(ch) + && isDefaultPartition(document, position, partitioning)) return position; position--; } @@ -493,24 +606,36 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { } /** - * Finds the smallest position in document such that the position is >= position - * and < bound and Character.isWhitespace(document.getChar(pos)) evaluates to false - * and the position is in the default partition. - * - * @param document the document being modified - * @param position the first character position in document to be considered - * @param partitioning the document partitioning - * @param bound the first position in document to not consider any more, with bound > position - * @return the smallest position of one element in chars in [position, scanTo) that resides in a Java partition, or -1 if none can be found + * Finds the smallest position in document such that the + * position is >= position and < bound + * and Character.isWhitespace(document.getChar(pos)) + * evaluates to false and the position is in the default + * partition. + * + * @param document + * the document being modified + * @param position + * the first character position in document to be + * considered + * @param partitioning + * the document partitioning + * @param bound + * the first position in document to not consider + * any more, with bound > position + * @return the smallest position of one element in chars in [position, + * scanTo) that resides in a Java partition, or + * -1 if none can be found */ - private static int firstNonWhitespaceForward(IDocument document, int position, String partitioning, int bound) { + 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)) + char ch = document.getChar(position); + if (!Character.isWhitespace(ch) + && isDefaultPartition(document, position, partitioning)) return position; position++; } @@ -520,27 +645,41 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { } /** - * Finds the highest position in document such that the position is <= position - * and > bound and document.getChar(position) == ch evaluates to true for at least one - * ch in chars and the position is in the default partition. - * - * @param document the document being modified - * @param position the first character position in document to be considered - * @param partitioning the document partitioning - * @param bound the first position in document to not consider any more, with scanTo > position - * @param chars an array of char to search for - * @return the highest position of one element in chars in (bound, position] that resides in a Java partition, or -1 if none can be found + * Finds the highest position in document such that the + * position is <= position and > bound + * and document.getChar(position) == ch evaluates to + * true for at least one ch in chars and the + * position is in the default partition. + * + * @param document + * the document being modified + * @param position + * the first character position in document to be + * considered + * @param partitioning + * the document partitioning + * @param bound + * the first position in document to not consider + * any more, with scanTo > + * position + * @param chars + * an array of char to search for + * @return the highest position of one element in chars in (bound, + * position] that resides in a Java partition, or + * -1 if none can be found */ - private static int scanBackward(IDocument document, int position, String partitioning, int bound, char[] chars) { + private static int scanBackward(IDocument document, int position, + String partitioning, int bound, char[] chars) { Assert.isTrue(bound >= -1); - Assert.isTrue(position < document.getLength() ); + Assert.isTrue(position < document.getLength()); Arrays.sort(chars); try { while (position > bound) { - if (Arrays.binarySearch(chars, document.getChar(position)) >= 0 && isDefaultPartition(document, position, partitioning)) + if (Arrays.binarySearch(chars, document.getChar(position)) >= 0 + && isDefaultPartition(document, position, partitioning)) return position; position--; @@ -550,34 +689,54 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { return -1; } -// /** -// * Finds the highest position in document such that the position is <= position -// * and > bound and document.getChar(position) == ch evaluates to true -// * and the position is in the default partition. -// * -// * @param document the document being modified -// * @param position the first character position in document to be considered -// * @param bound the first position in document to not consider any more, with scanTo > position -// * @param chars an array of char to search for -// * @return the highest position of one element in chars in [position, scanTo) that resides in a Java partition, or -1 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 highest position in document such that the + // position is <= position + // * and > bound and document.getChar(position) == + // ch evaluates to true + // * and the position is in the default partition. + // * + // * @param document the document being modified + // * @param position the first character position in document + // to be considered + // * @param bound the first position in document to not + // consider any more, with scanTo > position + // * @param chars an array of char to search for + // * @return the highest position of one element in chars in + // [position, scanTo) that resides in a Java + // partition, or -1 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 document such that the position is >= position - * and < bound and document.getChar(position) == ch evaluates to true for at least one - * ch in chars and the position is in the default partition. - * - * @param document the document being modified - * @param position the first character position in document to be considered - * @param partitioning the document partitioning - * @param bound the first position in document to not consider any more, with scanTo > position - * @param chars an array of char to search for - * @return the lowest position of one element in chars in [position, bound) that resides in a Java partition, or -1 if none can be found + * Finds the lowest position in document such that the + * position is >= position and < bound + * and document.getChar(position) == ch evaluates to + * true for at least one ch in chars and the + * position is in the default partition. + * + * @param document + * the document being modified + * @param position + * the first character position in document to be + * considered + * @param partitioning + * the document partitioning + * @param bound + * the first position in document to not consider + * any more, with scanTo > + * position + * @param chars + * an array of char to search for + * @return the lowest position of one element in chars in [position, + * bound) that resides in a Java partition, or + * -1 if none can be found */ - private static int scanForward(IDocument document, int position, String partitioning, int bound, char[] chars) { + private static int scanForward(IDocument document, int position, + String partitioning, int bound, char[] chars) { Assert.isTrue(position >= 0); Assert.isTrue(bound <= document.getLength()); @@ -586,7 +745,8 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { try { while (position < bound) { - if (Arrays.binarySearch(chars, document.getChar(position)) >= 0 && isDefaultPartition(document, position, partitioning)) + if (Arrays.binarySearch(chars, document.getChar(position)) >= 0 + && isDefaultPartition(document, position, partitioning)) return position; position++; @@ -597,42 +757,63 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { } /** - * Finds the lowest position in document such that the position is >= position - * and < bound and document.getChar(position) == ch evaluates to true - * and the position is in the default partition. - * - * @param document the document being modified - * @param position the first character position in document to be considered - * @param partitioning the document partitioning - * @param bound the first position in document to not consider any more, with scanTo > position - * @param chars an array of char to search for - * @return the lowest position of one element in chars in [position, bound) that resides in a Java partition, or -1 if none can be found + * Finds the lowest position in document such that the + * position is >= position and < bound + * and document.getChar(position) == ch evaluates to + * true and the position is in the default partition. + * + * @param document + * the document being modified + * @param position + * the first character position in document to be + * considered + * @param partitioning + * the document partitioning + * @param bound + * the first position in document to not consider + * any more, with scanTo > + * position + * @param chars + * an array of char to search for + * @return the lowest position of one element in chars in [position, + * bound) that resides in a Java partition, or + * -1 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}); + 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 document in the range (offset, length) - * contains the new keyword. - * - * @param document the document being modified - * @param offset the first character position in document to be considered - * @param length the length of the character range to be considered - * @param partitioning the document partitioning - * @return true if the specified character range contains a new keyword, false otherwise. + * Checks whether the content of document in the range (offset, + * length) contains the new keyword. + * + * @param document + * the document being modified + * @param offset + * the first character position in document to be + * considered + * @param length + * the length of the character range to be considered + * @param partitioning + * the document partitioning + * @return true if the specified character range contains a + * new keyword, false otherwise. */ - private static boolean isNewMatch(IDocument document, int offset, int length, String partitioning) { + 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$ + 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$ + while (pos != -1 + && !isDefaultPartition(document, pos + offset, partitioning)) + pos = text.indexOf("new", pos + 2); //$NON-NLS-1$ if (pos < 0) return false; @@ -640,7 +821,8 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { if (pos != 0 && Scanner.isPHPIdentifierPart(text.charAt(pos - 1))) return false; - if (pos + 3 < length && Scanner.isPHPIdentifierPart(text.charAt(pos + 3))) + if (pos + 3 < length + && Scanner.isPHPIdentifierPart(text.charAt(pos + 3))) return false; return true; @@ -651,41 +833,65 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { } /** - * Checks whether the content of document at position looks like an - * anonymous class definition. position 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 document to be considered - * @param partitioning the document partitioning - * @return true if the content of document looks like an anonymous class definition, false otherwise + * Checks whether the content of document at + * position looks like an anonymous class definition. + * position 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 document to be + * considered + * @param partitioning + * the document partitioning + * @return true if the content of document + * looks like an anonymous class definition, false + * otherwise */ - private static boolean looksLikeAnonymousClassDef(IDocument document, int position, String partitioning) { - int previousCommaOrParen= scanBackward(document, position - 1, partitioning, -1, new char[] {',', '('}); - if (previousCommaOrParen == -1 || position < previousCommaOrParen + 5) // 2 for borders, 3 for "new" + private static boolean looksLikeAnonymousClassDef(IDocument document, + int position, String partitioning) { + int previousCommaOrParen = scanBackward(document, position - 1, + partitioning, -1, new char[] { ',', '(' }); + if (previousCommaOrParen == -1 || position < previousCommaOrParen + 5) // 2 + // for + // borders, + // 3 + // for + // "new" return false; - if (isNewMatch(document, previousCommaOrParen + 1, position - previousCommaOrParen - 2, partitioning)) + if (isNewMatch(document, previousCommaOrParen + 1, position + - previousCommaOrParen - 2, partitioning)) return true; return false; } /** - * Checks whether position resides in a default (Java) partition of document. - * - * @param document the document being modified - * @param position the position to be checked - * @param partitioning the document partitioning - * @return true if position is in the default partition of document, false otherwise + * Checks whether position resides in a default (Java) + * partition of document. + * + * @param document + * the document being modified + * @param position + * the position to be checked + * @param partitioning + * the document partitioning + * @return true if position is in the default + * partition of document, false + * otherwise */ - private static boolean isDefaultPartition(IDocument document, int position, String partitioning) { + 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); + // 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) { @@ -695,16 +901,23 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { } /** - * Finds the position of the parenthesis matching the closing parenthesis at position. - * - * @param document the document being modified - * @param position the position in document of a closing parenthesis - * @param partitioning the document partitioning - * @return the position in document of the matching parenthesis, or -1 if none can be found + * Finds the position of the parenthesis matching the closing parenthesis at + * position. + * + * @param document + * the document being modified + * @param position + * the position in document of a closing + * parenthesis + * @param partitioning + * the document partitioning + * @return the position in document 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= '('; + 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); @@ -714,9 +927,10 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { Assert.isTrue(document.getChar(position) == CLOSING_PAREN); - int depth= 1; + int depth = 1; while (true) { - position= scanBackward(document, position - 1, partitioning, -1, new char[] {CLOSING_PAREN, OPENING_PAREN}); + position = scanBackward(document, position - 1, partitioning, + -1, new char[] { CLOSING_PAREN, OPENING_PAREN }); if (position == -1) return -1; @@ -735,17 +949,27 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { } /** - * Checks whether, to the left of position and separated only by whitespace, - * document contains a keyword taking a parameter list and a block after it. - * These are: if, while, catch, for, synchronized, switch. - * - * @param document the document being modified - * @param position the first character position in document to be considered - * @param partitioning the document partitioning - * @return true if document contains any of the above keywords to the left of position, false otherwise + * Checks whether, to the left of position and separated only + * by whitespace, document contains a keyword taking a + * parameter list and a block after it. These are: if, + * while, catch, for, + * synchronized, switch. + * + * @param document + * the document being modified + * @param position + * the first character position in document to be + * considered + * @param partitioning + * the document partitioning + * @return true if document contains any of + * the above keywords to the left of position, + * false otherwise */ - private static boolean looksLikeIfWhileForCatch(IDocument document, int position, String partitioning) { - position= firstNonWhitespaceBackward(document, position, partitioning, -1); + private static boolean looksLikeIfWhileForCatch(IDocument document, + int position, String partitioning) { + position = firstNonWhitespaceBackward(document, position, partitioning, + -1); if (position == -1) return false; @@ -758,19 +982,27 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { } /** - * Checks whether code>document
                                                      contains the String like such - * that its last character is at position. If like starts with a - * identifier part (as determined by {@link Scanner#isPHPIdentifierPart(char)}), it is also made - * sure that like 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 document to be considered - * @param like the String to look for. - * @return true if document contains like such that it ends at position, false otherwise + * Checks whether code>document
                                                      contains the String like + * such that its last character is at position. If like + * starts with a identifier part (as determined by + * {@link Scanner#isPHPIdentifierPart(char)}), it is also made sure that + * like 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 document to be + * considered + * @param like + * the String to look for. + * @return true if document contains like + * such that it ends at position, false + * otherwise */ - private static boolean looksLike(IDocument document, int position, String like) { - int length= like.length(); + private static boolean looksLike(IDocument document, int position, + String like) { + int length = like.length(); if (position < length - 1) return false; @@ -778,7 +1010,10 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { if (!like.equals(document.get(position - length + 1, length))) return false; - if (position >= length && Scanner.isPHPIdentifierPart(like.charAt(0)) && Scanner.isPHPIdentifierPart(document.getChar(position - length))) + if (position >= length + && Scanner.isPHPIdentifierPart(like.charAt(0)) + && Scanner.isPHPIdentifierPart(document.getChar(position + - length))) return false; } catch (BadLocationException e) { @@ -789,48 +1024,66 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { } /** - * Checks whether the content of document at position looks like a - * method declaration header (i.e. only the return type and method name). position - * 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 document to be considered - * @param partitioning the document partitioning - * @return true if the content of document looks like a method definition, false otherwise + * Checks whether the content of document at + * position looks like a method declaration header (i.e. only + * the return type and method name). position 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 document to be + * considered + * @param partitioning + * the document partitioning + * @return true if the content of document + * looks like a method definition, false otherwise */ - private static boolean looksLikeMethodDecl(IDocument document, int position, String partitioning) { + private static boolean looksLikeMethodDecl(IDocument document, + int position, String partitioning) { // method name - position= eatIdentToLeft(document, position, partitioning); + position = eatIdentToLeft(document, position, partitioning); if (position < 1) return false; - position= eatBrackets(document, position - 1, partitioning); + position = eatBrackets(document, position - 1, partitioning); if (position < 1) return false; - position= eatIdentToLeft(document, position - 1, partitioning); + position = eatIdentToLeft(document, position - 1, partitioning); return position != -1; } /** - * From position to the left, eats any whitespace and then a pair of brackets - * as used to declare an array return type like
                                                      String [ ]
                                                      . - * The return value is either the position of the opening bracket or position if no - * pair of brackets can be parsed. - * - * @param document the document being modified - * @param position the first character position in document to be considered - * @param partitioning the document partitioning - * @return the smallest character position of bracket pair or position + * From position to the left, eats any whitespace and then a + * pair of brackets as used to declare an array return type like + * + *
                                                      +	 * String [ ]
                                                      +	 * 
                                                      . The return value is either the position of the opening bracket + * or position if no pair of brackets can be parsed. + * + * @param document + * the document being modified + * @param position + * the first character position in document to be + * considered + * @param partitioning + * the document partitioning + * @return the smallest character position of bracket pair or + * position */ - private static int eatBrackets(IDocument document, int position, String partitioning) { + private static int eatBrackets(IDocument document, int position, + String partitioning) { // accept array return type - int pos= firstNonWhitespaceBackward(document, position, partitioning, -1); + int pos = firstNonWhitespaceBackward(document, position, partitioning, + -1); try { if (pos > 1 && document.getChar(pos) == ']') { - pos= firstNonWhitespaceBackward(document, pos - 1, partitioning, -1); + pos = firstNonWhitespaceBackward(document, pos - 1, + partitioning, -1); if (pos > 0 && document.getChar(pos) == '[') return pos; } @@ -841,30 +1094,39 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { } /** - * From position to the left, eats any whitespace and the first identifier, returning - * the position of the first identifier character (in normal read order). - *

                                                      When called on a document with content " some string " and positionition 13, the - * return value will be 6 (the first letter in string). + * From position to the left, eats any whitespace and the + * first identifier, returning the position of the first identifier + * character (in normal read order). + *

                                                      + * When called on a document with content " some string " and + * positionition 13, the return value will be 6 (the first letter in + * string). *

                                                      - * - * @param document the document being modified - * @param position the first character position in document to be considered - * @param partitioning the document partitioning - * @return the smallest character position of an identifier or -1 if none can be found; always <= position + * + * @param document + * the document being modified + * @param position + * the first character position in document to be + * considered + * @param partitioning + * the document partitioning + * @return the smallest character position of an identifier or -1 if none + * can be found; always <= position */ - private static int eatIdentToLeft(IDocument document, int position, String partitioning) { + 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); + int p = firstNonWhitespaceBackward(document, position, partitioning, -1); if (p == -1) return -1; try { while (p >= 0) { - char ch= document.getChar(p); + char ch = document.getChar(p); if (Scanner.isPHPIdentifierPart(ch)) { p--; continue; @@ -887,57 +1149,74 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { } /** - * 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 line - * @param partitioning the document partitioning - * @return the position of the next Java partition, or the end of line + * 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 line + * @param partitioning + * the document partitioning + * @return the position of the next Java partition, or the end of + * line */ - private static int nextPartitionOrLineEnd(IDocument document, ITextSelection line, int offset, String partitioning) { + 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; + 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); + ITypedRegion partition = TextUtilities.getPartition(document, + partitioning, nextPartitionPos, true); + validPosition = getValidPositionForPartition(document, partition, + eol); while (validPosition == -1) { - nextPartitionPos= partition.getOffset() - 1; + nextPartitionPos = partition.getOffset() - 1; if (nextPartitionPos < docOffset) { - validPosition= docOffset; + validPosition = docOffset; break; } - partition= TextUtilities.getPartition(document, partitioning, nextPartitionPos, false); - validPosition= getValidPositionForPartition(document, partition, eol); + partition = TextUtilities.getPartition(document, partitioning, + nextPartitionPos, false); + validPosition = getValidPositionForPartition(document, + partition, eol); } } catch (BadLocationException e) { } - validPosition= Math.max(validPosition, docOffset); + validPosition = Math.max(validPosition, docOffset); // make relative to line validPosition -= line.getOffset(); return validPosition; } /** - * Returns a valid insert location (except for whitespace) in partition 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 maxOffset. 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 partition, or -1 if there is no valid insert location + * Returns a valid insert location (except for whitespace) in + * partition 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 + * maxOffset. 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 partition, or -1 if + * there is no valid insert location */ - private static int getValidPositionForPartition(IDocument doc, ITypedRegion partition, int maxOffset) { - final int INVALID= -1; + private static int getValidPositionForPartition(IDocument doc, + ITypedRegion partition, int maxOffset) { + final int INVALID = -1; if (IPHPPartitions.PHP_PHPDOC_COMMENT.equals(partition.getType())) return INVALID; @@ -946,10 +1225,11 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { if (IPHPPartitions.PHP_SINGLELINE_COMMENT.equals(partition.getType())) return INVALID; - int endOffset= Math.min(maxOffset, partition.getOffset() + partition.getLength()); + int endOffset = Math.min(maxOffset, partition.getOffset() + + partition.getLength()); -// if (IPHPPartitions.JAVA_CHARACTER.equals(partition.getType())) -// return endOffset; + // if (IPHPPartitions.JAVA_CHARACTER.equals(partition.getType())) + // return endOffset; if (IPHPPartitions.PHP_STRING_DQ.equals(partition.getType())) return endOffset; if (IPHPPartitions.PHP_STRING_SQ.equals(partition.getType())) @@ -958,7 +1238,8 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { return endOffset; if (IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())) { try { - if (doc.get(partition.getOffset(), endOffset - partition.getOffset()).trim().length() == 0) + if (doc.get(partition.getOffset(), + endOffset - partition.getOffset()).trim().length() == 0) return INVALID; else return endOffset; @@ -971,34 +1252,43 @@ public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { } /** - * 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 true if line contains for, false otherwise + * 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 true if line contains + * for, false otherwise */ private static boolean isForStatement(String line, int offset) { /* searching for (^|\s)for(\s|$) */ - int forPos= line.indexOf("for"); //$NON-NLS-1$ + int forPos = line.indexOf("for"); //$NON-NLS-1$ if (forPos != -1) { - if ((forPos == 0 || !Scanner.isPHPIdentifierPart(line.charAt(forPos - 1))) && (line.length() == forPos + 3 || !Scanner.isPHPIdentifierPart(line.charAt(forPos + 3)))) + if ((forPos == 0 || !Scanner.isPHPIdentifierPart(line + .charAt(forPos - 1))) + && (line.length() == forPos + 3 || !Scanner + .isPHPIdentifierPart(line.charAt(forPos + 3)))) return true; } return false; } /** - * Returns the position in text after which there comes only whitespace, up to - * offset. - * - * @param text the text being searched - * @param offset the maximum offset to search for - * @return the smallest value v such that text.substring(v, offset).trim() == 0 + * Returns the position in text after which there comes only + * whitespace, up to offset. + * + * @param text + * the text being searched + * @param offset + * the maximum offset to search for + * @return the smallest value v such that + * text.substring(v, offset).trim() == 0 */ private static int startOfWhitespaceBeforeOffset(String text, int offset) { - int i= Math.min(offset, text.length()); + int i = Math.min(offset, text.length()); for (; i >= 1; i--) { if (!Character.isWhitespace(text.charAt(i - 1))) break; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/SubstitutionTextReader.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/SubstitutionTextReader.java index 7570e05..cc89ebe 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/SubstitutionTextReader.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/SubstitutionTextReader.java @@ -1,150 +1,152 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html -Contributors: - IBM Corporation - Initial implementation -**********************************************************************/ + Contributors: + IBM Corporation - Initial implementation + **********************************************************************/ package net.sourceforge.phpdt.internal.ui.text; - import java.io.IOException; import java.io.Reader; import net.sourceforge.phpdt.internal.corext.phpdoc.SingleCharReader; - /** - * 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. + * 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. */ public abstract class SubstitutionTextReader extends SingleCharReader { - - protected static final String LINE_DELIM= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ - + + protected static final String LINE_DELIM = System.getProperty( + "line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ + private Reader fReader; + private boolean fWasWhiteSpace; + private int fCharAfterWhiteSpace; /** * Tells whether white space characters are skipped. */ - private boolean fSkipWhiteSpace= true; - + private boolean fSkipWhiteSpace = true; + private boolean fReadFromBuffer; + private StringBuffer fBuffer; - private int fIndex; + private int fIndex; protected SubstitutionTextReader(Reader reader) { - fReader= reader; - fBuffer= new StringBuffer(); - fIndex= 0; - fReadFromBuffer= false; - fCharAfterWhiteSpace= -1; - fWasWhiteSpace= true; + fReader = reader; + fBuffer = new StringBuffer(); + fIndex = 0; + fReadFromBuffer = false; + fCharAfterWhiteSpace = -1; + fWasWhiteSpace = true; } - + /** - * Implement to compute the substitution for the given character and - * if necessary subsequent characters. Use nextChar - * to read subsequent characters. + * Implement to compute the substitution for the given character and if + * necessary subsequent characters. Use nextChar to read + * subsequent characters. */ protected abstract String computeSubstitution(int c) throws IOException; - + /** * Returns the internal reader. */ protected Reader getReader() { return fReader; } - + /** * Returns the next character. */ protected int nextChar() throws IOException { - fReadFromBuffer= (fBuffer.length() > 0); + fReadFromBuffer = (fBuffer.length() > 0); if (fReadFromBuffer) { - char ch= fBuffer.charAt(fIndex++); + char ch = fBuffer.charAt(fIndex++); if (fIndex >= fBuffer.length()) { fBuffer.setLength(0); - fIndex= 0; + fIndex = 0; } return ch; } else { - int ch= fCharAfterWhiteSpace; + int ch = fCharAfterWhiteSpace; if (ch == -1) { - ch= fReader.read(); + ch = fReader.read(); } - if (fSkipWhiteSpace && Character.isWhitespace((char)ch)) { + if (fSkipWhiteSpace && Character.isWhitespace((char) ch)) { do { - ch= fReader.read(); - } while (Character.isWhitespace((char)ch)); + ch = fReader.read(); + } while (Character.isWhitespace((char) ch)); if (ch != -1) { - fCharAfterWhiteSpace= ch; + fCharAfterWhiteSpace = ch; return ' '; } } else { - fCharAfterWhiteSpace= -1; + fCharAfterWhiteSpace = -1; } return ch; } } - + /** * @see Reader#read() */ public int read() throws IOException { int c; do { - - c= nextChar(); + + c = nextChar(); while (!fReadFromBuffer) { - String s= computeSubstitution(c); + String s = computeSubstitution(c); if (s == null) break; if (s.length() > 0) fBuffer.insert(0, s); - c= nextChar(); + c = nextChar(); } - + } while (fSkipWhiteSpace && fWasWhiteSpace && (c == ' ')); - fWasWhiteSpace= (c == ' ' || c == '\r' || c == '\n'); + fWasWhiteSpace = (c == ' ' || c == '\r' || c == '\n'); return c; } - + /** * @see Reader#ready() - */ - public boolean ready() throws IOException { + */ + 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; + fWasWhiteSpace = true; + fCharAfterWhiteSpace = -1; fBuffer.setLength(0); - fIndex= 0; + fIndex = 0; } protected final void setSkipWhitespace(boolean state) { - fSkipWhiteSpace= state; + fSkipWhiteSpace = state; } protected final boolean isSkippingWhitespace() { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/Symbols.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/Symbols.java index 22e1a42..eeba337 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/Symbols.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/Symbols.java @@ -16,35 +16,65 @@ package net.sourceforge.phpdt.internal.ui.text; * @since 3.0 */ 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 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 TokenIDENT= 2000; + int TokenEOF = -1; + + int TokenLBRACE = 1; + + int TokenRBRACE = 2; + + int TokenLBRACKET = 3; + + int TokenRBRACKET = 4; + + int TokenLPAREN = 5; + + int TokenRPAREN = 6; + + int TokenSEMICOLON = 7; + + int TokenOTHER = 8; + + int TokenCOLON = 9; + + int TokenQUESTIONMARK = 10; + + int TokenCOMMA = 11; + + int TokenEQUAL = 12; + + int 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 TokenIDENT = 2000; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/TypingRun.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/TypingRun.java index 350672a..6a2cd02 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/TypingRun.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/TypingRun.java @@ -10,51 +10,55 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.ui.text; - - /** * Describes a run of similar typing changes. *

                                                      - * XXX to be extended with further information, e.g. offset, length, and - * content of the run. + * XXX to be extended with further information, e.g. offset, length, and content + * of the run. *

                                                      * * @since 3.0 */ public final class TypingRun { /** - * A change of type DELETE 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 DELETE 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 INSERT inserts one single character * (normal typing). - */ - public static final ChangeType INSERT= new ChangeType(true, "INSERT"); //$NON-NLS-1$ + */ + public static final ChangeType INSERT = new ChangeType(true, "INSERT"); //$NON-NLS-1$ + /** * A change of type NO_CHANGE does not change anything. */ - public static final ChangeType NO_CHANGE= new ChangeType(false, "NO_CHANGE"); //$NON-NLS-1$ + public static final ChangeType NO_CHANGE = new ChangeType(false, + "NO_CHANGE"); //$NON-NLS-1$ + /** * A change of type OVERTYPE replaces one single character * (overwrite mode, pasting a single character). */ - public static final ChangeType OVERTYPE= new ChangeType(true, "OVERTYPE"); //$NON-NLS-1$ + public static final ChangeType OVERTYPE = new ChangeType(true, "OVERTYPE"); //$NON-NLS-1$ + /** * A change of type SELECTION 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$ + public static final ChangeType SELECTION = new ChangeType(false, + "SELECTION"); //$NON-NLS-1$ + /** - * A change of type UNKNOWN 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 UNKNOWN. + * A change of type UNKNOWN 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 UNKNOWN. */ - public static final ChangeType UNKNOWN= new ChangeType(true, "UNKNOWN"); //$NON-NLS-1$ - + public static final ChangeType UNKNOWN = new ChangeType(true, "UNKNOWN"); //$NON-NLS-1$ /** * Enumeration of change types. @@ -63,14 +67,15 @@ public final class TypingRun { */ 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; + fIsModification = isRunPart; + fName = name; } - + /** * Returns true if changes of this type modify text. * @@ -80,7 +85,7 @@ public final class TypingRun { boolean isModification() { return fIsModification; } - + /* * @see java.lang.Object#toString() */ @@ -88,16 +93,17 @@ public final class TypingRun { return fName; } } - + /** * Creates a new run. * - * @param type the type of the run + * @param type + * the type of the run */ TypingRun(ChangeType type) { - this.type= type; + this.type = type; } - + /** The change type of this run. */ public final ChangeType type; } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/TypingRunDetector.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/TypingRunDetector.java index c7c5536..d74a9c3 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/TypingRunDetector.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/TypingRunDetector.java @@ -32,7 +32,6 @@ import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; - /** * When connected to a text viewer, a TypingRunDetector observes * TypingRun events. A typing run is a sequence of similar text @@ -48,10 +47,10 @@ 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; - + 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 @@ -61,24 +60,28 @@ public class TypingRunDetector { */ private static final class Change { private ChangeType fType; + private int fNextOffset; - + /** * Creates a new change of type type. * - * @param type the ChangeType of the new change - * @param nextOffset the offset of the next change in a typing run + * @param type + * the ChangeType 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; + fType = type; + fNextOffset = nextOffset; } - + /** * Returns true if the receiver can extend the typing * range the last change of which is described by change. * - * @param change the last change in a typing run + * @param change + * the last change in a typing run * @return true if the receiver is a valid extension to * change,false otherwise */ @@ -117,7 +120,7 @@ public class TypingRunDetector { public String toString() { return fType.toString() + "@" + fNextOffset; //$NON-NLS-1$ } - + /** * Returns the change type of this change. * @@ -127,7 +130,7 @@ public class TypingRunDetector { 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 @@ -142,14 +145,15 @@ public class TypingRunDetector { 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 { + private class SelectionListener implements MouseListener, KeyListener, + FocusListener { /* * @see org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent) @@ -163,22 +167,24 @@ public class TypingRunDetector { */ 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 + * 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 */ @@ -190,67 +196,73 @@ public class TypingRunDetector { */ 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; + 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(); + private final Set fListeners = new HashSet(); + /** * The viewer we work upon. Set to null in * uninstall. */ private ITextViewer fViewer; + /** The text event listener. */ - private final TextListener fTextListener= new TextListener(); - /** + private final TextListener fTextListener = new TextListener(); + + /** * The selection listener. Set to null when no run is active. */ private SelectionListener fSelectionListener; - + /* state variables */ - + /** The most recently observed change. Never null. */ private Change fLastChange; + /** The current run, or null if there is none. */ private TypingRun fRun; - + /** * Installs the receiver with a text viewer. * - * @param viewer the viewer to install on + * @param viewer + * the viewer to install on */ public void install(ITextViewer viewer) { Assert.isLegal(viewer != null); - fViewer= viewer; + 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; + fLastChange = new Change(TypingRun.UNKNOWN, -1); + fRun = null; + fSelectionListener = null; fViewer.addTextListener(fTextListener); } } @@ -263,10 +275,10 @@ public class TypingRunDetector { if (fViewer != null) { fListeners.clear(); disconnect(); - fViewer= null; + fViewer = null; } } - + /** * Disconnects any registered listeners. */ @@ -277,10 +289,11 @@ public class TypingRunDetector { /** * Adds a listener for TypingRun events. Repeatedly adding - * the same listener instance has no effect. Listeners may be added even - * if the receiver is neither connected nor installed. + * 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 + * @param listener + * the listener add */ public void addTypingRunListener(ITypingRunListener listener) { Assert.isLegal(listener != null); @@ -288,46 +301,49 @@ public class TypingRunDetector { if (fListeners.size() == 1) connect(); } - + /** * Removes the listener from this manager. If listener is not * registered with the receiver, nothing happens. - * - * @param listener the listener to remove, or null + * + * @param listener + * the listener to remove, or null */ 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 + * @param event + * the text event that describes the text modification */ void handleTextChanged(TextEvent event) { - Change type= computeChange(event); + Change type = computeChange(event); handleChange(type); } /** * Computes the change abstraction given a text event. * - * @param event the text event to analyze + * @param event + * the text event to analyze * @return a change object describing the event */ private Change computeChange(TextEvent event) { - DocumentEvent e= event.getDocumentEvent(); + 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(); + + int start = e.getOffset(); + int end = e.getOffset() + e.getLength(); + String newText = e.getText(); if (newText == null) - newText= new String(); - + newText = new String(); + if (start == end) { // no replace / delete / overwrite if (newText.length() == 1) @@ -338,36 +354,37 @@ public class TypingRunDetector { 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 + * @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; + fLastChange = change; if (change.isModification()) startOrContinue(); - + if (DEBUG) System.err.println("New change: " + change); //$NON-NLS-1$ } @@ -380,7 +397,7 @@ public class TypingRunDetector { if (!hasRun()) { if (DEBUG) System.err.println("+Start run"); //$NON-NLS-1$ - fRun= new TypingRun(fLastChange.getType()); + fRun = new TypingRun(fLastChange.getType()); ensureSelectionListenerAdded(); fireRunBegun(fRun); } @@ -401,7 +418,8 @@ public class TypingRunDetector { * Ends any active run and informs all listeners. If there is none, nothing * happens. * - * @param change the change that triggered ending the active run + * @param change + * the change that triggered ending the active run */ private void endIfStarted(Change change) { if (hasRun()) { @@ -409,7 +427,7 @@ public class TypingRunDetector { if (DEBUG) System.err.println("-End run"); //$NON-NLS-1$ fireRunEnded(fRun, change.getType()); - fRun= null; + fRun = null; } } @@ -419,8 +437,8 @@ public class TypingRunDetector { */ private void ensureSelectionListenerAdded() { if (fSelectionListener == null) { - fSelectionListener= new SelectionListener(); - StyledText textWidget= fViewer.getTextWidget(); + fSelectionListener = new SelectionListener(); + StyledText textWidget = fViewer.getTextWidget(); textWidget.addFocusListener(fSelectionListener); textWidget.addKeyListener(fSelectionListener); textWidget.addMouseListener(fSelectionListener); @@ -433,23 +451,24 @@ public class TypingRunDetector { */ private void ensureSelectionListenerRemoved() { if (fSelectionListener != null) { - StyledText textWidget= fViewer.getTextWidget(); + StyledText textWidget = fViewer.getTextWidget(); textWidget.removeFocusListener(fSelectionListener); textWidget.removeKeyListener(fSelectionListener); textWidget.removeMouseListener(fSelectionListener); - fSelectionListener= null; + fSelectionListener = null; } } /** * Informs all listeners about a newly started TypingRun. * - * @param run the new run + * @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(); + List listeners = new ArrayList(fListeners); + for (Iterator it = listeners.iterator(); it.hasNext();) { + ITypingRunListener listener = (ITypingRunListener) it.next(); listener.typingRunStarted(fRun); } } @@ -457,13 +476,15 @@ public class TypingRunDetector { /** * Informs all listeners about an ended TypingRun. * - * @param run the previously active run - * @param reason the type of change that caused the run to be ended + * @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(); + List listeners = new ArrayList(fListeners); + for (Iterator it = listeners.iterator(); it.hasNext();) { + ITypingRunListener listener = (ITypingRunListener) it.next(); listener.typingRunEnded(fRun, reason); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/comment/CommentFormattingContext.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/comment/CommentFormattingContext.java index 7e82a3a..127f285 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/comment/CommentFormattingContext.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/comment/CommentFormattingContext.java @@ -26,20 +26,19 @@ public class CommentFormattingContext extends FormattingContext { * @see org.eclipse.jface.text.formatter.IFormattingContext#getPreferenceKeys() */ public String[] getPreferenceKeys() { - return new String[] { - PreferenceConstants.FORMATTER_COMMENT_FORMAT, - PreferenceConstants.FORMATTER_COMMENT_FORMATHEADER, - PreferenceConstants.FORMATTER_COMMENT_FORMATSOURCE, - PreferenceConstants.FORMATTER_COMMENT_INDENTPARAMETERDESCRIPTION, - PreferenceConstants.FORMATTER_COMMENT_INDENTROOTTAGS, - PreferenceConstants.FORMATTER_COMMENT_NEWLINEFORPARAMETER, - PreferenceConstants.FORMATTER_COMMENT_SEPARATEROOTTAGS, - PreferenceConstants.FORMATTER_COMMENT_LINELENGTH, - PreferenceConstants.FORMATTER_COMMENT_CLEARBLANKLINES, - PreferenceConstants.FORMATTER_COMMENT_FORMATHTML }; + return new String[] { + PreferenceConstants.FORMATTER_COMMENT_FORMAT, + PreferenceConstants.FORMATTER_COMMENT_FORMATHEADER, + PreferenceConstants.FORMATTER_COMMENT_FORMATSOURCE, + PreferenceConstants.FORMATTER_COMMENT_INDENTPARAMETERDESCRIPTION, + PreferenceConstants.FORMATTER_COMMENT_INDENTROOTTAGS, + PreferenceConstants.FORMATTER_COMMENT_NEWLINEFORPARAMETER, + PreferenceConstants.FORMATTER_COMMENT_SEPARATEROOTTAGS, + PreferenceConstants.FORMATTER_COMMENT_LINELENGTH, + PreferenceConstants.FORMATTER_COMMENT_CLEARBLANKLINES, + PreferenceConstants.FORMATTER_COMMENT_FORMATHTML }; } - /* * @see org.eclipse.jface.text.formatter.IFormattingContext#isBooleanPreference(java.lang.String) */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/DefaultJavaFoldingPreferenceBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/DefaultJavaFoldingPreferenceBlock.java index 1fea426..5e7e1b1 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/DefaultJavaFoldingPreferenceBlock.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/DefaultJavaFoldingPreferenceBlock.java @@ -34,10 +34,11 @@ import org.eclipse.swt.widgets.Label; /** * Java default folding preferences. - * + * * @since 3.0 */ -public class DefaultJavaFoldingPreferenceBlock implements IJavaFoldingPreferenceBlock { +public class DefaultJavaFoldingPreferenceBlock implements + IJavaFoldingPreferenceBlock { private IPreferenceStore fStore; @@ -53,7 +54,8 @@ public class DefaultJavaFoldingPreferenceBlock implements IJavaFoldingPreference public void widgetSelected(SelectionEvent e) { Button button = (Button) e.widget; - fOverlayStore.setValue((String) fCheckBoxes.get(button), button.getSelection()); + fOverlayStore.setValue((String) fCheckBoxes.get(button), button + .getSelection()); } }; @@ -66,20 +68,24 @@ public class DefaultJavaFoldingPreferenceBlock implements IJavaFoldingPreference private OverlayKey[] createKeys() { ArrayList overlayKeys = new ArrayList(); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FOLDING_JAVADOC)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FOLDING_HEADERS)); - overlayKeys.add(new - OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_FOLDING_INNERTYPES)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, + 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)); - return (OverlayKey[]) overlayKeys.toArray(new OverlayKey[overlayKeys.size()]); + return (OverlayKey[]) overlayKeys.toArray(new OverlayKey[overlayKeys + .size()]); } /* @@ -96,17 +102,24 @@ public class DefaultJavaFoldingPreferenceBlock implements IJavaFoldingPreference inner.setLayout(layout); Label label = new Label(inner, SWT.LEFT); - label.setText(FoldingMessages.getString("DefaultJavaFoldingPreferenceBlock.title")); //$NON-NLS-1$ - - addCheckBox(inner, - FoldingMessages.getString("DefaultJavaFoldingPreferenceBlock.comments"), PreferenceConstants.EDITOR_FOLDING_JAVADOC, 0); //$NON-NLS-1$ - addCheckBox(inner, - FoldingMessages.getString("DefaultJavaFoldingPreferenceBlock.headers"), PreferenceConstants.EDITOR_FOLDING_HEADERS, 0);//$NON-NLS-1$ - addCheckBox(inner, - FoldingMessages.getString("DefaultJavaFoldingPreferenceBlock.innerTypes"), - PreferenceConstants.EDITOR_FOLDING_INNERTYPES, 0); //$NON-NLS-1$ - addCheckBox(inner, - FoldingMessages.getString("DefaultJavaFoldingPreferenceBlock.methods"), PreferenceConstants.EDITOR_FOLDING_METHODS, 0); //$NON-NLS-1$ + label.setText(FoldingMessages + .getString("DefaultJavaFoldingPreferenceBlock.title")); //$NON-NLS-1$ + + addCheckBox( + inner, + FoldingMessages + .getString("DefaultJavaFoldingPreferenceBlock.comments"), PreferenceConstants.EDITOR_FOLDING_JAVADOC, 0); //$NON-NLS-1$ + addCheckBox( + inner, + FoldingMessages + .getString("DefaultJavaFoldingPreferenceBlock.headers"), PreferenceConstants.EDITOR_FOLDING_HEADERS, 0);//$NON-NLS-1$ + addCheckBox(inner, FoldingMessages + .getString("DefaultJavaFoldingPreferenceBlock.innerTypes"), + PreferenceConstants.EDITOR_FOLDING_INNERTYPES, 0); //$NON-NLS-1$ + addCheckBox( + inner, + FoldingMessages + .getString("DefaultJavaFoldingPreferenceBlock.methods"), PreferenceConstants.EDITOR_FOLDING_METHODS, 0); //$NON-NLS-1$ // addCheckBox(inner, // FoldingMessages.getString("DefaultJavaFoldingPreferenceBlock.imports"), // PreferenceConstants.EDITOR_FOLDING_IMPORTS, 0); //$NON-NLS-1$ @@ -114,7 +127,8 @@ public class DefaultJavaFoldingPreferenceBlock implements IJavaFoldingPreference return inner; } - private Button addCheckBox(Composite parent, String label, String key, int indentation) { + private Button addCheckBox(Composite parent, String label, String key, + int indentation) { Button checkBox = new Button(parent, SWT.CHECK); checkBox.setText(label); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/DefaultJavaFoldingStructureProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/DefaultJavaFoldingStructureProvider.java index c06a287..2b8c0ee 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/DefaultJavaFoldingStructureProvider.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/DefaultJavaFoldingStructureProvider.java @@ -65,10 +65,11 @@ import org.eclipse.ui.texteditor.ITextEditor; /** * Updates the projection model of a class file or compilation unit. - * + * * @since 3.0 */ -public class DefaultJavaFoldingStructureProvider implements IProjectionListener, IJavaFoldingStructureProvider { +public class DefaultJavaFoldingStructureProvider implements + IProjectionListener, IJavaFoldingStructureProvider { private static class JavaProjectionAnnotation extends ProjectionAnnotation { @@ -76,7 +77,8 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, private boolean fIsComment; - public JavaProjectionAnnotation(IJavaElement element, boolean isCollapsed, boolean isComment) { + public JavaProjectionAnnotation(IJavaElement element, + boolean isCollapsed, boolean isComment) { super(isCollapsed); fJavaElement = element; fIsComment = isComment; @@ -131,7 +133,8 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, processDelta(delta); } - private IJavaElementDelta findElement(IJavaElement target, IJavaElementDelta delta) { + private IJavaElementDelta findElement(IJavaElement target, + IJavaElementDelta delta) { if (delta == null || target == null) return null; @@ -157,13 +160,14 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, } /** - * Projection position that will return two foldable regions: one folding away - * the region from after the '/**' to the beginning of the content, the other - * from after the first content line until after the comment. - * + * Projection position that will return two foldable regions: one folding + * away the region from after the '/**' to the beginning of the content, the + * other from after the first content line until after the comment. + * * @since 3.1 */ - private static final class CommentPosition extends Position implements IProjectionPosition { + private static final class CommentPosition extends Position implements + IProjectionPosition { CommentPosition(int offset, int length) { super(offset, length); } @@ -171,8 +175,10 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, /* * @see org.eclipse.jface.text.source.projection.IProjectionPosition#computeFoldingRegions(org.eclipse.jface.text.IDocument) */ - public IRegion[] computeProjectionRegions(IDocument document) throws BadLocationException { - DocumentCharacterIterator sequence = new DocumentCharacterIterator(document, offset, offset + length); + public IRegion[] computeProjectionRegions(IDocument document) + throws BadLocationException { + DocumentCharacterIterator sequence = new DocumentCharacterIterator( + document, offset, offset + length); int prefixEnd = 0; int contentStart = findFirstContent(sequence, prefixEnd); @@ -180,14 +186,18 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, int captionLine = document.getLineOfOffset(offset + contentStart); int lastLine = document.getLineOfOffset(offset + length); - Assert.isTrue(firstLine <= captionLine, "first folded line is greater than the caption line"); //$NON-NLS-1$ - Assert.isTrue(captionLine <= lastLine, "caption line is greater than the last folded line"); //$NON-NLS-1$ + Assert.isTrue(firstLine <= captionLine, + "first folded line is greater than the caption line"); //$NON-NLS-1$ + Assert.isTrue(captionLine <= lastLine, + "caption line is greater than the last folded line"); //$NON-NLS-1$ IRegion preRegion; if (firstLine < captionLine) { - // preRegion= new Region(offset + prefixEnd, contentStart - prefixEnd); + // preRegion= new Region(offset + prefixEnd, contentStart - + // prefixEnd); int preOffset = document.getLineOffset(firstLine); - IRegion preEndLineInfo = document.getLineInformation(captionLine); + IRegion preEndLineInfo = document + .getLineInformation(captionLine); int preEnd = preEndLineInfo.getOffset(); preRegion = new Region(preOffset, preEnd - preOffset); } else { @@ -196,7 +206,8 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, if (captionLine < lastLine) { int postOffset = document.getLineOffset(captionLine + 1); - IRegion postRegion = new Region(postOffset, offset + length - postOffset); + IRegion postRegion = new Region(postOffset, offset + length + - postOffset); if (preRegion == null) return new IRegion[] { postRegion }; @@ -211,13 +222,13 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, } /** - * Finds the offset of the first identifier part within content. - * Returns 0 if none is found. - * + * Finds the offset of the first identifier part within + * content. Returns 0 if none is found. + * * @param content - * the content to search - * @return the first index of a unicode identifier part, or zero if none can - * be found + * the content to search + * @return the first index of a unicode identifier part, or zero if none + * can be found */ private int findFirstContent(final CharSequence content, int prefixEnd) { int lenght = content.length(); @@ -234,7 +245,8 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, // * Returns 0 if none is found. // * // * @param content the content to search - // * @return the first index of a unicode identifier part, or zero if none + // * @return the first index of a unicode identifier part, or zero if + // none // can // * be found // */ @@ -244,7 +256,8 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, // int i= 0; // while (i < len && isWhiteSpace(content.charAt(i))) // i++; - // if (len >= i + 2 && content.charAt(i) == '/' && content.charAt(i + 1) == + // if (len >= i + 2 && content.charAt(i) == '/' && content.charAt(i + 1) + // == // '*') // if (len >= i + 3 && content.charAt(i + 2) == '*') // return i + 3; @@ -263,19 +276,21 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, */ public int computeCaptionOffset(IDocument document) { // return 0; - DocumentCharacterIterator sequence = new DocumentCharacterIterator(document, offset, offset + length); + DocumentCharacterIterator sequence = new DocumentCharacterIterator( + document, offset, offset + length); return findFirstContent(sequence, 0); } } /** - * Projection position that will return two foldable regions: one folding away - * the lines before the one containing the simple name of the java element, - * one folding away any lines after the caption. - * + * Projection position that will return two foldable regions: one folding + * away the lines before the one containing the simple name of the java + * element, one folding away any lines after the caption. + * * @since 3.1 */ - private static final class JavaElementPosition extends Position implements IProjectionPosition { + private static final class JavaElementPosition extends Position implements + IProjectionPosition { private IMember fMember; @@ -293,14 +308,16 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, /* * @see org.eclipse.jface.text.source.projection.IProjectionPosition#computeFoldingRegions(org.eclipse.jface.text.IDocument) */ - public IRegion[] computeProjectionRegions(IDocument document) throws BadLocationException { + public IRegion[] computeProjectionRegions(IDocument document) + throws BadLocationException { int nameStart = offset; try { /* - * The member's name range may not be correct. However, reconciling - * would trigger another element delta which would lead to reentrant - * situations. Therefore, we optimistically assume that the name range - * is correct, but double check the received lines below. + * The member's name range may not be correct. However, + * reconciling would trigger another element delta which would + * lead to reentrant situations. Therefore, we optimistically + * assume that the name range is correct, but double check the + * received lines below. */ ISourceRange nameRange = fMember.getNameRange(); if (nameRange != null) @@ -315,9 +332,9 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, int lastLine = document.getLineOfOffset(offset + length); /* - * see comment above - adjust the caption line to be inside the entire - * folded region, and rely on later element deltas to correct the name - * range. + * see comment above - adjust the caption line to be inside the + * entire folded region, and rely on later element deltas to correct + * the name range. */ if (captionLine < firstLine) captionLine = firstLine; @@ -327,7 +344,8 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, IRegion preRegion; if (firstLine < captionLine) { int preOffset = document.getLineOffset(firstLine); - IRegion preEndLineInfo = document.getLineInformation(captionLine); + IRegion preEndLineInfo = document + .getLineInformation(captionLine); int preEnd = preEndLineInfo.getOffset(); preRegion = new Region(preOffset, preEnd - preOffset); } else { @@ -336,7 +354,8 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, if (captionLine < lastLine) { int postOffset = document.getLineOffset(captionLine + 1); - IRegion postRegion = new Region(postOffset, offset + length - postOffset); + IRegion postRegion = new Region(postOffset, offset + length + - postOffset); if (preRegion == null) return new IRegion[] { postRegion }; @@ -353,7 +372,8 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, /* * @see org.eclipse.jface.text.source.projection.IProjectionPosition#computeCaptionOffset(org.eclipse.jface.text.IDocument) */ - public int computeCaptionOffset(IDocument document) throws BadLocationException { + public int computeCaptionOffset(IDocument document) + throws BadLocationException { int nameStart = offset; try { // need a reconcile here? @@ -427,7 +447,8 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, */ public void projectionEnabled() { // http://home.ott.oti.com/teams/wswb/anon/out/vms/index.html - // projectionEnabled messages are not always paired with projectionDisabled + // projectionEnabled messages are not always paired with + // projectionDisabled // i.e. multiple enabled messages may be sent out. // we have to make sure that we disable first when getting an enable // message. @@ -468,7 +489,8 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, fHasHeaderComment = false; if (fEditor instanceof PHPUnitEditor) { - IWorkingCopyManager manager = PHPeclipsePlugin.getDefault().getWorkingCopyManager(); + IWorkingCopyManager manager = PHPeclipsePlugin.getDefault() + .getWorkingCopyManager(); fInput = manager.getWorkingCopy(fEditor.getEditorInput()); } // else if (fEditor instanceof ClassFileEditor) { @@ -478,14 +500,16 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, // } if (fInput != null) { - ProjectionAnnotationModel model = (ProjectionAnnotationModel) fEditor.getAdapter(ProjectionAnnotationModel.class); + ProjectionAnnotationModel model = (ProjectionAnnotationModel) fEditor + .getAdapter(ProjectionAnnotationModel.class); if (model != null) { fCachedModel = model; if (fInput instanceof ICompilationUnit) { ICompilationUnit unit = (ICompilationUnit) fInput; synchronized (unit) { try { - // unit.reconcile(ICompilationUnit.NO_AST, false, null, null); + // unit.reconcile(ICompilationUnit.NO_AST, + // false, null, null); unit.reconcile(); } catch (JavaModelException x) { } @@ -494,14 +518,16 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, Map additions = computeAdditions((IParent) fInput); /* - * Minimize the events being sent out - as this happens in the UI - * thread merge everything into one call. + * Minimize the events being sent out - as this happens in + * the UI thread merge everything into one call. */ List removals = new LinkedList(); Iterator existing = model.getAnnotationIterator(); while (existing.hasNext()) removals.add(existing.next()); - model.replaceAnnotations((Annotation[]) removals.toArray(new Annotation[removals.size()]), additions); + model.replaceAnnotations((Annotation[]) removals + .toArray(new Annotation[removals.size()]), + additions); } } @@ -516,17 +542,23 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, } private void initializePreferences() { - IPreferenceStore store = PHPeclipsePlugin.getDefault().getPreferenceStore(); - fCollapseInnerTypes = store.getBoolean(PreferenceConstants.EDITOR_FOLDING_INNERTYPES); + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + fCollapseInnerTypes = store + .getBoolean(PreferenceConstants.EDITOR_FOLDING_INNERTYPES); // fCollapseImportContainer = // store.getBoolean(PreferenceConstants.EDITOR_FOLDING_IMPORTS); - fCollapseJavadoc = store.getBoolean(PreferenceConstants.EDITOR_FOLDING_JAVADOC); - fCollapseMethods = store.getBoolean(PreferenceConstants.EDITOR_FOLDING_METHODS); - fCollapseHeaderComments = store.getBoolean(PreferenceConstants.EDITOR_FOLDING_HEADERS); + fCollapseJavadoc = store + .getBoolean(PreferenceConstants.EDITOR_FOLDING_JAVADOC); + fCollapseMethods = store + .getBoolean(PreferenceConstants.EDITOR_FOLDING_METHODS); + fCollapseHeaderComments = store + .getBoolean(PreferenceConstants.EDITOR_FOLDING_HEADERS); } private Map computeAdditions(IParent parent) { - Map map = new LinkedHashMap(); // use a linked map to maintain ordering of + Map map = new LinkedHashMap(); // use a linked map to maintain ordering + // of // comments try { computeAdditions(parent.getChildren(), map); @@ -535,7 +567,8 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, return map; } - private void computeAdditions(IJavaElement[] elements, Map map) throws JavaModelException { + private void computeAdditions(IJavaElement[] elements, Map map) + throws JavaModelException { for (int i = 0; i < elements.length; i++) { IJavaElement element = elements[i]; @@ -563,9 +596,9 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, collapse = fAllowCollapsing; if (isInnerType((IType) element)) { collapse = collapse && fCollapseInnerTypes; - } - else { - collapse = false; //don't allow the most outer type to be folded, may be changed in future versions + } else { + collapse = false; // don't allow the most outer type to be + // folded, may be changed in future versions } createProjection = true; break; @@ -580,21 +613,28 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, if (regions != null) { // comments for (int i = 0; i < regions.length - 1; i++) { - Position position = createProjectionPosition(regions[i], null); + Position position = createProjectionPosition(regions[i], + null); boolean commentCollapse; if (position != null) { - if (i == 0 && (regions.length > 2 || fHasHeaderComment) && element == fFirstType) { - commentCollapse = fAllowCollapsing && fCollapseHeaderComments; + if (i == 0 && (regions.length > 2 || fHasHeaderComment) + && element == fFirstType) { + commentCollapse = fAllowCollapsing + && fCollapseHeaderComments; } else { - commentCollapse = fAllowCollapsing && fCollapseJavadoc; + commentCollapse = fAllowCollapsing + && fCollapseJavadoc; } - map.put(new JavaProjectionAnnotation(element, commentCollapse, true), position); + map.put(new JavaProjectionAnnotation(element, + commentCollapse, true), position); } } // code - Position position = createProjectionPosition(regions[regions.length - 1], element); + Position position = createProjectionPosition( + regions[regions.length - 1], element); if (position != null) - map.put(new JavaProjectionAnnotation(element, collapse, false), position); + map.put(new JavaProjectionAnnotation(element, collapse, + false), position); } } } @@ -619,10 +659,11 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, * More than one range may be returned if the element has a leading comment * which gets folded separately. If there are no foldable regions, * null is returned. - * + * * @param element - * the java element that can be folded - * @return the regions to be folded, or null if there are none + * the java element that can be folded + * @return the regions to be folded, or null if there are + * none */ private IRegion[] computeProjectionRanges(IJavaElement element) { @@ -649,7 +690,8 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, final int shift = range.getOffset(); int start = shift; if (element instanceof IType) { - Scanner scanner = ToolFactory.createScanner(true, false, false, false); + Scanner scanner = ToolFactory.createScanner(true, false, + false, false); scanner.setSource(contents.toCharArray()); scanner.setPHPMode(true); @@ -662,7 +704,8 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, switch (token) { case ITerminalSymbols.TokenNameCOMMENT_PHPDOC: case ITerminalSymbols.TokenNameCOMMENT_BLOCK: { - int end = shift + scanner.getCurrentTokenEndPosition() + 1; + int end = shift + + scanner.getCurrentTokenEndPosition() + 1; regions.add(new Region(start, end - start)); } case ITerminalSymbols.TokenNameCOMMENT_LINE: @@ -707,12 +750,14 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, } /* - * code adapted from CommentFormattingStrategy: scan the header content up - * to the first type. Once a comment is found, accumulate any additional - * comments up to the stop condition. The stop condition is reaching a - * package declaration, import container, or the end of the input. + * code adapted from CommentFormattingStrategy: scan the header + * content up to the first type. Once a comment is found, accumulate + * any additional comments up to the stop condition. The stop + * condition is reaching a package declaration, import container, or + * the end of the input. */ - IScanner scanner = ToolFactory.createScanner(true, false, false, false); + IScanner scanner = ToolFactory.createScanner(true, false, false, + false); scanner.setSource(content.toCharArray()); int headerStart = -1; @@ -721,12 +766,15 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, boolean foundComment = false; int terminal = scanner.getNextToken(); while (terminal != ITerminalSymbols.TokenNameEOF - && !(terminal == ITerminalSymbols.TokenNameclass || terminal == ITerminalSymbols.TokenNameinterface || foundComment)) { + && !(terminal == ITerminalSymbols.TokenNameclass + || terminal == ITerminalSymbols.TokenNameinterface || foundComment)) { - if (terminal == ITerminalSymbols.TokenNameCOMMENT_PHPDOC || terminal == ITerminalSymbols.TokenNameCOMMENT_BLOCK + if (terminal == ITerminalSymbols.TokenNameCOMMENT_PHPDOC + || terminal == ITerminalSymbols.TokenNameCOMMENT_BLOCK || terminal == ITerminalSymbols.TokenNameCOMMENT_LINE) { if (!foundComment) - headerStart = scanner.getCurrentTokenStartPosition(); + headerStart = scanner + .getCurrentTokenStartPosition(); headerEnd = scanner.getCurrentTokenEndPosition(); foundComment = true; } @@ -744,7 +792,8 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, return null; } - private Position createProjectionPosition(IRegion region, IJavaElement element) { + private Position createProjectionPosition(IRegion region, + IJavaElement element) { if (fCachedDocument == null) return null; @@ -752,18 +801,21 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, try { int start = fCachedDocument.getLineOfOffset(region.getOffset()); - int end = fCachedDocument.getLineOfOffset(region.getOffset() + region.getLength()); + int end = fCachedDocument.getLineOfOffset(region.getOffset() + + region.getLength()); if (start != end) { int offset = fCachedDocument.getLineOffset(start); int endOffset; if (fCachedDocument.getNumberOfLines() > end + 1) endOffset = fCachedDocument.getLineOffset(end + 1); else if (end > start) - endOffset = fCachedDocument.getLineOffset(end) + fCachedDocument.getLineLength(end); + endOffset = fCachedDocument.getLineOffset(end) + + fCachedDocument.getLineLength(end); else return null; if (element instanceof IMember) - return new JavaElementPosition(offset, endOffset - offset, (IMember) element); + return new JavaElementPosition(offset, endOffset - offset, + (IMember) element); else return new CommentPosition(offset, endOffset - offset); } @@ -782,7 +834,8 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, if ((delta.getFlags() & (IJavaElementDelta.F_CONTENT | IJavaElementDelta.F_CHILDREN)) == 0) return; - ProjectionAnnotationModel model = (ProjectionAnnotationModel) fEditor.getAdapter(ProjectionAnnotationModel.class); + ProjectionAnnotationModel model = (ProjectionAnnotationModel) fEditor + .getAdapter(ProjectionAnnotationModel.class); if (model == null) return; @@ -805,7 +858,8 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, Iterator e = updated.keySet().iterator(); while (e.hasNext()) { - JavaProjectionAnnotation newAnnotation = (JavaProjectionAnnotation) e.next(); + JavaProjectionAnnotation newAnnotation = (JavaProjectionAnnotation) e + .next(); IJavaElement element = newAnnotation.getElement(); Position newPosition = (Position) updated.get(newAnnotation); @@ -821,10 +875,14 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, Tuple tuple = (Tuple) x.next(); JavaProjectionAnnotation existingAnnotation = tuple.annotation; Position existingPosition = tuple.position; - if (newAnnotation.isComment() == existingAnnotation.isComment()) { - if (existingPosition != null && (!newPosition.equals(existingPosition))) { - existingPosition.setOffset(newPosition.getOffset()); - existingPosition.setLength(newPosition.getLength()); + if (newAnnotation.isComment() == existingAnnotation + .isComment()) { + if (existingPosition != null + && (!newPosition.equals(existingPosition))) { + existingPosition.setOffset(newPosition + .getOffset()); + existingPosition.setLength(newPosition + .getLength()); updates.add(existingAnnotation); } matched = true; @@ -868,10 +926,10 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, /** * Matches deleted annotations to changed or added ones. A deleted - * annotation/position tuple that has a matching addition / change is updated - * and marked as changed. The matching tuple is not added (for additions) or - * marked as deletion instead (for changes). The result is that more - * annotations are changed and fewer get deleted/re-added. + * annotation/position tuple that has a matching addition / change is + * updated and marked as changed. The matching tuple is not added (for + * additions) or marked as deletion instead (for changes). The result is + * that more annotations are changed and fewer get deleted/re-added. */ private void match(List deletions, Map additions, List changes) { if (deletions.isEmpty() || (additions.isEmpty() && changes.isEmpty())) @@ -882,7 +940,8 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, Iterator deletionIterator = deletions.iterator(); while (deletionIterator.hasNext()) { - JavaProjectionAnnotation deleted = (JavaProjectionAnnotation) deletionIterator.next(); + JavaProjectionAnnotation deleted = (JavaProjectionAnnotation) deletionIterator + .next(); Position deletedPosition = fCachedModel.getPosition(deleted); if (deletedPosition == null) continue; @@ -900,7 +959,8 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, IJavaElement element = match.annotation.getElement(); deleted.setElement(element); deletedPosition.setLength(match.position.getLength()); - if (deletedPosition instanceof JavaElementPosition && element instanceof IMember) { + if (deletedPosition instanceof JavaElementPosition + && element instanceof IMember) { JavaElementPosition jep = (JavaElementPosition) deletedPosition; jep.setMember((IMember) element); } @@ -918,35 +978,38 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, } /** - * Finds a match for tuple in a collection of annotations. The - * positions for the JavaProjectionAnnotation instances in - * annotations can be found in the passed + * Finds a match for tuple in a collection of annotations. + * The positions for the JavaProjectionAnnotation instances + * in annotations can be found in the passed * positionMap or fCachedModel if * positionMap is null. *

                                                      - * A tuple is said to match another if their annotations have the same comment - * flag and their position offsets are equal. + * A tuple is said to match another if their annotations have the same + * comment flag and their position offsets are equal. *

                                                      *

                                                      * If a match is found, the annotation gets removed from * annotations. *

                                                      - * + * * @param tuple - * the tuple for which we want to find a match + * the tuple for which we want to find a match * @param annotations - * collection of JavaProjectionAnnotation + * collection of JavaProjectionAnnotation * @param positionMap - * a Map<Annotation, Position> or - * null + * a Map<Annotation, Position> or + * null * @return a matching tuple or null for no match */ private Tuple findMatch(Tuple tuple, Collection annotations, Map positionMap) { Iterator it = annotations.iterator(); while (it.hasNext()) { - JavaProjectionAnnotation annotation = (JavaProjectionAnnotation) it.next(); + JavaProjectionAnnotation annotation = (JavaProjectionAnnotation) it + .next(); if (tuple.annotation.isComment() == annotation.isComment()) { - Position position = positionMap == null ? fCachedModel.getPosition(annotation) : (Position) positionMap.get(annotation); + Position position = positionMap == null ? fCachedModel + .getPosition(annotation) : (Position) positionMap + .get(annotation); if (position == null) continue; @@ -980,7 +1043,8 @@ public class DefaultJavaFoldingStructureProvider implements IProjectionListener, Comparator comparator = new Comparator() { public int compare(Object o1, Object o2) { - return ((Tuple) o1).position.getOffset() - ((Tuple) o2).position.getOffset(); + return ((Tuple) o1).position.getOffset() + - ((Tuple) o2).position.getOffset(); } }; for (Iterator it = map.values().iterator(); it.hasNext();) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/EmptyJavaFoldingPreferenceBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/EmptyJavaFoldingPreferenceBlock.java index cfc11fb..5ccaeaa 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/EmptyJavaFoldingPreferenceBlock.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/EmptyJavaFoldingPreferenceBlock.java @@ -19,11 +19,10 @@ import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; - /** * Empty preference block for extensions to the - * net.sourceforge.phpdt.ui.javaFoldingStructureProvider extension - * point that do not specify their own. + * net.sourceforge.phpdt.ui.javaFoldingStructureProvider + * extension point that do not specify their own. * * @since 3.0 */ @@ -32,24 +31,25 @@ class EmptyJavaFoldingPreferenceBlock implements IJavaFoldingPreferenceBlock { * @see net.sourceforge.phpdt.internal.ui.text.folding.IJavaFoldingPreferences#createControl(org.eclipse.swt.widgets.Group) */ public Control createControl(Composite composite) { - Composite inner= new Composite(composite, SWT.NONE); + 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 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.getString("EmptyJavaFoldingPreferenceBlock.emptyCaption")); //$NON-NLS-1$ - gd= new GridData(GridData.CENTER); + + label = new Label(inner, SWT.CENTER); + label.setText(FoldingMessages + .getString("EmptyJavaFoldingPreferenceBlock.emptyCaption")); //$NON-NLS-1$ + gd = new GridData(GridData.CENTER); label.setLayoutData(gd); - label= new Label(inner, SWT.CENTER); - gd= new GridData(GridData.FILL_BOTH); - gd.widthHint= 30; + label = new Label(inner, SWT.CENTER); + gd = new GridData(GridData.FILL_BOTH); + gd.widthHint = 30; label.setLayoutData(gd); - + return inner; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/FoldingMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/FoldingMessages.java index d3be2ca..2f641d3 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/FoldingMessages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/FoldingMessages.java @@ -18,9 +18,10 @@ import java.util.ResourceBundle; */ class FoldingMessages { - private static final String BUNDLE_NAME= FoldingMessages.class.getName(); + private static final String BUNDLE_NAME = FoldingMessages.class.getName(); - private static final ResourceBundle RESOURCE_BUNDLE= ResourceBundle.getBundle(BUNDLE_NAME); + private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle + .getBundle(BUNDLE_NAME); private FoldingMessages() { } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/JavaFoldingStructureProviderDescriptor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/JavaFoldingStructureProviderDescriptor.java index f800cf6..a810ba8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/JavaFoldingStructureProviderDescriptor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/JavaFoldingStructureProviderDescriptor.java @@ -25,58 +25,68 @@ import org.eclipse.jface.text.Assert; 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$ - + + 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 IJavaFoldingStructureProvider. */ private String fClass; + /** * true if the extension specifies a custom * IJavaFoldingPreferenceBlock. */ private boolean fHasPreferences; + /** The configuration element of this extension. */ private IConfigurationElement fElement; - + /** * Creates a new descriptor. * - * @param element the configuration element to read + * @param element + * the configuration element to read */ JavaFoldingStructureProviderDescriptor(IConfigurationElement element) { - fElement= element; - fId= element.getAttributeAsIs(ID); + fElement = element; + fId = element.getAttributeAsIs(ID); Assert.isLegal(fId != null); - - fName= element.getAttribute(NAME); + + fName = element.getAttribute(NAME); if (fName == null) - fName= fId; - - fClass= element.getAttributeAsIs(CLASS); + fName = fId; + + fClass = element.getAttributeAsIs(CLASS); Assert.isLegal(fClass != null); - + if (element.getAttributeAsIs(PREFERENCES_CLASS) == null) - fHasPreferences= false; + fHasPreferences = false; else - fHasPreferences= true; + 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 + * @throws CoreException + * if creation fails */ public IJavaFoldingStructureProvider createProvider() throws CoreException { - IJavaFoldingStructureProvider prov= (IJavaFoldingStructureProvider) fElement.createExecutableExtension(CLASS); + IJavaFoldingStructureProvider prov = (IJavaFoldingStructureProvider) fElement + .createExecutableExtension(CLASS); return prov; } @@ -85,17 +95,19 @@ public final class JavaFoldingStructureProviderDescriptor { * * @return a new instance of the reference provider described by this * descriptor - * @throws CoreException if creation fails + * @throws CoreException + * if creation fails */ public IJavaFoldingPreferenceBlock createPreferences() throws CoreException { if (fHasPreferences) { - IJavaFoldingPreferenceBlock prefs= (IJavaFoldingPreferenceBlock) fElement.createExecutableExtension(PREFERENCES_CLASS); + IJavaFoldingPreferenceBlock prefs = (IJavaFoldingPreferenceBlock) fElement + .createExecutableExtension(PREFERENCES_CLASS); return prefs; } else { return new EmptyJavaFoldingPreferenceBlock(); } } - + /** * Returns the identifier of the described extension. * @@ -104,7 +116,7 @@ public final class JavaFoldingStructureProviderDescriptor { public String getId() { return fId; } - + /** * Returns the name of the described extension. * diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/JavaFoldingStructureProviderRegistry.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/JavaFoldingStructureProviderRegistry.java index 3c2a176..99f7f2f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/JavaFoldingStructureProviderRegistry.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/JavaFoldingStructureProviderRegistry.java @@ -27,21 +27,22 @@ import org.eclipse.core.runtime.Platform; * @since 3.0 */ public class JavaFoldingStructureProviderRegistry { - - private static final String EXTENSION_POINT= "foldingStructureProviders"; //$NON-NLS-1$ - + + 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. + * Creates a new instance. */ public JavaFoldingStructureProviderRegistry() { } - + /** - * Returns an array of IJavaFoldingProviderDescriptor describing - * all extension to the foldingProviders extension point. + * Returns an array of IJavaFoldingProviderDescriptor + * describing all extension to the foldingProviders extension + * point. * * @return the list of extensions to the * quickDiffReferenceProvider extension point. @@ -49,25 +50,32 @@ public class JavaFoldingStructureProviderRegistry { public JavaFoldingStructureProviderDescriptor[] getFoldingProviderDescriptors() { synchronized (this) { ensureRegistered(); - return (JavaFoldingStructureProviderDescriptor[]) fDescriptors.values().toArray(new JavaFoldingStructureProviderDescriptor[fDescriptors.size()]); + return (JavaFoldingStructureProviderDescriptor[]) fDescriptors + .values() + .toArray( + new JavaFoldingStructureProviderDescriptor[fDescriptors + .size()]); } } - + /** * Returns the folding provider with identifier id or * null if no such provider is registered. * - * @param id the identifier for which a provider is wanted + * @param id + * the identifier for which a provider is wanted * @return the corresponding provider, or null if none can be * found */ - public JavaFoldingStructureProviderDescriptor getFoldingProviderDescriptor(String id) { + public JavaFoldingStructureProviderDescriptor getFoldingProviderDescriptor( + String id) { synchronized (this) { ensureRegistered(); - return (JavaFoldingStructureProviderDescriptor) fDescriptors.get(id); + return (JavaFoldingStructureProviderDescriptor) fDescriptors + .get(id); } } - + /** * Instantiates and returns the provider that is currently configured in the * preferences. @@ -75,18 +83,19 @@ public class JavaFoldingStructureProviderRegistry { * @return the current provider according to the preferences */ public IJavaFoldingStructureProvider getCurrentFoldingProvider() { - String id= PHPeclipsePlugin.getDefault().getPreferenceStore().getString(PreferenceConstants.EDITOR_FOLDING_PROVIDER); - JavaFoldingStructureProviderDescriptor desc= getFoldingProviderDescriptor(id); + String id = PHPeclipsePlugin.getDefault().getPreferenceStore() + .getString(PreferenceConstants.EDITOR_FOLDING_PROVIDER); + JavaFoldingStructureProviderDescriptor desc = getFoldingProviderDescriptor(id); if (desc != null) { try { return desc.createProvider(); } catch (CoreException e) { - PHPeclipsePlugin.log(e); + PHPeclipsePlugin.log(e); } } return null; } - + /** * Ensures that the extensions are read and stored in * fDescriptors. @@ -99,22 +108,25 @@ public class JavaFoldingStructureProviderRegistry { /** * Reads all extensions. *

                                                      - * This method can be called more than once in - * order to reload from a changed extension registry. + * This method can be called more than once in order to reload from a + * changed extension registry. *

                                                      */ public void reloadExtensions() { - IExtensionRegistry registry= Platform.getExtensionRegistry(); - Map map= new HashMap(); + IExtensionRegistry registry = Platform.getExtensionRegistry(); + Map map = new HashMap(); - IConfigurationElement[] elements= registry.getConfigurationElementsFor(PHPeclipsePlugin.getPluginId(), EXTENSION_POINT); - for (int i= 0; i < elements.length; i++) { - JavaFoldingStructureProviderDescriptor desc= new JavaFoldingStructureProviderDescriptor(elements[i]); + IConfigurationElement[] elements = registry + .getConfigurationElementsFor(PHPeclipsePlugin.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); + + synchronized (this) { + fDescriptors = Collections.unmodifiableMap(map); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IInvocationContext.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IInvocationContext.java index 4b637b1..ca5dec2 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IInvocationContext.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IInvocationContext.java @@ -1,4 +1,4 @@ - /******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 @@ -13,13 +13,12 @@ package net.sourceforge.phpdt.internal.ui.text.java; import net.sourceforge.phpdt.core.ICompilationUnit; import net.sourceforge.phpdt.core.dom.CompilationUnit; - /** * Context information for quick fix and quick assist processors. *

                                                      * Note: this interface is not intended to be implemented. *

                                                      - * + * * @since 3.0 */ public interface IInvocationContext { @@ -33,32 +32,38 @@ public interface IInvocationContext { * @return Returns the offset of the current selection */ int getSelectionOffset(); - + /** * @return Returns the length of the current selection */ int getSelectionLength(); - + /** - * Returns an AST of the compilation unit, possibly only a partial AST focused on the selection - * offset (see {@link net.sourceforge.phpdt.core.dom.ASTParser#setFocalPosition(int)}). - * The returned AST is shared and therefore protected and cannot be modified. - * The client must check the AST API level and do nothing if they are given an AST - * they can't handle. (see {@link net.sourceforge.phpdt.core.dom.AST#apiLevel()}). - * @return Returns the root of the AST corresponding to the current compilation unit. + * Returns an AST of the compilation unit, possibly only a partial AST + * focused on the selection offset (see + * {@link net.sourceforge.phpdt.core.dom.ASTParser#setFocalPosition(int)}). + * The returned AST is shared and therefore protected and cannot be + * modified. The client must check the AST API level and do nothing if they + * are given an AST they can't handle. (see + * {@link net.sourceforge.phpdt.core.dom.AST#apiLevel()}). + * + * @return Returns the root of the AST corresponding to the current + * compilation unit. */ CompilationUnit getASTRoot(); - + /** - * Convenience method to evaluate the AST node covering the current selection. + * Convenience method to evaluate the AST node covering the current + * selection. + * * @return Returns the node that covers the location of the problem */ -// ASTNode getCoveringNode(); - + // ASTNode getCoveringNode(); /** - * Convenience method to evaluate the AST node that is covered by the current selection. + * Convenience method to evaluate the AST node that is covered by the + * current selection. + * * @return Returns the node that is covered by the location of the problem - */ -// ASTNode getCoveredNode(); - + */ + // ASTNode getCoveredNode(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IJavaReconcilingListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IJavaReconcilingListener.java index dc67cf5..12aad9a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IJavaReconcilingListener.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IJavaReconcilingListener.java @@ -14,7 +14,6 @@ import net.sourceforge.phpdt.core.dom.CompilationUnit; import org.eclipse.core.runtime.IProgressMonitor; - /** * Interface of an object listening to Java reconciling. * @@ -26,13 +25,18 @@ public interface IJavaReconcilingListener { * Called before reconciling is started. */ void aboutToBeReconciled(); - + /** * Called after reconciling has been finished. - * @param ast the compilation unit AST or null if - * the working copy was consistent or reconciliation has been cancelled - * @param forced true iff this reconciliation was forced - * @param progressMonitor the progress monitor + * + * @param ast + * the compilation unit AST or null if the working + * copy was consistent or reconciliation has been cancelled + * @param forced + * true iff this reconciliation was forced + * @param progressMonitor + * the progress monitor */ - void reconciled(CompilationUnit ast, boolean forced, IProgressMonitor progressMonitor); + void reconciled(CompilationUnit ast, boolean forced, + IProgressMonitor progressMonitor); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IPHPCompletionProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IPHPCompletionProposal.java index 44ae14e..98ae9ba 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IPHPCompletionProposal.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IPHPCompletionProposal.java @@ -14,12 +14,12 @@ package net.sourceforge.phpdt.internal.ui.text.java; import org.eclipse.jface.text.contentassist.ICompletionProposal; /* - * CompletionProposal with a relevance value. - * The relevance value is used to sort the completion proposals. Proposals with higher relevance - * should be listed before proposals with lower relevance. + * CompletionProposal with a relevance value. The relevance value is used to + * sort the completion proposals. Proposals with higher relevance should be + * listed before proposals with lower relevance. */ public interface IPHPCompletionProposal extends ICompletionProposal { - + /** * Returns the relevance of the proposal. */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IProblemRequestorExtension.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IProblemRequestorExtension.java index a5af585..b9dcb85 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IProblemRequestorExtension.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IProblemRequestorExtension.java @@ -10,40 +10,41 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.ui.text.java; - import org.eclipse.core.runtime.IProgressMonitor; - /** * Extension to IProblemRequestor. */ public interface IProblemRequestorExtension { - + /** * Sets the progress monitor to this problem requestor. * - * @param monitor the progress monitor to be used + * @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 + * @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 beginReporting and - * endReporting can appear. + * Informs the problem requestor that a sequence of reportings is about to + * start. While a sequence is active, multiple peering calls of + * beginReporting and endReporting can appear. * * @since 3.0 */ void beginReportingSequence(); - + /** - * Informs the problem requestor that the sequence of reportings has been finished. + * Informs the problem requestor that the sequence of reportings has been + * finished. * * @since 3.0 */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IReconcilingParticipant.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IReconcilingParticipant.java index 96f9563..9878725 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IReconcilingParticipant.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IReconcilingParticipant.java @@ -5,13 +5,11 @@ package net.sourceforge.phpdt.internal.ui.text.java; * All Rights Reserved. */ - - /** * Interface of an object participating in reconciling. */ public interface IReconcilingParticipant { - + /** * Called after reconciling has been finished. */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaFormattingStrategy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaFormattingStrategy.java index 56ba202..0fd345d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaFormattingStrategy.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaFormattingStrategy.java @@ -15,43 +15,43 @@ import org.eclipse.jface.text.source.ISourceViewer; public class JavaFormattingStrategy implements IFormattingStrategy { - private String fInitialIndentation; - - private ISourceViewer fViewer; - - public JavaFormattingStrategy(ISourceViewer viewer) { - fViewer = viewer; - } - - /** - * @see IFormattingStrategy#formatterStarts(String) - */ - public void formatterStarts(String initialIndentation) { - fInitialIndentation = initialIndentation; - } - - /** - * @see IFormattingStrategy#formatterStops() - */ - public void formatterStops() { - } - - /** - * @see IFormattingStrategy#format(String, boolean, String, int[]) - */ - public String format(String content, boolean isLineStart, String indentation, - int[] positions) { - ICodeFormatter formatter = ToolFactory.createCodeFormatter(); - - IDocument doc = fViewer.getDocument(); - String lineDelimiter = StubUtility.getLineDelimiterFor(doc); - - int indent = 0; - if (fInitialIndentation != null) { - indent = Strings.computeIndent(fInitialIndentation, - CodeFormatterPreferencePage.getTabSize()); - } - - return formatter.format(content, indent, positions, lineDelimiter); - } + private String fInitialIndentation; + + private ISourceViewer fViewer; + + public JavaFormattingStrategy(ISourceViewer viewer) { + fViewer = viewer; + } + + /** + * @see IFormattingStrategy#formatterStarts(String) + */ + public void formatterStarts(String initialIndentation) { + fInitialIndentation = initialIndentation; + } + + /** + * @see IFormattingStrategy#formatterStops() + */ + public void formatterStops() { + } + + /** + * @see IFormattingStrategy#format(String, boolean, String, int[]) + */ + public String format(String content, boolean isLineStart, + String indentation, int[] positions) { + ICodeFormatter formatter = ToolFactory.createCodeFormatter(); + + IDocument doc = fViewer.getDocument(); + String lineDelimiter = StubUtility.getLineDelimiterFor(doc); + + int indent = 0; + if (fInitialIndentation != null) { + indent = Strings.computeIndent(fInitialIndentation, + CodeFormatterPreferencePage.getTabSize()); + } + + return formatter.format(content, indent, positions, lineDelimiter); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaHoverMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaHoverMessages.java index c4f9335..bedafbc 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaHoverMessages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaHoverMessages.java @@ -16,9 +16,11 @@ import java.util.ResourceBundle; class JavaHoverMessages { - private static final String RESOURCE_BUNDLE= JavaHoverMessages.class.getName(); + private static final String RESOURCE_BUNDLE = JavaHoverMessages.class + .getName(); - private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); + private static ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); private JavaHoverMessages() { } @@ -30,53 +32,58 @@ class JavaHoverMessages { return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$ } } + /** * Gets a string from the resource bundle and formats it with the argument * - * @param key the string used to get the bundle value, must not be null + * @param key + * the string used to get the bundle value, must not be null * @since 3.0 */ public static String getFormattedString(String key, Object arg) { - String format= null; + String format = null; try { - format= fgResourceBundle.getString(key); + format = fgResourceBundle.getString(key); } catch (MissingResourceException e) { return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$ } if (arg == null) - arg= ""; //$NON-NLS-1$ + arg = ""; //$NON-NLS-1$ return MessageFormat.format(format, new Object[] { arg }); } + /** * Gets a string from the resource bundle and formats it with the arguments * - * @param key the string used to get the bundle value, must not be null + * @param key + * the string used to get the bundle value, must not be null * @since 3.0 */ public static String getFormattedString(String key, Object arg1, Object arg2) { - String format= null; + String format = null; try { - format= fgResourceBundle.getString(key); + format = fgResourceBundle.getString(key); } catch (MissingResourceException e) { return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$ } if (arg1 == null) - arg1= ""; //$NON-NLS-1$ + arg1 = ""; //$NON-NLS-1$ if (arg2 == null) - arg2= ""; //$NON-NLS-1$ + arg2 = ""; //$NON-NLS-1$ return MessageFormat.format(format, new Object[] { arg1, arg2 }); } - + /** * Gets a string from the resource bundle and formats it with the argument * - * @param key the string used to get the bundle value, must not be null + * @param key + * the string used to get the bundle value, must not be null * @since 3.0 */ public static String getFormattedString(String key, boolean arg) { - String format= null; + String format = null; try { - format= fgResourceBundle.getString(key); + format = fgResourceBundle.getString(key); } catch (MissingResourceException e) { return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$ } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaParameterListValidator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaParameterListValidator.java index 82a09e9..71bf6ff 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaParameterListValidator.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaParameterListValidator.java @@ -10,10 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.ui.text.java; - -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.StyleRange; - import org.eclipse.jface.text.Assert; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; @@ -23,37 +19,42 @@ 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; - - -public class JavaParameterListValidator implements IContextInformationValidator, IContextInformationPresenter { +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) + * @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; + public void install(IContextInformation info, ITextViewer viewer, + int documentPosition) { + fPosition = documentPosition; + fViewer = viewer; + fInformation = info; - fCurrentParameter= -1; + fCurrentParameter = -1; } - private int getCommentEnd(IDocument d, int pos, int end) throws BadLocationException { + private int getCommentEnd(IDocument d, int pos, int end) + throws BadLocationException { while (pos < end) { - char curr= d.getChar(pos); + char curr = d.getChar(pos); pos++; if (curr == '*') { if (pos < end && d.getChar(pos) == '/') { @@ -64,9 +65,10 @@ public class JavaParameterListValidator implements IContextInformationValidator, return end; } - private int getStringEnd(IDocument d, int pos, int end, char ch) throws BadLocationException { + private int getStringEnd(IDocument d, int pos, int end, char ch) + throws BadLocationException { while (pos < end) { - char curr= d.getChar(pos); + char curr = d.getChar(pos); pos++; if (curr == '\\') { // ignore escaped characters @@ -78,61 +80,64 @@ public class JavaParameterListValidator implements IContextInformationValidator, return end; } - private int getCharCount(IDocument document, int start, int end, String increments, String decrements, boolean considerNesting) throws BadLocationException { + private int getCharCount(IDocument document, int start, int end, + String increments, String decrements, boolean considerNesting) + throws BadLocationException { - Assert.isTrue((increments.length() != 0 || decrements.length() != 0) && !increments.equals(decrements)); + Assert.isTrue((increments.length() != 0 || decrements.length() != 0) + && !increments.equals(decrements)); - int nestingLevel= 0; - int charCount= 0; + int nestingLevel = 0; + int charCount = 0; while (start < end) { - char curr= document.getChar(start++); + char curr = document.getChar(start++); switch (curr) { - case '/': - if (start < end) { - char next= document.getChar(start); - if (next == '*') { - // a comment starts, advance to the comment end - start= getCommentEnd(document, start + 1, end); - } else if (next == '/') { - // '//'-comment: nothing to do anymore on this line - start= end; - } - } - break; - case '*': - if (start < end) { - char next= document.getChar(start); - if (next == '/') { - // we have been in a comment: forget what we read before - charCount= 0; - ++ start; - } + case '/': + if (start < end) { + char next = document.getChar(start); + if (next == '*') { + // a comment starts, advance to the comment end + start = getCommentEnd(document, start + 1, end); + } else if (next == '/') { + // '//'-comment: nothing to do anymore on this line + start = end; } - break; - case '"': - case '\'': - start= getStringEnd(document, start, end, curr); - break; - default: - - if (considerNesting) { - - if ('(' == curr) - ++ nestingLevel; - else if (')' == curr) - -- nestingLevel; - - if (nestingLevel != 0) - break; + } + break; + case '*': + if (start < end) { + char next = document.getChar(start); + if (next == '/') { + // we have been in a comment: forget what we read before + charCount = 0; + ++start; } + } + break; + case '"': + case '\'': + start = getStringEnd(document, start, end, curr); + break; + default: - if (increments.indexOf(curr) >= 0) { - ++ charCount; - } + if (considerNesting) { - if (decrements.indexOf(curr) >= 0) { - -- charCount; - } + if ('(' == curr) + ++nestingLevel; + else if (')' == curr) + --nestingLevel; + + if (nestingLevel != 0) + break; + } + + if (increments.indexOf(curr) >= 0) { + ++charCount; + } + + if (decrements.indexOf(curr) >= 0) { + --charCount; + } } } @@ -148,13 +153,14 @@ public class JavaParameterListValidator implements IContextInformationValidator, if (position < fPosition) return false; - IDocument document= fViewer.getDocument(); - IRegion line= document.getLineInformationOfOffset(fPosition); + 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$ + return getCharCount(document, fPosition, position, + "(<", ")>", false) >= 0; //$NON-NLS-1$//$NON-NLS-2$ } catch (BadLocationException x) { return false; @@ -162,14 +168,17 @@ public class JavaParameterListValidator implements IContextInformationValidator, } /** - * @see IContextInformationPresenter#updatePresentation(int, TextPresentation) + * @see IContextInformationPresenter#updatePresentation(int, + * TextPresentation) */ - public boolean updatePresentation(int position, TextPresentation presentation) { + public boolean updatePresentation(int position, + TextPresentation presentation) { - int currentParameter= -1; + int currentParameter = -1; try { - currentParameter= getCharCount(fViewer.getDocument(), fPosition, position, ",", "", true); //$NON-NLS-1$//$NON-NLS-2$ + currentParameter = getCharCount(fViewer.getDocument(), fPosition, + position, ",", "", true); //$NON-NLS-1$//$NON-NLS-2$ } catch (BadLocationException x) { return false; } @@ -180,41 +189,44 @@ public class JavaParameterListValidator implements IContextInformationValidator, } presentation.clear(); - fCurrentParameter= currentParameter; + fCurrentParameter = currentParameter; - String s= fInformation.getInformationDisplayString(); - int start= 0; - int occurrences= 0; + String s = fInformation.getInformationDisplayString(); + int start = 0; + int occurrences = 0; while (occurrences < fCurrentParameter) { - int found= s.indexOf(',', start); + int found = s.indexOf(',', start); if (found == -1) break; - start= found + 1; - ++ occurrences; + start = found + 1; + ++occurrences; } if (occurrences < fCurrentParameter) { - presentation.addStyleRange(new StyleRange(0, s.length(), null, null, SWT.NORMAL)); + presentation.addStyleRange(new StyleRange(0, s.length(), null, + null, SWT.NORMAL)); return true; } if (start == -1) - start= 0; + start = 0; - int end= s.indexOf(',', start); + int end = s.indexOf(',', start); if (end == -1) - end= s.length(); + end = s.length(); if (start > 0) - presentation.addStyleRange(new StyleRange(0, start, null, null, SWT.NORMAL)); + presentation.addStyleRange(new StyleRange(0, start, null, null, + SWT.NORMAL)); if (end > start) - presentation.addStyleRange(new StyleRange(start, end - start, null, null, SWT.BOLD)); + 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)); + presentation.addStyleRange(new StyleRange(end, s.length() - end, + null, null, SWT.NORMAL)); return true; } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaReconcilingStrategy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaReconcilingStrategy.java index 8294154..fe21bcd 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaReconcilingStrategy.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaReconcilingStrategy.java @@ -24,184 +24,194 @@ import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.ITextEditor; -public class JavaReconcilingStrategy implements IReconcilingStrategy, IReconcilingStrategyExtension { - - private ITextEditor fEditor; - - private IWorkingCopyManager fManager; - - private IDocumentProvider fDocumentProvider; - - private IProgressMonitor fProgressMonitor; - - private boolean fNotify = true; - - private IJavaReconcilingListener fJavaReconcilingListener; - - private boolean fIsJavaReconcilingListener; - - public JavaReconcilingStrategy(ITextEditor editor) { - fEditor = editor; - fManager = PHPeclipsePlugin.getDefault().getWorkingCopyManager(); - fDocumentProvider = PHPeclipsePlugin.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() { - // // try { - // - // /* fix for missing cancel flag communication */ - // IProblemRequestorExtension extension = getProblemRequestorExtension(); - // if (extension != null) - // extension.setProgressMonitor(fProgressMonitor); - // - // // reconcile - //// synchronized (unit) { - //// unit.reconcile(true, fProgressMonitor); - //// } - // - // Parser parser = new Parser(); - // parser.initializeScanner(); - // // actualParser.setFileToParse(fileToParse); - // String text = fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput()).get(); - // parser.init(text); - // parser.reportSyntaxError(); - //// checkAndReportBracketAnomalies(parser.problemReporter()); - // - // /* fix for missing cancel flag communication */ - // if (extension != null) - // extension.setProgressMonitor(null); - // - // // update participants - // try { - // if (fEditor instanceof IReconcilingParticipant && fNotify && !fProgressMonitor.isCanceled()) { - // IReconcilingParticipant p = (IReconcilingParticipant) fEditor; - // p.reconciled(); - // } - // } finally { - // fNotify = true; - // } - - // JDT implementation: - try { - ICompilationUnit unit = fManager.getWorkingCopy(fEditor.getEditorInput()); - if (unit != null) { - try { - - /* fix for missing cancel flag communication */ - IProblemRequestorExtension extension = getProblemRequestorExtension(); - if (extension != null) - extension.setProgressMonitor(fProgressMonitor); - - // reconcile - synchronized (unit) { - unit.reconcile(true, fProgressMonitor); - } - - /* fix for missing cancel flag communication */ - if (extension != null) - extension.setProgressMonitor(null); - - // update participants - try { - if (fEditor instanceof IReconcilingParticipant && fNotify && !fProgressMonitor.isCanceled()) { - IReconcilingParticipant p = (IReconcilingParticipant) fEditor; - p.reconciled(); - } - } finally { - fNotify = true; - } - - } catch (JavaModelException x) { - // swallow exception - } - } - } 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(null, !fNotify, pm); - } - } finally { - fNotify = true; - } - - } - } - - /* - * @see IReconcilingStrategy#reconcile(IRegion) - */ - public void reconcile(IRegion partition) { - reconcile(); - } - - /* - * @see IReconcilingStrategy#reconcile(DirtyRegion, IRegion) - */ - public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) { - reconcile(); - } - - /* - * @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(); - } - - /** - * Tells this strategy whether to inform its participants. - * - * @param notify - * true if participant should be notified - */ - public void notifyParticipants(boolean notify) { - fNotify = notify; - } - - /** - * Tells this strategy whether to inform its listeners. - * - * @param notify - * true if listeners should be notified - */ - public void notifyListeners(boolean notify) { - fNotify = notify; - } - - /** - * Called before reconciling is started. - * - * @since 3.0 - */ - public void aboutToBeReconciled() { - if (fIsJavaReconcilingListener) - fJavaReconcilingListener.aboutToBeReconciled(); - } +public class JavaReconcilingStrategy implements IReconcilingStrategy, + IReconcilingStrategyExtension { + + private ITextEditor fEditor; + + private IWorkingCopyManager fManager; + + private IDocumentProvider fDocumentProvider; + + private IProgressMonitor fProgressMonitor; + + private boolean fNotify = true; + + private IJavaReconcilingListener fJavaReconcilingListener; + + private boolean fIsJavaReconcilingListener; + + public JavaReconcilingStrategy(ITextEditor editor) { + fEditor = editor; + fManager = PHPeclipsePlugin.getDefault().getWorkingCopyManager(); + fDocumentProvider = PHPeclipsePlugin.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() { + // // try { + // + // /* fix for missing cancel flag communication */ + // IProblemRequestorExtension extension = + // getProblemRequestorExtension(); + // if (extension != null) + // extension.setProgressMonitor(fProgressMonitor); + // + // // reconcile + // // synchronized (unit) { + // // unit.reconcile(true, fProgressMonitor); + // // } + // + // Parser parser = new Parser(); + // parser.initializeScanner(); + // // actualParser.setFileToParse(fileToParse); + // String text = + // fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput()).get(); + // parser.init(text); + // parser.reportSyntaxError(); + // // checkAndReportBracketAnomalies(parser.problemReporter()); + // + // /* fix for missing cancel flag communication */ + // if (extension != null) + // extension.setProgressMonitor(null); + // + // // update participants + // try { + // if (fEditor instanceof IReconcilingParticipant && fNotify && + // !fProgressMonitor.isCanceled()) { + // IReconcilingParticipant p = (IReconcilingParticipant) fEditor; + // p.reconciled(); + // } + // } finally { + // fNotify = true; + // } + + // JDT implementation: + try { + ICompilationUnit unit = fManager.getWorkingCopy(fEditor + .getEditorInput()); + if (unit != null) { + try { + + /* fix for missing cancel flag communication */ + IProblemRequestorExtension extension = getProblemRequestorExtension(); + if (extension != null) + extension.setProgressMonitor(fProgressMonitor); + + // reconcile + synchronized (unit) { + unit.reconcile(true, fProgressMonitor); + } + + /* fix for missing cancel flag communication */ + if (extension != null) + extension.setProgressMonitor(null); + + // update participants + try { + if (fEditor instanceof IReconcilingParticipant + && fNotify && !fProgressMonitor.isCanceled()) { + IReconcilingParticipant p = (IReconcilingParticipant) fEditor; + p.reconciled(); + } + } finally { + fNotify = true; + } + + } catch (JavaModelException x) { + // swallow exception + } + } + } 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(null, !fNotify, pm); + } + } finally { + fNotify = true; + } + + } + } + + /* + * @see IReconcilingStrategy#reconcile(IRegion) + */ + public void reconcile(IRegion partition) { + reconcile(); + } + + /* + * @see IReconcilingStrategy#reconcile(DirtyRegion, IRegion) + */ + public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) { + reconcile(); + } + + /* + * @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(); + } + + /** + * Tells this strategy whether to inform its participants. + * + * @param notify + * true if participant should be notified + */ + public void notifyParticipants(boolean notify) { + fNotify = notify; + } + + /** + * Tells this strategy whether to inform its listeners. + * + * @param notify + * true if listeners should be notified + */ + public void notifyListeners(boolean notify) { + fNotify = notify; + } + + /** + * Called before reconciling is started. + * + * @since 3.0 + */ + public void aboutToBeReconciled() { + if (fIsJavaReconcilingListener) + fJavaReconcilingListener.aboutToBeReconciled(); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaStringAutoIndentStrategyDQ.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaStringAutoIndentStrategyDQ.java index 1b59ee6..14dff9c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaStringAutoIndentStrategyDQ.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaStringAutoIndentStrategyDQ.java @@ -25,26 +25,29 @@ import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.texteditor.ITextEditorExtension3; - /** * Auto indent strategy for java strings */ -public class JavaStringAutoIndentStrategyDQ extends DefaultIndentLineAutoEditStrategy { +public class JavaStringAutoIndentStrategyDQ extends + DefaultIndentLineAutoEditStrategy { private String fPartitioning; /** * The input string doesn't contain any line delimiter. * - * @param inputString the given input string + * @param inputString + * the given input string * @return the displayable string. */ - private String displayString(String inputString, String indentation, String delimiter) { + 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()){ + 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$ @@ -74,36 +77,36 @@ public class JavaStringAutoIndentStrategyDQ extends DefaultIndentLineAutoEditStr } StringBuffer tokenBuffer = new StringBuffer(); - for (int i = 0; i < token.length(); i++){ + 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); + 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); @@ -112,75 +115,90 @@ public class JavaStringAutoIndentStrategyDQ extends DefaultIndentLineAutoEditStr } /** - * Creates a new Java string auto indent strategy for the given document partitioning. + * Creates a new Java string auto indent strategy for the given document + * partitioning. * - * @param partitioning the document partitioning + * @param partitioning + * the document partitioning */ public JavaStringAutoIndentStrategyDQ(String partitioning) { super(); - fPartitioning= partitioning; + fPartitioning = partitioning; } private boolean isLineDelimiter(IDocument document, String text) { - String[] delimiters= document.getLegalLineDelimiters(); + String[] delimiters = document.getLegalLineDelimiters(); if (delimiters != null) return TextUtilities.equals(delimiters, text) > -1; return false; } - private String getLineIndentation(IDocument document, int offset) throws BadLocationException { + 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(); + 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); + int end = findEndOfWhiteSpace(document, start, offset); return document.get(start, end - start); } - private String getModifiedText(String string, String indentation, String delimiter) throws BadLocationException { + private String getModifiedText(String string, String indentation, + String delimiter) throws BadLocationException { return displayString(string, indentation, delimiter); } - private void javaStringIndentAfterNewLine(IDocument document, DocumentCommand command) throws BadLocationException { + private void javaStringIndentAfterNewLine(IDocument document, + DocumentCommand command) throws BadLocationException { - ITypedRegion partition= TextUtilities.getPartition(document, fPartitioning, command.offset, false); - int offset= partition.getOffset(); - int length= partition.getLength(); + ITypedRegion partition = TextUtilities.getPartition(document, + fPartitioning, command.offset, false); + int offset = partition.getOffset(); + int length = partition.getLength(); if (command.offset == offset) { - // we are really just before the string partition -> feet the event through the java indenter - // new JavaAutoIndentStrategy(fPartitioning).customizeDocumentCommand(document, command); + // we are really just before the string partition -> feet the event + // through the java indenter + // new + // JavaAutoIndentStrategy(fPartitioning).customizeDocumentCommand(document, + // command); return; } - if (command.offset == offset + length && document.getChar(offset + length - 1) == '\"') + if (command.offset == offset + length + && document.getChar(offset + length - 1) == '\"') return; - String indentation= getLineIndentation(document, command.offset); - String delimiter= TextUtilities.getDefaultLineDelimiter(document); + 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()); + 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= PHPeclipsePlugin.getDefault().getPreferenceStore(); + IPreferenceStore preferenceStore = PHPeclipsePlugin.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_DQ)) - command.text= getModifiedText(command.text, indentation, delimiter); + command.text = "\" ." + command.text + indentation + "\""; //$NON-NLS-1$//$NON-NLS-2$ + else if (command.text.length() > 1 + && preferenceStore + .getBoolean(PreferenceConstants.EDITOR_ESCAPE_STRINGS_DQ)) + command.text = getModifiedText(command.text, indentation, delimiter); } private boolean isSmartMode() { - IWorkbenchPage page= PHPeclipsePlugin.getActivePage(); - if (page != null) { - IEditorPart part= page.getActiveEditor(); + IWorkbenchPage page = PHPeclipsePlugin.getActivePage(); + if (page != null) { + IEditorPart part = page.getActiveEditor(); if (part instanceof ITextEditorExtension3) { - ITextEditorExtension3 extension= (ITextEditorExtension3) part; + ITextEditorExtension3 extension = (ITextEditorExtension3) part; return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT; } } @@ -188,16 +206,21 @@ public class JavaStringAutoIndentStrategyDQ extends DefaultIndentLineAutoEditStr } /* - * @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(IDocument, DocumentCommand) + * @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(IDocument, + * DocumentCommand) */ - public void customizeDocumentCommand(IDocument document, DocumentCommand command) { + public void customizeDocumentCommand(IDocument document, + DocumentCommand command) { try { if (command.length != 0 || command.text == null) return; - IPreferenceStore preferenceStore= PHPeclipsePlugin.getDefault().getPreferenceStore(); + IPreferenceStore preferenceStore = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); - if (preferenceStore.getBoolean(PreferenceConstants.EDITOR_WRAP_STRINGS_DQ) && isSmartMode()) + if (preferenceStore + .getBoolean(PreferenceConstants.EDITOR_WRAP_STRINGS_DQ) + && isSmartMode()) javaStringIndentAfterNewLine(document, command); } catch (BadLocationException e) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaStringAutoIndentStrategySQ.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaStringAutoIndentStrategySQ.java index 3cc2044..d58f57b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaStringAutoIndentStrategySQ.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaStringAutoIndentStrategySQ.java @@ -25,26 +25,29 @@ import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.texteditor.ITextEditorExtension3; - /** * Auto indent strategy for java strings */ -public class JavaStringAutoIndentStrategySQ extends DefaultIndentLineAutoEditStrategy { +public class JavaStringAutoIndentStrategySQ extends + DefaultIndentLineAutoEditStrategy { private String fPartitioning; /** * The input string doesn't contain any line delimiter. * - * @param inputString the given input string + * @param inputString + * the given input string * @return the displayable string. */ - private String displayString(String inputString, String indentation, String delimiter) { + 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()){ + 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$ @@ -74,36 +77,36 @@ public class JavaStringAutoIndentStrategySQ extends DefaultIndentLineAutoEditStr } StringBuffer tokenBuffer = new StringBuffer(); - for (int i = 0; i < token.length(); i++){ + 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); + 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); @@ -112,75 +115,90 @@ public class JavaStringAutoIndentStrategySQ extends DefaultIndentLineAutoEditStr } /** - * Creates a new Java string auto indent strategy for the given document partitioning. + * Creates a new Java string auto indent strategy for the given document + * partitioning. * - * @param partitioning the document partitioning + * @param partitioning + * the document partitioning */ public JavaStringAutoIndentStrategySQ(String partitioning) { super(); - fPartitioning= partitioning; + fPartitioning = partitioning; } private boolean isLineDelimiter(IDocument document, String text) { - String[] delimiters= document.getLegalLineDelimiters(); + String[] delimiters = document.getLegalLineDelimiters(); if (delimiters != null) return TextUtilities.equals(delimiters, text) > -1; return false; } - private String getLineIndentation(IDocument document, int offset) throws BadLocationException { + 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(); + 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); + int end = findEndOfWhiteSpace(document, start, offset); return document.get(start, end - start); } - private String getModifiedText(String string, String indentation, String delimiter) throws BadLocationException { + private String getModifiedText(String string, String indentation, + String delimiter) throws BadLocationException { return displayString(string, indentation, delimiter); } - private void javaStringIndentAfterNewLine(IDocument document, DocumentCommand command) throws BadLocationException { + private void javaStringIndentAfterNewLine(IDocument document, + DocumentCommand command) throws BadLocationException { - ITypedRegion partition= TextUtilities.getPartition(document, fPartitioning, command.offset, false); - int offset= partition.getOffset(); - int length= partition.getLength(); + ITypedRegion partition = TextUtilities.getPartition(document, + fPartitioning, command.offset, false); + int offset = partition.getOffset(); + int length = partition.getLength(); if (command.offset == offset) { - // we are really just before the string partition -> feet the event through the java indenter - // new JavaAutoIndentStrategy(fPartitioning).customizeDocumentCommand(document, command); + // we are really just before the string partition -> feet the event + // through the java indenter + // new + // JavaAutoIndentStrategy(fPartitioning).customizeDocumentCommand(document, + // command); return; } - if (command.offset == offset + length && document.getChar(offset + length - 1) == '\'') + if (command.offset == offset + length + && document.getChar(offset + length - 1) == '\'') return; - String indentation= getLineIndentation(document, command.offset); - String delimiter= TextUtilities.getDefaultLineDelimiter(document); + 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()); + 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= PHPeclipsePlugin.getDefault().getPreferenceStore(); + IPreferenceStore preferenceStore = PHPeclipsePlugin.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_SQ)) - command.text= getModifiedText(command.text, indentation, delimiter); + command.text = "\' ." + command.text + indentation + "\'"; //$NON-NLS-1$//$NON-NLS-2$ + else if (command.text.length() > 1 + && preferenceStore + .getBoolean(PreferenceConstants.EDITOR_ESCAPE_STRINGS_SQ)) + command.text = getModifiedText(command.text, indentation, delimiter); } private boolean isSmartMode() { - IWorkbenchPage page= PHPeclipsePlugin.getActivePage(); - if (page != null) { - IEditorPart part= page.getActiveEditor(); + IWorkbenchPage page = PHPeclipsePlugin.getActivePage(); + if (page != null) { + IEditorPart part = page.getActiveEditor(); if (part instanceof ITextEditorExtension3) { - ITextEditorExtension3 extension= (ITextEditorExtension3) part; + ITextEditorExtension3 extension = (ITextEditorExtension3) part; return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT; } } @@ -188,16 +206,21 @@ public class JavaStringAutoIndentStrategySQ extends DefaultIndentLineAutoEditStr } /* - * @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(IDocument, DocumentCommand) + * @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(IDocument, + * DocumentCommand) */ - public void customizeDocumentCommand(IDocument document, DocumentCommand command) { + public void customizeDocumentCommand(IDocument document, + DocumentCommand command) { try { if (command.length != 0 || command.text == null) return; - IPreferenceStore preferenceStore= PHPeclipsePlugin.getDefault().getPreferenceStore(); + IPreferenceStore preferenceStore = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); - if (preferenceStore.getBoolean(PreferenceConstants.EDITOR_WRAP_STRINGS_SQ) && isSmartMode()) + if (preferenceStore + .getBoolean(PreferenceConstants.EDITOR_WRAP_STRINGS_SQ) + && isSmartMode()) javaStringIndentAfterNewLine(document, command); } catch (BadLocationException e) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/PHPCompletionProposalComparator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/PHPCompletionProposalComparator.java index 3340c92..bad8e94 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/PHPCompletionProposalComparator.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/PHPCompletionProposalComparator.java @@ -9,27 +9,28 @@ public class PHPCompletionProposalComparator implements Comparator { /** * Constructor for CompletionProposalComparator. */ -// public PHPCompletionProposalComparator() { -// fOrderAlphabetically= false; -// } - + // public PHPCompletionProposalComparator() { + // fOrderAlphabetically= false; + // } public void setOrderAlphabetically(boolean orderAlphabetically) { - fOrderAlphabetically= orderAlphabetically; + fOrderAlphabetically = orderAlphabetically; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see Comparator#compare(Object, Object) */ public int compare(Object o1, Object o2) { - IPHPCompletionProposal c1= (IPHPCompletionProposal) o1; - IPHPCompletionProposal c2= (IPHPCompletionProposal) o2; + IPHPCompletionProposal c1 = (IPHPCompletionProposal) o1; + IPHPCompletionProposal c2 = (IPHPCompletionProposal) o2; if (!fOrderAlphabetically) { - int relevanceDif= c2.getRelevance() - c1.getRelevance(); + int relevanceDif = c2.getRelevance() - c1.getRelevance(); if (relevanceDif != 0) { return relevanceDif; } } return c1.getDisplayString().compareToIgnoreCase(c2.getDisplayString()); - } - + } + } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AbstractAnnotationHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AbstractAnnotationHover.java index d87878c..64fc808 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AbstractAnnotationHover.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AbstractAnnotationHover.java @@ -30,75 +30,90 @@ import org.eclipse.ui.texteditor.AnnotationPreference; import org.eclipse.ui.texteditor.DefaultMarkerAnnotationAccess; import org.eclipse.ui.texteditor.IDocumentProvider; - /** * Abstract super class for annotation hovers. * * @since 3.0 */ -public abstract class AbstractAnnotationHover extends AbstractJavaEditorTextHover { +public abstract class AbstractAnnotationHover extends + AbstractJavaEditorTextHover { + + private IPreferenceStore fStore = PHPeclipsePlugin.getDefault() + .getCombinedPreferenceStore(); + + private DefaultMarkerAnnotationAccess fAnnotationAccess = new DefaultMarkerAnnotationAccess(); - private IPreferenceStore fStore= PHPeclipsePlugin.getDefault().getCombinedPreferenceStore(); - private DefaultMarkerAnnotationAccess fAnnotationAccess= new DefaultMarkerAnnotationAccess(); private boolean fAllAnnotations; - - + public AbstractAnnotationHover(boolean allAnnotations) { - fAllAnnotations= allAnnotations; + fAllAnnotations = allAnnotations; } - + /* * Formats a message as HTML text. */ private String formatMessage(String message) { - StringBuffer buffer= new StringBuffer(); + StringBuffer buffer = new StringBuffer(); HTMLPrinter.addPageProlog(buffer); - HTMLPrinter.addParagraph(buffer, HTMLPrinter.convertToHTMLContent(message)); + HTMLPrinter.addParagraph(buffer, HTMLPrinter + .convertToHTMLContent(message)); HTMLPrinter.addPageEpilog(buffer); return buffer.toString(); } - + /* * @see ITextHover#getHoverInfo(ITextViewer, IRegion) */ public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { - + if (getEditor() == null) return null; - - IDocumentProvider provider= PHPeclipsePlugin.getDefault().getCompilationUnitDocumentProvider(); - IAnnotationModel model= provider.getAnnotationModel(getEditor().getEditorInput()); - + + IDocumentProvider provider = PHPeclipsePlugin.getDefault() + .getCompilationUnitDocumentProvider(); + IAnnotationModel model = provider.getAnnotationModel(getEditor() + .getEditorInput()); + if (model != null) { - Iterator e= new JavaAnnotationIterator(model, true, fAllAnnotations); - int layer= -1; - String message= null; + Iterator e = new JavaAnnotationIterator(model, true, + fAllAnnotations); + int layer = -1; + String message = null; while (e.hasNext()) { - Annotation a= (Annotation) e.next(); + 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())))) + 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(); + 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; + message = msg; + layer = l; } } } if (layer > -1) return formatMessage(message); } - + return null; } - + /* * @see IJavaEditorTextHover#setEditor(IEditorPart) */ @@ -111,14 +126,16 @@ public abstract class AbstractAnnotationHover extends AbstractJavaEditorTextHove /** * Returns the annotation preference for the given annotation. - * - * @param annotation the annotation + * + * @param annotation + * the annotation * @return the annotation preference or null if none - */ + */ private AnnotationPreference getAnnotationPreference(Annotation annotation) { - + if (annotation.isMarkedDeleted()) return null; - return EditorsUI.getAnnotationPreferenceLookup().getAnnotationPreference(annotation); + return EditorsUI.getAnnotationPreferenceLookup() + .getAnnotationPreference(annotation); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AbstractJavaEditorTextHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AbstractJavaEditorTextHover.java index ce9fe79..1fc50ad 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AbstractJavaEditorTextHover.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AbstractJavaEditorTextHover.java @@ -36,46 +36,50 @@ import org.eclipse.ui.keys.KeySequence; /** * Abstract class for providing hover information for Java elements. - * + * * @since 2.1 */ -public abstract class AbstractJavaEditorTextHover implements IJavaEditorTextHover { - +public abstract class AbstractJavaEditorTextHover implements + IJavaEditorTextHover { private IEditorPart fEditor; + private ICommand fCommand; { - ICommandManager commandManager= PlatformUI.getWorkbench().getCommandSupport().getCommandManager(); -// fCommand= commandManager.getCommand(PHPEditorActionDefinitionIds.SHOW_JAVADOC); -// if (!fCommand.isDefined()) - fCommand= null; + ICommandManager commandManager = PlatformUI.getWorkbench() + .getCommandSupport().getCommandManager(); + // fCommand= + // commandManager.getCommand(PHPEditorActionDefinitionIds.SHOW_JAVADOC); + // if (!fCommand.isDefined()) + fCommand = null; } /* * @see IJavaEditorTextHover#setEditor(IEditorPart) */ public void setEditor(IEditorPart editor) { - fEditor= 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(); -// } -// -// IWorkingCopyManager manager= PHPeclipsePlugin.getDefault().getWorkingCopyManager(); -// return manager.getWorkingCopy(input); -// } -// -// return null; -// } + // protected ICodeAssist getCodeAssist() { + // if (fEditor != null) { + // IEditorInput input= fEditor.getEditorInput(); + // if (input instanceof IClassFileEditorInput) { + // IClassFileEditorInput cfeInput= (IClassFileEditorInput) input; + // return cfeInput.getClassFile(); + // } + // + // IWorkingCopyManager manager= + // PHPeclipsePlugin.getDefault().getWorkingCopyManager(); + // return manager.getWorkingCopy(input); + // } + // + // return null; + // } /* * @see ITextHover#getHoverRegion(ITextViewer, int) @@ -89,40 +93,42 @@ public abstract class AbstractJavaEditorTextHover implements IJavaEditorTextHove */ public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { -// ICodeAssist resolve= getCodeAssist(); -// if (resolve != null) { -// try { -// IJavaElement[] result= null; -// -// synchronized (resolve) { -// 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 (JavaModelException x) { -// PHPeclipsePlugin.log(x.getStatus()); -// } -// } + // ICodeAssist resolve= getCodeAssist(); + // if (resolve != null) { + // try { + // IJavaElement[] result= null; + // + // synchronized (resolve) { + // 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 (JavaModelException x) { + // PHPeclipsePlugin.log(x.getStatus()); + // } + // } return null; } /** * Provides hover information for the given Java elements. - * + * * @return the hover information string * @since 2.1 */ protected String getHoverInfo(IJavaElement[] javaElements) { return null; } + /* * @see ITextHoverExtension#getHoverControlCreator() * @since 3.0 @@ -130,44 +136,50 @@ public abstract class AbstractJavaEditorTextHover implements IJavaEditorTextHove public IInformationControlCreator getHoverControlCreator() { return new IInformationControlCreator() { public IInformationControl createInformationControl(Shell parent) { - return new DefaultInformationControl(parent, SWT.NONE, new HTMLTextPresenter(true), getTooltipAffordanceString()); + return new DefaultInformationControl(parent, SWT.NONE, + new HTMLTextPresenter(true), + getTooltipAffordanceString()); } }; } /** * Returns the tool tip affordance string. - * - * @return the affordance string or null if disabled or no key binding is defined + * + * @return the affordance string or null if disabled or no + * key binding is defined * @since 3.0 */ protected String getTooltipAffordanceString() { - if (!PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE)) + if (!PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean( + PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE)) return null; - KeySequence[] sequences= getKeySequences(); + KeySequence[] sequences = getKeySequences(); if (sequences == null) return null; - String keySequence= sequences[0].format(); - return JavaHoverMessages.getFormattedString("JavaTextHover.makeStickyHint", keySequence); //$NON-NLS-1$ + String keySequence = sequences[0].format(); + return JavaHoverMessages.getFormattedString( + "JavaTextHover.makeStickyHint", keySequence); //$NON-NLS-1$ } /** - * Returns the array of valid key sequence bindings for the - * show tool tip description command. - * + * Returns the array of valid key sequence bindings for the show tool tip + * description command. + * * @return the array with the {@link KeySequence}s - * + * * @since 3.0 */ private KeySequence[] getKeySequences() { if (fCommand != null) { - List list= fCommand.getKeySequenceBindings(); + List list = fCommand.getKeySequenceBindings(); if (!list.isEmpty()) { - KeySequence[] keySequences= new KeySequence[list.size()]; - for (int i= 0; i < keySequences.length; i++) { - keySequences[i]= ((IKeySequenceBinding) list.get(i)).getKeySequence(); + KeySequence[] keySequences = new KeySequence[list.size()]; + for (int i = 0; i < keySequences.length; i++) { + keySequences[i] = ((IKeySequenceBinding) list.get(i)) + .getKeySequence(); } return keySequences; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AnnotationExpandHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AnnotationExpandHover.java index f8cea73..581517a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AnnotationExpandHover.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AnnotationExpandHover.java @@ -18,13 +18,7 @@ import java.util.Iterator; import java.util.List; import java.util.Map; -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.jface.viewers.IDoubleClickListener; +import net.sourceforge.phpdt.internal.ui.text.java.hover.AnnotationExpansionControl.AnnotationHoverInput; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; @@ -46,26 +40,32 @@ 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 net.sourceforge.phpdt.internal.ui.text.java.hover.AnnotationExpansionControl.AnnotationHoverInput; - +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; /** - * 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 + * 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. - * + * * @since 3.2 */ -public class AnnotationExpandHover implements IAnnotationHover, IAnnotationHoverExtension { +public class AnnotationExpandHover implements IAnnotationHover, + IAnnotationHoverExtension { - private class InformationControlCreator implements IInformationControlCreator, IInformationControlCreatorExtension { + 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); + return new AnnotationExpansionControl(parent, SWT.NONE, + fAnnotationAccess); } /* @@ -100,35 +100,42 @@ public class AnnotationExpandHover implements IAnnotationHover, IAnnotationHover } /* - * @see org.eclipse.jface.text.source.IVerticalRulerListener#annotationContextMenuAboutToShow(org.eclipse.jface.text.source.VerticalRulerEvent, org.eclipse.swt.widgets.Menu) + * @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) { + public void annotationContextMenuAboutToShow(VerticalRulerEvent event, + Menu menu) { fCompositeRuler.fireAnnotationContextMenuAboutToShow(event, menu); } } + private final IInformationControlCreator fgCreator = new InformationControlCreator(); + + protected final IVerticalRulerListener fgListener = new VerticalRulerListener(); - 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; + 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) + * @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 @@ -136,24 +143,25 @@ public class AnnotationExpandHover implements IAnnotationHover, IAnnotationHover } protected Object getHoverInfoForLine(ISourceViewer viewer, int line) { - IAnnotationModel model= viewer.getAnnotationModel(); - IDocument document= viewer.getDocument(); + IAnnotationModel model = viewer.getAnnotationModel(); + IDocument document = viewer.getDocument(); if (model == null) return null; - List exact= new ArrayList(); - HashMap messagesAtPosition= new HashMap(); + List exact = new ArrayList(); + HashMap messagesAtPosition = new HashMap(); - Iterator e= model.getAnnotationIterator(); + Iterator e = model.getAnnotationIterator(); while (e.hasNext()) { - Annotation annotation= (Annotation) e.next(); - Position position= model.getPosition(annotation); + 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())) + if (isDuplicateMessage(messagesAtPosition, position, annotation + .getText())) continue; exact.add(annotation); @@ -168,13 +176,13 @@ public class AnnotationExpandHover implements IAnnotationHover, IAnnotationHover 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; + 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; } @@ -183,14 +191,15 @@ public class AnnotationExpandHover implements IAnnotationHover, IAnnotationHover class AnnotationComparator implements Comparator { /* - * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) + * @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; + Annotation a1 = (Annotation) o1; + Annotation a2 = (Annotation) o2; - Position p1= model.getPosition(a1); - Position p2= model.getPosition(a2); + Position p1 = model.getPosition(a1); + Position p2 = model.getPosition(a2); // annotation order: // primary order: by position in line @@ -207,28 +216,29 @@ public class AnnotationExpandHover implements IAnnotationHover, IAnnotationHover protected int getOrder(Annotation annotation) { if (fAnnotationAccess instanceof IAnnotationAccessExtension) { - IAnnotationAccessExtension extension= (IAnnotationAccessExtension) fAnnotationAccess; + IAnnotationAccessExtension extension = (IAnnotationAccessExtension) fAnnotationAccess; return extension.getLayer(annotation); } return IAnnotationAccessExtension.DEFAULT_LAYER; } - protected boolean isDuplicateMessage(Map messagesAtPosition, Position position, String message) { + protected boolean isDuplicateMessage(Map messagesAtPosition, + Position position, String message) { if (message == null) return false; - + if (messagesAtPosition.containsKey(position)) { - Object value= messagesAtPosition.get(position); + Object value = messagesAtPosition.get(position); if (message == null || message.equals(value)) return true; if (value instanceof List) { - List messages= (List)value; - if (messages.contains(message)) + List messages = (List) value; + if (messages.contains(message)) return true; messages.add(message); } else { - ArrayList messages= new ArrayList(); + ArrayList messages = new ArrayList(); messages.add(value); messages.add(message); messagesAtPosition.put(position, messages); @@ -241,17 +251,23 @@ public class AnnotationExpandHover implements IAnnotationHover, IAnnotationHover 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(); + 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); + 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); + int widgetLine = ((TextViewer) viewer) + .modelLine2WidgetLine(line); + Point loc = st.getLocationAtOffset(st + .getOffsetAtLine(widgetLine)); + fCompositeRuler.setLocationOfLastMouseButtonActivity(0, + loc.y); } } } @@ -259,20 +275,27 @@ public class AnnotationExpandHover implements IAnnotationHover, IAnnotationHover /** * Returns the distance to the ruler line. - * - * @param position the position - * @param document the document - * @param line the line number + * + * @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) { + protected int compareRulerLine(Position position, IDocument document, + int line) { if (position.getOffset() > -1 && position.getLength() > -1) { try { - int firstLine= document.getLineOfOffset(position.getOffset()); + int firstLine = document.getLineOfOffset(position.getOffset()); if (line == firstLine) return 1; - if (firstLine <= line && line <= document.getLineOfOffset(position.getOffset() + position.getLength())) + if (firstLine <= line + && line <= document.getLineOfOffset(position + .getOffset() + + position.getLength())) return 2; } catch (BadLocationException x) { } @@ -289,14 +312,17 @@ public class AnnotationExpandHover implements IAnnotationHover, IAnnotationHover } /* - * @see org.eclipse.jface.text.source.IAnnotationHoverExtension#getHoverInfo(org.eclipse.jface.text.source.ISourceViewer, org.eclipse.jface.text.source.ILineRange, int) + * @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) { + 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) + * @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); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AnnotationExpansionControl.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AnnotationExpansionControl.java index 5f2d7c0..199eaaf 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AnnotationExpansionControl.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AnnotationExpansionControl.java @@ -14,6 +14,26 @@ 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; @@ -45,87 +65,73 @@ import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Widget; -import org.eclipse.jface.viewers.IDoubleClickListener; - -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; - - /** - * A control that can display a number of annotations. The control can decide how it layouts the - * annotations to present them to the user. + * A control that can display a number of annotations. The control can decide + * how it layouts the annotations to present them to the user. *

                                                      - * 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 + * 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. *

                                                      - *

                                                      Each annotation can have its custom context menu and hover.

                                                      - * + *

                                                      + * Each annotation can have its custom context menu and hover. + *

                                                      + * * @since 3.2 */ -public class AnnotationExpansionControl implements IInformationControl, IInformationControlExtension, IInformationControlExtension2 { - +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 - * + * Input used by the control to display the annotations. TODO move to + * top-level class TODO encapsulate fields + * * @since 3.0 */ 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(); + 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); + oldStyles = setViewerBackground(fAnnotation); // set the selection - fSelection= this; + fSelection = this; if (fHoverManager != null) fHoverManager.showInformation(); if (fInput.fAnnotationListener != null) { - VerticalRulerEvent event= new VerticalRulerEvent(fAnnotation); + VerticalRulerEvent event = new VerticalRulerEvent(fAnnotation); fInput.fAnnotationListener.annotationSelected(event); } @@ -133,7 +139,7 @@ public class AnnotationExpansionControl implements IInformationControl, IInforma public void defaultSelected() { if (fInput.fAnnotationListener != null) { - VerticalRulerEvent event= new VerticalRulerEvent(fAnnotation); + VerticalRulerEvent event = new VerticalRulerEvent(fAnnotation); fInput.fAnnotationListener.annotationDefaultSelected(event); } @@ -142,25 +148,28 @@ public class AnnotationExpansionControl implements IInformationControl, IInforma public void showContextMenu(Menu menu) { if (fInput.fAnnotationListener != null) { - VerticalRulerEvent event= new VerticalRulerEvent(fAnnotation); - fInput.fAnnotationListener.annotationContextMenuAboutToShow(event, menu); + VerticalRulerEvent event = new VerticalRulerEvent(fAnnotation); + fInput.fAnnotationListener.annotationContextMenuAboutToShow( + event, menu); } } public void deselect() { // hide the popup -// fHoverManager.disposeInformationControl(); + // fHoverManager.disposeInformationControl(); // deselect - fSelection= null; + fSelection = null; resetViewerBackground(oldStyles); - oldStyles= null; + oldStyles = null; - Display disp= fShell.getDisplay(); + Display disp = fShell.getDisplay(); canvas.setCursor(null); // TODO: remove shading - for now: set standard background - canvas.setBackground(disp.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); + canvas + .setBackground(disp + .getSystemColor(SWT.COLOR_INFO_BACKGROUND)); } @@ -174,11 +183,11 @@ public class AnnotationExpansionControl implements IInformationControl, IInforma * @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 item = (Item) ((Widget) e.getSource()).getData(); item.deselect(); - item.canvas= null; - item.fAnnotation= null; - item.oldStyles= null; + item.canvas = null; + item.fAnnotation = null; + item.oldStyles = null; ((Widget) e.getSource()).setData(null); } @@ -196,9 +205,9 @@ public class AnnotationExpansionControl implements IInformationControl, IInforma // TODO: show per-item menu // for now: show ruler context menu if (fInput != null) { - Control ruler= fInput.fRulerInfo.getControl(); + Control ruler = fInput.fRulerInfo.getControl(); if (ruler != null && !ruler.isDisposed()) { - Menu menu= ruler.getMenu(); + Menu menu = ruler.getMenu(); if (menu != null && !menu.isDisposed()) { menu.setLocation(event.x, event.y); menu.addMenuListener(new MenuListener() { @@ -219,7 +228,6 @@ public class AnnotationExpansionControl implements IInformationControl, IInforma } } - /** * Listener on mouse events on the items. */ @@ -228,31 +236,36 @@ public class AnnotationExpansionControl implements IInformationControl, IInforma * @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) { + 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 + // 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(); -// } + // Canvas can= (Canvas) e.getSource(); + // Annotation a= (Annotation) can.getData(); + // if (a != null) { + // a.getDoubleClickAction().run(); + // } } /* * @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent) */ public void mouseUp(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 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(); } @@ -272,7 +285,7 @@ public class AnnotationExpansionControl implements IInformationControl, IInforma * @see org.eclipse.swt.events.MouseTrackListener#mouseEnter(org.eclipse.swt.events.MouseEvent) */ public void mouseEnter(MouseEvent e) { - Item item= (Item) ((Widget) e.getSource()).getData(); + Item item = (Item) ((Widget) e.getSource()).getData(); if (item != null) item.selected(); } @@ -282,26 +295,25 @@ public class AnnotationExpansionControl implements IInformationControl, IInforma */ public void mouseExit(MouseEvent e) { - Item item= (Item) ((Widget) e.getSource()).getData(); + 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); + 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); + Rectangle bounds = fShell.getBounds(); + // p= fShell.toControl(p); if (!bounds.contains(p)) dispose(); } else { - p= fShell.toControl(p); + p = fShell.toControl(p); if (!region.contains(p)) dispose(); } - } /* @@ -309,7 +321,7 @@ public class AnnotationExpansionControl implements IInformationControl, IInforma */ public void mouseHover(MouseEvent e) { if (fHoverManager == null) { - fHoverManager= new HoverManager(); + fHoverManager = new HoverManager(); fHoverManager.takesFocusWhenVisible(false); fHoverManager.install(fComposite); fHoverManager.showInformation(); @@ -317,31 +329,33 @@ public class AnnotationExpansionControl implements IInformationControl, IInforma } } - /** - * - * + * + * * @since 3.0 */ public class LinearLayouter { - private static final int ANNOTATION_SIZE= 14; - private static final int BORDER_WIDTH= 2; + 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; + 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; + GridData gridData = new GridData( + ANNOTATION_SIZE + 2 * BORDER_WIDTH, ANNOTATION_SIZE + 2 + * BORDER_WIDTH); + gridData.horizontalAlignment = GridData.CENTER; + gridData.verticalAlignment = GridData.CENTER; return gridData; } @@ -359,20 +373,23 @@ public class AnnotationExpansionControl implements IInformationControl, IInforma } } - - + /** - * Listener on paint events on the items. Paints the annotation image on the given GC. + * Listener on paint events on the items. Paints the annotation image on the + * given GC. */ 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; + 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()); + Rectangle rect = new Rectangle(fLayouter.getBorderWidth(), + fLayouter.getBorderWidth(), fLayouter + .getAnnotationSize(), fLayouter + .getAnnotationSize()); if (fAnnotationAccessExtension != null) fAnnotationAccessExtension.paint(a, e.gc, can, rect); } @@ -385,7 +402,7 @@ public class AnnotationExpansionControl implements IInformationControl, IInforma private final class HoverManager extends AbstractInformationControlManager { /** - * + * */ public HoverManager() { super(new IInformationControlCreator() { @@ -396,7 +413,8 @@ public class AnnotationExpansionControl implements IInformationControl, IInforma setMargins(5, 10); setAnchor(ANCHOR_BOTTOM); - setFallbackAnchors(new Anchor[] {ANCHOR_BOTTOM, ANCHOR_LEFT, ANCHOR_RIGHT} ); + setFallbackAnchors(new Anchor[] { ANCHOR_BOTTOM, ANCHOR_LEFT, + ANCHOR_RIGHT }); } /* @@ -404,120 +422,136 @@ public class AnnotationExpansionControl implements IInformationControl, IInforma */ protected void computeInformation() { if (fSelection != null) { - Rectangle subjectArea= fSelection.canvas.getBounds(); - Annotation annotation= fSelection.fAnnotation; + Rectangle subjectArea = fSelection.canvas.getBounds(); + Annotation annotation = fSelection.fAnnotation; String msg; if (annotation != null) - msg= annotation.getText(); + msg = annotation.getText(); else - msg= null; + 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 null 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 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(); + fLayouter = new LinearLayouter(); if (access instanceof IAnnotationAccessExtension) - fAnnotationAccessExtension= (IAnnotationAccessExtension) access; + fAnnotationAccessExtension = (IAnnotationAccessExtension) access; - fShell= new Shell(parent, shellStyle | SWT.NO_FOCUS | SWT.ON_TOP); - Display display= fShell.getDisplay(); + 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; + 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; + 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++) { + return; + Control[] children = fComposite.getChildren(); + Rectangle bounds = null; + for (int i = 0; i < children.length; i++) { if (bounds == null) - bounds= children[i].getBounds(); + 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 + // 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); + // 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); @@ -525,7 +559,7 @@ public class AnnotationExpansionControl implements IInformationControl, IInforma } private void setInfoSystemColor() { - Display display= fShell.getDisplay(); + Display display = fShell.getDisplay(); setForegroundColor(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); setBackgroundColor(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); } @@ -537,7 +571,6 @@ public class AnnotationExpansionControl implements IInformationControl, IInforma setInput(null); } - /* * @see org.eclipse.jface.text.IInformationControlExtension2#setInput(java.lang.Object) */ @@ -546,9 +579,9 @@ public class AnnotationExpansionControl implements IInformationControl, IInforma fInput.fViewer.removeViewportListener(fViewportListener); if (input instanceof AnnotationHoverInput) - fInput= (AnnotationHoverInput) input; + fInput = (AnnotationHoverInput) input; else - fInput= null; + fInput = null; inputChanged(fInput, null); } @@ -571,15 +604,15 @@ public class AnnotationExpansionControl implements IInformationControl, IInforma fShell.setRegion(fLayouter.getShellRegion(fInput.fAnnotations.length)); - Layout layout= fLayouter.getLayout(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]; + 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(); } @@ -590,18 +623,19 @@ public class AnnotationExpansionControl implements IInformationControl, IInforma if (fComposite == null) return; - Control[] children= fComposite.getChildren(); - int oldSize= children.length; - int newSize= fInput == null ? 0 : fInput.fAnnotations.length; + Control[] children = fComposite.getChildren(); + int oldSize = children.length; + int newSize = fInput == null ? 0 : fInput.fAnnotations.length; - Display display= fShell.getDisplay(); + 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(); + 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.setBackground(display + .getSystemColor(SWT.COLOR_INFO_BACKGROUND)); canvas.addPaintListener(fPaintListener); @@ -615,8 +649,8 @@ public class AnnotationExpansionControl implements IInformationControl, IInforma } // dispose of exceeding resources - for (int i= oldSize; i > newSize; i--) { - Item item= (Item) children[i - 1].getData(); + for (int i = oldSize; i > newSize; i--) { + Item item = (Item) children[i - 1].getData(); item.deselect(); children[i - 1].dispose(); } @@ -637,15 +671,15 @@ public class AnnotationExpansionControl implements IInformationControl, IInforma if (fShell != null) { if (!fShell.isDisposed()) fShell.dispose(); - fShell= null; - fComposite= null; + fShell = null; + fComposite = null; if (fHandCursor != null) fHandCursor.dispose(); - fHandCursor= null; + fHandCursor = null; if (fHoverManager != null) fHoverManager.dispose(); - fHoverManager= null; - fSelection= null; + fHoverManager = null; + fSelection = null; } } @@ -657,11 +691,12 @@ public class AnnotationExpansionControl implements IInformationControl, IInforma } /* - * @see org.eclipse.jface.text.IInformationControl#setSizeConstraints(int, int) + * @see org.eclipse.jface.text.IInformationControl#setSizeConstraints(int, + * int) */ public void setSizeConstraints(int maxWidth, int maxHeight) { - //fMaxWidth= maxWidth; - //fMaxHeight= maxHeight; + // fMaxWidth= maxWidth; + // fMaxHeight= maxHeight; } /* @@ -720,8 +755,8 @@ public class AnnotationExpansionControl implements IInformationControl, IInforma if (fComposite.isFocusControl()) return true; - Control[] children= fComposite.getChildren(); - for (int i= 0; i < children.length; i++) { + Control[] children = fComposite.getChildren(); + for (int i = 0; i < children.length; i++) { if (children[i].isFocusControl()) return true; } @@ -750,38 +785,43 @@ public class AnnotationExpansionControl implements IInformationControl, IInforma } private StyleRange[] setViewerBackground(Annotation annotation) { - StyledText text= fInput.fViewer.getTextWidget(); + StyledText text = fInput.fViewer.getTextWidget(); if (text == null || text.isDisposed()) return null; - Display disp= text.getDisplay(); + Display disp = text.getDisplay(); - Position pos= fInput.model.getPosition(annotation); + Position pos = fInput.model.getPosition(annotation); if (pos == null) return null; - IRegion region= ((TextViewer)fInput.fViewer).modelRange2WidgetRange(new Region(pos.offset, pos.length)); + 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()); + StyleRange[] ranges = text.getStyleRanges(region.getOffset(), region + .getLength()); - List undoRanges= new ArrayList(ranges.length); - for (int i= 0; i < ranges.length; i++) { + 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; + 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); + StyleRange undoRange = new StyleRange(offset, + curStart - offset, null, null); undoRanges.add(index, undoRange); index++; } @@ -789,35 +829,36 @@ public class AnnotationExpansionControl implements IInformationControl, IInforma // step index++; if (index < undoRanges.size()) { - offset= curEnd; - current= (StyleRange) undoRanges.get(index); - curStart= current.start; - curEnd= current.start + current.length; + 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; + offset = curEnd; + current = null; + curStart = region.getOffset() + region.getLength(); + curEnd = -1; } else - curEnd= region.getOffset() + region.getLength(); + 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(); + 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); + range.background = getHighlightColor(disp); } // set the ranges one by one - for (Iterator iter= shadedRanges.iterator(); iter.hasNext(); ) { + for (Iterator iter = shadedRanges.iterator(); iter.hasNext();) { text.setStyleRange((StyleRange) iter.next()); } - return (StyleRange[]) undoRanges.toArray(undoRanges.toArray(new StyleRange[0])); + return (StyleRange[]) undoRanges.toArray(undoRanges + .toArray(new StyleRange[0])); } private void resetViewerBackground(StyleRange[] oldRanges) { @@ -828,12 +869,12 @@ public class AnnotationExpansionControl implements IInformationControl, IInforma if (fInput == null) return; - StyledText text= fInput.fViewer.getTextWidget(); + 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++) { + for (int i = 0; i < oldRanges.length; i++) { text.setStyleRange(oldRanges[i]); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AnnotationHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AnnotationHover.java index 499e8db..55579c3 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AnnotationHover.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AnnotationHover.java @@ -35,54 +35,67 @@ import org.eclipse.ui.texteditor.AnnotationPreference; import org.eclipse.ui.texteditor.DefaultMarkerAnnotationAccess; import org.eclipse.ui.texteditor.IDocumentProvider; - public class AnnotationHover extends AbstractJavaEditorTextHover { - private IPreferenceStore fStore= PHPeclipsePlugin.getDefault().getPreferenceStore(); - private DefaultMarkerAnnotationAccess fAnnotationAccess= new DefaultMarkerAnnotationAccess(); + private IPreferenceStore fStore = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + + private DefaultMarkerAnnotationAccess fAnnotationAccess = new DefaultMarkerAnnotationAccess(); + private PHPTextHover fPHPTextHover = null; + /* * Formats a message as HTML text. */ private String formatMessage(String message) { - StringBuffer buffer= new StringBuffer(); + StringBuffer buffer = new StringBuffer(); HTMLPrinter.addPageProlog(buffer); - HTMLPrinter.addParagraph(buffer, message); //HTMLPrinter.convertToHTMLContent(message)); + HTMLPrinter.addParagraph(buffer, message); // HTMLPrinter.convertToHTMLContent(message)); HTMLPrinter.addPageEpilog(buffer); return buffer.toString(); } - + /* * @see ITextHover#getHoverInfo(ITextViewer, IRegion) */ public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { - + if (getEditor() == null) return null; - - IDocumentProvider provider= PHPeclipsePlugin.getDefault().getCompilationUnitDocumentProvider(); - IAnnotationModel model= provider.getAnnotationModel(getEditor().getEditorInput()); - String message= null; + + IDocumentProvider provider = PHPeclipsePlugin.getDefault() + .getCompilationUnitDocumentProvider(); + IAnnotationModel model = provider.getAnnotationModel(getEditor() + .getEditorInput()); + String message = null; if (model != null) { - Iterator e= new JavaAnnotationIterator(model, true); - int layer= -1; - + Iterator e = new JavaAnnotationIterator(model, true); + int layer = -1; + while (e.hasNext()) { - Annotation a= (Annotation) e.next(); + Annotation a = (Annotation) e.next(); - AnnotationPreference preference= getAnnotationPreference(a); - if (preference == null || !(fStore.getBoolean(preference.getTextPreferenceKey()) || (preference.getHighlightPreferenceKey() != null && fStore.getBoolean(preference.getHighlightPreferenceKey())))) + AnnotationPreference preference = getAnnotationPreference(a); + if (preference == 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(); + 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; + message = msg; + layer = l; } } } @@ -90,15 +103,15 @@ public class AnnotationHover extends AbstractJavaEditorTextHover { return formatMessage(message); } // Added as long as the above doesn't work - if (fPHPTextHover!=null) { - message = fPHPTextHover.getHoverInfo(textViewer, hoverRegion); - if (message!=null) { - return formatMessage(message); - } + if (fPHPTextHover != null) { + message = fPHPTextHover.getHoverInfo(textViewer, hoverRegion); + if (message != null) { + return formatMessage(message); + } } return null; } - + /* * @see IJavaEditorTextHover#setEditor(IEditorPart) */ @@ -111,7 +124,7 @@ public class AnnotationHover extends AbstractJavaEditorTextHover { try { IFile f = ((IFileEditorInput) editorInput).getFile(); fPHPTextHover = new PHPTextHover(f.getProject()); - return; + return; } catch (NullPointerException e) { // this exception occurs, if getTextHover is called by // preference pages ! @@ -126,15 +139,17 @@ public class AnnotationHover extends AbstractJavaEditorTextHover { /** * Returns the annotation preference for the given annotation. - * - * @param annotation the annotation + * + * @param annotation + * the annotation * @return the annotation preference or null if none - */ + */ private AnnotationPreference getAnnotationPreference(Annotation annotation) { - + if (annotation.isMarkedDeleted()) return null; - return EditorsUI.getAnnotationPreferenceLookup().getAnnotationPreference(annotation); + return EditorsUI.getAnnotationPreferenceLookup() + .getAnnotationPreference(annotation); } static boolean isJavaProblemHover(String id) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/BestMatchHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/BestMatchHover.java index 5b5e1cf..929bb67 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/BestMatchHover.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/BestMatchHover.java @@ -9,6 +9,7 @@ * IBM Corporation - initial API and implementation *******************************************************************************/ package net.sourceforge.phpdt.internal.ui.text.java.hover; + import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -25,14 +26,16 @@ import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.information.IInformationProviderExtension2; import org.eclipse.ui.IEditorPart; - /** * Caution: this implementation is a layer breaker and contains some "shortcuts" */ -public class BestMatchHover extends AbstractJavaEditorTextHover implements ITextHoverExtension, IInformationProviderExtension2 { +public class BestMatchHover extends AbstractJavaEditorTextHover implements + ITextHoverExtension, IInformationProviderExtension2 { private List fTextHoverSpecifications; + private List fInstantiatedTextHovers; + private ITextHover fBestHover; public BestMatchHover() { @@ -43,33 +46,37 @@ public class BestMatchHover extends AbstractJavaEditorTextHover implements IText 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); + fTextHoverSpecifications = new ArrayList(2); + fInstantiatedTextHovers = new ArrayList(2); // populate list - JavaEditorTextHoverDescriptor[] hoverDescs= PHPeclipsePlugin.getDefault().getJavaEditorTextHoverDescriptors(); - for (int i= 0; i < hoverDescs.length; i++) { + JavaEditorTextHoverDescriptor[] hoverDescs = PHPeclipsePlugin + .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())) + 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(); + for (Iterator iterator = new ArrayList(fTextHoverSpecifications) + .iterator(); iterator.hasNext();) { + JavaEditorTextHoverDescriptor spec = (JavaEditorTextHoverDescriptor) iterator + .next(); - IJavaEditorTextHover hover= spec.createTextHover(); + IJavaEditorTextHover hover = spec.createTextHover(); if (hover != null) { hover.setEditor(getEditor()); addTextHover(hover); @@ -89,17 +96,18 @@ public class BestMatchHover extends AbstractJavaEditorTextHover implements IText public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { checkTextHovers(); - fBestHover= null; + fBestHover = null; if (fInstantiatedTextHovers == null) return null; - for (Iterator iterator= fInstantiatedTextHovers.iterator(); iterator.hasNext(); ) { - ITextHover hover= (ITextHover)iterator.next(); + for (Iterator iterator = fInstantiatedTextHovers.iterator(); iterator + .hasNext();) { + ITextHover hover = (ITextHover) iterator.next(); - String s= hover.getHoverInfo(textViewer, hoverRegion); + String s = hover.getHoverInfo(textViewer, hoverRegion); if (s != null && s.trim().length() > 0) { - fBestHover= hover; + fBestHover = hover; return s; } } @@ -113,7 +121,7 @@ public class BestMatchHover extends AbstractJavaEditorTextHover implements IText */ public IInformationControlCreator getHoverControlCreator() { if (fBestHover instanceof ITextHoverExtension) - return ((ITextHoverExtension)fBestHover).getHoverControlCreator(); + return ((ITextHoverExtension) fBestHover).getHoverControlCreator(); return null; } @@ -124,7 +132,8 @@ public class BestMatchHover extends AbstractJavaEditorTextHover implements IText */ public IInformationControlCreator getInformationPresenterControlCreator() { if (fBestHover instanceof IInformationProviderExtension2) - return ((IInformationProviderExtension2)fBestHover).getInformationPresenterControlCreator(); + return ((IInformationProviderExtension2) fBestHover) + .getInformationPresenterControlCreator(); return null; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaEditorTextHoverDescriptor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaEditorTextHoverDescriptor.java index e2820e6..4acbeff 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaEditorTextHoverDescriptor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaEditorTextHoverDescriptor.java @@ -40,89 +40,112 @@ import org.osgi.framework.Bundle; */ public class JavaEditorTextHoverDescriptor implements Comparable { - private static final String JAVA_EDITOR_TEXT_HOVER_EXTENSION_POINT= "net.sourceforge.phpeclipse.phpEditorTextHovers"; //$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 static final String JAVA_EDITOR_TEXT_HOVER_EXTENSION_POINT = "net.sourceforge.phpeclipse.phpEditorTextHovers"; //$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. */ public static JavaEditorTextHoverDescriptor[] getContributedHovers() { - IExtensionRegistry registry= Platform.getExtensionRegistry(); - IConfigurationElement[] elements= registry.getConfigurationElementsFor(JAVA_EDITOR_TEXT_HOVER_EXTENSION_POINT); - JavaEditorTextHoverDescriptor[] hoverDescs= createDescriptors(elements); + 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 '.' + * @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$ + int stateMask = 0; + StringTokenizer modifierTokenizer = new StringTokenizer(modifiers, + ",;.:+-* "); //$NON-NLS-1$ while (modifierTokenizer.hasMoreTokens()) { - int modifier= EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken()); + int modifier = EditorUtility + .findLocalizedModifier(modifierTokenizer.nextToken()); if (modifier == 0 || (stateMask & modifier) == modifier) return -1; - stateMask= stateMask | modifier; + stateMask = stateMask | modifier; } return stateMask; } /** - * Creates a new Java Editor text hover descriptor from the given configuration element. + * Creates a new Java Editor text hover descriptor from the given + * configuration element. */ private JavaEditorTextHoverDescriptor(IConfigurationElement element) { Assert.isNotNull(element); - fElement= element; + fElement = element; } /** * Creates the Java editor text hover. */ public IJavaEditorTextHover createTextHover() { - String pluginId = fElement.getDeclaringExtension().getNamespace(); - boolean isHoversPlugInActivated= Platform.getBundle(pluginId).getState() == Bundle.ACTIVE; + String pluginId = fElement.getDeclaringExtension().getNamespace(); + boolean isHoversPlugInActivated = Platform.getBundle(pluginId) + .getState() == Bundle.ACTIVE; if (isHoversPlugInActivated || canActivatePlugIn()) { try { - return (IJavaEditorTextHover)fElement.createExecutableExtension(CLASS_ATTRIBUTE); + return (IJavaEditorTextHover) fElement + .createExecutableExtension(CLASS_ATTRIBUTE); } catch (CoreException x) { - PHPeclipsePlugin.log(new Status(IStatus.ERROR, PHPeclipsePlugin.getPluginId(), 0, JavaHoverMessages.getString("JavaTextHover.createTextHover"), null)); //$NON-NLS-1$ + PHPeclipsePlugin.log(new Status(IStatus.ERROR, PHPeclipsePlugin + .getPluginId(), 0, JavaHoverMessages + .getString("JavaTextHover.createTextHover"), null)); //$NON-NLS-1$ } } - + return null; } - //---- XML Attribute accessors --------------------------------------------- - + + // ---- XML Attribute accessors + // --------------------------------------------- + /** * Returns the hover's id. */ public String getId() { - return fElement.getAttribute(ID_ATTRIBUTE); + return fElement.getAttribute(ID_ATTRIBUTE); } /** @@ -131,18 +154,18 @@ public class JavaEditorTextHoverDescriptor implements Comparable { public String getHoverClassName() { return fElement.getAttribute(CLASS_ATTRIBUTE); } - + /** * Returns the hover's label. */ public String getLabel() { - String label= fElement.getAttribute(LABEL_ATTRIBUTE); + String label = fElement.getAttribute(LABEL_ATTRIBUTE); if (label != null) return label; - + // Return simple class name - label= getHoverClassName(); - int lastDot= label.lastIndexOf('.'); + label = getHoverClassName(); + int lastDot = label.lastIndexOf('.'); if (lastDot >= 0 && lastDot < label.length() - 1) return label.substring(lastDot + 1); else @@ -158,128 +181,151 @@ public class JavaEditorTextHoverDescriptor implements Comparable { return fElement.getAttribute(DESCRIPTION_ATTRIBUTE); } - public boolean canActivatePlugIn() { - return Boolean.valueOf(fElement.getAttribute(ACTIVATE_PLUG_IN_ATTRIBUTE)).booleanValue(); + 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) + if (obj == null || !obj.getClass().equals(this.getClass()) + || getId() == null) return false; - return getId().equals(((JavaEditorTextHoverDescriptor)obj).getId()); + return getId().equals(((JavaEditorTextHoverDescriptor) obj).getId()); } public int hashCode() { return getId().hashCode(); } - /* - * Implements a method from IComparable - */ + /* + * Implements a method from IComparable + */ public int compareTo(Object o) { - return Collator.getInstance().compare(getLabel(), ((JavaEditorTextHoverDescriptor)o).getLabel()); + return Collator.getInstance().compare(getLabel(), + ((JavaEditorTextHoverDescriptor) o).getLabel()); } -// /** -// * @param descriptor a JavaEditorTextHoverDescriptor -// * @return true if this contributed hover depends on the other one -// */ -// public boolean dependsOn(JavaEditorTextHoverDescriptor descriptor) { -// if (descriptor == null) -// return false; -// -// IPluginDescriptor thisPluginDescriptor= fElement.getDeclaringExtension().getDeclaringPluginDescriptor(); -// IPluginDescriptor otherPluginDescriptor= descriptor.fElement.getDeclaringExtension().getDeclaringPluginDescriptor(); -// return dependsOn(thisPluginDescriptor, otherPluginDescriptor); -// } - -// private boolean dependsOn(IPluginDescriptor descriptor0, IPluginDescriptor descriptor1) { -// -// IPluginRegistry registry= Platform.getPluginRegistry(); -// IPluginPrerequisite[] prerequisites= descriptor0.getPluginPrerequisites(); -// -// for (int i= 0; i < prerequisites.length; i++) { -// IPluginPrerequisite prerequisite= prerequisites[i]; -// String id= prerequisite.getUniqueIdentifier(); -// IPluginDescriptor descriptor= registry.getPluginDescriptor(id); -// -// if (descriptor != null && (descriptor.equals(descriptor1) || dependsOn(descriptor, descriptor1))) -// return true; -// } -// -// return false; -// } - - private static JavaEditorTextHoverDescriptor[] createDescriptors(IConfigurationElement[] elements) { - List result= new ArrayList(elements.length); - for (int i= 0; i < elements.length; i++) { - IConfigurationElement element= elements[i]; + // /** + // * @param descriptor a JavaEditorTextHoverDescriptor + // * @return true if this contributed hover depends on the + // other one + // */ + // public boolean dependsOn(JavaEditorTextHoverDescriptor descriptor) { + // if (descriptor == null) + // return false; + // + // IPluginDescriptor thisPluginDescriptor= + // fElement.getDeclaringExtension().getDeclaringPluginDescriptor(); + // IPluginDescriptor otherPluginDescriptor= + // descriptor.fElement.getDeclaringExtension().getDeclaringPluginDescriptor(); + // return dependsOn(thisPluginDescriptor, otherPluginDescriptor); + // } + + // private boolean dependsOn(IPluginDescriptor descriptor0, + // IPluginDescriptor descriptor1) { + // + // IPluginRegistry registry= Platform.getPluginRegistry(); + // IPluginPrerequisite[] prerequisites= + // descriptor0.getPluginPrerequisites(); + // + // for (int i= 0; i < prerequisites.length; i++) { + // IPluginPrerequisite prerequisite= prerequisites[i]; + // String id= prerequisite.getUniqueIdentifier(); + // IPluginDescriptor descriptor= registry.getPluginDescriptor(id); + // + // if (descriptor != null && (descriptor.equals(descriptor1) || + // dependsOn(descriptor, descriptor1))) + // return true; + // } + // + // return false; + // } + + 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); + JavaEditorTextHoverDescriptor desc = new JavaEditorTextHoverDescriptor( + element); result.add(desc); } } Collections.sort(result); - return (JavaEditorTextHoverDescriptor[])result.toArray(new JavaEditorTextHoverDescriptor[result.size()]); + return (JavaEditorTextHoverDescriptor[]) result + .toArray(new JavaEditorTextHoverDescriptor[result.size()]); } - private static void initializeFromPreferences(JavaEditorTextHoverDescriptor[] hovers) { - String compiledTextHoverModifiers= PHPeclipsePlugin.getDefault().getPreferenceStore().getString(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS); - - StringTokenizer tokenizer= new StringTokenizer(compiledTextHoverModifiers, VALUE_SEPARATOR); - HashMap idToModifier= new HashMap(tokenizer.countTokens() / 2); + private static void initializeFromPreferences( + JavaEditorTextHoverDescriptor[] hovers) { + String compiledTextHoverModifiers = PHPeclipsePlugin.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(); + String id = tokenizer.nextToken(); if (tokenizer.hasMoreTokens()) idToModifier.put(id, tokenizer.nextToken()); } - String compiledTextHoverModifierMasks= PHPeclipsePlugin.getDefault().getPreferenceStore().getString(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS); + String compiledTextHoverModifierMasks = PHPeclipsePlugin.getDefault() + .getPreferenceStore().getString( + PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS); - tokenizer= new StringTokenizer(compiledTextHoverModifierMasks, VALUE_SEPARATOR); - HashMap idToModifierMask= new HashMap(tokenizer.countTokens() / 2); + tokenizer = new StringTokenizer(compiledTextHoverModifierMasks, + VALUE_SEPARATOR); + HashMap idToModifierMask = new HashMap(tokenizer.countTokens() / 2); while (tokenizer.hasMoreTokens()) { - String id= tokenizer.nextToken(); + 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; + 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; - + modifierString = DISABLED_TAG; + if (modifierString.startsWith(DISABLED_TAG)) { - enabled= false; - modifierString= modifierString.substring(1); + enabled = false; + modifierString = modifierString.substring(1); } if (modifierString.equals(NO_MODIFIER)) - modifierString= ""; //$NON-NLS-1$ + modifierString = ""; //$NON-NLS-1$ - hovers[i].fModifierString= modifierString; - hovers[i].fIsEnabled= enabled; - hovers[i].fStateMask= computeStateMask(modifierString); + 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())); + hovers[i].fStateMask = Integer + .parseInt((String) idToModifierMask.get(hovers[i] + .getId())); } catch (NumberFormatException ex) { - hovers[i].fStateMask= -1; + hovers[i].fStateMask = -1; } // Fix modifier string - int stateMask= hovers[i].fStateMask; + int stateMask = hovers[i].fStateMask; if (stateMask == -1) - hovers[i].fModifierString=""; //$NON-NLS-1$ + hovers[i].fModifierString = ""; //$NON-NLS-1$ else - hovers[i].fModifierString= EditorUtility.getModifierString(stateMask); + hovers[i].fModifierString = EditorUtility + .getModifierString(stateMask); } } } - + /** * Returns the configured modifier getStateMask for this hover. * @@ -306,12 +352,12 @@ public class JavaEditorTextHoverDescriptor implements Comparable { public boolean isEnabled() { return fIsEnabled; } - + /** * Returns this hover descriptors configuration element. * * @return the configuration element - * @since 3.0 + * @since 3.0 */ public IConfigurationElement getConfigurationElement() { return fElement; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaEditorTextHoverProxy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaEditorTextHoverProxy.java index 9b08fae..7304174 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaEditorTextHoverProxy.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaEditorTextHoverProxy.java @@ -17,7 +17,6 @@ import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.ui.IEditorPart; - /** * Proxy for JavaEditorTextHovers. * @@ -26,10 +25,12 @@ import org.eclipse.ui.IEditorPart; public class JavaEditorTextHoverProxy extends AbstractJavaEditorTextHover { private JavaEditorTextHoverDescriptor fHoverDescriptor; + private IJavaEditorTextHover fHover; - public JavaEditorTextHoverProxy(JavaEditorTextHoverDescriptor descriptor, IEditorPart editor) { - fHoverDescriptor= descriptor; + public JavaEditorTextHoverProxy(JavaEditorTextHoverDescriptor descriptor, + IEditorPart editor) { + fHoverDescriptor = descriptor; setEditor(editor); } @@ -59,7 +60,7 @@ public class JavaEditorTextHoverProxy extends AbstractJavaEditorTextHover { else return null; } - + /* * @see ITextHover#getHoverInfo(ITextViewer, IRegion) */ @@ -78,7 +79,7 @@ public class JavaEditorTextHoverProxy extends AbstractJavaEditorTextHover { } private boolean createHover() { - fHover= fHoverDescriptor.createTextHover(); + fHover = fHoverDescriptor.createTextHover(); if (fHover != null) fHover.setEditor(getEditor()); return isCreated(); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaExpandHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaExpandHover.java index 6237921..9e0aad6 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaExpandHover.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaExpandHover.java @@ -45,27 +45,32 @@ import org.eclipse.ui.texteditor.AnnotationPreference; import org.eclipse.ui.texteditor.AnnotationPreferenceLookup; /** - * - * + * + * * @since 3.0 */ public class JavaExpandHover extends AnnotationExpandHover { /** Id of the no breakpoint fake annotation */ - public static final String NO_BREAKPOINT_ANNOTATION= "net.sourceforge.phpdt.internal.ui.NoBreakpointAnnotation"; //$NON-NLS-1$ + public static final String NO_BREAKPOINT_ANNOTATION = "net.sourceforge.phpdt.internal.ui.NoBreakpointAnnotation"; //$NON-NLS-1$ - private static class NoBreakpointAnnotation extends Annotation implements IAnnotationPresentation { + private static class NoBreakpointAnnotation extends Annotation implements + IAnnotationPresentation { public NoBreakpointAnnotation() { - super(NO_BREAKPOINT_ANNOTATION, false, JavaHoverMessages.getString("NoBreakpointAnnotation.addBreakpoint")); + super(NO_BREAKPOINT_ANNOTATION, false, JavaHoverMessages + .getString("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) + * @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= PHPUiImages.get(PHPUiImages.IMG_FIELD_PUBLIC); + // draw affordance so the user know she can click here to get a + // breakpoint + Image fImage = PHPUiImages.get(PHPUiImages.IMG_FIELD_PUBLIC); ImageUtilities.drawImage(fImage, gc, canvas, bounds, SWT.CENTER); } @@ -77,52 +82,64 @@ public class JavaExpandHover extends AnnotationExpandHover { } } - private AnnotationPreferenceLookup fLookup= new AnnotationPreferenceLookup(); - private IPreferenceStore fStore= PHPeclipsePlugin.getDefault().getCombinedPreferenceStore(); + private AnnotationPreferenceLookup fLookup = new AnnotationPreferenceLookup(); + + private IPreferenceStore fStore = PHPeclipsePlugin.getDefault() + .getCombinedPreferenceStore(); - public JavaExpandHover(CompositeRuler ruler, IAnnotationAccess access, IDoubleClickListener doubleClickListener) { + 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) + * @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(); + 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(); + List exact = new ArrayList(); + HashMap messagesAtPosition = new HashMap(); - Iterator e= model.getAnnotationIterator(); + Iterator e = model.getAnnotationIterator(); while (e.hasNext()) { - Annotation annotation= (Annotation) e.next(); + Annotation annotation = (Annotation) e.next(); if (fAnnotationAccess instanceof IAnnotationAccessExtension) - if (!((IAnnotationAccessExtension)fAnnotationAccess).isPaintable(annotation)) + if (!((IAnnotationAccessExtension) fAnnotationAccess) + .isPaintable(annotation)) continue; - - if (annotation instanceof IJavaAnnotation && !isIncluded((IJavaAnnotation)annotation, showTemporaryProblems)) + + if (annotation instanceof IJavaAnnotation + && !isIncluded((IJavaAnnotation) annotation, + showTemporaryProblems)) continue; - AnnotationPreference pref= fLookup.getAnnotationPreference(annotation); + AnnotationPreference pref = fLookup + .getAnnotationPreference(annotation); if (pref != null) { - String key= pref.getVerticalRulerPreferenceKey(); + String key = pref.getVerticalRulerPreferenceKey(); if (key != null && !fStore.getBoolean(key)) continue; } - Position position= model.getPosition(annotation); + Position position = model.getPosition(annotation); if (position == null) continue; if (compareRulerLine(position, document, line) == 1) { - if (isDuplicateMessage(messagesAtPosition, position, annotation.getText())) + if (isDuplicateMessage(messagesAtPosition, position, annotation + .getText())) continue; exact.add(annotation); @@ -135,7 +152,7 @@ public class JavaExpandHover extends AnnotationExpandHover { setLastRulerMouseLocation(viewer, line); if (exact.size() > 0) { - Annotation first= (Annotation) exact.get(0); + Annotation first = (Annotation) exact.get(0); if (!isBreakpointAnnotation(first)) exact.add(0, new NoBreakpointAnnotation()); } @@ -143,51 +160,54 @@ public class JavaExpandHover extends AnnotationExpandHover { 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() { + 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; + input.model = model; return input; } - private boolean isIncluded(IJavaAnnotation annotation, boolean showTemporaryProblems) { - + 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())) + 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); + + return showTemporaryProblems; // && + // JavaCorrectionProcessor.hasCorrections((Annotation)annotation); } /* * @see org.eclipse.ui.internal.texteditor.AnnotationExpandHover#getOrder(org.eclipse.jface.text.source.Annotation) */ protected int getOrder(Annotation annotation) { - if (isBreakpointAnnotation(annotation)) + if (isBreakpointAnnotation(annotation)) return 1000; else return super.getOrder(annotation); @@ -195,7 +215,7 @@ public class JavaExpandHover extends AnnotationExpandHover { private boolean isBreakpointAnnotation(Annotation a) { if (a instanceof JavaMarkerAnnotation) { - JavaMarkerAnnotation jma= (JavaMarkerAnnotation) a; + JavaMarkerAnnotation jma = (JavaMarkerAnnotation) a; // HACK to get breakpoints to show up first return jma.getType().equals("org.eclipse.debug.core.breakpoint"); //$NON-NLS-1$ } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaHoverMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaHoverMessages.java index 238785d..3582118 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaHoverMessages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaHoverMessages.java @@ -16,9 +16,10 @@ import java.util.ResourceBundle; class JavaHoverMessages { - private static final String RESOURCE_BUNDLE= "net.sourceforge.phpdt.internal.ui.text.java.hover.JavaHoverMessages";//$NON-NLS-1$ + private static final String RESOURCE_BUNDLE = "net.sourceforge.phpdt.internal.ui.text.java.hover.JavaHoverMessages";//$NON-NLS-1$ - private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); + private static ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); private JavaHoverMessages() { } @@ -30,53 +31,58 @@ class JavaHoverMessages { return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$ } } + /** * Gets a string from the resource bundle and formats it with the argument * - * @param key the string used to get the bundle value, must not be null + * @param key + * the string used to get the bundle value, must not be null * @since 3.0 */ public static String getFormattedString(String key, Object arg) { - String format= null; + String format = null; try { - format= fgResourceBundle.getString(key); + format = fgResourceBundle.getString(key); } catch (MissingResourceException e) { return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$ } if (arg == null) - arg= ""; //$NON-NLS-1$ + arg = ""; //$NON-NLS-1$ return MessageFormat.format(format, new Object[] { arg }); } + /** * Gets a string from the resource bundle and formats it with the arguments * - * @param key the string used to get the bundle value, must not be null + * @param key + * the string used to get the bundle value, must not be null * @since 3.0 */ public static String getFormattedString(String key, Object arg1, Object arg2) { - String format= null; + String format = null; try { - format= fgResourceBundle.getString(key); + format = fgResourceBundle.getString(key); } catch (MissingResourceException e) { return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$ } if (arg1 == null) - arg1= ""; //$NON-NLS-1$ + arg1 = ""; //$NON-NLS-1$ if (arg2 == null) - arg2= ""; //$NON-NLS-1$ + arg2 = ""; //$NON-NLS-1$ return MessageFormat.format(format, new Object[] { arg1, arg2 }); } - + /** * Gets a string from the resource bundle and formats it with the argument * - * @param key the string used to get the bundle value, must not be null + * @param key + * the string used to get the bundle value, must not be null * @since 3.0 */ public static String getFormattedString(String key, boolean arg) { - String format= null; + String format = null; try { - format= fgResourceBundle.getString(key); + format = fgResourceBundle.getString(key); } catch (MissingResourceException e) { return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$ } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaInformationProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaInformationProvider.java index ad98776..a8f3a8e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaInformationProvider.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaInformationProvider.java @@ -10,7 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.ui.text.java.hover; - import net.sourceforge.phpdt.internal.ui.text.JavaWordFinder; import net.sourceforge.phpdt.ui.text.java.hover.IJavaEditorTextHover; @@ -24,95 +23,97 @@ import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchWindow; - public class JavaInformationProvider implements IInformationProvider { 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; + 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; - - + public JavaInformationProvider(IEditorPart editor) { - - fEditor= editor; - + + fEditor = editor; + if (fEditor != null) { - - fPartListener= new EditorWatcher(); - IWorkbenchWindow window= fEditor.getSite().getWorkbenchWindow(); + + 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(); + + 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(); + + 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; + + return null; } /* @@ -120,11 +121,11 @@ public class JavaInformationProvider implements IInformationProvider { */ public String getInformation(ITextViewer textViewer, IRegion subject) { if (fImplementation != null) { - String s= fImplementation.getHoverInfo(textViewer, subject); + String s = fImplementation.getHoverInfo(textViewer, subject); if (s != null && s.trim().length() > 0) return s; } - + return null; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaSourceHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaSourceHover.java index 4754b2b..f59d8ce 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaSourceHover.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaSourceHover.java @@ -30,36 +30,39 @@ import org.eclipse.jface.text.IDocument; */ public class JavaSourceHover extends AbstractJavaEditorTextHover { - private final int LABEL_FLAGS= JavaElementLabels.ALL_FULLY_QUALIFIED - | JavaElementLabels.M_PRE_RETURNTYPE | JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.M_PARAMETER_NAMES | JavaElementLabels.M_EXCEPTIONS - | JavaElementLabels.F_PRE_TYPE_SIGNATURE; - + private final int LABEL_FLAGS = JavaElementLabels.ALL_FULLY_QUALIFIED + | JavaElementLabels.M_PRE_RETURNTYPE + | JavaElementLabels.M_PARAMETER_TYPES + | JavaElementLabels.M_PARAMETER_NAMES + | JavaElementLabels.M_EXCEPTIONS + | JavaElementLabels.F_PRE_TYPE_SIGNATURE; /* * @see JavaElementHover */ protected String getHoverInfo(IJavaElement[] result) { - int nResults= result.length; - StringBuffer buffer= new StringBuffer(); - + int nResults = result.length; + StringBuffer buffer = new StringBuffer(); + if (nResults > 1) { - - for (int i= 0; i < result.length; i++) { + + for (int i = 0; i < result.length; i++) { HTMLPrinter.startBulletList(buffer); - IJavaElement curr= result[i]; + IJavaElement curr = result[i]; if (curr instanceof IMember) HTMLPrinter.addBullet(buffer, getInfoText((IMember) curr)); HTMLPrinter.endBulletList(buffer); } - + } else { - - IJavaElement curr= result[0]; + + IJavaElement curr = result[0]; if (curr instanceof IMember && curr instanceof ISourceReference) { - HTMLPrinter.addSmallHeader(buffer, getInfoText(((IMember)curr))); + HTMLPrinter.addSmallHeader(buffer, + getInfoText(((IMember) curr))); try { - String source= ((ISourceReference)curr).getSource(); - source= removeLeadingComments(source); + String source = ((ISourceReference) curr).getSource(); + source = removeLeadingComments(source); HTMLPrinter.addParagraph(buffer, "
                                                      "); //$NON-NLS-1$
                                                       					HTMLPrinter.addParagraph(buffer, source);
                                                       					HTMLPrinter.addParagraph(buffer, "
                                                      "); //$NON-NLS-1$ @@ -68,13 +71,13 @@ public class JavaSourceHover extends AbstractJavaEditorTextHover { } } } - + if (buffer.length() > 0) { HTMLPrinter.insertPageProlog(buffer, 0); HTMLPrinter.addPageEpilog(buffer); return buffer.toString(); } - + return null; } @@ -83,19 +86,20 @@ public class JavaSourceHover extends AbstractJavaEditorTextHover { } private String removeLeadingComments(String source) { - PHPCodeReader reader= new PHPCodeReader(); - IDocument document= new Document(source); + PHPCodeReader reader = new PHPCodeReader(); + IDocument document = new Document(source); int i; try { - reader.configureForwardReader(document, 0, document.getLength(), true, false); - int c= reader.read(); + reader.configureForwardReader(document, 0, document.getLength(), + true, false); + int c = reader.read(); while (c != -1 && (c == '\r' || c == '\n')) { - c= reader.read(); + c = reader.read(); } - i= reader.getOffset(); + i = reader.getOffset(); reader.close(); } catch (IOException ex) { - i= 0; + i = 0; } finally { try { if (reader != null) diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaTypeHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaTypeHover.java index a0ca22f..a2b08f1 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaTypeHover.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaTypeHover.java @@ -16,15 +16,15 @@ import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.ui.IEditorPart; - public class JavaTypeHover implements IJavaEditorTextHover { - + private IJavaEditorTextHover fAnnotationHover; - //private IJavaEditorTextHover fJavadocHover; - + + // private IJavaEditorTextHover fJavadocHover; + public JavaTypeHover() { - fAnnotationHover= new AnnotationHover(); - // fJavadocHover= new JavadocHover(); + fAnnotationHover = new AnnotationHover(); + // fJavadocHover= new JavadocHover(); } /** @@ -32,26 +32,27 @@ public class JavaTypeHover implements IJavaEditorTextHover { */ public void setEditor(IEditorPart editor) { fAnnotationHover.setEditor(editor); - // fJavadocHover.setEditor(editor); + // fJavadocHover.setEditor(editor); } - + /* * @see ITextHover#getHoverRegion(ITextViewer, int) */ public IRegion getHoverRegion(ITextViewer textViewer, int offset) { - //return fJavadocHover.getHoverRegion(textViewer, offset); + // return fJavadocHover.getHoverRegion(textViewer, offset); return null; } - + /* * @see ITextHover#getHoverInfo(ITextViewer, IRegion) */ public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { - String hoverInfo= fAnnotationHover.getHoverInfo(textViewer, hoverRegion); + String hoverInfo = fAnnotationHover.getHoverInfo(textViewer, + hoverRegion); if (hoverInfo != null) return hoverInfo; - //return fJavadocHover.getHoverInfo(textViewer, hoverRegion); - return null; + // return fJavadocHover.getHoverInfo(textViewer, hoverRegion); + return null; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/ProblemHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/ProblemHover.java index e7e7a34..ea51f8e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/ProblemHover.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/ProblemHover.java @@ -11,13 +11,11 @@ package net.sourceforge.phpdt.internal.ui.text.java.hover; /** - * This annotation hover shows the description of the - * selected java annotation. + * 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 * - * XXX: Currently this problem hover only works for - * Java problems. - * see: https://bugs.eclipse.org/bugs/show_bug.cgi?id=62081 - * * @since 3.0 */ public class ProblemHover extends AbstractAnnotationHover { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/SourceViewerInformationControl.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/SourceViewerInformationControl.java index d48678b..d852710 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/SourceViewerInformationControl.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/SourceViewerInformationControl.java @@ -41,202 +41,246 @@ import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; /** - * Source viewer based implementation of IInformationControl. - * Displays information in a source viewer. + * Source viewer based implementation of IInformationControl. + * Displays information in a source viewer. * * @since 3.0 */ -public class SourceViewerInformationControl implements IInformationControl, IInformationControlExtension, DisposeListener { - +public class SourceViewerInformationControl implements IInformationControl, + IInformationControlExtension, DisposeListener { + /** Border thickness in pixels. */ - private static final int BORDER= 1; + 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; + private SourceViewer fViewer; + /** * The optional status field. * * @since 3.0 */ - private Label fStatusField; + private Label fStatusField; + /** * The separator for the optional status field. * * @since 3.0 */ - private Label fSeparator; + private Label fSeparator; + /** * The font of the optional status text label. * * @since 3.0 */ private Font fStatusTextFont; - + /** - * 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. + * 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 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) { + 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. + * 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 null if the status field should be hidden + * @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 + * null if the status field should be hidden * @since 3.0 */ - public SourceViewerInformationControl(Shell parent, int shellStyle, int style, String statusFieldText) { + 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 = new Shell(parent, SWT.NO_FOCUS | SWT.ON_TOP | shellStyle); + Display display = fShell.getDisplay(); fShell.setBackground(display.getSystemColor(SWT.COLOR_BLACK)); - Composite composite= fShell; - layout= new GridLayout(1, false); - int border= ((shellStyle & SWT.NO_TRIM) == 0) ? 0 : BORDER; - layout.marginHeight= border; - layout.marginWidth= border; + 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); + 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 = 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); + 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)); - } + composite.setForeground(display + .getSystemColor(SWT.COLOR_INFO_FOREGROUND)); + composite.setBackground(display + .getSystemColor(SWT.COLOR_INFO_BACKGROUND)); + } // Source viewer - IPreferenceStore store= PHPeclipsePlugin.getDefault().getCombinedPreferenceStore(); - fViewer= new JavaSourceViewer(composite, null, null, false, style, store); - fViewer.configure(new PHPSourceViewerConfiguration(PHPeclipsePlugin.getDefault().getJavaTextTools().getColorManager(), store, null, null)); + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getCombinedPreferenceStore(); + fViewer = new JavaSourceViewer(composite, null, null, false, style, + store); + fViewer.configure(new PHPSourceViewerConfiguration(PHPeclipsePlugin + .getDefault().getJavaTextTools().getColorManager(), store, + null, null)); fViewer.setEditable(false); - - fText= fViewer.getTextWidget(); - gd= new GridData(GridData.BEGINNING | GridData.FILL_BOTH); + + fText = fViewer.getTextWidget(); + gd = new GridData(GridData.BEGINNING | GridData.FILL_BOTH); fText.setLayoutData(gd); - fText.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_INFO_FOREGROUND)); - fText.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND)); - + fText.setForeground(parent.getDisplay().getSystemColor( + SWT.COLOR_INFO_FOREGROUND)); + fText.setBackground(parent.getDisplay().getSystemColor( + SWT.COLOR_INFO_BACKGROUND)); + fText.addKeyListener(new KeyListener() { - - public void keyPressed(KeyEvent e) { + + public void keyPressed(KeyEvent e) { if (e.character == 0x1B) // ESC fShell.dispose(); } - - public void keyReleased(KeyEvent e) {} + + 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 = 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 = new Label(composite, SWT.RIGHT); fStatusField.setText(statusFieldText); - Font font= fStatusField.getFont(); - FontData[] fontDatas= font.getFontData(); - for (int i= 0; i < fontDatas.length; i++) + 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); + 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); + 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.setForeground(display + .getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW)); - fStatusField.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); + fStatusField.setBackground(display + .getSystemColor(SWT.COLOR_INFO_BACKGROUND)); } - + addDisposeListener(this); } /** - * 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. + * 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) { + * @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, 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. + * 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 null if the status field should be hidden + * @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 + * null if the status field should be hidden * @since 3.0 - */ - public SourceViewerInformationControl(Shell parent,int style, String statusFieldText) { + */ + public SourceViewerInformationControl(Shell parent, int style, + String statusFieldText) { this(parent, SWT.NO_TRIM, 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. + * 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 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. + * 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 null if the status field should be hidden + * @param parent + * the parent shell + * @param statusFieldText + * the text to be used in the optional status field or + * null if the status field should be hidden * @since 3.0 */ public SourceViewerInformationControl(Shell parent, String statusFieldText) { this(parent, SWT.NONE, statusFieldText); } - + /* * @see org.eclipse.jface.text.IInformationControlExtension2#setInput(java.lang.Object) */ public void setInput(Object input) { if (input instanceof String) - setInformation((String)input); + setInformation((String) input); else setInformation(null); } @@ -249,33 +293,35 @@ public class SourceViewerInformationControl implements IInformationControl, IInf fViewer.setInput(null); return; } - - IDocument doc= new Document(content); - PHPeclipsePlugin.getDefault().getJavaTextTools().setupJavaDocumentPartitioner(doc); - + + IDocument doc = new Document(content); + PHPeclipsePlugin.getDefault().getJavaTextTools() + .setupJavaDocumentPartitioner(doc); + fViewer.setInput(doc); } - + /* * @see IInformationControl#setVisible(boolean) */ public void setVisible(boolean visible) { - fShell.setVisible(visible); + fShell.setVisible(visible); } /** * {@inheritDoc} + * * @since 3.0 */ public void widgetDisposed(DisposeEvent event) { if (fStatusTextFont != null && !fStatusTextFont.isDisposed()) fStatusTextFont.dispose(); - - fStatusTextFont= null; - fShell= null; - fText= null; + + fStatusTextFont = null; + fShell = null; + fText = null; } - + /** * {@inheritDoc} */ @@ -285,84 +331,86 @@ public class SourceViewerInformationControl implements IInformationControl, IInf 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; + 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) { - Rectangle trim= fShell.computeTrim(0, 0, 0, 0); - Point textLocation= fText.getLocation(); - location.x += trim.x - textLocation.x; - location.y += trim.y - textLocation.y; - fShell.setLocation(location); + Rectangle trim = fShell.computeTrim(0, 0, 0, 0); + Point textLocation = fText.getLocation(); + location.x += trim.x - textLocation.x; + location.y += trim.y - textLocation.y; + fShell.setLocation(location); } - + /* * @see IInformationControl#setSizeConstraints(int, int) */ public void setSizeConstraints(int maxWidth, int maxHeight) { - maxWidth= maxHeight; + maxWidth = maxHeight; } - + /* * @see IInformationControl#computeSizeHint() */ public Point computeSizeHint() { return fShell.computeSize(SWT.DEFAULT, SWT.DEFAULT); } - + /* * @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() */ @@ -370,29 +418,29 @@ public class SourceViewerInformationControl implements IInformationControl, IInf 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() { + + protected ISourceViewer getViewer() { return fViewer; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/ILinkedPositionListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/ILinkedPositionListener.java index 1f79b44..b462ede 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/ILinkedPositionListener.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/ILinkedPositionListener.java @@ -18,20 +18,22 @@ import org.eclipse.jface.text.Position; */ public interface ILinkedPositionListener { - /** - * Notifies that the linked mode has been left. On success, all changes are kept, otherwise all changes made to the linked - * positions are restored to the state before entering linked mode. - */ - void exit(int flags); + /** + * Notifies that the linked mode has been left. On success, all changes are + * kept, otherwise all changes made to the linked positions are restored to + * the state before entering linked mode. + */ + void exit(int flags); - /** - * Notifies the changed linked position. The listener is asked to reposition the caret at the given offset. - * - * @param position - * the linked position which initiated the change. - * @param caretOffset - * the caret offset relative to the position. - */ - void setCurrentPosition(Position position, int caretOffset); + /** + * Notifies the changed linked position. The listener is asked to reposition + * the caret at the given offset. + * + * @param position + * the linked position which initiated the change. + * @param caretOffset + * the caret offset relative to the position. + */ + void setCurrentPosition(Position position, int caretOffset); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionListener.java index 08fab6e..f204eb1 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionListener.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionListener.java @@ -1,13 +1,13 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html -Contributors: - IBM Corporation - Initial implementation -**********************************************************************/ + Contributors: + IBM Corporation - Initial implementation + **********************************************************************/ package net.sourceforge.phpdt.internal.ui.text.link; @@ -17,20 +17,22 @@ import org.eclipse.jface.text.Position; * A listener for highlight change notification and exititing linked mode. */ public interface LinkedPositionListener { - + /** - * Notifies that the linked mode has been left. On success, all changes - * are kept, otherwise all changes made to the linked positions are restored - * to the state before entering linked mode. + * Notifies that the linked mode has been left. On success, all changes are + * kept, otherwise all changes made to the linked positions are restored to + * the state before entering linked mode. */ void exit(boolean success); - + /** - * Notifies the changed linked position. The listener is asked - * to reposition the caret at the given offset. + * Notifies the changed linked position. The listener is asked to reposition + * the caret at the given offset. * - * @param position the linked position which initiated the change. - * @param caretOffset the caret offset relative to the position. + * @param position + * the linked position which initiated the change. + * @param caretOffset + * the caret offset relative to the position. */ void setCurrentPosition(Position position, int caretOffset); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionManager.java index 4fb0216..fe1c763 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionManager.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionManager.java @@ -32,54 +32,64 @@ import org.eclipse.jface.text.Position; import org.eclipse.jface.text.TypedPosition; import org.eclipse.jface.text.contentassist.ICompletionProposal; - /** - * This class manages linked positions in a document. Positions are linked - * by type names. If positions have the same type name, they are considered - * as linked. + * This class manages linked positions in a document. Positions are linked by + * type names. If positions have the same type name, they are considered as + * linked. * * The manager remains active on a document until any of the following actions * occurs: * *
                                                        - *
                                                      • A document change is performed which would invalidate any of the - * above constraints.
                                                      • + *
                                                      • A document change is performed which would invalidate any of the above + * constraints.
                                                      • * - *
                                                      • The method uninstall() is called.
                                                      • + *
                                                      • The method uninstall() is called.
                                                      • * - *
                                                      • Another instance of LinkedPositionManager tries to - * gain control of the same document. + *
                                                      • Another instance of LinkedPositionManager tries to gain + * control of the same document. *
                                                      */ -public class LinkedPositionManager implements IDocumentListener, IPositionUpdater, IAutoEditStrategy { - - // This class still exists to properly handle code assist. - // This is due to the fact that it cannot be distinguished betweeen document changes which are - // issued by code assist and document changes which origin from another text viewer. - // There is a conflict in interest since in the latter case the linked mode should be left, but in the former case +public class LinkedPositionManager implements IDocumentListener, + IPositionUpdater, IAutoEditStrategy { + + // This class still exists to properly handle code assist. + // This is due to the fact that it cannot be distinguished betweeen document + // changes which are + // issued by code assist and document changes which origin from another text + // viewer. + // There is a conflict in interest since in the latter case the linked mode + // should be left, but in the former case // the linked mode should remain. - // To support content assist, document changes have to be propagated to connected positions + // To support content assist, document changes have to be propagated to + // connected positions // by registering replace commands using IDocumentExtension. - // if it wasn't for the support of content assist, the documentChanged() method could be reduced to - // a simple call to leave(true) + // if it wasn't for the support of content assist, the documentChanged() + // method could be reduced to + // a simple call to leave(true) private class Replace implements IDocumentExtension.IReplace { - + private Position fReplacePosition; + private int fReplaceDeltaOffset; + private int fReplaceLength; + private String fReplaceText; - - public Replace(Position position, int deltaOffset, int length, String text) { - fReplacePosition= position; - fReplaceDeltaOffset= deltaOffset; - fReplaceLength= length; - fReplaceText= text; + + public Replace(Position position, int deltaOffset, int length, + String text) { + fReplacePosition = position; + fReplaceDeltaOffset = deltaOffset; + fReplaceLength = length; + fReplaceText = text; } - + public void perform(IDocument document, IDocumentListener owner) { document.removeDocumentListener(owner); try { - document.replace(fReplacePosition.getOffset() + fReplaceDeltaOffset, fReplaceLength, fReplaceText); + document.replace(fReplacePosition.getOffset() + + fReplaceDeltaOffset, fReplaceLength, fReplaceText); } catch (BadLocationException e) { PHPeclipsePlugin.log(e); // TBD @@ -87,278 +97,339 @@ public class LinkedPositionManager implements IDocumentListener, IPositionUpdate document.addDocumentListener(owner); } } - + private static class PositionComparator implements Comparator { /* * @see Comparator#compare(Object, Object) */ public int compare(Object object0, Object object1) { - Position position0= (Position) object0; - Position position1= (Position) object1; - + Position position0 = (Position) object0; + Position position1 = (Position) object1; + return position0.getOffset() - position1.getOffset(); } } - private static final String LINKED_POSITION_PREFIX= "LinkedPositionManager.linked.position"; //$NON-NLS-1$ - private static final Comparator fgPositionComparator= new PositionComparator(); - private static final Map fgActiveManagers= new HashMap(); - private static int fgCounter= 0; - + private static final String LINKED_POSITION_PREFIX = "LinkedPositionManager.linked.position"; //$NON-NLS-1$ + + private static final Comparator fgPositionComparator = new PositionComparator(); + + private static final Map fgActiveManagers = new HashMap(); + + private static int fgCounter = 0; + private IDocument fDocument; + private ILinkedPositionListener fListener; + private String fPositionCategoryName; + private boolean fMustLeave; - /** - * Flag that records the state of this manager. As there are many different entities that may - * call leave or exit, these cannot always be sure whether the linked position infrastructure is - * still active. This is especially true for multithreaded situations. - */ - private boolean fIsActive= false; + /** + * Flag that records the state of this manager. As there are many different + * entities that may call leave or exit, these cannot always be sure whether + * the linked position infrastructure is still active. This is especially + * true for multithreaded situations. + */ + private boolean fIsActive = false; /** - * Creates a LinkedPositionManager for a IDocument. + * Creates a LinkedPositionManager for a + * IDocument. * - * @param document the document to use with linked positions. - * @param canCoexist true if this manager can coexist with an already existing one + * @param document + * the document to use with linked positions. + * @param canCoexist + * true if this manager can coexist with an + * already existing one */ public LinkedPositionManager(IDocument document, boolean canCoexist) { Assert.isNotNull(document); - fDocument= document; - fPositionCategoryName= LINKED_POSITION_PREFIX + (fgCounter++); + fDocument = document; + fPositionCategoryName = LINKED_POSITION_PREFIX + (fgCounter++); install(canCoexist); } - + /** - * Creates a LinkedPositionManager for a IDocument. + * Creates a LinkedPositionManager for a + * IDocument. * - * @param document the document to use with linked positions. + * @param document + * the document to use with linked positions. */ public LinkedPositionManager(IDocument document) { this(document, false); } - + /** * Sets a listener to notify changes of current linked position. */ public void setLinkedPositionListener(ILinkedPositionListener listener) { - fListener= listener; + fListener = listener; } - + /** * Adds a linked position to the manager with the type being the content of - * the document at the specified range. - * There are the following constraints for linked positions: + * the document at the specified range. There are the following constraints + * for linked positions: * *
                                                        - *
                                                      • Any two positions have spacing of at least one character. - * This implies that two positions must not overlap.
                                                      • - * - *
                                                      • The string at any position must not contain line delimiters.
                                                      • + *
                                                      • Any two positions have spacing of at least one character. This + * implies that two positions must not overlap.
                                                      • + * + *
                                                      • The string at any position must not contain line delimiters.
                                                      • *
                                                      * - * @param offset the offset of the position. - * @param length the length of the position. + * @param offset + * the offset of the position. + * @param length + * the length of the position. */ public void addPosition(int offset, int length) throws BadLocationException { - String type= fDocument.get(offset, length); + String type = fDocument.get(offset, length); addPosition(offset, length, type); } - + /** - * Adds a linked position of the specified position type to the manager. + * Adds a linked position of the specified position type to the manager. * There are the following constraints for linked positions: * *
                                                        - *
                                                      • Any two positions have spacing of at least one character. - * This implies that two positions must not overlap.
                                                      • - * - *
                                                      • The string at any position must not contain line delimiters.
                                                      • + *
                                                      • Any two positions have spacing of at least one character. This + * implies that two positions must not overlap.
                                                      • + * + *
                                                      • The string at any position must not contain line delimiters.
                                                      • *
                                                      * - * @param offset the offset of the position. - * @param length the length of the position. - * @param type the position type name - any positions with the same type are linked. + * @param offset + * the offset of the position. + * @param length + * the length of the position. + * @param type + * the position type name - any positions with the same type are + * linked. */ - public void addPosition(int offset, int length, String type) throws BadLocationException { - Position[] positions= getPositions(fDocument); + public void addPosition(int offset, int length, String type) + throws BadLocationException { + Position[] positions = getPositions(fDocument); if (positions != null) { for (int i = 0; i < positions.length; i++) if (collides(positions[i], offset, length)) - throw new BadLocationException(LinkedPositionMessages.getString(("LinkedPositionManager.error.position.collision"))); //$NON-NLS-1$ + throw new BadLocationException( + LinkedPositionMessages + .getString(("LinkedPositionManager.error.position.collision"))); //$NON-NLS-1$ } - - String content= fDocument.get(offset, length); + + String content = fDocument.get(offset, length); if (containsLineDelimiters(content)) - throw new BadLocationException(LinkedPositionMessages.getString(("LinkedPositionManager.error.contains.line.delimiters"))); //$NON-NLS-1$ + throw new BadLocationException( + LinkedPositionMessages + .getString(("LinkedPositionManager.error.contains.line.delimiters"))); //$NON-NLS-1$ try { - fDocument.addPosition(fPositionCategoryName, new TypedPosition(offset, length, type)); + fDocument.addPosition(fPositionCategoryName, new TypedPosition( + offset, length, type)); } catch (BadPositionCategoryException e) { - PHPeclipsePlugin.log(e); + PHPeclipsePlugin.log(e); Assert.isTrue(false); } } - + /** - * Adds a linked position to the manager. The current document content at the specified range is - * taken as the position type. - *

                                                      + * Adds a linked position to the manager. The current document content at + * the specified range is taken as the position type. + *

                                                      * There are the following constraints for linked positions: * *

                                                        - *
                                                      • Any two positions have spacing of at least one character. - * This implies that two positions must not overlap.
                                                      • - * - *
                                                      • The string at any position must not contain line delimiters.
                                                      • + *
                                                      • Any two positions have spacing of at least one character. This + * implies that two positions must not overlap.
                                                      • + * + *
                                                      • The string at any position must not contain line delimiters.
                                                      • *
                                                      * - * It is usually best to set the first item in additionalChoices to be equal with - * the text inserted at the current position. + * It is usually best to set the first item in + * additionalChoices to be equal with the text inserted at + * the current position. *

                                                      * - * @param offset the offset of the position. - * @param length the length of the position. - * @param additionalChoices a number of additional choices to be displayed when selecting - * a position of this type. + * @param offset + * the offset of the position. + * @param length + * the length of the position. + * @param additionalChoices + * a number of additional choices to be displayed when selecting + * a position of this type. */ - public void addPosition(int offset, int length, ICompletionProposal[] additionalChoices) throws BadLocationException { - String type= fDocument.get(offset, length); + public void addPosition(int offset, int length, + ICompletionProposal[] additionalChoices) + throws BadLocationException { + String type = fDocument.get(offset, length); addPosition(offset, length, type, additionalChoices); } + /** - * Adds a linked position of the specified position type to the manager. + * Adds a linked position of the specified position type to the manager. * There are the following constraints for linked positions: * *
                                                        - *
                                                      • Any two positions have spacing of at least one character. - * This implies that two positions must not overlap.
                                                      • - * - *
                                                      • The string at any position must not contain line delimiters.
                                                      • + *
                                                      • Any two positions have spacing of at least one character. This + * implies that two positions must not overlap.
                                                      • + * + *
                                                      • The string at any position must not contain line delimiters.
                                                      • *
                                                      * - * It is usually best to set the first item in additionalChoices to be equal with - * the text inserted at the current position. + * It is usually best to set the first item in + * additionalChoices to be equal with the text inserted at + * the current position. * - * @param offset the offset of the position. - * @param length the length of the position. - * @param type the position type name - any positions with the same type are linked. - * @param additionalChoices a number of additional choices to be displayed when selecting - * a position of this type. + * @param offset + * the offset of the position. + * @param length + * the length of the position. + * @param type + * the position type name - any positions with the same type are + * linked. + * @param additionalChoices + * a number of additional choices to be displayed when selecting + * a position of this type. */ - public void addPosition(int offset, int length, String type, ICompletionProposal[] additionalChoices) throws BadLocationException { - Position[] positions= getPositions(fDocument); + public void addPosition(int offset, int length, String type, + ICompletionProposal[] additionalChoices) + throws BadLocationException { + Position[] positions = getPositions(fDocument); if (positions != null) { for (int i = 0; i < positions.length; i++) if (collides(positions[i], offset, length)) - throw new BadLocationException(LinkedPositionMessages.getString(("LinkedPositionManager.error.position.collision"))); //$NON-NLS-1$ + throw new BadLocationException( + LinkedPositionMessages + .getString(("LinkedPositionManager.error.position.collision"))); //$NON-NLS-1$ } - - String content= fDocument.get(offset, length); + + String content = fDocument.get(offset, length); if (containsLineDelimiters(content)) - throw new BadLocationException(LinkedPositionMessages.getString(("LinkedPositionManager.error.contains.line.delimiters"))); //$NON-NLS-1$ + throw new BadLocationException( + LinkedPositionMessages + .getString(("LinkedPositionManager.error.contains.line.delimiters"))); //$NON-NLS-1$ try { - fDocument.addPosition(fPositionCategoryName, new ProposalPosition(offset, length, type, additionalChoices)); + fDocument.addPosition(fPositionCategoryName, new ProposalPosition( + offset, length, type, additionalChoices)); } catch (BadPositionCategoryException e) { - PHPeclipsePlugin.log(e); + PHPeclipsePlugin.log(e); Assert.isTrue(false); } } - + /** * Tests if a manager is already active for a document. */ public static boolean hasActiveManager(IDocument document) { return fgActiveManagers.get(document) != null; } - + private void install(boolean canCoexist) { - + if (fIsActive) - ;//JavaPlugin.log(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionManager is already active: "+fPositionCategoryName, new IllegalStateException())); //$NON-NLS-1$ + ;// JavaPlugin.log(new Status(IStatus.WARNING, + // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionManager + // is already active: "+fPositionCategoryName, new + // IllegalStateException())); //$NON-NLS-1$ else { - fIsActive= true; - //JavaPlugin.log(new Status(IStatus.INFO, JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionManager activated: "+fPositionCategoryName, new Exception())); //$NON-NLS-1$ + fIsActive = true; + // JavaPlugin.log(new Status(IStatus.INFO, JavaPlugin.getPluginId(), + // IStatus.OK, "LinkedPositionManager activated: + // "+fPositionCategoryName, new Exception())); //$NON-NLS-1$ } - + if (!canCoexist) { - LinkedPositionManager manager= (LinkedPositionManager) fgActiveManagers.get(fDocument); + LinkedPositionManager manager = (LinkedPositionManager) fgActiveManagers + .get(fDocument); if (manager != null) - manager.leave(true); + manager.leave(true); } - + fgActiveManagers.put(fDocument, this); fDocument.addPositionCategory(fPositionCategoryName); - fDocument.addPositionUpdater(this); + fDocument.addPositionUpdater(this); fDocument.addDocumentListener(this); - - fMustLeave= false; - } - + + fMustLeave = false; + } + /** - * Leaves the linked mode. If unsuccessful, the linked positions - * are restored to the values at the time they were added. + * Leaves the linked mode. If unsuccessful, the linked positions are + * restored to the values at the time they were added. */ - public void uninstall(boolean success) { - + public void uninstall(boolean success) { + if (!fIsActive) // we migth also just return - ;//JavaPlugin(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionManager activated: "+fPositionCategoryName, new IllegalStateException())); //$NON-NLS-1$ + ;// JavaPlugin(new Status(IStatus.WARNING, + // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionManager + // activated: "+fPositionCategoryName, new + // IllegalStateException())); //$NON-NLS-1$ else { fDocument.removeDocumentListener(this); - + try { - Position[] positions= getPositions(fDocument); + Position[] positions = getPositions(fDocument); if ((!success) && (positions != null)) { // restore - for (int i= 0; i != positions.length; i++) { - TypedPosition position= (TypedPosition) positions[i]; - fDocument.replace(position.getOffset(), position.getLength(), position.getType()); + for (int i = 0; i != positions.length; i++) { + TypedPosition position = (TypedPosition) positions[i]; + fDocument.replace(position.getOffset(), position + .getLength(), position.getType()); } - } - + } + fDocument.removePositionCategory(fPositionCategoryName); - - fIsActive= false; - // JavaPlugin.log(new Status(IStatus.INFO, JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionManager deactivated: "+fPositionCategoryName, new Exception())); //$NON-NLS-1$ - + + fIsActive = false; + // JavaPlugin.log(new Status(IStatus.INFO, + // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionManager + // deactivated: "+fPositionCategoryName, new Exception())); + // //$NON-NLS-1$ + } catch (BadLocationException e) { - PHPeclipsePlugin.log(e); + PHPeclipsePlugin.log(e); Assert.isTrue(false); - + } catch (BadPositionCategoryException e) { - PHPeclipsePlugin.log(e); + PHPeclipsePlugin.log(e); Assert.isTrue(false); - + } finally { - fDocument.removePositionUpdater(this); - fgActiveManagers.remove(fDocument); + fDocument.removePositionUpdater(this); + fgActiveManagers.remove(fDocument); } } - + } /** - * Returns the position at the given offset, null if there is no position. + * Returns the position at the given offset, null if there is + * no position. + * * @since 2.1 */ public Position getPosition(int offset) { - Position[] positions= getPositions(fDocument); + Position[] positions = getPositions(fDocument); if (positions == null) return null; - for (int i= positions.length - 1; i >= 0; i--) { - Position position= positions[i]; - if (offset >= position.getOffset() && offset <= position.getOffset() + position.getLength()) + for (int i = positions.length - 1; i >= 0; i--) { + Position position = positions[i]; + if (offset >= position.getOffset() + && offset <= position.getOffset() + position.getLength()) return positions[i]; } - + return null; } @@ -370,75 +441,78 @@ public class LinkedPositionManager implements IDocumentListener, IPositionUpdate public Position getFirstPosition() { return getNextPosition(-1); } - + public Position getLastPosition() { - Position[] positions= getPositions(fDocument); - for (int i= positions.length - 1; i >= 0; i--) { - String type= ((TypedPosition) positions[i]).getType(); + Position[] positions = getPositions(fDocument); + for (int i = positions.length - 1; i >= 0; i--) { + String type = ((TypedPosition) positions[i]).getType(); int j; for (j = 0; j != i; j++) if (((TypedPosition) positions[j]).getType().equals(type)) break; if (j == i) - return positions[i]; + return positions[i]; } return null; } /** - * Returns the next linked position with an offset greater than offset. - * If another position with the same type and offset lower than offset - * exists, the position is skipped. + * Returns the next linked position with an offset greater than + * offset. If another position with the same type and offset + * lower than offset exists, the position is skipped. * * @return returns null if no linked position exist. */ public Position getNextPosition(int offset) { - Position[] positions= getPositions(fDocument); + Position[] positions = getPositions(fDocument); return findNextPosition(positions, offset); } private static Position findNextPosition(Position[] positions, int offset) { // skip already visited types - for (int i= 0; i != positions.length; i++) { + for (int i = 0; i != positions.length; i++) { if (positions[i].getOffset() > offset) { - String type= ((TypedPosition) positions[i]).getType(); + String type = ((TypedPosition) positions[i]).getType(); int j; for (j = 0; j != i; j++) if (((TypedPosition) positions[j]).getType().equals(type)) break; if (j == i) - return positions[i]; + return positions[i]; } } return null; } - + /** - * Returns the position with the greatest offset smaller than offset. - * + * Returns the position with the greatest offset smaller than + * offset. + * * @return returns null if no linked position exist. */ public Position getPreviousPosition(int offset) { - Position[] positions= getPositions(fDocument); + Position[] positions = getPositions(fDocument); if (positions == null) return null; - TypedPosition currentPosition= (TypedPosition) findCurrentPosition(positions, offset); - String currentType= currentPosition == null ? null : currentPosition.getType(); + TypedPosition currentPosition = (TypedPosition) findCurrentPosition( + positions, offset); + String currentType = currentPosition == null ? null : currentPosition + .getType(); - Position lastPosition= null; - Position position= getFirstPosition(); + Position lastPosition = null; + Position position = getFirstPosition(); while (position != null && position.getOffset() < offset) { if (!((TypedPosition) position).getType().equals(currentType)) - lastPosition= position; - position= findNextPosition(positions, position.getOffset()); + lastPosition = position; + position = findNextPosition(positions, position.getOffset()); } - + return lastPosition; } @@ -446,60 +520,64 @@ public class LinkedPositionManager implements IDocumentListener, IPositionUpdate if (!fIsActive) // we migth also just return an empty array - ;//JavaPlugin(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionManager is not active: "+fPositionCategoryName, new IllegalStateException())); //$NON-NLS-1$ - + ;// JavaPlugin(new Status(IStatus.WARNING, + // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionManager + // is not active: "+fPositionCategoryName, new + // IllegalStateException())); //$NON-NLS-1$ + try { - Position[] positions= document.getPositions(fPositionCategoryName); + Position[] positions = document.getPositions(fPositionCategoryName); Arrays.sort(positions, fgPositionComparator); return positions; } catch (BadPositionCategoryException e) { - PHPeclipsePlugin.log(e); + PHPeclipsePlugin.log(e); Assert.isTrue(false); } - + return null; - } + } public static boolean includes(Position position, int offset, int length) { - return - (offset >= position.getOffset()) && - (offset + length <= position.getOffset() + position.getLength()); + return (offset >= position.getOffset()) + && (offset + length <= position.getOffset() + + position.getLength()); } public static boolean excludes(Position position, int offset, int length) { - return - (offset + length <= position.getOffset()) || - (position.getOffset() + position.getLength() <= offset); + return (offset + length <= position.getOffset()) + || (position.getOffset() + position.getLength() <= offset); } /* * Collides if spacing if positions intersect each other or are adjacent. */ private static boolean collides(Position position, int offset, int length) { - return - (offset <= position.getOffset() + position.getLength()) && - (position.getOffset() <= offset + length); + return (offset <= position.getOffset() + position.getLength()) + && (position.getOffset() <= offset + length); } - + private void leave(boolean success) { try { uninstall(success); - + if (fListener != null) - fListener.exit((success ? LinkedPositionUI.COMMIT : 0) | LinkedPositionUI.UPDATE_CARET); + fListener.exit((success ? LinkedPositionUI.COMMIT : 0) + | LinkedPositionUI.UPDATE_CARET); } finally { - fMustLeave= false; - } + fMustLeave = false; + } } - + private void abort() { uninstall(true); // don't revert anything - + if (fListener != null) - fListener.exit(LinkedPositionUI.COMMIT); // don't let the UI restore anything - - // don't set fMustLeave, as we will get re-registered by a document event + fListener.exit(LinkedPositionUI.COMMIT); // don't let the UI + // restore anything + + // don't set fMustLeave, as we will get re-registered by a document + // event } /* @@ -512,29 +590,30 @@ public class LinkedPositionManager implements IDocumentListener, IPositionUpdate return; } - IDocument document= event.getDocument(); + IDocument document = event.getDocument(); - Position[] positions= getPositions(document); - Position position= findCurrentPosition(positions, event.getOffset()); + Position[] positions = getPositions(document); + Position position = findCurrentPosition(positions, event.getOffset()); // modification outside editable position if (position == null) { // check for destruction of constraints (spacing of at least 1) - if ((event.getText() == null || event.getText().length() == 0) && - (findCurrentPosition(positions, event.getOffset()) != null) && // will never become true, see condition above - (findCurrentPosition(positions, event.getOffset() + event.getLength()) != null)) - { + if ((event.getText() == null || event.getText().length() == 0) + && (findCurrentPosition(positions, event.getOffset()) != null) + && // will never become true, see condition above + (findCurrentPosition(positions, event.getOffset() + + event.getLength()) != null)) { leave(true); - } + } - // modification intersects editable position + // modification intersects editable position } else { // modificaction inside editable position if (includes(position, event.getOffset(), event.getLength())) { if (containsLineDelimiters(event.getText())) leave(true); - // modificaction exceeds editable position + // modificaction exceeds editable position } else { leave(true); } @@ -545,73 +624,81 @@ public class LinkedPositionManager implements IDocumentListener, IPositionUpdate * @see IDocumentListener#documentChanged(DocumentEvent) */ public void documentChanged(DocumentEvent event) { - - // have to handle code assist, so can't just leave the linked mode + + // have to handle code assist, so can't just leave the linked mode // leave(true); - - IDocument document= event.getDocument(); - Position[] positions= getPositions(document); - TypedPosition currentPosition= (TypedPosition) findCurrentPosition(positions, event.getOffset()); + IDocument document = event.getDocument(); + + Position[] positions = getPositions(document); + TypedPosition currentPosition = (TypedPosition) findCurrentPosition( + positions, event.getOffset()); // ignore document changes (assume it won't invalidate constraints) if (currentPosition == null) return; - - int deltaOffset= event.getOffset() - currentPosition.getOffset(); + + int deltaOffset = event.getOffset() - currentPosition.getOffset(); if (fListener != null) { - int length= event.getText() == null ? 0 : event.getText().length(); - fListener.setCurrentPosition(currentPosition, deltaOffset + length); + int length = event.getText() == null ? 0 : event.getText().length(); + fListener.setCurrentPosition(currentPosition, deltaOffset + length); } - for (int i= 0; i != positions.length; i++) { - TypedPosition p= (TypedPosition) positions[i]; - - if (p.getType().equals(currentPosition.getType()) && !p.equals(currentPosition)) { - Replace replace= new Replace(p, deltaOffset, event.getLength(), event.getText()); - ((IDocumentExtension) document).registerPostNotificationReplace(this, replace); + for (int i = 0; i != positions.length; i++) { + TypedPosition p = (TypedPosition) positions[i]; + + if (p.getType().equals(currentPosition.getType()) + && !p.equals(currentPosition)) { + Replace replace = new Replace(p, deltaOffset, + event.getLength(), event.getText()); + ((IDocumentExtension) document) + .registerPostNotificationReplace(this, replace); } } } - + /* * @see IPositionUpdater#update(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; - - Position[] positions= getPositions(event.getDocument()); - - - for (int i= 0; i != positions.length; i++) { - - Position position= positions[i]; - + + int eventOffset = event.getOffset(); + int eventOldLength = event.getLength(); + int eventNewLength = event.getText() == null ? 0 : event.getText() + .length(); + int deltaLength = eventNewLength - eventOldLength; + + Position[] positions = getPositions(event.getDocument()); + + 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 + + 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 (end < eventOffset) // position comes way before change - + // leave alone ; - else if (offset <= eventOffset && end >= eventOffset + eventOldLength) { + 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; + int newEnd = eventOffset + eventNewLength; position.setLength(newEnd - offset); - } else if (end > eventOffset + eventOldLength) { - // event extends from before position into it - adjust offset and length + } 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 int newOffset = eventOffset + eventNewLength; @@ -620,71 +707,77 @@ public class LinkedPositionManager implements IDocumentListener, IPositionUpdate } else { // event consumes the position - delete it position.delete(); -// JavaPlugin.log(new Status(IStatus.INFO, JavaPlugin.getPluginId(), IStatus.OK, "linked position deleted -> must leave: "+fPositionCategoryName, null)); //$NON-NLS-1$ - fMustLeave= true; + // JavaPlugin.log(new Status(IStatus.INFO, + // JavaPlugin.getPluginId(), IStatus.OK, "linked position + // deleted -> must leave: "+fPositionCategoryName, null)); + // //$NON-NLS-1$ + fMustLeave = true; } } - + if (fMustLeave) abort(); } private static Position findCurrentPosition(Position[] positions, int offset) { - for (int i= 0; i != positions.length; i++) + for (int i = 0; i != positions.length; i++) if (includes(positions[i], offset, 0)) return positions[i]; - - return null; + + return null; } private boolean containsLineDelimiters(String string) { - + if (string == null) return false; - - String[] delimiters= fDocument.getLegalLineDelimiters(); - for (int i= 0; i != delimiters.length; i++) + String[] delimiters = fDocument.getLegalLineDelimiters(); + + for (int i = 0; i != delimiters.length; i++) if (string.indexOf(delimiters[i]) != -1) return true; return false; } - + /** * Test if ok to modify through UI. */ public boolean anyPositionIncludes(int offset, int length) { - Position[] positions= getPositions(fDocument); + Position[] positions = getPositions(fDocument); - Position position= findCurrentPosition(positions, offset); + Position position = findCurrentPosition(positions, offset); if (position == null) return false; - + return includes(position, offset, length); } - + /** * Returns the position that includes the given range. + * * @param offset * @param length * @return position that includes the given range */ public Position getEmbracingPosition(int offset, int length) { - Position[] positions= getPositions(fDocument); + Position[] positions = getPositions(fDocument); - Position position= findCurrentPosition(positions, offset); + Position position = findCurrentPosition(positions, offset); if (position != null && includes(position, offset, length)) return position; - + return null; } - + /* - * @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.DocumentCommand) + * @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, + * org.eclipse.jface.text.DocumentCommand) */ - public void customizeDocumentCommand(IDocument document, DocumentCommand command) { - + public void customizeDocumentCommand(IDocument document, + DocumentCommand command) { + if (fMustLeave) { leave(true); return; @@ -696,8 +789,9 @@ public class LinkedPositionManager implements IDocumentListener, IPositionUpdate return; } - Position[] positions= getPositions(document); - TypedPosition currentPosition= (TypedPosition) findCurrentPosition(positions, command.offset); + Position[] positions = getPositions(document); + TypedPosition currentPosition = (TypedPosition) findCurrentPosition( + positions, command.offset); // handle edits outside of a position if (currentPosition == null) { @@ -705,26 +799,29 @@ public class LinkedPositionManager implements IDocumentListener, IPositionUpdate return; } - if (! command.doit) + if (!command.doit) return; - command.doit= false; - command.owner= this; - command.caretOffset= command.offset + command.length; + command.doit = false; + command.owner = this; + command.caretOffset = command.offset + command.length; - int deltaOffset= command.offset - currentPosition.getOffset(); + int deltaOffset = command.offset - currentPosition.getOffset(); if (fListener != null) - fListener.setCurrentPosition(currentPosition, deltaOffset + command.text.length()); - - for (int i= 0; i != positions.length; i++) { - TypedPosition position= (TypedPosition) positions[i]; - + fListener.setCurrentPosition(currentPosition, deltaOffset + + command.text.length()); + + for (int i = 0; i != positions.length; i++) { + TypedPosition position = (TypedPosition) positions[i]; + try { - if (position.getType().equals(currentPosition.getType()) && !position.equals(currentPosition)) - command.addCommand(position.getOffset() + deltaOffset, command.length, command.text, this); + if (position.getType().equals(currentPosition.getType()) + && !position.equals(currentPosition)) + command.addCommand(position.getOffset() + deltaOffset, + command.length, command.text, this); } catch (BadLocationException e) { - PHPeclipsePlugin.log(e); + PHPeclipsePlugin.log(e); } } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionMessages.java index 4a6b8fb..decf492 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionMessages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionMessages.java @@ -10,8 +10,11 @@ import java.util.ResourceBundle; public class LinkedPositionMessages { - private static final String RESOURCE_BUNDLE= LinkedPositionMessages.class.getName(); - private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); + private static final String RESOURCE_BUNDLE = LinkedPositionMessages.class + .getName(); + + private static ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); private LinkedPositionMessages() { } @@ -23,20 +26,20 @@ public class LinkedPositionMessages { return '!' + key + '!'; } } - + /** * Gets a string from the resource bundle and formats it with the argument * - * @param key the string used to get the bundle value, must not be null + * @param key + * the string used to get the bundle value, must not be null */ public static String getFormattedString(String key, Object arg) { return MessageFormat.format(getString(key), new Object[] { arg }); } - /** * Gets a string from the resource bundle and formats it with arguments - */ + */ public static String getFormattedString(String key, Object[] args) { return MessageFormat.format(getString(key), args); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionUI.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionUI.java index 48d0b39..0d170b5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionUI.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionUI.java @@ -57,13 +57,14 @@ import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; - - /** - * A user interface for LinkedPositionManager, using ITextViewer. + * A user interface for LinkedPositionManager, using + * ITextViewer. */ public class LinkedPositionUI implements ILinkedPositionListener, - ITextInputListener, ITextListener, ModifyListener, VerifyListener, VerifyKeyListener, PaintListener, IPropertyChangeListener, ShellListener { + ITextInputListener, ITextListener, ModifyListener, VerifyListener, + VerifyKeyListener, PaintListener, IPropertyChangeListener, + ShellListener { /** * A listener for notification when the user cancelled the edit operation. @@ -74,72 +75,94 @@ public class LinkedPositionUI implements ILinkedPositionListener, public static class ExitFlags { public int flags; + public boolean doit; + public ExitFlags(int flags, boolean doit) { - this.flags= flags; - this.doit= doit; + this.flags = flags; + this.doit = doit; } } public interface ExitPolicy { - ExitFlags doExit(LinkedPositionManager manager, VerifyEvent event, int offset, int length); + ExitFlags doExit(LinkedPositionManager manager, VerifyEvent event, + int offset, int length); } // leave flags - private static final int UNINSTALL= 1; // uninstall linked position manager - public static final int COMMIT= 2; // commit changes - private static final int DOCUMENT_CHANGED= 4; // document has changed - public static final int UPDATE_CARET= 8; // update caret + private static final int UNINSTALL = 1; // uninstall linked position manager + + public static final int COMMIT = 2; // commit changes + + private static final int DOCUMENT_CHANGED = 4; // document has changed - private static final IPreferenceStore fgStore= PHPeclipsePlugin.getDefault().getPreferenceStore(); - private static final String CARET_POSITION_PREFIX= "LinkedPositionUI.caret.position"; //$NON-NLS-1$ - private static int fgCounter= 0; + public static final int UPDATE_CARET = 8; // update caret + private static final IPreferenceStore fgStore = PHPeclipsePlugin + .getDefault().getPreferenceStore(); + + private static final String CARET_POSITION_PREFIX = "LinkedPositionUI.caret.position"; //$NON-NLS-1$ + + private static int fgCounter = 0; private final ITextViewer fViewer; + private final LinkedPositionManager fManager; + private final IPositionUpdater fUpdater; + private final String fPositionCategoryName; + private Color fFrameColor; - private int fFinalCaretOffset= -1; // no final caret offset + private int fFinalCaretOffset = -1; // no final caret offset + private Position fFinalCaretPosition; private Position fFramePosition; - private int fInitialOffset= -1; + + private int fInitialOffset = -1; + private int fCaretOffset; private ExitPolicy fExitPolicy; + private ExitListener fExitListener; private boolean fNeedRedraw; private String fContentType; + private Position fPreviousPosition; -// private ContentAssistant2 fAssistant; + + // private ContentAssistant2 fAssistant; /** - * Flag that records the state of this ui object. As there are many different entities that may - * call leave or exit, these cannot always be sure whether the linked position infrastructure is - * still active. This is especially true for multithreaded situations. + * Flag that records the state of this ui object. As there are many + * different entities that may call leave or exit, these cannot always be + * sure whether the linked position infrastructure is still active. This is + * especially true for multithreaded situations. */ - private boolean fIsActive= false; + private boolean fIsActive = false; /** * Creates a user interface for LinkedPositionManager. - * - * @param viewer the text viewer. - * @param manager the LinkedPositionManager managing a IDocument of the ITextViewer. + * + * @param viewer + * the text viewer. + * @param manager + * the LinkedPositionManager managing a + * IDocument of the ITextViewer. */ public LinkedPositionUI(ITextViewer viewer, LinkedPositionManager manager) { Assert.isNotNull(viewer); Assert.isNotNull(manager); - fViewer= viewer; - fManager= manager; + fViewer = viewer; + fManager = manager; - fPositionCategoryName= CARET_POSITION_PREFIX + (fgCounter++); - fUpdater= new DefaultPositionUpdater(fPositionCategoryName); + fPositionCategoryName = CARET_POSITION_PREFIX + (fgCounter++); + fUpdater = new DefaultPositionUpdater(fPositionCategoryName); fManager.setLinkedPositionListener(this); @@ -150,7 +173,8 @@ public class LinkedPositionUI implements ILinkedPositionListener, * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { - if (event.getProperty().equals(PreferenceConstants.EDITOR_LINKED_POSITION_COLOR)) { + if (event.getProperty().equals( + PreferenceConstants.EDITOR_LINKED_POSITION_COLOR)) { initializeHighlightColor(fViewer); redrawRegion(); } @@ -161,27 +185,30 @@ public class LinkedPositionUI implements ILinkedPositionListener, if (fFrameColor != null) fFrameColor.dispose(); - StyledText text= viewer.getTextWidget(); + StyledText text = viewer.getTextWidget(); if (text != null) { - Display display= text.getDisplay(); - fFrameColor= createColor(fgStore, PreferenceConstants.EDITOR_LINKED_POSITION_COLOR, display); + Display display = text.getDisplay(); + fFrameColor = createColor(fgStore, + PreferenceConstants.EDITOR_LINKED_POSITION_COLOR, display); } } /** - * Creates a color from the information stored in the given preference store. - * Returns null if there is no such information available. + * Creates a color from the information stored in the given preference + * store. Returns null if there is no such information + * available. */ - private Color createColor(IPreferenceStore store, String key, Display display) { + private Color createColor(IPreferenceStore store, String key, + Display display) { - RGB rgb= null; + RGB rgb = null; if (store.contains(key)) { if (store.isDefault(key)) - rgb= PreferenceConverter.getDefaultColor(store, key); + rgb = PreferenceConverter.getDefaultColor(store, key); else - rgb= PreferenceConverter.getColor(store, key); + rgb = PreferenceConverter.getColor(store, key); if (rgb != null) return new Color(display, rgb); @@ -192,20 +219,21 @@ public class LinkedPositionUI implements ILinkedPositionListener, /** * Sets the initial offset. + * * @param offset */ public void setInitialOffset(int offset) { - fInitialOffset= offset; + fInitialOffset = offset; } /** * Sets the final position of the caret when the linked mode is exited - * successfully by leaving the last linked position using TAB. - * The set position will be a TAB stop as well as the positions configured in the + * successfully by leaving the last linked position using TAB. The set + * position will be a TAB stop as well as the positions configured in the * LinkedPositionManager. */ public void setFinalCaretOffset(int offset) { - fFinalCaretOffset= offset; + fFinalCaretOffset = offset; } /** @@ -213,81 +241,91 @@ public class LinkedPositionUI implements ILinkedPositionListener, * is exited unsuccessfully by hitting ESC. */ public void setCancelListener(ExitListener listener) { - fExitListener= listener; + fExitListener = listener; } /** - * Sets an ExitPolicy which decides when and how - * the linked mode is exited. + * Sets an ExitPolicy which decides when and how the linked + * mode is exited. */ public void setExitPolicy(ExitPolicy policy) { - fExitPolicy= policy; + fExitPolicy = policy; } /* - * @see LinkedPositionManager.LinkedPositionListener#setCurrentPositions(Position, int) + * @see LinkedPositionManager.LinkedPositionListener#setCurrentPositions(Position, + * int) */ public void setCurrentPosition(Position position, int caretOffset) { if (!fIsActive) - ;//JavaPlugin.log(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is not active: "+fPositionCategoryName, new IllegalStateException())); //$NON-NLS-1$ + ;// JavaPlugin.log(new Status(IStatus.WARNING, + // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is + // not active: "+fPositionCategoryName, new + // IllegalStateException())); //$NON-NLS-1$ if (!fFramePosition.equals(position)) { - fNeedRedraw= true; - fFramePosition= position; + fNeedRedraw = true; + fFramePosition = position; } - fCaretOffset= caretOffset; + fCaretOffset = caretOffset; } /** * Enters the linked mode. The linked mode can be left by calling * exit. - * + * * @see #exit(boolean) */ public void enter() { if (fIsActive) - ;//JavaPlugin.log(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is already active: "+fPositionCategoryName, new IllegalStateException())); //$NON-NLS-1$ + ;// JavaPlugin.log(new Status(IStatus.WARNING, + // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is + // already active: "+fPositionCategoryName, new + // IllegalStateException())); //$NON-NLS-1$ else { - fIsActive= true; - // JavaPlugin.log(new Status(IStatus.INFO, JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI activated: "+fPositionCategoryName, new Exception())); //$NON-NLS-1$ + fIsActive = true; + // JavaPlugin.log(new Status(IStatus.INFO, JavaPlugin.getPluginId(), + // IStatus.OK, "LinkedPositionUI activated: "+fPositionCategoryName, + // new Exception())); //$NON-NLS-1$ } - // track final caret - IDocument document= fViewer.getDocument(); + IDocument document = fViewer.getDocument(); document.addPositionCategory(fPositionCategoryName); document.addPositionUpdater(fUpdater); try { if (fFinalCaretOffset != -1) { - fFinalCaretPosition= new Position(fFinalCaretOffset); - document.addPosition(fPositionCategoryName, fFinalCaretPosition); + fFinalCaretPosition = new Position(fFinalCaretOffset); + document + .addPosition(fPositionCategoryName, fFinalCaretPosition); } } catch (BadLocationException e) { handleException(fViewer.getTextWidget().getShell(), e); } catch (BadPositionCategoryException e) { - PHPeclipsePlugin.log(e); + PHPeclipsePlugin.log(e); Assert.isTrue(false); } fViewer.addTextInputListener(this); fViewer.addTextListener(this); - ITextViewerExtension extension= (ITextViewerExtension) fViewer; + ITextViewerExtension extension = (ITextViewerExtension) fViewer; extension.prependVerifyKeyListener(this); - StyledText text= fViewer.getTextWidget(); + StyledText text = fViewer.getTextWidget(); text.addVerifyListener(this); text.addModifyListener(this); text.addPaintListener(this); text.showSelection(); - Shell shell= text.getShell(); + Shell shell = text.getShell(); shell.addShellListener(this); - fFramePosition= (fInitialOffset == -1) ? fManager.getFirstPosition() : fManager.getPosition(fInitialOffset); + fFramePosition = (fInitialOffset == -1) ? fManager.getFirstPosition() + : fManager.getPosition(fInitialOffset); if (fFramePosition == null) { leave(UNINSTALL | COMMIT | UPDATE_CARET); return; @@ -295,30 +333,33 @@ public class LinkedPositionUI implements ILinkedPositionListener, fgStore.addPropertyChangeListener(this); -// try { -// fContentType= TextUtilities.getContentType(document, IJavaPartitions.JAVA_PARTITIONING, fFramePosition.offset); -// if (fViewer instanceof ITextViewerExtension2) { -// ((ITextViewerExtension2) fViewer).prependAutoEditStrategy(fManager, fContentType); -// } else { -// Assert.isTrue(false); -// } -// -// } catch (BadLocationException e) { -// handleException(fViewer.getTextWidget().getShell(), e); -// } + // try { + // fContentType= TextUtilities.getContentType(document, + // IJavaPartitions.JAVA_PARTITIONING, fFramePosition.offset); + // if (fViewer instanceof ITextViewerExtension2) { + // ((ITextViewerExtension2) fViewer).prependAutoEditStrategy(fManager, + // fContentType); + // } else { + // Assert.isTrue(false); + // } + // + // } catch (BadLocationException e) { + // handleException(fViewer.getTextWidget().getShell(), e); + // } try { - fContentType= document.getContentType(fFramePosition.offset); - if (fViewer instanceof ITextViewerExtension2) { - ((ITextViewerExtension2) fViewer).prependAutoEditStrategy(fManager, fContentType); - } else { - Assert.isTrue(false); - } + fContentType = document.getContentType(fFramePosition.offset); + if (fViewer instanceof ITextViewerExtension2) { + ((ITextViewerExtension2) fViewer).prependAutoEditStrategy( + fManager, fContentType); + } else { + Assert.isTrue(false); + } } catch (BadLocationException e) { - handleException(fViewer.getTextWidget().getShell(), e); + handleException(fViewer.getTextWidget().getShell(), e); } selectRegion(); -// triggerContentAssist(); + // triggerContentAssist(); } /* @@ -334,24 +375,32 @@ public class LinkedPositionUI implements ILinkedPositionListener, */ public IRegion getSelectedRegion() { if (!fIsActive) - ;//JavaPlugin.log(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is not active: "+fPositionCategoryName, new IllegalStateException())); //$NON-NLS-1$ + ;// JavaPlugin.log(new Status(IStatus.WARNING, + // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is + // not active: "+fPositionCategoryName, new + // IllegalStateException())); //$NON-NLS-1$ if (fFramePosition == null) return new Region(fFinalCaretOffset, 0); else - return new Region(fFramePosition.getOffset(), fFramePosition.getLength()); + return new Region(fFramePosition.getOffset(), fFramePosition + .getLength()); } private void leave(int flags) { if (!fIsActive) - ;//JavaPlugin.log(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is not active: "+fPositionCategoryName, new IllegalStateException())); //$NON-NLS-1$ + ;// JavaPlugin.log(new Status(IStatus.WARNING, + // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is + // not active: "+fPositionCategoryName, new + // IllegalStateException())); //$NON-NLS-1$ else { - fIsActive= false; - //JavaPlugin.log(new Status(IStatus.INFO, JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI deactivated: "+fPositionCategoryName, new Exception())); //$NON-NLS-1$ + fIsActive = false; + // JavaPlugin.log(new Status(IStatus.INFO, JavaPlugin.getPluginId(), + // IStatus.OK, "LinkedPositionUI deactivated: + // "+fPositionCategoryName, new Exception())); //$NON-NLS-1$ } - - fInitialOffset= -1; + fInitialOffset = -1; if ((flags & UNINSTALL) != 0) fManager.uninstall((flags & COMMIT) != 0); @@ -360,11 +409,12 @@ public class LinkedPositionUI implements ILinkedPositionListener, if (fFrameColor != null) { fFrameColor.dispose(); - fFrameColor= null; + fFrameColor = null; } - StyledText text= fViewer.getTextWidget(); - // bail out if the styled text is null, meaning the viewer has been disposed (-> document is null as well) + StyledText text = fViewer.getTextWidget(); + // bail out if the styled text is null, meaning the viewer has been + // disposed (-> document is null as well) // see pr https://bugs.eclipse.org/bugs/show_bug.cgi?id=46821 if (text == null) return; @@ -373,55 +423,58 @@ public class LinkedPositionUI implements ILinkedPositionListener, text.removeModifyListener(this); text.removeVerifyListener(this); - Shell shell= text.getShell(); + Shell shell = text.getShell(); shell.removeShellListener(this); -// if (fAssistant != null) { -// Display display= text.getDisplay(); -// if (display != null && !display.isDisposed()) { -// display.asyncExec(new Runnable() { -// public void run() { -// if (fAssistant != null) { -// fAssistant.uninstall(); -// fAssistant= null; -// } -// } -// }); -// } -// } - - ITextViewerExtension extension= (ITextViewerExtension) fViewer; + // if (fAssistant != null) { + // Display display= text.getDisplay(); + // if (display != null && !display.isDisposed()) { + // display.asyncExec(new Runnable() { + // public void run() { + // if (fAssistant != null) { + // fAssistant.uninstall(); + // fAssistant= null; + // } + // } + // }); + // } + // } + + ITextViewerExtension extension = (ITextViewerExtension) fViewer; extension.removeVerifyKeyListener(this); - IRewriteTarget target= extension.getRewriteTarget(); + IRewriteTarget target = extension.getRewriteTarget(); target.endCompoundChange(); if (fViewer instanceof ITextViewerExtension2 && fContentType != null) - ((ITextViewerExtension2) fViewer).removeAutoEditStrategy(fManager, fContentType); - fContentType= null; + ((ITextViewerExtension2) fViewer).removeAutoEditStrategy(fManager, + fContentType); + fContentType = null; fViewer.removeTextListener(this); fViewer.removeTextInputListener(this); try { - IDocument document= fViewer.getDocument(); + IDocument document = fViewer.getDocument(); - if (((flags & COMMIT) != 0) && - ((flags & DOCUMENT_CHANGED) == 0) && - ((flags & UPDATE_CARET) != 0)) - { - Position[] positions= document.getPositions(fPositionCategoryName); + if (((flags & COMMIT) != 0) && ((flags & DOCUMENT_CHANGED) == 0) + && ((flags & UPDATE_CARET) != 0)) { + Position[] positions = document + .getPositions(fPositionCategoryName); if ((positions != null) && (positions.length != 0)) { if (fViewer instanceof ITextViewerExtension5) { - ITextViewerExtension5 extension3= (ITextViewerExtension5) fViewer; - int widgetOffset= extension3.modelOffset2WidgetOffset(positions[0].getOffset()); + ITextViewerExtension5 extension3 = (ITextViewerExtension5) fViewer; + int widgetOffset = extension3 + .modelOffset2WidgetOffset(positions[0] + .getOffset()); if (widgetOffset >= 0) text.setSelection(widgetOffset, widgetOffset); } else { - IRegion region= fViewer.getVisibleRegion(); - int offset= positions[0].getOffset() - region.getOffset(); + IRegion region = fViewer.getVisibleRegion(); + int offset = positions[0].getOffset() + - region.getOffset(); if ((offset >= 0) && (offset <= region.getLength())) text.setSelection(offset, offset); } @@ -432,9 +485,8 @@ public class LinkedPositionUI implements ILinkedPositionListener, document.removePositionCategory(fPositionCategoryName); if (fExitListener != null) - fExitListener.exit( - ((flags & COMMIT) != 0) || - ((flags & DOCUMENT_CHANGED) != 0)); + fExitListener.exit(((flags & COMMIT) != 0) + || ((flags & DOCUMENT_CHANGED) != 0)); } catch (BadPositionCategoryException e) { PHPeclipsePlugin.log(e); @@ -447,76 +499,82 @@ public class LinkedPositionUI implements ILinkedPositionListener, private void next() { if (!fIsActive) - ;//JavaPlugin.log(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is not active: "+fPositionCategoryName, new IllegalStateException())); //$NON-NLS-1$ + ;// JavaPlugin.log(new Status(IStatus.WARNING, + // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is + // not active: "+fPositionCategoryName, new + // IllegalStateException())); //$NON-NLS-1$ redrawRegion(); if (fFramePosition == fFinalCaretPosition) - fFramePosition= fManager.getFirstPosition(); + fFramePosition = fManager.getFirstPosition(); else - fFramePosition= fManager.getNextPosition(fFramePosition.getOffset()); + fFramePosition = fManager.getNextPosition(fFramePosition + .getOffset()); if (fFramePosition == null) { if (fFinalCaretPosition != null) - fFramePosition= fFinalCaretPosition; + fFramePosition = fFinalCaretPosition; else - fFramePosition= fManager.getFirstPosition(); + fFramePosition = fManager.getFirstPosition(); } if (fFramePosition == null) { leave(UNINSTALL | COMMIT | UPDATE_CARET); } else { selectRegion(); -// triggerContentAssist(); + // triggerContentAssist(); redrawRegion(); } } private void previous() { if (!fIsActive) - ;//JavaPlugin.log(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is not active: "+fPositionCategoryName, new IllegalStateException())); //$NON-NLS-1$ + ;// JavaPlugin.log(new Status(IStatus.WARNING, + // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is + // not active: "+fPositionCategoryName, new + // IllegalStateException())); //$NON-NLS-1$ redrawRegion(); - fFramePosition= fManager.getPreviousPosition(fFramePosition.getOffset()); + fFramePosition = fManager.getPreviousPosition(fFramePosition + .getOffset()); if (fFramePosition == null) { if (fFinalCaretPosition != null) - fFramePosition= fFinalCaretPosition; + fFramePosition = fFinalCaretPosition; else - fFramePosition= fManager.getLastPosition(); + fFramePosition = fManager.getLastPosition(); } if (fFramePosition == null) { leave(UNINSTALL | COMMIT | UPDATE_CARET); } else { selectRegion(); -// triggerContentAssist(); + // triggerContentAssist(); redrawRegion(); } } /** Trigger content assist on choice positions */ -// private void triggerContentAssist() { -// if (fFramePosition instanceof ProposalPosition) { -// -// ProposalPosition pp= (ProposalPosition) fFramePosition; -// initializeContentAssistant(); -// if (fAssistant == null) -// return; -// fAssistant.setCompletions(pp.getChoices()); -// fAssistant.showPossibleCompletions(); -// } else { -// if (fAssistant != null) -// fAssistant.setCompletions(new ICompletionProposal[0]); -// } -// } - + // private void triggerContentAssist() { + // if (fFramePosition instanceof ProposalPosition) { + // + // ProposalPosition pp= (ProposalPosition) fFramePosition; + // initializeContentAssistant(); + // if (fAssistant == null) + // return; + // fAssistant.setCompletions(pp.getChoices()); + // fAssistant.showPossibleCompletions(); + // } else { + // if (fAssistant != null) + // fAssistant.setCompletions(new ICompletionProposal[0]); + // } + // } /** Lazy initialize content assistant for this linked ui */ -// private void initializeContentAssistant() { -// if (fAssistant != null) -// return; -// fAssistant= new ContentAssistant2(); -// fAssistant.setDocumentPartitioning(IJavaPartitions.JAVA_PARTITIONING); -// fAssistant.install(fViewer); -// } - + // private void initializeContentAssistant() { + // if (fAssistant != null) + // return; + // fAssistant= new ContentAssistant2(); + // fAssistant.setDocumentPartitioning(IJavaPartitions.JAVA_PARTITIONING); + // fAssistant.install(fViewer); + // } /* * @see VerifyKeyListener#verifyKey(VerifyEvent) */ @@ -525,72 +583,74 @@ public class LinkedPositionUI implements ILinkedPositionListener, if (!event.doit || !fIsActive) return; - Point selection= fViewer.getSelectedRange(); - int offset= selection.x; - int length= selection.y; + Point selection = fViewer.getSelectedRange(); + int offset = selection.x; + int length = selection.y; - ExitFlags exitFlags= fExitPolicy == null ? null : fExitPolicy.doExit(fManager, event, offset, length); + ExitFlags exitFlags = fExitPolicy == null ? null : fExitPolicy.doExit( + fManager, event, offset, length); if (exitFlags != null) { leave(UNINSTALL | exitFlags.flags); - event.doit= exitFlags.doit; + event.doit = exitFlags.doit; return; } switch (event.character) { // [SHIFT-]TAB = hop between edit boxes - case 0x09: - { - // if tab was treated as a document change, would it exceed variable range? - if (!LinkedPositionManager.includes(fFramePosition, offset, length)) { - leave(UNINSTALL | COMMIT); - return; - } + case 0x09: { + // if tab was treated as a document change, would it exceed variable + // range? + if (!LinkedPositionManager.includes(fFramePosition, offset, length)) { + leave(UNINSTALL | COMMIT); + return; } + } if (event.stateMask == SWT.SHIFT) previous(); else next(); - event.doit= false; + event.doit = false; break; // ENTER case 0x0A: // Ctrl+Enter - case 0x0D: - { -// if (fAssistant != null && fAssistant.wasProposalChosen()) { -// next(); -// event.doit= false; -// break; -// } - - // if enter was treated as a document change, would it exceed variable range? - if (!LinkedPositionManager.includes(fFramePosition, offset, length) - || (fFramePosition == fFinalCaretPosition)) { - leave(UNINSTALL | COMMIT); - return; - } + case 0x0D: { + // if (fAssistant != null && fAssistant.wasProposalChosen()) { + // next(); + // event.doit= false; + // break; + // } + + // if enter was treated as a document change, would it exceed + // variable range? + if (!LinkedPositionManager.includes(fFramePosition, offset, length) + || (fFramePosition == fFinalCaretPosition)) { + leave(UNINSTALL | COMMIT); + return; } + } leave(UNINSTALL | COMMIT | UPDATE_CARET); - event.doit= false; + event.doit = false; break; // ESC case 0x1B: leave(UNINSTALL | COMMIT); - event.doit= false; + event.doit = false; break; case ';': leave(UNINSTALL | COMMIT); - event.doit= true; + event.doit = true; break; default: if (event.character != 0) { - if (!controlUndoBehavior(offset, length) || fFramePosition == fFinalCaretPosition) { + if (!controlUndoBehavior(offset, length) + || fFramePosition == fFinalCaretPosition) { leave(UNINSTALL | COMMIT); break; } @@ -600,18 +660,19 @@ public class LinkedPositionUI implements ILinkedPositionListener, private boolean controlUndoBehavior(int offset, int length) { - Position position= fManager.getEmbracingPosition(offset, length); + Position position = fManager.getEmbracingPosition(offset, length); if (position != null) { - ITextViewerExtension extension= (ITextViewerExtension) fViewer; - IRewriteTarget target= extension.getRewriteTarget(); + ITextViewerExtension extension = (ITextViewerExtension) fViewer; + IRewriteTarget target = extension.getRewriteTarget(); - if (fPreviousPosition != null && !fPreviousPosition.equals(position)) + if (fPreviousPosition != null + && !fPreviousPosition.equals(position)) target.endCompoundChange(); target.beginCompoundChange(); } - fPreviousPosition= position; + fPreviousPosition = position; return fPreviousPosition != null; } @@ -622,23 +683,23 @@ public class LinkedPositionUI implements ILinkedPositionListener, if (!event.doit) return; - - int offset= 0; - int length= 0; + int offset = 0; + int length = 0; if (fViewer instanceof ITextViewerExtension5) { - ITextViewerExtension5 extension= (ITextViewerExtension5) fViewer; - IRegion modelRange= extension.widgetRange2ModelRange(new Region(event.start, event.end - event.start)); + ITextViewerExtension5 extension = (ITextViewerExtension5) fViewer; + IRegion modelRange = extension.widgetRange2ModelRange(new Region( + event.start, event.end - event.start)); if (modelRange == null) return; - offset= modelRange.getOffset(); - length= modelRange.getLength(); + offset = modelRange.getOffset(); + length = modelRange.getLength(); } else { - IRegion visibleRegion= fViewer.getVisibleRegion(); - offset= event.start + visibleRegion.getOffset(); - length= event.end - event.start; + IRegion visibleRegion = fViewer.getVisibleRegion(); + offset = event.start + visibleRegion.getOffset(); + length = event.end - event.start; } // allow changes only within linked positions when coming through UI @@ -653,26 +714,26 @@ public class LinkedPositionUI implements ILinkedPositionListener, if (fFramePosition == null) return; - IRegion widgetRange= asWidgetRange(fFramePosition); + IRegion widgetRange = asWidgetRange(fFramePosition); if (widgetRange == null) { leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); return; } - int offset= widgetRange.getOffset(); - int length= widgetRange.getLength(); + int offset = widgetRange.getOffset(); + int length = widgetRange.getLength(); - StyledText text= fViewer.getTextWidget(); + StyledText text = fViewer.getTextWidget(); // support for bidi - Point minLocation= getMinimumLocation(text, offset, length); - Point maxLocation= getMaximumLocation(text, offset, length); + Point minLocation = getMinimumLocation(text, offset, length); + Point maxLocation = getMaximumLocation(text, offset, length); - int x1= minLocation.x; - int x2= minLocation.x + maxLocation.x - minLocation.x - 1; - int y= minLocation.y + text.getLineHeight() - 1; + int x1 = minLocation.x; + int x2 = minLocation.x + maxLocation.x - minLocation.x - 1; + int y = minLocation.y + text.getLineHeight() - 1; - GC gc= event.gc; + GC gc = event.gc; gc.setForeground(fFrameColor); gc.drawLine(x1, y, x2, y); } @@ -680,87 +741,92 @@ public class LinkedPositionUI implements ILinkedPositionListener, protected IRegion asWidgetRange(Position position) { if (fViewer instanceof ITextViewerExtension5) { - ITextViewerExtension5 extension= (ITextViewerExtension5) fViewer; - return extension.modelRange2WidgetRange(new Region(position.getOffset(), position.getLength())); + ITextViewerExtension5 extension = (ITextViewerExtension5) fViewer; + return extension.modelRange2WidgetRange(new Region(position + .getOffset(), position.getLength())); } else { - IRegion region= fViewer.getVisibleRegion(); + IRegion region = fViewer.getVisibleRegion(); if (includes(region, position)) - return new Region(position.getOffset() - region.getOffset(), position.getLength()); + return new Region(position.getOffset() - region.getOffset(), + position.getLength()); } return null; } - private static Point getMinimumLocation(StyledText text, int offset, int length) { - Point minLocation= new Point(Integer.MAX_VALUE, Integer.MAX_VALUE); + private static Point getMinimumLocation(StyledText text, int offset, + int length) { + Point minLocation = new Point(Integer.MAX_VALUE, Integer.MAX_VALUE); - for (int i= 0; i <= length; i++) { - Point location= text.getLocationAtOffset(offset + i); + for (int i = 0; i <= length; i++) { + Point location = text.getLocationAtOffset(offset + i); if (location.x < minLocation.x) - minLocation.x= location.x; + minLocation.x = location.x; if (location.y < minLocation.y) - minLocation.y= location.y; + minLocation.y = location.y; } return minLocation; } - private static Point getMaximumLocation(StyledText text, int offset, int length) { - Point maxLocation= new Point(Integer.MIN_VALUE, Integer.MIN_VALUE); + private static Point getMaximumLocation(StyledText text, int offset, + int length) { + Point maxLocation = new Point(Integer.MIN_VALUE, Integer.MIN_VALUE); - for (int i= 0; i <= length; i++) { - Point location= text.getLocationAtOffset(offset + i); + for (int i = 0; i <= length; i++) { + Point location = text.getLocationAtOffset(offset + i); if (location.x > maxLocation.x) - maxLocation.x= location.x; + maxLocation.x = location.x; if (location.y > maxLocation.y) - maxLocation.y= location.y; + maxLocation.y = location.y; } return maxLocation; } private void redrawRegion() { - IRegion widgetRange= asWidgetRange(fFramePosition); + IRegion widgetRange = asWidgetRange(fFramePosition); if (widgetRange == null) { - leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); - return; + leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); + return; } - StyledText text= fViewer.getTextWidget(); + StyledText text = fViewer.getTextWidget(); if (text != null && !text.isDisposed()) - text.redrawRange(widgetRange.getOffset(), widgetRange.getLength(), true); + text.redrawRange(widgetRange.getOffset(), widgetRange.getLength(), + true); } private void selectRegion() { - IRegion widgetRange= asWidgetRange(fFramePosition); + IRegion widgetRange = asWidgetRange(fFramePosition); if (widgetRange == null) { - leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); - return; + leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); + return; } - StyledText text= fViewer.getTextWidget(); + StyledText text = fViewer.getTextWidget(); if (text != null && !text.isDisposed()) { - int start= widgetRange.getOffset(); - int end= widgetRange.getLength() + start; + int start = widgetRange.getOffset(); + int end = widgetRange.getLength() + start; text.setSelection(start, end); } } private void updateCaret() { - IRegion widgetRange= asWidgetRange(fFramePosition); + IRegion widgetRange = asWidgetRange(fFramePosition); if (widgetRange == null) { - leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); - return; + leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); + return; } - int offset= widgetRange.getOffset() + fCaretOffset; - StyledText text= fViewer.getTextWidget(); + int offset = widgetRange.getOffset() + fCaretOffset; + StyledText text = fViewer.getTextWidget(); if (text != null && !text.isDisposed()) text.setCaretOffset(offset); } @@ -775,11 +841,13 @@ public class LinkedPositionUI implements ILinkedPositionListener, } private static void handleException(Shell shell, Exception e) { - String title= LinkedPositionMessages.getString("LinkedPositionUI.error.title"); //$NON-NLS-1$ + String title = LinkedPositionMessages + .getString("LinkedPositionUI.error.title"); //$NON-NLS-1$ if (e instanceof CoreException) - ExceptionHandler.handle((CoreException)e, shell, title, null); + ExceptionHandler.handle((CoreException) e, shell, title, null); else if (e instanceof InvocationTargetException) - ExceptionHandler.handle((InvocationTargetException)e, shell, title, null); + ExceptionHandler.handle((InvocationTargetException) e, shell, + title, null); else { MessageDialog.openError(shell, title, e.getMessage()); PHPeclipsePlugin.log(e); @@ -787,11 +855,14 @@ public class LinkedPositionUI implements ILinkedPositionListener, } /* - * @see ITextInputListener#inputDocumentAboutToBeChanged(IDocument, IDocument) + * @see ITextInputListener#inputDocumentAboutToBeChanged(IDocument, + * IDocument) */ - public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) { + public void inputDocumentAboutToBeChanged(IDocument oldInput, + IDocument newInput) { // 5326: leave linked mode on document change - int flags= UNINSTALL | COMMIT | (oldInput.equals(newInput) ? 0 : DOCUMENT_CHANGED); + int flags = UNINSTALL | COMMIT + | (oldInput.equals(newInput) ? 0 : DOCUMENT_CHANGED); leave(flags); } @@ -802,9 +873,10 @@ public class LinkedPositionUI implements ILinkedPositionListener, } private static boolean includes(IRegion region, Position position) { - return - position.getOffset() >= region.getOffset() && - position.getOffset() + position.getLength() <= region.getOffset() + region.getLength(); + return position.getOffset() >= region.getOffset() + && position.getOffset() + position.getLength() <= region + .getOffset() + + region.getLength(); } /* @@ -815,7 +887,7 @@ public class LinkedPositionUI implements ILinkedPositionListener, return; redrawRegion(); - fNeedRedraw= false; + fNeedRedraw = false; } /* @@ -828,44 +900,54 @@ public class LinkedPositionUI implements ILinkedPositionListener, * @see org.eclipse.swt.events.ShellListener#shellClosed(org.eclipse.swt.events.ShellEvent) */ public void shellClosed(ShellEvent event) { - leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); + leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); } /* * @see org.eclipse.swt.events.ShellListener#shellDeactivated(org.eclipse.swt.events.ShellEvent) */ public void shellDeactivated(ShellEvent event) { - // don't deactivate on focus lost, since the proposal popups may take focus - // plus: it doesn't hurt if you can check with another window without losing linked mode + // don't deactivate on focus lost, since the proposal popups may take + // focus + // plus: it doesn't hurt if you can check with another window without + // losing linked mode // since there is no intrusive popup sticking out. - // need to check first what happens on reentering based on an open action + // need to check first what happens on reentering based on an open + // action // Seems to be no problem // TODO check whether we can leave it or uncomment it after debugging - // PS: why DOCUMENT_CHANGED? We want to trigger a redraw! (Shell deactivated does not mean + // PS: why DOCUMENT_CHANGED? We want to trigger a redraw! (Shell + // deactivated does not mean // it is not visible any longer. -// leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); + // leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); // Better: - // Check with content assistant and only leave if its not the proposal shell that took the + // Check with content assistant and only leave if its not the proposal + // shell that took the // focus away. StyledText text; Display display; -// if (fAssistant == null || fViewer == null || (text= fViewer.getTextWidget()) == null -// || (display= text.getDisplay()) == null || display.isDisposed()) { - if ( fViewer == null || (text= fViewer.getTextWidget()) == null - || (display= text.getDisplay()) == null || display.isDisposed()) { - leave(UNINSTALL | COMMIT); + // if (fAssistant == null || fViewer == null || (text= + // fViewer.getTextWidget()) == null + // || (display= text.getDisplay()) == null || display.isDisposed()) { + if (fViewer == null || (text = fViewer.getTextWidget()) == null + || (display = text.getDisplay()) == null + || display.isDisposed()) { + leave(UNINSTALL | COMMIT); } else { - // Post in UI thread since the assistant popup will only get the focus after we lose it. + // Post in UI thread since the assistant popup will only get the + // focus after we lose it. display.asyncExec(new Runnable() { public void run() { - // TODO add isDisposed / isUninstalled / hasLeft check? for now: check for content type, + // TODO add isDisposed / isUninstalled / hasLeft check? for + // now: check for content type, // since it gets nullified in leave() - if (fIsActive) {// && (fAssistant == null || !fAssistant.hasFocus())) { + if (fIsActive) {// && (fAssistant == null || + // !fAssistant.hasFocus())) { leave(UNINSTALL | COMMIT); } } @@ -883,7 +965,7 @@ public class LinkedPositionUI implements ILinkedPositionListener, * @see org.eclipse.swt.events.ShellListener#shellIconified(org.eclipse.swt.events.ShellEvent) */ public void shellIconified(ShellEvent event) { - leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); + leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/ProposalPosition.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/ProposalPosition.java index 6e18440..4996443 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/ProposalPosition.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/ProposalPosition.java @@ -19,8 +19,11 @@ import org.eclipse.jface.text.contentassist.ICompletionProposal; * */ public class ProposalPosition extends TypedPosition { - - /** The choices available for this position, fChoices[0] is the original type. */ + + /** + * The choices available for this position, fChoices[0] is the original + * type. + */ private final ICompletionProposal[] fChoices; /* @@ -29,26 +32,28 @@ public class ProposalPosition extends TypedPosition { public boolean equals(Object o) { if (o instanceof ProposalPosition) { if (super.equals(o)) { - return Arrays.equals(fChoices, ((ProposalPosition)o).fChoices); + return Arrays.equals(fChoices, ((ProposalPosition) o).fChoices); } } return false; } - + /** * @param offset * @param length * @param type */ - public ProposalPosition(int offset, int length, String type, ICompletionProposal[] choices) { + public ProposalPosition(int offset, int length, String type, + ICompletionProposal[] choices) { super(offset, length, type); - fChoices= new ICompletionProposal[choices.length]; + fChoices = new ICompletionProposal[choices.length]; System.arraycopy(choices, 0, fChoices, 0, choices.length); } - + /** * - * @return an array of choices, including the initial one. Clients must not modify it. + * @return an array of choices, including the initial one. Clients must not + * modify it. */ public ICompletionProposal[] getChoices() { updateChoicePositions(); @@ -59,9 +64,9 @@ public class ProposalPosition extends TypedPosition { * */ private void updateChoicePositions() { - for (int i= 0; i < fChoices.length; i++) { -// if (fChoices[i] instanceof JavaCompletionProposal) -// ((JavaCompletionProposal)fChoices[i]).setReplacementOffset(offset); + for (int i = 0; i < fChoices.length; i++) { + // if (fChoices[i] instanceof JavaCompletionProposal) + // ((JavaCompletionProposal)fChoices[i]).setReplacementOffset(offset); } } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/IHtmlTagConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/IHtmlTagConstants.java index 31f1827..859d9b3 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/IHtmlTagConstants.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/IHtmlTagConstants.java @@ -19,20 +19,23 @@ package net.sourceforge.phpdt.internal.ui.text.phpdoc; public interface IHtmlTagConstants { /** Html tag close prefix */ - public static final String HTML_CLOSE_PREFIX= "', ' ', '&', '^', '~', '\"' }; + public static final char[] HTML_ENTITY_CHARACTERS = new char[] { '<', '>', + ' ', '&', '^', '~', '\"' }; /** Html entity codes */ - public static final String[] HTML_ENTITY_CODES= new String[] { "<", ">", " ", "&", "ˆ", "˜", """ }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ + public static final String[] HTML_ENTITY_CODES = new String[] { + "<", ">", " ", "&", "ˆ", "˜", """ }; //$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[] { "b", "blockquote", "br", "code", "dd", "dl", "dt", "em", "hr", "h1", "h2", "h3", "h4", "h5", "h6", "i", "li", "nl", "ol", "p", "pre", "q", "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$ + public static final String[] HTML_GENERAL_TAGS = new String[] { + "b", "blockquote", "br", "code", "dd", "dl", "dt", "em", "hr", "h1", "h2", "h3", "h4", "h5", "h6", "i", "li", "nl", "ol", "p", "pre", "q", "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$ /** Html tag postfix */ - public static final char HTML_TAG_POSTFIX= '>'; + public static final char HTML_TAG_POSTFIX = '>'; /** Html tag prefix */ - public static final char HTML_TAG_PREFIX= '<'; + public static final char HTML_TAG_PREFIX = '<'; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/IJavaDocTagConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/IJavaDocTagConstants.java index eeaeda5..f6055c6 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/IJavaDocTagConstants.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/IJavaDocTagConstants.java @@ -19,38 +19,46 @@ package net.sourceforge.phpdt.internal.ui.text.phpdoc; public interface IJavaDocTagConstants { /** Javadoc break tags */ - public static final String[] JAVADOC_BREAK_TAGS= new String[] { "dd", "dt", "li", "td", "th", "tr", "h1", "h2", "h3", "h4", "h5", "h6", "q" }; //$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$ + public static final String[] JAVADOC_BREAK_TAGS = new String[] { + "dd", "dt", "li", "td", "th", "tr", "h1", "h2", "h3", "h4", "h5", "h6", "q" }; //$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 single break tag */ - public static final String[] JAVADOC_SINGLE_BREAK_TAG= new String[] { "br" }; //$NON-NLS-1$ + public static final String[] JAVADOC_SINGLE_BREAK_TAG = new String[] { "br" }; //$NON-NLS-1$ /** Javadoc code tags */ - public static final String[] JAVADOC_CODE_TAGS= new String[] { "pre" }; //$NON-NLS-1$ + public static final String[] JAVADOC_CODE_TAGS = new String[] { "pre" }; //$NON-NLS-1$ /** 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", "@since", "@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$ //$NON-NLS-18$ + public static final String[] JAVADOC_GENERAL_TAGS = new String[] { + "@author", "@deprecated", "@docRoot", "@exception", "@inheritDoc", "@link", "@linkplain", "@param", "@return", "@see", "@serial", "@serialData", "@serialField", "@since", "@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$ //$NON-NLS-18$ /** Javadoc immutable tags */ - public static final String[] JAVADOC_IMMUTABLE_TAGS= new String[] { "code", "em", "pre", "q", "tt" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + public static final String[] JAVADOC_IMMUTABLE_TAGS = new String[] { + "code", "em", "pre", "q", "tt" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ /** 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$ + 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 new line tags */ - public static final String[] JAVADOC_NEWLINE_TAGS= new String[] { "dd", "dt", "li", "td", "th", "tr", "h1", "h2", "h3", "h4", "h5", "h6", "q" }; //$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$ + public static final String[] JAVADOC_NEWLINE_TAGS = new String[] { + "dd", "dt", "li", "td", "th", "tr", "h1", "h2", "h3", "h4", "h5", "h6", "q" }; //$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 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$ + 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$ + 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", "@since", "@version", "@inheritDoc" }; //$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$ + public static final String[] JAVADOC_ROOT_TAGS = new String[] { + "@author", "@deprecated", "@return", "@see", "@serial", "@serialData", "@since", "@version", "@inheritDoc" }; //$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$ /** Javadoc separator tags */ - public static final String[] JAVADOC_SEPARATOR_TAGS= new String[] { "dl", "hr", "nl", "p", "pre", "ul", "ol" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ + public static final String[] JAVADOC_SEPARATOR_TAGS = new String[] { + "dl", "hr", "nl", "p", "pre", "ul", "ol" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ /** Javadoc tag prefix */ - public static final char JAVADOC_TAG_PREFIX= '@'; + public static final char JAVADOC_TAG_PREFIX = '@'; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/JavaDocAutoIndentStrategy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/JavaDocAutoIndentStrategy.java index 2f5d8b7..20f3c40 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/JavaDocAutoIndentStrategy.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/JavaDocAutoIndentStrategy.java @@ -11,7 +11,6 @@ package net.sourceforge.phpdt.internal.ui.text.phpdoc; - import java.text.BreakIterator; import net.sourceforge.phpdt.core.ICompilationUnit; @@ -42,21 +41,23 @@ import org.eclipse.ui.PlatformUI; import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; import org.eclipse.ui.texteditor.ITextEditorExtension3; - /** * Auto indent strategy for java doc comments */ -public class JavaDocAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy { +public class JavaDocAutoIndentStrategy extends + DefaultIndentLineAutoEditStrategy { private String fPartitioning; /** - * Creates a new Javadoc auto indent strategy for the given document partitioning. + * Creates a new Javadoc auto indent strategy for the given document + * partitioning. * - * @param partitioning the document partitioning + * @param partitioning + * the document partitioning */ public JavaDocAutoIndentStrategy(String partitioning) { - fPartitioning= partitioning; + fPartitioning = partitioning; } private static String getLineDelimiter(IDocument document) { @@ -64,19 +65,21 @@ public class JavaDocAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy if (document.getNumberOfLines() > 1) return document.getLineDelimiter(0); } catch (BadLocationException e) { - PHPeclipsePlugin.log(e); + PHPeclipsePlugin.log(e); } return System.getProperty("line.separator"); //$NON-NLS-1$ } /** - * Copies the indentation of the previous line and add 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 + * Copies the indentation of the previous line and add 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 jdocIndentAfterNewLine(IDocument d, DocumentCommand c) { @@ -85,70 +88,82 @@ public class JavaDocAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy try { // find start of line - int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset); - IRegion info= d.getLineInformationOfOffset(p); - int start= info.getOffset(); + int p = (c.offset == d.getLength() ? c.offset - 1 : c.offset); + IRegion info = d.getLineInformationOfOffset(p); + int start = info.getOffset(); // find white spaces - int end= findEndOfWhiteSpace(d, start, c.offset); + int end = findEndOfWhiteSpace(d, start, c.offset); - StringBuffer buf= new StringBuffer(c.text); - if (end >= start) { // 1GEYL1R: ITPJUI:ALL - java doc edit smartness not work for class comments + StringBuffer buf = new StringBuffer(c.text); + if (end >= start) { // 1GEYL1R: ITPJUI:ALL - java doc edit smartness + // not work for class comments // append to input - String indentation= jdocExtractLinePrefix(d, d.getLineOfOffset(c.offset)); + String indentation = jdocExtractLinePrefix(d, d + .getLineOfOffset(c.offset)); buf.append(indentation); if (end < c.offset) { if (d.getChar(end) == '/') { // javadoc started on this line buf.append(" * "); //$NON-NLS-1$ - if (PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CLOSE_JAVADOCS) && isNewComment(d, c.offset, fPartitioning)) { - String lineDelimiter= getLineDelimiter(d); + if (PHPeclipsePlugin + .getDefault() + .getPreferenceStore() + .getBoolean( + PreferenceConstants.EDITOR_CLOSE_JAVADOCS) + && isNewComment(d, c.offset, fPartitioning)) { + String lineDelimiter = getLineDelimiter(d); - String endTag= lineDelimiter + indentation + " */"; //$NON-NLS-1$ + String endTag = lineDelimiter + indentation + " */"; //$NON-NLS-1$ d.replace(c.offset, 0, endTag); //$NON-NLS-1$ // evaluate method signature - ICompilationUnit unit= getCompilationUnit(); - -// if (PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS) && -// unit != null) -// { -// try { -// JavaModelUtil.reconcile(unit); -// String string= createJavaDocTags(d, c, indentation, lineDelimiter, unit); -// if (string != null) { -// d.replace(c.offset, 0, string); -// } -// } catch (CoreException e) { -// // ignore -// } -// } + ICompilationUnit unit = getCompilationUnit(); + + // if + // (PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS) + // && + // unit != null) + // { + // try { + // JavaModelUtil.reconcile(unit); + // String string= createJavaDocTags(d, c, + // indentation, lineDelimiter, unit); + // if (string != null) { + // d.replace(c.offset, 0, string); + // } + // } catch (CoreException e) { + // // ignore + // } + // } } } } } - c.text= buf.toString(); + c.text = buf.toString(); } catch (BadLocationException excp) { // stop work } } - private String createJavaDocTags(IDocument document, DocumentCommand command, String indentation, String lineDelimiter, ICompilationUnit unit) - throws CoreException, BadLocationException - { - IJavaElement element= unit.getElementAt(command.offset); + private String createJavaDocTags(IDocument document, + DocumentCommand command, String indentation, String lineDelimiter, + ICompilationUnit unit) throws CoreException, BadLocationException { + IJavaElement element = unit.getElementAt(command.offset); if (element == null) return null; switch (element.getElementType()) { case IJavaElement.TYPE: - return createTypeTags(document, command, indentation, lineDelimiter, (IType) element); + return createTypeTags(document, command, indentation, + lineDelimiter, (IType) element); case IJavaElement.METHOD: - return createMethodTags(document, command, indentation, lineDelimiter, (IMethod) element); + return createMethodTags(document, command, indentation, + lineDelimiter, (IMethod) element); default: return null; @@ -156,70 +171,87 @@ public class JavaDocAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy } /* - * Removes start and end of a comment and corrects indentation and line delimiters. + * Removes start and end of a comment and corrects indentation and line + * delimiters. */ - private String prepareTemplateComment(String comment, String indentation, String lineDelimiter) { - // trim comment start and end if any + private String prepareTemplateComment(String comment, String indentation, + 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(); + 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 '/**' + comment = comment.substring(3); // remove '/**' } else { - comment= comment.substring(2); // remove '/*' + comment = comment.substring(2); // remove '/*' } } -// return Strings.changeIndent(comment, 0, CodeFormatterUtil.getTabWidth(), indentation, lineDelimiter); - return Strings.changeIndent(comment, 0, getTabWidth(), indentation, lineDelimiter); + // return Strings.changeIndent(comment, 0, + // CodeFormatterUtil.getTabWidth(), indentation, lineDelimiter); + return Strings.changeIndent(comment, 0, getTabWidth(), indentation, + lineDelimiter); } public static int getTabWidth() { - Preferences preferences= PHPeclipsePlugin.getDefault().getPluginPreferences(); - return preferences.getInt(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH); + Preferences preferences = PHPeclipsePlugin.getDefault() + .getPluginPreferences(); + return preferences + .getInt(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH); } - private String createTypeTags(IDocument document, DocumentCommand command, String indentation, String lineDelimiter, IType type) - throws CoreException - { - String comment= CodeGeneration.getTypeComment(type.getCompilationUnit(), type.getTypeQualifiedName('.'), lineDelimiter); + private String createTypeTags(IDocument document, DocumentCommand command, + String indentation, String lineDelimiter, IType type) + throws CoreException { + String comment = CodeGeneration.getTypeComment(type + .getCompilationUnit(), type.getTypeQualifiedName('.'), + lineDelimiter); if (comment != null) { - return prepareTemplateComment(comment.trim(), indentation, lineDelimiter); + return prepareTemplateComment(comment.trim(), indentation, + lineDelimiter); } return null; } - private String createMethodTags(IDocument document, DocumentCommand command, String indentation, String lineDelimiter, IMethod method) - throws CoreException, BadLocationException - { - IRegion partition= TextUtilities.getPartition(document, fPartitioning, command.offset, false); - ISourceRange sourceRange= method.getSourceRange(); - if (sourceRange == null || sourceRange.getOffset() != partition.getOffset()) + private String createMethodTags(IDocument document, + DocumentCommand command, String indentation, String lineDelimiter, + IMethod method) throws CoreException, BadLocationException { + IRegion partition = TextUtilities.getPartition(document, fPartitioning, + command.offset, false); + ISourceRange sourceRange = method.getSourceRange(); + if (sourceRange == null + || sourceRange.getOffset() != partition.getOffset()) return null; -// IMethod inheritedMethod= getInheritedMethod(method); -// String comment= CodeGeneration.getMethodComment(method, inheritedMethod, lineDelimiter); -// if (comment != null) { -// comment= comment.trim(); -// boolean javadocComment= comment.startsWith("/**"); //$NON-NLS-1$ -// boolean isJavaDoc= partition.getLength() >= 3 && document.get(partition.getOffset(), 3).equals("/**"); //$NON-NLS-1$ -// if (javadocComment == isJavaDoc) { -// return prepareTemplateComment(comment, indentation, lineDelimiter); -// } -// } + // IMethod inheritedMethod= getInheritedMethod(method); + // String comment= CodeGeneration.getMethodComment(method, + // inheritedMethod, lineDelimiter); + // if (comment != null) { + // comment= comment.trim(); + // boolean javadocComment= comment.startsWith("/**"); //$NON-NLS-1$ + // boolean isJavaDoc= partition.getLength() >= 3 && + // document.get(partition.getOffset(), 3).equals("/**"); //$NON-NLS-1$ + // if (javadocComment == isJavaDoc) { + // return prepareTemplateComment(comment, indentation, lineDelimiter); + // } + // } return null; } /** - * Returns the method inherited from, null if method is newly defined. + * Returns the method inherited from, null if method is newly + * defined. */ -// private static IMethod getInheritedMethod(IMethod method) throws JavaModelException { -// IType declaringType= method.getDeclaringType(); -// ITypeHierarchy typeHierarchy= SuperTypeHierarchyCache.getTypeHierarchy(declaringType); -// return JavaModelUtil.findMethodDeclarationInHierarchy(typeHierarchy, declaringType, -// method.getElementName(), method.getParameterTypes(), method.isConstructor()); -// } - + // private static IMethod getInheritedMethod(IMethod method) throws + // JavaModelException { + // IType declaringType= method.getDeclaringType(); + // ITypeHierarchy typeHierarchy= + // SuperTypeHierarchyCache.getTypeHierarchy(declaringType); + // return JavaModelUtil.findMethodDeclarationInHierarchy(typeHierarchy, + // declaringType, + // method.getElementName(), method.getParameterTypes(), + // method.isConstructor()); + // } protected void jdocIndentForCommentEnd(IDocument d, DocumentCommand c) { if (c.offset < 2 || d.getLength() == 0) { return; @@ -236,28 +268,33 @@ public class JavaDocAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy } /** - * Guesses if the command operates within a newly created javadoc comment or not. - * If in doubt, it will assume that the javadoc is new. + * Guesses if the command operates within a newly created javadoc comment or + * not. If in doubt, it will assume that the javadoc is new. */ - private static boolean isNewComment(IDocument document, int commandOffset, String partitioning) { + private static boolean isNewComment(IDocument document, int commandOffset, + String partitioning) { try { - int lineIndex= document.getLineOfOffset(commandOffset) + 1; + int lineIndex = document.getLineOfOffset(commandOffset) + 1; if (lineIndex >= document.getNumberOfLines()) return true; - IRegion line= document.getLineInformation(lineIndex); - ITypedRegion partition= TextUtilities.getPartition(document, partitioning, commandOffset, false); - int partitionEnd= partition.getOffset() + partition.getLength(); + IRegion line = document.getLineInformation(lineIndex); + ITypedRegion partition = TextUtilities.getPartition(document, + partitioning, 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 + return true; // partition goes to end of document - probably + // a new comment - String comment= document.get(partition.getOffset(), partition.getLength()); + 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 true; // enclosed another comment -> probably a new + // comment return false; @@ -267,11 +304,11 @@ public class JavaDocAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy } private boolean isSmartMode() { - IWorkbenchPage page= PHPeclipsePlugin.getActivePage(); - if (page != null) { - IEditorPart part= page.getActiveEditor(); + IWorkbenchPage page = PHPeclipsePlugin.getActivePage(); + if (page != null) { + IEditorPart part = page.getActiveEditor(); if (part instanceof ITextEditorExtension3) { - ITextEditorExtension3 extension= (ITextEditorExtension3) part; + ITextEditorExtension3 extension = (ITextEditorExtension3) part; return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT; } } @@ -281,7 +318,8 @@ public class JavaDocAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy /* * @see IAutoIndentStrategy#customizeDocumentCommand */ - public void customizeDocumentCommand(IDocument document, DocumentCommand command) { + public void customizeDocumentCommand(IDocument document, + DocumentCommand command) { if (!isSmartMode()) return; @@ -289,8 +327,9 @@ public class JavaDocAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy try { if (command.text != null && command.length == 0) { - String[] lineDelimiters= document.getLegalLineDelimiters(); - int index= TextUtilities.endsWith(lineDelimiters, command.text); + String[] lineDelimiters = document.getLegalLineDelimiters(); + int index = TextUtilities + .endsWith(lineDelimiters, command.text); if (index > -1) { // ends with line delimiter if (lineDelimiters[index].equals(command.text)) @@ -305,69 +344,79 @@ public class JavaDocAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy return; } - ITypedRegion partition= TextUtilities.getPartition(document, fPartitioning, command.offset, true); - int partitionStart= partition.getOffset(); - int partitionEnd= partition.getLength() + partitionStart; + ITypedRegion partition = TextUtilities.getPartition(document, + fPartitioning, command.offset, true); + int partitionStart = partition.getOffset(); + int partitionEnd = partition.getLength() + partitionStart; - String text= command.text; - int offset= command.offset; - int length= command.length; + String text = command.text; + int offset = command.offset; + int length = command.length; // partition change - final int PREFIX_LENGTH= "/*".length(); //$NON-NLS-1$ - final int POSTFIX_LENGTH= "*/".length(); //$NON-NLS-1$ - if ((offset < partitionStart + PREFIX_LENGTH || offset + length > partitionEnd - POSTFIX_LENGTH) || - text != null && text.length() >= 2 && ((text.indexOf("*/") != -1) || (document.getChar(offset) == '*' && text.startsWith("/")))) //$NON-NLS-1$ //$NON-NLS-2$ + final int PREFIX_LENGTH = "/*".length(); //$NON-NLS-1$ + final int POSTFIX_LENGTH = "*/".length(); //$NON-NLS-1$ + if ((offset < partitionStart + PREFIX_LENGTH || offset + length > partitionEnd + - POSTFIX_LENGTH) + || text != null + && text.length() >= 2 + && ((text.indexOf("*/") != -1) || (document.getChar(offset) == '*' && text.startsWith("/")))) //$NON-NLS-1$ //$NON-NLS-2$ return; if (command.text == null || command.text.length() == 0) jdocHandleBackspaceDelete(document, command); - else if (command.text != null && command.length == 0 && command.text.length() > 0) + else if (command.text != null && command.length == 0 + && command.text.length() > 0) jdocWrapParagraphOnInsert(document, command); } catch (BadLocationException e) { - PHPeclipsePlugin.log(e); + PHPeclipsePlugin.log(e); } } - private void flushCommand(IDocument document, DocumentCommand command) throws BadLocationException { + private void flushCommand(IDocument document, DocumentCommand command) + throws BadLocationException { if (!command.doit) return; document.replace(command.offset, command.length, command.text); - command.doit= false; + command.doit = false; if (command.text != null) command.offset += command.text.length(); - command.length= 0; - command.text= null; + command.length = 0; + command.text = null; } - protected void jdocWrapParagraphOnInsert(IDocument document, DocumentCommand command) throws BadLocationException { + protected void jdocWrapParagraphOnInsert(IDocument document, + DocumentCommand command) throws BadLocationException { -// Assert.isTrue(command.length == 0); -// Assert.isTrue(command.text != null && command.text.length() == 1); + // Assert.isTrue(command.length == 0); + // Assert.isTrue(command.text != null && command.text.length() == 1); - if (!getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_FORMAT_JAVADOCS)) + if (!getPreferenceStore().getBoolean( + PreferenceConstants.EDITOR_FORMAT_JAVADOCS)) return; - int line= document.getLineOfOffset(command.offset); - IRegion region= document.getLineInformation(line); - int lineOffset= region.getOffset(); - int lineLength= region.getLength(); + int line = document.getLineOfOffset(command.offset); + IRegion region = document.getLineInformation(line); + int lineOffset = region.getOffset(); + int lineLength = region.getLength(); - String lineContents= document.get(lineOffset, lineLength); - StringBuffer buffer= new StringBuffer(lineContents); - int start= command.offset - lineOffset; - int end= command.length + start; + String lineContents = document.get(lineOffset, lineLength); + StringBuffer buffer = new StringBuffer(lineContents); + int start = command.offset - lineOffset; + int end = command.length + start; buffer.replace(start, end, command.text); // handle whitespace - if (command.text != null && command.text.length() != 0 && command.text.trim().length() == 0) { + if (command.text != null && command.text.length() != 0 + && command.text.trim().length() == 0) { - String endOfLine= document.get(command.offset, lineOffset + lineLength - command.offset); + String endOfLine = document.get(command.offset, lineOffset + + lineLength - command.offset); // end of line if (endOfLine.length() == 0) { @@ -375,21 +424,25 @@ public class JavaDocAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy flushCommand(document, command); if (isLineTooShort(document, line)) { - int[] caretOffset= {command.offset}; - jdocWrapParagraphFromLine(document, line, caretOffset, false); - command.offset= caretOffset[0]; + int[] caretOffset = { command.offset }; + jdocWrapParagraphFromLine(document, line, caretOffset, + false); + command.offset = caretOffset[0]; return; } // move caret to next line if possible - if (line < document.getNumberOfLines() - 1 && isJavaDocLine(document, line + 1)) { - String lineDelimiter= document.getLineDelimiter(line); - String nextLinePrefix= jdocExtractLinePrefix(document, line + 1); - command.offset += lineDelimiter.length() + nextLinePrefix.length(); + if (line < document.getNumberOfLines() - 1 + && isJavaDocLine(document, line + 1)) { + String lineDelimiter = document.getLineDelimiter(line); + String nextLinePrefix = jdocExtractLinePrefix(document, + line + 1); + command.offset += lineDelimiter.length() + + nextLinePrefix.length(); } return; - // inside whitespace at end of line + // inside whitespace at end of line } else if (endOfLine.trim().length() == 0) { // simply insert space return; @@ -397,18 +450,21 @@ public class JavaDocAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy } // change in prefix region - String prefix= jdocExtractLinePrefix(document, line); - boolean wrapAlways= command.offset >= lineOffset && command.offset <= lineOffset + prefix.length(); + String prefix = jdocExtractLinePrefix(document, line); + boolean wrapAlways = command.offset >= lineOffset + && command.offset <= lineOffset + prefix.length(); // must insert the text now because it may include whitepace flushCommand(document, command); - if (wrapAlways || calculateDisplayedWidth(buffer.toString()) > getMargin() || isLineTooShort(document, line)) { - int[] caretOffset= {command.offset}; + if (wrapAlways + || calculateDisplayedWidth(buffer.toString()) > getMargin() + || isLineTooShort(document, line)) { + int[] caretOffset = { command.offset }; jdocWrapParagraphFromLine(document, line, caretOffset, wrapAlways); if (!wrapAlways) - command.offset= caretOffset[0]; + command.offset = caretOffset[0]; } } @@ -419,9 +475,10 @@ public class JavaDocAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy * @param line * @param always */ - private void jdocWrapParagraphFromLine(IDocument document, int line, int[] caretOffset, boolean always) throws BadLocationException { + private void jdocWrapParagraphFromLine(IDocument document, int line, + int[] caretOffset, boolean always) throws BadLocationException { - String indent= jdocExtractLinePrefix(document, line); + String indent = jdocExtractLinePrefix(document, line); if (!always) { if (!indent.trim().startsWith("*")) //$NON-NLS-1$ return; @@ -429,145 +486,159 @@ public class JavaDocAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy if (indent.trim().startsWith("*/")) //$NON-NLS-1$ return; - if (!isLineTooLong(document, line) && !isLineTooShort(document, line)) + if (!isLineTooLong(document, line) + && !isLineTooShort(document, line)) return; } - boolean caretRelativeToParagraphOffset= false; - int caret= caretOffset[0]; + boolean caretRelativeToParagraphOffset = false; + int caret = caretOffset[0]; - int caretLine= document.getLineOfOffset(caret); - int lineOffset= document.getLineOffset(line); - int paragraphOffset= lineOffset + indent.length(); + int caretLine = document.getLineOfOffset(caret); + int lineOffset = document.getLineOffset(line); + int paragraphOffset = lineOffset + indent.length(); if (paragraphOffset < caret) { caret -= paragraphOffset; - caretRelativeToParagraphOffset= true; + caretRelativeToParagraphOffset = true; } else { caret -= lineOffset; } - StringBuffer buffer= new StringBuffer(); - int currentLine= line; + StringBuffer buffer = new StringBuffer(); + int currentLine = line; while (line == currentLine || isJavaDocLine(document, currentLine)) { - if (buffer.length() != 0 && !Character.isWhitespace(buffer.charAt(buffer.length() - 1))) { + if (buffer.length() != 0 + && !Character.isWhitespace(buffer + .charAt(buffer.length() - 1))) { buffer.append(' '); if (currentLine <= caretLine) { - // in this case caretRelativeToParagraphOffset is always true + // in this case caretRelativeToParagraphOffset is always + // true ++caret; } } - String string= getLineContents(document, currentLine); + String string = getLineContents(document, currentLine); buffer.append(string); currentLine++; } - String paragraph= buffer.toString(); + String paragraph = buffer.toString(); if (paragraph.trim().length() == 0) return; - caretOffset[0]= caretRelativeToParagraphOffset ? caret : 0; - String delimiter= document.getLineDelimiter(0); - String wrapped= formatParagraph(paragraph, caretOffset, indent, delimiter, getMargin()); + caretOffset[0] = caretRelativeToParagraphOffset ? caret : 0; + String delimiter = document.getLineDelimiter(0); + String wrapped = formatParagraph(paragraph, caretOffset, indent, + delimiter, getMargin()); - int beginning= document.getLineOffset(line); - int end= document.getLineOffset(currentLine); + int beginning = document.getLineOffset(line); + int end = document.getLineOffset(currentLine); document.replace(beginning, end - beginning, wrapped.toString()); - caretOffset[0]= caretRelativeToParagraphOffset ? caretOffset[0] + beginning : caret + beginning; + caretOffset[0] = caretRelativeToParagraphOffset ? caretOffset[0] + + beginning : caret + beginning; } /** - * Line break iterator to handle whitespaces as first class citizens. + * Line break iterator to handle whitespaces as first class citizens. */ private static class LineBreakIterator { private final String fString; - private final BreakIterator fIterator= BreakIterator.getLineInstance(); + + private final BreakIterator fIterator = BreakIterator.getLineInstance(); private int fStart; + private int fEnd; + private int fBufferedEnd; public LineBreakIterator(String string) { - fString= string; + fString = string; fIterator.setText(string); } public int first() { - fBufferedEnd= -1; - fStart= fIterator.first(); + fBufferedEnd = -1; + fStart = fIterator.first(); return fStart; } public int next() { if (fBufferedEnd != -1) { - fStart= fEnd; - fEnd= fBufferedEnd; - fBufferedEnd= -1; + fStart = fEnd; + fEnd = fBufferedEnd; + fBufferedEnd = -1; return fEnd; } - fStart= fEnd; - fEnd= fIterator.next(); + fStart = fEnd; + fEnd = fIterator.next(); if (fEnd == BreakIterator.DONE) return fEnd; - final String string= fString.substring(fStart, fEnd); + final String string = fString.substring(fStart, fEnd); // whitespace if (string.trim().length() == 0) return fEnd; - final String word= string.trim(); + final String word = string.trim(); if (word.length() == string.length()) return fEnd; // suspected whitespace - fBufferedEnd= fEnd; + fBufferedEnd = fEnd; return fStart + word.length(); } } /** - * Formats a paragraph, using break iterator. + * Formats a paragraph, using break iterator. * - * @param offset an offset within the paragraph, which will be updated with respect to formatting. + * @param offset + * an offset within the paragraph, which will be updated with + * respect to formatting. */ - private static String formatParagraph(String paragraph, int[] offset, String prefix, String lineDelimiter, int margin) { + private static String formatParagraph(String paragraph, int[] offset, + String prefix, String lineDelimiter, int margin) { - LineBreakIterator iterator= new LineBreakIterator(paragraph); + LineBreakIterator iterator = new LineBreakIterator(paragraph); - StringBuffer paragraphBuffer= new StringBuffer(); - StringBuffer lineBuffer= new StringBuffer(); - StringBuffer whiteSpaceBuffer= new StringBuffer(); + StringBuffer paragraphBuffer = new StringBuffer(); + StringBuffer lineBuffer = new StringBuffer(); + StringBuffer whiteSpaceBuffer = new StringBuffer(); - int index= offset[0]; - int indexBuffer= -1; + int index = offset[0]; + int indexBuffer = -1; - // line delimiter could be null + // line delimiter could be null if (lineDelimiter == null) - lineDelimiter= ""; //$NON-NLS-1$ + lineDelimiter = ""; //$NON-NLS-1$ - for (int start= iterator.first(), end= iterator.next(); end != BreakIterator.DONE; start= end, end= iterator.next()) { + for (int start = iterator.first(), end = iterator.next(); end != BreakIterator.DONE; start = end, end = iterator + .next()) { - String word= paragraph.substring(start, end); + String word = paragraph.substring(start, end); // word is whitespace if (word.trim().length() == 0) { whiteSpaceBuffer.append(word); - // first word of line is always appended + // first word of line is always appended } else if (lineBuffer.length() == 0) { lineBuffer.append(prefix); lineBuffer.append(whiteSpaceBuffer.toString()); lineBuffer.append(word); } else { - String line= lineBuffer.toString() + whiteSpaceBuffer.toString() + word.toString(); + String line = lineBuffer.toString() + + whiteSpaceBuffer.toString() + word.toString(); // margin exceeded if (calculateDisplayedWidth(line) > margin) { @@ -580,16 +651,18 @@ public class JavaDocAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy // flush index buffer if (indexBuffer != -1) { - offset[0]= indexBuffer; + offset[0] = indexBuffer; // correct for caret in whitespace at the end of line - if (whiteSpaceBuffer.length() != 0 && index < start && index >= start - whiteSpaceBuffer.length()) - offset[0] -= (index - (start - whiteSpaceBuffer.length())); - indexBuffer= -1; + if (whiteSpaceBuffer.length() != 0 && index < start + && index >= start - whiteSpaceBuffer.length()) + offset[0] -= (index - (start - whiteSpaceBuffer + .length())); + indexBuffer = -1; } whiteSpaceBuffer.setLength(0); - // margin not exceeded + // margin not exceeded } else { lineBuffer.append(whiteSpaceBuffer.toString()); lineBuffer.append(word); @@ -598,7 +671,8 @@ public class JavaDocAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy } if (index >= start && index < end) { - indexBuffer= paragraphBuffer.length() + lineBuffer.length() + (index - start); + indexBuffer = paragraphBuffer.length() + lineBuffer.length() + + (index - start); if (word.trim().length() != 0) indexBuffer -= word.length(); } @@ -610,11 +684,11 @@ public class JavaDocAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy // flush index buffer if (indexBuffer != -1) - offset[0]= indexBuffer; + offset[0] = indexBuffer; // last position is not returned by break iterator else if (offset[0] == paragraph.length()) - offset[0]= paragraphBuffer.length() - lineDelimiter.length(); + offset[0] = paragraphBuffer.length() - lineDelimiter.length(); return paragraphBuffer.toString(); } @@ -624,17 +698,19 @@ public class JavaDocAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy } /** - * Returns the displayed width of a string, taking in account the displayed tab width. - * The result can be compared against the print margin. + * Returns the displayed width of a string, taking in account the displayed + * tab width. The result can be compared against the print margin. */ private static int calculateDisplayedWidth(String string) { - int tabWidth= getPreferenceStore().getInt(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH); - if (tabWidth<=0) { - tabWidth = 2; + int tabWidth = getPreferenceStore() + .getInt( + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH); + if (tabWidth <= 0) { + tabWidth = 2; } - int column= 0; - for (int i= 0; i < string.length(); i++) + int column = 0; + for (int i = 0; i < string.length(); i++) if ('\t' == string.charAt(i)) column += tabWidth - (column % tabWidth); else @@ -643,44 +719,51 @@ public class JavaDocAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy return column; } - private String jdocExtractLinePrefix(IDocument d, int line) throws BadLocationException { + private String jdocExtractLinePrefix(IDocument d, int line) + throws BadLocationException { - IRegion region= d.getLineInformation(line); - int lineOffset= region.getOffset(); - int index= findEndOfWhiteSpace(d, lineOffset, lineOffset + d.getLineLength(line)); + IRegion region = d.getLineInformation(line); + int lineOffset = region.getOffset(); + int index = findEndOfWhiteSpace(d, lineOffset, lineOffset + + d.getLineLength(line)); if (d.getChar(index) == '*') { index++; - if (index != lineOffset + region.getLength() &&d.getChar(index) == ' ') + if (index != lineOffset + region.getLength() + && d.getChar(index) == ' ') index++; } return d.get(lineOffset, index - lineOffset); } - private String getLineContents(IDocument d, int line) throws BadLocationException { + private String getLineContents(IDocument d, int line) + throws BadLocationException { int offset = d.getLineOffset(line); int length = d.getLineLength(line); - String lineDelimiter= d.getLineDelimiter(line); + String lineDelimiter = d.getLineDelimiter(line); if (lineDelimiter != null) - length= length - lineDelimiter.length(); + length = length - lineDelimiter.length(); String lineContents = d.get(offset, length); int trim = jdocExtractLinePrefix(d, line).length(); return lineContents.substring(trim); } - private static String getLine(IDocument document, int line) throws BadLocationException { - IRegion region= document.getLineInformation(line); + private static String getLine(IDocument document, int line) + throws BadLocationException { + IRegion region = document.getLineInformation(line); return document.get(region.getOffset(), region.getLength()); } /** - * Returns true if the javadoc line is too short, false otherwise. + * Returns true if the javadoc line is too short, + * false otherwise. */ - private boolean isLineTooShort(IDocument document, int line) throws BadLocationException { + private boolean isLineTooShort(IDocument document, int line) + throws BadLocationException { if (!isJavaDocLine(document, line + 1)) return false; - String nextLine= getLineContents(document, line + 1); + String nextLine = getLineContents(document, line + 1); if (nextLine.trim().length() == 0) return false; @@ -688,48 +771,53 @@ public class JavaDocAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy } /** - * Returns true if the line is too long, false otherwise. + * Returns true if the line is too long, false + * otherwise. */ - private boolean isLineTooLong(IDocument document, int line) throws BadLocationException { - String lineContents= getLine(document, line); + private boolean isLineTooLong(IDocument document, int line) + throws BadLocationException { + String lineContents = getLine(document, line); return calculateDisplayedWidth(lineContents) > getMargin(); } private static int getMargin() { - return getPreferenceStore().getInt(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN); + return getPreferenceStore() + .getInt( + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN); } - private static final String[] fgInlineTags= { - "", "", "", "", "" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + private static final String[] fgInlineTags = { + "", "", "", "", "" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ }; private boolean isInlineTag(String string) { - for (int i= 0; i < fgInlineTags.length; i++) + for (int i = 0; i < fgInlineTags.length; i++) if (string.startsWith(fgInlineTags[i])) return true; return false; } /** - * returns true if the specified line is part of a paragraph and should be merged with - * the previous line. + * returns true if the specified line is part of a paragraph and should be + * merged with the previous line. */ - private boolean isJavaDocLine(IDocument document, int line) throws BadLocationException { + private boolean isJavaDocLine(IDocument document, int line) + throws BadLocationException { if (document.getNumberOfLines() < line) return false; - int offset= document.getLineOffset(line); - int length= document.getLineLength(line); - int firstChar= findEndOfWhiteSpace(document, offset, offset + length); + int offset = document.getLineOffset(line); + int length = document.getLineLength(line); + int firstChar = findEndOfWhiteSpace(document, offset, offset + length); length -= firstChar - offset; - String lineContents= document.get(firstChar, length); + String lineContents = document.get(firstChar, length); - String prefix= lineContents.trim(); + String prefix = lineContents.trim(); if (!prefix.startsWith("*") || prefix.startsWith("*/")) //$NON-NLS-1$ //$NON-NLS-2$ return false; - lineContents= lineContents.substring(1).trim().toLowerCase(); + lineContents = lineContents.substring(1).trim().toLowerCase(); // preserve empty lines if (lineContents.length() == 0) @@ -746,89 +834,100 @@ public class JavaDocAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy return true; } - protected void jdocHandleBackspaceDelete(IDocument document, DocumentCommand c) { + protected void jdocHandleBackspaceDelete(IDocument document, + DocumentCommand c) { - if (!getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_FORMAT_JAVADOCS)) + if (!getPreferenceStore().getBoolean( + PreferenceConstants.EDITOR_FORMAT_JAVADOCS)) return; try { - String text= document.get(c.offset, c.length); - int line= document.getLineOfOffset(c.offset); - int lineOffset= document.getLineOffset(line); + String text = document.get(c.offset, c.length); + int line = document.getLineOfOffset(c.offset); + int lineOffset = document.getLineOffset(line); // erase line delimiter - String lineDelimiter= document.getLineDelimiter(line); + String lineDelimiter = document.getLineDelimiter(line); if (lineDelimiter != null && lineDelimiter.equals(text)) { - String prefix= jdocExtractLinePrefix(document, line + 1); + String prefix = jdocExtractLinePrefix(document, line + 1); // strip prefix if any if (prefix.length() > 0) { - int length= document.getLineDelimiter(line).length() + prefix.length(); + int length = document.getLineDelimiter(line).length() + + prefix.length(); document.replace(c.offset, length, null); - c.doit= false; - c.length= 0; + c.doit = false; + c.length = 0; return; } - // backspace: beginning of a javadoc line - } else if (document.getChar(c.offset - 1) == '*' && jdocExtractLinePrefix(document, line).length() - 1 >= c.offset - lineOffset) { + // backspace: beginning of a javadoc line + } else if (document.getChar(c.offset - 1) == '*' + && jdocExtractLinePrefix(document, line).length() - 1 >= c.offset + - lineOffset) { - lineDelimiter= document.getLineDelimiter(line - 1); - String prefix= jdocExtractLinePrefix(document, line); - int length= (lineDelimiter != null ? lineDelimiter.length() : 0) + prefix.length(); + lineDelimiter = document.getLineDelimiter(line - 1); + String prefix = jdocExtractLinePrefix(document, line); + int length = (lineDelimiter != null ? lineDelimiter.length() + : 0) + + prefix.length(); document.replace(c.offset - length + 1, length, null); - c.doit= false; + c.doit = false; c.offset -= length - 1; - c.length= 0; + c.length = 0; return; } else { document.replace(c.offset, c.length, null); - c.doit= false; - c.length= 0; + c.doit = false; + c.length = 0; } } catch (BadLocationException e) { - PHPeclipsePlugin.log(e); + PHPeclipsePlugin.log(e); } try { - int line= document.getLineOfOffset(c.offset); - int lineOffset= document.getLineOffset(line); - String prefix= jdocExtractLinePrefix(document, line); - boolean always= c.offset > lineOffset && c.offset <= lineOffset + prefix.length(); - int[] caretOffset= {c.offset}; - jdocWrapParagraphFromLine(document, document.getLineOfOffset(c.offset), caretOffset, always); - c.offset= caretOffset[0]; + int line = document.getLineOfOffset(c.offset); + int lineOffset = document.getLineOffset(line); + String prefix = jdocExtractLinePrefix(document, line); + boolean always = c.offset > lineOffset + && c.offset <= lineOffset + prefix.length(); + int[] caretOffset = { c.offset }; + jdocWrapParagraphFromLine(document, document + .getLineOfOffset(c.offset), caretOffset, always); + c.offset = caretOffset[0]; } catch (BadLocationException e) { - PHPeclipsePlugin.log(e); + PHPeclipsePlugin.log(e); } } /** - * Returns the compilation unit of the CompilationUnitEditor invoking the AutoIndentStrategy, - * might return null on error. + * Returns the compilation unit of the CompilationUnitEditor invoking the + * AutoIndentStrategy, might return null on error. */ private static ICompilationUnit getCompilationUnit() { - IWorkbenchWindow window= PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + IWorkbenchWindow window = PlatformUI.getWorkbench() + .getActiveWorkbenchWindow(); if (window == null) return null; - IWorkbenchPage page= window.getActivePage(); + IWorkbenchPage page = window.getActivePage(); if (page == null) return null; - IEditorPart editor= page.getActiveEditor(); + IEditorPart editor = page.getActiveEditor(); if (editor == null) return null; - IWorkingCopyManager manager= PHPeclipsePlugin.getDefault().getWorkingCopyManager(); - ICompilationUnit unit= manager.getWorkingCopy(editor.getEditorInput()); + IWorkingCopyManager manager = PHPeclipsePlugin.getDefault() + .getWorkingCopyManager(); + ICompilationUnit unit = manager.getWorkingCopy(editor.getEditorInput()); if (unit == null) return null; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/PHPDocCodeScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/PHPDocCodeScanner.java index 24aa1f8..e57a133 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/PHPDocCodeScanner.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/PHPDocCodeScanner.java @@ -34,158 +34,147 @@ import org.eclipse.jface.text.rules.WordRule; */ public final class PHPDocCodeScanner extends AbstractJavaScanner { - /** - * A key word detector. - */ - static class JavaDocKeywordDetector implements IWordDetector { - - /** - * @see IWordDetector#isWordStart - */ - public boolean isWordStart(char c) { - return (c == '@'); - } - - /** - * @see IWordDetector#isWordPart - */ - public boolean isWordPart(char c) { - return Character.isLetter(c); - } - }; - - /** - * Detector for HTML comment delimiters. - */ - static class HTMLCommentDetector implements IWordDetector { - - /** - * @see IWordDetector#isWordStart - */ - public boolean isWordStart(char c) { - return (c == '<' || c == '-'); - } - - /** - * @see IWordDetector#isWordPart - */ - 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 checkForWhitespace(ICharacterScanner scanner) { - - try { - - char c = getDocument().getChar(getTokenOffset() + 1); - if (!Character.isWhitespace(c)) - return fToken; - - } catch (BadLocationException x) { - } - - return Token.UNDEFINED; - } - - /* - * @see PatternRule#evaluate(ICharacterScanner) - */ - public IToken evaluate(ICharacterScanner scanner) { - IToken result = super.evaluate(scanner); - if (result == fToken) - return checkForWhitespace(scanner); - return result; - } - }; - - private static String[] fgKeywords = { - "@author", - "@copyright", - "@deprecated", - "@exception", - "@link", - "@package", - "@param", - "@return", - "@see", - "@serial", - "@serialData", - "@serialField", - "@since", - "@throws", - "@version" }; //$NON-NLS-12$ //$NON-NLS-11$ //$NON-NLS-10$ //$NON-NLS-7$ //$NON-NLS-9$ //$NON-NLS-8$ //$NON-NLS-6$ //$NON-NLS-5$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ - - private static String[] fgTokenProperties = { IPreferenceConstants.PHPDOC_KEYWORD, IPreferenceConstants.PHPDOC_TAG, - IPreferenceConstants.PHPDOC_LINK, IPreferenceConstants.PHPDOC_DEFAULT }; - - public PHPDocCodeScanner(IColorManager manager, IPreferenceStore store) { - super(manager, store); - initialize(); - } - - public IDocument getDocument() { - return fDocument; - } - - /* - * @see AbstractJavaScanner#getTokenProperties() - */ - protected String[] getTokenProperties() { - return fgTokenProperties; - } - - /* - * @see AbstractJavaScanner#createRules() - */ - protected List createRules() { - - List list = new ArrayList(); - - // Add rule for tags. - Token token = getToken(IPreferenceConstants.PHPDOC_TAG); - list.add(new TagRule(token)); - - // Add rule for HTML comments - WordRule wordRule = new WordRule(new HTMLCommentDetector(), token); - wordRule.addWord("", token); //$NON-NLS-1$ - list.add(wordRule); - - // Add rule for links. - token = getToken(IPreferenceConstants.PHPDOC_LINK); - list.add(new SingleLineRule("{@link", "}", token)); //$NON-NLS-2$ //$NON-NLS-1$ - - // Add generic whitespace rule. - list.add(new WhitespaceRule(new PHPWhitespaceDetector())); - - // Add word rule for keywords. - token = getToken(IPreferenceConstants.PHPDOC_DEFAULT); - wordRule = new WordRule(new JavaDocKeywordDetector(), token); - - token = getToken(IPreferenceConstants.PHPDOC_KEYWORD); - for (int i = 0; i < fgKeywords.length; i++) - wordRule.addWord(fgKeywords[i], token); - list.add(wordRule); - - setDefaultReturnToken(getToken(IPreferenceConstants.PHPDOC_DEFAULT)); - return list; - } + /** + * A key word detector. + */ + static class JavaDocKeywordDetector implements IWordDetector { + + /** + * @see IWordDetector#isWordStart + */ + public boolean isWordStart(char c) { + return (c == '@'); + } + + /** + * @see IWordDetector#isWordPart + */ + public boolean isWordPart(char c) { + return Character.isLetter(c); + } + }; + + /** + * Detector for HTML comment delimiters. + */ + static class HTMLCommentDetector implements IWordDetector { + + /** + * @see IWordDetector#isWordStart + */ + public boolean isWordStart(char c) { + return (c == '<' || c == '-'); + } + + /** + * @see IWordDetector#isWordPart + */ + 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 checkForWhitespace(ICharacterScanner scanner) { + + try { + + char c = getDocument().getChar(getTokenOffset() + 1); + if (!Character.isWhitespace(c)) + return fToken; + + } catch (BadLocationException x) { + } + + return Token.UNDEFINED; + } + + /* + * @see PatternRule#evaluate(ICharacterScanner) + */ + public IToken evaluate(ICharacterScanner scanner) { + IToken result = super.evaluate(scanner); + if (result == fToken) + return checkForWhitespace(scanner); + return result; + } + }; + + private static String[] fgKeywords = { "@author", "@copyright", + "@deprecated", "@exception", "@link", "@package", "@param", + "@return", "@see", "@serial", "@serialData", "@serialField", + "@since", "@throws", "@version" }; //$NON-NLS-12$ //$NON-NLS-11$ //$NON-NLS-10$ //$NON-NLS-7$ //$NON-NLS-9$ //$NON-NLS-8$ //$NON-NLS-6$ //$NON-NLS-5$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ + + private static String[] fgTokenProperties = { + IPreferenceConstants.PHPDOC_KEYWORD, + IPreferenceConstants.PHPDOC_TAG, IPreferenceConstants.PHPDOC_LINK, + IPreferenceConstants.PHPDOC_DEFAULT }; + + public PHPDocCodeScanner(IColorManager manager, IPreferenceStore store) { + super(manager, store); + initialize(); + } + + public IDocument getDocument() { + return fDocument; + } + + /* + * @see AbstractJavaScanner#getTokenProperties() + */ + protected String[] getTokenProperties() { + return fgTokenProperties; + } + + /* + * @see AbstractJavaScanner#createRules() + */ + protected List createRules() { + + List list = new ArrayList(); + + // Add rule for tags. + Token token = getToken(IPreferenceConstants.PHPDOC_TAG); + list.add(new TagRule(token)); + + // Add rule for HTML comments + WordRule wordRule = new WordRule(new HTMLCommentDetector(), token); + wordRule.addWord("", token); //$NON-NLS-1$ + list.add(wordRule); + + // Add rule for links. + token = getToken(IPreferenceConstants.PHPDOC_LINK); + list.add(new SingleLineRule("{@link", "}", token)); //$NON-NLS-2$ //$NON-NLS-1$ + + // Add generic whitespace rule. + list.add(new WhitespaceRule(new PHPWhitespaceDetector())); + + // Add word rule for keywords. + token = getToken(IPreferenceConstants.PHPDOC_DEFAULT); + wordRule = new WordRule(new JavaDocKeywordDetector(), token); + + token = getToken(IPreferenceConstants.PHPDOC_KEYWORD); + for (int i = 0; i < fgKeywords.length; i++) + wordRule.addWord(fgKeywords[i], token); + list.add(wordRule); + + setDefaultReturnToken(getToken(IPreferenceConstants.PHPDOC_DEFAULT)); + return list; + } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/PHPDocCompletionProcessor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/PHPDocCompletionProcessor.java index fe1f77d..098433b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/PHPDocCompletionProcessor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/PHPDocCompletionProcessor.java @@ -29,167 +29,180 @@ import org.eclipse.ui.IEditorPart; */ public class PHPDocCompletionProcessor implements IContentAssistProcessor { - private static class PHPDocCompletionProposalComparator implements Comparator { - public int compare(Object o1, Object o2) { - ICompletionProposal c1 = (ICompletionProposal) o1; - ICompletionProposal c2 = (ICompletionProposal) o2; - return c1.getDisplayString().compareTo(c2.getDisplayString()); - } - }; - - // private IEditorPart fEditor; - // private IWorkingCopyManager fManager; - private char[] fProposalAutoActivationSet; - - private PHPCompletionProposalComparator fComparator; - - private TemplateEngine fTemplateEngine; - - private boolean fRestrictToMatchingCase; - - private IEditorPart fEditor; - - protected IWorkingCopyManager fManager; - - public PHPDocCompletionProcessor(IEditorPart editor) { - fEditor = editor; - fManager = PHPeclipsePlugin.getDefault().getWorkingCopyManager(); - - // fEditor= editor; - // fManager= JavaPlugin.getDefault().getWorkingCopyManager(); - TemplateContextType contextType = PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType("phpdoc"); //$NON-NLS-1$ - if (contextType != null) - fTemplateEngine = new TemplateEngine(contextType); - fRestrictToMatchingCase = false; - - fComparator = new PHPCompletionProposalComparator(); - } - - /** - * Tells this processor to order the proposals alphabetically. - * - * @param order - * true if proposals should be ordered. - */ - public void orderProposalsAlphabetically(boolean order) { - fComparator.setOrderAlphabetically(order); - } - - /** - * Tells this processor to restrict is proposals to those starting with matching cases. - * - * @param restrict - * true if proposals should be restricted - */ - public void restrictProposalsToMatchingCases(boolean restrict) { - fRestrictToMatchingCase = restrict; - } - - /** - * @see IContentAssistProcessor#getErrorMessage() - */ - public String getErrorMessage() { - return null; - } - - /** - * @see IContentAssistProcessor#getContextInformationValidator() - */ - public IContextInformationValidator getContextInformationValidator() { - return null; - } - - /** - * @see IContentAssistProcessor#getContextInformationAutoActivationCharacters() - */ - public char[] getContextInformationAutoActivationCharacters() { - return null; - } - - /** - * @see IContentAssistProcessor#getCompletionProposalAutoActivationCharacters() - */ - public char[] getCompletionProposalAutoActivationCharacters() { - return fProposalAutoActivationSet; - } - - /** - * Sets this processor's set of characters triggering the activation of the completion proposal computation. - * - * @param activationSet - * the activation set - */ - public void setCompletionProposalAutoActivationCharacters(char[] activationSet) { - fProposalAutoActivationSet = activationSet; - } - - /** - * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int) - */ - public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) { - return null; - } - - /** - * @see IContentAssistProcessor#computeCompletionProposals(ITextViewer, int) - */ - public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) { - ICompilationUnit unit = fManager.getWorkingCopy(fEditor.getEditorInput()); - IDocument document = viewer.getDocument(); - - IPHPCompletionProposal[] results = new IPHPCompletionProposal[0]; - - // try { - // if (unit != null) { - // - // int offset= documentOffset; - // int length= 0; - // - // Point selection= viewer.getSelectedRange(); - // if (selection.y > 0) { - // offset= selection.x; - // length= selection.y; - // } - // - // JavaDocCompletionEvaluator evaluator= new JavaDocCompletionEvaluator(unit, document, offset, length); - // evaluator.restrictProposalsToMatchingCases(fRestrictToMatchingCase); - // results= evaluator.computeProposals(); - // } - // } catch (JavaModelException e) { - // JavaPlugin.log(e); - // } - - if (fTemplateEngine != null) { - // try { - fTemplateEngine.reset(); - fTemplateEngine.complete(viewer, documentOffset, unit); - // } catch (JavaModelException x) { - // } - - IPHPCompletionProposal[] templateResults = fTemplateEngine.getResults(); - if (results.length == 0) { - results = templateResults; - } else { - // concatenate arrays - IPHPCompletionProposal[] total = new IPHPCompletionProposal[results.length + templateResults.length]; - System.arraycopy(templateResults, 0, total, 0, templateResults.length); - System.arraycopy(results, 0, total, templateResults.length, results.length); - results = total; - } - } - - /* - * Order here and not in result collector to make sure that the order applies to all proposals and not just those of the - * compilation unit. - */ - return order(results); - } - - /** - * Order the given proposals. - */ - private IPHPCompletionProposal[] order(IPHPCompletionProposal[] proposals) { - Arrays.sort(proposals, fComparator); - return proposals; - } + private static class PHPDocCompletionProposalComparator implements + Comparator { + public int compare(Object o1, Object o2) { + ICompletionProposal c1 = (ICompletionProposal) o1; + ICompletionProposal c2 = (ICompletionProposal) o2; + return c1.getDisplayString().compareTo(c2.getDisplayString()); + } + }; + + // private IEditorPart fEditor; + // private IWorkingCopyManager fManager; + private char[] fProposalAutoActivationSet; + + private PHPCompletionProposalComparator fComparator; + + private TemplateEngine fTemplateEngine; + + private boolean fRestrictToMatchingCase; + + private IEditorPart fEditor; + + protected IWorkingCopyManager fManager; + + public PHPDocCompletionProcessor(IEditorPart editor) { + fEditor = editor; + fManager = PHPeclipsePlugin.getDefault().getWorkingCopyManager(); + + // fEditor= editor; + // fManager= JavaPlugin.getDefault().getWorkingCopyManager(); + TemplateContextType contextType = PHPeclipsePlugin.getDefault() + .getTemplateContextRegistry().getContextType("phpdoc"); //$NON-NLS-1$ + if (contextType != null) + fTemplateEngine = new TemplateEngine(contextType); + fRestrictToMatchingCase = false; + + fComparator = new PHPCompletionProposalComparator(); + } + + /** + * Tells this processor to order the proposals alphabetically. + * + * @param order + * true if proposals should be ordered. + */ + public void orderProposalsAlphabetically(boolean order) { + fComparator.setOrderAlphabetically(order); + } + + /** + * Tells this processor to restrict is proposals to those starting with + * matching cases. + * + * @param restrict + * true if proposals should be restricted + */ + public void restrictProposalsToMatchingCases(boolean restrict) { + fRestrictToMatchingCase = restrict; + } + + /** + * @see IContentAssistProcessor#getErrorMessage() + */ + public String getErrorMessage() { + return null; + } + + /** + * @see IContentAssistProcessor#getContextInformationValidator() + */ + public IContextInformationValidator getContextInformationValidator() { + return null; + } + + /** + * @see IContentAssistProcessor#getContextInformationAutoActivationCharacters() + */ + public char[] getContextInformationAutoActivationCharacters() { + return null; + } + + /** + * @see IContentAssistProcessor#getCompletionProposalAutoActivationCharacters() + */ + public char[] getCompletionProposalAutoActivationCharacters() { + return fProposalAutoActivationSet; + } + + /** + * Sets this processor's set of characters triggering the activation of the + * completion proposal computation. + * + * @param activationSet + * the activation set + */ + public void setCompletionProposalAutoActivationCharacters( + char[] activationSet) { + fProposalAutoActivationSet = activationSet; + } + + /** + * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int) + */ + public IContextInformation[] computeContextInformation(ITextViewer viewer, + int offset) { + return null; + } + + /** + * @see IContentAssistProcessor#computeCompletionProposals(ITextViewer, int) + */ + public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, + int documentOffset) { + ICompilationUnit unit = fManager.getWorkingCopy(fEditor + .getEditorInput()); + IDocument document = viewer.getDocument(); + + IPHPCompletionProposal[] results = new IPHPCompletionProposal[0]; + + // try { + // if (unit != null) { + // + // int offset= documentOffset; + // int length= 0; + // + // Point selection= viewer.getSelectedRange(); + // if (selection.y > 0) { + // offset= selection.x; + // length= selection.y; + // } + // + // JavaDocCompletionEvaluator evaluator= new + // JavaDocCompletionEvaluator(unit, document, offset, length); + // evaluator.restrictProposalsToMatchingCases(fRestrictToMatchingCase); + // results= evaluator.computeProposals(); + // } + // } catch (JavaModelException e) { + // JavaPlugin.log(e); + // } + + if (fTemplateEngine != null) { + // try { + fTemplateEngine.reset(); + fTemplateEngine.complete(viewer, documentOffset, unit); + // } catch (JavaModelException x) { + // } + + IPHPCompletionProposal[] templateResults = fTemplateEngine + .getResults(); + if (results.length == 0) { + results = templateResults; + } else { + // concatenate arrays + IPHPCompletionProposal[] total = new IPHPCompletionProposal[results.length + + templateResults.length]; + System.arraycopy(templateResults, 0, total, 0, + templateResults.length); + System.arraycopy(results, 0, total, templateResults.length, + results.length); + results = total; + } + } + + /* + * Order here and not in result collector to make sure that the order + * applies to all proposals and not just those of the compilation unit. + */ + return order(results); + } + + /** + * Order the given proposals. + */ + private IPHPCompletionProposal[] order(IPHPCompletionProposal[] proposals) { + Arrays.sort(proposals, fComparator); + return proposals; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/AddWordProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/AddWordProposal.java index c0140c1..b19a9eb 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/AddWordProposal.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/AddWordProposal.java @@ -43,13 +43,13 @@ public class AddWordProposal implements IPHPCompletionProposal { * Creates a new add word proposal * * @param word - * The word to add + * The word to add * @param context - * The invocation context + * The invocation context */ public AddWordProposal(final String word, final IInvocationContext context) { - fContext= context; - fWord= word; + fContext = context; + fWord = word; } /* @@ -57,8 +57,9 @@ public class AddWordProposal implements IPHPCompletionProposal { */ public final void apply(final IDocument document) { - final ISpellCheckEngine engine= SpellCheckEngine.getInstance(); - final ISpellChecker checker= engine.createSpellChecker(engine.getLocale(), PreferenceConstants.getPreferenceStore()); + final ISpellCheckEngine engine = SpellCheckEngine.getInstance(); + final ISpellChecker checker = engine.createSpellChecker(engine + .getLocale(), PreferenceConstants.getPreferenceStore()); if (checker != null) checker.addWord(fWord); @@ -68,7 +69,9 @@ public class AddWordProposal implements IPHPCompletionProposal { * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getAdditionalProposalInfo() */ public String getAdditionalProposalInfo() { - return MessageFormat.format(PHPUIMessages.getString("Spelling.add.info"), new String[] { WordCorrectionProposal.getHtmlRepresentation(fWord)}); //$NON-NLS-1$ + return MessageFormat + .format( + PHPUIMessages.getString("Spelling.add.info"), new String[] { WordCorrectionProposal.getHtmlRepresentation(fWord) }); //$NON-NLS-1$ } /* @@ -82,7 +85,8 @@ public class AddWordProposal implements IPHPCompletionProposal { * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getDisplayString() */ public String getDisplayString() { - return MessageFormat.format(PHPUIMessages.getString("Spelling.add.label"), new String[] { fWord }); //$NON-NLS-1$ + return MessageFormat.format(PHPUIMessages + .getString("Spelling.add.label"), new String[] { fWord }); //$NON-NLS-1$ } /* @@ -103,6 +107,7 @@ public class AddWordProposal implements IPHPCompletionProposal { * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getSelection(org.eclipse.jface.text.IDocument) */ public final Point getSelection(final IDocument document) { - return new Point(fContext.getSelectionOffset(), fContext.getSelectionLength()); + return new Point(fContext.getSelectionOffset(), fContext + .getSelectionLength()); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/ChangeCaseProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/ChangeCaseProposal.java index d83692d..57fde9b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/ChangeCaseProposal.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/ChangeCaseProposal.java @@ -15,7 +15,6 @@ import java.util.Locale; import net.sourceforge.phpdt.internal.ui.PHPUIMessages; import net.sourceforge.phpdt.internal.ui.text.java.IInvocationContext; - /** * Proposal to change the letter case of a word. @@ -28,18 +27,23 @@ public class ChangeCaseProposal extends WordCorrectionProposal { * Creates a new change case proposal. * * @param arguments - * The problem arguments associated with the spelling problem + * The problem arguments associated with the spelling problem * @param offset - * The offset in the document where to apply the proposal + * The offset in the document where to apply the proposal * @param length - * The lenght in the document to apply the proposal + * The lenght in the document to apply the proposal * @param context - * The invocation context for this proposal + * The invocation context for this proposal * @param locale - * The locale to use for the case change + * The locale to use for the case change */ - public ChangeCaseProposal(final String[] arguments, final int offset, final int length, final IInvocationContext context, final Locale locale) { - super(Character.isLowerCase(arguments[0].charAt(0)) ? Character.toUpperCase(arguments[0].charAt(0)) + arguments[0].substring(1) : arguments[0], arguments, offset, length, context, Integer.MAX_VALUE); + public ChangeCaseProposal(final String[] arguments, final int offset, + final int length, final IInvocationContext context, + final Locale locale) { + super(Character.isLowerCase(arguments[0].charAt(0)) ? Character + .toUpperCase(arguments[0].charAt(0)) + + arguments[0].substring(1) : arguments[0], arguments, offset, + length, context, Integer.MAX_VALUE); } /* diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/HtmlTagDictionary.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/HtmlTagDictionary.java index 2b2ba07..617f537 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/HtmlTagDictionary.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/HtmlTagDictionary.java @@ -16,13 +16,13 @@ import java.net.URL; import net.sourceforge.phpdt.internal.ui.text.phpdoc.IHtmlTagConstants; import net.sourceforge.phpdt.internal.ui.text.spelling.engine.AbstractSpellDictionary; - /** * Dictionary for html tags. * * @since 3.0 */ -public class HtmlTagDictionary extends AbstractSpellDictionary implements IHtmlTagConstants { +public class HtmlTagDictionary extends AbstractSpellDictionary implements + IHtmlTagConstants { /* * @see net.sourceforge.phpdt.internal.ui.text.spelling.engine.AbstractSpellDictionary#getName() @@ -49,10 +49,12 @@ public class HtmlTagDictionary extends AbstractSpellDictionary implements IHtmlT unload(); - for (int index= 0; index < HTML_GENERAL_TAGS.length; index++) { + for (int index = 0; index < HTML_GENERAL_TAGS.length; index++) { - hashWord(HTML_TAG_PREFIX + HTML_GENERAL_TAGS[index] + HTML_TAG_POSTFIX); - hashWord(HTML_CLOSE_PREFIX + HTML_GENERAL_TAGS[index] + HTML_TAG_POSTFIX); + hashWord(HTML_TAG_PREFIX + HTML_GENERAL_TAGS[index] + + HTML_TAG_POSTFIX); + hashWord(HTML_CLOSE_PREFIX + HTML_GENERAL_TAGS[index] + + HTML_TAG_POSTFIX); } return true; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/JavaDocTagDictionary.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/JavaDocTagDictionary.java index b2f05b7..94ed16b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/JavaDocTagDictionary.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/JavaDocTagDictionary.java @@ -16,13 +16,13 @@ import java.net.URL; import net.sourceforge.phpdt.internal.ui.text.phpdoc.IJavaDocTagConstants; import net.sourceforge.phpdt.internal.ui.text.spelling.engine.AbstractSpellDictionary; - /** * Dictionary for Javadoc tags. * * @since 3.0 */ -public class JavaDocTagDictionary extends AbstractSpellDictionary implements IJavaDocTagConstants { +public class JavaDocTagDictionary extends AbstractSpellDictionary implements + IJavaDocTagConstants { /* * @see net.sourceforge.phpdt.internal.ui.text.spelling.engine.AbstractSpellDictionary#getName() @@ -49,13 +49,13 @@ public class JavaDocTagDictionary extends AbstractSpellDictionary implements IJa unload(); - for (int index= 0; index < JAVADOC_LINK_TAGS.length; index++) + for (int index = 0; index < JAVADOC_LINK_TAGS.length; index++) hashWord(JAVADOC_LINK_TAGS[index]); - for (int index= 0; index < JAVADOC_ROOT_TAGS.length; index++) + for (int index = 0; index < JAVADOC_ROOT_TAGS.length; index++) hashWord(JAVADOC_ROOT_TAGS[index]); - for (int index= 0; index < JAVADOC_PARAM_TAGS.length; index++) + for (int index = 0; index < JAVADOC_PARAM_TAGS.length; index++) hashWord(JAVADOC_PARAM_TAGS[index]); return true; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellCheckEngine.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellCheckEngine.java index 568f1d7..2f8a304 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellCheckEngine.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellCheckEngine.java @@ -35,23 +35,22 @@ import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; - - /** * Spell check engine for Java source spell checking. * * @since 3.0 */ -public class SpellCheckEngine implements ISpellCheckEngine, IPropertyChangeListener { +public class SpellCheckEngine implements ISpellCheckEngine, + IPropertyChangeListener { /** The dictionary location */ - public static final String DICTIONARY_LOCATION= "dictionaries/"; //$NON-NLS-1$ + public static final String DICTIONARY_LOCATION = "dictionaries/"; //$NON-NLS-1$ /** The singleton spell checker instance */ - private static ISpellChecker fChecker= null; + private static ISpellChecker fChecker = null; /** The singleton engine instance */ - private static ISpellCheckEngine fEngine= null; + private static ISpellCheckEngine fEngine = null; /** * Returns the available locales for this spell check engine. @@ -60,23 +59,26 @@ public class SpellCheckEngine implements ISpellCheckEngine, IPropertyChangeListe */ public static Set getAvailableLocales() { - URL url= null; - Locale locale= null; - InputStream stream= null; + URL url = null; + Locale locale = null; + InputStream stream = null; - final Set result= new HashSet(); + final Set result = new HashSet(); try { - final URL location= getDictionaryLocation(); - final Locale[] locales= Locale.getAvailableLocales(); + final URL location = getDictionaryLocation(); + final Locale[] locales = Locale.getAvailableLocales(); - for (int index= 0; index < locales.length; index++) { + for (int index = 0; index < locales.length; index++) { - locale= locales[index]; - url= new URL(location, locale.toString().toLowerCase() + "." + PHPUIMessages.getString("Spelling.dictionary.file.extension")); //$NON-NLS-1$ //$NON-NLS-2$ + locale = locales[index]; + url = new URL( + location, + locale.toString().toLowerCase() + + "." + PHPUIMessages.getString("Spelling.dictionary.file.extension")); //$NON-NLS-1$ //$NON-NLS-2$ try { - stream= url.openStream(); + stream = url.openStream(); if (stream != null) { try { result.add(locale); @@ -109,13 +111,13 @@ public class SpellCheckEngine implements ISpellCheckEngine, IPropertyChangeListe * Returns the dictionary location. * * @throws MalformedURLException - * if the URL could not be created + * if the URL could not be created * @return The dictionary location, or null iff the location - * is not known + * is not known */ public static URL getDictionaryLocation() throws MalformedURLException { - final PHPeclipsePlugin plugin= PHPeclipsePlugin.getDefault(); + final PHPeclipsePlugin plugin = PHPeclipsePlugin.getDefault(); if (plugin != null) return plugin.getBundle().getEntry("/" + DICTIONARY_LOCATION); //$NON-NLS-1$ @@ -130,25 +132,25 @@ public class SpellCheckEngine implements ISpellCheckEngine, IPropertyChangeListe public static final synchronized ISpellCheckEngine getInstance() { if (fEngine == null) - fEngine= new SpellCheckEngine(); + fEngine = new SpellCheckEngine(); return fEngine; } /** The registered locale insenitive dictionaries */ - private final Set fGlobalDictionaries= new HashSet(); + private final Set fGlobalDictionaries = new HashSet(); /** The current locale */ - private Locale fLocale= null; + private Locale fLocale = null; /** The registered locale sensitive dictionaries */ - private final Map fLocaleDictionaries= new HashMap(); + private final Map fLocaleDictionaries = new HashMap(); /** The preference store where to listen */ - private IPreferenceStore fPreferences= null; + private IPreferenceStore fPreferences = null; /** The user dictionary */ - private ISpellDictionary fUserDictionary= null; + private ISpellDictionary fUserDictionary = null; /** * Creates a new spell check manager. @@ -161,13 +163,15 @@ public class SpellCheckEngine implements ISpellCheckEngine, IPropertyChangeListe try { - Locale locale= null; - final URL location= getDictionaryLocation(); + Locale locale = null; + final URL location = getDictionaryLocation(); - for (final Iterator iterator= getAvailableLocales().iterator(); iterator.hasNext();) { + for (final Iterator iterator = getAvailableLocales().iterator(); iterator + .hasNext();) { - locale= (Locale)iterator.next(); - fLocaleDictionaries.put(locale, new SpellReconcileDictionary(locale, location)); + locale = (Locale) iterator.next(); + fLocaleDictionaries.put(locale, new SpellReconcileDictionary( + locale, location)); } } catch (MalformedURLException exception) { @@ -178,39 +182,41 @@ public class SpellCheckEngine implements ISpellCheckEngine, IPropertyChangeListe /* * @see net.sourceforge.phpdt.ui.text.spelling.engine.ISpellCheckEngine#createSpellChecker(java.util.Locale,org.eclipse.jface.preference.IPreferenceStore) */ - public final synchronized ISpellChecker createSpellChecker(final Locale locale, final IPreferenceStore store) { + public final synchronized ISpellChecker createSpellChecker( + final Locale locale, final IPreferenceStore store) { if (fLocale != null && fLocale.equals(locale)) return fChecker; if (fChecker == null) { - fChecker= new DefaultSpellChecker(store); + fChecker = new DefaultSpellChecker(store); store.addPropertyChangeListener(this); - fPreferences= store; + fPreferences = store; - ISpellDictionary dictionary= null; - for (Iterator iterator= fGlobalDictionaries.iterator(); iterator.hasNext();) { + ISpellDictionary dictionary = null; + for (Iterator iterator = fGlobalDictionaries.iterator(); iterator + .hasNext();) { - dictionary= (ISpellDictionary)iterator.next(); + dictionary = (ISpellDictionary) iterator.next(); fChecker.addDictionary(dictionary); } } - ISpellDictionary dictionary= null; + ISpellDictionary dictionary = null; if (fLocale != null) { - dictionary= (ISpellDictionary)fLocaleDictionaries.get(fLocale); + dictionary = (ISpellDictionary) fLocaleDictionaries.get(fLocale); if (dictionary != null) { fChecker.removeDictionary(dictionary); dictionary.unload(); } } - fLocale= locale; + fLocale = locale; - dictionary= (ISpellDictionary)fLocaleDictionaries.get(locale); + dictionary = (ISpellDictionary) fLocaleDictionaries.get(locale); if (dictionary == null) { if (!getDefaultLocale().equals(locale)) { @@ -218,15 +224,20 @@ public class SpellCheckEngine implements ISpellCheckEngine, IPropertyChangeListe if (fPreferences != null) fPreferences.removePropertyChangeListener(this); - fChecker= null; - fLocale= null; + fChecker = null; + fLocale = null; } } else fChecker.addDictionary(dictionary); if (fPreferences != null) - propertyChange(new PropertyChangeEvent(this, ISpellCheckPreferenceKeys.SPELLING_USER_DICTIONARY, null, fPreferences.getString(ISpellCheckPreferenceKeys.SPELLING_USER_DICTIONARY))); + propertyChange(new PropertyChangeEvent( + this, + ISpellCheckPreferenceKeys.SPELLING_USER_DICTIONARY, + null, + fPreferences + .getString(ISpellCheckPreferenceKeys.SPELLING_USER_DICTIONARY))); return fChecker; } @@ -243,24 +254,26 @@ public class SpellCheckEngine implements ISpellCheckEngine, IPropertyChangeListe */ public final void propertyChange(final PropertyChangeEvent event) { - if (fChecker != null && event.getProperty().equals(ISpellCheckPreferenceKeys.SPELLING_USER_DICTIONARY)) { + if (fChecker != null + && event.getProperty().equals( + ISpellCheckPreferenceKeys.SPELLING_USER_DICTIONARY)) { if (fUserDictionary != null) { fChecker.removeDictionary(fUserDictionary); - fUserDictionary= null; + fUserDictionary = null; } - final String file= (String)event.getNewValue(); + final String file = (String) event.getNewValue(); if (file.length() > 0) { try { - final URL url= new URL("file", null, file); //$NON-NLS-1$ - InputStream stream= url.openStream(); + final URL url = new URL("file", null, file); //$NON-NLS-1$ + InputStream stream = url.openStream(); if (stream != null) { try { - fUserDictionary= new PersistentSpellDictionary(url); + fUserDictionary = new PersistentSpellDictionary(url); fChecker.addDictionary(fUserDictionary); } finally { stream.close(); @@ -278,7 +291,8 @@ public class SpellCheckEngine implements ISpellCheckEngine, IPropertyChangeListe /* * @see net.sourceforge.phpdt.ui.text.spelling.engine.ISpellCheckEngine#registerDictionary(net.sourceforge.phpdt.ui.text.spelling.engine.ISpellDictionary) */ - public synchronized final void registerDictionary(final ISpellDictionary dictionary) { + public synchronized final void registerDictionary( + final ISpellDictionary dictionary) { fGlobalDictionaries.add(dictionary); @@ -289,7 +303,8 @@ public class SpellCheckEngine implements ISpellCheckEngine, IPropertyChangeListe /* * @see net.sourceforge.phpdt.ui.text.spelling.engine.ISpellCheckEngine#registerDictionary(java.util.Locale,net.sourceforge.phpdt.ui.text.spelling.engine.ISpellDictionary) */ - public synchronized final void registerDictionary(final Locale locale, final ISpellDictionary dictionary) { + public synchronized final void registerDictionary(final Locale locale, + final ISpellDictionary dictionary) { fLocaleDictionaries.put(locale, dictionary); @@ -302,30 +317,33 @@ public class SpellCheckEngine implements ISpellCheckEngine, IPropertyChangeListe */ public synchronized final void unload() { - ISpellDictionary dictionary= null; - for (final Iterator iterator= fGlobalDictionaries.iterator(); iterator.hasNext();) { + ISpellDictionary dictionary = null; + for (final Iterator iterator = fGlobalDictionaries.iterator(); iterator + .hasNext();) { - dictionary= (ISpellDictionary)iterator.next(); + dictionary = (ISpellDictionary) iterator.next(); dictionary.unload(); } - for (final Iterator iterator= fLocaleDictionaries.values().iterator(); iterator.hasNext();) { + for (final Iterator iterator = fLocaleDictionaries.values().iterator(); iterator + .hasNext();) { - dictionary= (ISpellDictionary)iterator.next(); + dictionary = (ISpellDictionary) iterator.next(); dictionary.unload(); } if (fPreferences != null) fPreferences.removePropertyChangeListener(this); - fUserDictionary= null; - fChecker= null; + fUserDictionary = null; + fChecker = null; } /* * @see net.sourceforge.phpdt.ui.text.spelling.engine.ISpellCheckEngine#unregisterDictionary(net.sourceforge.phpdt.ui.text.spelling.engine.ISpellDictionary) */ - public synchronized final void unregisterDictionary(final ISpellDictionary dictionary) { + public synchronized final void unregisterDictionary( + final ISpellDictionary dictionary) { fGlobalDictionaries.remove(dictionary); fLocaleDictionaries.values().remove(dictionary); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellCheckIterator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellCheckIterator.java index f420cd7..022cabf 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellCheckIterator.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellCheckIterator.java @@ -30,7 +30,8 @@ import org.eclipse.jface.text.TextUtilities; * * @since 3.0 */ -public class SpellCheckIterator implements ISpellCheckIterator, IJavaDocTagConstants, IHtmlTagConstants { +public class SpellCheckIterator implements ISpellCheckIterator, + IJavaDocTagConstants, IHtmlTagConstants { /** The content of the region */ private final String fContent; @@ -39,10 +40,10 @@ public class SpellCheckIterator implements ISpellCheckIterator, IJavaDocTagConst private final String fDelimiter; /** The last token */ - private String fLastToken= null; + private String fLastToken = null; /** The next break */ - private int fNext= 1; + private int fNext = 1; /** The offset of the region */ private final int fOffset; @@ -51,13 +52,13 @@ public class SpellCheckIterator implements ISpellCheckIterator, IJavaDocTagConst private int fPredecessor; /** The previous break */ - private int fPrevious= 0; + private int fPrevious = 0; /** The sentence breaks */ - private final LinkedList fSentenceBreaks= new LinkedList(); + private final LinkedList fSentenceBreaks = new LinkedList(); /** Does the current word start a sentence? */ - private boolean fStartsSentence= false; + private boolean fStartsSentence = false; /** The successor break */ private int fSuccessor; @@ -69,42 +70,44 @@ public class SpellCheckIterator implements ISpellCheckIterator, IJavaDocTagConst * Creates a new spell check iterator. * * @param document - * The document containing the specified partition + * The document containing the specified partition * @param region - * The region to spell-check + * The region to spell-check * @param locale - * The locale to use for spell-checking + * The locale to use for spell-checking */ - public SpellCheckIterator(final IDocument document, final IRegion region, final Locale locale) { + public SpellCheckIterator(final IDocument document, final IRegion region, + final Locale locale) { - fOffset= region.getOffset(); - fWordIterator= BreakIterator.getWordInstance(locale); - fDelimiter= TextUtilities.getDefaultLineDelimiter(document); + fOffset = region.getOffset(); + fWordIterator = BreakIterator.getWordInstance(locale); + fDelimiter = TextUtilities.getDefaultLineDelimiter(document); String content; try { - content= document.get(region.getOffset(), region.getLength()); + content = document.get(region.getOffset(), region.getLength()); if (content.startsWith(NLSElement.TAG_PREFIX)) - content= ""; //$NON-NLS-1$ + content = ""; //$NON-NLS-1$ } catch (Exception exception) { - content= ""; //$NON-NLS-1$ + content = ""; //$NON-NLS-1$ } - fContent= content; + fContent = content; fWordIterator.setText(content); - fPredecessor= fWordIterator.first(); - fSuccessor= fWordIterator.next(); + fPredecessor = fWordIterator.first(); + fSuccessor = fWordIterator.next(); - final BreakIterator iterator= BreakIterator.getSentenceInstance(locale); + final BreakIterator iterator = BreakIterator + .getSentenceInstance(locale); iterator.setText(content); - int offset= iterator.current(); + int offset = iterator.current(); while (offset != BreakIterator.DONE) { fSentenceBreaks.add(new Integer(offset)); - offset= iterator.next(); + offset = iterator.next(); } } @@ -133,22 +136,22 @@ public class SpellCheckIterator implements ISpellCheckIterator, IJavaDocTagConst * Does the specified token consist of at least one letter and digits only? * * @param begin - * The begin index + * The begin index * @param end - * The end index - * @return true iff the token consists of digits and at - * least one letter only, false otherwise + * The end index + * @return true iff the token consists of digits and at least + * one letter only, false otherwise */ protected final boolean isAlphaNumeric(final int begin, final int end) { - char character= 0; + char character = 0; - boolean letter= false; - for (int index= begin; index < end; index++) { + boolean letter = false; + for (int index = begin; index < end; index++) { - character= fContent.charAt(index); + character = fContent.charAt(index); if (Character.isLetter(character)) - letter= true; + letter = true; if (!Character.isLetterOrDigit(character)) return false; @@ -160,15 +163,15 @@ public class SpellCheckIterator implements ISpellCheckIterator, IJavaDocTagConst * Was the last token a Javadoc tag tag? * * @param tags - * The javadoc tags to check - * @return true iff the last token was a Javadoc tag, false - * otherwise + * The javadoc tags to check + * @return true iff the last token was a Javadoc tag, + * false otherwise */ protected final boolean isJavadocToken(final String[] tags) { if (fLastToken != null) { - for (int index= 0; index < tags.length; index++) { + for (int index = 0; index < tags.length; index++) { if (fLastToken.equals(tags[index])) return true; @@ -182,14 +185,16 @@ public class SpellCheckIterator implements ISpellCheckIterator, IJavaDocTagConst * characters? * * @param begin - * The begin index + * The begin index * @return true iff the token is a single letter token, - * false otherwise + * false otherwise */ protected final boolean isSingleLetter(final int begin) { if (begin > 0 && begin < fContent.length() - 1) - return Character.isWhitespace(fContent.charAt(begin - 1)) && Character.isLetter(fContent.charAt(begin)) && Character.isWhitespace(fContent.charAt(begin + 1)); + return Character.isWhitespace(fContent.charAt(begin - 1)) + && Character.isLetter(fContent.charAt(begin)) + && Character.isWhitespace(fContent.charAt(begin + 1)); return false; } @@ -198,15 +203,16 @@ public class SpellCheckIterator implements ISpellCheckIterator, IJavaDocTagConst * Does the specified token look like an URL? * * @param begin - * The begin index - * @return true iff this token look like an URL, false - * otherwise + * The begin index + * @return true iff this token look like an URL, + * false otherwise */ protected final boolean isUrlToken(final int begin) { - for (int index= 0; index < DefaultSpellChecker.URL_PREFIXES.length; index++) { + for (int index = 0; index < DefaultSpellChecker.URL_PREFIXES.length; index++) { - if (fContent.startsWith(DefaultSpellChecker.URL_PREFIXES[index], begin)) + if (fContent.startsWith(DefaultSpellChecker.URL_PREFIXES[index], + begin)) return true; } return false; @@ -216,15 +222,15 @@ public class SpellCheckIterator implements ISpellCheckIterator, IJavaDocTagConst * Does the specified token consist of whitespace only? * * @param begin - * The begin index + * The begin index * @param end - * The end index + * The end index * @return true iff the token consists of whitespace only, - * false otherwise + * false otherwise */ protected final boolean isWhitespace(final int begin, final int end) { - for (int index= begin; index < end; index++) { + for (int index = begin; index < end; index++) { if (!Character.isWhitespace(fContent.charAt(index))) return false; @@ -237,11 +243,11 @@ public class SpellCheckIterator implements ISpellCheckIterator, IJavaDocTagConst */ public final Object next() { - String token= nextToken(); + String token = nextToken(); while (token == null && fSuccessor != BreakIterator.DONE) - token= nextToken(); + token = nextToken(); - fLastToken= token; + fLastToken = token; return token; } @@ -251,10 +257,10 @@ public class SpellCheckIterator implements ISpellCheckIterator, IJavaDocTagConst */ protected final void nextBreak() { - fNext= fSuccessor; - fPredecessor= fSuccessor; + fNext = fSuccessor; + fPredecessor = fSuccessor; - fSuccessor= fWordIterator.next(); + fSuccessor = fWordIterator.next(); } /** @@ -270,57 +276,63 @@ public class SpellCheckIterator implements ISpellCheckIterator, IJavaDocTagConst * Determines the next token to be spell-checked. * * @return The next token to be spell-checked, or null iff - * the next token is not a candidate for spell-checking. + * the next token is not a candidate for spell-checking. */ protected String nextToken() { - String token= null; + String token = null; - fPrevious= fPredecessor; - fStartsSentence= false; + fPrevious = fPredecessor; + fStartsSentence = false; nextBreak(); - boolean update= false; + boolean update = false; if (fNext - fPrevious > 0) { - if (fSuccessor != BreakIterator.DONE && fContent.charAt(fPrevious) == JAVADOC_TAG_PREFIX) { + if (fSuccessor != BreakIterator.DONE + && fContent.charAt(fPrevious) == JAVADOC_TAG_PREFIX) { nextBreak(); if (Character.isLetter(fContent.charAt(fPrevious + 1))) { - update= true; - token= fContent.substring(fPrevious, fNext); + update = true; + token = fContent.substring(fPrevious, fNext); } else - fPredecessor= fNext; + fPredecessor = fNext; - } else if (fSuccessor != BreakIterator.DONE && fContent.charAt(fPrevious) == HTML_TAG_PREFIX && (Character.isLetter(fContent.charAt(fNext)) || fContent.charAt(fNext) == '/')) { + } else if (fSuccessor != BreakIterator.DONE + && fContent.charAt(fPrevious) == HTML_TAG_PREFIX + && (Character.isLetter(fContent.charAt(fNext)) || fContent + .charAt(fNext) == '/')) { if (fContent.startsWith(HTML_CLOSE_PREFIX, fPrevious)) nextBreak(); nextBreak(); - if (fSuccessor != BreakIterator.DONE && fContent.charAt(fNext) == HTML_TAG_POSTFIX) { + if (fSuccessor != BreakIterator.DONE + && fContent.charAt(fNext) == HTML_TAG_POSTFIX) { nextBreak(); if (fSuccessor != BreakIterator.DONE) { - update= true; - token= fContent.substring(fPrevious, fNext); + update = true; + token = fContent.substring(fPrevious, fNext); } } - } else if (!isWhitespace(fPrevious, fNext) && isAlphaNumeric(fPrevious, fNext)) { + } else if (!isWhitespace(fPrevious, fNext) + && isAlphaNumeric(fPrevious, fNext)) { if (isUrlToken(fPrevious)) skipTokens(fPrevious, ' '); else if (isJavadocToken(JAVADOC_PARAM_TAGS)) - fLastToken= null; + fLastToken = null; else if (isJavadocToken(JAVADOC_REFERENCE_TAGS)) { - fLastToken= null; + fLastToken = null; skipTokens(fPrevious, fDelimiter.charAt(0)); } else if (fNext - fPrevious > 1 || isSingleLetter(fPrevious)) - token= fContent.substring(fPrevious, fNext); + token = fContent.substring(fPrevious, fNext); - update= true; + update = true; } } @@ -328,10 +340,11 @@ public class SpellCheckIterator implements ISpellCheckIterator, IJavaDocTagConst if (fPrevious >= nextSentence()) { - while (fSentenceBreaks.size() > 0 && fPrevious >= nextSentence()) + while (fSentenceBreaks.size() > 0 + && fPrevious >= nextSentence()) fSentenceBreaks.removeFirst(); - fStartsSentence= (fLastToken == null) || (token != null); + fStartsSentence = (fLastToken == null) || (token != null); } } return token; @@ -348,25 +361,25 @@ public class SpellCheckIterator implements ISpellCheckIterator, IJavaDocTagConst * Skip the tokens until the stop character is reached. * * @param begin - * The begin index + * The begin index * @param stop - * The stop character + * The stop character */ protected final void skipTokens(final int begin, final char stop) { - int end= begin; + int end = begin; while (end < fContent.length() && fContent.charAt(end) != stop) end++; if (end < fContent.length()) { - fNext= end; - fPredecessor= fNext; + fNext = end; + fPredecessor = fNext; - fSuccessor= fWordIterator.following(fNext); + fSuccessor = fWordIterator.following(fNext); } else - fSuccessor= BreakIterator.DONE; + fSuccessor = BreakIterator.DONE; } /* diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellReconcileDictionary.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellReconcileDictionary.java index d9edc82..4e3530c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellReconcileDictionary.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellReconcileDictionary.java @@ -18,21 +18,21 @@ import net.sourceforge.phpdt.internal.ui.text.phpdoc.IHtmlTagConstants; import net.sourceforge.phpdt.internal.ui.text.phpdoc.IJavaDocTagConstants; import net.sourceforge.phpdt.internal.ui.text.spelling.engine.LocaleSensitiveSpellDictionary; - /** * Dictionary used by the spell reconciling strategy. * * @since 3.0 */ -public class SpellReconcileDictionary extends LocaleSensitiveSpellDictionary implements IJavaDocTagConstants, IHtmlTagConstants { +public class SpellReconcileDictionary extends LocaleSensitiveSpellDictionary + implements IJavaDocTagConstants, IHtmlTagConstants { /** * Creates a new locale sensitive spell dictionary. * * @param locale - * The locale for this dictionary + * The locale for this dictionary * @param location - * The location of the locale sensitive dictionaries + * The location of the locale sensitive dictionaries */ public SpellReconcileDictionary(final Locale locale, final URL location) { super(locale, location); @@ -43,7 +43,7 @@ public class SpellReconcileDictionary extends LocaleSensitiveSpellDictionary imp */ public boolean isCorrect(final String word) { - final char character= word.charAt(0); + final char character = word.charAt(0); if (character != JAVADOC_TAG_PREFIX && character != HTML_TAG_PREFIX) return super.isCorrect(word); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellReconcileStrategy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellReconcileStrategy.java index ef18470..9074743 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellReconcileStrategy.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellReconcileStrategy.java @@ -42,7 +42,8 @@ import org.eclipse.ui.texteditor.ITextEditor; * * @since 3.0 */ -public class SpellReconcileStrategy implements IReconcilingStrategy, IReconcilingStrategyExtension, ISpellEventListener { +public class SpellReconcileStrategy implements IReconcilingStrategy, + IReconcilingStrategyExtension, ISpellEventListener { /** * Spelling problem to be accepted by problem requestors. @@ -50,22 +51,22 @@ public class SpellReconcileStrategy implements IReconcilingStrategy, IReconcilin public class SpellProblem implements IProblem { /** The id of the problem */ - public static final int Spelling= 0x80000000; + public static final int Spelling = 0x80000000; /** The end offset of the problem */ - private int fEnd= 0; + private int fEnd = 0; /** The line number of the problem */ - private int fLine= 1; + private int fLine = 1; /** Was the word found in the dictionary? */ private boolean fMatch; /** Does the word start a new sentence? */ - private boolean fSentence= false; + private boolean fSentence = false; /** The start offset of the problem */ - private int fStart= 0; + private int fStart = 0; /** The word which caused the problem */ private final String fWord; @@ -74,10 +75,10 @@ public class SpellReconcileStrategy implements IReconcilingStrategy, IReconcilin * Creates a new spelling problem * * @param word - * The word which caused the problem + * The word which caused the problem */ protected SpellProblem(final String word) { - fWord= word; + fWord = word; } /* @@ -85,20 +86,29 @@ public class SpellReconcileStrategy implements IReconcilingStrategy, IReconcilin */ public String[] getArguments() { - String prefix= ""; //$NON-NLS-1$ - String postfix= ""; //$NON-NLS-1$ + String prefix = ""; //$NON-NLS-1$ + String postfix = ""; //$NON-NLS-1$ try { - final IRegion line= fDocument.getLineInformationOfOffset(fStart); + final IRegion line = fDocument + .getLineInformationOfOffset(fStart); - prefix= fDocument.get(line.getOffset(), fStart - line.getOffset()); - postfix= fDocument.get(fEnd + 1, line.getOffset() + line.getLength() - fEnd); + prefix = fDocument.get(line.getOffset(), fStart + - line.getOffset()); + postfix = fDocument.get(fEnd + 1, line.getOffset() + + line.getLength() - fEnd); } catch (BadLocationException exception) { // Do nothing } - return new String[] { fWord, prefix, postfix, fSentence ? Boolean.toString(true) : Boolean.toString(false), fMatch ? Boolean.toString(true) : Boolean.toString(false)}; + return new String[] { + fWord, + prefix, + postfix, + fSentence ? Boolean.toString(true) : Boolean + .toString(false), + fMatch ? Boolean.toString(true) : Boolean.toString(false) }; } /* @@ -114,9 +124,13 @@ public class SpellReconcileStrategy implements IReconcilingStrategy, IReconcilin public String getMessage() { if (fSentence && fMatch) - return MessageFormat.format(PHPUIMessages.getString("Spelling.error.case.label"), new String[] { fWord }); //$NON-NLS-1$ + return MessageFormat + .format( + PHPUIMessages + .getString("Spelling.error.case.label"), new String[] { fWord }); //$NON-NLS-1$ - return MessageFormat.format(PHPUIMessages.getString("Spelling.error.label"), new String[] { fWord }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + return MessageFormat.format(PHPUIMessages + .getString("Spelling.error.label"), new String[] { fWord }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } /* @@ -150,8 +164,8 @@ public class SpellReconcileStrategy implements IReconcilingStrategy, IReconcilin /** * Was the problem word found in the dictionary? * - * @return true iff the word was found, false - * otherwise + * @return true iff the word was found, + * false otherwise */ public final boolean isDictionaryMatch() { return fMatch; @@ -167,8 +181,8 @@ public class SpellReconcileStrategy implements IReconcilingStrategy, IReconcilin /** * Does the problem word start a new sentence? * - * @return true iff it starts a new sentence, false - * otherwise + * @return true iff it starts a new sentence, + * false otherwise */ public final boolean isSentenceStart() { return fSentence; @@ -185,54 +199,54 @@ public class SpellReconcileStrategy implements IReconcilingStrategy, IReconcilin * Sets whether the problem word was found in the dictionary. * * @param match - * true iff the word was found, false - * otherwise + * true iff the word was found, + * false otherwise */ public final void setDictionaryMatch(final boolean match) { - fMatch= match; + fMatch = match; } /** * Sets whether the problem word starts a new sentence. * * @param sentence - * true iff the word starts a new sentence, - * false otherwise. + * true iff the word starts a new sentence, + * false otherwise. */ public final void setSentenceStart(final boolean sentence) { - fSentence= sentence; + fSentence = sentence; } /* * @see net.sourceforge.phpdt.core.compiler.IProblem#setSourceEnd(int) */ public final void setSourceEnd(final int end) { - fEnd= end; + fEnd = end; } /* * @see net.sourceforge.phpdt.core.compiler.IProblem#setSourceLineNumber(int) */ public final void setSourceLineNumber(final int line) { - fLine= line; + fLine = line; } /* * @see net.sourceforge.phpdt.core.compiler.IProblem#setSourceStart(int) */ public final void setSourceStart(final int start) { - fStart= start; + fStart = start; } } - /** The document to operate on */ - private IDocument fDocument= null; + /** The document to operate on */ + private IDocument fDocument = null; /** The text editor to operate on */ private final ITextEditor fEditor; /** The current locale */ - private Locale fLocale= SpellCheckEngine.getDefaultLocale(); + private Locale fLocale = SpellCheckEngine.getDefaultLocale(); /** The partitioning of the document */ private final String fPartitioning; @@ -247,18 +261,19 @@ public class SpellReconcileStrategy implements IReconcilingStrategy, IReconcilin * Creates a new comment reconcile strategy. * * @param editor - * The text editor to operate on + * The text editor to operate on * @param partitioning - * The partitioning of the document + * The partitioning of the document * @param store - * The preference store to get the preferences from + * The preference store to get the preferences from */ - public SpellReconcileStrategy(final ITextEditor editor, final String partitioning, final IPreferenceStore store) { - fEditor= editor; - fPartitioning= partitioning; - fPreferences= store; + public SpellReconcileStrategy(final ITextEditor editor, + final String partitioning, final IPreferenceStore store) { + fEditor = editor; + fPartitioning = partitioning; + fPreferences = store; - updateProblemRequestor(); + updateProblemRequestor(); } /** @@ -268,7 +283,8 @@ public class SpellReconcileStrategy implements IReconcilingStrategy, IReconcilin */ public Locale getLocale() { - final String locale= fPreferences.getString(ISpellCheckPreferenceKeys.SPELLING_LOCALE); + final String locale = fPreferences + .getString(ISpellCheckPreferenceKeys.SPELLING_LOCALE); if (locale.equals(fLocale.toString())) return fLocale; @@ -282,22 +298,23 @@ public class SpellReconcileStrategy implements IReconcilingStrategy, IReconcilin * @see net.sourceforge.phpdt.internal.ui.text.spelling.engine.ISpellEventListener#handle(net.sourceforge.phpdt.internal.ui.text.spelling.engine.ISpellEvent) */ public void handle(final ISpellEvent event) { - + if (fRequestor != null) { - - final SpellProblem problem= new SpellProblem(event.getWord()); - + + final SpellProblem problem = new SpellProblem(event.getWord()); + problem.setSourceStart(event.getBegin()); problem.setSourceEnd(event.getEnd()); problem.setSentenceStart(event.isStart()); problem.setDictionaryMatch(event.isMatch()); - + try { - problem.setSourceLineNumber(fDocument.getLineOfOffset(event.getBegin()) + 1); + problem.setSourceLineNumber(fDocument.getLineOfOffset(event + .getBegin()) + 1); } catch (BadLocationException x) { // Do nothing } - + fRequestor.acceptProblem(problem); } } @@ -320,30 +337,40 @@ public class SpellReconcileStrategy implements IReconcilingStrategy, IReconcilin */ public void reconcile(final IRegion region) { - if (fPreferences.getBoolean(ISpellCheckPreferenceKeys.SPELLING_CHECK_SPELLING) && fRequestor != null) { + if (fPreferences + .getBoolean(ISpellCheckPreferenceKeys.SPELLING_CHECK_SPELLING) + && fRequestor != null) { try { fRequestor.beginReporting(); - ITypedRegion partition= null; - final ITypedRegion[] partitions= TextUtilities.computePartitioning(fDocument, fPartitioning, 0, fDocument.getLength(), false); + ITypedRegion partition = null; + final ITypedRegion[] partitions = TextUtilities + .computePartitioning(fDocument, fPartitioning, 0, + fDocument.getLength(), false); - final Locale locale= getLocale(); - final ISpellCheckEngine engine= SpellCheckEngine.getInstance(); + final Locale locale = getLocale(); + final ISpellCheckEngine engine = SpellCheckEngine.getInstance(); - final ISpellChecker checker= engine.createSpellChecker(locale, fPreferences); + final ISpellChecker checker = engine.createSpellChecker(locale, + fPreferences); if (checker != null) { try { checker.addListener(this); - - for (int index= 0; index < partitions.length; index++) { - partition= partitions[index]; - if (!partition.getType().equals(IDocument.DEFAULT_CONTENT_TYPE) && - !partition.getType().equals(PHPDocumentPartitioner.PHP_SCRIPT_CODE)) - checker.execute(new SpellCheckIterator(fDocument, partition, locale)); + + for (int index = 0; index < partitions.length; index++) { + partition = partitions[index]; + if (!partition.getType().equals( + IDocument.DEFAULT_CONTENT_TYPE) + && !partition + .getType() + .equals( + PHPDocumentPartitioner.PHP_SCRIPT_CODE)) + checker.execute(new SpellCheckIterator( + fDocument, partition, locale)); } - + } finally { checker.removeListener(this); } @@ -360,8 +387,8 @@ public class SpellReconcileStrategy implements IReconcilingStrategy, IReconcilin * @see org.eclipse.jface.text.reconciler.IReconcilingStrategy#setDocument(org.eclipse.jface.text.IDocument) */ public final void setDocument(final IDocument document) { - fDocument= document; - + fDocument = document; + updateProblemRequestor(); } @@ -378,7 +405,9 @@ public class SpellReconcileStrategy implements IReconcilingStrategy, IReconcilin * @since 3.0 */ private void updateProblemRequestor() { - final IAnnotationModel model= fEditor.getDocumentProvider().getAnnotationModel(fEditor.getEditorInput()); - fRequestor= (model instanceof IProblemRequestor) ? (IProblemRequestor) model : null; + final IAnnotationModel model = fEditor.getDocumentProvider() + .getAnnotationModel(fEditor.getEditorInput()); + fRequestor = (model instanceof IProblemRequestor) ? (IProblemRequestor) model + : null; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/TaskTagDictionary.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/TaskTagDictionary.java index ea03a5d..867690b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/TaskTagDictionary.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/TaskTagDictionary.java @@ -26,7 +26,8 @@ import org.eclipse.core.runtime.Preferences.PropertyChangeEvent; * * @since 3.0 */ -public class TaskTagDictionary extends AbstractSpellDictionary implements IPropertyChangeListener { +public class TaskTagDictionary extends AbstractSpellDictionary implements + IPropertyChangeListener { /* * @see net.sourceforge.phpdt.internal.ui.text.spelling.engine.AbstractSpellDictionary#getName() @@ -40,7 +41,7 @@ public class TaskTagDictionary extends AbstractSpellDictionary implements IPrope */ protected boolean load(final URL url) { - final Plugin plugin= JavaCore.getPlugin(); + final Plugin plugin = JavaCore.getPlugin(); if (plugin != null) { plugin.getPluginPreferences().addPropertyChangeListener(this); @@ -63,7 +64,7 @@ public class TaskTagDictionary extends AbstractSpellDictionary implements IPrope */ public void unload() { - final Plugin plugin= JavaCore.getPlugin(); + final Plugin plugin = JavaCore.getPlugin(); if (plugin != null) plugin.getPluginPreferences().removePropertyChangeListener(this); @@ -75,12 +76,12 @@ public class TaskTagDictionary extends AbstractSpellDictionary implements IPrope */ protected boolean updateTaskTags() { - final String tags= JavaCore.getOption(JavaCore.COMPILER_TASK_TAGS); + final String tags = JavaCore.getOption(JavaCore.COMPILER_TASK_TAGS); if (tags != null) { unload(); - final StringTokenizer tokenizer= new StringTokenizer(tags, ","); //$NON-NLS-1$ + final StringTokenizer tokenizer = new StringTokenizer(tags, ","); //$NON-NLS-1$ while (tokenizer.hasMoreTokens()) hashWord(tokenizer.nextToken()); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/WordCorrectionProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/WordCorrectionProposal.java index 64ac2fe..60aaeb0 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/WordCorrectionProposal.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/WordCorrectionProposal.java @@ -30,27 +30,29 @@ import org.eclipse.swt.graphics.Point; * * @since 3.0 */ -public class WordCorrectionProposal implements IPHPCompletionProposal, IHtmlTagConstants { +public class WordCorrectionProposal implements IPHPCompletionProposal, + IHtmlTagConstants { /** * Returns the html representation of the specified string. * * @param string - * The string to return the html representation for + * The string to return the html representation for * @return The html representation for the string */ public static String getHtmlRepresentation(final String string) { - final int length= string.length(); - final StringBuffer buffer= new StringBuffer(string); + final int length = string.length(); + final StringBuffer buffer = new StringBuffer(string); - for (int offset= length - 1; offset >= 0; offset--) { + for (int offset = length - 1; offset >= 0; offset--) { - for (int index= 0; index < HTML_ENTITY_CHARACTERS.length; index++) { + for (int index = 0; index < HTML_ENTITY_CHARACTERS.length; index++) { if (string.charAt(offset) == HTML_ENTITY_CHARACTERS[index]) { - buffer.replace(offset, offset + 1, String.valueOf(HTML_ENTITY_CODES[index])); + buffer.replace(offset, offset + 1, String + .valueOf(HTML_ENTITY_CODES[index])); break; } } @@ -80,28 +82,32 @@ public class WordCorrectionProposal implements IPHPCompletionProposal, IHtmlTagC * Creates a new word correction proposal. * * @param word - * The corrected word + * The corrected word * @param arguments - * The problem arguments associated with the spelling problem + * The problem arguments associated with the spelling problem * @param offset - * The offset in the document where to apply the proposal + * The offset in the document where to apply the proposal * @param length - * The lenght in the document to apply the proposal + * The lenght in the document to apply the proposal * @param context - * The invocation context for this proposal + * The invocation context for this proposal * @param relevance - * The relevance of this proposal + * The relevance of this proposal */ - public WordCorrectionProposal(final String word, final String[] arguments, final int offset, final int length, final IInvocationContext context, final int relevance) { + public WordCorrectionProposal(final String word, final String[] arguments, + final int offset, final int length, + final IInvocationContext context, final int relevance) { - fWord= Character.isUpperCase(arguments[0].charAt(0)) ? Character.toUpperCase(word.charAt(0)) + word.substring(1) : word; + fWord = Character.isUpperCase(arguments[0].charAt(0)) ? Character + .toUpperCase(word.charAt(0)) + + word.substring(1) : word; - fOffset= offset; - fLength= length; - fContext= context; - fRelevance= relevance; + fOffset = offset; + fLength = length; + fContext = context; + fRelevance = relevance; - final StringBuffer buffer= new StringBuffer(80); + final StringBuffer buffer = new StringBuffer(80); buffer.append("...
                                                      "); //$NON-NLS-1$ buffer.append(getHtmlRepresentation(arguments[1])); @@ -111,7 +117,7 @@ public class WordCorrectionProposal implements IPHPCompletionProposal, IHtmlTagC buffer.append(getHtmlRepresentation(arguments[2])); buffer.append("
                                                      ..."); //$NON-NLS-1$ - fLine= buffer.toString(); + fLine = buffer.toString(); } /* @@ -143,7 +149,8 @@ public class WordCorrectionProposal implements IPHPCompletionProposal, IHtmlTagC * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getDisplayString() */ public String getDisplayString() { - return MessageFormat.format(PHPUIMessages.getString("Spelling.correct.label"), new String[] { fWord }); //$NON-NLS-1$ + return MessageFormat.format(PHPUIMessages + .getString("Spelling.correct.label"), new String[] { fWord }); //$NON-NLS-1$ } /* @@ -165,10 +172,10 @@ public class WordCorrectionProposal implements IPHPCompletionProposal, IHtmlTagC */ public final Point getSelection(final IDocument document) { - int offset= fContext.getSelectionOffset(); - int length= fContext.getSelectionLength(); + int offset = fContext.getSelectionOffset(); + int length = fContext.getSelectionLength(); - final int delta= fWord.length() - fLength; + final int delta = fWord.length() - fLength; if (offset <= fOffset && offset + length >= fOffset) length += delta; else if (offset > fOffset && offset + length > fOffset + fLength) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/WordIgnoreProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/WordIgnoreProposal.java index d2e076b..47add64 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/WordIgnoreProposal.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/WordIgnoreProposal.java @@ -43,13 +43,14 @@ public class WordIgnoreProposal implements IPHPCompletionProposal { * Creates a new spell ignore proposal. * * @param word - * The word to ignore + * The word to ignore * @param context - * The invocation context + * The invocation context */ - public WordIgnoreProposal(final String word, final IInvocationContext context) { - fWord= word; - fContext= context; + public WordIgnoreProposal(final String word, + final IInvocationContext context) { + fWord = word; + fContext = context; } /* @@ -57,8 +58,9 @@ public class WordIgnoreProposal implements IPHPCompletionProposal { */ public final void apply(final IDocument document) { - final ISpellCheckEngine engine= SpellCheckEngine.getInstance(); - final ISpellChecker checker= engine.createSpellChecker(engine.getLocale(), PreferenceConstants.getPreferenceStore()); + final ISpellCheckEngine engine = SpellCheckEngine.getInstance(); + final ISpellChecker checker = engine.createSpellChecker(engine + .getLocale(), PreferenceConstants.getPreferenceStore()); if (checker != null) checker.ignoreWord(fWord); @@ -68,7 +70,9 @@ public class WordIgnoreProposal implements IPHPCompletionProposal { * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getAdditionalProposalInfo() */ public String getAdditionalProposalInfo() { - return MessageFormat.format(PHPUIMessages.getString("Spelling.ignore.info"), new String[] { WordCorrectionProposal.getHtmlRepresentation(fWord)}); //$NON-NLS-1$ + return MessageFormat + .format( + PHPUIMessages.getString("Spelling.ignore.info"), new String[] { WordCorrectionProposal.getHtmlRepresentation(fWord) }); //$NON-NLS-1$ } /* @@ -82,7 +86,8 @@ public class WordIgnoreProposal implements IPHPCompletionProposal { * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getDisplayString() */ public String getDisplayString() { - return MessageFormat.format(PHPUIMessages.getString("Spelling.ignore.label"), new String[] { fWord }); //$NON-NLS-1$ + return MessageFormat.format(PHPUIMessages + .getString("Spelling.ignore.label"), new String[] { fWord }); //$NON-NLS-1$ } /* @@ -91,6 +96,7 @@ public class WordIgnoreProposal implements IPHPCompletionProposal { public Image getImage() { return PHPUiImages.get(PHPUiImages.IMG_OBJS_NLS_NEVER_TRANSLATE); } + /* * @see net.sourceforge.phpdt.ui.text.java.IJavaCompletionProposal#getRelevance() */ @@ -102,6 +108,7 @@ public class WordIgnoreProposal implements IPHPCompletionProposal { * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getSelection(org.eclipse.jface.text.IDocument) */ public final Point getSelection(final IDocument document) { - return new Point(fContext.getSelectionOffset(), fContext.getSelectionLength()); + return new Point(fContext.getSelectionOffset(), fContext + .getSelectionLength()); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/AbstractSpellDictionary.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/AbstractSpellDictionary.java index e268c0b..8e0bab5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/AbstractSpellDictionary.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/AbstractSpellDictionary.java @@ -32,41 +32,41 @@ import java.util.Set; public abstract class AbstractSpellDictionary implements ISpellDictionary { /** The bucket capacity */ - protected static final int BUCKET_CAPACITY= 4; + protected static final int BUCKET_CAPACITY = 4; /** The word buffer capacity */ - protected static final int BUFFER_CAPACITY= 32; + protected static final int BUFFER_CAPACITY = 32; /** The distance threshold */ - protected static final int DISTANCE_THRESHOLD= 160; + protected static final int DISTANCE_THRESHOLD = 160; /** The hash capacity */ - protected static final int HASH_CAPACITY= 22 * 1024; + protected static final int HASH_CAPACITY = 22 * 1024; /** The phonetic distance algorithm */ - private IPhoneticDistanceAlgorithm fDistanceAlgorithm= new DefaultPhoneticDistanceAlgorithm(); + private IPhoneticDistanceAlgorithm fDistanceAlgorithm = new DefaultPhoneticDistanceAlgorithm(); /** The mapping from phonetic hashes to word lists */ - private final Map fHashBuckets= new HashMap(HASH_CAPACITY); + private final Map fHashBuckets = new HashMap(HASH_CAPACITY); /** The phonetic hash provider */ - private IPhoneticHashProvider fHashProvider= new DefaultPhoneticHashProvider(); + private IPhoneticHashProvider fHashProvider = new DefaultPhoneticHashProvider(); /** Is the dictionary already loaded? */ - private boolean fLoaded= false; + private boolean fLoaded = false; /** * Returns all candidates with the same phonetic hash. * * @param hash - * The hash to retrieve the candidates of + * The hash to retrieve the candidates of * @return Array of candidates for the phonetic hash */ protected final ArrayList getCandidates(final String hash) { - ArrayList list= (ArrayList)fHashBuckets.get(hash); + ArrayList list = (ArrayList) fHashBuckets.get(hash); if (list == null) - list= new ArrayList(0); + list = new ArrayList(0); return list; } @@ -76,34 +76,35 @@ public abstract class AbstractSpellDictionary implements ISpellDictionary { * distance to the specified word. * * @param word - * The word to find the nearest matches for + * The word to find the nearest matches for * @param sentence - * true iff the proposals start a new sentence, - * false otherwise + * true iff the proposals start a new sentence, + * false otherwise * @param hashs - * Array of close hashes to find the matches + * Array of close hashes to find the matches * @return Set of ranked words with bounded distance to the specified word */ - protected final HashSet getCandidates(final String word, final boolean sentence, final ArrayList hashs) { + protected final HashSet getCandidates(final String word, + final boolean sentence, final ArrayList hashs) { - int distance= 0; - String hash= null; + int distance = 0; + String hash = null; - String candidate= null; - List candidates= null; + String candidate = null; + List candidates = null; - final StringBuffer buffer= new StringBuffer(BUFFER_CAPACITY); - final HashSet result= new HashSet(BUCKET_CAPACITY * hashs.size()); + final StringBuffer buffer = new StringBuffer(BUFFER_CAPACITY); + final HashSet result = new HashSet(BUCKET_CAPACITY * hashs.size()); - for (int index= 0; index < hashs.size(); index++) { + for (int index = 0; index < hashs.size(); index++) { - hash= (String)hashs.get(index); - candidates= getCandidates(hash); + hash = (String) hashs.get(index); + candidates = getCandidates(hash); - for (int offset= 0; offset < candidates.size(); offset++) { + for (int offset = 0; offset < candidates.size(); offset++) { - candidate= (String)candidates.get(offset); - distance= fDistanceAlgorithm.getDistance(word, candidate); + candidate = (String) candidates.get(offset); + distance = fDistanceAlgorithm.getDistance(word, candidate); if (distance < DISTANCE_THRESHOLD) { @@ -111,9 +112,11 @@ public abstract class AbstractSpellDictionary implements ISpellDictionary { buffer.append(candidate); if (sentence) - buffer.setCharAt(0, Character.toUpperCase(buffer.charAt(0))); + buffer.setCharAt(0, Character.toUpperCase(buffer + .charAt(0))); - result.add(new RankedWordProposal(buffer.toString(), -distance)); + result.add(new RankedWordProposal(buffer.toString(), + -distance)); } } } @@ -125,29 +128,30 @@ public abstract class AbstractSpellDictionary implements ISpellDictionary { * possible distance to the specified word. * * @param word - * The word to find the nearest matches for + * The word to find the nearest matches for * @param sentence - * true iff the proposals start a new sentence, - * false otherwise + * true iff the proposals start a new sentence, + * false otherwise * @param result - * Set of ranked words with smallest possible distance to the - * specified word + * Set of ranked words with smallest possible distance to the + * specified word */ - protected final void getCandidates(final String word, final boolean sentence, final HashSet result) { + protected final void getCandidates(final String word, + final boolean sentence, final HashSet result) { - int distance= 0; - int minimum= Integer.MAX_VALUE; + int distance = 0; + int minimum = Integer.MAX_VALUE; - String candidate= null; - StringBuffer buffer= new StringBuffer(BUFFER_CAPACITY); + String candidate = null; + StringBuffer buffer = new StringBuffer(BUFFER_CAPACITY); - final ArrayList candidates= getCandidates(fHashProvider.getHash(word)); - final ArrayList matches= new ArrayList(candidates.size()); + final ArrayList candidates = getCandidates(fHashProvider.getHash(word)); + final ArrayList matches = new ArrayList(candidates.size()); - for (int index= 0; index < candidates.size(); index++) { + for (int index = 0; index < candidates.size(); index++) { - candidate= (String)candidates.get(index); - distance= fDistanceAlgorithm.getDistance(word, candidate); + candidate = (String) candidates.get(index); + distance = fDistanceAlgorithm.getDistance(word, candidate); if (distance <= minimum) { @@ -155,18 +159,22 @@ public abstract class AbstractSpellDictionary implements ISpellDictionary { buffer.append(candidate); if (sentence) - buffer.setCharAt(0, Character.toUpperCase(buffer.charAt(0))); - - matches.add(new RankedWordProposal(buffer.toString(), -distance)); - minimum= distance; + buffer + .setCharAt(0, Character.toUpperCase(buffer + .charAt(0))); + + matches + .add(new RankedWordProposal(buffer.toString(), + -distance)); + minimum = distance; } } - RankedWordProposal match= null; + RankedWordProposal match = null; - for (int index= 0; index < matches.size(); index++) { + for (int index = 0; index < matches.size(); index++) { - match= (RankedWordProposal)matches.get(index); + match = (RankedWordProposal) matches.get(index); if (match.getRank() == minimum) result.add(match); } @@ -204,75 +212,76 @@ public abstract class AbstractSpellDictionary implements ISpellDictionary { // Do nothing } - final String hash= fHashProvider.getHash(word); - final char[] mutators= fHashProvider.getMutators(); + final String hash = fHashProvider.getHash(word); + final char[] mutators = fHashProvider.getMutators(); - final ArrayList neighborhood= new ArrayList((word.length() + 1) * (mutators.length + 2)); + final ArrayList neighborhood = new ArrayList((word.length() + 1) + * (mutators.length + 2)); neighborhood.add(hash); - final HashSet candidates= getCandidates(word, sentence, neighborhood); + final HashSet candidates = getCandidates(word, sentence, neighborhood); neighborhood.clear(); - char previous= 0; - char next= 0; + char previous = 0; + char next = 0; - char[] characters= word.toCharArray(); - for (int index= 0; index < word.length() - 1; index++) { + char[] characters = word.toCharArray(); + for (int index = 0; index < word.length() - 1; index++) { - next= characters[index]; - previous= characters[index + 1]; + next = characters[index]; + previous = characters[index + 1]; - characters[index]= previous; - characters[index + 1]= next; + characters[index] = previous; + characters[index + 1] = next; neighborhood.add(fHashProvider.getHash(new String(characters))); - characters[index]= next; - characters[index + 1]= previous; + characters[index] = next; + characters[index + 1] = previous; } - final String sentinel= word + " "; //$NON-NLS-1$ + final String sentinel = word + " "; //$NON-NLS-1$ - characters= sentinel.toCharArray(); - int offset= characters.length - 1; + characters = sentinel.toCharArray(); + int offset = characters.length - 1; while (true) { - for (int index= 0; index < mutators.length; index++) { + for (int index = 0; index < mutators.length; index++) { - characters[offset]= mutators[index]; + characters[offset] = mutators[index]; neighborhood.add(fHashProvider.getHash(new String(characters))); } if (offset == 0) break; - characters[offset]= characters[offset - 1]; + characters[offset] = characters[offset - 1]; --offset; } - char mutated= 0; - characters= word.toCharArray(); + char mutated = 0; + characters = word.toCharArray(); - for (int index= 0; index < word.length(); index++) { + for (int index = 0; index < word.length(); index++) { - mutated= characters[index]; - for (int mutator= 0; mutator < mutators.length; mutator++) { + mutated = characters[index]; + for (int mutator = 0; mutator < mutators.length; mutator++) { - characters[index]= mutators[mutator]; + characters[index] = mutators[mutator]; neighborhood.add(fHashProvider.getHash(new String(characters))); } - characters[index]= mutated; + characters[index] = mutated; } - characters= word.toCharArray(); - final char[] deleted= new char[characters.length - 1]; + characters = word.toCharArray(); + final char[] deleted = new char[characters.length - 1]; - for (int index= 0; index < deleted.length; index++) - deleted[index]= characters[index]; + for (int index = 0; index < deleted.length; index++) + deleted[index] = characters[index]; - next= characters[characters.length - 1]; - offset= deleted.length; + next = characters[characters.length - 1]; + offset = deleted.length; while (true) { @@ -280,15 +289,15 @@ public abstract class AbstractSpellDictionary implements ISpellDictionary { if (offset == 0) break; - previous= next; - next= deleted[offset - 1]; + previous = next; + next = deleted[offset - 1]; - deleted[offset - 1]= previous; + deleted[offset - 1] = previous; --offset; } neighborhood.remove(hash); - final HashSet matches= getCandidates(word, sentence, neighborhood); + final HashSet matches = getCandidates(word, sentence, neighborhood); if (matches.size() == 0 && candidates.size() == 0) getCandidates(word, sentence, candidates); @@ -302,7 +311,7 @@ public abstract class AbstractSpellDictionary implements ISpellDictionary { * Returns the URL of the dictionary word list. * * @throws MalformedURLException - * if the URL could not be retrieved + * if the URL could not be retrieved * @return The URL of the dictionary word list */ protected abstract URL getURL() throws MalformedURLException; @@ -311,16 +320,16 @@ public abstract class AbstractSpellDictionary implements ISpellDictionary { * Hashes the word into the dictionary. * * @param word - * The word to hash in the dictionary + * The word to hash in the dictionary */ protected final void hashWord(final String word) { - final String hash= fHashProvider.getHash(word); - ArrayList bucket= (ArrayList)fHashBuckets.get(hash); + final String hash = fHashProvider.getHash(word); + ArrayList bucket = (ArrayList) fHashBuckets.get(hash); if (bucket == null) { - bucket= new ArrayList(BUCKET_CAPACITY); + bucket = new ArrayList(BUCKET_CAPACITY); fHashBuckets.put(hash, bucket); } @@ -341,9 +350,10 @@ public abstract class AbstractSpellDictionary implements ISpellDictionary { // Do nothing } - final ArrayList candidates= getCandidates(fHashProvider.getHash(word)); + final ArrayList candidates = getCandidates(fHashProvider.getHash(word)); - if (candidates.contains(word) || candidates.contains(word.toLowerCase())) + if (candidates.contains(word) + || candidates.contains(word.toLowerCase())) return true; return false; @@ -360,9 +370,9 @@ public abstract class AbstractSpellDictionary implements ISpellDictionary { * Loads a dictionary word list from disk. * * @param url - * The URL of the word list to load - * @return true iff the word list could be loaded, false - * otherwise + * The URL of the word list to load + * @return true iff the word list could be loaded, + * false otherwise */ protected synchronized boolean load(final URL url) { @@ -370,16 +380,17 @@ public abstract class AbstractSpellDictionary implements ISpellDictionary { try { - final InputStream stream= url.openStream(); + final InputStream stream = url.openStream(); if (stream != null) { - String word= null; + String word = null; - final BufferedReader reader= new BufferedReader(new InputStreamReader(stream)); - while ((word= reader.readLine()) != null) + final BufferedReader reader = new BufferedReader( + new InputStreamReader(stream)); + while ((word = reader.readLine()) != null) hashWord(word); - return fLoaded= true; + return fLoaded = true; } } catch (IOException exception) { // Do nothing @@ -392,20 +403,21 @@ public abstract class AbstractSpellDictionary implements ISpellDictionary { * Sets the phonetic distance algorithm to use. * * @param algorithm - * The phonetic distance algorithm + * The phonetic distance algorithm */ - protected final void setDistanceAlgorithm(final IPhoneticDistanceAlgorithm algorithm) { - fDistanceAlgorithm= algorithm; + protected final void setDistanceAlgorithm( + final IPhoneticDistanceAlgorithm algorithm) { + fDistanceAlgorithm = algorithm; } /** * Sets the phonetic hash provider to use. * * @param provider - * The phonetic hash provider + * The phonetic hash provider */ protected final void setHashProvider(final IPhoneticHashProvider provider) { - fHashProvider= provider; + fHashProvider = provider; } /* @@ -413,17 +425,17 @@ public abstract class AbstractSpellDictionary implements ISpellDictionary { */ public synchronized void unload() { - fLoaded= false; + fLoaded = false; fHashBuckets.clear(); } - + /* * @see net.sourceforge.phpdt.ui.text.spelling.engine.ISpellDictionary#acceptsWords() */ public boolean acceptsWords() { return false; } - + /* * @see net.sourceforge.phpdt.internal.ui.text.spelling.engine.ISpellDictionary#addWord(java.lang.String) */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/DefaultPhoneticDistanceAlgorithm.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/DefaultPhoneticDistanceAlgorithm.java index 2d758bb..cb95f37 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/DefaultPhoneticDistanceAlgorithm.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/DefaultPhoneticDistanceAlgorithm.java @@ -19,83 +19,86 @@ package net.sourceforge.phpdt.internal.ui.text.spelling.engine; * * @since 3.0 */ -public final class DefaultPhoneticDistanceAlgorithm implements IPhoneticDistanceAlgorithm { +public final class DefaultPhoneticDistanceAlgorithm implements + IPhoneticDistanceAlgorithm { /** The change case cost */ - public static final int COST_CASE= 10; + public static final int COST_CASE = 10; /** The insert character cost */ - public static final int COST_INSERT= 95; + public static final int COST_INSERT = 95; /** The remove character cost */ - public static final int COST_REMOVE= 95; + public static final int COST_REMOVE = 95; /** The substitute characters cost */ - public static final int COST_SUBSTITUTE= 100; + public static final int COST_SUBSTITUTE = 100; /** The swap characters cost */ - public static final int COST_SWAP= 90; + 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 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 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; + 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; + 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 swap = Integer.MAX_VALUE; + int change = Integer.MAX_VALUE; int minimum, diagonal, insert, remove; - for (int row= 1; row < rows; row++) { + for (int row = 1; row < rows; row++) { - source= first[row]; - for (int column= 1; column < columns; column++) { + source = first[row]; + for (int column = 1; column < columns; column++) { - target= second[column]; - diagonal= metric[row - 1][column - 1]; + target = second[column]; + diagonal = metric[row - 1][column - 1]; if (source == target) { - metric[row][column]= diagonal; + metric[row][column] = diagonal; continue; } - change= Integer.MAX_VALUE; - if (Character.toLowerCase(source) == Character.toLowerCase(target)) - change= COST_CASE + diagonal; + 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]; + 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; + minimum = COST_SUBSTITUTE + diagonal; if (swap < minimum) - minimum= swap; + minimum = swap; - remove= metric[row][column - 1]; + remove = metric[row][column - 1]; if (COST_REMOVE + remove < minimum) - minimum= COST_REMOVE + remove; + minimum = COST_REMOVE + remove; - insert= metric[row - 1][column]; + insert = metric[row - 1][column]; if (COST_INSERT + insert < minimum) - minimum= COST_INSERT + insert; + minimum = COST_INSERT + insert; if (change < minimum) - minimum= change; + minimum = change; - metric[row][column]= minimum; + metric[row][column] = minimum; } } return metric[rows - 1][columns - 1]; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/DefaultPhoneticHashProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/DefaultPhoneticHashProvider.java index 73b4ad1..2229bcf 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/DefaultPhoneticHashProvider.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/DefaultPhoneticHashProvider.java @@ -14,138 +14,240 @@ package net.sourceforge.phpdt.internal.ui.text.spelling.engine; /** * Default phonetic hash provider for english languages. *

                                                      - * This algorithm uses an adapted version double metaphone algorithm by - * Lawrence Philips. + * This algorithm uses an adapted version double metaphone algorithm by Lawrence + * Philips. *

                                                      * * @since 3.0 */ 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$ + 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' }; + 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' }; + 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 + * Array of candidates to check * @param token - * The token to check for occurrences of the candidates + * The token to check for occurrences of the candidates * @param offset - * The offset where to begin checking in the string + * The offset where to begin checking in the string * @param length - * The length of the range in the string to check + * The length of the range in the string to check * @return true iff the string contains one of the - * candidates, false otherwise. + * candidates, false otherwise. */ - protected static final boolean hasOneOf(final String[] candidates, final char[] token, final int offset, final int length) { + 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++) { + final String checkable = new String(token, offset, length); + for (int index = 0; index < candidates.length; index++) { if (candidates[index].equals(checkable)) return true; @@ -158,15 +260,16 @@ public final class DefaultPhoneticHashProvider implements IPhoneticHashProvider * list. * * @param candidates - * Array of candidates to check + * Array of candidates to check * @param token - * The token to check for occurrences of the candidates + * The token to check for occurrences of the candidates * @return true iff the string contains one of the - * candidates, false otherwise. + * candidates, false otherwise. */ - protected static final boolean hasOneOf(final String[] candidates, final String token) { + protected static final boolean hasOneOf(final String[] candidates, + final String token) { - for (int index= 0; index < candidates.length; index++) { + for (int index = 0; index < candidates.length; index++) { if (token.indexOf(candidates[index]) >= 0) return true; @@ -179,20 +282,21 @@ public final class DefaultPhoneticHashProvider implements IPhoneticHashProvider * offset. * * @param token - * The token to check for a vowel + * The token to check for a vowel * @param offset - * The offset where to begin checking in the token + * The offset where to begin checking in the token * @param length - * The length of the range in the token to check - * @return true iff the token contains a vowel, false - * otherwise. + * The length of the range in the token to check + * @return true iff the token contains a vowel, + * false otherwise. */ - protected static final boolean hasVowel(final char[] token, final int offset, final int length) { + 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++) { + final char character = token[offset]; + for (int index = 0; index < VOWEL_CHARACTERS.length; index++) { if (VOWEL_CHARACTERS[index] == character) return true; @@ -206,13 +310,13 @@ public final class DefaultPhoneticHashProvider implements IPhoneticHashProvider */ public final String getHash(final String word) { - final String input= word.toUpperCase() + " "; //$NON-NLS-1$ - final char[] hashable= input.toCharArray(); + 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); + final boolean has95 = hasOneOf(meta95, input); + final StringBuffer buffer = new StringBuffer(hashable.length); - int offset= 0; + int offset = 0; if (hasOneOf(meta26, hashable, 0, 2)) offset += 1; @@ -224,451 +328,516 @@ public final class DefaultPhoneticHashProvider implements IPhoneticHashProvider 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'); + 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; - case 'B' : - buffer.append('P'); - if (hashable[offset + 1] == 'B') - offset += 2; - else - offset += 1; + } + 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; - 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)) { + } + if (hasOneOf(meta05, hashable, offset, 2)) { + if ((offset > 0) && hasOneOf(meta06, hashable, offset, 4)) { 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)) { + 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(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$ + 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'); - offset += 3; - break; } else { - buffer.append('K'); - offset += 2; - break; + buffer.append('X'); } } - if (hasOneOf(meta24, hashable, offset, 2)) { - buffer.append('K'); - offset += 2; + 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 if (hasOneOf(meta25, hashable, offset, 2)) { - buffer.append('S'); + } else { + buffer.append('K'); offset += 2; break; } + } + if (hasOneOf(meta24, hashable, offset, 2)) { 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; + offset += 2; break; - case '\u00C7' : + } else if (hasOneOf(meta25, hashable, offset, 2)) { buffer.append('S'); - offset += 1; + offset += 2; 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; + } + 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; - } - if (hasOneOf(meta38, hashable, offset + 1, 2) && !has95) { - buffer.append("KL"); //$NON-NLS-1$ + } else { + buffer.append("TK"); //$NON-NLS-1$ offset += 2; break; } - if ((offset == 0) && ((hashable[offset + 1] == 'Y') || hasOneOf(meta39, hashable, offset + 1, 2))) { + } + 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 ((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'); + 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; - } - 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 { + if ((offset > 2) && (hashable[offset - 1] == 'U') + && hasOneOf(meta36, hashable, offset - 3, 1)) { + buffer.append('F'); } else { - buffer.append('J'); + if ((offset > 0) && (hashable[offset - 1] != 'I')) + buffer.append('K'); } offset += 2; break; } - if (hashable[offset + 1] == 'G') - offset += 2; - else - offset += 1; + } + 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; - case 'H' : - if (((offset == 0) || hasVowel(hashable, offset - 1, hashable.length)) && hasVowel(hashable, offset + 1, hashable.length)) { - buffer.append('H'); - offset += 2; + } + 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 { - offset += 1; + buffer.append('J'); } + offset += 2; 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 (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'); } - if ((offset == 0) && !hasOneOf(meta53, hashable, offset, 4)) { + 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 (hasVowel(hashable, offset - 1, hashable.length) && !has95 && ((hashable[offset + 1] == 'A') || hashable[offset + 1] == 'O')) { + if (offset == (hashable.length - 1)) { buffer.append('J'); } else { - if (offset == (hashable.length - 1)) { + if (!hasOneOf(meta54, hashable, offset + 1, 1) + && !hasOneOf(meta55, hashable, offset - 1, + 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')) + } + 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; - else - offset += 1; - buffer.append('M'); + 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; - case 'N' : - if (hashable[offset + 1] == 'N') - offset += 2; - else - offset += 1; - buffer.append('N'); + } + 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; - case '\u00D1' : + } + if ((offset == 0) && hasOneOf(meta66, hashable, offset, 5)) { + buffer.append('X'); 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; + } + if (hasOneOf(meta67, hashable, offset, 2)) { + if (hasOneOf(meta68, hashable, offset + 1, 4)) + buffer.append('S'); else - offset += 1; - buffer.append('P'); + buffer.append('X'); + offset += 2; break; - case 'Q' : - if (hashable[offset + 1] == 'Q') - offset += 2; - else - offset += 1; - buffer.append('K'); + } + if (hasOneOf(meta69, hashable, offset, 3) + || hasOneOf(meta70, hashable, offset, 4)) { + buffer.append('S'); + offset += 3; 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') + } + 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; - 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; + } + 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('X'); - offset += 3; - break; + buffer.append("SK"); //$NON-NLS-1$ } - if (hasOneOf(meta77, hashable, offset + 2, 1)) { - buffer.append('S'); + offset += 3; + break; + } else { + buffer.append('X'); offset += 3; break; } - buffer.append("SK"); //$NON-NLS-1$ - offset += 3; - break; - } - if (!((offset == (hashable.length - 1)) && hasOneOf(meta78, hashable, offset - 2, 2))) + if (hasOneOf(meta77, hashable, offset + 2, 1)) { 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'); + buffer.append("SK"); //$NON-NLS-1$ + offset += 3; 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; - } + } + 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; - 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; + } + if (hasOneOf(meta81, hashable, offset, 3)) { + buffer.append('X'); + offset += 3; break; - case 'Z' : - if (hashable[offset + 1] == 'H') { - buffer.append('J'); - offset += 2; - 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('S'); + buffer.append('0'); } - if (hashable[offset + 1] == 'Z') - offset += 2; - else - offset += 1; + 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; - default : + } + 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(); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/DefaultSpellChecker.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/DefaultSpellChecker.java index 3453691..2b4da35 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/DefaultSpellChecker.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/DefaultSpellChecker.java @@ -26,19 +26,20 @@ import org.eclipse.jface.preference.IPreferenceStore; 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$ + 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 true iff this word contains digits, false> - * otherwise + * The word to check + * @return true iff this word contains digits, + * false> otherwise */ protected static boolean isDigits(final String word) { - for (int index= 0; index < word.length(); index++) { + for (int index = 0; index < word.length(); index++) { if (Character.isDigit(word.charAt(index))) return true; @@ -50,30 +51,31 @@ public class DefaultSpellChecker implements ISpellChecker { * Does this word contain mixed-case letters? * * @param word - * The word to check + * The word to check * @param sentence - * true iff the specified word starts a new - * sentence, false otherwise - * @return true iff the contains mixed-case letters, false - * otherwise + * true iff the specified word starts a new + * sentence, false otherwise + * @return true iff the contains mixed-case letters, + * false otherwise */ - protected static boolean isMixedCase(final String word, final boolean sentence) { + protected static boolean isMixedCase(final String word, + final boolean sentence) { - final int length= word.length(); - boolean upper= Character.isUpperCase(word.charAt(0)); + final int length = word.length(); + boolean upper = Character.isUpperCase(word.charAt(0)); if (sentence && upper && (length > 1)) - upper= Character.isUpperCase(word.charAt(1)); + upper = Character.isUpperCase(word.charAt(1)); if (upper) { - for (int index= length - 1; index > 0; index--) { + 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--) { + for (int index = length - 1; index > 0; index--) { if (Character.isUpperCase(word.charAt(index))) return true; } @@ -85,13 +87,13 @@ public class DefaultSpellChecker implements ISpellChecker { * Does this word contain upper-case letters only? * * @param word - * The word to check + * The word to check * @return true iff this word only contains upper-case - * letters, false otherwise + * letters, false otherwise */ protected static boolean isUpperCase(final String word) { - for (int index= word.length() - 1; index >= 0; index--) { + for (int index = word.length() - 1; index >= 0; index--) { if (Character.isLowerCase(word.charAt(index))) return false; @@ -103,13 +105,13 @@ public class DefaultSpellChecker implements ISpellChecker { * Does this word look like an URL? * * @param word - * The word to check - * @return true iff this word looks like an URL, false - * otherwise + * The word to check + * @return true iff this word looks like an URL, + * false otherwise */ protected static boolean isUrl(final String word) { - for (int index= 0; index < URL_PREFIXES.length; index++) { + for (int index = 0; index < URL_PREFIXES.length; index++) { if (word.startsWith(URL_PREFIXES[index])) return true; @@ -121,18 +123,19 @@ public class DefaultSpellChecker implements ISpellChecker { * The dictionaries to use for spell-checking. Synchronized to avoid * concurrent modifications. */ - private final Set fDictionaries= Collections.synchronizedSet(new HashSet()); + 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()); + 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()); + private final Set fListeners = Collections.synchronizedSet(new HashSet()); /** * The preference store. Assumes the IPreferenceStore @@ -144,10 +147,10 @@ public class DefaultSpellChecker implements ISpellChecker { * Creates a new default spell-checker. * * @param store - * The preference store for this spell-checker + * The preference store for this spell-checker */ public DefaultSpellChecker(final IPreferenceStore store) { - fPreferences= store; + fPreferences = store; } /* @@ -165,23 +168,23 @@ public class DefaultSpellChecker implements ISpellChecker { // synchronizing is necessary as this is a write access fListeners.add(listener); } - + /* * @see net.sourceforge.phpdt.ui.text.spelling.engine.ISpellChecker#acceptsWords() */ public boolean acceptsWords() { - // synchronizing might not be needed here since acceptWords is + // synchronizing might not be needed here since acceptWords is // a read-only access and only called in the same thread as // the modifing methods add/checkWord (?) Set copy; synchronized (fDictionaries) { - copy= new HashSet(fDictionaries); + copy = new HashSet(fDictionaries); } - - ISpellDictionary dictionary= null; - for (final Iterator iterator= copy.iterator(); iterator.hasNext();) { - dictionary= (ISpellDictionary)iterator.next(); + ISpellDictionary dictionary = null; + for (final Iterator iterator = copy.iterator(); iterator.hasNext();) { + + dictionary = (ISpellDictionary) iterator.next(); if (dictionary.acceptsWords()) return true; } @@ -195,16 +198,16 @@ public class DefaultSpellChecker implements ISpellChecker { // synchronizing is necessary as this is a write access Set copy; synchronized (fDictionaries) { - copy= new HashSet(fDictionaries); + copy = new HashSet(fDictionaries); } - final String addable= word.toLowerCase(); + final String addable = word.toLowerCase(); fIgnored.add(addable); - ISpellDictionary dictionary= null; - for (final Iterator iterator= copy.iterator(); iterator.hasNext();) { + ISpellDictionary dictionary = null; + for (final Iterator iterator = copy.iterator(); iterator.hasNext();) { - dictionary= (ISpellDictionary)iterator.next(); + dictionary = (ISpellDictionary) iterator.next(); dictionary.addWord(addable); } } @@ -222,38 +225,51 @@ public class DefaultSpellChecker implements ISpellChecker { */ public void execute(final ISpellCheckIterator iterator) { - final boolean ignoreDigits= fPreferences.getBoolean(ISpellCheckPreferenceKeys.SPELLING_IGNORE_DIGITS); - final boolean ignoreMixed= fPreferences.getBoolean(ISpellCheckPreferenceKeys.SPELLING_IGNORE_MIXED); - final boolean ignoreSentence= fPreferences.getBoolean(ISpellCheckPreferenceKeys.SPELLING_IGNORE_SENTENCE); - final boolean ignoreUpper= fPreferences.getBoolean(ISpellCheckPreferenceKeys.SPELLING_IGNORE_UPPER); - final boolean ignoreURLS= fPreferences.getBoolean(ISpellCheckPreferenceKeys.SPELLING_IGNORE_URLS); + final boolean ignoreDigits = fPreferences + .getBoolean(ISpellCheckPreferenceKeys.SPELLING_IGNORE_DIGITS); + final boolean ignoreMixed = fPreferences + .getBoolean(ISpellCheckPreferenceKeys.SPELLING_IGNORE_MIXED); + final boolean ignoreSentence = fPreferences + .getBoolean(ISpellCheckPreferenceKeys.SPELLING_IGNORE_SENTENCE); + final boolean ignoreUpper = fPreferences + .getBoolean(ISpellCheckPreferenceKeys.SPELLING_IGNORE_UPPER); + final boolean ignoreURLS = fPreferences + .getBoolean(ISpellCheckPreferenceKeys.SPELLING_IGNORE_URLS); - String word= null; - boolean starts= false; + String word = null; + boolean starts = false; while (iterator.hasNext()) { - word= (String)iterator.next(); + word = (String) iterator.next(); if (word != null) { - // synchronizing is necessary as this is called inside the reconciler + // synchronizing is necessary as this is called inside the + // reconciler if (!fIgnored.contains(word)) { - starts= iterator.startsSentence(); + 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)); + + 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)); + if (!ignoreSentence && starts + && Character.isLowerCase(word.charAt(0))) + fireEvent(new SpellEvent(this, word, iterator + .getBegin(), iterator.getEnd(), true, true)); } } } @@ -264,16 +280,16 @@ public class DefaultSpellChecker implements ISpellChecker { * Fires the specified event. * * @param event - * Event to fire + * 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); + copy = new HashSet(fListeners); } - for (final Iterator iterator= copy.iterator(); iterator.hasNext();) { - ((ISpellEventListener)iterator.next()).handle(event); + for (final Iterator iterator = copy.iterator(); iterator.hasNext();) { + ((ISpellEventListener) iterator.next()).handle(event); } } @@ -281,21 +297,21 @@ public class DefaultSpellChecker implements ISpellChecker { * @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 + + // 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); + copy = new HashSet(fDictionaries); } - ISpellDictionary dictionary= null; - final HashSet proposals= new HashSet(); + ISpellDictionary dictionary = null; + final HashSet proposals = new HashSet(); - for (final Iterator iterator= copy.iterator(); iterator.hasNext();) { + for (final Iterator iterator = copy.iterator(); iterator.hasNext();) { - dictionary= (ISpellDictionary)iterator.next(); + dictionary = (ISpellDictionary) iterator.next(); proposals.addAll(dictionary.getProposals(word, sentence)); } return proposals; @@ -316,16 +332,16 @@ public class DefaultSpellChecker implements ISpellChecker { // synchronizing is necessary as this is called from execute Set copy; synchronized (fDictionaries) { - copy= new HashSet(fDictionaries); + copy = new HashSet(fDictionaries); } if (fIgnored.contains(word.toLowerCase())) return true; - ISpellDictionary dictionary= null; - for (final Iterator iterator= copy.iterator(); iterator.hasNext();) { + ISpellDictionary dictionary = null; + for (final Iterator iterator = copy.iterator(); iterator.hasNext();) { - dictionary= (ISpellDictionary)iterator.next(); + dictionary = (ISpellDictionary) iterator.next(); if (dictionary.isCorrect(word)) return true; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/IPhoneticDistanceAlgorithm.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/IPhoneticDistanceAlgorithm.java index dd6eec7..9dc335e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/IPhoneticDistanceAlgorithm.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/IPhoneticDistanceAlgorithm.java @@ -22,9 +22,9 @@ public interface IPhoneticDistanceAlgorithm { * Returns the non-negative phonetic distance between two words * * @param from - * The first word + * The first word * @param to - * The second word + * The second word * @return The non-negative phonetic distance between the words. */ public int getDistance(String from, String to); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/IPhoneticHashProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/IPhoneticHashProvider.java index 042b474..ddc9b82 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/IPhoneticHashProvider.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/IPhoneticHashProvider.java @@ -22,7 +22,7 @@ public interface IPhoneticHashProvider { * Returns the phonetic hash for the word. * * @param word - * The word to get the phonetic hash for + * The word to get the phonetic hash for * @return The phonetic hash for the word */ public String getHash(String word); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellCheckEngine.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellCheckEngine.java index 1720efa..b857bd7 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellCheckEngine.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellCheckEngine.java @@ -27,11 +27,11 @@ public interface ISpellCheckEngine { * appropriate dictionaries. * * @param locale - * The locale to get the spell checker for + * The locale to get the spell checker for * @param store - * The preference store for the spell-checker + * The preference store for the spell-checker * @return A configured instance of a spell checker, or null - * iff no dictionary could be found for that locale + * iff no dictionary could be found for that locale */ ISpellChecker createSpellChecker(Locale locale, IPreferenceStore store); @@ -45,12 +45,13 @@ public interface ISpellCheckEngine { /** * Registers a dictionary for all locales available on the platform. *

                                                      - * This call is equivalent to calling registerDictionary(Locale,ISpellDictionary) - * for each of the locales returned by Locale.getAvailableLocales(). + * This call is equivalent to calling + * registerDictionary(Locale,ISpellDictionary) for each of + * the locales returned by Locale.getAvailableLocales(). *

                                                      * * @param dictionary - * The dictionary to register + * The dictionary to register */ void registerDictionary(ISpellDictionary dictionary); @@ -58,9 +59,9 @@ public interface ISpellCheckEngine { * Registers a dictionary tuned for the specified locale with this engine. * * @param locale - * The locale to register the dictionary with + * The locale to register the dictionary with * @param dictionary - * The dictionary to register + * The dictionary to register */ void registerDictionary(Locale locale, ISpellDictionary dictionary); @@ -68,20 +69,21 @@ public interface ISpellCheckEngine { * Unloads the spell check engine and its associated components. *

                                                      * All registered dictionaries are unloaded and the engine unregisters for - * preference changes. After a new call to getSpellChecker(Locale), - * it registers again for preference changes. The dictionaries perform lazy - * loading, that is to say on the next query they reload their associated - * word lists. + * preference changes. After a new call to + * getSpellChecker(Locale), it registers again for + * preference changes. The dictionaries perform lazy loading, that is to say + * on the next query they reload their associated word lists. */ void unload(); /** * Unregisters a dictionary previously registered either by a call to - * registerDictionary(Locale,ISpellDictionary) or registerDictionary(ISpellDictionary). - * If the dictionary was not registered before, nothing happens. + * registerDictionary(Locale,ISpellDictionary) or + * registerDictionary(ISpellDictionary). If the dictionary + * was not registered before, nothing happens. * * @param dictionary - * The dictionary to unregister + * The dictionary to unregister */ void unregisterDictionary(ISpellDictionary dictionary); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellCheckPreferenceKeys.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellCheckPreferenceKeys.java index ef4bf10..b11c817 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellCheckPreferenceKeys.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellCheckPreferenceKeys.java @@ -25,7 +25,7 @@ public interface ISpellCheckPreferenceKeys { * Value is of type Boolean. *

                                                      */ - public final static String SPELLING_CHECK_SPELLING= "spelling_check_spelling"; //$NON-NLS-1$ + public final static String SPELLING_CHECK_SPELLING = "spelling_check_spelling"; //$NON-NLS-1$ /** * A named preference that controls whether words containing digits should @@ -34,7 +34,7 @@ public interface ISpellCheckPreferenceKeys { * Value is of type Boolean. *

                                                      */ - public final static String SPELLING_IGNORE_DIGITS= "spelling_ignore_digits"; //$NON-NLS-1$ + public final static String SPELLING_IGNORE_DIGITS = "spelling_ignore_digits"; //$NON-NLS-1$ /** * A named preference that controls whether mixed case words should be @@ -43,7 +43,7 @@ public interface ISpellCheckPreferenceKeys { * Value is of type Boolean. *

                                                      */ - public final static String SPELLING_IGNORE_MIXED= "spelling_ignore_mixed"; //$NON-NLS-1$ + public final static String SPELLING_IGNORE_MIXED = "spelling_ignore_mixed"; //$NON-NLS-1$ /** * A named preference that controls whether sentence capitalization should @@ -52,7 +52,7 @@ public interface ISpellCheckPreferenceKeys { * Value is of type Boolean. *

                                                      */ - public final static String SPELLING_IGNORE_SENTENCE= "spelling_ignore_sentence"; //$NON-NLS-1$ + public final static String SPELLING_IGNORE_SENTENCE = "spelling_ignore_sentence"; //$NON-NLS-1$ /** * A named preference that controls whether upper case words should be @@ -61,7 +61,7 @@ public interface ISpellCheckPreferenceKeys { * Value is of type Boolean. *

                                                      */ - public final static String SPELLING_IGNORE_UPPER= "spelling_ignore_upper"; //$NON-NLS-1$ + public final static String SPELLING_IGNORE_UPPER = "spelling_ignore_upper"; //$NON-NLS-1$ /** * A named preference that controls whether urls should be ignored during @@ -70,7 +70,7 @@ public interface ISpellCheckPreferenceKeys { * Value is of type Boolean. *

                                                      */ - public final static String SPELLING_IGNORE_URLS= "spelling_ignore_urls"; //$NON-NLS-1$ + public final static String SPELLING_IGNORE_URLS = "spelling_ignore_urls"; //$NON-NLS-1$ /** * A named preference that controls the locale used for spell-checking. @@ -78,7 +78,7 @@ public interface ISpellCheckPreferenceKeys { * Value is of type String. *

                                                      */ - public final static String SPELLING_LOCALE= "spelling_locale"; //$NON-NLS-1$ + public final static String SPELLING_LOCALE = "spelling_locale"; //$NON-NLS-1$ /** * A named preference that controls the number of proposals offered during @@ -87,7 +87,7 @@ public interface ISpellCheckPreferenceKeys { * Value is of type Integer. *

                                                      */ - public final static String SPELLING_PROPOSAL_THRESHOLD= "spelling_proposal_threshold"; //$NON-NLS-1$ + public final static String SPELLING_PROPOSAL_THRESHOLD = "spelling_proposal_threshold"; //$NON-NLS-1$ /** * A named preference that specifies the workspace user dictionary. @@ -95,13 +95,14 @@ public interface ISpellCheckPreferenceKeys { * Value is of type String. *

                                                      */ - public final static String SPELLING_USER_DICTIONARY= "spelling_user_dictionary"; //$NON-NLS-1$ - + public final static String SPELLING_USER_DICTIONARY = "spelling_user_dictionary"; //$NON-NLS-1$ + /** - * A named preference that specifies whether spelling dictionaries are available to content assist. + * A named preference that specifies whether spelling dictionaries are + * available to content assist. *

                                                      * Value is of type Boolean. *

                                                      */ - public final static String SPELLING_ENABLE_CONTENTASSIST= "spelling_enable_contentassist"; //$NON-NLS-1$ + public final static String SPELLING_ENABLE_CONTENTASSIST = "spelling_enable_contentassist"; //$NON-NLS-1$ } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellChecker.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellChecker.java index decb9b5..13a9a92 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellChecker.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellChecker.java @@ -24,7 +24,7 @@ public interface ISpellChecker { * Adds a dictionary to the list of active dictionaries. * * @param dictionary - * The dictionary to add + * The dictionary to add */ public void addDictionary(ISpellDictionary dictionary); @@ -32,14 +32,15 @@ public interface ISpellChecker { * Adds a spell event listener to the active listeners. * * @param listener - * The listener to add + * The listener to add */ public void addListener(ISpellEventListener listener); - + /** * Returns whether this spell checker accepts word additions. * - * @return true if word additions are accepted, false otherwise + * @return true if word additions are accepted, + * false otherwise */ public boolean acceptsWords(); @@ -47,7 +48,7 @@ public interface ISpellChecker { * Adds the specified word to the set of correct words. * * @param word - * The word to add to the set of correct words + * The word to add to the set of correct words */ public void addWord(String word); @@ -55,7 +56,7 @@ public interface ISpellChecker { * Checks the specified word until calling ignoreWord(String). * * @param word - * The word to check + * The word to check */ public void checkWord(String word); @@ -64,7 +65,7 @@ public interface ISpellChecker { * be thread safe as this may be called inside a reconciler thread. * * @param iterator - * The iterator to use for spell-checking + * The iterator to use for spell-checking */ public void execute(ISpellCheckIterator iterator); @@ -72,10 +73,10 @@ public interface ISpellChecker { * Returns the ranked proposals for a word. * * @param word - * The word to retrieve the proposals for + * The word to retrieve the proposals for * @param sentence - * true iff the proposals should start a - * sentence, false otherwise + * true iff the proposals should start a sentence, + * false otherwise * @return Set of ranked proposals for the word */ public Set getProposals(String word, boolean sentence); @@ -84,7 +85,7 @@ public interface ISpellChecker { * Ignores the specified word until calling checkWord(String). * * @param word - * The word to ignore + * The word to ignore */ public void ignoreWord(String word); @@ -93,9 +94,9 @@ public interface ISpellChecker { * safe as this may be called from within a reconciler thread. * * @param word - * The word to check its spelling - * @return true iff the word is correctly spelled, false - * otherwise + * The word to check its spelling + * @return true iff the word is correctly spelled, + * false otherwise */ public boolean isCorrect(String word); @@ -103,7 +104,7 @@ public interface ISpellChecker { * Remove a dictionary from the list of active dictionaries. * * @param dictionary - * The dictionary to remove + * The dictionary to remove */ public void removeDictionary(ISpellDictionary dictionary); @@ -111,7 +112,7 @@ public interface ISpellChecker { * Removes a spell event listener from the active listeners. * * @param listener - * The listener to remove + * The listener to remove */ public void removeListener(ISpellEventListener listener); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellDictionary.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellDictionary.java index 05701c9..213b548 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellDictionary.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellDictionary.java @@ -19,11 +19,12 @@ import java.util.Set; * @since 3.0 */ public interface ISpellDictionary { - + /** * Returns whether this dictionary accepts new words. * - * @return true if this dictionary accepts new words, false otherwise + * @return true if this dictionary accepts new words, + * false otherwise */ public boolean acceptsWords(); @@ -31,7 +32,7 @@ public interface ISpellDictionary { * Externalizes the specified word. * * @param word - * The word to externalize in the dictionary + * The word to externalize in the dictionary */ public void addWord(String word); @@ -39,10 +40,10 @@ public interface ISpellDictionary { * Returns the ranked word proposals for an incorrectly spelled word. * * @param word - * The word to retrieve the proposals for + * The word to retrieve the proposals for * @param sentence - * true iff the proposals start a new sentence, - * false otherwise + * true iff the proposals start a new sentence, + * false otherwise * @return Array of ranked word proposals */ public Set getProposals(String word, boolean sentence); @@ -51,9 +52,9 @@ public interface ISpellDictionary { * Is the specified word correctly spelled? * * @param word - * The word to spell-check - * @return true iff this word is correctly spelled, false - * otherwise. + * The word to spell-check + * @return true iff this word is correctly spelled, + * false otherwise. */ public boolean isCorrect(String word); @@ -61,7 +62,7 @@ public interface ISpellDictionary { * Is the dictionary loaded? * * @return true iff it is loaded, false - * otherwise + * otherwise */ public boolean isLoaded(); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellEvent.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellEvent.java index 98e6f9b..ccbd107 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellEvent.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellEvent.java @@ -51,7 +51,8 @@ public interface ISpellEvent { /** * Was the incorrectly spelled word found in the dictionary? * - * @return true iff the word was found, false otherwise + * @return true iff the word was found, false + * otherwise */ public boolean isMatch(); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellEventListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellEventListener.java index dfb4a03..bd38687 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellEventListener.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellEventListener.java @@ -11,7 +11,6 @@ package net.sourceforge.phpdt.internal.ui.text.spelling.engine; - /** * Interface for spell event listeners. * @@ -23,7 +22,7 @@ public interface ISpellEventListener { * Handles a spell event. * * @param event - * Event to handle + * Event to handle */ public void handle(ISpellEvent event); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/LocaleSensitiveSpellDictionary.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/LocaleSensitiveSpellDictionary.java index 15b88f2..a80ba1a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/LocaleSensitiveSpellDictionary.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/LocaleSensitiveSpellDictionary.java @@ -34,13 +34,14 @@ public class LocaleSensitiveSpellDictionary extends AbstractSpellDictionary { * Creates a new locale sensitive spell dictionary. * * @param locale - * The locale for this dictionary + * The locale for this dictionary * @param location - * The location of the locale sensitive dictionaries + * The location of the locale sensitive dictionaries */ - public LocaleSensitiveSpellDictionary(final Locale locale, final URL location) { - fLocation= location; - fLocale= locale; + public LocaleSensitiveSpellDictionary(final Locale locale, + final URL location) { + fLocation = location; + fLocale = locale; } /** @@ -56,6 +57,9 @@ public class LocaleSensitiveSpellDictionary extends AbstractSpellDictionary { * @see net.sourceforge.phpdt.internal.ui.text.spelling.engine.AbstractSpellDictionary#getURL() */ protected final URL getURL() throws MalformedURLException { - return new URL(fLocation, fLocale.toString().toLowerCase() + "." + PHPUIMessages.getString("Spelling.dictionary.file.extension")); //$NON-NLS-1$ //$NON-NLS-2$ + return new URL( + fLocation, + fLocale.toString().toLowerCase() + + "." + PHPUIMessages.getString("Spelling.dictionary.file.extension")); //$NON-NLS-1$ //$NON-NLS-2$ } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/PersistentSpellDictionary.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/PersistentSpellDictionary.java index be610d8..20cb55c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/PersistentSpellDictionary.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/PersistentSpellDictionary.java @@ -29,12 +29,12 @@ public class PersistentSpellDictionary extends AbstractSpellDictionary { * Creates a new persistent spell dictionary. * * @param url - * The URL of the word list for this dictionary + * The URL of the word list for this dictionary */ public PersistentSpellDictionary(final URL url) { - fLocation= url; + fLocation = url; } - + /* * @see net.sourceforge.phpdt.ui.text.spelling.engine.AbstractSpellDictionary#acceptsWords() */ @@ -52,7 +52,8 @@ public class PersistentSpellDictionary extends AbstractSpellDictionary { hashWord(word); try { - final FileWriter writer= new FileWriter(fLocation.getPath(), true); + final FileWriter writer = new FileWriter(fLocation.getPath(), + true); writer.write(word); writer.write("\n"); //$NON-NLS-1$ writer.close(); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/RankedWordProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/RankedWordProposal.java index 9909796..282d05f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/RankedWordProposal.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/RankedWordProposal.java @@ -28,13 +28,13 @@ public class RankedWordProposal implements Comparable { * Creates a new ranked word proposal. * * @param text - * The text of this proposal + * The text of this proposal * @param rank - * The rank of this proposal + * The rank of this proposal */ public RankedWordProposal(final String text, final int rank) { - fText= text; - fRank= rank; + fText = text; + fRank = rank; } /* @@ -42,8 +42,8 @@ public class RankedWordProposal implements Comparable { */ public final int compareTo(Object object) { - final RankedWordProposal word= (RankedWordProposal)object; - final int rank= word.getRank(); + final RankedWordProposal word = (RankedWordProposal) object; + final int rank = word.getRank(); if (fRank < rank) return -1; @@ -94,9 +94,9 @@ public class RankedWordProposal implements Comparable { * Sets the rank of the word. * * @param rank - * The rank to set + * The rank to set */ public final void setRank(final int rank) { - fRank= rank; + fRank = rank; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/SpellEvent.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/SpellEvent.java index 627ea52..da9d671 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/SpellEvent.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/SpellEvent.java @@ -42,27 +42,29 @@ public class SpellEvent implements ISpellEvent { * Creates a new spell event. * * @param checker - * The spell-checker that causes the event + * The spell-checker that causes the event * @param word - * The word that causes the event + * The word that causes the event * @param begin - * The begin index of the word in the spell-checkable medium + * The begin index of the word in the spell-checkable medium * @param end - * The end index of the word in the spell-checkable medium + * The end index of the word in the spell-checkable medium * @param sentence - * true iff the word starts a new sentence, - * false otherwise + * true iff the word starts a new sentence, + * false otherwise * @param match - * true iff the word was found in the dictionary, - * false otherwise + * true iff the word was found in the dictionary, + * false 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; + 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; } /* diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/AbstractProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/AbstractProposal.java index 51773b9..4089800 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/AbstractProposal.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/AbstractProposal.java @@ -80,7 +80,8 @@ public abstract class AbstractProposal implements IPHPCompletionProposal { * @see ICompletionProposal#getSelection(IDocument) */ public Point getSelection(IDocument document) { - return new Point(fSelectedRegion.getOffset(), fSelectedRegion.getLength()); + return new Point(fSelectedRegion.getOffset(), fSelectedRegion + .getLength()); } protected void handleException(CoreException e) { @@ -93,7 +94,8 @@ public abstract class AbstractProposal implements IPHPCompletionProposal { protected void openErrorDialog(BadLocationException e) { Shell shell = fViewer.getTextWidget().getShell(); - MessageDialog.openError(shell, TemplateMessages.getString("TemplateEvaluator.error.title"), e.getMessage()); //$NON-NLS-1$ + MessageDialog.openError(shell, TemplateMessages + .getString("TemplateEvaluator.error.title"), e.getMessage()); //$NON-NLS-1$ } public IContextInformation getContextInformation() { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/BuiltInEngine.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/BuiltInEngine.java index 8aac30a..1ab738f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/BuiltInEngine.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/BuiltInEngine.java @@ -21,93 +21,105 @@ import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.Region; import org.eclipse.swt.graphics.Point; -//import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionManager; public class BuiltInEngine { - /** The context type. */ - private JavaContextType fContextType; - /** The result proposals. */ - private ArrayList fProposals = new ArrayList(); + /** The context type. */ + private JavaContextType fContextType; - /** - * Creates the template engine for a particular context type. - * See TemplateContext for supported context types. - */ - public BuiltInEngine(JavaContextType contextType) { - // Assert.isNotNull(contextType); - fContextType = contextType; - } + /** The result proposals. */ + private ArrayList fProposals = new ArrayList(); - /** - * Empties the collector. - * - * @param viewer the text viewer - * @param unit the compilation unit (may be null) - */ - public void reset() { - fProposals.clear(); - } + /** + * Creates the template engine for a particular context type. See + * TemplateContext for supported context types. + */ + public BuiltInEngine(JavaContextType contextType) { + // Assert.isNotNull(contextType); + fContextType = contextType; + } - /** - * Returns the array of matching templates. - */ - public IPHPCompletionProposal[] getResults() { - return (IPHPCompletionProposal[]) fProposals.toArray(new IPHPCompletionProposal[fProposals.size()]); - } + /** + * Empties the collector. + * + * @param viewer + * the text viewer + * @param unit + * the compilation unit (may be null) + */ + public void reset() { + fProposals.clear(); + } - /** - * Inspects the context of the compilation unit around completionPosition - * 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 null) - */ - public void complete(ITextViewer viewer, int completionPosition, ArrayList identifiers,ICompilationUnit compilationUnit) - //hrows JavaModelException - { - IDocument document = viewer.getDocument(); + /** + * Returns the array of matching templates. + */ + public IPHPCompletionProposal[] getResults() { + return (IPHPCompletionProposal[]) fProposals + .toArray(new IPHPCompletionProposal[fProposals.size()]); + } - // prohibit recursion - // if (LinkedPositionManager.hasActiveManager(document)) - // return; + /** + * Inspects the context of the compilation unit around + * completionPosition 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 null) + */ + public void complete(ITextViewer viewer, int completionPosition, + ArrayList identifiers, ICompilationUnit compilationUnit) + // hrows JavaModelException + { + IDocument document = viewer.getDocument(); - if (!(fContextType instanceof CompilationUnitContextType)) - return; - Point selection = viewer.getSelectedRange(); - // remember selected text - String selectedText = null; - if (selection.y != 0) { - try { - selectedText = document.get(selection.x, selection.y); - } catch (BadLocationException e) { - } - } + // prohibit recursion + // if (LinkedPositionManager.hasActiveManager(document)) + // return; -// ((CompilationUnitContextType) fContextType).setContextParameters(document, completionPosition, selection.y); //mpilationUnit); -// JavaContext context = (JavaContext) fContextType.createContext(); - JavaContext context = (JavaContext) fContextType.createContext(document, completionPosition,selection.y,compilationUnit); - context.setVariable("selection", selectedText); //$NON-NLS-1$ - int start = context.getStart(); - int end = context.getEnd(); - IRegion region = new Region(start, end - start); + if (!(fContextType instanceof CompilationUnitContextType)) + return; + Point selection = viewer.getSelectedRange(); + // remember selected text + String selectedText = null; + if (selection.y != 0) { + try { + selectedText = document.get(selection.x, selection.y); + } catch (BadLocationException e) { + } + } - // Template[] templates= Templates.getInstance().getTemplates(); - String identifier = null; - int maxProposals = PHPeclipsePlugin.MAX_PROPOSALS; - PHPElement element = null; - for (int i = 0; i != identifiers.size(); i++) { - element = (PHPElement) identifiers.get(i); - if (element instanceof PHPFunction) { - identifier = ((PHPFunction) element).getName(); - if (context.canEvaluate(identifier)) { - if (maxProposals-- < 0) { - return; - } - fProposals.add(new BuiltInProposal(identifier, (PHPFunction) element, context, region, viewer)); - } - } - } - } + // ((CompilationUnitContextType) + // fContextType).setContextParameters(document, completionPosition, + // selection.y); //mpilationUnit); + // JavaContext context = (JavaContext) fContextType.createContext(); + JavaContext context = (JavaContext) fContextType.createContext( + document, completionPosition, selection.y, 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= Templates.getInstance().getTemplates(); + String identifier = null; + int maxProposals = PHPeclipsePlugin.MAX_PROPOSALS; + PHPElement element = null; + for (int i = 0; i != identifiers.size(); i++) { + element = (PHPElement) identifiers.get(i); + if (element instanceof PHPFunction) { + identifier = ((PHPFunction) element).getName(); + if (context.canEvaluate(identifier)) { + if (maxProposals-- < 0) { + return; + } + fProposals.add(new BuiltInProposal(identifier, + (PHPFunction) element, context, region, viewer)); + } + } + } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/BuiltInProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/BuiltInProposal.java index a0e1bda..900604a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/BuiltInProposal.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/BuiltInProposal.java @@ -39,15 +39,16 @@ public class BuiltInProposal extends AbstractProposal { /** * Creates a template proposal with a template and its context. - * + * * @param template - * the template + * the template * @param context - * the context in which the template was requested. + * the context in which the template was requested. * @param image - * the icon of the proposal. + * the icon of the proposal. */ - public BuiltInProposal(String functionName, PHPFunction function, TemplateContext context, IRegion region, ITextViewer viewer) { + public BuiltInProposal(String functionName, PHPFunction function, + TemplateContext context, IRegion region, ITextViewer viewer) { super(viewer); fBuiltinFunctionName = functionName; fFunction = function; @@ -68,7 +69,8 @@ public class BuiltInProposal extends AbstractProposal { int end = fRegion.getOffset() + fRegion.getLength(); // insert template string - // String templateString = fTemplate; // fTemplateBuffer.getString(); + // String templateString = fTemplate; // + // fTemplateBuffer.getString(); document.replace(start, end - start, fBuiltinFunctionName + "()"); // translate positions @@ -88,8 +90,10 @@ public class BuiltInProposal extends AbstractProposal { // } LinkedPositionUI editor = new LinkedPositionUI(fViewer, manager); - editor.setFinalCaretOffset(fBuiltinFunctionName.length() + start + 1); - // editor.setFinalCaretOffset(getCaretOffset(fTemplateBuffer) + start); + editor.setFinalCaretOffset(fBuiltinFunctionName.length() + start + + 1); + // editor.setFinalCaretOffset(getCaretOffset(fTemplateBuffer) + + // start); editor.enter(); fSelectedRegion = editor.getSelectedRegion(); @@ -118,12 +122,15 @@ public class BuiltInProposal extends AbstractProposal { if (i0 >= 0 && (i0 < newline || newline < 0)) { int i1 = contextInfoString.indexOf(')', i0 + 1); if (i1 > 0) { - fContextInfo = new ContextInformation(null, contextInfoString.substring(i0+1, i1)); + fContextInfo = new ContextInformation(null, + contextInfoString.substring(i0 + 1, i1)); } else { - fContextInfo = new ContextInformation(null, contextInfoString); + fContextInfo = new ContextInformation(null, + contextInfoString); } } else { - fContextInfo = new ContextInformation(null, contextInfoString); + fContextInfo = new ContextInformation(null, + contextInfoString); } } } @@ -134,7 +141,8 @@ public class BuiltInProposal extends AbstractProposal { * @see ICompletionProposal#getDisplayString() */ public String getDisplayString() { - return fBuiltinFunctionName + TemplateMessages.getString("TemplateProposal.delimiter") + fFunction.getUsage(); // $NON-NLS-1$ + return fBuiltinFunctionName + + TemplateMessages.getString("TemplateProposal.delimiter") + fFunction.getUsage(); // $NON-NLS-1$ // //$NON-NLS-1$ } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/DeclarationEngine.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/DeclarationEngine.java index 835b5d4..f393c18 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/DeclarationEngine.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/DeclarationEngine.java @@ -25,240 +25,274 @@ import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.Region; import org.eclipse.swt.graphics.Point; -//import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionManager; public class DeclarationEngine { - /** The context type. */ - private JavaContextType fContextType; - /** The result proposals. */ - private ArrayList fProposals = new ArrayList(); - /** Token determines last which declarations are allowed for proposal */ - private int fLastSignificantToken; - - private IProject fProject; -// private IFile fFile; - private String fFileName; - - /** - * Creates the template engine for a particular context type. - * See TemplateContext for supported context types. - */ - public DeclarationEngine(IProject project, JavaContextType contextType, int lastSignificantToken, IFile file) { - // Assert.isNotNull(contextType); - fProject = project; - fContextType = contextType; - - fLastSignificantToken = lastSignificantToken; -// fFile = file; - if (file != null) { - fFileName = file.getProjectRelativePath().toString(); - } else { - fFileName = ""; - } - } - - /** - * Empties the collector. - * - * @param viewer the text viewer - * @param unit the compilation unit (may be null) - */ - public void reset() { - fProposals.clear(); - } - - /** - * Returns the array of matching templates. - */ - public IPHPCompletionProposal[] getResults() { - return (IPHPCompletionProposal[]) fProposals.toArray(new IPHPCompletionProposal[fProposals.size()]); - } - - /** - * Inspects the context of the compilation unit around completionPosition - * 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 null) - */ - public void completeObject(ITextViewer viewer, int completionPosition, SortedMap map, ICompilationUnit compilationUnit) { - IDocument document = viewer.getDocument(); - - if (!(fContextType instanceof CompilationUnitContextType)) - return; - - Point selection = viewer.getSelectedRange(); - - // remember selected text - String selectedText = null; - - if (selection.y != 0) { - try { - selectedText = document.get(selection.x, selection.y); - } catch (BadLocationException e) { - } - } - - JavaContext context = (JavaContext) fContextType.createContext(document, completionPosition,selection.y,compilationUnit); - context.setVariable("selection", selectedText); //$NON-NLS-1$ - - int start = context.getStart(); - int end = context.getEnd(); - String prefix = context.getKey(); - IRegion region = new Region(start, end - start); - - String identifier = null; - - SortedMap subMap = map.subMap(prefix, prefix + '\255'); - Iterator iter = subMap.keySet().iterator(); - PHPIdentifierLocation location; - ArrayList list; - int maxProposals = PHPeclipsePlugin.MAX_PROPOSALS; - while (iter.hasNext()) { - identifier = (String) iter.next(); - if (context.canEvaluate(identifier)) { - list = (ArrayList) subMap.get(identifier); - for (int i = 0; i < list.size(); i++) { - location = (PHPIdentifierLocation) list.get(i); - int type = location.getType(); - switch (fLastSignificantToken) { - case ITerminalSymbols.TokenNameMINUS_GREATER : - if (type != PHPIdentifierLocation.METHOD && type != PHPIdentifierLocation.VARIABLE) { - continue; // for loop - } - break; - case ITerminalSymbols.TokenNameVariable : - if (type != PHPIdentifierLocation.METHOD && type != PHPIdentifierLocation.VARIABLE) { - continue; // for loop - } -// check all filenames of the subclasses -// if (fFileName.equals(location.getFilename())) { -// continue; // for loop -// } - break; - case ITerminalSymbols.TokenNamethis_PHP_COMPLETION: - if (type != PHPIdentifierLocation.METHOD && type != PHPIdentifierLocation.VARIABLE) { - continue; // for loop - } - // check all filenames of the subclasses -// if (!fFileName.equals(location.getFilename())) { -// continue; // for loop -// } - break; - case ITerminalSymbols.TokenNamenew : - if (type != PHPIdentifierLocation.CLASS && type != PHPIdentifierLocation.CONSTRUCTOR) { - continue; // for loop - } - break; - default : - if (type == PHPIdentifierLocation.METHOD || type == PHPIdentifierLocation.CONSTRUCTOR || type == PHPIdentifierLocation.VARIABLE) { - continue; // for loop - } - } - if (maxProposals-- < 0) { - return; - } - fProposals.add( new DeclarationProposal(fProject, identifier, location, context, region, viewer)); - } - } - } - - } - - /** - * Inspects the context of the compilation unit around completionPosition - * 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 null) - */ - public void complete(ITextViewer viewer, int completionPosition, SortedMap map, ICompilationUnit compilationUnit) { - IDocument document = viewer.getDocument(); - - if (!(fContextType instanceof CompilationUnitContextType)) - return; - - Point selection = viewer.getSelectedRange(); - - // remember selected text - String selectedText = null; - - if (selection.y != 0) { - try { - selectedText = document.get(selection.x, selection.y); - } catch (BadLocationException e) { - } - } - -// ((CompilationUnitContextType) fContextType).setContextParameters(document, completionPosition, selection.y); - -// CompilationUnitContext context = (CompilationUnitContext) fContextType.createContext(); - JavaContext context = (JavaContext) fContextType.createContext(document, completionPosition,selection.y,compilationUnit); - context.setVariable("selection", selectedText); //$NON-NLS-1$ - - int start = context.getStart(); - int end = context.getEnd(); - String prefix = context.getKey(); - IRegion region = new Region(start, end - start); - - String identifier = null; - - SortedMap subMap = map.subMap(prefix, prefix + '\255'); - Iterator iter = subMap.keySet().iterator(); - PHPIdentifierLocation location; - ArrayList list; - int maxProposals = PHPeclipsePlugin.MAX_PROPOSALS; - while (iter.hasNext()) { - identifier = (String) iter.next(); - if (context.canEvaluate(identifier)) { - list = (ArrayList) subMap.get(identifier); - for (int i = 0; i < list.size(); i++) { - location = (PHPIdentifierLocation) list.get(i); - int type = location.getType(); - switch (fLastSignificantToken) { - case ITerminalSymbols.TokenNameMINUS_GREATER : - if (type != PHPIdentifierLocation.METHOD && type != PHPIdentifierLocation.VARIABLE) { - continue; // for loop - } - break; - case ITerminalSymbols.TokenNameVariable : - if (type != PHPIdentifierLocation.METHOD && type != PHPIdentifierLocation.VARIABLE) { - continue; // for loop - } -// check all filenames of the subclasses - if (fFileName.equals(location.getFilename())) { - continue; // for loop - } - break; - case ITerminalSymbols.TokenNamethis_PHP_COMPLETION: - if (type != PHPIdentifierLocation.METHOD && type != PHPIdentifierLocation.VARIABLE) { - continue; // for loop - } - // check all filenames of the subclasses - if (!fFileName.equals(location.getFilename())) { - continue; // for loop - } - break; - case ITerminalSymbols.TokenNamenew : - if (type != PHPIdentifierLocation.CLASS && type != PHPIdentifierLocation.CONSTRUCTOR) { - continue; // for loop - } - break; - default : - if (type == PHPIdentifierLocation.METHOD || type == PHPIdentifierLocation.CONSTRUCTOR || type == PHPIdentifierLocation.VARIABLE) { - continue; // for loop - } - } - if (maxProposals-- < 0) { - return; - } - fProposals.add( new DeclarationProposal(fProject, identifier, location, context, region, viewer)); - } - } - } - - } + /** The context type. */ + private JavaContextType fContextType; + + /** The result proposals. */ + private ArrayList fProposals = new ArrayList(); + + /** Token determines last which declarations are allowed for proposal */ + private int fLastSignificantToken; + + private IProject fProject; + + // private IFile fFile; + private String fFileName; + + /** + * Creates the template engine for a particular context type. See + * TemplateContext for supported context types. + */ + public DeclarationEngine(IProject project, JavaContextType contextType, + int lastSignificantToken, IFile file) { + // Assert.isNotNull(contextType); + fProject = project; + fContextType = contextType; + + fLastSignificantToken = lastSignificantToken; + // fFile = file; + if (file != null) { + fFileName = file.getProjectRelativePath().toString(); + } else { + fFileName = ""; + } + } + + /** + * Empties the collector. + * + * @param viewer + * the text viewer + * @param unit + * the compilation unit (may be null) + */ + public void reset() { + fProposals.clear(); + } + + /** + * Returns the array of matching templates. + */ + public IPHPCompletionProposal[] getResults() { + return (IPHPCompletionProposal[]) fProposals + .toArray(new IPHPCompletionProposal[fProposals.size()]); + } + + /** + * Inspects the context of the compilation unit around + * completionPosition 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 null) + */ + public void completeObject(ITextViewer viewer, int completionPosition, + SortedMap map, ICompilationUnit compilationUnit) { + IDocument document = viewer.getDocument(); + + if (!(fContextType instanceof CompilationUnitContextType)) + return; + + Point selection = viewer.getSelectedRange(); + + // remember selected text + String selectedText = null; + + if (selection.y != 0) { + try { + selectedText = document.get(selection.x, selection.y); + } catch (BadLocationException e) { + } + } + + JavaContext context = (JavaContext) fContextType.createContext( + document, completionPosition, selection.y, compilationUnit); + context.setVariable("selection", selectedText); //$NON-NLS-1$ + + int start = context.getStart(); + int end = context.getEnd(); + String prefix = context.getKey(); + IRegion region = new Region(start, end - start); + + String identifier = null; + + SortedMap subMap = map.subMap(prefix, prefix + '\255'); + Iterator iter = subMap.keySet().iterator(); + PHPIdentifierLocation location; + ArrayList list; + int maxProposals = PHPeclipsePlugin.MAX_PROPOSALS; + while (iter.hasNext()) { + identifier = (String) iter.next(); + if (context.canEvaluate(identifier)) { + list = (ArrayList) subMap.get(identifier); + for (int i = 0; i < list.size(); i++) { + location = (PHPIdentifierLocation) list.get(i); + int type = location.getType(); + switch (fLastSignificantToken) { + case ITerminalSymbols.TokenNameMINUS_GREATER: + if (type != PHPIdentifierLocation.METHOD + && type != PHPIdentifierLocation.VARIABLE) { + continue; // for loop + } + break; + case ITerminalSymbols.TokenNameVariable: + if (type != PHPIdentifierLocation.METHOD + && type != PHPIdentifierLocation.VARIABLE) { + continue; // for loop + } + // check all filenames of the subclasses + // if (fFileName.equals(location.getFilename())) { + // continue; // for loop + // } + break; + case ITerminalSymbols.TokenNamethis_PHP_COMPLETION: + if (type != PHPIdentifierLocation.METHOD + && type != PHPIdentifierLocation.VARIABLE) { + continue; // for loop + } + // check all filenames of the subclasses + // if (!fFileName.equals(location.getFilename())) { + // continue; // for loop + // } + break; + case ITerminalSymbols.TokenNamenew: + if (type != PHPIdentifierLocation.CLASS + && type != PHPIdentifierLocation.CONSTRUCTOR) { + continue; // for loop + } + break; + default: + if (type == PHPIdentifierLocation.METHOD + || type == PHPIdentifierLocation.CONSTRUCTOR + || type == PHPIdentifierLocation.VARIABLE) { + continue; // for loop + } + } + if (maxProposals-- < 0) { + return; + } + fProposals.add(new DeclarationProposal(fProject, + identifier, location, context, region, viewer)); + } + } + } + + } + + /** + * Inspects the context of the compilation unit around + * completionPosition 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 null) + */ + public void complete(ITextViewer viewer, int completionPosition, + SortedMap map, ICompilationUnit compilationUnit) { + IDocument document = viewer.getDocument(); + + if (!(fContextType instanceof CompilationUnitContextType)) + return; + + Point selection = viewer.getSelectedRange(); + + // remember selected text + String selectedText = null; + + if (selection.y != 0) { + try { + selectedText = document.get(selection.x, selection.y); + } catch (BadLocationException e) { + } + } + + // ((CompilationUnitContextType) + // fContextType).setContextParameters(document, completionPosition, + // selection.y); + + // CompilationUnitContext context = (CompilationUnitContext) + // fContextType.createContext(); + JavaContext context = (JavaContext) fContextType.createContext( + document, completionPosition, selection.y, compilationUnit); + context.setVariable("selection", selectedText); //$NON-NLS-1$ + + int start = context.getStart(); + int end = context.getEnd(); + String prefix = context.getKey(); + IRegion region = new Region(start, end - start); + + String identifier = null; + + SortedMap subMap = map.subMap(prefix, prefix + '\255'); + Iterator iter = subMap.keySet().iterator(); + PHPIdentifierLocation location; + ArrayList list; + int maxProposals = PHPeclipsePlugin.MAX_PROPOSALS; + while (iter.hasNext()) { + identifier = (String) iter.next(); + if (context.canEvaluate(identifier)) { + list = (ArrayList) subMap.get(identifier); + for (int i = 0; i < list.size(); i++) { + location = (PHPIdentifierLocation) list.get(i); + int type = location.getType(); + switch (fLastSignificantToken) { + case ITerminalSymbols.TokenNameMINUS_GREATER: + if (type != PHPIdentifierLocation.METHOD + && type != PHPIdentifierLocation.VARIABLE) { + continue; // for loop + } + break; + case ITerminalSymbols.TokenNameVariable: + if (type != PHPIdentifierLocation.METHOD + && type != PHPIdentifierLocation.VARIABLE) { + continue; // for loop + } + // check all filenames of the subclasses + if (fFileName.equals(location.getFilename())) { + continue; // for loop + } + break; + case ITerminalSymbols.TokenNamethis_PHP_COMPLETION: + if (type != PHPIdentifierLocation.METHOD + && type != PHPIdentifierLocation.VARIABLE) { + continue; // for loop + } + // check all filenames of the subclasses + if (!fFileName.equals(location.getFilename())) { + continue; // for loop + } + break; + case ITerminalSymbols.TokenNamenew: + if (type != PHPIdentifierLocation.CLASS + && type != PHPIdentifierLocation.CONSTRUCTOR) { + continue; // for loop + } + break; + default: + if (type == PHPIdentifierLocation.METHOD + || type == PHPIdentifierLocation.CONSTRUCTOR + || type == PHPIdentifierLocation.VARIABLE) { + continue; // for loop + } + } + if (maxProposals-- < 0) { + return; + } + fProposals.add(new DeclarationProposal(fProject, + identifier, location, context, region, viewer)); + } + } + } + + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/DeclarationProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/DeclarationProposal.java index bb65147..d2edd51 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/DeclarationProposal.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/DeclarationProposal.java @@ -55,15 +55,16 @@ public class DeclarationProposal extends AbstractProposal { // implements /** * Creates a template proposal with a template and its context. - * + * * @param template - * the template + * the template * @param context - * the context in which the template was requested. + * the context in which the template was requested. * @param image - * the icon of the proposal. + * the icon of the proposal. */ - public DeclarationProposal(IProject project, String identifierName, PHPIdentifierLocation location, TemplateContext context, + public DeclarationProposal(IProject project, String identifierName, + PHPIdentifierLocation location, TemplateContext context, IRegion region, ITextViewer viewer) { super(viewer); // Image image_fun, @@ -121,13 +122,19 @@ public class DeclarationProposal extends AbstractProposal { // implements LinkedPositionUI editor = new LinkedPositionUI(fViewer, manager); switch (fLocation.getType()) { case PHPIdentifierLocation.FUNCTION: - editor.setFinalCaretOffset(fIdentifierName.length() + start + 1); + editor + .setFinalCaretOffset(fIdentifierName.length() + start + + 1); break; case PHPIdentifierLocation.CONSTRUCTOR: - editor.setFinalCaretOffset(fIdentifierName.length() + start + 1); + editor + .setFinalCaretOffset(fIdentifierName.length() + start + + 1); break; case PHPIdentifierLocation.METHOD: - editor.setFinalCaretOffset(fIdentifierName.length() + start + 1); + editor + .setFinalCaretOffset(fIdentifierName.length() + start + + 1); break; default: @@ -166,7 +173,8 @@ public class DeclarationProposal extends AbstractProposal { // implements workspaceLocation = fProject.getLocation().toString() + '/'; } else { // should never happen? - workspaceLocation = PHPeclipsePlugin.getWorkspace().getRoot().getLocation().toString(); + workspaceLocation = PHPeclipsePlugin.getWorkspace().getRoot() + .getLocation().toString(); } String filename = workspaceLocation + fLocation.getFilename(); PHPDocUtil.appendPHPDoc(hoverInfoBuffer, filename, fLocation); @@ -178,14 +186,16 @@ public class DeclarationProposal extends AbstractProposal { // implements if (fLocation != null) { fInfo = fLocation.getUsage(); if (fInfo != null) { - // extract the parameter context information for the function: + // extract the parameter context information for the + // function: int i0 = fInfo.indexOf('('); int newline = fInfo.indexOf('\n'); if (i0 >= 0 && (i0 < newline || newline < 0)) { int i1 = fInfo.indexOf(')', i0 + 1); if (i1 > 0) { - fContextInfo = new ContextInformation(null, fInfo.substring(i0+1, i1)); + fContextInfo = new ContextInformation(null, fInfo + .substring(i0 + 1, i1)); } else { fContextInfo = new ContextInformation(null, fInfo); } @@ -207,13 +217,16 @@ public class DeclarationProposal extends AbstractProposal { // implements workspaceLocation = fProject.getName().toString() + '/'; } else { // should never happen? - workspaceLocation = PHPeclipsePlugin.getWorkspace().getRoot().getLocation().toString(); + workspaceLocation = PHPeclipsePlugin.getWorkspace().getRoot() + .getLocation().toString(); } String filename = workspaceLocation + fLocation.getFilename(); String usage = PHPDocUtil.getUsage(filename, fLocation); - String result = fIdentifierName + TemplateMessages.getString("TemplateProposal.delimiter"); + String result = fIdentifierName + + TemplateMessages.getString("TemplateProposal.delimiter"); if (usage.length() > 0) { - result += usage + TemplateMessages.getString("TemplateProposal.delimiter"); + result += usage + + TemplateMessages.getString("TemplateProposal.delimiter"); } result += filename; return result; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/IdentifierEngine.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/IdentifierEngine.java index f9f0d99..03f177a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/IdentifierEngine.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/IdentifierEngine.java @@ -20,96 +20,102 @@ import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.Region; import org.eclipse.swt.graphics.Point; -//import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionManager; public class IdentifierEngine { - /** The context type. */ - private JavaContextType fContextType; - /** The result proposals. */ - private ArrayList fProposals = new ArrayList(); - - /** - * Creates the template engine for a particular context type. - * See TemplateContext for supported context types. - */ - public IdentifierEngine(JavaContextType contextType) { - // Assert.isNotNull(contextType); - fContextType = contextType; - } - - /** - * Empties the collector. - * - * @param viewer the text viewer - * @param unit the compilation unit (may be null) - */ - public void reset() { - fProposals.clear(); - } - - /** - * Returns the array of matching templates. - */ - public IPHPCompletionProposal[] getResults() { - return (IPHPCompletionProposal[]) fProposals.toArray(new IPHPCompletionProposal[fProposals.size()]); - } - - /** - * Inspects the context of the compilation unit around completionPosition - * 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 null) - */ - public void complete(ITextViewer viewer, int completionPosition, Object[] identifiers,ICompilationUnit compilationUnit) - //hrows JavaModelException - { - IDocument document = viewer.getDocument(); - - if (!(fContextType instanceof CompilationUnitContextType)) - return; - - Point selection = viewer.getSelectedRange(); - // remember selected text - String selectedText = null; - if (selection.y != 0) { - try { - selectedText = document.get(selection.x, selection.y); - } catch (BadLocationException e) { - } - } - -// ((CompilationUnitContextType) fContextType).setContextParameters(document, completionPosition, selection.y); //mpilationUnit); - -// JavaContext context = (JavaContext) fContextType.createContext(); - JavaContext context = (JavaContext) fContextType.createContext(document, completionPosition,selection.y,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= Templates.getInstance().getTemplates(); - String identifier = null; - int maxProposals = PHPeclipsePlugin.MAX_PROPOSALS; - - for (int i = 0; i != identifiers.length; i++) { - identifier = (String) identifiers[i]; - if (context.canEvaluate(identifier)) { - if (maxProposals-- < 0) { - return; - } - fProposals.add( - new IdentifierProposal( - identifier, - context, - region, - viewer, - PHPUiImages.get(PHPUiImages.IMG_FUN), - PHPUiImages.get(PHPUiImages.IMG_VAR))); - } - } - } + /** The context type. */ + private JavaContextType fContextType; + + /** The result proposals. */ + private ArrayList fProposals = new ArrayList(); + + /** + * Creates the template engine for a particular context type. See + * TemplateContext for supported context types. + */ + public IdentifierEngine(JavaContextType contextType) { + // Assert.isNotNull(contextType); + fContextType = contextType; + } + + /** + * Empties the collector. + * + * @param viewer + * the text viewer + * @param unit + * the compilation unit (may be null) + */ + public void reset() { + fProposals.clear(); + } + + /** + * Returns the array of matching templates. + */ + public IPHPCompletionProposal[] getResults() { + return (IPHPCompletionProposal[]) fProposals + .toArray(new IPHPCompletionProposal[fProposals.size()]); + } + + /** + * Inspects the context of the compilation unit around + * completionPosition 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 null) + */ + public void complete(ITextViewer viewer, int completionPosition, + Object[] identifiers, ICompilationUnit compilationUnit) + // hrows JavaModelException + { + IDocument document = viewer.getDocument(); + + if (!(fContextType instanceof CompilationUnitContextType)) + return; + + Point selection = viewer.getSelectedRange(); + // remember selected text + String selectedText = null; + if (selection.y != 0) { + try { + selectedText = document.get(selection.x, selection.y); + } catch (BadLocationException e) { + } + } + + // ((CompilationUnitContextType) + // fContextType).setContextParameters(document, completionPosition, + // selection.y); //mpilationUnit); + + // JavaContext context = (JavaContext) fContextType.createContext(); + JavaContext context = (JavaContext) fContextType.createContext( + document, completionPosition, selection.y, 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= Templates.getInstance().getTemplates(); + String identifier = null; + int maxProposals = PHPeclipsePlugin.MAX_PROPOSALS; + + for (int i = 0; i != identifiers.length; i++) { + identifier = (String) identifiers[i]; + if (context.canEvaluate(identifier)) { + if (maxProposals-- < 0) { + return; + } + fProposals.add(new IdentifierProposal(identifier, context, + region, viewer, PHPUiImages.get(PHPUiImages.IMG_FUN), + PHPUiImages.get(PHPUiImages.IMG_VAR))); + } + } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/IdentifierProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/IdentifierProposal.java index 967ec7c..280739e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/IdentifierProposal.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/IdentifierProposal.java @@ -10,8 +10,6 @@ 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.contentassist.ContextInformation; -import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jface.text.templates.TemplateContext; import org.eclipse.swt.graphics.Image; @@ -19,77 +17,84 @@ import org.eclipse.swt.graphics.Image; * A PHP identifier proposal. */ public class IdentifierProposal extends AbstractProposal { - private final TemplateContext fContext; - - private final Image fImage_fun; - private final Image fImage_var; - //private TemplateBuffer fTemplateBuffer; - private String fOldText; - private final IRegion fRegion; - // private IRegion fSelectedRegion; // initialized by apply() - private final String fTemplate; - - public IdentifierProposal(String template, TemplateContext context, - IRegion region, ITextViewer viewer, Image image_fun, Image image_var) { - super(viewer); - fTemplate = template; - fContext = context; - - // fViewer = viewer; - fImage_fun = image_fun; - fImage_var = image_var; - fRegion = region; - } - - public void apply(IDocument document) { - try { - int start = fRegion.getOffset(); - int end = fRegion.getOffset() + fRegion.getLength(); - document.replace(start, end - start, fTemplate); - // translate positions - LinkedPositionManager manager = new LinkedPositionManager(document); - - LinkedPositionUI editor = new LinkedPositionUI(fViewer, manager); - editor.setFinalCaretOffset(fTemplate.length() + start); - // editor.setFinalCaretOffset(getCaretOffset(fTemplateBuffer) + start); - editor.enter(); - fSelectedRegion = editor.getSelectedRegion(); - } catch (BadLocationException e) { - PHPeclipsePlugin.log(e); - openErrorDialog(e); - } - } - - public String getAdditionalProposalInfo() { - return textToHTML(fTemplate); // fTemplateBuffer.getString()); - } - - public String getDisplayString() { - return fTemplate + TemplateMessages.getString("TemplateProposal.delimiter") + fTemplate; // $NON-NLS-1$ - } - - public Image getImage() { - if (fTemplate.charAt(0) == '$') { - return fImage_var; - } - return fImage_fun; - } - - public int getRelevance() { - if (fContext instanceof JavaContext) { - JavaContext context = (JavaContext) fContext; - switch (context.getCharacterBeforeStart()) { - // high relevance after whitespace - case ' ' : - case '\r' : - case '\n' : - case '\t' : - return 50; - default : - return 0; - } - } else { - return 50; - } - } + private final TemplateContext fContext; + + private final Image fImage_fun; + + private final Image fImage_var; + + // private TemplateBuffer fTemplateBuffer; + private String fOldText; + + private final IRegion fRegion; + + // private IRegion fSelectedRegion; // initialized by apply() + private final String fTemplate; + + public IdentifierProposal(String template, TemplateContext context, + IRegion region, ITextViewer viewer, Image image_fun, Image image_var) { + super(viewer); + fTemplate = template; + fContext = context; + + // fViewer = viewer; + fImage_fun = image_fun; + fImage_var = image_var; + fRegion = region; + } + + public void apply(IDocument document) { + try { + int start = fRegion.getOffset(); + int end = fRegion.getOffset() + fRegion.getLength(); + document.replace(start, end - start, fTemplate); + // translate positions + LinkedPositionManager manager = new LinkedPositionManager(document); + + LinkedPositionUI editor = new LinkedPositionUI(fViewer, manager); + editor.setFinalCaretOffset(fTemplate.length() + start); + // editor.setFinalCaretOffset(getCaretOffset(fTemplateBuffer) + + // start); + editor.enter(); + fSelectedRegion = editor.getSelectedRegion(); + } catch (BadLocationException e) { + PHPeclipsePlugin.log(e); + openErrorDialog(e); + } + } + + public String getAdditionalProposalInfo() { + return textToHTML(fTemplate); // fTemplateBuffer.getString()); + } + + public String getDisplayString() { + return fTemplate + + TemplateMessages.getString("TemplateProposal.delimiter") + + fTemplate; // $NON-NLS-1$ + } + + public Image getImage() { + if (fTemplate.charAt(0) == '$') { + return fImage_var; + } + return fImage_fun; + } + + public int getRelevance() { + if (fContext instanceof JavaContext) { + JavaContext context = (JavaContext) fContext; + switch (context.getCharacterBeforeStart()) { + // high relevance after whitespace + case ' ': + case '\r': + case '\n': + case '\t': + return 50; + default: + return 0; + } + } else { + return 50; + } + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/LocalVariableProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/LocalVariableProposal.java index d74f323..2cd8210 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/LocalVariableProposal.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/LocalVariableProposal.java @@ -17,124 +17,127 @@ import org.eclipse.swt.graphics.Image; */ public class LocalVariableProposal extends AbstractProposal { - private final String fIdentifierName; - - private final IRegion fRegion; - - private final int fRelevance; - - /** - * Creates a template proposal with a template and its context. - * - * @param template - * the template - * @param image - * the icon of the proposal. - */ - public LocalVariableProposal(String identifierName, IRegion region, ITextViewer viewer) { - this(identifierName, region, viewer, 99); - } - - public LocalVariableProposal(String identifierName, IRegion region, ITextViewer viewer, int relevance) { - super(viewer); - fIdentifierName = identifierName; - fRegion = region; - fRelevance = relevance; - } - - /* - * @see ICompletionProposal#apply(IDocument) - */ - public void apply(IDocument document) { - try { - // if (fTemplateBuffer == null) - // fTemplateBuffer= fContext.evaluate(fTemplate); - - int start = fRegion.getOffset(); - int end = fRegion.getOffset() + fRegion.getLength(); - - document.replace(start, end - start, fIdentifierName); - - // translate positions - LinkedPositionManager manager = new LinkedPositionManager(document); - - LinkedPositionUI editor = new LinkedPositionUI(fViewer, manager); - editor.setFinalCaretOffset(fIdentifierName.length() + start); - editor.enter(); - - fSelectedRegion = editor.getSelectedRegion(); - - } catch (BadLocationException e) { - PHPeclipsePlugin.log(e); - openErrorDialog(e); - - } - // catch (CoreException e) { - // handleException(e); - // } - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object obj) { - if (obj instanceof LocalVariableProposal) { - return fIdentifierName.equals(((LocalVariableProposal) obj).fIdentifierName); - } - return false; - } - - /* - * @see ICompletionProposal#getAdditionalProposalInfo() - */ - public String getAdditionalProposalInfo() { - StringBuffer hoverInfoBuffer = new StringBuffer(); - if (fRelevance>95) { - hoverInfoBuffer.append("function source variable -"); - } else { - hoverInfoBuffer.append("editor source variable -"); - } - hoverInfoBuffer.append(fIdentifierName); - return hoverInfoBuffer.toString(); - } - - /* - * @see ICompletionProposal#getContextInformation() - */ - public IContextInformation getContextInformation() { - return null; - } - - /* - * @see ICompletionProposal#getDisplayString() - */ - public String getDisplayString() { - return fIdentifierName; // $NON-NLS-1$ //$NON-NLS-1$ - } - - /* - * @see ICompletionProposal#getImage() - */ - public Image getImage() { - return PHPUiImages.get(PHPUiImages.IMG_VAR); - } - - /* - * @see IJavaCompletionProposal#getRelevance() - */ - public int getRelevance() { - return fRelevance; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - public int hashCode() { - return fIdentifierName.hashCode(); - } + private final String fIdentifierName; + + private final IRegion fRegion; + + private final int fRelevance; + + /** + * Creates a template proposal with a template and its context. + * + * @param template + * the template + * @param image + * the icon of the proposal. + */ + public LocalVariableProposal(String identifierName, IRegion region, + ITextViewer viewer) { + this(identifierName, region, viewer, 99); + } + + public LocalVariableProposal(String identifierName, IRegion region, + ITextViewer viewer, int relevance) { + super(viewer); + fIdentifierName = identifierName; + fRegion = region; + fRelevance = relevance; + } + + /* + * @see ICompletionProposal#apply(IDocument) + */ + public void apply(IDocument document) { + try { + // if (fTemplateBuffer == null) + // fTemplateBuffer= fContext.evaluate(fTemplate); + + int start = fRegion.getOffset(); + int end = fRegion.getOffset() + fRegion.getLength(); + + document.replace(start, end - start, fIdentifierName); + + // translate positions + LinkedPositionManager manager = new LinkedPositionManager(document); + + LinkedPositionUI editor = new LinkedPositionUI(fViewer, manager); + editor.setFinalCaretOffset(fIdentifierName.length() + start); + editor.enter(); + + fSelectedRegion = editor.getSelectedRegion(); + + } catch (BadLocationException e) { + PHPeclipsePlugin.log(e); + openErrorDialog(e); + + } + // catch (CoreException e) { + // handleException(e); + // } + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + public boolean equals(Object obj) { + if (obj instanceof LocalVariableProposal) { + return fIdentifierName + .equals(((LocalVariableProposal) obj).fIdentifierName); + } + return false; + } + + /* + * @see ICompletionProposal#getAdditionalProposalInfo() + */ + public String getAdditionalProposalInfo() { + StringBuffer hoverInfoBuffer = new StringBuffer(); + if (fRelevance > 95) { + hoverInfoBuffer.append("function source variable -"); + } else { + hoverInfoBuffer.append("editor source variable -"); + } + hoverInfoBuffer.append(fIdentifierName); + return hoverInfoBuffer.toString(); + } + + /* + * @see ICompletionProposal#getContextInformation() + */ + public IContextInformation getContextInformation() { + return null; + } + + /* + * @see ICompletionProposal#getDisplayString() + */ + public String getDisplayString() { + return fIdentifierName; // $NON-NLS-1$ //$NON-NLS-1$ + } + + /* + * @see ICompletionProposal#getImage() + */ + public Image getImage() { + return PHPUiImages.get(PHPUiImages.IMG_VAR); + } + + /* + * @see IJavaCompletionProposal#getRelevance() + */ + public int getRelevance() { + return fRelevance; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#hashCode() + */ + public int hashCode() { + return fIdentifierName.hashCode(); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/SQLProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/SQLProposal.java index 66cd62c..cd3ba69 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/SQLProposal.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/SQLProposal.java @@ -3,6 +3,7 @@ * All Rights Reserved. */ package net.sourceforge.phpdt.internal.ui.text.template; + import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionManager; import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI; import net.sourceforge.phpeclipse.PHPeclipsePlugin; @@ -14,135 +15,151 @@ import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jface.text.templates.TemplateContext; import org.eclipse.swt.graphics.Image; + /** * A PHP identifier proposal. */ -public class SQLProposal extends AbstractProposal { //implements - // IPHPCompletionProposal - // { - private final TemplateContext fContext; - private final Image fImage_var; - private final IRegion fRegion; - private final String fColumnName; - private final String fTableName; - - private int fRelevance; - /** - * 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 image - * the icon of the proposal. - */ - public SQLProposal(String tableName, TemplateContext context, IRegion region, - ITextViewer viewer, Image image_var) { - super(viewer); - fTableName = tableName; - fColumnName = null; - fContext = context; - fImage_var = image_var; - fRegion = region; - fRelevance = 0; - } - - public SQLProposal(String tableName, String columnName, TemplateContext context, IRegion region, - ITextViewer viewer, Image image_var) { - super(viewer); - fTableName = tableName; - fColumnName = columnName; - fContext = context; - fImage_var = image_var; - fRegion = region; - fRelevance = 0; - } - /* - * @see ICompletionProposal#apply(IDocument) - */ - public void apply(IDocument document) { - try { - // if (fTemplateBuffer == null) - // fTemplateBuffer= fContext.evaluate(fTemplate); - int start = fRegion.getOffset(); - int end = fRegion.getOffset() + fRegion.getLength(); - String resultString = fTableName; - if (fColumnName!=null) { - resultString = fColumnName; - } - // insert template string - // String templateString = fTemplate; // fTemplateBuffer.getString(); - document.replace(start, end - start, resultString); - // translate positions - LinkedPositionManager manager = new LinkedPositionManager(document); - // TemplatePosition[] variables= fTemplateBuffer.getVariables(); - // for (int i= 0; i != variables.length; i++) { - // TemplatePosition variable= variables[i]; - // - // if (variable.isResolved()) - // continue; - // - // int[] offsets= variable.getOffsets(); - // int length= variable.getLength(); - // - // for (int j= 0; j != offsets.length; j++) - // manager.addPosition(offsets[j] + start, length); - // } - LinkedPositionUI editor = new LinkedPositionUI(fViewer, manager); - editor.setFinalCaretOffset(resultString.length() + start); - // editor.setFinalCaretOffset(getCaretOffset(fTemplateBuffer) + start); - editor.enter(); - fSelectedRegion = editor.getSelectedRegion(); - } catch (BadLocationException e) { - PHPeclipsePlugin.log(e); - openErrorDialog(e); - } - // catch (CoreException e) { - // handleException(e); - // } - } - /* - * @see ICompletionProposal#getAdditionalProposalInfo() - */ - public String getAdditionalProposalInfo() { - if (fColumnName==null) { - return textToHTML(fTableName); - } - return fColumnName+" (Table: "+fTableName+")"; - } - - /* - * @see ICompletionProposal#getContextInformation() - */ - public IContextInformation getContextInformation() { - return null; - } - /* - * @see ICompletionProposal#getDisplayString() - */ - public String getDisplayString() { - if (fColumnName==null) { - return fTableName; - } - return fColumnName+" (Table: "+fTableName+")"; // $NON-NLS-1$ - } - /* - * @see ICompletionProposal#getImage() - */ - public Image getImage() { - return fImage_var; - } - /* - * @see IJavaCompletionProposal#getRelevance() - */ - public int getRelevance() { - return fRelevance; - } - /** - * @param relevance The relevance to set. - */ - public void setRelevance(int relevance) { - fRelevance = relevance; - } +public class SQLProposal extends AbstractProposal { // implements + // IPHPCompletionProposal + // { + private final TemplateContext fContext; + + private final Image fImage_var; + + private final IRegion fRegion; + + private final String fColumnName; + + private final String fTableName; + + private int fRelevance; + + /** + * 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 image + * the icon of the proposal. + */ + public SQLProposal(String tableName, TemplateContext context, + IRegion region, ITextViewer viewer, Image image_var) { + super(viewer); + fTableName = tableName; + fColumnName = null; + fContext = context; + fImage_var = image_var; + fRegion = region; + fRelevance = 0; + } + + public SQLProposal(String tableName, String columnName, + TemplateContext context, IRegion region, ITextViewer viewer, + Image image_var) { + super(viewer); + fTableName = tableName; + fColumnName = columnName; + fContext = context; + fImage_var = image_var; + fRegion = region; + fRelevance = 0; + } + + /* + * @see ICompletionProposal#apply(IDocument) + */ + public void apply(IDocument document) { + try { + // if (fTemplateBuffer == null) + // fTemplateBuffer= fContext.evaluate(fTemplate); + int start = fRegion.getOffset(); + int end = fRegion.getOffset() + fRegion.getLength(); + String resultString = fTableName; + if (fColumnName != null) { + resultString = fColumnName; + } + // insert template string + // String templateString = fTemplate; // + // fTemplateBuffer.getString(); + document.replace(start, end - start, resultString); + // translate positions + LinkedPositionManager manager = new LinkedPositionManager(document); + // TemplatePosition[] variables= fTemplateBuffer.getVariables(); + // for (int i= 0; i != variables.length; i++) { + // TemplatePosition variable= variables[i]; + // + // if (variable.isResolved()) + // continue; + // + // int[] offsets= variable.getOffsets(); + // int length= variable.getLength(); + // + // for (int j= 0; j != offsets.length; j++) + // manager.addPosition(offsets[j] + start, length); + // } + LinkedPositionUI editor = new LinkedPositionUI(fViewer, manager); + editor.setFinalCaretOffset(resultString.length() + start); + // editor.setFinalCaretOffset(getCaretOffset(fTemplateBuffer) + + // start); + editor.enter(); + fSelectedRegion = editor.getSelectedRegion(); + } catch (BadLocationException e) { + PHPeclipsePlugin.log(e); + openErrorDialog(e); + } + // catch (CoreException e) { + // handleException(e); + // } + } + + /* + * @see ICompletionProposal#getAdditionalProposalInfo() + */ + public String getAdditionalProposalInfo() { + if (fColumnName == null) { + return textToHTML(fTableName); + } + return fColumnName + " (Table: " + fTableName + ")"; + } + + /* + * @see ICompletionProposal#getContextInformation() + */ + public IContextInformation getContextInformation() { + return null; + } + + /* + * @see ICompletionProposal#getDisplayString() + */ + public String getDisplayString() { + if (fColumnName == null) { + return fTableName; + } + return fColumnName + " (Table: " + fTableName + ")"; // $NON-NLS-1$ + } + + /* + * @see ICompletionProposal#getImage() + */ + public Image getImage() { + return fImage_var; + } + + /* + * @see IJavaCompletionProposal#getRelevance() + */ + public int getRelevance() { + return fRelevance; + } + + /** + * @param relevance + * The relevance to set. + */ + public void setRelevance(int relevance) { + fRelevance = relevance; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/InclusivePositionUpdater.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/InclusivePositionUpdater.java index c88cb9f..dcd7b5f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/InclusivePositionUpdater.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/InclusivePositionUpdater.java @@ -16,8 +16,8 @@ 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. + * Position updater that takes any change in [position.offset, position.offset + + * position.length] as belonging to the position. * * @since 3.0 */ @@ -29,10 +29,11 @@ class InclusivePositionUpdater implements IPositionUpdater { /** * Creates a new updater for the given category. * - * @param category the new category. + * @param category + * the new category. */ public InclusivePositionUpdater(String category) { - fCategory= category; + fCategory = category; } /* @@ -40,46 +41,49 @@ class InclusivePositionUpdater implements IPositionUpdater { */ 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; + 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); + Position[] positions = event.getDocument().getPositions(fCategory); - for (int i= 0; i != positions.length; i++) { + for (int i = 0; i != positions.length; i++) { - Position position= positions[i]; + Position position = positions[i]; if (position.isDeleted()) continue; - int offset= position.getOffset(); - int length= position.getLength(); - int end= offset + length; + int offset = position.getOffset(); + int length = position.getLength(); + int end = offset + length; - if (offset > eventOffset + eventOldLength) + 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) { + } 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; + int newEnd = eventOffset + eventNewLength; position.setLength(newEnd - offset); } else if (end > eventOffset + eventOldLength) { - // event extends from before position into it - adjust offset + // 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; + int deleted = eventOffset + eventOldLength - offset; position.setLength(length - deleted + eventNewLength); } else { // event consumes the position - delete it diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/MultiVariable.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/MultiVariable.java index c9a6572..4ed0899 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/MultiVariable.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/MultiVariable.java @@ -16,38 +16,40 @@ import java.util.Map; import org.eclipse.jface.text.Assert; import org.eclipse.jface.text.templates.TemplateVariable; - /** * */ public class MultiVariable extends TemplateVariable { - private final Map fValueMap= new HashMap(); + private final Map fValueMap = new HashMap(); + private Object fSet; - private Object fDefaultKey= null; - + + private Object fDefaultKey = null; + public MultiVariable(String type, String defaultValue, int[] offsets) { super(type, defaultValue, offsets); fValueMap.put(fDefaultKey, new String[] { defaultValue }); - fSet= getDefaultValue(); + fSet = getDefaultValue(); } - + /** * Sets the values of this variable under a specific set. * - * @param set the set identifier for which the values are valid - * @param values the possible values of this variable + * @param set + * the set identifier for which the values are valid + * @param values + * the possible values of this variable */ public void setValues(Object set, String[] values) { Assert.isNotNull(set); Assert.isTrue(values.length > 0); fValueMap.put(set, values); if (fDefaultKey == null) { - fDefaultKey= set; - fSet= getDefaultValue(); + fDefaultKey = set; + fSet = getDefaultValue(); } } - - + /* * @see org.eclipse.jface.text.templates.TemplateVariable#setValues(java.lang.String[]) */ @@ -56,22 +58,22 @@ public class MultiVariable extends TemplateVariable { Assert.isNotNull(values); Assert.isTrue(values.length > 0); fValueMap.put(fDefaultKey, values); - fSet= getDefaultValue(); + fSet = getDefaultValue(); } } - - + /* * @see org.eclipse.jface.text.templates.TemplateVariable#getValues() */ public String[] getValues() { return (String[]) fValueMap.get(fDefaultKey); } - + /** * Returns the choices for the set identified by set. * - * @param set the set identifier + * @param set + * the set identifier * @return the choices for this variable and the given set, or * null if the set is not defined. */ @@ -85,9 +87,9 @@ public class MultiVariable extends TemplateVariable { public Object getSet() { return fSet; } - + public void setSet(Object set) { - fSet= set; + fSet = set; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/MultiVariableGuess.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/MultiVariableGuess.java index 4e2e4bd..1f0ebc2 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/MultiVariableGuess.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/MultiVariableGuess.java @@ -25,76 +25,106 @@ 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. + * 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 ICompletionProposal interface and extension. + * Implementation of the ICompletionProposal interface and + * extension. */ - class Proposal implements ICompletionProposal, ICompletionProposalExtension2 { - + 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 null. - * - * @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 + * 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 null. + * + * @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); + 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 + * 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) { + 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; + + fReplacementString = replacementString; + fReplacementOffset = replacementOffset; + fReplacementLength = replacementLength; + fCursorPosition = cursorPosition; + fImage = image; + fDisplayString = displayString; + fContextInformation = contextInformation; + fAdditionalProposalInfo = additionalProposalInfo; } /* @@ -102,12 +132,13 @@ public class MultiVariableGuess { */ public void apply(IDocument document) { try { - document.replace(fReplacementOffset, fReplacementLength, fReplacementString); + document.replace(fReplacementOffset, fReplacementLength, + fReplacementString); } catch (BadLocationException x) { // ignore } } - + /* * @see ICompletionProposal#getSelection(IDocument) */ @@ -144,32 +175,38 @@ public class MultiVariableGuess { public String getAdditionalProposalInfo() { return fAdditionalProposalInfo; } - + /* - * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#apply(org.eclipse.jface.text.ITextViewer, char, int, int) + * @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) { + 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) + * @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) + * @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) { + public boolean validate(IDocument document, int offset, + DocumentEvent event) { try { - String content= document.get(fReplacementOffset, fReplacementLength); + String content = document.get(fReplacementOffset, + fReplacementLength); if (content.startsWith(fReplacementString)) return true; } catch (BadLocationException e) { @@ -178,30 +215,32 @@ public class MultiVariableGuess { return false; } } - - private final List fSlaves= new ArrayList(); - + + private final List fSlaves = new ArrayList(); + private MultiVariable fMaster; /** * @param mv */ public MultiVariableGuess(MultiVariable mv) { - fMaster= mv; + fMaster = mv; } /** * @param variable * @return */ - public ICompletionProposal[] getProposals(MultiVariable variable, int offset, int length) { + public ICompletionProposal[] getProposals(MultiVariable variable, + int offset, int length) { if (variable.equals(fMaster)) { - String[] choices= variable.getValues(); - - ICompletionProposal[] ret= new ICompletionProposal[choices.length]; - for (int i= 0; i < ret.length; i++) { - ret[i]= new Proposal(choices[i], offset, length, offset + length) { - + String[] choices = variable.getValues(); + + ICompletionProposal[] ret = new ICompletionProposal[choices.length]; + for (int i = 0; i < ret.length; i++) { + ret[i] = new Proposal(choices[i], offset, length, offset + + length) { + /* * @see org.eclipse.jface.text.link.MultiVariableGuess.Proposal#apply(org.eclipse.jface.text.IDocument) */ @@ -209,14 +248,18 @@ public class MultiVariableGuess { super.apply(document); try { - Object old= fMaster.getSet(); + Object old = fMaster.getSet(); fMaster.setSet(fReplacementString); if (!fReplacementString.equals(old)) { - for (Iterator it= fSlaves.iterator(); it.hasNext();) { - VariablePosition pos= (VariablePosition) it.next(); - String[] values= pos.getVariable().getValues(fReplacementString); + for (Iterator it = fSlaves.iterator(); it + .hasNext();) { + VariablePosition pos = (VariablePosition) it + .next(); + String[] values = pos.getVariable() + .getValues(fReplacementString); if (values != null) - document.replace(pos.getOffset(), pos.getLength(), values[0]); + document.replace(pos.getOffset(), pos + .getLength(), values[0]); } } } catch (BadLocationException e) { @@ -226,21 +269,22 @@ public class MultiVariableGuess { } }; } - + return ret; - + } else { - - String[] choices= variable.getValues(fMaster.getSet()); - + + String[] choices = variable.getValues(fMaster.getSet()); + if (choices == null || choices.length < 2) return null; - - ICompletionProposal[] ret= new ICompletionProposal[choices.length]; - for (int i= 0; i < ret.length; i++) { - ret[i]= new Proposal(choices[i], offset, length, offset + length); + + ICompletionProposal[] ret = new ICompletionProposal[choices.length]; + for (int i = 0; i < ret.length; i++) { + ret[i] = new Proposal(choices[i], offset, length, offset + + length); } - + return ret; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/PositionBasedCompletionProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/PositionBasedCompletionProposal.java index 5e87151..b2396fb 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/PositionBasedCompletionProposal.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/PositionBasedCompletionProposal.java @@ -11,7 +11,6 @@ package net.sourceforge.phpdt.internal.ui.text.template.contentassist; - import org.eclipse.jface.text.Assert; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DocumentEvent; @@ -25,96 +24,124 @@ import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; - /** - * An enhanced implementation of the ICompletionProposal interface implementing all the extension interfaces. - * It uses a position to track its replacement offset and length. The position must be set up externally. + * An enhanced implementation of the ICompletionProposal + * 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 { - +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 null. - * - * @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 based on the provided information. The + * replacement string is considered being the display string too. All + * remaining fields are set to null. + * + * @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) { + * 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; - } - + + 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); + 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() */ @@ -123,39 +150,44 @@ public class PositionBasedCompletionProposal implements ICompletionProposal, ICo 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) + * @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) { + 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) + * @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) + * @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(), fReplacementPosition.getLength()); + String content = document.get(fReplacementPosition.getOffset(), + fReplacementPosition.getLength()); if (content.startsWith(fReplacementString)) return true; } catch (BadLocationException e) { @@ -165,14 +197,16 @@ public class PositionBasedCompletionProposal implements ICompletionProposal, ICo } /* - * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension#apply(org.eclipse.jface.text.IDocument, char, int) + * @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) + * @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 @@ -192,6 +226,5 @@ public class PositionBasedCompletionProposal implements ICompletionProposal, ICo public int getContextInformationPosition() { return fReplacementPosition.getOffset(); } - -} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateContentAssistMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateContentAssistMessages.java index 4a8cf15..c675e0a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateContentAssistMessages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateContentAssistMessages.java @@ -16,8 +16,11 @@ import java.util.ResourceBundle; class TemplateContentAssistMessages { - private static final String RESOURCE_BUNDLE= TemplateContentAssistMessages.class.getName(); - private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); + private static final String RESOURCE_BUNDLE = TemplateContentAssistMessages.class + .getName(); + + private static ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); private TemplateContentAssistMessages() { } @@ -29,20 +32,20 @@ class TemplateContentAssistMessages { return '!' + key + '!'; } } - + /** * Gets a string from the resource bundle and formats it with the argument * - * @param key the string used to get the bundle value, must not be null + * @param key + * the string used to get the bundle value, must not be null */ public static String getFormattedString(String key, Object arg) { return MessageFormat.format(getString(key), new Object[] { arg }); } - /** * Gets a string from the resource bundle and formats it with arguments - */ + */ public static String getFormattedString(String key, Object[] args) { return MessageFormat.format(getString(key), args); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateEngine.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateEngine.java index 13b4a92..64f1f12 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateEngine.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateEngine.java @@ -31,21 +31,23 @@ import org.eclipse.swt.graphics.Point; 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$ + 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(); + private ArrayList fProposals = new ArrayList(); /** - * Creates the template engine for a particular context type. - * See TemplateContext for supported context types. + * Creates the template engine for a particular context type. See + * TemplateContext for supported context types. */ public TemplateEngine(TemplateContextType contextType) { Assert.isNotNull(contextType); - fContextType= contextType; + fContextType = contextType; } /** @@ -59,70 +61,86 @@ public class TemplateEngine { * Returns the array of matching templates. */ public TemplateProposal[] getResults() { - return (TemplateProposal[]) fProposals.toArray(new TemplateProposal[fProposals.size()]); + return (TemplateProposal[]) fProposals + .toArray(new TemplateProposal[fProposals.size()]); } /** - * Inspects the context of the compilation unit around completionPosition - * 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 null) + * Inspects the context of the compilation unit around + * completionPosition 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 null) */ - public void complete(ITextViewer viewer, int completionPosition, ICompilationUnit compilationUnit) { - IDocument document= viewer.getDocument(); + public void complete(ITextViewer viewer, int completionPosition, + ICompilationUnit compilationUnit) { + IDocument document = viewer.getDocument(); if (!(fContextType instanceof CompilationUnitContextType)) return; - Point selection= viewer.getSelectedRange(); + Point selection = viewer.getSelectedRange(); // remember selected text - String selectedText= null; + String selectedText = null; if (selection.y != 0) { try { - selectedText= document.get(selection.x, selection.y); - } catch (BadLocationException e) {} + selectedText = document.get(selection.x, selection.y); + } catch (BadLocationException e) { + } } - - CompilationUnitContext context= ((CompilationUnitContextType) fContextType).createContext(document, completionPosition, selection.y, compilationUnit); + CompilationUnitContext context = ((CompilationUnitContextType) fContextType) + .createContext(document, completionPosition, selection.y, + compilationUnit); context.setVariable("selection", selectedText); //$NON-NLS-1$ - int start= context.getStart(); - int end= context.getEnd(); - IRegion region= new Region(start, end - start); + int start = context.getStart(); + int end = context.getEnd(); + IRegion region = new Region(start, end - start); - Template[] templates= PHPeclipsePlugin.getDefault().getTemplateStore().getTemplates(); + Template[] templates = PHPeclipsePlugin.getDefault().getTemplateStore() + .getTemplates(); if (selection.y == 0) { - for (int i= 0; i != templates.length; i++) + for (int i = 0; i != templates.length; i++) if (context.canEvaluate(templates[i])) - fProposals.add(new TemplateProposal(templates[i], context, region, PHPUiImages.get(PHPUiImages.IMG_OBJS_TEMPLATE))); + fProposals.add(new TemplateProposal(templates[i], context, + region, PHPUiImages + .get(PHPUiImages.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, PHPUiImages.get(PHPUiImages.IMG_OBJS_TEMPLATE))); + 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, PHPUiImages + .get(PHPUiImages.IMG_OBJS_TEMPLATE))); } } } } /** - * Returns true 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. - * + * Returns true 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 true if one or multiple lines are selected * @since 2.1 */ @@ -130,17 +148,18 @@ public class TemplateEngine { if (viewer == null) return false; - Point s= viewer.getSelectedRange(); + 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()); + 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/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateInformationControlCreator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateInformationControlCreator.java index a766686..522ac13 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateInformationControlCreator.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateInformationControlCreator.java @@ -19,22 +19,22 @@ import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.widgets.Shell; +final public class TemplateInformationControlCreator implements + IInformationControlCreator, IInformationControlCreatorExtension { -final public class TemplateInformationControlCreator implements IInformationControlCreator, IInformationControlCreatorExtension { - private SourceViewerInformationControl fControl; - - public TemplateInformationControlCreator() { + + public TemplateInformationControlCreator() { } - + /* * @see org.eclipse.jface.text.IInformationControlCreator#createInformationControl(org.eclipse.swt.widgets.Shell) */ public IInformationControl createInformationControl(Shell parent) { - fControl= new SourceViewerInformationControl(parent); + fControl = new SourceViewerInformationControl(parent); fControl.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { - fControl= null; + fControl = null; } }); return fControl; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateProposal.java index 57e4b4a..bb98859 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateProposal.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateProposal.java @@ -54,39 +54,51 @@ import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.texteditor.link.EditorLinkedModeUI; + /** * A template proposal. */ -public class TemplateProposal implements IPHPCompletionProposal, ICompletionProposalExtension2, ICompletionProposalExtension3 { +public class TemplateProposal implements IPHPCompletionProposal, + ICompletionProposalExtension2, ICompletionProposalExtension3 { 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 + * + * @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) { + 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; + fTemplate = template; + fContext = context; + fImage = image; + fRegion = region; - fDisplayString= null; + fDisplayString = null; if (context instanceof JavaContext) { switch (((JavaContext) context).getCharacterBeforeStart()) { @@ -95,13 +107,13 @@ public class TemplateProposal implements IPHPCompletionProposal, ICompletionProp case '\r': case '\n': case '\t': - fRelevance= 90; + fRelevance = 90; break; default: - fRelevance= 0; + fRelevance = 0; } } else { - fRelevance= 90; + fRelevance = 90; } } @@ -113,101 +125,114 @@ public class TemplateProposal implements IPHPCompletionProposal, ICompletionProp } /* - * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#apply(org.eclipse.jface.text.ITextViewer, char, int, int) + * @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) { + public void apply(ITextViewer viewer, char trigger, int stateMask, + int offset) { try { fContext.setReadOnly(false); TemplateBuffer templateBuffer; try { - templateBuffer= fContext.evaluate(fTemplate); + templateBuffer = fContext.evaluate(fTemplate); } catch (TemplateException e1) { - fSelectedRegion= fRegion; + fSelectedRegion = fRegion; return; } - int start= getReplaceOffset(); - int end= getReplaceEndOffset(); - end= Math.max(end, offset); + int start = getReplaceOffset(); + int end = getReplaceEndOffset(); + end = Math.max(end, offset); // insert template string - IDocument document= viewer.getDocument(); - String templateString= templateBuffer.getString(); + IDocument document = viewer.getDocument(); + String templateString = templateBuffer.getString(); document.replace(start, end - start, templateString); // translate positions - LinkedModeModel model= new LinkedModeModel(); - TemplateVariable[] variables= templateBuffer.getVariables(); + LinkedModeModel model = new LinkedModeModel(); + TemplateVariable[] variables = templateBuffer.getVariables(); - MultiVariableGuess guess= fContext instanceof CompilationUnitContext ? ((CompilationUnitContext) fContext).getMultiVariableGuess() : null; + MultiVariableGuess guess = fContext instanceof CompilationUnitContext ? ((CompilationUnitContext) fContext) + .getMultiVariableGuess() + : null; - boolean hasPositions= false; - for (int i= 0; i != variables.length; i++) { - TemplateVariable variable= variables[i]; + boolean hasPositions = false; + for (int i = 0; i != variables.length; i++) { + TemplateVariable variable = variables[i]; if (variable.isUnambiguous()) continue; - LinkedPositionGroup group= new LinkedPositionGroup(); + LinkedPositionGroup group = new LinkedPositionGroup(); - int[] offsets= variable.getOffsets(); - int length= variable.getLength(); + 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); + 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++) { + 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); + Position pos = new Position(offsets[0] + start, length); document.addPosition(getCategory(), pos); - proposals[j]= new PositionBasedCompletionProposal(values[j], pos, length); + proposals[j] = new PositionBasedCompletionProposal( + values[j], pos, length); } if (proposals.length > 1) - first= new ProposalPosition(document, offsets[0] + start, length, proposals); + first = new ProposalPosition(document, offsets[0] + + start, length, proposals); else - first= new LinkedPosition(document, offsets[0] + start, length); + first = new LinkedPosition(document, + offsets[0] + start, length); } - for (int j= 0; j != offsets.length; j++) + for (int j = 0; j != offsets.length; j++) if (j == 0) group.addPosition(first); else - group.addPosition(new LinkedPosition(document, offsets[j] + start, length)); + group.addPosition(new LinkedPosition(document, + offsets[j] + start, length)); model.addGroup(group); - hasPositions= true; + hasPositions = true; } if (hasPositions) { model.forceInstall(); - PHPEditor editor= getJavaEditor(); + PHPEditor editor = getJavaEditor(); if (editor != null) { - model.addLinkingListener(new EditorHighlightingSynchronizer(editor)); + model + .addLinkingListener(new EditorHighlightingSynchronizer( + editor)); } - LinkedModeUI ui= new EditorLinkedModeUI(model, viewer); - ui.setExitPosition(viewer, getCaretOffset(templateBuffer) + start, 0, Integer.MAX_VALUE); + LinkedModeUI ui = new EditorLinkedModeUI(model, viewer); + ui.setExitPosition(viewer, getCaretOffset(templateBuffer) + + start, 0, Integer.MAX_VALUE); ui.enter(); - fSelectedRegion= ui.getSelectedRegion(); + fSelectedRegion = ui.getSelectedRegion(); } else - fSelectedRegion= new Region(getCaretOffset(templateBuffer) + start, 0); + fSelectedRegion = new Region(getCaretOffset(templateBuffer) + + start, 0); } catch (BadLocationException e) { - PHPeclipsePlugin.log(e); + PHPeclipsePlugin.log(e); openErrorDialog(viewer.getTextWidget().getShell(), e); - fSelectedRegion= fRegion; + fSelectedRegion = fRegion; } catch (BadPositionCategoryException e) { - PHPeclipsePlugin.log(e); + PHPeclipsePlugin.log(e); openErrorDialog(viewer.getTextWidget().getShell(), e); - fSelectedRegion= fRegion; + fSelectedRegion = fRegion; } } @@ -215,11 +240,11 @@ public class TemplateProposal implements IPHPCompletionProposal, ICompletionProp /** * Returns the currently active java editor, or null if it * cannot be determined. - * - * @return the currently active java editor, or null + * + * @return the currently active java editor, or null */ private PHPEditor getJavaEditor() { - IEditorPart part= PHPeclipsePlugin.getActivePage().getActiveEditor(); + IEditorPart part = PHPeclipsePlugin.getActivePage().getActiveEditor(); if (part instanceof PHPEditor) return (PHPEditor) part; else @@ -229,17 +254,17 @@ public class TemplateProposal implements IPHPCompletionProposal, ICompletionProp /** * 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(); + DocumentTemplateContext docContext = (DocumentTemplateContext) fContext; + start = docContext.getStart(); } else { - start= fRegion.getOffset(); + start = fRegion.getOffset(); } return start; } @@ -247,31 +272,34 @@ public class TemplateProposal implements IPHPCompletionProposal, ICompletionProp /** * 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(); + DocumentTemplateContext docContext = (DocumentTemplateContext) fContext; + end = docContext.getEnd(); } else { - end= fRegion.getOffset() + fRegion.getLength(); + end = fRegion.getOffset() + fRegion.getLength(); } return end; } - private void ensurePositionCategoryInstalled(final IDocument document, LinkedModeModel model) { + private void ensurePositionCategoryInstalled(final IDocument document, + LinkedModeModel model) { if (!document.containsPositionCategory(getCategory())) { document.addPositionCategory(getCategory()); - final InclusivePositionUpdater updater= new InclusivePositionUpdater(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) + * @see org.eclipse.jface.text.link.ILinkedModeListener#left(org.eclipse.jface.text.link.LinkedModeModel, + * int) */ public void left(LinkedModeModel environment, int flags) { try { @@ -282,8 +310,11 @@ public class TemplateProposal implements IPHPCompletionProposal, ICompletionProp document.removePositionUpdater(updater); } - public void suspend(LinkedModeModel environment) {} - public void resume(LinkedModeModel environment, int flags) {} + public void suspend(LinkedModeModel environment) { + } + + public void resume(LinkedModeModel environment, int flags) { + } }); } } @@ -294,9 +325,9 @@ public class TemplateProposal implements IPHPCompletionProposal, ICompletionProp private int getCaretOffset(TemplateBuffer buffer) { - TemplateVariable[] variables= buffer.getVariables(); - for (int i= 0; i != variables.length; i++) { - TemplateVariable variable= variables[i]; + 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]; } @@ -308,26 +339,29 @@ public class TemplateProposal implements IPHPCompletionProposal, ICompletionProp * @see ICompletionProposal#getSelection(IDocument) */ public Point getSelection(IDocument document) { - return new Point(fSelectedRegion.getOffset(), fSelectedRegion.getLength()); + return new Point(fSelectedRegion.getOffset(), fSelectedRegion + .getLength()); } /* * @see ICompletionProposal#getAdditionalProposalInfo() */ public String getAdditionalProposalInfo() { - try { - fContext.setReadOnly(true); + try { + fContext.setReadOnly(true); TemplateBuffer templateBuffer; try { - templateBuffer= fContext.evaluate(fTemplate); + templateBuffer = fContext.evaluate(fTemplate); } catch (TemplateException e1) { return null; } return templateBuffer.getString(); - } catch (BadLocationException e) { - handleException(PHPeclipsePlugin.getActiveWorkbenchShell(), new CoreException(new Status(IStatus.ERROR, PHPeclipsePlugin.getPluginId(), IStatus.OK, "", e))); //$NON-NLS-1$ + } catch (BadLocationException e) { + handleException(PHPeclipsePlugin.getActiveWorkbenchShell(), + new CoreException(new Status(IStatus.ERROR, + PHPeclipsePlugin.getPluginId(), IStatus.OK, "", e))); //$NON-NLS-1$ return null; } } @@ -337,13 +371,15 @@ public class TemplateProposal implements IPHPCompletionProposal, ICompletionProp */ public String getDisplayString() { if (fDisplayString == null) { - fDisplayString= fTemplate.getName() + TemplateContentAssistMessages.getString("TemplateProposal.delimiter") + fTemplate.getDescription(); //$NON-NLS-1$ + fDisplayString = fTemplate.getName() + + TemplateContentAssistMessages + .getString("TemplateProposal.delimiter") + fTemplate.getDescription(); //$NON-NLS-1$ } return fDisplayString; } public void setDisplayString(String displayString) { - fDisplayString= displayString; + fDisplayString = displayString; } /* @@ -361,11 +397,13 @@ public class TemplateProposal implements IPHPCompletionProposal, ICompletionProp } private void openErrorDialog(Shell shell, Exception e) { - MessageDialog.openError(shell, TemplateContentAssistMessages.getString("TemplateEvaluator.error.title"), e.getMessage()); //$NON-NLS-1$ + MessageDialog.openError(shell, TemplateContentAssistMessages + .getString("TemplateEvaluator.error.title"), e.getMessage()); //$NON-NLS-1$ } private void handleException(Shell shell, CoreException e) { - ExceptionHandler.handle(e, shell, TemplateContentAssistMessages.getString("TemplateEvaluator.error.title"), null); //$NON-NLS-1$ + ExceptionHandler.handle(e, shell, TemplateContentAssistMessages + .getString("TemplateEvaluator.error.title"), null); //$NON-NLS-1$ } /* @@ -376,7 +414,7 @@ public class TemplateProposal implements IPHPCompletionProposal, ICompletionProp } public void setRelevance(int relevance) { - fRelevance= relevance; + fRelevance = relevance; } public Template getTemplate() { @@ -391,7 +429,8 @@ public class TemplateProposal implements IPHPCompletionProposal, ICompletionProp } /* - * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#selected(org.eclipse.jface.text.ITextViewer, boolean) + * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#selected(org.eclipse.jface.text.ITextViewer, + * boolean) */ public void selected(ITextViewer viewer, boolean smartToggle) { } @@ -403,13 +442,15 @@ public class TemplateProposal implements IPHPCompletionProposal, ICompletionProp } /* - * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#validate(org.eclipse.jface.text.IDocument, int, org.eclipse.jface.text.DocumentEvent) + * @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(); + int replaceOffset = getReplaceOffset(); if (offset >= replaceOffset) { - String content= document.get(replaceOffset, offset - replaceOffset); + String content = document.get(replaceOffset, offset + - replaceOffset); return fTemplate.getName().startsWith(content); } } catch (BadLocationException e) { @@ -421,7 +462,8 @@ public class TemplateProposal implements IPHPCompletionProposal, ICompletionProp /* * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension3#getReplacementString() */ - public CharSequence getPrefixCompletionText(IDocument document, int completionOffset) { + public CharSequence getPrefixCompletionText(IDocument document, + int completionOffset) { return fTemplate.getName(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/VariablePosition.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/VariablePosition.java index 5edace0..6bf87f2 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/VariablePosition.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/VariablePosition.java @@ -16,28 +16,30 @@ 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, + 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) { + + 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; + fVariable = variable; + fGuess = guess; } - - + /* * @see org.eclipse.jface.text.link.ProposalPosition#equals(java.lang.Object) */ @@ -47,14 +49,14 @@ public class VariablePosition extends ProposalPosition { } 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() */ @@ -68,5 +70,5 @@ public class VariablePosition extends ProposalPosition { public MultiVariable getVariable() { return fVariable; } - + } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplatePreferencesMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplatePreferencesMessages.java index cfdf5de..29a9740 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplatePreferencesMessages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplatePreferencesMessages.java @@ -16,8 +16,11 @@ import java.util.ResourceBundle; class TemplatePreferencesMessages { - private static final String RESOURCE_BUNDLE= TemplatePreferencesMessages.class.getName(); - private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); + private static final String RESOURCE_BUNDLE = TemplatePreferencesMessages.class + .getName(); + + private static ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); private TemplatePreferencesMessages() { } @@ -29,20 +32,20 @@ class TemplatePreferencesMessages { return '!' + key + '!'; } } - + /** * Gets a string from the resource bundle and formats it with the argument * - * @param key the string used to get the bundle value, must not be null + * @param key + * the string used to get the bundle value, must not be null */ public static String getFormattedString(String key, Object arg) { return MessageFormat.format(getString(key), new Object[] { arg }); } - /** * Gets a string from the resource bundle and formats it with arguments - */ + */ public static String getFormattedString(String key, Object[] args) { return MessageFormat.format(getString(key), args); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplateVariableProcessor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplateVariableProcessor.java index 1f6008f..ea9665c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplateVariableProcessor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplateVariableProcessor.java @@ -24,16 +24,15 @@ 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 { - -public class TemplateVariableProcessor implements IContentAssistProcessor { - - private static Comparator fgTemplateVariableProposalComparator= new Comparator() { + 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()); + TemplateVariableProposal proposal0 = (TemplateVariableProposal) arg0; + TemplateVariableProposal proposal1 = (TemplateVariableProposal) arg1; + + return proposal0.getDisplayString().compareTo( + proposal1.getDisplayString()); } public boolean equals(Object arg0) { @@ -41,77 +40,81 @@ public class TemplateVariableProcessor implements IContentAssistProcessor { } }; - /** the context type */ private TemplateContextType fContextType; - + /** * Sets the context type. */ public void setContextType(TemplateContextType contextType) { - fContextType= contextType; + fContextType = contextType; } - + /** * Gets the context type. */ public TemplateContextType getContextType() { - return fContextType; - } - + return fContextType; + } + /* * @see IContentAssistProcessor#computeCompletionProposals(ITextViewer, int) */ - public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) { + 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; + List proposals = new ArrayList(); + + String text = viewer.getDocument().get(); + int start = getStart(text, documentOffset); + int end = documentOffset; - String string= text.substring(start, end); - String prefix= (string.length() >= 2) - ? string.substring(2) - : null; + String string = text.substring(start, end); + String prefix = (string.length() >= 2) ? string.substring(2) : null; - int offset= start; - int length= end - start; + int offset = start; + int length = end - start; - for (Iterator iterator= fContextType.resolvers(); iterator.hasNext(); ) { - TemplateVariableResolver variable= (TemplateVariableResolver) iterator.next(); + for (Iterator iterator = fContextType.resolvers(); iterator.hasNext();) { + TemplateVariableResolver variable = (TemplateVariableResolver) iterator + .next(); if (prefix == null || variable.getType().startsWith(prefix)) - proposals.add(new TemplateVariableProposal(variable, offset, length, viewer)); + proposals.add(new TemplateVariableProposal(variable, offset, + length, viewer)); } Collections.sort(proposals, fgTemplateVariableProposalComparator); - return (ICompletionProposal[]) proposals.toArray(new ICompletionProposal[proposals.size()]); + 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; + int start = end; if (start >= 1 && string.charAt(start - 1) == '$') return start - 1; - - while ((start != 0) && Character.isUnicodeIdentifierPart(string.charAt(start - 1))) + + while ((start != 0) + && Character.isUnicodeIdentifierPart(string.charAt(start - 1))) start--; - if (start >= 2 && string.charAt(start - 1) == '{' && string.charAt(start - 2) == '$') + 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) { + public IContextInformation[] computeContextInformation(ITextViewer viewer, + int documentOffset) { return null; } @@ -119,7 +122,7 @@ public class TemplateVariableProcessor implements IContentAssistProcessor { * @see IContentAssistProcessor#getCompletionProposalAutoActivationCharacters() */ public char[] getCompletionProposalAutoActivationCharacters() { - return new char[] {'$'}; + return new char[] { '$' }; } /* @@ -144,4 +147,3 @@ public class TemplateVariableProcessor implements IContentAssistProcessor { } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplateVariableProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplateVariableProposal.java index 5550d19..13ec454 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplateVariableProposal.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplateVariableProposal.java @@ -29,42 +29,54 @@ import org.eclipse.swt.widgets.Shell; public class TemplateVariableProposal implements ICompletionProposal { private TemplateVariableResolver fVariable; + private int fOffset; - private int fLength; + + private int fLength; + private ITextViewer fViewer; - + private Point fSelection; /** * 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 variable + * the template variable + * @param offset + * the offset to replace + * @param length + * the length to replace + * @param viewer + * the viewer */ - public TemplateVariableProposal(TemplateVariableResolver variable, int offset, int length, ITextViewer viewer) { - fVariable= variable; - fOffset= offset; - fLength= length; - fViewer= viewer; + public TemplateVariableProposal(TemplateVariableResolver variable, + int offset, int length, ITextViewer viewer) { + fVariable = variable; + fOffset = offset; + fLength = length; + fViewer = viewer; } - + /* * @see ICompletionProposal#apply(IDocument) */ public void apply(IDocument document) { try { - String variable= fVariable.getType().equals("dollar") ? "$$" : "${" + fVariable.getType() + '}'; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + String variable = fVariable.getType().equals("dollar") ? "$$" : "${" + fVariable.getType() + '}'; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ document.replace(fOffset, fLength, variable); - fSelection= new Point(fOffset + variable.length(), 0); + fSelection = new Point(fOffset + variable.length(), 0); } catch (BadLocationException e) { PHPeclipsePlugin.log(e); - Shell shell= fViewer.getTextWidget().getShell(); - MessageDialog.openError(shell, TemplatePreferencesMessages.getString("TemplateVariableProposal.error.title"), e.getMessage()); //$NON-NLS-1$ + Shell shell = fViewer.getTextWidget().getShell(); + MessageDialog + .openError( + shell, + TemplatePreferencesMessages + .getString("TemplateVariableProposal.error.title"), e.getMessage()); //$NON-NLS-1$ } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/DirectorySelector.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/DirectorySelector.java index 91c24a3..8a686f7 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/DirectorySelector.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/DirectorySelector.java @@ -19,13 +19,13 @@ public class DirectorySelector extends ResourceSelector { File path = new File(currentWorkingDir); if (path.exists()) { dialog.setFilterPath(currentWorkingDir); - } + } } - + String selectedDirectory = dialog.open(); if (selectedDirectory != null) { textField.setText(selectedDirectory); - } + } } protected String validateResourceSelection() { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/ExceptionHandler.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/ExceptionHandler.java index fcf0d66..bdae82b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/ExceptionHandler.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/ExceptionHandler.java @@ -12,35 +12,39 @@ import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Shell; - public class ExceptionHandler { - private static ExceptionHandler fgInstance= new ExceptionHandler(); - + private static ExceptionHandler fgInstance = new ExceptionHandler(); + public static void log(Throwable t, String message) { - PHPeclipsePlugin.getDefault().getLog().log(new Status(IStatus.ERROR, PHPeclipsePlugin.PLUGIN_ID, - IStatus.ERROR, message, t)); + PHPeclipsePlugin.getDefault().getLog().log( + new Status(IStatus.ERROR, PHPeclipsePlugin.PLUGIN_ID, + IStatus.ERROR, message, t)); } - + public static void handle(CoreException e, String title, String message) { handle(e, PHPeclipsePlugin.getActiveWorkbenchShell(), title, message); } - - public static void handle(CoreException e, Shell parent, String title, String message) { + + public static void handle(CoreException e, Shell parent, String title, + String message) { fgInstance.perform(e, parent, title, message); } - - public static void handle(InvocationTargetException e, String title, String message) { + + public static void handle(InvocationTargetException e, String title, + String message) { handle(e, PHPeclipsePlugin.getActiveWorkbenchShell(), title, message); } - - public static void handle(InvocationTargetException e, Shell parent, String title, String message) { + + public static void handle(InvocationTargetException e, Shell parent, + String title, String message) { fgInstance.perform(e, parent, title, message); } - protected void perform(CoreException e, Shell shell, String title, String message) { + protected void perform(CoreException e, Shell shell, String title, + String message) { PHPeclipsePlugin.log(e); - IStatus status= e.getStatus(); + IStatus status = e.getStatus(); if (status != null) { ErrorDialog.openError(shell, title, message, status); } else { @@ -48,30 +52,34 @@ public class ExceptionHandler { } } - protected void perform(InvocationTargetException e, Shell shell, String title, String message) { - Throwable target= e.getTargetException(); + protected void perform(InvocationTargetException e, Shell shell, + String title, String message) { + Throwable target = e.getTargetException(); if (target instanceof CoreException) { - perform((CoreException)target, shell, title, message); + perform((CoreException) target, shell, title, message); } else { PHPeclipsePlugin.log(e); if (e.getMessage() != null && e.getMessage().length() > 0) { displayMessageDialog(e, e.getMessage(), shell, title, message); } else { - displayMessageDialog(e, target.getMessage(), shell, title, message); + displayMessageDialog(e, target.getMessage(), shell, title, + message); } } } - private void displayMessageDialog(Throwable t, String exceptionMessage, Shell shell, String title, String message) { - StringWriter msg= new StringWriter(); + private void displayMessageDialog(Throwable t, String exceptionMessage, + Shell shell, String title, String message) { + StringWriter msg = new StringWriter(); if (message != null) { msg.write(message); msg.write("\n\n"); } if (exceptionMessage == null || exceptionMessage.length() == 0) - msg.write(PHPUIMessages.getString("ExceptionDialog.seeErrorLogMessage")); + msg.write(PHPUIMessages + .getString("ExceptionDialog.seeErrorLogMessage")); else msg.write(exceptionMessage); - MessageDialog.openError(shell, title, msg.toString()); - } + MessageDialog.openError(shell, title, msg.toString()); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/FilteredList.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/FilteredList.java index 892c2df..65b17f6 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/FilteredList.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/FilteredList.java @@ -20,10 +20,9 @@ import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableItem; /** - * A composite widget which holds a list of elements for user selection. - * The elements are sorted alphabetically. - * Optionally, the elements can be filtered and duplicate entries can - * be hidden (folding). + * A composite widget which holds a list of elements for user selection. The + * elements are sorted alphabetically. Optionally, the elements can be filtered + * and duplicate entries can be hidden (folding). */ public class FilteredList extends Composite { @@ -31,90 +30,110 @@ public class FilteredList extends Composite { /** * Sets the filter. * - * @param pattern the filter pattern. - * @param ignoreCase a flag indicating whether pattern matching is case insensitive or not. - * @param ignoreWildCards a flag indicating whether wildcard characters are interpreted or not. + * @param pattern + * the filter pattern. + * @param ignoreCase + * a flag indicating whether pattern matching is case + * insensitive or not. + * @param ignoreWildCards + * a flag indicating whether wildcard characters are + * interpreted or not. */ - void setFilter(String pattern, boolean ignoreCase, boolean ignoreWildCards); + void setFilter(String pattern, boolean ignoreCase, + boolean ignoreWildCards); /** - * Returns true if the object matches the pattern, false otherwise. - * setFilter() must have been called at least once prior to a call to this method. + * Returns true if the object matches the pattern, + * false otherwise. setFilter() must have + * been called at least once prior to a call to this method. */ - boolean match(Object element); + boolean match(Object element); } - + private class DefaultFilterMatcher implements FilterMatcher { private StringMatcher fMatcher; - - public void setFilter(String pattern, boolean ignoreCase, boolean ignoreWildCards) { - fMatcher= new StringMatcher(pattern + '*', ignoreCase, ignoreWildCards); + + public void setFilter(String pattern, boolean ignoreCase, + boolean ignoreWildCards) { + fMatcher = new StringMatcher(pattern + '*', ignoreCase, + ignoreWildCards); } - + public boolean match(Object element) { return fMatcher.match(fRenderer.getText(element)); - } + } } private Table fList; + private ILabelProvider fRenderer; - private boolean fMatchEmtpyString= true; + + private boolean fMatchEmtpyString = true; + private boolean fIgnoreCase; + private boolean fAllowDuplicates; - private String fFilter= ""; //$NON-NLS-1$ + + private String fFilter = ""; //$NON-NLS-1$ + private TwoArrayQuickSorter fSorter; - - private Object[] fElements= new Object[0]; + + private Object[] fElements = new Object[0]; + private Label[] fLabels; - private Vector fImages= new Vector(); + + private Vector fImages = new Vector(); private int[] fFoldedIndices; + private int fFoldedCount; - + private int[] fFilteredIndices; + private int fFilteredCount; - - private FilterMatcher fFilterMatcher= new DefaultFilterMatcher(); + + private FilterMatcher fFilterMatcher = new DefaultFilterMatcher(); + private Comparator fComparator; private static class Label { public final String string; + public final Image image; public Label(String string, Image image) { - this.string= string; - this.image= image; + this.string = string; + this.image = image; } - + public boolean equals(Label label) { if (label == null) return false; - - return - string.equals(label.string) && - image.equals(label.image); + + return string.equals(label.string) && image.equals(label.image); } } private final class LabelComparator implements Comparator { private boolean fIgnoreCase; - + LabelComparator(boolean ignoreCase) { - fIgnoreCase= ignoreCase; + fIgnoreCase = ignoreCase; } - + public int compare(Object left, Object right) { - Label leftLabel= (Label) left; - Label rightLabel= (Label) right; + Label leftLabel = (Label) left; + Label rightLabel = (Label) right; int value; - + if (fComparator == null) { - value= fIgnoreCase - ? leftLabel.string.compareToIgnoreCase(rightLabel.string) - : leftLabel.string.compareTo(rightLabel.string); + value = fIgnoreCase ? leftLabel.string + .compareToIgnoreCase(rightLabel.string) + : leftLabel.string.compareTo(rightLabel.string); } else { - value= fComparator.compare(leftLabel.string, rightLabel.string); + value = fComparator + .compare(leftLabel.string, rightLabel.string); } if (value != 0) @@ -124,73 +143,82 @@ public class FilteredList extends Composite { if (leftLabel.image == null) { return (rightLabel.image == null) ? 0 : -1; } else if (rightLabel.image == null) { - return +1; + return +1; } else { - return - fImages.indexOf(leftLabel.image) - - fImages.indexOf(rightLabel.image); + return fImages.indexOf(leftLabel.image) + - fImages.indexOf(rightLabel.image); } } - - } - + + } + /** * Constructs a new instance of a filtered list. - * @param parent the parent composite. - * @param style the widget style. - * @param renderer the label renderer. - * @param ignoreCase specifies whether sorting and folding is case sensitive. - * @param allowDuplicates specifies whether folding of duplicates is desired. - * @param matchEmptyString specifies whether empty filter strings should filter everything or nothing. + * + * @param parent + * the parent composite. + * @param style + * the widget style. + * @param renderer + * the label renderer. + * @param ignoreCase + * specifies whether sorting and folding is case sensitive. + * @param allowDuplicates + * specifies whether folding of duplicates is desired. + * @param matchEmptyString + * specifies whether empty filter strings should filter + * everything or nothing. */ public FilteredList(Composite parent, int style, ILabelProvider renderer, - boolean ignoreCase, boolean allowDuplicates, boolean matchEmptyString) - { + boolean ignoreCase, boolean allowDuplicates, + boolean matchEmptyString) { super(parent, SWT.NONE); - GridLayout layout= new GridLayout(); - layout.marginHeight= 0; - layout.marginWidth= 0; + GridLayout layout = new GridLayout(); + layout.marginHeight = 0; + layout.marginWidth = 0; setLayout(layout); - - fList= new Table(this, style); + + fList = new Table(this, style); fList.setLayoutData(new GridData(GridData.FILL_BOTH)); fList.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { fRenderer.dispose(); } }); - - fRenderer= renderer; - fIgnoreCase= ignoreCase; - fSorter= new TwoArrayQuickSorter(new LabelComparator(ignoreCase)); - fAllowDuplicates= allowDuplicates; - fMatchEmtpyString= matchEmptyString; + + fRenderer = renderer; + fIgnoreCase = ignoreCase; + fSorter = new TwoArrayQuickSorter(new LabelComparator(ignoreCase)); + fAllowDuplicates = allowDuplicates; + fMatchEmtpyString = matchEmptyString; } /** * Sets the list of elements. - * @param elements the elements to be shown in the list. + * + * @param elements + * the elements to be shown in the list. */ public void setElements(Object[] elements) { if (elements == null) { - fElements= new Object[0]; + fElements = new Object[0]; } else { // copy list for sorting - fElements= new Object[elements.length]; + fElements = new Object[elements.length]; System.arraycopy(elements, 0, fElements, 0, elements.length); } - - int length= fElements.length; - - // fill labels - fLabels= new Label[length]; - Set imageSet= new HashSet(); - for (int i= 0; i != length; i++) { - String text= fRenderer.getText(fElements[i]); - Image image= fRenderer.getImage(fElements[i]); - - fLabels[i]= new Label(text, image); + + int length = fElements.length; + + // fill labels + fLabels = new Label[length]; + Set imageSet = new HashSet(); + for (int i = 0; i != length; i++) { + String text = fRenderer.getText(fElements[i]); + Image image = fRenderer.getImage(fElements[i]); + + fLabels[i] = new Label(text, image); imageSet.add(image); } fImages.clear(); @@ -198,18 +226,20 @@ public class FilteredList extends Composite { fSorter.sort(fLabels, fElements); - fFilteredIndices= new int[length]; - fFilteredCount= filter(); - - fFoldedIndices= new int[length]; - fFoldedCount= fold(); + fFilteredIndices = new int[length]; + fFilteredCount = filter(); + + fFoldedIndices = new int[length]; + fFoldedCount = fold(); updateList(); } /** * Tests if the list (before folding and filtering) is empty. - * @return returns true if the list is empty, false otherwise. + * + * @return returns true if the list is empty, + * false otherwise. */ public boolean isEmpty() { return (fElements == null) || (fElements.length == 0); @@ -220,129 +250,144 @@ public class FilteredList extends Composite { */ public void setFilterMatcher(FilterMatcher filterMatcher) { Assert.isNotNull(filterMatcher); - fFilterMatcher= filterMatcher; + fFilterMatcher = filterMatcher; } - + /** * Sets a custom comparator for sorting the list. */ public void setComparator(Comparator comparator) { - Assert.isNotNull(comparator); - fComparator= comparator; + Assert.isNotNull(comparator); + fComparator = comparator; } - /** - * Adds a selection listener to the list. - * @param listener the selection listener to be added. - */ + /** + * Adds a selection listener to the list. + * + * @param listener + * the selection listener to be added. + */ public void addSelectionListener(SelectionListener listener) { fList.addSelectionListener(listener); } - /** - * Removes a selection listener from the list. - * @param listener the selection listener to be removed. - */ + /** + * Removes a selection listener from the list. + * + * @param listener + * the selection listener to be removed. + */ public void removeSelectionListener(SelectionListener listener) { fList.removeSelectionListener(listener); - } + } - /** - * Sets the selection of the list. - * @param selection an array of indices specifying the selection. - */ + /** + * Sets the selection of the list. + * + * @param selection + * an array of indices specifying the selection. + */ public void setSelection(int[] selection) { fList.setSelection(selection); } - + /** * Returns the selection of the list. + * * @return returns an array of indices specifying the current selection. */ public int[] getSelectionIndices() { return fList.getSelectionIndices(); } - + /** - * Returns the selection of the list. - * This is a convenience function for getSelectionIndices(). + * Returns the selection of the list. This is a convenience function for + * getSelectionIndices(). + * * @return returns the index of the selection, -1 for no selection. */ public int getSelectionIndex() { - return fList.getSelectionIndex(); + return fList.getSelectionIndex(); } - + /** * Sets the selection of the list. - * @param elements the array of elements to be selected. + * + * @param elements + * the array of elements to be selected. */ public void setSelection(Object[] elements) { if ((elements == null) || (fElements == null)) - return; - + return; + // fill indices - int[] indices= new int[elements.length]; - for (int i= 0; i != elements.length; i++) { - int j; - for (j= 0; j != fFoldedCount; j++) { - int max= (j == fFoldedCount - 1) - ? fFilteredCount - : fFoldedIndices[j + 1]; - - int l; - for (l= fFoldedIndices[j]; l != max; l++) { + int[] indices = new int[elements.length]; + for (int i = 0; i != elements.length; i++) { + int j; + for (j = 0; j != fFoldedCount; j++) { + int max = (j == fFoldedCount - 1) ? fFilteredCount + : fFoldedIndices[j + 1]; + + int l; + for (l = fFoldedIndices[j]; l != max; l++) { // found matching element? if (fElements[fFilteredIndices[l]].equals(elements[i])) { - indices[i]= j; - break; + indices[i] = j; + break; } } - + if (l != max) break; } - + // not found if (j == fFoldedCount) indices[i] = 0; } - + fList.setSelection(indices); } - + /** * Returns an array of the selected elements. The type of the elements * returned in the list are the same as the ones passed with - * setElements. The array does not contain the rendered strings. + * setElements. The array does not contain the rendered + * strings. + * * @return returns the array of selected elements. */ public Object[] getSelection() { if (fList.isDisposed() || (fList.getSelectionCount() == 0)) return new Object[0]; - int[] indices= fList.getSelectionIndices(); - Object[] elements= new Object[indices.length]; - - for (int i= 0; i != indices.length; i++) - elements[i]= fElements[fFilteredIndices[fFoldedIndices[indices[i]]]]; - - return elements; + int[] indices = fList.getSelectionIndices(); + Object[] elements = new Object[indices.length]; + + for (int i = 0; i != indices.length; i++) + elements[i] = fElements[fFilteredIndices[fFoldedIndices[indices[i]]]]; + + return elements; } /** - * Sets the filter pattern. Current only prefix filter patterns are supported. - * @param filter the filter pattern. + * Sets the filter pattern. Current only prefix filter patterns are + * supported. + * + * @param filter + * the filter pattern. */ public void setFilter(String filter) { - fFilter= (filter == null) ? "" : filter; //$NON-NLS-1$ + fFilter = (filter == null) ? "" : filter; //$NON-NLS-1$ - fFilteredCount= filter(); - fFoldedCount= fold(); + fFilteredCount = filter(); + fFoldedCount = fold(); updateList(); } - + /** * Returns the filter pattern. + * * @return returns the filter pattern. */ public String getFilter() { @@ -351,48 +396,50 @@ public class FilteredList extends Composite { /** * Returns all elements which are folded together to one entry in the list. - * @param index the index selecting the entry in the list. - * @return returns an array of elements folded together, null if index is out of range. + * + * @param index + * the index selecting the entry in the list. + * @return returns an array of elements folded together, null + * if index is out of range. */ public Object[] getFoldedElements(int index) { if ((index < 0) || (index >= fFoldedCount)) return null; - - int start= fFoldedIndices[index]; - int count= (index == fFoldedCount - 1) - ? fFilteredCount - start - : fFoldedIndices[index + 1] - start; - - Object[] elements= new Object[count]; - for (int i= 0; i != count; i++) - elements[i]= fElements[fFilteredIndices[start + i]]; - + + int start = fFoldedIndices[index]; + int count = (index == fFoldedCount - 1) ? fFilteredCount - start + : fFoldedIndices[index + 1] - start; + + Object[] elements = new Object[count]; + for (int i = 0; i != count; i++) + elements[i] = fElements[fFilteredIndices[start + i]]; + return elements; } - /* - * Folds duplicate entries. Two elements are considered as a pair of - * duplicates if they coiincide in the rendered string and image. - * @return returns the number of elements after folding. - */ + /* + * Folds duplicate entries. Two elements are considered as a pair of + * duplicates if they coiincide in the rendered string and image. @return + * returns the number of elements after folding. + */ private int fold() { if (fAllowDuplicates) { - for (int i= 0; i != fFilteredCount; i++) - fFoldedIndices[i]= i; // identity mapping + for (int i = 0; i != fFilteredCount; i++) + fFoldedIndices[i] = i; // identity mapping + + return fFilteredCount; - return fFilteredCount; - } else { - int k= 0; - Label last= null; - for (int i= 0; i != fFilteredCount; i++) { - int j= fFilteredIndices[i]; - - Label current= fLabels[j]; - if (! current.equals(last)) { - fFoldedIndices[k]= i; + int k = 0; + Label last = null; + for (int i = 0; i != fFilteredCount; i++) { + int j = fFilteredIndices[i]; + + Label current = fLabels[j]; + if (!current.equals(last)) { + fFoldedIndices[k] = i; k++; - last= current; + last = current; } } return k; @@ -400,47 +447,48 @@ public class FilteredList extends Composite { } /* - * Filters the list with the filter pattern. - * @return returns the number of elements after filtering. + * Filters the list with the filter pattern. @return returns the number of + * elements after filtering. */ private int filter() { - if (((fFilter == null) || (fFilter.length() == 0)) && !fMatchEmtpyString) + if (((fFilter == null) || (fFilter.length() == 0)) + && !fMatchEmtpyString) return 0; - + fFilterMatcher.setFilter(fFilter.trim(), fIgnoreCase, false); - int k= 0; - for (int i= 0; i != fElements.length; i++) { + int k = 0; + for (int i = 0; i != fElements.length; i++) { if (fFilterMatcher.match(fElements[i])) - fFilteredIndices[k++]= i; - } - + fFilteredIndices[k++] = i; + } + return k; - } + } /* * Updates the list widget. - */ + */ private void updateList() { if (fList.isDisposed()) return; - + fList.setRedraw(false); - + // resize table - int itemCount= fList.getItemCount(); + int itemCount = fList.getItemCount(); if (fFoldedCount < itemCount) fList.remove(0, itemCount - fFoldedCount - 1); else if (fFoldedCount > itemCount) - for (int i= 0; i != fFoldedCount - itemCount; i++) + for (int i = 0; i != fFoldedCount - itemCount; i++) new TableItem(fList, SWT.NONE); // fill table - TableItem[] items= fList.getItems(); - for (int i= 0; i != fFoldedCount; i++) { - TableItem item= items[i]; - Label label= fLabels[fFilteredIndices[fFoldedIndices[i]]]; - + TableItem[] items = fList.getItems(); + for (int i = 0; i != fFoldedCount; i++) { + TableItem item = items[i]; + Label label = fLabels[fFilteredIndices[fFoldedIndices[i]]]; + item.setText(label.string); item.setImage(label.image); } @@ -448,9 +496,9 @@ public class FilteredList extends Composite { // select first item if any if (fList.getItemCount() > 0) fList.setSelection(0); - - fList.setRedraw(true); + + fList.setRedraw(true); fList.notifyListeners(SWT.Selection, new Event()); } - + } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPElementVisitor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPElementVisitor.java index 347ff8c..275bd57 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPElementVisitor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPElementVisitor.java @@ -17,24 +17,24 @@ public class PHPElementVisitor implements IResourceVisitor { public boolean visit(IResource resource) throws CoreException { switch (resource.getType()) { - case IResource.PROJECT : - return true; + case IResource.PROJECT: + return true; - case IResource.FOLDER : - return true; + case IResource.FOLDER: + return true; - case IResource.FILE : - IFile fileResource = (IFile) resource; - if ( PHPFileUtil.isPHPFile(fileResource) ) { - phpFiles.add(fileResource); - return true; - } + case IResource.FILE: + IFile fileResource = (IFile) resource; + if (PHPFileUtil.isPHPFile(fileResource)) { + phpFiles.add(fileResource); + return true; + } - default : - return false; + default: + return false; } } - + public Object[] getCollectedPHPFiles() { return phpFiles.toArray(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPFileSelector.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPFileSelector.java index 41fce7c..bb920a7 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPFileSelector.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPFileSelector.java @@ -16,91 +16,97 @@ import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.model.IWorkbenchAdapter; public class PHPFileSelector extends ResourceSelector { - static class FileLabelProvider extends LabelProvider { - /** - * Returns the implementation of IWorkbenchAdapter for the given object. - * - * @param o - * the object to look up. - * @return IWorkbenchAdapter or null if the adapter is not defined or the object is not adaptable. - */ - protected final IWorkbenchAdapter getAdapter(Object o) { - if (!(o instanceof IAdaptable)) { - return null; - } - return (IWorkbenchAdapter) ((IAdaptable) o).getAdapter(IWorkbenchAdapter.class); - } + static class FileLabelProvider extends LabelProvider { + /** + * Returns the implementation of IWorkbenchAdapter for the given object. + * + * @param o + * the object to look up. + * @return IWorkbenchAdapter or null if the adapter is + * not defined or the object is not adaptable. + */ + protected final IWorkbenchAdapter getAdapter(Object o) { + if (!(o instanceof IAdaptable)) { + return null; + } + return (IWorkbenchAdapter) ((IAdaptable) o) + .getAdapter(IWorkbenchAdapter.class); + } - /* - * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object) - */ - public String getText(Object element) { - if (element instanceof IFile) { - // query the element for its label - IWorkbenchAdapter adapter = getAdapter(element); - if (adapter == null) { - return ""; //$NON-NLS-1$ - } - String filename = adapter.getLabel(element); - IPath path = ((IFile) element).getFullPath(); - String filePathname = path != null ? path.toString() : ""; //$NON-NLS-1$ - return filename + " (" + filePathname + ")"; - } - return super.getText(element); - } - } + /* + * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object) + */ + public String getText(Object element) { + if (element instanceof IFile) { + // query the element for its label + IWorkbenchAdapter adapter = getAdapter(element); + if (adapter == null) { + return ""; //$NON-NLS-1$ + } + String filename = adapter.getLabel(element); + IPath path = ((IFile) element).getFullPath(); + String filePathname = path != null ? path.toString() : ""; //$NON-NLS-1$ + return filename + " (" + filePathname + ")"; + } + return super.getText(element); + } + } - protected PHPProjectSelector phpProjectSelector; + protected PHPProjectSelector phpProjectSelector; - public PHPFileSelector(Composite parent, PHPProjectSelector aProjectSelector) { - super(parent); - Assert.isNotNull(aProjectSelector); - phpProjectSelector = aProjectSelector; + public PHPFileSelector(Composite parent, PHPProjectSelector aProjectSelector) { + super(parent); + Assert.isNotNull(aProjectSelector); + phpProjectSelector = aProjectSelector; - browseDialogTitle = "File Selection"; - } + browseDialogTitle = "File Selection"; + } - protected Object[] getPHPFiles() { - IProject phpProject = phpProjectSelector.getSelection(); - if (phpProject == null) - return new Object[0]; + protected Object[] getPHPFiles() { + IProject phpProject = phpProjectSelector.getSelection(); + if (phpProject == null) + return new Object[0]; - PHPElementVisitor visitor = new PHPElementVisitor(); - try { - phpProject.accept(visitor); - } catch (CoreException e) { - PHPeclipsePlugin.log(e); - } - return visitor.getCollectedPHPFiles(); - } + PHPElementVisitor visitor = new PHPElementVisitor(); + try { + phpProject.accept(visitor); + } catch (CoreException e) { + PHPeclipsePlugin.log(e); + } + return visitor.getCollectedPHPFiles(); + } - public IFile getSelection() { - String fileName = getSelectionText(); - if (fileName != null && !fileName.equals("")) { - IPath filePath = new Path(fileName); - IProject project = phpProjectSelector.getSelection(); - if (project != null && project.exists(filePath)) - return project.getFile(filePath); - } + public IFile getSelection() { + String fileName = getSelectionText(); + if (fileName != null && !fileName.equals("")) { + IPath filePath = new Path(fileName); + IProject project = phpProjectSelector.getSelection(); + if (project != null && project.exists(filePath)) + return project.getFile(filePath); + } - return null; - } + return null; + } - protected void handleBrowseSelected() { -// ElementListSelectionDialog dialog = new ElementListSelectionDialog(getShell(), new WorkbenchLabelProvider()); - ElementListSelectionDialog dialog = new ElementListSelectionDialog(getShell(), new FileLabelProvider()); + protected void handleBrowseSelected() { + // ElementListSelectionDialog dialog = new + // ElementListSelectionDialog(getShell(), new WorkbenchLabelProvider()); + ElementListSelectionDialog dialog = new ElementListSelectionDialog( + getShell(), new FileLabelProvider()); - dialog.setTitle(browseDialogTitle); - dialog.setMessage(browseDialogMessage); - dialog.setElements(getPHPFiles()); + dialog.setTitle(browseDialogTitle); + dialog.setMessage(browseDialogMessage); + dialog.setElements(getPHPFiles()); - if (dialog.open() == ElementListSelectionDialog.OK) { - textField.setText(((IResource) dialog.getFirstResult()).getProjectRelativePath().toString()); - } - } + if (dialog.open() == ElementListSelectionDialog.OK) { + textField.setText(((IResource) dialog.getFirstResult()) + .getProjectRelativePath().toString()); + } + } - protected String validateResourceSelection() { - IFile selection = getSelection(); - return selection == null ? EMPTY_STRING : selection.getProjectRelativePath().toString(); - } + protected String validateResourceSelection() { + IFile selection = getSelection(); + return selection == null ? EMPTY_STRING : selection + .getProjectRelativePath().toString(); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPFileUtil.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPFileUtil.java index 172078e..d17c8e4 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPFileUtil.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPFileUtil.java @@ -45,7 +45,8 @@ public class PHPFileUtil { */ public final static boolean isPHPFileName(String name) { - // avoid handling a file without base name, e.g. ".php", which is a valid + // avoid handling a file without base name, e.g. ".php", which is a + // valid // Eclipse resource name File file = new File(name); if (file.getName().startsWith(".")) { @@ -78,8 +79,8 @@ public class PHPFileUtil { } /** - * Returns true iff the file extension is a valid PHP Unit name implementation - * is not creating extra strings. + * Returns true iff the file extension is a valid PHP Unit name + * implementation is not creating extra strings. */ public final static boolean isValidPHPUnitName(String filename) { return PHPFileUtil.isPHPFileName(filename); @@ -93,7 +94,8 @@ public class PHPFileUtil { // ArrayList list = new ArrayList(); // final IPreferenceStore store = // PHPeclipsePlugin.getDefault().getPreferenceStore(); - // String extensions = store.getString(PHPeclipsePlugin.PHP_EXTENSION_PREFS); + // String extensions = + // store.getString(PHPeclipsePlugin.PHP_EXTENSION_PREFS); // extensions = extensions.trim(); // if (extensions.length() != 0) { // StringTokenizer tokenizer = new StringTokenizer(extensions, " ,;:/-|"); @@ -116,18 +118,18 @@ public class PHPFileUtil { // } /** * @param php_extensions - * The PHP extensions to set. + * The PHP extensions to set. */ // public static void setExtensions(String[] php_extensions) { // PHP_EXTENSIONS = php_extensions; // } /** * Creata the file for the given absolute file path - * + * * @param absoluteFilePath * @param project - * @return the file for the given absolute file path or null if - * no existing file can be found + * @return the file for the given absolute file path or null + * if no existing file can be found */ public static IFile createFile(IPath absoluteFilePath, IProject project) { if (absoluteFilePath == null || project == null) { @@ -135,21 +137,23 @@ public class PHPFileUtil { } String projectPath = project.getLocation().toString(); - String filePath = absoluteFilePath.toString().substring(projectPath.length() + 1); + String filePath = absoluteFilePath.toString().substring( + projectPath.length() + 1); return project.getFile(filePath); } /** * Determine the path of an include name string - * + * * @param includeNameString * @param resource * @param project * @return the path for the given include filename or null if * no existing file can be found */ - public static IPath determineFilePath(String includeNameString, IResource resource, IProject project) { + public static IPath determineFilePath(String includeNameString, + IResource resource, IProject project) { IPath documentRootPath = ProjectPrefUtil.getDocumentRoot(project); IPath resourcePath = resource.getProjectRelativePath(); @@ -162,7 +166,8 @@ public class PHPFileUtil { } if (includeNameString.startsWith("../")) { - path = project.getLocation().append(resourcePath.removeLastSegments(1)); + path = project.getLocation().append( + resourcePath.removeLastSegments(1)); path = path.append(includeNameString); file = path.toFile(); if (file.exists()) { @@ -182,7 +187,8 @@ public class PHPFileUtil { List includePaths = ProjectPrefUtil.getIncludePaths(project); if (includePaths.size() > 0) { for (int i = 0; i < includePaths.size(); i++) { - path = new Path(includePaths.get(i).toString()).append(includeNameString); + path = new Path(includePaths.get(i).toString()) + .append(includeNameString); file = path.toFile(); if (file.exists()) { return path; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPProjectSelector.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPProjectSelector.java index 71f3c41..9b41539 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPProjectSelector.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPProjectSelector.java @@ -12,20 +12,22 @@ public class PHPProjectSelector extends ResourceSelector { public PHPProjectSelector(Composite parent) { super(parent); - + browseDialogTitle = "Project Selection"; - } + } public IProject getSelection() { String projectName = getSelectionText(); if (projectName != null && !projectName.equals("")) - return PHPeclipsePlugin.getWorkspace().getRoot().getProject(projectName); - + return PHPeclipsePlugin.getWorkspace().getRoot().getProject( + projectName); + return null; } protected void handleBrowseSelected() { - ElementListSelectionDialog dialog = new ElementListSelectionDialog(getShell(), new WorkbenchLabelProvider()); + ElementListSelectionDialog dialog = new ElementListSelectionDialog( + getShell(), new WorkbenchLabelProvider()); dialog.setTitle(browseDialogTitle); dialog.setMessage(browseDialogMessage); dialog.setElements(JavaCore.getPHPProjects()); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PixelConverter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PixelConverter.java index 2ae19e3..46ace94 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PixelConverter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PixelConverter.java @@ -6,18 +6,18 @@ import org.eclipse.swt.graphics.GC; import org.eclipse.swt.widgets.Control; public class PixelConverter { - + private FontMetrics fFontMetrics; - + public PixelConverter(Control control) { GC gc = new GC(control); gc.setFont(control.getFont()); - fFontMetrics= gc.getFontMetrics(); + fFontMetrics = gc.getFontMetrics(); gc.dispose(); } - + private FontMetrics fgFontMetrics; - + /** * @see org.eclipse.jface.dialogs.DialogPage#convertHeightInCharsToPixels(int) */ @@ -38,12 +38,12 @@ public class PixelConverter { public int convertVerticalDLUsToPixels(int dlus) { return Dialog.convertVerticalDLUsToPixels(fFontMetrics, dlus); } - + /** * @see org.eclipse.jface.dialogs.DialogPage#convertWidthInCharsToPixels(int) */ public int convertWidthInCharsToPixels(int chars) { return Dialog.convertWidthInCharsToPixels(fFontMetrics, chars); - } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/ResourceSelector.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/ResourceSelector.java index cb28566..42e78de 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/ResourceSelector.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/ResourceSelector.java @@ -14,11 +14,17 @@ import org.eclipse.swt.widgets.Text; public abstract class ResourceSelector { protected final static String EMPTY_STRING = ""; + protected Composite composite; + protected Button browseButton; + protected Text textField; + protected String browseDialogMessage = EMPTY_STRING; + protected String browseDialogTitle = EMPTY_STRING; + protected String validatedSelectionText = EMPTY_STRING; public ResourceSelector(Composite parent) { @@ -47,6 +53,7 @@ public abstract class ResourceSelector { } protected abstract void handleBrowseSelected(); + protected abstract String validateResourceSelection(); protected Shell getShell() { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/SWTUtil.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/SWTUtil.java index f45e83c..979463c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/SWTUtil.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/SWTUtil.java @@ -10,7 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.ui.util; - import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.util.Assert; @@ -29,91 +28,93 @@ import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.Widget; /** - * Utility class to simplify access to some SWT resources. + * Utility class to simplify access to some SWT resources. */ public class SWTUtil { - + /** - * Returns the standard display to be used. The method first checks, if - * the thread calling this method has an associated disaply. If so, this - * display is returned. Otherwise the method returns the default display. + * Returns the standard display to be used. The method first checks, if the + * thread calling this method has an associated disaply. If so, this display + * is returned. Otherwise the method returns the default display. */ public static Display getStandardDisplay() { Display display; - display= Display.getCurrent(); + display = Display.getCurrent(); if (display == null) - display= Display.getDefault(); - return display; + display = Display.getDefault(); + return display; } - + /** - * Returns the shell for the given widget. If the widget doesn't represent - * a SWT object that manage a shell, null is returned. + * Returns the shell for the given widget. If the widget doesn't represent a + * SWT object that manage a shell, null is returned. * * @return the shell for the given widget */ public static Shell getShell(Widget widget) { if (widget instanceof Control) - return ((Control)widget).getShell(); + return ((Control) widget).getShell(); if (widget instanceof Caret) - return ((Caret)widget).getParent().getShell(); + return ((Caret) widget).getParent().getShell(); if (widget instanceof DragSource) - return ((DragSource)widget).getControl().getShell(); + return ((DragSource) widget).getControl().getShell(); if (widget instanceof DropTarget) - return ((DropTarget)widget).getControl().getShell(); + return ((DropTarget) widget).getControl().getShell(); if (widget instanceof Menu) - return ((Menu)widget).getParent().getShell(); + return ((Menu) widget).getParent().getShell(); if (widget instanceof ScrollBar) - return ((ScrollBar)widget).getParent().getShell(); - - return null; - } + return ((ScrollBar) widget).getParent().getShell(); + return null; + } /** * Returns a width hint for a button control. */ public static int getButtonWidthHint(Button button) { button.setFont(JFaceResources.getDialogFont()); - PixelConverter converter= new PixelConverter(button); - int widthHint= converter.convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH); - return Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x); + PixelConverter converter = new PixelConverter(button); + int widthHint = converter + .convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH); + return Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAULT, + true).x); } /** * Returns a height hint for a button control. - */ + */ public static int getButtonHeightHint(Button button) { button.setFont(JFaceResources.getDialogFont()); - PixelConverter converter= new PixelConverter(button); - return converter.convertVerticalDLUsToPixels(IDialogConstants.BUTTON_HEIGHT); + PixelConverter converter = new PixelConverter(button); + return converter + .convertVerticalDLUsToPixels(IDialogConstants.BUTTON_HEIGHT); } - + /** - * Sets width and height hint for the button control. - * Note: This is a NOP if the button's layout data is not - * an instance of GridData. + * Sets width and height hint for the button control. Note: This is + * a NOP if the button's layout data is not an instance of + * GridData. * - * @param button the button for which to set the dimension hint - */ + * @param button + * the button for which to set the dimension hint + */ public static void setButtonDimensionHint(Button button) { Assert.isNotNull(button); - Object gd= button.getLayoutData(); + Object gd = button.getLayoutData(); if (gd instanceof GridData) { - ((GridData)gd).heightHint= getButtonHeightHint(button); - ((GridData)gd).widthHint= getButtonWidthHint(button); - ((GridData)gd).horizontalAlignment = GridData.FILL; + ((GridData) gd).heightHint = getButtonHeightHint(button); + ((GridData) gd).widthHint = getButtonWidthHint(button); + ((GridData) gd).horizontalAlignment = GridData.FILL; } } - + public static int getTableHeightHint(Table table, int rows) { if (table.getFont().equals(JFaceResources.getDefaultFont())) table.setFont(JFaceResources.getDialogFont()); - int result= table.getItemHeight() * rows + table.getHeaderHeight(); + int result = table.getItemHeight() * rows + table.getHeaderHeight(); if (table.getLinesVisible()) - result+= table.getGridLineWidth() * (rows - 1); - return result; + result += table.getGridLineWidth() * (rows - 1); + return result; } - } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/StreamUtil.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/StreamUtil.java index 55c8865..5cdf1b9 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/StreamUtil.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/StreamUtil.java @@ -5,24 +5,25 @@ import java.io.InputStream; import java.io.OutputStream; public class StreamUtil { - public static void transferStreams(InputStream source, OutputStream destination) throws IOException { - try { - byte[] buffer = new byte[8192]; - while (true) { - int bytesRead = source.read(buffer); - if (bytesRead == -1) - break; - destination.write(buffer, 0, bytesRead); - } - } finally { - try { - source.close(); - } catch (IOException e) { - } - try { - destination.close(); - } catch (IOException e) { - } - } - } + public static void transferStreams(InputStream source, + OutputStream destination) throws IOException { + try { + byte[] buffer = new byte[8192]; + while (true) { + int bytesRead = source.read(buffer); + if (bytesRead == -1) + break; + destination.write(buffer, 0, bytesRead); + } + } finally { + try { + source.close(); + } catch (IOException e) { + } + try { + destination.close(); + } catch (IOException e) { + } + } + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/StringMatcher.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/StringMatcher.java index f15c2f8..756f28e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/StringMatcher.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/StringMatcher.java @@ -2,75 +2,91 @@ package net.sourceforge.phpdt.internal.ui.util; import java.util.Vector; - /** * A string pattern matcher, suppporting * and ? wildcards. */ -public class StringMatcher { +public class StringMatcher { protected String fPattern; + protected int fLength; // pattern length + protected boolean fIgnoreWildCards; + protected boolean fIgnoreCase; + protected boolean fHasLeadingStar; + protected boolean fHasTrailingStar; - protected String fSegments[]; //the given pattern is split into * separated segments + + protected String fSegments[]; // the given pattern is split into * + // separated segments /* boundary value beyond which we don't need to search in the text */ - protected int fBound= 0; - + protected int fBound = 0; + + protected static final char fSingleWildCard = '\u0000'; - protected static final char fSingleWildCard= '\u0000'; - public static class Position { - int start; //inclusive - int end; //exclusive + int start; // inclusive + + int end; // exclusive + public Position(int start, int end) { - this.start= start; - this.end= end; + this.start = start; + this.end = end; } + public int getStart() { return start; } + public int getEnd() { return end; } } + /** - * StringMatcher constructor takes in a String object that is a simple - * pattern which may contain ‘*’ for 0 and many characters and - * ‘?’ for exactly one character. - * - * Literal '*' and '?' characters must be escaped in the pattern - * e.g., "\*" means literal "*", etc. - * - * Escaping any other character (including the escape character itself), - * just results in that character in the pattern. - * e.g., "\a" means "a" and "\\" means "\" - * + * StringMatcher constructor takes in a String object that is a simple + * pattern which may contain �*� for 0 and many characters and �?� for + * exactly one character. + * + * Literal '*' and '?' characters must be escaped in the pattern e.g., "\*" + * means literal "*", etc. + * + * Escaping any other character (including the escape character itself), + * just results in that character in the pattern. e.g., "\a" means "a" and + * "\\" means "\" + * * If invoking the StringMatcher with string literals in Java, don't forget * escape characters are represented by "\\". - * - * @param pattern the pattern to match text against - * @param ignoreCase if true, case is ignored - * @param ignoreWildCards if true, wild cards and their escape sequences are ignored - * (everything is taken literally). + * + * @param pattern + * the pattern to match text against + * @param ignoreCase + * if true, case is ignored + * @param ignoreWildCards + * if true, wild cards and their escape sequences are ignored + * (everything is taken literally). */ - public StringMatcher(String pattern, boolean ignoreCase, boolean ignoreWildCards) { + public StringMatcher(String pattern, boolean ignoreCase, + boolean ignoreWildCards) { if (pattern == null) throw new IllegalArgumentException(); - fIgnoreCase= ignoreCase; - fIgnoreWildCards= ignoreWildCards; - fPattern= pattern; - fLength= pattern.length(); - + fIgnoreCase = ignoreCase; + fIgnoreWildCards = ignoreWildCards; + fPattern = pattern; + fLength = pattern.length(); + if (fIgnoreWildCards) { parseNoWildCards(); } else { parseWildCards(); } } + /** - * Find the first occurrence of the pattern between startstartend(exclusive). * @param text, the String object to search in * @param start, the starting index of the search range, inclusive @@ -85,184 +101,204 @@ public class StringMatcher { public StringMatcher.Position find(String text, int start, int end) { if (text == null) throw new IllegalArgumentException(); - - int tlen= text.length(); + + int tlen = text.length(); if (start < 0) - start= 0; + start = 0; if (end > tlen) - end= tlen; - if (end < 0 ||start >= end ) + end = tlen; + if (end < 0 || start >= end) return null; if (fLength == 0) return new Position(start, start); if (fIgnoreWildCards) { - int x= posIn(text, start, end); + int x = posIn(text, start, end); if (x < 0) return null; - return new Position(x, x+fLength); + return new Position(x, x + fLength); } - int segCount= fSegments.length; - if (segCount == 0)//pattern contains only '*'(s) - return new Position (start, end); - - int curPos= start; - int matchStart= -1; + int segCount = fSegments.length; + if (segCount == 0)// pattern contains only '*'(s) + return new Position(start, end); + + int curPos = start; + int matchStart = -1; int i; - for (i= 0; i < segCount && curPos < end; ++i) { - String current= fSegments[i]; - int nextMatch= regExpPosIn(text, curPos, end, current); - if (nextMatch < 0 ) + for (i = 0; i < segCount && curPos < end; ++i) { + String current = fSegments[i]; + int nextMatch = regExpPosIn(text, curPos, end, current); + if (nextMatch < 0) return null; - if(i == 0) - matchStart= nextMatch; - curPos= nextMatch + current.length(); + if (i == 0) + matchStart = nextMatch; + curPos = nextMatch + current.length(); } if (i < segCount) return null; return new Position(matchStart, curPos); } + /** - * match the given text with the pattern + * match the given text with the pattern + * * @return true if matched eitherwise false - * @param text, a String object + * @param text, a String object */ public boolean match(String text) { return match(text, 0, text.length()); } + /** - * Given the starting (inclusive) and the ending (exclusive) positions in the - * text, determine if the given substring matches with aPattern + * Given the starting (inclusive) and the ending (exclusive) positions in + * the text, determine if the given substring matches with + * aPattern + * * @return true if the specified portion of the text matches the pattern - * @param String text, a String object that contains the substring to match - * @param int start marks the starting position (inclusive) of the substring - * @param int end marks the ending index (exclusive) of the substring + * @param String + * text, a String object that contains the + * substring to match + * @param int + * start marks the starting position (inclusive) of the substring + * @param int end marks the ending index (exclusive) of the substring */ public boolean match(String text, int start, int end) { if (null == text) throw new IllegalArgumentException(); - + if (start > end) return false; - + if (fIgnoreWildCards) - return (end - start == fLength) && fPattern.regionMatches(fIgnoreCase, 0, text, start, fLength); - int segCount= fSegments.length; - if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) // pattern contains only '*'(s) + return (end - start == fLength) + && fPattern.regionMatches(fIgnoreCase, 0, text, start, + fLength); + int segCount = fSegments.length; + if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) // pattern + // contains + // only + // '*'(s) return true; if (start == end) return fLength == 0; if (fLength == 0) - return start == end; - - int tlen= text.length(); + return start == end; + + int tlen = text.length(); if (start < 0) - start= 0; + start = 0; if (end > tlen) - end= tlen; - - int tCurPos= start; - int bound= end - fBound; - if ( bound < 0) + end = tlen; + + int tCurPos = start; + int bound = end - fBound; + if (bound < 0) return false; - int i=0; - String current= fSegments[i]; - int segLength= current.length(); + int i = 0; + String current = fSegments[i]; + int segLength = current.length(); /* process first segment */ - if (!fHasLeadingStar){ - if(!regExpRegionMatches(text, start, current, 0, segLength)) { + if (!fHasLeadingStar) { + if (!regExpRegionMatches(text, start, current, 0, segLength)) { return false; } else { ++i; - tCurPos= tCurPos + segLength; + tCurPos = tCurPos + segLength; } } - /* process middle segments */ + /* process middle segments */ while (i < segCount) { - current= fSegments[i]; + current = fSegments[i]; int currentMatch; - int k= current.indexOf(fSingleWildCard); + int k = current.indexOf(fSingleWildCard); if (k < 0) { - currentMatch= textPosIn(text, tCurPos, end, current); + currentMatch = textPosIn(text, tCurPos, end, current); if (currentMatch < 0) return false; - } else { - currentMatch= regExpPosIn(text, tCurPos, end, current); + } else { + currentMatch = regExpPosIn(text, tCurPos, end, current); if (currentMatch < 0) return false; } - tCurPos= currentMatch + current.length(); + tCurPos = currentMatch + current.length(); i++; } /* process final segment */ if (!fHasTrailingStar && tCurPos != end) { - int clen= current.length(); + int clen = current.length(); return regExpRegionMatches(text, end - clen, current, 0, clen); } - return i == segCount ; + return i == segCount; } + /** - * This method parses the given pattern into segments seperated by wildcard '*' characters. - * Since wildcards are not being used in this case, the pattern consists of a single segment. + * This method parses the given pattern into segments seperated by wildcard + * '*' characters. Since wildcards are not being used in this case, the + * pattern consists of a single segment. */ private void parseNoWildCards() { - fSegments= new String[1]; - fSegments[0]= fPattern; - fBound= fLength; + fSegments = new String[1]; + fSegments[0] = fPattern; + fBound = fLength; } + /** - * Parses the given pattern into segments seperated by wildcard '*' characters. - * @param p, a String object that is a simple regular expression with ‘*’ and/or ‘?’ + * Parses the given pattern into segments seperated by wildcard '*' + * characters. + * + * @param p, + * a String object that is a simple regular expression with �*� + * and/or �?� */ private void parseWildCards() { - if(fPattern.startsWith("*"))//$NON-NLS-1$ - fHasLeadingStar= true; - if(fPattern.endsWith("*")) {//$NON-NLS-1$ + if (fPattern.startsWith("*"))//$NON-NLS-1$ + fHasLeadingStar = true; + if (fPattern.endsWith("*")) {//$NON-NLS-1$ /* make sure it's not an escaped wildcard */ if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') { - fHasTrailingStar= true; + fHasTrailingStar = true; } } - Vector temp= new Vector(); + Vector temp = new Vector(); - int pos= 0; - StringBuffer buf= new StringBuffer(); + int pos = 0; + StringBuffer buf = new StringBuffer(); while (pos < fLength) { - char c= fPattern.charAt(pos++); + char c = fPattern.charAt(pos++); switch (c) { - case '\\': - if (pos >= fLength) { - buf.append(c); + case '\\': + if (pos >= fLength) { + buf.append(c); + } else { + char next = fPattern.charAt(pos++); + /* if it's an escape sequence */ + if (next == '*' || next == '?' || next == '\\') { + buf.append(next); } else { - char next= fPattern.charAt(pos++); - /* if it's an escape sequence */ - if (next == '*' || next == '?' || next == '\\') { - buf.append(next); - } else { - /* not an escape sequence, just insert literally */ - buf.append(c); - buf.append(next); - } + /* not an escape sequence, just insert literally */ + buf.append(c); + buf.append(next); } + } break; - case '*': - if (buf.length() > 0) { - /* new segment */ - temp.addElement(buf.toString()); - fBound += buf.length(); - buf.setLength(0); - } + case '*': + if (buf.length() > 0) { + /* new segment */ + temp.addElement(buf.toString()); + fBound += buf.length(); + buf.setLength(0); + } break; - case '?': - /* append special character representing single match wildcard */ - buf.append(fSingleWildCard); + case '?': + /* append special character representing single match wildcard */ + buf.append(fSingleWildCard); break; - default: - buf.append(c); + default: + buf.append(c); } } @@ -271,64 +307,78 @@ public class StringMatcher { temp.addElement(buf.toString()); fBound += buf.length(); } - - fSegments= new String[temp.size()]; + + fSegments = new String[temp.size()]; temp.copyInto(fSegments); } - /** + + /** * @param text, a string which contains no wildcard - * @param start, the starting index in the text for search, inclusive + * @param start, the starting index in the text for search, + * inclusive * @param end, the stopping point of search, exclusive - * @return the starting index in the text of the pattern , or -1 if not found + * @return the starting index in the text of the pattern , or -1 if not + * found */ - protected int posIn(String text, int start, int end) {//no wild card in pattern - int max= end - fLength; - + protected int posIn(String text, int start, int end) {// no wild card in + // pattern + int max = end - fLength; + if (!fIgnoreCase) { - int i= text.indexOf(fPattern, start); + int i = text.indexOf(fPattern, start); if (i == -1 || i > max) return -1; return i; } - - for (int i= start; i <= max; ++i) { + + for (int i = start; i <= max; ++i) { if (text.regionMatches(true, i, fPattern, 0, fLength)) return i; } - + return -1; } - /** - * @param text, a simple regular expression that may only contain '?'(s) - * @param start, the starting index in the text for search, inclusive + + /** + * @param text, a simple regular expression that may only + * contain '?'(s) + * @param start, the starting index in the text for search, + * inclusive * @param end, the stopping point of search, exclusive * @param p, a simple regular expression that may contains '?' * @param caseIgnored, wether the pattern is not casesensitive - * @return the starting index in the text of the pattern , or -1 if not found + * @return the starting index in the text of the pattern , or -1 if not + * found */ protected int regExpPosIn(String text, int start, int end, String p) { - int plen= p.length(); - - int max= end - plen; - for (int i= start; i <= max; ++i) { + int plen = p.length(); + + int max = end - plen; + for (int i = start; i <= max; ++i) { if (regExpRegionMatches(text, i, p, 0, plen)) return i; } return -1; } + /** * * @return boolean * @param text, a String to match - * @param start, int that indicates the starting index of match, inclusive - * @param end int that indicates the ending index of match, exclusive - * @param p, String, String, a simple regular expression that may contain '?' - * @param ignoreCase, boolean indicating wether code>p is case sensitive + * @param start, int that indicates the starting index of + * match, inclusive + * @param end int that indicates the ending index of match, + * exclusive + * @param p, String, String, a simple regular expression that + * may contain '?' + * @param ignoreCase, boolean indicating wether code>p + * is case sensitive */ - protected boolean regExpRegionMatches(String text, int tStart, String p, int pStart, int plen) { + protected boolean regExpRegionMatches(String text, int tStart, String p, + int pStart, int plen) { while (plen-- > 0) { - char tchar= text.charAt(tStart++); - char pchar= p.charAt(pStart++); + char tchar = text.charAt(tStart++); + char pchar = p.charAt(pStart++); /* process wild cards */ if (!fIgnoreWildCards) { @@ -340,42 +390,51 @@ public class StringMatcher { if (pchar == tchar) continue; if (fIgnoreCase) { - if (Character.toUpperCase(tchar) == Character.toUpperCase(pchar)) + if (Character.toUpperCase(tchar) == Character + .toUpperCase(pchar)) continue; - // comparing after converting to upper case doesn't handle all cases; + // comparing after converting to upper case doesn't handle all + // cases; // also compare after converting to lower case - if (Character.toLowerCase(tchar) == Character.toLowerCase(pchar)) + if (Character.toLowerCase(tchar) == Character + .toLowerCase(pchar)) continue; } return false; } return true; } - /** + + /** * @param text, the string to match - * @param start, the starting index in the text for search, inclusive + * @param start, the starting index in the text for search, + * inclusive * @param end, the stopping point of search, exclusive - * @param code>p, a string that has no wildcard - * @param ignoreCase, boolean indicating wether code>p is case sensitive - * @return the starting index in the text of the pattern , or -1 if not found + * @param code>p + * , a string that has no wildcard + * @param + * ignoreCase, boolean indicating wether code>p + * is case sensitive + * @return the starting index in the text of the pattern , or -1 if not + * found */ - protected int textPosIn(String text, int start, int end, String p) { - - int plen= p.length(); - int max= end - plen; - + protected int textPosIn(String text, int start, int end, String p) { + + int plen = p.length(); + int max = end - plen; + if (!fIgnoreCase) { - int i= text.indexOf(p, start); + int i = text.indexOf(p, start); if (i == -1 || i > max) return -1; return i; } - - for (int i= start; i <= max; ++i) { + + for (int i = start; i <= max; ++i) { if (text.regionMatches(true, i, p, 0, plen)) return i; } - + return -1; } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/TabFolderLayout.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/TabFolderLayout.java index ba37d7b..7c2f0cb 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/TabFolderLayout.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/TabFolderLayout.java @@ -13,32 +13,33 @@ import org.eclipse.swt.widgets.Layout; public class TabFolderLayout extends Layout { - protected Point computeSize (Composite composite, int wHint, int hHint, boolean flushCache) { + protected Point computeSize(Composite composite, int wHint, int hHint, + boolean flushCache) { if (wHint != SWT.DEFAULT && hHint != SWT.DEFAULT) return new Point(wHint, hHint); - - Control [] children = composite.getChildren (); + + Control[] children = composite.getChildren(); int count = children.length; int maxWidth = 0, maxHeight = 0; - for (int i=0; iTableLayoutComposite. */ public TableLayoutComposite(Composite parent, int style) { super(parent, style); - addControlListener(new ControlAdapter() { - public void controlResized(ControlEvent e) { - Rectangle area= getClientArea(); - Table table= (Table)getChildren()[0]; - Point preferredSize= computeTableSize(table); - int width= area.width - 2 * table.getBorderWidth(); - if (preferredSize.y > area.height) { - // Subtract the scrollbar width from the total column width - // if a vertical scrollbar will be required - Point vBarSize = table.getVerticalBar().getSize(); - width -= vBarSize.x; - } - layoutTable(table, width, area, table.getSize().x < area.width); - } - }); + addControlListener(new ControlAdapter() { + public void controlResized(ControlEvent e) { + Rectangle area = getClientArea(); + Table table = (Table) getChildren()[0]; + Point preferredSize = computeTableSize(table); + int width = area.width - 2 * table.getBorderWidth(); + if (preferredSize.y > area.height) { + // Subtract the scrollbar width from the total column width + // if a vertical scrollbar will be required + Point vBarSize = table.getVerticalBar().getSize(); + width -= vBarSize.x; + } + layoutTable(table, width, area, table.getSize().x < area.width); + } + }); } - + /** * Adds a new column of data to this table layout. - * - * @param data the column layout data + * + * @param data + * the column layout data */ public void addColumnData(ColumnLayoutData data) { columns.add(data); } - - //---- Helpers ------------------------------------------------------------------------------------- - + + // ---- Helpers + // ------------------------------------------------------------------------------------- + private Point computeTableSize(Table table) { - Point result= table.computeSize(SWT.DEFAULT, SWT.DEFAULT); - - int width= 0; - int size= columns.size(); - for (int i= 0; i < size; ++i) { - ColumnLayoutData layoutData= (ColumnLayoutData) columns.get(i); + Point result = table.computeSize(SWT.DEFAULT, SWT.DEFAULT); + + int width = 0; + int size = columns.size(); + for (int i = 0; i < size; ++i) { + ColumnLayoutData layoutData = (ColumnLayoutData) columns.get(i); if (layoutData instanceof ColumnPixelData) { - ColumnPixelData col= (ColumnPixelData) layoutData; + ColumnPixelData col = (ColumnPixelData) layoutData; width += col.width; } else if (layoutData instanceof ColumnWeightData) { - ColumnWeightData col= (ColumnWeightData) layoutData; + ColumnWeightData col = (ColumnWeightData) layoutData; width += col.minimumWidth; } else { Assert.isTrue(false, "Unknown column layout data"); //$NON-NLS-1$ } } if (width > result.x) - result.x= width; + result.x = width; return result; } - - private void layoutTable(Table table, int width, Rectangle area, boolean increase) { + + private void layoutTable(Table table, int width, Rectangle area, + boolean increase) { // XXX: Layout is being called with an invalid value the first time // it is being called on Linux. This method resets the // Layout to null so we make sure we run it only when @@ -98,26 +101,28 @@ public class TableLayoutComposite extends Composite { if (width <= 1) return; - TableColumn[] tableColumns= table.getColumns(); - int size= Math.min(columns.size(), tableColumns.length); - int[] widths= new int[size]; - int fixedWidth= 0; - int numberOfWeightColumns= 0; - int totalWeight= 0; + TableColumn[] tableColumns = table.getColumns(); + int size = Math.min(columns.size(), tableColumns.length); + int[] widths = new int[size]; + int fixedWidth = 0; + int numberOfWeightColumns = 0; + int totalWeight = 0; // First calc space occupied by fixed columns - for (int i= 0; i < size; i++) { - ColumnLayoutData col= (ColumnLayoutData) columns.get(i); + for (int i = 0; i < size; i++) { + ColumnLayoutData col = (ColumnLayoutData) columns.get(i); if (col instanceof ColumnPixelData) { - int pixels= ((ColumnPixelData) col).width; - widths[i]= pixels; + int pixels = ((ColumnPixelData) col).width; + widths[i] = pixels; fixedWidth += pixels; } else if (col instanceof ColumnWeightData) { - ColumnWeightData cw= (ColumnWeightData) col; + ColumnWeightData cw = (ColumnWeightData) col; numberOfWeightColumns++; - // first time, use the weight specified by the column data, otherwise use the actual width as the weight - // int weight = firstTime ? cw.weight : tableColumns[i].getWidth(); - int weight= cw.weight; + // first time, use the weight specified by the column data, + // otherwise use the actual width as the weight + // int weight = firstTime ? cw.weight : + // tableColumns[i].getWidth(); + int weight = cw.weight; totalWeight += weight; } else { Assert.isTrue(false, "Unknown column layout data"); //$NON-NLS-1$ @@ -127,40 +132,42 @@ public class TableLayoutComposite extends Composite { // Do we have columns that have a weight if (numberOfWeightColumns > 0) { // Now distribute the rest to the columns with weight. - int rest= width - fixedWidth; - int totalDistributed= 0; - for (int i= 0; i < size; ++i) { - ColumnLayoutData col= (ColumnLayoutData) columns.get(i); + int rest = width - fixedWidth; + int totalDistributed = 0; + for (int i = 0; i < size; ++i) { + ColumnLayoutData col = (ColumnLayoutData) columns.get(i); if (col instanceof ColumnWeightData) { - ColumnWeightData cw= (ColumnWeightData) col; + ColumnWeightData cw = (ColumnWeightData) col; // calculate weight as above - // int weight = firstTime ? cw.weight : tableColumns[i].getWidth(); - int weight= cw.weight; - int pixels= totalWeight == 0 ? 0 : weight * rest / totalWeight; + // int weight = firstTime ? cw.weight : + // tableColumns[i].getWidth(); + int weight = cw.weight; + int pixels = totalWeight == 0 ? 0 : weight * rest + / totalWeight; if (pixels < cw.minimumWidth) - pixels= cw.minimumWidth; + pixels = cw.minimumWidth; totalDistributed += pixels; - widths[i]= pixels; + widths[i] = pixels; } } // Distribute any remaining pixels to columns with weight. - int diff= rest - totalDistributed; - for (int i= 0; diff > 0; ++i) { + int diff = rest - totalDistributed; + for (int i = 0; diff > 0; ++i) { if (i == size) - i= 0; - ColumnLayoutData col= (ColumnLayoutData) columns.get(i); + i = 0; + ColumnLayoutData col = (ColumnLayoutData) columns.get(i); if (col instanceof ColumnWeightData) { ++widths[i]; --diff; } } } - + if (increase) { table.setSize(area.width, area.height); } - for (int i= 0; i < size; i++) { + for (int i = 0; i < size; i++) { tableColumns[i].setWidth(widths[i]); } if (!increase) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/TwoArrayQuickSorter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/TwoArrayQuickSorter.java index bf8bb1b..86db922 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/TwoArrayQuickSorter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/TwoArrayQuickSorter.java @@ -5,11 +5,11 @@ import java.util.Comparator; import org.eclipse.jface.util.Assert; /** - * Quick sort to sort key-value pairs. The keys and arrays are specified - * in separate arrays. + * Quick sort to sort key-value pairs. The keys and arrays are specified in + * separate arrays. */ public class TwoArrayQuickSorter { - + private Comparator fComparator; /** @@ -17,39 +17,47 @@ public class TwoArrayQuickSorter { */ public static final class StringComparator implements Comparator { private boolean fIgnoreCase; - + StringComparator(boolean ignoreCase) { - fIgnoreCase= ignoreCase; + fIgnoreCase = ignoreCase; } - + public int compare(Object left, Object right) { - return fIgnoreCase - ? ((String) left).compareToIgnoreCase((String) right) - : ((String) left).compareTo((String) right); + return fIgnoreCase ? ((String) left) + .compareToIgnoreCase((String) right) : ((String) left) + .compareTo((String) right); } - } + } /** - * Creates a sorter with default string comparator. - * The keys are assumed to be strings. - * @param ignoreCase specifies whether sorting is case sensitive or not. - */ + * Creates a sorter with default string comparator. The keys are assumed to + * be strings. + * + * @param ignoreCase + * specifies whether sorting is case sensitive or not. + */ public TwoArrayQuickSorter(boolean ignoreCase) { - fComparator= new StringComparator(ignoreCase); + fComparator = new StringComparator(ignoreCase); } /** * Creates a sorter with a comparator. - * @param comparator the comparator to order the elements. The comparator must not be null. + * + * @param comparator + * the comparator to order the elements. The comparator must not + * be null. */ public TwoArrayQuickSorter(Comparator comparator) { - fComparator= comparator; + fComparator = comparator; } - + /** * Sorts keys and values in parallel. - * @param keys the keys to use for sorting. - * @param values the values associated with the keys. + * + * @param keys + * the keys to use for sorting. + * @param values + * the values associated with the keys. */ public void sort(Object[] keys, Object[] values) { if ((keys == null) || (values == null)) { @@ -59,44 +67,45 @@ public class TwoArrayQuickSorter { if (keys.length <= 1) return; - - internalSort(keys, values, 0, keys.length - 1); + + internalSort(keys, values, 0, keys.length - 1); } - private void internalSort(Object[] keys, Object[] values, int left, int right) { - int original_left= left; - int original_right= right; - - Object mid= keys[(left + right) / 2]; - do { + private void internalSort(Object[] keys, Object[] values, int left, + int right) { + int original_left = left; + int original_right = right; + + Object mid = keys[(left + right) / 2]; + do { while (fComparator.compare(keys[left], mid) < 0) - left++; + left++; while (fComparator.compare(mid, keys[right]) < 0) - right--; + right--; if (left <= right) { swap(keys, left, right); swap(values, left, right); - left++; - right--; - } + left++; + right--; + } } while (left <= right); - + if (original_left < right) - internalSort(keys , values, original_left, right); + internalSort(keys, values, original_left, right); if (left < original_right) - internalSort(keys, values, left, original_right); + internalSort(keys, values, left, original_right); } - /* - * Swaps x[a] with x[b]. - */ - private static final void swap(Object x[], int a, int b) { + /* + * Swaps x[a] with x[b]. + */ + private static final void swap(Object x[], int a, int b) { Object t = x[a]; x[a] = x[b]; x[b] = t; - } - + } + } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/AppearanceAwareLabelProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/AppearanceAwareLabelProvider.java index 265ccbf..bbed6ac 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/AppearanceAwareLabelProvider.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/AppearanceAwareLabelProvider.java @@ -17,18 +17,22 @@ import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.LabelProviderChangedEvent; - /** - * JavaUILabelProvider that respects settings from the Appearance preference page. - * Triggers a viewer update when a preference changes. + * JavaUILabelProvider that respects settings from the Appearance preference + * page. Triggers a viewer update when a preference changes. */ -public class AppearanceAwareLabelProvider extends JavaUILabelProvider implements IPropertyChangeListener { +public class AppearanceAwareLabelProvider extends JavaUILabelProvider implements + IPropertyChangeListener { + + public final static int DEFAULT_TEXTFLAGS = JavaElementLabels.ROOT_VARIABLE + | JavaElementLabels.M_PARAMETER_TYPES + | JavaElementLabels.M_APP_RETURNTYPE + | JavaElementLabels.REFERENCED_ROOT_POST_QUALIFIED; + + public final static int DEFAULT_IMAGEFLAGS = JavaElementImageProvider.OVERLAY_ICONS; - public final static int DEFAULT_TEXTFLAGS= JavaElementLabels.ROOT_VARIABLE | JavaElementLabels.M_PARAMETER_TYPES | - JavaElementLabels.M_APP_RETURNTYPE | JavaElementLabels.REFERENCED_ROOT_POST_QUALIFIED; - public final static int DEFAULT_IMAGEFLAGS= JavaElementImageProvider.OVERLAY_ICONS; - private int fTextFlagMask; + private int fImageFlagMask; /** @@ -37,48 +41,54 @@ public class AppearanceAwareLabelProvider extends JavaUILabelProvider implements public AppearanceAwareLabelProvider(int textFlags, int imageFlags) { super(textFlags, imageFlags); initMasks(); - PreferenceConstants.getPreferenceStore().addPropertyChangeListener(this); + PreferenceConstants.getPreferenceStore() + .addPropertyChangeListener(this); } /** * Creates a labelProvider with DEFAULT_TEXTFLAGS and DEFAULT_IMAGEFLAGS - */ + */ public AppearanceAwareLabelProvider() { this(DEFAULT_TEXTFLAGS, DEFAULT_IMAGEFLAGS); } - + private void initMasks() { - IPreferenceStore store= PreferenceConstants.getPreferenceStore(); - fTextFlagMask= -1; + IPreferenceStore store = PreferenceConstants.getPreferenceStore(); + fTextFlagMask = -1; if (!store.getBoolean(PreferenceConstants.APPEARANCE_METHOD_RETURNTYPE)) { fTextFlagMask ^= JavaElementLabels.M_APP_RETURNTYPE; } - if (!store.getBoolean(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES)) { + if (!store + .getBoolean(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES)) { fTextFlagMask ^= JavaElementLabels.P_COMPRESSED; } - - fImageFlagMask= -1; + + fImageFlagMask = -1; } /* * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { - String property= event.getProperty(); + String property = event.getProperty(); if (property.equals(PreferenceConstants.APPEARANCE_METHOD_RETURNTYPE) - || property.equals(PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW) - || property.equals(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES)) { + || property + .equals(PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW) + || property + .equals(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES)) { initMasks(); - LabelProviderChangedEvent lpEvent= new LabelProviderChangedEvent(this, null); // refresh all + LabelProviderChangedEvent lpEvent = new LabelProviderChangedEvent( + this, null); // refresh all fireLabelProviderChanged(lpEvent); - } + } } /* * @see IBaseLabelProvider#dispose() */ public void dispose() { - PreferenceConstants.getPreferenceStore().removePropertyChangeListener(this); + PreferenceConstants.getPreferenceStore().removePropertyChangeListener( + this); super.dispose(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ContainerCheckedTreeViewer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ContainerCheckedTreeViewer.java index deaac0e..0bd7141 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ContainerCheckedTreeViewer.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ContainerCheckedTreeViewer.java @@ -14,16 +14,17 @@ import org.eclipse.swt.widgets.TreeItem; import org.eclipse.swt.widgets.Widget; /** - * CheckboxTreeViewer with special behaviour of the checked / gray state on - * container (non-leaf) nodes: - * The grayed state is used to visualize the checked state of its children. - * Containers are checked and non-gary if all contained leafs are checked. The - * container is grayed if some but not all leafs are checked. + * CheckboxTreeViewer with special behaviour of the checked / gray state on + * container (non-leaf) nodes: The grayed state is used to visualize the checked + * state of its children. Containers are checked and non-gary if all contained + * leafs are checked. The container is grayed if some but not all leafs are + * checked. */ -public class ContainerCheckedTreeViewer extends CheckboxTreeViewer { +public class ContainerCheckedTreeViewer extends CheckboxTreeViewer { /** * Constructor for ContainerCheckedTreeViewer. + * * @see CheckboxTreeViewer#CheckboxTreeViewer(Composite) */ public ContainerCheckedTreeViewer(Composite parent) { @@ -33,6 +34,7 @@ public class ContainerCheckedTreeViewer extends CheckboxTreeViewer { /** * Constructor for ContainerCheckedTreeViewer. + * * @see CheckboxTreeViewer#CheckboxTreeViewer(Composite,int) */ public ContainerCheckedTreeViewer(Composite parent, int style) { @@ -42,6 +44,7 @@ public class ContainerCheckedTreeViewer extends CheckboxTreeViewer { /** * Constructor for ContainerCheckedTreeViewer. + * * @see CheckboxTreeViewer#CheckboxTreeViewer(Tree) */ public ContainerCheckedTreeViewer(Tree tree) { @@ -57,7 +60,9 @@ public class ContainerCheckedTreeViewer extends CheckboxTreeViewer { } }); addTreeListener(new ITreeViewerListener() { - public void treeCollapsed(TreeExpansionEvent event) {} + public void treeCollapsed(TreeExpansionEvent event) { + } + public void treeExpanded(TreeExpansionEvent event) { Widget item = findItem(event.getElement()); if (item instanceof TreeItem) { @@ -78,7 +83,7 @@ public class ContainerCheckedTreeViewer extends CheckboxTreeViewer { } /** - * The item has expanded. Updates the checked state of its children. + * The item has expanded. Updates the checked state of its children. */ private void initializeItem(TreeItem item) { if (item.getChecked() && !item.getGrayed()) { @@ -94,7 +99,8 @@ public class ContainerCheckedTreeViewer extends CheckboxTreeViewer { boolean state = parent.getChecked(); for (int i = 0; i < children.length; i++) { TreeItem curr = (TreeItem) children[i]; - if (curr.getData() != null && ((curr.getChecked() != state) || curr.getGrayed())) { + if (curr.getData() != null + && ((curr.getChecked() != state) || curr.getGrayed())) { curr.setChecked(state); curr.setGrayed(false); updateChildrenItems(curr); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/DecoratingJavaLabelProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/DecoratingJavaLabelProvider.java index 5712683..268cfaf 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/DecoratingJavaLabelProvider.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/DecoratingJavaLabelProvider.java @@ -23,24 +23,25 @@ import org.eclipse.ui.PlatformUI; /** * Decorator prepared for the switch to use lightweight label decorators: * uncomment the lbale decorator entries in plugin.xml and change - * USE_LIGHTWEIGHT to true. - * Certain views don't want problems or override indicators, so they signal this - * in the constructor. So on each getImage the corrsponding decorators are - * turned off and on again. - */ + * USE_LIGHTWEIGHT to true. Certain views don't want problems or override + * indicators, so they signal this in the constructor. So on each getImage the + * corrsponding decorators are turned off and on again. + */ public class DecoratingJavaLabelProvider extends DecoratingLabelProvider { - private static final boolean USE_LIGHTWEIGHT= false; - - private static final String PROBLEM_DECORATOR_ID= "net.sourceforge.phpdt.ui.problem.decorator"; //$NON-NLS-1$ - private static final String OVERRIDE_DECORATOR_ID= "net.sourceforge.phpdt.ui.override.decorator"; //$NON-NLS-1$ - + private static final boolean USE_LIGHTWEIGHT = false; + + private static final String PROBLEM_DECORATOR_ID = "net.sourceforge.phpdt.ui.problem.decorator"; //$NON-NLS-1$ + + private static final String OVERRIDE_DECORATOR_ID = "net.sourceforge.phpdt.ui.override.decorator"; //$NON-NLS-1$ + private boolean fUseErrorTick; + private boolean fUseOverride; /** - * Decorating label provider for Java. Combines a JavaUILabelProvider - * with problem and override indicuator with the workbench decorator (label + * Decorating label provider for Java. Combines a JavaUILabelProvider with + * problem and override indicuator with the workbench decorator (label * decorator extension point). */ public DecoratingJavaLabelProvider(JavaUILabelProvider labelProvider) { @@ -48,33 +49,43 @@ public class DecoratingJavaLabelProvider extends DecoratingLabelProvider { } /** - * Decorating label provider for Java. Combines a JavaUILabelProvider - * (if enabled with problem and override indicator) with the workbench - * decorator (label decorator extension point). + * Decorating label provider for Java. Combines a JavaUILabelProvider (if + * enabled with problem and override indicator) with the workbench decorator + * (label decorator extension point). */ - public DecoratingJavaLabelProvider(JavaUILabelProvider labelProvider, boolean errorTick, boolean override) { - super(labelProvider, PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator()); - fUseErrorTick= errorTick; - fUseOverride= override; + public DecoratingJavaLabelProvider(JavaUILabelProvider labelProvider, + boolean errorTick, boolean override) { + super(labelProvider, PlatformUI.getWorkbench().getDecoratorManager() + .getLabelDecorator()); + fUseErrorTick = errorTick; + fUseOverride = override; if (!USE_LIGHTWEIGHT) { if (errorTick) { - labelProvider.addLabelDecorator(new ProblemsLabelDecorator(null)); + labelProvider + .addLabelDecorator(new ProblemsLabelDecorator(null)); } if (override) { - labelProvider.addLabelDecorator(new OverrideIndicatorLabelDecorator(null)); + labelProvider + .addLabelDecorator(new OverrideIndicatorLabelDecorator( + null)); } } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object) */ public Image getImage(Object element) { if (USE_LIGHTWEIGHT) { - IDecoratorManager manager= PlatformUI.getWorkbench().getDecoratorManager(); - - boolean disableErrorTick= manager.getEnabled(PROBLEM_DECORATOR_ID) && !fUseErrorTick; - boolean disableOverride= manager.getEnabled(OVERRIDE_DECORATOR_ID) && !fUseOverride; + IDecoratorManager manager = PlatformUI.getWorkbench() + .getDecoratorManager(); + + boolean disableErrorTick = manager.getEnabled(PROBLEM_DECORATOR_ID) + && !fUseErrorTick; + boolean disableOverride = manager.getEnabled(OVERRIDE_DECORATOR_ID) + && !fUseOverride; try { if (disableErrorTick) { manager.setEnabled(PROBLEM_DECORATOR_ID, false); @@ -82,7 +93,7 @@ public class DecoratingJavaLabelProvider extends DecoratingLabelProvider { if (disableOverride) { manager.setEnabled(OVERRIDE_DECORATOR_ID, false); } - Image image= super.getImage(element); + Image image = super.getImage(element); if (disableErrorTick) { manager.setEnabled(PROBLEM_DECORATOR_ID, true); } @@ -97,15 +108,20 @@ public class DecoratingJavaLabelProvider extends DecoratingLabelProvider { return super.getImage(element); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object) */ public String getText(Object element) { if (USE_LIGHTWEIGHT) { - IDecoratorManager manager= PlatformUI.getWorkbench().getDecoratorManager(); - - boolean disableErrorTick= manager.getEnabled(PROBLEM_DECORATOR_ID) && !fUseErrorTick; - boolean disableOverride= manager.getEnabled(OVERRIDE_DECORATOR_ID) && !fUseOverride; + IDecoratorManager manager = PlatformUI.getWorkbench() + .getDecoratorManager(); + + boolean disableErrorTick = manager.getEnabled(PROBLEM_DECORATOR_ID) + && !fUseErrorTick; + boolean disableOverride = manager.getEnabled(OVERRIDE_DECORATOR_ID) + && !fUseOverride; try { if (disableErrorTick) { manager.setEnabled(PROBLEM_DECORATOR_ID, false); @@ -113,7 +129,7 @@ public class DecoratingJavaLabelProvider extends DecoratingLabelProvider { if (disableOverride) { manager.setEnabled(OVERRIDE_DECORATOR_ID, false); } - String text= super.getText(element); + String text = super.getText(element); if (disableErrorTick) { manager.setEnabled(PROBLEM_DECORATOR_ID, true); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/FilterUpdater.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/FilterUpdater.java index be7f8fa..f115b51 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/FilterUpdater.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/FilterUpdater.java @@ -17,29 +17,31 @@ import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.swt.widgets.Control; - public class FilterUpdater implements IResourceChangeListener { private StructuredViewer fViewer; - + public FilterUpdater(StructuredViewer viewer) { Assert.isNotNull(viewer); - fViewer= viewer; + fViewer = viewer; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.core.resources.IResourceChangeListener#resourceChanged(org.eclipse.core.resources.IResourceChangeEvent) */ public void resourceChanged(IResourceChangeEvent event) { - IResourceDelta delta= event.getDelta(); + IResourceDelta delta = event.getDelta(); if (delta == null) return; - - IResourceDelta[] projDeltas = delta.getAffectedChildren(IResourceDelta.CHANGED); - for (int i= 0; i < projDeltas.length; i++) { - IResourceDelta pDelta= projDeltas[i]; + + IResourceDelta[] projDeltas = delta + .getAffectedChildren(IResourceDelta.CHANGED); + for (int i = 0; i < projDeltas.length; i++) { + IResourceDelta pDelta = projDeltas[i]; if ((pDelta.getFlags() & IResourceDelta.DESCRIPTION) != 0) { - final Control ctrl= fViewer.getControl(); + final Control ctrl = fViewer.getControl(); if (ctrl != null && !ctrl.isDisposed()) { // async is needed due to bug 33783 ctrl.getDisplay().asyncExec(new Runnable() { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/IProblemChangedListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/IProblemChangedListener.java index ed030b0..948ba8c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/IProblemChangedListener.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/IProblemChangedListener.java @@ -13,19 +13,23 @@ package net.sourceforge.phpdt.internal.ui.viewsupport; import org.eclipse.core.resources.IResource; /** - * Can be added to a ProblemMarkerManager to get notified about problem - * marker changes. Used to update error ticks. + * Can be added to a ProblemMarkerManager to get notified about problem marker + * changes. Used to update error ticks. */ public interface IProblemChangedListener { - + /** - * Called when problems changed. This call is posted in an aynch exec, therefore passed - * resources must not exist. - * @param changedElements A set with elements of type IResource that - * describe the resources that had an problem change. - * @param isMarkerChange If set to true, the change was a marker change, if - * false, the change came from an annotation model modification. + * Called when problems changed. This call is posted in an aynch exec, + * therefore passed resources must not exist. + * + * @param changedElements + * A set with elements of type IResource that + * describe the resources that had an problem change. + * @param isMarkerChange + * If set to true, the change was a marker + * change, if false, the change came from an + * annotation model modification. */ void problemsChanged(IResource[] changedResources, boolean isMarkerChange); - + } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ISelectionListenerWithAST.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ISelectionListenerWithAST.java index d470a99..4bd1312 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ISelectionListenerWithAST.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ISelectionListenerWithAST.java @@ -11,25 +11,30 @@ package net.sourceforge.phpdt.internal.ui.viewsupport; import org.eclipse.jface.text.ITextSelection; - import org.eclipse.ui.IEditorPart; /** - * Listener to be informed on text selection changes in an editor (post selection), including the corresponding AST. - * The AST is shared and must not be modified. - * Listeners can be registered in a SelectionListenerWithASTManager. + * Listener to be informed on text selection changes in an editor (post + * selection), including the corresponding AST. The AST is shared and must not + * be modified. Listeners can be registered in a + * SelectionListenerWithASTManager. */ public interface ISelectionListenerWithAST { /** - * Called when a selection has changed. The method is called in a post selection event in an background - * thread. - * @param part The editor part in which the selection change has occured. - * @param selection The new text selection - * @param astRoot The AST tree corresponding to the editor's input. This AST is shared and must - * not be modified. + * Called when a selection has changed. The method is called in a post + * selection event in an background thread. + * + * @param part + * The editor part in which the selection change has occured. + * @param selection + * The new text selection + * @param astRoot + * The AST tree corresponding to the editor's input. This AST is + * shared and must not be modified. */ void selectionChanged(IEditorPart part, ITextSelection selection); -// void selectionChanged(IEditorPart part, ITextSelection selection, CompilationUnit astRoot); + // void selectionChanged(IEditorPart part, ITextSelection selection, + // CompilationUnit astRoot); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/IViewPartInputProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/IViewPartInputProvider.java index 54764c8..137cd08 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/IViewPartInputProvider.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/IViewPartInputProvider.java @@ -4,10 +4,10 @@ package net.sourceforge.phpdt.internal.ui.viewsupport; * Interface common to all view parts that provide an input. */ public interface IViewPartInputProvider { - + /** * Returns the input. - * + * * @return the input object */ public Object getViewPartInput(); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ImageDescriptorRegistry.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ImageDescriptorRegistry.java index 7a79909..5e1d19d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ImageDescriptorRegistry.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ImageDescriptorRegistry.java @@ -19,46 +19,52 @@ import org.eclipse.swt.widgets.Display; */ public class ImageDescriptorRegistry { - private HashMap fRegistry= new HashMap(10); + private HashMap fRegistry = new HashMap(10); + private Display fDisplay; - + /** - * Creates a new image descriptor registry for the current or default display, - * respectively. + * Creates a new image descriptor registry for the current or default + * display, respectively. */ public ImageDescriptorRegistry() { this(SWTUtil.getStandardDisplay()); } - + /** * Creates a new image descriptor registry for the given display. All images * managed by this registry will be disposed when the display gets disposed. * - * @param diaplay the display the images managed by this registry are allocated for + * @param diaplay + * the display the images managed by this registry are allocated + * for */ public ImageDescriptorRegistry(Display display) { - fDisplay= display; + fDisplay = display; Assert.isNotNull(fDisplay); hookDisplay(); } - + /** * Returns the image assiciated with the given image descriptor. * - * @param descriptor the image descriptor for which the registry manages an image - * @return the image associated with the image descriptor or null - * if the image descriptor can't create the requested image. + * @param descriptor + * the image descriptor for which the registry manages an image + * @return the image associated with the image descriptor or + * null if the image descriptor can't create the + * requested image. */ public Image get(ImageDescriptor descriptor) { if (descriptor == null) - descriptor= ImageDescriptor.getMissingImageDescriptor(); - - Image result= (Image)fRegistry.get(descriptor); + descriptor = ImageDescriptor.getMissingImageDescriptor(); + + Image result = (Image) fRegistry.get(descriptor); if (result != null) return result; - - Assert.isTrue(fDisplay == SWTUtil.getStandardDisplay(), "Allocating image for wrong display."); //$NON-NLS-1$ - result= descriptor.createImage(); + + Assert.isTrue(fDisplay == SWTUtil.getStandardDisplay(), + "Allocating image for wrong display."); //$NON-NLS-1$ + result = descriptor.createImage(); if (result != null) fRegistry.put(descriptor, result); return result; @@ -66,21 +72,20 @@ public class ImageDescriptorRegistry { /** * Disposes all images managed by this registry. - */ + */ public void dispose() { - for (Iterator iter= fRegistry.values().iterator(); iter.hasNext(); ) { - Image image= (Image)iter.next(); + for (Iterator iter = fRegistry.values().iterator(); iter.hasNext();) { + Image image = (Image) iter.next(); image.dispose(); } fRegistry.clear(); } - + private void hookDisplay() { fDisplay.disposeExec(new Runnable() { public void run() { dispose(); - } + } }); } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ImageImageDescriptor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ImageImageDescriptor.java index bdb770a..f49ca9f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ImageImageDescriptor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ImageImageDescriptor.java @@ -15,7 +15,7 @@ import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; /** - */ + */ public class ImageImageDescriptor extends ImageDescriptor { private Image fImage; @@ -25,24 +25,31 @@ public class ImageImageDescriptor extends ImageDescriptor { */ public ImageImageDescriptor(Image image) { super(); - fImage= image; + fImage = image; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see ImageDescriptor#getImageData() */ public ImageData getImageData() { return fImage.getImageData(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see Object#equals(Object) */ public boolean equals(Object obj) { - return (obj != null) && getClass().equals(obj.getClass()) && fImage.equals(((ImageImageDescriptor)obj).fImage); + return (obj != null) && getClass().equals(obj.getClass()) + && fImage.equals(((ImageImageDescriptor) obj).fImage); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see Object#hashCode() */ public int hashCode() { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaElementImageProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaElementImageProvider.java index 627a491..5433e55 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaElementImageProvider.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaElementImageProvider.java @@ -36,386 +36,424 @@ import org.eclipse.ui.ide.IDE.SharedImages; import org.eclipse.ui.model.IWorkbenchAdapter; /** - * Default strategy of the Java plugin for the construction of Java element icons. + * Default strategy of the Java plugin for the construction of Java element + * icons. */ public class JavaElementImageProvider { - /** - * Flags for the JavaImageLabelProvider: - * Generate images with overlays. - */ - public final static int OVERLAY_ICONS = 0x1; - - /** - * Generate small sized images. - */ - public final static int SMALL_ICONS = 0x2; - - /** - * Use the 'light' style for rendering types. - */ - public final static int LIGHT_TYPE_ICONS = 0x4; - - public static final Point SMALL_SIZE = new Point(16, 16); - public static final Point BIG_SIZE = new Point(22, 16); - - private static ImageDescriptor DESC_OBJ_PROJECT_CLOSED; - private static ImageDescriptor DESC_OBJ_PROJECT; - private static ImageDescriptor DESC_OBJ_FOLDER; - { - ISharedImages images = PHPeclipsePlugin.getDefault().getWorkbench().getSharedImages(); - DESC_OBJ_PROJECT_CLOSED = images.getImageDescriptor(SharedImages.IMG_OBJ_PROJECT_CLOSED); - DESC_OBJ_PROJECT = images.getImageDescriptor(SharedImages.IMG_OBJ_PROJECT); - DESC_OBJ_FOLDER = images.getImageDescriptor(ISharedImages.IMG_OBJ_FOLDER); - } - - private ImageDescriptorRegistry fRegistry; - - public JavaElementImageProvider() { - fRegistry = null; // lazy initialization - } - - /** - * Returns the icon for a given element. The icon depends on the element type - * and element properties. If configured, overlay icons are constructed for - * ISourceReferences. - * @param flags Flags as defined by the JavaImageLabelProvider - */ - public Image getImageLabel(Object element, int flags) { - return getImageLabel(computeDescriptor(element, flags)); - } - - private Image getImageLabel(ImageDescriptor descriptor) { - if (descriptor == null) - return null; - return getRegistry().get(descriptor); - } - - private ImageDescriptorRegistry getRegistry() { - if (fRegistry == null) { - fRegistry = PHPeclipsePlugin.getImageDescriptorRegistry(); - } - return fRegistry; - } - - private ImageDescriptor computeDescriptor(Object element, int flags) { - if (element instanceof IJavaElement) { - return getJavaImageDescriptor((IJavaElement) element, flags); - } else if (element instanceof IFile) { - IFile file = (IFile) element; - if ("java".equals(file.getFileExtension())) { //$NON-NLS-1$ - return getCUResourceImageDescriptor(file, flags); // image for a CU not on the build path - } - return getWorkbenchImageDescriptor(file, flags); - } else if (element instanceof IAdaptable) { - return getWorkbenchImageDescriptor((IAdaptable) element, flags); - } - return null; - } - - private static boolean showOverlayIcons(int flags) { - return (flags & OVERLAY_ICONS) != 0; - } - - private static boolean useSmallSize(int flags) { - return (flags & SMALL_ICONS) != 0; - } - - private static boolean useLightIcons(int flags) { - return (flags & LIGHT_TYPE_ICONS) != 0; - } - - /** - * Returns an image descriptor for a compilatio unit not on the class path. - * The descriptor includes overlays, if specified. - */ - public ImageDescriptor getCUResourceImageDescriptor(IFile file, int flags) { - Point size = useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE; - return new JavaElementImageDescriptor(PHPUiImages.DESC_OBJS_CUNIT_RESOURCE, 0, size); - } - - /** - * Returns an image descriptor for a java element. The descriptor includes overlays, if specified. - */ - public ImageDescriptor getJavaImageDescriptor(IJavaElement element, int flags) { - int adornmentFlags = computeJavaAdornmentFlags(element, flags); - Point size = useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE; - return new JavaElementImageDescriptor(getBaseImageDescriptor(element, flags), adornmentFlags, size); - } - - /** - * Returns an image descriptor for a IAdaptable. The descriptor includes overlays, if specified (only error ticks apply). - * Returns null if no image could be found. - */ - public ImageDescriptor getWorkbenchImageDescriptor(IAdaptable adaptable, int flags) { - IWorkbenchAdapter wbAdapter = (IWorkbenchAdapter) adaptable.getAdapter(IWorkbenchAdapter.class); - if (wbAdapter == null) { - return null; - } - ImageDescriptor descriptor = wbAdapter.getImageDescriptor(adaptable); - if (descriptor == null) { - return null; - } - - Point size = useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE; - return new JavaElementImageDescriptor(descriptor, 0, size); - } - - // ---- Computation of base image key ------------------------------------------------- - - /** - * Returns an image descriptor for a java element. This is the base image, no overlays. - */ - public ImageDescriptor getBaseImageDescriptor(IJavaElement element, int renderFlags) { + /** + * Flags for the JavaImageLabelProvider: Generate images with overlays. + */ + public final static int OVERLAY_ICONS = 0x1; + + /** + * Generate small sized images. + */ + public final static int SMALL_ICONS = 0x2; + + /** + * Use the 'light' style for rendering types. + */ + public final static int LIGHT_TYPE_ICONS = 0x4; + + public static final Point SMALL_SIZE = new Point(16, 16); + + public static final Point BIG_SIZE = new Point(22, 16); + + private static ImageDescriptor DESC_OBJ_PROJECT_CLOSED; + + private static ImageDescriptor DESC_OBJ_PROJECT; + + private static ImageDescriptor DESC_OBJ_FOLDER; + { + ISharedImages images = PHPeclipsePlugin.getDefault().getWorkbench() + .getSharedImages(); + DESC_OBJ_PROJECT_CLOSED = images + .getImageDescriptor(SharedImages.IMG_OBJ_PROJECT_CLOSED); + DESC_OBJ_PROJECT = images + .getImageDescriptor(SharedImages.IMG_OBJ_PROJECT); + DESC_OBJ_FOLDER = images + .getImageDescriptor(ISharedImages.IMG_OBJ_FOLDER); + } + + private ImageDescriptorRegistry fRegistry; + + public JavaElementImageProvider() { + fRegistry = null; // lazy initialization + } + + /** + * Returns the icon for a given element. The icon depends on the element + * type and element properties. If configured, overlay icons are constructed + * for ISourceReferences. + * + * @param flags + * Flags as defined by the JavaImageLabelProvider + */ + public Image getImageLabel(Object element, int flags) { + return getImageLabel(computeDescriptor(element, flags)); + } + + private Image getImageLabel(ImageDescriptor descriptor) { + if (descriptor == null) + return null; + return getRegistry().get(descriptor); + } + + private ImageDescriptorRegistry getRegistry() { + if (fRegistry == null) { + fRegistry = PHPeclipsePlugin.getImageDescriptorRegistry(); + } + return fRegistry; + } + + private ImageDescriptor computeDescriptor(Object element, int flags) { + if (element instanceof IJavaElement) { + return getJavaImageDescriptor((IJavaElement) element, flags); + } else if (element instanceof IFile) { + IFile file = (IFile) element; + if ("java".equals(file.getFileExtension())) { //$NON-NLS-1$ + return getCUResourceImageDescriptor(file, flags); // image for + // a CU not + // on the + // build + // path + } + return getWorkbenchImageDescriptor(file, flags); + } else if (element instanceof IAdaptable) { + return getWorkbenchImageDescriptor((IAdaptable) element, flags); + } + return null; + } + + private static boolean showOverlayIcons(int flags) { + return (flags & OVERLAY_ICONS) != 0; + } + + private static boolean useSmallSize(int flags) { + return (flags & SMALL_ICONS) != 0; + } + + private static boolean useLightIcons(int flags) { + return (flags & LIGHT_TYPE_ICONS) != 0; + } + + /** + * Returns an image descriptor for a compilatio unit not on the class path. + * The descriptor includes overlays, if specified. + */ + public ImageDescriptor getCUResourceImageDescriptor(IFile file, int flags) { + Point size = useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE; + return new JavaElementImageDescriptor( + PHPUiImages.DESC_OBJS_CUNIT_RESOURCE, 0, size); + } + + /** + * Returns an image descriptor for a java element. The descriptor includes + * overlays, if specified. + */ + public ImageDescriptor getJavaImageDescriptor(IJavaElement element, + int flags) { + int adornmentFlags = computeJavaAdornmentFlags(element, flags); + Point size = useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE; + return new JavaElementImageDescriptor(getBaseImageDescriptor(element, + flags), adornmentFlags, size); + } + + /** + * Returns an image descriptor for a IAdaptable. The descriptor includes + * overlays, if specified (only error ticks apply). Returns + * null if no image could be found. + */ + public ImageDescriptor getWorkbenchImageDescriptor(IAdaptable adaptable, + int flags) { + IWorkbenchAdapter wbAdapter = (IWorkbenchAdapter) adaptable + .getAdapter(IWorkbenchAdapter.class); + if (wbAdapter == null) { + return null; + } + ImageDescriptor descriptor = wbAdapter.getImageDescriptor(adaptable); + if (descriptor == null) { + return null; + } + + Point size = useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE; + return new JavaElementImageDescriptor(descriptor, 0, size); + } + + // ---- Computation of base image key + // ------------------------------------------------- + + /** + * Returns an image descriptor for a java element. This is the base image, + * no overlays. + */ + public ImageDescriptor getBaseImageDescriptor(IJavaElement element, + int renderFlags) { IType type = null; boolean isInterface = false; - try { - switch (element.getElementType()) { - case IJavaElement.INITIALIZER : - return PHPUiImages.DESC_MISC_PRIVATE; // 23479 - case IJavaElement.METHOD : - IMember member = (IMember) element; - type = member.getDeclaringType(); - isInterface = (type != null) && member.getDeclaringType().isInterface(); - return getMethodImageDescriptor(isInterface, member.getFlags()); - case IJavaElement.FIELD : - IField field = (IField) element; - return getFieldImageDescriptor(field.getDeclaringType().isInterface(), field.getFlags()); - - case IJavaElement.PACKAGE_DECLARATION : - return PHPUiImages.DESC_OBJS_PACKDECL; - - case IJavaElement.IMPORT_DECLARATION : - return PHPUiImages.DESC_OBJS_IMPDECL; - - case IJavaElement.IMPORT_CONTAINER : - return PHPUiImages.DESC_OBJS_IMPCONT; - - case IJavaElement.TYPE : - { - type = (IType) element; - isInterface = type.isInterface(); - - if (useLightIcons(renderFlags)) { - return isInterface ? PHPUiImages.DESC_OBJS_INTERFACEALT : PHPUiImages.DESC_OBJS_CLASSALT; - } - boolean isInner = type.getDeclaringType() != null; - return getTypeImageDescriptor(isInterface, isInner, type.getFlags()); - } - - case IJavaElement.PACKAGE_FRAGMENT_ROOT : - { - IPackageFragmentRoot root = (IPackageFragmentRoot) element; - // if (root.isArchive()) { - // IPath attach= root.getSourceAttachmentPath(); - // if (root.isExternal()) { - // if (attach == null) { - // return PHPUiImages.DESC_OBJS_EXTJAR; - // } else { - // return PHPUiImages.DESC_OBJS_EXTJAR_WSRC; - // } - // } else { - // if (attach == null) { - // return PHPUiImages.DESC_OBJS_JAR; - // } else { - // return PHPUiImages.DESC_OBJS_JAR_WSRC; - // } - // } - // } else { - return PHPUiImages.DESC_OBJS_PACKFRAG_ROOT; - // } - } - - case IJavaElement.PACKAGE_FRAGMENT : - return getPackageFragmentIcon(element, renderFlags); - - case IJavaElement.COMPILATION_UNIT : - return PHPUiImages.DESC_OBJS_CUNIT; - - case IJavaElement.CLASS_FILE : - /* this is too expensive for large packages - try { - IClassFile cfile= (IClassFile)element; - if (cfile.isClass()) - return PHPUiImages.IMG_OBJS_CFILECLASS; - return PHPUiImages.IMG_OBJS_CFILEINT; - } catch(JavaModelException e) { - // fall through; - }*/ - return PHPUiImages.DESC_OBJS_CFILE; - - case IJavaElement.JAVA_PROJECT : - IJavaProject jp = (IJavaProject) element; - if (jp.getProject().isOpen()) { - IProject project = jp.getProject(); - IWorkbenchAdapter adapter = (IWorkbenchAdapter) project.getAdapter(IWorkbenchAdapter.class); - if (adapter != null) { - ImageDescriptor result = adapter.getImageDescriptor(project); - if (result != null) - return result; - } - return DESC_OBJ_PROJECT; - } - return DESC_OBJ_PROJECT_CLOSED; - - case IJavaElement.JAVA_MODEL : - return PHPUiImages.DESC_OBJS_JAVA_MODEL; - } - - Assert.isTrue(false, PHPUIMessages.getString("JavaImageLabelprovider.assert.wrongImage")); //$NON-NLS-1$ - return null; //$NON-NLS-1$ - - } catch (JavaModelException e) { - if (e.isDoesNotExist()) - return PHPUiImages.DESC_OBJS_UNKNOWN; - PHPeclipsePlugin.log(e); - return PHPUiImages.DESC_OBJS_GHOST; - } - } - - protected ImageDescriptor getPackageFragmentIcon(IJavaElement element, int renderFlags) throws JavaModelException { - // IPackageFragment fragment= (IPackageFragment)element; - // boolean containsJavaElements= false; - // try { - // containsJavaElements= fragment.hasChildren(); - // } catch(JavaModelException e) { - // // assuming no children; - // } - // if(!containsJavaElements && (fragment.getNonJavaResources().length > 0)) - // return PHPUiImages.DESC_OBJS_EMPTY_PACKAGE_RESOURCES; - // else if (!containsJavaElements) - // return PHPUiImages.DESC_OBJS_EMPTY_PACKAGE; - return PHPUiImages.DESC_OBJS_PACKAGE; - } - - public void dispose() { - } - - // ---- Methods to compute the adornments flags --------------------------------- - - private int computeJavaAdornmentFlags(IJavaElement element, int renderFlags) { - int flags = 0; - if (showOverlayIcons(renderFlags) && element instanceof IMember) { - try { - IMember member = (IMember) element; - - if (element.getElementType() == IJavaElement.METHOD && ((IMethod) element).isConstructor()) - flags |= JavaElementImageDescriptor.CONSTRUCTOR; - - int modifiers = member.getFlags(); - if (Flags.isAbstract(modifiers) && confirmAbstract(member)) - flags |= JavaElementImageDescriptor.ABSTRACT; - if (Flags.isFinal(modifiers) || isInterfaceField(member)) - flags |= JavaElementImageDescriptor.FINAL; - // if (Flags.isSynchronized(modifiers) && confirmSynchronized(member)) - // flags |= JavaElementImageDescriptor.SYNCHRONIZED; - if (Flags.isStatic(modifiers) || isInterfaceField(member)) - flags |= JavaElementImageDescriptor.STATIC; - - // if (member.getElementType() == IJavaElement.TYPE) { - // if (JavaModelUtil.hasMainMethod((IType) member)) { - // flags |= JavaElementImageDescriptor.RUNNABLE; - // } - // } - } catch (JavaModelException e) { - // do nothing. Can't compute runnable adornment or get flags - } - } - return flags; - } - - private static boolean confirmAbstract(IMember element) throws JavaModelException { - // never show the abstract symbol on interfaces or members in interfaces - if (element.getElementType() == IJavaElement.TYPE) { - return ((IType) element).isClass(); - } - return element.getDeclaringType().isClass(); - } - - private static boolean isInterfaceField(IMember element) throws JavaModelException { - // always show the final && static symbol on interface fields - if (element.getElementType() == IJavaElement.FIELD) { - return element.getDeclaringType().isInterface(); - } - return false; - } - - private static boolean confirmSynchronized(IJavaElement member) { - // Synchronized types are allowed but meaningless. - return member.getElementType() != IJavaElement.TYPE; - } - - public static ImageDescriptor getMethodImageDescriptor(boolean isInInterface, int flags) { - if (Flags.isPublic(flags) || isInInterface) - return PHPUiImages.DESC_MISC_PUBLIC; - if (Flags.isProtected(flags)) - return PHPUiImages.DESC_MISC_PROTECTED; - if (Flags.isPrivate(flags)) - return PHPUiImages.DESC_MISC_PRIVATE; - - return PHPUiImages.DESC_MISC_DEFAULT; - } - - public static ImageDescriptor getFieldImageDescriptor(boolean isInInterface, int flags) { - if (Flags.isPublic(flags) || isInInterface) - return PHPUiImages.DESC_FIELD_PUBLIC; - if (Flags.isProtected(flags)) - return PHPUiImages.DESC_FIELD_PROTECTED; - if (Flags.isPrivate(flags)) - return PHPUiImages.DESC_FIELD_PRIVATE; - - return PHPUiImages.DESC_FIELD_DEFAULT; - } - - public static ImageDescriptor getTypeImageDescriptor(boolean isInterface, boolean isInner, int flags) { - if (isInner) { - if (isInterface) { - return getInnerInterfaceImageDescriptor(flags); - } else { - return getInnerClassImageDescriptor(flags); - } - } else { - if (isInterface) { - return getInterfaceImageDescriptor(flags); - } else { - return getClassImageDescriptor(flags); - } - } - } - - private static ImageDescriptor getClassImageDescriptor(int flags) { - if (Flags.isPublic(flags) || Flags.isProtected(flags) || Flags.isPrivate(flags)) - return PHPUiImages.DESC_OBJS_CLASS; - else - return PHPUiImages.DESC_OBJS_CLASS_DEFAULT; - } - - private static ImageDescriptor getInnerClassImageDescriptor(int flags) { - if (Flags.isPublic(flags)) - return PHPUiImages.DESC_OBJS_INNER_CLASS_PUBLIC; - else if (Flags.isPrivate(flags)) - return PHPUiImages.DESC_OBJS_INNER_CLASS_PRIVATE; - else if (Flags.isProtected(flags)) - return PHPUiImages.DESC_OBJS_INNER_CLASS_PROTECTED; - else - return PHPUiImages.DESC_OBJS_INNER_CLASS_DEFAULT; - } - - private static ImageDescriptor getInterfaceImageDescriptor(int flags) { - if (Flags.isPublic(flags) || Flags.isProtected(flags) || Flags.isPrivate(flags)) - return PHPUiImages.DESC_OBJS_INTERFACE; - else - return PHPUiImages.DESC_OBJS_INTERFACE_DEFAULT; - } - - private static ImageDescriptor getInnerInterfaceImageDescriptor(int flags) { - if (Flags.isPublic(flags)) - return PHPUiImages.DESC_OBJS_INNER_INTERFACE_PUBLIC; - else if (Flags.isPrivate(flags)) - return PHPUiImages.DESC_OBJS_INNER_INTERFACE_PRIVATE; - else if (Flags.isProtected(flags)) - return PHPUiImages.DESC_OBJS_INNER_INTERFACE_PROTECTED; - else - return PHPUiImages.DESC_OBJS_INTERFACE_DEFAULT; - } + try { + switch (element.getElementType()) { + case IJavaElement.INITIALIZER: + return PHPUiImages.DESC_MISC_PRIVATE; // 23479 + case IJavaElement.METHOD: + IMember member = (IMember) element; + type = member.getDeclaringType(); + isInterface = (type != null) + && member.getDeclaringType().isInterface(); + return getMethodImageDescriptor(isInterface, member.getFlags()); + case IJavaElement.FIELD: + IField field = (IField) element; + return getFieldImageDescriptor(field.getDeclaringType() + .isInterface(), field.getFlags()); + + case IJavaElement.PACKAGE_DECLARATION: + return PHPUiImages.DESC_OBJS_PACKDECL; + + case IJavaElement.IMPORT_DECLARATION: + return PHPUiImages.DESC_OBJS_IMPDECL; + + case IJavaElement.IMPORT_CONTAINER: + return PHPUiImages.DESC_OBJS_IMPCONT; + + case IJavaElement.TYPE: { + type = (IType) element; + isInterface = type.isInterface(); + + if (useLightIcons(renderFlags)) { + return isInterface ? PHPUiImages.DESC_OBJS_INTERFACEALT + : PHPUiImages.DESC_OBJS_CLASSALT; + } + boolean isInner = type.getDeclaringType() != null; + return getTypeImageDescriptor(isInterface, isInner, type + .getFlags()); + } + + case IJavaElement.PACKAGE_FRAGMENT_ROOT: { + IPackageFragmentRoot root = (IPackageFragmentRoot) element; + // if (root.isArchive()) { + // IPath attach= root.getSourceAttachmentPath(); + // if (root.isExternal()) { + // if (attach == null) { + // return PHPUiImages.DESC_OBJS_EXTJAR; + // } else { + // return PHPUiImages.DESC_OBJS_EXTJAR_WSRC; + // } + // } else { + // if (attach == null) { + // return PHPUiImages.DESC_OBJS_JAR; + // } else { + // return PHPUiImages.DESC_OBJS_JAR_WSRC; + // } + // } + // } else { + return PHPUiImages.DESC_OBJS_PACKFRAG_ROOT; + // } + } + + case IJavaElement.PACKAGE_FRAGMENT: + return getPackageFragmentIcon(element, renderFlags); + + case IJavaElement.COMPILATION_UNIT: + return PHPUiImages.DESC_OBJS_CUNIT; + + case IJavaElement.CLASS_FILE: + /* + * this is too expensive for large packages try { IClassFile + * cfile= (IClassFile)element; if (cfile.isClass()) return + * PHPUiImages.IMG_OBJS_CFILECLASS; return + * PHPUiImages.IMG_OBJS_CFILEINT; } catch(JavaModelException e) { // + * fall through; } + */ + return PHPUiImages.DESC_OBJS_CFILE; + + case IJavaElement.JAVA_PROJECT: + IJavaProject jp = (IJavaProject) element; + if (jp.getProject().isOpen()) { + IProject project = jp.getProject(); + IWorkbenchAdapter adapter = (IWorkbenchAdapter) project + .getAdapter(IWorkbenchAdapter.class); + if (adapter != null) { + ImageDescriptor result = adapter + .getImageDescriptor(project); + if (result != null) + return result; + } + return DESC_OBJ_PROJECT; + } + return DESC_OBJ_PROJECT_CLOSED; + + case IJavaElement.JAVA_MODEL: + return PHPUiImages.DESC_OBJS_JAVA_MODEL; + } + + Assert.isTrue(false, PHPUIMessages + .getString("JavaImageLabelprovider.assert.wrongImage")); //$NON-NLS-1$ + return null; //$NON-NLS-1$ + + } catch (JavaModelException e) { + if (e.isDoesNotExist()) + return PHPUiImages.DESC_OBJS_UNKNOWN; + PHPeclipsePlugin.log(e); + return PHPUiImages.DESC_OBJS_GHOST; + } + } + + protected ImageDescriptor getPackageFragmentIcon(IJavaElement element, + int renderFlags) throws JavaModelException { + // IPackageFragment fragment= (IPackageFragment)element; + // boolean containsJavaElements= false; + // try { + // containsJavaElements= fragment.hasChildren(); + // } catch(JavaModelException e) { + // // assuming no children; + // } + // if(!containsJavaElements && (fragment.getNonJavaResources().length > + // 0)) + // return PHPUiImages.DESC_OBJS_EMPTY_PACKAGE_RESOURCES; + // else if (!containsJavaElements) + // return PHPUiImages.DESC_OBJS_EMPTY_PACKAGE; + return PHPUiImages.DESC_OBJS_PACKAGE; + } + + public void dispose() { + } + + // ---- Methods to compute the adornments flags + // --------------------------------- + + private int computeJavaAdornmentFlags(IJavaElement element, int renderFlags) { + int flags = 0; + if (showOverlayIcons(renderFlags) && element instanceof IMember) { + try { + IMember member = (IMember) element; + + if (element.getElementType() == IJavaElement.METHOD + && ((IMethod) element).isConstructor()) + flags |= JavaElementImageDescriptor.CONSTRUCTOR; + + int modifiers = member.getFlags(); + if (Flags.isAbstract(modifiers) && confirmAbstract(member)) + flags |= JavaElementImageDescriptor.ABSTRACT; + if (Flags.isFinal(modifiers) || isInterfaceField(member)) + flags |= JavaElementImageDescriptor.FINAL; + // if (Flags.isSynchronized(modifiers) && + // confirmSynchronized(member)) + // flags |= JavaElementImageDescriptor.SYNCHRONIZED; + if (Flags.isStatic(modifiers) || isInterfaceField(member)) + flags |= JavaElementImageDescriptor.STATIC; + + // if (member.getElementType() == IJavaElement.TYPE) { + // if (JavaModelUtil.hasMainMethod((IType) member)) { + // flags |= JavaElementImageDescriptor.RUNNABLE; + // } + // } + } catch (JavaModelException e) { + // do nothing. Can't compute runnable adornment or get flags + } + } + return flags; + } + + private static boolean confirmAbstract(IMember element) + throws JavaModelException { + // never show the abstract symbol on interfaces or members in interfaces + if (element.getElementType() == IJavaElement.TYPE) { + return ((IType) element).isClass(); + } + return element.getDeclaringType().isClass(); + } + + private static boolean isInterfaceField(IMember element) + throws JavaModelException { + // always show the final && static symbol on interface fields + if (element.getElementType() == IJavaElement.FIELD) { + return element.getDeclaringType().isInterface(); + } + return false; + } + + private static boolean confirmSynchronized(IJavaElement member) { + // Synchronized types are allowed but meaningless. + return member.getElementType() != IJavaElement.TYPE; + } + + public static ImageDescriptor getMethodImageDescriptor( + boolean isInInterface, int flags) { + if (Flags.isPublic(flags) || isInInterface) + return PHPUiImages.DESC_MISC_PUBLIC; + if (Flags.isProtected(flags)) + return PHPUiImages.DESC_MISC_PROTECTED; + if (Flags.isPrivate(flags)) + return PHPUiImages.DESC_MISC_PRIVATE; + + return PHPUiImages.DESC_MISC_DEFAULT; + } + + public static ImageDescriptor getFieldImageDescriptor( + boolean isInInterface, int flags) { + if (Flags.isPublic(flags) || isInInterface) + return PHPUiImages.DESC_FIELD_PUBLIC; + if (Flags.isProtected(flags)) + return PHPUiImages.DESC_FIELD_PROTECTED; + if (Flags.isPrivate(flags)) + return PHPUiImages.DESC_FIELD_PRIVATE; + + return PHPUiImages.DESC_FIELD_DEFAULT; + } + + public static ImageDescriptor getTypeImageDescriptor(boolean isInterface, + boolean isInner, int flags) { + if (isInner) { + if (isInterface) { + return getInnerInterfaceImageDescriptor(flags); + } else { + return getInnerClassImageDescriptor(flags); + } + } else { + if (isInterface) { + return getInterfaceImageDescriptor(flags); + } else { + return getClassImageDescriptor(flags); + } + } + } + + private static ImageDescriptor getClassImageDescriptor(int flags) { + if (Flags.isPublic(flags) || Flags.isProtected(flags) + || Flags.isPrivate(flags)) + return PHPUiImages.DESC_OBJS_CLASS; + else + return PHPUiImages.DESC_OBJS_CLASS_DEFAULT; + } + + private static ImageDescriptor getInnerClassImageDescriptor(int flags) { + if (Flags.isPublic(flags)) + return PHPUiImages.DESC_OBJS_INNER_CLASS_PUBLIC; + else if (Flags.isPrivate(flags)) + return PHPUiImages.DESC_OBJS_INNER_CLASS_PRIVATE; + else if (Flags.isProtected(flags)) + return PHPUiImages.DESC_OBJS_INNER_CLASS_PROTECTED; + else + return PHPUiImages.DESC_OBJS_INNER_CLASS_DEFAULT; + } + + private static ImageDescriptor getInterfaceImageDescriptor(int flags) { + if (Flags.isPublic(flags) || Flags.isProtected(flags) + || Flags.isPrivate(flags)) + return PHPUiImages.DESC_OBJS_INTERFACE; + else + return PHPUiImages.DESC_OBJS_INTERFACE_DEFAULT; + } + + private static ImageDescriptor getInnerInterfaceImageDescriptor(int flags) { + if (Flags.isPublic(flags)) + return PHPUiImages.DESC_OBJS_INNER_INTERFACE_PUBLIC; + else if (Flags.isPrivate(flags)) + return PHPUiImages.DESC_OBJS_INNER_INTERFACE_PRIVATE; + else if (Flags.isProtected(flags)) + return PHPUiImages.DESC_OBJS_INNER_INTERFACE_PROTECTED; + else + return PHPUiImages.DESC_OBJS_INTERFACE_DEFAULT; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaElementLabels.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaElementLabels.java index 325d623..801580e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaElementLabels.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaElementLabels.java @@ -32,734 +32,780 @@ import org.eclipse.ui.model.IWorkbenchAdapter; public class JavaElementLabels { - /** - * Method names contain parameter types. - * e.g. foo(int) - */ - public final static int M_PARAMETER_TYPES = 1 << 0; - - /** - * Method names contain parameter names. - * e.g. foo(index) - */ - public final static int M_PARAMETER_NAMES = 1 << 1; - - /** - * Method names contain thrown exceptions. - * e.g. foo throws IOException - */ - public final static int M_EXCEPTIONS = 1 << 2; - - /** - * Method names contain return type (appended) - * e.g. foo : int - */ - public final static int M_APP_RETURNTYPE = 1 << 3; - - /** - * Method names contain return type (appended) - * e.g. int foo - */ - public final static int M_PRE_RETURNTYPE = 1 << 4; - - /** - * Method names are fully qualified. - * e.g. java.util.Vector.size - */ - public final static int M_FULLY_QUALIFIED = 1 << 5; - - /** - * Method names are post qualified. - * e.g. size - java.util.Vector - */ - public final static int M_POST_QUALIFIED = 1 << 6; - - /** - * Initializer names are fully qualified. - * e.g. java.util.Vector.{ ... } - */ - public final static int I_FULLY_QUALIFIED = 1 << 7; - - /** - * Type names are post qualified. - * e.g. { ... } - java.util.Map - */ - public final static int I_POST_QUALIFIED = 1 << 8; - - /** - * Field names contain the declared type (appended) - * e.g. int fHello - */ - public final static int F_APP_TYPE_SIGNATURE = 1 << 9; - - /** - * Field names contain the declared type (prepended) - * e.g. fHello : int - */ - public final static int F_PRE_TYPE_SIGNATURE = 1 << 10; - - /** - * Fields names are fully qualified. - * e.g. java.lang.System.out - */ - public final static int F_FULLY_QUALIFIED = 1 << 11; - - /** - * Fields names are post qualified. - * e.g. out - java.lang.System - */ - public final static int F_POST_QUALIFIED = 1 << 12; - - /** - * Type names are fully qualified. - * e.g. java.util.Map.MapEntry - */ - public final static int T_FULLY_QUALIFIED = 1 << 13; - - /** - * Type names are type container qualified. - * e.g. Map.MapEntry - */ - public final static int T_CONTAINER_QUALIFIED = 1 << 14; - - /** - * Type names are post qualified. - * e.g. MapEntry - java.util.Map - */ - public final static int T_POST_QUALIFIED = 1 << 15; - - /** - * Declarations (import container / declarartion, package declarartion) are qualified. - * e.g. java.util.Vector.class/import container - */ - public final static int D_QUALIFIED = 1 << 16; - - /** - * Declarations (import container / declarartion, package declarartion) are post qualified. - * e.g. import container - java.util.Vector.class - */ - public final static int D_POST_QUALIFIED = 1 << 17; - - /** - * Class file names are fully qualified. - * e.g. java.util.Vector.class - */ - public final static int CF_QUALIFIED = 1 << 18; - - /** - * Class file names are post qualified. - * e.g. Vector.class - java.util - */ - public final static int CF_POST_QUALIFIED = 1 << 19; - - /** - * Compilation unit names are fully qualified. - * e.g. java.util.Vector.java - */ - public final static int CU_QUALIFIED = 1 << 20; - - /** - * Compilation unit names are post qualified. - * e.g. Vector.java - java.util - */ - public final static int CU_POST_QUALIFIED = 1 << 21; - - /** - * Package names are qualified. - * e.g. MyProject/src/java.util - */ - public final static int P_QUALIFIED = 1 << 22; - - /** - * Package names are post qualified. - * e.g. java.util - MyProject/src - */ - public final static int P_POST_QUALIFIED = 1 << 23; - - /** - * Package Fragment Roots contain variable name if from a variable. - * e.g. JRE_LIB - c:\java\lib\rt.jar - */ - public final static int ROOT_VARIABLE = 1 << 24; - - /** - * Package Fragment Roots contain the project name if not an archive (prepended). - * e.g. MyProject/src - */ - public final static int ROOT_QUALIFIED = 1 << 25; - - /** - * Package Fragment Roots contain the project name if not an archive (appended). - * e.g. src - MyProject - */ - public final static int ROOT_POST_QUALIFIED = 1 << 26; - - /** - * Add root path to all elements except Package Fragment Roots and Java projects. - * e.g. java.lang.Vector - c:\java\lib\rt.jar - * Option only applies to getElementLabel - */ - public final static int APPEND_ROOT_PATH = 1 << 27; - - /** - * Add root path to all elements except Package Fragment Roots and Java projects. - * e.g. java.lang.Vector - c:\java\lib\rt.jar - * Option only applies to getElementLabel - */ - public final static int PREPEND_ROOT_PATH = 1 << 28; - - /** - * Package names are compressed. - * e.g. o*.e*.search - */ - public final static int P_COMPRESSED = 1 << 29; - - /** - * Post qualify referenced package fragement roots. For example - * jdt.jar - net.sourceforge.phpdt.ui if the jar is referenced - * from another project. - */ - public final static int REFERENCED_ROOT_POST_QUALIFIED = 1 << 30; - - /** - * Qualify all elements - */ - public final static int ALL_FULLY_QUALIFIED = - F_FULLY_QUALIFIED - | M_FULLY_QUALIFIED - | I_FULLY_QUALIFIED - | T_FULLY_QUALIFIED - | D_QUALIFIED - | CF_QUALIFIED - | CU_QUALIFIED - | P_QUALIFIED - | ROOT_QUALIFIED; - - /** - * Post qualify all elements - */ - public final static int ALL_POST_QUALIFIED = - F_POST_QUALIFIED - | M_POST_QUALIFIED - | I_POST_QUALIFIED - | T_POST_QUALIFIED - | D_POST_QUALIFIED - | CF_POST_QUALIFIED - | CU_POST_QUALIFIED - | P_POST_QUALIFIED - | ROOT_POST_QUALIFIED; - - /** - * Default options (M_PARAMETER_TYPES enabled) - */ - public final static int ALL_DEFAULT = M_PARAMETER_TYPES; - - /** - * Default qualify options (All except Root and Package) - */ - public final static int DEFAULT_QUALIFIED = - F_FULLY_QUALIFIED | M_FULLY_QUALIFIED | I_FULLY_QUALIFIED | T_FULLY_QUALIFIED | D_QUALIFIED | CF_QUALIFIED | CU_QUALIFIED; - - /** - * Default post qualify options (All except Root and Package) - */ - public final static int DEFAULT_POST_QUALIFIED = - F_POST_QUALIFIED - | M_POST_QUALIFIED - | I_POST_QUALIFIED - | T_POST_QUALIFIED - | D_POST_QUALIFIED - | CF_POST_QUALIFIED - | CU_POST_QUALIFIED; - - public final static String CONCAT_STRING = PHPUIMessages.getString("JavaElementLabels.concat_string"); // " - "; //$NON-NLS-1$ - public final static String COMMA_STRING = PHPUIMessages.getString("JavaElementLabels.comma_string"); // ", "; //$NON-NLS-1$ - public final static String DECL_STRING = PHPUIMessages.getString("JavaElementLabels.declseparator_string"); // " "; // use for return type //$NON-NLS-1$ - - /* - * Package name compression - */ - private static String fgPkgNamePattern = ""; //$NON-NLS-1$ - private static String fgPkgNamePrefix; - private static String fgPkgNamePostfix; - private static int fgPkgNameChars; - private static int fgPkgNameLength = -1; - - private JavaElementLabels() { - } - - private static boolean getFlag(int flags, int flag) { - return (flags & flag) != 0; - } - - public static String getTextLabel(Object obj, int flags) { - if (obj instanceof IJavaElement) { - return getElementLabel((IJavaElement) obj, flags); - } else if (obj instanceof IAdaptable) { - IWorkbenchAdapter wbadapter = (IWorkbenchAdapter) ((IAdaptable) obj).getAdapter(IWorkbenchAdapter.class); - if (wbadapter != null) { - return wbadapter.getLabel(obj); - } - } - return ""; //$NON-NLS-1$ - } - - /** - * Returns the label for a Java element. Flags as defined above. - */ - public static String getElementLabel(IJavaElement element, int flags) { - StringBuffer buf = new StringBuffer(60); - getElementLabel(element, flags, buf); - return buf.toString(); - } - - /** - * Returns the label for a Java element. Flags as defined above. - */ - public static void getElementLabel(IJavaElement element, int flags, StringBuffer buf) { - int type = element.getElementType(); - IPackageFragmentRoot root = null; - - if (type != IJavaElement.JAVA_MODEL && type != IJavaElement.JAVA_PROJECT && type != IJavaElement.PACKAGE_FRAGMENT_ROOT) - root = JavaModelUtil.getPackageFragmentRoot(element); - if (root != null && getFlag(flags, PREPEND_ROOT_PATH)) { - getPackageFragmentRootLabel(root, ROOT_QUALIFIED, buf); - buf.append(CONCAT_STRING); - } - - switch (type) { - case IJavaElement.METHOD : - getMethodLabel((IMethod) element, flags, buf); - break; - case IJavaElement.FIELD : - getFieldLabel((IField) element, flags, buf); - break; - // case IJavaElement.INITIALIZER: - // getInitializerLabel((IInitializer) element, flags, buf); - // break; - case IJavaElement.TYPE : - getTypeLabel((IType) element, flags, buf); - break; - // case IJavaElement.CLASS_FILE: - // getClassFileLabel((IClassFile) element, flags, buf); - // break; - case IJavaElement.COMPILATION_UNIT : - getCompilationUnitLabel((ICompilationUnit) element, flags, buf); - break; - case IJavaElement.PACKAGE_FRAGMENT : - getPackageFragmentLabel((IPackageFragment) element, flags, buf); - break; - case IJavaElement.PACKAGE_FRAGMENT_ROOT : - getPackageFragmentRootLabel((IPackageFragmentRoot) element, flags, buf); - break; - case IJavaElement.IMPORT_CONTAINER : - case IJavaElement.IMPORT_DECLARATION : - case IJavaElement.PACKAGE_DECLARATION : - getDeclararionLabel(element, flags, buf); - break; - case IJavaElement.JAVA_PROJECT : - case IJavaElement.JAVA_MODEL : - buf.append(element.getElementName()); - break; - default : - buf.append(element.getElementName()); - } - - if (root != null && getFlag(flags, APPEND_ROOT_PATH)) { - buf.append(CONCAT_STRING); - getPackageFragmentRootLabel(root, ROOT_QUALIFIED, buf); - } - } - - /** - * Appends the label for a method to a StringBuffer. Considers the M_* flags. - */ - public static void getMethodLabel(IMethod method, int flags, StringBuffer buf) { - try { - // return type - if (getFlag(flags, M_PRE_RETURNTYPE) && method.exists() && !method.isConstructor()) { - buf.append(Signature.getSimpleName(Signature.toString(method.getReturnType()))); - buf.append(' '); - } - - // qualification - if (getFlag(flags, M_FULLY_QUALIFIED)) { - getTypeLabel(method.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf); - buf.append('.'); - } - - buf.append(method.getElementName()); - - // parameters - if (getFlag(flags, M_PARAMETER_TYPES | M_PARAMETER_NAMES)) { - buf.append('('); - - String[] types = getFlag(flags, M_PARAMETER_TYPES) ? method.getParameterTypes() : null; - String[] names = (getFlag(flags, M_PARAMETER_NAMES) && method.exists()) ? method.getParameterNames() : null; - int nParams = types != null ? types.length : names.length; - - for (int i = 0; i < nParams; i++) { - if (i > 0) { - buf.append(COMMA_STRING); //$NON-NLS-1$ - } - if (types != null) { - buf.append(Signature.getSimpleName(Signature.toString(types[i]))); - } - if (names != null) { - if (types != null) { - buf.append(' '); - } - buf.append(names[i]); - } - } - buf.append(')'); - } - - if (getFlag(flags, M_EXCEPTIONS) && method.exists()) { - String[] types = method.getExceptionTypes(); - if (types.length > 0) { - buf.append(" throws "); //$NON-NLS-1$ - for (int i = 0; i < types.length; i++) { - if (i > 0) { - buf.append(COMMA_STRING); - } - buf.append(Signature.getSimpleName(Signature.toString(types[i]))); - } - } - } - - if (getFlag(flags, M_APP_RETURNTYPE) && method.exists() && !method.isConstructor()) { - buf.append(DECL_STRING); - buf.append(Signature.getSimpleName(Signature.toString(method.getReturnType()))); - } - - // post qualification - if (getFlag(flags, M_POST_QUALIFIED)) { - buf.append(CONCAT_STRING); - getTypeLabel(method.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf); - } - - } catch (JavaModelException e) { - PHPeclipsePlugin.log(e); // NotExistsException will not reach this point - } - } - - /** - * Appends the label for a field to a StringBuffer. Considers the F_* flags. - */ - public static void getFieldLabel(IField field, int flags, StringBuffer buf) { - try { - if (getFlag(flags, F_PRE_TYPE_SIGNATURE) && field.exists()) { - buf.append(Signature.toString(field.getTypeSignature())); - buf.append(' '); - } - - // qualification - if (getFlag(flags, F_FULLY_QUALIFIED)) { - getTypeLabel(field.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf); - buf.append('.'); - } - buf.append(field.getElementName()); - - if (getFlag(flags, F_APP_TYPE_SIGNATURE) && field.exists()) { - buf.append(DECL_STRING); - buf.append(Signature.toString(field.getTypeSignature())); - } - - // post qualification - if (getFlag(flags, F_POST_QUALIFIED)) { - buf.append(CONCAT_STRING); - getTypeLabel(field.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf); - } - - } catch (JavaModelException e) { - PHPeclipsePlugin.log(e); // NotExistsException will not reach this point - } - } - - /** - * Appends the label for a initializer to a StringBuffer. Considers the I_* flags. - */ - // public static void getInitializerLabel(IInitializer initializer, int flags, StringBuffer buf) { - // // qualification - // if (getFlag(flags, I_FULLY_QUALIFIED)) { - // getTypeLabel(initializer.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf); - // buf.append('.'); - // } - // buf.append(JavaUIMessages.getString("JavaElementLabels.initializer")); //$NON-NLS-1$ - // - // // post qualification - // if (getFlag(flags, I_POST_QUALIFIED)) { - // buf.append(CONCAT_STRING); - // getTypeLabel(initializer.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf); - // } - // } - - /** - * Appends the label for a type to a StringBuffer. Considers the T_* flags. - */ - public static void getTypeLabel(IType type, int flags, StringBuffer buf) { - if (getFlag(flags, T_FULLY_QUALIFIED)) { - if (type != null) { // jsurfer INSERT - IPackageFragment pack = type.getPackageFragment(); - if (!pack.isDefaultPackage()) { - getPackageFragmentLabel(pack, (flags & P_COMPRESSED), buf); - buf.append('.'); - } - buf.append(JavaModelUtil.getTypeQualifiedName(type)); - } // jsurfer INSERT - } else if (getFlag(flags, T_CONTAINER_QUALIFIED)) { - buf.append(JavaModelUtil.getTypeQualifiedName(type)); - } else { - buf.append(type.getElementName()); - } - // post qualification - if (getFlag(flags, T_POST_QUALIFIED)) { - buf.append(CONCAT_STRING); - IType declaringType = type.getDeclaringType(); - if (declaringType != null) { - getTypeLabel(declaringType, T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf); - } else { - getPackageFragmentLabel(type.getPackageFragment(), (flags & P_COMPRESSED), buf); - } - } - } - - /** - * Appends the label for a declaration to a StringBuffer. Considers the D_* flags. - */ - public static void getDeclararionLabel(IJavaElement declaration, int flags, StringBuffer buf) { - if (getFlag(flags, D_QUALIFIED)) { - IJavaElement openable = (IJavaElement) declaration.getOpenable(); - if (openable != null) { - buf.append(getElementLabel(openable, CF_QUALIFIED | CU_QUALIFIED)); - buf.append('/'); - } - } - if (declaration.getElementType() == IJavaElement.IMPORT_CONTAINER) { - buf.append(PHPUIMessages.getString("JavaElementLabels.import_container")); //$NON-NLS-1$ - } else { - buf.append(declaration.getElementName()); - } - // post qualification - if (getFlag(flags, D_POST_QUALIFIED)) { - IJavaElement openable = (IJavaElement) declaration.getOpenable(); - if (openable != null) { - buf.append(CONCAT_STRING); - buf.append(getElementLabel(openable, CF_QUALIFIED | CU_QUALIFIED)); - } - } - } - - /** - * Appends the label for a class file to a StringBuffer. Considers the CF_* flags. - */ - // public static void getClassFileLabel(IClassFile classFile, int flags, StringBuffer buf) { - // if (getFlag(flags, CF_QUALIFIED)) { - // IPackageFragment pack= (IPackageFragment) classFile.getParent(); - // if (!pack.isDefaultPackage()) { - // buf.append(pack.getElementName()); - // buf.append('.'); - // } - // } - // buf.append(classFile.getElementName()); - // - // if (getFlag(flags, CF_POST_QUALIFIED)) { - // buf.append(CONCAT_STRING); - // getPackageFragmentLabel((IPackageFragment) classFile.getParent(), 0, buf); - // } - // } - - /** - * Appends the label for a compilation unit to a StringBuffer. Considers the CU_* flags. - */ - public static void getCompilationUnitLabel(ICompilationUnit cu, int flags, StringBuffer buf) { - if (getFlag(flags, CU_QUALIFIED)) { - IPackageFragment pack = (IPackageFragment) cu.getParent(); - if (!pack.isDefaultPackage()) { - buf.append(pack.getElementName()); - buf.append('.'); - } - } - buf.append(cu.getElementName()); - - if (getFlag(flags, CU_POST_QUALIFIED)) { - buf.append(CONCAT_STRING); - getPackageFragmentLabel((IPackageFragment) cu.getParent(), 0, buf); - } - } - - /** - * Appends the label for a package fragment to a StringBuffer. Considers the P_* flags. - */ - public static void getPackageFragmentLabel(IPackageFragment pack, int flags, StringBuffer buf) { - if (getFlag(flags, P_QUALIFIED)) { - getPackageFragmentRootLabel((IPackageFragmentRoot) pack.getParent(), ROOT_QUALIFIED, buf); - buf.append('/'); - } - refreshPackageNamePattern(); - if (pack.isDefaultPackage()) { - buf.append(PHPUIMessages.getString("JavaElementLabels.default_package")); //$NON-NLS-1$ - } else if (getFlag(flags, P_COMPRESSED) && fgPkgNameLength >= 0) { - String name = pack.getElementName(); - int start = 0; - int dot = name.indexOf('.', start); - while (dot > 0) { - if (dot - start > fgPkgNameLength - 1) { - buf.append(fgPkgNamePrefix); - if (fgPkgNameChars > 0) - buf.append(name.substring(start, Math.min(start + fgPkgNameChars, dot))); - buf.append(fgPkgNamePostfix); - } else - buf.append(name.substring(start, dot + 1)); - start = dot + 1; - dot = name.indexOf('.', start); - } - buf.append(name.substring(start)); - } else { - buf.append(pack.getElementName()); - } - if (getFlag(flags, P_POST_QUALIFIED)) { - buf.append(CONCAT_STRING); - getPackageFragmentRootLabel((IPackageFragmentRoot) pack.getParent(), ROOT_QUALIFIED, buf); - } - } - - /** - * Appends the label for a package fragment root to a StringBuffer. Considers the ROOT_* flags. - */ - public static void getPackageFragmentRootLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) { - if (root.isArchive()) - getArchiveLabel(root, flags, buf); - else - getFolderLabel(root, flags, buf); - } - - private static void getArchiveLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) { - // Handle variables different - if (getFlag(flags, ROOT_VARIABLE) && getVariableLabel(root, flags, buf)) - return; - boolean external = root.isExternal(); - if (external) - getExternalArchiveLabel(root, flags, buf); - else - getInternalArchiveLabel(root, flags, buf); - } - - private static boolean getVariableLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) { - // try { - // IClasspathEntry rawEntry= root.getRawClasspathEntry(); - // if (rawEntry != null) { - // if (rawEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) { - // buf.append(rawEntry.getPath().makeRelative()); - // buf.append(CONCAT_STRING); - // if (root.isExternal()) - // buf.append(root.getPath().toOSString()); - // else - // buf.append(root.getPath().makeRelative().toString()); - // return true; - // } - // } - // } catch (JavaModelException e) { - // PHPeclipsePlugin.log(e); // problems with class path - // } - return false; - } - - private static void getExternalArchiveLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) { - IPath path = root.getPath(); - if (getFlag(flags, REFERENCED_ROOT_POST_QUALIFIED)) { - int segements = path.segmentCount(); - if (segements > 0) { - buf.append(path.segment(segements - 1)); - if (segements > 1 || path.getDevice() != null) { - buf.append(CONCAT_STRING); - buf.append(path.removeLastSegments(1).toOSString()); - } - } else { - buf.append(path.toOSString()); - } - } else { - buf.append(path.toOSString()); - } - } - - private static void getInternalArchiveLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) { - IResource resource = root.getResource(); - boolean rootQualified = getFlag(flags, ROOT_QUALIFIED); - boolean referencedQualified = - getFlag(flags, REFERENCED_ROOT_POST_QUALIFIED) && JavaModelUtil.isReferenced(root) && resource != null; - if (rootQualified) { - buf.append(root.getPath().makeRelative().toString()); - } else { - buf.append(root.getElementName()); - if (referencedQualified) { - buf.append(CONCAT_STRING); - buf.append(resource.getParent().getFullPath().makeRelative().toString()); - } else if (getFlag(flags, ROOT_POST_QUALIFIED)) { - buf.append(CONCAT_STRING); - buf.append(root.getParent().getPath().makeRelative().toString()); - } - } - } - - private static void getFolderLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) { - IResource resource = root.getResource(); - boolean rootQualified = getFlag(flags, ROOT_QUALIFIED); - boolean referencedQualified = - getFlag(flags, REFERENCED_ROOT_POST_QUALIFIED) && JavaModelUtil.isReferenced(root) && resource != null; - if (rootQualified) { - buf.append(root.getPath().makeRelative().toString()); - } else { - if (resource != null) - buf.append(resource.getProjectRelativePath().toString()); - else - buf.append(root.getElementName()); - if (referencedQualified) { - buf.append(CONCAT_STRING); - buf.append(resource.getProject().getName()); - } else if (getFlag(flags, ROOT_POST_QUALIFIED)) { - buf.append(CONCAT_STRING); - buf.append(root.getParent().getElementName()); - } - } - } - - private static void refreshPackageNamePattern() { - String pattern = getPkgNamePatternForPackagesView(); - if (pattern.equals(fgPkgNamePattern)) - return; - else if (pattern.equals("")) { //$NON-NLS-1$ - fgPkgNamePattern = ""; //$NON-NLS-1$ - fgPkgNameLength = -1; - return; - } - fgPkgNamePattern = pattern; - int i = 0; - fgPkgNameChars = 0; - fgPkgNamePrefix = ""; //$NON-NLS-1$ - fgPkgNamePostfix = ""; //$NON-NLS-1$ - while (i < pattern.length()) { - char ch = pattern.charAt(i); - if (Character.isDigit(ch)) { - fgPkgNameChars = ch - 48; - if (i > 0) - fgPkgNamePrefix = pattern.substring(0, i); - if (i >= 0) - fgPkgNamePostfix = pattern.substring(i + 1); - fgPkgNameLength = fgPkgNamePrefix.length() + fgPkgNameChars + fgPkgNamePostfix.length(); - return; - } - i++; - } - fgPkgNamePrefix = pattern; - fgPkgNameLength = pattern.length(); - } - - private static String getPkgNamePatternForPackagesView() { - IPreferenceStore store = PreferenceConstants.getPreferenceStore(); - if (!store.getBoolean(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES)) - return ""; //$NON-NLS-1$ - return store.getString(PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW); - } + /** + * Method names contain parameter types. e.g. foo(int) + */ + public final static int M_PARAMETER_TYPES = 1 << 0; + + /** + * Method names contain parameter names. e.g. foo(index) + */ + public final static int M_PARAMETER_NAMES = 1 << 1; + + /** + * Method names contain thrown exceptions. e.g. + * foo throws IOException + */ + public final static int M_EXCEPTIONS = 1 << 2; + + /** + * Method names contain return type (appended) e.g. foo : int + */ + public final static int M_APP_RETURNTYPE = 1 << 3; + + /** + * Method names contain return type (appended) e.g. int foo + */ + public final static int M_PRE_RETURNTYPE = 1 << 4; + + /** + * Method names are fully qualified. e.g. java.util.Vector.size + */ + public final static int M_FULLY_QUALIFIED = 1 << 5; + + /** + * Method names are post qualified. e.g. + * size - java.util.Vector + */ + public final static int M_POST_QUALIFIED = 1 << 6; + + /** + * Initializer names are fully qualified. e.g. + * java.util.Vector.{ ... } + */ + public final static int I_FULLY_QUALIFIED = 1 << 7; + + /** + * Type names are post qualified. e.g. { ... } - java.util.Map + */ + public final static int I_POST_QUALIFIED = 1 << 8; + + /** + * Field names contain the declared type (appended) e.g. + * int fHello + */ + public final static int F_APP_TYPE_SIGNATURE = 1 << 9; + + /** + * Field names contain the declared type (prepended) e.g. + * fHello : int + */ + public final static int F_PRE_TYPE_SIGNATURE = 1 << 10; + + /** + * Fields names are fully qualified. e.g. java.lang.System.out + */ + public final static int F_FULLY_QUALIFIED = 1 << 11; + + /** + * Fields names are post qualified. e.g. out - java.lang.System + */ + public final static int F_POST_QUALIFIED = 1 << 12; + + /** + * Type names are fully qualified. e.g. java.util.Map.MapEntry + */ + public final static int T_FULLY_QUALIFIED = 1 << 13; + + /** + * Type names are type container qualified. e.g. Map.MapEntry + */ + public final static int T_CONTAINER_QUALIFIED = 1 << 14; + + /** + * Type names are post qualified. e.g. MapEntry - java.util.Map + */ + public final static int T_POST_QUALIFIED = 1 << 15; + + /** + * Declarations (import container / declarartion, package declarartion) are + * qualified. e.g. java.util.Vector.class/import container + */ + public final static int D_QUALIFIED = 1 << 16; + + /** + * Declarations (import container / declarartion, package declarartion) are + * post qualified. e.g. + * import container - java.util.Vector.class + */ + public final static int D_POST_QUALIFIED = 1 << 17; + + /** + * Class file names are fully qualified. e.g. + * java.util.Vector.class + */ + public final static int CF_QUALIFIED = 1 << 18; + + /** + * Class file names are post qualified. e.g. + * Vector.class - java.util + */ + public final static int CF_POST_QUALIFIED = 1 << 19; + + /** + * Compilation unit names are fully qualified. e.g. + * java.util.Vector.java + */ + public final static int CU_QUALIFIED = 1 << 20; + + /** + * Compilation unit names are post qualified. e.g. + * Vector.java - java.util + */ + public final static int CU_POST_QUALIFIED = 1 << 21; + + /** + * Package names are qualified. e.g. MyProject/src/java.util + */ + public final static int P_QUALIFIED = 1 << 22; + + /** + * Package names are post qualified. e.g. + * java.util - MyProject/src + */ + public final static int P_POST_QUALIFIED = 1 << 23; + + /** + * Package Fragment Roots contain variable name if from a variable. e.g. + * JRE_LIB - c:\java\lib\rt.jar + */ + public final static int ROOT_VARIABLE = 1 << 24; + + /** + * Package Fragment Roots contain the project name if not an archive + * (prepended). e.g. MyProject/src + */ + public final static int ROOT_QUALIFIED = 1 << 25; + + /** + * Package Fragment Roots contain the project name if not an archive + * (appended). e.g. src - MyProject + */ + public final static int ROOT_POST_QUALIFIED = 1 << 26; + + /** + * Add root path to all elements except Package Fragment Roots and Java + * projects. e.g. java.lang.Vector - c:\java\lib\rt.jar + * Option only applies to getElementLabel + */ + public final static int APPEND_ROOT_PATH = 1 << 27; + + /** + * Add root path to all elements except Package Fragment Roots and Java + * projects. e.g. java.lang.Vector - c:\java\lib\rt.jar + * Option only applies to getElementLabel + */ + public final static int PREPEND_ROOT_PATH = 1 << 28; + + /** + * Package names are compressed. e.g. o*.e*.search + */ + public final static int P_COMPRESSED = 1 << 29; + + /** + * Post qualify referenced package fragement roots. For example + * jdt.jar - net.sourceforge.phpdt.ui if the jar is + * referenced from another project. + */ + public final static int REFERENCED_ROOT_POST_QUALIFIED = 1 << 30; + + /** + * Qualify all elements + */ + public final static int ALL_FULLY_QUALIFIED = F_FULLY_QUALIFIED + | M_FULLY_QUALIFIED | I_FULLY_QUALIFIED | T_FULLY_QUALIFIED + | D_QUALIFIED | CF_QUALIFIED | CU_QUALIFIED | P_QUALIFIED + | ROOT_QUALIFIED; + + /** + * Post qualify all elements + */ + public final static int ALL_POST_QUALIFIED = F_POST_QUALIFIED + | M_POST_QUALIFIED | I_POST_QUALIFIED | T_POST_QUALIFIED + | D_POST_QUALIFIED | CF_POST_QUALIFIED | CU_POST_QUALIFIED + | P_POST_QUALIFIED | ROOT_POST_QUALIFIED; + + /** + * Default options (M_PARAMETER_TYPES enabled) + */ + public final static int ALL_DEFAULT = M_PARAMETER_TYPES; + + /** + * Default qualify options (All except Root and Package) + */ + public final static int DEFAULT_QUALIFIED = F_FULLY_QUALIFIED + | M_FULLY_QUALIFIED | I_FULLY_QUALIFIED | T_FULLY_QUALIFIED + | D_QUALIFIED | CF_QUALIFIED | CU_QUALIFIED; + + /** + * Default post qualify options (All except Root and Package) + */ + public final static int DEFAULT_POST_QUALIFIED = F_POST_QUALIFIED + | M_POST_QUALIFIED | I_POST_QUALIFIED | T_POST_QUALIFIED + | D_POST_QUALIFIED | CF_POST_QUALIFIED | CU_POST_QUALIFIED; + + public final static String CONCAT_STRING = PHPUIMessages + .getString("JavaElementLabels.concat_string"); // " - "; + // //$NON-NLS-1$ + + public final static String COMMA_STRING = PHPUIMessages + .getString("JavaElementLabels.comma_string"); // ", "; + // //$NON-NLS-1$ + + public final static String DECL_STRING = PHPUIMessages + .getString("JavaElementLabels.declseparator_string"); // " "; // + // use for + // return + // type + // //$NON-NLS-1$ + + /* + * Package name compression + */ + private static String fgPkgNamePattern = ""; //$NON-NLS-1$ + + private static String fgPkgNamePrefix; + + private static String fgPkgNamePostfix; + + private static int fgPkgNameChars; + + private static int fgPkgNameLength = -1; + + private JavaElementLabels() { + } + + private static boolean getFlag(int flags, int flag) { + return (flags & flag) != 0; + } + + public static String getTextLabel(Object obj, int flags) { + if (obj instanceof IJavaElement) { + return getElementLabel((IJavaElement) obj, flags); + } else if (obj instanceof IAdaptable) { + IWorkbenchAdapter wbadapter = (IWorkbenchAdapter) ((IAdaptable) obj) + .getAdapter(IWorkbenchAdapter.class); + if (wbadapter != null) { + return wbadapter.getLabel(obj); + } + } + return ""; //$NON-NLS-1$ + } + + /** + * Returns the label for a Java element. Flags as defined above. + */ + public static String getElementLabel(IJavaElement element, int flags) { + StringBuffer buf = new StringBuffer(60); + getElementLabel(element, flags, buf); + return buf.toString(); + } + + /** + * Returns the label for a Java element. Flags as defined above. + */ + public static void getElementLabel(IJavaElement element, int flags, + StringBuffer buf) { + int type = element.getElementType(); + IPackageFragmentRoot root = null; + + if (type != IJavaElement.JAVA_MODEL + && type != IJavaElement.JAVA_PROJECT + && type != IJavaElement.PACKAGE_FRAGMENT_ROOT) + root = JavaModelUtil.getPackageFragmentRoot(element); + if (root != null && getFlag(flags, PREPEND_ROOT_PATH)) { + getPackageFragmentRootLabel(root, ROOT_QUALIFIED, buf); + buf.append(CONCAT_STRING); + } + + switch (type) { + case IJavaElement.METHOD: + getMethodLabel((IMethod) element, flags, buf); + break; + case IJavaElement.FIELD: + getFieldLabel((IField) element, flags, buf); + break; + // case IJavaElement.INITIALIZER: + // getInitializerLabel((IInitializer) element, flags, buf); + // break; + case IJavaElement.TYPE: + getTypeLabel((IType) element, flags, buf); + break; + // case IJavaElement.CLASS_FILE: + // getClassFileLabel((IClassFile) element, flags, buf); + // break; + case IJavaElement.COMPILATION_UNIT: + getCompilationUnitLabel((ICompilationUnit) element, flags, buf); + break; + case IJavaElement.PACKAGE_FRAGMENT: + getPackageFragmentLabel((IPackageFragment) element, flags, buf); + break; + case IJavaElement.PACKAGE_FRAGMENT_ROOT: + getPackageFragmentRootLabel((IPackageFragmentRoot) element, flags, + buf); + break; + case IJavaElement.IMPORT_CONTAINER: + case IJavaElement.IMPORT_DECLARATION: + case IJavaElement.PACKAGE_DECLARATION: + getDeclararionLabel(element, flags, buf); + break; + case IJavaElement.JAVA_PROJECT: + case IJavaElement.JAVA_MODEL: + buf.append(element.getElementName()); + break; + default: + buf.append(element.getElementName()); + } + + if (root != null && getFlag(flags, APPEND_ROOT_PATH)) { + buf.append(CONCAT_STRING); + getPackageFragmentRootLabel(root, ROOT_QUALIFIED, buf); + } + } + + /** + * Appends the label for a method to a StringBuffer. Considers the M_* + * flags. + */ + public static void getMethodLabel(IMethod method, int flags, + StringBuffer buf) { + try { + // return type + if (getFlag(flags, M_PRE_RETURNTYPE) && method.exists() + && !method.isConstructor()) { + buf.append(Signature.getSimpleName(Signature.toString(method + .getReturnType()))); + buf.append(' '); + } + + // qualification + if (getFlag(flags, M_FULLY_QUALIFIED)) { + getTypeLabel(method.getDeclaringType(), T_FULLY_QUALIFIED + | (flags & P_COMPRESSED), buf); + buf.append('.'); + } + + buf.append(method.getElementName()); + + // parameters + if (getFlag(flags, M_PARAMETER_TYPES | M_PARAMETER_NAMES)) { + buf.append('('); + + String[] types = getFlag(flags, M_PARAMETER_TYPES) ? method + .getParameterTypes() : null; + String[] names = (getFlag(flags, M_PARAMETER_NAMES) && method + .exists()) ? method.getParameterNames() : null; + int nParams = types != null ? types.length : names.length; + + for (int i = 0; i < nParams; i++) { + if (i > 0) { + buf.append(COMMA_STRING); //$NON-NLS-1$ + } + if (types != null) { + buf.append(Signature.getSimpleName(Signature + .toString(types[i]))); + } + if (names != null) { + if (types != null) { + buf.append(' '); + } + buf.append(names[i]); + } + } + buf.append(')'); + } + + if (getFlag(flags, M_EXCEPTIONS) && method.exists()) { + String[] types = method.getExceptionTypes(); + if (types.length > 0) { + buf.append(" throws "); //$NON-NLS-1$ + for (int i = 0; i < types.length; i++) { + if (i > 0) { + buf.append(COMMA_STRING); + } + buf.append(Signature.getSimpleName(Signature + .toString(types[i]))); + } + } + } + + if (getFlag(flags, M_APP_RETURNTYPE) && method.exists() + && !method.isConstructor()) { + buf.append(DECL_STRING); + buf.append(Signature.getSimpleName(Signature.toString(method + .getReturnType()))); + } + + // post qualification + if (getFlag(flags, M_POST_QUALIFIED)) { + buf.append(CONCAT_STRING); + getTypeLabel(method.getDeclaringType(), T_FULLY_QUALIFIED + | (flags & P_COMPRESSED), buf); + } + + } catch (JavaModelException e) { + PHPeclipsePlugin.log(e); // NotExistsException will not reach + // this point + } + } + + /** + * Appends the label for a field to a StringBuffer. Considers the F_* flags. + */ + public static void getFieldLabel(IField field, int flags, StringBuffer buf) { + try { + if (getFlag(flags, F_PRE_TYPE_SIGNATURE) && field.exists()) { + buf.append(Signature.toString(field.getTypeSignature())); + buf.append(' '); + } + + // qualification + if (getFlag(flags, F_FULLY_QUALIFIED)) { + getTypeLabel(field.getDeclaringType(), T_FULLY_QUALIFIED + | (flags & P_COMPRESSED), buf); + buf.append('.'); + } + buf.append(field.getElementName()); + + if (getFlag(flags, F_APP_TYPE_SIGNATURE) && field.exists()) { + buf.append(DECL_STRING); + buf.append(Signature.toString(field.getTypeSignature())); + } + + // post qualification + if (getFlag(flags, F_POST_QUALIFIED)) { + buf.append(CONCAT_STRING); + getTypeLabel(field.getDeclaringType(), T_FULLY_QUALIFIED + | (flags & P_COMPRESSED), buf); + } + + } catch (JavaModelException e) { + PHPeclipsePlugin.log(e); // NotExistsException will not reach + // this point + } + } + + /** + * Appends the label for a initializer to a StringBuffer. Considers the I_* + * flags. + */ + // public static void getInitializerLabel(IInitializer initializer, int + // flags, StringBuffer buf) { + // // qualification + // if (getFlag(flags, I_FULLY_QUALIFIED)) { + // getTypeLabel(initializer.getDeclaringType(), T_FULLY_QUALIFIED | (flags & + // P_COMPRESSED), buf); + // buf.append('.'); + // } + // buf.append(JavaUIMessages.getString("JavaElementLabels.initializer")); + // //$NON-NLS-1$ + // + // // post qualification + // if (getFlag(flags, I_POST_QUALIFIED)) { + // buf.append(CONCAT_STRING); + // getTypeLabel(initializer.getDeclaringType(), T_FULLY_QUALIFIED | (flags & + // P_COMPRESSED), buf); + // } + // } + /** + * Appends the label for a type to a StringBuffer. Considers the T_* flags. + */ + public static void getTypeLabel(IType type, int flags, StringBuffer buf) { + if (getFlag(flags, T_FULLY_QUALIFIED)) { + if (type != null) { // jsurfer INSERT + IPackageFragment pack = type.getPackageFragment(); + if (!pack.isDefaultPackage()) { + getPackageFragmentLabel(pack, (flags & P_COMPRESSED), buf); + buf.append('.'); + } + buf.append(JavaModelUtil.getTypeQualifiedName(type)); + } // jsurfer INSERT + } else if (getFlag(flags, T_CONTAINER_QUALIFIED)) { + buf.append(JavaModelUtil.getTypeQualifiedName(type)); + } else { + buf.append(type.getElementName()); + } + // post qualification + if (getFlag(flags, T_POST_QUALIFIED)) { + buf.append(CONCAT_STRING); + IType declaringType = type.getDeclaringType(); + if (declaringType != null) { + getTypeLabel(declaringType, T_FULLY_QUALIFIED + | (flags & P_COMPRESSED), buf); + } else { + getPackageFragmentLabel(type.getPackageFragment(), + (flags & P_COMPRESSED), buf); + } + } + } + + /** + * Appends the label for a declaration to a StringBuffer. Considers the D_* + * flags. + */ + public static void getDeclararionLabel(IJavaElement declaration, int flags, + StringBuffer buf) { + if (getFlag(flags, D_QUALIFIED)) { + IJavaElement openable = (IJavaElement) declaration.getOpenable(); + if (openable != null) { + buf.append(getElementLabel(openable, CF_QUALIFIED + | CU_QUALIFIED)); + buf.append('/'); + } + } + if (declaration.getElementType() == IJavaElement.IMPORT_CONTAINER) { + buf.append(PHPUIMessages + .getString("JavaElementLabels.import_container")); //$NON-NLS-1$ + } else { + buf.append(declaration.getElementName()); + } + // post qualification + if (getFlag(flags, D_POST_QUALIFIED)) { + IJavaElement openable = (IJavaElement) declaration.getOpenable(); + if (openable != null) { + buf.append(CONCAT_STRING); + buf.append(getElementLabel(openable, CF_QUALIFIED + | CU_QUALIFIED)); + } + } + } + + /** + * Appends the label for a class file to a StringBuffer. Considers the CF_* + * flags. + */ + // public static void getClassFileLabel(IClassFile classFile, int flags, + // StringBuffer buf) { + // if (getFlag(flags, CF_QUALIFIED)) { + // IPackageFragment pack= (IPackageFragment) classFile.getParent(); + // if (!pack.isDefaultPackage()) { + // buf.append(pack.getElementName()); + // buf.append('.'); + // } + // } + // buf.append(classFile.getElementName()); + // + // if (getFlag(flags, CF_POST_QUALIFIED)) { + // buf.append(CONCAT_STRING); + // getPackageFragmentLabel((IPackageFragment) classFile.getParent(), 0, + // buf); + // } + // } + /** + * Appends the label for a compilation unit to a StringBuffer. Considers the + * CU_* flags. + */ + public static void getCompilationUnitLabel(ICompilationUnit cu, int flags, + StringBuffer buf) { + if (getFlag(flags, CU_QUALIFIED)) { + IPackageFragment pack = (IPackageFragment) cu.getParent(); + if (!pack.isDefaultPackage()) { + buf.append(pack.getElementName()); + buf.append('.'); + } + } + buf.append(cu.getElementName()); + + if (getFlag(flags, CU_POST_QUALIFIED)) { + buf.append(CONCAT_STRING); + getPackageFragmentLabel((IPackageFragment) cu.getParent(), 0, buf); + } + } + + /** + * Appends the label for a package fragment to a StringBuffer. Considers the + * P_* flags. + */ + public static void getPackageFragmentLabel(IPackageFragment pack, + int flags, StringBuffer buf) { + if (getFlag(flags, P_QUALIFIED)) { + getPackageFragmentRootLabel( + (IPackageFragmentRoot) pack.getParent(), ROOT_QUALIFIED, + buf); + buf.append('/'); + } + refreshPackageNamePattern(); + if (pack.isDefaultPackage()) { + buf.append(PHPUIMessages + .getString("JavaElementLabels.default_package")); //$NON-NLS-1$ + } else if (getFlag(flags, P_COMPRESSED) && fgPkgNameLength >= 0) { + String name = pack.getElementName(); + int start = 0; + int dot = name.indexOf('.', start); + while (dot > 0) { + if (dot - start > fgPkgNameLength - 1) { + buf.append(fgPkgNamePrefix); + if (fgPkgNameChars > 0) + buf.append(name.substring(start, Math.min(start + + fgPkgNameChars, dot))); + buf.append(fgPkgNamePostfix); + } else + buf.append(name.substring(start, dot + 1)); + start = dot + 1; + dot = name.indexOf('.', start); + } + buf.append(name.substring(start)); + } else { + buf.append(pack.getElementName()); + } + if (getFlag(flags, P_POST_QUALIFIED)) { + buf.append(CONCAT_STRING); + getPackageFragmentRootLabel( + (IPackageFragmentRoot) pack.getParent(), ROOT_QUALIFIED, + buf); + } + } + + /** + * Appends the label for a package fragment root to a StringBuffer. + * Considers the ROOT_* flags. + */ + public static void getPackageFragmentRootLabel(IPackageFragmentRoot root, + int flags, StringBuffer buf) { + if (root.isArchive()) + getArchiveLabel(root, flags, buf); + else + getFolderLabel(root, flags, buf); + } + + private static void getArchiveLabel(IPackageFragmentRoot root, int flags, + StringBuffer buf) { + // Handle variables different + if (getFlag(flags, ROOT_VARIABLE) && getVariableLabel(root, flags, buf)) + return; + boolean external = root.isExternal(); + if (external) + getExternalArchiveLabel(root, flags, buf); + else + getInternalArchiveLabel(root, flags, buf); + } + + private static boolean getVariableLabel(IPackageFragmentRoot root, + int flags, StringBuffer buf) { + // try { + // IClasspathEntry rawEntry= root.getRawClasspathEntry(); + // if (rawEntry != null) { + // if (rawEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) { + // buf.append(rawEntry.getPath().makeRelative()); + // buf.append(CONCAT_STRING); + // if (root.isExternal()) + // buf.append(root.getPath().toOSString()); + // else + // buf.append(root.getPath().makeRelative().toString()); + // return true; + // } + // } + // } catch (JavaModelException e) { + // PHPeclipsePlugin.log(e); // problems with class path + // } + return false; + } + + private static void getExternalArchiveLabel(IPackageFragmentRoot root, + int flags, StringBuffer buf) { + IPath path = root.getPath(); + if (getFlag(flags, REFERENCED_ROOT_POST_QUALIFIED)) { + int segements = path.segmentCount(); + if (segements > 0) { + buf.append(path.segment(segements - 1)); + if (segements > 1 || path.getDevice() != null) { + buf.append(CONCAT_STRING); + buf.append(path.removeLastSegments(1).toOSString()); + } + } else { + buf.append(path.toOSString()); + } + } else { + buf.append(path.toOSString()); + } + } + + private static void getInternalArchiveLabel(IPackageFragmentRoot root, + int flags, StringBuffer buf) { + IResource resource = root.getResource(); + boolean rootQualified = getFlag(flags, ROOT_QUALIFIED); + boolean referencedQualified = getFlag(flags, + REFERENCED_ROOT_POST_QUALIFIED) + && JavaModelUtil.isReferenced(root) && resource != null; + if (rootQualified) { + buf.append(root.getPath().makeRelative().toString()); + } else { + buf.append(root.getElementName()); + if (referencedQualified) { + buf.append(CONCAT_STRING); + buf.append(resource.getParent().getFullPath().makeRelative() + .toString()); + } else if (getFlag(flags, ROOT_POST_QUALIFIED)) { + buf.append(CONCAT_STRING); + buf + .append(root.getParent().getPath().makeRelative() + .toString()); + } + } + } + + private static void getFolderLabel(IPackageFragmentRoot root, int flags, + StringBuffer buf) { + IResource resource = root.getResource(); + boolean rootQualified = getFlag(flags, ROOT_QUALIFIED); + boolean referencedQualified = getFlag(flags, + REFERENCED_ROOT_POST_QUALIFIED) + && JavaModelUtil.isReferenced(root) && resource != null; + if (rootQualified) { + buf.append(root.getPath().makeRelative().toString()); + } else { + if (resource != null) + buf.append(resource.getProjectRelativePath().toString()); + else + buf.append(root.getElementName()); + if (referencedQualified) { + buf.append(CONCAT_STRING); + buf.append(resource.getProject().getName()); + } else if (getFlag(flags, ROOT_POST_QUALIFIED)) { + buf.append(CONCAT_STRING); + buf.append(root.getParent().getElementName()); + } + } + } + + private static void refreshPackageNamePattern() { + String pattern = getPkgNamePatternForPackagesView(); + if (pattern.equals(fgPkgNamePattern)) + return; + else if (pattern.equals("")) { //$NON-NLS-1$ + fgPkgNamePattern = ""; //$NON-NLS-1$ + fgPkgNameLength = -1; + return; + } + fgPkgNamePattern = pattern; + int i = 0; + fgPkgNameChars = 0; + fgPkgNamePrefix = ""; //$NON-NLS-1$ + fgPkgNamePostfix = ""; //$NON-NLS-1$ + while (i < pattern.length()) { + char ch = pattern.charAt(i); + if (Character.isDigit(ch)) { + fgPkgNameChars = ch - 48; + if (i > 0) + fgPkgNamePrefix = pattern.substring(0, i); + if (i >= 0) + fgPkgNamePostfix = pattern.substring(i + 1); + fgPkgNameLength = fgPkgNamePrefix.length() + fgPkgNameChars + + fgPkgNamePostfix.length(); + return; + } + i++; + } + fgPkgNamePrefix = pattern; + fgPkgNameLength = pattern.length(); + } + + private static String getPkgNamePatternForPackagesView() { + IPreferenceStore store = PreferenceConstants.getPreferenceStore(); + if (!store + .getBoolean(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES)) + return ""; //$NON-NLS-1$ + return store + .getString(PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaUILabelProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaUILabelProvider.java index 7a76d1d..abe10ec 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaUILabelProvider.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaUILabelProvider.java @@ -19,64 +19,73 @@ import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.graphics.Image; public class JavaUILabelProvider extends LabelProvider { - + protected JavaElementImageProvider fImageLabelProvider; + protected StorageLabelProvider fStorageLabelProvider; - + protected ArrayList fLabelDecorators; private int fImageFlags; + private int fTextFlags; /** * Creates a new label provider with default flags. */ public JavaUILabelProvider() { - this(JavaElementLabels.M_PARAMETER_TYPES, JavaElementImageProvider.OVERLAY_ICONS); + this(JavaElementLabels.M_PARAMETER_TYPES, + JavaElementImageProvider.OVERLAY_ICONS); } /** - * @param textFlags Flags defined in JavaElementLabels. - * @param imageFlags Flags defined in JavaElementImageProvider. + * @param textFlags + * Flags defined in JavaElementLabels. + * @param imageFlags + * Flags defined in JavaElementImageProvider. */ public JavaUILabelProvider(int textFlags, int imageFlags) { - fImageLabelProvider= new JavaElementImageProvider(); - fLabelDecorators= null; - - fStorageLabelProvider= new StorageLabelProvider(); - fImageFlags= imageFlags; - fTextFlags= textFlags; - } - + fImageLabelProvider = new JavaElementImageProvider(); + fLabelDecorators = null; + + fStorageLabelProvider = new StorageLabelProvider(); + fImageFlags = imageFlags; + fTextFlags = textFlags; + } + /** * Adds a decorator to the label provider */ public void addLabelDecorator(ILabelDecorator decorator) { if (fLabelDecorators == null) { - fLabelDecorators= new ArrayList(2); + fLabelDecorators = new ArrayList(2); } fLabelDecorators.add(decorator); } - + /** * Sets the textFlags. - * @param textFlags The textFlags to set + * + * @param textFlags + * The textFlags to set */ public final void setTextFlags(int textFlags) { - fTextFlags= textFlags; + fTextFlags = textFlags; } /** - * Sets the imageFlags - * @param imageFlags The imageFlags to set + * Sets the imageFlags + * + * @param imageFlags + * The imageFlags to set */ public final void setImageFlags(int imageFlags) { - fImageFlags= imageFlags; + fImageFlags = imageFlags; } - + /** - * Gets the image flags. - * Can be overwriten by super classes. + * Gets the image flags. Can be overwriten by super classes. + * * @return Returns a int */ public final int getImageFlags() { @@ -85,15 +94,17 @@ public class JavaUILabelProvider extends LabelProvider { /** * Gets the text flags. + * * @return Returns a int */ public final int getTextFlags() { return fTextFlags; } - + /** - * Evaluates the image flags for a element. - * Can be overwriten by super classes. + * Evaluates the image flags for a element. Can be overwriten by super + * classes. + * * @return Returns a int */ protected int evaluateImageFlags(Object element) { @@ -101,97 +112,118 @@ public class JavaUILabelProvider extends LabelProvider { } /** - * Evaluates the text flags for a element. Can be overwriten by super classes. + * Evaluates the text flags for a element. Can be overwriten by super + * classes. + * * @return Returns a int */ protected int evaluateTextFlags(Object element) { return getTextFlags(); } - - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see ILabelProvider#getImage */ public Image getImage(Object element) { - Image result= fImageLabelProvider.getImageLabel(element, evaluateImageFlags(element)); + Image result = fImageLabelProvider.getImageLabel(element, + evaluateImageFlags(element)); if (result == null && (element instanceof IStorage)) { - result= fStorageLabelProvider.getImage(element); + result = fStorageLabelProvider.getImage(element); } if (fLabelDecorators != null && result != null) { - for (int i= 0; i < fLabelDecorators.size(); i++) { - ILabelDecorator decorator= (ILabelDecorator) fLabelDecorators.get(i); - result= decorator.decorateImage(result, element); + for (int i = 0; i < fLabelDecorators.size(); i++) { + ILabelDecorator decorator = (ILabelDecorator) fLabelDecorators + .get(i); + result = decorator.decorateImage(result, element); } - } + } return result; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see ILabelProvider#getText */ public String getText(Object element) { - String result= JavaElementLabels.getTextLabel(element, evaluateTextFlags(element)); + String result = JavaElementLabels.getTextLabel(element, + evaluateTextFlags(element)); if (result.length() == 0 && (element instanceof IStorage)) { - result= fStorageLabelProvider.getText(element); + result = fStorageLabelProvider.getText(element); } if (fLabelDecorators != null && result.length() > 0) { - for (int i= 0; i < fLabelDecorators.size(); i++) { - ILabelDecorator decorator= (ILabelDecorator) fLabelDecorators.get(i); - result= decorator.decorateText(result, element); + for (int i = 0; i < fLabelDecorators.size(); i++) { + ILabelDecorator decorator = (ILabelDecorator) fLabelDecorators + .get(i); + result = decorator.decorateText(result, element); } - } + } return result; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see IBaseLabelProvider#dispose */ public void dispose() { if (fLabelDecorators != null) { - for (int i= 0; i < fLabelDecorators.size(); i++) { - ILabelDecorator decorator= (ILabelDecorator) fLabelDecorators.get(i); + for (int i = 0; i < fLabelDecorators.size(); i++) { + ILabelDecorator decorator = (ILabelDecorator) fLabelDecorators + .get(i); decorator.dispose(); } - fLabelDecorators= null; + fLabelDecorators = null; } fStorageLabelProvider.dispose(); fImageLabelProvider.dispose(); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see IBaseLabelProvider#addListener(ILabelProviderListener) */ public void addListener(ILabelProviderListener listener) { if (fLabelDecorators != null) { - for (int i= 0; i < fLabelDecorators.size(); i++) { - ILabelDecorator decorator= (ILabelDecorator) fLabelDecorators.get(i); + for (int i = 0; i < fLabelDecorators.size(); i++) { + ILabelDecorator decorator = (ILabelDecorator) fLabelDecorators + .get(i); decorator.addListener(listener); } } - super.addListener(listener); + super.addListener(listener); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see IBaseLabelProvider#isLabelProperty(Object, String) */ public boolean isLabelProperty(Object element, String property) { - return true; + return true; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see IBaseLabelProvider#removeListener(ILabelProviderListener) */ public void removeListener(ILabelProviderListener listener) { if (fLabelDecorators != null) { - for (int i= 0; i < fLabelDecorators.size(); i++) { - ILabelDecorator decorator= (ILabelDecorator) fLabelDecorators.get(i); + for (int i = 0; i < fLabelDecorators.size(); i++) { + ILabelDecorator decorator = (ILabelDecorator) fLabelDecorators + .get(i); decorator.removeListener(listener); } } - super.removeListener(listener); + super.removeListener(listener); } - - public static ILabelDecorator[] getDecorators(boolean errortick, ILabelDecorator extra) { + + public static ILabelDecorator[] getDecorators(boolean errortick, + ILabelDecorator extra) { if (errortick) { if (extra == null) { return new ILabelDecorator[] {}; @@ -203,6 +235,6 @@ public class JavaUILabelProvider extends LabelProvider { return new ILabelDecorator[] { extra }; } return null; - } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ListContentProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ListContentProvider.java index 3d6fcda..e520f4f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ListContentProvider.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ListContentProvider.java @@ -15,15 +15,15 @@ import java.util.List; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.Viewer; -/** +/** * A specialized content provider to show a list of editor parts. - */ + */ public class ListContentProvider implements IStructuredContentProvider { - List fContents; + List fContents; public ListContentProvider() { } - + public Object[] getElements(Object input) { if (fContents != null && fContents == input) return fContents.toArray(); @@ -31,16 +31,16 @@ public class ListContentProvider implements IStructuredContentProvider { } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - if (newInput instanceof List) - fContents= (List)newInput; + if (newInput instanceof List) + fContents = (List) newInput; else - fContents= null; + fContents = null; // we use a fixed set. } public void dispose() { } - + public boolean isDeleted(Object o) { return fContents != null && !fContents.contains(o); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/MemberFilter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/MemberFilter.java index 8e8bad2..5b5bf44 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/MemberFilter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/MemberFilter.java @@ -21,15 +21,17 @@ import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; /** - * Filter for the methods viewer. - * Changing a filter property does not trigger a refiltering of the viewer + * Filter for the methods viewer. Changing a filter property does not trigger a + * refiltering of the viewer */ public class MemberFilter extends ViewerFilter { - public static final int FILTER_NONPUBLIC= 1; - public static final int FILTER_STATIC= 2; - public static final int FILTER_FIELDS= 4; - + public static final int FILTER_NONPUBLIC = 1; + + public static final int FILTER_STATIC = 2; + + public static final int FILTER_FIELDS = 4; + private int fFilterProperties; /** @@ -38,63 +40,75 @@ public class MemberFilter extends ViewerFilter { public final void addFilter(int filter) { fFilterProperties |= filter; } + /** * Modifies filter and remove a property to filter for - */ + */ public final void removeFilter(int filter) { fFilterProperties &= (-1 ^ filter); } + /** * Tests if a property is filtered - */ + */ public final boolean hasFilter(int filter) { return (fFilterProperties & filter) != 0; } - + /* * @see ViewerFilter@isFilterProperty */ public boolean isFilterProperty(Object element, Object property) { return false; } + /* * @see ViewerFilter@select - */ + */ public boolean select(Viewer viewer, Object parentElement, Object element) { try { if (hasFilter(FILTER_FIELDS) && element instanceof IField) { return false; } if (element instanceof IMember) { - IMember member= (IMember)element; - if (member.getElementName().startsWith("<")) { // filter out //$NON-NLS-1$ + IMember member = (IMember) element; + if (member.getElementName().startsWith("<")) { // filter out + // + // //$NON-NLS-1$ return false; } - int flags= member.getFlags(); - if (hasFilter(FILTER_STATIC) && (Flags.isStatic(flags) || isFieldInInterface(member)) && member.getElementType() != IJavaElement.TYPE) { + int flags = member.getFlags(); + if (hasFilter(FILTER_STATIC) + && (Flags.isStatic(flags) || isFieldInInterface(member)) + && member.getElementType() != IJavaElement.TYPE) { return false; } - if (hasFilter(FILTER_NONPUBLIC) && !Flags.isPublic(flags) && !isMemberInInterface(member) && !isTopLevelType(member)) { + if (hasFilter(FILTER_NONPUBLIC) && !Flags.isPublic(flags) + && !isMemberInInterface(member) + && !isTopLevelType(member)) { return false; } - } + } } catch (JavaModelException e) { // ignore } return true; } - - private boolean isMemberInInterface(IMember member) throws JavaModelException { - IType parent= member.getDeclaringType(); + + private boolean isMemberInInterface(IMember member) + throws JavaModelException { + IType parent = member.getDeclaringType(); return parent != null && parent.isInterface(); } - - private boolean isFieldInInterface(IMember member) throws JavaModelException { - return (member.getElementType() == IJavaElement.FIELD) && member.getDeclaringType().isInterface(); - } - + + private boolean isFieldInInterface(IMember member) + throws JavaModelException { + return (member.getElementType() == IJavaElement.FIELD) + && member.getDeclaringType().isInterface(); + } + private boolean isTopLevelType(IMember member) throws JavaModelException { - IType parent= member.getDeclaringType(); + IType parent = member.getDeclaringType(); return parent == null; - } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/MemberFilterAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/MemberFilterAction.java index 26e8b63..634678f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/MemberFilterAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/MemberFilterAction.java @@ -21,12 +21,14 @@ import org.eclipse.ui.PlatformUI; public class MemberFilterAction extends Action { private int fFilterProperty; + private MemberFilterActionGroup fFilterActionGroup; - public MemberFilterAction(MemberFilterActionGroup actionGroup, String title, int property, String contextHelpId, boolean initValue) { + public MemberFilterAction(MemberFilterActionGroup actionGroup, + String title, int property, String contextHelpId, boolean initValue) { super(title); - fFilterActionGroup= actionGroup; - fFilterProperty= property; + fFilterActionGroup = actionGroup; + fFilterProperty = property; PlatformUI.getWorkbench().getHelpSystem().setHelp(this, contextHelpId); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ProblemMarkerManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ProblemMarkerManager.java index 5ce6d58..3661197 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ProblemMarkerManager.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ProblemMarkerManager.java @@ -10,7 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.ui.viewsupport; - import java.util.HashSet; import net.sourceforge.phpdt.internal.ui.util.SWTUtil; @@ -33,32 +32,35 @@ import org.eclipse.jface.text.source.IAnnotationModelListenerExtension; import org.eclipse.jface.util.ListenerList; import org.eclipse.swt.widgets.Display; - - /** - * Listens to resource deltas and filters for marker changes of type IMarker.PROBLEM - * Viewers showing error ticks should register as listener to + * Listens to resource deltas and filters for marker changes of type + * IMarker.PROBLEM Viewers showing error ticks should register as listener to * this type. */ -public class ProblemMarkerManager implements IResourceChangeListener, IAnnotationModelListener , IAnnotationModelListenerExtension { +public class ProblemMarkerManager implements IResourceChangeListener, + IAnnotationModelListener, IAnnotationModelListenerExtension { /** - * Visitors used to look if the element change delta containes a marker change. + * Visitors used to look if the element change delta containes a marker + * change. */ private static class ProjectErrorVisitor implements IResourceDeltaVisitor { - private HashSet fChangedElements; - + private HashSet fChangedElements; + public ProjectErrorVisitor(HashSet changedElements) { - fChangedElements= changedElements; + fChangedElements = changedElements; } - + public boolean visit(IResourceDelta delta) throws CoreException { - IResource res= delta.getResource(); - if (res instanceof IProject && delta.getKind() == IResourceDelta.CHANGED) { + IResource res = delta.getResource(); + if (res instanceof IProject + && delta.getKind() == IResourceDelta.CHANGED) { try { - IProject project= (IProject) res; - if (!project.isAccessible() || !project.hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) { + IProject project = (IProject) res; + if (!project.isAccessible() + || !project + .hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) { // only track open Java projects return false; } @@ -70,29 +72,34 @@ public class ProblemMarkerManager implements IResourceChangeListener, IAnnotatio checkInvalidate(delta, res); return true; } - + private void checkInvalidate(IResourceDelta delta, IResource resource) { - int kind= delta.getKind(); - if (kind == IResourceDelta.REMOVED || kind == IResourceDelta.ADDED || (kind == IResourceDelta.CHANGED && isErrorDelta(delta))) { + int kind = delta.getKind(); + if (kind == IResourceDelta.REMOVED || kind == IResourceDelta.ADDED + || (kind == IResourceDelta.CHANGED && isErrorDelta(delta))) { // invalidate the resource and all parents - while (resource.getType() != IResource.ROOT && fChangedElements.add(resource)) { - resource= resource.getParent(); + while (resource.getType() != IResource.ROOT + && fChangedElements.add(resource)) { + resource = resource.getParent(); } - } - } - - private boolean isErrorDelta(IResourceDelta delta) { + } + } + + private boolean isErrorDelta(IResourceDelta delta) { if ((delta.getFlags() & IResourceDelta.MARKERS) != 0) { - IMarkerDelta[] markerDeltas= delta.getMarkerDeltas(); - for (int i= 0; i < markerDeltas.length; i++) { + IMarkerDelta[] markerDeltas = delta.getMarkerDeltas(); + for (int i = 0; i < markerDeltas.length; i++) { if (markerDeltas[i].isSubtypeOf(IMarker.PROBLEM)) { - int kind= markerDeltas[i].getKind(); - if (kind == IResourceDelta.ADDED || kind == IResourceDelta.REMOVED) + int kind = markerDeltas[i].getKind(); + if (kind == IResourceDelta.ADDED + || kind == IResourceDelta.REMOVED) return true; - int severity= markerDeltas[i].getAttribute(IMarker.SEVERITY, -1); - int newSeverity= markerDeltas[i].getMarker().getAttribute(IMarker.SEVERITY, -1); + int severity = markerDeltas[i].getAttribute( + IMarker.SEVERITY, -1); + int newSeverity = markerDeltas[i].getMarker() + .getAttribute(IMarker.SEVERITY, -1); if (newSeverity != severity) - return true; + return true; } } } @@ -101,20 +108,19 @@ public class ProblemMarkerManager implements IResourceChangeListener, IAnnotatio } private ListenerList fListeners; - - + public ProblemMarkerManager() { - fListeners= new ListenerList(10); + fListeners = new ListenerList(10); } /* * @see IResourceChangeListener#resourceChanged - */ + */ public void resourceChanged(IResourceChangeEvent event) { - HashSet changedElements= new HashSet(); - + HashSet changedElements = new HashSet(); + try { - IResourceDelta delta= event.getDelta(); + IResourceDelta delta = event.getDelta(); if (delta != null) delta.accept(new ProjectErrorVisitor(changedElements)); } catch (CoreException e) { @@ -122,65 +128,75 @@ public class ProblemMarkerManager implements IResourceChangeListener, IAnnotatio } if (!changedElements.isEmpty()) { - IResource[] changes= (IResource[]) changedElements.toArray(new IResource[changedElements.size()]); + IResource[] changes = (IResource[]) changedElements + .toArray(new IResource[changedElements.size()]); fireChanges(changes, true); } } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see IAnnotationModelListener#modelChanged(IAnnotationModel) */ public void modelChanged(IAnnotationModel model) { // no action } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see IAnnotationModelListenerExtension#modelChanged(AnnotationModelEvent) */ public void modelChanged(AnnotationModelEvent event) { if (event instanceof CompilationUnitAnnotationModelEvent) { - CompilationUnitAnnotationModelEvent cuEvent= (CompilationUnitAnnotationModelEvent) event; + CompilationUnitAnnotationModelEvent cuEvent = (CompilationUnitAnnotationModelEvent) event; if (cuEvent.includesProblemMarkerAnnotationChanges()) { - IResource[] changes= new IResource[] { cuEvent.getUnderlyingResource() }; + IResource[] changes = new IResource[] { cuEvent + .getUnderlyingResource() }; fireChanges(changes, false); } } - } - + } + /** * Adds a listener for problem marker changes. */ public void addListener(IProblemChangedListener listener) { - if (fListeners.isEmpty()) { + if (fListeners.isEmpty()) { PHPeclipsePlugin.getWorkspace().addResourceChangeListener(this); - PHPeclipsePlugin.getDefault().getCompilationUnitDocumentProvider().addGlobalAnnotationModelListener(this); + PHPeclipsePlugin.getDefault().getCompilationUnitDocumentProvider() + .addGlobalAnnotationModelListener(this); } fListeners.add(listener); } /** * Removes a IProblemChangedListener. - */ + */ public void removeListener(IProblemChangedListener listener) { fListeners.remove(listener); if (fListeners.isEmpty()) { PHPeclipsePlugin.getWorkspace().removeResourceChangeListener(this); - PHPeclipsePlugin.getDefault().getCompilationUnitDocumentProvider().removeGlobalAnnotationModelListener(this); + PHPeclipsePlugin.getDefault().getCompilationUnitDocumentProvider() + .removeGlobalAnnotationModelListener(this); } } - - private void fireChanges(final IResource[] changes, final boolean isMarkerChange) { - Display display= SWTUtil.getStandardDisplay(); + + private void fireChanges(final IResource[] changes, + final boolean isMarkerChange) { + Display display = SWTUtil.getStandardDisplay(); if (display != null && !display.isDisposed()) { display.asyncExec(new Runnable() { - public void run() { - Object[] listeners= fListeners.getListeners(); - for (int i= 0; i < listeners.length; i++) { - IProblemChangedListener curr= (IProblemChangedListener) listeners[i]; + public void run() { + Object[] listeners = fListeners.getListeners(); + for (int i = 0; i < listeners.length; i++) { + IProblemChangedListener curr = (IProblemChangedListener) listeners[i]; curr.problemsChanged(changes, isMarkerChange); - } + } } }); - } + } } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ProblemTableViewer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ProblemTableViewer.java index 54778c5..6bc9ca3 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ProblemTableViewer.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ProblemTableViewer.java @@ -26,9 +26,9 @@ import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.Widget; /** - * Extends a TableViewer to allow more performance when showing error ticks. - * A ProblemItemMapper is contained that maps all items in - * the tree to underlying resource + * Extends a TableViewer to allow more performance when showing error ticks. A + * ProblemItemMapper is contained that maps all items in the tree + * to underlying resource */ public class ProblemTableViewer extends TableViewer { @@ -36,6 +36,7 @@ public class ProblemTableViewer extends TableViewer { /** * Constructor for ProblemTableViewer. + * * @param parent */ public ProblemTableViewer(Composite parent) { @@ -45,6 +46,7 @@ public class ProblemTableViewer extends TableViewer { /** * Constructor for ProblemTableViewer. + * * @param parent * @param style */ @@ -55,6 +57,7 @@ public class ProblemTableViewer extends TableViewer { /** * Constructor for ProblemTableViewer. + * * @param table */ public ProblemTableViewer(Table table) { @@ -63,9 +66,9 @@ public class ProblemTableViewer extends TableViewer { } private void initMapper() { - fResourceToItemsMapper= new ResourceToItemsMapper(this); + fResourceToItemsMapper = new ResourceToItemsMapper(this); } - + /* * @see StructuredViewer#mapElement(Object, Widget) */ @@ -82,7 +85,7 @@ public class ProblemTableViewer extends TableViewer { protected void unmapElement(Object element, Widget item) { if (item instanceof Item) { fResourceToItemsMapper.removeFromMap(element, (Item) item); - } + } super.unmapElement(element, item); } @@ -93,23 +96,23 @@ public class ProblemTableViewer extends TableViewer { fResourceToItemsMapper.clearMap(); super.unmapAllElements(); } - + /* * @see ContentViewer#handleLabelProviderChanged(LabelProviderChangedEvent) */ protected void handleLabelProviderChanged(LabelProviderChangedEvent event) { if (event instanceof ProblemsLabelChangedEvent) { - ProblemsLabelChangedEvent e= (ProblemsLabelChangedEvent) event; + ProblemsLabelChangedEvent e = (ProblemsLabelChangedEvent) event; if (!e.isMarkerChange() && canIgnoreChangesFromAnnotionModel()) { return; } } - - Object[] changed= event.getElements(); + + Object[] changed = event.getElements(); if (changed != null && !fResourceToItemsMapper.isEmpty()) { - ArrayList others= new ArrayList(changed.length); - for (int i= 0; i < changed.length; i++) { - Object curr= changed[i]; + ArrayList others = new ArrayList(changed.length); + for (int i = 0; i < changed.length; i++) { + Object curr = changed[i]; if (curr instanceof IResource) { fResourceToItemsMapper.resourceChanged((IResource) curr); } else { @@ -119,17 +122,20 @@ public class ProblemTableViewer extends TableViewer { if (others.isEmpty()) { return; } - event= new LabelProviderChangedEvent((IBaseLabelProvider) event.getSource(), others.toArray()); + event = new LabelProviderChangedEvent((IBaseLabelProvider) event + .getSource(), others.toArray()); } super.handleLabelProviderChanged(event); } - + /** - * Answers whether this viewer can ignore label provider changes resulting from - * marker changes in annotation models + * Answers whether this viewer can ignore label provider changes resulting + * from marker changes in annotation models */ private boolean canIgnoreChangesFromAnnotionModel() { - Object contentProvider= getContentProvider(); - return contentProvider instanceof IWorkingCopyProvider && !((IWorkingCopyProvider)contentProvider).providesWorkingCopies(); + Object contentProvider = getContentProvider(); + return contentProvider instanceof IWorkingCopyProvider + && !((IWorkingCopyProvider) contentProvider) + .providesWorkingCopies(); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ProblemTreeViewer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ProblemTreeViewer.java index d68c3fd..ba501eb 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ProblemTreeViewer.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ProblemTreeViewer.java @@ -27,9 +27,9 @@ import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.Widget; /** - * Extends a TreeViewer to allow more performance when showing error ticks. - * A ProblemItemMapper is contained that maps all items in - * the tree to underlying resource + * Extends a TreeViewer to allow more performance when showing error ticks. A + * ProblemItemMapper is contained that maps all items in the tree + * to underlying resource */ public class ProblemTreeViewer extends TreeViewer { @@ -58,12 +58,11 @@ public class ProblemTreeViewer extends TreeViewer { super(tree); initMapper(); } - + private void initMapper() { - fResourceToItemsMapper= new ResourceToItemsMapper(this); + fResourceToItemsMapper = new ResourceToItemsMapper(this); } - - + /* * @see StructuredViewer#mapElement(Object, Widget) */ @@ -80,7 +79,7 @@ public class ProblemTreeViewer extends TreeViewer { protected void unmapElement(Object element, Widget item) { if (item instanceof Item) { fResourceToItemsMapper.removeFromMap(element, (Item) item); - } + } super.unmapElement(element, item); } @@ -97,17 +96,17 @@ public class ProblemTreeViewer extends TreeViewer { */ protected void handleLabelProviderChanged(LabelProviderChangedEvent event) { if (event instanceof ProblemsLabelChangedEvent) { - ProblemsLabelChangedEvent e= (ProblemsLabelChangedEvent) event; + ProblemsLabelChangedEvent e = (ProblemsLabelChangedEvent) event; if (!e.isMarkerChange() && canIgnoreChangesFromAnnotionModel()) { return; } - } - - Object[] changed= event.getElements(); + } + + Object[] changed = event.getElements(); if (changed != null && !fResourceToItemsMapper.isEmpty()) { - ArrayList others= new ArrayList(); - for (int i= 0; i < changed.length; i++) { - Object curr= changed[i]; + ArrayList others = new ArrayList(); + for (int i = 0; i < changed.length; i++) { + Object curr = changed[i]; if (curr instanceof IResource) { fResourceToItemsMapper.resourceChanged((IResource) curr); } else { @@ -117,21 +116,26 @@ public class ProblemTreeViewer extends TreeViewer { if (others.isEmpty()) { return; } - event= new LabelProviderChangedEvent((IBaseLabelProvider) event.getSource(), others.toArray()); + event = new LabelProviderChangedEvent((IBaseLabelProvider) event + .getSource(), others.toArray()); } super.handleLabelProviderChanged(event); } - + /** - * Answers whether this viewer can ignore label provider changes resulting from - * marker changes in annotation models + * Answers whether this viewer can ignore label provider changes resulting + * from marker changes in annotation models */ private boolean canIgnoreChangesFromAnnotionModel() { - Object contentProvider= getContentProvider(); - return contentProvider instanceof IWorkingCopyProvider && !((IWorkingCopyProvider)contentProvider).providesWorkingCopies(); + Object contentProvider = getContentProvider(); + return contentProvider instanceof IWorkingCopyProvider + && !((IWorkingCopyProvider) contentProvider) + .providesWorkingCopies(); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.jface.viewers.AbstractTreeViewer#isExpandable(java.lang.Object) */ public boolean isExpandable(Object element) { @@ -142,4 +146,3 @@ public class ProblemTreeViewer extends TreeViewer { return super.isExpandable(element); } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ResourceToItemsMapper.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ResourceToItemsMapper.java index a28a8ab..dba7cae 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ResourceToItemsMapper.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ResourceToItemsMapper.java @@ -27,58 +27,62 @@ import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Item; /** - * Helper class for updating error markers and other decorators that work on resources. - * Items are mapped to their element's underlying resource. - * Method resourceChanged updates all items that are affected from the changed - * elements. + * Helper class for updating error markers and other decorators that work on + * resources. Items are mapped to their element's underlying resource. Method + * resourceChanged updates all items that are affected from the + * changed elements. */ public class ResourceToItemsMapper { - private static final int NUMBER_LIST_REUSE= 10; + private static final int NUMBER_LIST_REUSE = 10; // map from resource to item private HashMap fResourceToItem; + private Stack fReuseLists; - + private ContentViewer fContentViewer; public ResourceToItemsMapper(ContentViewer viewer) { - fResourceToItem= new HashMap(); - fReuseLists= new Stack(); - - fContentViewer= viewer; + fResourceToItem = new HashMap(); + fReuseLists = new Stack(); + + fContentViewer = viewer; } /** * Must be called from the UI thread. */ public void resourceChanged(IResource changedResource) { - Object obj= fResourceToItem.get(changedResource); + Object obj = fResourceToItem.get(changedResource); if (obj == null) { // not mapped } else if (obj instanceof Item) { updateItem((Item) obj); } else { // List of Items - List list= (List) obj; - for (int k= 0; k < list.size(); k++) { + List list = (List) obj; + for (int k = 0; k < list.size(); k++) { updateItem((Item) list.get(k)); } } } - + private void updateItem(Item item) { if (!item.isDisposed()) { // defensive code - ILabelProvider lprovider= (ILabelProvider) fContentViewer.getLabelProvider(); - - Object data= item.getData(); - - // If it is an IItemLabelProvider than short circuit: patch Tod (bug 55012) + ILabelProvider lprovider = (ILabelProvider) fContentViewer + .getLabelProvider(); + + Object data = item.getData(); + + // If it is an IItemLabelProvider than short circuit: patch Tod (bug + // 55012) if (lprovider instanceof IViewerLabelProvider) { - IViewerLabelProvider provider= (IViewerLabelProvider) lprovider; - - ViewerLabel updateLabel= new ViewerLabel(item.getText(), item.getImage()); + IViewerLabelProvider provider = (IViewerLabelProvider) lprovider; + + ViewerLabel updateLabel = new ViewerLabel(item.getText(), item + .getImage()); provider.updateLabel(updateLabel, data); - + if (updateLabel.hasNewImage()) { item.setImage(updateLabel.getImage()); } @@ -86,13 +90,13 @@ public class ResourceToItemsMapper { item.setText(updateLabel.getText()); } } else { - Image oldImage= item.getImage(); - Image image= lprovider.getImage(data); + Image oldImage = item.getImage(); + Image image = lprovider.getImage(data); if (image != null && !image.equals(oldImage)) { item.setImage(image); } - String oldText= item.getText(); - String text= lprovider.getText(data); + String oldText = item.getText(); + String text = lprovider.getText(data); if (text != null && !text.equals(oldText)) { item.setText(text); } @@ -102,24 +106,27 @@ public class ResourceToItemsMapper { /** * Adds a new item to the map. - * @param element Element to map - * @param item The item used for the element + * + * @param element + * Element to map + * @param item + * The item used for the element */ public void addToMap(Object element, Item item) { - IResource resource= getCorrespondingResource(element); + IResource resource = getCorrespondingResource(element); if (resource != null) { - Object existingMapping= fResourceToItem.get(resource); + Object existingMapping = fResourceToItem.get(resource); if (existingMapping == null) { fResourceToItem.put(resource, item); } else if (existingMapping instanceof Item) { if (existingMapping != item) { - List list= getNewList(); + List list = getNewList(); list.add(existingMapping); list.add(item); fResourceToItem.put(resource, list); } - } else { // List - List list= (List) existingMapping; + } else { // List + List list = (List) existingMapping; if (!list.contains(item)) { list.add(item); } @@ -129,17 +136,17 @@ public class ResourceToItemsMapper { /** * Removes an element from the map. - */ + */ public void removeFromMap(Object element, Item item) { - IResource resource= getCorrespondingResource(element); + IResource resource = getCorrespondingResource(element); if (resource != null) { - Object existingMapping= fResourceToItem.get(resource); + Object existingMapping = fResourceToItem.get(resource); if (existingMapping == null) { return; } else if (existingMapping instanceof Item) { fResourceToItem.remove(resource); } else { // List - List list= (List) existingMapping; + List list = (List) existingMapping; list.remove(item); if (list.isEmpty()) { fResourceToItem.remove(list); @@ -148,51 +155,54 @@ public class ResourceToItemsMapper { } } } - + private List getNewList() { if (!fReuseLists.isEmpty()) { return (List) fReuseLists.pop(); } return new ArrayList(2); } - + private void releaseList(List list) { if (fReuseLists.size() < NUMBER_LIST_REUSE) { fReuseLists.push(list); } } - + /** * Clears the map. */ public void clearMap() { fResourceToItem.clear(); } - + /** * Tests if the map is empty */ public boolean isEmpty() { return fResourceToItem.isEmpty(); - } - + } + /** - * Method that decides which elements can have error markers - * Returns null if an element can not have error markers. - */ + * Method that decides which elements can have error markers Returns null if + * an element can not have error markers. + */ private static IResource getCorrespondingResource(Object element) { if (element instanceof IJavaElement) { - IJavaElement elem= (IJavaElement) element; - if (!elem.isReadOnly()) { // only modifieable elements can get error ticks - IResource res= elem.getResource(); + IJavaElement elem = (IJavaElement) element; + if (!elem.isReadOnly()) { // only modifieable elements can get + // error ticks + IResource res = elem.getResource(); if (res == null) { - ICompilationUnit cu= (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT); + ICompilationUnit cu = (ICompilationUnit) elem + .getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) { - // elements in compilation units are mapped to the underlying resource of the original cu - res= cu.getResource(); + // elements in compilation units are mapped to the + // underlying resource of the original cu + res = cu.getResource(); } } - return res; + return res; } return null; } else if (element instanceof IResource) { @@ -200,5 +210,5 @@ public class ResourceToItemsMapper { } return null; } - + } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/SelectionListenerWithASTManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/SelectionListenerWithASTManager.java index a08966a..6741cba 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/SelectionListenerWithASTManager.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/SelectionListenerWithASTManager.java @@ -43,40 +43,45 @@ public class SelectionListenerWithASTManager { */ public static SelectionListenerWithASTManager getDefault() { if (fgDefault == null) { - fgDefault= new SelectionListenerWithASTManager(); + fgDefault = new SelectionListenerWithASTManager(); } return fgDefault; } - private final static class PartListenerGroup { private ITextEditor fPart; - private ISelectionChangedListener fSelectionListener, fPostSelectionListener; + + private ISelectionChangedListener fSelectionListener, + fPostSelectionListener; + private Job fCurrentJob; + private ListenerList fAstListeners; + /** - * Lock to avoid having more than one calculateAndInform job in parallel. - * Only jobs may synchronize on this as otherwise deadlocks are possible. + * Lock to avoid having more than one calculateAndInform job in + * parallel. Only jobs may synchronize on this as otherwise deadlocks + * are possible. */ - private final Object fJobLock= new Object(); + private final Object fJobLock = new Object(); public PartListenerGroup(ITextEditor part) { - fPart= part; - fCurrentJob= null; - fAstListeners= new ListenerList(); + fPart = part; + fCurrentJob = null; + fAstListeners = new ListenerList(); - fSelectionListener= new ISelectionChangedListener() { + fSelectionListener = new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { - ISelection selection= event.getSelection(); + ISelection selection = event.getSelection(); if (selection instanceof ITextSelection) { fireSelectionChanged((ITextSelection) selection); } } }; - fPostSelectionListener= new ISelectionChangedListener() { + fPostSelectionListener = new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { - ISelection selection= event.getSelection(); + ISelection selection = event.getSelection(); if (selection instanceof ITextSelection) { firePostSelectionChanged((ITextSelection) selection); } @@ -90,10 +95,13 @@ public class SelectionListenerWithASTManager { public void install(ISelectionListenerWithAST listener) { if (isEmpty()) { - ISelectionProvider selectionProvider= fPart.getSelectionProvider(); + ISelectionProvider selectionProvider = fPart + .getSelectionProvider(); if (selectionProvider instanceof IPostSelectionProvider) { - ((IPostSelectionProvider) selectionProvider).addPostSelectionChangedListener(fPostSelectionListener); - selectionProvider.addSelectionChangedListener(fSelectionListener); + ((IPostSelectionProvider) selectionProvider) + .addPostSelectionChangedListener(fPostSelectionListener); + selectionProvider + .addSelectionChangedListener(fSelectionListener); } } fAstListeners.add(listener); @@ -102,10 +110,13 @@ public class SelectionListenerWithASTManager { public void uninstall(ISelectionListenerWithAST listener) { fAstListeners.remove(listener); if (isEmpty()) { - ISelectionProvider selectionProvider= fPart.getSelectionProvider(); + ISelectionProvider selectionProvider = fPart + .getSelectionProvider(); if (selectionProvider instanceof IPostSelectionProvider) { - ((IPostSelectionProvider) selectionProvider).removePostSelectionChangedListener(fPostSelectionListener); - selectionProvider.removeSelectionChangedListener(fSelectionListener); + ((IPostSelectionProvider) selectionProvider) + .removePostSelectionChangedListener(fPostSelectionListener); + selectionProvider + .removeSelectionChangedListener(fSelectionListener); } } } @@ -120,15 +131,16 @@ public class SelectionListenerWithASTManager { if (fCurrentJob != null) { fCurrentJob.cancel(); } - final IJavaElement input= getJavaElement(); + final IJavaElement input = getJavaElement(); if (input == null) { return; } - fCurrentJob= new Job("SelectionListenerWithASTManager Job") {//JavaUIMessages.SelectionListenerWithASTManager_job_title) { + fCurrentJob = new Job("SelectionListenerWithASTManager Job") {// JavaUIMessages.SelectionListenerWithASTManager_job_title) + // { public IStatus run(IProgressMonitor monitor) { if (monitor == null) { - monitor= new NullProgressMonitor(); + monitor = new NullProgressMonitor(); } synchronized (fJobLock) { return calculateASTandInform(input, selection, monitor); @@ -141,34 +153,39 @@ public class SelectionListenerWithASTManager { } private IJavaElement getJavaElement() { - IEditorInput editorInput= fPart.getEditorInput(); + IEditorInput editorInput = fPart.getEditorInput(); if (editorInput != null) - return (IJavaElement)editorInput.getAdapter(IJavaElement.class); + return (IJavaElement) editorInput + .getAdapter(IJavaElement.class); return null; } - protected IStatus calculateASTandInform(IJavaElement input, ITextSelection selection, IProgressMonitor monitor) { + protected IStatus calculateASTandInform(IJavaElement input, + ITextSelection selection, IProgressMonitor monitor) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } // create AST try { -// CompilationUnit astRoot= PHPeclipsePlugin.getDefault().getASTProvider().getAST(input, ASTProvider.WAIT_ACTIVE_ONLY, monitor); + // CompilationUnit astRoot= + // PHPeclipsePlugin.getDefault().getASTProvider().getAST(input, + // ASTProvider.WAIT_ACTIVE_ONLY, monitor); -// if (astRoot != null && !monitor.isCanceled()) { - Object[] listeners; - synchronized (PartListenerGroup.this) { - listeners= fAstListeners.getListeners(); - } - for (int i= 0; i < listeners.length; i++) { - ((ISelectionListenerWithAST) listeners[i]).selectionChanged(fPart, selection);//, astRoot); - if (monitor.isCanceled()) { - return Status.CANCEL_STATUS; - } + // if (astRoot != null && !monitor.isCanceled()) { + Object[] listeners; + synchronized (PartListenerGroup.this) { + listeners = fAstListeners.getListeners(); + } + for (int i = 0; i < listeners.length; i++) { + ((ISelectionListenerWithAST) listeners[i]) + .selectionChanged(fPart, selection);// , astRoot); + if (monitor.isCanceled()) { + return Status.CANCEL_STATUS; } - return Status.OK_STATUS; -// } + } + return Status.OK_STATUS; + // } } catch (OperationCanceledException e) { // thrown when cancelling the AST creation } @@ -176,23 +193,26 @@ public class SelectionListenerWithASTManager { } } - private Map fListenerGroups; private SelectionListenerWithASTManager() { - fListenerGroups= new HashMap(); + fListenerGroups = new HashMap(); } /** * Registers a selection listener for the given editor part. - * @param part The editor part to listen to. - * @param listener The listener to register. + * + * @param part + * The editor part to listen to. + * @param listener + * The listener to register. */ public void addListener(ITextEditor part, ISelectionListenerWithAST listener) { synchronized (this) { - PartListenerGroup partListener= (PartListenerGroup) fListenerGroups.get(part); + PartListenerGroup partListener = (PartListenerGroup) fListenerGroups + .get(part); if (partListener == null) { - partListener= new PartListenerGroup(part); + partListener = new PartListenerGroup(part); fListenerGroups.put(part, partListener); } partListener.install(listener); @@ -201,12 +221,17 @@ public class SelectionListenerWithASTManager { /** * Unregisters a selection listener. - * @param part The editor part the listener was registered. - * @param listener The listener to unregister. + * + * @param part + * The editor part the listener was registered. + * @param listener + * The listener to unregister. */ - public void removeListener(ITextEditor part, ISelectionListenerWithAST listener) { + public void removeListener(ITextEditor part, + ISelectionListenerWithAST listener) { synchronized (this) { - PartListenerGroup partListener= (PartListenerGroup) fListenerGroups.get(part); + PartListenerGroup partListener = (PartListenerGroup) fListenerGroups + .get(part); if (partListener != null) { partListener.uninstall(listener); if (partListener.isEmpty()) { @@ -217,17 +242,22 @@ public class SelectionListenerWithASTManager { } /** - * Forces a selection changed event that is sent to all listeners registered to the given editor - * part. The event is sent from a background thread: this method call can return before the listeners - * are informed. - * @param part The editor part that has a changed selection - * @param selection The new text selection + * Forces a selection changed event that is sent to all listeners registered + * to the given editor part. The event is sent from a background thread: + * this method call can return before the listeners are informed. + * + * @param part + * The editor part that has a changed selection + * @param selection + * The new text selection */ public void forceSelectionChange(ITextEditor part, ITextSelection selection) { synchronized (this) { - PartListenerGroup partListener= (PartListenerGroup) fListenerGroups.get(part); + PartListenerGroup partListener = (PartListenerGroup) fListenerGroups + .get(part); if (partListener != null) { partListener.firePostSelectionChanged(selection); } } - }} + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/StatusBarUpdater.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/StatusBarUpdater.java index ec9f214..978536f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/StatusBarUpdater.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/StatusBarUpdater.java @@ -10,7 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.ui.viewsupport; - import net.sourceforge.phpdt.core.IJavaElement; import net.sourceforge.phpdt.internal.ui.PHPUIMessages; @@ -23,39 +22,45 @@ import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; /** - * Add the StatusBarUpdater to your ViewPart to have the statusbar - * describing the selected elements. + * Add the StatusBarUpdater to your ViewPart to have the + * statusbar describing the selected elements. */ public class StatusBarUpdater implements ISelectionChangedListener { - - private final int LABEL_FLAGS= JavaElementLabels.DEFAULT_QUALIFIED | JavaElementLabels.ROOT_POST_QUALIFIED | JavaElementLabels.APPEND_ROOT_PATH | - JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.M_PARAMETER_NAMES | JavaElementLabels.M_APP_RETURNTYPE | JavaElementLabels.M_EXCEPTIONS | - JavaElementLabels.F_APP_TYPE_SIGNATURE; - + + private final int LABEL_FLAGS = JavaElementLabels.DEFAULT_QUALIFIED + | JavaElementLabels.ROOT_POST_QUALIFIED + | JavaElementLabels.APPEND_ROOT_PATH + | JavaElementLabels.M_PARAMETER_TYPES + | JavaElementLabels.M_PARAMETER_NAMES + | JavaElementLabels.M_APP_RETURNTYPE + | JavaElementLabels.M_EXCEPTIONS + | JavaElementLabels.F_APP_TYPE_SIGNATURE; + private IStatusLineManager fStatusLineManager; - + public StatusBarUpdater(IStatusLineManager statusLineManager) { - fStatusLineManager= statusLineManager; + fStatusLineManager = statusLineManager; } - + /* * @see ISelectionChangedListener#selectionChanged */ public void selectionChanged(SelectionChangedEvent event) { - String statusBarMessage= formatMessage(event.getSelection()); + String statusBarMessage = formatMessage(event.getSelection()); fStatusLineManager.setMessage(statusBarMessage); } - - + protected String formatMessage(ISelection sel) { if (sel instanceof IStructuredSelection && !sel.isEmpty()) { - IStructuredSelection selection= (IStructuredSelection) sel; - - int nElements= selection.size(); + IStructuredSelection selection = (IStructuredSelection) sel; + + int nElements = selection.size(); if (nElements > 1) { - return PHPUIMessages.getFormattedString("StatusBarUpdater.num_elements_selected", String.valueOf(nElements)); //$NON-NLS-1$ - } else { - Object elem= selection.getFirstElement(); + return PHPUIMessages + .getFormattedString( + "StatusBarUpdater.num_elements_selected", String.valueOf(nElements)); //$NON-NLS-1$ + } else { + Object elem = selection.getFirstElement(); if (elem instanceof IJavaElement) { return formatJavaElementMessage((IJavaElement) elem); } else if (elem instanceof IResource) { @@ -63,19 +68,20 @@ public class StatusBarUpdater implements ISelectionChangedListener { } } } - return ""; //$NON-NLS-1$ + return ""; //$NON-NLS-1$ } - + private String formatJavaElementMessage(IJavaElement element) { return JavaElementLabels.getElementLabel(element, LABEL_FLAGS); } - + private String formatResourceMessage(IResource element) { - IContainer parent= element.getParent(); + IContainer parent = element.getParent(); if (parent != null && parent.getType() != IResource.ROOT) - return element.getName() + JavaElementLabels.CONCAT_STRING + parent.getFullPath().makeRelative().toString(); + return element.getName() + JavaElementLabels.CONCAT_STRING + + parent.getFullPath().makeRelative().toString(); else return element.getName(); - } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/StorageLabelProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/StorageLabelProvider.java index 069bd37..a5d86bc 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/StorageLabelProvider.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/StorageLabelProvider.java @@ -10,7 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.ui.viewsupport; - import java.util.HashMap; import java.util.Iterator; import java.util.Map; @@ -25,57 +24,65 @@ import org.eclipse.ui.IFileEditorMapping; import org.eclipse.ui.PlatformUI; /** - * Standard label provider for IStorage objects. - * Use this class when you want to present IStorage objects in a viewer. + * Standard label provider for IStorage objects. Use this class when you want to + * present IStorage objects in a viewer. */ public class StorageLabelProvider extends LabelProvider { - - private IEditorRegistry fEditorRegistry= PlatformUI.getWorkbench().getEditorRegistry(); - private Map fJarImageMap= new HashMap(10); + + private IEditorRegistry fEditorRegistry = PlatformUI.getWorkbench() + .getEditorRegistry(); + + private Map fJarImageMap = new HashMap(10); + private Image fDefaultImage; - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see ILabelProvider#getImage */ public Image getImage(Object element) { - if (element instanceof IStorage) - return getImageForJarEntry((IStorage)element); + if (element instanceof IStorage) + return getImageForJarEntry((IStorage) element); return super.getImage(element); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see ILabelProvider#getText */ public String getText(Object element) { if (element instanceof IStorage) - return ((IStorage)element).getName(); + return ((IStorage) element).getName(); return super.getText(element); } - /* (non-Javadoc) + /* + * (non-Javadoc) * * @see IBaseLabelProvider#dispose */ public void dispose() { if (fJarImageMap != null) { - Iterator each= fJarImageMap.values().iterator(); + Iterator each = fJarImageMap.values().iterator(); while (each.hasNext()) { - Image image= (Image)each.next(); + Image image = (Image) each.next(); image.dispose(); } - fJarImageMap= null; + fJarImageMap = null; } if (fDefaultImage != null) fDefaultImage.dispose(); - fDefaultImage= null; + fDefaultImage = null; } - + /* - * Gets and caches an image for a JarEntryFile. - * The image for a JarEntryFile is retrieved from the EditorRegistry. - */ + * Gets and caches an image for a JarEntryFile. The image for a JarEntryFile + * is retrieved from the EditorRegistry. + */ private Image getImageForJarEntry(IStorage element) { if (fJarImageMap == null) return getDefaultImage(); @@ -84,43 +91,44 @@ public class StorageLabelProvider extends LabelProvider { return getDefaultImage(); // Try to find icon for full name - String name= element.getName(); - Image image= (Image)fJarImageMap.get(name); - if (image != null) + String name = element.getName(); + Image image = (Image) fJarImageMap.get(name); + if (image != null) return image; - IFileEditorMapping[] mappings= fEditorRegistry.getFileEditorMappings(); - int i= 0; + IFileEditorMapping[] mappings = fEditorRegistry.getFileEditorMappings(); + int i = 0; while (i < mappings.length) { if (mappings[i].getLabel().equals(name)) break; i++; } - String key= name; + String key = name; if (i == mappings.length) { // Try to find icon for extension - IPath path= element.getFullPath(); + IPath path = element.getFullPath(); if (path == null) return getDefaultImage(); - key= path.getFileExtension(); + key = path.getFileExtension(); if (key == null) return getDefaultImage(); - image= (Image)fJarImageMap.get(key); - if (image != null) + image = (Image) fJarImageMap.get(key); + if (image != null) return image; } - // Get the image from the editor registry - ImageDescriptor desc= fEditorRegistry.getImageDescriptor(name); - image= desc.createImage(); + // Get the image from the editor registry + ImageDescriptor desc = fEditorRegistry.getImageDescriptor(name); + image = desc.createImage(); fJarImageMap.put(key, image); return image; } - + private Image getDefaultImage() { if (fDefaultImage == null) - fDefaultImage= fEditorRegistry.getImageDescriptor((String)null).createImage(); + fDefaultImage = fEditorRegistry.getImageDescriptor((String) null) + .createImage(); return fDefaultImage; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/IStatusChangeListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/IStatusChangeListener.java index 63129e3..4e1a2ab 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/IStatusChangeListener.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/IStatusChangeListener.java @@ -13,11 +13,12 @@ package net.sourceforge.phpdt.internal.ui.wizards; import org.eclipse.core.runtime.IStatus; public interface IStatusChangeListener { - + /** * Notifies this listener that the given status has changed. * - * @param status the new status + * @param status + * the new status */ void statusChanged(IStatus status); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/NewClassCreationWizard.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/NewClassCreationWizard.java index efb355c..dc7cfda 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/NewClassCreationWizard.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/NewClassCreationWizard.java @@ -21,7 +21,6 @@ import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; - public class NewClassCreationWizard extends NewElementWizard { private NewClassWizardPage fPage; @@ -30,38 +29,44 @@ public class NewClassCreationWizard extends NewElementWizard { super(); setDefaultPageImageDescriptor(PHPUiImages.DESC_WIZBAN_NEWCLASS); setDialogSettings(PHPeclipsePlugin.getDefault().getDialogSettings()); - setWindowTitle(NewWizardMessages.getString("NewClassCreationWizard.title")); //$NON-NLS-1$ + setWindowTitle(NewWizardMessages + .getString("NewClassCreationWizard.title")); //$NON-NLS-1$ } /* * @see Wizard#createPages - */ + */ public void addPages() { super.addPages(); - fPage= new NewClassWizardPage(); + fPage = new NewClassWizardPage(); addPage(fPage); fPage.init(getSelection()); - } - + } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpdt.internal.ui.wizards.NewElementWizard#finishPage(org.eclipse.core.runtime.IProgressMonitor) */ - protected void finishPage(IProgressMonitor monitor) throws InterruptedException, CoreException { + protected void finishPage(IProgressMonitor monitor) + throws InterruptedException, CoreException { fPage.createType(monitor); // use the full progress monitor - ICompilationUnit cu= JavaModelUtil.toOriginal(fPage.getCreatedType().getCompilationUnit()); + ICompilationUnit cu = JavaModelUtil.toOriginal(fPage.getCreatedType() + .getCompilationUnit()); if (cu != null) { - IResource resource= cu.getResource(); + IResource resource = cu.getResource(); selectAndReveal(resource); openResource((IFile) resource); - } + } } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.jface.wizard.IWizard#performFinish() */ public boolean performFinish() { -// warnAboutTypeCommentDeprecation(); + // warnAboutTypeCommentDeprecation(); return super.performFinish(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/NewElementWizard.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/NewElementWizard.java index 5110243..3f95c8c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/NewElementWizard.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/NewElementWizard.java @@ -35,104 +35,119 @@ import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard; public abstract class NewElementWizard extends Wizard implements INewWizard { - private IWorkbench fWorkbench; - private IStructuredSelection fSelection; - - public NewElementWizard() { - setNeedsProgressMonitor(true); - } - - protected void openResource(final IFile resource) { - final IWorkbenchPage activePage = PHPeclipsePlugin.getActivePage(); - if (activePage != null) { - final Display display = getShell().getDisplay(); - if (display != null) { - display.asyncExec(new Runnable() { - public void run() { - try { - IDE.openEditor(activePage, resource, true); - } catch (PartInitException e) { - PHPeclipsePlugin.log(e); - } - } - }); - } - } - } - - /** - * Subclasses should override to perform the actions of the wizard. This method is run in the wizard container's context as a - * workspace runnable. - */ - protected void finishPage(IProgressMonitor monitor) throws InterruptedException, CoreException { - } - - protected void handleFinishException(Shell shell, InvocationTargetException e) { - String title = NewWizardMessages.getString("NewElementWizard.op_error.title"); //$NON-NLS-1$ - String message = NewWizardMessages.getString("NewElementWizard.op_error.message"); //$NON-NLS-1$ - ExceptionHandler.handle(e, shell, title, message); - } - - /* - * @see Wizard#performFinish - */ - public boolean performFinish() { - IWorkspaceRunnable op = new IWorkspaceRunnable() { - public void run(IProgressMonitor monitor) throws CoreException, OperationCanceledException { - try { - finishPage(monitor); - } catch (InterruptedException e) { - throw new OperationCanceledException(e.getMessage()); - } - } - }; - try { - getContainer().run(false, true, new WorkbenchRunnableAdapter(op)); - } catch (InvocationTargetException e) { - handleFinishException(getShell(), e); - return false; - } catch (InterruptedException e) { - return false; - } - return true; - } - - // protected void warnAboutTypeCommentDeprecation() { - // String key= IUIConstants.DIALOGSTORE_TYPECOMMENT_DEPRECATED; - // if (OptionalMessageDialog.isDialogEnabled(key)) { - // Templates templates= Templates.getInstance(); - // boolean isOldWorkspace= templates.getTemplates("filecomment").length > 0 && templates.getTemplates("typecomment").length > 0; - // //$NON-NLS-1$ //$NON-NLS-2$ - // if (!isOldWorkspace) { - // OptionalMessageDialog.setDialogEnabled(key, false); - // } - // String title= NewWizardMessages.getString("NewElementWizard.typecomment.deprecated.title"); //$NON-NLS-1$ - // String message= NewWizardMessages.getString("NewElementWizard.typecomment.deprecated.message"); //$NON-NLS-1$ - // OptionalMessageDialog.open(key, getShell(), title, OptionalMessageDialog.getDefaultImage(), message, - // OptionalMessageDialog.INFORMATION, new String[] { IDialogConstants.OK_LABEL }, 0); - // } - // } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench, org.eclipse.jface.viewers.IStructuredSelection) - */ - public void init(IWorkbench workbench, IStructuredSelection currentSelection) { - fWorkbench = workbench; - fSelection = currentSelection; - } - - public IStructuredSelection getSelection() { - return fSelection; - } - - public IWorkbench getWorkbench() { - return fWorkbench; - } - - protected void selectAndReveal(IResource newResource) { - BasicNewResourceWizard.selectAndReveal(newResource, fWorkbench.getActiveWorkbenchWindow()); - } + private IWorkbench fWorkbench; + + private IStructuredSelection fSelection; + + public NewElementWizard() { + setNeedsProgressMonitor(true); + } + + protected void openResource(final IFile resource) { + final IWorkbenchPage activePage = PHPeclipsePlugin.getActivePage(); + if (activePage != null) { + final Display display = getShell().getDisplay(); + if (display != null) { + display.asyncExec(new Runnable() { + public void run() { + try { + IDE.openEditor(activePage, resource, true); + } catch (PartInitException e) { + PHPeclipsePlugin.log(e); + } + } + }); + } + } + } + + /** + * Subclasses should override to perform the actions of the wizard. This + * method is run in the wizard container's context as a workspace runnable. + */ + protected void finishPage(IProgressMonitor monitor) + throws InterruptedException, CoreException { + } + + protected void handleFinishException(Shell shell, + InvocationTargetException e) { + String title = NewWizardMessages + .getString("NewElementWizard.op_error.title"); //$NON-NLS-1$ + String message = NewWizardMessages + .getString("NewElementWizard.op_error.message"); //$NON-NLS-1$ + ExceptionHandler.handle(e, shell, title, message); + } + + /* + * @see Wizard#performFinish + */ + public boolean performFinish() { + IWorkspaceRunnable op = new IWorkspaceRunnable() { + public void run(IProgressMonitor monitor) throws CoreException, + OperationCanceledException { + try { + finishPage(monitor); + } catch (InterruptedException e) { + throw new OperationCanceledException(e.getMessage()); + } + } + }; + try { + getContainer().run(false, true, new WorkbenchRunnableAdapter(op)); + } catch (InvocationTargetException e) { + handleFinishException(getShell(), e); + return false; + } catch (InterruptedException e) { + return false; + } + return true; + } + + // protected void warnAboutTypeCommentDeprecation() { + // String key= IUIConstants.DIALOGSTORE_TYPECOMMENT_DEPRECATED; + // if (OptionalMessageDialog.isDialogEnabled(key)) { + // Templates templates= Templates.getInstance(); + // boolean isOldWorkspace= templates.getTemplates("filecomment").length > 0 + // && templates.getTemplates("typecomment").length > 0; + // //$NON-NLS-1$ //$NON-NLS-2$ + // if (!isOldWorkspace) { + // OptionalMessageDialog.setDialogEnabled(key, false); + // } + // String title= + // NewWizardMessages.getString("NewElementWizard.typecomment.deprecated.title"); + // //$NON-NLS-1$ + // String message= + // NewWizardMessages.getString("NewElementWizard.typecomment.deprecated.message"); + // //$NON-NLS-1$ + // OptionalMessageDialog.open(key, getShell(), title, + // OptionalMessageDialog.getDefaultImage(), message, + // OptionalMessageDialog.INFORMATION, new String[] { + // IDialogConstants.OK_LABEL }, 0); + // } + // } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench, + * org.eclipse.jface.viewers.IStructuredSelection) + */ + public void init(IWorkbench workbench, IStructuredSelection currentSelection) { + fWorkbench = workbench; + fSelection = currentSelection; + } + + public IStructuredSelection getSelection() { + return fSelection; + } + + public IWorkbench getWorkbench() { + return fWorkbench; + } + + protected void selectAndReveal(IResource newResource) { + BasicNewResourceWizard.selectAndReveal(newResource, fWorkbench + .getActiveWorkbenchWindow()); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/NewWizardMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/NewWizardMessages.java index 2291f3c..a78bece 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/NewWizardMessages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/NewWizardMessages.java @@ -10,20 +10,21 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.ui.wizards; - import java.text.MessageFormat; import java.util.MissingResourceException; import java.util.ResourceBundle; - public class NewWizardMessages { - private static final String RESOURCE_BUNDLE= NewWizardMessages.class.getName(); - private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); + private static final String RESOURCE_BUNDLE = NewWizardMessages.class + .getName(); + + private static ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); private NewWizardMessages() { } - + public static String getString(String key) { try { return fgResourceBundle.getString(key); @@ -31,11 +32,12 @@ public class NewWizardMessages { return '!' + key + '!'; } } - + /** * Gets a string from the resource bundle and formats it with the argument * - * @param key the string used to get the bundle value, must not be null + * @param key + * the string used to get the bundle value, must not be null */ public static String getFormattedString(String key, Object arg) { return MessageFormat.format(getString(key), new Object[] { arg }); @@ -43,7 +45,7 @@ public class NewWizardMessages { /** * Gets a string from the resource bundle and formats it with arguments - */ + */ public static String getFormattedString(String key, Object[] args) { return MessageFormat.format(getString(key), args); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/CheckedListDialogField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/CheckedListDialogField.java index 755815f..fe748f9 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/CheckedListDialogField.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/CheckedListDialogField.java @@ -26,89 +26,92 @@ import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Table; /** - * A list with checkboxes and a button bar. Typical buttons are 'Check All' and 'Uncheck All'. - * List model is independend of widget creation. - * DialogFields controls are: Label, List and Composite containing buttons. + * A list with checkboxes and a button bar. Typical buttons are 'Check All' and + * 'Uncheck All'. List model is independend of widget creation. DialogFields + * controls are: Label, List and Composite containing buttons. */ public class CheckedListDialogField extends ListDialogField { - + private int fCheckAllButtonIndex; + private int fUncheckAllButtonIndex; - + private List fCheckElements; - public CheckedListDialogField(IListAdapter adapter, String[] customButtonLabels, ILabelProvider lprovider) { + public CheckedListDialogField(IListAdapter adapter, + String[] customButtonLabels, ILabelProvider lprovider) { super(adapter, customButtonLabels, lprovider); - fCheckElements= new ArrayList(); - - fCheckAllButtonIndex= -1; - fUncheckAllButtonIndex= -1; + fCheckElements = new ArrayList(); + + fCheckAllButtonIndex = -1; + fUncheckAllButtonIndex = -1; } /** - * Sets the index of the 'check' button in the button label array passed in the constructor. - * The behaviour of the button marked as the check button will then be handled internally. - * (enable state, button invocation behaviour) - */ + * Sets the index of the 'check' button in the button label array passed in + * the constructor. The behaviour of the button marked as the check button + * will then be handled internally. (enable state, button invocation + * behaviour) + */ public void setCheckAllButtonIndex(int checkButtonIndex) { Assert.isTrue(checkButtonIndex < fButtonLabels.length); - fCheckAllButtonIndex= checkButtonIndex; + fCheckAllButtonIndex = checkButtonIndex; } /** - * Sets the index of the 'uncheck' button in the button label array passed in the constructor. - * The behaviour of the button marked as the uncheck button will then be handled internally. - * (enable state, button invocation behaviour) - */ + * Sets the index of the 'uncheck' button in the button label array passed + * in the constructor. The behaviour of the button marked as the uncheck + * button will then be handled internally. (enable state, button invocation + * behaviour) + */ public void setUncheckAllButtonIndex(int uncheckButtonIndex) { Assert.isTrue(uncheckButtonIndex < fButtonLabels.length); - fUncheckAllButtonIndex= uncheckButtonIndex; + fUncheckAllButtonIndex = uncheckButtonIndex; } - /* * @see ListDialogField#createTableViewer */ protected TableViewer createTableViewer(Composite parent) { - Table table= new Table(parent, SWT.CHECK + getListStyle()); - CheckboxTableViewer tableViewer= new CheckboxTableViewer(table); + Table table = new Table(parent, SWT.CHECK + getListStyle()); + CheckboxTableViewer tableViewer = new CheckboxTableViewer(table); tableViewer.addCheckStateListener(new ICheckStateListener() { public void checkStateChanged(CheckStateChangedEvent e) { doCheckStateChanged(e); } }); return tableViewer; - } - - + } + /* * @see ListDialogField#getListControl */ public Control getListControl(Composite parent) { - Control control= super.getListControl(parent); + Control control = super.getListControl(parent); if (parent != null) { - ((CheckboxTableViewer)fTable).setCheckedElements(fCheckElements.toArray()); + ((CheckboxTableViewer) fTable).setCheckedElements(fCheckElements + .toArray()); } return control; - } - + } + /* - * @see DialogField#dialogFieldChanged - * Hooks in to get element changes to update check model. + * @see DialogField#dialogFieldChanged Hooks in to get element changes to + * update check model. */ public void dialogFieldChanged() { - for (int i= fCheckElements.size() -1; i >= 0; i--) { + for (int i = fCheckElements.size() - 1; i >= 0; i--) { if (!fElements.contains(fCheckElements.get(i))) { fCheckElements.remove(i); } } super.dialogFieldChanged(); - } - + } + private void checkStateChanged() { - //call super and do not update check model + // call super and do not update check model super.dialogFieldChanged(); - } + } /** * Gets the checked elements. @@ -116,72 +119,72 @@ public class CheckedListDialogField extends ListDialogField { public List getCheckedElements() { return new ArrayList(fCheckElements); } - + /** * Returns true if the element is checked. */ public boolean isChecked(Object obj) { return fCheckElements.contains(obj); - } - + } + /** * Sets the checked elements. - */ + */ public void setCheckedElements(List list) { - fCheckElements= new ArrayList(list); + fCheckElements = new ArrayList(list); if (fTable != null) { - ((CheckboxTableViewer)fTable).setCheckedElements(list.toArray()); + ((CheckboxTableViewer) fTable).setCheckedElements(list.toArray()); } checkStateChanged(); } /** * Sets the checked state of an element. - */ + */ public void setChecked(Object object, boolean state) { setCheckedWithoutUpdate(object, state); checkStateChanged(); } - + /** - * Sets the checked state of an element. No dialog changed listener is informed. - */ + * Sets the checked state of an element. No dialog changed listener is + * informed. + */ public void setCheckedWithoutUpdate(Object object, boolean state) { if (!fCheckElements.contains(object)) { fCheckElements.add(object); } if (fTable != null) { - ((CheckboxTableViewer)fTable).setChecked(object, state); + ((CheckboxTableViewer) fTable).setChecked(object, state); } } /** * Sets the check state of all elements - */ + */ public void checkAll(boolean state) { if (state) { - fCheckElements= getElements(); + fCheckElements = getElements(); } else { fCheckElements.clear(); } if (fTable != null) { - ((CheckboxTableViewer)fTable).setAllChecked(state); + ((CheckboxTableViewer) fTable).setAllChecked(state); } checkStateChanged(); } - - + private void doCheckStateChanged(CheckStateChangedEvent e) { if (e.getChecked()) { fCheckElements.add(e.getElement()); } else { fCheckElements.remove(e.getElement()); - } + } checkStateChanged(); } - + // ------ enable / disable management - + /* * @see ListDialogField#getManagedButtonState */ @@ -192,11 +195,11 @@ public class CheckedListDialogField extends ListDialogField { return !fElements.isEmpty(); } return super.getManagedButtonState(sel, index); - } + } /* * @see ListDialogField#extraButtonPressed - */ + */ protected boolean managedButtonPressed(int index) { if (index == fCheckAllButtonIndex) { checkAll(true); @@ -207,9 +210,5 @@ public class CheckedListDialogField extends ListDialogField { } return true; } - - - - } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/ComboDialogField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/ComboDialogField.java index 6803557..777e4bf 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/ComboDialogField.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/ComboDialogField.java @@ -24,55 +24,60 @@ import org.eclipse.swt.widgets.Label; * Dialog field containing a label and a combo control. */ public class ComboDialogField extends DialogField { - + private String fText; + private int fSelectionIndex; + private String[] fItems; + private Combo fComboControl; + private ModifyListener fModifyListener; + private int fFlags; - + public ComboDialogField(int flags) { super(); - fText= ""; //$NON-NLS-1$ - fItems= new String[0]; - fFlags= flags; - fSelectionIndex= -1; + fText = ""; //$NON-NLS-1$ + fItems = new String[0]; + fFlags = flags; + fSelectionIndex = -1; } - + // ------- layout helpers - + /* * @see DialogField#doFillIntoGrid */ public Control[] doFillIntoGrid(Composite parent, int nColumns) { assertEnoughColumns(nColumns); - - Label label= getLabelControl(parent); + + Label label = getLabelControl(parent); label.setLayoutData(gridDataForLabel(1)); - Combo combo= getComboControl(parent); + Combo combo = getComboControl(parent); combo.setLayoutData(gridDataForCombo(nColumns - 1)); - + return new Control[] { label, combo }; - } + } /* * @see DialogField#getNumberOfControls */ public int getNumberOfControls() { - return 2; + return 2; } - + protected static GridData gridDataForCombo(int span) { - GridData gd= new GridData(); - gd.horizontalAlignment= GridData.FILL; - gd.grabExcessHorizontalSpace= false; - gd.horizontalSpan= span; + GridData gd = new GridData(); + gd.horizontalAlignment = GridData.FILL; + gd.grabExcessHorizontalSpace = false; + gd.horizontalSpan = span; return gd; - } - + } + // ------- focus methods - + /* * @see DialogField#setFocus */ @@ -82,31 +87,34 @@ public class ComboDialogField extends DialogField { } return true; } - - // ------- ui creation + + // ------- ui creation /** * Creates or returns the created combo control. - * @param parent The parent composite or null when the widget has - * already been created. - */ + * + * @param parent + * The parent composite or null when the widget + * has already been created. + */ public Combo getComboControl(Composite parent) { if (fComboControl == null) { assertCompositeNotNull(parent); - fModifyListener= new ModifyListener() { + fModifyListener = new ModifyListener() { public void modifyText(ModifyEvent e) { doModifyText(e); } }; - SelectionListener selectionListener= new SelectionListener() { + SelectionListener selectionListener = new SelectionListener() { public void widgetSelected(SelectionEvent e) { doSelectionChanged(e); } - - public void widgetDefaultSelected(SelectionEvent e) { }; + + public void widgetDefaultSelected(SelectionEvent e) { + }; }; - - fComboControl= new Combo(parent, fFlags); + + fComboControl = new Combo(parent, fFlags); // moved up due to 1GEUNW2 fComboControl.setItems(fItems); if (fSelectionIndex != -1) { @@ -120,106 +128,105 @@ public class ComboDialogField extends DialogField { fComboControl.setEnabled(isEnabled()); } return fComboControl; - } - + } + private void doModifyText(ModifyEvent e) { if (isOkToUse(fComboControl)) { - fText= fComboControl.getText(); - fSelectionIndex= fComboControl.getSelectionIndex(); + fText = fComboControl.getText(); + fSelectionIndex = fComboControl.getSelectionIndex(); } dialogFieldChanged(); } - + private void doSelectionChanged(SelectionEvent e) { if (isOkToUse(fComboControl)) { - fItems= fComboControl.getItems(); - fText= fComboControl.getText(); - fSelectionIndex= fComboControl.getSelectionIndex(); + fItems = fComboControl.getItems(); + fText = fComboControl.getText(); + fSelectionIndex = fComboControl.getSelectionIndex(); } - dialogFieldChanged(); + dialogFieldChanged(); } - + // ------ enable / disable management - + /* * @see DialogField#updateEnableState - */ + */ protected void updateEnableState() { - super.updateEnableState(); + super.updateEnableState(); if (isOkToUse(fComboControl)) { fComboControl.setEnabled(isEnabled()); - } - } - - // ------ text access - + } + } + + // ------ text access + /** * Gets the combo items. - */ + */ public String[] getItems() { return fItems; } - + /** * Sets the combo items. Triggers a dialog-changed event. */ public void setItems(String[] items) { - fItems= items; + fItems = items; if (isOkToUse(fComboControl)) { fComboControl.setItems(items); } dialogFieldChanged(); } - + /** * Gets the text. - */ + */ public String getText() { return fText; } - + /** * Sets the text. Triggers a dialog-changed event. */ public void setText(String text) { - fText= text; + fText = text; if (isOkToUse(fComboControl)) { fComboControl.setText(text); } else { dialogFieldChanged(); - } + } } /** * Selects an item. - */ + */ public void selectItem(int index) { if (isOkToUse(fComboControl)) { fComboControl.select(index); } else { if (index >= 0 && index < fItems.length) { - fText= fItems[index]; - fSelectionIndex= index; + fText = fItems[index]; + fSelectionIndex = index; } } dialogFieldChanged(); } - + public int getSelectionIndex() { return fSelectionIndex; } - /** * Sets the text without triggering a dialog-changed event. */ public void setTextWithoutUpdate(String text) { - fText= text; + fText = text; if (isOkToUse(fComboControl)) { fComboControl.removeModifyListener(fModifyListener); fComboControl.setText(text); fComboControl.addModifyListener(fModifyListener); } } - + } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/DialogField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/DialogField.java index ac4f483..b624ec5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/DialogField.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/DialogField.java @@ -19,60 +19,60 @@ import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; /** - * Base class of all dialog fields. - * Dialog fields manage controls together with the model, independed - * from the creation time of the widgets. - * - support for automated layouting. - * - enable / disable, set focus a concept of the base class. + * Base class of all dialog fields. Dialog fields manage controls together with + * the model, independed from the creation time of the widgets. - support for + * automated layouting. - enable / disable, set focus a concept of the base + * class. * * DialogField have a label. - */ + */ public class DialogField { private Label fLabel; + protected String fLabelText; - + private IDialogFieldListener fDialogFieldListener; - + private boolean fEnabled; public DialogField() { - fEnabled= true; - fLabel= null; - fLabelText= ""; //$NON-NLS-1$ + fEnabled = true; + fLabel = null; + fLabelText = ""; //$NON-NLS-1$ } - + /** * Sets the label of the dialog field. */ public void setLabelText(String labeltext) { - fLabelText= labeltext; + fLabelText = labeltext; } - + // ------ change listener - + /** * Defines the listener for this dialog field. - */ + */ public final void setDialogFieldListener(IDialogFieldListener listener) { - fDialogFieldListener= listener; + fDialogFieldListener = listener; } /** * Programatical invocation of a dialog field change. - */ + */ public void dialogFieldChanged() { if (fDialogFieldListener != null) { fDialogFieldListener.dialogFieldChanged(this); } - } - + } + // ------- focus management - + /** - * Tries to set the focus to the dialog field. - * Returns true if the dialog field can take focus. - * To be reimplemented by dialog field implementors. + * Tries to set the focus to the dialog field. Returns true + * if the dialog field can take focus. To be reimplemented by dialog field + * implementors. */ public boolean setFocus() { return false; @@ -80,125 +80,127 @@ public class DialogField { /** * Posts setFocus to the display event queue. - */ + */ public void postSetFocusOnDialogField(Display display) { if (display != null) { - display.asyncExec( - new Runnable() { - public void run() { - setFocus(); - } + display.asyncExec(new Runnable() { + public void run() { + setFocus(); } - ); + }); } - } - + } + // ------- layout helpers - + /** - * Creates all controls of the dialog field and fills it to a composite. - * The composite is assumed to have MGridLayout as - * layout. - * The dialog field will adjust its controls' spans to the number of columns given. - * To be reimplemented by dialog field implementors. + * Creates all controls of the dialog field and fills it to a composite. The + * composite is assumed to have MGridLayout as layout. The + * dialog field will adjust its controls' spans to the number of columns + * given. To be reimplemented by dialog field implementors. */ public Control[] doFillIntoGrid(Composite parent, int nColumns) { assertEnoughColumns(nColumns); - - Label label= getLabelControl(parent); + + Label label = getLabelControl(parent); label.setLayoutData(gridDataForLabel(nColumns)); - + return new Control[] { label }; } - + /** - * Returns the number of columns of the dialog field. - * To be reimplemented by dialog field implementors. + * Returns the number of columns of the dialog field. To be reimplemented by + * dialog field implementors. */ public int getNumberOfControls() { - return 1; - } - + return 1; + } + protected static GridData gridDataForLabel(int span) { - GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); - gd.horizontalSpan= span; + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + gd.horizontalSpan = span; return gd; } - + // ------- ui creation /** * Creates or returns the created label widget. - * @param parent The parent composite or null if the widget has - * already been created. - */ + * + * @param parent + * The parent composite or null if the widget has + * already been created. + */ public Label getLabelControl(Composite parent) { if (fLabel == null) { assertCompositeNotNull(parent); - - fLabel= new Label(parent, SWT.LEFT | SWT.WRAP); + + fLabel = new Label(parent, SWT.LEFT | SWT.WRAP); fLabel.setFont(parent.getFont()); - fLabel.setEnabled(fEnabled); + fLabel.setEnabled(fEnabled); if (fLabelText != null && !"".equals(fLabelText)) { //$NON-NLS-1$ fLabel.setText(fLabelText); } else { // XXX: to avoid a 16 pixel wide empty label - revisit fLabel.setText("."); //$NON-NLS-1$ fLabel.setVisible(false); - } + } } return fLabel; } /** * Creates a spacer control. - * @param parent The parent composite - */ + * + * @param parent + * The parent composite + */ public static Control createEmptySpace(Composite parent) { return createEmptySpace(parent, 1); } /** - * Creates a spacer control with the given span. - * The composite is assumed to have MGridLayout as - * layout. - * @param parent The parent composite - */ + * Creates a spacer control with the given span. The composite is assumed to + * have MGridLayout as layout. + * + * @param parent + * The parent composite + */ public static Control createEmptySpace(Composite parent, int span) { - Label label= new Label(parent, SWT.LEFT); - GridData gd= new GridData(); - gd.horizontalAlignment= GridData.BEGINNING; - gd.grabExcessHorizontalSpace= false; - gd.horizontalSpan= span; - gd.horizontalIndent= 0; - gd.widthHint= 0; - gd.heightHint= 0; + Label label = new Label(parent, SWT.LEFT); + GridData gd = new GridData(); + gd.horizontalAlignment = GridData.BEGINNING; + gd.grabExcessHorizontalSpace = false; + gd.horizontalSpan = span; + gd.horizontalIndent = 0; + gd.widthHint = 0; + gd.heightHint = 0; label.setLayoutData(gd); return label; } - + /** * Tests is the control is not null and not disposed. - */ + */ protected final boolean isOkToUse(Control control) { return (control != null) && !(control.isDisposed()); } - + // --------- enable / disable management - + /** * Sets the enable state of the dialog field. */ public final void setEnabled(boolean enabled) { if (enabled != fEnabled) { - fEnabled= enabled; + fEnabled = enabled; updateEnableState(); } } - + /** - * Called when the enable state changed. - * To be extended by dialog field implementors. + * Called when the enable state changed. To be extended by dialog field + * implementors. */ protected void updateEnableState() { if (fLabel != null) { @@ -208,20 +210,19 @@ public class DialogField { /** * Gets the enable state of the dialog field. - */ + */ public final boolean isEnabled() { return fEnabled; } protected final void assertCompositeNotNull(Composite comp) { - Assert.isNotNull(comp, "uncreated control requested with composite null"); //$NON-NLS-1$ + Assert.isNotNull(comp, + "uncreated control requested with composite null"); //$NON-NLS-1$ } - + protected final void assertEnoughColumns(int nColumns) { - Assert.isTrue(nColumns >= getNumberOfControls(), "given number of columns is too small"); //$NON-NLS-1$ + Assert.isTrue(nColumns >= getNumberOfControls(), + "given number of columns is too small"); //$NON-NLS-1$ } - - - } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/IDialogFieldListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/IDialogFieldListener.java index cbee35c..2d497d8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/IDialogFieldListener.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/IDialogFieldListener.java @@ -14,7 +14,7 @@ package net.sourceforge.phpdt.internal.ui.wizards.dialogfields; * Change listener used by DialogField */ public interface IDialogFieldListener { - + /** * The dialog field has changed. */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/IListAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/IListAdapter.java index 79db768..825a78c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/IListAdapter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/IListAdapter.java @@ -11,23 +11,24 @@ package net.sourceforge.phpdt.internal.ui.wizards.dialogfields; /** - * Change listener used by ListDialogField and CheckedListDialogField + * Change listener used by ListDialogField and + * CheckedListDialogField */ public interface IListAdapter { - + /** * A button from the button bar has been pressed. */ void customButtonPressed(ListDialogField field, int index); - + /** * The selection of the list has changed. - */ + */ void selectionChanged(ListDialogField field); - + /** * En entry in the list has been double clicked */ - void doubleClicked(ListDialogField field); + void doubleClicked(ListDialogField field); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/IStringButtonAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/IStringButtonAdapter.java index 81be1b9..7a3f1cf 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/IStringButtonAdapter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/IStringButtonAdapter.java @@ -14,7 +14,7 @@ package net.sourceforge.phpdt.internal.ui.wizards.dialogfields; * Change listener used by StringButtonDialogField */ public interface IStringButtonAdapter { - + void changeControlPressed(DialogField field); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/ITreeListAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/ITreeListAdapter.java index 8aa130d..d4d186b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/ITreeListAdapter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/ITreeListAdapter.java @@ -16,15 +16,15 @@ import org.eclipse.swt.events.KeyEvent; * Change listener used by TreeListDialogField */ public interface ITreeListAdapter { - + /** * A button from the button bar has been pressed. */ void customButtonPressed(TreeListDialogField field, int index); - + /** * The selection of the list has changed. - */ + */ void selectionChanged(TreeListDialogField field); /** diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/LayoutUtil.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/LayoutUtil.java index 2abec85..baee413 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/LayoutUtil.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/LayoutUtil.java @@ -17,124 +17,143 @@ import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; public class LayoutUtil { - + /** * Calculates the number of columns needed by field editors */ public static int getNumberOfColumns(DialogField[] editors) { - int nCulumns= 0; - for (int i= 0; i < editors.length; i++) { - nCulumns= Math.max(editors[i].getNumberOfControls(), nCulumns); + int nCulumns = 0; + for (int i = 0; i < editors.length; i++) { + nCulumns = Math.max(editors[i].getNumberOfControls(), nCulumns); } return nCulumns; } - + /** * Creates a composite and fills in the given editors. - * @param labelOnTop Defines if the label of all fields should be on top of the fields - */ - public static void doDefaultLayout(Composite parent, DialogField[] editors, boolean labelOnTop) { + * + * @param labelOnTop + * Defines if the label of all fields should be on top of the + * fields + */ + public static void doDefaultLayout(Composite parent, DialogField[] editors, + boolean labelOnTop) { doDefaultLayout(parent, editors, labelOnTop, 0, 0, 0, 0); } /** * Creates a composite and fills in the given editors. - * @param labelOnTop Defines if the label of all fields should be on top of the fields - * @param minWidth The minimal width of the composite - * @param minHeight The minimal height of the composite + * + * @param labelOnTop + * Defines if the label of all fields should be on top of the + * fields + * @param minWidth + * The minimal width of the composite + * @param minHeight + * The minimal height of the composite */ - public static void doDefaultLayout(Composite parent, DialogField[] editors, boolean labelOnTop, int minWidth, int minHeight) { + public static void doDefaultLayout(Composite parent, DialogField[] editors, + boolean labelOnTop, int minWidth, int minHeight) { doDefaultLayout(parent, editors, labelOnTop, minWidth, minHeight, 0, 0); } /** * Creates a composite and fills in the given editors. - * @param labelOnTop Defines if the label of all fields should be on top of the fields - * @param minWidth The minimal width of the composite - * @param minHeight The minimal height of the composite - * @param marginWidth The margin width to be used by the composite - * @param marginHeight The margin height to be used by the composite + * + * @param labelOnTop + * Defines if the label of all fields should be on top of the + * fields + * @param minWidth + * The minimal width of the composite + * @param minHeight + * The minimal height of the composite + * @param marginWidth + * The margin width to be used by the composite + * @param marginHeight + * The margin height to be used by the composite * @deprecated - */ - public static void doDefaultLayout(Composite parent, DialogField[] editors, boolean labelOnTop, int minWidth, int minHeight, int marginWidth, int marginHeight) { - int nCulumns= getNumberOfColumns(editors); - Control[][] controls= new Control[editors.length][]; - for (int i= 0; i < editors.length; i++) { - controls[i]= editors[i].doFillIntoGrid(parent, nCulumns); + */ + public static void doDefaultLayout(Composite parent, DialogField[] editors, + boolean labelOnTop, int minWidth, int minHeight, int marginWidth, + int marginHeight) { + int nCulumns = getNumberOfColumns(editors); + Control[][] controls = new Control[editors.length][]; + for (int i = 0; i < editors.length; i++) { + controls[i] = editors[i].doFillIntoGrid(parent, nCulumns); } if (labelOnTop) { nCulumns--; modifyLabelSpans(controls, nCulumns); } - GridLayout layout= new GridLayout(); + GridLayout layout = new GridLayout(); if (marginWidth != SWT.DEFAULT) { - layout.marginWidth= marginWidth; + layout.marginWidth = marginWidth; } if (marginHeight != SWT.DEFAULT) { - layout.marginHeight= marginHeight; + layout.marginHeight = marginHeight; } - layout.numColumns= nCulumns; + layout.numColumns = nCulumns; parent.setLayout(layout); } - + private static void modifyLabelSpans(Control[][] controls, int nCulumns) { - for (int i= 0; i < controls.length; i++) { + for (int i = 0; i < controls.length; i++) { setHorizontalSpan(controls[i][0], nCulumns); } } - + /** * Sets the span of a control. Assumes that GridData is used. */ public static void setHorizontalSpan(Control control, int span) { - Object ld= control.getLayoutData(); + Object ld = control.getLayoutData(); if (ld instanceof GridData) { - ((GridData)ld).horizontalSpan= span; + ((GridData) ld).horizontalSpan = span; } else if (span != 1) { - GridData gd= new GridData(); - gd.horizontalSpan= span; + GridData gd = new GridData(); + gd.horizontalSpan = span; control.setLayoutData(gd); } - } + } /** * Sets the width hint of a control. Assumes that GridData is used. */ public static void setWidthHint(Control control, int widthHint) { - Object ld= control.getLayoutData(); + Object ld = control.getLayoutData(); if (ld instanceof GridData) { - ((GridData)ld).widthHint= widthHint; + ((GridData) ld).widthHint = widthHint; } } - + /** * Sets the heigthHint hint of a control. Assumes that GridData is used. */ public static void setHeigthHint(Control control, int heigthHint) { - Object ld= control.getLayoutData(); + Object ld = control.getLayoutData(); if (ld instanceof GridData) { - ((GridData)ld).heightHint= heigthHint; + ((GridData) ld).heightHint = heigthHint; } - } - + } + /** * Sets the horizontal indent of a control. Assumes that GridData is used. */ public static void setHorizontalIndent(Control control, int horizontalIndent) { - Object ld= control.getLayoutData(); + Object ld = control.getLayoutData(); if (ld instanceof GridData) { - ((GridData)ld).horizontalIndent= horizontalIndent; + ((GridData) ld).horizontalIndent = horizontalIndent; } } - + /** * Sets the horizontal indent of a control. Assumes that GridData is used. */ public static void setHorizontalGrabbing(Control control) { - Object ld= control.getLayoutData(); + Object ld = control.getLayoutData(); if (ld instanceof GridData) { - ((GridData)ld).grabExcessHorizontalSpace= true; + ((GridData) ld).grabExcessHorizontalSpace = true; } - } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/ListDialogField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/ListDialogField.java index 867e0f2..2c028b0 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/ListDialogField.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/ListDialogField.java @@ -10,7 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.ui.wizards.dialogfields; - import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -51,160 +50,178 @@ import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; /** - * A list with a button bar. - * Typical buttons are 'Add', 'Remove', 'Up' and 'Down'. - * List model is independend of widget creation. - * DialogFields controls are: Label, List and Composite containing buttons. + * A list with a button bar. Typical buttons are 'Add', 'Remove', 'Up' and + * 'Down'. List model is independend of widget creation. DialogFields controls + * are: Label, List and Composite containing buttons. */ public class ListDialogField extends DialogField { - + public static class ColumnsDescription { private ColumnLayoutData[] columns; + private String[] headers; + private boolean drawLines; - - public ColumnsDescription(ColumnLayoutData[] columns, String[] headers, boolean drawLines) { - this.columns= columns; - this.headers= headers; - this.drawLines= drawLines; + + public ColumnsDescription(ColumnLayoutData[] columns, String[] headers, + boolean drawLines) { + this.columns = columns; + this.headers = headers; + this.drawLines = drawLines; } - + public ColumnsDescription(String[] headers, boolean drawLines) { this(createColumnWeightData(headers.length), headers, drawLines); } - + public ColumnsDescription(int nColumns, boolean drawLines) { this(createColumnWeightData(nColumns), null, drawLines); } - + private static ColumnLayoutData[] createColumnWeightData(int nColumns) { - ColumnLayoutData[] data= new ColumnLayoutData[nColumns]; - for (int i= 0; i < nColumns; i++) { - data[i]= new ColumnWeightData(1); - } + ColumnLayoutData[] data = new ColumnLayoutData[nColumns]; + for (int i = 0; i < nColumns; i++) { + data[i] = new ColumnWeightData(1); + } return data; } } - + protected TableViewer fTable; + protected ILabelProvider fLabelProvider; + protected ListViewerAdapter fListViewerAdapter; + protected List fElements; + protected ViewerSorter fViewerSorter; protected String[] fButtonLabels; + private Button[] fButtonControls; - + private boolean[] fButtonsEnabled; - + private int fRemoveButtonIndex; + private int fUpButtonIndex; + private int fDownButtonIndex; - + private Label fLastSeparator; - + private Control fTableControl; + private Composite fButtonsControl; + private ISelection fSelectionWhenEnabled; - + private IListAdapter fListAdapter; - + private Object fParentElement; - + private ColumnsDescription fTableColumns; - /** * Creates the ListDialogField. - * @param adapter A listener for button invocation, selection changes. Can - * be null. - * @param buttonLabels The labels of all buttons: null is a valid array entry and - * marks a separator. - * @param lprovider The label provider to render the table entries - */ - public ListDialogField(IListAdapter adapter, String[] buttonLabels, ILabelProvider lprovider) { + * + * @param adapter + * A listener for button invocation, selection changes. Can be + * null. + * @param buttonLabels + * The labels of all buttons: null is a valid + * array entry and marks a separator. + * @param lprovider + * The label provider to render the table entries + */ + public ListDialogField(IListAdapter adapter, String[] buttonLabels, + ILabelProvider lprovider) { super(); - fListAdapter= adapter; + fListAdapter = adapter; + + fLabelProvider = lprovider; + fListViewerAdapter = new ListViewerAdapter(); + fParentElement = this; - fLabelProvider= lprovider; - fListViewerAdapter= new ListViewerAdapter(); - fParentElement= this; + fElements = new ArrayList(10); - fElements= new ArrayList(10); - - fButtonLabels= buttonLabels; + fButtonLabels = buttonLabels; if (fButtonLabels != null) { - int nButtons= fButtonLabels.length; - fButtonsEnabled= new boolean[nButtons]; - for (int i= 0; i < nButtons; i++) { - fButtonsEnabled[i]= true; + int nButtons = fButtonLabels.length; + fButtonsEnabled = new boolean[nButtons]; + for (int i = 0; i < nButtons; i++) { + fButtonsEnabled[i] = true; } - } - - fTable= null; - fTableControl= null; - fButtonsControl= null; - fTableColumns= null; - - fRemoveButtonIndex= -1; - fUpButtonIndex= -1; - fDownButtonIndex= -1; - } - + } + + fTable = null; + fTableControl = null; + fButtonsControl = null; + fTableColumns = null; + + fRemoveButtonIndex = -1; + fUpButtonIndex = -1; + fDownButtonIndex = -1; + } + /** - * Sets the index of the 'remove' button in the button label array passed in the constructor. - * The behaviour of the button marked as the 'remove' button will then be handled internally. - * (enable state, button invocation behaviour) - */ + * Sets the index of the 'remove' button in the button label array passed in + * the constructor. The behaviour of the button marked as the 'remove' + * button will then be handled internally. (enable state, button invocation + * behaviour) + */ public void setRemoveButtonIndex(int removeButtonIndex) { Assert.isTrue(removeButtonIndex < fButtonLabels.length); - fRemoveButtonIndex= removeButtonIndex; + fRemoveButtonIndex = removeButtonIndex; } /** - * Sets the index of the 'up' button in the button label array passed in the constructor. - * The behaviour of the button marked as the 'up' button will then be handled internally. - * (enable state, button invocation behaviour) - */ + * Sets the index of the 'up' button in the button label array passed in the + * constructor. The behaviour of the button marked as the 'up' button will + * then be handled internally. (enable state, button invocation behaviour) + */ public void setUpButtonIndex(int upButtonIndex) { Assert.isTrue(upButtonIndex < fButtonLabels.length); - fUpButtonIndex= upButtonIndex; + fUpButtonIndex = upButtonIndex; } /** - * Sets the index of the 'down' button in the button label array passed in the constructor. - * The behaviour of the button marked as the 'down' button will then be handled internally. - * (enable state, button invocation behaviour) - */ + * Sets the index of the 'down' button in the button label array passed in + * the constructor. The behaviour of the button marked as the 'down' button + * will then be handled internally. (enable state, button invocation + * behaviour) + */ public void setDownButtonIndex(int downButtonIndex) { Assert.isTrue(downButtonIndex < fButtonLabels.length); - fDownButtonIndex= downButtonIndex; + fDownButtonIndex = downButtonIndex; } - + /** * Sets the viewerSorter. - * @param viewerSorter The viewerSorter to set + * + * @param viewerSorter + * The viewerSorter to set */ public void setViewerSorter(ViewerSorter viewerSorter) { - fViewerSorter= viewerSorter; + fViewerSorter = viewerSorter; } - + public void setTableColumns(ColumnsDescription column) { - fTableColumns= column; + fTableColumns = column; } - - - + // ------ adapter communication - + private void buttonPressed(int index) { if (!managedButtonPressed(index) && fListAdapter != null) { fListAdapter.customButtonPressed(this, index); } } - + /** * Checks if the button pressed is handled internally + * * @return Returns true if button has been handled. */ protected boolean managedButtonPressed(int index) { @@ -219,95 +236,98 @@ public class ListDialogField extends DialogField { } return true; } - // ------ layout helpers - + /* * @see DialogField#doFillIntoGrid */ public Control[] doFillIntoGrid(Composite parent, int nColumns) { - PixelConverter converter= new PixelConverter(parent); - + PixelConverter converter = new PixelConverter(parent); + assertEnoughColumns(nColumns); - - Label label= getLabelControl(parent); - GridData gd= gridDataForLabel(1); - gd.verticalAlignment= GridData.BEGINNING; + + Label label = getLabelControl(parent); + GridData gd = gridDataForLabel(1); + gd.verticalAlignment = GridData.BEGINNING; label.setLayoutData(gd); - - Control list= getListControl(parent); - gd= new GridData(); - gd.horizontalAlignment= GridData.FILL; - gd.grabExcessHorizontalSpace= false; - gd.verticalAlignment= GridData.FILL; - gd.grabExcessVerticalSpace= true; - gd.horizontalSpan= nColumns - 2; - gd.widthHint= converter.convertWidthInCharsToPixels(50); - gd.heightHint= converter.convertHeightInCharsToPixels(6); + + Control list = getListControl(parent); + gd = new GridData(); + gd.horizontalAlignment = GridData.FILL; + gd.grabExcessHorizontalSpace = false; + gd.verticalAlignment = GridData.FILL; + gd.grabExcessVerticalSpace = true; + gd.horizontalSpan = nColumns - 2; + gd.widthHint = converter.convertWidthInCharsToPixels(50); + gd.heightHint = converter.convertHeightInCharsToPixels(6); list.setLayoutData(gd); - - Composite buttons= getButtonBox(parent); - gd= new GridData(); - gd.horizontalAlignment= GridData.FILL; - gd.grabExcessHorizontalSpace= false; - gd.verticalAlignment= GridData.FILL; - gd.grabExcessVerticalSpace= true; - gd.horizontalSpan= 1; + + Composite buttons = getButtonBox(parent); + gd = new GridData(); + gd.horizontalAlignment = GridData.FILL; + gd.grabExcessHorizontalSpace = false; + gd.verticalAlignment = GridData.FILL; + gd.grabExcessVerticalSpace = true; + gd.horizontalSpan = 1; buttons.setLayoutData(gd); - + return new Control[] { label, list, buttons }; } /* * @see DialogField#getNumberOfControls - */ + */ public int getNumberOfControls() { - return 3; + return 3; } /** - * Sets the minimal width of the buttons. Must be called after widget creation. - */ + * Sets the minimal width of the buttons. Must be called after widget + * creation. + */ public void setButtonsMinWidth(int minWidth) { if (fLastSeparator != null) { - ((GridData)fLastSeparator.getLayoutData()).widthHint= minWidth; + ((GridData) fLastSeparator.getLayoutData()).widthHint = minWidth; } } - - + // ------ ui creation - + /** - * Returns the list control. When called the first time, the control will be created. - * @param The parent composite when called the first time, or null - * after. + * Returns the list control. When called the first time, the control will be + * created. + * + * @param The + * parent composite when called the first time, or + * null after. */ public Control getListControl(Composite parent) { if (fTableControl == null) { assertCompositeNotNull(parent); - + if (fTableColumns == null) { - fTable= createTableViewer(parent); - Table tableControl= fTable.getTable(); - - fTableControl= tableControl; + fTable = createTableViewer(parent); + Table tableControl = fTable.getTable(); + + fTableControl = tableControl; tableControl.setLayout(new TableLayout()); } else { - TableLayoutComposite composite= new TableLayoutComposite(parent, SWT.NONE); - fTableControl= composite; - - fTable= createTableViewer(composite); - Table tableControl= fTable.getTable(); - + TableLayoutComposite composite = new TableLayoutComposite( + parent, SWT.NONE); + fTableControl = composite; + + fTable = createTableViewer(composite); + Table tableControl = fTable.getTable(); + tableControl.setHeaderVisible(fTableColumns.headers != null); tableControl.setLinesVisible(fTableColumns.drawLines); - ColumnLayoutData[] columns= fTableColumns.columns; - for (int i= 0; i < columns.length; i++) { + ColumnLayoutData[] columns = fTableColumns.columns; + for (int i = 0; i < columns.length; i++) { composite.addColumnData(columns[i]); - TableColumn column= new TableColumn(tableControl, SWT.NONE); - //tableLayout.addColumnData(columns[i]); + TableColumn column = new TableColumn(tableControl, SWT.NONE); + // tableLayout.addColumnData(columns[i]); if (fTableColumns.headers != null) { column.setText(fTableColumns.headers[i]); } @@ -319,20 +339,20 @@ public class ListDialogField extends DialogField { handleKeyPressed(e); } }); - - //fTableControl.setLayout(tableLayout); - + + // fTableControl.setLayout(tableLayout); + fTable.setContentProvider(fListViewerAdapter); fTable.setLabelProvider(fLabelProvider); fTable.addSelectionChangedListener(fListViewerAdapter); fTable.addDoubleClickListener(fListViewerAdapter); - + fTable.setInput(fParentElement); - + if (fViewerSorter != null) { fTable.setSorter(fViewerSorter); } - + fTableControl.setEnabled(isEnabled()); if (fSelectionWhenEnabled != null) { postSetSelection(fSelectionWhenEnabled); @@ -343,104 +363,110 @@ public class ListDialogField extends DialogField { /** * Returns the internally used table viewer. - */ + */ public TableViewer getTableViewer() { return fTable; } - - /* + + /* * Subclasses may override to specify a different style. */ - protected int getListStyle(){ - int style= SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL ; + protected int getListStyle() { + int style = SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL; if (fTableColumns != null) { style |= SWT.FULL_SELECTION; } - return style; + return style; } - + protected TableViewer createTableViewer(Composite parent) { - Table table= new Table(parent, getListStyle()); + Table table = new Table(parent, getListStyle()); return new TableViewer(table); - } - - protected Button createButton(Composite parent, String label, SelectionListener listener) { - Button button= new Button(parent, SWT.PUSH); + } + + protected Button createButton(Composite parent, String label, + SelectionListener listener) { + Button button = new Button(parent, SWT.PUSH); button.setText(label); button.addSelectionListener(listener); - GridData gd= new GridData(); - gd.horizontalAlignment= GridData.FILL; - gd.grabExcessHorizontalSpace= true; - gd.verticalAlignment= GridData.BEGINNING; + GridData gd = new GridData(); + gd.horizontalAlignment = GridData.FILL; + gd.grabExcessHorizontalSpace = true; + gd.verticalAlignment = GridData.BEGINNING; gd.heightHint = SWTUtil.getButtonHeightHint(button); gd.widthHint = SWTUtil.getButtonWidthHint(button); - + button.setLayoutData(gd); return button; } - + private Label createSeparator(Composite parent) { - Label separator= new Label(parent, SWT.NONE); + Label separator = new Label(parent, SWT.NONE); separator.setVisible(false); - GridData gd= new GridData(); - gd.horizontalAlignment= GridData.FILL; - gd.verticalAlignment= GridData.BEGINNING; - gd.heightHint= 4; + GridData gd = new GridData(); + gd.horizontalAlignment = GridData.FILL; + gd.verticalAlignment = GridData.BEGINNING; + gd.heightHint = 4; separator.setLayoutData(gd); return separator; - } + } /** - * Returns the composite containing the buttons. When called the first time, the control - * will be created. - * @param The parent composite when called the first time, or null - * after. - */ + * Returns the composite containing the buttons. When called the first time, + * the control will be created. + * + * @param The + * parent composite when called the first time, or + * null after. + */ public Composite getButtonBox(Composite parent) { if (fButtonsControl == null) { assertCompositeNotNull(parent); - - SelectionListener listener= new SelectionListener() { + + SelectionListener listener = new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { doButtonSelected(e); } + public void widgetSelected(SelectionEvent e) { doButtonSelected(e); } }; - - Composite contents= new Composite(parent, SWT.NULL); - GridLayout layout= new GridLayout(); - layout.marginWidth= 0; - layout.marginHeight= 0; + + Composite contents = new Composite(parent, SWT.NULL); + GridLayout layout = new GridLayout(); + layout.marginWidth = 0; + layout.marginHeight = 0; contents.setLayout(layout); - + if (fButtonLabels != null) { - fButtonControls= new Button[fButtonLabels.length]; - for (int i= 0; i < fButtonLabels.length; i++) { - String currLabel= fButtonLabels[i]; + fButtonControls = new Button[fButtonLabels.length]; + for (int i = 0; i < fButtonLabels.length; i++) { + String currLabel = fButtonLabels[i]; if (currLabel != null) { - fButtonControls[i]= createButton(contents, currLabel, listener); - fButtonControls[i].setEnabled(isEnabled() && fButtonsEnabled[i]); + fButtonControls[i] = createButton(contents, currLabel, + listener); + fButtonControls[i].setEnabled(isEnabled() + && fButtonsEnabled[i]); } else { - fButtonControls[i]= null; + fButtonControls[i] = null; createSeparator(contents); } } } - - fLastSeparator= createSeparator(contents); - + + fLastSeparator = createSeparator(contents); + updateButtonState(); - fButtonsControl= contents; + fButtonsControl = contents; } - + return fButtonsControl; } - + private void doButtonSelected(SelectionEvent e) { if (fButtonControls != null) { - for (int i= 0; i < fButtonControls.length; i++) { + for (int i = 0; i < fButtonControls.length; i++) { if (e.widget == fButtonControls[i]) { buttonPressed(i); return; @@ -448,44 +474,46 @@ public class ListDialogField extends DialogField { } } } - + /** - * Handles key events in the table viewer. Specifically - * when the delete key is pressed. + * Handles key events in the table viewer. Specifically when the delete key + * is pressed. */ protected void handleKeyPressed(KeyEvent event) { if (event.character == SWT.DEL && event.stateMask == 0) { - if (fRemoveButtonIndex != -1 && isButtonEnabled(fTable.getSelection(), fRemoveButtonIndex)) { + if (fRemoveButtonIndex != -1 + && isButtonEnabled(fTable.getSelection(), + fRemoveButtonIndex)) { managedButtonPressed(fRemoveButtonIndex); } - } - } - + } + } + // ------ enable / disable management /* * @see DialogField#dialogFieldChanged - */ + */ public void dialogFieldChanged() { super.dialogFieldChanged(); updateButtonState(); } - + /* * Updates the enable state of the all buttons - */ + */ protected void updateButtonState() { if (fButtonControls != null) { - ISelection sel= fTable.getSelection(); - for (int i= 0; i < fButtonControls.length; i++) { - Button button= fButtonControls[i]; + ISelection sel = fTable.getSelection(); + for (int i = 0; i < fButtonControls.length; i++) { + Button button = fButtonControls[i]; if (isOkToUse(button)) { button.setEnabled(isButtonEnabled(sel, i)); - } + } } } } - + protected boolean getManagedButtonState(ISelection sel, int index) { if (index == fRemoveButtonIndex) { return !sel.isEmpty(); @@ -495,22 +523,22 @@ public class ListDialogField extends DialogField { return !sel.isEmpty() && canMoveDown(); } return true; - } + } /* * @see DialogField#updateEnableState - */ + */ protected void updateEnableState() { super.updateEnableState(); - - boolean enabled= isEnabled(); + + boolean enabled = isEnabled(); if (isOkToUse(fTableControl)) { if (!enabled) { - fSelectionWhenEnabled= fTable.getSelection(); + fSelectionWhenEnabled = fTable.getSelection(); selectElements(null); } else { selectElements(fSelectionWhenEnabled); - fSelectionWhenEnabled= null; + fSelectionWhenEnabled = null; } fTableControl.setEnabled(enabled); } @@ -519,27 +547,26 @@ public class ListDialogField extends DialogField { /** * Sets a button enabled or disabled. - */ + */ public void enableButton(int index, boolean enable) { if (fButtonsEnabled != null && index < fButtonsEnabled.length) { - fButtonsEnabled[index]= enable; + fButtonsEnabled[index] = enable; updateButtonState(); } } - + private boolean isButtonEnabled(ISelection sel, int index) { - boolean extraState= getManagedButtonState(sel, index); + boolean extraState = getManagedButtonState(sel, index); return isEnabled() && extraState && fButtonsEnabled[index]; - } - + } // ------ model access - + /** * Sets the elements shown in the list. */ public void setElements(List elements) { - fElements= new ArrayList(elements); + fElements = new ArrayList(elements); if (fTable != null) { fTable.refresh(); } @@ -547,36 +574,37 @@ public class ListDialogField extends DialogField { } /** - * Gets the elements shown in the list. - * The list returned is a copy, so it can be modified by the user. - */ + * Gets the elements shown in the list. The list returned is a copy, so it + * can be modified by the user. + */ public List getElements() { return new ArrayList(fElements); } /** * Gets the elements shown at the given index. - */ + */ public Object getElement(int index) { return fElements.get(index); } - + /** - * Gets the index of an element in the list or -1 if element is not in list. - */ + * Gets the index of an element in the list or -1 if element is not in list. + */ public int getIndexOfElement(Object elem) { return fElements.indexOf(elem); - } + } /** * Replace an element. - */ - public void replaceElement(Object oldElement, Object newElement) throws IllegalArgumentException { - int idx= fElements.indexOf(oldElement); + */ + public void replaceElement(Object oldElement, Object newElement) + throws IllegalArgumentException { + int idx = fElements.indexOf(oldElement); if (idx != -1) { fElements.set(idx, newElement); if (fTable != null) { - List selected= getSelectedElements(); + List selected = getSelectedElements(); if (selected.remove(oldElement)) { selected.add(newElement); } @@ -587,12 +615,12 @@ public class ListDialogField extends DialogField { } else { throw new IllegalArgumentException(); } - } + } /** * Adds an element at the end of the list. - */ - public void addElement(Object element) { + */ + public void addElement(Object element) { if (fElements.contains(element)) { return; } @@ -605,19 +633,19 @@ public class ListDialogField extends DialogField { /** * Adds elements at the end of the list. - */ + */ public void addElements(List elements) { - int nElements= elements.size(); - + int nElements = elements.size(); + if (nElements > 0) { // filter duplicated - ArrayList elementsToAdd= new ArrayList(nElements); - - for (int i= 0; i < nElements; i++) { - Object elem= elements.get(i); + ArrayList elementsToAdd = new ArrayList(nElements); + + for (int i = 0; i < nElements; i++) { + Object elem = elements.get(i); if (!fElements.contains(elem)) { elementsToAdd.add(elem); - } + } } fElements.addAll(elementsToAdd); if (fTable != null) { @@ -625,11 +653,11 @@ public class ListDialogField extends DialogField { } dialogFieldChanged(); } - } + } /** * Adds an element at a position. - */ + */ public void insertElementAt(Object element, int index) { if (fElements.contains(element)) { return; @@ -638,14 +666,13 @@ public class ListDialogField extends DialogField { if (fTable != null) { fTable.add(element); } - - dialogFieldChanged(); - } + dialogFieldChanged(); + } /** * Adds an element at a position. - */ + */ public void removeAllElements() { if (fElements.size() > 0) { fElements.clear(); @@ -655,10 +682,10 @@ public class ListDialogField extends DialogField { dialogFieldChanged(); } } - + /** * Removes an element from the list. - */ + */ public void removeElement(Object element) throws IllegalArgumentException { if (fElements.remove(element)) { if (fTable != null) { @@ -672,7 +699,7 @@ public class ListDialogField extends DialogField { /** * Removes elements from the list. - */ + */ public void removeElements(List elements) { if (elements.size() > 0) { fElements.removeAll(elements); @@ -685,41 +712,39 @@ public class ListDialogField extends DialogField { /** * Gets the number of elements - */ + */ public int getSize() { return fElements.size(); } - public void selectElements(ISelection selection) { - fSelectionWhenEnabled= selection; + fSelectionWhenEnabled = selection; if (fTable != null) { fTable.setSelection(selection, true); } } - + public void selectFirstElement() { - Object element= null; + Object element = null; if (fViewerSorter != null) { - Object[] arr= fElements.toArray(); + Object[] arr = fElements.toArray(); fViewerSorter.sort(fTable, arr); if (arr.length > 0) { - element= arr[0]; + element = arr[0]; } } else { if (fElements.size() > 0) { - element= fElements.get(0); + element = fElements.get(0); } } if (element != null) { selectElements(new StructuredSelection(element)); } } - - + public void postSetSelection(final ISelection selection) { if (isOkToUse(fTableControl)) { - Display d= fTableControl.getDisplay(); + Display d = fTableControl.getDisplay(); d.asyncExec(new Runnable() { public void run() { if (isOkToUse(fTableControl)) { @@ -729,7 +754,7 @@ public class ListDialogField extends DialogField { }); } } - + /** * Refreshes the table. */ @@ -738,69 +763,68 @@ public class ListDialogField extends DialogField { fTable.refresh(); } } - + // ------- list maintenance - + private List moveUp(List elements, List move) { - int nElements= elements.size(); - List res= new ArrayList(nElements); - Object floating= null; - for (int i= 0; i < nElements; i++) { - Object curr= elements.get(i); + int nElements = elements.size(); + List res = new ArrayList(nElements); + Object floating = null; + for (int i = 0; i < nElements; i++) { + Object curr = elements.get(i); if (move.contains(curr)) { res.add(curr); } else { if (floating != null) { res.add(floating); } - floating= curr; + floating = curr; } } if (floating != null) { res.add(floating); } return res; - } - + } + private void moveUp(List toMoveUp) { if (toMoveUp.size() > 0) { setElements(moveUp(fElements, toMoveUp)); fTable.reveal(toMoveUp.get(0)); } } - + private void moveDown(List toMoveDown) { if (toMoveDown.size() > 0) { setElements(reverse(moveUp(reverse(fElements), toMoveDown))); fTable.reveal(toMoveDown.get(toMoveDown.size() - 1)); } } - + private List reverse(List p) { - List reverse= new ArrayList(p.size()); - for (int i= p.size()-1; i >= 0; i--) { + List reverse = new ArrayList(p.size()); + for (int i = p.size() - 1; i >= 0; i--) { reverse.add(p.get(i)); } return reverse; } - - + private void remove() { removeElements(getSelectedElements()); } - + private void up() { moveUp(getSelectedElements()); } - + private void down() { moveDown(getSelectedElements()); } - + private boolean canMoveUp() { if (isOkToUse(fTableControl)) { - int[] indc= fTable.getTable().getSelectionIndices(); - for (int i= 0; i < indc.length; i++) { + int[] indc = fTable.getTable().getSelectionIndices(); + for (int i = 0; i < indc.length; i++) { if (indc[i] != i) { return true; } @@ -808,29 +832,29 @@ public class ListDialogField extends DialogField { } return false; } - + private boolean canMoveDown() { if (isOkToUse(fTableControl)) { - int[] indc= fTable.getTable().getSelectionIndices(); - int k= fElements.size() - 1; - for (int i= indc.length - 1; i >= 0 ; i--, k--) { + int[] indc = fTable.getTable().getSelectionIndices(); + int k = fElements.size() - 1; + for (int i = indc.length - 1; i >= 0; i--, k--) { if (indc[i] != k) { return true; } } } return false; - } + } /** * Returns the selected elements. */ public List getSelectedElements() { - List result= new ArrayList(); + List result = new ArrayList(); if (fTable != null) { - ISelection selection= fTable.getSelection(); + ISelection selection = fTable.getSelection(); if (selection instanceof IStructuredSelection) { - Iterator iter= ((IStructuredSelection)selection).iterator(); + Iterator iter = ((IStructuredSelection) selection).iterator(); while (iter.hasNext()) { result.add(iter.next()); } @@ -838,35 +862,38 @@ public class ListDialogField extends DialogField { } return result; } - + // ------- ListViewerAdapter - - private class ListViewerAdapter implements IStructuredContentProvider, ISelectionChangedListener, IDoubleClickListener { + + private class ListViewerAdapter implements IStructuredContentProvider, + ISelectionChangedListener, IDoubleClickListener { // ------- ITableContentProvider Interface ------------ - + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { // will never happen } - + public boolean isDeleted(Object element) { return false; } - + public void dispose() { } - + public Object[] getElements(Object obj) { return fElements.toArray(); } - + // ------- ISelectionChangedListener Interface ------------ - + public void selectionChanged(SelectionChangedEvent event) { doListSelected(event); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.jface.viewers.IDoubleClickListener#doubleClick(org.eclipse.jface.viewers.DoubleClickEvent) */ public void doubleClick(DoubleClickEvent event) { @@ -874,21 +901,18 @@ public class ListDialogField extends DialogField { } } - - + protected void doListSelected(SelectionChangedEvent event) { updateButtonState(); if (fListAdapter != null) { fListAdapter.selectionChanged(this); } } - + protected void doDoubleClick(DoubleClickEvent event) { if (fListAdapter != null) { fListAdapter.doubleClicked(this); } - } - - + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/SelectionButtonDialogField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/SelectionButtonDialogField.java index a97e525..57b9cd2 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/SelectionButtonDialogField.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/SelectionButtonDialogField.java @@ -20,54 +20,56 @@ import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; - - /** * Dialog Field containing a single button such as a radio or checkbox button. */ public class SelectionButtonDialogField extends DialogField { - + private Button fButton; + private boolean fIsSelected; + private DialogField[] fAttachedDialogFields; + private int fButtonStyle; /** - * Creates a selection button. - * Allowed button styles: SWT.RADIO, SWT.CHECK, SWT.TOGGLE, SWT.PUSH + * Creates a selection button. Allowed button styles: SWT.RADIO, SWT.CHECK, + * SWT.TOGGLE, SWT.PUSH */ public SelectionButtonDialogField(int buttonStyle) { super(); - fIsSelected= false; - fAttachedDialogFields= null; - fButtonStyle= buttonStyle; + fIsSelected = false; + fAttachedDialogFields = null; + fButtonStyle = buttonStyle; } - + /** - * Attaches a field to the selection state of the selection button. - * The attached field will be disabled if the selection button is not selected. + * Attaches a field to the selection state of the selection button. The + * attached field will be disabled if the selection button is not selected. */ public void attachDialogField(DialogField dialogField) { attachDialogFields(new DialogField[] { dialogField }); } /** - * Attaches fields to the selection state of the selection button. - * The attached fields will be disabled if the selection button is not selected. - */ + * Attaches fields to the selection state of the selection button. The + * attached fields will be disabled if the selection button is not selected. + */ public void attachDialogFields(DialogField[] dialogFields) { - fAttachedDialogFields= dialogFields; - for (int i= 0; i < dialogFields.length; i++) { + fAttachedDialogFields = dialogFields; + for (int i = 0; i < dialogFields.length; i++) { dialogFields[i].setEnabled(fIsSelected); } - } - + } + /** - * Returns true is teh gived field is attached to the selection button. + * Returns true is teh gived field is attached to the + * selection button. */ public boolean isAttached(DialogField editor) { if (fAttachedDialogFields != null) { - for (int i=0; i < fAttachedDialogFields.length; i++) { + for (int i = 0; i < fAttachedDialogFields.length; i++) { if (fAttachedDialogFields[i] == editor) { return true; } @@ -75,49 +77,52 @@ public class SelectionButtonDialogField extends DialogField { } return false; } - + // ------- layout helpers - + /* * @see DialogField#doFillIntoGrid */ public Control[] doFillIntoGrid(Composite parent, int nColumns) { assertEnoughColumns(nColumns); - - Button button= getSelectionButton(parent); - GridData gd= new GridData(); - gd.horizontalSpan= nColumns; - gd.horizontalAlignment= GridData.FILL; + + Button button = getSelectionButton(parent); + GridData gd = new GridData(); + gd.horizontalSpan = nColumns; + gd.horizontalAlignment = GridData.FILL; if (fButtonStyle == SWT.PUSH) { gd.heightHint = SWTUtil.getButtonHeightHint(button); gd.widthHint = SWTUtil.getButtonWidthHint(button); - } - + } + button.setLayoutData(gd); - + return new Control[] { button }; - } + } /* * @see DialogField#getNumberOfControls - */ + */ public int getNumberOfControls() { - return 1; - } - - // ------- ui creation + return 1; + } + + // ------- ui creation /** - * Returns the selection button widget. When called the first time, the widget will be created. - * @param The parent composite when called the first time, or null - * after. - */ + * Returns the selection button widget. When called the first time, the + * widget will be created. + * + * @param The + * parent composite when called the first time, or + * null after. + */ public Button getSelectionButton(Composite group) { if (fButton == null) { assertCompositeNotNull(group); - - fButton= new Button(group, fButtonStyle); - fButton.setFont(group.getFont()); + + fButton = new Button(group, fButtonStyle); + fButton.setFont(group.getFont()); fButton.setText(fLabelText); fButton.setEnabled(isEnabled()); fButton.setSelection(fIsSelected); @@ -125,29 +130,30 @@ public class SelectionButtonDialogField extends DialogField { public void widgetDefaultSelected(SelectionEvent e) { doWidgetSelected(e); } + public void widgetSelected(SelectionEvent e) { doWidgetSelected(e); } - }); + }); } return fButton; } - + private void doWidgetSelected(SelectionEvent e) { if (isOkToUse(fButton)) { changeValue(fButton.getSelection()); } - } - + } + private void changeValue(boolean newState) { if (fIsSelected != newState) { - fIsSelected= newState; + fIsSelected = newState; if (fAttachedDialogFields != null) { - boolean focusSet= false; - for (int i= 0; i < fAttachedDialogFields.length; i++) { + boolean focusSet = false; + for (int i = 0; i < fAttachedDialogFields.length; i++) { fAttachedDialogFields[i].setEnabled(fIsSelected); if (fIsSelected && !focusSet) { - focusSet= fAttachedDialogFields[i].setFocus(); + focusSet = fAttachedDialogFields[i].setFocus(); } } } @@ -155,10 +161,10 @@ public class SelectionButtonDialogField extends DialogField { } else if (fButtonStyle == SWT.PUSH) { dialogFieldChanged(); } - } + } + + // ------ model access - // ------ model access - /** * Returns the selection state of the button. */ @@ -168,7 +174,7 @@ public class SelectionButtonDialogField extends DialogField { /** * Sets the selection state of the button. - */ + */ public void setSelection(boolean selected) { changeValue(selected); if (isOkToUse(fButton)) { @@ -180,15 +186,12 @@ public class SelectionButtonDialogField extends DialogField { /* * @see DialogField#updateEnableState - */ + */ protected void updateEnableState() { super.updateEnableState(); if (isOkToUse(fButton)) { fButton.setEnabled(isEnabled()); - } + } } - - - - + } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/SelectionButtonDialogFieldGroup.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/SelectionButtonDialogFieldGroup.java index e846b67..2655aa8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/SelectionButtonDialogFieldGroup.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/SelectionButtonDialogFieldGroup.java @@ -26,95 +26,103 @@ import org.eclipse.swt.widgets.Label; * Dialog field describing a group with buttons (Checkboxes, radio buttons..) */ public class SelectionButtonDialogFieldGroup extends DialogField { - + private Composite fButtonComposite; - + private Button[] fButtons; + private String[] fButtonNames; + private boolean[] fButtonsSelected; + private boolean[] fButtonsEnabled; - + private int fGroupBorderStyle; + private int fGroupNumberOfColumns; - private int fButtonsStyle; - + + private int fButtonsStyle; + /** * Creates a group without border. */ - public SelectionButtonDialogFieldGroup(int buttonsStyle, String[] buttonNames, int nColumns) { - this(buttonsStyle, buttonNames, nColumns, SWT.NONE); - } - - + public SelectionButtonDialogFieldGroup(int buttonsStyle, + String[] buttonNames, int nColumns) { + this(buttonsStyle, buttonNames, nColumns, SWT.NONE); + } + /** - * Creates a group with border (label in border). - * Accepted button styles are: SWT.RADIO, SWT.CHECK, SWT.TOGGLE - * For border styles see Group - */ - public SelectionButtonDialogFieldGroup(int buttonsStyle, String[] buttonNames, int nColumns, int borderStyle) { + * Creates a group with border (label in border). Accepted button styles + * are: SWT.RADIO, SWT.CHECK, SWT.TOGGLE For border styles see + * Group + */ + public SelectionButtonDialogFieldGroup(int buttonsStyle, + String[] buttonNames, int nColumns, int borderStyle) { super(); - - Assert.isTrue(buttonsStyle == SWT.RADIO || buttonsStyle == SWT.CHECK || buttonsStyle == SWT.TOGGLE); - fButtonNames= buttonNames; - - int nButtons= buttonNames.length; - fButtonsSelected= new boolean[nButtons]; - fButtonsEnabled= new boolean[nButtons]; - for (int i= 0; i < nButtons; i++) { - fButtonsSelected[i]= false; - fButtonsEnabled[i]= true; + + Assert.isTrue(buttonsStyle == SWT.RADIO || buttonsStyle == SWT.CHECK + || buttonsStyle == SWT.TOGGLE); + fButtonNames = buttonNames; + + int nButtons = buttonNames.length; + fButtonsSelected = new boolean[nButtons]; + fButtonsEnabled = new boolean[nButtons]; + for (int i = 0; i < nButtons; i++) { + fButtonsSelected[i] = false; + fButtonsEnabled[i] = true; } if (fButtonsStyle == SWT.RADIO) { - fButtonsSelected[0]= true; + fButtonsSelected[0] = true; } - - fGroupBorderStyle= borderStyle; - fGroupNumberOfColumns= (nColumns <= 0) ? nButtons : nColumns; - - fButtonsStyle= buttonsStyle; - + + fGroupBorderStyle = borderStyle; + fGroupNumberOfColumns = (nColumns <= 0) ? nButtons : nColumns; + + fButtonsStyle = buttonsStyle; + } - + // ------- layout helpers - + /* * @see DialogField#doFillIntoGrid */ public Control[] doFillIntoGrid(Composite parent, int nColumns) { assertEnoughColumns(nColumns); - + if (fGroupBorderStyle == SWT.NONE) { - Label label= getLabelControl(parent); + Label label = getLabelControl(parent); label.setLayoutData(gridDataForLabel(1)); - - Composite buttonsgroup= getSelectionButtonsGroup(parent); - GridData gd= new GridData(); - gd.horizontalSpan= nColumns - 1; + + Composite buttonsgroup = getSelectionButtonsGroup(parent); + GridData gd = new GridData(); + gd.horizontalSpan = nColumns - 1; buttonsgroup.setLayoutData(gd); - + return new Control[] { label, buttonsgroup }; } else { - Composite buttonsgroup= getSelectionButtonsGroup(parent); - GridData gd= new GridData(); - gd.horizontalSpan= nColumns; + Composite buttonsgroup = getSelectionButtonsGroup(parent); + GridData gd = new GridData(); + gd.horizontalSpan = nColumns; buttonsgroup.setLayoutData(gd); - + return new Control[] { buttonsgroup }; } - } + } /* * @see DialogField#doFillIntoGrid - */ + */ public int getNumberOfControls() { return (fGroupBorderStyle == SWT.NONE) ? 2 : 1; } - + // ------- ui creation - - private Button createSelectionButton(int index, Composite group, SelectionListener listener) { - Button button= new Button(group, fButtonsStyle | SWT.LEFT); - button.setFont(group.getFont()); + + private Button createSelectionButton(int index, Composite group, + SelectionListener listener) { + Button button = new Button(group, fButtonsStyle | SWT.LEFT); + button.setFont(group.getFont()); button.setText(fButtonNames[index]); button.setEnabled(isEnabled() && fButtonsEnabled[index]); button.setSelection(fButtonsSelected[index]); @@ -124,48 +132,53 @@ public class SelectionButtonDialogFieldGroup extends DialogField { } /** - * Returns the group widget. When called the first time, the widget will be created. - * @param The parent composite when called the first time, or null - * after. + * Returns the group widget. When called the first time, the widget will be + * created. + * + * @param The + * parent composite when called the first time, or + * null after. */ public Composite getSelectionButtonsGroup(Composite parent) { if (fButtonComposite == null) { assertCompositeNotNull(parent); - - GridLayout layout= new GridLayout(); - layout.makeColumnsEqualWidth= true; - layout.numColumns= fGroupNumberOfColumns; - + + GridLayout layout = new GridLayout(); + layout.makeColumnsEqualWidth = true; + layout.numColumns = fGroupNumberOfColumns; + if (fGroupBorderStyle != SWT.NONE) { - Group group= new Group(parent, fGroupBorderStyle); + Group group = new Group(parent, fGroupBorderStyle); if (fLabelText != null && fLabelText.length() > 0) { group.setText(fLabelText); } - fButtonComposite= group; + fButtonComposite = group; } else { - fButtonComposite= new Composite(parent, SWT.NULL); - layout.marginHeight= 0; - layout.marginWidth= 0; + fButtonComposite = new Composite(parent, SWT.NULL); + layout.marginHeight = 0; + layout.marginWidth = 0; } fButtonComposite.setLayout(layout); - - SelectionListener listener= new SelectionListener() { + + SelectionListener listener = new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { doWidgetSelected(e); } + public void widgetSelected(SelectionEvent e) { doWidgetSelected(e); } - }; - int nButtons= fButtonNames.length; - fButtons= new Button[nButtons]; - for (int i= 0; i < nButtons; i++) { - fButtons[i]= createSelectionButton(i, fButtonComposite, listener); + }; + int nButtons = fButtonNames.length; + fButtons = new Button[nButtons]; + for (int i = 0; i < nButtons; i++) { + fButtons[i] = createSelectionButton(i, fButtonComposite, + listener); } - int nRows= nButtons / fGroupNumberOfColumns; - int nFillElements= nRows * fGroupNumberOfColumns - nButtons; - for (int i= 0; i < nFillElements; i++) { + int nRows = nButtons / fGroupNumberOfColumns; + int nFillElements = nRows * fGroupNumberOfColumns - nButtons; + for (int i = 0; i < nFillElements; i++) { createEmptySpace(fButtonComposite); } } @@ -173,31 +186,34 @@ public class SelectionButtonDialogFieldGroup extends DialogField { } /** - * Returns a button from the group or null if not yet created. - */ + * Returns a button from the group or null if not yet + * created. + */ public Button getSelectionButton(int index) { if (index >= 0 && index < fButtons.length) { return fButtons[index]; } return null; } - + private void doWidgetSelected(SelectionEvent e) { - Button button= (Button)e.widget; - for (int i= 0; i < fButtons.length; i++) { + Button button = (Button) e.widget; + for (int i = 0; i < fButtons.length; i++) { if (fButtons[i] == button) { - fButtonsSelected[i]= button.getSelection(); + fButtonsSelected[i] = button.getSelection(); dialogFieldChanged(); return; } } - } - - // ------ model access + } + + // ------ model access /** * Returns the selection state of a button contained in the group. - * @param The index of the button + * + * @param The + * index of the button */ public boolean isSelected(int index) { if (index >= 0 && index < fButtonsSelected.length) { @@ -205,16 +221,16 @@ public class SelectionButtonDialogFieldGroup extends DialogField { } return false; } - + /** * Sets the selection state of a button contained in the group. */ public void setSelection(int index, boolean selected) { if (index >= 0 && index < fButtonsSelected.length) { if (fButtonsSelected[index] != selected) { - fButtonsSelected[index]= selected; + fButtonsSelected[index] = selected; if (fButtons != null) { - Button button= fButtons[index]; + Button button = fButtons[index]; if (isOkToUse(button)) { button.setSelection(selected); } @@ -224,32 +240,32 @@ public class SelectionButtonDialogFieldGroup extends DialogField { } // ------ enable / disable management - + protected void updateEnableState() { super.updateEnableState(); if (fButtons != null) { - boolean enabled= isEnabled(); - for (int i= 0; i < fButtons.length; i++) { - Button button= fButtons[i]; + boolean enabled = isEnabled(); + for (int i = 0; i < fButtons.length; i++) { + Button button = fButtons[i]; if (isOkToUse(button)) { button.setEnabled(enabled && fButtonsEnabled[i]); } } } } - + /** * Sets the enable state of a button contained in the group. - */ + */ public void enableSelectionButton(int index, boolean enable) { if (index >= 0 && index < fButtonsEnabled.length) { - fButtonsEnabled[index]= enable; + fButtonsEnabled[index] = enable; if (fButtons != null) { - Button button= fButtons[index]; + Button button = fButtons[index]; if (isOkToUse(button)) { button.setEnabled(isEnabled() && enable); } } } - } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/Separator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/Separator.java index 08f587d..ea736b9 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/Separator.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/Separator.java @@ -20,73 +20,79 @@ import org.eclipse.swt.widgets.Label; * Dialog field describing a separator. */ public class Separator extends DialogField { - + private Label fSeparator; + private int fStyle; - + public Separator() { this(SWT.NONE); - } - + } + /** - * @param style of the separator. See Label for possible - * styles. + * @param style + * of the separator. See Label for possible + * styles. */ public Separator(int style) { super(); - fStyle= style; + fStyle = style; } - + // ------- layout helpers /** * Creates the separator and fills it in a MGridLayout. - * @param height The heigth of the separator - */ + * + * @param height + * The heigth of the separator + */ public Control[] doFillIntoGrid(Composite parent, int nColumns, int height) { assertEnoughColumns(nColumns); - - Control separator= getSeparator(parent); + + Control separator = getSeparator(parent); separator.setLayoutData(gridDataForSeperator(nColumns, height)); - + return new Control[] { separator }; } /* * @see DialogField#doFillIntoGrid - */ + */ public Control[] doFillIntoGrid(Composite parent, int nColumns) { return doFillIntoGrid(parent, nColumns, 4); } /* * @see DialogField#getNumberOfControls - */ + */ public int getNumberOfControls() { - return 1; + return 1; } - + protected static GridData gridDataForSeperator(int span, int height) { - GridData gd= new GridData(); - gd.horizontalAlignment= GridData.FILL; - gd.verticalAlignment= GridData.BEGINNING; - gd.heightHint= height; - gd.horizontalSpan= span; + GridData gd = new GridData(); + gd.horizontalAlignment = GridData.FILL; + gd.verticalAlignment = GridData.BEGINNING; + gd.heightHint = height; + gd.horizontalSpan = span; return gd; } - - // ------- ui creation + + // ------- ui creation /** * Creates or returns the created separator. - * @param parent The parent composite or null if the widget has - * already been created. - */ + * + * @param parent + * The parent composite or null if the widget has + * already been created. + */ public Control getSeparator(Composite parent) { if (fSeparator == null) { assertCompositeNotNull(parent); - fSeparator= new Label(parent, fStyle); - } + fSeparator = new Label(parent, fStyle); + } return fSeparator; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/StringButtonDialogField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/StringButtonDialogField.java index fb13bc4..aa06105 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/StringButtonDialogField.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/StringButtonDialogField.java @@ -22,105 +22,109 @@ import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; - /** * Dialog field containing a label, text control and a button control. */ public class StringButtonDialogField extends StringDialogField { - + private Button fBrowseButton; + private String fBrowseButtonLabel; + private IStringButtonAdapter fStringButtonAdapter; - + private boolean fButtonEnabled; - + public StringButtonDialogField(IStringButtonAdapter adapter) { super(); - fStringButtonAdapter= adapter; - fBrowseButtonLabel= "!Browse...!"; //$NON-NLS-1$ - fButtonEnabled= true; + fStringButtonAdapter = adapter; + fBrowseButtonLabel = "!Browse...!"; //$NON-NLS-1$ + fButtonEnabled = true; } /** * Sets the label of the button. */ public void setButtonLabel(String label) { - fBrowseButtonLabel= label; + fBrowseButtonLabel = label; } - + // ------ adapter communication /** * Programmatical pressing of the button - */ + */ public void changeControlPressed() { fStringButtonAdapter.changeControlPressed(this); } - + // ------- layout helpers /* * @see DialogField#doFillIntoGrid - */ + */ public Control[] doFillIntoGrid(Composite parent, int nColumns) { assertEnoughColumns(nColumns); - - Label label= getLabelControl(parent); + + Label label = getLabelControl(parent); label.setLayoutData(gridDataForLabel(1)); - Text text= getTextControl(parent); + Text text = getTextControl(parent); text.setLayoutData(gridDataForText(nColumns - 2)); - Button button= getChangeControl(parent); + Button button = getChangeControl(parent); button.setLayoutData(gridDataForButton(button, 1)); - + return new Control[] { label, text, button }; - } + } /* * @see DialogField#getNumberOfControls - */ + */ public int getNumberOfControls() { - return 3; + return 3; } - + protected static GridData gridDataForButton(Button button, int span) { - GridData gd= new GridData(); - gd.horizontalAlignment= GridData.FILL; - gd.grabExcessHorizontalSpace= false; - gd.horizontalSpan= span; + GridData gd = new GridData(); + gd.horizontalAlignment = GridData.FILL; + gd.grabExcessHorizontalSpace = false; + gd.horizontalSpan = span; gd.heightHint = SWTUtil.getButtonHeightHint(button); - gd.widthHint = SWTUtil.getButtonWidthHint(button); + gd.widthHint = SWTUtil.getButtonWidthHint(button); return gd; - } - - // ------- ui creation + } + + // ------- ui creation /** * Creates or returns the created buttom widget. - * @param parent The parent composite or null if the widget has - * already been created. - */ + * + * @param parent + * The parent composite or null if the widget has + * already been created. + */ public Button getChangeControl(Composite parent) { if (fBrowseButton == null) { assertCompositeNotNull(parent); - - fBrowseButton= new Button(parent, SWT.PUSH); + + fBrowseButton = new Button(parent, SWT.PUSH); fBrowseButton.setText(fBrowseButtonLabel); fBrowseButton.setEnabled(isEnabled() && fButtonEnabled); fBrowseButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { changeControlPressed(); } + public void widgetSelected(SelectionEvent e) { changeControlPressed(); } - }); - + }); + } return fBrowseButton; } - + // ------ enable / disable management - + /** * Sets the enable state of the button. */ @@ -128,16 +132,16 @@ public class StringButtonDialogField extends StringDialogField { if (isOkToUse(fBrowseButton)) { fBrowseButton.setEnabled(isEnabled() && enable); } - fButtonEnabled= enable; + fButtonEnabled = enable; } /* * @see DialogField#updateEnableState - */ + */ protected void updateEnableState() { super.updateEnableState(); if (isOkToUse(fBrowseButton)) { fBrowseButton.setEnabled(isEnabled() && fButtonEnabled); } - } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/StringButtonStatusDialogField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/StringButtonStatusDialogField.java index 53a8a5f..87fd7ea 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/StringButtonStatusDialogField.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/StringButtonStatusDialogField.java @@ -22,40 +22,41 @@ import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; /** - * Dialog field containing a label, text control, status label and a button control. - * The status label can be either a image or text label, and can be usd to give - * additional information about the current element chosen. + * Dialog field containing a label, text control, status label and a button + * control. The status label can be either a image or text label, and can be usd + * to give additional information about the current element chosen. */ public class StringButtonStatusDialogField extends StringButtonDialogField { - + private Label fStatusLabelControl; - private Object fStatus; // String or ImageDescriptor - + + private Object fStatus; // String or ImageDescriptor + private String fWidthHintString; - private int fWidthHint; - + + private int fWidthHint; + public StringButtonStatusDialogField(IStringButtonAdapter adapter) { super(adapter); - fStatus= null; - fWidthHintString= null; - fWidthHint= -1; + fStatus = null; + fWidthHintString = null; + fWidthHint = -1; } - + // ------ set status /** * Sets the status string. - */ + */ public void setStatus(String status) { if (isOkToUse(fStatusLabelControl)) { fStatusLabelControl.setText(status); } - fStatus= status; + fStatus = status; } - + /** - * Sets the status image. - * Caller is responsible to dispose image + * Sets the status image. Caller is responsible to dispose image */ public void setStatus(Image image) { if (isOkToUse(fStatusLabelControl)) { @@ -65,104 +66,106 @@ public class StringButtonStatusDialogField extends StringButtonDialogField { fStatusLabelControl.setImage(image); } } - fStatus= image; - } + fStatus = image; + } /** - * Sets the staus string hint of the status label. - * The string is used to calculate the size of the status label. - */ + * Sets the staus string hint of the status label. The string is used to + * calculate the size of the status label. + */ public void setStatusWidthHint(String widthHintString) { - fWidthHintString= widthHintString; - fWidthHint= -1; + fWidthHintString = widthHintString; + fWidthHint = -1; } - + /** * Sets the width hint of the status label. */ public void setStatusWidthHint(int widthHint) { - fWidthHint= widthHint; - fWidthHintString= null; + fWidthHint = widthHint; + fWidthHintString = null; } - - // ------- layout helpers + + // ------- layout helpers /* * @see DialogField#doFillIntoGrid - */ + */ public Control[] doFillIntoGrid(Composite parent, int nColumns) { assertEnoughColumns(nColumns); - - Label label= getLabelControl(parent); + + Label label = getLabelControl(parent); label.setLayoutData(gridDataForLabel(1)); - Text text= getTextControl(parent); + Text text = getTextControl(parent); text.setLayoutData(gridDataForText(nColumns - 3)); - Label status= getStatusLabelControl(parent); + Label status = getStatusLabelControl(parent); status.setLayoutData(gridDataForStatusLabel(parent, 1)); - Button button= getChangeControl(parent); + Button button = getChangeControl(parent); button.setLayoutData(gridDataForButton(button, 1)); - + return new Control[] { label, text, status, button }; } - + /* * @see DialogField#getNumberOfControls */ public int getNumberOfControls() { - return 4; + return 4; } - + protected GridData gridDataForStatusLabel(Control aControl, int span) { - GridData gd= new GridData(); - gd.horizontalAlignment= GridData.BEGINNING; - gd.grabExcessHorizontalSpace= false; - gd.horizontalIndent= 0; + GridData gd = new GridData(); + gd.horizontalAlignment = GridData.BEGINNING; + gd.grabExcessHorizontalSpace = false; + gd.horizontalIndent = 0; if (fWidthHintString != null) { - GC gc= new GC(aControl); + GC gc = new GC(aControl); gc.setFont(JFaceResources.getDialogFont()); - gd.widthHint= gc.textExtent(fWidthHintString).x; + gd.widthHint = gc.textExtent(fWidthHintString).x; gc.dispose(); } else if (fWidthHint != -1) { - gd.widthHint= fWidthHint; + gd.widthHint = fWidthHint; } else { - gd.widthHint= SWT.DEFAULT; - } + gd.widthHint = SWT.DEFAULT; + } return gd; } - - // ------- ui creation + + // ------- ui creation /** * Creates or returns the created status label widget. - * @param parent The parent composite or null when the widget has - * already been created. - */ + * + * @param parent + * The parent composite or null when the widget + * has already been created. + */ public Label getStatusLabelControl(Composite parent) { if (fStatusLabelControl == null) { - assertCompositeNotNull(parent); - fStatusLabelControl= new Label(parent, SWT.LEFT); + assertCompositeNotNull(parent); + fStatusLabelControl = new Label(parent, SWT.LEFT); fStatusLabelControl.setFont(parent.getFont()); fStatusLabelControl.setEnabled(isEnabled()); if (fStatus instanceof Image) { - fStatusLabelControl.setImage((Image)fStatus); + fStatusLabelControl.setImage((Image) fStatus); } else if (fStatus instanceof String) { - fStatusLabelControl.setText((String)fStatus); + fStatusLabelControl.setText((String) fStatus); } else { // must be null } } return fStatusLabelControl; } - + // ------ enable / disable management /* * @see DialogField#updateEnableState - */ + */ protected void updateEnableState() { super.updateEnableState(); if (isOkToUse(fStatusLabelControl)) { fStatusLabelControl.setEnabled(isEnabled()); } - } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/StringDialogField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/StringDialogField.java index 6176a28..e43b145 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/StringDialogField.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/StringDialogField.java @@ -23,49 +23,51 @@ import org.eclipse.swt.widgets.Text; * Dialog field containing a label and a text control. */ public class StringDialogField extends DialogField { - + private String fText; + private Text fTextControl; + private ModifyListener fModifyListener; - + public StringDialogField() { super(); - fText= ""; //$NON-NLS-1$ + fText = ""; //$NON-NLS-1$ } - + // ------- layout helpers - + /* * @see DialogField#doFillIntoGrid */ public Control[] doFillIntoGrid(Composite parent, int nColumns) { assertEnoughColumns(nColumns); - - Label label= getLabelControl(parent); + + Label label = getLabelControl(parent); label.setLayoutData(gridDataForLabel(1)); - Text text= getTextControl(parent); + Text text = getTextControl(parent); text.setLayoutData(gridDataForText(nColumns - 1)); - + return new Control[] { label, text }; - } + } /* * @see DialogField#getNumberOfControls */ public int getNumberOfControls() { - return 2; + return 2; } - + protected static GridData gridDataForText(int span) { - GridData gd= new GridData(); - gd.horizontalAlignment= GridData.FILL; - gd.grabExcessHorizontalSpace= false; - gd.horizontalSpan= span; + GridData gd = new GridData(); + gd.horizontalAlignment = GridData.FILL; + gd.grabExcessHorizontalSpace = false; + gd.horizontalSpan = span; return gd; - } - + } + // ------- focus methods - + /* * @see DialogField#setFocus */ @@ -76,84 +78,86 @@ public class StringDialogField extends DialogField { } return true; } - - // ------- ui creation + + // ------- ui creation /** * Creates or returns the created text control. - * @param parent The parent composite or null when the widget has - * already been created. - */ + * + * @param parent + * The parent composite or null when the widget + * has already been created. + */ public Text getTextControl(Composite parent) { if (fTextControl == null) { assertCompositeNotNull(parent); - fModifyListener= new ModifyListener() { + fModifyListener = new ModifyListener() { public void modifyText(ModifyEvent e) { doModifyText(e); } }; - - fTextControl= new Text(parent, SWT.SINGLE | SWT.BORDER); + + fTextControl = new Text(parent, SWT.SINGLE | SWT.BORDER); // moved up due to 1GEUNW2 fTextControl.setText(fText); fTextControl.setFont(parent.getFont()); fTextControl.addModifyListener(fModifyListener); - + fTextControl.setEnabled(isEnabled()); } return fTextControl; } - + private void doModifyText(ModifyEvent e) { if (isOkToUse(fTextControl)) { - fText= fTextControl.getText(); + fText = fTextControl.getText(); } dialogFieldChanged(); - } - + } + // ------ enable / disable management - + /* * @see DialogField#updateEnableState - */ + */ protected void updateEnableState() { - super.updateEnableState(); + super.updateEnableState(); if (isOkToUse(fTextControl)) { fTextControl.setEnabled(isEnabled()); - } - } - - // ------ text access - + } + } + + // ------ text access + /** * Gets the text. Can not be null - */ + */ public String getText() { return fText; } - + /** * Sets the text. Triggers a dialog-changed event. */ public void setText(String text) { - fText= text; + fText = text; if (isOkToUse(fTextControl)) { fTextControl.setText(text); } else { dialogFieldChanged(); - } + } } /** * Sets the text without triggering a dialog-changed event. */ public void setTextWithoutUpdate(String text) { - fText= text; + fText = text; if (isOkToUse(fTextControl)) { fTextControl.removeModifyListener(fModifyListener); fTextControl.setText(text); fTextControl.addModifyListener(fModifyListener); } } - + } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/TreeListDialogField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/TreeListDialogField.java index 4cf3892..8bed2ad 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/TreeListDialogField.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/TreeListDialogField.java @@ -44,125 +44,138 @@ import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Tree; - /** - * A list with a button bar. - * Typical buttons are 'Add', 'Remove', 'Up' and 'Down'. - * List model is independend of widget creation. - * DialogFields controls are: Label, List and Composite containing buttons. + * A list with a button bar. Typical buttons are 'Add', 'Remove', 'Up' and + * 'Down'. List model is independend of widget creation. DialogFields controls + * are: Label, List and Composite containing buttons. */ public class TreeListDialogField extends DialogField { protected TreeViewer fTree; + protected ILabelProvider fLabelProvider; + protected TreeViewerAdapter fTreeViewerAdapter; + protected List fElements; + protected ViewerSorter fViewerSorter; protected String[] fButtonLabels; + private Button[] fButtonControls; private boolean[] fButtonsEnabled; private int fRemoveButtonIndex; + private int fUpButtonIndex; + private int fDownButtonIndex; private Label fLastSeparator; private Tree fTreeControl; + private Composite fButtonsControl; + private ISelection fSelectionWhenEnabled; private ITreeListAdapter fTreeAdapter; private Object fParentElement; + private int fTreeExpandLevel; /** - * @param adapter Can be null. + * @param adapter + * Can be null. */ - public TreeListDialogField(ITreeListAdapter adapter, String[] buttonLabels, ILabelProvider lprovider) { + public TreeListDialogField(ITreeListAdapter adapter, String[] buttonLabels, + ILabelProvider lprovider) { super(); - fTreeAdapter= adapter; + fTreeAdapter = adapter; - fLabelProvider= lprovider; - fTreeViewerAdapter= new TreeViewerAdapter(); - fParentElement= this; + fLabelProvider = lprovider; + fTreeViewerAdapter = new TreeViewerAdapter(); + fParentElement = this; - fElements= new ArrayList(10); + fElements = new ArrayList(10); - fButtonLabels= buttonLabels; + fButtonLabels = buttonLabels; if (fButtonLabels != null) { - int nButtons= fButtonLabels.length; - fButtonsEnabled= new boolean[nButtons]; - for (int i= 0; i < nButtons; i++) { - fButtonsEnabled[i]= true; + int nButtons = fButtonLabels.length; + fButtonsEnabled = new boolean[nButtons]; + for (int i = 0; i < nButtons; i++) { + fButtonsEnabled[i] = true; } } - fTree= null; - fTreeControl= null; - fButtonsControl= null; + fTree = null; + fTreeControl = null; + fButtonsControl = null; + + fRemoveButtonIndex = -1; + fUpButtonIndex = -1; + fDownButtonIndex = -1; - fRemoveButtonIndex= -1; - fUpButtonIndex= -1; - fDownButtonIndex= -1; - - fTreeExpandLevel= 0; + fTreeExpandLevel = 0; } /** - * Sets the index of the 'remove' button in the button label array passed in - * the constructor. The behaviour of the button marked as the 'remove' button - * will then behandled internally. (enable state, button invocation - * behaviour) - */ + * Sets the index of the 'remove' button in the button label array passed in + * the constructor. The behaviour of the button marked as the 'remove' + * button will then behandled internally. (enable state, button invocation + * behaviour) + */ public void setRemoveButtonIndex(int removeButtonIndex) { Assert.isTrue(removeButtonIndex < fButtonLabels.length); - fRemoveButtonIndex= removeButtonIndex; + fRemoveButtonIndex = removeButtonIndex; } /** - * Sets the index of the 'up' button in the button label array passed in the - * constructor. The behaviour of the button marked as the 'up' button will - * then behandled internally. - * (enable state, button invocation behaviour) - */ + * Sets the index of the 'up' button in the button label array passed in the + * constructor. The behaviour of the button marked as the 'up' button will + * then behandled internally. (enable state, button invocation behaviour) + */ public void setUpButtonIndex(int upButtonIndex) { Assert.isTrue(upButtonIndex < fButtonLabels.length); - fUpButtonIndex= upButtonIndex; + fUpButtonIndex = upButtonIndex; } /** - * Sets the index of the 'down' button in the button label array passed in - * the constructor. The behaviour of the button marked as the 'down' button - * will then be handled internally. (enable state, button invocation - * behaviour) - */ + * Sets the index of the 'down' button in the button label array passed in + * the constructor. The behaviour of the button marked as the 'down' button + * will then be handled internally. (enable state, button invocation + * behaviour) + */ public void setDownButtonIndex(int downButtonIndex) { Assert.isTrue(downButtonIndex < fButtonLabels.length); - fDownButtonIndex= downButtonIndex; + fDownButtonIndex = downButtonIndex; } /** - * Sets the viewerSorter. - * @param viewerSorter The viewerSorter to set - */ + * Sets the viewerSorter. + * + * @param viewerSorter + * The viewerSorter to set + */ public void setViewerSorter(ViewerSorter viewerSorter) { - fViewerSorter= viewerSorter; + fViewerSorter = viewerSorter; } - + /** - * Sets the viewerSorter. - * @param viewerSorter The viewerSorter to set - */ + * Sets the viewerSorter. + * + * @param viewerSorter + * The viewerSorter to set + */ public void setTreeExpansionLevel(int level) { - fTreeExpandLevel= level; + fTreeExpandLevel = level; if (fTree != null) { fTree.expandToLevel(level); } - } + } // ------ adapter communication @@ -173,9 +186,10 @@ public class TreeListDialogField extends DialogField { } /** - * Checks if the button pressed is handled internally - * @return Returns true if button has been handled. - */ + * Checks if the button pressed is handled internally + * + * @return Returns true if button has been handled. + */ protected boolean managedButtonPressed(int index) { if (index == fRemoveButtonIndex) { remove(); @@ -192,73 +206,76 @@ public class TreeListDialogField extends DialogField { // ------ layout helpers /* - * @see DialogField#doFillIntoGrid - */ + * @see DialogField#doFillIntoGrid + */ public Control[] doFillIntoGrid(Composite parent, int nColumns) { - PixelConverter converter= new PixelConverter(parent); + PixelConverter converter = new PixelConverter(parent); assertEnoughColumns(nColumns); - Label label= getLabelControl(parent); - GridData gd= gridDataForLabel(1); - gd.verticalAlignment= GridData.BEGINNING; + Label label = getLabelControl(parent); + GridData gd = gridDataForLabel(1); + gd.verticalAlignment = GridData.BEGINNING; label.setLayoutData(gd); - Control list= getTreeControl(parent); - gd= new GridData(); - gd.horizontalAlignment= GridData.FILL; - gd.grabExcessHorizontalSpace= false; - gd.verticalAlignment= GridData.FILL; - gd.grabExcessVerticalSpace= true; - gd.horizontalSpan= nColumns - 2; - gd.widthHint= converter.convertWidthInCharsToPixels(50); - gd.heightHint= converter.convertHeightInCharsToPixels(6); + Control list = getTreeControl(parent); + gd = new GridData(); + gd.horizontalAlignment = GridData.FILL; + gd.grabExcessHorizontalSpace = false; + gd.verticalAlignment = GridData.FILL; + gd.grabExcessVerticalSpace = true; + gd.horizontalSpan = nColumns - 2; + gd.widthHint = converter.convertWidthInCharsToPixels(50); + gd.heightHint = converter.convertHeightInCharsToPixels(6); list.setLayoutData(gd); - Composite buttons= getButtonBox(parent); - gd= new GridData(); - gd.horizontalAlignment= GridData.FILL; - gd.grabExcessHorizontalSpace= false; - gd.verticalAlignment= GridData.FILL; - gd.grabExcessVerticalSpace= true; - gd.horizontalSpan= 1; + Composite buttons = getButtonBox(parent); + gd = new GridData(); + gd.horizontalAlignment = GridData.FILL; + gd.grabExcessHorizontalSpace = false; + gd.verticalAlignment = GridData.FILL; + gd.grabExcessVerticalSpace = true; + gd.horizontalSpan = 1; buttons.setLayoutData(gd); return new Control[] { label, list, buttons }; } /* - * @see DialogField#getNumberOfControls - */ + * @see DialogField#getNumberOfControls + */ public int getNumberOfControls() { return 3; } /** - * Sets the minimal width of the buttons. Must be called after widget creation. - */ + * Sets the minimal width of the buttons. Must be called after widget + * creation. + */ public void setButtonsMinWidth(int minWidth) { if (fLastSeparator != null) { - ((GridData) fLastSeparator.getLayoutData()).widthHint= minWidth; + ((GridData) fLastSeparator.getLayoutData()).widthHint = minWidth; } } // ------ ui creation /** - * Returns the tree control. When called the first time, the control will be - * created. - * @param The parent composite when called the first time, or null - * after. - */ + * Returns the tree control. When called the first time, the control will be + * created. + * + * @param The + * parent composite when called the first time, or + * null after. + */ public Control getTreeControl(Composite parent) { if (fTreeControl == null) { assertCompositeNotNull(parent); - fTree= createTreeViewer(parent); + fTree = createTreeViewer(parent); - fTreeControl= (Tree) fTree.getControl(); + fTreeControl = (Tree) fTree.getControl(); fTreeControl.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { handleKeyPressed(e); @@ -286,94 +303,100 @@ public class TreeListDialogField extends DialogField { } /** - * Returns the internally used table viewer. - */ + * Returns the internally used table viewer. + */ public TreeViewer getTreeViewer() { return fTree; } /* - * Subclasses may override to specify a different style. - */ + * Subclasses may override to specify a different style. + */ protected int getTreeStyle() { - int style= SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL; + int style = SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL; return style; } protected TreeViewer createTreeViewer(Composite parent) { - Tree tree= new Tree(parent, getTreeStyle()); + Tree tree = new Tree(parent, getTreeStyle()); return new TreeViewer(tree); } - protected Button createButton(Composite parent, String label, SelectionListener listener) { - Button button= new Button(parent, SWT.PUSH); + protected Button createButton(Composite parent, String label, + SelectionListener listener) { + Button button = new Button(parent, SWT.PUSH); button.setText(label); button.addSelectionListener(listener); - GridData gd= new GridData(); - gd.horizontalAlignment= GridData.FILL; - gd.grabExcessHorizontalSpace= true; - gd.verticalAlignment= GridData.BEGINNING; - gd.heightHint= SWTUtil.getButtonHeightHint(button); - gd.widthHint= SWTUtil.getButtonWidthHint(button); + GridData gd = new GridData(); + gd.horizontalAlignment = GridData.FILL; + gd.grabExcessHorizontalSpace = true; + gd.verticalAlignment = GridData.BEGINNING; + gd.heightHint = SWTUtil.getButtonHeightHint(button); + gd.widthHint = SWTUtil.getButtonWidthHint(button); button.setLayoutData(gd); return button; } private Label createSeparator(Composite parent) { - Label separator= new Label(parent, SWT.NONE); + Label separator = new Label(parent, SWT.NONE); separator.setVisible(false); - GridData gd= new GridData(); - gd.horizontalAlignment= GridData.FILL; - gd.verticalAlignment= GridData.BEGINNING; - gd.heightHint= 4; + GridData gd = new GridData(); + gd.horizontalAlignment = GridData.FILL; + gd.verticalAlignment = GridData.BEGINNING; + gd.heightHint = 4; separator.setLayoutData(gd); return separator; } /** - * Returns the composite containing the buttons. When called the first time, the control - * will be created. - * @param The parent composite when called the first time, or null - * after. - */ + * Returns the composite containing the buttons. When called the first time, + * the control will be created. + * + * @param The + * parent composite when called the first time, or + * null after. + */ public Composite getButtonBox(Composite parent) { if (fButtonsControl == null) { assertCompositeNotNull(parent); - SelectionListener listener= new SelectionListener() { + SelectionListener listener = new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { doButtonSelected(e); } + public void widgetSelected(SelectionEvent e) { doButtonSelected(e); } }; - Composite contents= new Composite(parent, SWT.NULL); - GridLayout layout= new GridLayout(); - layout.marginWidth= 0; - layout.marginHeight= 0; + Composite contents = new Composite(parent, SWT.NULL); + GridLayout layout = new GridLayout(); + layout.marginWidth = 0; + layout.marginHeight = 0; contents.setLayout(layout); if (fButtonLabels != null) { - fButtonControls= new Button[fButtonLabels.length]; - for (int i= 0; i < fButtonLabels.length; i++) { - String currLabel= fButtonLabels[i]; + fButtonControls = new Button[fButtonLabels.length]; + for (int i = 0; i < fButtonLabels.length; i++) { + String currLabel = fButtonLabels[i]; if (currLabel != null) { - fButtonControls[i]= createButton(contents, currLabel, listener); - fButtonControls[i].setEnabled(isEnabled() && fButtonsEnabled[i]); + fButtonControls[i] = createButton(contents, currLabel, + listener); + fButtonControls[i].setEnabled(isEnabled() + && fButtonsEnabled[i]); } else { - fButtonControls[i]= null; + fButtonControls[i] = null; createSeparator(contents); } } } - fLastSeparator= createSeparator(contents); + fLastSeparator = createSeparator(contents); updateButtonState(); - fButtonsControl= contents; + fButtonsControl = contents; } return fButtonsControl; @@ -381,7 +404,7 @@ public class TreeListDialogField extends DialogField { private void doButtonSelected(SelectionEvent e) { if (fButtonControls != null) { - for (int i= 0; i < fButtonControls.length; i++) { + for (int i = 0; i < fButtonControls.length; i++) { if (e.widget == fButtonControls[i]) { buttonPressed(i); return; @@ -391,12 +414,13 @@ public class TreeListDialogField extends DialogField { } /** - * Handles key events in the table viewer. Specifically - * when the delete key is pressed. - */ + * Handles key events in the table viewer. Specifically when the delete key + * is pressed. + */ protected void handleKeyPressed(KeyEvent event) { if (event.character == SWT.DEL && event.stateMask == 0) { - if (fRemoveButtonIndex != -1 && isButtonEnabled(fTree.getSelection(), fRemoveButtonIndex)) { + if (fRemoveButtonIndex != -1 + && isButtonEnabled(fTree.getSelection(), fRemoveButtonIndex)) { managedButtonPressed(fRemoveButtonIndex); return; } @@ -407,42 +431,40 @@ public class TreeListDialogField extends DialogField { // ------ enable / disable management /* - * @see DialogField#dialogFieldChanged - */ + * @see DialogField#dialogFieldChanged + */ public void dialogFieldChanged() { super.dialogFieldChanged(); updateButtonState(); } /* - * Updates the enable state of the all buttons - */ + * Updates the enable state of the all buttons + */ protected void updateButtonState() { if (fButtonControls != null) { - ISelection sel= fTree.getSelection(); - for (int i= 0; i < fButtonControls.length; i++) { - Button button= fButtonControls[i]; + ISelection sel = fTree.getSelection(); + for (int i = 0; i < fButtonControls.length; i++) { + Button button = fButtonControls[i]; if (isOkToUse(button)) { button.setEnabled(isButtonEnabled(sel, i)); } } } } - - + protected boolean containsAttributes(List selected) { - for (int i= 0; i < selected.size(); i++) { + for (int i = 0; i < selected.size(); i++) { if (!fElements.contains(selected.get(i))) { return true; } } return false; } - protected boolean getManagedButtonState(ISelection sel, int index) { - List selected= getSelectedElements(); - boolean hasAttributes= containsAttributes(selected); + List selected = getSelectedElements(); + boolean hasAttributes = containsAttributes(selected); if (index == fRemoveButtonIndex) { return !selected.isEmpty() && !hasAttributes; } else if (index == fUpButtonIndex) { @@ -454,19 +476,19 @@ public class TreeListDialogField extends DialogField { } /* - * @see DialogField#updateEnableState - */ + * @see DialogField#updateEnableState + */ protected void updateEnableState() { super.updateEnableState(); - boolean enabled= isEnabled(); + boolean enabled = isEnabled(); if (isOkToUse(fTreeControl)) { if (!enabled) { - fSelectionWhenEnabled= fTree.getSelection(); + fSelectionWhenEnabled = fTree.getSelection(); selectElements(null); } else { selectElements(fSelectionWhenEnabled); - fSelectionWhenEnabled= null; + fSelectionWhenEnabled = null; } fTreeControl.setEnabled(enabled); } @@ -474,27 +496,27 @@ public class TreeListDialogField extends DialogField { } /** - * Sets a button enabled or disabled. - */ + * Sets a button enabled or disabled. + */ public void enableButton(int index, boolean enable) { if (fButtonsEnabled != null && index < fButtonsEnabled.length) { - fButtonsEnabled[index]= enable; + fButtonsEnabled[index] = enable; updateButtonState(); } } private boolean isButtonEnabled(ISelection sel, int index) { - boolean extraState= getManagedButtonState(sel, index); + boolean extraState = getManagedButtonState(sel, index); return isEnabled() && extraState && fButtonsEnabled[index]; } // ------ model access /** - * Sets the elements shown in the list. - */ + * Sets the elements shown in the list. + */ public void setElements(List elements) { - fElements= new ArrayList(elements); + fElements = new ArrayList(elements); refresh(); if (fTree != null) { fTree.expandToLevel(fTreeExpandLevel); @@ -503,40 +525,41 @@ public class TreeListDialogField extends DialogField { } /** - * Gets the elements shown in the list. - * The list returned is a copy, so it can be modified by the user. - */ + * Gets the elements shown in the list. The list returned is a copy, so it + * can be modified by the user. + */ public List getElements() { return new ArrayList(fElements); } /** - * Gets the element shown at the given index. - */ + * Gets the element shown at the given index. + */ public Object getElement(int index) { return fElements.get(index); } - + /** - * Gets the index of an element in the list or -1 if element is not in list. - */ + * Gets the index of an element in the list or -1 if element is not in list. + */ public int getIndexOfElement(Object elem) { return fElements.indexOf(elem); - } + } /** - * Replace an element. - */ - public void replaceElement(Object oldElement, Object newElement) throws IllegalArgumentException { - int idx= fElements.indexOf(oldElement); + * Replace an element. + */ + public void replaceElement(Object oldElement, Object newElement) + throws IllegalArgumentException { + int idx = fElements.indexOf(oldElement); if (idx != -1) { fElements.set(idx, newElement); if (fTree != null) { - List selected= getSelectedElements(); + List selected = getSelectedElements(); if (selected.remove(oldElement)) { selected.add(newElement); } - boolean isExpanded= fTree.getExpandedState(oldElement); + boolean isExpanded = fTree.getExpandedState(oldElement); fTree.remove(oldElement); fTree.add(fParentElement, newElement); if (isExpanded) { @@ -551,8 +574,8 @@ public class TreeListDialogField extends DialogField { } /** - * Adds an element at the end of the tree list. - */ + * Adds an element at the end of the tree list. + */ public void addElement(Object element) { if (fElements.contains(element)) { return; @@ -566,17 +589,17 @@ public class TreeListDialogField extends DialogField { } /** - * Adds elements at the end of the tree list. - */ + * Adds elements at the end of the tree list. + */ public void addElements(List elements) { - int nElements= elements.size(); + int nElements = elements.size(); if (nElements > 0) { // filter duplicated - ArrayList elementsToAdd= new ArrayList(nElements); + ArrayList elementsToAdd = new ArrayList(nElements); - for (int i= 0; i < nElements; i++) { - Object elem= elements.get(i); + for (int i = 0; i < nElements; i++) { + Object elem = elements.get(i); if (!fElements.contains(elem)) { elementsToAdd.add(elem); } @@ -584,7 +607,7 @@ public class TreeListDialogField extends DialogField { fElements.addAll(elementsToAdd); if (fTree != null) { fTree.add(fParentElement, elementsToAdd.toArray()); - for (int i= 0; i < elementsToAdd.size(); i++) { + for (int i = 0; i < elementsToAdd.size(); i++) { fTree.expandToLevel(elementsToAdd.get(i), fTreeExpandLevel); } } @@ -593,8 +616,8 @@ public class TreeListDialogField extends DialogField { } /** - * Adds an element at a position. - */ + * Adds an element at a position. + */ public void insertElementAt(Object element, int index) { if (fElements.contains(element)) { return; @@ -611,8 +634,8 @@ public class TreeListDialogField extends DialogField { } /** - * Adds an element at a position. - */ + * Adds an element at a position. + */ public void removeAllElements() { if (fElements.size() > 0) { fElements.clear(); @@ -622,8 +645,8 @@ public class TreeListDialogField extends DialogField { } /** - * Removes an element from the list. - */ + * Removes an element from the list. + */ public void removeElement(Object element) throws IllegalArgumentException { if (fElements.remove(element)) { if (fTree != null) { @@ -636,8 +659,8 @@ public class TreeListDialogField extends DialogField { } /** - * Removes elements from the list. - */ + * Removes elements from the list. + */ public void removeElements(List elements) { if (elements.size() > 0) { fElements.removeAll(elements); @@ -649,30 +672,30 @@ public class TreeListDialogField extends DialogField { } /** - * Gets the number of elements - */ + * Gets the number of elements + */ public int getSize() { return fElements.size(); } public void selectElements(ISelection selection) { - fSelectionWhenEnabled= selection; + fSelectionWhenEnabled = selection; if (fTree != null) { fTree.setSelection(selection, true); } } public void selectFirstElement() { - Object element= null; + Object element = null; if (fViewerSorter != null) { - Object[] arr= fElements.toArray(); + Object[] arr = fElements.toArray(); fViewerSorter.sort(fTree, arr); if (arr.length > 0) { - element= arr[0]; + element = arr[0]; } } else { if (fElements.size() > 0) { - element= fElements.get(0); + element = fElements.get(0); } } if (element != null) { @@ -682,7 +705,7 @@ public class TreeListDialogField extends DialogField { public void postSetSelection(final ISelection selection) { if (isOkToUse(fTreeControl)) { - Display d= fTreeControl.getDisplay(); + Display d = fTreeControl.getDisplay(); d.asyncExec(new Runnable() { public void run() { if (isOkToUse(fTreeControl)) { @@ -694,38 +717,38 @@ public class TreeListDialogField extends DialogField { } /** - * Refreshes the tree. - */ + * Refreshes the tree. + */ public void refresh() { if (fTree != null) { fTree.refresh(); } } - + /** - * Refreshes the tree. - */ + * Refreshes the tree. + */ public void refresh(Object element) { if (fTree != null) { fTree.refresh(element); } - } + } // ------- list maintenance private List moveUp(List elements, List move) { - int nElements= elements.size(); - List res= new ArrayList(nElements); - Object floating= null; - for (int i= 0; i < nElements; i++) { - Object curr= elements.get(i); + int nElements = elements.size(); + List res = new ArrayList(nElements); + Object floating = null; + for (int i = 0; i < nElements; i++) { + Object curr = elements.get(i); if (move.contains(curr)) { res.add(curr); } else { if (floating != null) { res.add(floating); } - floating= curr; + floating = curr; } } if (floating != null) { @@ -749,8 +772,8 @@ public class TreeListDialogField extends DialogField { } private List reverse(List p) { - List reverse= new ArrayList(p.size()); - for (int i= p.size() - 1; i >= 0; i--) { + List reverse = new ArrayList(p.size()); + for (int i = p.size() - 1; i >= 0; i--) { reverse.add(p.get(i)); } return reverse; @@ -770,9 +793,9 @@ public class TreeListDialogField extends DialogField { private boolean canMoveUp(List selectedElements) { if (isOkToUse(fTreeControl)) { - int nSelected= selectedElements.size(); - int nElements= fElements.size(); - for (int i= 0; i < nElements && nSelected > 0; i++) { + int nSelected = selectedElements.size(); + int nElements = fElements.size(); + for (int i = 0; i < nElements && nSelected > 0; i++) { if (!selectedElements.contains(fElements.get(i))) { return true; } @@ -784,26 +807,26 @@ public class TreeListDialogField extends DialogField { private boolean canMoveDown(List selectedElements) { if (isOkToUse(fTreeControl)) { - int nSelected= selectedElements.size(); - for (int i= fElements.size() - 1; i >= 0 && nSelected > 0; i--) { + int nSelected = selectedElements.size(); + for (int i = fElements.size() - 1; i >= 0 && nSelected > 0; i--) { if (!selectedElements.contains(fElements.get(i))) { return true; } - nSelected--; + nSelected--; } } return false; } /** - * Returns the selected elements. - */ + * Returns the selected elements. + */ public List getSelectedElements() { - ArrayList result= new ArrayList(); + ArrayList result = new ArrayList(); if (fTree != null) { - ISelection selection= fTree.getSelection(); + ISelection selection = fTree.getSelection(); if (selection instanceof IStructuredSelection) { - Iterator iter= ((IStructuredSelection)selection).iterator(); + Iterator iter = ((IStructuredSelection) selection).iterator(); while (iter.hasNext()) { result.add(iter.next()); } @@ -811,19 +834,19 @@ public class TreeListDialogField extends DialogField { } return result; } - + public void expandElement(Object element, int level) { if (fTree != null) { fTree.expandToLevel(element, level); } } - // ------- TreeViewerAdapter - private class TreeViewerAdapter implements ITreeContentProvider, ISelectionChangedListener, IDoubleClickListener { + private class TreeViewerAdapter implements ITreeContentProvider, + ISelectionChangedListener, IDoubleClickListener { - private final Object[] NO_ELEMENTS= new Object[0]; + private final Object[] NO_ELEMENTS = new Object[0]; // ------- ITreeContentProvider Interface ------------ @@ -841,40 +864,45 @@ public class TreeListDialogField extends DialogField { public Object[] getElements(Object obj) { return fElements.toArray(); } - + public Object[] getChildren(Object element) { if (fTreeAdapter != null) { - return fTreeAdapter.getChildren(TreeListDialogField.this, element); + return fTreeAdapter.getChildren(TreeListDialogField.this, + element); } return NO_ELEMENTS; } public Object getParent(Object element) { if (!fElements.contains(element) && fTreeAdapter != null) { - return fTreeAdapter.getParent(TreeListDialogField.this, element); + return fTreeAdapter + .getParent(TreeListDialogField.this, element); } return fParentElement; } public boolean hasChildren(Object element) { if (fTreeAdapter != null) { - return fTreeAdapter.hasChildren(TreeListDialogField.this, element); + return fTreeAdapter.hasChildren(TreeListDialogField.this, + element); } return false; - } + } // ------- ISelectionChangedListener Interface ------------ public void selectionChanged(SelectionChangedEvent event) { doListSelected(event); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.jface.viewers.IDoubleClickListener#doubleClick(org.eclipse.jface.viewers.DoubleClickEvent) */ public void doubleClick(DoubleClickEvent event) { doDoubleClick(event); - } + } } @@ -884,13 +912,11 @@ public class TreeListDialogField extends DialogField { fTreeAdapter.selectionChanged(this); } } - + protected void doDoubleClick(DoubleClickEvent event) { if (fTreeAdapter != null) { fTreeAdapter.doubleClicked(this); } } - - } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/CoreTexts.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/CoreTexts.java index bad78a2..8e3a03b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/CoreTexts.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/CoreTexts.java @@ -10,7 +10,7 @@ import org.eclipse.osgi.util.NLS; * provides internationalized messages Strings from the coretexts resource * bundle. *

                                                      - * + * */ public class CoreTexts extends NLS { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenameIdentifierDelegate.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenameIdentifierDelegate.java index 570112e..beaf423 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenameIdentifierDelegate.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenameIdentifierDelegate.java @@ -41,7 +41,7 @@ import org.eclipse.text.edits.ReplaceEdit; *

                                                      * delegate object that contains the logic used by the processor. *

                                                      - * + * */ public class RenameIdentifierDelegate { @@ -71,7 +71,8 @@ public class RenameIdentifierDelegate { return result; } - RefactoringStatus checkFinalConditions(final IProgressMonitor pm, final CheckConditionsContext ctxt) { + RefactoringStatus checkFinalConditions(final IProgressMonitor pm, + final CheckConditionsContext ctxt) { RefactoringStatus result = new RefactoringStatus(); pm.beginTask(CoreTexts.renamePropertyDelegate_checking, 100); // do something long-running here: traverse the entire project (or even @@ -89,20 +90,27 @@ public class RenameIdentifierDelegate { if (members[i] instanceof IProject) { project = (IProject) members[i]; try { - if (project.isNatureEnabled(PHPeclipsePlugin.PHP_NATURE_ID)) { + if (project + .isNatureEnabled(PHPeclipsePlugin.PHP_NATURE_ID)) { search(project, result); } } catch (CoreException e) { - String msg = "Project: " + project.getLocation().toOSString() + " CoreException " + e.getMessage(); + String msg = "Project: " + + project.getLocation().toOSString() + + " CoreException " + e.getMessage(); result.addError(msg); } catch (Exception e) { - String msg = "Project: " + project.getLocation().toOSString() + " Exception " + e.getMessage(); + String msg = "Project: " + + project.getLocation().toOSString() + + " Exception " + e.getMessage(); result.addError(msg); } } } } catch (CoreException e) { - String msg = "Workspace: " + rootContainer.getLocation().toOSString() + " CoreException " + e.getMessage(); + String msg = "Workspace: " + + rootContainer.getLocation().toOSString() + + " CoreException " + e.getMessage(); result.addError(msg); } } else { @@ -112,10 +120,12 @@ public class RenameIdentifierDelegate { search(project, result); } } catch (CoreException e) { - String msg = "Project: " + project.getLocation().toOSString() + " CoreException " + e.getMessage(); + String msg = "Project: " + project.getLocation().toOSString() + + " CoreException " + e.getMessage(); result.addError(msg); } catch (Exception e) { - String msg = "Project: " + project.getLocation().toOSString() + " Exception " + e.getMessage(); + String msg = "Project: " + project.getLocation().toOSString() + + " Exception " + e.getMessage(); result.addError(msg); } } @@ -125,7 +135,8 @@ public class RenameIdentifierDelegate { if (ctxt != null) { IFile[] files = new IFile[phpFiles.size()]; phpFiles.keySet().toArray(files); - IConditionChecker checker = ctxt.getChecker(ValidateEditChecker.class); + IConditionChecker checker = ctxt + .getChecker(ValidateEditChecker.class); ValidateEditChecker editChecker = (ValidateEditChecker) checker; editChecker.addFiles(files); } @@ -133,9 +144,11 @@ public class RenameIdentifierDelegate { return result; } - protected void createChange(final IProgressMonitor pm, final CompositeChange rootChange) { + protected void createChange(final IProgressMonitor pm, + final CompositeChange rootChange) { try { - pm.beginTask(CoreTexts.renamePropertyDelegate_collectingChanges, 100); + pm.beginTask(CoreTexts.renamePropertyDelegate_collectingChanges, + 100); // all files in the same bundle if (info.isUpdateProject()) { rootChange.addAll(createChangesForContainer(pm)); @@ -157,7 +170,8 @@ public class RenameIdentifierDelegate { // MultiTextEdit fileChangeRootEdit = new MultiTextEdit(); // result.setEdit(fileChangeRootEdit); // - // // edit object for the text replacement in the file, this is the only child + // // edit object for the text replacement in the file, this is the only + // child // ReplaceEdit edit = new ReplaceEdit(info.getOffset(), // info.getOldName().length(), info.getNewName()); // fileChangeRootEdit.addChild(edit); @@ -179,16 +193,18 @@ public class RenameIdentifierDelegate { MultiTextEdit fileChangeRootEdit = new MultiTextEdit(); tfc.setEdit(fileChangeRootEdit); - // edit object for the text replacement in the file, there could be + // edit object for the text replacement in the file, there could + // be // multiple childs ReplaceEdit edit; for (int i = 0; i < list.size(); i++) { - edit = new ReplaceEdit(((Integer) list.get(i)).intValue(), info.getOldName().length(), info.getNewName()); + edit = new ReplaceEdit(((Integer) list.get(i)).intValue(), + info.getOldName().length(), info.getNewName()); fileChangeRootEdit.addChild(edit); } result.add(tfc); } - work = new Double((++indx)* percent).intValue(); + work = new Double((++indx) * percent).intValue(); pm.worked(work); } return (Change[]) result.toArray(new Change[result.size()]); @@ -198,7 +214,8 @@ public class RenameIdentifierDelegate { return candidate == null || candidate.trim().length() == 0; } - // private boolean isPropertyKey( final IFile file, final String candidate ) { + // private boolean isPropertyKey( final IFile file, final String candidate ) + // { // boolean result = false; // try { // Properties props = new Properties(); @@ -231,7 +248,8 @@ public class RenameIdentifierDelegate { // return result; // } - private void search(final IContainer rootContainer, final RefactoringStatus status) { + private void search(final IContainer rootContainer, + final RefactoringStatus status) { try { IResource[] members = rootContainer.members(); for (int i = 0; i < members.length; i++) { @@ -264,7 +282,8 @@ public class RenameIdentifierDelegate { // finds the offsets of the identifier to rename // usually, this would be the job of a proper parser; // using a primitive brute-force approach here - private void determineKeyOffsets(final IFile file, final RefactoringStatus status) { + private void determineKeyOffsets(final IFile file, + final RefactoringStatus status) { ArrayList matches = new ArrayList(); try { String content = readFileContent(file, status); @@ -277,24 +296,29 @@ public class RenameIdentifierDelegate { try { fToken = scanner.getNextToken(); while (fToken != ITerminalSymbols.TokenNameEOF) { - if (fToken == ITerminalSymbols.TokenNameVariable || fToken == ITerminalSymbols.TokenNameIdentifier) { + if (fToken == ITerminalSymbols.TokenNameVariable + || fToken == ITerminalSymbols.TokenNameIdentifier) { if (scanner.equalsCurrentTokenSource(word)) { - matches.add(new Integer(scanner.getCurrentTokenStartPosition())); + matches.add(new Integer(scanner + .getCurrentTokenStartPosition())); } } fToken = scanner.getNextToken(); } } catch (InvalidInputException e) { - String msg = "File: " + file.getLocation().toOSString() + " InvalidInputException " + e.getMessage(); + String msg = "File: " + file.getLocation().toOSString() + + " InvalidInputException " + e.getMessage(); status.addError(msg); } catch (SyntaxError e) { - String msg = "File: " + file.getLocation().toOSString() + " SyntaxError " + e.getMessage(); + String msg = "File: " + file.getLocation().toOSString() + + " SyntaxError " + e.getMessage(); status.addError(msg); } } catch (Exception e) { - String msg = "File: " + file.getLocation().toOSString() + " Exception " + e.getMessage(); + String msg = "File: " + file.getLocation().toOSString() + + " Exception " + e.getMessage(); status.addError(msg); } if (matches.size() > 0) { @@ -312,7 +336,8 @@ public class RenameIdentifierDelegate { // if( result == -1 ) { // // still nothing found, we add a warning to the status // // (we have checked the file contains the property, so that we can't - // // determine it's offset is probably because of the rough way employed + // // determine it's offset is probably because of the rough way + // employed // // here to find it) // String msg = CoreTexts.renamePropertyDelegate_propNotFound // + file.getLocation().toOSString(); @@ -321,7 +346,8 @@ public class RenameIdentifierDelegate { // return result; } - private String readFileContent(final IFile file, final RefactoringStatus refStatus) { + private String readFileContent(final IFile file, + final RefactoringStatus refStatus) { String result = null; try { InputStream is = file.getContents(); @@ -350,7 +376,8 @@ public class RenameIdentifierDelegate { // final int candidateIndex ) { // int index = candidateIndex + info.getOldName().length(); // // skip whitespace - // while( content.charAt( index ) == ' ' || content.charAt( index ) == '\t' ) + // while( content.charAt( index ) == ' ' || content.charAt( index ) == '\t' + // ) // { // index++; // } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenameIdentifierInfo.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenameIdentifierInfo.java index 6951116..b8d8e5b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenameIdentifierInfo.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenameIdentifierInfo.java @@ -12,7 +12,7 @@ import org.eclipse.core.resources.IFile; * an info object that holds the information that is passed from the user to the * refactoring. *

                                                      - * + * */ public class RenameIdentifierInfo { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenameIdentifierRefactoring.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenameIdentifierRefactoring.java index 54c2bad..e7c4c24 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenameIdentifierRefactoring.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenameIdentifierRefactoring.java @@ -10,12 +10,12 @@ import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor; *

                                                      * Refactoring for renaming identifiers in PHP files. *

                                                      - * + * *

                                                      * All the actual work is done in the processor, so we just have to keep a * reference to one here. *

                                                      - * + * */ public class RenameIdentifierRefactoring extends ProcessorBasedRefactoring { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenameLocalVariableDelegate.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenameLocalVariableDelegate.java index 81bc31a..b61f6a4 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenameLocalVariableDelegate.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenameLocalVariableDelegate.java @@ -31,201 +31,232 @@ import org.eclipse.ltk.core.refactoring.participants.ValidateEditChecker; *

                                                      * delegate object that contains the logic used by the processor. *

                                                      - * + * */ public class RenameLocalVariableDelegate extends RenameIdentifierDelegate { - public RenameLocalVariableDelegate(final RenameIdentifierInfo info) { - super(info); - } - - RefactoringStatus checkInitialConditions() { - RefactoringStatus result = new RefactoringStatus(); - IFile sourceFile = info.getSourceFile(); - if (sourceFile == null || !sourceFile.exists()) { - result.addFatalError(CoreTexts.renamePropertyDelegate_noSourceFile); - } else if (info.getSourceFile().isReadOnly()) { - result.addFatalError(CoreTexts.renamePropertyDelegate_roFile); - } else if (isEmpty(info.getOldName())) { - // || !isPropertyKey( info.getSourceFile(), info.getOldName() ) ) { - result.addFatalError(CoreTexts.renamePropertyDelegate_noPHPKey); + public RenameLocalVariableDelegate(final RenameIdentifierInfo info) { + super(info); } - return result; - } - - RefactoringStatus checkFinalConditions(final IProgressMonitor pm, final CheckConditionsContext ctxt) { - RefactoringStatus result = new RefactoringStatus(); - pm.beginTask(CoreTexts.renamePropertyDelegate_checking, 100); - // do something long-running here: traverse the entire project (or even - // workspace) to look for all *.p files with the same bundle - // base name - IFile file = info.getSourceFile(); - IProject project = file.getProject(); - try { - SourceMethod method = info.getMethod(); - ISourceRange range = method.getSourceRange(); - if (project.isNatureEnabled(PHPeclipsePlugin.PHP_NATURE_ID)) { - determineMethodOffsets(file, range.getOffset(), range.getLength(), result); - } - } catch (CoreException e) { - String msg = "Project: " + project.getLocation().toOSString() + " CoreException " + e.getMessage(); - result.addError(msg); - } catch (Exception e) { - String msg = "Project: " + project.getLocation().toOSString() + " Exception " + e.getMessage(); - result.addError(msg); + + RefactoringStatus checkInitialConditions() { + RefactoringStatus result = new RefactoringStatus(); + IFile sourceFile = info.getSourceFile(); + if (sourceFile == null || !sourceFile.exists()) { + result.addFatalError(CoreTexts.renamePropertyDelegate_noSourceFile); + } else if (info.getSourceFile().isReadOnly()) { + result.addFatalError(CoreTexts.renamePropertyDelegate_roFile); + } else if (isEmpty(info.getOldName())) { + // || !isPropertyKey( info.getSourceFile(), info.getOldName() ) ) { + result.addFatalError(CoreTexts.renamePropertyDelegate_noPHPKey); + } + return result; } - pm.worked(50); + RefactoringStatus checkFinalConditions(final IProgressMonitor pm, + final CheckConditionsContext ctxt) { + RefactoringStatus result = new RefactoringStatus(); + pm.beginTask(CoreTexts.renamePropertyDelegate_checking, 100); + // do something long-running here: traverse the entire project (or even + // workspace) to look for all *.p files with the same bundle + // base name + IFile file = info.getSourceFile(); + IProject project = file.getProject(); + try { + SourceMethod method = info.getMethod(); + ISourceRange range = method.getSourceRange(); + if (project.isNatureEnabled(PHPeclipsePlugin.PHP_NATURE_ID)) { + determineMethodOffsets(file, range.getOffset(), range + .getLength(), result); + } + } catch (CoreException e) { + String msg = "Project: " + project.getLocation().toOSString() + + " CoreException " + e.getMessage(); + result.addError(msg); + } catch (Exception e) { + String msg = "Project: " + project.getLocation().toOSString() + + " Exception " + e.getMessage(); + result.addError(msg); + } + + pm.worked(50); - if (ctxt != null) { - IFile[] files = new IFile[phpFiles.size()]; - phpFiles.keySet().toArray(files); - IConditionChecker checker = ctxt.getChecker(ValidateEditChecker.class); - ValidateEditChecker editChecker = (ValidateEditChecker) checker; - editChecker.addFiles(files); - } - pm.done(); - return result; - } - - protected void createChange(final IProgressMonitor pm, final CompositeChange rootChange) { - try { - pm.beginTask(CoreTexts.renamePropertyDelegate_collectingChanges, 100); - // all files in the same bundle - rootChange.addAll(createChangesForContainer(pm)); - } finally { - pm.done(); + if (ctxt != null) { + IFile[] files = new IFile[phpFiles.size()]; + phpFiles.keySet().toArray(files); + IConditionChecker checker = ctxt + .getChecker(ValidateEditChecker.class); + ValidateEditChecker editChecker = (ValidateEditChecker) checker; + editChecker.addFiles(files); + } + pm.done(); + return result; } - } - - private void determineMethodOffsets(final IFile file, int offset, int length, final RefactoringStatus status) { - ArrayList matches = new ArrayList(); - try { - String content = readFileContent(file, status); - - // - // Find a PHPdoc directly before the method - // - Scanner firstScanner = new Scanner(true, false); - firstScanner.setSource(content.toCharArray()); - int fToken = ITerminalSymbols.TokenNameEOF; - int start = 0; - int phpdocStart = -1; - try { - fToken = firstScanner.getNextToken(); - while (fToken != ITerminalSymbols.TokenNameEOF && start < offset) { - if (fToken == ITerminalSymbols.TokenNameCOMMENT_PHPDOC) { - phpdocStart = firstScanner.getCurrentTokenStartPosition(); - } else { - phpdocStart = -1; - } - fToken = firstScanner.getNextToken(); - start = firstScanner.getCurrentTokenStartPosition(); + + protected void createChange(final IProgressMonitor pm, + final CompositeChange rootChange) { + try { + pm.beginTask(CoreTexts.renamePropertyDelegate_collectingChanges, + 100); + // all files in the same bundle + rootChange.addAll(createChangesForContainer(pm)); + } finally { + pm.done(); } + } - } catch (InvalidInputException e) { - String msg = "File: " + file.getLocation().toOSString() + " InvalidInputException " + e.getMessage(); - status.addError(msg); - } catch (SyntaxError e) { - String msg = "File: " + file.getLocation().toOSString() + " SyntaxError " + e.getMessage(); - status.addError(msg); - } - - // - // Find matches for the word in the PHPdoc+method declaration - // - if (phpdocStart >= 0 && phpdocStart < offset) { - length += offset - phpdocStart; - offset = phpdocStart; - } - String methodString = content.substring(offset, offset + length); - Scanner secondScanner = new Scanner(true, false); - secondScanner.setSource(methodString.toCharArray()); - secondScanner.setPHPMode(true); - String wordStr = info.getOldName(); - boolean renameDQString = info.isRenameDQString(); - boolean renamePHPdoc = info.isRenamePHPdoc(); - boolean renameOtherComments = info.isRenameOtherComments(); - char[] word = wordStr.toCharArray(); - - fToken = ITerminalSymbols.TokenNameEOF; - // double quoted string - String tokenString; - // double quoted string offset - int tokenOffset; - int index; - try { - fToken = secondScanner.getNextToken(); - while (fToken != ITerminalSymbols.TokenNameEOF) { - if (fToken == ITerminalSymbols.TokenNameVariable) { - if (secondScanner.equalsCurrentTokenSource(word)) { - // the current variable token is equal to the given word - matches.add(new Integer(secondScanner.getCurrentTokenStartPosition() + offset)); - } - } else if (fToken == ITerminalSymbols.TokenNameStringDoubleQuote && renameDQString) { - // determine the word in double quoted strings: - tokenString = new String(secondScanner.getCurrentTokenSource()); - tokenOffset = secondScanner.getCurrentTokenStartPosition(); - index = -1; - while ((index = tokenString.indexOf(wordStr, index + 1)) >= 0) { - matches.add(new Integer(offset + tokenOffset + index)); + private void determineMethodOffsets(final IFile file, int offset, + int length, final RefactoringStatus status) { + ArrayList matches = new ArrayList(); + try { + String content = readFileContent(file, status); + + // + // Find a PHPdoc directly before the method + // + Scanner firstScanner = new Scanner(true, false); + firstScanner.setSource(content.toCharArray()); + int fToken = ITerminalSymbols.TokenNameEOF; + int start = 0; + int phpdocStart = -1; + try { + fToken = firstScanner.getNextToken(); + while (fToken != ITerminalSymbols.TokenNameEOF + && start < offset) { + if (fToken == ITerminalSymbols.TokenNameCOMMENT_PHPDOC) { + phpdocStart = firstScanner + .getCurrentTokenStartPosition(); + } else { + phpdocStart = -1; + } + fToken = firstScanner.getNextToken(); + start = firstScanner.getCurrentTokenStartPosition(); + } + + } catch (InvalidInputException e) { + String msg = "File: " + file.getLocation().toOSString() + + " InvalidInputException " + e.getMessage(); + status.addError(msg); + } catch (SyntaxError e) { + String msg = "File: " + file.getLocation().toOSString() + + " SyntaxError " + e.getMessage(); + status.addError(msg); } - } else if (fToken == ITerminalSymbols.TokenNameCOMMENT_PHPDOC && renamePHPdoc) { - tokenString = new String(secondScanner.getCurrentTokenSource()); - tokenOffset = secondScanner.getCurrentTokenStartPosition(); - index = -1; - while ((index = tokenString.indexOf(wordStr, index + 1)) >= 0) { - matches.add(new Integer(offset + tokenOffset + index)); + + // + // Find matches for the word in the PHPdoc+method declaration + // + if (phpdocStart >= 0 && phpdocStart < offset) { + length += offset - phpdocStart; + offset = phpdocStart; } - } else if ( (fToken == ITerminalSymbols.TokenNameCOMMENT_BLOCK || fToken == ITerminalSymbols.TokenNameCOMMENT_LINE) && renameOtherComments) { - tokenString = new String(secondScanner.getCurrentTokenSource()); - tokenOffset = secondScanner.getCurrentTokenStartPosition(); - index = -1; - while ((index = tokenString.indexOf(wordStr, index + 1)) >= 0) { - matches.add(new Integer(offset + tokenOffset + index)); + String methodString = content.substring(offset, offset + length); + Scanner secondScanner = new Scanner(true, false); + secondScanner.setSource(methodString.toCharArray()); + secondScanner.setPHPMode(true); + String wordStr = info.getOldName(); + boolean renameDQString = info.isRenameDQString(); + boolean renamePHPdoc = info.isRenamePHPdoc(); + boolean renameOtherComments = info.isRenameOtherComments(); + char[] word = wordStr.toCharArray(); + + fToken = ITerminalSymbols.TokenNameEOF; + // double quoted string + String tokenString; + // double quoted string offset + int tokenOffset; + int index; + try { + fToken = secondScanner.getNextToken(); + while (fToken != ITerminalSymbols.TokenNameEOF) { + if (fToken == ITerminalSymbols.TokenNameVariable) { + if (secondScanner.equalsCurrentTokenSource(word)) { + // the current variable token is equal to the given + // word + matches.add(new Integer(secondScanner + .getCurrentTokenStartPosition() + + offset)); + } + } else if (fToken == ITerminalSymbols.TokenNameStringDoubleQuote + && renameDQString) { + // determine the word in double quoted strings: + tokenString = new String(secondScanner + .getCurrentTokenSource()); + tokenOffset = secondScanner + .getCurrentTokenStartPosition(); + index = -1; + while ((index = tokenString.indexOf(wordStr, index + 1)) >= 0) { + matches.add(new Integer(offset + tokenOffset + + index)); + } + } else if (fToken == ITerminalSymbols.TokenNameCOMMENT_PHPDOC + && renamePHPdoc) { + tokenString = new String(secondScanner + .getCurrentTokenSource()); + tokenOffset = secondScanner + .getCurrentTokenStartPosition(); + index = -1; + while ((index = tokenString.indexOf(wordStr, index + 1)) >= 0) { + matches.add(new Integer(offset + tokenOffset + + index)); + } + } else if ((fToken == ITerminalSymbols.TokenNameCOMMENT_BLOCK || fToken == ITerminalSymbols.TokenNameCOMMENT_LINE) + && renameOtherComments) { + tokenString = new String(secondScanner + .getCurrentTokenSource()); + tokenOffset = secondScanner + .getCurrentTokenStartPosition(); + index = -1; + while ((index = tokenString.indexOf(wordStr, index + 1)) >= 0) { + matches.add(new Integer(offset + tokenOffset + + index)); + } + } + fToken = secondScanner.getNextToken(); + } + + } catch (InvalidInputException e) { + String msg = "File: " + file.getLocation().toOSString() + + " InvalidInputException " + e.getMessage(); + status.addError(msg); + } catch (SyntaxError e) { + String msg = "File: " + file.getLocation().toOSString() + + " SyntaxError " + e.getMessage(); + status.addError(msg); } - } - fToken = secondScanner.getNextToken(); - } - } catch (InvalidInputException e) { - String msg = "File: " + file.getLocation().toOSString() + " InvalidInputException " + e.getMessage(); - status.addError(msg); - } catch (SyntaxError e) { - String msg = "File: " + file.getLocation().toOSString() + " SyntaxError " + e.getMessage(); - status.addError(msg); - } - - } catch (Exception e) { - String msg = "File: " + file.getLocation().toOSString() + " Exception " + e.getMessage(); - status.addError(msg); - } - if (matches.size() > 0) { - phpFiles.put(file, matches); + } catch (Exception e) { + String msg = "File: " + file.getLocation().toOSString() + + " Exception " + e.getMessage(); + status.addError(msg); + } + if (matches.size() > 0) { + phpFiles.put(file, matches); + } } - } - - private String readFileContent(final IFile file, final RefactoringStatus refStatus) { - String result = null; - try { - InputStream is = file.getContents(); - byte[] buf = new byte[1024]; - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - int len = is.read(buf); - while (len > 0) { - bos.write(buf, 0, len); - len = is.read(buf); - } - is.close(); - result = new String(bos.toByteArray()); - } catch (Exception ex) { - String msg = ex.toString(); - refStatus.addFatalError(msg); - String pluginId = PHPeclipsePlugin.getPluginId(); - IStatus status = new Status(IStatus.ERROR, pluginId, 0, msg, ex); - PHPeclipsePlugin.getDefault().getLog().log(status); + + private String readFileContent(final IFile file, + final RefactoringStatus refStatus) { + String result = null; + try { + InputStream is = file.getContents(); + byte[] buf = new byte[1024]; + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + int len = is.read(buf); + while (len > 0) { + bos.write(buf, 0, len); + len = is.read(buf); + } + is.close(); + result = new String(bos.toByteArray()); + } catch (Exception ex) { + String msg = ex.toString(); + refStatus.addFatalError(msg); + String pluginId = PHPeclipsePlugin.getPluginId(); + IStatus status = new Status(IStatus.ERROR, pluginId, 0, msg, ex); + PHPeclipsePlugin.getDefault().getLog().log(status); + } + return result; } - return result; - } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenamePHPProcessor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenamePHPProcessor.java index be64c83..f1d489a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenamePHPProcessor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenamePHPProcessor.java @@ -3,66 +3,79 @@ // modified for phpeclipse.de project by axelcl package net.sourceforge.phpdt.ltk.core; -import org.eclipse.core.runtime.*; -import org.eclipse.ltk.core.refactoring.*; -import org.eclipse.ltk.core.refactoring.participants.*; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.ltk.core.refactoring.Change; +import org.eclipse.ltk.core.refactoring.CompositeChange; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext; +import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant; +import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor; +import org.eclipse.ltk.core.refactoring.participants.SharableParticipants; -/**

                                                      The processor is where the work is delegated to if participants are - * involved. The processor loads the participants and manages the lifecycle - * of the refactoring. In order to do that, the refactoring entry point - * methods must be implemented.

                                                      - * - */ +/** + *

                                                      + * The processor is where the work is delegated to if participants are involved. + * The processor loads the participants and manages the lifecycle of the + * refactoring. In order to do that, the refactoring entry point methods must be + * implemented. + *

                                                      + * + */ public class RenamePHPProcessor extends RefactoringProcessor { - private final RenameIdentifierInfo info; - private final RenameIdentifierDelegate delegate; + private final RenameIdentifierInfo info; - public RenamePHPProcessor( final RenameIdentifierInfo info, final RenameIdentifierDelegate delegate ) { - this.info = info; - this.delegate = delegate; - } + private final RenameIdentifierDelegate delegate; + public RenamePHPProcessor(final RenameIdentifierInfo info, + final RenameIdentifierDelegate delegate) { + this.info = info; + this.delegate = delegate; + } - public Object[] getElements() { - // usually, this would be some element object in the object model on which - // we work (e.g. a Java element if we were in the Java Model); in this case - // we have only the property name - return new Object[] { info.getOldName() }; - } + public Object[] getElements() { + // usually, this would be some element object in the object model on + // which + // we work (e.g. a Java element if we were in the Java Model); in this + // case + // we have only the property name + return new Object[] { info.getOldName() }; + } - public String getIdentifier() { - return getClass().getName(); - } + public String getIdentifier() { + return getClass().getName(); + } - public String getProcessorName() { - return CoreTexts.renamePropertyProcessor_name; - } + public String getProcessorName() { + return CoreTexts.renamePropertyProcessor_name; + } - public boolean isApplicable() throws CoreException { - return true; - } + public boolean isApplicable() throws CoreException { + return true; + } - public RefactoringStatus checkInitialConditions( final IProgressMonitor pm ) { - return delegate.checkInitialConditions(); - } + public RefactoringStatus checkInitialConditions(final IProgressMonitor pm) { + return delegate.checkInitialConditions(); + } - public RefactoringStatus checkFinalConditions( - final IProgressMonitor pm, final CheckConditionsContext context ) { - return delegate.checkFinalConditions( pm, context ); - } + public RefactoringStatus checkFinalConditions(final IProgressMonitor pm, + final CheckConditionsContext context) { + return delegate.checkFinalConditions(pm, context); + } - public Change createChange( final IProgressMonitor pm ) { - CompositeChange result = new CompositeChange( getProcessorName() ); - delegate.createChange( pm, result ); - return result; - } + public Change createChange(final IProgressMonitor pm) { + CompositeChange result = new CompositeChange(getProcessorName()); + delegate.createChange(pm, result); + return result; + } - public RefactoringParticipant[] loadParticipants( - final RefactoringStatus status, - final SharableParticipants sharedParticipants ) { - // This would be the place to load the participants via the - // ParticipantManager and decide which of them are allowed to participate. - return new RefactoringParticipant[ 0 ]; - } + public RefactoringParticipant[] loadParticipants( + final RefactoringStatus status, + final SharableParticipants sharedParticipants) { + // This would be the place to load the participants via the + // ParticipantManager and decide which of them are allowed to + // participate. + return new RefactoringParticipant[0]; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/UITexts.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/UITexts.java index adac1e0..0914c0c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/UITexts.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/UITexts.java @@ -9,7 +9,7 @@ import org.eclipse.osgi.util.NLS; *

                                                      * provides internationalized String messages for the UI. *

                                                      - * + * */ public class UITexts { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/actions/RenameLocalVariable.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/actions/RenameLocalVariable.java index 0b1a91c..0ed5df5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/actions/RenameLocalVariable.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/actions/RenameLocalVariable.java @@ -51,7 +51,8 @@ public class RenameLocalVariable implements IEditorActionDelegate { private RenameIdentifierInfo info = new RenameIdentifierInfo(); - public void setActiveEditor(final IAction action, final IEditorPart targetEditor) { + public void setActiveEditor(final IAction action, + final IEditorPart targetEditor) { this.targetEditor = targetEditor; onPHPFile = false; IFile file = getFile(); @@ -71,20 +72,28 @@ public class RenameLocalVariable implements IEditorActionDelegate { if (targetEditor != null && (targetEditor instanceof PHPEditor)) { PHPEditor editor = (PHPEditor) targetEditor; if (editor != null) { - ITextSelection textSelection = (ITextSelection) editor.getSelectionProvider().getSelection(); - IDocument doc = editor.getDocumentProvider().getDocument(editor.getEditorInput()); + ITextSelection textSelection = (ITextSelection) editor + .getSelectionProvider().getSelection(); + IDocument doc = editor.getDocumentProvider() + .getDocument(editor.getEditorInput()); int pos = textSelection.getOffset(); point = PHPWordExtractor.findWord(doc, pos); if (point != null) { try { word = doc.get(point.x, point.y); - IWorkingCopyManager manager = PHPeclipsePlugin.getDefault().getWorkingCopyManager(); - ICompilationUnit unit = manager.getWorkingCopy(editor.getEditorInput()); - SourceMethod method = (SourceMethod) findEnclosingElement(point.x, unit, IJavaElement.METHOD); - if (word == null || word.charAt(0) != '$' || method == null || !(method instanceof SourceMethod)) { + IWorkingCopyManager manager = PHPeclipsePlugin + .getDefault().getWorkingCopyManager(); + ICompilationUnit unit = manager + .getWorkingCopy(editor.getEditorInput()); + SourceMethod method = (SourceMethod) findEnclosingElement( + point.x, unit, IJavaElement.METHOD); + if (word == null || word.charAt(0) != '$' + || method == null + || !(method instanceof SourceMethod)) { refuseLocalVariable(); } else { - applySelection((ITextSelection) selection, word, point, method); + applySelection((ITextSelection) selection, + word, point, method); if (saveAll()) { openWizard(); } @@ -102,7 +111,8 @@ public class RenameLocalVariable implements IEditorActionDelegate { * Returns the enclosing element of a particular element type, * null if no enclosing element of that type exists. */ - public IJavaElement findEnclosingElement(int start, ICompilationUnit cu, int elementType) { + public IJavaElement findEnclosingElement(int start, ICompilationUnit cu, + int elementType) { if (cu == null) return null; @@ -119,14 +129,16 @@ public class RenameLocalVariable implements IEditorActionDelegate { } } - public void selectionChanged(final IAction action, final ISelection selection) { + public void selectionChanged(final IAction action, + final ISelection selection) { this.selection = selection; } // helping methods // //////////////// - private void applySelection(final ITextSelection textSelection, String word, Point point, SourceMethod method) { + private void applySelection(final ITextSelection textSelection, + String word, Point point, SourceMethod method) { if (word != null) { info.setOldName(word); info.setNewName(word); @@ -158,11 +170,15 @@ public class RenameLocalVariable implements IEditorActionDelegate { } private void openWizard() { - RenameLocalVariableDelegate delegate = new RenameLocalVariableDelegate(info); + RenameLocalVariableDelegate delegate = new RenameLocalVariableDelegate( + info); RefactoringProcessor processor = new RenamePHPProcessor(info, delegate); - RenameIdentifierRefactoring ref = new RenameIdentifierRefactoring(processor); - RenameLocalVariableWizard wizard = new RenameLocalVariableWizard(ref, info); - RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation(wizard); + RenameIdentifierRefactoring ref = new RenameIdentifierRefactoring( + processor); + RenameLocalVariableWizard wizard = new RenameLocalVariableWizard(ref, + info); + RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation( + wizard); try { String titleForFailedChecks = ""; //$NON-NLS-1$ op.run(getShell(), titleForFailedChecks); @@ -176,7 +192,8 @@ public class RenameLocalVariable implements IEditorActionDelegate { if (targetEditor != null) { result = targetEditor.getSite().getShell(); } else { - result = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); + result = PlatformUI.getWorkbench().getActiveWorkbenchWindow() + .getShell(); } return result; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/actions/RenamePHPIdentifier.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/actions/RenamePHPIdentifier.java index c73d1f4..53d06a5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/actions/RenamePHPIdentifier.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/actions/RenamePHPIdentifier.java @@ -6,8 +6,8 @@ package net.sourceforge.phpdt.ltk.ui.actions; import net.sourceforge.phpdt.internal.ui.util.PHPFileUtil; import net.sourceforge.phpdt.ltk.core.RenameIdentifierDelegate; import net.sourceforge.phpdt.ltk.core.RenameIdentifierInfo; -import net.sourceforge.phpdt.ltk.core.RenamePHPProcessor; import net.sourceforge.phpdt.ltk.core.RenameIdentifierRefactoring; +import net.sourceforge.phpdt.ltk.core.RenamePHPProcessor; import net.sourceforge.phpdt.ltk.ui.UITexts; import net.sourceforge.phpdt.ltk.ui.wizards.RenameIdentifierWizard; import net.sourceforge.phpeclipse.phpeditor.PHPEditor; @@ -39,11 +39,11 @@ import org.eclipse.ui.texteditor.ITextEditor; *

                                                      * action that is triggered from the editor context menu. *

                                                      - * + * *

                                                      * This action is declared in the plugin.xml. *

                                                      - * + * */ public class RenamePHPIdentifier implements IEditorActionDelegate { @@ -58,7 +58,8 @@ public class RenamePHPIdentifier implements IEditorActionDelegate { // interface methods of IEditorActionDelegate // /////////////////////////////////////////// - public void setActiveEditor(final IAction action, final IEditorPart targetEditor) { + public void setActiveEditor(final IAction action, + final IEditorPart targetEditor) { this.targetEditor = targetEditor; onPHPFile = false; IFile file = getFile(); @@ -78,8 +79,10 @@ public class RenamePHPIdentifier implements IEditorActionDelegate { if (targetEditor != null && (targetEditor instanceof PHPEditor)) { PHPEditor editor = (PHPEditor) targetEditor; if (editor != null) { - ITextSelection textSelection = (ITextSelection) editor.getSelectionProvider().getSelection(); - IDocument doc = editor.getDocumentProvider().getDocument(editor.getEditorInput()); + ITextSelection textSelection = (ITextSelection) editor + .getSelectionProvider().getSelection(); + IDocument doc = editor.getDocumentProvider() + .getDocument(editor.getEditorInput()); int pos = textSelection.getOffset(); point = PHPWordExtractor.findWord(doc, pos); if (point != null) { @@ -98,14 +101,16 @@ public class RenamePHPIdentifier implements IEditorActionDelegate { } } - public void selectionChanged(final IAction action, final ISelection selection) { + public void selectionChanged(final IAction action, + final ISelection selection) { this.selection = selection; } // helping methods // //////////////// - private void applySelection(final ITextSelection textSelection, String word, Point point) { + private void applySelection(final ITextSelection textSelection, + String word, Point point) { if (word != null) { info.setOldName(word); info.setNewName(word); @@ -130,11 +135,13 @@ public class RenamePHPIdentifier implements IEditorActionDelegate { } private void openWizard() { - RenameIdentifierDelegate delegate = new RenameIdentifierDelegate( info ); + RenameIdentifierDelegate delegate = new RenameIdentifierDelegate(info); RefactoringProcessor processor = new RenamePHPProcessor(info, delegate); - RenameIdentifierRefactoring ref = new RenameIdentifierRefactoring(processor); + RenameIdentifierRefactoring ref = new RenameIdentifierRefactoring( + processor); RenameIdentifierWizard wizard = new RenameIdentifierWizard(ref, info); - RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation(wizard); + RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation( + wizard); try { String titleForFailedChecks = ""; //$NON-NLS-1$ op.run(getShell(), titleForFailedChecks); @@ -148,7 +155,8 @@ public class RenamePHPIdentifier implements IEditorActionDelegate { if (targetEditor != null) { result = targetEditor.getSite().getShell(); } else { - result = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); + result = PlatformUI.getWorkbench().getActiveWorkbenchWindow() + .getShell(); } return result; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameIdentifierPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameIdentifierPage.java index 24f0d63..027f590 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameIdentifierPage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameIdentifierPage.java @@ -21,155 +21,160 @@ import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; - -/**

                                                      the input page for the Rename Property refactoring, where users can - * control the effects of the refactoring; to be shown in the wizard.

                                                      - * - *

                                                      We let the user enter the new name for the property, and we let her - * decide whether other property files in the bundle should be affected, and - * whether the operation is supposed to span the entire workspace or only - * the current project.

                                                      - * - */ +/** + *

                                                      + * the input page for the Rename Property refactoring, where users can control + * the effects of the refactoring; to be shown in the wizard. + *

                                                      + * + *

                                                      + * We let the user enter the new name for the property, and we let her decide + * whether other property files in the bundle should be affected, and whether + * the operation is supposed to span the entire workspace or only the current + * project. + *

                                                      + * + */ public class RenameIdentifierPage extends UserInputWizardPage { - private static final String DS_KEY = RenameIdentifierPage.class.getName(); - private static final String DS_UPDATE_BUNDLE = "UPDATE_BUNDLE"; //$NON-NLS-1$ - private static final String DS_ALL_PROJECTS = "ALL_PROJECTS"; //$NON-NLS-1$ - - private final RenameIdentifierInfo info; - - private IDialogSettings dialogSettings; - private Text txtNewName; - private Button cbUpdateBundle; - private Button cbAllProjects; - - - public RenameIdentifierPage( final RenameIdentifierInfo info ) { - super( RenameIdentifierPage.class.getName() ); - this.info = info; - initDialogSettings(); - } - - - // interface methods of UserInputWizardPage - /////////////////////////////////////////// - - public void createControl( final Composite parent ) { - Composite composite = createRootComposite( parent ); - setControl( composite ); - - createLblNewName( composite ); - createTxtNewName( composite ); - createCbUpdateBundle( composite ); - createCbAllProjects( composite ); - - validate(); - } - - - // UI creation methods - ////////////////////// - - private Composite createRootComposite( final Composite parent ) { - Composite result = new Composite( parent, SWT.NONE ); - GridLayout gridLayout = new GridLayout( 2, false ); - gridLayout.marginWidth = 10; - gridLayout.marginHeight = 10; - result.setLayout( gridLayout ); - initializeDialogUnits( result ); - Dialog.applyDialogFont( result ); - return result; - } - - private void createLblNewName( final Composite composite ) { - Label lblNewName = new Label( composite, SWT.NONE ); - lblNewName.setText( UITexts.renamePropertyInputPage_lblNewName ); - } - - private void createTxtNewName(Composite composite) { - txtNewName = new Text( composite, SWT.BORDER ); - txtNewName.setText( info.getOldName() ); - txtNewName.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); - txtNewName.selectAll(); - txtNewName.addKeyListener( new KeyAdapter() { - public void keyReleased( final KeyEvent e ) { - info.setNewName( txtNewName.getText() ); - validate(); - } - } ); - } - - private void createCbUpdateBundle( final Composite composite ) { - String texts = UITexts.renamePropertyInputPage_cbUpdateBundle; - cbUpdateBundle = createCheckbox( composite, texts ); - cbUpdateBundle.addSelectionListener( new SelectionAdapter() { - public void widgetSelected( final SelectionEvent event ) { - boolean selected = cbUpdateBundle.getSelection(); - dialogSettings.put( DS_UPDATE_BUNDLE, selected ); - info.setUpdateProject( selected ); - } - } ); - initUpdateBundleOption(); - } - - private void createCbAllProjects( final Composite composite ) { - String text = UITexts.renamePropertyInputPage_cbAllProjects; - cbAllProjects = createCheckbox( composite, text ); - cbAllProjects.addSelectionListener( new SelectionAdapter() { - public void widgetSelected( final SelectionEvent event ) { - boolean selected = cbAllProjects.getSelection(); - dialogSettings.put( DS_ALL_PROJECTS, selected ); - info.setAllProjects( selected ); - // for demonstration purposes, we enforce the preview for refactorings - // that span the entire workspace - getRefactoringWizard().setForcePreviewReview( selected ); - } - } ); - initAllProjectsOption(); - } - - private Button createCheckbox( final Composite composite, - final String text ) { - Button result = new Button( composite, SWT.CHECK ); - result.setText( text ); - - GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); - gridData.horizontalSpan = 2; - result.setLayoutData( gridData ); - - return result; - } - - - // helping methods - ////////////////// - - private void initDialogSettings() { - IDialogSettings ds = PHPeclipsePlugin.getDefault().getDialogSettings(); - dialogSettings = ds.getSection( DS_KEY ); - if( dialogSettings == null ) { - dialogSettings = ds.addNewSection( DS_KEY ); - // init default values - dialogSettings.put( DS_UPDATE_BUNDLE, true ); - dialogSettings.put( DS_ALL_PROJECTS, false ); - } - } - - private void validate() { - String txt = txtNewName.getText(); - setPageComplete( txt.length() > 0 && !txt.equals( info.getOldName() ) ); - } - - private void initUpdateBundleOption() { - boolean updateRefs = dialogSettings.getBoolean( DS_UPDATE_BUNDLE ); - cbUpdateBundle.setSelection( updateRefs ); - info.setUpdateProject( updateRefs ); - } - - private void initAllProjectsOption() { - boolean allProjects = dialogSettings.getBoolean( DS_ALL_PROJECTS ); - cbAllProjects.setSelection( allProjects ); - info.setAllProjects( allProjects ); - } + private static final String DS_KEY = RenameIdentifierPage.class.getName(); + + private static final String DS_UPDATE_BUNDLE = "UPDATE_BUNDLE"; //$NON-NLS-1$ + + private static final String DS_ALL_PROJECTS = "ALL_PROJECTS"; //$NON-NLS-1$ + + private final RenameIdentifierInfo info; + + private IDialogSettings dialogSettings; + + private Text txtNewName; + + private Button cbUpdateBundle; + + private Button cbAllProjects; + + public RenameIdentifierPage(final RenameIdentifierInfo info) { + super(RenameIdentifierPage.class.getName()); + this.info = info; + initDialogSettings(); + } + + // interface methods of UserInputWizardPage + // ///////////////////////////////////////// + + public void createControl(final Composite parent) { + Composite composite = createRootComposite(parent); + setControl(composite); + + createLblNewName(composite); + createTxtNewName(composite); + createCbUpdateBundle(composite); + createCbAllProjects(composite); + + validate(); + } + + // UI creation methods + // //////////////////// + + private Composite createRootComposite(final Composite parent) { + Composite result = new Composite(parent, SWT.NONE); + GridLayout gridLayout = new GridLayout(2, false); + gridLayout.marginWidth = 10; + gridLayout.marginHeight = 10; + result.setLayout(gridLayout); + initializeDialogUnits(result); + Dialog.applyDialogFont(result); + return result; + } + + private void createLblNewName(final Composite composite) { + Label lblNewName = new Label(composite, SWT.NONE); + lblNewName.setText(UITexts.renamePropertyInputPage_lblNewName); + } + + private void createTxtNewName(Composite composite) { + txtNewName = new Text(composite, SWT.BORDER); + txtNewName.setText(info.getOldName()); + txtNewName.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + txtNewName.selectAll(); + txtNewName.addKeyListener(new KeyAdapter() { + public void keyReleased(final KeyEvent e) { + info.setNewName(txtNewName.getText()); + validate(); + } + }); + } + + private void createCbUpdateBundle(final Composite composite) { + String texts = UITexts.renamePropertyInputPage_cbUpdateBundle; + cbUpdateBundle = createCheckbox(composite, texts); + cbUpdateBundle.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(final SelectionEvent event) { + boolean selected = cbUpdateBundle.getSelection(); + dialogSettings.put(DS_UPDATE_BUNDLE, selected); + info.setUpdateProject(selected); + } + }); + initUpdateBundleOption(); + } + + private void createCbAllProjects(final Composite composite) { + String text = UITexts.renamePropertyInputPage_cbAllProjects; + cbAllProjects = createCheckbox(composite, text); + cbAllProjects.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(final SelectionEvent event) { + boolean selected = cbAllProjects.getSelection(); + dialogSettings.put(DS_ALL_PROJECTS, selected); + info.setAllProjects(selected); + // for demonstration purposes, we enforce the preview for + // refactorings + // that span the entire workspace + getRefactoringWizard().setForcePreviewReview(selected); + } + }); + initAllProjectsOption(); + } + + private Button createCheckbox(final Composite composite, final String text) { + Button result = new Button(composite, SWT.CHECK); + result.setText(text); + + GridData gridData = new GridData(GridData.FILL_HORIZONTAL); + gridData.horizontalSpan = 2; + result.setLayoutData(gridData); + + return result; + } + + // helping methods + // //////////////// + + private void initDialogSettings() { + IDialogSettings ds = PHPeclipsePlugin.getDefault().getDialogSettings(); + dialogSettings = ds.getSection(DS_KEY); + if (dialogSettings == null) { + dialogSettings = ds.addNewSection(DS_KEY); + // init default values + dialogSettings.put(DS_UPDATE_BUNDLE, true); + dialogSettings.put(DS_ALL_PROJECTS, false); + } + } + + private void validate() { + String txt = txtNewName.getText(); + setPageComplete(txt.length() > 0 && !txt.equals(info.getOldName())); + } + + private void initUpdateBundleOption() { + boolean updateRefs = dialogSettings.getBoolean(DS_UPDATE_BUNDLE); + cbUpdateBundle.setSelection(updateRefs); + info.setUpdateProject(updateRefs); + } + + private void initAllProjectsOption() { + boolean allProjects = dialogSettings.getBoolean(DS_ALL_PROJECTS); + cbAllProjects.setSelection(allProjects); + info.setAllProjects(allProjects); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameIdentifierWizard.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameIdentifierWizard.java index d3570f0..ca8bb68 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameIdentifierWizard.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameIdentifierWizard.java @@ -7,33 +7,34 @@ import net.sourceforge.phpdt.ltk.core.RenameIdentifierRefactoring; import org.eclipse.ltk.ui.refactoring.RefactoringWizard; - - -/**

                                                      The wizard that is shown to the user for entering the necessary - * information for property renaming.

                                                      - * - *

                                                      The wizard class is primarily needed for deciding which pages are - * shown to the user. The actual user interface creation goes on the - * pages.

                                                      - * - */ +/** + *

                                                      + * The wizard that is shown to the user for entering the necessary information + * for property renaming. + *

                                                      + * + *

                                                      + * The wizard class is primarily needed for deciding which pages are shown to + * the user. The actual user interface creation goes on the pages. + *

                                                      + * + */ public class RenameIdentifierWizard extends RefactoringWizard { - private final RenameIdentifierInfo info; - - - public RenameIdentifierWizard( final RenameIdentifierRefactoring refactoring, - final RenameIdentifierInfo info ) { - super( refactoring, DIALOG_BASED_USER_INTERFACE ); - this.info = info; - } + private final RenameIdentifierInfo info; + public RenameIdentifierWizard( + final RenameIdentifierRefactoring refactoring, + final RenameIdentifierInfo info) { + super(refactoring, DIALOG_BASED_USER_INTERFACE); + this.info = info; + } - // interface methods of RefactoringWizard - ///////////////////////////////////////// + // interface methods of RefactoringWizard + // /////////////////////////////////////// - protected void addUserInputPages() { - setDefaultPageTitle( getRefactoring().getName() ); - addPage( new RenameLocalVariablePage( info ) ); - } + protected void addUserInputPages() { + setDefaultPageTitle(getRefactoring().getName()); + addPage(new RenameLocalVariablePage(info)); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameLocalVariablePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameLocalVariablePage.java index 3da0b98..ce7987b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameLocalVariablePage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameLocalVariablePage.java @@ -27,18 +27,19 @@ import org.eclipse.swt.widgets.Text; * the input page for the Rename Property refactoring, where users can control * the effects of the refactoring; to be shown in the wizard. *

                                                      - * + * *

                                                      * We let the user enter the new name for the property, and we let her decide * whether other property files in the bundle should be affected, and whether * the operation is supposed to span the entire workspace or only the current * project. *

                                                      - * + * */ public class RenameLocalVariablePage extends UserInputWizardPage { - private static final String DS_KEY = RenameLocalVariablePage.class.getName(); + private static final String DS_KEY = RenameLocalVariablePage.class + .getName(); private static final String DS_RENAME_DQ_STRINGS = "RENAME_DQ_STRINGS"; //$NON-NLS-1$ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameLocalVariableWizard.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameLocalVariableWizard.java index e3ee6da..a4f8941 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameLocalVariableWizard.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameLocalVariableWizard.java @@ -7,30 +7,31 @@ import net.sourceforge.phpdt.ltk.core.RenameIdentifierRefactoring; import org.eclipse.ltk.ui.refactoring.RefactoringWizard; - - -/**

                                                      The wizard that is shown to the user for entering the necessary - * information for property renaming of local PHP variables.

                                                      - * - *

                                                      The wizard class is primarily needed for deciding which pages are - * shown to the user. The actual user interface creation goes on the - * pages.

                                                      - * - */ +/** + *

                                                      + * The wizard that is shown to the user for entering the necessary information + * for property renaming of local PHP variables. + *

                                                      + * + *

                                                      + * The wizard class is primarily needed for deciding which pages are shown to + * the user. The actual user interface creation goes on the pages. + *

                                                      + * + */ public class RenameLocalVariableWizard extends RefactoringWizard { - private final RenameIdentifierInfo info; - - - public RenameLocalVariableWizard( final RenameIdentifierRefactoring refactoring, - final RenameIdentifierInfo info ) { - super( refactoring, DIALOG_BASED_USER_INTERFACE ); - this.info = info; - } + private final RenameIdentifierInfo info; + public RenameLocalVariableWizard( + final RenameIdentifierRefactoring refactoring, + final RenameIdentifierInfo info) { + super(refactoring, DIALOG_BASED_USER_INTERFACE); + this.info = info; + } - protected void addUserInputPages() { - setDefaultPageTitle( getRefactoring().getName() ); - addPage( new RenameLocalVariablePage( info ) ); - } + protected void addUserInputPages() { + setDefaultPageTitle(getRefactoring().getName()); + addPage(new RenameLocalVariablePage(info)); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/CodeGeneration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/CodeGeneration.java index b5f67d3..05dacb0 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/CodeGeneration.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/CodeGeneration.java @@ -17,222 +17,394 @@ import net.sourceforge.phpdt.internal.corext.codemanipulation.StubUtility; import org.eclipse.core.runtime.CoreException; /** - * Class that offers access to the templates contained in the 'code templates' preference page. + * Class that offers access to the templates contained in the 'code templates' + * preference page. * * @since 2.1 */ public class CodeGeneration { - + private CodeGeneration() { } - + /** - * Returns the content for a new compilation unit using the 'new Java file' code template. - * @param cu The compilation to create the source for. The compilation unit does not need to exist. - * @param typeComment The comment for the type to be created. Used when the code template contains a ${typecomment} variable. Can be null if - * no comment should be added. - * @param typeContent The code of the type, including type declaration and body. - * @param lineDelimiter The line delimiter to be used. - * @return Returns the new content or null if the template is undefined or empty. - * @throws CoreException Thrown when the evaluation of the code template fails. + * Returns the content for a new compilation unit using the 'new Java file' + * code template. + * + * @param cu + * The compilation to create the source for. The compilation unit + * does not need to exist. + * @param typeComment + * The comment for the type to be created. Used when the code + * template contains a ${typecomment} variable. Can be + * null if no comment should be added. + * @param typeContent + * The code of the type, including type declaration and body. + * @param lineDelimiter + * The line delimiter to be used. + * @return Returns the new content or null if the template is + * undefined or empty. + * @throws CoreException + * Thrown when the evaluation of the code template fails. */ - public static String getCompilationUnitContent(ICompilationUnit cu, String typeComment, String typeContent, String lineDelimiter) throws CoreException { - return StubUtility.getCompilationUnitContent(cu, typeComment, typeContent, lineDelimiter); + public static String getCompilationUnitContent(ICompilationUnit cu, + String typeComment, String typeContent, String lineDelimiter) + throws CoreException { + return StubUtility.getCompilationUnitContent(cu, typeComment, + typeContent, lineDelimiter); } - + /** - * Returns the content for a new type comment using the 'type comment' code template. The returned content is unformatted and is not indented. - * @param cu The compilation where the type is contained. The compilation unit does not need to exist. - * @param typeQualifiedName The name of the type to which the comment is added. For inner types the name must be qualified and include the outer - * types names (dot separated). See {@link net.sourceforge.phpdt.core.IType#getTypeQualifiedName(char)}. - * @param lineDelimiter The line delimiter to be used. - * @return Returns the new content or null if the code template is undefined or empty. The returned content is unformatted and is not indented. - * @throws CoreException Thrown when the evaluation of the code template fails. - */ - public static String getTypeComment(ICompilationUnit cu, String typeQualifiedName, String lineDelimiter) throws CoreException { + * Returns the content for a new type comment using the 'type comment' code + * template. The returned content is unformatted and is not indented. + * + * @param cu + * The compilation where the type is contained. The compilation + * unit does not need to exist. + * @param typeQualifiedName + * The name of the type to which the comment is added. For inner + * types the name must be qualified and include the outer types + * names (dot separated). See + * {@link net.sourceforge.phpdt.core.IType#getTypeQualifiedName(char)}. + * @param lineDelimiter + * The line delimiter to be used. + * @return Returns the new content or null if the code + * template is undefined or empty. The returned content is + * unformatted and is not indented. + * @throws CoreException + * Thrown when the evaluation of the code template fails. + */ + public static String getTypeComment(ICompilationUnit cu, + String typeQualifiedName, String lineDelimiter) + throws CoreException { return StubUtility.getTypeComment(cu, typeQualifiedName, lineDelimiter); } /** - * Returns the content for a new field comment using the 'field comment' code template. The returned content is unformatted and is not indented. - * @param cu The compilation where the field is contained. The compilation unit does not need to exist. - * @param typeName The name of the field declared type. - * @param fieldName The name of the field to which the comment is added. - * @param lineDelimiter The line delimiter to be used. - * @return Returns the new content or null if the code template is undefined or empty. The returned content is unformatted and is not indented. - * @throws CoreException Thrown when the evaluation of the code template fails. + * Returns the content for a new field comment using the 'field comment' + * code template. The returned content is unformatted and is not indented. + * + * @param cu + * The compilation where the field is contained. The compilation + * unit does not need to exist. + * @param typeName + * The name of the field declared type. + * @param fieldName + * The name of the field to which the comment is added. + * @param lineDelimiter + * The line delimiter to be used. + * @return Returns the new content or null if the code + * template is undefined or empty. The returned content is + * unformatted and is not indented. + * @throws CoreException + * Thrown when the evaluation of the code template fails. * @since 3.0 - */ - public static String getFieldComment(ICompilationUnit cu, String typeName, String fieldName, String lineDelimiter) throws CoreException { - return StubUtility.getFieldComment(cu, typeName, fieldName, lineDelimiter); - } - - /** - * Returns the comment for a method or constructor using the comment code templates (constructor / method / overriding method). - * null is returned if the template is empty. - * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist. - * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer - * types names (dot separated). See {@link net.sourceforge.phpdt.core.IType#getTypeQualifiedName(char)}. - * @param decl The MethodDeclaration AST node that will be added as new - * method. The node does not need to exist in an AST (no parent needed) and does not need to resolve. - * See {@link net.sourceforge.phpdt.core.dom.AST#newMethodDeclaration()} for how to create such a node. - * @param overridden The binding of the method that will be overridden by the created - * method or null if no method is overridden. - * @param lineDelimiter The line delimiter to be used. - * @return Returns the generated method comment or null if the - * code template is empty. The returned content is unformatted and not indented (formatting required). - * @throws CoreException Thrown when the evaluation of the code template fails. */ -// public static String getMethodComment(ICompilationUnit cu, String declaringTypeName, MethodDeclaration decl, IMethodBinding overridden, String lineDelimiter) throws CoreException { -// return StubUtility.getMethodComment(cu, declaringTypeName, decl, overridden, lineDelimiter); -// } + public static String getFieldComment(ICompilationUnit cu, String typeName, + String fieldName, String lineDelimiter) throws CoreException { + return StubUtility.getFieldComment(cu, typeName, fieldName, + lineDelimiter); + } /** - * Returns the comment for a method or constructor using the comment code templates (constructor / method / overriding method). - * null is returned if the template is empty. - *

                                                      The returned string is unformatted and not indented. - *

                                                      Exception types and return type are in signature notation. e.g. a source method declared as public void foo(String text, int length) - * would return the array {"QString;","I"} as parameter types. See {@link net.sourceforge.phpdt.core.Signature}. + * Returns the comment for a method or constructor using the comment code + * templates (constructor / method / overriding method). null + * is returned if the template is empty. + * + * @param cu + * The compilation unit to which the method belongs. The + * compilation unit does not need to exist. + * @param declaringTypeName + * Name of the type to which the method belongs. For inner types + * the name must be qualified and include the outer types names + * (dot separated). See + * {@link net.sourceforge.phpdt.core.IType#getTypeQualifiedName(char)}. + * @param decl + * The MethodDeclaration AST node that will be added as new + * method. The node does not need to exist in an AST (no parent + * needed) and does not need to resolve. See + * {@link net.sourceforge.phpdt.core.dom.AST#newMethodDeclaration()} + * for how to create such a node. + * @param overridden + * The binding of the method that will be overridden by the + * created method or null if no method is + * overridden. + * @param lineDelimiter + * The line delimiter to be used. + * @return Returns the generated method comment or null if + * the code template is empty. The returned content is unformatted + * and not indented (formatting required). + * @throws CoreException + * Thrown when the evaluation of the code template fails. + */ + // public static String getMethodComment(ICompilationUnit cu, String + // declaringTypeName, MethodDeclaration decl, IMethodBinding overridden, + // String lineDelimiter) throws CoreException { + // return StubUtility.getMethodComment(cu, declaringTypeName, decl, + // overridden, lineDelimiter); + // } + /** + * Returns the comment for a method or constructor using the comment code + * templates (constructor / method / overriding method). null + * is returned if the template is empty. + *

                                                      + * The returned string is unformatted and not indented. + *

                                                      + * Exception types and return type are in signature notation. e.g. a source + * method declared as public void foo(String text, int length) + * would return the array {"QString;","I"} as parameter + * types. See {@link net.sourceforge.phpdt.core.Signature}. * - * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist. - * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer - * types names (dot separated). See {@link net.sourceforge.phpdt.core.IType#getTypeQualifiedName(char)}. - * @param methodName Name of the method. - * @param paramNames Names of the parameters for the method. - * @param excTypeSig Thrown exceptions (Signature notation). - * @param retTypeSig Return type (Signature notation) or null - * for constructors. - * @param overridden The method that will be overridden by the created method or - * null for non-overriding methods. If not null, the method must exist. - * @param lineDelimiter The line delimiter to be used. - * @return Returns the constructed comment or null if - * the comment code template is empty. The returned content is unformatted and not indented (formatting required). - * @throws CoreException Thrown when the evaluation of the code template fails. + * @param cu + * The compilation unit to which the method belongs. The + * compilation unit does not need to exist. + * @param declaringTypeName + * Name of the type to which the method belongs. For inner types + * the name must be qualified and include the outer types names + * (dot separated). See + * {@link net.sourceforge.phpdt.core.IType#getTypeQualifiedName(char)}. + * @param methodName + * Name of the method. + * @param paramNames + * Names of the parameters for the method. + * @param excTypeSig + * Thrown exceptions (Signature notation). + * @param retTypeSig + * Return type (Signature notation) or null for + * constructors. + * @param overridden + * The method that will be overridden by the created method or + * null for non-overriding methods. If not + * null, the method must exist. + * @param lineDelimiter + * The line delimiter to be used. + * @return Returns the constructed comment or null if the + * comment code template is empty. The returned content is + * unformatted and not indented (formatting required). + * @throws CoreException + * Thrown when the evaluation of the code template fails. */ - public static String getMethodComment(ICompilationUnit cu, String declaringTypeName, String methodName, String[] paramNames, String[] excTypeSig, String retTypeSig, IMethod overridden, String lineDelimiter) throws CoreException { - return StubUtility.getMethodComment(cu, declaringTypeName, methodName, paramNames, excTypeSig, retTypeSig, overridden, lineDelimiter); + public static String getMethodComment(ICompilationUnit cu, + String declaringTypeName, String methodName, String[] paramNames, + String[] excTypeSig, String retTypeSig, IMethod overridden, + String lineDelimiter) throws CoreException { + return StubUtility.getMethodComment(cu, declaringTypeName, methodName, + paramNames, excTypeSig, retTypeSig, overridden, lineDelimiter); } - + /** - * Returns the comment for a method or constructor using the comment code templates (constructor / method / overriding method). - * null is returned if the template is empty. - *

                                                      The returned string is unformatted and not indented. + * Returns the comment for a method or constructor using the comment code + * templates (constructor / method / overriding method). null + * is returned if the template is empty. + *

                                                      + * The returned string is unformatted and not indented. * - * @param method The method to be documented. The method must exist. - * @param overridden The method that will be overridden by the created method or - * null for non-overriding methods. If not null, the method must exist. - * @param lineDelimiter The line delimiter to be used. - * @return Returns the constructed comment or null if - * the comment code template is empty. The returned string is unformatted and and has no indent (formatting required). - * @throws CoreException Thrown when the evaluation of the code template fails. + * @param method + * The method to be documented. The method must exist. + * @param overridden + * The method that will be overridden by the created method or + * null for non-overriding methods. If not + * null, the method must exist. + * @param lineDelimiter + * The line delimiter to be used. + * @return Returns the constructed comment or null if the + * comment code template is empty. The returned string is + * unformatted and and has no indent (formatting required). + * @throws CoreException + * Thrown when the evaluation of the code template fails. */ - public static String getMethodComment(IMethod method, IMethod overridden, String lineDelimiter) throws CoreException { + public static String getMethodComment(IMethod method, IMethod overridden, + String lineDelimiter) throws CoreException { return StubUtility.getMethodComment(method, overridden, lineDelimiter); - } + } /** - * Returns the content of the body for a method or constructor using the method body templates. - * null is returned if the template is empty. - *

                                                      The returned string is unformatted and not indented. + * Returns the content of the body for a method or constructor using the + * method body templates. null is returned if the template is + * empty. + *

                                                      + * The returned string is unformatted and not indented. * - * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist. - * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer - * types names (dot separated). See {@link net.sourceforge.phpdt.core.IType#getTypeQualifiedName(char)}. - * @param methodName Name of the method. - * @param isConstructor Defines if the created body is for a constructor. - * @param bodyStatement The code to be entered at the place of the variable ${body_statement}. - * @param lineDelimiter The line delimiter to be used. + * @param cu + * The compilation unit to which the method belongs. The + * compilation unit does not need to exist. + * @param declaringTypeName + * Name of the type to which the method belongs. For inner types + * the name must be qualified and include the outer types names + * (dot separated). See + * {@link net.sourceforge.phpdt.core.IType#getTypeQualifiedName(char)}. + * @param methodName + * Name of the method. + * @param isConstructor + * Defines if the created body is for a constructor. + * @param bodyStatement + * The code to be entered at the place of the variable + * ${body_statement}. + * @param lineDelimiter + * The line delimiter to be used. * @return Returns the constructed body content or null if - * the comment code template is empty. The returned string is unformatted and and has no indent (formatting required). - * @throws CoreException Thrown when the evaluation of the code template fails. - */ - public static String getMethodBodyContent(ICompilationUnit cu, String declaringTypeName, String methodName, boolean isConstructor, String bodyStatement, String lineDelimiter) throws CoreException { - return StubUtility.getMethodBodyContent(isConstructor, cu.getJavaProject(), declaringTypeName, methodName, bodyStatement, lineDelimiter); + * the comment code template is empty. The returned string is + * unformatted and and has no indent (formatting required). + * @throws CoreException + * Thrown when the evaluation of the code template fails. + */ + public static String getMethodBodyContent(ICompilationUnit cu, + String declaringTypeName, String methodName, boolean isConstructor, + String bodyStatement, String lineDelimiter) throws CoreException { + return StubUtility.getMethodBodyContent(isConstructor, cu + .getJavaProject(), declaringTypeName, methodName, + bodyStatement, lineDelimiter); } - + /** - * Returns the content of body for a getter method using the getter method body template. - * null is returned if the template is empty. - *

                                                      The returned string is unformatted and not indented. + * Returns the content of body for a getter method using the getter method + * body template. null is returned if the template is empty. + *

                                                      + * The returned string is unformatted and not indented. * - * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist. - * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer - * types names (dot separated). See {@link net.sourceforge.phpdt.core.IType#getTypeQualifiedName(char)}. - * @param methodName The name of the getter method. - * @param fieldName The name of the field to get in the getter method, corresponding to the template variable for ${field}. - * @param lineDelimiter The line delimiter to be used. + * @param cu + * The compilation unit to which the method belongs. The + * compilation unit does not need to exist. + * @param declaringTypeName + * Name of the type to which the method belongs. For inner types + * the name must be qualified and include the outer types names + * (dot separated). See + * {@link net.sourceforge.phpdt.core.IType#getTypeQualifiedName(char)}. + * @param methodName + * The name of the getter method. + * @param fieldName + * The name of the field to get in the getter method, + * corresponding to the template variable for ${field}. + * @param lineDelimiter + * The line delimiter to be used. * @return Returns the constructed body content or null if - * the comment code template is empty. The returned string is unformatted and and has no indent (formatting required). - * @throws CoreException Thrown when the evaluation of the code template fails. + * the comment code template is empty. The returned string is + * unformatted and and has no indent (formatting required). + * @throws CoreException + * Thrown when the evaluation of the code template fails. * @since 3.0 - */ - public static String getGetterMethodBodyContent(ICompilationUnit cu, String declaringTypeName, String methodName, String fieldName, String lineDelimiter) throws CoreException { - return StubUtility.getGetterMethodBodyContent(cu.getJavaProject(), declaringTypeName, methodName, fieldName, lineDelimiter); + */ + public static String getGetterMethodBodyContent(ICompilationUnit cu, + String declaringTypeName, String methodName, String fieldName, + String lineDelimiter) throws CoreException { + return StubUtility.getGetterMethodBodyContent(cu.getJavaProject(), + declaringTypeName, methodName, fieldName, lineDelimiter); } - + /** - * Returns the content of body for a setter method using the setter method body template. - * null is returned if the template is empty. - *

                                                      The returned string is unformatted and not indented. + * Returns the content of body for a setter method using the setter method + * body template. null is returned if the template is empty. + *

                                                      + * The returned string is unformatted and not indented. * - * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist. - * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer - * types names (dot separated). See {@link net.sourceforge.phpdt.core.IType#getTypeQualifiedName(char)}. - * @param methodName The name of the setter method. - * @param fieldName The name of the field to be set in the setter method, corresponding to the template variable for ${field}. - * @param paramName The name of the parameter passed to the setter method, corresponding to the template variable for $(param). - * @param lineDelimiter The line delimiter to be used. + * @param cu + * The compilation unit to which the method belongs. The + * compilation unit does not need to exist. + * @param declaringTypeName + * Name of the type to which the method belongs. For inner types + * the name must be qualified and include the outer types names + * (dot separated). See + * {@link net.sourceforge.phpdt.core.IType#getTypeQualifiedName(char)}. + * @param methodName + * The name of the setter method. + * @param fieldName + * The name of the field to be set in the setter method, + * corresponding to the template variable for ${field}. + * @param paramName + * The name of the parameter passed to the setter method, + * corresponding to the template variable for $(param). + * @param lineDelimiter + * The line delimiter to be used. * @return Returns the constructed body content or null if - * the comment code template is empty. The returned string is unformatted and and has no indent (formatting required). - * @throws CoreException Thrown when the evaluation of the code template fails. + * the comment code template is empty. The returned string is + * unformatted and and has no indent (formatting required). + * @throws CoreException + * Thrown when the evaluation of the code template fails. * @since 3.0 - */ - public static String getSetterMethodBodyContent(ICompilationUnit cu, String declaringTypeName, String methodName, String fieldName, String paramName, String lineDelimiter) throws CoreException { - return StubUtility.getSetterMethodBodyContent(cu.getJavaProject(), declaringTypeName, methodName, fieldName, paramName, lineDelimiter); + */ + public static String getSetterMethodBodyContent(ICompilationUnit cu, + String declaringTypeName, String methodName, String fieldName, + String paramName, String lineDelimiter) throws CoreException { + return StubUtility.getSetterMethodBodyContent(cu.getJavaProject(), + declaringTypeName, methodName, fieldName, paramName, + lineDelimiter); } - + /** - * Returns the comment for a getter method using the getter comment template. - * null is returned if the template is empty. - *

                                                      The returned string is unformatted and not indented. + * Returns the comment for a getter method using the getter comment + * template. null is returned if the template is empty. + *

                                                      + * The returned string is unformatted and not indented. * - * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist. - * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer - * types names (dot separated). See {@link net.sourceforge.phpdt.core.IType#getTypeQualifiedName(char)}. - * @param methodName Name of the method. - * @param fieldName Name of the field to get. - * @param fieldType The type of the field to get. - * @param bareFieldName The field name without prefix or suffix. - * @param lineDelimiter The line delimiter to be used. - * @return Returns the generated getter comment or null if the - * code template is empty. The returned content is not indented. - * @throws CoreException Thrown when the evaluation of the code template fails. + * @param cu + * The compilation unit to which the method belongs. The + * compilation unit does not need to exist. + * @param declaringTypeName + * Name of the type to which the method belongs. For inner types + * the name must be qualified and include the outer types names + * (dot separated). See + * {@link net.sourceforge.phpdt.core.IType#getTypeQualifiedName(char)}. + * @param methodName + * Name of the method. + * @param fieldName + * Name of the field to get. + * @param fieldType + * The type of the field to get. + * @param bareFieldName + * The field name without prefix or suffix. + * @param lineDelimiter + * The line delimiter to be used. + * @return Returns the generated getter comment or null if + * the code template is empty. The returned content is not indented. + * @throws CoreException + * Thrown when the evaluation of the code template fails. * @since 3.0 */ - public static String getGetterComment(ICompilationUnit cu, String declaringTypeName, String methodName, String fieldName, String fieldType, String bareFieldName, String lineDelimiter) throws CoreException { - return StubUtility.getGetterComment(cu, declaringTypeName, methodName, fieldName, fieldType, bareFieldName, lineDelimiter); + public static String getGetterComment(ICompilationUnit cu, + String declaringTypeName, String methodName, String fieldName, + String fieldType, String bareFieldName, String lineDelimiter) + throws CoreException { + return StubUtility.getGetterComment(cu, declaringTypeName, methodName, + fieldName, fieldType, bareFieldName, lineDelimiter); } - + /** - * Returns the comment for a setter method using the setter method body template. - * null is returned if the template is empty. - *

                                                      The returned string is unformatted and not indented. + * Returns the comment for a setter method using the setter method body + * template. null is returned if the template is empty. + *

                                                      + * The returned string is unformatted and not indented. * - * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist. - * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer - * types names (dot separated). See {@link net.sourceforge.phpdt.core.IType#getTypeQualifiedName(char)}. - * @param methodName Name of the method. - * @param fieldName Name of the field that is set. - * @param fieldType The type of the field that is to set. - * @param paramName The name of the parameter that used to set. - * @param bareFieldName The field name without prefix or suffix. - * @param lineDelimiter The line delimiter to be used. - * @return Returns the generated setter comment or null if the - * code template is empty. The returned comment is not indented. - * @throws CoreException Thrown when the evaluation of the code template fails. + * @param cu + * The compilation unit to which the method belongs. The + * compilation unit does not need to exist. + * @param declaringTypeName + * Name of the type to which the method belongs. For inner types + * the name must be qualified and include the outer types names + * (dot separated). See + * {@link net.sourceforge.phpdt.core.IType#getTypeQualifiedName(char)}. + * @param methodName + * Name of the method. + * @param fieldName + * Name of the field that is set. + * @param fieldType + * The type of the field that is to set. + * @param paramName + * The name of the parameter that used to set. + * @param bareFieldName + * The field name without prefix or suffix. + * @param lineDelimiter + * The line delimiter to be used. + * @return Returns the generated setter comment or null if + * the code template is empty. The returned comment is not indented. + * @throws CoreException + * Thrown when the evaluation of the code template fails. * @since 3.0 */ - public static String getSetterComment(ICompilationUnit cu, String declaringTypeName, String methodName, String fieldName, String fieldType, String paramName, String bareFieldName, String lineDelimiter) throws CoreException { - return StubUtility.getSetterComment(cu, declaringTypeName, methodName, fieldName, fieldType, paramName, bareFieldName, lineDelimiter); - } + public static String getSetterComment(ICompilationUnit cu, + String declaringTypeName, String methodName, String fieldName, + String fieldType, String paramName, String bareFieldName, + String lineDelimiter) throws CoreException { + return StubUtility.getSetterComment(cu, declaringTypeName, methodName, + fieldName, fieldType, paramName, bareFieldName, lineDelimiter); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IContextMenuConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IContextMenuConstants.java index 9b9164f..40fcd3c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IContextMenuConstants.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IContextMenuConstants.java @@ -19,31 +19,36 @@ import org.eclipse.ui.IWorkbenchActionConstants; *

                                                      */ public interface IContextMenuConstants { - - + /** * Type hierarchy view part: pop-up menu target ID for type hierarchy viewer - * (value "net.sourceforge.phpdt.ui.TypeHierarchy.typehierarchy"). + * (value + * "net.sourceforge.phpdt.ui.TypeHierarchy.typehierarchy"). * * @since 2.0 */ - public static final String TARGET_ID_HIERARCHY_VIEW= JavaUI.ID_TYPE_HIERARCHY + ".typehierarchy"; //$NON-NLS-1$ + public static final String TARGET_ID_HIERARCHY_VIEW = JavaUI.ID_TYPE_HIERARCHY + + ".typehierarchy"; //$NON-NLS-1$ /** - * Type hierarchy view part: pop-up menu target ID for supertype hierarchy viewer - * (value "net.sourceforge.phpdt.ui.TypeHierarchy.supertypes"). + * Type hierarchy view part: pop-up menu target ID for supertype hierarchy + * viewer (value + * "net.sourceforge.phpdt.ui.TypeHierarchy.supertypes"). * * @since 2.0 */ - public static final String TARGET_ID_SUPERTYPES_VIEW= JavaUI.ID_TYPE_HIERARCHY + ".supertypes"; //$NON-NLS-1$ + public static final String TARGET_ID_SUPERTYPES_VIEW = JavaUI.ID_TYPE_HIERARCHY + + ".supertypes"; //$NON-NLS-1$ /** - * Type hierarchy view part: Pop-up menu target ID for the subtype hierarchy viewer - * (value "net.sourceforge.phpdt.ui.TypeHierarchy.subtypes"). + * Type hierarchy view part: Pop-up menu target ID for the subtype hierarchy + * viewer (value + * "net.sourceforge.phpdt.ui.TypeHierarchy.subtypes"). * * @since 2.0 */ - public static final String TARGET_ID_SUBTYPES_VIEW= JavaUI.ID_TYPE_HIERARCHY + ".subtypes"; //$NON-NLS-1$ + public static final String TARGET_ID_SUBTYPES_VIEW = JavaUI.ID_TYPE_HIERARCHY + + ".subtypes"; //$NON-NLS-1$ /** * Type hierarchy view part: pop-up menu target ID for the meber viewer @@ -51,98 +56,109 @@ public interface IContextMenuConstants { * * @since 2.0 */ - public static final String TARGET_ID_MEMBERS_VIEW= JavaUI.ID_TYPE_HIERARCHY + ".members"; //$NON-NLS-1$ - + public static final String TARGET_ID_MEMBERS_VIEW = JavaUI.ID_TYPE_HIERARCHY + + ".members"; //$NON-NLS-1$ /** - * Pop-up menu: name of group for goto actions (value "group.open"). + * Pop-up menu: name of group for goto actions (value + * "group.open"). *

                                                      * Examples for open actions are: *

                                                        - *
                                                      • Go Into
                                                      • - *
                                                      • Go To
                                                      • + *
                                                      • Go Into
                                                      • + *
                                                      • Go To
                                                      • *
                                                      *

                                                      */ - public static final String GROUP_GOTO= "group.goto"; //$NON-NLS-1$ + public static final String GROUP_GOTO = "group.goto"; //$NON-NLS-1$ + /** - * Pop-up menu: name of group for open actions (value "group.open"). + * Pop-up menu: name of group for open actions (value + * "group.open"). *

                                                      * Examples for open actions are: *

                                                        - *
                                                      • Open To
                                                      • - *
                                                      • Open With
                                                      • + *
                                                      • Open To
                                                      • + *
                                                      • Open With
                                                      • *
                                                      *

                                                      */ - public static final String GROUP_OPEN= "group.open"; //$NON-NLS-1$ - + public static final String GROUP_OPEN = "group.open"; //$NON-NLS-1$ + /** - * Pop-up menu: name of group for show actions (value "group.show"). + * Pop-up menu: name of group for show actions (value + * "group.show"). *

                                                      * Examples for show actions are: *

                                                        - *
                                                      • Show in Navigator
                                                      • - *
                                                      • Show in Type Hierarchy
                                                      • + *
                                                      • Show in Navigator
                                                      • + *
                                                      • Show in Type Hierarchy
                                                      • *
                                                      *

                                                      */ - public static final String GROUP_SHOW= "group.show"; //$NON-NLS-1$ - + public static final String GROUP_SHOW = "group.show"; //$NON-NLS-1$ + /** - * Pop-up menu: name of group for new actions (value "group.new"). + * Pop-up menu: name of group for new actions (value + * "group.new"). *

                                                      * Examples for new actions are: *

                                                        - *
                                                      • Create new class
                                                      • - *
                                                      • Create new interface
                                                      • + *
                                                      • Create new class
                                                      • + *
                                                      • Create new interface
                                                      • *
                                                      *

                                                      */ - public static final String GROUP_NEW= "group.new"; //$NON-NLS-1$ + public static final String GROUP_NEW = "group.new"; //$NON-NLS-1$ /** - * Pop-up menu: name of group for build actions (value "group.build"). + * Pop-up menu: name of group for build actions (value + * "group.build"). */ - public static final String GROUP_BUILD= "group.build"; //$NON-NLS-1$ - + public static final String GROUP_BUILD = "group.build"; //$NON-NLS-1$ + /** - * Pop-up menu: name of group for reorganize actions (value "group.reorganize"). - */ - public static final String GROUP_REORGANIZE= IWorkbenchActionConstants.GROUP_REORGANIZE; - + * Pop-up menu: name of group for reorganize actions (value + * "group.reorganize"). + */ + public static final String GROUP_REORGANIZE = IWorkbenchActionConstants.GROUP_REORGANIZE; + /** - * Pop-up menu: name of group for code generation actions ( - * value "group.generate"). - */ - public static final String GROUP_GENERATE= "group.generate"; //$NON-NLS-1$ + * Pop-up menu: name of group for code generation actions ( value + * "group.generate"). + */ + public static final String GROUP_GENERATE = "group.generate"; //$NON-NLS-1$ /** * Pop-up menu: name of group for source actions. This is an alias for - * GROUP_GENERATE to be more consistent with main menu - * bar structure. + * GROUP_GENERATE to be more consistent with main menu bar + * structure. * * @since 2.0 - */ - public static final String GROUP_SOURCE= GROUP_GENERATE; + */ + public static final String GROUP_SOURCE = GROUP_GENERATE; /** - * Pop-up menu: name of group for search actions (value "group.search"). - */ - public static final String GROUP_SEARCH= "group.search"; //$NON-NLS-1$ - + * Pop-up menu: name of group for search actions (value + * "group.search"). + */ + public static final String GROUP_SEARCH = "group.search"; //$NON-NLS-1$ + /** - * Pop-up menu: name of group for additional actions (value "additions"). - */ - public static final String GROUP_ADDITIONS= "additions"; //$NON-NLS-1$ + * Pop-up menu: name of group for additional actions (value + * "additions"). + */ + public static final String GROUP_ADDITIONS = "additions"; //$NON-NLS-1$ /** - * Pop-up menu: name of group for viewer setup actions (value "group.viewerSetup"). - */ - public static final String GROUP_VIEWER_SETUP= "group.viewerSetup"; //$NON-NLS-1$ + * Pop-up menu: name of group for viewer setup actions (value + * "group.viewerSetup"). + */ + public static final String GROUP_VIEWER_SETUP = "group.viewerSetup"; //$NON-NLS-1$ /** - * Pop-up menu: name of group for properties actions (value "group.properties"). - */ - public static final String GROUP_PROPERTIES= "group.properties"; //$NON-NLS-1$ + * Pop-up menu: name of group for properties actions (value + * "group.properties"). + */ + public static final String GROUP_PROPERTIES = "group.properties"; //$NON-NLS-1$ } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IJavaElementSearchConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IJavaElementSearchConstants.java index 705fe7c..699d33e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IJavaElementSearchConstants.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IJavaElementSearchConstants.java @@ -15,48 +15,49 @@ package net.sourceforge.phpdt.ui; *

                                                      * This interface declares constants only; it is not intended to be implemented. *

                                                      - * + * * @see JavaUI */ public interface IJavaElementSearchConstants { - /** - * Search scope constant (bit mask) indicating that classes should be considered. - * Used when opening certain kinds of selection dialogs. + /** + * Search scope constant (bit mask) indicating that classes should be + * considered. Used when opening certain kinds of selection dialogs. */ - public static final int CONSIDER_CLASSES= 1 << 1; + public static final int CONSIDER_CLASSES = 1 << 1; - /** - * Search scope constant (bit mask) indicating that interfaces should be considered. - * Used when opening certain kinds of selection dialogs. + /** + * Search scope constant (bit mask) indicating that interfaces should be + * considered. Used when opening certain kinds of selection dialogs. */ - public static final int CONSIDER_INTERFACES= 1 << 2; + public static final int CONSIDER_INTERFACES = 1 << 2; /** - * Search scope constant (bit mask) indicating that both classes and interfaces - * should be considered. Equivalent to + * Search scope constant (bit mask) indicating that both classes and + * interfaces should be considered. Equivalent to * CONSIDER_CLASSES | CONSIDER_INTERFACES. */ - public static final int CONSIDER_TYPES= CONSIDER_CLASSES | CONSIDER_INTERFACES; + public static final int CONSIDER_TYPES = CONSIDER_CLASSES + | CONSIDER_INTERFACES; /** - * Search scope constant (bit mask) indicating that binaries should be considered. - * Used when opening certain kinds of selection dialogs. + * Search scope constant (bit mask) indicating that binaries should be + * considered. Used when opening certain kinds of selection dialogs. */ - public static final int CONSIDER_BINARIES= 1 << 3; + public static final int CONSIDER_BINARIES = 1 << 3; /** - * Search scope constant (bit mask) indicating that external JARs should be considered. - * Used when opening certain kinds of selection dialogs. + * Search scope constant (bit mask) indicating that external JARs should be + * considered. Used when opening certain kinds of selection dialogs. */ - public static final int CONSIDER_EXTERNAL_JARS= 1 << 4; + public static final int CONSIDER_EXTERNAL_JARS = 1 << 4; /** - * Search scope constant (bit mask) indicating that required projects should be considered. - * Used when opening certain kinds of selection dialogs. + * Search scope constant (bit mask) indicating that required projects should + * be considered. Used when opening certain kinds of selection dialogs. * * @since 2.0 - */ - public static final int CONSIDER_REQUIRED_PROJECTS= 1 << 5; + */ + public static final int CONSIDER_REQUIRED_PROJECTS = 1 << 5; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IPackagesViewPart.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IPackagesViewPart.java index 392ea8d..5bb16f4 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IPackagesViewPart.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IPackagesViewPart.java @@ -16,23 +16,24 @@ import org.eclipse.ui.IViewPart; /** * The standard Packages view presents a Java-centric view of the workspace. * Within Java projects, the resource hierarchy is organized into Java packages - * as described by the project's classpath. Note that this view shows both Java + * as described by the project's classpath. Note that this view shows both Java * elements and ordinary resources. *

                                                      * This interface is not intended to be implemented by clients. *

                                                      - * + * * @see JavaUI#ID_PACKAGES */ public interface IPackagesViewPart extends IViewPart { /** - * Selects and reveals the given element in this packages view. - * The tree will be expanded as needed to show the element. - * - * @param element the element to be revealed + * Selects and reveals the given element in this packages view. The tree + * will be expanded as needed to show the element. + * + * @param element + * the element to be revealed */ void selectAndReveal(Object element); - + /** * Returns the TreeViewer shown in the Packages view. * diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/ITypeHierarchyViewPart.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/ITypeHierarchyViewPart.java index d8a0837..950238d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/ITypeHierarchyViewPart.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/ITypeHierarchyViewPart.java @@ -10,62 +10,66 @@ *******************************************************************************/ package net.sourceforge.phpdt.ui; - import net.sourceforge.phpdt.core.IJavaElement; import net.sourceforge.phpdt.core.IType; import org.eclipse.ui.IViewPart; /** - * The standard type hierarchy view presents a type hierarchy for a given input class - * or interface. Visually, this view consists of a pair of viewers, one showing the type - * hierarchy, the other showing the members of the type selected in the first. + * The standard type hierarchy view presents a type hierarchy for a given input + * class or interface. Visually, this view consists of a pair of viewers, one + * showing the type hierarchy, the other showing the members of the type + * selected in the first. *

                                                      * This interface is not intended to be implemented by clients. *

                                                      - * + * * @see JavaUI#ID_TYPE_HIERARCHY */ public interface ITypeHierarchyViewPart extends IViewPart { /** * Sets the input element of this type hierarchy view to a type. - * - * @param type the input element of this type hierarchy view, or null - * to clear any input element + * + * @param type + * the input element of this type hierarchy view, or + * null to clear any input element * @deprecated use setInputElement instead */ public void setInput(IType type); - + /** - * Sets the input element of this type hierarchy view. The following input types are possible - * IMember (types, methods, fields..), IPackageFragment, IPackageFragmentRoot - * and IJavaProject. - * - * @param element the input element of this type hierarchy view, or null - * to clear any input + * Sets the input element of this type hierarchy view. The following input + * types are possible IMember (types, methods, fields..), + * IPackageFragment, IPackageFragmentRoot and + * IJavaProject. + * + * @param element + * the input element of this type hierarchy view, or + * null to clear any input * * @since 2.0 */ - public void setInputElement(IJavaElement element); + public void setInputElement(IJavaElement element); /** * Returns the input element of this type hierarchy view. - * - * @return the input element, or null if no input element is set + * + * @return the input element, or null if no input element is + * set * @see #setInput(IType) * @deprecated use getInputElement instead */ public IType getInput(); - /** * Returns the input element of this type hierarchy view. - * - * @return the input element, or null if no input element is set + * + * @return the input element, or null if no input element is + * set * @see #setInputElement(IJavaElement) * * @since 2.0 */ - public IJavaElement getInputElement(); + public IJavaElement getInputElement(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyManager.java index c5538bc..e0be2c6 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyManager.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyManager.java @@ -17,57 +17,62 @@ import org.eclipse.ui.IEditorInput; /** * Interface for accessing working copies of ICompilationUnit - * objects. The original compilation unit is only given indirectly by means - * of an IEditorInput. The life cycle is as follows: + * objects. The original compilation unit is only given indirectly by means of + * an IEditorInput. The life cycle is as follows: *
                                                        - *
                                                      • connect creates and remembers a working copy of the - * compilation unit which is encoded in the given editor input
                                                      • - *
                                                      • getWorkingCopy returns the working copy remembered on - * connect
                                                      • - *
                                                      • disconnect destroys the working copy remembered on - * connect
                                                      • + *
                                                      • connect creates and remembers a working copy of the + * compilation unit which is encoded in the given editor input
                                                      • + *
                                                      • getWorkingCopy returns the working copy remembered on + * connect
                                                      • + *
                                                      • disconnect destroys the working copy remembered on + * connect
                                                      • *
                                                      *

                                                      * This interface is not intended to be implemented by clients. *

                                                      - * + * * @see JavaUI#getWorkingCopyManager */ public interface IWorkingCopyManager { - + /** - * Connects the given editor input to this manager. After calling - * this method, a working copy will be available for the compilation unit encoded - * in the given editor input (does nothing if there is no encoded compilation unit). - * - * @param input the editor input - * @exception CoreException if the working copy cannot be created for the - * compilation unit + * Connects the given editor input to this manager. After calling this + * method, a working copy will be available for the compilation unit encoded + * in the given editor input (does nothing if there is no encoded + * compilation unit). + * + * @param input + * the editor input + * @exception CoreException + * if the working copy cannot be created for the compilation + * unit */ void connect(IEditorInput input) throws CoreException; - + /** - * Disconnects the given editor input from this manager. After calling - * this method, a working copy for the compilation unit encoded - * in the given editor input will no longer be available. Does nothing if there - * is no encoded compilation unit, or if there is no remembered working copy for + * Disconnects the given editor input from this manager. After calling this + * method, a working copy for the compilation unit encoded in the given + * editor input will no longer be available. Does nothing if there is no + * encoded compilation unit, or if there is no remembered working copy for * the compilation unit. * - * @param input the editor input + * @param input + * the editor input */ void disconnect(IEditorInput input); - + /** - * Returns the working copy remembered for the compilation unit encoded in the - * given editor input. - * - * @param input the editor input - * @return the working copy of the compilation unit, or null if the - * input does not encode an editor input, or if there is no remembered working - * copy for this compilation unit + * Returns the working copy remembered for the compilation unit encoded in + * the given editor input. + * + * @param input + * the editor input + * @return the working copy of the compilation unit, or null + * if the input does not encode an editor input, or if there is no + * remembered working copy for this compilation unit */ ICompilationUnit getWorkingCopy(IEditorInput input); - + /** * Shuts down this working copy manager. All working copies still remembered * by this manager are destroyed. diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyManagerExtension.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyManagerExtension.java index 3bca478..1e354a9 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyManagerExtension.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyManagerExtension.java @@ -17,27 +17,34 @@ import org.eclipse.ui.IEditorInput; /** * Extension interface for IWorkingCopyManager. + * * @since 2.1 */ public interface IWorkingCopyManagerExtension { - + /** - * Sets the given working copy for the given editor input. If the given editor input - * is not connected to this working copy manager, this call has no effect.

                                                      - * This working copy manager does not assume the ownership of this working copy, i.e., - * the given working copy is not automatically be freed when this manager is shut down. + * Sets the given working copy for the given editor input. If the given + * editor input is not connected to this working copy manager, this call has + * no effect. + *

                                                      + * This working copy manager does not assume the ownership of this working + * copy, i.e., the given working copy is not automatically be freed when + * this manager is shut down. * - * @param input the editor input - * @param workingCopy the working copy + * @param input + * the editor input + * @param workingCopy + * the working copy */ void setWorkingCopy(IEditorInput input, ICompilationUnit workingCopy); - + /** * Removes the working copy set for the given editor input. If there is no * working copy set for this input or this input is not connected to this * working copy manager, this call has no effect. * - * @param input the editor input + * @param input + * the editor input */ void removeWorkingCopy(IEditorInput input); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyProvider.java index 585cfc9..7f0a3e0 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyProvider.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyProvider.java @@ -11,24 +11,24 @@ package net.sourceforge.phpdt.ui; /** - * Interface used for Java element content providers to indicate that - * the content provider can return working copy elements for members - * below compilation units. + * Interface used for Java element content providers to indicate that the + * content provider can return working copy elements for members below + * compilation units. * *

                                                      * This interface is not intended to be implemented by clients. *

                                                      - * + * * @see net.sourceforge.phpdt.ui.StandardJavaElementContentProvider * @see net.sourceforge.phpdt.core.IWorkingCopy * - * @since 2.0 + * @since 2.0 */ public interface IWorkingCopyProvider { - + /** - * Returns true if the content provider returns working - * copy elements; otherwise false is returned. + * Returns true if the content provider returns working copy + * elements; otherwise false is returned. * * @return whether working copy elements are provided. */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementImageDescriptor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementImageDescriptor.java index c34e2bc..e008eff 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementImageDescriptor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementImageDescriptor.java @@ -10,7 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpdt.ui; - import net.sourceforge.phpdt.internal.ui.PHPUiImages; import org.eclipse.jface.resource.CompositeImageDescriptor; @@ -20,81 +19,89 @@ import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.Point; /** - * A JavaImageDescriptor consists of a base image and several adornments. The adornments - * are computed according to the flags either passed during creation or set via the method - * setAdornments. + * A JavaImageDescriptor consists of a base image and several adornments. The + * adornments are computed according to the flags either passed during creation + * or set via the method setAdornments. * *

                                                      * This class may be instantiated; it is not intended to be subclassed. *

                                                      - * - * @since 2.0 + * + * @since 2.0 */ public class JavaElementImageDescriptor extends CompositeImageDescriptor { - + /** Flag to render the abstract adornment */ - public final static int ABSTRACT= 0x001; - + public final static int ABSTRACT = 0x001; + /** Flag to render the final adornment */ - public final static int FINAL= 0x002; - + public final static int FINAL = 0x002; + /** Flag to render the synchronized adornment */ - public final static int SYNCHRONIZED= 0x004; - + public final static int SYNCHRONIZED = 0x004; + /** Flag to render the static adornment */ - public final static int STATIC= 0x008; - + public final static int STATIC = 0x008; + /** Flag to render the runnable adornment */ - public final static int RUNNABLE= 0x010; - + public final static int RUNNABLE = 0x010; + /** Flag to render the waring adornment */ - public final static int WARNING= 0x020; - + public final static int WARNING = 0x020; + /** Flag to render the error adornment */ - public final static int ERROR= 0x040; - + public final static int ERROR = 0x040; + /** Flag to render the 'override' adornment */ - public final static int OVERRIDES= 0x080; - + public final static int OVERRIDES = 0x080; + /** Flag to render the 'implements' adornment */ - public final static int IMPLEMENTS= 0x100; - + public final static int IMPLEMENTS = 0x100; + /** Flag to render the 'constructor' adornment */ - public final static int CONSTRUCTOR= 0x200; + public final static int CONSTRUCTOR = 0x200; private ImageDescriptor fBaseImage; + private int fFlags; + private Point fSize; /** * Creates a new JavaElementImageDescriptor. * - * @param baseImage an image descriptor used as the base image - * @param flags flags indicating which adornments are to be rendered. See setAdornments - * for valid values. - * @param size the size of the resulting image + * @param baseImage + * an image descriptor used as the base image + * @param flags + * flags indicating which adornments are to be rendered. See + * setAdornments for valid values. + * @param size + * the size of the resulting image * @see #setAdornments(int) */ - public JavaElementImageDescriptor(ImageDescriptor baseImage, int flags, Point size) { - fBaseImage= baseImage; + public JavaElementImageDescriptor(ImageDescriptor baseImage, int flags, + Point size) { + fBaseImage = baseImage; Assert.isNotNull(fBaseImage); - fFlags= flags; + fFlags = flags; Assert.isTrue(fFlags >= 0); - fSize= size; + fSize = size; Assert.isNotNull(fSize); } - + /** - * Sets the descriptors adornments. Valid values are: ABSTRACT, FINAL, - * SYNCHRONIZED, STATIC, RUNNABLE, WARNING, - * ERROR, OVERRIDDES, IMPLEMENTS, CONSTRUCTOR, - * or any combination of those. + * Sets the descriptors adornments. Valid values are: ABSTRACT, + * FINAL, SYNCHRONIZED, STATIC, + * RUNNABLE, WARNING, ERROR, + * OVERRIDDES, IMPLEMENTS, + * CONSTRUCTOR, or any combination of those. * - * @param adornments the image descritpors adornments + * @param adornments + * the image descritpors adornments */ public void setAdornments(int adornments) { Assert.isTrue(adornments >= 0); - fFlags= adornments; + fFlags = adornments; } /** @@ -109,128 +116,134 @@ public class JavaElementImageDescriptor extends CompositeImageDescriptor { /** * Sets the size of the image created by calling createImage(). * - * @param size the size of the image returned from calling createImage() + * @param size + * the size of the image returned from calling + * createImage() * @see ImageDescriptor#createImage() */ public void setImageSize(Point size) { Assert.isNotNull(size); Assert.isTrue(size.x >= 0 && size.y >= 0); - fSize= size; + fSize = size; } - + /** - * Returns the size of the image created by calling createImage(). + * Returns the size of the image created by calling + * createImage(). * - * @return the size of the image created by calling createImage() + * @return the size of the image created by calling + * createImage() * @see ImageDescriptor#createImage() */ public Point getImageSize() { return new Point(fSize.x, fSize.y); } - - /* (non-Javadoc) - * Method declared in CompositeImageDescriptor + + /* + * (non-Javadoc) Method declared in CompositeImageDescriptor */ protected Point getSize() { return fSize; } - - /* (non-Javadoc) - * Method declared on Object. + + /* + * (non-Javadoc) Method declared on Object. */ public boolean equals(Object object) { - if (object == null || !JavaElementImageDescriptor.class.equals(object.getClass())) + if (object == null + || !JavaElementImageDescriptor.class.equals(object.getClass())) return false; - - JavaElementImageDescriptor other= (JavaElementImageDescriptor)object; - return (fBaseImage.equals(other.fBaseImage) && fFlags == other.fFlags && fSize.equals(other.fSize)); + + JavaElementImageDescriptor other = (JavaElementImageDescriptor) object; + return (fBaseImage.equals(other.fBaseImage) && fFlags == other.fFlags && fSize + .equals(other.fSize)); } - - /* (non-Javadoc) - * Method declared on Object. + + /* + * (non-Javadoc) Method declared on Object. */ public int hashCode() { return fBaseImage.hashCode() | fFlags | fSize.hashCode(); } - - /* (non-Javadoc) - * Method declared in CompositeImageDescriptor + + /* + * (non-Javadoc) Method declared in CompositeImageDescriptor */ protected void drawCompositeImage(int width, int height) { ImageData bg; - if ((bg= fBaseImage.getImageData()) == null) - bg= DEFAULT_IMAGE_DATA; - + if ((bg = fBaseImage.getImageData()) == null) + bg = DEFAULT_IMAGE_DATA; + drawImage(bg, 0, 0); drawTopRight(); drawBottomRight(); drawBottomLeft(); - } - - private void drawTopRight() { - int x= getSize().x; - ImageData data= null; + } + + private void drawTopRight() { + int x = getSize().x; + ImageData data = null; if ((fFlags & ABSTRACT) != 0) { - data= PHPUiImages.DESC_OVR_ABSTRACT.getImageData(); - x-= data.width; + data = PHPUiImages.DESC_OVR_ABSTRACT.getImageData(); + x -= data.width; drawImage(data, x, 0); } if ((fFlags & CONSTRUCTOR) != 0) { - data= PHPUiImages.DESC_OVR_CONSTRUCTOR.getImageData(); - x-= data.width; + data = PHPUiImages.DESC_OVR_CONSTRUCTOR.getImageData(); + x -= data.width; drawImage(data, x, 0); } if ((fFlags & FINAL) != 0) { - data= PHPUiImages.DESC_OVR_FINAL.getImageData(); - x-= data.width; + data = PHPUiImages.DESC_OVR_FINAL.getImageData(); + x -= data.width; drawImage(data, x, 0); } if ((fFlags & STATIC) != 0) { - data= PHPUiImages.DESC_OVR_STATIC.getImageData(); - x-= data.width; + data = PHPUiImages.DESC_OVR_STATIC.getImageData(); + x -= data.width; drawImage(data, x, 0); } - } - + } + private void drawBottomRight() { - Point size= getSize(); - int x= size.x; - ImageData data= null; + Point size = getSize(); + int x = size.x; + ImageData data = null; if ((fFlags & OVERRIDES) != 0) { - data= PHPUiImages.DESC_OVR_OVERRIDES.getImageData(); - x-= data.width; + data = PHPUiImages.DESC_OVR_OVERRIDES.getImageData(); + x -= data.width; drawImage(data, x, size.y - data.height); } if ((fFlags & IMPLEMENTS) != 0) { - data= PHPUiImages.DESC_OVR_IMPLEMENTS.getImageData(); - x-= data.width; + data = PHPUiImages.DESC_OVR_IMPLEMENTS.getImageData(); + x -= data.width; drawImage(data, x, size.y - data.height); - } + } if ((fFlags & SYNCHRONIZED) != 0) { - data= PHPUiImages.DESC_OVR_SYNCH.getImageData(); - x-= data.width; + data = PHPUiImages.DESC_OVR_SYNCH.getImageData(); + x -= data.width; drawImage(data, x, size.y - data.height); } if ((fFlags & RUNNABLE) != 0) { - data= PHPUiImages.DESC_OVR_RUN.getImageData(); - x-= data.width; + data = PHPUiImages.DESC_OVR_RUN.getImageData(); + x -= data.width; drawImage(data, x, size.y - data.height); } - } - + } + private void drawBottomLeft() { - Point size= getSize(); - int x= 0; - ImageData data= null; + Point size = getSize(); + int x = 0; + ImageData data = null; if ((fFlags & ERROR) != 0) { - data= PHPUiImages.DESC_OVR_ERROR.getImageData(); + data = PHPUiImages.DESC_OVR_ERROR.getImageData(); drawImage(data, x, size.y - data.height); - x+= data.width; + x += data.width; } if ((fFlags & WARNING) != 0) { - data= PHPUiImages.DESC_OVR_WARNING.getImageData(); + data = PHPUiImages.DESC_OVR_WARNING.getImageData(); drawImage(data, x, size.y - data.height); - x+= data.width; + x += data.width; } - } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementLabelProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementLabelProvider.java index 4067228..44eb464 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementLabelProvider.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementLabelProvider.java @@ -18,124 +18,130 @@ import org.eclipse.core.resources.IStorage; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.graphics.Image; - - /** - * Standard label provider for Java elements. - * Use this class when you want to present the Java elements in a viewer. + * Standard label provider for Java elements. Use this class when you want to + * present the Java elements in a viewer. *

                                                      - * The implementation also handles non-Java elements by forwarding the requests to the - * IWorkbenchAdapter of the element. + * The implementation also handles non-Java elements by forwarding the requests + * to the IWorkbenchAdapter of the element. *

                                                      *

                                                      * This class may be instantiated; it is not intended to be subclassed. *

                                                      */ public class JavaElementLabelProvider extends LabelProvider { - + /** - * Flag (bit mask) indicating that methods labels include the method return type. (appended) + * Flag (bit mask) indicating that methods labels include the method return + * type. (appended) */ - public final static int SHOW_RETURN_TYPE= 0x001; - + public final static int SHOW_RETURN_TYPE = 0x001; + /** - * Flag (bit mask) indicating that method label include method parameter types. + * Flag (bit mask) indicating that method label include method parameter + * types. */ - public final static int SHOW_PARAMETERS= 0x002; - + public final static int SHOW_PARAMETERS = 0x002; + /** - * Flag (bit mask) indicating that the label of a member should include the container. - * For example, include the name of the type enclosing a field. + * Flag (bit mask) indicating that the label of a member should include the + * container. For example, include the name of the type enclosing a field. + * * @deprecated Use SHOW_QUALIFIED or SHOW_ROOT instead */ - public final static int SHOW_CONTAINER= 0x004; + public final static int SHOW_CONTAINER = 0x004; /** - * Flag (bit mask) indicating that the label of a type should be fully qualified. - * For example, include the fully qualified name of the type enclosing a type. + * Flag (bit mask) indicating that the label of a type should be fully + * qualified. For example, include the fully qualified name of the type + * enclosing a type. + * * @deprecated Use SHOW_QUALIFIED instead */ - public final static int SHOW_CONTAINER_QUALIFICATION= 0x008; + public final static int SHOW_CONTAINER_QUALIFICATION = 0x008; /** * Flag (bit mask) indicating that the label should include overlay icons * for element type and modifiers. */ - public final static int SHOW_OVERLAY_ICONS= 0x010; + public final static int SHOW_OVERLAY_ICONS = 0x010; /** - * Flag (bit mask) indicating thata field label should include the declared type. + * Flag (bit mask) indicating thata field label should include the declared + * type. */ - public final static int SHOW_TYPE= 0x020; + public final static int SHOW_TYPE = 0x020; /** * Flag (bit mask) indicating that the label should include the name of the * package fragment root (appended). */ - public final static int SHOW_ROOT= 0x040; - + public final static int SHOW_ROOT = 0x040; + /** * Flag (bit mask) indicating that the label qualification of a type should * be shown after the name. + * * @deprecated SHOW_POST_QUALIFIED instead */ - public final static int SHOW_POSTIFIX_QUALIFICATION= 0x080; + public final static int SHOW_POSTIFIX_QUALIFICATION = 0x080; /** - * Flag (bit mask) indicating that the label should show the icons with no space - * reserved for overlays. + * Flag (bit mask) indicating that the label should show the icons with no + * space reserved for overlays. */ - public final static int SHOW_SMALL_ICONS= 0x100; - + public final static int SHOW_SMALL_ICONS = 0x100; + /** - * Flag (bit mask) indicating that the packagefragment roots from variables should - * be rendered with the variable in the name + * Flag (bit mask) indicating that the packagefragment roots from variables + * should be rendered with the variable in the name */ - public final static int SHOW_VARIABLE= 0x200; - + public final static int SHOW_VARIABLE = 0x200; + /** - * Flag (bit mask) indicating that Complation Units, Class Files, Types, Declarations and Members - * should be rendered qualified. - * Examples: java.lang.String, java.util.Vector.size() + * Flag (bit mask) indicating that Complation Units, Class Files, Types, + * Declarations and Members should be rendered qualified. Examples: + * java.lang.String, java.util.Vector.size() * * @since 2.0 */ - public final static int SHOW_QUALIFIED= 0x400; + public final static int SHOW_QUALIFIED = 0x400; /** - * Flag (bit mask) indicating that Complation Units, Class Files, Types, Declarations and Members - * should be rendered qualified. The qualifcation is appended - * Examples: String - java.lang, size() - java.util.Vector + * Flag (bit mask) indicating that Complation Units, Class Files, Types, + * Declarations and Members should be rendered qualified. The qualifcation + * is appended Examples: String - java.lang, size() - java.util.Vector * * @since 2.0 */ - public final static int SHOW_POST_QUALIFIED= 0x800; - - + public final static int SHOW_POST_QUALIFIED = 0x800; + /** - * Constant (value 0) indicating that the label should show + * Constant (value 0) indicating that the label should show * the basic images only. */ - public final static int SHOW_BASICS= 0x000; - - + public final static int SHOW_BASICS = 0x000; + /** - * Constant indicating the default label rendering. - * Currently the default is equivalent to - * SHOW_PARAMETERS | SHOW_OVERLAY_ICONS. + * Constant indicating the default label rendering. Currently the default is + * equivalent to SHOW_PARAMETERS | SHOW_OVERLAY_ICONS. */ - public final static int SHOW_DEFAULT= new Integer(SHOW_PARAMETERS | SHOW_OVERLAY_ICONS).intValue(); + public final static int SHOW_DEFAULT = new Integer(SHOW_PARAMETERS + | SHOW_OVERLAY_ICONS).intValue(); private JavaElementImageProvider fImageLabelProvider; - + private StorageLabelProvider fStorageLabelProvider; + private int fFlags; + private int fImageFlags; + private int fTextFlags; - + /** * Creates a new label provider with SHOW_DEFAULT flag. - * + * * @see #SHOW_DEFAULT * @since 2.0 */ @@ -145,108 +151,132 @@ public class JavaElementLabelProvider extends LabelProvider { /** * Creates a new label provider. - * - * @param flags the initial options; a bitwise OR of SHOW_* constants + * + * @param flags + * the initial options; a bitwise OR of SHOW_* + * constants */ public JavaElementLabelProvider(int flags) { - fImageLabelProvider= new JavaElementImageProvider(); - fStorageLabelProvider= new StorageLabelProvider(); - fFlags= flags; + fImageLabelProvider = new JavaElementImageProvider(); + fStorageLabelProvider = new StorageLabelProvider(); + fFlags = flags; updateImageProviderFlags(); - updateTextProviderFlags(); + updateTextProviderFlags(); } - - private boolean getFlag( int flag) { + + private boolean getFlag(int flag) { return (fFlags & flag) != 0; } - + /** * Turns on the rendering options specified in the given flags. - * - * @param flags the options; a bitwise OR of SHOW_* constants + * + * @param flags + * the options; a bitwise OR of SHOW_* constants */ public void turnOn(int flags) { fFlags |= flags; updateImageProviderFlags(); updateTextProviderFlags(); } - + /** * Turns off the rendering options specified in the given flags. - * - * @param flags the initial options; a bitwise OR of SHOW_* constants + * + * @param flags + * the initial options; a bitwise OR of SHOW_* + * constants */ public void turnOff(int flags) { fFlags &= (~flags); updateImageProviderFlags(); updateTextProviderFlags(); } - + private void updateImageProviderFlags() { - fImageFlags= 0; + fImageFlags = 0; if (getFlag(SHOW_OVERLAY_ICONS)) { fImageFlags |= JavaElementImageProvider.OVERLAY_ICONS; } if (getFlag(SHOW_SMALL_ICONS)) { fImageFlags |= JavaElementImageProvider.SMALL_ICONS; } - } - + } + private void updateTextProviderFlags() { - fTextFlags= 0; + fTextFlags = 0; if (getFlag(SHOW_RETURN_TYPE)) { fTextFlags |= JavaElementLabels.M_APP_RETURNTYPE; } if (getFlag(SHOW_PARAMETERS)) { fTextFlags |= JavaElementLabels.M_PARAMETER_TYPES; - } + } if (getFlag(SHOW_CONTAINER)) { - fTextFlags |= JavaElementLabels.P_POST_QUALIFIED | JavaElementLabels.T_POST_QUALIFIED | JavaElementLabels.CF_POST_QUALIFIED | JavaElementLabels.CU_POST_QUALIFIED | JavaElementLabels.M_POST_QUALIFIED | JavaElementLabels.F_POST_QUALIFIED; + fTextFlags |= JavaElementLabels.P_POST_QUALIFIED + | JavaElementLabels.T_POST_QUALIFIED + | JavaElementLabels.CF_POST_QUALIFIED + | JavaElementLabels.CU_POST_QUALIFIED + | JavaElementLabels.M_POST_QUALIFIED + | JavaElementLabels.F_POST_QUALIFIED; } if (getFlag(SHOW_POSTIFIX_QUALIFICATION)) { - fTextFlags |= (JavaElementLabels.T_POST_QUALIFIED | JavaElementLabels.CF_POST_QUALIFIED | JavaElementLabels.CU_POST_QUALIFIED); + fTextFlags |= (JavaElementLabels.T_POST_QUALIFIED + | JavaElementLabels.CF_POST_QUALIFIED | JavaElementLabels.CU_POST_QUALIFIED); } else if (getFlag(SHOW_CONTAINER_QUALIFICATION)) { - fTextFlags |=(JavaElementLabels.T_FULLY_QUALIFIED | JavaElementLabels.CF_QUALIFIED | JavaElementLabels.CU_QUALIFIED); + fTextFlags |= (JavaElementLabels.T_FULLY_QUALIFIED + | JavaElementLabels.CF_QUALIFIED | JavaElementLabels.CU_QUALIFIED); } if (getFlag(SHOW_TYPE)) { fTextFlags |= JavaElementLabels.F_APP_TYPE_SIGNATURE; } if (getFlag(SHOW_ROOT)) { fTextFlags |= JavaElementLabels.APPEND_ROOT_PATH; - } + } if (getFlag(SHOW_VARIABLE)) { fTextFlags |= JavaElementLabels.ROOT_VARIABLE; } if (getFlag(SHOW_QUALIFIED)) { - fTextFlags |= (JavaElementLabels.F_FULLY_QUALIFIED | JavaElementLabels.M_FULLY_QUALIFIED | JavaElementLabels.I_FULLY_QUALIFIED - | JavaElementLabels.T_FULLY_QUALIFIED | JavaElementLabels.D_QUALIFIED | JavaElementLabels.CF_QUALIFIED | JavaElementLabels.CU_QUALIFIED); + fTextFlags |= (JavaElementLabels.F_FULLY_QUALIFIED + | JavaElementLabels.M_FULLY_QUALIFIED + | JavaElementLabels.I_FULLY_QUALIFIED + | JavaElementLabels.T_FULLY_QUALIFIED + | JavaElementLabels.D_QUALIFIED + | JavaElementLabels.CF_QUALIFIED | JavaElementLabels.CU_QUALIFIED); } if (getFlag(SHOW_POST_QUALIFIED)) { - fTextFlags |= (JavaElementLabels.F_POST_QUALIFIED | JavaElementLabels.M_POST_QUALIFIED | JavaElementLabels.I_POST_QUALIFIED - | JavaElementLabels.T_POST_QUALIFIED | JavaElementLabels.D_POST_QUALIFIED | JavaElementLabels.CF_POST_QUALIFIED | JavaElementLabels.CU_POST_QUALIFIED); - } + fTextFlags |= (JavaElementLabels.F_POST_QUALIFIED + | JavaElementLabels.M_POST_QUALIFIED + | JavaElementLabels.I_POST_QUALIFIED + | JavaElementLabels.T_POST_QUALIFIED + | JavaElementLabels.D_POST_QUALIFIED + | JavaElementLabels.CF_POST_QUALIFIED | JavaElementLabels.CU_POST_QUALIFIED); + } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see ILabelProvider#getImage */ public Image getImage(Object element) { - Image result= fImageLabelProvider.getImageLabel(element, fImageFlags); + Image result = fImageLabelProvider.getImageLabel(element, fImageFlags); if (result != null) { return result; } - if (element instanceof IStorage) + if (element instanceof IStorage) return fStorageLabelProvider.getImage(element); return result; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see ILabelProvider#getText */ public String getText(Object element) { - String text= JavaElementLabels.getTextLabel(element, fTextFlags); + String text = JavaElementLabels.getTextLabel(element, fTextFlags); if (text.length() > 0) { return text; } @@ -257,7 +287,8 @@ public class JavaElementLabelProvider extends LabelProvider { return text; } - /* (non-Javadoc) + /* + * (non-Javadoc) * * @see IBaseLabelProvider#dispose */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementSorter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementSorter.java index ce6061d..dd2e04f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementSorter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementSorter.java @@ -40,9 +40,8 @@ import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.ui.model.IWorkbenchAdapter; - /** - * Sorter for Java elements. Ordered by element category, then by element name. + * Sorter for Java elements. Ordered by element category, then by element name. * Package fragment roots are sorted as ordered on the classpath. * *

                                                      @@ -52,43 +51,53 @@ import org.eclipse.ui.model.IWorkbenchAdapter; * @since 2.0 */ public class JavaElementSorter extends ViewerSorter { - - private static final int PROJECTS= 1; - private static final int PACKAGEFRAGMENTROOTS= 2; - private static final int PACKAGEFRAGMENT= 3; - - private static final int COMPILATIONUNITS= 4; - private static final int CLASSFILES= 5; - - private static final int RESOURCEFOLDERS= 7; - private static final int RESOURCES= 8; - private static final int STORAGE= 9; - - private static final int PACKAGE_DECL= 10; - private static final int IMPORT_CONTAINER= 11; - private static final int IMPORT_DECLARATION= 12; - + + private static final int PROJECTS = 1; + + private static final int PACKAGEFRAGMENTROOTS = 2; + + private static final int PACKAGEFRAGMENT = 3; + + private static final int COMPILATIONUNITS = 4; + + private static final int CLASSFILES = 5; + + private static final int RESOURCEFOLDERS = 7; + + private static final int RESOURCES = 8; + + private static final int STORAGE = 9; + + private static final int PACKAGE_DECL = 10; + + private static final int IMPORT_CONTAINER = 11; + + private static final int IMPORT_DECLARATION = 12; + // Includes all categories ordered using the OutlineSortOrderPage: // types, initializers, methods & fields - private static final int MEMBERSOFFSET= 15; - - private static final int JAVAELEMENTS= 50; - private static final int OTHERS= 51; - + private static final int MEMBERSOFFSET = 15; + + private static final int JAVAELEMENTS = 50; + + private static final int OTHERS = 51; + private MembersOrderPreferenceCache fMemberOrderCache; - + /** * Constructor. */ - public JavaElementSorter() { + public JavaElementSorter() { super(null); // delay initialization of collator - fMemberOrderCache= PHPeclipsePlugin.getDefault().getMemberOrderPreferenceCache(); + fMemberOrderCache = PHPeclipsePlugin.getDefault() + .getMemberOrderPreferenceCache(); } - + /** - * @deprecated Bug 22518. Method never used: does not override ViewerSorter#isSorterProperty(Object, String). - * Method could be removed, but kept for API compatibility. - */ + * @deprecated Bug 22518. Method never used: does not override + * ViewerSorter#isSorterProperty(Object, String). Method could + * be removed, but kept for API compatibility. + */ public boolean isSorterProperty(Object element, Object property) { return true; } @@ -99,64 +108,64 @@ public class JavaElementSorter extends ViewerSorter { public int category(Object element) { if (element instanceof IJavaElement) { try { - IJavaElement je= (IJavaElement) element; + IJavaElement je = (IJavaElement) element; switch (je.getElementType()) { - case IJavaElement.METHOD: - { - IMethod method= (IMethod) je; - if (method.isConstructor()) { - return getMemberCategory(MembersOrderPreferenceCache.CONSTRUCTORS_INDEX); - } - int flags= method.getFlags(); - if (Flags.isStatic(flags)) - return getMemberCategory(MembersOrderPreferenceCache.STATIC_METHODS_INDEX); - else - return getMemberCategory(MembersOrderPreferenceCache.METHOD_INDEX); - } - case IJavaElement.FIELD : - { - int flags= ((IField) je).getFlags(); - if (Flags.isStatic(flags)) - return getMemberCategory(MembersOrderPreferenceCache.STATIC_FIELDS_INDEX); - else - return getMemberCategory(MembersOrderPreferenceCache.FIELDS_INDEX); - } -// case IJavaElement.INITIALIZER : -// { -// int flags= ((IInitializer) je).getFlags(); -// if (Flags.isStatic(flags)) -// return getMemberCategory(MembersOrderPreferenceCache.STATIC_INIT_INDEX); -// else -// return getMemberCategory(MembersOrderPreferenceCache.INIT_INDEX); -// } - case IJavaElement.TYPE : - return getMemberCategory(MembersOrderPreferenceCache.TYPE_INDEX); - case IJavaElement.PACKAGE_DECLARATION : - return PACKAGE_DECL; - case IJavaElement.IMPORT_CONTAINER : - return IMPORT_CONTAINER; - case IJavaElement.IMPORT_DECLARATION : - return IMPORT_DECLARATION; - case IJavaElement.PACKAGE_FRAGMENT : - IPackageFragment pack= (IPackageFragment) je; - if (pack.getParent().getResource() instanceof IProject) { - return PACKAGEFRAGMENTROOTS; - } - return PACKAGEFRAGMENT; - case IJavaElement.PACKAGE_FRAGMENT_ROOT : + case IJavaElement.METHOD: { + IMethod method = (IMethod) je; + if (method.isConstructor()) { + return getMemberCategory(MembersOrderPreferenceCache.CONSTRUCTORS_INDEX); + } + int flags = method.getFlags(); + if (Flags.isStatic(flags)) + return getMemberCategory(MembersOrderPreferenceCache.STATIC_METHODS_INDEX); + else + return getMemberCategory(MembersOrderPreferenceCache.METHOD_INDEX); + } + case IJavaElement.FIELD: { + int flags = ((IField) je).getFlags(); + if (Flags.isStatic(flags)) + return getMemberCategory(MembersOrderPreferenceCache.STATIC_FIELDS_INDEX); + else + return getMemberCategory(MembersOrderPreferenceCache.FIELDS_INDEX); + } + // case IJavaElement.INITIALIZER : + // { + // int flags= ((IInitializer) je).getFlags(); + // if (Flags.isStatic(flags)) + // return + // getMemberCategory(MembersOrderPreferenceCache.STATIC_INIT_INDEX); + // else + // return + // getMemberCategory(MembersOrderPreferenceCache.INIT_INDEX); + // } + case IJavaElement.TYPE: + return getMemberCategory(MembersOrderPreferenceCache.TYPE_INDEX); + case IJavaElement.PACKAGE_DECLARATION: + return PACKAGE_DECL; + case IJavaElement.IMPORT_CONTAINER: + return IMPORT_CONTAINER; + case IJavaElement.IMPORT_DECLARATION: + return IMPORT_DECLARATION; + case IJavaElement.PACKAGE_FRAGMENT: + IPackageFragment pack = (IPackageFragment) je; + if (pack.getParent().getResource() instanceof IProject) { return PACKAGEFRAGMENTROOTS; - case IJavaElement.JAVA_PROJECT : - return PROJECTS; - case IJavaElement.CLASS_FILE : - return CLASSFILES; - case IJavaElement.COMPILATION_UNIT : - return COMPILATIONUNITS; + } + return PACKAGEFRAGMENT; + case IJavaElement.PACKAGE_FRAGMENT_ROOT: + return PACKAGEFRAGMENTROOTS; + case IJavaElement.JAVA_PROJECT: + return PROJECTS; + case IJavaElement.CLASS_FILE: + return CLASSFILES; + case IJavaElement.COMPILATION_UNIT: + return COMPILATIONUNITS; } } catch (JavaModelException e) { if (!e.isDoesNotExist()) - PHPeclipsePlugin.log(e); + PHPeclipsePlugin.log(e); } return JAVAELEMENTS; } else if (element instanceof IFile) { @@ -167,37 +176,39 @@ public class JavaElementSorter extends ViewerSorter { return RESOURCEFOLDERS; } else if (element instanceof IStorage) { return STORAGE; - } -// else if (element instanceof ClassPathContainer) { -// return PACKAGEFRAGMENTROOTS; -// } + } + // else if (element instanceof ClassPathContainer) { + // return PACKAGEFRAGMENTROOTS; + // } return OTHERS; } - + private int getMemberCategory(int kind) { - int offset= fMemberOrderCache.getCategoryIndex(kind); + int offset = fMemberOrderCache.getCategoryIndex(kind); return offset + MEMBERSOFFSET; } - + /* * @see ViewerSorter#compare */ public int compare(Viewer viewer, Object e1, Object e2) { - int cat1= category(e1); - int cat2= category(e2); + int cat1 = category(e1); + int cat2 = category(e2); if (cat1 != cat2) return cat1 - cat2; - + if (cat1 == PROJECTS) { - IWorkbenchAdapter a1= (IWorkbenchAdapter)((IAdaptable)e1).getAdapter(IWorkbenchAdapter.class); - IWorkbenchAdapter a2= (IWorkbenchAdapter)((IAdaptable)e2).getAdapter(IWorkbenchAdapter.class); - return getCollator().compare(a1.getLabel(e1), a2.getLabel(e2)); + IWorkbenchAdapter a1 = (IWorkbenchAdapter) ((IAdaptable) e1) + .getAdapter(IWorkbenchAdapter.class); + IWorkbenchAdapter a2 = (IWorkbenchAdapter) ((IAdaptable) e2) + .getAdapter(IWorkbenchAdapter.class); + return getCollator().compare(a1.getLabel(e1), a2.getLabel(e2)); } - + if (cat1 == PACKAGEFRAGMENTROOTS) { - IPackageFragmentRoot root1= getPackageFragmentRoot(e1); - IPackageFragmentRoot root2= getPackageFragmentRoot(e2); + IPackageFragmentRoot root1 = getPackageFragmentRoot(e1); + IPackageFragmentRoot root2 = getPackageFragmentRoot(e2); if (root1 == null) { if (root2 == null) { return 0; @@ -206,28 +217,31 @@ public class JavaElementSorter extends ViewerSorter { } } else if (root2 == null) { return -1; - } + } if (!root1.getPath().equals(root2.getPath())) { - int p1= getClassPathIndex(root1); - int p2= getClassPathIndex(root2); + int p1 = getClassPathIndex(root1); + int p2 = getClassPathIndex(root2); if (p1 != p2) { return p1 - p2; } } - e1= root1; // normalize classpath container to root - e2= root2; + e1 = root1; // normalize classpath container to root + e2 = root2; } - // non - java resources are sorted using the label from the viewers label provider - if (cat1 == PROJECTS || cat1 == RESOURCES || cat1 == RESOURCEFOLDERS || cat1 == STORAGE || cat1 == OTHERS) { + // non - java resources are sorted using the label from the viewers + // label provider + if (cat1 == PROJECTS || cat1 == RESOURCES || cat1 == RESOURCEFOLDERS + || cat1 == STORAGE || cat1 == OTHERS) { return compareWithLabelProvider(viewer, e1, e2); } - + if (e1 instanceof IMember) { if (fMemberOrderCache.isSortByVisibility()) { try { - int flags1= JdtFlags.getVisibilityCode((IMember) e1); - int flags2= JdtFlags.getVisibilityCode((IMember) e2); - int vis= fMemberOrderCache.getVisibilityIndex(flags1) - fMemberOrderCache.getVisibilityIndex(flags2); + int flags1 = JdtFlags.getVisibilityCode((IMember) e1); + int flags2 = JdtFlags.getVisibilityCode((IMember) e2); + int vis = fMemberOrderCache.getVisibilityIndex(flags1) + - fMemberOrderCache.getVisibilityIndex(flags2); if (vis != 0) { return vis; } @@ -235,15 +249,17 @@ public class JavaElementSorter extends ViewerSorter { } } } - - String name1= ((IJavaElement) e1).getElementName(); - String name2= ((IJavaElement) e2).getElementName(); - + + String name1 = ((IJavaElement) e1).getElementName(); + String name2 = ((IJavaElement) e2).getElementName(); + if (e1 instanceof IType) { // handle anonymous types if (name1.length() == 0) { if (name2.length() == 0) { try { - return getCollator().compare(((IType) e1).getSuperclassName(), ((IType) e2).getSuperclassName()); + return getCollator().compare( + ((IType) e1).getSuperclassName(), + ((IType) e2).getSuperclassName()); } catch (JavaModelException e) { return 0; } @@ -254,18 +270,19 @@ public class JavaElementSorter extends ViewerSorter { return -1; } } - - int cmp= getCollator().compare(name1, name2); + + int cmp = getCollator().compare(name1, name2); if (cmp != 0) { return cmp; } - + if (e1 instanceof IMethod) { - String[] params1= ((IMethod) e1).getParameterTypes(); - String[] params2= ((IMethod) e2).getParameterTypes(); - int len= Math.min(params1.length, params2.length); + String[] params1 = ((IMethod) e1).getParameterTypes(); + String[] params2 = ((IMethod) e2).getParameterTypes(); + int len = Math.min(params1.length, params2.length); for (int i = 0; i < len; i++) { - cmp= getCollator().compare(Signature.toString(params1[i]), Signature.toString(params2[i])); + cmp = getCollator().compare(Signature.toString(params1[i]), + Signature.toString(params2[i])); if (cmp != 0) { return cmp; } @@ -274,26 +291,26 @@ public class JavaElementSorter extends ViewerSorter { } return 0; } - private IPackageFragmentRoot getPackageFragmentRoot(Object element) { -// if (element instanceof ClassPathContainer) { -// // return first package fragment root from the container -// ClassPathContainer cp= (ClassPathContainer)element; -// Object[] roots= cp.getPackageFragmentRoots(); -// if (roots.length > 0) -// return (IPackageFragmentRoot)roots[0]; -// // non resolvable - return null -// return null; -// } - return JavaModelUtil.getPackageFragmentRoot((IJavaElement)element); + // if (element instanceof ClassPathContainer) { + // // return first package fragment root from the container + // ClassPathContainer cp= (ClassPathContainer)element; + // Object[] roots= cp.getPackageFragmentRoots(); + // if (roots.length > 0) + // return (IPackageFragmentRoot)roots[0]; + // // non resolvable - return null + // return null; + // } + return JavaModelUtil.getPackageFragmentRoot((IJavaElement) element); } - + private int compareWithLabelProvider(Viewer viewer, Object e1, Object e2) { if (viewer == null || !(viewer instanceof ContentViewer)) { - IBaseLabelProvider prov = ((ContentViewer) viewer).getLabelProvider(); + IBaseLabelProvider prov = ((ContentViewer) viewer) + .getLabelProvider(); if (prov instanceof ILabelProvider) { - ILabelProvider lprov= (ILabelProvider) prov; + ILabelProvider lprov = (ILabelProvider) prov; String name1 = lprov.getText(e1); String name2 = lprov.getText(e2); if (name1 != null && name2 != null) { @@ -303,12 +320,13 @@ public class JavaElementSorter extends ViewerSorter { } return 0; // can't compare } - + private int getClassPathIndex(IPackageFragmentRoot root) { try { - IPath rootPath= root.getPath(); - IPackageFragmentRoot[] roots= root.getJavaProject().getPackageFragmentRoots(); - for (int i= 0; i < roots.length; i++) { + IPath rootPath = root.getPath(); + IPackageFragmentRoot[] roots = root.getJavaProject() + .getPackageFragmentRoots(); + for (int i = 0; i < roots.length; i++) { if (roots[i].getPath().equals(rootPath)) { return i; } @@ -318,13 +336,15 @@ public class JavaElementSorter extends ViewerSorter { return Integer.MAX_VALUE; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.eclipse.jface.viewers.ViewerSorter#getCollator() */ public final Collator getCollator() { if (collator == null) { - collator= Collator.getInstance(); + collator = Collator.getInstance(); } return collator; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaUI.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaUI.java index 9d306a6..4f37f42 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaUI.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaUI.java @@ -25,12 +25,13 @@ import org.eclipse.ui.internal.SharedImages; import org.eclipse.ui.texteditor.IDocumentProvider; /** - * Central access point for the Java UI plug-in (id "net.sourceforge.phpdt.ui"). - * This class provides static methods for: + * Central access point for the Java UI plug-in (id + * "net.sourceforge.phpdt.ui"). This class provides static + * methods for: *

                                                        - *
                                                      • creating various kinds of selection dialogs to present a collection - * of Java elements to the user and let them make a selection.
                                                      • - *
                                                      • opening a Java editor on a compilation unit.
                                                      • + *
                                                      • creating various kinds of selection dialogs to present a collection of + * Java elements to the user and let them make a selection.
                                                      • + *
                                                      • opening a Java editor on a compilation unit.
                                                      • *
                                                      *

                                                      * This class provides static methods and fields only; it is not intended to be @@ -38,515 +39,610 @@ import org.eclipse.ui.texteditor.IDocumentProvider; *

                                                      */ public final class JavaUI { - - private static ISharedImages fgSharedImages= null; - + + private static ISharedImages fgSharedImages = null; + private JavaUI() { // prevent instantiation of JavaUI. } - + /** * The id of the Java plugin (value "net.sourceforge.phpdt.ui"). - */ -// public static final String ID_PLUGIN= "net.sourceforge.phpdt.ui"; //$NON-NLS-1$ - - /** - * The id of the Java perspective - * (value "net.sourceforge.phpdt.ui.JavaPerspective"). - */ - // public static final String ID_PERSPECTIVE= "net.sourceforge.phpdt.ui.JavaPerspective"; //$NON-NLS-1$ - - /** - * The id of the Java hierarchy perspective - * (value "net.sourceforge.phpdt.ui.JavaHierarchyPerspective"). - */ -// public static final String ID_HIERARCHYPERSPECTIVE= "net.sourceforge.phpdt.ui.JavaHierarchyPerspective"; //$NON-NLS-1$ - + */ + // public static final String ID_PLUGIN= "net.sourceforge.phpdt.ui"; + // //$NON-NLS-1$ /** - * The id of the Java action set - * (value "net.sourceforge.phpdt.ui.JavaActionSet"). + * The id of the Java perspective (value + * "net.sourceforge.phpdt.ui.JavaPerspective"). */ -// public static final String ID_ACTION_SET= "net.sourceforge.phpdt.ui.JavaActionSet"; //$NON-NLS-1$ - + // public static final String ID_PERSPECTIVE= + // "net.sourceforge.phpdt.ui.JavaPerspective"; //$NON-NLS-1$ + /** + * The id of the Java hierarchy perspective (value + * "net.sourceforge.phpdt.ui.JavaHierarchyPerspective"). + */ + // public static final String ID_HIERARCHYPERSPECTIVE= + // "net.sourceforge.phpdt.ui.JavaHierarchyPerspective"; //$NON-NLS-1$ /** - * The id of the Java Element Creation action set - * (value "net.sourceforge.phpdt.ui.JavaElementCreationActionSet"). + * The id of the Java action set (value + * "net.sourceforge.phpdt.ui.JavaActionSet"). + */ + // public static final String ID_ACTION_SET= + // "net.sourceforge.phpdt.ui.JavaActionSet"; //$NON-NLS-1$ + /** + * The id of the Java Element Creation action set (value + * "net.sourceforge.phpdt.ui.JavaElementCreationActionSet"). * * @since 2.0 */ -// public static final String ID_ELEMENT_CREATION_ACTION_SET= "net.sourceforge.phpdt.ui.JavaElementCreationActionSet"; //$NON-NLS-1$ - + // public static final String ID_ELEMENT_CREATION_ACTION_SET= + // "net.sourceforge.phpdt.ui.JavaElementCreationActionSet"; //$NON-NLS-1$ /** - * The id of the Java Coding action set - * (value "net.sourceforge.phpdt.ui.CodingActionSet"). + * The id of the Java Coding action set (value + * "net.sourceforge.phpdt.ui.CodingActionSet"). * * @since 2.0 */ -// public static final String ID_CODING_ACTION_SET= "net.sourceforge.phpdt.ui.CodingActionSet"; //$NON-NLS-1$ - + // public static final String ID_CODING_ACTION_SET= + // "net.sourceforge.phpdt.ui.CodingActionSet"; //$NON-NLS-1$ /** - * The id of the Java action set for open actions - * (value "net.sourceforge.phpdt.ui.A_OpenActionSet"). + * The id of the Java action set for open actions (value + * "net.sourceforge.phpdt.ui.A_OpenActionSet"). * * @since 2.0 */ -// public static final String ID_OPEN_ACTION_SET= "net.sourceforge.phpdt.ui.A_OpenActionSet"; //$NON-NLS-1$ - + // public static final String ID_OPEN_ACTION_SET= + // "net.sourceforge.phpdt.ui.A_OpenActionSet"; //$NON-NLS-1$ /** - * The id of the Java Search action set - * (value net.sourceforge.phpdt.ui.SearchActionSet"). + * The id of the Java Search action set (value + * net.sourceforge.phpdt.ui.SearchActionSet"). * * @since 2.0 */ -// public static final String ID_SEARCH_ACTION_SET= "net.sourceforge.phpdt.ui.SearchActionSet"; //$NON-NLS-1$ - + // public static final String ID_SEARCH_ACTION_SET= + // "net.sourceforge.phpdt.ui.SearchActionSet"; //$NON-NLS-1$ /** * The editor part id of the editor that presents Java compilation units * (value "net.sourceforge.phpdt.ui.CompilationUnitEditor"). - */ -// public static final String ID_CU_EDITOR= "net.sourceforge.phpdt.ui.PHPUnitEditor"; //$NON-NLS-1$ - + */ + // public static final String ID_CU_EDITOR= + // "net.sourceforge.phpdt.ui.PHPUnitEditor"; //$NON-NLS-1$ /** * The editor part id of the editor that presents Java binary class files * (value "net.sourceforge.phpdt.ui.ClassFileEditor"). */ -// public static final String ID_CF_EDITOR= "net.sourceforge.phpdt.ui.ClassFileEditor"; //$NON-NLS-1$ - + // public static final String ID_CF_EDITOR= + // "net.sourceforge.phpdt.ui.ClassFileEditor"; //$NON-NLS-1$ /** - * The editor part id of the code snippet editor - * (value "net.sourceforge.phpdt.ui.SnippetEditor"). + * The editor part id of the code snippet editor (value + * "net.sourceforge.phpdt.ui.SnippetEditor"). */ -// public static final String ID_SNIPPET_EDITOR= "net.sourceforge.phpdt.ui.SnippetEditor"; //$NON-NLS-1$ - + // public static final String ID_SNIPPET_EDITOR= + // "net.sourceforge.phpdt.ui.SnippetEditor"; //$NON-NLS-1$ /** - * The view part id of the Packages view - * (value "net.sourceforge.phpdt.ui.PackageExplorer"). + * The view part id of the Packages view (value + * "net.sourceforge.phpdt.ui.PackageExplorer"). *

                                                      - * When this id is used to access - * a view part with IWorkbenchPage.findView or - * showView, the returned IViewPart - * can be safely cast to an IPackagesViewPart. + * When this id is used to access a view part with + * IWorkbenchPage.findView or showView, the + * returned IViewPart can be safely cast to an + * IPackagesViewPart. *

                                                      - * + * * @see IPackagesViewPart * @see org.eclipse.ui.IWorkbenchPage#findView(java.lang.String) * @see org.eclipse.ui.IWorkbenchPage#showView(java.lang.String) - */ - public static final String ID_PACKAGES= "net.sourceforge.phpdt.ui.PackageExplorer"; //$NON-NLS-1$ - - /** - * The view part id of the type hierarchy part. - * (value "net.sourceforge.phpdt.ui.TypeHierarchy"). + */ + public static final String ID_PACKAGES = "net.sourceforge.phpdt.ui.PackageExplorer"; //$NON-NLS-1$ + + /** + * The view part id of the type hierarchy part. (value + * "net.sourceforge.phpdt.ui.TypeHierarchy"). *

                                                      - * When this id is used to access - * a view part with IWorkbenchPage.findView or - * showView, the returned IViewPart - * can be safely cast to an ITypeHierarchyViewPart. + * When this id is used to access a view part with + * IWorkbenchPage.findView or showView, the + * returned IViewPart can be safely cast to an + * ITypeHierarchyViewPart. *

                                                      - * + * * @see ITypeHierarchyViewPart * @see org.eclipse.ui.IWorkbenchPage#findView(java.lang.String) * @see org.eclipse.ui.IWorkbenchPage#showView(java.lang.String) - */ - public static final String ID_TYPE_HIERARCHY= "net.sourceforge.phpdt.ui.TypeHierarchy"; //$NON-NLS-1$ + */ + public static final String ID_TYPE_HIERARCHY = "net.sourceforge.phpdt.ui.TypeHierarchy"; //$NON-NLS-1$ /** - * The id of the Java Browsing Perspective - * (value "net.sourceforge.phpdt.ui.JavaBrowsingPerspective"). + * The id of the Java Browsing Perspective (value + * "net.sourceforge.phpdt.ui.JavaBrowsingPerspective"). * * @since 2.0 */ -// public static String ID_BROWSING_PERSPECTIVE= "net.sourceforge.phpdt.ui.JavaBrowsingPerspective"; //$NON-NLS-1$ - + // public static String ID_BROWSING_PERSPECTIVE= + // "net.sourceforge.phpdt.ui.JavaBrowsingPerspective"; //$NON-NLS-1$ /** - * The view part id of the Java Browsing Projects view - * (value "net.sourceforge.phpdt.ui.ProjectsView"). + * The view part id of the Java Browsing Projects view (value + * "net.sourceforge.phpdt.ui.ProjectsView"). * * @since 2.0 */ -// public static String ID_PROJECTS_VIEW= "net.sourceforge.phpdt.ui.ProjectsView"; //$NON-NLS-1$ - + // public static String ID_PROJECTS_VIEW= + // "net.sourceforge.phpdt.ui.ProjectsView"; //$NON-NLS-1$ /** - * The view part id of the Java Browsing Packages view - * (value "net.sourceforge.phpdt.ui.PackagesView"). + * The view part id of the Java Browsing Packages view (value + * "net.sourceforge.phpdt.ui.PackagesView"). * * @since 2.0 */ -// public static String ID_PACKAGES_VIEW= "net.sourceforge.phpdt.ui.PackagesView"; //$NON-NLS-1$ - + // public static String ID_PACKAGES_VIEW= + // "net.sourceforge.phpdt.ui.PackagesView"; //$NON-NLS-1$ /** - * The view part id of the Java Browsing Types view - * (value "net.sourceforge.phpdt.ui.TypesView"). + * The view part id of the Java Browsing Types view (value + * "net.sourceforge.phpdt.ui.TypesView"). * * @since 2.0 */ -// public static String ID_TYPES_VIEW= "net.sourceforge.phpdt.ui.TypesView"; //$NON-NLS-1$ - + // public static String ID_TYPES_VIEW= "net.sourceforge.phpdt.ui.TypesView"; + // //$NON-NLS-1$ /** - * The view part id of the Java Browsing Members view - * (value "net.sourceforge.phpdt.ui.MembersView"). + * The view part id of the Java Browsing Members view (value + * "net.sourceforge.phpdt.ui.MembersView"). * * @since 2.0 */ -// public static String ID_MEMBERS_VIEW= "net.sourceforge.phpdt.ui.MembersView"; //$NON-NLS-1$ - + // public static String ID_MEMBERS_VIEW= + // "net.sourceforge.phpdt.ui.MembersView"; //$NON-NLS-1$ /** - * The class org.eclipse.debug.core.model.IProcess allows attaching - * String properties to processes. The Java UI contributes a property - * page for IProcess that will show the contents of the property - * with this key. - * The intent of this property is to show the command line a process - * was launched with. + * The class org.eclipse.debug.core.model.IProcess allows attaching String + * properties to processes. The Java UI contributes a property page for + * IProcess that will show the contents of the property with this key. The + * intent of this property is to show the command line a process was + * launched with. + * * @deprecated */ -// public final static String ATTR_CMDLINE= "net.sourceforge.phpdt.ui.launcher.cmdLine"; //$NON-NLS-1$ - + // public final static String ATTR_CMDLINE= + // "net.sourceforge.phpdt.ui.launcher.cmdLine"; //$NON-NLS-1$ /** * Returns the shared images for the Java UI. - * + * * @return the shared images manager */ public static ISharedImages getSharedImages() { if (fgSharedImages == null) - fgSharedImages= new SharedImages(); - + fgSharedImages = new SharedImages(); + return fgSharedImages; } - - /** - * Creates a selection dialog that lists all packages of the given Java project. - * The caller is responsible for opening the dialog with Window.open, - * and subsequently extracting the selected package (of type - * IPackageFragment) via SelectionDialog.getResult. - * - * @param parent the parent shell of the dialog to be created - * @param project the Java project - * @param style flags defining the style of the dialog; the valid flags are: - * IJavaElementSearchConstants.CONSIDER_BINARIES, indicating that - * packages from binary package fragment roots should be included in addition - * to those from source package fragment roots; - * IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS, indicating that - * packages from required projects should be included as well. - * @param filter the initial pattern to filter the set of packages. For example "com" shows - * all packages starting with "com". The meta character '?' representing any character and - * '*' representing any string are supported. Clients can pass an empty string if no filtering - * is required. + + /** + * Creates a selection dialog that lists all packages of the given Java + * project. The caller is responsible for opening the dialog with + * Window.open, and subsequently extracting the selected + * package (of type IPackageFragment) via + * SelectionDialog.getResult. + * + * @param parent + * the parent shell of the dialog to be created + * @param project + * the Java project + * @param style + * flags defining the style of the dialog; the valid flags are: + * IJavaElementSearchConstants.CONSIDER_BINARIES, + * indicating that packages from binary package fragment roots + * should be included in addition to those from source package + * fragment roots; + * IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS, + * indicating that packages from required projects should be + * included as well. + * @param filter + * the initial pattern to filter the set of packages. For example + * "com" shows all packages starting with "com". The meta + * character '?' representing any character and '*' representing + * any string are supported. Clients can pass an empty string if + * no filtering is required. * @return a new selection dialog - * @exception JavaModelException if the selection dialog could not be opened + * @exception JavaModelException + * if the selection dialog could not be opened * * @since 2.0 */ -// public static SelectionDialog createPackageDialog(Shell parent, IJavaProject project, int style, String filter) throws JavaModelException { -// Assert.isTrue((style | IJavaElementSearchConstants.CONSIDER_BINARIES | IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS) == -// (IJavaElementSearchConstants.CONSIDER_BINARIES | IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS)); -// -// IPackageFragmentRoot[] roots= null; -// if ((style & IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS) != 0) { -// roots= project.getAllPackageFragmentRoots(); -// } else { -// roots= project.getPackageFragmentRoots(); -// } -// -// List consideredRoots= null; -// if ((style & IJavaElementSearchConstants.CONSIDER_BINARIES) != 0) { -// consideredRoots= Arrays.asList(roots); -// } else { -// consideredRoots= new ArrayList(roots.length); -// for (int i= 0; i < roots.length; i++) { -// IPackageFragmentRoot root= roots[i]; -// if (root.getKind() != IPackageFragmentRoot.K_BINARY) -// consideredRoots.add(root); -// -// } -// } -// -// int flags= JavaElementLabelProvider.SHOW_DEFAULT; -// if (consideredRoots.size() > 1) -// flags= flags | JavaElementLabelProvider.SHOW_ROOT; -// -// List packages= new ArrayList(); -// Iterator iter= consideredRoots.iterator(); -// while(iter.hasNext()) { -// IPackageFragmentRoot root= (IPackageFragmentRoot)iter.next(); -// packages.addAll(Arrays.asList(root.getChildren())); -// } -// ElementListSelectionDialog dialog= new ElementListSelectionDialog(parent, new JavaElementLabelProvider(flags)); -// dialog.setIgnoreCase(false); -// dialog.setElements(packages.toArray()); // XXX inefficient -// dialog.setFilter(filter); -// return dialog; -// } - - /** - * Creates a selection dialog that lists all packages of the given Java project. - * The caller is responsible for opening the dialog with Window.open, - * and subsequently extracting the selected package (of type - * IPackageFragment) via SelectionDialog.getResult. - * - * @param parent the parent shell of the dialog to be created - * @param project the Java project - * @param style flags defining the style of the dialog; the valid flags are: - * IJavaElementSearchConstants.CONSIDER_BINARIES, indicating that - * packages from binary package fragment roots should be included in addition - * to those from source package fragment roots; - * IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS, indicating that - * packages from required projects should be included as well. + // public static SelectionDialog createPackageDialog(Shell parent, + // IJavaProject project, int style, String filter) throws JavaModelException + // { + // Assert.isTrue((style | IJavaElementSearchConstants.CONSIDER_BINARIES | + // IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS) == + // (IJavaElementSearchConstants.CONSIDER_BINARIES | + // IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS)); + // + // IPackageFragmentRoot[] roots= null; + // if ((style & IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS) != + // 0) { + // roots= project.getAllPackageFragmentRoots(); + // } else { + // roots= project.getPackageFragmentRoots(); + // } + // + // List consideredRoots= null; + // if ((style & IJavaElementSearchConstants.CONSIDER_BINARIES) != 0) { + // consideredRoots= Arrays.asList(roots); + // } else { + // consideredRoots= new ArrayList(roots.length); + // for (int i= 0; i < roots.length; i++) { + // IPackageFragmentRoot root= roots[i]; + // if (root.getKind() != IPackageFragmentRoot.K_BINARY) + // consideredRoots.add(root); + // + // } + // } + // + // int flags= JavaElementLabelProvider.SHOW_DEFAULT; + // if (consideredRoots.size() > 1) + // flags= flags | JavaElementLabelProvider.SHOW_ROOT; + // + // List packages= new ArrayList(); + // Iterator iter= consideredRoots.iterator(); + // while(iter.hasNext()) { + // IPackageFragmentRoot root= (IPackageFragmentRoot)iter.next(); + // packages.addAll(Arrays.asList(root.getChildren())); + // } + // ElementListSelectionDialog dialog= new ElementListSelectionDialog(parent, + // new JavaElementLabelProvider(flags)); + // dialog.setIgnoreCase(false); + // dialog.setElements(packages.toArray()); // XXX inefficient + // dialog.setFilter(filter); + // return dialog; + // } + /** + * Creates a selection dialog that lists all packages of the given Java + * project. The caller is responsible for opening the dialog with + * Window.open, and subsequently extracting the selected + * package (of type IPackageFragment) via + * SelectionDialog.getResult. + * + * @param parent + * the parent shell of the dialog to be created + * @param project + * the Java project + * @param style + * flags defining the style of the dialog; the valid flags are: + * IJavaElementSearchConstants.CONSIDER_BINARIES, + * indicating that packages from binary package fragment roots + * should be included in addition to those from source package + * fragment roots; + * IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS, + * indicating that packages from required projects should be + * included as well. * @return a new selection dialog - * @exception JavaModelException if the selection dialog could not be opened - */ -// public static SelectionDialog createPackageDialog(Shell parent, IJavaProject project, int style) throws JavaModelException { -// return createPackageDialog(parent, project, style, ""); //$NON-NLS-1$ -// } - - /** - * Creates a selection dialog that lists all packages under the given package - * fragment root. - * The caller is responsible for opening the dialog with Window.open, - * and subsequently extracting the selected package (of type - * IPackageFragment) via SelectionDialog.getResult. - * - * @param parent the parent shell of the dialog to be created - * @param root the package fragment root - * @param filter the initial pattern to filter the set of packages. For example "com" shows - * all packages starting with "com". The meta character '?' representing any character and - * '*' representing any string are supported. Clients can pass an empty string if no filtering - * is required. + * @exception JavaModelException + * if the selection dialog could not be opened + */ + // public static SelectionDialog createPackageDialog(Shell parent, + // IJavaProject project, int style) throws JavaModelException { + // return createPackageDialog(parent, project, style, ""); //$NON-NLS-1$ + // } + /** + * Creates a selection dialog that lists all packages under the given + * package fragment root. The caller is responsible for opening the dialog + * with Window.open, and subsequently extracting the + * selected package (of type IPackageFragment) via + * SelectionDialog.getResult. + * + * @param parent + * the parent shell of the dialog to be created + * @param root + * the package fragment root + * @param filter + * the initial pattern to filter the set of packages. For example + * "com" shows all packages starting with "com". The meta + * character '?' representing any character and '*' representing + * any string are supported. Clients can pass an empty string if + * no filtering is required. * @return a new selection dialog - * @exception JavaModelException if the selection dialog could not be opened + * @exception JavaModelException + * if the selection dialog could not be opened * * @since 2.0 */ -// public static SelectionDialog createPackageDialog(Shell parent, IPackageFragmentRoot root, String filter) throws JavaModelException { -// ElementListSelectionDialog dialog= new ElementListSelectionDialog(parent, new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT)); -// dialog.setIgnoreCase(false); -// dialog.setElements(root.getChildren()); -// dialog.setFilter(filter); -// return dialog; -// } - - /** - * Creates a selection dialog that lists all packages under the given package - * fragment root. - * The caller is responsible for opening the dialog with Window.open, - * and subsequently extracting the selected package (of type - * IPackageFragment) via SelectionDialog.getResult. - * - * @param parent the parent shell of the dialog to be created - * @param root the package fragment root + // public static SelectionDialog createPackageDialog(Shell parent, + // IPackageFragmentRoot root, String filter) throws JavaModelException { + // ElementListSelectionDialog dialog= new ElementListSelectionDialog(parent, + // new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT)); + // dialog.setIgnoreCase(false); + // dialog.setElements(root.getChildren()); + // dialog.setFilter(filter); + // return dialog; + // } + /** + * Creates a selection dialog that lists all packages under the given + * package fragment root. The caller is responsible for opening the dialog + * with Window.open, and subsequently extracting the + * selected package (of type IPackageFragment) via + * SelectionDialog.getResult. + * + * @param parent + * the parent shell of the dialog to be created + * @param root + * the package fragment root * @return a new selection dialog - * @exception JavaModelException if the selection dialog could not be opened - */ -// public static SelectionDialog createPackageDialog(Shell parent, IPackageFragmentRoot root) throws JavaModelException { -// return createPackageDialog(parent, root, ""); //$NON-NLS-1$ -// } - - /** - * Creates a selection dialog that lists all types in the given scope. - * The caller is responsible for opening the dialog with Window.open, - * and subsequently extracting the selected type(s) (of type - * IType) via SelectionDialog.getResult. - * - * @param parent the parent shell of the dialog to be created - * @param context the runnable context used to show progress when the dialog - * is being populated - * @param scope the scope that limits which types are included - * @param style flags defining the style of the dialog; the only valid values are - * IJavaElementSearchConstants.CONSIDER_CLASSES, - * CONSIDER_INTERFACES, or their bitwise OR - * (equivalent to CONSIDER_TYPES) - * @param multipleSelection true if multiple selection is allowed - * @param filter the initial pattern to filter the set of types. For example "Abstract" shows - * all types starting with "abstract". The meta character '?' representing any character and - * '*' representing any string are supported. Clients can pass an empty string if no filtering - * is required. - * @exception JavaModelException if the selection dialog could not be opened + * @exception JavaModelException + * if the selection dialog could not be opened + */ + // public static SelectionDialog createPackageDialog(Shell parent, + // IPackageFragmentRoot root) throws JavaModelException { + // return createPackageDialog(parent, root, ""); //$NON-NLS-1$ + // } + /** + * Creates a selection dialog that lists all types in the given scope. The + * caller is responsible for opening the dialog with + * Window.open, and subsequently extracting the selected + * type(s) (of type IType) via + * SelectionDialog.getResult. + * + * @param parent + * the parent shell of the dialog to be created + * @param context + * the runnable context used to show progress when the dialog is + * being populated + * @param scope + * the scope that limits which types are included + * @param style + * flags defining the style of the dialog; the only valid values + * are IJavaElementSearchConstants.CONSIDER_CLASSES, + * CONSIDER_INTERFACES, or their bitwise OR + * (equivalent to CONSIDER_TYPES) + * @param multipleSelection + * true if multiple selection is allowed + * @param filter + * the initial pattern to filter the set of types. For example + * "Abstract" shows all types starting with "abstract". The meta + * character '?' representing any character and '*' representing + * any string are supported. Clients can pass an empty string if + * no filtering is required. + * @exception JavaModelException + * if the selection dialog could not be opened * * @since 2.0 */ -// public static SelectionDialog createTypeDialog(Shell parent, IRunnableContext context, IJavaSearchScope scope, int style, boolean multipleSelection, String filter) throws JavaModelException { -// int elementKinds= 0; -// if (style == IJavaElementSearchConstants.CONSIDER_TYPES) { -// elementKinds= IJavaSearchConstants.TYPE; -// } else if (style == IJavaElementSearchConstants.CONSIDER_INTERFACES) { -// elementKinds= IJavaSearchConstants.INTERFACE; -// } else if (style == IJavaElementSearchConstants.CONSIDER_CLASSES) { -// elementKinds= IJavaSearchConstants.CLASS; -// } else { -// Assert.isTrue(false, "illegal style"); //$NON-NLS-1$ -// } -// if (multipleSelection) { -// MultiTypeSelectionDialog dialog= new MultiTypeSelectionDialog(parent, context, elementKinds, scope); -// dialog.setMessage(JavaUIMessages.getString("JavaUI.defaultDialogMessage")); //$NON-NLS-1$ -// dialog.setFilter(filter); -// return dialog; -// } else { -// TypeSelectionDialog dialog= new TypeSelectionDialog(parent, context, elementKinds, scope); -// dialog.setMessage(JavaUIMessages.getString("JavaUI.defaultDialogMessage")); //$NON-NLS-1$ -// dialog.setFilter(filter); -// return dialog; -// } -// } - - /** - * Creates a selection dialog that lists all types in the given scope. - * The caller is responsible for opening the dialog with Window.open, - * and subsequently extracting the selected type(s) (of type - * IType) via SelectionDialog.getResult. - * - * @param parent the parent shell of the dialog to be created - * @param context the runnable context used to show progress when the dialog - * is being populated - * @param scope the scope that limits which types are included - * @param style flags defining the style of the dialog; the only valid values are - * IJavaElementSearchConstants.CONSIDER_CLASSES, - * CONSIDER_INTERFACES, or their bitwise OR - * (equivalent to CONSIDER_TYPES) - * @param multipleSelection true if multiple selection is allowed + // public static SelectionDialog createTypeDialog(Shell parent, + // IRunnableContext context, IJavaSearchScope scope, int style, boolean + // multipleSelection, String filter) throws JavaModelException { + // int elementKinds= 0; + // if (style == IJavaElementSearchConstants.CONSIDER_TYPES) { + // elementKinds= IJavaSearchConstants.TYPE; + // } else if (style == IJavaElementSearchConstants.CONSIDER_INTERFACES) { + // elementKinds= IJavaSearchConstants.INTERFACE; + // } else if (style == IJavaElementSearchConstants.CONSIDER_CLASSES) { + // elementKinds= IJavaSearchConstants.CLASS; + // } else { + // Assert.isTrue(false, "illegal style"); //$NON-NLS-1$ + // } + // if (multipleSelection) { + // MultiTypeSelectionDialog dialog= new MultiTypeSelectionDialog(parent, + // context, elementKinds, scope); + // dialog.setMessage(JavaUIMessages.getString("JavaUI.defaultDialogMessage")); + // //$NON-NLS-1$ + // dialog.setFilter(filter); + // return dialog; + // } else { + // TypeSelectionDialog dialog= new TypeSelectionDialog(parent, context, + // elementKinds, scope); + // dialog.setMessage(JavaUIMessages.getString("JavaUI.defaultDialogMessage")); + // //$NON-NLS-1$ + // dialog.setFilter(filter); + // return dialog; + // } + // } + /** + * Creates a selection dialog that lists all types in the given scope. The + * caller is responsible for opening the dialog with + * Window.open, and subsequently extracting the selected + * type(s) (of type IType) via + * SelectionDialog.getResult. + * + * @param parent + * the parent shell of the dialog to be created + * @param context + * the runnable context used to show progress when the dialog is + * being populated + * @param scope + * the scope that limits which types are included + * @param style + * flags defining the style of the dialog; the only valid values + * are IJavaElementSearchConstants.CONSIDER_CLASSES, + * CONSIDER_INTERFACES, or their bitwise OR + * (equivalent to CONSIDER_TYPES) + * @param multipleSelection + * true if multiple selection is allowed * @return a new selection dialog - * @exception JavaModelException if the selection dialog could not be opened - */ -// public static SelectionDialog createTypeDialog(Shell parent, IRunnableContext context, IJavaSearchScope scope, int style, boolean multipleSelection) throws JavaModelException { -// return createTypeDialog(parent, context, scope, style, multipleSelection, "");//$NON-NLS-1$ -// } - - /** - * Creates a selection dialog that lists all types in the given scope containing - * a standard main method. - * The caller is responsible for opening the dialog with Window.open, - * and subsequently extracting the selected type(s) (of type - * IType) via SelectionDialog.getResult. - * - * @param parent the parent shell of the dialog to be created - * @param context the runnable context used to show progress when the dialog - * is being populated - * @param scope the scope that limits which types are included - * @param style flags defining the style of the dialog; the only valid values are - * IJavaElementSearchConstants.CONSIDER_BINARIES, - * CONSIDER_EXTERNAL_JARS, or their bitwise OR, or 0 - * @param multipleSelection true if multiple selection is allowed - * @param filter the initial pattern to filter the set of types containg a main method. For - * example "App" shows all types starting with "app". The meta character '?' representing - * any character and '*' representing any string are supported. Clients can pass an empty - * string if no filtering is required. + * @exception JavaModelException + * if the selection dialog could not be opened + */ + // public static SelectionDialog createTypeDialog(Shell parent, + // IRunnableContext context, IJavaSearchScope scope, int style, boolean + // multipleSelection) throws JavaModelException { + // return createTypeDialog(parent, context, scope, style, multipleSelection, + // "");//$NON-NLS-1$ + // } + /** + * Creates a selection dialog that lists all types in the given scope + * containing a standard main method. The caller is + * responsible for opening the dialog with Window.open, and + * subsequently extracting the selected type(s) (of type IType) + * via SelectionDialog.getResult. + * + * @param parent + * the parent shell of the dialog to be created + * @param context + * the runnable context used to show progress when the dialog is + * being populated + * @param scope + * the scope that limits which types are included + * @param style + * flags defining the style of the dialog; the only valid values + * are IJavaElementSearchConstants.CONSIDER_BINARIES, + * CONSIDER_EXTERNAL_JARS, or their bitwise OR, + * or 0 + * @param multipleSelection + * true if multiple selection is allowed + * @param filter + * the initial pattern to filter the set of types containg a main + * method. For example "App" shows all types starting with "app". + * The meta character '?' representing any character and '*' + * representing any string are supported. Clients can pass an + * empty string if no filtering is required. * @return a new selection dialog * * @since 2.0 */ -// public static SelectionDialog createMainTypeDialog(Shell parent, IRunnableContext context, IJavaSearchScope scope, int style, boolean multipleSelection, String filter) { -// if (multipleSelection) { -// MultiMainTypeSelectionDialog dialog= new MultiMainTypeSelectionDialog(parent, context, scope, style); -// dialog.setFilter(filter); -// return dialog; -// } else { -// MainTypeSelectionDialog dialog= new MainTypeSelectionDialog(parent, context, scope, style); -// dialog.setFilter(filter); -// return dialog; -// } -// } - - /** - * Creates a selection dialog that lists all types in the given scope containing - * a standard main method. - * The caller is responsible for opening the dialog with Window.open, - * and subsequently extracting the selected type(s) (of type - * IType) via SelectionDialog.getResult. - * - * @param parent the parent shell of the dialog to be created - * @param context the runnable context used to show progress when the dialog - * is being populated - * @param scope the scope that limits which types are included - * @param style flags defining the style of the dialog; the only valid values are - * IJavaElementSearchConstants.CONSIDER_BINARIES, - * CONSIDER_EXTERNAL_JARS, or their bitwise OR, or 0 - * @param multipleSelection true if multiple selection is allowed + // public static SelectionDialog createMainTypeDialog(Shell parent, + // IRunnableContext context, IJavaSearchScope scope, int style, boolean + // multipleSelection, String filter) { + // if (multipleSelection) { + // MultiMainTypeSelectionDialog dialog= new + // MultiMainTypeSelectionDialog(parent, context, scope, style); + // dialog.setFilter(filter); + // return dialog; + // } else { + // MainTypeSelectionDialog dialog= new MainTypeSelectionDialog(parent, + // context, scope, style); + // dialog.setFilter(filter); + // return dialog; + // } + // } + /** + * Creates a selection dialog that lists all types in the given scope + * containing a standard main method. The caller is + * responsible for opening the dialog with Window.open, and + * subsequently extracting the selected type(s) (of type IType) + * via SelectionDialog.getResult. + * + * @param parent + * the parent shell of the dialog to be created + * @param context + * the runnable context used to show progress when the dialog is + * being populated + * @param scope + * the scope that limits which types are included + * @param style + * flags defining the style of the dialog; the only valid values + * are IJavaElementSearchConstants.CONSIDER_BINARIES, + * CONSIDER_EXTERNAL_JARS, or their bitwise OR, + * or 0 + * @param multipleSelection + * true if multiple selection is allowed * @return a new selection dialog */ -// public static SelectionDialog createMainTypeDialog(Shell parent, IRunnableContext context, IJavaSearchScope scope, int style, boolean multipleSelection) { -// return createMainTypeDialog(parent, context, scope, style, multipleSelection, "");//$NON-NLS-1$ -// } - - /** - * Creates a selection dialog that lists all types in the given project. - * The caller is responsible for opening the dialog with Window.open, - * and subsequently extracting the selected type(s) (of type - * IType) via SelectionDialog.getResult. - * - * @param parent the parent shell of the dialog to be created - * @param context the runnable context used to show progress when the dialog - * is being populated - * @param project the Java project - * @param style flags defining the style of the dialog; the only valid values are - * IJavaElementSearchConstants.CONSIDER_CLASSES, - * CONSIDER_INTERFACES, or their bitwise OR - * (equivalent to CONSIDER_TYPES) - * @param multipleSelection true if multiple selection is allowed + // public static SelectionDialog createMainTypeDialog(Shell parent, + // IRunnableContext context, IJavaSearchScope scope, int style, boolean + // multipleSelection) { + // return createMainTypeDialog(parent, context, scope, style, + // multipleSelection, "");//$NON-NLS-1$ + // } + /** + * Creates a selection dialog that lists all types in the given project. The + * caller is responsible for opening the dialog with + * Window.open, and subsequently extracting the selected + * type(s) (of type IType) via + * SelectionDialog.getResult. + * + * @param parent + * the parent shell of the dialog to be created + * @param context + * the runnable context used to show progress when the dialog is + * being populated + * @param project + * the Java project + * @param style + * flags defining the style of the dialog; the only valid values + * are IJavaElementSearchConstants.CONSIDER_CLASSES, + * CONSIDER_INTERFACES, or their bitwise OR + * (equivalent to CONSIDER_TYPES) + * @param multipleSelection + * true if multiple selection is allowed * @return a new selection dialog - * @exception JavaModelException if the selection dialog could not be opened - */ -// public static SelectionDialog createTypeDialog(Shell parent, IRunnableContext context, IProject project, int style, boolean multipleSelection) throws JavaModelException { -// IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaProject[] { JavaCore.create(project) }); -// return createTypeDialog(parent, context, scope, style, multipleSelection); -// } - - /** - * Opens a Java editor on the given Java element. The element can be a compilation unit - * or class file. If there already is an open Java editor for the given element, it is returned. - * - * @param element the input element; either a compilation unit - * (ICompilationUnit) or a class file (
                                                      IClassFile) - * @return the editor, or null if wrong element type or opening failed - * @exception PartInitException if the editor could not be initialized - * @exception JavaModelException if this element does not exist or if an - * exception occurs while accessing its underlying resource - */ - public static IEditorPart openInEditor(IJavaElement element) throws JavaModelException, PartInitException { + * @exception JavaModelException + * if the selection dialog could not be opened + */ + // public static SelectionDialog createTypeDialog(Shell parent, + // IRunnableContext context, IProject project, int style, boolean + // multipleSelection) throws JavaModelException { + // IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new + // IJavaProject[] { JavaCore.create(project) }); + // return createTypeDialog(parent, context, scope, style, + // multipleSelection); + // } + /** + * Opens a Java editor on the given Java element. The element can be a + * compilation unit or class file. If there already is an open Java editor + * for the given element, it is returned. + * + * @param element + * the input element; either a compilation unit (ICompilationUnit) + * or a class file (IClassFile) + * @return the editor, or null if wrong element type or + * opening failed + * @exception PartInitException + * if the editor could not be initialized + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its underlying resource + */ + public static IEditorPart openInEditor(IJavaElement element) + throws JavaModelException, PartInitException { return EditorUtility.openInEditor(element); } - /** + /** * Reveals the source range of the given source reference element in the - * given editor. No checking is done if the editor displays a compilation unit or - * class file that contains the given source reference. The editor simply reveals - * the source range denoted by the given source reference. - * - * @param part the editor displaying the compilation unit or class file - * @param element the source reference element defining the source range to be revealed - * - * @deprecated use revealInEditor(IEditorPart, IJavaElement) instead - */ -// public static void revealInEditor(IEditorPart part, ISourceReference element) { -// if (element instanceof IJavaElement) -// revealInEditor(part, (IJavaElement) element); -// } - - /** - * Reveals the given java element in the given editor. If the element is not an instance - * of ISourceReference this method result in a NOP. If it is a source - * reference no checking is done if the editor displays a compilation unit or class file that - * contains the source reference element. The editor simply reveals the source range - * denoted by the given element. - * - * @param part the editor displaying a compilation unit or class file - * @param element the element to be revealed + * given editor. No checking is done if the editor displays a compilation + * unit or class file that contains the given source reference. The editor + * simply reveals the source range denoted by the given source reference. + * + * @param part + * the editor displaying the compilation unit or class file + * @param element + * the source reference element defining the source range to be + * revealed + * + * @deprecated use revealInEditor(IEditorPart, IJavaElement) + * instead + */ + // public static void revealInEditor(IEditorPart part, ISourceReference + // element) { + // if (element instanceof IJavaElement) + // revealInEditor(part, (IJavaElement) element); + // } + /** + * Reveals the given java element in the given editor. If the element is not + * an instance of ISourceReference this method result in a + * NOP. If it is a source reference no checking is done if the editor + * displays a compilation unit or class file that contains the source + * reference element. The editor simply reveals the source range denoted by + * the given element. + * + * @param part + * the editor displaying a compilation unit or class file + * @param element + * the element to be revealed * * @since 2.0 */ -// public static void revealInEditor(IEditorPart part, IJavaElement element) { -// EditorUtility.revealInEditor(part, element); -// } - + // public static void revealInEditor(IEditorPart part, IJavaElement element) + // { + // EditorUtility.revealInEditor(part, element); + // } /** * Returns the working copy manager for the Java UI plug-in. - * + * * @return the working copy manager for the Java UI plug-in */ public static IWorkingCopyManager getWorkingCopyManager() { return PHPeclipsePlugin.getDefault().getWorkingCopyManager(); } - + /** - * Answers the shared working copies currently registered for the Java plug-in. - * Note that the returned array can include working copies that are + * Answers the shared working copies currently registered for the Java + * plug-in. Note that the returned array can include working copies that are * not on the class path of a Java project. * * @return the list of shared working copies @@ -557,7 +653,7 @@ public final class JavaUI { public static IWorkingCopy[] getSharedWorkingCopies() { return JavaCore.getSharedWorkingCopies(getBufferFactory()); } - + /** * Answers the shared working copies that are on the class path of a Java * project currently registered for the Java plug-in. @@ -568,118 +664,126 @@ public final class JavaUI { * @see #getSharedWorkingCopies() * @since 2.1 */ -// public static IWorkingCopy[] getSharedWorkingCopiesOnClasspath() { -// IWorkingCopy[] wcs= getSharedWorkingCopies(); -// List result= new ArrayList(wcs.length); -// for (int i = 0; i < wcs.length; i++) { -// IWorkingCopy wc= wcs[i]; -// if (wc instanceof IJavaElement) { -// IJavaElement je= (IJavaElement)wc; -// if (je.getJavaProject().isOnClasspath(je)) { -// result.add(wc); -// } -// } -// } -// return (IWorkingCopy[])result.toArray(new IWorkingCopy[result.size()]); -// } - + // public static IWorkingCopy[] getSharedWorkingCopiesOnClasspath() { + // IWorkingCopy[] wcs= getSharedWorkingCopies(); + // List result= new ArrayList(wcs.length); + // for (int i = 0; i < wcs.length; i++) { + // IWorkingCopy wc= wcs[i]; + // if (wc instanceof IJavaElement) { + // IJavaElement je= (IJavaElement)wc; + // if (je.getJavaProject().isOnClasspath(je)) { + // result.add(wc); + // } + // } + // } + // return (IWorkingCopy[])result.toArray(new IWorkingCopy[result.size()]); + // } /** * Returns the BufferFactory for the Java UI plug-in. - * + * * @return the BufferFactory for the Java UI plug-in * * @see net.sourceforge.phpdt.core.IBufferFactory * @since 2.0 - * @deprecated {@link IBufferFactory} has been replaced by {@link net.sourceforge.phpdt.core.WorkingCopyOwner}. - * The Java UI plug-in uses the primary working copy owner that can be accessed with null in - * API's that require an owner + * @deprecated {@link IBufferFactory} has been replaced by + * {@link net.sourceforge.phpdt.core.WorkingCopyOwner}. The + * Java UI plug-in uses the primary working copy owner + * that can be accessed with null in API's that + * require an owner */ public static IBufferFactory getBufferFactory() { return PHPeclipsePlugin.getDefault().getBufferFactory(); } + /** * Returns the DocumentProvider used for Java compilation units. - * + * * @return the DocumentProvider for Java compilation units. * * @see IDocumentProvider * @since 2.0 */ public static IDocumentProvider getDocumentProvider() { - return PHPeclipsePlugin.getDefault().getCompilationUnitDocumentProvider(); + return PHPeclipsePlugin.getDefault() + .getCompilationUnitDocumentProvider(); } - + /** * Sets the Javadoc location for an archive with the given path. * - * @param archivePath the path of the library; this can be an workspace path - * or an external path in case of an external library. - * @param url The Javadoc location to set. This location should contain index.html and - * a file 'package-list'. null clears the current documentation - * location. + * @param archivePath + * the path of the library; this can be an workspace path or an + * external path in case of an external library. + * @param url + * The Javadoc location to set. This location should contain + * index.html and a file 'package-list'. null + * clears the current documentation location. * * @since 2.0 */ -// public static void setLibraryJavadocLocation(IPath archivePath, URL url) { -// JavaDocLocations.setLibraryJavadocLocation(archivePath, url); -// } - + // public static void setLibraryJavadocLocation(IPath archivePath, URL url) + // { + // JavaDocLocations.setLibraryJavadocLocation(archivePath, url); + // } /** * Returns the Javadoc location for an archive or null if no * location is available. * - * @param archivePath the path of the library. This can be an workspace path - * or an external path in case of an external library. + * @param archivePath + * the path of the library. This can be an workspace path or an + * external path in case of an external library. * * @since 2.0 - */ -// public static URL getLibraryJavadocLocation(IPath archivePath) { -// return JavaDocLocations.getLibraryJavadocLocation(archivePath); -// } - + */ + // public static URL getLibraryJavadocLocation(IPath archivePath) { + // return JavaDocLocations.getLibraryJavadocLocation(archivePath); + // } /** * Sets the Javadoc location for a Java project. This location is used for * all types located in the project's source folders. * - * @param project the project - * @param url The Javadoc location to set. This location should contain index.html and - * a file 'package-list'. null clears the current documentation - * location. + * @param project + * the project + * @param url + * The Javadoc location to set. This location should contain + * index.html and a file 'package-list'. null + * clears the current documentation location. * * @since 2.1 */ -// public static void setProjectJavadocLocation(IJavaProject project, URL url) { -// JavaDocLocations.setProjectJavadocLocation(project, url); -// } - + // public static void setProjectJavadocLocation(IJavaProject project, URL + // url) { + // JavaDocLocations.setProjectJavadocLocation(project, url); + // } /** - * Returns the Javadoc location for a Java project or null if no - * location is available. This location is used for all types located in the project's - * source folders. + * Returns the Javadoc location for a Java project or null if + * no location is available. This location is used for all types located in + * the project's source folders. * - * @param project the project + * @param project + * the project * * @since 2.1 - */ -// public static URL getProjectJavadocLocation(IJavaProject project) { -// return JavaDocLocations.getProjectJavadocLocation(project); -// } - + */ + // public static URL getProjectJavadocLocation(IJavaProject project) { + // return JavaDocLocations.getProjectJavadocLocation(project); + // } /** - * Returns the Javadoc base URL for an element. The base location contains the - * index file. This location doesn't have to exist. Returns + * Returns the Javadoc base URL for an element. The base location contains + * the index file. This location doesn't have to exist. Returns * null if no javadoc location has been attached to the * element's library or project. Example of a returned URL is http://www. * junit. org/junit/javadoc. * - * @param The element for which the doc URL is requested. + * @param The + * element for which the doc URL is requested. * * @since 2.0 - */ -// public static URL getJavadocBaseLocation(IJavaElement element) throws JavaModelException { -// return JavaDocLocations.getJavadocBaseLocation(element); -// } - + */ + // public static URL getJavadocBaseLocation(IJavaElement element) throws + // JavaModelException { + // return JavaDocLocations.getJavadocBaseLocation(element); + // } /** * Returns the Javadoc URL for an element. Example of a returned URL is * http://www.junit.org/junit/javadoc/junit/extensions/TestSetup.html. @@ -687,14 +791,18 @@ public final class JavaUI { * if no javadoc location has been attached to the element's library or * project. * - * @param The element for which the doc URL is requested. - * @param includeAnchor If set, the URL contains an anchor for member references: - * http://www.junit.org/junit/javadoc/junit/extensions/TestSetup.html#run(junit.framework.TestResult). Note - * that this involves type resolving and is a more expensive call than without anchor. + * @param The + * element for which the doc URL is requested. + * @param includeAnchor + * If set, the URL contains an anchor for member references: + * http://www.junit.org/junit/javadoc/junit/extensions/TestSetup.html#run(junit.framework.TestResult). + * Note that this involves type resolving and is a more expensive + * call than without anchor. * * @since 2.0 - */ -// public static URL getJavadocLocation(IJavaElement element, boolean includeAnchor) throws JavaModelException { -// return JavaDocLocations.getJavadocLocation(element, includeAnchor); -// } + */ + // public static URL getJavadocLocation(IJavaElement element, boolean + // includeAnchor) throws JavaModelException { + // return JavaDocLocations.getJavadocLocation(element, includeAnchor); + // } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/OverrideIndicatorLabelDecorator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/OverrideIndicatorLabelDecorator.java index 90e0f65..1cf420e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/OverrideIndicatorLabelDecorator.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/OverrideIndicatorLabelDecorator.java @@ -28,10 +28,10 @@ import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; - /** - * LabelDecorator that decorates an method's image with override or implements overlays. - * The viewer using this decorator is responsible for updating the images on element changes. + * LabelDecorator that decorates an method's image with override or implements + * overlays. The viewer using this decorator is responsible for updating the + * images on element changes. * *

                                                      * This class may be instantiated; it is not intended to be subclassed. @@ -39,79 +39,91 @@ import org.eclipse.swt.graphics.Rectangle; * * @since 2.0 */ -public class OverrideIndicatorLabelDecorator implements ILabelDecorator, ILightweightLabelDecorator { +public class OverrideIndicatorLabelDecorator implements ILabelDecorator, + ILightweightLabelDecorator { private ImageDescriptorRegistry fRegistry; - private boolean fUseNewRegistry= false; + + private boolean fUseNewRegistry = false; /** * Creates a decorator. The decorator creates an own image registry to cache - * images. + * images. */ public OverrideIndicatorLabelDecorator() { this(null); - fUseNewRegistry= true; - } + fUseNewRegistry = true; + } /* * Creates decorator with a shared image registry. * - * @param registry The registry to use or null to use the Java plugin's - * image registry. - */ + * @param registry The registry to use or null to use the + * Java plugin's image registry. + */ /** - * Note: This constructor is for internal use only. Clients should not call this constructor. + * Note: This constructor is for internal use only. Clients should not call + * this constructor. */ public OverrideIndicatorLabelDecorator(ImageDescriptorRegistry registry) { - fRegistry= registry; + fRegistry = registry; } - + private ImageDescriptorRegistry getRegistry() { if (fRegistry == null) { - fRegistry= fUseNewRegistry ? new ImageDescriptorRegistry() : PHPeclipsePlugin.getImageDescriptorRegistry(); + fRegistry = fUseNewRegistry ? new ImageDescriptorRegistry() + : PHPeclipsePlugin.getImageDescriptorRegistry(); } return fRegistry; - } - - - /* (non-Javadoc) + } + + /* + * (non-Javadoc) + * * @see ILabelDecorator#decorateText(String, Object) */ public String decorateText(String text, Object element) { return text; - } + } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see ILabelDecorator#decorateImage(Image, Object) */ public Image decorateImage(Image image, Object element) { - int adornmentFlags= computeAdornmentFlags(element); + int adornmentFlags = computeAdornmentFlags(element); if (adornmentFlags != 0) { - ImageDescriptor baseImage= new ImageImageDescriptor(image); - Rectangle bounds= image.getBounds(); - return getRegistry().get(new JavaElementImageDescriptor(baseImage, adornmentFlags, new Point(bounds.width, bounds.height))); + ImageDescriptor baseImage = new ImageImageDescriptor(image); + Rectangle bounds = image.getBounds(); + return getRegistry().get( + new JavaElementImageDescriptor(baseImage, adornmentFlags, + new Point(bounds.width, bounds.height))); } return image; } - + /** - * Note: This method is for internal use only. Clients should not call this method. + * Note: This method is for internal use only. Clients should not call this + * method. */ public int computeAdornmentFlags(Object element) { if (element instanceof IMethod) { - if (!PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.APPEARANCE_OVERRIDE_INDICATOR)) { + if (!PreferenceConstants.getPreferenceStore().getBoolean( + PreferenceConstants.APPEARANCE_OVERRIDE_INDICATOR)) { return 0; } - + try { - IMethod method= (IMethod) element; -// if (!method.getJavaProject().isOnClasspath(method)) { -// return 0; -// } - - int flags= method.getFlags(); - IType type = method.getDeclaringType();//jsurfer INSERT - if (type!=null && type.isClass() && !method.isConstructor() && !Flags.isPrivate(flags) && !Flags.isStatic(flags)) { + IMethod method = (IMethod) element; + // if (!method.getJavaProject().isOnClasspath(method)) { + // return 0; + // } + + int flags = method.getFlags(); + IType type = method.getDeclaringType();// jsurfer INSERT + if (type != null && type.isClass() && !method.isConstructor() + && !Flags.isPrivate(flags) && !Flags.isStatic(flags)) { return getOverrideIndicators(method); } } catch (JavaModelException e) { @@ -122,42 +134,54 @@ public class OverrideIndicatorLabelDecorator implements ILabelDecorator, ILightw } return 0; } - + /** - * Note: This method is for internal use only. Clients should not call this method. + * Note: This method is for internal use only. Clients should not call this + * method. */ - protected int getOverrideIndicators(IMethod method) throws JavaModelException { - IType type= method.getDeclaringType(); -// ITypeHierarchy hierarchy= SuperTypeHierarchyCache.getTypeHierarchy(type); -// if (hierarchy != null) { -// return findInHierarchy(type, hierarchy, method.getElementName(), method.getParameterTypes()); -// } + protected int getOverrideIndicators(IMethod method) + throws JavaModelException { + IType type = method.getDeclaringType(); + // ITypeHierarchy hierarchy= + // SuperTypeHierarchyCache.getTypeHierarchy(type); + // if (hierarchy != null) { + // return findInHierarchy(type, hierarchy, method.getElementName(), + // method.getParameterTypes()); + // } return 0; } - + /** - * Note: This method is for internal use only. Clients should not call this method. + * Note: This method is for internal use only. Clients should not call this + * method. */ -// protected int findInHierarchy(IType type, ITypeHierarchy hierarchy, String name, String[] paramTypes) throws JavaModelException { -// IMethod impl= JavaModelUtil.findMethodDeclarationInHierarchy(hierarchy, type, name, paramTypes, false); -// if (impl != null) { -// IMethod overridden= JavaModelUtil.findMethodImplementationInHierarchy(hierarchy, type, name, paramTypes, false); -// if (overridden != null) { -// return JavaElementImageDescriptor.OVERRIDES; -// } else { -// return JavaElementImageDescriptor.IMPLEMENTS; -// } -// } -// return 0; -// } - - /* (non-Javadoc) + // protected int findInHierarchy(IType type, ITypeHierarchy hierarchy, + // String name, String[] paramTypes) throws JavaModelException { + // IMethod impl= JavaModelUtil.findMethodDeclarationInHierarchy(hierarchy, + // type, name, paramTypes, false); + // if (impl != null) { + // IMethod overridden= + // JavaModelUtil.findMethodImplementationInHierarchy(hierarchy, type, name, + // paramTypes, false); + // if (overridden != null) { + // return JavaElementImageDescriptor.OVERRIDES; + // } else { + // return JavaElementImageDescriptor.IMPLEMENTS; + // } + // } + // return 0; + // } + /* + * (non-Javadoc) + * * @see IBaseLabelProvider#addListener(ILabelProviderListener) */ public void addListener(ILabelProviderListener listener) { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see IBaseLabelProvider#dispose() */ public void dispose() { @@ -166,24 +190,31 @@ public class OverrideIndicatorLabelDecorator implements ILabelDecorator, ILightw } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see IBaseLabelProvider#isLabelProperty(Object, String) */ public boolean isLabelProperty(Object element, String property) { return true; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see IBaseLabelProvider#removeListener(ILabelProviderListener) */ public void removeListener(ILabelProviderListener listener) { } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.ILightweightLabelDecorator#decorate(java.lang.Object, org.eclipse.jface.viewers.IDecoration) + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.ILightweightLabelDecorator#decorate(java.lang.Object, + * org.eclipse.jface.viewers.IDecoration) */ - public void decorate(Object element, IDecoration decoration) { - int adornmentFlags= computeAdornmentFlags(element); + public void decorate(Object element, IDecoration decoration) { + int adornmentFlags = computeAdornmentFlags(element); if (adornmentFlags != 0) { decoration.addOverlay(PHPUiImages.DESC_OVR_OVERRIDES); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/PreferenceConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/PreferenceConstants.java index 0ff3193..c2b546c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/PreferenceConstants.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/PreferenceConstants.java @@ -26,2597 +26,3059 @@ import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; import org.eclipse.ui.texteditor.AbstractTextEditor; // -//import org.phpeclipse.phpdt.internal.ui.JavaPlugin; -//import org.phpeclipse.phpdt.internal.ui.preferences.NewJavaProjectPreferencePage; +// import org.phpeclipse.phpdt.internal.ui.JavaPlugin; +// import +// org.phpeclipse.phpdt.internal.ui.preferences.NewJavaProjectPreferencePage; /** - * Preference constants used in the JDT-UI preference store. Clients should only read the JDT-UI preference store using these - * values. Clients are not allowed to modify the preference store programmatically. - * + * Preference constants used in the JDT-UI preference store. Clients should only + * read the JDT-UI preference store using these values. Clients are not allowed + * to modify the preference store programmatically. + * * @since 2.0 */ public class PreferenceConstants { - private PreferenceConstants() { - } - - /** - * A named preference that controls return type rendering of methods in the UI. - *

                                                      - * Value is of type Boolean: if true return types are rendered - *

                                                      - */ - public static final String APPEARANCE_METHOD_RETURNTYPE = "net.sourceforge.phpdt.ui.methodreturntype"; //$NON-NLS-1$ - - /** - * A named preference that controls if override indicators are rendered in the UI. - *

                                                      - * Value is of type Boolean: if true override indicators are rendered - *

                                                      - */ - public static final String APPEARANCE_OVERRIDE_INDICATOR = "net.sourceforge.phpdt.ui.overrideindicator"; //$NON-NLS-1$ - - /** - * A named preference that defines the pattern used for package name compression. - *

                                                      - * Value is of type String. For example foe the given package name 'net.sourceforge.phpdt' pattern '.' will compress it - * to '..jdt', '1~' to 'o~.e~.jdt'. - *

                                                      - */ - public static final String APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW = "PackagesView.pkgNamePatternForPackagesView"; //$NON-NLS-1$ - - /** - * A named preference that controls if package name compression is turned on or off. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @see #APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW - */ - public static final String APPEARANCE_COMPRESS_PACKAGE_NAMES = "net.sourceforge.phpdt.ui.compresspackagenames"; //$NON-NLS-1$ - - /** - * A named preference that controls if empty inner packages are folded in the hierarchical mode of the package explorer. - *

                                                      - * Value is of type Boolean: if true empty inner packages are folded. - *

                                                      - * - * @since 2.1 - */ - public static final String APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER = "net.sourceforge.phpdt.ui.flatPackagesInPackageExplorer"; //$NON-NLS-1$ - - /** - * A named preference that defines how member elements are ordered by the Java views using the JavaElementSorter. - *

                                                      - * Value is of type String: A comma separated list of the following entries. Each entry must be in the list, no - * duplication. List order defines the sort order. - *

                                                        - *
                                                      • T : Types
                                                      • - *
                                                      • C : Constructors
                                                      • - *
                                                      • I : Initializers
                                                      • - *
                                                      • M : Methods
                                                      • - *
                                                      • F : Fields
                                                      • - *
                                                      • SI : Static Initializers
                                                      • - *
                                                      • SM : Static Methods
                                                      • - *
                                                      • SF : Static Fields
                                                      • - *
                                                      - *

                                                      - * - * @since 2.1 - */ - public static final String APPEARANCE_MEMBER_SORT_ORDER = "outlinesortoption"; //$NON-NLS-1$ - - /** - * A named preference that defines how member elements are ordered by visibility in the Java views using the - * JavaElementSorter. - *

                                                      - * Value is of type String: A comma separated list of the following entries. Each entry must be in the list, no - * duplication. List order defines the sort order. - *

                                                        - *
                                                      • B : Public
                                                      • - *
                                                      • V : Private
                                                      • - *
                                                      • R : Protected
                                                      • - *
                                                      • D : Default
                                                      • - *
                                                      - *

                                                      - * - * @since 3.0 - */ - public static final String APPEARANCE_VISIBILITY_SORT_ORDER = "net.sourceforge.phpdt.ui.visibility.order"; //$NON-NLS-1$ - - /** - * A named preferences that controls if Java elements are also sorted by visibility. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public static final String APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER = "net.sourceforge.phpdt.ui.enable.visibility.order"; //$NON-NLS-1$ - - /** - * A named preference that controls if prefix removal during setter/getter generation is turned on or off. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public static final String CODEGEN_USE_GETTERSETTER_PREFIX = "net.sourceforge.phpdt.ui.gettersetter.prefix.enable"; //$NON-NLS-1$ - - /** - * A named preference that holds a list of prefixes to be removed from a local variable to compute setter and gettter names. - *

                                                      - * Value is of type String: comma separated list of prefixed - *

                                                      - * - * @see #CODEGEN_USE_GETTERSETTER_PREFIX - */ - public static final String CODEGEN_GETTERSETTER_PREFIX = "net.sourceforge.phpdt.ui.gettersetter.prefix.list"; //$NON-NLS-1$ - - /** - * A named preference that controls if suffix removal during setter/getter generation is turned on or off. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public static final String CODEGEN_USE_GETTERSETTER_SUFFIX = "net.sourceforge.phpdt.ui.gettersetter.suffix.enable"; //$NON-NLS-1$ - - /** - * A named preference that holds a list of suffixes to be removed from a local variable to compute setter and getter names. - *

                                                      - * Value is of type String: comma separated list of suffixes - *

                                                      - * - * @see #CODEGEN_USE_GETTERSETTER_SUFFIX - */ - public static final String CODEGEN_GETTERSETTER_SUFFIX = "net.sourceforge.phpdt.ui.gettersetter.suffix.list"; //$NON-NLS-1$ - /** + private PreferenceConstants() { + } + + /** + * A named preference that controls return type rendering of methods in the + * UI. + *

                                                      + * Value is of type Boolean: if true return + * types are rendered + *

                                                      + */ + public static final String APPEARANCE_METHOD_RETURNTYPE = "net.sourceforge.phpdt.ui.methodreturntype"; //$NON-NLS-1$ + + /** + * A named preference that controls if override indicators are rendered in + * the UI. + *

                                                      + * Value is of type Boolean: if true override + * indicators are rendered + *

                                                      + */ + public static final String APPEARANCE_OVERRIDE_INDICATOR = "net.sourceforge.phpdt.ui.overrideindicator"; //$NON-NLS-1$ + + /** + * A named preference that defines the pattern used for package name + * compression. + *

                                                      + * Value is of type String. For example foe the given + * package name 'net.sourceforge.phpdt' pattern '.' will compress it to + * '..jdt', '1~' to 'o~.e~.jdt'. + *

                                                      + */ + public static final String APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW = "PackagesView.pkgNamePatternForPackagesView"; //$NON-NLS-1$ + + /** + * A named preference that controls if package name compression is turned on + * or off. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @see #APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW + */ + public static final String APPEARANCE_COMPRESS_PACKAGE_NAMES = "net.sourceforge.phpdt.ui.compresspackagenames"; //$NON-NLS-1$ + + /** + * A named preference that controls if empty inner packages are folded in + * the hierarchical mode of the package explorer. + *

                                                      + * Value is of type Boolean: if true empty + * inner packages are folded. + *

                                                      + * + * @since 2.1 + */ + public static final String APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER = "net.sourceforge.phpdt.ui.flatPackagesInPackageExplorer"; //$NON-NLS-1$ + + /** + * A named preference that defines how member elements are ordered by the + * Java views using the JavaElementSorter. + *

                                                      + * Value is of type String: A comma separated list of the + * following entries. Each entry must be in the list, no duplication. List + * order defines the sort order. + *

                                                        + *
                                                      • T : Types
                                                      • + *
                                                      • C : Constructors
                                                      • + *
                                                      • I : Initializers
                                                      • + *
                                                      • M : Methods
                                                      • + *
                                                      • F : Fields
                                                      • + *
                                                      • SI : Static Initializers
                                                      • + *
                                                      • SM : Static Methods
                                                      • + *
                                                      • SF : Static Fields
                                                      • + *
                                                      + *

                                                      + * + * @since 2.1 + */ + public static final String APPEARANCE_MEMBER_SORT_ORDER = "outlinesortoption"; //$NON-NLS-1$ + + /** + * A named preference that defines how member elements are ordered by + * visibility in the Java views using the JavaElementSorter. + *

                                                      + * Value is of type String: A comma separated list of the + * following entries. Each entry must be in the list, no duplication. List + * order defines the sort order. + *

                                                        + *
                                                      • B : Public
                                                      • + *
                                                      • V : Private
                                                      • + *
                                                      • R : Protected
                                                      • + *
                                                      • D : Default
                                                      • + *
                                                      + *

                                                      + * + * @since 3.0 + */ + public static final String APPEARANCE_VISIBILITY_SORT_ORDER = "net.sourceforge.phpdt.ui.visibility.order"; //$NON-NLS-1$ + + /** + * A named preferences that controls if Java elements are also sorted by + * visibility. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public static final String APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER = "net.sourceforge.phpdt.ui.enable.visibility.order"; //$NON-NLS-1$ + + /** + * A named preference that controls if prefix removal during setter/getter + * generation is turned on or off. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public static final String CODEGEN_USE_GETTERSETTER_PREFIX = "net.sourceforge.phpdt.ui.gettersetter.prefix.enable"; //$NON-NLS-1$ + + /** + * A named preference that holds a list of prefixes to be removed from a + * local variable to compute setter and gettter names. + *

                                                      + * Value is of type String: comma separated list of prefixed + *

                                                      + * + * @see #CODEGEN_USE_GETTERSETTER_PREFIX + */ + public static final String CODEGEN_GETTERSETTER_PREFIX = "net.sourceforge.phpdt.ui.gettersetter.prefix.list"; //$NON-NLS-1$ + + /** + * A named preference that controls if suffix removal during setter/getter + * generation is turned on or off. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public static final String CODEGEN_USE_GETTERSETTER_SUFFIX = "net.sourceforge.phpdt.ui.gettersetter.suffix.enable"; //$NON-NLS-1$ + + /** + * A named preference that holds a list of suffixes to be removed from a + * local variable to compute setter and getter names. + *

                                                      + * Value is of type String: comma separated list of suffixes + *

                                                      + * + * @see #CODEGEN_USE_GETTERSETTER_SUFFIX + */ + public static final String CODEGEN_GETTERSETTER_SUFFIX = "net.sourceforge.phpdt.ui.gettersetter.suffix.list"; //$NON-NLS-1$ + + /** * A named preference that controls whether the keyword "this" will be added * automatically to field accesses in generated methods. *

                                                      * Value is of type Boolean. *

                                                      + * * @since 3.0 */ - public static final String CODEGEN_KEYWORD_THIS= "org.eclipse.jdt.ui.keywordthis"; //$NON-NLS-1$ + public static final String CODEGEN_KEYWORD_THIS = "org.eclipse.jdt.ui.keywordthis"; //$NON-NLS-1$ /** - * A named preference that controls whether to use the prefix "is" or the prefix "get" for - * automatically created getters which return a boolean field. + * A named preference that controls whether to use the prefix "is" or the + * prefix "get" for automatically created getters which return a boolean + * field. *

                                                      * Value is of type Boolean. *

                                                      + * * @since 3.0 */ - public static final String CODEGEN_IS_FOR_GETTERS= "org.eclipse.jdt.ui.gettersetter.use.is"; //$NON-NLS-1$ + public static final String CODEGEN_IS_FOR_GETTERS = "org.eclipse.jdt.ui.gettersetter.use.is"; //$NON-NLS-1$ + + /** + * A named preference that defines the preferred variable names for + * exceptions in catch clauses. + *

                                                      + * Value is of type String. + *

                                                      + * + * @since 3.0 + */ + public static final String CODEGEN_EXCEPTION_VAR_NAME = "org.eclipse.jdt.ui.exception.name"; //$NON-NLS-1$ + + /** + * A named preference that controls if comment stubs will be added + * automatically to newly created types and methods. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public static final String CODEGEN_ADD_COMMENTS = "net.sourceforge.phpdt.ui.phpdoc"; //$NON-NLS-1$ + + /** + * A name preference that controls if a JavaDoc stub gets added to newly + * created types and methods. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @deprecated Use CODEGEN_ADD_COMMENTS instead (Name is more precise). + */ + // public static final String CODEGEN__JAVADOC_STUBS = CODEGEN_ADD_COMMENTS; + // //$NON-NLS-1$ + /** + * A named preference that controls if a non-phpdoc comment gets added to + * methods generated via the "Override Methods" operation. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public static final String CODEGEN__NON_JAVADOC_COMMENTS = "net.sourceforge.phpdt.ui.seecomments"; //$NON-NLS-1$ + + /** + * A named preference that controls if a file comment gets added to newly + * created files. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public static final String CODEGEN__FILE_COMMENTS = "net.sourceforge.phpdt.ui.filecomments"; //$NON-NLS-1$ + + /** + * A named preference that holds a list of comma separated package names. + * The list specifies the import order used by the "Organize Imports" + * opeation. + *

                                                      + * Value is of type String: semicolon separated list of + * package names + *

                                                      + */ + // public static final String ORGIMPORTS_IMPORTORDER = + // "net.sourceforge.phpdt.ui.importorder"; //$NON-NLS-1$ + /** + * A named preference that specifies the number of imports added before a + * star-import declaration is used. + *

                                                      + * Value is of type Int: positive value specifing the number + * of non star-import is used + *

                                                      + */ + public static final String ORGIMPORTS_ONDEMANDTHRESHOLD = "net.sourceforge.phpdt.ui.ondemandthreshold"; //$NON-NLS-1$ + + /** + * A named preferences that controls if types that start with a lower case + * letters get added by the "Organize Import" operation. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public static final String ORGIMPORTS_IGNORELOWERCASE = "net.sourceforge.phpdt.ui.ignorelowercasenames"; //$NON-NLS-1$ + + /** + * A named preference that speficies whether children of a compilation unit + * are shown in the package explorer. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public static final String SHOW_CU_CHILDREN = "net.sourceforge.phpdt.ui.packages.cuchildren"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the package explorer's selection + * is linked to the active editor. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public static final String LINK_PACKAGES_TO_EDITOR = "net.sourceforge.phpdt.ui.packages.linktoeditor"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the hierarchy view's selection + * is linked to the active editor. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public static final String LINK_TYPEHIERARCHY_TO_EDITOR = "net.sourceforge.phpdt.ui.packages.linktypehierarchytoeditor"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the browsing view's selection is + * linked to the active editor. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public static final String LINK_BROWSING_VIEW_TO_EDITOR = "net.sourceforge.phpdt.ui.browsing.linktoeditor"; //$NON-NLS-1$ + + /** + * A named preference that controls whether new projects are generated using + * source and output folder. + *

                                                      + * Value is of type Boolean. if true new + * projects are created with a source and output folder. If + * false source and output folder equals to the project. + *

                                                      + */ + public static final String SRCBIN_FOLDERS_IN_NEWPROJ = "net.sourceforge.phpdt.ui.wizards.srcBinFoldersInNewProjects"; //$NON-NLS-1$ + + /** + * A named preference that specifies the source folder name used when + * creating a new Java project. Value is inactive if + * SRCBIN_FOLDERS_IN_NEWPROJ is set to false. + *

                                                      + * Value is of type String. + *

                                                      + * + * @see #SRCBIN_FOLDERS_IN_NEWPROJ + */ + public static final String SRCBIN_SRCNAME = "net.sourceforge.phpdt.ui.wizards.srcBinFoldersSrcName"; //$NON-NLS-1$ + + /** + * A named preference that specifies the output folder name used when + * creating a new Java project. Value is inactive if + * SRCBIN_FOLDERS_IN_NEWPROJ is set to false. + *

                                                      + * Value is of type String. + *

                                                      + * + * @see #SRCBIN_FOLDERS_IN_NEWPROJ + */ + public static final String SRCBIN_BINNAME = "net.sourceforge.phpdt.ui.wizards.srcBinFoldersBinName"; //$NON-NLS-1$ + + /** + * A named preference that holds a list of possible JRE libraries used by + * the New Java Project wizard. An library consists of a description and an + * arbitrary number of IClasspathEntrys, that will represent + * the JRE on the new project's classpath. + *

                                                      + * Value is of type String: a semicolon separated list of + * encoded JRE libraries. NEWPROJECT_JRELIBRARY_INDEX defines + * the currently used library. Clients should use the method + * encodeJRELibrary to encode a JRE library into a string and + * the methods decodeJRELibraryDescription(String) and + * decodeJRELibraryClasspathEntries(String) + * to decode the description and the array of classpath entries from an + * encoded string. + *

                                                      + * + * @see #NEWPROJECT_JRELIBRARY_INDEX + * @see #encodeJRELibrary(String, IClasspathEntry[]) + * @see #decodeJRELibraryDescription(String) + * @see #decodeJRELibraryClasspathEntries(String) + */ + public static final String NEWPROJECT_JRELIBRARY_LIST = "net.sourceforge.phpdt.ui.wizards.jre.list"; //$NON-NLS-1$ + + /** + * A named preferences that specifies the current active JRE library. + *

                                                      + * Value is of type Int: an index into the list of possible + * JRE libraries. + *

                                                      + * + * @see #NEWPROJECT_JRELIBRARY_LIST + */ + public static final String NEWPROJECT_JRELIBRARY_INDEX = "net.sourceforge.phpdt.ui.wizards.jre.index"; //$NON-NLS-1$ + + /** + * A named preference that controls if a new type hierarchy gets opened in a + * new type hierarchy perspective or inside the type hierarchy view part. + *

                                                      + * Value is of type String: possible values are + * OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE + * or + * OPEN_TYPE_HIERARCHY_IN_VIEW_PART. + *

                                                      + * + * @see #OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE + * @see #OPEN_TYPE_HIERARCHY_IN_VIEW_PART + */ + public static final String OPEN_TYPE_HIERARCHY = "net.sourceforge.phpdt.ui.openTypeHierarchy"; //$NON-NLS-1$ + + /** + * A string value used by the named preference + * OPEN_TYPE_HIERARCHY. + * + * @see #OPEN_TYPE_HIERARCHY + */ + public static final String OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE = "perspective"; //$NON-NLS-1$ + + /** + * A string value used by the named preference + * OPEN_TYPE_HIERARCHY. + * + * @see #OPEN_TYPE_HIERARCHY + */ + public static final String OPEN_TYPE_HIERARCHY_IN_VIEW_PART = "viewPart"; //$NON-NLS-1$ + + /** + * A named preference that controls the behaviour when double clicking on a + * container in the packages view. + *

                                                      + * Value is of type String: possible values are + * DOUBLE_CLICK_GOES_INTO + * or + * DOUBLE_CLICK_EXPANDS. + *

                                                      + * + * @see #DOUBLE_CLICK_EXPANDS + * @see #DOUBLE_CLICK_GOES_INTO + */ + public static final String DOUBLE_CLICK = "packageview.doubleclick"; //$NON-NLS-1$ + + /** + * A string value used by the named preference DOUBLE_CLICK. + * + * @see #DOUBLE_CLICK + */ + public static final String DOUBLE_CLICK_GOES_INTO = "packageview.gointo"; //$NON-NLS-1$ + + /** + * A string value used by the named preference DOUBLE_CLICK. + * + * @see #DOUBLE_CLICK + */ + public static final String DOUBLE_CLICK_EXPANDS = "packageview.doubleclick.expands"; //$NON-NLS-1$ + + /** + * A named preference that controls whether Java views update their + * presentation while editing or when saving the content of an editor. + *

                                                      + * Value is of type String: possible values are + * UPDATE_ON_SAVE + * or + * UPDATE_WHILE_EDITING. + *

                                                      + * + * @see #UPDATE_ON_SAVE + * @see #UPDATE_WHILE_EDITING + */ + public static final String UPDATE_JAVA_VIEWS = "JavaUI.update"; //$NON-NLS-1$ + + /** + * A string value used by the named preference + * UPDATE_JAVA_VIEWS + * + * @see #UPDATE_JAVA_VIEWS + */ + public static final String UPDATE_ON_SAVE = "JavaUI.update.onSave"; //$NON-NLS-1$ + /** + * A string value used by the named preference + * UPDATE_JAVA_VIEWS + * + * @see #UPDATE_JAVA_VIEWS + */ + public static final String UPDATE_WHILE_EDITING = "JavaUI.update.whileEditing"; //$NON-NLS-1$ /** - * A named preference that defines the preferred variable names for exceptions in - * catch clauses. + * A named preference that holds the path of the Javadoc command used by the + * Javadoc creation wizard. *

                                                      * Value is of type String. *

                                                      + */ + public static final String JAVADOC_COMMAND = "command"; //$NON-NLS-1$ + + /** + * A named preference that defines whether hint to make hover sticky should + * be shown. + * + * @see JavaUI + * @since 3.0 + */ + public static final String EDITOR_SHOW_TEXT_HOVER_AFFORDANCE = "PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE"; //$NON-NLS-1$ + + /** + * A named preference that defines the key for the hover modifiers. + * + * @see JavaUI + * @since 2.1 + */ + public static final String EDITOR_TEXT_HOVER_MODIFIERS = "hoverModifiers"; //$NON-NLS-1$ + + /** + * The id of the best match hover contributed for extension point + * javaEditorTextHovers. + * + * @since 2.1 + */ + public static String ID_BESTMATCH_HOVER = "net.sourceforge.phpdt.ui.BestMatchHover"; //$NON-NLS-1$ + + /** + * The id of the source code hover contributed for extension point + * javaEditorTextHovers. + * + * @since 2.1 + */ + public static String ID_SOURCE_HOVER = "net.sourceforge.phpdt.ui.JavaSourceHover"; //$NON-NLS-1$ + + /** + * The id of the problem hover contributed for extension point + * javaEditorTextHovers. + * + * @since 2.1 + */ + public static String ID_PROBLEM_HOVER = "net.sourceforge.phpdt.ui.ProblemHover"; //$NON-NLS-1$ + + /** + * A named preference that controls whether bracket matching highlighting is + * turned on or off. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String EDITOR_MATCHING_BRACKETS = "matchingBrackets"; //$NON-NLS-1$ + + /** + * A named preference that holds the color used to highlight matching + * brackets. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_MATCHING_BRACKETS_COLOR = "matchingBracketsColor"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the current line highlighting is + * turned on or off. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String EDITOR_CURRENT_LINE = "currentLine"; //$NON-NLS-1$ + + /** + * A named preference that holds the color used to highlight the current + * line. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_CURRENT_LINE_COLOR = "currentLineColor"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the print margin is turned on or + * off. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String EDITOR_PRINT_MARGIN = "printMargin"; //$NON-NLS-1$ + + /** + * A named preference that holds the color used to render the print margin. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_PRINT_MARGIN_COLOR = "printMarginColor"; //$NON-NLS-1$ + + /** + * Print margin column. Int value. + */ + public final static String EDITOR_PRINT_MARGIN_COLUMN = "printMarginColumn"; //$NON-NLS-1$ + + /** + * A named preference that holds the color used for the find/replace scope. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_FIND_SCOPE_COLOR = AbstractTextEditor.PREFERENCE_COLOR_FIND_SCOPE; + + /** + * A named preference that specifies if the editor uses spaces for tabs. + *

                                                      + * Value is of type Boolean. If true spaces + * instead of tabs are used in the editor. If false the + * editor inserts a tab character when pressing the tab key. + *

                                                      + */ + public final static String EDITOR_SPACES_FOR_TABS = "spacesForTabs"; //$NON-NLS-1$ + + /** + * A named preference that holds the number of spaces used per tab in the + * editor. + *

                                                      + * Value is of type Int: positive int value specifying the + * number of spaces per tab. + *

                                                      + */ + public final static String EDITOR_TAB_WIDTH = AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH; // "net.sourceforge.phpdt.ui.editor.tab.width"; + + // //$NON-NLS-1$ + + /** + * A named preference that controls whether the outline view selection + * should stay in sync with with the element at the current cursor position. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE = "JavaEditor.SyncOutlineOnCursorMove"; //$NON-NLS-1$ + + /** + * A named preference that controls if correction indicators are shown in + * the UI. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String EDITOR_CORRECTION_INDICATION = "JavaEditor.ShowTemporaryProblem"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the editor shows problem + * indicators in text (squiggly lines). + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + // public final static String EDITOR_PROBLEM_INDICATION = + // "problemIndication"; //$NON-NLS-1$ + /** + * A named preference that holds the color used to render problem + * indicators. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see #EDITOR_PROBLEM_INDICATION + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + // public final static String EDITOR_PROBLEM_INDICATION_COLOR = + // "problemIndicationColor"; //$NON-NLS-1$ + /** + * PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR; A named preference + * that controls whether the editor shows warning indicators in text + * (squiggly lines). + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + // public final static String EDITOR_WARNING_INDICATION = + // "warningIndication"; //$NON-NLS-1$ + /** + * A named preference that holds the color used to render warning + * indicators. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see #EDITOR_WARNING_INDICATION + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + // public final static String EDITOR_WARNING_INDICATION_COLOR = + // "warningIndicationColor"; //$NON-NLS-1$ + /** + * A named preference that controls whether the editor shows task indicators + * in text (squiggly lines). + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String EDITOR_TASK_INDICATION = "taskIndication"; //$NON-NLS-1$ + + /** + * A named preference that holds the color used to render task indicators. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see #EDITOR_TASK_INDICATION + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_TASK_INDICATION_COLOR = "taskIndicationColor"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the editor shows bookmark + * indicators in text (squiggly lines). + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String EDITOR_BOOKMARK_INDICATION = "bookmarkIndication"; //$NON-NLS-1$ + + /** + * A named preference that holds the color used to render bookmark + * indicators. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see #EDITOR_BOOKMARK_INDICATION + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + * @since 2.1 + */ + public final static String EDITOR_BOOKMARK_INDICATION_COLOR = "bookmarkIndicationColor"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the editor shows search + * indicators in text (squiggly lines). + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String EDITOR_SEARCH_RESULT_INDICATION = "searchResultIndication"; //$NON-NLS-1$ + + /** + * A named preference that holds the color used to render search indicators. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see #EDITOR_SEARCH_RESULT_INDICATION + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + * @since 2.1 + */ + public final static String EDITOR_SEARCH_RESULT_INDICATION_COLOR = "searchResultIndicationColor"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the editor shows unknown + * indicators in text (squiggly lines). + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String EDITOR_UNKNOWN_INDICATION = "othersIndication"; //$NON-NLS-1$ + + /** + * A named preference that holds the color used to render unknown + * indicators. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see #EDITOR_UNKNOWN_INDICATION + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + * @since 2.1 + */ + public final static String EDITOR_UNKNOWN_INDICATION_COLOR = "othersIndicationColor"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the overview ruler shows error + * indicators. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER = "errorIndicationInOverviewRuler"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the overview ruler shows warning + * indicators. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER = "warningIndicationInOverviewRuler"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the overview ruler shows task + * indicators. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER = "taskIndicationInOverviewRuler"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the overview ruler shows + * bookmark indicators. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER = "bookmarkIndicationInOverviewRuler"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the overview ruler shows search + * result indicators. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER = "searchResultIndicationInOverviewRuler"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the overview ruler shows unknown + * indicators. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER = "othersIndicationInOverviewRuler"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'close strings' feature is + * enabled in PHP mode + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String EDITOR_CLOSE_STRINGS_DQ_PHP = "closeStringsPHPDQ"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'close strings' feature is + * enabled in PHP mode + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String EDITOR_CLOSE_STRINGS_SQ_PHP = "closeStringsPHPSQ"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'close brackets' feature is + * enabled in PHP mode + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String EDITOR_CLOSE_BRACKETS_PHP = "closeBracketsPHP"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'wrap words' feature is + * enabled. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String EDITOR_WRAP_WORDS = "wrapWords"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'wrap strings' feature is + * enabled. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String EDITOR_WRAP_STRINGS_DQ = "wrapStringsDQ"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'escape strings' feature is + * enabled. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String EDITOR_ESCAPE_STRINGS_DQ = "escapeStringsDQ"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'wrap strings' feature is + * enabled. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String EDITOR_WRAP_STRINGS_SQ = "wrapStringsDQ"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'escape strings' feature is + * enabled. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String EDITOR_ESCAPE_STRINGS_SQ = "escapeStringsSQ"; //$NON-NLS-1$ + + /** + * A named preference that controls if content assist inserts the common + * prefix of all proposals before presenting choices. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String CODEASSIST_PREFIX_COMPLETION = "content_assist_prefix_completion"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'close braces' feature is + * enabled. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String EDITOR_CLOSE_BRACES = "closeBraces"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'close php docs' feature is + * enabled. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String EDITOR_CLOSE_JAVADOCS = "closeJavaDocs"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'add JavaDoc tags' feature + * is enabled. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String EDITOR_ADD_JAVADOC_TAGS = "addJavaDocTags"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'format Javadoc tags' + * feature is enabled. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String EDITOR_FORMAT_JAVADOCS = "formatJavaDocs"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'smart paste' feature is + * enabled. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String EDITOR_SMART_PASTE = "smartPaste"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'close strings' feature is + * enabled in HTML mode + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String EDITOR_CLOSE_STRINGS_HTML = "closeStringsHTML"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'close brackets' feature is + * enabled in HTML mode + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String EDITOR_CLOSE_BRACKETS_HTML = "closeBracketsHTML"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'smart home-end' feature is + * enabled. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String EDITOR_SMART_HOME_END = AbstractTextEditor.PREFERENCE_NAVIGATION_SMART_HOME_END; + + /** + * A named preference that controls whether the 'sub-word navigation' + * feature is enabled. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String EDITOR_SUB_WORD_NAVIGATION = "subWordNavigation"; //$NON-NLS-1$ + + /** + * A named preference that controls if temporary problems are evaluated and + * shown in the UI. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String EDITOR_EVALUTE_TEMPORARY_PROBLEMS = "handleTemporaryProblems"; //$NON-NLS-1$ + + /** + * A named preference that controls if the overview ruler is shown in the + * UI. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String EDITOR_OVERVIEW_RULER = "overviewRuler"; //$NON-NLS-1$ + + /** + * A named preference that controls if the line number ruler is shown in the + * UI. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String EDITOR_LINE_NUMBER_RULER = "lineNumberRuler"; //$NON-NLS-1$ + + /** + * A named preference that holds the color used to render line numbers + * inside the line number ruler. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + * @see #EDITOR_LINE_NUMBER_RULER + */ + public final static String EDITOR_LINE_NUMBER_RULER_COLOR = "lineNumberColor"; //$NON-NLS-1$ + + /** + * A named preference that holds the color used to render linked positions + * inside code templates. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_LINKED_POSITION_COLOR = "linkedPositionColor"; //$NON-NLS-1$ + + /** + * A named preference that holds the color used as the text foreground. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_FOREGROUND_COLOR = AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND; + + /** + * A named preference that describes if the system default foreground color + * is used as the text foreground. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String EDITOR_FOREGROUND_DEFAULT_COLOR = AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT; + + /** + * A named preference that holds the color used as the text background. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_BACKGROUND_COLOR = AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND; + + /** + * A named preference that describes if the system default background color + * is used as the text foreground. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String EDITOR_BACKGROUND_DEFAULT_COLOR = AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT; + + /** + * Preference key suffix for bold text style preference keys. + */ + public static final String EDITOR_BOLD_SUFFIX = "_bold"; //$NON-NLS-1$ + + /** + * Preference key suffix for bold text style preference keys. + */ + public static final String EDITOR_ITALIC_SUFFIX = "_italic"; //$NON-NLS-1$ + + /** + * A named preference that holds the color used to render multi line + * comments. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_MULTI_LINE_COMMENT_COLOR = IPreferenceConstants.PHP_MULTILINE_COMMENT; + + /** + * The symbolic font name for the Java editor text font (value + * "net.sourceforge.phpdt.ui.editors.textfont"). + * + * @since 2.1 + */ + public final static String EDITOR_TEXT_FONT = "net.sourceforge.phpdt.ui.editors.textfont"; //$NON-NLS-1$ + + /** + * A named preference that controls whether multi line comments are rendered + * in bold. + *

                                                      + * Value is of type Boolean. If true multi + * line comments are rendered in bold. If false the are + * rendered using no font style attribute. + *

                                                      + */ + public final static String EDITOR_MULTI_LINE_COMMENT_BOLD = IPreferenceConstants.PHP_MULTILINE_COMMENT + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render single line + * comments. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_SINGLE_LINE_COMMENT_COLOR = IPreferenceConstants.PHP_SINGLELINE_COMMENT; + + /** + * A named preference that controls whether sinle line comments are rendered + * in bold. + *

                                                      + * Value is of type Boolean. If true single + * line comments are rendered in bold. If false the are + * rendered using no font style attribute. + *

                                                      + */ + public final static String EDITOR_SINGLE_LINE_COMMENT_BOLD = IPreferenceConstants.PHP_SINGLELINE_COMMENT + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render operators and + * brackets. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + * @since 3.0 + */ + public final static String EDITOR_PHP_OPERATOR_COLOR = IPreferenceConstants.PHP_OPERATOR; + + /** + * A named preference that controls whether operators and brackets are + * rendered in bold. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String EDITOR_PHP_OPERATOR_BOLD = IPreferenceConstants.PHP_OPERATOR + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that controls whether operators and brackets are + * rendered in italic. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String EDITOR_PHP_OPERATOR_ITALIC = IPreferenceConstants.PHP_OPERATOR + + EDITOR_ITALIC_SUFFIX; + + /** + * A named preference that holds the color used to render operators and + * brackets. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + * @since 3.0 + */ + public final static String EDITOR_PHP_BRACE_OPERATOR_COLOR = IPreferenceConstants.PHP_BRACE_OPERATOR; + + /** + * A named preference that controls whether operators and brackets are + * rendered in bold. + *

                                                      + * Value is of type Boolean. + *

                                                      + * * @since 3.0 */ - public static final String CODEGEN_EXCEPTION_VAR_NAME= "org.eclipse.jdt.ui.exception.name"; //$NON-NLS-1$ - - /** - * A named preference that controls if comment stubs will be added automatically to newly created types and methods. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public static final String CODEGEN_ADD_COMMENTS = "net.sourceforge.phpdt.ui.phpdoc"; //$NON-NLS-1$ - - /** - * A name preference that controls if a JavaDoc stub gets added to newly created types and methods. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @deprecated Use CODEGEN_ADD_COMMENTS instead (Name is more precise). - */ - // public static final String CODEGEN__JAVADOC_STUBS = CODEGEN_ADD_COMMENTS; //$NON-NLS-1$ - /** - * A named preference that controls if a non-phpdoc comment gets added to methods generated via the "Override Methods" operation. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public static final String CODEGEN__NON_JAVADOC_COMMENTS = "net.sourceforge.phpdt.ui.seecomments"; //$NON-NLS-1$ - - /** - * A named preference that controls if a file comment gets added to newly created files. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public static final String CODEGEN__FILE_COMMENTS = "net.sourceforge.phpdt.ui.filecomments"; //$NON-NLS-1$ - - /** - * A named preference that holds a list of comma separated package names. The list specifies the import order used by the - * "Organize Imports" opeation. - *

                                                      - * Value is of type String: semicolon separated list of package names - *

                                                      - */ -// public static final String ORGIMPORTS_IMPORTORDER = "net.sourceforge.phpdt.ui.importorder"; //$NON-NLS-1$ - - /** - * A named preference that specifies the number of imports added before a star-import declaration is used. - *

                                                      - * Value is of type Int: positive value specifing the number of non star-import is used - *

                                                      - */ - public static final String ORGIMPORTS_ONDEMANDTHRESHOLD = "net.sourceforge.phpdt.ui.ondemandthreshold"; //$NON-NLS-1$ - - /** - * A named preferences that controls if types that start with a lower case letters get added by the "Organize Import" operation. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public static final String ORGIMPORTS_IGNORELOWERCASE = "net.sourceforge.phpdt.ui.ignorelowercasenames"; //$NON-NLS-1$ - - /** - * A named preference that speficies whether children of a compilation unit are shown in the package explorer. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public static final String SHOW_CU_CHILDREN = "net.sourceforge.phpdt.ui.packages.cuchildren"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the package explorer's selection is linked to the active editor. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public static final String LINK_PACKAGES_TO_EDITOR = "net.sourceforge.phpdt.ui.packages.linktoeditor"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the hierarchy view's selection is linked to the active editor. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public static final String LINK_TYPEHIERARCHY_TO_EDITOR = "net.sourceforge.phpdt.ui.packages.linktypehierarchytoeditor"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the browsing view's selection is linked to the active editor. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public static final String LINK_BROWSING_VIEW_TO_EDITOR = "net.sourceforge.phpdt.ui.browsing.linktoeditor"; //$NON-NLS-1$ - - /** - * A named preference that controls whether new projects are generated using source and output folder. - *

                                                      - * Value is of type Boolean. if true new projects are created with a source and output folder. If - * false source and output folder equals to the project. - *

                                                      - */ - public static final String SRCBIN_FOLDERS_IN_NEWPROJ = "net.sourceforge.phpdt.ui.wizards.srcBinFoldersInNewProjects"; //$NON-NLS-1$ - - /** - * A named preference that specifies the source folder name used when creating a new Java project. Value is inactive if - * SRCBIN_FOLDERS_IN_NEWPROJ is set to false. - *

                                                      - * Value is of type String. - *

                                                      - * - * @see #SRCBIN_FOLDERS_IN_NEWPROJ - */ - public static final String SRCBIN_SRCNAME = "net.sourceforge.phpdt.ui.wizards.srcBinFoldersSrcName"; //$NON-NLS-1$ - - /** - * A named preference that specifies the output folder name used when creating a new Java project. Value is inactive if - * SRCBIN_FOLDERS_IN_NEWPROJ is set to false. - *

                                                      - * Value is of type String. - *

                                                      - * - * @see #SRCBIN_FOLDERS_IN_NEWPROJ - */ - public static final String SRCBIN_BINNAME = "net.sourceforge.phpdt.ui.wizards.srcBinFoldersBinName"; //$NON-NLS-1$ - - /** - * A named preference that holds a list of possible JRE libraries used by the New Java Project wizard. An library consists of a - * description and an arbitrary number of IClasspathEntrys, that will represent the JRE on the new project's - * classpath. - *

                                                      - * Value is of type String: a semicolon separated list of encoded JRE libraries. - * NEWPROJECT_JRELIBRARY_INDEX defines the currently used library. Clients should use the method - * encodeJRELibrary to encode a JRE library into a string and the methods - * decodeJRELibraryDescription(String) and - * decodeJRELibraryClasspathEntries(String) to decode the - * description and the array of classpath entries from an encoded string. - *

                                                      - * - * @see #NEWPROJECT_JRELIBRARY_INDEX - * @see #encodeJRELibrary(String, IClasspathEntry[]) - * @see #decodeJRELibraryDescription(String) - * @see #decodeJRELibraryClasspathEntries(String) - */ - public static final String NEWPROJECT_JRELIBRARY_LIST = "net.sourceforge.phpdt.ui.wizards.jre.list"; //$NON-NLS-1$ - - /** - * A named preferences that specifies the current active JRE library. - *

                                                      - * Value is of type Int: an index into the list of possible JRE libraries. - *

                                                      - * - * @see #NEWPROJECT_JRELIBRARY_LIST - */ - public static final String NEWPROJECT_JRELIBRARY_INDEX = "net.sourceforge.phpdt.ui.wizards.jre.index"; //$NON-NLS-1$ - - /** - * A named preference that controls if a new type hierarchy gets opened in a new type hierarchy perspective or inside the type - * hierarchy view part. - *

                                                      - * Value is of type String: possible values are - * OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE or - * OPEN_TYPE_HIERARCHY_IN_VIEW_PART. - *

                                                      - * - * @see #OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE - * @see #OPEN_TYPE_HIERARCHY_IN_VIEW_PART - */ - public static final String OPEN_TYPE_HIERARCHY = "net.sourceforge.phpdt.ui.openTypeHierarchy"; //$NON-NLS-1$ - - /** - * A string value used by the named preference OPEN_TYPE_HIERARCHY. - * - * @see #OPEN_TYPE_HIERARCHY - */ - public static final String OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE = "perspective"; //$NON-NLS-1$ - - /** - * A string value used by the named preference OPEN_TYPE_HIERARCHY. - * - * @see #OPEN_TYPE_HIERARCHY - */ - public static final String OPEN_TYPE_HIERARCHY_IN_VIEW_PART = "viewPart"; //$NON-NLS-1$ - - /** - * A named preference that controls the behaviour when double clicking on a container in the packages view. - *

                                                      - * Value is of type String: possible values are - * DOUBLE_CLICK_GOES_INTO or - * DOUBLE_CLICK_EXPANDS. - *

                                                      - * - * @see #DOUBLE_CLICK_EXPANDS - * @see #DOUBLE_CLICK_GOES_INTO - */ - public static final String DOUBLE_CLICK = "packageview.doubleclick"; //$NON-NLS-1$ - - /** - * A string value used by the named preference DOUBLE_CLICK. - * - * @see #DOUBLE_CLICK - */ - public static final String DOUBLE_CLICK_GOES_INTO = "packageview.gointo"; //$NON-NLS-1$ - - /** - * A string value used by the named preference DOUBLE_CLICK. - * - * @see #DOUBLE_CLICK - */ - public static final String DOUBLE_CLICK_EXPANDS = "packageview.doubleclick.expands"; //$NON-NLS-1$ - - /** - * A named preference that controls whether Java views update their presentation while editing or when saving the content of an - * editor. - *

                                                      - * Value is of type String: possible values are - * UPDATE_ON_SAVE or - * UPDATE_WHILE_EDITING. - *

                                                      - * - * @see #UPDATE_ON_SAVE - * @see #UPDATE_WHILE_EDITING - */ - public static final String UPDATE_JAVA_VIEWS = "JavaUI.update"; //$NON-NLS-1$ - - /** - * A string value used by the named preference UPDATE_JAVA_VIEWS - * - * @see #UPDATE_JAVA_VIEWS - */ - public static final String UPDATE_ON_SAVE = "JavaUI.update.onSave"; //$NON-NLS-1$ - - /** - * A string value used by the named preference UPDATE_JAVA_VIEWS - * - * @see #UPDATE_JAVA_VIEWS - */ - public static final String UPDATE_WHILE_EDITING = "JavaUI.update.whileEditing"; //$NON-NLS-1$ - - /** - * A named preference that holds the path of the Javadoc command used by the Javadoc creation wizard. - *

                                                      - * Value is of type String. - *

                                                      - */ - public static final String JAVADOC_COMMAND = "command"; //$NON-NLS-1$ - - /** - * A named preference that defines whether hint to make hover sticky should be shown. - * - * @see JavaUI - * @since 3.0 - */ - public static final String EDITOR_SHOW_TEXT_HOVER_AFFORDANCE = "PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE"; //$NON-NLS-1$ - - /** - * A named preference that defines the key for the hover modifiers. - * - * @see JavaUI - * @since 2.1 - */ - public static final String EDITOR_TEXT_HOVER_MODIFIERS = "hoverModifiers"; //$NON-NLS-1$ - - /** - * The id of the best match hover contributed for extension point javaEditorTextHovers. - * - * @since 2.1 - */ - public static String ID_BESTMATCH_HOVER = "net.sourceforge.phpdt.ui.BestMatchHover"; //$NON-NLS-1$ - - /** - * The id of the source code hover contributed for extension point javaEditorTextHovers. - * - * @since 2.1 - */ - public static String ID_SOURCE_HOVER = "net.sourceforge.phpdt.ui.JavaSourceHover"; //$NON-NLS-1$ - - /** - * The id of the problem hover contributed for extension point javaEditorTextHovers. - * - * @since 2.1 - */ - public static String ID_PROBLEM_HOVER = "net.sourceforge.phpdt.ui.ProblemHover"; //$NON-NLS-1$ - - /** - * A named preference that controls whether bracket matching highlighting is turned on or off. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String EDITOR_MATCHING_BRACKETS = "matchingBrackets"; //$NON-NLS-1$ - - /** - * A named preference that holds the color used to highlight matching brackets. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_MATCHING_BRACKETS_COLOR = "matchingBracketsColor"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the current line highlighting is turned on or off. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String EDITOR_CURRENT_LINE = "currentLine"; //$NON-NLS-1$ - - /** - * A named preference that holds the color used to highlight the current line. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_CURRENT_LINE_COLOR = "currentLineColor"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the print margin is turned on or off. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String EDITOR_PRINT_MARGIN = "printMargin"; //$NON-NLS-1$ - - /** - * A named preference that holds the color used to render the print margin. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_PRINT_MARGIN_COLOR = "printMarginColor"; //$NON-NLS-1$ - - /** - * Print margin column. Int value. - */ - public final static String EDITOR_PRINT_MARGIN_COLUMN = "printMarginColumn"; //$NON-NLS-1$ - - /** - * A named preference that holds the color used for the find/replace scope. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_FIND_SCOPE_COLOR = AbstractTextEditor.PREFERENCE_COLOR_FIND_SCOPE; - - /** - * A named preference that specifies if the editor uses spaces for tabs. - *

                                                      - * Value is of type Boolean. If true spaces instead of tabs are used in the editor. If - * false the editor inserts a tab character when pressing the tab key. - *

                                                      - */ - public final static String EDITOR_SPACES_FOR_TABS = "spacesForTabs"; //$NON-NLS-1$ - - /** - * A named preference that holds the number of spaces used per tab in the editor. - *

                                                      - * Value is of type Int: positive int value specifying the number of spaces per tab. - *

                                                      - */ - public final static String EDITOR_TAB_WIDTH = AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH; //"net.sourceforge.phpdt.ui.editor.tab.width"; - - // //$NON-NLS-1$ - - /** - * A named preference that controls whether the outline view selection should stay in sync with with the element at the current - * cursor position. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE = "JavaEditor.SyncOutlineOnCursorMove"; //$NON-NLS-1$ - - /** - * A named preference that controls if correction indicators are shown in the UI. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String EDITOR_CORRECTION_INDICATION = "JavaEditor.ShowTemporaryProblem"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the editor shows problem indicators in text (squiggly lines). - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - // public final static String EDITOR_PROBLEM_INDICATION = "problemIndication"; //$NON-NLS-1$ - /** - * A named preference that holds the color used to render problem indicators. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see #EDITOR_PROBLEM_INDICATION - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - // public final static String EDITOR_PROBLEM_INDICATION_COLOR = "problemIndicationColor"; //$NON-NLS-1$ - /** - * PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR; A named preference that controls whether the editor shows warning - * indicators in text (squiggly lines). - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - // public final static String EDITOR_WARNING_INDICATION = "warningIndication"; //$NON-NLS-1$ - /** - * A named preference that holds the color used to render warning indicators. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see #EDITOR_WARNING_INDICATION - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - // public final static String EDITOR_WARNING_INDICATION_COLOR = "warningIndicationColor"; //$NON-NLS-1$ - /** - * A named preference that controls whether the editor shows task indicators in text (squiggly lines). - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String EDITOR_TASK_INDICATION = "taskIndication"; //$NON-NLS-1$ - - /** - * A named preference that holds the color used to render task indicators. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see #EDITOR_TASK_INDICATION - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_TASK_INDICATION_COLOR = "taskIndicationColor"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the editor shows bookmark indicators in text (squiggly lines). - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String EDITOR_BOOKMARK_INDICATION = "bookmarkIndication"; //$NON-NLS-1$ - - /** - * A named preference that holds the color used to render bookmark indicators. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see #EDITOR_BOOKMARK_INDICATION - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - * @since 2.1 - */ - public final static String EDITOR_BOOKMARK_INDICATION_COLOR = "bookmarkIndicationColor"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the editor shows search indicators in text (squiggly lines). - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String EDITOR_SEARCH_RESULT_INDICATION = "searchResultIndication"; //$NON-NLS-1$ - - /** - * A named preference that holds the color used to render search indicators. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see #EDITOR_SEARCH_RESULT_INDICATION - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - * @since 2.1 - */ - public final static String EDITOR_SEARCH_RESULT_INDICATION_COLOR = "searchResultIndicationColor"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the editor shows unknown indicators in text (squiggly lines). - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String EDITOR_UNKNOWN_INDICATION = "othersIndication"; //$NON-NLS-1$ - - /** - * A named preference that holds the color used to render unknown indicators. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see #EDITOR_UNKNOWN_INDICATION - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - * @since 2.1 - */ - public final static String EDITOR_UNKNOWN_INDICATION_COLOR = "othersIndicationColor"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the overview ruler shows error indicators. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER = "errorIndicationInOverviewRuler"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the overview ruler shows warning indicators. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER = "warningIndicationInOverviewRuler"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the overview ruler shows task indicators. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER = "taskIndicationInOverviewRuler"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the overview ruler shows bookmark indicators. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER = "bookmarkIndicationInOverviewRuler"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the overview ruler shows search result indicators. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER = "searchResultIndicationInOverviewRuler"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the overview ruler shows unknown indicators. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER = "othersIndicationInOverviewRuler"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'close strings' feature is enabled in PHP mode - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String EDITOR_CLOSE_STRINGS_DQ_PHP = "closeStringsPHPDQ"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'close strings' feature is enabled in PHP mode - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String EDITOR_CLOSE_STRINGS_SQ_PHP = "closeStringsPHPSQ"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'close brackets' feature is enabled in PHP mode - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String EDITOR_CLOSE_BRACKETS_PHP = "closeBracketsPHP"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'wrap words' feature is enabled. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String EDITOR_WRAP_WORDS = "wrapWords"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'wrap strings' feature is enabled. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String EDITOR_WRAP_STRINGS_DQ = "wrapStringsDQ"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'escape strings' feature is enabled. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String EDITOR_ESCAPE_STRINGS_DQ = "escapeStringsDQ"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'wrap strings' feature is enabled. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String EDITOR_WRAP_STRINGS_SQ = "wrapStringsDQ"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'escape strings' feature is enabled. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String EDITOR_ESCAPE_STRINGS_SQ = "escapeStringsSQ"; //$NON-NLS-1$ - - /** - * A named preference that controls if content assist inserts the common prefix of all proposals before presenting choices. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String CODEASSIST_PREFIX_COMPLETION = "content_assist_prefix_completion"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'close braces' feature is enabled. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String EDITOR_CLOSE_BRACES = "closeBraces"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'close php docs' feature is enabled. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String EDITOR_CLOSE_JAVADOCS = "closeJavaDocs"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'add JavaDoc tags' feature is enabled. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String EDITOR_ADD_JAVADOC_TAGS = "addJavaDocTags"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'format Javadoc tags' feature is enabled. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String EDITOR_FORMAT_JAVADOCS = "formatJavaDocs"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'smart paste' feature is enabled. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String EDITOR_SMART_PASTE = "smartPaste"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'close strings' feature is enabled in HTML mode - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String EDITOR_CLOSE_STRINGS_HTML = "closeStringsHTML"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'close brackets' feature is enabled in HTML mode - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String EDITOR_CLOSE_BRACKETS_HTML = "closeBracketsHTML"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'smart home-end' feature is enabled. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String EDITOR_SMART_HOME_END = AbstractTextEditor.PREFERENCE_NAVIGATION_SMART_HOME_END; - - /** - * A named preference that controls whether the 'sub-word navigation' feature is enabled. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String EDITOR_SUB_WORD_NAVIGATION = "subWordNavigation"; //$NON-NLS-1$ - - /** - * A named preference that controls if temporary problems are evaluated and shown in the UI. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String EDITOR_EVALUTE_TEMPORARY_PROBLEMS = "handleTemporaryProblems"; //$NON-NLS-1$ - - /** - * A named preference that controls if the overview ruler is shown in the UI. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String EDITOR_OVERVIEW_RULER = "overviewRuler"; //$NON-NLS-1$ - - /** - * A named preference that controls if the line number ruler is shown in the UI. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String EDITOR_LINE_NUMBER_RULER = "lineNumberRuler"; //$NON-NLS-1$ - - /** - * A named preference that holds the color used to render line numbers inside the line number ruler. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - * @see #EDITOR_LINE_NUMBER_RULER - */ - public final static String EDITOR_LINE_NUMBER_RULER_COLOR = "lineNumberColor"; //$NON-NLS-1$ - - /** - * A named preference that holds the color used to render linked positions inside code templates. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_LINKED_POSITION_COLOR = "linkedPositionColor"; //$NON-NLS-1$ - - /** - * A named preference that holds the color used as the text foreground. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_FOREGROUND_COLOR = AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND; - - /** - * A named preference that describes if the system default foreground color is used as the text foreground. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String EDITOR_FOREGROUND_DEFAULT_COLOR = AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT; - - /** - * A named preference that holds the color used as the text background. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_BACKGROUND_COLOR = AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND; - - /** - * A named preference that describes if the system default background color is used as the text foreground. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String EDITOR_BACKGROUND_DEFAULT_COLOR = AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT; - - /** - * Preference key suffix for bold text style preference keys. - */ - public static final String EDITOR_BOLD_SUFFIX = "_bold"; //$NON-NLS-1$ - - /** - * Preference key suffix for bold text style preference keys. - */ - public static final String EDITOR_ITALIC_SUFFIX = "_italic"; //$NON-NLS-1$ - - /** - * A named preference that holds the color used to render multi line comments. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_MULTI_LINE_COMMENT_COLOR = IPreferenceConstants.PHP_MULTILINE_COMMENT; - - /** - * The symbolic font name for the Java editor text font (value "net.sourceforge.phpdt.ui.editors.textfont"). - * - * @since 2.1 - */ - public final static String EDITOR_TEXT_FONT = "net.sourceforge.phpdt.ui.editors.textfont"; //$NON-NLS-1$ - - /** - * A named preference that controls whether multi line comments are rendered in bold. - *

                                                      - * Value is of type Boolean. If true multi line comments are rendered in bold. If - * false the are rendered using no font style attribute. - *

                                                      - */ - public final static String EDITOR_MULTI_LINE_COMMENT_BOLD = IPreferenceConstants.PHP_MULTILINE_COMMENT + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render single line comments. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_SINGLE_LINE_COMMENT_COLOR = IPreferenceConstants.PHP_SINGLELINE_COMMENT; - - /** - * A named preference that controls whether sinle line comments are rendered in bold. - *

                                                      - * Value is of type Boolean. If true single line comments are rendered in bold. If - * false the are rendered using no font style attribute. - *

                                                      - */ - public final static String EDITOR_SINGLE_LINE_COMMENT_BOLD = IPreferenceConstants.PHP_SINGLELINE_COMMENT + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render operators and brackets. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - * @since 3.0 - */ - public final static String EDITOR_PHP_OPERATOR_COLOR = IPreferenceConstants.PHP_OPERATOR; - - /** - * A named preference that controls whether operators and brackets are rendered in bold. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String EDITOR_PHP_OPERATOR_BOLD = IPreferenceConstants.PHP_OPERATOR + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that controls whether operators and brackets are rendered in italic. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String EDITOR_PHP_OPERATOR_ITALIC = IPreferenceConstants.PHP_OPERATOR + EDITOR_ITALIC_SUFFIX; - - /** - * A named preference that holds the color used to render operators and brackets. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - * @since 3.0 - */ - public final static String EDITOR_PHP_BRACE_OPERATOR_COLOR = IPreferenceConstants.PHP_BRACE_OPERATOR; - - /** - * A named preference that controls whether operators and brackets are rendered in bold. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String EDITOR_PHP_BRACE_OPERATOR_BOLD = IPreferenceConstants.PHP_BRACE_OPERATOR + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that controls whether operators and brackets are rendered in italic. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String EDITOR_PHP_BRACE_OPERATOR_ITALIC = IPreferenceConstants.PHP_BRACE_OPERATOR + EDITOR_ITALIC_SUFFIX; - - /** - * A named preference that holds the color used to render the 'return' keyword. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - * @since 3.0 - */ - public final static String EDITOR_PHP_KEYWORD_RETURN_COLOR = IPreferenceConstants.PHP_KEYWORD_RETURN; - - /** - * A named preference that controls whether 'return' keyword is rendered in bold. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String EDITOR_PHP_KEYWORD_RETURN_BOLD = IPreferenceConstants.PHP_KEYWORD_RETURN + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that controls whether 'return' keyword is rendered in italic. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String EDITOR_PHP_KEYWORD_RETURN_ITALIC = IPreferenceConstants.PHP_KEYWORD_RETURN + EDITOR_ITALIC_SUFFIX; - - /** - * A named preference that holds the color used to render php start and stop tags. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_PHP_TAG_COLOR = IPreferenceConstants.PHP_TAG; - - /** - * A named preference that controls whether php start and stop tags are rendered in bold. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String EDITOR_PHP_TAG_BOLD = IPreferenceConstants.PHP_TAG + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render php keywords. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_JAVA_KEYWORD_COLOR = IPreferenceConstants.PHP_KEYWORD; - - /** - * A named preference that controls whether keywords are rendered in bold. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String EDITOR_JAVA_KEYWORD_BOLD = IPreferenceConstants.PHP_KEYWORD + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render predefined php function names. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_PHP_FUNCTIONNAME_COLOR = IPreferenceConstants.PHP_FUNCTIONNAME; - - /** - * A named preference that controls whether function names are rendered in bold. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String EDITOR_PHP_FUNCTIONNAME_BOLD = IPreferenceConstants.PHP_FUNCTIONNAME + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render php variables with prefix '$_'. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_PHP_VARIABLE_DOLLAR_COLOR = IPreferenceConstants.PHP_VARIABLE_DOLLAR; - - /** - * A named preference that controls whether variables with prefix '$_' are rendered in bold. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String EDITOR_PHP_VARIABLE_DOLLAR_BOLD = IPreferenceConstants.PHP_VARIABLE_DOLLAR + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render php variables. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_PHP_VARIABLE_COLOR = IPreferenceConstants.PHP_VARIABLE; - - /** - * A named preference that controls whether variables are rendered in bold. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String EDITOR_PHP_VARIABLE_BOLD = IPreferenceConstants.PHP_VARIABLE + EDITOR_BOLD_SUFFIX; - /** - * A named preference that holds the color used to render php constants. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_PHP_CONSTANT_COLOR = IPreferenceConstants.PHP_CONSTANT; - - /** - * A named preference that controls whether constants are rendered in bold. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String EDITOR_PHP_CONSTANT_BOLD = IPreferenceConstants.PHP_CONSTANT + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render php types. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_PHP_TYPE_COLOR = IPreferenceConstants.PHP_TYPE; - - /** - * A named preference that controls whether types are rendered in bold. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String EDITOR_PHP_TYPE_BOLD = IPreferenceConstants.PHP_TYPE + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render string constants. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_STRING_COLOR_DQ = IPreferenceConstants.PHP_STRING_DQ; - - /** - * A named preference that controls whether string constants are rendered in bold. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String EDITOR_STRING_BOLD_DQ = IPreferenceConstants.PHP_STRING_DQ + EDITOR_BOLD_SUFFIX; - - public final static String EDITOR_STRING_COLOR_SQ = IPreferenceConstants.PHP_STRING_SQ; - - /** - * A named preference that controls whether string constants are rendered in bold. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String EDITOR_STRING_BOLD_SQ = IPreferenceConstants.PHP_STRING_SQ + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render php default text. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_JAVA_DEFAULT_COLOR = IPreferenceConstants.PHP_DEFAULT; - - /** - * A named preference that controls whether Java default text is rendered in bold. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String EDITOR_JAVA_DEFAULT_BOLD = IPreferenceConstants.PHP_DEFAULT + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render task tags. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - * @since 2.1 - */ - public final static String EDITOR_TASK_TAG_COLOR = IPreferenceConstants.TASK_TAG; - - /** - * A named preference that controls whether task tags are rendered in bold. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String EDITOR_TASK_TAG_BOLD = IPreferenceConstants.TASK_TAG + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render phpdoc keywords. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_JAVADOC_KEYWORD_COLOR = IPreferenceConstants.PHPDOC_KEYWORD; - - /** - * A named preference that controls whether phpdoc keywords are rendered in bold. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String EDITOR_JAVADOC_KEYWORD_BOLD = IPreferenceConstants.PHPDOC_KEYWORD + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render phpdoc tags. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_JAVADOC_TAG_COLOR = IPreferenceConstants.PHPDOC_TAG; - - /** - * A named preference that controls whether phpdoc tags are rendered in bold. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String EDITOR_JAVADOC_TAG_BOLD = IPreferenceConstants.PHPDOC_TAG + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render phpdoc links. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_JAVADOC_LINKS_COLOR = IPreferenceConstants.PHPDOC_LINK; - - /** - * A named preference that controls whether phpdoc links are rendered in bold. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String EDITOR_JAVADOC_LINKS_BOLD = IPreferenceConstants.PHPDOC_LINK + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render phpdoc default text. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_JAVADOC_DEFAULT_COLOR = IPreferenceConstants.PHPDOC_DEFAULT; - - /** - * A named preference that controls whether phpdoc default text is rendered in bold. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String EDITOR_JAVADOC_DEFAULT_BOLD = IPreferenceConstants.PHPDOC_DEFAULT + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used for 'linked-mode' underline. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - * @since 2.1 - */ - public final static String EDITOR_LINK_COLOR = "linkColor"; //$NON-NLS-1$ - - /** - * A named preference that controls whether hover tooltips in the editor are turned on or off. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public static final String EDITOR_SHOW_HOVER = "net.sourceforge.phpdt.ui.editor.showHover"; //$NON-NLS-1$ - - /** - * A named preference that defines the hover shown when no control key is pressed. - *

                                                      - * Value is of type String: possible values are - * EDITOR_NO_HOVER_CONFIGURED_ID or - * EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a hover contributed as phpEditorTextHovers. - *

                                                      - * - * @see #EDITOR_NO_HOVER_CONFIGURED_ID - * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID - * @see JavaUI - * @since 2.1 - */ - public static final String EDITOR_NONE_HOVER = "noneHover"; //$NON-NLS-1$ - - /** - * A named preference that defines the hover shown when the CTRL modifier key is pressed. - *

                                                      - * Value is of type String: possible values are - * EDITOR_NO_HOVER_CONFIGURED_ID or - * EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a hover contributed as phpEditorTextHovers. - *

                                                      - * - * @see #EDITOR_NO_HOVER_CONFIGURED_ID - * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID - * @see JavaUI - * @since 2.1 - */ - public static final String EDITOR_CTRL_HOVER = "ctrlHover"; //$NON-NLS-1$ - - /** - * A named preference that defines the hover shown when the SHIFT modifier key is pressed. - *

                                                      - * Value is of type String: possible values are - * EDITOR_NO_HOVER_CONFIGURED_ID or - * EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a hover contributed as phpEditorTextHovers. - *

                                                      - * - * @see #EDITOR_NO_HOVER_CONFIGURED_ID - * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID - * @see JavaUI ID_*_HOVER - * @since 2.1 - */ - public static final String EDITOR_SHIFT_HOVER = "shiftHover"; //$NON-NLS-1$ - - /** - * A named preference that defines the hover shown when the CTRL + ALT modifier keys is pressed. - *

                                                      - * Value is of type String: possible values are - * EDITOR_NO_HOVER_CONFIGURED_ID or - * EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a hover contributed as phpEditorTextHovers. - *

                                                      - * - * @see #EDITOR_NO_HOVER_CONFIGURED_ID - * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID - * @see JavaUI ID_*_HOVER - * @since 2.1 - */ - public static final String EDITOR_CTRL_ALT_HOVER = "ctrlAltHover"; //$NON-NLS-1$ - - /** - * A named preference that defines the hover shown when the CTRL + ALT + SHIFT modifier keys is pressed. - *

                                                      - * Value is of type String: possible values are - * EDITOR_NO_HOVER_CONFIGURED_ID or - * EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a hover contributed as phpEditorTextHovers. - *

                                                      - * - * @see #EDITOR_NO_HOVER_CONFIGURED_ID - * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID - * @see JavaUI ID_*_HOVER - * @since 2.1 - */ - public static final String EDITOR_CTRL_ALT_SHIFT_HOVER = "ctrlAltShiftHover"; //$NON-NLS-1$ - - /** - * A named preference that defines the hover shown when the CTRL + SHIFT modifier keys is pressed. - *

                                                      - * Value is of type String: possible values are - * EDITOR_NO_HOVER_CONFIGURED_ID or - * EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a hover contributed as phpEditorTextHovers. - *

                                                      - * - * @see #EDITOR_NO_HOVER_CONFIGURED_ID - * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID - * @see JavaUI ID_*_HOVER - * @since 2.1 - */ - public static final String EDITOR_CTRL_SHIFT_HOVER = "ctrlShiftHover"; //$NON-NLS-1$ - - /** - * A named preference that defines the hover shown when the ALT modifier key is pressed. - *

                                                      - * Value is of type String: possible values are - * EDITOR_NO_HOVER_CONFIGURED_ID, - * EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a hover contributed as phpEditorTextHovers. - *

                                                      - * - * @see #EDITOR_NO_HOVER_CONFIGURED_ID - * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID - * @see JavaUI ID_*_HOVER - * @since 2.1 - */ - public static final String EDITOR_ALT_SHIFT_HOVER = "altShiftHover"; //$NON-NLS-1$ - - /** - * A string value used by the named preferences for hover configuration to descibe that no hover should be shown for the given key - * modifiers. - * - * @since 2.1 - */ - public static final String EDITOR_NO_HOVER_CONFIGURED_ID = "noHoverConfiguredId"; //$NON-NLS-1$ - - /** - * A string value used by the named preferences for hover configuration to descibe that the default hover should be shown for the - * given key modifiers. The default hover is described by the EDITOR_DEFAULT_HOVER property. - * - * @since 2.1 - */ - public static final String EDITOR_DEFAULT_HOVER_CONFIGURED_ID = "defaultHoverConfiguredId"; //$NON-NLS-1$ - - /** - * A named preference that defines the hover named the 'default hover'. Value is of type String: possible values - * are - * EDITOR_NO_HOVER_CONFIGURED_ID or the hover id of a hover - * contributed as phpEditorTextHovers. - *

                                                      - *@since 2.1 - */ - public static final String EDITOR_DEFAULT_HOVER = "defaultHover"; //$NON-NLS-1$ - - /** - * A named preference that controls if segmented view (show selected element only) is turned on or off. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public static final String EDITOR_SHOW_SEGMENTS = "net.sourceforge.phpdt.ui.editor.showSegments"; //$NON-NLS-1$ - - /** - * A named preference that controls if browser like links are turned on or off. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public static final String EDITOR_BROWSER_LIKE_LINKS = "browserLikeLinks"; //$NON-NLS-1$ - - /** - * A named preference that controls the key modifier for browser like links. - *

                                                      - * Value is of type String. - *

                                                      - * - * @since 2.1 - */ - public static final String EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER = "browserLikeLinksKeyModifier"; //$NON-NLS-1$ - - /** - * A named preference that controls whether occurrences are marked in the editor. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public static final String EDITOR_MARK_OCCURRENCES = "markOccurrences"; //$NON-NLS-1$ - - /** - * A named preference that controls whether occurrences are sticky in the editor. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public static final String EDITOR_STICKY_OCCURRENCES = "stickyOccurrences"; //$NON-NLS-1$ - - /** - * A named preference that controls disabling of the overwrite mode. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public static final String EDITOR_DISABLE_OVERWRITE_MODE = "disable_overwrite_mode"; //$NON-NLS-1$ - - /** - * A named preference that controls the "smart semicolon" smart typing handler - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public static final String EDITOR_SMART_SEMICOLON = "smart_semicolon"; //$NON-NLS-1$ - - /** - * A named preference that controls the smart backspace behavior. - *

                                                      - * Value is of type Boolean. - * - * @since 3.0 - */ - public static final String EDITOR_SMART_BACKSPACE = "smart_backspace"; //$NON-NLS-1$ - - /** - * A named preference that controls the "smart opening brace" smart typing handler - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public static final String EDITOR_SMART_OPENING_BRACE = "smart_opening_brace"; //$NON-NLS-1$ - - /** - * A named preference that controls the smart tab behaviour. - *

                                                      - * Value is of type Boolean. - * - * @since 3.0 - */ - public static final String EDITOR_SMART_TAB = "smart_tab"; //$NON-NLS-1$ - - public static final String EDITOR_P_RTRIM_ON_SAVE = "editor_p_trim_on_save"; //$NON-NLS-1$ - - /** - * A named preference that controls whether Java comments should be spell-checked. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String SPELLING_CHECK_SPELLING = ISpellCheckPreferenceKeys.SPELLING_CHECK_SPELLING; - - /** - * A named preference that controls whether words containing digits should be skipped during spell-checking. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String SPELLING_IGNORE_DIGITS = ISpellCheckPreferenceKeys.SPELLING_IGNORE_DIGITS; - - /** - * A named preference that controls whether mixed case words should be skipped during spell-checking. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String SPELLING_IGNORE_MIXED = ISpellCheckPreferenceKeys.SPELLING_IGNORE_MIXED; - - /** - * A named preference that controls whether sentence capitalization should be ignored during spell-checking. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String SPELLING_IGNORE_SENTENCE = ISpellCheckPreferenceKeys.SPELLING_IGNORE_SENTENCE; - - /** - * A named preference that controls whether upper case words should be skipped during spell-checking. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String SPELLING_IGNORE_UPPER = ISpellCheckPreferenceKeys.SPELLING_IGNORE_UPPER; - - /** - * A named preference that controls whether urls should be ignored during spell-checking. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String SPELLING_IGNORE_URLS = ISpellCheckPreferenceKeys.SPELLING_IGNORE_URLS; - - /** - * A named preference that controls the locale used for spell-checking. - *

                                                      - * Value is of type String. - *

                                                      - * - * @since 3.0 - */ - public final static String SPELLING_LOCALE = ISpellCheckPreferenceKeys.SPELLING_LOCALE; - - /** - * A named preference that controls the number of proposals offered during spell-checking. - *

                                                      - * Value is of type Integer. - *

                                                      - * - * @since 3.0 - */ - public final static String SPELLING_PROPOSAL_THRESHOLD = ISpellCheckPreferenceKeys.SPELLING_PROPOSAL_THRESHOLD; - - /** - * A named preference that specifies the workspace user dictionary. - *

                                                      - * Value is of type Integer. - *

                                                      - * - * @since 3.0 - */ - public final static String SPELLING_USER_DICTIONARY = ISpellCheckPreferenceKeys.SPELLING_USER_DICTIONARY; - - /** - * A named preference that specifies whether spelling dictionaries are available to content assist. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String SPELLING_ENABLE_CONTENTASSIST = ISpellCheckPreferenceKeys.SPELLING_ENABLE_CONTENTASSIST; - - /** - * A named preference that controls whether code snippets are formatted in Javadoc comments. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String FORMATTER_COMMENT_FORMATSOURCE = "comment_format_source_code"; //$NON-NLS-1$ - - /** - * A named preference that controls whether description of Javadoc parameters are indented. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String FORMATTER_COMMENT_INDENTPARAMETERDESCRIPTION = "comment_indent_parameter_description"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the header comment of a Java source file is formatted. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String FORMATTER_COMMENT_FORMATHEADER = "comment_format_header"; //$NON-NLS-1$ - - /** - * A named preference that controls whether Javadoc root tags are indented. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String FORMATTER_COMMENT_INDENTROOTTAGS = "comment_indent_root_tags"; //$NON-NLS-1$ - - /** - * A named preference that controls whether Javadoc comments are formatted by the content formatter. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String FORMATTER_COMMENT_FORMAT = "comment_format_comments"; //$NON-NLS-1$ - - /** - * A named preference that controls whether a new line is inserted after Javadoc root tag parameters. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String FORMATTER_COMMENT_NEWLINEFORPARAMETER = "comment_new_line_for_parameter"; //$NON-NLS-1$ - - /** - * A named preference that controls whether an empty line is inserted before the Javadoc root tag block. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String FORMATTER_COMMENT_SEPARATEROOTTAGS = "comment_separate_root_tags"; //$NON-NLS-1$ - - /** - * A named preference that controls whether blank lines are cleared during formatting - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String FORMATTER_COMMENT_CLEARBLANKLINES = "comment_clear_blank_lines"; //$NON-NLS-1$ - - /** - * A named preference that controls the line length of comments. - *

                                                      - * Value is of type Integer. The value must be at least 4 for reasonable formatting. - *

                                                      - * - * @since 3.0 - */ - public final static String FORMATTER_COMMENT_LINELENGTH = "comment_line_length"; //$NON-NLS-1$ - - /** - * A named preference that controls whether html tags are formatted. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String FORMATTER_COMMENT_FORMATHTML = "comment_format_html"; //$NON-NLS-1$ - - /** - * A named preference that controls if the Java code assist gets auto activated. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String CODEASSIST_AUTOACTIVATION = "content_assist_autoactivation"; //$NON-NLS-1$ - - /** - * A name preference that holds the auto activation delay time in milli seconds. - *

                                                      - * Value is of type Int. - *

                                                      - */ - public final static String CODEASSIST_AUTOACTIVATION_DELAY = "content_assist_autoactivation_delay"; //$NON-NLS-1$ - - /** - * A named preference that controls if code assist contains only visible proposals. - *

                                                      - * Value is of type Boolean. if true code assist only contains visible members. If - * false all members are included. - *

                                                      - */ - public final static String CODEASSIST_SHOW_VISIBLE_PROPOSALS = "content_assist_show_visible_proposals"; //$NON-NLS-1$ - - /** - * A named preference that controls if the Java code assist inserts a proposal automatically if only one proposal is available. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String CODEASSIST_AUTOINSERT = "content_assist_autoinsert"; //$NON-NLS-1$ - - /** - * A named preference that controls if the Java code assist adds import statements. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String CODEASSIST_ADDIMPORT = "content_assist_add_import"; //$NON-NLS-1$ - - /** - * A named preference that controls if the Java code assist only inserts completions. If set to false the proposals can also - * _replace_ code. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String CODEASSIST_INSERT_COMPLETION = "content_assist_insert_completion"; //$NON-NLS-1$ - - /** - * A named preference that controls whether code assist proposals filtering is case sensitive or not. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String CODEASSIST_CASE_SENSITIVITY = "content_assist_case_sensitivity"; //$NON-NLS-1$ - - /** - * A named preference that defines if code assist proposals are sorted in alphabetical order. - *

                                                      - * Value is of type Boolean. If true that are sorted in alphabetical order. If false - * that are unsorted. - *

                                                      - */ - public final static String CODEASSIST_ORDER_PROPOSALS = "content_assist_order_proposals"; //$NON-NLS-1$ - - /** - * A named preference that controls if argument names are filled in when a method is selected from as list of code assist - * proposal. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public final static String CODEASSIST_FILL_ARGUMENT_NAMES = "content_assist_fill_method_arguments"; //$NON-NLS-1$ - - /** - * A named preference that controls if method arguments are guessed when a method is selected from as list of code assist - * proposal. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public final static String CODEASSIST_GUESS_METHOD_ARGUMENTS = "content_assist_guess_method_arguments"; //$NON-NLS-1$ - - /** - * A named preference that holds the characters that auto activate code assist in PHP code. - *

                                                      - * Value is of type Sring. All characters that trigger auto code assist in PHP code. - *

                                                      - */ - public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA = "content_assist_autoactivation_triggers_php"; //$NON-NLS-1$ - - /** - * A named preference that holds the characters that auto activate code assist in PHPDoc. - *

                                                      - * Value is of type Sring. All characters that trigger auto code assist in PHPDoc. - *

                                                      - */ - public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC = "content_assist_autoactivation_triggers_phpdoc"; //$NON-NLS-1$ - - /** - * A named preference that holds the characters that auto activate code assist in HTML. - *

                                                      - * Value is of type Sring. All characters that trigger auto code assist in HTML. - *

                                                      - */ - public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_HTML = "content_assist_autoactivation_triggers_html"; //$NON-NLS-1$ - - /** - * A named preference that holds the background color used in the code assist selection dialog. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String CODEASSIST_PROPOSALS_BACKGROUND = "content_assist_proposals_background"; //$NON-NLS-1$ - - /** - * A named preference that holds the foreground color used in the code assist selection dialog. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String CODEASSIST_PROPOSALS_FOREGROUND = "content_assist_proposals_foreground"; //$NON-NLS-1$ - - /** - * A named preference that holds the background color used for parameter hints. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String CODEASSIST_PARAMETERS_BACKGROUND = "content_assist_parameters_background"; //$NON-NLS-1$ - - /** - * A named preference that holds the foreground color used in the code assist selection dialog - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String CODEASSIST_PARAMETERS_FOREGROUND = "content_assist_parameters_foreground"; //$NON-NLS-1$ - - /** - * A named preference that holds the background color used in the code assist selection dialog to mark replaced code. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - * @since 2.1 - */ - public final static String CODEASSIST_REPLACEMENT_BACKGROUND = "content_assist_completion_replacement_background"; //$NON-NLS-1$ - - /** - * A named preference that holds the foreground color used in the code assist selection dialog to mark replaced code. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - * @since 2.1 - */ - public final static String CODEASSIST_REPLACEMENT_FOREGROUND = "content_assist_completion_replacement_foreground"; //$NON-NLS-1$ - - /** - * A named preference that controls the behaviour of the refactoring wizard for showing the error page. - *

                                                      - * Value is of type String. Valid values are: REFACTOR_FATAL_SEVERITY, - * REFACTOR_ERROR_SEVERITY,REFACTOR_WARNING_SEVERITY - * REFACTOR_INFO_SEVERITY, - * REFACTOR_OK_SEVERITY. - *

                                                      - * - * @see #REFACTOR_FATAL_SEVERITY - * @see #REFACTOR_ERROR_SEVERITY - * @see #REFACTOR_WARNING_SEVERITY - * @see #REFACTOR_INFO_SEVERITY - * @see #REFACTOR_OK_SEVERITY - */ - public static final String REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD = "Refactoring.ErrorPage.severityThreshold"; //$NON-NLS-1$ - - /** - * A string value used by the named preference REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD. - * - * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD - */ - public static final String REFACTOR_FATAL_SEVERITY = "4"; //$NON-NLS-1$ - - /** - * A string value used by the named preference REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD. - * - * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD - */ - public static final String REFACTOR_ERROR_SEVERITY = "3"; //$NON-NLS-1$ - - /** - * A string value used by the named preference REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD. - * - * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD - */ - public static final String REFACTOR_WARNING_SEVERITY = "2"; //$NON-NLS-1$ - - /** - * A string value used by the named preference REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD. - * - * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD - */ - public static final String REFACTOR_INFO_SEVERITY = "1"; //$NON-NLS-1$ - - /** - * A string value used by the named preference REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD. - * - * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD - */ - public static final String REFACTOR_OK_SEVERITY = "0"; //$NON-NLS-1$ - - /** - * A named preference thet controls whether all dirty editors are automatically saved before a refactoring is executed. - *

                                                      - * Value is of type Boolean. - *

                                                      - */ - public static final String REFACTOR_SAVE_ALL_EDITORS = "Refactoring.savealleditors"; //$NON-NLS-1$ - - /** - * A named preference that controls if the Java Browsing views are linked to the active editor. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @see #LINK_PACKAGES_TO_EDITOR - */ - public static final String BROWSING_LINK_VIEW_TO_EDITOR = "net.sourceforge.phpdt.ui.browsing.linktoeditor"; //$NON-NLS-1$ - - /** - * A named preference that controls the layout of the Java Browsing views vertically. Boolean value. - *

                                                      - * Value is of type Boolean. If true the views are stacked vertical. - * If false they are stacked horizontal. - *

                                                      - */ - public static final String BROWSING_STACK_VERTICALLY = "net.sourceforge.phpdt.ui.browsing.stackVertically"; //$NON-NLS-1$ - - /** - * A named preference that controls if templates are formatted when applied. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 2.1 - */ - public static final String TEMPLATES_USE_CODEFORMATTER = "net.sourceforge.phpdt.ui.template.format"; //$NON-NLS-1$ - - /** - * A named preference that controls whether annotation roll over is used or not. - *

                                                      - * Value is of type Boolean. If true the annotation ruler column - * uses a roll over to display multiple annotations - *

                                                      - * - * @since 3.0 - */ - public static final String EDITOR_ANNOTATION_ROLL_OVER = "editor_annotation_roll_over"; //$NON-NLS-1$ - - /** - * A named preference that controls the key modifier mask for browser like links. The value is only used if the value of - * EDITOR_BROWSER_LIKE_LINKS cannot be resolved to valid SWT modifier bits. - *

                                                      - * Value is of type String. - *

                                                      - * - * @see #EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER - * @since 2.1.1 - */ - public static final String EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK = "browserLikeLinksKeyModifierMask"; //$NON-NLS-1$ - - /** - * A named preference that defines the key for the hover modifier state masks. The value is only used if the value of - * EDITOR_TEXT_HOVER_MODIFIERS cannot be resolved to valid SWT modifier bits. - * - * @see JavaUI - * @see #EDITOR_TEXT_HOVER_MODIFIERS - * @since 2.1.1 - */ - public static final String EDITOR_TEXT_HOVER_MODIFIER_MASKS = "hoverModifierMasks"; //$NON-NLS-1$ - - /** - * A named preference that controls whether folding is enabled in the Java editor. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public static final String EDITOR_FOLDING_ENABLED = "editor_folding_enabled"; //$NON-NLS-1$ - - /** - * A named preference that stores the configured folding provider. - *

                                                      - * Value is of type String. - *

                                                      - * - * @since 3.0 - */ - public static final String EDITOR_FOLDING_PROVIDER = "editor_folding_provider"; //$NON-NLS-1$ - - /** - * A named preference that stores the value for Javadoc folding for the default folding provider. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public static final String EDITOR_FOLDING_JAVADOC = "editor_folding_default_javadoc"; //$NON-NLS-1$ - - /** - * A named preference that stores the value for inner type folding for the default folding provider. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public static final String EDITOR_FOLDING_INNERTYPES = "editor_folding_default_innertypes"; //$NON-NLS-1$ - - /** - * A named preference that stores the value for method folding for the default folding provider. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public static final String EDITOR_FOLDING_METHODS = "editor_folding_default_methods"; //$NON-NLS-1$ - - /** - * A named preference that stores the value for imports folding for the default folding provider. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ -// public static final String EDITOR_FOLDING_IMPORTS = "editor_folding_default_imports"; //$NON-NLS-1$ - /** - * A named preference that stores the value for header comment folding for the default folding provider. + public final static String EDITOR_PHP_BRACE_OPERATOR_BOLD = IPreferenceConstants.PHP_BRACE_OPERATOR + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that controls whether operators and brackets are + * rendered in italic. *

                                                      * Value is of type Boolean. *

                                                      + * + * @since 3.0 + */ + public final static String EDITOR_PHP_BRACE_OPERATOR_ITALIC = IPreferenceConstants.PHP_BRACE_OPERATOR + + EDITOR_ITALIC_SUFFIX; + + /** + * A named preference that holds the color used to render the 'return' + * keyword. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + * @since 3.0 + */ + public final static String EDITOR_PHP_KEYWORD_RETURN_COLOR = IPreferenceConstants.PHP_KEYWORD_RETURN; + + /** + * A named preference that controls whether 'return' keyword is rendered in + * bold. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String EDITOR_PHP_KEYWORD_RETURN_BOLD = IPreferenceConstants.PHP_KEYWORD_RETURN + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that controls whether 'return' keyword is rendered in + * italic. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String EDITOR_PHP_KEYWORD_RETURN_ITALIC = IPreferenceConstants.PHP_KEYWORD_RETURN + + EDITOR_ITALIC_SUFFIX; + + /** + * A named preference that holds the color used to render php start and stop + * tags. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_PHP_TAG_COLOR = IPreferenceConstants.PHP_TAG; + + /** + * A named preference that controls whether php start and stop tags are + * rendered in bold. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String EDITOR_PHP_TAG_BOLD = IPreferenceConstants.PHP_TAG + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render php keywords. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_JAVA_KEYWORD_COLOR = IPreferenceConstants.PHP_KEYWORD; + + /** + * A named preference that controls whether keywords are rendered in bold. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String EDITOR_JAVA_KEYWORD_BOLD = IPreferenceConstants.PHP_KEYWORD + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render predefined php + * function names. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_PHP_FUNCTIONNAME_COLOR = IPreferenceConstants.PHP_FUNCTIONNAME; + + /** + * A named preference that controls whether function names are rendered in + * bold. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String EDITOR_PHP_FUNCTIONNAME_BOLD = IPreferenceConstants.PHP_FUNCTIONNAME + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render php variables with + * prefix '$_'. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_PHP_VARIABLE_DOLLAR_COLOR = IPreferenceConstants.PHP_VARIABLE_DOLLAR; + + /** + * A named preference that controls whether variables with prefix '$_' are + * rendered in bold. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String EDITOR_PHP_VARIABLE_DOLLAR_BOLD = IPreferenceConstants.PHP_VARIABLE_DOLLAR + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render php variables. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_PHP_VARIABLE_COLOR = IPreferenceConstants.PHP_VARIABLE; + + /** + * A named preference that controls whether variables are rendered in bold. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String EDITOR_PHP_VARIABLE_BOLD = IPreferenceConstants.PHP_VARIABLE + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render php constants. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_PHP_CONSTANT_COLOR = IPreferenceConstants.PHP_CONSTANT; + + /** + * A named preference that controls whether constants are rendered in bold. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String EDITOR_PHP_CONSTANT_BOLD = IPreferenceConstants.PHP_CONSTANT + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render php types. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_PHP_TYPE_COLOR = IPreferenceConstants.PHP_TYPE; + + /** + * A named preference that controls whether types are rendered in bold. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String EDITOR_PHP_TYPE_BOLD = IPreferenceConstants.PHP_TYPE + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render string constants. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_STRING_COLOR_DQ = IPreferenceConstants.PHP_STRING_DQ; + + /** + * A named preference that controls whether string constants are rendered in + * bold. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String EDITOR_STRING_BOLD_DQ = IPreferenceConstants.PHP_STRING_DQ + + EDITOR_BOLD_SUFFIX; + + public final static String EDITOR_STRING_COLOR_SQ = IPreferenceConstants.PHP_STRING_SQ; + + /** + * A named preference that controls whether string constants are rendered in + * bold. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String EDITOR_STRING_BOLD_SQ = IPreferenceConstants.PHP_STRING_SQ + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render php default text. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_JAVA_DEFAULT_COLOR = IPreferenceConstants.PHP_DEFAULT; + + /** + * A named preference that controls whether Java default text is rendered in + * bold. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String EDITOR_JAVA_DEFAULT_BOLD = IPreferenceConstants.PHP_DEFAULT + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render task tags. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + * @since 2.1 + */ + public final static String EDITOR_TASK_TAG_COLOR = IPreferenceConstants.TASK_TAG; + + /** + * A named preference that controls whether task tags are rendered in bold. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String EDITOR_TASK_TAG_BOLD = IPreferenceConstants.TASK_TAG + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render phpdoc keywords. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_JAVADOC_KEYWORD_COLOR = IPreferenceConstants.PHPDOC_KEYWORD; + + /** + * A named preference that controls whether phpdoc keywords are rendered in + * bold. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String EDITOR_JAVADOC_KEYWORD_BOLD = IPreferenceConstants.PHPDOC_KEYWORD + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render phpdoc tags. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_JAVADOC_TAG_COLOR = IPreferenceConstants.PHPDOC_TAG; + + /** + * A named preference that controls whether phpdoc tags are rendered in + * bold. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String EDITOR_JAVADOC_TAG_BOLD = IPreferenceConstants.PHPDOC_TAG + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render phpdoc links. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_JAVADOC_LINKS_COLOR = IPreferenceConstants.PHPDOC_LINK; + + /** + * A named preference that controls whether phpdoc links are rendered in + * bold. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String EDITOR_JAVADOC_LINKS_BOLD = IPreferenceConstants.PHPDOC_LINK + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render phpdoc default + * text. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_JAVADOC_DEFAULT_COLOR = IPreferenceConstants.PHPDOC_DEFAULT; + + /** + * A named preference that controls whether phpdoc default text is rendered + * in bold. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String EDITOR_JAVADOC_DEFAULT_BOLD = IPreferenceConstants.PHPDOC_DEFAULT + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used for 'linked-mode' underline. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + * @since 2.1 + */ + public final static String EDITOR_LINK_COLOR = "linkColor"; //$NON-NLS-1$ + + /** + * A named preference that controls whether hover tooltips in the editor are + * turned on or off. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public static final String EDITOR_SHOW_HOVER = "net.sourceforge.phpdt.ui.editor.showHover"; //$NON-NLS-1$ + + /** + * A named preference that defines the hover shown when no control key is + * pressed. + *

                                                      + * Value is of type String: possible values are + * EDITOR_NO_HOVER_CONFIGURED_ID + * or EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a + * hover contributed as phpEditorTextHovers. + *

                                                      + * + * @see #EDITOR_NO_HOVER_CONFIGURED_ID + * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID + * @see JavaUI + * @since 2.1 + */ + public static final String EDITOR_NONE_HOVER = "noneHover"; //$NON-NLS-1$ + + /** + * A named preference that defines the hover shown when the + * CTRL modifier key is pressed. + *

                                                      + * Value is of type String: possible values are + * EDITOR_NO_HOVER_CONFIGURED_ID + * or EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a + * hover contributed as phpEditorTextHovers. + *

                                                      + * + * @see #EDITOR_NO_HOVER_CONFIGURED_ID + * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID + * @see JavaUI + * @since 2.1 + */ + public static final String EDITOR_CTRL_HOVER = "ctrlHover"; //$NON-NLS-1$ + + /** + * A named preference that defines the hover shown when the + * SHIFT modifier key is pressed. + *

                                                      + * Value is of type String: possible values are + * EDITOR_NO_HOVER_CONFIGURED_ID + * or EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a + * hover contributed as phpEditorTextHovers. + *

                                                      + * + * @see #EDITOR_NO_HOVER_CONFIGURED_ID + * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID + * @see JavaUI ID_*_HOVER + * @since 2.1 + */ + public static final String EDITOR_SHIFT_HOVER = "shiftHover"; //$NON-NLS-1$ + + /** + * A named preference that defines the hover shown when the + * CTRL + ALT modifier keys is pressed. + *

                                                      + * Value is of type String: possible values are + * EDITOR_NO_HOVER_CONFIGURED_ID + * or EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a + * hover contributed as phpEditorTextHovers. + *

                                                      + * + * @see #EDITOR_NO_HOVER_CONFIGURED_ID + * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID + * @see JavaUI ID_*_HOVER + * @since 2.1 + */ + public static final String EDITOR_CTRL_ALT_HOVER = "ctrlAltHover"; //$NON-NLS-1$ + + /** + * A named preference that defines the hover shown when the + * CTRL + ALT + SHIFT modifier keys is pressed. + *

                                                      + * Value is of type String: possible values are + * EDITOR_NO_HOVER_CONFIGURED_ID + * or EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a + * hover contributed as phpEditorTextHovers. + *

                                                      + * + * @see #EDITOR_NO_HOVER_CONFIGURED_ID + * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID + * @see JavaUI ID_*_HOVER + * @since 2.1 + */ + public static final String EDITOR_CTRL_ALT_SHIFT_HOVER = "ctrlAltShiftHover"; //$NON-NLS-1$ + + /** + * A named preference that defines the hover shown when the + * CTRL + SHIFT modifier keys is pressed. + *

                                                      + * Value is of type String: possible values are + * EDITOR_NO_HOVER_CONFIGURED_ID + * or EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a + * hover contributed as phpEditorTextHovers. + *

                                                      + * + * @see #EDITOR_NO_HOVER_CONFIGURED_ID + * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID + * @see JavaUI ID_*_HOVER + * @since 2.1 + */ + public static final String EDITOR_CTRL_SHIFT_HOVER = "ctrlShiftHover"; //$NON-NLS-1$ + + /** + * A named preference that defines the hover shown when the ALT + * modifier key is pressed. + *

                                                      + * Value is of type String: possible values are + * EDITOR_NO_HOVER_CONFIGURED_ID, + * EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a + * hover contributed as phpEditorTextHovers. + *

                                                      + * + * @see #EDITOR_NO_HOVER_CONFIGURED_ID + * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID + * @see JavaUI ID_*_HOVER + * @since 2.1 + */ + public static final String EDITOR_ALT_SHIFT_HOVER = "altShiftHover"; //$NON-NLS-1$ + + /** + * A string value used by the named preferences for hover configuration to + * descibe that no hover should be shown for the given key modifiers. + * + * @since 2.1 + */ + public static final String EDITOR_NO_HOVER_CONFIGURED_ID = "noHoverConfiguredId"; //$NON-NLS-1$ + + /** + * A string value used by the named preferences for hover configuration to + * descibe that the default hover should be shown for the given key + * modifiers. The default hover is described by the + * EDITOR_DEFAULT_HOVER property. + * + * @since 2.1 + */ + public static final String EDITOR_DEFAULT_HOVER_CONFIGURED_ID = "defaultHoverConfiguredId"; //$NON-NLS-1$ + + /** + * A named preference that defines the hover named the 'default hover'. + * Value is of type String: possible values are + * EDITOR_NO_HOVER_CONFIGURED_ID + * or the hover id of a hover + * contributed as phpEditorTextHovers. + *

                                                      + *@since 2.1 + */ + public static final String EDITOR_DEFAULT_HOVER = "defaultHover"; //$NON-NLS-1$ + + /** + * A named preference that controls if segmented view (show selected element + * only) is turned on or off. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public static final String EDITOR_SHOW_SEGMENTS = "net.sourceforge.phpdt.ui.editor.showSegments"; //$NON-NLS-1$ + + /** + * A named preference that controls if browser like links are turned on or + * off. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public static final String EDITOR_BROWSER_LIKE_LINKS = "browserLikeLinks"; //$NON-NLS-1$ + + /** + * A named preference that controls the key modifier for browser like links. + *

                                                      + * Value is of type String. + *

                                                      + * + * @since 2.1 + */ + public static final String EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER = "browserLikeLinksKeyModifier"; //$NON-NLS-1$ + + /** + * A named preference that controls whether occurrences are marked in the + * editor. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public static final String EDITOR_MARK_OCCURRENCES = "markOccurrences"; //$NON-NLS-1$ + + /** + * A named preference that controls whether occurrences are sticky in the + * editor. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public static final String EDITOR_STICKY_OCCURRENCES = "stickyOccurrences"; //$NON-NLS-1$ + + /** + * A named preference that controls disabling of the overwrite mode. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public static final String EDITOR_DISABLE_OVERWRITE_MODE = "disable_overwrite_mode"; //$NON-NLS-1$ + + /** + * A named preference that controls the "smart semicolon" smart typing + * handler + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public static final String EDITOR_SMART_SEMICOLON = "smart_semicolon"; //$NON-NLS-1$ + + /** + * A named preference that controls the smart backspace behavior. + *

                                                      + * Value is of type Boolean. + * + * @since 3.0 + */ + public static final String EDITOR_SMART_BACKSPACE = "smart_backspace"; //$NON-NLS-1$ + + /** + * A named preference that controls the "smart opening brace" smart typing + * handler + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public static final String EDITOR_SMART_OPENING_BRACE = "smart_opening_brace"; //$NON-NLS-1$ + + /** + * A named preference that controls the smart tab behaviour. + *

                                                      + * Value is of type Boolean. + * + * @since 3.0 + */ + public static final String EDITOR_SMART_TAB = "smart_tab"; //$NON-NLS-1$ + + public static final String EDITOR_P_RTRIM_ON_SAVE = "editor_p_trim_on_save"; //$NON-NLS-1$ + + /** + * A named preference that controls whether Java comments should be + * spell-checked. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String SPELLING_CHECK_SPELLING = ISpellCheckPreferenceKeys.SPELLING_CHECK_SPELLING; + + /** + * A named preference that controls whether words containing digits should + * be skipped during spell-checking. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String SPELLING_IGNORE_DIGITS = ISpellCheckPreferenceKeys.SPELLING_IGNORE_DIGITS; + + /** + * A named preference that controls whether mixed case words should be + * skipped during spell-checking. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String SPELLING_IGNORE_MIXED = ISpellCheckPreferenceKeys.SPELLING_IGNORE_MIXED; + + /** + * A named preference that controls whether sentence capitalization should + * be ignored during spell-checking. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String SPELLING_IGNORE_SENTENCE = ISpellCheckPreferenceKeys.SPELLING_IGNORE_SENTENCE; + + /** + * A named preference that controls whether upper case words should be + * skipped during spell-checking. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String SPELLING_IGNORE_UPPER = ISpellCheckPreferenceKeys.SPELLING_IGNORE_UPPER; + + /** + * A named preference that controls whether urls should be ignored during + * spell-checking. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String SPELLING_IGNORE_URLS = ISpellCheckPreferenceKeys.SPELLING_IGNORE_URLS; + + /** + * A named preference that controls the locale used for spell-checking. + *

                                                      + * Value is of type String. + *

                                                      + * + * @since 3.0 + */ + public final static String SPELLING_LOCALE = ISpellCheckPreferenceKeys.SPELLING_LOCALE; + + /** + * A named preference that controls the number of proposals offered during + * spell-checking. + *

                                                      + * Value is of type Integer. + *

                                                      + * + * @since 3.0 + */ + public final static String SPELLING_PROPOSAL_THRESHOLD = ISpellCheckPreferenceKeys.SPELLING_PROPOSAL_THRESHOLD; + + /** + * A named preference that specifies the workspace user dictionary. + *

                                                      + * Value is of type Integer. + *

                                                      + * + * @since 3.0 + */ + public final static String SPELLING_USER_DICTIONARY = ISpellCheckPreferenceKeys.SPELLING_USER_DICTIONARY; + + /** + * A named preference that specifies whether spelling dictionaries are + * available to content assist. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String SPELLING_ENABLE_CONTENTASSIST = ISpellCheckPreferenceKeys.SPELLING_ENABLE_CONTENTASSIST; + + /** + * A named preference that controls whether code snippets are formatted in + * Javadoc comments. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String FORMATTER_COMMENT_FORMATSOURCE = "comment_format_source_code"; //$NON-NLS-1$ + + /** + * A named preference that controls whether description of Javadoc + * parameters are indented. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String FORMATTER_COMMENT_INDENTPARAMETERDESCRIPTION = "comment_indent_parameter_description"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the header comment of a Java + * source file is formatted. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String FORMATTER_COMMENT_FORMATHEADER = "comment_format_header"; //$NON-NLS-1$ + + /** + * A named preference that controls whether Javadoc root tags are indented. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String FORMATTER_COMMENT_INDENTROOTTAGS = "comment_indent_root_tags"; //$NON-NLS-1$ + + /** + * A named preference that controls whether Javadoc comments are formatted + * by the content formatter. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String FORMATTER_COMMENT_FORMAT = "comment_format_comments"; //$NON-NLS-1$ + + /** + * A named preference that controls whether a new line is inserted after + * Javadoc root tag parameters. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String FORMATTER_COMMENT_NEWLINEFORPARAMETER = "comment_new_line_for_parameter"; //$NON-NLS-1$ + + /** + * A named preference that controls whether an empty line is inserted before + * the Javadoc root tag block. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String FORMATTER_COMMENT_SEPARATEROOTTAGS = "comment_separate_root_tags"; //$NON-NLS-1$ + + /** + * A named preference that controls whether blank lines are cleared during + * formatting + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String FORMATTER_COMMENT_CLEARBLANKLINES = "comment_clear_blank_lines"; //$NON-NLS-1$ + + /** + * A named preference that controls the line length of comments. + *

                                                      + * Value is of type Integer. The value must be at least 4 + * for reasonable formatting. + *

                                                      + * + * @since 3.0 + */ + public final static String FORMATTER_COMMENT_LINELENGTH = "comment_line_length"; //$NON-NLS-1$ + + /** + * A named preference that controls whether html tags are formatted. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String FORMATTER_COMMENT_FORMATHTML = "comment_format_html"; //$NON-NLS-1$ + + /** + * A named preference that controls if the Java code assist gets auto + * activated. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String CODEASSIST_AUTOACTIVATION = "content_assist_autoactivation"; //$NON-NLS-1$ + + /** + * A name preference that holds the auto activation delay time in milli + * seconds. + *

                                                      + * Value is of type Int. + *

                                                      + */ + public final static String CODEASSIST_AUTOACTIVATION_DELAY = "content_assist_autoactivation_delay"; //$NON-NLS-1$ + + /** + * A named preference that controls if code assist contains only visible + * proposals. + *

                                                      + * Value is of type Boolean. if + * true code assist only contains visible members. If + * false all members are included. + *

                                                      + */ + public final static String CODEASSIST_SHOW_VISIBLE_PROPOSALS = "content_assist_show_visible_proposals"; //$NON-NLS-1$ + + /** + * A named preference that controls if the Java code assist inserts a + * proposal automatically if only one proposal is available. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String CODEASSIST_AUTOINSERT = "content_assist_autoinsert"; //$NON-NLS-1$ + + /** + * A named preference that controls if the Java code assist adds import + * statements. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String CODEASSIST_ADDIMPORT = "content_assist_add_import"; //$NON-NLS-1$ + + /** + * A named preference that controls if the Java code assist only inserts + * completions. If set to false the proposals can also _replace_ code. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String CODEASSIST_INSERT_COMPLETION = "content_assist_insert_completion"; //$NON-NLS-1$ + + /** + * A named preference that controls whether code assist proposals filtering + * is case sensitive or not. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String CODEASSIST_CASE_SENSITIVITY = "content_assist_case_sensitivity"; //$NON-NLS-1$ + + /** + * A named preference that defines if code assist proposals are sorted in + * alphabetical order. + *

                                                      + * Value is of type Boolean. If true that are + * sorted in alphabetical order. If false that are unsorted. + *

                                                      + */ + public final static String CODEASSIST_ORDER_PROPOSALS = "content_assist_order_proposals"; //$NON-NLS-1$ + + /** + * A named preference that controls if argument names are filled in when a + * method is selected from as list of code assist proposal. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public final static String CODEASSIST_FILL_ARGUMENT_NAMES = "content_assist_fill_method_arguments"; //$NON-NLS-1$ + + /** + * A named preference that controls if method arguments are guessed when a + * method is selected from as list of code assist proposal. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public final static String CODEASSIST_GUESS_METHOD_ARGUMENTS = "content_assist_guess_method_arguments"; //$NON-NLS-1$ + + /** + * A named preference that holds the characters that auto activate code + * assist in PHP code. + *

                                                      + * Value is of type Sring. All characters that trigger auto + * code assist in PHP code. + *

                                                      + */ + public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA = "content_assist_autoactivation_triggers_php"; //$NON-NLS-1$ + + /** + * A named preference that holds the characters that auto activate code + * assist in PHPDoc. + *

                                                      + * Value is of type Sring. All characters that trigger auto + * code assist in PHPDoc. + *

                                                      + */ + public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC = "content_assist_autoactivation_triggers_phpdoc"; //$NON-NLS-1$ + + /** + * A named preference that holds the characters that auto activate code + * assist in HTML. + *

                                                      + * Value is of type Sring. All characters that trigger auto + * code assist in HTML. + *

                                                      + */ + public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_HTML = "content_assist_autoactivation_triggers_html"; //$NON-NLS-1$ + + /** + * A named preference that holds the background color used in the code + * assist selection dialog. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String CODEASSIST_PROPOSALS_BACKGROUND = "content_assist_proposals_background"; //$NON-NLS-1$ + + /** + * A named preference that holds the foreground color used in the code + * assist selection dialog. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String CODEASSIST_PROPOSALS_FOREGROUND = "content_assist_proposals_foreground"; //$NON-NLS-1$ + + /** + * A named preference that holds the background color used for parameter + * hints. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String CODEASSIST_PARAMETERS_BACKGROUND = "content_assist_parameters_background"; //$NON-NLS-1$ + + /** + * A named preference that holds the foreground color used in the code + * assist selection dialog + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String CODEASSIST_PARAMETERS_FOREGROUND = "content_assist_parameters_foreground"; //$NON-NLS-1$ + + /** + * A named preference that holds the background color used in the code + * assist selection dialog to mark replaced code. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + * @since 2.1 + */ + public final static String CODEASSIST_REPLACEMENT_BACKGROUND = "content_assist_completion_replacement_background"; //$NON-NLS-1$ + + /** + * A named preference that holds the foreground color used in the code + * assist selection dialog to mark replaced code. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + * @since 2.1 + */ + public final static String CODEASSIST_REPLACEMENT_FOREGROUND = "content_assist_completion_replacement_foreground"; //$NON-NLS-1$ + + /** + * A named preference that controls the behaviour of the refactoring wizard + * for showing the error page. + *

                                                      + * Value is of type String. Valid values are: + * REFACTOR_FATAL_SEVERITY, + * REFACTOR_ERROR_SEVERITY,REFACTOR_WARNING_SEVERITY + * REFACTOR_INFO_SEVERITY, + * REFACTOR_OK_SEVERITY. + *

                                                      + * + * @see #REFACTOR_FATAL_SEVERITY + * @see #REFACTOR_ERROR_SEVERITY + * @see #REFACTOR_WARNING_SEVERITY + * @see #REFACTOR_INFO_SEVERITY + * @see #REFACTOR_OK_SEVERITY + */ + public static final String REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD = "Refactoring.ErrorPage.severityThreshold"; //$NON-NLS-1$ + + /** + * A string value used by the named preference + * REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD. + * + * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD + */ + public static final String REFACTOR_FATAL_SEVERITY = "4"; //$NON-NLS-1$ + + /** + * A string value used by the named preference + * REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD. + * + * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD + */ + public static final String REFACTOR_ERROR_SEVERITY = "3"; //$NON-NLS-1$ + + /** + * A string value used by the named preference + * REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD. + * + * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD + */ + public static final String REFACTOR_WARNING_SEVERITY = "2"; //$NON-NLS-1$ + + /** + * A string value used by the named preference + * REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD. + * + * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD + */ + public static final String REFACTOR_INFO_SEVERITY = "1"; //$NON-NLS-1$ + + /** + * A string value used by the named preference + * REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD. + * + * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD + */ + public static final String REFACTOR_OK_SEVERITY = "0"; //$NON-NLS-1$ + + /** + * A named preference thet controls whether all dirty editors are + * automatically saved before a refactoring is executed. + *

                                                      + * Value is of type Boolean. + *

                                                      + */ + public static final String REFACTOR_SAVE_ALL_EDITORS = "Refactoring.savealleditors"; //$NON-NLS-1$ + + /** + * A named preference that controls if the Java Browsing views are linked to + * the active editor. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @see #LINK_PACKAGES_TO_EDITOR + */ + public static final String BROWSING_LINK_VIEW_TO_EDITOR = "net.sourceforge.phpdt.ui.browsing.linktoeditor"; //$NON-NLS-1$ + + /** + * A named preference that controls the layout of the Java Browsing views + * vertically. Boolean value. + *

                                                      + * Value is of type Boolean. If + * true the views are stacked vertical. + * If false they are stacked horizontal. + *

                                                      + */ + public static final String BROWSING_STACK_VERTICALLY = "net.sourceforge.phpdt.ui.browsing.stackVertically"; //$NON-NLS-1$ + + /** + * A named preference that controls if templates are formatted when applied. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 2.1 + */ + public static final String TEMPLATES_USE_CODEFORMATTER = "net.sourceforge.phpdt.ui.template.format"; //$NON-NLS-1$ + + /** + * A named preference that controls whether annotation roll over is used or + * not. + *

                                                      + * Value is of type Boolean. If + * true the annotation ruler column + * uses a roll over to display multiple annotations + *

                                                      * - * @since 3.1 + * @since 3.0 */ - public static final String EDITOR_FOLDING_HEADERS= "editor_folding_default_headers"; //$NON-NLS-1$ - - public static void initializeDefaultValues(IPreferenceStore store) { - store.setDefault(PreferenceConstants.EDITOR_SHOW_SEGMENTS, false); - - // JavaBasePreferencePage - store.setDefault(PreferenceConstants.LINK_PACKAGES_TO_EDITOR, true); - store.setDefault(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR, false); - store.setDefault(PreferenceConstants.LINK_BROWSING_VIEW_TO_EDITOR, true); - store.setDefault(PreferenceConstants.OPEN_TYPE_HIERARCHY, PreferenceConstants.OPEN_TYPE_HIERARCHY_IN_VIEW_PART); - store.setDefault(PreferenceConstants.DOUBLE_CLICK, PreferenceConstants.DOUBLE_CLICK_EXPANDS); - store.setDefault(PreferenceConstants.UPDATE_JAVA_VIEWS, PreferenceConstants.UPDATE_WHILE_EDITING); - - // AppearancePreferencePage - store.setDefault(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES, false); - store.setDefault(PreferenceConstants.APPEARANCE_METHOD_RETURNTYPE, false); - store.setDefault(PreferenceConstants.SHOW_CU_CHILDREN, true); - store.setDefault(PreferenceConstants.APPEARANCE_OVERRIDE_INDICATOR, true); - store.setDefault(PreferenceConstants.BROWSING_STACK_VERTICALLY, false); - store.setDefault(PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW, ""); //$NON-NLS-1$ - store.setDefault(PreferenceConstants.APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER, true); - - // ImportOrganizePreferencePage -// store.setDefault(PreferenceConstants.ORGIMPORTS_IMPORTORDER, "php;phpx;org;com"); //$NON-NLS-1$ - store.setDefault(PreferenceConstants.ORGIMPORTS_ONDEMANDTHRESHOLD, 99); - store.setDefault(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE, true); - - // ClasspathVariablesPreferencePage - // CodeFormatterPreferencePage - // CompilerPreferencePage - // no initialization needed - - // RefactoringPreferencePage - store.setDefault(PreferenceConstants.REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD, PreferenceConstants.REFACTOR_ERROR_SEVERITY); - store.setDefault(PreferenceConstants.REFACTOR_SAVE_ALL_EDITORS, false); - store.setDefault("RefactoringUI", "dialog"); - - // TemplatePreferencePage - store.setDefault(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER, true); - - // CodeGenerationPreferencePage - store.setDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_PREFIX, false); - store.setDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_SUFFIX, false); - store.setDefault(PreferenceConstants.CODEGEN_GETTERSETTER_PREFIX, "fg, f, _$, _, m_"); //$NON-NLS-1$ - store.setDefault(PreferenceConstants.CODEGEN_GETTERSETTER_SUFFIX, "_"); //$NON-NLS-1$ - - store.setDefault(PreferenceConstants.CODEGEN_KEYWORD_THIS, false); - store.setDefault(PreferenceConstants.CODEGEN_IS_FOR_GETTERS, true); - store.setDefault(PreferenceConstants.CODEGEN_EXCEPTION_VAR_NAME, "e"); //$NON-NLS-1$ - store.setDefault(PreferenceConstants.CODEGEN_ADD_COMMENTS, true); - store.setDefault(PreferenceConstants.CODEGEN__NON_JAVADOC_COMMENTS, false); - store.setDefault(PreferenceConstants.CODEGEN__FILE_COMMENTS, false); - - // MembersOrderPreferencePage - store.setDefault(PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER, "T,SF,SI,SM,I,F,C,M"); //$NON-NLS-1$ - store.setDefault(PreferenceConstants.APPEARANCE_VISIBILITY_SORT_ORDER, "B,V,R,D"); //$NON-NLS-1$ - store.setDefault(PreferenceConstants.APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER, false); - // must add here to guarantee that it is the first in the listener list - store.addPropertyChangeListener(PHPeclipsePlugin.getDefault().getMemberOrderPreferenceCache()); + public static final String EDITOR_ANNOTATION_ROLL_OVER = "editor_annotation_roll_over"; //$NON-NLS-1$ - store.setDefault(PreferenceConstants.EDITOR_MATCHING_BRACKETS, true); - PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR, new RGB(192, 192, 192)); + /** + * A named preference that controls the key modifier mask for browser like + * links. The value is only used if the value of + * EDITOR_BROWSER_LIKE_LINKS cannot be resolved to valid SWT + * modifier bits. + *

                                                      + * Value is of type String. + *

                                                      + * + * @see #EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER + * @since 2.1.1 + */ + public static final String EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK = "browserLikeLinksKeyModifierMask"; //$NON-NLS-1$ - store.setDefault(PreferenceConstants.EDITOR_CURRENT_LINE, true); - PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_CURRENT_LINE_COLOR, new RGB(225, 235, 224)); + /** + * A named preference that defines the key for the hover modifier state + * masks. The value is only used if the value of + * EDITOR_TEXT_HOVER_MODIFIERS cannot be resolved to valid + * SWT modifier bits. + * + * @see JavaUI + * @see #EDITOR_TEXT_HOVER_MODIFIERS + * @since 2.1.1 + */ + public static final String EDITOR_TEXT_HOVER_MODIFIER_MASKS = "hoverModifierMasks"; //$NON-NLS-1$ - store.setDefault(PreferenceConstants.EDITOR_PRINT_MARGIN, false); - store.setDefault(PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN, 80); - PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR, new RGB(176, 180, 185)); + /** + * A named preference that controls whether folding is enabled in the Java + * editor. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public static final String EDITOR_FOLDING_ENABLED = "editor_folding_enabled"; //$NON-NLS-1$ - PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_FIND_SCOPE_COLOR, new RGB(185, 176, 180)); + /** + * A named preference that stores the configured folding provider. + *

                                                      + * Value is of type String. + *

                                                      + * + * @since 3.0 + */ + public static final String EDITOR_FOLDING_PROVIDER = "editor_folding_provider"; //$NON-NLS-1$ + + /** + * A named preference that stores the value for Javadoc folding for the + * default folding provider. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public static final String EDITOR_FOLDING_JAVADOC = "editor_folding_default_javadoc"; //$NON-NLS-1$ + + /** + * A named preference that stores the value for inner type folding for the + * default folding provider. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public static final String EDITOR_FOLDING_INNERTYPES = "editor_folding_default_innertypes"; //$NON-NLS-1$ + + /** + * A named preference that stores the value for method folding for the + * default folding provider. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public static final String EDITOR_FOLDING_METHODS = "editor_folding_default_methods"; //$NON-NLS-1$ - // store.setDefault(PreferenceConstants.EDITOR_PROBLEM_INDICATION, true); - // PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR, new RGB(255, 0, 128)); - // store.setDefault(PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER, true); - // - // store.setDefault(PreferenceConstants.EDITOR_WARNING_INDICATION, true); - // PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR, new RGB(244, 200, 45)); - // store.setDefault(PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER, true); - // - // store.setDefault(PreferenceConstants.EDITOR_TASK_INDICATION, false); - // PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_TASK_INDICATION_COLOR, new RGB(0, 128, 255)); - // store.setDefault(PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER, false); - // - // store.setDefault(PreferenceConstants.EDITOR_BOOKMARK_INDICATION, false); - // PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR, new RGB(34, 164, 99)); - // store.setDefault(PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER, false); - // - // store.setDefault(PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION, false); - // PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR, new RGB(192, 192, 192)); - // store.setDefault(PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER, false); - // - // store.setDefault(PreferenceConstants.EDITOR_UNKNOWN_INDICATION, false); - // PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR, new RGB(0, 0, 0)); - // store.setDefault(PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER, false); - - store.setDefault(PreferenceConstants.EDITOR_CORRECTION_INDICATION, true); - store.setDefault(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, true); - - store.setDefault(PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, true); - - store.setDefault(PreferenceConstants.EDITOR_OVERVIEW_RULER, true); - - store.setDefault(PreferenceConstants.EDITOR_LINE_NUMBER_RULER, false); - PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR, new RGB(0, 0, 0)); - - // WorkbenchChainedTextFontFieldEditor.startPropagate(store, JFaceResources.TEXT_FONT); - - PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINKED_POSITION_COLOR, new RGB(0, 200, 100)); - PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINK_COLOR, new RGB(0, 0, 255)); - - store.setDefault(PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR, true); - - store.setDefault(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR, true); - - store.setDefault(PreferenceConstants.EDITOR_TAB_WIDTH, 4); - store.setDefault(PreferenceConstants.EDITOR_SPACES_FOR_TABS, false); - - PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR, new RGB(63, 127, 95)); - store.setDefault(PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_BOLD, false); - - PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR, new RGB(63, 127, 95)); - store.setDefault(PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_BOLD, false); - - PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_PHP_TAG_COLOR, new RGB(255, 0, 128)); - store.setDefault(PreferenceConstants.EDITOR_PHP_TAG_BOLD, true); - - PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR, new RGB(127, 0, 85)); - store.setDefault(PreferenceConstants.EDITOR_JAVA_KEYWORD_BOLD, true); - - PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_PHP_FUNCTIONNAME_COLOR, new RGB(127, 127, 159)); - store.setDefault(PreferenceConstants.EDITOR_PHP_FUNCTIONNAME_BOLD, false); - - PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_PHP_VARIABLE_COLOR, new RGB(127, 159, 191)); - store.setDefault(PreferenceConstants.EDITOR_PHP_VARIABLE_BOLD, false); - - PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_PHP_VARIABLE_DOLLAR_COLOR, new RGB(127, 159, 191)); - store.setDefault(PreferenceConstants.EDITOR_PHP_VARIABLE_DOLLAR_BOLD, false); - - PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_PHP_CONSTANT_COLOR, new RGB(127, 0, 85)); - store.setDefault(PreferenceConstants.EDITOR_PHP_CONSTANT_BOLD, false); - - PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_PHP_TYPE_COLOR, new RGB(127, 0, 85)); - store.setDefault(PreferenceConstants.EDITOR_PHP_TYPE_BOLD, false); - - PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_STRING_COLOR_DQ, PHPColorProvider.STRING_DQ); - store.setDefault(PreferenceConstants.EDITOR_STRING_BOLD_DQ, false); - - PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_STRING_COLOR_SQ, PHPColorProvider.STRING_SQ); - store.setDefault(PreferenceConstants.EDITOR_STRING_BOLD_SQ, true); - - PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR, new RGB(0, 0, 0)); - store.setDefault(PreferenceConstants.EDITOR_JAVA_DEFAULT_BOLD, false); - - PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR, new RGB(127, 159, 191)); - store.setDefault(PreferenceConstants.EDITOR_JAVADOC_KEYWORD_BOLD, true); - - PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR, new RGB(127, 127, 159)); - store.setDefault(PreferenceConstants.EDITOR_JAVADOC_TAG_BOLD, false); - - PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR, new RGB(63, 63, 191)); - store.setDefault(PreferenceConstants.EDITOR_JAVADOC_LINKS_BOLD, false); - - PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR, new RGB(63, 95, 191)); - store.setDefault(PreferenceConstants.EDITOR_JAVADOC_DEFAULT_BOLD, false); - - store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION, true); - store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY, 500); - - store.setDefault(PreferenceConstants.CODEASSIST_AUTOINSERT, true); - PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND, new RGB(254, 241, 233)); - PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND, new RGB(0, 0, 0)); - PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND, new RGB(254, 241, 233)); - PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND, new RGB(0, 0, 0)); - PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND, new RGB(255, 255, 0)); - PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND, new RGB(255, 0, 0)); - store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA, "$>"); //$NON-NLS-1$ - store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC, "@"); //$NON-NLS-1$ - store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_HTML, "<&#"); //$NON-NLS-1$ - store.setDefault(PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS, true); - store.setDefault(PreferenceConstants.CODEASSIST_CASE_SENSITIVITY, false); - store.setDefault(PreferenceConstants.CODEASSIST_ORDER_PROPOSALS, false); - store.setDefault(PreferenceConstants.CODEASSIST_ADDIMPORT, true); - store.setDefault(PreferenceConstants.CODEASSIST_INSERT_COMPLETION, true); - store.setDefault(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES, false); - store.setDefault(PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS, true); - store.setDefault(PreferenceConstants.CODEASSIST_PREFIX_COMPLETION, false); - - store.setDefault(PreferenceConstants.EDITOR_SMART_HOME_END, true); - store.setDefault(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION, true); - store.setDefault(PreferenceConstants.EDITOR_SMART_PASTE, true); - store.setDefault(PreferenceConstants.EDITOR_CLOSE_STRINGS_DQ_PHP, true); - store.setDefault(PreferenceConstants.EDITOR_CLOSE_STRINGS_SQ_PHP, true); - store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP, true); - store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACES, true); - store.setDefault(PreferenceConstants.EDITOR_CLOSE_JAVADOCS, true); - store.setDefault(PreferenceConstants.EDITOR_WRAP_WORDS, false); - store.setDefault(PreferenceConstants.EDITOR_WRAP_STRINGS_DQ, true); - store.setDefault(PreferenceConstants.EDITOR_ESCAPE_STRINGS_DQ, false); - store.setDefault(PreferenceConstants.EDITOR_WRAP_STRINGS_SQ, true); - store.setDefault(PreferenceConstants.EDITOR_ESCAPE_STRINGS_SQ, false); - store.setDefault(PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, true); - store.setDefault(PreferenceConstants.EDITOR_FORMAT_JAVADOCS, false); - store.setDefault(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE, false); - - store.setDefault(PreferenceConstants.EDITOR_CLOSE_STRINGS_HTML, true); - store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACKETS_HTML, true); - - // store.setDefault(PreferenceConstants.EDITOR_DEFAULT_HOVER, JavaPlugin.ID_BESTMATCH_HOVER); - store.setDefault(PreferenceConstants.EDITOR_NONE_HOVER, PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); - // store.setDefault(PreferenceConstants.EDITOR_CTRL_HOVER, JavaPlugin.ID_SOURCE_HOVER); - store.setDefault(PreferenceConstants.EDITOR_SHIFT_HOVER, PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); - store.setDefault(PreferenceConstants.EDITOR_CTRL_SHIFT_HOVER, PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); - store.setDefault(PreferenceConstants.EDITOR_CTRL_ALT_HOVER, PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); - store.setDefault(PreferenceConstants.EDITOR_ALT_SHIFT_HOVER, PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); - store.setDefault(PreferenceConstants.EDITOR_CTRL_ALT_SHIFT_HOVER, PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); - - String ctrl = Action.findModifierString(SWT.CTRL); - store.setDefault(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS, - "net.sourceforge.phpdt.ui.BestMatchHover;0;net.sourceforge.phpdt.ui.JavaSourceHover;" + ctrl); //$NON-NLS-1$ - store.setDefault(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS, - "net.sourceforge.phpdt.ui.BestMatchHover;0;net.sourceforge.phpdt.ui.JavaSourceHover;" + SWT.CTRL); //$NON-NLS-1$ - store.setDefault(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE, true); - - store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS, true); - store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER, ctrl); - store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK, SWT.CTRL); - -// mark occurrences + /** + * A named preference that stores the value for imports folding for the + * default folding provider. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + // public static final String EDITOR_FOLDING_IMPORTS = + // "editor_folding_default_imports"; //$NON-NLS-1$ + /** + * A named preference that stores the value for header comment folding for + * the default folding provider. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.1 + */ + public static final String EDITOR_FOLDING_HEADERS = "editor_folding_default_headers"; //$NON-NLS-1$ + + public static void initializeDefaultValues(IPreferenceStore store) { + store.setDefault(PreferenceConstants.EDITOR_SHOW_SEGMENTS, false); + + // JavaBasePreferencePage + store.setDefault(PreferenceConstants.LINK_PACKAGES_TO_EDITOR, true); + store.setDefault(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR, + false); + store + .setDefault(PreferenceConstants.LINK_BROWSING_VIEW_TO_EDITOR, + true); + store.setDefault(PreferenceConstants.OPEN_TYPE_HIERARCHY, + PreferenceConstants.OPEN_TYPE_HIERARCHY_IN_VIEW_PART); + store.setDefault(PreferenceConstants.DOUBLE_CLICK, + PreferenceConstants.DOUBLE_CLICK_EXPANDS); + store.setDefault(PreferenceConstants.UPDATE_JAVA_VIEWS, + PreferenceConstants.UPDATE_WHILE_EDITING); + + // AppearancePreferencePage + store.setDefault(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES, + false); + store.setDefault(PreferenceConstants.APPEARANCE_METHOD_RETURNTYPE, + false); + store.setDefault(PreferenceConstants.SHOW_CU_CHILDREN, true); + store.setDefault(PreferenceConstants.APPEARANCE_OVERRIDE_INDICATOR, + true); + store.setDefault(PreferenceConstants.BROWSING_STACK_VERTICALLY, false); + store.setDefault( + PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW, + ""); //$NON-NLS-1$ + store + .setDefault( + PreferenceConstants.APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER, + true); + + // ImportOrganizePreferencePage + // store.setDefault(PreferenceConstants.ORGIMPORTS_IMPORTORDER, + // "php;phpx;org;com"); //$NON-NLS-1$ + store.setDefault(PreferenceConstants.ORGIMPORTS_ONDEMANDTHRESHOLD, 99); + store.setDefault(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE, true); + + // ClasspathVariablesPreferencePage + // CodeFormatterPreferencePage + // CompilerPreferencePage + // no initialization needed + + // RefactoringPreferencePage + store.setDefault( + PreferenceConstants.REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD, + PreferenceConstants.REFACTOR_ERROR_SEVERITY); + store.setDefault(PreferenceConstants.REFACTOR_SAVE_ALL_EDITORS, false); + store.setDefault("RefactoringUI", "dialog"); + + // TemplatePreferencePage + store.setDefault(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER, true); + + // CodeGenerationPreferencePage + store.setDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_PREFIX, + false); + store.setDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_SUFFIX, + false); + store.setDefault(PreferenceConstants.CODEGEN_GETTERSETTER_PREFIX, + "fg, f, _$, _, m_"); //$NON-NLS-1$ + store.setDefault(PreferenceConstants.CODEGEN_GETTERSETTER_SUFFIX, "_"); //$NON-NLS-1$ + + store.setDefault(PreferenceConstants.CODEGEN_KEYWORD_THIS, false); + store.setDefault(PreferenceConstants.CODEGEN_IS_FOR_GETTERS, true); + store.setDefault(PreferenceConstants.CODEGEN_EXCEPTION_VAR_NAME, "e"); //$NON-NLS-1$ + store.setDefault(PreferenceConstants.CODEGEN_ADD_COMMENTS, true); + store.setDefault(PreferenceConstants.CODEGEN__NON_JAVADOC_COMMENTS, + false); + store.setDefault(PreferenceConstants.CODEGEN__FILE_COMMENTS, false); + + // MembersOrderPreferencePage + store.setDefault(PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER, + "T,SF,SI,SM,I,F,C,M"); //$NON-NLS-1$ + store.setDefault(PreferenceConstants.APPEARANCE_VISIBILITY_SORT_ORDER, + "B,V,R,D"); //$NON-NLS-1$ + store.setDefault( + PreferenceConstants.APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER, + false); + // must add here to guarantee that it is the first in the listener list + store.addPropertyChangeListener(PHPeclipsePlugin.getDefault() + .getMemberOrderPreferenceCache()); + + store.setDefault(PreferenceConstants.EDITOR_MATCHING_BRACKETS, true); + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR, new RGB( + 192, 192, 192)); + + store.setDefault(PreferenceConstants.EDITOR_CURRENT_LINE, true); + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_CURRENT_LINE_COLOR, new RGB(225, + 235, 224)); + + store.setDefault(PreferenceConstants.EDITOR_PRINT_MARGIN, false); + store.setDefault(PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN, 80); + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR, new RGB(176, + 180, 185)); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_FIND_SCOPE_COLOR, new RGB(185, 176, + 180)); + + // store.setDefault(PreferenceConstants.EDITOR_PROBLEM_INDICATION, + // true); + // PreferenceConverter.setDefault(store, + // PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR, new RGB(255, 0, + // 128)); + // store.setDefault(PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER, + // true); + // + // store.setDefault(PreferenceConstants.EDITOR_WARNING_INDICATION, + // true); + // PreferenceConverter.setDefault(store, + // PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR, new RGB(244, + // 200, 45)); + // store.setDefault(PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER, + // true); + // + // store.setDefault(PreferenceConstants.EDITOR_TASK_INDICATION, false); + // PreferenceConverter.setDefault(store, + // PreferenceConstants.EDITOR_TASK_INDICATION_COLOR, new RGB(0, 128, + // 255)); + // store.setDefault(PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER, + // false); + // + // store.setDefault(PreferenceConstants.EDITOR_BOOKMARK_INDICATION, + // false); + // PreferenceConverter.setDefault(store, + // PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR, new RGB(34, + // 164, 99)); + // store.setDefault(PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER, + // false); + // + // store.setDefault(PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION, + // false); + // PreferenceConverter.setDefault(store, + // PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR, new + // RGB(192, 192, 192)); + // store.setDefault(PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER, + // false); + // + // store.setDefault(PreferenceConstants.EDITOR_UNKNOWN_INDICATION, + // false); + // PreferenceConverter.setDefault(store, + // PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR, new RGB(0, 0, + // 0)); + // store.setDefault(PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER, + // false); + + store + .setDefault(PreferenceConstants.EDITOR_CORRECTION_INDICATION, + true); + store.setDefault( + PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, true); + + store.setDefault(PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, + true); + + store.setDefault(PreferenceConstants.EDITOR_OVERVIEW_RULER, true); + + store.setDefault(PreferenceConstants.EDITOR_LINE_NUMBER_RULER, false); + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR, new RGB(0, + 0, 0)); + + // WorkbenchChainedTextFontFieldEditor.startPropagate(store, + // JFaceResources.TEXT_FONT); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_LINKED_POSITION_COLOR, new RGB(0, + 200, 100)); + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_LINK_COLOR, new RGB(0, 0, 255)); + + store.setDefault(PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR, + true); + + store.setDefault(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR, + true); + + store.setDefault(PreferenceConstants.EDITOR_TAB_WIDTH, 4); + store.setDefault(PreferenceConstants.EDITOR_SPACES_FOR_TABS, false); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR, new RGB( + 63, 127, 95)); + store.setDefault(PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_BOLD, + false); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR, new RGB( + 63, 127, 95)); + store.setDefault(PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_BOLD, + false); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_PHP_TAG_COLOR, new RGB(255, 0, 128)); + store.setDefault(PreferenceConstants.EDITOR_PHP_TAG_BOLD, true); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR, new RGB(127, 0, + 85)); + store.setDefault(PreferenceConstants.EDITOR_JAVA_KEYWORD_BOLD, true); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_PHP_FUNCTIONNAME_COLOR, new RGB(127, + 127, 159)); + store.setDefault(PreferenceConstants.EDITOR_PHP_FUNCTIONNAME_BOLD, + false); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_PHP_VARIABLE_COLOR, new RGB(127, + 159, 191)); + store.setDefault(PreferenceConstants.EDITOR_PHP_VARIABLE_BOLD, false); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_PHP_VARIABLE_DOLLAR_COLOR, new RGB( + 127, 159, 191)); + store.setDefault(PreferenceConstants.EDITOR_PHP_VARIABLE_DOLLAR_BOLD, + false); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_PHP_CONSTANT_COLOR, new RGB(127, 0, + 85)); + store.setDefault(PreferenceConstants.EDITOR_PHP_CONSTANT_BOLD, false); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_PHP_TYPE_COLOR, new RGB(127, 0, 85)); + store.setDefault(PreferenceConstants.EDITOR_PHP_TYPE_BOLD, false); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_STRING_COLOR_DQ, + PHPColorProvider.STRING_DQ); + store.setDefault(PreferenceConstants.EDITOR_STRING_BOLD_DQ, false); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_STRING_COLOR_SQ, + PHPColorProvider.STRING_SQ); + store.setDefault(PreferenceConstants.EDITOR_STRING_BOLD_SQ, true); + + PreferenceConverter + .setDefault(store, + PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR, new RGB( + 0, 0, 0)); + store.setDefault(PreferenceConstants.EDITOR_JAVA_DEFAULT_BOLD, false); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR, new RGB(127, + 159, 191)); + store.setDefault(PreferenceConstants.EDITOR_JAVADOC_KEYWORD_BOLD, true); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR, new RGB(127, 127, + 159)); + store.setDefault(PreferenceConstants.EDITOR_JAVADOC_TAG_BOLD, false); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR, new RGB(63, 63, + 191)); + store.setDefault(PreferenceConstants.EDITOR_JAVADOC_LINKS_BOLD, false); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR, new RGB(63, + 95, 191)); + store + .setDefault(PreferenceConstants.EDITOR_JAVADOC_DEFAULT_BOLD, + false); + + store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION, true); + store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY, + 500); + + store.setDefault(PreferenceConstants.CODEASSIST_AUTOINSERT, true); + PreferenceConverter.setDefault(store, + PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND, new RGB( + 254, 241, 233)); + PreferenceConverter.setDefault(store, + PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND, new RGB(0, + 0, 0)); + PreferenceConverter.setDefault(store, + PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND, new RGB( + 254, 241, 233)); + PreferenceConverter.setDefault(store, + PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND, new RGB( + 0, 0, 0)); + PreferenceConverter.setDefault(store, + PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND, new RGB( + 255, 255, 0)); + PreferenceConverter.setDefault(store, + PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND, new RGB( + 255, 0, 0)); + store.setDefault( + PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA, + "$>"); //$NON-NLS-1$ + store.setDefault( + PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC, + "@"); //$NON-NLS-1$ + store.setDefault( + PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_HTML, + "<&#"); //$NON-NLS-1$ + store.setDefault(PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS, + true); + store + .setDefault(PreferenceConstants.CODEASSIST_CASE_SENSITIVITY, + false); + store.setDefault(PreferenceConstants.CODEASSIST_ORDER_PROPOSALS, false); + store.setDefault(PreferenceConstants.CODEASSIST_ADDIMPORT, true); + store + .setDefault(PreferenceConstants.CODEASSIST_INSERT_COMPLETION, + true); + store.setDefault(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES, + false); + store.setDefault(PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS, + true); + store.setDefault(PreferenceConstants.CODEASSIST_PREFIX_COMPLETION, + false); + + store.setDefault(PreferenceConstants.EDITOR_SMART_HOME_END, true); + store.setDefault(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION, true); + store.setDefault(PreferenceConstants.EDITOR_SMART_PASTE, true); + store.setDefault(PreferenceConstants.EDITOR_CLOSE_STRINGS_DQ_PHP, true); + store.setDefault(PreferenceConstants.EDITOR_CLOSE_STRINGS_SQ_PHP, true); + store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP, true); + store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACES, true); + store.setDefault(PreferenceConstants.EDITOR_CLOSE_JAVADOCS, true); + store.setDefault(PreferenceConstants.EDITOR_WRAP_WORDS, false); + store.setDefault(PreferenceConstants.EDITOR_WRAP_STRINGS_DQ, true); + store.setDefault(PreferenceConstants.EDITOR_ESCAPE_STRINGS_DQ, false); + store.setDefault(PreferenceConstants.EDITOR_WRAP_STRINGS_SQ, true); + store.setDefault(PreferenceConstants.EDITOR_ESCAPE_STRINGS_SQ, false); + store.setDefault(PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, true); + store.setDefault(PreferenceConstants.EDITOR_FORMAT_JAVADOCS, false); + store.setDefault(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE, + false); + + store.setDefault(PreferenceConstants.EDITOR_CLOSE_STRINGS_HTML, true); + store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACKETS_HTML, true); + + // store.setDefault(PreferenceConstants.EDITOR_DEFAULT_HOVER, + // JavaPlugin.ID_BESTMATCH_HOVER); + store.setDefault(PreferenceConstants.EDITOR_NONE_HOVER, + PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); + // store.setDefault(PreferenceConstants.EDITOR_CTRL_HOVER, + // JavaPlugin.ID_SOURCE_HOVER); + store.setDefault(PreferenceConstants.EDITOR_SHIFT_HOVER, + PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); + store.setDefault(PreferenceConstants.EDITOR_CTRL_SHIFT_HOVER, + PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); + store.setDefault(PreferenceConstants.EDITOR_CTRL_ALT_HOVER, + PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); + store.setDefault(PreferenceConstants.EDITOR_ALT_SHIFT_HOVER, + PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); + store.setDefault(PreferenceConstants.EDITOR_CTRL_ALT_SHIFT_HOVER, + PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); + + String ctrl = Action.findModifierString(SWT.CTRL); + store + .setDefault( + PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS, + "net.sourceforge.phpdt.ui.BestMatchHover;0;net.sourceforge.phpdt.ui.JavaSourceHover;" + ctrl); //$NON-NLS-1$ + store + .setDefault( + PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS, + "net.sourceforge.phpdt.ui.BestMatchHover;0;net.sourceforge.phpdt.ui.JavaSourceHover;" + SWT.CTRL); //$NON-NLS-1$ + store.setDefault(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE, + true); + + store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS, true); + store.setDefault( + PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER, + ctrl); + store + .setDefault( + PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK, + SWT.CTRL); + + // mark occurrences store.setDefault(PreferenceConstants.EDITOR_MARK_OCCURRENCES, true); store.setDefault(PreferenceConstants.EDITOR_STICKY_OCCURRENCES, true); -// store.setDefault(PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES, true); -// store.setDefault(PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES, true); -// store.setDefault(PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES, true); -// store.setDefault(PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES, true); -// store.setDefault(PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES, true); -// store.setDefault(PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES, true); -// store.setDefault(PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS, true); -// store.setDefault(PreferenceConstants.EDITOR_MARK_IMPLEMENTORS, true); - - // spell checking - store.setDefault(PreferenceConstants.SPELLING_CHECK_SPELLING, false); - store.setDefault(PreferenceConstants.SPELLING_LOCALE, SpellCheckEngine.getDefaultLocale().toString()); - store.setDefault(PreferenceConstants.SPELLING_IGNORE_DIGITS, true); - store.setDefault(PreferenceConstants.SPELLING_IGNORE_MIXED, true); - store.setDefault(PreferenceConstants.SPELLING_IGNORE_SENTENCE, true); - store.setDefault(PreferenceConstants.SPELLING_IGNORE_UPPER, true); - store.setDefault(PreferenceConstants.SPELLING_IGNORE_URLS, true); - store.setDefault(PreferenceConstants.SPELLING_USER_DICTIONARY, ""); //$NON-NLS-1$ - store.setDefault(PreferenceConstants.SPELLING_PROPOSAL_THRESHOLD, 20); - store.setDefault(PreferenceConstants.SPELLING_ENABLE_CONTENTASSIST, false); - - // folding - store.setDefault(PreferenceConstants.EDITOR_FOLDING_ENABLED, true); - store.setDefault(PreferenceConstants.EDITOR_FOLDING_PROVIDER, "net.sourceforge.phpdt.ui.text.defaultFoldingProvider"); //$NON-NLS-1$ - store.setDefault(PreferenceConstants.EDITOR_FOLDING_JAVADOC, true); - store.setDefault(PreferenceConstants.EDITOR_FOLDING_INNERTYPES, true); - store.setDefault(PreferenceConstants.EDITOR_FOLDING_METHODS, false); -// store.setDefault(PreferenceConstants.EDITOR_FOLDING_IMPORTS, false); - store.setDefault(PreferenceConstants.EDITOR_FOLDING_HEADERS, true); - - store.setDefault(PreferenceConstants.EDITOR_SMART_BACKSPACE, true); - store.setDefault(PreferenceConstants.EDITOR_P_RTRIM_ON_SAVE, false); - // do more complicated stuff - // NewJavaProjectPreferencePage.initDefaults(store); - } - - /** - * Returns the JDT-UI preference store. - * - * @return the JDT-UI preference store - */ - public static IPreferenceStore getPreferenceStore() { - return PHPeclipsePlugin.getDefault().getPreferenceStore(); - } - - // /** - // * Encodes a JRE library to be used in the named preference NEWPROJECT_JRELIBRARY_LIST. - // * - // * @param description a string value describing the JRE library. The description is used - // * to indentify the JDR library in the UI - // * @param entries an array of classpath entries to be encoded - // * - // * @return the encoded string. - // */ - // public static String encodeJRELibrary(String description, IClasspathEntry[] entries) { - // return NewJavaProjectPreferencePage.encodeJRELibrary(description, entries); - // } - // - // /** - // * Decodes an encoded JRE library and returns its description string. - // * - // * @return the description of an encoded JRE library - // * - // * @see #encodeJRELibrary(String, IClasspathEntry[]) - // */ - // public static String decodeJRELibraryDescription(String encodedLibrary) { - // return NewJavaProjectPreferencePage.decodeJRELibraryDescription(encodedLibrary); - // } - // - // /** - // * Decodes an encoded JRE library and returns its classpath entries. - // * - // * @return the array of classpath entries of an encoded JRE library. - // * - // * @see #encodeJRELibrary(String, IClasspathEntry[]) - // */ - // public static IClasspathEntry[] decodeJRELibraryClasspathEntries(String encodedLibrary) { - // return NewJavaProjectPreferencePage.decodeJRELibraryClasspathEntries(encodedLibrary); - // } - // - // /** - // * Returns the current configuration for the JRE to be used as default in new Java projects. - // * This is a convenience method to access the named preference NEWPROJECT_JRELIBRARY_LIST - // * with the index defined by NEWPROJECT_JRELIBRARY_INDEX. - // * - // * @return the current default set of classpath entries - // * - // * @see #NEWPROJECT_JRELIBRARY_LIST - // * @see #NEWPROJECT_JRELIBRARY_INDEX - // */ - // public static IClasspathEntry[] getDefaultJRELibrary() { - // return NewJavaProjectPreferencePage.getDefaultJRELibrary(); - // } + // store.setDefault(PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES, + // true); + // store.setDefault(PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES, + // true); + // store.setDefault(PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES, + // true); + // store.setDefault(PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES, + // true); + // store.setDefault(PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES, + // true); + // store.setDefault(PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES, + // true); + // store.setDefault(PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS, + // true); + // store.setDefault(PreferenceConstants.EDITOR_MARK_IMPLEMENTORS, true); + + // spell checking + store.setDefault(PreferenceConstants.SPELLING_CHECK_SPELLING, false); + store.setDefault(PreferenceConstants.SPELLING_LOCALE, SpellCheckEngine + .getDefaultLocale().toString()); + store.setDefault(PreferenceConstants.SPELLING_IGNORE_DIGITS, true); + store.setDefault(PreferenceConstants.SPELLING_IGNORE_MIXED, true); + store.setDefault(PreferenceConstants.SPELLING_IGNORE_SENTENCE, true); + store.setDefault(PreferenceConstants.SPELLING_IGNORE_UPPER, true); + store.setDefault(PreferenceConstants.SPELLING_IGNORE_URLS, true); + store.setDefault(PreferenceConstants.SPELLING_USER_DICTIONARY, ""); //$NON-NLS-1$ + store.setDefault(PreferenceConstants.SPELLING_PROPOSAL_THRESHOLD, 20); + store.setDefault(PreferenceConstants.SPELLING_ENABLE_CONTENTASSIST, + false); + + // folding + store.setDefault(PreferenceConstants.EDITOR_FOLDING_ENABLED, true); + store.setDefault(PreferenceConstants.EDITOR_FOLDING_PROVIDER, + "net.sourceforge.phpdt.ui.text.defaultFoldingProvider"); //$NON-NLS-1$ + store.setDefault(PreferenceConstants.EDITOR_FOLDING_JAVADOC, true); + store.setDefault(PreferenceConstants.EDITOR_FOLDING_INNERTYPES, true); + store.setDefault(PreferenceConstants.EDITOR_FOLDING_METHODS, false); + // store.setDefault(PreferenceConstants.EDITOR_FOLDING_IMPORTS, false); + store.setDefault(PreferenceConstants.EDITOR_FOLDING_HEADERS, true); + + store.setDefault(PreferenceConstants.EDITOR_SMART_BACKSPACE, true); + store.setDefault(PreferenceConstants.EDITOR_P_RTRIM_ON_SAVE, false); + // do more complicated stuff + // NewJavaProjectPreferencePage.initDefaults(store); + } + + /** + * Returns the JDT-UI preference store. + * + * @return the JDT-UI preference store + */ + public static IPreferenceStore getPreferenceStore() { + return PHPeclipsePlugin.getDefault().getPreferenceStore(); + } + + // /** + // * Encodes a JRE library to be used in the named preference + // NEWPROJECT_JRELIBRARY_LIST. + // * + // * @param description a string value describing the JRE library. The + // description is used + // * to indentify the JDR library in the UI + // * @param entries an array of classpath entries to be encoded + // * + // * @return the encoded string. + // */ + // public static String encodeJRELibrary(String description, + // IClasspathEntry[] entries) { + // return NewJavaProjectPreferencePage.encodeJRELibrary(description, + // entries); + // } + // + // /** + // * Decodes an encoded JRE library and returns its description string. + // * + // * @return the description of an encoded JRE library + // * + // * @see #encodeJRELibrary(String, IClasspathEntry[]) + // */ + // public static String decodeJRELibraryDescription(String encodedLibrary) { + // return + // NewJavaProjectPreferencePage.decodeJRELibraryDescription(encodedLibrary); + // } + // + // /** + // * Decodes an encoded JRE library and returns its classpath entries. + // * + // * @return the array of classpath entries of an encoded JRE library. + // * + // * @see #encodeJRELibrary(String, IClasspathEntry[]) + // */ + // public static IClasspathEntry[] decodeJRELibraryClasspathEntries(String + // encodedLibrary) { + // return + // NewJavaProjectPreferencePage.decodeJRELibraryClasspathEntries(encodedLibrary); + // } + // + // /** + // * Returns the current configuration for the JRE to be used as default in + // new Java projects. + // * This is a convenience method to access the named preference + // NEWPROJECT_JRELIBRARY_LIST + // * with the index defined by + // NEWPROJECT_JRELIBRARY_INDEX. + // * + // * @return the current default set of classpath entries + // * + // * @see #NEWPROJECT_JRELIBRARY_LIST + // * @see #NEWPROJECT_JRELIBRARY_INDEX + // */ + // public static IClasspathEntry[] getDefaultJRELibrary() { + // return NewJavaProjectPreferencePage.getDefaultJRELibrary(); + // } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/ProblemsLabelDecorator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/ProblemsLabelDecorator.java index 53e172d..674d70d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/ProblemsLabelDecorator.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/ProblemsLabelDecorator.java @@ -45,40 +45,47 @@ import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.texteditor.MarkerAnnotation; /** - * LabelDecorator that decorates an element's image with error and warning overlays that - * represent the severity of markers attached to the element's underlying resource. To see - * a problem decoration for a marker, the marker needs to be a subtype of IMarker.PROBLEM. + * LabelDecorator that decorates an element's image with error and warning + * overlays that represent the severity of markers attached to the element's + * underlying resource. To see a problem decoration for a marker, the marker + * needs to be a subtype of IMarker.PROBLEM. *

                                                      - * Note: Only images for elements in Java projects are currently updated on marker changes. + * Note: Only images for elements in Java projects are currently updated on + * marker changes. *

                                                      * * @since 2.0 */ -public class ProblemsLabelDecorator implements ILabelDecorator, ILightweightLabelDecorator { - +public class ProblemsLabelDecorator implements ILabelDecorator, + ILightweightLabelDecorator { + /** - * This is a special LabelProviderChangedEvent carring additional - * information whether the event orgins from a maker change. + * This is a special LabelProviderChangedEvent carring + * additional information whether the event orgins from a maker change. *

                                                      * ProblemsLabelChangedEvents are only generated by * ProblemsLabelDecorators. *

                                                      */ - public static class ProblemsLabelChangedEvent extends LabelProviderChangedEvent { + public static class ProblemsLabelChangedEvent extends + LabelProviderChangedEvent { private boolean fMarkerChange; /** - * Note: This constructor is for internal use only. Clients should not call this constructor. + * Note: This constructor is for internal use only. Clients should not + * call this constructor. */ - public ProblemsLabelChangedEvent(IBaseLabelProvider source, IResource[] changedResource, boolean isMarkerChange) { + public ProblemsLabelChangedEvent(IBaseLabelProvider source, + IResource[] changedResource, boolean isMarkerChange) { super(source, changedResource); - fMarkerChange= isMarkerChange; + fMarkerChange = isMarkerChange; } - + /** - * Returns whether this event origins from marker changes. If false an annotation - * model change is the origin. In this case viewers not displaying working copies can ignore these + * Returns whether this event origins from marker changes. If + * false an annotation model change is the origin. In + * this case viewers not displaying working copies can ignore these * events. * * @return if this event origins from a marker change. @@ -89,13 +96,16 @@ public class ProblemsLabelDecorator implements ILabelDecorator, ILightweightLabe } - private static final int ERRORTICK_WARNING= JavaElementImageDescriptor.WARNING; - private static final int ERRORTICK_ERROR= JavaElementImageDescriptor.ERROR; + private static final int ERRORTICK_WARNING = JavaElementImageDescriptor.WARNING; + + private static final int ERRORTICK_ERROR = JavaElementImageDescriptor.ERROR; private ImageDescriptorRegistry fRegistry; - private boolean fUseNewRegistry= false; + + private boolean fUseNewRegistry = false; + private IProblemChangedListener fProblemChangedListener; - + private ListenerList fListeners; /** @@ -103,89 +113,106 @@ public class ProblemsLabelDecorator implements ILabelDecorator, ILightweightLabe */ public ProblemsLabelDecorator() { this(null); - fUseNewRegistry= true; + fUseNewRegistry = true; } - + /* * Creates decorator with a shared image registry. * - * @param registry The registry to use or null to use the Java plugin's - * image registry. + * @param registry The registry to use or null to use the + * Java plugin's image registry. */ /** - * Note: This constructor is for internal use only. Clients should not call this constructor. + * Note: This constructor is for internal use only. Clients should not call + * this constructor. */ public ProblemsLabelDecorator(ImageDescriptorRegistry registry) { - fRegistry= registry; - fProblemChangedListener= null; + fRegistry = registry; + fProblemChangedListener = null; } - + private ImageDescriptorRegistry getRegistry() { if (fRegistry == null) { - fRegistry= fUseNewRegistry ? new ImageDescriptorRegistry() : PHPeclipsePlugin.getImageDescriptorRegistry(); + fRegistry = fUseNewRegistry ? new ImageDescriptorRegistry() + : PHPeclipsePlugin.getImageDescriptorRegistry(); } return fRegistry; } - - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see ILabelDecorator#decorateText(String, Object) */ public String decorateText(String text, Object element) { return text; - } + } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see ILabelDecorator#decorateImage(Image, Object) */ public Image decorateImage(Image image, Object obj) { - int adornmentFlags= computeAdornmentFlags(obj); + int adornmentFlags = computeAdornmentFlags(obj); if (adornmentFlags != 0) { - ImageDescriptor baseImage= new ImageImageDescriptor(image); - Rectangle bounds= image.getBounds(); - return getRegistry().get(new JavaElementImageDescriptor(baseImage, adornmentFlags, new Point(bounds.width, bounds.height))); + ImageDescriptor baseImage = new ImageImageDescriptor(image); + Rectangle bounds = image.getBounds(); + return getRegistry().get( + new JavaElementImageDescriptor(baseImage, adornmentFlags, + new Point(bounds.width, bounds.height))); } return image; } /** - * Note: This method is for internal use only. Clients should not call this method. + * Note: This method is for internal use only. Clients should not call this + * method. */ protected int computeAdornmentFlags(Object obj) { try { if (obj instanceof IJavaElement) { - IJavaElement element= (IJavaElement) obj; - int type= element.getElementType(); + IJavaElement element = (IJavaElement) obj; + int type = element.getElementType(); switch (type) { - case IJavaElement.JAVA_PROJECT: - case IJavaElement.PACKAGE_FRAGMENT_ROOT: - return getErrorTicksFromMarkers(element.getResource(), IResource.DEPTH_INFINITE, null); - case IJavaElement.PACKAGE_FRAGMENT: - case IJavaElement.CLASS_FILE: - return getErrorTicksFromMarkers(element.getResource(), IResource.DEPTH_ONE, null); - case IJavaElement.COMPILATION_UNIT: - case IJavaElement.PACKAGE_DECLARATION: - case IJavaElement.IMPORT_DECLARATION: - case IJavaElement.IMPORT_CONTAINER: - case IJavaElement.TYPE: - case IJavaElement.INITIALIZER: - case IJavaElement.METHOD: - case IJavaElement.FIELD: - ICompilationUnit cu= (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT); - if (cu != null) { - ISourceReference ref= (type == IJavaElement.COMPILATION_UNIT) ? null : (ISourceReference) element; - // The assumption is that only source elements in compilation unit can have markers - if (cu.isWorkingCopy()) { - // working copy: look at annotation model - return getErrorTicksFromWorkingCopy((ICompilationUnit) cu.getOriginalElement(), ref); - } - return getErrorTicksFromMarkers(cu.getResource(), IResource.DEPTH_ONE, ref); + case IJavaElement.JAVA_PROJECT: + case IJavaElement.PACKAGE_FRAGMENT_ROOT: + return getErrorTicksFromMarkers(element.getResource(), + IResource.DEPTH_INFINITE, null); + case IJavaElement.PACKAGE_FRAGMENT: + case IJavaElement.CLASS_FILE: + return getErrorTicksFromMarkers(element.getResource(), + IResource.DEPTH_ONE, null); + case IJavaElement.COMPILATION_UNIT: + case IJavaElement.PACKAGE_DECLARATION: + case IJavaElement.IMPORT_DECLARATION: + case IJavaElement.IMPORT_CONTAINER: + case IJavaElement.TYPE: + case IJavaElement.INITIALIZER: + case IJavaElement.METHOD: + case IJavaElement.FIELD: + ICompilationUnit cu = (ICompilationUnit) element + .getAncestor(IJavaElement.COMPILATION_UNIT); + if (cu != null) { + ISourceReference ref = (type == IJavaElement.COMPILATION_UNIT) ? null + : (ISourceReference) element; + // The assumption is that only source elements in + // compilation unit can have markers + if (cu.isWorkingCopy()) { + // working copy: look at annotation model + return getErrorTicksFromWorkingCopy( + (ICompilationUnit) cu.getOriginalElement(), + ref); } - break; - default: + return getErrorTicksFromMarkers(cu.getResource(), + IResource.DEPTH_ONE, ref); + } + break; + default: } } else if (obj instanceof IResource) { - return getErrorTicksFromMarkers((IResource) obj, IResource.DEPTH_INFINITE, null); + return getErrorTicksFromMarkers((IResource) obj, + IResource.DEPTH_INFINITE, null); } } catch (CoreException e) { if (e instanceof JavaModelException) { @@ -198,162 +225,195 @@ public class ProblemsLabelDecorator implements ILabelDecorator, ILightweightLabe return 0; } - private int getErrorTicksFromMarkers(IResource res, int depth, ISourceReference sourceElement) throws CoreException { + private int getErrorTicksFromMarkers(IResource res, int depth, + ISourceReference sourceElement) throws CoreException { if (res == null || !res.isAccessible()) { return 0; } - int info= 0; - - IMarker[] markers= res.findMarkers(IMarker.PROBLEM, true, depth); + int info = 0; + + IMarker[] markers = res.findMarkers(IMarker.PROBLEM, true, depth); if (markers != null) { - for (int i= 0; i < markers.length && (info != ERRORTICK_ERROR); i++) { - IMarker curr= markers[i]; - if (sourceElement == null || isMarkerInRange(curr, sourceElement)) { - int priority= curr.getAttribute(IMarker.SEVERITY, -1); + for (int i = 0; i < markers.length && (info != ERRORTICK_ERROR); i++) { + IMarker curr = markers[i]; + if (sourceElement == null + || isMarkerInRange(curr, sourceElement)) { + int priority = curr.getAttribute(IMarker.SEVERITY, -1); if (priority == IMarker.SEVERITY_WARNING) { - info= ERRORTICK_WARNING; + info = ERRORTICK_WARNING; } else if (priority == IMarker.SEVERITY_ERROR) { - info= ERRORTICK_ERROR; + info = ERRORTICK_ERROR; } } - } + } } return info; } - private boolean isMarkerInRange(IMarker marker, ISourceReference sourceElement) throws CoreException { + private boolean isMarkerInRange(IMarker marker, + ISourceReference sourceElement) throws CoreException { if (marker.isSubtypeOf(IMarker.TEXT)) { - int pos= marker.getAttribute(IMarker.CHAR_START, -1); + int pos = marker.getAttribute(IMarker.CHAR_START, -1); return isInside(pos, sourceElement); } return false; } - - - private int getErrorTicksFromWorkingCopy(ICompilationUnit original, ISourceReference sourceElement) throws CoreException { - int info= 0; - FileEditorInput editorInput= new FileEditorInput((IFile) original.getResource()); - IAnnotationModel model= PHPeclipsePlugin.getDefault().getCompilationUnitDocumentProvider().getAnnotationModel(editorInput); + + private int getErrorTicksFromWorkingCopy(ICompilationUnit original, + ISourceReference sourceElement) throws CoreException { + int info = 0; + FileEditorInput editorInput = new FileEditorInput((IFile) original + .getResource()); + IAnnotationModel model = PHPeclipsePlugin.getDefault() + .getCompilationUnitDocumentProvider().getAnnotationModel( + editorInput); if (model != null) { - Iterator iter= model.getAnnotationIterator(); + Iterator iter = model.getAnnotationIterator(); while ((info != ERRORTICK_ERROR) && iter.hasNext()) { - Annotation curr= (Annotation) iter.next(); - IMarker marker= isAnnotationInRange(model, curr, sourceElement); + Annotation curr = (Annotation) iter.next(); + IMarker marker = isAnnotationInRange(model, curr, sourceElement); if (marker != null) { - int priority= marker.getAttribute(IMarker.SEVERITY, -1); + int priority = marker.getAttribute(IMarker.SEVERITY, -1); if (priority == IMarker.SEVERITY_WARNING) { - info= ERRORTICK_WARNING; + info = ERRORTICK_WARNING; } else if (priority == IMarker.SEVERITY_ERROR) { - info= ERRORTICK_ERROR; + info = ERRORTICK_ERROR; } } } } return info; } - - private IMarker isAnnotationInRange(IAnnotationModel model, Annotation annot, ISourceReference sourceElement) throws CoreException { + + private IMarker isAnnotationInRange(IAnnotationModel model, + Annotation annot, ISourceReference sourceElement) + throws CoreException { if (annot instanceof MarkerAnnotation) { - IMarker marker= ((MarkerAnnotation) annot).getMarker(); + IMarker marker = ((MarkerAnnotation) annot).getMarker(); if (marker.exists() && marker.isSubtypeOf(IMarker.PROBLEM)) { - Position pos= model.getPosition(annot); - if (sourceElement == null || isInside(pos.getOffset(), sourceElement)) { + Position pos = model.getPosition(annot); + if (sourceElement == null + || isInside(pos.getOffset(), sourceElement)) { return marker; } } } return null; } - + /** * Tests if a position is inside the source range of an element. - * @param pos Position to be tested. - * @param sourceElement Source element (must be a IJavaElement) - * @return boolean Return true if position is located inside the source element. - * @throws CoreException Exception thrown if element range could not be accessed. + * + * @param pos + * Position to be tested. + * @param sourceElement + * Source element (must be a IJavaElement) + * @return boolean Return true if position is located inside + * the source element. + * @throws CoreException + * Exception thrown if element range could not be accessed. * * @since 2.1 */ - protected boolean isInside(int pos, ISourceReference sourceElement) throws CoreException { - ISourceRange range= sourceElement.getSourceRange(); + protected boolean isInside(int pos, ISourceReference sourceElement) + throws CoreException { + ISourceRange range = sourceElement.getSourceRange(); if (range != null) { - int rangeOffset= range.getOffset(); - return (rangeOffset <= pos && rangeOffset + range.getLength() > pos); + int rangeOffset = range.getOffset(); + return (rangeOffset <= pos && rangeOffset + range.getLength() > pos); } return false; - } - - /* (non-Javadoc) + } + + /* + * (non-Javadoc) + * * @see IBaseLabelProvider#dispose() */ public void dispose() { if (fProblemChangedListener != null) { - PHPeclipsePlugin.getDefault().getProblemMarkerManager().removeListener(fProblemChangedListener); - fProblemChangedListener= null; + PHPeclipsePlugin.getDefault().getProblemMarkerManager() + .removeListener(fProblemChangedListener); + fProblemChangedListener = null; } if (fRegistry != null && fUseNewRegistry) { fRegistry.dispose(); } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see IBaseLabelProvider#isLabelProperty(Object, String) */ public boolean isLabelProperty(Object element, String property) { return true; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see IBaseLabelProvider#addListener(ILabelProviderListener) */ public void addListener(ILabelProviderListener listener) { if (fListeners == null) { - fListeners= new ListenerList(); + fListeners = new ListenerList(); } fListeners.add(listener); if (fProblemChangedListener == null) { - fProblemChangedListener= new IProblemChangedListener() { - public void problemsChanged(IResource[] changedResources, boolean isMarkerChange) { + fProblemChangedListener = new IProblemChangedListener() { + public void problemsChanged(IResource[] changedResources, + boolean isMarkerChange) { fireProblemsChanged(changedResources, isMarkerChange); } }; - PHPeclipsePlugin.getDefault().getProblemMarkerManager().addListener(fProblemChangedListener); + PHPeclipsePlugin.getDefault().getProblemMarkerManager() + .addListener(fProblemChangedListener); } - } + } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see IBaseLabelProvider#removeListener(ILabelProviderListener) */ public void removeListener(ILabelProviderListener listener) { if (fListeners != null) { fListeners.remove(listener); if (fListeners.isEmpty() && fProblemChangedListener != null) { - PHPeclipsePlugin.getDefault().getProblemMarkerManager().removeListener(fProblemChangedListener); - fProblemChangedListener= null; + PHPeclipsePlugin.getDefault().getProblemMarkerManager() + .removeListener(fProblemChangedListener); + fProblemChangedListener = null; } } } - - private void fireProblemsChanged(IResource[] changedResources, boolean isMarkerChange) { + + private void fireProblemsChanged(IResource[] changedResources, + boolean isMarkerChange) { if (fListeners != null && !fListeners.isEmpty()) { - LabelProviderChangedEvent event= new ProblemsLabelChangedEvent(this, changedResources, isMarkerChange); - Object[] listeners= fListeners.getListeners(); - for (int i= 0; i < listeners.length; i++) { - ((ILabelProviderListener) listeners[i]).labelProviderChanged(event); + LabelProviderChangedEvent event = new ProblemsLabelChangedEvent( + this, changedResources, isMarkerChange); + Object[] listeners = fListeners.getListeners(); + for (int i = 0; i < listeners.length; i++) { + ((ILabelProviderListener) listeners[i]) + .labelProviderChanged(event); } } } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.ILightweightLabelDecorator#decorate(java.lang.Object, org.eclipse.jface.viewers.IDecoration) + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.ILightweightLabelDecorator#decorate(java.lang.Object, + * org.eclipse.jface.viewers.IDecoration) */ - public void decorate(Object element, IDecoration decoration) { - int adornmentFlags= computeAdornmentFlags(element); + public void decorate(Object element, IDecoration decoration) { + int adornmentFlags = computeAdornmentFlags(element); if (adornmentFlags == ERRORTICK_ERROR) { decoration.addOverlay(PHPUiImages.DESC_OVR_ERROR); } else if (adornmentFlags == ERRORTICK_WARNING) { decoration.addOverlay(PHPUiImages.DESC_OVR_WARNING); - } + } } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/StandardJavaElementContentProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/StandardJavaElementContentProvider.java index 31c8017..87d461c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/StandardJavaElementContentProvider.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/StandardJavaElementContentProvider.java @@ -34,100 +34,132 @@ import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.Viewer; - /** - * A base content provider for Java elements. It provides access to the - * Java element hierarchy without listening to changes in the Java model. - * If updating the presentation on Java model change is required than - * clients have to subclass, listen to Java model changes and have to update - * the UI using corresponding methods provided by the JFace viewers or their - * own UI presentation. + * A base content provider for Java elements. It provides access to the Java + * element hierarchy without listening to changes in the Java model. If updating + * the presentation on Java model change is required than clients have to + * subclass, listen to Java model changes and have to update the UI using + * corresponding methods provided by the JFace viewers or their own UI + * presentation. *

                                                      * The following Java element hierarchy is surfaced by this content provider: *

                                                      + * *

                                                      -Java model (IJavaModel)
                                                      -   Java project (IJavaProject)
                                                      -      package fragment root (IPackageFragmentRoot)
                                                      -         package fragment (IPackageFragment)
                                                      -            compilation unit (ICompilationUnit)
                                                      -            binary class file (IClassFile)
                                                      + *  Java model (
                                                      + * 
                                                      + * IJavaModel
                                                      + * 
                                                      + * )
                                                      + *  Java project (
                                                      + * 
                                                      + * IJavaProject
                                                      + * 
                                                      + * )
                                                      + *  package fragment root (
                                                      + * 
                                                      + * IPackageFragmentRoot
                                                      + * 
                                                      + * )
                                                      + *  package fragment (
                                                      + * 
                                                      + * IPackageFragment
                                                      + * 
                                                      + * )
                                                      + *  compilation unit (
                                                      + * 
                                                      + * ICompilationUnit
                                                      + * 
                                                      + * )
                                                      + *  binary class file (
                                                      + * 
                                                      + * IClassFile
                                                      + * 
                                                      + * )
                                                        * 
                                                      - *

                                                      + * + *

                                                      *

                                                      - * Note that when the entire Java project is declared to be package fragment root, - * the corresponding package fragment root element that normally appears between the - * Java project and the package fragments is automatically filtered out. + * Note that when the entire Java project is declared to be package fragment + * root, the corresponding package fragment root element that normally appears + * between the Java project and the package fragments is automatically filtered + * out. *

                                                      - * This content provider can optionally return working copy elements for members - * below compilation units. If enabled, working copy members are returned for those - * compilation units in the Java element hierarchy for which a shared working copy exists - * in JDT core. + * This content provider can optionally return working copy elements for members + * below compilation units. If enabled, working copy members are returned for + * those compilation units in the Java element hierarchy for which a shared + * working copy exists in JDT core. * * @see net.sourceforge.phpdt.ui.IWorkingCopyProvider * @see JavaCore#getSharedWorkingCopies(net.sourceforge.phpdt.core.IBufferFactory) * * @since 2.0 */ -public class StandardJavaElementContentProvider implements ITreeContentProvider, IWorkingCopyProvider { +public class StandardJavaElementContentProvider implements + ITreeContentProvider, IWorkingCopyProvider { + + protected static final Object[] NO_CHILDREN = new Object[0]; + + protected boolean fProvideMembers = false; - protected static final Object[] NO_CHILDREN= new Object[0]; + protected boolean fProvideWorkingCopy = false; - protected boolean fProvideMembers= false; - protected boolean fProvideWorkingCopy= false; - /** - * Creates a new content provider. The content provider does not - * provide members of compilation units or class files and it does - * not provide working copy elements. - */ + * Creates a new content provider. The content provider does not provide + * members of compilation units or class files and it does not provide + * working copy elements. + */ public StandardJavaElementContentProvider() { } - + /** * Creates a new StandardJavaElementContentProvider. - * - * @param provideMembers if true members below compilation units - * and class files are provided. - * @param provideWorkingCopy if true the element provider provides - * working copies members of compilation units which have an associated working - * copy in JDT core. Otherwise only original elements are provided. + * + * @param provideMembers + * if true members below compilation units and + * class files are provided. + * @param provideWorkingCopy + * if true the element provider provides working + * copies members of compilation units which have an associated + * working copy in JDT core. Otherwise only original elements are + * provided. */ - public StandardJavaElementContentProvider(boolean provideMembers, boolean provideWorkingCopy) { - fProvideMembers= provideMembers; - fProvideWorkingCopy= provideWorkingCopy; + public StandardJavaElementContentProvider(boolean provideMembers, + boolean provideWorkingCopy) { + fProvideMembers = provideMembers; + fProvideWorkingCopy = provideWorkingCopy; } - + /** - * Returns whether members are provided when asking - * for a compilation units or class file for its children. + * Returns whether members are provided when asking for a compilation units + * or class file for its children. * - * @return true if the content provider provides members; - * otherwise false is returned + * @return true if the content provider provides members; + * otherwise false is returned */ public boolean getProvideMembers() { return fProvideMembers; } /** - * Sets whether the content provider is supposed to return members - * when asking a compilation unit or class file for its children. + * Sets whether the content provider is supposed to return members when + * asking a compilation unit or class file for its children. * - * @param b if true then members are provided. - * If false compilation units and class files are the - * leaves provided by this content provider. + * @param b + * if true then members are provided. If + * false compilation units and class files are the + * leaves provided by this content provider. */ public void setProvideMembers(boolean b) { - fProvideMembers= b; + fProvideMembers = b; } - + /** - * Returns whether the provided members are from a working - * copy or the original compilation unit. + * Returns whether the provided members are from a working copy or the + * original compilation unit. * - * @return true if the content provider provides - * working copy members; otherwise false is - * returned + * @return true if the content provider provides working copy + * members; otherwise false is returned * * @see #setProvideWorkingCopy(boolean) */ @@ -136,314 +168,344 @@ public class StandardJavaElementContentProvider implements ITreeContentProvider, } /** - * Sets whether the members are provided from a shared working copy - * that exists for a original compilation unit in the Java element hierarchy. + * Sets whether the members are provided from a shared working copy that + * exists for a original compilation unit in the Java element hierarchy. * - * @param b if true members are provided from a - * working copy if one exists in JDT core. If false the - * provider always returns original elements. + * @param b + * if true members are provided from a working + * copy if one exists in JDT core. If false the + * provider always returns original elements. */ public void setProvideWorkingCopy(boolean b) { - fProvideWorkingCopy= b; + fProvideWorkingCopy = b; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see IWorkingCopyProvider#providesWorkingCopies() */ public boolean providesWorkingCopies() { return fProvideWorkingCopy; } - /* (non-Javadoc) - * Method declared on IStructuredContentProvider. + /* + * (non-Javadoc) Method declared on IStructuredContentProvider. */ public Object[] getElements(Object parent) { return getChildren(parent); } - - /* (non-Javadoc) - * Method declared on IContentProvider. + + /* + * (non-Javadoc) Method declared on IContentProvider. */ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } - /* (non-Javadoc) - * Method declared on IContentProvider. + /* + * (non-Javadoc) Method declared on IContentProvider. */ public void dispose() { } - /* (non-Javadoc) - * Method declared on ITreeContentProvider. + /* + * (non-Javadoc) Method declared on ITreeContentProvider. */ public Object[] getChildren(Object element) { if (!exists(element)) return NO_CHILDREN; - + try { - if (element instanceof IJavaModel) - return getJavaProjects((IJavaModel)element); - -// if (element instanceof IJavaProject) -// return getPackageFragmentRoots((IJavaProject)element); -// - if (element instanceof IPackageFragmentRoot) - return getPackageFragments((IPackageFragmentRoot)element); - -// if (element instanceof IPackageFragment) -// return getPackageContents((IPackageFragment)element); - + if (element instanceof IJavaModel) + return getJavaProjects((IJavaModel) element); + + // if (element instanceof IJavaProject) + // return getPackageFragmentRoots((IJavaProject)element); + // + if (element instanceof IPackageFragmentRoot) + return getPackageFragments((IPackageFragmentRoot) element); + + // if (element instanceof IPackageFragment) + // return getPackageContents((IPackageFragment)element); + if (element instanceof IFolder) - return getResources((IFolder)element); - - if (fProvideMembers && element instanceof ISourceReference && element instanceof IParent) { + return getResources((IFolder) element); + + if (fProvideMembers && element instanceof ISourceReference + && element instanceof IParent) { if (fProvideWorkingCopy && element instanceof ICompilationUnit) { - element= JavaModelUtil.toWorkingCopy((ICompilationUnit) element); + element = JavaModelUtil + .toWorkingCopy((ICompilationUnit) element); } - return ((IParent)element).getChildren(); + return ((IParent) element).getChildren(); } } catch (JavaModelException e) { return NO_CHILDREN; - } - return NO_CHILDREN; + } + return NO_CHILDREN; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see ITreeContentProvider */ public boolean hasChildren(Object element) { if (fProvideMembers) { // assume CUs and class files are never empty - if (element instanceof ICompilationUnit ){ -// || -// element instanceof IClassFile) { + if (element instanceof ICompilationUnit) { + // || + // element instanceof IClassFile) { return true; } } else { // don't allow to drill down into a compilation unit or class file if (element instanceof ICompilationUnit || -// element instanceof IClassFile || - element instanceof IFile) - return false; + // element instanceof IClassFile || + element instanceof IFile) + return false; } - + if (element instanceof IJavaProject) { - IJavaProject jp= (IJavaProject)element; + IJavaProject jp = (IJavaProject) element; if (!jp.getProject().isOpen()) { return false; - } + } } - + if (element instanceof IParent) { try { - // when we have Java children return true, else we fetch all the children - if (((IParent)element).hasChildren()) + // when we have Java children return true, else we fetch all the + // children + if (((IParent) element).hasChildren()) return true; - } catch(JavaModelException e) { + } catch (JavaModelException e) { return true; } } - Object[] children= getChildren(element); + Object[] children = getChildren(element); return (children != null) && children.length > 0; } - - /* (non-Javadoc) - * Method declared on ITreeContentProvider. + + /* + * (non-Javadoc) Method declared on ITreeContentProvider. */ public Object getParent(Object element) { if (!exists(element)) return null; - return internalGetParent(element); + return internalGetParent(element); } - - private Object[] getPackageFragments(IPackageFragmentRoot root) throws JavaModelException { - IJavaElement[] fragments= root.getChildren(); -// Object[] nonJavaResources= root.getNonJavaResources(); -// if (nonJavaResources == null) - return fragments; -// return concatenate(fragments, nonJavaResources); + + private Object[] getPackageFragments(IPackageFragmentRoot root) + throws JavaModelException { + IJavaElement[] fragments = root.getChildren(); + // Object[] nonJavaResources= root.getNonJavaResources(); + // if (nonJavaResources == null) + return fragments; + // return concatenate(fragments, nonJavaResources); } - + /** - * Note: This method is for internal use only. Clients should not call this method. + * Note: This method is for internal use only. Clients should not call this + * method. */ -// protected Object[] getPackageFragmentRoots(IJavaProject project) throws JavaModelException { -// if (!project.getProject().isOpen()) -// return NO_CHILDREN; -// -// IPackageFragmentRoot[] roots= project.getPackageFragmentRoots(); -// List list= new ArrayList(roots.length); -// // filter out package fragments that correspond to projects and -// // replace them with the package fragments directly -// for (int i= 0; i < roots.length; i++) { -// IPackageFragmentRoot root= (IPackageFragmentRoot)roots[i]; -// if (isProjectPackageFragmentRoot(root)) { -// Object[] children= root.getChildren(); -// for (int k= 0; k < children.length; k++) -// list.add(children[k]); -// } -// else if (hasChildren(root)) { -// list.add(root); -// } -// } -// return concatenate(list.toArray(), project.getNonJavaResources()); -// } - + // protected Object[] getPackageFragmentRoots(IJavaProject project) throws + // JavaModelException { + // if (!project.getProject().isOpen()) + // return NO_CHILDREN; + // + // IPackageFragmentRoot[] roots= project.getPackageFragmentRoots(); + // List list= new ArrayList(roots.length); + // // filter out package fragments that correspond to projects and + // // replace them with the package fragments directly + // for (int i= 0; i < roots.length; i++) { + // IPackageFragmentRoot root= (IPackageFragmentRoot)roots[i]; + // if (isProjectPackageFragmentRoot(root)) { + // Object[] children= root.getChildren(); + // for (int k= 0; k < children.length; k++) + // list.add(children[k]); + // } + // else if (hasChildren(root)) { + // list.add(root); + // } + // } + // return concatenate(list.toArray(), project.getNonJavaResources()); + // } /** - * Note: This method is for internal use only. Clients should not call this method. + * Note: This method is for internal use only. Clients should not call this + * method. */ protected Object[] getJavaProjects(IJavaModel jm) throws JavaModelException { return jm.getJavaProjects(); } - -// private Object[] getPackageContents(IPackageFragment fragment) throws JavaModelException { -// if (fragment.getKind() == IPackageFragmentRoot.K_SOURCE) { -// return concatenate(fragment.getCompilationUnits(), fragment.getNonJavaResources()); -// } -// return concatenate(fragment.getClassFiles(), fragment.getNonJavaResources()); -// } - + + // private Object[] getPackageContents(IPackageFragment fragment) throws + // JavaModelException { + // if (fragment.getKind() == IPackageFragmentRoot.K_SOURCE) { + // return concatenate(fragment.getCompilationUnits(), + // fragment.getNonJavaResources()); + // } + // return concatenate(fragment.getClassFiles(), + // fragment.getNonJavaResources()); + // } + private Object[] getResources(IFolder folder) { try { // filter out folders that are package fragment roots - Object[] members= folder.members(); - List nonJavaResources= new ArrayList(); - for (int i= 0; i < members.length; i++) { - Object o= members[i]; - // A folder can also be a package fragement root in the following case + Object[] members = folder.members(); + List nonJavaResources = new ArrayList(); + for (int i = 0; i < members.length; i++) { + Object o = members[i]; + // A folder can also be a package fragement root in the + // following case // Project - // + src <- source folder - // + excluded <- excluded from class path - // + included <- a new source folder. - // Included is a member of excluded, but since it is rendered as a source + // + src <- source folder + // + excluded <- excluded from class path + // + included <- a new source folder. + // Included is a member of excluded, but since it is rendered as + // a source // folder we have to exclude it as a normal child. if (o instanceof IFolder) { - IJavaElement element= JavaCore.create((IFolder)o); - if (element instanceof IPackageFragmentRoot && element.exists()) { + IJavaElement element = JavaCore.create((IFolder) o); + if (element instanceof IPackageFragmentRoot + && element.exists()) { continue; } } nonJavaResources.add(o); } return nonJavaResources.toArray(); - } catch(CoreException e) { + } catch (CoreException e) { return NO_CHILDREN; } } - + /** - * Note: This method is for internal use only. Clients should not call this method. + * Note: This method is for internal use only. Clients should not call this + * method. */ protected boolean isClassPathChange(IJavaElementDelta delta) { - + // need to test the flags only for package fragment roots if (delta.getElement().getElementType() != IJavaElement.PACKAGE_FRAGMENT_ROOT) return false; - - int flags= delta.getFlags(); - return (delta.getKind() == IJavaElementDelta.CHANGED && - ((flags & IJavaElementDelta.F_ADDED_TO_CLASSPATH) != 0) || - ((flags & IJavaElementDelta.F_REMOVED_FROM_CLASSPATH) != 0) || - ((flags & IJavaElementDelta.F_REORDER) != 0)); + + int flags = delta.getFlags(); + return (delta.getKind() == IJavaElementDelta.CHANGED + && ((flags & IJavaElementDelta.F_ADDED_TO_CLASSPATH) != 0) + || ((flags & IJavaElementDelta.F_REMOVED_FROM_CLASSPATH) != 0) || ((flags & IJavaElementDelta.F_REORDER) != 0)); } - + /** - * Note: This method is for internal use only. Clients should not call this method. + * Note: This method is for internal use only. Clients should not call this + * method. */ protected Object skipProjectPackageFragmentRoot(IPackageFragmentRoot root) { try { if (isProjectPackageFragmentRoot(root)) - return root.getParent(); + return root.getParent(); return root; - } catch(JavaModelException e) { + } catch (JavaModelException e) { return root; } } - + /** - * Note: This method is for internal use only. Clients should not call this method. + * Note: This method is for internal use only. Clients should not call this + * method. */ - protected boolean isPackageFragmentEmpty(IJavaElement element) throws JavaModelException { + protected boolean isPackageFragmentEmpty(IJavaElement element) + throws JavaModelException { if (element instanceof IPackageFragment) { - IPackageFragment fragment= (IPackageFragment)element; - if (!(fragment.hasChildren() ) ) -// || -// fragment.getNonJavaResources().length > 0) && fragment.hasSubpackages()) + IPackageFragment fragment = (IPackageFragment) element; + if (!(fragment.hasChildren())) + // || + // fragment.getNonJavaResources().length > 0) && + // fragment.hasSubpackages()) return true; } return false; } /** - * Note: This method is for internal use only. Clients should not call this method. + * Note: This method is for internal use only. Clients should not call this + * method. */ - protected boolean isProjectPackageFragmentRoot(IPackageFragmentRoot root) throws JavaModelException { - IResource resource= root.getResource(); + protected boolean isProjectPackageFragmentRoot(IPackageFragmentRoot root) + throws JavaModelException { + IResource resource = root.getResource(); return (resource instanceof IProject); } - + /** - * Note: This method is for internal use only. Clients should not call this method. + * Note: This method is for internal use only. Clients should not call this + * method. */ protected boolean exists(Object element) { if (element == null) { return false; } if (element instanceof IResource) { - return ((IResource)element).exists(); + return ((IResource) element).exists(); } if (element instanceof IJavaElement) { - return ((IJavaElement)element).exists(); + return ((IJavaElement) element).exists(); } return true; } - + /** - * Note: This method is for internal use only. Clients should not call this method. + * Note: This method is for internal use only. Clients should not call this + * method. */ protected Object internalGetParent(Object element) { if (element instanceof IJavaProject) { - return ((IJavaProject)element).getJavaModel(); + return ((IJavaProject) element).getJavaModel(); } // try to map resources to the containing package fragment if (element instanceof IResource) { - IResource parent= ((IResource)element).getParent(); - IJavaElement jParent= JavaCore.create(parent); + IResource parent = ((IResource) element).getParent(); + IJavaElement jParent = JavaCore.create(parent); // http://bugs.eclipse.org/bugs/show_bug.cgi?id=31374 - if (jParent != null && jParent.exists()) + if (jParent != null && jParent.exists()) return jParent; return parent; } - // for package fragments that are contained in a project package fragment + // for package fragments that are contained in a project package + // fragment // we have to skip the package fragment root as the parent. if (element instanceof IPackageFragment) { - IPackageFragmentRoot parent= (IPackageFragmentRoot)((IPackageFragment)element).getParent(); + IPackageFragmentRoot parent = (IPackageFragmentRoot) ((IPackageFragment) element) + .getParent(); return skipProjectPackageFragmentRoot(parent); } if (element instanceof IJavaElement) { - IJavaElement candidate= ((IJavaElement)element).getParent(); - // If the parent is a CU we might have shown working copy elements below CU level. If so + IJavaElement candidate = ((IJavaElement) element).getParent(); + // If the parent is a CU we might have shown working copy elements + // below CU level. If so // return the original element instead of the working copy. - if (candidate != null && candidate.getElementType() == IJavaElement.COMPILATION_UNIT) { - candidate= JavaModelUtil.toOriginal((ICompilationUnit) candidate); + if (candidate != null + && candidate.getElementType() == IJavaElement.COMPILATION_UNIT) { + candidate = JavaModelUtil + .toOriginal((ICompilationUnit) candidate); } return candidate; } return null; } - + /** - * Note: This method is for internal use only. Clients should not call this method. + * Note: This method is for internal use only. Clients should not call this + * method. */ protected static Object[] concatenate(Object[] a1, Object[] a2) { - int a1Len= a1.length; - int a2Len= a2.length; - Object[] res= new Object[a1Len + a2Len]; + int a1Len = a1.length; + int a2Len = a2.length; + Object[] res = new Object[a1Len + a2Len]; System.arraycopy(a1, 0, res, 0, a1Len); - System.arraycopy(a2, 0, res, a1Len, a2Len); + System.arraycopy(a2, 0, res, a1Len, a2Len); return res; } - } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/CustomFiltersActionGroup.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/CustomFiltersActionGroup.java index 226f4f1..e8b0078 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/CustomFiltersActionGroup.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/CustomFiltersActionGroup.java @@ -57,8 +57,7 @@ import org.eclipse.ui.IViewPart; import org.eclipse.ui.actions.ActionGroup; /** - * Action group to add the filter action to a view part's tool bar - * menu. + * Action group to add the filter action to a view part's tool bar menu. *

                                                      * This class may be instantiated; it is not intended to be subclassed. *

                                                      @@ -69,11 +68,12 @@ public class CustomFiltersActionGroup extends ActionGroup { class ShowFilterDialogAction extends Action { ShowFilterDialogAction() { - setText(FilterMessages.getString("OpenCustomFiltersDialogAction.text")); //$NON-NLS-1$ + setText(FilterMessages + .getString("OpenCustomFiltersDialogAction.text")); //$NON-NLS-1$ setImageDescriptor(PHPUiImages.DESC_ELCL_FILTER); setDisabledImageDescriptor(PHPUiImages.DESC_DLCL_FILTER); } - + public void run() { openDialog(); } @@ -87,52 +87,64 @@ public class CustomFiltersActionGroup extends ActionGroup { class FilterActionMenuContributionItem extends ContributionItem { private int fItemNumber; + private boolean fState; + private String fFilterId; + private String fFilterName; + private CustomFiltersActionGroup fActionGroup; /** * Constructor for FilterActionMenuContributionItem. * - * @param actionGroup the action group - * @param filterId the id of the filter - * @param filterName the name of the filter - * @param state the initial state of the filter - * @param itemNumber the menu item index + * @param actionGroup + * the action group + * @param filterId + * the id of the filter + * @param filterName + * the name of the filter + * @param state + * the initial state of the filter + * @param itemNumber + * the menu item index */ - public FilterActionMenuContributionItem(CustomFiltersActionGroup actionGroup, String filterId, String filterName, boolean state, int itemNumber) { + public FilterActionMenuContributionItem( + CustomFiltersActionGroup actionGroup, String filterId, + String filterName, boolean state, int itemNumber) { super(filterId); Assert.isNotNull(actionGroup); Assert.isNotNull(filterId); Assert.isNotNull(filterName); - fActionGroup= actionGroup; - fFilterId= filterId; - fFilterName= filterName; - fState= state; - fItemNumber= itemNumber; + fActionGroup = actionGroup; + fFilterId = filterId; + fFilterName = filterName; + fState = state; + fItemNumber = itemNumber; } /* * Overrides method from ContributionItem. */ public void fill(Menu menu, int index) { - MenuItem mi= new MenuItem(menu, SWT.CHECK, index); - mi.setText("&" + fItemNumber + " " + fFilterName); //$NON-NLS-1$ //$NON-NLS-2$ + MenuItem mi = new MenuItem(menu, SWT.CHECK, index); + mi.setText("&" + fItemNumber + " " + fFilterName); //$NON-NLS-1$ //$NON-NLS-2$ /* - * XXX: Don't set the image - would look bad because other menu items don't provide image - * XXX: Get working set specific image name from XML - would need to cache icons + * XXX: Don't set the image - would look bad because other menu + * items don't provide image XXX: Get working set specific image + * name from XML - would need to cache icons */ -// mi.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_JAVA_WORKING_SET)); + // mi.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_JAVA_WORKING_SET)); mi.setSelection(fState); mi.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { - fState= !fState; + fState = !fState; fActionGroup.setFilter(fFilterId, fState); } }); } - + /* * @see org.eclipse.jface.action.IContributionItem#isDynamic() */ @@ -142,63 +154,82 @@ public class CustomFiltersActionGroup extends ActionGroup { } private static final String TAG_CUSTOM_FILTERS = "customFilters"; //$NON-NLS-1$ - private static final String TAG_USER_DEFINED_PATTERNS_ENABLED= "userDefinedPatternsEnabled"; //$NON-NLS-1$ - private static final String TAG_USER_DEFINED_PATTERNS= "userDefinedPatterns"; //$NON-NLS-1$ - private static final String TAG_XML_DEFINED_FILTERS= "xmlDefinedFilters"; //$NON-NLS-1$ + + private static final String TAG_USER_DEFINED_PATTERNS_ENABLED = "userDefinedPatternsEnabled"; //$NON-NLS-1$ + + private static final String TAG_USER_DEFINED_PATTERNS = "userDefinedPatterns"; //$NON-NLS-1$ + + private static final String TAG_XML_DEFINED_FILTERS = "xmlDefinedFilters"; //$NON-NLS-1$ + private static final String TAG_LRU_FILTERS = "lastRecentlyUsedFilters"; //$NON-NLS-1$ - private static final String TAG_CHILD= "child"; //$NON-NLS-1$ - private static final String TAG_PATTERN= "pattern"; //$NON-NLS-1$ - private static final String TAG_FILTER_ID= "filterId"; //$NON-NLS-1$ - private static final String TAG_IS_ENABLED= "isEnabled"; //$NON-NLS-1$ + private static final String TAG_CHILD = "child"; //$NON-NLS-1$ + + private static final String TAG_PATTERN = "pattern"; //$NON-NLS-1$ + + private static final String TAG_FILTER_ID = "filterId"; //$NON-NLS-1$ - private static final String SEPARATOR= ","; //$NON-NLS-1$ + private static final String TAG_IS_ENABLED = "isEnabled"; //$NON-NLS-1$ - private static final int MAX_FILTER_MENU_ENTRIES= 3; - private static final String RECENT_FILTERS_GROUP_NAME= "recentFiltersGroup"; //$NON-NLS-1$ + private static final String SEPARATOR = ","; //$NON-NLS-1$ + + private static final int MAX_FILTER_MENU_ENTRIES = 3; + + private static final String RECENT_FILTERS_GROUP_NAME = "recentFiltersGroup"; //$NON-NLS-1$ private StructuredViewer fViewer; private NamePatternFilter fPatternFilter; + private Map fInstalledBuiltInFilters; - + private Map fEnabledFilterIds; + private boolean fUserDefinedPatternsEnabled; + private String[] fUserDefinedPatterns; + /** * Recently changed filter Ids stack with oldest on top (i.e. at the end). - * + * * @since 3.0 */ - private Stack fLRUFilterIdsStack; + private Stack fLRUFilterIdsStack; + /** - * Handle to menu manager to dynamically update - * the last recently used filters. + * Handle to menu manager to dynamically update the last recently used + * filters. * * @since 3.0 */ private IMenuManager fMenuManager; + /** - * The menu listener which dynamically updates - * the last recently used filters. + * The menu listener which dynamically updates the last recently used + * filters. * * @since 3.0 */ private IMenuListener fMenuListener; + /** * Filter Ids used in the last view menu invocation. * * @since 3.0 */ private String[] fFilterIdsUsedInLastViewMenu; + private HashMap fFilterDescriptorMap; + private String fTargetId; - + /** * Creates a new CustomFiltersActionGroup. * - * @param part the view part that owns this action group - * @param viewer the viewer to be filtered + * @param part + * the view part that owns this action group + * @param viewer + * the viewer to be filtered */ public CustomFiltersActionGroup(IViewPart part, StructuredViewer viewer) { this(part.getViewSite().getId(), viewer); @@ -207,23 +238,25 @@ public class CustomFiltersActionGroup extends ActionGroup { /** * Creates a new CustomFiltersActionGroup. * - * @param ownerId the id of this action group's owner - * @param viewer the viewer to be filtered + * @param ownerId + * the id of this action group's owner + * @param viewer + * the viewer to be filtered */ public CustomFiltersActionGroup(String ownerId, StructuredViewer viewer) { Assert.isNotNull(ownerId); Assert.isNotNull(viewer); - fTargetId= ownerId; - fViewer= viewer; + fTargetId = ownerId; + fViewer = viewer; - fLRUFilterIdsStack= new Stack(); + fLRUFilterIdsStack = new Stack(); initializeWithPluginContributions(); initializeWithViewDefaults(); - + installFilters(); } - + /* * Method declared on ActionGroup. */ @@ -232,139 +265,146 @@ public class CustomFiltersActionGroup extends ActionGroup { fillViewMenu(actionBars.getMenuManager()); } - public String[] removeFiltersFor(Object parent, Object element, IContentProvider contentProvider) { - String[] enabledFilters= getEnabledFilterIds(); - Set newFilters= new HashSet(); - for (int i= 0; i < enabledFilters.length; i++) { - String filterName= enabledFilters[i]; - ViewerFilter filter= (ViewerFilter) fInstalledBuiltInFilters.get(filterName); - if (filter == null) - newFilters.add(filterName); - else if (isSelected(parent, element, contentProvider, filter)) - newFilters.add(filterName); - } - if (newFilters.size() == enabledFilters.length) - return new String[0]; - return (String[])newFilters.toArray(new String[newFilters.size()]); - } - + public String[] removeFiltersFor(Object parent, Object element, + IContentProvider contentProvider) { + String[] enabledFilters = getEnabledFilterIds(); + Set newFilters = new HashSet(); + for (int i = 0; i < enabledFilters.length; i++) { + String filterName = enabledFilters[i]; + ViewerFilter filter = (ViewerFilter) fInstalledBuiltInFilters + .get(filterName); + if (filter == null) + newFilters.add(filterName); + else if (isSelected(parent, element, contentProvider, filter)) + newFilters.add(filterName); + } + if (newFilters.size() == enabledFilters.length) + return new String[0]; + return (String[]) newFilters.toArray(new String[newFilters.size()]); + } + public void setFilters(String[] newFilters) { - setEnabledFilterIds(newFilters); - updateViewerFilters(true); - } - - private boolean isSelected(Object parent, Object element, IContentProvider contentProvider, ViewerFilter filter) { - if (contentProvider instanceof ITreeContentProvider) { - // the element and all its parents have to be selected - ITreeContentProvider provider = (ITreeContentProvider) contentProvider; - while (element != null && !(element instanceof IJavaModel)) { - if (!filter.select(fViewer, parent, element)) - return false; - element= provider.getParent( element); - } - return true; - } - return filter.select(fViewer, parent, element); - } - - /** + setEnabledFilterIds(newFilters); + updateViewerFilters(true); + } + + private boolean isSelected(Object parent, Object element, + IContentProvider contentProvider, ViewerFilter filter) { + if (contentProvider instanceof ITreeContentProvider) { + // the element and all its parents have to be selected + ITreeContentProvider provider = (ITreeContentProvider) contentProvider; + while (element != null && !(element instanceof IJavaModel)) { + if (!filter.select(fViewer, parent, element)) + return false; + element = provider.getParent(element); + } + return true; + } + return filter.select(fViewer, parent, element); + } + + /** * Sets the enable state of the given filter. * - * @param filterId the id of the filter - * @param state the filter state + * @param filterId + * the id of the filter + * @param state + * the filter state */ private void setFilter(String filterId, boolean state) { // Renew filter id in LRU stack fLRUFilterIdsStack.remove(filterId); fLRUFilterIdsStack.add(0, filterId); - + fEnabledFilterIds.put(filterId, new Boolean(state)); storeViewDefaults(); - + updateViewerFilters(true); } - + private String[] getEnabledFilterIds() { - Set enabledFilterIds= new HashSet(fEnabledFilterIds.size()); - Iterator iter= fEnabledFilterIds.entrySet().iterator(); + Set enabledFilterIds = new HashSet(fEnabledFilterIds.size()); + Iterator iter = fEnabledFilterIds.entrySet().iterator(); while (iter.hasNext()) { - Map.Entry entry= (Map.Entry)iter.next(); - String id= (String)entry.getKey(); - boolean isEnabled= ((Boolean)entry.getValue()).booleanValue(); + Map.Entry entry = (Map.Entry) iter.next(); + String id = (String) entry.getKey(); + boolean isEnabled = ((Boolean) entry.getValue()).booleanValue(); if (isEnabled) enabledFilterIds.add(id); } - return (String[])enabledFilterIds.toArray(new String[enabledFilterIds.size()]); + return (String[]) enabledFilterIds.toArray(new String[enabledFilterIds + .size()]); } - private void setEnabledFilterIds(String[] enabledIds) { - Iterator iter= fEnabledFilterIds.keySet().iterator(); + Iterator iter = fEnabledFilterIds.keySet().iterator(); while (iter.hasNext()) { - String id= (String)iter.next(); + String id = (String) iter.next(); fEnabledFilterIds.put(id, Boolean.FALSE); } - for (int i= 0; i < enabledIds.length; i++) + for (int i = 0; i < enabledIds.length; i++) fEnabledFilterIds.put(enabledIds[i], Boolean.TRUE); } private void setUserDefinedPatterns(String[] patterns) { - fUserDefinedPatterns= patterns; + fUserDefinedPatterns = patterns; cleanUpPatternDuplicates(); } /** * Sets the recently changed filters. * - * @param changeHistory the change history + * @param changeHistory + * the change history * @since 3.0 */ private void setRecentlyChangedFilters(Stack changeHistory) { - Stack oldestFirstStack= new Stack(); - - int length= Math.min(changeHistory.size(), MAX_FILTER_MENU_ENTRIES); - for (int i= 0; i < length; i++) - oldestFirstStack.push(((FilterDescriptor)changeHistory.pop()).getId()); - - length= Math.min(fLRUFilterIdsStack.size(), MAX_FILTER_MENU_ENTRIES - oldestFirstStack.size()); - int NEWEST= 0; - for (int i= 0; i < length; i++) { - Object filter= fLRUFilterIdsStack.remove(NEWEST); + Stack oldestFirstStack = new Stack(); + + int length = Math.min(changeHistory.size(), MAX_FILTER_MENU_ENTRIES); + for (int i = 0; i < length; i++) + oldestFirstStack.push(((FilterDescriptor) changeHistory.pop()) + .getId()); + + length = Math.min(fLRUFilterIdsStack.size(), MAX_FILTER_MENU_ENTRIES + - oldestFirstStack.size()); + int NEWEST = 0; + for (int i = 0; i < length; i++) { + Object filter = fLRUFilterIdsStack.remove(NEWEST); if (!oldestFirstStack.contains(filter)) oldestFirstStack.push(filter); } - fLRUFilterIdsStack= oldestFirstStack; + fLRUFilterIdsStack = oldestFirstStack; } - + private boolean areUserDefinedPatternsEnabled() { return fUserDefinedPatternsEnabled; } private void setUserDefinedPatternsEnabled(boolean state) { - fUserDefinedPatternsEnabled= state; + fUserDefinedPatternsEnabled = state; } private void fillToolBar(IToolBarManager tooBar) { } /** - * Fills the given view menu with the entries managed by the - * group. + * Fills the given view menu with the entries managed by the group. * - * @param viewMenu the menu to fill + * @param viewMenu + * the menu to fill */ public void fillViewMenu(IMenuManager viewMenu) { /* - * Don't change the separator group name. - * Using this name ensures that other filters - * get contributed to the same group. + * Don't change the separator group name. Using this name ensures that + * other filters get contributed to the same group. */ viewMenu.add(new Separator("filters")); //$NON-NLS-1$ viewMenu.add(new GroupMarker(RECENT_FILTERS_GROUP_NAME)); viewMenu.add(new ShowFilterDialogAction()); - fMenuManager= viewMenu; - fMenuListener= new IMenuListener() { + fMenuManager = viewMenu; + fMenuListener = new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { removePreviousLRUFilterActions(manager); addLRUFilterActions(manager); @@ -376,28 +416,32 @@ public class CustomFiltersActionGroup extends ActionGroup { private void removePreviousLRUFilterActions(IMenuManager mm) { if (fFilterIdsUsedInLastViewMenu == null) return; - - for (int i= 0; i < fFilterIdsUsedInLastViewMenu.length; i++) + + for (int i = 0; i < fFilterIdsUsedInLastViewMenu.length; i++) mm.remove(fFilterIdsUsedInLastViewMenu[i]); } private void addLRUFilterActions(IMenuManager mm) { if (fLRUFilterIdsStack.isEmpty()) { - fFilterIdsUsedInLastViewMenu= null; + fFilterIdsUsedInLastViewMenu = null; return; } - - SortedSet sortedFilters= new TreeSet(fLRUFilterIdsStack); - String[] recentlyChangedFilterIds= (String[])sortedFilters.toArray(new String[sortedFilters.size()]); - - fFilterIdsUsedInLastViewMenu= new String[recentlyChangedFilterIds.length]; - for (int i= 0; i < recentlyChangedFilterIds.length; i++) { - String id= recentlyChangedFilterIds[i]; - fFilterIdsUsedInLastViewMenu[i]= id; - boolean state= fEnabledFilterIds.containsKey(id) && ((Boolean)fEnabledFilterIds.get(id)).booleanValue(); - FilterDescriptor filterDesc= (FilterDescriptor)fFilterDescriptorMap.get(id); + + SortedSet sortedFilters = new TreeSet(fLRUFilterIdsStack); + String[] recentlyChangedFilterIds = (String[]) sortedFilters + .toArray(new String[sortedFilters.size()]); + + fFilterIdsUsedInLastViewMenu = new String[recentlyChangedFilterIds.length]; + for (int i = 0; i < recentlyChangedFilterIds.length; i++) { + String id = recentlyChangedFilterIds[i]; + fFilterIdsUsedInLastViewMenu[i] = id; + boolean state = fEnabledFilterIds.containsKey(id) + && ((Boolean) fEnabledFilterIds.get(id)).booleanValue(); + FilterDescriptor filterDesc = (FilterDescriptor) fFilterDescriptorMap + .get(id); if (filterDesc != null) { - IContributionItem item= new FilterActionMenuContributionItem(this, id, filterDesc.getName(), state, i+1); + IContributionItem item = new FilterActionMenuContributionItem( + this, id, filterDesc.getName(), state, i + 1); mm.insertBefore(RECENT_FILTERS_GROUP_NAME, item); } } @@ -411,36 +455,38 @@ public class CustomFiltersActionGroup extends ActionGroup { fMenuManager.removeMenuListener(fMenuListener); super.dispose(); } - + private void initializeWithPluginContributions() { - fUserDefinedPatterns= new String[0]; - fUserDefinedPatternsEnabled= false; - - FilterDescriptor[] filterDescs= FilterDescriptor.getFilterDescriptors(fTargetId); - fFilterDescriptorMap= new HashMap(filterDescs.length); - fEnabledFilterIds= new HashMap(filterDescs.length); - for (int i= 0; i < filterDescs.length; i++) { - String id= filterDescs[i].getId(); - Boolean isEnabled= new Boolean(filterDescs[i].isEnabled()); + fUserDefinedPatterns = new String[0]; + fUserDefinedPatternsEnabled = false; + + FilterDescriptor[] filterDescs = FilterDescriptor + .getFilterDescriptors(fTargetId); + fFilterDescriptorMap = new HashMap(filterDescs.length); + fEnabledFilterIds = new HashMap(filterDescs.length); + for (int i = 0; i < filterDescs.length; i++) { + String id = filterDescs[i].getId(); + Boolean isEnabled = new Boolean(filterDescs[i].isEnabled()); if (fEnabledFilterIds.containsKey(id)) - PHPeclipsePlugin.logErrorMessage("WARNING: Duplicate id for extension-point \"net.sourceforge.phpdt.ui.javaElementFilters\""); //$NON-NLS-1$ + PHPeclipsePlugin + .logErrorMessage("WARNING: Duplicate id for extension-point \"net.sourceforge.phpdt.ui.javaElementFilters\""); //$NON-NLS-1$ fEnabledFilterIds.put(id, isEnabled); fFilterDescriptorMap.put(id, filterDescs[i]); } } // ---------- viewer filter handling ---------- - + private void installFilters() { - fInstalledBuiltInFilters= new HashMap(fEnabledFilterIds.size()); - fPatternFilter= new NamePatternFilter(); + fInstalledBuiltInFilters = new HashMap(fEnabledFilterIds.size()); + fPatternFilter = new NamePatternFilter(); fPatternFilter.setPatterns(getUserAndBuiltInPatterns()); fViewer.addFilter(fPatternFilter); updateBuiltInFilters(); } private void updateViewerFilters(boolean refresh) { - String[] patterns= getUserAndBuiltInPatterns(); + String[] patterns = getUserAndBuiltInPatterns(); fPatternFilter.setPatterns(patterns); fViewer.getControl().setRedraw(false); updateBuiltInFilters(); @@ -448,38 +494,41 @@ public class CustomFiltersActionGroup extends ActionGroup { fViewer.refresh(); fViewer.getControl().setRedraw(true); } - + private void updateBuiltInFilters() { - Set installedFilters= fInstalledBuiltInFilters.keySet(); - Set filtersToAdd= new HashSet(fEnabledFilterIds.size()); - Set filtersToRemove= new HashSet(fEnabledFilterIds.size()); - Iterator iter= fEnabledFilterIds.entrySet().iterator(); + Set installedFilters = fInstalledBuiltInFilters.keySet(); + Set filtersToAdd = new HashSet(fEnabledFilterIds.size()); + Set filtersToRemove = new HashSet(fEnabledFilterIds.size()); + Iterator iter = fEnabledFilterIds.entrySet().iterator(); while (iter.hasNext()) { - Map.Entry entry= (Map.Entry)iter.next(); - String id= (String)entry.getKey(); - boolean isEnabled= ((Boolean)entry.getValue()).booleanValue(); + Map.Entry entry = (Map.Entry) iter.next(); + String id = (String) entry.getKey(); + boolean isEnabled = ((Boolean) entry.getValue()).booleanValue(); if (isEnabled && !installedFilters.contains(id)) filtersToAdd.add(id); else if (!isEnabled && installedFilters.contains(id)) filtersToRemove.add(id); } - + // Install the filters - FilterDescriptor[] filterDescs= FilterDescriptor.getFilterDescriptors(fTargetId); - for (int i= 0; i < filterDescs.length; i++) { - String id= filterDescs[i].getId(); + FilterDescriptor[] filterDescs = FilterDescriptor + .getFilterDescriptors(fTargetId); + for (int i = 0; i < filterDescs.length; i++) { + String id = filterDescs[i].getId(); // just to double check - id should denote a custom filter anyway - boolean isCustomFilter= filterDescs[i].isCustomFilter(); + boolean isCustomFilter = filterDescs[i].isCustomFilter(); if (isCustomFilter) { if (filtersToAdd.contains(id)) { - ViewerFilter filter= filterDescs[i].createViewerFilter(); + ViewerFilter filter = filterDescs[i].createViewerFilter(); if (filter != null) { fViewer.addFilter(filter); fInstalledBuiltInFilters.put(id, filter); } } if (filtersToRemove.contains(id)) { - fViewer.removeFilter((ViewerFilter)fInstalledBuiltInFilters.get(id)); + fViewer + .removeFilter((ViewerFilter) fInstalledBuiltInFilters + .get(id)); fInstalledBuiltInFilters.remove(id); } } @@ -487,81 +536,95 @@ public class CustomFiltersActionGroup extends ActionGroup { } private String[] getUserAndBuiltInPatterns() { - List patterns= new ArrayList(fUserDefinedPatterns.length); + List patterns = new ArrayList(fUserDefinedPatterns.length); if (areUserDefinedPatternsEnabled()) patterns.addAll(Arrays.asList(fUserDefinedPatterns)); - FilterDescriptor[] filterDescs= FilterDescriptor.getFilterDescriptors(fTargetId); - for (int i= 0; i < filterDescs.length; i++) { - String id= filterDescs[i].getId(); - boolean isPatternFilter= filterDescs[i].isPatternFilter(); - Object isEnabled= fEnabledFilterIds.get(id); - if (isEnabled != null && isPatternFilter && ((Boolean)isEnabled).booleanValue()) + FilterDescriptor[] filterDescs = FilterDescriptor + .getFilterDescriptors(fTargetId); + for (int i = 0; i < filterDescs.length; i++) { + String id = filterDescs[i].getId(); + boolean isPatternFilter = filterDescs[i].isPatternFilter(); + Object isEnabled = fEnabledFilterIds.get(id); + if (isEnabled != null && isPatternFilter + && ((Boolean) isEnabled).booleanValue()) patterns.add(filterDescs[i].getPattern()); } - return (String[])patterns.toArray(new String[patterns.size()]); + return (String[]) patterns.toArray(new String[patterns.size()]); } // ---------- view kind/defaults persistency ---------- - + private void initializeWithViewDefaults() { // get default values for view - IPreferenceStore store= PHPeclipsePlugin.getDefault().getPreferenceStore(); + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); // XXX: can be removed once bug 22533 is fixed. if (!store.contains(getPreferenceKey("TAG_DUMMY_TO_TEST_EXISTENCE")))//$NON-NLS-1$ return; // XXX: Uncomment once bug 22533 is fixed. -// if (!store.contains(getPreferenceKey(TAG_USER_DEFINED_PATTERNS_ENABLED))) -// return; - - fUserDefinedPatternsEnabled= store.getBoolean(getPreferenceKey(TAG_USER_DEFINED_PATTERNS_ENABLED)); - setUserDefinedPatterns(CustomFiltersDialog.convertFromString(store.getString(getPreferenceKey(TAG_USER_DEFINED_PATTERNS)), SEPARATOR)); + // if + // (!store.contains(getPreferenceKey(TAG_USER_DEFINED_PATTERNS_ENABLED))) + // return; - Iterator iter= fEnabledFilterIds.keySet().iterator(); + fUserDefinedPatternsEnabled = store + .getBoolean(getPreferenceKey(TAG_USER_DEFINED_PATTERNS_ENABLED)); + setUserDefinedPatterns(CustomFiltersDialog.convertFromString(store + .getString(getPreferenceKey(TAG_USER_DEFINED_PATTERNS)), + SEPARATOR)); + + Iterator iter = fEnabledFilterIds.keySet().iterator(); while (iter.hasNext()) { - String id= (String)iter.next(); - Boolean isEnabled= new Boolean(store.getBoolean(id)); + String id = (String) iter.next(); + Boolean isEnabled = new Boolean(store.getBoolean(id)); fEnabledFilterIds.put(id, isEnabled); } - + fLRUFilterIdsStack.clear(); - String lruFilterIds= store.getString(TAG_LRU_FILTERS); - StringTokenizer tokenizer= new StringTokenizer(lruFilterIds, SEPARATOR); + String lruFilterIds = store.getString(TAG_LRU_FILTERS); + StringTokenizer tokenizer = new StringTokenizer(lruFilterIds, SEPARATOR); while (tokenizer.hasMoreTokens()) { - String id= tokenizer.nextToken(); - if (fFilterDescriptorMap.containsKey(id) && !fLRUFilterIdsStack.contains(id)) + String id = tokenizer.nextToken(); + if (fFilterDescriptorMap.containsKey(id) + && !fLRUFilterIdsStack.contains(id)) fLRUFilterIdsStack.push(id); } } private void storeViewDefaults() { // get default values for view - IPreferenceStore store= PHPeclipsePlugin.getDefault().getPreferenceStore(); + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); // XXX: can be removed once bug 22533 is fixed. - store.setValue(getPreferenceKey("TAG_DUMMY_TO_TEST_EXISTENCE"), "storedViewPreferences");//$NON-NLS-1$//$NON-NLS-2$ - - store.setValue(getPreferenceKey(TAG_USER_DEFINED_PATTERNS_ENABLED), fUserDefinedPatternsEnabled); - store.setValue(getPreferenceKey(TAG_USER_DEFINED_PATTERNS), CustomFiltersDialog.convertToString(fUserDefinedPatterns ,SEPARATOR)); + store + .setValue( + getPreferenceKey("TAG_DUMMY_TO_TEST_EXISTENCE"), "storedViewPreferences");//$NON-NLS-1$//$NON-NLS-2$ - Iterator iter= fEnabledFilterIds.entrySet().iterator(); + store.setValue(getPreferenceKey(TAG_USER_DEFINED_PATTERNS_ENABLED), + fUserDefinedPatternsEnabled); + store.setValue(getPreferenceKey(TAG_USER_DEFINED_PATTERNS), + CustomFiltersDialog.convertToString(fUserDefinedPatterns, + SEPARATOR)); + + Iterator iter = fEnabledFilterIds.entrySet().iterator(); while (iter.hasNext()) { - Map.Entry entry= (Map.Entry)iter.next(); - String id= (String)entry.getKey(); - boolean isEnabled= ((Boolean)entry.getValue()).booleanValue(); + Map.Entry entry = (Map.Entry) iter.next(); + String id = (String) entry.getKey(); + boolean isEnabled = ((Boolean) entry.getValue()).booleanValue(); store.setValue(id, isEnabled); } - StringBuffer buf= new StringBuffer(fLRUFilterIdsStack.size() * 20); - iter= fLRUFilterIdsStack.iterator(); + StringBuffer buf = new StringBuffer(fLRUFilterIdsStack.size() * 20); + iter = fLRUFilterIdsStack.iterator(); while (iter.hasNext()) { - buf.append((String)iter.next()); + buf.append((String) iter.next()); buf.append(SEPARATOR); } store.setValue(TAG_LRU_FILTERS, buf.toString()); } - + private String getPreferenceKey(String tag) { return "CustomFiltersActionGroup." + fTargetId + '.' + tag; //$NON-NLS-1$ } @@ -571,54 +634,59 @@ public class CustomFiltersActionGroup extends ActionGroup { /** * Saves the state of the custom filters in a memento. * - * @param memento the memento into which the state is saved + * @param memento + * the memento into which the state is saved */ public void saveState(IMemento memento) { - IMemento customFilters= memento.createChild(TAG_CUSTOM_FILTERS); - customFilters.putString(TAG_USER_DEFINED_PATTERNS_ENABLED, new Boolean(fUserDefinedPatternsEnabled).toString()); + IMemento customFilters = memento.createChild(TAG_CUSTOM_FILTERS); + customFilters.putString(TAG_USER_DEFINED_PATTERNS_ENABLED, new Boolean( + fUserDefinedPatternsEnabled).toString()); saveUserDefinedPatterns(customFilters); saveXmlDefinedFilters(customFilters); saveLRUFilters(customFilters); } private void saveXmlDefinedFilters(IMemento memento) { - if(fEnabledFilterIds != null && !fEnabledFilterIds.isEmpty()) { - IMemento xmlDefinedFilters= memento.createChild(TAG_XML_DEFINED_FILTERS); - Iterator iter= fEnabledFilterIds.entrySet().iterator(); + if (fEnabledFilterIds != null && !fEnabledFilterIds.isEmpty()) { + IMemento xmlDefinedFilters = memento + .createChild(TAG_XML_DEFINED_FILTERS); + Iterator iter = fEnabledFilterIds.entrySet().iterator(); while (iter.hasNext()) { - Map.Entry entry= (Map.Entry)iter.next(); - String id= (String)entry.getKey(); - Boolean isEnabled= (Boolean)entry.getValue(); - IMemento child= xmlDefinedFilters.createChild(TAG_CHILD); + Map.Entry entry = (Map.Entry) iter.next(); + String id = (String) entry.getKey(); + Boolean isEnabled = (Boolean) entry.getValue(); + IMemento child = xmlDefinedFilters.createChild(TAG_CHILD); child.putString(TAG_FILTER_ID, id); child.putString(TAG_IS_ENABLED, isEnabled.toString()); } } } + /** - * Stores the last recently used filter Ids into - * the given memento + * Stores the last recently used filter Ids into the given memento * - * @param memento the memento into which to store the LRU filter Ids + * @param memento + * the memento into which to store the LRU filter Ids * @since 3.0 */ private void saveLRUFilters(IMemento memento) { - if(fLRUFilterIdsStack != null && !fLRUFilterIdsStack.isEmpty()) { - IMemento lruFilters= memento.createChild(TAG_LRU_FILTERS); - Iterator iter= fLRUFilterIdsStack.iterator(); + if (fLRUFilterIdsStack != null && !fLRUFilterIdsStack.isEmpty()) { + IMemento lruFilters = memento.createChild(TAG_LRU_FILTERS); + Iterator iter = fLRUFilterIdsStack.iterator(); while (iter.hasNext()) { - String id= (String)iter.next(); - IMemento child= lruFilters.createChild(TAG_CHILD); + String id = (String) iter.next(); + IMemento child = lruFilters.createChild(TAG_CHILD); child.putString(TAG_FILTER_ID, id); } } } private void saveUserDefinedPatterns(IMemento memento) { - if(fUserDefinedPatterns != null && fUserDefinedPatterns.length > 0) { - IMemento userDefinedPatterns= memento.createChild(TAG_USER_DEFINED_PATTERNS); - for (int i= 0; i < fUserDefinedPatterns.length; i++) { - IMemento child= userDefinedPatterns.createChild(TAG_CHILD); + if (fUserDefinedPatterns != null && fUserDefinedPatterns.length > 0) { + IMemento userDefinedPatterns = memento + .createChild(TAG_USER_DEFINED_PATTERNS); + for (int i = 0; i < fUserDefinedPatterns.length; i++) { + IMemento child = userDefinedPatterns.createChild(TAG_CHILD); child.putString(TAG_PATTERN, fUserDefinedPatterns[i]); } } @@ -630,33 +698,37 @@ public class CustomFiltersActionGroup extends ActionGroup { * Note: This method does not refresh the viewer. *

                                                      * - * @param memento the memento from which the state is restored - */ + * @param memento + * the memento from which the state is restored + */ public void restoreState(IMemento memento) { if (memento == null) return; - IMemento customFilters= memento.getChild(TAG_CUSTOM_FILTERS); + IMemento customFilters = memento.getChild(TAG_CUSTOM_FILTERS); if (customFilters == null) return; - String userDefinedPatternsEnabled= customFilters.getString(TAG_USER_DEFINED_PATTERNS_ENABLED); + String userDefinedPatternsEnabled = customFilters + .getString(TAG_USER_DEFINED_PATTERNS_ENABLED); if (userDefinedPatternsEnabled == null) return; - fUserDefinedPatternsEnabled= Boolean.valueOf(userDefinedPatternsEnabled).booleanValue(); + fUserDefinedPatternsEnabled = Boolean.valueOf( + userDefinedPatternsEnabled).booleanValue(); restoreUserDefinedPatterns(customFilters); restoreXmlDefinedFilters(customFilters); restoreLRUFilters(customFilters); - + updateViewerFilters(false); } private void restoreUserDefinedPatterns(IMemento memento) { - IMemento userDefinedPatterns= memento.getChild(TAG_USER_DEFINED_PATTERNS); - if(userDefinedPatterns != null) { - IMemento children[]= userDefinedPatterns.getChildren(TAG_CHILD); - String[] patterns= new String[children.length]; + IMemento userDefinedPatterns = memento + .getChild(TAG_USER_DEFINED_PATTERNS); + if (userDefinedPatterns != null) { + IMemento children[] = userDefinedPatterns.getChildren(TAG_CHILD); + String[] patterns = new String[children.length]; for (int i = 0; i < children.length; i++) - patterns[i]= children[i].getString(TAG_PATTERN); + patterns[i] = children[i].getString(TAG_PATTERN); setUserDefinedPatterns(patterns); } else @@ -664,25 +736,27 @@ public class CustomFiltersActionGroup extends ActionGroup { } private void restoreXmlDefinedFilters(IMemento memento) { - IMemento xmlDefinedFilters= memento.getChild(TAG_XML_DEFINED_FILTERS); - if(xmlDefinedFilters != null) { - IMemento[] children= xmlDefinedFilters.getChildren(TAG_CHILD); - for (int i= 0; i < children.length; i++) { - String id= children[i].getString(TAG_FILTER_ID); - Boolean isEnabled= new Boolean(children[i].getString(TAG_IS_ENABLED)); + IMemento xmlDefinedFilters = memento.getChild(TAG_XML_DEFINED_FILTERS); + if (xmlDefinedFilters != null) { + IMemento[] children = xmlDefinedFilters.getChildren(TAG_CHILD); + for (int i = 0; i < children.length; i++) { + String id = children[i].getString(TAG_FILTER_ID); + Boolean isEnabled = new Boolean(children[i] + .getString(TAG_IS_ENABLED)); fEnabledFilterIds.put(id, isEnabled); } } } private void restoreLRUFilters(IMemento memento) { - IMemento lruFilters= memento.getChild(TAG_LRU_FILTERS); + IMemento lruFilters = memento.getChild(TAG_LRU_FILTERS); fLRUFilterIdsStack.clear(); - if(lruFilters != null) { - IMemento[] children= lruFilters.getChildren(TAG_CHILD); - for (int i= 0; i < children.length; i++) { - String id= children[i].getString(TAG_FILTER_ID); - if (fFilterDescriptorMap.containsKey(id) && !fLRUFilterIdsStack.contains(id)) + if (lruFilters != null) { + IMemento[] children = lruFilters.getChildren(TAG_CHILD); + for (int i = 0; i < children.length; i++) { + String id = children[i].getString(TAG_FILTER_ID); + if (fFilterDescriptorMap.containsKey(id) + && !fLRUFilterIdsStack.contains(id)) fLRUFilterIdsStack.push(id); } } @@ -691,37 +765,40 @@ public class CustomFiltersActionGroup extends ActionGroup { private void cleanUpPatternDuplicates() { if (!areUserDefinedPatternsEnabled()) return; - List userDefinedPatterns= new ArrayList(Arrays.asList(fUserDefinedPatterns)); - FilterDescriptor[] filters= FilterDescriptor.getFilterDescriptors(fTargetId); + List userDefinedPatterns = new ArrayList(Arrays + .asList(fUserDefinedPatterns)); + FilterDescriptor[] filters = FilterDescriptor + .getFilterDescriptors(fTargetId); - for (int i= 0; i < filters.length; i++) { + for (int i = 0; i < filters.length; i++) { if (filters[i].isPatternFilter()) { - String pattern= filters[i].getPattern(); + String pattern = filters[i].getPattern(); if (userDefinedPatterns.contains(pattern)) { fEnabledFilterIds.put(filters[i].getId(), Boolean.TRUE); - boolean hasMore= true; + boolean hasMore = true; while (hasMore) - hasMore= userDefinedPatterns.remove(pattern); + hasMore = userDefinedPatterns.remove(pattern); } } } - fUserDefinedPatterns= (String[])userDefinedPatterns.toArray(new String[userDefinedPatterns.size()]); - setUserDefinedPatternsEnabled(fUserDefinedPatternsEnabled && fUserDefinedPatterns.length > 0); + fUserDefinedPatterns = (String[]) userDefinedPatterns + .toArray(new String[userDefinedPatterns.size()]); + setUserDefinedPatternsEnabled(fUserDefinedPatternsEnabled + && fUserDefinedPatterns.length > 0); } - + // ---------- dialog related code ---------- private void openDialog() { - CustomFiltersDialog dialog= new CustomFiltersDialog( - fViewer.getControl().getShell(), - fTargetId, - areUserDefinedPatternsEnabled(), - fUserDefinedPatterns, - getEnabledFilterIds()); - + CustomFiltersDialog dialog = new CustomFiltersDialog(fViewer + .getControl().getShell(), fTargetId, + areUserDefinedPatternsEnabled(), fUserDefinedPatterns, + getEnabledFilterIds()); + if (dialog.open() == Window.OK) { setEnabledFilterIds(dialog.getEnabledFilterIds()); - setUserDefinedPatternsEnabled(dialog.areUserDefinedPatternsEnabled()); + setUserDefinedPatternsEnabled(dialog + .areUserDefinedPatternsEnabled()); setUserDefinedPatterns(dialog.getUserDefinedPatterns()); setRecentlyChangedFilters(dialog.getFilterDescriptorChangeHistory()); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/GenerateActionGroup.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/GenerateActionGroup.java index e5f593a..f627deb 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/GenerateActionGroup.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/GenerateActionGroup.java @@ -39,169 +39,184 @@ import org.eclipse.ui.texteditor.IUpdate; /** * Action group that adds the source and generate actions to a part's context * menu and installs handlers for the corresponding global menu actions. - * + * *

                                                      * This class may be instantiated; it is not intended to be subclassed. *

                                                      - * + * * @since 2.0 */ public class GenerateActionGroup extends ActionGroup { - /** - * Pop-up menu: id of the source sub menu (value net.sourceforge.phpdt.ui.source.menu). - * + /** + * Pop-up menu: id of the source sub menu (value + * net.sourceforge.phpdt.ui.source.menu). + * * @since 3.0 */ - public static final String MENU_ID= "net.sourceforge.pheclipse.ui.source.menu"; //$NON-NLS-1$ + public static final String MENU_ID = "net.sourceforge.pheclipse.ui.source.menu"; //$NON-NLS-1$ + + private PHPEditor fEditor; - private PHPEditor fEditor; -// private boolean fEditorIsOwner; + // private boolean fEditorIsOwner; private IWorkbenchSite fSite; - private String fGroupName= IContextMenuConstants.GROUP_SOURCE; + + private String fGroupName = IContextMenuConstants.GROUP_SOURCE; + private List fRegisteredSelectionListeners; -// private AddImportOnSelectionAction fAddImport; -// private OverrideMethodsAction fOverrideMethods; -// private AddGetterSetterAction fAddGetterSetter; -// private AddUnimplementedConstructorsAction fAddUnimplementedConstructors; -// private AddJavaDocStubAction fAddJavaDocStub; + // private AddImportOnSelectionAction fAddImport; + // private OverrideMethodsAction fOverrideMethods; + // private AddGetterSetterAction fAddGetterSetter; + // private AddUnimplementedConstructorsAction fAddUnimplementedConstructors; + // private AddJavaDocStubAction fAddJavaDocStub; private AddBookmarkAction fAddBookmark; + private AddTaskAction fAddTaskAction; -// private ExternalizeStringsAction fExternalizeStrings; -// private FindStringsToExternalizeAction fFindStringsToExternalize; -// private SurroundWithTryCatchAction fSurroundWithTryCatch; + + // private ExternalizeStringsAction fExternalizeStrings; + // private FindStringsToExternalizeAction fFindStringsToExternalize; + // private SurroundWithTryCatchAction fSurroundWithTryCatch; // private OrganizeImportsAction fOrganizeImports; /** - * Note: This constructor is for internal use only. Clients should not call this constructor. + * Note: This constructor is for internal use only. Clients should not call + * this constructor. */ public GenerateActionGroup(PHPEditor editor, String groupName) { - fSite= editor.getSite(); - fEditor= editor; - fGroupName= groupName; - - ISelectionProvider provider= fSite.getSelectionProvider(); - ISelection selection= provider.getSelection(); - -// fAddImport= new AddImportOnSelectionAction(editor); -// fAddImport.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_IMPORT); -// fAddImport.update(); -// editor.setAction("AddImport", fAddImport); //$NON-NLS-1$ - -// fOrganizeImports= new OrganizeImportsAction(editor); -// fOrganizeImports.setActionDefinitionId(IJavaEditorActionDefinitionIds.ORGANIZE_IMPORTS); -// fOrganizeImports.editorStateChanged(); -// editor.setAction("OrganizeImports", fOrganizeImports); //$NON-NLS-1$ - -// fOverrideMethods= new OverrideMethodsAction(editor); -// fOverrideMethods.setActionDefinitionId(IJavaEditorActionDefinitionIds.OVERRIDE_METHODS); -// fOverrideMethods.editorStateChanged(); -// editor.setAction("OverrideMethods", fOverrideMethods); //$NON-NLS-1$ - -// fAddGetterSetter= new AddGetterSetterAction(editor); -// fAddGetterSetter.setActionDefinitionId(IJavaEditorActionDefinitionIds.CREATE_GETTER_SETTER); -// fAddGetterSetter.editorStateChanged(); -// editor.setAction("AddGetterSetter", fAddGetterSetter); //$NON-NLS-1$ - -// fAddUnimplementedConstructors= new AddUnimplementedConstructorsAction(editor); -// fAddUnimplementedConstructors.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_UNIMPLEMENTED_CONTRUCTORS); -// fAddUnimplementedConstructors.editorStateChanged(); -// editor.setAction("AddUnimplementedConstructors", fAddUnimplementedConstructors); //$NON-NLS-1$ - -// fAddJavaDocStub= new AddJavaDocStubAction(editor); -// fAddJavaDocStub.editorStateChanged(); -// -// fSurroundWithTryCatch= new SurroundWithTryCatchAction(editor); -// fSurroundWithTryCatch.setActionDefinitionId(IJavaEditorActionDefinitionIds.SURROUND_WITH_TRY_CATCH); -// fSurroundWithTryCatch.update(selection); -// provider.addSelectionChangedListener(fSurroundWithTryCatch); -// editor.setAction("SurroundWithTryCatch", fSurroundWithTryCatch); //$NON-NLS-1$ -// -// fExternalizeStrings= new ExternalizeStringsAction(editor); -// fExternalizeStrings.setActionDefinitionId(IJavaEditorActionDefinitionIds.EXTERNALIZE_STRINGS); -// fExternalizeStrings.editorStateChanged(); -// editor.setAction("ExternalizeStrings", fExternalizeStrings); //$NON-NLS-1$ + fSite = editor.getSite(); + fEditor = editor; + fGroupName = groupName; + + ISelectionProvider provider = fSite.getSelectionProvider(); + ISelection selection = provider.getSelection(); + + // fAddImport= new AddImportOnSelectionAction(editor); + // fAddImport.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_IMPORT); + // fAddImport.update(); + // editor.setAction("AddImport", fAddImport); //$NON-NLS-1$ + + // fOrganizeImports= new OrganizeImportsAction(editor); + // fOrganizeImports.setActionDefinitionId(IJavaEditorActionDefinitionIds.ORGANIZE_IMPORTS); + // fOrganizeImports.editorStateChanged(); + // editor.setAction("OrganizeImports", fOrganizeImports); //$NON-NLS-1$ + + // fOverrideMethods= new OverrideMethodsAction(editor); + // fOverrideMethods.setActionDefinitionId(IJavaEditorActionDefinitionIds.OVERRIDE_METHODS); + // fOverrideMethods.editorStateChanged(); + // editor.setAction("OverrideMethods", fOverrideMethods); //$NON-NLS-1$ + + // fAddGetterSetter= new AddGetterSetterAction(editor); + // fAddGetterSetter.setActionDefinitionId(IJavaEditorActionDefinitionIds.CREATE_GETTER_SETTER); + // fAddGetterSetter.editorStateChanged(); + // editor.setAction("AddGetterSetter", fAddGetterSetter); //$NON-NLS-1$ + + // fAddUnimplementedConstructors= new + // AddUnimplementedConstructorsAction(editor); + // fAddUnimplementedConstructors.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_UNIMPLEMENTED_CONTRUCTORS); + // fAddUnimplementedConstructors.editorStateChanged(); + // editor.setAction("AddUnimplementedConstructors", + // fAddUnimplementedConstructors); //$NON-NLS-1$ + + // fAddJavaDocStub= new AddJavaDocStubAction(editor); + // fAddJavaDocStub.editorStateChanged(); + // + // fSurroundWithTryCatch= new SurroundWithTryCatchAction(editor); + // fSurroundWithTryCatch.setActionDefinitionId(IJavaEditorActionDefinitionIds.SURROUND_WITH_TRY_CATCH); + // fSurroundWithTryCatch.update(selection); + // provider.addSelectionChangedListener(fSurroundWithTryCatch); + // editor.setAction("SurroundWithTryCatch", fSurroundWithTryCatch); + // //$NON-NLS-1$ + // + // fExternalizeStrings= new ExternalizeStringsAction(editor); + // fExternalizeStrings.setActionDefinitionId(IJavaEditorActionDefinitionIds.EXTERNALIZE_STRINGS); + // fExternalizeStrings.editorStateChanged(); + // editor.setAction("ExternalizeStrings", fExternalizeStrings); + // //$NON-NLS-1$ } /** - * Creates a new GenerateActionGroup. The group - * requires that the selection provided by the page's selection provider - * is of type org.eclipse.jface.viewers.IStructuredSelection. - * - * @param page the page that owns this action group + * Creates a new GenerateActionGroup. The group requires + * that the selection provided by the page's selection provider is of type + * org.eclipse.jface.viewers.IStructuredSelection. + * + * @param page + * the page that owns this action group */ public GenerateActionGroup(Page page) { this(page.getSite()); } /** - * Creates a new GenerateActionGroup. The group - * requires that the selection provided by the part's selection provider - * is of type org.eclipse.jface.viewers.IStructuredSelection. - * - * @param part the view part that owns this action group + * Creates a new GenerateActionGroup. The group requires + * that the selection provided by the part's selection provider is of type + * org.eclipse.jface.viewers.IStructuredSelection. + * + * @param part + * the view part that owns this action group */ public GenerateActionGroup(IViewPart part) { this(part.getSite()); } private GenerateActionGroup(IWorkbenchSite site) { - fSite= site; - ISelectionProvider provider= fSite.getSelectionProvider(); - ISelection selection= provider.getSelection(); - -// fOverrideMethods= new OverrideMethodsAction(site); -// fAddGetterSetter= new AddGetterSetterAction(site); -// fAddUnimplementedConstructors= new AddUnimplementedConstructorsAction(site); -// fAddJavaDocStub= new AddJavaDocStubAction(site); - fAddBookmark= new AddBookmarkAction(site.getShell()); - fAddTaskAction= new AddTaskAction(site); -// fExternalizeStrings= new ExternalizeStringsAction(site); -// fFindStringsToExternalize= new FindStringsToExternalizeAction(site); -// fOrganizeImports= new OrganizeImportsAction(site); -// -// fOverrideMethods.update(selection); -// fAddGetterSetter.update(selection); -// fAddUnimplementedConstructors.update(selection); -// fAddJavaDocStub.update(selection); -// fExternalizeStrings.update(selection); -// fFindStringsToExternalize.update(selection); + fSite = site; + ISelectionProvider provider = fSite.getSelectionProvider(); + ISelection selection = provider.getSelection(); + + // fOverrideMethods= new OverrideMethodsAction(site); + // fAddGetterSetter= new AddGetterSetterAction(site); + // fAddUnimplementedConstructors= new + // AddUnimplementedConstructorsAction(site); + // fAddJavaDocStub= new AddJavaDocStubAction(site); + fAddBookmark = new AddBookmarkAction(site.getShell()); + fAddTaskAction = new AddTaskAction(site); + // fExternalizeStrings= new ExternalizeStringsAction(site); + // fFindStringsToExternalize= new FindStringsToExternalizeAction(site); + // fOrganizeImports= new OrganizeImportsAction(site); + // + // fOverrideMethods.update(selection); + // fAddGetterSetter.update(selection); + // fAddUnimplementedConstructors.update(selection); + // fAddJavaDocStub.update(selection); + // fExternalizeStrings.update(selection); + // fFindStringsToExternalize.update(selection); fAddTaskAction.update(selection); -// fOrganizeImports.update(selection); + // fOrganizeImports.update(selection); if (selection instanceof IStructuredSelection) { - IStructuredSelection ss= (IStructuredSelection)selection; + IStructuredSelection ss = (IStructuredSelection) selection; fAddBookmark.selectionChanged(ss); } else { fAddBookmark.setEnabled(false); } -// registerSelectionListener(provider, fOverrideMethods); -// registerSelectionListener(provider, fAddGetterSetter); -// registerSelectionListener(provider, fAddUnimplementedConstructors); -// registerSelectionListener(provider, fAddJavaDocStub); + // registerSelectionListener(provider, fOverrideMethods); + // registerSelectionListener(provider, fAddGetterSetter); + // registerSelectionListener(provider, fAddUnimplementedConstructors); + // registerSelectionListener(provider, fAddJavaDocStub); registerSelectionListener(provider, fAddBookmark); -// registerSelectionListener(provider, fExternalizeStrings); -// registerSelectionListener(provider, fFindStringsToExternalize); -// registerSelectionListener(provider, fOrganizeImports); + // registerSelectionListener(provider, fExternalizeStrings); + // registerSelectionListener(provider, fFindStringsToExternalize); + // registerSelectionListener(provider, fOrganizeImports); registerSelectionListener(provider, fAddTaskAction); } - private void registerSelectionListener(ISelectionProvider provider, ISelectionChangedListener listener) { + private void registerSelectionListener(ISelectionProvider provider, + ISelectionChangedListener listener) { if (fRegisteredSelectionListeners == null) - fRegisteredSelectionListeners= new ArrayList(12); + fRegisteredSelectionListeners = new ArrayList(12); provider.addSelectionChangedListener(listener); fRegisteredSelectionListeners.add(listener); } /* - * The state of the editor owning this action group has changed. - * This method does nothing if the group's owner isn't an - * editor. + * The state of the editor owning this action group has changed. This method + * does nothing if the group's owner isn't an editor. */ /** - * Note: This method is for internal use only. Clients should not call this method. + * Note: This method is for internal use only. Clients should not call this + * method. */ public void editorStateChanged() { Assert.isTrue(isEditorOwner()); @@ -209,120 +224,137 @@ public class GenerateActionGroup extends ActionGroup { // http://dev.eclipse.org/bugs/show_bug.cgi?id=17709 } - /* (non-Javadoc) - * Method declared in ActionGroup + /* + * (non-Javadoc) Method declared in ActionGroup */ public void fillActionBars(IActionBars actionBar) { super.fillActionBars(actionBar); setGlobalActionHandlers(actionBar); } - /* (non-Javadoc) - * Method declared in ActionGroup + /* + * (non-Javadoc) Method declared in ActionGroup */ -// public void fillContextMenu(IMenuManager menu) { -// super.fillContextMenu(menu); -// if (fEditorIsOwner) { -// IMenuManager subMenu= createEditorSubMenu(menu); -// if (subMenu != null) -// menu.appendToGroup(fGroupName, subMenu); -// } else { -//// appendToGroup(menu, fOrganizeImports); -//// appendToGroup(menu, fOverrideMethods); -//// appendToGroup(menu, fAddGetterSetter); -//// appendToGroup(menu, fAddUnimplementedConstructors); -//// appendToGroup(menu, fAddJavaDocStub); -// appendToGroup(menu, fAddBookmark); -// } -// } - /* (non-Javadoc) - * Method declared in ActionGroup + // public void fillContextMenu(IMenuManager menu) { + // super.fillContextMenu(menu); + // if (fEditorIsOwner) { + // IMenuManager subMenu= createEditorSubMenu(menu); + // if (subMenu != null) + // menu.appendToGroup(fGroupName, subMenu); + // } else { + // // appendToGroup(menu, fOrganizeImports); + // // appendToGroup(menu, fOverrideMethods); + // // appendToGroup(menu, fAddGetterSetter); + // // appendToGroup(menu, fAddUnimplementedConstructors); + // // appendToGroup(menu, fAddJavaDocStub); + // appendToGroup(menu, fAddBookmark); + // } + // } + /* + * (non-Javadoc) Method declared in ActionGroup */ -// public void fillContextMenu(IMenuManager menu) { -// super.fillContextMenu(menu); -// IMenuManager subMenu= null; -// if (isEditorOwner()) { -// subMenu= fillEditorSubMenu(menu); -// } else { -// // subMenu= createViewSubMenu(menu); -// } -// if (subMenu != null) -// menu.appendToGroup(fGroupName, subMenu); -// } + // public void fillContextMenu(IMenuManager menu) { + // super.fillContextMenu(menu); + // IMenuManager subMenu= null; + // if (isEditorOwner()) { + // subMenu= fillEditorSubMenu(menu); + // } else { + // // subMenu= createViewSubMenu(menu); + // } + // if (subMenu != null) + // menu.appendToGroup(fGroupName, subMenu); + // } public void fillContextMenu(IMenuManager menu) { super.fillContextMenu(menu); - String shortCut= null; //$NON-NLS-1$ -// if (fQuickAccessAction != null) { -// shortCut= fQuickAccessAction.getShortCutString(); //$NON-NLS-1$ -// } - IMenuManager subMenu= new MenuManager( - ActionMessages.getString("SourceMenu.label") + (shortCut != null ? "\t" + shortCut : ""), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - MENU_ID); - int added= 0; + String shortCut = null; //$NON-NLS-1$ + // if (fQuickAccessAction != null) { + // shortCut= fQuickAccessAction.getShortCutString(); //$NON-NLS-1$ + // } + IMenuManager subMenu = new MenuManager( + ActionMessages.getString("SourceMenu.label") + (shortCut != null ? "\t" + shortCut : ""), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + MENU_ID); + int added = 0; if (isEditorOwner()) { - added= fillEditorSubMenu(subMenu); + added = fillEditorSubMenu(subMenu); } -// else { -// added= fillViewSubMenu(subMenu); -// } + // else { + // added= fillViewSubMenu(subMenu); + // } if (added > 0) menu.appendToGroup(fGroupName, subMenu); } - private int fillEditorSubMenu(IMenuManager source) { -// IMenuManager result= new MenuManager(ActionMessages.getString("SourceMenu.label")); //$NON-NLS-1$ - int added= 0; - added+= addEditorAction(source, "Comment"); //$NON-NLS-1$ - added+= addEditorAction(source, "Uncomment"); //$NON-NLS-1$ - added+= addEditorAction(source, "ToggleComment"); //$NON-NLS-1$ - added+= addEditorAction(source, "AddBlockComment"); //$NON-NLS-1$ - added+= addEditorAction(source, "RemoveBlockComment"); //$NON-NLS-1$ - added+= addEditorAction(source, "Format"); //$NON-NLS-1$ - added+= addEditorAction(source, "Indent"); //$NON-NLS-1$ -// result.add(new Separator()); -// added+= addAction(result, fOrganizeImports); -// added+= addAction(result, fAddImport); -// result.add(new Separator()); -// added+= addAction(result, fOverrideMethods); -// added+= addAction(result, fAddGetterSetter); -// added+= addAction(result, fAddUnimplementedConstructors); -// added+= addAction(result, fAddJavaDocStub); -// added+= addAction(result, fAddBookmark); -// result.add(new Separator()); -// added+= addAction(result, fSurroundWithTryCatch); -// added+= addAction(result, fExternalizeStrings); -// if (added == 0) -// result= null; - return added; - } - /* (non-Javadoc) - * Method declared in ActionGroup + + private int fillEditorSubMenu(IMenuManager source) { + // IMenuManager result= new + // MenuManager(ActionMessages.getString("SourceMenu.label")); + // //$NON-NLS-1$ + int added = 0; + added += addEditorAction(source, "Comment"); //$NON-NLS-1$ + added += addEditorAction(source, "Uncomment"); //$NON-NLS-1$ + added += addEditorAction(source, "ToggleComment"); //$NON-NLS-1$ + added += addEditorAction(source, "AddBlockComment"); //$NON-NLS-1$ + added += addEditorAction(source, "RemoveBlockComment"); //$NON-NLS-1$ + added += addEditorAction(source, "Format"); //$NON-NLS-1$ + added += addEditorAction(source, "Indent"); //$NON-NLS-1$ + // result.add(new Separator()); + // added+= addAction(result, fOrganizeImports); + // added+= addAction(result, fAddImport); + // result.add(new Separator()); + // added+= addAction(result, fOverrideMethods); + // added+= addAction(result, fAddGetterSetter); + // added+= addAction(result, fAddUnimplementedConstructors); + // added+= addAction(result, fAddJavaDocStub); + // added+= addAction(result, fAddBookmark); + // result.add(new Separator()); + // added+= addAction(result, fSurroundWithTryCatch); + // added+= addAction(result, fExternalizeStrings); + // if (added == 0) + // result= null; + return added; + } + + /* + * (non-Javadoc) Method declared in ActionGroup */ public void dispose() { if (fRegisteredSelectionListeners != null) { - ISelectionProvider provider= fSite.getSelectionProvider(); - for (Iterator iter= fRegisteredSelectionListeners.iterator(); iter.hasNext();) { - ISelectionChangedListener listener= (ISelectionChangedListener) iter.next(); + ISelectionProvider provider = fSite.getSelectionProvider(); + for (Iterator iter = fRegisteredSelectionListeners.iterator(); iter + .hasNext();) { + ISelectionChangedListener listener = (ISelectionChangedListener) iter + .next(); provider.removeSelectionChangedListener(listener); } } - fEditor= null; + fEditor = null; super.dispose(); } private void setGlobalActionHandlers(IActionBars actionBar) { -// actionBar.setGlobalActionHandler(JdtActionConstants.ADD_IMPORT, fAddImport); -// actionBar.setGlobalActionHandler(JdtActionConstants.SURROUND_WITH_TRY_CATCH, fSurroundWithTryCatch); -// actionBar.setGlobalActionHandler(JdtActionConstants.OVERRIDE_METHODS, fOverrideMethods); -// actionBar.setGlobalActionHandler(JdtActionConstants.GENERATE_GETTER_SETTER, fAddGetterSetter); -// actionBar.setGlobalActionHandler(JdtActionConstants.ADD_CONSTRUCTOR_FROM_SUPERCLASS, fAddUnimplementedConstructors); -// actionBar.setGlobalActionHandler(JdtActionConstants.ADD_JAVA_DOC_COMMENT, fAddJavaDocStub); -// actionBar.setGlobalActionHandler(JdtActionConstants.EXTERNALIZE_STRINGS, fExternalizeStrings); -// actionBar.setGlobalActionHandler(JdtActionConstants.FIND_STRINGS_TO_EXTERNALIZE, fFindStringsToExternalize); -// actionBar.setGlobalActionHandler(JdtActionConstants.ORGANIZE_IMPORTS, fOrganizeImports); + // actionBar.setGlobalActionHandler(JdtActionConstants.ADD_IMPORT, + // fAddImport); + // actionBar.setGlobalActionHandler(JdtActionConstants.SURROUND_WITH_TRY_CATCH, + // fSurroundWithTryCatch); + // actionBar.setGlobalActionHandler(JdtActionConstants.OVERRIDE_METHODS, + // fOverrideMethods); + // actionBar.setGlobalActionHandler(JdtActionConstants.GENERATE_GETTER_SETTER, + // fAddGetterSetter); + // actionBar.setGlobalActionHandler(JdtActionConstants.ADD_CONSTRUCTOR_FROM_SUPERCLASS, + // fAddUnimplementedConstructors); + // actionBar.setGlobalActionHandler(JdtActionConstants.ADD_JAVA_DOC_COMMENT, + // fAddJavaDocStub); + // actionBar.setGlobalActionHandler(JdtActionConstants.EXTERNALIZE_STRINGS, + // fExternalizeStrings); + // actionBar.setGlobalActionHandler(JdtActionConstants.FIND_STRINGS_TO_EXTERNALIZE, + // fFindStringsToExternalize); + // actionBar.setGlobalActionHandler(JdtActionConstants.ORGANIZE_IMPORTS, + // fOrganizeImports); if (!isEditorOwner()) { // editor provides its own implementation of these actions. - actionBar.setGlobalActionHandler(IDEActionFactory.BOOKMARK.getId(), fAddBookmark); - actionBar.setGlobalActionHandler(IDEActionFactory.ADD_TASK.getId(), fAddTaskAction); + actionBar.setGlobalActionHandler(IDEActionFactory.BOOKMARK.getId(), + fAddBookmark); + actionBar.setGlobalActionHandler(IDEActionFactory.ADD_TASK.getId(), + fAddTaskAction); } } @@ -342,22 +374,22 @@ public class GenerateActionGroup extends ActionGroup { return 0; } - private int addEditorAction(IMenuManager menu, String actionID) { - if (fEditor == null) - return 0; - IAction action= fEditor.getAction(actionID); - if (action == null) - return 0; - if (action instanceof IUpdate) - ((IUpdate)action).update(); - if (action.isEnabled()) { - menu.add(action); - return 1; - } - return 0; - } - - private boolean isEditorOwner() { - return fEditor != null; - } + private int addEditorAction(IMenuManager menu, String actionID) { + if (fEditor == null) + return 0; + IAction action = fEditor.getAction(actionID); + if (action == null) + return 0; + if (action instanceof IUpdate) + ((IUpdate) action).update(); + if (action.isEnabled()) { + menu.add(action); + return 1; + } + return 0; + } + + private boolean isEditorOwner() { + return fEditor != null; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/GotoMatchingBracketAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/GotoMatchingBracketAction.java index 4bd636d..ae586c0 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/GotoMatchingBracketAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/GotoMatchingBracketAction.java @@ -11,22 +11,21 @@ import net.sourceforge.phpeclipse.phpeditor.PHPEditorMessages; import org.eclipse.jface.action.Action; - public class GotoMatchingBracketAction extends Action { - public final static String GOTO_MATCHING_BRACKET= "GotoMatchingBracket"; //$NON-NLS-1$ - + public final static String GOTO_MATCHING_BRACKET = "GotoMatchingBracket"; //$NON-NLS-1$ + private final PHPEditor fEditor; - + public GotoMatchingBracketAction(PHPEditor editor) { super(PHPEditorMessages.getString("GotoMatchingBracket.label")); Assert.isNotNull(editor); - fEditor= editor; + fEditor = editor; setEnabled(null != fEditor); } - + public void run() { fEditor.gotoMatchingBracket(); } - + } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/MemberFilterActionGroup.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/MemberFilterActionGroup.java index 48815ed..873c76e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/MemberFilterActionGroup.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/MemberFilterActionGroup.java @@ -28,14 +28,14 @@ import org.eclipse.ui.IMemento; import org.eclipse.ui.actions.ActionGroup; /** - * Action Group that contributes filter buttons for a view parts showing - * methods and fields. Contributed filters are: hide fields, hide static - * members and hide non-public members. + * Action Group that contributes filter buttons for a view parts showing methods + * and fields. Contributed filters are: hide fields, hide static members and + * hide non-public members. *

                                                      - * The action group installs a filter on a structured viewer. The filter is connected - * to the actions installed in the view part's toolbar menu and is updated when the - * state of the buttons changes. - * + * The action group installs a filter on a structured viewer. The filter is + * connected to the actions installed in the view part's toolbar menu and is + * updated when the state of the buttons changes. + * *

                                                      * This class may be instantiated; it is not intended to be subclassed. *

                                                      @@ -44,141 +44,178 @@ import org.eclipse.ui.actions.ActionGroup; */ public class MemberFilterActionGroup extends ActionGroup { - public static final int FILTER_NONPUBLIC= MemberFilter.FILTER_NONPUBLIC; - public static final int FILTER_STATIC= MemberFilter.FILTER_STATIC; - public static final int FILTER_FIELDS= MemberFilter.FILTER_FIELDS; - - private static final String TAG_HIDEFIELDS= "hidefields"; //$NON-NLS-1$ - private static final String TAG_HIDESTATIC= "hidestatic"; //$NON-NLS-1$ - private static final String TAG_HIDENONPUBLIC= "hidenonpublic"; //$NON-NLS-1$ - + public static final int FILTER_NONPUBLIC = MemberFilter.FILTER_NONPUBLIC; + + public static final int FILTER_STATIC = MemberFilter.FILTER_STATIC; + + public static final int FILTER_FIELDS = MemberFilter.FILTER_FIELDS; + + private static final String TAG_HIDEFIELDS = "hidefields"; //$NON-NLS-1$ + + private static final String TAG_HIDESTATIC = "hidestatic"; //$NON-NLS-1$ + + private static final String TAG_HIDENONPUBLIC = "hidenonpublic"; //$NON-NLS-1$ + private MemberFilterAction[] fFilterActions; + private MemberFilter fFilter; - + private StructuredViewer fViewer; + private String fViewerId; + private boolean fInViewMenu; - - + /** * Creates a new MemberFilterActionGroup. * - * @param viewer the viewer to be filtered - * @param viewerId a unique id of the viewer. Used as a key to to store - * the last used filter settings in the preference store + * @param viewer + * the viewer to be filtered + * @param viewerId + * a unique id of the viewer. Used as a key to to store the last + * used filter settings in the preference store */ public MemberFilterActionGroup(StructuredViewer viewer, String viewerId) { this(viewer, viewerId, false); } - + /** * Creates a new MemberFilterActionGroup. * - * @param viewer the viewer to be filtered - * @param viewerId a unique id of the viewer. Used as a key to to store - * the last used filter settings in the preference store - * @param inViewMenu if true the actions are added to the view - * menu. If false they are added to the toobar. + * @param viewer + * the viewer to be filtered + * @param viewerId + * a unique id of the viewer. Used as a key to to store the last + * used filter settings in the preference store + * @param inViewMenu + * if true the actions are added to the view menu. + * If false they are added to the toobar. * * @since 2.1 */ - public MemberFilterActionGroup(StructuredViewer viewer, String viewerId, boolean inViewMenu) { - fViewer= viewer; - fViewerId= viewerId; - fInViewMenu= inViewMenu; - + public MemberFilterActionGroup(StructuredViewer viewer, String viewerId, + boolean inViewMenu) { + fViewer = viewer; + fViewerId = viewerId; + fInViewMenu = inViewMenu; + // get initial values - IPreferenceStore store= PHPeclipsePlugin.getDefault().getPreferenceStore(); - boolean doHideFields= store.getBoolean(getPreferenceKey(FILTER_FIELDS)); - boolean doHideStatic= store.getBoolean(getPreferenceKey(FILTER_STATIC)); - boolean doHidePublic= store.getBoolean(getPreferenceKey(FILTER_NONPUBLIC)); + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + boolean doHideFields = store + .getBoolean(getPreferenceKey(FILTER_FIELDS)); + boolean doHideStatic = store + .getBoolean(getPreferenceKey(FILTER_STATIC)); + boolean doHidePublic = store + .getBoolean(getPreferenceKey(FILTER_NONPUBLIC)); - fFilter= new MemberFilter(); + fFilter = new MemberFilter(); if (doHideFields) fFilter.addFilter(FILTER_FIELDS); if (doHideStatic) - fFilter.addFilter(FILTER_STATIC); + fFilter.addFilter(FILTER_STATIC); if (doHidePublic) - fFilter.addFilter(FILTER_NONPUBLIC); - + fFilter.addFilter(FILTER_NONPUBLIC); + // fields - String title= ActionMessages.getString("MemberFilterActionGroup.hide_fields.label"); //$NON-NLS-1$ - String helpContext= IJavaHelpContextIds.FILTER_FIELDS_ACTION; - MemberFilterAction hideFields= new MemberFilterAction(this, title, FILTER_FIELDS, helpContext, doHideFields); - hideFields.setDescription(ActionMessages.getString("MemberFilterActionGroup.hide_fields.description")); //$NON-NLS-1$ - hideFields.setToolTipText(ActionMessages.getString("MemberFilterActionGroup.hide_fields.tooltip")); //$NON-NLS-1$ + String title = ActionMessages + .getString("MemberFilterActionGroup.hide_fields.label"); //$NON-NLS-1$ + String helpContext = IJavaHelpContextIds.FILTER_FIELDS_ACTION; + MemberFilterAction hideFields = new MemberFilterAction(this, title, + FILTER_FIELDS, helpContext, doHideFields); + hideFields.setDescription(ActionMessages + .getString("MemberFilterActionGroup.hide_fields.description")); //$NON-NLS-1$ + hideFields.setToolTipText(ActionMessages + .getString("MemberFilterActionGroup.hide_fields.tooltip")); //$NON-NLS-1$ PHPUiImages.setLocalImageDescriptors(hideFields, "fields_co.gif"); //$NON-NLS-1$ - + // static - title= ActionMessages.getString("MemberFilterActionGroup.hide_static.label"); //$NON-NLS-1$ - helpContext= IJavaHelpContextIds.FILTER_STATIC_ACTION; - MemberFilterAction hideStatic= new MemberFilterAction(this, title, FILTER_STATIC, helpContext, doHideStatic); - hideStatic.setDescription(ActionMessages.getString("MemberFilterActionGroup.hide_static.description")); //$NON-NLS-1$ - hideStatic.setToolTipText(ActionMessages.getString("MemberFilterActionGroup.hide_static.tooltip")); //$NON-NLS-1$ + title = ActionMessages + .getString("MemberFilterActionGroup.hide_static.label"); //$NON-NLS-1$ + helpContext = IJavaHelpContextIds.FILTER_STATIC_ACTION; + MemberFilterAction hideStatic = new MemberFilterAction(this, title, + FILTER_STATIC, helpContext, doHideStatic); + hideStatic.setDescription(ActionMessages + .getString("MemberFilterActionGroup.hide_static.description")); //$NON-NLS-1$ + hideStatic.setToolTipText(ActionMessages + .getString("MemberFilterActionGroup.hide_static.tooltip")); //$NON-NLS-1$ PHPUiImages.setLocalImageDescriptors(hideStatic, "static_co.gif"); //$NON-NLS-1$ - + // non-public - title= ActionMessages.getString("MemberFilterActionGroup.hide_nonpublic.label"); //$NON-NLS-1$ - helpContext= IJavaHelpContextIds.FILTER_PUBLIC_ACTION; - MemberFilterAction hideNonPublic= new MemberFilterAction(this, title, FILTER_NONPUBLIC, helpContext, doHidePublic); - hideNonPublic.setDescription(ActionMessages.getString("MemberFilterActionGroup.hide_nonpublic.description")); //$NON-NLS-1$ - hideNonPublic.setToolTipText(ActionMessages.getString("MemberFilterActionGroup.hide_nonpublic.tooltip")); //$NON-NLS-1$ + title = ActionMessages + .getString("MemberFilterActionGroup.hide_nonpublic.label"); //$NON-NLS-1$ + helpContext = IJavaHelpContextIds.FILTER_PUBLIC_ACTION; + MemberFilterAction hideNonPublic = new MemberFilterAction(this, title, + FILTER_NONPUBLIC, helpContext, doHidePublic); + hideNonPublic + .setDescription(ActionMessages + .getString("MemberFilterActionGroup.hide_nonpublic.description")); //$NON-NLS-1$ + hideNonPublic.setToolTipText(ActionMessages + .getString("MemberFilterActionGroup.hide_nonpublic.tooltip")); //$NON-NLS-1$ PHPUiImages.setLocalImageDescriptors(hideNonPublic, "public_co.gif"); //$NON-NLS-1$ - + // order corresponds to order in toolbar - fFilterActions= new MemberFilterAction[] { hideFields, hideStatic, hideNonPublic }; - + fFilterActions = new MemberFilterAction[] { hideFields, hideStatic, + hideNonPublic }; + fViewer.addFilter(fFilter); } - + private String getPreferenceKey(int filterProperty) { return "MemberFilterActionGroup." + fViewerId + '.' + String.valueOf(filterProperty); //$NON-NLS-1$ } - + /** * Sets the member filters. * - * @param filterProperty the filter to be manipulated. Valid values are FILTER_FIELDS, - * FILTER_PUBLIC, and FILTER_PRIVATE as defined by this action - * group - * @param set if true the given filter is installed. If false the - * given filter is removed - * . - */ + * @param filterProperty + * the filter to be manipulated. Valid values are + * FILTER_FIELDS, FILTER_PUBLIC, + * and FILTER_PRIVATE as defined by this action + * group + * @param set + * if true the given filter is installed. If + * false the given filter is removed . + */ public void setMemberFilter(int filterProperty, boolean set) { - setMemberFilters(new int[] {filterProperty}, new boolean[] {set}, true); + setMemberFilters(new int[] { filterProperty }, new boolean[] { set }, + true); } - private void setMemberFilters(int[] propertyKeys, boolean[] propertyValues, boolean refresh) { + private void setMemberFilters(int[] propertyKeys, boolean[] propertyValues, + boolean refresh) { if (propertyKeys.length == 0) return; Assert.isTrue(propertyKeys.length == propertyValues.length); - - for (int i= 0; i < propertyKeys.length; i++) { - int filterProperty= propertyKeys[i]; - boolean set= propertyValues[i]; + + for (int i = 0; i < propertyKeys.length; i++) { + int filterProperty = propertyKeys[i]; + boolean set = propertyValues[i]; if (set) { fFilter.addFilter(filterProperty); } else { fFilter.removeFilter(filterProperty); } - IPreferenceStore store= PHPeclipsePlugin.getDefault().getPreferenceStore(); - - for (int j= 0; j < fFilterActions.length; j++) { - int currProperty= fFilterActions[j].getFilterProperty(); + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + + for (int j = 0; j < fFilterActions.length; j++) { + int currProperty = fFilterActions[j].getFilterProperty(); if (currProperty == filterProperty) { fFilterActions[j].setChecked(set); } - store.setValue(getPreferenceKey(currProperty), hasMemberFilter(currProperty)); + store.setValue(getPreferenceKey(currProperty), + hasMemberFilter(currProperty)); } } if (refresh) { fViewer.getControl().setRedraw(false); - BusyIndicator.showWhile(fViewer.getControl().getDisplay(), new Runnable() { - public void run() { - fViewer.refresh(); - } - }); + BusyIndicator.showWhile(fViewer.getControl().getDisplay(), + new Runnable() { + public void run() { + fViewer.refresh(); + } + }); fViewer.getControl().setRedraw(true); } } @@ -186,53 +223,65 @@ public class MemberFilterActionGroup extends ActionGroup { /** * Returns true if the given filter is installed. * - * @param filterProperty the filter to be tested. Valid values are FILTER_FIELDS, - * FILTER_PUBLIC, and FILTER_PRIVATE as defined by this action - * group - */ + * @param filterProperty + * the filter to be tested. Valid values are + * FILTER_FIELDS, FILTER_PUBLIC, + * and FILTER_PRIVATE as defined by this action + * group + */ public boolean hasMemberFilter(int filterProperty) { return fFilter.hasFilter(filterProperty); } - + /** * Saves the state of the filter actions in a memento. * - * @param memento the memento to which the state is saved + * @param memento + * the memento to which the state is saved */ public void saveState(IMemento memento) { - memento.putString(TAG_HIDEFIELDS, String.valueOf(hasMemberFilter(FILTER_FIELDS))); - memento.putString(TAG_HIDESTATIC, String.valueOf(hasMemberFilter(FILTER_STATIC))); - memento.putString(TAG_HIDENONPUBLIC, String.valueOf(hasMemberFilter(FILTER_NONPUBLIC))); + memento.putString(TAG_HIDEFIELDS, String + .valueOf(hasMemberFilter(FILTER_FIELDS))); + memento.putString(TAG_HIDESTATIC, String + .valueOf(hasMemberFilter(FILTER_STATIC))); + memento.putString(TAG_HIDENONPUBLIC, String + .valueOf(hasMemberFilter(FILTER_NONPUBLIC))); } - + /** * Restores the state of the filter actions from a memento. *

                                                      * Note: This method does not refresh the viewer. *

                                                      - * @param memento the memento from which the state is restored - */ + * + * @param memento + * the memento from which the state is restored + */ public void restoreState(IMemento memento) { - setMemberFilters( - new int[] {FILTER_FIELDS, FILTER_STATIC, FILTER_NONPUBLIC}, - new boolean[] { - Boolean.valueOf(memento.getString(TAG_HIDEFIELDS)).booleanValue(), - Boolean.valueOf(memento.getString(TAG_HIDESTATIC)).booleanValue(), - Boolean.valueOf(memento.getString(TAG_HIDENONPUBLIC)).booleanValue() - }, false); + setMemberFilters(new int[] { FILTER_FIELDS, FILTER_STATIC, + FILTER_NONPUBLIC }, new boolean[] { + Boolean.valueOf(memento.getString(TAG_HIDEFIELDS)) + .booleanValue(), + Boolean.valueOf(memento.getString(TAG_HIDESTATIC)) + .booleanValue(), + Boolean.valueOf(memento.getString(TAG_HIDENONPUBLIC)) + .booleanValue() }, false); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see ActionGroup#fillActionBars(IActionBars) */ public void fillActionBars(IActionBars actionBars) { contributeToToolBar(actionBars.getToolBarManager()); }; - + /** * Adds the filter actions to the given tool bar * - * @param tbm the tool bar to which the actions are added + * @param tbm + * the tool bar to which the actions are added */ public void contributeToToolBar(IToolBarManager tbm) { if (fInViewMenu) @@ -241,17 +290,18 @@ public class MemberFilterActionGroup extends ActionGroup { tbm.add(fFilterActions[1]); // static tbm.add(fFilterActions[2]); // public } - + /** * Adds the filter actions to the given menu manager. * - * @param menu the menu manager to which the actions are added + * @param menu + * the menu manager to which the actions are added * @since 2.1 */ public void contributeToViewMenu(IMenuManager menu) { if (!fInViewMenu) return; - final String filters= "filters"; //$NON-NLS-1$ + final String filters = "filters"; //$NON-NLS-1$ if (menu.find(filters) != null) { menu.prependToGroup(filters, fFilterActions[0]); // fields menu.prependToGroup(filters, fFilterActions[1]); // static @@ -262,8 +312,10 @@ public class MemberFilterActionGroup extends ActionGroup { menu.add(fFilterActions[2]); // public } } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see ActionGroup#dispose() */ public void dispose() { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/OpenEditorActionGroup.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/OpenEditorActionGroup.java index 108ca77..a1474ea 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/OpenEditorActionGroup.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/OpenEditorActionGroup.java @@ -31,9 +31,9 @@ import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.actions.OpenWithMenu; /** - * Action group that adds the actions opening a new editor to the - * context menu and the action bar's navigate menu. - * + * Action group that adds the actions opening a new editor to the context menu + * and the action bar's navigate menu. + * *

                                                      * This class may be instantiated; it is not intended to be subclassed. *

                                                      @@ -43,63 +43,67 @@ import org.eclipse.ui.actions.OpenWithMenu; public class OpenEditorActionGroup extends ActionGroup { private IWorkbenchSite fSite; + private boolean fIsEditorOwner; + private PHPOpenDeclarationAction fOpen; /** - * Creates a new OpenActionGroup. The group requires - * that the selection provided by the part's selection provider is of type + * Creates a new OpenActionGroup. The group requires that + * the selection provided by the part's selection provider is of type * org.eclipse.jface.viewers.IStructuredSelection. * - * @param part the view part that owns this action group + * @param part + * the view part that owns this action group */ public OpenEditorActionGroup(IViewPart part) { - fSite= part.getSite(); - fOpen= new PHPOpenDeclarationAction(fSite); + fSite = part.getSite(); + fOpen = new PHPOpenDeclarationAction(fSite); fOpen.setActionDefinitionId(PHPEditorActionDefinitionIds.OPEN_EDITOR); initialize(fSite.getSelectionProvider()); } - + /** - * Note: This constructor is for internal use only. Clients should not call this constructor. + * Note: This constructor is for internal use only. Clients should not call + * this constructor. */ public OpenEditorActionGroup(PHPEditor part) { - fIsEditorOwner= true; - fOpen= new PHPOpenDeclarationAction(part); + fIsEditorOwner = true; + fOpen = new PHPOpenDeclarationAction(part); fOpen.setActionDefinitionId(PHPEditorActionDefinitionIds.OPEN_EDITOR); part.setAction("OpenEditor", fOpen); //$NON-NLS-1$ - fSite= part.getEditorSite(); + fSite = part.getEditorSite(); initialize(fSite.getSelectionProvider()); } /** - * Returns the open action managed by this action group. + * Returns the open action managed by this action group. * - * @return the open action. Returns null if the group - * doesn't provide any open action + * @return the open action. Returns null if the group doesn't + * provide any open action */ public IAction getOpenAction() { return fOpen; } private void initialize(ISelectionProvider provider) { - ISelection selection= provider.getSelection(); + ISelection selection = provider.getSelection(); fOpen.update(selection); if (!fIsEditorOwner) { provider.addSelectionChangedListener(fOpen); } } - /* (non-Javadoc) - * Method declared in ActionGroup + /* + * (non-Javadoc) Method declared in ActionGroup */ public void fillActionBars(IActionBars actionBar) { super.fillActionBars(actionBar); setGlobalActionHandlers(actionBar); } - - /* (non-Javadoc) - * Method declared in ActionGroup + + /* + * (non-Javadoc) Method declared in ActionGroup */ public void fillContextMenu(IMenuManager menu) { super.fillContextMenu(menu); @@ -113,39 +117,40 @@ public class OpenEditorActionGroup extends ActionGroup { * @see ActionGroup#dispose() */ public void dispose() { - ISelectionProvider provider= fSite.getSelectionProvider(); + ISelectionProvider provider = fSite.getSelectionProvider(); provider.removeSelectionChangedListener(fOpen); super.dispose(); } - + private void setGlobalActionHandlers(IActionBars actionBars) { actionBars.setGlobalActionHandler(PHPdtActionConstants.OPEN, fOpen); } - + private void appendToGroup(IMenuManager menu, IAction action) { if (action.isEnabled()) menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, action); } - + private void addOpenWithMenu(IMenuManager menu) { - ISelection selection= getContext().getSelection(); + ISelection selection = getContext().getSelection(); if (selection.isEmpty() || !(selection instanceof IStructuredSelection)) return; - IStructuredSelection ss= (IStructuredSelection)selection; + IStructuredSelection ss = (IStructuredSelection) selection; if (ss.size() != 1) return; - Object o= ss.getFirstElement(); + Object o = ss.getFirstElement(); if (!(o instanceof IAdaptable)) return; - IAdaptable element= (IAdaptable)o; - Object resource= element.getAdapter(IResource.class); + IAdaptable element = (IAdaptable) o; + Object resource = element.getAdapter(IResource.class); if (!(resource instanceof IFile)) - return; + return; // Create a menu flyout. - IMenuManager submenu= new MenuManager(ActionMessages.getString("OpenWithMenu.label")); //$NON-NLS-1$ + IMenuManager submenu = new MenuManager(ActionMessages + .getString("OpenWithMenu.label")); //$NON-NLS-1$ submenu.add(new OpenWithMenu(fSite.getPage(), (IFile) resource)); // Add the submenu. diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/OpenPHPPerspectiveAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/OpenPHPPerspectiveAction.java index 238f7a9..1fc57ae 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/OpenPHPPerspectiveAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/OpenPHPPerspectiveAction.java @@ -37,24 +37,31 @@ public class OpenPHPPerspectiveAction extends Action { * Create a new OpenPHPPerspectiveAction. */ public OpenPHPPerspectiveAction() { -// WorkbenchHelp.setHelp(this, IJavaHelpContextIds.OPEN_JAVA_PERSPECTIVE_ACTION); + // WorkbenchHelp.setHelp(this, + // IJavaHelpContextIds.OPEN_JAVA_PERSPECTIVE_ACTION); } public void run() { - IWorkbench workbench= PHPeclipsePlugin.getDefault().getWorkbench(); - IWorkbenchWindow window= workbench.getActiveWorkbenchWindow(); - IWorkbenchPage page= window.getActivePage(); + IWorkbench workbench = PHPeclipsePlugin.getDefault().getWorkbench(); + IWorkbenchWindow window = workbench.getActiveWorkbenchWindow(); + IWorkbenchPage page = window.getActivePage(); IAdaptable input; if (page != null) - input= page.getInput(); + input = page.getInput(); else - input= ResourcesPlugin.getWorkspace().getRoot(); + input = ResourcesPlugin.getWorkspace().getRoot(); try { - workbench.showPerspective(PHPeclipsePlugin.ID_PERSPECTIVE, window, input); + workbench.showPerspective(PHPeclipsePlugin.ID_PERSPECTIVE, window, + input); } catch (WorkbenchException e) { - ExceptionHandler.handle(e, window.getShell(), - ActionMessages.getString("OpenPHPPerspectiveAction.dialog.title"), //$NON-NLS-1$ - ActionMessages.getString("OpenPHPPerspectiveAction.error.open_failed")); //$NON-NLS-1$ + ExceptionHandler + .handle( + e, + window.getShell(), + ActionMessages + .getString("OpenPHPPerspectiveAction.dialog.title"), //$NON-NLS-1$ + ActionMessages + .getString("OpenPHPPerspectiveAction.error.open_failed")); //$NON-NLS-1$ } } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/PHPEditorActionDefinitionIds.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/PHPEditorActionDefinitionIds.java index e0065b7..13c5b40 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/PHPEditorActionDefinitionIds.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/PHPEditorActionDefinitionIds.java @@ -1,39 +1,42 @@ package net.sourceforge.phpdt.ui.actions; public interface PHPEditorActionDefinitionIds { - /** - * Value: net.sourceforge.phpeclipse.phpeditor.comment - */ - public static final String COMMENT = "net.sourceforge.phpdt.ui.actions.comment"; - - /** - * Value: net.sourceforge.phpeclipse.phpeditor.uncomment - */ - public static final String UNCOMMENT = "net.sourceforge.phpdt.ui.actions.uncomment"; - - // navigate - - /** - * Action definition ID of the navigate -> open action - * (value "org.phpeclipse.phpdt.ui.edit.text.php.open.editor"). - */ - public static final String OPEN_EDITOR = "net.sourceforge.phpeclipse.ui.edit.text.java.open.editor"; //$NON-NLS-1$ - /** - * Action definition ID of the toggle presentation toolbar button action - * (value "net.sourceforge.phpdt.ui.edit.text.java.toggle.presentation"). - */ - public static final String TOGGLE_PRESENTATION = "net.sourceforge.phpeclipse.ui.edit.text.java.toggle.presentation"; //$NON-NLS-1$ - - /** - * Action definition ID of the toggle text hover toolbar button action - * (value "net.sourceforge.phpdt.ui.edit.text.java.toggle.text.hover"). - */ - public static final String TOGGLE_TEXT_HOVER = "net.sourceforge.phpeclipse.ui.edit.text.java.toggle.text.hover"; //$NON-NLS-1$ - - /** - * Action definition ID of the edit -> show Javadoc action - * (value "net.sourceforge.phpdt.ui.edit.text.java.show.javadoc"). + /** + * Value: net.sourceforge.phpeclipse.phpeditor.comment */ -public static final String SHOW_JAVADOC = "net.sourceforge.phpeclipse.ui.edit.text.java.show.javadoc"; //$NON-NLS-1$ + public static final String COMMENT = "net.sourceforge.phpdt.ui.actions.comment"; + + /** + * Value: net.sourceforge.phpeclipse.phpeditor.uncomment + */ + public static final String UNCOMMENT = "net.sourceforge.phpdt.ui.actions.uncomment"; + + // navigate + + /** + * Action definition ID of the navigate -> open action (value + * "org.phpeclipse.phpdt.ui.edit.text.php.open.editor"). + */ + public static final String OPEN_EDITOR = "net.sourceforge.phpeclipse.ui.edit.text.java.open.editor"; //$NON-NLS-1$ + + /** + * Action definition ID of the toggle presentation toolbar button action + * (value + * "net.sourceforge.phpdt.ui.edit.text.java.toggle.presentation"). + */ + public static final String TOGGLE_PRESENTATION = "net.sourceforge.phpeclipse.ui.edit.text.java.toggle.presentation"; //$NON-NLS-1$ + + /** + * Action definition ID of the toggle text hover toolbar button action + * (value + * "net.sourceforge.phpdt.ui.edit.text.java.toggle.text.hover"). + */ + public static final String TOGGLE_TEXT_HOVER = "net.sourceforge.phpeclipse.ui.edit.text.java.toggle.text.hover"; //$NON-NLS-1$ + + /** + * Action definition ID of the edit -> show Javadoc action (value + * "net.sourceforge.phpdt.ui.edit.text.java.show.javadoc"). + */ + public static final String SHOW_JAVADOC = "net.sourceforge.phpeclipse.ui.edit.text.java.show.javadoc"; //$NON-NLS-1$ } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/PHPdtActionConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/PHPdtActionConstants.java index 1f6fc5f..b7b5df5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/PHPdtActionConstants.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/PHPdtActionConstants.java @@ -11,8 +11,8 @@ package net.sourceforge.phpdt.ui.actions; /** - * Action ids for standard actions, for groups in the menu bar, and - * for actions in context menus of PHPDT views. + * Action ids for standard actions, for groups in the menu bar, and for actions + * in context menus of PHPDT views. * *

                                                      * This class may be instantiated; it is not intended to be subclassed. @@ -22,104 +22,108 @@ package net.sourceforge.phpdt.ui.actions; */ public class PHPdtActionConstants { - // Edit menu - /** - * Edit menu: name of standard Show Javadoc global action - * (value "net.sourceforge.phpdt.ui.actions.ShowJavaDoc"). + // Edit menu + /** + * Edit menu: name of standard Show Javadoc global action (value + * "net.sourceforge.phpdt.ui.actions.ShowJavaDoc"). + */ + public static final String SHOW_JAVA_DOC = "net.sourceforge.phpeclipse.phpeditor.ShowJavaDoc"; //$NON-NLS-1$ + + /** + * Edit menu: name of standard Code Assist global action (value + * "org.phpeclipse.phpdt.ui.actions.ContentAssist"). + */ + public static final String CONTENT_ASSIST = "net.sourceforge.phpeclipse.phpeditor.ContentAssist"; //$NON-NLS-1$ + + // Source menu + + /** + * Source menu: name of standard Comment global action (value + * "net.sourceforge.phpdt.ui.actions.Comment"). */ - public static final String SHOW_JAVA_DOC= "net.sourceforge.phpeclipse.phpeditor.ShowJavaDoc"; //$NON-NLS-1$ - - /** - * Edit menu: name of standard Code Assist global action - * (value "org.phpeclipse.phpdt.ui.actions.ContentAssist"). - */ - public static final String CONTENT_ASSIST = "net.sourceforge.phpeclipse.phpeditor.ContentAssist"; //$NON-NLS-1$ - - // Source menu - - /** - * Source menu: name of standard Comment global action - * (value "net.sourceforge.phpdt.ui.actions.Comment"). - */ - public static final String COMMENT = "net.sourceforge.phpeclipse.phpeditor.Comment"; //$NON-NLS-1$ - - /** - * Source menu: name of standard Uncomment global action - * (value "net.sourceforge.phpdt.ui.actions.Uncomment"). - */ - public static final String UNCOMMENT = "net.sourceforge.phpeclipse.phpeditor.Uncomment"; //$NON-NLS-1$ - - /** - * Source menu: name of standard ToggleComment global action - * (value "net.sourceforge.phpdt.ui.actions.ToggleComment"). + public static final String COMMENT = "net.sourceforge.phpeclipse.phpeditor.Comment"; //$NON-NLS-1$ + + /** + * Source menu: name of standard Uncomment global action (value + * "net.sourceforge.phpdt.ui.actions.Uncomment"). + */ + public static final String UNCOMMENT = "net.sourceforge.phpeclipse.phpeditor.Uncomment"; //$NON-NLS-1$ + + /** + * Source menu: name of standard ToggleComment global action (value + * "net.sourceforge.phpdt.ui.actions.ToggleComment"). + * * @since 3.0 */ - public static final String TOGGLE_COMMENT= "net.sourceforge.phpeclipse.ui.actions.ToggleComment"; //$NON-NLS-1$ - + public static final String TOGGLE_COMMENT = "net.sourceforge.phpeclipse.ui.actions.ToggleComment"; //$NON-NLS-1$ + /** - * Source menu: name of standard Comment global action - * (value "net.sourceforge.phpdt.ui.actions.AddBlockComment"). + * Source menu: name of standard Comment global action (value + * "net.sourceforge.phpdt.ui.actions.AddBlockComment"). * * @since 3.0 */ - public static final String ADD_BLOCK_COMMENT= "net.sourceforge.phpeclipse.ui.actions.AddBlockComment"; //$NON-NLS-1$ - + public static final String ADD_BLOCK_COMMENT = "net.sourceforge.phpeclipse.ui.actions.AddBlockComment"; //$NON-NLS-1$ + /** - * Source menu: name of standard Uncomment global action - * (value "net.sourceforge.phpdt.ui.actions.RemoveBlockComment"). + * Source menu: name of standard Uncomment global action (value + * "net.sourceforge.phpdt.ui.actions.RemoveBlockComment"). * * @since 3.0 */ - public static final String REMOVE_BLOCK_COMMENT= "net.sourceforge.phpeclipse.ui.actions.RemoveBlockComment"; //$NON-NLS-1$ - + public static final String REMOVE_BLOCK_COMMENT = "net.sourceforge.phpeclipse.ui.actions.RemoveBlockComment"; //$NON-NLS-1$ + /** - * Source menu: name of standard Indent global action - * (value "net.sourceforge.phpdt.ui.actions.Indent"). + * Source menu: name of standard Indent global action (value + * "net.sourceforge.phpdt.ui.actions.Indent"). * * @since 3.0 */ - public static final String INDENT= "net.sourceforge.phpeclipse.ui.actions.Indent"; //$NON-NLS-1$ - - /** - * Source menu: name of standard Shift Rightl action - * (value "net.sourceforge.phpeclipse.phpeditor.ShiftRight"). - */ - public static final String SHIFT_RIGHT = "net.sourceforge.phpeclipse.phpeditor.ShiftRight"; //$NON-NLS-1$ - - /** - * Source menu: name of standard Shift Left global action - * (value "net.sourceforge.phpeclipse.phpeditor.ShiftLeft"). - */ - public static final String SHIFT_LEFT = "net.sourceforge.phpeclipse.phpeditor.ShiftLeft"; //$NON-NLS-1$ - - /** - * Source menu: name of standard Format global action (value "org. - * phpeclipse.phpdt.ui.actions.Format"). - */ - public static final String FORMAT = "net.sourceforge.phpeclipse.phpeditor.Format"; //$NON-NLS-1$ - - /** - * Source menu: name of standard Convert Line Delimiters To Windows global action - * (value "org.phpeclipse.phpdt.ui.actions.ConvertLineDelimitersToWindows"). - */ - public static String CONVERT_LINE_DELIMITERS_TO_WINDOWS = "net.sourceforge.phpeclipse.ui.actions.ConvertLineDelimitersToWindows"; //$NON-NLS-1$ - - /** - * Source menu: name of standard Convert Line Delimiters To UNIX global action - * (value "org.phpeclipse.phpdt.ui.actions.ConvertLineDelimitersToUNIX"). - */ - public static String CONVERT_LINE_DELIMITERS_TO_UNIX = "net.sourceforge.phpeclipse.ui.actions.ConvertLineDelimitersToUNIX"; //$NON-NLS-1$ - - /** - * Source menu: name of standardConvert Line Delimiters ToMac global action - * (value "org.phpeclipse.phpdt.ui.actions.ConvertLineDelimitersToMac"). - */ - public static String CONVERT_LINE_DELIMITERS_TO_MAC = "net.sourceforge.phpeclipse.ui.actions.ConvertLineDelimitersToMac"; //$NON-NLS-1$ - - /** - * Navigate menu: name of standard Open global action - * (value "org.phpeclipse.phpdt.ui.actions.Open"). - */ - public static final String OPEN = "net.sourceforge.phpeclipse.ui.actions.Open"; //$NON-NLS-1$ + public static final String INDENT = "net.sourceforge.phpeclipse.ui.actions.Indent"; //$NON-NLS-1$ + + /** + * Source menu: name of standard Shift Rightl action (value + * "net.sourceforge.phpeclipse.phpeditor.ShiftRight"). + */ + public static final String SHIFT_RIGHT = "net.sourceforge.phpeclipse.phpeditor.ShiftRight"; //$NON-NLS-1$ + + /** + * Source menu: name of standard Shift Left global action (value + * "net.sourceforge.phpeclipse.phpeditor.ShiftLeft"). + */ + public static final String SHIFT_LEFT = "net.sourceforge.phpeclipse.phpeditor.ShiftLeft"; //$NON-NLS-1$ + + /** + * Source menu: name of standard Format global action (value "org. + * phpeclipse.phpdt.ui.actions.Format"). + */ + public static final String FORMAT = "net.sourceforge.phpeclipse.phpeditor.Format"; //$NON-NLS-1$ + + /** + * Source menu: name of standard Convert Line Delimiters To Windows global + * action (value + * "org.phpeclipse.phpdt.ui.actions.ConvertLineDelimitersToWindows"). + */ + public static String CONVERT_LINE_DELIMITERS_TO_WINDOWS = "net.sourceforge.phpeclipse.ui.actions.ConvertLineDelimitersToWindows"; //$NON-NLS-1$ + + /** + * Source menu: name of standard Convert Line Delimiters To UNIX global + * action (value + * "org.phpeclipse.phpdt.ui.actions.ConvertLineDelimitersToUNIX"). + */ + public static String CONVERT_LINE_DELIMITERS_TO_UNIX = "net.sourceforge.phpeclipse.ui.actions.ConvertLineDelimitersToUNIX"; //$NON-NLS-1$ + + /** + * Source menu: name of standardConvert Line Delimiters ToMac global action + * (value + * "org.phpeclipse.phpdt.ui.actions.ConvertLineDelimitersToMac"). + */ + public static String CONVERT_LINE_DELIMITERS_TO_MAC = "net.sourceforge.phpeclipse.ui.actions.ConvertLineDelimitersToMac"; //$NON-NLS-1$ + + /** + * Navigate menu: name of standard Open global action (value + * "org.phpeclipse.phpdt.ui.actions.Open"). + */ + public static final String OPEN = "net.sourceforge.phpeclipse.ui.actions.Open"; //$NON-NLS-1$ } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/SelectionDispatchAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/SelectionDispatchAction.java index 321c425..41d8d34 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/SelectionDispatchAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/SelectionDispatchAction.java @@ -22,18 +22,19 @@ import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IWorkbenchSite; /** - * Action that dispatches the IAction#run() and the - * ISelectionChangedListener#selectionChanged - * according to the type of the selection. + * Action that dispatches the IAction#run() and the + * ISelectionChangedListener#selectionChanged according to the + * type of the selection. * *

                                                        - *
                                                      • if selection is of type ITextSelection then - * run(ITextSelection) and selectionChanged(ITextSelection) - * is called.
                                                      • - *
                                                      • if selection is of type IStructuredSelection then - * run(IStructuredSelection) and - * selectionChanged(IStructuredSelection) is called.
                                                      • - *
                                                      • default is to call run(ISelection) and + *
                                                      • if selection is of type ITextSelection then + * run(ITextSelection) and + * selectionChanged(ITextSelection) is called.
                                                      • + *
                                                      • if selection is of type IStructuredSelection then + * run(IStructuredSelection) and + * selectionChanged(IStructuredSelection) + * is called.
                                                      • + *
                                                      • default is to call run(ISelection) and * selectionChanged(ISelection).
                                                      • *
                                                      * @@ -43,21 +44,23 @@ import org.eclipse.ui.IWorkbenchSite; * * @since 2.0 */ -public abstract class SelectionDispatchAction extends Action implements ISelectionChangedListener { - +public abstract class SelectionDispatchAction extends Action implements + ISelectionChangedListener { + private IWorkbenchSite fSite; - + /** * Creates a new action with no text and no image. *

                                                      * Configure the action later using the set methods. *

                                                      * - * @param site the site this action is working on + * @param site + * the site this action is working on */ protected SelectionDispatchAction(IWorkbenchSite site) { Assert.isNotNull(site); - fSite= site; + fSite = site; } /** @@ -73,7 +76,7 @@ public abstract class SelectionDispatchAction extends Action implements ISelecti * Returns the selection provided by the site owning this action. * * @return the site's selection - */ + */ public ISelection getSelection() { return getSelectionProvider().getSelection(); } @@ -81,94 +84,101 @@ public abstract class SelectionDispatchAction extends Action implements ISelecti /** * Returns the shell provided by the site owning this action. * - * @return the site's shell + * @return the site's shell */ - public Shell getShell() { + public Shell getShell() { return fSite.getShell(); } - + /** * Returns the selection provider managed by the site owning this action. * - * @return the site's selection provider + * @return the site's selection provider */ public ISelectionProvider getSelectionProvider() { return fSite.getSelectionProvider(); } /** - * Updates the action's enablement state according to the given selection. This - * default implementation calls one of the selectionChanged - * methods depending on the type of the passed selection. + * Updates the action's enablement state according to the given selection. + * This default implementation calls one of the + * selectionChanged methods depending on the type of the + * passed selection. * - * @param selection the selection this action is working on + * @param selection + * the selection this action is working on */ public void update(ISelection selection) { dispatchSelectionChanged(selection); } /** - * Notifies this action that the given structured selection has changed. This default - * implementation calls selectionChanged(ISelection selection). + * Notifies this action that the given structured selection has changed. + * This default implementation calls + * selectionChanged(ISelection selection). * - * @param selection the new selection - */ + * @param selection + * the new selection + */ protected void selectionChanged(IStructuredSelection selection) { - selectionChanged((ISelection)selection); + selectionChanged((ISelection) selection); } /** - * Executes this actions with the given structured selection. This default implementation - * calls run(ISelection selection). + * Executes this actions with the given structured selection. This default + * implementation calls run(ISelection selection). */ protected void run(IStructuredSelection selection) { - run((ISelection)selection); + run((ISelection) selection); } - + /** - * Notifies this action that the given text selection has changed. This default - * implementation calls selectionChanged(ISelection selection). + * Notifies this action that the given text selection has changed. This + * default implementation calls + * selectionChanged(ISelection selection). * - * @param selection the new selection - */ + * @param selection + * the new selection + */ protected void selectionChanged(ITextSelection selection) { - selectionChanged((ISelection)selection); + selectionChanged((ISelection) selection); } - + /** - * Executes this actions with the given text selection. This default implementation - * calls run(ISelection selection). + * Executes this actions with the given text selection. This default + * implementation calls run(ISelection selection). */ protected void run(ITextSelection selection) { - run((ISelection)selection); + run((ISelection) selection); } - + /** - * Notifies this action that the given selection has changed. This default + * Notifies this action that the given selection has changed. This default * implementation sets the action's enablement state to false. * - * @param selection the new selection - */ + * @param selection + * the new selection + */ protected void selectionChanged(ISelection selection) { setEnabled(false); } - + /** - * Executes this actions with the given selection. This default implementation - * does nothing. + * Executes this actions with the given selection. This default + * implementation does nothing. */ protected void run(ISelection selection) { } - /* (non-Javadoc) - * Method declared on IAction. + /* + * (non-Javadoc) Method declared on IAction. */ public void run() { dispatchRun(getSelection()); } - - /* (non-Javadoc) - * Method declared on ISelectionChangedListener. + + /* + * (non-Javadoc) Method declared on ISelectionChangedListener. */ public void selectionChanged(SelectionChangedEvent event) { dispatchSelectionChanged(event.getSelection()); @@ -176,9 +186,9 @@ public abstract class SelectionDispatchAction extends Action implements ISelecti private void dispatchSelectionChanged(ISelection selection) { if (selection instanceof IStructuredSelection) { - selectionChanged((IStructuredSelection)selection); + selectionChanged((IStructuredSelection) selection); } else if (selection instanceof ITextSelection) { - selectionChanged((ITextSelection)selection); + selectionChanged((ITextSelection) selection); } else { selectionChanged(selection); } @@ -186,9 +196,9 @@ public abstract class SelectionDispatchAction extends Action implements ISelecti private void dispatchRun(ISelection selection) { if (selection instanceof IStructuredSelection) { - run((IStructuredSelection)selection); + run((IStructuredSelection) selection); } else if (selection instanceof ITextSelection) { - run((ITextSelection)selection); + run((ITextSelection) selection); } else { run(selection); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/IColorManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/IColorManager.java index 8db5028..2a6b3a5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/IColorManager.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/IColorManager.java @@ -14,39 +14,38 @@ import org.eclipse.jface.text.source.ISharedTextColors; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.RGB; - /** - * Manages SWT color objects for given color keys and - * given RGB objects. Until the dispose - * method is called, the same color object is returned for - * equal keys and equal RGB values. + * Manages SWT color objects for given color keys and given RGB + * objects. Until the dispose method is called, the same color + * object is returned for equal keys and equal RGB values. *

                                                      * This interface may be implemented by clients. *

                                                      - * + * * @see IJavaColorConstants */ public interface IColorManager extends ISharedTextColors { - + /** - * Returns a color object for the given key. The color objects - * are remembered internally; the same color object is returned - * for equal keys. - * - * @param key the color key + * Returns a color object for the given key. The color objects are + * remembered internally; the same color object is returned for equal keys. + * + * @param key + * the color key * @return the color object for the given key */ Color getColor(String key); - + /** * Returns the color object for the value represented by the given * RGB object. - * - * @param rgb the rgb color specification + * + * @param rgb + * the rgb color specification * @return the color object for the given rgb value */ - Color getColor(RGB rgb); - + Color getColor(RGB rgb); + /** * Disposes all color objects remembered by this color manager. */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/IColorManagerExtension.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/IColorManagerExtension.java index 1b38030..15c0346 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/IColorManagerExtension.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/IColorManagerExtension.java @@ -13,27 +13,31 @@ package net.sourceforge.phpdt.ui.text; import org.eclipse.swt.graphics.RGB; /** - * A color manager extension for extending IColorManager + * A color manager extension for extending IColorManager * instances with new functionality. * * @since 2.0 */ public interface IColorManagerExtension { - + /** * Remembers the given color specification under the given key. - * - * @param key the color key - * @param rgb the color specification - * @exception UnsupportedOperationException if there is already a - * color specification remembered under the given key + * + * @param key + * the color key + * @param rgb + * the color specification + * @exception UnsupportedOperationException + * if there is already a color specification remembered under + * the given key */ void bindColor(String key, RGB rgb); - - + /** * Forgets the color specification remembered under the given key. - * @param key the color key + * + * @param key + * the color key */ void unbindColor(String key); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/IJavaColorConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/IJavaColorConstants.java index be9ad3a..936d157 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/IJavaColorConstants.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/IJavaColorConstants.java @@ -11,51 +11,54 @@ package net.sourceforge.phpdt.ui.text; /** - * Color keys used for syntax highlighting PHP - * code and PHPDoc compliant comments. - * A IColorManager is responsible for mapping - * concrete colors to these keys. + * Color keys used for syntax highlighting PHP code and PHPDoc compliant + * comments. A IColorManager is responsible for mapping concrete + * colors to these keys. *

                                                      - * This interface declares static final fields only; it is not intended to be + * This interface declares static final fields only; it is not intended to be * implemented. *

                                                      - * + * * @see IColorManager */ public interface IJavaColorConstants { - - /** - * Note: This constant is for internal use only. Clients should not use this constant. - * The prefix all color constants start with. + + /** + * Note: This constant is for internal use only. Clients should not use this + * constant. The prefix all color constants start with. */ -// String PREFIX= "php_"; //$NON-NLS-1$ -// -// /** The color key for multi-line comments in PHP code. */ -// String PHP_MULTI_LINE_COMMENT= "php_multi_line_comment"; //$NON-NLS-1$ -// /** The color key for single-line comments in PHP code. */ -// String PHP_SINGLE_LINE_COMMENT= "php_single_line_comment"; //$NON-NLS-1$ -// /** The color key for PHP keywords in PHP code. */ -// String PHP_KEYWORD= "php_keyword"; //$NON-NLS-1$ -// /** The color key for string and character literals in PHP code. */ -// String PHP_STRING= "php_string"; //$NON-NLS-1$ -// /** The color key for everthing in PHP code for which no other color is specified. */ -// String PHP_DEFAULT= "php_default"; //$NON-NLS-1$ -// /** The color key for predefined PHP function namesin PHP code. */ -// String PHP_FUNCTIONNAME= "php_functionname"; //$NON-NLS-1$ -// /** The color key for ($-)variables in PHP code. */ -// String PHP_VARIABLE= "php_variable"; //$NON-NLS-1$ -// /** The color key for constants in PHP code */ -// String PHP_CONSTANT= "php_constant"; //$NON-NLS-1$ -// /** The color key for the PHP built-in types in PHP code. */ -// String PHP_TYPE= "php_type"; //$NON-NLS-1$ - - -// /** The color key for PHPDoc keywords (@foo) in PHPDoc comments. */ -// String PHPDOC_KEYWORD= "php_doc_keyword"; //$NON-NLS-1$ -// /** The color key for HTML tags (<foo>) in PHPDoc comments. */ -// String PHPDOC_TAG= "php_doc_tag"; //$NON-NLS-1$ -// /** The color key for PHPDoc links ({foo}) in PHPDoc comments. */ -// String PHPDOC_LINK= "php_doc_link"; //$NON-NLS-1$ -// /** The color key for everthing in PHPDoc comments for which no other color is specified. */ -// String PHPDOC_DEFAULT= "php_doc_default"; //$NON-NLS-1$ + // String PREFIX= "php_"; //$NON-NLS-1$ + // + // /** The color key for multi-line comments in PHP code. */ + // String PHP_MULTI_LINE_COMMENT= "php_multi_line_comment"; //$NON-NLS-1$ + // /** The color key for single-line comments in PHP code. */ + // String PHP_SINGLE_LINE_COMMENT= "php_single_line_comment"; //$NON-NLS-1$ + // /** The color key for PHP keywords in PHP code. */ + // String PHP_KEYWORD= "php_keyword"; //$NON-NLS-1$ + // /** The color key for string and character literals in PHP code. */ + // String PHP_STRING= "php_string"; //$NON-NLS-1$ + // /** The color key for everthing in PHP code for which no other color is + // specified. */ + // String PHP_DEFAULT= "php_default"; //$NON-NLS-1$ + // /** The color key for predefined PHP function namesin PHP code. */ + // String PHP_FUNCTIONNAME= "php_functionname"; //$NON-NLS-1$ + // /** The color key for ($-)variables in PHP code. */ + // String PHP_VARIABLE= "php_variable"; //$NON-NLS-1$ + // /** The color key for constants in PHP code */ + // String PHP_CONSTANT= "php_constant"; //$NON-NLS-1$ + // /** The color key for the PHP built-in types in PHP code. */ + // String PHP_TYPE= "php_type"; //$NON-NLS-1$ + + // /** The color key for PHPDoc keywords (@foo) in PHPDoc + // comments. */ + // String PHPDOC_KEYWORD= "php_doc_keyword"; //$NON-NLS-1$ + // /** The color key for HTML tags (<foo>) in PHPDoc + // comments. */ + // String PHPDOC_TAG= "php_doc_tag"; //$NON-NLS-1$ + // /** The color key for PHPDoc links ({foo}) in PHPDoc + // comments. */ + // String PHPDOC_LINK= "php_doc_link"; //$NON-NLS-1$ + // /** The color key for everthing in PHPDoc comments for which no other + // color is specified. */ + // String PHPDOC_DEFAULT= "php_doc_default"; //$NON-NLS-1$ } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/JavaTextTools.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/JavaTextTools.java index 1c69685..10c34c1 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/JavaTextTools.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/JavaTextTools.java @@ -30,657 +30,706 @@ import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; // -//import org.phpeclipse.phpdt.internal.ui.text.FastJavaPartitionScanner; -//import org.phpeclipse.phpdt.internal.ui.text.JavaColorManager; -//import org.phpeclipse.phpdt.internal.ui.text.JavaPartitionScanner; -//import org.phpeclipse.phpdt.internal.ui.text.SingleTokenJavaScanner; -//import org.phpeclipse.phpdt.internal.ui.text.php.JavaCodeScanner; -//import org.phpeclipse.phpdt.internal.ui.text.phpdoc.JavaDocScanner; +// import org.phpeclipse.phpdt.internal.ui.text.FastJavaPartitionScanner; +// import org.phpeclipse.phpdt.internal.ui.text.JavaColorManager; +// import org.phpeclipse.phpdt.internal.ui.text.JavaPartitionScanner; +// import org.phpeclipse.phpdt.internal.ui.text.SingleTokenJavaScanner; +// import org.phpeclipse.phpdt.internal.ui.text.php.JavaCodeScanner; +// import org.phpeclipse.phpdt.internal.ui.text.phpdoc.JavaDocScanner; /** - * Tools required to configure a Java text viewer. The color manager and all scanner exist only one time, i.e. the same instances - * are returned to all clients. Thus, clients share those tools. + * Tools required to configure a Java text viewer. The color manager and all + * scanner exist only one time, i.e. the same instances are returned to all + * clients. Thus, clients share those tools. *

                                                      * This class may be instantiated; it is not intended to be subclassed. *

                                                      */ public class JavaTextTools implements IPHPPartitions { - // private static final String[] TOKENS = { - // JSPScriptScanner.JSP_DEFAULT, - // JSPScriptScanner.JSP_BRACKET }; - private final static String[] LEGAL_CONTENT_TYPES = new String[] { - PHP_PHPDOC_COMMENT, - PHP_MULTILINE_COMMENT, - PHP_SINGLELINE_COMMENT, - PHP_STRING_DQ, - PHP_STRING_SQ, - PHP_STRING_HEREDOC}; - -// private static XMLPartitionScanner HTML_PARTITION_SCANNER = null; - -// private static FastJavaPartitionScanner PHP_PARTITION_SCANNER = null; - - private static HTMLPartitionScanner SMARTY_PARTITION_SCANNER = null; - -// private static XMLPartitionScanner XML_PARTITION_SCANNER = null; - - // private final static String[] TYPES= new String[] { PHPPartitionScanner.PHP, PHPPartitionScanner.JAVA_DOC, - // PHPPartitionScanner.JAVA_MULTILINE_COMMENT }; - // private final static String[] TYPES = new String[] { - // IPHPPartitions.PHP_PARTITIONING, - // IPHPPartitions.PHP_PHPDOC_COMMENT, - // // IPHPPartitions.HTML, - // // IPHPPartitions.HTML_MULTILINE_COMMENT, - // IPHPPartitions.JAVASCRIPT, - // IPHPPartitions.CSS, - // IPHPPartitions.SMARTY, - // IPHPPartitions.SMARTY_MULTILINE_COMMENT }; - - /** - * This tools' preference listener. - */ - private class PreferenceListener implements IPropertyChangeListener, Preferences.IPropertyChangeListener { - public void propertyChange(PropertyChangeEvent event) { - adaptToPreferenceChange(event); - } - - public void propertyChange(Preferences.PropertyChangeEvent event) { - adaptToPreferenceChange(new PropertyChangeEvent(event.getSource(), event.getProperty(), event.getOldValue(), event - .getNewValue())); - } - }; - - // /** The color manager */ - private JavaColorManager colorManager; - - /** The PHP source code scanner */ - private PHPCodeScanner fCodeScanner; - - /** The PHP multiline comment scanner */ - private SingleTokenPHPScanner fMultilineCommentScanner; - - /** The Java singleline comment scanner */ - private SingleTokenPHPScanner fSinglelineCommentScanner; - - /** The PHP double quoted string scanner */ -// private SingleTokenPHPScanner fStringDQScanner; - - /** The PHP single quoted string scanner */ -// private SingleTokenPHPScanner fStringSQScanner; - - /** The PHPDoc scanner */ - private PHPDocCodeScanner fPHPDocScanner; - - /** The HTML scanner */ - // private HTMLCodeScanner fHTMLScanner; - /** The Smarty scanner */ - private SmartyCodeScanner fSmartyScanner; - - /** The SmartyDoc scanner */ - private SmartyDocCodeScanner fSmartyDocScanner; - - /** The Java partitions scanner. */ - private FastJavaPartitionScanner fPartitionScanner; - - /** The preference store */ - private IPreferenceStore fPreferenceStore; - - /** The XML Language text tools */ - private XMLTextTools xmlTextTools; - - /** - * The core preference store. - * - * @since 2.1 - */ - private Preferences fCorePreferenceStore; - - /** The preference change listener */ - private PreferenceListener fPreferenceListener = new PreferenceListener(); - - /** The JSP partitions scanner */ - private PHPPartitionScanner jspPartitionScanner = null; - - /** The JSP script subpartitions scanner */ - // private JSPScriptScanner jspScriptScanner; - /** The PHP plain text scanner */ - // private RuleBasedScanner jspTextScanner; - /** The PHP brackets scanner */ - // private RuleBasedScanner jspBracketScanner; - /** - * Creates a new Java text tools collection. - * - * @param store - * the preference store to initialize the text tools. The text tool instance installs a listener on the passed preference - * store to adapt itself to changes in the preference store. In general PreferenceConstants. - * getPreferenceStore() - * should be used to initialize the text tools. - * @param coreStore - * optional preference store to initialize the text tools. The text tool instance installs a listener on the passed - * preference store to adapt itself to changes in the preference store. - * @see net.sourceforge.phpdt.ui.PreferenceConstants#getPreferenceStore() - * @since 2.1 - */ - public JavaTextTools(IPreferenceStore store, Preferences coreStore) { - this(store, coreStore, true); - } - - /** - * Creates a new Java text tools collection. - * - * @param store - * the preference store to initialize the text tools. The text tool instance installs a listener on the passed preference - * store to adapt itself to changes in the preference store. In general PreferenceConstants. - * getPreferenceStore() - * shoould be used to initialize the text tools. - * @param coreStore - * optional preference store to initialize the text tools. The text tool instance installs a listener on the passed - * preference store to adapt itself to changes in the preference store. - * @param autoDisposeOnDisplayDispose - * if true the color manager automatically disposes all managed colors when the current display gets - * disposed and all calls to {@link org.eclipse.jface.text.source.ISharedTextColors#dispose()}are ignored. - * @see net.sourceforge.phpdt.ui.PreferenceConstants#getPreferenceStore() - * @since 2.1 - */ - public JavaTextTools(IPreferenceStore store, Preferences coreStore, boolean autoDisposeOnDisplayDispose) { - // super(store, TOKENS, ); - // REVISIT: preference store - xmlTextTools = new XMLTextTools(XMLPlugin.getDefault().getPreferenceStore()); - - colorManager = new JavaColorManager(autoDisposeOnDisplayDispose); - fPreferenceStore = store; - fPreferenceStore.addPropertyChangeListener(fPreferenceListener); - - fCorePreferenceStore = coreStore; - if (fCorePreferenceStore != null) - fCorePreferenceStore.addPropertyChangeListener(fPreferenceListener); - - fCodeScanner = new PHPCodeScanner((JavaColorManager) colorManager, store); - fMultilineCommentScanner = new SingleTokenPHPScanner((JavaColorManager) colorManager, store, - IPreferenceConstants.PHP_MULTILINE_COMMENT); - fSinglelineCommentScanner = new SingleTokenPHPScanner((JavaColorManager) colorManager, store, - IPreferenceConstants.PHP_SINGLELINE_COMMENT); -// fStringDQScanner = new SingleTokenPHPScanner((JavaColorManager) colorManager, store, IPreferenceConstants.PHP_STRING); -// fStringSQScanner = new SingleTokenPHPScanner((JavaColorManager) colorManager, store, IPreferenceConstants.PHP_STRING); - - fPHPDocScanner = new PHPDocCodeScanner((JavaColorManager) colorManager, store); - // fHTMLScanner = new HTMLCodeScanner((JavaColorManager)fColorManager, store); - fSmartyScanner = new SmartyCodeScanner((JavaColorManager) colorManager, store); - fSmartyDocScanner = new SmartyDocCodeScanner((JavaColorManager) colorManager, store); - - fPartitionScanner = new FastJavaPartitionScanner(); - - // jspScriptScanner = new JSPScriptScanner(); - // fPartitionScanner = new FastJavaPartitionScanner(); - // fPartitionScanner = new PHPPartitionScanner(); - - // jspBracketScanner = new RuleBasedScanner(); - // jspBracketScanner.setDefaultReturnToken(new Token(JSPScriptScanner.JSP_BRACKET)); - // jspTextScanner = new RuleBasedScanner(); - // jspTextScanner.setDefaultReturnToken(new Token(JSPScriptScanner.JSP_DEFAULT)); - } - - /** - * - */ - public XMLTextTools getXMLTextTools() { - return xmlTextTools; - } - - /** - * Disposes all the individual tools of this tools collection. - */ - public void dispose() { - - fCodeScanner = null; - fMultilineCommentScanner = null; - fSinglelineCommentScanner = null; -// fStringDQScanner = null; -// fStringSQScanner = null; - fPHPDocScanner = null; - // fPartitionScanner = null; - - if (colorManager != null) { - colorManager.dispose(); - colorManager = null; - } - - if (fPreferenceStore != null) { - fPreferenceStore.removePropertyChangeListener(fPreferenceListener); - fPreferenceStore = null; - - if (fCorePreferenceStore != null) { - fCorePreferenceStore.removePropertyChangeListener(fPreferenceListener); - fCorePreferenceStore = null; - } - - fPreferenceListener = null; - } - } - - /** - * Returns the color manager which is used to manage any Java-specific colors needed for such things like syntax highlighting. - * - * @return the color manager to be used for Java text viewers - */ - public JavaColorManager getColorManager() { - return (JavaColorManager) colorManager; - } - - /** - * Returns a scanner which is configured to scan Java source code. - * - * @return a Java source code scanner - */ - public RuleBasedScanner getCodeScanner() { - return fCodeScanner; - } - - /** - * Returns a scanner which is configured to scan Java multiline comments. - * - * @return a Java multiline comment scanner - * - * @since 2.0 - */ - public RuleBasedScanner getMultilineCommentScanner() { - return fMultilineCommentScanner; - } - - /** - * Returns a scanner which is configured to scan HTML code. - * - * @return a HTML scanner - * - * @since 2.0 - */ - // public RuleBasedScanner getHTMLScanner() { - // return fHTMLScanner; - // } - /** - * Returns a scanner which is configured to scan Smarty code. - * - * @return a Smarty scanner - * - * @since 2.0 - */ - public RuleBasedScanner getSmartyScanner() { - return fSmartyScanner; - } - - /** - * Returns a scanner which is configured to scan Smarty code. - * - * @return a Smarty scanner - * - * @since 2.0 - */ - public RuleBasedScanner getSmartyDocScanner() { - return fSmartyDocScanner; - } - - /** - * Returns a scanner which is configured to scan Java singleline comments. - * - * @return a Java singleline comment scanner - * - * @since 2.0 - */ - public RuleBasedScanner getSinglelineCommentScanner() { - return fSinglelineCommentScanner; - } - - /** - * Returns a scanner which is configured to scan Java strings. - * - * @return a Java string scanner - * - * @since 2.0 - */ -// public RuleBasedScanner getStringScanner() { -// return fStringDQScanner; -// } - - /** - * Returns a scanner which is configured to scan JavaDoc compliant comments. Notes that the start sequence "/**" and the - * corresponding end sequence are part of the JavaDoc comment. - * - * @return a JavaDoc scanner - */ - public RuleBasedScanner getJavaDocScanner() { - return fPHPDocScanner; - } - - /** - * Returns a scanner which is configured to scan Java-specific partitions, which are multi-line comments, JavaDoc comments, and - * regular Java source code. - * - * @return a Java partition scanner - */ - // public IPartitionTokenScanner getPartitionScanner() { - // return fPartitionScanner; - // } - /** - * Factory method for creating a PHP-specific document partitioner using this object's partitions scanner. This method is a - * convenience method. - * - * @return a newly created Java document partitioner - */ - public IDocumentPartitioner createDocumentPartitioner() { - return createDocumentPartitioner(".php"); - } - - /** - * Factory method for creating a PHP-specific document partitioner using this object's partitions scanner. This method is a - * convenience method. - * - * @return a newly created Java document partitioner - */ - public IDocumentPartitioner createDocumentPartitioner(String extension) { - - // String[] types = - // new String[] { - // FastJavaPartitionScanner.JAVA_DOC, - // FastJavaPartitionScanner.JAVA_MULTI_LINE_COMMENT, - // FastJavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT, - // FastJavaPartitionScanner.JAVA_STRING }; - // - // return new DefaultPartitioner(getPartitionScanner(), types); - IDocumentPartitioner partitioner = null; - // System.out.println(extension); - if (extension.equalsIgnoreCase(".html") || extension.equalsIgnoreCase(".htm")) { - // html - partitioner = createHTMLPartitioner(); - partitioner = createJSPPartitioner(); - } else if (extension.equalsIgnoreCase(".xml")) { - // xml - partitioner = createXMLPartitioner(); - // } else if (extension.equalsIgnoreCase(".js")) { - // // javascript - // partitioner = createJavaScriptPartitioner(); - // } else if (extension.equalsIgnoreCase(".css")) { - // // cascading style sheets - // partitioner = createCSSPartitioner(); - } else if (extension.equalsIgnoreCase(".tpl")) { - // smarty ? - partitioner = createSmartyPartitioner(); - // } else if (extension.equalsIgnoreCase(".inc")) { - // // php include files ? - // partitioner = createIncludePartitioner(); - } - - if (partitioner == null) { - partitioner = createJSPPartitioner(); - } - - return partitioner; - } - - /** - * Sets up the Java document partitioner for the given document for the given partitioning. - * - * @param document - * the document to be set up - * @param partitioning - * the document partitioning - * @param element - * TODO - * - * @since 3.0 - */ - // public void setupJavaDocumentPartitioner(IDocument document, String partitioning, Object element) { - // IDocumentPartitioner partitioner = createDocumentPartitioner(".php"); - // - // // if (document instanceof IDocumentExtension3) { - // // IDocumentExtension3 extension3= (IDocumentExtension3) document; - // // extension3.setDocumentPartitioner(partitioning, partitioner); - // // } else { - // document.setDocumentPartitioner(partitioner); - // // } - // partitioner.connect(document); - // } - public void setupHTMLDocumentPartitioner(IDocument document, String partitioning, Object element) { - IDocumentPartitioner partitioner = createDocumentPartitioner(".html"); - - // if (document instanceof IDocumentExtension3) { - // IDocumentExtension3 extension3= (IDocumentExtension3) document; - // extension3.setDocumentPartitioner(partitioning, partitioner); - // } else { - document.setDocumentPartitioner(partitioner); - // } - partitioner.connect(document); - } - - public void setupSmartyDocumentPartitioner(IDocument document, String partitioning, Object element) { - IDocumentPartitioner partitioner = createDocumentPartitioner(".tpl"); - - // if (document instanceof IDocumentExtension3) { - // IDocumentExtension3 extension3= (IDocumentExtension3) document; - // extension3.setDocumentPartitioner(partitioning, partitioner); - // } else { - document.setDocumentPartitioner(partitioner); - // } - partitioner.connect(document); - } - - /** - * Returns the names of the document position categories used by the document partitioners created by this object to manage their - * partition information. If the partitioners don't use document position categories, the returned result is null. - * - * @return the partition managing position categories or null if there is none - */ - public String[] getPartitionManagingPositionCategories() { - return new String[] { DefaultPartitioner.CONTENT_TYPES_CATEGORY }; - } - - /** - * Determines whether the preference change encoded by the given event changes the behavior of one its contained components. - * - * @param event - * the event to be investigated - * @return true if event causes a behavioral change - * @since 2.0 - * @deprecated As of 3.0, replaced by - * {@link net.sourceforge.phpdt.ui.text.JavaSourceViewerConfiguration#affectsTextPresentation(PropertyChangeEvent)} - */ - // public boolean affectsBehavior(PropertyChangeEvent event) { - // return fCodeScanner.affectsBehavior(event) - // || fMultilineCommentScanner.affectsBehavior(event) - // || fSinglelineCommentScanner.affectsBehavior(event) - // || fStringDQScanner.affectsBehavior(event) - // || fPHPDocScanner.affectsBehavior(event); - // } - /** - * Adapts the behavior of the contained components to the change encoded in the given event. - * - * @param event - * the event to which to adapt - * @since 2.0 - */ - protected void adaptToPreferenceChange(PropertyChangeEvent event) { - if (fCodeScanner.affectsBehavior(event)) - fCodeScanner.adaptToPreferenceChange(event); - if (fMultilineCommentScanner.affectsBehavior(event)) - fMultilineCommentScanner.adaptToPreferenceChange(event); - if (fSinglelineCommentScanner.affectsBehavior(event)) - fSinglelineCommentScanner.adaptToPreferenceChange(event); - // if (fStringDQScanner.affectsBehavior(event)) - // fStringDQScanner.adaptToPreferenceChange(event); - if (fPHPDocScanner.affectsBehavior(event)) - fPHPDocScanner.adaptToPreferenceChange(event); - // if (fHTMLScanner.affectsBehavior(event)) - // fHTMLScanner.adaptToPreferenceChange(event); - if (fSmartyScanner.affectsBehavior(event)) - fSmartyScanner.adaptToPreferenceChange(event); - if (fSmartyDocScanner.affectsBehavior(event)) - fSmartyDocScanner.adaptToPreferenceChange(event); - // if (XMLPlugin.getDefault().getXMLTextTools().affectsBehavior(event)) { - // XMLPlugin.getDefault().getXMLTextTools().adaptToPreferenceChange(event); - // } - } - - /** - * Return a partitioner for .html files. - */ - public IDocumentPartitioner createHTMLPartitioner() { - // return new DefaultPartitioner(getHTMLPartitionScanner(), TYPES); - return xmlTextTools.createXMLPartitioner(); - } - - // private static IDocumentPartitioner createIncludePartitioner() { - // // return new DefaultPartitioner(getPHPPartitionScanner(), TYPES); - // return new DefaultPartitioner(getPHPPartitionScanner(), FastJavaPartitionScanner.PHP_PARTITION_TYPES); - // - // } - - // private static IDocumentPartitioner createJavaScriptPartitioner() { - // return new DefaultPartitioner(getHTMLPartitionScanner(), TYPES); - // } - - /** - * Return a partitioner for .php files. - */ - public IDocumentPartitioner createPHPPartitioner() { - // return new DefaultPartitioner(getPHPPartitionScanner(), TYPES); - return new DefaultPartitioner(getPHPPartitionScanner(), LEGAL_CONTENT_TYPES); - } - - private IDocumentPartitioner createJSPPartitioner() { - return new PHPDocumentPartitioner(getJSPPartitionScanner()); - // return new JSPDocumentPartitioner(getJSPPartitionScanner(), jspScriptScanner); - } - - /** - * - */ - // public IPartitionTokenScanner getJSPScriptScanner() { - // return jspScriptScanner; - // } - private IDocumentPartitioner createSmartyPartitioner() { - return new DefaultPartitioner(getSmartyPartitionScanner(), XMLTextTools.TYPES); - } - - private IDocumentPartitioner createXMLPartitioner() { - // return new DefaultPartitioner(getXMLPartitionScanner(), XMLTextTools.TYPES); - return xmlTextTools.createXMLPartitioner(); - } - - // private IDocumentPartitioner createCSSPartitioner() { - // return new DefaultPartitioner(getHTMLPartitionScanner(), XMLTextTools.TYPES); - // } - - /** - * Return a scanner for creating html partitions. - */ - // private static XMLPartitionScanner getHTMLPartitionScanner() { - // // if (HTML_PARTITION_SCANNER == null) - // // HTML_PARTITION_SCANNER = new HTMLPartitionScanner(IPHPPartitions.HTML_FILE); - // // return HTML_PARTITION_SCANNER;^ - // if (HTML_PARTITION_SCANNER == null) - // HTML_PARTITION_SCANNER = new XMLPartitionScanner(false); - // return HTML_PARTITION_SCANNER; - // } - /** - * Return a scanner for creating php partitions. - */ - private FastJavaPartitionScanner getPHPPartitionScanner() { - // if (PHP_PARTITION_SCANNER == null) - // PHP_PARTITION_SCANNER = new FastJavaPartitionScanner(); //new PHPPartitionScanner(IPHPPartitions.PHP_FILE); - // return PHP_PARTITION_SCANNER; - return fPartitionScanner; - } - - /** - * Returns a scanner which is configured to scan plain text in JSP. - * - * @return a JSP text scanner - */ - // public RuleBasedScanner getJSPTextScanner() { - // return jspTextScanner; - // } - /** - * Returns a scanner which is configured to scan plain text in JSP. - * - * @return a JSP text scanner - */ - // public RuleBasedScanner getJSPBracketScanner() { - // return jspBracketScanner; - // } - /** - * Return a scanner for creating smarty partitions. - */ - private static HTMLPartitionScanner getSmartyPartitionScanner() { - if (SMARTY_PARTITION_SCANNER == null) - SMARTY_PARTITION_SCANNER = new HTMLPartitionScanner(IPHPPartitions.SMARTY_FILE); - return SMARTY_PARTITION_SCANNER; - } - - /** - * Return a scanner for creating xml partitions. - */ -// private static XMLPartitionScanner getXMLPartitionScanner() { -// // if (XML_PARTITION_SCANNER == null) -// // XML_PARTITION_SCANNER = new HTMLPartitionScanner(IPHPPartitions.XML_FILE); -// // return XML_PARTITION_SCANNER; -// if (XML_PARTITION_SCANNER == null) -// XML_PARTITION_SCANNER = new XMLPartitionScanner(false); -// return XML_PARTITION_SCANNER; -// } - - private PHPPartitionScanner getJSPPartitionScanner() { - if (jspPartitionScanner == null) - jspPartitionScanner = new PHPPartitionScanner(); - return jspPartitionScanner; - } - - /** - * Sets up the Java document partitioner for the given document for the default partitioning. - * - * @param document - * the document to be set up - * @since 3.0 - */ - public void setupJavaDocumentPartitioner(IDocument document) { - setupJavaDocumentPartitioner(document, IDocumentExtension3.DEFAULT_PARTITIONING); - } - - /** - * Sets up the Java document partitioner for the given document for the given partitioning. - * - * @param document - * the document to be set up - * @param partitioning - * the document partitioning - * @since 3.0 - */ - public void setupJavaDocumentPartitioner(IDocument document, String partitioning) { - IDocumentPartitioner partitioner = createDocumentPartitioner(); - if (document instanceof IDocumentExtension3) { - IDocumentExtension3 extension3 = (IDocumentExtension3) document; - extension3.setDocumentPartitioner(partitioning, partitioner); - } else { - document.setDocumentPartitioner(partitioner); - } - partitioner.connect(document); - } - - /** - * Returns this text tool's preference store. - * - * @return the preference store - * @since 3.0 - */ - protected IPreferenceStore getPreferenceStore() { - return fPreferenceStore; - } - - /** - * Returns this text tool's core preference store. - * - * @return the core preference store - * @since 3.0 - */ - protected Preferences getCorePreferenceStore() { - return fCorePreferenceStore; - } + // private static final String[] TOKENS = { + // JSPScriptScanner.JSP_DEFAULT, + // JSPScriptScanner.JSP_BRACKET }; + private final static String[] LEGAL_CONTENT_TYPES = new String[] { + PHP_PHPDOC_COMMENT, PHP_MULTILINE_COMMENT, PHP_SINGLELINE_COMMENT, + PHP_STRING_DQ, PHP_STRING_SQ, PHP_STRING_HEREDOC }; + + // private static XMLPartitionScanner HTML_PARTITION_SCANNER = null; + + // private static FastJavaPartitionScanner PHP_PARTITION_SCANNER = null; + + private static HTMLPartitionScanner SMARTY_PARTITION_SCANNER = null; + + // private static XMLPartitionScanner XML_PARTITION_SCANNER = null; + + // private final static String[] TYPES= new String[] { + // PHPPartitionScanner.PHP, PHPPartitionScanner.JAVA_DOC, + // PHPPartitionScanner.JAVA_MULTILINE_COMMENT }; + // private final static String[] TYPES = new String[] { + // IPHPPartitions.PHP_PARTITIONING, + // IPHPPartitions.PHP_PHPDOC_COMMENT, + // // IPHPPartitions.HTML, + // // IPHPPartitions.HTML_MULTILINE_COMMENT, + // IPHPPartitions.JAVASCRIPT, + // IPHPPartitions.CSS, + // IPHPPartitions.SMARTY, + // IPHPPartitions.SMARTY_MULTILINE_COMMENT }; + + /** + * This tools' preference listener. + */ + private class PreferenceListener implements IPropertyChangeListener, + Preferences.IPropertyChangeListener { + public void propertyChange(PropertyChangeEvent event) { + adaptToPreferenceChange(event); + } + + public void propertyChange(Preferences.PropertyChangeEvent event) { + adaptToPreferenceChange(new PropertyChangeEvent(event.getSource(), + event.getProperty(), event.getOldValue(), event + .getNewValue())); + } + }; + + // /** The color manager */ + private JavaColorManager colorManager; + + /** The PHP source code scanner */ + private PHPCodeScanner fCodeScanner; + + /** The PHP multiline comment scanner */ + private SingleTokenPHPScanner fMultilineCommentScanner; + + /** The Java singleline comment scanner */ + private SingleTokenPHPScanner fSinglelineCommentScanner; + + /** The PHP double quoted string scanner */ + // private SingleTokenPHPScanner fStringDQScanner; + /** The PHP single quoted string scanner */ + // private SingleTokenPHPScanner fStringSQScanner; + /** The PHPDoc scanner */ + private PHPDocCodeScanner fPHPDocScanner; + + /** The HTML scanner */ + // private HTMLCodeScanner fHTMLScanner; + /** The Smarty scanner */ + private SmartyCodeScanner fSmartyScanner; + + /** The SmartyDoc scanner */ + private SmartyDocCodeScanner fSmartyDocScanner; + + /** The Java partitions scanner. */ + private FastJavaPartitionScanner fPartitionScanner; + + /** The preference store */ + private IPreferenceStore fPreferenceStore; + + /** The XML Language text tools */ + private XMLTextTools xmlTextTools; + + /** + * The core preference store. + * + * @since 2.1 + */ + private Preferences fCorePreferenceStore; + + /** The preference change listener */ + private PreferenceListener fPreferenceListener = new PreferenceListener(); + + /** The JSP partitions scanner */ + private PHPPartitionScanner jspPartitionScanner = null; + + /** The JSP script subpartitions scanner */ + // private JSPScriptScanner jspScriptScanner; + /** The PHP plain text scanner */ + // private RuleBasedScanner jspTextScanner; + /** The PHP brackets scanner */ + // private RuleBasedScanner jspBracketScanner; + /** + * Creates a new Java text tools collection. + * + * @param store + * the preference store to initialize the text tools. The text + * tool instance installs a listener on the passed preference + * store to adapt itself to changes in the preference store. In + * general PreferenceConstants. + * getPreferenceStore() + * should be used to initialize the text tools. + * @param coreStore + * optional preference store to initialize the text tools. The + * text tool instance installs a listener on the passed + * preference store to adapt itself to changes in the preference + * store. + * @see net.sourceforge.phpdt.ui.PreferenceConstants#getPreferenceStore() + * @since 2.1 + */ + public JavaTextTools(IPreferenceStore store, Preferences coreStore) { + this(store, coreStore, true); + } + + /** + * Creates a new Java text tools collection. + * + * @param store + * the preference store to initialize the text tools. The text + * tool instance installs a listener on the passed preference + * store to adapt itself to changes in the preference store. In + * general PreferenceConstants. + * getPreferenceStore() + * shoould be used to initialize the text tools. + * @param coreStore + * optional preference store to initialize the text tools. The + * text tool instance installs a listener on the passed + * preference store to adapt itself to changes in the preference + * store. + * @param autoDisposeOnDisplayDispose + * if true the color manager automatically + * disposes all managed colors when the current display gets + * disposed and all calls to + * {@link org.eclipse.jface.text.source.ISharedTextColors#dispose()}are + * ignored. + * @see net.sourceforge.phpdt.ui.PreferenceConstants#getPreferenceStore() + * @since 2.1 + */ + public JavaTextTools(IPreferenceStore store, Preferences coreStore, + boolean autoDisposeOnDisplayDispose) { + // super(store, TOKENS, ); + // REVISIT: preference store + xmlTextTools = new XMLTextTools(XMLPlugin.getDefault() + .getPreferenceStore()); + + colorManager = new JavaColorManager(autoDisposeOnDisplayDispose); + fPreferenceStore = store; + fPreferenceStore.addPropertyChangeListener(fPreferenceListener); + + fCorePreferenceStore = coreStore; + if (fCorePreferenceStore != null) + fCorePreferenceStore.addPropertyChangeListener(fPreferenceListener); + + fCodeScanner = new PHPCodeScanner((JavaColorManager) colorManager, + store); + fMultilineCommentScanner = new SingleTokenPHPScanner( + (JavaColorManager) colorManager, store, + IPreferenceConstants.PHP_MULTILINE_COMMENT); + fSinglelineCommentScanner = new SingleTokenPHPScanner( + (JavaColorManager) colorManager, store, + IPreferenceConstants.PHP_SINGLELINE_COMMENT); + // fStringDQScanner = new SingleTokenPHPScanner((JavaColorManager) + // colorManager, store, IPreferenceConstants.PHP_STRING); + // fStringSQScanner = new SingleTokenPHPScanner((JavaColorManager) + // colorManager, store, IPreferenceConstants.PHP_STRING); + + fPHPDocScanner = new PHPDocCodeScanner((JavaColorManager) colorManager, + store); + // fHTMLScanner = new HTMLCodeScanner((JavaColorManager)fColorManager, + // store); + fSmartyScanner = new SmartyCodeScanner((JavaColorManager) colorManager, + store); + fSmartyDocScanner = new SmartyDocCodeScanner( + (JavaColorManager) colorManager, store); + + fPartitionScanner = new FastJavaPartitionScanner(); + + // jspScriptScanner = new JSPScriptScanner(); + // fPartitionScanner = new FastJavaPartitionScanner(); + // fPartitionScanner = new PHPPartitionScanner(); + + // jspBracketScanner = new RuleBasedScanner(); + // jspBracketScanner.setDefaultReturnToken(new + // Token(JSPScriptScanner.JSP_BRACKET)); + // jspTextScanner = new RuleBasedScanner(); + // jspTextScanner.setDefaultReturnToken(new + // Token(JSPScriptScanner.JSP_DEFAULT)); + } + + /** + * + */ + public XMLTextTools getXMLTextTools() { + return xmlTextTools; + } + + /** + * Disposes all the individual tools of this tools collection. + */ + public void dispose() { + + fCodeScanner = null; + fMultilineCommentScanner = null; + fSinglelineCommentScanner = null; + // fStringDQScanner = null; + // fStringSQScanner = null; + fPHPDocScanner = null; + // fPartitionScanner = null; + + if (colorManager != null) { + colorManager.dispose(); + colorManager = null; + } + + if (fPreferenceStore != null) { + fPreferenceStore.removePropertyChangeListener(fPreferenceListener); + fPreferenceStore = null; + + if (fCorePreferenceStore != null) { + fCorePreferenceStore + .removePropertyChangeListener(fPreferenceListener); + fCorePreferenceStore = null; + } + + fPreferenceListener = null; + } + } + + /** + * Returns the color manager which is used to manage any Java-specific + * colors needed for such things like syntax highlighting. + * + * @return the color manager to be used for Java text viewers + */ + public JavaColorManager getColorManager() { + return (JavaColorManager) colorManager; + } + + /** + * Returns a scanner which is configured to scan Java source code. + * + * @return a Java source code scanner + */ + public RuleBasedScanner getCodeScanner() { + return fCodeScanner; + } + + /** + * Returns a scanner which is configured to scan Java multiline comments. + * + * @return a Java multiline comment scanner + * + * @since 2.0 + */ + public RuleBasedScanner getMultilineCommentScanner() { + return fMultilineCommentScanner; + } + + /** + * Returns a scanner which is configured to scan HTML code. + * + * @return a HTML scanner + * + * @since 2.0 + */ + // public RuleBasedScanner getHTMLScanner() { + // return fHTMLScanner; + // } + /** + * Returns a scanner which is configured to scan Smarty code. + * + * @return a Smarty scanner + * + * @since 2.0 + */ + public RuleBasedScanner getSmartyScanner() { + return fSmartyScanner; + } + + /** + * Returns a scanner which is configured to scan Smarty code. + * + * @return a Smarty scanner + * + * @since 2.0 + */ + public RuleBasedScanner getSmartyDocScanner() { + return fSmartyDocScanner; + } + + /** + * Returns a scanner which is configured to scan Java singleline comments. + * + * @return a Java singleline comment scanner + * + * @since 2.0 + */ + public RuleBasedScanner getSinglelineCommentScanner() { + return fSinglelineCommentScanner; + } + + /** + * Returns a scanner which is configured to scan Java strings. + * + * @return a Java string scanner + * + * @since 2.0 + */ + // public RuleBasedScanner getStringScanner() { + // return fStringDQScanner; + // } + /** + * Returns a scanner which is configured to scan JavaDoc compliant comments. + * Notes that the start sequence "/**" and the corresponding end sequence + * are part of the JavaDoc comment. + * + * @return a JavaDoc scanner + */ + public RuleBasedScanner getJavaDocScanner() { + return fPHPDocScanner; + } + + /** + * Returns a scanner which is configured to scan Java-specific partitions, + * which are multi-line comments, JavaDoc comments, and regular Java source + * code. + * + * @return a Java partition scanner + */ + // public IPartitionTokenScanner getPartitionScanner() { + // return fPartitionScanner; + // } + /** + * Factory method for creating a PHP-specific document partitioner using + * this object's partitions scanner. This method is a convenience method. + * + * @return a newly created Java document partitioner + */ + public IDocumentPartitioner createDocumentPartitioner() { + return createDocumentPartitioner(".php"); + } + + /** + * Factory method for creating a PHP-specific document partitioner using + * this object's partitions scanner. This method is a convenience method. + * + * @return a newly created Java document partitioner + */ + public IDocumentPartitioner createDocumentPartitioner(String extension) { + + // String[] types = + // new String[] { + // FastJavaPartitionScanner.JAVA_DOC, + // FastJavaPartitionScanner.JAVA_MULTI_LINE_COMMENT, + // FastJavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT, + // FastJavaPartitionScanner.JAVA_STRING }; + // + // return new DefaultPartitioner(getPartitionScanner(), types); + IDocumentPartitioner partitioner = null; + // System.out.println(extension); + if (extension.equalsIgnoreCase(".html") + || extension.equalsIgnoreCase(".htm")) { + // html + partitioner = createHTMLPartitioner(); + partitioner = createJSPPartitioner(); + } else if (extension.equalsIgnoreCase(".xml")) { + // xml + partitioner = createXMLPartitioner(); + // } else if (extension.equalsIgnoreCase(".js")) { + // // javascript + // partitioner = createJavaScriptPartitioner(); + // } else if (extension.equalsIgnoreCase(".css")) { + // // cascading style sheets + // partitioner = createCSSPartitioner(); + } else if (extension.equalsIgnoreCase(".tpl")) { + // smarty ? + partitioner = createSmartyPartitioner(); + // } else if (extension.equalsIgnoreCase(".inc")) { + // // php include files ? + // partitioner = createIncludePartitioner(); + } + + if (partitioner == null) { + partitioner = createJSPPartitioner(); + } + + return partitioner; + } + + /** + * Sets up the Java document partitioner for the given document for the + * given partitioning. + * + * @param document + * the document to be set up + * @param partitioning + * the document partitioning + * @param element + * TODO + * + * @since 3.0 + */ + // public void setupJavaDocumentPartitioner(IDocument document, String + // partitioning, Object element) { + // IDocumentPartitioner partitioner = createDocumentPartitioner(".php"); + // + // // if (document instanceof IDocumentExtension3) { + // // IDocumentExtension3 extension3= (IDocumentExtension3) document; + // // extension3.setDocumentPartitioner(partitioning, partitioner); + // // } else { + // document.setDocumentPartitioner(partitioner); + // // } + // partitioner.connect(document); + // } + public void setupHTMLDocumentPartitioner(IDocument document, + String partitioning, Object element) { + IDocumentPartitioner partitioner = createDocumentPartitioner(".html"); + + // if (document instanceof IDocumentExtension3) { + // IDocumentExtension3 extension3= (IDocumentExtension3) document; + // extension3.setDocumentPartitioner(partitioning, partitioner); + // } else { + document.setDocumentPartitioner(partitioner); + // } + partitioner.connect(document); + } + + public void setupSmartyDocumentPartitioner(IDocument document, + String partitioning, Object element) { + IDocumentPartitioner partitioner = createDocumentPartitioner(".tpl"); + + // if (document instanceof IDocumentExtension3) { + // IDocumentExtension3 extension3= (IDocumentExtension3) document; + // extension3.setDocumentPartitioner(partitioning, partitioner); + // } else { + document.setDocumentPartitioner(partitioner); + // } + partitioner.connect(document); + } + + /** + * Returns the names of the document position categories used by the + * document partitioners created by this object to manage their partition + * information. If the partitioners don't use document position categories, + * the returned result is null. + * + * @return the partition managing position categories or null + * if there is none + */ + public String[] getPartitionManagingPositionCategories() { + return new String[] { DefaultPartitioner.CONTENT_TYPES_CATEGORY }; + } + + /** + * Determines whether the preference change encoded by the given event + * changes the behavior of one its contained components. + * + * @param event + * the event to be investigated + * @return true if event causes a behavioral change + * @since 2.0 + * @deprecated As of 3.0, replaced by + * {@link net.sourceforge.phpdt.ui.text.JavaSourceViewerConfiguration#affectsTextPresentation(PropertyChangeEvent)} + */ + // public boolean affectsBehavior(PropertyChangeEvent event) { + // return fCodeScanner.affectsBehavior(event) + // || fMultilineCommentScanner.affectsBehavior(event) + // || fSinglelineCommentScanner.affectsBehavior(event) + // || fStringDQScanner.affectsBehavior(event) + // || fPHPDocScanner.affectsBehavior(event); + // } + /** + * Adapts the behavior of the contained components to the change encoded in + * the given event. + * + * @param event + * the event to which to adapt + * @since 2.0 + */ + protected void adaptToPreferenceChange(PropertyChangeEvent event) { + if (fCodeScanner.affectsBehavior(event)) + fCodeScanner.adaptToPreferenceChange(event); + if (fMultilineCommentScanner.affectsBehavior(event)) + fMultilineCommentScanner.adaptToPreferenceChange(event); + if (fSinglelineCommentScanner.affectsBehavior(event)) + fSinglelineCommentScanner.adaptToPreferenceChange(event); + // if (fStringDQScanner.affectsBehavior(event)) + // fStringDQScanner.adaptToPreferenceChange(event); + if (fPHPDocScanner.affectsBehavior(event)) + fPHPDocScanner.adaptToPreferenceChange(event); + // if (fHTMLScanner.affectsBehavior(event)) + // fHTMLScanner.adaptToPreferenceChange(event); + if (fSmartyScanner.affectsBehavior(event)) + fSmartyScanner.adaptToPreferenceChange(event); + if (fSmartyDocScanner.affectsBehavior(event)) + fSmartyDocScanner.adaptToPreferenceChange(event); + // if (XMLPlugin.getDefault().getXMLTextTools().affectsBehavior(event)) + // { + // XMLPlugin.getDefault().getXMLTextTools().adaptToPreferenceChange(event); + // } + } + + /** + * Return a partitioner for .html files. + */ + public IDocumentPartitioner createHTMLPartitioner() { + // return new DefaultPartitioner(getHTMLPartitionScanner(), TYPES); + return xmlTextTools.createXMLPartitioner(); + } + + // private static IDocumentPartitioner createIncludePartitioner() { + // // return new DefaultPartitioner(getPHPPartitionScanner(), TYPES); + // return new DefaultPartitioner(getPHPPartitionScanner(), + // FastJavaPartitionScanner.PHP_PARTITION_TYPES); + // + // } + + // private static IDocumentPartitioner createJavaScriptPartitioner() { + // return new DefaultPartitioner(getHTMLPartitionScanner(), TYPES); + // } + + /** + * Return a partitioner for .php files. + */ + public IDocumentPartitioner createPHPPartitioner() { + // return new DefaultPartitioner(getPHPPartitionScanner(), TYPES); + return new DefaultPartitioner(getPHPPartitionScanner(), + LEGAL_CONTENT_TYPES); + } + + private IDocumentPartitioner createJSPPartitioner() { + return new PHPDocumentPartitioner(getJSPPartitionScanner()); + // return new JSPDocumentPartitioner(getJSPPartitionScanner(), + // jspScriptScanner); + } + + /** + * + */ + // public IPartitionTokenScanner getJSPScriptScanner() { + // return jspScriptScanner; + // } + private IDocumentPartitioner createSmartyPartitioner() { + return new DefaultPartitioner(getSmartyPartitionScanner(), + XMLTextTools.TYPES); + } + + private IDocumentPartitioner createXMLPartitioner() { + // return new DefaultPartitioner(getXMLPartitionScanner(), + // XMLTextTools.TYPES); + return xmlTextTools.createXMLPartitioner(); + } + + // private IDocumentPartitioner createCSSPartitioner() { + // return new DefaultPartitioner(getHTMLPartitionScanner(), + // XMLTextTools.TYPES); + // } + + /** + * Return a scanner for creating html partitions. + */ + // private static XMLPartitionScanner getHTMLPartitionScanner() { + // // if (HTML_PARTITION_SCANNER == null) + // // HTML_PARTITION_SCANNER = new + // HTMLPartitionScanner(IPHPPartitions.HTML_FILE); + // // return HTML_PARTITION_SCANNER;^ + // if (HTML_PARTITION_SCANNER == null) + // HTML_PARTITION_SCANNER = new XMLPartitionScanner(false); + // return HTML_PARTITION_SCANNER; + // } + /** + * Return a scanner for creating php partitions. + */ + private FastJavaPartitionScanner getPHPPartitionScanner() { + // if (PHP_PARTITION_SCANNER == null) + // PHP_PARTITION_SCANNER = new FastJavaPartitionScanner(); //new + // PHPPartitionScanner(IPHPPartitions.PHP_FILE); + // return PHP_PARTITION_SCANNER; + return fPartitionScanner; + } + + /** + * Returns a scanner which is configured to scan plain text in JSP. + * + * @return a JSP text scanner + */ + // public RuleBasedScanner getJSPTextScanner() { + // return jspTextScanner; + // } + /** + * Returns a scanner which is configured to scan plain text in JSP. + * + * @return a JSP text scanner + */ + // public RuleBasedScanner getJSPBracketScanner() { + // return jspBracketScanner; + // } + /** + * Return a scanner for creating smarty partitions. + */ + private static HTMLPartitionScanner getSmartyPartitionScanner() { + if (SMARTY_PARTITION_SCANNER == null) + SMARTY_PARTITION_SCANNER = new HTMLPartitionScanner( + IPHPPartitions.SMARTY_FILE); + return SMARTY_PARTITION_SCANNER; + } + + /** + * Return a scanner for creating xml partitions. + */ + // private static XMLPartitionScanner getXMLPartitionScanner() { + // // if (XML_PARTITION_SCANNER == null) + // // XML_PARTITION_SCANNER = new + // HTMLPartitionScanner(IPHPPartitions.XML_FILE); + // // return XML_PARTITION_SCANNER; + // if (XML_PARTITION_SCANNER == null) + // XML_PARTITION_SCANNER = new XMLPartitionScanner(false); + // return XML_PARTITION_SCANNER; + // } + private PHPPartitionScanner getJSPPartitionScanner() { + if (jspPartitionScanner == null) + jspPartitionScanner = new PHPPartitionScanner(); + return jspPartitionScanner; + } + + /** + * Sets up the Java document partitioner for the given document for the + * default partitioning. + * + * @param document + * the document to be set up + * @since 3.0 + */ + public void setupJavaDocumentPartitioner(IDocument document) { + setupJavaDocumentPartitioner(document, + IDocumentExtension3.DEFAULT_PARTITIONING); + } + + /** + * Sets up the Java document partitioner for the given document for the + * given partitioning. + * + * @param document + * the document to be set up + * @param partitioning + * the document partitioning + * @since 3.0 + */ + public void setupJavaDocumentPartitioner(IDocument document, + String partitioning) { + IDocumentPartitioner partitioner = createDocumentPartitioner(); + if (document instanceof IDocumentExtension3) { + IDocumentExtension3 extension3 = (IDocumentExtension3) document; + extension3.setDocumentPartitioner(partitioning, partitioner); + } else { + document.setDocumentPartitioner(partitioner); + } + partitioner.connect(document); + } + + /** + * Returns this text tool's preference store. + * + * @return the preference store + * @since 3.0 + */ + protected IPreferenceStore getPreferenceStore() { + return fPreferenceStore; + } + + /** + * Returns this text tool's core preference store. + * + * @return the core preference store + * @since 3.0 + */ + protected Preferences getCorePreferenceStore() { + return fCorePreferenceStore; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/PHPSourceViewerConfiguration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/PHPSourceViewerConfiguration.java index e6bfa94..f2d4ab6 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/PHPSourceViewerConfiguration.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/PHPSourceViewerConfiguration.java @@ -91,322 +91,354 @@ import org.eclipse.ui.texteditor.ITextEditor; * Configuration for an SourceViewer which shows PHP code. */ public class PHPSourceViewerConfiguration extends SourceViewerConfiguration { - /** - * Preference key used to look up display tab width. - * - * @since 2.0 - */ - public final static String PREFERENCE_TAB_WIDTH = PreferenceConstants.EDITOR_TAB_WIDTH; - - /** - * Preference key for inserting spaces rather than tabs. - * - * @since 2.0 - */ - public final static String SPACES_FOR_TABS = PreferenceConstants.EDITOR_SPACES_FOR_TABS; - - // public static final String HTML_DEFAULT = - // IPHPPartitionScannerConstants.HTML; - //IDocument.DEFAULT_CONTENT_TYPE; -// private JavaTextTools fJavaTextTools; - - private ITextEditor fTextEditor; - - /** - * The document partitioning. - * - * @since 3.0 - */ - private String fDocumentPartitioning; - - private ContentFormatter fFormatter; - - /** - * Single token scanner. - */ - static class SingleTokenScanner extends BufferedRuleBasedScanner { - public SingleTokenScanner(TextAttribute attribute) { - setDefaultReturnToken(new Token(attribute)); - } - }; - - /** - * The document partitioning. - * - * @since 3.0 - */ - // private String fDocumentPartitioning; - /** - * The Java source code scanner - * - * @since 3.0 - */ - private AbstractJavaScanner fCodeScanner; - - /** - * The Java multi-line comment scanner - * - * @since 3.0 - */ - private AbstractJavaScanner fMultilineCommentScanner; - - /** - * The Java single-line comment scanner - * - * @since 3.0 - */ - private AbstractJavaScanner fSinglelineCommentScanner; - - /** - * The PHP double quoted string scanner - */ - private AbstractJavaScanner fStringDQScanner; - /** - * The PHP single quoted string scanner - */ - private AbstractJavaScanner fStringSQScanner; - - /** - * The Javadoc scanner - * - * @since 3.0 - */ - private AbstractJavaScanner fJavaDocScanner; - - /** - * The preference store, can be read-only - * - * @since 3.0 - */ - private IPreferenceStore fPreferenceStore; - - /** - * The color manager - * - * @since 3.0 - */ - private IColorManager fColorManager; - - private XMLTextTools fXMLTextTools; - - private XMLConfiguration xmlConfiguration; - - /** - * 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. - *

                                                      - * Creates a Java source viewer configuration in the new setup without text tools. Clients are allowed to call - * {@link JavaSourceViewerConfiguration#handlePropertyChangeEvent(PropertyChangeEvent)}and disallowed to call - * {@link JavaSourceViewerConfiguration#getPreferenceStore()}on the resulting Java source viewer configuration. - *

                                                      - * - * @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 - * @param partitioning - * the document partitioning for this configuration - * @since 3.0 - */ - public PHPSourceViewerConfiguration(IColorManager colorManager, IPreferenceStore preferenceStore, ITextEditor editor, - String partitioning) { - fColorManager = colorManager; - fPreferenceStore = preferenceStore; - fTextEditor = editor; - fDocumentPartitioning = partitioning; - // fJavaTextTools = PHPeclipsePlugin.getDefault().getJavaTextTools(); - fXMLTextTools = XMLPlugin.getDefault().getXMLTextTools(); - xmlConfiguration = new XMLConfiguration(fXMLTextTools); - fColorManager = colorManager; - fPreferenceStore = preferenceStore; - fTextEditor = editor; - fDocumentPartitioning = partitioning; - - initializeScanners(); - } - - /** - * Creates a new Java source viewer configuration for viewers in the given editor using the given Java tools. - * - * @param tools - * the Java text tools to be used - * @param editor - * the editor in which the configured viewer(s) will reside - * @see JavaTextTools - * @deprecated As of 3.0, replaced by - * {@link JavaSourceViewerConfiguration#JavaSourceViewerConfiguration(IColorManager, IPreferenceStore, ITextEditor, String)} - */ - // public PHPSourceViewerConfiguration(JavaTextTools tools, PHPEditor editor, String partitioning) { - // fJavaTextTools = tools; - // fColorManager = tools.getColorManager(); - // fPreferenceStore = createPreferenceStore(); - // fDocumentPartitioning = partitioning; - // fCodeScanner = (AbstractJavaScanner) fJavaTextTools.getCodeScanner(); - // fMultilineCommentScanner = (AbstractJavaScanner) fJavaTextTools.getMultilineCommentScanner(); - // fSinglelineCommentScanner = (AbstractJavaScanner) fJavaTextTools.getSinglelineCommentScanner(); - // fStringDQScanner = (AbstractJavaScanner) fJavaTextTools.getStringScanner(); - // fJavaDocScanner = (AbstractJavaScanner) fJavaTextTools.getJavaDocScanner(); - // fTextEditor = editor; - // fXMLTextTools = XMLPlugin.getDefault().getXMLTextTools(); - // xmlConfiguration = new XMLConfiguration(fXMLTextTools); - // } - /** - * Returns the color manager for this configuration. - * - * @return the color manager - */ - protected IColorManager getColorManager() { - return fColorManager; - } - - /** - * Initializes the scanners. - * - * @since 3.0 - */ - private void initializeScanners() { -// Assert.isTrue(isNewSetup()); - fCodeScanner = new PHPCodeScanner(getColorManager(), fPreferenceStore); - fMultilineCommentScanner = new SingleTokenPHPScanner(getColorManager(), fPreferenceStore, - IPreferenceConstants.PHP_MULTILINE_COMMENT); - fSinglelineCommentScanner = new SingleTokenPHPScanner(getColorManager(), fPreferenceStore, - IPreferenceConstants.PHP_SINGLELINE_COMMENT); -// fStringDQScanner = new SingleTokenPHPScanner(getColorManager(), fPreferenceStore, IPreferenceConstants.PHP_STRING_DQ); - fStringDQScanner = new PHPStringDQCodeScanner(getColorManager(), fPreferenceStore); - fStringSQScanner = new SingleTokenPHPScanner(getColorManager(), fPreferenceStore, IPreferenceConstants.PHP_STRING_SQ); - fJavaDocScanner = new PHPDocCodeScanner(getColorManager(), fPreferenceStore); - } - - /** - * Determines whether the preference change encoded by the given event changes the behavior of one of its contained components. - * - * @param event - * the event to be investigated - * @return true if event causes a behavioral change - * @since 3.0 - */ - public boolean affectsTextPresentation(PropertyChangeEvent event) { - return fCodeScanner.affectsBehavior(event) || fMultilineCommentScanner.affectsBehavior(event) - || fSinglelineCommentScanner.affectsBehavior(event) || fStringDQScanner.affectsBehavior(event)|| fStringSQScanner.affectsBehavior(event) - || fJavaDocScanner.affectsBehavior(event); - } - - /** - * Adapts the behavior of the contained components to the change encoded in the given event. - *

                                                      - * Clients are not allowed to call this method if the old setup with text tools is in use. - *

                                                      - * - * @param event - * the event to which to adapt - * @see JavaSourceViewerConfiguration#JavaSourceViewerConfiguration(IColorManager, IPreferenceStore, ITextEditor, String) - * @since 3.0 - */ - public void handlePropertyChangeEvent(PropertyChangeEvent event) { -// Assert.isTrue(isNewSetup()); - if (fCodeScanner.affectsBehavior(event)) - fCodeScanner.adaptToPreferenceChange(event); - if (fMultilineCommentScanner.affectsBehavior(event)) - fMultilineCommentScanner.adaptToPreferenceChange(event); - if (fSinglelineCommentScanner.affectsBehavior(event)) - fSinglelineCommentScanner.adaptToPreferenceChange(event); - if (fStringDQScanner.affectsBehavior(event)) - fStringDQScanner.adaptToPreferenceChange(event); - if (fStringSQScanner.affectsBehavior(event)) - fStringSQScanner.adaptToPreferenceChange(event); - if (fJavaDocScanner.affectsBehavior(event)) - fJavaDocScanner.adaptToPreferenceChange(event); - } - - /* - * @see SourceViewerConfiguration#getContentFormatter(ISourceViewer) - */ - public IContentFormatter getContentFormatter(ISourceViewer sourceViewer) { - // if (fFormatter == null) { - // fFormatter = new ContentFormatter(); - // fFormattingStrategy = new HTMLFormattingStrategy(this, - // sourceViewer); - // fFormatter.setFormattingStrategy(fFormattingStrategy, HTML_DEFAULT); - // fFormatter.enablePartitionAwareFormatting(false); - // fFormatter.setPartitionManagingPositionCategories(getConfiguredContentTypes(null)); - // } - // return fFormatter; - if (fFormatter == null) { - //ContentFormatter - fFormatter = new ContentFormatter(); - IFormattingStrategy strategy = new JavaFormattingStrategy(sourceViewer); - fFormatter.setFormattingStrategy(strategy, IDocument.DEFAULT_CONTENT_TYPE); - fFormatter.enablePartitionAwareFormatting(false); - fFormatter.setPartitionManagingPositionCategories(getPartitionManagingPositionCategories()); - } - return fFormatter; - } - - /** - * Returns the names of the document position categories used by the document partitioners created by this object to manage their - * partition information. If the partitioners don't use document position categories, the returned result is null. - * - * @return the partition managing position categories or null if there is none - */ - public String[] getPartitionManagingPositionCategories() { - return new String[] { DefaultPartitioner.CONTENT_TYPES_CATEGORY }; - } - - // /** - // * Returns the names of the document position categories used by the - // document - // * partitioners created by this object to manage their partition - // information. - // * If the partitioners don't use document position categories, the - // returned - // * result is null. - // * - // * @return the partition managing position categories or - // null - // * if there is none - // */ - // private String[] getPartitionManagingPositionCategories() { - // return new String[] { DefaultPartitioner.CONTENT_TYPES_CATEGORY }; - // } - public ITextEditor getEditor() { - return fTextEditor; - } - - /** - * Returns the preference store used by this configuration to initialize the individual bits and pieces. - * - * @return the preference store used to initialize this configuration - * - * @since 2.0 - */ - protected IPreferenceStore getPreferenceStore() { - return PHPeclipsePlugin.getDefault().getPreferenceStore(); - } - - // /* (non-Javadoc) - // * Method declared on SourceViewerConfiguration - // */ - // public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) { - // return new PHPAnnotationHover(); - // } - /* - * @see SourceViewerConfiguration#getAnnotationHover(ISourceViewer) - */ - public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) { - return new JavaAnnotationHover(JavaAnnotationHover.VERTICAL_RULER_HOVER); - } - - /* - * @see SourceViewerConfiguration#getOverviewRulerAnnotationHover(ISourceViewer) - * @since 3.0 - */ - public IAnnotationHover getOverviewRulerAnnotationHover(ISourceViewer sourceViewer) { - return new JavaAnnotationHover(JavaAnnotationHover.OVERVIEW_RULER_HOVER); - } - - public IAutoEditStrategy[] getAutoEditStrategies( + /** + * Preference key used to look up display tab width. + * + * @since 2.0 + */ + public final static String PREFERENCE_TAB_WIDTH = PreferenceConstants.EDITOR_TAB_WIDTH; + + /** + * Preference key for inserting spaces rather than tabs. + * + * @since 2.0 + */ + public final static String SPACES_FOR_TABS = PreferenceConstants.EDITOR_SPACES_FOR_TABS; + + // public static final String HTML_DEFAULT = + // IPHPPartitionScannerConstants.HTML; + // IDocument.DEFAULT_CONTENT_TYPE; + // private JavaTextTools fJavaTextTools; + + private ITextEditor fTextEditor; + + /** + * The document partitioning. + * + * @since 3.0 + */ + private String fDocumentPartitioning; + + private ContentFormatter fFormatter; + + /** + * Single token scanner. + */ + static class SingleTokenScanner extends BufferedRuleBasedScanner { + public SingleTokenScanner(TextAttribute attribute) { + setDefaultReturnToken(new Token(attribute)); + } + }; + + /** + * The document partitioning. + * + * @since 3.0 + */ + // private String fDocumentPartitioning; + /** + * The Java source code scanner + * + * @since 3.0 + */ + private AbstractJavaScanner fCodeScanner; + + /** + * The Java multi-line comment scanner + * + * @since 3.0 + */ + private AbstractJavaScanner fMultilineCommentScanner; + + /** + * The Java single-line comment scanner + * + * @since 3.0 + */ + private AbstractJavaScanner fSinglelineCommentScanner; + + /** + * The PHP double quoted string scanner + */ + private AbstractJavaScanner fStringDQScanner; + + /** + * The PHP single quoted string scanner + */ + private AbstractJavaScanner fStringSQScanner; + + /** + * The Javadoc scanner + * + * @since 3.0 + */ + private AbstractJavaScanner fJavaDocScanner; + + /** + * The preference store, can be read-only + * + * @since 3.0 + */ + private IPreferenceStore fPreferenceStore; + + /** + * The color manager + * + * @since 3.0 + */ + private IColorManager fColorManager; + + private XMLTextTools fXMLTextTools; + + private XMLConfiguration xmlConfiguration; + + /** + * 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. + *

                                                      + * Creates a Java source viewer configuration in the new setup without text + * tools. Clients are allowed to call + * {@link JavaSourceViewerConfiguration#handlePropertyChangeEvent(PropertyChangeEvent)}and + * disallowed to call + * {@link JavaSourceViewerConfiguration#getPreferenceStore()}on the + * resulting Java source viewer configuration. + *

                                                      + * + * @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 + * @param partitioning + * the document partitioning for this configuration + * @since 3.0 + */ + public PHPSourceViewerConfiguration(IColorManager colorManager, + IPreferenceStore preferenceStore, ITextEditor editor, + String partitioning) { + fColorManager = colorManager; + fPreferenceStore = preferenceStore; + fTextEditor = editor; + fDocumentPartitioning = partitioning; + // fJavaTextTools = PHPeclipsePlugin.getDefault().getJavaTextTools(); + fXMLTextTools = XMLPlugin.getDefault().getXMLTextTools(); + xmlConfiguration = new XMLConfiguration(fXMLTextTools); + fColorManager = colorManager; + fPreferenceStore = preferenceStore; + fTextEditor = editor; + fDocumentPartitioning = partitioning; + + initializeScanners(); + } + + /** + * Creates a new Java source viewer configuration for viewers in the given + * editor using the given Java tools. + * + * @param tools + * the Java text tools to be used + * @param editor + * the editor in which the configured viewer(s) will reside + * @see JavaTextTools + * @deprecated As of 3.0, replaced by + * {@link JavaSourceViewerConfiguration#JavaSourceViewerConfiguration(IColorManager, IPreferenceStore, ITextEditor, String)} + */ + // public PHPSourceViewerConfiguration(JavaTextTools tools, PHPEditor + // editor, String partitioning) { + // fJavaTextTools = tools; + // fColorManager = tools.getColorManager(); + // fPreferenceStore = createPreferenceStore(); + // fDocumentPartitioning = partitioning; + // fCodeScanner = (AbstractJavaScanner) fJavaTextTools.getCodeScanner(); + // fMultilineCommentScanner = (AbstractJavaScanner) + // fJavaTextTools.getMultilineCommentScanner(); + // fSinglelineCommentScanner = (AbstractJavaScanner) + // fJavaTextTools.getSinglelineCommentScanner(); + // fStringDQScanner = (AbstractJavaScanner) + // fJavaTextTools.getStringScanner(); + // fJavaDocScanner = (AbstractJavaScanner) + // fJavaTextTools.getJavaDocScanner(); + // fTextEditor = editor; + // fXMLTextTools = XMLPlugin.getDefault().getXMLTextTools(); + // xmlConfiguration = new XMLConfiguration(fXMLTextTools); + // } + /** + * Returns the color manager for this configuration. + * + * @return the color manager + */ + protected IColorManager getColorManager() { + return fColorManager; + } + + /** + * Initializes the scanners. + * + * @since 3.0 + */ + private void initializeScanners() { + // Assert.isTrue(isNewSetup()); + fCodeScanner = new PHPCodeScanner(getColorManager(), fPreferenceStore); + fMultilineCommentScanner = new SingleTokenPHPScanner(getColorManager(), + fPreferenceStore, IPreferenceConstants.PHP_MULTILINE_COMMENT); + fSinglelineCommentScanner = new SingleTokenPHPScanner( + getColorManager(), fPreferenceStore, + IPreferenceConstants.PHP_SINGLELINE_COMMENT); + // fStringDQScanner = new SingleTokenPHPScanner(getColorManager(), + // fPreferenceStore, IPreferenceConstants.PHP_STRING_DQ); + fStringDQScanner = new PHPStringDQCodeScanner(getColorManager(), + fPreferenceStore); + fStringSQScanner = new SingleTokenPHPScanner(getColorManager(), + fPreferenceStore, IPreferenceConstants.PHP_STRING_SQ); + fJavaDocScanner = new PHPDocCodeScanner(getColorManager(), + fPreferenceStore); + } + + /** + * Determines whether the preference change encoded by the given event + * changes the behavior of one of its contained components. + * + * @param event + * the event to be investigated + * @return true if event causes a behavioral change + * @since 3.0 + */ + public boolean affectsTextPresentation(PropertyChangeEvent event) { + return fCodeScanner.affectsBehavior(event) + || fMultilineCommentScanner.affectsBehavior(event) + || fSinglelineCommentScanner.affectsBehavior(event) + || fStringDQScanner.affectsBehavior(event) + || fStringSQScanner.affectsBehavior(event) + || fJavaDocScanner.affectsBehavior(event); + } + + /** + * Adapts the behavior of the contained components to the change encoded in + * the given event. + *

                                                      + * Clients are not allowed to call this method if the old setup with text + * tools is in use. + *

                                                      + * + * @param event + * the event to which to adapt + * @see JavaSourceViewerConfiguration#JavaSourceViewerConfiguration(IColorManager, + * IPreferenceStore, ITextEditor, String) + * @since 3.0 + */ + public void handlePropertyChangeEvent(PropertyChangeEvent event) { + // Assert.isTrue(isNewSetup()); + if (fCodeScanner.affectsBehavior(event)) + fCodeScanner.adaptToPreferenceChange(event); + if (fMultilineCommentScanner.affectsBehavior(event)) + fMultilineCommentScanner.adaptToPreferenceChange(event); + if (fSinglelineCommentScanner.affectsBehavior(event)) + fSinglelineCommentScanner.adaptToPreferenceChange(event); + if (fStringDQScanner.affectsBehavior(event)) + fStringDQScanner.adaptToPreferenceChange(event); + if (fStringSQScanner.affectsBehavior(event)) + fStringSQScanner.adaptToPreferenceChange(event); + if (fJavaDocScanner.affectsBehavior(event)) + fJavaDocScanner.adaptToPreferenceChange(event); + } + + /* + * @see SourceViewerConfiguration#getContentFormatter(ISourceViewer) + */ + public IContentFormatter getContentFormatter(ISourceViewer sourceViewer) { + // if (fFormatter == null) { + // fFormatter = new ContentFormatter(); + // fFormattingStrategy = new HTMLFormattingStrategy(this, + // sourceViewer); + // fFormatter.setFormattingStrategy(fFormattingStrategy, HTML_DEFAULT); + // fFormatter.enablePartitionAwareFormatting(false); + // fFormatter.setPartitionManagingPositionCategories(getConfiguredContentTypes(null)); + // } + // return fFormatter; + if (fFormatter == null) { + // ContentFormatter + fFormatter = new ContentFormatter(); + IFormattingStrategy strategy = new JavaFormattingStrategy( + sourceViewer); + fFormatter.setFormattingStrategy(strategy, + IDocument.DEFAULT_CONTENT_TYPE); + fFormatter.enablePartitionAwareFormatting(false); + fFormatter + .setPartitionManagingPositionCategories(getPartitionManagingPositionCategories()); + } + return fFormatter; + } + + /** + * Returns the names of the document position categories used by the + * document partitioners created by this object to manage their partition + * information. If the partitioners don't use document position categories, + * the returned result is null. + * + * @return the partition managing position categories or null + * if there is none + */ + public String[] getPartitionManagingPositionCategories() { + return new String[] { DefaultPartitioner.CONTENT_TYPES_CATEGORY }; + } + + // /** + // * Returns the names of the document position categories used by the + // document + // * partitioners created by this object to manage their partition + // information. + // * If the partitioners don't use document position categories, the + // returned + // * result is null. + // * + // * @return the partition managing position categories or + // null + // * if there is none + // */ + // private String[] getPartitionManagingPositionCategories() { + // return new String[] { DefaultPartitioner.CONTENT_TYPES_CATEGORY }; + // } + public ITextEditor getEditor() { + return fTextEditor; + } + + /** + * Returns the preference store used by this configuration to initialize the + * individual bits and pieces. + * + * @return the preference store used to initialize this configuration + * + * @since 2.0 + */ + protected IPreferenceStore getPreferenceStore() { + return PHPeclipsePlugin.getDefault().getPreferenceStore(); + } + + // /* (non-Javadoc) + // * Method declared on SourceViewerConfiguration + // */ + // public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) { + // return new PHPAnnotationHover(); + // } + /* + * @see SourceViewerConfiguration#getAnnotationHover(ISourceViewer) + */ + public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) { + return new JavaAnnotationHover(JavaAnnotationHover.VERTICAL_RULER_HOVER); + } + + /* + * @see SourceViewerConfiguration#getOverviewRulerAnnotationHover(ISourceViewer) + * @since 3.0 + */ + public IAnnotationHover getOverviewRulerAnnotationHover( + ISourceViewer sourceViewer) { + return new JavaAnnotationHover(JavaAnnotationHover.OVERVIEW_RULER_HOVER); + } + + public IAutoEditStrategy[] getAutoEditStrategies( ISourceViewer sourceViewer, String contentType) { IAutoEditStrategy strategy = new DefaultIndentLineAutoEditStrategy(); if (IPHPPartitions.PHP_PHPDOC_COMMENT.equals(contentType) @@ -434,581 +466,679 @@ public class PHPSourceViewerConfiguration extends SourceViewerConfiguration { return result; } - /** - * Returns the PHP source code scanner for this configuration. - * - * @return the PHP source code scanner - */ - protected RuleBasedScanner getCodeScanner() { - return fCodeScanner; //fJavaTextTools.getCodeScanner(); - } - - /** - * Returns the Java multi-line comment scanner for this configuration. - * - * @return the Java multi-line comment scanner - * @since 2.0 - */ - protected RuleBasedScanner getMultilineCommentScanner() { - return fMultilineCommentScanner; - } - - /** - * Returns the Java single-line comment scanner for this configuration. - * - * @return the Java single-line comment scanner - * @since 2.0 - */ - protected RuleBasedScanner getSinglelineCommentScanner() { - return fSinglelineCommentScanner; - } - - /** - * Returns the PHP double quoted string scanner for this configuration. - * - * @return the PHP double quoted string scanner - */ - protected RuleBasedScanner getStringDQScanner() { - return fStringDQScanner; - } - - /** - * Returns the PHP single quoted string scanner for this configuration. - * - * @return the PHP single quoted string scanner - */ - protected RuleBasedScanner getStringSQScanner() { - return fStringSQScanner; - } - /** - * Returns the HTML source code scanner for this configuration. - * - * @return the HTML source code scanner - */ - // protected RuleBasedScanner getHTMLScanner() { - // return fJavaTextTools.getHTMLScanner(); - // } - /** - * Returns the Smarty source code scanner for this configuration. - * - * @return the Smarty source code scanner - */ - // protected RuleBasedScanner getSmartyScanner() { - // return fJavaTextTools.getSmartyScanner(); - // } - /* - * @see SourceViewerConfiguration#getReconciler(ISourceViewer) - */ - /* - * @see SourceViewerConfiguration#getReconciler(ISourceViewer) - */ - public IReconciler getReconciler(ISourceViewer sourceViewer) { - - final ITextEditor editor = getEditor(); - if (editor != null && editor.isEditable()) { - - JavaCompositeReconcilingStrategy strategy = new JavaCompositeReconcilingStrategy(editor, - getConfiguredDocumentPartitioning(sourceViewer)); - JavaReconciler reconciler = new JavaReconciler(editor, strategy, false); - reconciler.setIsIncrementalReconciler(false); - reconciler.setProgressMonitor(new NullProgressMonitor()); - reconciler.setDelay(500); - - return reconciler; - } - return null; - } - - /* - * @see SourceViewerConfiguration#getConfiguredTextHoverStateMasks(ISourceViewer, String) - * @since 2.1 - */ - public int[] getConfiguredTextHoverStateMasks(ISourceViewer sourceViewer, String contentType) { - JavaEditorTextHoverDescriptor[] hoverDescs = PHPeclipsePlugin.getDefault().getJavaEditorTextHoverDescriptors(); - int stateMasks[] = new int[hoverDescs.length]; - int stateMasksLength = 0; - for (int i = 0; i < hoverDescs.length; i++) { - if (hoverDescs[i].isEnabled()) { - int j = 0; - int stateMask = hoverDescs[i].getStateMask(); - while (j < stateMasksLength) { - if (stateMasks[j] == stateMask) - break; - j++; + /** + * Returns the PHP source code scanner for this configuration. + * + * @return the PHP source code scanner + */ + protected RuleBasedScanner getCodeScanner() { + return fCodeScanner; // fJavaTextTools.getCodeScanner(); + } + + /** + * Returns the Java multi-line comment scanner for this configuration. + * + * @return the Java multi-line comment scanner + * @since 2.0 + */ + protected RuleBasedScanner getMultilineCommentScanner() { + return fMultilineCommentScanner; + } + + /** + * Returns the Java single-line comment scanner for this configuration. + * + * @return the Java single-line comment scanner + * @since 2.0 + */ + protected RuleBasedScanner getSinglelineCommentScanner() { + return fSinglelineCommentScanner; + } + + /** + * Returns the PHP double quoted string scanner for this configuration. + * + * @return the PHP double quoted string scanner + */ + protected RuleBasedScanner getStringDQScanner() { + return fStringDQScanner; + } + + /** + * Returns the PHP single quoted string scanner for this configuration. + * + * @return the PHP single quoted string scanner + */ + protected RuleBasedScanner getStringSQScanner() { + return fStringSQScanner; + } + + /** + * Returns the HTML source code scanner for this configuration. + * + * @return the HTML source code scanner + */ + // protected RuleBasedScanner getHTMLScanner() { + // return fJavaTextTools.getHTMLScanner(); + // } + /** + * Returns the Smarty source code scanner for this configuration. + * + * @return the Smarty source code scanner + */ + // protected RuleBasedScanner getSmartyScanner() { + // return fJavaTextTools.getSmartyScanner(); + // } + /* + * @see SourceViewerConfiguration#getReconciler(ISourceViewer) + */ + /* + * @see SourceViewerConfiguration#getReconciler(ISourceViewer) + */ + public IReconciler getReconciler(ISourceViewer sourceViewer) { + + final ITextEditor editor = getEditor(); + if (editor != null && editor.isEditable()) { + + JavaCompositeReconcilingStrategy strategy = new JavaCompositeReconcilingStrategy( + editor, getConfiguredDocumentPartitioning(sourceViewer)); + JavaReconciler reconciler = new JavaReconciler(editor, strategy, + false); + reconciler.setIsIncrementalReconciler(false); + reconciler.setProgressMonitor(new NullProgressMonitor()); + reconciler.setDelay(500); + + return reconciler; + } + return null; + } + + /* + * @see SourceViewerConfiguration#getConfiguredTextHoverStateMasks(ISourceViewer, + * String) + * @since 2.1 + */ + public int[] getConfiguredTextHoverStateMasks(ISourceViewer sourceViewer, + String contentType) { + JavaEditorTextHoverDescriptor[] hoverDescs = PHPeclipsePlugin + .getDefault().getJavaEditorTextHoverDescriptors(); + int stateMasks[] = new int[hoverDescs.length]; + int stateMasksLength = 0; + for (int i = 0; i < hoverDescs.length; i++) { + if (hoverDescs[i].isEnabled()) { + int j = 0; + int stateMask = hoverDescs[i].getStateMask(); + while (j < stateMasksLength) { + if (stateMasks[j] == stateMask) + break; + j++; + } + if (j == stateMasksLength) + stateMasks[stateMasksLength++] = stateMask; + } + } + if (stateMasksLength == hoverDescs.length) + return stateMasks; + int[] shortenedStateMasks = new int[stateMasksLength]; + System.arraycopy(stateMasks, 0, shortenedStateMasks, 0, + stateMasksLength); + return shortenedStateMasks; + } + + /* + * @see SourceViewerConfiguration#getTextHover(ISourceViewer, String, int) + * @since 2.1 + */ + public ITextHover getTextHover(ISourceViewer sourceViewer, + String contentType, int stateMask) { + JavaEditorTextHoverDescriptor[] hoverDescs = PHPeclipsePlugin + .getDefault().getJavaEditorTextHoverDescriptors(); + int i = 0; + while (i < hoverDescs.length) { + if (hoverDescs[i].isEnabled() + && hoverDescs[i].getStateMask() == stateMask) + return new JavaEditorTextHoverProxy(hoverDescs[i], getEditor()); + i++; + } + return null; + // if (fEditor != null) { + // IEditorInput editorInput = fEditor.getEditorInput(); + // if (editorInput instanceof IFileEditorInput) { + // try { + // IFile f = ((IFileEditorInput) editorInput).getFile(); + // return new PHPTextHover(f.getProject()); + // } catch (NullPointerException e) { + // // this exception occurs, if getTextHover is called by + // // preference pages ! + // } + // } + // } + // return new PHPTextHover(null); + } + + /* + * @see SourceViewerConfiguration#getTextHover(ISourceViewer, String) + */ + public ITextHover getTextHover(ISourceViewer sourceViewer, + String contentType) { + return getTextHover(sourceViewer, contentType, + ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK); + } + + /** + * Returns the SmartyDoc source code scanner for this configuration. + * + * @return the SmartyDoc source code scanner + */ + // protected RuleBasedScanner getSmartyDocScanner() { + // return fJavaTextTools.getSmartyDocScanner(); + // } + /** + * Returns the PHPDoc source code scanner for this configuration. + * + * @return the PHPDoc source code scanner + */ + protected RuleBasedScanner getPHPDocScanner() { + return fJavaDocScanner; // fJavaTextTools.getJavaDocScanner(); + } + + /* + * (non-Javadoc) Method declared on SourceViewerConfiguration + */ + public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) { + return new String[] { IDocument.DEFAULT_CONTENT_TYPE, + PHPPartitionScanner.PHP_SCRIPTING_AREA, + + IPHPPartitions.HTML, IPHPPartitions.HTML_MULTILINE_COMMENT, + IPHPPartitions.PHP_PARTITIONING, + IPHPPartitions.PHP_SINGLELINE_COMMENT, + IPHPPartitions.PHP_MULTILINE_COMMENT, + IPHPPartitions.PHP_PHPDOC_COMMENT, + IPHPPartitions.PHP_STRING_DQ, IPHPPartitions.PHP_STRING_SQ, + IPHPPartitions.PHP_STRING_HEREDOC, IPHPPartitions.CSS, + IPHPPartitions.CSS_MULTILINE_COMMENT, + IPHPPartitions.JAVASCRIPT, IPHPPartitions.JS_MULTILINE_COMMENT, + IPHPPartitions.SMARTY, IPHPPartitions.SMARTY_MULTILINE_COMMENT, + + XMLPartitionScanner.XML_PI, XMLPartitionScanner.XML_COMMENT, + XMLPartitionScanner.XML_DECL, XMLPartitionScanner.XML_TAG, + XMLPartitionScanner.XML_ATTRIBUTE, + XMLPartitionScanner.XML_CDATA, + + XMLPartitionScanner.DTD_INTERNAL, + XMLPartitionScanner.DTD_INTERNAL_PI, + XMLPartitionScanner.DTD_INTERNAL_COMMENT, + XMLPartitionScanner.DTD_INTERNAL_DECL, + + PHPDocumentPartitioner.PHP_TEMPLATE_DATA, + PHPDocumentPartitioner.PHP_SCRIPT_CODE }; + } + + public String[] getConfiguredHTMLContentTypes() { + return new String[] { XMLPartitionScanner.XML_PI, + XMLPartitionScanner.XML_COMMENT, XMLPartitionScanner.XML_DECL, + XMLPartitionScanner.XML_TAG, XMLPartitionScanner.XML_ATTRIBUTE, + XMLPartitionScanner.XML_CDATA, + + XMLPartitionScanner.DTD_INTERNAL, + XMLPartitionScanner.DTD_INTERNAL_PI, + XMLPartitionScanner.DTD_INTERNAL_COMMENT, + XMLPartitionScanner.DTD_INTERNAL_DECL, }; + } + + public String[] getConfiguredPHPContentTypes() { + return new String[] { IDocument.DEFAULT_CONTENT_TYPE, + IPHPPartitions.PHP_PARTITIONING, + IPHPPartitions.PHP_SINGLELINE_COMMENT, + IPHPPartitions.PHP_MULTILINE_COMMENT, + IPHPPartitions.PHP_PHPDOC_COMMENT, + IPHPPartitions.PHP_STRING_DQ, IPHPPartitions.PHP_STRING_SQ, + IPHPPartitions.PHP_STRING_HEREDOC, IPHPPartitions.CSS, + IPHPPartitions.CSS_MULTILINE_COMMENT, + IPHPPartitions.JAVASCRIPT, IPHPPartitions.JS_MULTILINE_COMMENT, + IPHPPartitions.SMARTY, IPHPPartitions.SMARTY_MULTILINE_COMMENT, }; + } + + /* + * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getConfiguredDocumentPartitioning(org.eclipse.jface.text.source.ISourceViewer) + * @since 3.0 + */ + public String getConfiguredDocumentPartitioning(ISourceViewer sourceViewer) { + if (fDocumentPartitioning != null) + return fDocumentPartitioning; + return super.getConfiguredDocumentPartitioning(sourceViewer); + } + + /* + * (non-Javadoc) Method declared on SourceViewerConfiguration + */ + public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { + ContentAssistant assistant = new ContentAssistant(); + IContentAssistProcessor processor = new HTMLCompletionProcessor( + getEditor()); + assistant + .setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); + assistant.setContentAssistProcessor(processor, IPHPPartitions.HTML); + assistant.setContentAssistProcessor(processor, + IPHPPartitions.HTML_MULTILINE_COMMENT); + + assistant.setContentAssistProcessor(processor, IPHPPartitions.CSS); + assistant.setContentAssistProcessor(processor, + IPHPPartitions.CSS_MULTILINE_COMMENT); + assistant.setContentAssistProcessor(processor, + IPHPPartitions.JAVASCRIPT); + assistant.setContentAssistProcessor(processor, + IPHPPartitions.JS_MULTILINE_COMMENT); + // TODO define special smarty partition content assist + assistant.setContentAssistProcessor(processor, IPHPPartitions.SMARTY); + assistant.setContentAssistProcessor(processor, + IPHPPartitions.SMARTY_MULTILINE_COMMENT); + + assistant.setContentAssistProcessor(processor, + PHPDocumentPartitioner.PHP_TEMPLATE_DATA); + String[] htmlTypes = getConfiguredHTMLContentTypes(); + for (int i = 0; i < htmlTypes.length; i++) { + assistant.setContentAssistProcessor(processor, htmlTypes[i]); } - if (j == stateMasksLength) - stateMasks[stateMasksLength++] = stateMask; - } - } - if (stateMasksLength == hoverDescs.length) - return stateMasks; - int[] shortenedStateMasks = new int[stateMasksLength]; - System.arraycopy(stateMasks, 0, shortenedStateMasks, 0, stateMasksLength); - return shortenedStateMasks; - } - - /* - * @see SourceViewerConfiguration#getTextHover(ISourceViewer, String, int) - * @since 2.1 - */ - public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType, int stateMask) { - JavaEditorTextHoverDescriptor[] hoverDescs = PHPeclipsePlugin.getDefault().getJavaEditorTextHoverDescriptors(); - int i = 0; - while (i < hoverDescs.length) { - if (hoverDescs[i].isEnabled() && hoverDescs[i].getStateMask() == stateMask) - return new JavaEditorTextHoverProxy(hoverDescs[i], getEditor()); - i++; - } - return null; - // if (fEditor != null) { - // IEditorInput editorInput = fEditor.getEditorInput(); - // if (editorInput instanceof IFileEditorInput) { - // try { - // IFile f = ((IFileEditorInput) editorInput).getFile(); - // return new PHPTextHover(f.getProject()); - // } catch (NullPointerException e) { - // // this exception occurs, if getTextHover is called by - // // preference pages ! - // } - // } - // } - // return new PHPTextHover(null); - } - - /* - * @see SourceViewerConfiguration#getTextHover(ISourceViewer, String) - */ - public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) { - return getTextHover(sourceViewer, contentType, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK); - } - - /** - * Returns the SmartyDoc source code scanner for this configuration. - * - * @return the SmartyDoc source code scanner - */ - // protected RuleBasedScanner getSmartyDocScanner() { - // return fJavaTextTools.getSmartyDocScanner(); - // } - /** - * Returns the PHPDoc source code scanner for this configuration. - * - * @return the PHPDoc source code scanner - */ - protected RuleBasedScanner getPHPDocScanner() { - return fJavaDocScanner; //fJavaTextTools.getJavaDocScanner(); - } - - /* - * (non-Javadoc) Method declared on SourceViewerConfiguration - */ - public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) { - return new String[] { IDocument.DEFAULT_CONTENT_TYPE, PHPPartitionScanner.PHP_SCRIPTING_AREA, - - IPHPPartitions.HTML, IPHPPartitions.HTML_MULTILINE_COMMENT, IPHPPartitions.PHP_PARTITIONING, - IPHPPartitions.PHP_SINGLELINE_COMMENT, IPHPPartitions.PHP_MULTILINE_COMMENT, IPHPPartitions.PHP_PHPDOC_COMMENT, - IPHPPartitions.PHP_STRING_DQ, IPHPPartitions.PHP_STRING_SQ, IPHPPartitions.PHP_STRING_HEREDOC, IPHPPartitions.CSS, IPHPPartitions.CSS_MULTILINE_COMMENT, - IPHPPartitions.JAVASCRIPT, IPHPPartitions.JS_MULTILINE_COMMENT, IPHPPartitions.SMARTY, - IPHPPartitions.SMARTY_MULTILINE_COMMENT, - - XMLPartitionScanner.XML_PI, XMLPartitionScanner.XML_COMMENT, XMLPartitionScanner.XML_DECL, XMLPartitionScanner.XML_TAG, - XMLPartitionScanner.XML_ATTRIBUTE, XMLPartitionScanner.XML_CDATA, - - XMLPartitionScanner.DTD_INTERNAL, XMLPartitionScanner.DTD_INTERNAL_PI, XMLPartitionScanner.DTD_INTERNAL_COMMENT, - XMLPartitionScanner.DTD_INTERNAL_DECL, - - PHPDocumentPartitioner.PHP_TEMPLATE_DATA, PHPDocumentPartitioner.PHP_SCRIPT_CODE }; - } - - public String[] getConfiguredHTMLContentTypes() { - return new String[] { XMLPartitionScanner.XML_PI, XMLPartitionScanner.XML_COMMENT, XMLPartitionScanner.XML_DECL, - XMLPartitionScanner.XML_TAG, XMLPartitionScanner.XML_ATTRIBUTE, XMLPartitionScanner.XML_CDATA, - - XMLPartitionScanner.DTD_INTERNAL, XMLPartitionScanner.DTD_INTERNAL_PI, XMLPartitionScanner.DTD_INTERNAL_COMMENT, - XMLPartitionScanner.DTD_INTERNAL_DECL, }; - } - - public String[] getConfiguredPHPContentTypes() { - return new String[] { IDocument.DEFAULT_CONTENT_TYPE, IPHPPartitions.PHP_PARTITIONING, IPHPPartitions.PHP_SINGLELINE_COMMENT, - IPHPPartitions.PHP_MULTILINE_COMMENT, IPHPPartitions.PHP_PHPDOC_COMMENT, IPHPPartitions.PHP_STRING_DQ, - IPHPPartitions.PHP_STRING_SQ, IPHPPartitions.PHP_STRING_HEREDOC, IPHPPartitions.CSS, IPHPPartitions.CSS_MULTILINE_COMMENT, IPHPPartitions.JAVASCRIPT, - IPHPPartitions.JS_MULTILINE_COMMENT, IPHPPartitions.SMARTY, IPHPPartitions.SMARTY_MULTILINE_COMMENT, }; - } - - /* - * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getConfiguredDocumentPartitioning(org.eclipse.jface.text.source.ISourceViewer) - * @since 3.0 - */ - public String getConfiguredDocumentPartitioning(ISourceViewer sourceViewer) { - if (fDocumentPartitioning != null) - return fDocumentPartitioning; - return super.getConfiguredDocumentPartitioning(sourceViewer); - } - - /* - * (non-Javadoc) Method declared on SourceViewerConfiguration - */ - public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { - ContentAssistant assistant = new ContentAssistant(); - IContentAssistProcessor processor = new HTMLCompletionProcessor(getEditor()); - assistant.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); - assistant.setContentAssistProcessor(processor, IPHPPartitions.HTML); - assistant.setContentAssistProcessor(processor, IPHPPartitions.HTML_MULTILINE_COMMENT); - - assistant.setContentAssistProcessor(processor, IPHPPartitions.CSS); - assistant.setContentAssistProcessor(processor, IPHPPartitions.CSS_MULTILINE_COMMENT); - assistant.setContentAssistProcessor(processor, IPHPPartitions.JAVASCRIPT); - assistant.setContentAssistProcessor(processor, IPHPPartitions.JS_MULTILINE_COMMENT); - // TODO define special smarty partition content assist - assistant.setContentAssistProcessor(processor, IPHPPartitions.SMARTY); - assistant.setContentAssistProcessor(processor, IPHPPartitions.SMARTY_MULTILINE_COMMENT); - - assistant.setContentAssistProcessor(processor, PHPDocumentPartitioner.PHP_TEMPLATE_DATA); - String[] htmlTypes = getConfiguredHTMLContentTypes(); - for (int i = 0; i < htmlTypes.length; i++) { - assistant.setContentAssistProcessor(processor, htmlTypes[i]); - } - processor = new PHPCompletionProcessor(getEditor()); - - assistant.setContentAssistProcessor(processor, PHPDocumentPartitioner.PHP_SCRIPT_CODE); - assistant.setContentAssistProcessor(processor, IPHPPartitions.PHP_PARTITIONING); - assistant.setContentAssistProcessor(processor, IPHPPartitions.PHP_STRING_DQ); - assistant.setContentAssistProcessor(processor, IPHPPartitions.PHP_STRING_SQ); - assistant.setContentAssistProcessor(processor, IPHPPartitions.PHP_STRING_HEREDOC); - - assistant.setContentAssistProcessor(new PHPDocCompletionProcessor(getEditor()), IPHPPartitions.PHP_PHPDOC_COMMENT); - // assistant.enableAutoActivation(true); - // assistant.setAutoActivationDelay(500); - // assistant.setProposalPopupOrientation(ContentAssistant.PROPOSAL_OVERLAY); - // ContentAssistPreference.configure(assistant, getPreferenceStore()); - // assistant.setContextInformationPopupOrientation( - // ContentAssistant.CONTEXT_INFO_ABOVE); - // assistant.setContextInformationPopupBackground( - // PHPEditorEnvironment.getPHPColorProvider().getColor( - // new RGB(150, 150, 0))); - ContentAssistPreference.configure(assistant, getPreferenceStore()); - assistant.setContextInformationPopupOrientation(ContentAssistant.CONTEXT_INFO_ABOVE); - assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer)); - return assistant; - } - - /* - * (non-Javadoc) Method declared on SourceViewerConfiguration - */ - // public String getDefaultPrefix(ISourceViewer sourceViewer, String - // contentType) { - // return (PHPPartitionScanner.PHP.equals(contentType) ? "//" : null); - // //$NON-NLS-1$ - // // return (IDocument.DEFAULT_CONTENT_TYPE.equals(contentType) ? "//" : - // null); //$NON-NLS-1$ - // } - /* - * @see SourceViewerConfiguration#getDefaultPrefix(ISourceViewer, String) - * @since 2.0 - */ - public String[] getDefaultPrefixes(ISourceViewer sourceViewer, String contentType) { - return new String[] { "//", "" }; //$NON-NLS-1$ //$NON-NLS-2$ - } - - /* - * (non-Javadoc) Method declared on SourceViewerConfiguration - */ - public ITextDoubleClickStrategy getDoubleClickStrategy(ISourceViewer sourceViewer, String contentType) { - return new PHPDoubleClickSelector(); - } - - /* - * @see SourceViewerConfiguration#getIndentPrefixes(ISourceViewer, String) - */ - public String[] getIndentPrefixes(ISourceViewer sourceViewer, String contentType) { - Vector vector = new Vector(); - // prefix[0] is either '\t' or ' ' x tabWidth, depending on useSpaces - final IPreferenceStore preferences = PHPeclipsePlugin.getDefault().getPreferenceStore(); - int tabWidth = preferences.getInt(JavaCore.FORMATTER_TAB_SIZE); - boolean useSpaces = getPreferenceStore().getBoolean(SPACES_FOR_TABS); - for (int i = 0; i <= tabWidth; i++) { - StringBuffer prefix = new StringBuffer(); - if (useSpaces) { - for (int j = 0; j + i < tabWidth; j++) - prefix.append(' '); - if (i != 0) - prefix.append('\t'); - } else { - for (int j = 0; j < i; j++) - prefix.append(' '); - if (i != tabWidth) - prefix.append('\t'); - } - vector.add(prefix.toString()); - } - vector.add(""); //$NON-NLS-1$ - return (String[]) vector.toArray(new String[vector.size()]); - } - - /** - * @return true iff the new setup without text tools is in use. - * - * @since 3.0 - */ -// private boolean isNewSetup() { -// return fJavaTextTools == null; -// } - - /** - * Creates and returns a preference store which combines the preference stores from the text tools and which is read-only. - * - * @return the read-only preference store - * @since 3.0 - */ -// private IPreferenceStore createPreferenceStore() { -// Assert.isTrue(!isNewSetup()); -// IPreferenceStore generalTextStore = EditorsUI.getPreferenceStore(); -// if (fJavaTextTools.getCorePreferenceStore() == null) -// return new ChainedPreferenceStore(new IPreferenceStore[] { fJavaTextTools.getPreferenceStore(), generalTextStore }); -// -// return new ChainedPreferenceStore(new IPreferenceStore[] { fJavaTextTools.getPreferenceStore(), -// new PreferencesAdapter(fJavaTextTools.getCorePreferenceStore()), generalTextStore }); -// } - - /* - * (non-Javadoc) Method declared on SourceViewerConfiguration - */ - public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) { - // PHPColorProvider provider = - // PHPEditorEnvironment.getPHPColorProvider(); - // JavaColorManager provider = - // PHPEditorEnvironment.getPHPColorProvider(); - PresentationReconciler phpReconciler = new JavaPresentationReconciler(); - phpReconciler.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); - - // DefaultDamagerRepairer dr = new DefaultDamagerRepairer(getHTMLScanner()); - // reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE); - // reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE); - // dr = new DefaultDamagerRepairer(getHTMLScanner()); - // reconciler.setDamager(dr, IPHPPartitions.HTML); - // reconciler.setRepairer(dr, IPHPPartitions.HTML); - // dr = new DefaultDamagerRepairer(getHTMLScanner()); - // reconciler.setDamager(dr, IPHPPartitions.CSS); - // reconciler.setRepairer(dr, IPHPPartitions.CSS); - // dr = new DefaultDamagerRepairer(getHTMLScanner()); - // reconciler.setDamager(dr, IPHPPartitions.CSS_MULTILINE_COMMENT); - // reconciler.setRepairer(dr, IPHPPartitions.CSS_MULTILINE_COMMENT); - // dr = new DefaultDamagerRepairer(getHTMLScanner()); - // reconciler.setDamager(dr, IPHPPartitions.JAVASCRIPT); - // reconciler.setRepairer(dr, IPHPPartitions.JAVASCRIPT); - // dr = new DefaultDamagerRepairer(getHTMLScanner()); - // reconciler.setDamager(dr, IPHPPartitions.JS_MULTILINE_COMMENT); - // reconciler.setRepairer(dr, IPHPPartitions.JS_MULTILINE_COMMENT); - // DefaultDamagerRepairer phpDR = new DefaultDamagerRepairer(getSmartyScanner()); - // phpReconciler.setDamager(phpDR, IPHPPartitions.SMARTY); - // phpReconciler.setRepairer(phpDR, IPHPPartitions.SMARTY); - // phpDR = new DefaultDamagerRepairer(getSmartyDocScanner()); - // phpReconciler.setDamager(phpDR, IPHPPartitions.SMARTY_MULTILINE_COMMENT); - // phpReconciler.setRepairer(phpDR, IPHPPartitions.SMARTY_MULTILINE_COMMENT); - // dr = new DefaultDamagerRepairer(new SingleTokenScanner(new TextAttribute(fJavaTextTools.getColorManager().getColor( - // PHPColorProvider.MULTI_LINE_COMMENT)))); - // reconciler.setDamager(dr, IPHPPartitions.HTML_MULTILINE_COMMENT); - // reconciler.setRepairer(dr, IPHPPartitions.HTML_MULTILINE_COMMENT); - - DefaultDamagerRepairer phpDR = new DefaultDamagerRepairer(getCodeScanner()); - phpReconciler.setDamager(phpDR, IDocument.DEFAULT_CONTENT_TYPE); - phpReconciler.setRepairer(phpDR, IDocument.DEFAULT_CONTENT_TYPE); - - phpDR = new DefaultDamagerRepairer(getCodeScanner()); - phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_PARTITIONING); - phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_PARTITIONING); - - phpDR = new DefaultDamagerRepairer(getPHPDocScanner()); - phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_PHPDOC_COMMENT); - phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_PHPDOC_COMMENT); - - phpDR = new DefaultDamagerRepairer(getStringDQScanner()); - phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_STRING_DQ); - phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_STRING_DQ); - phpDR = new DefaultDamagerRepairer(getStringSQScanner()); - phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_STRING_SQ); - phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_STRING_SQ); - phpDR = new DefaultDamagerRepairer(getStringDQScanner()); - phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_STRING_HEREDOC); - phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_STRING_HEREDOC); - phpDR = new DefaultDamagerRepairer(getSinglelineCommentScanner()); - phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_SINGLELINE_COMMENT); - phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_SINGLELINE_COMMENT); - phpDR = new DefaultDamagerRepairer(getMultilineCommentScanner()); - phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_MULTILINE_COMMENT); - phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_MULTILINE_COMMENT); - - PresentationReconciler reconciler = new PresentationReconciler(); - reconciler.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); + processor = new PHPCompletionProcessor(getEditor()); + + assistant.setContentAssistProcessor(processor, + PHPDocumentPartitioner.PHP_SCRIPT_CODE); + assistant.setContentAssistProcessor(processor, + IPHPPartitions.PHP_PARTITIONING); + assistant.setContentAssistProcessor(processor, + IPHPPartitions.PHP_STRING_DQ); + assistant.setContentAssistProcessor(processor, + IPHPPartitions.PHP_STRING_SQ); + assistant.setContentAssistProcessor(processor, + IPHPPartitions.PHP_STRING_HEREDOC); + + assistant.setContentAssistProcessor(new PHPDocCompletionProcessor( + getEditor()), IPHPPartitions.PHP_PHPDOC_COMMENT); + // assistant.enableAutoActivation(true); + // assistant.setAutoActivationDelay(500); + // assistant.setProposalPopupOrientation(ContentAssistant.PROPOSAL_OVERLAY); + // ContentAssistPreference.configure(assistant, getPreferenceStore()); + // assistant.setContextInformationPopupOrientation( + // ContentAssistant.CONTEXT_INFO_ABOVE); + // assistant.setContextInformationPopupBackground( + // PHPEditorEnvironment.getPHPColorProvider().getColor( + // new RGB(150, 150, 0))); + ContentAssistPreference.configure(assistant, getPreferenceStore()); + assistant + .setContextInformationPopupOrientation(ContentAssistant.CONTEXT_INFO_ABOVE); + assistant + .setInformationControlCreator(getInformationControlCreator(sourceViewer)); + return assistant; + } + + /* + * (non-Javadoc) Method declared on SourceViewerConfiguration + */ + // public String getDefaultPrefix(ISourceViewer sourceViewer, String + // contentType) { + // return (PHPPartitionScanner.PHP.equals(contentType) ? "//" : null); + // //$NON-NLS-1$ + // // return (IDocument.DEFAULT_CONTENT_TYPE.equals(contentType) ? "//" : + // null); //$NON-NLS-1$ + // } + /* + * @see SourceViewerConfiguration#getDefaultPrefix(ISourceViewer, String) + * @since 2.0 + */ + public String[] getDefaultPrefixes(ISourceViewer sourceViewer, + String contentType) { + return new String[] { "//", "" }; //$NON-NLS-1$ //$NON-NLS-2$ + } + + /* + * (non-Javadoc) Method declared on SourceViewerConfiguration + */ + public ITextDoubleClickStrategy getDoubleClickStrategy( + ISourceViewer sourceViewer, String contentType) { + return new PHPDoubleClickSelector(); + } + + /* + * @see SourceViewerConfiguration#getIndentPrefixes(ISourceViewer, String) + */ + public String[] getIndentPrefixes(ISourceViewer sourceViewer, + String contentType) { + Vector vector = new Vector(); + // prefix[0] is either '\t' or ' ' x tabWidth, depending on useSpaces + final IPreferenceStore preferences = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + int tabWidth = preferences.getInt(JavaCore.FORMATTER_TAB_SIZE); + boolean useSpaces = getPreferenceStore().getBoolean(SPACES_FOR_TABS); + for (int i = 0; i <= tabWidth; i++) { + StringBuffer prefix = new StringBuffer(); + if (useSpaces) { + for (int j = 0; j + i < tabWidth; j++) + prefix.append(' '); + if (i != 0) + prefix.append('\t'); + } else { + for (int j = 0; j < i; j++) + prefix.append(' '); + if (i != tabWidth) + prefix.append('\t'); + } + vector.add(prefix.toString()); + } + vector.add(""); //$NON-NLS-1$ + return (String[]) vector.toArray(new String[vector.size()]); + } + + /** + * @return true iff the new setup without text tools is in + * use. + * + * @since 3.0 + */ + // private boolean isNewSetup() { + // return fJavaTextTools == null; + // } + /** + * Creates and returns a preference store which combines the preference + * stores from the text tools and which is read-only. + * + * @return the read-only preference store + * @since 3.0 + */ + // private IPreferenceStore createPreferenceStore() { + // Assert.isTrue(!isNewSetup()); + // IPreferenceStore generalTextStore = EditorsUI.getPreferenceStore(); + // if (fJavaTextTools.getCorePreferenceStore() == null) + // return new ChainedPreferenceStore(new IPreferenceStore[] { + // fJavaTextTools.getPreferenceStore(), generalTextStore }); // -// JavaTextTools jspTextTools = PHPeclipsePlugin.getDefault().getJavaTextTools(); - DefaultDamagerRepairer dr = new DefaultDamagerRepairer(getPHPDocScanner());//jspTextTools.getJSPTextScanner()); - reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE); - reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE); - - // dr = new DefaultDamagerRepairer(new SingleTokenScanner(new TextAttribute(fJavaTextTools.getColorManager().getColor( - // PHPColorProvider.PHPDOC_TAG))));//jspTextTools.getJSPBracketScanner()); - // reconciler.setDamager(dr, JSPScriptScanner.JSP_BRACKET); - // reconciler.setRepairer(dr, JSPScriptScanner.JSP_BRACKET); - - // xml partitions - configureEmbeddedPresentationReconciler(reconciler, xmlConfiguration.getPresentationReconciler(sourceViewer), xmlConfiguration - .getConfiguredContentTypes(sourceViewer), PHPDocumentPartitioner.PHP_TEMPLATE_DATA); - - // java partitions - configureEmbeddedPresentationReconciler(reconciler, phpReconciler, getConfiguredPHPContentTypes(), - PHPDocumentPartitioner.PHP_SCRIPT_CODE); - - return reconciler; - } - - private void configureEmbeddedPresentationReconciler(PresentationReconciler reconciler, IPresentationReconciler embedded, - String[] types, String defaultType) { - for (int i = 0; i < types.length; i++) { - String type = types[i]; - - IPresentationDamager damager = embedded.getDamager(type); - IPresentationRepairer repairer = embedded.getRepairer(type); - - if (type == IDocument.DEFAULT_CONTENT_TYPE) { - type = defaultType; - } - - reconciler.setDamager(damager, type); - reconciler.setRepairer(repairer, type); - } - } - - /* - * (non-Javadoc) Method declared on SourceViewerConfiguration - */ - public int getTabWidth(ISourceViewer sourceViewer) { - return getPreferenceStore().getInt(PREFERENCE_TAB_WIDTH); - } - - /* - * (non-Javadoc) Method declared on SourceViewerConfiguration - */ - // public ITextHover getTextHover(ISourceViewer sourceViewer, String - // contentType) { - // if (fEditor != null) { - // IEditorInput editorInput = fEditor.getEditorInput(); - // if (editorInput instanceof IFileEditorInput) { - // try { - // IFile f = ((IFileEditorInput) editorInput).getFile(); - // return new PHPTextHover(f.getProject()); - // } catch (NullPointerException e) { - // // this exception occurs, if getTextHover is called by preference pages - // ! - // } - // } - // } - // return new PHPTextHover(null); - // } - /* - * @see SourceViewerConfiguration#getInformationControlCreator(ISourceViewer) - * @since 2.0 - */ - public IInformationControlCreator getInformationControlCreator(ISourceViewer sourceViewer) { - return new IInformationControlCreator() { - public IInformationControl createInformationControl(Shell parent) { - return new DefaultInformationControl(parent, SWT.NONE, new HTMLTextPresenter(true)); - // return new HoverBrowserControl(parent); - } - }; - } - - /* - * @see SourceViewerConfiguration#getInformationPresenter(ISourceViewer) - * @since 2.0 - */ - public IInformationPresenter getInformationPresenter(ISourceViewer sourceViewer) { - InformationPresenter presenter = new InformationPresenter(getInformationPresenterControlCreator(sourceViewer)); - presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); - IInformationProvider provider = new JavaInformationProvider(getEditor()); - presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE); - presenter.setInformationProvider(provider, IPHPPartitions.PHP_PHPDOC_COMMENT); - // presenter.setInformationProvider(provider, IPHPPartitions.JAVA_CHARACTER); - presenter.setSizeConstraints(60, 10, true, true); - return presenter; - } - - /* - * @see SourceViewerConfiguration#getInformationPresenter(ISourceViewer) - * @since 2.0 - */ - // public IInformationPresenter getInformationPresenter(ISourceViewer - // sourceViewer) { - // InformationPresenter presenter= new - // InformationPresenter(getInformationPresenterControlCreator(sourceViewer)); - // IInformationProvider provider= new JavaInformationProvider(getEditor()); - // presenter.setInformationProvider(provider, - // IDocument.DEFAULT_CONTENT_TYPE); - // presenter.setInformationProvider(provider, IJavaPartitions.JAVA_DOC); - // presenter.setSizeConstraints(60, 10, true, true); - // return presenter; - // } - /** - * Returns the information presenter control creator. The creator is a factory creating the presenter controls for the given - * source viewer. This implementation always returns a creator for DefaultInformationControl instances. - * - * @param sourceViewer - * the source viewer to be configured by this configuration - * @return an information control creator - * @since 2.1 - */ - private IInformationControlCreator getInformationPresenterControlCreator(ISourceViewer sourceViewer) { - return new IInformationControlCreator() { - public IInformationControl createInformationControl(Shell parent) { - int shellStyle = SWT.RESIZE; - int style = SWT.V_SCROLL | SWT.H_SCROLL; - return new DefaultInformationControl(parent, shellStyle, style, new HTMLTextPresenter(false)); - // return new HoverBrowserControl(parent); - } - }; - } - - /** - * Returns the outline presenter control creator. The creator is a factory creating outline presenter controls for the given - * source viewer. This implementation always returns a creator for JavaOutlineInformationControl instances. - * - * @param sourceViewer - * the source viewer to be configured by this configuration - * @return an information control creator - * @since 2.1 - */ - private IInformationControlCreator getOutlinePresenterControlCreator(ISourceViewer sourceViewer) { - return new IInformationControlCreator() { - public IInformationControl createInformationControl(Shell parent) { - int shellStyle = SWT.RESIZE; - int treeStyle = SWT.V_SCROLL | SWT.H_SCROLL; - return new JavaOutlineInformationControl(parent, shellStyle, treeStyle); - } - }; - } - - /** - * Returns the outline presenter which will determine and shown information requested for the current cursor position. - * - * @param sourceViewer - * the source viewer to be configured by this configuration - * @param doCodeResolve - * a boolean which specifies whether code resolve should be used to compute the Java element - * @return an information presenter - * @since 2.1 - */ - public IInformationPresenter getOutlinePresenter(ISourceViewer sourceViewer, boolean doCodeResolve) { - InformationPresenter presenter = new InformationPresenter(getOutlinePresenterControlCreator(sourceViewer)); - presenter.setAnchor(InformationPresenter.ANCHOR_GLOBAL); - IInformationProvider provider = new JavaElementProvider(getEditor(), doCodeResolve); - presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE); - presenter.setInformationProvider(provider, PHPDocumentPartitioner.PHP_SCRIPT_CODE); - presenter.setInformationProvider(provider, IPHPPartitions.PHP_PARTITIONING); - presenter.setInformationProvider(provider, IPHPPartitions.PHP_PHPDOC_COMMENT); - presenter.setInformationProvider(provider, IPHPPartitions.SMARTY_MULTILINE_COMMENT); - presenter.setInformationProvider(provider, IPHPPartitions.HTML); - presenter.setInformationProvider(provider, IPHPPartitions.HTML_MULTILINE_COMMENT); - presenter.setSizeConstraints(40, 20, true, false); - return presenter; - } + // return new ChainedPreferenceStore(new IPreferenceStore[] { + // fJavaTextTools.getPreferenceStore(), + // new PreferencesAdapter(fJavaTextTools.getCorePreferenceStore()), + // generalTextStore }); + // } + /* + * (non-Javadoc) Method declared on SourceViewerConfiguration + */ + public IPresentationReconciler getPresentationReconciler( + ISourceViewer sourceViewer) { + // PHPColorProvider provider = + // PHPEditorEnvironment.getPHPColorProvider(); + // JavaColorManager provider = + // PHPEditorEnvironment.getPHPColorProvider(); + PresentationReconciler phpReconciler = new JavaPresentationReconciler(); + phpReconciler + .setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); + + // DefaultDamagerRepairer dr = new + // DefaultDamagerRepairer(getHTMLScanner()); + // reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE); + // reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE); + // dr = new DefaultDamagerRepairer(getHTMLScanner()); + // reconciler.setDamager(dr, IPHPPartitions.HTML); + // reconciler.setRepairer(dr, IPHPPartitions.HTML); + // dr = new DefaultDamagerRepairer(getHTMLScanner()); + // reconciler.setDamager(dr, IPHPPartitions.CSS); + // reconciler.setRepairer(dr, IPHPPartitions.CSS); + // dr = new DefaultDamagerRepairer(getHTMLScanner()); + // reconciler.setDamager(dr, IPHPPartitions.CSS_MULTILINE_COMMENT); + // reconciler.setRepairer(dr, IPHPPartitions.CSS_MULTILINE_COMMENT); + // dr = new DefaultDamagerRepairer(getHTMLScanner()); + // reconciler.setDamager(dr, IPHPPartitions.JAVASCRIPT); + // reconciler.setRepairer(dr, IPHPPartitions.JAVASCRIPT); + // dr = new DefaultDamagerRepairer(getHTMLScanner()); + // reconciler.setDamager(dr, IPHPPartitions.JS_MULTILINE_COMMENT); + // reconciler.setRepairer(dr, IPHPPartitions.JS_MULTILINE_COMMENT); + // DefaultDamagerRepairer phpDR = new + // DefaultDamagerRepairer(getSmartyScanner()); + // phpReconciler.setDamager(phpDR, IPHPPartitions.SMARTY); + // phpReconciler.setRepairer(phpDR, IPHPPartitions.SMARTY); + // phpDR = new DefaultDamagerRepairer(getSmartyDocScanner()); + // phpReconciler.setDamager(phpDR, + // IPHPPartitions.SMARTY_MULTILINE_COMMENT); + // phpReconciler.setRepairer(phpDR, + // IPHPPartitions.SMARTY_MULTILINE_COMMENT); + // dr = new DefaultDamagerRepairer(new SingleTokenScanner(new + // TextAttribute(fJavaTextTools.getColorManager().getColor( + // PHPColorProvider.MULTI_LINE_COMMENT)))); + // reconciler.setDamager(dr, IPHPPartitions.HTML_MULTILINE_COMMENT); + // reconciler.setRepairer(dr, IPHPPartitions.HTML_MULTILINE_COMMENT); + + DefaultDamagerRepairer phpDR = new DefaultDamagerRepairer( + getCodeScanner()); + phpReconciler.setDamager(phpDR, IDocument.DEFAULT_CONTENT_TYPE); + phpReconciler.setRepairer(phpDR, IDocument.DEFAULT_CONTENT_TYPE); + + phpDR = new DefaultDamagerRepairer(getCodeScanner()); + phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_PARTITIONING); + phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_PARTITIONING); + + phpDR = new DefaultDamagerRepairer(getPHPDocScanner()); + phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_PHPDOC_COMMENT); + phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_PHPDOC_COMMENT); + + phpDR = new DefaultDamagerRepairer(getStringDQScanner()); + phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_STRING_DQ); + phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_STRING_DQ); + phpDR = new DefaultDamagerRepairer(getStringSQScanner()); + phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_STRING_SQ); + phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_STRING_SQ); + phpDR = new DefaultDamagerRepairer(getStringDQScanner()); + phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_STRING_HEREDOC); + phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_STRING_HEREDOC); + phpDR = new DefaultDamagerRepairer(getSinglelineCommentScanner()); + phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_SINGLELINE_COMMENT); + phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_SINGLELINE_COMMENT); + phpDR = new DefaultDamagerRepairer(getMultilineCommentScanner()); + phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_MULTILINE_COMMENT); + phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_MULTILINE_COMMENT); + + PresentationReconciler reconciler = new PresentationReconciler(); + reconciler + .setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); + // + // JavaTextTools jspTextTools = + // PHPeclipsePlugin.getDefault().getJavaTextTools(); + DefaultDamagerRepairer dr = new DefaultDamagerRepairer( + getPHPDocScanner());// jspTextTools.getJSPTextScanner()); + reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE); + reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE); + + // dr = new DefaultDamagerRepairer(new SingleTokenScanner(new + // TextAttribute(fJavaTextTools.getColorManager().getColor( + // PHPColorProvider.PHPDOC_TAG))));//jspTextTools.getJSPBracketScanner()); + // reconciler.setDamager(dr, JSPScriptScanner.JSP_BRACKET); + // reconciler.setRepairer(dr, JSPScriptScanner.JSP_BRACKET); + + // xml partitions + configureEmbeddedPresentationReconciler(reconciler, xmlConfiguration + .getPresentationReconciler(sourceViewer), xmlConfiguration + .getConfiguredContentTypes(sourceViewer), + PHPDocumentPartitioner.PHP_TEMPLATE_DATA); + + // java partitions + configureEmbeddedPresentationReconciler(reconciler, phpReconciler, + getConfiguredPHPContentTypes(), + PHPDocumentPartitioner.PHP_SCRIPT_CODE); + + return reconciler; + } + + private void configureEmbeddedPresentationReconciler( + PresentationReconciler reconciler, + IPresentationReconciler embedded, String[] types, String defaultType) { + for (int i = 0; i < types.length; i++) { + String type = types[i]; + + IPresentationDamager damager = embedded.getDamager(type); + IPresentationRepairer repairer = embedded.getRepairer(type); + + if (type == IDocument.DEFAULT_CONTENT_TYPE) { + type = defaultType; + } + + reconciler.setDamager(damager, type); + reconciler.setRepairer(repairer, type); + } + } + + /* + * (non-Javadoc) Method declared on SourceViewerConfiguration + */ + public int getTabWidth(ISourceViewer sourceViewer) { + return getPreferenceStore().getInt(PREFERENCE_TAB_WIDTH); + } + + /* + * (non-Javadoc) Method declared on SourceViewerConfiguration + */ + // public ITextHover getTextHover(ISourceViewer sourceViewer, String + // contentType) { + // if (fEditor != null) { + // IEditorInput editorInput = fEditor.getEditorInput(); + // if (editorInput instanceof IFileEditorInput) { + // try { + // IFile f = ((IFileEditorInput) editorInput).getFile(); + // return new PHPTextHover(f.getProject()); + // } catch (NullPointerException e) { + // // this exception occurs, if getTextHover is called by preference pages + // ! + // } + // } + // } + // return new PHPTextHover(null); + // } + /* + * @see SourceViewerConfiguration#getInformationControlCreator(ISourceViewer) + * @since 2.0 + */ + public IInformationControlCreator getInformationControlCreator( + ISourceViewer sourceViewer) { + return new IInformationControlCreator() { + public IInformationControl createInformationControl(Shell parent) { + return new DefaultInformationControl(parent, SWT.NONE, + new HTMLTextPresenter(true)); + // return new HoverBrowserControl(parent); + } + }; + } + + /* + * @see SourceViewerConfiguration#getInformationPresenter(ISourceViewer) + * @since 2.0 + */ + public IInformationPresenter getInformationPresenter( + ISourceViewer sourceViewer) { + InformationPresenter presenter = new InformationPresenter( + getInformationPresenterControlCreator(sourceViewer)); + presenter + .setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); + IInformationProvider provider = new JavaInformationProvider(getEditor()); + presenter.setInformationProvider(provider, + IDocument.DEFAULT_CONTENT_TYPE); + presenter.setInformationProvider(provider, + IPHPPartitions.PHP_PHPDOC_COMMENT); + // presenter.setInformationProvider(provider, + // IPHPPartitions.JAVA_CHARACTER); + presenter.setSizeConstraints(60, 10, true, true); + return presenter; + } + + /* + * @see SourceViewerConfiguration#getInformationPresenter(ISourceViewer) + * @since 2.0 + */ + // public IInformationPresenter getInformationPresenter(ISourceViewer + // sourceViewer) { + // InformationPresenter presenter= new + // InformationPresenter(getInformationPresenterControlCreator(sourceViewer)); + // IInformationProvider provider= new JavaInformationProvider(getEditor()); + // presenter.setInformationProvider(provider, + // IDocument.DEFAULT_CONTENT_TYPE); + // presenter.setInformationProvider(provider, IJavaPartitions.JAVA_DOC); + // presenter.setSizeConstraints(60, 10, true, true); + // return presenter; + // } + /** + * Returns the information presenter control creator. The creator is a + * factory creating the presenter controls for the given source viewer. This + * implementation always returns a creator for + * DefaultInformationControl instances. + * + * @param sourceViewer + * the source viewer to be configured by this configuration + * @return an information control creator + * @since 2.1 + */ + private IInformationControlCreator getInformationPresenterControlCreator( + ISourceViewer sourceViewer) { + return new IInformationControlCreator() { + public IInformationControl createInformationControl(Shell parent) { + int shellStyle = SWT.RESIZE; + int style = SWT.V_SCROLL | SWT.H_SCROLL; + return new DefaultInformationControl(parent, shellStyle, style, + new HTMLTextPresenter(false)); + // return new HoverBrowserControl(parent); + } + }; + } + + /** + * Returns the outline presenter control creator. The creator is a factory + * creating outline presenter controls for the given source viewer. This + * implementation always returns a creator for + * JavaOutlineInformationControl instances. + * + * @param sourceViewer + * the source viewer to be configured by this configuration + * @return an information control creator + * @since 2.1 + */ + private IInformationControlCreator getOutlinePresenterControlCreator( + ISourceViewer sourceViewer) { + return new IInformationControlCreator() { + public IInformationControl createInformationControl(Shell parent) { + int shellStyle = SWT.RESIZE; + int treeStyle = SWT.V_SCROLL | SWT.H_SCROLL; + return new JavaOutlineInformationControl(parent, shellStyle, + treeStyle); + } + }; + } + + /** + * Returns the outline presenter which will determine and shown information + * requested for the current cursor position. + * + * @param sourceViewer + * the source viewer to be configured by this configuration + * @param doCodeResolve + * a boolean which specifies whether code resolve should be used + * to compute the Java element + * @return an information presenter + * @since 2.1 + */ + public IInformationPresenter getOutlinePresenter( + ISourceViewer sourceViewer, boolean doCodeResolve) { + InformationPresenter presenter = new InformationPresenter( + getOutlinePresenterControlCreator(sourceViewer)); + presenter.setAnchor(InformationPresenter.ANCHOR_GLOBAL); + IInformationProvider provider = new JavaElementProvider(getEditor(), + doCodeResolve); + presenter.setInformationProvider(provider, + IDocument.DEFAULT_CONTENT_TYPE); + presenter.setInformationProvider(provider, + PHPDocumentPartitioner.PHP_SCRIPT_CODE); + presenter.setInformationProvider(provider, + IPHPPartitions.PHP_PARTITIONING); + presenter.setInformationProvider(provider, + IPHPPartitions.PHP_PHPDOC_COMMENT); + presenter.setInformationProvider(provider, + IPHPPartitions.SMARTY_MULTILINE_COMMENT); + presenter.setInformationProvider(provider, IPHPPartitions.HTML); + presenter.setInformationProvider(provider, + IPHPPartitions.HTML_MULTILINE_COMMENT); + presenter.setSizeConstraints(40, 20, true, false); + return presenter; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/PHPStringDQCodeScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/PHPStringDQCodeScanner.java index 85dbb75..6203ece 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/PHPStringDQCodeScanner.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/PHPStringDQCodeScanner.java @@ -30,92 +30,96 @@ import org.eclipse.jface.text.rules.WordRule; */ public final class PHPStringDQCodeScanner extends AbstractJavaScanner { - private static String[] fgTokenProperties = { IPreferenceConstants.PHP_STRING_DQ, IPreferenceConstants.PHP_VARIABLE, IPreferenceConstants.PHP_VARIABLE_DOLLAR}; + private static String[] fgTokenProperties = { + IPreferenceConstants.PHP_STRING_DQ, + IPreferenceConstants.PHP_VARIABLE, + IPreferenceConstants.PHP_VARIABLE_DOLLAR }; - private class PHPWordRule extends WordRule { - private StringBuffer fBuffer = new StringBuffer(); + private class PHPWordRule extends WordRule { + private StringBuffer fBuffer = new StringBuffer(); - public PHPWordRule(IWordDetector detector) { - super(detector, Token.UNDEFINED); - } + public PHPWordRule(IWordDetector detector) { + super(detector, Token.UNDEFINED); + } - public PHPWordRule(IWordDetector detector, IToken defaultToken) { - super(detector, defaultToken); - } + public PHPWordRule(IWordDetector detector, IToken defaultToken) { + super(detector, defaultToken); + } - public IToken evaluate(ICharacterScanner scanner) { - int c = scanner.read(); - boolean isUnderscore = false; - if (fDetector.isWordStart((char) c)) { - if (fColumn == UNDEFINED || (fColumn == scanner.getColumn() - 1)) { - - fBuffer.setLength(0); - fBuffer.append((char) c); - c = scanner.read(); - if (c=='_') { - isUnderscore = true; - } - while (c != ICharacterScanner.EOF && fDetector.isWordPart((char) c)) { - fBuffer.append((char) c); - c = scanner.read(); - // hack for coloring object elements with variable color instead of string color - if (c=='-') { - int c2=scanner.read(); - if (c2=='>') { - fBuffer.append(c); - fBuffer.append(c2); - c=scanner.read(); - } - else { + public IToken evaluate(ICharacterScanner scanner) { + int c = scanner.read(); + boolean isUnderscore = false; + if (fDetector.isWordStart((char) c)) { + if (fColumn == UNDEFINED + || (fColumn == scanner.getColumn() - 1)) { + + fBuffer.setLength(0); + fBuffer.append((char) c); + c = scanner.read(); + if (c == '_') { + isUnderscore = true; + } + while (c != ICharacterScanner.EOF + && fDetector.isWordPart((char) c)) { + fBuffer.append((char) c); + c = scanner.read(); + // hack for coloring object elements with variable color + // instead of string color + if (c == '-') { + int c2 = scanner.read(); + if (c2 == '>') { + fBuffer.append(c); + fBuffer.append(c2); + c = scanner.read(); + } else { + scanner.unread(); + } + } + // hack end + } scanner.unread(); + if (isUnderscore) { + return getToken(IPreferenceConstants.PHP_VARIABLE_DOLLAR); + } + return getToken(IPreferenceConstants.PHP_VARIABLE); } } - // hack end - } - scanner.unread(); - if (isUnderscore) { - return getToken(IPreferenceConstants.PHP_VARIABLE_DOLLAR); - } - return getToken(IPreferenceConstants.PHP_VARIABLE); - } - } - scanner.unread(); - return Token.UNDEFINED; + scanner.unread(); + return Token.UNDEFINED; + } } - } - public PHPStringDQCodeScanner(IColorManager manager, IPreferenceStore store) { - super(manager, store); - initialize(); - } + public PHPStringDQCodeScanner(IColorManager manager, IPreferenceStore store) { + super(manager, store); + initialize(); + } - public IDocument getDocument() { - return fDocument; - } + public IDocument getDocument() { + return fDocument; + } - /* - * @see AbstractJavaScanner#getTokenProperties() - */ - protected String[] getTokenProperties() { - return fgTokenProperties; - } + /* + * @see AbstractJavaScanner#getTokenProperties() + */ + protected String[] getTokenProperties() { + return fgTokenProperties; + } - /* - * @see AbstractJavaScanner#createRules() - */ - protected List createRules() { + /* + * @see AbstractJavaScanner#createRules() + */ + protected List createRules() { - List list = new ArrayList(); + List list = new ArrayList(); - // Add rule for tags. - Token token = getToken(IPreferenceConstants.PHP_STRING_DQ); - PHPWordRule wordRule = new PHPWordRule(new PHPVariableDetector(), token); + // Add rule for tags. + Token token = getToken(IPreferenceConstants.PHP_STRING_DQ); + PHPWordRule wordRule = new PHPWordRule(new PHPVariableDetector(), token); - list.add(wordRule); + list.add(wordRule); - setDefaultReturnToken(getToken(IPreferenceConstants.PHP_STRING_DQ)); - return list; - } + setDefaultReturnToken(getToken(IPreferenceConstants.PHP_STRING_DQ)); + return list; + } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/SingleTokenPHPScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/SingleTokenPHPScanner.java index ec10e41..81bdd4e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/SingleTokenPHPScanner.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/SingleTokenPHPScanner.java @@ -5,25 +5,23 @@ package net.sourceforge.phpdt.ui.text; - import java.util.List; import net.sourceforge.phpdt.internal.ui.text.AbstractJavaScanner; import org.eclipse.jface.preference.IPreferenceStore; - /** * */ -public final class SingleTokenPHPScanner extends AbstractJavaScanner{ - - +public final class SingleTokenPHPScanner extends AbstractJavaScanner { + private String[] fProperty; - - public SingleTokenPHPScanner(IColorManager manager, IPreferenceStore store, String property) { + + public SingleTokenPHPScanner(IColorManager manager, IPreferenceStore store, + String property) { super(manager, store); - fProperty= new String[] { property }; + fProperty = new String[] { property }; initialize(); } @@ -42,4 +40,3 @@ public final class SingleTokenPHPScanner extends AbstractJavaScanner{ return null; } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/folding/IJavaFoldingPreferenceBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/folding/IJavaFoldingPreferenceBlock.java index a5e7358..dc9e1bf 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/folding/IJavaFoldingPreferenceBlock.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/folding/IJavaFoldingPreferenceBlock.java @@ -13,11 +13,11 @@ package net.sourceforge.phpdt.ui.text.folding; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; - /** - * Contributors to the net.sourceforge.phpdt.ui.foldingStructureProvider extension point - * can specify an implementation of this interface to be displayed on the Java > Editor > Folding - * preference page. + * Contributors to the + * net.sourceforge.phpdt.ui.foldingStructureProvider extension + * point can specify an implementation of this interface to be displayed on the + * Java > Editor > Folding preference page. *

                                                      * Clients may implement this interface. *

                                                      @@ -30,13 +30,14 @@ public interface IJavaFoldingPreferenceBlock { * Creates the control that will be displayed on the Java Editor folding * preference page. * - * @param parent the parent composite to which to add the preferences control - * @return the control that was added to parent + * @param parent + * the parent composite to which to add the preferences control + * @return the control that was added to parent */ Control createControl(Composite parent); /** - * Called after creating the control. Implementations should load the + * Called after creating the control. Implementations should load the * preferences values and update the controls accordingly. */ void initialize(); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/folding/IJavaFoldingStructureProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/folding/IJavaFoldingStructureProvider.java index 7ea9529..9fa814a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/folding/IJavaFoldingStructureProvider.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/folding/IJavaFoldingStructureProvider.java @@ -35,9 +35,11 @@ public interface IJavaFoldingStructureProvider { * viewer and enable / disable generation of projection * structure accordingly. * - * @param editor the editor that this provider works on - * @param viewer the projection viewer that displays the annotations created - * by this structure provider + * @param editor + * the editor that this provider works on + * @param viewer + * the projection viewer that displays the annotations created by + * this structure provider */ public abstract void install(ITextEditor editor, ProjectionViewer viewer); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/java/hover/IJavaEditorTextHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/java/hover/IJavaEditorTextHover.java index 350bef0..5f4dda2 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/java/hover/IJavaEditorTextHover.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/java/hover/IJavaEditorTextHover.java @@ -15,11 +15,12 @@ import org.eclipse.ui.IEditorPart; /** * Provides a hover popup which appears on top of an editor with relevant - * display information. If the text hover does not provide information no - * hover popup is shown. + * display information. If the text hover does not provide information no hover + * popup is shown. *

                                                      - * Clients may implement this interface.

                                                      - * + * Clients may implement this interface. + *

                                                      + * * @see org.eclipse.ui.IEditorPart * @see org.eclipse.jface.text.ITextHover * @@ -30,9 +31,9 @@ public interface IJavaEditorTextHover extends ITextHover { /** * Sets the editor on which the hover is shown. * - * @param editor the editor on which the hover popup should be shown + * @param editor + * the editor on which the hover popup should be shown */ void setEditor(IEditorPart editor); } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewClassWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewClassWizardPage.java index 2db3c31..4203e32 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewClassWizardPage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewClassWizardPage.java @@ -26,231 +26,250 @@ import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; /** - * Wizard page to create a new class. + * Wizard page to create a new class. *

                                                      - * Note: This class is not intended to be subclassed. To implement a different kind of - * a new class wizard page, extend NewTypeWizardPage. + * Note: This class is not intended to be subclassed. To implement a different + * kind of a new class wizard page, extend NewTypeWizardPage. *

                                                      * * @since 2.0 */ public class NewClassWizardPage extends NewTypeWizardPage { - private final static String PAGE_NAME = "NewClassWizardPage"; //$NON-NLS-1$ - - private final static String SETTINGS_CREATEMAIN = "create_main"; //$NON-NLS-1$ - private final static String SETTINGS_CREATECONSTR = "create_constructor"; //$NON-NLS-1$ - private final static String SETTINGS_CREATEUNIMPLEMENTED = "create_unimplemented"; //$NON-NLS-1$ - - private SelectionButtonDialogFieldGroup fMethodStubsButtons; - - /** - * Creates a new NewClassWizardPage - */ - public NewClassWizardPage() { - super(true, PAGE_NAME); - - setTitle(NewWizardMessages.getString("NewClassWizardPage.title")); //$NON-NLS-1$ - setDescription(NewWizardMessages.getString("NewClassWizardPage.description")); //$NON-NLS-1$ - - String[] buttonNames3 = new String[] { NewWizardMessages.getString("NewClassWizardPage.methods.main"), NewWizardMessages.getString("NewClassWizardPage.methods.constructors"), //$NON-NLS-1$ //$NON-NLS-2$ - NewWizardMessages.getString("NewClassWizardPage.methods.inherited") //$NON-NLS-1$ - }; - fMethodStubsButtons = new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames3, 1); - fMethodStubsButtons.setLabelText(NewWizardMessages.getString("NewClassWizardPage.methods.label")); //$NON-NLS-1$ - } - - // -------- Initialization --------- - - /** - * The wizard owning this page is responsible for calling this method with the - * current selection. The selection is used to initialize the fields of the wizard - * page. - * - * @param selection used to initialize the fields - */ - public void init(IStructuredSelection selection) { - IJavaElement jelem = getInitialJavaElement(selection); - initContainerPage(jelem); - initTypePage(jelem); - doStatusUpdate(); - - boolean createMain = false; - boolean createConstructors = false; - boolean createUnimplemented = true; - IDialogSettings section = getDialogSettings().getSection(PAGE_NAME); - if (section != null) { - createMain = section.getBoolean(SETTINGS_CREATEMAIN); - createConstructors = section.getBoolean(SETTINGS_CREATECONSTR); - createUnimplemented = section.getBoolean(SETTINGS_CREATEUNIMPLEMENTED); - } - - setMethodStubSelection(createMain, createConstructors, createUnimplemented, true); - } - - // ------ validation -------- - private void doStatusUpdate() { - // status of all used components - IStatus[] status = - new IStatus[] { - fContainerStatus, - isEnclosingTypeSelected() ? fEnclosingTypeStatus : fPackageStatus, - fTypeNameStatus, - fModifierStatus, - // fSuperClassStatus, - // fSuperInterfacesStatus - }; - - // the mode severe status will be displayed and the ok button enabled/disabled. - updateStatus(status); - } - - /* - * @see NewContainerWizardPage#handleFieldChanged - */ - protected void handleFieldChanged(String fieldName) { - super.handleFieldChanged(fieldName); - - doStatusUpdate(); - } - - // ------ ui -------- - - /* - * @see WizardPage#createControl - */ - public void createControl(Composite parent) { - initializeDialogUnits(parent); - - Composite composite = new Composite(parent, SWT.NONE); - - int nColumns = 4; - - GridLayout layout = new GridLayout(); - layout.numColumns = nColumns; - composite.setLayout(layout); - - // pick & choose the wanted UI components - - createContainerControls(composite, nColumns); - createPackageControls(composite, nColumns); - createEnclosingTypeControls(composite, nColumns); - - createSeparator(composite, nColumns); - - createTypeNameControls(composite, nColumns); - createModifierControls(composite, nColumns); - - createSuperClassControls(composite, nColumns); - createSuperInterfacesControls(composite, nColumns); - - createMethodStubSelectionControls(composite, nColumns); - - setControl(composite); - - Dialog.applyDialogFont(composite); - // WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.NEW_CLASS_WIZARD_PAGE); - } - - /* - * @see WizardPage#becomesVisible - */ - public void setVisible(boolean visible) { - super.setVisible(visible); - if (visible) { - setFocus(); - } - } - - private void createMethodStubSelectionControls(Composite composite, int nColumns) { - Control labelControl = fMethodStubsButtons.getLabelControl(composite); - LayoutUtil.setHorizontalSpan(labelControl, nColumns); - - DialogField.createEmptySpace(composite); - - Control buttonGroup = fMethodStubsButtons.getSelectionButtonsGroup(composite); - LayoutUtil.setHorizontalSpan(buttonGroup, nColumns - 1); - } - - /** - * Returns the current selection state of the 'Create Main' checkbox. - * - * @return the selection state of the 'Create Main' checkbox - */ - public boolean isCreateMain() { - return fMethodStubsButtons.isSelected(0); - } - - /** - * Returns the current selection state of the 'Create Constructors' checkbox. - * - * @return the selection state of the 'Create Constructors' checkbox - */ - public boolean isCreateConstructors() { - return fMethodStubsButtons.isSelected(1); - } - - /** - * Returns the current selection state of the 'Create inherited abstract methods' - * checkbox. - * - * @return the selection state of the 'Create inherited abstract methods' checkbox - */ - public boolean isCreateInherited() { - return fMethodStubsButtons.isSelected(2); - } - - /** - * Sets the selection state of the method stub checkboxes. - * - * @param createMain initial selection state of the 'Create Main' checkbox. - * @param createConstructors initial selection state of the 'Create Constructors' checkbox. - * @param createInherited initial selection state of the 'Create inherited abstract methods' checkbox. - * @param canBeModified if true the method stub checkboxes can be changed by - * the user. If false the buttons are "read-only" - */ - public void setMethodStubSelection( - boolean createMain, - boolean createConstructors, - boolean createInherited, - boolean canBeModified) { - fMethodStubsButtons.setSelection(0, createMain); - fMethodStubsButtons.setSelection(1, createConstructors); - fMethodStubsButtons.setSelection(2, createInherited); - - fMethodStubsButtons.setEnabled(canBeModified); - } - - // ---- creation ---------------- - - /* - * @see NewTypeWizardPage#createTypeMembers - */ - // protected void createTypeMembers(IType type, ImportsManager imports, IProgressMonitor monitor) throws CoreException { - // boolean doMain= isCreateMain(); - // boolean doConstr= isCreateConstructors(); - // boolean doInherited= isCreateInherited(); - // createInheritedMethods(type, doConstr, doInherited, imports, new SubProgressMonitor(monitor, 1)); - // - // if (doMain) { - // StringBuffer buf= new StringBuffer(); - // buf.append("public static void main("); //$NON-NLS-1$ - // buf.append(imports.addImport("java.lang.String")); //$NON-NLS-1$ - // buf.append("[] args) {}"); //$NON-NLS-1$ - // type.createMethod(buf.toString(), null, false, null); - // } - // - // IDialogSettings section= getDialogSettings().getSection(PAGE_NAME); - // if (section == null) { - // section= getDialogSettings().addNewSection(PAGE_NAME); - // } - // section.put(SETTINGS_CREATEMAIN, doMain); - // section.put(SETTINGS_CREATECONSTR, doConstr); - // section.put(SETTINGS_CREATEUNIMPLEMENTED, doInherited); - // - // if (monitor != null) { - // monitor.done(); - // } - // } - + private final static String PAGE_NAME = "NewClassWizardPage"; //$NON-NLS-1$ + + private final static String SETTINGS_CREATEMAIN = "create_main"; //$NON-NLS-1$ + + private final static String SETTINGS_CREATECONSTR = "create_constructor"; //$NON-NLS-1$ + + private final static String SETTINGS_CREATEUNIMPLEMENTED = "create_unimplemented"; //$NON-NLS-1$ + + private SelectionButtonDialogFieldGroup fMethodStubsButtons; + + /** + * Creates a new NewClassWizardPage + */ + public NewClassWizardPage() { + super(true, PAGE_NAME); + + setTitle(NewWizardMessages.getString("NewClassWizardPage.title")); //$NON-NLS-1$ + setDescription(NewWizardMessages + .getString("NewClassWizardPage.description")); //$NON-NLS-1$ + + String[] buttonNames3 = new String[] { + NewWizardMessages.getString("NewClassWizardPage.methods.main"), NewWizardMessages.getString("NewClassWizardPage.methods.constructors"), //$NON-NLS-1$ //$NON-NLS-2$ + NewWizardMessages + .getString("NewClassWizardPage.methods.inherited") //$NON-NLS-1$ + }; + fMethodStubsButtons = new SelectionButtonDialogFieldGroup(SWT.CHECK, + buttonNames3, 1); + fMethodStubsButtons.setLabelText(NewWizardMessages + .getString("NewClassWizardPage.methods.label")); //$NON-NLS-1$ + } + + // -------- Initialization --------- + + /** + * The wizard owning this page is responsible for calling this method with + * the current selection. The selection is used to initialize the fields of + * the wizard page. + * + * @param selection + * used to initialize the fields + */ + public void init(IStructuredSelection selection) { + IJavaElement jelem = getInitialJavaElement(selection); + initContainerPage(jelem); + initTypePage(jelem); + doStatusUpdate(); + + boolean createMain = false; + boolean createConstructors = false; + boolean createUnimplemented = true; + IDialogSettings section = getDialogSettings().getSection(PAGE_NAME); + if (section != null) { + createMain = section.getBoolean(SETTINGS_CREATEMAIN); + createConstructors = section.getBoolean(SETTINGS_CREATECONSTR); + createUnimplemented = section + .getBoolean(SETTINGS_CREATEUNIMPLEMENTED); + } + + setMethodStubSelection(createMain, createConstructors, + createUnimplemented, true); + } + + // ------ validation -------- + private void doStatusUpdate() { + // status of all used components + IStatus[] status = new IStatus[] { + fContainerStatus, + isEnclosingTypeSelected() ? fEnclosingTypeStatus + : fPackageStatus, fTypeNameStatus, fModifierStatus, + // fSuperClassStatus, + // fSuperInterfacesStatus + }; + + // the mode severe status will be displayed and the ok button + // enabled/disabled. + updateStatus(status); + } + + /* + * @see NewContainerWizardPage#handleFieldChanged + */ + protected void handleFieldChanged(String fieldName) { + super.handleFieldChanged(fieldName); + + doStatusUpdate(); + } + + // ------ ui -------- + + /* + * @see WizardPage#createControl + */ + public void createControl(Composite parent) { + initializeDialogUnits(parent); + + Composite composite = new Composite(parent, SWT.NONE); + + int nColumns = 4; + + GridLayout layout = new GridLayout(); + layout.numColumns = nColumns; + composite.setLayout(layout); + + // pick & choose the wanted UI components + + createContainerControls(composite, nColumns); + createPackageControls(composite, nColumns); + createEnclosingTypeControls(composite, nColumns); + + createSeparator(composite, nColumns); + + createTypeNameControls(composite, nColumns); + createModifierControls(composite, nColumns); + + createSuperClassControls(composite, nColumns); + createSuperInterfacesControls(composite, nColumns); + + createMethodStubSelectionControls(composite, nColumns); + + setControl(composite); + + Dialog.applyDialogFont(composite); + // WorkbenchHelp.setHelp(composite, + // IJavaHelpContextIds.NEW_CLASS_WIZARD_PAGE); + } + + /* + * @see WizardPage#becomesVisible + */ + public void setVisible(boolean visible) { + super.setVisible(visible); + if (visible) { + setFocus(); + } + } + + private void createMethodStubSelectionControls(Composite composite, + int nColumns) { + Control labelControl = fMethodStubsButtons.getLabelControl(composite); + LayoutUtil.setHorizontalSpan(labelControl, nColumns); + + DialogField.createEmptySpace(composite); + + Control buttonGroup = fMethodStubsButtons + .getSelectionButtonsGroup(composite); + LayoutUtil.setHorizontalSpan(buttonGroup, nColumns - 1); + } + + /** + * Returns the current selection state of the 'Create Main' checkbox. + * + * @return the selection state of the 'Create Main' checkbox + */ + public boolean isCreateMain() { + return fMethodStubsButtons.isSelected(0); + } + + /** + * Returns the current selection state of the 'Create Constructors' + * checkbox. + * + * @return the selection state of the 'Create Constructors' checkbox + */ + public boolean isCreateConstructors() { + return fMethodStubsButtons.isSelected(1); + } + + /** + * Returns the current selection state of the 'Create inherited abstract + * methods' checkbox. + * + * @return the selection state of the 'Create inherited abstract methods' + * checkbox + */ + public boolean isCreateInherited() { + return fMethodStubsButtons.isSelected(2); + } + + /** + * Sets the selection state of the method stub checkboxes. + * + * @param createMain + * initial selection state of the 'Create Main' checkbox. + * @param createConstructors + * initial selection state of the 'Create Constructors' checkbox. + * @param createInherited + * initial selection state of the 'Create inherited abstract + * methods' checkbox. + * @param canBeModified + * if true the method stub checkboxes can be + * changed by the user. If false the buttons are + * "read-only" + */ + public void setMethodStubSelection(boolean createMain, + boolean createConstructors, boolean createInherited, + boolean canBeModified) { + fMethodStubsButtons.setSelection(0, createMain); + fMethodStubsButtons.setSelection(1, createConstructors); + fMethodStubsButtons.setSelection(2, createInherited); + + fMethodStubsButtons.setEnabled(canBeModified); + } + + // ---- creation ---------------- + + /* + * @see NewTypeWizardPage#createTypeMembers + */ + // protected void createTypeMembers(IType type, ImportsManager imports, + // IProgressMonitor monitor) throws CoreException { + // boolean doMain= isCreateMain(); + // boolean doConstr= isCreateConstructors(); + // boolean doInherited= isCreateInherited(); + // createInheritedMethods(type, doConstr, doInherited, imports, new + // SubProgressMonitor(monitor, 1)); + // + // if (doMain) { + // StringBuffer buf= new StringBuffer(); + // buf.append("public static void main("); //$NON-NLS-1$ + // buf.append(imports.addImport("java.lang.String")); //$NON-NLS-1$ + // buf.append("[] args) {}"); //$NON-NLS-1$ + // type.createMethod(buf.toString(), null, false, null); + // } + // + // IDialogSettings section= getDialogSettings().getSection(PAGE_NAME); + // if (section == null) { + // section= getDialogSettings().addNewSection(PAGE_NAME); + // } + // section.put(SETTINGS_CREATEMAIN, doMain); + // section.put(SETTINGS_CREATECONSTR, doConstr); + // section.put(SETTINGS_CREATEUNIMPLEMENTED, doInherited); + // + // if (monitor != null) { + // monitor.done(); + // } + // } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewContainerWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewContainerWizardPage.java index 4460b0b..a776745 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewContainerWizardPage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewContainerWizardPage.java @@ -39,133 +39,146 @@ import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.views.contentoutline.ContentOutline; /** - * Wizard page that acts as a base class for wizard pages that create new Java elements. - * The class provides a input field for source folders (called container in this class) and - * API to validate the enter source folder name. + * Wizard page that acts as a base class for wizard pages that create new Java + * elements. The class provides a input field for source folders (called + * container in this class) and API to validate the enter source folder name. * * @since 2.0 */ public abstract class NewContainerWizardPage extends NewElementWizardPage { - + /** Id of the container field */ - protected static final String CONTAINER= "NewContainerWizardPage.container"; //$NON-NLS-1$ + protected static final String CONTAINER = "NewContainerWizardPage.container"; //$NON-NLS-1$ /** The status of the last validation. */ protected IStatus fContainerStatus; private StringButtonDialogField fContainerDialogField; - + /* * package fragment root corresponding to the input type (can be null) */ private IPackageFragmentRoot fCurrRoot; - + private IWorkspaceRoot fWorkspaceRoot; - + /** * Create a new NewContainerWizardPage * - * @param name the wizard page's name + * @param name + * the wizard page's name */ public NewContainerWizardPage(String name) { super(name); - fWorkspaceRoot= ResourcesPlugin.getWorkspace().getRoot(); - ContainerFieldAdapter adapter= new ContainerFieldAdapter(); - - fContainerDialogField= new StringButtonDialogField(adapter); + fWorkspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); + ContainerFieldAdapter adapter = new ContainerFieldAdapter(); + + fContainerDialogField = new StringButtonDialogField(adapter); fContainerDialogField.setDialogFieldListener(adapter); - fContainerDialogField.setLabelText(NewWizardMessages.getString("NewContainerWizardPage.container.label")); //$NON-NLS-1$ - fContainerDialogField.setButtonLabel(NewWizardMessages.getString("NewContainerWizardPage.container.button")); //$NON-NLS-1$ - - fContainerStatus= new StatusInfo(); - fCurrRoot= null; + fContainerDialogField.setLabelText(NewWizardMessages + .getString("NewContainerWizardPage.container.label")); //$NON-NLS-1$ + fContainerDialogField.setButtonLabel(NewWizardMessages + .getString("NewContainerWizardPage.container.button")); //$NON-NLS-1$ + + fContainerStatus = new StatusInfo(); + fCurrRoot = null; } - + /** * Initializes the source folder field with a valid package fragement root. * The package fragement root is computed from the given Java element. * - * @param elem the Java element used to compute the initial package - * fragment root used as the source folder + * @param elem + * the Java element used to compute the initial package fragment + * root used as the source folder */ protected void initContainerPage(IJavaElement elem) { - IPackageFragmentRoot initRoot= null; -// if (elem != null) { -// initRoot= JavaModelUtil.getPackageFragmentRoot(elem); -// if (initRoot == null || initRoot.isArchive()) { -// IJavaProject jproject= elem.getJavaProject(); -// if (jproject != null) { -// try { -// initRoot= null; -// if (jproject.exists()) { -// IPackageFragmentRoot[] roots= jproject.getPackageFragmentRoots(); -// for (int i= 0; i < roots.length; i++) { -// if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) { -// initRoot= roots[i]; -// break; -// } -// } -// } -// } catch (JavaModelException e) { -// PHPeclipsePlugin.log(e); -// } -// if (initRoot == null) { -// initRoot= jproject.getPackageFragmentRoot(jproject.getResource()); -// } -// } -// } -// } -// setPackageFragmentRoot(initRoot, true); + IPackageFragmentRoot initRoot = null; + // if (elem != null) { + // initRoot= JavaModelUtil.getPackageFragmentRoot(elem); + // if (initRoot == null || initRoot.isArchive()) { + // IJavaProject jproject= elem.getJavaProject(); + // if (jproject != null) { + // try { + // initRoot= null; + // if (jproject.exists()) { + // IPackageFragmentRoot[] roots= jproject.getPackageFragmentRoots(); + // for (int i= 0; i < roots.length; i++) { + // if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) { + // initRoot= roots[i]; + // break; + // } + // } + // } + // } catch (JavaModelException e) { + // PHPeclipsePlugin.log(e); + // } + // if (initRoot == null) { + // initRoot= jproject.getPackageFragmentRoot(jproject.getResource()); + // } + // } + // } + // } + // setPackageFragmentRoot(initRoot, true); } - + /** - * Utility method to inspect a selection to find a Java element. + * Utility method to inspect a selection to find a Java element. * - * @param selection the selection to be inspected - * @return a Java element to be used as the initial selection, or null, - * if no Java element exists in the given selection + * @param selection + * the selection to be inspected + * @return a Java element to be used as the initial selection, or + * null, if no Java element exists in the given + * selection */ protected IJavaElement getInitialJavaElement(IStructuredSelection selection) { - IJavaElement jelem= null; + IJavaElement jelem = null; if (selection != null && !selection.isEmpty()) { - Object selectedElement= selection.getFirstElement(); + Object selectedElement = selection.getFirstElement(); if (selectedElement instanceof IAdaptable) { - IAdaptable adaptable= (IAdaptable) selectedElement; - - jelem= (IJavaElement) adaptable.getAdapter(IJavaElement.class); + IAdaptable adaptable = (IAdaptable) selectedElement; + + jelem = (IJavaElement) adaptable.getAdapter(IJavaElement.class); if (jelem == null) { - IResource resource= (IResource) adaptable.getAdapter(IResource.class); - if (resource != null && resource.getType() != IResource.ROOT) { - while (jelem == null && resource.getType() != IResource.PROJECT) { - resource= resource.getParent(); - jelem= (IJavaElement) resource.getAdapter(IJavaElement.class); + IResource resource = (IResource) adaptable + .getAdapter(IResource.class); + if (resource != null + && resource.getType() != IResource.ROOT) { + while (jelem == null + && resource.getType() != IResource.PROJECT) { + resource = resource.getParent(); + jelem = (IJavaElement) resource + .getAdapter(IJavaElement.class); } if (jelem == null) { - jelem= JavaCore.create(resource); // java project + jelem = JavaCore.create(resource); // java project } } } } } if (jelem == null) { - IWorkbenchPart part= PHPeclipsePlugin.getActivePage().getActivePart(); + IWorkbenchPart part = PHPeclipsePlugin.getActivePage() + .getActivePart(); if (part instanceof ContentOutline) { - part= PHPeclipsePlugin.getActivePage().getActiveEditor(); + part = PHPeclipsePlugin.getActivePage().getActiveEditor(); } - + if (part instanceof IViewPartInputProvider) { - Object elem= ((IViewPartInputProvider)part).getViewPartInput(); + Object elem = ((IViewPartInputProvider) part) + .getViewPartInput(); if (elem instanceof IJavaElement) { - jelem= (IJavaElement) elem; + jelem = (IJavaElement) elem; } } } if (jelem == null || jelem.getElementType() == IJavaElement.JAVA_MODEL) { try { - IJavaProject[] projects= JavaCore.create(getWorkspaceRoot()).getJavaProjects(); + IJavaProject[] projects = JavaCore.create(getWorkspaceRoot()) + .getJavaProjects(); if (projects.length == 1) { - jelem= projects[0]; + jelem = projects[0]; } } catch (JavaModelException e) { PHPeclipsePlugin.log(e); @@ -173,11 +186,11 @@ public abstract class NewContainerWizardPage extends NewElementWizardPage { } return jelem; } - + /** * Returns the recommended maximum width for text fields (in pixels). This * method requires that createContent has been called before this method is - * call. Subclasses may override to change the maximum width for text + * call. Subclasses may override to change the maximum width for text * fields. * * @return the recommended maximum width for text fields. @@ -185,162 +198,178 @@ public abstract class NewContainerWizardPage extends NewElementWizardPage { protected int getMaxFieldWidth() { return convertWidthInCharsToPixels(40); } - - + /** - * Creates the necessary controls (label, text field and browse button) to edit - * the source folder location. The method expects that the parent composite - * uses a GridLayout as its layout manager and that the - * grid layout has at least 3 columns. + * Creates the necessary controls (label, text field and browse button) to + * edit the source folder location. The method expects that the parent + * composite uses a GridLayout as its layout manager and that + * the grid layout has at least 3 columns. * - * @param parent the parent composite - * @param nColumns the number of columns to span. This number must be - * greater or equal three + * @param parent + * the parent composite + * @param nColumns + * the number of columns to span. This number must be greater or + * equal three */ protected void createContainerControls(Composite parent, int nColumns) { fContainerDialogField.doFillIntoGrid(parent, nColumns); - LayoutUtil.setWidthHint(fContainerDialogField.getTextControl(null), getMaxFieldWidth()); + LayoutUtil.setWidthHint(fContainerDialogField.getTextControl(null), + getMaxFieldWidth()); } /** * Sets the focus to the source folder's text field. - */ + */ protected void setFocusOnContainer() { fContainerDialogField.setFocus(); } // -------- ContainerFieldAdapter -------- - private class ContainerFieldAdapter implements IStringButtonAdapter, IDialogFieldListener { + private class ContainerFieldAdapter implements IStringButtonAdapter, + IDialogFieldListener { // -------- IStringButtonAdapter public void changeControlPressed(DialogField field) { containerChangeControlPressed(field); } - + // -------- IDialogFieldListener public void dialogFieldChanged(DialogField field) { containerDialogFieldChanged(field); } } - + private void containerChangeControlPressed(DialogField field) { // take the current jproject as init element of the dialog -// IPackageFragmentRoot root= getPackageFragmentRoot(); -// root= chooseSourceContainer(root); -// if (root != null) { -// setPackageFragmentRoot(root, true); -// } + // IPackageFragmentRoot root= getPackageFragmentRoot(); + // root= chooseSourceContainer(root); + // if (root != null) { + // setPackageFragmentRoot(root, true); + // } } - + private void containerDialogFieldChanged(DialogField field) { if (field == fContainerDialogField) { - fContainerStatus= containerChanged(); + fContainerStatus = containerChanged(); } // tell all others handleFieldChanged(CONTAINER); } - + // ----------- validation ---------- - + /** - * This method is a hook which gets called after the source folder's - * text input field has changed. This default implementation updates - * the model and returns an error status. The underlying model - * is only valid if the returned status is OK. + * This method is a hook which gets called after the source folder's text + * input field has changed. This default implementation updates the model + * and returns an error status. The underlying model is only valid if the + * returned status is OK. * * @return the model's error status */ protected IStatus containerChanged() { - StatusInfo status= new StatusInfo(); - - fCurrRoot= null; - String str= getPackageFragmentRootText(); + StatusInfo status = new StatusInfo(); + + fCurrRoot = null; + String str = getPackageFragmentRootText(); if (str.length() == 0) { - status.setError(NewWizardMessages.getString("NewContainerWizardPage.error.EnterContainerName")); //$NON-NLS-1$ + status + .setError(NewWizardMessages + .getString("NewContainerWizardPage.error.EnterContainerName")); //$NON-NLS-1$ return status; } - IPath path= new Path(str); - IResource res= fWorkspaceRoot.findMember(path); + IPath path = new Path(str); + IResource res = fWorkspaceRoot.findMember(path); if (res != null) { - int resType= res.getType(); + int resType = res.getType(); if (resType == IResource.PROJECT || resType == IResource.FOLDER) { - IProject proj= res.getProject(); + IProject proj = res.getProject(); if (!proj.isOpen()) { - status.setError(NewWizardMessages.getFormattedString("NewContainerWizardPage.error.ProjectClosed", proj.getFullPath().toString())); //$NON-NLS-1$ + status + .setError(NewWizardMessages + .getFormattedString( + "NewContainerWizardPage.error.ProjectClosed", proj.getFullPath().toString())); //$NON-NLS-1$ return status; - } - IJavaProject jproject= JavaCore.create(proj); -// fCurrRoot= jproject.getPackageFragmentRoot(res); -// if (res.exists()) { -// try { -// if (!proj.hasNature(JavaCore.NATURE_ID)) { -// if (resType == IResource.PROJECT) { -// status.setError(NewWizardMessages.getString("NewContainerWizardPage.warning.NotAJavaProject")); //$NON-NLS-1$ -// } else { -// status.setWarning(NewWizardMessages.getString("NewContainerWizardPage.warning.NotInAJavaProject")); //$NON-NLS-1$ -// } -// return status; -// } -// } catch (CoreException e) { -// status.setWarning(NewWizardMessages.getString("NewContainerWizardPage.warning.NotAJavaProject")); //$NON-NLS-1$ -// } -// if (!jproject.isOnClasspath(fCurrRoot)) { -// status.setWarning(NewWizardMessages.getFormattedString("NewContainerWizardPage.warning.NotOnClassPath", str)); //$NON-NLS-1$ -// } -// if (fCurrRoot.isArchive()) { -// status.setError(NewWizardMessages.getFormattedString("NewContainerWizardPage.error.ContainerIsBinary", str)); //$NON-NLS-1$ -// return status; -// } -// } + } + IJavaProject jproject = JavaCore.create(proj); + // fCurrRoot= jproject.getPackageFragmentRoot(res); + // if (res.exists()) { + // try { + // if (!proj.hasNature(JavaCore.NATURE_ID)) { + // if (resType == IResource.PROJECT) { + // status.setError(NewWizardMessages.getString("NewContainerWizardPage.warning.NotAJavaProject")); + // //$NON-NLS-1$ + // } else { + // status.setWarning(NewWizardMessages.getString("NewContainerWizardPage.warning.NotInAJavaProject")); + // //$NON-NLS-1$ + // } + // return status; + // } + // } catch (CoreException e) { + // status.setWarning(NewWizardMessages.getString("NewContainerWizardPage.warning.NotAJavaProject")); + // //$NON-NLS-1$ + // } + // if (!jproject.isOnClasspath(fCurrRoot)) { + // status.setWarning(NewWizardMessages.getFormattedString("NewContainerWizardPage.warning.NotOnClassPath", + // str)); //$NON-NLS-1$ + // } + // if (fCurrRoot.isArchive()) { + // status.setError(NewWizardMessages.getFormattedString("NewContainerWizardPage.error.ContainerIsBinary", + // str)); //$NON-NLS-1$ + // return status; + // } + // } return status; } else { - status.setError(NewWizardMessages.getFormattedString("NewContainerWizardPage.error.NotAFolder", str)); //$NON-NLS-1$ + status.setError(NewWizardMessages.getFormattedString( + "NewContainerWizardPage.error.NotAFolder", str)); //$NON-NLS-1$ return status; } } else { - status.setError(NewWizardMessages.getFormattedString("NewContainerWizardPage.error.ContainerDoesNotExist", str)); //$NON-NLS-1$ + status.setError(NewWizardMessages.getFormattedString( + "NewContainerWizardPage.error.ContainerDoesNotExist", str)); //$NON-NLS-1$ return status; } } - + // -------- update message ---------------- - + /** - * Hook method that gets called when a field on this page has changed. For this page the - * method gets called when the source folder field changes. + * Hook method that gets called when a field on this page has changed. For + * this page the method gets called when the source folder field changes. *

                                                      - * Every sub type is responsible to call this method when a field on its page has changed. - * Subtypes override (extend) the method to add verification when a own field has a - * dependency to an other field. For example the class name input must be verified - * again when the package field changes (check for duplicated class names). + * Every sub type is responsible to call this method when a field on its + * page has changed. Subtypes override (extend) the method to add + * verification when a own field has a dependency to an other field. For + * example the class name input must be verified again when the package + * field changes (check for duplicated class names). * - * @param fieldName The name of the field that has changed (field id). For the - * source folder the field id is CONTAINER + * @param fieldName + * The name of the field that has changed (field id). For the + * source folder the field id is CONTAINER */ protected void handleFieldChanged(String fieldName) { - } - - + } + // ---- get ---------------- - + /** * Returns the workspace root. * * @return the workspace root - */ + */ protected IWorkspaceRoot getWorkspaceRoot() { return fWorkspaceRoot; - } - + } + /** - * Returns the IPackageFragmentRoot that corresponds to the current - * value of the source folder field. + * Returns the IPackageFragmentRoot that corresponds to the + * current value of the source folder field. * - * @return the IPackageFragmentRoot or null if the current source - * folder value is not a valid package fragment root + * @return the IPackageFragmentRoot or null if the current + * source folder value is not a valid package fragment root * - */ + */ public IPackageFragmentRoot getPackageFragmentRoot() { return fCurrRoot; } @@ -349,85 +378,96 @@ public abstract class NewContainerWizardPage extends NewElementWizardPage { * Returns the current text of source folder text field. * * @return the text of the source folder text field - */ + */ public String getPackageFragmentRootText() { return fContainerDialogField.getText(); } - - + /** - * Sets the current source folder (model and text field) to the given package - * fragment root. + * Sets the current source folder (model and text field) to the given + * package fragment root. * - * @param canBeModified if false the source folder field can - * not be changed by the user. If true the field is editable - */ -// public void setPackageFragmentRoot(IPackageFragmentRoot root, boolean canBeModified) { -// fCurrRoot= root; -// String str= (root == null) ? "" : root.getPath().makeRelative().toString(); //$NON-NLS-1$ -// fContainerDialogField.setText(str); -// fContainerDialogField.setEnabled(canBeModified); -// } - + * @param canBeModified + * if false the source folder field can not be + * changed by the user. If true the field is + * editable + */ + // public void setPackageFragmentRoot(IPackageFragmentRoot root, boolean + // canBeModified) { + // fCurrRoot= root; + // String str= (root == null) ? "" : + // root.getPath().makeRelative().toString(); //$NON-NLS-1$ + // fContainerDialogField.setText(str); + // fContainerDialogField.setEnabled(canBeModified); + // } // ------------- choose source container dialog - -// private IPackageFragmentRoot chooseSourceContainer(IJavaElement initElement) { -// Class[] acceptedClasses= new Class[] { IPackageFragmentRoot.class, IJavaProject.class }; -// TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, false) { -// public boolean isSelectedValid(Object element) { -// try { -// if (element instanceof IJavaProject) { -// IJavaProject jproject= (IJavaProject)element; -// IPath path= jproject.getProject().getFullPath(); -// return (jproject.findPackageFragmentRoot(path) != null); -// } else if (element instanceof IPackageFragmentRoot) { -// return (((IPackageFragmentRoot)element).getKind() == IPackageFragmentRoot.K_SOURCE); -// } -// return true; -// } catch (JavaModelException e) { -// PHPeclipsePlugin.log(e.getStatus()); // just log, no ui in validation -// } -// return false; -// } -// }; -// -// acceptedClasses= new Class[] { IJavaModel.class, IPackageFragmentRoot.class, IJavaProject.class }; -// ViewerFilter filter= new TypedViewerFilter(acceptedClasses) { -// public boolean select(Viewer viewer, Object parent, Object element) { -// if (element instanceof IPackageFragmentRoot) { -// try { -// return (((IPackageFragmentRoot)element).getKind() == IPackageFragmentRoot.K_SOURCE); -// } catch (JavaModelException e) { -// PHPeclipsePlugin.log(e.getStatus()); // just log, no ui in validation -// return false; -// } -// } -// return super.select(viewer, parent, element); -// } -// }; -// -// StandardJavaElementContentProvider provider= new StandardJavaElementContentProvider(); -// ILabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT); -// ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), labelProvider, provider); -// dialog.setValidator(validator); -// dialog.setSorter(new JavaElementSorter()); -// dialog.setTitle(NewWizardMessages.getString("NewContainerWizardPage.ChooseSourceContainerDialog.title")); //$NON-NLS-1$ -// dialog.setMessage(NewWizardMessages.getString("NewContainerWizardPage.ChooseSourceContainerDialog.description")); //$NON-NLS-1$ -// dialog.addFilter(filter); -// dialog.setInput(JavaCore.create(fWorkspaceRoot)); -// dialog.setInitialSelection(initElement); -// -// if (dialog.open() == ElementTreeSelectionDialog.OK) { -// Object element= dialog.getFirstResult(); -// if (element instanceof IJavaProject) { -// IJavaProject jproject= (IJavaProject)element; -// return jproject.getPackageFragmentRoot(jproject.getProject()); -// } else if (element instanceof IPackageFragmentRoot) { -// return (IPackageFragmentRoot)element; -// } -// return null; -// } -// return null; -// } - + // private IPackageFragmentRoot chooseSourceContainer(IJavaElement + // initElement) { + // Class[] acceptedClasses= new Class[] { IPackageFragmentRoot.class, + // IJavaProject.class }; + // TypedElementSelectionValidator validator= new + // TypedElementSelectionValidator(acceptedClasses, false) { + // public boolean isSelectedValid(Object element) { + // try { + // if (element instanceof IJavaProject) { + // IJavaProject jproject= (IJavaProject)element; + // IPath path= jproject.getProject().getFullPath(); + // return (jproject.findPackageFragmentRoot(path) != null); + // } else if (element instanceof IPackageFragmentRoot) { + // return (((IPackageFragmentRoot)element).getKind() == + // IPackageFragmentRoot.K_SOURCE); + // } + // return true; + // } catch (JavaModelException e) { + // PHPeclipsePlugin.log(e.getStatus()); // just log, no ui in validation + // } + // return false; + // } + // }; + // + // acceptedClasses= new Class[] { IJavaModel.class, + // IPackageFragmentRoot.class, IJavaProject.class }; + // ViewerFilter filter= new TypedViewerFilter(acceptedClasses) { + // public boolean select(Viewer viewer, Object parent, Object element) { + // if (element instanceof IPackageFragmentRoot) { + // try { + // return (((IPackageFragmentRoot)element).getKind() == + // IPackageFragmentRoot.K_SOURCE); + // } catch (JavaModelException e) { + // PHPeclipsePlugin.log(e.getStatus()); // just log, no ui in validation + // return false; + // } + // } + // return super.select(viewer, parent, element); + // } + // }; + // + // StandardJavaElementContentProvider provider= new + // StandardJavaElementContentProvider(); + // ILabelProvider labelProvider= new + // JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT); + // ElementTreeSelectionDialog dialog= new + // ElementTreeSelectionDialog(getShell(), labelProvider, provider); + // dialog.setValidator(validator); + // dialog.setSorter(new JavaElementSorter()); + // dialog.setTitle(NewWizardMessages.getString("NewContainerWizardPage.ChooseSourceContainerDialog.title")); + // //$NON-NLS-1$ + // dialog.setMessage(NewWizardMessages.getString("NewContainerWizardPage.ChooseSourceContainerDialog.description")); + // //$NON-NLS-1$ + // dialog.addFilter(filter); + // dialog.setInput(JavaCore.create(fWorkspaceRoot)); + // dialog.setInitialSelection(initElement); + // + // if (dialog.open() == ElementTreeSelectionDialog.OK) { + // Object element= dialog.getFirstResult(); + // if (element instanceof IJavaProject) { + // IJavaProject jproject= (IJavaProject)element; + // return jproject.getPackageFragmentRoot(jproject.getProject()); + // } else if (element instanceof IPackageFragmentRoot) { + // return (IPackageFragmentRoot)element; + // } + // return null; + // } + // return null; + // } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewElementWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewElementWizardPage.java index 424404a..653d4a0 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewElementWizardPage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewElementWizardPage.java @@ -26,59 +26,63 @@ import org.eclipse.jface.wizard.WizardPage; public abstract class NewElementWizardPage extends WizardPage { private IStatus fCurrStatus; - + private boolean fPageVisible; /** * Creates a NewElementWizardPage. * - * @param name the wizard page's name - */ + * @param name + * the wizard page's name + */ public NewElementWizardPage(String name) { super(name); - fPageVisible= false; - fCurrStatus= new StatusInfo(); + fPageVisible = false; + fCurrStatus = new StatusInfo(); } - + // ---- WizardPage ---------------- - + /* * @see WizardPage#becomesVisible */ public void setVisible(boolean visible) { super.setVisible(visible); - fPageVisible= visible; + fPageVisible = visible; // policy: wizards are not allowed to come up with an error message if (visible && fCurrStatus.matches(IStatus.ERROR)) { - StatusInfo status= new StatusInfo(); - status.setError(""); //$NON-NLS-1$ - fCurrStatus= status; - } + StatusInfo status = new StatusInfo(); + status.setError(""); //$NON-NLS-1$ + fCurrStatus = status; + } updateStatus(fCurrStatus); - } + } /** * Updates the status line and the ok button according to the given status * - * @param status status to apply + * @param status + * status to apply */ protected void updateStatus(IStatus status) { - fCurrStatus= status; + fCurrStatus = status; setPageComplete(!status.matches(IStatus.ERROR)); if (fPageVisible) { StatusUtil.applyToStatusLine(this, status); } } - + /** - * Updates the status line and the ok button according to the status evaluate from - * an array of status. The most severe error is taken. In case that two status with - * the same severity exists, the status with lower index is taken. + * Updates the status line and the ok button according to the status + * evaluate from an array of status. The most severe error is taken. In case + * that two status with the same severity exists, the status with lower + * index is taken. * - * @param status the array of status + * @param status + * the array of status */ protected void updateStatus(IStatus[] status) { updateStatus(StatusUtil.getMostSevere(status)); - } - + } + } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewTypeWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewTypeWizardPage.java index eda96b3..a73147a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewTypeWizardPage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewTypeWizardPage.java @@ -67,14 +67,14 @@ import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; /** - * The class NewTypeWizardPage contains controls and validation routines - * for a 'New Type WizardPage'. Implementors decide which components to add and to enable. - * Implementors can also customize the validation code. NewTypeWizardPage - * is intended to serve as base class of all wizards that create types like applets, servlets, classes, - * interfaces, etc. + * The class NewTypeWizardPage contains controls and validation + * routines for a 'New Type WizardPage'. Implementors decide which components to + * add and to enable. Implementors can also customize the validation code. + * NewTypeWizardPage is intended to serve as base class of all + * wizards that create types like applets, servlets, classes, interfaces, etc. *

                                                      - * See NewClassWizardPage or NewInterfaceWizardPage for an - * example usage of NewTypeWizardPage. + * See NewClassWizardPage or NewInterfaceWizardPage + * for an example usage of NewTypeWizardPage. *

                                                      * * @see net.sourceforge.phpdt.ui.wizards.NewClassWizardPage @@ -84,1638 +84,1871 @@ import org.eclipse.swt.widgets.Control; */ public abstract class NewTypeWizardPage extends NewContainerWizardPage { - /** - * Class used in stub creation routines to add needed imports to a - * compilation unit. - */ - // public static class ImportsManager { - // - // private IImportsStructure fImportsStructure; - // - // /* package */ ImportsManager(IImportsStructure structure) { - // fImportsStructure= structure; - // } - // - // /* package */ IImportsStructure getImportsStructure() { - // return fImportsStructure; - // } - // - // /** - // * Adds a new import declaration that is sorted in the existing imports. - // * If an import already exists or the import would conflict with another import - // * of an other type with the same simple name the import is not added. - // * - // * @param qualifiedTypeName The fully qualified name of the type to import - // * (dot separated) - // * @return Returns the simple type name that can be used in the code or the - // * fully qualified type name if an import conflict prevented the import - // */ - // public String addImport(String qualifiedTypeName) { - // return fImportsStructure.addImport(qualifiedTypeName); - // } - // } - - /** Public access flag. See The Java Virtual Machine Specification for more details. */ - public int F_PUBLIC = Flags.AccPublic; - /** Private access flag. See The Java Virtual Machine Specification for more details. */ - public int F_PRIVATE = Flags.AccPrivate; - /** Protected access flag. See The Java Virtual Machine Specification for more details. */ - public int F_PROTECTED = Flags.AccProtected; - /** Static access flag. See The Java Virtual Machine Specification for more details. */ - public int F_STATIC = Flags.AccStatic; - /** Final access flag. See The Java Virtual Machine Specification for more details. */ - public int F_FINAL = Flags.AccFinal; - /** Abstract property flag. See The Java Virtual Machine Specification for more details. */ - // public int F_ABSTRACT = Flags.AccAbstract; - - private final static String PAGE_NAME = "NewTypeWizardPage"; //$NON-NLS-1$ - - /** Field ID of the package input field */ - protected final static String PACKAGE = PAGE_NAME + ".package"; //$NON-NLS-1$ - /** Field ID of the eclosing type input field */ - protected final static String ENCLOSING = PAGE_NAME + ".enclosing"; //$NON-NLS-1$ - /** Field ID of the enclosing type checkbox */ - protected final static String ENCLOSINGSELECTION = ENCLOSING + ".selection"; //$NON-NLS-1$ - /** Field ID of the type name input field */ - protected final static String TYPENAME = PAGE_NAME + ".typename"; //$NON-NLS-1$ - /** Field ID of the super type input field */ - protected final static String SUPER = PAGE_NAME + ".superclass"; //$NON-NLS-1$ - /** Field ID of the super interfaces input field */ - protected final static String INTERFACES = PAGE_NAME + ".interfaces"; //$NON-NLS-1$ - /** Field ID of the modifier checkboxes */ - protected final static String MODIFIERS = PAGE_NAME + ".modifiers"; //$NON-NLS-1$ - /** Field ID of the method stubs checkboxes */ - protected final static String METHODS = PAGE_NAME + ".methods"; //$NON-NLS-1$ - - private class InterfacesListLabelProvider extends LabelProvider { - - private Image fInterfaceImage; - - public InterfacesListLabelProvider() { - super(); - fInterfaceImage = PHPUiImages.get(PHPUiImages.IMG_OBJS_INTERFACE); - } - - public Image getImage(Object element) { - return fInterfaceImage; - } - } - - private StringButtonStatusDialogField fPackageDialogField; - - private SelectionButtonDialogField fEnclosingTypeSelection; - private StringButtonDialogField fEnclosingTypeDialogField; - - private boolean fCanModifyPackage; - private boolean fCanModifyEnclosingType; - - private IPackageFragment fCurrPackage; - - // private IType fCurrEnclosingType; - private StringDialogField fTypeNameDialogField; - - private StringButtonDialogField fSuperClassDialogField; - private ListDialogField fSuperInterfacesDialogField; - - // private IType fSuperClass; - - private SelectionButtonDialogFieldGroup fAccMdfButtons; - private SelectionButtonDialogFieldGroup fOtherMdfButtons; - - private IType fCreatedType; - - protected IStatus fEnclosingTypeStatus; - protected IStatus fPackageStatus; - protected IStatus fTypeNameStatus; - // protected IStatus fSuperClassStatus; - protected IStatus fModifierStatus; - // protected IStatus fSuperInterfacesStatus; - - private boolean fIsClass; - private int fStaticMdfIndex; - - private final int PUBLIC_INDEX = 0, DEFAULT_INDEX = 1, PRIVATE_INDEX = 2, PROTECTED_INDEX = 3; - private final int ABSTRACT_INDEX = 0, FINAL_INDEX = 1; - - /** - * Creates a new NewTypeWizardPage - * - * @param isClass true if a new class is to be created; otherwise - * an interface is to be created - * @param pageName the wizard page's name - */ - public NewTypeWizardPage(boolean isClass, String pageName) { - super(pageName); - fCreatedType= null; - - fIsClass = isClass; - - TypeFieldsAdapter adapter = new TypeFieldsAdapter(); - - fPackageDialogField = new StringButtonStatusDialogField(adapter); - fPackageDialogField.setDialogFieldListener(adapter); - fPackageDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.package.label")); //$NON-NLS-1$ - fPackageDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.package.button")); //$NON-NLS-1$ - fPackageDialogField.setStatusWidthHint(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$ - - fEnclosingTypeSelection = new SelectionButtonDialogField(SWT.CHECK); - fEnclosingTypeSelection.setDialogFieldListener(adapter); - fEnclosingTypeSelection.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.enclosing.selection.label")); //$NON-NLS-1$ - - fEnclosingTypeDialogField = new StringButtonDialogField(adapter); - fEnclosingTypeDialogField.setDialogFieldListener(adapter); - fEnclosingTypeDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.enclosing.button")); //$NON-NLS-1$ - - fTypeNameDialogField = new StringDialogField(); - fTypeNameDialogField.setDialogFieldListener(adapter); - fTypeNameDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.typename.label")); //$NON-NLS-1$ - - fSuperClassDialogField = new StringButtonDialogField(adapter); - fSuperClassDialogField.setDialogFieldListener(adapter); - fSuperClassDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.superclass.label")); //$NON-NLS-1$ - fSuperClassDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.superclass.button")); //$NON-NLS-1$ - - String[] addButtons = new String[] { - /* 0 */ - NewWizardMessages.getString("NewTypeWizardPage.interfaces.add"), //$NON-NLS-1$ - /* 1 */ - null, - /* 2 */ - NewWizardMessages.getString("NewTypeWizardPage.interfaces.remove") //$NON-NLS-1$ - }; - fSuperInterfacesDialogField = new ListDialogField(adapter, addButtons, new InterfacesListLabelProvider()); - fSuperInterfacesDialogField.setDialogFieldListener(adapter); - String interfaceLabel = fIsClass ? NewWizardMessages.getString("NewTypeWizardPage.interfaces.class.label") : NewWizardMessages.getString("NewTypeWizardPage.interfaces.ifc.label"); //$NON-NLS-1$ //$NON-NLS-2$ - fSuperInterfacesDialogField.setLabelText(interfaceLabel); - fSuperInterfacesDialogField.setRemoveButtonIndex(2); - - String[] buttonNames1 = new String[] { - /* 0 == PUBLIC_INDEX */ - NewWizardMessages.getString("NewTypeWizardPage.modifiers.public"), //$NON-NLS-1$ - /* 1 == DEFAULT_INDEX */ - NewWizardMessages.getString("NewTypeWizardPage.modifiers.default"), //$NON-NLS-1$ - /* 2 == PRIVATE_INDEX */ - NewWizardMessages.getString("NewTypeWizardPage.modifiers.private"), //$NON-NLS-1$ - /* 3 == PROTECTED_INDEX*/ - NewWizardMessages.getString("NewTypeWizardPage.modifiers.protected") //$NON-NLS-1$ - }; - fAccMdfButtons = new SelectionButtonDialogFieldGroup(SWT.RADIO, buttonNames1, 4); - fAccMdfButtons.setDialogFieldListener(adapter); - fAccMdfButtons.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.modifiers.acc.label")); //$NON-NLS-1$ - fAccMdfButtons.setSelection(0, true); - - String[] buttonNames2; - if (fIsClass) { - buttonNames2 = new String[] { - /* 0 == ABSTRACT_INDEX */ - NewWizardMessages.getString("NewTypeWizardPage.modifiers.abstract"), //$NON-NLS-1$ - /* 1 == FINAL_INDEX */ - NewWizardMessages.getString("NewTypeWizardPage.modifiers.final"), //$NON-NLS-1$ - /* 2 */ - NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$ - }; - fStaticMdfIndex = 2; // index of the static checkbox is 2 - } else { - buttonNames2 = new String[] { NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$ - }; - fStaticMdfIndex = 0; // index of the static checkbox is 0 - } - - fOtherMdfButtons = new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames2, 4); - fOtherMdfButtons.setDialogFieldListener(adapter); - - fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, false); - fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, false); - fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, false); - - fPackageStatus = new StatusInfo(); - fEnclosingTypeStatus = new StatusInfo(); - - fCanModifyPackage = true; - fCanModifyEnclosingType = true; - updateEnableState(); - - fTypeNameStatus = new StatusInfo(); - // fSuperClassStatus= new StatusInfo(); - // fSuperInterfacesStatus= new StatusInfo(); - fModifierStatus = new StatusInfo(); - } - - /** - * Initializes all fields provided by the page with a given selection. - * - * @param elem the selection used to intialize this page or - * null if no selection was available - */ - protected void initTypePage(IJavaElement elem) { - String initSuperclass = "java.lang.Object"; //$NON-NLS-1$ - ArrayList initSuperinterfaces = new ArrayList(5); - - IPackageFragment pack = null; - IType enclosingType = null; - - if (elem != null) { - // evaluate the enclosing type - pack = (IPackageFragment) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT); - IType typeInCU = (IType) elem.getAncestor(IJavaElement.TYPE); - if (typeInCU != null) { - if (typeInCU.getCompilationUnit() != null) { - enclosingType = typeInCU; - } - } else { - ICompilationUnit cu = (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT); - if (cu != null) { - // enclosingType= cu.findPrimaryType(); - } - } - - // try { - // IType type= null; - // if (elem.getElementType() == IJavaElement.TYPE) { - // type= (IType)elem; - // if (type.exists()) { - // String superName= JavaModelUtil.getFullyQualifiedName(type); - // if (type.isInterface()) { - // initSuperinterfaces.add(superName); - // } else { - // initSuperclass= superName; - // } - // } - // } - // } catch (JavaModelException e) { - // PHPeclipsePlugin.log(e); - // // ignore this exception now - // } - } - - setPackageFragment(pack, true); - // setEnclosingType(enclosingType, true); - setEnclosingTypeSelection(false, true); - - setTypeName("", true); //$NON-NLS-1$ - setSuperClass(initSuperclass, true); - setSuperInterfaces(initSuperinterfaces, true); - } - - // -------- UI Creation --------- - - /** - * Creates a separator line. Expects a GridLayout with at least 1 column. - * - * @param composite the parent composite - * @param nColumns number of columns to span - */ - protected void createSeparator(Composite composite, int nColumns) { - (new Separator(SWT.SEPARATOR | SWT.HORIZONTAL)).doFillIntoGrid(composite, nColumns, convertHeightInCharsToPixels(1)); - } - - /** - * Creates the controls for the package name field. Expects a GridLayout with at - * least 4 columns. - * - * @param composite the parent composite - * @param nColumns number of columns to span - */ - protected void createPackageControls(Composite composite, int nColumns) { - fPackageDialogField.doFillIntoGrid(composite, nColumns); - LayoutUtil.setWidthHint(fPackageDialogField.getTextControl(null), getMaxFieldWidth()); - LayoutUtil.setHorizontalGrabbing(fPackageDialogField.getTextControl(null)); - } - - /** - * Creates the controls for the enclosing type name field. Expects a GridLayout with at - * least 4 columns. - * - * @param composite the parent composite - * @param nColumns number of columns to span - */ - protected void createEnclosingTypeControls(Composite composite, int nColumns) { - // #6891 - Composite tabGroup = new Composite(composite, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.marginWidth = 0; - layout.marginHeight = 0; - tabGroup.setLayout(layout); - - fEnclosingTypeSelection.doFillIntoGrid(tabGroup, 1); - - Control c = fEnclosingTypeDialogField.getTextControl(composite); - GridData gd = new GridData(GridData.FILL_HORIZONTAL); - gd.widthHint = getMaxFieldWidth(); - gd.horizontalSpan = 2; - c.setLayoutData(gd); - - Button button = fEnclosingTypeDialogField.getChangeControl(composite); - gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - gd.heightHint = SWTUtil.getButtonHeightHint(button); - gd.widthHint = SWTUtil.getButtonWidthHint(button); - button.setLayoutData(gd); - } - - /** - * Creates the controls for the type name field. Expects a GridLayout with at - * least 2 columns. - * - * @param composite the parent composite - * @param nColumns number of columns to span - */ - protected void createTypeNameControls(Composite composite, int nColumns) { - fTypeNameDialogField.doFillIntoGrid(composite, nColumns - 1); - DialogField.createEmptySpace(composite); - - LayoutUtil.setWidthHint(fTypeNameDialogField.getTextControl(null), getMaxFieldWidth()); - } - - /** - * Creates the controls for the modifiers radio/ceckbox buttons. Expects a - * GridLayout with at least 3 columns. - * - * @param composite the parent composite - * @param nColumns number of columns to span - */ - protected void createModifierControls(Composite composite, int nColumns) { - LayoutUtil.setHorizontalSpan(fAccMdfButtons.getLabelControl(composite), 1); - - Control control = fAccMdfButtons.getSelectionButtonsGroup(composite); - GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - gd.horizontalSpan = nColumns - 2; - control.setLayoutData(gd); - - DialogField.createEmptySpace(composite); - - DialogField.createEmptySpace(composite); - - control = fOtherMdfButtons.getSelectionButtonsGroup(composite); - gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - gd.horizontalSpan = nColumns - 2; - control.setLayoutData(gd); - - DialogField.createEmptySpace(composite); - } - - /** - * Creates the controls for the superclass name field. Expects a GridLayout - * with at least 3 columns. - * - * @param composite the parent composite - * @param nColumns number of columns to span - */ - protected void createSuperClassControls(Composite composite, int nColumns) { - fSuperClassDialogField.doFillIntoGrid(composite, nColumns); - LayoutUtil.setWidthHint(fSuperClassDialogField.getTextControl(null), getMaxFieldWidth()); - } - - /** - * Creates the controls for the superclass name field. Expects a GridLayout with - * at least 3 columns. - * - * @param composite the parent composite - * @param nColumns number of columns to span - */ - protected void createSuperInterfacesControls(Composite composite, int nColumns) { - fSuperInterfacesDialogField.doFillIntoGrid(composite, nColumns); - GridData gd = (GridData) fSuperInterfacesDialogField.getListControl(null).getLayoutData(); - if (fIsClass) { - gd.heightHint = convertHeightInCharsToPixels(3); - } else { - gd.heightHint = convertHeightInCharsToPixels(6); - } - gd.grabExcessVerticalSpace = false; - gd.widthHint = getMaxFieldWidth(); - } - - /** - * Sets the focus on the type name input field. - */ - protected void setFocus() { - fTypeNameDialogField.setFocus(); - } - - // -------- TypeFieldsAdapter -------- - - private class TypeFieldsAdapter implements IStringButtonAdapter, IDialogFieldListener, IListAdapter { - - // -------- IStringButtonAdapter - public void changeControlPressed(DialogField field) { - // typePageChangeControlPressed(field); - } - - // -------- IListAdapter - public void customButtonPressed(ListDialogField field, int index) { - // typePageCustomButtonPressed(field, index); - } - - public void selectionChanged(ListDialogField field) { - } - - // -------- IDialogFieldListener - public void dialogFieldChanged(DialogField field) { - typePageDialogFieldChanged(field); - } - - public void doubleClicked(ListDialogField field) { - } - } - - // private void typePageChangeControlPressed(DialogField field) { - // if (field == fPackageDialogField) { - // IPackageFragment pack= choosePackage(); - // if (pack != null) { - // fPackageDialogField.setText(pack.getElementName()); - // } - // } else if (field == fEnclosingTypeDialogField) { - // IType type= chooseEnclosingType(); - // if (type != null) { - // fEnclosingTypeDialogField.setText(JavaModelUtil.getFullyQualifiedName(type)); - // } - // } else if (field == fSuperClassDialogField) { - // IType type= chooseSuperType(); - // if (type != null) { - // fSuperClassDialogField.setText(JavaModelUtil.getFullyQualifiedName(type)); - // } - // } - // } - - // private void typePageCustomButtonPressed(DialogField field, int index) { - // if (field == fSuperInterfacesDialogField) { - // chooseSuperInterfaces(); - // } - // } - - /* - * A field on the type has changed. The fields' status and all dependend - * status are updated. - */ - private void typePageDialogFieldChanged(DialogField field) { - String fieldName = null; - if (field == fPackageDialogField) { - fPackageStatus = packageChanged(); - updatePackageStatusLabel(); - fTypeNameStatus = typeNameChanged(); - // fSuperClassStatus= superClassChanged(); - fieldName = PACKAGE; - } else if (field == fEnclosingTypeDialogField) { - // fEnclosingTypeStatus= enclosingTypeChanged(); - fTypeNameStatus = typeNameChanged(); - // fSuperClassStatus= superClassChanged(); - fieldName = ENCLOSING; - } else if (field == fEnclosingTypeSelection) { - updateEnableState(); - boolean isEnclosedType = isEnclosingTypeSelected(); - if (!isEnclosedType) { - if (fAccMdfButtons.isSelected(PRIVATE_INDEX) || fAccMdfButtons.isSelected(PROTECTED_INDEX)) { - fAccMdfButtons.setSelection(PRIVATE_INDEX, false); - fAccMdfButtons.setSelection(PROTECTED_INDEX, false); - fAccMdfButtons.setSelection(PUBLIC_INDEX, true); - } - if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { - fOtherMdfButtons.setSelection(fStaticMdfIndex, false); - } - } - fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, isEnclosedType && fIsClass); - fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, isEnclosedType && fIsClass); - fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, isEnclosedType); - fTypeNameStatus = typeNameChanged(); - // fSuperClassStatus= superClassChanged(); - fieldName = ENCLOSINGSELECTION; - } else if (field == fTypeNameDialogField) { - fTypeNameStatus = typeNameChanged(); - fieldName = TYPENAME; - } else if (field == fSuperClassDialogField) { - // fSuperClassStatus= superClassChanged(); - fieldName = SUPER; - } else if (field == fSuperInterfacesDialogField) { - // fSuperInterfacesStatus= superInterfacesChanged(); - fieldName = INTERFACES; - } else if (field == fOtherMdfButtons) { - fModifierStatus = modifiersChanged(); - fieldName = MODIFIERS; - } else { - fieldName = METHODS; - } - // tell all others - handleFieldChanged(fieldName); - } - - // -------- update message ---------------- - - /* - * @see net.sourceforge.phpdt.ui.wizards.NewContainerWizardPage#handleFieldChanged(String) - */ - protected void handleFieldChanged(String fieldName) { - super.handleFieldChanged(fieldName); - if (fieldName == CONTAINER) { - fPackageStatus = packageChanged(); - // fEnclosingTypeStatus= enclosingTypeChanged(); - fTypeNameStatus = typeNameChanged(); - // fSuperClassStatus= superClassChanged(); - // fSuperInterfacesStatus= superInterfacesChanged(); - } - } - - // ---- set / get ---------------- - - /** - * Returns the text of the package input field. - * - * @return the text of the package input field - */ - public String getPackageText() { - return fPackageDialogField.getText(); - } - - /** - * Returns the text of the enclosing type input field. - * - * @return the text of the enclosing type input field - */ - public String getEnclosingTypeText() { - return fEnclosingTypeDialogField.getText(); - } - - /** - * Returns the package fragment corresponding to the current input. - * - * @return a package fragement or null if the input - * could not be resolved. - */ - public IPackageFragment getPackageFragment() { - if (!isEnclosingTypeSelected()) { - return fCurrPackage; - } else { - // if (fCurrEnclosingType != null) { - // return fCurrEnclosingType.getPackageFragment(); - // } - } - return null; - } - - /** - * Sets the package fragment to the given value. The method updates the model - * and the text of the control. - * - * @param pack the package fragement to be set - * @param canBeModified if true the package fragment is - * editable; otherwise it is read-only. - */ - public void setPackageFragment(IPackageFragment pack, boolean canBeModified) { - fCurrPackage = pack; - fCanModifyPackage = canBeModified; - String str = (pack == null) ? "" : pack.getElementName(); //$NON-NLS-1$ - fPackageDialogField.setText(str); - updateEnableState(); - } - - /** - * Returns the enclosing type corresponding to the current input. - * - * @return the enclosing type or null if the enclosing type is - * not selected or the input could not be resolved - */ - public IType getEnclosingType() { - // if (isEnclosingTypeSelected()) { - // return fCurrEnclosingType; - // } - return null; - } - - /** - * Sets the enclosing type. The method updates the underlying model - * and the text of the control. - * - * @param type the enclosing type - * @param canBeModified if true the enclosing type field is - * editable; otherwise it is read-only. - */ - // public void setEnclosingType(IType type, boolean canBeModified) { - // fCurrEnclosingType= type; - // fCanModifyEnclosingType= canBeModified; - // String str= (type == null) ? "" : JavaModelUtil.getFullyQualifiedName(type); //$NON-NLS-1$ - // fEnclosingTypeDialogField.setText(str); - // updateEnableState(); - // } - - /** - * Returns the selection state of the enclosing type checkbox. - * - * @return the seleciton state of the enclosing type checkbox - */ - public boolean isEnclosingTypeSelected() { - return fEnclosingTypeSelection.isSelected(); - } - - /** - * Sets the enclosing type checkbox's selection state. - * - * @param isSelected the checkbox's selection state - * @param canBeModified if true the enclosing type checkbox is - * modifiable; otherwise it is read-only. - */ - public void setEnclosingTypeSelection(boolean isSelected, boolean canBeModified) { - fEnclosingTypeSelection.setSelection(isSelected); - fEnclosingTypeSelection.setEnabled(canBeModified); - updateEnableState(); - } - - /** - * Returns the type name entered into the type input field. - * - * @return the type name - */ - public String getTypeName() { - return fTypeNameDialogField.getText(); - } - - /** - * Sets the type name input field's text to the given value. Method doesn't update - * the model. - * - * @param name the new type name - * @param canBeModified if true the enclosing type name field is - * editable; otherwise it is read-only. - */ - public void setTypeName(String name, boolean canBeModified) { - fTypeNameDialogField.setText(name); - fTypeNameDialogField.setEnabled(canBeModified); - } - - /** - * Returns the selected modifiers. - * - * @return the selected modifiers - * @see Flags - */ - public int getModifiers() { - int mdf = 0; - if (fAccMdfButtons.isSelected(PUBLIC_INDEX)) { - mdf += F_PUBLIC; - } else if (fAccMdfButtons.isSelected(PRIVATE_INDEX)) { - mdf += F_PRIVATE; - } else if (fAccMdfButtons.isSelected(PROTECTED_INDEX)) { - mdf += F_PROTECTED; - } - // if (fOtherMdfButtons.isSelected(ABSTRACT_INDEX) && (fStaticMdfIndex != 0)) { - // mdf+= F_ABSTRACT; - // } - if (fOtherMdfButtons.isSelected(FINAL_INDEX)) { - mdf += F_FINAL; - } - if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { - mdf += F_STATIC; - } - return mdf; - } - - /** - * Sets the modifiers. - * - * @param modifiers F_PUBLIC, F_PRIVATE, - * F_PROTECTED, F_ABSTRACT, F_FINAL - * or F_STATIC or, a valid combination. - * @param canBeModified if true the modifier fields are - * editable; otherwise they are read-only - * @see Flags - */ - public void setModifiers(int modifiers, boolean canBeModified) { - if (Flags.isPublic(modifiers)) { - fAccMdfButtons.setSelection(PUBLIC_INDEX, true); - } else if (Flags.isPrivate(modifiers)) { - fAccMdfButtons.setSelection(PRIVATE_INDEX, true); - } else if (Flags.isProtected(modifiers)) { - fAccMdfButtons.setSelection(PROTECTED_INDEX, true); - } else { - fAccMdfButtons.setSelection(DEFAULT_INDEX, true); - } - // if (Flags.isAbstract(modifiers)) { - // fOtherMdfButtons.setSelection(ABSTRACT_INDEX, true); - // } - if (Flags.isFinal(modifiers)) { - fOtherMdfButtons.setSelection(FINAL_INDEX, true); - } - if (Flags.isStatic(modifiers)) { - fOtherMdfButtons.setSelection(fStaticMdfIndex, true); - } - - fAccMdfButtons.setEnabled(canBeModified); - fOtherMdfButtons.setEnabled(canBeModified); - } - - /** - * Returns the content of the superclass input field. - * - * @return the superclass name - */ - public String getSuperClass() { - return fSuperClassDialogField.getText(); - } - - /** - * Sets the super class name. - * - * @param name the new superclass name - * @param canBeModified if true the superclass name field is - * editable; otherwise it is read-only. - */ - public void setSuperClass(String name, boolean canBeModified) { - fSuperClassDialogField.setText(name); - fSuperClassDialogField.setEnabled(canBeModified); - } - - /** - * Returns the chosen super interfaces. - * - * @return a list of chosen super interfaces. The list's elements - * are of type String - */ - public List getSuperInterfaces() { - return fSuperInterfacesDialogField.getElements(); - } - - /** - * Sets the super interfaces. - * - * @param interfacesNames a list of super interface. The method requires that - * the list's elements are of type String - * @param canBeModified if true the super interface field is - * editable; otherwise it is read-only. - */ - public void setSuperInterfaces(List interfacesNames, boolean canBeModified) { - fSuperInterfacesDialogField.setElements(interfacesNames); - fSuperInterfacesDialogField.setEnabled(canBeModified); - } - - // ----------- validation ---------- - - /** - * A hook method that gets called when the package field has changed. The method - * validates the package name and returns the status of the validation. The validation - * also updates the package fragment model. - *

                                                      - * Subclasses may extend this method to perform their own validation. - *

                                                      - * - * @return the status of the validation - */ - protected IStatus packageChanged() { - StatusInfo status = new StatusInfo(); - fPackageDialogField.enableButton(getPackageFragmentRoot() != null); - - // String packName= getPackageText(); - // if (packName.length() > 0) { - // IStatus val= JavaConventions.validatePackageName(packName); - // if (val.getSeverity() == IStatus.ERROR) { - // status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidPackageName", val.getMessage())); //$NON-NLS-1$ - // return status; - // } else if (val.getSeverity() == IStatus.WARNING) { - // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.DiscouragedPackageName", val.getMessage())); //$NON-NLS-1$ - // // continue - // } - // } - - // IPackageFragmentRoot root= getPackageFragmentRoot(); - // if (root != null) { - // if (root.getJavaProject().exists() && packName.length() > 0) { - // try { - // IPath rootPath= root.getPath(); - // IPath outputPath= root.getJavaProject().getOutputLocation(); - // if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) { - // // if the bin folder is inside of our root, dont allow to name a package - // // like the bin folder - // IPath packagePath= rootPath.append(packName.replace('.', '/')); - // if (outputPath.isPrefixOf(packagePath)) { - // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ClashOutputLocation")); //$NON-NLS-1$ - // return status; - // } - // } - // } catch (JavaModelException e) { - // PHPeclipsePlugin.log(e); - // // let pass - // } - // } - // - // fCurrPackage= root.getPackageFragment(packName); - // } else { - // status.setError(""); //$NON-NLS-1$ - // } - return status; - } - - /* - * Updates the 'default' label next to the package field. - */ - private void updatePackageStatusLabel() { - String packName = getPackageText(); - - if (packName.length() == 0) { - fPackageDialogField.setStatus(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$ - } else { - fPackageDialogField.setStatus(""); //$NON-NLS-1$ - } - } - - /* - * Updates the enable state of buttons related to the enclosing type selection checkbox. - */ - private void updateEnableState() { - boolean enclosing = isEnclosingTypeSelected(); - fPackageDialogField.setEnabled(fCanModifyPackage && !enclosing); - fEnclosingTypeDialogField.setEnabled(fCanModifyEnclosingType && enclosing); - } - - /** - * Hook method that gets called when the enclosing type name has changed. The method - * validates the enclosing type and returns the status of the validation. It also updates the - * enclosing type model. - *

                                                      - * Subclasses may extend this method to perform their own validation. - *

                                                      - * - * @return the status of the validation - */ - // protected IStatus enclosingTypeChanged() { - // StatusInfo status= new StatusInfo(); - // fCurrEnclosingType= null; - // - // IPackageFragmentRoot root= getPackageFragmentRoot(); - // - // fEnclosingTypeDialogField.enableButton(root != null); - // if (root == null) { - // status.setError(""); //$NON-NLS-1$ - // return status; - // } - // - // String enclName= getEnclosingTypeText(); - // if (enclName.length() == 0) { - // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeEnterName")); //$NON-NLS-1$ - // return status; - // } - // try { - // IType type= findType(root.getJavaProject(), enclName); - // if (type == null) { - // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); //$NON-NLS-1$ - // return status; - // } - // - // if (type.getCompilationUnit() == null) { - // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotInCU")); //$NON-NLS-1$ - // return status; - // } - // if (!JavaModelUtil.isEditable(type.getCompilationUnit())) { - // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotEditable")); //$NON-NLS-1$ - // return status; - // } - // - // fCurrEnclosingType= type; - // IPackageFragmentRoot enclosingRoot= JavaModelUtil.getPackageFragmentRoot(type); - // if (!enclosingRoot.equals(root)) { - // status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.EnclosingNotInSourceFolder")); //$NON-NLS-1$ - // } - // return status; - // } catch (JavaModelException e) { - // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); //$NON-NLS-1$ - // PHPeclipsePlugin.log(e); - // return status; - // } - // } - - /** - * Hook method that gets called when the type name has changed. The method validates the - * type name and returns the status of the validation. - *

                                                      - * Subclasses may extend this method to perform their own validation. - *

                                                      - * - * @return the status of the validation - */ - protected IStatus typeNameChanged() { - StatusInfo status = new StatusInfo(); - String typeName = getTypeName(); - // must not be empty - if (typeName.length() == 0) { - status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnterTypeName")); //$NON-NLS-1$ - return status; - } - if (typeName.indexOf('.') != -1) { - status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.QualifiedName")); //$NON-NLS-1$ - return status; - } - // IStatus val= JavaConventions.validateJavaTypeName(typeName); - // if (val.getSeverity() == IStatus.ERROR) { - // status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidTypeName", val.getMessage())); //$NON-NLS-1$ - // return status; - // } else if (val.getSeverity() == IStatus.WARNING) { - // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.TypeNameDiscouraged", val.getMessage())); //$NON-NLS-1$ - // // continue checking - // } - - // must not exist - if (!isEnclosingTypeSelected()) { - IPackageFragment pack = getPackageFragment(); - if (pack != null) { - ICompilationUnit cu = pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$ - if (cu.getResource().exists()) { - status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$ - return status; - } - } - } else { - IType type = getEnclosingType(); - if (type != null) { - IType member = type.getType(typeName); - if (member.exists()) { - status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$ - return status; - } - } - } - return status; - } - - /** - * Hook method that gets called when the superclass name has changed. The method - * validates the superclass name and returns the status of the validation. - *

                                                      - * Subclasses may extend this method to perform their own validation. - *

                                                      - * - * @return the status of the validation - */ - // protected IStatus superClassChanged() { - // StatusInfo status= new StatusInfo(); - // IPackageFragmentRoot root= getPackageFragmentRoot(); - // fSuperClassDialogField.enableButton(root != null); - // - // fSuperClass= null; - // - // String sclassName= getSuperClass(); - // if (sclassName.length() == 0) { - // // accept the empty field (stands for java.lang.Object) - // return status; - // } - // IStatus val= JavaConventions.validateJavaTypeName(sclassName); - // if (val.getSeverity() == IStatus.ERROR) { - // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); //$NON-NLS-1$ - // return status; - // } - // if (root != null) { - // try { - // IType type= resolveSuperTypeName(root.getJavaProject(), sclassName); - // if (type == null) { - // status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.SuperClassNotExists")); //$NON-NLS-1$ - // return status; - // } else { - // if (type.isInterface()) { - // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotClass", sclassName)); //$NON-NLS-1$ - // return status; - // } - // int flags= type.getFlags(); - // if (Flags.isFinal(flags)) { - // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsFinal", sclassName)); //$NON-NLS-1$ - // return status; - // } else if (!JavaModelUtil.isVisible(type, getPackageFragment())) { - // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotVisible", sclassName)); //$NON-NLS-1$ - // return status; - // } - // } - // fSuperClass= type; - // } catch (JavaModelException e) { - // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); //$NON-NLS-1$ - // PHPeclipsePlugin.log(e); - // } - // } else { - // status.setError(""); //$NON-NLS-1$ - // } - // return status; - // - // } - - // private IType resolveSuperTypeName(IJavaProject jproject, String sclassName) throws JavaModelException { - // if (!jproject.exists()) { - // return null; - // } - // IType type= null; - // if (isEnclosingTypeSelected()) { - // // search in the context of the enclosing type - // IType enclosingType= getEnclosingType(); - // if (enclosingType != null) { - // String[][] res= enclosingType.resolveType(sclassName); - // if (res != null && res.length > 0) { - // type= jproject.findType(res[0][0], res[0][1]); - // } - // } - // } else { - // IPackageFragment currPack= getPackageFragment(); - // if (type == null && currPack != null) { - // String packName= currPack.getElementName(); - // // search in own package - // if (!currPack.isDefaultPackage()) { - // type= jproject.findType(packName, sclassName); - // } - // // search in java.lang - // if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$ - // type= jproject.findType("java.lang", sclassName); //$NON-NLS-1$ - // } - // } - // // search fully qualified - // if (type == null) { - // type= jproject.findType(sclassName); - // } - // } - // return type; - // } - - // private IType findType(IJavaProject project, String typeName) throws JavaModelException { - // if (project.exists()) { - // return project.findType(typeName); - // } - // return null; - // } - - /** - * Hook method that gets called when the list of super interface has changed. The method - * validates the superinterfaces and returns the status of the validation. - *

                                                      - * Subclasses may extend this method to perform their own validation. - *

                                                      - * - * @return the status of the validation - */ - // protected IStatus superInterfacesChanged() { - // StatusInfo status= new StatusInfo(); - // - // IPackageFragmentRoot root= getPackageFragmentRoot(); - // fSuperInterfacesDialogField.enableButton(0, root != null); - // - // if (root != null) { - // List elements= fSuperInterfacesDialogField.getElements(); - // int nElements= elements.size(); - // for (int i= 0; i < nElements; i++) { - // String intfname= (String)elements.get(i); - // try { - // IType type= findType(root.getJavaProject(), intfname); - // if (type == null) { - // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceNotExists", intfname)); //$NON-NLS-1$ - // return status; - // } else { - // if (type.isClass()) { - // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotInterface", intfname)); //$NON-NLS-1$ - // return status; - // } - // if (!JavaModelUtil.isVisible(type, getPackageFragment())) { - // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotVisible", intfname)); //$NON-NLS-1$ - // return status; - // } - // } - // } catch (JavaModelException e) { - // PHPeclipsePlugin.log(e); - // // let pass, checking is an extra - // } - // } - // } - // return status; - // } - - /** - * Hook method that gets called when the modifiers have changed. The method validates - * the modifiers and returns the status of the validation. - *

                                                      - * Subclasses may extend this method to perform their own validation. - *

                                                      - * - * @return the status of the validation - */ - protected IStatus modifiersChanged() { - StatusInfo status = new StatusInfo(); - int modifiers = getModifiers(); - // if (Flags.isFinal(modifiers) && Flags.isAbstract(modifiers)) { - // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ModifiersFinalAndAbstract")); //$NON-NLS-1$ - // } - return status; - } - - // selection dialogs - - // private IPackageFragment choosePackage() { - // IPackageFragmentRoot froot= getPackageFragmentRoot(); - // IJavaElement[] packages= null; - // try { - // if (froot != null && froot.exists()) { - // packages= froot.getChildren(); - // } - // } catch (JavaModelException e) { - // PHPeclipsePlugin.log(e); - // } - // if (packages == null) { - // packages= new IJavaElement[0]; - // } - // - // ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT)); - // dialog.setIgnoreCase(false); - // dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.title")); //$NON-NLS-1$ - // dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.description")); //$NON-NLS-1$ - // dialog.setEmptyListMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.empty")); //$NON-NLS-1$ - // dialog.setElements(packages); - // IPackageFragment pack= getPackageFragment(); - // if (pack != null) { - // dialog.setInitialSelections(new Object[] { pack }); - // } - // - // if (dialog.open() == ElementListSelectionDialog.OK) { - // return (IPackageFragment) dialog.getFirstResult(); - // } - // return null; - // } - - // private IType chooseEnclosingType() { - // IPackageFragmentRoot root= getPackageFragmentRoot(); - // if (root == null) { - // return null; - // } - // - // IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaElement[] { root }); - // - // TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), IJavaSearchConstants.TYPE, scope); - // dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.title")); //$NON-NLS-1$ - // dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.description")); //$NON-NLS-1$ - // dialog.setFilter(Signature.getSimpleName(getEnclosingTypeText())); - // - // if (dialog.open() == TypeSelectionDialog.OK) { - // return (IType) dialog.getFirstResult(); - // } - // return null; - // } - - // private IType chooseSuperType() { - // IPackageFragmentRoot root= getPackageFragmentRoot(); - // if (root == null) { - // return null; - // } - // - // IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; - // IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); - // - // TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), IJavaSearchConstants.CLASS, scope); - // dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.title")); //$NON-NLS-1$ - // dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.message")); //$NON-NLS-1$ - // dialog.setFilter(getSuperClass()); - // - // if (dialog.open() == TypeSelectionDialog.OK) { - // return (IType) dialog.getFirstResult(); - // } - // return null; - // } - - // private void chooseSuperInterfaces() { - // IPackageFragmentRoot root= getPackageFragmentRoot(); - // if (root == null) { - // return; - // } - // - // IJavaProject project= root.getJavaProject(); - // SuperInterfaceSelectionDialog dialog= new SuperInterfaceSelectionDialog(getShell(), getWizard().getContainer(), fSuperInterfacesDialogField, project); - // dialog.setTitle(fIsClass ? NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.class.title") : NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.interface.title")); //$NON-NLS-1$ //$NON-NLS-2$ - // dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.message")); //$NON-NLS-1$ - // dialog.open(); - // return; - // } - - // ---- creation ---------------- - - /** - * Creates the new type using the entered field values. - * - * @param monitor a progress monitor to report progress. - */ - public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException { - if (monitor == null) { - monitor = new NullProgressMonitor(); - } - - monitor.beginTask(NewWizardMessages.getString("NewTypeWizardPage.operationdesc"), 10); //$NON-NLS-1$ - ICompilationUnit createdWorkingCopy = null; - try { -// IPackageFragmentRoot root = getPackageFragmentRoot(); -// IPackageFragment pack = getPackageFragment(); -// if (pack == null) { -// pack = root.getPackageFragment(""); //$NON-NLS-1$ -// } -// -// if (!pack.exists()) { -// String packName = pack.getElementName(); -// pack = root.createPackageFragment(packName, true, null); -// } - - monitor.worked(1); - - String clName = getTypeName(); - - boolean isInnerClass = isEnclosingTypeSelected(); - - IType createdType; -// ImportsStructure imports; - int indent = 0; - - IPreferenceStore store = PreferenceConstants.getPreferenceStore(); -// String[] prefOrder = JavaPreferencesSettings.getImportOrderPreference(store); -// int threshold = JavaPreferencesSettings.getImportNumberThreshold(store); -// - String lineDelimiter = null; -// if (!isInnerClass) { - lineDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ -// -// ICompilationUnit parentCU = pack.createCompilationUnit(clName + ".php", "", false, new SubProgressMonitor(monitor, 2)); //$NON-NLS-1$ //$NON-NLS-2$ -// createdWorkingCopy = (ICompilationUnit) parentCU.getSharedWorkingCopy(null, JavaUI.getBufferFactory(), null); -// -// imports = new ImportsStructure(createdWorkingCopy, prefOrder, threshold, false); -// // add an import that will be removed again. Having this import solves 14661 -// imports.addImport(pack.getElementName(), getTypeName()); -// - String typeContent = constructTypeStub(lineDelimiter);//new ImportsManager(imports), lineDelimiter); - -// String cuContent = constructCUContent(parentCU, typeContent, lineDelimiter); - -// createdWorkingCopy.getBuffer().setContents(cuContent); -// - createdType = createdWorkingCopy.getType(clName); -// } else { -// IType enclosingType = getEnclosingType(); -// -// // if we are working on a enclosed type that is open in an editor, -// // then replace the enclosing type with its working copy -// IType workingCopy = (IType) EditorUtility.getWorkingCopy(enclosingType); -// if (workingCopy != null) { -// enclosingType = workingCopy; -// } -// -// ICompilationUnit parentCU = enclosingType.getCompilationUnit(); -// imports = new ImportsStructure(parentCU, prefOrder, threshold, true); -// -// // add imports that will be removed again. Having the imports solves 14661 -// IType[] topLevelTypes = parentCU.getTypes(); -// for (int i = 0; i < topLevelTypes.length; i++) { -// imports.addImport(topLevelTypes[i].getFullyQualifiedName('.')); -// } -// -// lineDelimiter = StubUtility.getLineDelimiterUsed(enclosingType); -// StringBuffer content = new StringBuffer(); -// String comment = getTypeComment(parentCU); -// if (comment != null) { -// content.append(comment); -// content.append(lineDelimiter); -// } -// content.append(constructTypeStub(new ImportsManager(imports), lineDelimiter)); -// IJavaElement[] elems = enclosingType.getChildren(); -// IJavaElement sibling = elems.length > 0 ? elems[0] : null; -// -// createdType = enclosingType.createType(content.toString(), sibling, false, new SubProgressMonitor(monitor, 1)); -// -// indent = StubUtility.getIndentUsed(enclosingType) + 1; -// } -// -// // add imports for superclass/interfaces, so types can be resolved correctly -// imports.create(false, new SubProgressMonitor(monitor, 1)); -// - ICompilationUnit cu = createdType.getCompilationUnit(); - synchronized (cu) { - cu.reconcile(); - } -// createTypeMembers(createdType, new ImportsManager(imports), new SubProgressMonitor(monitor, 1)); -// -// // add imports -// imports.create(false, new SubProgressMonitor(monitor, 1)); - - synchronized (cu) { - cu.reconcile(); - } - ISourceRange range = createdType.getSourceRange(); - - IBuffer buf = cu.getBuffer(); - String originalContent = buf.getText(range.getOffset(), range.getLength()); - String formattedContent = StubUtility.codeFormat(originalContent, indent, lineDelimiter); - buf.replace(range.getOffset(), range.getLength(), formattedContent); - if (!isInnerClass) { - String fileComment = getFileComment(cu); - if (fileComment != null && fileComment.length() > 0) { - buf.replace(0, 0, fileComment + lineDelimiter); - } - cu.commit(false, new SubProgressMonitor(monitor, 1)); - } else { - monitor.worked(1); - } - fCreatedType = createdType; - } finally { - if (createdWorkingCopy != null) { - createdWorkingCopy.destroy(); - } - monitor.done(); - } - } - - /** - * Uses the New Java file template from the code template page to generate a - * compilation unit with the given type content. - * @param cu The new created compilation unit - * @param typeContent The content of the type, including signature and type - * body. - * @param lineDelimiter The line delimiter to be used. - * @return String Returns the result of evaluating the new file template - * with the given type content. - * @throws CoreException - * @since 2.1 - */ - // protected String constructCUContent(ICompilationUnit cu, String typeContent, String lineDelimiter) throws CoreException { - // StringBuffer typeQualifiedName= new StringBuffer(); - // if (isEnclosingTypeSelected()) { - // typeQualifiedName.append(JavaModelUtil.getTypeQualifiedName(getEnclosingType())).append('.'); - // } - // typeQualifiedName.append(getTypeName()); - // String typeComment= CodeGeneration.getTypeComment(cu, typeQualifiedName.toString(), lineDelimiter); - // IPackageFragment pack= (IPackageFragment) cu.getParent(); - // String content= CodeGeneration.getCompilationUnitContent(cu, typeComment, typeContent, lineDelimiter); - // if (content != null) { - // CompilationUnit unit= AST.parseCompilationUnit(content.toCharArray()); - // if ((pack.isDefaultPackage() || unit.getPackage() != null) && !unit.types().isEmpty()) { - // return content; - // } - // } - // StringBuffer buf= new StringBuffer(); - // if (!pack.isDefaultPackage()) { - // buf.append("package ").append(pack.getElementName()).append(';'); //$NON-NLS-1$ - // } - // buf.append(lineDelimiter).append(lineDelimiter); - // if (typeComment != null) { - // buf.append(typeComment).append(lineDelimiter); - // } - // buf.append(typeContent); - // return buf.toString(); - // } - - /** - * Returns the created type. The method only returns a valid type - * after createType has been called. - * - * @return the created type - * @see #createType(IProgressMonitor) - */ - public IType getCreatedType() { - return fCreatedType; - } - - // ---- construct cu body---------------- - - // private void writeSuperClass(StringBuffer buf, ImportsManager imports) { - // String typename= getSuperClass(); - // if (fIsClass && typename.length() > 0 && !"java.lang.Object".equals(typename)) { //$NON-NLS-1$ - // buf.append(" extends "); //$NON-NLS-1$ - // - // String qualifiedName= fSuperClass != null ? JavaModelUtil.getFullyQualifiedName(fSuperClass) : typename; - // buf.append(imports.addImport(qualifiedName)); - // } - // } - - // private void writeSuperInterfaces(StringBuffer buf, ImportsManager imports) { - // List interfaces= getSuperInterfaces(); - // int last= interfaces.size() - 1; - // if (last >= 0) { - // if (fIsClass) { - // buf.append(" implements "); //$NON-NLS-1$ - // } else { - // buf.append(" extends "); //$NON-NLS-1$ - // } - // for (int i= 0; i <= last; i++) { - // String typename= (String) interfaces.get(i); - // buf.append(imports.addImport(typename)); - // if (i < last) { - // buf.append(','); - // } - // } - // } - // } - - /* - * Called from createType to construct the source for this type - */ - private String constructTypeStub(String lineDelimiter) { // ImportsManager imports, String lineDelimiter) { - StringBuffer buf= new StringBuffer(); - - int modifiers= getModifiers(); - buf.append(Flags.toString(modifiers)); - if (modifiers != 0) { - buf.append(' '); - } - buf.append(fIsClass ? "class " : "interface "); //$NON-NLS-2$ //$NON-NLS-1$ - buf.append(getTypeName()); -// writeSuperClass(buf, imports); -// writeSuperInterfaces(buf, imports); - buf.append('{'); - buf.append(lineDelimiter); - buf.append(lineDelimiter); - buf.append('}'); - buf.append(lineDelimiter); - return buf.toString(); - } - - /** - * @deprecated Overwrite createTypeMembers(IType, IImportsManager, IProgressMonitor) instead - */ - // protected void createTypeMembers(IType newType, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { - // //deprecated - // } - - /** - * Hook method that gets called from createType to support adding of - * unanticipated methods, fields, and inner types to the created type. - *

                                                      - * Implementers can use any methods defined on IType to manipulate the - * new type. - *

                                                      - *

                                                      - * The source code of the new type will be formtted using the platform's formatter. Needed - * imports are added by the wizard at the end of the type creation process using the given - * import manager. - *

                                                      - * - * @param newType the new type created via createType - * @param imports an import manager which can be used to add new imports - * @param monitor a progress monitor to report progress. Must not be null - * - * @see #createType(IProgressMonitor) - */ - // protected void createTypeMembers(IType newType, ImportsManager imports, IProgressMonitor monitor) throws CoreException { - // // call for compatibility - // createTypeMembers(newType, ((ImportsManager)imports).getImportsStructure(), monitor); - // - // // default implementation does nothing - // // example would be - // // String mainMathod= "public void foo(Vector vec) {}" - // // createdType.createMethod(main, null, false, null); - // // imports.addImport("java.lang.Vector"); - // } - - /** - * @deprecated Instead of file templates, the new type code template - * specifies the stub for a compilation unit. - */ - protected String getFileComment(ICompilationUnit parentCU) { - return null; - } - - private boolean isValidComment(String template) { - IScanner scanner = ToolFactory.createScanner(true, false, false); //, false); - scanner.setSource(template.toCharArray()); - try { - int next = scanner.getNextToken(); - while (next == ITerminalSymbols.TokenNameCOMMENT_LINE - || next == ITerminalSymbols.TokenNameCOMMENT_PHPDOC - || next == ITerminalSymbols.TokenNameCOMMENT_BLOCK) { - next = scanner.getNextToken(); - } - return next == ITerminalSymbols.TokenNameEOF; - } catch (InvalidInputException e) { - } - return false; - } - - /** - * Hook method that gets called from createType to retrieve - * a type comment. This default implementation returns the content of the - * 'typecomment' template. - * - * @return the type comment or null if a type comment - * is not desired - */ - protected String getTypeComment(ICompilationUnit parentCU) { - if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEGEN_ADD_COMMENTS)) { - try { - StringBuffer typeName= new StringBuffer(); - if (isEnclosingTypeSelected()) { - typeName.append(JavaModelUtil.getTypeQualifiedName(getEnclosingType())).append('.'); - } - typeName.append(getTypeName()); - String comment= CodeGeneration.getTypeComment(parentCU, typeName.toString(), String.valueOf('\n')); - if (comment != null && isValidComment(comment)) { - return comment; - } - } catch (CoreException e) { - PHPeclipsePlugin.log(e); - } - } - return null; - } - - /** - * @deprecated Use getTemplate(String,ICompilationUnit,int) - */ - protected String getTemplate(String name, ICompilationUnit parentCU) { - return getTemplate(name, parentCU, 0); - } - - /** - * Returns the string resulting from evaluation the given template in - * the context of the given compilation unit. This accesses the normal - * template page, not the code templates. To use code templates use - * constructCUContent to construct a compilation unit stub or - * getTypeComment for the comment of the type. - * - * @param name the template to be evaluated - * @param parentCU the templates evaluation context - * @param pos a source offset into the parent compilation unit. The - * template is evalutated at the given source offset - */ - protected String getTemplate(String name, ICompilationUnit parentCU, int pos) { - try { - Template[] templates = Templates.getInstance().getTemplates(name); - if (templates.length > 0) { - return JavaContext.evaluateTemplate(templates[0], parentCU, pos); - } - } catch (CoreException e) { - PHPeclipsePlugin.log(e); - } catch (BadLocationException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } catch (TemplateException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - return null; - } - - /** - * @deprecated Use createInheritedMethods(IType,boolean,boolean,IImportsManager,IProgressMonitor) - */ - // protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { - // return createInheritedMethods(type, doConstructors, doUnimplementedMethods, new ImportsManager(imports), monitor); - // } - - /** - * Creates the bodies of all unimplemented methods and constructors and adds them to the type. - * Method is typically called by implementers of NewTypeWizardPage to add - * needed method and constructors. - * - * @param type the type for which the new methods and constructor are to be created - * @param doConstructors if true unimplemented constructors are created - * @param doUnimplementedMethods if true unimplemented methods are created - * @param imports an import manager to add all neded import statements - * @param monitor a progress monitor to report progress - */ - // protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, ImportsManager imports, IProgressMonitor monitor) throws CoreException { - // ArrayList newMethods= new ArrayList(); - // ITypeHierarchy hierarchy= null; - // CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); - // - // if (doConstructors) { - // hierarchy= type.newSupertypeHierarchy(monitor); - // IType superclass= hierarchy.getSuperclass(type); - // if (superclass != null) { - // String[] constructors= StubUtility.evalConstructors(type, superclass, settings, imports.getImportsStructure()); - // if (constructors != null) { - // for (int i= 0; i < constructors.length; i++) { - // newMethods.add(constructors[i]); - // } - // } - // - // } - // } - // if (doUnimplementedMethods) { - // if (hierarchy == null) { - // hierarchy= type.newSupertypeHierarchy(monitor); - // } - // String[] unimplemented= StubUtility.evalUnimplementedMethods(type, hierarchy, false, settings, null, imports.getImportsStructure()); - // if (unimplemented != null) { - // for (int i= 0; i < unimplemented.length; i++) { - // newMethods.add(unimplemented[i]); - // } - // } - // } - // IMethod[] createdMethods= new IMethod[newMethods.size()]; - // for (int i= 0; i < newMethods.size(); i++) { - // String content= (String) newMethods.get(i) + '\n'; // content will be formatted, ok to use \n - // createdMethods[i]= type.createMethod(content, null, false, null); - // } - // return createdMethods; - // } - - // ---- creation ---------------- - - /** - * Returns the runnable that creates the type using the current settings. - * The returned runnable must be executed in the UI thread. - * - * @return the runnable to create the new type - */ - // public IRunnableWithProgress getRunnable() { - // return new IRunnableWithProgress() { - // public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { - // try { - // if (monitor == null) { - // monitor= new NullProgressMonitor(); - // } - // createType(monitor); - // } catch (CoreException e) { - // throw new InvocationTargetException(e); - // } - // } - // }; - // } + /** + * Class used in stub creation routines to add needed imports to a + * compilation unit. + */ + // public static class ImportsManager { + // + // private IImportsStructure fImportsStructure; + // + // /* package */ ImportsManager(IImportsStructure structure) { + // fImportsStructure= structure; + // } + // + // /* package */ IImportsStructure getImportsStructure() { + // return fImportsStructure; + // } + // + // /** + // * Adds a new import declaration that is sorted in the existing imports. + // * If an import already exists or the import would conflict with another + // import + // * of an other type with the same simple name the import is not added. + // * + // * @param qualifiedTypeName The fully qualified name of the type to import + // * (dot separated) + // * @return Returns the simple type name that can be used in the code or + // the + // * fully qualified type name if an import conflict prevented the import + // */ + // public String addImport(String qualifiedTypeName) { + // return fImportsStructure.addImport(qualifiedTypeName); + // } + // } + /** + * Public access flag. See The Java Virtual Machine Specification for more + * details. + */ + public int F_PUBLIC = Flags.AccPublic; + /** + * Private access flag. See The Java Virtual Machine Specification for more + * details. + */ + public int F_PRIVATE = Flags.AccPrivate; + + /** + * Protected access flag. See The Java Virtual Machine Specification for + * more details. + */ + public int F_PROTECTED = Flags.AccProtected; + + /** + * Static access flag. See The Java Virtual Machine Specification for more + * details. + */ + public int F_STATIC = Flags.AccStatic; + + /** + * Final access flag. See The Java Virtual Machine Specification for more + * details. + */ + public int F_FINAL = Flags.AccFinal; + + /** + * Abstract property flag. See The Java Virtual Machine Specification for + * more details. + */ + // public int F_ABSTRACT = Flags.AccAbstract; + private final static String PAGE_NAME = "NewTypeWizardPage"; //$NON-NLS-1$ + + /** Field ID of the package input field */ + protected final static String PACKAGE = PAGE_NAME + ".package"; //$NON-NLS-1$ + + /** Field ID of the eclosing type input field */ + protected final static String ENCLOSING = PAGE_NAME + ".enclosing"; //$NON-NLS-1$ + + /** Field ID of the enclosing type checkbox */ + protected final static String ENCLOSINGSELECTION = ENCLOSING + ".selection"; //$NON-NLS-1$ + + /** Field ID of the type name input field */ + protected final static String TYPENAME = PAGE_NAME + ".typename"; //$NON-NLS-1$ + + /** Field ID of the super type input field */ + protected final static String SUPER = PAGE_NAME + ".superclass"; //$NON-NLS-1$ + + /** Field ID of the super interfaces input field */ + protected final static String INTERFACES = PAGE_NAME + ".interfaces"; //$NON-NLS-1$ + + /** Field ID of the modifier checkboxes */ + protected final static String MODIFIERS = PAGE_NAME + ".modifiers"; //$NON-NLS-1$ + + /** Field ID of the method stubs checkboxes */ + protected final static String METHODS = PAGE_NAME + ".methods"; //$NON-NLS-1$ + + private class InterfacesListLabelProvider extends LabelProvider { + + private Image fInterfaceImage; + + public InterfacesListLabelProvider() { + super(); + fInterfaceImage = PHPUiImages.get(PHPUiImages.IMG_OBJS_INTERFACE); + } + + public Image getImage(Object element) { + return fInterfaceImage; + } + } + + private StringButtonStatusDialogField fPackageDialogField; + + private SelectionButtonDialogField fEnclosingTypeSelection; + + private StringButtonDialogField fEnclosingTypeDialogField; + + private boolean fCanModifyPackage; + + private boolean fCanModifyEnclosingType; + + private IPackageFragment fCurrPackage; + + // private IType fCurrEnclosingType; + private StringDialogField fTypeNameDialogField; + + private StringButtonDialogField fSuperClassDialogField; + + private ListDialogField fSuperInterfacesDialogField; + + // private IType fSuperClass; + + private SelectionButtonDialogFieldGroup fAccMdfButtons; + + private SelectionButtonDialogFieldGroup fOtherMdfButtons; + + private IType fCreatedType; + + protected IStatus fEnclosingTypeStatus; + + protected IStatus fPackageStatus; + + protected IStatus fTypeNameStatus; + + // protected IStatus fSuperClassStatus; + protected IStatus fModifierStatus; + + // protected IStatus fSuperInterfacesStatus; + + private boolean fIsClass; + + private int fStaticMdfIndex; + + private final int PUBLIC_INDEX = 0, DEFAULT_INDEX = 1, PRIVATE_INDEX = 2, + PROTECTED_INDEX = 3; + + private final int ABSTRACT_INDEX = 0, FINAL_INDEX = 1; + + /** + * Creates a new NewTypeWizardPage + * + * @param isClass + * true if a new class is to be created; otherwise + * an interface is to be created + * @param pageName + * the wizard page's name + */ + public NewTypeWizardPage(boolean isClass, String pageName) { + super(pageName); + fCreatedType = null; + + fIsClass = isClass; + + TypeFieldsAdapter adapter = new TypeFieldsAdapter(); + + fPackageDialogField = new StringButtonStatusDialogField(adapter); + fPackageDialogField.setDialogFieldListener(adapter); + fPackageDialogField.setLabelText(NewWizardMessages + .getString("NewTypeWizardPage.package.label")); //$NON-NLS-1$ + fPackageDialogField.setButtonLabel(NewWizardMessages + .getString("NewTypeWizardPage.package.button")); //$NON-NLS-1$ + fPackageDialogField.setStatusWidthHint(NewWizardMessages + .getString("NewTypeWizardPage.default")); //$NON-NLS-1$ + + fEnclosingTypeSelection = new SelectionButtonDialogField(SWT.CHECK); + fEnclosingTypeSelection.setDialogFieldListener(adapter); + fEnclosingTypeSelection.setLabelText(NewWizardMessages + .getString("NewTypeWizardPage.enclosing.selection.label")); //$NON-NLS-1$ + + fEnclosingTypeDialogField = new StringButtonDialogField(adapter); + fEnclosingTypeDialogField.setDialogFieldListener(adapter); + fEnclosingTypeDialogField.setButtonLabel(NewWizardMessages + .getString("NewTypeWizardPage.enclosing.button")); //$NON-NLS-1$ + + fTypeNameDialogField = new StringDialogField(); + fTypeNameDialogField.setDialogFieldListener(adapter); + fTypeNameDialogField.setLabelText(NewWizardMessages + .getString("NewTypeWizardPage.typename.label")); //$NON-NLS-1$ + + fSuperClassDialogField = new StringButtonDialogField(adapter); + fSuperClassDialogField.setDialogFieldListener(adapter); + fSuperClassDialogField.setLabelText(NewWizardMessages + .getString("NewTypeWizardPage.superclass.label")); //$NON-NLS-1$ + fSuperClassDialogField.setButtonLabel(NewWizardMessages + .getString("NewTypeWizardPage.superclass.button")); //$NON-NLS-1$ + + String[] addButtons = new String[] { + /* 0 */ + NewWizardMessages.getString("NewTypeWizardPage.interfaces.add"), //$NON-NLS-1$ + /* 1 */ + null, + /* 2 */ + NewWizardMessages + .getString("NewTypeWizardPage.interfaces.remove") //$NON-NLS-1$ + }; + fSuperInterfacesDialogField = new ListDialogField(adapter, addButtons, + new InterfacesListLabelProvider()); + fSuperInterfacesDialogField.setDialogFieldListener(adapter); + String interfaceLabel = fIsClass ? NewWizardMessages + .getString("NewTypeWizardPage.interfaces.class.label") : NewWizardMessages.getString("NewTypeWizardPage.interfaces.ifc.label"); //$NON-NLS-1$ //$NON-NLS-2$ + fSuperInterfacesDialogField.setLabelText(interfaceLabel); + fSuperInterfacesDialogField.setRemoveButtonIndex(2); + + String[] buttonNames1 = new String[] { + /* 0 == PUBLIC_INDEX */ + NewWizardMessages + .getString("NewTypeWizardPage.modifiers.public"), //$NON-NLS-1$ + /* 1 == DEFAULT_INDEX */ + NewWizardMessages + .getString("NewTypeWizardPage.modifiers.default"), //$NON-NLS-1$ + /* 2 == PRIVATE_INDEX */ + NewWizardMessages + .getString("NewTypeWizardPage.modifiers.private"), //$NON-NLS-1$ + /* 3 == PROTECTED_INDEX */ + NewWizardMessages + .getString("NewTypeWizardPage.modifiers.protected") //$NON-NLS-1$ + }; + fAccMdfButtons = new SelectionButtonDialogFieldGroup(SWT.RADIO, + buttonNames1, 4); + fAccMdfButtons.setDialogFieldListener(adapter); + fAccMdfButtons.setLabelText(NewWizardMessages + .getString("NewTypeWizardPage.modifiers.acc.label")); //$NON-NLS-1$ + fAccMdfButtons.setSelection(0, true); + + String[] buttonNames2; + if (fIsClass) { + buttonNames2 = new String[] { + /* 0 == ABSTRACT_INDEX */ + NewWizardMessages + .getString("NewTypeWizardPage.modifiers.abstract"), //$NON-NLS-1$ + /* 1 == FINAL_INDEX */ + NewWizardMessages + .getString("NewTypeWizardPage.modifiers.final"), //$NON-NLS-1$ + /* 2 */ + NewWizardMessages + .getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$ + }; + fStaticMdfIndex = 2; // index of the static checkbox is 2 + } else { + buttonNames2 = new String[] { NewWizardMessages + .getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$ + }; + fStaticMdfIndex = 0; // index of the static checkbox is 0 + } + + fOtherMdfButtons = new SelectionButtonDialogFieldGroup(SWT.CHECK, + buttonNames2, 4); + fOtherMdfButtons.setDialogFieldListener(adapter); + + fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, false); + fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, false); + fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, false); + + fPackageStatus = new StatusInfo(); + fEnclosingTypeStatus = new StatusInfo(); + + fCanModifyPackage = true; + fCanModifyEnclosingType = true; + updateEnableState(); + + fTypeNameStatus = new StatusInfo(); + // fSuperClassStatus= new StatusInfo(); + // fSuperInterfacesStatus= new StatusInfo(); + fModifierStatus = new StatusInfo(); + } + + /** + * Initializes all fields provided by the page with a given selection. + * + * @param elem + * the selection used to intialize this page or + * null + * if no selection was available + */ + protected void initTypePage(IJavaElement elem) { + String initSuperclass = "java.lang.Object"; //$NON-NLS-1$ + ArrayList initSuperinterfaces = new ArrayList(5); + + IPackageFragment pack = null; + IType enclosingType = null; + + if (elem != null) { + // evaluate the enclosing type + pack = (IPackageFragment) elem + .getAncestor(IJavaElement.PACKAGE_FRAGMENT); + IType typeInCU = (IType) elem.getAncestor(IJavaElement.TYPE); + if (typeInCU != null) { + if (typeInCU.getCompilationUnit() != null) { + enclosingType = typeInCU; + } + } else { + ICompilationUnit cu = (ICompilationUnit) elem + .getAncestor(IJavaElement.COMPILATION_UNIT); + if (cu != null) { + // enclosingType= cu.findPrimaryType(); + } + } + + // try { + // IType type= null; + // if (elem.getElementType() == IJavaElement.TYPE) { + // type= (IType)elem; + // if (type.exists()) { + // String superName= JavaModelUtil.getFullyQualifiedName(type); + // if (type.isInterface()) { + // initSuperinterfaces.add(superName); + // } else { + // initSuperclass= superName; + // } + // } + // } + // } catch (JavaModelException e) { + // PHPeclipsePlugin.log(e); + // // ignore this exception now + // } + } + + setPackageFragment(pack, true); + // setEnclosingType(enclosingType, true); + setEnclosingTypeSelection(false, true); + + setTypeName("", true); //$NON-NLS-1$ + setSuperClass(initSuperclass, true); + setSuperInterfaces(initSuperinterfaces, true); + } + + // -------- UI Creation --------- + + /** + * Creates a separator line. Expects a GridLayout with at + * least 1 column. + * + * @param composite + * the parent composite + * @param nColumns + * number of columns to span + */ + protected void createSeparator(Composite composite, int nColumns) { + (new Separator(SWT.SEPARATOR | SWT.HORIZONTAL)).doFillIntoGrid( + composite, nColumns, convertHeightInCharsToPixels(1)); + } + + /** + * Creates the controls for the package name field. Expects a + * GridLayout with at least 4 columns. + * + * @param composite + * the parent composite + * @param nColumns + * number of columns to span + */ + protected void createPackageControls(Composite composite, int nColumns) { + fPackageDialogField.doFillIntoGrid(composite, nColumns); + LayoutUtil.setWidthHint(fPackageDialogField.getTextControl(null), + getMaxFieldWidth()); + LayoutUtil.setHorizontalGrabbing(fPackageDialogField + .getTextControl(null)); + } + + /** + * Creates the controls for the enclosing type name field. Expects a + * GridLayout with at least 4 columns. + * + * @param composite + * the parent composite + * @param nColumns + * number of columns to span + */ + protected void createEnclosingTypeControls(Composite composite, int nColumns) { + // #6891 + Composite tabGroup = new Composite(composite, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginWidth = 0; + layout.marginHeight = 0; + tabGroup.setLayout(layout); + + fEnclosingTypeSelection.doFillIntoGrid(tabGroup, 1); + + Control c = fEnclosingTypeDialogField.getTextControl(composite); + GridData gd = new GridData(GridData.FILL_HORIZONTAL); + gd.widthHint = getMaxFieldWidth(); + gd.horizontalSpan = 2; + c.setLayoutData(gd); + + Button button = fEnclosingTypeDialogField.getChangeControl(composite); + gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + gd.heightHint = SWTUtil.getButtonHeightHint(button); + gd.widthHint = SWTUtil.getButtonWidthHint(button); + button.setLayoutData(gd); + } + + /** + * Creates the controls for the type name field. Expects a + * GridLayout with at least 2 columns. + * + * @param composite + * the parent composite + * @param nColumns + * number of columns to span + */ + protected void createTypeNameControls(Composite composite, int nColumns) { + fTypeNameDialogField.doFillIntoGrid(composite, nColumns - 1); + DialogField.createEmptySpace(composite); + + LayoutUtil.setWidthHint(fTypeNameDialogField.getTextControl(null), + getMaxFieldWidth()); + } + + /** + * Creates the controls for the modifiers radio/ceckbox buttons. Expects a + * GridLayout with at least 3 columns. + * + * @param composite + * the parent composite + * @param nColumns + * number of columns to span + */ + protected void createModifierControls(Composite composite, int nColumns) { + LayoutUtil.setHorizontalSpan(fAccMdfButtons.getLabelControl(composite), + 1); + + Control control = fAccMdfButtons.getSelectionButtonsGroup(composite); + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + gd.horizontalSpan = nColumns - 2; + control.setLayoutData(gd); + + DialogField.createEmptySpace(composite); + + DialogField.createEmptySpace(composite); + + control = fOtherMdfButtons.getSelectionButtonsGroup(composite); + gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + gd.horizontalSpan = nColumns - 2; + control.setLayoutData(gd); + + DialogField.createEmptySpace(composite); + } + + /** + * Creates the controls for the superclass name field. Expects a + * GridLayout with at least 3 columns. + * + * @param composite + * the parent composite + * @param nColumns + * number of columns to span + */ + protected void createSuperClassControls(Composite composite, int nColumns) { + fSuperClassDialogField.doFillIntoGrid(composite, nColumns); + LayoutUtil.setWidthHint(fSuperClassDialogField.getTextControl(null), + getMaxFieldWidth()); + } + + /** + * Creates the controls for the superclass name field. Expects a + * GridLayout with at least 3 columns. + * + * @param composite + * the parent composite + * @param nColumns + * number of columns to span + */ + protected void createSuperInterfacesControls(Composite composite, + int nColumns) { + fSuperInterfacesDialogField.doFillIntoGrid(composite, nColumns); + GridData gd = (GridData) fSuperInterfacesDialogField.getListControl( + null).getLayoutData(); + if (fIsClass) { + gd.heightHint = convertHeightInCharsToPixels(3); + } else { + gd.heightHint = convertHeightInCharsToPixels(6); + } + gd.grabExcessVerticalSpace = false; + gd.widthHint = getMaxFieldWidth(); + } + + /** + * Sets the focus on the type name input field. + */ + protected void setFocus() { + fTypeNameDialogField.setFocus(); + } + + // -------- TypeFieldsAdapter -------- + + private class TypeFieldsAdapter implements IStringButtonAdapter, + IDialogFieldListener, IListAdapter { + + // -------- IStringButtonAdapter + public void changeControlPressed(DialogField field) { + // typePageChangeControlPressed(field); + } + + // -------- IListAdapter + public void customButtonPressed(ListDialogField field, int index) { + // typePageCustomButtonPressed(field, index); + } + + public void selectionChanged(ListDialogField field) { + } + + // -------- IDialogFieldListener + public void dialogFieldChanged(DialogField field) { + typePageDialogFieldChanged(field); + } + + public void doubleClicked(ListDialogField field) { + } + } + + // private void typePageChangeControlPressed(DialogField field) { + // if (field == fPackageDialogField) { + // IPackageFragment pack= choosePackage(); + // if (pack != null) { + // fPackageDialogField.setText(pack.getElementName()); + // } + // } else if (field == fEnclosingTypeDialogField) { + // IType type= chooseEnclosingType(); + // if (type != null) { + // fEnclosingTypeDialogField.setText(JavaModelUtil.getFullyQualifiedName(type)); + // } + // } else if (field == fSuperClassDialogField) { + // IType type= chooseSuperType(); + // if (type != null) { + // fSuperClassDialogField.setText(JavaModelUtil.getFullyQualifiedName(type)); + // } + // } + // } + + // private void typePageCustomButtonPressed(DialogField field, int index) { + // if (field == fSuperInterfacesDialogField) { + // chooseSuperInterfaces(); + // } + // } + + /* + * A field on the type has changed. The fields' status and all dependend + * status are updated. + */ + private void typePageDialogFieldChanged(DialogField field) { + String fieldName = null; + if (field == fPackageDialogField) { + fPackageStatus = packageChanged(); + updatePackageStatusLabel(); + fTypeNameStatus = typeNameChanged(); + // fSuperClassStatus= superClassChanged(); + fieldName = PACKAGE; + } else if (field == fEnclosingTypeDialogField) { + // fEnclosingTypeStatus= enclosingTypeChanged(); + fTypeNameStatus = typeNameChanged(); + // fSuperClassStatus= superClassChanged(); + fieldName = ENCLOSING; + } else if (field == fEnclosingTypeSelection) { + updateEnableState(); + boolean isEnclosedType = isEnclosingTypeSelected(); + if (!isEnclosedType) { + if (fAccMdfButtons.isSelected(PRIVATE_INDEX) + || fAccMdfButtons.isSelected(PROTECTED_INDEX)) { + fAccMdfButtons.setSelection(PRIVATE_INDEX, false); + fAccMdfButtons.setSelection(PROTECTED_INDEX, false); + fAccMdfButtons.setSelection(PUBLIC_INDEX, true); + } + if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { + fOtherMdfButtons.setSelection(fStaticMdfIndex, false); + } + } + fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, isEnclosedType + && fIsClass); + fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, + isEnclosedType && fIsClass); + fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, + isEnclosedType); + fTypeNameStatus = typeNameChanged(); + // fSuperClassStatus= superClassChanged(); + fieldName = ENCLOSINGSELECTION; + } else if (field == fTypeNameDialogField) { + fTypeNameStatus = typeNameChanged(); + fieldName = TYPENAME; + } else if (field == fSuperClassDialogField) { + // fSuperClassStatus= superClassChanged(); + fieldName = SUPER; + } else if (field == fSuperInterfacesDialogField) { + // fSuperInterfacesStatus= superInterfacesChanged(); + fieldName = INTERFACES; + } else if (field == fOtherMdfButtons) { + fModifierStatus = modifiersChanged(); + fieldName = MODIFIERS; + } else { + fieldName = METHODS; + } + // tell all others + handleFieldChanged(fieldName); + } + + // -------- update message ---------------- + + /* + * @see net.sourceforge.phpdt.ui.wizards.NewContainerWizardPage#handleFieldChanged(String) + */ + protected void handleFieldChanged(String fieldName) { + super.handleFieldChanged(fieldName); + if (fieldName == CONTAINER) { + fPackageStatus = packageChanged(); + // fEnclosingTypeStatus= enclosingTypeChanged(); + fTypeNameStatus = typeNameChanged(); + // fSuperClassStatus= superClassChanged(); + // fSuperInterfacesStatus= superInterfacesChanged(); + } + } + + // ---- set / get ---------------- + + /** + * Returns the text of the package input field. + * + * @return the text of the package input field + */ + public String getPackageText() { + return fPackageDialogField.getText(); + } + + /** + * Returns the text of the enclosing type input field. + * + * @return the text of the enclosing type input field + */ + public String getEnclosingTypeText() { + return fEnclosingTypeDialogField.getText(); + } + + /** + * Returns the package fragment corresponding to the current input. + * + * @return a package fragement or null if the input could not + * be resolved. + */ + public IPackageFragment getPackageFragment() { + if (!isEnclosingTypeSelected()) { + return fCurrPackage; + } else { + // if (fCurrEnclosingType != null) { + // return fCurrEnclosingType.getPackageFragment(); + // } + } + return null; + } + + /** + * Sets the package fragment to the given value. The method updates the + * model and the text of the control. + * + * @param pack + * the package fragement to be set + * @param canBeModified + * if true the package fragment is editable; + * otherwise it is read-only. + */ + public void setPackageFragment(IPackageFragment pack, boolean canBeModified) { + fCurrPackage = pack; + fCanModifyPackage = canBeModified; + String str = (pack == null) ? "" : pack.getElementName(); //$NON-NLS-1$ + fPackageDialogField.setText(str); + updateEnableState(); + } + + /** + * Returns the enclosing type corresponding to the current input. + * + * @return the enclosing type or null if the enclosing type + * is not selected or the input could not be resolved + */ + public IType getEnclosingType() { + // if (isEnclosingTypeSelected()) { + // return fCurrEnclosingType; + // } + return null; + } + + /** + * Sets the enclosing type. The method updates the underlying model and the + * text of the control. + * + * @param type + * the enclosing type + * @param canBeModified + * if true the enclosing type field is editable; + * otherwise it is read-only. + */ + // public void setEnclosingType(IType type, boolean canBeModified) { + // fCurrEnclosingType= type; + // fCanModifyEnclosingType= canBeModified; + // String str= (type == null) ? "" : + // JavaModelUtil.getFullyQualifiedName(type); //$NON-NLS-1$ + // fEnclosingTypeDialogField.setText(str); + // updateEnableState(); + // } + /** + * Returns the selection state of the enclosing type checkbox. + * + * @return the seleciton state of the enclosing type checkbox + */ + public boolean isEnclosingTypeSelected() { + return fEnclosingTypeSelection.isSelected(); + } + + /** + * Sets the enclosing type checkbox's selection state. + * + * @param isSelected + * the checkbox's selection state + * @param canBeModified + * if true the enclosing type checkbox is + * modifiable; otherwise it is read-only. + */ + public void setEnclosingTypeSelection(boolean isSelected, + boolean canBeModified) { + fEnclosingTypeSelection.setSelection(isSelected); + fEnclosingTypeSelection.setEnabled(canBeModified); + updateEnableState(); + } + + /** + * Returns the type name entered into the type input field. + * + * @return the type name + */ + public String getTypeName() { + return fTypeNameDialogField.getText(); + } + + /** + * Sets the type name input field's text to the given value. Method doesn't + * update the model. + * + * @param name + * the new type name + * @param canBeModified + * if true the enclosing type name field is + * editable; otherwise it is read-only. + */ + public void setTypeName(String name, boolean canBeModified) { + fTypeNameDialogField.setText(name); + fTypeNameDialogField.setEnabled(canBeModified); + } + + /** + * Returns the selected modifiers. + * + * @return the selected modifiers + * @see Flags + */ + public int getModifiers() { + int mdf = 0; + if (fAccMdfButtons.isSelected(PUBLIC_INDEX)) { + mdf += F_PUBLIC; + } else if (fAccMdfButtons.isSelected(PRIVATE_INDEX)) { + mdf += F_PRIVATE; + } else if (fAccMdfButtons.isSelected(PROTECTED_INDEX)) { + mdf += F_PROTECTED; + } + // if (fOtherMdfButtons.isSelected(ABSTRACT_INDEX) && (fStaticMdfIndex + // != 0)) { + // mdf+= F_ABSTRACT; + // } + if (fOtherMdfButtons.isSelected(FINAL_INDEX)) { + mdf += F_FINAL; + } + if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { + mdf += F_STATIC; + } + return mdf; + } + + /** + * Sets the modifiers. + * + * @param modifiers + * F_PUBLIC, F_PRIVATE, + * F_PROTECTED, F_ABSTRACT, F_FINAL + * or F_STATIC or, a valid combination. + * @param canBeModified + * if true the modifier fields are editable; + * otherwise they are read-only + * @see Flags + */ + public void setModifiers(int modifiers, boolean canBeModified) { + if (Flags.isPublic(modifiers)) { + fAccMdfButtons.setSelection(PUBLIC_INDEX, true); + } else if (Flags.isPrivate(modifiers)) { + fAccMdfButtons.setSelection(PRIVATE_INDEX, true); + } else if (Flags.isProtected(modifiers)) { + fAccMdfButtons.setSelection(PROTECTED_INDEX, true); + } else { + fAccMdfButtons.setSelection(DEFAULT_INDEX, true); + } + // if (Flags.isAbstract(modifiers)) { + // fOtherMdfButtons.setSelection(ABSTRACT_INDEX, true); + // } + if (Flags.isFinal(modifiers)) { + fOtherMdfButtons.setSelection(FINAL_INDEX, true); + } + if (Flags.isStatic(modifiers)) { + fOtherMdfButtons.setSelection(fStaticMdfIndex, true); + } + + fAccMdfButtons.setEnabled(canBeModified); + fOtherMdfButtons.setEnabled(canBeModified); + } + + /** + * Returns the content of the superclass input field. + * + * @return the superclass name + */ + public String getSuperClass() { + return fSuperClassDialogField.getText(); + } + + /** + * Sets the super class name. + * + * @param name + * the new superclass name + * @param canBeModified + * if true the superclass name field is editable; + * otherwise it is read-only. + */ + public void setSuperClass(String name, boolean canBeModified) { + fSuperClassDialogField.setText(name); + fSuperClassDialogField.setEnabled(canBeModified); + } + + /** + * Returns the chosen super interfaces. + * + * @return a list of chosen super interfaces. The list's elements are of + * type String + */ + public List getSuperInterfaces() { + return fSuperInterfacesDialogField.getElements(); + } + + /** + * Sets the super interfaces. + * + * @param interfacesNames + * a list of super interface. The method requires that the list's + * elements are of type String + * @param canBeModified + * if true the super interface field is editable; + * otherwise it is read-only. + */ + public void setSuperInterfaces(List interfacesNames, boolean canBeModified) { + fSuperInterfacesDialogField.setElements(interfacesNames); + fSuperInterfacesDialogField.setEnabled(canBeModified); + } + + // ----------- validation ---------- + + /** + * A hook method that gets called when the package field has changed. The + * method validates the package name and returns the status of the + * validation. The validation also updates the package fragment model. + *

                                                      + * Subclasses may extend this method to perform their own validation. + *

                                                      + * + * @return the status of the validation + */ + protected IStatus packageChanged() { + StatusInfo status = new StatusInfo(); + fPackageDialogField.enableButton(getPackageFragmentRoot() != null); + + // String packName= getPackageText(); + // if (packName.length() > 0) { + // IStatus val= JavaConventions.validatePackageName(packName); + // if (val.getSeverity() == IStatus.ERROR) { + // status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidPackageName", + // val.getMessage())); //$NON-NLS-1$ + // return status; + // } else if (val.getSeverity() == IStatus.WARNING) { + // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.DiscouragedPackageName", + // val.getMessage())); //$NON-NLS-1$ + // // continue + // } + // } + + // IPackageFragmentRoot root= getPackageFragmentRoot(); + // if (root != null) { + // if (root.getJavaProject().exists() && packName.length() > 0) { + // try { + // IPath rootPath= root.getPath(); + // IPath outputPath= root.getJavaProject().getOutputLocation(); + // if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) + // { + // // if the bin folder is inside of our root, dont allow to name a + // package + // // like the bin folder + // IPath packagePath= rootPath.append(packName.replace('.', '/')); + // if (outputPath.isPrefixOf(packagePath)) { + // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ClashOutputLocation")); + // //$NON-NLS-1$ + // return status; + // } + // } + // } catch (JavaModelException e) { + // PHPeclipsePlugin.log(e); + // // let pass + // } + // } + // + // fCurrPackage= root.getPackageFragment(packName); + // } else { + // status.setError(""); //$NON-NLS-1$ + // } + return status; + } + + /* + * Updates the 'default' label next to the package field. + */ + private void updatePackageStatusLabel() { + String packName = getPackageText(); + + if (packName.length() == 0) { + fPackageDialogField.setStatus(NewWizardMessages + .getString("NewTypeWizardPage.default")); //$NON-NLS-1$ + } else { + fPackageDialogField.setStatus(""); //$NON-NLS-1$ + } + } + + /* + * Updates the enable state of buttons related to the enclosing type + * selection checkbox. + */ + private void updateEnableState() { + boolean enclosing = isEnclosingTypeSelected(); + fPackageDialogField.setEnabled(fCanModifyPackage && !enclosing); + fEnclosingTypeDialogField.setEnabled(fCanModifyEnclosingType + && enclosing); + } + + /** + * Hook method that gets called when the enclosing type name has changed. + * The method validates the enclosing type and returns the status of the + * validation. It also updates the enclosing type model. + *

                                                      + * Subclasses may extend this method to perform their own validation. + *

                                                      + * + * @return the status of the validation + */ + // protected IStatus enclosingTypeChanged() { + // StatusInfo status= new StatusInfo(); + // fCurrEnclosingType= null; + // + // IPackageFragmentRoot root= getPackageFragmentRoot(); + // + // fEnclosingTypeDialogField.enableButton(root != null); + // if (root == null) { + // status.setError(""); //$NON-NLS-1$ + // return status; + // } + // + // String enclName= getEnclosingTypeText(); + // if (enclName.length() == 0) { + // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeEnterName")); + // //$NON-NLS-1$ + // return status; + // } + // try { + // IType type= findType(root.getJavaProject(), enclName); + // if (type == null) { + // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); + // //$NON-NLS-1$ + // return status; + // } + // + // if (type.getCompilationUnit() == null) { + // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotInCU")); + // //$NON-NLS-1$ + // return status; + // } + // if (!JavaModelUtil.isEditable(type.getCompilationUnit())) { + // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotEditable")); + // //$NON-NLS-1$ + // return status; + // } + // + // fCurrEnclosingType= type; + // IPackageFragmentRoot enclosingRoot= + // JavaModelUtil.getPackageFragmentRoot(type); + // if (!enclosingRoot.equals(root)) { + // status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.EnclosingNotInSourceFolder")); + // //$NON-NLS-1$ + // } + // return status; + // } catch (JavaModelException e) { + // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); + // //$NON-NLS-1$ + // PHPeclipsePlugin.log(e); + // return status; + // } + // } + /** + * Hook method that gets called when the type name has changed. The method + * validates the type name and returns the status of the validation. + *

                                                      + * Subclasses may extend this method to perform their own validation. + *

                                                      + * + * @return the status of the validation + */ + protected IStatus typeNameChanged() { + StatusInfo status = new StatusInfo(); + String typeName = getTypeName(); + // must not be empty + if (typeName.length() == 0) { + status.setError(NewWizardMessages + .getString("NewTypeWizardPage.error.EnterTypeName")); //$NON-NLS-1$ + return status; + } + if (typeName.indexOf('.') != -1) { + status.setError(NewWizardMessages + .getString("NewTypeWizardPage.error.QualifiedName")); //$NON-NLS-1$ + return status; + } + // IStatus val= JavaConventions.validateJavaTypeName(typeName); + // if (val.getSeverity() == IStatus.ERROR) { + // status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidTypeName", + // val.getMessage())); //$NON-NLS-1$ + // return status; + // } else if (val.getSeverity() == IStatus.WARNING) { + // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.TypeNameDiscouraged", + // val.getMessage())); //$NON-NLS-1$ + // // continue checking + // } + + // must not exist + if (!isEnclosingTypeSelected()) { + IPackageFragment pack = getPackageFragment(); + if (pack != null) { + ICompilationUnit cu = pack.getCompilationUnit(typeName + + ".java"); //$NON-NLS-1$ + if (cu.getResource().exists()) { + status + .setError(NewWizardMessages + .getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$ + return status; + } + } + } else { + IType type = getEnclosingType(); + if (type != null) { + IType member = type.getType(typeName); + if (member.exists()) { + status + .setError(NewWizardMessages + .getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$ + return status; + } + } + } + return status; + } + + /** + * Hook method that gets called when the superclass name has changed. The + * method validates the superclass name and returns the status of the + * validation. + *

                                                      + * Subclasses may extend this method to perform their own validation. + *

                                                      + * + * @return the status of the validation + */ + // protected IStatus superClassChanged() { + // StatusInfo status= new StatusInfo(); + // IPackageFragmentRoot root= getPackageFragmentRoot(); + // fSuperClassDialogField.enableButton(root != null); + // + // fSuperClass= null; + // + // String sclassName= getSuperClass(); + // if (sclassName.length() == 0) { + // // accept the empty field (stands for java.lang.Object) + // return status; + // } + // IStatus val= JavaConventions.validateJavaTypeName(sclassName); + // if (val.getSeverity() == IStatus.ERROR) { + // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); + // //$NON-NLS-1$ + // return status; + // } + // if (root != null) { + // try { + // IType type= resolveSuperTypeName(root.getJavaProject(), sclassName); + // if (type == null) { + // status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.SuperClassNotExists")); + // //$NON-NLS-1$ + // return status; + // } else { + // if (type.isInterface()) { + // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotClass", + // sclassName)); //$NON-NLS-1$ + // return status; + // } + // int flags= type.getFlags(); + // if (Flags.isFinal(flags)) { + // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsFinal", + // sclassName)); //$NON-NLS-1$ + // return status; + // } else if (!JavaModelUtil.isVisible(type, getPackageFragment())) { + // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotVisible", + // sclassName)); //$NON-NLS-1$ + // return status; + // } + // } + // fSuperClass= type; + // } catch (JavaModelException e) { + // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); + // //$NON-NLS-1$ + // PHPeclipsePlugin.log(e); + // } + // } else { + // status.setError(""); //$NON-NLS-1$ + // } + // return status; + // + // } + // private IType resolveSuperTypeName(IJavaProject jproject, String + // sclassName) throws JavaModelException { + // if (!jproject.exists()) { + // return null; + // } + // IType type= null; + // if (isEnclosingTypeSelected()) { + // // search in the context of the enclosing type + // IType enclosingType= getEnclosingType(); + // if (enclosingType != null) { + // String[][] res= enclosingType.resolveType(sclassName); + // if (res != null && res.length > 0) { + // type= jproject.findType(res[0][0], res[0][1]); + // } + // } + // } else { + // IPackageFragment currPack= getPackageFragment(); + // if (type == null && currPack != null) { + // String packName= currPack.getElementName(); + // // search in own package + // if (!currPack.isDefaultPackage()) { + // type= jproject.findType(packName, sclassName); + // } + // // search in java.lang + // if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$ + // type= jproject.findType("java.lang", sclassName); //$NON-NLS-1$ + // } + // } + // // search fully qualified + // if (type == null) { + // type= jproject.findType(sclassName); + // } + // } + // return type; + // } + // private IType findType(IJavaProject project, String typeName) throws + // JavaModelException { + // if (project.exists()) { + // return project.findType(typeName); + // } + // return null; + // } + /** + * Hook method that gets called when the list of super interface has + * changed. The method validates the superinterfaces and returns the status + * of the validation. + *

                                                      + * Subclasses may extend this method to perform their own validation. + *

                                                      + * + * @return the status of the validation + */ + // protected IStatus superInterfacesChanged() { + // StatusInfo status= new StatusInfo(); + // + // IPackageFragmentRoot root= getPackageFragmentRoot(); + // fSuperInterfacesDialogField.enableButton(0, root != null); + // + // if (root != null) { + // List elements= fSuperInterfacesDialogField.getElements(); + // int nElements= elements.size(); + // for (int i= 0; i < nElements; i++) { + // String intfname= (String)elements.get(i); + // try { + // IType type= findType(root.getJavaProject(), intfname); + // if (type == null) { + // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceNotExists", + // intfname)); //$NON-NLS-1$ + // return status; + // } else { + // if (type.isClass()) { + // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotInterface", + // intfname)); //$NON-NLS-1$ + // return status; + // } + // if (!JavaModelUtil.isVisible(type, getPackageFragment())) { + // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotVisible", + // intfname)); //$NON-NLS-1$ + // return status; + // } + // } + // } catch (JavaModelException e) { + // PHPeclipsePlugin.log(e); + // // let pass, checking is an extra + // } + // } + // } + // return status; + // } + /** + * Hook method that gets called when the modifiers have changed. The method + * validates the modifiers and returns the status of the validation. + *

                                                      + * Subclasses may extend this method to perform their own validation. + *

                                                      + * + * @return the status of the validation + */ + protected IStatus modifiersChanged() { + StatusInfo status = new StatusInfo(); + int modifiers = getModifiers(); + // if (Flags.isFinal(modifiers) && Flags.isAbstract(modifiers)) { + // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ModifiersFinalAndAbstract")); + // //$NON-NLS-1$ + // } + return status; + } + + // selection dialogs + + // private IPackageFragment choosePackage() { + // IPackageFragmentRoot froot= getPackageFragmentRoot(); + // IJavaElement[] packages= null; + // try { + // if (froot != null && froot.exists()) { + // packages= froot.getChildren(); + // } + // } catch (JavaModelException e) { + // PHPeclipsePlugin.log(e); + // } + // if (packages == null) { + // packages= new IJavaElement[0]; + // } + // + // ElementListSelectionDialog dialog= new + // ElementListSelectionDialog(getShell(), new + // JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT)); + // dialog.setIgnoreCase(false); + // dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.title")); + // //$NON-NLS-1$ + // dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.description")); + // //$NON-NLS-1$ + // dialog.setEmptyListMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.empty")); + // //$NON-NLS-1$ + // dialog.setElements(packages); + // IPackageFragment pack= getPackageFragment(); + // if (pack != null) { + // dialog.setInitialSelections(new Object[] { pack }); + // } + // + // if (dialog.open() == ElementListSelectionDialog.OK) { + // return (IPackageFragment) dialog.getFirstResult(); + // } + // return null; + // } + + // private IType chooseEnclosingType() { + // IPackageFragmentRoot root= getPackageFragmentRoot(); + // if (root == null) { + // return null; + // } + // + // IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new + // IJavaElement[] { root }); + // + // TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), + // getWizard().getContainer(), IJavaSearchConstants.TYPE, scope); + // dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.title")); + // //$NON-NLS-1$ + // dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.description")); + // //$NON-NLS-1$ + // dialog.setFilter(Signature.getSimpleName(getEnclosingTypeText())); + // + // if (dialog.open() == TypeSelectionDialog.OK) { + // return (IType) dialog.getFirstResult(); + // } + // return null; + // } + + // private IType chooseSuperType() { + // IPackageFragmentRoot root= getPackageFragmentRoot(); + // if (root == null) { + // return null; + // } + // + // IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; + // IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); + // + // TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), + // getWizard().getContainer(), IJavaSearchConstants.CLASS, scope); + // dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.title")); + // //$NON-NLS-1$ + // dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.message")); + // //$NON-NLS-1$ + // dialog.setFilter(getSuperClass()); + // + // if (dialog.open() == TypeSelectionDialog.OK) { + // return (IType) dialog.getFirstResult(); + // } + // return null; + // } + + // private void chooseSuperInterfaces() { + // IPackageFragmentRoot root= getPackageFragmentRoot(); + // if (root == null) { + // return; + // } + // + // IJavaProject project= root.getJavaProject(); + // SuperInterfaceSelectionDialog dialog= new + // SuperInterfaceSelectionDialog(getShell(), getWizard().getContainer(), + // fSuperInterfacesDialogField, project); + // dialog.setTitle(fIsClass ? + // NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.class.title") + // : + // NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.interface.title")); + // //$NON-NLS-1$ //$NON-NLS-2$ + // dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.message")); + // //$NON-NLS-1$ + // dialog.open(); + // return; + // } + + // ---- creation ---------------- + + /** + * Creates the new type using the entered field values. + * + * @param monitor + * a progress monitor to report progress. + */ + public void createType(IProgressMonitor monitor) throws CoreException, + InterruptedException { + if (monitor == null) { + monitor = new NullProgressMonitor(); + } + + monitor.beginTask(NewWizardMessages + .getString("NewTypeWizardPage.operationdesc"), 10); //$NON-NLS-1$ + ICompilationUnit createdWorkingCopy = null; + try { + // IPackageFragmentRoot root = getPackageFragmentRoot(); + // IPackageFragment pack = getPackageFragment(); + // if (pack == null) { + // pack = root.getPackageFragment(""); //$NON-NLS-1$ + // } + // + // if (!pack.exists()) { + // String packName = pack.getElementName(); + // pack = root.createPackageFragment(packName, true, null); + // } + + monitor.worked(1); + + String clName = getTypeName(); + + boolean isInnerClass = isEnclosingTypeSelected(); + + IType createdType; + // ImportsStructure imports; + int indent = 0; + + IPreferenceStore store = PreferenceConstants.getPreferenceStore(); + // String[] prefOrder = + // JavaPreferencesSettings.getImportOrderPreference(store); + // int threshold = + // JavaPreferencesSettings.getImportNumberThreshold(store); + // + String lineDelimiter = null; + // if (!isInnerClass) { + lineDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ + // + // ICompilationUnit parentCU = pack.createCompilationUnit(clName + + // ".php", "", false, new SubProgressMonitor(monitor, 2)); + // //$NON-NLS-1$ //$NON-NLS-2$ + // createdWorkingCopy = (ICompilationUnit) + // parentCU.getSharedWorkingCopy(null, JavaUI.getBufferFactory(), + // null); + // + // imports = new ImportsStructure(createdWorkingCopy, prefOrder, + // threshold, false); + // // add an import that will be removed again. Having this import + // solves 14661 + // imports.addImport(pack.getElementName(), getTypeName()); + // + String typeContent = constructTypeStub(lineDelimiter);// new + // ImportsManager(imports), + // lineDelimiter); + + // String cuContent = constructCUContent(parentCU, typeContent, + // lineDelimiter); + + // createdWorkingCopy.getBuffer().setContents(cuContent); + // + createdType = createdWorkingCopy.getType(clName); + // } else { + // IType enclosingType = getEnclosingType(); + // + // // if we are working on a enclosed type that is open in an + // editor, + // // then replace the enclosing type with its working copy + // IType workingCopy = (IType) + // EditorUtility.getWorkingCopy(enclosingType); + // if (workingCopy != null) { + // enclosingType = workingCopy; + // } + // + // ICompilationUnit parentCU = enclosingType.getCompilationUnit(); + // imports = new ImportsStructure(parentCU, prefOrder, threshold, + // true); + // + // // add imports that will be removed again. Having the imports + // solves 14661 + // IType[] topLevelTypes = parentCU.getTypes(); + // for (int i = 0; i < topLevelTypes.length; i++) { + // imports.addImport(topLevelTypes[i].getFullyQualifiedName('.')); + // } + // + // lineDelimiter = StubUtility.getLineDelimiterUsed(enclosingType); + // StringBuffer content = new StringBuffer(); + // String comment = getTypeComment(parentCU); + // if (comment != null) { + // content.append(comment); + // content.append(lineDelimiter); + // } + // content.append(constructTypeStub(new ImportsManager(imports), + // lineDelimiter)); + // IJavaElement[] elems = enclosingType.getChildren(); + // IJavaElement sibling = elems.length > 0 ? elems[0] : null; + // + // createdType = enclosingType.createType(content.toString(), + // sibling, false, new SubProgressMonitor(monitor, 1)); + // + // indent = StubUtility.getIndentUsed(enclosingType) + 1; + // } + // + // // add imports for superclass/interfaces, so types can be + // resolved correctly + // imports.create(false, new SubProgressMonitor(monitor, 1)); + // + ICompilationUnit cu = createdType.getCompilationUnit(); + synchronized (cu) { + cu.reconcile(); + } + // createTypeMembers(createdType, new ImportsManager(imports), new + // SubProgressMonitor(monitor, 1)); + // + // // add imports + // imports.create(false, new SubProgressMonitor(monitor, 1)); + + synchronized (cu) { + cu.reconcile(); + } + ISourceRange range = createdType.getSourceRange(); + + IBuffer buf = cu.getBuffer(); + String originalContent = buf.getText(range.getOffset(), range + .getLength()); + String formattedContent = StubUtility.codeFormat(originalContent, + indent, lineDelimiter); + buf.replace(range.getOffset(), range.getLength(), formattedContent); + if (!isInnerClass) { + String fileComment = getFileComment(cu); + if (fileComment != null && fileComment.length() > 0) { + buf.replace(0, 0, fileComment + lineDelimiter); + } + cu.commit(false, new SubProgressMonitor(monitor, 1)); + } else { + monitor.worked(1); + } + fCreatedType = createdType; + } finally { + if (createdWorkingCopy != null) { + createdWorkingCopy.destroy(); + } + monitor.done(); + } + } + + /** + * Uses the New Java file template from the code template page to generate a + * compilation unit with the given type content. + * + * @param cu + * The new created compilation unit + * @param typeContent + * The content of the type, including signature and type body. + * @param lineDelimiter + * The line delimiter to be used. + * @return String Returns the result of evaluating the new file template + * with the given type content. + * @throws CoreException + * @since 2.1 + */ + // protected String constructCUContent(ICompilationUnit cu, String + // typeContent, String lineDelimiter) throws CoreException { + // StringBuffer typeQualifiedName= new StringBuffer(); + // if (isEnclosingTypeSelected()) { + // typeQualifiedName.append(JavaModelUtil.getTypeQualifiedName(getEnclosingType())).append('.'); + // } + // typeQualifiedName.append(getTypeName()); + // String typeComment= CodeGeneration.getTypeComment(cu, + // typeQualifiedName.toString(), lineDelimiter); + // IPackageFragment pack= (IPackageFragment) cu.getParent(); + // String content= CodeGeneration.getCompilationUnitContent(cu, typeComment, + // typeContent, lineDelimiter); + // if (content != null) { + // CompilationUnit unit= AST.parseCompilationUnit(content.toCharArray()); + // if ((pack.isDefaultPackage() || unit.getPackage() != null) && + // !unit.types().isEmpty()) { + // return content; + // } + // } + // StringBuffer buf= new StringBuffer(); + // if (!pack.isDefaultPackage()) { + // buf.append("package ").append(pack.getElementName()).append(';'); + // //$NON-NLS-1$ + // } + // buf.append(lineDelimiter).append(lineDelimiter); + // if (typeComment != null) { + // buf.append(typeComment).append(lineDelimiter); + // } + // buf.append(typeContent); + // return buf.toString(); + // } + /** + * Returns the created type. The method only returns a valid type after + * createType has been called. + * + * @return the created type + * @see #createType(IProgressMonitor) + */ + public IType getCreatedType() { + return fCreatedType; + } + + // ---- construct cu body---------------- + + // private void writeSuperClass(StringBuffer buf, ImportsManager imports) { + // String typename= getSuperClass(); + // if (fIsClass && typename.length() > 0 && + // !"java.lang.Object".equals(typename)) { //$NON-NLS-1$ + // buf.append(" extends "); //$NON-NLS-1$ + // + // String qualifiedName= fSuperClass != null ? + // JavaModelUtil.getFullyQualifiedName(fSuperClass) : typename; + // buf.append(imports.addImport(qualifiedName)); + // } + // } + + // private void writeSuperInterfaces(StringBuffer buf, ImportsManager + // imports) { + // List interfaces= getSuperInterfaces(); + // int last= interfaces.size() - 1; + // if (last >= 0) { + // if (fIsClass) { + // buf.append(" implements "); //$NON-NLS-1$ + // } else { + // buf.append(" extends "); //$NON-NLS-1$ + // } + // for (int i= 0; i <= last; i++) { + // String typename= (String) interfaces.get(i); + // buf.append(imports.addImport(typename)); + // if (i < last) { + // buf.append(','); + // } + // } + // } + // } + + /* + * Called from createType to construct the source for this type + */ + private String constructTypeStub(String lineDelimiter) { // ImportsManager + // imports, + // String + // lineDelimiter) + // { + StringBuffer buf = new StringBuffer(); + + int modifiers = getModifiers(); + buf.append(Flags.toString(modifiers)); + if (modifiers != 0) { + buf.append(' '); + } + buf.append(fIsClass ? "class " : "interface "); //$NON-NLS-2$ //$NON-NLS-1$ + buf.append(getTypeName()); + // writeSuperClass(buf, imports); + // writeSuperInterfaces(buf, imports); + buf.append('{'); + buf.append(lineDelimiter); + buf.append(lineDelimiter); + buf.append('}'); + buf.append(lineDelimiter); + return buf.toString(); + } + + /** + * @deprecated Overwrite createTypeMembers(IType, IImportsManager, + * IProgressMonitor) instead + */ + // protected void createTypeMembers(IType newType, IImportsStructure + // imports, IProgressMonitor monitor) throws CoreException { + // //deprecated + // } + /** + * Hook method that gets called from createType to support + * adding of unanticipated methods, fields, and inner types to the created + * type. + *

                                                      + * Implementers can use any methods defined on IType to + * manipulate the new type. + *

                                                      + *

                                                      + * The source code of the new type will be formtted using the platform's + * formatter. Needed imports are added by the wizard at the end of the type + * creation process using the given import manager. + *

                                                      + * + * @param newType + * the new type created via createType + * @param imports + * an import manager which can be used to add new imports + * @param monitor + * a progress monitor to report progress. Must not be + * null + * + * @see #createType(IProgressMonitor) + */ + // protected void createTypeMembers(IType newType, ImportsManager imports, + // IProgressMonitor monitor) throws CoreException { + // // call for compatibility + // createTypeMembers(newType, + // ((ImportsManager)imports).getImportsStructure(), monitor); + // + // // default implementation does nothing + // // example would be + // // String mainMathod= "public void foo(Vector vec) {}" + // // createdType.createMethod(main, null, false, null); + // // imports.addImport("java.lang.Vector"); + // } + /** + * @deprecated Instead of file templates, the new type code template + * specifies the stub for a compilation unit. + */ + protected String getFileComment(ICompilationUnit parentCU) { + return null; + } + + private boolean isValidComment(String template) { + IScanner scanner = ToolFactory.createScanner(true, false, false); // , + // false); + scanner.setSource(template.toCharArray()); + try { + int next = scanner.getNextToken(); + while (next == ITerminalSymbols.TokenNameCOMMENT_LINE + || next == ITerminalSymbols.TokenNameCOMMENT_PHPDOC + || next == ITerminalSymbols.TokenNameCOMMENT_BLOCK) { + next = scanner.getNextToken(); + } + return next == ITerminalSymbols.TokenNameEOF; + } catch (InvalidInputException e) { + } + return false; + } + + /** + * Hook method that gets called from createType to retrieve a + * type comment. This default implementation returns the content of the + * 'typecomment' template. + * + * @return the type comment or null if a type comment is not + * desired + */ + protected String getTypeComment(ICompilationUnit parentCU) { + if (PreferenceConstants.getPreferenceStore().getBoolean( + PreferenceConstants.CODEGEN_ADD_COMMENTS)) { + try { + StringBuffer typeName = new StringBuffer(); + if (isEnclosingTypeSelected()) { + typeName.append( + JavaModelUtil + .getTypeQualifiedName(getEnclosingType())) + .append('.'); + } + typeName.append(getTypeName()); + String comment = CodeGeneration.getTypeComment(parentCU, + typeName.toString(), String.valueOf('\n')); + if (comment != null && isValidComment(comment)) { + return comment; + } + } catch (CoreException e) { + PHPeclipsePlugin.log(e); + } + } + return null; + } + + /** + * @deprecated Use getTemplate(String,ICompilationUnit,int) + */ + protected String getTemplate(String name, ICompilationUnit parentCU) { + return getTemplate(name, parentCU, 0); + } + + /** + * Returns the string resulting from evaluation the given template in the + * context of the given compilation unit. This accesses the normal template + * page, not the code templates. To use code templates use + * constructCUContent to construct a compilation unit stub or + * getTypeComment for the comment of the type. + * + * @param name + * the template to be evaluated + * @param parentCU + * the templates evaluation context + * @param pos + * a source offset into the parent compilation unit. The template + * is evalutated at the given source offset + */ + protected String getTemplate(String name, ICompilationUnit parentCU, int pos) { + try { + Template[] templates = Templates.getInstance().getTemplates(name); + if (templates.length > 0) { + return JavaContext + .evaluateTemplate(templates[0], parentCU, pos); + } + } catch (CoreException e) { + PHPeclipsePlugin.log(e); + } catch (BadLocationException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (TemplateException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + return null; + } + + /** + * @deprecated Use + * createInheritedMethods(IType,boolean,boolean,IImportsManager,IProgressMonitor) + */ + // protected IMethod[] createInheritedMethods(IType type, boolean + // doConstructors, boolean doUnimplementedMethods, IImportsStructure + // imports, IProgressMonitor monitor) throws CoreException { + // return createInheritedMethods(type, doConstructors, + // doUnimplementedMethods, new ImportsManager(imports), monitor); + // } + /** + * Creates the bodies of all unimplemented methods and constructors and adds + * them to the type. Method is typically called by implementers of + * NewTypeWizardPage to add needed method and constructors. + * + * @param type + * the type for which the new methods and constructor are to be + * created + * @param doConstructors + * if true unimplemented constructors are created + * @param doUnimplementedMethods + * if true unimplemented methods are created + * @param imports + * an import manager to add all neded import statements + * @param monitor + * a progress monitor to report progress + */ + // protected IMethod[] createInheritedMethods(IType type, boolean + // doConstructors, boolean doUnimplementedMethods, ImportsManager imports, + // IProgressMonitor monitor) throws CoreException { + // ArrayList newMethods= new ArrayList(); + // ITypeHierarchy hierarchy= null; + // CodeGenerationSettings settings= + // JavaPreferencesSettings.getCodeGenerationSettings(); + // + // if (doConstructors) { + // hierarchy= type.newSupertypeHierarchy(monitor); + // IType superclass= hierarchy.getSuperclass(type); + // if (superclass != null) { + // String[] constructors= StubUtility.evalConstructors(type, superclass, + // settings, imports.getImportsStructure()); + // if (constructors != null) { + // for (int i= 0; i < constructors.length; i++) { + // newMethods.add(constructors[i]); + // } + // } + // + // } + // } + // if (doUnimplementedMethods) { + // if (hierarchy == null) { + // hierarchy= type.newSupertypeHierarchy(monitor); + // } + // String[] unimplemented= StubUtility.evalUnimplementedMethods(type, + // hierarchy, false, settings, null, imports.getImportsStructure()); + // if (unimplemented != null) { + // for (int i= 0; i < unimplemented.length; i++) { + // newMethods.add(unimplemented[i]); + // } + // } + // } + // IMethod[] createdMethods= new IMethod[newMethods.size()]; + // for (int i= 0; i < newMethods.size(); i++) { + // String content= (String) newMethods.get(i) + '\n'; // content will be + // formatted, ok to use \n + // createdMethods[i]= type.createMethod(content, null, false, null); + // } + // return createdMethods; + // } + // ---- creation ---------------- + /** + * Returns the runnable that creates the type using the current settings. + * The returned runnable must be executed in the UI thread. + * + * @return the runnable to create the new type + */ + // public IRunnableWithProgress getRunnable() { + // return new IRunnableWithProgress() { + // public void run(IProgressMonitor monitor) throws + // InvocationTargetException, InterruptedException { + // try { + // if (monitor == null) { + // monitor= new NullProgressMonitor(); + // } + // createType(monitor); + // } catch (CoreException e) { + // throw new InvocationTargetException(e); + // } + // } + // }; + // } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/IPreferenceConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/IPreferenceConstants.java index f0f5946..6b399eb 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/IPreferenceConstants.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/IPreferenceConstants.java @@ -11,349 +11,394 @@ **********************************************************************/ package net.sourceforge.phpeclipse; - /** * Predefined prference constants */ public interface IPreferenceConstants { - /** - * Preference key suffix for bold text style preference keys. - * - * @since 2.1 - */ - public static final String EDITOR_BOLD_SUFFIX = "_bold"; //$NON-NLS-1$ - - /** - * Preference key suffix for italic text style preference keys. - * - * @since 3.0 - */ - public static final String EDITOR_ITALIC_SUFFIX = "_italic"; //$NON-NLS-1$ - - // public static final String LOCALHOST_PREF = "_localhost"; - // public static final String DOCUMENTROOT_PREF = "_documentroot"; -// public static final String XAMPP_START_PREF = "_xampp_start_pref"; -// -// public static final String XAMPP_STOP_PREF = "_xampp_stop_pref"; -// -// public static final String MYSQL_RUN_PREF = "_mysql_run_pref"; -// -// public static final String MYSQL_START_BACKGROUND = "_mysql_start_background"; -// -// public static final String MYSQL_PREF = "__mysql_start"; -// -// public static final String APACHE_RUN_PREF = "_apache_run_pref"; -// -// public static final String APACHE_START_BACKGROUND = "_apache_start_background"; -// -// public static final String APACHE_START_PREF = "__apache_start"; -// -// public static final String APACHE_STOP_BACKGROUND = "_apache_stop_background"; -// -// public static final String APACHE_STOP_PREF = "__apache_stop"; -// -// public static final String APACHE_RESTART_BACKGROUND = "_apache_restart_background"; -// -// public static final String APACHE_RESTART_PREF = "__apache_restart"; - -// public static final String HTTPD_CONF_PATH_PREF = "__httpd_conf_path"; -// -// public static final String ETC_HOSTS_PATH_PREF = "__etc_hosts_path"; - -// public static final String SHOW_OUTPUT_IN_CONSOLE = "_show_output_in_console"; - -// public static final String PHP_RUN_PREF = "_php_run_pref"; -// -// public static final String EXTERNAL_PARSER_PREF = "_external_parser"; - -// public static final String PHP_EXTENSION_PREFS = "_php_parser_extensions"; - -// public static final String PHP_PARSER_DEFAULT = "_php_parser_default"; - - // public static final String PHP_INTERNAL_PARSER = "_php_internal_parser"; - // public static final String PHP_EXTERNAL_PARSER = "_php_external_parser"; - // public static final String PHP_PARSE_ON_SAVE = "_php_parse_on_save"; - public static final String PHP_MULTILINE_COMMENT = "_php_multilineComment"; - - public static final String PHP_MULTILINE_COMMENT_BOLD = "_php_multilineComment_bold"; - - public static final String PHP_MULTILINE_COMMENT_ITALIC = "_php_multilineComment_italic"; - - public static final String PHP_MULTILINE_COMMENT_UNDERLINE = "_php_multilineComment_underline"; - - /** - * The color key for operators and brackets in PHP code (value "__php_operator"). - * - * @since 3.0 - */ - public static final String PHP_OPERATOR = "__php_operator"; //$NON-NLS-1$ - - /** - * The color key for {} in PHP code (value "__php_brace_operator"). - * - * @since 3.0 - */ - public static final String PHP_BRACE_OPERATOR = "__php_brace_operator"; //$NON-NLS-1$ - - /** - * A named preference that holds the color used to render operators and brackets. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - * @since 3.0 - */ - public final static String EDITOR_PHP_OPERATOR_COLOR = PHP_OPERATOR; - - /** - * A named preference that controls whether operators and brackets are rendered in bold. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String EDITOR_PHP_OPERATOR_BOLD = PHP_OPERATOR + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that controls whether operators and brackets are rendered in italic. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String EDITOR_PHP_OPERATOR_ITALIC = PHP_OPERATOR + EDITOR_ITALIC_SUFFIX; - - /** - * A named preference that holds the color used to render operators and brackets. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - * @since 3.0 - */ - public final static String EDITOR_PHP_BRACE_OPERATOR_COLOR = PHP_BRACE_OPERATOR; - - /** - * A named preference that controls whether operators and brackets are rendered in bold. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String EDITOR_PHP_BRACE_OPERATOR_BOLD = PHP_BRACE_OPERATOR + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that controls whether operators and brackets are rendered in italic. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String EDITOR_PHP_BRACE_OPERATOR_ITALIC = PHP_BRACE_OPERATOR + EDITOR_ITALIC_SUFFIX; - - /** - * The color key for keyword 'return' in PHP code (value "__php_keyword_return"). - * - * @since 3.0 - */ - public static final String PHP_KEYWORD_RETURN = "__php_keyword_return"; //$NON-NLS-1$ - - /** - * A named preference that holds the color used to render the 'return' keyword. - *

                                                      - * Value is of type String. A RGB color value encoded as a string using class PreferenceConverter - *

                                                      - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - * @since 3.0 - */ - public final static String EDITOR_PHP_KEYWORD_RETURN_COLOR = PHP_KEYWORD_RETURN; - - /** - * A named preference that controls whether 'return' keyword is rendered in bold. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String EDITOR_PHP_KEYWORD_RETURN_BOLD = PHP_KEYWORD_RETURN + EDITOR_BOLD_SUFFIX; + /** + * Preference key suffix for bold text style preference keys. + * + * @since 2.1 + */ + public static final String EDITOR_BOLD_SUFFIX = "_bold"; //$NON-NLS-1$ + + /** + * Preference key suffix for italic text style preference keys. + * + * @since 3.0 + */ + public static final String EDITOR_ITALIC_SUFFIX = "_italic"; //$NON-NLS-1$ + + // public static final String LOCALHOST_PREF = "_localhost"; + // public static final String DOCUMENTROOT_PREF = "_documentroot"; + // public static final String XAMPP_START_PREF = "_xampp_start_pref"; + // + // public static final String XAMPP_STOP_PREF = "_xampp_stop_pref"; + // + // public static final String MYSQL_RUN_PREF = "_mysql_run_pref"; + // + // public static final String MYSQL_START_BACKGROUND = + // "_mysql_start_background"; + // + // public static final String MYSQL_PREF = "__mysql_start"; + // + // public static final String APACHE_RUN_PREF = "_apache_run_pref"; + // + // public static final String APACHE_START_BACKGROUND = + // "_apache_start_background"; + // + // public static final String APACHE_START_PREF = "__apache_start"; + // + // public static final String APACHE_STOP_BACKGROUND = + // "_apache_stop_background"; + // + // public static final String APACHE_STOP_PREF = "__apache_stop"; + // + // public static final String APACHE_RESTART_BACKGROUND = + // "_apache_restart_background"; + // + // public static final String APACHE_RESTART_PREF = "__apache_restart"; + + // public static final String HTTPD_CONF_PATH_PREF = "__httpd_conf_path"; + // + // public static final String ETC_HOSTS_PATH_PREF = "__etc_hosts_path"; + + // public static final String SHOW_OUTPUT_IN_CONSOLE = + // "_show_output_in_console"; + + // public static final String PHP_RUN_PREF = "_php_run_pref"; + // + // public static final String EXTERNAL_PARSER_PREF = "_external_parser"; + + // public static final String PHP_EXTENSION_PREFS = + // "_php_parser_extensions"; + + // public static final String PHP_PARSER_DEFAULT = "_php_parser_default"; + + // public static final String PHP_INTERNAL_PARSER = "_php_internal_parser"; + // public static final String PHP_EXTERNAL_PARSER = "_php_external_parser"; + // public static final String PHP_PARSE_ON_SAVE = "_php_parse_on_save"; + public static final String PHP_MULTILINE_COMMENT = "_php_multilineComment"; + + public static final String PHP_MULTILINE_COMMENT_BOLD = "_php_multilineComment_bold"; + + public static final String PHP_MULTILINE_COMMENT_ITALIC = "_php_multilineComment_italic"; + + public static final String PHP_MULTILINE_COMMENT_UNDERLINE = "_php_multilineComment_underline"; + + /** + * The color key for operators and brackets in PHP code (value + * "__php_operator"). + * + * @since 3.0 + */ + public static final String PHP_OPERATOR = "__php_operator"; //$NON-NLS-1$ + + /** + * The color key for {} in PHP code (value + * "__php_brace_operator"). + * + * @since 3.0 + */ + public static final String PHP_BRACE_OPERATOR = "__php_brace_operator"; //$NON-NLS-1$ + + /** + * A named preference that holds the color used to render operators and + * brackets. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + * @since 3.0 + */ + public final static String EDITOR_PHP_OPERATOR_COLOR = PHP_OPERATOR; + + /** + * A named preference that controls whether operators and brackets are + * rendered in bold. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String EDITOR_PHP_OPERATOR_BOLD = PHP_OPERATOR + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that controls whether operators and brackets are + * rendered in italic. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String EDITOR_PHP_OPERATOR_ITALIC = PHP_OPERATOR + + EDITOR_ITALIC_SUFFIX; + + /** + * A named preference that holds the color used to render operators and + * brackets. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + * @since 3.0 + */ + public final static String EDITOR_PHP_BRACE_OPERATOR_COLOR = PHP_BRACE_OPERATOR; + + /** + * A named preference that controls whether operators and brackets are + * rendered in bold. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String EDITOR_PHP_BRACE_OPERATOR_BOLD = PHP_BRACE_OPERATOR + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that controls whether operators and brackets are + * rendered in italic. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String EDITOR_PHP_BRACE_OPERATOR_ITALIC = PHP_BRACE_OPERATOR + + EDITOR_ITALIC_SUFFIX; + + /** + * The color key for keyword 'return' in PHP code (value + * "__php_keyword_return"). + * + * @since 3.0 + */ + public static final String PHP_KEYWORD_RETURN = "__php_keyword_return"; //$NON-NLS-1$ + + /** + * A named preference that holds the color used to render the 'return' + * keyword. + *

                                                      + * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

                                                      + * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + * @since 3.0 + */ + public final static String EDITOR_PHP_KEYWORD_RETURN_COLOR = PHP_KEYWORD_RETURN; + + /** + * A named preference that controls whether 'return' keyword is rendered in + * bold. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String EDITOR_PHP_KEYWORD_RETURN_BOLD = PHP_KEYWORD_RETURN + + EDITOR_BOLD_SUFFIX; - /** - * A named preference that controls whether 'return' keyword is rendered in italic. - *

                                                      - * Value is of type Boolean. - *

                                                      - * - * @since 3.0 - */ - public final static String EDITOR_PHP_KEYWORD_RETURN_ITALIC = PHP_KEYWORD_RETURN + EDITOR_ITALIC_SUFFIX; + /** + * A named preference that controls whether 'return' keyword is rendered in + * italic. + *

                                                      + * Value is of type Boolean. + *

                                                      + * + * @since 3.0 + */ + public final static String EDITOR_PHP_KEYWORD_RETURN_ITALIC = PHP_KEYWORD_RETURN + + EDITOR_ITALIC_SUFFIX; - public static final String PHP_SINGLELINE_COMMENT = "_php_singlelineComment"; + public static final String PHP_SINGLELINE_COMMENT = "_php_singlelineComment"; - public static final String PHP_SINGLELINE_COMMENT_BOLD = "_php_singlelineComment_bold";//$NON-NLS-1$ + public static final String PHP_SINGLELINE_COMMENT_BOLD = "_php_singlelineComment_bold";//$NON-NLS-1$ - public static final String PHP_SINGLELINE_COMMENT_ITALIC = "_php_singlelineComment_italic";//$NON-NLS-1$ + public static final String PHP_SINGLELINE_COMMENT_ITALIC = "_php_singlelineComment_italic";//$NON-NLS-1$ - public static final String PHP_SINGLELINE_COMMENT_UNDERLINE = "_php_singlelineComment_underline";//$NON-NLS-1$ + public static final String PHP_SINGLELINE_COMMENT_UNDERLINE = "_php_singlelineComment_underline";//$NON-NLS-1$ - public static final String PHP_TAG = "_php_tag";//$NON-NLS-1$ + public static final String PHP_TAG = "_php_tag";//$NON-NLS-1$ - public static final String PHP_TAG_BOLD = "_php_tag_bold";//$NON-NLS-1$ + public static final String PHP_TAG_BOLD = "_php_tag_bold";//$NON-NLS-1$ - public static final String PHP_TAG_ITALIC = "_php_tag_italic";//$NON-NLS-1$ + public static final String PHP_TAG_ITALIC = "_php_tag_italic";//$NON-NLS-1$ - public static final String PHP_TAG_UNDERLINE = "_php_tag_underline";//$NON-NLS-1$ + public static final String PHP_TAG_UNDERLINE = "_php_tag_underline";//$NON-NLS-1$ - public static final String PHP_KEYWORD = "_php_keyword";//$NON-NLS-1$ + public static final String PHP_KEYWORD = "_php_keyword";//$NON-NLS-1$ - public static final String PHP_KEYWORD_BOLD = "_php_keyword_bold";//$NON-NLS-1$ + public static final String PHP_KEYWORD_BOLD = "_php_keyword_bold";//$NON-NLS-1$ - public static final String PHP_KEYWORD_ITALIC = "_php_keyword_italic";//$NON-NLS-1$ + public static final String PHP_KEYWORD_ITALIC = "_php_keyword_italic";//$NON-NLS-1$ - public static final String PHP_KEYWORD_UNDERLINE = "_php_keyword_underline";//$NON-NLS-1$ + public static final String PHP_KEYWORD_UNDERLINE = "_php_keyword_underline";//$NON-NLS-1$ - public static final String PHP_VARIABLE = "_php_variable";//$NON-NLS-1$ + public static final String PHP_VARIABLE = "_php_variable";//$NON-NLS-1$ - public static final String PHP_VARIABLE_BOLD = "_php_variable_bold";//$NON-NLS-1$ + public static final String PHP_VARIABLE_BOLD = "_php_variable_bold";//$NON-NLS-1$ - public static final String PHP_VARIABLE_ITALIC = "_php_variable_italic";//$NON-NLS-1$ + public static final String PHP_VARIABLE_ITALIC = "_php_variable_italic";//$NON-NLS-1$ - public static final String PHP_VARIABLE_UNDERLINE = "_php_variable_underline";//$NON-NLS-1$ + public static final String PHP_VARIABLE_UNDERLINE = "_php_variable_underline";//$NON-NLS-1$ - public static final String PHP_VARIABLE_DOLLAR = "_php_variable_dollar";//$NON-NLS-1$ + public static final String PHP_VARIABLE_DOLLAR = "_php_variable_dollar";//$NON-NLS-1$ - public static final String PHP_VARIABLE_DOLLAR_BOLD = "_php_variable_dollar_bold";//$NON-NLS-1$ + public static final String PHP_VARIABLE_DOLLAR_BOLD = "_php_variable_dollar_bold";//$NON-NLS-1$ - public static final String PHP_VARIABLE_DOLLAR_ITALIC = "_php_variable_dollar_italic";//$NON-NLS-1$ + public static final String PHP_VARIABLE_DOLLAR_ITALIC = "_php_variable_dollar_italic";//$NON-NLS-1$ - public static final String PHP_VARIABLE_DOLLAR_UNDERLINE = "_php_variable_dollar_underline";//$NON-NLS-1$ + public static final String PHP_VARIABLE_DOLLAR_UNDERLINE = "_php_variable_dollar_underline";//$NON-NLS-1$ - public static final String PHP_TYPE = "_php_type";//$NON-NLS-1$ + public static final String PHP_TYPE = "_php_type";//$NON-NLS-1$ - public static final String PHP_TYPE_BOLD = "_php_type_bold";//$NON-NLS-1$ + public static final String PHP_TYPE_BOLD = "_php_type_bold";//$NON-NLS-1$ - public static final String PHP_TYPE_ITALIC = "_php_type_italic";//$NON-NLS-1$ + public static final String PHP_TYPE_ITALIC = "_php_type_italic";//$NON-NLS-1$ - public static final String PHP_TYPE_UNDERLINE = "_php_type_underline";//$NON-NLS-1$ + public static final String PHP_TYPE_UNDERLINE = "_php_type_underline";//$NON-NLS-1$ - public static final String PHP_CONSTANT = "_php_constant";//$NON-NLS-1$ + public static final String PHP_CONSTANT = "_php_constant";//$NON-NLS-1$ - public static final String PHP_CONSTANT_BOLD = "_php_constant_bold";//$NON-NLS-1$ + public static final String PHP_CONSTANT_BOLD = "_php_constant_bold";//$NON-NLS-1$ - public static final String PHP_CONSTANT_ITALIC = "_php_constant_italic";//$NON-NLS-1$ + public static final String PHP_CONSTANT_ITALIC = "_php_constant_italic";//$NON-NLS-1$ - public static final String PHP_CONSTANT_UNDERLINE = "_php_constant_underline";//$NON-NLS-1$ + public static final String PHP_CONSTANT_UNDERLINE = "_php_constant_underline";//$NON-NLS-1$ - public static final String PHP_FUNCTIONNAME = "_php_functionname";//$NON-NLS-1$ + public static final String PHP_FUNCTIONNAME = "_php_functionname";//$NON-NLS-1$ - public static final String PHP_FUNCTIONNAME_BOLD = "_php_functionname_bold";//$NON-NLS-1$ + public static final String PHP_FUNCTIONNAME_BOLD = "_php_functionname_bold";//$NON-NLS-1$ - public static final String PHP_FUNCTIONNAME_ITALIC = "_php_functionname_italic";//$NON-NLS-1$ + public static final String PHP_FUNCTIONNAME_ITALIC = "_php_functionname_italic";//$NON-NLS-1$ - public static final String PHP_FUNCTIONNAME_UNDERLINE = "_php_functionname_underline";//$NON-NLS-1$ + public static final String PHP_FUNCTIONNAME_UNDERLINE = "_php_functionname_underline";//$NON-NLS-1$ - public static final String PHP_STRING_DQ = "_php_string";//$NON-NLS-1$ + public static final String PHP_STRING_DQ = "_php_string";//$NON-NLS-1$ - public static final String PHP_STRING_BOLD_DQ = "_php_string_bold"; + public static final String PHP_STRING_BOLD_DQ = "_php_string_bold"; - public static final String PHP_STRING_ITALIC_DQ = "_php_string_italic"; + public static final String PHP_STRING_ITALIC_DQ = "_php_string_italic"; - public static final String PHP_STRING_UNDERLINE_DQ = "_php_string_underline"; + public static final String PHP_STRING_UNDERLINE_DQ = "_php_string_underline"; - public static final String PHP_STRING_SQ = "_php_string_sq";//$NON-NLS-1$ + public static final String PHP_STRING_SQ = "_php_string_sq";//$NON-NLS-1$ - public static final String PHP_STRING_BOLD_SQ = "_php_string_sq_bold"; + public static final String PHP_STRING_BOLD_SQ = "_php_string_sq_bold"; - public static final String PHP_STRING_ITALIC_SQ = "_php_string_sq_italic"; + public static final String PHP_STRING_ITALIC_SQ = "_php_string_sq_italic"; - public static final String PHP_STRING_UNDERLINE_SQ = "_php_string_sq_underline"; + public static final String PHP_STRING_UNDERLINE_SQ = "_php_string_sq_underline"; - public static final String PHP_DEFAULT = "_php_default"; + public static final String PHP_DEFAULT = "_php_default"; - public static final String PHP_DEFAULT_BOLD = "_php_default_bold"; + public static final String PHP_DEFAULT_BOLD = "_php_default_bold"; - public static final String PHP_DEFAULT_ITALIC = "_php_default_italic"; + public static final String PHP_DEFAULT_ITALIC = "_php_default_italic"; - public static final String PHP_DEFAULT_UNDERLINE = "_php_default_underline"; + public static final String PHP_DEFAULT_UNDERLINE = "_php_default_underline"; - public static final String TASK_TAG = "_php_comment_task_tag"; //$NON-NLS-1$ + public static final String TASK_TAG = "_php_comment_task_tag"; //$NON-NLS-1$ - public static final String TASK_TAG_BOLD = "_php_comment_task_tag_bold"; //$NON-NLS-1$ + public static final String TASK_TAG_BOLD = "_php_comment_task_tag_bold"; //$NON-NLS-1$ - /** - * The color key for PHPDoc keywords (@foo) in PHPDoc comments. - */ - public static final String PHPDOC_KEYWORD = "_php_doc_keyword"; //$NON-NLS-1$ + /** + * The color key for PHPDoc keywords (@foo) in PHPDoc comments. + */ + public static final String PHPDOC_KEYWORD = "_php_doc_keyword"; //$NON-NLS-1$ - public static final String PHPDOC_KEYWORD_BOLD = "_php_doc_keyword_bold"; + public static final String PHPDOC_KEYWORD_BOLD = "_php_doc_keyword_bold"; - public static final String PHPDOC_KEYWORD_ITALIC = "_php_doc_keyword_italic"; + public static final String PHPDOC_KEYWORD_ITALIC = "_php_doc_keyword_italic"; - public static final String PHPDOC_KEYWORD_UNDERLINE = "_php_doc_keyword_underline"; + public static final String PHPDOC_KEYWORD_UNDERLINE = "_php_doc_keyword_underline"; - /** The color key for HTML tags (<foo>) in PHPDoc comments. */ - public static final String PHPDOC_TAG = "_php_doc_tag"; //$NON-NLS-1$ + /** + * The color key for HTML tags (<foo>) in PHPDoc + * comments. + */ + public static final String PHPDOC_TAG = "_php_doc_tag"; //$NON-NLS-1$ - public static final String PHPDOC_TAG_BOLD = "_php_doc_tag_bold"; + public static final String PHPDOC_TAG_BOLD = "_php_doc_tag_bold"; - public static final String PHPDOC_TAG_ITALIC = "_php_doc_tag_italic"; + public static final String PHPDOC_TAG_ITALIC = "_php_doc_tag_italic"; - public static final String PHPDOC_TAG_UNDERLINE = "_php_doc_tag_underline"; + public static final String PHPDOC_TAG_UNDERLINE = "_php_doc_tag_underline"; - /** The color key for PHPDoc links ({foo}) in PHPDoc comments. */ - public static final String PHPDOC_LINK = "_php_doc_link"; //$NON-NLS-1$ + /** + * The color key for PHPDoc links ({foo}) in PHPDoc + * comments. + */ + public static final String PHPDOC_LINK = "_php_doc_link"; //$NON-NLS-1$ - public static final String PHPDOC_LINK_BOLD = "_php_doc_link_bold"; + public static final String PHPDOC_LINK_BOLD = "_php_doc_link_bold"; - public static final String PHPDOC_LINK_ITALIC = "_php_doc_link_italic"; + public static final String PHPDOC_LINK_ITALIC = "_php_doc_link_italic"; - public static final String PHPDOC_LINK_UNDERLINE = "_php_doc_link_underline"; + public static final String PHPDOC_LINK_UNDERLINE = "_php_doc_link_underline"; - /** The color key for everthing in PHPDoc comments for which no other color is specified. */ - public static final String PHPDOC_DEFAULT = "_php_doc_default"; //$NON-NLS-1$ + /** + * The color key for everthing in PHPDoc comments for which no other color + * is specified. + */ + public static final String PHPDOC_DEFAULT = "_php_doc_default"; //$NON-NLS-1$ - public static final String PHPDOC_DEFAULT_BOLD = "_php_doc_default_bold"; + public static final String PHPDOC_DEFAULT_BOLD = "_php_doc_default_bold"; - public static final String PHPDOC_DEFAULT_ITALIC = "_php_doc_default_italic"; + public static final String PHPDOC_DEFAULT_ITALIC = "_php_doc_default_italic"; - public static final String PHPDOC_DEFAULT_UNDERLINE = "_php_doc_default_underline"; + public static final String PHPDOC_DEFAULT_UNDERLINE = "_php_doc_default_underline"; - // public static final String LINKED_POSITION_COLOR = "_linkedPositionColor"; - // public static final String PHP_EDITOR_BACKGROUND = "_php_editor_background"; - public static final String PHP_USERDEF_XMLFILE = "_userdef_xmlfile"; + // public static final String LINKED_POSITION_COLOR = + // "_linkedPositionColor"; + // public static final String PHP_EDITOR_BACKGROUND = + // "_php_editor_background"; + public static final String PHP_USERDEF_XMLFILE = "_userdef_xmlfile"; - /** Preference key for showing the line number ruler */ - // public final static String LINE_NUMBER_RULER = "_lineNumberRuler"; //$NON-NLS-1$ - /** Preference key for the foreground color of the line numbers */ - // public final static String LINE_NUMBER_COLOR = "_lineNumberColor"; //$NON-NLS-1$ - // public final static String PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT = "_defaultBackgroundColor"; //$NON-NLS-1$ - // public final static String PREFERENCE_COLOR_BACKGROUND = "backgroundColor"; //$NON-NLS-1$ - /** Preference key for content assist proposal color */ - public final static String PROPOSALS_FOREGROUND = "content_assist_proposals_foreground"; //$NON-NLS-1$ + /** Preference key for showing the line number ruler */ + // public final static String LINE_NUMBER_RULER = "_lineNumberRuler"; + // //$NON-NLS-1$ + /** Preference key for the foreground color of the line numbers */ + // public final static String LINE_NUMBER_COLOR = "_lineNumberColor"; + // //$NON-NLS-1$ + // public final static String PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT = + // "_defaultBackgroundColor"; //$NON-NLS-1$ + // public final static String PREFERENCE_COLOR_BACKGROUND = + // "backgroundColor"; //$NON-NLS-1$ + /** Preference key for content assist proposal color */ + public final static String PROPOSALS_FOREGROUND = "content_assist_proposals_foreground"; //$NON-NLS-1$ - /** Preference key for content assist proposal color */ - public final static String PROPOSALS_BACKGROUND = "content_assist_proposals_background"; //$NON-NLS-1$ + /** Preference key for content assist proposal color */ + public final static String PROPOSALS_BACKGROUND = "content_assist_proposals_background"; //$NON-NLS-1$ - public static final String EDITOR_EVALUTE_TEMPORARY_PROBLEMS = null; + public static final String EDITOR_EVALUTE_TEMPORARY_PROBLEMS = null; - public static final String EDITOR_CORRECTION_INDICATION = null; + public static final String EDITOR_CORRECTION_INDICATION = null; -// public static final String PHP_OBFUSCATOR_DEFAULT = "_php_obfuscator_default"; - // public static final String PHP_BOOKMARK_DEFAULT = "_php_bookmark_default"; - // public static final String PHP_LOCALHOST_PREF = "_php_localhost"; - // public static final String PHP_DOCUMENTROOT_PREF = "_php_documentroot"; - // - // public static final String PHP_AUTO_PREVIEW_DEFAULT = "_auto_preview"; - // public static final String PHP_BRING_TO_TOP_PREVIEW_DEFAULT = "_bring_to_top_preview"; - // public static final String PHP_SHOW_HTML_FILES_LOCAL = "_show_html_files_local"; + // public static final String PHP_OBFUSCATOR_DEFAULT = + // "_php_obfuscator_default"; + // public static final String PHP_BOOKMARK_DEFAULT = + // "_php_bookmark_default"; + // public static final String PHP_LOCALHOST_PREF = "_php_localhost"; + // public static final String PHP_DOCUMENTROOT_PREF = "_php_documentroot"; + // + // public static final String PHP_AUTO_PREVIEW_DEFAULT = "_auto_preview"; + // public static final String PHP_BRING_TO_TOP_PREVIEW_DEFAULT = + // "_bring_to_top_preview"; + // public static final String PHP_SHOW_HTML_FILES_LOCAL = + // "_show_html_files_local"; } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/LoadPathEntry.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/LoadPathEntry.java index e908153..92e2c43 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/LoadPathEntry.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/LoadPathEntry.java @@ -4,35 +4,36 @@ import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IPath; public class LoadPathEntry { - public static final String TYPE_PROJECT = "project"; + public static final String TYPE_PROJECT = "project"; - protected IProject project; - protected String type; + protected IProject project; - public LoadPathEntry(IProject aProjectEntry) { - project = aProjectEntry; - type = TYPE_PROJECT; - } + protected String type; - public IPath getPath() { - return project.getFullPath(); - } + public LoadPathEntry(IProject aProjectEntry) { + project = aProjectEntry; + type = TYPE_PROJECT; + } - public IProject getProject() { - return project; - } + public IPath getPath() { + return project.getFullPath(); + } - public String getType() { - return type; - } + public IProject getProject() { + return project; + } - public String toXML() { - StringBuffer buffer = new StringBuffer(); + public String getType() { + return type; + } - buffer.append(""); + public String toXML() { + StringBuffer buffer = new StringBuffer(); - return buffer.toString(); - } + buffer.append(""); + + return buffer.toString(); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPConsole.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPConsole.java index b4d4a3f..c7ddf42 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPConsole.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPConsole.java @@ -10,98 +10,102 @@ import org.eclipse.ui.console.MessageConsole; import org.eclipse.ui.console.MessageConsoleStream; public class PHPConsole { - private MessageConsole myConsole; + private MessageConsole myConsole; - private MessageConsoleStream stream; + private MessageConsoleStream stream; - private boolean hasMessages; + private boolean hasMessages; - public PHPConsole() { - hasMessages = false; - myConsole = new MessageConsole("PHPeclipse Console", null); - ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[] { myConsole }); - ConsolePlugin.getDefault().getConsoleManager().showConsoleView(myConsole); - // layout.addView(IConsoleConstants.ID_CONSOLE_VIEW, IPageLayout.BOTTOM, .5f,IPageLayout.ID_EDITOR_AREA); - stream = myConsole.newMessageStream(); - } + public PHPConsole() { + hasMessages = false; + myConsole = new MessageConsole("PHPeclipse Console", null); + ConsolePlugin.getDefault().getConsoleManager().addConsoles( + new IConsole[] { myConsole }); + ConsolePlugin.getDefault().getConsoleManager().showConsoleView( + myConsole); + // layout.addView(IConsoleConstants.ID_CONSOLE_VIEW, IPageLayout.BOTTOM, + // .5f,IPageLayout.ID_EDITOR_AREA); + stream = myConsole.newMessageStream(); + } - /** - * @return - */ - public Color getColor() { - return stream.getColor(); - } + /** + * @return + */ + public Color getColor() { + return stream.getColor(); + } - /** - * @return - */ - public MessageConsole getConsole() { - return stream.getConsole(); - } + /** + * @return + */ + public MessageConsole getConsole() { + return stream.getConsole(); + } - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - public int hashCode() { - return stream.hashCode(); - } + /* + * (non-Javadoc) + * + * @see java.lang.Object#hashCode() + */ + public int hashCode() { + return stream.hashCode(); + } - /** - * @param message - */ - public void print(String message) { - hasMessages = true; - stream.print(message); - } + /** + * @param message + */ + public void print(String message) { + hasMessages = true; + stream.print(message); + } - /** - * - */ - public void println() { - hasMessages = true; - stream.println(); - } + /** + * + */ + public void println() { + hasMessages = true; + stream.println(); + } - /** - * @param message - */ - public void println(String message) { - hasMessages = true; - stream.println(message); - } + /** + * @param message + */ + public void println(String message) { + hasMessages = true; + stream.println(message); + } - /** - * @param color - */ - public void setColor(Color color) { - stream.setColor(color); - } + /** + * @param color + */ + public void setColor(Color color) { + stream.setColor(color); + } - // public void reportError(String title, String message) { - // if (hasMessages) { - // WikiEditorPlugin.getDefault().reportError(title, message); - // } - // } + // public void reportError(String title, String message) { + // if (hasMessages) { + // WikiEditorPlugin.getDefault().reportError(title, message); + // } + // } - // public void reportError() { - // reportError("Problems listed", "Open console view for problems log!"); - // } - /** - * Creates a string buffer from the given input stream - */ - public static String getStringFromStream(InputStream stream) throws IOException { - StringBuffer buffer = new StringBuffer(); - byte[] b = new byte[100]; - int finished = 0; - while (finished != -1) { - finished = stream.read(b); - if (finished != -1) { - String current = new String(b, 0, finished); - buffer.append(current); - } - } - return buffer.toString(); - } + // public void reportError() { + // reportError("Problems listed", "Open console view for problems log!"); + // } + /** + * Creates a string buffer from the given input stream + */ + public static String getStringFromStream(InputStream stream) + throws IOException { + StringBuffer buffer = new StringBuffer(); + byte[] b = new byte[100]; + int finished = 0; + while (finished != -1) { + finished = stream.read(b); + if (finished != -1) { + String current = new String(b, 0, finished); + buffer.append(current); + } + } + return buffer.toString(); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPPerspectiveFactory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPPerspectiveFactory.java index 6f59900..94f26a3 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPPerspectiveFactory.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPPerspectiveFactory.java @@ -11,6 +11,7 @@ import org.eclipse.ui.console.IConsoleConstants; public class PHPPerspectiveFactory implements IPerspectiveFactory { public static final String ID_PROGRESS_VIEW = "org.eclipse.ui.views.ProgressView"; //$NON-NLS-1$ + // see bug 63563 public PHPPerspectiveFactory() { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPeclipsePlugin.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPeclipsePlugin.java index e344236..2a2005c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPeclipsePlugin.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPeclipsePlugin.java @@ -117,1407 +117,1559 @@ import org.osgi.framework.BundleContext; /** * The main plugin class to be used in the desktop. */ -public class PHPeclipsePlugin extends AbstractUIPlugin implements IPreferenceConstants { - /** - * The id of the PHP plugin (value "net.sourceforge.phpeclipse"). - */ - public static final String PLUGIN_ID = "net.sourceforge.phpeclipse"; //$NON-NLS-1$ - public static final String EDITOR_ID = PHPeclipsePlugin.PLUGIN_ID+".PHPUnitEditor"; - public static final String ID_PERSPECTIVE = "net.sourceforge.phpeclipse.PHPPerspective"; //$NON-NLS-1$ - - IWorkspace w; - - /** - * id of builder - matches plugin.xml (concatenate pluginid.builderid) - */ - public static final String BUILDER_PARSER_ID = PLUGIN_ID + ".parserbuilder"; - - //public static final String BUILDER_INDEX_ID = PLUGIN_ID + ".indexbuilder"; - /** General debug flag */ - - public static final boolean DEBUG = false; - - /** - * The maximum number of allowed proposals by category - */ - public final static int MAX_PROPOSALS = 200; - - /** - * The key to store customized templates. - * - * @since 3.0 - */ - private static final String TEMPLATES_KEY = "net.sourceforge.phpdt.ui.text.custom_templates"; //$NON-NLS-1$ - - /** - * The key to store customized code templates. - * - * @since 3.0 - */ - private static final String CODE_TEMPLATES_KEY = "net.sourceforge.phpdt.ui.text.custom_code_templates"; //$NON-NLS-1$ - - /** - * The key to store whether the legacy templates have been migrated - * - * @since 3.0 - */ - // private static final String TEMPLATES_MIGRATION_KEY= "net.sourceforge.phpdt.ui.text.templates_migrated"; //$NON-NLS-1$ - /** - * The key to store whether the legacy code templates have been migrated - * - * @since 3.0 - */ - // private static final String CODE_TEMPLATES_MIGRATION_KEY= "net.sourceforge.phpdt.ui.text.code_templates_migrated"; - // //$NON-NLS-1$ -// private static ExternalToolsPlugin externalTools; - - /** - * The Java virtual machine that we are running on. - */ - // private static int jvm; - // /** MRJ 2.0 */ - // private static final int MRJ_2_0 = 0; - // - // /** MRJ 2.1 or later */ - // private static final int MRJ_2_1 = 1; - // - // /** Java on Mac OS X 10.0 (MRJ 3.0) */ - // private static final int MRJ_3_0 = 3; - // - // /** MRJ 3.1 */ - // private static final int MRJ_3_1 = 4; - // - // /** JVM constant for any other platform */ - // private static final int OTHER = -1; - // public static final String PHP_RESOURCES_VIEW_ID = PLUGIN_ID + - // ".resourcesview.ViewPHPResources"; //$NON-NLS-1$ - public static final String PHP_CODING_ACTION_SET_ID = PLUGIN_ID + ".ui.CodingActionSet"; //$NON-NLS-1$ - - public final static String PHP_NATURE_ID = PLUGIN_ID + ".phpnature"; - - public static final String PHPPARSER_ORIGINAL = "net.sourceforge.phpdt.internal.compiler.parser.Parser"; - - public static final String PHPPARSER_NEW = "test.PHPParser"; - - /** Change this if you want to switch PHP Parser. */ - public static final String PHPPARSER = PHPPARSER_ORIGINAL; - - //The shared instance. - private static PHPeclipsePlugin plugin; - - /** - * The template context type registry for the java editor. - * - * @since 3.0 - */ - private ContextTypeRegistry fContextTypeRegistry; - - /** - * The code template context type registry for the java editor. - * - * @since 3.0 - */ - private ContextTypeRegistry fCodeTemplateContextTypeRegistry; - - /** - * The template store for the java editor. - * - * @since 3.0 - */ - private TemplateStore fTemplateStore; - - /** - * The coded template store for the java editor. - * - * @since 3.0 - */ - private TemplateStore fCodeTemplateStore; - - /** Windows 9x */ - private static final int WINDOWS_9x = 6; - - /** Windows NT */ - private static final int WINDOWS_NT = 5; - - private ImageDescriptorRegistry fImageDescriptorRegistry; - - private HashMap fIndexManagerMap = new HashMap(); - - private IWorkingCopyManager fWorkingCopyManager; - - private IBufferFactory fBufferFactory; - - private ICompilationUnitDocumentProvider fCompilationUnitDocumentProvider; - - private JavaTextTools fJavaTextTools; - - private ProblemMarkerManager fProblemMarkerManager; - - private MembersOrderPreferenceCache fMembersOrderPreferenceCache; - - private IFile fLastEditorFile = null; - - private JavaEditorTextHoverDescriptor[] fJavaEditorTextHoverDescriptors; - - private JavaElementAdapterFactory fJavaElementAdapterFactory; - - // private MarkerAdapterFactory fMarkerAdapterFactory; - // private EditorInputAdapterFactory fEditorInputAdapterFactory; - private ResourceAdapterFactory fResourceAdapterFactory; - - // private LogicalPackageAdapterFactory fLogicalPackageAdapterFactory; - private IPropertyChangeListener fFontPropertyChangeListener; - - /** - * Property change listener on this plugin's preference store. - * - * @since 3.0 - */ - // private IPropertyChangeListener fPropertyChangeListener; - /** - * The combined preference store. - * - * @since 3.0 - */ - private IPreferenceStore fCombinedPreferenceStore; - - /** - * The extension point registry for the net.sourceforge.phpdt.ui.javaFoldingStructureProvider extension point. - * - * @since 3.0 - */ - private JavaFoldingStructureProviderRegistry fFoldingStructureProviderRegistry; - - /** - * Mockup preference store for firing events and registering listeners on project setting changes. FIXME: Temporary solution. - * - * @since 3.0 - */ - private MockupPreferenceStore fMockupPreferenceStore; - - /** - * The constructor. - */ - public PHPeclipsePlugin() { - super(); - plugin = this; -// externalTools = new ExternalToolsPlugin(); - - // try { - // resourceBundle = - // ResourceBundle.getBundle("net.sourceforge.PHPeclipsePluginResources"); - // } catch (MissingResourceException x) { - // resourceBundle = null; - // } - } - - // /** - // * Returns all Java editor text hovers contributed to the workbench. - // * - // * @return an array of JavaEditorTextHoverDescriptor - // * @since 2.1 - // */ - // public JavaEditorTextHoverDescriptor[] getJavaEditorTextHoverDescriptors() - // { - // if (fJavaEditorTextHoverDescriptors == null) - // fJavaEditorTextHoverDescriptors = JavaEditorTextHoverDescriptor - // .getContributedHovers(); - // return fJavaEditorTextHoverDescriptors; - // } - /** - * Returns all Java editor text hovers contributed to the workbench. - * - * @return an array of JavaEditorTextHoverDescriptor - * @since 2.1 - */ - public JavaEditorTextHoverDescriptor[] getJavaEditorTextHoverDescriptors() { - if (fJavaEditorTextHoverDescriptors == null) { - fJavaEditorTextHoverDescriptors = JavaEditorTextHoverDescriptor.getContributedHovers(); - ConfigurationElementSorter sorter = new ConfigurationElementSorter() { - /* - * @see org.eclipse.ui.texteditor.ConfigurationElementSorter#getConfigurationElement(java.lang.Object) - */ - public IConfigurationElement getConfigurationElement(Object object) { - return ((JavaEditorTextHoverDescriptor) object).getConfigurationElement(); +public class PHPeclipsePlugin extends AbstractUIPlugin implements + IPreferenceConstants { + /** + * The id of the PHP plugin (value "net.sourceforge.phpeclipse"). + */ + public static final String PLUGIN_ID = "net.sourceforge.phpeclipse"; //$NON-NLS-1$ + + public static final String EDITOR_ID = PHPeclipsePlugin.PLUGIN_ID + + ".PHPUnitEditor"; + + public static final String ID_PERSPECTIVE = "net.sourceforge.phpeclipse.PHPPerspective"; //$NON-NLS-1$ + + IWorkspace w; + + /** + * id of builder - matches plugin.xml (concatenate pluginid.builderid) + */ + public static final String BUILDER_PARSER_ID = PLUGIN_ID + ".parserbuilder"; + + // public static final String BUILDER_INDEX_ID = PLUGIN_ID + + // ".indexbuilder"; + /** General debug flag */ + + public static final boolean DEBUG = false; + + /** + * The maximum number of allowed proposals by category + */ + public final static int MAX_PROPOSALS = 200; + + /** + * The key to store customized templates. + * + * @since 3.0 + */ + private static final String TEMPLATES_KEY = "net.sourceforge.phpdt.ui.text.custom_templates"; //$NON-NLS-1$ + + /** + * The key to store customized code templates. + * + * @since 3.0 + */ + private static final String CODE_TEMPLATES_KEY = "net.sourceforge.phpdt.ui.text.custom_code_templates"; //$NON-NLS-1$ + + /** + * The key to store whether the legacy templates have been migrated + * + * @since 3.0 + */ + // private static final String TEMPLATES_MIGRATION_KEY= + // "net.sourceforge.phpdt.ui.text.templates_migrated"; //$NON-NLS-1$ + /** + * The key to store whether the legacy code templates have been migrated + * + * @since 3.0 + */ + // private static final String CODE_TEMPLATES_MIGRATION_KEY= + // "net.sourceforge.phpdt.ui.text.code_templates_migrated"; + // //$NON-NLS-1$ + // private static ExternalToolsPlugin externalTools; + /** + * The Java virtual machine that we are running on. + */ + // private static int jvm; + // /** MRJ 2.0 */ + // private static final int MRJ_2_0 = 0; + // + // /** MRJ 2.1 or later */ + // private static final int MRJ_2_1 = 1; + // + // /** Java on Mac OS X 10.0 (MRJ 3.0) */ + // private static final int MRJ_3_0 = 3; + // + // /** MRJ 3.1 */ + // private static final int MRJ_3_1 = 4; + // + // /** JVM constant for any other platform */ + // private static final int OTHER = -1; + // public static final String PHP_RESOURCES_VIEW_ID = PLUGIN_ID + + // ".resourcesview.ViewPHPResources"; //$NON-NLS-1$ + public static final String PHP_CODING_ACTION_SET_ID = PLUGIN_ID + + ".ui.CodingActionSet"; //$NON-NLS-1$ + + public final static String PHP_NATURE_ID = PLUGIN_ID + ".phpnature"; + + public static final String PHPPARSER_ORIGINAL = "net.sourceforge.phpdt.internal.compiler.parser.Parser"; + + public static final String PHPPARSER_NEW = "test.PHPParser"; + + /** Change this if you want to switch PHP Parser. */ + public static final String PHPPARSER = PHPPARSER_ORIGINAL; + + // The shared instance. + private static PHPeclipsePlugin plugin; + + /** + * The template context type registry for the java editor. + * + * @since 3.0 + */ + private ContextTypeRegistry fContextTypeRegistry; + + /** + * The code template context type registry for the java editor. + * + * @since 3.0 + */ + private ContextTypeRegistry fCodeTemplateContextTypeRegistry; + + /** + * The template store for the java editor. + * + * @since 3.0 + */ + private TemplateStore fTemplateStore; + + /** + * The coded template store for the java editor. + * + * @since 3.0 + */ + private TemplateStore fCodeTemplateStore; + + /** Windows 9x */ + private static final int WINDOWS_9x = 6; + + /** Windows NT */ + private static final int WINDOWS_NT = 5; + + private ImageDescriptorRegistry fImageDescriptorRegistry; + + private HashMap fIndexManagerMap = new HashMap(); + + private IWorkingCopyManager fWorkingCopyManager; + + private IBufferFactory fBufferFactory; + + private ICompilationUnitDocumentProvider fCompilationUnitDocumentProvider; + + private JavaTextTools fJavaTextTools; + + private ProblemMarkerManager fProblemMarkerManager; + + private MembersOrderPreferenceCache fMembersOrderPreferenceCache; + + private IFile fLastEditorFile = null; + + private JavaEditorTextHoverDescriptor[] fJavaEditorTextHoverDescriptors; + + private JavaElementAdapterFactory fJavaElementAdapterFactory; + + // private MarkerAdapterFactory fMarkerAdapterFactory; + // private EditorInputAdapterFactory fEditorInputAdapterFactory; + private ResourceAdapterFactory fResourceAdapterFactory; + + // private LogicalPackageAdapterFactory fLogicalPackageAdapterFactory; + private IPropertyChangeListener fFontPropertyChangeListener; + + /** + * Property change listener on this plugin's preference store. + * + * @since 3.0 + */ + // private IPropertyChangeListener fPropertyChangeListener; + /** + * The combined preference store. + * + * @since 3.0 + */ + private IPreferenceStore fCombinedPreferenceStore; + + /** + * The extension point registry for the + * net.sourceforge.phpdt.ui.javaFoldingStructureProvider + * extension point. + * + * @since 3.0 + */ + private JavaFoldingStructureProviderRegistry fFoldingStructureProviderRegistry; + + /** + * Mockup preference store for firing events and registering listeners on + * project setting changes. FIXME: Temporary solution. + * + * @since 3.0 + */ + private MockupPreferenceStore fMockupPreferenceStore; + + /** + * The constructor. + */ + public PHPeclipsePlugin() { + super(); + plugin = this; + // externalTools = new ExternalToolsPlugin(); + + // try { + // resourceBundle = + // ResourceBundle.getBundle("net.sourceforge.PHPeclipsePluginResources"); + // } catch (MissingResourceException x) { + // resourceBundle = null; + // } + } + + // /** + // * Returns all Java editor text hovers contributed to the workbench. + // * + // * @return an array of JavaEditorTextHoverDescriptor + // * @since 2.1 + // */ + // public JavaEditorTextHoverDescriptor[] + // getJavaEditorTextHoverDescriptors() + // { + // if (fJavaEditorTextHoverDescriptors == null) + // fJavaEditorTextHoverDescriptors = JavaEditorTextHoverDescriptor + // .getContributedHovers(); + // return fJavaEditorTextHoverDescriptors; + // } + /** + * Returns all Java editor text hovers contributed to the workbench. + * + * @return an array of JavaEditorTextHoverDescriptor + * @since 2.1 + */ + public JavaEditorTextHoverDescriptor[] getJavaEditorTextHoverDescriptors() { + if (fJavaEditorTextHoverDescriptors == null) { + fJavaEditorTextHoverDescriptors = JavaEditorTextHoverDescriptor + .getContributedHovers(); + ConfigurationElementSorter sorter = new ConfigurationElementSorter() { + /* + * @see org.eclipse.ui.texteditor.ConfigurationElementSorter#getConfigurationElement(java.lang.Object) + */ + public IConfigurationElement getConfigurationElement( + Object object) { + return ((JavaEditorTextHoverDescriptor) object) + .getConfigurationElement(); + } + }; + sorter.sort(fJavaEditorTextHoverDescriptors); + + // The Problem hover has to be the first and the Annotation hover + // has to + // be the last one in the JDT UI's hover list + int length = fJavaEditorTextHoverDescriptors.length; + int first = -1; + int last = length - 1; + int problemHoverIndex = -1; + int annotationHoverIndex = -1; + for (int i = 0; i < length; i++) { + if (!fJavaEditorTextHoverDescriptors[i].getId().startsWith( + PLUGIN_ID)) { + if (problemHoverIndex == -1 || annotationHoverIndex == -1) + continue; + else { + last = i - 1; + break; + } + } + if (first == -1) + first = i; + + if (fJavaEditorTextHoverDescriptors[i].getId().equals( + "net.sourceforge.phpdt.ui.AnnotationHover")) { //$NON-NLS-1$ + annotationHoverIndex = i; + continue; + } + if (fJavaEditorTextHoverDescriptors[i].getId().equals( + "net.sourceforge.phpdt.ui.ProblemHover")) { //$NON-NLS-1$ + problemHoverIndex = i; + continue; + } + } + + JavaEditorTextHoverDescriptor hoverDescriptor = null; + + if (first > -1 && problemHoverIndex > -1 + && problemHoverIndex != first) { + // move problem hover to beginning + hoverDescriptor = fJavaEditorTextHoverDescriptors[first]; + fJavaEditorTextHoverDescriptors[first] = fJavaEditorTextHoverDescriptors[problemHoverIndex]; + fJavaEditorTextHoverDescriptors[problemHoverIndex] = hoverDescriptor; + + // update annotation hover index if needed + if (annotationHoverIndex == first) + annotationHoverIndex = problemHoverIndex; + } + + if (annotationHoverIndex > -1 && annotationHoverIndex != last) { + // move annotation hover to end + hoverDescriptor = fJavaEditorTextHoverDescriptors[last]; + fJavaEditorTextHoverDescriptors[last] = fJavaEditorTextHoverDescriptors[annotationHoverIndex]; + fJavaEditorTextHoverDescriptors[annotationHoverIndex] = hoverDescriptor; + } + + // Move Best Match hover to front + for (int i = 0; i < fJavaEditorTextHoverDescriptors.length - 1; i++) { + if (PreferenceConstants.ID_BESTMATCH_HOVER + .equals(fJavaEditorTextHoverDescriptors[i].getId())) { + hoverDescriptor = fJavaEditorTextHoverDescriptors[i]; + for (int j = i; j > 0; j--) + fJavaEditorTextHoverDescriptors[j] = fJavaEditorTextHoverDescriptors[j - 1]; + fJavaEditorTextHoverDescriptors[0] = hoverDescriptor; + break; + } + + } } - }; - sorter.sort(fJavaEditorTextHoverDescriptors); - - // The Problem hover has to be the first and the Annotation hover has to - // be the last one in the JDT UI's hover list - int length = fJavaEditorTextHoverDescriptors.length; - int first = -1; - int last = length - 1; - int problemHoverIndex = -1; - int annotationHoverIndex = -1; - for (int i = 0; i < length; i++) { - if (!fJavaEditorTextHoverDescriptors[i].getId().startsWith(PLUGIN_ID)) { - if (problemHoverIndex == -1 || annotationHoverIndex == -1) - continue; - else { - last = i - 1; - break; - } + + return fJavaEditorTextHoverDescriptors; + } + + /** + * Resets the Java editor text hovers contributed to the workbench. + *

                                                      + * This will force a rebuild of the descriptors the next time a client asks + * for them. + *

                                                      + * + * @return an array of JavaEditorTextHoverDescriptor + * @since 2.1 + */ + public void resetJavaEditorTextHoverDescriptors() { + fJavaEditorTextHoverDescriptors = null; + } + + /** + * Creates the PHP plugin standard groups in a context menu. + */ + public static void createStandardGroups(IMenuManager menu) { + if (!menu.isEmpty()) + return; + menu.add(new Separator(IContextMenuConstants.GROUP_NEW)); + menu.add(new GroupMarker(IContextMenuConstants.GROUP_GOTO)); + menu.add(new Separator(IContextMenuConstants.GROUP_OPEN)); + menu.add(new GroupMarker(IContextMenuConstants.GROUP_SHOW)); + menu.add(new Separator(IContextMenuConstants.GROUP_REORGANIZE)); + menu.add(new Separator(IContextMenuConstants.GROUP_GENERATE)); + menu.add(new Separator(IContextMenuConstants.GROUP_SEARCH)); + menu.add(new Separator(IContextMenuConstants.GROUP_BUILD)); + menu.add(new Separator(IContextMenuConstants.GROUP_ADDITIONS)); + menu.add(new Separator(IContextMenuConstants.GROUP_VIEWER_SETUP)); + menu.add(new Separator(IContextMenuConstants.GROUP_PROPERTIES)); + } + + public static IWorkbenchPage getActivePage() { + return getDefault().internalGetActivePage(); + } + + public static Shell getActiveWorkbenchShell() { + return getActiveWorkbenchWindow().getShell(); + } + + /** + * Returns an array of all editors that have an unsaved content. If the + * identical content is presented in more than one editor, only one of those + * editor parts is part of the result. + * + * @return an array of all dirty editor parts. + */ + public static IEditorPart[] getDirtyEditors() { + Set inputs = new HashSet(); + List result = new ArrayList(0); + IWorkbench workbench = getDefault().getWorkbench(); + IWorkbenchWindow[] windows = workbench.getWorkbenchWindows(); + for (int i = 0; i < windows.length; i++) { + IWorkbenchPage[] pages = windows[i].getPages(); + for (int x = 0; x < pages.length; x++) { + IEditorPart[] editors = pages[x].getDirtyEditors(); + for (int z = 0; z < editors.length; z++) { + IEditorPart ep = editors[z]; + IEditorInput input = ep.getEditorInput(); + if (!inputs.contains(input)) { + inputs.add(input); + result.add(ep); + } + } + } } - if (first == -1) - first = i; + return (IEditorPart[]) result.toArray(new IEditorPart[result.size()]); + } + + public static IWorkbenchWindow getActiveWorkbenchWindow() { + return getDefault().getWorkbench().getActiveWorkbenchWindow(); + } + + /** + * Returns the shared instance. + */ + public static PHPeclipsePlugin getDefault() { + return plugin; + } + + public static ImageDescriptorRegistry getImageDescriptorRegistry() { + return getDefault().internalGetImageDescriptorRegistry(); + } + + static IPath getInstallLocation() { + return new Path(getDefault().getBundle().getEntry("/").getFile()); + } + + // public static int getJVM() { + // return jvm; + // } + + public static String getPluginId() { + return getDefault().getBundle().getSymbolicName(); + } - if (fJavaEditorTextHoverDescriptors[i].getId().equals("net.sourceforge.phpdt.ui.AnnotationHover")) { //$NON-NLS-1$ - annotationHoverIndex = i; - continue; + /** + * Returns the standard display to be used. The method first checks, if the + * thread calling this method has an associated display. If so, this display + * is returned. Otherwise the method returns the default display. + */ + public static Display getStandardDisplay() { + Display display = Display.getCurrent(); + if (display == null) { + display = Display.getDefault(); } - if (fJavaEditorTextHoverDescriptors[i].getId().equals("net.sourceforge.phpdt.ui.ProblemHover")) { //$NON-NLS-1$ - problemHoverIndex = i; - continue; + return display; + } + + // public static ExternalToolsPlugin getExternalTools() { + // return externalTools; + // } + /** + * Returns the workspace instance. + */ + public static IWorkspace getWorkspace() { + return ResourcesPlugin.getWorkspace(); + } + + public static boolean isDebug() { + return getDefault().isDebugging(); + } + + // public static void logErrorMessage(String message) { + // log(new Status(IStatus.ERROR, getPluginId(), + // JavaStatusConstants.INTERNAL_ERROR, message, null)); + // } + // + // public static void logErrorStatus(String message, IStatus status) { + // if (status == null) { + // logErrorMessage(message); + // return; + // } + // MultiStatus multi= new MultiStatus(getPluginId(), + // JavaStatusConstants.INTERNAL_ERROR, message, null); + // multi.add(status); + // log(multi); + // } + // + // public static void log(Throwable e) { + // log(new Status(IStatus.ERROR, getPluginId(), + // JavaStatusConstants.INTERNAL_ERROR, + // JavaUIMessages.getString("JavaPlugin.internal_error"), e)); //$NON-NLS-1$ + // } + public static void log(int severity, String message) { + Status status = new Status(severity, PLUGIN_ID, IStatus.OK, message, + null); + log(status); + } + + public static void log(IStatus status) { + getDefault().getLog().log(status); + } + + public static void log(Throwable t) { + log(error(t)); + } + + public static void log(String message, Throwable t) { + log(error(message, t)); + } + + public static void logErrorMessage(String message) { + log(new Status(IStatus.ERROR, getPluginId(), + IJavaStatusConstants.INTERNAL_ERROR, message, null)); + } + + public static IStatus error(Throwable t) { + return error("PHPeclipsePlugin.internalErrorOccurred", t); //$NON-NLS-1$ + } + + public static IStatus error(String message, Throwable t) { + return new Status(IStatus.ERROR, PLUGIN_ID, IStatus.ERROR, message, t); + } + + // private static void setJVM() { + // String osName = System.getProperty("os.name"); + // if (osName.startsWith("Mac OS")) { + // String mrjVersion = System.getProperty("mrj.version"); + // String majorMRJVersion = mrjVersion.substring(0, 3); + // jvm = OTHER; + // try { + // double version = Double.valueOf(majorMRJVersion).doubleValue(); + // if (version == 2) { + // jvm = MRJ_2_0; + // } else if (version >= 2.1 && version < 3) { + // jvm = MRJ_2_1; + // } else if (version == 3.0) { + // jvm = MRJ_3_0; + // } else if (version >= 3.1) { + // jvm = MRJ_3_1; + // } + // } catch (NumberFormatException nfe) { + // } + // } else if (osName.startsWith("Windows")) { + // if (osName.indexOf("9") != -1) { + // jvm = WINDOWS_9x; + // } else { + // jvm = WINDOWS_NT; + // } + // } + // } + + // TODO: refactor this into a better method name ! + public synchronized ICompilationUnitDocumentProvider getCompilationUnitDocumentProvider() { + if (fCompilationUnitDocumentProvider == null) + fCompilationUnitDocumentProvider = new PHPDocumentProvider(); + return fCompilationUnitDocumentProvider; + } + + /** + * Get the identifier index manager for the given project + * + * @param iProject + * the current project + * @return + */ + public IdentifierIndexManager getIndexManager(IProject iProject) { + IPath path = iProject.getWorkingLocation(PHPeclipsePlugin.PLUGIN_ID); + path = path.append("project.index"); + String indexFilename = path.toString(); + // try { + // IdentDB db = IdentDB.getInstance(); + // } catch (ClassNotFoundException e) { + // e.printStackTrace(); + // } catch (SQLException e) { + // e.printStackTrace(); + // } + IdentifierIndexManager indexManager = (IdentifierIndexManager) fIndexManagerMap + .get(indexFilename); + if (indexManager == null) { + indexManager = new IdentifierIndexManager(indexFilename); + fIndexManagerMap.put(indexFilename, indexManager); } - } - - JavaEditorTextHoverDescriptor hoverDescriptor = null; - - if (first > -1 && problemHoverIndex > -1 && problemHoverIndex != first) { - // move problem hover to beginning - hoverDescriptor = fJavaEditorTextHoverDescriptors[first]; - fJavaEditorTextHoverDescriptors[first] = fJavaEditorTextHoverDescriptors[problemHoverIndex]; - fJavaEditorTextHoverDescriptors[problemHoverIndex] = hoverDescriptor; - - // update annotation hover index if needed - if (annotationHoverIndex == first) - annotationHoverIndex = problemHoverIndex; - } - - if (annotationHoverIndex > -1 && annotationHoverIndex != last) { - // move annotation hover to end - hoverDescriptor = fJavaEditorTextHoverDescriptors[last]; - fJavaEditorTextHoverDescriptors[last] = fJavaEditorTextHoverDescriptors[annotationHoverIndex]; - fJavaEditorTextHoverDescriptors[annotationHoverIndex] = hoverDescriptor; - } - - // Move Best Match hover to front - for (int i = 0; i < fJavaEditorTextHoverDescriptors.length - 1; i++) { - if (PreferenceConstants.ID_BESTMATCH_HOVER.equals(fJavaEditorTextHoverDescriptors[i].getId())) { - hoverDescriptor = fJavaEditorTextHoverDescriptors[i]; - for (int j = i; j > 0; j--) - fJavaEditorTextHoverDescriptors[j] = fJavaEditorTextHoverDescriptors[j - 1]; - fJavaEditorTextHoverDescriptors[0] = hoverDescriptor; - break; + return indexManager; + } + + public synchronized IWorkingCopyManager getWorkingCopyManager() { + if (fWorkingCopyManager == null) { + ICompilationUnitDocumentProvider provider = getCompilationUnitDocumentProvider(); + fWorkingCopyManager = new WorkingCopyManager(provider); } + return fWorkingCopyManager; + } - } + public synchronized MembersOrderPreferenceCache getMemberOrderPreferenceCache() { + if (fMembersOrderPreferenceCache == null) + fMembersOrderPreferenceCache = new MembersOrderPreferenceCache(); + return fMembersOrderPreferenceCache; } - return fJavaEditorTextHoverDescriptors; - } - - /** - * Resets the Java editor text hovers contributed to the workbench. - *

                                                      - * This will force a rebuild of the descriptors the next time a client asks for them. - *

                                                      - * - * @return an array of JavaEditorTextHoverDescriptor - * @since 2.1 - */ - public void resetJavaEditorTextHoverDescriptors() { - fJavaEditorTextHoverDescriptors = null; - } - - /** - * Creates the PHP plugin standard groups in a context menu. - */ - public static void createStandardGroups(IMenuManager menu) { - if (!menu.isEmpty()) - return; - menu.add(new Separator(IContextMenuConstants.GROUP_NEW)); - menu.add(new GroupMarker(IContextMenuConstants.GROUP_GOTO)); - menu.add(new Separator(IContextMenuConstants.GROUP_OPEN)); - menu.add(new GroupMarker(IContextMenuConstants.GROUP_SHOW)); - menu.add(new Separator(IContextMenuConstants.GROUP_REORGANIZE)); - menu.add(new Separator(IContextMenuConstants.GROUP_GENERATE)); - menu.add(new Separator(IContextMenuConstants.GROUP_SEARCH)); - menu.add(new Separator(IContextMenuConstants.GROUP_BUILD)); - menu.add(new Separator(IContextMenuConstants.GROUP_ADDITIONS)); - menu.add(new Separator(IContextMenuConstants.GROUP_VIEWER_SETUP)); - menu.add(new Separator(IContextMenuConstants.GROUP_PROPERTIES)); - } - - public static IWorkbenchPage getActivePage() { - return getDefault().internalGetActivePage(); - } - - public static Shell getActiveWorkbenchShell() { - return getActiveWorkbenchWindow().getShell(); - } - - /** - * Returns an array of all editors that have an unsaved content. If the identical content is presented in more than one editor, - * only one of those editor parts is part of the result. - * - * @return an array of all dirty editor parts. - */ - public static IEditorPart[] getDirtyEditors() { - Set inputs = new HashSet(); - List result = new ArrayList(0); - IWorkbench workbench = getDefault().getWorkbench(); - IWorkbenchWindow[] windows = workbench.getWorkbenchWindows(); - for (int i = 0; i < windows.length; i++) { - IWorkbenchPage[] pages = windows[i].getPages(); - for (int x = 0; x < pages.length; x++) { - IEditorPart[] editors = pages[x].getDirtyEditors(); - for (int z = 0; z < editors.length; z++) { - IEditorPart ep = editors[z]; - IEditorInput input = ep.getEditorInput(); - if (!inputs.contains(input)) { - inputs.add(input); - result.add(ep); - } - } - } + /** + * Returns the mockup preference store for firing events and registering + * listeners on project setting changes. Temporary solution. + */ + public MockupPreferenceStore getMockupPreferenceStore() { + if (fMockupPreferenceStore == null) + fMockupPreferenceStore = new MockupPreferenceStore(); + + return fMockupPreferenceStore; } - return (IEditorPart[]) result.toArray(new IEditorPart[result.size()]); - } - - public static IWorkbenchWindow getActiveWorkbenchWindow() { - return getDefault().getWorkbench().getActiveWorkbenchWindow(); - } - - /** - * Returns the shared instance. - */ - public static PHPeclipsePlugin getDefault() { - return plugin; - } - - public static ImageDescriptorRegistry getImageDescriptorRegistry() { - return getDefault().internalGetImageDescriptorRegistry(); - } - - static IPath getInstallLocation() { - return new Path(getDefault().getBundle().getEntry("/").getFile()); - } - - // public static int getJVM() { - // return jvm; - // } - - public static String getPluginId() { - return getDefault().getBundle().getSymbolicName() ; - } - - /** - * Returns the standard display to be used. The method first checks, if the thread calling this method has an associated display. - * If so, this display is returned. Otherwise the method returns the default display. - */ - public static Display getStandardDisplay() { - Display display = Display.getCurrent(); - if (display == null) { - display = Display.getDefault(); + + public synchronized ProblemMarkerManager getProblemMarkerManager() { + if (fProblemMarkerManager == null) + fProblemMarkerManager = new ProblemMarkerManager(); + return fProblemMarkerManager; } - return display; - } - - // public static ExternalToolsPlugin getExternalTools() { - // return externalTools; - // } - /** - * Returns the workspace instance. - */ - public static IWorkspace getWorkspace() { - return ResourcesPlugin.getWorkspace(); - } - - public static boolean isDebug() { - return getDefault().isDebugging(); - } - - // public static void logErrorMessage(String message) { - // log(new Status(IStatus.ERROR, getPluginId(), - // JavaStatusConstants.INTERNAL_ERROR, message, null)); - // } - // - // public static void logErrorStatus(String message, IStatus status) { - // if (status == null) { - // logErrorMessage(message); - // return; - // } - // MultiStatus multi= new MultiStatus(getPluginId(), - // JavaStatusConstants.INTERNAL_ERROR, message, null); - // multi.add(status); - // log(multi); - // } - // - // public static void log(Throwable e) { - // log(new Status(IStatus.ERROR, getPluginId(), - // JavaStatusConstants.INTERNAL_ERROR, - // JavaUIMessages.getString("JavaPlugin.internal_error"), e)); //$NON-NLS-1$ - // } - public static void log(int severity, String message) { - Status status = new Status(severity, PLUGIN_ID, IStatus.OK, message, null); - log(status); - } - - public static void log(IStatus status) { - getDefault().getLog().log(status); - } - - public static void log(Throwable t) { - log(error(t)); - } - - public static void log(String message, Throwable t) { - log(error(message, t)); - } - - public static void logErrorMessage(String message) { - log(new Status(IStatus.ERROR, getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, null)); - } - - public static IStatus error(Throwable t) { - return error("PHPeclipsePlugin.internalErrorOccurred", t); //$NON-NLS-1$ - } - - public static IStatus error(String message, Throwable t) { - return new Status(IStatus.ERROR, PLUGIN_ID, IStatus.ERROR, message, t); - } - - // private static void setJVM() { - // String osName = System.getProperty("os.name"); - // if (osName.startsWith("Mac OS")) { - // String mrjVersion = System.getProperty("mrj.version"); - // String majorMRJVersion = mrjVersion.substring(0, 3); - // jvm = OTHER; - // try { - // double version = Double.valueOf(majorMRJVersion).doubleValue(); - // if (version == 2) { - // jvm = MRJ_2_0; - // } else if (version >= 2.1 && version < 3) { - // jvm = MRJ_2_1; - // } else if (version == 3.0) { - // jvm = MRJ_3_0; - // } else if (version >= 3.1) { - // jvm = MRJ_3_1; - // } - // } catch (NumberFormatException nfe) { - // } - // } else if (osName.startsWith("Windows")) { - // if (osName.indexOf("9") != -1) { - // jvm = WINDOWS_9x; - // } else { - // jvm = WINDOWS_NT; - // } - // } - // } - - // TODO: refactor this into a better method name ! - public synchronized ICompilationUnitDocumentProvider getCompilationUnitDocumentProvider() { - if (fCompilationUnitDocumentProvider == null) - fCompilationUnitDocumentProvider = new PHPDocumentProvider(); - return fCompilationUnitDocumentProvider; - } - - /** - * Get the identifier index manager for the given project - * - * @param iProject - * the current project - * @return - */ - public IdentifierIndexManager getIndexManager(IProject iProject) { - IPath path = iProject.getWorkingLocation(PHPeclipsePlugin.PLUGIN_ID); - path = path.append("project.index"); - String indexFilename = path.toString(); -// try { -// IdentDB db = IdentDB.getInstance(); -// } catch (ClassNotFoundException e) { -// e.printStackTrace(); -// } catch (SQLException e) { -// e.printStackTrace(); -// } - IdentifierIndexManager indexManager = (IdentifierIndexManager) fIndexManagerMap.get(indexFilename); - if (indexManager == null) { - indexManager = new IdentifierIndexManager(indexFilename); - fIndexManagerMap.put(indexFilename, indexManager); + + // public synchronized JavaTextTools getJavaTextTools() { + // if (fJavaTextTools == null) + // fJavaTextTools = new JavaTextTools(getPreferenceStore()); + // return fJavaTextTools; + // } + public synchronized JavaTextTools getJavaTextTools() { + if (fJavaTextTools == null) + fJavaTextTools = new JavaTextTools(getPreferenceStore(), JavaCore + .getPlugin().getPluginPreferences()); + return fJavaTextTools; } - return indexManager; - } - public synchronized IWorkingCopyManager getWorkingCopyManager() { - if (fWorkingCopyManager == null) { - ICompilationUnitDocumentProvider provider = getCompilationUnitDocumentProvider(); - fWorkingCopyManager = new WorkingCopyManager(provider); + public IFile getLastEditorFile() { + return fLastEditorFile; } - return fWorkingCopyManager; - } - - public synchronized MembersOrderPreferenceCache getMemberOrderPreferenceCache() { - if (fMembersOrderPreferenceCache == null) - fMembersOrderPreferenceCache = new MembersOrderPreferenceCache(); - return fMembersOrderPreferenceCache; - } - - /** - * Returns the mockup preference store for firing events and registering listeners on project setting changes. Temporary solution. - */ - public MockupPreferenceStore getMockupPreferenceStore() { - if (fMockupPreferenceStore == null) - fMockupPreferenceStore = new MockupPreferenceStore(); - - return fMockupPreferenceStore; - } - - public synchronized ProblemMarkerManager getProblemMarkerManager() { - if (fProblemMarkerManager == null) - fProblemMarkerManager = new ProblemMarkerManager(); - return fProblemMarkerManager; - } - - // public synchronized JavaTextTools getJavaTextTools() { - // if (fJavaTextTools == null) - // fJavaTextTools = new JavaTextTools(getPreferenceStore()); - // return fJavaTextTools; - // } - public synchronized JavaTextTools getJavaTextTools() { - if (fJavaTextTools == null) - fJavaTextTools = new JavaTextTools(getPreferenceStore(), JavaCore.getPlugin().getPluginPreferences()); - return fJavaTextTools; - } - - public IFile getLastEditorFile() { - return fLastEditorFile; - } - - /** - * Returns the string from the plugin's resource bundle, or 'key' if not found. - */ - // public static String getResourceString(String key) { - // ResourceBundle bundle = PHPeclipsePlugin.getDefault().getResourceBundle(); - // try { - // return bundle.getString(key); - // } catch (MissingResourceException e) { - // return key; - // } - // } - /** - * Returns the plugin's resource bundle, - */ - // public ResourceBundle getResourceBundle() { - // return resourceBundle; - // } - protected void initializeDefaultPreferences(IPreferenceStore store) { - String operatingSystem = Platform.getOS(); - // maxosx, linux, solaris, win32,... - try { - InputStream is = getDefault().openStream( - new Path("prefs/default_" + operatingSystem + ".properties")); - PropertyResourceBundle resourceBundle = new PropertyResourceBundle(is); - Enumeration e = resourceBundle.getKeys(); - String key; - while (e.hasMoreElements()) { - key = (String)e.nextElement(); - store.setDefault(key, resourceBundle.getString( key )); - } - } catch (Exception e) { - // no default properties found - if (operatingSystem.equals(Platform.OS_WIN32)) { -// store.setDefault(PHP_RUN_PREF, "c:\\apache\\php\\php.exe"); -// store.setDefault(EXTERNAL_PARSER_PREF, "c:\\apache\\php\\php -l -f {0}"); -// store.setDefault(MYSQL_RUN_PREF, "c:\\apache\\mysql\\bin\\mysqld-nt.exe"); -// store.setDefault(APACHE_RUN_PREF, "c:\\apache\\apache.exe"); -// store.setDefault(XAMPP_START_PREF, "c:\\xampp\\xampp_start.exe"); -// store.setDefault(XAMPP_STOP_PREF, "c:\\xampp\\xampp_stop.exe"); -// store.setDefault( -// ETC_HOSTS_PATH_PREF, "c:\\windows\\system32\\drivers\\etc\\hosts"); - } else { -// store.setDefault(PHP_RUN_PREF, "/apache/php/php"); -// store.setDefault(EXTERNAL_PARSER_PREF, "/apache/php/php -l -f {0}"); -// store.setDefault(MYSQL_RUN_PREF, "/apache/mysql/bin/mysqld"); -// store.setDefault(APACHE_RUN_PREF, "/apache/apache"); -// store.setDefault(XAMPP_START_PREF, "xamp/xampp_start"); -// store.setDefault(XAMPP_STOP_PREF, "xampp/xampp_stop"); - } -// store.setDefault(MYSQL_PREF, "--standalone"); -// store.setDefault(APACHE_START_PREF, "-c \"DocumentRoot \"{0}\"\""); -// store.setDefault(APACHE_STOP_PREF, "-k shutdown"); -// store.setDefault(APACHE_RESTART_PREF, "-k restart"); -// store.setDefault(MYSQL_START_BACKGROUND, "true"); -// store.setDefault(APACHE_START_BACKGROUND, "true"); -// store.setDefault(APACHE_STOP_BACKGROUND, "true"); -// store.setDefault(APACHE_RESTART_BACKGROUND, "true"); + + /** + * Returns the string from the plugin's resource bundle, or 'key' if not + * found. + */ + // public static String getResourceString(String key) { + // ResourceBundle bundle = + // PHPeclipsePlugin.getDefault().getResourceBundle(); + // try { + // return bundle.getString(key); + // } catch (MissingResourceException e) { + // return key; + // } + // } + /** + * Returns the plugin's resource bundle, + */ + // public ResourceBundle getResourceBundle() { + // return resourceBundle; + // } + protected void initializeDefaultPreferences(IPreferenceStore store) { + String operatingSystem = Platform.getOS(); + // maxosx, linux, solaris, win32,... + try { + InputStream is = getDefault() + .openStream( + new Path("prefs/default_" + operatingSystem + + ".properties")); + PropertyResourceBundle resourceBundle = new PropertyResourceBundle( + is); + Enumeration e = resourceBundle.getKeys(); + String key; + while (e.hasMoreElements()) { + key = (String) e.nextElement(); + store.setDefault(key, resourceBundle.getString(key)); + } + } catch (Exception e) { + // no default properties found + if (operatingSystem.equals(Platform.OS_WIN32)) { + // store.setDefault(PHP_RUN_PREF, "c:\\apache\\php\\php.exe"); + // store.setDefault(EXTERNAL_PARSER_PREF, "c:\\apache\\php\\php + // -l -f {0}"); + // store.setDefault(MYSQL_RUN_PREF, + // "c:\\apache\\mysql\\bin\\mysqld-nt.exe"); + // store.setDefault(APACHE_RUN_PREF, "c:\\apache\\apache.exe"); + // store.setDefault(XAMPP_START_PREF, + // "c:\\xampp\\xampp_start.exe"); + // store.setDefault(XAMPP_STOP_PREF, + // "c:\\xampp\\xampp_stop.exe"); + // store.setDefault( + // ETC_HOSTS_PATH_PREF, + // "c:\\windows\\system32\\drivers\\etc\\hosts"); + } else { + // store.setDefault(PHP_RUN_PREF, "/apache/php/php"); + // store.setDefault(EXTERNAL_PARSER_PREF, "/apache/php/php -l -f + // {0}"); + // store.setDefault(MYSQL_RUN_PREF, "/apache/mysql/bin/mysqld"); + // store.setDefault(APACHE_RUN_PREF, "/apache/apache"); + // store.setDefault(XAMPP_START_PREF, "xamp/xampp_start"); + // store.setDefault(XAMPP_STOP_PREF, "xampp/xampp_stop"); + } + // store.setDefault(MYSQL_PREF, "--standalone"); + // store.setDefault(APACHE_START_PREF, "-c \"DocumentRoot + // \"{0}\"\""); + // store.setDefault(APACHE_STOP_PREF, "-k shutdown"); + // store.setDefault(APACHE_RESTART_PREF, "-k restart"); + // store.setDefault(MYSQL_START_BACKGROUND, "true"); + // store.setDefault(APACHE_START_BACKGROUND, "true"); + // store.setDefault(APACHE_STOP_BACKGROUND, "true"); + // store.setDefault(APACHE_RESTART_BACKGROUND, "true"); + } + + // store.setDefault(SHOW_OUTPUT_IN_CONSOLE, "true"); + // store.setDefault(PHP_OBFUSCATOR_DEFAULT, "c:\\temp"); + // if (operatingSystem.equals(Platform.OS_WIN32)) { + // store.setDefault(EXTERNAL_BROWSER_PREF, "rundll32 + // url.dll,FileProtocolHandler {0}"); + // } else if (operatingSystem.equals(Platform.OS_MACOSX)) { + // store.setDefault(PHP_OBFUSCATOR_DEFAULT, "/tmp"); + // TODO How do we start Safari on Mac OS X ? + // store.setDefault(EXTERNAL_BROWSER_PREF, "netscape {0}"); + // } else { + // store.setDefault(PHP_OBFUSCATOR_DEFAULT, "/tmp"); + // store.setDefault(EXTERNAL_BROWSER_PREF, "netscape {0}"); + // } + + // store.setDefault(PHP_EXTENSION_PREFS, + // "php,php3,php4,php5,phtml,inc,module,class"); + + // store.setDefault(PHP_PARSER_DEFAULT, PHP_EXTERNAL_PARSER); + // store.setDefault(PHP_INTERNAL_PARSER, "false"); + // store.setDefault(PHP_EXTERNAL_PARSER, "true"); + // store.setDefault(PHP_PARSE_ON_SAVE, "true"); + // show line numbers: + // store.setDefault(LINE_NUMBER_RULER, "false"); + // store.setDefault(FORMATTER_TAB_SIZE, "4"); + // php syntax highlighting + store.setDefault(PHP_USERDEF_XMLFILE, ""); + // assume there is none chooA + // PreferenceConverter.setDefault(store, PHP_MULTILINE_COMMENT, + // PHPColorProvider.MULTI_LINE_COMMENT); + // PreferenceConverter.setDefault(store, PHP_SINGLELINE_COMMENT, + // PHPColorProvider.SINGLE_LINE_COMMENT); + PreferenceConverter.setDefault(store, PHP_TAG, PHPColorProvider.TAG); + PreferenceConverter.setDefault(store, PHP_KEYWORD, + PHPColorProvider.KEYWORD); + PreferenceConverter.setDefault(store, PHP_VARIABLE, + PHPColorProvider.VARIABLE); + PreferenceConverter.setDefault(store, PHP_VARIABLE_DOLLAR, + PHPColorProvider.VARIABLE); + PreferenceConverter.setDefault(store, PHP_FUNCTIONNAME, + PHPColorProvider.FUNCTION_NAME); + PreferenceConverter.setDefault(store, PHP_CONSTANT, + PHPColorProvider.CONSTANT); + PreferenceConverter.setDefault(store, PHP_TYPE, PHPColorProvider.TYPE); + // PreferenceConverter.setDefault(store, PHP_STRING_DQ, + // PHPColorProvider.STRING_DQ); + // store.setDefault(PHP_STRING_BOLD_DQ, true); + // PreferenceConverter.setDefault(store, PHP_STRING_SQ, + // PHPColorProvider.STRING_SQ); + PreferenceConverter.setDefault(store, PHP_DEFAULT, + PHPColorProvider.DEFAULT); + PreferenceConverter.setDefault(store, PHPDOC_KEYWORD, + PHPColorProvider.PHPDOC_KEYWORD); + PreferenceConverter.setDefault(store, PHPDOC_TAG, + PHPColorProvider.PHPDOC_TAG); + PreferenceConverter.setDefault(store, PHPDOC_LINK, + PHPColorProvider.PHPDOC_LINK); + PreferenceConverter.setDefault(store, PHPDOC_DEFAULT, + PHPColorProvider.PHPDOC_DEFAULT); + + PreferenceConverter.setDefault(store, EDITOR_PHP_KEYWORD_RETURN_COLOR, + new RGB(127, 0, 85)); + store.setDefault(EDITOR_PHP_KEYWORD_RETURN_BOLD, true); + store.setDefault(EDITOR_PHP_KEYWORD_RETURN_ITALIC, false); + + PreferenceConverter.setDefault(store, EDITOR_PHP_OPERATOR_COLOR, + new RGB(0, 0, 0)); + store.setDefault(EDITOR_PHP_OPERATOR_BOLD, false); + store.setDefault(EDITOR_PHP_OPERATOR_ITALIC, false); + + PreferenceConverter.setDefault(store, EDITOR_PHP_BRACE_OPERATOR_COLOR, + new RGB(0, 0, 0)); + store.setDefault(EDITOR_PHP_BRACE_OPERATOR_BOLD, false); + store.setDefault(EDITOR_PHP_BRACE_OPERATOR_ITALIC, false); + // PreferenceConverter.setDefault( + // store, + // PHP_EDITOR_BACKGROUND, + // PHPColorProvider.BACKGROUND); + // PreferenceConverter.setDefault( + // store, + // LINKED_POSITION_COLOR, + // PHPColorProvider.LINKED_POSITION_COLOR); + // PreferenceConverter.setDefault( + // store, + // LINE_NUMBER_COLOR, + // PHPColorProvider.LINE_NUMBER_COLOR); + // // set default PHPDoc colors: + // PreferenceConverter.setDefault( + // store, + // PHPDOC_KEYWORD, + // PHPColorProvider.PHPDOC_KEYWORD); + // PreferenceConverter.setDefault( + // store, + // PHPDOC_LINK, + // PHPColorProvider.PHPDOC_LINK); + // PreferenceConverter.setDefault( + // store, + // PHPDOC_DEFAULT, + // PHPColorProvider.PHPDOC_DEFAULT); + // PreferenceConverter.setDefault( + // store, + // PHPDOC_TAG, + // PHPColorProvider.PHPDOC_TAG); + // store.setDefault(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT, "true"); + // PreferenceConverter.setDefault( + // store, + // PREFERENCE_COLOR_BACKGROUND, + // PHPColorProvider.BACKGROUND_COLOR); + // language stuff + // store.setDefault(RESOURCE_BUNDLE, LANGUAGE_DEFAULT); + // store.setDefault(RESOURCE_BUNDLE_EN_GB, "true"); + // store.setDefault(RESOURCE_BUNDLE_DE, "false"); + // store.setDefault(RESOURCE_BUNDLE_FR, "false"); + // store.setDefault(RESOURCE_BUNDLE_ES, "false"); + // TemplatePreferencePage.initDefaults(store); + // this will initialize the static fields in the syntaxrdr class + new PHPSyntaxRdr(); + JavaCore.initializeDefaultPluginPreferences(); + PreferenceConstants.initializeDefaultValues(store); + // externalTools.initializeDefaultPreferences(store); + MarkerAnnotationPreferences.initializeDefaultValues(store); } -// store.setDefault(SHOW_OUTPUT_IN_CONSOLE, "true"); -// store.setDefault(PHP_OBFUSCATOR_DEFAULT, "c:\\temp"); -// if (operatingSystem.equals(Platform.OS_WIN32)) { - // store.setDefault(EXTERNAL_BROWSER_PREF, "rundll32 url.dll,FileProtocolHandler {0}"); -// } else if (operatingSystem.equals(Platform.OS_MACOSX)) { -// store.setDefault(PHP_OBFUSCATOR_DEFAULT, "/tmp"); - // TODO How do we start Safari on Mac OS X ? - // store.setDefault(EXTERNAL_BROWSER_PREF, "netscape {0}"); -// } else { -// store.setDefault(PHP_OBFUSCATOR_DEFAULT, "/tmp"); - // store.setDefault(EXTERNAL_BROWSER_PREF, "netscape {0}"); -// } - -// store.setDefault(PHP_EXTENSION_PREFS, "php,php3,php4,php5,phtml,inc,module,class"); - - // store.setDefault(PHP_PARSER_DEFAULT, PHP_EXTERNAL_PARSER); - // store.setDefault(PHP_INTERNAL_PARSER, "false"); - // store.setDefault(PHP_EXTERNAL_PARSER, "true"); - // store.setDefault(PHP_PARSE_ON_SAVE, "true"); - // show line numbers: - // store.setDefault(LINE_NUMBER_RULER, "false"); - // store.setDefault(FORMATTER_TAB_SIZE, "4"); - // php syntax highlighting - store.setDefault(PHP_USERDEF_XMLFILE, ""); - //assume there is none chooA -// PreferenceConverter.setDefault(store, PHP_MULTILINE_COMMENT, PHPColorProvider.MULTI_LINE_COMMENT); -// PreferenceConverter.setDefault(store, PHP_SINGLELINE_COMMENT, PHPColorProvider.SINGLE_LINE_COMMENT); - PreferenceConverter.setDefault(store, PHP_TAG, PHPColorProvider.TAG); - PreferenceConverter.setDefault(store, PHP_KEYWORD, PHPColorProvider.KEYWORD); - PreferenceConverter.setDefault(store, PHP_VARIABLE, PHPColorProvider.VARIABLE); - PreferenceConverter.setDefault(store, PHP_VARIABLE_DOLLAR, PHPColorProvider.VARIABLE); - PreferenceConverter.setDefault(store, PHP_FUNCTIONNAME, PHPColorProvider.FUNCTION_NAME); - PreferenceConverter.setDefault(store, PHP_CONSTANT, PHPColorProvider.CONSTANT); - PreferenceConverter.setDefault(store, PHP_TYPE, PHPColorProvider.TYPE); -// PreferenceConverter.setDefault(store, PHP_STRING_DQ, PHPColorProvider.STRING_DQ); -// store.setDefault(PHP_STRING_BOLD_DQ, true); -// PreferenceConverter.setDefault(store, PHP_STRING_SQ, PHPColorProvider.STRING_SQ); - PreferenceConverter.setDefault(store, PHP_DEFAULT, PHPColorProvider.DEFAULT); - PreferenceConverter.setDefault(store, PHPDOC_KEYWORD, PHPColorProvider.PHPDOC_KEYWORD); - PreferenceConverter.setDefault(store, PHPDOC_TAG, PHPColorProvider.PHPDOC_TAG); - PreferenceConverter.setDefault(store, PHPDOC_LINK, PHPColorProvider.PHPDOC_LINK); - PreferenceConverter.setDefault(store, PHPDOC_DEFAULT, PHPColorProvider.PHPDOC_DEFAULT); - - PreferenceConverter.setDefault(store, EDITOR_PHP_KEYWORD_RETURN_COLOR, new RGB(127, 0, 85)); - store.setDefault(EDITOR_PHP_KEYWORD_RETURN_BOLD, true); - store.setDefault(EDITOR_PHP_KEYWORD_RETURN_ITALIC, false); - - PreferenceConverter.setDefault(store, EDITOR_PHP_OPERATOR_COLOR, new RGB(0, 0, 0)); - store.setDefault(EDITOR_PHP_OPERATOR_BOLD, false); - store.setDefault(EDITOR_PHP_OPERATOR_ITALIC, false); - - PreferenceConverter.setDefault(store, EDITOR_PHP_BRACE_OPERATOR_COLOR, new RGB(0, 0, 0)); - store.setDefault(EDITOR_PHP_BRACE_OPERATOR_BOLD, false); - store.setDefault(EDITOR_PHP_BRACE_OPERATOR_ITALIC, false); - // PreferenceConverter.setDefault( - // store, - // PHP_EDITOR_BACKGROUND, - // PHPColorProvider.BACKGROUND); - // PreferenceConverter.setDefault( - // store, - // LINKED_POSITION_COLOR, - // PHPColorProvider.LINKED_POSITION_COLOR); - // PreferenceConverter.setDefault( - // store, - // LINE_NUMBER_COLOR, - // PHPColorProvider.LINE_NUMBER_COLOR); - // // set default PHPDoc colors: - // PreferenceConverter.setDefault( - // store, - // PHPDOC_KEYWORD, - // PHPColorProvider.PHPDOC_KEYWORD); - // PreferenceConverter.setDefault( - // store, - // PHPDOC_LINK, - // PHPColorProvider.PHPDOC_LINK); - // PreferenceConverter.setDefault( - // store, - // PHPDOC_DEFAULT, - // PHPColorProvider.PHPDOC_DEFAULT); - // PreferenceConverter.setDefault( - // store, - // PHPDOC_TAG, - // PHPColorProvider.PHPDOC_TAG); - // store.setDefault(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT, "true"); - // PreferenceConverter.setDefault( - // store, - // PREFERENCE_COLOR_BACKGROUND, - // PHPColorProvider.BACKGROUND_COLOR); - //language stuff - // store.setDefault(RESOURCE_BUNDLE, LANGUAGE_DEFAULT); - // store.setDefault(RESOURCE_BUNDLE_EN_GB, "true"); - // store.setDefault(RESOURCE_BUNDLE_DE, "false"); - // store.setDefault(RESOURCE_BUNDLE_FR, "false"); - // store.setDefault(RESOURCE_BUNDLE_ES, "false"); - // TemplatePreferencePage.initDefaults(store); - //this will initialize the static fields in the syntaxrdr class - new PHPSyntaxRdr(); - JavaCore.initializeDefaultPluginPreferences(); - PreferenceConstants.initializeDefaultValues(store); -// externalTools.initializeDefaultPreferences(store); - MarkerAnnotationPreferences.initializeDefaultValues(store); - } - - private IWorkbenchPage internalGetActivePage() { - IWorkbenchWindow window = getWorkbench().getActiveWorkbenchWindow(); - if (window != null) - return window.getActivePage(); - return null; - } - - private ImageDescriptorRegistry internalGetImageDescriptorRegistry() { - if (fImageDescriptorRegistry == null) - fImageDescriptorRegistry = new ImageDescriptorRegistry(); - return fImageDescriptorRegistry; - } - - /** - * Open a file in the Workbench that may or may not exist in the workspace. Must be run on the UI thread. - * - * @param filename - * @throws CoreException - */ - public ITextEditor openFileInTextEditor(String filename) throws CoreException { - // reject directories - if (new File(filename).isDirectory()) - return null; - IWorkbench workbench = PlatformUI.getWorkbench(); - IWorkbenchWindow window = workbench.getWorkbenchWindows()[0]; - IWorkbenchPage page = window.getActivePage(); - IPath path = new Path(filename); - // If the file exists in the workspace, open it - IFile file = getWorkspace().getRoot().getFileForLocation(path); - IEditorPart editor; - ITextEditor textEditor; - if (file != null && file.exists()) { - editor = IDE.openEditor(page, file, true); - textEditor = (ITextEditor) editor.getAdapter(ITextEditor.class); - } else { - // Otherwise open the stream directly - if (page == null) + private IWorkbenchPage internalGetActivePage() { + IWorkbenchWindow window = getWorkbench().getActiveWorkbenchWindow(); + if (window != null) + return window.getActivePage(); return null; - FileStorage storage = new FileStorage(path); - IEditorRegistry registry = getWorkbench().getEditorRegistry(); - IEditorDescriptor desc = registry.getDefaultEditor(filename); - if (desc == null) { - desc = registry.findEditor(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID); - // desc = registry.getDefaultEditor(); - } - IEditorInput input = new ExternalEditorInput(storage); - editor = page.openEditor(input, desc.getId()); - textEditor = (ITextEditor) editor.getAdapter(ITextEditor.class); - // If the storage provider is not ours, we can't guarantee read/write. - if (textEditor != null) { - IDocumentProvider documentProvider = textEditor.getDocumentProvider(); - if (!(documentProvider instanceof ExternalStorageDocumentProvider)) { - storage.setReadOnly(); + } + + private ImageDescriptorRegistry internalGetImageDescriptorRegistry() { + if (fImageDescriptorRegistry == null) + fImageDescriptorRegistry = new ImageDescriptorRegistry(); + return fImageDescriptorRegistry; + } + + /** + * Open a file in the Workbench that may or may not exist in the workspace. + * Must be run on the UI thread. + * + * @param filename + * @throws CoreException + */ + public ITextEditor openFileInTextEditor(String filename) + throws CoreException { + // reject directories + if (new File(filename).isDirectory()) + return null; + IWorkbench workbench = PlatformUI.getWorkbench(); + IWorkbenchWindow window = workbench.getWorkbenchWindows()[0]; + IWorkbenchPage page = window.getActivePage(); + IPath path = new Path(filename); + // If the file exists in the workspace, open it + IFile file = getWorkspace().getRoot().getFileForLocation(path); + IEditorPart editor; + ITextEditor textEditor; + if (file != null && file.exists()) { + editor = IDE.openEditor(page, file, true); + textEditor = (ITextEditor) editor.getAdapter(ITextEditor.class); + } else { + // Otherwise open the stream directly + if (page == null) + return null; + FileStorage storage = new FileStorage(path); + IEditorRegistry registry = getWorkbench().getEditorRegistry(); + IEditorDescriptor desc = registry.getDefaultEditor(filename); + if (desc == null) { + desc = registry + .findEditor(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID); + // desc = registry.getDefaultEditor(); + } + IEditorInput input = new ExternalEditorInput(storage); + editor = page.openEditor(input, desc.getId()); + textEditor = (ITextEditor) editor.getAdapter(ITextEditor.class); + // If the storage provider is not ours, we can't guarantee + // read/write. + if (textEditor != null) { + IDocumentProvider documentProvider = textEditor + .getDocumentProvider(); + if (!(documentProvider instanceof ExternalStorageDocumentProvider)) { + storage.setReadOnly(); + } + } } - } + return textEditor; } - return textEditor; - } - - /** - * Open a file in the Workbench that may or may not exist in the workspace. Must be run on the UI thread. - * - * @param filename - * @param line - * @throws CoreException - */ - public void openFileAndGotoLine(String filename, int line) throws CoreException { - ITextEditor textEditor = openFileInTextEditor(filename); - if (textEditor != null) { - // If a line number was given, go to it - if (line > 0) { - try { - line--; // document is 0 based - IDocument document = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput()); - textEditor.selectAndReveal(document.getLineOffset(line), document.getLineLength(line)); - } catch (BadLocationException e) { - // invalid text position -> do nothing + + /** + * Open a file in the Workbench that may or may not exist in the workspace. + * Must be run on the UI thread. + * + * @param filename + * @param line + * @throws CoreException + */ + public void openFileAndGotoLine(String filename, int line) + throws CoreException { + ITextEditor textEditor = openFileInTextEditor(filename); + if (textEditor != null) { + // If a line number was given, go to it + if (line > 0) { + try { + line--; // document is 0 based + IDocument document = textEditor.getDocumentProvider() + .getDocument(textEditor.getEditorInput()); + textEditor.selectAndReveal(document.getLineOffset(line), + document.getLineLength(line)); + } catch (BadLocationException e) { + // invalid text position -> do nothing + } + } } - } } - } - - /** - * Open a file in the Workbench that may or may not exist in the workspace. Must be run on the UI thread. - * - * @param filename - * @param offset - * @throws CoreException - */ - public void openFileAndGotoOffset(String filename, int offset, int length) throws CoreException { - ITextEditor textEditor = openFileInTextEditor(filename); - if (textEditor != null) { - // If a line number was given, go to it - if (offset >= 0) { - IDocument document = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput()); - textEditor.selectAndReveal(offset, length); - } + + /** + * Open a file in the Workbench that may or may not exist in the workspace. + * Must be run on the UI thread. + * + * @param filename + * @param offset + * @throws CoreException + */ + public void openFileAndGotoOffset(String filename, int offset, int length) + throws CoreException { + ITextEditor textEditor = openFileInTextEditor(filename); + if (textEditor != null) { + // If a line number was given, go to it + if (offset >= 0) { + IDocument document = textEditor.getDocumentProvider() + .getDocument(textEditor.getEditorInput()); + textEditor.selectAndReveal(offset, length); + } + } } - } - public void openFileAndFindString(String filename, String findString) throws CoreException { - ITextEditor textEditor = openFileInTextEditor(filename); - if (textEditor != null) { - // If a string was given, go to it - if (findString != null) { - try { - IDocument document = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput()); - int offset = document.search(0, findString, true, false, true); - textEditor.selectAndReveal(offset, findString.length()); - } catch (BadLocationException e) { - // invalid text position -> do nothing + public void openFileAndFindString(String filename, String findString) + throws CoreException { + ITextEditor textEditor = openFileInTextEditor(filename); + if (textEditor != null) { + // If a string was given, go to it + if (findString != null) { + try { + IDocument document = textEditor.getDocumentProvider() + .getDocument(textEditor.getEditorInput()); + int offset = document.search(0, findString, true, false, + true); + textEditor.selectAndReveal(offset, findString.length()); + } catch (BadLocationException e) { + // invalid text position -> do nothing + } + } } - } } - } - - public void setLastEditorFile(IFile textEditor) { - this.fLastEditorFile = textEditor; - } - - /* - * @see org.eclipse.core.runtime.Plugin#stop - */ - public void stop(BundleContext context) throws Exception { - try { - // JavaCore.stop(this, context); - plugin.savePluginPreferences(); - IWorkspace workspace = ResourcesPlugin.getWorkspace(); - workspace.removeResourceChangeListener(JavaModelManager.getJavaModelManager().deltaState); - workspace.removeSaveParticipant(plugin); - - JavaModelManager.getJavaModelManager().shutdown(); - - // save the information from the php index files if necessary - Collection collection = fIndexManagerMap.values(); - Iterator iterator = collection.iterator(); - IdentifierIndexManager indexManager = null; - while (iterator.hasNext()) { - indexManager = (IdentifierIndexManager) iterator.next(); - indexManager.writeFile(); - } - if (fImageDescriptorRegistry != null) - fImageDescriptorRegistry.dispose(); - - // AllTypesCache.terminate(); - - if (fImageDescriptorRegistry != null) - fImageDescriptorRegistry.dispose(); - - unregisterAdapters(); - - // if (fASTProvider != null) { - // fASTProvider.dispose(); - // fASTProvider= null; - // } - - if (fWorkingCopyManager != null) { - fWorkingCopyManager.shutdown(); - fWorkingCopyManager = null; - } - - if (fCompilationUnitDocumentProvider != null) { - fCompilationUnitDocumentProvider.shutdown(); - fCompilationUnitDocumentProvider = null; - } - - if (fJavaTextTools != null) { - fJavaTextTools.dispose(); - fJavaTextTools = null; - } - // JavaDocLocations.shutdownJavadocLocations(); - - uninstallPreferenceStoreBackwardsCompatibility(); - - // RefactoringCore.getUndoManager().shutdown(); - } finally { - super.stop(context); + + public void setLastEditorFile(IFile textEditor) { + this.fLastEditorFile = textEditor; } - } - - /** - * @see org.eclipse.ui.plugin.AbstractUIPlugin#shutdown() - */ - // public void shutdown() throws CoreException { - // // moved down (see below): - // // super.shutdown(); - // // externalTools.shutDown(); - // ColorManager.getDefault().dispose(); - // // save the information from the php index files if necessary - // Collection collection = fIndexManagerMap.values(); - // Iterator iterator = collection.iterator(); - // IdentifierIndexManager indexManager = null; - // while (iterator.hasNext()) { - // indexManager = (IdentifierIndexManager) iterator.next(); - // indexManager.writeFile(); - // } - // if (fImageDescriptorRegistry != null) - // fImageDescriptorRegistry.dispose(); - // // unregisterAdapters(); - // super.shutdown(); - // if (fWorkingCopyManager != null) { - // fWorkingCopyManager.shutdown(); - // fWorkingCopyManager = null; - // } - // if (fCompilationUnitDocumentProvider != null) { - // fCompilationUnitDocumentProvider.shutdown(); - // fCompilationUnitDocumentProvider = null; - // } - // if (fJavaTextTools != null) { - // fJavaTextTools.dispose(); - // fJavaTextTools = null; - // } - // // JavaDocLocations.shutdownJavadocLocations(); - // // - // // - // JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener); - // // begin JavaCore#shutdown() - // //savePluginPreferences(); - // savePluginPreferences(); - // IWorkspace workspace = ResourcesPlugin.getWorkspace(); - // workspace.removeResourceChangeListener(JavaModelManager.getJavaModelManager().deltaState); - // workspace.removeSaveParticipant(this); - // ((JavaModelManager) JavaModelManager.getJavaModelManager()).shutdown(); - // // end JavaCore#shutdown() - // } - /** - * Installs backwards compatibility for the preference store. - */ - private void installPreferenceStoreBackwardsCompatibility() { /* - * Installs backwards compatibility: propagate the Java editor font from a pre-2.1 plug-in to the Platform UI's preference store - * to preserve the Java editor font from a pre-2.1 workspace. This is done only once. + * @see org.eclipse.core.runtime.Plugin#stop */ - String fontPropagatedKey = "fontPropagated"; //$NON-NLS-1$ - if (getPreferenceStore().contains(JFaceResources.TEXT_FONT) && !getPreferenceStore().isDefault(JFaceResources.TEXT_FONT)) { - if (!getPreferenceStore().getBoolean(fontPropagatedKey)) - PreferenceConverter.setValue(PlatformUI.getWorkbench().getPreferenceStore(), PreferenceConstants.EDITOR_TEXT_FONT, - PreferenceConverter.getFontDataArray(getPreferenceStore(), JFaceResources.TEXT_FONT)); + public void stop(BundleContext context) throws Exception { + try { + // JavaCore.stop(this, context); + plugin.savePluginPreferences(); + IWorkspace workspace = ResourcesPlugin.getWorkspace(); + workspace.removeResourceChangeListener(JavaModelManager + .getJavaModelManager().deltaState); + workspace.removeSaveParticipant(plugin); + + JavaModelManager.getJavaModelManager().shutdown(); + + // save the information from the php index files if necessary + Collection collection = fIndexManagerMap.values(); + Iterator iterator = collection.iterator(); + IdentifierIndexManager indexManager = null; + while (iterator.hasNext()) { + indexManager = (IdentifierIndexManager) iterator.next(); + indexManager.writeFile(); + } + if (fImageDescriptorRegistry != null) + fImageDescriptorRegistry.dispose(); + + // AllTypesCache.terminate(); + + if (fImageDescriptorRegistry != null) + fImageDescriptorRegistry.dispose(); + + unregisterAdapters(); + + // if (fASTProvider != null) { + // fASTProvider.dispose(); + // fASTProvider= null; + // } + + if (fWorkingCopyManager != null) { + fWorkingCopyManager.shutdown(); + fWorkingCopyManager = null; + } + + if (fCompilationUnitDocumentProvider != null) { + fCompilationUnitDocumentProvider.shutdown(); + fCompilationUnitDocumentProvider = null; + } + + if (fJavaTextTools != null) { + fJavaTextTools.dispose(); + fJavaTextTools = null; + } + // JavaDocLocations.shutdownJavadocLocations(); + + uninstallPreferenceStoreBackwardsCompatibility(); + + // RefactoringCore.getUndoManager().shutdown(); + } finally { + super.stop(context); + } } - getPreferenceStore().setValue(fontPropagatedKey, true); - /* - * Backwards compatibility: set the Java editor font in this plug-in's preference store to let older versions access it. Since - * 2.1 the Java editor font is managed by the workbench font preference page. + /** + * @see org.eclipse.ui.plugin.AbstractUIPlugin#shutdown() + */ + // public void shutdown() throws CoreException { + // // moved down (see below): + // // super.shutdown(); + // // externalTools.shutDown(); + // ColorManager.getDefault().dispose(); + // // save the information from the php index files if necessary + // Collection collection = fIndexManagerMap.values(); + // Iterator iterator = collection.iterator(); + // IdentifierIndexManager indexManager = null; + // while (iterator.hasNext()) { + // indexManager = (IdentifierIndexManager) iterator.next(); + // indexManager.writeFile(); + // } + // if (fImageDescriptorRegistry != null) + // fImageDescriptorRegistry.dispose(); + // // unregisterAdapters(); + // super.shutdown(); + // if (fWorkingCopyManager != null) { + // fWorkingCopyManager.shutdown(); + // fWorkingCopyManager = null; + // } + // if (fCompilationUnitDocumentProvider != null) { + // fCompilationUnitDocumentProvider.shutdown(); + // fCompilationUnitDocumentProvider = null; + // } + // if (fJavaTextTools != null) { + // fJavaTextTools.dispose(); + // fJavaTextTools = null; + // } + // // JavaDocLocations.shutdownJavadocLocations(); + // // + // // + // JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener); + // // begin JavaCore#shutdown() + // //savePluginPreferences(); + // savePluginPreferences(); + // IWorkspace workspace = ResourcesPlugin.getWorkspace(); + // workspace.removeResourceChangeListener(JavaModelManager.getJavaModelManager().deltaState); + // workspace.removeSaveParticipant(this); + // ((JavaModelManager) JavaModelManager.getJavaModelManager()).shutdown(); + // // end JavaCore#shutdown() + // } + /** + * Installs backwards compatibility for the preference store. */ - PreferenceConverter.putValue(getPreferenceStore(), JFaceResources.TEXT_FONT, JFaceResources.getFontRegistry().getFontData( - PreferenceConstants.EDITOR_TEXT_FONT)); - - fFontPropertyChangeListener = new IPropertyChangeListener() { - public void propertyChange(PropertyChangeEvent event) { - if (PreferenceConstants.EDITOR_TEXT_FONT.equals(event.getProperty())) - PreferenceConverter.putValue(getPreferenceStore(), JFaceResources.TEXT_FONT, JFaceResources.getFontRegistry() - .getFontData(PreferenceConstants.EDITOR_TEXT_FONT)); - } - }; - JFaceResources.getFontRegistry().addListener(fFontPropertyChangeListener); + private void installPreferenceStoreBackwardsCompatibility() { - /* - * Backwards compatibility: propagate the Java editor tab width from a pre-3.0 plug-in to the new preference key. This is done - * only once. + /* + * Installs backwards compatibility: propagate the Java editor font from + * a pre-2.1 plug-in to the Platform UI's preference store to preserve + * the Java editor font from a pre-2.1 workspace. This is done only + * once. + */ + String fontPropagatedKey = "fontPropagated"; //$NON-NLS-1$ + if (getPreferenceStore().contains(JFaceResources.TEXT_FONT) + && !getPreferenceStore().isDefault(JFaceResources.TEXT_FONT)) { + if (!getPreferenceStore().getBoolean(fontPropagatedKey)) + PreferenceConverter + .setValue(PlatformUI.getWorkbench() + .getPreferenceStore(), + PreferenceConstants.EDITOR_TEXT_FONT, + PreferenceConverter.getFontDataArray( + getPreferenceStore(), + JFaceResources.TEXT_FONT)); + } + getPreferenceStore().setValue(fontPropagatedKey, true); + + /* + * Backwards compatibility: set the Java editor font in this plug-in's + * preference store to let older versions access it. Since 2.1 the Java + * editor font is managed by the workbench font preference page. + */ + PreferenceConverter.putValue(getPreferenceStore(), + JFaceResources.TEXT_FONT, JFaceResources.getFontRegistry() + .getFontData(PreferenceConstants.EDITOR_TEXT_FONT)); + + fFontPropertyChangeListener = new IPropertyChangeListener() { + public void propertyChange(PropertyChangeEvent event) { + if (PreferenceConstants.EDITOR_TEXT_FONT.equals(event + .getProperty())) + PreferenceConverter.putValue(getPreferenceStore(), + JFaceResources.TEXT_FONT, + JFaceResources.getFontRegistry().getFontData( + PreferenceConstants.EDITOR_TEXT_FONT)); + } + }; + JFaceResources.getFontRegistry().addListener( + fFontPropertyChangeListener); + + /* + * Backwards compatibility: propagate the Java editor tab width from a + * pre-3.0 plug-in to the new preference key. This is done only once. + */ + // final String oldTabWidthKey = PreferenceConstants.EDITOR_TAB_WIDTH; + // final String newTabWidthKey = + // AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH; + // String tabWidthPropagatedKey = "tabWidthPropagated"; //$NON-NLS-1$ + // if (getPreferenceStore().contains(oldTabWidthKey) && + // !getPreferenceStore().isDefault(oldTabWidthKey)) { + // if (!getPreferenceStore().getBoolean(tabWidthPropagatedKey)) + // getPreferenceStore().setValue(newTabWidthKey, + // getPreferenceStore().getInt(oldTabWidthKey)); + // } + // getPreferenceStore().setValue(tabWidthPropagatedKey, true); + // + // /* + // * Backwards compatibility: set the Java editor tab width in this + // plug-in's preference store with the old key to let older + // * versions access it. Since 3.0 the tab width is managed by the + // extended texteditor and uses a new key. + // */ + // getPreferenceStore().putValue(oldTabWidthKey, + // getPreferenceStore().getString(newTabWidthKey)); + // fPropertyChangeListener = new IPropertyChangeListener() { + // public void propertyChange(PropertyChangeEvent event) { + // if (newTabWidthKey.equals(event.getProperty())) + // getPreferenceStore().putValue(oldTabWidthKey, + // getPreferenceStore().getString(newTabWidthKey)); + // } + // }; + // getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener); + /* + * Backward compatibility for the refactoring preference key. + */ + // getPreferenceStore().setValue( + // PreferenceConstants.REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD, + // RefactoringCore.getConditionCheckingFailedSeverity()); + } + + /** + * Uninstalls backwards compatibility for the preference store. */ - // final String oldTabWidthKey = PreferenceConstants.EDITOR_TAB_WIDTH; - // final String newTabWidthKey = AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH; - // String tabWidthPropagatedKey = "tabWidthPropagated"; //$NON-NLS-1$ - // if (getPreferenceStore().contains(oldTabWidthKey) && !getPreferenceStore().isDefault(oldTabWidthKey)) { - // if (!getPreferenceStore().getBoolean(tabWidthPropagatedKey)) - // getPreferenceStore().setValue(newTabWidthKey, getPreferenceStore().getInt(oldTabWidthKey)); - // } - // getPreferenceStore().setValue(tabWidthPropagatedKey, true); - // - // /* - // * Backwards compatibility: set the Java editor tab width in this plug-in's preference store with the old key to let older - // * versions access it. Since 3.0 the tab width is managed by the extended texteditor and uses a new key. - // */ - // getPreferenceStore().putValue(oldTabWidthKey, getPreferenceStore().getString(newTabWidthKey)); - // fPropertyChangeListener = new IPropertyChangeListener() { - // public void propertyChange(PropertyChangeEvent event) { - // if (newTabWidthKey.equals(event.getProperty())) - // getPreferenceStore().putValue(oldTabWidthKey, getPreferenceStore().getString(newTabWidthKey)); - // } - // }; - // getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener); + private void uninstallPreferenceStoreBackwardsCompatibility() { + JFaceResources.getFontRegistry().removeListener( + fFontPropertyChangeListener); + // getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener); + } + /* - * Backward compatibility for the refactoring preference key. + * (non - Javadoc) Method declared in Plugin */ - // getPreferenceStore().setValue( - // PreferenceConstants.REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD, - // RefactoringCore.getConditionCheckingFailedSeverity()); - } - - /** - * Uninstalls backwards compatibility for the preference store. - */ - private void uninstallPreferenceStoreBackwardsCompatibility() { - JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener); - // getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener); - } - - /* - * (non - Javadoc) Method declared in Plugin - */ - public void start(BundleContext context) throws Exception { - super.start(context); - - // JavaCore.start(this, context); - final JavaModelManager modelManager = JavaModelManager.getJavaModelManager(); - try { - modelManager.configurePluginDebugOptions(); - - // request state folder creation (workaround 19885) - // JavaCore.getPlugin().getStateLocation(); - getStateLocation(); - // retrieve variable values - PHPeclipsePlugin.getDefault().getPluginPreferences().addPropertyChangeListener( - new JavaModelManager.PluginPreferencesListener()); - // manager.loadVariablesAndContainers(); - - final IWorkspace workspace = ResourcesPlugin.getWorkspace(); - workspace.addResourceChangeListener(modelManager.deltaState, IResourceChangeEvent.PRE_BUILD | IResourceChangeEvent.POST_BUILD - | IResourceChangeEvent.POST_CHANGE | IResourceChangeEvent.PRE_DELETE | IResourceChangeEvent.PRE_CLOSE); - - // startIndexing(); - ISavedState savedState = workspace.addSaveParticipant(PHPeclipsePlugin.this, modelManager); - - // process deltas since last activated in indexer thread so that indexes are up-to-date. - // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38658 - Job processSavedState = new Job(Util.bind("savedState.jobName")) { //$NON-NLS-1$ - protected IStatus run(IProgressMonitor monitor) { - try { - // add save participant and process delta atomically - // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=59937 - workspace.run(new IWorkspaceRunnable() { - public void run(IProgressMonitor progress) throws CoreException { - ISavedState savedState = workspace.addSaveParticipant(PHPeclipsePlugin.this, modelManager); - if (savedState != null) { - // the event type coming from the saved state is always POST_AUTO_BUILD - // force it to be POST_CHANGE so that the delta processor can handle it - modelManager.deltaState.getDeltaProcessor().overridenEventType = IResourceChangeEvent.POST_CHANGE; - savedState.processResourceChangeEvents(modelManager.deltaState); + public void start(BundleContext context) throws Exception { + super.start(context); + + // JavaCore.start(this, context); + final JavaModelManager modelManager = JavaModelManager + .getJavaModelManager(); + try { + modelManager.configurePluginDebugOptions(); + + // request state folder creation (workaround 19885) + // JavaCore.getPlugin().getStateLocation(); + getStateLocation(); + // retrieve variable values + PHPeclipsePlugin.getDefault().getPluginPreferences() + .addPropertyChangeListener( + new JavaModelManager.PluginPreferencesListener()); + // manager.loadVariablesAndContainers(); + + final IWorkspace workspace = ResourcesPlugin.getWorkspace(); + workspace.addResourceChangeListener(modelManager.deltaState, + IResourceChangeEvent.PRE_BUILD + | IResourceChangeEvent.POST_BUILD + | IResourceChangeEvent.POST_CHANGE + | IResourceChangeEvent.PRE_DELETE + | IResourceChangeEvent.PRE_CLOSE); + + // startIndexing(); + ISavedState savedState = workspace.addSaveParticipant( + PHPeclipsePlugin.this, modelManager); + + // process deltas since last activated in indexer thread so that + // indexes are up-to-date. + // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38658 + Job processSavedState = new Job(Util.bind("savedState.jobName")) { //$NON-NLS-1$ + protected IStatus run(IProgressMonitor monitor) { + try { + // add save participant and process delta atomically + // see + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=59937 + workspace.run(new IWorkspaceRunnable() { + public void run(IProgressMonitor progress) + throws CoreException { + ISavedState savedState = workspace + .addSaveParticipant( + PHPeclipsePlugin.this, + modelManager); + if (savedState != null) { + // the event type coming from the saved + // state is always POST_AUTO_BUILD + // force it to be POST_CHANGE so that the + // delta processor can handle it + modelManager.deltaState.getDeltaProcessor().overridenEventType = IResourceChangeEvent.POST_CHANGE; + savedState + .processResourceChangeEvents(modelManager.deltaState); + } + } + }, monitor); + } catch (CoreException e) { + return e.getStatus(); + } + return Status.OK_STATUS; } - } - }, monitor); - } catch (CoreException e) { - return e.getStatus(); - } - return Status.OK_STATUS; + }; + processSavedState.setSystem(true); + processSavedState.setPriority(Job.SHORT); // process asap + processSavedState.schedule(); + } catch (RuntimeException e) { + modelManager.shutdown(); + throw e; } - }; - processSavedState.setSystem(true); - processSavedState.setPriority(Job.SHORT); // process asap - processSavedState.schedule(); - } catch (RuntimeException e) { - modelManager.shutdown(); - throw e; + + registerAdapters(); + + // if (USE_WORKING_COPY_OWNERS) { + WorkingCopyOwner.setPrimaryBufferProvider(new WorkingCopyOwner() { + public IBuffer createBuffer(ICompilationUnit workingCopy) { + ICompilationUnit original = workingCopy.getPrimary(); + IResource resource = original.getResource(); + if (resource instanceof IFile) + return new DocumentAdapter(workingCopy, (IFile) resource); + return DocumentAdapter.NULL; + } + }); + // } + + installPreferenceStoreBackwardsCompatibility(); + } - registerAdapters(); - - // if (USE_WORKING_COPY_OWNERS) { - WorkingCopyOwner.setPrimaryBufferProvider(new WorkingCopyOwner() { - public IBuffer createBuffer(ICompilationUnit workingCopy) { - ICompilationUnit original = workingCopy.getPrimary(); - IResource resource = original.getResource(); - if (resource instanceof IFile) - return new DocumentAdapter(workingCopy, (IFile) resource); - return DocumentAdapter.NULL; - } - }); - // } - - installPreferenceStoreBackwardsCompatibility(); - - } - - // registerAdapters(); - // - // // externalTools.startUp(); - // getStandardDisplay().asyncExec(new Runnable() { - // public void run() { - // //initialize the variable context manager - // VariableContextManager.getDefault(); - // } - // }); - // - // // if (USE_WORKING_COPY_OWNERS) { - // WorkingCopyOwner.setPrimaryBufferProvider(new WorkingCopyOwner() { - // public IBuffer createBuffer(ICompilationUnit workingCopy) { - // ICompilationUnit original = workingCopy.getPrimary(); - // IResource resource = original.getResource(); - // if (resource instanceof IFile) - // return new DocumentAdapter(workingCopy, (IFile) resource); - // return DocumentAdapter.NULL; - // } - // }); - // // } - - // installPreferenceStoreBackwardsCompatibility(); - - // AllTypesCache.initialize(); - - // Initialize AST provider - // getASTProvider(); - // } - - // public void startup() throws CoreException { - // super.startup(); - // // begin JavaCore.startup(); - // JavaModelManager manager = JavaModelManager.getJavaModelManager(); - // try { - // manager.configurePluginDebugOptions(); - // // request state folder creation (workaround 19885) - // // JavaCore.getPlugin().getStateLocation(); - // getStateLocation(); - // // retrieve variable values - // // - // JavaCore.getPlugin().getPluginPreferences().addPropertyChangeListener(new - // // JavaModelManager.PluginPreferencesListener()); - // getPluginPreferences().addPropertyChangeListener( - // new JavaModelManager.PluginPreferencesListener()); - // // TODO temp-del - // // manager.loadVariablesAndContainers(); - // final IWorkspace workspace = ResourcesPlugin.getWorkspace(); - // workspace.addResourceChangeListener( - // manager.deltaState, - // IResourceChangeEvent.PRE_BUILD - // | IResourceChangeEvent.POST_BUILD - // | IResourceChangeEvent.POST_CHANGE - // | IResourceChangeEvent.PRE_DELETE - // | IResourceChangeEvent.PRE_CLOSE); - // // startIndexing(); - // workspace.addSaveParticipant(PHPeclipsePlugin.getDefault(), manager); - // } catch (CoreException e) { - // } catch (RuntimeException e) { - // manager.shutdown(); - // throw e; - // } - // // end JavaCore.startup(); - // IAdapterManager platformManager = Platform.getAdapterManager(); - // platformManager.registerAdapters(new PHPElementAdapterFactory(), - // PHPElement.class); - // platformManager.registerAdapters(new ResourceAdapterFactory(), - // IResource.class); - // // externalTools.startUp(); - // getStandardDisplay().asyncExec(new Runnable() { - // public void run() { - // //initialize the variable context manager - // VariableContextManager.getDefault(); - // } - // }); - // } - - private void registerAdapters() { - fJavaElementAdapterFactory = new JavaElementAdapterFactory(); - // fMarkerAdapterFactory= new MarkerAdapterFactory(); - // fEditorInputAdapterFactory= new EditorInputAdapterFactory(); - fResourceAdapterFactory = new ResourceAdapterFactory(); - // fLogicalPackageAdapterFactory= new LogicalPackageAdapterFactory(); - - IAdapterManager manager = Platform.getAdapterManager(); - manager.registerAdapters(fJavaElementAdapterFactory, IJavaElement.class); - // manager.registerAdapters(fMarkerAdapterFactory, IMarker.class); - // manager.registerAdapters(fEditorInputAdapterFactory, IEditorInput.class); - manager.registerAdapters(fResourceAdapterFactory, IResource.class); - // manager.registerAdapters(fLogicalPackageAdapterFactory, - // LogicalPackage.class); - } - - private void unregisterAdapters() { - IAdapterManager manager = Platform.getAdapterManager(); - manager.unregisterAdapters(fJavaElementAdapterFactory); - // manager.unregisterAdapters(fMarkerAdapterFactory); - // manager.unregisterAdapters(fEditorInputAdapterFactory); - manager.unregisterAdapters(fResourceAdapterFactory); - // manager.unregisterAdapters(fLogicalPackageAdapterFactory); - } - - /** - * Returns a combined preference store, this store is read-only. - * - * @return the combined preference store - * - * @since 3.0 - */ - public IPreferenceStore getCombinedPreferenceStore() { - if (fCombinedPreferenceStore == null) { - IPreferenceStore generalTextStore = EditorsUI.getPreferenceStore(); - fCombinedPreferenceStore = new ChainedPreferenceStore(new IPreferenceStore[] { - getPreferenceStore(), - new PreferencesAdapter(PHPeclipsePlugin.getDefault().getPluginPreferences()), - generalTextStore }); + // registerAdapters(); + // + // // externalTools.startUp(); + // getStandardDisplay().asyncExec(new Runnable() { + // public void run() { + // //initialize the variable context manager + // VariableContextManager.getDefault(); + // } + // }); + // + // // if (USE_WORKING_COPY_OWNERS) { + // WorkingCopyOwner.setPrimaryBufferProvider(new WorkingCopyOwner() { + // public IBuffer createBuffer(ICompilationUnit workingCopy) { + // ICompilationUnit original = workingCopy.getPrimary(); + // IResource resource = original.getResource(); + // if (resource instanceof IFile) + // return new DocumentAdapter(workingCopy, (IFile) resource); + // return DocumentAdapter.NULL; + // } + // }); + // // } + + // installPreferenceStoreBackwardsCompatibility(); + + // AllTypesCache.initialize(); + + // Initialize AST provider + // getASTProvider(); + // } + + // public void startup() throws CoreException { + // super.startup(); + // // begin JavaCore.startup(); + // JavaModelManager manager = JavaModelManager.getJavaModelManager(); + // try { + // manager.configurePluginDebugOptions(); + // // request state folder creation (workaround 19885) + // // JavaCore.getPlugin().getStateLocation(); + // getStateLocation(); + // // retrieve variable values + // // + // JavaCore.getPlugin().getPluginPreferences().addPropertyChangeListener(new + // // JavaModelManager.PluginPreferencesListener()); + // getPluginPreferences().addPropertyChangeListener( + // new JavaModelManager.PluginPreferencesListener()); + // // TODO temp-del + // // manager.loadVariablesAndContainers(); + // final IWorkspace workspace = ResourcesPlugin.getWorkspace(); + // workspace.addResourceChangeListener( + // manager.deltaState, + // IResourceChangeEvent.PRE_BUILD + // | IResourceChangeEvent.POST_BUILD + // | IResourceChangeEvent.POST_CHANGE + // | IResourceChangeEvent.PRE_DELETE + // | IResourceChangeEvent.PRE_CLOSE); + // // startIndexing(); + // workspace.addSaveParticipant(PHPeclipsePlugin.getDefault(), manager); + // } catch (CoreException e) { + // } catch (RuntimeException e) { + // manager.shutdown(); + // throw e; + // } + // // end JavaCore.startup(); + // IAdapterManager platformManager = Platform.getAdapterManager(); + // platformManager.registerAdapters(new PHPElementAdapterFactory(), + // PHPElement.class); + // platformManager.registerAdapters(new ResourceAdapterFactory(), + // IResource.class); + // // externalTools.startUp(); + // getStandardDisplay().asyncExec(new Runnable() { + // public void run() { + // //initialize the variable context manager + // VariableContextManager.getDefault(); + // } + // }); + // } + + private void registerAdapters() { + fJavaElementAdapterFactory = new JavaElementAdapterFactory(); + // fMarkerAdapterFactory= new MarkerAdapterFactory(); + // fEditorInputAdapterFactory= new EditorInputAdapterFactory(); + fResourceAdapterFactory = new ResourceAdapterFactory(); + // fLogicalPackageAdapterFactory= new LogicalPackageAdapterFactory(); + + IAdapterManager manager = Platform.getAdapterManager(); + manager + .registerAdapters(fJavaElementAdapterFactory, + IJavaElement.class); + // manager.registerAdapters(fMarkerAdapterFactory, IMarker.class); + // manager.registerAdapters(fEditorInputAdapterFactory, + // IEditorInput.class); + manager.registerAdapters(fResourceAdapterFactory, IResource.class); + // manager.registerAdapters(fLogicalPackageAdapterFactory, + // LogicalPackage.class); } - return fCombinedPreferenceStore; - } - - public synchronized IBufferFactory getBufferFactory() { - if (fBufferFactory == null) - fBufferFactory = new CustomBufferFactory(); - return fBufferFactory; - } - - /** - * Returns the registry of the extensions to the net.sourceforge.phpdt.ui.javaFoldingStructureProvider extension - * point. - * - * @return the registry of contributed IJavaFoldingStructureProvider - * @since 3.0 - */ - public synchronized JavaFoldingStructureProviderRegistry getFoldingStructureProviderRegistry() { - if (fFoldingStructureProviderRegistry == null) - fFoldingStructureProviderRegistry = new JavaFoldingStructureProviderRegistry(); - return fFoldingStructureProviderRegistry; - } - - /** - * Runs the given action as an atomic Java model operation. - *

                                                      - * After running a method that modifies java elements, registered listeners receive after-the-fact notification of what just - * transpired, in the form of a element changed event. This method allows clients to call a number of methods that modify java - * elements and only have element changed event notifications reported at the end of the entire batch. - *

                                                      - *

                                                      - * If this method is called outside the dynamic scope of another such call, this method runs the action and then reports a single - * element changed event describing the net effect of all changes done to java elements by the action. - *

                                                      - *

                                                      - * If this method is called in the dynamic scope of another such call, this method simply runs the action. - *

                                                      - * - * @param action - * the action to perform - * @param monitor - * a progress monitor, or null if progress reporting and cancellation are not desired - * @exception CoreException - * if the operation failed. - * @since 2.1 - */ - public static void run(IWorkspaceRunnable action, IProgressMonitor monitor) throws CoreException { - run(action, ResourcesPlugin.getWorkspace().getRoot(), monitor); - } - - /** - * Runs the given action as an atomic Java model operation. - *

                                                      - * After running a method that modifies java elements, registered listeners receive after-the-fact notification of what just - * transpired, in the form of a element changed event. This method allows clients to call a number of methods that modify java - * elements and only have element changed event notifications reported at the end of the entire batch. - *

                                                      - *

                                                      - * If this method is called outside the dynamic scope of another such call, this method runs the action and then reports a single - * element changed event describing the net effect of all changes done to java elements by the action. - *

                                                      - *

                                                      - * If this method is called in the dynamic scope of another such call, this method simply runs the action. - *

                                                      - *

                                                      - * The supplied scheduling rule is used to determine whether this operation can be run simultaneously with workspace changes in - * other threads. See IWorkspace.run(...) for more details. - *

                                                      - * - * @param action - * the action to perform - * @param rule - * the scheduling rule to use when running this operation, or null if there are no scheduling restrictions - * for this operation. - * @param monitor - * a progress monitor, or null if progress reporting and cancellation are not desired - * @exception CoreException - * if the operation failed. - * @since 3.0 - */ - public static void run(IWorkspaceRunnable action, ISchedulingRule rule, IProgressMonitor monitor) throws CoreException { - IWorkspace workspace = ResourcesPlugin.getWorkspace(); - if (workspace.isTreeLocked()) { - new BatchOperation(action).run(monitor); - } else { - // use IWorkspace.run(...) to ensure that a build will be done in - // autobuild mode - workspace.run(new BatchOperation(action), rule, IWorkspace.AVOID_UPDATE, monitor); + + private void unregisterAdapters() { + IAdapterManager manager = Platform.getAdapterManager(); + manager.unregisterAdapters(fJavaElementAdapterFactory); + // manager.unregisterAdapters(fMarkerAdapterFactory); + // manager.unregisterAdapters(fEditorInputAdapterFactory); + manager.unregisterAdapters(fResourceAdapterFactory); + // manager.unregisterAdapters(fLogicalPackageAdapterFactory); } - } - - /** - * Returns the template context type registry for the java plugin. - * - * @return the template context type registry for the java plugin - * @since 3.0 - */ - public ContextTypeRegistry getTemplateContextRegistry() { - if (fContextTypeRegistry == null) { - fContextTypeRegistry = new ContributionContextTypeRegistry(); - - fContextTypeRegistry.addContextType(new JavaContextType()); - fContextTypeRegistry.addContextType(new JavaDocContextType()); - fContextTypeRegistry.addContextType(new HTMLContextType()); + + /** + * Returns a combined preference store, this store is read-only. + * + * @return the combined preference store + * + * @since 3.0 + */ + public IPreferenceStore getCombinedPreferenceStore() { + if (fCombinedPreferenceStore == null) { + IPreferenceStore generalTextStore = EditorsUI.getPreferenceStore(); + fCombinedPreferenceStore = new ChainedPreferenceStore( + new IPreferenceStore[] { + getPreferenceStore(), + new PreferencesAdapter(PHPeclipsePlugin + .getDefault().getPluginPreferences()), + generalTextStore }); + } + return fCombinedPreferenceStore; + } + + public synchronized IBufferFactory getBufferFactory() { + if (fBufferFactory == null) + fBufferFactory = new CustomBufferFactory(); + return fBufferFactory; } - return fContextTypeRegistry; - } - - /** - * Returns the template store for the java editor templates. - * - * @return the template store for the java editor templates - * @since 3.0 - */ - public TemplateStore getTemplateStore() { - if (fTemplateStore == null) { - // boolean alreadyMigrated= getPreferenceStore().getBoolean(TEMPLATES_MIGRATION_KEY); - // if (alreadyMigrated) - fTemplateStore = new ContributionTemplateStore(getTemplateContextRegistry(), getPreferenceStore(), TEMPLATES_KEY); - // else { - // fTemplateStore= new CompatibilityTemplateStore(getTemplateContextRegistry(), getPreferenceStore(), TEMPLATES_KEY, - // Templates.getInstance()); - // getPreferenceStore().setValue(TEMPLATES_MIGRATION_KEY, true); - // } - - try { - fTemplateStore.load(); - } catch (IOException e) { - log(e); - } + /** + * Returns the registry of the extensions to the + * net.sourceforge.phpdt.ui.javaFoldingStructureProvider + * extension point. + * + * @return the registry of contributed + * IJavaFoldingStructureProvider + * @since 3.0 + */ + public synchronized JavaFoldingStructureProviderRegistry getFoldingStructureProviderRegistry() { + if (fFoldingStructureProviderRegistry == null) + fFoldingStructureProviderRegistry = new JavaFoldingStructureProviderRegistry(); + return fFoldingStructureProviderRegistry; + } + + /** + * Runs the given action as an atomic Java model operation. + *

                                                      + * After running a method that modifies java elements, registered listeners + * receive after-the-fact notification of what just transpired, in the form + * of a element changed event. This method allows clients to call a number + * of methods that modify java elements and only have element changed event + * notifications reported at the end of the entire batch. + *

                                                      + *

                                                      + * If this method is called outside the dynamic scope of another such call, + * this method runs the action and then reports a single element changed + * event describing the net effect of all changes done to java elements by + * the action. + *

                                                      + *

                                                      + * If this method is called in the dynamic scope of another such call, this + * method simply runs the action. + *

                                                      + * + * @param action + * the action to perform + * @param monitor + * a progress monitor, or null if progress + * reporting and cancellation are not desired + * @exception CoreException + * if the operation failed. + * @since 2.1 + */ + public static void run(IWorkspaceRunnable action, IProgressMonitor monitor) + throws CoreException { + run(action, ResourcesPlugin.getWorkspace().getRoot(), monitor); } - return fTemplateStore; - } + /** + * Runs the given action as an atomic Java model operation. + *

                                                      + * After running a method that modifies java elements, registered listeners + * receive after-the-fact notification of what just transpired, in the form + * of a element changed event. This method allows clients to call a number + * of methods that modify java elements and only have element changed event + * notifications reported at the end of the entire batch. + *

                                                      + *

                                                      + * If this method is called outside the dynamic scope of another such call, + * this method runs the action and then reports a single element changed + * event describing the net effect of all changes done to java elements by + * the action. + *

                                                      + *

                                                      + * If this method is called in the dynamic scope of another such call, this + * method simply runs the action. + *

                                                      + *

                                                      + * The supplied scheduling rule is used to determine whether this operation + * can be run simultaneously with workspace changes in other threads. See + * IWorkspace.run(...) for more details. + *

                                                      + * + * @param action + * the action to perform + * @param rule + * the scheduling rule to use when running this operation, or + * null if there are no scheduling restrictions + * for this operation. + * @param monitor + * a progress monitor, or null if progress + * reporting and cancellation are not desired + * @exception CoreException + * if the operation failed. + * @since 3.0 + */ + public static void run(IWorkspaceRunnable action, ISchedulingRule rule, + IProgressMonitor monitor) throws CoreException { + IWorkspace workspace = ResourcesPlugin.getWorkspace(); + if (workspace.isTreeLocked()) { + new BatchOperation(action).run(monitor); + } else { + // use IWorkspace.run(...) to ensure that a build will be done in + // autobuild mode + workspace.run(new BatchOperation(action), rule, + IWorkspace.AVOID_UPDATE, monitor); + } + } + + /** + * Returns the template context type registry for the java plugin. + * + * @return the template context type registry for the java plugin + * @since 3.0 + */ + public ContextTypeRegistry getTemplateContextRegistry() { + if (fContextTypeRegistry == null) { + fContextTypeRegistry = new ContributionContextTypeRegistry(); + + fContextTypeRegistry.addContextType(new JavaContextType()); + fContextTypeRegistry.addContextType(new JavaDocContextType()); + fContextTypeRegistry.addContextType(new HTMLContextType()); + } - /** - * Returns the template context type registry for the code generation templates. - * - * @return the template context type registry for the code generation templates - * @since 3.0 - */ - public ContextTypeRegistry getCodeTemplateContextRegistry() { - if (fCodeTemplateContextTypeRegistry == null) { - fCodeTemplateContextTypeRegistry = new ContributionContextTypeRegistry(); + return fContextTypeRegistry; + } - CodeTemplateContextType.registerContextTypes(fCodeTemplateContextTypeRegistry); + /** + * Returns the template store for the java editor templates. + * + * @return the template store for the java editor templates + * @since 3.0 + */ + public TemplateStore getTemplateStore() { + if (fTemplateStore == null) { + // boolean alreadyMigrated= + // getPreferenceStore().getBoolean(TEMPLATES_MIGRATION_KEY); + // if (alreadyMigrated) + fTemplateStore = new ContributionTemplateStore( + getTemplateContextRegistry(), getPreferenceStore(), + TEMPLATES_KEY); + // else { + // fTemplateStore= new + // CompatibilityTemplateStore(getTemplateContextRegistry(), + // getPreferenceStore(), TEMPLATES_KEY, + // Templates.getInstance()); + // getPreferenceStore().setValue(TEMPLATES_MIGRATION_KEY, true); + // } + + try { + fTemplateStore.load(); + } catch (IOException e) { + log(e); + } + } + + return fTemplateStore; } - return fCodeTemplateContextTypeRegistry; - } - - /** - * Returns the template store for the code generation templates. - * - * @return the template store for the code generation templates - * @since 3.0 - */ - public TemplateStore getCodeTemplateStore() { - if (fCodeTemplateStore == null) { - // boolean alreadyMigrated= getPreferenceStore().getBoolean(CODE_TEMPLATES_MIGRATION_KEY); - // if (alreadyMigrated) - fCodeTemplateStore = new ContributionTemplateStore(getCodeTemplateContextRegistry(), getPreferenceStore(), CODE_TEMPLATES_KEY); - // else { - // fCodeTemplateStore= new CompatibilityTemplateStore(getCodeTemplateContextRegistry(), getPreferenceStore(), - // CODE_TEMPLATES_KEY, CodeTemplates.getInstance()); - // getPreferenceStore().setValue(CODE_TEMPLATES_MIGRATION_KEY, true); - // } - - try { - fCodeTemplateStore.load(); - } catch (IOException e) { - log(e); - } - - // compatibility / bug fixing code for duplicated templates - // TODO remove for 3.0 - // CompatibilityTemplateStore.pruneDuplicates(fCodeTemplateStore, true); + /** + * Returns the template context type registry for the code generation + * templates. + * + * @return the template context type registry for the code generation + * templates + * @since 3.0 + */ + public ContextTypeRegistry getCodeTemplateContextRegistry() { + if (fCodeTemplateContextTypeRegistry == null) { + fCodeTemplateContextTypeRegistry = new ContributionContextTypeRegistry(); + + CodeTemplateContextType + .registerContextTypes(fCodeTemplateContextTypeRegistry); + } + + return fCodeTemplateContextTypeRegistry; } - return fCodeTemplateStore; - } + /** + * Returns the template store for the code generation templates. + * + * @return the template store for the code generation templates + * @since 3.0 + */ + public TemplateStore getCodeTemplateStore() { + if (fCodeTemplateStore == null) { + // boolean alreadyMigrated= + // getPreferenceStore().getBoolean(CODE_TEMPLATES_MIGRATION_KEY); + // if (alreadyMigrated) + fCodeTemplateStore = new ContributionTemplateStore( + getCodeTemplateContextRegistry(), getPreferenceStore(), + CODE_TEMPLATES_KEY); + // else { + // fCodeTemplateStore= new + // CompatibilityTemplateStore(getCodeTemplateContextRegistry(), + // getPreferenceStore(), + // CODE_TEMPLATES_KEY, CodeTemplates.getInstance()); + // getPreferenceStore().setValue(CODE_TEMPLATES_MIGRATION_KEY, + // true); + // } + + try { + fCodeTemplateStore.load(); + } catch (IOException e) { + log(e); + } + + // compatibility / bug fixing code for duplicated templates + // TODO remove for 3.0 + // CompatibilityTemplateStore.pruneDuplicates(fCodeTemplateStore, + // true); + } + + return fCodeTemplateStore; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/IncludesScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/IncludesScanner.java index a556aef..bb1c88f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/IncludesScanner.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/IncludesScanner.java @@ -21,148 +21,167 @@ import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.Path; import org.eclipse.ui.IFileEditorInput; - public class IncludesScanner implements ITerminalSymbols { -// private final PHPOpenAllIncludesEditorAction fOpenAllIncludesAction; - private IProject fProject; - private IFileEditorInput fEditorInput; - private HashSet fSet; - public IncludesScanner(IProject project, IFileEditorInput editorInput) { - fProject = project; -// fOpenAllIncludesAction = action; - fEditorInput = editorInput; - fSet = new HashSet(); - } - /** - * Add the information for a given IFile resource - * - */ - public void addFile(IFile fileToParse) { - - try { - if (fileToParse.exists()) { - addInputStream(new BufferedInputStream(fileToParse.getContents()), fileToParse.getProjectRelativePath().toString()); - } - } catch (CoreException e1) { - e1.printStackTrace(); - } - } - - private void addInputStream(InputStream stream, String filePath) throws CoreException { - try { - if (fSet.add(filePath)) { // new entry in set - parseIdentifiers(Util.getInputStreamAsCharArray(stream, -1, null)); - } - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - if (stream != null) { - stream.close(); - } - } catch (IOException e) { - } - } - } - - /** - * Get the next token from input - */ - private int getNextToken(Scanner scanner) { - int token; - try { - token = scanner.getNextToken(); - if (Scanner.DEBUG) { - int currentEndPosition = scanner.getCurrentTokenEndPosition(); - int currentStartPosition = scanner.getCurrentTokenStartPosition(); - System.out.print(currentStartPosition + "," + currentEndPosition + ": "); - System.out.println(scanner.toStringAction(token)); - } - return token; - } catch (InvalidInputException e) { - } - return TokenNameERROR; - } - - private void parseIdentifiers(char[] charArray) { - char[] ident; - IFile file; - String identifier; - int counter = 0; - - Scanner scanner = new Scanner(false, false, false, false, true, null, null, true /*taskCaseSensitive*/); - scanner.setSource(charArray); - scanner.setPHPMode(false); - int token = getNextToken(scanner); - try { - while (token != TokenNameEOF) { // && fToken != TokenNameERROR) { - if (token == TokenNameinclude || token == TokenNameinclude_once || token == TokenNamerequire - || token == TokenNamerequire_once) { - while (token != TokenNameEOF && token != TokenNameERROR && token != TokenNameSEMICOLON && token != TokenNameRPAREN - && token != TokenNameLBRACE && token != TokenNameRBRACE) { - token = getNextToken(scanner); - if (token == TokenNameStringDoubleQuote || token == TokenNameStringSingleQuote) { - char[] includeName = scanner.getCurrentStringLiteralSource(); - try { - file = getIncludeFile(new String(includeName)); - addFile(file); - } catch (Exception e) { - // ignore - } - break; - } - } - } - token = getNextToken(scanner); - } - } catch (SyntaxError e) { - // e.printStackTrace(); - } - } - - private IContainer getWorkingLocation(IFileEditorInput editorInput) { - if (editorInput == null || editorInput.getFile() == null) { - return null; - } - return editorInput.getFile().getParent(); - } - public IFile getIncludeFile(String relativeFilename) { - IContainer container = getWorkingLocation(fEditorInput); - String fullPath = fProject.getLocation().toString(); - IFile file = null; - if (relativeFilename.startsWith("../")) { - Path path = new Path(relativeFilename); - file = container.getFile(path); - return file; - } - int index = relativeFilename.lastIndexOf('/'); - - if (index >= 0) { - Path path = new Path(relativeFilename); - file = fProject.getFile(path); - if (file.exists()) { - return file; - } - } - Path path = new Path(relativeFilename); - file = container.getFile(path); - - return file; - } - /** - * Returns a list of includes - * @return the determined list of includes - */ - public List getList() { - ArrayList list = new ArrayList(); - list.addAll(fSet); - return list; - } - - /** - * @return Returns the set. - */ - public Set getSet() { - return fSet; - } + // private final PHPOpenAllIncludesEditorAction fOpenAllIncludesAction; + private IProject fProject; + + private IFileEditorInput fEditorInput; + + private HashSet fSet; + + public IncludesScanner(IProject project, IFileEditorInput editorInput) { + fProject = project; + // fOpenAllIncludesAction = action; + fEditorInput = editorInput; + fSet = new HashSet(); + } + + /** + * Add the information for a given IFile resource + * + */ + public void addFile(IFile fileToParse) { + + try { + if (fileToParse.exists()) { + addInputStream(new BufferedInputStream(fileToParse + .getContents()), fileToParse.getProjectRelativePath() + .toString()); + } + } catch (CoreException e1) { + e1.printStackTrace(); + } + } + + private void addInputStream(InputStream stream, String filePath) + throws CoreException { + try { + if (fSet.add(filePath)) { // new entry in set + parseIdentifiers(Util.getInputStreamAsCharArray(stream, -1, + null)); + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (stream != null) { + stream.close(); + } + } catch (IOException e) { + } + } + } + + /** + * Get the next token from input + */ + private int getNextToken(Scanner scanner) { + int token; + try { + token = scanner.getNextToken(); + if (Scanner.DEBUG) { + int currentEndPosition = scanner.getCurrentTokenEndPosition(); + int currentStartPosition = scanner + .getCurrentTokenStartPosition(); + System.out.print(currentStartPosition + "," + + currentEndPosition + ": "); + System.out.println(scanner.toStringAction(token)); + } + return token; + } catch (InvalidInputException e) { + } + return TokenNameERROR; + } + + private void parseIdentifiers(char[] charArray) { + char[] ident; + IFile file; + String identifier; + int counter = 0; + + Scanner scanner = new Scanner(false, false, false, false, true, null, + null, true /* taskCaseSensitive */); + scanner.setSource(charArray); + scanner.setPHPMode(false); + int token = getNextToken(scanner); + try { + while (token != TokenNameEOF) { // && fToken != TokenNameERROR) { + if (token == TokenNameinclude || token == TokenNameinclude_once + || token == TokenNamerequire + || token == TokenNamerequire_once) { + while (token != TokenNameEOF && token != TokenNameERROR + && token != TokenNameSEMICOLON + && token != TokenNameRPAREN + && token != TokenNameLBRACE + && token != TokenNameRBRACE) { + token = getNextToken(scanner); + if (token == TokenNameStringDoubleQuote + || token == TokenNameStringSingleQuote) { + char[] includeName = scanner + .getCurrentStringLiteralSource(); + try { + file = getIncludeFile(new String(includeName)); + addFile(file); + } catch (Exception e) { + // ignore + } + break; + } + } + } + token = getNextToken(scanner); + } + } catch (SyntaxError e) { + // e.printStackTrace(); + } + } + + private IContainer getWorkingLocation(IFileEditorInput editorInput) { + if (editorInput == null || editorInput.getFile() == null) { + return null; + } + return editorInput.getFile().getParent(); + } + + public IFile getIncludeFile(String relativeFilename) { + IContainer container = getWorkingLocation(fEditorInput); + String fullPath = fProject.getLocation().toString(); + IFile file = null; + if (relativeFilename.startsWith("../")) { + Path path = new Path(relativeFilename); + file = container.getFile(path); + return file; + } + int index = relativeFilename.lastIndexOf('/'); + + if (index >= 0) { + Path path = new Path(relativeFilename); + file = fProject.getFile(path); + if (file.exists()) { + return file; + } + } + Path path = new Path(relativeFilename); + file = container.getFile(path); + + return file; + } + + /** + * Returns a list of includes + * + * @return the determined list of includes + */ + public List getList() { + ArrayList list = new ArrayList(); + list.addAll(fSet); + return list; + } + + /** + * @return Returns the set. + */ + public Set getSet() { + return fSet; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/OpenDeclarationEditorAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/OpenDeclarationEditorAction.java index 37f7d5d..6d4e18b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/OpenDeclarationEditorAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/OpenDeclarationEditorAction.java @@ -12,6 +12,7 @@ import java.util.List; import java.util.Set; import net.sourceforge.phpdt.internal.ui.util.PHPFileUtil; +import net.sourceforge.phpdt.internal.ui.viewsupport.ListContentProvider; import net.sourceforge.phpeclipse.PHPeclipsePlugin; import net.sourceforge.phpeclipse.builder.IdentifierIndexManager; import net.sourceforge.phpeclipse.builder.PHPIdentifierLocation; @@ -27,237 +28,277 @@ import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.window.Window; -import net.sourceforge.phpdt.internal.ui.viewsupport.ListContentProvider; import org.eclipse.swt.graphics.Point; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.dialogs.ListSelectionDialog; public class OpenDeclarationEditorAction { - private PHPEditor fEditor; + private PHPEditor fEditor; + + private IProject fProject; - private IProject fProject; + private boolean isIncludeString; - private boolean isIncludeString; + public OpenDeclarationEditorAction(PHPEditor editor) { + fEditor = editor; + fProject = null; + isIncludeString = false; + } - public OpenDeclarationEditorAction(PHPEditor editor) { - fEditor = editor; - fProject = null; - isIncludeString = false; - } + /** + * @param selection + */ + protected void openSelectedElement(ITextSelection selection) { + IDocument doc = fEditor.getDocumentProvider().getDocument( + fEditor.getEditorInput()); + int pos = selection.getOffset(); + openSelectedPosition(doc, pos); + } - /** - * @param selection - */ - protected void openSelectedElement(ITextSelection selection) { - IDocument doc = fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput()); - int pos = selection.getOffset(); - openSelectedPosition(doc, pos); - } + protected void openSelectedPosition(IDocument doc, int position) { + IFile f = ((IFileEditorInput) fEditor.getEditorInput()).getFile(); + fProject = f.getProject(); + // System.out.println(selection.getText()); + String identifierOrInclude = getIdentifierOrInclude(doc, position); + // System.out.println(word); + if (identifierOrInclude != null && !identifierOrInclude.equals("")) { + if (isIncludeString) { + openIncludeFile(identifierOrInclude); + } else { + openIdentifierDeclaration(f, identifierOrInclude); + } + } + } - protected void openSelectedPosition(IDocument doc, int position) { - IFile f = ((IFileEditorInput) fEditor.getEditorInput()).getFile(); - fProject = f.getProject(); - // System.out.println(selection.getText()); - String identifierOrInclude = getIdentifierOrInclude(doc, position); - // System.out.println(word); - if (identifierOrInclude != null && !identifierOrInclude.equals("")) { - if (isIncludeString) { - openIncludeFile(identifierOrInclude); - } else { - openIdentifierDeclaration(f, identifierOrInclude); - } - } - } - - /** - * @param filename - */ - private void openIncludeFile(String filename) { - if (filename != null && !filename.equals("")) { - try { - IFile currentFile = ((IFileEditorInput) fEditor.getEditorInput()).getFile(); - IPath path = PHPFileUtil.determineFilePath(filename, currentFile, fProject); - if (path != null) { - IFile file = PHPFileUtil.createFile(path, fProject); - if (file != null && file.exists()) { - PHPeclipsePlugin.getDefault().openFileInTextEditor(file.getLocation().toString()); - return; - } - } - } catch (Exception e) { - // ignore - } + /** + * @param filename + */ + private void openIncludeFile(String filename) { + if (filename != null && !filename.equals("")) { + try { + IFile currentFile = ((IFileEditorInput) fEditor + .getEditorInput()).getFile(); + IPath path = PHPFileUtil.determineFilePath(filename, + currentFile, fProject); + if (path != null) { + IFile file = PHPFileUtil.createFile(path, fProject); + if (file != null && file.exists()) { + PHPeclipsePlugin.getDefault().openFileInTextEditor( + file.getLocation().toString()); + return; + } + } + } catch (Exception e) { + // ignore + } - try { + try { - IdentifierIndexManager indexManager = PHPeclipsePlugin.getDefault().getIndexManager(fProject); - // filename = StringUtil.replaceRegExChars(filename); - List list = indexManager.getFileList(filename); - if (list != null && list.size() > 0) { - //String workspaceLocation = PHPeclipsePlugin.getWorkspace().getRoot().getLocation().toString(); - String workspaceLocation = fProject.getLocation().toString() + java.io.File.separatorChar; + IdentifierIndexManager indexManager = PHPeclipsePlugin + .getDefault().getIndexManager(fProject); + // filename = StringUtil.replaceRegExChars(filename); + List list = indexManager.getFileList(filename); + if (list != null && list.size() > 0) { + // String workspaceLocation = + // PHPeclipsePlugin.getWorkspace().getRoot().getLocation().toString(); + String workspaceLocation = fProject.getLocation() + .toString() + + java.io.File.separatorChar; - ListSelectionDialog listSelectionDialog = new ListSelectionDialog(PHPeclipsePlugin.getDefault().getWorkbench() - .getActiveWorkbenchWindow().getShell(), list, new ListContentProvider(), new LabelProvider(), - "Select the includes to open."); - listSelectionDialog.setTitle("Multiple includes found"); - if (listSelectionDialog.open() == Window.OK) { - Object[] locations = listSelectionDialog.getResult(); - if (locations != null) { - try { - for (int i = 0; i < locations.length; i++) { - // PHPIdentifierLocation location = (PHPIdentifierLocation) - // locations[i]; - String openFilename = workspaceLocation + ((String) locations[i]); - PHPeclipsePlugin.getDefault().openFileInTextEditor(openFilename); - } - } catch (CoreException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } + ListSelectionDialog listSelectionDialog = new ListSelectionDialog( + PHPeclipsePlugin.getDefault().getWorkbench() + .getActiveWorkbenchWindow().getShell(), + list, new ListContentProvider(), + new LabelProvider(), "Select the includes to open."); + listSelectionDialog.setTitle("Multiple includes found"); + if (listSelectionDialog.open() == Window.OK) { + Object[] locations = listSelectionDialog.getResult(); + if (locations != null) { + try { + for (int i = 0; i < locations.length; i++) { + // PHPIdentifierLocation location = + // (PHPIdentifierLocation) + // locations[i]; + String openFilename = workspaceLocation + + ((String) locations[i]); + PHPeclipsePlugin.getDefault() + .openFileInTextEditor(openFilename); + } + } catch (CoreException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } - } - } catch (Exception e) { - } + } + } catch (Exception e) { + } - } - return; - } + } + return; + } - /** - * @param f - * @param identiifer - */ - private void openIdentifierDeclaration(IFile f, String identiifer) { - if (identiifer != null && !identiifer.equals("")) { - IdentifierIndexManager indexManager = PHPeclipsePlugin.getDefault().getIndexManager(fProject); - List locationsList = indexManager.getLocations(identiifer); - if (locationsList != null && locationsList.size() > 0) { + /** + * @param f + * @param identiifer + */ + private void openIdentifierDeclaration(IFile f, String identiifer) { + if (identiifer != null && !identiifer.equals("")) { + IdentifierIndexManager indexManager = PHPeclipsePlugin.getDefault() + .getIndexManager(fProject); + List locationsList = indexManager.getLocations(identiifer); + if (locationsList != null && locationsList.size() > 0) { - // String workspaceLocation = PHPeclipsePlugin.getWorkspace().getRoot() - // .getLocation().toString(); + // String workspaceLocation = + // PHPeclipsePlugin.getWorkspace().getRoot() + // .getLocation().toString(); - String workspaceLocation = fProject.getLocation().toString() + java.io.File.separatorChar; - // TODO show all entries of the list in a dialog box - // at the moment always the first entry will be opened - if (locationsList.size() > 1) { - // determine all includes: - IncludesScanner includesScanner = new IncludesScanner(fProject, (IFileEditorInput) fEditor.getEditorInput()); - includesScanner.addFile(f); - Set exactIncludeSet = includesScanner.getSet(); + String workspaceLocation = fProject.getLocation().toString() + + java.io.File.separatorChar; + // TODO show all entries of the list in a dialog box + // at the moment always the first entry will be opened + if (locationsList.size() > 1) { + // determine all includes: + IncludesScanner includesScanner = new IncludesScanner( + fProject, (IFileEditorInput) fEditor + .getEditorInput()); + includesScanner.addFile(f); + Set exactIncludeSet = includesScanner.getSet(); - PHPIdentifierLocation includeName; - for (int i = 0; i < locationsList.size(); i++) { - includeName = (PHPIdentifierLocation) locationsList.get(i); - if (exactIncludeSet.contains(includeName.getFilename())) { - includeName.setMatch(PHPIdentifierLocation.EXACT_MATCH); - } else { - includeName.setMatch(PHPIdentifierLocation.UNDEFINED_MATCH); - } - } - Collections.sort(locationsList); + PHPIdentifierLocation includeName; + for (int i = 0; i < locationsList.size(); i++) { + includeName = (PHPIdentifierLocation) locationsList + .get(i); + if (exactIncludeSet.contains(includeName.getFilename())) { + includeName + .setMatch(PHPIdentifierLocation.EXACT_MATCH); + } else { + includeName + .setMatch(PHPIdentifierLocation.UNDEFINED_MATCH); + } + } + Collections.sort(locationsList); - ListSelectionDialog listSelectionDialog = new ListSelectionDialog(PHPeclipsePlugin.getDefault().getWorkbench() - .getActiveWorkbenchWindow().getShell(), locationsList, new ListContentProvider(), new LabelProvider(), - "Select the resources to open."); - listSelectionDialog.setTitle("Multiple declarations found"); - if (listSelectionDialog.open() == Window.OK) { - Object[] locations = listSelectionDialog.getResult(); - if (locations != null) { - try { - for (int i = 0; i < locations.length; i++) { - PHPIdentifierLocation location = (PHPIdentifierLocation) locations[i]; - String filename = workspaceLocation + location.getFilename(); - // System.out.println(filename); - if (location.getOffset() >= 0) { - PHPeclipsePlugin.getDefault().openFileAndGotoOffset(filename, location.getOffset(), identiifer.length()); - } else { - PHPeclipsePlugin.getDefault().openFileAndFindString(filename, identiifer); - } - } - } catch (CoreException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - } else { - try { - PHPIdentifierLocation location = (PHPIdentifierLocation) locationsList.get(0); - String filename = workspaceLocation + location.getFilename(); - // System.out.println(filename); - if (location.getOffset() >= 0) { - PHPeclipsePlugin.getDefault().openFileAndGotoOffset(filename, location.getOffset(), identiifer.length()); - } else { - PHPeclipsePlugin.getDefault().openFileAndFindString(filename, identiifer); - } - } catch (CoreException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - } - } + ListSelectionDialog listSelectionDialog = new ListSelectionDialog( + PHPeclipsePlugin.getDefault().getWorkbench() + .getActiveWorkbenchWindow().getShell(), + locationsList, new ListContentProvider(), + new LabelProvider(), + "Select the resources to open."); + listSelectionDialog.setTitle("Multiple declarations found"); + if (listSelectionDialog.open() == Window.OK) { + Object[] locations = listSelectionDialog.getResult(); + if (locations != null) { + try { + for (int i = 0; i < locations.length; i++) { + PHPIdentifierLocation location = (PHPIdentifierLocation) locations[i]; + String filename = workspaceLocation + + location.getFilename(); + // System.out.println(filename); + if (location.getOffset() >= 0) { + PHPeclipsePlugin.getDefault() + .openFileAndGotoOffset( + filename, + location.getOffset(), + identiifer.length()); + } else { + PHPeclipsePlugin.getDefault() + .openFileAndFindString( + filename, identiifer); + } + } + } catch (CoreException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + } else { + try { + PHPIdentifierLocation location = (PHPIdentifierLocation) locationsList + .get(0); + String filename = workspaceLocation + + location.getFilename(); + // System.out.println(filename); + if (location.getOffset() >= 0) { + PHPeclipsePlugin.getDefault() + .openFileAndGotoOffset(filename, + location.getOffset(), + identiifer.length()); + } else { + PHPeclipsePlugin + .getDefault() + .openFileAndFindString(filename, identiifer); + } + } catch (CoreException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + } + } - private String getIdentifierOrInclude(IDocument doc, int pos) { - // private String getPHPIncludeText(IDocument doc, int pos) { - Point word = null; - int start = -1; - int end = -1; - isIncludeString = false; - try { - // try to find an include string - int position = pos; - char character = ' '; + private String getIdentifierOrInclude(IDocument doc, int pos) { + // private String getPHPIncludeText(IDocument doc, int pos) { + Point word = null; + int start = -1; + int end = -1; + isIncludeString = false; + try { + // try to find an include string + int position = pos; + char character = ' '; - while (position >= 0) { - character = doc.getChar(position); - if ((character == '\"') || (character == '\'') || (character == '\r') || (character == '\n')) - break; - --position; - } - if ((character == '\"') || (character == '\'')) { - start = position; + while (position >= 0) { + character = doc.getChar(position); + if ((character == '\"') || (character == '\'') + || (character == '\r') || (character == '\n')) + break; + --position; + } + if ((character == '\"') || (character == '\'')) { + start = position; - position = pos; - int length = doc.getLength(); - character = ' '; - while (position < length) { - character = doc.getChar(position); - if ((character == '\"') || (character == '\'') || (character == '\r') || (character == '\n')) - break; - ++position; - } - if ((character == '\"') || (character == '\'')) { - start++; - end = position; + position = pos; + int length = doc.getLength(); + character = ' '; + while (position < length) { + character = doc.getChar(position); + if ((character == '\"') || (character == '\'') + || (character == '\r') || (character == '\n')) + break; + ++position; + } + if ((character == '\"') || (character == '\'')) { + start++; + end = position; - if (end > start) { - word = new Point(start, end - start); // include name found - isIncludeString = true; - } - } - } + if (end > start) { + word = new Point(start, end - start); // include name + // found + isIncludeString = true; + } + } + } - // try to find an identifier - if (word == null) { - word = PHPWordExtractor.findWord(doc, pos); // identifier found - isIncludeString = false; - } - } catch (BadLocationException x) { - } + // try to find an identifier + if (word == null) { + word = PHPWordExtractor.findWord(doc, pos); // identifier found + isIncludeString = false; + } + } catch (BadLocationException x) { + } - if (word != null) { - try { - return doc.get(word.x, word.y); - } catch (BadLocationException e) { - } - } - return ""; - } + if (word != null) { + try { + return doc.get(word.x, word.y); + } catch (BadLocationException e) { + } + } + return ""; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPActionMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPActionMessages.java index 352a5dd..7851c84 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPActionMessages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPActionMessages.java @@ -4,15 +4,15 @@ */ package net.sourceforge.phpeclipse.actions; - import java.util.MissingResourceException; import java.util.ResourceBundle; public class PHPActionMessages { - private static final String RESOURCE_BUNDLE= "net.sourceforge.phpeclipse.actions.PHPActionMessages";//$NON-NLS-1$ + private static final String RESOURCE_BUNDLE = "net.sourceforge.phpeclipse.actions.PHPActionMessages";//$NON-NLS-1$ - private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); + private static ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); private PHPActionMessages() { } @@ -24,7 +24,7 @@ public class PHPActionMessages { return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$ } } - + public static ResourceBundle getResourceBundle() { return fgResourceBundle; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPEclipseShowAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPEclipseShowAction.java index d6881ed..75f1995 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPEclipseShowAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPEclipseShowAction.java @@ -32,105 +32,128 @@ import org.eclipse.ui.IActionDelegate; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; - public class PHPEclipseShowAction implements IObjectActionDelegate { - private IWorkbenchPart workbenchPart; + private IWorkbenchPart workbenchPart; - /** - * Constructor for Action1. - */ - public PHPEclipseShowAction() { - super(); - } + /** + * Constructor for Action1. + */ + public PHPEclipseShowAction() { + super(); + } - /** - * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart) - */ - public void setActivePart(IAction action, IWorkbenchPart targetPart) { - workbenchPart = targetPart; - } + /** + * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart) + */ + public void setActivePart(IAction action, IWorkbenchPart targetPart) { + workbenchPart = targetPart; + } - public void run(IAction action) { - ISelectionProvider selectionProvider = null; - selectionProvider = workbenchPart.getSite().getSelectionProvider(); - StructuredSelection selection = null; - selection = (StructuredSelection) selectionProvider.getSelection(); - IPreferenceStore store = PHPeclipsePlugin.getDefault().getPreferenceStore(); - Shell shell = null; - Iterator iterator = null; - iterator = selection.iterator(); - while (iterator.hasNext()) { - // obj => selected object in the view - Object obj = iterator.next(); - // is it a resource - if (obj instanceof IResource) { - IResource resource = (IResource) obj; - // check if it's a file resource - switch (resource.getType()) { - case IResource.FILE: - // single file: - IFile previewFile = (IFile) resource; - String extension = previewFile.getFileExtension().toLowerCase(); - boolean bringToTopPreview = ProjectPrefUtil.getPreviewBooleanValue(previewFile, IPreferenceConstants.PHP_BRING_TO_TOP_PREVIEW_DEFAULT); -// boolean showHTMLFilesLocal = ProjectPrefUtil.getPreviewBooleanValue(previewFile, IPreferenceConstants.PHP_SHOW_HTML_FILES_LOCAL); -// boolean showXMLFilesLocal = ProjectPrefUtil.getPreviewBooleanValue(previewFile, IPreferenceConstants.PHP_SHOW_XML_FILES_LOCAL); - boolean isHTMLFileName = "html".equals(extension) || "htm".equals(extension) || "xhtml".equals(extension); - boolean isXMLFileName = "xml".equals(extension) || "xsd".equals(extension) || "dtd".equals(extension); + public void run(IAction action) { + ISelectionProvider selectionProvider = null; + selectionProvider = workbenchPart.getSite().getSelectionProvider(); + StructuredSelection selection = null; + selection = (StructuredSelection) selectionProvider.getSelection(); + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + Shell shell = null; + Iterator iterator = null; + iterator = selection.iterator(); + while (iterator.hasNext()) { + // obj => selected object in the view + Object obj = iterator.next(); + // is it a resource + if (obj instanceof IResource) { + IResource resource = (IResource) obj; + // check if it's a file resource + switch (resource.getType()) { + case IResource.FILE: + // single file: + IFile previewFile = (IFile) resource; + String extension = previewFile.getFileExtension() + .toLowerCase(); + boolean bringToTopPreview = ProjectPrefUtil + .getPreviewBooleanValue( + previewFile, + IPreferenceConstants.PHP_BRING_TO_TOP_PREVIEW_DEFAULT); + // boolean showHTMLFilesLocal = + // ProjectPrefUtil.getPreviewBooleanValue(previewFile, + // IPreferenceConstants.PHP_SHOW_HTML_FILES_LOCAL); + // boolean showXMLFilesLocal = + // ProjectPrefUtil.getPreviewBooleanValue(previewFile, + // IPreferenceConstants.PHP_SHOW_XML_FILES_LOCAL); + boolean isHTMLFileName = "html".equals(extension) + || "htm".equals(extension) + || "xhtml".equals(extension); + boolean isXMLFileName = "xml".equals(extension) + || "xsd".equals(extension) + || "dtd".equals(extension); - String localhostURL; -// if (showHTMLFilesLocal && isHTMLFileName) { -// localhostURL = "file://"+previewFile.getLocation().toString(); -// } else if (showXMLFilesLocal && isXMLFileName) { -// localhostURL = "file://"+previewFile.getLocation().toString(); -// } else - if ((localhostURL = ShowExternalPreviewAction.getLocalhostURL(store, previewFile)) == null) { - MessageDialog.openInformation(shell, "Couldn't create localhost URL", - "Please configure your localhost and documentRoot"); - return; - } + String localhostURL; + // if (showHTMLFilesLocal && isHTMLFileName) { + // localhostURL = + // "file://"+previewFile.getLocation().toString(); + // } else if (showXMLFilesLocal && isXMLFileName) { + // localhostURL = + // "file://"+previewFile.getLocation().toString(); + // } else + if ((localhostURL = ShowExternalPreviewAction + .getLocalhostURL(store, previewFile)) == null) { + MessageDialog + .openInformation(shell, + "Couldn't create localhost URL", + "Please configure your localhost and documentRoot"); + return; + } - try { -// if (store.getBoolean(PHPeclipsePlugin.USE_EXTERNAL_BROWSER_PREF)) { -// String[] arguments = { localhostURL }; -// MessageFormat form = new MessageFormat(store.getString(PHPeclipsePlugin.EXTERNAL_BROWSER_PREF)); -// Runtime runtime = Runtime.getRuntime(); -// String command = form.format(arguments); -// // console.write("External Browser command: " + command + "\n"); -// runtime.exec(command); -// } else { - open(new URL(localhostURL), shell, localhostURL); -// } - } catch (MalformedURLException e) { - MessageDialog.openInformation(shell, "MalformedURLException: ", e.toString()); - } - } - } - } - } + try { + // if + // (store.getBoolean(PHPeclipsePlugin.USE_EXTERNAL_BROWSER_PREF)) + // { + // String[] arguments = { localhostURL }; + // MessageFormat form = new + // MessageFormat(store.getString(PHPeclipsePlugin.EXTERNAL_BROWSER_PREF)); + // Runtime runtime = Runtime.getRuntime(); + // String command = form.format(arguments); + // // console.write("External Browser command: " + + // command + "\n"); + // runtime.exec(command); + // } else { + open(new URL(localhostURL), shell, localhostURL); + // } + } catch (MalformedURLException e) { + MessageDialog.openInformation(shell, + "MalformedURLException: ", e.toString()); + } + } + } + } + } - /** - * @see IActionDelegate#selectionChanged(IAction, ISelection) - */ - public void selectionChanged(IAction action, ISelection selection) { - } + /** + * @see IActionDelegate#selectionChanged(IAction, ISelection) + */ + public void selectionChanged(IAction action, ISelection selection) { + } - public static void open(final URL url, final Shell shell, final String dialogTitle) { -// if (WebBrowserUtil.canUseInternalWebBrowser()) { -// IWorkbenchPage page = PHPeclipsePlugin.getActivePage(); -// try { -// IViewPart part = page.findView(BrowserView.ID_BROWSER); -// if (part == null) { -// part = page.showView(BrowserView.ID_BROWSER); -// } else { -// page.bringToTop(part); -// } -// ((BrowserView) part).setUrl(url.toExternalForm()); -// } catch (Exception e) { -// } -// } else { - BrowserManager manager = BrowserManager.getInstance(); - IWebBrowser browser = manager.getCurrentWebBrowser(); - browser.openURL(url); -// } - } + public static void open(final URL url, final Shell shell, + final String dialogTitle) { + // if (WebBrowserUtil.canUseInternalWebBrowser()) { + // IWorkbenchPage page = PHPeclipsePlugin.getActivePage(); + // try { + // IViewPart part = page.findView(BrowserView.ID_BROWSER); + // if (part == null) { + // part = page.showView(BrowserView.ID_BROWSER); + // } else { + // page.bringToTop(part); + // } + // ((BrowserView) part).setUrl(url.toExternalForm()); + // } catch (Exception e) { + // } + // } else { + BrowserManager manager = BrowserManager.getInstance(); + IWebBrowser browser = manager.getCurrentWebBrowser(); + browser.openURL(url); + // } + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPOpenAllIncludesEditorAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPOpenAllIncludesEditorAction.java index c21740f..3dd63ff 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPOpenAllIncludesEditorAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPOpenAllIncludesEditorAction.java @@ -11,6 +11,7 @@ package net.sourceforge.phpeclipse.actions; import java.io.File; import java.util.List; +import net.sourceforge.phpdt.internal.ui.viewsupport.ListContentProvider; import net.sourceforge.phpeclipse.PHPeclipsePlugin; import net.sourceforge.phpeclipse.phpeditor.PHPEditor; @@ -27,7 +28,6 @@ import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.window.Window; -import net.sourceforge.phpdt.internal.ui.viewsupport.ListContentProvider; import org.eclipse.swt.graphics.Point; import org.eclipse.ui.IEditorActionDelegate; import org.eclipse.ui.IEditorPart; @@ -37,178 +37,206 @@ import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.actions.ActionDelegate; import org.eclipse.ui.dialogs.ListSelectionDialog; -public class PHPOpenAllIncludesEditorAction extends ActionDelegate implements IEditorActionDelegate { - - private IWorkbenchWindow fWindow; - private PHPEditor fEditor; - private IProject fProject; - private IncludesScanner fIncludesScanner; - public void dispose() { - } - - public void init(IWorkbenchWindow window) { - this.fWindow = window; - } - - public void selectionChanged(IAction action, ISelection selection) { - if (!selection.isEmpty()) { - if (selection instanceof TextSelection) { - action.setEnabled(true); - } else if (fWindow.getActivePage() != null && fWindow.getActivePage().getActivePart() != null) { - // - } - } - } - private IWorkbenchPage getActivePage() { - IWorkbenchWindow workbenchWindow = fEditor.getEditorSite().getWorkbenchWindow(); - IWorkbenchPage page = workbenchWindow.getActivePage(); - return page; - } - public IContainer getWorkingLocation(IFileEditorInput editorInput) { - if (editorInput == null || editorInput.getFile() == null) { - return null; - } - return editorInput.getFile().getParent(); - } - private IFile getIncludeFile(IProject project, IFileEditorInput editorInput, String relativeFilename) { - IContainer container = getWorkingLocation(editorInput); - String fullPath = project.getLocation().toString(); - IFile file = null; - if (relativeFilename.startsWith("../")) { - Path path = new Path(relativeFilename); - file = container.getFile(path); - return file; - } - int index = relativeFilename.lastIndexOf('/'); - - if (index >= 0) { - Path path = new Path(relativeFilename); - file = project.getFile(path); - if (file.exists()) { - return file; - } - } - - Path path = new Path(relativeFilename); - file = container.getFile(path); - - return file; - } - - public void run(IAction action) { - if (fEditor == null) { - IEditorPart targetEditor = fWindow.getActivePage().getActiveEditor(); - if (targetEditor != null && (targetEditor instanceof PHPEditor)) { - fEditor = (PHPEditor) targetEditor; - } - } - if (fEditor != null) { - // determine the current Project from a (file-based) Editor - IFile f = ((IFileEditorInput) fEditor.getEditorInput()).getFile(); - fProject = f.getProject(); - // System.out.println(fProject.toString()); - - ITextSelection selection = (ITextSelection) fEditor.getSelectionProvider().getSelection(); - IDocument doc = fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput()); - fIncludesScanner = new IncludesScanner(fProject, (IFileEditorInput) fEditor.getEditorInput()); - int pos = selection.getOffset(); - // System.out.println(selection.getText()); - String filename = getPHPIncludeText(doc, pos); - - if (filename != null && !filename.equals("")) { - try { - IFile file = fIncludesScanner.getIncludeFile(filename); - fIncludesScanner.addFile(file); - } catch (Exception e) { - // ignore - } - - try { - - List list = fIncludesScanner.getList(); - if (list != null && list.size() > 0) { -// String workspaceLocation = PHPeclipsePlugin.getWorkspace().getRoot().getLocation().toString(); - String workspaceLocation = fProject.getLocation().toString()+File.separatorChar; - - ListSelectionDialog listSelectionDialog = new ListSelectionDialog(PHPeclipsePlugin.getDefault().getWorkbench() - .getActiveWorkbenchWindow().getShell(), list, new ListContentProvider(), new LabelProvider(), - "Select the includes to open."); - listSelectionDialog.setTitle("Multiple includes found"); - if (listSelectionDialog.open() == Window.OK) { - Object[] locations = listSelectionDialog.getResult(); - if (locations != null) { - try { - for (int i = 0; i < locations.length; i++) { - // PHPIdentifierLocation location = (PHPIdentifierLocation) - // locations[i]; - String openFilename = workspaceLocation + ((String) locations[i]); - PHPeclipsePlugin.getDefault().openFileInTextEditor(openFilename); - } - } catch (CoreException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - } - } catch (Exception e) { - } - - } - } - } - - public void setActiveEditor(IAction action, IEditorPart targetEditor) { - if (targetEditor != null && (targetEditor instanceof PHPEditor)) { - fEditor = (PHPEditor) targetEditor; - } - } - - private String getPHPIncludeText(IDocument doc, int pos) { - Point word = null; - int start = -1; - int end = -1; - - try { - - int position = pos; - char character; - - while (position >= 0) { - character = doc.getChar(position); - if ((character == '\"') || (character == '\'') || (character == '\r') || (character == '\n')) - break; - --position; - } - - start = position; - - position = pos; - int length = doc.getLength(); - - while (position < length) { - character = doc.getChar(position); - if ((character == '\"') || (character == '\'') || (character == '\r') || (character == '\n')) - break; - ++position; - } - - start++; - end = position; - - if (end > start) - word = new Point(start, end - start); - - } catch (BadLocationException x) { - } - - if (word != null) { - try { - return doc.get(word.x, word.y); - } catch (BadLocationException e) { - } - } - return ""; - } +public class PHPOpenAllIncludesEditorAction extends ActionDelegate implements + IEditorActionDelegate { + + private IWorkbenchWindow fWindow; + + private PHPEditor fEditor; + + private IProject fProject; + + private IncludesScanner fIncludesScanner; + + public void dispose() { + } + + public void init(IWorkbenchWindow window) { + this.fWindow = window; + } + + public void selectionChanged(IAction action, ISelection selection) { + if (!selection.isEmpty()) { + if (selection instanceof TextSelection) { + action.setEnabled(true); + } else if (fWindow.getActivePage() != null + && fWindow.getActivePage().getActivePart() != null) { + // + } + } + } + + private IWorkbenchPage getActivePage() { + IWorkbenchWindow workbenchWindow = fEditor.getEditorSite() + .getWorkbenchWindow(); + IWorkbenchPage page = workbenchWindow.getActivePage(); + return page; + } + + public IContainer getWorkingLocation(IFileEditorInput editorInput) { + if (editorInput == null || editorInput.getFile() == null) { + return null; + } + return editorInput.getFile().getParent(); + } + + private IFile getIncludeFile(IProject project, + IFileEditorInput editorInput, String relativeFilename) { + IContainer container = getWorkingLocation(editorInput); + String fullPath = project.getLocation().toString(); + IFile file = null; + if (relativeFilename.startsWith("../")) { + Path path = new Path(relativeFilename); + file = container.getFile(path); + return file; + } + int index = relativeFilename.lastIndexOf('/'); + + if (index >= 0) { + Path path = new Path(relativeFilename); + file = project.getFile(path); + if (file.exists()) { + return file; + } + } + + Path path = new Path(relativeFilename); + file = container.getFile(path); + + return file; + } + + public void run(IAction action) { + if (fEditor == null) { + IEditorPart targetEditor = fWindow.getActivePage() + .getActiveEditor(); + if (targetEditor != null && (targetEditor instanceof PHPEditor)) { + fEditor = (PHPEditor) targetEditor; + } + } + if (fEditor != null) { + // determine the current Project from a (file-based) Editor + IFile f = ((IFileEditorInput) fEditor.getEditorInput()).getFile(); + fProject = f.getProject(); + // System.out.println(fProject.toString()); + + ITextSelection selection = (ITextSelection) fEditor + .getSelectionProvider().getSelection(); + IDocument doc = fEditor.getDocumentProvider().getDocument( + fEditor.getEditorInput()); + fIncludesScanner = new IncludesScanner(fProject, + (IFileEditorInput) fEditor.getEditorInput()); + int pos = selection.getOffset(); + // System.out.println(selection.getText()); + String filename = getPHPIncludeText(doc, pos); + + if (filename != null && !filename.equals("")) { + try { + IFile file = fIncludesScanner.getIncludeFile(filename); + fIncludesScanner.addFile(file); + } catch (Exception e) { + // ignore + } + + try { + + List list = fIncludesScanner.getList(); + if (list != null && list.size() > 0) { + // String workspaceLocation = + // PHPeclipsePlugin.getWorkspace().getRoot().getLocation().toString(); + String workspaceLocation = fProject.getLocation() + .toString() + + File.separatorChar; + + ListSelectionDialog listSelectionDialog = new ListSelectionDialog( + PHPeclipsePlugin.getDefault().getWorkbench() + .getActiveWorkbenchWindow().getShell(), + list, new ListContentProvider(), + new LabelProvider(), + "Select the includes to open."); + listSelectionDialog.setTitle("Multiple includes found"); + if (listSelectionDialog.open() == Window.OK) { + Object[] locations = listSelectionDialog + .getResult(); + if (locations != null) { + try { + for (int i = 0; i < locations.length; i++) { + // PHPIdentifierLocation location = + // (PHPIdentifierLocation) + // locations[i]; + String openFilename = workspaceLocation + + ((String) locations[i]); + PHPeclipsePlugin.getDefault() + .openFileInTextEditor( + openFilename); + } + } catch (CoreException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + } + } catch (Exception e) { + } + + } + } + } + + public void setActiveEditor(IAction action, IEditorPart targetEditor) { + if (targetEditor != null && (targetEditor instanceof PHPEditor)) { + fEditor = (PHPEditor) targetEditor; + } + } + + private String getPHPIncludeText(IDocument doc, int pos) { + Point word = null; + int start = -1; + int end = -1; + + try { + + int position = pos; + char character; + + while (position >= 0) { + character = doc.getChar(position); + if ((character == '\"') || (character == '\'') + || (character == '\r') || (character == '\n')) + break; + --position; + } + + start = position; + + position = pos; + int length = doc.getLength(); + + while (position < length) { + character = doc.getChar(position); + if ((character == '\"') || (character == '\'') + || (character == '\r') || (character == '\n')) + break; + ++position; + } + + start++; + end = position; + + if (end > start) + word = new Point(start, end - start); + + } catch (BadLocationException x) { + } + + if (word != null) { + try { + return doc.get(word.x, word.y); + } catch (BadLocationException e) { + } + } + return ""; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPOpenDeclarationAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPOpenDeclarationAction.java index 7fc1dae..47edccb 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPOpenDeclarationAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPOpenDeclarationAction.java @@ -22,82 +22,92 @@ import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.IWorkbenchWindow; public class PHPOpenDeclarationAction extends SelectionDispatchAction { - private IWorkbenchWindow fWindow; + private IWorkbenchWindow fWindow; - private PHPEditor fEditor; + private PHPEditor fEditor; - public void dispose() { - } + public void dispose() { + } - public PHPOpenDeclarationAction(IWorkbenchSite site) { - super(site); - // setText(ActionMessages.getString("OpenAction.label")); //$NON-NLS-1$ - // setToolTipText(ActionMessages.getString("OpenAction.tooltip")); //$NON-NLS-1$ - // setDescription(ActionMessages.getString("OpenAction.description")); //$NON-NLS-1$ - // WorkbenchHelp.setHelp(this, IJavaHelpContextIds.OPEN_ACTION); - } - - /** - * Note: This constructor is for internal use only. Clients should not call this constructor. - */ - public PHPOpenDeclarationAction(PHPEditor editor) { - this(editor.getEditorSite()); - fEditor = editor; - // setText(ActionMessages.getString("OpenAction.declaration.label")); //$NON-NLS-1$ - setEnabled(SelectionConverter.canOperateOn(fEditor)); - } - - public void init(IWorkbenchWindow window) { - this.fWindow = window; - } + public PHPOpenDeclarationAction(IWorkbenchSite site) { + super(site); + // setText(ActionMessages.getString("OpenAction.label")); //$NON-NLS-1$ + // setToolTipText(ActionMessages.getString("OpenAction.tooltip")); + // //$NON-NLS-1$ + // setDescription(ActionMessages.getString("OpenAction.description")); + // //$NON-NLS-1$ + // WorkbenchHelp.setHelp(this, IJavaHelpContextIds.OPEN_ACTION); + } - public void selectionChanged(IAction action, ISelection selection) { - if (!selection.isEmpty()) { - if (selection instanceof TextSelection) { - action.setEnabled(true); - } else if (fWindow.getActivePage() != null && fWindow.getActivePage().getActivePart() != null) { - // - } - } - } + /** + * Note: This constructor is for internal use only. Clients should not call + * this constructor. + */ + public PHPOpenDeclarationAction(PHPEditor editor) { + this(editor.getEditorSite()); + fEditor = editor; + // setText(ActionMessages.getString("OpenAction.declaration.label")); + // //$NON-NLS-1$ + setEnabled(SelectionConverter.canOperateOn(fEditor)); + } - private boolean checkEnabled(IStructuredSelection selection) { - if (selection.isEmpty()) - return false; - return true; - } + public void init(IWorkbenchWindow window) { + this.fWindow = window; + } - /* - * (non-Javadoc) Method declared on SelectionDispatchAction. - */ - public void run(ITextSelection selection) { - if (!ActionUtil.isProcessable(getShell(), fEditor)) - return; - OpenDeclarationEditorAction openAction = new OpenDeclarationEditorAction(fEditor); - openAction.openSelectedElement(selection); - } + public void selectionChanged(IAction action, ISelection selection) { + if (!selection.isEmpty()) { + if (selection instanceof TextSelection) { + action.setEnabled(true); + } else if (fWindow.getActivePage() != null + && fWindow.getActivePage().getActivePart() != null) { + // + } + } + } - /* - * (non-Javadoc) Method declared on SelectionDispatchAction. - */ - public void run(IStructuredSelection selection) { - if (!checkEnabled(selection)) - return; - run(selection.toArray()); - } + private boolean checkEnabled(IStructuredSelection selection) { + if (selection.isEmpty()) + return false; + return true; + } - /** - * Note: this method is for internal use only. Clients should not call this method. - */ - public void run(Object[] elements) { - if (elements != null && elements.length > 0) { - ITextSelection selection = (ITextSelection) fEditor.getSelectionProvider().getSelection(); - IDocument doc = fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput()); - int pos = selection.getOffset(); + /* + * (non-Javadoc) Method declared on SelectionDispatchAction. + */ + public void run(ITextSelection selection) { + if (!ActionUtil.isProcessable(getShell(), fEditor)) + return; + OpenDeclarationEditorAction openAction = new OpenDeclarationEditorAction( + fEditor); + openAction.openSelectedElement(selection); + } - OpenDeclarationEditorAction openAction = new OpenDeclarationEditorAction(fEditor); - openAction.openSelectedPosition(doc, pos); - } - } + /* + * (non-Javadoc) Method declared on SelectionDispatchAction. + */ + public void run(IStructuredSelection selection) { + if (!checkEnabled(selection)) + return; + run(selection.toArray()); + } + + /** + * Note: this method is for internal use only. Clients should not call this + * method. + */ + public void run(Object[] elements) { + if (elements != null && elements.length > 0) { + ITextSelection selection = (ITextSelection) fEditor + .getSelectionProvider().getSelection(); + IDocument doc = fEditor.getDocumentProvider().getDocument( + fEditor.getEditorInput()); + int pos = selection.getOffset(); + + OpenDeclarationEditorAction openAction = new OpenDeclarationEditorAction( + fEditor); + openAction.openSelectedPosition(doc, pos); + } + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPOpenDeclarationEditorAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPOpenDeclarationEditorAction.java index e689c33..d800960 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPOpenDeclarationEditorAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPOpenDeclarationEditorAction.java @@ -19,49 +19,54 @@ import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.actions.ActionDelegate; -public class PHPOpenDeclarationEditorAction extends ActionDelegate implements IEditorActionDelegate { - private IWorkbenchWindow fWindow; +public class PHPOpenDeclarationEditorAction extends ActionDelegate implements + IEditorActionDelegate { + private IWorkbenchWindow fWindow; - private PHPEditor fEditor; + private PHPEditor fEditor; - public void init(IWorkbenchWindow window) { - this.fWindow = window; - } + public void init(IWorkbenchWindow window) { + this.fWindow = window; + } - public void selectionChanged(IAction action, ISelection selection) { - if (!selection.isEmpty()) { - if (selection instanceof TextSelection) { - action.setEnabled(true); - } else if (fWindow.getActivePage() != null && fWindow.getActivePage().getActivePart() != null) { - // - } - } - } + public void selectionChanged(IAction action, ISelection selection) { + if (!selection.isEmpty()) { + if (selection instanceof TextSelection) { + action.setEnabled(true); + } else if (fWindow.getActivePage() != null + && fWindow.getActivePage().getActivePart() != null) { + // + } + } + } - private boolean checkEnabled(IStructuredSelection selection) { - if (selection.isEmpty()) - return false; - return true; - } - - public void run(IAction action) { - if (fEditor == null) { - IEditorPart targetEditor = fWindow.getActivePage().getActiveEditor(); - if (targetEditor != null && (targetEditor instanceof PHPEditor)) { - fEditor = (PHPEditor) targetEditor; - } - } - if (fEditor != null) { - ITextSelection selection = (ITextSelection) fEditor.getSelectionProvider().getSelection(); - OpenDeclarationEditorAction openAction = new OpenDeclarationEditorAction(fEditor); - openAction.openSelectedElement(selection); - } - } + private boolean checkEnabled(IStructuredSelection selection) { + if (selection.isEmpty()) + return false; + return true; + } - public void setActiveEditor(IAction action, IEditorPart targetEditor) { - if (targetEditor != null && (targetEditor instanceof PHPEditor)) { - fEditor = (PHPEditor) targetEditor; - } - } + public void run(IAction action) { + if (fEditor == null) { + IEditorPart targetEditor = fWindow.getActivePage() + .getActiveEditor(); + if (targetEditor != null && (targetEditor instanceof PHPEditor)) { + fEditor = (PHPEditor) targetEditor; + } + } + if (fEditor != null) { + ITextSelection selection = (ITextSelection) fEditor + .getSelectionProvider().getSelection(); + OpenDeclarationEditorAction openAction = new OpenDeclarationEditorAction( + fEditor); + openAction.openSelectedElement(selection); + } + } + + public void setActiveEditor(IAction action, IEditorPart targetEditor) { + if (targetEditor != null && (targetEditor instanceof PHPEditor)) { + fEditor = (PHPEditor) targetEditor; + } + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/ExternalEditorInput.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/ExternalEditorInput.java index b9e0232..07be7dc 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/ExternalEditorInput.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/ExternalEditorInput.java @@ -12,87 +12,90 @@ import org.eclipse.ui.PlatformUI; */ public class ExternalEditorInput implements IStorageEditorInput { - IStorage externalFile; + IStorage externalFile; - /** - * Two ExternalEditorInputs are equal if their IStorage's are equal. - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!(obj instanceof ExternalEditorInput)) - return false; - ExternalEditorInput other = (ExternalEditorInput) obj; - return externalFile.equals(other.externalFile); - } - - /* - * @see IEditorInput#exists() - */ - public boolean exists() { - // External file can not be deleted + /** + * Two ExternalEditorInputs are equal if their IStorage's are equal. + * + * @see java.lang.Object#equals(java.lang.Object) + */ + public boolean equals(Object obj) { + if (this == obj) return true; - } + if (!(obj instanceof ExternalEditorInput)) + return false; + ExternalEditorInput other = (ExternalEditorInput) obj; + return externalFile.equals(other.externalFile); + } + + /* + * @see IEditorInput#exists() + */ + public boolean exists() { + // External file can not be deleted + return true; + } - /* - * @see IAdaptable#getAdapter(Class) - */ - public Object getAdapter(Class adapter) { - return null; - } + /* + * @see IAdaptable#getAdapter(Class) + */ + public Object getAdapter(Class adapter) { + return null; + } - /* - * @see IEditorInput#getContentType() - */ - public String getContentType() { - return externalFile.getFullPath().getFileExtension(); - } + /* + * @see IEditorInput#getContentType() + */ + public String getContentType() { + return externalFile.getFullPath().getFileExtension(); + } - /* - * @see IEditorInput#getFullPath() - */ - public String getFullPath() { - return externalFile.getFullPath().toString(); - } + /* + * @see IEditorInput#getFullPath() + */ + public String getFullPath() { + return externalFile.getFullPath().toString(); + } - /* - * @see IEditorInput#getImageDescriptor() - */ - public ImageDescriptor getImageDescriptor() { - IEditorRegistry registry = PlatformUI.getWorkbench().getEditorRegistry(); - return registry.getImageDescriptor(externalFile.getFullPath().getFileExtension()); - } + /* + * @see IEditorInput#getImageDescriptor() + */ + public ImageDescriptor getImageDescriptor() { + IEditorRegistry registry = PlatformUI.getWorkbench() + .getEditorRegistry(); + return registry.getImageDescriptor(externalFile.getFullPath() + .getFileExtension()); + } - /* - * @see IEditorInput#getName() - */ - public String getName() { - return externalFile.getName(); - } + /* + * @see IEditorInput#getName() + */ + public String getName() { + return externalFile.getName(); + } - /* - * @see IEditorInput#getPersistable() - */ - public IPersistableElement getPersistable() { - return null; - } + /* + * @see IEditorInput#getPersistable() + */ + public IPersistableElement getPersistable() { + return null; + } - /* - * see IStorageEditorInput#getStorage() - */ - public IStorage getStorage() { - return externalFile; - } + /* + * see IStorageEditorInput#getStorage() + */ + public IStorage getStorage() { + return externalFile; + } - /* - * @see IEditorInput#getToolTipText() - */ - public String getToolTipText() { - return externalFile.getFullPath().toString(); - } + /* + * @see IEditorInput#getToolTipText() + */ + public String getToolTipText() { + return externalFile.getFullPath().toString(); + } - public ExternalEditorInput(IStorage exFile) { - externalFile = exFile; - } + public ExternalEditorInput(IStorage exFile) { + externalFile = exFile; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/ExternalStorageDocumentProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/ExternalStorageDocumentProvider.java index 8b84819..c1d2ad5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/ExternalStorageDocumentProvider.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/ExternalStorageDocumentProvider.java @@ -19,37 +19,42 @@ import org.eclipse.ui.editors.text.StorageDocumentProvider; */ public class ExternalStorageDocumentProvider extends StorageDocumentProvider { - /* (non-Javadoc) - * @see org.eclipse.ui.texteditor.AbstractDocumentProvider#doSaveDocument(org.eclipse.core.runtime.IProgressMonitor, java.lang.Object, org.eclipse.jface.text.IDocument, boolean) - */ - protected void doSaveDocument(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite) - throws CoreException { - if (element instanceof ExternalEditorInput) { - ExternalEditorInput external = (ExternalEditorInput) element; - FileStorage storage = (FileStorage)external.getStorage(); - String encoding = getEncoding(element); - if (encoding == null) - encoding = getDefaultEncoding(); - try { - InputStream stream = new ByteArrayInputStream(document.get().getBytes(encoding)); - try { - // inform about the upcoming content change - fireElementStateChanging(element); - storage.setContents(stream, overwrite, true, monitor); - } catch (RuntimeException e) { - // inform about failure - fireElementStateChangeFailed(element); - throw e; - } - } catch (IOException e) { - IStatus s = new Status(IStatus.ERROR, PHPeclipsePlugin.PLUGIN_ID, IStatus.OK, e.getMessage(), e); - throw new CoreException(s); - } - - } else { - super.doSaveDocument(monitor, element, document, overwrite); + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.texteditor.AbstractDocumentProvider#doSaveDocument(org.eclipse.core.runtime.IProgressMonitor, + * java.lang.Object, org.eclipse.jface.text.IDocument, boolean) + */ + protected void doSaveDocument(IProgressMonitor monitor, Object element, + IDocument document, boolean overwrite) throws CoreException { + if (element instanceof ExternalEditorInput) { + ExternalEditorInput external = (ExternalEditorInput) element; + FileStorage storage = (FileStorage) external.getStorage(); + String encoding = getEncoding(element); + if (encoding == null) + encoding = getDefaultEncoding(); + try { + InputStream stream = new ByteArrayInputStream(document.get() + .getBytes(encoding)); + try { + // inform about the upcoming content change + fireElementStateChanging(element); + storage.setContents(stream, overwrite, true, monitor); + } catch (RuntimeException e) { + // inform about failure + fireElementStateChangeFailed(element); + throw e; + } + } catch (IOException e) { + IStatus s = new Status(IStatus.ERROR, + PHPeclipsePlugin.PLUGIN_ID, IStatus.OK, e.getMessage(), + e); + throw new CoreException(s); } - } -} + } else { + super.doSaveDocument(monitor, element, document, overwrite); + } + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/FileStorage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/FileStorage.java index d4b5f6a..4bb9ac8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/FileStorage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/FileStorage.java @@ -24,96 +24,114 @@ import org.eclipse.core.runtime.Status; */ /** - * + * * @see IStorage */ public class FileStorage extends PlatformObject implements IStorage { - private boolean forceReadOnly; - private final IPath path; - private final File file; - - /** - * Two FileStorages are equal if their IPaths are equal. - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!(obj instanceof FileStorage)) - return false; - FileStorage other = (FileStorage) obj; - return path.equals(other.path); - } - - /* (non-Javadoc) - * @see org.eclipse.core.resources.IStorage#getContents() - */ - public InputStream getContents() throws CoreException { - try { - return new FileInputStream(file); - } catch (FileNotFoundException e) { - throw new CoreException(new Status(IStatus.ERROR, PHPeclipsePlugin.PLUGIN_ID, IStatus.ERROR, e.toString(), e)); - } - } - - /* (non-Javadoc) - * @see org.eclipse.core.resources.IStorage#getFullPath() - */ - public IPath getFullPath() { - return this.path; - } - - /* (non-Javadoc) - * @see org.eclipse.core.resources.IStorage#getName() - */ - public String getName() { - return this.path.lastSegment(); - } - - /* (non-Javadoc) - * @see org.eclipse.core.resources.IStorage#isReadOnly() - */ - public boolean isReadOnly() { - return forceReadOnly || !file.canWrite(); - } - - /** - * Method FileStorage. - * @param path - */ - public FileStorage(IPath path) { - this.path = path; - this.file = path.toFile(); - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - public String toString() { - return path.toOSString(); - } - - /** - * @param stream - * @param overwrite - * @param b - * @param monitor - */ - public void setContents(InputStream stream, boolean overwrite, boolean b, IProgressMonitor monitor) throws CoreException { - try { - StreamUtil.transferStreams(stream, new FileOutputStream(file)); - } catch (FileNotFoundException e) { - throw new CoreException(new Status(IStatus.ERROR, PHPeclipsePlugin.PLUGIN_ID, IStatus.ERROR, e.toString(), e)); - } catch (IOException e) { - throw new CoreException(new Status(IStatus.ERROR, PHPeclipsePlugin.PLUGIN_ID, IStatus.ERROR, e.toString(), e)); - } - } - - /** - * Some document providers (notably CompilationUnitDocumentProvider) - * can't handle read/write storage. - */ - public void setReadOnly() { - forceReadOnly = true; - } + private boolean forceReadOnly; + + private final IPath path; + + private final File file; + + /** + * Two FileStorages are equal if their IPaths are equal. + * + * @see java.lang.Object#equals(java.lang.Object) + */ + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!(obj instanceof FileStorage)) + return false; + FileStorage other = (FileStorage) obj; + return path.equals(other.path); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.core.resources.IStorage#getContents() + */ + public InputStream getContents() throws CoreException { + try { + return new FileInputStream(file); + } catch (FileNotFoundException e) { + throw new CoreException(new Status(IStatus.ERROR, + PHPeclipsePlugin.PLUGIN_ID, IStatus.ERROR, e.toString(), e)); + } + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.core.resources.IStorage#getFullPath() + */ + public IPath getFullPath() { + return this.path; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.core.resources.IStorage#getName() + */ + public String getName() { + return this.path.lastSegment(); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.core.resources.IStorage#isReadOnly() + */ + public boolean isReadOnly() { + return forceReadOnly || !file.canWrite(); + } + + /** + * Method FileStorage. + * + * @param path + */ + public FileStorage(IPath path) { + this.path = path; + this.file = path.toFile(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + public String toString() { + return path.toOSString(); + } + + /** + * @param stream + * @param overwrite + * @param b + * @param monitor + */ + public void setContents(InputStream stream, boolean overwrite, boolean b, + IProgressMonitor monitor) throws CoreException { + try { + StreamUtil.transferStreams(stream, new FileOutputStream(file)); + } catch (FileNotFoundException e) { + throw new CoreException(new Status(IStatus.ERROR, + PHPeclipsePlugin.PLUGIN_ID, IStatus.ERROR, e.toString(), e)); + } catch (IOException e) { + throw new CoreException(new Status(IStatus.ERROR, + PHPeclipsePlugin.PLUGIN_ID, IStatus.ERROR, e.toString(), e)); + } + } + + /** + * Some document providers (notably CompilationUnitDocumentProvider) can't + * handle read/write storage. + */ + public void setReadOnly() { + forceReadOnly = true; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/IdentifierIndexManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/IdentifierIndexManager.java index 1a38bc6..499bd82 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/IdentifierIndexManager.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/IdentifierIndexManager.java @@ -32,899 +32,997 @@ import org.eclipse.core.runtime.IStatus; /** * Manages the identifer index information for a specific project - * + * */ public class IdentifierIndexManager { - public class LineCreator implements ITerminalSymbols { - private Scanner fScanner; - - private int fToken; - - public LineCreator() { - fScanner = new Scanner(true, false, false, false, true, null, null, true /* taskCaseSensitive */); - } - - /** - * Add the information of the current identifier to the line - * - * @param typeOfIdentifier - * the type of the identifier ('c'lass, 'd'efine, 'f'unction, 'm'ethod(class), 'v'ariable(class) 'g'lobal variable) - * @param identifier - * current identifier - * @param line - * Buffer for the current index line - */ - private void addIdentifierInformation(char typeOfIdentifier, char[] identifier, StringBuffer line) { - line.append('\t'); - line.append(typeOfIdentifier); - line.append(identifier); - // line.append("\to"); // Offset - // line.append(fScanner.getCurrentTokenStartPosition()); - } - - /** - * Add the information of the current identifier to the line - * - * @param typeOfIdentifier - * the type of the identifier ('c'lass, 'd'efine, 'f'unction, 'm'ethod(class), 'v'ariable(class) 'g'lobal variable) - * @param identifier - * current identifier - * @param line - * Buffer for the current index line - * @param phpdocOffset - * the offset of the PHPdoc comment if available - * @param phpdocLength - * the length of the PHPdoc comment if available - */ - private void addIdentifierInformation(char typeOfIdentifier, char[] identifier, StringBuffer line, int phpdocOffset, - int phpdocLength) { - line.append('\t'); - line.append(typeOfIdentifier); - line.append(identifier); - line.append("\to"); // Offset - line.append(fScanner.getCurrentTokenStartPosition()); - if (phpdocOffset >= 0) { - line.append("\tp"); // phpdoc offset - line.append(phpdocOffset); - line.append("\tl"); // phpdoc length - line.append(phpdocLength); - } - } - - private void addClassVariableInformation(char typeOfIdentifier, char[] identifier, StringBuffer line, int phpdocOffset, - int phpdocLength) { - line.append('\t'); - line.append(typeOfIdentifier); - line.append(identifier); - line.append("\to"); // Offset - // we don't store the '$' in the index for class variables: - line.append(fScanner.getCurrentTokenStartPosition() + 1); - if (phpdocOffset >= 0) { - line.append("\tp"); // phpdoc offset - line.append(phpdocOffset); - line.append("\tl"); // phpdoc length - line.append(phpdocLength); - } - } - - /** - * Get the next token from input - */ - private void getNextToken() throws InvalidInputException { - // try { - fToken = fScanner.getNextToken(); - if (Scanner.DEBUG) { - int currentEndPosition = fScanner.getCurrentTokenEndPosition(); - int currentStartPosition = fScanner.getCurrentTokenStartPosition(); - System.out.print(currentStartPosition + "," + currentEndPosition + ": "); - System.out.println(fScanner.toStringAction(fToken)); - } - return; - // } catch (InvalidInputException e) { - // // ignore errors - // // e.printStackTrace(); - // } - // fToken = TokenNameERROR; - } - - private void parseDeclarations(char[] parent, StringBuffer buf, boolean goBack) { - char[] ident; - char[] classVariable; - int counter = 0; - boolean hasModifiers = false; - int phpdocOffset = -1; - int phpdocLength = -1; - try { - while (fToken != TokenNameEOF && fToken != TokenNameERROR) { - phpdocOffset = -1; - hasModifiers = false; - if (fToken == TokenNameCOMMENT_PHPDOC) { - phpdocOffset = fScanner.getCurrentTokenStartPosition(); - phpdocLength = fScanner.getCurrentTokenEndPosition() - fScanner.getCurrentTokenStartPosition() + 1; - getNextToken(); - while (fToken == TokenNamestatic || fToken == TokenNamefinal || fToken == TokenNamepublic - || fToken == TokenNameprotected || fToken == TokenNameprivate || fToken == TokenNameabstract) { - hasModifiers = true; - getNextToken(); - } - if (fToken == TokenNameEOF || fToken == TokenNameERROR) { - break; - } - } - if (fToken == TokenNamefunction) { - getNextToken(); - if (fToken == TokenNameAND) { - getNextToken(); - } - if (fToken == TokenNameIdentifier) { - ident = fScanner.getCurrentIdentifierSource(); - if (parent != null && equalCharArrays(parent, ident)) { - // constructor function - addIdentifierInformation('k', ident, buf, phpdocOffset, phpdocLength); - } else { - if (parent != null) { - // class method function - addIdentifierInformation('m', ident, buf, phpdocOffset, phpdocLength); - } else { - // nested function ?! - addIdentifierInformation('f', ident, buf, phpdocOffset, phpdocLength); - } - } - getNextToken(); - parseDeclarations(null, buf, true); - } - } else if (fToken == TokenNameclass || fToken == TokenNameinterface) { - getNextToken(); - if (fToken == TokenNameIdentifier) { - ident = fScanner.getCurrentIdentifierSource(); - addIdentifierInformation('c', ident, buf, phpdocOffset, phpdocLength); - getNextToken(); - if (fToken == TokenNameextends) { - getNextToken(); - while (fToken == TokenNameIdentifier) { - ident = fScanner.getCurrentIdentifierSource(); - // extends ident - addIdentifierInformation('e', ident, buf); - getNextToken(); - if (fToken == TokenNameCOMMA) { - getNextToken(); - } - } - } - if (fToken == TokenNameimplements) { - getNextToken(); - while (fToken == TokenNameIdentifier) { - ident = fScanner.getCurrentIdentifierSource(); - // implements ident - addIdentifierInformation('e', ident, buf); - getNextToken(); - if (fToken == TokenNameCOMMA) { - getNextToken(); - } - } - } - //skip tokens for classname, extends and others until we have - // the opening '{' - while (fToken != TokenNameLBRACE && fToken != TokenNameEOF && fToken != TokenNameERROR) { - getNextToken(); - } - parseDeclarations(ident, buf, true); - } - } else if (fToken == TokenNamevar || hasModifiers || fToken == TokenNamestatic || fToken == TokenNamefinal - || fToken == TokenNamepublic || fToken == TokenNameprotected || fToken == TokenNameprivate) { - while (fToken == TokenNamevar || fToken == TokenNamestatic || fToken == TokenNamefinal || fToken == TokenNamepublic - || fToken == TokenNameprotected || fToken == TokenNameprivate) { - getNextToken(); - } - while (fToken == TokenNameVariable) { - ident = fScanner.getCurrentIdentifierSource(); - classVariable = new char[ident.length - 1]; - System.arraycopy(ident, 1, classVariable, 0, ident.length - 1); - addClassVariableInformation('v', classVariable, buf, phpdocOffset, phpdocLength); - getNextToken(); - if (fToken == TokenNameCOMMA) { - getNextToken(); - } - } - } else if (!hasModifiers && fToken == TokenNameIdentifier) { - ident = fScanner.getCurrentIdentifierSource(); - getNextToken(); - if (ident.length == 6 && ident[0] == 'd' && ident[1] == 'e' && ident[2] == 'f' && ident[3] == 'i' && ident[4] == 'n' - && ident[5] == 'e') { - if (fToken == TokenNameLPAREN) { - getNextToken(); - if (fToken == TokenNameStringDoubleQuote) { - ident = fScanner.getCurrentStringLiteralSource(); - addIdentifierInformation('d', ident, buf, phpdocOffset, phpdocLength); - getNextToken(); - } else if (fToken == TokenNameStringSingleQuote) { - ident = fScanner.getCurrentStringLiteralSource(); - addIdentifierInformation('d', ident, buf, phpdocOffset, phpdocLength); - getNextToken(); - } - } - } - } else if (fToken == TokenNameglobal) { - // global variable - while (fToken != TokenNameEOF && fToken != TokenNameERROR && fToken != TokenNameSEMICOLON && fToken != TokenNameLBRACE - && fToken != TokenNameRBRACE) { - getNextToken(); - if (fToken == TokenNameVariable) { - ident = fScanner.getCurrentIdentifierSource(); - addIdentifierInformation('g', ident, buf, phpdocOffset, phpdocLength); - } - } - } else if (fToken == TokenNameLBRACE) { - getNextToken(); - counter++; - } else if (fToken == TokenNameRBRACE) { - getNextToken(); - --counter; - if (counter == 0 && goBack) { - return; - } - } else { - getNextToken(); - } - } - } catch (InvalidInputException e) { - // ignore errors - } catch (SyntaxError e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - synchronized public void parseIdentifiers(char[] charArray, StringBuffer buf) { - char[] ident; - String identifier; - int counter = 0; - boolean hasModifiers = false; - int phpdocOffset = -1; - int phpdocLength = -1; - fScanner.setSource(charArray); - fScanner.setPHPMode(false); - fToken = TokenNameEOF; - try { - getNextToken(); - while (fToken != TokenNameEOF) { // && fToken != TokenNameERROR) { - phpdocOffset = -1; - hasModifiers = false; - if (fToken == TokenNameCOMMENT_PHPDOC) { - phpdocOffset = fScanner.getCurrentTokenStartPosition(); - phpdocLength = fScanner.getCurrentTokenEndPosition() - fScanner.getCurrentTokenStartPosition() + 1; - getNextToken(); - while (fToken == TokenNamestatic || fToken == TokenNamefinal || fToken == TokenNamepublic - || fToken == TokenNameprotected || fToken == TokenNameprivate || fToken == TokenNameabstract) { - hasModifiers = true; - getNextToken(); - } - if (fToken == TokenNameEOF || fToken == TokenNameERROR) { - break; - } - } - if (fToken == TokenNamefunction) { - getNextToken(); - if (fToken == TokenNameAND) { - getNextToken(); - } - if (fToken == TokenNameIdentifier) { - ident = fScanner.getCurrentIdentifierSource(); - addIdentifierInformation('f', ident, buf, phpdocOffset, phpdocLength); - getNextToken(); - parseDeclarations(null, buf, true); - } - } else if (fToken == TokenNameclass || fToken == TokenNameinterface) { - getNextToken(); - if (fToken == TokenNameIdentifier) { - ident = fScanner.getCurrentIdentifierSource(); - addIdentifierInformation('c', ident, buf, phpdocOffset, phpdocLength); - getNextToken(); - if (fToken == TokenNameextends) { - getNextToken(); - while (fToken == TokenNameIdentifier) { - ident = fScanner.getCurrentIdentifierSource(); - // extends ident - addIdentifierInformation('e', ident, buf); - getNextToken(); - if (fToken == TokenNameCOMMA) { - getNextToken(); - } - } - } - if (fToken == TokenNameimplements) { - getNextToken(); - while (fToken == TokenNameIdentifier) { - ident = fScanner.getCurrentIdentifierSource(); - // implements ident - addIdentifierInformation('e', ident, buf); - getNextToken(); - if (fToken == TokenNameCOMMA) { - getNextToken(); - } - } - } - //skip fTokens for classname, extends and others until we have - // the opening '{' - while (fToken != TokenNameLBRACE && fToken != TokenNameEOF && fToken != TokenNameERROR) { - getNextToken(); - } - parseDeclarations(ident, buf, true); - } - } else if (fToken == TokenNameVariable) { - // global variable - ident = fScanner.getCurrentIdentifierSource(); - addIdentifierInformation('g', ident, buf, phpdocOffset, phpdocLength); - getNextToken(); - } else if (!hasModifiers && fToken == TokenNameIdentifier) { - ident = fScanner.getCurrentIdentifierSource(); - getNextToken(); - if (ident.length == 6 && ident[0] == 'd' && ident[1] == 'e' && ident[2] == 'f' && ident[3] == 'i' && ident[4] == 'n' - && ident[5] == 'e') { - if (fToken == TokenNameLPAREN) { - getNextToken(); - if (fToken == TokenNameStringDoubleQuote) { - ident = fScanner.getCurrentStringLiteralSource(); - addIdentifierInformation('d', ident, buf, phpdocOffset, phpdocLength); - getNextToken(); - } else if (fToken == TokenNameStringSingleQuote) { - ident = fScanner.getCurrentStringLiteralSource(); - addIdentifierInformation('d', ident, buf, phpdocOffset, phpdocLength); - getNextToken(); - } - } - } - } else { - getNextToken(); - } - } - } catch (InvalidInputException e) { - // ignore errors - } catch (SyntaxError e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - class StringComparator implements Comparator { - public int compare(Object o1, Object o2) { - String s1 = (String) o1; - String s2 = (String) o2; - return s1.compareTo(s2); - // return s1.toUpperCase().compareTo(s2.toUpperCase()); - } - - public boolean equals(Object o) { - String s = (String) o; - return compare(this, o) == 0; - } - } - - private HashMap fFileMap; - - private String fFilename; - - private TreeMap fIndentifierMap; - - public IdentifierIndexManager(String filename) { - fFilename = filename; - initialize(); - readFile(); - } - - /** - * Check if 2 char arrays are equal - * - * @param a - * @param b - * @return - */ - private static boolean equalCharArrays(char[] a, char[] b) { - if (a.length != b.length) { - return false; - } - for (int i = 0; i < b.length; i++) { - if (a[i] != b[i]) { - return false; - } - } - return true; - } - - public LineCreator createLineCreator() { - return new LineCreator(); - } - - /** - * Add the information for a given IFile resource - * - */ - public void addFile(IFile fileToParse) { - // InputStream iStream; - LineCreator lineCreator = createLineCreator(); - try { - addInputStream(new BufferedInputStream(fileToParse.getContents()), fileToParse.getProjectRelativePath().toString(), - lineCreator); - } catch (CoreException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - } - - /** - * @param fileToParse - * @param lineCreator - * @throws CoreException - */ - public void addInputStream(InputStream stream, String filePath, LineCreator lineCreator) throws CoreException { - try { - StringBuffer lineBuffer = new StringBuffer(); - lineBuffer.append(filePath); - int lineLength = lineBuffer.length(); - lineCreator.parseIdentifiers(Util.getInputStreamAsCharArray(stream, -1, null), lineBuffer); - // if (lineLength != lineBuffer.length()) { - // always add the file for Open Include Action - addLine(lineBuffer.toString()); - // } - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - if (stream != null) { - stream.close(); - } - } catch (IOException e) { - } - } - } - - /** - * Adds a line of the index file for function, class, class-method and class-variable names - * - * @param line - */ - private void addLine(String line) { - addLine(fIndentifierMap, fFileMap, line, null); - } - - public TreeMap getIdentifiers(IFile file) { - TreeMap treeMap = new TreeMap(new StringComparator()); - addIdentifiers(treeMap, file); - return treeMap; - } - - public TreeMap getIdentifiers(String startClazz) { - TreeMap treeMap = new TreeMap(new StringComparator()); - addIdentifiers(treeMap, startClazz); - return treeMap; - } - - public void addIdentifiers(TreeMap treeMap, IFile file) { - String line = (String) fFileMap.get(file.getProjectRelativePath().toString()); - if (line != null) { - PHPIdentifierLocation ident; - ArrayList allClassNames = new ArrayList(); - addLine(treeMap, null, line, allClassNames); - int i = 0; - while (i < allClassNames.size()) { - String clazz = (String) allClassNames.get(i++); - addClassName(treeMap, clazz, allClassNames); - } - } - } - - public void addIdentifiers(TreeMap treeMap, String startClazz) { - PHPIdentifierLocation ident; - ArrayList allClassNames = new ArrayList(); - addClassName(treeMap, startClazz, allClassNames); - int i = 0; - while (i < allClassNames.size()) { - String clazz = (String) allClassNames.get(i++); - addClassName(treeMap, clazz, allClassNames); - } - } - - /** - * @param treeMap - * @param clazz - * @param allClassNames - */ - private boolean addClassName(TreeMap treeMap, String clazz, List allClassNames) { - String line; - PHPIdentifierLocation ident; - List list = getLocations(clazz); - if (list == null) { - return false; - } - boolean result = false; - for (int i = 0; i < list.size(); i++) { - ident = (PHPIdentifierLocation) list.get(i); - if (ident.isClass()) { - line = (String) fFileMap.get(ident.getFilename()); - addLine(treeMap, null, line, allClassNames); - result = true; - } - } - return result; - } - - /** - * Adds a line of the index file for function, class, class-method and class-variable names - * - * @param line - */ - public void addLine(TreeMap treeMap, HashMap fileMap, String line, List allClassNames) { - StringTokenizer tokenizer; - String phpFileName = null; - String token; - String identifier = null; - String classname = null; - String offset = null; - PHPIdentifierLocation phpIdentifier = null; - boolean tokenExists = false; - tokenizer = new StringTokenizer(line, "\t"); - // first token contains the filename: - try { - if (tokenizer.hasMoreTokens()) { - phpFileName = tokenizer.nextToken(); - //System.out.println(token); - } else { - return; - } - // all the other tokens are identifiers: - while (tokenizer.hasMoreTokens()) { - token = tokenizer.nextToken(); - //System.out.println(token); - switch (token.charAt(0)) { - case 'c': - // class name - identifier = token.substring(1); - classname = identifier; - phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.CLASS, phpFileName); - break; - case 'd': - // define - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.DEFINE, phpFileName); - break; - case 'e': - // extends - // not in map - identifier = null; - phpIdentifier = null; - if (allClassNames != null) { - String extName = token.substring(1); - if (!allClassNames.contains(extName)) { - allClassNames.add(extName); - } - } - break; - case 'f': - // function name - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.FUNCTION, phpFileName); - break; - case 'g': - // global variable - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.GLOBAL_VARIABLE, phpFileName); - break; - case 'i': - // implements - // not in map - identifier = null; - phpIdentifier = null; - if (allClassNames != null) { - String implName = token.substring(1); - if (!allClassNames.contains(implName)) { - allClassNames.add(implName); - } - } - break; - case 'k': - // constructor function name - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.CONSTRUCTOR, phpFileName); - break; - case 'm': - //method inside a class - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.METHOD, phpFileName, classname); - break; - case 'v': - // variable inside a class - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.VARIABLE, phpFileName, classname); - break; - case 'o': - // offset information - identifier = null; - if (phpIdentifier != null) { - offset = token.substring(1); - phpIdentifier.setOffset(Integer.parseInt(offset)); - } - break; - case 'p': - // PHPdoc offset information - identifier = null; - if (phpIdentifier != null) { - offset = token.substring(1); - phpIdentifier.setPHPDocOffset(Integer.parseInt(offset)); - } - break; - case 'l': - // PHPdoc length information - identifier = null; - if (phpIdentifier != null) { - offset = token.substring(1); - phpIdentifier.setPHPDocLength(Integer.parseInt(offset)); - } - break; - default: - PHPeclipsePlugin.log(IStatus.ERROR, "Unknown token character in IdentifierIndexManager: " + token.charAt(0)); - identifier = null; - phpIdentifier = null; - classname = null; - } - if (identifier != null && phpIdentifier != null) { - tokenExists = true; - ArrayList list = (ArrayList) treeMap.get(identifier); - if (list == null) { - list = new ArrayList(); - list.add(phpIdentifier); - treeMap.put(identifier, list); - } else { - boolean flag = false; - for (int i = 0; i < list.size(); i++) { - if (list.get(i).equals(phpIdentifier)) { - flag = true; - break; - } - } - if (flag == false) { - list.add(phpIdentifier); - } - } - } - } - if (fileMap != null) { - fileMap.put(phpFileName, line); - } - } catch (Throwable e) { - // write to workspace/.metadata/.log file - PHPeclipsePlugin.log(e); - } - // if (tokenExists) { - - // } - } - - /** - * Change the information for a given IFile resource - * - */ - public void changeFile(IFile fileToParse) { - removeFile(fileToParse); - addFile(fileToParse); - } - - /** - * Get a list of all PHPIdentifierLocation object's associated with an identifier - * - * @param identifier - * @return - */ - public List getLocations(String identifier) { - List list=(List) fIndentifierMap.get(identifier); - if (list!=null) { - return list; - } - return new ArrayList(); - } - - /** - * Initialize (i.e. clear) the current index information - * - */ - public void initialize() { - fIndentifierMap = new TreeMap(new StringComparator()); - fFileMap = new HashMap(); - } - - private void readFile() { - FileReader fileReader; - try { - fileReader = new FileReader(fFilename); - BufferedReader bufferedReader = new BufferedReader(fileReader); - String line; - while (bufferedReader.ready()) { - // all entries for one file are in a line - // separated by tabs ! - line = bufferedReader.readLine(); - addLine(line); - } - fileReader.close(); - } catch (FileNotFoundException e) { - // ignore this - // TODO DialogBox which asks the user if she/he likes to build new index? - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - /** - * Remove the information for a given IFile resource - * - */ - public void removeFile(IFile fileToParse) { - // String line = (String) - // fFileMap.get(fileToParse.getLocation().toString()); - String line = (String) fFileMap.get(fileToParse.getProjectRelativePath().toString()); - if (line != null) { - removeLine(line); - } - } - - /** - * Removes a line of the index file for function, class, class-method and class-variable names - * - * @param line - */ - private void removeLine(String line) { - StringTokenizer tokenizer; - String phpFileName = null; - String token; - String identifier = null; - String classname = null; - PHPIdentifier phpIdentifier = null; - boolean tokenExists = false; - tokenizer = new StringTokenizer(line, "\t"); - // first token contains the filename: - if (tokenizer.hasMoreTokens()) { - phpFileName = tokenizer.nextToken(); - //System.out.println(token); - } else { - return; - } - int offset = -1; - // all the other tokens are identifiers: - while (tokenizer.hasMoreTokens()) { - token = tokenizer.nextToken(); - //System.out.println(token); - switch (token.charAt(0)) { - case 'c': - // class name - identifier = token.substring(1); - classname = identifier; - phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.CLASS, phpFileName); - break; - case 'd': - // define - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.DEFINE, phpFileName); - break; - case 'e': - // extends - identifier = null; - phpIdentifier = null; - break; - case 'f': - // function name - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.FUNCTION, phpFileName); - break; - case 'g': - // global variable - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.GLOBAL_VARIABLE, phpFileName); - break; - case 'i': - // implements - identifier = null; - phpIdentifier = null; - break; - case 'k': - // constructor function name - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.CONSTRUCTOR, phpFileName); - break; - case 'm': - //method inside a class - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.METHOD, phpFileName, classname); - break; - case 'o': - // offset information - identifier = null; - break; - case 'p': - // PHPdoc offset information - identifier = null; - break; - case 'l': - // PHPdoc length information - identifier = null; - break; - case 'v': - // variable inside a class - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.VARIABLE, phpFileName, classname); - break; - default: - PHPeclipsePlugin.log(IStatus.ERROR, "Unknown token character in IdentifierIndexManager: " + token.charAt(0)); - identifier = null; - phpIdentifier = null; - classname = null; - } - if (identifier != null && phpIdentifier != null) { - ArrayList list = (ArrayList) fIndentifierMap.get(identifier); - if (list == null) { - } else { - for (int i = 0; i < list.size(); i++) { - if (list.get(i).equals(phpIdentifier)) { - list.remove(i); - break; - } - } - if (list.size() == 0) { - fIndentifierMap.remove(identifier); - } - } - } - } - fFileMap.remove(phpFileName); - } - - /** - * Save the current index information in the projects index file - * - */ - public void writeFile() { - FileWriter fileWriter; - try { - fileWriter = new FileWriter(fFilename); - String line; - Collection collection = fFileMap.values(); - Iterator iterator = collection.iterator(); - while (iterator.hasNext()) { - line = (String) iterator.next(); - fileWriter.write(line + '\n'); - } - fileWriter.close(); - } catch (FileNotFoundException e) { - // ignore exception; project is deleted by user - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - /** - * @param fromKey - * @param toKey - * @return - */ - public SortedMap getIdentifierMap() { - return fIndentifierMap; - } - - synchronized public List getFileList(String filePattern) { - Set set = fFileMap.keySet(); - if (set.isEmpty()) { - return null; - } - Iterator iter = set.iterator(); - ArrayList list = new ArrayList(); - String fileName; - int index; - while (iter.hasNext()) { - fileName = (String) iter.next(); - if ((index = fileName.indexOf(filePattern)) != -1 && fileName.length() == (index + filePattern.length())) { - list.add(fileName); - } - } - return list; - } + public class LineCreator implements ITerminalSymbols { + private Scanner fScanner; + + private int fToken; + + public LineCreator() { + fScanner = new Scanner(true, false, false, false, true, null, null, + true /* taskCaseSensitive */); + } + + /** + * Add the information of the current identifier to the line + * + * @param typeOfIdentifier + * the type of the identifier ('c'lass, 'd'efine, 'f'unction, + * 'm'ethod(class), 'v'ariable(class) 'g'lobal variable) + * @param identifier + * current identifier + * @param line + * Buffer for the current index line + */ + private void addIdentifierInformation(char typeOfIdentifier, + char[] identifier, StringBuffer line) { + line.append('\t'); + line.append(typeOfIdentifier); + line.append(identifier); + // line.append("\to"); // Offset + // line.append(fScanner.getCurrentTokenStartPosition()); + } + + /** + * Add the information of the current identifier to the line + * + * @param typeOfIdentifier + * the type of the identifier ('c'lass, 'd'efine, 'f'unction, + * 'm'ethod(class), 'v'ariable(class) 'g'lobal variable) + * @param identifier + * current identifier + * @param line + * Buffer for the current index line + * @param phpdocOffset + * the offset of the PHPdoc comment if available + * @param phpdocLength + * the length of the PHPdoc comment if available + */ + private void addIdentifierInformation(char typeOfIdentifier, + char[] identifier, StringBuffer line, int phpdocOffset, + int phpdocLength) { + line.append('\t'); + line.append(typeOfIdentifier); + line.append(identifier); + line.append("\to"); // Offset + line.append(fScanner.getCurrentTokenStartPosition()); + if (phpdocOffset >= 0) { + line.append("\tp"); // phpdoc offset + line.append(phpdocOffset); + line.append("\tl"); // phpdoc length + line.append(phpdocLength); + } + } + + private void addClassVariableInformation(char typeOfIdentifier, + char[] identifier, StringBuffer line, int phpdocOffset, + int phpdocLength) { + line.append('\t'); + line.append(typeOfIdentifier); + line.append(identifier); + line.append("\to"); // Offset + // we don't store the '$' in the index for class variables: + line.append(fScanner.getCurrentTokenStartPosition() + 1); + if (phpdocOffset >= 0) { + line.append("\tp"); // phpdoc offset + line.append(phpdocOffset); + line.append("\tl"); // phpdoc length + line.append(phpdocLength); + } + } + + /** + * Get the next token from input + */ + private void getNextToken() throws InvalidInputException { + // try { + fToken = fScanner.getNextToken(); + if (Scanner.DEBUG) { + int currentEndPosition = fScanner.getCurrentTokenEndPosition(); + int currentStartPosition = fScanner + .getCurrentTokenStartPosition(); + System.out.print(currentStartPosition + "," + + currentEndPosition + ": "); + System.out.println(fScanner.toStringAction(fToken)); + } + return; + // } catch (InvalidInputException e) { + // // ignore errors + // // e.printStackTrace(); + // } + // fToken = TokenNameERROR; + } + + private void parseDeclarations(char[] parent, StringBuffer buf, + boolean goBack) { + char[] ident; + char[] classVariable; + int counter = 0; + boolean hasModifiers = false; + int phpdocOffset = -1; + int phpdocLength = -1; + try { + while (fToken != TokenNameEOF && fToken != TokenNameERROR) { + phpdocOffset = -1; + hasModifiers = false; + if (fToken == TokenNameCOMMENT_PHPDOC) { + phpdocOffset = fScanner.getCurrentTokenStartPosition(); + phpdocLength = fScanner.getCurrentTokenEndPosition() + - fScanner.getCurrentTokenStartPosition() + 1; + getNextToken(); + while (fToken == TokenNamestatic + || fToken == TokenNamefinal + || fToken == TokenNamepublic + || fToken == TokenNameprotected + || fToken == TokenNameprivate + || fToken == TokenNameabstract) { + hasModifiers = true; + getNextToken(); + } + if (fToken == TokenNameEOF || fToken == TokenNameERROR) { + break; + } + } + if (fToken == TokenNamefunction) { + getNextToken(); + if (fToken == TokenNameAND) { + getNextToken(); + } + if (fToken == TokenNameIdentifier) { + ident = fScanner.getCurrentIdentifierSource(); + if (parent != null + && equalCharArrays(parent, ident)) { + // constructor function + addIdentifierInformation('k', ident, buf, + phpdocOffset, phpdocLength); + } else { + if (parent != null) { + // class method function + addIdentifierInformation('m', ident, buf, + phpdocOffset, phpdocLength); + } else { + // nested function ?! + addIdentifierInformation('f', ident, buf, + phpdocOffset, phpdocLength); + } + } + getNextToken(); + parseDeclarations(null, buf, true); + } + } else if (fToken == TokenNameclass + || fToken == TokenNameinterface) { + getNextToken(); + if (fToken == TokenNameIdentifier) { + ident = fScanner.getCurrentIdentifierSource(); + addIdentifierInformation('c', ident, buf, + phpdocOffset, phpdocLength); + getNextToken(); + if (fToken == TokenNameextends) { + getNextToken(); + while (fToken == TokenNameIdentifier) { + ident = fScanner + .getCurrentIdentifierSource(); + // extends ident + addIdentifierInformation('e', ident, buf); + getNextToken(); + if (fToken == TokenNameCOMMA) { + getNextToken(); + } + } + } + if (fToken == TokenNameimplements) { + getNextToken(); + while (fToken == TokenNameIdentifier) { + ident = fScanner + .getCurrentIdentifierSource(); + // implements ident + addIdentifierInformation('e', ident, buf); + getNextToken(); + if (fToken == TokenNameCOMMA) { + getNextToken(); + } + } + } + // skip tokens for classname, extends and others + // until we have + // the opening '{' + while (fToken != TokenNameLBRACE + && fToken != TokenNameEOF + && fToken != TokenNameERROR) { + getNextToken(); + } + parseDeclarations(ident, buf, true); + } + } else if (fToken == TokenNamevar || hasModifiers + || fToken == TokenNamestatic + || fToken == TokenNamefinal + || fToken == TokenNamepublic + || fToken == TokenNameprotected + || fToken == TokenNameprivate) { + while (fToken == TokenNamevar + || fToken == TokenNamestatic + || fToken == TokenNamefinal + || fToken == TokenNamepublic + || fToken == TokenNameprotected + || fToken == TokenNameprivate) { + getNextToken(); + } + while (fToken == TokenNameVariable) { + ident = fScanner.getCurrentIdentifierSource(); + classVariable = new char[ident.length - 1]; + System.arraycopy(ident, 1, classVariable, 0, + ident.length - 1); + addClassVariableInformation('v', classVariable, + buf, phpdocOffset, phpdocLength); + getNextToken(); + if (fToken == TokenNameCOMMA) { + getNextToken(); + } + } + } else if (!hasModifiers && fToken == TokenNameIdentifier) { + ident = fScanner.getCurrentIdentifierSource(); + getNextToken(); + if (ident.length == 6 && ident[0] == 'd' + && ident[1] == 'e' && ident[2] == 'f' + && ident[3] == 'i' && ident[4] == 'n' + && ident[5] == 'e') { + if (fToken == TokenNameLPAREN) { + getNextToken(); + if (fToken == TokenNameStringDoubleQuote) { + ident = fScanner + .getCurrentStringLiteralSource(); + addIdentifierInformation('d', ident, buf, + phpdocOffset, phpdocLength); + getNextToken(); + } else if (fToken == TokenNameStringSingleQuote) { + ident = fScanner + .getCurrentStringLiteralSource(); + addIdentifierInformation('d', ident, buf, + phpdocOffset, phpdocLength); + getNextToken(); + } + } + } + } else if (fToken == TokenNameglobal) { + // global variable + while (fToken != TokenNameEOF + && fToken != TokenNameERROR + && fToken != TokenNameSEMICOLON + && fToken != TokenNameLBRACE + && fToken != TokenNameRBRACE) { + getNextToken(); + if (fToken == TokenNameVariable) { + ident = fScanner.getCurrentIdentifierSource(); + addIdentifierInformation('g', ident, buf, + phpdocOffset, phpdocLength); + } + } + } else if (fToken == TokenNameLBRACE) { + getNextToken(); + counter++; + } else if (fToken == TokenNameRBRACE) { + getNextToken(); + --counter; + if (counter == 0 && goBack) { + return; + } + } else { + getNextToken(); + } + } + } catch (InvalidInputException e) { + // ignore errors + } catch (SyntaxError e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + synchronized public void parseIdentifiers(char[] charArray, + StringBuffer buf) { + char[] ident; + String identifier; + int counter = 0; + boolean hasModifiers = false; + int phpdocOffset = -1; + int phpdocLength = -1; + fScanner.setSource(charArray); + fScanner.setPHPMode(false); + fToken = TokenNameEOF; + try { + getNextToken(); + while (fToken != TokenNameEOF) { // && fToken != + // TokenNameERROR) { + phpdocOffset = -1; + hasModifiers = false; + if (fToken == TokenNameCOMMENT_PHPDOC) { + phpdocOffset = fScanner.getCurrentTokenStartPosition(); + phpdocLength = fScanner.getCurrentTokenEndPosition() + - fScanner.getCurrentTokenStartPosition() + 1; + getNextToken(); + while (fToken == TokenNamestatic + || fToken == TokenNamefinal + || fToken == TokenNamepublic + || fToken == TokenNameprotected + || fToken == TokenNameprivate + || fToken == TokenNameabstract) { + hasModifiers = true; + getNextToken(); + } + if (fToken == TokenNameEOF || fToken == TokenNameERROR) { + break; + } + } + if (fToken == TokenNamefunction) { + getNextToken(); + if (fToken == TokenNameAND) { + getNextToken(); + } + if (fToken == TokenNameIdentifier) { + ident = fScanner.getCurrentIdentifierSource(); + addIdentifierInformation('f', ident, buf, + phpdocOffset, phpdocLength); + getNextToken(); + parseDeclarations(null, buf, true); + } + } else if (fToken == TokenNameclass + || fToken == TokenNameinterface) { + getNextToken(); + if (fToken == TokenNameIdentifier) { + ident = fScanner.getCurrentIdentifierSource(); + addIdentifierInformation('c', ident, buf, + phpdocOffset, phpdocLength); + getNextToken(); + if (fToken == TokenNameextends) { + getNextToken(); + while (fToken == TokenNameIdentifier) { + ident = fScanner + .getCurrentIdentifierSource(); + // extends ident + addIdentifierInformation('e', ident, buf); + getNextToken(); + if (fToken == TokenNameCOMMA) { + getNextToken(); + } + } + } + if (fToken == TokenNameimplements) { + getNextToken(); + while (fToken == TokenNameIdentifier) { + ident = fScanner + .getCurrentIdentifierSource(); + // implements ident + addIdentifierInformation('e', ident, buf); + getNextToken(); + if (fToken == TokenNameCOMMA) { + getNextToken(); + } + } + } + // skip fTokens for classname, extends and others + // until we have + // the opening '{' + while (fToken != TokenNameLBRACE + && fToken != TokenNameEOF + && fToken != TokenNameERROR) { + getNextToken(); + } + parseDeclarations(ident, buf, true); + } + } else if (fToken == TokenNameVariable) { + // global variable + ident = fScanner.getCurrentIdentifierSource(); + addIdentifierInformation('g', ident, buf, phpdocOffset, + phpdocLength); + getNextToken(); + } else if (!hasModifiers && fToken == TokenNameIdentifier) { + ident = fScanner.getCurrentIdentifierSource(); + getNextToken(); + if (ident.length == 6 && ident[0] == 'd' + && ident[1] == 'e' && ident[2] == 'f' + && ident[3] == 'i' && ident[4] == 'n' + && ident[5] == 'e') { + if (fToken == TokenNameLPAREN) { + getNextToken(); + if (fToken == TokenNameStringDoubleQuote) { + ident = fScanner + .getCurrentStringLiteralSource(); + addIdentifierInformation('d', ident, buf, + phpdocOffset, phpdocLength); + getNextToken(); + } else if (fToken == TokenNameStringSingleQuote) { + ident = fScanner + .getCurrentStringLiteralSource(); + addIdentifierInformation('d', ident, buf, + phpdocOffset, phpdocLength); + getNextToken(); + } + } + } + } else { + getNextToken(); + } + } + } catch (InvalidInputException e) { + // ignore errors + } catch (SyntaxError e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + class StringComparator implements Comparator { + public int compare(Object o1, Object o2) { + String s1 = (String) o1; + String s2 = (String) o2; + return s1.compareTo(s2); + // return s1.toUpperCase().compareTo(s2.toUpperCase()); + } + + public boolean equals(Object o) { + String s = (String) o; + return compare(this, o) == 0; + } + } + + private HashMap fFileMap; + + private String fFilename; + + private TreeMap fIndentifierMap; + + public IdentifierIndexManager(String filename) { + fFilename = filename; + initialize(); + readFile(); + } + + /** + * Check if 2 char arrays are equal + * + * @param a + * @param b + * @return + */ + private static boolean equalCharArrays(char[] a, char[] b) { + if (a.length != b.length) { + return false; + } + for (int i = 0; i < b.length; i++) { + if (a[i] != b[i]) { + return false; + } + } + return true; + } + + public LineCreator createLineCreator() { + return new LineCreator(); + } + + /** + * Add the information for a given IFile resource + * + */ + public void addFile(IFile fileToParse) { + // InputStream iStream; + LineCreator lineCreator = createLineCreator(); + try { + addInputStream(new BufferedInputStream(fileToParse.getContents()), + fileToParse.getProjectRelativePath().toString(), + lineCreator); + } catch (CoreException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } + + /** + * @param fileToParse + * @param lineCreator + * @throws CoreException + */ + public void addInputStream(InputStream stream, String filePath, + LineCreator lineCreator) throws CoreException { + try { + StringBuffer lineBuffer = new StringBuffer(); + lineBuffer.append(filePath); + int lineLength = lineBuffer.length(); + lineCreator.parseIdentifiers(Util.getInputStreamAsCharArray(stream, + -1, null), lineBuffer); + // if (lineLength != lineBuffer.length()) { + // always add the file for Open Include Action + addLine(lineBuffer.toString()); + // } + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (stream != null) { + stream.close(); + } + } catch (IOException e) { + } + } + } + + /** + * Adds a line of the index file for function, class, class-method and + * class-variable names + * + * @param line + */ + private void addLine(String line) { + addLine(fIndentifierMap, fFileMap, line, null); + } + + public TreeMap getIdentifiers(IFile file) { + TreeMap treeMap = new TreeMap(new StringComparator()); + addIdentifiers(treeMap, file); + return treeMap; + } + + public TreeMap getIdentifiers(String startClazz) { + TreeMap treeMap = new TreeMap(new StringComparator()); + addIdentifiers(treeMap, startClazz); + return treeMap; + } + + public void addIdentifiers(TreeMap treeMap, IFile file) { + String line = (String) fFileMap.get(file.getProjectRelativePath() + .toString()); + if (line != null) { + PHPIdentifierLocation ident; + ArrayList allClassNames = new ArrayList(); + addLine(treeMap, null, line, allClassNames); + int i = 0; + while (i < allClassNames.size()) { + String clazz = (String) allClassNames.get(i++); + addClassName(treeMap, clazz, allClassNames); + } + } + } + + public void addIdentifiers(TreeMap treeMap, String startClazz) { + PHPIdentifierLocation ident; + ArrayList allClassNames = new ArrayList(); + addClassName(treeMap, startClazz, allClassNames); + int i = 0; + while (i < allClassNames.size()) { + String clazz = (String) allClassNames.get(i++); + addClassName(treeMap, clazz, allClassNames); + } + } + + /** + * @param treeMap + * @param clazz + * @param allClassNames + */ + private boolean addClassName(TreeMap treeMap, String clazz, + List allClassNames) { + String line; + PHPIdentifierLocation ident; + List list = getLocations(clazz); + if (list == null) { + return false; + } + boolean result = false; + for (int i = 0; i < list.size(); i++) { + ident = (PHPIdentifierLocation) list.get(i); + if (ident.isClass()) { + line = (String) fFileMap.get(ident.getFilename()); + addLine(treeMap, null, line, allClassNames); + result = true; + } + } + return result; + } + + /** + * Adds a line of the index file for function, class, class-method and + * class-variable names + * + * @param line + */ + public void addLine(TreeMap treeMap, HashMap fileMap, String line, + List allClassNames) { + StringTokenizer tokenizer; + String phpFileName = null; + String token; + String identifier = null; + String classname = null; + String offset = null; + PHPIdentifierLocation phpIdentifier = null; + boolean tokenExists = false; + tokenizer = new StringTokenizer(line, "\t"); + // first token contains the filename: + try { + if (tokenizer.hasMoreTokens()) { + phpFileName = tokenizer.nextToken(); + // System.out.println(token); + } else { + return; + } + // all the other tokens are identifiers: + while (tokenizer.hasMoreTokens()) { + token = tokenizer.nextToken(); + // System.out.println(token); + switch (token.charAt(0)) { + case 'c': + // class name + identifier = token.substring(1); + classname = identifier; + phpIdentifier = new PHPIdentifierLocation(identifier, + PHPIdentifier.CLASS, phpFileName); + break; + case 'd': + // define + identifier = token.substring(1); + phpIdentifier = new PHPIdentifierLocation(identifier, + PHPIdentifier.DEFINE, phpFileName); + break; + case 'e': + // extends + // not in map + identifier = null; + phpIdentifier = null; + if (allClassNames != null) { + String extName = token.substring(1); + if (!allClassNames.contains(extName)) { + allClassNames.add(extName); + } + } + break; + case 'f': + // function name + identifier = token.substring(1); + phpIdentifier = new PHPIdentifierLocation(identifier, + PHPIdentifier.FUNCTION, phpFileName); + break; + case 'g': + // global variable + identifier = token.substring(1); + phpIdentifier = new PHPIdentifierLocation(identifier, + PHPIdentifier.GLOBAL_VARIABLE, phpFileName); + break; + case 'i': + // implements + // not in map + identifier = null; + phpIdentifier = null; + if (allClassNames != null) { + String implName = token.substring(1); + if (!allClassNames.contains(implName)) { + allClassNames.add(implName); + } + } + break; + case 'k': + // constructor function name + identifier = token.substring(1); + phpIdentifier = new PHPIdentifierLocation(identifier, + PHPIdentifier.CONSTRUCTOR, phpFileName); + break; + case 'm': + // method inside a class + identifier = token.substring(1); + phpIdentifier = new PHPIdentifierLocation(identifier, + PHPIdentifier.METHOD, phpFileName, classname); + break; + case 'v': + // variable inside a class + identifier = token.substring(1); + phpIdentifier = new PHPIdentifierLocation(identifier, + PHPIdentifier.VARIABLE, phpFileName, classname); + break; + case 'o': + // offset information + identifier = null; + if (phpIdentifier != null) { + offset = token.substring(1); + phpIdentifier.setOffset(Integer.parseInt(offset)); + } + break; + case 'p': + // PHPdoc offset information + identifier = null; + if (phpIdentifier != null) { + offset = token.substring(1); + phpIdentifier.setPHPDocOffset(Integer.parseInt(offset)); + } + break; + case 'l': + // PHPdoc length information + identifier = null; + if (phpIdentifier != null) { + offset = token.substring(1); + phpIdentifier.setPHPDocLength(Integer.parseInt(offset)); + } + break; + default: + PHPeclipsePlugin.log(IStatus.ERROR, + "Unknown token character in IdentifierIndexManager: " + + token.charAt(0)); + identifier = null; + phpIdentifier = null; + classname = null; + } + if (identifier != null && phpIdentifier != null) { + tokenExists = true; + ArrayList list = (ArrayList) treeMap.get(identifier); + if (list == null) { + list = new ArrayList(); + list.add(phpIdentifier); + treeMap.put(identifier, list); + } else { + boolean flag = false; + for (int i = 0; i < list.size(); i++) { + if (list.get(i).equals(phpIdentifier)) { + flag = true; + break; + } + } + if (flag == false) { + list.add(phpIdentifier); + } + } + } + } + if (fileMap != null) { + fileMap.put(phpFileName, line); + } + } catch (Throwable e) { + // write to workspace/.metadata/.log file + PHPeclipsePlugin.log(e); + } + // if (tokenExists) { + + // } + } + + /** + * Change the information for a given IFile resource + * + */ + public void changeFile(IFile fileToParse) { + removeFile(fileToParse); + addFile(fileToParse); + } + + /** + * Get a list of all PHPIdentifierLocation object's associated with an + * identifier + * + * @param identifier + * @return + */ + public List getLocations(String identifier) { + List list = (List) fIndentifierMap.get(identifier); + if (list != null) { + return list; + } + return new ArrayList(); + } + + /** + * Initialize (i.e. clear) the current index information + * + */ + public void initialize() { + fIndentifierMap = new TreeMap(new StringComparator()); + fFileMap = new HashMap(); + } + + private void readFile() { + FileReader fileReader; + try { + fileReader = new FileReader(fFilename); + BufferedReader bufferedReader = new BufferedReader(fileReader); + String line; + while (bufferedReader.ready()) { + // all entries for one file are in a line + // separated by tabs ! + line = bufferedReader.readLine(); + addLine(line); + } + fileReader.close(); + } catch (FileNotFoundException e) { + // ignore this + // TODO DialogBox which asks the user if she/he likes to build new + // index? + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + /** + * Remove the information for a given IFile resource + * + */ + public void removeFile(IFile fileToParse) { + // String line = (String) + // fFileMap.get(fileToParse.getLocation().toString()); + String line = (String) fFileMap.get(fileToParse + .getProjectRelativePath().toString()); + if (line != null) { + removeLine(line); + } + } + + /** + * Removes a line of the index file for function, class, class-method and + * class-variable names + * + * @param line + */ + private void removeLine(String line) { + StringTokenizer tokenizer; + String phpFileName = null; + String token; + String identifier = null; + String classname = null; + PHPIdentifier phpIdentifier = null; + boolean tokenExists = false; + tokenizer = new StringTokenizer(line, "\t"); + // first token contains the filename: + if (tokenizer.hasMoreTokens()) { + phpFileName = tokenizer.nextToken(); + // System.out.println(token); + } else { + return; + } + int offset = -1; + // all the other tokens are identifiers: + while (tokenizer.hasMoreTokens()) { + token = tokenizer.nextToken(); + // System.out.println(token); + switch (token.charAt(0)) { + case 'c': + // class name + identifier = token.substring(1); + classname = identifier; + phpIdentifier = new PHPIdentifierLocation(identifier, + PHPIdentifier.CLASS, phpFileName); + break; + case 'd': + // define + identifier = token.substring(1); + phpIdentifier = new PHPIdentifierLocation(identifier, + PHPIdentifier.DEFINE, phpFileName); + break; + case 'e': + // extends + identifier = null; + phpIdentifier = null; + break; + case 'f': + // function name + identifier = token.substring(1); + phpIdentifier = new PHPIdentifierLocation(identifier, + PHPIdentifier.FUNCTION, phpFileName); + break; + case 'g': + // global variable + identifier = token.substring(1); + phpIdentifier = new PHPIdentifierLocation(identifier, + PHPIdentifier.GLOBAL_VARIABLE, phpFileName); + break; + case 'i': + // implements + identifier = null; + phpIdentifier = null; + break; + case 'k': + // constructor function name + identifier = token.substring(1); + phpIdentifier = new PHPIdentifierLocation(identifier, + PHPIdentifier.CONSTRUCTOR, phpFileName); + break; + case 'm': + // method inside a class + identifier = token.substring(1); + phpIdentifier = new PHPIdentifierLocation(identifier, + PHPIdentifier.METHOD, phpFileName, classname); + break; + case 'o': + // offset information + identifier = null; + break; + case 'p': + // PHPdoc offset information + identifier = null; + break; + case 'l': + // PHPdoc length information + identifier = null; + break; + case 'v': + // variable inside a class + identifier = token.substring(1); + phpIdentifier = new PHPIdentifierLocation(identifier, + PHPIdentifier.VARIABLE, phpFileName, classname); + break; + default: + PHPeclipsePlugin.log(IStatus.ERROR, + "Unknown token character in IdentifierIndexManager: " + + token.charAt(0)); + identifier = null; + phpIdentifier = null; + classname = null; + } + if (identifier != null && phpIdentifier != null) { + ArrayList list = (ArrayList) fIndentifierMap.get(identifier); + if (list == null) { + } else { + for (int i = 0; i < list.size(); i++) { + if (list.get(i).equals(phpIdentifier)) { + list.remove(i); + break; + } + } + if (list.size() == 0) { + fIndentifierMap.remove(identifier); + } + } + } + } + fFileMap.remove(phpFileName); + } + + /** + * Save the current index information in the projects index file + * + */ + public void writeFile() { + FileWriter fileWriter; + try { + fileWriter = new FileWriter(fFilename); + String line; + Collection collection = fFileMap.values(); + Iterator iterator = collection.iterator(); + while (iterator.hasNext()) { + line = (String) iterator.next(); + fileWriter.write(line + '\n'); + } + fileWriter.close(); + } catch (FileNotFoundException e) { + // ignore exception; project is deleted by user + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + /** + * @param fromKey + * @param toKey + * @return + */ + public SortedMap getIdentifierMap() { + return fIndentifierMap; + } + + synchronized public List getFileList(String filePattern) { + Set set = fFileMap.keySet(); + if (set.isEmpty()) { + return null; + } + Iterator iter = set.iterator(); + ArrayList list = new ArrayList(); + String fileName; + int index; + while (iter.hasNext()) { + fileName = (String) iter.next(); + if ((index = fileName.indexOf(filePattern)) != -1 + && fileName.length() == (index + filePattern.length())) { + list.add(fileName); + } + } + return list; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/PHPIdentifierLocation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/PHPIdentifierLocation.java index 57886e6..afad5af 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/PHPIdentifierLocation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/PHPIdentifierLocation.java @@ -3,184 +3,191 @@ package net.sourceforge.phpeclipse.builder; import net.sourceforge.phpeclipse.obfuscator.PHPIdentifier; /** - * + * */ public class PHPIdentifierLocation extends PHPIdentifier implements Comparable { - final public static int UNDEFINED_MATCH = 0; - final public static int PATTERN_MATCH = 1; - final public static int EXACT_MATCH = 2; - - private int fMatch; - - private String fClassname; - - private String fFilename; - - private int fOffset; - - private int fPHPDocLength; - - private int fPHPDocOffset; - - private String fUsage; - - public PHPIdentifierLocation(String identifier, int type, String filename) { - this(identifier, type, filename, null); - } - - public PHPIdentifierLocation(String identifier, int type, String filename, - String classname) { - super(identifier, type); - fFilename = filename; - fClassname = classname; - fOffset = -1; - fPHPDocLength = -1; - fPHPDocOffset = -1; - fUsage = null; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object obj) { - if (!(obj instanceof PHPIdentifierLocation)) { - return false; - } - return super.equals(obj) - && fFilename.equals(((PHPIdentifierLocation) obj).fFilename); - } - - /** - * @return - */ - public String getClassname() { - return fClassname; - } - - /** - * @return - */ - public String getFilename() { - return fFilename; - } - - /** - * @return - */ - public int getOffset() { - return fOffset; - } - - /** - * @return - */ - public int getPHPDocLength() { - return fPHPDocLength; - } - - /** - * @return - */ - public int getPHPDocOffset() { - return fPHPDocOffset; - } - - /** - * @return - */ - public String getUsage() { - return fUsage; - } - - /** - * @param string - */ - public void setClassname(String string) { - fClassname = string; - } - - /** - * @param string - */ - public void setFilename(String string) { - fFilename = string; - } - - /** - * @param i - */ - public void setOffset(int i) { - fOffset = i; - } - - /** - * @param i - */ - public void setPHPDocLength(int i) { - fPHPDocLength = i; - } - - /** - * @param i - */ - public void setPHPDocOffset(int i) { - fPHPDocOffset = i; - } - - /** - * @param string - */ - public void setUsage(String string) { - fUsage = string; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - public String toString() { - String result=null; - switch (fMatch) { - case UNDEFINED_MATCH: - result = " ["; - break; - case PATTERN_MATCH: - result = " [pattern include]["; - break; - case EXACT_MATCH: - result = " [exact include]["; - break; - default: - result = ""; - } - return super.toString() + result + fFilename+"]"; - } - - /* (non-Javadoc) - * @see java.lang.Comparable#compareTo(java.lang.Object) - */ - public int compareTo(Object o) { - PHPIdentifierLocation i = (PHPIdentifierLocation)o; - if (fMatch>i.fMatch) { - return -1; - } else if (fMatch i.fMatch) { + return -1; + } else if (fMatch < i.fMatch) { + return 1; + } + return fFilename.compareTo(i.fFilename); + } + + /** + * @return Returns the match. + */ + public int getMatch() { + return fMatch; + } + + /** + * @param match + * The match to set. + */ + public void setMatch(int match) { + fMatch = match; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorIgnoreSet.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorIgnoreSet.java index eef0d1b..3c323aa 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorIgnoreSet.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorIgnoreSet.java @@ -35,36 +35,39 @@ import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** - * ObfuscatorIgnoreSet manages a collection of templates and makes them - * persistent. + * ObfuscatorIgnoreSet manages a collection of templates and + * makes them persistent. */ public class ObfuscatorIgnoreSet { - // private static class TemplateComparator implements Comparator { - // public int compare(Object arg0, Object arg1) { - // if (arg0 == arg1) - // return 0; + // private static class TemplateComparator implements Comparator { + // public int compare(Object arg0, Object arg1) { + // if (arg0 == arg1) + // return 0; // - // if (arg0 == null) - // return -1; + // if (arg0 == null) + // return -1; // - // Template template0= (Template) arg0; - // Template template1= (Template) arg1; + // Template template0= (Template) arg0; + // Template template1= (Template) arg1; // - // return template0.getName().compareTo(template1.getName()); - // } - // } + // return template0.getName().compareTo(template1.getName()); + // } + // } private static final String TEMPLATE_TAG = "ignore"; //$NON-NLS-1$ - // private static final String NAME_ATTRIBUTE= "name"; //$NON-NLS-1$ - // private static final String DESCRIPTION_ATTRIBUTE= "description"; //$NON-NLS-1$ - // private static final String CONTEXT_ATTRIBUTE= "context"; //$NON-NLS-1$ - // private static final String ENABLED_ATTRIBUTE= "enabled"; //$NON-NLS-1$ - // private List fTemplates= new ArrayList(); + // private static final String NAME_ATTRIBUTE= "name"; //$NON-NLS-1$ + // private static final String DESCRIPTION_ATTRIBUTE= "description"; + // //$NON-NLS-1$ + // private static final String CONTEXT_ATTRIBUTE= "context"; //$NON-NLS-1$ + // private static final String ENABLED_ATTRIBUTE= "enabled"; //$NON-NLS-1$ + + // private List fTemplates= new ArrayList(); private HashMap fIdentifierMap = new HashMap(); - // private Comparator fTemplateComparator= new TemplateComparator(); - // private Template[] fSortedTemplates= new Template[0]; + + // private Comparator fTemplateComparator= new TemplateComparator(); + // private Template[] fSortedTemplates= new Template[0]; /** * Convenience method for reading templates from a file. @@ -95,8 +98,8 @@ public class ObfuscatorIgnoreSet { */ public void addFromStream(InputStream stream) throws CoreException { try { - DocumentBuilderFactory factory = - DocumentBuilderFactory.newInstance(); + DocumentBuilderFactory factory = DocumentBuilderFactory + .newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document document = parser.parse(new InputSource(stream)); NodeList elements = document.getElementsByTagName(TEMPLATE_TAG); @@ -109,15 +112,20 @@ public class ObfuscatorIgnoreSet { if (attributes == null) continue; - // String name= getAttributeValue(attributes, NAME_ATTRIBUTE); - // String description= getAttributeValue(attributes, DESCRIPTION_ATTRIBUTE); - // String context= getAttributeValue(attributes, CONTEXT_ATTRIBUTE); - // Node enabledNode= attributes.getNamedItem(ENABLED_ATTRIBUTE); + // String name= getAttributeValue(attributes, NAME_ATTRIBUTE); + // String description= getAttributeValue(attributes, + // DESCRIPTION_ATTRIBUTE); + // String context= getAttributeValue(attributes, + // CONTEXT_ATTRIBUTE); + // Node enabledNode= attributes.getNamedItem(ENABLED_ATTRIBUTE); - // if (name == null || description == null || context == null) - // throw new SAXException(ObfuscatorMessages.getString("TemplateSet.error.missing.attribute")); //$NON-NLS-1$ + // if (name == null || description == null || context == null) + // throw new + // SAXException(ObfuscatorMessages.getString("TemplateSet.error.missing.attribute")); + // //$NON-NLS-1$ - // boolean enabled= true; //(enabledNode == null) || (enabledNode.getNodeValue().equals("true")); //$NON-NLS-1$ + // boolean enabled= true; //(enabledNode == null) || + // (enabledNode.getNodeValue().equals("true")); //$NON-NLS-1$ StringBuffer buffer = new StringBuffer(); NodeList children = node.getChildNodes(); @@ -127,13 +135,15 @@ public class ObfuscatorIgnoreSet { buffer.append(value); } String pattern = buffer.toString().trim(); - fIdentifierMap.put(pattern, new PHPIdentifier(pattern, PHPIdentifier.VARIABLE) ); - // Template template= new Template(name, description, context, pattern); - // template.setEnabled(enabled); - // add(template); + fIdentifierMap.put(pattern, new PHPIdentifier(pattern, + PHPIdentifier.VARIABLE)); + // Template template= new Template(name, description, context, + // pattern); + // template.setEnabled(enabled); + // add(template); } - // sort(); + // sort(); } catch (ParserConfigurationException e) { throwReadException(e); @@ -178,43 +188,48 @@ public class ObfuscatorIgnoreSet { */ public void saveToStream(OutputStream stream) throws CoreException { try { - DocumentBuilderFactory factory = - DocumentBuilderFactory.newInstance(); + DocumentBuilderFactory factory = DocumentBuilderFactory + .newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); - Node root = document.createElement("obfuscator"); // $NON-NLS-1$ //$NON-NLS-1$ + Node root = document.createElement("obfuscator"); // $NON-NLS-1$ + // //$NON-NLS-1$ document.appendChild(root); Iterator iter = fIdentifierMap.keySet().iterator(); while (iter.hasNext()) { - // for (int i= 0; i != fTemplates.size(); i++) { - // Template template= (Template) fTemplates.get(i); + // for (int i= 0; i != fTemplates.size(); i++) { + // Template template= (Template) fTemplates.get(i); - Node node = document.createElement("ignore"); // $NON-NLS-1$ //$NON-NLS-1$ + Node node = document.createElement("ignore"); // $NON-NLS-1$ + // //$NON-NLS-1$ root.appendChild(node); - // NamedNodeMap attributes= node.getAttributes(); + // NamedNodeMap attributes= node.getAttributes(); // - // Attr name= document.createAttribute(NAME_ATTRIBUTE); - // name.setValue(template.getName()); - // attributes.setNamedItem(name); + // Attr name= document.createAttribute(NAME_ATTRIBUTE); + // name.setValue(template.getName()); + // attributes.setNamedItem(name); // - // Attr description= document.createAttribute(DESCRIPTION_ATTRIBUTE); - // description.setValue(template.getDescription()); - // attributes.setNamedItem(description); + // Attr description= + // document.createAttribute(DESCRIPTION_ATTRIBUTE); + // description.setValue(template.getDescription()); + // attributes.setNamedItem(description); // - // Attr context= document.createAttribute(CONTEXT_ATTRIBUTE); - // context.setValue(template.getContextTypeName()); - // attributes.setNamedItem(context); + // Attr context= document.createAttribute(CONTEXT_ATTRIBUTE); + // context.setValue(template.getContextTypeName()); + // attributes.setNamedItem(context); // - // Attr enabled= document.createAttribute(ENABLED_ATTRIBUTE); - // enabled.setValue(template.isEnabled() ? "true" : "false"); //$NON-NLS-1$ //$NON-NLS-2$ - // attributes.setNamedItem(enabled); + // Attr enabled= document.createAttribute(ENABLED_ATTRIBUTE); + // enabled.setValue(template.isEnabled() ? "true" : "false"); + // //$NON-NLS-1$ //$NON-NLS-2$ + // attributes.setNamedItem(enabled); Text pattern = document.createTextNode((String) iter.next()); node.appendChild(pattern); } - Transformer transformer=TransformerFactory.newInstance().newTransformer(); + Transformer transformer = TransformerFactory.newInstance() + .newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$ transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$ DOMSource source = new DOMSource(document); @@ -226,98 +241,104 @@ public class ObfuscatorIgnoreSet { throwWriteException(e); } catch (TransformerException e) { throwWriteException(e); - } -// OutputFormat format = new OutputFormat(); -// format.setPreserveSpace(true); -// Serializer serializer = SerializerFactory.getSerializerFactory("xml").makeSerializer(stream, format); //$NON-NLS-1$ -// serializer.asDOMSerializer().serialize(document); -// -// } catch (ParserConfigurationException e) { -// throwWriteException(e); -// } catch (IOException e) { -// throwWriteException(e); -// } + } + // OutputFormat format = new OutputFormat(); + // format.setPreserveSpace(true); + // Serializer serializer = + // SerializerFactory.getSerializerFactory("xml").makeSerializer(stream, + // format); //$NON-NLS-1$ + // serializer.asDOMSerializer().serialize(document); + // + // } catch (ParserConfigurationException e) { + // throwWriteException(e); + // } catch (IOException e) { + // throwWriteException(e); + // } } private static void throwReadException(Throwable t) throws CoreException { PHPeclipsePlugin.log(t); - // IStatus status= new JavaUIStatus(JavaStatusConstants.TEMPLATE_IO_EXCEPTION, - // ObfuscatorMessages.getString("TemplateSet.error.read"), t); //$NON-NLS-1$ - // throw new JavaUIException(status); + // IStatus status= new + // JavaUIStatus(JavaStatusConstants.TEMPLATE_IO_EXCEPTION, + // ObfuscatorMessages.getString("TemplateSet.error.read"), t); + // //$NON-NLS-1$ + // throw new JavaUIException(status); } private static void throwWriteException(Throwable t) throws CoreException { PHPeclipsePlugin.log(t); - // IStatus status= new JavaUIStatus(JavaStatusConstants.TEMPLATE_IO_EXCEPTION, - // ObfuscatorMessages.getString("TemplateSet.error.write"), t); //$NON-NLS-1$ - // throw new JavaUIException(status); + // IStatus status= new + // JavaUIStatus(JavaStatusConstants.TEMPLATE_IO_EXCEPTION, + // ObfuscatorMessages.getString("TemplateSet.error.write"), t); + // //$NON-NLS-1$ + // throw new JavaUIException(status); } /** * Adds a template to the set. */ - // public void add(Template template) { - // if (exists(template)) - // return; // ignore duplicate + // public void add(Template template) { + // if (exists(template)) + // return; // ignore duplicate // - // fTemplates.add(template); - // sort(); - // } - - // private boolean exists(Template template) { - // for (Iterator iterator = fTemplates.iterator(); iterator.hasNext();) { - // Template anotherTemplate = (Template) iterator.next(); + // fTemplates.add(template); + // sort(); + // } + // private boolean exists(Template template) { + // for (Iterator iterator = fTemplates.iterator(); iterator.hasNext();) { + // Template anotherTemplate = (Template) iterator.next(); // - // if (template.equals(anotherTemplate)) - // return true; - // } + // if (template.equals(anotherTemplate)) + // return true; + // } // - // return false; - // } + // return false; + // } // - // /** - // * Removes a template to the set. - // */ - // public void remove(Template template) { - // fTemplates.remove(template); - // sort(); - // } + // /** + // * Removes a template to the set. + // */ + // public void remove(Template template) { + // fTemplates.remove(template); + // sort(); + // } // - /** - * Empties the set. - */ - public void clear() { - fIdentifierMap.clear(); - // fTemplates.clear(); - // sort(); - } + /** + * Empties the set. + */ + public void clear() { + fIdentifierMap.clear(); + // fTemplates.clear(); + // sort(); + } + // - // /** - // * Returns all templates. - // */ - // public Template[] getTemplates() { - // return (Template[]) fTemplates.toArray(new Template[fTemplates.size()]); - // } + // /** + // * Returns all templates. + // */ + // public Template[] getTemplates() { + // return (Template[]) fTemplates.toArray(new Template[fTemplates.size()]); + // } /** * Returns all templates with a given name. */ - // public Template[] getTemplates(String name) { - // ArrayList res= new ArrayList(); - // for (Iterator iterator= fTemplates.iterator(); iterator.hasNext();) { - // Template curr= (Template) iterator.next(); - // if (curr.getName().equals(name)) { - // res.add(curr); - // } - // } - // return (Template[]) res.toArray(new Template[res.size()]); - // } + // public Template[] getTemplates(String name) { + // ArrayList res= new ArrayList(); + // for (Iterator iterator= fTemplates.iterator(); iterator.hasNext();) { + // Template curr= (Template) iterator.next(); + // if (curr.getName().equals(name)) { + // res.add(curr); + // } + // } + // return (Template[]) res.toArray(new Template[res.size()]); + // } // - // private void sort() { - // fSortedTemplates= (Template[]) fTemplates.toArray(new Template[fTemplates.size()]); - // Arrays.sort(fSortedTemplates, fTemplateComparator); - // } - + // private void sort() { + // fSortedTemplates= (Template[]) fTemplates.toArray(new + // Template[fTemplates.size()]); + // Arrays.sort(fSortedTemplates, fTemplateComparator); + // } /** * @return */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorIgnores.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorIgnores.java index c713805..46a585e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorIgnores.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorIgnores.java @@ -19,97 +19,101 @@ import org.eclipse.jface.dialogs.ErrorDialog; */ public class ObfuscatorIgnores extends ObfuscatorIgnoreSet { - private static final String DEFAULT_FILE = "default-obfuscator.xml"; //$NON-NLS-1$ - private static final String TEMPLATE_FILE = "obfuscator.xml"; //$NON-NLS-1$ + private static final String DEFAULT_FILE = "default-obfuscator.xml"; //$NON-NLS-1$ + + private static final String TEMPLATE_FILE = "obfuscator.xml"; //$NON-NLS-1$ + + /** Singleton. */ + private static ObfuscatorIgnores fgIgnores; - /** Singleton. */ - private static ObfuscatorIgnores fgIgnores; private IProject fProject; - public ObfuscatorIgnores(IProject project) { - fProject = project; - try { - File templateFile = getTemplateFile(); - if (templateFile.exists()) { - addFromFile(templateFile); - } else { - addFromStream(getDefaultsAsStream()); - saveToFile(templateFile); - } - - } catch (CoreException e) { - PHPeclipsePlugin.log(e); - ErrorDialog.openError(null, ObfuscatorMessages.getString("Obfuscator.error.title"), //$NON-NLS-1$ - e.getMessage(), e.getStatus()); - - clear(); - } - } - /** - * Returns an instance of templates. - */ -// public static ObfuscatorIgnores getInstance() { -// if (fgIgnores == null) -// fgIgnores = create(); -// -// return fgIgnores; -// } -// -// private static ObfuscatorIgnores create() { -// ObfuscatorIgnores templates = new ObfuscatorIgnores(); -// -// try { -// File templateFile = getTemplateFile(); -// if (templateFile.exists()) { -// templates.addFromFile(templateFile); -// } else { -// templates.addFromStream(getDefaultsAsStream()); -// templates.saveToFile(templateFile); -// } -// -// } catch (CoreException e) { -// PHPeclipsePlugin.log(e); -// ErrorDialog.openError(null, ObfuscatorMessages.getString("Templates.error.title"), //$NON-NLS-1$ -// e.getMessage(), e.getStatus()); -// -// templates.clear(); -// } -// -// return templates; -// } - - /** - * Resets the template set. - */ - public void reset() throws CoreException { - clear(); - addFromFile(getTemplateFile()); - } - - /** - * Resets the template set with the default templates. - */ - public void restoreDefaults() throws CoreException { - clear(); - addFromStream(getDefaultsAsStream()); - } - - /** - * Saves the template set. - */ - public void save() throws CoreException { - saveToFile(getTemplateFile()); - } - - private InputStream getDefaultsAsStream() { - return ObfuscatorIgnores.class.getResourceAsStream(DEFAULT_FILE); - } - - private File getTemplateFile() { - IPath path = fProject.getLocation(); - // PHPeclipsePlugin.getDefault().getStateLocation(); - path = path.append(TEMPLATE_FILE); - - return path.toFile(); - } + public ObfuscatorIgnores(IProject project) { + fProject = project; + try { + File templateFile = getTemplateFile(); + if (templateFile.exists()) { + addFromFile(templateFile); + } else { + addFromStream(getDefaultsAsStream()); + saveToFile(templateFile); + } + + } catch (CoreException e) { + PHPeclipsePlugin.log(e); + ErrorDialog.openError(null, ObfuscatorMessages + .getString("Obfuscator.error.title"), //$NON-NLS-1$ + e.getMessage(), e.getStatus()); + + clear(); + } + } + + /** + * Returns an instance of templates. + */ + // public static ObfuscatorIgnores getInstance() { + // if (fgIgnores == null) + // fgIgnores = create(); + // + // return fgIgnores; + // } + // + // private static ObfuscatorIgnores create() { + // ObfuscatorIgnores templates = new ObfuscatorIgnores(); + // + // try { + // File templateFile = getTemplateFile(); + // if (templateFile.exists()) { + // templates.addFromFile(templateFile); + // } else { + // templates.addFromStream(getDefaultsAsStream()); + // templates.saveToFile(templateFile); + // } + // + // } catch (CoreException e) { + // PHPeclipsePlugin.log(e); + // ErrorDialog.openError(null, + // ObfuscatorMessages.getString("Templates.error.title"), //$NON-NLS-1$ + // e.getMessage(), e.getStatus()); + // + // templates.clear(); + // } + // + // return templates; + // } + /** + * Resets the template set. + */ + public void reset() throws CoreException { + clear(); + addFromFile(getTemplateFile()); + } + + /** + * Resets the template set with the default templates. + */ + public void restoreDefaults() throws CoreException { + clear(); + addFromStream(getDefaultsAsStream()); + } + + /** + * Saves the template set. + */ + public void save() throws CoreException { + saveToFile(getTemplateFile()); + } + + private InputStream getDefaultsAsStream() { + return ObfuscatorIgnores.class.getResourceAsStream(DEFAULT_FILE); + } + + private File getTemplateFile() { + IPath path = fProject.getLocation(); + // PHPeclipsePlugin.getDefault().getStateLocation(); + path = path.append(TEMPLATE_FILE); + + return path.toFile(); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorMessages.java index e6209d9..2f99776 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorMessages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorMessages.java @@ -10,8 +10,11 @@ import java.util.ResourceBundle; public class ObfuscatorMessages { - private static final String RESOURCE_BUNDLE= ObfuscatorMessages.class.getName(); - private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); + private static final String RESOURCE_BUNDLE = ObfuscatorMessages.class + .getName(); + + private static ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); private ObfuscatorMessages() { } @@ -23,20 +26,20 @@ public class ObfuscatorMessages { return '!' + key + '!'; } } - + /** * Gets a string from the resource bundle and formats it with the argument * - * @param key the string used to get the bundle value, must not be null + * @param key + * the string used to get the bundle value, must not be null */ public static String getFormattedString(String key, Object arg) { return MessageFormat.format(getString(key), new Object[] { arg }); } - /** * Gets a string from the resource bundle and formats it with arguments - */ + */ public static String getFormattedString(String key, Object[] args) { return MessageFormat.format(getString(key), args); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorPass1Exporter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorPass1Exporter.java index cd18ce5..a275475 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorPass1Exporter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorPass1Exporter.java @@ -36,201 +36,222 @@ import org.eclipse.jface.preference.IPreferenceStore; */ public class ObfuscatorPass1Exporter implements ITerminalSymbols { - protected Scanner fScanner; - protected int fToken; - - protected HashMap fIdentifierMap; - - public ObfuscatorPass1Exporter(Scanner scanner, HashMap identifierMap) { - fScanner = scanner; - fIdentifierMap = identifierMap; - } - - /** - * Get the next token from input - */ - private void getNextToken() { - - try { - fToken = fScanner.getNextToken(); - if (Scanner.DEBUG) { - int currentEndPosition = fScanner.getCurrentTokenEndPosition(); - int currentStartPosition = fScanner.getCurrentTokenStartPosition(); - - System.out.print(currentStartPosition + "," + currentEndPosition + ": "); - System.out.println(fScanner.toStringAction(fToken)); - } - return; - } catch (InvalidInputException e) { - - } - fToken = TokenNameERROR; - } - - private void parseIdentifiers(boolean goBack) { - char[] ident; - String identifier; - PHPIdentifier value; - int counter = 0; - - IPreferenceStore store = PHPeclipsePlugin.getDefault().getPreferenceStore(); - try { - while (fToken != TokenNameEOF && fToken != TokenNameERROR) { - if (fToken == TokenNameVariable) { - identifier = new String(fScanner.getCurrentIdentifierSource()); - value = (PHPIdentifier) fIdentifierMap.get(identifier); - if (value == null) { - fIdentifierMap.put(identifier, new PHPIdentifier(null, PHPIdentifier.VARIABLE)); - } - getNextToken(); - // } else if (fToken == TokenNamefunction) { - // getNextToken(); - // if (fToken == TokenNameAND) { - // getNextToken(); - // } - // if (fToken == TokenNameIdentifier) { - // ident = fScanner.getCurrentIdentifierSource(); - // outlineInfo.addVariable(new String(ident)); - // temp = new PHPFunctionDeclaration(current, new String(ident), fScanner.getCurrentTokenStartPosition()); - // current.add(temp); - // getNextToken(); - // parseDeclarations(outlineInfo, temp, true); - // } - // } else if (fToken == TokenNameclass) { - // getNextToken(); - // if (fToken == TokenNameIdentifier) { - // ident = fScanner.getCurrentIdentifierSource(); - // outlineInfo.addVariable(new String(ident)); - // temp = new PHPClassDeclaration(current, new String(ident), fScanner.getCurrentTokenStartPosition()); - // current.add(temp); - // getNextToken(); - // - // //skip fTokens for classname, extends and others until we have the opening '{' - // while (fToken != TokenNameLBRACE && fToken != TokenNameEOF && fToken != TokenNameERROR) { - // getNextToken(); - // } - // parseDeclarations(outlineInfo, temp, true); - // // stack.pop(); - // } - } else if (fToken == TokenNameStringDoubleQuote) { - char currentCharacter; - int i = fScanner.startPosition; - ArrayList varList = new ArrayList(); - - while (i < fScanner.currentPosition) { - currentCharacter = fScanner.source[i++]; - if (currentCharacter == '$' && fScanner.source[i - 2] != '\\') { - StringBuffer varName = new StringBuffer(); - varName.append("$"); - while (i < fScanner.currentPosition) { - currentCharacter = fScanner.source[i++]; - if (!Scanner.isPHPIdentifierPart(currentCharacter)) { - break; // while loop - } - varName.append(currentCharacter); - } - varList.add(varName.toString()); - } - } - - for (i = 0; i < varList.size(); i++) { - identifier = (String) varList.get(i); - value = (PHPIdentifier) fIdentifierMap.get(identifier); - if (value == null) { - fIdentifierMap.put(identifier, new PHPIdentifier(null, PHPIdentifier.VARIABLE)); - } - } - - getNextToken(); - } else if (fToken == TokenNameLBRACE) { - getNextToken(); - counter++; - } else if (fToken == TokenNameRBRACE) { - getNextToken(); - --counter; - if (counter == 0 && goBack) { - return; - } - } else { - getNextToken(); - } - } - } catch (SyntaxError sytaxErr) { - // do nothing - } - } - - /** - * Do nothing in first pass - */ - public void createFolder(IPath destinationPath) { - // do nothing here - // new File(destinationPath.toOSString()).mkdir(); - } - /** - * Writes the passed resource to the specified location recursively - */ - public void write(IResource resource, IPath destinationPath) throws CoreException, IOException { - if (resource.getType() == IResource.FILE) - writeFile((IFile) resource, destinationPath); - else - writeChildren((IContainer) resource, destinationPath); - } - /** - * Exports the passed container's children - */ - protected void writeChildren(IContainer folder, IPath destinationPath) throws CoreException, IOException { - if (folder.isAccessible()) { - IResource[] children = folder.members(); - for (int i = 0; i < children.length; i++) { - IResource child = children[i]; - writeResource(child, destinationPath.append(child.getName())); - } - } - } - /** - * Analyzes the passed file resource for the PHP obfuscator - */ - protected void writeFile(IFile file, IPath destinationPath) throws IOException, CoreException { - if (! PHPFileUtil.isPHPFile(file) ){ + protected Scanner fScanner; + + protected int fToken; + + protected HashMap fIdentifierMap; + + public ObfuscatorPass1Exporter(Scanner scanner, HashMap identifierMap) { + fScanner = scanner; + fIdentifierMap = identifierMap; + } + + /** + * Get the next token from input + */ + private void getNextToken() { + + try { + fToken = fScanner.getNextToken(); + if (Scanner.DEBUG) { + int currentEndPosition = fScanner.getCurrentTokenEndPosition(); + int currentStartPosition = fScanner + .getCurrentTokenStartPosition(); + + System.out.print(currentStartPosition + "," + + currentEndPosition + ": "); + System.out.println(fScanner.toStringAction(fToken)); + } return; + } catch (InvalidInputException e) { + + } + fToken = TokenNameERROR; + } + + private void parseIdentifiers(boolean goBack) { + char[] ident; + String identifier; + PHPIdentifier value; + int counter = 0; + + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + try { + while (fToken != TokenNameEOF && fToken != TokenNameERROR) { + if (fToken == TokenNameVariable) { + identifier = new String(fScanner + .getCurrentIdentifierSource()); + value = (PHPIdentifier) fIdentifierMap.get(identifier); + if (value == null) { + fIdentifierMap.put(identifier, new PHPIdentifier(null, + PHPIdentifier.VARIABLE)); + } + getNextToken(); + // } else if (fToken == TokenNamefunction) { + // getNextToken(); + // if (fToken == TokenNameAND) { + // getNextToken(); + // } + // if (fToken == TokenNameIdentifier) { + // ident = fScanner.getCurrentIdentifierSource(); + // outlineInfo.addVariable(new String(ident)); + // temp = new PHPFunctionDeclaration(current, new + // String(ident), fScanner.getCurrentTokenStartPosition()); + // current.add(temp); + // getNextToken(); + // parseDeclarations(outlineInfo, temp, true); + // } + // } else if (fToken == TokenNameclass) { + // getNextToken(); + // if (fToken == TokenNameIdentifier) { + // ident = fScanner.getCurrentIdentifierSource(); + // outlineInfo.addVariable(new String(ident)); + // temp = new PHPClassDeclaration(current, new + // String(ident), fScanner.getCurrentTokenStartPosition()); + // current.add(temp); + // getNextToken(); + // + // //skip fTokens for classname, extends and others until we + // have the opening '{' + // while (fToken != TokenNameLBRACE && fToken != + // TokenNameEOF && fToken != TokenNameERROR) { + // getNextToken(); + // } + // parseDeclarations(outlineInfo, temp, true); + // // stack.pop(); + // } + } else if (fToken == TokenNameStringDoubleQuote) { + char currentCharacter; + int i = fScanner.startPosition; + ArrayList varList = new ArrayList(); + + while (i < fScanner.currentPosition) { + currentCharacter = fScanner.source[i++]; + if (currentCharacter == '$' + && fScanner.source[i - 2] != '\\') { + StringBuffer varName = new StringBuffer(); + varName.append("$"); + while (i < fScanner.currentPosition) { + currentCharacter = fScanner.source[i++]; + if (!Scanner + .isPHPIdentifierPart(currentCharacter)) { + break; // while loop + } + varName.append(currentCharacter); + } + varList.add(varName.toString()); + } + } + + for (i = 0; i < varList.size(); i++) { + identifier = (String) varList.get(i); + value = (PHPIdentifier) fIdentifierMap.get(identifier); + if (value == null) { + fIdentifierMap.put(identifier, new PHPIdentifier( + null, PHPIdentifier.VARIABLE)); + } + } + + getNextToken(); + } else if (fToken == TokenNameLBRACE) { + getNextToken(); + counter++; + } else if (fToken == TokenNameRBRACE) { + getNextToken(); + --counter; + if (counter == 0 && goBack) { + return; + } + } else { + getNextToken(); + } + } + } catch (SyntaxError sytaxErr) { + // do nothing + } + } + + /** + * Do nothing in first pass + */ + public void createFolder(IPath destinationPath) { + // do nothing here + // new File(destinationPath.toOSString()).mkdir(); + } + + /** + * Writes the passed resource to the specified location recursively + */ + public void write(IResource resource, IPath destinationPath) + throws CoreException, IOException { + if (resource.getType() == IResource.FILE) + writeFile((IFile) resource, destinationPath); + else + writeChildren((IContainer) resource, destinationPath); + } + + /** + * Exports the passed container's children + */ + protected void writeChildren(IContainer folder, IPath destinationPath) + throws CoreException, IOException { + if (folder.isAccessible()) { + IResource[] children = folder.members(); + for (int i = 0; i < children.length; i++) { + IResource child = children[i]; + writeResource(child, destinationPath.append(child.getName())); + } + } + } + + /** + * Analyzes the passed file resource for the PHP obfuscator + */ + protected void writeFile(IFile file, IPath destinationPath) + throws IOException, CoreException { + if (!PHPFileUtil.isPHPFile(file)) { + return; + } + InputStream stream = null; + char[] charArray = null; + try { + stream = new BufferedInputStream(file.getContents()); + charArray = Util.getInputStreamAsCharArray(stream, -1, null); + } catch (IOException e) { + return; + } finally { + try { + if (stream != null) { + stream.close(); + } + } catch (IOException e) { + } + } + + if (charArray == null) { + // TODO show error message + return; + } + /* fScanner initialization */ + fScanner.setSource(charArray); + fScanner.setPHPMode(false); + fToken = TokenNameEOF; + getNextToken(); + parseIdentifiers(false); + } + + /** + * Writes the passed resource to the specified location recursively + */ + protected void writeResource(IResource resource, IPath destinationPath) + throws CoreException, IOException { + if (resource.getType() == IResource.FILE) + writeFile((IFile) resource, destinationPath); + else { + createFolder(destinationPath); + writeChildren((IContainer) resource, destinationPath); } - InputStream stream = null; - char[] charArray = null; - try { - stream = new BufferedInputStream(file.getContents()); - charArray = Util.getInputStreamAsCharArray(stream, -1, null); - } catch (IOException e) { - return; - } finally { - try { - if (stream != null) { - stream.close(); - } - } catch (IOException e) { - } - } - - if (charArray == null) { - // TODO show error message - return; - } - /* fScanner initialization */ - fScanner.setSource(charArray); - fScanner.setPHPMode(false); - fToken = TokenNameEOF; - getNextToken(); - parseIdentifiers(false); - } - /** - * Writes the passed resource to the specified location recursively - */ - protected void writeResource(IResource resource, IPath destinationPath) throws CoreException, IOException { - if (resource.getType() == IResource.FILE) - writeFile((IFile) resource, destinationPath); - else { - createFolder(destinationPath); - writeChildren((IContainer) resource, destinationPath); - } - } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorPass2Exporter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorPass2Exporter.java index 093f1e3..47923a6 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorPass2Exporter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorPass2Exporter.java @@ -40,305 +40,342 @@ import org.eclipse.jface.preference.IPreferenceStore; * Helper class for exporting resources to the file system. */ public class ObfuscatorPass2Exporter implements ITerminalSymbols { - private Scanner fScanner; - private int fToken; - private int fCounter; - - protected HashMap fIdentifierMap; - - public ObfuscatorPass2Exporter(Scanner scanner, HashMap identifierMap) { - fScanner = scanner; - fIdentifierMap = identifierMap; - fCounter = 0; - } - - /** - * gets the next token from input - */ - private void getNextToken() { - - try { - fToken = fScanner.getNextToken(); - if (Scanner.DEBUG) { - int currentEndPosition = fScanner.getCurrentTokenEndPosition(); - int currentStartPosition = fScanner.getCurrentTokenStartPosition(); - - System.out.print(currentStartPosition + "," + currentEndPosition + ": "); - System.out.println(fScanner.toStringAction(fToken)); - } - return; - } catch (InvalidInputException e) { - - } - fToken = TokenNameERROR; - } - - private boolean obfuscate(StringBuffer buf) { - char[] ident; - String identifier; - PHPIdentifier value; - - int startPosition = 0; - int lastPosition = 0; - - IPreferenceStore store = PHPeclipsePlugin.getDefault().getPreferenceStore(); - try { - while (fToken != TokenNameEOF && fToken != TokenNameERROR) { - if (fToken == TokenNameVariable) { - identifier = new String(fScanner.getCurrentIdentifierSource()); - lastPosition = fScanner.startPosition; - int len = lastPosition - startPosition; - buf.append(fScanner.source, startPosition, len); - value = (PHPIdentifier) fIdentifierMap.get(identifier); - if (value != null) { - String obfuscatedIdentifier = value.getIdentifier(); - if (obfuscatedIdentifier == null) { - buf.append("$v" + Integer.toString(fCounter)); - value.setIdentifier("$v" + Integer.toString(fCounter++)); - } else { - buf.append(obfuscatedIdentifier); - } - // System.out.println(hexString.toString()); - } else { - buf.append(identifier); - } - startPosition = fScanner.currentPosition; - getNextToken(); - } else if (fToken == TokenNameIdentifier) { - identifier = new String(fScanner.getCurrentIdentifierSource()); - lastPosition = fScanner.startPosition; - int len = lastPosition - startPosition; - buf.append(fScanner.source, startPosition, len); - value = (PHPIdentifier) fIdentifierMap.get(identifier); - if (value != null) { - String obfuscatedIdentifier = value.getIdentifier(); - if (obfuscatedIdentifier == null) { - buf.append("_" + Integer.toString(fCounter)); - value.setIdentifier("_" + Integer.toString(fCounter++)); - } else { - buf.append(obfuscatedIdentifier); - } - // System.out.println(hexString.toString()); - } else { - buf.append(identifier); - } - startPosition = fScanner.currentPosition; - getNextToken(); - - } else if (fToken == TokenNameCOMMENT_LINE || fToken == TokenNameCOMMENT_BLOCK || fToken == TokenNameCOMMENT_PHPDOC) { - lastPosition = fScanner.startPosition; - buf.append(fScanner.source, startPosition, lastPosition - startPosition); - startPosition = fScanner.currentPosition; - getNextToken(); - } else if (fToken == TokenNameStringDoubleQuote) { - char currentCharacter; - int i = fScanner.startPosition; - ArrayList varList = new ArrayList(); - - lastPosition = fScanner.startPosition; - int len = lastPosition - startPosition; - buf.append(fScanner.source, startPosition, len); - - while (i < fScanner.currentPosition) { - currentCharacter = fScanner.source[i++]; - if (currentCharacter == '$' && fScanner.source[i - 2] != '\\') { - StringBuffer varName = new StringBuffer(); - varName.append("$"); - while (i < fScanner.currentPosition) { - currentCharacter = fScanner.source[i++]; - if (!Scanner.isPHPIdentifierPart(currentCharacter)) { - break; // while loop - } - varName.append(currentCharacter); - } - varList.add(varName.toString()); - } - } - StringBuffer stringLiteral = new StringBuffer(); - stringLiteral.append(fScanner.source, fScanner.startPosition, fScanner.currentPosition - fScanner.startPosition); - String stringIdent; - String replacement; - int index; - - for (int j = 0; j < varList.size(); j++) { - stringIdent = (String) varList.get(j); - len = stringIdent.length(); - value = (PHPIdentifier) fIdentifierMap.get(stringIdent); - if (value != null) { - String obfuscatedIdentifier = value.getIdentifier(); - if (obfuscatedIdentifier == null) { - replacement = "$v" + Integer.toString(fCounter); - value.setIdentifier("$v" + Integer.toString(fCounter++)); - } else { - replacement = obfuscatedIdentifier; - } - // System.out.println(hexString.toString()); - } else { - replacement = stringIdent; - } - index = stringLiteral.indexOf(stringIdent); - if (index >= 0) { - if (index > 0 && stringLiteral.charAt(index - 1) != '\\') { - stringLiteral.replace(index, index + stringIdent.length(), replacement); - } else if (index == 0) { - stringLiteral.replace(index, index + stringIdent.length(), replacement); - } - } - } - buf.append(stringLiteral); - startPosition = fScanner.currentPosition; - getNextToken(); - } - if (fToken == TokenNameMINUS_GREATER) { // i.e. $this->var_name - getNextToken(); - if (fToken == TokenNameIdentifier) { - // assuming this is a dereferenced variable - identifier = new String(fScanner.getCurrentIdentifierSource()); - lastPosition = fScanner.startPosition; - int len = lastPosition - startPosition; - buf.append(fScanner.source, startPosition, len); - value = (PHPIdentifier) fIdentifierMap.get("$" + identifier); - if (value != null && value.isVariable()) { - String obfuscatedIdentifier = value.getIdentifier(); - if (obfuscatedIdentifier == null) { - // note: don't place a $ before the identifier - buf.append("v" + Integer.toString(fCounter)); - value.setIdentifier("$v" + Integer.toString(fCounter++)); - } else { - if (obfuscatedIdentifier.charAt(0) == '$') { - buf.append(obfuscatedIdentifier.substring(1)); - } else { - buf.append(obfuscatedIdentifier); - } - } - } else { - buf.append(identifier); - } - startPosition = fScanner.currentPosition; - getNextToken(); - } - - } else { - getNextToken(); - } - } - if (startPosition < fScanner.source.length) { - buf.append(fScanner.source, startPosition, fScanner.source.length - startPosition); - } - return true; - } catch (SyntaxError sytaxErr) { - // do nothing - } - - return false; - } - /** - * Creates the specified file system directory at destinationPath. - * This creates a new file system directory. - */ - public void createFolder(IPath destinationPath) { - new File(destinationPath.toOSString()).mkdir(); - } - /** - * Writes the passed resource to the specified location recursively - */ - public void write(IResource resource, IPath destinationPath) throws CoreException, IOException { - if (resource.getType() == IResource.FILE) - writeFile((IFile) resource, destinationPath); - else - writeChildren((IContainer) resource, destinationPath); - } - /** - * Exports the passed container's children - */ - protected void writeChildren(IContainer folder, IPath destinationPath) throws CoreException, IOException { - if (folder.isAccessible()) { - IResource[] children = folder.members(); - for (int i = 0; i < children.length; i++) { - IResource child = children[i]; - writeResource(child, destinationPath.append(child.getName())); - } - } - } - /** - * Writes the passed file resource to the specified destination on the local - * file system - */ - protected void writeFile(IFile file, IPath destinationPath) throws IOException, CoreException { - if (PHPFileUtil.isPHPFile(file)) { - InputStream stream = null; - char[] charArray = null; - try { - stream = new BufferedInputStream(file.getContents()); - charArray = Util.getInputStreamAsCharArray(stream, -1, null); - } catch (IOException e) { - return; - } finally { - try { - if (stream != null) { - stream.close(); - } - } catch (IOException e) { - } - } - - if (charArray == null) { - // TODO show error message - return; - } - - fScanner.setSource(charArray); - fScanner.setPHPMode(false); - fToken = TokenNameEOF; - getNextToken(); - - StringBuffer buf = new StringBuffer(); - if (!obfuscate(buf)) { - copyFile(file, destinationPath); - } else { - // charArray = buf.toString().toCharArray(); - // File targetFile = new File(destinationPath.toOSString()); - BufferedWriter bw = new BufferedWriter(new FileWriter(destinationPath.toOSString())); - bw.write(buf.toString()); - bw.close(); - } - - } else { - copyFile(file, destinationPath); - } - } - - private void copyFile(IFile file, IPath destinationPath) throws FileNotFoundException, CoreException, IOException { - FileOutputStream output = null; - InputStream contentStream = null; - - try { - output = new FileOutputStream(destinationPath.toOSString()); - contentStream = file.getContents(false); - int chunkSize = contentStream.available(); - byte[] readBuffer = new byte[chunkSize]; - int n = contentStream.read(readBuffer); - - while (n > 0) { - output.write(readBuffer); - n = contentStream.read(readBuffer); - } - } finally { - if (output != null) - output.close(); - if (contentStream != null) - contentStream.close(); - } - } - /** - * Writes the passed resource to the specified location recursively - */ - protected void writeResource(IResource resource, IPath destinationPath) throws CoreException, IOException { - if (resource.getType() == IResource.FILE) - writeFile((IFile) resource, destinationPath); - else { - createFolder(destinationPath); - writeChildren((IContainer) resource, destinationPath); - } - } + private Scanner fScanner; + + private int fToken; + + private int fCounter; + + protected HashMap fIdentifierMap; + + public ObfuscatorPass2Exporter(Scanner scanner, HashMap identifierMap) { + fScanner = scanner; + fIdentifierMap = identifierMap; + fCounter = 0; + } + + /** + * gets the next token from input + */ + private void getNextToken() { + + try { + fToken = fScanner.getNextToken(); + if (Scanner.DEBUG) { + int currentEndPosition = fScanner.getCurrentTokenEndPosition(); + int currentStartPosition = fScanner + .getCurrentTokenStartPosition(); + + System.out.print(currentStartPosition + "," + + currentEndPosition + ": "); + System.out.println(fScanner.toStringAction(fToken)); + } + return; + } catch (InvalidInputException e) { + + } + fToken = TokenNameERROR; + } + + private boolean obfuscate(StringBuffer buf) { + char[] ident; + String identifier; + PHPIdentifier value; + + int startPosition = 0; + int lastPosition = 0; + + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + try { + while (fToken != TokenNameEOF && fToken != TokenNameERROR) { + if (fToken == TokenNameVariable) { + identifier = new String(fScanner + .getCurrentIdentifierSource()); + lastPosition = fScanner.startPosition; + int len = lastPosition - startPosition; + buf.append(fScanner.source, startPosition, len); + value = (PHPIdentifier) fIdentifierMap.get(identifier); + if (value != null) { + String obfuscatedIdentifier = value.getIdentifier(); + if (obfuscatedIdentifier == null) { + buf.append("$v" + Integer.toString(fCounter)); + value.setIdentifier("$v" + + Integer.toString(fCounter++)); + } else { + buf.append(obfuscatedIdentifier); + } + // System.out.println(hexString.toString()); + } else { + buf.append(identifier); + } + startPosition = fScanner.currentPosition; + getNextToken(); + } else if (fToken == TokenNameIdentifier) { + identifier = new String(fScanner + .getCurrentIdentifierSource()); + lastPosition = fScanner.startPosition; + int len = lastPosition - startPosition; + buf.append(fScanner.source, startPosition, len); + value = (PHPIdentifier) fIdentifierMap.get(identifier); + if (value != null) { + String obfuscatedIdentifier = value.getIdentifier(); + if (obfuscatedIdentifier == null) { + buf.append("_" + Integer.toString(fCounter)); + value.setIdentifier("_" + + Integer.toString(fCounter++)); + } else { + buf.append(obfuscatedIdentifier); + } + // System.out.println(hexString.toString()); + } else { + buf.append(identifier); + } + startPosition = fScanner.currentPosition; + getNextToken(); + + } else if (fToken == TokenNameCOMMENT_LINE + || fToken == TokenNameCOMMENT_BLOCK + || fToken == TokenNameCOMMENT_PHPDOC) { + lastPosition = fScanner.startPosition; + buf.append(fScanner.source, startPosition, lastPosition + - startPosition); + startPosition = fScanner.currentPosition; + getNextToken(); + } else if (fToken == TokenNameStringDoubleQuote) { + char currentCharacter; + int i = fScanner.startPosition; + ArrayList varList = new ArrayList(); + + lastPosition = fScanner.startPosition; + int len = lastPosition - startPosition; + buf.append(fScanner.source, startPosition, len); + + while (i < fScanner.currentPosition) { + currentCharacter = fScanner.source[i++]; + if (currentCharacter == '$' + && fScanner.source[i - 2] != '\\') { + StringBuffer varName = new StringBuffer(); + varName.append("$"); + while (i < fScanner.currentPosition) { + currentCharacter = fScanner.source[i++]; + if (!Scanner + .isPHPIdentifierPart(currentCharacter)) { + break; // while loop + } + varName.append(currentCharacter); + } + varList.add(varName.toString()); + } + } + StringBuffer stringLiteral = new StringBuffer(); + stringLiteral.append(fScanner.source, + fScanner.startPosition, fScanner.currentPosition + - fScanner.startPosition); + String stringIdent; + String replacement; + int index; + + for (int j = 0; j < varList.size(); j++) { + stringIdent = (String) varList.get(j); + len = stringIdent.length(); + value = (PHPIdentifier) fIdentifierMap.get(stringIdent); + if (value != null) { + String obfuscatedIdentifier = value.getIdentifier(); + if (obfuscatedIdentifier == null) { + replacement = "$v" + Integer.toString(fCounter); + value.setIdentifier("$v" + + Integer.toString(fCounter++)); + } else { + replacement = obfuscatedIdentifier; + } + // System.out.println(hexString.toString()); + } else { + replacement = stringIdent; + } + index = stringLiteral.indexOf(stringIdent); + if (index >= 0) { + if (index > 0 + && stringLiteral.charAt(index - 1) != '\\') { + stringLiteral.replace(index, index + + stringIdent.length(), replacement); + } else if (index == 0) { + stringLiteral.replace(index, index + + stringIdent.length(), replacement); + } + } + } + buf.append(stringLiteral); + startPosition = fScanner.currentPosition; + getNextToken(); + } + if (fToken == TokenNameMINUS_GREATER) { // i.e. $this->var_name + getNextToken(); + if (fToken == TokenNameIdentifier) { + // assuming this is a dereferenced variable + identifier = new String(fScanner + .getCurrentIdentifierSource()); + lastPosition = fScanner.startPosition; + int len = lastPosition - startPosition; + buf.append(fScanner.source, startPosition, len); + value = (PHPIdentifier) fIdentifierMap.get("$" + + identifier); + if (value != null && value.isVariable()) { + String obfuscatedIdentifier = value.getIdentifier(); + if (obfuscatedIdentifier == null) { + // note: don't place a $ before the identifier + buf.append("v" + Integer.toString(fCounter)); + value.setIdentifier("$v" + + Integer.toString(fCounter++)); + } else { + if (obfuscatedIdentifier.charAt(0) == '$') { + buf.append(obfuscatedIdentifier + .substring(1)); + } else { + buf.append(obfuscatedIdentifier); + } + } + } else { + buf.append(identifier); + } + startPosition = fScanner.currentPosition; + getNextToken(); + } + + } else { + getNextToken(); + } + } + if (startPosition < fScanner.source.length) { + buf.append(fScanner.source, startPosition, + fScanner.source.length - startPosition); + } + return true; + } catch (SyntaxError sytaxErr) { + // do nothing + } + + return false; + } + + /** + * Creates the specified file system directory at + * destinationPath. This creates a new file system + * directory. + */ + public void createFolder(IPath destinationPath) { + new File(destinationPath.toOSString()).mkdir(); + } + + /** + * Writes the passed resource to the specified location recursively + */ + public void write(IResource resource, IPath destinationPath) + throws CoreException, IOException { + if (resource.getType() == IResource.FILE) + writeFile((IFile) resource, destinationPath); + else + writeChildren((IContainer) resource, destinationPath); + } + + /** + * Exports the passed container's children + */ + protected void writeChildren(IContainer folder, IPath destinationPath) + throws CoreException, IOException { + if (folder.isAccessible()) { + IResource[] children = folder.members(); + for (int i = 0; i < children.length; i++) { + IResource child = children[i]; + writeResource(child, destinationPath.append(child.getName())); + } + } + } + + /** + * Writes the passed file resource to the specified destination on the local + * file system + */ + protected void writeFile(IFile file, IPath destinationPath) + throws IOException, CoreException { + if (PHPFileUtil.isPHPFile(file)) { + InputStream stream = null; + char[] charArray = null; + try { + stream = new BufferedInputStream(file.getContents()); + charArray = Util.getInputStreamAsCharArray(stream, -1, null); + } catch (IOException e) { + return; + } finally { + try { + if (stream != null) { + stream.close(); + } + } catch (IOException e) { + } + } + + if (charArray == null) { + // TODO show error message + return; + } + + fScanner.setSource(charArray); + fScanner.setPHPMode(false); + fToken = TokenNameEOF; + getNextToken(); + + StringBuffer buf = new StringBuffer(); + if (!obfuscate(buf)) { + copyFile(file, destinationPath); + } else { + // charArray = buf.toString().toCharArray(); + // File targetFile = new File(destinationPath.toOSString()); + BufferedWriter bw = new BufferedWriter(new FileWriter( + destinationPath.toOSString())); + bw.write(buf.toString()); + bw.close(); + } + + } else { + copyFile(file, destinationPath); + } + } + + private void copyFile(IFile file, IPath destinationPath) + throws FileNotFoundException, CoreException, IOException { + FileOutputStream output = null; + InputStream contentStream = null; + + try { + output = new FileOutputStream(destinationPath.toOSString()); + contentStream = file.getContents(false); + int chunkSize = contentStream.available(); + byte[] readBuffer = new byte[chunkSize]; + int n = contentStream.read(readBuffer); + + while (n > 0) { + output.write(readBuffer); + n = contentStream.read(readBuffer); + } + } finally { + if (output != null) + output.close(); + if (contentStream != null) + contentStream.close(); + } + } + + /** + * Writes the passed resource to the specified location recursively + */ + protected void writeResource(IResource resource, IPath destinationPath) + throws CoreException, IOException { + if (resource.getType() == IResource.FILE) + writeFile((IFile) resource, destinationPath); + else { + createFolder(destinationPath); + writeChildren((IContainer) resource, destinationPath); + } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/PHPIdentifier.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/PHPIdentifier.java index fab771e..53369ef 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/PHPIdentifier.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/PHPIdentifier.java @@ -1,109 +1,119 @@ package net.sourceforge.phpeclipse.obfuscator; /** - * Object which holds an PHP identifier name (i.e. class, function, variable,...) - * + * Object which holds an PHP identifier name (i.e. class, function, + * variable,...) + * */ public class PHPIdentifier { - public final static int CLASS = 1; - public final static int FUNCTION = 2; - public final static int VARIABLE = 3; - public final static int METHOD = 4; - public final static int DEFINE = 5; - public final static int CONSTRUCTOR = 6; - public final static int GLOBAL_VARIABLE = 7; - public final static int EXTENDS = 8; - public final static int IMPLEMENTS = 9; - - private String fIdentifier; - - private int fType; - - public PHPIdentifier(String identifier, int type) { - fType = type; - fIdentifier = identifier; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object obj) { - if (!(obj instanceof PHPIdentifier)) { - return false; - } - return ((PHPIdentifier) obj).fType == fType && ((PHPIdentifier) obj).fIdentifier.equals(fIdentifier); - } - - public String getIdentifier() { - return fIdentifier; - } - - public int getType() { - return fType; - } - - public boolean isClass() { - return fType == CLASS; - } - - public boolean isFunction() { - return fType == FUNCTION; - } - - public boolean isVariable() { - return fType == VARIABLE; - } - - public boolean isMethod() { - return fType == METHOD; - } - - public boolean isDefine() { - return fType == DEFINE; - } - - public boolean isGlobalVariable() { - return fType == GLOBAL_VARIABLE; - } - - public boolean isConstructor() { - return fType == CONSTRUCTOR; - } - - public void setIdentifier(String fIdentifier) { - this.fIdentifier = fIdentifier; - } - - public void setType(int fType) { - this.fType = fType; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - public String toString() { - switch (fType) { - case CLASS : - return "class - "; - case CONSTRUCTOR : - return "constructor - "; - case DEFINE : - return "define - "; - case FUNCTION : - return "function - "; - case GLOBAL_VARIABLE : - return "global variable - "; - case METHOD : - return "method - "; - case VARIABLE : - return "variable - "; - } - return ""; - } + public final static int CLASS = 1; + + public final static int FUNCTION = 2; + + public final static int VARIABLE = 3; + + public final static int METHOD = 4; + + public final static int DEFINE = 5; + + public final static int CONSTRUCTOR = 6; + + public final static int GLOBAL_VARIABLE = 7; + + public final static int EXTENDS = 8; + + public final static int IMPLEMENTS = 9; + + private String fIdentifier; + + private int fType; + + public PHPIdentifier(String identifier, int type) { + fType = type; + fIdentifier = identifier; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + public boolean equals(Object obj) { + if (!(obj instanceof PHPIdentifier)) { + return false; + } + return ((PHPIdentifier) obj).fType == fType + && ((PHPIdentifier) obj).fIdentifier.equals(fIdentifier); + } + + public String getIdentifier() { + return fIdentifier; + } + + public int getType() { + return fType; + } + + public boolean isClass() { + return fType == CLASS; + } + + public boolean isFunction() { + return fType == FUNCTION; + } + + public boolean isVariable() { + return fType == VARIABLE; + } + + public boolean isMethod() { + return fType == METHOD; + } + + public boolean isDefine() { + return fType == DEFINE; + } + + public boolean isGlobalVariable() { + return fType == GLOBAL_VARIABLE; + } + + public boolean isConstructor() { + return fType == CONSTRUCTOR; + } + + public void setIdentifier(String fIdentifier) { + this.fIdentifier = fIdentifier; + } + + public void setType(int fType) { + this.fType = fType; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + public String toString() { + switch (fType) { + case CLASS: + return "class - "; + case CONSTRUCTOR: + return "constructor - "; + case DEFINE: + return "define - "; + case FUNCTION: + return "function - "; + case GLOBAL_VARIABLE: + return "global variable - "; + case METHOD: + return "method - "; + case VARIABLE: + return "variable - "; + } + return ""; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/ObfuscatorExportMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/ObfuscatorExportMessages.java index 655f7c8..3878513 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/ObfuscatorExportMessages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/ObfuscatorExportMessages.java @@ -9,7 +9,7 @@ * IBM Corporation - initial API and implementation *******************************************************************************/ package net.sourceforge.phpeclipse.obfuscator.export; - + import java.text.MessageFormat; import java.util.MissingResourceException; import java.util.ResourceBundle; @@ -18,35 +18,41 @@ import java.util.ResourceBundle; * Utility class which helps managing messages */ class ObfuscatorExportMessages { - private static final String RESOURCE_BUNDLE= "net.sourceforge.phpeclipse.obfuscator.export.messages";//$NON-NLS-1$ - private static ResourceBundle bundle = ResourceBundle.getBundle(RESOURCE_BUNDLE); -private ObfuscatorExportMessages(){ - // prevent instantiation of class -} -/** - * Returns the formatted message for the given key in - * the resource bundle. - * - * @param key the resource name - * @param args the message arguments - * @return the string - */ -public static String format(String key, Object[] args) { - return MessageFormat.format(getString(key),args); -} -/** - * Returns the resource object with the given key in - * the resource bundle. If there isn't any value under - * the given key, the key is returned. - * - * @param key the resource name - * @return the string - */ -public static String getString(String key) { - try { - return bundle.getString(key); - } catch (MissingResourceException e) { - return key; + private static final String RESOURCE_BUNDLE = "net.sourceforge.phpeclipse.obfuscator.export.messages";//$NON-NLS-1$ + + private static ResourceBundle bundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); + + private ObfuscatorExportMessages() { + // prevent instantiation of class + } + + /** + * Returns the formatted message for the given key in the resource bundle. + * + * @param key + * the resource name + * @param args + * the message arguments + * @return the string + */ + public static String format(String key, Object[] args) { + return MessageFormat.format(getString(key), args); + } + + /** + * Returns the resource object with the given key in the resource bundle. If + * there isn't any value under the given key, the key is returned. + * + * @param key + * the resource name + * @return the string + */ + public static String getString(String key) { + try { + return bundle.getString(key); + } catch (MissingResourceException e) { + return key; + } } -} } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/ObfuscatorExportOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/ObfuscatorExportOperation.java index f8e50dc..e78ce6a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/ObfuscatorExportOperation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/ObfuscatorExportOperation.java @@ -9,7 +9,7 @@ * IBM Corporation - initial API and implementation *******************************************************************************/ package net.sourceforge.phpeclipse.obfuscator.export; - + import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -39,602 +39,703 @@ import org.eclipse.jface.operation.ModalContext; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.IOverwriteQuery; - /** - * Operation for exporting the contents of a resource to the local file system. + * Operation for exporting the contents of a resource to the local file system. */ -/*package*/ +/* package */ class ObfuscatorExportOperation implements IRunnableWithProgress { - private IPath fPath; - private IProgressMonitor fMonitor; - private ObfuscatorPass1Exporter fExporter1 = null; - private ObfuscatorPass2Exporter fExporter2 = null; - private HashMap fCurrentIdentifierMap = null; - private HashMap fProjectMap = null; - private String fCurrentProjectName = ""; - - private List fResourcesToExport; - private IOverwriteQuery fOverwriteCallback; - private IResource fResource; - private List errorTable = new ArrayList(1); - - //The constants for the overwrite 3 state - private static final int OVERWRITE_NOT_SET = 0; - private static final int OVERWRITE_NONE = 1; - private static final int OVERWRITE_ALL = 2; - private int overwriteState = OVERWRITE_NOT_SET; - - // private boolean createLeadupStructure = true; - private boolean createContainerDirectories = true; - /** - * Create an instance of this class. Use this constructor if you wish to - * export specific resources without a common parent resource - */ - // public ObfuscatorExportOperation(List resources, String destinationPath, IOverwriteQuery overwriteImplementor) { - // super(); - // - // exporter1 = new ObfuscatorPass1Exporter(new Scanner(false, false), identifierMap); - // exporter2 = new ObfuscatorPass2Exporter(new Scanner(true, true), identifierMap); - // identifierMap = null; - // - // // Eliminate redundancies in list of resources being exported - // Iterator elementsEnum = resources.iterator(); - // while (elementsEnum.hasNext()) { - // IResource currentResource = (IResource) elementsEnum.next(); - // if (isDescendent(resources, currentResource)) - // elementsEnum.remove(); //Remove currentResource - // } - // - // resourcesToExport = resources; - // path = new Path(destinationPath); - // overwriteCallback = overwriteImplementor; - // } - /** - * Create an instance of this class. Use this constructor if you wish to - * recursively export a single resource - */ - public ObfuscatorExportOperation(IResource res, String destinationPath, IOverwriteQuery overwriteImplementor) { - super(); - - fResource = res; - fPath = new Path(destinationPath); - fOverwriteCallback = overwriteImplementor; - } - /** - * Create an instance of this class. Use this constructor if you wish to - * export specific resources with a common parent resource (affects container - * directory creation) - */ - public ObfuscatorExportOperation(IResource res, List resources, String destinationPath, IOverwriteQuery overwriteImplementor) { - this(res, destinationPath, overwriteImplementor); - fResourcesToExport = resources; - } - /** - * Add a new entry to the error table with the passed information - */ - protected void addError(String message, Throwable e) { - errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, message, e)); - } - /** - * Answer the total number of file resources that exist at or below self in the - * resources hierarchy. - * - * @return int - * @param resource org.eclipse.core.resources.IResource - */ - protected int countChildrenOf(IResource resource) throws CoreException { - if (resource.getType() == IResource.FILE) - return 1; - - int count = 0; - if (resource.isAccessible()) { - IResource[] children = ((IContainer) resource).members(); - for (int i = 0; i < children.length; i++) - count += countChildrenOf(children[i]); - } - - return count; - } - /** - * Answer a boolean indicating the number of file resources that were - * specified for export - * - * @return int - */ - protected int countSelectedResources() throws CoreException { - int result = 0; - Iterator resources = fResourcesToExport.iterator(); - - while (resources.hasNext()) - result += countChildrenOf((IResource) resources.next()); - - return result; - } - /** - * Create the directories required for exporting the passed resource, - * based upon its container hierarchy - * - * @param resource org.eclipse.core.resources.IResource - */ - protected void createLeadupDirectoriesFor(IResource resource) { - IPath resourcePath = resource.getFullPath().removeLastSegments(1); - - for (int i = 0; i < resourcePath.segmentCount(); i++) { - fPath = fPath.append(resourcePath.segment(i)); - fExporter2.createFolder(fPath); - } - } - /** - * Recursively export the previously-specified resource - */ - protected void exportAllResources1() throws InterruptedException { - if (fResource.getType() == IResource.FILE) { - exportFile1((IFile) fResource, fPath); - } else { - try { - setExporters(fResource); - exportChildren1(((IContainer) fResource).members(), fPath); - } catch (CoreException e) { - // not safe to show a dialog - // should never happen because the file system export wizard ensures that the - // single resource chosen for export is both existent and accessible - errorTable.add(e); - } - } - } - /** - * Recursively export the previously-specified resource - */ - protected void exportAllResources2() throws InterruptedException { - if (fResource.getType() == IResource.FILE) { - exportFile2((IFile) fResource, fPath); - } else { - try { - setExporters(fResource); - exportChildren2(((IContainer) fResource).members(), fPath); - } catch (CoreException e) { - // not safe to show a dialog - // should never happen because the file system export wizard ensures that the - // single resource chosen for export is both existent and accessible - errorTable.add(e); - } - } - } - /** - * Export all of the resources contained in the passed collection - * - * @param children java.util.Enumeration - * @param currentPath IPath - */ - protected void exportChildren1(IResource[] children, IPath currentPath) throws InterruptedException { - for (int i = 0; i < children.length; i++) { - IResource child = children[i]; - if (!child.isAccessible()) - continue; - - if (child.getType() == IResource.FILE) - exportFile1((IFile) child, currentPath); - else { - IPath destination = currentPath.append(child.getName()); - fExporter1.createFolder(destination); - try { - exportChildren1(((IContainer) child).members(), destination); - } catch (CoreException e) { - // not safe to show a dialog - // should never happen because: - // i. this method is called recursively iterating over the result of #members, - // which only answers existing children - // ii. there is an #isAccessible check done before #members is invoked - errorTable.add(e.getStatus()); - } - } - } - } - - /** - * Export all of the resources contained in the passed collection - * - * @param children java.util.Enumeration - * @param currentPath IPath - */ - protected void exportChildren2(IResource[] children, IPath currentPath) throws InterruptedException { - for (int i = 0; i < children.length; i++) { - IResource child = children[i]; - if (!child.isAccessible()) - continue; - - if (child.getType() == IResource.FILE) - exportFile2((IFile) child, currentPath); - else { - IPath destination = currentPath.append(child.getName()); - fExporter2.createFolder(destination); - try { - exportChildren2(((IContainer) child).members(), destination); - } catch (CoreException e) { - // not safe to show a dialog - // should never happen because: - // i. this method is called recursively iterating over the result of #members, - // which only answers existing children - // ii. there is an #isAccessible check done before #members is invoked - errorTable.add(e.getStatus()); - } - } - } - } - - protected void exportFile1(IFile file, IPath location) throws InterruptedException { - IPath fullPath = location.append(file.getName()); - fMonitor.subTask(file.getFullPath().toString()); - String properPathString = fullPath.toOSString(); - File targetFile = new File(properPathString); - - // if (targetFile.exists()) { - // if (!targetFile.canWrite()) { - // errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, ObfuscatorExportMessages.format("ObfuscatorTransfer.cannotOverwrite", //$NON-NLS-1$ - // new Object[] { targetFile.getAbsolutePath()}), null)); - // monitor.worked(1); - // return; - // } - // - // if (overwriteState == OVERWRITE_NONE) - // return; - // - // if (overwriteState != OVERWRITE_ALL) { - // String overwriteAnswer = overwriteCallback.queryOverwrite(properPathString); - // - // if (overwriteAnswer.equals(IOverwriteQuery.CANCEL)) - // throw new InterruptedException(); - // - // if (overwriteAnswer.equals(IOverwriteQuery.NO)) { - // monitor.worked(1); - // return; - // } - // - // if (overwriteAnswer.equals(IOverwriteQuery.NO_ALL)) { - // monitor.worked(1); - // overwriteState = OVERWRITE_NONE; - // return; - // } - // - // if (overwriteAnswer.equals(IOverwriteQuery.ALL)) - // overwriteState = OVERWRITE_ALL; - // } - // } - - try { - setExporters(file); - fExporter1.write(file, fullPath); - } catch (IOException e) { - errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, ObfuscatorExportMessages.format("ObfuscatorTransfer.errorExporting", //$NON-NLS-1$ - new Object[] { fullPath, e.getMessage()}), e)); - } catch (CoreException e) { - errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, ObfuscatorExportMessages.format("ObfuscatorTransfer.errorExporting", //$NON-NLS-1$ - new Object[] { fullPath, e.getMessage()}), e)); - } - - fMonitor.worked(1); - ModalContext.checkCanceled(fMonitor); - } - /** - * Export the passed file to the specified location - * - * @param file org.eclipse.core.resources.IFile - * @param location org.eclipse.core.runtime.IPath - */ - protected void exportFile2(IFile file, IPath location) throws InterruptedException { - IPath fullPath = location.append(file.getName()); - fMonitor.subTask(file.getFullPath().toString()); - String properPathString = fullPath.toOSString(); - File targetFile = new File(properPathString); - - if (targetFile.exists()) { - if (!targetFile.canWrite()) { - errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, ObfuscatorExportMessages.format("ObfuscatorTransfer.cannotOverwrite", //$NON-NLS-1$ - new Object[] { targetFile.getAbsolutePath()}), null)); - fMonitor.worked(1); - return; - } - - if (overwriteState == OVERWRITE_NONE) - return; - - if (overwriteState != OVERWRITE_ALL) { - String overwriteAnswer = fOverwriteCallback.queryOverwrite(properPathString); - - if (overwriteAnswer.equals(IOverwriteQuery.CANCEL)) - throw new InterruptedException(); - - if (overwriteAnswer.equals(IOverwriteQuery.NO)) { - fMonitor.worked(1); - return; - } - - if (overwriteAnswer.equals(IOverwriteQuery.NO_ALL)) { - fMonitor.worked(1); - overwriteState = OVERWRITE_NONE; - return; - } - - if (overwriteAnswer.equals(IOverwriteQuery.ALL)) - overwriteState = OVERWRITE_ALL; - } - } - - try { - setExporters(file); - fExporter2.write(file, fullPath); - } catch (IOException e) { - errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, ObfuscatorExportMessages.format("ObfuscatorTransfer.errorExporting", //$NON-NLS-1$ - new Object[] { fullPath, e.getMessage()}), e)); - } catch (CoreException e) { - errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, ObfuscatorExportMessages.format("ObfuscatorTransfer.errorExporting", //$NON-NLS-1$ - new Object[] { fullPath, e.getMessage()}), e)); - } - - fMonitor.worked(1); - ModalContext.checkCanceled(fMonitor); - } - - protected void exportSpecifiedResources1() throws InterruptedException { - Iterator resources = fResourcesToExport.iterator(); - IPath initPath = (IPath) fPath.clone(); - - while (resources.hasNext()) { - IResource currentResource = (IResource) resources.next(); - if (!currentResource.isAccessible()) - continue; - setExporters(currentResource); - fPath = initPath; - - if (fResource == null) { - // No root resource specified and creation of containment directories - // is required. Create containers from depth 2 onwards (ie.- project's - // child inclusive) for each resource being exported. - // if (createLeadupStructure) - // createLeadupDirectoriesFor(currentResource); - - } else { - // Root resource specified. Must create containment directories - // from this point onwards for each resource being exported - IPath containersToCreate = - currentResource.getFullPath().removeFirstSegments(fResource.getFullPath().segmentCount()).removeLastSegments(1); - - for (int i = 0; i < containersToCreate.segmentCount(); i++) { - fPath = fPath.append(containersToCreate.segment(i)); - fExporter1.createFolder(fPath); - } - } - - if (currentResource.getType() == IResource.FILE) - exportFile1((IFile) currentResource, fPath); - else { - if (createContainerDirectories) { - fPath = fPath.append(currentResource.getName()); - fExporter1.createFolder(fPath); - } - - try { - exportChildren1(((IContainer) currentResource).members(), fPath); - } catch (CoreException e) { - // should never happen because #isAccessible is called before #members is invoked, - // which implicitly does an existence check - errorTable.add(e.getStatus()); - } - } - } - } - /** - * Export the resources contained in the previously-defined - * resourcesToExport collection - */ - protected void exportSpecifiedResources2() throws InterruptedException { - Iterator resources = fResourcesToExport.iterator(); - IPath initPath = (IPath) fPath.clone(); - - while (resources.hasNext()) { - IResource currentResource = (IResource) resources.next(); - if (!currentResource.isAccessible()) - continue; - setExporters(currentResource); - - fPath = initPath; - - if (fResource == null) { - // No root resource specified and creation of containment directories - // is required. Create containers from depth 2 onwards (ie.- project's - // child inclusive) for each resource being exported. - // if (createLeadupStructure) - // createLeadupDirectoriesFor(currentResource); - - } else { - // Root resource specified. Must create containment directories - // from this point onwards for each resource being exported - IPath containersToCreate = - currentResource.getFullPath().removeFirstSegments(fResource.getFullPath().segmentCount()).removeLastSegments(1); - - for (int i = 0; i < containersToCreate.segmentCount(); i++) { - fPath = fPath.append(containersToCreate.segment(i)); - fExporter2.createFolder(fPath); - } - } - - if (currentResource.getType() == IResource.FILE) - exportFile2((IFile) currentResource, fPath); - else { - if (createContainerDirectories) { - fPath = fPath.append(currentResource.getName()); - fExporter2.createFolder(fPath); - } - - try { - exportChildren2(((IContainer) currentResource).members(), fPath); - } catch (CoreException e) { - // should never happen because #isAccessible is called before #members is invoked, - // which implicitly does an existence check - errorTable.add(e.getStatus()); - } - } - } - } - /** - * Returns the status of the export operation. - * If there were any errors, the result is a status object containing - * individual status objects for each error. - * If there were no errors, the result is a status object with error code OK. - * - * @return the status - */ - public IStatus getStatus() { - IStatus[] errors = new IStatus[errorTable.size()]; - errorTable.toArray(errors); - return new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, errors, ObfuscatorExportMessages.getString("ObfuscatorExportOperation.problemsExporting"), //$NON-NLS-1$ - null); - } - /** - * Answer a boolean indicating whether the passed child is a descendent - * of one or more members of the passed resources collection - * - * @return boolean - * @param resources java.util.List - * @param child org.eclipse.core.resources.IResource - */ - protected boolean isDescendent(List resources, IResource child) { - if (child.getType() == IResource.PROJECT) - return false; - - IResource parent = child.getParent(); - if (resources.contains(parent)) - return true; - - return isDescendent(resources, parent); - } - - private void setExporters(IResource resource) { - if (fCurrentIdentifierMap == null) { - if (fProjectMap == null) { - fProjectMap = new HashMap(); - } - createExporters(resource); - } else { - IProject project = resource.getProject(); - if (!fCurrentProjectName.equals(project.getName())) { - HashMap temp = (HashMap) fProjectMap.get(project.getName()); - if (temp != null) { - fCurrentProjectName = project.getName(); - fCurrentIdentifierMap = temp; - fExporter1 = new ObfuscatorPass1Exporter(new Scanner(false, false), fCurrentIdentifierMap); - fExporter2 = new ObfuscatorPass2Exporter(new Scanner(true, true), fCurrentIdentifierMap); - return; - } - createExporters(resource); - } - } - } - - private void createExporters(IResource resource) { - IProject project = resource.getProject(); - IPreferenceStore store = PHPeclipsePlugin.getDefault().getPreferenceStore(); - ObfuscatorIgnores ignore = new ObfuscatorIgnores(project); - fCurrentIdentifierMap = ignore.getIdentifierMap(); - fCurrentProjectName = project.getName(); - fProjectMap.put(fCurrentProjectName, fCurrentIdentifierMap); - fExporter1 = new ObfuscatorPass1Exporter(new Scanner(false, false), fCurrentIdentifierMap); - fExporter2 = new ObfuscatorPass2Exporter(new Scanner(true, true), fCurrentIdentifierMap); - } - /** - * Export the resources that were previously specified for export - * (or if a single resource was specified then export it recursively) - */ - public void run(IProgressMonitor monitor) throws InterruptedException { - this.fMonitor = monitor; - final IPath tempPath = (IPath) fPath.clone(); - if (fResource != null) { - setExporters(fResource); - // if (createLeadupStructure) - // createLeadupDirectoriesFor(resource); - - if (createContainerDirectories && fResource.getType() != IResource.FILE) { - // ensure it's a container - fPath = fPath.append(fResource.getName()); - fExporter2.createFolder(fPath); - } - } - - try { - // reset variables for this run: - fCurrentIdentifierMap = null; - fProjectMap = null; - fCurrentProjectName = ""; - - // count number of files - int totalWork = IProgressMonitor.UNKNOWN; - try { - if (fResourcesToExport == null) { - totalWork = countChildrenOf(fResource); - } else { - totalWork = countSelectedResources(); - } - } catch (CoreException e) { - // Should not happen - errorTable.add(e.getStatus()); - } - monitor.beginTask(ObfuscatorExportMessages.getString("ObfuscatorTransfer.exportingTitle1"), totalWork); //$NON-NLS-1$ - if (fResourcesToExport == null) { - exportAllResources1(); - } else { - exportSpecifiedResources1(); - } - - // try { - // if (resourcesToExport == null) - // totalWork = countChildrenOf(resource); - // else - // totalWork = countSelectedResources(); - // } catch (CoreException e) { - // // Should not happen - // errorTable.add(e.getStatus()); - // } - - // reset path: - fPath = tempPath; - monitor.beginTask(ObfuscatorExportMessages.getString("ObfuscatorTransfer.exportingTitle2"), totalWork); //$NON-NLS-1$ - if (fResourcesToExport == null) { - exportAllResources2(); - } else { - exportSpecifiedResources2(); - } - } finally { - monitor.done(); - } - } - /** - * Set this boolean indicating whether a directory should be created for - * Folder resources that are explicitly passed for export - * - * @param value boolean - */ - // public void setCreateContainerDirectories(boolean value) { - // createContainerDirectories = value; - // } - /** - * Set this boolean indicating whether each exported resource's complete path should - * include containment hierarchies as dictated by its parents - * - * @param value boolean - */ - // public void setCreateLeadupStructure(boolean value) { - // createLeadupStructure = value; - // } - /** - * Set this boolean indicating whether exported resources should automatically - * overwrite existing files when a conflict occurs. If not - * query the user. - * - * @param value boolean - */ - public void setOverwriteFiles(boolean value) { - if (value) - overwriteState = OVERWRITE_ALL; - } + private IPath fPath; + + private IProgressMonitor fMonitor; + + private ObfuscatorPass1Exporter fExporter1 = null; + + private ObfuscatorPass2Exporter fExporter2 = null; + + private HashMap fCurrentIdentifierMap = null; + + private HashMap fProjectMap = null; + + private String fCurrentProjectName = ""; + + private List fResourcesToExport; + + private IOverwriteQuery fOverwriteCallback; + + private IResource fResource; + + private List errorTable = new ArrayList(1); + + // The constants for the overwrite 3 state + private static final int OVERWRITE_NOT_SET = 0; + + private static final int OVERWRITE_NONE = 1; + + private static final int OVERWRITE_ALL = 2; + + private int overwriteState = OVERWRITE_NOT_SET; + + // private boolean createLeadupStructure = true; + private boolean createContainerDirectories = true; + + /** + * Create an instance of this class. Use this constructor if you wish to + * export specific resources without a common parent resource + */ + // public ObfuscatorExportOperation(List resources, String destinationPath, + // IOverwriteQuery overwriteImplementor) { + // super(); + // + // exporter1 = new ObfuscatorPass1Exporter(new Scanner(false, false), + // identifierMap); + // exporter2 = new ObfuscatorPass2Exporter(new Scanner(true, true), + // identifierMap); + // identifierMap = null; + // + // // Eliminate redundancies in list of resources being exported + // Iterator elementsEnum = resources.iterator(); + // while (elementsEnum.hasNext()) { + // IResource currentResource = (IResource) elementsEnum.next(); + // if (isDescendent(resources, currentResource)) + // elementsEnum.remove(); //Remove currentResource + // } + // + // resourcesToExport = resources; + // path = new Path(destinationPath); + // overwriteCallback = overwriteImplementor; + // } + /** + * Create an instance of this class. Use this constructor if you wish to + * recursively export a single resource + */ + public ObfuscatorExportOperation(IResource res, String destinationPath, + IOverwriteQuery overwriteImplementor) { + super(); + + fResource = res; + fPath = new Path(destinationPath); + fOverwriteCallback = overwriteImplementor; + } + + /** + * Create an instance of this class. Use this constructor if you wish to + * export specific resources with a common parent resource (affects + * container directory creation) + */ + public ObfuscatorExportOperation(IResource res, List resources, + String destinationPath, IOverwriteQuery overwriteImplementor) { + this(res, destinationPath, overwriteImplementor); + fResourcesToExport = resources; + } + + /** + * Add a new entry to the error table with the passed information + */ + protected void addError(String message, Throwable e) { + errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, + message, e)); + } + + /** + * Answer the total number of file resources that exist at or below self in + * the resources hierarchy. + * + * @return int + * @param resource + * org.eclipse.core.resources.IResource + */ + protected int countChildrenOf(IResource resource) throws CoreException { + if (resource.getType() == IResource.FILE) + return 1; + + int count = 0; + if (resource.isAccessible()) { + IResource[] children = ((IContainer) resource).members(); + for (int i = 0; i < children.length; i++) + count += countChildrenOf(children[i]); + } + + return count; + } + + /** + * Answer a boolean indicating the number of file resources that were + * specified for export + * + * @return int + */ + protected int countSelectedResources() throws CoreException { + int result = 0; + Iterator resources = fResourcesToExport.iterator(); + + while (resources.hasNext()) + result += countChildrenOf((IResource) resources.next()); + + return result; + } + + /** + * Create the directories required for exporting the passed resource, based + * upon its container hierarchy + * + * @param resource + * org.eclipse.core.resources.IResource + */ + protected void createLeadupDirectoriesFor(IResource resource) { + IPath resourcePath = resource.getFullPath().removeLastSegments(1); + + for (int i = 0; i < resourcePath.segmentCount(); i++) { + fPath = fPath.append(resourcePath.segment(i)); + fExporter2.createFolder(fPath); + } + } + + /** + * Recursively export the previously-specified resource + */ + protected void exportAllResources1() throws InterruptedException { + if (fResource.getType() == IResource.FILE) { + exportFile1((IFile) fResource, fPath); + } else { + try { + setExporters(fResource); + exportChildren1(((IContainer) fResource).members(), fPath); + } catch (CoreException e) { + // not safe to show a dialog + // should never happen because the file system export wizard + // ensures that the + // single resource chosen for export is both existent and + // accessible + errorTable.add(e); + } + } + } + + /** + * Recursively export the previously-specified resource + */ + protected void exportAllResources2() throws InterruptedException { + if (fResource.getType() == IResource.FILE) { + exportFile2((IFile) fResource, fPath); + } else { + try { + setExporters(fResource); + exportChildren2(((IContainer) fResource).members(), fPath); + } catch (CoreException e) { + // not safe to show a dialog + // should never happen because the file system export wizard + // ensures that the + // single resource chosen for export is both existent and + // accessible + errorTable.add(e); + } + } + } + + /** + * Export all of the resources contained in the passed collection + * + * @param children + * java.util.Enumeration + * @param currentPath + * IPath + */ + protected void exportChildren1(IResource[] children, IPath currentPath) + throws InterruptedException { + for (int i = 0; i < children.length; i++) { + IResource child = children[i]; + if (!child.isAccessible()) + continue; + + if (child.getType() == IResource.FILE) + exportFile1((IFile) child, currentPath); + else { + IPath destination = currentPath.append(child.getName()); + fExporter1.createFolder(destination); + try { + exportChildren1(((IContainer) child).members(), destination); + } catch (CoreException e) { + // not safe to show a dialog + // should never happen because: + // i. this method is called recursively iterating over the + // result of #members, + // which only answers existing children + // ii. there is an #isAccessible check done before #members + // is invoked + errorTable.add(e.getStatus()); + } + } + } + } + + /** + * Export all of the resources contained in the passed collection + * + * @param children + * java.util.Enumeration + * @param currentPath + * IPath + */ + protected void exportChildren2(IResource[] children, IPath currentPath) + throws InterruptedException { + for (int i = 0; i < children.length; i++) { + IResource child = children[i]; + if (!child.isAccessible()) + continue; + + if (child.getType() == IResource.FILE) + exportFile2((IFile) child, currentPath); + else { + IPath destination = currentPath.append(child.getName()); + fExporter2.createFolder(destination); + try { + exportChildren2(((IContainer) child).members(), destination); + } catch (CoreException e) { + // not safe to show a dialog + // should never happen because: + // i. this method is called recursively iterating over the + // result of #members, + // which only answers existing children + // ii. there is an #isAccessible check done before #members + // is invoked + errorTable.add(e.getStatus()); + } + } + } + } + + protected void exportFile1(IFile file, IPath location) + throws InterruptedException { + IPath fullPath = location.append(file.getName()); + fMonitor.subTask(file.getFullPath().toString()); + String properPathString = fullPath.toOSString(); + File targetFile = new File(properPathString); + + // if (targetFile.exists()) { + // if (!targetFile.canWrite()) { + // errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, + // ObfuscatorExportMessages.format("ObfuscatorTransfer.cannotOverwrite", + // //$NON-NLS-1$ + // new Object[] { targetFile.getAbsolutePath()}), null)); + // monitor.worked(1); + // return; + // } + // + // if (overwriteState == OVERWRITE_NONE) + // return; + // + // if (overwriteState != OVERWRITE_ALL) { + // String overwriteAnswer = + // overwriteCallback.queryOverwrite(properPathString); + // + // if (overwriteAnswer.equals(IOverwriteQuery.CANCEL)) + // throw new InterruptedException(); + // + // if (overwriteAnswer.equals(IOverwriteQuery.NO)) { + // monitor.worked(1); + // return; + // } + // + // if (overwriteAnswer.equals(IOverwriteQuery.NO_ALL)) { + // monitor.worked(1); + // overwriteState = OVERWRITE_NONE; + // return; + // } + // + // if (overwriteAnswer.equals(IOverwriteQuery.ALL)) + // overwriteState = OVERWRITE_ALL; + // } + // } + + try { + setExporters(file); + fExporter1.write(file, fullPath); + } catch (IOException e) { + errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, + ObfuscatorExportMessages.format( + "ObfuscatorTransfer.errorExporting", //$NON-NLS-1$ + new Object[] { fullPath, e.getMessage() }), e)); + } catch (CoreException e) { + errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, + ObfuscatorExportMessages.format( + "ObfuscatorTransfer.errorExporting", //$NON-NLS-1$ + new Object[] { fullPath, e.getMessage() }), e)); + } + + fMonitor.worked(1); + ModalContext.checkCanceled(fMonitor); + } + + /** + * Export the passed file to the specified location + * + * @param file + * org.eclipse.core.resources.IFile + * @param location + * org.eclipse.core.runtime.IPath + */ + protected void exportFile2(IFile file, IPath location) + throws InterruptedException { + IPath fullPath = location.append(file.getName()); + fMonitor.subTask(file.getFullPath().toString()); + String properPathString = fullPath.toOSString(); + File targetFile = new File(properPathString); + + if (targetFile.exists()) { + if (!targetFile.canWrite()) { + errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, + 0, ObfuscatorExportMessages.format( + "ObfuscatorTransfer.cannotOverwrite", //$NON-NLS-1$ + new Object[] { targetFile.getAbsolutePath() }), + null)); + fMonitor.worked(1); + return; + } + + if (overwriteState == OVERWRITE_NONE) + return; + + if (overwriteState != OVERWRITE_ALL) { + String overwriteAnswer = fOverwriteCallback + .queryOverwrite(properPathString); + + if (overwriteAnswer.equals(IOverwriteQuery.CANCEL)) + throw new InterruptedException(); + + if (overwriteAnswer.equals(IOverwriteQuery.NO)) { + fMonitor.worked(1); + return; + } + + if (overwriteAnswer.equals(IOverwriteQuery.NO_ALL)) { + fMonitor.worked(1); + overwriteState = OVERWRITE_NONE; + return; + } + + if (overwriteAnswer.equals(IOverwriteQuery.ALL)) + overwriteState = OVERWRITE_ALL; + } + } + + try { + setExporters(file); + fExporter2.write(file, fullPath); + } catch (IOException e) { + errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, + ObfuscatorExportMessages.format( + "ObfuscatorTransfer.errorExporting", //$NON-NLS-1$ + new Object[] { fullPath, e.getMessage() }), e)); + } catch (CoreException e) { + errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, + ObfuscatorExportMessages.format( + "ObfuscatorTransfer.errorExporting", //$NON-NLS-1$ + new Object[] { fullPath, e.getMessage() }), e)); + } + + fMonitor.worked(1); + ModalContext.checkCanceled(fMonitor); + } + + protected void exportSpecifiedResources1() throws InterruptedException { + Iterator resources = fResourcesToExport.iterator(); + IPath initPath = (IPath) fPath.clone(); + + while (resources.hasNext()) { + IResource currentResource = (IResource) resources.next(); + if (!currentResource.isAccessible()) + continue; + setExporters(currentResource); + fPath = initPath; + + if (fResource == null) { + // No root resource specified and creation of containment + // directories + // is required. Create containers from depth 2 onwards (ie.- + // project's + // child inclusive) for each resource being exported. + // if (createLeadupStructure) + // createLeadupDirectoriesFor(currentResource); + + } else { + // Root resource specified. Must create containment directories + // from this point onwards for each resource being exported + IPath containersToCreate = currentResource.getFullPath() + .removeFirstSegments( + fResource.getFullPath().segmentCount()) + .removeLastSegments(1); + + for (int i = 0; i < containersToCreate.segmentCount(); i++) { + fPath = fPath.append(containersToCreate.segment(i)); + fExporter1.createFolder(fPath); + } + } + + if (currentResource.getType() == IResource.FILE) + exportFile1((IFile) currentResource, fPath); + else { + if (createContainerDirectories) { + fPath = fPath.append(currentResource.getName()); + fExporter1.createFolder(fPath); + } + + try { + exportChildren1(((IContainer) currentResource).members(), + fPath); + } catch (CoreException e) { + // should never happen because #isAccessible is called + // before #members is invoked, + // which implicitly does an existence check + errorTable.add(e.getStatus()); + } + } + } + } + + /** + * Export the resources contained in the previously-defined + * resourcesToExport collection + */ + protected void exportSpecifiedResources2() throws InterruptedException { + Iterator resources = fResourcesToExport.iterator(); + IPath initPath = (IPath) fPath.clone(); + + while (resources.hasNext()) { + IResource currentResource = (IResource) resources.next(); + if (!currentResource.isAccessible()) + continue; + setExporters(currentResource); + + fPath = initPath; + + if (fResource == null) { + // No root resource specified and creation of containment + // directories + // is required. Create containers from depth 2 onwards (ie.- + // project's + // child inclusive) for each resource being exported. + // if (createLeadupStructure) + // createLeadupDirectoriesFor(currentResource); + + } else { + // Root resource specified. Must create containment directories + // from this point onwards for each resource being exported + IPath containersToCreate = currentResource.getFullPath() + .removeFirstSegments( + fResource.getFullPath().segmentCount()) + .removeLastSegments(1); + + for (int i = 0; i < containersToCreate.segmentCount(); i++) { + fPath = fPath.append(containersToCreate.segment(i)); + fExporter2.createFolder(fPath); + } + } + + if (currentResource.getType() == IResource.FILE) + exportFile2((IFile) currentResource, fPath); + else { + if (createContainerDirectories) { + fPath = fPath.append(currentResource.getName()); + fExporter2.createFolder(fPath); + } + + try { + exportChildren2(((IContainer) currentResource).members(), + fPath); + } catch (CoreException e) { + // should never happen because #isAccessible is called + // before #members is invoked, + // which implicitly does an existence check + errorTable.add(e.getStatus()); + } + } + } + } + + /** + * Returns the status of the export operation. If there were any errors, the + * result is a status object containing individual status objects for each + * error. If there were no errors, the result is a status object with error + * code OK. + * + * @return the status + */ + public IStatus getStatus() { + IStatus[] errors = new IStatus[errorTable.size()]; + errorTable.toArray(errors); + return new MultiStatus( + PlatformUI.PLUGIN_ID, + IStatus.OK, + errors, + ObfuscatorExportMessages + .getString("ObfuscatorExportOperation.problemsExporting"), //$NON-NLS-1$ + null); + } + + /** + * Answer a boolean indicating whether the passed child is a descendent of + * one or more members of the passed resources collection + * + * @return boolean + * @param resources + * java.util.List + * @param child + * org.eclipse.core.resources.IResource + */ + protected boolean isDescendent(List resources, IResource child) { + if (child.getType() == IResource.PROJECT) + return false; + + IResource parent = child.getParent(); + if (resources.contains(parent)) + return true; + + return isDescendent(resources, parent); + } + + private void setExporters(IResource resource) { + if (fCurrentIdentifierMap == null) { + if (fProjectMap == null) { + fProjectMap = new HashMap(); + } + createExporters(resource); + } else { + IProject project = resource.getProject(); + if (!fCurrentProjectName.equals(project.getName())) { + HashMap temp = (HashMap) fProjectMap.get(project.getName()); + if (temp != null) { + fCurrentProjectName = project.getName(); + fCurrentIdentifierMap = temp; + fExporter1 = new ObfuscatorPass1Exporter(new Scanner(false, + false), fCurrentIdentifierMap); + fExporter2 = new ObfuscatorPass2Exporter(new Scanner(true, + true), fCurrentIdentifierMap); + return; + } + createExporters(resource); + } + } + } + + private void createExporters(IResource resource) { + IProject project = resource.getProject(); + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + ObfuscatorIgnores ignore = new ObfuscatorIgnores(project); + fCurrentIdentifierMap = ignore.getIdentifierMap(); + fCurrentProjectName = project.getName(); + fProjectMap.put(fCurrentProjectName, fCurrentIdentifierMap); + fExporter1 = new ObfuscatorPass1Exporter(new Scanner(false, false), + fCurrentIdentifierMap); + fExporter2 = new ObfuscatorPass2Exporter(new Scanner(true, true), + fCurrentIdentifierMap); + } + + /** + * Export the resources that were previously specified for export (or if a + * single resource was specified then export it recursively) + */ + public void run(IProgressMonitor monitor) throws InterruptedException { + this.fMonitor = monitor; + final IPath tempPath = (IPath) fPath.clone(); + if (fResource != null) { + setExporters(fResource); + // if (createLeadupStructure) + // createLeadupDirectoriesFor(resource); + + if (createContainerDirectories + && fResource.getType() != IResource.FILE) { + // ensure it's a container + fPath = fPath.append(fResource.getName()); + fExporter2.createFolder(fPath); + } + } + + try { + // reset variables for this run: + fCurrentIdentifierMap = null; + fProjectMap = null; + fCurrentProjectName = ""; + + // count number of files + int totalWork = IProgressMonitor.UNKNOWN; + try { + if (fResourcesToExport == null) { + totalWork = countChildrenOf(fResource); + } else { + totalWork = countSelectedResources(); + } + } catch (CoreException e) { + // Should not happen + errorTable.add(e.getStatus()); + } + monitor + .beginTask( + ObfuscatorExportMessages + .getString("ObfuscatorTransfer.exportingTitle1"), totalWork); //$NON-NLS-1$ + if (fResourcesToExport == null) { + exportAllResources1(); + } else { + exportSpecifiedResources1(); + } + + // try { + // if (resourcesToExport == null) + // totalWork = countChildrenOf(resource); + // else + // totalWork = countSelectedResources(); + // } catch (CoreException e) { + // // Should not happen + // errorTable.add(e.getStatus()); + // } + + // reset path: + fPath = tempPath; + monitor + .beginTask( + ObfuscatorExportMessages + .getString("ObfuscatorTransfer.exportingTitle2"), totalWork); //$NON-NLS-1$ + if (fResourcesToExport == null) { + exportAllResources2(); + } else { + exportSpecifiedResources2(); + } + } finally { + monitor.done(); + } + } + + /** + * Set this boolean indicating whether a directory should be created for + * Folder resources that are explicitly passed for export + * + * @param value + * boolean + */ + // public void setCreateContainerDirectories(boolean value) { + // createContainerDirectories = value; + // } + /** + * Set this boolean indicating whether each exported resource's complete + * path should include containment hierarchies as dictated by its parents + * + * @param value + * boolean + */ + // public void setCreateLeadupStructure(boolean value) { + // createLeadupStructure = value; + // } + /** + * Set this boolean indicating whether exported resources should + * automatically overwrite existing files when a conflict occurs. If not + * query the user. + * + * @param value + * boolean + */ + public void setOverwriteFiles(boolean value) { + if (value) + overwriteState = OVERWRITE_ALL; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/ObfuscatorExportWizard.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/ObfuscatorExportWizard.java index 3e92b98..5111b04 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/ObfuscatorExportWizard.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/ObfuscatorExportWizard.java @@ -27,99 +27,113 @@ import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.plugin.AbstractUIPlugin; - /** - * Standard workbench wizard for exporting resources from the workspace - * to the local file system. + * Standard workbench wizard for exporting resources from the workspace to the + * local file system. *

                                                      - * This class may be instantiated and used without further configuration; - * this class is not intended to be subclassed. + * This class may be instantiated and used without further configuration; this + * class is not intended to be subclassed. *

                                                      *

                                                      * Example: + * *

                                                        * IWizard wizard = new ObfuscatorExportWizard();
                                                        * wizard.init(workbench, selection);
                                                        * WizardDialog dialog = new WizardDialog(shell, wizard);
                                                        * dialog.open();
                                                        * 
                                                      - * During the call to open, the wizard dialog is presented to the - * user. When the user hits Finish, the user-selected workspace resources - * are exported to the user-specified location in the local file system, - * the dialog closes, and the call to open returns. + * + * During the call to open, the wizard dialog is presented to + * the user. When the user hits Finish, the user-selected workspace resources + * are exported to the user-specified location in the local file system, the + * dialog closes, and the call to open returns. *

                                                      */ public class ObfuscatorExportWizard extends Wizard implements IExportWizard { private IWorkbench workbench; + private IStructuredSelection selection; + private WizardObfuscatorResourceExportPage1 mainPage; -/** - * Creates a wizard for exporting workspace resources to the local file system. - */ -public ObfuscatorExportWizard() { - AbstractUIPlugin plugin = (AbstractUIPlugin) Platform.getPlugin(PlatformUI.PLUGIN_ID); - IDialogSettings workbenchSettings = plugin.getDialogSettings(); - IDialogSettings section = workbenchSettings.getSection("ObfuscatorExportWizard");//$NON-NLS-1$ - if(section == null) - section = workbenchSettings.addNewSection("ObfuscatorExportWizard");//$NON-NLS-1$ - setDialogSettings(section); -} -/* (non-Javadoc) - * Method declared on IWizard. - */ -public void addPages() { - super.addPages(); - mainPage = new WizardObfuscatorResourceExportPage1(selection); - addPage(mainPage); -} -/** - * Returns the image descriptor with the given relative path. - */ -private ImageDescriptor getImageDescriptor(String relativePath) { - String iconPath = "icons/full/";//$NON-NLS-1$ - try { - AbstractUIPlugin plugin = (AbstractUIPlugin) Platform.getPlugin(PlatformUI.PLUGIN_ID); - URL installURL = plugin.getBundle().getEntry("/"); - URL url = new URL(installURL, iconPath + relativePath); - return ImageDescriptor.createFromURL(url); + + /** + * Creates a wizard for exporting workspace resources to the local file + * system. + */ + public ObfuscatorExportWizard() { + AbstractUIPlugin plugin = (AbstractUIPlugin) Platform + .getPlugin(PlatformUI.PLUGIN_ID); + IDialogSettings workbenchSettings = plugin.getDialogSettings(); + IDialogSettings section = workbenchSettings + .getSection("ObfuscatorExportWizard");//$NON-NLS-1$ + if (section == null) + section = workbenchSettings.addNewSection("ObfuscatorExportWizard");//$NON-NLS-1$ + setDialogSettings(section); } - catch (MalformedURLException e) { - // Should not happen - return null; + + /* + * (non-Javadoc) Method declared on IWizard. + */ + public void addPages() { + super.addPages(); + mainPage = new WizardObfuscatorResourceExportPage1(selection); + addPage(mainPage); + } + + /** + * Returns the image descriptor with the given relative path. + */ + private ImageDescriptor getImageDescriptor(String relativePath) { + String iconPath = "icons/full/";//$NON-NLS-1$ + try { + AbstractUIPlugin plugin = (AbstractUIPlugin) Platform + .getPlugin(PlatformUI.PLUGIN_ID); + URL installURL = plugin.getBundle().getEntry("/"); + URL url = new URL(installURL, iconPath + relativePath); + return ImageDescriptor.createFromURL(url); + } catch (MalformedURLException e) { + // Should not happen + return null; + } } -} -/* (non-Javadoc) - * Method declared on IWorkbenchWizard. - */ -public void init(IWorkbench workbench, IStructuredSelection currentSelection) { - this.workbench = workbench; + /* + * (non-Javadoc) Method declared on IWorkbenchWizard. + */ + public void init(IWorkbench workbench, IStructuredSelection currentSelection) { + this.workbench = workbench; - //Make it the current selection by default but look it up otherwise + // Make it the current selection by default but look it up otherwise - selection = currentSelection; + selection = currentSelection; - if(currentSelection.isEmpty() && workbench.getActiveWorkbenchWindow() != null){ - IWorkbenchPage page = workbench.getActiveWorkbenchWindow().getActivePage(); - if(page != null){ - IEditorPart currentEditor = page.getActiveEditor(); - if(currentEditor != null){ - Object selectedResource = currentEditor.getEditorInput().getAdapter(IResource.class); - if(selectedResource != null) - selection = new StructuredSelection(selectedResource); + if (currentSelection.isEmpty() + && workbench.getActiveWorkbenchWindow() != null) { + IWorkbenchPage page = workbench.getActiveWorkbenchWindow() + .getActivePage(); + if (page != null) { + IEditorPart currentEditor = page.getActiveEditor(); + if (currentEditor != null) { + Object selectedResource = currentEditor.getEditorInput() + .getAdapter(IResource.class); + if (selectedResource != null) + selection = new StructuredSelection(selectedResource); + } } } + + setWindowTitle(ObfuscatorExportMessages + .getString("ObfuscatorTransfer.export")); //$NON-NLS-1$ + setDefaultPageImageDescriptor(getImageDescriptor("wizban/exportdir_wiz.gif"));//$NON-NLS-1$ + setNeedsProgressMonitor(true); } - setWindowTitle(ObfuscatorExportMessages.getString("ObfuscatorTransfer.export")); //$NON-NLS-1$ - setDefaultPageImageDescriptor(getImageDescriptor("wizban/exportdir_wiz.gif"));//$NON-NLS-1$ - setNeedsProgressMonitor(true); -} -/* (non-Javadoc) - * Method declared on IWizard. - */ -public boolean performFinish() { - return mainPage.finish(); -} + /* + * (non-Javadoc) Method declared on IWizard. + */ + public boolean performFinish() { + return mainPage.finish(); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/WizardObfuscatorResourceExportPage1.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/WizardObfuscatorResourceExportPage1.java index 2b0c9e2..bb5dd99 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/WizardObfuscatorResourceExportPage1.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/WizardObfuscatorResourceExportPage1.java @@ -9,7 +9,7 @@ * IBM Corporation - initial API and implementation *******************************************************************************/ package net.sourceforge.phpeclipse.obfuscator.export; - + import java.io.File; import java.lang.reflect.InvocationTargetException; import java.util.List; @@ -40,71 +40,85 @@ import org.eclipse.swt.widgets.Widget; import org.eclipse.ui.dialogs.WizardExportResourcesPage; /** - * Page 1 of the base resource export-to-file-system Wizard + * Page 1 of the base resource export-to-file-system Wizard */ -/*package*/ -class WizardObfuscatorResourceExportPage1 - extends WizardExportResourcesPage - implements Listener { +/* package */ +class WizardObfuscatorResourceExportPage1 extends WizardExportResourcesPage + implements Listener { // widgets private Combo destinationNameField; + private Button destinationBrowseButton; + protected Button overwriteExistingFilesCheckbox; -// protected Button createDirectoryStructureButton; -// protected Button createSelectionOnlyButton; + + // protected Button createDirectoryStructureButton; + // protected Button createSelectionOnlyButton; // constants private static final int SIZING_TEXT_FIELD_WIDTH = 250; // dialog store id constants - private static final String STORE_DESTINATION_NAMES_ID = - "WizardObfuscatorResourceExportPage1.STORE_DESTINATION_NAMES_ID"; //$NON-NLS-1$ - private static final String STORE_OVERWRITE_EXISTING_FILES_ID = - "WizardObfuscatorResourceExportPage1.STORE_OVERWRITE_EXISTING_FILES_ID"; //$NON-NLS-1$ -// private static final String STORE_CREATE_STRUCTURE_ID = -// "WizardObfuscatorResourceExportPage1.STORE_CREATE_STRUCTURE_ID"; //$NON-NLS-1$ - //messages - private static final String SELECT_DESTINATION_MESSAGE = ObfuscatorExportMessages.getString("FileExport.selectDestinationMessage"); //$NON-NLS-1$ - private static final String SELECT_DESTINATION_TITLE = ObfuscatorExportMessages.getString("FileExport.selectDestinationTitle"); //$NON-NLS-1$ + private static final String STORE_DESTINATION_NAMES_ID = "WizardObfuscatorResourceExportPage1.STORE_DESTINATION_NAMES_ID"; //$NON-NLS-1$ + + private static final String STORE_OVERWRITE_EXISTING_FILES_ID = "WizardObfuscatorResourceExportPage1.STORE_OVERWRITE_EXISTING_FILES_ID"; //$NON-NLS-1$ + // private static final String STORE_CREATE_STRUCTURE_ID = + // "WizardObfuscatorResourceExportPage1.STORE_CREATE_STRUCTURE_ID"; + // //$NON-NLS-1$ + + // messages + private static final String SELECT_DESTINATION_MESSAGE = ObfuscatorExportMessages + .getString("FileExport.selectDestinationMessage"); //$NON-NLS-1$ + + private static final String SELECT_DESTINATION_TITLE = ObfuscatorExportMessages + .getString("FileExport.selectDestinationTitle"); //$NON-NLS-1$ + /** - * Create an instance of this class + * Create an instance of this class */ - protected WizardObfuscatorResourceExportPage1( - String name, - IStructuredSelection selection) { + protected WizardObfuscatorResourceExportPage1(String name, + IStructuredSelection selection) { super(name, selection); } + /** - * Create an instance of this class + * Create an instance of this class */ public WizardObfuscatorResourceExportPage1(IStructuredSelection selection) { this("fileSystemExportPage1", selection); //$NON-NLS-1$ - setTitle(ObfuscatorExportMessages.getString("ObfuscatorTransfer.fileSystemTitle")); //$NON-NLS-1$ - setDescription(ObfuscatorExportMessages.getString("FileExport.exportLocalFileSystem")); //$NON-NLS-1$ + setTitle(ObfuscatorExportMessages + .getString("ObfuscatorTransfer.fileSystemTitle")); //$NON-NLS-1$ + setDescription(ObfuscatorExportMessages + .getString("FileExport.exportLocalFileSystem")); //$NON-NLS-1$ } + /** - * Add the passed value to self's destination widget's history - * - * @param value java.lang.String + * Add the passed value to self's destination widget's history + * + * @param value + * java.lang.String */ protected void addDestinationItem(String value) { destinationNameField.add(value); } - /** (non-Javadoc) - * Method declared on IDialogPage. + + /** + * (non-Javadoc) Method declared on IDialogPage. */ public void createControl(Composite parent) { super.createControl(parent); giveFocusToDestination(); -// WorkbenchHelp.setHelp( -// getControl(), -// IDataTransferHelpContextIds.FILE_SYSTEM_EXPORT_WIZARD_PAGE); + // WorkbenchHelp.setHelp( + // getControl(), + // IDataTransferHelpContextIds.FILE_SYSTEM_EXPORT_WIZARD_PAGE); } + /** - * Create the export destination specification widgets - * - * @param parent org.eclipse.swt.widgets.Composite + * Create the export destination specification widgets + * + * @param parent + * org.eclipse.swt.widgets.Composite */ protected void createDestinationGroup(Composite parent) { @@ -114,8 +128,7 @@ class WizardObfuscatorResourceExportPage1 GridLayout layout = new GridLayout(); layout.numColumns = 3; destinationSelectionGroup.setLayout(layout); - destinationSelectionGroup.setLayoutData( - new GridData( + destinationSelectionGroup.setLayoutData(new GridData( GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL)); destinationSelectionGroup.setFont(font); @@ -124,21 +137,21 @@ class WizardObfuscatorResourceExportPage1 destinationLabel.setFont(font); // destination name entry field - destinationNameField = - new Combo(destinationSelectionGroup, SWT.SINGLE | SWT.BORDER); + destinationNameField = new Combo(destinationSelectionGroup, SWT.SINGLE + | SWT.BORDER); destinationNameField.addListener(SWT.Modify, this); destinationNameField.addListener(SWT.Selection, this); - GridData data = - new GridData( - GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL); + GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL + | GridData.GRAB_HORIZONTAL); data.widthHint = SIZING_TEXT_FIELD_WIDTH; destinationNameField.setLayoutData(data); destinationNameField.setFont(font); // destination browse button - destinationBrowseButton = - new Button(destinationSelectionGroup, SWT.PUSH); - destinationBrowseButton.setText(ObfuscatorExportMessages.getString("ObfuscatorTransfer.browse")); //$NON-NLS-1$ + destinationBrowseButton = new Button(destinationSelectionGroup, + SWT.PUSH); + destinationBrowseButton.setText(ObfuscatorExportMessages + .getString("ObfuscatorTransfer.browse")); //$NON-NLS-1$ destinationBrowseButton.addListener(SWT.Selection, this); destinationBrowseButton.setFont(font); setButtonLayoutData(destinationBrowseButton); @@ -155,63 +168,69 @@ class WizardObfuscatorResourceExportPage1 Font font = optionsGroup.getFont(); createOverwriteExisting(optionsGroup, font); -// createDirectoryStructureOptions(optionsGroup, font); + // createDirectoryStructureOptions(optionsGroup, font); } /** - * Create the buttons for the group that determine if the entire or - * selected directory structure should be created. + * Create the buttons for the group that determine if the entire or selected + * directory structure should be created. + * * @param optionsGroup * @param font */ -// protected void createDirectoryStructureOptions( -// Group optionsGroup, -// Font font) { -// // create directory structure radios -// createDirectoryStructureButton = -// new Button(optionsGroup, SWT.RADIO | SWT.LEFT); -// createDirectoryStructureButton.setText(ObfuscatorExportMessages.getString("FileExport.createDirectoryStructure")); //$NON-NLS-1$ -// createDirectoryStructureButton.setSelection(false); -// createDirectoryStructureButton.setFont(font); -// -// // create directory structure radios -// createSelectionOnlyButton = -// new Button(optionsGroup, SWT.RADIO | SWT.LEFT); -// createSelectionOnlyButton.setText( -// ObfuscatorExportMessages.getString( -// "FileExport.createSelectedDirectories"));//$NON-NLS-1$ -// createSelectionOnlyButton.setSelection(true); -// createSelectionOnlyButton.setFont(font); -// } - + // protected void createDirectoryStructureOptions( + // Group optionsGroup, + // Font font) { + // // create directory structure radios + // createDirectoryStructureButton = + // new Button(optionsGroup, SWT.RADIO | SWT.LEFT); + // createDirectoryStructureButton.setText(ObfuscatorExportMessages.getString("FileExport.createDirectoryStructure")); + // //$NON-NLS-1$ + // createDirectoryStructureButton.setSelection(false); + // createDirectoryStructureButton.setFont(font); + // + // // create directory structure radios + // createSelectionOnlyButton = + // new Button(optionsGroup, SWT.RADIO | SWT.LEFT); + // createSelectionOnlyButton.setText( + // ObfuscatorExportMessages.getString( + // "FileExport.createSelectedDirectories"));//$NON-NLS-1$ + // createSelectionOnlyButton.setSelection(true); + // createSelectionOnlyButton.setFont(font); + // } /** * Create the button for checking if we should ask if we are going to * overwrite existing files. + * * @param optionsGroup * @param font */ protected void createOverwriteExisting(Group optionsGroup, Font font) { // overwrite... checkbox - overwriteExistingFilesCheckbox = - new Button(optionsGroup, SWT.CHECK | SWT.LEFT); - overwriteExistingFilesCheckbox.setText(ObfuscatorExportMessages.getString("ExportFile.overwriteExisting")); //$NON-NLS-1$ + overwriteExistingFilesCheckbox = new Button(optionsGroup, SWT.CHECK + | SWT.LEFT); + overwriteExistingFilesCheckbox.setText(ObfuscatorExportMessages + .getString("ExportFile.overwriteExisting")); //$NON-NLS-1$ overwriteExistingFilesCheckbox.setFont(font); } /** - * Attempts to ensure that the specified directory exists on the local file system. - * Answers a boolean indicating success. - * + * Attempts to ensure that the specified directory exists on the local file + * system. Answers a boolean indicating success. + * * @return boolean - * @param directory java.io.File + * @param directory + * java.io.File */ protected boolean ensureDirectoryExists(File directory) { if (!directory.exists()) { - if (!queryYesNoQuestion(ObfuscatorExportMessages.getString("ObfuscatorTransfer.createTargetDirectory"))) //$NON-NLS-1$ + if (!queryYesNoQuestion(ObfuscatorExportMessages + .getString("ObfuscatorTransfer.createTargetDirectory"))) //$NON-NLS-1$ return false; if (!directory.mkdirs()) { - displayErrorDialog(ObfuscatorExportMessages.getString("ObfuscatorTransfer.directoryCreationError")); //$NON-NLS-1$ + displayErrorDialog(ObfuscatorExportMessages + .getString("ObfuscatorTransfer.directoryCreationError")); //$NON-NLS-1$ giveFocusToDestination(); return false; } @@ -219,30 +238,34 @@ class WizardObfuscatorResourceExportPage1 return true; } + /** - * If the target for export does not exist then attempt to create it. - * Answer a boolean indicating whether the target exists (ie.- if it - * either pre-existed or this method was able to create it) - * - * @return boolean + * If the target for export does not exist then attempt to create it. Answer + * a boolean indicating whether the target exists (ie.- if it either + * pre-existed or this method was able to create it) + * + * @return boolean */ protected boolean ensureTargetIsValid(File targetDirectory) { if (targetDirectory.exists() && !targetDirectory.isDirectory()) { - displayErrorDialog(ObfuscatorExportMessages.getString("FileExport.directoryExists")); //$NON-NLS-1$ + displayErrorDialog(ObfuscatorExportMessages + .getString("FileExport.directoryExists")); //$NON-NLS-1$ giveFocusToDestination(); return false; } return ensureDirectoryExists(targetDirectory); } + /** - * Set up and execute the passed Operation. Answer a boolean indicating success. - * - * @return boolean + * Set up and execute the passed Operation. Answer a boolean indicating + * success. + * + * @return boolean */ protected boolean executeExportOperation(ObfuscatorExportOperation op) { -// op.setCreateLeadupStructure( -// createDirectoryStructureButton.getSelection()); + // op.setCreateLeadupStructure( + // createDirectoryStructureButton.getSelection()); op.setOverwriteFiles(overwriteExistingFilesCheckbox.getSelection()); try { @@ -256,20 +279,23 @@ class WizardObfuscatorResourceExportPage1 IStatus status = op.getStatus(); if (!status.isOK()) { - ErrorDialog.openError(getContainer().getShell(), ObfuscatorExportMessages.getString("ObfuscatorTransfer.exportProblems"), //$NON-NLS-1$ - null, // no special message - status); + ErrorDialog.openError(getContainer().getShell(), + ObfuscatorExportMessages + .getString("ObfuscatorTransfer.exportProblems"), //$NON-NLS-1$ + null, // no special message + status); return false; } return true; } + /** - * The Finish button was pressed. Try to do the required work now and answer - * a boolean indicating success. If false is returned then the wizard will - * not close. - * - * @return boolean + * The Finish button was pressed. Try to do the required work now and answer + * a boolean indicating success. If false is returned then the wizard will + * not close. + * + * @return boolean */ public boolean finish() { if (!ensureTargetIsValid(new File(getDestinationValue()))) @@ -277,53 +303,55 @@ class WizardObfuscatorResourceExportPage1 List resourcesToExport = getWhiteCheckedResources(); - //Save dirty editors if possible but do not stop if not all are saved + // Save dirty editors if possible but do not stop if not all are saved saveDirtyEditors(); // about to invoke the operation so save our state saveWidgetValues(); if (resourcesToExport.size() > 0) - return executeExportOperation( - new ObfuscatorExportOperation( - null, - resourcesToExport, - getDestinationValue(), - this)); + return executeExportOperation(new ObfuscatorExportOperation(null, + resourcesToExport, getDestinationValue(), this)); - MessageDialog.openInformation(getContainer().getShell(), ObfuscatorExportMessages.getString("ObfuscatorTransfer.information"), //$NON-NLS-1$ - ObfuscatorExportMessages.getString("FileExport.noneSelected")); //$NON-NLS-1$ + MessageDialog.openInformation(getContainer().getShell(), + ObfuscatorExportMessages + .getString("ObfuscatorTransfer.information"), //$NON-NLS-1$ + ObfuscatorExportMessages.getString("FileExport.noneSelected")); //$NON-NLS-1$ return false; } + /** - * Answer the string to display in self as the destination type - * - * @return java.lang.String + * Answer the string to display in self as the destination type + * + * @return java.lang.String */ protected String getDestinationLabel() { return ObfuscatorExportMessages.getString("FileExport.toDirectory"); //$NON-NLS-1$ } + /** - * Answer the contents of self's destination specification widget - * - * @return java.lang.String + * Answer the contents of self's destination specification widget + * + * @return java.lang.String */ protected String getDestinationValue() { return destinationNameField.getText().trim(); } + /** - * Set the current input focus to self's destination entry field + * Set the current input focus to self's destination entry field */ protected void giveFocusToDestination() { destinationNameField.setFocus(); } + /** - * Open an appropriate destination browser so that the user can specify a source - * to import from + * Open an appropriate destination browser so that the user can specify a + * source to import from */ protected void handleDestinationBrowseButtonPressed() { - DirectoryDialog dialog = - new DirectoryDialog(getContainer().getShell(), SWT.SAVE); + DirectoryDialog dialog = new DirectoryDialog(getContainer().getShell(), + SWT.SAVE); dialog.setMessage(SELECT_DESTINATION_MESSAGE); dialog.setText(SELECT_DESTINATION_TITLE); dialog.setFilterPath(getDestinationValue()); @@ -334,9 +362,12 @@ class WizardObfuscatorResourceExportPage1 setDestinationValue(selectedDirectoryName); } } + /** * Handle all events and enablements for widgets in this page - * @param e Event + * + * @param e + * Event */ public void handleEvent(Event e) { Widget source = e.widget; @@ -346,43 +377,43 @@ class WizardObfuscatorResourceExportPage1 updatePageCompletion(); } + /** - * Hook method for saving widget values for restoration by the next instance - * of this class. + * Hook method for saving widget values for restoration by the next instance + * of this class. */ protected void internalSaveWidgetValues() { // update directory names history IDialogSettings settings = getDialogSettings(); if (settings != null) { - String[] directoryNames = - settings.getArray(STORE_DESTINATION_NAMES_ID); + String[] directoryNames = settings + .getArray(STORE_DESTINATION_NAMES_ID); if (directoryNames == null) directoryNames = new String[0]; - directoryNames = - addToHistory(directoryNames, getDestinationValue()); + directoryNames = addToHistory(directoryNames, getDestinationValue()); settings.put(STORE_DESTINATION_NAMES_ID, directoryNames); // options - settings.put( - STORE_OVERWRITE_EXISTING_FILES_ID, - overwriteExistingFilesCheckbox.getSelection()); + settings.put(STORE_OVERWRITE_EXISTING_FILES_ID, + overwriteExistingFilesCheckbox.getSelection()); -// settings.put( -// STORE_CREATE_STRUCTURE_ID, -// createDirectoryStructureButton.getSelection()); + // settings.put( + // STORE_CREATE_STRUCTURE_ID, + // createDirectoryStructureButton.getSelection()); } } + /** - * Hook method for restoring widget values to the values that they held - * last time this wizard was used to completion. + * Hook method for restoring widget values to the values that they held last + * time this wizard was used to completion. */ protected void restoreWidgetValues() { IDialogSettings settings = getDialogSettings(); if (settings != null) { - String[] directoryNames = - settings.getArray(STORE_DESTINATION_NAMES_ID); + String[] directoryNames = settings + .getArray(STORE_DESTINATION_NAMES_ID); if (directoryNames == null) return; // ie.- no settings stored @@ -392,26 +423,28 @@ class WizardObfuscatorResourceExportPage1 addDestinationItem(directoryNames[i]); // options - overwriteExistingFilesCheckbox.setSelection( - settings.getBoolean(STORE_OVERWRITE_EXISTING_FILES_ID)); + overwriteExistingFilesCheckbox.setSelection(settings + .getBoolean(STORE_OVERWRITE_EXISTING_FILES_ID)); -// boolean createDirectories = -// settings.getBoolean(STORE_CREATE_STRUCTURE_ID); -// createDirectoryStructureButton.setSelection(createDirectories); -// createSelectionOnlyButton.setSelection(!createDirectories); + // boolean createDirectories = + // settings.getBoolean(STORE_CREATE_STRUCTURE_ID); + // createDirectoryStructureButton.setSelection(createDirectories); + // createSelectionOnlyButton.setSelection(!createDirectories); } } + /** - * Set the contents of the receivers destination specification widget to - * the passed value - * + * Set the contents of the receivers destination specification widget to the + * passed value + * */ protected void setDestinationValue(String value) { destinationNameField.setText(value); } + /** - * Answer a boolean indicating whether the receivers destination specification - * widgets currently all contain valid values. + * Answer a boolean indicating whether the receivers destination + * specification widgets currently all contain valid values. */ protected boolean validateDestinationGroup() { String destinationValue = getDestinationValue(); @@ -420,32 +453,34 @@ class WizardObfuscatorResourceExportPage1 return false; } - String conflictingContainer = - getConflictingContainerNameFor(destinationValue); + String conflictingContainer = getConflictingContainerNameFor(destinationValue); if (conflictingContainer == null) setErrorMessage(""); //$NON-NLS-1$ else { - setErrorMessage(ObfuscatorExportMessages.format("FileExport.conflictingContainer", //$NON-NLS-1$ - new Object[] { conflictingContainer })); + setErrorMessage(ObfuscatorExportMessages.format( + "FileExport.conflictingContainer", //$NON-NLS-1$ + new Object[] { conflictingContainer })); giveFocusToDestination(); return false; } return true; } - + /** * Get the message used to denote an empty destination. */ - protected String destinationEmptyMessage(){ - return ObfuscatorExportMessages.getString("FileExport.destinationEmpty"); //$NON-NLS-1$ + protected String destinationEmptyMessage() { + return ObfuscatorExportMessages + .getString("FileExport.destinationEmpty"); //$NON-NLS-1$ } /** - * Returns the name of a container with a location that encompasses targetDirectory. - * Returns null if there is no conflict. + * Returns the name of a container with a location that encompasses + * targetDirectory. Returns null if there is no conflict. * - * @param targetDirectory the path of the directory to check. + * @param targetDirectory + * the path of the directory to check. * @return the conflicting container name or null */ protected String getConflictingContainerNameFor(String targetDirectory) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/AnnotationType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/AnnotationType.java index a9e0ebc..6fadf0c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/AnnotationType.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/AnnotationType.java @@ -1,34 +1,40 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - IBM Corporation - Initial implementation -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + **********************************************************************/ package net.sourceforge.phpeclipse.phpeditor; import org.eclipse.jface.text.Assert; public final class AnnotationType { - - public static final AnnotationType ALL= new AnnotationType(); - public static final AnnotationType UNKNOWN= new AnnotationType(); - public static final AnnotationType BOOKMARK= new AnnotationType(); - public static final AnnotationType TASK= new AnnotationType(); - public static final AnnotationType ERROR= new AnnotationType(); - public static final AnnotationType WARNING= new AnnotationType(); - public static final AnnotationType SEARCH= new AnnotationType(); - + + public static final AnnotationType ALL = new AnnotationType(); + + public static final AnnotationType UNKNOWN = new AnnotationType(); + + public static final AnnotationType BOOKMARK = new AnnotationType(); + + public static final AnnotationType TASK = new AnnotationType(); + + public static final AnnotationType ERROR = new AnnotationType(); + + public static final AnnotationType WARNING = new AnnotationType(); + + public static final AnnotationType SEARCH = new AnnotationType(); + private AnnotationType() { } public String toString() { if (this == ALL) return "AnnotationType.ALL"; //$NON-NLS-1$ - + if (this == UNKNOWN) return "AnnotationType.UNKNOWN"; //$NON-NLS-1$ @@ -37,7 +43,7 @@ public final class AnnotationType { if (this == TASK) return "AnnotationType.TASK"; //$NON-NLS-1$ - + if (this == ERROR) return "AnnotationType.ERROR"; //$NON-NLS-1$ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/BasicEditorActionContributor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/BasicEditorActionContributor.java index 95f1105..1f542a7 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/BasicEditorActionContributor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/BasicEditorActionContributor.java @@ -10,7 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpeclipse.phpeditor; - import net.sourceforge.phpdt.internal.ui.PHPUiImages; import net.sourceforge.phpdt.ui.IContextMenuConstants; import net.sourceforge.phpdt.ui.actions.PHPdtActionConstants; @@ -26,86 +25,109 @@ import org.eclipse.ui.ide.IDEActionFactory; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.RetargetTextEditorAction; +public class BasicEditorActionContributor extends + BasicJavaEditorActionContributor { -public class BasicEditorActionContributor extends BasicJavaEditorActionContributor { - protected RetargetAction fRetargetContentAssist; + protected RetargetTextEditorAction fContentAssist; -// protected RetargetTextEditorAction fContextInformation; -// protected RetargetTextEditorAction fCorrectionAssist; + + // protected RetargetTextEditorAction fContextInformation; + // protected RetargetTextEditorAction fCorrectionAssist; private EncodingActionGroup fEncodingActionGroup; - - + public BasicEditorActionContributor() { - - fRetargetContentAssist= new RetargetAction(PHPdtActionConstants.CONTENT_ASSIST, PHPEditorMessages.getString("ContentAssistProposal.label")); //$NON-NLS-1$ - fRetargetContentAssist.setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); + + fRetargetContentAssist = new RetargetAction( + PHPdtActionConstants.CONTENT_ASSIST, PHPEditorMessages + .getString("ContentAssistProposal.label")); //$NON-NLS-1$ + fRetargetContentAssist + .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); markAsPartListener(fRetargetContentAssist); - - fContentAssist= new RetargetTextEditorAction(PHPEditorMessages.getResourceBundle(), "ContentAssistProposal."); //$NON-NLS-1$ - fContentAssist.setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); + + fContentAssist = new RetargetTextEditorAction(PHPEditorMessages + .getResourceBundle(), "ContentAssistProposal."); //$NON-NLS-1$ + fContentAssist + .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); fContentAssist.setImageDescriptor(PHPUiImages.DESC_CLCL_CODE_ASSIST); - fContentAssist.setDisabledImageDescriptor(PHPUiImages.DESC_DLCL_CODE_ASSIST); - -// fContextInformation= new RetargetTextEditorAction(PHPEditorMessages.getResourceBundle(), "ContentAssistContextInformation."); //$NON-NLS-1$ -// fContextInformation.setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION); - -// fCorrectionAssist= new RetargetTextEditorAction(PHPEditorMessages.getResourceBundle(), "CorrectionAssistProposal."); //$NON-NLS-1$ -// fCorrectionAssist.setActionDefinitionId(PHPEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS); - + fContentAssist + .setDisabledImageDescriptor(PHPUiImages.DESC_DLCL_CODE_ASSIST); + + // fContextInformation= new + // RetargetTextEditorAction(PHPEditorMessages.getResourceBundle(), + // "ContentAssistContextInformation."); //$NON-NLS-1$ + // fContextInformation.setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION); + + // fCorrectionAssist= new + // RetargetTextEditorAction(PHPEditorMessages.getResourceBundle(), + // "CorrectionAssistProposal."); //$NON-NLS-1$ + // fCorrectionAssist.setActionDefinitionId(PHPEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS); + // character encoding - fEncodingActionGroup= new EncodingActionGroup(); + fEncodingActionGroup = new EncodingActionGroup(); } - + /* * @see EditorActionBarContributor#contributeToMenu(IMenuManager) */ public void contributeToMenu(IMenuManager menu) { - + super.contributeToMenu(menu); - - IMenuManager editMenu= menu.findMenuUsingPath(IWorkbenchActionConstants.M_EDIT); + + IMenuManager editMenu = menu + .findMenuUsingPath(IWorkbenchActionConstants.M_EDIT); if (editMenu != null) { - editMenu.appendToGroup(IContextMenuConstants.GROUP_GENERATE, fRetargetContentAssist); -// editMenu.appendToGroup(IContextMenuConstants.GROUP_GENERATE, fCorrectionAssist); -// editMenu.appendToGroup(IContextMenuConstants.GROUP_GENERATE, fContextInformation); - } + editMenu.appendToGroup(IContextMenuConstants.GROUP_GENERATE, + fRetargetContentAssist); + // editMenu.appendToGroup(IContextMenuConstants.GROUP_GENERATE, + // fCorrectionAssist); + // editMenu.appendToGroup(IContextMenuConstants.GROUP_GENERATE, + // fContextInformation); + } } - + /* * @see IEditorActionBarContributor#setActiveEditor(IEditorPart) - */ + */ public void setActiveEditor(IEditorPart part) { super.setActiveEditor(part); - - ITextEditor textEditor= null; + + ITextEditor textEditor = null; if (part instanceof ITextEditor) - textEditor= (ITextEditor) part; - - fContentAssist.setAction(getAction(textEditor, "ContentAssistProposal")); //$NON-NLS-1$ -// fContextInformation.setAction(getAction(textEditor, "ContentAssistContextInformation")); //$NON-NLS-1$ -// fCorrectionAssist.setAction(getAction(textEditor, "CorrectionAssistProposal")); //$NON-NLS-1$ - - IActionBars actionBars= getActionBars(); - actionBars.setGlobalActionHandler(PHPdtActionConstants.SHIFT_RIGHT, getAction(textEditor, "ShiftRight")); //$NON-NLS-1$ - actionBars.setGlobalActionHandler(PHPdtActionConstants.SHIFT_LEFT, getAction(textEditor, "ShiftLeft")); //$NON-NLS-1$ - - actionBars.setGlobalActionHandler(IDEActionFactory.ADD_TASK.getId(), getAction(textEditor, IDEActionFactory.ADD_TASK.getId())); //$NON-NLS-1$ - actionBars.setGlobalActionHandler(IDEActionFactory.BOOKMARK.getId(), getAction(textEditor, IDEActionFactory.BOOKMARK.getId())); //$NON-NLS-1$ - + textEditor = (ITextEditor) part; + + fContentAssist + .setAction(getAction(textEditor, "ContentAssistProposal")); //$NON-NLS-1$ + // fContextInformation.setAction(getAction(textEditor, + // "ContentAssistContextInformation")); //$NON-NLS-1$ + // fCorrectionAssist.setAction(getAction(textEditor, + // "CorrectionAssistProposal")); //$NON-NLS-1$ + + IActionBars actionBars = getActionBars(); + actionBars.setGlobalActionHandler(PHPdtActionConstants.SHIFT_RIGHT, + getAction(textEditor, "ShiftRight")); //$NON-NLS-1$ + actionBars.setGlobalActionHandler(PHPdtActionConstants.SHIFT_LEFT, + getAction(textEditor, "ShiftLeft")); //$NON-NLS-1$ + + actionBars.setGlobalActionHandler(IDEActionFactory.ADD_TASK.getId(), + getAction(textEditor, IDEActionFactory.ADD_TASK.getId())); //$NON-NLS-1$ + actionBars.setGlobalActionHandler(IDEActionFactory.BOOKMARK.getId(), + getAction(textEditor, IDEActionFactory.BOOKMARK.getId())); //$NON-NLS-1$ + // character encoding fEncodingActionGroup.retarget(textEditor); } - + /* * @see IEditorActionBarContributor#init(IActionBars, IWorkbenchPage) */ public void init(IActionBars bars, IWorkbenchPage page) { super.init(bars, page); - - // register actions that have a dynamic editor. - bars.setGlobalActionHandler(PHPdtActionConstants.CONTENT_ASSIST, fContentAssist); + + // register actions that have a dynamic editor. + bars.setGlobalActionHandler(PHPdtActionConstants.CONTENT_ASSIST, + fContentAssist); // character encoding fEncodingActionGroup.fillActionBars(bars); - } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/BasicJavaEditorActionContributor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/BasicJavaEditorActionContributor.java index 1ef9980..5048803 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/BasicJavaEditorActionContributor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/BasicJavaEditorActionContributor.java @@ -35,198 +35,255 @@ import org.eclipse.ui.texteditor.RetargetTextEditorAction; /** * Common base class for action contributors for Java editors. */ -public class BasicJavaEditorActionContributor extends BasicTextEditorActionContributor { - - private List fPartListeners= new ArrayList(); - +public class BasicJavaEditorActionContributor extends + BasicTextEditorActionContributor { + + private List fPartListeners = new ArrayList(); + private TogglePresentationAction fTogglePresentation; -// private GotoAnnotationAction fPreviousAnnotation; -// private GotoAnnotationAction fNextAnnotation; - + + // private GotoAnnotationAction fPreviousAnnotation; + // private GotoAnnotationAction fNextAnnotation; + private RetargetTextEditorAction fGotoMatchingBracket; -// private RetargetTextEditorAction fShowOutline; -// private RetargetTextEditorAction fOpenStructure; -// private RetargetTextEditorAction fOpenHierarchy; - -// private RetargetAction fRetargetShowJavaDoc; -// private RetargetTextEditorAction fShowJavaDoc; - -// private RetargetTextEditorAction fStructureSelectEnclosingAction; -// private RetargetTextEditorAction fStructureSelectNextAction; -// private RetargetTextEditorAction fStructureSelectPreviousAction; -// private RetargetTextEditorAction fStructureSelectHistoryAction; - - private RetargetTextEditorAction fGotoNextMemberAction; + + // private RetargetTextEditorAction fShowOutline; + // private RetargetTextEditorAction fOpenStructure; + // private RetargetTextEditorAction fOpenHierarchy; + + // private RetargetAction fRetargetShowJavaDoc; + // private RetargetTextEditorAction fShowJavaDoc; + + // private RetargetTextEditorAction fStructureSelectEnclosingAction; + // private RetargetTextEditorAction fStructureSelectNextAction; + // private RetargetTextEditorAction fStructureSelectPreviousAction; + // private RetargetTextEditorAction fStructureSelectHistoryAction; + + private RetargetTextEditorAction fGotoNextMemberAction; + private RetargetTextEditorAction fGotoPreviousMemberAction; -// -// private RetargetTextEditorAction fRemoveOccurrenceAnnotationsAction; - + + // + // private RetargetTextEditorAction fRemoveOccurrenceAnnotationsAction; + public BasicJavaEditorActionContributor() { super(); - - ResourceBundle b= PHPEditorMessages.getResourceBundle(); - -// fRetargetShowJavaDoc= new RetargetAction(PHPdtActionConstants.SHOW_JAVA_DOC, PHPEditorMessages.getString("ShowJavaDoc.label")); //$NON-NLS-1$ -// fRetargetShowJavaDoc.setActionDefinitionId(net.sourceforge.phpdt.ui.actions.PHPEditorActionDefinitionIds.SHOW_JAVADOC); -// markAsPartListener(fRetargetShowJavaDoc); - - // actions that are "contributed" to editors, they are considered belonging to the active editor - fTogglePresentation= new TogglePresentationAction(); - -// fPreviousAnnotation= new GotoAnnotationAction("PreviousAnnotation.", false); //$NON-NLS-1$ -// -// fNextAnnotation= new GotoAnnotationAction("NextAnnotation.", true); //$NON-NLS-1$ - - fGotoMatchingBracket= new RetargetTextEditorAction(b, "GotoMatchingBracket."); //$NON-NLS-1$ - fGotoMatchingBracket.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_MATCHING_BRACKET); - -// fShowJavaDoc= new RetargetTextEditorAction(b, "ShowJavaDoc."); //$NON-NLS-1$ -// fShowJavaDoc.setActionDefinitionId(net.sourceforge.phpdt.ui.actions.PHPEditorActionDefinitionIds.SHOW_JAVADOC); - -// fShowOutline= new RetargetTextEditorAction(PHPEditorMessages.getResourceBundle(), "ShowOutline."); //$NON-NLS-1$ -// fShowOutline.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE); -// -// fOpenHierarchy= new RetargetTextEditorAction(PHPEditorMessages.getResourceBundle(), "OpenHierarchy."); //$NON-NLS-1$ -// fOpenHierarchy.setActionDefinitionId(PHPEditorActionDefinitionIds.OPEN_HIERARCHY); -// -// fOpenStructure= new RetargetTextEditorAction(PHPEditorMessages.getResourceBundle(), "OpenStructure."); //$NON-NLS-1$ -// fOpenStructure.setActionDefinitionId(PHPEditorActionDefinitionIds.OPEN_STRUCTURE); - -// fStructureSelectEnclosingAction= new RetargetTextEditorAction(b, "StructureSelectEnclosing."); //$NON-NLS-1$ -// fStructureSelectEnclosingAction.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_ENCLOSING); -// fStructureSelectNextAction= new RetargetTextEditorAction(b, "StructureSelectNext."); //$NON-NLS-1$ -// fStructureSelectNextAction.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_NEXT); -// fStructureSelectPreviousAction= new RetargetTextEditorAction(b, "StructureSelectPrevious."); //$NON-NLS-1$ -// fStructureSelectPreviousAction.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_PREVIOUS); -// fStructureSelectHistoryAction= new RetargetTextEditorAction(b, "StructureSelectHistory."); //$NON-NLS-1$ -// fStructureSelectHistoryAction.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_LAST); -// - fGotoNextMemberAction= new RetargetTextEditorAction(b, "GotoNextMember."); //$NON-NLS-1$ - fGotoNextMemberAction.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_NEXT_MEMBER); - fGotoPreviousMemberAction= new RetargetTextEditorAction(b, "GotoPreviousMember."); //$NON-NLS-1$ - fGotoPreviousMemberAction.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER); -// -// fRemoveOccurrenceAnnotationsAction= new RetargetTextEditorAction(b, "RemoveOccurrenceAnnotations."); //$NON-NLS-1$ -// fRemoveOccurrenceAnnotationsAction.setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_OCCURRENCE_ANNOTATIONS); + + ResourceBundle b = PHPEditorMessages.getResourceBundle(); + + // fRetargetShowJavaDoc= new + // RetargetAction(PHPdtActionConstants.SHOW_JAVA_DOC, + // PHPEditorMessages.getString("ShowJavaDoc.label")); //$NON-NLS-1$ + // fRetargetShowJavaDoc.setActionDefinitionId(net.sourceforge.phpdt.ui.actions.PHPEditorActionDefinitionIds.SHOW_JAVADOC); + // markAsPartListener(fRetargetShowJavaDoc); + + // actions that are "contributed" to editors, they are considered + // belonging to the active editor + fTogglePresentation = new TogglePresentationAction(); + + // fPreviousAnnotation= new GotoAnnotationAction("PreviousAnnotation.", + // false); //$NON-NLS-1$ + // + // fNextAnnotation= new GotoAnnotationAction("NextAnnotation.", true); + // //$NON-NLS-1$ + + fGotoMatchingBracket = new RetargetTextEditorAction(b, + "GotoMatchingBracket."); //$NON-NLS-1$ + fGotoMatchingBracket + .setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_MATCHING_BRACKET); + + // fShowJavaDoc= new RetargetTextEditorAction(b, "ShowJavaDoc."); + // //$NON-NLS-1$ + // fShowJavaDoc.setActionDefinitionId(net.sourceforge.phpdt.ui.actions.PHPEditorActionDefinitionIds.SHOW_JAVADOC); + + // fShowOutline= new + // RetargetTextEditorAction(PHPEditorMessages.getResourceBundle(), + // "ShowOutline."); //$NON-NLS-1$ + // fShowOutline.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE); + // + // fOpenHierarchy= new + // RetargetTextEditorAction(PHPEditorMessages.getResourceBundle(), + // "OpenHierarchy."); //$NON-NLS-1$ + // fOpenHierarchy.setActionDefinitionId(PHPEditorActionDefinitionIds.OPEN_HIERARCHY); + // + // fOpenStructure= new + // RetargetTextEditorAction(PHPEditorMessages.getResourceBundle(), + // "OpenStructure."); //$NON-NLS-1$ + // fOpenStructure.setActionDefinitionId(PHPEditorActionDefinitionIds.OPEN_STRUCTURE); + + // fStructureSelectEnclosingAction= new RetargetTextEditorAction(b, + // "StructureSelectEnclosing."); //$NON-NLS-1$ + // fStructureSelectEnclosingAction.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_ENCLOSING); + // fStructureSelectNextAction= new RetargetTextEditorAction(b, + // "StructureSelectNext."); //$NON-NLS-1$ + // fStructureSelectNextAction.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_NEXT); + // fStructureSelectPreviousAction= new RetargetTextEditorAction(b, + // "StructureSelectPrevious."); //$NON-NLS-1$ + // fStructureSelectPreviousAction.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_PREVIOUS); + // fStructureSelectHistoryAction= new RetargetTextEditorAction(b, + // "StructureSelectHistory."); //$NON-NLS-1$ + // fStructureSelectHistoryAction.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_LAST); + // + fGotoNextMemberAction = new RetargetTextEditorAction(b, + "GotoNextMember."); //$NON-NLS-1$ + fGotoNextMemberAction + .setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_NEXT_MEMBER); + fGotoPreviousMemberAction = new RetargetTextEditorAction(b, + "GotoPreviousMember."); //$NON-NLS-1$ + fGotoPreviousMemberAction + .setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER); + // + // fRemoveOccurrenceAnnotationsAction= new RetargetTextEditorAction(b, + // "RemoveOccurrenceAnnotations."); //$NON-NLS-1$ + // fRemoveOccurrenceAnnotationsAction.setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_OCCURRENCE_ANNOTATIONS); } - + protected final void markAsPartListener(RetargetAction action) { fPartListeners.add(action); } - + /* * @see IEditorActionBarContributor#init(IActionBars, IWorkbenchPage) */ - public void init(IActionBars bars, IWorkbenchPage page) { - Iterator e= fPartListeners.iterator(); - while (e.hasNext()) + public void init(IActionBars bars, IWorkbenchPage page) { + Iterator e = fPartListeners.iterator(); + while (e.hasNext()) page.addPartListener((RetargetAction) e.next()); - + super.init(bars, page); - - // register actions that have a dynamic editor. -// bars.setGlobalActionHandler(ITextEditorActionDefinitionIds.GOTO_NEXT_ANNOTATION, fNextAnnotation); -// bars.setGlobalActionHandler(ITextEditorActionDefinitionIds.GOTO_PREVIOUS_ANNOTATION, fPreviousAnnotation); -// bars.setGlobalActionHandler(ITextEditorActionConstants.NEXT, fNextAnnotation); -// bars.setGlobalActionHandler(ITextEditorActionConstants.PREVIOUS, fPreviousAnnotation); - bars.setGlobalActionHandler(ITextEditorActionDefinitionIds.TOGGLE_SHOW_SELECTED_ELEMENT_ONLY, fTogglePresentation); - -// bars.setGlobalActionHandler(PHPdtActionConstants.SHOW_JAVA_DOC, fShowJavaDoc); + + // register actions that have a dynamic editor. + // bars.setGlobalActionHandler(ITextEditorActionDefinitionIds.GOTO_NEXT_ANNOTATION, + // fNextAnnotation); + // bars.setGlobalActionHandler(ITextEditorActionDefinitionIds.GOTO_PREVIOUS_ANNOTATION, + // fPreviousAnnotation); + // bars.setGlobalActionHandler(ITextEditorActionConstants.NEXT, + // fNextAnnotation); + // bars.setGlobalActionHandler(ITextEditorActionConstants.PREVIOUS, + // fPreviousAnnotation); + bars + .setGlobalActionHandler( + ITextEditorActionDefinitionIds.TOGGLE_SHOW_SELECTED_ELEMENT_ONLY, + fTogglePresentation); + + // bars.setGlobalActionHandler(PHPdtActionConstants.SHOW_JAVA_DOC, + // fShowJavaDoc); } - + /* * @see org.eclipse.ui.part.EditorActionBarContributor#contributeToMenu(org.eclipse.jface.action.IMenuManager) */ public void contributeToMenu(IMenuManager menu) { - + super.contributeToMenu(menu); - - IMenuManager editMenu= menu.findMenuUsingPath(IWorkbenchActionConstants.M_EDIT); + + IMenuManager editMenu = menu + .findMenuUsingPath(IWorkbenchActionConstants.M_EDIT); if (editMenu != null) { - editMenu.add(new Separator(IContextMenuConstants.GROUP_OPEN)); + editMenu.add(new Separator(IContextMenuConstants.GROUP_OPEN)); editMenu.add(new Separator(IContextMenuConstants.GROUP_GENERATE)); editMenu.add(new Separator(IContextMenuConstants.GROUP_ADDITIONS)); - -// MenuManager structureSelection= new MenuManager(PHPEditorMessages.getString("ExpandSelectionMenu.label"), "expandSelection"); //$NON-NLS-1$ //$NON-NLS-2$ -// structureSelection.add(fStructureSelectEnclosingAction); -// structureSelection.add(fStructureSelectNextAction); -// structureSelection.add(fStructureSelectPreviousAction); -// structureSelection.add(fStructureSelectHistoryAction); -// editMenu.appendToGroup(IContextMenuConstants.GROUP_OPEN, structureSelection); - -// editMenu.appendToGroup(IContextMenuConstants.GROUP_GENERATE, fRetargetShowJavaDoc); + + // MenuManager structureSelection= new + // MenuManager(PHPEditorMessages.getString("ExpandSelectionMenu.label"), + // "expandSelection"); //$NON-NLS-1$ //$NON-NLS-2$ + // structureSelection.add(fStructureSelectEnclosingAction); + // structureSelection.add(fStructureSelectNextAction); + // structureSelection.add(fStructureSelectPreviousAction); + // structureSelection.add(fStructureSelectHistoryAction); + // editMenu.appendToGroup(IContextMenuConstants.GROUP_OPEN, + // structureSelection); + + // editMenu.appendToGroup(IContextMenuConstants.GROUP_GENERATE, + // fRetargetShowJavaDoc); } -// IMenuManager navigateMenu= menu.findMenuUsingPath(IWorkbenchActionConstants.M_NAVIGATE); -// if (navigateMenu != null) { -// navigateMenu.appendToGroup(IWorkbenchActionConstants.SHOW_EXT, fShowOutline); -// navigateMenu.appendToGroup(IWorkbenchActionConstants.SHOW_EXT, fOpenHierarchy); -// } - - IMenuManager gotoMenu= menu.findMenuUsingPath("navigate/goTo"); //$NON-NLS-1$ + // IMenuManager navigateMenu= + // menu.findMenuUsingPath(IWorkbenchActionConstants.M_NAVIGATE); + // if (navigateMenu != null) { + // navigateMenu.appendToGroup(IWorkbenchActionConstants.SHOW_EXT, + // fShowOutline); + // navigateMenu.appendToGroup(IWorkbenchActionConstants.SHOW_EXT, + // fOpenHierarchy); + // } + + IMenuManager gotoMenu = menu.findMenuUsingPath("navigate/goTo"); //$NON-NLS-1$ if (gotoMenu != null) { - gotoMenu.add(new Separator("additions2")); //$NON-NLS-1$ + gotoMenu.add(new Separator("additions2")); //$NON-NLS-1$ gotoMenu.appendToGroup("additions2", fGotoPreviousMemberAction); //$NON-NLS-1$ gotoMenu.appendToGroup("additions2", fGotoNextMemberAction); //$NON-NLS-1$ gotoMenu.appendToGroup("additions2", fGotoMatchingBracket); //$NON-NLS-1$ } } - + /* * @see EditorActionBarContributor#setActiveEditor(IEditorPart) */ public void setActiveEditor(IEditorPart part) { - + super.setActiveEditor(part); - - IActionBars actionBars= getActionBars(); - IStatusLineManager manager= actionBars.getStatusLineManager(); + + IActionBars actionBars = getActionBars(); + IStatusLineManager manager = actionBars.getStatusLineManager(); manager.setMessage(null); manager.setErrorMessage(null); - - ITextEditor textEditor= null; + + ITextEditor textEditor = null; if (part instanceof ITextEditor) - textEditor= (ITextEditor) part; - + textEditor = (ITextEditor) part; + fTogglePresentation.setEditor(textEditor); -// fPreviousAnnotation.setEditor(textEditor); -// fNextAnnotation.setEditor(textEditor); - - fGotoMatchingBracket.setAction(getAction(textEditor, GotoMatchingBracketAction.GOTO_MATCHING_BRACKET)); -// fShowJavaDoc.setAction(getAction(textEditor, "ShowJavaDoc")); //$NON-NLS-1$ -// fShowOutline.setAction(getAction(textEditor, IJavaEditorActionDefinitionIds.SHOW_OUTLINE)); -// fOpenHierarchy.setAction(getAction(textEditor, IJavaEditorActionDefinitionIds.OPEN_HIERARCHY)); -// fOpenStructure.setAction(getAction(textEditor, IJavaEditorActionDefinitionIds.OPEN_STRUCTURE)); - -// fStructureSelectEnclosingAction.setAction(getAction(textEditor, StructureSelectionAction.ENCLOSING)); -// fStructureSelectNextAction.setAction(getAction(textEditor, StructureSelectionAction.NEXT)); -// fStructureSelectPreviousAction.setAction(getAction(textEditor, StructureSelectionAction.PREVIOUS)); -// fStructureSelectHistoryAction.setAction(getAction(textEditor, StructureSelectionAction.HISTORY)); - -// fGotoNextMemberAction.setAction(getAction(textEditor, GoToNextPreviousMemberAction.NEXT_MEMBER)); -// fGotoPreviousMemberAction.setAction(getAction(textEditor, GoToNextPreviousMemberAction.PREVIOUS_MEMBER)); - -// fRemoveOccurrenceAnnotationsAction.setAction(getAction(textEditor, "RemoveOccurrenceAnnotations")); //$NON-NLS-1$ + // fPreviousAnnotation.setEditor(textEditor); + // fNextAnnotation.setEditor(textEditor); + + fGotoMatchingBracket.setAction(getAction(textEditor, + GotoMatchingBracketAction.GOTO_MATCHING_BRACKET)); + // fShowJavaDoc.setAction(getAction(textEditor, "ShowJavaDoc")); + // //$NON-NLS-1$ + // fShowOutline.setAction(getAction(textEditor, + // IJavaEditorActionDefinitionIds.SHOW_OUTLINE)); + // fOpenHierarchy.setAction(getAction(textEditor, + // IJavaEditorActionDefinitionIds.OPEN_HIERARCHY)); + // fOpenStructure.setAction(getAction(textEditor, + // IJavaEditorActionDefinitionIds.OPEN_STRUCTURE)); + + // fStructureSelectEnclosingAction.setAction(getAction(textEditor, + // StructureSelectionAction.ENCLOSING)); + // fStructureSelectNextAction.setAction(getAction(textEditor, + // StructureSelectionAction.NEXT)); + // fStructureSelectPreviousAction.setAction(getAction(textEditor, + // StructureSelectionAction.PREVIOUS)); + // fStructureSelectHistoryAction.setAction(getAction(textEditor, + // StructureSelectionAction.HISTORY)); + + // fGotoNextMemberAction.setAction(getAction(textEditor, + // GoToNextPreviousMemberAction.NEXT_MEMBER)); + // fGotoPreviousMemberAction.setAction(getAction(textEditor, + // GoToNextPreviousMemberAction.PREVIOUS_MEMBER)); + + // fRemoveOccurrenceAnnotationsAction.setAction(getAction(textEditor, + // "RemoveOccurrenceAnnotations")); //$NON-NLS-1$ if (part instanceof PHPEditor) { - PHPEditor javaEditor= (PHPEditor) part; + PHPEditor javaEditor = (PHPEditor) part; javaEditor.getActionGroup().fillActionBars(getActionBars()); - FoldingActionGroup foldingActions= javaEditor.getFoldingActionGroup(); + FoldingActionGroup foldingActions = javaEditor + .getFoldingActionGroup(); if (foldingActions != null) foldingActions.updateActionBars(); } } - + /* * @see IEditorActionBarContributor#dispose() */ public void dispose() { - - Iterator e= fPartListeners.iterator(); - while (e.hasNext()) + + Iterator e = fPartListeners.iterator(); + while (e.hasNext()) getPage().removePartListener((RetargetAction) e.next()); fPartListeners.clear(); - + setActiveEditor(null); super.dispose(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/BracketPainter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/BracketPainter.java index e105679..e73790b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/BracketPainter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/BracketPainter.java @@ -19,43 +19,47 @@ import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; - public final class BracketPainter implements IPainter, PaintListener { - private PHPPairMatcher fMatcher= new PHPPairMatcher(new char[] { '{', '}', '(', ')', '[', ']' }); - private Position fBracketPosition= new Position(0, 0); + private PHPPairMatcher fMatcher = new PHPPairMatcher(new char[] { '{', '}', + '(', ')', '[', ']' }); + + private Position fBracketPosition = new Position(0, 0); + private int fAnchor; - private boolean fIsActive= false; + private boolean fIsActive = false; + private ISourceViewer fSourceViewer; + private StyledText fTextWidget; + private Color fColor; private IPositionManager fPositionManager; - public BracketPainter(ISourceViewer sourceViewer) { - fSourceViewer= sourceViewer; - fTextWidget= sourceViewer.getTextWidget(); + fSourceViewer = sourceViewer; + fTextWidget = sourceViewer.getTextWidget(); } public void setHighlightColor(Color color) { - fColor= color; + fColor = color; } public void dispose() { if (fMatcher != null) { fMatcher.dispose(); - fMatcher= null; + fMatcher = null; } - fColor= null; - fTextWidget= null; + fColor = null; + fTextWidget = null; } public void deactivate(boolean redraw) { if (fIsActive) { - fIsActive= false; + fIsActive = false; fTextWidget.removePaintListener(this); if (fPositionManager != null) fPositionManager.removeManagedPosition(fBracketPosition); @@ -74,23 +78,26 @@ public final class BracketPainter implements IPainter, PaintListener { if (fBracketPosition.isDeleted) return; - int offset= fBracketPosition.getOffset(); - int length= fBracketPosition.getLength(); + int offset = fBracketPosition.getOffset(); + int length = fBracketPosition.getLength(); if (length < 1) return; if (fSourceViewer instanceof ITextViewerExtension5) { - ITextViewerExtension5 extension= (ITextViewerExtension5) fSourceViewer; - IRegion widgetRange= extension.modelRange2WidgetRange(new Region(offset, length)); + ITextViewerExtension5 extension = (ITextViewerExtension5) fSourceViewer; + IRegion widgetRange = extension.modelRange2WidgetRange(new Region( + offset, length)); if (widgetRange == null) return; - offset= widgetRange.getOffset(); - length= widgetRange.getLength(); + offset = widgetRange.getOffset(); + length = widgetRange.getLength(); } else { - IRegion region= fSourceViewer.getVisibleRegion(); - if (region.getOffset() > offset || region.getOffset() + region.getLength() < offset + length) + IRegion region = fSourceViewer.getVisibleRegion(); + if (region.getOffset() > offset + || region.getOffset() + region.getLength() < offset + + length) return; offset -= region.getOffset(); } @@ -98,16 +105,17 @@ public final class BracketPainter implements IPainter, PaintListener { if (PHPPairMatcher.RIGHT == fAnchor) draw(gc, offset, 1); else - draw(gc, offset + length -1, 1); + draw(gc, offset + length - 1, 1); } private void draw(GC gc, int offset, int length) { if (gc != null) { - Point left= fTextWidget.getLocationAtOffset(offset); - Point right= fTextWidget.getLocationAtOffset(offset + length); + Point left = fTextWidget.getLocationAtOffset(offset); + Point right = fTextWidget.getLocationAtOffset(offset + length); gc.setForeground(fColor); - gc.drawRectangle(left.x, left.y, right.x - left.x - 1, gc.getFontMetrics().getHeight() - 1); + gc.drawRectangle(left.x, left.y, right.x - left.x - 1, gc + .getFontMetrics().getHeight() - 1); } else { fTextWidget.redrawRange(offset, length, true); @@ -118,13 +126,13 @@ public final class BracketPainter implements IPainter, PaintListener { * @see IPainter#paint(int) */ public void paint(int reason) { - Point selection= fSourceViewer.getSelectedRange(); + Point selection = fSourceViewer.getSelectedRange(); if (selection.y > 0) { deactivate(true); return; } - IRegion pair= fMatcher.match(fSourceViewer.getDocument(), selection.x); + IRegion pair = fMatcher.match(fSourceViewer.getDocument(), selection.x); if (pair == null) { deactivate(true); return; @@ -132,29 +140,29 @@ public final class BracketPainter implements IPainter, PaintListener { if (fIsActive) { // only if different - if (pair.getOffset() != fBracketPosition.getOffset() || - pair.getLength() != fBracketPosition.getLength() || - fMatcher.getAnchor() != fAnchor) { + if (pair.getOffset() != fBracketPosition.getOffset() + || pair.getLength() != fBracketPosition.getLength() + || fMatcher.getAnchor() != fAnchor) { // remove old highlighting handleDrawRequest(null); // update position - fBracketPosition.isDeleted= false; - fBracketPosition.offset= pair.getOffset(); - fBracketPosition.length= pair.getLength(); - fAnchor= fMatcher.getAnchor(); + fBracketPosition.isDeleted = false; + fBracketPosition.offset = pair.getOffset(); + fBracketPosition.length = pair.getLength(); + fAnchor = fMatcher.getAnchor(); // apply new highlighting handleDrawRequest(null); } } else { - fIsActive= true; + fIsActive = true; - fBracketPosition.isDeleted= false; - fBracketPosition.offset= pair.getOffset(); - fBracketPosition.length= pair.getLength(); - fAnchor= fMatcher.getAnchor(); + fBracketPosition.isDeleted = false; + fBracketPosition.offset = pair.getOffset(); + fBracketPosition.length = pair.getLength(); + fAnchor = fMatcher.getAnchor(); fTextWidget.addPaintListener(this); fPositionManager.addManagedPosition(fBracketPosition); @@ -166,6 +174,6 @@ public final class BracketPainter implements IPainter, PaintListener { * @see IPainter#setPositionManager(IPositionManager) */ public void setPositionManager(IPositionManager manager) { - fPositionManager= manager; + fPositionManager = manager; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/BreakpointImageProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/BreakpointImageProvider.java index 16578e7..b57d14d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/BreakpointImageProvider.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/BreakpointImageProvider.java @@ -21,10 +21,11 @@ import org.eclipse.ui.texteditor.MarkerAnnotation; /** * BreakpointImageProvider + * * @since 3.0 */ public class BreakpointImageProvider implements IAnnotationImageProvider { - + private IDebugModelPresentation fPresentation; /* @@ -32,12 +33,12 @@ public class BreakpointImageProvider implements IAnnotationImageProvider { */ public Image getManagedImage(Annotation annotation) { if (annotation instanceof MarkerAnnotation) { - MarkerAnnotation markerAnnotation= (MarkerAnnotation) annotation; - IMarker marker= markerAnnotation.getMarker(); + MarkerAnnotation markerAnnotation = (MarkerAnnotation) annotation; + IMarker marker = markerAnnotation.getMarker(); if (marker != null && marker.exists()) return getPresentation().getImage(marker); } - + return null; } @@ -54,10 +55,10 @@ public class BreakpointImageProvider implements IAnnotationImageProvider { public ImageDescriptor getImageDescriptor(String imageDescritporId) { return null; } - + private IDebugModelPresentation getPresentation() { - if (fPresentation == null) - fPresentation= DebugUITools.newDebugModelPresentation(); + if (fPresentation == null) + fPresentation = DebugUITools.newDebugModelPresentation(); return fPresentation; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/CompilationUnitAnnotationModelEvent.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/CompilationUnitAnnotationModelEvent.java index 56204d3..fa55f33 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/CompilationUnitAnnotationModelEvent.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/CompilationUnitAnnotationModelEvent.java @@ -10,8 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpeclipse.phpeditor; - - import net.sourceforge.phpeclipse.PHPeclipsePlugin; import org.eclipse.core.resources.IMarker; @@ -23,44 +21,48 @@ import org.eclipse.jface.text.source.AnnotationModelEvent; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.ui.texteditor.MarkerAnnotation; - /** * Event sent out by changes of the compilation unit annotation model. */ -public class CompilationUnitAnnotationModelEvent extends AnnotationModelEvent { - +public class CompilationUnitAnnotationModelEvent extends AnnotationModelEvent { + private boolean fIncludesProblemMarkerAnnotations; + private IResource fUnderlyingResource; - + /** * Constructor for CompilationUnitAnnotationModelEvent. + * * @param model - * @param underlyingResource The annotation model's underlying resource + * @param underlyingResource + * The annotation model's underlying resource */ - public CompilationUnitAnnotationModelEvent(IAnnotationModel model, IResource underlyingResource) { + public CompilationUnitAnnotationModelEvent(IAnnotationModel model, + IResource underlyingResource) { super(model); - fUnderlyingResource= underlyingResource; - fIncludesProblemMarkerAnnotations= false; + fUnderlyingResource = underlyingResource; + fIncludesProblemMarkerAnnotations = false; } - + private void testIfProblemMarker(Annotation annotation) { if (fIncludesProblemMarkerAnnotations) { return; } if (annotation instanceof JavaMarkerAnnotation) { - fIncludesProblemMarkerAnnotations= ((JavaMarkerAnnotation) annotation).isProblem(); + fIncludesProblemMarkerAnnotations = ((JavaMarkerAnnotation) annotation) + .isProblem(); } else if (annotation instanceof MarkerAnnotation) { try { - IMarker marker= ((MarkerAnnotation) annotation).getMarker(); + IMarker marker = ((MarkerAnnotation) annotation).getMarker(); if (!marker.exists() || marker.isSubtypeOf(IMarker.PROBLEM)) { - fIncludesProblemMarkerAnnotations= true; + fIncludesProblemMarkerAnnotations = true; } } catch (CoreException e) { PHPeclipsePlugin.log(e); } - } + } } - + /* * @see org.eclipse.jface.text.source.AnnotationModelEvent#annotationAdded(org.eclipse.jface.text.source.Annotation) */ @@ -69,7 +71,6 @@ public class CompilationUnitAnnotationModelEvent extends AnnotationModelEvent { testIfProblemMarker(annotation); } - /* * @see org.eclipse.jface.text.source.AnnotationModelEvent#annotationRemoved(org.eclipse.jface.text.source.Annotation) */ @@ -79,13 +80,14 @@ public class CompilationUnitAnnotationModelEvent extends AnnotationModelEvent { } /* - * @see org.eclipse.jface.text.source.AnnotationModelEvent#annotationRemoved(org.eclipse.jface.text.source.Annotation, org.eclipse.jface.text.Position) + * @see org.eclipse.jface.text.source.AnnotationModelEvent#annotationRemoved(org.eclipse.jface.text.source.Annotation, + * org.eclipse.jface.text.Position) */ public void annotationRemoved(Annotation annotation, Position position) { super.annotationRemoved(annotation, position); testIfProblemMarker(annotation); } - + /* * @see org.eclipse.jface.text.source.AnnotationModelEvent#annotationChanged(org.eclipse.jface.text.source.Annotation) */ @@ -93,7 +95,7 @@ public class CompilationUnitAnnotationModelEvent extends AnnotationModelEvent { testIfProblemMarker(annotation); super.annotationChanged(annotation); } - + /** * Returns whether the change included problem marker annotations. * @@ -102,7 +104,7 @@ public class CompilationUnitAnnotationModelEvent extends AnnotationModelEvent { public boolean includesProblemMarkerAnnotationChanges() { return fIncludesProblemMarkerAnnotations; } - + /** * Returns the annotation model's underlying resource */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/CompilationUnitEditorActionContributor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/CompilationUnitEditorActionContributor.java index 524e966..57ed72d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/CompilationUnitEditorActionContributor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/CompilationUnitEditorActionContributor.java @@ -18,48 +18,57 @@ import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.texteditor.ITextEditor; -public class CompilationUnitEditorActionContributor extends BasicEditorActionContributor { - public CompilationUnitEditorActionContributor() { - super(); - } +public class CompilationUnitEditorActionContributor extends + BasicEditorActionContributor { + public CompilationUnitEditorActionContributor() { + super(); + } - /* - * @see IEditorActionBarContributor#setActiveEditor(IEditorPart) - */ - public void setActiveEditor(IEditorPart part) { - super.setActiveEditor(part); + /* + * @see IEditorActionBarContributor#setActiveEditor(IEditorPart) + */ + public void setActiveEditor(IEditorPart part) { + super.setActiveEditor(part); - ITextEditor textEditor = null; - if (part instanceof ITextEditor) - textEditor = (ITextEditor) part; + ITextEditor textEditor = null; + if (part instanceof ITextEditor) + textEditor = (ITextEditor) part; - // Source menu. - IActionBars bars = getActionBars(); - bars.setGlobalActionHandler(PHPdtActionConstants.COMMENT, getAction(textEditor, "Comment")); //$NON-NLS-1$ - bars.setGlobalActionHandler(PHPdtActionConstants.UNCOMMENT, getAction(textEditor, "Uncomment")); //$NON-NLS-1$ - bars.setGlobalActionHandler(PHPdtActionConstants.TOGGLE_COMMENT, getAction(textEditor, "ToggleComment")); //$NON-NLS-1$ - bars.setGlobalActionHandler(PHPdtActionConstants.FORMAT, getAction(textEditor, "Format")); //$NON-NLS-1$ - bars.setGlobalActionHandler(PHPdtActionConstants.ADD_BLOCK_COMMENT, getAction(textEditor, "AddBlockComment")); //$NON-NLS-1$ - bars.setGlobalActionHandler(PHPdtActionConstants.REMOVE_BLOCK_COMMENT, getAction(textEditor, "RemoveBlockComment")); //$NON-NLS-1$ - // bars.setGlobalActionHandler(PHPdtActionConstants.INDENT, getAction( - // textEditor, "Indent")); //$NON-NLS-1$ //$NON-NLS-2$ + // Source menu. + IActionBars bars = getActionBars(); + bars.setGlobalActionHandler(PHPdtActionConstants.COMMENT, getAction( + textEditor, "Comment")); //$NON-NLS-1$ + bars.setGlobalActionHandler(PHPdtActionConstants.UNCOMMENT, getAction( + textEditor, "Uncomment")); //$NON-NLS-1$ + bars.setGlobalActionHandler(PHPdtActionConstants.TOGGLE_COMMENT, + getAction(textEditor, "ToggleComment")); //$NON-NLS-1$ + bars.setGlobalActionHandler(PHPdtActionConstants.FORMAT, getAction( + textEditor, "Format")); //$NON-NLS-1$ + bars.setGlobalActionHandler(PHPdtActionConstants.ADD_BLOCK_COMMENT, + getAction(textEditor, "AddBlockComment")); //$NON-NLS-1$ + bars.setGlobalActionHandler(PHPdtActionConstants.REMOVE_BLOCK_COMMENT, + getAction(textEditor, "RemoveBlockComment")); //$NON-NLS-1$ + // bars.setGlobalActionHandler(PHPdtActionConstants.INDENT, getAction( + // textEditor, "Indent")); //$NON-NLS-1$ //$NON-NLS-2$ - if (textEditor != null) { - IFile file = null; - IEditorInput editorInput = textEditor.getEditorInput(); + if (textEditor != null) { + IFile file = null; + IEditorInput editorInput = textEditor.getEditorInput(); - if (editorInput instanceof IFileEditorInput) { - file = ((IFileEditorInput) editorInput).getFile(); - } + if (editorInput instanceof IFileEditorInput) { + file = ((IFileEditorInput) editorInput).getFile(); + } - PHPeclipsePlugin.getDefault().setLastEditorFile(file); - - ShowExternalPreviewAction fShowExternalPreviewAction = ShowExternalPreviewAction.getInstance(); - fShowExternalPreviewAction.setEditor(textEditor); - fShowExternalPreviewAction.update(); - if (fShowExternalPreviewAction != null) { - fShowExternalPreviewAction.doRun(ShowExternalPreviewAction.PHP_TYPE); - } - } - } + PHPeclipsePlugin.getDefault().setLastEditorFile(file); + + ShowExternalPreviewAction fShowExternalPreviewAction = ShowExternalPreviewAction + .getInstance(); + fShowExternalPreviewAction.setEditor(textEditor); + fShowExternalPreviewAction.update(); + if (fShowExternalPreviewAction != null) { + fShowExternalPreviewAction + .doRun(ShowExternalPreviewAction.PHP_TYPE); + } + } + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/CustomBufferFactory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/CustomBufferFactory.java index d32638a..7bd764c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/CustomBufferFactory.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/CustomBufferFactory.java @@ -1,13 +1,13 @@ /********************************************************************** -Copyright (c) 2000, 2003 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html + Copyright (c) 2000, 2003 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html -Contributors: - IBM Corporation - Initial implementation -**********************************************************************/ + Contributors: + IBM Corporation - Initial implementation + **********************************************************************/ package net.sourceforge.phpeclipse.phpeditor; @@ -19,25 +19,25 @@ import net.sourceforge.phpdt.core.IOpenable; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; - /** * Creates IBuffers based on documents. + * * @deprecated since 3.0 no longer used */ public class CustomBufferFactory implements IBufferFactory { - + /* * @see net.sourceforge.phpdt.core.IBufferFactory#createBuffer(net.sourceforge.phpdt.core.IOpenable) */ public IBuffer createBuffer(IOpenable owner) { if (owner instanceof ICompilationUnit) { - ICompilationUnit unit= (ICompilationUnit) owner; - ICompilationUnit original= unit.getPrimary(); - IResource resource= original.getResource(); + ICompilationUnit unit = (ICompilationUnit) owner; + ICompilationUnit original = unit.getPrimary(); + IResource resource = original.getResource(); if (resource instanceof IFile) { return new DocumentAdapter(unit, (IFile) resource); } - + } return DocumentAdapter.NULL; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/DocumentAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/DocumentAdapter.java index 006503e..6c0bdff 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/DocumentAdapter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/DocumentAdapter.java @@ -11,7 +11,6 @@ package net.sourceforge.phpeclipse.phpeditor; - import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; @@ -43,126 +42,178 @@ import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentListener; import org.eclipse.swt.widgets.Display; - - /** - * Adapts IDocument to IBuffer. Uses the - * same algorithm as the text widget to determine the buffer's line delimiter. - * All text inserted into the buffer is converted to this line delimiter. - * This class is public for test purposes only. + * Adapts IDocument to IBuffer. Uses the same + * algorithm as the text widget to determine the buffer's line delimiter. All + * text inserted into the buffer is converted to this line delimiter. This class + * is public for test purposes only. */ public class DocumentAdapter implements IBuffer, IDocumentListener { - /** - * Internal implementation of a NULL instanceof IBuffer. - */ - static private class NullBuffer implements IBuffer { - public void addBufferChangedListener(IBufferChangedListener listener) {} - public void append(char[] text) {} - public void append(String text) {} - public void close() {} - public char getChar(int position) { return 0; } - public char[] getCharacters() { return null; } - public String getContents() { return null; } - public int getLength() { return 0; } - public IOpenable getOwner() { return null; } - public String getText(int offset, int length) { return null; } - public IResource getUnderlyingResource() { return null; } - public boolean hasUnsavedChanges() { return false; } - public boolean isClosed() { return false; } - public boolean isReadOnly() { return true; } - public void removeBufferChangedListener(IBufferChangedListener listener) {} - public void replace(int position, int length, char[] text) {} - public void replace(int position, int length, String text) {} - public void save(IProgressMonitor progress, boolean force) throws JavaModelException {} - public void setContents(char[] contents) {} - public void setContents(String contents) {} - } - - - /** NULL implementing IBuffer */ - public final static IBuffer NULL= new NullBuffer(); - - - /** - * Executes a document set content call in the ui thread. - */ - protected class DocumentSetCommand implements Runnable { - - private String fContents; - - public void run() { - fDocument.set(fContents); - } + /** + * Internal implementation of a NULL instanceof IBuffer. + */ + static private class NullBuffer implements IBuffer { + public void addBufferChangedListener(IBufferChangedListener listener) { + } - public void set(String contents) { - fContents= contents; - Display.getDefault().syncExec(this); - } + public void append(char[] text) { } - /** - * Executes a document replace call in the ui thread. - */ - protected class DocumentReplaceCommand implements Runnable { + public void append(String text) { + } - private int fOffset; - private int fLength; - private String fText; + public void close() { + } - public void run() { - try { - fDocument.replace(fOffset, fLength, fText); - } catch (BadLocationException x) { - // ignore - } - } + public char getChar(int position) { + return 0; + } - public void replace(int offset, int length, String text) { - fOffset= offset; - fLength= length; - fText= text; - Display.getDefault().syncExec(this); + public char[] getCharacters() { + return null; + } + + public String getContents() { + return null; + } + + public int getLength() { + return 0; + } + + public IOpenable getOwner() { + return null; + } + + public String getText(int offset, int length) { + return null; + } + + public IResource getUnderlyingResource() { + return null; + } + + public boolean hasUnsavedChanges() { + return false; + } + + public boolean isClosed() { + return false; + } + + public boolean isReadOnly() { + return true; + } + + public void removeBufferChangedListener(IBufferChangedListener listener) { + } + + public void replace(int position, int length, char[] text) { + } + + public void replace(int position, int length, String text) { + } + + public void save(IProgressMonitor progress, boolean force) + throws JavaModelException { + } + + public void setContents(char[] contents) { + } + + public void setContents(String contents) { + } + } + + /** NULL implementing IBuffer */ + public final static IBuffer NULL = new NullBuffer(); + + /** + * Executes a document set content call in the ui thread. + */ + protected class DocumentSetCommand implements Runnable { + + private String fContents; + + public void run() { + fDocument.set(fContents); + } + + public void set(String contents) { + fContents = contents; + Display.getDefault().syncExec(this); + } + } + + /** + * Executes a document replace call in the ui thread. + */ + protected class DocumentReplaceCommand implements Runnable { + + private int fOffset; + + private int fLength; + + private String fText; + + public void run() { + try { + fDocument.replace(fOffset, fLength, fText); + } catch (BadLocationException x) { + // ignore } } - private static final boolean DEBUG_LINE_DELIMITERS= true; + public void replace(int offset, int length, String text) { + fOffset = offset; + fLength = length; + fText = text; + Display.getDefault().syncExec(this); + } + } + + private static final boolean DEBUG_LINE_DELIMITERS = true; private IOpenable fOwner; + private IFile fFile; + private ITextFileBuffer fTextFileBuffer; + private IDocument fDocument; - private DocumentSetCommand fSetCmd= new DocumentSetCommand(); - private DocumentReplaceCommand fReplaceCmd= new DocumentReplaceCommand(); + private DocumentSetCommand fSetCmd = new DocumentSetCommand(); + + private DocumentReplaceCommand fReplaceCmd = new DocumentReplaceCommand(); private Set fLegalLineDelimiters; - private List fBufferListeners= new ArrayList(3); - private IStatus fStatus; + private List fBufferListeners = new ArrayList(3); + private IStatus fStatus; /** * This method is public for test purposes only. */ public DocumentAdapter(IOpenable owner, IFile file) { - fOwner= owner; - fFile= file; + fOwner = owner; + fFile = file; initialize(); } private void initialize() { - ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager(); - IPath location= fFile.getFullPath(); + ITextFileBufferManager manager = FileBuffers.getTextFileBufferManager(); + IPath location = fFile.getFullPath(); try { manager.connect(location, new NullProgressMonitor()); - fTextFileBuffer= manager.getTextFileBuffer(location); - fDocument= fTextFileBuffer.getDocument(); + fTextFileBuffer = manager.getTextFileBuffer(location); + fDocument = fTextFileBuffer.getDocument(); } catch (CoreException x) { - fStatus= x.getStatus(); - fDocument= manager.createEmptyDocument(location); + fStatus = x.getStatus(); + fDocument = manager.createEmptyDocument(location); } fDocument.addPrenotifiedDocumentListener(this); } @@ -180,7 +231,7 @@ public class DocumentAdapter implements IBuffer, IDocumentListener { /** * Returns the adapted document. - * + * * @return the adapted document */ public IDocument getDocument() { @@ -229,18 +280,20 @@ public class DocumentAdapter implements IBuffer, IDocumentListener { if (isClosed()) return; - IDocument d= fDocument; - fDocument= null; + IDocument d = fDocument; + fDocument = null; d.removePrenotifiedDocumentListener(this); if (fTextFileBuffer != null) { - ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager(); + ITextFileBufferManager manager = FileBuffers + .getTextFileBufferManager(); try { - manager.disconnect(fTextFileBuffer.getLocation(), new NullProgressMonitor()); + manager.disconnect(fTextFileBuffer.getLocation(), + new NullProgressMonitor()); } catch (CoreException x) { // ignore } - fTextFileBuffer= null; + fTextFileBuffer = null; } fireBufferChanged(new BufferChangedEvent(this, 0, 0, null)); @@ -259,10 +312,10 @@ public class DocumentAdapter implements IBuffer, IDocumentListener { } /* - * @see IBuffer#getCharacters() + * @see IBuffer#getCharacters() */ public char[] getCharacters() { - String content= getContents(); + String content = getContents(); return content == null ? null : content.toCharArray(); } @@ -323,8 +376,9 @@ public class DocumentAdapter implements IBuffer, IDocumentListener { * @see IBuffer#isReadOnly() */ public boolean isReadOnly() { - IResource resource= getUnderlyingResource(); - return resource == null ? true : resource.getResourceAttributes().isReadOnly(); + IResource resource = getUnderlyingResource(); + return resource == null ? true : resource.getResourceAttributes() + .isReadOnly(); } /* @@ -347,7 +401,8 @@ public class DocumentAdapter implements IBuffer, IDocumentListener { /* * @see IBuffer#save(IProgressMonitor, boolean) */ - public void save(IProgressMonitor progress, boolean force) throws JavaModelException { + public void save(IProgressMonitor progress, boolean force) + throws JavaModelException { try { if (fTextFileBuffer != null) fTextFileBuffer.commit(progress, force); @@ -367,7 +422,7 @@ public class DocumentAdapter implements IBuffer, IDocumentListener { * @see IBuffer#setContents(String) */ public void setContents(String contents) { - int oldLength= fDocument.getLength(); + int oldLength = fDocument.getLength(); if (contents == null) { @@ -386,16 +441,15 @@ public class DocumentAdapter implements IBuffer, IDocumentListener { } } - private void validateLineDelimiters(String contents) { if (fLegalLineDelimiters == null) { // collect all line delimiters in the document - HashSet existingDelimiters= new HashSet(); + HashSet existingDelimiters = new HashSet(); - for (int i= fDocument.getNumberOfLines() - 1; i >= 0; i-- ) { + for (int i = fDocument.getNumberOfLines() - 1; i >= 0; i--) { try { - String curr= fDocument.getLineDelimiter(i); + String curr = fDocument.getLineDelimiter(i); if (curr != null) { existingDelimiters.add(curr); } @@ -406,23 +460,24 @@ public class DocumentAdapter implements IBuffer, IDocumentListener { if (existingDelimiters.isEmpty()) { return; // first insertion of a line delimiter: no test } - fLegalLineDelimiters= existingDelimiters; + fLegalLineDelimiters = existingDelimiters; } - DefaultLineTracker tracker= new DefaultLineTracker(); + DefaultLineTracker tracker = new DefaultLineTracker(); tracker.set(contents); - int lines= tracker.getNumberOfLines(); + int lines = tracker.getNumberOfLines(); if (lines <= 1) return; - for (int i= 0; i < lines; i++) { + for (int i = 0; i < lines; i++) { try { - String curr= tracker.getLineDelimiter(i); + String curr = tracker.getLineDelimiter(i); if (curr != null && !fLegalLineDelimiters.contains(curr)) { - StringBuffer buf= new StringBuffer("New line delimiter added to new code: "); //$NON-NLS-1$ - for (int k= 0; k < curr.length(); k++) { + StringBuffer buf = new StringBuffer( + "New line delimiter added to new code: "); //$NON-NLS-1$ + for (int k = 0; k < curr.length(); k++) { buf.append(String.valueOf((int) curr.charAt(k))); } PHPeclipsePlugin.log(new Exception(buf.toString())); @@ -444,12 +499,13 @@ public class DocumentAdapter implements IBuffer, IDocumentListener { * @see IDocumentListener#documentChanged(DocumentEvent) */ public void documentChanged(DocumentEvent event) { - fireBufferChanged(new BufferChangedEvent(this, event.getOffset(), event.getLength(), event.getText())); + fireBufferChanged(new BufferChangedEvent(this, event.getOffset(), event + .getLength(), event.getText())); } private void fireBufferChanged(BufferChangedEvent event) { if (fBufferListeners != null && fBufferListeners.size() > 0) { - Iterator e= new ArrayList(fBufferListeners).iterator(); + Iterator e = new ArrayList(fBufferListeners).iterator(); while (e.hasNext()) ((IBufferChangedListener) e.next()).bufferChanged(event); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/EditorHighlightingSynchronizer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/EditorHighlightingSynchronizer.java index 4f635d6..4125a28 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/EditorHighlightingSynchronizer.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/EditorHighlightingSynchronizer.java @@ -14,7 +14,6 @@ import org.eclipse.jface.text.Assert; import org.eclipse.jface.text.link.ILinkedModeListener; import org.eclipse.jface.text.link.LinkedModeModel; - /** * Turns off occurrences highlighting on a java editor until linked mode is * left. @@ -22,32 +21,35 @@ import org.eclipse.jface.text.link.LinkedModeModel; * @since 3.0 */ public class EditorHighlightingSynchronizer implements ILinkedModeListener { - + private final PHPEditor fEditor; -// private final boolean fWasOccurrencesOn; - + + // private final boolean fWasOccurrencesOn; + /** * Creates a new synchronizer. * - * @param editor the java editor the occurrences markers of which will be - * synchonized with the linked mode + * @param editor + * the java editor the occurrences markers of which will be + * synchonized with the linked mode * */ public EditorHighlightingSynchronizer(PHPEditor editor) { Assert.isLegal(editor != null); - fEditor= editor; -// fWasOccurrencesOn= fEditor.isMarkingOccurrences(); -// -// if (fWasOccurrencesOn) -// fEditor.uninstallOccurrencesFinder(); + fEditor = editor; + // fWasOccurrencesOn= fEditor.isMarkingOccurrences(); + // + // if (fWasOccurrencesOn) + // fEditor.uninstallOccurrencesFinder(); } /* - * @see org.eclipse.jface.text.link.ILinkedModeListener#left(org.eclipse.jface.text.link.LinkedModeModel, int) + * @see org.eclipse.jface.text.link.ILinkedModeListener#left(org.eclipse.jface.text.link.LinkedModeModel, + * int) */ public void left(LinkedModeModel environment, int flags) { -// if (fWasOccurrencesOn) -// fEditor.installOccurrencesFinder(); + // if (fWasOccurrencesOn) + // fEditor.installOccurrencesFinder(); } /* @@ -57,7 +59,8 @@ public class EditorHighlightingSynchronizer implements ILinkedModeListener { } /* - * @see org.eclipse.jface.text.link.ILinkedModeListener#resume(org.eclipse.jface.text.link.LinkedModeModel, int) + * @see org.eclipse.jface.text.link.ILinkedModeListener#resume(org.eclipse.jface.text.link.LinkedModeModel, + * int) */ public void resume(LinkedModeModel environment, int flags) { } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/EditorUtility.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/EditorUtility.java index b951472..7c1747a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/EditorUtility.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/EditorUtility.java @@ -11,7 +11,6 @@ package net.sourceforge.phpeclipse.phpeditor; - import net.sourceforge.phpdt.core.ICompilationUnit; import net.sourceforge.phpdt.core.IJavaElement; import net.sourceforge.phpdt.core.IJavaProject; @@ -40,17 +39,15 @@ import org.eclipse.ui.ide.IDE; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.texteditor.ITextEditor; - /** * A number of routines for working with JavaElements in editors - * - * Use 'isOpenInEditor' to test if an element is already open in a editor - * Use 'openInEditor' to force opening an element in a editor - * With 'getWorkingCopy' you get the working copy (element in the editor) of an element + * + * Use 'isOpenInEditor' to test if an element is already open in a editor Use + * 'openInEditor' to force opening an element in a editor With 'getWorkingCopy' + * you get the working copy (element in the editor) of an element */ public class EditorUtility { - - + public static boolean isEditorInput(Object element, IEditorPart editor) { if (editor != null) { try { @@ -61,86 +58,97 @@ public class EditorUtility { } return false; } - - /** + + /** * Tests if a cu is currently shown in an editor - * @return the IEditorPart if shown, null if element is not open in an editor - */ + * + * @return the IEditorPart if shown, null if element is not open in an + * editor + */ public static IEditorPart isOpenInEditor(Object inputElement) { - IEditorInput input= null; - + IEditorInput input = null; + try { input = getEditorInput(inputElement); } catch (JavaModelException x) { PHPeclipsePlugin.log(x.getStatus()); } - + if (input != null) { - IWorkbenchPage p= PHPeclipsePlugin.getActivePage(); + IWorkbenchPage p = PHPeclipsePlugin.getActivePage(); if (p != null) { return p.findEditor(input); } } - + return null; } - + /** - * Opens a Java editor for an element such as IJavaElement, IFile, or IStorage. - * The editor is activated by default. + * Opens a Java editor for an element such as IJavaElement, + * IFile, or IStorage. The editor is + * activated by default. + * * @return the IEditorPart or null if wrong element type or opening failed */ - public static IEditorPart openInEditor(Object inputElement) throws JavaModelException, PartInitException { + public static IEditorPart openInEditor(Object inputElement) + throws JavaModelException, PartInitException { return openInEditor(inputElement, true); } - + /** * Opens a Java editor for an element (IJavaElement, IFile, IStorage...) + * * @return the IEditorPart or null if wrong element type or opening failed */ - public static IEditorPart openInEditor(Object inputElement, boolean activate) throws JavaModelException, PartInitException { - + public static IEditorPart openInEditor(Object inputElement, boolean activate) + throws JavaModelException, PartInitException { + if (inputElement instanceof IFile) return openInEditor((IFile) inputElement, activate); - - IEditorInput input= getEditorInput(inputElement); + + IEditorInput input = getEditorInput(inputElement); if (input instanceof IFileEditorInput) { - IFileEditorInput fileInput= (IFileEditorInput) input; + IFileEditorInput fileInput = (IFileEditorInput) input; return openInEditor(fileInput.getFile(), activate); } - + if (input != null) - return openInEditor(input, getEditorID(input, inputElement), activate); - + return openInEditor(input, getEditorID(input, inputElement), + activate); + return null; } - - /** + + /** * Selects a Java Element in an editor - */ + */ public static void revealInEditor(IEditorPart part, IJavaElement element) { if (element != null && part instanceof PHPEditor) { ((PHPEditor) part).setSelection(element); } } - - private static IEditorPart openInEditor(IFile file, boolean activate) throws PartInitException { - if (file != null) { - IWorkbenchPage p= PHPeclipsePlugin.getActivePage(); - if (p != null) { - IEditorPart editorPart= IDE.openEditor(p, file, activate); - initializeHighlightRange(editorPart); - return editorPart; - } - } - return null; + + private static IEditorPart openInEditor(IFile file, boolean activate) + throws PartInitException { + if (file != null) { + IWorkbenchPage p = PHPeclipsePlugin.getActivePage(); + if (p != null) { + IEditorPart editorPart = IDE.openEditor(p, file, activate); + initializeHighlightRange(editorPart); + return editorPart; + } + } + return null; } - private static IEditorPart openInEditor(IEditorInput input, String editorID, boolean activate) throws PartInitException { + private static IEditorPart openInEditor(IEditorInput input, + String editorID, boolean activate) throws PartInitException { if (input != null) { - IWorkbenchPage p= PHPeclipsePlugin.getActivePage(); + IWorkbenchPage p = PHPeclipsePlugin.getActivePage(); if (p != null) { - IEditorPart editorPart= p.openEditor(input, editorID, activate); + IEditorPart editorPart = p + .openEditor(input, editorID, activate); initializeHighlightRange(editorPart); return editorPart; } @@ -150,164 +158,188 @@ public class EditorUtility { private static void initializeHighlightRange(IEditorPart editorPart) { if (editorPart instanceof ITextEditor) { - TogglePresentationAction toggleAction= new TogglePresentationAction(); + TogglePresentationAction toggleAction = new TogglePresentationAction(); // Initialize editor - toggleAction.setEditor((ITextEditor)editorPart); + toggleAction.setEditor((ITextEditor) editorPart); // Reset action toggleAction.setEditor(null); } } - + /** - *@deprecated Made it public again for java debugger UI. + * @deprecated Made it public again for java debugger UI. */ public static String getEditorID(IEditorInput input, Object inputObject) { - IEditorRegistry registry= PlatformUI.getWorkbench().getEditorRegistry(); - IEditorDescriptor descriptor= registry.getDefaultEditor(input.getName()); + IEditorRegistry registry = PlatformUI.getWorkbench() + .getEditorRegistry(); + IEditorDescriptor descriptor = registry.getDefaultEditor(input + .getName()); if (descriptor != null) return descriptor.getId(); return null; } - - private static IEditorInput getEditorInput(IJavaElement element) throws JavaModelException { + + private static IEditorInput getEditorInput(IJavaElement element) + throws JavaModelException { while (element != null) { - if (element instanceof IWorkingCopy && ((IWorkingCopy) element).isWorkingCopy()) - element= ((IWorkingCopy) element).getOriginalElement(); - + if (element instanceof IWorkingCopy + && ((IWorkingCopy) element).isWorkingCopy()) + element = ((IWorkingCopy) element).getOriginalElement(); + if (element instanceof ICompilationUnit) { - ICompilationUnit unit= (ICompilationUnit) element; - IResource resource= unit.getResource(); - if (resource instanceof IFile) - return new FileEditorInput((IFile) resource); + ICompilationUnit unit = (ICompilationUnit) element; + IResource resource = unit.getResource(); + if (resource instanceof IFile) + return new FileEditorInput((IFile) resource); } - -// if (element instanceof IClassFile) -// return new InternalClassFileEditorInput((IClassFile) element); -// - element= element.getParent(); + + // if (element instanceof IClassFile) + // return new InternalClassFileEditorInput((IClassFile) element); + // + element = element.getParent(); } - + return null; - } + } + + public static IEditorInput getEditorInput(Object input) + throws JavaModelException { - public static IEditorInput getEditorInput(Object input) throws JavaModelException { - if (input instanceof IJavaElement) return getEditorInput((IJavaElement) input); - - if (input instanceof IFile) + + if (input instanceof IFile) return new FileEditorInput((IFile) input); - -// if (input instanceof IStorage) -// return new JarEntryEditorInput((IStorage)input); - + + // if (input instanceof IStorage) + // return new JarEntryEditorInput((IStorage)input); + return null; } - + /** - * If the current active editor edits a java element return it, else - * return null + * If the current active editor edits a java element return it, else return + * null */ public static IJavaElement getActiveEditorJavaInput() { - IWorkbenchPage page= PHPeclipsePlugin.getActivePage(); + IWorkbenchPage page = PHPeclipsePlugin.getActivePage(); if (page != null) { - IEditorPart part= page.getActiveEditor(); + IEditorPart part = page.getActiveEditor(); if (part != null) { - IEditorInput editorInput= part.getEditorInput(); + IEditorInput editorInput = part.getEditorInput(); if (editorInput != null) { - return (IJavaElement)editorInput.getAdapter(IJavaElement.class); + return (IJavaElement) editorInput + .getAdapter(IJavaElement.class); } } } - return null; + return null; } - - /** + + /** * Gets the working copy of an compilation unit opened in an editor - * @param part the editor part - * @param cu the original compilation unit (or another working copy) + * + * @param part + * the editor part + * @param cu + * the original compilation unit (or another working copy) * @return the working copy of the compilation unit, or null if not found - */ + */ public static ICompilationUnit getWorkingCopy(ICompilationUnit cu) { if (cu == null) return null; if (cu.isWorkingCopy()) return cu; - - return (ICompilationUnit)cu.findSharedWorkingCopy(JavaUI.getBufferFactory()); + + return (ICompilationUnit) cu.findSharedWorkingCopy(JavaUI + .getBufferFactory()); } - - /** + + /** * Gets the working copy of an member opened in an editor - * - * @param member the original member or a member in a working copy - * @return the corresponding member in the shared working copy or null if not found - */ - public static IMember getWorkingCopy(IMember member) throws JavaModelException { - ICompilationUnit cu= member.getCompilationUnit(); + * + * @param member + * the original member or a member in a working copy + * @return the corresponding member in the shared working copy or + * null if not found + */ + public static IMember getWorkingCopy(IMember member) + throws JavaModelException { + ICompilationUnit cu = member.getCompilationUnit(); if (cu != null) { - ICompilationUnit workingCopy= getWorkingCopy(cu); + ICompilationUnit workingCopy = getWorkingCopy(cu); if (workingCopy != null) { - return JavaModelUtil.findMemberInCompilationUnit(workingCopy, member); + return JavaModelUtil.findMemberInCompilationUnit(workingCopy, + member); } } return null; } - + /** * Returns the compilation unit for the given java element. - * @param element the java element whose compilation unit is searched for + * + * @param element + * the java element whose compilation unit is searched for * @return the compilation unit of the given java element */ private static ICompilationUnit getCompilationUnit(IJavaElement element) { - + if (element == null) return null; - + if (element instanceof IMember) return ((IMember) element).getCompilationUnit(); - - int type= element.getElementType(); + + int type = element.getElementType(); if (IJavaElement.COMPILATION_UNIT == type) return (ICompilationUnit) element; if (IJavaElement.CLASS_FILE == type) return null; - + return getCompilationUnit(element.getParent()); } - - /** + + /** * Returns the working copy of the given java element. - * @param javaElement the javaElement for which the working copyshould be found - * @param reconcile indicates whether the working copy must be reconcile prior to searching it - * @return the working copy of the given element or null if none - */ - public static IJavaElement getWorkingCopy(IJavaElement element, boolean reconcile) throws JavaModelException { - ICompilationUnit unit= getCompilationUnit(element); + * + * @param javaElement + * the javaElement for which the working copyshould be found + * @param reconcile + * indicates whether the working copy must be reconcile prior to + * searching it + * @return the working copy of the given element or null if + * none + */ + public static IJavaElement getWorkingCopy(IJavaElement element, + boolean reconcile) throws JavaModelException { + ICompilationUnit unit = getCompilationUnit(element); if (unit == null) return null; - + if (unit.isWorkingCopy()) return element; - - ICompilationUnit workingCopy= getWorkingCopy(unit); + + ICompilationUnit workingCopy = getWorkingCopy(unit); if (workingCopy != null) { if (reconcile) { synchronized (workingCopy) { workingCopy.reconcile(); - return JavaModelUtil.findInCompilationUnit(workingCopy, element); + return JavaModelUtil.findInCompilationUnit(workingCopy, + element); } } else { - return JavaModelUtil.findInCompilationUnit(workingCopy, element); + return JavaModelUtil + .findInCompilationUnit(workingCopy, element); } } - + return null; } /** - * Maps the localized modifier name to a code in the same - * manner as #findModifier. + * Maps the localized modifier name to a code in the same manner as + * #findModifier. * * @return the SWT modifier bit, or 0 if no match was found * @see findModifier @@ -316,7 +348,7 @@ public class EditorUtility { public static int findLocalizedModifier(String token) { if (token == null) return 0; - + if (token.equalsIgnoreCase(Action.findModifierString(SWT.CTRL))) return SWT.CTRL; if (token.equalsIgnoreCase(Action.findModifierString(SWT.SHIFT))) @@ -330,67 +362,75 @@ public class EditorUtility { } /** - * Returns the modifier string for the given SWT modifier - * modifier bits. + * Returns the modifier string for the given SWT modifier modifier bits. * - * @param stateMask the SWT modifier bits + * @param stateMask + * the SWT modifier bits * @return the modifier string * @since 2.1.1 */ public static String getModifierString(int stateMask) { - String modifierString= ""; //$NON-NLS-1$ + String modifierString = ""; //$NON-NLS-1$ if ((stateMask & SWT.CTRL) == SWT.CTRL) - modifierString= appendModifierString(modifierString, SWT.CTRL); + modifierString = appendModifierString(modifierString, SWT.CTRL); if ((stateMask & SWT.ALT) == SWT.ALT) - modifierString= appendModifierString(modifierString, SWT.ALT); + modifierString = appendModifierString(modifierString, SWT.ALT); if ((stateMask & SWT.SHIFT) == SWT.SHIFT) - modifierString= appendModifierString(modifierString, SWT.SHIFT); + modifierString = appendModifierString(modifierString, SWT.SHIFT); if ((stateMask & SWT.COMMAND) == SWT.COMMAND) - modifierString= appendModifierString(modifierString, SWT.COMMAND); - + modifierString = appendModifierString(modifierString, SWT.COMMAND); + return modifierString; } /** - * Appends to modifier string of the given SWT modifier bit - * to the given modifierString. + * Appends to modifier string of the given SWT modifier bit to the given + * modifierString. * - * @param modifierString the modifier string - * @param modifier an int with SWT modifier bit + * @param modifierString + * the modifier string + * @param modifier + * an int with SWT modifier bit * @return the concatenated modifier string * @since 2.1.1 */ - private static String appendModifierString(String modifierString, int modifier) { + private static String appendModifierString(String modifierString, + int modifier) { if (modifierString == null) - modifierString= ""; //$NON-NLS-1$ - String newModifierString= Action.findModifierString(modifier); + modifierString = ""; //$NON-NLS-1$ + String newModifierString = Action.findModifierString(modifier); if (modifierString.length() == 0) return newModifierString; - return PHPEditorMessages.getFormattedString("EditorUtility.concatModifierStrings", new String[] {modifierString, newModifierString}); //$NON-NLS-1$ + return PHPEditorMessages + .getFormattedString( + "EditorUtility.concatModifierStrings", new String[] { modifierString, newModifierString }); //$NON-NLS-1$ } - + /** - * Returns the Java project for a given editor input or null if no corresponding - * Java project exists. + * Returns the Java project for a given editor input or null + * if no corresponding Java project exists. * - * @param input the editor input + * @param input + * the editor input * @return the corresponding Java project * * @since 3.0 */ public static IJavaProject getJavaProject(IEditorInput input) { - IJavaProject jProject= null; + IJavaProject jProject = null; if (input instanceof IFileEditorInput) { - IProject project= ((IFileEditorInput)input).getFile().getProject(); + IProject project = ((IFileEditorInput) input).getFile() + .getProject(); if (project != null) { - jProject= JavaCore.create(project); + jProject = JavaCore.create(project); if (!jProject.exists()) - jProject= null; + jProject = null; } - } -// else if (input instanceof IClassFileEditorInput) { -// jProject= ((IClassFileEditorInput)input).getClassFile().getJavaProject(); -// } + } + // else if (input instanceof IClassFileEditorInput) { + // jProject= + // ((IClassFileEditorInput)input).getClassFile().getJavaProject(); + // } return jProject; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/GotoAnnotationAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/GotoAnnotationAction.java index f82eb05..781cff9 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/GotoAnnotationAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/GotoAnnotationAction.java @@ -17,22 +17,23 @@ import org.eclipse.ui.PlatformUI; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.TextEditorAction; - public class GotoAnnotationAction extends TextEditorAction { private boolean fForward; public GotoAnnotationAction(String prefix, boolean forward) { super(PHPEditorMessages.getResourceBundle(), prefix, null); - fForward= forward; + fForward = forward; if (forward) - PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.GOTO_NEXT_ERROR_ACTION); + PlatformUI.getWorkbench().getHelpSystem().setHelp(this, + IJavaHelpContextIds.GOTO_NEXT_ERROR_ACTION); else - PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.GOTO_PREVIOUS_ERROR_ACTION); + PlatformUI.getWorkbench().getHelpSystem().setHelp(this, + IJavaHelpContextIds.GOTO_PREVIOUS_ERROR_ACTION); } public void run() { - PHPEditor e= (PHPEditor) getTextEditor(); + PHPEditor e = (PHPEditor) getTextEditor(); e.gotoAnnotation(fForward); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/GotoErrorAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/GotoErrorAction.java index bbfb96f..8a835e2 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/GotoErrorAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/GotoErrorAction.java @@ -17,22 +17,23 @@ import org.eclipse.ui.PlatformUI; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.TextEditorAction; - public class GotoErrorAction extends TextEditorAction { private boolean fForward; public GotoErrorAction(String prefix, boolean forward) { super(PHPEditorMessages.getResourceBundle(), prefix, null); - fForward= forward; + fForward = forward; if (forward) - PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.GOTO_NEXT_ERROR_ACTION); + PlatformUI.getWorkbench().getHelpSystem().setHelp(this, + IJavaHelpContextIds.GOTO_NEXT_ERROR_ACTION); else - PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.GOTO_PREVIOUS_ERROR_ACTION); + PlatformUI.getWorkbench().getHelpSystem().setHelp(this, + IJavaHelpContextIds.GOTO_PREVIOUS_ERROR_ACTION); } public void run() { - PHPEditor e= (PHPEditor) getTextEditor(); + PHPEditor e = (PHPEditor) getTextEditor(); e.gotoError(fForward); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/HTMLDocumentSetupParticipant.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/HTMLDocumentSetupParticipant.java index 823ca01..3e07d2c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/HTMLDocumentSetupParticipant.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/HTMLDocumentSetupParticipant.java @@ -1,13 +1,13 @@ /********************************************************************** -Copyright (c) 2000, 2003 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html + Copyright (c) 2000, 2003 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html -Contributors: - IBM Corporation - Initial implementation -**********************************************************************/ + Contributors: + IBM Corporation - Initial implementation + **********************************************************************/ package net.sourceforge.phpeclipse.phpeditor; import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; @@ -20,16 +20,18 @@ import org.eclipse.jface.text.IDocument; /** * The document setup participant for PHPDT. */ -public class HTMLDocumentSetupParticipant implements IDocumentSetupParticipant { +public class HTMLDocumentSetupParticipant implements IDocumentSetupParticipant { public HTMLDocumentSetupParticipant() { } - + /* * @see org.eclipse.core.filebuffers.IDocumentSetupParticipant#setup(org.eclipse.jface.text.IDocument) */ public void setup(IDocument document) { - JavaTextTools tools= PHPeclipsePlugin.getDefault().getJavaTextTools(); - tools.setupHTMLDocumentPartitioner(document, IPHPPartitions.PHP_PARTITIONING, null); //IPHPPartitions.PHP_PARTITIONING, null); + JavaTextTools tools = PHPeclipsePlugin.getDefault().getJavaTextTools(); + tools.setupHTMLDocumentPartitioner(document, + IPHPPartitions.PHP_PARTITIONING, null); // IPHPPartitions.PHP_PARTITIONING, + // null); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ICompilationUnitDocumentProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ICompilationUnitDocumentProvider.java index ec74b34..115130c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ICompilationUnitDocumentProvider.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ICompilationUnitDocumentProvider.java @@ -24,59 +24,73 @@ import org.eclipse.ui.texteditor.IDocumentProviderExtension3; /** * @since 3.0 */ -public interface ICompilationUnitDocumentProvider extends IDocumentProvider, IDocumentProviderExtension2, IDocumentProviderExtension3 { - +public interface ICompilationUnitDocumentProvider extends IDocumentProvider, + IDocumentProviderExtension2, IDocumentProviderExtension3 { + /** * Shuts down this provider. */ void shutdown(); - + /** * Returns the working copy for the given element. * - * @param element the element + * @param element + * the element * @return the working copy for the given element */ ICompilationUnit getWorkingCopy(Object element); - + /** - * Saves the content of the given document to the given element. This method has - * only an effect if it is called when directly or indirectly inside saveDocument. + * Saves the content of the given document to the given element. This method + * has only an effect if it is called when directly or indirectly inside + * saveDocument. * - * @param monitor the progress monitor - * @param element the element to which to save - * @param document the document to save - * @param overwrite true if the save should be enforced + * @param monitor + * the progress monitor + * @param element + * the element to which to save + * @param document + * the document to save + * @param overwrite + * true if the save should be enforced */ - void saveDocumentContent(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite) throws CoreException; - + void saveDocumentContent(IProgressMonitor monitor, Object element, + IDocument document, boolean overwrite) throws CoreException; + /** - * Creates a line tracker for the given element. It is of the same kind as the one that would be - * used for a newly created document for the given element. + * Creates a line tracker for the given element. It is of the same kind as + * the one that would be used for a newly created document for the given + * element. * - * @param element the element + * @param element + * the element * @return a line tracker for the given element */ ILineTracker createLineTracker(Object element); - + /** * Sets the document provider's save policy. * - * @param savePolicy the save policy + * @param savePolicy + * the save policy */ void setSavePolicy(ISavePolicy savePolicy); - + /** - * Adds a listener that reports changes from all compilation unit annotation models. + * Adds a listener that reports changes from all compilation unit annotation + * models. * - * @param listener the listener + * @param listener + * the listener */ void addGlobalAnnotationModelListener(IAnnotationModelListener listener); /** * Removes the listener. * - * @param listener the listener - */ + * @param listener + * the listener + */ void removeGlobalAnnotationModelListener(IAnnotationModelListener listener); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IJavaAnnotation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IJavaAnnotation.java index f35399b..2e109ad 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IJavaAnnotation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IJavaAnnotation.java @@ -18,41 +18,40 @@ import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Display; /** - * Interface of annotations representing markers - * and problems. + * Interface of annotations representing markers and problems. * * @see org.eclipse.core.resources.IMarker * @see net.sourceforge.phpdt.core.compiler.IProblem */ public interface IJavaAnnotation { - + /** * @see org.eclipse.jface.text.source.Annotation#getType() */ String getType(); - + /** * @see org.eclipse.jface.text.source.Annotation#isPersistent() */ boolean isPersistent(); - + /** * @see org.eclipse.jface.text.source.Annotation#isMarkedDeleted() */ boolean isMarkedDeleted(); - + /** - * @see org.eclipse.jface.text.source.Annotation#getText() + * @see org.eclipse.jface.text.source.Annotation#getText() */ String getText(); - + /** * Returns whether this annotation is overlaid. * * @return true if overlaid */ boolean hasOverlay(); - + /** * Returns the overlay of this annotation. * @@ -60,48 +59,50 @@ public interface IJavaAnnotation { * @since 3.0 */ IJavaAnnotation getOverlay(); - + /** - * Returns an iterator for iterating over the - * annotation which are overlaid by this annotation. + * Returns an iterator for iterating over the annotation which are overlaid + * by this annotation. * * @return an iterator over the overlaid annotaions */ Iterator getOverlaidIterator(); - + /** - * Adds the given annotation to the list of - * annotations which are overlaid by this annotations. - * - * @param annotation the problem annoation + * Adds the given annotation to the list of annotations which are overlaid + * by this annotations. + * + * @param annotation + * the problem annoation */ void addOverlaid(IJavaAnnotation annotation); - + /** - * Removes the given annotation from the list of - * annotations which are overlaid by this annotation. - * - * @param annotation the problem annoation + * Removes the given annotation from the list of annotations which are + * overlaid by this annotation. + * + * @param annotation + * the problem annoation */ void removeOverlaid(IJavaAnnotation annotation); - + /** - * Tells whether this annotation is a problem - * annotation. + * Tells whether this annotation is a problem annotation. * * @return true if it is a problem annotation */ boolean isProblem(); - + /** - * Returns the compilation unit corresponding to the document on which the annotation is set - * or null if no corresponding co0mpilationunit exists. + * Returns the compilation unit corresponding to the document on which the + * annotation is set or null if no corresponding + * co0mpilationunit exists. */ ICompilationUnit getCompilationUnit(); - + String[] getArguments(); - + int getId(); - + Image getImage(Display display); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IJavaEditorActionConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IJavaEditorActionConstants.java index 85b94d9..fd91df3 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IJavaEditorActionConstants.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IJavaEditorActionConstants.java @@ -18,16 +18,15 @@ public interface IJavaEditorActionConstants { /** * ID of the action to toggle the style of the presentation. */ - public static final String TOGGLE_PRESENTATION= "togglePresentation"; //$NON-NLS-1$ + public static final String TOGGLE_PRESENTATION = "togglePresentation"; //$NON-NLS-1$ - /** * ID of the toolbar action to go to the previous error. */ - public static final String PREVIOUS_ERROR= "gotoPreviousError"; //$NON-NLS-1$ - + public static final String PREVIOUS_ERROR = "gotoPreviousError"; //$NON-NLS-1$ + /** * ID of the toolbar action to go to the next error. */ - public static final String NEXT_ERROR= "gotoNextError"; //$NON-NLS-1$ + public static final String NEXT_ERROR = "gotoNextError"; //$NON-NLS-1$ } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IPainter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IPainter.java index ce0caba..80d2594 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IPainter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IPainter.java @@ -5,35 +5,38 @@ package net.sourceforge.phpeclipse.phpeditor; * All Rights Reserved. */ - public interface IPainter { - /** Paint reasons */ - int SELECTION= 0; - int TEXT_CHANGE= 1; - int KEY_STROKE= 2; - int MOUSE_BUTTON= 4; - int INTERNAL= 8; - int CONFIGURATION= 16; - - - /** - * Disposes this painter. - *

                                                      - * XXX: The relationship with deactivate is not yet defined. - *

                                                      - * */ - void dispose(); - - void paint(int reason); - - /** - * Deactivates the painter. - *

                                                      - * XXX: The relationship with dispose is not yet defined. - *

                                                      - */ - void deactivate(boolean redraw); - - void setPositionManager(IPositionManager manager); + /** Paint reasons */ + int SELECTION = 0; + + int TEXT_CHANGE = 1; + + int KEY_STROKE = 2; + + int MOUSE_BUTTON = 4; + + int INTERNAL = 8; + + int CONFIGURATION = 16; + + /** + * Disposes this painter. + *

                                                      + * XXX: The relationship with deactivate is not yet defined. + *

                                                      + */ + void dispose(); + + void paint(int reason); + + /** + * Deactivates the painter. + *

                                                      + * XXX: The relationship with dispose is not yet defined. + *

                                                      + */ + void deactivate(boolean redraw); + + void setPositionManager(IPositionManager manager); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IPositionManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IPositionManager.java index 9b96295..8b4965c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IPositionManager.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IPositionManager.java @@ -7,10 +7,9 @@ package net.sourceforge.phpeclipse.phpeditor; import org.eclipse.jface.text.Position; - public interface IPositionManager { - + void addManagedPosition(Position position); - + void removeManagedPosition(Position position); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IProblemAnnotation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IProblemAnnotation.java index 6413787..bd6a3ee 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IProblemAnnotation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IProblemAnnotation.java @@ -1,60 +1,57 @@ package net.sourceforge.phpeclipse.phpeditor; + /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ - import java.util.Iterator; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Display; - /** * Interface of annotations representing problems. */ public interface IProblemAnnotation { - + AnnotationType getAnnotationType(); - + boolean isTemporary(); - + String getMessage(); - + String[] getArguments(); - + int getId(); - - + Image getImage(Display display); - + boolean isRelevant(); - + boolean hasOverlay(); - + Iterator getOverlaidIterator(); - + void addOverlaid(IProblemAnnotation annotation); - + void removeOverlaid(IProblemAnnotation annotation); - - + /** * @deprecated */ boolean isProblem(); - + /** * @deprecated */ boolean isTask(); - + /** * @deprecated */ boolean isWarning(); - + /** * @deprecated */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ISavePolicy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ISavePolicy.java index 4228763..4b26a0c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ISavePolicy.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ISavePolicy.java @@ -10,21 +10,18 @@ *******************************************************************************/ package net.sourceforge.phpeclipse.phpeditor; - - import net.sourceforge.phpdt.core.ICompilationUnit; public interface ISavePolicy { /** - * + * */ void preSave(ICompilationUnit unit); - + /** - * Returns the compilation unit in which the argument - * has been changed. If the argument is not changed, the - * returned result is null. + * Returns the compilation unit in which the argument has been changed. If + * the argument is not changed, the returned result is null. */ ICompilationUnit postSave(ICompilationUnit unit); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaAnnotationImageProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaAnnotationImageProvider.java index e162a01..ae92cf6 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaAnnotationImageProvider.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaAnnotationImageProvider.java @@ -22,7 +22,6 @@ import org.eclipse.swt.widgets.Display; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.texteditor.IAnnotationImageProvider; -//import net.sourceforge.phpdt.internal.ui.text.correction.JavaCorrectionProcessor; /** * Image provider for annotations based on Java problem markers. @@ -30,39 +29,46 @@ import org.eclipse.ui.texteditor.IAnnotationImageProvider; * @since 3.0 */ public class JavaAnnotationImageProvider implements IAnnotationImageProvider { - - private final static int NO_IMAGE= 0; - private final static int GRAY_IMAGE= 1; - private final static int OVERLAY_IMAGE= 2; - private final static int QUICKFIX_IMAGE= 3; - private final static int QUICKFIX_ERROR_IMAGE= 4; - - + + private final static int NO_IMAGE = 0; + + private final static int GRAY_IMAGE = 1; + + private final static int OVERLAY_IMAGE = 2; + + private final static int QUICKFIX_IMAGE = 3; + + private final static int QUICKFIX_ERROR_IMAGE = 4; + private static Image fgQuickFixImage; + private static Image fgQuickFixErrorImage; + private static ImageRegistry fgImageRegistry; - + private boolean fShowQuickFixIcon; + private int fCachedImageType; + private Image fCachedImage; - - + public JavaAnnotationImageProvider() { - fShowQuickFixIcon= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CORRECTION_INDICATION); + fShowQuickFixIcon = PreferenceConstants.getPreferenceStore() + .getBoolean(PreferenceConstants.EDITOR_CORRECTION_INDICATION); } - + /* * @see org.eclipse.jface.text.source.IAnnotationImageProvider#getManagedImage(org.eclipse.jface.text.source.Annotation) */ public Image getManagedImage(Annotation annotation) { if (annotation instanceof IJavaAnnotation) { - IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation; - int imageType= getImageType(javaAnnotation); + IJavaAnnotation javaAnnotation = (IJavaAnnotation) annotation; + int imageType = getImageType(javaAnnotation); return getImage(javaAnnotation, imageType, Display.getCurrent()); } return null; } - + /* * @see org.eclipse.jface.text.source.IAnnotationImageProvider#getImageDescriptorId(org.eclipse.jface.text.source.Annotation) */ @@ -78,86 +84,95 @@ public class JavaAnnotationImageProvider implements IAnnotationImageProvider { // unmanaged images are not supported return null; } - - + private boolean showQuickFix(IJavaAnnotation annotation) { - // return fShowQuickFixIcon && annotation.isProblem() && JavaCorrectionProcessor.hasCorrections(annotation); - return false; + // return fShowQuickFixIcon && annotation.isProblem() && + // JavaCorrectionProcessor.hasCorrections(annotation); + return false; } - + private Image getQuickFixImage() { if (fgQuickFixImage == null) - fgQuickFixImage= PHPUiImages.get(PHPUiImages.IMG_OBJS_FIXABLE_PROBLEM); + fgQuickFixImage = PHPUiImages + .get(PHPUiImages.IMG_OBJS_FIXABLE_PROBLEM); return fgQuickFixImage; } private Image getQuickFixErrorImage() { if (fgQuickFixErrorImage == null) - fgQuickFixErrorImage= PHPUiImages.get(PHPUiImages.IMG_OBJS_FIXABLE_ERROR); + fgQuickFixErrorImage = PHPUiImages + .get(PHPUiImages.IMG_OBJS_FIXABLE_ERROR); return fgQuickFixErrorImage; } - + private ImageRegistry getImageRegistry(Display display) { if (fgImageRegistry == null) - fgImageRegistry= new ImageRegistry(display); + fgImageRegistry = new ImageRegistry(display); return fgImageRegistry; } - + private int getImageType(IJavaAnnotation annotation) { - int imageType= NO_IMAGE; + int imageType = NO_IMAGE; if (annotation.hasOverlay()) - imageType= OVERLAY_IMAGE; + imageType = OVERLAY_IMAGE; else if (!annotation.isMarkedDeleted()) { if (showQuickFix(annotation)) - imageType= JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE.equals(annotation.getType()) ? QUICKFIX_ERROR_IMAGE : QUICKFIX_IMAGE; + imageType = JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE + .equals(annotation.getType()) ? QUICKFIX_ERROR_IMAGE + : QUICKFIX_IMAGE; } else { - imageType= GRAY_IMAGE; + imageType = GRAY_IMAGE; } return imageType; } - private Image getImage(IJavaAnnotation annotation, int imageType, Display display) { + private Image getImage(IJavaAnnotation annotation, int imageType, + Display display) { if (fCachedImageType == imageType) return fCachedImage; - - Image image= null; + + Image image = null; switch (imageType) { - case OVERLAY_IMAGE: - IJavaAnnotation overlay= annotation.getOverlay(); - image= overlay.getImage(display); - break; - case QUICKFIX_IMAGE: - image= getQuickFixImage(); - break; - case QUICKFIX_ERROR_IMAGE: - image= getQuickFixErrorImage(); - break; - case GRAY_IMAGE: { - ISharedImages sharedImages= PlatformUI.getWorkbench().getSharedImages(); - String annotationType= annotation.getType(); - if (JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE.equals(annotationType)) { - image= sharedImages.getImage(ISharedImages.IMG_OBJS_ERROR_TSK); - } else if (JavaMarkerAnnotation.WARNING_ANNOTATION_TYPE.equals(annotationType)) { - image= sharedImages.getImage(ISharedImages.IMG_OBJS_WARN_TSK); - } else if (JavaMarkerAnnotation.INFO_ANNOTATION_TYPE.equals(annotationType)) { - image= sharedImages.getImage(ISharedImages.IMG_OBJS_INFO_TSK); - } - if (image != null) { - ImageRegistry registry= getImageRegistry(display); - String key= Integer.toString(image.hashCode()); - Image grayImage= registry.get(key); - if (grayImage == null) { - grayImage= new Image(display, image, SWT.IMAGE_GRAY); - registry.put(key, grayImage); - } - image= grayImage; + case OVERLAY_IMAGE: + IJavaAnnotation overlay = annotation.getOverlay(); + image = overlay.getImage(display); + break; + case QUICKFIX_IMAGE: + image = getQuickFixImage(); + break; + case QUICKFIX_ERROR_IMAGE: + image = getQuickFixErrorImage(); + break; + case GRAY_IMAGE: { + ISharedImages sharedImages = PlatformUI.getWorkbench() + .getSharedImages(); + String annotationType = annotation.getType(); + if (JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE + .equals(annotationType)) { + image = sharedImages.getImage(ISharedImages.IMG_OBJS_ERROR_TSK); + } else if (JavaMarkerAnnotation.WARNING_ANNOTATION_TYPE + .equals(annotationType)) { + image = sharedImages.getImage(ISharedImages.IMG_OBJS_WARN_TSK); + } else if (JavaMarkerAnnotation.INFO_ANNOTATION_TYPE + .equals(annotationType)) { + image = sharedImages.getImage(ISharedImages.IMG_OBJS_INFO_TSK); + } + if (image != null) { + ImageRegistry registry = getImageRegistry(display); + String key = Integer.toString(image.hashCode()); + Image grayImage = registry.get(key); + if (grayImage == null) { + grayImage = new Image(display, image, SWT.IMAGE_GRAY); + registry.put(key, grayImage); } - break; + image = grayImage; } + break; } - - fCachedImageType= imageType; - fCachedImage= image; + } + + fCachedImageType = imageType; + fCachedImage = image; return fCachedImage; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaAnnotationIterator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaAnnotationIterator.java index ad4eb24..40ef7c2 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaAnnotationIterator.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaAnnotationIterator.java @@ -16,61 +16,70 @@ import java.util.Iterator; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.IAnnotationModel; - /** * Filters problems based on their types. */ public class JavaAnnotationIterator implements Iterator { - + private Iterator fIterator; + private Annotation fNext; + private boolean fSkipIrrelevants; + private boolean fReturnAllAnnotations; - + /** - * Equivalent to JavaAnnotationIterator(model, skipIrrelevants, false). + * Equivalent to + * JavaAnnotationIterator(model, skipIrrelevants, false). */ - public JavaAnnotationIterator(IAnnotationModel model, boolean skipIrrelevants) { + public JavaAnnotationIterator(IAnnotationModel model, + boolean skipIrrelevants) { this(model, skipIrrelevants, false); } - + /** - * Returns a new JavaAnnotationIterator. - * @param model the annotation model - * @param skipIrrelevants whether to skip irrelevant annotations - * @param returnAllAnnotations Whether to return non IJavaAnnotations as well + * Returns a new JavaAnnotationIterator. + * + * @param model + * the annotation model + * @param skipIrrelevants + * whether to skip irrelevant annotations + * @param returnAllAnnotations + * Whether to return non IJavaAnnotations as well */ - public JavaAnnotationIterator(IAnnotationModel model, boolean skipIrrelevants, boolean returnAllAnnotations) { - fReturnAllAnnotations= returnAllAnnotations; + public JavaAnnotationIterator(IAnnotationModel model, + boolean skipIrrelevants, boolean returnAllAnnotations) { + fReturnAllAnnotations = returnAllAnnotations; if (model != null) - fIterator= model.getAnnotationIterator(); + fIterator = model.getAnnotationIterator(); else - fIterator= Collections.EMPTY_LIST.iterator(); - fSkipIrrelevants= skipIrrelevants; + fIterator = Collections.EMPTY_LIST.iterator(); + fSkipIrrelevants = skipIrrelevants; skip(); } - + private void skip() { while (fIterator.hasNext()) { - Annotation next= (Annotation) fIterator.next(); + Annotation next = (Annotation) fIterator.next(); if (next instanceof IJavaAnnotation) { if (fSkipIrrelevants) { if (!next.isMarkedDeleted()) { - fNext= next; + fNext = next; return; } } else { - fNext= next; + fNext = next; return; } } else if (fReturnAllAnnotations) { - fNext= next; + fNext = next; return; } } - fNext= null; + fNext = null; } - + /* * @see Iterator#hasNext() */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaDocumentFactory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaDocumentFactory.java index a2fa69b..1166d26 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaDocumentFactory.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaDocumentFactory.java @@ -1,27 +1,26 @@ /********************************************************************** -Copyright (c) 2000, 2003 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html + Copyright (c) 2000, 2003 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html -Contributors: - IBM Corporation - Initial implementation -**********************************************************************/ + Contributors: + IBM Corporation - Initial implementation + **********************************************************************/ package net.sourceforge.phpeclipse.phpeditor; import org.eclipse.core.filebuffers.IDocumentFactory; import org.eclipse.jface.text.IDocument; - /** * The document factory for JDT UI, */ -public class JavaDocumentFactory implements IDocumentFactory { +public class JavaDocumentFactory implements IDocumentFactory { public JavaDocumentFactory() { } - + /* * @see org.eclipse.core.filebuffers.IDocumentFactory#createDocument() */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaDocumentSetupParticipant.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaDocumentSetupParticipant.java index d65fe4c..ce4929a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaDocumentSetupParticipant.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaDocumentSetupParticipant.java @@ -1,13 +1,13 @@ /********************************************************************** -Copyright (c) 2000, 2003 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html + Copyright (c) 2000, 2003 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html -Contributors: - IBM Corporation - Initial implementation -**********************************************************************/ + Contributors: + IBM Corporation - Initial implementation + **********************************************************************/ package net.sourceforge.phpeclipse.phpeditor; import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; @@ -20,18 +20,21 @@ import org.eclipse.jface.text.IDocument; /** * The document setup participant for PHPDT. */ -public class JavaDocumentSetupParticipant implements IDocumentSetupParticipant { +public class JavaDocumentSetupParticipant implements IDocumentSetupParticipant { public JavaDocumentSetupParticipant() { } - + /* * @see org.eclipse.core.filebuffers.IDocumentSetupParticipant#setup(org.eclipse.jface.text.IDocument) */ public void setup(IDocument document) { - JavaTextTools tools= PHPeclipsePlugin.getDefault().getJavaTextTools(); - tools.setupJavaDocumentPartitioner(document, IPHPPartitions.PHP_PARTITIONING); + JavaTextTools tools = PHPeclipsePlugin.getDefault().getJavaTextTools(); + tools.setupJavaDocumentPartitioner(document, + IPHPPartitions.PHP_PARTITIONING); -// tools.setupJavaDocumentPartitioner(document, IPHPPartitions.PHP_PARTITIONING, null); //IPHPPartitions.PHP_PARTITIONING, null); + // tools.setupJavaDocumentPartitioner(document, + // IPHPPartitions.PHP_PARTITIONING, null); + // //IPHPPartitions.PHP_PARTITIONING, null); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaEditorErrorTickUpdater.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaEditorErrorTickUpdater.java index af78de1..7d849d9 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaEditorErrorTickUpdater.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaEditorErrorTickUpdater.java @@ -24,35 +24,42 @@ import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorInput; /** - * The JavaEditorErrorTickUpdater will register as a IProblemChangedListener - * to listen on problem changes of the editor's input. It updates the title images when the annotation - * model changed. + * The JavaEditorErrorTickUpdater will register as a + * IProblemChangedListener to listen on problem changes of the editor's input. + * It updates the title images when the annotation model changed. */ public class JavaEditorErrorTickUpdater implements IProblemChangedListener { private PHPEditor fJavaEditor; + private JavaUILabelProvider fLabelProvider; public JavaEditorErrorTickUpdater(PHPEditor editor) { Assert.isNotNull(editor); - fJavaEditor= editor; - fLabelProvider= new JavaUILabelProvider(0, JavaElementImageProvider.SMALL_ICONS); + fJavaEditor = editor; + fLabelProvider = new JavaUILabelProvider(0, + JavaElementImageProvider.SMALL_ICONS); fLabelProvider.addLabelDecorator(new ProblemsLabelDecorator(null)); - PHPeclipsePlugin.getDefault().getProblemMarkerManager().addListener(this); + PHPeclipsePlugin.getDefault().getProblemMarkerManager().addListener( + this); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see IProblemChangedListener#problemsChanged(IResource[], boolean) */ - public void problemsChanged(IResource[] changedResources, boolean isMarkerChange) { + public void problemsChanged(IResource[] changedResources, + boolean isMarkerChange) { if (isMarkerChange) { return; } - IEditorInput input= fJavaEditor.getEditorInput(); + IEditorInput input = fJavaEditor.getEditorInput(); if (input != null) { // might run async, tests needed - IJavaElement jelement= (IJavaElement) input.getAdapter(IJavaElement.class); + IJavaElement jelement = (IJavaElement) input + .getAdapter(IJavaElement.class); if (jelement != null) { - IResource resource= jelement.getResource(); + IResource resource = jelement.getResource(); for (int i = 0; i < changedResources.length; i++) { if (changedResources[i].equals(resource)) { updateEditorImage(jelement); @@ -60,21 +67,21 @@ public class JavaEditorErrorTickUpdater implements IProblemChangedListener { } } } - } - + } + public void updateEditorImage(IJavaElement jelement) { - Image titleImage= fJavaEditor.getTitleImage(); + Image titleImage = fJavaEditor.getTitleImage(); if (titleImage == null) { return; } - Image newImage= fLabelProvider.getImage(jelement); + Image newImage = fLabelProvider.getImage(jelement); if (titleImage != newImage) { postImageChange(newImage); } } - + private void postImageChange(final Image newImage) { - Shell shell= fJavaEditor.getEditorSite().getShell(); + Shell shell = fJavaEditor.getEditorSite().getShell(); if (shell != null && !shell.isDisposed()) { shell.getDisplay().syncExec(new Runnable() { public void run() { @@ -82,14 +89,12 @@ public class JavaEditorErrorTickUpdater implements IProblemChangedListener { } }); } - } - + } + public void dispose() { fLabelProvider.dispose(); - PHPeclipsePlugin.getDefault().getProblemMarkerManager().removeListener(this); + PHPeclipsePlugin.getDefault().getProblemMarkerManager().removeListener( + this); } - } - - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaMarkerAnnotation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaMarkerAnnotation.java index 2e6c47f..e72f265 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaMarkerAnnotation.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaMarkerAnnotation.java @@ -11,7 +11,6 @@ package net.sourceforge.phpeclipse.phpeditor; - import java.util.Iterator; import net.sourceforge.phpdt.core.ICompilationUnit; @@ -25,37 +24,40 @@ import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.texteditor.MarkerAnnotation; +public class JavaMarkerAnnotation extends MarkerAnnotation implements + IJavaAnnotation { + + public static final String JAVA_MARKER_TYPE_PREFIX = "net.sourceforge.phpdt"; //$NON-NLS-1$ + + public static final String ERROR_ANNOTATION_TYPE = "net.sourceforge.phpdt.ui.error"; //$NON-NLS-1$ + public static final String WARNING_ANNOTATION_TYPE = "net.sourceforge.phpdt.ui.warning"; //$NON-NLS-1$ -public class JavaMarkerAnnotation extends MarkerAnnotation implements IJavaAnnotation { + public static final String INFO_ANNOTATION_TYPE = "net.sourceforge.phpdt.ui.info"; //$NON-NLS-1$ - public static final String JAVA_MARKER_TYPE_PREFIX= "net.sourceforge.phpdt"; //$NON-NLS-1$ - public static final String ERROR_ANNOTATION_TYPE= "net.sourceforge.phpdt.ui.error"; //$NON-NLS-1$ - public static final String WARNING_ANNOTATION_TYPE= "net.sourceforge.phpdt.ui.warning"; //$NON-NLS-1$ - public static final String INFO_ANNOTATION_TYPE= "net.sourceforge.phpdt.ui.info"; //$NON-NLS-1$ - public static final String TASK_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.task"; //$NON-NLS-1$ + public static final String TASK_ANNOTATION_TYPE = "org.eclipse.ui.workbench.texteditor.task"; //$NON-NLS-1$ private IJavaAnnotation fOverlay; - - + public JavaMarkerAnnotation(IMarker marker) { super(marker); } - + /* * @see net.sourceforge.phpdt.internal.ui.javaeditor.IJavaAnnotation#getImage(org.eclipse.swt.widgets.Display) */ public Image getImage(Display display) { return super.getImage(display); } - + /* * @see IJavaAnnotation#getArguments() */ public String[] getArguments() { - IMarker marker= getMarker(); + IMarker marker = getMarker(); if (marker != null && marker.exists() && isProblem()) - return JavaModelUtil.getProblemArgumentsFromMarker(marker.getAttribute(IJavaModelMarker.ARGUMENTS, "")); //$NON-NLS-1$ + return JavaModelUtil.getProblemArgumentsFromMarker(marker + .getAttribute(IJavaModelMarker.ARGUMENTS, "")); //$NON-NLS-1$ return null; } @@ -63,65 +65,67 @@ public class JavaMarkerAnnotation extends MarkerAnnotation implements IJavaAnnot * @see IJavaAnnotation#getId() */ public int getId() { - IMarker marker= getMarker(); - if (marker == null || !marker.exists()) + IMarker marker = getMarker(); + if (marker == null || !marker.exists()) return -1; - + if (isProblem()) return marker.getAttribute(IJavaModelMarker.ID, -1); - -// if (TASK_ANNOTATION_TYPE.equals(getAnnotationType())) { -// try { -// if (marker.isSubtypeOf(IJavaModelMarker.TASK_MARKER)) { -// return IProblem.Task; -// } -// } catch (CoreException e) { -// JavaPlugin.log(e); // should no happen, we test for marker.exists -// } -// } - + + // if (TASK_ANNOTATION_TYPE.equals(getAnnotationType())) { + // try { + // if (marker.isSubtypeOf(IJavaModelMarker.TASK_MARKER)) { + // return IProblem.Task; + // } + // } catch (CoreException e) { + // JavaPlugin.log(e); // should no happen, we test for marker.exists + // } + // } + return -1; } - + /* * @see IJavaAnnotation#isProblem() */ public boolean isProblem() { - String type= getType(); - return WARNING_ANNOTATION_TYPE.equals(type) || ERROR_ANNOTATION_TYPE.equals(type); + String type = getType(); + return WARNING_ANNOTATION_TYPE.equals(type) + || ERROR_ANNOTATION_TYPE.equals(type); } /** * Overlays this annotation with the given javaAnnotation. * - * @param javaAnnotation annotation that is overlaid by this annotation + * @param javaAnnotation + * annotation that is overlaid by this annotation */ public void setOverlay(IJavaAnnotation javaAnnotation) { if (fOverlay != null) fOverlay.removeOverlaid(this); - - fOverlay= javaAnnotation; + + fOverlay = javaAnnotation; if (!isMarkedDeleted()) markDeleted(fOverlay != null); - + if (fOverlay != null) fOverlay.addOverlaid(this); } - + /* * @see IJavaAnnotation#hasOverlay() */ public boolean hasOverlay() { return fOverlay != null; } - + /* * @see net.sourceforge.phpdt.internal.ui.javaeditor.IJavaAnnotation#getOverlay() */ public IJavaAnnotation getOverlay() { return fOverlay; } - + /* * @see IJavaAnnotation#addOverlaid(IJavaAnnotation) */ @@ -135,7 +139,7 @@ public class JavaMarkerAnnotation extends MarkerAnnotation implements IJavaAnnot public void removeOverlaid(IJavaAnnotation annotation) { // not supported } - + /* * @see IJavaAnnotation#getOverlaidIterator() */ @@ -144,14 +148,16 @@ public class JavaMarkerAnnotation extends MarkerAnnotation implements IJavaAnnot return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see net.sourceforge.phpdt.internal.ui.javaeditor.IJavaAnnotation#getCompilationUnit() */ public ICompilationUnit getCompilationUnit() { - IJavaElement element= JavaCore.create(getMarker().getResource()); + IJavaElement element = JavaCore.create(getMarker().getResource()); if (element instanceof ICompilationUnit) { - ICompilationUnit cu= (ICompilationUnit)element; - ICompilationUnit workingCopy= EditorUtility.getWorkingCopy(cu); + ICompilationUnit cu = (ICompilationUnit) element; + ICompilationUnit workingCopy = EditorUtility.getWorkingCopy(cu); if (workingCopy != null) { return workingCopy; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaOutlinePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaOutlinePage.java index c552344..f3a1eae 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaOutlinePage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaOutlinePage.java @@ -10,7 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpeclipse.phpeditor; - import java.util.Enumeration; import java.util.Hashtable; import java.util.List; @@ -109,754 +108,806 @@ import org.eclipse.ui.texteditor.TextEditorAction; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; import org.eclipse.ui.views.navigator.LocalSelectionTransfer; - /** - * The content outline page of the Java editor. The viewer implements a proprietary - * update mechanism based on Java model deltas. It does not react on domain changes. - * It is specified to show the content of ICompilationUnits and IClassFiles. - * Publishes its context menu under PHPeclipsePlugin.getDefault().getPluginId() + ".outline". + * The content outline page of the Java editor. The viewer implements a + * proprietary update mechanism based on Java model deltas. It does not react on + * domain changes. It is specified to show the content of ICompilationUnits and + * IClassFiles. Publishes its context menu under + * PHPeclipsePlugin.getDefault().getPluginId() + ".outline". */ -public class JavaOutlinePage extends Page implements IContentOutlinePage, IAdaptable , IPostSelectionProvider { - - static Object[] NO_CHILDREN= new Object[0]; - - /** - * The element change listener of the java outline viewer. - * @see IElementChangedListener - */ - class ElementChangedListener implements IElementChangedListener { +public class JavaOutlinePage extends Page implements IContentOutlinePage, + IAdaptable, IPostSelectionProvider { - public void elementChanged(final ElementChangedEvent e) { + static Object[] NO_CHILDREN = new Object[0]; - if (getControl() == null) + /** + * The element change listener of the java outline viewer. + * + * @see IElementChangedListener + */ + class ElementChangedListener implements IElementChangedListener { + + public void elementChanged(final ElementChangedEvent e) { + + if (getControl() == null) + return; + + Display d = getControl().getDisplay(); + if (d != null) { + d.asyncExec(new Runnable() { + public void run() { + ICompilationUnit cu = (ICompilationUnit) fInput; + IJavaElement base = cu; + // if (fTopLevelTypeOnly) { + // base= getMainType(cu); + // if (base == null) { + if (fOutlineViewer != null) + fOutlineViewer.refresh(true); return; - - Display d= getControl().getDisplay(); - if (d != null) { - d.asyncExec(new Runnable() { - public void run() { - ICompilationUnit cu= (ICompilationUnit) fInput; - IJavaElement base= cu; -// if (fTopLevelTypeOnly) { -// base= getMainType(cu); -// if (base == null) { - if (fOutlineViewer != null) - fOutlineViewer.refresh(true); - return; -// } -// } -// IJavaElementDelta delta= findElement(base, e.getDelta()); -// if (delta != null && fOutlineViewer != null) { -// fOutlineViewer.reconcile(delta); -// } - } - }); - } - } - - private boolean isPossibleStructuralChange(IJavaElementDelta cuDelta) { - if (cuDelta.getKind() != IJavaElementDelta.CHANGED) { - return true; // add or remove - } - int flags= cuDelta.getFlags(); - if ((flags & IJavaElementDelta.F_CHILDREN) != 0) { - return true; - } - return (flags & (IJavaElementDelta.F_CONTENT | IJavaElementDelta.F_FINE_GRAINED)) == IJavaElementDelta.F_CONTENT; - } - - protected IJavaElementDelta findElement(IJavaElement unit, IJavaElementDelta delta) { - - if (delta == null || unit == null) - return null; - - IJavaElement element= delta.getElement(); - - if (unit.equals(element)) { - if (isPossibleStructuralChange(delta)) { - return delta; - } - return null; + // } + // } + // IJavaElementDelta delta= findElement(base, + // e.getDelta()); + // if (delta != null && fOutlineViewer != null) { + // fOutlineViewer.reconcile(delta); + // } } + }); + } + } + private boolean isPossibleStructuralChange(IJavaElementDelta cuDelta) { + if (cuDelta.getKind() != IJavaElementDelta.CHANGED) { + return true; // add or remove + } + int flags = cuDelta.getFlags(); + if ((flags & IJavaElementDelta.F_CHILDREN) != 0) { + return true; + } + return (flags & (IJavaElementDelta.F_CONTENT | IJavaElementDelta.F_FINE_GRAINED)) == IJavaElementDelta.F_CONTENT; + } - if (element.getElementType() > IJavaElement.CLASS_FILE) - return null; + protected IJavaElementDelta findElement(IJavaElement unit, + IJavaElementDelta delta) { - IJavaElementDelta[] children= delta.getAffectedChildren(); - if (children == null || children.length == 0) - return null; + if (delta == null || unit == null) + return null; - for (int i= 0; i < children.length; i++) { - IJavaElementDelta d= findElement(unit, children[i]); - if (d != null) - return d; - } + IJavaElement element = delta.getElement(); - return null; + if (unit.equals(element)) { + if (isPossibleStructuralChange(delta)) { + return delta; } + return null; } - static class NoClassElement extends WorkbenchAdapter implements IAdaptable { - /* - * @see java.lang.Object#toString() - */ - public String toString() { - return PHPEditorMessages.getString("JavaOutlinePage.error.NoTopLevelType"); //$NON-NLS-1$ - } + if (element.getElementType() > IJavaElement.CLASS_FILE) + return null; - /* - * @see org.eclipse.core.runtime.IAdaptable#getAdapter(Class) - */ - public Object getAdapter(Class clas) { - if (clas == IWorkbenchAdapter.class) - return this; - return null; - } + IJavaElementDelta[] children = delta.getAffectedChildren(); + if (children == null || children.length == 0) + return null; + + for (int i = 0; i < children.length; i++) { + IJavaElementDelta d = findElement(unit, children[i]); + if (d != null) + return d; } - /** - * Content provider for the children of an ICompilationUnit or - * an IClassFile - * @see ITreeContentProvider - */ - class ChildrenProvider implements ITreeContentProvider { + return null; + } + } - private Object[] NO_CLASS= new Object[] {new NoClassElement()}; - private ElementChangedListener fListener; + static class NoClassElement extends WorkbenchAdapter implements IAdaptable { + /* + * @see java.lang.Object#toString() + */ + public String toString() { + return PHPEditorMessages + .getString("JavaOutlinePage.error.NoTopLevelType"); //$NON-NLS-1$ + } - protected boolean matches(IJavaElement element) { - if (element.getElementType() == IJavaElement.METHOD) { - String name= element.getElementName(); - return (name != null && name.indexOf('<') >= 0); - } - return false; - } + /* + * @see org.eclipse.core.runtime.IAdaptable#getAdapter(Class) + */ + public Object getAdapter(Class clas) { + if (clas == IWorkbenchAdapter.class) + return this; + return null; + } + } - protected IJavaElement[] filter(IJavaElement[] children) { - boolean initializers= false; - for (int i= 0; i < children.length; i++) { - if (matches(children[i])) { - initializers= true; - break; - } - } + /** + * Content provider for the children of an ICompilationUnit or an IClassFile + * + * @see ITreeContentProvider + */ + class ChildrenProvider implements ITreeContentProvider { - if (!initializers) - return children; + private Object[] NO_CLASS = new Object[] { new NoClassElement() }; - Vector v= new Vector(); - for (int i= 0; i < children.length; i++) { - if (matches(children[i])) - continue; - v.addElement(children[i]); - } + private ElementChangedListener fListener; - IJavaElement[] result= new IJavaElement[v.size()]; - v.copyInto(result); - return result; - } + protected boolean matches(IJavaElement element) { + if (element.getElementType() == IJavaElement.METHOD) { + String name = element.getElementName(); + return (name != null && name.indexOf('<') >= 0); + } + return false; + } - public Object[] getChildren(Object parent) { - if (parent instanceof IParent) { - IParent c= (IParent) parent; - try { - return filter(c.getChildren()); - } catch (JavaModelException x) { - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=38341 - // don't log NotExist exceptions as this is a valid case - // since we might have been posted and the element - // removed in the meantime. - if (PHPeclipsePlugin.isDebug() || !x.isDoesNotExist()) - PHPeclipsePlugin.log(x); - } - } - return NO_CHILDREN; + protected IJavaElement[] filter(IJavaElement[] children) { + boolean initializers = false; + for (int i = 0; i < children.length; i++) { + if (matches(children[i])) { + initializers = true; + break; } + } - public Object[] getElements(Object parent) { - if (fTopLevelTypeOnly) { - if (parent instanceof ICompilationUnit) { - try { - IType type= getMainType((ICompilationUnit) parent); - return type != null ? type.getChildren() : NO_CLASS; - } catch (JavaModelException e) { - PHPeclipsePlugin.log(e); - } - } -// else if (parent instanceof IClassFile) { -// try { -// IType type= getMainType((IClassFile) parent); -// return type != null ? type.getChildren() : NO_CLASS; -// } catch (JavaModelException e) { -// PHPeclipsePlugin.log(e); -// } -// } - } - return getChildren(parent); - } + if (!initializers) + return children; - public Object getParent(Object child) { - if (child instanceof IJavaElement) { - IJavaElement e= (IJavaElement) child; - return e.getParent(); - } - return null; - } + Vector v = new Vector(); + for (int i = 0; i < children.length; i++) { + if (matches(children[i])) + continue; + v.addElement(children[i]); + } - public boolean hasChildren(Object parent) { - if (parent instanceof IParent) { - IParent c= (IParent) parent; - try { - IJavaElement[] children= filter(c.getChildren()); - return (children != null && children.length > 0); - } catch (JavaModelException x) { - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=38341 - // don't log NotExist exceptions as this is a valid case - // since we might have been posted and the element - // removed in the meantime. - if (PHPeclipsePlugin.isDebug() || !x.isDoesNotExist()) - PHPeclipsePlugin.log(x); - } - } - return false; - } + IJavaElement[] result = new IJavaElement[v.size()]; + v.copyInto(result); + return result; + } - public boolean isDeleted(Object o) { - return false; + public Object[] getChildren(Object parent) { + if (parent instanceof IParent) { + IParent c = (IParent) parent; + try { + return filter(c.getChildren()); + } catch (JavaModelException x) { + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=38341 + // don't log NotExist exceptions as this is a valid case + // since we might have been posted and the element + // removed in the meantime. + if (PHPeclipsePlugin.isDebug() || !x.isDoesNotExist()) + PHPeclipsePlugin.log(x); } + } + return NO_CHILDREN; + } - public void dispose() { - if (fListener != null) { - JavaCore.removeElementChangedListener(fListener); - fListener= null; + public Object[] getElements(Object parent) { + if (fTopLevelTypeOnly) { + if (parent instanceof ICompilationUnit) { + try { + IType type = getMainType((ICompilationUnit) parent); + return type != null ? type.getChildren() : NO_CLASS; + } catch (JavaModelException e) { + PHPeclipsePlugin.log(e); } } + // else if (parent instanceof IClassFile) { + // try { + // IType type= getMainType((IClassFile) parent); + // return type != null ? type.getChildren() : NO_CLASS; + // } catch (JavaModelException e) { + // PHPeclipsePlugin.log(e); + // } + // } + } + return getChildren(parent); + } - /* - * @see IContentProvider#inputChanged(Viewer, Object, Object) - */ - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - boolean isCU= (newInput instanceof ICompilationUnit); - - if (isCU && fListener == null) { - fListener= new ElementChangedListener(); - JavaCore.addElementChangedListener(fListener); - } else if (!isCU && fListener != null) { - JavaCore.removeElementChangedListener(fListener); - fListener= null; - } + public Object getParent(Object child) { + if (child instanceof IJavaElement) { + IJavaElement e = (IJavaElement) child; + return e.getParent(); + } + return null; + } + + public boolean hasChildren(Object parent) { + if (parent instanceof IParent) { + IParent c = (IParent) parent; + try { + IJavaElement[] children = filter(c.getChildren()); + return (children != null && children.length > 0); + } catch (JavaModelException x) { + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=38341 + // don't log NotExist exceptions as this is a valid case + // since we might have been posted and the element + // removed in the meantime. + if (PHPeclipsePlugin.isDebug() || !x.isDoesNotExist()) + PHPeclipsePlugin.log(x); } } + return false; + } + public boolean isDeleted(Object o) { + return false; + } - class JavaOutlineViewer extends TreeViewer { + public void dispose() { + if (fListener != null) { + JavaCore.removeElementChangedListener(fListener); + fListener = null; + } + } - /** - * Indicates an item which has been reused. At the point of - * its reuse it has been expanded. This field is used to - * communicate between internalExpandToLevel and - * reuseTreeItem. - */ - private Item fReusedExpandedItem; - private boolean fReorderedMembers; - private boolean fForceFireSelectionChanged; + /* + * @see IContentProvider#inputChanged(Viewer, Object, Object) + */ + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + boolean isCU = (newInput instanceof ICompilationUnit); + + if (isCU && fListener == null) { + fListener = new ElementChangedListener(); + JavaCore.addElementChangedListener(fListener); + } else if (!isCU && fListener != null) { + JavaCore.removeElementChangedListener(fListener); + fListener = null; + } + } + } - public JavaOutlineViewer(Tree tree) { - super(tree); - setAutoExpandLevel(ALL_LEVELS); - setUseHashlookup(true); - } + class JavaOutlineViewer extends TreeViewer { - /** - * Investigates the given element change event and if affected - * incrementally updates the Java outline. - * - * @param delta the Java element delta used to reconcile the Java outline - */ - public void reconcile(IJavaElementDelta delta) { - fReorderedMembers= false; - fForceFireSelectionChanged= false; - if (getSorter() == null) { - if (fTopLevelTypeOnly - && delta.getElement() instanceof IType - && (delta.getKind() & IJavaElementDelta.ADDED) != 0) - { - refresh(true); - - } else { - Widget w= findItem(fInput); - if (w != null && !w.isDisposed()) - update(w, delta); - if (fForceFireSelectionChanged) - fireSelectionChanged(new SelectionChangedEvent(getSite().getSelectionProvider(), this.getSelection())); - if (fReorderedMembers) { - refresh(false); - fReorderedMembers= false; - } - } - } else { - // just for now - refresh(true); - } - } - - /* - * @see TreeViewer#internalExpandToLevel - */ - protected void internalExpandToLevel(Widget node, int level) { - if (node instanceof Item) { - Item i= (Item) node; - if (i.getData() instanceof IJavaElement) { - IJavaElement je= (IJavaElement) i.getData(); - if (je.getElementType() == IJavaElement.IMPORT_CONTAINER || isInnerType(je)) { - if (i != fReusedExpandedItem) { - setExpanded(i, false); - return; - } - } - } - } - super.internalExpandToLevel(node, level); - } + /** + * Indicates an item which has been reused. At the point of its reuse it + * has been expanded. This field is used to communicate between + * internalExpandToLevel and reuseTreeItem. + */ + private Item fReusedExpandedItem; - protected void reuseTreeItem(Item item, Object element) { + private boolean fReorderedMembers; - // remove children - Item[] c= getChildren(item); - if (c != null && c.length > 0) { + private boolean fForceFireSelectionChanged; - if (getExpanded(item)) - fReusedExpandedItem= item; + public JavaOutlineViewer(Tree tree) { + super(tree); + setAutoExpandLevel(ALL_LEVELS); + setUseHashlookup(true); + } - for (int k= 0; k < c.length; k++) { - if (c[k].getData() != null) - disassociate(c[k]); - c[k].dispose(); - } + /** + * Investigates the given element change event and if affected + * incrementally updates the Java outline. + * + * @param delta + * the Java element delta used to reconcile the Java outline + */ + public void reconcile(IJavaElementDelta delta) { + fReorderedMembers = false; + fForceFireSelectionChanged = false; + if (getSorter() == null) { + if (fTopLevelTypeOnly && delta.getElement() instanceof IType + && (delta.getKind() & IJavaElementDelta.ADDED) != 0) { + refresh(true); + + } else { + Widget w = findItem(fInput); + if (w != null && !w.isDisposed()) + update(w, delta); + if (fForceFireSelectionChanged) + fireSelectionChanged(new SelectionChangedEvent( + getSite().getSelectionProvider(), this + .getSelection())); + if (fReorderedMembers) { + refresh(false); + fReorderedMembers = false; } - - updateItem(item, element); - updatePlus(item, element); - internalExpandToLevel(item, ALL_LEVELS); - - fReusedExpandedItem= null; - fForceFireSelectionChanged= true; } + } else { + // just for now + refresh(true); + } + } - protected boolean mustUpdateParent(IJavaElementDelta delta, IJavaElement element) { - if (element instanceof IMethod) { - if ((delta.getKind() & IJavaElementDelta.ADDED) != 0) { - try { - return ((IMethod)element).isMainMethod(); - } catch (JavaModelException e) { - PHPeclipsePlugin.log(e.getStatus()); - } + /* + * @see TreeViewer#internalExpandToLevel + */ + protected void internalExpandToLevel(Widget node, int level) { + if (node instanceof Item) { + Item i = (Item) node; + if (i.getData() instanceof IJavaElement) { + IJavaElement je = (IJavaElement) i.getData(); + if (je.getElementType() == IJavaElement.IMPORT_CONTAINER + || isInnerType(je)) { + if (i != fReusedExpandedItem) { + setExpanded(i, false); + return; } - return "main".equals(element.getElementName()); //$NON-NLS-1$ } - return false; } + } + super.internalExpandToLevel(node, level); + } - /* - * @see org.eclipse.jface.viewers.AbstractTreeViewer#isExpandable(java.lang.Object) - */ - public boolean isExpandable(Object element) { - if (hasFilters()) { - return getFilteredChildren(element).length > 0; - } - return super.isExpandable(element); - } + protected void reuseTreeItem(Item item, Object element) { - protected ISourceRange getSourceRange(IJavaElement element) throws JavaModelException { - if (element instanceof ISourceReference) - return ((ISourceReference) element).getSourceRange(); - if (element instanceof IMember)// && !(element instanceof IInitializer)) - return ((IMember) element).getNameRange(); - return null; - } + // remove children + Item[] c = getChildren(item); + if (c != null && c.length > 0) { + + if (getExpanded(item)) + fReusedExpandedItem = item; - protected boolean overlaps(ISourceRange range, int start, int end) { - return start <= (range.getOffset() + range.getLength() - 1) && range.getOffset() <= end; + for (int k = 0; k < c.length; k++) { + if (c[k].getData() != null) + disassociate(c[k]); + c[k].dispose(); } + } - protected boolean filtered(IJavaElement parent, IJavaElement child) { + updateItem(item, element); + updatePlus(item, element); + internalExpandToLevel(item, ALL_LEVELS); - Object[] result= new Object[] { child }; - ViewerFilter[] filters= getFilters(); - for (int i= 0; i < filters.length; i++) { - result= filters[i].filter(this, parent, result); - if (result.length == 0) - return true; - } + fReusedExpandedItem = null; + fForceFireSelectionChanged = true; + } - return false; + protected boolean mustUpdateParent(IJavaElementDelta delta, + IJavaElement element) { + if (element instanceof IMethod) { + if ((delta.getKind() & IJavaElementDelta.ADDED) != 0) { + try { + return ((IMethod) element).isMainMethod(); + } catch (JavaModelException e) { + PHPeclipsePlugin.log(e.getStatus()); + } } + return "main".equals(element.getElementName()); //$NON-NLS-1$ + } + return false; + } - protected void update(Widget w, IJavaElementDelta delta) { + /* + * @see org.eclipse.jface.viewers.AbstractTreeViewer#isExpandable(java.lang.Object) + */ + public boolean isExpandable(Object element) { + if (hasFilters()) { + return getFilteredChildren(element).length > 0; + } + return super.isExpandable(element); + } - Item item; + protected ISourceRange getSourceRange(IJavaElement element) + throws JavaModelException { + if (element instanceof ISourceReference) + return ((ISourceReference) element).getSourceRange(); + if (element instanceof IMember)// && !(element instanceof + // IInitializer)) + return ((IMember) element).getNameRange(); + return null; + } - IJavaElement parent= delta.getElement(); - IJavaElementDelta[] affected= delta.getAffectedChildren(); - Item[] children= getChildren(w); + protected boolean overlaps(ISourceRange range, int start, int end) { + return start <= (range.getOffset() + range.getLength() - 1) + && range.getOffset() <= end; + } - boolean doUpdateParent= false; - boolean doUpdateParentsPlus= false; + protected boolean filtered(IJavaElement parent, IJavaElement child) { - Vector deletions= new Vector(); - Vector additions= new Vector(); + Object[] result = new Object[] { child }; + ViewerFilter[] filters = getFilters(); + for (int i = 0; i < filters.length; i++) { + result = filters[i].filter(this, parent, result); + if (result.length == 0) + return true; + } - for (int i= 0; i < affected.length; i++) { - IJavaElementDelta affectedDelta= affected[i]; - IJavaElement affectedElement= affectedDelta.getElement(); - int status= affected[i].getKind(); + return false; + } - // find tree item with affected element - int j; - for (j= 0; j < children.length; j++) - if (affectedElement.equals(children[j].getData())) - break; + protected void update(Widget w, IJavaElementDelta delta) { - if (j == children.length) { - // remove from collapsed parent - if ((status & IJavaElementDelta.REMOVED) != 0) { - doUpdateParentsPlus= true; - continue; - } - // addition - if ((status & IJavaElementDelta.CHANGED) != 0 && - (affectedDelta.getFlags() & IJavaElementDelta.F_MODIFIERS) != 0 && - !filtered(parent, affectedElement)) - { - additions.addElement(affectedDelta); - } - continue; - } + Item item; - item= children[j]; + IJavaElement parent = delta.getElement(); + IJavaElementDelta[] affected = delta.getAffectedChildren(); + Item[] children = getChildren(w); - // removed - if ((status & IJavaElementDelta.REMOVED) != 0) { - deletions.addElement(item); - doUpdateParent= doUpdateParent || mustUpdateParent(affectedDelta, affectedElement); - - // changed - } else if ((status & IJavaElementDelta.CHANGED) != 0) { - int change= affectedDelta.getFlags(); - doUpdateParent= doUpdateParent || mustUpdateParent(affectedDelta, affectedElement); - - if ((change & IJavaElementDelta.F_MODIFIERS) != 0) { - if (filtered(parent, affectedElement)) - deletions.addElement(item); - else - updateItem(item, affectedElement); - } + boolean doUpdateParent = false; + boolean doUpdateParentsPlus = false; - if ((change & IJavaElementDelta.F_CONTENT) != 0) - updateItem(item, affectedElement); + Vector deletions = new Vector(); + Vector additions = new Vector(); - if ((change & IJavaElementDelta.F_CHILDREN) != 0) - update(item, affectedDelta); + for (int i = 0; i < affected.length; i++) { + IJavaElementDelta affectedDelta = affected[i]; + IJavaElement affectedElement = affectedDelta.getElement(); + int status = affected[i].getKind(); - if ((change & IJavaElementDelta.F_REORDER) != 0) - fReorderedMembers= true; - } - } + // find tree item with affected element + int j; + for (j = 0; j < children.length; j++) + if (affectedElement.equals(children[j].getData())) + break; - // find all elements to add - IJavaElementDelta[] add= delta.getAddedChildren(); - if (additions.size() > 0) { - IJavaElementDelta[] tmp= new IJavaElementDelta[add.length + additions.size()]; - System.arraycopy(add, 0, tmp, 0, add.length); - for (int i= 0; i < additions.size(); i++) - tmp[i + add.length]= (IJavaElementDelta) additions.elementAt(i); - add= tmp; + if (j == children.length) { + // remove from collapsed parent + if ((status & IJavaElementDelta.REMOVED) != 0) { + doUpdateParentsPlus = true; + continue; + } + // addition + if ((status & IJavaElementDelta.CHANGED) != 0 + && (affectedDelta.getFlags() & IJavaElementDelta.F_MODIFIERS) != 0 + && !filtered(parent, affectedElement)) { + additions.addElement(affectedDelta); } + continue; + } - // add at the right position - go2: for (int i= 0; i < add.length; i++) { + item = children[j]; - try { + // removed + if ((status & IJavaElementDelta.REMOVED) != 0) { + deletions.addElement(item); + doUpdateParent = doUpdateParent + || mustUpdateParent(affectedDelta, affectedElement); - IJavaElement e= add[i].getElement(); - if (filtered(parent, e)) - continue go2; + // changed + } else if ((status & IJavaElementDelta.CHANGED) != 0) { + int change = affectedDelta.getFlags(); + doUpdateParent = doUpdateParent + || mustUpdateParent(affectedDelta, affectedElement); - doUpdateParent= doUpdateParent || mustUpdateParent(add[i], e); - ISourceRange rng= getSourceRange(e); - int start= rng.getOffset(); - int end= start + rng.getLength() - 1; - int nameOffset= Integer.MAX_VALUE; - if (e instanceof IField) { - ISourceRange nameRange= ((IField) e).getNameRange(); - if (nameRange != null) - nameOffset= nameRange.getOffset(); - } + if ((change & IJavaElementDelta.F_MODIFIERS) != 0) { + if (filtered(parent, affectedElement)) + deletions.addElement(item); + else + updateItem(item, affectedElement); + } - Item last= null; - item= null; - children= getChildren(w); + if ((change & IJavaElementDelta.F_CONTENT) != 0) + updateItem(item, affectedElement); - for (int j= 0; j < children.length; j++) { - item= children[j]; - IJavaElement r= (IJavaElement) item.getData(); + if ((change & IJavaElementDelta.F_CHILDREN) != 0) + update(item, affectedDelta); - if (r == null) { - // parent node collapsed and not be opened before -> do nothing - continue go2; - } + if ((change & IJavaElementDelta.F_REORDER) != 0) + fReorderedMembers = true; + } + } + // find all elements to add + IJavaElementDelta[] add = delta.getAddedChildren(); + if (additions.size() > 0) { + IJavaElementDelta[] tmp = new IJavaElementDelta[add.length + + additions.size()]; + System.arraycopy(add, 0, tmp, 0, add.length); + for (int i = 0; i < additions.size(); i++) + tmp[i + add.length] = (IJavaElementDelta) additions + .elementAt(i); + add = tmp; + } - try { - rng= getSourceRange(r); - - // multi-field declarations always start at - // the same offset. They also have the same - // end offset if the field sequence is terminated - // with a semicolon. If not, the source range - // ends behind the identifier / initializer - // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=51851 - boolean multiFieldDeclaration= - r.getElementType() == IJavaElement.FIELD - && e.getElementType() == IJavaElement.FIELD - && rng.getOffset() == start; - - // elements are inserted by occurrence - // however, multi-field declarations have - // equal source ranges offsets, therefore we - // compare name-range offsets. - boolean multiFieldOrderBefore= false; - if (multiFieldDeclaration) { - if (r instanceof IField) { - ISourceRange nameRange= ((IField) r).getNameRange(); - if (nameRange != null) { - if (nameRange.getOffset() > nameOffset) - multiFieldOrderBefore= true; - } - } - } + // add at the right position + go2: for (int i = 0; i < add.length; i++) { + + try { + + IJavaElement e = add[i].getElement(); + if (filtered(parent, e)) + continue go2; + + doUpdateParent = doUpdateParent + || mustUpdateParent(add[i], e); + ISourceRange rng = getSourceRange(e); + int start = rng.getOffset(); + int end = start + rng.getLength() - 1; + int nameOffset = Integer.MAX_VALUE; + if (e instanceof IField) { + ISourceRange nameRange = ((IField) e).getNameRange(); + if (nameRange != null) + nameOffset = nameRange.getOffset(); + } - if (!multiFieldDeclaration && overlaps(rng, start, end)) { + Item last = null; + item = null; + children = getChildren(w); - // be tolerant if the delta is not correct, or if - // the tree has been updated other than by a delta - reuseTreeItem(item, e); - continue go2; + for (int j = 0; j < children.length; j++) { + item = children[j]; + IJavaElement r = (IJavaElement) item.getData(); - } else if (multiFieldOrderBefore || rng.getOffset() > start) { + if (r == null) { + // parent node collapsed and not be opened before -> + // do nothing + continue go2; + } - if (last != null && deletions.contains(last)) { - // reuse item - deletions.removeElement(last); - reuseTreeItem(last, e); - } else { - // nothing to reuse - createTreeItem(w, e, j); - } - continue go2; + try { + rng = getSourceRange(r); + + // multi-field declarations always start at + // the same offset. They also have the same + // end offset if the field sequence is terminated + // with a semicolon. If not, the source range + // ends behind the identifier / initializer + // see + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=51851 + boolean multiFieldDeclaration = r.getElementType() == IJavaElement.FIELD + && e.getElementType() == IJavaElement.FIELD + && rng.getOffset() == start; + + // elements are inserted by occurrence + // however, multi-field declarations have + // equal source ranges offsets, therefore we + // compare name-range offsets. + boolean multiFieldOrderBefore = false; + if (multiFieldDeclaration) { + if (r instanceof IField) { + ISourceRange nameRange = ((IField) r) + .getNameRange(); + if (nameRange != null) { + if (nameRange.getOffset() > nameOffset) + multiFieldOrderBefore = true; } - - } catch (JavaModelException x) { - // stumbled over deleted element } - - last= item; } - // add at the end of the list - if (last != null && deletions.contains(last)) { - // reuse item - deletions.removeElement(last); - reuseTreeItem(last, e); - } else { - // nothing to reuse - createTreeItem(w, e, -1); + if (!multiFieldDeclaration + && overlaps(rng, start, end)) { + + // be tolerant if the delta is not correct, or + // if + // the tree has been updated other than by a + // delta + reuseTreeItem(item, e); + continue go2; + + } else if (multiFieldOrderBefore + || rng.getOffset() > start) { + + if (last != null && deletions.contains(last)) { + // reuse item + deletions.removeElement(last); + reuseTreeItem(last, e); + } else { + // nothing to reuse + createTreeItem(w, e, j); + } + continue go2; } } catch (JavaModelException x) { - // the element to be added is not present -> don't add it + // stumbled over deleted element } - } + last = item; + } - // remove items which haven't been reused - Enumeration e= deletions.elements(); - while (e.hasMoreElements()) { - item= (Item) e.nextElement(); - disassociate(item); - item.dispose(); + // add at the end of the list + if (last != null && deletions.contains(last)) { + // reuse item + deletions.removeElement(last); + reuseTreeItem(last, e); + } else { + // nothing to reuse + createTreeItem(w, e, -1); } - if (doUpdateParent) - updateItem(w, delta.getElement()); - if (!doUpdateParent && doUpdateParentsPlus && w instanceof Item) - updatePlus((Item)w, delta.getElement()); + } catch (JavaModelException x) { + // the element to be added is not present -> don't add it } + } + // remove items which haven't been reused + Enumeration e = deletions.elements(); + while (e.hasMoreElements()) { + item = (Item) e.nextElement(); + disassociate(item); + item.dispose(); + } + if (doUpdateParent) + updateItem(w, delta.getElement()); + if (!doUpdateParent && doUpdateParentsPlus && w instanceof Item) + updatePlus((Item) w, delta.getElement()); + } - /* - * @see ContentViewer#handleLabelProviderChanged(LabelProviderChangedEvent) - */ - protected void handleLabelProviderChanged(LabelProviderChangedEvent event) { - Object input= getInput(); - if (event instanceof ProblemsLabelChangedEvent) { - ProblemsLabelChangedEvent e= (ProblemsLabelChangedEvent) event; - if (e.isMarkerChange() && input instanceof ICompilationUnit) { - return; // marker changes can be ignored - } - } - // look if the underlying resource changed - Object[] changed= event.getElements(); - if (changed != null) { - IResource resource= getUnderlyingResource(); - if (resource != null) { - for (int i= 0; i < changed.length; i++) { - if (changed[i] != null && changed[i].equals(resource)) { - // change event to a full refresh - event= new LabelProviderChangedEvent((IBaseLabelProvider) event.getSource()); - break; - } - } - } - } - super.handleLabelProviderChanged(event); + /* + * @see ContentViewer#handleLabelProviderChanged(LabelProviderChangedEvent) + */ + protected void handleLabelProviderChanged( + LabelProviderChangedEvent event) { + Object input = getInput(); + if (event instanceof ProblemsLabelChangedEvent) { + ProblemsLabelChangedEvent e = (ProblemsLabelChangedEvent) event; + if (e.isMarkerChange() && input instanceof ICompilationUnit) { + return; // marker changes can be ignored } - - private IResource getUnderlyingResource() { - Object input= getInput(); - if (input instanceof ICompilationUnit) { - ICompilationUnit cu= (ICompilationUnit) input; - cu= JavaModelUtil.toOriginal(cu); - return cu.getResource(); + } + // look if the underlying resource changed + Object[] changed = event.getElements(); + if (changed != null) { + IResource resource = getUnderlyingResource(); + if (resource != null) { + for (int i = 0; i < changed.length; i++) { + if (changed[i] != null && changed[i].equals(resource)) { + // change event to a full refresh + event = new LabelProviderChangedEvent( + (IBaseLabelProvider) event.getSource()); + break; + } } -// else if (input instanceof IClassFile) { -// return ((IClassFile) input).getResource(); -// } - return null; } - - } + super.handleLabelProviderChanged(event); + } - class LexicalSortingAction extends Action { - - private JavaElementSorter fSorter= new JavaElementSorter(); + private IResource getUnderlyingResource() { + Object input = getInput(); + if (input instanceof ICompilationUnit) { + ICompilationUnit cu = (ICompilationUnit) input; + cu = JavaModelUtil.toOriginal(cu); + return cu.getResource(); + } + // else if (input instanceof IClassFile) { + // return ((IClassFile) input).getResource(); + // } + return null; + } - public LexicalSortingAction() { - super(); - PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.LEXICAL_SORTING_OUTLINE_ACTION); - setText(PHPEditorMessages.getString("JavaOutlinePage.Sort.label")); //$NON-NLS-1$ - PHPUiImages.setLocalImageDescriptors(this, "alphab_sort_co.gif"); //$NON-NLS-1$ - setToolTipText(PHPEditorMessages.getString("JavaOutlinePage.Sort.tooltip")); //$NON-NLS-1$ - setDescription(PHPEditorMessages.getString("JavaOutlinePage.Sort.description")); //$NON-NLS-1$ + } - boolean checked= PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean("LexicalSortingAction.isChecked"); //$NON-NLS-1$ - valueChanged(checked, false); - } + class LexicalSortingAction extends Action { + + private JavaElementSorter fSorter = new JavaElementSorter(); + + public LexicalSortingAction() { + super(); + PlatformUI.getWorkbench().getHelpSystem().setHelp(this, + IJavaHelpContextIds.LEXICAL_SORTING_OUTLINE_ACTION); + setText(PHPEditorMessages.getString("JavaOutlinePage.Sort.label")); //$NON-NLS-1$ + PHPUiImages.setLocalImageDescriptors(this, "alphab_sort_co.gif"); //$NON-NLS-1$ + setToolTipText(PHPEditorMessages + .getString("JavaOutlinePage.Sort.tooltip")); //$NON-NLS-1$ + setDescription(PHPEditorMessages + .getString("JavaOutlinePage.Sort.description")); //$NON-NLS-1$ + + boolean checked = PHPeclipsePlugin.getDefault() + .getPreferenceStore().getBoolean( + "LexicalSortingAction.isChecked"); //$NON-NLS-1$ + valueChanged(checked, false); + } - public void run() { - valueChanged(isChecked(), true); - } + public void run() { + valueChanged(isChecked(), true); + } - private void valueChanged(final boolean on, boolean store) { - setChecked(on); - BusyIndicator.showWhile(fOutlineViewer.getControl().getDisplay(), new Runnable() { + private void valueChanged(final boolean on, boolean store) { + setChecked(on); + BusyIndicator.showWhile(fOutlineViewer.getControl().getDisplay(), + new Runnable() { public void run() { - fOutlineViewer.setSorter(on ? fSorter : null); } + fOutlineViewer.setSorter(on ? fSorter : null); + } }); - if (store) - PHPeclipsePlugin.getDefault().getPreferenceStore().setValue("LexicalSortingAction.isChecked", on); //$NON-NLS-1$ - } - } + if (store) + PHPeclipsePlugin.getDefault().getPreferenceStore().setValue( + "LexicalSortingAction.isChecked", on); //$NON-NLS-1$ + } + } - class ClassOnlyAction extends Action { + class ClassOnlyAction extends Action { + + public ClassOnlyAction() { + super(); + PlatformUI.getWorkbench().getHelpSystem().setHelp(this, + IJavaHelpContextIds.GO_INTO_TOP_LEVEL_TYPE_ACTION); + setText(PHPEditorMessages + .getString("JavaOutlinePage.GoIntoTopLevelType.label")); //$NON-NLS-1$ + setToolTipText(PHPEditorMessages + .getString("JavaOutlinePage.GoIntoTopLevelType.tooltip")); //$NON-NLS-1$ + setDescription(PHPEditorMessages + .getString("JavaOutlinePage.GoIntoTopLevelType.description")); //$NON-NLS-1$ + PHPUiImages.setLocalImageDescriptors(this, + "gointo_toplevel_type.gif"); //$NON-NLS-1$ + + IPreferenceStore preferenceStore = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + boolean showclass = preferenceStore + .getBoolean("GoIntoTopLevelTypeAction.isChecked"); //$NON-NLS-1$ + setTopLevelTypeOnly(showclass); + } - public ClassOnlyAction() { - super(); - PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.GO_INTO_TOP_LEVEL_TYPE_ACTION); - setText(PHPEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.label")); //$NON-NLS-1$ - setToolTipText(PHPEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.tooltip")); //$NON-NLS-1$ - setDescription(PHPEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.description")); //$NON-NLS-1$ - PHPUiImages.setLocalImageDescriptors(this, "gointo_toplevel_type.gif"); //$NON-NLS-1$ + /* + * @see org.eclipse.jface.action.Action#run() + */ + public void run() { + setTopLevelTypeOnly(!fTopLevelTypeOnly); + } - IPreferenceStore preferenceStore= PHPeclipsePlugin.getDefault().getPreferenceStore(); - boolean showclass= preferenceStore.getBoolean("GoIntoTopLevelTypeAction.isChecked"); //$NON-NLS-1$ - setTopLevelTypeOnly(showclass); - } + private void setTopLevelTypeOnly(boolean show) { + fTopLevelTypeOnly = show; + setChecked(show); + fOutlineViewer.refresh(false); - /* - * @see org.eclipse.jface.action.Action#run() - */ - public void run() { - setTopLevelTypeOnly(!fTopLevelTypeOnly); - } + IPreferenceStore preferenceStore = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + preferenceStore + .setValue("GoIntoTopLevelTypeAction.isChecked", show); //$NON-NLS-1$ + } + } - private void setTopLevelTypeOnly(boolean show) { - fTopLevelTypeOnly= show; - setChecked(show); - fOutlineViewer.refresh(false); + /** + * This action toggles whether this Java Outline page links its selection to + * the active editor. + * + * @since 3.0 + */ + public class ToggleLinkingAction extends AbstractToggleLinkingAction { - IPreferenceStore preferenceStore= PHPeclipsePlugin.getDefault().getPreferenceStore(); - preferenceStore.setValue("GoIntoTopLevelTypeAction.isChecked", show); //$NON-NLS-1$ - } - } + JavaOutlinePage fJavaOutlinePage; /** - * This action toggles whether this Java Outline page links - * its selection to the active editor. - * - * @since 3.0 + * Constructs a new action. + * + * @param outlinePage + * the Java outline page */ - public class ToggleLinkingAction extends AbstractToggleLinkingAction { - - JavaOutlinePage fJavaOutlinePage; - - /** - * Constructs a new action. - * - * @param outlinePage the Java outline page - */ - public ToggleLinkingAction(JavaOutlinePage outlinePage) { - boolean isLinkingEnabled= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE); - setChecked(isLinkingEnabled); - fJavaOutlinePage= outlinePage; - } - - /** - * Runs the action. - */ - public void run() { - PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, isChecked()); - if (isChecked() && fEditor != null) - fEditor.synchronizeOutlinePage(fEditor.computeHighlightRangeSourceReference(), false); - } + public ToggleLinkingAction(JavaOutlinePage outlinePage) { + boolean isLinkingEnabled = PreferenceConstants + .getPreferenceStore() + .getBoolean( + PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE); + setChecked(isLinkingEnabled); + fJavaOutlinePage = outlinePage; + } + /** + * Runs the action. + */ + public void run() { + PreferenceConstants.getPreferenceStore().setValue( + PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, + isChecked()); + if (isChecked() && fEditor != null) + fEditor.synchronizeOutlinePage(fEditor + .computeHighlightRangeSourceReference(), false); } + } /** A flag to show contents of top level type only */ private boolean fTopLevelTypeOnly; private IJavaElement fInput; + private String fContextMenuID; + private Menu fMenu; + private JavaOutlineViewer fOutlineViewer; + private PHPEditor fEditor; private MemberFilterActionGroup fMemberFilterActionGroup; - private ListenerList fSelectionChangedListeners= new ListenerList(); - private ListenerList fPostSelectionChangedListeners= new ListenerList(); - private Hashtable fActions= new Hashtable(); + private ListenerList fSelectionChangedListeners = new ListenerList(); + + private ListenerList fPostSelectionChangedListeners = new ListenerList(); + + private Hashtable fActions = new Hashtable(); private TogglePresentationAction fTogglePresentation; + private GotoAnnotationAction fPreviousAnnotation; + private GotoAnnotationAction fNextAnnotation; + private TextEditorAction fShowJavadoc; + private IAction fUndo; + private IAction fRedo; private ToggleLinkingAction fToggleLinkingAction; @@ -864,8 +915,10 @@ public class JavaOutlinePage extends Page implements IContentOutlinePage, IAdapt private CompositeActionGroup fActionGroups; private IPropertyChangeListener fPropertyChangeListener; + /** * Custom filter action group. + * * @since 3.0 */ private CustomFiltersActionGroup fCustomFiltersActionGroup; @@ -875,66 +928,69 @@ public class JavaOutlinePage extends Page implements IContentOutlinePage, IAdapt Assert.isNotNull(editor); - fContextMenuID= contextMenuID; - fEditor= editor; - fTogglePresentation= new TogglePresentationAction(); - fPreviousAnnotation= new GotoAnnotationAction("PreviousAnnotation.", false); //$NON-NLS-1$ - fNextAnnotation= new GotoAnnotationAction("NextAnnotation.", true); //$NON-NLS-1$ - fShowJavadoc= (TextEditorAction) fEditor.getAction("ShowJavaDoc"); //$NON-NLS-1$ - fUndo= fEditor.getAction(ITextEditorActionConstants.UNDO); - fRedo= fEditor.getAction(ITextEditorActionConstants.REDO); + fContextMenuID = contextMenuID; + fEditor = editor; + fTogglePresentation = new TogglePresentationAction(); + fPreviousAnnotation = new GotoAnnotationAction( + "PreviousAnnotation.", false); //$NON-NLS-1$ + fNextAnnotation = new GotoAnnotationAction("NextAnnotation.", true); //$NON-NLS-1$ + fShowJavadoc = (TextEditorAction) fEditor.getAction("ShowJavaDoc"); //$NON-NLS-1$ + fUndo = fEditor.getAction(ITextEditorActionConstants.UNDO); + fRedo = fEditor.getAction(ITextEditorActionConstants.REDO); fTogglePresentation.setEditor(editor); fPreviousAnnotation.setEditor(editor); fNextAnnotation.setEditor(editor); - fPropertyChangeListener= new IPropertyChangeListener() { + fPropertyChangeListener = new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { doPropertyChange(event); } }; - PHPeclipsePlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener); + PHPeclipsePlugin.getDefault().getPreferenceStore() + .addPropertyChangeListener(fPropertyChangeListener); } /** - * Returns the primary type of a compilation unit (has the same - * name as the compilation unit). - * - * @param compilationUnit the compilation unit + * Returns the primary type of a compilation unit (has the same name as the + * compilation unit). + * + * @param compilationUnit + * the compilation unit * @return returns the primary type of the compilation unit, or - * null if is does not have one + * null if is does not have one */ protected IType getMainType(ICompilationUnit compilationUnit) { if (compilationUnit == null) return null; - String name= compilationUnit.getElementName(); - int index= name.indexOf('.'); + String name = compilationUnit.getElementName(); + int index = name.indexOf('.'); if (index != -1) - name= name.substring(0, index); - IType type= compilationUnit.getType(name); + name = name.substring(0, index); + IType type = compilationUnit.getType(name); return type.exists() ? type : null; } /** * Returns the primary type of a class file. - * - * @param classFile the class file + * + * @param classFile + * the class file * @return returns the primary type of the class file, or null - * if is does not have one + * if is does not have one */ -// protected IType getMainType(IClassFile classFile) { -// try { -// IType type= classFile.getType(); -// return type != null && type.exists() ? type : null; -// } catch (JavaModelException e) { -// return null; -// } -// } - - /* (non-Javadoc) - * Method declared on Page + // protected IType getMainType(IClassFile classFile) { + // try { + // IType type= classFile.getType(); + // return type != null && type.exists() ? type : null; + // } catch (JavaModelException e) { + // return null; + // } + // } + /* + * (non-Javadoc) Method declared on Page */ public void init(IPageSite pageSite) { super.init(pageSite); @@ -942,7 +998,8 @@ public class JavaOutlinePage extends Page implements IContentOutlinePage, IAdapt private void doPropertyChange(PropertyChangeEvent event) { if (fOutlineViewer != null) { - if (MembersOrderPreferenceCache.isMemberOrderProperty(event.getProperty())) { + if (MembersOrderPreferenceCache.isMemberOrderProperty(event + .getProperty())) { fOutlineViewer.refresh(false); } } @@ -961,7 +1018,8 @@ public class JavaOutlinePage extends Page implements IContentOutlinePage, IAdapt /* * @see ISelectionProvider#removeSelectionChangedListener(ISelectionChangedListener) */ - public void removeSelectionChangedListener(ISelectionChangedListener listener) { + public void removeSelectionChangedListener( + ISelectionChangedListener listener) { if (fOutlineViewer != null) fOutlineViewer.removeSelectionChangedListener(listener); else @@ -988,7 +1046,8 @@ public class JavaOutlinePage extends Page implements IContentOutlinePage, IAdapt /* * @see org.eclipse.jface.text.IPostSelectionProvider#addPostSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) */ - public void addPostSelectionChangedListener(ISelectionChangedListener listener) { + public void addPostSelectionChangedListener( + ISelectionChangedListener listener) { if (fOutlineViewer != null) fOutlineViewer.addPostSelectionChangedListener(listener); else @@ -998,7 +1057,8 @@ public class JavaOutlinePage extends Page implements IContentOutlinePage, IAdapt /* * @see org.eclipse.jface.text.IPostSelectionProvider#removePostSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) */ - public void removePostSelectionChangedListener(ISelectionChangedListener listener) { + public void removePostSelectionChangedListener( + ISelectionChangedListener listener) { if (fOutlineViewer != null) fOutlineViewer.removePostSelectionChangedListener(listener); else @@ -1007,19 +1067,21 @@ public class JavaOutlinePage extends Page implements IContentOutlinePage, IAdapt private void registerToolbarActions(IActionBars actionBars) { - IToolBarManager toolBarManager= actionBars.getToolBarManager(); + IToolBarManager toolBarManager = actionBars.getToolBarManager(); if (toolBarManager != null) { toolBarManager.add(new LexicalSortingAction()); - fMemberFilterActionGroup= new MemberFilterActionGroup(fOutlineViewer, "net.sourceforge.phpeclipse.JavaOutlinePage"); //$NON-NLS-1$ + fMemberFilterActionGroup = new MemberFilterActionGroup( + fOutlineViewer, + "net.sourceforge.phpeclipse.JavaOutlinePage"); //$NON-NLS-1$ fMemberFilterActionGroup.contributeToToolBar(toolBarManager); fCustomFiltersActionGroup.fillActionBars(actionBars); - IMenuManager menu= actionBars.getMenuManager(); + IMenuManager menu = actionBars.getMenuManager(); menu.add(new Separator("EndFilterGroup")); //$NON-NLS-1$ - fToggleLinkingAction= new ToggleLinkingAction(this); + fToggleLinkingAction = new ToggleLinkingAction(this); menu.add(new ClassOnlyAction()); menu.add(fToggleLinkingAction); } @@ -1030,74 +1092,91 @@ public class JavaOutlinePage extends Page implements IContentOutlinePage, IAdapt */ public void createControl(Composite parent) { - Tree tree= new Tree(parent, SWT.MULTI); + Tree tree = new Tree(parent, SWT.MULTI); - AppearanceAwareLabelProvider lprovider= new AppearanceAwareLabelProvider( - AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.F_APP_TYPE_SIGNATURE, - AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS - ); + AppearanceAwareLabelProvider lprovider = new AppearanceAwareLabelProvider( + AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS + | JavaElementLabels.F_APP_TYPE_SIGNATURE, + AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS); - fOutlineViewer= new JavaOutlineViewer(tree); + fOutlineViewer = new JavaOutlineViewer(tree); initDragAndDrop(); fOutlineViewer.setContentProvider(new ChildrenProvider()); - fOutlineViewer.setLabelProvider(new DecoratingJavaLabelProvider(lprovider)); + fOutlineViewer.setLabelProvider(new DecoratingJavaLabelProvider( + lprovider)); - Object[] listeners= fSelectionChangedListeners.getListeners(); - for (int i= 0; i < listeners.length; i++) { + Object[] listeners = fSelectionChangedListeners.getListeners(); + for (int i = 0; i < listeners.length; i++) { fSelectionChangedListeners.remove(listeners[i]); - fOutlineViewer.addSelectionChangedListener((ISelectionChangedListener) listeners[i]); + fOutlineViewer + .addSelectionChangedListener((ISelectionChangedListener) listeners[i]); } - listeners= fPostSelectionChangedListeners.getListeners(); - for (int i= 0; i < listeners.length; i++) { + listeners = fPostSelectionChangedListeners.getListeners(); + for (int i = 0; i < listeners.length; i++) { fPostSelectionChangedListeners.remove(listeners[i]); - fOutlineViewer.addPostSelectionChangedListener((ISelectionChangedListener) listeners[i]); + fOutlineViewer + .addPostSelectionChangedListener((ISelectionChangedListener) listeners[i]); } - MenuManager manager= new MenuManager(fContextMenuID, fContextMenuID); + MenuManager manager = new MenuManager(fContextMenuID, fContextMenuID); manager.setRemoveAllWhenShown(true); manager.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager m) { contextMenuAboutToShow(m); } }); - fMenu= manager.createContextMenu(tree); + fMenu = manager.createContextMenu(tree); tree.setMenu(fMenu); - IPageSite site= getSite(); - site.registerContextMenu(PHPeclipsePlugin.getPluginId() + ".outline", manager, fOutlineViewer); //$NON-NLS-1$ + IPageSite site = getSite(); + site + .registerContextMenu(PHPeclipsePlugin.getPluginId() + + ".outline", manager, fOutlineViewer); //$NON-NLS-1$ site.setSelectionProvider(fOutlineViewer); - // we must create the groups after we have set the selection provider to the site - fActionGroups= new CompositeActionGroup(new ActionGroup[] { -// new OpenViewActionGroup(this), -// new CCPActionGroup(this), - new GenerateActionGroup(this)}); -// new RefactorActionGroup(this), -// new JavaSearchActionGroup(this)}); + // we must create the groups after we have set the selection provider to + // the site + fActionGroups = new CompositeActionGroup(new ActionGroup[] { + // new OpenViewActionGroup(this), + // new CCPActionGroup(this), + new GenerateActionGroup(this) }); + // new RefactorActionGroup(this), + // new JavaSearchActionGroup(this)}); // register global actions - IActionBars bars= site.getActionBars(); + IActionBars bars = site.getActionBars(); bars.setGlobalActionHandler(ITextEditorActionConstants.UNDO, fUndo); bars.setGlobalActionHandler(ITextEditorActionConstants.REDO, fRedo); - bars.setGlobalActionHandler(ActionFactory.PREVIOUS.getId(), fPreviousAnnotation); - bars.setGlobalActionHandler(ActionFactory.NEXT.getId(), fNextAnnotation); - bars.setGlobalActionHandler(PHPdtActionConstants.SHOW_JAVA_DOC, fShowJavadoc); - bars.setGlobalActionHandler(ITextEditorActionDefinitionIds.TOGGLE_SHOW_SELECTED_ELEMENT_ONLY, fTogglePresentation); - bars.setGlobalActionHandler(ITextEditorActionDefinitionIds.GOTO_NEXT_ANNOTATION, fNextAnnotation); - bars.setGlobalActionHandler(ITextEditorActionDefinitionIds.GOTO_PREVIOUS_ANNOTATION, fPreviousAnnotation); - + bars.setGlobalActionHandler(ActionFactory.PREVIOUS.getId(), + fPreviousAnnotation); + bars + .setGlobalActionHandler(ActionFactory.NEXT.getId(), + fNextAnnotation); + bars.setGlobalActionHandler(PHPdtActionConstants.SHOW_JAVA_DOC, + fShowJavadoc); + bars + .setGlobalActionHandler( + ITextEditorActionDefinitionIds.TOGGLE_SHOW_SELECTED_ELEMENT_ONLY, + fTogglePresentation); + bars.setGlobalActionHandler( + ITextEditorActionDefinitionIds.GOTO_NEXT_ANNOTATION, + fNextAnnotation); + bars.setGlobalActionHandler( + ITextEditorActionDefinitionIds.GOTO_PREVIOUS_ANNOTATION, + fPreviousAnnotation); fActionGroups.fillActionBars(bars); - IStatusLineManager statusLineManager= bars.getStatusLineManager(); + IStatusLineManager statusLineManager = bars.getStatusLineManager(); if (statusLineManager != null) { - StatusBarUpdater updater= new StatusBarUpdater(statusLineManager); + StatusBarUpdater updater = new StatusBarUpdater(statusLineManager); fOutlineViewer.addPostSelectionChangedListener(updater); } // Custom filter group - fCustomFiltersActionGroup= new CustomFiltersActionGroup("net.sourceforge.phpdt.ui.JavaOutlinePage", fOutlineViewer); //$NON-NLS-1$ + fCustomFiltersActionGroup = new CustomFiltersActionGroup( + "net.sourceforge.phpdt.ui.JavaOutlinePage", fOutlineViewer); //$NON-NLS-1$ registerToolbarActions(bars); @@ -1111,32 +1190,32 @@ public class JavaOutlinePage extends Page implements IContentOutlinePage, IAdapt if (fMemberFilterActionGroup != null) { fMemberFilterActionGroup.dispose(); - fMemberFilterActionGroup= null; + fMemberFilterActionGroup = null; } if (fCustomFiltersActionGroup != null) { fCustomFiltersActionGroup.dispose(); - fCustomFiltersActionGroup= null; + fCustomFiltersActionGroup = null; } - fEditor.outlinePageClosed(); - fEditor= null; + fEditor = null; fSelectionChangedListeners.clear(); - fSelectionChangedListeners= null; + fSelectionChangedListeners = null; fPostSelectionChangedListeners.clear(); - fPostSelectionChangedListeners= null; + fPostSelectionChangedListeners = null; if (fPropertyChangeListener != null) { - PHPeclipsePlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener); - fPropertyChangeListener= null; + PHPeclipsePlugin.getDefault().getPreferenceStore() + .removePropertyChangeListener(fPropertyChangeListener); + fPropertyChangeListener = null; } if (fMenu != null && !fMenu.isDisposed()) { fMenu.dispose(); - fMenu= null; + fMenu = null; } if (fActionGroups != null) @@ -1146,7 +1225,7 @@ public class JavaOutlinePage extends Page implements IContentOutlinePage, IAdapt fPreviousAnnotation.setEditor(null); fNextAnnotation.setEditor(null); - fOutlineViewer= null; + fOutlineViewer = null; super.dispose(); } @@ -1158,7 +1237,7 @@ public class JavaOutlinePage extends Page implements IContentOutlinePage, IAdapt } public void setInput(IJavaElement inputElement) { - fInput= inputElement; + fInput = inputElement; if (fOutlineViewer != null) fOutlineViewer.setInput(fInput); } @@ -1166,12 +1245,13 @@ public class JavaOutlinePage extends Page implements IContentOutlinePage, IAdapt public void select(ISourceReference reference) { if (fOutlineViewer != null) { - ISelection s= fOutlineViewer.getSelection(); + ISelection s = fOutlineViewer.getSelection(); if (s instanceof IStructuredSelection) { - IStructuredSelection ss= (IStructuredSelection) s; - List elements= ss.toList(); + IStructuredSelection ss = (IStructuredSelection) s; + List elements = ss.toList(); if (!elements.contains(reference)) { - s= (reference == null ? StructuredSelection.EMPTY : new StructuredSelection(reference)); + s = (reference == null ? StructuredSelection.EMPTY + : new StructuredSelection(reference)); fOutlineViewer.setSelection(s, true); } } @@ -1214,25 +1294,28 @@ public class JavaOutlinePage extends Page implements IContentOutlinePage, IAdapt } /** - * Convenience method to add the action installed under the given actionID to the - * specified group of the menu. - * - * @param menu the menu manager - * @param group the group to which to add the action - * @param actionID the ID of the new action + * Convenience method to add the action installed under the given actionID + * to the specified group of the menu. + * + * @param menu + * the menu manager + * @param group + * the group to which to add the action + * @param actionID + * the ID of the new action */ protected void addAction(IMenuManager menu, String group, String actionID) { - IAction action= getAction(actionID); + IAction action = getAction(actionID); if (action != null) { if (action instanceof IUpdate) ((IUpdate) action).update(); if (action.isEnabled()) { - IMenuManager subMenu= menu.findMenuUsingPath(group); - if (subMenu != null) - subMenu.add(action); - else - menu.appendToGroup(group, action); + IMenuManager subMenu = menu.findMenuUsingPath(group); + if (subMenu != null) + subMenu.add(action); + else + menu.appendToGroup(group, action); } } } @@ -1241,7 +1324,7 @@ public class JavaOutlinePage extends Page implements IContentOutlinePage, IAdapt PHPeclipsePlugin.createStandardGroups(menu); - IStructuredSelection selection= (IStructuredSelection)getSelection(); + IStructuredSelection selection = (IStructuredSelection) getSelection(); fActionGroups.setContext(new ActionContext(selection)); fActionGroups.fillContextMenu(menu); } @@ -1256,20 +1339,21 @@ public class JavaOutlinePage extends Page implements IContentOutlinePage, IAdapt /** * Checks whether a given Java element is an inner type. - * - * @param element the java element + * + * @param element + * the java element * @return true iff the given element is an inner type */ private boolean isInnerType(IJavaElement element) { if (element != null && element.getElementType() == IJavaElement.TYPE) { - IType type= (IType)element; + IType type = (IType) element; try { return type.isMember(); } catch (JavaModelException e) { - IJavaElement parent= type.getParent(); + IJavaElement parent = type.getParent(); if (parent != null) { - int parentElementType= parent.getElementType(); + int parentElementType = parent.getElementType(); return (parentElementType != IJavaElement.COMPILATION_UNIT && parentElementType != IJavaElement.CLASS_FILE); } } @@ -1280,32 +1364,31 @@ public class JavaOutlinePage extends Page implements IContentOutlinePage, IAdapt /** * Returns the IShowInSource for this view. - * + * * @return the {@link IShowInSource} */ protected IShowInSource getShowInSource() { return new IShowInSource() { public ShowInContext getShowInContext() { - return new ShowInContext( - null, - getSite().getSelectionProvider().getSelection()); + return new ShowInContext(null, getSite().getSelectionProvider() + .getSelection()); } }; } /** * Returns the IShowInTarget for this view. - * + * * @return the {@link IShowInTarget} */ protected IShowInTarget getShowInTarget() { return new IShowInTarget() { public boolean show(ShowInContext context) { - ISelection sel= context.getSelection(); + ISelection sel = context.getSelection(); if (sel instanceof ITextSelection) { - ITextSelection tsel= (ITextSelection) sel; - int offset= tsel.getOffset(); - IJavaElement element= fEditor.getElementAt(offset); + ITextSelection tsel = (ITextSelection) sel; + int offset = tsel.getOffset(); + IJavaElement element = fEditor.getElementAt(offset); if (element != null) { setSelection(new StructuredSelection(element)); return true; @@ -1317,21 +1400,24 @@ public class JavaOutlinePage extends Page implements IContentOutlinePage, IAdapt } private void initDragAndDrop() { - int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK; - Transfer[] transfers= new Transfer[] { - LocalSelectionTransfer.getInstance() - }; + int ops = DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK; + Transfer[] transfers = new Transfer[] { LocalSelectionTransfer + .getInstance() }; // Drop Adapter -// TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] { -// new SelectionTransferDropAdapter(fOutlineViewer) -// }; -// fOutlineViewer.addDropSupport(ops | DND.DROP_DEFAULT, transfers, new DelegatingDropAdapter(dropListeners)); + // TransferDropTargetListener[] dropListeners= new + // TransferDropTargetListener[] { + // new SelectionTransferDropAdapter(fOutlineViewer) + // }; + // fOutlineViewer.addDropSupport(ops | DND.DROP_DEFAULT, transfers, new + // DelegatingDropAdapter(dropListeners)); // Drag Adapter -// TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] { -// new SelectionTransferDragAdapter(fOutlineViewer) -// }; -// fOutlineViewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(fOutlineViewer, dragListeners)); + // TransferDragSourceListener[] dragListeners= new + // TransferDragSourceListener[] { + // new SelectionTransferDragAdapter(fOutlineViewer) + // }; + // fOutlineViewer.addDragSupport(ops, transfers, new + // JdtViewerDragAdapter(fOutlineViewer, dragListeners)); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSelectMarkerRulerAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSelectMarkerRulerAction.java index ec3ed89..e265b54 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSelectMarkerRulerAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSelectMarkerRulerAction.java @@ -32,33 +32,39 @@ import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.ITextEditorExtension; import org.eclipse.ui.texteditor.SelectMarkerRulerAction; - /** - * A special select marker ruler action which activates quick fix if clicked on a quick fixable problem. + * A special select marker ruler action which activates quick fix if clicked on + * a quick fixable problem. */ public class JavaSelectMarkerRulerAction extends SelectMarkerRulerAction { private ITextEditor fTextEditor; + private Position fPosition; - public JavaSelectMarkerRulerAction(ResourceBundle bundle, String prefix, ITextEditor editor, IVerticalRulerInfo ruler) { + public JavaSelectMarkerRulerAction(ResourceBundle bundle, String prefix, + ITextEditor editor, IVerticalRulerInfo ruler) { super(bundle, prefix, editor, ruler); - fTextEditor= editor; - PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.JAVA_SELECT_MARKER_RULER_ACTION); + fTextEditor = editor; + PlatformUI.getWorkbench().getHelpSystem().setHelp(this, + IJavaHelpContextIds.JAVA_SELECT_MARKER_RULER_ACTION); } public void run() { -// if (PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER)) -// return; + // if + // (PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER)) + // return; if (fPosition != null) { - ITextOperationTarget operation= (ITextOperationTarget) fTextEditor.getAdapter(ITextOperationTarget.class); -// final int opCode= PHPUnitEditor.CORRECTIONASSIST_PROPOSALS; -// if (operation != null && operation.canDoOperation(opCode)) { -// fTextEditor.selectAndReveal(fPosition.getOffset(), fPosition.getLength()); -// operation.doOperation(opCode); -// return; -// } + ITextOperationTarget operation = (ITextOperationTarget) fTextEditor + .getAdapter(ITextOperationTarget.class); + // final int opCode= PHPUnitEditor.CORRECTIONASSIST_PROPOSALS; + // if (operation != null && operation.canDoOperation(opCode)) { + // fTextEditor.selectAndReveal(fPosition.getOffset(), + // fPosition.getLength()); + // operation.doOperation(opCode); + // return; + // } return; } super.run(); @@ -66,13 +72,14 @@ public class JavaSelectMarkerRulerAction extends SelectMarkerRulerAction { public void update() { // Begin Fix for http://dev.eclipse.org/bugs/show_bug.cgi?id=20114 - if (!(fTextEditor instanceof ITextEditorExtension) || ((ITextEditorExtension) fTextEditor).isEditorInputReadOnly()) { - fPosition= null; + if (!(fTextEditor instanceof ITextEditorExtension) + || ((ITextEditorExtension) fTextEditor).isEditorInputReadOnly()) { + fPosition = null; super.update(); return; } // End Fix for http://dev.eclipse.org/bugs/show_bug.cgi?id=20114 - fPosition= getJavaAnnotationPosition(); + fPosition = getJavaAnnotationPosition(); if (fPosition != null) setEnabled(true); else @@ -80,37 +87,41 @@ public class JavaSelectMarkerRulerAction extends SelectMarkerRulerAction { } private Position getJavaAnnotationPosition() { - AbstractMarkerAnnotationModel model= getAnnotationModel(); - IDocument document= getDocument(); + AbstractMarkerAnnotationModel model = getAnnotationModel(); + IDocument document = getDocument(); if (model == null) return null; - ICompilationUnit cu= getCompilationUnit(); + ICompilationUnit cu = getCompilationUnit(); if (cu == null) { return null; } -// boolean hasAssistLightbulb= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.APPEARANCE_QUICKASSIST_LIGHTBULB); - Annotation assistAnnotation= null; + // boolean hasAssistLightbulb= + // PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.APPEARANCE_QUICKASSIST_LIGHTBULB); + Annotation assistAnnotation = null; - Iterator iter= model.getAnnotationIterator(); + Iterator iter = model.getAnnotationIterator(); while (iter.hasNext()) { - Annotation annotation= (Annotation) iter.next(); + Annotation annotation = (Annotation) iter.next(); if (annotation instanceof IJavaAnnotation) { - IJavaAnnotation javaAnnotation= (IJavaAnnotation)annotation; + IJavaAnnotation javaAnnotation = (IJavaAnnotation) annotation; if (!javaAnnotation.isMarkedDeleted()) { - Position position= model.getPosition(annotation); -// if (includesRulerLine(position, document) && JavaCorrectionProcessor.hasCorrections(javaAnnotation)) -// return position; + Position position = model.getPosition(annotation); + // if (includesRulerLine(position, document) && + // JavaCorrectionProcessor.hasCorrections(javaAnnotation)) + // return position; } } -// else if (hasAssistLightbulb && annotation instanceof AssistAnnotation) { -// // there is only one AssistAnnotation at a time -// assistAnnotation= annotation; -// } + // else if (hasAssistLightbulb && annotation instanceof + // AssistAnnotation) { + // // there is only one AssistAnnotation at a time + // assistAnnotation= annotation; + // } } if (assistAnnotation != null) { - Position position= model.getPosition(assistAnnotation); - // no need to check 'JavaCorrectionProcessor.hasAssists': annotation only created when + Position position = model.getPosition(assistAnnotation); + // no need to check 'JavaCorrectionProcessor.hasAssists': annotation + // only created when // there are assists if (includesRulerLine(position, document)) return position; @@ -119,14 +130,13 @@ public class JavaSelectMarkerRulerAction extends SelectMarkerRulerAction { } private ICompilationUnit getCompilationUnit() { - IEditorInput input= fTextEditor.getEditorInput(); + IEditorInput input = fTextEditor.getEditorInput(); if (input instanceof IFileEditorInput) { - IFile file= ((IFileEditorInput) input).getFile(); - IJavaElement element= JavaCore.create(file); + IFile file = ((IFileEditorInput) input).getFile(); + IJavaElement element = JavaCore.create(file); if (element instanceof ICompilationUnit) return (ICompilationUnit) element; } return null; } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSelectMarkerRulerAction2.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSelectMarkerRulerAction2.java index 78e6932..5b3abd8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSelectMarkerRulerAction2.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSelectMarkerRulerAction2.java @@ -26,49 +26,56 @@ import org.eclipse.ui.texteditor.ITextEditorActionConstants; import org.eclipse.ui.texteditor.IUpdate; import org.eclipse.ui.texteditor.SelectAnnotationRulerAction; -//import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; -//import net.sourceforge.phpdt.internal.ui.text.correction.JavaCorrectionProcessor; -//import net.sourceforge.phpdt.internal.ui.text.correction.QuickAssistLightBulbUpdater.AssistAnnotation; -//import net.sourceforge.phpdt.internal.ui.text.java.hover.JavaExpandHover; +// import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; +// import +// net.sourceforge.phpdt.internal.ui.text.correction.JavaCorrectionProcessor; +// import +// net.sourceforge.phpdt.internal.ui.text.correction.QuickAssistLightBulbUpdater.AssistAnnotation; +// import net.sourceforge.phpdt.internal.ui.text.java.hover.JavaExpandHover; /** - * A special select marker ruler action which activates quick fix if clicked on a quick fixable problem. + * A special select marker ruler action which activates quick fix if clicked on + * a quick fixable problem. */ public class JavaSelectMarkerRulerAction2 extends SelectAnnotationRulerAction { - public JavaSelectMarkerRulerAction2(ResourceBundle bundle, String prefix, ITextEditor editor) { + public JavaSelectMarkerRulerAction2(ResourceBundle bundle, String prefix, + ITextEditor editor) { super(bundle, prefix, editor); - PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.JAVA_SELECT_MARKER_RULER_ACTION); + PlatformUI.getWorkbench().getHelpSystem().setHelp(this, + IJavaHelpContextIds.JAVA_SELECT_MARKER_RULER_ACTION); } /* * @see org.eclipse.ui.texteditor.IVerticalRulerListener#annotationDefaultSelected(org.eclipse.ui.texteditor.VerticalRulerEvent) */ public void annotationDefaultSelected(VerticalRulerEvent event) { - Annotation annotation= event.getSelectedAnnotation(); - IAnnotationModel model= getAnnotationModel(); + Annotation annotation = event.getSelectedAnnotation(); + IAnnotationModel model = getAnnotationModel(); -// if (isOverrideIndicator(annotation)) { -// ((OverrideIndicatorManager.OverrideIndicator)annotation).open(); -// return; -// } + // if (isOverrideIndicator(annotation)) { + // ((OverrideIndicatorManager.OverrideIndicator)annotation).open(); + // return; + // } if (isBreakpoint(annotation)) triggerAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK); - Position position= model.getPosition(annotation); + Position position = model.getPosition(annotation); if (position == null) return; -// if (isQuickFixTarget(annotation)) { -// ITextOperationTarget operation= (ITextOperationTarget) getTextEditor().getAdapter(ITextOperationTarget.class); -// final int opCode= PHPUnitEditor.CORRECTIONASSIST_PROPOSALS; -// if (operation != null && operation.canDoOperation(opCode)) { -// getTextEditor().selectAndReveal(position.getOffset(), position.getLength()); -// operation.doOperation(opCode); -// return; -// } -// } + // if (isQuickFixTarget(annotation)) { + // ITextOperationTarget operation= (ITextOperationTarget) + // getTextEditor().getAdapter(ITextOperationTarget.class); + // final int opCode= PHPUnitEditor.CORRECTIONASSIST_PROPOSALS; + // if (operation != null && operation.canDoOperation(opCode)) { + // getTextEditor().selectAndReveal(position.getOffset(), + // position.getLength()); + // operation.doOperation(opCode); + // return; + // } + // } // default: super.annotationDefaultSelected(event); @@ -76,12 +83,14 @@ public class JavaSelectMarkerRulerAction2 extends SelectAnnotationRulerAction { /** * Tells whether the given annotation is an override annotation. - * - * @param annotation the annotation + * + * @param annotation + * the annotation * @return true iff the annotation is an override annotation */ private boolean isOverrideIndicator(Annotation annotation) { - return false; //annotation instanceof OverrideIndicatorManager.OverrideIndicator; + return false; // annotation instanceof + // OverrideIndicatorManager.OverrideIndicator; } /** @@ -90,22 +99,25 @@ public class JavaSelectMarkerRulerAction2 extends SelectAnnotationRulerAction { */ private boolean isBreakpoint(Annotation annotation) { return annotation.getType().equals("org.eclipse.debug.core.breakpoint"); - //|| annotation.getType().equals(JavaExpandHover.NO_BREAKPOINT_ANNOTATION); //$NON-NLS-1$ + // || + // annotation.getType().equals(JavaExpandHover.NO_BREAKPOINT_ANNOTATION); + // //$NON-NLS-1$ } private boolean isQuickFixTarget(Annotation a) { - return false; //JavaCorrectionProcessor.hasCorrections(a) || a instanceof AssistAnnotation; + return false; // JavaCorrectionProcessor.hasCorrections(a) || a + // instanceof AssistAnnotation; } private void triggerAction(String actionID) { - IAction action= getTextEditor().getAction(actionID); + IAction action = getTextEditor().getAction(actionID); if (action != null) { if (action instanceof IUpdate) ((IUpdate) action).update(); // hack to propagate line change if (action instanceof ISelectionListener) { - ((ISelectionListener)action).selectionChanged(null, null); + ((ISelectionListener) action).selectionChanged(null, null); } if (action.isEnabled()) action.run(); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSelectRulerAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSelectRulerAction.java index edb4565..586ff2e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSelectRulerAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSelectRulerAction.java @@ -18,9 +18,13 @@ import org.eclipse.ui.texteditor.ITextEditor; public class JavaSelectRulerAction extends AbstractRulerActionDelegate { /* - * @see AbstractRulerActionDelegate#createAction(ITextEditor, IVerticalRulerInfo) + * @see AbstractRulerActionDelegate#createAction(ITextEditor, + * IVerticalRulerInfo) */ - protected IAction createAction(ITextEditor editor, IVerticalRulerInfo rulerInfo) { - return new JavaSelectMarkerRulerAction(PHPEditorMessages.getResourceBundle(), "JavaSelectMarkerRulerAction.", editor, rulerInfo); //$NON-NLS-1$ + protected IAction createAction(ITextEditor editor, + IVerticalRulerInfo rulerInfo) { + return new JavaSelectMarkerRulerAction(PHPEditorMessages + .getResourceBundle(), + "JavaSelectMarkerRulerAction.", editor, rulerInfo); //$NON-NLS-1$ } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSourceViewer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSourceViewer.java index 030c7d5..124ee59 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSourceViewer.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSourceViewer.java @@ -37,70 +37,85 @@ import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; +public class JavaSourceViewer extends ProjectionViewer implements + IPropertyChangeListener { - -public class JavaSourceViewer extends ProjectionViewer implements IPropertyChangeListener { - - /** + /** * Text operation code for requesting the outline for the current input. */ - public static final int SHOW_OUTLINE= 51; + public static final int SHOW_OUTLINE = 51; /** - * Text operation code for requesting the outline for the element at the current position. + * Text operation code for requesting the outline for the element at the + * current position. */ - public static final int OPEN_STRUCTURE= 52; + public static final int OPEN_STRUCTURE = 52; /** * Text operation code for requesting the hierarchy for the current input. */ - public static final int SHOW_HIERARCHY= 53; + public static final int SHOW_HIERARCHY = 53; private IInformationPresenter fOutlinePresenter; + private IInformationPresenter fStructurePresenter; -// private IInformationPresenter fHierarchyPresenter; + + // private IInformationPresenter fHierarchyPresenter; /** * This viewer's foreground color. + * * @since 3.0 */ private Color fForegroundColor; - /** + + /** * The viewer's background color. + * * @since 3.0 */ private Color fBackgroundColor; + /** * This viewer's selection foreground color. + * * @since 3.0 */ private Color fSelectionForegroundColor; - /** + + /** * The viewer's selection background color. + * * @since 3.0 */ private Color fSelectionBackgroundColor; + /** * The preference store. * * @since 3.0 */ private IPreferenceStore fPreferenceStore; + /** * Is this source viewer configured? * * @since 3.0 */ private boolean fIsConfigured; + /** * The backspace manager of this viewer. * * @since 3.0 */ private SmartBackspaceManager fBackspaceManager; - - public JavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean showAnnotationsOverview, int styles, IPreferenceStore store) { - super(parent, verticalRuler, overviewRuler, showAnnotationsOverview, styles); + + public JavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, + IOverviewRuler overviewRuler, boolean showAnnotationsOverview, + int styles, IPreferenceStore store) { + super(parent, verticalRuler, overviewRuler, showAnnotationsOverview, + styles); setPreferenceStore(store); } @@ -108,17 +123,17 @@ public class JavaSourceViewer extends ProjectionViewer implements IPropertyChang * @see org.eclipse.jface.text.source.SourceViewer#createFormattingContext() * @since 3.0 */ -// public IFormattingContext createFormattingContext() { -// -// IFormattingContext context= new CommentFormattingContext(); -// Map map= new Hashtable(JavaCore.getOptions()); -// -// context.storeToMap(PreferenceConstants.getPreferenceStore(), map, false); -// context.setProperty(FormattingContextProperties.CONTEXT_PREFERENCES, map); -// -// return context; -// } - + // public IFormattingContext createFormattingContext() { + // + // IFormattingContext context= new CommentFormattingContext(); + // Map map= new Hashtable(JavaCore.getOptions()); + // + // context.storeToMap(PreferenceConstants.getPreferenceStore(), map, false); + // context.setProperty(FormattingContextProperties.CONTEXT_PREFERENCES, + // map); + // + // return context; + // } /* * @see ITextOperationTarget#doOperation(int) */ @@ -127,24 +142,24 @@ public class JavaSourceViewer extends ProjectionViewer implements IPropertyChang return; switch (operation) { - case SHOW_OUTLINE: - fOutlinePresenter.showInformation(); - return; - case OPEN_STRUCTURE: - fStructurePresenter.showInformation(); - return; - case SHOW_HIERARCHY: -// fHierarchyPresenter.showInformation(); - return; - case FORMAT: - Point point = getSelectedRange(); - if (point.y==0) { -// setSelectedRange(0, getDocument().getLength()); - revealRange(0, getDocument().getLength()); - } - break; + case SHOW_OUTLINE: + fOutlinePresenter.showInformation(); + return; + case OPEN_STRUCTURE: + fStructurePresenter.showInformation(); + return; + case SHOW_HIERARCHY: + // fHierarchyPresenter.showInformation(); + return; + case FORMAT: + Point point = getSelectedRange(); + if (point.y == 0) { + // setSelectedRange(0, getDocument().getLength()); + revealRange(0, getDocument().getLength()); + } + break; } - + super.doOperation(operation); } @@ -157,9 +172,9 @@ public class JavaSourceViewer extends ProjectionViewer implements IPropertyChang if (operation == OPEN_STRUCTURE) return fStructurePresenter != null; if (operation == SHOW_HIERARCHY) -// return fHierarchyPresenter != null; + // return fHierarchyPresenter != null; return false; - + return super.canDoOperation(operation); } @@ -169,104 +184,123 @@ public class JavaSourceViewer extends ProjectionViewer implements IPropertyChang public void configure(SourceViewerConfiguration configuration) { super.configure(configuration); if (configuration instanceof PHPSourceViewerConfiguration) { - fOutlinePresenter= ((PHPSourceViewerConfiguration)configuration).getOutlinePresenter(this, false); + fOutlinePresenter = ((PHPSourceViewerConfiguration) configuration) + .getOutlinePresenter(this, false); fOutlinePresenter.install(this); } if (configuration instanceof PHPSourceViewerConfiguration) { - fStructurePresenter= ((PHPSourceViewerConfiguration)configuration).getOutlinePresenter(this, true); + fStructurePresenter = ((PHPSourceViewerConfiguration) configuration) + .getOutlinePresenter(this, true); fStructurePresenter.install(this); } if (configuration instanceof PHPSourceViewerConfiguration) { -// fHierarchyPresenter= ((PHPSourceViewerConfiguration)configuration).getHierarchyPresenter(this, true); -// fHierarchyPresenter.install(this); - + // fHierarchyPresenter= + // ((PHPSourceViewerConfiguration)configuration).getHierarchyPresenter(this, + // true); + // fHierarchyPresenter.install(this); + if (fPreferenceStore != null) { fPreferenceStore.addPropertyChangeListener(this); initializeViewerColors(); } } - fIsConfigured= true; + fIsConfigured = true; } - - + protected void initializeViewerColors() { if (fPreferenceStore != null) { - - StyledText styledText= getTextWidget(); - + + StyledText styledText = getTextWidget(); + // ----------- foreground color -------------------- - Color color= fPreferenceStore.getBoolean(PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR) - ? null - : createColor(fPreferenceStore, PreferenceConstants.EDITOR_FOREGROUND_COLOR, styledText.getDisplay()); + Color color = fPreferenceStore + .getBoolean(PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR) ? null + : createColor(fPreferenceStore, + PreferenceConstants.EDITOR_FOREGROUND_COLOR, + styledText.getDisplay()); styledText.setForeground(color); - + if (fForegroundColor != null) fForegroundColor.dispose(); - - fForegroundColor= color; - + + fForegroundColor = color; + // ---------- background color ---------------------- - color= fPreferenceStore.getBoolean(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR) - ? null - : createColor(fPreferenceStore, PreferenceConstants.EDITOR_BACKGROUND_COLOR, styledText.getDisplay()); + color = fPreferenceStore + .getBoolean(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR) ? null + : createColor(fPreferenceStore, + PreferenceConstants.EDITOR_BACKGROUND_COLOR, + styledText.getDisplay()); styledText.setBackground(color); - + if (fBackgroundColor != null) fBackgroundColor.dispose(); - - fBackgroundColor= color; - + + fBackgroundColor = color; + // ----------- selection foreground color -------------------- - color= fPreferenceStore.getBoolean(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_DEFAULT_COLOR) - ? null - : createColor(fPreferenceStore, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_COLOR, styledText.getDisplay()); + color = fPreferenceStore + .getBoolean(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_DEFAULT_COLOR) ? null + : createColor( + fPreferenceStore, + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_COLOR, + styledText.getDisplay()); styledText.setSelectionForeground(color); - + if (fSelectionForegroundColor != null) fSelectionForegroundColor.dispose(); - - fSelectionForegroundColor= color; - + + fSelectionForegroundColor = color; + // ---------- selection background color ---------------------- - color= fPreferenceStore.getBoolean(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_DEFAULT_COLOR) - ? null - : createColor(fPreferenceStore, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_COLOR, styledText.getDisplay()); + color = fPreferenceStore + .getBoolean(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_DEFAULT_COLOR) ? null + : createColor( + fPreferenceStore, + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_COLOR, + styledText.getDisplay()); styledText.setSelectionBackground(color); - + if (fSelectionBackgroundColor != null) fSelectionBackgroundColor.dispose(); - - fSelectionBackgroundColor= color; + + fSelectionBackgroundColor = color; } - } - - /** - * Creates a color from the information stored in the given preference store. - * Returns null if there is no such information available. - * - * @param store the store to read from - * @param key the key used for the lookup in the preference store - * @param display the display used create the color - * @return the created color according to the specification in the preference store - * @since 3.0 - */ - private Color createColor(IPreferenceStore store, String key, Display display) { - - RGB rgb= null; - - if (store.contains(key)) { - - if (store.isDefault(key)) - rgb= PreferenceConverter.getDefaultColor(store, key); - else - rgb= PreferenceConverter.getColor(store, key); - - if (rgb != null) - return new Color(display, rgb); - } - - return null; - } + } + + /** + * Creates a color from the information stored in the given preference + * store. Returns null if there is no such information + * available. + * + * @param store + * the store to read from + * @param key + * the key used for the lookup in the preference store + * @param display + * the display used create the color + * @return the created color according to the specification in the + * preference store + * @since 3.0 + */ + private Color createColor(IPreferenceStore store, String key, + Display display) { + + RGB rgb = null; + + if (store.contains(key)) { + + if (store.isDefault(key)) + rgb = PreferenceConverter.getDefaultColor(store, key); + else + rgb = PreferenceConverter.getColor(store, key); + + if (rgb != null) + return new Color(display, rgb); + } + + return null; + } /* * @see org.eclipse.jface.text.source.ISourceViewerExtension2#unconfigure() @@ -274,40 +308,40 @@ public class JavaSourceViewer extends ProjectionViewer implements IPropertyChang */ public void unconfigure() { if (fOutlinePresenter != null) { - fOutlinePresenter.uninstall(); - fOutlinePresenter= null; + fOutlinePresenter.uninstall(); + fOutlinePresenter = null; } if (fStructurePresenter != null) { fStructurePresenter.uninstall(); - fStructurePresenter= null; + fStructurePresenter = null; } -// if (fHierarchyPresenter != null) { -// fHierarchyPresenter.uninstall(); -// fHierarchyPresenter= null; -// } + // if (fHierarchyPresenter != null) { + // fHierarchyPresenter.uninstall(); + // fHierarchyPresenter= null; + // } if (fForegroundColor != null) { fForegroundColor.dispose(); - fForegroundColor= null; + fForegroundColor = null; } if (fBackgroundColor != null) { fBackgroundColor.dispose(); - fBackgroundColor= null; + fBackgroundColor = null; } if (fPreferenceStore != null) fPreferenceStore.removePropertyChangeListener(this); - + super.unconfigure(); - - fIsConfigured= false; + + fIsConfigured = false; } - + /* * @see org.eclipse.jface.text.source.SourceViewer#rememberSelection() */ public Point rememberSelection() { return super.rememberSelection(); } - + /* * @see org.eclipse.jface.text.source.SourceViewer#restoreSelection() */ @@ -321,47 +355,54 @@ public class JavaSourceViewer extends ProjectionViewer implements IPropertyChang public void propertyChange(PropertyChangeEvent event) { String property = event.getProperty(); if (PreferenceConstants.EDITOR_FOREGROUND_COLOR.equals(property) - || PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR.equals(property) + || PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR + .equals(property) || PreferenceConstants.EDITOR_BACKGROUND_COLOR.equals(property) - || PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR.equals(property) - || AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_COLOR.equals(property) - || AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_DEFAULT_COLOR.equals(property) - || AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_COLOR.equals(property) - || AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_DEFAULT_COLOR.equals(property)) - { + || PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR + .equals(property) + || AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_COLOR + .equals(property) + || AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_DEFAULT_COLOR + .equals(property) + || AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_COLOR + .equals(property) + || AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_DEFAULT_COLOR + .equals(property)) { initializeViewerColors(); - } + } } /** * Sets the preference store on this viewer. * - * @param store the preference store + * @param store + * the preference store * * @since 3.0 */ public void setPreferenceStore(IPreferenceStore store) { if (fIsConfigured && fPreferenceStore != null) fPreferenceStore.removePropertyChangeListener(this); - - fPreferenceStore= store; + + fPreferenceStore = store; if (fIsConfigured && fPreferenceStore != null) { fPreferenceStore.addPropertyChangeListener(this); initializeViewerColors(); } } - + /* - * @see org.eclipse.jface.text.source.SourceViewer#createControl(org.eclipse.swt.widgets.Composite, int) + * @see org.eclipse.jface.text.source.SourceViewer#createControl(org.eclipse.swt.widgets.Composite, + * int) */ protected void createControl(Composite parent, int styles) { super.createControl(parent, styles); - fBackspaceManager= new SmartBackspaceManager(); + fBackspaceManager = new SmartBackspaceManager(); fBackspaceManager.install(this); } - + /** * Returns the backspace manager for this viewer. * @@ -372,46 +413,50 @@ public class JavaSourceViewer extends ProjectionViewer implements IPropertyChang public SmartBackspaceManager getBackspaceManager() { return fBackspaceManager; } - + /* * @see org.eclipse.jface.text.source.SourceViewer#handleDispose() */ protected void handleDispose() { if (fBackspaceManager != null) { fBackspaceManager.uninstall(); - fBackspaceManager= null; + fBackspaceManager = null; } - + super.handleDispose(); } - + /** - * Prepends the text presentation listener at the beginning of the viewer's - * list of text presentation listeners. If the listener is already registered - * with the viewer this call moves the listener to the beginning of - * the list. - * - * @param listener the text presentation listener + * Prepends the text presentation listener at the beginning of the viewer's + * list of text presentation listeners. If the listener is already + * registered with the viewer this call moves the listener to the beginning + * of the list. + * + * @param listener + * the text presentation listener * @since 3.0 */ - public void prependTextPresentationListener(ITextPresentationListener listener) { - + public void prependTextPresentationListener( + ITextPresentationListener listener) { + Assert.isNotNull(listener); if (fTextPresentationListeners == null) - fTextPresentationListeners= new ArrayList(); - + fTextPresentationListeners = new ArrayList(); + fTextPresentationListeners.remove(listener); fTextPresentationListeners.add(0, listener); } + /** * Sets the given reconciler. - * - * @param reconciler the reconciler + * + * @param reconciler + * the reconciler * @since 3.0 */ void setReconciler(IReconciler reconciler) { - fReconciler= reconciler; + fReconciler = reconciler; } /** diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaStorageDocumentProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaStorageDocumentProvider.java index e91b68d..cbecbe3 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaStorageDocumentProvider.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaStorageDocumentProvider.java @@ -1,13 +1,13 @@ /********************************************************************** -Copyright (c) 2000, 2003 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - IBM Corporation - Initial implementation -**********************************************************************/ + Copyright (c) 2000, 2003 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + **********************************************************************/ package net.sourceforge.phpeclipse.phpeditor; import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; @@ -21,21 +21,26 @@ import org.eclipse.ui.editors.text.StorageDocumentProvider; * @since 3.0 */ public class JavaStorageDocumentProvider extends StorageDocumentProvider { - + public JavaStorageDocumentProvider() { super(); } - + /* - * @see org.eclipse.ui.editors.text.StorageDocumentProvider#setupDocument(java.lang.Object, org.eclipse.jface.text.IDocument) + * @see org.eclipse.ui.editors.text.StorageDocumentProvider#setupDocument(java.lang.Object, + * org.eclipse.jface.text.IDocument) */ protected void setupDocument(Object element, IDocument document) { - + if (document != null) { - JavaTextTools tools= PHPeclipsePlugin.getDefault().getJavaTextTools(); - tools.setupJavaDocumentPartitioner(document, IPHPPartitions.PHP_PARTITIONING); + JavaTextTools tools = PHPeclipsePlugin.getDefault() + .getJavaTextTools(); + tools.setupJavaDocumentPartitioner(document, + IPHPPartitions.PHP_PARTITIONING); -// tools.setupJavaDocumentPartitioner(document, IDocument.DEFAULT_CONTENT_TYPE, element); //IPHPPartitions.HTML, element); + // tools.setupJavaDocumentPartitioner(document, + // IDocument.DEFAULT_CONTENT_TYPE, element); //IPHPPartitions.HTML, + // element); } } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/LinePainter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/LinePainter.java index a3b7167..b0f7533 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/LinePainter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/LinePainter.java @@ -18,22 +18,28 @@ import org.eclipse.swt.graphics.Point; public class LinePainter implements IPainter, LineBackgroundListener { private final ISourceViewer fViewer; + private Color fHighlightColor; + private IPositionManager fPositionManager; - // positions to keep track of beginning and end of line to be painted or cleared - private Position fCurrentLine= new Position(0, 0); - private Position fLastLine= new Position(0, 0); + // positions to keep track of beginning and end of line to be painted or + // cleared + private Position fCurrentLine = new Position(0, 0); + + private Position fLastLine = new Position(0, 0); + // used to keep track of the last line painted - private int fLastLineNumber= -1; + private int fLastLineNumber = -1; + private boolean fIsActive; public LinePainter(ISourceViewer sourceViewer) { - fViewer= sourceViewer; + fViewer = sourceViewer; } public void setHighlightColor(Color highlightColor) { - fHighlightColor= highlightColor; + fHighlightColor = highlightColor; } /* @@ -42,47 +48,52 @@ public class LinePainter implements IPainter, LineBackgroundListener { public void lineGetBackground(LineBackgroundEvent event) { // don't use cached line information because of asynch painting - StyledText textWidget= fViewer.getTextWidget(); + StyledText textWidget = fViewer.getTextWidget(); if (textWidget != null) { - - int caret= textWidget.getCaretOffset(); - int length= event.lineText.length(); + + int caret = textWidget.getCaretOffset(); + int length = event.lineText.length(); if (event.lineOffset <= caret && caret <= event.lineOffset + length) - event.lineBackground= fHighlightColor; + event.lineBackground = fHighlightColor; else - event.lineBackground= textWidget.getBackground(); + event.lineBackground = textWidget.getBackground(); } } private boolean updateHighlightLine() { try { - IDocument document= fViewer.getDocument(); + IDocument document = fViewer.getDocument(); - int offset= fViewer.getTextWidget().getCaretOffset() + fViewer.getVisibleRegion().getOffset(); - int lineNumber= document.getLineOfOffset(offset); - - // redraw if the current line number is different from the last line number we painted + int offset = fViewer.getTextWidget().getCaretOffset() + + fViewer.getVisibleRegion().getOffset(); + int lineNumber = document.getLineOfOffset(offset); + + // redraw if the current line number is different from the last line + // number we painted // initially fLastLineNumber is -1 if (lineNumber != fLastLineNumber) { - - fLastLine.offset= fCurrentLine.offset; - fLastLine.length= fCurrentLine.length; - fLastLine.isDeleted= fCurrentLine.isDeleted; - fCurrentLine.isDeleted= false; - fCurrentLine.offset= document.getLineOffset(lineNumber); + fLastLine.offset = fCurrentLine.offset; + fLastLine.length = fCurrentLine.length; + fLastLine.isDeleted = fCurrentLine.isDeleted; + + fCurrentLine.isDeleted = false; + fCurrentLine.offset = document.getLineOffset(lineNumber); if (lineNumber == document.getNumberOfLines() - 1) - fCurrentLine.length= document.getLength() - fCurrentLine.offset; + fCurrentLine.length = document.getLength() + - fCurrentLine.offset; else - fCurrentLine.length= document.getLineOffset(lineNumber + 1) - fCurrentLine.offset; - - fLastLineNumber= lineNumber; + fCurrentLine.length = document + .getLineOffset(lineNumber + 1) + - fCurrentLine.offset; + + fLastLineNumber = lineNumber; return true; - + } - + } catch (BadLocationException e) { } @@ -90,17 +101,18 @@ public class LinePainter implements IPainter, LineBackgroundListener { } private void drawHighlightLine(Position position, int visibleOffset) { - StyledText textWidget= fViewer.getTextWidget(); - + StyledText textWidget = fViewer.getTextWidget(); + // if the position that is about to be drawn was deleted then we can't if (position.isDeleted()) - return; - - int delta= position.offset - visibleOffset; + return; + + int delta = position.offset - visibleOffset; if (0 <= delta && delta <= fViewer.getVisibleRegion().getLength()) { - Point upperLeft= textWidget.getLocationAtOffset(delta); - int width= textWidget.getClientArea().width + textWidget.getHorizontalPixel(); - int height= textWidget.getLineHeight(); + Point upperLeft = textWidget.getLocationAtOffset(delta); + int width = textWidget.getClientArea().width + + textWidget.getHorizontalPixel(); + int height = textWidget.getLineHeight(); textWidget.redraw(upperLeft.x, upperLeft.y, width, height, false); } } @@ -110,20 +122,22 @@ public class LinePainter implements IPainter, LineBackgroundListener { */ public void deactivate(boolean redraw) { if (fIsActive) { - fIsActive= false; - - /* on turning off the feature one has to paint the currently - * highlighted line with the standard background color + fIsActive = false; + + /* + * on turning off the feature one has to paint the currently + * highlighted line with the standard background color */ if (redraw) - drawHighlightLine(fCurrentLine, fViewer.getVisibleRegion().getOffset()); - + drawHighlightLine(fCurrentLine, fViewer.getVisibleRegion() + .getOffset()); + fViewer.getTextWidget().removeLineBackgroundListener(this); - + if (fPositionManager != null) fPositionManager.removeManagedPosition(fCurrentLine); - - fLastLineNumber= -1; + + fLastLineNumber = -1; } } @@ -137,25 +151,26 @@ public class LinePainter implements IPainter, LineBackgroundListener { * @see IPainter#paint(int) */ public void paint(int reason) { - + // check selection - Point selection= fViewer.getTextWidget().getSelectionRange(); + Point selection = fViewer.getTextWidget().getSelectionRange(); if (selection.y > 0) { deactivate(true); return; } - + // initialization if (!fIsActive) { fViewer.getTextWidget().addLineBackgroundListener(this); fPositionManager.addManagedPosition(fCurrentLine); - fIsActive= true; + fIsActive = true; } - - //redraw line highlight only if it hasn't been drawn yet on the respective line + + // redraw line highlight only if it hasn't been drawn yet on the + // respective line if (updateHighlightLine()) { // used to handle segmented view of source files - int visibleRegionOffset= fViewer.getVisibleRegion().getOffset(); + int visibleRegionOffset = fViewer.getVisibleRegion().getOffset(); // clear last line drawHighlightLine(fLastLine, visibleRegionOffset); // draw new line diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPAnnotationHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPAnnotationHover.java index 552183e..7972adf 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPAnnotationHover.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPAnnotationHover.java @@ -1,16 +1,16 @@ package net.sourceforge.phpeclipse.phpeditor; /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html -Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de -**********************************************************************/ + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ import java.util.ArrayList; import java.util.Iterator; @@ -25,163 +25,153 @@ import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.ui.texteditor.MarkerAnnotation; -/** +/** * The PHPAnnotationHover provides the hover support for PHP editors. */ - + public class PHPAnnotationHover implements IAnnotationHover { - /* (non-Javadoc) - * Method declared on IAnnotationHover + /* + * (non-Javadoc) Method declared on IAnnotationHover + */ + // public String getHoverInfo(ISourceViewer sourceViewer, int lineNumber) { + // IDocument document= sourceViewer.getDocument(); + // + // try { + // IRegion info= document.getLineInformation(lineNumber); + // return document.get(info.getOffset(), info.getLength()); + // } catch (BadLocationException x) { + // } + // + // return null; + // } + // + static final int MAX_INFO_LENGTH = 80; + + /** + * @see org.eclipse.jface.text.source.IAnnotationHover#getHoverInfo(org.eclipse.jface.text.source.ISourceViewer, + * int) + */ + + public String getHoverInfo(ISourceViewer viewer, int line) { + String info = null; + List markers = getMarkersForLine(viewer, line); + if (markers != null) { + info = ""; + for (int i = 0; i < markers.size(); i++) { + IMarker marker = (IMarker) markers.get(i); + String message = marker.getAttribute(IMarker.MESSAGE, + (String) null); + if (message != null && message.trim().length() > 0) { + + if (message.length() > MAX_INFO_LENGTH) { + message = splitMessage(message); + } + info += message; + + if (i != markers.size() - 1) { + info += "\n"; + } + } + } + } + return info; + } + + private String splitMessage(String message) { + String result = ""; + + if (message.length() <= MAX_INFO_LENGTH) { + return message; + } + + String tmpStr = new String(message); + + while (tmpStr.length() > MAX_INFO_LENGTH) { + + int spacepos = tmpStr.indexOf(" ", MAX_INFO_LENGTH); + + if (spacepos != -1) { + result += tmpStr.substring(0, spacepos) + "\n"; + tmpStr = tmpStr.substring(spacepos); + } else { + result += tmpStr.substring(0, MAX_INFO_LENGTH) + "\n"; + tmpStr = tmpStr.substring(MAX_INFO_LENGTH); + } + + } + + result += tmpStr; + + return result; + } + + /** + * Returns all markers which includes the ruler's line of activity. + */ + protected List getMarkersForLine(ISourceViewer aViewer, int aLine) { + List markers = new ArrayList(); + IAnnotationModel model = aViewer.getAnnotationModel(); + if (model != null) { + Iterator e = model.getAnnotationIterator(); + while (e.hasNext()) { + Object o = e.next(); + if (o instanceof MarkerAnnotation) { + MarkerAnnotation a = (MarkerAnnotation) o; + if (compareRulerLine(model.getPosition(a), aViewer + .getDocument(), aLine) != 0) { + markers.add(a.getMarker()); + } + } + } + } + return markers; + } + + /** + * Returns one marker which includes the ruler's line of activity. + */ + protected IMarker getMarkerForLine(ISourceViewer aViewer, int aLine) { + IMarker marker = null; + IAnnotationModel model = aViewer.getAnnotationModel(); + if (model != null) { + Iterator e = model.getAnnotationIterator(); + while (e.hasNext()) { + Object o = e.next(); + if (o instanceof MarkerAnnotation) { + MarkerAnnotation a = (MarkerAnnotation) o; + if (compareRulerLine(model.getPosition(a), aViewer + .getDocument(), aLine) != 0) { + marker = a.getMarker(); + } + } + } + } + return marker; + } + + /** + * Returns distance of given line to specified position (1 = same line, 2 = + * included in given position, 0 = not related). */ -// public String getHoverInfo(ISourceViewer sourceViewer, int lineNumber) { -// IDocument document= sourceViewer.getDocument(); -// -// try { -// IRegion info= document.getLineInformation(lineNumber); -// return document.get(info.getOffset(), info.getLength()); -// } catch (BadLocationException x) { -// } -// -// return null; -// } -// - static final int MAX_INFO_LENGTH = 80; - - /** - * @see org.eclipse.jface.text.source.IAnnotationHover#getHoverInfo(org.eclipse.jface.text.source.ISourceViewer, int) - */ - - public String getHoverInfo(ISourceViewer viewer, int line) { - String info = null; - List markers = getMarkersForLine(viewer, line); - if (markers != null) { - info = ""; - for (int i = 0; i < markers.size(); i++) { - IMarker marker = (IMarker) markers.get(i); - String message = - marker.getAttribute(IMarker.MESSAGE, (String) null); - if (message != null && message.trim().length() > 0) { - - if (message.length() > MAX_INFO_LENGTH) { - message = splitMessage(message); - } - info += message; - - if(i != markers.size() - 1) { - info += "\n"; - } - } - } - } - return info; - } - - private String splitMessage(String message) { - String result = ""; - - if(message.length() <= MAX_INFO_LENGTH) { - return message; - } - - String tmpStr = new String(message); - - while(tmpStr.length() > MAX_INFO_LENGTH) { - - int spacepos = tmpStr.indexOf(" ", MAX_INFO_LENGTH); - - if(spacepos != -1) { - result += tmpStr.substring(0, spacepos) + "\n"; - tmpStr = tmpStr.substring(spacepos); - } - else { - result += tmpStr.substring(0, MAX_INFO_LENGTH) + "\n"; - tmpStr = tmpStr.substring(MAX_INFO_LENGTH); - } - - - - } - - result += tmpStr; - - return result; - } - - /** - * Returns all markers which includes the ruler's line of activity. - */ - protected List getMarkersForLine(ISourceViewer aViewer, int aLine) { - List markers = new ArrayList(); - IAnnotationModel model = aViewer.getAnnotationModel(); - if (model != null) { - Iterator e = model.getAnnotationIterator(); - while (e.hasNext()) { - Object o = e.next(); - if (o instanceof MarkerAnnotation) { - MarkerAnnotation a = (MarkerAnnotation) o; - if (compareRulerLine(model.getPosition(a), - aViewer.getDocument(), - aLine) - != 0) { - markers.add(a.getMarker()); - } - } - } - } - return markers; - } - - /** - * Returns one marker which includes the ruler's line of activity. - */ - protected IMarker getMarkerForLine(ISourceViewer aViewer, int aLine) { - IMarker marker = null; - IAnnotationModel model = aViewer.getAnnotationModel(); - if (model != null) { - Iterator e = model.getAnnotationIterator(); - while (e.hasNext()) { - Object o = e.next(); - if (o instanceof MarkerAnnotation) { - MarkerAnnotation a = (MarkerAnnotation) o; - if (compareRulerLine(model.getPosition(a), - aViewer.getDocument(), - aLine) - != 0) { - marker = a.getMarker(); - } - } - } - } - return marker; - } - - /** - * Returns distance of given line to specified position (1 = same line, - * 2 = included in given position, 0 = not related). - */ - protected int compareRulerLine( - Position aPosition, - IDocument aDocument, - int aLine) { - int distance = 0; - if (aPosition.getOffset() > -1 && aPosition.getLength() > -1) { - try { - int markerLine = - aDocument.getLineOfOffset(aPosition.getOffset()); - if (aLine == markerLine) { - distance = 1; - } else if ( - markerLine <= aLine - && aLine - <= aDocument.getLineOfOffset( - aPosition.getOffset() - + aPosition.getLength())) { - distance = 2; - } - } catch (BadLocationException e) { - } - } - return distance; - } + protected int compareRulerLine(Position aPosition, IDocument aDocument, + int aLine) { + int distance = 0; + if (aPosition.getOffset() > -1 && aPosition.getLength() > -1) { + try { + int markerLine = aDocument.getLineOfOffset(aPosition + .getOffset()); + if (aLine == markerLine) { + distance = 1; + } else if (markerLine <= aLine + && aLine <= aDocument.getLineOfOffset(aPosition + .getOffset() + + aPosition.getLength())) { + distance = 2; + } + } catch (BadLocationException e) { + } + } + return distance; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPDocumentProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPDocumentProvider.java index f659b91..9ea94bc 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPDocumentProvider.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPDocumentProvider.java @@ -1,16 +1,16 @@ package net.sourceforge.phpeclipse.phpeditor; /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html -Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de -**********************************************************************/ + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ import java.util.ArrayList; import java.util.Iterator; @@ -77,14 +77,15 @@ import org.eclipse.ui.texteditor.ResourceMarkerAnnotationModel; * The PHPDocumentProvider provides the IDocuments used by java editors. */ -public class PHPDocumentProvider extends TextFileDocumentProvider implements ICompilationUnitDocumentProvider { - /** - * Here for visibility issues only. - */ +public class PHPDocumentProvider extends TextFileDocumentProvider implements + ICompilationUnitDocumentProvider { + /** + * Here for visibility issues only. + */ - /** - * Bundle of all required informations to allow working copy management. - */ + /** + * Bundle of all required informations to allow working copy management. + */ /** * Bundle of all required informations to allow working copy management. */ @@ -93,41 +94,51 @@ public class PHPDocumentProvider extends TextFileDocumentProvider implements ICo } /** - * Annotation model dealing with java marker annotations and temporary problems. - * Also acts as problem requestor for its compilation unit. Initialiy inactive. Must explicitly be - * activated. + * Annotation model dealing with java marker annotations and temporary + * problems. Also acts as problem requestor for its compilation unit. + * Initialiy inactive. Must explicitly be activated. */ - protected static class CompilationUnitAnnotationModel extends ResourceMarkerAnnotationModel implements IProblemRequestor, IProblemRequestorExtension { + protected static class CompilationUnitAnnotationModel extends + ResourceMarkerAnnotationModel implements IProblemRequestor, + IProblemRequestorExtension { private static class ProblemRequestorState { - boolean fInsideReportingSequence= false; + boolean fInsideReportingSequence = false; + List fReportedProblems; } - private ThreadLocal fProblemRequestorState= new ThreadLocal(); - private int fStateCount= 0; + private ThreadLocal fProblemRequestorState = new ThreadLocal(); + + private int fStateCount = 0; private ICompilationUnit fCompilationUnit; + private List fGeneratedAnnotations; + private IProgressMonitor fProgressMonitor; - private boolean fIsActive= false; - private ReverseMap fReverseMap= new ReverseMap(); - private List fPreviouslyOverlaid= null; - private List fCurrentlyOverlaid= new ArrayList(); + private boolean fIsActive = false; + private ReverseMap fReverseMap = new ReverseMap(); + + private List fPreviouslyOverlaid = null; + + private List fCurrentlyOverlaid = new ArrayList(); public CompilationUnitAnnotationModel(IResource resource) { super(resource); } - public void setCompilationUnit(ICompilationUnit unit) { - fCompilationUnit= unit; + public void setCompilationUnit(ICompilationUnit unit) { + fCompilationUnit = unit; } protected MarkerAnnotation createMarkerAnnotation(IMarker marker) { - String markerType= MarkerUtilities.getMarkerType(marker); - if (markerType != null && markerType.startsWith(JavaMarkerAnnotation.JAVA_MARKER_TYPE_PREFIX)) + String markerType = MarkerUtilities.getMarkerType(marker); + if (markerType != null + && markerType + .startsWith(JavaMarkerAnnotation.JAVA_MARKER_TYPE_PREFIX)) return new JavaMarkerAnnotation(marker); return super.createMarkerAnnotation(marker); } @@ -140,11 +151,11 @@ public class PHPDocumentProvider extends TextFileDocumentProvider implements ICo } protected Position createPositionFromProblem(IProblem problem) { - int start= problem.getSourceStart(); + int start = problem.getSourceStart(); if (start < 0) return null; - int length= problem.getSourceEnd() - problem.getSourceStart() + 1; + int length = problem.getSourceEnd() - problem.getSourceStart() + 1; if (length < 0) return null; @@ -155,7 +166,8 @@ public class PHPDocumentProvider extends TextFileDocumentProvider implements ICo * @see IProblemRequestor#beginReporting() */ public void beginReporting() { - ProblemRequestorState state= (ProblemRequestorState) fProblemRequestorState.get(); + ProblemRequestorState state = (ProblemRequestorState) fProblemRequestorState + .get(); if (state == null) internalBeginReporting(false); } @@ -164,23 +176,27 @@ public class PHPDocumentProvider extends TextFileDocumentProvider implements ICo * @see net.sourceforge.phpdt.internal.ui.text.java.IProblemRequestorExtension#beginReportingSequence() */ public void beginReportingSequence() { - ProblemRequestorState state= (ProblemRequestorState) fProblemRequestorState.get(); + ProblemRequestorState state = (ProblemRequestorState) fProblemRequestorState + .get(); if (state == null) internalBeginReporting(true); } /** * Sets up the infrastructure necessary for problem reporting. - * - * @param insideReportingSequence true if this method - * call is issued from inside a reporting sequence + * + * @param insideReportingSequence + * true if this method call is issued from + * inside a reporting sequence */ private void internalBeginReporting(boolean insideReportingSequence) { if (fCompilationUnit != null) { - // && fCompilationUnit.getJavaProject().isOnClasspath(fCompilationUnit)) { - ProblemRequestorState state= new ProblemRequestorState(); - state.fInsideReportingSequence= insideReportingSequence; - state.fReportedProblems= new ArrayList(); + // && + // fCompilationUnit.getJavaProject().isOnClasspath(fCompilationUnit)) + // { + ProblemRequestorState state = new ProblemRequestorState(); + state.fInsideReportingSequence = insideReportingSequence; + state.fReportedProblems = new ArrayList(); synchronized (getLockObject()) { fProblemRequestorState.set(state); ++fStateCount; @@ -193,7 +209,8 @@ public class PHPDocumentProvider extends TextFileDocumentProvider implements ICo */ public void acceptProblem(IProblem problem) { if (isActive()) { - ProblemRequestorState state= (ProblemRequestorState) fProblemRequestorState.get(); + ProblemRequestorState state = (ProblemRequestorState) fProblemRequestorState + .get(); if (state != null) state.fReportedProblems.add(problem); } @@ -203,7 +220,8 @@ public class PHPDocumentProvider extends TextFileDocumentProvider implements ICo * @see IProblemRequestor#endReporting() */ public void endReporting() { - ProblemRequestorState state= (ProblemRequestorState) fProblemRequestorState.get(); + ProblemRequestorState state = (ProblemRequestorState) fProblemRequestorState + .get(); if (state != null && !state.fInsideReportingSequence) internalEndReporting(state); } @@ -212,16 +230,17 @@ public class PHPDocumentProvider extends TextFileDocumentProvider implements ICo * @see net.sourceforge.phpdt.internal.ui.text.java.IProblemRequestorExtension#endReportingSequence() */ public void endReportingSequence() { - ProblemRequestorState state= (ProblemRequestorState) fProblemRequestorState.get(); + ProblemRequestorState state = (ProblemRequestorState) fProblemRequestorState + .get(); if (state != null && state.fInsideReportingSequence) internalEndReporting(state); } private void internalEndReporting(ProblemRequestorState state) { - int stateCount= 0; - synchronized(getLockObject()) { - -- fStateCount; - stateCount= fStateCount; + int stateCount = 0; + synchronized (getLockObject()) { + --fStateCount; + stateCount = fStateCount; fProblemRequestorState.set(null); } @@ -236,42 +255,44 @@ public class PHPDocumentProvider extends TextFileDocumentProvider implements ICo if (fProgressMonitor != null && fProgressMonitor.isCanceled()) return; - boolean temporaryProblemsChanged= false; + boolean temporaryProblemsChanged = false; synchronized (getLockObject()) { - boolean isCanceled= false; + boolean isCanceled = false; - fPreviouslyOverlaid= fCurrentlyOverlaid; - fCurrentlyOverlaid= new ArrayList(); + fPreviouslyOverlaid = fCurrentlyOverlaid; + fCurrentlyOverlaid = new ArrayList(); if (fGeneratedAnnotations.size() > 0) { - temporaryProblemsChanged= true; + temporaryProblemsChanged = true; removeAnnotations(fGeneratedAnnotations, false, true); fGeneratedAnnotations.clear(); } if (reportedProblems != null && reportedProblems.size() > 0) { - Iterator e= reportedProblems.iterator(); + Iterator e = reportedProblems.iterator(); while (e.hasNext()) { - if (fProgressMonitor != null && fProgressMonitor.isCanceled()) { - isCanceled= true; + if (fProgressMonitor != null + && fProgressMonitor.isCanceled()) { + isCanceled = true; break; } - IProblem problem= (IProblem) e.next(); - Position position= createPositionFromProblem(problem); + IProblem problem = (IProblem) e.next(); + Position position = createPositionFromProblem(problem); if (position != null) { try { - ProblemAnnotation annotation= new ProblemAnnotation(problem, fCompilationUnit); + ProblemAnnotation annotation = new ProblemAnnotation( + problem, fCompilationUnit); overlayMarkers(position, annotation); addAnnotation(annotation, position, false); fGeneratedAnnotations.add(annotation); - temporaryProblemsChanged= true; + temporaryProblemsChanged = true; } catch (BadLocationException x) { // ignore invalid position } @@ -280,7 +301,7 @@ public class PHPDocumentProvider extends TextFileDocumentProvider implements ICo } removeMarkerOverlays(isCanceled); - fPreviouslyOverlaid= null; + fPreviouslyOverlaid = null; } if (temporaryProblemsChanged) @@ -291,9 +312,10 @@ public class PHPDocumentProvider extends TextFileDocumentProvider implements ICo if (isCanceled) { fCurrentlyOverlaid.addAll(fPreviouslyOverlaid); } else if (fPreviouslyOverlaid != null) { - Iterator e= fPreviouslyOverlaid.iterator(); + Iterator e = fPreviouslyOverlaid.iterator(); while (e.hasNext()) { - JavaMarkerAnnotation annotation= (JavaMarkerAnnotation) e.next(); + JavaMarkerAnnotation annotation = (JavaMarkerAnnotation) e + .next(); annotation.setOverlay(null); } } @@ -301,11 +323,13 @@ public class PHPDocumentProvider extends TextFileDocumentProvider implements ICo /** * Overlays value with problem annotation. + * * @param problemAnnotation */ - private void setOverlay(Object value, ProblemAnnotation problemAnnotation) { - if (value instanceof JavaMarkerAnnotation) { - JavaMarkerAnnotation annotation= (JavaMarkerAnnotation) value; + private void setOverlay(Object value, + ProblemAnnotation problemAnnotation) { + if (value instanceof JavaMarkerAnnotation) { + JavaMarkerAnnotation annotation = (JavaMarkerAnnotation) value; if (annotation.isProblem()) { annotation.setOverlay(problemAnnotation); fPreviouslyOverlaid.remove(annotation); @@ -315,10 +339,11 @@ public class PHPDocumentProvider extends TextFileDocumentProvider implements ICo } } - private void overlayMarkers(Position position, ProblemAnnotation problemAnnotation) { - Object value= getAnnotations(position); + private void overlayMarkers(Position position, + ProblemAnnotation problemAnnotation) { + Object value = getAnnotations(position); if (value instanceof List) { - List list= (List) value; + List list = (List) value; for (Iterator e = list.iterator(); e.hasNext();) setOverlay(e.next(), problemAnnotation); } else { @@ -327,10 +352,11 @@ public class PHPDocumentProvider extends TextFileDocumentProvider implements ICo } /** - * Tells this annotation model to collect temporary problems from now on. + * Tells this annotation model to collect temporary problems from now + * on. */ private void startCollectingProblems() { - fGeneratedAnnotations= new ArrayList(); + fGeneratedAnnotations = new ArrayList(); } /** @@ -339,7 +365,7 @@ public class PHPDocumentProvider extends TextFileDocumentProvider implements ICo private void stopCollectingProblems() { if (fGeneratedAnnotations != null) removeAnnotations(fGeneratedAnnotations, true, true); - fGeneratedAnnotations= null; + fGeneratedAnnotations = null; } /* @@ -353,7 +379,7 @@ public class PHPDocumentProvider extends TextFileDocumentProvider implements ICo * @see IProblemRequestorExtension#setProgressMonitor(IProgressMonitor) */ public void setProgressMonitor(IProgressMonitor monitor) { - fProgressMonitor= monitor; + fProgressMonitor = monitor; } /* @@ -361,7 +387,7 @@ public class PHPDocumentProvider extends TextFileDocumentProvider implements ICo */ public void setIsActive(boolean isActive) { if (fIsActive != isActive) { - fIsActive= isActive; + fIsActive = isActive; if (fIsActive) startCollectingProblems(); else @@ -376,17 +402,18 @@ public class PHPDocumentProvider extends TextFileDocumentProvider implements ICo /* * @see AnnotationModel#addAnnotation(Annotation, Position, boolean) */ - protected void addAnnotation(Annotation annotation, Position position, boolean fireModelChanged) throws BadLocationException { + protected void addAnnotation(Annotation annotation, Position position, + boolean fireModelChanged) throws BadLocationException { super.addAnnotation(annotation, position, fireModelChanged); - Object cached= fReverseMap.get(position); + Object cached = fReverseMap.get(position); if (cached == null) fReverseMap.put(position, annotation); else if (cached instanceof List) { - List list= (List) cached; + List list = (List) cached; list.add(annotation); } else if (cached instanceof Annotation) { - List list= new ArrayList(2); + List list = new ArrayList(2); list.add(cached); list.add(annotation); fReverseMap.put(position, list); @@ -404,11 +431,12 @@ public class PHPDocumentProvider extends TextFileDocumentProvider implements ICo /* * @see AnnotationModel#removeAnnotation(Annotation, boolean) */ - protected void removeAnnotation(Annotation annotation, boolean fireModelChanged) { - Position position= getPosition(annotation); - Object cached= fReverseMap.get(position); + protected void removeAnnotation(Annotation annotation, + boolean fireModelChanged) { + Position position = getPosition(annotation); + Object cached = fReverseMap.get(position); if (cached instanceof List) { - List list= (List) cached; + List list = (List) cached; list.remove(annotation); if (list.size() == 1) { fReverseMap.put(position, list.get(0)); @@ -421,121 +449,137 @@ public class PHPDocumentProvider extends TextFileDocumentProvider implements ICo } } + protected static class GlobalAnnotationModelListener implements + IAnnotationModelListener, IAnnotationModelListenerExtension { + private ListenerList fListenerList; - protected static class GlobalAnnotationModelListener implements IAnnotationModelListener, IAnnotationModelListenerExtension { - - private ListenerList fListenerList; - - public GlobalAnnotationModelListener() { - fListenerList = new ListenerList(); - } - - public void addListener(IAnnotationModelListener listener) { - fListenerList.add(listener); - } - - /** - * @see IAnnotationModelListenerExtension#modelChanged(AnnotationModelEvent) - */ - public void modelChanged(AnnotationModelEvent event) { - Object[] listeners = fListenerList.getListeners(); - for (int i = 0; i < listeners.length; i++) { - Object curr = listeners[i]; - if (curr instanceof IAnnotationModelListenerExtension) { - ((IAnnotationModelListenerExtension) curr).modelChanged(event); - } - } - } - - /** - * @see IAnnotationModelListener#modelChanged(IAnnotationModel) - */ - public void modelChanged(IAnnotationModel model) { - Object[] listeners = fListenerList.getListeners(); - for (int i = 0; i < listeners.length; i++) { - ((IAnnotationModelListener) listeners[i]).modelChanged(model); - } - } - - public void removeListener(IAnnotationModelListener listener) { - fListenerList.remove(listener); - } - } - - /** + public GlobalAnnotationModelListener() { + fListenerList = new ListenerList(); + } + + public void addListener(IAnnotationModelListener listener) { + fListenerList.add(listener); + } + + /** + * @see IAnnotationModelListenerExtension#modelChanged(AnnotationModelEvent) + */ + public void modelChanged(AnnotationModelEvent event) { + Object[] listeners = fListenerList.getListeners(); + for (int i = 0; i < listeners.length; i++) { + Object curr = listeners[i]; + if (curr instanceof IAnnotationModelListenerExtension) { + ((IAnnotationModelListenerExtension) curr) + .modelChanged(event); + } + } + } + + /** + * @see IAnnotationModelListener#modelChanged(IAnnotationModel) + */ + public void modelChanged(IAnnotationModel model) { + Object[] listeners = fListenerList.getListeners(); + for (int i = 0; i < listeners.length; i++) { + ((IAnnotationModelListener) listeners[i]).modelChanged(model); + } + } + + public void removeListener(IAnnotationModelListener listener) { + fListenerList.remove(listener); + } + } + + /** * Annotation representating an IProblem. */ - static public class ProblemAnnotation extends Annotation implements IJavaAnnotation, IAnnotationPresentation { + static public class ProblemAnnotation extends Annotation implements + IJavaAnnotation, IAnnotationPresentation { - private static final String SPELLING_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.spelling"; + private static final String SPELLING_ANNOTATION_TYPE = "org.eclipse.ui.workbench.texteditor.spelling"; - //XXX: To be fully correct these constants should be non-static + // XXX: To be fully correct these constants should be non-static /** * The layer in which task problem annotations are located. */ private static final int TASK_LAYER; + /** * The layer in which info problem annotations are located. */ private static final int INFO_LAYER; + /** - * The layer in which warning problem annotations representing are located. + * The layer in which warning problem annotations representing are + * located. */ private static final int WARNING_LAYER; + /** - * The layer in which error problem annotations representing are located. + * The layer in which error problem annotations representing are + * located. */ private static final int ERROR_LAYER; static { - AnnotationPreferenceLookup lookup= EditorsUI.getAnnotationPreferenceLookup(); - TASK_LAYER= computeLayer("org.eclipse.ui.workbench.texteditor.task", lookup); //$NON-NLS-1$ - INFO_LAYER= computeLayer("net.sourceforge.phpdt.ui.info", lookup); //$NON-NLS-1$ - WARNING_LAYER= computeLayer("net.sourceforge.phpdt.ui.warning", lookup); //$NON-NLS-1$ - ERROR_LAYER= computeLayer("net.sourceforge.phpdt.ui.error", lookup); //$NON-NLS-1$ + AnnotationPreferenceLookup lookup = EditorsUI + .getAnnotationPreferenceLookup(); + TASK_LAYER = computeLayer( + "org.eclipse.ui.workbench.texteditor.task", lookup); //$NON-NLS-1$ + INFO_LAYER = computeLayer("net.sourceforge.phpdt.ui.info", lookup); //$NON-NLS-1$ + WARNING_LAYER = computeLayer( + "net.sourceforge.phpdt.ui.warning", lookup); //$NON-NLS-1$ + ERROR_LAYER = computeLayer("net.sourceforge.phpdt.ui.error", lookup); //$NON-NLS-1$ } - private static int computeLayer(String annotationType, AnnotationPreferenceLookup lookup) { - Annotation annotation= new Annotation(annotationType, false, null); - AnnotationPreference preference= lookup.getAnnotationPreference(annotation); + private static int computeLayer(String annotationType, + AnnotationPreferenceLookup lookup) { + Annotation annotation = new Annotation(annotationType, false, null); + AnnotationPreference preference = lookup + .getAnnotationPreference(annotation); if (preference != null) return preference.getPresentationLayer() + 1; else return IAnnotationAccessExtension.DEFAULT_LAYER + 1; } -// private static Image fgQuickFixImage; -// private static Image fgQuickFixErrorImage; -// private static boolean fgQuickFixImagesInitialized= false; + // private static Image fgQuickFixImage; + // private static Image fgQuickFixErrorImage; + // private static boolean fgQuickFixImagesInitialized= false; private ICompilationUnit fCompilationUnit; + private List fOverlaids; + private IProblem fProblem; + private Image fImage; - private boolean fQuickFixImagesInitialized= false; - private int fLayer= IAnnotationAccessExtension.DEFAULT_LAYER; + + private boolean fQuickFixImagesInitialized = false; + + private int fLayer = IAnnotationAccessExtension.DEFAULT_LAYER; public ProblemAnnotation(IProblem problem, ICompilationUnit cu) { - fProblem= problem; - fCompilationUnit= cu; + fProblem = problem; + fCompilationUnit = cu; if (SpellProblem.Spelling == fProblem.getID()) { setType(SPELLING_ANNOTATION_TYPE); - fLayer= WARNING_LAYER; + fLayer = WARNING_LAYER; } else if (IProblem.Task == fProblem.getID()) { setType(JavaMarkerAnnotation.TASK_ANNOTATION_TYPE); - fLayer= TASK_LAYER; + fLayer = TASK_LAYER; } else if (fProblem.isWarning()) { setType(JavaMarkerAnnotation.WARNING_ANNOTATION_TYPE); - fLayer= WARNING_LAYER; + fLayer = WARNING_LAYER; } else if (fProblem.isError()) { setType(JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE); - fLayer= ERROR_LAYER; + fLayer = ERROR_LAYER; } else { setType(JavaMarkerAnnotation.INFO_ANNOTATION_TYPE); - fLayer= INFO_LAYER; + fLayer = INFO_LAYER; } } @@ -548,24 +592,29 @@ public class PHPDocumentProvider extends TextFileDocumentProvider implements ICo private void initializeImages() { // http://bugs.eclipse.org/bugs/show_bug.cgi?id=18936 -// if (!fQuickFixImagesInitialized) { -// if (isProblem() && indicateQuixFixableProblems() && JavaCorrectionProcessor.hasCorrections(this)) { // no light bulb for tasks -// if (!fgQuickFixImagesInitialized) { -// fgQuickFixImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_PROBLEM); -// fgQuickFixErrorImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_ERROR); -// fgQuickFixImagesInitialized= true; -// } -// if (JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE.equals(getType())) -// fImage= fgQuickFixErrorImage; -// else -// fImage= fgQuickFixImage; -// } -// fQuickFixImagesInitialized= true; -// } + // if (!fQuickFixImagesInitialized) { + // if (isProblem() && indicateQuixFixableProblems() && + // JavaCorrectionProcessor.hasCorrections(this)) { // no light bulb + // for tasks + // if (!fgQuickFixImagesInitialized) { + // fgQuickFixImage= + // JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_PROBLEM); + // fgQuickFixErrorImage= + // JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_ERROR); + // fgQuickFixImagesInitialized= true; + // } + // if (JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE.equals(getType())) + // fImage= fgQuickFixErrorImage; + // else + // fImage= fgQuickFixImage; + // } + // fQuickFixImagesInitialized= true; + // } } private boolean indicateQuixFixableProblems() { - return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CORRECTION_INDICATION); + return PreferenceConstants.getPreferenceStore().getBoolean( + PreferenceConstants.EDITOR_CORRECTION_INDICATION); } /* @@ -574,8 +623,10 @@ public class PHPDocumentProvider extends TextFileDocumentProvider implements ICo public void paint(GC gc, Canvas canvas, Rectangle r) { initializeImages(); if (fImage != null) - ImageUtilities.drawImage(fImage, gc, canvas, r, SWT.CENTER, SWT.TOP); + ImageUtilities.drawImage(fImage, gc, canvas, r, SWT.CENTER, + SWT.TOP); } + /* * @see IJavaAnnotation#getImage(Display) */ @@ -609,10 +660,10 @@ public class PHPDocumentProvider extends TextFileDocumentProvider implements ICo * @see IJavaAnnotation#isProblem() */ public boolean isProblem() { - String type= getType(); - return JavaMarkerAnnotation.WARNING_ANNOTATION_TYPE.equals(type) || - JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE.equals(type) || - SPELLING_ANNOTATION_TYPE.equals(type); + String type = getType(); + return JavaMarkerAnnotation.WARNING_ANNOTATION_TYPE.equals(type) + || JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE.equals(type) + || SPELLING_ANNOTATION_TYPE.equals(type); } /* @@ -634,7 +685,7 @@ public class PHPDocumentProvider extends TextFileDocumentProvider implements ICo */ public void addOverlaid(IJavaAnnotation annotation) { if (fOverlaids == null) - fOverlaids= new ArrayList(1); + fOverlaids = new ArrayList(1); fOverlaids.add(annotation); } @@ -645,7 +696,7 @@ public class PHPDocumentProvider extends TextFileDocumentProvider implements ICo if (fOverlaids != null) { fOverlaids.remove(annotation); if (fOverlaids.size() == 0) - fOverlaids= null; + fOverlaids = null; } } @@ -666,902 +717,979 @@ public class PHPDocumentProvider extends TextFileDocumentProvider implements ICo } } + /** + * Internal structure for mapping positions to some value. The reason for + * this specific structure is that positions can change over time. Thus a + * lookup is based on value and not on hash value. + */ + protected static class ReverseMap { + + static class Entry { + Position fPosition; + + Object fValue; + } + + private int fAnchor = 0; + + private List fList = new ArrayList(2); + + public ReverseMap() { + } + + public void clear() { + fList.clear(); + } + + public Object get(Position position) { + + Entry entry; + + // behind anchor + int length = fList.size(); + for (int i = fAnchor; i < length; i++) { + entry = (Entry) fList.get(i); + if (entry.fPosition.equals(position)) { + fAnchor = i; + return entry.fValue; + } + } + + // before anchor + for (int i = 0; i < fAnchor; i++) { + entry = (Entry) fList.get(i); + if (entry.fPosition.equals(position)) { + fAnchor = i; + return entry.fValue; + } + } + + return null; + } + + private int getIndex(Position position) { + Entry entry; + int length = fList.size(); + for (int i = 0; i < length; i++) { + entry = (Entry) fList.get(i); + if (entry.fPosition.equals(position)) + return i; + } + return -1; + } + + public void put(Position position, Object value) { + int index = getIndex(position); + if (index == -1) { + Entry entry = new Entry(); + entry.fPosition = position; + entry.fValue = value; + fList.add(entry); + } else { + Entry entry = (Entry) fList.get(index); + entry.fValue = value; + } + } + + public void remove(Position position) { + int index = getIndex(position); + if (index > -1) + fList.remove(index); + } + } + + /** + * Document that can also be used by a background reconciler. + */ + protected static class PartiallySynchronizedDocument extends Document { + + /* + * @see IDocumentExtension#startSequentialRewrite(boolean) + */ + synchronized public void startSequentialRewrite(boolean normalized) { + super.startSequentialRewrite(normalized); + } + + /* + * @see IDocumentExtension#stopSequentialRewrite() + */ + synchronized public void stopSequentialRewrite() { + super.stopSequentialRewrite(); + } + + /* + * @see IDocument#get() + */ + synchronized public String get() { + return super.get(); + } + + /* + * @see IDocument#get(int, int) + */ + synchronized public String get(int offset, int length) + throws BadLocationException { + return super.get(offset, length); + } + + /* + * @see IDocument#getChar(int) + */ + synchronized public char getChar(int offset) + throws BadLocationException { + return super.getChar(offset); + } + + /* + * @see IDocument#replace(int, int, String) + */ + synchronized public void replace(int offset, int length, String text) + throws BadLocationException { + super.replace(offset, length, text); + } - /** - * Internal structure for mapping positions to some value. - * The reason for this specific structure is that positions can - * change over time. Thus a lookup is based on value and not - * on hash value. - */ - protected static class ReverseMap { - - static class Entry { - Position fPosition; - Object fValue; - } - private int fAnchor = 0; - - private List fList = new ArrayList(2); - - public ReverseMap() { - } - - public void clear() { - fList.clear(); - } - - public Object get(Position position) { - - Entry entry; - - // behind anchor - int length = fList.size(); - for (int i = fAnchor; i < length; i++) { - entry = (Entry) fList.get(i); - if (entry.fPosition.equals(position)) { - fAnchor = i; - return entry.fValue; - } - } - - // before anchor - for (int i = 0; i < fAnchor; i++) { - entry = (Entry) fList.get(i); - if (entry.fPosition.equals(position)) { - fAnchor = i; - return entry.fValue; - } - } - - return null; - } - - private int getIndex(Position position) { - Entry entry; - int length = fList.size(); - for (int i = 0; i < length; i++) { - entry = (Entry) fList.get(i); - if (entry.fPosition.equals(position)) - return i; - } - return -1; - } - - public void put(Position position, Object value) { - int index = getIndex(position); - if (index == -1) { - Entry entry = new Entry(); - entry.fPosition = position; - entry.fValue = value; - fList.add(entry); - } else { - Entry entry = (Entry) fList.get(index); - entry.fValue = value; - } - } - - public void remove(Position position) { - int index = getIndex(position); - if (index > -1) - fList.remove(index); - } - } - - /** - * Document that can also be used by a background reconciler. - */ - protected static class PartiallySynchronizedDocument extends Document { - - /* - * @see IDocumentExtension#startSequentialRewrite(boolean) - */ - synchronized public void startSequentialRewrite(boolean normalized) { - super.startSequentialRewrite(normalized); - } - - /* - * @see IDocumentExtension#stopSequentialRewrite() - */ - synchronized public void stopSequentialRewrite() { - super.stopSequentialRewrite(); - } - - /* - * @see IDocument#get() - */ - synchronized public String get() { - return super.get(); - } - - /* - * @see IDocument#get(int, int) - */ - synchronized public String get(int offset, int length) throws BadLocationException { - return super.get(offset, length); - } - - /* - * @see IDocument#getChar(int) - */ - synchronized public char getChar(int offset) throws BadLocationException { - return super.getChar(offset); - } - - /* - * @see IDocument#replace(int, int, String) - */ - synchronized public void replace(int offset, int length, String text) throws BadLocationException { - super.replace(offset, length, text); - } - - /* - * @see IDocument#set(String) - */ - synchronized public void set(String text) { - super.set(text); - } - }; - // - // private static PHPPartitionScanner HTML_PARTITION_SCANNER = null; - // - // private static PHPPartitionScanner PHP_PARTITION_SCANNER = null; - // private static PHPPartitionScanner SMARTY_PARTITION_SCANNER = null; - // - // // private final static String[] TYPES= new String[] { PHPPartitionScanner.PHP, PHPPartitionScanner.JAVA_DOC, PHPPartitionScanner.JAVA_MULTILINE_COMMENT }; - // private final static String[] TYPES = - // new String[] { - // IPHPPartitionScannerConstants.PHP, - // IPHPPartitionScannerConstants.PHP_MULTILINE_COMMENT, - // IPHPPartitionScannerConstants.HTML, - // IPHPPartitionScannerConstants.HTML_MULTILINE_COMMENT, - // IPHPPartitionScannerConstants.JAVASCRIPT, - // IPHPPartitionScannerConstants.CSS, - // IPHPPartitionScannerConstants.SMARTY, - // IPHPPartitionScannerConstants.SMARTY_MULTILINE_COMMENT }; - // private static PHPPartitionScanner XML_PARTITION_SCANNER = null; - - /* Preference key for temporary problems */ - private final static String HANDLE_TEMPORARY_PROBLEMS = PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS; - - /** Indicates whether the save has been initialized by this provider */ - private boolean fIsAboutToSave = false; - /** The save policy used by this provider */ - private ISavePolicy fSavePolicy; - /** Internal property changed listener */ - private IPropertyChangeListener fPropertyListener; - - /** annotation model listener added to all created CU annotation models */ - private GlobalAnnotationModelListener fGlobalAnnotationModelListener; - - public PHPDocumentProvider() { -// IDocumentProvider provider= new TextFileDocumentProvider(new JavaStorageDocumentProvider()); - IDocumentProvider provider= new TextFileDocumentProvider(); - provider= new ForwardingDocumentProvider(IPHPPartitions.PHP_PARTITIONING, new JavaDocumentSetupParticipant(), provider); - setParentDocumentProvider(provider); - - fGlobalAnnotationModelListener= new GlobalAnnotationModelListener(); - fPropertyListener= new IPropertyChangeListener() { - public void propertyChange(PropertyChangeEvent event) { - if (HANDLE_TEMPORARY_PROBLEMS.equals(event.getProperty())) - enableHandlingTemporaryProblems(); + /* + * @see IDocument#set(String) + */ + synchronized public void set(String text) { + super.set(text); } }; - PHPeclipsePlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyListener); - - } - - /** - * Sets the document provider's save policy. - */ - public void setSavePolicy(ISavePolicy savePolicy) { - fSavePolicy = savePolicy; - } - - /** - * Creates a compilation unit from the given file. - * - * @param file the file from which to create the compilation unit - */ - protected ICompilationUnit createCompilationUnit(IFile file) { - Object element = JavaCore.create(file); - if (element instanceof ICompilationUnit) - return (ICompilationUnit) element; - return null; - } - - - /* + + // + // private static PHPPartitionScanner HTML_PARTITION_SCANNER = null; + // + // private static PHPPartitionScanner PHP_PARTITION_SCANNER = null; + // private static PHPPartitionScanner SMARTY_PARTITION_SCANNER = null; + // + // // private final static String[] TYPES= new String[] { + // PHPPartitionScanner.PHP, PHPPartitionScanner.JAVA_DOC, + // PHPPartitionScanner.JAVA_MULTILINE_COMMENT }; + // private final static String[] TYPES = + // new String[] { + // IPHPPartitionScannerConstants.PHP, + // IPHPPartitionScannerConstants.PHP_MULTILINE_COMMENT, + // IPHPPartitionScannerConstants.HTML, + // IPHPPartitionScannerConstants.HTML_MULTILINE_COMMENT, + // IPHPPartitionScannerConstants.JAVASCRIPT, + // IPHPPartitionScannerConstants.CSS, + // IPHPPartitionScannerConstants.SMARTY, + // IPHPPartitionScannerConstants.SMARTY_MULTILINE_COMMENT }; + // private static PHPPartitionScanner XML_PARTITION_SCANNER = null; + + /* Preference key for temporary problems */ + private final static String HANDLE_TEMPORARY_PROBLEMS = PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS; + + /** Indicates whether the save has been initialized by this provider */ + private boolean fIsAboutToSave = false; + + /** The save policy used by this provider */ + private ISavePolicy fSavePolicy; + + /** Internal property changed listener */ + private IPropertyChangeListener fPropertyListener; + + /** annotation model listener added to all created CU annotation models */ + private GlobalAnnotationModelListener fGlobalAnnotationModelListener; + + public PHPDocumentProvider() { + // IDocumentProvider provider= new TextFileDocumentProvider(new + // JavaStorageDocumentProvider()); + IDocumentProvider provider = new TextFileDocumentProvider(); + provider = new ForwardingDocumentProvider( + IPHPPartitions.PHP_PARTITIONING, + new JavaDocumentSetupParticipant(), provider); + setParentDocumentProvider(provider); + + fGlobalAnnotationModelListener = new GlobalAnnotationModelListener(); + fPropertyListener = new IPropertyChangeListener() { + public void propertyChange(PropertyChangeEvent event) { + if (HANDLE_TEMPORARY_PROBLEMS.equals(event.getProperty())) + enableHandlingTemporaryProblems(); + } + }; + PHPeclipsePlugin.getDefault().getPreferenceStore() + .addPropertyChangeListener(fPropertyListener); + + } + + /** + * Sets the document provider's save policy. + */ + public void setSavePolicy(ISavePolicy savePolicy) { + fSavePolicy = savePolicy; + } + + /** + * Creates a compilation unit from the given file. + * + * @param file + * the file from which to create the compilation unit + */ + protected ICompilationUnit createCompilationUnit(IFile file) { + Object element = JavaCore.create(file); + if (element instanceof ICompilationUnit) + return (ICompilationUnit) element; + return null; + } + + /* * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createEmptyFileInfo() */ protected FileInfo createEmptyFileInfo() { return new CompilationUnitInfo(); } + /* * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createAnnotationModel(org.eclipse.core.resources.IFile) */ protected IAnnotationModel createAnnotationModel(IFile file) { return new CompilationUnitAnnotationModel(file); } - /* - * @see AbstractDocumentProvider#createElementInfo(Object) - */ -// protected ElementInfo createElementInfo(Object element) throws CoreException { -// -// if (!(element instanceof IFileEditorInput)) -// return super.createElementInfo(element); -// -// IFileEditorInput input = (IFileEditorInput) element; -// ICompilationUnit original = createCompilationUnit(input.getFile()); -// if (original != null) { -// -// try { -// -// try { -// refreshFile(input.getFile()); -// } catch (CoreException x) { -// handleCoreException(x, PHPEditorMessages.getString("PHPDocumentProvider.error.createElementInfo")); //$NON-NLS-1$ -// } -// -// IAnnotationModel m = createCompilationUnitAnnotationModel(input); -// IProblemRequestor r = m instanceof IProblemRequestor ? (IProblemRequestor) m : null; -// ICompilationUnit c = (ICompilationUnit) original.getSharedWorkingCopy(getProgressMonitor(), fBufferFactory, r); -// -// DocumentAdapter a = null; -// try { -// a = (DocumentAdapter) c.getBuffer(); -// } catch (ClassCastException x) { -// IStatus status = new Status(IStatus.ERROR, PHPeclipsePlugin.PLUGIN_ID, PHPStatusConstants.TEMPLATE_IO_EXCEPTION, "Shared working copy has wrong buffer", x); //$NON-NLS-1$ -// throw new CoreException(status); -// } -// -// _FileSynchronizer f = new _FileSynchronizer(input); -// f.install(); -// -// CompilationUnitInfo info = new CompilationUnitInfo(a.getDocument(), m, f, c); -// info.setModificationStamp(computeModificationStamp(input.getFile())); -// info.fStatus = a.getStatus(); -// info.fEncoding = getPersistedEncoding(input); -// -// if (r instanceof IProblemRequestorExtension) { -// IProblemRequestorExtension extension = (IProblemRequestorExtension) r; -// extension.setIsActive(isHandlingTemporaryProblems()); -// } -// m.addAnnotationModelListener(fGlobalAnnotationModelListener); -// -// return info; -// -// } catch (JavaModelException x) { -// throw new CoreException(x.getStatus()); -// } -// } else { -// return super.createElementInfo(element); -// } -// } - - /* - * @see AbstractDocumentProvider#disposeElementInfo(Object, ElementInfo) - */ -// protected void disposeElementInfo(Object element, ElementInfo info) { -// -// if (info instanceof CompilationUnitInfo) { -// CompilationUnitInfo cuInfo = (CompilationUnitInfo) info; -// cuInfo.fCopy.destroy(); -// cuInfo.fModel.removeAnnotationModelListener(fGlobalAnnotationModelListener); -// } -// -// super.disposeElementInfo(element, info); -// } - - /* - * @see AbstractDocumentProvider#doSaveDocument(IProgressMonitor, Object, IDocument, boolean) - */ -// protected void doSaveDocument(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite) -// throws CoreException { -// -// ElementInfo elementInfo = getElementInfo(element); -// if (elementInfo instanceof CompilationUnitInfo) { -// CompilationUnitInfo info = (CompilationUnitInfo) elementInfo; -// -// // update structure, assumes lock on info.fCopy -// info.fCopy.reconcile(); -// -// ICompilationUnit original = (ICompilationUnit) info.fCopy.getOriginalElement(); -// IResource resource = original.getResource(); -// -// if (resource == null) { -// // underlying resource has been deleted, just recreate file, ignore the rest -// super.doSaveDocument(monitor, element, document, overwrite); -// return; -// } -// -// if (resource != null && !overwrite) -// checkSynchronizationState(info.fModificationStamp, resource); -// -// if (fSavePolicy != null) -// fSavePolicy.preSave(info.fCopy); -// -// // inform about the upcoming content change -// fireElementStateChanging(element); -// try { -// fIsAboutToSave = true; -// // commit working copy -// info.fCopy.commit(overwrite, monitor); -// } catch (CoreException x) { -// // inform about the failure -// fireElementStateChangeFailed(element); -// throw x; -// } catch (RuntimeException x) { -// // inform about the failure -// fireElementStateChangeFailed(element); -// throw x; -// } finally { -// fIsAboutToSave = false; -// } -// -// // If here, the dirty state of the editor will change to "not dirty". -// // Thus, the state changing flag will be reset. -// -// AbstractMarkerAnnotationModel model = (AbstractMarkerAnnotationModel) info.fModel; -// model.updateMarkers(info.fDocument); -// -// if (resource != null) -// info.setModificationStamp(computeModificationStamp(resource)); -// -// if (fSavePolicy != null) { -// ICompilationUnit unit = fSavePolicy.postSave(original); -// if (unit != null) { -// IResource r = unit.getResource(); -// IMarker[] markers = r.findMarkers(IMarker.MARKER, true, IResource.DEPTH_ZERO); -// if (markers != null && markers.length > 0) { -// for (int i = 0; i < markers.length; i++) -// model.updateMarker(markers[i], info.fDocument, null); -// } -// } -// } -// -// } else { -// super.doSaveDocument(monitor, element, document, overwrite); -// } -// } /* + * @see AbstractDocumentProvider#createElementInfo(Object) + */ + // protected ElementInfo createElementInfo(Object element) throws + // CoreException { + // + // if (!(element instanceof IFileEditorInput)) + // return super.createElementInfo(element); + // + // IFileEditorInput input = (IFileEditorInput) element; + // ICompilationUnit original = createCompilationUnit(input.getFile()); + // if (original != null) { + // + // try { + // + // try { + // refreshFile(input.getFile()); + // } catch (CoreException x) { + // handleCoreException(x, + // PHPEditorMessages.getString("PHPDocumentProvider.error.createElementInfo")); + // //$NON-NLS-1$ + // } + // + // IAnnotationModel m = createCompilationUnitAnnotationModel(input); + // IProblemRequestor r = m instanceof IProblemRequestor ? + // (IProblemRequestor) m : null; + // ICompilationUnit c = (ICompilationUnit) + // original.getSharedWorkingCopy(getProgressMonitor(), fBufferFactory, r); + // + // DocumentAdapter a = null; + // try { + // a = (DocumentAdapter) c.getBuffer(); + // } catch (ClassCastException x) { + // IStatus status = new Status(IStatus.ERROR, PHPeclipsePlugin.PLUGIN_ID, + // PHPStatusConstants.TEMPLATE_IO_EXCEPTION, "Shared working copy has wrong + // buffer", x); //$NON-NLS-1$ + // throw new CoreException(status); + // } + // + // _FileSynchronizer f = new _FileSynchronizer(input); + // f.install(); + // + // CompilationUnitInfo info = new CompilationUnitInfo(a.getDocument(), m, f, + // c); + // info.setModificationStamp(computeModificationStamp(input.getFile())); + // info.fStatus = a.getStatus(); + // info.fEncoding = getPersistedEncoding(input); + // + // if (r instanceof IProblemRequestorExtension) { + // IProblemRequestorExtension extension = (IProblemRequestorExtension) r; + // extension.setIsActive(isHandlingTemporaryProblems()); + // } + // m.addAnnotationModelListener(fGlobalAnnotationModelListener); + // + // return info; + // + // } catch (JavaModelException x) { + // throw new CoreException(x.getStatus()); + // } + // } else { + // return super.createElementInfo(element); + // } + // } + /* + * @see AbstractDocumentProvider#disposeElementInfo(Object, ElementInfo) + */ + // protected void disposeElementInfo(Object element, ElementInfo info) { + // + // if (info instanceof CompilationUnitInfo) { + // CompilationUnitInfo cuInfo = (CompilationUnitInfo) info; + // cuInfo.fCopy.destroy(); + // cuInfo.fModel.removeAnnotationModelListener(fGlobalAnnotationModelListener); + // } + // + // super.disposeElementInfo(element, info); + // } + /* + * @see AbstractDocumentProvider#doSaveDocument(IProgressMonitor, Object, + * IDocument, boolean) + */ + // protected void doSaveDocument(IProgressMonitor monitor, Object element, + // IDocument document, boolean overwrite) + // throws CoreException { + // + // ElementInfo elementInfo = getElementInfo(element); + // if (elementInfo instanceof CompilationUnitInfo) { + // CompilationUnitInfo info = (CompilationUnitInfo) elementInfo; + // + // // update structure, assumes lock on info.fCopy + // info.fCopy.reconcile(); + // + // ICompilationUnit original = (ICompilationUnit) + // info.fCopy.getOriginalElement(); + // IResource resource = original.getResource(); + // + // if (resource == null) { + // // underlying resource has been deleted, just recreate file, ignore the + // rest + // super.doSaveDocument(monitor, element, document, overwrite); + // return; + // } + // + // if (resource != null && !overwrite) + // checkSynchronizationState(info.fModificationStamp, resource); + // + // if (fSavePolicy != null) + // fSavePolicy.preSave(info.fCopy); + // + // // inform about the upcoming content change + // fireElementStateChanging(element); + // try { + // fIsAboutToSave = true; + // // commit working copy + // info.fCopy.commit(overwrite, monitor); + // } catch (CoreException x) { + // // inform about the failure + // fireElementStateChangeFailed(element); + // throw x; + // } catch (RuntimeException x) { + // // inform about the failure + // fireElementStateChangeFailed(element); + // throw x; + // } finally { + // fIsAboutToSave = false; + // } + // + // // If here, the dirty state of the editor will change to "not dirty". + // // Thus, the state changing flag will be reset. + // + // AbstractMarkerAnnotationModel model = (AbstractMarkerAnnotationModel) + // info.fModel; + // model.updateMarkers(info.fDocument); + // + // if (resource != null) + // info.setModificationStamp(computeModificationStamp(resource)); + // + // if (fSavePolicy != null) { + // ICompilationUnit unit = fSavePolicy.postSave(original); + // if (unit != null) { + // IResource r = unit.getResource(); + // IMarker[] markers = r.findMarkers(IMarker.MARKER, true, + // IResource.DEPTH_ZERO); + // if (markers != null && markers.length > 0) { + // for (int i = 0; i < markers.length; i++) + // model.updateMarker(markers[i], info.fDocument, null); + // } + // } + // } + // + // } else { + // super.doSaveDocument(monitor, element, document, overwrite); + // } + // } + /* * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createFileInfo(java.lang.Object) */ protected FileInfo createFileInfo(Object element) throws CoreException { if (!(element instanceof IFileEditorInput)) return null; - IFileEditorInput input= (IFileEditorInput) element; - ICompilationUnit original= createCompilationUnit(input.getFile()); + IFileEditorInput input = (IFileEditorInput) element; + ICompilationUnit original = createCompilationUnit(input.getFile()); if (original == null) return null; - FileInfo info= super.createFileInfo(element); + FileInfo info = super.createFileInfo(element); if (!(info instanceof CompilationUnitInfo)) return null; - CompilationUnitInfo cuInfo= (CompilationUnitInfo) info; + CompilationUnitInfo cuInfo = (CompilationUnitInfo) info; setUpSynchronization(cuInfo); - IProblemRequestor requestor= cuInfo.fModel instanceof IProblemRequestor ? (IProblemRequestor) cuInfo.fModel : null; + IProblemRequestor requestor = cuInfo.fModel instanceof IProblemRequestor ? (IProblemRequestor) cuInfo.fModel + : null; original.becomeWorkingCopy(requestor, getProgressMonitor()); - cuInfo.fCopy= original; + cuInfo.fCopy = original; - if (cuInfo.fModel instanceof CompilationUnitAnnotationModel) { - CompilationUnitAnnotationModel model= (CompilationUnitAnnotationModel) cuInfo.fModel; + if (cuInfo.fModel instanceof CompilationUnitAnnotationModel) { + CompilationUnitAnnotationModel model = (CompilationUnitAnnotationModel) cuInfo.fModel; model.setCompilationUnit(cuInfo.fCopy); } if (cuInfo.fModel != null) - cuInfo.fModel.addAnnotationModelListener(fGlobalAnnotationModelListener); + cuInfo.fModel + .addAnnotationModelListener(fGlobalAnnotationModelListener); if (requestor instanceof IProblemRequestorExtension) { - IProblemRequestorExtension extension= (IProblemRequestorExtension) requestor; + IProblemRequestorExtension extension = (IProblemRequestorExtension) requestor; extension.setIsActive(isHandlingTemporaryProblems()); } return cuInfo; } - private void setUpSynchronization(CompilationUnitInfo cuInfo) { - IDocument document= cuInfo.fTextFileBuffer.getDocument(); - IAnnotationModel model= cuInfo.fModel; + private void setUpSynchronization(CompilationUnitInfo cuInfo) { + IDocument document = cuInfo.fTextFileBuffer.getDocument(); + IAnnotationModel model = cuInfo.fModel; - if (document instanceof ISynchronizable && model instanceof ISynchronizable) { - Object lock= ((ISynchronizable) document).getLockObject(); - ((ISynchronizable) model).setLockObject(lock); - } - } + if (document instanceof ISynchronizable + && model instanceof ISynchronizable) { + Object lock = ((ISynchronizable) document).getLockObject(); + ((ISynchronizable) model).setLockObject(lock); + } + } - /* - * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#disposeFileInfo(java.lang.Object, org.eclipse.ui.editors.text.TextFileDocumentProvider.FileInfo) + /* + * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#disposeFileInfo(java.lang.Object, + * org.eclipse.ui.editors.text.TextFileDocumentProvider.FileInfo) */ protected void disposeFileInfo(Object element, FileInfo info) { if (info instanceof CompilationUnitInfo) { - CompilationUnitInfo cuInfo= (CompilationUnitInfo) info; + CompilationUnitInfo cuInfo = (CompilationUnitInfo) info; - try { - cuInfo.fCopy.discardWorkingCopy(); - } catch (JavaModelException x) { - handleCoreException(x, x.getMessage()); + try { + cuInfo.fCopy.discardWorkingCopy(); + } catch (JavaModelException x) { + handleCoreException(x, x.getMessage()); } if (cuInfo.fModel != null) - cuInfo.fModel.removeAnnotationModelListener(fGlobalAnnotationModelListener); + cuInfo.fModel + .removeAnnotationModelListener(fGlobalAnnotationModelListener); } super.disposeFileInfo(element, info); } - protected void commitWorkingCopy(IProgressMonitor monitor, Object element, CompilationUnitInfo info, boolean overwrite) throws CoreException { - synchronized (info.fCopy) { - info.fCopy.reconcile(); - } + protected void commitWorkingCopy(IProgressMonitor monitor, Object element, + CompilationUnitInfo info, boolean overwrite) throws CoreException { + synchronized (info.fCopy) { + info.fCopy.reconcile(); + } - IDocument document= info.fTextFileBuffer.getDocument(); - IResource resource= info.fCopy.getResource(); + IDocument document = info.fTextFileBuffer.getDocument(); + IResource resource = info.fCopy.getResource(); - Assert.isTrue(resource instanceof IFile); - if (!resource.exists()) { - // underlying resource has been deleted, just recreate file, ignore the rest - createFileFromDocument(monitor, (IFile) resource, document); - return; - } + Assert.isTrue(resource instanceof IFile); + if (!resource.exists()) { + // underlying resource has been deleted, just recreate file, ignore + // the rest + createFileFromDocument(monitor, (IFile) resource, document); + return; + } - if (fSavePolicy != null) - fSavePolicy.preSave(info.fCopy); + if (fSavePolicy != null) + fSavePolicy.preSave(info.fCopy); - try { + try { - fIsAboutToSave= true; - info.fCopy.commitWorkingCopy(overwrite, monitor); + fIsAboutToSave = true; + info.fCopy.commitWorkingCopy(overwrite, monitor); - } catch (CoreException x) { - // inform about the failure - fireElementStateChangeFailed(element); - throw x; - } catch (RuntimeException x) { - // inform about the failure - fireElementStateChangeFailed(element); - throw x; - } finally { - fIsAboutToSave= false; - } + } catch (CoreException x) { + // inform about the failure + fireElementStateChangeFailed(element); + throw x; + } catch (RuntimeException x) { + // inform about the failure + fireElementStateChangeFailed(element); + throw x; + } finally { + fIsAboutToSave = false; + } - // If here, the dirty state of the editor will change to "not dirty". - // Thus, the state changing flag will be reset. - if (info.fModel instanceof AbstractMarkerAnnotationModel) { - AbstractMarkerAnnotationModel model= (AbstractMarkerAnnotationModel) info.fModel; - model.updateMarkers(document); - } + // If here, the dirty state of the editor will change to "not dirty". + // Thus, the state changing flag will be reset. + if (info.fModel instanceof AbstractMarkerAnnotationModel) { + AbstractMarkerAnnotationModel model = (AbstractMarkerAnnotationModel) info.fModel; + model.updateMarkers(document); + } - if (fSavePolicy != null) { - ICompilationUnit unit= fSavePolicy.postSave(info.fCopy); - if (unit != null && info.fModel instanceof AbstractMarkerAnnotationModel) { - IResource r= unit.getResource(); - IMarker[] markers= r.findMarkers(IMarker.MARKER, true, IResource.DEPTH_ZERO); - if (markers != null && markers.length > 0) { - AbstractMarkerAnnotationModel model= (AbstractMarkerAnnotationModel) info.fModel; - for (int i= 0; i < markers.length; i++) - model.updateMarker(document, markers[i], null); + if (fSavePolicy != null) { + ICompilationUnit unit = fSavePolicy.postSave(info.fCopy); + if (unit != null + && info.fModel instanceof AbstractMarkerAnnotationModel) { + IResource r = unit.getResource(); + IMarker[] markers = r.findMarkers(IMarker.MARKER, true, + IResource.DEPTH_ZERO); + if (markers != null && markers.length > 0) { + AbstractMarkerAnnotationModel model = (AbstractMarkerAnnotationModel) info.fModel; + for (int i = 0; i < markers.length; i++) + model.updateMarker(document, markers[i], null); + } } } + } -} + /* + * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createSaveOperation(java.lang.Object, + * org.eclipse.jface.text.IDocument, boolean) + */ + protected DocumentProviderOperation createSaveOperation( + final Object element, final IDocument document, + final boolean overwrite) throws CoreException { + // final FileInfo info= getFileInfo(element); + // if (info instanceof CompilationUnitInfo) { + // return new DocumentProviderOperation() { + // /* + // * @see + // org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#execute(org.eclipse.core.runtime.IProgressMonitor) + // */ + // protected void execute(IProgressMonitor monitor) throws CoreException + // { + // commitWorkingCopy(monitor, element, (CompilationUnitInfo) info, + // overwrite); + // } + // /* + // * @see + // org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#getSchedulingRule() + // */ + // public ISchedulingRule getSchedulingRule() { + // if (info.fElement instanceof IFileEditorInput) { + // IFile file= ((IFileEditorInput) info.fElement).getFile(); + // IResourceRuleFactory ruleFactory= + // ResourcesPlugin.getWorkspace().getRuleFactory(); + // if (file == null || !file.exists()) + // return ruleFactory.createRule(file); + // else + // return ruleFactory.modifyRule(file); + // } else + // return null; + // } + // }; + // } + // return null; + final FileInfo info = getFileInfo(element); + if (info instanceof CompilationUnitInfo) { + return new DocumentProviderOperation() { + /* + * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#execute(org.eclipse.core.runtime.IProgressMonitor) + */ + protected void execute(IProgressMonitor monitor) + throws CoreException { + commitWorkingCopy(monitor, element, + (CompilationUnitInfo) info, overwrite); + } -/* - * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createSaveOperation(java.lang.Object, org.eclipse.jface.text.IDocument, boolean) - */ -protected DocumentProviderOperation createSaveOperation(final Object element, final IDocument document, final boolean overwrite) throws CoreException { -// final FileInfo info= getFileInfo(element); -// if (info instanceof CompilationUnitInfo) { -// return new DocumentProviderOperation() { -// /* -// * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#execute(org.eclipse.core.runtime.IProgressMonitor) -// */ -// protected void execute(IProgressMonitor monitor) throws CoreException { -// commitWorkingCopy(monitor, element, (CompilationUnitInfo) info, overwrite); -// } -// /* -// * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#getSchedulingRule() -// */ -// public ISchedulingRule getSchedulingRule() { -// if (info.fElement instanceof IFileEditorInput) { -// IFile file= ((IFileEditorInput) info.fElement).getFile(); -// IResourceRuleFactory ruleFactory= ResourcesPlugin.getWorkspace().getRuleFactory(); -// if (file == null || !file.exists()) -// return ruleFactory.createRule(file); -// else -// return ruleFactory.modifyRule(file); -// } else -// return null; -// } -// }; -// } -// return null; - final FileInfo info= getFileInfo(element); - if (info instanceof CompilationUnitInfo) { - return new DocumentProviderOperation() { - /* - * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#execute(org.eclipse.core.runtime.IProgressMonitor) - */ - protected void execute(IProgressMonitor monitor) throws CoreException { - commitWorkingCopy(monitor, element, (CompilationUnitInfo) info, overwrite); - } - /* - * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#getSchedulingRule() - */ - public ISchedulingRule getSchedulingRule() { - if (info.fElement instanceof IFileEditorInput) { - IFile file= ((IFileEditorInput) info.fElement).getFile(); - return computeSchedulingRule(file); - } else - return null; - } - }; + /* + * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#getSchedulingRule() + */ + public ISchedulingRule getSchedulingRule() { + if (info.fElement instanceof IFileEditorInput) { + IFile file = ((IFileEditorInput) info.fElement) + .getFile(); + return computeSchedulingRule(file); + } else + return null; + } + }; + } + return null; + } + + /* + * (non-Javadoc) Method declared on AbstractDocumentProvider + */ + // protected IDocument createDocument(Object element) throws CoreException { + // if (element instanceof IEditorInput) { + // Document document = new PartiallySynchronizedDocument(); + // if (setDocumentContent(document, (IEditorInput) element, + // getEncoding(element))) { + // initializeDocument(document, (IEditorInput) element); + // + // // + // // IDocument document = super.createDocument(element); + // // if (document != null) { + // // IDocumentPartitioner partitioner = null; + // // if (element instanceof FileEditorInput) { + // // IFile file = (IFile) ((FileEditorInput) + // element).getAdapter(IFile.class); + // // String filename = file.getLocation().toString(); + // // String extension = filename.substring(filename.lastIndexOf("."), + // filename.length()); + // // // System.out.println(extension); + // // if (extension.equalsIgnoreCase(".html") || + // extension.equalsIgnoreCase(".htm")) { + // // // html + // // partitioner = createHTMLPartitioner(); + // // } else if (extension.equalsIgnoreCase(".xml")) { + // // // xml + // // partitioner = createXMLPartitioner(); + // // } else if (extension.equalsIgnoreCase(".js")) { + // // // javascript + // // partitioner = createJavaScriptPartitioner(); + // // } else if (extension.equalsIgnoreCase(".css")) { + // // // cascading style sheets + // // partitioner = createCSSPartitioner(); + // // } else if (extension.equalsIgnoreCase(".tpl")) { + // // // smarty ? + // // partitioner = createSmartyPartitioner(); + // // } else if (extension.equalsIgnoreCase(".inc")) { + // // // php include files ? + // // partitioner = createIncludePartitioner(); + // // } + // // } + // // + // // if (partitioner == null) { + // // partitioner = createPHPPartitioner(); + // // } + // // document.setDocumentPartitioner(partitioner); + // // partitioner.connect(document); + // } + // return document; + // } + // return null; + // } + // /** + // * Return a partitioner for .html files. + // */ + // private IDocumentPartitioner createHTMLPartitioner() { + // return new DefaultPartitioner(getHTMLPartitionScanner(), TYPES); + // } + // + // private IDocumentPartitioner createIncludePartitioner() { + // return new DefaultPartitioner(getPHPPartitionScanner(), TYPES); + // } + // + // private IDocumentPartitioner createJavaScriptPartitioner() { + // return new DefaultPartitioner(getHTMLPartitionScanner(), TYPES); + // } + /** + * Creates a line tracker working with the same line delimiters as the + * document of the given element. Assumes the element to be managed by this + * document provider. + * + * @param element + * the element serving as blue print + * @return a line tracker based on the same line delimiters as the element's + * document + */ + public ILineTracker createLineTracker(Object element) { + return new DefaultLineTracker(); } - return null; -} - /* (non-Javadoc) - * Method declared on AbstractDocumentProvider - */ -// protected IDocument createDocument(Object element) throws CoreException { -// if (element instanceof IEditorInput) { -// Document document = new PartiallySynchronizedDocument(); -// if (setDocumentContent(document, (IEditorInput) element, getEncoding(element))) { -// initializeDocument(document, (IEditorInput) element); -// -// // -// // IDocument document = super.createDocument(element); -// // if (document != null) { -// // IDocumentPartitioner partitioner = null; -// // if (element instanceof FileEditorInput) { -// // IFile file = (IFile) ((FileEditorInput) element).getAdapter(IFile.class); -// // String filename = file.getLocation().toString(); -// // String extension = filename.substring(filename.lastIndexOf("."), filename.length()); -// // // System.out.println(extension); -// // if (extension.equalsIgnoreCase(".html") || extension.equalsIgnoreCase(".htm")) { -// // // html -// // partitioner = createHTMLPartitioner(); -// // } else if (extension.equalsIgnoreCase(".xml")) { -// // // xml -// // partitioner = createXMLPartitioner(); -// // } else if (extension.equalsIgnoreCase(".js")) { -// // // javascript -// // partitioner = createJavaScriptPartitioner(); -// // } else if (extension.equalsIgnoreCase(".css")) { -// // // cascading style sheets -// // partitioner = createCSSPartitioner(); -// // } else if (extension.equalsIgnoreCase(".tpl")) { -// // // smarty ? -// // partitioner = createSmartyPartitioner(); -// // } else if (extension.equalsIgnoreCase(".inc")) { -// // // php include files ? -// // partitioner = createIncludePartitioner(); -// // } -// // } -// // -// // if (partitioner == null) { -// // partitioner = createPHPPartitioner(); -// // } -// // document.setDocumentPartitioner(partitioner); -// // partitioner.connect(document); -// } -// return document; -// } -// return null; -// } - - // /** - // * Return a partitioner for .html files. - // */ - // private IDocumentPartitioner createHTMLPartitioner() { - // return new DefaultPartitioner(getHTMLPartitionScanner(), TYPES); - // } - // - // private IDocumentPartitioner createIncludePartitioner() { - // return new DefaultPartitioner(getPHPPartitionScanner(), TYPES); - // } - // - // private IDocumentPartitioner createJavaScriptPartitioner() { - // return new DefaultPartitioner(getHTMLPartitionScanner(), TYPES); - // } - - /** - * Creates a line tracker working with the same line delimiters as the document - * of the given element. Assumes the element to be managed by this document provider. - * - * @param element the element serving as blue print - * @return a line tracker based on the same line delimiters as the element's document - */ - public ILineTracker createLineTracker(Object element) { - return new DefaultLineTracker(); - } - - // /** - // * Return a partitioner for .php files. - // */ - // private IDocumentPartitioner createPHPPartitioner() { - // return new DefaultPartitioner(getPHPPartitionScanner(), TYPES); - // } - // - // private IDocumentPartitioner createSmartyPartitioner() { - // return new DefaultPartitioner(getSmartyPartitionScanner(), TYPES); - // } - // - // private IDocumentPartitioner createXMLPartitioner() { - // return new DefaultPartitioner(getXMLPartitionScanner(), TYPES); - // } - // - // /** - // * Return a scanner for creating html partitions. - // */ - // private PHPPartitionScanner getHTMLPartitionScanner() { - // if (HTML_PARTITION_SCANNER == null) - // HTML_PARTITION_SCANNER = new PHPPartitionScanner(IPHPPartitionScannerConstants.HTML_FILE); - // return HTML_PARTITION_SCANNER; - // } - // /** - // * Return a scanner for creating php partitions. - // */ - // private PHPPartitionScanner getPHPPartitionScanner() { - // if (PHP_PARTITION_SCANNER == null) - // PHP_PARTITION_SCANNER = new PHPPartitionScanner(IPHPPartitionScannerConstants.PHP_FILE); - // return PHP_PARTITION_SCANNER; - // } - // - // /** - // * Return a scanner for creating smarty partitions. - // */ - // private PHPPartitionScanner getSmartyPartitionScanner() { - // if (SMARTY_PARTITION_SCANNER == null) - // SMARTY_PARTITION_SCANNER = new PHPPartitionScanner(IPHPPartitionScannerConstants.SMARTY_FILE); - // return SMARTY_PARTITION_SCANNER; - // } - // - // /** - // * Return a scanner for creating xml partitions. - // */ - // private PHPPartitionScanner getXMLPartitionScanner() { - // if (XML_PARTITION_SCANNER == null) - // XML_PARTITION_SCANNER = new PHPPartitionScanner(IPHPPartitionScannerConstants.XML_FILE); - // return XML_PARTITION_SCANNER; - // } - -// protected void initializeDocument(IDocument document, IEditorInput editorInput) { -// if (document != null) { -// JavaTextTools tools = PHPeclipsePlugin.getDefault().getJavaTextTools(); -// IDocumentPartitioner partitioner = null; -// if (editorInput != null && editorInput instanceof FileEditorInput) { -// IFile file = (IFile) ((FileEditorInput) editorInput).getAdapter(IFile.class); -// String filename = file.getLocation().toString(); -// String extension = filename.substring(filename.lastIndexOf("."), filename.length()); -// partitioner = tools.createDocumentPartitioner(extension); -// } else { -// partitioner = tools.createDocumentPartitioner(".php"); -// } -// document.setDocumentPartitioner(partitioner); -// partitioner.connect(document); -// } -// } - - /* - * @see org.eclipse.ui.texteditor.AbstractDocumentProvider#doResetDocument(java.lang.Object, org.eclipse.core.runtime.IProgressMonitor) - */ -// protected void doResetDocument(Object element, IProgressMonitor monitor) throws CoreException { -// if (element == null) -// return; -// -// ElementInfo elementInfo= getElementInfo(element); -// if (elementInfo instanceof CompilationUnitInfo) { -// CompilationUnitInfo info= (CompilationUnitInfo) elementInfo; -// -// IDocument document; -// IStatus status= null; -// -// try { -// -// ICompilationUnit original= (ICompilationUnit) info.fCopy.getOriginalElement(); -// IResource resource= original.getResource(); -// if (resource instanceof IFile) { -// -// IFile file= (IFile) resource; -// -// try { -// refreshFile(file, monitor); -// } catch (CoreException x) { -// handleCoreException(x, PHPEditorMessages.getString("CompilationUnitDocumentProvider.error.resetDocument")); //$NON-NLS-1$ -// } -// -// IFileEditorInput input= new FileEditorInput(file); -// document= super.createDocument(input); -// -// } else { -// document= createEmptyDocument(); -// } -// -// } catch (CoreException x) { -// document= createEmptyDocument(); -// status= x.getStatus(); -// } -// -// fireElementContentAboutToBeReplaced(element); -// -// removeUnchangedElementListeners(element, info); -// info.fDocument.set(document.get()); -// info.fCanBeSaved= false; -// info.fStatus= status; -// addUnchangedElementListeners(element, info); -// -// fireElementContentReplaced(element); -// fireElementDirtyStateChanged(element, false); -// -// } else { -// super.doResetDocument(element, monitor); -// } -// } - - /* - * @see AbstractDocumentProvider#resetDocument(Object) - */ -// public void resetDocument(Object element) throws CoreException { -// if (element == null) -// return; -// -// ElementInfo elementInfo = getElementInfo(element); -// if (elementInfo instanceof CompilationUnitInfo) { -// CompilationUnitInfo info = (CompilationUnitInfo) elementInfo; -// -// IDocument document; -// IStatus status = null; -// -// try { -// -// ICompilationUnit original = (ICompilationUnit) info.fCopy.getOriginalElement(); -// IResource resource = original.getResource(); -// if (resource instanceof IFile) { -// -// IFile file = (IFile) resource; -// -// try { -// refreshFile(file); -// } catch (CoreException x) { -// handleCoreException(x, PHPEditorMessages.getString("PHPDocumentProvider.error.resetDocument")); //$NON-NLS-1$ -// } -// -// IFileEditorInput input = new FileEditorInput(file); -// document = super.createDocument(input); -// -// } else { -// document = new Document(); -// } -// -// } catch (CoreException x) { -// document = new Document(); -// status = x.getStatus(); -// } -// -// fireElementContentAboutToBeReplaced(element); -// -// removeUnchangedElementListeners(element, info); -// info.fDocument.set(document.get()); -// info.fCanBeSaved = false; -// info.fStatus = status; -// addUnchangedElementListeners(element, info); -// -// fireElementContentReplaced(element); -// fireElementDirtyStateChanged(element, false); -// -// } else { -// super.resetDocument(element); -// } -// } - /** - * Saves the content of the given document to the given element. - * This is only performed when this provider initiated the save. - * - * @param monitor the progress monitor - * @param element the element to which to save - * @param document the document to save - * @param overwrite true if the save should be enforced - */ - public void saveDocumentContent(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite) - throws CoreException { - if (!fIsAboutToSave) - return; - super.saveDocument(monitor, element, document, overwrite); -// if (!fIsAboutToSave) -// return; -// -// if (element instanceof IFileEditorInput) { -// IFileEditorInput input = (IFileEditorInput) element; -// try { -// String encoding = getEncoding(element); -// if (encoding == null) -// encoding = ResourcesPlugin.getEncoding(); -// InputStream stream = new ByteArrayInputStream(document.get().getBytes(encoding)); -// IFile file = input.getFile(); -// file.setContents(stream, overwrite, true, monitor); -// } catch (IOException x) { -// IStatus s = new Status(IStatus.ERROR, PHPeclipsePlugin.PLUGIN_ID, IStatus.OK, x.getMessage(), x); -// throw new CoreException(s); -// } -// } - } - /** - * Returns the underlying resource for the given element. - * - * @param the element - * @return the underlying resource of the given element - */ -// public IResource getUnderlyingResource(Object element) { -// if (element instanceof IFileEditorInput) { -// IFileEditorInput input = (IFileEditorInput) element; -// return input.getFile(); -// } -// return null; -// } + // /** + // * Return a partitioner for .php files. + // */ + // private IDocumentPartitioner createPHPPartitioner() { + // return new DefaultPartitioner(getPHPPartitionScanner(), TYPES); + // } + // + // private IDocumentPartitioner createSmartyPartitioner() { + // return new DefaultPartitioner(getSmartyPartitionScanner(), TYPES); + // } + // + // private IDocumentPartitioner createXMLPartitioner() { + // return new DefaultPartitioner(getXMLPartitionScanner(), TYPES); + // } + // + // /** + // * Return a scanner for creating html partitions. + // */ + // private PHPPartitionScanner getHTMLPartitionScanner() { + // if (HTML_PARTITION_SCANNER == null) + // HTML_PARTITION_SCANNER = new + // PHPPartitionScanner(IPHPPartitionScannerConstants.HTML_FILE); + // return HTML_PARTITION_SCANNER; + // } + // /** + // * Return a scanner for creating php partitions. + // */ + // private PHPPartitionScanner getPHPPartitionScanner() { + // if (PHP_PARTITION_SCANNER == null) + // PHP_PARTITION_SCANNER = new + // PHPPartitionScanner(IPHPPartitionScannerConstants.PHP_FILE); + // return PHP_PARTITION_SCANNER; + // } + // + // /** + // * Return a scanner for creating smarty partitions. + // */ + // private PHPPartitionScanner getSmartyPartitionScanner() { + // if (SMARTY_PARTITION_SCANNER == null) + // SMARTY_PARTITION_SCANNER = new + // PHPPartitionScanner(IPHPPartitionScannerConstants.SMARTY_FILE); + // return SMARTY_PARTITION_SCANNER; + // } + // + // /** + // * Return a scanner for creating xml partitions. + // */ + // private PHPPartitionScanner getXMLPartitionScanner() { + // if (XML_PARTITION_SCANNER == null) + // XML_PARTITION_SCANNER = new + // PHPPartitionScanner(IPHPPartitionScannerConstants.XML_FILE); + // return XML_PARTITION_SCANNER; + // } + + // protected void initializeDocument(IDocument document, IEditorInput + // editorInput) { + // if (document != null) { + // JavaTextTools tools = PHPeclipsePlugin.getDefault().getJavaTextTools(); + // IDocumentPartitioner partitioner = null; + // if (editorInput != null && editorInput instanceof FileEditorInput) { + // IFile file = (IFile) ((FileEditorInput) + // editorInput).getAdapter(IFile.class); + // String filename = file.getLocation().toString(); + // String extension = filename.substring(filename.lastIndexOf("."), + // filename.length()); + // partitioner = tools.createDocumentPartitioner(extension); + // } else { + // partitioner = tools.createDocumentPartitioner(".php"); + // } + // document.setDocumentPartitioner(partitioner); + // partitioner.connect(document); + // } + // } /* + * @see org.eclipse.ui.texteditor.AbstractDocumentProvider#doResetDocument(java.lang.Object, + * org.eclipse.core.runtime.IProgressMonitor) + */ + // protected void doResetDocument(Object element, IProgressMonitor monitor) + // throws CoreException { + // if (element == null) + // return; + // + // ElementInfo elementInfo= getElementInfo(element); + // if (elementInfo instanceof CompilationUnitInfo) { + // CompilationUnitInfo info= (CompilationUnitInfo) elementInfo; + // + // IDocument document; + // IStatus status= null; + // + // try { + // + // ICompilationUnit original= (ICompilationUnit) + // info.fCopy.getOriginalElement(); + // IResource resource= original.getResource(); + // if (resource instanceof IFile) { + // + // IFile file= (IFile) resource; + // + // try { + // refreshFile(file, monitor); + // } catch (CoreException x) { + // handleCoreException(x, + // PHPEditorMessages.getString("CompilationUnitDocumentProvider.error.resetDocument")); + // //$NON-NLS-1$ + // } + // + // IFileEditorInput input= new FileEditorInput(file); + // document= super.createDocument(input); + // + // } else { + // document= createEmptyDocument(); + // } + // + // } catch (CoreException x) { + // document= createEmptyDocument(); + // status= x.getStatus(); + // } + // + // fireElementContentAboutToBeReplaced(element); + // + // removeUnchangedElementListeners(element, info); + // info.fDocument.set(document.get()); + // info.fCanBeSaved= false; + // info.fStatus= status; + // addUnchangedElementListeners(element, info); + // + // fireElementContentReplaced(element); + // fireElementDirtyStateChanged(element, false); + // + // } else { + // super.doResetDocument(element, monitor); + // } + // } + /* + * @see AbstractDocumentProvider#resetDocument(Object) + */ + // public void resetDocument(Object element) throws CoreException { + // if (element == null) + // return; + // + // ElementInfo elementInfo = getElementInfo(element); + // if (elementInfo instanceof CompilationUnitInfo) { + // CompilationUnitInfo info = (CompilationUnitInfo) elementInfo; + // + // IDocument document; + // IStatus status = null; + // + // try { + // + // ICompilationUnit original = (ICompilationUnit) + // info.fCopy.getOriginalElement(); + // IResource resource = original.getResource(); + // if (resource instanceof IFile) { + // + // IFile file = (IFile) resource; + // + // try { + // refreshFile(file); + // } catch (CoreException x) { + // handleCoreException(x, + // PHPEditorMessages.getString("PHPDocumentProvider.error.resetDocument")); + // //$NON-NLS-1$ + // } + // + // IFileEditorInput input = new FileEditorInput(file); + // document = super.createDocument(input); + // + // } else { + // document = new Document(); + // } + // + // } catch (CoreException x) { + // document = new Document(); + // status = x.getStatus(); + // } + // + // fireElementContentAboutToBeReplaced(element); + // + // removeUnchangedElementListeners(element, info); + // info.fDocument.set(document.get()); + // info.fCanBeSaved = false; + // info.fStatus = status; + // addUnchangedElementListeners(element, info); + // + // fireElementContentReplaced(element); + // fireElementDirtyStateChanged(element, false); + // + // } else { + // super.resetDocument(element); + // } + // } + /** + * Saves the content of the given document to the given element. This is + * only performed when this provider initiated the save. + * + * @param monitor + * the progress monitor + * @param element + * the element to which to save + * @param document + * the document to save + * @param overwrite + * true if the save should be enforced + */ + public void saveDocumentContent(IProgressMonitor monitor, Object element, + IDocument document, boolean overwrite) throws CoreException { + if (!fIsAboutToSave) + return; + super.saveDocument(monitor, element, document, overwrite); + // if (!fIsAboutToSave) + // return; + // + // if (element instanceof IFileEditorInput) { + // IFileEditorInput input = (IFileEditorInput) element; + // try { + // String encoding = getEncoding(element); + // if (encoding == null) + // encoding = ResourcesPlugin.getEncoding(); + // InputStream stream = new + // ByteArrayInputStream(document.get().getBytes(encoding)); + // IFile file = input.getFile(); + // file.setContents(stream, overwrite, true, monitor); + // } catch (IOException x) { + // IStatus s = new Status(IStatus.ERROR, PHPeclipsePlugin.PLUGIN_ID, + // IStatus.OK, x.getMessage(), x); + // throw new CoreException(s); + // } + // } + } + + /** + * Returns the underlying resource for the given element. + * + * @param the + * element + * @return the underlying resource of the given element + */ + // public IResource getUnderlyingResource(Object element) { + // if (element instanceof IFileEditorInput) { + // IFileEditorInput input = (IFileEditorInput) element; + // return input.getFile(); + // } + // return null; + // } + /* * @see net.sourceforge.phpdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#getWorkingCopy(java.lang.Object) */ public ICompilationUnit getWorkingCopy(Object element) { - FileInfo fileInfo= getFileInfo(element); + FileInfo fileInfo = getFileInfo(element); if (fileInfo instanceof CompilationUnitInfo) { - CompilationUnitInfo info= (CompilationUnitInfo) fileInfo; + CompilationUnitInfo info = (CompilationUnitInfo) fileInfo; return info.fCopy; } return null; } - - /* + /* * @see net.sourceforge.phpdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#shutdown() */ public void shutdown() { - PHPeclipsePlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyListener); - Iterator e= getConnectedElementsIterator(); + PHPeclipsePlugin.getDefault().getPreferenceStore() + .removePropertyChangeListener(fPropertyListener); + Iterator e = getConnectedElementsIterator(); while (e.hasNext()) disconnect(e.next()); } - /** - * Returns the preference whether handling temporary problems is enabled. - */ - protected boolean isHandlingTemporaryProblems() { - IPreferenceStore store = PHPeclipsePlugin.getDefault().getPreferenceStore(); - return store.getBoolean(HANDLE_TEMPORARY_PROBLEMS); - } + /** + * Returns the preference whether handling temporary problems is enabled. + */ + protected boolean isHandlingTemporaryProblems() { + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + return store.getBoolean(HANDLE_TEMPORARY_PROBLEMS); + } - /** - * Switches the state of problem acceptance according to the value in the preference store. + /** + * Switches the state of problem acceptance according to the value in the + * preference store. */ protected void enableHandlingTemporaryProblems() { - boolean enable= isHandlingTemporaryProblems(); - for (Iterator iter= getFileInfosIterator(); iter.hasNext();) { - FileInfo info= (FileInfo) iter.next(); + boolean enable = isHandlingTemporaryProblems(); + for (Iterator iter = getFileInfosIterator(); iter.hasNext();) { + FileInfo info = (FileInfo) iter.next(); if (info.fModel instanceof IProblemRequestorExtension) { - IProblemRequestorExtension extension= (IProblemRequestorExtension) info.fModel; + IProblemRequestorExtension extension = (IProblemRequestorExtension) info.fModel; extension.setIsActive(enable); } } } - /** - * Adds a listener that reports changes from all compilation unit annotation models. - */ - public void addGlobalAnnotationModelListener(IAnnotationModelListener listener) { - fGlobalAnnotationModelListener.addListener(listener); - } + /** + * Adds a listener that reports changes from all compilation unit annotation + * models. + */ + public void addGlobalAnnotationModelListener( + IAnnotationModelListener listener) { + fGlobalAnnotationModelListener.addListener(listener); + } - /** - * Removes the listener. - */ - public void removeGlobalAnnotationModelListener(IAnnotationModelListener listener) { - fGlobalAnnotationModelListener.removeListener(listener); - } + /** + * Removes the listener. + */ + public void removeGlobalAnnotationModelListener( + IAnnotationModelListener listener) { + fGlobalAnnotationModelListener.removeListener(listener); + } /** * Computes the scheduling rule needed to create or modify a resource. If @@ -1570,25 +1698,29 @@ protected DocumentProviderOperation createSaveOperation(final Object element, fi * first parent of toCreateOrModify that exists. Then the * 'create' rule for the last non-existing resource is returned. *

                                                      - * XXX This is a workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=67601 + * XXX This is a workaround for + * https://bugs.eclipse.org/bugs/show_bug.cgi?id=67601 * IResourceRuleFactory.createRule should iterate the hierarchy itself. *

                                                      *

                                                      - * XXX to be replaced by call to TextFileDocumentProvider.computeSchedulingRule after 3.0 + * XXX to be replaced by call to + * TextFileDocumentProvider.computeSchedulingRule after 3.0 *

                                                      - * - * @param toCreateOrModify the resource to create or modify + * + * @param toCreateOrModify + * the resource to create or modify * @return the minimal scheduling rule needed to modify or create a resource */ - protected ISchedulingRule computeSchedulingRule(IResource toCreateOrModify) { - IResourceRuleFactory factory= ResourcesPlugin.getWorkspace().getRuleFactory(); + protected ISchedulingRule computeSchedulingRule(IResource toCreateOrModify) { + IResourceRuleFactory factory = ResourcesPlugin.getWorkspace() + .getRuleFactory(); if (toCreateOrModify.exists()) { return factory.modifyRule(toCreateOrModify); } else { - IResource parent= toCreateOrModify; + IResource parent = toCreateOrModify; do { - toCreateOrModify= parent; - parent= toCreateOrModify.getParent(); + toCreateOrModify = parent; + parent = toCreateOrModify.getParent(); } while (parent != null && !parent.exists()); return factory.createRule(toCreateOrModify); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPEditor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPEditor.java index 0ba1930..4eb14da 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPEditor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPEditor.java @@ -200,24 +200,25 @@ import org.eclipse.ui.views.tasklist.TaskList; /** * PHP specific text editor. */ -public abstract class PHPEditor extends AbstractDecoratedTextEditor implements IViewPartInputProvider, IShowInTargetList, - IShowInSource { +public abstract class PHPEditor extends AbstractDecoratedTextEditor implements + IViewPartInputProvider, IShowInTargetList, IShowInSource { // extends StatusTextEditor implements IViewPartInputProvider { // extends // TextEditor { /** * Internal implementation class for a change listener. - * + * * @since 3.0 */ - protected abstract class AbstractSelectionChangedListener implements ISelectionChangedListener { + protected abstract class AbstractSelectionChangedListener implements + ISelectionChangedListener { /** * Installs this selection changed listener with the given selection - * provider. If the selection provider is a post selection provider, post - * selection changed events are the preferred choice, otherwise normal - * selection changed events are requested. - * + * provider. If the selection provider is a post selection provider, + * post selection changed events are the preferred choice, otherwise + * normal selection changed events are requested. + * * @param selectionProvider */ public void install(ISelectionProvider selectionProvider) { @@ -235,9 +236,9 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Removes this selection changed listener from the given selection * provider. - * + * * @param selectionProvider - * the selection provider + * the selection provider */ public void uninstall(ISelectionProvider selectionProvider) { if (selectionProvider == null) @@ -253,11 +254,13 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I } /** - * Updates the Java outline page selection and this editor's range indicator. - * + * Updates the Java outline page selection and this editor's range + * indicator. + * * @since 3.0 */ - private class EditorSelectionChangedListener extends AbstractSelectionChangedListener { + private class EditorSelectionChangedListener extends + AbstractSelectionChangedListener { /* * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) @@ -314,7 +317,7 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I * This preference store is read-only i.e. write access throws an * {@link java.lang.UnsupportedOperationException}. *

                                                      - * + * * @since 3.0 */ private static class OptionsAdapter implements IPreferenceStore { @@ -326,19 +329,20 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Should the given event be filtered? - * + * * @param event - * The property change event. - * @return true iff the given event should be filtered. + * The property change event. + * @return true iff the given event should be + * filtered. */ public boolean isFiltered(PropertyChangeEvent event); } /** - * Property change listener. Listens for events in the options Map and fires - * a {@link org.eclipse.jface.util.PropertyChangeEvent}on this adapter with - * arguments from the received event. + * Property change listener. Listens for events in the options Map and + * fires a {@link org.eclipse.jface.util.PropertyChangeEvent}on this + * adapter with arguments from the received event. */ private class PropertyChangeListener implements IPropertyChangeListener { @@ -354,7 +358,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I else fOptions.put(event.getProperty(), event.getNewValue()); - firePropertyChangeEvent(event.getProperty(), event.getOldValue(), event.getNewValue()); + firePropertyChangeEvent(event.getProperty(), event + .getOldValue(), event.getNewValue()); } } @@ -375,15 +380,17 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Initialize with the given options. - * + * * @param options - * The options to wrap + * The options to wrap * @param mockupPreferenceStore - * the mock-up preference store + * the mock-up preference store * @param filter - * the property change filter + * the property change filter */ - public OptionsAdapter(Map options, IPreferenceStore mockupPreferenceStore, IPropertyChangeEventFilter filter) { + public OptionsAdapter(Map options, + IPreferenceStore mockupPreferenceStore, + IPropertyChangeEventFilter filter) { fMockupPreferenceStore = mockupPreferenceStore; fOptions = options; setFilter(filter); @@ -401,7 +408,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * {@inheritDoc} */ - public void removePropertyChangeListener(IPropertyChangeListener listener) { + public void removePropertyChangeListener( + IPropertyChangeListener listener) { fListeners.remove(listener); if (fListeners.size() == 0) fMockupPreferenceStore.removePropertyChangeListener(fListener); @@ -417,8 +425,10 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * {@inheritDoc} */ - public void firePropertyChangeEvent(String name, Object oldValue, Object newValue) { - PropertyChangeEvent event = new PropertyChangeEvent(this, name, oldValue, newValue); + public void firePropertyChangeEvent(String name, Object oldValue, + Object newValue) { + PropertyChangeEvent event = new PropertyChangeEvent(this, name, + oldValue, newValue); Object[] listeners = fListeners.getListeners(); for (int i = 0; i < listeners.length; i++) ((IPropertyChangeListener) listeners[i]).propertyChange(event); @@ -661,7 +671,7 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Returns the adapted options Map. - * + * * @return Returns the adapted options Map. */ public Map getOptions() { @@ -669,9 +679,9 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I } /** - * Returns the mock-up preference store, events are received through this - * preference store. - * + * Returns the mock-up preference store, events are received through + * this preference store. + * * @return Returns the mock-up preference store. */ public IPreferenceStore getMockupPreferenceStore() { @@ -680,9 +690,9 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Set the event filter to the given filter. - * + * * @param filter - * The new filter. + * The new filter. */ public void setFilter(IPropertyChangeEventFilter filter) { fFilter = filter; @@ -690,7 +700,7 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Returns the event filter. - * + * * @return The event filter. */ public IPropertyChangeEventFilter getFilter() { @@ -785,7 +795,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I // return SWT.NONE; // // int stateMask = 0; - // StringTokenizer modifierTokenizer = new StringTokenizer(modifiers, ",;.:+-* + // StringTokenizer modifierTokenizer = new StringTokenizer(modifiers, + // ",;.:+-* // "); //$NON-NLS-1$ // while (modifierTokenizer.hasMoreTokens()) { // int modifier = @@ -856,7 +867,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I // return; // // Display display = text.getDisplay(); - // fColor = createColor(getPreferenceStore(), PHPEditor.LINK_COLOR, display); + // fColor = createColor(getPreferenceStore(), PHPEditor.LINK_COLOR, + // display); // } // // /** @@ -1206,7 +1218,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I // return; // } // - // if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() != 0) + // if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() != + // 0) // { // deactivate(); // return; @@ -1296,7 +1309,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I // org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, // * org.eclipse.jface.text.IDocument) // */ - // public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { + // public void inputDocumentChanged(IDocument oldInput, IDocument newInput) + // { // if (newInput == null) // return; // newInput.addDocumentListener(this); @@ -1361,7 +1375,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I // region.getLength(); // } // - // private Point getMinimumLocation(StyledText text, int offset, int length) { + // private Point getMinimumLocation(StyledText text, int offset, int length) + // { // Point minLocation = new Point(Integer.MAX_VALUE, Integer.MAX_VALUE); // // for (int i = 0; i <= length; i++) { @@ -1376,7 +1391,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I // return minLocation; // } // - // private Point getMaximumLocation(StyledText text, int offset, int length) { + // private Point getMaximumLocation(StyledText text, int offset, int length) + // { // Point maxLocation = new Point(Integer.MIN_VALUE, Integer.MIN_VALUE); // // for (int i = 0; i <= length; i++) { @@ -1394,8 +1410,10 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /* * Link mode. */ - class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener, FocusListener, PaintListener, - IPropertyChangeListener, IDocumentListener, ITextInputListener, ITextPresentationListener { + class MouseClickListener implements KeyListener, MouseListener, + MouseMoveListener, FocusListener, PaintListener, + IPropertyChangeListener, IDocumentListener, ITextInputListener, + ITextPresentationListener { /** The session is active. */ private boolean fActive; @@ -1450,7 +1468,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I text.addFocusListener(this); text.addPaintListener(this); - ((ITextViewerExtension4) sourceViewer).addTextPresentationListener(this); + ((ITextViewerExtension4) sourceViewer) + .addTextPresentationListener(this); updateKeyModifierMask(); @@ -1459,11 +1478,13 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I } private void updateKeyModifierMask() { - String modifiers = getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER); + String modifiers = getPreferenceStore().getString( + BROWSER_LIKE_LINKS_KEY_MODIFIER); fKeyModifierMask = computeStateMask(modifiers); if (fKeyModifierMask == -1) { // Fall back to stored state mask - fKeyModifierMask = getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK); + fKeyModifierMask = getPreferenceStore().getInt( + BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK); } } @@ -1475,9 +1496,11 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I return SWT.NONE; int stateMask = 0; - StringTokenizer modifierTokenizer = new StringTokenizer(modifiers, ",;.:+-* "); //$NON-NLS-1$ + StringTokenizer modifierTokenizer = new StringTokenizer(modifiers, + ",;.:+-* "); //$NON-NLS-1$ while (modifierTokenizer.hasMoreTokens()) { - int modifier = EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken()); + int modifier = EditorUtility + .findLocalizedModifier(modifierTokenizer.nextToken()); if (modifier == 0 || (stateMask & modifier) == modifier) return -1; stateMask = stateMask | modifier; @@ -1503,7 +1526,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I IDocumentProvider documentProvider = getDocumentProvider(); if (documentProvider != null) { - IDocument document = documentProvider.getDocument(getEditorInput()); + IDocument document = documentProvider + .getDocument(getEditorInput()); if (document != null) document.removeDocumentListener(this); } @@ -1525,7 +1549,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I text.removeFocusListener(this); text.removePaintListener(this); - ((ITextViewerExtension4) sourceViewer).removeTextPresentationListener(this); + ((ITextViewerExtension4) sourceViewer) + .removeTextPresentationListener(this); } /* @@ -1536,7 +1561,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I ISourceViewer viewer = getSourceViewer(); if (viewer != null) updateColor(viewer); - } else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) { + } else if (event.getProperty().equals( + BROWSER_LIKE_LINKS_KEY_MODIFIER)) { updateKeyModifierMask(); } } @@ -1550,23 +1576,25 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I return; Display display = text.getDisplay(); - fColor = createColor(getPreferenceStore(), PHPEditor.LINK_COLOR, display); + fColor = createColor(getPreferenceStore(), PHPEditor.LINK_COLOR, + display); } /** * Creates a color from the information stored in the given preference * store. - * + * * @param store - * the preference store + * the preference store * @param key - * the key + * the key * @param display - * the display - * @return the color or null if there is no such information - * available + * the display + * @return the color or null if there is no such + * information available */ - private Color createColor(IPreferenceStore store, String key, Display display) { + private Color createColor(IPreferenceStore store, String key, + Display display) { RGB rgb = null; @@ -1604,7 +1632,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I // Invalidate ==> remove applied text presentation if (!redrawAll && viewer instanceof ITextViewerExtension2) - ((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length); + ((ITextViewerExtension2) viewer) + .invalidateTextPresentation(offset, length); else viewer.invalidateTextPresentation(); @@ -1718,9 +1747,12 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I if (fActiveRegion == null) return; IRegion region = textPresentation.getExtent(); - if (fActiveRegion.getOffset() + fActiveRegion.getLength() >= region.getOffset() - && region.getOffset() + region.getLength() > fActiveRegion.getOffset()) - textPresentation.mergeStyleRange(new StyleRange(fActiveRegion.getOffset(), fActiveRegion.getLength(), fColor, null)); + if (fActiveRegion.getOffset() + fActiveRegion.getLength() >= region + .getOffset() + && region.getOffset() + region.getLength() > fActiveRegion + .getOffset()) + textPresentation.mergeStyleRange(new StyleRange(fActiveRegion + .getOffset(), fActiveRegion.getLength(), fColor, null)); } private void highlightRegion(ISourceViewer viewer, IRegion region) { @@ -1747,7 +1779,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I length = widgetRange.getLength(); } else { - offset = region.getOffset() - viewer.getVisibleRegion().getOffset(); + offset = region.getOffset() + - viewer.getVisibleRegion().getOffset(); length = region.getLength(); } text.redrawRange(offset, length, false); @@ -1755,7 +1788,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I // Invalidate region ==> apply text presentation fActiveRegion = region; if (viewer instanceof ITextViewerExtension2) - ((ITextViewerExtension2) viewer).invalidateTextPresentation(region.getOffset(), region.getLength()); + ((ITextViewerExtension2) viewer).invalidateTextPresentation( + region.getOffset(), region.getLength()); else viewer.invalidateTextPresentation(); } @@ -1877,7 +1911,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I */ public void mouseMove(MouseEvent event) { - if (event.widget instanceof Control && !((Control) event.widget).isFocusControl()) { + if (event.widget instanceof Control + && !((Control) event.widget).isFocusControl()) { deactivate(); return; } @@ -1901,7 +1936,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I return; } - if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() != 0) { + if ((event.stateMask & SWT.BUTTON1) != 0 + && text.getSelectionCount() != 0) { deactivate(); return; } @@ -1934,7 +1970,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I */ public void documentAboutToBeChanged(DocumentEvent event) { if (fActive && fActiveRegion != null) { - fRememberedPosition = new Position(fActiveRegion.getOffset(), fActiveRegion.getLength()); + fRememberedPosition = new Position(fActiveRegion.getOffset(), + fActiveRegion.getLength()); try { event.getDocument().addPosition(fRememberedPosition); } catch (BadLocationException x) { @@ -1951,7 +1988,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I if (!fRememberedPosition.isDeleted()) { event.getDocument().removePosition(fRememberedPosition); - fActiveRegion = new Region(fRememberedPosition.getOffset(), fRememberedPosition.getLength()); + fActiveRegion = new Region(fRememberedPosition.getOffset(), + fRememberedPosition.getLength()); fRememberedPosition = null; ISourceViewer viewer = getSourceViewer(); @@ -1978,7 +2016,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, * org.eclipse.jface.text.IDocument) */ - public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) { + public void inputDocumentAboutToBeChanged(IDocument oldInput, + IDocument newInput) { if (oldInput == null) return; deactivate(); @@ -2016,7 +2055,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I if (viewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension = (ITextViewerExtension5) viewer; - IRegion widgetRange = extension.modelRange2WidgetRange(fActiveRegion); + IRegion widgetRange = extension + .modelRange2WidgetRange(fActiveRegion); if (widgetRange == null) return; @@ -2049,7 +2089,9 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I private boolean includes(IRegion region, IRegion position) { return position.getOffset() >= region.getOffset() - && position.getOffset() + position.getLength() <= region.getOffset() + region.getLength(); + && position.getOffset() + position.getLength() <= region + .getOffset() + + region.getLength(); } private Point getMinimumLocation(StyledText text, int offset, int length) { @@ -2085,9 +2127,9 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * This action dispatches into two behaviours: If there is no current text - * hover, the javadoc is displayed using information presenter. If there is a - * current text hover, it is converted into a information presenter in order - * to make it sticky. + * hover, the javadoc is displayed using information presenter. If there is + * a current text hover, it is converted into a information presenter in + * order to make it sticky. */ class InformationDispatchAction extends TextEditorAction { @@ -2097,7 +2139,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Creates a dispatch action. */ - public InformationDispatchAction(ResourceBundle resourceBundle, String prefix, final TextOperationAction textOperationAction) { + public InformationDispatchAction(ResourceBundle resourceBundle, + String prefix, final TextOperationAction textOperationAction) { super(resourceBundle, prefix, PHPEditor.this); if (textOperationAction == null) throw new IllegalArgumentException(); @@ -2129,8 +2172,10 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I return; } - Point hoverEventLocation = textViewerExtension2.getHoverEventLocation(); - int offset = computeOffsetAtLocation(sourceViewer, hoverEventLocation.x, hoverEventLocation.y); + Point hoverEventLocation = textViewerExtension2 + .getHoverEventLocation(); + int offset = computeOffsetAtLocation(sourceViewer, + hoverEventLocation.x, hoverEventLocation.y); if (offset == -1) { fTextOperationAction.run(); return; @@ -2141,11 +2186,13 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I IDocument document = sourceViewer.getDocument(); String contentType = document.getContentType(offset); - final IRegion hoverRegion = textHover.getHoverRegion(sourceViewer, offset); + final IRegion hoverRegion = textHover.getHoverRegion( + sourceViewer, offset); if (hoverRegion == null) return; - final String hoverInfo = textHover.getHoverInfo(sourceViewer, hoverRegion); + final String hoverInfo = textHover.getHoverInfo(sourceViewer, + hoverRegion); // with information provider IInformationProvider informationProvider = new IInformationProvider() { @@ -2161,13 +2208,15 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I * @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer, * org.eclipse.jface.text.IRegion) */ - public String getInformation(ITextViewer textViewer, IRegion subject) { + public String getInformation(ITextViewer textViewer, + IRegion subject) { return hoverInfo; } }; fInformationPresenter.setOffset(offset); - fInformationPresenter.setInformationProvider(informationProvider, contentType); + fInformationPresenter.setInformationProvider( + informationProvider, contentType); fInformationPresenter.showInformation(); } catch (BadLocationException e) { @@ -2184,7 +2233,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I return -1; try { - int widgetLocation = styledText.getOffsetAtLocation(new Point(x, y)); + int widgetLocation = styledText.getOffsetAtLocation(new Point( + x, y)); if (textViewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension = (ITextViewerExtension5) textViewer; return extension.widgetOffset2ModelOffset(widgetLocation); @@ -2201,28 +2251,29 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * This action implements smart home. - * + * * Instead of going to the start of a line it does the following: - if smart - * home/end is enabled and the caret is after the line's first non-whitespace - * then the caret is moved directly before it, taking JavaDoc and multi-line - * comments into account. - if the caret is before the line's first - * non-whitespace the caret is moved to the beginning of the line - if the - * caret is at the beginning of the line see first case. - * + * home/end is enabled and the caret is after the line's first + * non-whitespace then the caret is moved directly before it, taking JavaDoc + * and multi-line comments into account. - if the caret is before the line's + * first non-whitespace the caret is moved to the beginning of the line - if + * the caret is at the beginning of the line see first case. + * * @since 3.0 */ protected class SmartLineStartAction extends LineStartAction { /** * Creates a new smart line start action - * + * * @param textWidget - * the styled text widget + * the styled text widget * @param doSelect - * a boolean flag which tells if the text up to the beginning of - * the line should be selected + * a boolean flag which tells if the text up to the beginning + * of the line should be selected */ - public SmartLineStartAction(final StyledText textWidget, final boolean doSelect) { + public SmartLineStartAction(final StyledText textWidget, + final boolean doSelect) { super(textWidget, doSelect); } @@ -2230,28 +2281,36 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I * @see org.eclipse.ui.texteditor.AbstractTextEditor.LineStartAction#getLineStartPosition(java.lang.String, * int, java.lang.String) */ - protected int getLineStartPosition(final IDocument document, final String line, final int length, final int offset) { + protected int getLineStartPosition(final IDocument document, + final String line, final int length, final int offset) { String type = IDocument.DEFAULT_CONTENT_TYPE; try { - type = TextUtilities.getContentType(document, IPHPPartitions.PHP_PARTITIONING, offset, true); + type = TextUtilities.getContentType(document, + IPHPPartitions.PHP_PARTITIONING, offset, true); } catch (BadLocationException exception) { // Should not happen } - int index = super.getLineStartPosition(document, line, length, offset); - if (type.equals(IPHPPartitions.PHP_PHPDOC_COMMENT) || type.equals(IPHPPartitions.PHP_MULTILINE_COMMENT)) { - if (index < length - 1 && line.charAt(index) == '*' && line.charAt(index + 1) != '/') { + int index = super.getLineStartPosition(document, line, length, + offset); + if (type.equals(IPHPPartitions.PHP_PHPDOC_COMMENT) + || type.equals(IPHPPartitions.PHP_MULTILINE_COMMENT)) { + if (index < length - 1 && line.charAt(index) == '*' + && line.charAt(index + 1) != '/') { do { ++index; - } while (index < length && Character.isWhitespace(line.charAt(index))); + } while (index < length + && Character.isWhitespace(line.charAt(index))); } } else { - if (index < length - 1 && line.charAt(index) == '/' && line.charAt(index + 1) == '/') { + if (index < length - 1 && line.charAt(index) == '/' + && line.charAt(index + 1) == '/') { index++; do { ++index; - } while (index < length && Character.isWhitespace(line.charAt(index))); + } while (index < length + && Character.isWhitespace(line.charAt(index))); } } return index; @@ -2260,7 +2319,7 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Text navigation action to navigate to the next sub-word. - * + * * @since 3.0 */ protected abstract class NextSubWordAction extends TextNavigationAction { @@ -2269,10 +2328,10 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Creates a new next sub-word action. - * + * * @param code - * Action code for the default operation. Must be an action code - * from + * Action code for the default operation. Must be an action + * code from * @see org.eclipse.swt.custom.ST. */ protected NextSubWordAction(int code) { @@ -2283,18 +2342,23 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I * @see org.eclipse.jface.action.IAction#run() */ public void run() { - // Check whether we are in a java code partition and the preference is + // Check whether we are in a java code partition and the preference + // is // enabled final IPreferenceStore store = getPreferenceStore(); - if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) { + if (!store + .getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) { super.run(); return; } final ISourceViewer viewer = getSourceViewer(); final IDocument document = viewer.getDocument(); - fIterator.setText((CharacterIterator) new DocumentCharacterIterator(document)); - int position = widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); + fIterator + .setText((CharacterIterator) new DocumentCharacterIterator( + document)); + int position = widgetOffset2ModelOffset(viewer, viewer + .getTextWidget().getCaretOffset()); if (position == -1) return; @@ -2309,9 +2373,9 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Finds the next position after the given position. - * + * * @param position - * the current position + * the current position * @return the next position */ protected int findNextPosition(int position) { @@ -2329,16 +2393,16 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Sets the caret position to the sub-word boundary given with * position. - * + * * @param position - * Position where the action should move the caret + * Position where the action should move the caret */ protected abstract void setCaretPosition(int position); } /** * Text navigation action to navigate to the next sub-word. - * + * * @since 3.0 */ protected class NavigateNextSubWordAction extends NextSubWordAction { @@ -2354,16 +2418,18 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { - getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), position)); + getTextWidget().setCaretOffset( + modelOffset2WidgetOffset(getSourceViewer(), position)); } } /** * Text operation action to delete the next sub-word. - * + * * @since 3.0 */ - protected class DeleteNextSubWordAction extends NextSubWordAction implements IUpdate { + protected class DeleteNextSubWordAction extends NextSubWordAction implements + IUpdate { /** * Creates a new delete next sub-word action. @@ -2380,7 +2446,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I return; final ISourceViewer viewer = getSourceViewer(); - final int caret = widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); + final int caret = widgetOffset2ModelOffset(viewer, viewer + .getTextWidget().getCaretOffset()); try { viewer.getDocument().replace(caret, position - caret, ""); //$NON-NLS-1$ @@ -2406,7 +2473,7 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Text operation action to select the next sub-word. - * + * * @since 3.0 */ protected class SelectNextSubWordAction extends NextSubWordAction { @@ -2441,7 +2508,7 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Text navigation action to navigate to the previous sub-word. - * + * * @since 3.0 */ protected abstract class PreviousSubWordAction extends TextNavigationAction { @@ -2450,10 +2517,10 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Creates a new previous sub-word action. - * + * * @param code - * Action code for the default operation. Must be an action code - * from + * Action code for the default operation. Must be an action + * code from * @see org.eclipse.swt.custom.ST. */ protected PreviousSubWordAction(final int code) { @@ -2464,18 +2531,23 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I * @see org.eclipse.jface.action.IAction#run() */ public void run() { - // Check whether we are in a java code partition and the preference is + // Check whether we are in a java code partition and the preference + // is // enabled final IPreferenceStore store = getPreferenceStore(); - if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) { + if (!store + .getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) { super.run(); return; } final ISourceViewer viewer = getSourceViewer(); final IDocument document = viewer.getDocument(); - fIterator.setText((CharacterIterator) new DocumentCharacterIterator(document)); - int position = widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); + fIterator + .setText((CharacterIterator) new DocumentCharacterIterator( + document)); + int position = widgetOffset2ModelOffset(viewer, viewer + .getTextWidget().getCaretOffset()); if (position == -1) return; @@ -2490,9 +2562,9 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Finds the previous position before the given position. - * + * * @param position - * the current position + * the current position * @return the previous position */ protected int findPreviousPosition(int position) { @@ -2510,16 +2582,16 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Sets the caret position to the sub-word boundary given with * position. - * + * * @param position - * Position where the action should move the caret + * Position where the action should move the caret */ protected abstract void setCaretPosition(int position); } /** * Text navigation action to navigate to the previous sub-word. - * + * * @since 3.0 */ protected class NavigatePreviousSubWordAction extends PreviousSubWordAction { @@ -2535,16 +2607,18 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { - getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), position)); + getTextWidget().setCaretOffset( + modelOffset2WidgetOffset(getSourceViewer(), position)); } } /** * Text operation action to delete the previous sub-word. - * + * * @since 3.0 */ - protected class DeletePreviousSubWordAction extends PreviousSubWordAction implements IUpdate { + protected class DeletePreviousSubWordAction extends PreviousSubWordAction + implements IUpdate { /** * Creates a new delete previous sub-word action. @@ -2561,7 +2635,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I return; final ISourceViewer viewer = getSourceViewer(); - final int caret = widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); + final int caret = widgetOffset2ModelOffset(viewer, viewer + .getTextWidget().getCaretOffset()); try { viewer.getDocument().replace(position, caret - position, ""); //$NON-NLS-1$ @@ -2587,7 +2662,7 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Text operation action to select the previous sub-word. - * + * * @since 3.0 */ protected class SelectPreviousSubWordAction extends PreviousSubWordAction { @@ -2656,18 +2731,20 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I // } // }; - private class PropertyChangeListener implements org.eclipse.core.runtime.Preferences.IPropertyChangeListener { + private class PropertyChangeListener implements + org.eclipse.core.runtime.Preferences.IPropertyChangeListener { /* * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) */ - public void propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) { + public void propertyChange( + org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) { handlePreferencePropertyChanged(event); } }; /** * Finds and marks occurrence annotations. - * + * * @since 3.0 */ class OccurrencesFinderJob extends Job { @@ -2684,7 +2761,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I private Position[] fPositions; - public OccurrencesFinderJob(IDocument document, Position[] positions, ISelection selection) { + public OccurrencesFinderJob(IDocument document, Position[] positions, + ISelection selection) { super(PHPEditorMessages.JavaEditor_markOccurrences_job_name); fDocument = document; fSelection = selection; @@ -2701,7 +2779,9 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I } private boolean isCanceled() { - return fCanceled || fProgressMonitor.isCanceled() || fPostSelectionValidator != null + return fCanceled + || fProgressMonitor.isCanceled() + || fPostSelectionValidator != null && !(fPostSelectionValidator.isValid(fSelection) || fForcedMarkOccurrencesSelection == fSelection) || LinkedModeModel.hasInstalledModel(fDocument); } @@ -2728,7 +2808,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I if (documentProvider == null) return Status.CANCEL_STATUS; - IAnnotationModel annotationModel = documentProvider.getAnnotationModel(getEditorInput()); + IAnnotationModel annotationModel = documentProvider + .getAnnotationModel(getEditorInput()); if (annotationModel == null) return Status.CANCEL_STATUS; @@ -2750,8 +2831,11 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I // Skip this match continue; } - annotationMap.put(new Annotation("net.sourceforge.phpdt.ui.occurrences", false, message), //$NON-NLS-1$ - position); + annotationMap + .put( + new Annotation( + "net.sourceforge.phpdt.ui.occurrences", false, message), //$NON-NLS-1$ + position); } if (isCanceled()) @@ -2759,16 +2843,20 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I synchronized (getLockObject(annotationModel)) { if (annotationModel instanceof IAnnotationModelExtension) { - ((IAnnotationModelExtension) annotationModel).replaceAnnotations(fOccurrenceAnnotations, annotationMap); + ((IAnnotationModelExtension) annotationModel) + .replaceAnnotations(fOccurrenceAnnotations, + annotationMap); } else { removeOccurrenceAnnotations(); Iterator iter = annotationMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry mapEntry = (Map.Entry) iter.next(); - annotationModel.addAnnotation((Annotation) mapEntry.getKey(), (Position) mapEntry.getValue()); + annotationModel.addAnnotation((Annotation) mapEntry + .getKey(), (Position) mapEntry.getValue()); } } - fOccurrenceAnnotations = (Annotation[]) annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]); + fOccurrenceAnnotations = (Annotation[]) annotationMap.keySet() + .toArray(new Annotation[annotationMap.keySet().size()]); } return Status.OK_STATUS; @@ -2777,10 +2865,11 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Cancels the occurrences finder job upon document changes. - * + * * @since 3.0 */ - class OccurrencesFinderJobCanceler implements IDocumentListener, ITextInputListener { + class OccurrencesFinderJobCanceler implements IDocumentListener, + ITextInputListener { public void install() { ISourceViewer sourceViewer = getSourceViewer(); @@ -2805,7 +2894,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I IDocumentProvider documentProvider = getDocumentProvider(); if (documentProvider != null) { - IDocument document = documentProvider.getDocument(getEditorInput()); + IDocument document = documentProvider + .getDocument(getEditorInput()); if (document != null) document.removeDocumentListener(this); } @@ -2829,7 +2919,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, * org.eclipse.jface.text.IDocument) */ - public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) { + public void inputDocumentAboutToBeChanged(IDocument oldInput, + IDocument newInput) { if (oldInput == null) return; @@ -2849,7 +2940,7 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Internal activation listener. - * + * * @since 3.0 */ private class ActivationListener implements IWindowListener { @@ -2859,10 +2950,15 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I * @since 3.1 */ public void windowActivated(IWorkbenchWindow window) { - if (window == getEditorSite().getWorkbenchWindow() && fMarkOccurrenceAnnotations && isActivePart()) { - fForcedMarkOccurrencesSelection = getSelectionProvider().getSelection(); - SelectionListenerWithASTManager.getDefault().forceSelectionChange(PHPEditor.this, - (ITextSelection) fForcedMarkOccurrencesSelection); + if (window == getEditorSite().getWorkbenchWindow() + && fMarkOccurrenceAnnotations && isActivePart()) { + fForcedMarkOccurrencesSelection = getSelectionProvider() + .getSelection(); + SelectionListenerWithASTManager + .getDefault() + .forceSelectionChange( + PHPEditor.this, + (ITextSelection) fForcedMarkOccurrencesSelection); } } @@ -2871,7 +2967,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I * @since 3.1 */ public void windowDeactivated(IWorkbenchWindow window) { - if (window == getEditorSite().getWorkbenchWindow() && fMarkOccurrenceAnnotations && isActivePart()) + if (window == getEditorSite().getWorkbenchWindow() + && fMarkOccurrenceAnnotations && isActivePart()) removeOccurrenceAnnotations(); } @@ -2894,7 +2991,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I * Updates the selection in the editor's widget with the selection of the * outline page. */ - class OutlineSelectionChangedListener extends AbstractSelectionChangedListener { + class OutlineSelectionChangedListener extends + AbstractSelectionChangedListener { public void selectionChanged(SelectionChangedEvent event) { doSelectionChanged(event); } @@ -2902,7 +3000,7 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * The internal shell activation listener for updating occurrences. - * + * * @since 3.0 */ private ActivationListener fActivationListener = new ActivationListener(); @@ -2916,22 +3014,22 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Holds the current occurrence annotations. - * + * * @since 3.0 */ private Annotation[] fOccurrenceAnnotations = null; /** - * Tells whether all occurrences of the element at the current caret location - * are automatically marked in this editor. - * + * Tells whether all occurrences of the element at the current caret + * location are automatically marked in this editor. + * * @since 3.0 */ private boolean fMarkOccurrenceAnnotations; /** * The selection used when forcing occurrence marking through code. - * + * * @since 3.0 */ private ISelection fForcedMarkOccurrencesSelection; @@ -2939,7 +3037,7 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * The document modification stamp at the time when the last occurrence * marking took place. - * + * * @since 3.1 */ private long fMarkOccurrenceModificationStamp = IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP; @@ -2947,16 +3045,16 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * The region of the word under the caret used to when computing the current * occurrence markings. - * + * * @since 3.1 */ private IRegion fMarkOccurrenceTargetRegion; /** - * Tells whether the occurrence annotations are sticky i.e. whether they stay - * even if there's no valid Java element at the current caret position. Only - * valid if {@link #fMarkOccurrenceAnnotations} is true. - * + * Tells whether the occurrence annotations are sticky i.e. whether they + * stay even if there's no valid Java element at the current caret position. + * Only valid if {@link #fMarkOccurrenceAnnotations} is true. + * * @since 3.0 */ private boolean fStickyOccurrenceAnnotations; @@ -2997,7 +3095,7 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I // SelectionChangedListener(); /** * The editor selection changed listener. - * + * * @since 3.0 */ private EditorSelectionChangedListener fEditorSelectionChangedListener; @@ -3018,14 +3116,14 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Indicates whether this editor is about to update any annotation views. - * + * * @since 3.0 */ private boolean fIsUpdatingAnnotationViews = false; /** * The marker that served as last target for a goto marker request. - * + * * @since 3.0 */ private IMarker fLastMarkerTarget = null; @@ -3036,27 +3134,27 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * This editor's projection support - * + * * @since 3.0 */ private ProjectionSupport fProjectionSupport; /** * This editor's projection model updater - * + * * @since 3.0 */ private IJavaFoldingStructureProvider fProjectionModelUpdater; /** * The override and implements indicator manager for this editor. - * + * * @since 3.0 */ // protected OverrideIndicatorManager fOverrideIndicatorManager; /** * The action group for folding. - * + * * @since 3.0 */ private FoldingActionGroup fFoldingGroup; @@ -3078,22 +3176,23 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Returns the most narrow java element including the given offset - * + * * @param offset - * the offset inside of the requested element + * the offset inside of the requested element */ abstract protected IJavaElement getElementAt(int offset); /** - * Returns the java element of this editor's input corresponding to the given - * IJavaElement + * Returns the java element of this editor's input corresponding to the + * given IJavaElement */ abstract protected IJavaElement getCorrespondingElement(IJavaElement element); /** * Sets the input of the editor's outline page. */ - abstract protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input); + abstract protected void setOutlinePageInput(JavaOutlinePage page, + IEditorInput input); /** * Default constructor. @@ -3116,13 +3215,16 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I // jsurfer old code // JavaTextTools textTools = // PHPeclipsePlugin.getDefault().getJavaTextTools(); - // setSourceViewerConfiguration(new PHPSourceViewerConfiguration(textTools, + // setSourceViewerConfiguration(new + // PHPSourceViewerConfiguration(textTools, // this, IPHPPartitions.PHP_PARTITIONING)); //, // IJavaPartitions.JAVA_PARTITIONING)); IPreferenceStore store = createCombinedPreferenceStore(null); setPreferenceStore(store); - JavaTextTools textTools = PHPeclipsePlugin.getDefault().getJavaTextTools(); - setSourceViewerConfiguration(new PHPSourceViewerConfiguration(textTools.getColorManager(), store, this, + JavaTextTools textTools = PHPeclipsePlugin.getDefault() + .getJavaTextTools(); + setSourceViewerConfiguration(new PHPSourceViewerConfiguration(textTools + .getColorManager(), store, this, IPHPPartitions.PHP_PARTITIONING)); // TODO changed in 3.x ? @@ -3139,8 +3241,10 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I // setSourceViewerConfiguration(new // JavaSourceViewerConfiguration(textTools.getColorManager(), store, // this, IJavaPartitions.JAVA_PARTITIONING)); - fMarkOccurrenceAnnotations = store.getBoolean(PreferenceConstants.EDITOR_MARK_OCCURRENCES); - fStickyOccurrenceAnnotations = store.getBoolean(PreferenceConstants.EDITOR_STICKY_OCCURRENCES); + fMarkOccurrenceAnnotations = store + .getBoolean(PreferenceConstants.EDITOR_MARK_OCCURRENCES); + fStickyOccurrenceAnnotations = store + .getBoolean(PreferenceConstants.EDITOR_STICKY_OCCURRENCES); // fMarkTypeOccurrences= // store.getBoolean(PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES); // fMarkMethodOccurrences= @@ -3174,28 +3278,36 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I */ private void updateHoverBehavior() { SourceViewerConfiguration configuration = getSourceViewerConfiguration(); - String[] types = configuration.getConfiguredContentTypes(getSourceViewer()); + String[] types = configuration + .getConfiguredContentTypes(getSourceViewer()); for (int i = 0; i < types.length; i++) { String t = types[i]; - int[] stateMasks = configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t); + int[] stateMasks = configuration.getConfiguredTextHoverStateMasks( + getSourceViewer(), t); ISourceViewer sourceViewer = getSourceViewer(); if (sourceViewer instanceof ITextViewerExtension2) { if (stateMasks != null) { for (int j = 0; j < stateMasks.length; j++) { int stateMask = stateMasks[j]; - ITextHover textHover = configuration.getTextHover(sourceViewer, t, stateMask); - ((ITextViewerExtension2) sourceViewer).setTextHover(textHover, t, stateMask); + ITextHover textHover = configuration.getTextHover( + sourceViewer, t, stateMask); + ((ITextViewerExtension2) sourceViewer).setTextHover( + textHover, t, stateMask); } } else { - ITextHover textHover = configuration.getTextHover(sourceViewer, t); - ((ITextViewerExtension2) sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK); + ITextHover textHover = configuration.getTextHover( + sourceViewer, t); + ((ITextViewerExtension2) sourceViewer).setTextHover( + textHover, t, + ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK); } } else - sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t); + sourceViewer.setTextHover(configuration.getTextHover( + sourceViewer, t), t); } } @@ -3219,7 +3331,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I } boolean isFoldingEnabled() { - return PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_FOLDING_ENABLED); + return PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean( + PreferenceConstants.EDITOR_FOLDING_ENABLED); } /* @@ -3233,34 +3346,45 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I ProjectionViewer projectionViewer = (ProjectionViewer) getSourceViewer(); - fProjectionSupport = new ProjectionSupport(projectionViewer, getAnnotationAccess(), getSharedColors()); - fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.error"); //$NON-NLS-1$ - fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.warning"); //$NON-NLS-1$ - fProjectionSupport.setHoverControlCreator(new IInformationControlCreator() { - public IInformationControl createInformationControl(Shell shell) { - return new CustomSourceInformationControl(shell, IDocument.DEFAULT_CONTENT_TYPE); - } - }); + fProjectionSupport = new ProjectionSupport(projectionViewer, + getAnnotationAccess(), getSharedColors()); + fProjectionSupport + .addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.error"); //$NON-NLS-1$ + fProjectionSupport + .addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.warning"); //$NON-NLS-1$ + fProjectionSupport + .setHoverControlCreator(new IInformationControlCreator() { + public IInformationControl createInformationControl( + Shell shell) { + return new CustomSourceInformationControl(shell, + IDocument.DEFAULT_CONTENT_TYPE); + } + }); fProjectionSupport.install(); - fProjectionModelUpdater = PHPeclipsePlugin.getDefault().getFoldingStructureProviderRegistry().getCurrentFoldingProvider(); + fProjectionModelUpdater = PHPeclipsePlugin.getDefault() + .getFoldingStructureProviderRegistry() + .getCurrentFoldingProvider(); if (fProjectionModelUpdater != null) fProjectionModelUpdater.install(this, projectionViewer); if (isFoldingEnabled()) projectionViewer.doOperation(ProjectionViewer.TOGGLE); - Preferences preferences = PHPeclipsePlugin.getDefault().getPluginPreferences(); + Preferences preferences = PHPeclipsePlugin.getDefault() + .getPluginPreferences(); preferences.addPropertyChangeListener(fPropertyChangeListener); IInformationControlCreator informationControlCreator = new IInformationControlCreator() { public IInformationControl createInformationControl(Shell parent) { boolean cutDown = false; int style = cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL); - return new DefaultInformationControl(parent, SWT.RESIZE, style, new HTMLTextPresenter(cutDown)); + return new DefaultInformationControl(parent, SWT.RESIZE, style, + new HTMLTextPresenter(cutDown)); } }; - fInformationPresenter = new InformationPresenter(informationControlCreator); + fInformationPresenter = new InformationPresenter( + informationControlCreator); fInformationPresenter.setSizeConstraints(60, 10, true, true); fInformationPresenter.install(getSourceViewer()); @@ -3270,7 +3394,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I if (isBrowserLikeLinks()) enableBrowserLikeLinks(); - if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE)) + if (PreferenceConstants.getPreferenceStore().getBoolean( + PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE)) enableOverwriteMode(false); if (fMarkOccurrenceAnnotations) @@ -3284,14 +3409,17 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I private void setWordWrap() { if (getSourceViewer() != null) { getSourceViewer().getTextWidget().setWordWrap( - PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_WRAP_WORDS)); + PHPeclipsePlugin.getDefault().getPreferenceStore() + .getBoolean(PreferenceConstants.EDITOR_WRAP_WORDS)); } } - protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) { + protected void configureSourceViewerDecorationSupport( + SourceViewerDecorationSupport support) { support.setCharacterPairMatcher(fBracketMatcher); - support.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, MATCHING_BRACKETS_COLOR); + support.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, + MATCHING_BRACKETS_COLOR); super.configureSourceViewerDecorationSupport(support); } @@ -3310,20 +3438,23 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I * Jumps to the next enabled annotation according to the given direction. An * annotation type is enabled if it is configured to be in the Next/Previous * tool bar drop down menu and if it is checked. - * + * * @param forward - * true if search direction is forward, - * false if backward + * true if search direction is forward, + * false if backward */ public Annotation gotoAnnotation(boolean forward) { - ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection(); + ITextSelection selection = (ITextSelection) getSelectionProvider() + .getSelection(); Position position = new Position(0, 0); - Annotation annotation=null; + Annotation annotation = null; if (false /* delayed - see bug 18316 */) { - annotation=getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position); + annotation = getNextAnnotation(selection.getOffset(), selection + .getLength(), forward, position); selectAndReveal(position.getOffset(), position.getLength()); } else /* no delay - see bug 18316 */{ - annotation = getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position); + annotation = getNextAnnotation(selection.getOffset(), selection + .getLength(), forward, position); setStatusLineErrorMessage(null); setStatusLineMessage(null); if (annotation != null) { @@ -3337,9 +3468,9 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Returns the lock object for the given annotation model. - * + * * @param annotationModel - * the annotation model + * the annotation model * @return the annotation model's lock object * @since 3.0 */ @@ -3352,9 +3483,9 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Updates the annotation views that show the given annotation. - * + * * @param annotation - * the annotation + * the annotation */ private void updateAnnotationViews(Annotation annotation) { IMarker marker = null; @@ -3377,27 +3508,35 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I try { boolean isProblem = marker.isSubtypeOf(IMarker.PROBLEM); IWorkbenchPage page = getSite().getPage(); - IViewPart view = page.findView(isProblem ? IPageLayout.ID_PROBLEM_VIEW : IPageLayout.ID_TASK_LIST); //$NON-NLS-1$ //$NON-NLS-2$ + IViewPart view = page + .findView(isProblem ? IPageLayout.ID_PROBLEM_VIEW + : IPageLayout.ID_TASK_LIST); //$NON-NLS-1$ //$NON-NLS-2$ if (view != null) { - Method method = view.getClass().getMethod("setSelection", new Class[] { IStructuredSelection.class, boolean.class }); //$NON-NLS-1$ - method.invoke(view, new Object[] { new StructuredSelection(marker), Boolean.TRUE }); + Method method = view + .getClass() + .getMethod( + "setSelection", new Class[] { IStructuredSelection.class, boolean.class }); //$NON-NLS-1$ + method.invoke(view, new Object[] { + new StructuredSelection(marker), Boolean.TRUE }); } } catch (CoreException x) { } catch (NoSuchMethodException x) { } catch (IllegalAccessException x) { } catch (InvocationTargetException x) { } - // ignore exceptions, don't update any of the lists, just set status line + // ignore exceptions, don't update any of the lists, just set status + // line } } /** * Returns this document's complete text. - * + * * @return the document's complete text */ public String get() { - IDocument doc = this.getDocumentProvider().getDocument(this.getEditorInput()); + IDocument doc = this.getDocumentProvider().getDocument( + this.getEditorInput()); return doc.get(); } @@ -3428,8 +3567,9 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I super.createActions(); ActionGroup oeg, ovg, jsg, sg; - fActionGroups = new CompositeActionGroup(new ActionGroup[] { oeg = new OpenEditorActionGroup(this), - // sg= new ShowActionGroup(this), + fActionGroups = new CompositeActionGroup( + new ActionGroup[] { oeg = new OpenEditorActionGroup(this), + // sg= new ShowActionGroup(this), // ovg= new OpenViewActionGroup(this), // jsg= new JavaSearchActionGroup(this) }); @@ -3451,7 +3591,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I // IJavaHelpContextIds.SHOW_JAVADOC_ACTION); Action action = new GotoMatchingBracketAction(this); - action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_MATCHING_BRACKET); + action + .setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_MATCHING_BRACKET); setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action); // action= new @@ -3521,7 +3662,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I // setAction("RemoveOccurrenceAnnotations", action); //$NON-NLS-1$ // add annotation actions - action = new JavaSelectMarkerRulerAction2(PHPEditorMessages.getResourceBundle(), "Editor.RulerAnnotationSelection.", this); //$NON-NLS-1$ + action = new JavaSelectMarkerRulerAction2(PHPEditorMessages + .getResourceBundle(), "Editor.RulerAnnotationSelection.", this); //$NON-NLS-1$ setAction("AnnotationAction", action); //$NON-NLS-1$ } @@ -3531,7 +3673,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I if (getSourceViewer() instanceof JavaSourceViewer) { JavaSourceViewer viewer = (JavaSourceViewer) getSourceViewer(); if (viewer.getReconciler() == null) { - IReconciler reconciler = getSourceViewerConfiguration().getReconciler(viewer); + IReconciler reconciler = getSourceViewerConfiguration() + .getReconciler(viewer); if (reconciler != null) { reconciler.install(viewer); viewer.setReconciler(reconciler); @@ -3558,8 +3701,10 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I protected void setPreferenceStore(IPreferenceStore store) { super.setPreferenceStore(store); if (getSourceViewerConfiguration() instanceof PHPSourceViewerConfiguration) { - JavaTextTools textTools = PHPeclipsePlugin.getDefault().getJavaTextTools(); - setSourceViewerConfiguration(new PHPSourceViewerConfiguration(textTools.getColorManager(), store, this, + JavaTextTools textTools = PHPeclipsePlugin.getDefault() + .getJavaTextTools(); + setSourceViewerConfiguration(new PHPSourceViewerConfiguration( + textTools.getColorManager(), store, this, IPHPPartitions.PHP_PARTITIONING)); } if (getSourceViewer() instanceof JavaSourceViewer) @@ -3608,7 +3753,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I } if (fPropertyChangeListener != null) { - Preferences preferences = PHPeclipsePlugin.getDefault().getPluginPreferences(); + Preferences preferences = PHPeclipsePlugin.getDefault() + .getPluginPreferences(); preferences.removePropertyChangeListener(fPropertyChangeListener); fPropertyChangeListener = null; } @@ -3633,8 +3779,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * The PHPEditor implementation of this - * AbstractTextEditor method performs any extra revert behavior - * required by the php editor. + * AbstractTextEditor method performs any extra revert + * behavior required by the php editor. */ // public void doRevertToSaved() { // super.doRevertToSaved(); @@ -3742,7 +3888,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I // install & register preference store listener sourceViewer.configure(getSourceViewerConfiguration()); - getSourceViewerDecorationSupport(sourceViewer).install(getPreferenceStore()); + getSourceViewerDecorationSupport(sourceViewer).install( + getPreferenceStore()); if (isBrowserLikeLinks()) enableBrowserLikeLinks(); @@ -3762,10 +3909,13 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I */ public void editorContextMenuAboutToShow(MenuManager menu) { super.editorContextMenuAboutToShow(menu); - menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, new Separator(IContextMenuConstants.GROUP_OPEN)); - menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(IContextMenuConstants.GROUP_SHOW)); + menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, + new Separator(IContextMenuConstants.GROUP_OPEN)); + menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker( + IContextMenuConstants.GROUP_SHOW)); - ActionContext context = new ActionContext(getSelectionProvider().getSelection()); + ActionContext context = new ActionContext(getSelectionProvider() + .getSelection()); fContextMenuGroup.setContext(context); fContextMenuGroup.fillContextMenu(menu); fContextMenuGroup.setContext(null); @@ -3801,28 +3951,30 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I } /** - * Synchronizes the outliner selection with the given element position in the - * editor. - * + * Synchronizes the outliner selection with the given element position in + * the editor. + * * @param element - * the java element to select + * the java element to select */ protected void synchronizeOutlinePage(ISourceReference element) { synchronizeOutlinePage(element, true); } /** - * Synchronizes the outliner selection with the given element position in the - * editor. - * + * Synchronizes the outliner selection with the given element position in + * the editor. + * * @param element - * the java element to select + * the java element to select * @param checkIfOutlinePageActive - * true if check for active outline page needs to be - * done + * true if check for active outline page needs to + * be done */ - protected void synchronizeOutlinePage(ISourceReference element, boolean checkIfOutlinePageActive) { - if (fOutlinePage != null && element != null && !(checkIfOutlinePageActive && isJavaOutlinePageActive())) { + protected void synchronizeOutlinePage(ISourceReference element, + boolean checkIfOutlinePageActive) { + if (fOutlinePage != null && element != null + && !(checkIfOutlinePageActive && isJavaOutlinePageActive())) { fOutlineSelectionChangedListener.uninstall(fOutlinePage); fOutlinePage.select(element); fOutlineSelectionChangedListener.install(fOutlinePage); @@ -3830,8 +3982,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I } /** - * Synchronizes the outliner selection with the actual cursor position in the - * editor. + * Synchronizes the outliner selection with the actual cursor position in + * the editor. */ public void synchronizeOutlinePageSelection() { synchronizeOutlinePage(computeHighlightRangeSourceReference()); @@ -3868,7 +4020,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I ISelection selection = getSelectionProvider().getSelection(); if (selection instanceof TextSelection) { TextSelection textSelection = (TextSelection) selection; - if (textSelection.getOffset() != 0 || textSelection.getLength() != 0) + if (textSelection.getOffset() != 0 + || textSelection.getLength() != 0) markInNavigationHistory(); } @@ -3960,9 +4113,10 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I // IClassFile) // { /* - * If the element is an ICompilationUnit this unit is either the input of - * this editor or not being displayed. In both cases, nothing should - * happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128) + * If the element is an ICompilationUnit this unit is either the + * input of this editor or not being displayed. In both cases, + * nothing should happened. + * (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128) */ return; } @@ -4012,13 +4166,15 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I if (required == IShowInTargetList.class) { return new IShowInTargetList() { public String[] getShowInTargetIds() { - return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV }; + return new String[] { JavaUI.ID_PACKAGES, + IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV }; } }; } if (fProjectionSupport != null) { - Object adapter = fProjectionSupport.getAdapter(getSourceViewer(), required); + Object adapter = fProjectionSupport.getAdapter(getSourceViewer(), + required); if (adapter != null) return adapter; } @@ -4075,18 +4231,23 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I IJavaElement element = getElementAt(offset); while (element instanceof ISourceReference) { - ISourceRange range = ((ISourceReference) element).getSourceRange(); - if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) { + ISourceRange range = ((ISourceReference) element) + .getSourceRange(); + if (offset < range.getOffset() + range.getLength() + && range.getOffset() < offset + length) { ISourceViewer viewer = getSourceViewer(); if (viewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension = (ITextViewerExtension5) viewer; - extension.exposeModelRange(new Region(range.getOffset(), range.getLength())); + extension.exposeModelRange(new Region( + range.getOffset(), range.getLength())); } - setHighlightRange(range.getOffset(), range.getLength(), true); + setHighlightRange(range.getOffset(), range.getLength(), + true); if (fOutlinePage != null) { - fOutlineSelectionChangedListener.uninstall(fOutlinePage); + fOutlineSelectionChangedListener + .uninstall(fOutlinePage); fOutlinePage.select((ISourceReference) element); fOutlineSelectionChangedListener.install(fOutlinePage); } @@ -4169,10 +4330,12 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I if (PreferenceConstants.EDITOR_TAB_WIDTH.equals(property)) { Object value = event.getNewValue(); if (value instanceof Integer) { - sourceViewer.getTextWidget().setTabs(((Integer) value).intValue()); + sourceViewer.getTextWidget().setTabs( + ((Integer) value).intValue()); } else if (value instanceof String) { try { - sourceViewer.getTextWidget().setTabs(Integer.parseInt((String) value)); + sourceViewer.getTextWidget().setTabs( + Integer.parseInt((String) value)); } catch (NumberFormatException e) { // bug #1038071 - set default tab: sourceViewer.getTextWidget().setTabs(80); @@ -4216,7 +4379,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I return; } - if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE.equals(property)) { + if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE + .equals(property)) { if (event.getNewValue() instanceof Boolean) { Boolean disable = (Boolean) event.getNewValue(); enableOverwriteMode(!disable.booleanValue()); @@ -4227,9 +4391,11 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I boolean newBooleanValue = false; Object newValue = event.getNewValue(); if (newValue != null) - newBooleanValue = Boolean.valueOf(newValue.toString()).booleanValue(); + newBooleanValue = Boolean.valueOf(newValue.toString()) + .booleanValue(); - if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE.equals(property)) { + if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE + .equals(property)) { if (newBooleanValue) selectionChanged(); return; @@ -4261,7 +4427,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I // if (stickyOccurrenceAnnotations != fStickyOccurrenceAnnotations) // { - ((PHPSourceViewerConfiguration) getSourceViewerConfiguration()).handlePropertyChangeEvent(event); + ((PHPSourceViewerConfiguration) getSourceViewerConfiguration()) + .handlePropertyChangeEvent(event); // if (affectsOverrideIndicatorAnnotations(event)) { // if (isShowingOverrideIndicators()) { @@ -4280,7 +4447,9 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I if (fProjectionModelUpdater != null) fProjectionModelUpdater.uninstall(); // either freshly enabled or provider changed - fProjectionModelUpdater = PHPeclipsePlugin.getDefault().getFoldingStructureProviderRegistry().getCurrentFoldingProvider(); + fProjectionModelUpdater = PHPeclipsePlugin.getDefault() + .getFoldingStructureProviderRegistry() + .getCurrentFoldingProvider(); if (fProjectionModelUpdater != null) { fProjectionModelUpdater.install(this, projectionViewer); } @@ -4367,7 +4536,7 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Return whether the browser like links should be enabled according to the * preference store settings. - * + * * @return true if the browser like links should be enabled */ private boolean isBrowserLikeLinks() { @@ -4398,16 +4567,18 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Handles a property change event describing a change of the java core's * preferences and updates the preference related editor properties. - * + * * @param event - * the property change event + * the property change event */ - protected void handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) { + protected void handlePreferencePropertyChanged( + org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) { if (COMPILER_TASK_TAGS.equals(event.getProperty())) { ISourceViewer sourceViewer = getSourceViewer(); if (sourceViewer != null - && affectsTextPresentation(new PropertyChangeEvent(event.getSource(), event.getProperty(), event.getOldValue(), event - .getNewValue()))) + && affectsTextPresentation(new PropertyChangeEvent(event + .getSource(), event.getProperty(), event + .getOldValue(), event.getNewValue()))) sourceViewer.invalidateTextPresentation(); } if (PreferenceConstants.EDITOR_WRAP_WORDS.equals(event.getProperty())) { @@ -4416,9 +4587,9 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I } /** - * Return whether the line number ruler column should be visible according to - * the preference store settings. - * + * Return whether the line number ruler column should be visible according + * to the preference store settings. + * * @return true if the line numbers should be visible */ // protected boolean isLineNumberRulerVisible() { @@ -4457,9 +4628,9 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Initializes the given line number ruler column from the preference store. - * + * * @param rulerColumn - * the ruler column to be initialized + * the ruler column to be initialized */ // protected void initializeLineNumberRulerColumn(LineNumberRulerColumn // rulerColumn) { @@ -4637,7 +4808,7 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I * Preference key for key modifier mask of browser like links. The value is * only used if the value of EDITOR_BROWSER_LIKE_LINKS cannot * be resolved to valid SWT modifier bits. - * + * * @since 2.1.1 */ private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK; @@ -4656,7 +4827,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I return false; try { - return isBracket(document.getChar(offset - 1)) && isBracket(document.getChar(offset)); + return isBracket(document.getChar(offset - 1)) + && isBracket(document.getChar(offset)); } catch (BadLocationException e) { return false; @@ -4716,15 +4888,17 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I // } /** * Returns the Java element wrapped by this editors input. - * + * * @return the Java element wrapped by this editors input. * @since 3.0 */ abstract protected IJavaElement getInputJavaElement(); protected void updateStatusLine() { - ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection(); - Annotation annotation = getAnnotation(selection.getOffset(), selection.getLength()); + ITextSelection selection = (ITextSelection) getSelectionProvider() + .getSelection(); + Annotation annotation = getAnnotation(selection.getOffset(), selection + .getLength()); setStatusLineErrorMessage(null); setStatusLineMessage(null); if (annotation != null) { @@ -4734,7 +4908,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I } finally { fIsUpdatingAnnotationViews = false; } - if (annotation instanceof IJavaAnnotation && ((IJavaAnnotation) annotation).isProblem()) + if (annotation instanceof IJavaAnnotation + && ((IJavaAnnotation) annotation).isProblem()) setStatusLineMessage(annotation.getText()); } } @@ -4753,7 +4928,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I int selectionLength = Math.abs(selection.getLength()); if (selectionLength > 1) { - setStatusLineErrorMessage(PHPEditorMessages.getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$ + setStatusLineErrorMessage(PHPEditorMessages + .getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$ sourceViewer.getTextWidget().getDisplay().beep(); return; } @@ -4765,7 +4941,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I IRegion region = fBracketMatcher.match(document, sourceCaretOffset); if (region == null) { - setStatusLineErrorMessage(PHPEditorMessages.getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$ + setStatusLineErrorMessage(PHPEditorMessages + .getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$ sourceViewer.getTextWidget().getDisplay().beep(); return; } @@ -4777,7 +4954,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I return; int anchor = fBracketMatcher.getAnchor(); - int targetOffset = (PHPPairMatcher.RIGHT == anchor) ? offset : offset + length - 1; + int targetOffset = (PHPPairMatcher.RIGHT == anchor) ? offset : offset + + length - 1; boolean visible = false; if (sourceViewer instanceof ITextViewerExtension5) { @@ -4785,11 +4963,14 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I visible = (extension.modelOffset2WidgetOffset(targetOffset) > -1); } else { IRegion visibleRegion = sourceViewer.getVisibleRegion(); - visible = (targetOffset >= visibleRegion.getOffset() && targetOffset < visibleRegion.getOffset() + visibleRegion.getLength()); + visible = (targetOffset >= visibleRegion.getOffset() && targetOffset < visibleRegion + .getOffset() + + visibleRegion.getLength()); } if (!visible) { - setStatusLineErrorMessage(PHPEditorMessages.getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$ + setStatusLineErrorMessage(PHPEditorMessages + .getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$ sourceViewer.getTextWidget().getDisplay().beep(); return; } @@ -4803,9 +4984,9 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Ses the given message as error message to this editor's status line. - * + * * @param msg - * message to be set + * message to be set */ protected void setStatusLineErrorMessage(String msg) { IEditorStatusLine statusLine = (IEditorStatusLine) getAdapter(IEditorStatusLine.class); @@ -4815,9 +4996,9 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Sets the given message as message to this editor's status line. - * + * * @param msg - * message to be set + * message to be set * @since 3.0 */ protected void setStatusLineMessage(String msg) { @@ -4830,19 +5011,20 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I * Returns the annotation closest to the given range respecting the given * direction. If an annotation is found, the annotations current position is * copied into the provided annotation position. - * + * * @param offset - * the region offset + * the region offset * @param length - * the region length + * the region length * @param forward - * true for forwards, false for - * backward + * true for forwards, false for + * backward * @param annotationPosition - * the position of the found annotation + * the position of the found annotation * @return the found annotation */ - private Annotation getNextAnnotation(final int offset, final int length, boolean forward, Position annotationPosition) { + private Annotation getNextAnnotation(final int offset, final int length, + boolean forward, Position annotationPosition) { Annotation nextAnnotation = null; Position nextAnnotationPosition = null; @@ -4850,26 +5032,32 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I Position containingAnnotationPosition = null; boolean currentAnnotation = false; - IDocument document = getDocumentProvider().getDocument(getEditorInput()); + IDocument document = getDocumentProvider() + .getDocument(getEditorInput()); int endOfDocument = document.getLength(); int distance = Integer.MAX_VALUE; - IAnnotationModel model = getDocumentProvider().getAnnotationModel(getEditorInput()); + IAnnotationModel model = getDocumentProvider().getAnnotationModel( + getEditorInput()); Iterator e = new JavaAnnotationIterator(model, true, true); while (e.hasNext()) { Annotation a = (Annotation) e.next(); - if ((a instanceof IJavaAnnotation) && ((IJavaAnnotation) a).hasOverlay() || !isNavigationTarget(a)) + if ((a instanceof IJavaAnnotation) + && ((IJavaAnnotation) a).hasOverlay() + || !isNavigationTarget(a)) continue; Position p = model.getPosition(a); if (p == null) continue; - if (forward && p.offset == offset || !forward && p.offset + p.getLength() == offset + length) {// || + if (forward && p.offset == offset || !forward + && p.offset + p.getLength() == offset + length) {// || // p.includes(offset)) // { if (containingAnnotation == null - || (forward && p.length >= containingAnnotationPosition.length || !forward + || (forward + && p.length >= containingAnnotationPosition.length || !forward && p.length >= containingAnnotationPosition.length)) { containingAnnotation = a; containingAnnotationPosition = p; @@ -4883,17 +5071,22 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I if (currentDistance < 0) currentDistance = endOfDocument + currentDistance; - if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) { + if (currentDistance < distance + || currentDistance == distance + && p.length < nextAnnotationPosition.length) { distance = currentDistance; nextAnnotation = a; nextAnnotationPosition = p; } } else { - currentDistance = offset + length - (p.getOffset() + p.length); + currentDistance = offset + length + - (p.getOffset() + p.length); if (currentDistance < 0) currentDistance = endOfDocument + currentDistance; - if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) { + if (currentDistance < distance + || currentDistance == distance + && p.length < nextAnnotationPosition.length) { distance = currentDistance; nextAnnotation = a; nextAnnotationPosition = p; @@ -4901,9 +5094,12 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I } } } - if (containingAnnotationPosition != null && (!currentAnnotation || nextAnnotation == null)) { - annotationPosition.setOffset(containingAnnotationPosition.getOffset()); - annotationPosition.setLength(containingAnnotationPosition.getLength()); + if (containingAnnotationPosition != null + && (!currentAnnotation || nextAnnotation == null)) { + annotationPosition.setOffset(containingAnnotationPosition + .getOffset()); + annotationPosition.setLength(containingAnnotationPosition + .getLength()); return containingAnnotation; } if (nextAnnotationPosition != null) { @@ -4917,16 +5113,17 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Returns the annotation overlapping with the given range or * null. - * + * * @param offset - * the region offset + * the region offset * @param length - * the region length + * the region length * @return the found annotation or null * @since 3.0 */ private Annotation getAnnotation(int offset, int length) { - IAnnotationModel model = getDocumentProvider().getAnnotationModel(getEditorInput()); + IAnnotationModel model = getDocumentProvider().getAnnotationModel( + getEditorInput()); Iterator e = new JavaAnnotationIterator(model, true, true); while (e.hasNext()) { Annotation a = (Annotation) e.next(); @@ -4942,48 +5139,54 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I } /** - * Returns whether the given annotation is configured as a target for the "Go - * to Next/Previous Annotation" actions - * + * Returns whether the given annotation is configured as a target for the + * "Go to Next/Previous Annotation" actions + * * @param annotation - * the annotation + * the annotation * @return true if this is a target, false * otherwise * @since 3.0 */ protected boolean isNavigationTarget(Annotation annotation) { Preferences preferences = EditorsUI.getPluginPreferences(); - AnnotationPreference preference = getAnnotationPreferenceLookup().getAnnotationPreference(annotation); + AnnotationPreference preference = getAnnotationPreferenceLookup() + .getAnnotationPreference(annotation); // See bug 41689 // String key= forward ? preference.getIsGoToNextNavigationTargetKey() : // preference.getIsGoToPreviousNavigationTargetKey(); - String key = preference == null ? null : preference.getIsGoToNextNavigationTargetKey(); + String key = preference == null ? null : preference + .getIsGoToNextNavigationTargetKey(); return (key != null && preferences.getBoolean(key)); } /** * Returns a segmentation of the line of the given document appropriate for - * bidi rendering. The default implementation returns only the string literals - * of a php code line as segments. - * + * bidi rendering. The default implementation returns only the string + * literals of a php code line as segments. + * * @param document - * the document + * the document * @param lineOffset - * the offset of the line + * the offset of the line * @return the line's bidi segmentation * @throws BadLocationException - * in case lineOffset is not valid in document + * in case lineOffset is not valid in document */ - public static int[] getBidiLineSegments(IDocument document, int lineOffset) throws BadLocationException { + public static int[] getBidiLineSegments(IDocument document, int lineOffset) + throws BadLocationException { IRegion line = document.getLineInformationOfOffset(lineOffset); - ITypedRegion[] linePartitioning = document.computePartitioning(lineOffset, line.getLength()); + ITypedRegion[] linePartitioning = document.computePartitioning( + lineOffset, line.getLength()); List segmentation = new ArrayList(); for (int i = 0; i < linePartitioning.length; i++) { - if (IPHPPartitions.PHP_STRING_DQ.equals(linePartitioning[i].getType())) { + if (IPHPPartitions.PHP_STRING_DQ.equals(linePartitioning[i] + .getType())) { segmentation.add(linePartitioning[i]); - } else if (IPHPPartitions.PHP_STRING_HEREDOC.equals(linePartitioning[i].getType())) { + } else if (IPHPPartitions.PHP_STRING_HEREDOC + .equals(linePartitioning[i].getType())) { segmentation.add(linePartitioning[i]); } } @@ -5024,11 +5227,11 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I * Returns a segmentation of the given line appropriate for bidi rendering. * The default implementation returns only the string literals of a php code * line as segments. - * + * * @param lineOffset - * the offset of the line + * the offset of the line * @param line - * the content of the line + * the content of the line * @return the line's bidi segmentation */ protected int[] getBidiLineSegments(int lineOffset, String line) { @@ -5046,7 +5249,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I } /* - * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int) + * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, + * int) */ // protected final ISourceViewer createSourceViewer( // Composite parent, @@ -5089,7 +5293,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I // return store.getBoolean(OVERVIEW_RULER); // } /* - * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int) + * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, + * int) */ // protected ISourceViewer createJavaSourceViewer( // Composite parent, @@ -5101,25 +5306,32 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I // isOverviewRulerVisible(), styles); // } /* - * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int) + * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, + * int) */ - protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, + protected ISourceViewer createJavaSourceViewer(Composite parent, + IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles, IPreferenceStore store) { - return new JavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles, store); + return new JavaSourceViewer(parent, verticalRuler, getOverviewRuler(), + isOverviewRulerVisible(), styles, store); } /* - * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int) + * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, + * int) */ - protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) { + protected final ISourceViewer createSourceViewer(Composite parent, + IVerticalRuler verticalRuler, int styles) { - ISourceViewer viewer = createJavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles, + ISourceViewer viewer = createJavaSourceViewer(parent, verticalRuler, + getOverviewRuler(), isOverviewRulerVisible(), styles, getPreferenceStore()); StyledText text = viewer.getTextWidget(); text.addBidiSegmentListener(new BidiSegmentListener() { public void lineGetSegments(BidiSegmentEvent event) { - event.segments = getBidiLineSegments(event.lineOffset, event.lineText); + event.segments = getBidiLineSegments(event.lineOffset, + event.lineText); } }); @@ -5136,23 +5348,25 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I * @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent) */ protected boolean affectsTextPresentation(PropertyChangeEvent event) { - return ((PHPSourceViewerConfiguration) getSourceViewerConfiguration()).affectsTextPresentation(event) + return ((PHPSourceViewerConfiguration) getSourceViewerConfiguration()) + .affectsTextPresentation(event) || super.affectsTextPresentation(event); } // // protected boolean affectsTextPresentation(PropertyChangeEvent event) { - // JavaTextTools textTools = PHPeclipsePlugin.getDefault().getJavaTextTools(); + // JavaTextTools textTools = + // PHPeclipsePlugin.getDefault().getJavaTextTools(); // return textTools.affectsBehavior(event); // } /** * Creates and returns the preference store for this Java editor with the * given input. - * + * * @param input - * The editor input for which to create the preference store + * The editor input for which to create the preference store * @return the preference store for this editor - * + * * @since 3.0 */ private IPreferenceStore createCombinedPreferenceStore(IEditorInput input) { @@ -5160,25 +5374,31 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I IJavaProject project = EditorUtility.getJavaProject(input); if (project != null) - stores.add(new OptionsAdapter(project.getOptions(false), PHPeclipsePlugin.getDefault().getMockupPreferenceStore(), + stores.add(new OptionsAdapter(project.getOptions(false), + PHPeclipsePlugin.getDefault().getMockupPreferenceStore(), new OptionsAdapter.IPropertyChangeEventFilter() { public boolean isFiltered(PropertyChangeEvent event) { IJavaElement inputJavaElement = getInputJavaElement(); - IJavaProject javaProject = inputJavaElement != null ? inputJavaElement.getJavaProject() : null; + IJavaProject javaProject = inputJavaElement != null ? inputJavaElement + .getJavaProject() + : null; if (javaProject == null) return true; - return !javaProject.getProject().equals(event.getSource()); + return !javaProject.getProject().equals( + event.getSource()); } })); stores.add(PHPeclipsePlugin.getDefault().getPreferenceStore()); - stores.add(new PreferencesAdapter(JavaCore.getPlugin().getPluginPreferences())); + stores.add(new PreferencesAdapter(JavaCore.getPlugin() + .getPluginPreferences())); stores.add(EditorsUI.getPreferenceStore()); - return new ChainedPreferenceStore((IPreferenceStore[]) stores.toArray(new IPreferenceStore[stores.size()])); + return new ChainedPreferenceStore((IPreferenceStore[]) stores + .toArray(new IPreferenceStore[stores.size()])); } /** @@ -5190,7 +5410,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I ITextSelection s = (ITextSelection) provider.getSelection(); Position errorPosition = new Position(0, 0); - IJavaAnnotation nextError = getNextError(s.getOffset(), forward, errorPosition); + IJavaAnnotation nextError = getNextError(s.getOffset(), forward, + errorPosition); if (nextError != null) { @@ -5212,14 +5433,16 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I if (marker != null) { IWorkbenchPage page = getSite().getPage(); - IViewPart view = view = page.findView("org.eclipse.ui.views.TaskList"); //$NON-NLS-1$ + IViewPart view = view = page + .findView("org.eclipse.ui.views.TaskList"); //$NON-NLS-1$ if (view instanceof TaskList) { StructuredSelection ss = new StructuredSelection(marker); ((TaskList) view).setSelection(ss, true); } } - selectAndReveal(errorPosition.getOffset(), errorPosition.getLength()); + selectAndReveal(errorPosition.getOffset(), errorPosition + .getLength()); // setStatusLineErrorMessage(nextError.getMessage()); } else { @@ -5229,16 +5452,19 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I } } - private IJavaAnnotation getNextError(int offset, boolean forward, Position errorPosition) { + private IJavaAnnotation getNextError(int offset, boolean forward, + Position errorPosition) { IJavaAnnotation nextError = null; Position nextErrorPosition = null; - IDocument document = getDocumentProvider().getDocument(getEditorInput()); + IDocument document = getDocumentProvider() + .getDocument(getEditorInput()); int endOfDocument = document.getLength(); int distance = 0; - IAnnotationModel model = getDocumentProvider().getAnnotationModel(getEditorInput()); + IAnnotationModel model = getDocumentProvider().getAnnotationModel( + getEditorInput()); Iterator e = new JavaAnnotationIterator(model, false); while (e.hasNext()) { @@ -5254,11 +5480,13 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I if (forward) { currentDistance = p.getOffset() - offset; if (currentDistance < 0) - currentDistance = endOfDocument - offset + p.getOffset(); + currentDistance = endOfDocument - offset + + p.getOffset(); } else { currentDistance = offset - p.getOffset(); if (currentDistance < 0) - currentDistance = offset + endOfDocument - p.getOffset(); + currentDistance = offset + endOfDocument + - p.getOffset(); } if (nextError == null || currentDistance < distance) { @@ -5286,7 +5514,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I protected void installOverrideIndicator(boolean waitForReconcilation) { uninstallOverrideIndicator(); - IAnnotationModel model = getDocumentProvider().getAnnotationModel(getEditorInput()); + IAnnotationModel model = getDocumentProvider().getAnnotationModel( + getEditorInput()); final IJavaElement inputElement = getInputJavaElement(); if (model == null || inputElement == null) @@ -5297,7 +5526,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I // // if (provideAST) { // Job job= new - // Job(JavaEditorMessages.getString("OverrideIndicatorManager.intallJob")) { + // Job(JavaEditorMessages.getString("OverrideIndicatorManager.intallJob")) + // { // //$NON-NLS-1$ // /* // * @see @@ -5308,7 +5538,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I // CompilationUnit ast= // JavaPlugin.getDefault().getASTProvider().getAST(inputElement, true, // null); - // if (fOverrideIndicatorManager != null) // editor might have been closed + // if (fOverrideIndicatorManager != null) // editor might have been + // closed // in the meanwhile // fOverrideIndicatorManager.reconciled(ast, true, monitor); // return Status.OK_STATUS; @@ -5322,7 +5553,7 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Tells whether override indicators are shown. - * + * * @return true if the override indicators are shown * @since 3.0 */ @@ -5337,13 +5568,13 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I // } /** * Returns the boolean preference for the given key. - * + * * @param store - * the preference store + * the preference store * @param key - * the preference key - * @return true if the key exists in the store and its value is - * true + * the preference key + * @return true if the key exists in the store and its value + * is true * @since 3.0 */ private boolean getBoolean(IPreferenceStore store, String key) { @@ -5351,7 +5582,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I } protected boolean isPrefQuickDiffAlwaysOn() { - return false; // never show change ruler for the non-editable java editor. + return false; // never show change ruler for the non-editable java + // editor. // Overridden in subclasses like PHPUnitEditor } @@ -5368,11 +5600,13 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I setAction(ITextEditorActionDefinitionIds.LINE_START, action); action = new SmartLineStartAction(textWidget, true); - action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_LINE_START); + action + .setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_LINE_START); setAction(ITextEditorActionDefinitionIds.SELECT_LINE_START, action); action = new NavigatePreviousSubWordAction(); - action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_PREVIOUS); + action + .setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_PREVIOUS); setAction(ITextEditorActionDefinitionIds.WORD_PREVIOUS, action); textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_LEFT, SWT.NULL); @@ -5382,94 +5616,107 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_RIGHT, SWT.NULL); action = new SelectPreviousSubWordAction(); - action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS); + action + .setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS); setAction(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS, action); - textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_LEFT, SWT.NULL); + textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_LEFT, + SWT.NULL); action = new SelectNextSubWordAction(); - action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT); + action + .setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT); setAction(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT, action); - textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_RIGHT, SWT.NULL); + textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_RIGHT, + SWT.NULL); } /* * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createCompositeRuler() */ -// protected CompositeRuler createCompositeRuler() { -// if (!getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER)) -// return super.createCompositeRuler(); -// -// CompositeRuler ruler = new CompositeRuler(); -// AnnotationRulerColumn column = new AnnotationRulerColumn(VERTICAL_RULER_WIDTH, getAnnotationAccess()); -// column.setHover(new JavaExpandHover(ruler, getAnnotationAccess(), new IDoubleClickListener() { -// -// public void doubleClick(DoubleClickEvent event) { -// // for now: just invoke ruler double click action -// triggerAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK); -// } -// -// private void triggerAction(String actionID) { -// IAction action = getAction(actionID); -// if (action != null) { -// if (action instanceof IUpdate) -// ((IUpdate) action).update(); -// // hack to propagate line change -// if (action instanceof ISelectionListener) { -// ((ISelectionListener) action).selectionChanged(null, null); -// } -// if (action.isEnabled()) -// action.run(); -// } -// } -// -// })); -// ruler.addDecorator(0, column); -// -// if (isLineNumberRulerVisible()) -// ruler.addDecorator(1, createLineNumberRulerColumn()); -// else if (isPrefQuickDiffAlwaysOn()) -// ruler.addDecorator(1, createChangeRulerColumn()); -// -// return ruler; -// } - + // protected CompositeRuler createCompositeRuler() { + // if + // (!getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER)) + // return super.createCompositeRuler(); + // + // CompositeRuler ruler = new CompositeRuler(); + // AnnotationRulerColumn column = new + // AnnotationRulerColumn(VERTICAL_RULER_WIDTH, getAnnotationAccess()); + // column.setHover(new JavaExpandHover(ruler, getAnnotationAccess(), new + // IDoubleClickListener() { + // + // public void doubleClick(DoubleClickEvent event) { + // // for now: just invoke ruler double click action + // triggerAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK); + // } + // + // private void triggerAction(String actionID) { + // IAction action = getAction(actionID); + // if (action != null) { + // if (action instanceof IUpdate) + // ((IUpdate) action).update(); + // // hack to propagate line change + // if (action instanceof ISelectionListener) { + // ((ISelectionListener) action).selectionChanged(null, null); + // } + // if (action.isEnabled()) + // action.run(); + // } + // } + // + // })); + // ruler.addDecorator(0, column); + // + // if (isLineNumberRulerVisible()) + // ruler.addDecorator(1, createLineNumberRulerColumn()); + // else if (isPrefQuickDiffAlwaysOn()) + // ruler.addDecorator(1, createChangeRulerColumn()); + // + // return ruler; + // } /* * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createAnnotationRulerColumn(org.eclipse.jface.text.source.CompositeRuler) * @since 3.2 */ - protected IVerticalRulerColumn createAnnotationRulerColumn(CompositeRuler ruler) { - if (!getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER)) + protected IVerticalRulerColumn createAnnotationRulerColumn( + CompositeRuler ruler) { + if (!getPreferenceStore().getBoolean( + PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER)) return super.createAnnotationRulerColumn(ruler); - AnnotationRulerColumn column= new AnnotationRulerColumn(VERTICAL_RULER_WIDTH, getAnnotationAccess()); - column.setHover(new JavaExpandHover(ruler, getAnnotationAccess(), new IDoubleClickListener() { + AnnotationRulerColumn column = new AnnotationRulerColumn( + VERTICAL_RULER_WIDTH, getAnnotationAccess()); + column.setHover(new JavaExpandHover(ruler, getAnnotationAccess(), + new IDoubleClickListener() { - public void doubleClick(DoubleClickEvent event) { - // for now: just invoke ruler double click action - triggerAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK); - } + public void doubleClick(DoubleClickEvent event) { + // for now: just invoke ruler double click action + triggerAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK); + } - private void triggerAction(String actionID) { - IAction action= getAction(actionID); - if (action != null) { - if (action instanceof IUpdate) - ((IUpdate) action).update(); - // hack to propagate line change - if (action instanceof ISelectionListener) { - ((ISelectionListener)action).selectionChanged(null, null); + private void triggerAction(String actionID) { + IAction action = getAction(actionID); + if (action != null) { + if (action instanceof IUpdate) + ((IUpdate) action).update(); + // hack to propagate line change + if (action instanceof ISelectionListener) { + ((ISelectionListener) action).selectionChanged( + null, null); + } + if (action.isEnabled()) + action.run(); + } } - if (action.isEnabled()) - action.run(); - } - } - })); - + })); + return column; } + /** - * Returns the folding action group, or null if there is none. - * + * Returns the folding action group, or null if there is + * none. + * * @return the folding action group, or null if there is none * @since 3.0 */ @@ -5507,14 +5754,15 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * React to changed selection. - * + * * @since 3.0 */ protected void selectionChanged() { if (getSelectionProvider() == null) return; ISourceReference element = computeHighlightRangeSourceReference(); - if (getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE)) + if (getPreferenceStore().getBoolean( + PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE)) synchronizeOutlinePage(element); setSelection(element, false); updateStatusLine(); @@ -5522,7 +5770,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I private boolean isJavaOutlinePageActive() { IWorkbenchPart part = getActivePart(); - return part instanceof ContentOutline && ((ContentOutline) part).getCurrentPage() == fOutlinePage; + return part instanceof ContentOutline + && ((ContentOutline) part).getCurrentPage() == fOutlinePage; } private IWorkbenchPart getActivePart() { @@ -5536,7 +5785,7 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I * Computes and returns the source reference that includes the caret and * serves as provider for the outline page selection and the editor range * indication. - * + * * @return the computed source reference * @since 3.0 */ @@ -5552,7 +5801,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I int caret = 0; if (sourceViewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer; - caret = extension.widgetOffset2ModelOffset(styledText.getCaretOffset()); + caret = extension.widgetOffset2ModelOffset(styledText + .getCaretOffset()); } else { int offset = sourceViewer.getVisibleRegion().getOffset(); caret = offset + styledText.getCaretOffset(); @@ -5566,7 +5816,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) { IImportDeclaration declaration = (IImportDeclaration) element; - IImportContainer container = (IImportContainer) declaration.getParent(); + IImportContainer container = (IImportContainer) declaration + .getParent(); ISourceRange srcRange = null; try { @@ -5583,12 +5834,12 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Returns the most narrow java element including the given offset. - * + * * @param offset - * the offset inside of the requested element + * the offset inside of the requested element * @param reconcile - * true if editor input should be reconciled in - * advance + * true if editor input should be reconciled in + * advance * @return the most narrow java element * @since 3.0 */ @@ -5598,7 +5849,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I public ShowInContext getShowInContext() { FileEditorInput fei = (FileEditorInput) getEditorInput(); - ShowInContext context = BrowserUtil.getShowInContext(fei.getFile(), false, ""); + ShowInContext context = BrowserUtil.getShowInContext(fei.getFile(), + false, ""); if (context != null) { return context; } @@ -5611,11 +5863,11 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I /** * Updates the occurrences annotations based on the current selection. - * + * * @param selection - * the text selection + * the text selection * @param astRoot - * the compilation unit AST + * the compilation unit AST * @since 3.0 */ protected void updateOccurrenceAnnotations(ITextSelection selection) {// , @@ -5640,17 +5892,22 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I fMarkOccurrenceTargetRegion = null; if (document instanceof IDocumentExtension4) { int offset = selection.getOffset(); - long currentModificationStamp = ((IDocumentExtension4) document).getModificationStamp(); - if (fMarkOccurrenceTargetRegion != null && currentModificationStamp == fMarkOccurrenceModificationStamp) { + long currentModificationStamp = ((IDocumentExtension4) document) + .getModificationStamp(); + if (fMarkOccurrenceTargetRegion != null + && currentModificationStamp == fMarkOccurrenceModificationStamp) { if (fMarkOccurrenceTargetRegion.getOffset() <= offset - && offset <= fMarkOccurrenceTargetRegion.getOffset() + fMarkOccurrenceTargetRegion.getLength()) + && offset <= fMarkOccurrenceTargetRegion.getOffset() + + fMarkOccurrenceTargetRegion.getLength()) return; } - fMarkOccurrenceTargetRegion = JavaWordFinder.findWord(document, offset); + fMarkOccurrenceTargetRegion = JavaWordFinder.findWord(document, + offset); fMarkOccurrenceModificationStamp = currentModificationStamp; } - if (fMarkOccurrenceTargetRegion == null || fMarkOccurrenceTargetRegion.getLength() == 0) { + if (fMarkOccurrenceTargetRegion == null + || fMarkOccurrenceTargetRegion.getLength() == 0) { return; } @@ -5666,19 +5923,30 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I String wordStr; char[] word; - wordStr = document.get(fMarkOccurrenceTargetRegion.getOffset(), fMarkOccurrenceTargetRegion.getLength()); + wordStr = document.get(fMarkOccurrenceTargetRegion.getOffset(), + fMarkOccurrenceTargetRegion.getLength()); if (wordStr != null) { word = wordStr.toCharArray(); int fToken = ITerminalSymbols.TokenNameEOF; try { fToken = fScanner.getNextToken(); - while (fToken != ITerminalSymbols.TokenNameEOF) { // && fToken != + while (fToken != ITerminalSymbols.TokenNameEOF) { // && + // fToken + // != // TokenNameERROR) { - if (fToken == ITerminalSymbols.TokenNameVariable || fToken == ITerminalSymbols.TokenNameIdentifier) { + if (fToken == ITerminalSymbols.TokenNameVariable + || fToken == ITerminalSymbols.TokenNameIdentifier) { // global variable if (fScanner.equalsCurrentTokenSource(word)) { - matches.add(new Region(fScanner.getCurrentTokenStartPosition(), fScanner.getCurrentTokenEndPosition() - - fScanner.getCurrentTokenStartPosition() + 1)); + matches + .add(new Region( + fScanner + .getCurrentTokenStartPosition(), + fScanner + .getCurrentTokenEndPosition() + - fScanner + .getCurrentTokenStartPosition() + + 1)); } } fToken = fScanner.getNextToken(); @@ -5708,10 +5976,12 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I int i = 0; for (Iterator each = matches.iterator(); each.hasNext();) { IRegion currentNode = (IRegion) each.next(); - positions[i++] = new Position(currentNode.getOffset(), currentNode.getLength()); + positions[i++] = new Position(currentNode.getOffset(), currentNode + .getLength()); } - fOccurrencesFinderJob = new OccurrencesFinderJob(document, positions, selection); + fOccurrencesFinderJob = new OccurrencesFinderJob(document, positions, + selection); // fOccurrencesFinderJob.setPriority(Job.DECORATE); // fOccurrencesFinderJob.setSystem(true); // fOccurrencesFinderJob.schedule(); @@ -5722,17 +5992,21 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I fMarkOccurrenceAnnotations = true; fPostSelectionListenerWithAST = new ISelectionListenerWithAST() { - public void selectionChanged(IEditorPart part, ITextSelection selection) { // , + public void selectionChanged(IEditorPart part, + ITextSelection selection) { // , // CompilationUnit // astRoot) // { updateOccurrenceAnnotations(selection);// , astRoot); } }; - SelectionListenerWithASTManager.getDefault().addListener(this, fPostSelectionListenerWithAST); + SelectionListenerWithASTManager.getDefault().addListener(this, + fPostSelectionListenerWithAST); if (getSelectionProvider() != null) { - fForcedMarkOccurrencesSelection = getSelectionProvider().getSelection(); - SelectionListenerWithASTManager.getDefault().forceSelectionChange(this, (ITextSelection) fForcedMarkOccurrencesSelection); + fForcedMarkOccurrencesSelection = getSelectionProvider() + .getSelection(); + SelectionListenerWithASTManager.getDefault().forceSelectionChange( + this, (ITextSelection) fForcedMarkOccurrencesSelection); } if (fOccurrencesFinderJobCanceler == null) { @@ -5755,7 +6029,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I } if (fPostSelectionListenerWithAST != null) { - SelectionListenerWithASTManager.getDefault().removeListener(this, fPostSelectionListenerWithAST); + SelectionListenerWithASTManager.getDefault().removeListener(this, + fPostSelectionListenerWithAST); fPostSelectionListenerWithAST = null; } @@ -5774,13 +6049,15 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements I if (documentProvider == null) return; - IAnnotationModel annotationModel = documentProvider.getAnnotationModel(getEditorInput()); + IAnnotationModel annotationModel = documentProvider + .getAnnotationModel(getEditorInput()); if (annotationModel == null || fOccurrenceAnnotations == null) return; synchronized (getLockObject(annotationModel)) { if (annotationModel instanceof IAnnotationModelExtension) { - ((IAnnotationModelExtension) annotationModel).replaceAnnotations(fOccurrenceAnnotations, null); + ((IAnnotationModelExtension) annotationModel) + .replaceAnnotations(fOccurrenceAnnotations, null); } else { for (int i = 0, length = fOccurrenceAnnotations.length; i < length; i++) annotationModel.removeAnnotation(fOccurrenceAnnotations[i]); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPEditorActionDefinitionIds.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPEditorActionDefinitionIds.java index 34c9941..e5569e9 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPEditorActionDefinitionIds.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPEditorActionDefinitionIds.java @@ -2,77 +2,83 @@ package net.sourceforge.phpeclipse.phpeditor; import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; -public interface PHPEditorActionDefinitionIds extends ITextEditorActionDefinitionIds { - /** - * Action definition ID of the edit -> go to matching bracket action - * (value "org.phpeclipse.phpdt.ui.edit.text.php.goto.matching.bracket"). - * - * @since 2.1 - */ - public static final String GOTO_MATCHING_BRACKET = "net.sourceforge.phpeclipse.ui.edit.text.php.goto.matching.bracket"; //$NON-NLS-1$ - /** - * Action definition ID of the edit -> go to next member action - * (value "net.sourceforge.phpdt.ui.edit.text.java.goto.next.member"). - * +public interface PHPEditorActionDefinitionIds extends + ITextEditorActionDefinitionIds { + /** + * Action definition ID of the edit -> go to matching bracket action (value + * "org.phpeclipse.phpdt.ui.edit.text.php.goto.matching.bracket"). + * * @since 2.1 */ - public static final String GOTO_NEXT_MEMBER= "net.sourceforge.phpeclipse.ui.edit.text.php.goto.next.member"; //$NON-NLS-1$ + public static final String GOTO_MATCHING_BRACKET = "net.sourceforge.phpeclipse.ui.edit.text.php.goto.matching.bracket"; //$NON-NLS-1$ /** - * Action definition ID of the edit -> go to previous member action - * (value "net.sourceforge.phpdt.ui.edit.text.java.goto.previous.member"). - * + * Action definition ID of the edit -> go to next member action (value + * "net.sourceforge.phpdt.ui.edit.text.java.goto.next.member"). + * * @since 2.1 */ - public static final String GOTO_PREVIOUS_MEMBER= "net.sourceforge.phpeclipse.ui.edit.text.php.goto.previous.member"; //$NON-NLS-1$ + public static final String GOTO_NEXT_MEMBER = "net.sourceforge.phpeclipse.ui.edit.text.php.goto.next.member"; //$NON-NLS-1$ - /** - * Value: net.sourceforge.phpeclipse.phpeditor.comment - */ - public static final String COMMENT = "net.sourceforge.phpeclipse.phpeditor.comment"; + /** + * Action definition ID of the edit -> go to previous member action (value + * "net.sourceforge.phpdt.ui.edit.text.java.goto.previous.member"). + * + * @since 2.1 + */ + public static final String GOTO_PREVIOUS_MEMBER = "net.sourceforge.phpeclipse.ui.edit.text.php.goto.previous.member"; //$NON-NLS-1$ - /** - * Value: net.sourceforge.phpeclipse.phpeditor.uncomment - */ - public static final String UNCOMMENT = "net.sourceforge.phpeclipse.phpeditor.uncomment"; - /** - * Action definition ID of the source -> toggle comment action - * (value "net.sourceforge.phpdt.ui.edit.text.java.toggle.comment"). + /** + * Value: net.sourceforge.phpeclipse.phpeditor.comment + */ + public static final String COMMENT = "net.sourceforge.phpeclipse.phpeditor.comment"; + + /** + * Value: net.sourceforge.phpeclipse.phpeditor.uncomment + */ + public static final String UNCOMMENT = "net.sourceforge.phpeclipse.phpeditor.uncomment"; + + /** + * Action definition ID of the source -> toggle comment action (value + * "net.sourceforge.phpdt.ui.edit.text.java.toggle.comment"). + * * @since 3.0 */ - public static final String TOGGLE_COMMENT= "net.sourceforge.phpeclipse.phpeditor.toggle.comment"; //$NON-NLS-1$ - + public static final String TOGGLE_COMMENT = "net.sourceforge.phpeclipse.phpeditor.toggle.comment"; //$NON-NLS-1$ /** - * Action definition ID of the source -> add block comment action - * (value "net.sourceforge.phpdt.ui.edit.text.java.add.block.comment"). + * Action definition ID of the source -> add block comment action (value + * "net.sourceforge.phpdt.ui.edit.text.java.add.block.comment"). + * * @since 3.0 */ - public static final String ADD_BLOCK_COMMENT= "net.sourceforge.phpeclipse.phpeditor.add.block.comment"; //$NON-NLS-1$ + public static final String ADD_BLOCK_COMMENT = "net.sourceforge.phpeclipse.phpeditor.add.block.comment"; //$NON-NLS-1$ /** - * Action definition ID of the source -> remove block comment action - * (value "net.sourceforge.phpdt.ui.edit.text.java.remove.block.comment"). + * Action definition ID of the source -> remove block comment action (value + * "net.sourceforge.phpdt.ui.edit.text.java.remove.block.comment"). + * * @since 3.0 */ - public static final String REMOVE_BLOCK_COMMENT= "net.sourceforge.phpeclipse.phpeditor.remove.block.comment"; //$NON-NLS-1$ - + public static final String REMOVE_BLOCK_COMMENT = "net.sourceforge.phpeclipse.phpeditor.remove.block.comment"; //$NON-NLS-1$ + + /** + * Action definition ID of the source -> indent action (value + * "net.sourceforge.phpdt.ui.edit.text.java.indent"). + */ + public static final String INDENT = "net.sourceforge.phpeclipse.phpeditor.indent"; //$NON-NLS-1$ + /** - * Action definition ID of the source -> indent action - * (value "net.sourceforge.phpdt.ui.edit.text.java.indent"). + * Action definition ID of the source -> format action */ - public static final String INDENT= "net.sourceforge.phpeclipse.phpeditor.indent"; //$NON-NLS-1$ - - /** - * Action definition ID of the source -> format action - */ - public static final String FORMAT = "net.sourceforge.phpeclipse.phpeditor.format"; //$NON-NLS-1$ + public static final String FORMAT = "net.sourceforge.phpeclipse.phpeditor.format"; //$NON-NLS-1$ - /** - * Action definition ID of the edit -> content assist proposal action (value - * "org.phpeclipse.phpdt.ui.edit.text.php.content.assist. proposals" - * ). - */ -// public static final String CONTENT_ASSIST_PROPOSALS = "net.sourceforge.phpeclipse.ui.edit.text.php.content.assist.proposals"; //$NON-NLS-1$ - + /** + * Action definition ID of the edit -> content assist proposal action (value + * "org.phpeclipse.phpdt.ui.edit.text.php.content.assist. proposals" + * ). + */ + // public static final String CONTENT_ASSIST_PROPOSALS = + // "net.sourceforge.phpeclipse.ui.edit.text.php.content.assist.proposals"; + // //$NON-NLS-1$ } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPEditorMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPEditorMessages.java index 8260ce6..41536b9 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPEditorMessages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPEditorMessages.java @@ -19,7 +19,8 @@ public class PHPEditorMessages { private static final String RESOURCE_BUNDLE = "net.sourceforge.phpeclipse.phpeditor.PHPEditorMessages";//$NON-NLS-1$ - private static ResourceBundle fgResourceBundle = ResourceBundle.getBundle(RESOURCE_BUNDLE); + private static ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); public static String JavaEditor_markOccurrences_job_name = "JavaEditor.markOccurrences.job.name"; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPSyntaxRdr.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPSyntaxRdr.java index fb51811..bea41d8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPSyntaxRdr.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPSyntaxRdr.java @@ -40,270 +40,309 @@ import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** - * PHPSyntaxRdr reads PHP specifics from an XML file (eg. keywords) + * PHPSyntaxRdr reads PHP specifics from an XML file (eg. + * keywords) */ public class PHPSyntaxRdr { -// private static final String PHPDEFAULT_FILE = "default-syntax.xml"; //$NON-NLS-1$ - private static final String PHPSYNTAX_FILE = "syntax.xml"; //$NON-NLS-1$ -// private static final String USERSYNTAX_FILE = "usersyntax.xml"; //$NON-NLS-1$ -// private static final String USERDEFAULT_FILE = "default-usersyntax.xml"; //$NON-NLS-1$ - private static final String PHPSYNTAX_TAG = "s"; //$NON-NLS-1$ - private static final String KEYWORD_ATTR = "k"; //$NON-NLS-1$ - private static final String TYPE_ATTR = "t"; //$NON-NLS-1$ - private static final String CONSTANT_ATTR = "c"; //$NON-NLS-1$ - private static final String FN_ATTR = "f"; //$NON-NLS-1$ - private static final String USAGE_ATTR = "u"; //$NON-NLS-1$ -// private static final String TOKENVAL_ATTR = "tokenval"; //$NON-NLS-1$ - private static IPreferenceStore store; - private static boolean hasXMLFileBeenRead = true; - - //The following variable is used to hold the syntax from - //the suers custom file - if that file should be changed, - //then all entries in this variable should be removed from - //the word list, reread from the file and then reinserted. - private static ArrayList userdefsyntaxdata; - - private static ArrayList syntaxdata; - - public PHPSyntaxRdr() { - // see getSyntaxData() - syntaxdata = null; - store = PHPeclipsePlugin.getDefault().getPreferenceStore(); - } - - public static void readInSyntax() { - try { - hasXMLFileBeenRead = true; - /*Attempt to read the syntax file from the metadata - * if this does not work, create metadata from default*/ - File syntaxFile = getSyntaxFile(); - if (syntaxFile.exists()) { - readFromFile(syntaxFile); - } else { - readFromStream(PHPSyntaxRdr.class.getResourceAsStream(PHPSYNTAX_FILE)); - saveToFile(syntaxFile); - } - /*Read the user-defined syntax file if it exists*/ - //String buffer = new String(store.getString(PHPeclipsePlugin.PHP_USERDEF_XMLFILE)); - if (store == null) - store = PHPeclipsePlugin.getDefault().getPreferenceStore(); - String buffer = new String(store.getString(IPreferenceConstants.PHP_USERDEF_XMLFILE)); - if (!(buffer.equals("") || buffer == null)) { - readFromFile(buffer); - } - } catch (CoreException ce) { - ce.printStackTrace(); - } - } - - public static void readFromFile(String filename) { - try { - readFromFile(new File(filename)); - } catch (CoreException e) { - } - } - - public static void readFromFile(File file) throws CoreException { - InputStream stream = null; - - if (file.exists()) { - try { - stream = new FileInputStream(file); - readFromStream(stream); - } catch (IOException e) { - throwReadException(e); - } finally { - try { - if (stream != null) { - stream.close(); - } - } catch (IOException e) { - } - } - } - } - public static void readFromStream(InputStream stream) throws CoreException { - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder parser = factory.newDocumentBuilder(); - Document document = parser.parse(new InputSource(stream)); - // Read in the Standard PHPSyntax "stuff" - NodeList elements = document.getElementsByTagName(PHPSYNTAX_TAG); - - int count = elements.getLength(); - for (int i = 0; i != count; i++) { - Node node = elements.item(i); - NamedNodeMap attributes = node.getAttributes(); - - if (attributes == null) - continue; - - String Keyword = getAttributeValue(attributes, KEYWORD_ATTR); - String Type = getAttributeValue(attributes, TYPE_ATTR); - String Function = getAttributeValue(attributes, FN_ATTR); - String Constant = getAttributeValue(attributes, CONSTANT_ATTR); - String usage = getAttributeValue(attributes, USAGE_ATTR); -// String Tokenval = getAttributeValue(attributes, TOKENVAL_ATTR); - - StringBuffer buffer = new StringBuffer(); - NodeList children = node.getChildNodes(); - for (int j = 0; j != children.getLength(); j++) { - String value = children.item(j).getNodeValue(); - if (value != null) - buffer.append(value); - } - String description = buffer.toString().trim(); - - if (Keyword == null && Type == null && Function == null && Constant == null) { - //ignore as it is not a valid phpsyntax tag - } else { - if (Keyword != null) { -// syntaxdata.add(new PHPKeyword(Keyword, usage, Tokenval)); - syntaxdata.add(new PHPKeyword(Keyword, usage)); - } else if (Type != null) { - syntaxdata.add(new PHPType(Type, usage)); - } else if (Function != null) { - syntaxdata.add(new PHPFunction(Function, usage, description)); - } else if (Constant != null) { - syntaxdata.add(new PHPConstant(Constant, null, description)); - } - } - } - } catch (ParserConfigurationException e) { - throwReadException(e); - } catch (IOException e) { - throwReadException(e); - } catch (SAXParseException e) { - System.out.println("SAXParseException in line:"+e.getLineNumber()+" column:"+e.getColumnNumber()); - throwReadException(e); - } catch (SAXException e) { - throwReadException(e); - } - } - - public static ArrayList getSyntaxData() { - if (syntaxdata == null) { - syntaxdata = new ArrayList(); - readInSyntax(); - } - return syntaxdata; - } - - public static void replaceUserDefFile() { - /*Replace the user-defined syntax file if it exists*/ - String buffer = new String(store.getString(IPreferenceConstants.PHP_USERDEF_XMLFILE)); - if (!buffer.equals("") || buffer == null) { - readFromFile(buffer); - } - } - - public static ArrayList getUserSyntaxData() { - return userdefsyntaxdata; - } - - private static File getSyntaxFile() { - IPath path = PHPeclipsePlugin.getDefault().getStateLocation(); - path = path.append(PHPSYNTAX_FILE); - return path.toFile(); - } - - private static String getAttributeValue(NamedNodeMap attributes, String name) { - Node node = attributes.getNamedItem(name); - return node == null ? null : node.getNodeValue(); - } - - public static void saveToFile(File file) throws CoreException { - OutputStream stream = null; - try { - stream = new FileOutputStream(file); - saveToStream(stream); - } catch (IOException e) { - throwWriteException(e); - } finally { - try { - if (stream != null) - stream.close(); - } catch (IOException e) { - } - } - } - - public static void saveToStream(OutputStream stream) throws CoreException { - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - Document document = builder.newDocument(); - Node root = document.createElement("PHPStandardSyntax"); // $NON-NLS-1$ //$NON-NLS-1$ - document.appendChild(root); - for (int i = 0; i != syntaxdata.size(); i++) { - Object bufferobj = (Object) syntaxdata.get(i); - Attr name = null; - Node node = document.createElement(PHPSYNTAX_TAG); // $NON-NLS-1$ //$NON-NLS-1$ - root.appendChild(node); - NamedNodeMap attributes = node.getAttributes(); - if (bufferobj instanceof PHPType) - name = document.createAttribute(TYPE_ATTR); - if (bufferobj instanceof PHPKeyword) - name = document.createAttribute(KEYWORD_ATTR); - if (bufferobj instanceof PHPFunction) - name = document.createAttribute(FN_ATTR); - if (bufferobj instanceof PHPConstant) - name = document.createAttribute(CONSTANT_ATTR); - name.setValue(((PHPElement) bufferobj).getName()); - attributes.setNamedItem(name); - Attr description = document.createAttribute(USAGE_ATTR); - description.setValue(((PHPElement) bufferobj).getUsage()); - attributes.setNamedItem(description); -// if (bufferobj instanceof PHPKeyword) { -// Attr tokenval = document.createAttribute(TOKENVAL_ATTR); -// tokenval.setValue((new Integer(((PHPKeyword) bufferobj).gettokenval())).toString()); -// attributes.setNamedItem(tokenval); -// } - if (bufferobj instanceof PHPFunction) { - // Attr usage = document.createAttribute(USAGE_ATTR); - Text usage = document.createTextNode(((PHPFunction) bufferobj).getDescription()); - node.appendChild(usage); - } - if (bufferobj instanceof PHPConstant) { - // Attr usage = document.createAttribute(USAGE_ATTR); - Text usage = document.createTextNode(((PHPConstant) bufferobj).getDescription()); - node.appendChild(usage); - } - } - Transformer transformer=TransformerFactory.newInstance().newTransformer(); - transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$ - transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$ - DOMSource source = new DOMSource(document); - StreamResult result = new StreamResult(stream); - - transformer.transform(source, result); - - } catch (ParserConfigurationException e) { - throwWriteException(e); - } catch (TransformerException e) { - throwWriteException(e); - } -// OutputFormat format = new OutputFormat(); -// format.setPreserveSpace(true); -// try { -// Serializer serializer = SerializerFactory.getSerializerFactory("xml").makeSerializer(stream, format); -// serializer.asDOMSerializer().serialize(document); -// } catch (UnsupportedEncodingException e) { -// } catch (IOException e) { -// } //$NON-NLS-1$ -// // Serializer serializer = SerializerFactory.getSerializer().makeSerializer(stream, format); //$NON-NLS-1$ -// } catch (ParserConfigurationException e) { -// throwWriteException(e); -// } - } - - private static void throwReadException(Throwable t) throws CoreException { - PHPeclipsePlugin.log(t); - } - - private static void throwWriteException(Throwable t) throws CoreException { - PHPeclipsePlugin.log(t); - } + // private static final String PHPDEFAULT_FILE = "default-syntax.xml"; + // //$NON-NLS-1$ + private static final String PHPSYNTAX_FILE = "syntax.xml"; //$NON-NLS-1$ + // private static final String USERSYNTAX_FILE = "usersyntax.xml"; + // //$NON-NLS-1$ + // private static final String USERDEFAULT_FILE = "default-usersyntax.xml"; + // //$NON-NLS-1$ + + private static final String PHPSYNTAX_TAG = "s"; //$NON-NLS-1$ + + private static final String KEYWORD_ATTR = "k"; //$NON-NLS-1$ + + private static final String TYPE_ATTR = "t"; //$NON-NLS-1$ + + private static final String CONSTANT_ATTR = "c"; //$NON-NLS-1$ + + private static final String FN_ATTR = "f"; //$NON-NLS-1$ + + private static final String USAGE_ATTR = "u"; //$NON-NLS-1$ + // private static final String TOKENVAL_ATTR = "tokenval"; //$NON-NLS-1$ + + private static IPreferenceStore store; + + private static boolean hasXMLFileBeenRead = true; + + // The following variable is used to hold the syntax from + // the suers custom file - if that file should be changed, + // then all entries in this variable should be removed from + // the word list, reread from the file and then reinserted. + private static ArrayList userdefsyntaxdata; + + private static ArrayList syntaxdata; + + public PHPSyntaxRdr() { + // see getSyntaxData() + syntaxdata = null; + store = PHPeclipsePlugin.getDefault().getPreferenceStore(); + } + + public static void readInSyntax() { + try { + hasXMLFileBeenRead = true; + /* + * Attempt to read the syntax file from the metadata if this does + * not work, create metadata from default + */ + File syntaxFile = getSyntaxFile(); + if (syntaxFile.exists()) { + readFromFile(syntaxFile); + } else { + readFromStream(PHPSyntaxRdr.class + .getResourceAsStream(PHPSYNTAX_FILE)); + saveToFile(syntaxFile); + } + /* Read the user-defined syntax file if it exists */ + // String buffer = new + // String(store.getString(PHPeclipsePlugin.PHP_USERDEF_XMLFILE)); + if (store == null) + store = PHPeclipsePlugin.getDefault().getPreferenceStore(); + String buffer = new String(store + .getString(IPreferenceConstants.PHP_USERDEF_XMLFILE)); + if (!(buffer.equals("") || buffer == null)) { + readFromFile(buffer); + } + } catch (CoreException ce) { + ce.printStackTrace(); + } + } + + public static void readFromFile(String filename) { + try { + readFromFile(new File(filename)); + } catch (CoreException e) { + } + } + + public static void readFromFile(File file) throws CoreException { + InputStream stream = null; + + if (file.exists()) { + try { + stream = new FileInputStream(file); + readFromStream(stream); + } catch (IOException e) { + throwReadException(e); + } finally { + try { + if (stream != null) { + stream.close(); + } + } catch (IOException e) { + } + } + } + } + + public static void readFromStream(InputStream stream) throws CoreException { + try { + DocumentBuilderFactory factory = DocumentBuilderFactory + .newInstance(); + DocumentBuilder parser = factory.newDocumentBuilder(); + Document document = parser.parse(new InputSource(stream)); + // Read in the Standard PHPSyntax "stuff" + NodeList elements = document.getElementsByTagName(PHPSYNTAX_TAG); + + int count = elements.getLength(); + for (int i = 0; i != count; i++) { + Node node = elements.item(i); + NamedNodeMap attributes = node.getAttributes(); + + if (attributes == null) + continue; + + String Keyword = getAttributeValue(attributes, KEYWORD_ATTR); + String Type = getAttributeValue(attributes, TYPE_ATTR); + String Function = getAttributeValue(attributes, FN_ATTR); + String Constant = getAttributeValue(attributes, CONSTANT_ATTR); + String usage = getAttributeValue(attributes, USAGE_ATTR); + // String Tokenval = getAttributeValue(attributes, + // TOKENVAL_ATTR); + + StringBuffer buffer = new StringBuffer(); + NodeList children = node.getChildNodes(); + for (int j = 0; j != children.getLength(); j++) { + String value = children.item(j).getNodeValue(); + if (value != null) + buffer.append(value); + } + String description = buffer.toString().trim(); + + if (Keyword == null && Type == null && Function == null + && Constant == null) { + // ignore as it is not a valid phpsyntax tag + } else { + if (Keyword != null) { + // syntaxdata.add(new PHPKeyword(Keyword, usage, + // Tokenval)); + syntaxdata.add(new PHPKeyword(Keyword, usage)); + } else if (Type != null) { + syntaxdata.add(new PHPType(Type, usage)); + } else if (Function != null) { + syntaxdata.add(new PHPFunction(Function, usage, + description)); + } else if (Constant != null) { + syntaxdata.add(new PHPConstant(Constant, null, + description)); + } + } + } + } catch (ParserConfigurationException e) { + throwReadException(e); + } catch (IOException e) { + throwReadException(e); + } catch (SAXParseException e) { + System.out.println("SAXParseException in line:" + e.getLineNumber() + + " column:" + e.getColumnNumber()); + throwReadException(e); + } catch (SAXException e) { + throwReadException(e); + } + } + + public static ArrayList getSyntaxData() { + if (syntaxdata == null) { + syntaxdata = new ArrayList(); + readInSyntax(); + } + return syntaxdata; + } + + public static void replaceUserDefFile() { + /* Replace the user-defined syntax file if it exists */ + String buffer = new String(store + .getString(IPreferenceConstants.PHP_USERDEF_XMLFILE)); + if (!buffer.equals("") || buffer == null) { + readFromFile(buffer); + } + } + + public static ArrayList getUserSyntaxData() { + return userdefsyntaxdata; + } + + private static File getSyntaxFile() { + IPath path = PHPeclipsePlugin.getDefault().getStateLocation(); + path = path.append(PHPSYNTAX_FILE); + return path.toFile(); + } + + private static String getAttributeValue(NamedNodeMap attributes, String name) { + Node node = attributes.getNamedItem(name); + return node == null ? null : node.getNodeValue(); + } + + public static void saveToFile(File file) throws CoreException { + OutputStream stream = null; + try { + stream = new FileOutputStream(file); + saveToStream(stream); + } catch (IOException e) { + throwWriteException(e); + } finally { + try { + if (stream != null) + stream.close(); + } catch (IOException e) { + } + } + } + + public static void saveToStream(OutputStream stream) throws CoreException { + try { + DocumentBuilderFactory factory = DocumentBuilderFactory + .newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document document = builder.newDocument(); + Node root = document.createElement("PHPStandardSyntax"); // $NON-NLS-1$ + // //$NON-NLS-1$ + document.appendChild(root); + for (int i = 0; i != syntaxdata.size(); i++) { + Object bufferobj = (Object) syntaxdata.get(i); + Attr name = null; + Node node = document.createElement(PHPSYNTAX_TAG); // $NON-NLS-1$ + // //$NON-NLS-1$ + root.appendChild(node); + NamedNodeMap attributes = node.getAttributes(); + if (bufferobj instanceof PHPType) + name = document.createAttribute(TYPE_ATTR); + if (bufferobj instanceof PHPKeyword) + name = document.createAttribute(KEYWORD_ATTR); + if (bufferobj instanceof PHPFunction) + name = document.createAttribute(FN_ATTR); + if (bufferobj instanceof PHPConstant) + name = document.createAttribute(CONSTANT_ATTR); + name.setValue(((PHPElement) bufferobj).getName()); + attributes.setNamedItem(name); + Attr description = document.createAttribute(USAGE_ATTR); + description.setValue(((PHPElement) bufferobj).getUsage()); + attributes.setNamedItem(description); + // if (bufferobj instanceof PHPKeyword) { + // Attr tokenval = document.createAttribute(TOKENVAL_ATTR); + // tokenval.setValue((new Integer(((PHPKeyword) + // bufferobj).gettokenval())).toString()); + // attributes.setNamedItem(tokenval); + // } + if (bufferobj instanceof PHPFunction) { + // Attr usage = document.createAttribute(USAGE_ATTR); + Text usage = document + .createTextNode(((PHPFunction) bufferobj) + .getDescription()); + node.appendChild(usage); + } + if (bufferobj instanceof PHPConstant) { + // Attr usage = document.createAttribute(USAGE_ATTR); + Text usage = document + .createTextNode(((PHPConstant) bufferobj) + .getDescription()); + node.appendChild(usage); + } + } + Transformer transformer = TransformerFactory.newInstance() + .newTransformer(); + transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$ + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$ + DOMSource source = new DOMSource(document); + StreamResult result = new StreamResult(stream); + + transformer.transform(source, result); + + } catch (ParserConfigurationException e) { + throwWriteException(e); + } catch (TransformerException e) { + throwWriteException(e); + } + // OutputFormat format = new OutputFormat(); + // format.setPreserveSpace(true); + // try { + // Serializer serializer = + // SerializerFactory.getSerializerFactory("xml").makeSerializer(stream, + // format); + // serializer.asDOMSerializer().serialize(document); + // } catch (UnsupportedEncodingException e) { + // } catch (IOException e) { + // } //$NON-NLS-1$ + // // Serializer serializer = + // SerializerFactory.getSerializer().makeSerializer(stream, format); + // //$NON-NLS-1$ + // } catch (ParserConfigurationException e) { + // throwWriteException(e); + // } + } + + private static void throwReadException(Throwable t) throws CoreException { + PHPeclipsePlugin.log(t); + } + + private static void throwWriteException(Throwable t) throws CoreException { + PHPeclipsePlugin.log(t); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPTextHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPTextHover.java index 4d0aa94..08c077e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPTextHover.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPTextHover.java @@ -54,7 +54,8 @@ public class PHPTextHover implements ITextHover { if (hoverRegion != null) { try { if (hoverRegion.getLength() > -1) { - String word = textViewer.getDocument().get(hoverRegion.getOffset(), hoverRegion.getLength()); + String word = textViewer.getDocument().get( + hoverRegion.getOffset(), hoverRegion.getLength()); if (functionDescriptions == null) { functionDescriptions = new HashMap(); identDescriptions = new HashMap(); @@ -64,15 +65,19 @@ public class PHPTextHover implements ITextHover { for (int i = 0; i < syntaxbuffer.size(); i++) { elbuffer = (PHPElement) syntaxbuffer.get(i); if (elbuffer instanceof PHPFunction) { - functionDescriptions.put(elbuffer.getName(), elbuffer.getHoverText()); + functionDescriptions.put( + elbuffer.getName(), elbuffer + .getHoverText()); } else { - identDescriptions.put(elbuffer.getName(), elbuffer.getHoverText()); + identDescriptions.put(elbuffer.getName(), + elbuffer.getHoverText()); } } } // // while ((syntaxbuffer != null) - // && (!syntaxbuffer.isEmpty() && ((elbuffer = (PHPElement) + // && (!syntaxbuffer.isEmpty() && ((elbuffer = + // (PHPElement) // syntaxbuffer.remove(0)) != null))) { // functionDescriptions.put(elbuffer.getName(), // elbuffer.getHoverText()); @@ -80,11 +85,14 @@ public class PHPTextHover implements ITextHover { } String hoverInfo = (String) identDescriptions.get(word); if (hoverInfo == null & word.length() > 0) { - hoverInfo = (String) functionDescriptions.get(word.toLowerCase()); + hoverInfo = (String) functionDescriptions.get(word + .toLowerCase()); } if (hoverInfo == null && fProject != null) { - // get the possible PHPDoc information from the index file - IdentifierIndexManager indexManager = PHPeclipsePlugin.getDefault().getIndexManager(fProject); + // get the possible PHPDoc information from the index + // file + IdentifierIndexManager indexManager = PHPeclipsePlugin + .getDefault().getIndexManager(fProject); List list = indexManager.getLocations(word); if (list.size() > 0) { try { @@ -93,16 +101,22 @@ public class PHPTextHover implements ITextHover { StringBuffer hoverInfoBuffer = new StringBuffer(); String workspaceLocation; if (fProject != null) { - workspaceLocation = fProject.getLocation().toString() + '/'; + workspaceLocation = fProject.getLocation() + .toString() + '/'; } else { // should never happen? - workspaceLocation = PHPeclipsePlugin.getWorkspace().getRoot().getLocation().toString(); + workspaceLocation = PHPeclipsePlugin + .getWorkspace().getRoot() + .getLocation().toString(); } // boolean foundPHPdoc = false; for (int i = 0; i < list.size(); i++) { - location = (PHPIdentifierLocation) list.get(i); - filename = workspaceLocation + location.getFilename(); - PHPDocUtil.appendPHPDoc(hoverInfoBuffer, filename, location); + location = (PHPIdentifierLocation) list + .get(i); + filename = workspaceLocation + + location.getFilename(); + PHPDocUtil.appendPHPDoc(hoverInfoBuffer, + filename, location); } hoverInfo = hoverInfoBuffer.toString(); } catch (Throwable e) { @@ -126,9 +140,11 @@ public class PHPTextHover implements ITextHover { * (non-Javadoc) Method declared on ITextHover */ public IRegion getHoverRegion(ITextViewer textViewer, int offset) { - Point selection = PHPWordExtractor.findWord(textViewer.getDocument(), offset); + Point selection = PHPWordExtractor.findWord(textViewer.getDocument(), + offset); // show the extracted word as a tooltip - if (selection != null && selection.x <= offset && offset < selection.x + selection.y) + if (selection != null && selection.x <= offset + && offset < selection.x + selection.y) return new Region(selection.x, selection.y); return new Region(offset, 0); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPUnitEditor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPUnitEditor.java index 8a88ecf..c01fc83 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPUnitEditor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPUnitEditor.java @@ -117,271 +117,282 @@ import org.eclipse.ui.texteditor.TextOperationAction; /** * PHP specific text editor. */ -public class PHPUnitEditor extends PHPEditor { //implements - // IJavaReconcilingListener { - interface ITextConverter { - void customizeDocumentCommand(IDocument document, DocumentCommand command); - }; - - // class AdaptedSourceViewer extends JavaSourceViewer { - // private List fTextConverters; - // - // private boolean fIgnoreTextConverters = false; - // - // // private JavaCorrectionAssistant fCorrectionAssistant; - // public AdaptedSourceViewer(Composite parent, IVerticalRuler verticalRuler, - // IOverviewRuler overviewRuler, boolean showAnnotationsOverview, - // int styles, IPreferenceStore store) { - // super(parent, verticalRuler, overviewRuler, showAnnotationsOverview, - // styles, store); - // } - // - // // public AdaptedSourceViewer(Composite parent, - // // IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, - // // boolean showAnnotationsOverview, int styles) { - // // super(parent, verticalRuler, overviewRuler, - // // showAnnotationsOverview, styles); - // // } - // public IContentAssistant getContentAssistant() { - // return fContentAssistant; - // } - // - // /* - // * @see ITextOperationTarget#doOperation(int) - // */ - // public void doOperation(int operation) { - // if (getTextWidget() == null) - // return; - // switch (operation) { - // case CONTENTASSIST_PROPOSALS: - // String msg = fContentAssistant.showPossibleCompletions(); - // setStatusLineErrorMessage(msg); - // return; - // // case CORRECTIONASSIST_PROPOSALS: - // // fCorrectionAssistant.showPossibleCompletions(); - // // return; - // case UNDO: - // fIgnoreTextConverters = true; - // break; - // case REDO: - // fIgnoreTextConverters = true; - // break; - // } - // super.doOperation(operation); - // } - // - // /* - // * @see ITextOperationTarget#canDoOperation(int) - // */ - // public boolean canDoOperation(int operation) { - // // if (operation == CORRECTIONASSIST_PROPOSALS) - // // return isEditable(); - // return super.canDoOperation(operation); - // } - // - // /* - // * @see TextViewer#handleDispose() - // */ - // protected void handleDispose() { - // // if (fCorrectionAssistant != null) { - // // fCorrectionAssistant.uninstall(); - // // fCorrectionAssistant= null; - // // } - // super.handleDispose(); - // } - // - // public void insertTextConverter(ITextConverter textConverter, int index) { - // throw new UnsupportedOperationException(); - // } - // - // public void addTextConverter(ITextConverter textConverter) { - // if (fTextConverters == null) { - // fTextConverters = new ArrayList(1); - // fTextConverters.add(textConverter); - // } else if (!fTextConverters.contains(textConverter)) - // fTextConverters.add(textConverter); - // } - // - // public void removeTextConverter(ITextConverter textConverter) { - // if (fTextConverters != null) { - // fTextConverters.remove(textConverter); - // if (fTextConverters.size() == 0) - // fTextConverters = null; - // } - // } - // - // /* - // * @see TextViewer#customizeDocumentCommand(DocumentCommand) - // */ - // protected void customizeDocumentCommand(DocumentCommand command) { - // super.customizeDocumentCommand(command); - // if (!fIgnoreTextConverters && fTextConverters != null) { - // for (Iterator e = fTextConverters.iterator(); e.hasNext();) - // ((ITextConverter) e.next()).customizeDocumentCommand(getDocument(), - // command); - // } - // fIgnoreTextConverters = false; - // } - // - // // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 - // public void updateIndentationPrefixes() { - // SourceViewerConfiguration configuration = getSourceViewerConfiguration(); - // String[] types = configuration.getConfiguredContentTypes(this); - // for (int i = 0; i < types.length; i++) { - // String[] prefixes = configuration.getIndentPrefixes(this, types[i]); - // if (prefixes != null && prefixes.length > 0) - // setIndentPrefixes(prefixes, types[i]); - // } - // } - // - // /* - // * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper) - // */ - // public boolean requestWidgetToken(IWidgetTokenKeeper requester) { - // if (WorkbenchHelp.isContextHelpDisplayed()) - // return false; - // return super.requestWidgetToken(requester); - // } - // - //// /* - //// * @see org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration) - //// */ - //// public void configure(SourceViewerConfiguration configuration) { - //// super.configure(configuration); - //// // fCorrectionAssistant= new - //// // JavaCorrectionAssistant(CompilationUnitEditor.this); - //// // fCorrectionAssistant.install(this); - //// //TODO install SmartBracesAutoEditStrategy - //// // prependAutoEditStrategy(new SmartBracesAutoEditStrategy(this), - //// // IDocument.DEFAULT_CONTENT_TYPE); - //// } - // public void configure(SourceViewerConfiguration configuration) { - // super.configure(configuration); - //// fCorrectionAssistant= new JavaCorrectionAssistant(CompilationUnitEditor.this); - //// fCorrectionAssistant.install(this); - // IAutoEditStrategy smartSemi= new SmartSemicolonAutoEditStrategy(IPHPPartitions.PHP_PARTITIONING); - // prependAutoEditStrategy(smartSemi, IDocument.DEFAULT_CONTENT_TYPE); - // prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_DQ); - // prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_SQ); - //// prependAutoEditStrategy(smartSemi, IPHPPartitions.JAVA_CHARACTER); - // } - // }; - class AdaptedSourceViewer extends JavaSourceViewer { - - private List fTextConverters; - - private boolean fIgnoreTextConverters = false; - - // private JavaCorrectionAssistant fCorrectionAssistant; - - public AdaptedSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, - boolean showAnnotationsOverview, int styles, IPreferenceStore store) { - super(parent, verticalRuler, overviewRuler, showAnnotationsOverview, styles, store); - } +public class PHPUnitEditor extends PHPEditor { // implements + // IJavaReconcilingListener { + interface ITextConverter { + void customizeDocumentCommand(IDocument document, + DocumentCommand command); + }; + + // class AdaptedSourceViewer extends JavaSourceViewer { + // private List fTextConverters; + // + // private boolean fIgnoreTextConverters = false; + // + // // private JavaCorrectionAssistant fCorrectionAssistant; + // public AdaptedSourceViewer(Composite parent, IVerticalRuler + // verticalRuler, + // IOverviewRuler overviewRuler, boolean showAnnotationsOverview, + // int styles, IPreferenceStore store) { + // super(parent, verticalRuler, overviewRuler, showAnnotationsOverview, + // styles, store); + // } + // + // // public AdaptedSourceViewer(Composite parent, + // // IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, + // // boolean showAnnotationsOverview, int styles) { + // // super(parent, verticalRuler, overviewRuler, + // // showAnnotationsOverview, styles); + // // } + // public IContentAssistant getContentAssistant() { + // return fContentAssistant; + // } + // + // /* + // * @see ITextOperationTarget#doOperation(int) + // */ + // public void doOperation(int operation) { + // if (getTextWidget() == null) + // return; + // switch (operation) { + // case CONTENTASSIST_PROPOSALS: + // String msg = fContentAssistant.showPossibleCompletions(); + // setStatusLineErrorMessage(msg); + // return; + // // case CORRECTIONASSIST_PROPOSALS: + // // fCorrectionAssistant.showPossibleCompletions(); + // // return; + // case UNDO: + // fIgnoreTextConverters = true; + // break; + // case REDO: + // fIgnoreTextConverters = true; + // break; + // } + // super.doOperation(operation); + // } + // + // /* + // * @see ITextOperationTarget#canDoOperation(int) + // */ + // public boolean canDoOperation(int operation) { + // // if (operation == CORRECTIONASSIST_PROPOSALS) + // // return isEditable(); + // return super.canDoOperation(operation); + // } + // + // /* + // * @see TextViewer#handleDispose() + // */ + // protected void handleDispose() { + // // if (fCorrectionAssistant != null) { + // // fCorrectionAssistant.uninstall(); + // // fCorrectionAssistant= null; + // // } + // super.handleDispose(); + // } + // + // public void insertTextConverter(ITextConverter textConverter, int index) + // { + // throw new UnsupportedOperationException(); + // } + // + // public void addTextConverter(ITextConverter textConverter) { + // if (fTextConverters == null) { + // fTextConverters = new ArrayList(1); + // fTextConverters.add(textConverter); + // } else if (!fTextConverters.contains(textConverter)) + // fTextConverters.add(textConverter); + // } + // + // public void removeTextConverter(ITextConverter textConverter) { + // if (fTextConverters != null) { + // fTextConverters.remove(textConverter); + // if (fTextConverters.size() == 0) + // fTextConverters = null; + // } + // } + // + // /* + // * @see TextViewer#customizeDocumentCommand(DocumentCommand) + // */ + // protected void customizeDocumentCommand(DocumentCommand command) { + // super.customizeDocumentCommand(command); + // if (!fIgnoreTextConverters && fTextConverters != null) { + // for (Iterator e = fTextConverters.iterator(); e.hasNext();) + // ((ITextConverter) e.next()).customizeDocumentCommand(getDocument(), + // command); + // } + // fIgnoreTextConverters = false; + // } + // + // // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 + // public void updateIndentationPrefixes() { + // SourceViewerConfiguration configuration = getSourceViewerConfiguration(); + // String[] types = configuration.getConfiguredContentTypes(this); + // for (int i = 0; i < types.length; i++) { + // String[] prefixes = configuration.getIndentPrefixes(this, types[i]); + // if (prefixes != null && prefixes.length > 0) + // setIndentPrefixes(prefixes, types[i]); + // } + // } + // + // /* + // * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper) + // */ + // public boolean requestWidgetToken(IWidgetTokenKeeper requester) { + // if (WorkbenchHelp.isContextHelpDisplayed()) + // return false; + // return super.requestWidgetToken(requester); + // } + // + // // /* + // // * @see + // org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration) + // // */ + // // public void configure(SourceViewerConfiguration configuration) { + // // super.configure(configuration); + // // // fCorrectionAssistant= new + // // // JavaCorrectionAssistant(CompilationUnitEditor.this); + // // // fCorrectionAssistant.install(this); + // // //TODO install SmartBracesAutoEditStrategy + // // // prependAutoEditStrategy(new SmartBracesAutoEditStrategy(this), + // // // IDocument.DEFAULT_CONTENT_TYPE); + // // } + // public void configure(SourceViewerConfiguration configuration) { + // super.configure(configuration); + // // fCorrectionAssistant= new + // JavaCorrectionAssistant(CompilationUnitEditor.this); + // // fCorrectionAssistant.install(this); + // IAutoEditStrategy smartSemi= new + // SmartSemicolonAutoEditStrategy(IPHPPartitions.PHP_PARTITIONING); + // prependAutoEditStrategy(smartSemi, IDocument.DEFAULT_CONTENT_TYPE); + // prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_DQ); + // prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_SQ); + // // prependAutoEditStrategy(smartSemi, IPHPPartitions.JAVA_CHARACTER); + // } + // }; + class AdaptedSourceViewer extends JavaSourceViewer { + + private List fTextConverters; + + private boolean fIgnoreTextConverters = false; + + // private JavaCorrectionAssistant fCorrectionAssistant; + + public AdaptedSourceViewer(Composite parent, + IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, + boolean showAnnotationsOverview, int styles, + IPreferenceStore store) { + super(parent, verticalRuler, overviewRuler, + showAnnotationsOverview, styles, store); + } - public IContentAssistant getContentAssistant() { - return fContentAssistant; - } + public IContentAssistant getContentAssistant() { + return fContentAssistant; + } - /* - * @see ITextOperationTarget#doOperation(int) - */ - public void doOperation(int operation) { - - if (getTextWidget() == null) - return; - - switch (operation) { - case CONTENTASSIST_PROPOSALS: - String msg = fContentAssistant.showPossibleCompletions(); - setStatusLineErrorMessage(msg); - return; - // case CORRECTIONASSIST_PROPOSALS: - // msg = fCorrectionAssistant.showPossibleCompletions(); - // setStatusLineErrorMessage(msg); - // return; - case UNDO: - fIgnoreTextConverters = true; - super.doOperation(operation); - fIgnoreTextConverters = false; - return; - case REDO: - fIgnoreTextConverters = true; - super.doOperation(operation); - fIgnoreTextConverters = false; - return; - } - - super.doOperation(operation); - } + /* + * @see ITextOperationTarget#doOperation(int) + */ + public void doOperation(int operation) { - /* - * @see ITextOperationTarget#canDoOperation(int) - */ - public boolean canDoOperation(int operation) { - // if (operation == CORRECTIONASSIST_PROPOSALS) - // return isEditable(); + if (getTextWidget() == null) + return; - return super.canDoOperation(operation); - } + switch (operation) { + case CONTENTASSIST_PROPOSALS: + String msg = fContentAssistant.showPossibleCompletions(); + setStatusLineErrorMessage(msg); + return; + // case CORRECTIONASSIST_PROPOSALS: + // msg = fCorrectionAssistant.showPossibleCompletions(); + // setStatusLineErrorMessage(msg); + // return; + case UNDO: + fIgnoreTextConverters = true; + super.doOperation(operation); + fIgnoreTextConverters = false; + return; + case REDO: + fIgnoreTextConverters = true; + super.doOperation(operation); + fIgnoreTextConverters = false; + return; + } - /* - * @see org.eclipse.jface.text.source.ISourceViewerExtension2#unconfigure() - * @since 3.0 - */ - public void unconfigure() { - // if (fCorrectionAssistant != null) { - // fCorrectionAssistant.uninstall(); - // fCorrectionAssistant = null; - // } - super.unconfigure(); - } + super.doOperation(operation); + } - public void insertTextConverter(ITextConverter textConverter, int index) { - throw new UnsupportedOperationException(); - } + /* + * @see ITextOperationTarget#canDoOperation(int) + */ + public boolean canDoOperation(int operation) { + // if (operation == CORRECTIONASSIST_PROPOSALS) + // return isEditable(); - public void addTextConverter(ITextConverter textConverter) { - if (fTextConverters == null) { - fTextConverters = new ArrayList(1); - fTextConverters.add(textConverter); - } else if (!fTextConverters.contains(textConverter)) - fTextConverters.add(textConverter); - } + return super.canDoOperation(operation); + } - public void removeTextConverter(ITextConverter textConverter) { - if (fTextConverters != null) { - fTextConverters.remove(textConverter); - if (fTextConverters.size() == 0) - fTextConverters = null; - } - } + /* + * @see org.eclipse.jface.text.source.ISourceViewerExtension2#unconfigure() + * @since 3.0 + */ + public void unconfigure() { + // if (fCorrectionAssistant != null) { + // fCorrectionAssistant.uninstall(); + // fCorrectionAssistant = null; + // } + super.unconfigure(); + } - /* - * @see TextViewer#customizeDocumentCommand(DocumentCommand) - */ - protected void customizeDocumentCommand(DocumentCommand command) { - super.customizeDocumentCommand(command); - if (!fIgnoreTextConverters && fTextConverters != null) { - for (Iterator e = fTextConverters.iterator(); e.hasNext();) - ((ITextConverter) e.next()).customizeDocumentCommand(getDocument(), command); - } - } + public void insertTextConverter(ITextConverter textConverter, int index) { + throw new UnsupportedOperationException(); + } - // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 - public void updateIndentationPrefixes() { - SourceViewerConfiguration configuration = getSourceViewerConfiguration(); - String[] types = configuration.getConfiguredContentTypes(this); - for (int i = 0; i < types.length; i++) { - String[] prefixes = configuration.getIndentPrefixes(this, types[i]); - if (prefixes != null && prefixes.length > 0) - setIndentPrefixes(prefixes, types[i]); - } - } + public void addTextConverter(ITextConverter textConverter) { + if (fTextConverters == null) { + fTextConverters = new ArrayList(1); + fTextConverters.add(textConverter); + } else if (!fTextConverters.contains(textConverter)) + fTextConverters.add(textConverter); + } - /* - * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper) - */ + public void removeTextConverter(ITextConverter textConverter) { + if (fTextConverters != null) { + fTextConverters.remove(textConverter); + if (fTextConverters.size() == 0) + fTextConverters = null; + } + } + + /* + * @see TextViewer#customizeDocumentCommand(DocumentCommand) + */ + protected void customizeDocumentCommand(DocumentCommand command) { + super.customizeDocumentCommand(command); + if (!fIgnoreTextConverters && fTextConverters != null) { + for (Iterator e = fTextConverters.iterator(); e.hasNext();) + ((ITextConverter) e.next()).customizeDocumentCommand( + getDocument(), command); + } + } + + // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 + public void updateIndentationPrefixes() { + SourceViewerConfiguration configuration = getSourceViewerConfiguration(); + String[] types = configuration.getConfiguredContentTypes(this); + for (int i = 0; i < types.length; i++) { + String[] prefixes = configuration.getIndentPrefixes(this, + types[i]); + if (prefixes != null && prefixes.length > 0) + setIndentPrefixes(prefixes, types[i]); + } + } + + /* + * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper) + */ public boolean requestWidgetToken(IWidgetTokenKeeper requester) { if (PlatformUI.getWorkbench().getHelpSystem() .isContextHelpDisplayed()) @@ -389,11 +400,11 @@ public class PHPUnitEditor extends PHPEditor { //implements return super.requestWidgetToken(requester); } - /* - * @see IWidgetTokenOwnerExtension#requestWidgetToken(IWidgetTokenKeeper, - * int) - * @since 3.0 - */ + /* + * @see IWidgetTokenOwnerExtension#requestWidgetToken(IWidgetTokenKeeper, + * int) + * @since 3.0 + */ public boolean requestWidgetToken(IWidgetTokenKeeper requester, int priority) { if (PlatformUI.getWorkbench().getHelpSystem() @@ -402,2163 +413,2340 @@ public class PHPUnitEditor extends PHPEditor { //implements return super.requestWidgetToken(requester, priority); } - /* - * @see org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration) - */ - public void configure(SourceViewerConfiguration configuration) { - super.configure(configuration); - // fCorrectionAssistant = new JavaCorrectionAssistant(CompilationUnitEditor.this); - // fCorrectionAssistant.install(this); - IAutoEditStrategy smartSemi = new SmartSemicolonAutoEditStrategy(IPHPPartitions.PHP_PARTITIONING); - prependAutoEditStrategy(smartSemi, IDocument.DEFAULT_CONTENT_TYPE); - prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_DQ); - prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_SQ); - prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_HEREDOC); + /* + * @see org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration) + */ + public void configure(SourceViewerConfiguration configuration) { + super.configure(configuration); + // fCorrectionAssistant = new + // JavaCorrectionAssistant(CompilationUnitEditor.this); + // fCorrectionAssistant.install(this); + IAutoEditStrategy smartSemi = new SmartSemicolonAutoEditStrategy( + IPHPPartitions.PHP_PARTITIONING); + prependAutoEditStrategy(smartSemi, IDocument.DEFAULT_CONTENT_TYPE); + prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_DQ); + prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_SQ); + prependAutoEditStrategy(smartSemi, + IPHPPartitions.PHP_STRING_HEREDOC); + } + + /* + * @see org.eclipse.jface.text.source.SourceViewer#createFormattingContext() + * @since 3.0 + */ + public IFormattingContext createFormattingContext() { + IFormattingContext context = new CommentFormattingContext(); + + Map preferences; + IJavaElement inputJavaElement = getInputJavaElement(); + IJavaProject javaProject = inputJavaElement != null ? inputJavaElement + .getJavaProject() + : null; + if (javaProject == null) + preferences = new HashMap(JavaCore.getOptions()); + else + preferences = new HashMap(javaProject.getOptions(true)); + + context.storeToMap(PreferenceConstants.getPreferenceStore(), + preferences, false); + context.setProperty( + FormattingContextProperties.CONTEXT_PREFERENCES, + preferences); + + return context; + } } - /* - * @see org.eclipse.jface.text.source.SourceViewer#createFormattingContext() + /** + * Remembers data related to the current selection to be able to restore it + * later. + * * @since 3.0 */ - public IFormattingContext createFormattingContext() { - IFormattingContext context = new CommentFormattingContext(); + private class RememberedSelection { + /** The remembered selection start. */ + private RememberedOffset fStartOffset = new RememberedOffset(); - Map preferences; - IJavaElement inputJavaElement = getInputJavaElement(); - IJavaProject javaProject = inputJavaElement != null ? inputJavaElement.getJavaProject() : null; - if (javaProject == null) - preferences = new HashMap(JavaCore.getOptions()); - else - preferences = new HashMap(javaProject.getOptions(true)); + /** The remembered selection end. */ + private RememberedOffset fEndOffset = new RememberedOffset(); - context.storeToMap(PreferenceConstants.getPreferenceStore(), preferences, false); - context.setProperty(FormattingContextProperties.CONTEXT_PREFERENCES, preferences); + /** + * Remember current selection. + */ + public void remember() { + /* + * https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257 This method + * may be called inside an async call posted to the UI thread, so + * protect against intermediate disposal of the editor. + */ + ISourceViewer viewer = getSourceViewer(); + if (viewer != null) { + IRegion selection = getSignedSelection(viewer); + int startOffset = selection.getOffset(); + int endOffset = startOffset + selection.getLength(); + + fStartOffset.setOffset(startOffset); + fEndOffset.setOffset(endOffset); + } + } - return context; - } - } + /** + * Restore remembered selection. + */ + public void restore() { + /* + * https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257 This method + * may be called inside an async call posted to the UI thread, so + * protect against intermediate disposal of the editor. + */ + if (getSourceViewer() == null) + return; + + try { + + int startOffset, endOffset; + int revealStartOffset, revealEndOffset; + if (showsHighlightRangeOnly()) { + IJavaElement newStartElement = fStartOffset.getElement(); + startOffset = fStartOffset + .getRememberedOffset(newStartElement); + revealStartOffset = fStartOffset.getRevealOffset( + newStartElement, startOffset); + if (revealStartOffset == -1) + startOffset = -1; + + IJavaElement newEndElement = fEndOffset.getElement(); + endOffset = fEndOffset.getRememberedOffset(newEndElement); + revealEndOffset = fEndOffset.getRevealOffset(newEndElement, + endOffset); + if (revealEndOffset == -1) + endOffset = -1; + } else { + startOffset = fStartOffset.getOffset(); + revealStartOffset = startOffset; + endOffset = fEndOffset.getOffset(); + revealEndOffset = endOffset; + } - /** - * Remembers data related to the current selection to be able to restore it later. - * - * @since 3.0 - */ - private class RememberedSelection { - /** The remembered selection start. */ - private RememberedOffset fStartOffset = new RememberedOffset(); + if (startOffset == -1) { + startOffset = endOffset; // fallback to caret offset + revealStartOffset = revealEndOffset; + } - /** The remembered selection end. */ - private RememberedOffset fEndOffset = new RememberedOffset(); + if (endOffset == -1) { + endOffset = startOffset; // fallback to other offset + revealEndOffset = revealStartOffset; + } + + IJavaElement element; + if (endOffset == -1) { + // fallback to element selection + element = fEndOffset.getElement(); + if (element == null) + element = fStartOffset.getElement(); + if (element != null) + setSelection(element); + return; + } + + if (isValidSelection(revealStartOffset, revealEndOffset + - revealStartOffset) + && isValidSelection(startOffset, endOffset + - startOffset)) + selectAndReveal(startOffset, endOffset - startOffset, + revealStartOffset, revealEndOffset + - revealStartOffset); + } finally { + fStartOffset.clear(); + fEndOffset.clear(); + } + } + + private boolean isValidSelection(int offset, int length) { + IDocumentProvider provider = getDocumentProvider(); + if (provider != null) { + IDocument document = provider.getDocument(getEditorInput()); + if (document != null) { + int end = offset + length; + int documentLength = document.getLength(); + return 0 <= offset && offset <= documentLength && 0 <= end + && end <= documentLength; + } + } + return false; + } - /** - * Remember current selection. - */ - public void remember() { - /* - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257 This method may be called inside an async call posted to the UI thread, - * so protect against intermediate disposal of the editor. - */ - ISourceViewer viewer = getSourceViewer(); - if (viewer != null) { - IRegion selection = getSignedSelection(viewer); - int startOffset = selection.getOffset(); - int endOffset = startOffset + selection.getLength(); - - fStartOffset.setOffset(startOffset); - fEndOffset.setOffset(endOffset); - } } /** - * Restore remembered selection. + * Remembers additional data for a given offset to be able restore it later. + * + * @since 3.0 */ - public void restore() { - /* - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257 This method may be called inside an async call posted to the UI thread, - * so protect against intermediate disposal of the editor. - */ - if (getSourceViewer() == null) - return; - - try { - - int startOffset, endOffset; - int revealStartOffset, revealEndOffset; - if (showsHighlightRangeOnly()) { - IJavaElement newStartElement = fStartOffset.getElement(); - startOffset = fStartOffset.getRememberedOffset(newStartElement); - revealStartOffset = fStartOffset.getRevealOffset(newStartElement, startOffset); - if (revealStartOffset == -1) - startOffset = -1; - - IJavaElement newEndElement = fEndOffset.getElement(); - endOffset = fEndOffset.getRememberedOffset(newEndElement); - revealEndOffset = fEndOffset.getRevealOffset(newEndElement, endOffset); - if (revealEndOffset == -1) - endOffset = -1; - } else { - startOffset = fStartOffset.getOffset(); - revealStartOffset = startOffset; - endOffset = fEndOffset.getOffset(); - revealEndOffset = endOffset; - } + private class RememberedOffset { + /** Remembered line for the given offset */ + private int fLine; - if (startOffset == -1) { - startOffset = endOffset; // fallback to caret offset - revealStartOffset = revealEndOffset; - } + /** Remembered column for the given offset */ + private int fColumn; - if (endOffset == -1) { - endOffset = startOffset; // fallback to other offset - revealEndOffset = revealStartOffset; + /** Remembered Java element for the given offset */ + private IJavaElement fElement; + + /** Remembered Java element line for the given offset */ + private int fElementLine; + + /** + * Store visual properties of the given offset. + * + * @param offset + * Offset in the document + */ + public void setOffset(int offset) { + try { + IDocument document = getSourceViewer().getDocument(); + fLine = document.getLineOfOffset(offset); + fColumn = offset - document.getLineOffset(fLine); + fElement = getElementAt(offset, true); + + fElementLine = -1; + if (fElement instanceof IMember) { + ISourceRange range = ((IMember) fElement).getNameRange(); + if (range != null) + fElementLine = document.getLineOfOffset(range + .getOffset()); + } + if (fElementLine == -1) + fElementLine = document + .getLineOfOffset(getOffset(fElement)); + } catch (BadLocationException e) { + // should not happen + PHPeclipsePlugin.log(e); + clear(); + } catch (JavaModelException e) { + // should not happen + PHPeclipsePlugin.log(e.getStatus()); + clear(); + } } - IJavaElement element; - if (endOffset == -1) { - // fallback to element selection - element = fEndOffset.getElement(); - if (element == null) - element = fStartOffset.getElement(); - if (element != null) - setSelection(element); - return; + /** + * Return offset recomputed from stored visual properties. + * + * @return Offset in the document + */ + public int getOffset() { + IJavaElement newElement = getElement(); + + int offset = getRememberedOffset(newElement); + + if (offset != -1 && !containsOffset(newElement, offset) + && (offset == 0 || !containsOffset(newElement, offset - 1))) + return -1; + + return offset; } - if (isValidSelection(revealStartOffset, revealEndOffset - revealStartOffset) - && isValidSelection(startOffset, endOffset - startOffset)) - selectAndReveal(startOffset, endOffset - startOffset, revealStartOffset, revealEndOffset - revealStartOffset); - } finally { - fStartOffset.clear(); - fEndOffset.clear(); - } - } + /** + * Return offset recomputed from stored visual properties. + * + * @param newElement + * Enclosing element + * @return Offset in the document + */ + public int getRememberedOffset(IJavaElement newElement) { + try { + if (newElement == null) + return -1; + + IDocument document = getSourceViewer().getDocument(); + int newElementLine = -1; + if (newElement instanceof IMember) { + ISourceRange range = ((IMember) newElement).getNameRange(); + if (range != null) + newElementLine = document.getLineOfOffset(range + .getOffset()); + } + if (newElementLine == -1) + newElementLine = document + .getLineOfOffset(getOffset(newElement)); + if (newElementLine == -1) + return -1; + + int newLine = fLine + newElementLine - fElementLine; + if (newLine < 0 || newLine >= document.getNumberOfLines()) + return -1; + int maxColumn = document.getLineLength(newLine); + String lineDelimiter = document.getLineDelimiter(newLine); + if (lineDelimiter != null) + maxColumn = maxColumn - lineDelimiter.length(); + int offset; + if (fColumn > maxColumn) + offset = document.getLineOffset(newLine) + maxColumn; + else + offset = document.getLineOffset(newLine) + fColumn; + + return offset; + } catch (BadLocationException e) { + // should not happen + PHPeclipsePlugin.log(e); + return -1; + } catch (JavaModelException e) { + // should not happen + PHPeclipsePlugin.log(e.getStatus()); + return -1; + } + } - private boolean isValidSelection(int offset, int length) { - IDocumentProvider provider = getDocumentProvider(); - if (provider != null) { - IDocument document = provider.getDocument(getEditorInput()); - if (document != null) { - int end = offset + length; - int documentLength = document.getLength(); - return 0 <= offset && offset <= documentLength && 0 <= end && end <= documentLength; - } - } - return false; - } + /** + * Returns the offset used to reveal the given element based on the + * given selection offset. + * + * @param element + * the element + * @param offset + * the selection offset + * @return the offset to reveal the given element based on the given + * selection offset + */ + public int getRevealOffset(IJavaElement element, int offset) { + if (element == null || offset == -1) + return -1; + + if (containsOffset(element, offset)) { + if (offset > 0) { + IJavaElement alternateElement = getElementAt(offset, false); + if (element.getHandleIdentifier().equals( + alternateElement.getParent().getHandleIdentifier())) + return offset - 1; // Solves test case 2 from + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=47727#c3 + } + return offset; + } else if (offset > 0 && containsOffset(element, offset - 1)) + return offset - 1; // Solves test case 1 from + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=47727#c3 - } + return -1; + } - /** - * Remembers additional data for a given offset to be able restore it later. - * - * @since 3.0 - */ - private class RememberedOffset { - /** Remembered line for the given offset */ - private int fLine; + /** + * Return Java element recomputed from stored visual properties. + * + * @return Java element + */ + public IJavaElement getElement() { + if (fElement == null) + return null; - /** Remembered column for the given offset */ - private int fColumn; + return findElement(fElement); + } - /** Remembered Java element for the given offset */ - private IJavaElement fElement; + /** + * Clears the stored position + */ + public void clear() { + fLine = -1; + fColumn = -1; + fElement = null; + fElementLine = -1; + } - /** Remembered Java element line for the given offset */ - private int fElementLine; + /** + * Does the given Java element contain the given offset? + * + * @param element + * Java element + * @param offset + * Offset + * @return true iff the Java element contains the offset + */ + private boolean containsOffset(IJavaElement element, int offset) { + int elementOffset = getOffset(element); + int elementLength = getLength(element); + return (elementOffset > -1 && elementLength > -1) ? (offset >= elementOffset && offset < elementOffset + + elementLength) + : false; + } - /** - * Store visual properties of the given offset. - * - * @param offset - * Offset in the document - */ - public void setOffset(int offset) { - try { - IDocument document = getSourceViewer().getDocument(); - fLine = document.getLineOfOffset(offset); - fColumn = offset - document.getLineOffset(fLine); - fElement = getElementAt(offset, true); - - fElementLine = -1; - if (fElement instanceof IMember) { - ISourceRange range = ((IMember) fElement).getNameRange(); - if (range != null) - fElementLine = document.getLineOfOffset(range.getOffset()); - } - if (fElementLine == -1) - fElementLine = document.getLineOfOffset(getOffset(fElement)); - } catch (BadLocationException e) { - // should not happen - PHPeclipsePlugin.log(e); - clear(); - } catch (JavaModelException e) { - // should not happen - PHPeclipsePlugin.log(e.getStatus()); - clear(); - } - } + /** + * Returns the offset of the given Java element. + * + * @param element + * Java element + * @return Offset of the given Java element + */ + private int getOffset(IJavaElement element) { + if (element instanceof ISourceReference) { + ISourceReference sr = (ISourceReference) element; + try { + ISourceRange srcRange = sr.getSourceRange(); + if (srcRange != null) + return srcRange.getOffset(); + } catch (JavaModelException e) { + } + } + return -1; + } - /** - * Return offset recomputed from stored visual properties. - * - * @return Offset in the document - */ - public int getOffset() { - IJavaElement newElement = getElement(); + /** + * Returns the length of the given Java element. + * + * @param element + * Java element + * @return Length of the given Java element + */ + private int getLength(IJavaElement element) { + if (element instanceof ISourceReference) { + ISourceReference sr = (ISourceReference) element; + try { + ISourceRange srcRange = sr.getSourceRange(); + if (srcRange != null) + return srcRange.getLength(); + } catch (JavaModelException e) { + } + } + return -1; + } - int offset = getRememberedOffset(newElement); + /** + * Returns the updated java element for the old java element. + * + * @param element + * Old Java element + * @return Updated Java element + */ + private IJavaElement findElement(IJavaElement element) { + + if (element == null) + return null; + + IWorkingCopyManager manager = PHPeclipsePlugin.getDefault() + .getWorkingCopyManager(); + ICompilationUnit unit = manager.getWorkingCopy(getEditorInput()); + + if (unit != null) { + try { + + synchronized (unit) { + // unit.reconcile(ICompilationUnit.NO_AST, false, null, + // null); + unit.reconcile(); + } + IJavaElement[] findings = unit.findElements(element); + if (findings != null && findings.length > 0) + return findings[0]; + + } catch (JavaModelException x) { + PHPeclipsePlugin.log(x.getStatus()); + // nothing found, be tolerant and go on + } + } - if (offset != -1 && !containsOffset(newElement, offset) && (offset == 0 || !containsOffset(newElement, offset - 1))) - return -1; + return null; + } - return offset; } - /** - * Return offset recomputed from stored visual properties. - * - * @param newElement - * Enclosing element - * @return Offset in the document - */ - public int getRememberedOffset(IJavaElement newElement) { - try { - if (newElement == null) - return -1; - - IDocument document = getSourceViewer().getDocument(); - int newElementLine = -1; - if (newElement instanceof IMember) { - ISourceRange range = ((IMember) newElement).getNameRange(); - if (range != null) - newElementLine = document.getLineOfOffset(range.getOffset()); - } - if (newElementLine == -1) - newElementLine = document.getLineOfOffset(getOffset(newElement)); - if (newElementLine == -1) - return -1; - - int newLine = fLine + newElementLine - fElementLine; - if (newLine < 0 || newLine >= document.getNumberOfLines()) - return -1; - int maxColumn = document.getLineLength(newLine); - String lineDelimiter = document.getLineDelimiter(newLine); - if (lineDelimiter != null) - maxColumn = maxColumn - lineDelimiter.length(); - int offset; - if (fColumn > maxColumn) - offset = document.getLineOffset(newLine) + maxColumn; - else - offset = document.getLineOffset(newLine) + fColumn; - - return offset; - } catch (BadLocationException e) { - // should not happen - PHPeclipsePlugin.log(e); - return -1; - } catch (JavaModelException e) { - // should not happen - PHPeclipsePlugin.log(e.getStatus()); - return -1; - } - } + static class TabConverter implements ITextConverter { + private int fTabRatio; - /** - * Returns the offset used to reveal the given element based on the given selection offset. - * - * @param element - * the element - * @param offset - * the selection offset - * @return the offset to reveal the given element based on the given selection offset - */ - public int getRevealOffset(IJavaElement element, int offset) { - if (element == null || offset == -1) - return -1; + private ILineTracker fLineTracker; - if (containsOffset(element, offset)) { - if (offset > 0) { - IJavaElement alternateElement = getElementAt(offset, false); - if (element.getHandleIdentifier().equals(alternateElement.getParent().getHandleIdentifier())) - return offset - 1; // Solves test case 2 from https://bugs.eclipse.org/bugs/show_bug.cgi?id=47727#c3 + public TabConverter() { } - return offset; - } else if (offset > 0 && containsOffset(element, offset - 1)) - return offset - 1; // Solves test case 1 from https://bugs.eclipse.org/bugs/show_bug.cgi?id=47727#c3 - return -1; - } + public void setNumberOfSpacesPerTab(int ratio) { + fTabRatio = ratio; + } - /** - * Return Java element recomputed from stored visual properties. - * - * @return Java element - */ - public IJavaElement getElement() { - if (fElement == null) - return null; + public void setLineTracker(ILineTracker lineTracker) { + fLineTracker = lineTracker; + } - return findElement(fElement); - } + private int insertTabString(StringBuffer buffer, int offsetInLine) { + if (fTabRatio == 0) + return 0; + int remainder = offsetInLine % fTabRatio; + remainder = fTabRatio - remainder; + for (int i = 0; i < remainder; i++) + buffer.append(' '); + return remainder; + } - /** - * Clears the stored position - */ - public void clear() { - fLine = -1; - fColumn = -1; - fElement = null; - fElementLine = -1; - } + public void customizeDocumentCommand(IDocument document, + DocumentCommand command) { + String text = command.text; + if (text == null) + return; + int index = text.indexOf('\t'); + if (index > -1) { + StringBuffer buffer = new StringBuffer(); + fLineTracker.set(command.text); + int lines = fLineTracker.getNumberOfLines(); + try { + for (int i = 0; i < lines; i++) { + int offset = fLineTracker.getLineOffset(i); + int endOffset = offset + fLineTracker.getLineLength(i); + String line = text.substring(offset, endOffset); + int position = 0; + if (i == 0) { + IRegion firstLine = document + .getLineInformationOfOffset(command.offset); + position = command.offset - firstLine.getOffset(); + } + int length = line.length(); + for (int j = 0; j < length; j++) { + char c = line.charAt(j); + if (c == '\t') { + position += insertTabString(buffer, position); + } else { + buffer.append(c); + ++position; + } + } + } + command.text = buffer.toString(); + } catch (BadLocationException x) { + } + } + } + }; - /** - * Does the given Java element contain the given offset? - * - * @param element - * Java element - * @param offset - * Offset - * @return true iff the Java element contains the offset - */ - private boolean containsOffset(IJavaElement element, int offset) { - int elementOffset = getOffset(element); - int elementLength = getLength(element); - return (elementOffset > -1 && elementLength > -1) ? (offset >= elementOffset && offset < elementOffset + elementLength) - : false; - } + private static class ExitPolicy implements LinkedPositionUI.ExitPolicy { + final char fExitCharacter; - /** - * Returns the offset of the given Java element. - * - * @param element - * Java element - * @return Offset of the given Java element - */ - private int getOffset(IJavaElement element) { - if (element instanceof ISourceReference) { - ISourceReference sr = (ISourceReference) element; - try { - ISourceRange srcRange = sr.getSourceRange(); - if (srcRange != null) - return srcRange.getOffset(); - } catch (JavaModelException e) { + public ExitPolicy(char exitCharacter) { + fExitCharacter = exitCharacter; } - } - return -1; - } - /** - * Returns the length of the given Java element. - * - * @param element - * Java element - * @return Length of the given Java element - */ - private int getLength(IJavaElement element) { - if (element instanceof ISourceReference) { - ISourceReference sr = (ISourceReference) element; - try { - ISourceRange srcRange = sr.getSourceRange(); - if (srcRange != null) - return srcRange.getLength(); - } catch (JavaModelException e) { + /* + * @see org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionManager, + * org.eclipse.swt.events.VerifyEvent, int, int) + */ + public ExitFlags doExit(LinkedPositionManager manager, + VerifyEvent event, int offset, int length) { + if (event.character == fExitCharacter) { + if (manager.anyPositionIncludes(offset, length)) + return new ExitFlags(LinkedPositionUI.COMMIT + | LinkedPositionUI.UPDATE_CARET, false); + else + return new ExitFlags(LinkedPositionUI.COMMIT, true); + } + switch (event.character) { + case '\b': + if (manager.getFirstPosition().length == 0) + return new ExitFlags(0, false); + else + return null; + case '\n': + case '\r': + return new ExitFlags(LinkedPositionUI.COMMIT, true); + default: + return null; + } } - } - return -1; } - /** - * Returns the updated java element for the old java element. - * - * @param element - * Old Java element - * @return Updated Java element - */ - private IJavaElement findElement(IJavaElement element) { + private static class BracketLevel { + int fOffset; - if (element == null) - return null; + int fLength; - IWorkingCopyManager manager = PHPeclipsePlugin.getDefault().getWorkingCopyManager(); - ICompilationUnit unit = manager.getWorkingCopy(getEditorInput()); + LinkedPositionManager fManager; - if (unit != null) { - try { + LinkedPositionUI fEditor; + }; - synchronized (unit) { - // unit.reconcile(ICompilationUnit.NO_AST, false, null, null); - unit.reconcile(); - } - IJavaElement[] findings = unit.findElements(element); - if (findings != null && findings.length > 0) - return findings[0]; + private class BracketInserter implements VerifyKeyListener, + LinkedPositionUI.ExitListener { + private boolean fCloseBracketsPHP = true; - } catch (JavaModelException x) { - PHPeclipsePlugin.log(x.getStatus()); - // nothing found, be tolerant and go on - } - } + private boolean fCloseStringsPHPDQ = true; - return null; - } + private boolean fCloseStringsPHPSQ = true; - } + private int fOffset; - static class TabConverter implements ITextConverter { - private int fTabRatio; + private int fLength; - private ILineTracker fLineTracker; + public void setCloseBracketsPHPEnabled(boolean enabled) { + fCloseBracketsPHP = enabled; + } - public TabConverter() { - } + public void setCloseStringsPHPDQEnabled(boolean enabled) { + fCloseStringsPHPDQ = enabled; + } - public void setNumberOfSpacesPerTab(int ratio) { - fTabRatio = ratio; - } + public void setCloseStringsPHPSQEnabled(boolean enabled) { + fCloseStringsPHPSQ = enabled; + } - public void setLineTracker(ILineTracker lineTracker) { - fLineTracker = lineTracker; - } + private boolean hasIdentifierToTheRight(IDocument document, int offset) { + try { + int end = offset; + IRegion endLine = document.getLineInformationOfOffset(end); + int maxEnd = endLine.getOffset() + endLine.getLength(); + while (end != maxEnd + && Character.isWhitespace(document.getChar(end))) + ++end; + return end != maxEnd + && Scanner.isPHPIdentifierPart(document.getChar(end)); + } catch (BadLocationException e) { + // be conservative + return true; + } + } - private int insertTabString(StringBuffer buffer, int offsetInLine) { - if (fTabRatio == 0) - return 0; - int remainder = offsetInLine % fTabRatio; - remainder = fTabRatio - remainder; - for (int i = 0; i < remainder; i++) - buffer.append(' '); - return remainder; - } + private boolean hasIdentifierToTheLeft(IDocument document, int offset) { + try { + int start = offset; + IRegion startLine = document.getLineInformationOfOffset(start); + int minStart = startLine.getOffset(); + while (start != minStart + && Character.isWhitespace(document.getChar(start - 1))) + --start; + return start != minStart + && Scanner.isPHPIdentifierPart(document + .getChar(start - 1)); + } catch (BadLocationException e) { + return true; + } + } - public void customizeDocumentCommand(IDocument document, DocumentCommand command) { - String text = command.text; - if (text == null) - return; - int index = text.indexOf('\t'); - if (index > -1) { - StringBuffer buffer = new StringBuffer(); - fLineTracker.set(command.text); - int lines = fLineTracker.getNumberOfLines(); - try { - for (int i = 0; i < lines; i++) { - int offset = fLineTracker.getLineOffset(i); - int endOffset = offset + fLineTracker.getLineLength(i); - String line = text.substring(offset, endOffset); - int position = 0; - if (i == 0) { - IRegion firstLine = document.getLineInformationOfOffset(command.offset); - position = command.offset - firstLine.getOffset(); + private boolean hasCharacterToTheLeft(IDocument document, int offset, + char character) { + try { + int start = offset; + IRegion startLine = document.getLineInformationOfOffset(start); + int minStart = startLine.getOffset(); + while (start != minStart + && Character.isWhitespace(document.getChar(start - 1))) + --start; + return start != minStart + && document.getChar(start - 1) == character; + } catch (BadLocationException e) { + return false; } - int length = line.length(); - for (int j = 0; j < length; j++) { - char c = line.charAt(j); - if (c == '\t') { - position += insertTabString(buffer, position); - } else { - buffer.append(c); - ++position; - } + } + + private boolean hasCharacterToTheRight(IDocument document, int offset, + char character) { + try { + int end = offset; + IRegion endLine = document.getLineInformationOfOffset(end); + int maxEnd = endLine.getOffset() + endLine.getLength(); + while (end != maxEnd + && Character.isWhitespace(document.getChar(end))) + ++end; + return end != maxEnd && document.getChar(end) == character; + } catch (BadLocationException e) { + // be conservative + return true; } - } - command.text = buffer.toString(); - } catch (BadLocationException x) { } - } - } - }; - private static class ExitPolicy implements LinkedPositionUI.ExitPolicy { - final char fExitCharacter; + /* + * @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent) + */ + public void verifyKey(VerifyEvent event) { + if (!event.doit) + return; + final ISourceViewer sourceViewer = getSourceViewer(); + IDocument document = sourceViewer.getDocument(); + final Point selection = sourceViewer.getSelectedRange(); + final int offset = selection.x; + final int length = selection.y; + try { + ITypedRegion partition = document.getPartition(offset); + String type = partition.getType(); + if (type.equals(IPHPPartitions.PHP_PARTITIONING) + || type.equals(IDocument.DEFAULT_CONTENT_TYPE)) { + // you will get IDocument.DEFAULT_CONTENT_TYPE for both PHP + // and HTML area + switch (event.character) { + case '(': + if (hasCharacterToTheRight(document, offset + length, + '(')) + return; + // fall through + case '[': + if (!fCloseBracketsPHP) + return; + if (hasIdentifierToTheRight(document, offset + length)) + return; + // fall through + case '{': + if (!fCloseBracketsPHP) + return; + if (hasIdentifierToTheRight(document, offset + length)) + return; + // fall through + case '"': + if (event.character == '"') { + if (!fCloseStringsPHPDQ) + return; + // changed for statements like echo "" print "" + // if (hasIdentifierToTheLeft(document, offset) + // || + // hasIdentifierToTheRight(document, offset + + // length)) + if (hasIdentifierToTheRight(document, offset + + length)) + return; + } + // ITypedRegion partition= + // document.getPartition(offset); + // if (! + // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType()) + // && + // (partition.getOffset() != offset)) + // return; + final char characterDQ = event.character; + final char closingCharacterDQ = getPeerCharacter(characterDQ); + final StringBuffer bufferDQ = new StringBuffer(); + bufferDQ.append(characterDQ); + bufferDQ.append(closingCharacterDQ); + document.replace(offset, length, bufferDQ.toString()); + LinkedPositionManager managerDQ = new LinkedPositionManager( + document); + managerDQ.addPosition(offset + 1, 0); + fOffset = offset; + fLength = 2; + LinkedPositionUI editorDQ = new LinkedPositionUI( + sourceViewer, managerDQ); + editorDQ.setCancelListener(this); + editorDQ.setExitPolicy(new ExitPolicy( + closingCharacterDQ)); + editorDQ.setFinalCaretOffset(offset + 2); + editorDQ.enter(); + IRegion newSelectionDQ = editorDQ.getSelectedRegion(); + sourceViewer.setSelectedRange(newSelectionDQ + .getOffset(), newSelectionDQ.getLength()); + event.doit = false; + break; + case '\'': + if (event.character == '\'') { + if (!fCloseStringsPHPSQ) + return; + // changed for statements like echo "" print "" + // if (hasIdentifierToTheLeft(document, offset) + // || + // hasIdentifierToTheRight(document, offset + + // length)) + if (hasIdentifierToTheRight(document, offset + + length)) + return; + } + // ITypedRegion partition= + // document.getPartition(offset); + // if (! + // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType()) + // && + // (partition.getOffset() != offset)) + // return; + final char characterSQ = event.character; + final char closingCharacterSQ = getPeerCharacter(characterSQ); + final StringBuffer bufferSQ = new StringBuffer(); + bufferSQ.append(characterSQ); + bufferSQ.append(closingCharacterSQ); + document.replace(offset, length, bufferSQ.toString()); + LinkedPositionManager managerSQ = new LinkedPositionManager( + document); + managerSQ.addPosition(offset + 1, 0); + fOffset = offset; + fLength = 2; + LinkedPositionUI editorSQ = new LinkedPositionUI( + sourceViewer, managerSQ); + editorSQ.setCancelListener(this); + editorSQ.setExitPolicy(new ExitPolicy( + closingCharacterSQ)); + editorSQ.setFinalCaretOffset(offset + 2); + editorSQ.enter(); + IRegion newSelectionSQ = editorSQ.getSelectedRegion(); + sourceViewer.setSelectedRange(newSelectionSQ + .getOffset(), newSelectionSQ.getLength()); + event.doit = false; + case '\r': { // insert linebreaks and new closing brace + // after brace and return + if (!fCloseBracketsPHP) { + return; + } + if (hasCharacterToTheLeft(document, offset, '{') + && hasCharacterToTheRight(document, offset, '}')) { + String lineDelimiter = StubUtility + .getLineDelimiterFor(document); + int caretPos = sourceViewer.getTextWidget() + .getCaretOffset(); + final StringBuffer buffer = new StringBuffer( + lineDelimiter); + // get indentation + IRegion line = document + .getLineInformationOfOffset(offset); + String currentLine = document.get(line.getOffset(), + line.getLength()); + int index = 0; + int max = currentLine.length(); + StringBuffer indent = new StringBuffer(); + while (index < max + && Character.isWhitespace(currentLine + .charAt(index))) { + indent.append(currentLine.charAt(index)); + index++; + } + buffer.append(indent); + JavaHeuristicScanner scanner = new JavaHeuristicScanner( + document); + JavaIndenter indenter = new JavaIndenter(document, + scanner); + buffer.append(indenter.createIndent(1)); + int cursorPos = buffer.length(); + buffer.append(lineDelimiter); + buffer.append(indent); + document.replace(offset, length, buffer.toString()); + sourceViewer.getTextWidget().setCaretOffset( + caretPos + cursorPos); + event.doit = false; + } + } + } + } + } catch (BadLocationException e) { + } + } - public ExitPolicy(char exitCharacter) { - fExitCharacter = exitCharacter; + /* + * @see org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionUI.ExitListener#exit(boolean) + */ + public void exit(boolean accept) { + if (accept) + return; + // remove brackets + try { + final ISourceViewer sourceViewer = getSourceViewer(); + IDocument document = sourceViewer.getDocument(); + document.replace(fOffset, fLength, null); + } catch (BadLocationException e) { + } + } } - /* - * @see org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionManager, - * org.eclipse.swt.events.VerifyEvent, int, int) - */ - public ExitFlags doExit(LinkedPositionManager manager, VerifyEvent event, int offset, int length) { - if (event.character == fExitCharacter) { - if (manager.anyPositionIncludes(offset, length)) - return new ExitFlags(LinkedPositionUI.COMMIT | LinkedPositionUI.UPDATE_CARET, false); - else - return new ExitFlags(LinkedPositionUI.COMMIT, true); - } - switch (event.character) { - case '\b': - if (manager.getFirstPosition().length == 0) - return new ExitFlags(0, false); - else - return null; - case '\n': - case '\r': - return new ExitFlags(LinkedPositionUI.COMMIT, true); - default: - return null; - } - } - } + /** The editor's save policy */ + protected ISavePolicy fSavePolicy; - private static class BracketLevel { - int fOffset; + /** + * Listener to annotation model changes that updates the error tick in the + * tab image + */ + private JavaEditorErrorTickUpdater fJavaEditorErrorTickUpdater; + + /** The editor's paint manager */ + // private PaintManager fPaintManager; + /** The editor's bracket painter */ + // private BracketPainter fBracketPainter; + /** The editor's bracket matcher */ + private PHPPairMatcher fBracketMatcher; + + /** The editor's line painter */ + // private LinePainter fLinePainter; + /** The editor's print margin ruler painter */ + // private PrintMarginPainter fPrintMarginPainter; + /** The editor's problem painter */ + // private ProblemPainter fProblemPainter; + /** The editor's tab converter */ + private TabConverter fTabConverter; + + /** History for structure select action */ + // private SelectionHistory fSelectionHistory; + /** The preference property change listener for php core. */ + // private IPropertyChangeListener fPropertyChangeListener = new + // PropertyChangeListener(); + /** The remembered java element */ + private IJavaElement fRememberedElement; - int fLength; + /** + * The remembered selection. + * + * @since 3.0 + */ + private RememberedSelection fRememberedSelection = new RememberedSelection(); + + /** The remembered php element offset */ + private int fRememberedElementOffset; + + /** The bracket inserter. */ + private BracketInserter fBracketInserter = new BracketInserter(); + + /** The standard action groups added to the menu */ + private GenerateActionGroup fGenerateActionGroup; + + private CompositeActionGroup fContextMenuGroup; + + // private class PropertyChangeListener implements IPropertyChangeListener { + // /* + // * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) + // */ + // public void + // propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent + // event) { + // handlePreferencePropertyChanged(event); + // } + // } + /* Preference key for code formatter tab size */ + private final static String CODE_FORMATTER_TAB_SIZE = JavaCore.FORMATTER_TAB_SIZE; + + /** Preference key for matching brackets */ + // private final static String MATCHING_BRACKETS = + // PreferenceConstants.EDITOR_MATCHING_BRACKETS; + /** Preference key for matching brackets color */ + // private final static String MATCHING_BRACKETS_COLOR = + // PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR; + /** Preference key for highlighting current line */ + // private final static String CURRENT_LINE = + // PreferenceConstants.EDITOR_CURRENT_LINE; + /** Preference key for highlight color of current line */ + // private final static String CURRENT_LINE_COLOR = + // PreferenceConstants.EDITOR_CURRENT_LINE_COLOR; + /** Preference key for showing print marging ruler */ + // private final static String PRINT_MARGIN = + // PreferenceConstants.EDITOR_PRINT_MARGIN; + /** Preference key for print margin ruler color */ + // private final static String PRINT_MARGIN_COLOR = + // PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR; + /** Preference key for print margin ruler column */ + // private final static String PRINT_MARGIN_COLUMN = + // PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN; + /** Preference key for inserting spaces rather than tabs */ + private final static String SPACES_FOR_TABS = PreferenceConstants.EDITOR_SPACES_FOR_TABS; + + /** Preference key for error indication */ + // private final static String ERROR_INDICATION = + // PreferenceConstants.EDITOR_PROBLEM_INDICATION; + /** Preference key for error color */ + // private final static String ERROR_INDICATION_COLOR = + // PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR; + /** Preference key for warning indication */ + // private final static String WARNING_INDICATION = + // PreferenceConstants.EDITOR_WARNING_INDICATION; + /** Preference key for warning color */ + // private final static String WARNING_INDICATION_COLOR = + // PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR; + /** Preference key for task indication */ + private final static String TASK_INDICATION = PreferenceConstants.EDITOR_TASK_INDICATION; + + /** Preference key for task color */ + private final static String TASK_INDICATION_COLOR = PreferenceConstants.EDITOR_TASK_INDICATION_COLOR; + + /** Preference key for bookmark indication */ + private final static String BOOKMARK_INDICATION = PreferenceConstants.EDITOR_BOOKMARK_INDICATION; + + /** Preference key for bookmark color */ + private final static String BOOKMARK_INDICATION_COLOR = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR; + + /** Preference key for search result indication */ + private final static String SEARCH_RESULT_INDICATION = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION; + + /** Preference key for search result color */ + private final static String SEARCH_RESULT_INDICATION_COLOR = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR; + + /** Preference key for unknown annotation indication */ + private final static String UNKNOWN_INDICATION = PreferenceConstants.EDITOR_UNKNOWN_INDICATION; + + /** Preference key for unknown annotation color */ + private final static String UNKNOWN_INDICATION_COLOR = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR; + + /** Preference key for linked position color */ + private final static String LINKED_POSITION_COLOR = PreferenceConstants.EDITOR_LINKED_POSITION_COLOR; + + /** Preference key for shwoing the overview ruler */ + private final static String OVERVIEW_RULER = PreferenceConstants.EDITOR_OVERVIEW_RULER; + + /** Preference key for error indication in overview ruler */ + private final static String ERROR_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER; + + /** Preference key for warning indication in overview ruler */ + private final static String WARNING_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER; + + /** Preference key for task indication in overview ruler */ + private final static String TASK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER; + + /** Preference key for bookmark indication in overview ruler */ + private final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER; + + /** Preference key for search result indication in overview ruler */ + private final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER; + + /** Preference key for unknown annotation indication in overview ruler */ + private final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER; + + /** Preference key for automatically closing double quoted strings */ + private final static String CLOSE_STRINGS_DQ_PHP = PreferenceConstants.EDITOR_CLOSE_STRINGS_DQ_PHP; + + /** Preference key for automatically closing single quoted strings */ + private final static String CLOSE_STRINGS_SQ_PHP = PreferenceConstants.EDITOR_CLOSE_STRINGS_SQ_PHP; + + /** Preference key for automatically wrapping Java strings */ + // private final static String WRAP_STRINGS = + // PreferenceConstants.EDITOR_WRAP_STRINGS_DQ; + /** Preference key for automatically closing brackets and parenthesis */ + private final static String CLOSE_BRACKETS_PHP = PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP; + + /** Preference key for automatically closing phpdocs and comments */ + private final static String CLOSE_JAVADOCS = PreferenceConstants.EDITOR_CLOSE_JAVADOCS; + + /** Preference key for automatically adding phpdoc tags */ + private final static String ADD_JAVADOC_TAGS = PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS; + + /** Preference key for automatically formatting phpdocs */ + // private final static String FORMAT_JAVADOCS = + // PreferenceConstants.EDITOR_FORMAT_JAVADOCS; + /** Preference key for automatically closing strings */ + private final static String CLOSE_STRINGS_HTML = PreferenceConstants.EDITOR_CLOSE_STRINGS_HTML; + + /** Preference key for automatically closing brackets and parenthesis */ + private final static String CLOSE_BRACKETS_HTML = PreferenceConstants.EDITOR_CLOSE_BRACKETS_HTML; + + /** Preference key for smart paste */ + private final static String SMART_PASTE = PreferenceConstants.EDITOR_SMART_PASTE; + + // private final static class AnnotationInfo { + // public String fColorPreference; + // public String fOverviewRulerPreference; + // public String fEditorPreference; + // }; + // private final static Map ANNOTATION_MAP; + // static { + // + // AnnotationInfo info; + // ANNOTATION_MAP = new HashMap(); + // + // info = new AnnotationInfo(); + // info.fColorPreference = TASK_INDICATION_COLOR; + // info.fOverviewRulerPreference = TASK_INDICATION_IN_OVERVIEW_RULER; + // info.fEditorPreference = TASK_INDICATION; + // ANNOTATION_MAP.put(AnnotationType.TASK, info); + // + // info = new AnnotationInfo(); + // info.fColorPreference = ERROR_INDICATION_COLOR; + // info.fOverviewRulerPreference = ERROR_INDICATION_IN_OVERVIEW_RULER; + // info.fEditorPreference = ERROR_INDICATION; + // ANNOTATION_MAP.put(AnnotationType.ERROR, info); + // + // info = new AnnotationInfo(); + // info.fColorPreference = WARNING_INDICATION_COLOR; + // info.fOverviewRulerPreference = WARNING_INDICATION_IN_OVERVIEW_RULER; + // info.fEditorPreference = WARNING_INDICATION; + // ANNOTATION_MAP.put(AnnotationType.WARNING, info); + // + // info = new AnnotationInfo(); + // info.fColorPreference = BOOKMARK_INDICATION_COLOR; + // info.fOverviewRulerPreference = BOOKMARK_INDICATION_IN_OVERVIEW_RULER; + // info.fEditorPreference = BOOKMARK_INDICATION; + // ANNOTATION_MAP.put(AnnotationType.BOOKMARK, info); + // + // info = new AnnotationInfo(); + // info.fColorPreference = SEARCH_RESULT_INDICATION_COLOR; + // info.fOverviewRulerPreference = + // SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER; + // info.fEditorPreference = SEARCH_RESULT_INDICATION; + // ANNOTATION_MAP.put(AnnotationType.SEARCH, info); + // + // info = new AnnotationInfo(); + // info.fColorPreference = UNKNOWN_INDICATION_COLOR; + // info.fOverviewRulerPreference = UNKNOWN_INDICATION_IN_OVERVIEW_RULER; + // info.fEditorPreference = UNKNOWN_INDICATION; + // ANNOTATION_MAP.put(AnnotationType.UNKNOWN, info); + // }; + // + // private final static AnnotationType[] ANNOTATION_LAYERS = + // new AnnotationType[] { + // AnnotationType.UNKNOWN, + // AnnotationType.BOOKMARK, + // AnnotationType.TASK, + // AnnotationType.SEARCH, + // AnnotationType.WARNING, + // AnnotationType.ERROR }; + /** + * Creates a new php unit editor. + */ - LinkedPositionManager fManager; + /** + * Reconciling listeners. + * + * @since 3.0 + */ + private ListenerList fReconcilingListeners = new ListenerList(); - LinkedPositionUI fEditor; - }; + /** + * Mutex for the reconciler. See + * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898 for a description of + * the problem. + *

                                                      + * TODO remove once the underlying problem is solved. + *

                                                      + */ + private final Object fReconcilerLock = new Object(); - private class BracketInserter implements VerifyKeyListener, LinkedPositionUI.ExitListener { - private boolean fCloseBracketsPHP = true; + public PHPUnitEditor() { + super(); + setDocumentProvider(PHPeclipsePlugin.getDefault() + .getCompilationUnitDocumentProvider()); + setEditorContextMenuId("#PHPEditorContext"); //$NON-NLS-1$ + setRulerContextMenuId("#PHPRulerContext"); //$NON-NLS-1$ + setOutlinerContextMenuId("#PHPOutlinerContext"); //$NON-NLS-1$ + // don't set help contextId, we install our own help context + fSavePolicy = null; + fJavaEditorErrorTickUpdater = new JavaEditorErrorTickUpdater(this); + } - private boolean fCloseStringsPHPDQ = true; + /* + * @see AbstractTextEditor#createActions() + */ + protected void createActions() { + super.createActions(); + Action action; + // Action action= new + // TextOperationAction(PHPEditorMessages.getResourceBundle(), + // "CorrectionAssistProposal.", this, CORRECTIONASSIST_PROPOSALS); + // //$NON-NLS-1$ + // action.setActionDefinitionId(PHPEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS); + // setAction("CorrectionAssistProposal", action); //$NON-NLS-1$ + // markAsStateDependentAction("CorrectionAssistProposal", true); + // //$NON-NLS-1$ + // // WorkbenchHelp.setHelp(action, + // IJavaHelpContextIds.QUICK_FIX_ACTION); + action = new ContentAssistAction(PHPEditorMessages.getResourceBundle(), + "ContentAssistProposal.", this); //$NON-NLS-1$ + action + .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); + setAction("ContentAssistProposal", action); //$NON-NLS-1$ + markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$ + // WorkbenchHelp.setHelp(action, + // IJavaHelpContextIds.CONTENT_ASSIST_ACTION); + // action = new + // TextOperationAction(PHPEditorMessages.getResourceBundle(), + // "ContentAssistContextInformation.", this, + // ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$ + // action + // .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION); + // setAction("ContentAssistContextInformation", action); //$NON-NLS-1$ + // markAsStateDependentAction("ContentAssistContextInformation", true); + // //$NON-NLS-1$ + // WorkbenchHelp.setHelp(action, + // IJavaHelpContextIds.PARAMETER_HINTS_ACTION); + // action= new + // TextOperationAction(PHPEditorMessages.getResourceBundle(), + // "ContentAssistCompletePrefix.", this, CONTENTASSIST_COMPLETE_PREFIX); + // //$NON-NLS-1$ + // action.setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_COMPLETE_PREFIX); + // setAction("ContentAssistCompletePrefix", action); //$NON-NLS-1$ + // markAsStateDependentAction("ContentAssistCompletePrefix", true); + // //$NON-NLS-1$ + // // WorkbenchHelp.setHelp(action, + // IJavaHelpContextIds.PARAMETER_HINTS_ACTION); + action = new TextOperationAction(PHPEditorMessages.getResourceBundle(), + "Comment.", this, ITextOperationTarget.PREFIX); //$NON-NLS-1$ + action.setActionDefinitionId(PHPEditorActionDefinitionIds.COMMENT); + setAction("Comment", action); //$NON-NLS-1$ + markAsStateDependentAction("Comment", true); //$NON-NLS-1$ + // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.COMMENT_ACTION); + action = new TextOperationAction(PHPEditorMessages.getResourceBundle(), + "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX); //$NON-NLS-1$ + action.setActionDefinitionId(PHPEditorActionDefinitionIds.UNCOMMENT); + setAction("Uncomment", action); //$NON-NLS-1$ + markAsStateDependentAction("Uncomment", true); //$NON-NLS-1$ + // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.UNCOMMENT_ACTION); + + action = new ToggleCommentAction(PHPEditorMessages.getResourceBundle(), + "ToggleComment.", this); //$NON-NLS-1$ + action + .setActionDefinitionId(PHPEditorActionDefinitionIds.TOGGLE_COMMENT); + setAction("ToggleComment", action); //$NON-NLS-1$ + markAsStateDependentAction("ToggleComment", true); //$NON-NLS-1$ + // WorkbenchHelp.setHelp(action, + // IJavaHelpContextIds.TOGGLE_COMMENT_ACTION); + configureToggleCommentAction(); + + action = new TextOperationAction(PHPEditorMessages.getResourceBundle(), + "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$ + action.setActionDefinitionId(PHPEditorActionDefinitionIds.FORMAT); + setAction("Format", action); //$NON-NLS-1$ + markAsStateDependentAction("Format", true); //$NON-NLS-1$ + markAsSelectionDependentAction("Format", true); //$NON-NLS-1$ + // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.FORMAT_ACTION); + + // action = new + // AddBlockCommentAction(PHPEditorMessages.getResourceBundle(), + // "AddBlockComment.", this); //$NON-NLS-1$ + // action + // .setActionDefinitionId(PHPEditorActionDefinitionIds.ADD_BLOCK_COMMENT); + // setAction("AddBlockComment", action); //$NON-NLS-1$ + // markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$ + // markAsSelectionDependentAction("AddBlockComment", true); + // //$NON-NLS-1$ + // // WorkbenchHelp.setHelp(action, + // // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION); + // action = new RemoveBlockCommentAction( + // PHPEditorMessages.getResourceBundle(), "RemoveBlockComment.", this); + // //$NON-NLS-1$ + // action + // .setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT); + // setAction("RemoveBlockComment", action); //$NON-NLS-1$ + // markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$ + // markAsSelectionDependentAction("RemoveBlockComment", true); + // //$NON-NLS-1$ + // WorkbenchHelp.setHelp(action, + // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION); + action = new IndentAction(PHPEditorMessages.getResourceBundle(), + "Indent.", this, false); //$NON-NLS-1$ + action.setActionDefinitionId(PHPEditorActionDefinitionIds.INDENT); + setAction("Indent", action); //$NON-NLS-1$ + markAsStateDependentAction("Indent", true); //$NON-NLS-1$ + markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$ + // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION); + // + // action= new IndentAction(PHPEditorMessages.getResourceBundle(), + // "Indent.", this, true); //$NON-NLS-1$ + // setAction("IndentOnTab", action); //$NON-NLS-1$ + // markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$ + // markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$ + // - private boolean fCloseStringsPHPSQ = true; + action = new AddBlockCommentAction(PHPEditorMessages + .getResourceBundle(), "AddBlockComment.", this); //$NON-NLS-1$ + action + .setActionDefinitionId(PHPEditorActionDefinitionIds.ADD_BLOCK_COMMENT); + setAction("AddBlockComment", action); //$NON-NLS-1$ + markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$ + markAsSelectionDependentAction("AddBlockComment", true); //$NON-NLS-1$ + // WorkbenchHelp.setHelp(action, + // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION); + + action = new RemoveBlockCommentAction(PHPEditorMessages + .getResourceBundle(), "RemoveBlockComment.", this); //$NON-NLS-1$ + action + .setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT); + setAction("RemoveBlockComment", action); //$NON-NLS-1$ + markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$ + markAsSelectionDependentAction("RemoveBlockComment", true); //$NON-NLS-1$ + // WorkbenchHelp.setHelp(action, + // IJavaHelpContextIds.REMOVE_BLOCK_COMMENT_ACTION); + + // action= new IndentAction(PHPEditorMessages.getResourceBundle(), + // "Indent.", this, false); //$NON-NLS-1$ + // action.setActionDefinitionId(PHPEditorActionDefinitionIds.INDENT); + // setAction("Indent", action); //$NON-NLS-1$ + // markAsStateDependentAction("Indent", true); //$NON-NLS-1$ + // markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$ + // // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION); + // + action = new IndentAction(PHPEditorMessages.getResourceBundle(), + "Indent.", this, true); //$NON-NLS-1$ + setAction("IndentOnTab", action); //$NON-NLS-1$ + markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$ + markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$ + + if (getPreferenceStore().getBoolean( + PreferenceConstants.EDITOR_SMART_TAB)) { + // don't replace Shift Right - have to make sure their enablement is + // mutually exclusive + // removeActionActivationCode(ITextEditorActionConstants.SHIFT_RIGHT); + setActionActivationCode("IndentOnTab", '\t', -1, SWT.NONE); //$NON-NLS-1$ + } + fGenerateActionGroup = new GenerateActionGroup(this, + ITextEditorActionConstants.GROUP_EDIT); + // ActionGroup rg= new RefactorActionGroup(this, + // ITextEditorActionConstants.GROUP_EDIT); - private int fOffset; + // fActionGroups.addGroup(rg); + fActionGroups.addGroup(fGenerateActionGroup); - private int fLength; + // We have to keep the context menu group separate to have better + // control over positioning + fContextMenuGroup = new CompositeActionGroup( + new ActionGroup[] { fGenerateActionGroup + // rg, + // new LocalHistoryActionGroup(this, + // ITextEditorActionConstants.GROUP_EDIT) + }); - public void setCloseBracketsPHPEnabled(boolean enabled) { - fCloseBracketsPHP = enabled; } - public void setCloseStringsPHPDQEnabled(boolean enabled) { - fCloseStringsPHPDQ = enabled; + /* + * @see JavaEditor#getElementAt(int) + */ + protected IJavaElement getElementAt(int offset) { + return getElementAt(offset, true); } - public void setCloseStringsPHPSQEnabled(boolean enabled) { - fCloseStringsPHPSQ = enabled; + /** + * Returns the most narrow element including the given offset. If + * reconcile is true the editor's input + * element is reconciled in advance. If it is false this + * method only returns a result if the editor's input element does not need + * to be reconciled. + * + * @param offset + * the offset included by the retrieved element + * @param reconcile + * true if working copy should be reconciled + */ + protected IJavaElement getElementAt(int offset, boolean reconcile) { + IWorkingCopyManager manager = PHPeclipsePlugin.getDefault() + .getWorkingCopyManager(); + ICompilationUnit unit = manager.getWorkingCopy(getEditorInput()); + if (unit != null) { + try { + if (reconcile) { + synchronized (unit) { + unit.reconcile(); + } + return unit.getElementAt(offset); + } else if (unit.isConsistent()) + return unit.getElementAt(offset); + } catch (JavaModelException x) { + PHPeclipsePlugin.log(x.getStatus()); + // nothing found, be tolerant and go on + } + } + return null; } - private boolean hasIdentifierToTheRight(IDocument document, int offset) { - try { - int end = offset; - IRegion endLine = document.getLineInformationOfOffset(end); - int maxEnd = endLine.getOffset() + endLine.getLength(); - while (end != maxEnd && Character.isWhitespace(document.getChar(end))) - ++end; - return end != maxEnd && Scanner.isPHPIdentifierPart(document.getChar(end)); - } catch (BadLocationException e) { - // be conservative - return true; - } + /* + * @see JavaEditor#getCorrespondingElement(IJavaElement) + */ + protected IJavaElement getCorrespondingElement(IJavaElement element) { + try { + return EditorUtility.getWorkingCopy(element, true); + } catch (JavaModelException x) { + PHPeclipsePlugin.log(x.getStatus()); + // nothing found, be tolerant and go on + } + return null; } - private boolean hasIdentifierToTheLeft(IDocument document, int offset) { - try { - int start = offset; - IRegion startLine = document.getLineInformationOfOffset(start); - int minStart = startLine.getOffset(); - while (start != minStart && Character.isWhitespace(document.getChar(start - 1))) - --start; - return start != minStart && Scanner.isPHPIdentifierPart(document.getChar(start - 1)); - } catch (BadLocationException e) { - return true; - } + public void createPartControl(Composite parent) { + super.createPartControl(parent); + // fPaintManager = new PaintManager(getSourceViewer()); + LinePainter linePainter; + linePainter = new LinePainter(getSourceViewer()); + linePainter.setHighlightColor(new Color(Display.getCurrent(), 225, 235, + 224)); + // fPaintManager.addPainter(linePainter); + // if (isBracketHighlightingEnabled()) + // startBracketHighlighting(); + // if (isLineHighlightingEnabled()) + // startLineHighlighting(); + // if (isPrintMarginVisible()) + // showPrintMargin(); + // Iterator e = ANNOTATION_MAP.keySet().iterator(); + // while (e.hasNext()) { + // AnnotationType type = (AnnotationType) e.next(); + // if (isAnnotationIndicationEnabled(type)) + // startAnnotationIndication(type); + // } + if (isTabConversionEnabled()) + startTabConversion(); + // if (isOverviewRulerVisible()) + // showOverviewRuler(); + // + // Preferences preferences = + // PHPeclipsePlugin.getDefault().getPluginPreferences(); + // preferences.addPropertyChangeListener(fPropertyChangeListener); + IPreferenceStore preferenceStore = getPreferenceStore(); + boolean closeBracketsPHP = preferenceStore + .getBoolean(CLOSE_BRACKETS_PHP); + boolean closeStringsPHPDQ = preferenceStore + .getBoolean(CLOSE_STRINGS_DQ_PHP); + boolean closeStringsPHPSQ = preferenceStore + .getBoolean(CLOSE_STRINGS_SQ_PHP); + fBracketInserter.setCloseBracketsPHPEnabled(closeBracketsPHP); + fBracketInserter.setCloseStringsPHPDQEnabled(closeStringsPHPDQ); + fBracketInserter.setCloseStringsPHPSQEnabled(closeStringsPHPSQ); + ISourceViewer sourceViewer = getSourceViewer(); + if (sourceViewer instanceof ITextViewerExtension) + ((ITextViewerExtension) sourceViewer) + .prependVerifyKeyListener(fBracketInserter); + } + + private static char getPeerCharacter(char character) { + switch (character) { + case '(': + return ')'; + case ')': + return '('; + case '[': + return ']'; + case ']': + return '['; + case '"': + return character; + case '\'': + return character; + case '{': + return '}'; + default: + throw new IllegalArgumentException(); + } } - private boolean hasCharacterToTheLeft(IDocument document, int offset, char character) { - try { - int start = offset; - IRegion startLine = document.getLineInformationOfOffset(start); - int minStart = startLine.getOffset(); - while (start != minStart && Character.isWhitespace(document.getChar(start - 1))) - --start; - return start != minStart && document.getChar(start - 1)== character; - } catch (BadLocationException e) { - return false; - } - } - - private boolean hasCharacterToTheRight(IDocument document, int offset, char character) { - try { - int end = offset; - IRegion endLine = document.getLineInformationOfOffset(end); - int maxEnd = endLine.getOffset() + endLine.getLength(); - while (end != maxEnd && Character.isWhitespace(document.getChar(end))) - ++end; - return end != maxEnd && document.getChar(end) == character; - } catch (BadLocationException e) { - // be conservative - return true; - } + // private void startBracketHighlighting() { + // if (fBracketPainter == null) { + // ISourceViewer sourceViewer = getSourceViewer(); + // fBracketPainter = new BracketPainter(sourceViewer); + // fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR)); + // // fPaintManager.addPainter(fBracketPainter); + // } + // } + // + // private void stopBracketHighlighting() { + // if (fBracketPainter != null) { + // // fPaintManager.removePainter(fBracketPainter); + // fBracketPainter.deactivate(true); + // fBracketPainter.dispose(); + // fBracketPainter = null; + // } + // } + + // private boolean isBracketHighlightingEnabled() { + // IPreferenceStore store = getPreferenceStore(); + // return store.getBoolean(MATCHING_BRACKETS); + // } + + // private void startLineHighlighting() { + // if (fLinePainter == null) { + // ISourceViewer sourceViewer = getSourceViewer(); + // fLinePainter = new LinePainter(sourceViewer); + // fLinePainter.setHighlightColor(getColor(CURRENT_LINE_COLOR)); + // // fPaintManager.addPainter(fLinePainter); + // } + // } + + // private void stopLineHighlighting() { + // if (fLinePainter != null) { + // // fPaintManager.removePainter(fLinePainter); + // fLinePainter.deactivate(true); + // fLinePainter.dispose(); + // fLinePainter = null; + // } + // } + + // private boolean isLineHighlightingEnabled() { + // IPreferenceStore store = getPreferenceStore(); + // return store.getBoolean(CURRENT_LINE); + // } + + // private void showPrintMargin() { + // if (fPrintMarginPainter == null) { + // fPrintMarginPainter = new PrintMarginPainter(getSourceViewer()); + // fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR)); + // fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN)); + // // fPaintManager.addPainter(fPrintMarginPainter); + // } + // } + + // private void hidePrintMargin() { + // if (fPrintMarginPainter != null) { + // // fPaintManager.removePainter(fPrintMarginPainter); + // fPrintMarginPainter.deactivate(true); + // fPrintMarginPainter.dispose(); + // fPrintMarginPainter = null; + // } + // } + + // private boolean isPrintMarginVisible() { + // IPreferenceStore store = getPreferenceStore(); + // return store.getBoolean(PRINT_MARGIN); + // } + + private int getTabSize() { + Preferences preferences = PHPeclipsePlugin.getDefault() + .getPluginPreferences(); + return preferences.getInt(CODE_FORMATTER_TAB_SIZE); + } + + private boolean isTabConversionEnabled() { + IPreferenceStore store = getPreferenceStore(); + return store.getBoolean(SPACES_FOR_TABS); + } + + private Color getColor(String key) { + RGB rgb = PreferenceConverter.getColor(getPreferenceStore(), key); + return getColor(rgb); + } + + private Color getColor(RGB rgb) { + JavaTextTools textTools = PHPeclipsePlugin.getDefault() + .getJavaTextTools(); + return textTools.getColorManager().getColor(rgb); + } + + // private Color getColor(AnnotationType annotationType) { + // AnnotationInfo info = (AnnotationInfo) + // ANNOTATION_MAP.get(annotationType); + // if (info != null) + // return getColor(info.fColorPreference); + // return null; + // } + public void dispose() { + ISourceViewer sourceViewer = getSourceViewer(); + if (sourceViewer instanceof ITextViewerExtension) + ((ITextViewerExtension) sourceViewer) + .removeVerifyKeyListener(fBracketInserter); + // if (fPropertyChangeListener != null) { + // Preferences preferences = + // PHPeclipsePlugin.getDefault().getPluginPreferences(); + // preferences.removePropertyChangeListener(fPropertyChangeListener); + // fPropertyChangeListener = null; + // } + if (fJavaEditorErrorTickUpdater != null) { + fJavaEditorErrorTickUpdater.dispose(); + fJavaEditorErrorTickUpdater = null; + } + // if (fSelectionHistory != null) + // fSelectionHistory.dispose(); + // if (fPaintManager != null) { + // fPaintManager.dispose(); + // fPaintManager = null; + // } + if (fActionGroups != null) { + fActionGroups.dispose(); + fActionGroups = null; + } + super.dispose(); + } + + // protected AnnotationType getAnnotationType(String preferenceKey) { + // Iterator e = ANNOTATION_MAP.keySet().iterator(); + // while (e.hasNext()) { + // AnnotationType type = (AnnotationType) e.next(); + // AnnotationInfo info = (AnnotationInfo) ANNOTATION_MAP.get(type); + // if (info != null) { + // if (preferenceKey.equals(info.fColorPreference) + // || preferenceKey.equals(info.fEditorPreference) + // || preferenceKey.equals(info.fOverviewRulerPreference)) + // return type; + // } + // } + // return null; + // } + /* + * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent) + */ + protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { + try { + AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer(); + if (asv != null) { + String p = event.getProperty(); + if (CLOSE_BRACKETS_PHP.equals(p)) { + fBracketInserter + .setCloseBracketsPHPEnabled(getPreferenceStore() + .getBoolean(p)); + return; + } + if (CLOSE_STRINGS_DQ_PHP.equals(p)) { + fBracketInserter + .setCloseStringsPHPDQEnabled(getPreferenceStore() + .getBoolean(p)); + return; + } + if (CLOSE_STRINGS_SQ_PHP.equals(p)) { + fBracketInserter + .setCloseStringsPHPSQEnabled(getPreferenceStore() + .getBoolean(p)); + return; + } + if (SPACES_FOR_TABS.equals(p)) { + if (isTabConversionEnabled()) + startTabConversion(); + else + stopTabConversion(); + return; + } + // if (MATCHING_BRACKETS.equals(p)) { + // if (isBracketHighlightingEnabled()) + // startBracketHighlighting(); + // else + // stopBracketHighlighting(); + // return; + // } + // if (MATCHING_BRACKETS_COLOR.equals(p)) { + // if (fBracketPainter != null) + // fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR)); + // return; + // } + // if (CURRENT_LINE.equals(p)) { + // if (isLineHighlightingEnabled()) + // startLineHighlighting(); + // else + // stopLineHighlighting(); + // return; + // } + // if (CURRENT_LINE_COLOR.equals(p)) { + // if (fLinePainter != null) { + // stopLineHighlighting(); + // startLineHighlighting(); + // } + // return; + // } + // if (PRINT_MARGIN.equals(p)) { + // if (isPrintMarginVisible()) + // showPrintMargin(); + // else + // hidePrintMargin(); + // return; + // } + // if (PRINT_MARGIN_COLOR.equals(p)) { + // if (fPrintMarginPainter != null) + // fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR)); + // return; + // } + // if (PRINT_MARGIN_COLUMN.equals(p)) { + // if (fPrintMarginPainter != null) + // fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN)); + // return; + // } + // if (OVERVIEW_RULER.equals(p)) { + // if (isOverviewRulerVisible()) + // showOverviewRuler(); + // else + // hideOverviewRuler(); + // return; + // } + // AnnotationType type = getAnnotationType(p); + // if (type != null) { + // + // AnnotationInfo info = (AnnotationInfo) + // ANNOTATION_MAP.get(type); + // if (info.fColorPreference.equals(p)) { + // Color color = getColor(type); + // if (fProblemPainter != null) { + // fProblemPainter.setColor(type, color); + // fProblemPainter.paint(IPainter.CONFIGURATION); + // } + // setColorInOverviewRuler(type, color); + // return; + // } + // + // if (info.fEditorPreference.equals(p)) { + // if (isAnnotationIndicationEnabled(type)) + // startAnnotationIndication(type); + // else + // stopAnnotationIndication(type); + // return; + // } + // + // if (info.fOverviewRulerPreference.equals(p)) { + // if (isAnnotationIndicationInOverviewRulerEnabled(type)) + // showAnnotationIndicationInOverviewRuler(type, true); + // else + // showAnnotationIndicationInOverviewRuler(type, false); + // return; + // } + // } + IContentAssistant c = asv.getContentAssistant(); + if (c instanceof ContentAssistant) + ContentAssistPreference.changeConfiguration( + (ContentAssistant) c, getPreferenceStore(), event); + } + } finally { + super.handlePreferenceStoreChanged(event); + } } /* - * @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent) + * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent) */ - public void verifyKey(VerifyEvent event) { - if (!event.doit) - return; - final ISourceViewer sourceViewer = getSourceViewer(); - IDocument document = sourceViewer.getDocument(); - final Point selection = sourceViewer.getSelectedRange(); - final int offset = selection.x; - final int length = selection.y; - try { - ITypedRegion partition = document.getPartition(offset); - String type = partition.getType(); - if (type.equals(IPHPPartitions.PHP_PARTITIONING) || type.equals(IDocument.DEFAULT_CONTENT_TYPE)) { - // you will get IDocument.DEFAULT_CONTENT_TYPE for both PHP and HTML area - switch (event.character) { - case '(': - if (hasCharacterToTheRight(document, offset + length, '(')) - return; - // fall through - case '[': - if (!fCloseBracketsPHP) - return; - if (hasIdentifierToTheRight(document, offset + length)) - return; - // fall through - case '{': - if (!fCloseBracketsPHP) - return; - if (hasIdentifierToTheRight(document, offset + length)) - return; - // fall through - case '"': - if (event.character == '"') { - if (!fCloseStringsPHPDQ) - return; - // changed for statements like echo "" print "" - // if (hasIdentifierToTheLeft(document, offset) - // || - // hasIdentifierToTheRight(document, offset + - // length)) - if (hasIdentifierToTheRight(document, offset + length)) - return; - } - // ITypedRegion partition= - // document.getPartition(offset); - // if (! - // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType()) - // && - // (partition.getOffset() != offset)) - // return; - final char characterDQ = event.character; - final char closingCharacterDQ = getPeerCharacter(characterDQ); - final StringBuffer bufferDQ = new StringBuffer(); - bufferDQ.append(characterDQ); - bufferDQ.append(closingCharacterDQ); - document.replace(offset, length, bufferDQ.toString()); - LinkedPositionManager managerDQ = new LinkedPositionManager(document); - managerDQ.addPosition(offset + 1, 0); - fOffset = offset; - fLength = 2; - LinkedPositionUI editorDQ = new LinkedPositionUI(sourceViewer, managerDQ); - editorDQ.setCancelListener(this); - editorDQ.setExitPolicy(new ExitPolicy(closingCharacterDQ)); - editorDQ.setFinalCaretOffset(offset + 2); - editorDQ.enter(); - IRegion newSelectionDQ = editorDQ.getSelectedRegion(); - sourceViewer.setSelectedRange(newSelectionDQ.getOffset(), newSelectionDQ.getLength()); - event.doit = false; - break; - case '\'': - if (event.character == '\'') { - if (!fCloseStringsPHPSQ) - return; - // changed for statements like echo "" print "" - // if (hasIdentifierToTheLeft(document, offset) - // || - // hasIdentifierToTheRight(document, offset + - // length)) - if (hasIdentifierToTheRight(document, offset + length)) - return; + protected void handlePreferencePropertyChanged( + org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) { + AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer(); + if (asv != null) { + String p = event.getProperty(); + if (CODE_FORMATTER_TAB_SIZE.equals(p)) { + asv.updateIndentationPrefixes(); + if (fTabConverter != null) + fTabConverter.setNumberOfSpacesPerTab(getTabSize()); } - // ITypedRegion partition= - // document.getPartition(offset); - // if (! - // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType()) - // && - // (partition.getOffset() != offset)) - // return; - final char characterSQ = event.character; - final char closingCharacterSQ = getPeerCharacter(characterSQ); - final StringBuffer bufferSQ = new StringBuffer(); - bufferSQ.append(characterSQ); - bufferSQ.append(closingCharacterSQ); - document.replace(offset, length, bufferSQ.toString()); - LinkedPositionManager managerSQ = new LinkedPositionManager(document); - managerSQ.addPosition(offset + 1, 0); - fOffset = offset; - fLength = 2; - LinkedPositionUI editorSQ = new LinkedPositionUI(sourceViewer, managerSQ); - editorSQ.setCancelListener(this); - editorSQ.setExitPolicy(new ExitPolicy(closingCharacterSQ)); - editorSQ.setFinalCaretOffset(offset + 2); - editorSQ.enter(); - IRegion newSelectionSQ = editorSQ.getSelectedRegion(); - sourceViewer.setSelectedRange(newSelectionSQ.getOffset(), newSelectionSQ.getLength()); - event.doit = false; - case '\r': { // insert linebreaks and new closing brace after brace and return - if (!fCloseBracketsPHP) { - return; - } - if (hasCharacterToTheLeft(document,offset,'{') && hasCharacterToTheRight(document,offset,'}')) { - String lineDelimiter=StubUtility.getLineDelimiterFor(document); - int caretPos=sourceViewer.getTextWidget().getCaretOffset(); - final StringBuffer buffer = new StringBuffer(lineDelimiter); - // get indentation - IRegion line = document.getLineInformationOfOffset(offset); - String currentLine=document.get(line.getOffset(),line.getLength()); - int index=0; - int max=currentLine.length(); - StringBuffer indent=new StringBuffer(); - while (index - * TODO remove once the underlying problem is solved. - *

                                                      - */ - private final Object fReconcilerLock = new Object(); - - public PHPUnitEditor() { - super(); - setDocumentProvider(PHPeclipsePlugin.getDefault().getCompilationUnitDocumentProvider()); - setEditorContextMenuId("#PHPEditorContext"); //$NON-NLS-1$ - setRulerContextMenuId("#PHPRulerContext"); //$NON-NLS-1$ - setOutlinerContextMenuId("#PHPOutlinerContext"); //$NON-NLS-1$ - // don't set help contextId, we install our own help context - fSavePolicy = null; - fJavaEditorErrorTickUpdater = new JavaEditorErrorTickUpdater(this); - } - - /* - * @see AbstractTextEditor#createActions() - */ - protected void createActions() { - super.createActions(); - Action action; - // Action action= new - // TextOperationAction(PHPEditorMessages.getResourceBundle(), - // "CorrectionAssistProposal.", this, CORRECTIONASSIST_PROPOSALS); - // //$NON-NLS-1$ - // action.setActionDefinitionId(PHPEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS); - // setAction("CorrectionAssistProposal", action); //$NON-NLS-1$ - // markAsStateDependentAction("CorrectionAssistProposal", true); - // //$NON-NLS-1$ - //// WorkbenchHelp.setHelp(action, - // IJavaHelpContextIds.QUICK_FIX_ACTION); - action = new ContentAssistAction(PHPEditorMessages.getResourceBundle(), "ContentAssistProposal.", this); //$NON-NLS-1$ - action.setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); - setAction("ContentAssistProposal", action); //$NON-NLS-1$ - markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$ - // WorkbenchHelp.setHelp(action, - // IJavaHelpContextIds.CONTENT_ASSIST_ACTION); - // action = new TextOperationAction(PHPEditorMessages.getResourceBundle(), - // "ContentAssistContextInformation.", this, - // ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$ - // action - // .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION); - // setAction("ContentAssistContextInformation", action); //$NON-NLS-1$ - // markAsStateDependentAction("ContentAssistContextInformation", true); - // //$NON-NLS-1$ - // WorkbenchHelp.setHelp(action, - // IJavaHelpContextIds.PARAMETER_HINTS_ACTION); - // action= new - // TextOperationAction(PHPEditorMessages.getResourceBundle(), - // "ContentAssistCompletePrefix.", this, CONTENTASSIST_COMPLETE_PREFIX); - // //$NON-NLS-1$ - // action.setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_COMPLETE_PREFIX); - // setAction("ContentAssistCompletePrefix", action); //$NON-NLS-1$ - // markAsStateDependentAction("ContentAssistCompletePrefix", true); - // //$NON-NLS-1$ - //// WorkbenchHelp.setHelp(action, - // IJavaHelpContextIds.PARAMETER_HINTS_ACTION); - action = new TextOperationAction(PHPEditorMessages.getResourceBundle(), "Comment.", this, ITextOperationTarget.PREFIX); //$NON-NLS-1$ - action.setActionDefinitionId(PHPEditorActionDefinitionIds.COMMENT); - setAction("Comment", action); //$NON-NLS-1$ - markAsStateDependentAction("Comment", true); //$NON-NLS-1$ - // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.COMMENT_ACTION); - action = new TextOperationAction(PHPEditorMessages.getResourceBundle(), "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX); //$NON-NLS-1$ - action.setActionDefinitionId(PHPEditorActionDefinitionIds.UNCOMMENT); - setAction("Uncomment", action); //$NON-NLS-1$ - markAsStateDependentAction("Uncomment", true); //$NON-NLS-1$ - // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.UNCOMMENT_ACTION); - - action = new ToggleCommentAction(PHPEditorMessages.getResourceBundle(), "ToggleComment.", this); //$NON-NLS-1$ - action.setActionDefinitionId(PHPEditorActionDefinitionIds.TOGGLE_COMMENT); - setAction("ToggleComment", action); //$NON-NLS-1$ - markAsStateDependentAction("ToggleComment", true); //$NON-NLS-1$ - //WorkbenchHelp.setHelp(action, - // IJavaHelpContextIds.TOGGLE_COMMENT_ACTION); - configureToggleCommentAction(); - - action = new TextOperationAction(PHPEditorMessages.getResourceBundle(), "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$ - action.setActionDefinitionId(PHPEditorActionDefinitionIds.FORMAT); - setAction("Format", action); //$NON-NLS-1$ - markAsStateDependentAction("Format", true); //$NON-NLS-1$ - markAsSelectionDependentAction("Format", true); //$NON-NLS-1$ - // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.FORMAT_ACTION); - - // action = new AddBlockCommentAction(PHPEditorMessages.getResourceBundle(), - // "AddBlockComment.", this); //$NON-NLS-1$ - // action - // .setActionDefinitionId(PHPEditorActionDefinitionIds.ADD_BLOCK_COMMENT); - // setAction("AddBlockComment", action); //$NON-NLS-1$ - // markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$ - // markAsSelectionDependentAction("AddBlockComment", true); //$NON-NLS-1$ - // // WorkbenchHelp.setHelp(action, - // // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION); - // action = new RemoveBlockCommentAction( - // PHPEditorMessages.getResourceBundle(), "RemoveBlockComment.", this); //$NON-NLS-1$ - // action - // .setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT); - // setAction("RemoveBlockComment", action); //$NON-NLS-1$ - // markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$ - // markAsSelectionDependentAction("RemoveBlockComment", true); //$NON-NLS-1$ - // WorkbenchHelp.setHelp(action, - // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION); - action= new IndentAction(PHPEditorMessages.getResourceBundle(), - "Indent.", this, false); //$NON-NLS-1$ - action.setActionDefinitionId(PHPEditorActionDefinitionIds.INDENT); - setAction("Indent", action); //$NON-NLS-1$ - markAsStateDependentAction("Indent", true); //$NON-NLS-1$ - markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$ - // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION); - // - // action= new IndentAction(PHPEditorMessages.getResourceBundle(), - // "Indent.", this, true); //$NON-NLS-1$ - // setAction("IndentOnTab", action); //$NON-NLS-1$ - // markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$ - // markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$ - // - action = new AddBlockCommentAction(PHPEditorMessages.getResourceBundle(), "AddBlockComment.", this); //$NON-NLS-1$ - action.setActionDefinitionId(PHPEditorActionDefinitionIds.ADD_BLOCK_COMMENT); - setAction("AddBlockComment", action); //$NON-NLS-1$ - markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$ - markAsSelectionDependentAction("AddBlockComment", true); //$NON-NLS-1$ - // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION); - - action = new RemoveBlockCommentAction(PHPEditorMessages.getResourceBundle(), "RemoveBlockComment.", this); //$NON-NLS-1$ - action.setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT); - setAction("RemoveBlockComment", action); //$NON-NLS-1$ - markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$ - markAsSelectionDependentAction("RemoveBlockComment", true); //$NON-NLS-1$ - // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.REMOVE_BLOCK_COMMENT_ACTION); - - // action= new IndentAction(PHPEditorMessages.getResourceBundle(), "Indent.", this, false); //$NON-NLS-1$ - // action.setActionDefinitionId(PHPEditorActionDefinitionIds.INDENT); - // setAction("Indent", action); //$NON-NLS-1$ - // markAsStateDependentAction("Indent", true); //$NON-NLS-1$ - // markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$ - //// WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION); - // - action = new IndentAction(PHPEditorMessages.getResourceBundle(), "Indent.", this, true); //$NON-NLS-1$ - setAction("IndentOnTab", action); //$NON-NLS-1$ - markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$ - markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$ - - if (getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_TAB)) { - // don't replace Shift Right - have to make sure their enablement is - // mutually exclusive - // removeActionActivationCode(ITextEditorActionConstants.SHIFT_RIGHT); - setActionActivationCode("IndentOnTab", '\t', -1, SWT.NONE); //$NON-NLS-1$ - } - fGenerateActionGroup = new GenerateActionGroup(this, ITextEditorActionConstants.GROUP_EDIT); - // ActionGroup rg= new RefactorActionGroup(this, ITextEditorActionConstants.GROUP_EDIT); - - // fActionGroups.addGroup(rg); - fActionGroups.addGroup(fGenerateActionGroup); - - // We have to keep the context menu group separate to have better control over positioning - fContextMenuGroup = new CompositeActionGroup(new ActionGroup[] { fGenerateActionGroup - // rg, - // new LocalHistoryActionGroup(this, ITextEditorActionConstants.GROUP_EDIT) - }); - - } - - /* - * @see JavaEditor#getElementAt(int) - */ - protected IJavaElement getElementAt(int offset) { - return getElementAt(offset, true); - } - - /** - * Returns the most narrow element including the given offset. If reconcile is true the editor's - * input element is reconciled in advance. If it is false this method only returns a result if the editor's input - * element does not need to be reconciled. - * - * @param offset - * the offset included by the retrieved element - * @param reconcile - * true if working copy should be reconciled - */ - protected IJavaElement getElementAt(int offset, boolean reconcile) { - IWorkingCopyManager manager = PHPeclipsePlugin.getDefault().getWorkingCopyManager(); - ICompilationUnit unit = manager.getWorkingCopy(getEditorInput()); - if (unit != null) { - try { - if (reconcile) { - synchronized (unit) { - unit.reconcile(); - } - return unit.getElementAt(offset); - } else if (unit.isConsistent()) - return unit.getElementAt(offset); - } catch (JavaModelException x) { - PHPeclipsePlugin.log(x.getStatus()); - // nothing found, be tolerant and go on - } - } - return null; - } - - /* - * @see JavaEditor#getCorrespondingElement(IJavaElement) - */ - protected IJavaElement getCorrespondingElement(IJavaElement element) { - try { - return EditorUtility.getWorkingCopy(element, true); - } catch (JavaModelException x) { - PHPeclipsePlugin.log(x.getStatus()); - // nothing found, be tolerant and go on - } - return null; - } - - public void createPartControl(Composite parent) { - super.createPartControl(parent); - // fPaintManager = new PaintManager(getSourceViewer()); - LinePainter linePainter; - linePainter = new LinePainter(getSourceViewer()); - linePainter.setHighlightColor(new Color(Display.getCurrent(), 225, 235, 224)); - // fPaintManager.addPainter(linePainter); - // if (isBracketHighlightingEnabled()) - // startBracketHighlighting(); - // if (isLineHighlightingEnabled()) - // startLineHighlighting(); - // if (isPrintMarginVisible()) - // showPrintMargin(); - // Iterator e = ANNOTATION_MAP.keySet().iterator(); - // while (e.hasNext()) { - // AnnotationType type = (AnnotationType) e.next(); - // if (isAnnotationIndicationEnabled(type)) - // startAnnotationIndication(type); - // } - if (isTabConversionEnabled()) - startTabConversion(); - // if (isOverviewRulerVisible()) - // showOverviewRuler(); - // - // Preferences preferences = - // PHPeclipsePlugin.getDefault().getPluginPreferences(); - // preferences.addPropertyChangeListener(fPropertyChangeListener); - IPreferenceStore preferenceStore = getPreferenceStore(); - boolean closeBracketsPHP = preferenceStore.getBoolean(CLOSE_BRACKETS_PHP); - boolean closeStringsPHPDQ = preferenceStore.getBoolean(CLOSE_STRINGS_DQ_PHP); - boolean closeStringsPHPSQ = preferenceStore.getBoolean(CLOSE_STRINGS_SQ_PHP); - fBracketInserter.setCloseBracketsPHPEnabled(closeBracketsPHP); - fBracketInserter.setCloseStringsPHPDQEnabled(closeStringsPHPDQ); - fBracketInserter.setCloseStringsPHPSQEnabled(closeStringsPHPSQ); - ISourceViewer sourceViewer = getSourceViewer(); - if (sourceViewer instanceof ITextViewerExtension) - ((ITextViewerExtension) sourceViewer).prependVerifyKeyListener(fBracketInserter); - } - - private static char getPeerCharacter(char character) { - switch (character) { - case '(': - return ')'; - case ')': - return '('; - case '[': - return ']'; - case ']': - return '['; - case '"': - return character; - case '\'': - return character; - case '{': - return '}'; - default: - throw new IllegalArgumentException(); - } - } - - // private void startBracketHighlighting() { - // if (fBracketPainter == null) { - // ISourceViewer sourceViewer = getSourceViewer(); - // fBracketPainter = new BracketPainter(sourceViewer); - // fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR)); - // // fPaintManager.addPainter(fBracketPainter); - // } - // } - // - // private void stopBracketHighlighting() { - // if (fBracketPainter != null) { - // // fPaintManager.removePainter(fBracketPainter); - // fBracketPainter.deactivate(true); - // fBracketPainter.dispose(); - // fBracketPainter = null; - // } - // } - - // private boolean isBracketHighlightingEnabled() { - // IPreferenceStore store = getPreferenceStore(); - // return store.getBoolean(MATCHING_BRACKETS); - // } - - // private void startLineHighlighting() { - // if (fLinePainter == null) { - // ISourceViewer sourceViewer = getSourceViewer(); - // fLinePainter = new LinePainter(sourceViewer); - // fLinePainter.setHighlightColor(getColor(CURRENT_LINE_COLOR)); - // // fPaintManager.addPainter(fLinePainter); - // } - // } - - // private void stopLineHighlighting() { - // if (fLinePainter != null) { - // // fPaintManager.removePainter(fLinePainter); - // fLinePainter.deactivate(true); - // fLinePainter.dispose(); - // fLinePainter = null; - // } - // } - - // private boolean isLineHighlightingEnabled() { - // IPreferenceStore store = getPreferenceStore(); - // return store.getBoolean(CURRENT_LINE); - // } - - // private void showPrintMargin() { - // if (fPrintMarginPainter == null) { - // fPrintMarginPainter = new PrintMarginPainter(getSourceViewer()); - // fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR)); - // fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN)); - // // fPaintManager.addPainter(fPrintMarginPainter); - // } - // } - - // private void hidePrintMargin() { - // if (fPrintMarginPainter != null) { - // // fPaintManager.removePainter(fPrintMarginPainter); - // fPrintMarginPainter.deactivate(true); - // fPrintMarginPainter.dispose(); - // fPrintMarginPainter = null; - // } - // } - - // private boolean isPrintMarginVisible() { - // IPreferenceStore store = getPreferenceStore(); - // return store.getBoolean(PRINT_MARGIN); - // } - - private int getTabSize() { - Preferences preferences = PHPeclipsePlugin.getDefault().getPluginPreferences(); - return preferences.getInt(CODE_FORMATTER_TAB_SIZE); - } - - private boolean isTabConversionEnabled() { - IPreferenceStore store = getPreferenceStore(); - return store.getBoolean(SPACES_FOR_TABS); - } - - private Color getColor(String key) { - RGB rgb = PreferenceConverter.getColor(getPreferenceStore(), key); - return getColor(rgb); - } - - private Color getColor(RGB rgb) { - JavaTextTools textTools = PHPeclipsePlugin.getDefault().getJavaTextTools(); - return textTools.getColorManager().getColor(rgb); - } - - // private Color getColor(AnnotationType annotationType) { - // AnnotationInfo info = (AnnotationInfo) - // ANNOTATION_MAP.get(annotationType); - // if (info != null) - // return getColor(info.fColorPreference); - // return null; - // } - public void dispose() { - ISourceViewer sourceViewer = getSourceViewer(); - if (sourceViewer instanceof ITextViewerExtension) - ((ITextViewerExtension) sourceViewer).removeVerifyKeyListener(fBracketInserter); - // if (fPropertyChangeListener != null) { - // Preferences preferences = - // PHPeclipsePlugin.getDefault().getPluginPreferences(); - // preferences.removePropertyChangeListener(fPropertyChangeListener); - // fPropertyChangeListener = null; - // } - if (fJavaEditorErrorTickUpdater != null) { - fJavaEditorErrorTickUpdater.dispose(); - fJavaEditorErrorTickUpdater = null; - } - // if (fSelectionHistory != null) - // fSelectionHistory.dispose(); - // if (fPaintManager != null) { - // fPaintManager.dispose(); - // fPaintManager = null; - // } - if (fActionGroups != null) { - fActionGroups.dispose(); - fActionGroups = null; - } - super.dispose(); - } - - // protected AnnotationType getAnnotationType(String preferenceKey) { - // Iterator e = ANNOTATION_MAP.keySet().iterator(); - // while (e.hasNext()) { - // AnnotationType type = (AnnotationType) e.next(); - // AnnotationInfo info = (AnnotationInfo) ANNOTATION_MAP.get(type); - // if (info != null) { - // if (preferenceKey.equals(info.fColorPreference) - // || preferenceKey.equals(info.fEditorPreference) - // || preferenceKey.equals(info.fOverviewRulerPreference)) - // return type; - // } - // } - // return null; - // } - /* - * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent) - */ - protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { - try { - AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer(); - if (asv != null) { - String p = event.getProperty(); - if (CLOSE_BRACKETS_PHP.equals(p)) { - fBracketInserter.setCloseBracketsPHPEnabled(getPreferenceStore().getBoolean(p)); - return; - } - if (CLOSE_STRINGS_DQ_PHP.equals(p)) { - fBracketInserter.setCloseStringsPHPDQEnabled(getPreferenceStore().getBoolean(p)); - return; - } - if (CLOSE_STRINGS_SQ_PHP.equals(p)) { - fBracketInserter.setCloseStringsPHPSQEnabled(getPreferenceStore().getBoolean(p)); - return; - } - if (SPACES_FOR_TABS.equals(p)) { - if (isTabConversionEnabled()) - startTabConversion(); - else - stopTabConversion(); - return; - } - // if (MATCHING_BRACKETS.equals(p)) { - // if (isBracketHighlightingEnabled()) - // startBracketHighlighting(); - // else - // stopBracketHighlighting(); - // return; - // } - // if (MATCHING_BRACKETS_COLOR.equals(p)) { - // if (fBracketPainter != null) - // fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR)); - // return; - // } - // if (CURRENT_LINE.equals(p)) { - // if (isLineHighlightingEnabled()) - // startLineHighlighting(); - // else - // stopLineHighlighting(); - // return; - // } - // if (CURRENT_LINE_COLOR.equals(p)) { - // if (fLinePainter != null) { - // stopLineHighlighting(); - // startLineHighlighting(); - // } - // return; - // } - // if (PRINT_MARGIN.equals(p)) { - // if (isPrintMarginVisible()) - // showPrintMargin(); - // else - // hidePrintMargin(); - // return; - // } - // if (PRINT_MARGIN_COLOR.equals(p)) { - // if (fPrintMarginPainter != null) - // fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR)); - // return; - // } - // if (PRINT_MARGIN_COLUMN.equals(p)) { - // if (fPrintMarginPainter != null) - // fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN)); - // return; - // } - // if (OVERVIEW_RULER.equals(p)) { - // if (isOverviewRulerVisible()) - // showOverviewRuler(); - // else - // hideOverviewRuler(); - // return; - // } - // AnnotationType type = getAnnotationType(p); - // if (type != null) { - // - // AnnotationInfo info = (AnnotationInfo) - // ANNOTATION_MAP.get(type); - // if (info.fColorPreference.equals(p)) { - // Color color = getColor(type); - // if (fProblemPainter != null) { - // fProblemPainter.setColor(type, color); - // fProblemPainter.paint(IPainter.CONFIGURATION); - // } - // setColorInOverviewRuler(type, color); - // return; - // } - // - // if (info.fEditorPreference.equals(p)) { - // if (isAnnotationIndicationEnabled(type)) - // startAnnotationIndication(type); - // else - // stopAnnotationIndication(type); - // return; - // } - // - // if (info.fOverviewRulerPreference.equals(p)) { - // if (isAnnotationIndicationInOverviewRulerEnabled(type)) - // showAnnotationIndicationInOverviewRuler(type, true); - // else - // showAnnotationIndicationInOverviewRuler(type, false); - // return; - // } - // } - IContentAssistant c = asv.getContentAssistant(); - if (c instanceof ContentAssistant) - ContentAssistPreference.changeConfiguration((ContentAssistant) c, getPreferenceStore(), event); - } - } finally { - super.handlePreferenceStoreChanged(event); - } - } - - /* - * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent) - */ - protected void handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) { - AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer(); - if (asv != null) { - String p = event.getProperty(); - if (CODE_FORMATTER_TAB_SIZE.equals(p)) { - asv.updateIndentationPrefixes(); - if (fTabConverter != null) - fTabConverter.setNumberOfSpacesPerTab(getTabSize()); - } + // protected ISourceViewer createJavaSourceViewer(Composite parent, + // IVerticalRuler ruler, int styles) { + // return new AdaptedSourceViewer(parent, ruler, styles); + // } + private boolean isValidSelection(int offset, int length) { + IDocumentProvider provider = getDocumentProvider(); + if (provider != null) { + IDocument document = provider.getDocument(getEditorInput()); + if (document != null) { + int end = offset + length; + int documentLength = document.getLength(); + return 0 <= offset && offset <= documentLength && 0 <= end + && end <= documentLength; + } + } + return false; } - super.handlePreferencePropertyChanged(event); - } - - /** - * Handles a property change event describing a change of the php core's preferences and updates the preference related editor - * properties. - * - * @param event - * the property change event - */ - // protected void - // handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent - // event) { - // AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer(); - // if (asv != null) { - // String p = event.getProperty(); - // if (CODE_FORMATTER_TAB_SIZE.equals(p)) { - // asv.updateIndentationPrefixes(); - // if (fTabConverter != null) - // fTabConverter.setNumberOfSpacesPerTab(getTabSize()); - // } - // } - // } - /* - * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#createJavaSourceViewer(org.eclipse.swt.widgets.Composite, - * org.eclipse.jface.text.source.IVerticalRuler, org.eclipse.jface.text.source.IOverviewRuler, boolean, int) - */ - protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, - boolean isOverviewRulerVisible, int styles, IPreferenceStore store) { - return new AdaptedSourceViewer(parent, verticalRuler, overviewRuler, isOverviewRulerVisible, styles, store); - } - - // protected ISourceViewer createJavaSourceViewer(Composite parent, - // IVerticalRuler ruler, int styles) { - // return new AdaptedSourceViewer(parent, ruler, styles); - // } - private boolean isValidSelection(int offset, int length) { - IDocumentProvider provider = getDocumentProvider(); - if (provider != null) { - IDocument document = provider.getDocument(getEditorInput()); - if (document != null) { - int end = offset + length; - int documentLength = document.getLength(); - return 0 <= offset && offset <= documentLength && 0 <= end && end <= documentLength; - } + + /* + * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#getInputElement() + */ + protected IJavaElement getInputJavaElement() { + return PHPeclipsePlugin.getDefault().getWorkingCopyManager() + .getWorkingCopy(getEditorInput()); } - return false; - } - - /* - * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#getInputElement() - */ - protected IJavaElement getInputJavaElement() { - return PHPeclipsePlugin.getDefault().getWorkingCopyManager().getWorkingCopy(getEditorInput()); - } - - /* - * @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager) - */ - public void editorContextMenuAboutToShow(IMenuManager menu) { - super.editorContextMenuAboutToShow(menu); - ActionContext context = new ActionContext(getSelectionProvider().getSelection()); - fContextMenuGroup.setContext(context); - fContextMenuGroup.fillContextMenu(menu); - fContextMenuGroup.setContext(null); - } - - /* - * @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput) - */ - protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) { - if (page != null) { - IWorkingCopyManager manager = PHPeclipsePlugin.getDefault().getWorkingCopyManager(); - page.setInput(manager.getWorkingCopy(input)); + + /* + * @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager) + */ + public void editorContextMenuAboutToShow(IMenuManager menu) { + super.editorContextMenuAboutToShow(menu); + ActionContext context = new ActionContext(getSelectionProvider() + .getSelection()); + fContextMenuGroup.setContext(context); + fContextMenuGroup.fillContextMenu(menu); + fContextMenuGroup.setContext(null); } - } - - /* - * @see AbstractTextEditor#performSaveOperation(WorkspaceModifyOperation, IProgressMonitor) - */ - // protected void performSaveOperation(WorkspaceModifyOperation operation, - // IProgressMonitor progressMonitor) { - // IDocumentProvider p = getDocumentProvider(); - // if (p instanceof PHPDocumentProvider) { - // PHPDocumentProvider cp = (PHPDocumentProvider) p; - // cp.setSavePolicy(fSavePolicy); - // } - // - // try { - // super.performSaveOperation(operation, progressMonitor); - // } finally { - // if (p instanceof PHPDocumentProvider) { - // PHPDocumentProvider cp = (PHPDocumentProvider) p; - // cp.setSavePolicy(null); - // } - // } - // } - /* - * @see AbstractTextEditor#doSave(IProgressMonitor) - */ - public void doSave(IProgressMonitor progressMonitor) { - - IDocumentProvider p = getDocumentProvider(); - if (p == null) { - // editor has been closed - return; + + /* + * @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput) + */ + protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) { + if (page != null) { + IWorkingCopyManager manager = PHPeclipsePlugin.getDefault() + .getWorkingCopyManager(); + page.setInput(manager.getWorkingCopy(input)); + } } - if (p.isDeleted(getEditorInput())) { + /* + * @see AbstractTextEditor#performSaveOperation(WorkspaceModifyOperation, + * IProgressMonitor) + */ + // protected void performSaveOperation(WorkspaceModifyOperation operation, + // IProgressMonitor progressMonitor) { + // IDocumentProvider p = getDocumentProvider(); + // if (p instanceof PHPDocumentProvider) { + // PHPDocumentProvider cp = (PHPDocumentProvider) p; + // cp.setSavePolicy(fSavePolicy); + // } + // + // try { + // super.performSaveOperation(operation, progressMonitor); + // } finally { + // if (p instanceof PHPDocumentProvider) { + // PHPDocumentProvider cp = (PHPDocumentProvider) p; + // cp.setSavePolicy(null); + // } + // } + // } + /* + * @see AbstractTextEditor#doSave(IProgressMonitor) + */ + public void doSave(IProgressMonitor progressMonitor) { - if (isSaveAsAllowed()) { + IDocumentProvider p = getDocumentProvider(); + if (p == null) { + // editor has been closed + return; + } - /* - * 1GEUSSR: ITPUI:ALL - User should never loose changes made in the editors. Changed Behavior to make sure that if called - * inside a regular save (because of deletion of input element) there is a way to report back to the caller. - */ - performSaveAs(progressMonitor); + if (p.isDeleted(getEditorInput())) { + + if (isSaveAsAllowed()) { + + /* + * 1GEUSSR: ITPUI:ALL - User should never loose changes made in + * the editors. Changed Behavior to make sure that if called + * inside a regular save (because of deletion of input element) + * there is a way to report back to the caller. + */ + performSaveAs(progressMonitor); + + } else { + + /* + * 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still + * there Missing resources. + */ + Shell shell = getSite().getShell(); + MessageDialog + .openError( + shell, + PHPEditorMessages + .getString("PHPUnitEditor.error.saving.title1"), PHPEditorMessages.getString("PHPUnitEditor.error.saving.message1")); //$NON-NLS-1$ //$NON-NLS-2$ + } - } else { + } else { + if (getPreferenceStore().getBoolean( + PreferenceConstants.EDITOR_P_RTRIM_ON_SAVE)) { + RTrimAction trimAction = new RTrimAction(); + trimAction.setActiveEditor(null, getSite().getPage() + .getActiveEditor()); + trimAction.run(null); + } + + setStatusLineErrorMessage(null); + + updateState(getEditorInput()); + validateState(getEditorInput()); + + IWorkingCopyManager manager = PHPeclipsePlugin.getDefault() + .getWorkingCopyManager(); + ICompilationUnit unit = manager.getWorkingCopy(getEditorInput()); + + if (unit != null) { + synchronized (unit) { + performSave(false, progressMonitor); + } + } else + performSave(false, progressMonitor); + } + } + + public boolean isSaveAsAllowed() { + return true; + } + + /** + * The compilation unit editor implementation of this + * AbstractTextEditor method asks the user for the workspace + * path of a file resource and saves the document there. See + * http://dev.eclipse.org/bugs/show_bug.cgi?id=6295 + * + * @param progressMonitor + * the progress monitor + */ + protected void performSaveAs(IProgressMonitor progressMonitor) { - /* - * 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still there Missing resources. - */ Shell shell = getSite().getShell(); - MessageDialog - .openError( - shell, - PHPEditorMessages.getString("PHPUnitEditor.error.saving.title1"), PHPEditorMessages.getString("PHPUnitEditor.error.saving.message1")); //$NON-NLS-1$ //$NON-NLS-2$ - } + IEditorInput input = getEditorInput(); - } else { - if (getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_P_RTRIM_ON_SAVE)) { - RTrimAction trimAction = new RTrimAction(); - trimAction.setActiveEditor(null, getSite().getPage().getActiveEditor()); - trimAction.run(null); - } + SaveAsDialog dialog = new SaveAsDialog(shell); - setStatusLineErrorMessage(null); + IFile original = (input instanceof IFileEditorInput) ? ((IFileEditorInput) input) + .getFile() + : null; + if (original != null) + dialog.setOriginalFile(original); - updateState(getEditorInput()); - validateState(getEditorInput()); + dialog.create(); - IWorkingCopyManager manager = PHPeclipsePlugin.getDefault().getWorkingCopyManager(); - ICompilationUnit unit = manager.getWorkingCopy(getEditorInput()); + IDocumentProvider provider = getDocumentProvider(); + if (provider == null) { + // editor has been programmatically closed while the dialog was open + return; + } - if (unit != null) { - synchronized (unit) { - performSave(false, progressMonitor); + if (provider.isDeleted(input) && original != null) { + String message = PHPEditorMessages + .getFormattedString( + "CompilationUnitEditor.warning.save.delete", new Object[] { original.getName() }); //$NON-NLS-1$ + dialog.setErrorMessage(null); + dialog.setMessage(message, IMessageProvider.WARNING); } - } else - performSave(false, progressMonitor); - } - } - public boolean isSaveAsAllowed() { - return true; - } + if (dialog.open() == Window.CANCEL) { + if (progressMonitor != null) + progressMonitor.setCanceled(true); + return; + } - /** - * The compilation unit editor implementation of this AbstractTextEditor method asks the user for the workspace - * path of a file resource and saves the document there. See http://dev.eclipse.org/bugs/show_bug.cgi?id=6295 - * - * @param progressMonitor - * the progress monitor - */ - protected void performSaveAs(IProgressMonitor progressMonitor) { + IPath filePath = dialog.getResult(); + if (filePath == null) { + if (progressMonitor != null) + progressMonitor.setCanceled(true); + return; + } - Shell shell = getSite().getShell(); - IEditorInput input = getEditorInput(); + IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); + IFile file = workspaceRoot.getFile(filePath); + final IEditorInput newInput = new FileEditorInput(file); - SaveAsDialog dialog = new SaveAsDialog(shell); + boolean success = false; + try { - IFile original = (input instanceof IFileEditorInput) ? ((IFileEditorInput) input).getFile() : null; - if (original != null) - dialog.setOriginalFile(original); + provider.aboutToChange(newInput); + getDocumentProvider().saveDocument(progressMonitor, newInput, + getDocumentProvider().getDocument(getEditorInput()), true); + success = true; + + } catch (CoreException x) { + IStatus status = x.getStatus(); + if (status == null || status.getSeverity() != IStatus.CANCEL) + ErrorDialog + .openError( + shell, + PHPEditorMessages + .getString("CompilationUnitEditor.error.saving.title2"), PHPEditorMessages.getString("CompilationUnitEditor.error.saving.message2"), x.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$ + } finally { + provider.changed(newInput); + if (success) + setInput(newInput); + } - dialog.create(); + if (progressMonitor != null) + progressMonitor.setCanceled(!success); + } - IDocumentProvider provider = getDocumentProvider(); - if (provider == null) { - // editor has been programmatically closed while the dialog was open - return; + /* + * @see AbstractTextEditor#doSetInput(IEditorInput) + */ + protected void doSetInput(IEditorInput input) throws CoreException { + super.doSetInput(input); + configureTabConverter(); + configureToggleCommentAction(); + } + + // /* + // * @see + // net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#installOverrideIndicator(boolean) + // * @since 3.0 + // */ + // protected void installOverrideIndicator(boolean waitForReconcilation) { + // IAnnotationModel model= + // getDocumentProvider().getAnnotationModel(getEditorInput()); + // if (!waitForReconcilation) + // super.installOverrideIndicator(false); + // else { + // uninstallOverrideIndicator(); + // IJavaElement inputElement= getInputJavaElement(); + // if (model == null || inputElement == null) + // return; + // + // fOverrideIndicatorManager= new OverrideIndicatorManager(model, + // inputElement, null); + // addReconcileListener(fOverrideIndicatorManager); + // } + // } + // + // /* + // * @see + // net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#uninstallOverrideIndicator() + // * @since 3.0 + // */ + // protected void uninstallOverrideIndicator() { + // if (fOverrideIndicatorManager != null) + // removeReconcileListener(fOverrideIndicatorManager); + // super.uninstallOverrideIndicator(); + // } + + /** + * Configures the toggle comment action + * + * @since 3.0 + */ + private void configureToggleCommentAction() { + IAction action = getAction("ToggleComment"); //$NON-NLS-1$ + if (action instanceof ToggleCommentAction) { + ISourceViewer sourceViewer = getSourceViewer(); + SourceViewerConfiguration configuration = getSourceViewerConfiguration(); + ((ToggleCommentAction) action).configure(sourceViewer, + configuration); + } } - if (provider.isDeleted(input) && original != null) { - String message = PHPEditorMessages.getFormattedString( - "CompilationUnitEditor.warning.save.delete", new Object[] { original.getName() }); //$NON-NLS-1$ - dialog.setErrorMessage(null); - dialog.setMessage(message, IMessageProvider.WARNING); + // private void configureTabConverter() { + // if (fTabConverter != null) { + // IDocumentProvider provider = getDocumentProvider(); + // if (provider instanceof PHPDocumentProvider) { + // PHPDocumentProvider cup = (PHPDocumentProvider) provider; + // fTabConverter.setLineTracker(cup.createLineTracker(getEditorInput())); + // } + // } + // } + private void configureTabConverter() { + if (fTabConverter != null) { + IDocumentProvider provider = getDocumentProvider(); + if (provider instanceof ICompilationUnitDocumentProvider) { + ICompilationUnitDocumentProvider cup = (ICompilationUnitDocumentProvider) provider; + fTabConverter.setLineTracker(cup + .createLineTracker(getEditorInput())); + } + } } - if (dialog.open() == Window.CANCEL) { - if (progressMonitor != null) - progressMonitor.setCanceled(true); - return; + private void startTabConversion() { + if (fTabConverter == null) { + fTabConverter = new TabConverter(); + configureTabConverter(); + fTabConverter.setNumberOfSpacesPerTab(getTabSize()); + AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer(); + asv.addTextConverter(fTabConverter); + // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 + asv.updateIndentationPrefixes(); + } } - IPath filePath = dialog.getResult(); - if (filePath == null) { - if (progressMonitor != null) - progressMonitor.setCanceled(true); - return; + private void stopTabConversion() { + if (fTabConverter != null) { + AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer(); + asv.removeTextConverter(fTabConverter); + // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 + asv.updateIndentationPrefixes(); + fTabConverter = null; + } } - IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); - IFile file = workspaceRoot.getFile(filePath); - final IEditorInput newInput = new FileEditorInput(file); - - boolean success = false; - try { - - provider.aboutToChange(newInput); - getDocumentProvider().saveDocument(progressMonitor, newInput, getDocumentProvider().getDocument(getEditorInput()), true); - success = true; - - } catch (CoreException x) { - IStatus status = x.getStatus(); - if (status == null || status.getSeverity() != IStatus.CANCEL) - ErrorDialog - .openError( - shell, - PHPEditorMessages.getString("CompilationUnitEditor.error.saving.title2"), PHPEditorMessages.getString("CompilationUnitEditor.error.saving.message2"), x.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$ - } finally { - provider.changed(newInput); - if (success) - setInput(newInput); + /* + * @see org.eclipse.ui.texteditor.AbstractTextEditor#performSave(boolean, + * org.eclipse.core.runtime.IProgressMonitor) + */ + protected void performSave(boolean overwrite, + IProgressMonitor progressMonitor) { + // IDocumentProvider p = getDocumentProvider(); + // if (p instanceof PHPDocumentProvider) { + // PHPDocumentProvider cp = (PHPDocumentProvider) p; + // cp.setSavePolicy(fSavePolicy); + // } + // try { + // super.performSave(overwrite, progressMonitor); + // } finally { + // if (p instanceof PHPDocumentProvider) { + // PHPDocumentProvider cp = (PHPDocumentProvider) p; + // cp.setSavePolicy(null); + // } + // } + + IDocumentProvider p = getDocumentProvider(); + if (p instanceof ICompilationUnitDocumentProvider) { + ICompilationUnitDocumentProvider cp = (ICompilationUnitDocumentProvider) p; + cp.setSavePolicy(fSavePolicy); + } + try { + super.performSave(overwrite, progressMonitor); + } finally { + if (p instanceof ICompilationUnitDocumentProvider) { + ICompilationUnitDocumentProvider cp = (ICompilationUnitDocumentProvider) p; + cp.setSavePolicy(null); + } + } } - if (progressMonitor != null) - progressMonitor.setCanceled(!success); - } - - /* - * @see AbstractTextEditor#doSetInput(IEditorInput) - */ - protected void doSetInput(IEditorInput input) throws CoreException { - super.doSetInput(input); - configureTabConverter(); - configureToggleCommentAction(); - } - - // /* - // * @see - // net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#installOverrideIndicator(boolean) - // * @since 3.0 - // */ - // protected void installOverrideIndicator(boolean waitForReconcilation) { - // IAnnotationModel model= - // getDocumentProvider().getAnnotationModel(getEditorInput()); - // if (!waitForReconcilation) - // super.installOverrideIndicator(false); - // else { - // uninstallOverrideIndicator(); - // IJavaElement inputElement= getInputJavaElement(); - // if (model == null || inputElement == null) - // return; - // - // fOverrideIndicatorManager= new OverrideIndicatorManager(model, - // inputElement, null); - // addReconcileListener(fOverrideIndicatorManager); - // } - // } - // - // /* - // * @see - // net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#uninstallOverrideIndicator() - // * @since 3.0 - // */ - // protected void uninstallOverrideIndicator() { - // if (fOverrideIndicatorManager != null) - // removeReconcileListener(fOverrideIndicatorManager); - // super.uninstallOverrideIndicator(); - // } - - /** - * Configures the toggle comment action - * - * @since 3.0 - */ - private void configureToggleCommentAction() { - IAction action = getAction("ToggleComment"); //$NON-NLS-1$ - if (action instanceof ToggleCommentAction) { - ISourceViewer sourceViewer = getSourceViewer(); - SourceViewerConfiguration configuration = getSourceViewerConfiguration(); - ((ToggleCommentAction) action).configure(sourceViewer, configuration); + /* + * @see AbstractTextEditor#doSaveAs + */ + public void doSaveAs() { + if (askIfNonWorkbenchEncodingIsOk()) { + super.doSaveAs(); + } } - } - - // private void configureTabConverter() { - // if (fTabConverter != null) { - // IDocumentProvider provider = getDocumentProvider(); - // if (provider instanceof PHPDocumentProvider) { - // PHPDocumentProvider cup = (PHPDocumentProvider) provider; - // fTabConverter.setLineTracker(cup.createLineTracker(getEditorInput())); - // } - // } - // } - private void configureTabConverter() { - if (fTabConverter != null) { - IDocumentProvider provider = getDocumentProvider(); - if (provider instanceof ICompilationUnitDocumentProvider) { - ICompilationUnitDocumentProvider cup = (ICompilationUnitDocumentProvider) provider; - fTabConverter.setLineTracker(cup.createLineTracker(getEditorInput())); - } + + /** + * Asks the user if it is ok to store in non-workbench encoding. + * + * @return if the user wants to continue + */ + private boolean askIfNonWorkbenchEncodingIsOk() { + IDocumentProvider provider = getDocumentProvider(); + if (provider instanceof IStorageDocumentProvider) { + IEditorInput input = getEditorInput(); + IStorageDocumentProvider storageProvider = (IStorageDocumentProvider) provider; + String encoding = storageProvider.getEncoding(input); + String defaultEncoding = storageProvider.getDefaultEncoding(); + if (encoding != null && !encoding.equals(defaultEncoding)) { + Shell shell = getSite().getShell(); + String title = PHPEditorMessages + .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.title"); //$NON-NLS-1$ + String msg; + if (input != null) + msg = MessageFormat + .format( + PHPEditorMessages + .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message1"), + new String[] { input.getName(), encoding }); //$NON-NLS-1$ + else + msg = MessageFormat + .format( + PHPEditorMessages + .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message2"), + new String[] { encoding }); //$NON-NLS-1$ + return MessageDialog.openQuestion(shell, title, msg); + } + } + return true; } - } - - private void startTabConversion() { - if (fTabConverter == null) { - fTabConverter = new TabConverter(); - configureTabConverter(); - fTabConverter.setNumberOfSpacesPerTab(getTabSize()); - AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer(); - asv.addTextConverter(fTabConverter); - // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 - asv.updateIndentationPrefixes(); + + /* + * @see net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener#aboutToBeReconciled() + * @since 3.0 + */ + public void aboutToBeReconciled() { + + // Notify AST provider + // PHPeclipsePlugin.getDefault().getASTProvider().aboutToBeReconciled(getInputJavaElement()); + + // Notify listeners + Object[] listeners = fReconcilingListeners.getListeners(); + for (int i = 0, length = listeners.length; i < length; ++i) + ((IJavaReconcilingListener) listeners[i]).aboutToBeReconciled(); } - } - - private void stopTabConversion() { - if (fTabConverter != null) { - AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer(); - asv.removeTextConverter(fTabConverter); - // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 - asv.updateIndentationPrefixes(); - fTabConverter = null; + + /* + * @see net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener#reconciled(CompilationUnit, + * boolean, IProgressMonitor) + * @since 3.0 + */ + public void reconciled(CompilationUnit ast, boolean forced, + IProgressMonitor progressMonitor) { + + // Always notify AST provider + // PHPeclipsePlugin.getDefault().getASTProvider().reconciled(ast, + // getInputJavaElement()); + + // Notify listeners + // Object[] listeners = fReconcilingListeners.getListeners(); + // for (int i = 0, length= listeners.length; i < length; ++i) + // ((IJavaReconcilingListener)listeners[i]).reconciled(ast, forced, + // progressMonitor); + + // Update Java Outline page selection + if (!forced && !progressMonitor.isCanceled()) { + Shell shell = getSite().getShell(); + if (shell != null && !shell.isDisposed()) { + shell.getDisplay().asyncExec(new Runnable() { + public void run() { + selectionChanged(); + } + }); + } + } } - } - - /* - * @see org.eclipse.ui.texteditor.AbstractTextEditor#performSave(boolean, org.eclipse.core.runtime.IProgressMonitor) - */ - protected void performSave(boolean overwrite, IProgressMonitor progressMonitor) { - // IDocumentProvider p = getDocumentProvider(); - // if (p instanceof PHPDocumentProvider) { - // PHPDocumentProvider cp = (PHPDocumentProvider) p; - // cp.setSavePolicy(fSavePolicy); - // } - // try { - // super.performSave(overwrite, progressMonitor); - // } finally { - // if (p instanceof PHPDocumentProvider) { - // PHPDocumentProvider cp = (PHPDocumentProvider) p; - // cp.setSavePolicy(null); - // } - // } - - IDocumentProvider p = getDocumentProvider(); - if (p instanceof ICompilationUnitDocumentProvider) { - ICompilationUnitDocumentProvider cp = (ICompilationUnitDocumentProvider) p; - cp.setSavePolicy(fSavePolicy); + + /** + * Returns the updated java element for the old java element. + */ + private IJavaElement findElement(IJavaElement element) { + if (element == null) + return null; + IWorkingCopyManager manager = PHPeclipsePlugin.getDefault() + .getWorkingCopyManager(); + ICompilationUnit unit = manager.getWorkingCopy(getEditorInput()); + if (unit != null) { + try { + synchronized (unit) { + unit.reconcile(); + } + IJavaElement[] findings = unit.findElements(element); + if (findings != null && findings.length > 0) + return findings[0]; + } catch (JavaModelException x) { + PHPeclipsePlugin.log(x.getStatus()); + // nothing found, be tolerant and go on + } + } + return null; } - try { - super.performSave(overwrite, progressMonitor); - } finally { - if (p instanceof ICompilationUnitDocumentProvider) { - ICompilationUnitDocumentProvider cp = (ICompilationUnitDocumentProvider) p; - cp.setSavePolicy(null); - } + + /** + * Returns the offset of the given Java element. + */ + private int getOffset(IJavaElement element) { + if (element instanceof ISourceReference) { + ISourceReference sr = (ISourceReference) element; + try { + ISourceRange srcRange = sr.getSourceRange(); + if (srcRange != null) + return srcRange.getOffset(); + } catch (JavaModelException e) { + } + } + return -1; } - } - - /* - * @see AbstractTextEditor#doSaveAs - */ - public void doSaveAs() { - if (askIfNonWorkbenchEncodingIsOk()) { - super.doSaveAs(); + + /* + * @see AbstractTextEditor#restoreSelection() + */ + // protected void restoreSelection() { + // try { + // if (getSourceViewer() == null || fRememberedSelection == null) + // return; + // IJavaElement newElement = findElement(fRememberedElement); + // int newOffset = getOffset(newElement); + // int delta = (newOffset > -1 && fRememberedElementOffset > -1) ? newOffset + // - fRememberedElementOffset : 0; + // if (isValidSelection(delta + fRememberedSelection.getOffset(), + // fRememberedSelection.getLength())) + // selectAndReveal(delta + fRememberedSelection.getOffset(), + // fRememberedSelection.getLength()); + // } finally { + // fRememberedSelection = null; + // fRememberedElement = null; + // fRememberedElementOffset = -1; + // } + // } + /** + * Tells whether this is the active editor in the active page. + * + * @return true if this is the active editor in the active + * page + * @see IWorkbenchPage#getActiveEditor(); + */ + protected final boolean isActiveEditor() { + IWorkbenchWindow window = getSite().getWorkbenchWindow(); + IWorkbenchPage page = window.getActivePage(); + if (page == null) + return false; + IEditorPart activeEditor = page.getActiveEditor(); + return activeEditor != null && activeEditor.equals(this); } - } - - /** - * Asks the user if it is ok to store in non-workbench encoding. - * - * @return if the user wants to continue - */ - private boolean askIfNonWorkbenchEncodingIsOk() { - IDocumentProvider provider = getDocumentProvider(); - if (provider instanceof IStorageDocumentProvider) { - IEditorInput input = getEditorInput(); - IStorageDocumentProvider storageProvider = (IStorageDocumentProvider) provider; - String encoding = storageProvider.getEncoding(input); - String defaultEncoding = storageProvider.getDefaultEncoding(); - if (encoding != null && !encoding.equals(defaultEncoding)) { - Shell shell = getSite().getShell(); - String title = PHPEditorMessages.getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.title"); //$NON-NLS-1$ - String msg; - if (input != null) - msg = MessageFormat.format(PHPEditorMessages.getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message1"), - new String[] { input.getName(), encoding }); //$NON-NLS-1$ - else - msg = MessageFormat.format(PHPEditorMessages.getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message2"), - new String[] { encoding }); //$NON-NLS-1$ - return MessageDialog.openQuestion(shell, title, msg); - } + + /** + * Adds the given listener. Has no effect if an identical listener was not + * already registered. + * + * @param listener + * The reconcile listener to be added + * @since 3.0 + */ + final void addReconcileListener(IJavaReconcilingListener listener) { + synchronized (fReconcilingListeners) { + fReconcilingListeners.add(listener); + } } - return true; - } - - /* - * @see net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener#aboutToBeReconciled() - * @since 3.0 - */ - public void aboutToBeReconciled() { - - // Notify AST provider - // PHPeclipsePlugin.getDefault().getASTProvider().aboutToBeReconciled(getInputJavaElement()); - - // Notify listeners - Object[] listeners = fReconcilingListeners.getListeners(); - for (int i = 0, length = listeners.length; i < length; ++i) - ((IJavaReconcilingListener) listeners[i]).aboutToBeReconciled(); - } - - /* - * @see net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener#reconciled(CompilationUnit, boolean, - * IProgressMonitor) - * @since 3.0 - */ - public void reconciled(CompilationUnit ast, boolean forced, IProgressMonitor progressMonitor) { - - // Always notify AST provider - // PHPeclipsePlugin.getDefault().getASTProvider().reconciled(ast, getInputJavaElement()); - - // Notify listeners - // Object[] listeners = fReconcilingListeners.getListeners(); - // for (int i = 0, length= listeners.length; i < length; ++i) - // ((IJavaReconcilingListener)listeners[i]).reconciled(ast, forced, progressMonitor); - - // Update Java Outline page selection - if (!forced && !progressMonitor.isCanceled()) { - Shell shell = getSite().getShell(); - if (shell != null && !shell.isDisposed()) { - shell.getDisplay().asyncExec(new Runnable() { - public void run() { - selectionChanged(); - } - }); - } + + /** + * Removes the given listener. Has no effect if an identical listener was + * not already registered. + * + * @param listener + * the reconcile listener to be removed + * @since 3.0 + */ + final void removeReconcileListener(IJavaReconcilingListener listener) { + synchronized (fReconcilingListeners) { + fReconcilingListeners.remove(listener); + } } - } - - /** - * Returns the updated java element for the old java element. - */ - private IJavaElement findElement(IJavaElement element) { - if (element == null) - return null; - IWorkingCopyManager manager = PHPeclipsePlugin.getDefault().getWorkingCopyManager(); - ICompilationUnit unit = manager.getWorkingCopy(getEditorInput()); - if (unit != null) { - try { - synchronized (unit) { - unit.reconcile(); - } - IJavaElement[] findings = unit.findElements(element); - if (findings != null && findings.length > 0) - return findings[0]; - } catch (JavaModelException x) { - PHPeclipsePlugin.log(x.getStatus()); - // nothing found, be tolerant and go on - } + + protected void updateStateDependentActions() { + super.updateStateDependentActions(); + fGenerateActionGroup.editorStateChanged(); } - return null; - } - - /** - * Returns the offset of the given Java element. - */ - private int getOffset(IJavaElement element) { - if (element instanceof ISourceReference) { - ISourceReference sr = (ISourceReference) element; - try { - ISourceRange srcRange = sr.getSourceRange(); - if (srcRange != null) - return srcRange.getOffset(); - } catch (JavaModelException e) { - } + + /* + * @see AbstractTextEditor#rememberSelection() + */ + protected void rememberSelection() { + fRememberedSelection.remember(); } - return -1; - } - - /* - * @see AbstractTextEditor#restoreSelection() - */ - // protected void restoreSelection() { - // try { - // if (getSourceViewer() == null || fRememberedSelection == null) - // return; - // IJavaElement newElement = findElement(fRememberedElement); - // int newOffset = getOffset(newElement); - // int delta = (newOffset > -1 && fRememberedElementOffset > -1) ? newOffset - // - fRememberedElementOffset : 0; - // if (isValidSelection(delta + fRememberedSelection.getOffset(), - // fRememberedSelection.getLength())) - // selectAndReveal(delta + fRememberedSelection.getOffset(), - // fRememberedSelection.getLength()); - // } finally { - // fRememberedSelection = null; - // fRememberedElement = null; - // fRememberedElementOffset = -1; - // } - // } - /** - * Tells whether this is the active editor in the active page. - * - * @return true if this is the active editor in the active page - * @see IWorkbenchPage#getActiveEditor(); - */ - protected final boolean isActiveEditor() { - IWorkbenchWindow window = getSite().getWorkbenchWindow(); - IWorkbenchPage page = window.getActivePage(); - if (page == null) - return false; - IEditorPart activeEditor = page.getActiveEditor(); - return activeEditor != null && activeEditor.equals(this); - } - - /** - * Adds the given listener. Has no effect if an identical listener was not already registered. - * - * @param listener - * The reconcile listener to be added - * @since 3.0 - */ - final void addReconcileListener(IJavaReconcilingListener listener) { - synchronized (fReconcilingListeners) { - fReconcilingListeners.add(listener); + + /* + * @see AbstractTextEditor#restoreSelection() + */ + protected void restoreSelection() { + fRememberedSelection.restore(); } - } - - /** - * Removes the given listener. Has no effect if an identical listener was not already registered. - * - * @param listener - * the reconcile listener to be removed - * @since 3.0 - */ - final void removeReconcileListener(IJavaReconcilingListener listener) { - synchronized (fReconcilingListeners) { - fReconcilingListeners.remove(listener); + + /* + * @see AbstractTextEditor#canHandleMove(IEditorInput, IEditorInput) + */ + protected boolean canHandleMove(IEditorInput originalElement, + IEditorInput movedElement) { + + String oldExtension = ""; //$NON-NLS-1$ + if (originalElement instanceof IFileEditorInput) { + IFile file = ((IFileEditorInput) originalElement).getFile(); + if (file != null) { + String ext = file.getFileExtension(); + if (ext != null) + oldExtension = ext; + } + } + + String newExtension = ""; //$NON-NLS-1$ + if (movedElement instanceof IFileEditorInput) { + IFile file = ((IFileEditorInput) movedElement).getFile(); + if (file != null) + newExtension = file.getFileExtension(); + } + + return oldExtension.equals(newExtension); } - } - - protected void updateStateDependentActions() { - super.updateStateDependentActions(); - fGenerateActionGroup.editorStateChanged(); - } - - /* - * @see AbstractTextEditor#rememberSelection() - */ - protected void rememberSelection() { - fRememberedSelection.remember(); - } - - /* - * @see AbstractTextEditor#restoreSelection() - */ - protected void restoreSelection() { - fRememberedSelection.restore(); - } - - /* - * @see AbstractTextEditor#canHandleMove(IEditorInput, IEditorInput) - */ - protected boolean canHandleMove(IEditorInput originalElement, IEditorInput movedElement) { - - String oldExtension = ""; //$NON-NLS-1$ - if (originalElement instanceof IFileEditorInput) { - IFile file = ((IFileEditorInput) originalElement).getFile(); - if (file != null) { - String ext = file.getFileExtension(); - if (ext != null) - oldExtension = ext; - } + + /* + * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#isPrefQuickDiffAlwaysOn() + */ + protected boolean isPrefQuickDiffAlwaysOn() { + // reestablishes the behaviour from AbstractDecoratedTextEditor which + // was hacked by JavaEditor + // to disable the change bar for the class file (attached source) java + // editor. + IPreferenceStore store = getPreferenceStore(); + return store + .getBoolean(AbstractDecoratedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON); } - String newExtension = ""; //$NON-NLS-1$ - if (movedElement instanceof IFileEditorInput) { - IFile file = ((IFileEditorInput) movedElement).getFile(); - if (file != null) - newExtension = file.getFileExtension(); + /* + * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#getAdapter(java.lang.Class) + */ + public Object getAdapter(Class required) { + if (SmartBackspaceManager.class.equals(required)) { + if (getSourceViewer() instanceof JavaSourceViewer) { + return ((JavaSourceViewer) getSourceViewer()) + .getBackspaceManager(); + } + } + + return super.getAdapter(required); } - return oldExtension.equals(newExtension); - } - - /* - * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#isPrefQuickDiffAlwaysOn() - */ - protected boolean isPrefQuickDiffAlwaysOn() { - // reestablishes the behaviour from AbstractDecoratedTextEditor which was hacked by JavaEditor - // to disable the change bar for the class file (attached source) java editor. - IPreferenceStore store = getPreferenceStore(); - return store.getBoolean(AbstractDecoratedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON); - } - - /* - * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#getAdapter(java.lang.Class) - */ - public Object getAdapter(Class required) { - if (SmartBackspaceManager.class.equals(required)) { - if (getSourceViewer() instanceof JavaSourceViewer) { - return ((JavaSourceViewer) getSourceViewer()).getBackspaceManager(); - } + /** + * Returns the mutex for the reconciler. See + * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898 for a description of + * the problem. + *

                                                      + * TODO remove once the underlying problem is solved. + *

                                                      + * + * @return the lock reconcilers may use to synchronize on + */ + public Object getReconcilerLock() { + return fReconcilerLock; } - return super.getAdapter(required); - } - - /** - * Returns the mutex for the reconciler. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898 for a description of the problem. - *

                                                      - * TODO remove once the underlying problem is solved. - *

                                                      - * - * @return the lock reconcilers may use to synchronize on - */ - public Object getReconcilerLock() { - return fReconcilerLock; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.AbstractTextEditor#editorSaved() - */ - protected void editorSaved() { - super.editorSaved(); - ShowExternalPreviewAction a = ShowExternalPreviewAction.getInstance(); - if (a != null) { - a.refresh(ShowExternalPreviewAction.PHP_TYPE); + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.texteditor.AbstractTextEditor#editorSaved() + */ + protected void editorSaved() { + super.editorSaved(); + ShowExternalPreviewAction a = ShowExternalPreviewAction.getInstance(); + if (a != null) { + a.refresh(ShowExternalPreviewAction.PHP_TYPE); + } } - } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PaintManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PaintManager.java index 03b6594..9e880b4 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PaintManager.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PaintManager.java @@ -1,6 +1,5 @@ package net.sourceforge.phpeclipse.phpeditor; - /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. @@ -30,38 +29,37 @@ import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.widgets.Control; - -public final class PaintManager implements KeyListener, MouseListener, ISelectionChangedListener, ITextListener, ITextInputListener { - +public final class PaintManager implements KeyListener, MouseListener, + ISelectionChangedListener, ITextListener, ITextInputListener { static class PaintPositionUpdater extends DefaultPositionUpdater { - + /** * Creates the position updater. */ protected PaintPositionUpdater(String category) { super(category); } - + /** - * If an insertion happens at a position's offset, the - * position is extended rather than shifted. Also, if something is added - * right behind the end of the position, the position is extended rather - * than kept stable. + * If an insertion happens at a position's offset, the position is + * extended rather than shifted. Also, if something is added right + * behind the end of the position, the position is extended rather than + * kept stable. */ protected void adaptToInsert() { - - int myStart= fPosition.offset; - int myEnd= fPosition.offset + fPosition.length; - myEnd= Math.max(myStart, myEnd); - - int yoursStart= fOffset; - int yoursEnd= fOffset + fReplaceLength;// - 1; - yoursEnd= Math.max(yoursStart, yoursEnd); - + + int myStart = fPosition.offset; + int myEnd = fPosition.offset + fPosition.length; + myEnd = Math.max(myStart, myEnd); + + int yoursStart = fOffset; + int yoursEnd = fOffset + fReplaceLength;// - 1; + yoursEnd = Math.max(yoursStart, yoursEnd); + if (myEnd < yoursStart) return; - + if (myStart <= yoursStart) fPosition.length += fReplaceLength; else @@ -70,38 +68,40 @@ public final class PaintManager implements KeyListener, MouseListener, ISelectio }; static class PositionManager implements IPositionManager { - + private IDocument fDocument; + private IPositionUpdater fPositionUpdater; + private String fCategory; - + public PositionManager() { - fCategory= getClass().getName() + hashCode(); - fPositionUpdater= new PaintPositionUpdater(fCategory); + fCategory = getClass().getName() + hashCode(); + fPositionUpdater = new PaintPositionUpdater(fCategory); } public void install(IDocument document) { - fDocument= document; + fDocument = document; fDocument.addPositionCategory(fCategory); fDocument.addPositionUpdater(fPositionUpdater); } - + public void dispose() { uninstall(fDocument); } - + public void uninstall(IDocument document) { if (document == fDocument && document != null) { try { fDocument.removePositionUpdater(fPositionUpdater); - fDocument.removePositionCategory(fCategory); + fDocument.removePositionCategory(fCategory); } catch (BadPositionCategoryException x) { // should not happen } - fDocument= null; + fDocument = null; } } - + /* * @see IPositionManager#addManagedPosition(Position) */ @@ -114,7 +114,7 @@ public final class PaintManager implements KeyListener, MouseListener, ISelectio // should not happen } } - + /* * @see IPositionManager#removeManagedPosition(Position) */ @@ -126,19 +126,21 @@ public final class PaintManager implements KeyListener, MouseListener, ISelectio } } }; - - - private List fPainters= new ArrayList(2); + + private List fPainters = new ArrayList(2); + private PositionManager fManager; + private ISourceViewer fSourceViewer; - private boolean fTextChanged= false; - private boolean fAutoRepeat= false; - - + + private boolean fTextChanged = false; + + private boolean fAutoRepeat = false; + public PaintManager(ISourceViewer sourceViewer) { - fSourceViewer= sourceViewer; + fSourceViewer = sourceViewer; } - + public void addPainter(IPainter painter) { if (!fPainters.contains(painter)) { fPainters.add(painter); @@ -148,62 +150,62 @@ public final class PaintManager implements KeyListener, MouseListener, ISelectio painter.paint(IPainter.INTERNAL); } } - + public void removePainter(IPainter painter) { if (fPainters.remove(painter)) painter.setPositionManager(null); if (fPainters.size() == 0) dispose(); } - + private void install() { - - fManager= new PositionManager(); + + fManager = new PositionManager(); fManager.install(fSourceViewer.getDocument()); - + fSourceViewer.addTextInputListener(this); - - ISelectionProvider provider= fSourceViewer.getSelectionProvider(); + + ISelectionProvider provider = fSourceViewer.getSelectionProvider(); provider.addSelectionChangedListener(this); - + fSourceViewer.addTextListener(this); - - StyledText text= fSourceViewer.getTextWidget(); + + StyledText text = fSourceViewer.getTextWidget(); text.addKeyListener(this); text.addMouseListener(this); } - + public void dispose() { - + if (fManager != null) { fManager.dispose(); - fManager= null; + fManager = null; } - + for (Iterator e = fPainters.iterator(); e.hasNext();) - ((IPainter) e.next()).dispose(); + ((IPainter) e.next()).dispose(); fPainters.clear(); - + fSourceViewer.removeTextInputListener(this); - - ISelectionProvider provider= fSourceViewer.getSelectionProvider(); + + ISelectionProvider provider = fSourceViewer.getSelectionProvider(); if (provider != null) provider.removeSelectionChangedListener(this); - + fSourceViewer.removeTextListener(this); - - StyledText text= fSourceViewer.getTextWidget(); + + StyledText text = fSourceViewer.getTextWidget(); if (text != null && !text.isDisposed()) { text.removeKeyListener(this); text.removeMouseListener(this); } } - + private void paint(int reason) { for (Iterator e = fPainters.iterator(); e.hasNext();) ((IPainter) e.next()).paint(reason); } - + /* * @see KeyListener#keyPressed(KeyEvent) */ @@ -222,58 +224,60 @@ public final class PaintManager implements KeyListener, MouseListener, ISelectio */ public void mouseDoubleClick(MouseEvent e) { } - + /* * @see MouseListener#mouseDown(MouseEvent) */ public void mouseDown(MouseEvent e) { paint(IPainter.MOUSE_BUTTON); } - + /* * @see MouseListener#mouseUp(MouseEvent) */ public void mouseUp(MouseEvent e) { } - + /* * @see ISelectionChangedListener#selectionChanged(SelectionChangedEvent) */ public void selectionChanged(SelectionChangedEvent event) { paint(IPainter.SELECTION); } - + /* * @see ITextListener#textChanged(TextEvent) */ public void textChanged(TextEvent event) { - + if (!event.getViewerRedrawState()) return; - - fTextChanged= true; - Control control= fSourceViewer.getTextWidget(); + + fTextChanged = true; + Control control = fSourceViewer.getTextWidget(); if (control != null) { control.getDisplay().asyncExec(new Runnable() { public void run() { - if (fTextChanged && fSourceViewer != null) + if (fTextChanged && fSourceViewer != null) paint(IPainter.TEXT_CHANGE); } }); } } - + /* - * @see ITextInputListener#inputDocumentAboutToBeChanged(IDocument, IDocument) + * @see ITextInputListener#inputDocumentAboutToBeChanged(IDocument, + * IDocument) */ - public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) { + public void inputDocumentAboutToBeChanged(IDocument oldInput, + IDocument newInput) { if (oldInput != null) { for (Iterator e = fPainters.iterator(); e.hasNext();) - ((IPainter) e.next()).deactivate(false); + ((IPainter) e.next()).deactivate(false); fManager.uninstall(oldInput); } } - + /* * @see ITextInputListener#inputDocumentChanged(IDocument, IDocument) */ @@ -284,4 +288,3 @@ public final class PaintManager implements KeyListener, MouseListener, ISelectio } } } - diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PartiallySynchronizedDocument.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PartiallySynchronizedDocument.java index f0e78b7..7dfb207 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PartiallySynchronizedDocument.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PartiallySynchronizedDocument.java @@ -1,13 +1,13 @@ /********************************************************************** -Copyright (c) 2000, 2003 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - IBM Corporation - Initial implementation -**********************************************************************/ + Copyright (c) 2000, 2003 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + **********************************************************************/ package net.sourceforge.phpeclipse.phpeditor; import org.eclipse.jface.text.BadLocationException; @@ -16,36 +16,37 @@ import org.eclipse.jface.text.Document; import org.eclipse.jface.text.ISynchronizable; import org.eclipse.jface.text.Position; - /** * Document that can also be used by a background reconciler. */ -public class PartiallySynchronizedDocument extends Document implements ISynchronizable { - - private final Object fInternalLockObject= new Object(); - private Object fLockObject; - - /* - * @see org.eclipse.jface.text.ISynchronizable#setLockObject(java.lang.Object) - */ - public void setLockObject(Object lockObject) { - fLockObject= lockObject; - } - - /* - * @see org.eclipse.jface.text.ISynchronizable#getLockObject() - */ - public Object getLockObject() { - return fLockObject == null ? fInternalLockObject : fLockObject; - } - +public class PartiallySynchronizedDocument extends Document implements + ISynchronizable { + + private final Object fInternalLockObject = new Object(); + + private Object fLockObject; + + /* + * @see org.eclipse.jface.text.ISynchronizable#setLockObject(java.lang.Object) + */ + public void setLockObject(Object lockObject) { + fLockObject = lockObject; + } + + /* + * @see org.eclipse.jface.text.ISynchronizable#getLockObject() + */ + public Object getLockObject() { + return fLockObject == null ? fInternalLockObject : fLockObject; + } + /* * @see IDocumentExtension#startSequentialRewrite(boolean) */ public void startSequentialRewrite(boolean normalized) { - synchronized (getLockObject()) { - super.startSequentialRewrite(normalized); - } + synchronized (getLockObject()) { + super.startSequentialRewrite(normalized); + } } /* @@ -53,79 +54,85 @@ public class PartiallySynchronizedDocument extends Document implements ISynchron */ public void stopSequentialRewrite() { synchronized (getLockObject()) { - super.stopSequentialRewrite(); - } - } - + super.stopSequentialRewrite(); + } + } + /* * @see IDocument#get() */ public String get() { synchronized (getLockObject()) { - return super.get(); - } - } - + return super.get(); + } + } + /* * @see IDocument#get(int, int) */ public String get(int offset, int length) throws BadLocationException { synchronized (getLockObject()) { - return super.get(offset, length); - } + return super.get(offset, length); + } } - + /* * @see IDocument#getChar(int) */ public char getChar(int offset) throws BadLocationException { synchronized (getLockObject()) { - return super.getChar(offset); - } + return super.getChar(offset); + } } - + /* * @see IDocument#replace(int, int, String) */ - public void replace(int offset, int length, String text) throws BadLocationException { + public void replace(int offset, int length, String text) + throws BadLocationException { synchronized (getLockObject()) { - super.replace(offset, length, text); - } + super.replace(offset, length, text); + } } - + /* * @see IDocument#set(String) */ public void set(String text) { synchronized (getLockObject()) { - super.set(text); - } + super.set(text); + } } - + /* - * @see org.eclipse.jface.text.AbstractDocument#addPosition(java.lang.String, org.eclipse.jface.text.Position) + * @see org.eclipse.jface.text.AbstractDocument#addPosition(java.lang.String, + * org.eclipse.jface.text.Position) */ - public void addPosition(String category, Position position) throws BadLocationException, BadPositionCategoryException { + public void addPosition(String category, Position position) + throws BadLocationException, BadPositionCategoryException { synchronized (getLockObject()) { - super.addPosition(category, position); - } + super.addPosition(category, position); + } } - + /* - * @see org.eclipse.jface.text.AbstractDocument#removePosition(java.lang.String, org.eclipse.jface.text.Position) + * @see org.eclipse.jface.text.AbstractDocument#removePosition(java.lang.String, + * org.eclipse.jface.text.Position) */ - public void removePosition(String category, Position position) throws BadPositionCategoryException { + public void removePosition(String category, Position position) + throws BadPositionCategoryException { synchronized (getLockObject()) { - super.removePosition(category, position); - } + super.removePosition(category, position); + } } - + /* * @see org.eclipse.jface.text.AbstractDocument#getPositions(java.lang.String) */ - public Position[] getPositions(String category) throws BadPositionCategoryException { + public Position[] getPositions(String category) + throws BadPositionCategoryException { synchronized (getLockObject()) { - return super.getPositions(category); - } + return super.getPositions(category); + } } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PresentationAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PresentationAction.java index 1cec0bd..a2ad6dd 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PresentationAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PresentationAction.java @@ -1,53 +1,54 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ package net.sourceforge.phpeclipse.phpeditor; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.TextEditorAction; - /** - * A toolbar action which toggles the presentation model of the - * connected text editor. The editor shows either the highlight range - * only or always the whole document. + * A toolbar action which toggles the presentation model of the connected text + * editor. The editor shows either the highlight range only or always the whole + * document. */ public class PresentationAction extends TextEditorAction { - /** - * Constructs and updates the action. - */ - public PresentationAction() { - super(PHPEditorMessages.getResourceBundle(), "TogglePresentation.", null); //$NON-NLS-1$ - update(); - } - - /* (non-Javadoc) - * Method declared on IAction - */ - public void run() { - - ITextEditor editor = getTextEditor(); - - editor.resetHighlightRange(); - boolean show = editor.showsHighlightRangeOnly(); - setChecked(!show); - editor.showHighlightRangeOnly(!show); - } - - /* (non-Javadoc) - * Method declared on TextEditorAction - */ - public void update() { - setChecked(getTextEditor() != null && getTextEditor().showsHighlightRangeOnly()); - setEnabled(true); - } + /** + * Constructs and updates the action. + */ + public PresentationAction() { + super(PHPEditorMessages.getResourceBundle(), + "TogglePresentation.", null); //$NON-NLS-1$ + update(); + } + + /* + * (non-Javadoc) Method declared on IAction + */ + public void run() { + + ITextEditor editor = getTextEditor(); + + editor.resetHighlightRange(); + boolean show = editor.showsHighlightRangeOnly(); + setChecked(!show); + editor.showHighlightRangeOnly(!show); + } + + /* + * (non-Javadoc) Method declared on TextEditorAction + */ + public void update() { + setChecked(getTextEditor() != null + && getTextEditor().showsHighlightRangeOnly()); + setEnabled(true); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PrintMarginPainter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PrintMarginPainter.java index f722bbc..c941e15 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PrintMarginPainter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PrintMarginPainter.java @@ -14,45 +14,46 @@ import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Rectangle; +public class PrintMarginPainter implements IPainter, PaintListener { + private StyledText fTextWidget; -public class PrintMarginPainter implements IPainter, PaintListener { - + private int fMarginWidth = 80; - private StyledText fTextWidget; - - private int fMarginWidth= 80; private Color fColor; - private int fLineStyle= SWT.LINE_SOLID; - private int fLineWidth= 1; - - private int fCachedWidgetX= -1; - private boolean fIsActive= false; - + + private int fLineStyle = SWT.LINE_SOLID; + + private int fLineWidth = 1; + + private int fCachedWidgetX = -1; + + private boolean fIsActive = false; + public PrintMarginPainter(ISourceViewer sourceViewer) { - fTextWidget= sourceViewer.getTextWidget(); + fTextWidget = sourceViewer.getTextWidget(); } - + public void setMarginRulerColumn(int width) { - fMarginWidth= width; + fMarginWidth = width; intialize(); } - + public void setMarginRulerStyle(int lineStyle) { - fLineStyle= lineStyle; + fLineStyle = lineStyle; } - + public void setMarginRulerWidth(int lineWidth) { - fLineWidth= lineWidth; + fLineWidth = lineWidth; } - + /** * Must be called before paint is called the first time. */ public void setMarginRulerColor(Color color) { - fColor= color; + fColor = color; } - + /** * Must be called explicitly when font of text widget changes. */ @@ -60,32 +61,32 @@ public class PrintMarginPainter implements IPainter, PaintListener { computeWidgetX(); fTextWidget.redraw(); } - + private void computeWidgetX() { - GC gc= new GC(fTextWidget); - int pixels= gc.getFontMetrics().getAverageCharWidth(); + GC gc = new GC(fTextWidget); + int pixels = gc.getFontMetrics().getAverageCharWidth(); gc.dispose(); - - fCachedWidgetX= pixels * fMarginWidth; + + fCachedWidgetX = pixels * fMarginWidth; } - + /* * @see IPainter#deactivate(boolean) */ public void deactivate(boolean redraw) { if (fIsActive) { - fIsActive= false; + fIsActive = false; fTextWidget.removePaintListener(this); if (redraw) fTextWidget.redraw(); - } + } } /* * @see IPainter#dispose() */ public void dispose() { - fTextWidget= null; + fTextWidget = null; } /* @@ -93,7 +94,7 @@ public class PrintMarginPainter implements IPainter, PaintListener { */ public void paint(int reason) { if (!fIsActive) { - fIsActive= true; + fIsActive = true; fTextWidget.addPaintListener(this); if (fCachedWidgetX == -1) computeWidgetX(); @@ -106,15 +107,15 @@ public class PrintMarginPainter implements IPainter, PaintListener { */ public void setPositionManager(IPositionManager manager) { } - + /* * @see PaintListener#paintControl(PaintEvent) */ public void paintControl(PaintEvent e) { if (fTextWidget != null) { - int x= fCachedWidgetX - fTextWidget.getHorizontalPixel(); + int x = fCachedWidgetX - fTextWidget.getHorizontalPixel(); if (x >= 0) { - Rectangle area= fTextWidget.getClientArea(); + Rectangle area = fTextWidget.getClientArea(); e.gc.setForeground(fColor); e.gc.setLineStyle(fLineStyle); e.gc.setLineWidth(fLineWidth); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ProblemAnnotationIterator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ProblemAnnotationIterator.java index 8a8c31a..7895116 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ProblemAnnotationIterator.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ProblemAnnotationIterator.java @@ -5,46 +5,47 @@ package net.sourceforge.phpeclipse.phpeditor; * All Rights Reserved. */ - import java.util.Iterator; import org.eclipse.jface.text.source.IAnnotationModel; - /** * Filters problems based on their types. */ public class ProblemAnnotationIterator implements Iterator { - + private Iterator fIterator; + private IProblemAnnotation fNext; + private boolean fSkipIrrelevants; - - public ProblemAnnotationIterator(IAnnotationModel model, boolean skipIrrelevants) { - fIterator= model.getAnnotationIterator(); - fSkipIrrelevants= skipIrrelevants; + + public ProblemAnnotationIterator(IAnnotationModel model, + boolean skipIrrelevants) { + fIterator = model.getAnnotationIterator(); + fSkipIrrelevants = skipIrrelevants; skip(); } - + private void skip() { while (fIterator.hasNext()) { - Object next= fIterator.next(); + Object next = fIterator.next(); if (next instanceof IProblemAnnotation) { - IProblemAnnotation a= (IProblemAnnotation) next; + IProblemAnnotation a = (IProblemAnnotation) next; if (fSkipIrrelevants) { if (a.isRelevant()) { - fNext= a; + fNext = a; return; } } else { - fNext= a; + fNext = a; return; } } } - fNext= null; + fNext = null; } - + /* * @see Iterator#hasNext() */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ProblemPainter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ProblemPainter.java index 15cef95..d02d7cb 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ProblemPainter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ProblemPainter.java @@ -1,17 +1,16 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html -Contributors: - IBM Corporation - Initial implementation -**********************************************************************/ + Contributors: + IBM Corporation - Initial implementation + **********************************************************************/ package net.sourceforge.phpeclipse.phpeditor; - import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -45,33 +44,41 @@ import org.eclipse.ui.texteditor.ITextEditor; /** * Highlights the temporary problems. */ -public class ProblemPainter implements IPainter, PaintListener, IAnnotationModelListener { +public class ProblemPainter implements IPainter, PaintListener, + IAnnotationModelListener { private static class ProblemPosition { Position fPosition; + Color fColor; + boolean fMultiLine; }; - private boolean fIsActive= false; - private boolean fIsPainting= false; - private boolean fIsSettingModel= false; + private boolean fIsActive = false; + + private boolean fIsPainting = false; + + private boolean fIsSettingModel = false; private ITextEditor fTextEditor; + private ISourceViewer fSourceViewer; + private StyledText fTextWidget; + private IAnnotationModel fModel; - private List fProblemPositions= new ArrayList(); - private Map fColorTable= new HashMap(); - private Set fAnnotationSet= new HashSet(); + private List fProblemPositions = new ArrayList(); + private Map fColorTable = new HashMap(); + private Set fAnnotationSet = new HashSet(); public ProblemPainter(ITextEditor textEditor, ISourceViewer sourceViewer) { - fTextEditor= textEditor; - fSourceViewer= sourceViewer; - fTextWidget= sourceViewer.getTextWidget(); + fTextEditor = textEditor; + fSourceViewer = sourceViewer; + fTextWidget = sourceViewer.getTextWidget(); } private boolean hasProblems() { @@ -80,7 +87,7 @@ public class ProblemPainter implements IPainter, PaintListener, IAnnotationModel private void enablePainting() { if (!fIsPainting && hasProblems()) { - fIsPainting= true; + fIsPainting = true; fTextWidget.addPaintListener(this); handleDrawRequest(null); } @@ -88,7 +95,7 @@ public class ProblemPainter implements IPainter, PaintListener, IAnnotationModel private void disablePainting(boolean redraw) { if (fIsPainting) { - fIsPainting= false; + fIsPainting = false; fTextWidget.removePaintListener(this); if (redraw && hasProblems()) handleDrawRequest(null); @@ -99,13 +106,13 @@ public class ProblemPainter implements IPainter, PaintListener, IAnnotationModel if (fModel != model) { if (fModel != null) fModel.removeAnnotationModelListener(this); - fModel= model; + fModel = model; if (fModel != null) { try { - fIsSettingModel= true; + fIsSettingModel = true; fModel.addAnnotationModelListener(this); } finally { - fIsSettingModel= false; + fIsSettingModel = false; } } } @@ -116,21 +123,21 @@ public class ProblemPainter implements IPainter, PaintListener, IAnnotationModel fProblemPositions.clear(); if (fModel != null) { - Iterator e= new ProblemAnnotationIterator(fModel, true); + Iterator e = new ProblemAnnotationIterator(fModel, true); while (e.hasNext()) { - IProblemAnnotation pa= (IProblemAnnotation) e.next(); - Annotation a= (Annotation) pa; + IProblemAnnotation pa = (IProblemAnnotation) e.next(); + Annotation a = (Annotation) pa; - Color color= null; - AnnotationType type= pa.getAnnotationType(); + Color color = null; + AnnotationType type = pa.getAnnotationType(); if (fAnnotationSet.contains(type)) - color= (Color) fColorTable.get(type); + color = (Color) fColorTable.get(type); if (color != null) { - ProblemPosition pp= new ProblemPosition(); - pp.fPosition= fModel.getPosition(a); - pp.fColor= color; - pp.fMultiLine= true; + ProblemPosition pp = new ProblemPosition(); + pp.fPosition = fModel.getPosition(a); + pp.fColor = color; + pp.fMultiLine = true; fProblemPositions.add(pp); } } @@ -153,11 +160,12 @@ public class ProblemPainter implements IPainter, PaintListener, IAnnotationModel // inside the ui thread -> no need for posting updatePainting(); } else { - Display d= fTextWidget.getDisplay(); + Display d = fTextWidget.getDisplay(); if (d != null) { d.asyncExec(new Runnable() { public void run() { - if (fTextWidget != null && !fTextWidget.isDisposed()) + if (fTextWidget != null + && !fTextWidget.isDisposed()) updatePainting(); } }); @@ -191,29 +199,29 @@ public class ProblemPainter implements IPainter, PaintListener, IAnnotationModel if (fColorTable != null) fColorTable.clear(); - fColorTable= null; + fColorTable = null; if (fAnnotationSet != null) fAnnotationSet.clear(); - fAnnotationSet= null; + fAnnotationSet = null; - fTextWidget= null; - fModel= null; - fProblemPositions= null; + fTextWidget = null; + fModel = null; + fProblemPositions = null; } /* - * Returns the document offset of the upper left corner of the widgets viewport, - * possibly including partially visible lines. + * Returns the document offset of the upper left corner of the widgets + * viewport, possibly including partially visible lines. */ private int getInclusiveTopIndexStartOffset() { if (fTextWidget != null && !fTextWidget.isDisposed()) { - int top= fSourceViewer.getTopIndex(); + int top = fSourceViewer.getTopIndex(); if ((fTextWidget.getTopPixel() % fTextWidget.getLineHeight()) != 0) top--; try { - IDocument document= fSourceViewer.getDocument(); + IDocument document = fSourceViewer.getDocument(); return document.getLineOffset(top); } catch (BadLocationException ex) { } @@ -232,39 +240,47 @@ public class ProblemPainter implements IPainter, PaintListener, IAnnotationModel private void handleDrawRequest(GC gc) { - int vOffset= getInclusiveTopIndexStartOffset(); + int vOffset = getInclusiveTopIndexStartOffset(); // http://bugs.eclipse.org/bugs/show_bug.cgi?id=17147 - int vLength= fSourceViewer.getBottomIndexEndOffset() + 1; + int vLength = fSourceViewer.getBottomIndexEndOffset() + 1; for (Iterator e = fProblemPositions.iterator(); e.hasNext();) { ProblemPosition pp = (ProblemPosition) e.next(); - Position p= pp.fPosition; + Position p = pp.fPosition; if (p.overlapsWith(vOffset, vLength)) { if (!pp.fMultiLine) { - IRegion widgetRange= getWidgetRange(p); + IRegion widgetRange = getWidgetRange(p); if (widgetRange != null) - draw(gc, widgetRange.getOffset(), widgetRange.getLength(), pp.fColor); + draw(gc, widgetRange.getOffset(), widgetRange + .getLength(), pp.fColor); } else { - IDocument document= fSourceViewer.getDocument(); + IDocument document = fSourceViewer.getDocument(); try { - int startLine= document.getLineOfOffset(p.getOffset()); - int lastInclusive= Math.max(p.getOffset(), p.getOffset() + p.getLength() - 1); - int endLine= document.getLineOfOffset(lastInclusive); - - for (int i= startLine; i <= endLine; i++) { - IRegion line= document.getLineInformation(i); - int paintStart= Math.max(line.getOffset(), p.getOffset()); - int paintEnd= Math.min(line.getOffset() + line.getLength(), p.getOffset() + p.getLength()); + int startLine = document.getLineOfOffset(p.getOffset()); + int lastInclusive = Math.max(p.getOffset(), p + .getOffset() + + p.getLength() - 1); + int endLine = document.getLineOfOffset(lastInclusive); + + for (int i = startLine; i <= endLine; i++) { + IRegion line = document.getLineInformation(i); + int paintStart = Math.max(line.getOffset(), p + .getOffset()); + int paintEnd = Math.min(line.getOffset() + + line.getLength(), p.getOffset() + + p.getLength()); if (paintEnd > paintStart) { // otherwise inside a line delimiter - IRegion widgetRange= getWidgetRange(new Position(paintStart, paintEnd - paintStart)); + IRegion widgetRange = getWidgetRange(new Position( + paintStart, paintEnd - paintStart)); if (widgetRange != null) - draw(gc, widgetRange.getOffset(), widgetRange.getLength(), pp.fColor); + draw(gc, widgetRange.getOffset(), + widgetRange.getLength(), pp.fColor); } } @@ -277,18 +293,20 @@ public class ProblemPainter implements IPainter, PaintListener, IAnnotationModel private IRegion getWidgetRange(Position p) { if (fSourceViewer instanceof ITextViewerExtension5) { - ITextViewerExtension5 extension= (ITextViewerExtension5) fSourceViewer; - return extension.modelRange2WidgetRange(new Region(p.getOffset(), p.getLength())); + ITextViewerExtension5 extension = (ITextViewerExtension5) fSourceViewer; + return extension.modelRange2WidgetRange(new Region(p.getOffset(), p + .getLength())); } else { - IRegion region= fSourceViewer.getVisibleRegion(); - int offset= region.getOffset(); - int length= region.getLength(); + IRegion region = fSourceViewer.getVisibleRegion(); + int offset = region.getOffset(); + int length = region.getLength(); - if (p.overlapsWith(offset , length)) { - int p1= Math.max(offset, p.getOffset()); - int p2= Math.min(offset + length, p.getOffset() + p.getLength()); + if (p.overlapsWith(offset, length)) { + int p1 = Math.max(offset, p.getOffset()); + int p2 = Math.min(offset + length, p.getOffset() + + p.getLength()); return new Region(p1 - offset, p2 - p1); } } @@ -298,42 +316,42 @@ public class ProblemPainter implements IPainter, PaintListener, IAnnotationModel private int[] computePolyline(Point left, Point right, int height) { - final int WIDTH= 4; // must be even - final int HEIGHT= 2; // can be any number -// final int MINPEEKS= 2; // minimal number of peeks + final int WIDTH = 4; // must be even + final int HEIGHT = 2; // can be any number + // final int MINPEEKS= 2; // minimal number of peeks - int peeks= (right.x - left.x) / WIDTH; -// if (peeks < MINPEEKS) { -// int missing= (MINPEEKS - peeks) * WIDTH; -// left.x= Math.max(0, left.x - missing/2); -// peeks= MINPEEKS; -// } + int peeks = (right.x - left.x) / WIDTH; + // if (peeks < MINPEEKS) { + // int missing= (MINPEEKS - peeks) * WIDTH; + // left.x= Math.max(0, left.x - missing/2); + // peeks= MINPEEKS; + // } - int leftX= left.x; + int leftX = left.x; // compute (number of point) * 2 - int length= ((2 * peeks) + 1) * 2; + int length = ((2 * peeks) + 1) * 2; if (length < 0) return new int[0]; - int[] coordinates= new int[length]; + int[] coordinates = new int[length]; // cache peeks' y-coordinates - int bottom= left.y + height - 1; - int top= bottom - HEIGHT; + int bottom = left.y + height - 1; + int top = bottom - HEIGHT; // populate array with peek coordinates - for (int i= 0; i < peeks; i++) { - int index= 4 * i; - coordinates[index]= leftX + (WIDTH * i); - coordinates[index+1]= bottom; - coordinates[index+2]= coordinates[index] + WIDTH/2; - coordinates[index+3]= top; + for (int i = 0; i < peeks; i++) { + int index = 4 * i; + coordinates[index] = leftX + (WIDTH * i); + coordinates[index + 1] = bottom; + coordinates[index + 2] = coordinates[index] + WIDTH / 2; + coordinates[index + 3] = top; } // the last down flank is missing - coordinates[length-2]= left.x + (WIDTH * peeks); - coordinates[length-1]= bottom; + coordinates[length - 2] = left.x + (WIDTH * peeks); + coordinates[length - 1] = bottom; return coordinates; } @@ -341,11 +359,12 @@ public class ProblemPainter implements IPainter, PaintListener, IAnnotationModel private void draw(GC gc, int offset, int length, Color color) { if (gc != null) { - Point left= fTextWidget.getLocationAtOffset(offset); - Point right= fTextWidget.getLocationAtOffset(offset + length); + Point left = fTextWidget.getLocationAtOffset(offset); + Point right = fTextWidget.getLocationAtOffset(offset + length); gc.setForeground(color); - int[] polyline= computePolyline(left, right, gc.getFontMetrics().getHeight()); + int[] polyline = computePolyline(left, right, gc.getFontMetrics() + .getHeight()); gc.drawPolyline(polyline); } else { @@ -358,7 +377,7 @@ public class ProblemPainter implements IPainter, PaintListener, IAnnotationModel */ public void deactivate(boolean redraw) { if (fIsActive) { - fIsActive= false; + fIsActive = false; disablePainting(redraw); setModel(null); catchupWithModel(); @@ -370,8 +389,9 @@ public class ProblemPainter implements IPainter, PaintListener, IAnnotationModel */ public void paint(int reason) { if (!fIsActive) { - fIsActive= true; - IDocumentProvider provider= PHPeclipsePlugin.getDefault().getCompilationUnitDocumentProvider(); + fIsActive = true; + IDocumentProvider provider = PHPeclipsePlugin.getDefault() + .getCompilationUnitDocumentProvider(); setModel(provider.getAnnotationModel(fTextEditor.getEditorInput())); } else if (CONFIGURATION == reason || INTERNAL == reason) updatePainting(); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/SmartyDocumentSetupParticipant.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/SmartyDocumentSetupParticipant.java index 7bd6ceb..db7dede 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/SmartyDocumentSetupParticipant.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/SmartyDocumentSetupParticipant.java @@ -1,13 +1,13 @@ /********************************************************************** -Copyright (c) 2000, 2003 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html + Copyright (c) 2000, 2003 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html -Contributors: - IBM Corporation - Initial implementation -**********************************************************************/ + Contributors: + IBM Corporation - Initial implementation + **********************************************************************/ package net.sourceforge.phpeclipse.phpeditor; import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; @@ -20,16 +20,19 @@ import org.eclipse.jface.text.IDocument; /** * The document setup participant for PHPDT. */ -public class SmartyDocumentSetupParticipant implements IDocumentSetupParticipant { +public class SmartyDocumentSetupParticipant implements + IDocumentSetupParticipant { public SmartyDocumentSetupParticipant() { } - + /* * @see org.eclipse.core.filebuffers.IDocumentSetupParticipant#setup(org.eclipse.jface.text.IDocument) */ public void setup(IDocument document) { - JavaTextTools tools= PHPeclipsePlugin.getDefault().getJavaTextTools(); - tools.setupSmartyDocumentPartitioner(document, IPHPPartitions.PHP_PARTITIONING, null); //IPHPPartitions.PHP_PARTITIONING, null); + JavaTextTools tools = PHPeclipsePlugin.getDefault().getJavaTextTools(); + tools.setupSmartyDocumentPartitioner(document, + IPHPPartitions.PHP_PARTITIONING, null); // IPHPPartitions.PHP_PARTITIONING, + // null); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ToggleCommentAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ToggleCommentAction.java index 506df17..ada76ed 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ToggleCommentAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ToggleCommentAction.java @@ -35,226 +35,263 @@ import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.ResourceAction; import org.eclipse.ui.texteditor.TextEditorAction; - - /** * An action which toggles comment prefixes on the selected lines. * * @since 3.0 */ public final class ToggleCommentAction extends TextEditorAction { - + /** The text operation target */ private ITextOperationTarget fOperationTarget; + /** The document partitioning */ private String fDocumentPartitioning; + /** The comment prefixes */ private Map fPrefixesMap; - + /** * Creates and initializes the action for the given text editor. The action * configures its visual representation from the given resource bundle. - * - * @param bundle the resource bundle - * @param prefix a prefix to be prepended to the various resource keys - * (described in ResourceAction constructor), or - * null if none - * @param editor the text editor + * + * @param bundle + * the resource bundle + * @param prefix + * a prefix to be prepended to the various resource keys + * (described in ResourceAction constructor), or + * null if none + * @param editor + * the text editor * @see ResourceAction#ResourceAction(ResourceBundle, String, int) */ - public ToggleCommentAction(ResourceBundle bundle, String prefix, ITextEditor editor) { + public ToggleCommentAction(ResourceBundle bundle, String prefix, + ITextEditor editor) { super(bundle, prefix, editor); } - + /** - * Implementation of the IAction prototype. Checks if the selected - * lines are all commented or not and uncomments/comments them respectively. + * Implementation of the IAction prototype. Checks if the + * selected lines are all commented or not and uncomments/comments them + * respectively. */ public void run() { - if (fOperationTarget == null || fDocumentPartitioning == null || fPrefixesMap == null) + if (fOperationTarget == null || fDocumentPartitioning == null + || fPrefixesMap == null) return; - - ITextEditor editor= getTextEditor(); + + ITextEditor editor = getTextEditor(); if (editor == null) return; if (!validateEditorInputState()) return; - + final int operationCode; if (isSelectionCommented(editor.getSelectionProvider().getSelection())) - operationCode= ITextOperationTarget.STRIP_PREFIX; + operationCode = ITextOperationTarget.STRIP_PREFIX; else - operationCode= ITextOperationTarget.PREFIX; - - Shell shell= editor.getSite().getShell(); + operationCode = ITextOperationTarget.PREFIX; + + Shell shell = editor.getSite().getShell(); if (!fOperationTarget.canDoOperation(operationCode)) { if (shell != null) - MessageDialog.openError(shell, PHPEditorMessages.getString("ToggleComment.error.title"), PHPEditorMessages.getString("ToggleComment.error.message")); //$NON-NLS-1$ //$NON-NLS-2$ + MessageDialog + .openError( + shell, + PHPEditorMessages + .getString("ToggleComment.error.title"), PHPEditorMessages.getString("ToggleComment.error.message")); //$NON-NLS-1$ //$NON-NLS-2$ return; } - - Display display= null; - if (shell != null && !shell.isDisposed()) - display= shell.getDisplay(); - + + Display display = null; + if (shell != null && !shell.isDisposed()) + display = shell.getDisplay(); + BusyIndicator.showWhile(display, new Runnable() { public void run() { fOperationTarget.doOperation(operationCode); } }); } - + /** * Is the given selection single-line commented? - * - * @param selection Selection to check + * + * @param selection + * Selection to check * @return true iff all selected lines are commented */ private boolean isSelectionCommented(ISelection selection) { if (!(selection instanceof ITextSelection)) return false; - - ITextSelection textSelection= (ITextSelection) selection; + + ITextSelection textSelection = (ITextSelection) selection; if (textSelection.getStartLine() < 0 || textSelection.getEndLine() < 0) return false; - - IDocument document= getTextEditor().getDocumentProvider().getDocument(getTextEditor().getEditorInput()); - + + IDocument document = getTextEditor().getDocumentProvider().getDocument( + getTextEditor().getEditorInput()); + try { - - IRegion block= getTextBlockFromSelection(textSelection, document); - ITypedRegion[] regions= TextUtilities.computePartitioning(document, fDocumentPartitioning, block.getOffset(), block.getLength(), false); - int lineCount= 0; - int[] lines= new int[regions.length * 2]; // [startline, endline, startline, endline, ...] - for (int i= 0, j= 0; i < regions.length; i++, j+= 2) { + IRegion block = getTextBlockFromSelection(textSelection, document); + ITypedRegion[] regions = TextUtilities.computePartitioning( + document, fDocumentPartitioning, block.getOffset(), block + .getLength(), false); + + int lineCount = 0; + int[] lines = new int[regions.length * 2]; // [startline, endline, + // startline, endline, + // ...] + for (int i = 0, j = 0; i < regions.length; i++, j += 2) { // start line of region - lines[j]= getFirstCompleteLineOfRegion(regions[i], document); + lines[j] = getFirstCompleteLineOfRegion(regions[i], document); // end line of region - int length= regions[i].getLength(); - int offset= regions[i].getOffset() + length; + int length = regions[i].getLength(); + int offset = regions[i].getOffset() + length; if (length > 0) offset--; - lines[j + 1]= (lines[j] == -1 ? -1 : document.getLineOfOffset(offset)); + lines[j + 1] = (lines[j] == -1 ? -1 : document + .getLineOfOffset(offset)); lineCount += lines[j + 1] - lines[j] + 1; } // Perform the check - for (int i= 0, j= 0; i < regions.length; i++, j += 2) { - String[] prefixes= (String[]) fPrefixesMap.get(regions[i].getType()); - if (prefixes != null && prefixes.length > 0 && lines[j] >= 0 && lines[j + 1] >= 0) - if (!isBlockCommented(lines[j], lines[j + 1], prefixes, document)) + for (int i = 0, j = 0; i < regions.length; i++, j += 2) { + String[] prefixes = (String[]) fPrefixesMap.get(regions[i] + .getType()); + if (prefixes != null && prefixes.length > 0 && lines[j] >= 0 + && lines[j + 1] >= 0) + if (!isBlockCommented(lines[j], lines[j + 1], prefixes, + document)) return false; } - + return true; - + } catch (BadLocationException x) { // should not happen PHPeclipsePlugin.log(x); } - + return false; } /** - * Creates a region describing the text block (something that starts at - * the beginning of a line) completely containing the current selection. + * Creates a region describing the text block (something that starts at the + * beginning of a line) completely containing the current selection. * - * @param selection The selection to use - * @param document The document - * @return the region describing the text block comprising the given selection + * @param selection + * The selection to use + * @param document + * The document + * @return the region describing the text block comprising the given + * selection */ - private IRegion getTextBlockFromSelection(ITextSelection selection, IDocument document) { - + private IRegion getTextBlockFromSelection(ITextSelection selection, + IDocument document) { + try { - IRegion line= document.getLineInformationOfOffset(selection.getOffset()); - int length= selection.getLength() == 0 ? line.getLength() : selection.getLength() + (selection.getOffset() - line.getOffset()); + IRegion line = document.getLineInformationOfOffset(selection + .getOffset()); + int length = selection.getLength() == 0 ? line.getLength() + : selection.getLength() + + (selection.getOffset() - line.getOffset()); return new Region(line.getOffset(), length); - + } catch (BadLocationException x) { // should not happen PHPeclipsePlugin.log(x); } - - return null; + + return null; } /** - * Returns the index of the first line whose start offset is in the given text range. - * - * @param region the text range in characters where to find the line - * @param document The document - * @return the first line whose start index is in the given range, -1 if there is no such line + * Returns the index of the first line whose start offset is in the given + * text range. + * + * @param region + * the text range in characters where to find the line + * @param document + * The document + * @return the first line whose start index is in the given range, -1 if + * there is no such line */ private int getFirstCompleteLineOfRegion(IRegion region, IDocument document) { - + try { - - int startLine= document.getLineOfOffset(region.getOffset()); - - int offset= document.getLineOffset(startLine); + + int startLine = document.getLineOfOffset(region.getOffset()); + + int offset = document.getLineOffset(startLine); if (offset >= region.getOffset()) return startLine; - - offset= document.getLineOffset(startLine + 1); - return (offset > region.getOffset() + region.getLength() ? -1 : startLine + 1); - + + offset = document.getLineOffset(startLine + 1); + return (offset > region.getOffset() + region.getLength() ? -1 + : startLine + 1); + } catch (BadLocationException x) { // should not happen PHPeclipsePlugin.log(x); } - + return -1; } - + /** * Determines whether each line is prefixed by one of the prefixes. * - * @param startLine Start line in document - * @param endLine End line in document - * @param prefixes Possible comment prefixes - * @param document The document + * @param startLine + * Start line in document + * @param endLine + * End line in document + * @param prefixes + * Possible comment prefixes + * @param document + * The document * @return true iff each line from startLine - * to and including endLine is prepended by one - * of the prefixes, ignoring whitespace at the - * begin of line + * to and including endLine is prepended by one of + * the prefixes, ignoring whitespace at the begin of + * line */ - private boolean isBlockCommented(int startLine, int endLine, String[] prefixes, IDocument document) { - + private boolean isBlockCommented(int startLine, int endLine, + String[] prefixes, IDocument document) { + try { - + // check for occurrences of prefixes in the given lines - for (int i= startLine; i <= endLine; i++) { - - IRegion line= document.getLineInformation(i); - String text= document.get(line.getOffset(), line.getLength()); - - int[] found= TextUtilities.indexOf(prefixes, text, 0); - + for (int i = startLine; i <= endLine; i++) { + + IRegion line = document.getLineInformation(i); + String text = document.get(line.getOffset(), line.getLength()); + + int[] found = TextUtilities.indexOf(prefixes, text, 0); + if (found[0] == -1) // found a line which is not commented return false; - - String s= document.get(line.getOffset(), found[0]); - s= s.trim(); + + String s = document.get(line.getOffset(), found[0]); + s = s.trim(); if (s.length() != 0) // found a line which is not commented return false; - + } return true; - + } catch (BadLocationException x) { // should not happen PHPeclipsePlugin.log(x); } - + return false; } - + /** * Implementation of the IUpdate prototype method discovers * the operation through the current editor's @@ -263,58 +300,65 @@ public final class ToggleCommentAction extends TextEditorAction { */ public void update() { super.update(); - + if (!canModifyEditor()) { setEnabled(false); return; } - - ITextEditor editor= getTextEditor(); + + ITextEditor editor = getTextEditor(); if (fOperationTarget == null && editor != null) - fOperationTarget= (ITextOperationTarget) editor.getAdapter(ITextOperationTarget.class); - - boolean isEnabled= (fOperationTarget != null && fOperationTarget.canDoOperation(ITextOperationTarget.PREFIX) && fOperationTarget.canDoOperation(ITextOperationTarget.STRIP_PREFIX)); + fOperationTarget = (ITextOperationTarget) editor + .getAdapter(ITextOperationTarget.class); + + boolean isEnabled = (fOperationTarget != null + && fOperationTarget.canDoOperation(ITextOperationTarget.PREFIX) && fOperationTarget + .canDoOperation(ITextOperationTarget.STRIP_PREFIX)); setEnabled(isEnabled); } - + /* * @see TextEditorAction#setEditor(ITextEditor) */ public void setEditor(ITextEditor editor) { super.setEditor(editor); - fOperationTarget= null; + fOperationTarget = null; } - - public void configure(ISourceViewer sourceViewer, SourceViewerConfiguration configuration) { - fPrefixesMap= null; - - String[] types= configuration.getConfiguredContentTypes(sourceViewer); - Map prefixesMap= new HashMap(types.length); - for (int i= 0; i < types.length; i++) { - String type= types[i]; - String[] prefixes= configuration.getDefaultPrefixes(sourceViewer, type); + + public void configure(ISourceViewer sourceViewer, + SourceViewerConfiguration configuration) { + fPrefixesMap = null; + + String[] types = configuration.getConfiguredContentTypes(sourceViewer); + Map prefixesMap = new HashMap(types.length); + for (int i = 0; i < types.length; i++) { + String type = types[i]; + String[] prefixes = configuration.getDefaultPrefixes(sourceViewer, + type); if (prefixes != null && prefixes.length > 0) { - int emptyPrefixes= 0; - for (int j= 0; j < prefixes.length; j++) + int emptyPrefixes = 0; + for (int j = 0; j < prefixes.length; j++) if (prefixes[j].length() == 0) emptyPrefixes++; - + if (emptyPrefixes > 0) { - String[] nonemptyPrefixes= new String[prefixes.length - emptyPrefixes]; - for (int j= 0, k= 0; j < prefixes.length; j++) { - String prefix= prefixes[j]; + String[] nonemptyPrefixes = new String[prefixes.length + - emptyPrefixes]; + for (int j = 0, k = 0; j < prefixes.length; j++) { + String prefix = prefixes[j]; if (prefix.length() != 0) { - nonemptyPrefixes[k]= prefix; + nonemptyPrefixes[k] = prefix; k++; } } - prefixes= nonemptyPrefixes; + prefixes = nonemptyPrefixes; } - + prefixesMap.put(type, prefixes); } } - fDocumentPartitioning= configuration.getConfiguredDocumentPartitioning(sourceViewer); - fPrefixesMap= prefixesMap; + fDocumentPartitioning = configuration + .getConfiguredDocumentPartitioning(sourceViewer); + fPrefixesMap = prefixesMap; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/TogglePresentationAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/TogglePresentationAction.java index 1a59a91..71b3da6 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/TogglePresentationAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/TogglePresentationAction.java @@ -10,7 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpeclipse.phpeditor; - import net.sourceforge.phpdt.internal.ui.PHPUiImages; import net.sourceforge.phpdt.ui.PreferenceConstants; import net.sourceforge.phpdt.ui.actions.PHPEditorActionDefinitionIds; @@ -23,102 +22,109 @@ import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.TextEditorAction; - /** - * A toolbar action which toggles the presentation model of the - * connected text editor. The editor shows either the highlight range - * only or always the whole document. + * A toolbar action which toggles the presentation model of the connected text + * editor. The editor shows either the highlight range only or always the whole + * document. */ -public class TogglePresentationAction extends TextEditorAction implements IPropertyChangeListener { - +public class TogglePresentationAction extends TextEditorAction implements + IPropertyChangeListener { + private IPreferenceStore fStore; /** * Constructs and updates the action. */ public TogglePresentationAction() { - super(PHPEditorMessages.getResourceBundle(), "TogglePresentation.", null); //$NON-NLS-1$ + super(PHPEditorMessages.getResourceBundle(), + "TogglePresentation.", null); //$NON-NLS-1$ PHPUiImages.setToolImageDescriptors(this, "segment_edit.gif"); //$NON-NLS-1$ - setToolTipText(PHPEditorMessages.getString("TogglePresentation.tooltip")); //$NON-NLS-1$ + setToolTipText(PHPEditorMessages + .getString("TogglePresentation.tooltip")); //$NON-NLS-1$ setActionDefinitionId(PHPEditorActionDefinitionIds.TOGGLE_PRESENTATION); -// WorkbenchHelp.setHelp(this, IJavaHelpContextIds.TOGGLE_PRESENTATION_ACTION); + // WorkbenchHelp.setHelp(this, + // IJavaHelpContextIds.TOGGLE_PRESENTATION_ACTION); update(); } - + /* * @see IAction#actionPerformed */ public void run() { - - ITextEditor editor= getTextEditor(); + + ITextEditor editor = getTextEditor(); if (editor == null) return; - - IRegion remembered= editor.getHighlightRange(); + + IRegion remembered = editor.getHighlightRange(); editor.resetHighlightRange(); - - boolean showAll= !editor.showsHighlightRangeOnly(); + + boolean showAll = !editor.showsHighlightRangeOnly(); setChecked(showAll); - + editor.showHighlightRangeOnly(showAll); if (remembered != null) - editor.setHighlightRange(remembered.getOffset(), remembered.getLength(), true); - + editor.setHighlightRange(remembered.getOffset(), remembered + .getLength(), true); + fStore.removePropertyChangeListener(this); fStore.setValue(PreferenceConstants.EDITOR_SHOW_SEGMENTS, showAll); fStore.addPropertyChangeListener(this); } - + /* * @see TextEditorAction#update */ public void update() { - ITextEditor editor= getTextEditor(); - boolean checked= (editor != null && editor.showsHighlightRangeOnly()); + ITextEditor editor = getTextEditor(); + boolean checked = (editor != null && editor.showsHighlightRangeOnly()); setChecked(checked); setEnabled(editor != null); } - + /* * @see TextEditorAction#setEditor(ITextEditor) */ public void setEditor(ITextEditor editor) { - + super.setEditor(editor); - + if (editor != null) { - + if (fStore == null) { - fStore= PHPeclipsePlugin.getDefault().getPreferenceStore(); + fStore = PHPeclipsePlugin.getDefault().getPreferenceStore(); fStore.addPropertyChangeListener(this); } synchronizeWithPreference(editor); - + } else if (fStore != null) { fStore.removePropertyChangeListener(this); - fStore= null; + fStore = null; } - + update(); } - + /** - * Synchronizes the appearance of the editor with what the preference store tells him. + * Synchronizes the appearance of the editor with what the preference store + * tells him. */ private void synchronizeWithPreference(ITextEditor editor) { - + if (editor == null) return; - - boolean showSegments= fStore.getBoolean(PreferenceConstants.EDITOR_SHOW_SEGMENTS); + + boolean showSegments = fStore + .getBoolean(PreferenceConstants.EDITOR_SHOW_SEGMENTS); setChecked(showSegments); - + if (editor.showsHighlightRangeOnly() != showSegments) { - IRegion remembered= editor.getHighlightRange(); + IRegion remembered = editor.getHighlightRange(); editor.resetHighlightRange(); editor.showHighlightRangeOnly(showSegments); if (remembered != null) - editor.setHighlightRange(remembered.getOffset(), remembered.getLength(), true); + editor.setHighlightRange(remembered.getOffset(), remembered + .getLength(), true); } } @@ -126,7 +132,8 @@ public class TogglePresentationAction extends TextEditorAction implements IPrope * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { - if (event.getProperty().equals(PreferenceConstants.EDITOR_SHOW_SEGMENTS)) + if (event.getProperty() + .equals(PreferenceConstants.EDITOR_SHOW_SEGMENTS)) synchronizeWithPreference(getTextEditor()); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/WorkingCopyManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/WorkingCopyManager.java index 33bd236..1f96fb2 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/WorkingCopyManager.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/WorkingCopyManager.java @@ -11,7 +11,6 @@ package net.sourceforge.phpeclipse.phpeditor; - import java.util.HashMap; import java.util.Map; @@ -23,26 +22,30 @@ import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.text.Assert; import org.eclipse.ui.IEditorInput; - /** - * This working copy manager works together with a given compilation unit document provider and - * additionally offers to "overwrite" the working copy provided by this document provider. + * This working copy manager works together with a given compilation unit + * document provider and additionally offers to "overwrite" the working copy + * provided by this document provider. */ -public class WorkingCopyManager implements IWorkingCopyManager, IWorkingCopyManagerExtension { - +public class WorkingCopyManager implements IWorkingCopyManager, + IWorkingCopyManagerExtension { + private ICompilationUnitDocumentProvider fDocumentProvider; + private Map fMap; + private boolean fIsShuttingDown; /** * Creates a new working copy manager that co-operates with the given * compilation unit document provider. * - * @param provider the provider + * @param provider + * the provider */ public WorkingCopyManager(ICompilationUnitDocumentProvider provider) { Assert.isNotNull(provider); - fDocumentProvider= provider; + fDocumentProvider = provider; } /* @@ -51,28 +54,28 @@ public class WorkingCopyManager implements IWorkingCopyManager, IWorkingCopyMana public void connect(IEditorInput input) throws CoreException { fDocumentProvider.connect(input); } - + /* * @see net.sourceforge.phpdt.ui.IWorkingCopyManager#disconnect(org.eclipse.ui.IEditorInput) */ public void disconnect(IEditorInput input) { fDocumentProvider.disconnect(input); } - + /* * @see net.sourceforge.phpdt.ui.IWorkingCopyManager#shutdown() */ public void shutdown() { if (!fIsShuttingDown) { - fIsShuttingDown= true; + fIsShuttingDown = true; try { if (fMap != null) { fMap.clear(); - fMap= null; + fMap = null; } fDocumentProvider.shutdown(); } finally { - fIsShuttingDown= false; + fIsShuttingDown = false; } } } @@ -81,26 +84,29 @@ public class WorkingCopyManager implements IWorkingCopyManager, IWorkingCopyMana * @see net.sourceforge.phpdt.ui.IWorkingCopyManager#getWorkingCopy(org.eclipse.ui.IEditorInput) */ public ICompilationUnit getWorkingCopy(IEditorInput input) { - ICompilationUnit unit= fMap == null ? null : (ICompilationUnit) fMap.get(input); + ICompilationUnit unit = fMap == null ? null : (ICompilationUnit) fMap + .get(input); return unit != null ? unit : fDocumentProvider.getWorkingCopy(input); } - + /* - * @see net.sourceforge.phpdt.internal.ui.javaeditor.IWorkingCopyManagerExtension#setWorkingCopy(org.eclipse.ui.IEditorInput, net.sourceforge.phpdt.core.ICompilationUnit) + * @see net.sourceforge.phpdt.internal.ui.javaeditor.IWorkingCopyManagerExtension#setWorkingCopy(org.eclipse.ui.IEditorInput, + * net.sourceforge.phpdt.core.ICompilationUnit) */ public void setWorkingCopy(IEditorInput input, ICompilationUnit workingCopy) { if (fDocumentProvider.getDocument(input) != null) { if (fMap == null) - fMap= new HashMap(); + fMap = new HashMap(); fMap.put(input, workingCopy); } } + /* * @see net.sourceforge.phpdt.internal.ui.javaeditor.IWorkingCopyManagerExtension#removeWorkingCopy(org.eclipse.ui.IEditorInput) */ public void removeWorkingCopy(IEditorInput input) { fMap.remove(input); if (fMap.isEmpty()) - fMap= null; + fMap = null; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/actions/RTrimAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/actions/RTrimAction.java index 154b992..d4a1718 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/actions/RTrimAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/actions/RTrimAction.java @@ -41,7 +41,7 @@ public class RTrimAction implements IEditorActionDelegate { ITextEditor editor = null; /** - * + * */ public RTrimAction() { super(); @@ -58,8 +58,10 @@ public class RTrimAction implements IEditorActionDelegate { * this gets called for every action */ public void run(IAction action) { - IDocument doc = editor.getDocumentProvider().getDocument(editor.getEditorInput()); - ITextSelection sel = (ITextSelection) editor.getSelectionProvider().getSelection(); + IDocument doc = editor.getDocumentProvider().getDocument( + editor.getEditorInput()); + ITextSelection sel = (ITextSelection) editor.getSelectionProvider() + .getSelection(); int currentLine = 0; int originalCursorOffset = sel.getOffset(); @@ -67,25 +69,28 @@ public class RTrimAction implements IEditorActionDelegate { int originalSelectionLength = sel.getLength(); int selectionLength = originalSelectionLength; String oldText; - int lineEnd; - + int lineEnd; + try { while (currentLine < doc.getNumberOfLines()) { int offset = doc.getLineOffset(currentLine); int length = doc.getLineLength(currentLine); oldText = doc.get(offset, length); - - //-- Starts at the end of the line, looking for the first non-first 'white space' - //-- it then breaks out. No point in carrying on, as we have found our true line end - for (lineEnd=oldText.length(); lineEnd > 0; --lineEnd ){ - if ( oldText.charAt(lineEnd-1) != '\t' && oldText.charAt(lineEnd-1) != ' ' ){ + + // -- Starts at the end of the line, looking for the first + // non-first 'white space' + // -- it then breaks out. No point in carrying on, as we have + // found our true line end + for (lineEnd = oldText.length(); lineEnd > 0; --lineEnd) { + if (oldText.charAt(lineEnd - 1) != '\t' + && oldText.charAt(lineEnd - 1) != ' ') { break; } } - - //-- Only replace the line if the lengths are different - if ( lineEnd != oldText.length() ) { + + // -- Only replace the line if the lengths are different + if (lineEnd != oldText.length()) { String newText = oldText.substring(0, lineEnd); doc.replace(offset, length, newText); @@ -93,16 +98,27 @@ public class RTrimAction implements IEditorActionDelegate { if (oldText.length() != newText.length()) { cursorOffset -= oldText.length() - newText.length(); } - } else if (offset <= cursorOffset + selectionLength && selectionLength > 0) { + } else if (offset <= cursorOffset + selectionLength + && selectionLength > 0) { selectionLength -= oldText.length() - newText.length(); - } else if (offset + length == cursorOffset + 2) { // Check if the cursor is at the end of the line. + } else if (offset + length == cursorOffset + 2) { // Check + // if + // the + // cursor + // is at + // the + // end + // of + // the + // line. cursorOffset -= 2; } } currentLine++; } - TextSelection selection = new TextSelection(doc, cursorOffset, selectionLength); + TextSelection selection = new TextSelection(doc, cursorOffset, + selectionLength); editor.getSelectionProvider().setSelection(selection); } catch (Exception blx) { blx.printStackTrace(); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLCodeScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLCodeScanner.java index a21ea07..64501fd 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLCodeScanner.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLCodeScanner.java @@ -1,14 +1,14 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ package net.sourceforge.phpeclipse.phpeditor.php; import java.util.ArrayList; @@ -36,145 +36,160 @@ import org.eclipse.jface.text.rules.WordRule; */ public class HTMLCodeScanner extends AbstractJavaScanner { -// private static String[] fgKeywords = { -// }; -// -// private static String[] fgTypes = { -// }; - -// private IToken keyword; - private static String[] fgTokenProperties = - { - IPreferenceConstants.PHP_MULTILINE_COMMENT, - IPreferenceConstants.PHP_SINGLELINE_COMMENT, - IPreferenceConstants.PHP_TAG, - IPreferenceConstants.PHP_KEYWORD, - IPreferenceConstants.PHP_FUNCTIONNAME, - IPreferenceConstants.PHP_VARIABLE, - IPreferenceConstants.PHP_VARIABLE_DOLLAR, - IPreferenceConstants.PHP_STRING_DQ, - IPreferenceConstants.PHP_STRING_SQ, - IPreferenceConstants.PHP_TYPE, - IPreferenceConstants.PHP_CONSTANT, - IPreferenceConstants.PHP_DEFAULT, - IPreferenceConstants.PHP_OPERATOR, - IPreferenceConstants.PHP_BRACE_OPERATOR, - IPreferenceConstants.PHP_KEYWORD_RETURN}; - /* - * @see AbstractJavaScanner#getTokenProperties() - */ - protected String[] getTokenProperties() { - return fgTokenProperties; - } - private class HTMLWordRule extends WordRule { - private StringBuffer fBuffer = new StringBuffer(); - - public HTMLWordRule(IWordDetector detector) { - super(detector, Token.UNDEFINED); - } - - public HTMLWordRule(IWordDetector detector, IToken defaultToken) { - super(detector, defaultToken); - } - - public IToken evaluate(ICharacterScanner scanner) { - int c = scanner.read(); - boolean tagBegin = false; - if (fDetector.isWordStart((char) c)) { - if (c == '<') { - tagBegin = true; - } - if (fColumn == UNDEFINED || (fColumn == scanner.getColumn() - 1)) { - - fBuffer.setLength(0); - do { - fBuffer.append((char) c); - c = scanner.read(); - if (c == '>') { - fBuffer.append((char) c); - c = scanner.read(); - break; - } - if (c == '/' && (fBuffer.length() > 2) ) { - break; - } - } while (c != ICharacterScanner.EOF && fDetector.isWordPart((char) c)); - scanner.unread(); - - if (tagBegin) { - return getToken(IPreferenceConstants.PHP_KEYWORD); - } - IToken token = (IToken) fWords.get(fBuffer.toString()); - if (token != null) - return token; - - if (fDefaultToken.isUndefined()) - unreadBuffer(scanner); - - return fDefaultToken; - } - } - - scanner.unread(); - return Token.UNDEFINED; - } - - } - - //private static String[] fgConstants = { "__LINE__", "__FILE__", "true", "false" }; - private TextAttribute fComment; - private TextAttribute fKeyword; - private TextAttribute fType; - private TextAttribute fString; - private PHPColorProvider fColorProvider; - - /** - * Creates a Java code scanner - */ - public HTMLCodeScanner(IColorManager manager, IPreferenceStore store) { - super(manager, store); - initialize(); - } - - /* - * @see AbstractJavaScanner#createRules() - */ - protected List createRules() { - List rules = new ArrayList(); - -// keyword = new Token(new TextAttribute(provider.getColor(PHPColorProvider.KEYWORD))); -// IToken type = new Token(new TextAttribute(provider.getColor(PHPColorProvider.FUNCTION_NAME))); -// IToken string = new Token(new TextAttribute(provider.getColor(PHPColorProvider.STRING_DQ))); -// IToken comment = new Token(new TextAttribute(provider.getColor(PHPColorProvider.SINGLE_LINE_COMMENT))); -// IToken multi_comment = new Token(new TextAttribute(provider.getColor(PHPColorProvider.MULTI_LINE_COMMENT))); -// IToken other = new Token(new TextAttribute(provider.getColor(PHPColorProvider.DEFAULT))); - - //variable = new Token(new TextAttribute(provider.getColor(PHPColorProvider.VARIABLE))); - - - // Add rule for single line comments. - //rules.add(new EndOfLineRule("//", comment)); //$NON-NLS-1$ - //rules.add(new EndOfLineRule("#", comment)); - - // Add rule for strings and character constants. - rules.add(new SingleLineRule("\"", "\"", getToken(IPreferenceConstants.PHP_STRING_DQ))); //$NON-NLS-2$ //$NON-NLS-1$ - // rules.add(new SingleLineRule("'", "'", string, '\\')); //$NON-NLS-2$ //$NON-NLS-1$ - - // rules.add(new SingleLineRule("//", "//", php_comment)); - // rules.add(new MultiLineRule("/*", "*/", multi_comment)); - - // Add generic whitespace rule. - rules.add(new WhitespaceRule(new PHPWhitespaceDetector())); - - // Add word rule for keywords, types, and constants. - HTMLWordRule wordRule = new HTMLWordRule(new HTMLWordDetector(), getToken(IPreferenceConstants.PHP_DEFAULT)); -// for (int i = 0; i < fgKeywords.length; i++) -// wordRule.addWord(fgKeywords[i], keyword); -// for (int i = 0; i < fgTypes.length; i++) -// wordRule.addWord(fgTypes[i], type); - rules.add(wordRule); - - setDefaultReturnToken(getToken(IPreferenceConstants.PHP_DEFAULT)); -return rules; - } + // private static String[] fgKeywords = { + // }; + // + // private static String[] fgTypes = { + // }; + + // private IToken keyword; + private static String[] fgTokenProperties = { + IPreferenceConstants.PHP_MULTILINE_COMMENT, + IPreferenceConstants.PHP_SINGLELINE_COMMENT, + IPreferenceConstants.PHP_TAG, IPreferenceConstants.PHP_KEYWORD, + IPreferenceConstants.PHP_FUNCTIONNAME, + IPreferenceConstants.PHP_VARIABLE, + IPreferenceConstants.PHP_VARIABLE_DOLLAR, + IPreferenceConstants.PHP_STRING_DQ, + IPreferenceConstants.PHP_STRING_SQ, IPreferenceConstants.PHP_TYPE, + IPreferenceConstants.PHP_CONSTANT, + IPreferenceConstants.PHP_DEFAULT, + IPreferenceConstants.PHP_OPERATOR, + IPreferenceConstants.PHP_BRACE_OPERATOR, + IPreferenceConstants.PHP_KEYWORD_RETURN }; + + /* + * @see AbstractJavaScanner#getTokenProperties() + */ + protected String[] getTokenProperties() { + return fgTokenProperties; + } + + private class HTMLWordRule extends WordRule { + private StringBuffer fBuffer = new StringBuffer(); + + public HTMLWordRule(IWordDetector detector) { + super(detector, Token.UNDEFINED); + } + + public HTMLWordRule(IWordDetector detector, IToken defaultToken) { + super(detector, defaultToken); + } + + public IToken evaluate(ICharacterScanner scanner) { + int c = scanner.read(); + boolean tagBegin = false; + if (fDetector.isWordStart((char) c)) { + if (c == '<') { + tagBegin = true; + } + if (fColumn == UNDEFINED + || (fColumn == scanner.getColumn() - 1)) { + + fBuffer.setLength(0); + do { + fBuffer.append((char) c); + c = scanner.read(); + if (c == '>') { + fBuffer.append((char) c); + c = scanner.read(); + break; + } + if (c == '/' && (fBuffer.length() > 2)) { + break; + } + } while (c != ICharacterScanner.EOF + && fDetector.isWordPart((char) c)); + scanner.unread(); + + if (tagBegin) { + return getToken(IPreferenceConstants.PHP_KEYWORD); + } + IToken token = (IToken) fWords.get(fBuffer.toString()); + if (token != null) + return token; + + if (fDefaultToken.isUndefined()) + unreadBuffer(scanner); + + return fDefaultToken; + } + } + + scanner.unread(); + return Token.UNDEFINED; + } + + } + + // private static String[] fgConstants = { "__LINE__", "__FILE__", "true", + // "false" }; + private TextAttribute fComment; + + private TextAttribute fKeyword; + + private TextAttribute fType; + + private TextAttribute fString; + + private PHPColorProvider fColorProvider; + + /** + * Creates a Java code scanner + */ + public HTMLCodeScanner(IColorManager manager, IPreferenceStore store) { + super(manager, store); + initialize(); + } + + /* + * @see AbstractJavaScanner#createRules() + */ + protected List createRules() { + List rules = new ArrayList(); + + // keyword = new Token(new + // TextAttribute(provider.getColor(PHPColorProvider.KEYWORD))); + // IToken type = new Token(new + // TextAttribute(provider.getColor(PHPColorProvider.FUNCTION_NAME))); + // IToken string = new Token(new + // TextAttribute(provider.getColor(PHPColorProvider.STRING_DQ))); + // IToken comment = new Token(new + // TextAttribute(provider.getColor(PHPColorProvider.SINGLE_LINE_COMMENT))); + // IToken multi_comment = new Token(new + // TextAttribute(provider.getColor(PHPColorProvider.MULTI_LINE_COMMENT))); + // IToken other = new Token(new + // TextAttribute(provider.getColor(PHPColorProvider.DEFAULT))); + + // variable = new Token(new + // TextAttribute(provider.getColor(PHPColorProvider.VARIABLE))); + + // Add rule for single line comments. + // rules.add(new EndOfLineRule("//", comment)); //$NON-NLS-1$ + // rules.add(new EndOfLineRule("#", comment)); + + // Add rule for strings and character constants. + rules.add(new SingleLineRule( + "\"", "\"", getToken(IPreferenceConstants.PHP_STRING_DQ))); //$NON-NLS-2$ //$NON-NLS-1$ + // rules.add(new SingleLineRule("'", "'", string, '\\')); //$NON-NLS-2$ + // //$NON-NLS-1$ + + // rules.add(new SingleLineRule("//", "//", php_comment)); + // rules.add(new MultiLineRule("/*", "*/", multi_comment)); + + // Add generic whitespace rule. + rules.add(new WhitespaceRule(new PHPWhitespaceDetector())); + + // Add word rule for keywords, types, and constants. + HTMLWordRule wordRule = new HTMLWordRule(new HTMLWordDetector(), + getToken(IPreferenceConstants.PHP_DEFAULT)); + // for (int i = 0; i < fgKeywords.length; i++) + // wordRule.addWord(fgKeywords[i], keyword); + // for (int i = 0; i < fgTypes.length; i++) + // wordRule.addWord(fgTypes[i], type); + rules.add(wordRule); + + setDefaultReturnToken(getToken(IPreferenceConstants.PHP_DEFAULT)); + return rules; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLCompletionProcessor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLCompletionProcessor.java index 91e1339..adf3f23 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLCompletionProcessor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLCompletionProcessor.java @@ -1,14 +1,14 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ package net.sourceforge.phpeclipse.phpeditor.php; import java.util.ArrayList; @@ -40,232 +40,269 @@ import org.eclipse.ui.IEditorPart; */ public class HTMLCompletionProcessor implements IContentAssistProcessor { - /** - * Simple content assist tip closer. The tip is valid in a range - * of 5 characters around its popup location. - */ - protected static class Validator implements IContextInformationValidator, IContextInformationPresenter { - - protected int fInstallOffset; - - /* - * @see IContextInformationValidator#isContextInformationValid(int) - */ - public boolean isContextInformationValid(int offset) { - return Math.abs(fInstallOffset - offset) < 5; - } - - /* - * @see IContextInformationValidator#install(IContextInformation, ITextViewer, int) - */ - public void install(IContextInformation info, ITextViewer viewer, int offset) { - fInstallOffset = offset; - } - - /* - * @see org.eclipse.jface.text.contentassist.IContextInformationPresenter#updatePresentation(int, TextPresentation) - */ - public boolean updatePresentation(int documentPosition, TextPresentation presentation) { - return false; - } - }; - - private static 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; - } - }; - - protected IContextInformationValidator fValidator = new Validator(); - private TemplateEngine fTemplateEngine; - private char[] fProposalAutoActivationSet; - private PHPCompletionProposalComparator fComparator; - private int fNumberOfComputedResults = 0; - - private IEditorPart fEditor; - - protected IWorkingCopyManager fManager; - - public HTMLCompletionProcessor(IEditorPart editor) { - fEditor = editor; - fManager = PHPeclipsePlugin.getDefault().getWorkingCopyManager(); - - TemplateContextType contextType = PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType("html"); //$NON-NLS-1$ - if (contextType != null) - fTemplateEngine = new TemplateEngine(contextType); - - fComparator = new PHPCompletionProposalComparator(); - } - - /* (non-Javadoc) - * Method declared on IContentAssistProcessor - */ - public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) { - int contextInformationPosition = guessContextInformationPosition(viewer, documentOffset); - return internalComputeCompletionProposals(viewer, documentOffset, contextInformationPosition); - } - - private ICompletionProposal[] internalComputeCompletionProposals(ITextViewer viewer, int offset, int contextOffset) { - IDocument document = viewer.getDocument(); - ICompilationUnit unit= fManager.getWorkingCopy(fEditor.getEditorInput()); - - if (fTemplateEngine != null) { - ICompletionProposal[] results; - // try { - fTemplateEngine.reset(); - fTemplateEngine.complete(viewer, offset, unit); - // } catch (JavaModelException x) { - // Shell shell= viewer.getTextWidget().getShell(); - // ErrorDialog.openError(shell, JavaTextMessages.getString("CompletionProcessor.error.accessing.title"), JavaTextMessages.getString("CompletionProcessor.error.accessing.message"), x.getStatus()); //$NON-NLS-2$ //$NON-NLS-1$ - // } - - IPHPCompletionProposal[] templateResults = fTemplateEngine.getResults(); - - // concatenate arrays - IPHPCompletionProposal[] total; - total = new IPHPCompletionProposal[templateResults.length]; - System.arraycopy(templateResults, 0, total, 0, templateResults.length); - results = total; - - fNumberOfComputedResults = (results == null ? 0 : results.length); - /* - * Order here and not in result collector to make sure that the order - * applies to all proposals and not just those of the compilation unit. - */ - return order(results); - } - return new IPHPCompletionProposal[0]; - } - - private int guessContextInformationPosition(ITextViewer viewer, int offset) { - int contextPosition = offset; - IDocument document = viewer.getDocument(); - return contextPosition; - } - - /* (non-Javadoc) - * Method declared on IContentAssistProcessor - */ - // public IContextInformation[] computeContextInformation(ITextViewer viewer, int documentOffset) { - // IContextInformation[] result = new IContextInformation[5]; - // for (int i = 0; i < result.length; i++) - // result[i] = new ContextInformation(MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.ContextInfo.display.pattern"), new Object[] { new Integer(i), new Integer(documentOffset)}), //$NON-NLS-1$ - // MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.ContextInfo.value.pattern"), new Object[] { new Integer(i), new Integer(documentOffset - 5), new Integer(documentOffset + 5)})); //$NON-NLS-1$ - // return result; - // } - /** - * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int) - */ - public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) { - int contextInformationPosition = guessContextInformationPosition(viewer, offset); - List result = addContextInformations(viewer, contextInformationPosition); - return (IContextInformation[]) result.toArray(new IContextInformation[result.size()]); - } - - private List addContextInformations(ITextViewer viewer, int offset) { - ICompletionProposal[] proposals = internalComputeCompletionProposals(viewer, offset, -1); - - List result = new ArrayList(); - for (int i = 0; i < proposals.length; i++) { - IContextInformation contextInformation = proposals[i].getContextInformation(); - if (contextInformation != null) { - ContextInformationWrapper wrapper = new ContextInformationWrapper(contextInformation); - wrapper.setContextInformationPosition(offset); - result.add(wrapper); - } - } - return result; - } - - /** - * Order the given proposals. - */ - private ICompletionProposal[] order(ICompletionProposal[] proposals) { - Arrays.sort(proposals, fComparator); - return proposals; - } - - /** - * Tells this processor to order the proposals alphabetically. - * - * @param order true if proposals should be ordered. - */ - public void orderProposalsAlphabetically(boolean order) { - fComparator.setOrderAlphabetically(order); - } - - /** - * @see IContentAssistProcessor#getCompletionProposalAutoActivationCharacters() - */ - public char[] getCompletionProposalAutoActivationCharacters() { - return fProposalAutoActivationSet; - } - - /** - * Sets this processor's set of characters triggering the activation of the - * completion proposal computation. - * - * @param activationSet the activation set - */ - public void setCompletionProposalAutoActivationCharacters(char[] activationSet) { - fProposalAutoActivationSet= activationSet; - } - - /* (non-Javadoc) - * Method declared on IContentAssistProcessor - */ - public char[] getContextInformationAutoActivationCharacters() { - return new char[] { - }; - } - - /* (non-Javadoc) - * Method declared on IContentAssistProcessor - */ - public IContextInformationValidator getContextInformationValidator() { - return fValidator; - } - - /* (non-Javadoc) - * Method declared on IContentAssistProcessor - */ - public String getErrorMessage() { - return null; - } + /** + * Simple content assist tip closer. The tip is valid in a range of 5 + * characters around its popup location. + */ + protected static class Validator implements IContextInformationValidator, + IContextInformationPresenter { + + protected int fInstallOffset; + + /* + * @see IContextInformationValidator#isContextInformationValid(int) + */ + public boolean isContextInformationValid(int offset) { + return Math.abs(fInstallOffset - offset) < 5; + } + + /* + * @see IContextInformationValidator#install(IContextInformation, + * ITextViewer, int) + */ + public void install(IContextInformation info, ITextViewer viewer, + int offset) { + fInstallOffset = offset; + } + + /* + * @see org.eclipse.jface.text.contentassist.IContextInformationPresenter#updatePresentation(int, + * TextPresentation) + */ + public boolean updatePresentation(int documentPosition, + TextPresentation presentation) { + return false; + } + }; + + private static 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; + } + }; + + protected IContextInformationValidator fValidator = new Validator(); + + private TemplateEngine fTemplateEngine; + + private char[] fProposalAutoActivationSet; + + private PHPCompletionProposalComparator fComparator; + + private int fNumberOfComputedResults = 0; + + private IEditorPart fEditor; + + protected IWorkingCopyManager fManager; + + public HTMLCompletionProcessor(IEditorPart editor) { + fEditor = editor; + fManager = PHPeclipsePlugin.getDefault().getWorkingCopyManager(); + + TemplateContextType contextType = PHPeclipsePlugin.getDefault() + .getTemplateContextRegistry().getContextType("html"); //$NON-NLS-1$ + if (contextType != null) + fTemplateEngine = new TemplateEngine(contextType); + + fComparator = new PHPCompletionProposalComparator(); + } + + /* + * (non-Javadoc) Method declared on IContentAssistProcessor + */ + public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, + int documentOffset) { + int contextInformationPosition = guessContextInformationPosition( + viewer, documentOffset); + return internalComputeCompletionProposals(viewer, documentOffset, + contextInformationPosition); + } + + private ICompletionProposal[] internalComputeCompletionProposals( + ITextViewer viewer, int offset, int contextOffset) { + IDocument document = viewer.getDocument(); + ICompilationUnit unit = fManager.getWorkingCopy(fEditor + .getEditorInput()); + + if (fTemplateEngine != null) { + ICompletionProposal[] results; + // try { + fTemplateEngine.reset(); + fTemplateEngine.complete(viewer, offset, unit); + // } catch (JavaModelException x) { + // Shell shell= viewer.getTextWidget().getShell(); + // ErrorDialog.openError(shell, + // JavaTextMessages.getString("CompletionProcessor.error.accessing.title"), + // JavaTextMessages.getString("CompletionProcessor.error.accessing.message"), + // x.getStatus()); //$NON-NLS-2$ //$NON-NLS-1$ + // } + + IPHPCompletionProposal[] templateResults = fTemplateEngine + .getResults(); + + // concatenate arrays + IPHPCompletionProposal[] total; + total = new IPHPCompletionProposal[templateResults.length]; + System.arraycopy(templateResults, 0, total, 0, + templateResults.length); + results = total; + + fNumberOfComputedResults = (results == null ? 0 : results.length); + /* + * Order here and not in result collector to make sure that the + * order applies to all proposals and not just those of the + * compilation unit. + */ + return order(results); + } + return new IPHPCompletionProposal[0]; + } + + private int guessContextInformationPosition(ITextViewer viewer, int offset) { + int contextPosition = offset; + IDocument document = viewer.getDocument(); + return contextPosition; + } + + /* + * (non-Javadoc) Method declared on IContentAssistProcessor + */ + // public IContextInformation[] computeContextInformation(ITextViewer + // viewer, int documentOffset) { + // IContextInformation[] result = new IContextInformation[5]; + // for (int i = 0; i < result.length; i++) + // result[i] = new + // ContextInformation(MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.ContextInfo.display.pattern"), + // new Object[] { new Integer(i), new Integer(documentOffset)}), + // //$NON-NLS-1$ + // MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.ContextInfo.value.pattern"), + // new Object[] { new Integer(i), new Integer(documentOffset - 5), new + // Integer(documentOffset + 5)})); //$NON-NLS-1$ + // return result; + // } + /** + * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int) + */ + public IContextInformation[] computeContextInformation(ITextViewer viewer, + int offset) { + int contextInformationPosition = guessContextInformationPosition( + viewer, offset); + List result = addContextInformations(viewer, contextInformationPosition); + return (IContextInformation[]) result + .toArray(new IContextInformation[result.size()]); + } + + private List addContextInformations(ITextViewer viewer, int offset) { + ICompletionProposal[] proposals = internalComputeCompletionProposals( + viewer, offset, -1); + + List result = new ArrayList(); + for (int i = 0; i < proposals.length; i++) { + IContextInformation contextInformation = proposals[i] + .getContextInformation(); + if (contextInformation != null) { + ContextInformationWrapper wrapper = new ContextInformationWrapper( + contextInformation); + wrapper.setContextInformationPosition(offset); + result.add(wrapper); + } + } + return result; + } + + /** + * Order the given proposals. + */ + private ICompletionProposal[] order(ICompletionProposal[] proposals) { + Arrays.sort(proposals, fComparator); + return proposals; + } + + /** + * Tells this processor to order the proposals alphabetically. + * + * @param order + * true if proposals should be ordered. + */ + public void orderProposalsAlphabetically(boolean order) { + fComparator.setOrderAlphabetically(order); + } + + /** + * @see IContentAssistProcessor#getCompletionProposalAutoActivationCharacters() + */ + public char[] getCompletionProposalAutoActivationCharacters() { + return fProposalAutoActivationSet; + } + + /** + * Sets this processor's set of characters triggering the activation of the + * completion proposal computation. + * + * @param activationSet + * the activation set + */ + public void setCompletionProposalAutoActivationCharacters( + char[] activationSet) { + fProposalAutoActivationSet = activationSet; + } + + /* + * (non-Javadoc) Method declared on IContentAssistProcessor + */ + public char[] getContextInformationAutoActivationCharacters() { + return new char[] {}; + } + + /* + * (non-Javadoc) Method declared on IContentAssistProcessor + */ + public IContextInformationValidator getContextInformationValidator() { + return fValidator; + } + + /* + * (non-Javadoc) Method declared on IContentAssistProcessor + */ + public String getErrorMessage() { + return null; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLPartitionScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLPartitionScanner.java index e56ac83..eab265e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLPartitionScanner.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLPartitionScanner.java @@ -6,7 +6,7 @@ * Created on 05.03.2003 * * @author Stefan Langer (musk) - * @version $Revision: 1.2 $ + * @version $Revision: 1.3 $ */ package net.sourceforge.phpeclipse.phpeditor.php; @@ -29,408 +29,444 @@ import org.eclipse.jface.text.rules.Token; * */ public class HTMLPartitionScanner implements IPartitionTokenScanner { - private static final boolean DEBUG = false; - - private boolean fInString = false; - private boolean fInDoubString = false; - private IDocument fDocument = null; - private int fOffset = -1; - private String fContentType = IPHPPartitions.HTML; - private String fPrevContentType = IPHPPartitions.HTML; - private boolean partitionBorder = false; - private int fTokenOffset; - private int fEnd = -1; - private int fLength; - private int fCurrentLength; - private int fFileType; - private Map tokens = new HashMap(); - - public HTMLPartitionScanner() { - this(IPHPPartitions.PHP_FILE); - } - - public HTMLPartitionScanner(int fileType) { - this.tokens.put(IPHPPartitions.HTML, new Token(IPHPPartitions.HTML)); - this.tokens.put( - IPHPPartitions.HTML_MULTILINE_COMMENT, - new Token(IPHPPartitions.HTML_MULTILINE_COMMENT)); - - this.tokens.put(IPHPPartitions.SMARTY, new Token(IPHPPartitions.SMARTY)); - this.tokens.put( - IPHPPartitions.SMARTY_MULTILINE_COMMENT, - new Token(IPHPPartitions.SMARTY_MULTILINE_COMMENT)); - - this.tokens.put(IDocument.DEFAULT_CONTENT_TYPE, new Token(IDocument.DEFAULT_CONTENT_TYPE)); - fFileType = fileType; - } - - private IToken getToken(String type) { - fLength = fCurrentLength; - if (DEBUG) { - - try { - if (fLength <= 0) { - int line = fDocument.getLineOfOffset(fOffset); - System.err.println("Error at " + line + " offset:" + String.valueOf(fOffset - fDocument.getLineOffset(line))); - } - } catch (BadLocationException e) { // should never happen - // TODO Write stacktrace to log - e.printStackTrace(); - } - } - Assert.isTrue(fLength > 0, "Partition length <= 0!"); - fCurrentLength = 0; - // String can never cross partition borders so reset string detection - fInString = false; - fInDoubString = false; - IToken token = (IToken) this.tokens.get(type); - Assert.isNotNull(token, "Token for type \"" + type + "\" not found!"); - if (DEBUG) { - System.out.println("Partition: fTokenOffset=" + fTokenOffset + " fContentType=" + type + " fLength=" + fLength); - } - return token; - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.rules.IPartitionTokenScanner#setPartialRange(org.eclipse.jface.text.IDocument, int, int, java.lang.String, int) - */ - public void setPartialRange(IDocument document, int offset, int length, String contentType, int partitionOffset) { - if (DEBUG) { - System.out.println("*****"); - System.out.println("PartialRange: contentType=" + contentType + " partitionOffset=" + partitionOffset); - } - - try { - if (partitionOffset > -1) { - partitionBorder = false; - // because of strings we have to parse the whole partition - this.setRange(document, partitionOffset, offset - partitionOffset + length); - // sometimes we get a wrong partition so we retrieve the partition - // directly from the document - fContentType = fDocument.getContentType(partitionOffset); - } else - this.setRange(document, offset, length); - - } catch (BadLocationException e) { - // should never happen - // TODO print stack trace to log - // fall back just scan the whole document again - this.setRange(document, 0, fDocument.getLength()); - } - - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.rules.ITokenScanner#getTokenLength() - */ - public int getTokenLength() { - return fLength; - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.rules.ITokenScanner#getTokenOffset() - */ - public int getTokenOffset() { - return fTokenOffset; - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.rules.ITokenScanner#nextToken() - */ - public IToken nextToken() { - int c; - - // check if we are not allready at the end of the - // file - if ((c = read()) == ICharacterScanner.EOF) { - partitionBorder = false; - return Token.EOF; - } else - unread(); - - if (partitionBorder) { - fTokenOffset = fOffset; - partitionBorder = false; - } - - while ((c = read()) != ICharacterScanner.EOF) { - switch (c) { - case '<' : - if ( checkPattern(new char[] { '!', '-', '-' })) { // return previouse partition - if (fContentType != IPHPPartitions.HTML_MULTILINE_COMMENT && fCurrentLength > 4) { - unread(4); - IToken token = getToken(fContentType); - fContentType = IPHPPartitions.HTML_MULTILINE_COMMENT; - return token; - } else - fContentType = IPHPPartitions.HTML_MULTILINE_COMMENT; - - fTokenOffset = fOffset - 4; - fCurrentLength = 4; - } - break; - case '-' : - if (fContentType == IPHPPartitions.HTML_MULTILINE_COMMENT - && checkPattern(new char[] { '-', '>' })) { - fContentType = IPHPPartitions.HTML; - partitionBorder = true; - return getToken(IPHPPartitions.HTML_MULTILINE_COMMENT); - } - break; - case '{' : // SMARTY code starts here ? - if (fFileType == IPHPPartitions.SMARTY_FILE) { - if ((c = read()) == '*') { - if (DEBUG) { - System.out.println( - "SMARTYDOC_TOKEN start " - + fTokenOffset - + " fContentType=" - + fContentType - + " fLength=" - + fLength - + " fOffset=" - + fOffset - + " fCurrentLength=" - + fCurrentLength); - } - if (fContentType != IPHPPartitions.SMARTY_MULTILINE_COMMENT && fCurrentLength > 2) { - // SMARTY doc code starts here - unread(2); - IToken token = getToken(fContentType); - fContentType = IPHPPartitions.SMARTY_MULTILINE_COMMENT; - return token; - // } else if (fContentType == IPHPPartitionScannerConstants.HTML && fOffset == 2) { - // fContentType = IPHPPartitionScannerConstants.SMARTY_MULTILINE_COMMENT; - } else { // if (fContentType == IPHPPartitionScannerConstants.SMARTY_MULTILINE_COMMENT) { - fContentType = IPHPPartitions.SMARTY_MULTILINE_COMMENT; - fTokenOffset = fOffset - 2; - fCurrentLength = 2; - } - break; - } - if (DEBUG) { - System.out.println( - "SMARTY_TOKEN start " - + fTokenOffset - + " fContentType=" - + fContentType - + " fLength=" - + fLength - + " fOffset=" - + fOffset); - } - if (c != ICharacterScanner.EOF) { - unread(); - } - if (fContentType != IPHPPartitions.SMARTY && fCurrentLength > 1) { - unread(1); - IToken token = getToken(fContentType); - fContentType = IPHPPartitions.SMARTY; - return token; - // } else if (fContentType == IPHPPartitionScannerConstants.HTML && fOffset==1) { - // fContentType = IPHPPartitionScannerConstants.SMARTY; - } else { - fContentType = IPHPPartitions.SMARTY; - fTokenOffset = fOffset - 1; - fCurrentLength = 1; - } - } - break; - case '}' : // SMARTY code ends here ? - if (fFileType == IPHPPartitions.SMARTY_FILE && fContentType == IPHPPartitions.SMARTY) { - if (DEBUG) { - System.out.println( - "SMARTY_TOKEN end " - + fTokenOffset - + " fContentType=" - + fContentType - + " fLength=" - + fLength - + " fOffset=" - + fOffset); - } - fContentType = IPHPPartitions.HTML; - partitionBorder = true; - return getToken(IPHPPartitions.SMARTY); - } - break; -// case '/' : -// if (!isInString(IPHPPartitions.PHP_PARTITIONING) && (c = read()) == '*') { // MULTINE COMMENT JAVASCRIPT, CSS, PHP -// if (fContentType == IPHPPartitions.PHP_PARTITIONING && fCurrentLength > 2) { -// unread(2); -// IToken token = getToken(fContentType); -// fContentType = IPHPPartitions.PHP_PHPDOC_COMMENT; -// return token; -// } else if (fContentType == IPHPPartitions.PHP_PHPDOC_COMMENT) { -// fTokenOffset = fOffset - 2; -// fCurrentLength = 2; -// } -// -// } else if (!isInString(IPHPPartitions.PHP_PARTITIONING) && c != ICharacterScanner.EOF) -// unread(); -// break; - case '*' : - if (fFileType == IPHPPartitions.SMARTY_FILE && (c = read()) == '}') { - if (DEBUG) { - System.out.println( - "SMARTYDOC_TOKEN end " - + fTokenOffset - + " fContentType=" - + fContentType - + " fLength=" - + fLength - + " fOffset=" - + fOffset); - } - if (fContentType == IPHPPartitions.SMARTY_MULTILINE_COMMENT) { - fContentType = IPHPPartitions.HTML; - partitionBorder = true; - return getToken(IPHPPartitions.SMARTY_MULTILINE_COMMENT); - } - } - break; - case '\'' : - if (!fInDoubString) - fInString = !fInString; - break; - case '"' : - // toggle String mode - if (!fInString) - fInDoubString = !fInDoubString; - break; - } - } // end of file reached but we have to return the - // last partition. - return getToken(fContentType); - } - /* (non-Javadoc) - * @see org.eclipse.jface.text.rules.ITokenScanner#setRange(org.eclipse.jface.text.IDocument, int, int) - */ - public void setRange(IDocument document, int offset, int length) { - if (DEBUG) { - System.out.println("SET RANGE: offset=" + offset + " length=" + length); - } - - fDocument = document; - fOffset = offset; - fTokenOffset = offset; - fCurrentLength = 0; - fLength = 0; - fEnd = fOffset + length; - fInString = false; - fInDoubString = false; - fContentType = IPHPPartitions.HTML; - // String[] prev = getPartitionStack(offset); - } - - private int read() { - try { - if (fOffset < fEnd) { - fCurrentLength++; - return fDocument.getChar(fOffset++); - } - return ICharacterScanner.EOF; - } catch (BadLocationException e) { - // should never happen - // TODO write stacktrace to log - fOffset = fEnd; - return ICharacterScanner.EOF; - } - } - - private void unread() { - --fOffset; - --fCurrentLength; - } - - private void unread(int num) { - fOffset -= num; - fCurrentLength -= num; - } - - private boolean checkPattern(char[] pattern) { - return checkPattern(pattern, false); - } - - /** - * Check if next character sequence read from document is equals to - * the provided pattern. Pattern is read from left to right until the - * first character read doesn't match. If this happens all read characters are - * unread. - * @param pattern The pattern to check. - * @return true if pattern is equals else returns false. - */ - private boolean checkPattern(char[] pattern, boolean ignoreCase) { - int prevOffset = fOffset; - int prevLength = fCurrentLength; - for (int i = 0; i < pattern.length; i++) { - int c = read(); - - if (c == ICharacterScanner.EOF || !letterEquals(c, pattern[i], ignoreCase)) { - fOffset = prevOffset; - fCurrentLength = prevLength; - return false; - } - } - - return true; - } - - private boolean letterEquals(int test, char letter, boolean ignoreCase) { - if (test == letter) - return true; - else if (ignoreCase && Character.isLowerCase(letter) && test == Character.toUpperCase(letter)) - return true; - else if (ignoreCase && Character.isUpperCase(letter) && test == Character.toLowerCase(letter)) - return true; - - return false; - } - - /** - * Checks wether the offset is in a String and the specified - * contenttype is the current content type. - * Strings are delimited, mutual exclusive, by a " or by a '. - * - * @param contentType The contenttype to check. - * @return true if the current offset is in a string else - * returns false. - */ - private boolean isInString(String contentType) { - if (fContentType == contentType) - return (fInString || fInDoubString); - else - return false; - } - - /** - * Returns the previouse partition stack for the given offset. - * - * @param offset The offset to return the previouse partitionstack for. - * - * @return The stack as a string array. - */ - private String[] getPartitionStack(int offset) { - ArrayList types = new ArrayList(); - int tmpOffset = 0; - try { - ITypedRegion region = fDocument.getPartition(offset); - tmpOffset = region.getOffset(); - while (tmpOffset - 1 > 0) { - region = fDocument.getPartition(tmpOffset - 1); - tmpOffset = region.getOffset(); - types.add(0, region.getType()); - } - } catch (BadLocationException e) { - if (DEBUG) { - e.printStackTrace(); - } - } - - String[] retVal = new String[types.size()]; - - retVal = (String[]) types.toArray(retVal); - return retVal; - } + private static final boolean DEBUG = false; + + private boolean fInString = false; + + private boolean fInDoubString = false; + + private IDocument fDocument = null; + + private int fOffset = -1; + + private String fContentType = IPHPPartitions.HTML; + + private String fPrevContentType = IPHPPartitions.HTML; + + private boolean partitionBorder = false; + + private int fTokenOffset; + + private int fEnd = -1; + + private int fLength; + + private int fCurrentLength; + + private int fFileType; + + private Map tokens = new HashMap(); + + public HTMLPartitionScanner() { + this(IPHPPartitions.PHP_FILE); + } + + public HTMLPartitionScanner(int fileType) { + this.tokens.put(IPHPPartitions.HTML, new Token(IPHPPartitions.HTML)); + this.tokens.put(IPHPPartitions.HTML_MULTILINE_COMMENT, new Token( + IPHPPartitions.HTML_MULTILINE_COMMENT)); + + this.tokens + .put(IPHPPartitions.SMARTY, new Token(IPHPPartitions.SMARTY)); + this.tokens.put(IPHPPartitions.SMARTY_MULTILINE_COMMENT, new Token( + IPHPPartitions.SMARTY_MULTILINE_COMMENT)); + + this.tokens.put(IDocument.DEFAULT_CONTENT_TYPE, new Token( + IDocument.DEFAULT_CONTENT_TYPE)); + fFileType = fileType; + } + + private IToken getToken(String type) { + fLength = fCurrentLength; + if (DEBUG) { + + try { + if (fLength <= 0) { + int line = fDocument.getLineOfOffset(fOffset); + System.err.println("Error at " + + line + + " offset:" + + String.valueOf(fOffset + - fDocument.getLineOffset(line))); + } + } catch (BadLocationException e) { // should never happen + // TODO Write stacktrace to log + e.printStackTrace(); + } + } + Assert.isTrue(fLength > 0, "Partition length <= 0!"); + fCurrentLength = 0; + // String can never cross partition borders so reset string detection + fInString = false; + fInDoubString = false; + IToken token = (IToken) this.tokens.get(type); + Assert.isNotNull(token, "Token for type \"" + type + "\" not found!"); + if (DEBUG) { + System.out.println("Partition: fTokenOffset=" + fTokenOffset + + " fContentType=" + type + " fLength=" + fLength); + } + return token; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.rules.IPartitionTokenScanner#setPartialRange(org.eclipse.jface.text.IDocument, + * int, int, java.lang.String, int) + */ + public void setPartialRange(IDocument document, int offset, int length, + String contentType, int partitionOffset) { + if (DEBUG) { + System.out.println("*****"); + System.out.println("PartialRange: contentType=" + contentType + + " partitionOffset=" + partitionOffset); + } + + try { + if (partitionOffset > -1) { + partitionBorder = false; + // because of strings we have to parse the whole partition + this.setRange(document, partitionOffset, offset + - partitionOffset + length); + // sometimes we get a wrong partition so we retrieve the + // partition + // directly from the document + fContentType = fDocument.getContentType(partitionOffset); + } else + this.setRange(document, offset, length); + + } catch (BadLocationException e) { + // should never happen + // TODO print stack trace to log + // fall back just scan the whole document again + this.setRange(document, 0, fDocument.getLength()); + } + + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.rules.ITokenScanner#getTokenLength() + */ + public int getTokenLength() { + return fLength; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.rules.ITokenScanner#getTokenOffset() + */ + public int getTokenOffset() { + return fTokenOffset; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.rules.ITokenScanner#nextToken() + */ + public IToken nextToken() { + int c; + + // check if we are not allready at the end of the + // file + if ((c = read()) == ICharacterScanner.EOF) { + partitionBorder = false; + return Token.EOF; + } else + unread(); + + if (partitionBorder) { + fTokenOffset = fOffset; + partitionBorder = false; + } + + while ((c = read()) != ICharacterScanner.EOF) { + switch (c) { + case '<': + if (checkPattern(new char[] { '!', '-', '-' })) { // return + // previouse + // partition + if (fContentType != IPHPPartitions.HTML_MULTILINE_COMMENT + && fCurrentLength > 4) { + unread(4); + IToken token = getToken(fContentType); + fContentType = IPHPPartitions.HTML_MULTILINE_COMMENT; + return token; + } else + fContentType = IPHPPartitions.HTML_MULTILINE_COMMENT; + + fTokenOffset = fOffset - 4; + fCurrentLength = 4; + } + break; + case '-': + if (fContentType == IPHPPartitions.HTML_MULTILINE_COMMENT + && checkPattern(new char[] { '-', '>' })) { + fContentType = IPHPPartitions.HTML; + partitionBorder = true; + return getToken(IPHPPartitions.HTML_MULTILINE_COMMENT); + } + break; + case '{': // SMARTY code starts here ? + if (fFileType == IPHPPartitions.SMARTY_FILE) { + if ((c = read()) == '*') { + if (DEBUG) { + System.out.println("SMARTYDOC_TOKEN start " + + fTokenOffset + " fContentType=" + + fContentType + " fLength=" + fLength + + " fOffset=" + fOffset + + " fCurrentLength=" + fCurrentLength); + } + if (fContentType != IPHPPartitions.SMARTY_MULTILINE_COMMENT + && fCurrentLength > 2) { + // SMARTY doc code starts here + unread(2); + IToken token = getToken(fContentType); + fContentType = IPHPPartitions.SMARTY_MULTILINE_COMMENT; + return token; + // } else if (fContentType == + // IPHPPartitionScannerConstants.HTML && fOffset == + // 2) { + // fContentType = + // IPHPPartitionScannerConstants.SMARTY_MULTILINE_COMMENT; + } else { // if (fContentType == + // IPHPPartitionScannerConstants.SMARTY_MULTILINE_COMMENT) + // { + fContentType = IPHPPartitions.SMARTY_MULTILINE_COMMENT; + fTokenOffset = fOffset - 2; + fCurrentLength = 2; + } + break; + } + if (DEBUG) { + System.out.println("SMARTY_TOKEN start " + fTokenOffset + + " fContentType=" + fContentType + " fLength=" + + fLength + " fOffset=" + fOffset); + } + if (c != ICharacterScanner.EOF) { + unread(); + } + if (fContentType != IPHPPartitions.SMARTY + && fCurrentLength > 1) { + unread(1); + IToken token = getToken(fContentType); + fContentType = IPHPPartitions.SMARTY; + return token; + // } else if (fContentType == + // IPHPPartitionScannerConstants.HTML && fOffset==1) { + // fContentType = IPHPPartitionScannerConstants.SMARTY; + } else { + fContentType = IPHPPartitions.SMARTY; + fTokenOffset = fOffset - 1; + fCurrentLength = 1; + } + } + break; + case '}': // SMARTY code ends here ? + if (fFileType == IPHPPartitions.SMARTY_FILE + && fContentType == IPHPPartitions.SMARTY) { + if (DEBUG) { + System.out.println("SMARTY_TOKEN end " + fTokenOffset + + " fContentType=" + fContentType + " fLength=" + + fLength + " fOffset=" + fOffset); + } + fContentType = IPHPPartitions.HTML; + partitionBorder = true; + return getToken(IPHPPartitions.SMARTY); + } + break; + // case '/' : + // if (!isInString(IPHPPartitions.PHP_PARTITIONING) && (c = read()) + // == '*') { // MULTINE COMMENT JAVASCRIPT, CSS, PHP + // if (fContentType == IPHPPartitions.PHP_PARTITIONING && + // fCurrentLength > 2) { + // unread(2); + // IToken token = getToken(fContentType); + // fContentType = IPHPPartitions.PHP_PHPDOC_COMMENT; + // return token; + // } else if (fContentType == IPHPPartitions.PHP_PHPDOC_COMMENT) { + // fTokenOffset = fOffset - 2; + // fCurrentLength = 2; + // } + // + // } else if (!isInString(IPHPPartitions.PHP_PARTITIONING) && c != + // ICharacterScanner.EOF) + // unread(); + // break; + case '*': + if (fFileType == IPHPPartitions.SMARTY_FILE + && (c = read()) == '}') { + if (DEBUG) { + System.out.println("SMARTYDOC_TOKEN end " + + fTokenOffset + " fContentType=" + + fContentType + " fLength=" + fLength + + " fOffset=" + fOffset); + } + if (fContentType == IPHPPartitions.SMARTY_MULTILINE_COMMENT) { + fContentType = IPHPPartitions.HTML; + partitionBorder = true; + return getToken(IPHPPartitions.SMARTY_MULTILINE_COMMENT); + } + } + break; + case '\'': + if (!fInDoubString) + fInString = !fInString; + break; + case '"': + // toggle String mode + if (!fInString) + fInDoubString = !fInDoubString; + break; + } + } // end of file reached but we have to return the + // last partition. + return getToken(fContentType); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.rules.ITokenScanner#setRange(org.eclipse.jface.text.IDocument, + * int, int) + */ + public void setRange(IDocument document, int offset, int length) { + if (DEBUG) { + System.out.println("SET RANGE: offset=" + offset + " length=" + + length); + } + + fDocument = document; + fOffset = offset; + fTokenOffset = offset; + fCurrentLength = 0; + fLength = 0; + fEnd = fOffset + length; + fInString = false; + fInDoubString = false; + fContentType = IPHPPartitions.HTML; + // String[] prev = getPartitionStack(offset); + } + + private int read() { + try { + if (fOffset < fEnd) { + fCurrentLength++; + return fDocument.getChar(fOffset++); + } + return ICharacterScanner.EOF; + } catch (BadLocationException e) { + // should never happen + // TODO write stacktrace to log + fOffset = fEnd; + return ICharacterScanner.EOF; + } + } + + private void unread() { + --fOffset; + --fCurrentLength; + } + + private void unread(int num) { + fOffset -= num; + fCurrentLength -= num; + } + + private boolean checkPattern(char[] pattern) { + return checkPattern(pattern, false); + } + + /** + * Check if next character sequence read from document is equals to the + * provided pattern. Pattern is read from left to right until the first + * character read doesn't match. If this happens all read characters are + * unread. + * + * @param pattern + * The pattern to check. + * @return true if pattern is equals else returns + * false. + */ + private boolean checkPattern(char[] pattern, boolean ignoreCase) { + int prevOffset = fOffset; + int prevLength = fCurrentLength; + for (int i = 0; i < pattern.length; i++) { + int c = read(); + + if (c == ICharacterScanner.EOF + || !letterEquals(c, pattern[i], ignoreCase)) { + fOffset = prevOffset; + fCurrentLength = prevLength; + return false; + } + } + + return true; + } + + private boolean letterEquals(int test, char letter, boolean ignoreCase) { + if (test == letter) + return true; + else if (ignoreCase && Character.isLowerCase(letter) + && test == Character.toUpperCase(letter)) + return true; + else if (ignoreCase && Character.isUpperCase(letter) + && test == Character.toLowerCase(letter)) + return true; + + return false; + } + + /** + * Checks wether the offset is in a String and the specified + * contenttype is the current content type. Strings are delimited, mutual + * exclusive, by a " or by a '. + * + * @param contentType + * The contenttype to check. + * @return true if the current offset is in a string else + * returns false. + */ + private boolean isInString(String contentType) { + if (fContentType == contentType) + return (fInString || fInDoubString); + else + return false; + } + + /** + * Returns the previouse partition stack for the given offset. + * + * @param offset + * The offset to return the previouse partitionstack for. + * + * @return The stack as a string array. + */ + private String[] getPartitionStack(int offset) { + ArrayList types = new ArrayList(); + int tmpOffset = 0; + try { + ITypedRegion region = fDocument.getPartition(offset); + tmpOffset = region.getOffset(); + while (tmpOffset - 1 > 0) { + region = fDocument.getPartition(tmpOffset - 1); + tmpOffset = region.getOffset(); + types.add(0, region.getType()); + } + } catch (BadLocationException e) { + if (DEBUG) { + e.printStackTrace(); + } + } + + String[] retVal = new String[types.size()]; + + retVal = (String[]) types.toArray(retVal); + return retVal; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLWordExtractor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLWordExtractor.java index 7c950b0..9968341 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLWordExtractor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLWordExtractor.java @@ -1,14 +1,14 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html -Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de -**********************************************************************/ + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ package net.sourceforge.phpeclipse.phpeditor.php; import net.sourceforge.phpdt.internal.compiler.parser.Scanner; @@ -22,67 +22,70 @@ import org.eclipse.swt.graphics.Point; */ public class HTMLWordExtractor { - /** - * Find the location of the word at offset in document. - * @returns Point - x is the start position, y is the end position. - * Return null if it is not found. - * @param document the document being searched. - * @param offset - the position to start searching from. - */ - public static Point findWord(IDocument document, int offset) { + /** + * Find the location of the word at offset in document. + * + * @returns Point - x is the start position, y is the end position. Return + * null if it is not found. + * @param document + * the document being searched. + * @param offset - + * the position to start searching from. + */ + public static Point findWord(IDocument document, int offset) { - int start = -1; - int end = -1; + int start = -1; + int end = -1; - try { + try { - int position = offset; - char character = ' '; + int position = offset; + char character = ' '; - while (position >= 0) { - character = document.getChar(position); - if (!Scanner.isPHPIdentifierPart(character)) - break; - --position; - } - if ((position > 0) && (character == '<')) { - --position; - } - if ((position > 1) && (character == '/')) { - character = document.getChar(position - 1); - if (character == '<') { - --position; - --position; - } - } - if (position==offset) { - return null; - } + while (position >= 0) { + character = document.getChar(position); + if (!Scanner.isPHPIdentifierPart(character)) + break; + --position; + } + if ((position > 0) && (character == '<')) { + --position; + } + if ((position > 1) && (character == '/')) { + character = document.getChar(position - 1); + if (character == '<') { + --position; + --position; + } + } + if (position == offset) { + return null; + } - start = position; + start = position; - position = offset; - int length = document.getLength(); - character = ' '; + position = offset; + int length = document.getLength(); + character = ' '; - while (position < length) { - character = document.getChar(position); - if (!Scanner.isPHPIdentifierPart(character)) - break; - ++position; - } - if ((position < length) && (character == '>')) { - ++position; - } - start++; - end = position; + while (position < length) { + character = document.getChar(position); + if (!Scanner.isPHPIdentifierPart(character)) + break; + ++position; + } + if ((position < length) && (character == '>')) { + ++position; + } + start++; + end = position; - if (end > start) - return new Point(start, end - start); + if (end > start) + return new Point(start, end - start); - } catch (BadLocationException x) { - } + } catch (BadLocationException x) { + } - return null; - } + return null; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPAutoIndentStrategy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPAutoIndentStrategy.java index f2956f0..0283480 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPAutoIndentStrategy.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPAutoIndentStrategy.java @@ -1,14 +1,14 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html -Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de -**********************************************************************/ + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ package net.sourceforge.phpeclipse.phpeditor.php; import org.eclipse.jface.text.BadLocationException; @@ -24,8 +24,8 @@ public class PHPAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy { public PHPAutoIndentStrategy() { } - /* (non-Javadoc) - * Method declared on IAutoIndentStrategy + /* + * (non-Javadoc) Method declared on IAutoIndentStrategy */ public void customizeDocumentCommand(IDocument d, DocumentCommand c) { if (c.length == 0 && c.text != null && endsWithDelimiter(d, c.text)) @@ -36,13 +36,14 @@ public class PHPAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy { } /** - * Returns whether or not the text ends with one of the given search strings. + * Returns whether or not the text ends with one of the given search + * strings. */ private boolean endsWithDelimiter(IDocument d, String txt) { - String[] delimiters= d.getLegalLineDelimiters(); + String[] delimiters = d.getLegalLineDelimiters(); - for (int i= 0; i < delimiters.length; i++) { + for (int i = 0; i < delimiters.length; i++) { if (txt.endsWith(delimiters[i])) return true; } @@ -52,103 +53,123 @@ public class PHPAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy { /** * Returns the line number of the next bracket after end. + * * @returns the line number of the next matching bracket after end - * @param document - the document being parsed - * @param line - the line to start searching back from - * @param end - the end position to search back from - * @param closingBracketIncrease - the number of brackets to skip + * @param document - + * the document being parsed + * @param line - + * the line to start searching back from + * @param end - + * the end position to search back from + * @param closingBracketIncrease - + * the number of brackets to skip */ - protected int findMatchingOpenBracket(IDocument document, int line, int end, int closingBracketIncrease) throws BadLocationException { + protected int findMatchingOpenBracket(IDocument document, int line, + int end, int closingBracketIncrease) throws BadLocationException { - int start= document.getLineOffset(line); - int brackcount= getBracketCount(document, start, end, false) - closingBracketIncrease; + int start = document.getLineOffset(line); + int brackcount = getBracketCount(document, start, end, false) + - closingBracketIncrease; - // sum up the brackets counts of each line (closing brackets count negative, + // sum up the brackets counts of each line (closing brackets count + // negative, // opening positive) until we find a line the brings the count to zero while (brackcount < 0) { line--; if (line < 0) { return -1; } - start= document.getLineOffset(line); - end= start + document.getLineLength(line) - 1; + start = document.getLineOffset(line); + end = start + document.getLineLength(line) - 1; brackcount += getBracketCount(document, start, end, false); } return line; } /** - * Returns the bracket value of a section of text. Closing brackets have a value of -1 and - * open brackets have a value of 1. + * Returns the bracket value of a section of text. Closing brackets have a + * value of -1 and open brackets have a value of 1. + * * @returns the line number of the next matching bracket after end - * @param document - the document being parsed - * @param start - the start position for the search - * @param end - the end position for the search - * @param ignoreCloseBrackets - whether or not to ignore closing brackets in the count + * @param document - + * the document being parsed + * @param start - + * the start position for the search + * @param end - + * the end position for the search + * @param ignoreCloseBrackets - + * whether or not to ignore closing brackets in the count */ - private int getBracketCount(IDocument document, int start, int end, boolean ignoreCloseBrackets) throws BadLocationException { + private int getBracketCount(IDocument document, int start, int end, + boolean ignoreCloseBrackets) throws BadLocationException { int begin = start; - int bracketcount= 0; + int bracketcount = 0; while (begin < end) { - char curr= document.getChar(begin); + char curr = document.getChar(begin); begin++; switch (curr) { - case '/' : - if (begin < end) { - char next= document.getChar(begin); - if (next == '*') { - // a comment starts, advance to the comment end - begin= getCommentEnd(document, begin + 1, end); - } else if (next == '/') { - // '//'-comment: nothing to do anymore on this line - begin= end; - } + case '/': + if (begin < end) { + char next = document.getChar(begin); + if (next == '*') { + // a comment starts, advance to the comment end + begin = getCommentEnd(document, begin + 1, end); + } else if (next == '/') { + // '//'-comment: nothing to do anymore on this line + begin = end; } - break; - case '*' : - if (begin < end) { - char next= document.getChar(begin); - if (next == '/') { - // we have been in a comment: forget what we read before - bracketcount= 0; - begin++; - } - } - break; - case '{' : - bracketcount++; - ignoreCloseBrackets= false; - break; - case '}' : - if (!ignoreCloseBrackets) { - bracketcount--; - } - break; - case '"' : - case '\'' : - begin= getStringEnd(document, begin, end, curr); - break; - default : + } + break; + case '*': + if (begin < end) { + char next = document.getChar(begin); + if (next == '/') { + // we have been in a comment: forget what we read before + bracketcount = 0; + begin++; } + } + break; + case '{': + bracketcount++; + ignoreCloseBrackets = false; + break; + case '}': + if (!ignoreCloseBrackets) { + bracketcount--; + } + break; + case '"': + case '\'': + begin = getStringEnd(document, begin, end, curr); + break; + default: + } } return bracketcount; } /** * Returns the end position a comment starting at pos. + * * @returns the end position a comment starting at pos - * @param document - the document being parsed - * @param position - the start position for the search - * @param end - the end position for the search + * @param document - + * the document being parsed + * @param position - + * the start position for the search + * @param end - + * the end position for the search */ - private int getCommentEnd(IDocument document, int position, int end) throws BadLocationException { + private int getCommentEnd(IDocument document, int position, int end) + throws BadLocationException { int currentPosition = position; while (currentPosition < end) { - char curr= document.getChar(currentPosition); + char curr = document.getChar(currentPosition); currentPosition++; if (curr == '*') { - if (currentPosition < end && document.getChar(currentPosition) == '/') { + if (currentPosition < end + && document.getChar(currentPosition) == '/') { return currentPosition + 1; } } @@ -158,15 +179,19 @@ public class PHPAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy { /** * Returns the String at line with the leading whitespace removed. + * * @returns the String at line with the leading whitespace removed. - * @param document - the document being parsed - * @param line - the line being searched + * @param document - + * the document being parsed + * @param line - + * the line being searched */ - protected String getIndentOfLine(IDocument document, int line) throws BadLocationException { + protected String getIndentOfLine(IDocument document, int line) + throws BadLocationException { if (line > -1) { - int start= document.getLineOffset(line); - int end= start + document.getLineLength(line) - 1; - int whiteend= findEndOfWhiteSpace(document, start, end); + int start = document.getLineOffset(line); + int end = start + document.getLineLength(line) - 1; + int whiteend = findEndOfWhiteSpace(document, start, end); return document.get(start, whiteend - start); } else { return ""; //$NON-NLS-1$ @@ -175,16 +200,22 @@ public class PHPAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy { /** * Returns the position of the character in the document after position. + * * @returns the next location of character. - * @param document - the document being parsed - * @param position - the position to start searching from - * @param end - the end of the document - * @param character - the character you are trying to match + * @param document - + * the document being parsed + * @param position - + * the position to start searching from + * @param end - + * the end of the document + * @param character - + * the character you are trying to match */ - private int getStringEnd(IDocument document, int position, int end, char character) throws BadLocationException { + private int getStringEnd(IDocument document, int position, int end, + char character) throws BadLocationException { int currentPosition = position; while (currentPosition < end) { - char currentCharacter= document.getChar(currentPosition); + char currentCharacter = document.getChar(currentPosition); currentPosition++; if (currentCharacter == '\\') { // ignore escaped characters @@ -197,82 +228,106 @@ public class PHPAutoIndentStrategy extends DefaultIndentLineAutoEditStrategy { } /** - * Set the indent of a new line based on the command provided in the supplied document. - * @param document - the document being parsed - * @param command - the command being performed + * Set the indent of a new line based on the command provided in the + * supplied document. + * + * @param document - + * the document being parsed + * @param command - + * the command being performed */ - protected void smartIndentAfterNewLine(IDocument document, DocumentCommand command) { + protected void smartIndentAfterNewLine(IDocument document, + DocumentCommand command) { - int docLength= document.getLength(); + int docLength = document.getLength(); if (command.offset == -1 || docLength == 0) return; try { - int p= (command.offset == docLength ? command.offset - 1 : command.offset); - int line= document.getLineOfOffset(p); + int p = (command.offset == docLength ? command.offset - 1 + : command.offset); + int line = document.getLineOfOffset(p); - StringBuffer buf= new StringBuffer(command.text); - if (command.offset < docLength && document.getChar(command.offset) == '}') { - int indLine= findMatchingOpenBracket(document, line, command.offset, 0); + StringBuffer buf = new StringBuffer(command.text); + if (command.offset < docLength + && document.getChar(command.offset) == '}') { + int indLine = findMatchingOpenBracket(document, line, + command.offset, 0); if (indLine == -1) { - indLine= line; + indLine = line; } buf.append(getIndentOfLine(document, indLine)); } else { - int start= document.getLineOffset(line); - int whiteend= findEndOfWhiteSpace(document, start, command.offset); + int start = document.getLineOffset(line); + int whiteend = findEndOfWhiteSpace(document, start, + command.offset); int offset = -1; -// if (command.offset > 0 && command.offset < docLength && document.getChar(command.offset-1) == '{') { -// offset = command.offset; -// } + // if (command.offset > 0 && command.offset < docLength && + // document.getChar(command.offset-1) == '{') { + // offset = command.offset; + // } buf.append(document.get(start, whiteend - start)); if (getBracketCount(document, start, command.offset, true) > 0) { buf.append('\t'); } -// if (offset >= 0) { -// buf.append('}'); -// } + // if (offset >= 0) { + // buf.append('}'); + // } } - command.text= buf.toString(); + command.text = buf.toString(); } catch (BadLocationException excp) { - System.out.println(PHPEditorMessages.getString("AutoIndent.error.bad_location_1")); //$NON-NLS-1$ + System.out.println(PHPEditorMessages + .getString("AutoIndent.error.bad_location_1")); //$NON-NLS-1$ } } /** - * Set the indent of a bracket based on the command provided in the supplied document. - * @param document - the document being parsed - * @param command - the command being performed + * Set the indent of a bracket based on the command provided in the supplied + * document. + * + * @param document - + * the document being parsed + * @param command - + * the command being performed */ - protected void smartInsertAfterBracket(IDocument document, DocumentCommand command) { + protected void smartInsertAfterBracket(IDocument document, + DocumentCommand command) { if (command.offset == -1 || document.getLength() == 0) return; try { - int p= (command.offset == document.getLength() ? command.offset - 1 : command.offset); - int line= document.getLineOfOffset(p); - int start= document.getLineOffset(line); - int whiteend= findEndOfWhiteSpace(document, start, command.offset); + int p = (command.offset == document.getLength() ? command.offset - 1 + : command.offset); + int line = document.getLineOfOffset(p); + int start = document.getLineOffset(line); + int whiteend = findEndOfWhiteSpace(document, start, command.offset); - // shift only when line does not contain any text up to the closing bracket + // shift only when line does not contain any text up to the closing + // bracket if (whiteend == command.offset) { - // evaluate the line with the opening bracket that matches out closing bracket - int indLine= findMatchingOpenBracket(document, line, command.offset, 1); + // evaluate the line with the opening bracket that matches out + // closing bracket + int indLine = findMatchingOpenBracket(document, line, + command.offset, 1); if (indLine != -1 && indLine != line) { // take the indent of the found line - StringBuffer replaceText= new StringBuffer(getIndentOfLine(document, indLine)); - // add the rest of the current line including the just added close bracket - replaceText.append(document.get(whiteend, command.offset - whiteend)); + StringBuffer replaceText = new StringBuffer( + getIndentOfLine(document, indLine)); + // add the rest of the current line including the just added + // close bracket + replaceText.append(document.get(whiteend, command.offset + - whiteend)); replaceText.append(command.text); // modify document command - command.length= command.offset - start; - command.offset= start; - command.text= replaceText.toString(); + command.length = command.offset - start; + command.offset = start; + command.text = replaceText.toString(); } } } catch (BadLocationException excp) { - System.out.println(PHPEditorMessages.getString("AutoIndent.error.bad_location_2")); //$NON-NLS-1$ + System.out.println(PHPEditorMessages + .getString("AutoIndent.error.bad_location_2")); //$NON-NLS-1$ } } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPCodeScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPCodeScanner.java index eaa7e44..410e0c1 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPCodeScanner.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPCodeScanner.java @@ -41,14 +41,15 @@ public class PHPCodeScanner extends AbstractJavaScanner { /** * Rule to detect java operators. - * + * * @since 3.0 */ protected class OperatorRule implements IRule { /** Java operators */ - private final char[] PHP_OPERATORS = { ';', '(', ')', '.', '=', '/', '\\', '+', '-', '*', '[', ']', '<', '>', ':', '?', '!', - ',', '|', '&', '^', '%', '~', '@' }; + private final char[] PHP_OPERATORS = { ';', '(', ')', '.', '=', '/', + '\\', '+', '-', '*', '[', ']', '<', '>', ':', '?', '!', ',', + '|', '&', '^', '%', '~', '@' }; /** Token to return for this rule */ private final IToken fToken; @@ -61,13 +62,14 @@ public class PHPCodeScanner extends AbstractJavaScanner { /** * Creates a new operator rule. - * + * * @param token - * Token to use for this rule + * Token to use for this rule * @param tokenHeredoc - * TODO + * TODO */ - public OperatorRule(IToken token, IToken tokenBraces, IToken tokenHeredoc) { + public OperatorRule(IToken token, IToken tokenBraces, + IToken tokenHeredoc) { fToken = token; fTokenBraces = tokenBraces; fTokenHeredoc = tokenHeredoc; @@ -75,9 +77,9 @@ public class PHPCodeScanner extends AbstractJavaScanner { /** * Is this character an operator character? - * + * * @param character - * Character to determine whether it is an operator character + * Character to determine whether it is an operator character * @return true iff the character is an operator, * false otherwise. */ @@ -101,7 +103,8 @@ public class PHPCodeScanner extends AbstractJavaScanner { if (isOperator((char) character)) { int lastCharacter = character; character = scanner.read(); - // the readHEREDOC(scanner) call doesn't work, if we have our own partitions for single quoted + // the readHEREDOC(scanner) call doesn't work, if we have our + // own partitions for single quoted // or double quoted strings: // // if (lastCharacter == '<' && character == '<') { @@ -185,15 +188,16 @@ public class PHPCodeScanner extends AbstractJavaScanner { // } /** - * Check if lastCharacter/character are a PHP start or end token ( <? ... - * ?> ) - * + * Check if lastCharacter/character are a PHP start or end token ( <? + * ... ?> ) + * * @param scanner * @param lastCharacter * @param character * @return */ - private boolean checkPHPTag(ICharacterScanner scanner, int lastCharacter, int character) { + private boolean checkPHPTag(ICharacterScanner scanner, + int lastCharacter, int character) { if (lastCharacter == '<' && character == '?') { scanner.unread(); scanner.unread(); @@ -259,12 +263,13 @@ public class PHPCodeScanner extends AbstractJavaScanner { /** * 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 null + * the word this rule will search for, may not be + * null * @param token - * the token to be returned if the word has been found, may not be - * null + * the token to be returned if the word has been found, may + * not be null */ public void addWordIgnoreCase(String word, IToken token) { Assert.isNotNull(word); @@ -325,7 +330,8 @@ public class PHPCodeScanner extends AbstractJavaScanner { if (c == '$') { isVariable = true; } - if (fColumn == UNDEFINED || (fColumn == scanner.getColumn() - 1)) { + if (fColumn == UNDEFINED + || (fColumn == scanner.getColumn() - 1)) { fBuffer.setLength(0); fBuffer.append((char) c); @@ -333,7 +339,8 @@ public class PHPCodeScanner extends AbstractJavaScanner { if (c == '_') { isUnderscore = true; } - while (c != ICharacterScanner.EOF && fDetector.isWordPart((char) c)) { + while (c != ICharacterScanner.EOF + && fDetector.isWordPart((char) c)) { fBuffer.append((char) c); c = scanner.read(); } @@ -368,17 +375,26 @@ public class PHPCodeScanner extends AbstractJavaScanner { // private PHPColorProvider fColorProvider; - private static String[] fgTokenProperties = { IPreferenceConstants.PHP_MULTILINE_COMMENT, - IPreferenceConstants.PHP_SINGLELINE_COMMENT, IPreferenceConstants.PHP_TAG, IPreferenceConstants.PHP_KEYWORD, - IPreferenceConstants.PHP_FUNCTIONNAME, IPreferenceConstants.PHP_VARIABLE, IPreferenceConstants.PHP_VARIABLE_DOLLAR, - IPreferenceConstants.PHP_STRING_DQ, IPreferenceConstants.PHP_STRING_SQ, IPreferenceConstants.PHP_TYPE, - IPreferenceConstants.PHP_CONSTANT, IPreferenceConstants.PHP_DEFAULT, IPreferenceConstants.PHP_OPERATOR, - IPreferenceConstants.PHP_BRACE_OPERATOR, IPreferenceConstants.PHP_KEYWORD_RETURN }; + private static String[] fgTokenProperties = { + IPreferenceConstants.PHP_MULTILINE_COMMENT, + IPreferenceConstants.PHP_SINGLELINE_COMMENT, + IPreferenceConstants.PHP_TAG, IPreferenceConstants.PHP_KEYWORD, + IPreferenceConstants.PHP_FUNCTIONNAME, + IPreferenceConstants.PHP_VARIABLE, + IPreferenceConstants.PHP_VARIABLE_DOLLAR, + IPreferenceConstants.PHP_STRING_DQ, + IPreferenceConstants.PHP_STRING_SQ, IPreferenceConstants.PHP_TYPE, + IPreferenceConstants.PHP_CONSTANT, + IPreferenceConstants.PHP_DEFAULT, + IPreferenceConstants.PHP_OPERATOR, + IPreferenceConstants.PHP_BRACE_OPERATOR, + IPreferenceConstants.PHP_KEYWORD_RETURN }; /** * Creates a PHP code scanner */ - // public PHPCodeScanner(JavaColorManager provider, IPreferenceStore store) { + // public PHPCodeScanner(JavaColorManager provider, IPreferenceStore store) + // { public PHPCodeScanner(IColorManager manager, IPreferenceStore store) { super(manager, store); initialize(); @@ -435,7 +451,8 @@ public class PHPCodeScanner extends AbstractJavaScanner { wordRule.addWord(name, keyword); } } else if (elbuffer instanceof PHPFunction) { - wordRule.addWordIgnoreCase(((PHPFunction) elbuffer).getName(), functionName); + wordRule.addWordIgnoreCase(((PHPFunction) elbuffer).getName(), + functionName); } else if (elbuffer instanceof PHPType) { wordRule.addWord(elbuffer.getName(), type); } else if (elbuffer instanceof PHPConstant) { @@ -448,7 +465,8 @@ public class PHPCodeScanner extends AbstractJavaScanner { wordRule.addWord("return", token); // Add rule for operators and brackets (at the end !) - rules.add(new OperatorRule(getToken(IPreferenceConstants.PHP_OPERATOR), getToken(IPreferenceConstants.PHP_BRACE_OPERATOR), + rules.add(new OperatorRule(getToken(IPreferenceConstants.PHP_OPERATOR), + getToken(IPreferenceConstants.PHP_BRACE_OPERATOR), getToken(IPreferenceConstants.PHP_STRING_DQ))); rules.add(wordRule); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPCompletionProcessor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPCompletionProcessor.java index cce63ca..4f364ff 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPCompletionProcessor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPCompletionProcessor.java @@ -110,7 +110,8 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { // return false; // } // }; - private static class ContextInformationWrapper implements IContextInformation, IContextInformationExtension { + private static class ContextInformationWrapper implements + IContextInformation, IContextInformationExtension { private final IContextInformation fContextInformation; private int fPosition; @@ -152,31 +153,31 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { } }; -// private class TableName { -// String fTableName; -// -// TableName() { -// fTableName = null; -// } -// -// /** -// * @return Returns the tableName. -// */ -// public String getTableName() { -// if (fTableName == null) { -// return ""; -// } -// return fTableName; -// } -// -// /** -// * @param tableName -// * The tableName to set. -// */ -// public void setTableName(String tableName) { -// fTableName = tableName; -// } -// } + // private class TableName { + // String fTableName; + // + // TableName() { + // fTableName = null; + // } + // + // /** + // * @return Returns the tableName. + // */ + // public String getTableName() { + // if (fTableName == null) { + // return ""; + // } + // return fTableName; + // } + // + // /** + // * @param tableName + // * The tableName to set. + // */ + // public void setTableName(String tableName) { + // fTableName = tableName; + // } + // } private char[] fProposalAutoActivationSet; @@ -193,7 +194,8 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { public PHPCompletionProcessor(IEditorPart editor) { fEditor = editor; fManager = PHPeclipsePlugin.getDefault().getWorkingCopyManager(); - TemplateContextType contextType = PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType("php"); //$NON-NLS-1$ + TemplateContextType contextType = PHPeclipsePlugin.getDefault() + .getTemplateContextRegistry().getContextType("php"); //$NON-NLS-1$ if (contextType != null) fTemplateEngine = new TemplateEngine(contextType); fComparator = new PHPCompletionProposalComparator(); @@ -201,9 +203,9 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { /** * Tells this processor to order the proposals alphabetically. - * + * * @param order - * true if proposals should be ordered. + * true if proposals should be ordered. */ public void orderProposalsAlphabetically(boolean order) { fComparator.setOrderAlphabetically(order); @@ -212,27 +214,32 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { /** * Sets this processor's set of characters triggering the activation of the * completion proposal computation. - * + * * @param activationSet - * the activation set + * the activation set */ - public void setCompletionProposalAutoActivationCharacters(char[] activationSet) { + public void setCompletionProposalAutoActivationCharacters( + char[] activationSet) { fProposalAutoActivationSet = activationSet; } /* * (non-Javadoc) Method declared on IContentAssistProcessor */ - public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) { - int contextInformationPosition = guessContextInformationPosition(viewer, documentOffset); - return internalComputeCompletionProposals(viewer, documentOffset, contextInformationPosition); + public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, + int documentOffset) { + int contextInformationPosition = guessContextInformationPosition( + viewer, documentOffset); + return internalComputeCompletionProposals(viewer, documentOffset, + contextInformationPosition); } - private int getLastToken(List list, ITextViewer viewer, int completionPosition, JavaContext context) { -// TableName tableName) { + private int getLastToken(List list, ITextViewer viewer, + int completionPosition, JavaContext context) { + // TableName tableName) { IDocument document = viewer.getDocument(); int start = context.getStart(); -// int end = context.getEnd(); + // int end = context.getEnd(); String startText; int lastSignificantToken = ITerminalSymbols.TokenNameEOF; try { @@ -261,8 +268,9 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { } int token = ITerminalSymbols.TokenNameEOF; // token = getLastSQLToken(startText); -// tableName.setTableName(getLastSQLTableName(startText)); - Scanner scanner = ToolFactory.createScanner(false, false, false); + // tableName.setTableName(getLastSQLTableName(startText)); + Scanner scanner = ToolFactory + .createScanner(false, false, false); scanner.setSource(startText.toCharArray()); scanner.setPHPMode(true); int beforeLastToken = ITerminalSymbols.TokenNameEOF; @@ -271,11 +279,14 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { try { token = scanner.getNextToken(); lastToken = token; - while (token != ITerminalSymbols.TokenNameERROR && token != ITerminalSymbols.TokenNameEOF) { + while (token != ITerminalSymbols.TokenNameERROR + && token != ITerminalSymbols.TokenNameEOF) { beforeLastToken = lastToken; if (token == ITerminalSymbols.TokenNameVariable) { ident = scanner.getCurrentTokenSource(); - if (ident.length == 5 && ident[0] == '$' && ident[1] == 't' && ident[2] == 'h' && ident[3] == 'i' && ident[4] == 's') { + if (ident.length == 5 && ident[0] == '$' + && ident[1] == 't' && ident[2] == 'h' + && ident[3] == 'i' && ident[4] == 's') { token = ITerminalSymbols.TokenNamethis_PHP_COMPLETION; } } @@ -319,165 +330,168 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { tableNameStart = currentCharacterPosition - 1; } else { if (!Scanner.isPHPIdentifierPart(ch)) { - return sqlText.substring(tableNameStart, currentCharacterPosition - 1); + return sqlText.substring(tableNameStart, + currentCharacterPosition - 1); } } } } catch (IndexOutOfBoundsException e) { if (tableNameStart >= 0) { - return sqlText.substring(tableNameStart, currentCharacterPosition - 1); + return sqlText.substring(tableNameStart, + currentCharacterPosition - 1); } } return ""; } -// private String getLastSQLTableName(String startText) { -// // scan for sql identifiers -// char ch = ' '; -// int currentSQLPosition = startText.length(); -// int identEnd = -1; -// String ident = null; -// try { -// while (true) { -// ch = startText.charAt(--currentSQLPosition); -// if (Scanner.isSQLIdentifierPart(ch)) { -// // if (ch >= 'A' && ch <= 'Z') { -// if (identEnd < 0) { -// identEnd = currentSQLPosition + 1; -// } -// // } else if (ch >= 'a' && ch <= 'z') { -// // if (identEnd < 0) { -// // identEnd = currentSQLPosition + 1; -// // } -// } else if (identEnd >= 0) { -// ident = startText.substring(currentSQLPosition + 1, identEnd); -// // select -- from -- where -- -// // update -- set -- where -- -// // insert into -- ( -- ) values ( -- ) -// if (ident.length() >= 4 && ident.length() <= 6) { -// ident = ident.toLowerCase(); -// switch (ident.length()) { -// // case 3 : -// // if (ident.equals("set")) { -// // // System.out.println("set"); -// // token = ITerminalSymbols.TokenNameSQLset; -// // return token; -// // } -// // break; -// case 4: -// if (ident.equals("from")) { -// // System.out.println("from"); -// return getSQLTableName(startText, identEnd); -// } else if (ident.equals("into")) { -// // System.out.println("into"); -// return getSQLTableName(startText, identEnd); -// } -// break; -// case 6: -// if (ident.equals("update")) { -// // System.out.println("update"); -// return getSQLTableName(startText, identEnd); -// } -// break; -// } -// } -// identEnd = -1; -// } else if (Character.isWhitespace(ch)) { -// } -// } -// } catch (IndexOutOfBoundsException e) { -// } -// return ""; -// } + // private String getLastSQLTableName(String startText) { + // // scan for sql identifiers + // char ch = ' '; + // int currentSQLPosition = startText.length(); + // int identEnd = -1; + // String ident = null; + // try { + // while (true) { + // ch = startText.charAt(--currentSQLPosition); + // if (Scanner.isSQLIdentifierPart(ch)) { + // // if (ch >= 'A' && ch <= 'Z') { + // if (identEnd < 0) { + // identEnd = currentSQLPosition + 1; + // } + // // } else if (ch >= 'a' && ch <= 'z') { + // // if (identEnd < 0) { + // // identEnd = currentSQLPosition + 1; + // // } + // } else if (identEnd >= 0) { + // ident = startText.substring(currentSQLPosition + 1, identEnd); + // // select -- from -- where -- + // // update -- set -- where -- + // // insert into -- ( -- ) values ( -- ) + // if (ident.length() >= 4 && ident.length() <= 6) { + // ident = ident.toLowerCase(); + // switch (ident.length()) { + // // case 3 : + // // if (ident.equals("set")) { + // // // System.out.println("set"); + // // token = ITerminalSymbols.TokenNameSQLset; + // // return token; + // // } + // // break; + // case 4: + // if (ident.equals("from")) { + // // System.out.println("from"); + // return getSQLTableName(startText, identEnd); + // } else if (ident.equals("into")) { + // // System.out.println("into"); + // return getSQLTableName(startText, identEnd); + // } + // break; + // case 6: + // if (ident.equals("update")) { + // // System.out.println("update"); + // return getSQLTableName(startText, identEnd); + // } + // break; + // } + // } + // identEnd = -1; + // } else if (Character.isWhitespace(ch)) { + // } + // } + // } catch (IndexOutOfBoundsException e) { + // } + // return ""; + // } /** * Detect the last significant SQL token in the text before the completion - * + * * @param startText */ -// private int getLastSQLToken(String startText) { -// int token; -// // scan for sql identifiers -// char ch = ' '; -// int currentSQLPosition = startText.length(); -// int identEnd = -1; -// String ident = null; -// try { -// while (true) { -// ch = startText.charAt(--currentSQLPosition); -// if (ch >= 'A' && ch <= 'Z') { -// if (identEnd < 0) { -// identEnd = currentSQLPosition + 1; -// } -// } else if (ch >= 'a' && ch <= 'z') { -// if (identEnd < 0) { -// identEnd = currentSQLPosition + 1; -// } -// } else if (identEnd >= 0) { -// ident = startText.substring(currentSQLPosition + 1, identEnd); -// // select -- from -- where -- -// // update -- set -- where -- -// // insert into -- ( -- ) values ( -- ) -// if (ident.length() >= 3 && ident.length() <= 6) { -// ident = ident.toLowerCase(); -// switch (ident.length()) { -// case 3: -// if (ident.equals("set")) { -// // System.out.println("set"); -// token = ITerminalSymbols.TokenNameSQLset; -// return token; -// } -// break; -// case 4: -// if (ident.equals("from")) { -// // System.out.println("from"); -// token = ITerminalSymbols.TokenNameSQLfrom; -// // getSQLTableName(); -// return token; -// } else if (ident.equals("into")) { -// // System.out.println("into"); -// token = ITerminalSymbols.TokenNameSQLinto; -// return token; -// } -// break; -// case 5: -// if (ident.equals("where")) { -// // System.out.println("where"); -// token = ITerminalSymbols.TokenNameSQLwhere; -// return token; -// } -// break; -// case 6: -// if (ident.equals("select")) { -// // System.out.println("select"); -// token = ITerminalSymbols.TokenNameSQLselect; -// return token; -// } else if (ident.equals("insert")) { -// // System.out.println("insert"); -// token = ITerminalSymbols.TokenNameSQLinsert; -// return token; -// } else if (ident.equals("update")) { -// // System.out.println("update"); -// token = ITerminalSymbols.TokenNameSQLupdate; -// return token; -// } else if (ident.equals("values")) { -// // System.out.println("values"); -// token = ITerminalSymbols.TokenNameSQLvalues; -// return token; -// } -// break; -// } -// } -// identEnd = -1; -// } -// } -// } catch (IndexOutOfBoundsException e) { -// } -// return ITerminalSymbols.TokenNameEOF; -// } - - private ICompletionProposal[] internalComputeCompletionProposals(ITextViewer viewer, int offset, int contextOffset) { - ICompilationUnit unit = fManager.getWorkingCopy(fEditor.getEditorInput()); + // private int getLastSQLToken(String startText) { + // int token; + // // scan for sql identifiers + // char ch = ' '; + // int currentSQLPosition = startText.length(); + // int identEnd = -1; + // String ident = null; + // try { + // while (true) { + // ch = startText.charAt(--currentSQLPosition); + // if (ch >= 'A' && ch <= 'Z') { + // if (identEnd < 0) { + // identEnd = currentSQLPosition + 1; + // } + // } else if (ch >= 'a' && ch <= 'z') { + // if (identEnd < 0) { + // identEnd = currentSQLPosition + 1; + // } + // } else if (identEnd >= 0) { + // ident = startText.substring(currentSQLPosition + 1, identEnd); + // // select -- from -- where -- + // // update -- set -- where -- + // // insert into -- ( -- ) values ( -- ) + // if (ident.length() >= 3 && ident.length() <= 6) { + // ident = ident.toLowerCase(); + // switch (ident.length()) { + // case 3: + // if (ident.equals("set")) { + // // System.out.println("set"); + // token = ITerminalSymbols.TokenNameSQLset; + // return token; + // } + // break; + // case 4: + // if (ident.equals("from")) { + // // System.out.println("from"); + // token = ITerminalSymbols.TokenNameSQLfrom; + // // getSQLTableName(); + // return token; + // } else if (ident.equals("into")) { + // // System.out.println("into"); + // token = ITerminalSymbols.TokenNameSQLinto; + // return token; + // } + // break; + // case 5: + // if (ident.equals("where")) { + // // System.out.println("where"); + // token = ITerminalSymbols.TokenNameSQLwhere; + // return token; + // } + // break; + // case 6: + // if (ident.equals("select")) { + // // System.out.println("select"); + // token = ITerminalSymbols.TokenNameSQLselect; + // return token; + // } else if (ident.equals("insert")) { + // // System.out.println("insert"); + // token = ITerminalSymbols.TokenNameSQLinsert; + // return token; + // } else if (ident.equals("update")) { + // // System.out.println("update"); + // token = ITerminalSymbols.TokenNameSQLupdate; + // return token; + // } else if (ident.equals("values")) { + // // System.out.println("values"); + // token = ITerminalSymbols.TokenNameSQLvalues; + // return token; + // } + // break; + // } + // } + // identEnd = -1; + // } + // } + // } catch (IndexOutOfBoundsException e) { + // } + // return ITerminalSymbols.TokenNameEOF; + // } + private ICompletionProposal[] internalComputeCompletionProposals( + ITextViewer viewer, int offset, int contextOffset) { + ICompilationUnit unit = fManager.getWorkingCopy(fEditor + .getEditorInput()); IDocument document = viewer.getDocument(); IFile file = null; IProject project = null; @@ -485,12 +499,11 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { PHPEditor editor = null; if (fEditor != null && (fEditor instanceof PHPEditor)) { editor = (PHPEditor) fEditor; - IEditorInput editorInput=editor.getEditorInput(); + IEditorInput editorInput = editor.getEditorInput(); if (editorInput instanceof IFileEditorInput) { file = ((IFileEditorInput) editorInput).getFile(); project = file.getProject(); - } - else { + } else { return new ICompletionProposal[0]; } } @@ -510,7 +523,7 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { // restrict auto activation for '>' character to '->' token try { - char ch = document.getChar(offset-1); + char ch = document.getChar(offset - 1); if (ch == '>') { for (int i = 0; i < fProposalAutoActivationSet.length; i++) { ch = fProposalAutoActivationSet[i]; @@ -528,24 +541,28 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { } } - JavaContextType phpContextType = (JavaContextType) PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType( - "php"); //$NON-NLS-1$ - JavaContext context = (JavaContext) phpContextType.createContext(document, offset, selection.y, unit); + JavaContextType phpContextType = (JavaContextType) PHPeclipsePlugin + .getDefault().getTemplateContextRegistry() + .getContextType("php"); //$NON-NLS-1$ + JavaContext context = (JavaContext) phpContextType.createContext( + document, offset, selection.y, unit); context.setVariable("selection", selectedText); //$NON-NLS-1$ String prefix = context.getKey(); HashMap methodVariables = null; // HashMap typeVariables = null; HashMap unitVariables = null; - ICompilationUnit compilationUnit = (ICompilationUnit) context.findEnclosingElement(IJavaElement.COMPILATION_UNIT); -// if (compilationUnit != null) { -// unitVariables = ((CompilationUnit) compilationUnit).variables; -// } - IType type = (IType) context.findEnclosingElement(IJavaElement.TYPE); - if (type != null) { -// typeVariables = ((SourceType) type).variables; - } - IMethod method = (IMethod) context.findEnclosingElement(IJavaElement.METHOD); + ICompilationUnit compilationUnit = (ICompilationUnit) context + .findEnclosingElement(IJavaElement.COMPILATION_UNIT); + // if (compilationUnit != null) { + // unitVariables = ((CompilationUnit) compilationUnit).variables; + // } + IType type = (IType) context.findEnclosingElement(IJavaElement.TYPE); + if (type != null) { + // typeVariables = ((SourceType) type).variables; + } + IMethod method = (IMethod) context + .findEnclosingElement(IJavaElement.METHOD); // if (method != null) { // methodVariables = ((SourceMethod) method).variables; // } @@ -559,23 +576,29 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { HashSet localVariables = new HashSet(); if (compilationUnit != null) { unitVariables = getUnitVariables(unitVariables, compilationUnit); - getVariableProposals(localVariables, viewer, project, context, unitVariables, lowerCasePrefix, 94); + getVariableProposals(localVariables, viewer, project, context, + unitVariables, lowerCasePrefix, 94); } if (method != null) { methodVariables = getMethodVariables(methodVariables, method); - getVariableProposals(localVariables, viewer, project, context, methodVariables, lowerCasePrefix, 99); + getVariableProposals(localVariables, viewer, project, context, + methodVariables, lowerCasePrefix, 99); } if (!localVariables.isEmpty()) { - localVariableResults = (IPHPCompletionProposal[]) localVariables.toArray(new IPHPCompletionProposal[localVariables.size()]); + localVariableResults = (IPHPCompletionProposal[]) localVariables + .toArray(new IPHPCompletionProposal[localVariables + .size()]); } } -// TableName sqlTable = new TableName(); + // TableName sqlTable = new TableName(); ArrayList list = new ArrayList(); list.add(null); - int lastSignificantToken = getLastToken(list, viewer, offset, context); //, sqlTable); + int lastSignificantToken = getLastToken(list, viewer, offset, context); // , + // sqlTable); boolean useClassMembers = (lastSignificantToken == ITerminalSymbols.TokenNameMINUS_GREATER) - || (lastSignificantToken == ITerminalSymbols.TokenNameVariable) || (lastSignificantToken == ITerminalSymbols.TokenNamenew) + || (lastSignificantToken == ITerminalSymbols.TokenNameVariable) + || (lastSignificantToken == ITerminalSymbols.TokenNamenew) || (lastSignificantToken == ITerminalSymbols.TokenNamethis_PHP_COMPLETION); if (fTemplateEngine != null) { @@ -593,23 +616,29 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { IPHPCompletionProposal[] declarationResults = new IPHPCompletionProposal[0]; if (project != null) { DeclarationEngine declarationEngine; - JavaContextType contextType = (JavaContextType) PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType( - "php"); //$NON-NLS-1$ + JavaContextType contextType = (JavaContextType) PHPeclipsePlugin + .getDefault().getTemplateContextRegistry() + .getContextType("php"); //$NON-NLS-1$ if (contextType != null) { - IdentifierIndexManager indexManager = PHPeclipsePlugin.getDefault().getIndexManager(project); + IdentifierIndexManager indexManager = PHPeclipsePlugin + .getDefault().getIndexManager(project); SortedMap sortedMap; - declarationEngine = new DeclarationEngine(project, contextType, lastSignificantToken, file); + declarationEngine = new DeclarationEngine(project, + contextType, lastSignificantToken, file); if (lastSignificantToken == ITerminalSymbols.TokenNamethis_PHP_COMPLETION) { // complete '$this->' sortedMap = indexManager.getIdentifiers(file); - declarationEngine.completeObject(viewer, offset, sortedMap, unit); + declarationEngine.completeObject(viewer, offset, + sortedMap, unit); } else { String typeRef = null; char[] varName = (char[]) list.get(0); if (varName != null) { if (method != null) { - methodVariables = getMethodVariables(methodVariables, method); - VariableInfo info = (VariableInfo) methodVariables.get(new String(varName)); + methodVariables = getMethodVariables( + methodVariables, method); + VariableInfo info = (VariableInfo) methodVariables + .get(new String(varName)); if (info != null && info.typeIdentifier != null) { typeRef = new String(info.typeIdentifier); } @@ -618,11 +647,13 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { if (typeRef != null) { // complete '$variable->' with type information sortedMap = indexManager.getIdentifiers(typeRef); - declarationEngine.completeObject(viewer, offset, sortedMap, unit); + declarationEngine.completeObject(viewer, offset, + sortedMap, unit); } else { // complete '$variable->' without type information sortedMap = indexManager.getIdentifierMap(); - declarationEngine.complete(viewer, offset, sortedMap, unit); + declarationEngine.complete(viewer, offset, + sortedMap, unit); } } declarationResults = declarationEngine.getResults(); @@ -633,8 +664,9 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { IPHPCompletionProposal[] builtinResults = new IPHPCompletionProposal[0]; if ((!useClassMembers) && syntaxbuffer != null) { BuiltInEngine builtinEngine; - JavaContextType contextType = (JavaContextType) PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType( - "php"); //$NON-NLS-1$ + JavaContextType contextType = (JavaContextType) PHPeclipsePlugin + .getDefault().getTemplateContextRegistry() + .getContextType("php"); //$NON-NLS-1$ if (contextType != null) { builtinEngine = new BuiltInEngine(contextType); builtinEngine.complete(viewer, offset, syntaxbuffer, unit); @@ -648,28 +680,40 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { // } // concatenate the result arrays IPHPCompletionProposal[] total; - total = new IPHPCompletionProposal[localVariableResults.length + templateResults.length + identifierResults.length + total = new IPHPCompletionProposal[localVariableResults.length + + templateResults.length + identifierResults.length + builtinResults.length + declarationResults.length];// + // sqlResults.length]; - System.arraycopy(templateResults, 0, total, 0, templateResults.length); - System.arraycopy(identifierResults, 0, total, templateResults.length, identifierResults.length); - System.arraycopy(builtinResults, 0, total, templateResults.length + identifierResults.length, builtinResults.length); - System.arraycopy(declarationResults, 0, total, templateResults.length + identifierResults.length + builtinResults.length, - declarationResults.length); + System.arraycopy(templateResults, 0, total, 0, + templateResults.length); + System.arraycopy(identifierResults, 0, total, + templateResults.length, identifierResults.length); + System.arraycopy(builtinResults, 0, total, templateResults.length + + identifierResults.length, builtinResults.length); + System.arraycopy(declarationResults, 0, total, + templateResults.length + identifierResults.length + + builtinResults.length, declarationResults.length); // System.arraycopy(sqlResults, 0, total, templateResults.length + // identifierResults.length + builtinResults.length // + declarationResults.length, sqlResults.length); - // System.arraycopy(localVariableResults, 0, total, templateResults.length + // System.arraycopy(localVariableResults, 0, total, + // templateResults.length // + identifierResults.length + builtinResults.length // + declarationResults.length + sqlResults.length, // localVariableResults.length); - System.arraycopy(localVariableResults, 0, total, templateResults.length + identifierResults.length + builtinResults.length - + declarationResults.length, localVariableResults.length); + System + .arraycopy(localVariableResults, 0, total, + templateResults.length + identifierResults.length + + builtinResults.length + + declarationResults.length, + localVariableResults.length); results = total; -// fNumberOfComputedResults = (results == null ? 0 : results.length); + // fNumberOfComputedResults = (results == null ? 0 : + // results.length); /* - * Order here and not in result collector to make sure that the order - * applies to all proposals and not just those of the compilation unit. + * Order here and not in result collector to make sure that the + * order applies to all proposals and not just those of the + * compilation unit. */ return order(results); } @@ -680,16 +724,20 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { * @param unitVariables * @param unit */ - private HashMap getUnitVariables(HashMap unitVariables, ICompilationUnit unit) { + private HashMap getUnitVariables(HashMap unitVariables, + ICompilationUnit unit) { if (unitVariables == null) { try { String unitText = unit.getSource(); unitVariables = new HashMap(); - ProblemReporter problemReporter = new ProblemReporter(DefaultErrorHandlingPolicies.exitAfterAllProblems(), - new CompilerOptions(JavaCore.getOptions()), new DefaultProblemFactory()); + ProblemReporter problemReporter = new ProblemReporter( + DefaultErrorHandlingPolicies.exitAfterAllProblems(), + new CompilerOptions(JavaCore.getOptions()), + new DefaultProblemFactory()); UnitParser parser = new UnitParser(problemReporter); - parser.compilationUnit = new CompilationUnitDeclaration(problemReporter, null, unitText.length()); + parser.compilationUnit = new CompilationUnitDeclaration( + problemReporter, null, unitText.length()); parser.parse(unitText, unitVariables); } catch (Exception e) { @@ -710,10 +758,13 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { try { String methodText = method.getSource(); methodVariables = new HashMap(); - ProblemReporter problemReporter = new ProblemReporter(DefaultErrorHandlingPolicies.exitAfterAllProblems(), - new CompilerOptions(JavaCore.getOptions()), new DefaultProblemFactory()); + ProblemReporter problemReporter = new ProblemReporter( + DefaultErrorHandlingPolicies.exitAfterAllProblems(), + new CompilerOptions(JavaCore.getOptions()), + new DefaultProblemFactory()); UnitParser parser = new UnitParser(problemReporter); - parser.compilationUnit = new CompilationUnitDeclaration(problemReporter, null, methodText.length()); + parser.compilationUnit = new CompilationUnitDeclaration( + problemReporter, null, methodText.length()); parser.parseFunction(methodText, methodVariables); } catch (Exception e) { // TODO Auto-generated catch block @@ -731,7 +782,8 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { * @param prefix * @return */ - private void getVariableProposals(HashSet localVariables, ITextViewer viewer, IProject project, JavaContext context, + private void getVariableProposals(HashSet localVariables, + ITextViewer viewer, IProject project, JavaContext context, HashMap variables, String prefix, int relevance) { // try { int start = context.getStart(); @@ -739,7 +791,8 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { IRegion region = new Region(start, end - start); // IMethod method = (IMethod) // context.findEnclosingElement(IJavaElement.METHOD); - // if (method != null && (method instanceof SourceMethod) && ((SourceMethod) + // if (method != null && (method instanceof SourceMethod) && + // ((SourceMethod) // method).variables != null) { // HashMap map = ((SourceMethod) method).variables; Set set = variables.keySet(); @@ -751,7 +804,8 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { if (varName.length() >= prefix.length()) { matchesVarName = true; for (int i = 0; i < prefix.length(); i++) { - if (prefix.charAt(i) != Character.toLowerCase(varName.charAt(i))) { + if (prefix.charAt(i) != Character.toLowerCase(varName + .charAt(i))) { matchesVarName = false; break; } @@ -759,10 +813,12 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { if (matchesVarName) { LocalVariableProposal prop; // if (varName.length == prefix.length()) { - // prop = new LocalVariableProposal(new String(varName), region, + // prop = new LocalVariableProposal(new String(varName), + // region, // viewer, relevance-10); // } else { - prop = new LocalVariableProposal(new String(varName), region, viewer, relevance); + prop = new LocalVariableProposal(new String(varName), + region, viewer, relevance); // } localVariables.add(prop); } @@ -803,7 +859,8 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { // } // } // } catch (Throwable e) { - // // ignore - Syntax exceptions could occur, if there are syntax errors ! + // // ignore - Syntax exceptions could occur, if there are syntax errors + // ! // } } @@ -816,7 +873,8 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { * @param sqlResults * @return */ - // private ICompletionProposal[] getSQLProposals(ITextViewer viewer, IProject + // private ICompletionProposal[] getSQLProposals(ITextViewer viewer, + // IProject // project, DocumentTemplateContext context, // String prefix, TableName sqlTable) { // ICompletionProposal[] sqlResults = new ICompletionProposal[0]; @@ -935,19 +993,25 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { /** * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int) */ - public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) { - int contextInformationPosition = guessContextInformationPosition(viewer, offset); + public IContextInformation[] computeContextInformation(ITextViewer viewer, + int offset) { + int contextInformationPosition = guessContextInformationPosition( + viewer, offset); List result = addContextInformations(viewer, contextInformationPosition); - return (IContextInformation[]) result.toArray(new IContextInformation[result.size()]); + return (IContextInformation[]) result + .toArray(new IContextInformation[result.size()]); } private List addContextInformations(ITextViewer viewer, int offset) { - ICompletionProposal[] proposals = internalComputeCompletionProposals(viewer, offset, -1); + ICompletionProposal[] proposals = internalComputeCompletionProposals( + viewer, offset, -1); List result = new ArrayList(); for (int i = 0; i < proposals.length; i++) { - IContextInformation contextInformation = proposals[i].getContextInformation(); + IContextInformation contextInformation = proposals[i] + .getContextInformation(); if (contextInformation != null) { - ContextInformationWrapper wrapper = new ContextInformationWrapper(contextInformation); + ContextInformationWrapper wrapper = new ContextInformationWrapper( + contextInformation); wrapper.setContextInformationPosition(offset); result.add(wrapper); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPConstant.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPConstant.java index 177bb6f..b77593b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPConstant.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPConstant.java @@ -1,30 +1,29 @@ package net.sourceforge.phpeclipse.phpeditor.php; - /** * @author Choochter - * + * * To change this generated comment edit the template variable "typecomment": - * Window>Preferences>Java>ObfuscatorIgnores. - * To enable and disable the creation of type comments go to - * Window>Preferences>Java>Code Generation. + * Window>Preferences>Java>ObfuscatorIgnores. To enable and disable the creation + * of type comments go to Window>Preferences>Java>Code Generation. */ public class PHPConstant extends PHPElement { - private String fDescription; - - public void setDescription(String description) { - this.fDescription = description; - } - public String getDescription() { - return this.fDescription; - } + private String fDescription; + + public void setDescription(String description) { + this.fDescription = description; + } + + public String getDescription() { + return this.fDescription; + } + + public String getHoverText() { + return super.getHoverText() + "
                                                      " + getDescription(); + } - public String getHoverText() { - return super.getHoverText()+"
                                                      "+getDescription(); - } - - public PHPConstant(String Name, String usage, String description) { - super(Name, usage); - setDescription(description); - } + public PHPConstant(String Name, String usage, String description) { + super(Name, usage); + setDescription(description); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPDocumentPartitioner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPDocumentPartitioner.java index 7a342c4..75728b9 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPDocumentPartitioner.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPDocumentPartitioner.java @@ -8,7 +8,7 @@ Contributors: Igor Malinin - initial contribution - $Id: PHPDocumentPartitioner.java,v 1.5 2005-10-09 12:05:31 axelcl Exp $ + $Id: PHPDocumentPartitioner.java,v 1.6 2006-10-21 23:18:33 pombredanne Exp $ **********************************************************************/ package net.sourceforge.phpeclipse.phpeditor.php; @@ -23,70 +23,70 @@ import org.eclipse.jface.text.IDocumentPartitioner; import org.eclipse.jface.text.rules.IPartitionTokenScanner; /** - * - * + * + * * @author Igor Malinin */ public class PHPDocumentPartitioner extends MultiViewPartitioner { - public static final String PHP_TEMPLATE_DATA = "__php_template_data"; + public static final String PHP_TEMPLATE_DATA = "__php_template_data"; - public static final String PHP_SCRIPT_CODE = "__php_script_code"; + public static final String PHP_SCRIPT_CODE = "__php_script_code"; - public static final String[] LEGAL_TYPES = { - PHP_TEMPLATE_DATA, - PHP_SCRIPT_CODE - }; + public static final String[] LEGAL_TYPES = { PHP_TEMPLATE_DATA, + PHP_SCRIPT_CODE }; + public PHPDocumentPartitioner(IPartitionTokenScanner scanner) { + super(scanner); + } - public PHPDocumentPartitioner(IPartitionTokenScanner scanner) { - super(scanner); - } - - protected FlatNode createNode(String type, int offset, int length) { - if (type.equals(PHPPartitionScanner.PHP_SCRIPTING_AREA)) { - if (DEBUG) { - Assert.isTrue(offset >= 0); - } - ViewNode node = new ViewNode(type); - node.offset = offset; - node.length = length; - return node; - } - - return super.createNode(type, offset, length); - } - - /* - * @see net.sf.solareclipse.text.rules.DocumentViewPartitioner#createPartitioner(String) - */ - protected IDocumentPartitioner createPartitioner(String contentType) { - if (contentType == null) { - // return JavaTextTools.createHTMLPartitioner(); - return PHPeclipsePlugin.getDefault().getJavaTextTools().getXMLTextTools().createPHPXMLPartitioner(); - } - - if (contentType.equals(PHPPartitionScanner.PHP_SCRIPTING_AREA)) { - return PHPeclipsePlugin.getDefault().getJavaTextTools().createPHPPartitioner(); - } - return null; - } + protected FlatNode createNode(String type, int offset, int length) { + if (type.equals(PHPPartitionScanner.PHP_SCRIPTING_AREA)) { + if (DEBUG) { + Assert.isTrue(offset >= 0); + } + ViewNode node = new ViewNode(type); + node.offset = offset; + node.length = length; + return node; + } + + return super.createNode(type, offset, length); + } - /* - * @see net.sf.solareclipse.text.rules.DocumentViewPartitioner#getContentType(String, String) - */ - protected String getContentType(String parent, String view) { - if (parent == null) { - if (view == IDocument.DEFAULT_CONTENT_TYPE) { - return PHP_TEMPLATE_DATA; - } - } else { - if (view == IDocument.DEFAULT_CONTENT_TYPE) { - return PHP_SCRIPT_CODE; - } - } + /* + * @see net.sf.solareclipse.text.rules.DocumentViewPartitioner#createPartitioner(String) + */ + protected IDocumentPartitioner createPartitioner(String contentType) { + if (contentType == null) { + // return JavaTextTools.createHTMLPartitioner(); + return PHPeclipsePlugin.getDefault().getJavaTextTools() + .getXMLTextTools().createPHPXMLPartitioner(); + } + + if (contentType.equals(PHPPartitionScanner.PHP_SCRIPTING_AREA)) { + return PHPeclipsePlugin.getDefault().getJavaTextTools() + .createPHPPartitioner(); + } + return null; + } - return super.getContentType(parent, view); - } + /* + * @see net.sf.solareclipse.text.rules.DocumentViewPartitioner#getContentType(String, + * String) + */ + protected String getContentType(String parent, String view) { + if (parent == null) { + if (view == IDocument.DEFAULT_CONTENT_TYPE) { + return PHP_TEMPLATE_DATA; + } + } else { + if (view == IDocument.DEFAULT_CONTENT_TYPE) { + return PHP_SCRIPT_CODE; + } + } + + return super.getContentType(parent, view); + } public String[] getLegalContentTypes() { return LEGAL_TYPES; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPDoubleClickSelector.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPDoubleClickSelector.java index e91ca82..9a38d3b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPDoubleClickSelector.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPDoubleClickSelector.java @@ -1,17 +1,16 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ package net.sourceforge.phpeclipse.phpeditor.php; - import net.sourceforge.phpdt.internal.compiler.parser.Scanner; import org.eclipse.jface.text.BadLocationException; @@ -25,21 +24,25 @@ import org.eclipse.jface.text.ITextViewer; public class PHPDoubleClickSelector implements ITextDoubleClickStrategy { protected ITextViewer fText; + protected int fPos; + protected int fStartPos; + protected int fEndPos; - protected static char[] fgBrackets = { '{', '}', '(', ')', '[', ']', '"', '"' }; + protected static char[] fgBrackets = { '{', '}', '(', ')', '[', ']', '"', + '"' }; - /* + /* * Create a PHPDoubleClickSelector. */ public PHPDoubleClickSelector() { super(); } - /* (non-Javadoc) - * Method declared on ITextDoubleClickStrategy + /* + * (non-Javadoc) Method declared on ITextDoubleClickStrategy */ public void doubleClicked(ITextViewer text) { @@ -92,13 +95,15 @@ public class PHPDoubleClickSelector implements ITextDoubleClickStrategy { } if (fStartPos > -1 && bracketIndex1 < bracketIndex2) { - fEndPos = searchForClosingBracket(fStartPos, prevChar, fgBrackets[bracketIndex1 + 1], doc); + fEndPos = searchForClosingBracket(fStartPos, prevChar, + fgBrackets[bracketIndex1 + 1], doc); if (fEndPos > -1) return true; else fStartPos = -1; } else if (fEndPos > -1) { - fStartPos = searchForOpenBracket(fEndPos, fgBrackets[bracketIndex2 - 1], nextChar, doc); + fStartPos = searchForOpenBracket(fEndPos, + fgBrackets[bracketIndex2 - 1], nextChar, doc); if (fStartPos > -1) return true; else @@ -156,14 +161,19 @@ public class PHPDoubleClickSelector implements ITextDoubleClickStrategy { /** * Returns the position of the closing bracket after startPosition. + * * @returns the location of the closing bracket. - * @param startPosition - the beginning position - * @param openBracket - the character that represents the open bracket - * @param closeBracket - the character that represents the close bracket - * @param document - the document being searched + * @param startPosition - + * the beginning position + * @param openBracket - + * the character that represents the open bracket + * @param closeBracket - + * the character that represents the close bracket + * @param document - + * the document being searched */ - protected int searchForClosingBracket(int startPosition, char openBracket, char closeBracket, IDocument document) - throws BadLocationException { + protected int searchForClosingBracket(int startPosition, char openBracket, + char closeBracket, IDocument document) throws BadLocationException { int stack = 1; int closePosition = startPosition + 1; int length = document.getLength(); @@ -187,14 +197,19 @@ public class PHPDoubleClickSelector implements ITextDoubleClickStrategy { /** * Returns the position of the open bracket before startPosition. + * * @returns the location of the starting bracket. - * @param startPosition - the beginning position - * @param openBracket - the character that represents the open bracket - * @param closeBracket - the character that represents the close bracket - * @param document - the document being searched + * @param startPosition - + * the beginning position + * @param openBracket - + * the character that represents the open bracket + * @param closeBracket - + * the character that represents the close bracket + * @param document - + * the document being searched */ - protected int searchForOpenBracket(int startPosition, char openBracket, char closeBracket, IDocument document) - throws BadLocationException { + protected int searchForOpenBracket(int startPosition, char openBracket, + char closeBracket, IDocument document) throws BadLocationException { int stack = 1; int openPos = startPosition - 1; char nextChar; @@ -215,8 +230,8 @@ public class PHPDoubleClickSelector implements ITextDoubleClickStrategy { } /** - * Select the area between the selected bracket and the closing bracket. Return - * true if successful. + * Select the area between the selected bracket and the closing bracket. + * Return true if successful. */ protected boolean selectBracketBlock() { if (matchBracketsAt()) { @@ -232,7 +247,7 @@ public class PHPDoubleClickSelector implements ITextDoubleClickStrategy { } /** - * Select the word at the current selection. + * Select the word at the current selection. */ protected void selectWord() { if (matchWord()) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPEditorMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPEditorMessages.java index 32d8095..905771d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPEditorMessages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPEditorMessages.java @@ -1,14 +1,14 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ package net.sourceforge.phpeclipse.phpeditor.php; import java.util.MissingResourceException; @@ -18,19 +18,20 @@ public class PHPEditorMessages { private static final String RESOURCE_BUNDLE = "net.sourceforge.phpeclipse.phpeditor.PHPEditorMessages"; //$NON-NLS-1$ -// private static ResourceBundle fgResourceBundle = null; - private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); + // private static ResourceBundle fgResourceBundle = null; + private static ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); // ResourceBundle.getBundle(RESOURCE_BUNDLE); private PHPEditorMessages() { -// if (fgResourceBundle == null) { -// try { -// fgResourceBundle = ResourceBundle.getBundle(RESOURCE_BUNDLE); -// } catch (MissingResourceException x) { -// fgResourceBundle = null; -// } -// } + // if (fgResourceBundle == null) { + // try { + // fgResourceBundle = ResourceBundle.getBundle(RESOURCE_BUNDLE); + // } catch (MissingResourceException x) { + // fgResourceBundle = null; + // } + // } } public static String getString(String key) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPElement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPElement.java index a72254d..fde8279 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPElement.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPElement.java @@ -5,40 +5,42 @@ package net.sourceforge.phpeclipse.phpeditor.php; */ public abstract class PHPElement { - private String ElementName; - private String ElementUsage; - - //Setters - public final void setName(String ElementName) { - this.ElementName = ElementName; - } - public final void setUsage(String usage) { - this.ElementUsage = usage; - } - - //Getters - public final String getName() { - return ElementName; - } - - public final String getUsage() { - return ElementUsage; - } - - public String getHoverText() { - return ""+getUsage()+""; - } - - public PHPElement() { - } - - public PHPElement(String name, String usage) { - setName(name); - if ((usage == null) || (usage.equals(""))) { - setUsage(name + " - "); - } else { - setUsage(usage); - } - } + private String ElementName; + + private String ElementUsage; + + // Setters + public final void setName(String ElementName) { + this.ElementName = ElementName; + } + + public final void setUsage(String usage) { + this.ElementUsage = usage; + } + + // Getters + public final String getName() { + return ElementName; + } + + public final String getUsage() { + return ElementUsage; + } + + public String getHoverText() { + return "" + getUsage() + ""; + } + + public PHPElement() { + } + + public PHPElement(String name, String usage) { + setName(name); + if ((usage == null) || (usage.equals(""))) { + setUsage(name + " - "); + } else { + setUsage(usage); + } + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPFunction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPFunction.java index 76bd20a..2949a27 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPFunction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPFunction.java @@ -2,28 +2,28 @@ package net.sourceforge.phpeclipse.phpeditor.php; /** * @author Choochter - * + * * To change this generated comment edit the template variable "typecomment": - * Window>Preferences>Java>ObfuscatorIgnores. - * To enable and disable the creation of type comments go to - * Window>Preferences>Java>Code Generation. + * Window>Preferences>Java>ObfuscatorIgnores. To enable and disable the creation + * of type comments go to Window>Preferences>Java>Code Generation. */ public class PHPFunction extends PHPElement { - private String fDescription; - - public void setDescription(String description) { - this.fDescription = description; - } - public String getDescription() { - return this.fDescription; - } + private String fDescription; - public String getHoverText() { - return super.getHoverText()+"
                                                      "+getDescription(); - } - - public PHPFunction(String Name, String usage, String description) { - super(Name, usage); - setDescription(description); - } + public void setDescription(String description) { + this.fDescription = description; + } + + public String getDescription() { + return this.fDescription; + } + + public String getHoverText() { + return super.getHoverText() + "
                                                      " + getDescription(); + } + + public PHPFunction(String Name, String usage, String description) { + super(Name, usage); + setDescription(description); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPKeyword.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPKeyword.java index 099d95e..c710e18 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPKeyword.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPKeyword.java @@ -2,28 +2,28 @@ package net.sourceforge.phpeclipse.phpeditor.php; /** * @author Choochter - * + * * To change this generated comment edit the template variable "typecomment": - * Window>Preferences>Java>ObfuscatorIgnores. - * To enable and disable the creation of type comments go to - * Window>Preferences>Java>Code Generation. + * Window>Preferences>Java>ObfuscatorIgnores. To enable and disable the creation + * of type comments go to Window>Preferences>Java>Code Generation. */ -public class PHPKeyword extends PHPElement{ -// private int tokenval; -// public void settokenval(String tokenval) { this.tokenval = Integer.parseInt(tokenval);} -// public void settokenval(int tokenval) { this.tokenval = tokenval;} -// public int gettokenval() { return this.tokenval; } - - public PHPKeyword(String Name, String Description){ +public class PHPKeyword extends PHPElement { + // private int tokenval; + // public void settokenval(String tokenval) { this.tokenval = + // Integer.parseInt(tokenval);} + // public void settokenval(int tokenval) { this.tokenval = tokenval;} + // public int gettokenval() { return this.tokenval; } + + public PHPKeyword(String Name, String Description) { super(Name, Description); -// if ((tokenval == null) || (tokenval.equals(""))) -// { -// //if there is not a tokenval, then not implemented. -// settokenval(-1); -// } -// else { -// settokenval(tokenval); -// } - //settokenval(tokenval); + // if ((tokenval == null) || (tokenval.equals(""))) + // { + // //if there is not a tokenval, then not implemented. + // settokenval(-1); + // } + // else { + // settokenval(tokenval); + // } + // settokenval(tokenval); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPPartitionScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPPartitionScanner.java index 5d25697..514e802 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPPartitionScanner.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPPartitionScanner.java @@ -8,7 +8,7 @@ Contributors: Igor Malinin - initial contribution - $Id: PHPPartitionScanner.java,v 1.33 2005-10-10 19:56:02 axelcl Exp $ + $Id: PHPPartitionScanner.java,v 1.34 2006-10-21 23:18:32 pombredanne Exp $ **********************************************************************/ package net.sourceforge.phpeclipse.phpeditor.php; @@ -27,8 +27,8 @@ import org.eclipse.jface.text.rules.IToken; import org.eclipse.jface.text.rules.Token; /** - * - * + * + * * @author Igor Malinin */ public class PHPPartitionScanner implements IPartitionTokenScanner { @@ -267,7 +267,8 @@ public class PHPPartitionScanner implements IPartitionTokenScanner { if (position >= end) { return false; } - ch = document.getChar(position++); // ignore escaped character + ch = document.getChar(position++); // ignore escaped + // character } else if (ch == '"') { return true; } @@ -291,7 +292,8 @@ public class PHPPartitionScanner implements IPartitionTokenScanner { if (position >= end) { return false; } - ch = document.getChar(position++); // ignore escaped character + ch = document.getChar(position++); // ignore escaped + // character } else if (ch == '\'') { return true; } @@ -337,7 +339,8 @@ public class PHPPartitionScanner implements IPartitionTokenScanner { if (pos == heredocIdent.length) { return true; } - ch = document.getChar(position++); // ignore escaped character + ch = document.getChar(position++); // ignore escaped + // character if (ch != heredocIdent[pos]) { break; } @@ -427,7 +430,8 @@ public class PHPPartitionScanner implements IPartitionTokenScanner { /* * @see org.eclipse.jface.text.rules.IPartitionTokenScanner */ - public void setPartialRange(IDocument document, int offset, int length, String contentType, int partitionOffset) { + public void setPartialRange(IDocument document, int offset, int length, + String contentType, int partitionOffset) { // state = STATE_DEFAULT; if (partitionOffset > -1) { int delta = offset - partitionOffset; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPType.java index 701ba82..5b109ee 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPType.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPType.java @@ -2,14 +2,13 @@ package net.sourceforge.phpeclipse.phpeditor.php; /** * @author Choochter - * + * * To change this generated comment edit the template variable "typecomment": - * Window>Preferences>Java>ObfuscatorIgnores. - * To enable and disable the creation of type comments go to - * Window>Preferences>Java>Code Generation. + * Window>Preferences>Java>ObfuscatorIgnores. To enable and disable the creation + * of type comments go to Window>Preferences>Java>Code Generation. */ public class PHPType extends PHPElement { - public PHPType(String Name, String Description) { - super(Name, Description); - } + public PHPType(String Name, String Description) { + super(Name, Description); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPWordExtractor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPWordExtractor.java index 4db149a..ed9b88c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPWordExtractor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPWordExtractor.java @@ -1,14 +1,14 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ package net.sourceforge.phpeclipse.phpeditor.php; import net.sourceforge.phpdt.internal.compiler.parser.Scanner; @@ -24,10 +24,13 @@ public class PHPWordExtractor { /** * Find the location of the word at offset in document. - * @returns Point - x is the start position, y is the end position. - * Return null if it is not found. - * @param document the document being searched. - * @param offset - the position to start searching from. + * + * @returns Point - x is the start position, y is the end position. Return + * null if it is not found. + * @param document + * the document being searched. + * @param offset - + * the position to start searching from. */ public static Point findWord(IDocument document, int offset) { @@ -41,7 +44,8 @@ public class PHPWordExtractor { while (position >= 0) { character = document.getChar(position); - if (!Scanner.isPHPIdentifierPart(character) && (character != '$')) + if (!Scanner.isPHPIdentifierPart(character) + && (character != '$')) break; --position; } @@ -53,12 +57,13 @@ public class PHPWordExtractor { while (position < length) { character = document.getChar(position); - if (!Scanner.isPHPIdentifierPart(character) && (character != '$')) + if (!Scanner.isPHPIdentifierPart(character) + && (character != '$')) break; ++position; } - start++; + start++; end = position; if (end > start) diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/SmartyCodeScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/SmartyCodeScanner.java index 36a9abc..ac1aa25 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/SmartyCodeScanner.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/SmartyCodeScanner.java @@ -1,14 +1,14 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ package net.sourceforge.phpeclipse.phpeditor.php; import java.util.ArrayList; @@ -33,174 +33,150 @@ import org.eclipse.jface.text.rules.WordRule; * PHP Code Scanner */ public class SmartyCodeScanner extends AbstractJavaScanner { - public static String[] SMARTY_KEYWORDS = - { - "capture", - "config_load", - "else", - "elseif", - "foreach", - "foreachelse", - "if", - "include", - "insert", - "ldelim", - "literal", - "php", - "rdelim", - "section", - "sectionelse", - "strip" }; - public static String[] SMARTY_FUNCTION_NAMES = - { - "assign", - "counter", - "cycle", - "debug", - "eval", - "fetch", - "html_checkboxes", - "html_image", - "html_options", - "html_radios", - "html_select_date", - "html_select_time", - "html_table", - "math", - "popup", - "popup_init", - "textformat" }; - private class SmartyWordRule extends WordRule { - private StringBuffer fBuffer = new StringBuffer(); - - public SmartyWordRule(IWordDetector detector) { - super(detector, Token.UNDEFINED); - } - - public SmartyWordRule(IWordDetector detector, IToken defaultToken) { - super(detector, defaultToken); - } - - public IToken evaluate(ICharacterScanner scanner) { - int c = scanner.read(); - boolean isVariable = false; - if (c == '{') { - c = scanner.read(); - if (c != '/') { - scanner.unread(); - } - return getToken(IPreferenceConstants.PHP_TAG); - } - if (c == '}') { - return getToken(IPreferenceConstants.PHP_TAG); - } - if (fDetector.isWordStart((char) c)) { - if (c == '$') { - isVariable = true; - } - if (fColumn == UNDEFINED || (fColumn == scanner.getColumn() - 1)) { - - fBuffer.setLength(0); - do { - fBuffer.append((char) c); - c = scanner.read(); - } while (c != ICharacterScanner.EOF && fDetector.isWordPart((char) c)); - scanner.unread(); - - if (isVariable) { - return getToken(IPreferenceConstants.PHP_VARIABLE); - } - IToken token = (IToken) fWords.get(fBuffer.toString()); - if (token != null) - return token; - - if (fDefaultToken.isUndefined()) - unreadBuffer(scanner); - - return fDefaultToken; - } - } - - scanner.unread(); - return Token.UNDEFINED; - } - } - - private static String[] fgTokenProperties = - { - IPreferenceConstants.PHP_MULTILINE_COMMENT, - IPreferenceConstants.PHP_SINGLELINE_COMMENT, - IPreferenceConstants.PHP_TAG, - IPreferenceConstants.PHP_KEYWORD, - IPreferenceConstants.PHP_FUNCTIONNAME, - IPreferenceConstants.PHP_VARIABLE, - IPreferenceConstants.PHP_VARIABLE_DOLLAR, - IPreferenceConstants.PHP_STRING_DQ, - IPreferenceConstants.PHP_STRING_SQ, - IPreferenceConstants.PHP_TYPE, - IPreferenceConstants.PHP_CONSTANT, - IPreferenceConstants.PHP_DEFAULT }; - /** - * Creates a PHP code scanner - */ - // public PHPCodeScanner(JavaColorManager provider, IPreferenceStore store) { - public SmartyCodeScanner(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 strings and character constants. - Token token = getToken(IPreferenceConstants.PHP_STRING_DQ); - rules.add(new MultiLineRule("\"", "\"", token, '\\')); //$NON-NLS-2$ //$NON-NLS-1$ - - // Add generic whitespace rule. - rules.add(new WhitespaceRule(new PHPWhitespaceDetector())); - // Add word rule for keywords, types, and constants. - token = getToken(IPreferenceConstants.PHP_DEFAULT); - - SmartyWordRule wordRule = new SmartyWordRule(new PHPWordDetector(), token); - - Token keyword = getToken(IPreferenceConstants.PHP_KEYWORD); - Token functionName = getToken(IPreferenceConstants.PHP_FUNCTIONNAME); -// Token type = getToken(IPreferenceConstants.PHP_TYPE); -// Token constant = getToken(IPreferenceConstants.PHP_CONSTANT); - - - for (int i = 0; i < SMARTY_KEYWORDS.length; i++) { - wordRule.addWord(SMARTY_KEYWORDS[i], keyword); - } - - for (int i = 0; i < SMARTY_FUNCTION_NAMES.length; i++) { - wordRule.addWord(SMARTY_FUNCTION_NAMES[i], functionName); - } - -// ArrayList buffer = PHPSyntaxRdr.getSyntaxData(); -// PHPElement elbuffer = null; -// for (int i = 0; i < buffer.size(); i++) { -// -// elbuffer = (PHPElement) buffer.get(i); -// if (elbuffer instanceof PHPKeyword) -// wordRule.addWord(((PHPKeyword) elbuffer).getName(), keyword); -// // if (elbuffer instanceof PHPFunction) -// // wordRule.addWord(((PHPFunction) elbuffer).getName(), functionName); -// if (elbuffer instanceof PHPType) -// wordRule.addWord(elbuffer.getName(), type); -// if (elbuffer instanceof PHPConstant) -// wordRule.addWord(elbuffer.getName(), constant); -// } - rules.add(wordRule); - setDefaultReturnToken(getToken(IPreferenceConstants.PHP_DEFAULT)); - return rules; - } + public static String[] SMARTY_KEYWORDS = { "capture", "config_load", + "else", "elseif", "foreach", "foreachelse", "if", "include", + "insert", "ldelim", "literal", "php", "rdelim", "section", + "sectionelse", "strip" }; + + public static String[] SMARTY_FUNCTION_NAMES = { "assign", "counter", + "cycle", "debug", "eval", "fetch", "html_checkboxes", "html_image", + "html_options", "html_radios", "html_select_date", + "html_select_time", "html_table", "math", "popup", "popup_init", + "textformat" }; + + private class SmartyWordRule extends WordRule { + private StringBuffer fBuffer = new StringBuffer(); + + public SmartyWordRule(IWordDetector detector) { + super(detector, Token.UNDEFINED); + } + + public SmartyWordRule(IWordDetector detector, IToken defaultToken) { + super(detector, defaultToken); + } + + public IToken evaluate(ICharacterScanner scanner) { + int c = scanner.read(); + boolean isVariable = false; + if (c == '{') { + c = scanner.read(); + if (c != '/') { + scanner.unread(); + } + return getToken(IPreferenceConstants.PHP_TAG); + } + if (c == '}') { + return getToken(IPreferenceConstants.PHP_TAG); + } + if (fDetector.isWordStart((char) c)) { + if (c == '$') { + isVariable = true; + } + if (fColumn == UNDEFINED + || (fColumn == scanner.getColumn() - 1)) { + + fBuffer.setLength(0); + do { + fBuffer.append((char) c); + c = scanner.read(); + } while (c != ICharacterScanner.EOF + && fDetector.isWordPart((char) c)); + scanner.unread(); + + if (isVariable) { + return getToken(IPreferenceConstants.PHP_VARIABLE); + } + IToken token = (IToken) fWords.get(fBuffer.toString()); + if (token != null) + return token; + + if (fDefaultToken.isUndefined()) + unreadBuffer(scanner); + + return fDefaultToken; + } + } + + scanner.unread(); + return Token.UNDEFINED; + } + } + + private static String[] fgTokenProperties = { + IPreferenceConstants.PHP_MULTILINE_COMMENT, + IPreferenceConstants.PHP_SINGLELINE_COMMENT, + IPreferenceConstants.PHP_TAG, IPreferenceConstants.PHP_KEYWORD, + IPreferenceConstants.PHP_FUNCTIONNAME, + IPreferenceConstants.PHP_VARIABLE, + IPreferenceConstants.PHP_VARIABLE_DOLLAR, + IPreferenceConstants.PHP_STRING_DQ, + IPreferenceConstants.PHP_STRING_SQ, IPreferenceConstants.PHP_TYPE, + IPreferenceConstants.PHP_CONSTANT, IPreferenceConstants.PHP_DEFAULT }; + + /** + * Creates a PHP code scanner + */ + // public PHPCodeScanner(JavaColorManager provider, IPreferenceStore store) + // { + public SmartyCodeScanner(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 strings and character constants. + Token token = getToken(IPreferenceConstants.PHP_STRING_DQ); + rules.add(new MultiLineRule("\"", "\"", token, '\\')); //$NON-NLS-2$ //$NON-NLS-1$ + + // Add generic whitespace rule. + rules.add(new WhitespaceRule(new PHPWhitespaceDetector())); + // Add word rule for keywords, types, and constants. + token = getToken(IPreferenceConstants.PHP_DEFAULT); + + SmartyWordRule wordRule = new SmartyWordRule(new PHPWordDetector(), + token); + + Token keyword = getToken(IPreferenceConstants.PHP_KEYWORD); + Token functionName = getToken(IPreferenceConstants.PHP_FUNCTIONNAME); + // Token type = getToken(IPreferenceConstants.PHP_TYPE); + // Token constant = getToken(IPreferenceConstants.PHP_CONSTANT); + + for (int i = 0; i < SMARTY_KEYWORDS.length; i++) { + wordRule.addWord(SMARTY_KEYWORDS[i], keyword); + } + + for (int i = 0; i < SMARTY_FUNCTION_NAMES.length; i++) { + wordRule.addWord(SMARTY_FUNCTION_NAMES[i], functionName); + } + + // ArrayList buffer = PHPSyntaxRdr.getSyntaxData(); + // PHPElement elbuffer = null; + // for (int i = 0; i < buffer.size(); i++) { + // + // elbuffer = (PHPElement) buffer.get(i); + // if (elbuffer instanceof PHPKeyword) + // wordRule.addWord(((PHPKeyword) elbuffer).getName(), keyword); + // // if (elbuffer instanceof PHPFunction) + // // wordRule.addWord(((PHPFunction) elbuffer).getName(), + // functionName); + // if (elbuffer instanceof PHPType) + // wordRule.addWord(elbuffer.getName(), type); + // if (elbuffer instanceof PHPConstant) + // wordRule.addWord(elbuffer.getName(), constant); + // } + rules.add(wordRule); + setDefaultReturnToken(getToken(IPreferenceConstants.PHP_DEFAULT)); + return rules; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/SmartyDocCodeScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/SmartyDocCodeScanner.java index a0e42ea..f81ed22 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/SmartyDocCodeScanner.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/SmartyDocCodeScanner.java @@ -1,16 +1,15 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - IBM Corporation - Initial implementation -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + **********************************************************************/ package net.sourceforge.phpeclipse.phpeditor.php; - import java.util.ArrayList; import java.util.List; @@ -30,164 +29,150 @@ import org.eclipse.jface.text.rules.Token; import org.eclipse.jface.text.rules.WhitespaceRule; import org.eclipse.jface.text.rules.WordRule; - - - /** * A rule based SmartyDoc scanner. */ public final class SmartyDocCodeScanner extends AbstractJavaScanner { - - - /** - * A key word detector. - */ - static class JavaDocKeywordDetector implements IWordDetector { - - /** - * @see IWordDetector#isWordStart - */ - public boolean isWordStart(char c) { - return (c == '@'); - } - - /** - * @see IWordDetector#isWordPart - */ - public boolean isWordPart(char c) { - return Character.isLetter(c); - } - }; - - - /** - * Detector for HTML comment delimiters. - */ - static class HTMLCommentDetector implements IWordDetector { - - /** - * @see IWordDetector#isWordStart - */ - public boolean isWordStart(char c) { - return (c == '<' || c == '-'); - } - - /** - * @see IWordDetector#isWordPart - */ - 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 checkForWhitespace(ICharacterScanner scanner) { - - try { - - char c= getDocument().getChar(getTokenOffset() + 1); - if (!Character.isWhitespace(c)) - return fToken; - - } catch (BadLocationException x) { - } - - return Token.UNDEFINED; - } - - /* - * @see PatternRule#evaluate(ICharacterScanner) - */ - public IToken evaluate(ICharacterScanner scanner) { - IToken result= super.evaluate(scanner); - if (result == fToken) - return checkForWhitespace(scanner); - return result; - } - }; - - - private static String[] fgKeywords= {"@author", "@deprecated", "@exception", "@param", "@return", "@see", "@serial", "@serialData", "@serialField", "@since", "@throws", "@version"}; //$NON-NLS-12$ //$NON-NLS-11$ //$NON-NLS-10$ //$NON-NLS-7$ //$NON-NLS-9$ //$NON-NLS-8$ //$NON-NLS-6$ //$NON-NLS-5$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ - - private static String[] fgTokenProperties= { - IPreferenceConstants.PHPDOC_KEYWORD, - IPreferenceConstants.PHPDOC_TAG, - IPreferenceConstants.PHPDOC_LINK, - IPreferenceConstants.PHPDOC_DEFAULT - }; - - - public SmartyDocCodeScanner(IColorManager manager, IPreferenceStore store) { - super(manager, store); - initialize(); - } - - public IDocument getDocument() { - return fDocument; - } - - /* - * @see AbstractJavaScanner#getTokenProperties() - */ - protected String[] getTokenProperties() { - return fgTokenProperties; - } - - /* - * @see AbstractJavaScanner#createRules() - */ - protected List createRules() { - - List list= new ArrayList(); - - // Add rule for tags. - Token token= getToken(IPreferenceConstants.PHPDOC_TAG); - list.add(new TagRule(token)); - - - // Add rule for HTML comments - WordRule wordRule= new WordRule(new HTMLCommentDetector(), token); - wordRule.addWord("", token); //$NON-NLS-1$ - list.add(wordRule); - - - // Add rule for links. - token= getToken(IPreferenceConstants.PHPDOC_LINK); - list.add(new SingleLineRule("{@link", "}", token)); //$NON-NLS-2$ //$NON-NLS-1$ - - - // Add generic whitespace rule. - list.add(new WhitespaceRule(new PHPWhitespaceDetector())); - - - // Add word rule for keywords. - token= getToken(IPreferenceConstants.PHPDOC_DEFAULT); - wordRule= new WordRule(new JavaDocKeywordDetector(), token); - - token= getToken(IPreferenceConstants.PHPDOC_KEYWORD); - for (int i= 0; i < fgKeywords.length; i++) - wordRule.addWord(fgKeywords[i], token); - list.add(wordRule); - - setDefaultReturnToken(getToken(IPreferenceConstants.PHPDOC_DEFAULT)); - return list; - } -} - + /** + * A key word detector. + */ + static class JavaDocKeywordDetector implements IWordDetector { + + /** + * @see IWordDetector#isWordStart + */ + public boolean isWordStart(char c) { + return (c == '@'); + } + + /** + * @see IWordDetector#isWordPart + */ + public boolean isWordPart(char c) { + return Character.isLetter(c); + } + }; + + /** + * Detector for HTML comment delimiters. + */ + static class HTMLCommentDetector implements IWordDetector { + + /** + * @see IWordDetector#isWordStart + */ + public boolean isWordStart(char c) { + return (c == '<' || c == '-'); + } + + /** + * @see IWordDetector#isWordPart + */ + 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 checkForWhitespace(ICharacterScanner scanner) { + + try { + + char c = getDocument().getChar(getTokenOffset() + 1); + if (!Character.isWhitespace(c)) + return fToken; + + } catch (BadLocationException x) { + } + + return Token.UNDEFINED; + } + + /* + * @see PatternRule#evaluate(ICharacterScanner) + */ + public IToken evaluate(ICharacterScanner scanner) { + IToken result = super.evaluate(scanner); + if (result == fToken) + return checkForWhitespace(scanner); + return result; + } + }; + + private static String[] fgKeywords = { + "@author", "@deprecated", "@exception", "@param", "@return", "@see", "@serial", "@serialData", "@serialField", "@since", "@throws", "@version" }; //$NON-NLS-12$ //$NON-NLS-11$ //$NON-NLS-10$ //$NON-NLS-7$ //$NON-NLS-9$ //$NON-NLS-8$ //$NON-NLS-6$ //$NON-NLS-5$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ + + private static String[] fgTokenProperties = { + IPreferenceConstants.PHPDOC_KEYWORD, + IPreferenceConstants.PHPDOC_TAG, IPreferenceConstants.PHPDOC_LINK, + IPreferenceConstants.PHPDOC_DEFAULT }; + + public SmartyDocCodeScanner(IColorManager manager, IPreferenceStore store) { + super(manager, store); + initialize(); + } + + public IDocument getDocument() { + return fDocument; + } + + /* + * @see AbstractJavaScanner#getTokenProperties() + */ + protected String[] getTokenProperties() { + return fgTokenProperties; + } + + /* + * @see AbstractJavaScanner#createRules() + */ + protected List createRules() { + + List list = new ArrayList(); + + // Add rule for tags. + Token token = getToken(IPreferenceConstants.PHPDOC_TAG); + list.add(new TagRule(token)); + + // Add rule for HTML comments + WordRule wordRule = new WordRule(new HTMLCommentDetector(), token); + wordRule.addWord("", token); //$NON-NLS-1$ + list.add(wordRule); + + // Add rule for links. + token = getToken(IPreferenceConstants.PHPDOC_LINK); + list.add(new SingleLineRule("{@link", "}", token)); //$NON-NLS-2$ //$NON-NLS-1$ + + // Add generic whitespace rule. + list.add(new WhitespaceRule(new PHPWhitespaceDetector())); + + // Add word rule for keywords. + token = getToken(IPreferenceConstants.PHPDOC_DEFAULT); + wordRule = new WordRule(new JavaDocKeywordDetector(), token); + + token = getToken(IPreferenceConstants.PHPDOC_KEYWORD); + for (int i = 0; i < fgKeywords.length; i++) + wordRule.addWord(fgKeywords[i], token); + list.add(wordRule); + + setDefaultReturnToken(getToken(IPreferenceConstants.PHPDOC_DEFAULT)); + return list; + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/HTMLWordDetector.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/HTMLWordDetector.java index 1e467e0..517c1c7 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/HTMLWordDetector.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/HTMLWordDetector.java @@ -1,16 +1,16 @@ package net.sourceforge.phpeclipse.phpeditor.util; /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html -Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de -**********************************************************************/ + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ import net.sourceforge.phpdt.internal.compiler.parser.Scanner; @@ -21,17 +21,18 @@ import org.eclipse.jface.text.rules.IWordDetector; */ public class HTMLWordDetector implements IWordDetector { - /* (non-Javadoc) - * Method declared on IWordDetector. + /* + * (non-Javadoc) Method declared on IWordDetector. */ public boolean isWordPart(char character) { - return Scanner.isPHPIdentifierPart(character)||(character=='/')||(character=='>'); + return Scanner.isPHPIdentifierPart(character) || (character == '/') + || (character == '>'); } - - /* (non-Javadoc) - * Method declared on IWordDetector. + + /* + * (non-Javadoc) Method declared on IWordDetector. */ public boolean isWordStart(char character) { - return character=='<'; + return character == '<'; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPColorProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPColorProvider.java index 6f05c78..89894af 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPColorProvider.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPColorProvider.java @@ -1,14 +1,14 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ package net.sourceforge.phpeclipse.phpeditor.util; import java.util.HashMap; @@ -18,54 +18,69 @@ import java.util.Map; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Display; + /** * Manager for colors used in the Java editor */ public class PHPColorProvider { - public static final RGB MULTI_LINE_COMMENT = new RGB(63, 127, 95); - public static final RGB SINGLE_LINE_COMMENT = new RGB(63, 127, 95); + public static final RGB MULTI_LINE_COMMENT = new RGB(63, 127, 95); + + public static final RGB SINGLE_LINE_COMMENT = new RGB(63, 127, 95); + public static final RGB TAG = new RGB(255, 0, 128); - public static final RGB KEYWORD = new RGB(127, 0, 85); - public static final RGB VARIABLE = new RGB(127, 159, 191); - public static final RGB FUNCTION_NAME = new RGB(127, 127, 159); - public static final RGB STRING_DQ = new RGB(42, 0, 255); - public static final RGB STRING_SQ = new RGB(42, 0, 255); - public static final RGB DEFAULT = new RGB(0, 0, 0); - public static final RGB TYPE = new RGB(127, 0, 85); - public static final RGB CONSTANT = new RGB(127, 0, 85); - public static final RGB BACKGROUND = new RGB(255, 255, 255); - - // public static final RGB LINKED_POSITION_COLOR = new RGB(0, 0, 0); - -// public static final RGB LINE_NUMBER_COLOR = new RGB(0, 0, 0); -// public static final RGB BACKGROUND_COLOR = new RGB(255, 255, 255); - - public static final RGB PHPDOC_TAG = new RGB(63, 127, 95); - public static final RGB PHPDOC_LINK = new RGB(63, 63, 191); - public static final RGB PHPDOC_DEFAULT = new RGB(63, 95, 191); - public static final RGB PHPDOC_KEYWORD = new RGB(127, 159, 191); - - protected Map fColorTable = new HashMap(10); - - /** - * Release all of the color resources held onto by the receiver. - */ - public void dispose() { - Iterator e = fColorTable.values().iterator(); - while (e.hasNext()) - ((Color) e.next()).dispose(); - } - - /** - * Return the Color that is stored in the Color table as rgb. - */ - public Color getColor(RGB rgb) { - Color color = (Color) fColorTable.get(rgb); - if (color == null) { - color = new Color(Display.getCurrent(), rgb); - fColorTable.put(rgb, color); - } - return color; - } + + public static final RGB KEYWORD = new RGB(127, 0, 85); + + public static final RGB VARIABLE = new RGB(127, 159, 191); + + public static final RGB FUNCTION_NAME = new RGB(127, 127, 159); + + public static final RGB STRING_DQ = new RGB(42, 0, 255); + + public static final RGB STRING_SQ = new RGB(42, 0, 255); + + public static final RGB DEFAULT = new RGB(0, 0, 0); + + public static final RGB TYPE = new RGB(127, 0, 85); + + public static final RGB CONSTANT = new RGB(127, 0, 85); + + public static final RGB BACKGROUND = new RGB(255, 255, 255); + + // public static final RGB LINKED_POSITION_COLOR = new RGB(0, 0, 0); + + // public static final RGB LINE_NUMBER_COLOR = new RGB(0, 0, 0); + // public static final RGB BACKGROUND_COLOR = new RGB(255, 255, 255); + + public static final RGB PHPDOC_TAG = new RGB(63, 127, 95); + + public static final RGB PHPDOC_LINK = new RGB(63, 63, 191); + + public static final RGB PHPDOC_DEFAULT = new RGB(63, 95, 191); + + public static final RGB PHPDOC_KEYWORD = new RGB(127, 159, 191); + + protected Map fColorTable = new HashMap(10); + + /** + * Release all of the color resources held onto by the receiver. + */ + public void dispose() { + Iterator e = fColorTable.values().iterator(); + while (e.hasNext()) + ((Color) e.next()).dispose(); + } + + /** + * Return the Color that is stored in the Color table as rgb. + */ + public Color getColor(RGB rgb) { + Color color = (Color) fColorTable.get(rgb); + if (color == null) { + color = new Color(Display.getCurrent(), rgb); + fColorTable.put(rgb, color); + } + return color; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPVariableDetector.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPVariableDetector.java index e6f7d8f..b1c4b1b 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPVariableDetector.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPVariableDetector.java @@ -1,14 +1,14 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html -Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de -**********************************************************************/ + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ package net.sourceforge.phpeclipse.phpeditor.util; import net.sourceforge.phpdt.internal.compiler.parser.Scanner; @@ -16,21 +16,22 @@ import net.sourceforge.phpdt.internal.compiler.parser.Scanner; import org.eclipse.jface.text.rules.IWordDetector; /** - * A PHP aware variable detector (i.e. a PHP identifier starting with a '$' character). + * A PHP aware variable detector (i.e. a PHP identifier starting with a '$' + * character). */ public class PHPVariableDetector implements IWordDetector { - /* (non-Javadoc) - * Method declared on IWordDetector. + /* + * (non-Javadoc) Method declared on IWordDetector. */ public boolean isWordPart(char character) { return Scanner.isPHPIdentifierPart(character); } - - /* (non-Javadoc) - * Method declared on IWordDetector. + + /* + * (non-Javadoc) Method declared on IWordDetector. */ public boolean isWordStart(char character) { - return character=='$'; + return character == '$'; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPWhitespaceDetector.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPWhitespaceDetector.java index 32589f4..65337cf 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPWhitespaceDetector.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPWhitespaceDetector.java @@ -1,14 +1,14 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html -Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de -**********************************************************************/ + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ package net.sourceforge.phpeclipse.phpeditor.util; import org.eclipse.jface.text.rules.IWhitespaceDetector; @@ -18,8 +18,8 @@ import org.eclipse.jface.text.rules.IWhitespaceDetector; */ public class PHPWhitespaceDetector implements IWhitespaceDetector { - /* (non-Javadoc) - * Method declared on IWhitespaceDetector + /* + * (non-Javadoc) Method declared on IWhitespaceDetector */ public boolean isWhitespace(char character) { return Character.isWhitespace(character); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPWordDetector.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPWordDetector.java index 1050592..c799309 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPWordDetector.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPWordDetector.java @@ -1,14 +1,14 @@ /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html -Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de -**********************************************************************/ + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ package net.sourceforge.phpeclipse.phpeditor.util; import net.sourceforge.phpdt.internal.compiler.parser.Scanner; @@ -20,15 +20,15 @@ import org.eclipse.jface.text.rules.IWordDetector; */ public class PHPWordDetector implements IWordDetector { - /* (non-Javadoc) - * Method declared on IWordDetector. + /* + * (non-Javadoc) Method declared on IWordDetector. */ public boolean isWordPart(char character) { return Scanner.isPHPIdentifierPart(character); } - - /* (non-Javadoc) - * Method declared on IWordDetector. + + /* + * (non-Javadoc) Method declared on IWordDetector. */ public boolean isWordStart(char character) { return Scanner.isPHPIdentOrVarStart(character); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/ColorEditor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/ColorEditor.java index 4cf783e..5a2cef9 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/ColorEditor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/ColorEditor.java @@ -26,90 +26,95 @@ import org.eclipse.swt.widgets.Display; * A "button" of a certain color determined by the color picker. */ public class ColorEditor { - + private Point fExtent; + private Image fImage; + private RGB fColorValue; + private Color fColor; + private Button fButton; - + public ColorEditor(Composite parent) { - - fButton= new Button(parent, SWT.PUSH); - fExtent= computeImageSize(parent); - fImage= new Image(parent.getDisplay(), fExtent.x, fExtent.y); - - GC gc= new GC(fImage); + + fButton = new Button(parent, SWT.PUSH); + fExtent = computeImageSize(parent); + fImage = new Image(parent.getDisplay(), fExtent.x, fExtent.y); + + GC gc = new GC(fImage); gc.setBackground(fButton.getBackground()); gc.fillRectangle(0, 0, fExtent.x, fExtent.y); gc.dispose(); - + fButton.setImage(fImage); fButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { - ColorDialog colorDialog= new ColorDialog(fButton.getShell()); + ColorDialog colorDialog = new ColorDialog(fButton.getShell()); colorDialog.setRGB(fColorValue); RGB newColor = colorDialog.open(); if (newColor != null) { - fColorValue= newColor; + fColorValue = newColor; updateColorImage(); } } }); - + fButton.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent event) { - if (fImage != null) { + if (fImage != null) { fImage.dispose(); - fImage= null; + fImage = null; } if (fColor != null) { fColor.dispose(); - fColor= null; + fColor = null; } } }); } - + public RGB getColorValue() { return fColorValue; } - + public void setColorValue(RGB rgb) { - fColorValue= rgb; + fColorValue = rgb; updateColorImage(); } - + public Button getButton() { return fButton; } - + protected void updateColorImage() { - - Display display= fButton.getDisplay(); - - GC gc= new GC(fImage); + + Display display = fButton.getDisplay(); + + GC gc = new GC(fImage); gc.setForeground(display.getSystemColor(SWT.COLOR_BLACK)); gc.drawRectangle(0, 2, fExtent.x - 1, fExtent.y - 4); - + if (fColor != null) fColor.dispose(); - - fColor= new Color(display, fColorValue); + + fColor = new Color(display, fColorValue); gc.setBackground(fColor); gc.fillRectangle(1, 3, fExtent.x - 2, fExtent.y - 5); gc.dispose(); - + fButton.setImage(fImage); } - + protected Point computeImageSize(Control window) { - GC gc= new GC(window); - Font f= JFaceResources.getFontRegistry().get(JFaceResources.DEFAULT_FONT); + GC gc = new GC(window); + Font f = JFaceResources.getFontRegistry().get( + JFaceResources.DEFAULT_FONT); gc.setFont(f); - int height= gc.getFontMetrics().getHeight(); + int height = gc.getFontMetrics().getHeight(); gc.dispose(); - Point p= new Point(height * 3 - 6, height); + Point p = new Point(height * 3 - 6, height); return p; } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/OverlayPreferenceStore.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/OverlayPreferenceStore.java index 11032cf..917e813 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/OverlayPreferenceStore.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/OverlayPreferenceStore.java @@ -15,429 +15,442 @@ import org.eclipse.jface.util.PropertyChangeEvent; */ public class OverlayPreferenceStore implements IPreferenceStore { - public static final class TypeDescriptor { - private TypeDescriptor() { - } - }; - - public static final TypeDescriptor BOOLEAN = new TypeDescriptor(); - public static final TypeDescriptor DOUBLE = new TypeDescriptor(); - public static final TypeDescriptor FLOAT = new TypeDescriptor(); - public static final TypeDescriptor INT = new TypeDescriptor(); - public static final TypeDescriptor LONG = new TypeDescriptor(); - public static final TypeDescriptor STRING = new TypeDescriptor(); - - public static class OverlayKey { - - TypeDescriptor fDescriptor; - String fKey; - - public OverlayKey(TypeDescriptor descriptor, String key) { - fDescriptor = descriptor; - fKey = key; - } - }; - - private class PropertyListener implements IPropertyChangeListener { - - /* - * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) - */ - public void propertyChange(PropertyChangeEvent event) { - OverlayKey key = findOverlayKey(event.getProperty()); - if (key != null) - propagateProperty(fParent, key, fStore); - } - }; - - private IPreferenceStore fParent; - private IPreferenceStore fStore; - private OverlayKey[] fOverlayKeys; - - private PropertyListener fPropertyListener; - - public OverlayPreferenceStore(IPreferenceStore parent, OverlayKey[] overlayKeys) { - fParent = parent; - fOverlayKeys = overlayKeys; - fStore = new PreferenceStore(); - } - - private OverlayKey findOverlayKey(String key) { - for (int i = 0; i < fOverlayKeys.length; i++) { - if (fOverlayKeys[i].fKey.equals(key)) - return fOverlayKeys[i]; - } - return null; - } + public static final class TypeDescriptor { + private TypeDescriptor() { + } + }; - private boolean covers(String key) { - return (findOverlayKey(key) != null); - } + public static final TypeDescriptor BOOLEAN = new TypeDescriptor(); - private void propagateProperty(IPreferenceStore orgin, OverlayKey key, IPreferenceStore target) { - - if (orgin.isDefault(key.fKey)) { - if (!target.isDefault(key.fKey)) - target.setToDefault(key.fKey); - return; - } + public static final TypeDescriptor DOUBLE = new TypeDescriptor(); - TypeDescriptor d = key.fDescriptor; - if (BOOLEAN == d) { + public static final TypeDescriptor FLOAT = new TypeDescriptor(); - boolean originValue = orgin.getBoolean(key.fKey); - boolean targetValue = target.getBoolean(key.fKey); - if (targetValue != originValue) - target.setValue(key.fKey, originValue); + public static final TypeDescriptor INT = new TypeDescriptor(); - } else if (DOUBLE == d) { - - double originValue = orgin.getDouble(key.fKey); - double targetValue = target.getDouble(key.fKey); - if (targetValue != originValue) - target.setValue(key.fKey, originValue); - - } else if (FLOAT == d) { - - float originValue = orgin.getFloat(key.fKey); - float targetValue = target.getFloat(key.fKey); - if (targetValue != originValue) - target.setValue(key.fKey, originValue); - - } else if (INT == d) { - - int originValue = orgin.getInt(key.fKey); - int targetValue = target.getInt(key.fKey); - if (targetValue != originValue) - target.setValue(key.fKey, originValue); - - } else if (LONG == d) { - - long originValue = orgin.getLong(key.fKey); - long targetValue = target.getLong(key.fKey); - if (targetValue != originValue) - target.setValue(key.fKey, originValue); - - } else if (STRING == d) { - - String originValue = orgin.getString(key.fKey); - String targetValue = target.getString(key.fKey); - if (targetValue != null && originValue != null && !targetValue.equals(originValue)) - target.setValue(key.fKey, originValue); - - } - } - - public void propagate() { - for (int i = 0; i < fOverlayKeys.length; i++) - propagateProperty(fStore, fOverlayKeys[i], fParent); - } - - private void loadProperty(IPreferenceStore orgin, OverlayKey key, IPreferenceStore target, boolean forceInitialization) { - TypeDescriptor d = key.fDescriptor; - if (BOOLEAN == d) { - - if (forceInitialization) - target.setValue(key.fKey, true); - target.setValue(key.fKey, orgin.getBoolean(key.fKey)); - target.setDefault(key.fKey, orgin.getDefaultBoolean(key.fKey)); - - } else if (DOUBLE == d) { - - if (forceInitialization) - target.setValue(key.fKey, 1.0D); - target.setValue(key.fKey, orgin.getDouble(key.fKey)); - target.setDefault(key.fKey, orgin.getDefaultDouble(key.fKey)); - - } else if (FLOAT == d) { - - if (forceInitialization) - target.setValue(key.fKey, 1.0F); - target.setValue(key.fKey, orgin.getFloat(key.fKey)); - target.setDefault(key.fKey, orgin.getDefaultFloat(key.fKey)); - - } else if (INT == d) { - - if (forceInitialization) - target.setValue(key.fKey, 1); - target.setValue(key.fKey, orgin.getInt(key.fKey)); - target.setDefault(key.fKey, orgin.getDefaultInt(key.fKey)); - - } else if (LONG == d) { - - if (forceInitialization) - target.setValue(key.fKey, 1L); - target.setValue(key.fKey, orgin.getLong(key.fKey)); - target.setDefault(key.fKey, orgin.getDefaultLong(key.fKey)); - - } else if (STRING == d) { - - if (forceInitialization) - target.setValue(key.fKey, "1"); //$NON-NLS-1$ - target.setValue(key.fKey, orgin.getString(key.fKey)); - target.setDefault(key.fKey, orgin.getDefaultString(key.fKey)); - - } - } - - public void load() { - for (int i = 0; i < fOverlayKeys.length; i++) - loadProperty(fParent, fOverlayKeys[i], fStore, true); - } - - public void loadDefaults() { - for (int i = 0; i < fOverlayKeys.length; i++) - setToDefault(fOverlayKeys[i].fKey); - } - - public void start() { - if (fPropertyListener == null) { - fPropertyListener = new PropertyListener(); - fParent.addPropertyChangeListener(fPropertyListener); - } - } - - public void stop() { - if (fPropertyListener != null) { - fParent.removePropertyChangeListener(fPropertyListener); - fPropertyListener = null; - } - } - - /* - * @see IPreferenceStore#addPropertyChangeListener(IPropertyChangeListener) - */ - public void addPropertyChangeListener(IPropertyChangeListener listener) { - fStore.addPropertyChangeListener(listener); - } - - /* - * @see IPreferenceStore#removePropertyChangeListener(IPropertyChangeListener) - */ - public void removePropertyChangeListener(IPropertyChangeListener listener) { - fStore.removePropertyChangeListener(listener); - } - - /* - * @see IPreferenceStore#firePropertyChangeEvent(String, Object, Object) - */ - public void firePropertyChangeEvent(String name, Object oldValue, Object newValue) { - fStore.firePropertyChangeEvent(name, oldValue, newValue); - } - - /* - * @see IPreferenceStore#contains(String) - */ - public boolean contains(String name) { - return fStore.contains(name); - } - - /* - * @see IPreferenceStore#getBoolean(String) - */ - public boolean getBoolean(String name) { - return fStore.getBoolean(name); - } - - /* - * @see IPreferenceStore#getDefaultBoolean(String) - */ - public boolean getDefaultBoolean(String name) { - return fStore.getDefaultBoolean(name); - } - - /* - * @see IPreferenceStore#getDefaultDouble(String) - */ - public double getDefaultDouble(String name) { - return fStore.getDefaultDouble(name); - } - - /* - * @see IPreferenceStore#getDefaultFloat(String) - */ - public float getDefaultFloat(String name) { - return fStore.getDefaultFloat(name); - } - - /* - * @see IPreferenceStore#getDefaultInt(String) - */ - public int getDefaultInt(String name) { - return fStore.getDefaultInt(name); - } - - /* - * @see IPreferenceStore#getDefaultLong(String) - */ - public long getDefaultLong(String name) { - return fStore.getDefaultLong(name); - } - - /* - * @see IPreferenceStore#getDefaultString(String) - */ - public String getDefaultString(String name) { - return fStore.getDefaultString(name); - } - - /* - * @see IPreferenceStore#getDouble(String) - */ - public double getDouble(String name) { - return fStore.getDouble(name); - } - - /* - * @see IPreferenceStore#getFloat(String) - */ - public float getFloat(String name) { - return fStore.getFloat(name); - } - - /* - * @see IPreferenceStore#getInt(String) - */ - public int getInt(String name) { - return fStore.getInt(name); - } - - /* - * @see IPreferenceStore#getLong(String) - */ - public long getLong(String name) { - return fStore.getLong(name); - } - - /* - * @see IPreferenceStore#getString(String) - */ - public String getString(String name) { - return fStore.getString(name); - } - - /* - * @see IPreferenceStore#isDefault(String) - */ - public boolean isDefault(String name) { - return fStore.isDefault(name); - } - - /* - * @see IPreferenceStore#needsSaving() - */ - public boolean needsSaving() { - return fStore.needsSaving(); - } - - /* - * @see IPreferenceStore#putValue(String, String) - */ - public void putValue(String name, String value) { - if (covers(name)) - fStore.putValue(name, value); - } - - /* - * @see IPreferenceStore#setDefault(String, double) - */ - public void setDefault(String name, double value) { - if (covers(name)) - fStore.setDefault(name, value); - } - - /* - * @see IPreferenceStore#setDefault(String, float) - */ - public void setDefault(String name, float value) { - if (covers(name)) - fStore.setDefault(name, value); - } - - /* - * @see IPreferenceStore#setDefault(String, int) - */ - public void setDefault(String name, int value) { - if (covers(name)) - fStore.setDefault(name, value); - } - - /* - * @see IPreferenceStore#setDefault(String, long) - */ - public void setDefault(String name, long value) { - if (covers(name)) - fStore.setDefault(name, value); - } - - /* - * @see IPreferenceStore#setDefault(String, String) - */ - public void setDefault(String name, String value) { - if (covers(name)) - fStore.setDefault(name, value); - } - - /* - * @see IPreferenceStore#setDefault(String, boolean) - */ - public void setDefault(String name, boolean value) { - if (covers(name)) - fStore.setDefault(name, value); - } - - /* - * @see IPreferenceStore#setToDefault(String) - */ - public void setToDefault(String name) { - fStore.setToDefault(name); - } - - /* - * @see IPreferenceStore#setValue(String, double) - */ - public void setValue(String name, double value) { - if (covers(name)) - fStore.setValue(name, value); - } - - /* - * @see IPreferenceStore#setValue(String, float) - */ - public void setValue(String name, float value) { - if (covers(name)) - fStore.setValue(name, value); - } - - /* - * @see IPreferenceStore#setValue(String, int) - */ - public void setValue(String name, int value) { - if (covers(name)) - fStore.setValue(name, value); - } - - /* - * @see IPreferenceStore#setValue(String, long) - */ - public void setValue(String name, long value) { - if (covers(name)) - fStore.setValue(name, value); - } - - /* - * @see IPreferenceStore#setValue(String, String) - */ - public void setValue(String name, String value) { - if (covers(name)) - fStore.setValue(name, value); - } - - /* - * @see IPreferenceStore#setValue(String, boolean) - */ - public void setValue(String name, boolean value) { - if (covers(name)) - fStore.setValue(name, value); - } + public static final TypeDescriptor LONG = new TypeDescriptor(); + + public static final TypeDescriptor STRING = new TypeDescriptor(); + + public static class OverlayKey { + + TypeDescriptor fDescriptor; + + String fKey; + + public OverlayKey(TypeDescriptor descriptor, String key) { + fDescriptor = descriptor; + fKey = key; + } + }; + + private class PropertyListener implements IPropertyChangeListener { + + /* + * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) + */ + public void propertyChange(PropertyChangeEvent event) { + OverlayKey key = findOverlayKey(event.getProperty()); + if (key != null) + propagateProperty(fParent, key, fStore); + } + }; + + private IPreferenceStore fParent; + + private IPreferenceStore fStore; + + private OverlayKey[] fOverlayKeys; + + private PropertyListener fPropertyListener; + + public OverlayPreferenceStore(IPreferenceStore parent, + OverlayKey[] overlayKeys) { + fParent = parent; + fOverlayKeys = overlayKeys; + fStore = new PreferenceStore(); + } + + private OverlayKey findOverlayKey(String key) { + for (int i = 0; i < fOverlayKeys.length; i++) { + if (fOverlayKeys[i].fKey.equals(key)) + return fOverlayKeys[i]; + } + return null; + } + + private boolean covers(String key) { + return (findOverlayKey(key) != null); + } + + private void propagateProperty(IPreferenceStore orgin, OverlayKey key, + IPreferenceStore target) { + + if (orgin.isDefault(key.fKey)) { + if (!target.isDefault(key.fKey)) + target.setToDefault(key.fKey); + return; + } + + TypeDescriptor d = key.fDescriptor; + if (BOOLEAN == d) { + + boolean originValue = orgin.getBoolean(key.fKey); + boolean targetValue = target.getBoolean(key.fKey); + if (targetValue != originValue) + target.setValue(key.fKey, originValue); + + } else if (DOUBLE == d) { + + double originValue = orgin.getDouble(key.fKey); + double targetValue = target.getDouble(key.fKey); + if (targetValue != originValue) + target.setValue(key.fKey, originValue); + + } else if (FLOAT == d) { + + float originValue = orgin.getFloat(key.fKey); + float targetValue = target.getFloat(key.fKey); + if (targetValue != originValue) + target.setValue(key.fKey, originValue); + + } else if (INT == d) { + + int originValue = orgin.getInt(key.fKey); + int targetValue = target.getInt(key.fKey); + if (targetValue != originValue) + target.setValue(key.fKey, originValue); + + } else if (LONG == d) { + + long originValue = orgin.getLong(key.fKey); + long targetValue = target.getLong(key.fKey); + if (targetValue != originValue) + target.setValue(key.fKey, originValue); + + } else if (STRING == d) { + + String originValue = orgin.getString(key.fKey); + String targetValue = target.getString(key.fKey); + if (targetValue != null && originValue != null + && !targetValue.equals(originValue)) + target.setValue(key.fKey, originValue); + + } + } + + public void propagate() { + for (int i = 0; i < fOverlayKeys.length; i++) + propagateProperty(fStore, fOverlayKeys[i], fParent); + } + + private void loadProperty(IPreferenceStore orgin, OverlayKey key, + IPreferenceStore target, boolean forceInitialization) { + TypeDescriptor d = key.fDescriptor; + if (BOOLEAN == d) { + + if (forceInitialization) + target.setValue(key.fKey, true); + target.setValue(key.fKey, orgin.getBoolean(key.fKey)); + target.setDefault(key.fKey, orgin.getDefaultBoolean(key.fKey)); + + } else if (DOUBLE == d) { + + if (forceInitialization) + target.setValue(key.fKey, 1.0D); + target.setValue(key.fKey, orgin.getDouble(key.fKey)); + target.setDefault(key.fKey, orgin.getDefaultDouble(key.fKey)); + + } else if (FLOAT == d) { + + if (forceInitialization) + target.setValue(key.fKey, 1.0F); + target.setValue(key.fKey, orgin.getFloat(key.fKey)); + target.setDefault(key.fKey, orgin.getDefaultFloat(key.fKey)); + + } else if (INT == d) { + + if (forceInitialization) + target.setValue(key.fKey, 1); + target.setValue(key.fKey, orgin.getInt(key.fKey)); + target.setDefault(key.fKey, orgin.getDefaultInt(key.fKey)); + + } else if (LONG == d) { + + if (forceInitialization) + target.setValue(key.fKey, 1L); + target.setValue(key.fKey, orgin.getLong(key.fKey)); + target.setDefault(key.fKey, orgin.getDefaultLong(key.fKey)); + + } else if (STRING == d) { + + if (forceInitialization) + target.setValue(key.fKey, "1"); //$NON-NLS-1$ + target.setValue(key.fKey, orgin.getString(key.fKey)); + target.setDefault(key.fKey, orgin.getDefaultString(key.fKey)); + + } + } + + public void load() { + for (int i = 0; i < fOverlayKeys.length; i++) + loadProperty(fParent, fOverlayKeys[i], fStore, true); + } + + public void loadDefaults() { + for (int i = 0; i < fOverlayKeys.length; i++) + setToDefault(fOverlayKeys[i].fKey); + } + + public void start() { + if (fPropertyListener == null) { + fPropertyListener = new PropertyListener(); + fParent.addPropertyChangeListener(fPropertyListener); + } + } + + public void stop() { + if (fPropertyListener != null) { + fParent.removePropertyChangeListener(fPropertyListener); + fPropertyListener = null; + } + } + + /* + * @see IPreferenceStore#addPropertyChangeListener(IPropertyChangeListener) + */ + public void addPropertyChangeListener(IPropertyChangeListener listener) { + fStore.addPropertyChangeListener(listener); + } + + /* + * @see IPreferenceStore#removePropertyChangeListener(IPropertyChangeListener) + */ + public void removePropertyChangeListener(IPropertyChangeListener listener) { + fStore.removePropertyChangeListener(listener); + } + + /* + * @see IPreferenceStore#firePropertyChangeEvent(String, Object, Object) + */ + public void firePropertyChangeEvent(String name, Object oldValue, + Object newValue) { + fStore.firePropertyChangeEvent(name, oldValue, newValue); + } + + /* + * @see IPreferenceStore#contains(String) + */ + public boolean contains(String name) { + return fStore.contains(name); + } + + /* + * @see IPreferenceStore#getBoolean(String) + */ + public boolean getBoolean(String name) { + return fStore.getBoolean(name); + } + + /* + * @see IPreferenceStore#getDefaultBoolean(String) + */ + public boolean getDefaultBoolean(String name) { + return fStore.getDefaultBoolean(name); + } + + /* + * @see IPreferenceStore#getDefaultDouble(String) + */ + public double getDefaultDouble(String name) { + return fStore.getDefaultDouble(name); + } + + /* + * @see IPreferenceStore#getDefaultFloat(String) + */ + public float getDefaultFloat(String name) { + return fStore.getDefaultFloat(name); + } + + /* + * @see IPreferenceStore#getDefaultInt(String) + */ + public int getDefaultInt(String name) { + return fStore.getDefaultInt(name); + } + + /* + * @see IPreferenceStore#getDefaultLong(String) + */ + public long getDefaultLong(String name) { + return fStore.getDefaultLong(name); + } + + /* + * @see IPreferenceStore#getDefaultString(String) + */ + public String getDefaultString(String name) { + return fStore.getDefaultString(name); + } + + /* + * @see IPreferenceStore#getDouble(String) + */ + public double getDouble(String name) { + return fStore.getDouble(name); + } + + /* + * @see IPreferenceStore#getFloat(String) + */ + public float getFloat(String name) { + return fStore.getFloat(name); + } + + /* + * @see IPreferenceStore#getInt(String) + */ + public int getInt(String name) { + return fStore.getInt(name); + } + + /* + * @see IPreferenceStore#getLong(String) + */ + public long getLong(String name) { + return fStore.getLong(name); + } + + /* + * @see IPreferenceStore#getString(String) + */ + public String getString(String name) { + return fStore.getString(name); + } + + /* + * @see IPreferenceStore#isDefault(String) + */ + public boolean isDefault(String name) { + return fStore.isDefault(name); + } + + /* + * @see IPreferenceStore#needsSaving() + */ + public boolean needsSaving() { + return fStore.needsSaving(); + } + + /* + * @see IPreferenceStore#putValue(String, String) + */ + public void putValue(String name, String value) { + if (covers(name)) + fStore.putValue(name, value); + } + + /* + * @see IPreferenceStore#setDefault(String, double) + */ + public void setDefault(String name, double value) { + if (covers(name)) + fStore.setDefault(name, value); + } + + /* + * @see IPreferenceStore#setDefault(String, float) + */ + public void setDefault(String name, float value) { + if (covers(name)) + fStore.setDefault(name, value); + } + + /* + * @see IPreferenceStore#setDefault(String, int) + */ + public void setDefault(String name, int value) { + if (covers(name)) + fStore.setDefault(name, value); + } + + /* + * @see IPreferenceStore#setDefault(String, long) + */ + public void setDefault(String name, long value) { + if (covers(name)) + fStore.setDefault(name, value); + } + + /* + * @see IPreferenceStore#setDefault(String, String) + */ + public void setDefault(String name, String value) { + if (covers(name)) + fStore.setDefault(name, value); + } + + /* + * @see IPreferenceStore#setDefault(String, boolean) + */ + public void setDefault(String name, boolean value) { + if (covers(name)) + fStore.setDefault(name, value); + } + + /* + * @see IPreferenceStore#setToDefault(String) + */ + public void setToDefault(String name) { + fStore.setToDefault(name); + } + + /* + * @see IPreferenceStore#setValue(String, double) + */ + public void setValue(String name, double value) { + if (covers(name)) + fStore.setValue(name, value); + } + + /* + * @see IPreferenceStore#setValue(String, float) + */ + public void setValue(String name, float value) { + if (covers(name)) + fStore.setValue(name, value); + } + + /* + * @see IPreferenceStore#setValue(String, int) + */ + public void setValue(String name, int value) { + if (covers(name)) + fStore.setValue(name, value); + } + + /* + * @see IPreferenceStore#setValue(String, long) + */ + public void setValue(String name, long value) { + if (covers(name)) + fStore.setValue(name, value); + } + + /* + * @see IPreferenceStore#setValue(String, String) + */ + public void setValue(String name, String value) { + if (covers(name)) + fStore.setValue(name, value); + } + + /* + * @see IPreferenceStore#setValue(String, boolean) + */ + public void setValue(String name, boolean value) { + if (covers(name)) + fStore.setValue(name, value); + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPPreferencesMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPPreferencesMessages.java index 69e0c0d..1c60d30 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPPreferencesMessages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPPreferencesMessages.java @@ -6,8 +6,11 @@ import java.util.ResourceBundle; public class PHPPreferencesMessages { - private static final String RESOURCE_BUNDLE= PHPPreferencesMessages.class.getName(); - private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); + private static final String RESOURCE_BUNDLE = PHPPreferencesMessages.class + .getName(); + + private static ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); private PHPPreferencesMessages() { } @@ -19,20 +22,20 @@ public class PHPPreferencesMessages { return '!' + key + '!'; } } - + /** * Gets a string from the resource bundle and formats it with the argument * - * @param key the string used to get the bundle value, must not be null + * @param key + * the string used to get the bundle value, must not be null */ public static String getFormattedString(String key, Object arg) { return MessageFormat.format(getString(key), new Object[] { arg }); } - /** * Gets a string from the resource bundle and formats it with arguments - */ + */ public static String getFormattedString(String key, Object[] args) { return MessageFormat.format(getString(key), args); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPProjectLibraryPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPProjectLibraryPage.java index 98fe54d..c088627 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPProjectLibraryPage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPProjectLibraryPage.java @@ -30,124 +30,135 @@ import org.eclipse.ui.IWorkbench; import org.eclipse.ui.ide.IDE.SharedImages; public class PHPProjectLibraryPage { - protected JavaProject workingProject; - - protected PHPProjectLibraryPage(JavaProject theWorkingProject) { - super(); - workingProject = theWorkingProject; - } - - protected Control getControl(Composite parent) { - Composite composite = new Composite(parent, SWT.NONE); - composite.setLayout(new FillLayout()); - - Table projectsTable = new Table(composite, SWT.CHECK | SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION); - projectsTable.setHeaderVisible(false); - projectsTable.setLinesVisible(false); - projectsTable.computeSize(SWT.DEFAULT, SWT.DEFAULT); - - TableColumn tableColumn = new TableColumn(projectsTable, SWT.NONE); - tableColumn.setWidth(200); - tableColumn.setText(PHPPreferencesMessages.getString("PHPEditorPreferencePageLibraryPage.project")); //$NON-NLS-1$ - - CheckboxTableViewer projectsTableViewer = new CheckboxTableViewer(projectsTable); - projectsTableViewer.addCheckStateListener(new ICheckStateListener() { - public void checkStateChanged(CheckStateChangedEvent event) { - projectCheckedUnchecked(event); - } - }); - - projectsTableViewer.setContentProvider(getContentProvider()); - projectsTableViewer.setLabelProvider(getLabelProvider()); - - projectsTableViewer.setInput(getWorkspaceProjects()); - projectsTableViewer.setCheckedElements(workingProject.getReferencedProjects().toArray()); - - return composite; - } - - protected void projectCheckedUnchecked(CheckStateChangedEvent event) { - IProject checkEventProject = (IProject) event.getElement(); - if (event.getChecked()) - getWorkingProject().addLoadPathEntry(checkEventProject); - else - getWorkingProject().removeLoadPathEntry(checkEventProject); - } - - protected JavaProject getWorkingProject() { - return workingProject; - } - - protected List getWorkspaceProjects() { - IWorkspaceRoot root = PHPeclipsePlugin.getWorkspace().getRoot(); - return Arrays.asList(root.getProjects()); - } - - protected ITableLabelProvider getLabelProvider() { - ITableLabelProvider labelProvider = new ITableLabelProvider() { - public Image getColumnImage(Object element, int columnIndex) { - IWorkbench workbench = PHPeclipsePlugin.getDefault().getWorkbench(); - return workbench.getSharedImages().getImage(SharedImages.IMG_OBJ_PROJECT); - } - - public String getColumnText(Object element, int columnIndex) { - if (element instanceof IProject) - return ((IProject) element).getName(); - - return PHPPreferencesMessages.getString("PHPEditorPreferencePageLibraryPage.elementNotIProject"); //$NON-NLS-1$ - } - - public void addListener(ILabelProviderListener listener) { - } - - public void dispose() { - } - - public boolean isLabelProperty(Object element, String property) { - return false; - } - - public void removeListener(ILabelProviderListener listener) { - } - }; - - return labelProvider; - } - - protected IContentProvider getContentProvider() { - IStructuredContentProvider contentProvider = new IStructuredContentProvider() { - protected List PHPEditorPreferencePages; - - public Object[] getElements(Object inputElement) { - return PHPEditorPreferencePages.toArray(); - } - - public void dispose() { - } - - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - PHPEditorPreferencePages = new ArrayList(); - - if (!(newInput instanceof List)) - return; - - Iterator workspaceProjectsIterator = ((List) newInput).iterator(); - while (workspaceProjectsIterator.hasNext()) { - Object anObject = workspaceProjectsIterator.next(); - if (anObject instanceof IProject) { - IProject project = (IProject) anObject; - if (project.getName() != workingProject.getProject().getName()) { - try { - if (project.hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) - PHPEditorPreferencePages.add(project); - } catch (CoreException e) { - } - } - } - } - } - }; - - return contentProvider; - } + protected JavaProject workingProject; + + protected PHPProjectLibraryPage(JavaProject theWorkingProject) { + super(); + workingProject = theWorkingProject; + } + + protected Control getControl(Composite parent) { + Composite composite = new Composite(parent, SWT.NONE); + composite.setLayout(new FillLayout()); + + Table projectsTable = new Table(composite, SWT.CHECK | SWT.BORDER + | SWT.MULTI | SWT.FULL_SELECTION); + projectsTable.setHeaderVisible(false); + projectsTable.setLinesVisible(false); + projectsTable.computeSize(SWT.DEFAULT, SWT.DEFAULT); + + TableColumn tableColumn = new TableColumn(projectsTable, SWT.NONE); + tableColumn.setWidth(200); + tableColumn.setText(PHPPreferencesMessages + .getString("PHPEditorPreferencePageLibraryPage.project")); //$NON-NLS-1$ + + CheckboxTableViewer projectsTableViewer = new CheckboxTableViewer( + projectsTable); + projectsTableViewer.addCheckStateListener(new ICheckStateListener() { + public void checkStateChanged(CheckStateChangedEvent event) { + projectCheckedUnchecked(event); + } + }); + + projectsTableViewer.setContentProvider(getContentProvider()); + projectsTableViewer.setLabelProvider(getLabelProvider()); + + projectsTableViewer.setInput(getWorkspaceProjects()); + projectsTableViewer.setCheckedElements(workingProject + .getReferencedProjects().toArray()); + + return composite; + } + + protected void projectCheckedUnchecked(CheckStateChangedEvent event) { + IProject checkEventProject = (IProject) event.getElement(); + if (event.getChecked()) + getWorkingProject().addLoadPathEntry(checkEventProject); + else + getWorkingProject().removeLoadPathEntry(checkEventProject); + } + + protected JavaProject getWorkingProject() { + return workingProject; + } + + protected List getWorkspaceProjects() { + IWorkspaceRoot root = PHPeclipsePlugin.getWorkspace().getRoot(); + return Arrays.asList(root.getProjects()); + } + + protected ITableLabelProvider getLabelProvider() { + ITableLabelProvider labelProvider = new ITableLabelProvider() { + public Image getColumnImage(Object element, int columnIndex) { + IWorkbench workbench = PHPeclipsePlugin.getDefault() + .getWorkbench(); + return workbench.getSharedImages().getImage( + SharedImages.IMG_OBJ_PROJECT); + } + + public String getColumnText(Object element, int columnIndex) { + if (element instanceof IProject) + return ((IProject) element).getName(); + + return PHPPreferencesMessages + .getString("PHPEditorPreferencePageLibraryPage.elementNotIProject"); //$NON-NLS-1$ + } + + public void addListener(ILabelProviderListener listener) { + } + + public void dispose() { + } + + public boolean isLabelProperty(Object element, String property) { + return false; + } + + public void removeListener(ILabelProviderListener listener) { + } + }; + + return labelProvider; + } + + protected IContentProvider getContentProvider() { + IStructuredContentProvider contentProvider = new IStructuredContentProvider() { + protected List PHPEditorPreferencePages; + + public Object[] getElements(Object inputElement) { + return PHPEditorPreferencePages.toArray(); + } + + public void dispose() { + } + + public void inputChanged(Viewer viewer, Object oldInput, + Object newInput) { + PHPEditorPreferencePages = new ArrayList(); + + if (!(newInput instanceof List)) + return; + + Iterator workspaceProjectsIterator = ((List) newInput) + .iterator(); + while (workspaceProjectsIterator.hasNext()) { + Object anObject = workspaceProjectsIterator.next(); + if (anObject instanceof IProject) { + IProject project = (IProject) anObject; + if (project.getName() != workingProject.getProject() + .getName()) { + try { + if (project + .hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) + PHPEditorPreferencePages.add(project); + } catch (CoreException e) { + } + } + } + } + } + }; + + return contentProvider; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPProjectPropertyPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPProjectPropertyPage.java index e336c0b..2f3ba51 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPProjectPropertyPage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPProjectPropertyPage.java @@ -19,79 +19,84 @@ import org.eclipse.swt.widgets.TabItem; import org.eclipse.ui.IWorkbenchPropertyPage; import org.eclipse.ui.dialogs.PropertyPage; -public class PHPProjectPropertyPage extends PropertyPage implements IWorkbenchPropertyPage { - protected PHPProjectLibraryPage projectsPage; - protected JavaProject workingProject; - - public PHPProjectPropertyPage() { - } - - protected Control createContents(Composite parent) { - noDefaultAndApplyButton(); - - workingProject = getPHPProject(); - if (workingProject == null || !workingProject.getProject().isOpen()) - return createClosedProjectPageContents(parent); - - return createProjectPageContents(parent); - } - - protected JavaProject getPHPProject() { - IAdaptable selectedElement = getElement(); - if (selectedElement == null) - return null; - - if (selectedElement instanceof JavaProject) - return (JavaProject) selectedElement; - - if (selectedElement instanceof IProject) { - IProject simpleProject = (IProject) selectedElement; - try { - if (simpleProject.hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) { - JavaProject phpProject = new JavaProject(); - phpProject.setProject(simpleProject); - return phpProject; - } - } catch (CoreException e) { - PHPeclipsePlugin.log(e); - } - } - - return null; - } - - protected Control createClosedProjectPageContents(Composite parent) { - Label label = new Label(parent, SWT.NONE); - label.setText(PHPPreferencesMessages.getString("PHPProjectPropertyPage.phpProjectClosed")); //$NON-NLS-1$ - - return label; - } - - protected Control createProjectPageContents(Composite parent) { - TabFolder tabFolder = new TabFolder(parent, SWT.NONE); - tabFolder.setLayout(new GridLayout()); - tabFolder.setLayoutData(new GridData(GridData.FILL_BOTH)); - tabFolder.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - //tabChanged(e.item); - } - }); - - projectsPage = new PHPProjectLibraryPage(workingProject); - TabItem tabItem = new TabItem(tabFolder, SWT.NONE); - tabItem.setText(PHPPreferencesMessages.getString("PHPProjectLibraryPage.tabName")); //$NON-NLS-1$ - // tabItem.setData(projectsPage); - tabItem.setControl(projectsPage.getControl(tabFolder)); - - return tabFolder; - } - public boolean performOk() { - try { - projectsPage.getWorkingProject().save(); - } catch (CoreException e) { - PHPeclipsePlugin.log(e); - } - return super.performOk(); - } +public class PHPProjectPropertyPage extends PropertyPage implements + IWorkbenchPropertyPage { + protected PHPProjectLibraryPage projectsPage; + + protected JavaProject workingProject; + + public PHPProjectPropertyPage() { + } + + protected Control createContents(Composite parent) { + noDefaultAndApplyButton(); + + workingProject = getPHPProject(); + if (workingProject == null || !workingProject.getProject().isOpen()) + return createClosedProjectPageContents(parent); + + return createProjectPageContents(parent); + } + + protected JavaProject getPHPProject() { + IAdaptable selectedElement = getElement(); + if (selectedElement == null) + return null; + + if (selectedElement instanceof JavaProject) + return (JavaProject) selectedElement; + + if (selectedElement instanceof IProject) { + IProject simpleProject = (IProject) selectedElement; + try { + if (simpleProject.hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) { + JavaProject phpProject = new JavaProject(); + phpProject.setProject(simpleProject); + return phpProject; + } + } catch (CoreException e) { + PHPeclipsePlugin.log(e); + } + } + + return null; + } + + protected Control createClosedProjectPageContents(Composite parent) { + Label label = new Label(parent, SWT.NONE); + label.setText(PHPPreferencesMessages + .getString("PHPProjectPropertyPage.phpProjectClosed")); //$NON-NLS-1$ + + return label; + } + + protected Control createProjectPageContents(Composite parent) { + TabFolder tabFolder = new TabFolder(parent, SWT.NONE); + tabFolder.setLayout(new GridLayout()); + tabFolder.setLayoutData(new GridData(GridData.FILL_BOTH)); + tabFolder.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + // tabChanged(e.item); + } + }); + + projectsPage = new PHPProjectLibraryPage(workingProject); + TabItem tabItem = new TabItem(tabFolder, SWT.NONE); + tabItem.setText(PHPPreferencesMessages + .getString("PHPProjectLibraryPage.tabName")); //$NON-NLS-1$ + // tabItem.setData(projectsPage); + tabItem.setControl(projectsPage.getControl(tabFolder)); + + return tabFolder; + } + + public boolean performOk() { + try { + projectsPage.getWorkingProject().save(); + } catch (CoreException e) { + PHPeclipsePlugin.log(e); + } + return super.performOk(); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/HTMLFileWizard.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/HTMLFileWizard.java index 0f9c718..4f1ae6d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/HTMLFileWizard.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/HTMLFileWizard.java @@ -52,126 +52,142 @@ import org.eclipse.ui.ide.IDE; */ public class HTMLFileWizard extends Wizard implements INewWizard { - private HTMLFileWizardPage page; - - private ISelection selection; - - public HTMLFileWizard() { - super(); - setNeedsProgressMonitor(true); - setWindowTitle(PHPWizardMessages.getString("WizardNewProjectCreationPage.html.windowTitle")); - } - - /** - * Adding the page to the wizard. - */ - public void addPages() { - page = new HTMLFileWizardPage(selection); - addPage(page); - } - - /** - * This method is called when 'Finish' button is pressed in the wizard. We will create an operation and run it using wizard as - * execution context. - */ - public boolean performFinish() { - final String containerName = page.getContainerName(); - final String fileName = page.getFileName(); - IRunnableWithProgress op = new IRunnableWithProgress() { - public void run(IProgressMonitor monitor) throws InvocationTargetException { - try { - doFinish(containerName, fileName, monitor); - } catch (CoreException e) { - throw new InvocationTargetException(e); - } finally { - monitor.done(); - } - } - }; - try { - getContainer().run(true, false, op); - } catch (InterruptedException e) { - return false; - } catch (InvocationTargetException e) { - Throwable realException = e.getTargetException(); - MessageDialog.openError(getShell(), PHPWizardMessages.getString("Wizard.error"), realException.getMessage()); - return false; - } - return true; - } - - /** - * The worker method. It will find the container, create the file if missing or just replace its contents, and open the editor on - * the newly created file. - */ - private void doFinish(String containerName, String fileName, IProgressMonitor monitor) throws CoreException { - // create a sample file - monitor.beginTask(PHPWizardMessages.getString("Wizard.Monitor.creating") + " " + fileName, 2); - IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); - IResource resource = root.findMember(new Path(containerName)); - if (!resource.exists() || !(resource instanceof IContainer)) { - throwCoreException(PHPWizardMessages.getString("Wizard.Monitor.containerDoesNotExistException")); - } - IContainer container = (IContainer) resource; - final IFile file = container.getFile(new Path(fileName)); - IProject project = file.getProject(); - String projectName = project.getName(); - try { - InputStream stream; - stream = openContentStream(fileName, projectName); - if (file.exists()) { - file.setContents(stream, true, true, monitor); - } else { - file.create(stream, true, monitor); - } - stream.close(); - } catch (IOException e) { - } - monitor.worked(1); - monitor.setTaskName(PHPWizardMessages.getString("Wizard.Monitor.openingFile")); - getShell().getDisplay().asyncExec(new Runnable() { - public void run() { - IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); - try { - IDE.openEditor(page, file, true); - } catch (PartInitException e) { - } - } - }); - monitor.worked(1); - } - - /** - * We will initialize file contents with a sample text. - */ - private InputStream openContentStream(String fileName, String projectname) { - try { - Template template = PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(CodeTemplateContextType.NEWHTML); - if (template == null) { - return null; - } - String lineDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ - CodeTemplateContext context = new CodeTemplateContext(template.getContextTypeId(), null, lineDelimiter); - context.setFileNameVariable(fileName, projectname); - return new ByteArrayInputStream(StubUtility.evaluateTemplate(context, template).getBytes()); - } catch (CoreException e) { - e.printStackTrace(); - return null; - } - } - - private void throwCoreException(String message) throws CoreException { - IStatus status = new Status(IStatus.ERROR, "net.sourceforge.phpeclipse.wizards", IStatus.OK, message, null); - throw new CoreException(status); - } - - /** - * We will accept the selection in the workbench to see if we can initialize from it. - * - * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection) - */ - public void init(IWorkbench workbench, IStructuredSelection selection) { - this.selection = selection; - } + private HTMLFileWizardPage page; + + private ISelection selection; + + public HTMLFileWizard() { + super(); + setNeedsProgressMonitor(true); + setWindowTitle(PHPWizardMessages + .getString("WizardNewProjectCreationPage.html.windowTitle")); + } + + /** + * Adding the page to the wizard. + */ + public void addPages() { + page = new HTMLFileWizardPage(selection); + addPage(page); + } + + /** + * This method is called when 'Finish' button is pressed in the wizard. We + * will create an operation and run it using wizard as execution context. + */ + public boolean performFinish() { + final String containerName = page.getContainerName(); + final String fileName = page.getFileName(); + IRunnableWithProgress op = new IRunnableWithProgress() { + public void run(IProgressMonitor monitor) + throws InvocationTargetException { + try { + doFinish(containerName, fileName, monitor); + } catch (CoreException e) { + throw new InvocationTargetException(e); + } finally { + monitor.done(); + } + } + }; + try { + getContainer().run(true, false, op); + } catch (InterruptedException e) { + return false; + } catch (InvocationTargetException e) { + Throwable realException = e.getTargetException(); + MessageDialog.openError(getShell(), PHPWizardMessages + .getString("Wizard.error"), realException.getMessage()); + return false; + } + return true; + } + + /** + * The worker method. It will find the container, create the file if missing + * or just replace its contents, and open the editor on the newly created + * file. + */ + private void doFinish(String containerName, String fileName, + IProgressMonitor monitor) throws CoreException { + // create a sample file + monitor.beginTask(PHPWizardMessages + .getString("Wizard.Monitor.creating") + + " " + fileName, 2); + IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); + IResource resource = root.findMember(new Path(containerName)); + if (!resource.exists() || !(resource instanceof IContainer)) { + throwCoreException(PHPWizardMessages + .getString("Wizard.Monitor.containerDoesNotExistException")); + } + IContainer container = (IContainer) resource; + final IFile file = container.getFile(new Path(fileName)); + IProject project = file.getProject(); + String projectName = project.getName(); + try { + InputStream stream; + stream = openContentStream(fileName, projectName); + if (file.exists()) { + file.setContents(stream, true, true, monitor); + } else { + file.create(stream, true, monitor); + } + stream.close(); + } catch (IOException e) { + } + monitor.worked(1); + monitor.setTaskName(PHPWizardMessages + .getString("Wizard.Monitor.openingFile")); + getShell().getDisplay().asyncExec(new Runnable() { + public void run() { + IWorkbenchPage page = PlatformUI.getWorkbench() + .getActiveWorkbenchWindow().getActivePage(); + try { + IDE.openEditor(page, file, true); + } catch (PartInitException e) { + } + } + }); + monitor.worked(1); + } + + /** + * We will initialize file contents with a sample text. + */ + private InputStream openContentStream(String fileName, String projectname) { + try { + Template template = PHPeclipsePlugin.getDefault() + .getCodeTemplateStore().findTemplate( + CodeTemplateContextType.NEWHTML); + if (template == null) { + return null; + } + String lineDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ + CodeTemplateContext context = new CodeTemplateContext(template + .getContextTypeId(), null, lineDelimiter); + context.setFileNameVariable(fileName, projectname); + return new ByteArrayInputStream(StubUtility.evaluateTemplate( + context, template).getBytes()); + } catch (CoreException e) { + e.printStackTrace(); + return null; + } + } + + private void throwCoreException(String message) throws CoreException { + IStatus status = new Status(IStatus.ERROR, + "net.sourceforge.phpeclipse.wizards", IStatus.OK, message, null); + throw new CoreException(status); + } + + /** + * We will accept the selection in the workbench to see if we can initialize + * from it. + * + * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection) + */ + public void init(IWorkbench workbench, IStructuredSelection selection) { + this.selection = selection; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/HTMLFileWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/HTMLFileWizardPage.java index dc70027..40f8127 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/HTMLFileWizardPage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/HTMLFileWizardPage.java @@ -41,153 +41,156 @@ import org.eclipse.ui.dialogs.ContainerSelectionDialog; */ public class HTMLFileWizardPage extends WizardPage { - private static final String INITIAL_FILENAME = "file.html"; - -private Text containerText; - - private Text fileText; - - private ISelection selection; - - /** - * Constructor for SampleNewWizardPage. - * - * @param pageName - */ - public HTMLFileWizardPage(ISelection selection) { - super("wizardPage"); - setTitle(PHPWizardMessages.getString("WizardPage.html.title")); - setDescription(PHPWizardMessages.getString("WizardPage.html.description")); - this.selection = selection; - } - - /** - * @see IDialogPage#createControl(Composite) - */ - public void createControl(Composite parent) { - Composite container = new Composite(parent, SWT.NULL); - GridLayout layout = new GridLayout(); - container.setLayout(layout); - layout.numColumns = 3; - layout.verticalSpacing = 9; - Label label = new Label(container, SWT.NULL); - label.setText(PHPWizardMessages.getString("WizardPage.containerLabel")); - - containerText = new Text(container, SWT.BORDER | SWT.SINGLE); - GridData gd = new GridData(GridData.FILL_HORIZONTAL); - containerText.setLayoutData(gd); - containerText.addModifyListener(new ModifyListener() { - public void modifyText(ModifyEvent e) { - dialogChanged(); - } - }); - - Button button = new Button(container, SWT.PUSH); - button.setText(PHPWizardMessages.getString("WizardPage.browseButtonText")); - button.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - handleBrowse(); - } - }); - label = new Label(container, SWT.NULL); - label.setText(PHPWizardMessages.getString("WizardPage.fileLabel")); - - fileText = new Text(container, SWT.BORDER | SWT.SINGLE); - gd = new GridData(GridData.FILL_HORIZONTAL); - fileText.setLayoutData(gd); - fileText.addModifyListener(new ModifyListener() { - public void modifyText(ModifyEvent e) { - dialogChanged(); - } - }); - initialize(); - dialogChanged(); - setControl(container); - } - - /** - * Tests if the current workbench selection is a suitable container to use. - */ - - private void initialize() { - if (selection != null && selection.isEmpty() == false - && selection instanceof IStructuredSelection) { - IStructuredSelection ssel = (IStructuredSelection) selection; - if (ssel.size() > 1) - return; - Object obj = ssel.getFirstElement(); - if (obj instanceof IResource) { - IContainer container; - if (obj instanceof IContainer) - container = (IContainer) obj; - else - container = ((IResource) obj).getParent(); - containerText.setText(container.getFullPath().toString()); - fileText.setFocus(); - } - } - fileText.setText(INITIAL_FILENAME); - } - - /** - * Uses the standard container selection dialog to choose the new value for - * the container field. - */ - - private void handleBrowse() { - ContainerSelectionDialog dialog = new ContainerSelectionDialog(getShell(), - ResourcesPlugin.getWorkspace().getRoot(), false, PHPWizardMessages - .getString("WizardPage.selectNewFileContainer")); - if (dialog.open() == ContainerSelectionDialog.OK) { - Object[] result = dialog.getResult(); - if (result.length == 1) { - IContainer container = (IContainer) result[0]; - containerText.setText(container.getFullPath().toString()); - } - } - } - - /** - * Ensures that both text fields are set. - */ - private void dialogChanged() { - String container = getContainerName(); - String fileName = getFileName(); - - if (container.length() == 0) { - updateStatus(PHPWizardMessages - .getString("WizardPage.containerMustBeSpecified")); - return; - } - if (fileName.length() == 0) { - updateStatus("WizardPage.nameMustBeSpecified"); - return; - } - - updateStatus(null); - } - - private void updateStatus(String message) { - setErrorMessage(message); - setPageComplete(message == null); - } - - public String getContainerName() { - return containerText.getText(); - } - - public String getFileName() { - return fileText.getText(); - } - - /** - * @see WizardPage#isPageComplete() - */ - public boolean isPageComplete() { - return !checkFolderForExistingFile() && super.isPageComplete(); - } - - /** + private static final String INITIAL_FILENAME = "file.html"; + + private Text containerText; + + private Text fileText; + + private ISelection selection; + + /** + * Constructor for SampleNewWizardPage. + * + * @param pageName + */ + public HTMLFileWizardPage(ISelection selection) { + super("wizardPage"); + setTitle(PHPWizardMessages.getString("WizardPage.html.title")); + setDescription(PHPWizardMessages + .getString("WizardPage.html.description")); + this.selection = selection; + } + + /** + * @see IDialogPage#createControl(Composite) + */ + public void createControl(Composite parent) { + Composite container = new Composite(parent, SWT.NULL); + GridLayout layout = new GridLayout(); + container.setLayout(layout); + layout.numColumns = 3; + layout.verticalSpacing = 9; + Label label = new Label(container, SWT.NULL); + label.setText(PHPWizardMessages.getString("WizardPage.containerLabel")); + + containerText = new Text(container, SWT.BORDER | SWT.SINGLE); + GridData gd = new GridData(GridData.FILL_HORIZONTAL); + containerText.setLayoutData(gd); + containerText.addModifyListener(new ModifyListener() { + public void modifyText(ModifyEvent e) { + dialogChanged(); + } + }); + + Button button = new Button(container, SWT.PUSH); + button.setText(PHPWizardMessages + .getString("WizardPage.browseButtonText")); + button.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + handleBrowse(); + } + }); + label = new Label(container, SWT.NULL); + label.setText(PHPWizardMessages.getString("WizardPage.fileLabel")); + + fileText = new Text(container, SWT.BORDER | SWT.SINGLE); + gd = new GridData(GridData.FILL_HORIZONTAL); + fileText.setLayoutData(gd); + fileText.addModifyListener(new ModifyListener() { + public void modifyText(ModifyEvent e) { + dialogChanged(); + } + }); + initialize(); + dialogChanged(); + setControl(container); + } + + /** + * Tests if the current workbench selection is a suitable container to use. + */ + + private void initialize() { + if (selection != null && selection.isEmpty() == false + && selection instanceof IStructuredSelection) { + IStructuredSelection ssel = (IStructuredSelection) selection; + if (ssel.size() > 1) + return; + Object obj = ssel.getFirstElement(); + if (obj instanceof IResource) { + IContainer container; + if (obj instanceof IContainer) + container = (IContainer) obj; + else + container = ((IResource) obj).getParent(); + containerText.setText(container.getFullPath().toString()); + fileText.setFocus(); + } + } + fileText.setText(INITIAL_FILENAME); + } + + /** + * Uses the standard container selection dialog to choose the new value for + * the container field. + */ + + private void handleBrowse() { + ContainerSelectionDialog dialog = new ContainerSelectionDialog( + getShell(), ResourcesPlugin.getWorkspace().getRoot(), false, + PHPWizardMessages + .getString("WizardPage.selectNewFileContainer")); + if (dialog.open() == ContainerSelectionDialog.OK) { + Object[] result = dialog.getResult(); + if (result.length == 1) { + IContainer container = (IContainer) result[0]; + containerText.setText(container.getFullPath().toString()); + } + } + } + + /** + * Ensures that both text fields are set. + */ + private void dialogChanged() { + String container = getContainerName(); + String fileName = getFileName(); + + if (container.length() == 0) { + updateStatus(PHPWizardMessages + .getString("WizardPage.containerMustBeSpecified")); + return; + } + if (fileName.length() == 0) { + updateStatus("WizardPage.nameMustBeSpecified"); + return; + } + + updateStatus(null); + } + + private void updateStatus(String message) { + setErrorMessage(message); + setPageComplete(message == null); + } + + public String getContainerName() { + return containerText.getText(); + } + + public String getFileName() { + return fileText.getText(); + } + + /** + * @see WizardPage#isPageComplete() + */ + public boolean isPageComplete() { + return !checkFolderForExistingFile() && super.isPageComplete(); + } + + /** * Finds the current directory where the file should be created */ protected boolean checkFolderForExistingFile() { @@ -226,11 +229,14 @@ private Text containerText; public void setVisible(boolean visible) { super.setVisible(visible); if (visible) { - String fileName=fileText.getText().trim(); - if (getFileContainer() != null && fileName.equalsIgnoreCase(INITIAL_FILENAME)) { + String fileName = fileText.getText().trim(); + if (getFileContainer() != null + && fileName.equalsIgnoreCase(INITIAL_FILENAME)) { fileText.setFocus(); fileText.setText(fileName); - fileText.setSelection(0, fileName.length()-(new Path(INITIAL_FILENAME)).getFileExtension().length()-1); + fileText.setSelection(0, fileName.length() + - (new Path(INITIAL_FILENAME)).getFileExtension() + .length() - 1); } } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/NewProjectCreationWizard.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/NewProjectCreationWizard.java index c895758..0601e03 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/NewProjectCreationWizard.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/NewProjectCreationWizard.java @@ -23,42 +23,53 @@ import org.eclipse.ui.dialogs.WizardNewProjectCreationPage; import org.eclipse.ui.wizards.newresource.BasicNewProjectResourceWizard; import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard; -public class NewProjectCreationWizard extends BasicNewResourceWizard implements INewWizard, IExecutableExtension { +public class NewProjectCreationWizard extends BasicNewResourceWizard implements + INewWizard, IExecutableExtension { protected WizardNewProjectCreationPage projectPage; + protected IConfigurationElement configurationElement; + protected IProject newProject; - + public NewProjectCreationWizard() { - setWindowTitle(PHPWizardMessages.getString("NewProjectCreationWizard.windowTitle")); + setWindowTitle(PHPWizardMessages + .getString("NewProjectCreationWizard.windowTitle")); } public boolean performFinish() { - IRunnableWithProgress projectCreationOperation = new WorkspaceModifyDelegatingOperation(getProjectCreationRunnable()); + IRunnableWithProgress projectCreationOperation = new WorkspaceModifyDelegatingOperation( + getProjectCreationRunnable()); try { getContainer().run(false, true, projectCreationOperation); - } catch (Exception e) { + } catch (Exception e) { PHPeclipsePlugin.log(e); return false; } BasicNewProjectResourceWizard.updatePerspective(configurationElement); selectAndReveal(newProject); - // open the PHP perspective + // open the PHP perspective new OpenPHPPerspectiveAction().run(); return true; } protected IRunnableWithProgress getProjectCreationRunnable() { return new IRunnableWithProgress() { - public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { + public void run(IProgressMonitor monitor) + throws InvocationTargetException, InterruptedException { int remainingWorkUnits = 10; - monitor.beginTask(PHPWizardMessages.getString("NewProjectCreationWizard.projectCreationMessage"), remainingWorkUnits); + monitor + .beginTask( + PHPWizardMessages + .getString("NewProjectCreationWizard.projectCreationMessage"), + remainingWorkUnits); IWorkspace workspace = PHPeclipsePlugin.getWorkspace(); newProject = projectPage.getProjectHandle(); - - IProjectDescription description = workspace.newProjectDescription(newProject.getName()); + + IProjectDescription description = workspace + .newProjectDescription(newProject.getName()); IPath path = Platform.getLocation(); IPath customPath = projectPage.getLocationPath(); if (!path.equals(customPath)) { @@ -68,14 +79,16 @@ public class NewProjectCreationWizard extends BasicNewResourceWizard implements try { if (!newProject.exists()) { - newProject.create(description, new SubProgressMonitor(monitor, 1)); + newProject.create(description, new SubProgressMonitor( + monitor, 1)); remainingWorkUnits--; } if (!newProject.isOpen()) { newProject.open(new SubProgressMonitor(monitor, 1)); remainingWorkUnits--; } - JavaCore.addPHPNature(newProject, new SubProgressMonitor(monitor, remainingWorkUnits)); + JavaCore.addPHPNature(newProject, new SubProgressMonitor( + monitor, remainingWorkUnits)); } catch (CoreException e) { throw new InvocationTargetException(e); } finally { @@ -88,14 +101,18 @@ public class NewProjectCreationWizard extends BasicNewResourceWizard implements public void addPages() { super.addPages(); - projectPage = new WizardNewProjectCreationPage(PHPWizardMessages.getString("WizardNewProjectCreationPage.pageName")); - projectPage.setTitle(PHPWizardMessages.getString("WizardNewProjectCreationPage.pageTitle")); - projectPage.setDescription(PHPWizardMessages.getString("WizardNewProjectCreationPage.pageDescription")); + projectPage = new WizardNewProjectCreationPage(PHPWizardMessages + .getString("WizardNewProjectCreationPage.pageName")); + projectPage.setTitle(PHPWizardMessages + .getString("WizardNewProjectCreationPage.pageTitle")); + projectPage.setDescription(PHPWizardMessages + .getString("WizardNewProjectCreationPage.pageDescription")); addPage(projectPage); } - public void setInitializationData(IConfigurationElement config, String propertyName, Object data) throws CoreException { + public void setInitializationData(IConfigurationElement config, + String propertyName, Object data) throws CoreException { configurationElement = config; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPFileWizard.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPFileWizard.java index 7cae6d8..41f06a4 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPFileWizard.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPFileWizard.java @@ -52,174 +52,190 @@ import org.eclipse.ui.ide.IDE; */ public class PHPFileWizard extends Wizard implements INewWizard { - private PHPFileWizardPage page; - - private ISelection selection; - - public PHPFileWizard() { - super(); - setNeedsProgressMonitor(true); - setWindowTitle(PHPWizardMessages.getString("WizardNewProjectCreationPage.windowTitle")); - } - - /** - * Adding the page to the wizard. - */ - public void addPages() { - page = new PHPFileWizardPage(selection); - addPage(page); - } - - /** - * This method is called when 'Finish' button is pressed in the wizard. We will create an operation and run it using wizard as - * execution context. - */ - public boolean performFinish() { - final String containerName = page.getContainerName(); - final String fileName = page.getFileName(); - IRunnableWithProgress op = new IRunnableWithProgress() { - public void run(IProgressMonitor monitor) throws InvocationTargetException { - try { - doFinish(containerName, fileName, monitor); - } catch (CoreException e) { - throw new InvocationTargetException(e); - } finally { - monitor.done(); - } - } - }; - try { - getContainer().run(true, false, op); - } catch (InterruptedException e) { - return false; - } catch (InvocationTargetException e) { - Throwable realException = e.getTargetException(); - MessageDialog.openError(getShell(), PHPWizardMessages.getString("Wizard.error"), realException.getMessage()); - return false; - } - return true; - } - - /** - * The worker method. It will find the container, create the file if missing or just replace its contents, and open the editor on - * the newly created file. - */ - private void doFinish(String containerName, String fileName, IProgressMonitor monitor) throws CoreException { - // create a sample file - monitor.beginTask(PHPWizardMessages.getString("Wizard.Monitor.creating") + " " + fileName, 2); - IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); - IResource resource = root.findMember(new Path(containerName)); - if (!resource.exists() || !(resource instanceof IContainer)) { - throwCoreException(PHPWizardMessages.getString("Wizard.Monitor.containerDoesNotExistException")); - } - IContainer container = (IContainer) resource; - final IFile file = container.getFile(new Path(fileName)); - IProject project = file.getProject(); - String projectName = project.getName(); - String className = getClassName(fileName); - - try { - InputStream stream; - if (className == null) { - stream = openContentStream(fileName, projectName); - } else { - stream = openContentStreamClass(className); - } - if (file.exists()) { - file.setContents(stream, true, true, monitor); - } else { - file.create(stream, true, monitor); - } - stream.close(); - } catch (IOException e) { - } - monitor.worked(1); - monitor.setTaskName(PHPWizardMessages.getString("Wizard.Monitor.openingFile")); - getShell().getDisplay().asyncExec(new Runnable() { - public void run() { - IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); - try { - IDE.openEditor(page, file, true); - } catch (PartInitException e) { - } - } - }); - monitor.worked(1); - } - - /** - * Check if the filename is like this anyname.class.php - * - * @param fFileName - * the filename - * @return the anyname or null - */ - private static final String getClassName(final String fileName) { - final int lastDot = fileName.lastIndexOf('.'); - if (lastDot == -1) - return null; - final int precLastDot = fileName.lastIndexOf('.', lastDot - 1); - if (precLastDot == -1) - return null; - if (!fileName.substring(precLastDot + 1, lastDot).toUpperCase().equals("CLASS")) - return null; - return fileName.substring(0, precLastDot); - } - - /** - * We will initialize file contents for a class - * - * @param className - * the classname - */ - private InputStream openContentStreamClass(final String className) { - StringBuffer contents = new StringBuffer(""); - return new ByteArrayInputStream(contents.toString().getBytes()); - } - - /** - * We will initialize file contents with a sample text. - */ - private InputStream openContentStream(String fileName, String projectname) { - try { - Template template = PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(CodeTemplateContextType.NEWTYPE); - if (template == null) { - return null; - } - String lineDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ - CodeTemplateContext context = new CodeTemplateContext(template.getContextTypeId(), null, lineDelimiter); - context.setFileNameVariable(fileName, projectname); - String content=StubUtility.evaluateTemplate(context, template); - if (content==null) { - content=""; - } - return new ByteArrayInputStream(content.getBytes()); - } catch (CoreException e) { - e.printStackTrace(); - return null; - } - - } - - private void throwCoreException(String message) throws CoreException { - IStatus status = new Status(IStatus.ERROR, "net.sourceforge.phpeclipse.wizards", IStatus.OK, message, null); - throw new CoreException(status); - } - - /** - * We will accept the selection in the workbench to see if we can initialize from it. - * - * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection) - */ - public void init(IWorkbench workbench, IStructuredSelection selection) { - this.selection = selection; - } + private PHPFileWizardPage page; + + private ISelection selection; + + public PHPFileWizard() { + super(); + setNeedsProgressMonitor(true); + setWindowTitle(PHPWizardMessages + .getString("WizardNewProjectCreationPage.windowTitle")); + } + + /** + * Adding the page to the wizard. + */ + public void addPages() { + page = new PHPFileWizardPage(selection); + addPage(page); + } + + /** + * This method is called when 'Finish' button is pressed in the wizard. We + * will create an operation and run it using wizard as execution context. + */ + public boolean performFinish() { + final String containerName = page.getContainerName(); + final String fileName = page.getFileName(); + IRunnableWithProgress op = new IRunnableWithProgress() { + public void run(IProgressMonitor monitor) + throws InvocationTargetException { + try { + doFinish(containerName, fileName, monitor); + } catch (CoreException e) { + throw new InvocationTargetException(e); + } finally { + monitor.done(); + } + } + }; + try { + getContainer().run(true, false, op); + } catch (InterruptedException e) { + return false; + } catch (InvocationTargetException e) { + Throwable realException = e.getTargetException(); + MessageDialog.openError(getShell(), PHPWizardMessages + .getString("Wizard.error"), realException.getMessage()); + return false; + } + return true; + } + + /** + * The worker method. It will find the container, create the file if missing + * or just replace its contents, and open the editor on the newly created + * file. + */ + private void doFinish(String containerName, String fileName, + IProgressMonitor monitor) throws CoreException { + // create a sample file + monitor.beginTask(PHPWizardMessages + .getString("Wizard.Monitor.creating") + + " " + fileName, 2); + IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); + IResource resource = root.findMember(new Path(containerName)); + if (!resource.exists() || !(resource instanceof IContainer)) { + throwCoreException(PHPWizardMessages + .getString("Wizard.Monitor.containerDoesNotExistException")); + } + IContainer container = (IContainer) resource; + final IFile file = container.getFile(new Path(fileName)); + IProject project = file.getProject(); + String projectName = project.getName(); + String className = getClassName(fileName); + + try { + InputStream stream; + if (className == null) { + stream = openContentStream(fileName, projectName); + } else { + stream = openContentStreamClass(className); + } + if (file.exists()) { + file.setContents(stream, true, true, monitor); + } else { + file.create(stream, true, monitor); + } + stream.close(); + } catch (IOException e) { + } + monitor.worked(1); + monitor.setTaskName(PHPWizardMessages + .getString("Wizard.Monitor.openingFile")); + getShell().getDisplay().asyncExec(new Runnable() { + public void run() { + IWorkbenchPage page = PlatformUI.getWorkbench() + .getActiveWorkbenchWindow().getActivePage(); + try { + IDE.openEditor(page, file, true); + } catch (PartInitException e) { + } + } + }); + monitor.worked(1); + } + + /** + * Check if the filename is like this anyname.class.php + * + * @param fFileName + * the filename + * @return the anyname or null + */ + private static final String getClassName(final String fileName) { + final int lastDot = fileName.lastIndexOf('.'); + if (lastDot == -1) + return null; + final int precLastDot = fileName.lastIndexOf('.', lastDot - 1); + if (precLastDot == -1) + return null; + if (!fileName.substring(precLastDot + 1, lastDot).toUpperCase().equals( + "CLASS")) + return null; + return fileName.substring(0, precLastDot); + } + + /** + * We will initialize file contents for a class + * + * @param className + * the classname + */ + private InputStream openContentStreamClass(final String className) { + StringBuffer contents = new StringBuffer(""); + return new ByteArrayInputStream(contents.toString().getBytes()); + } + + /** + * We will initialize file contents with a sample text. + */ + private InputStream openContentStream(String fileName, String projectname) { + try { + Template template = PHPeclipsePlugin.getDefault() + .getCodeTemplateStore().findTemplate( + CodeTemplateContextType.NEWTYPE); + if (template == null) { + return null; + } + String lineDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ + CodeTemplateContext context = new CodeTemplateContext(template + .getContextTypeId(), null, lineDelimiter); + context.setFileNameVariable(fileName, projectname); + String content = StubUtility.evaluateTemplate(context, template); + if (content == null) { + content = ""; + } + return new ByteArrayInputStream(content.getBytes()); + } catch (CoreException e) { + e.printStackTrace(); + return null; + } + + } + + private void throwCoreException(String message) throws CoreException { + IStatus status = new Status(IStatus.ERROR, + "net.sourceforge.phpeclipse.wizards", IStatus.OK, message, null); + throw new CoreException(status); + } + + /** + * We will accept the selection in the workbench to see if we can initialize + * from it. + * + * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection) + */ + public void init(IWorkbench workbench, IStructuredSelection selection) { + this.selection = selection; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPFileWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPFileWizardPage.java index bbcc353..f4ac33a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPFileWizardPage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPFileWizardPage.java @@ -51,7 +51,7 @@ public class PHPFileWizardPage extends WizardPage { /** * Constructor for SampleNewWizardPage. - * + * * @param pageName */ public PHPFileWizardPage(ISelection selection) { @@ -83,7 +83,8 @@ public class PHPFileWizardPage extends WizardPage { }); Button button = new Button(container, SWT.PUSH); - button.setText(PHPWizardMessages.getString("WizardPage.browseButtonText")); + button.setText(PHPWizardMessages + .getString("WizardPage.browseButtonText")); button.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { handleBrowse(); @@ -110,7 +111,8 @@ public class PHPFileWizardPage extends WizardPage { */ private void initialize() { - if (selection != null && selection.isEmpty() == false && selection instanceof IStructuredSelection) { + if (selection != null && selection.isEmpty() == false + && selection instanceof IStructuredSelection) { IStructuredSelection ssel = (IStructuredSelection) selection; if (ssel.size() > 1) return; @@ -134,8 +136,10 @@ public class PHPFileWizardPage extends WizardPage { */ private void handleBrowse() { - ContainerSelectionDialog dialog = new ContainerSelectionDialog(getShell(), ResourcesPlugin.getWorkspace().getRoot(), false, - PHPWizardMessages.getString("WizardPage.selectNewFileContainer")); + ContainerSelectionDialog dialog = new ContainerSelectionDialog( + getShell(), ResourcesPlugin.getWorkspace().getRoot(), false, + PHPWizardMessages + .getString("WizardPage.selectNewFileContainer")); if (dialog.open() == ContainerSelectionDialog.OK) { Object[] results = dialog.getResult(); if (results.length == 1) { @@ -156,7 +160,8 @@ public class PHPFileWizardPage extends WizardPage { String fileName = getFileName(); if (container.length() == 0) { - updateStatus(PHPWizardMessages.getString("WizardPage.containerMustBeSpecified")); + updateStatus(PHPWizardMessages + .getString("WizardPage.containerMustBeSpecified")); return; } if (fileName.length() == 0) { @@ -193,9 +198,11 @@ public class PHPFileWizardPage extends WizardPage { protected boolean checkFolderForExistingFile() { IContainer container = getFileContainer(); if (container != null) { - IResource file = container.getFile(new Path(fileText.getText().trim())); + IResource file = container.getFile(new Path(fileText.getText() + .trim())); if (file != null && file.exists()) { - this.setErrorMessage(PHPWizardMessages.getString("WizardPage.fileAlreadyExists")); + this.setErrorMessage(PHPWizardMessages + .getString("WizardPage.fileAlreadyExists")); return true; } } @@ -204,14 +211,16 @@ public class PHPFileWizardPage extends WizardPage { private IContainer getFileContainer() { if (containerText.getText() != null) { - IPath containerPath = new Path(containerText.getText().trim()); + IPath containerPath = new Path(containerText.getText().trim()); IContainer container = null; if (containerPath.segmentCount() > 1) { - container = ResourcesPlugin.getWorkspace().getRoot().getFolder(containerPath); + container = ResourcesPlugin.getWorkspace().getRoot().getFolder( + containerPath); } else { if (containerPath.segmentCount() == 1) { // this is a project - container = ResourcesPlugin.getWorkspace().getRoot().getProject(containerText.getText().trim()); + container = ResourcesPlugin.getWorkspace().getRoot() + .getProject(containerText.getText().trim()); } } if (container != null && container.exists()) { @@ -225,10 +234,13 @@ public class PHPFileWizardPage extends WizardPage { super.setVisible(visible); if (visible) { String fileName = fileText.getText().trim(); - if (getFileContainer() != null && fileName.equalsIgnoreCase(INITIAL_FILENAME)) { + if (getFileContainer() != null + && fileName.equalsIgnoreCase(INITIAL_FILENAME)) { fileText.setFocus(); fileText.setText(fileName); - fileText.setSelection(0, fileName.length() - (new Path(INITIAL_FILENAME)).getFileExtension().length() - 1); + fileText.setSelection(0, fileName.length() + - (new Path(INITIAL_FILENAME)).getFileExtension() + .length() - 1); } } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPWizardMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPWizardMessages.java index 88ed120..a95f119 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPWizardMessages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPWizardMessages.java @@ -1,25 +1,27 @@ package net.sourceforge.phpeclipse.wizards; /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html -Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de -**********************************************************************/ + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ import java.util.MissingResourceException; import java.util.ResourceBundle; public class PHPWizardMessages { - private static final String RESOURCE_BUNDLE= PHPWizardMessages.class.getName();//$NON-NLS-1$ + private static final String RESOURCE_BUNDLE = PHPWizardMessages.class + .getName();//$NON-NLS-1$ - private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); + private static ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(RESOURCE_BUNDLE); private PHPWizardMessages() { } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/TempnewPHPProject.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/TempnewPHPProject.java index d0ac04f..05cace3 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/TempnewPHPProject.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/TempnewPHPProject.java @@ -19,76 +19,85 @@ import org.eclipse.ui.dialogs.WizardNewProjectCreationPage; import org.eclipse.ui.wizards.newresource.BasicNewProjectResourceWizard; import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard; -public class TempnewPHPProject extends BasicNewResourceWizard implements INewWizard { - /* - * This class has been added to cvs to provide a project page that works correctly and doesn't freezde while i investigate the - * errors completely - */ - private WizardNewProjectCreationPage phpProjPage; +public class TempnewPHPProject extends BasicNewResourceWizard implements + INewWizard { + /* + * This class has been added to cvs to provide a project page that works + * correctly and doesn't freezde while i investigate the errors completely + */ + private WizardNewProjectCreationPage phpProjPage; - private IConfigurationElement fConfigElement; + private IConfigurationElement fConfigElement; - public TempnewPHPProject() { - setNeedsProgressMonitor(true); - setWindowTitle("New Project creation"); //$NON-NLS-1$ + public TempnewPHPProject() { + setNeedsProgressMonitor(true); + setWindowTitle("New Project creation"); //$NON-NLS-1$ - } + } - public void addPages() { - super.addPages(); - phpProjPage = new WizardNewProjectCreationPage("NewProjectCreationWizard"); //$NON-NLS-1$ - phpProjPage.setTitle(PHPWizardMessages.getString("WizardNewProjectCreationPage.pageTitle")); //$NON-NLS-1$ - phpProjPage.setDescription(PHPWizardMessages.getString("WizardNewProjectCreationPage.pageDescription")); //$NON-NLS-1$ - addPage(phpProjPage); - } + public void addPages() { + super.addPages(); + phpProjPage = new WizardNewProjectCreationPage( + "NewProjectCreationWizard"); //$NON-NLS-1$ + phpProjPage.setTitle(PHPWizardMessages + .getString("WizardNewProjectCreationPage.pageTitle")); //$NON-NLS-1$ + phpProjPage.setDescription(PHPWizardMessages + .getString("WizardNewProjectCreationPage.pageDescription")); //$NON-NLS-1$ + addPage(phpProjPage); + } - public void setInitializationData(IConfigurationElement cfig, String propertyName, Object data) { - fConfigElement = cfig; - } + public void setInitializationData(IConfigurationElement cfig, + String propertyName, Object data) { + fConfigElement = cfig; + } - protected void initializeDefaultPageImageDescriptor() { - // not used yet - } + protected void initializeDefaultPageImageDescriptor() { + // not used yet + } - protected void finishPage() throws InterruptedException, CoreException { - createProject(phpProjPage.getProjectHandle(), phpProjPage.getLocationPath(), new NullProgressMonitor()); - BasicNewProjectResourceWizard.updatePerspective(fConfigElement); - selectAndReveal(phpProjPage.getProjectHandle()); - } + protected void finishPage() throws InterruptedException, CoreException { + createProject(phpProjPage.getProjectHandle(), phpProjPage + .getLocationPath(), new NullProgressMonitor()); + BasicNewProjectResourceWizard.updatePerspective(fConfigElement); + selectAndReveal(phpProjPage.getProjectHandle()); + } - protected void handleFinishException(Shell shell, InvocationTargetException e) { - ExceptionHandler.handle(e, getShell(), "Error title", "Error message"); - } + protected void handleFinishException(Shell shell, + InvocationTargetException e) { + ExceptionHandler.handle(e, getShell(), "Error title", "Error message"); + } - public boolean performFinish() { - try { - finishPage(); - } catch (InterruptedException e) { - } catch (CoreException e) { - } - return true; - } + public boolean performFinish() { + try { + finishPage(); + } catch (InterruptedException e) { + } catch (CoreException e) { + } + return true; + } - public void createProject(IProject project, IPath locationPath, IProgressMonitor monitor) throws CoreException { - try { - if (!project.exists()) { - IProjectDescription desc = project.getWorkspace().newProjectDescription(project.getName()); - if (Platform.getLocation().equals(locationPath)) { - locationPath = null; - } - desc.setLocation(locationPath); - project.create(desc, monitor); - monitor = null; - } - if (!project.isOpen()) { - project.open(monitor); - monitor = null; - } - JavaCore.addPHPNature(project, new NullProgressMonitor()); - } finally { - if (monitor != null) { - monitor.done(); - } - } - } + public void createProject(IProject project, IPath locationPath, + IProgressMonitor monitor) throws CoreException { + try { + if (!project.exists()) { + IProjectDescription desc = project.getWorkspace() + .newProjectDescription(project.getName()); + if (Platform.getLocation().equals(locationPath)) { + locationPath = null; + } + desc.setLocation(locationPath); + project.create(desc, monitor); + monitor = null; + } + if (!project.isOpen()) { + project.open(monitor); + monitor = null; + } + JavaCore.addPHPNature(project, new NullProgressMonitor()); + } finally { + if (monitor != null) { + monitor.done(); + } + } + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/EditElementWizard.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/EditElementWizard.java index 1e965a9..c2be185 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/EditElementWizard.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/EditElementWizard.java @@ -1,5 +1,5 @@ /* - * $Id: EditElementWizard.java,v 1.2 2005-07-08 21:30:33 axelcl Exp $ + * $Id: EditElementWizard.java,v 1.3 2006-10-21 23:18:43 pombredanne Exp $ * Copyright Narushima Hironori. All rights reserved. */ package net.sourceforge.phpeclipse.wizards.html; @@ -17,100 +17,105 @@ import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.texteditor.ITextEditor; /** - * EditElementWizard. TODO: privides extension point element editor. pluggable element edit page. + * EditElementWizard. TODO: privides extension point element editor. pluggable + * element edit page. */ public class EditElementWizard extends Wizard { - static Object[] elementEditPages = new Object[] { - // "a", AElementWizardPage.class, - // "img", ImgElementWizardPage.class, - "dl", ListElementWizardPage.class, - "ul", ListElementWizardPage.class, - "ol", ListElementWizardPage.class, - "table", TableElementWizardPage.class }; - - String targetElemName; - - ITextEditor htEditor; - - EditElementWizardPage rootPage; - - /** - * Second argument specify element name, If specify null, call new element edit wizard page. - */ - public EditElementWizard(ITextEditor editor, String targetElemName) { - htEditor = editor; - this.targetElemName = targetElemName; - - setWindowTitle("Edit HTML Element"); - setDefaultPageImageDescriptor(PHPUiImages.getDescriptor("wizban/editelem_wiz.gif")); - - setForcePreviousAndNextButtons(true); - } - - public void addPages() { - if (targetElemName == null) { - rootPage = new NewElementWizardPage(); - } else { - IDocument doc = getDocument(); - rootPage = createElementEditPage(targetElemName); - rootPage.setEditType(EditElementWizardPage.MODIFY); - } - addPage(rootPage); - } - - public boolean performFinish() { - IWizardPage page = rootPage; - for (IWizardPage p; (p = page.getNextPage()) != null;) { - page = p; - } - if (page instanceof EditElementWizardPage) { - ((EditElementWizardPage) page).performFinish(); - } - return true; - } - - public IDocument getDocument() { - return htEditor.getDocumentProvider().getDocument(htEditor.getEditorInput()); - } - - public ITextSelection getSelection() { - return (ITextSelection) htEditor.getSelectionProvider().getSelection(); - } - - public void setSelection(ITextSelection sel) { - htEditor.getSelectionProvider().setSelection(sel); - } - - public IFile getCurrentEditFile() { - IEditorInput input = htEditor.getEditorInput(); - return (input instanceof IFileEditorInput) ? ((IFileEditorInput) input).getFile() : null; - } - - /** - * If not edit target returns UnknownElementWizardPage. - */ - public EditElementWizardPage createElementEditPage(String elementName) { - EditElementWizardPage page = null; - try { - for (int i = 0; i < elementEditPages.length; i += 2) { - if (((String) elementEditPages[i]).equalsIgnoreCase(elementName)) { - Class klass = (Class) elementEditPages[i + 1]; - page = (EditElementWizardPage) klass.newInstance(); - } - } - } catch (InstantiationException e) { - PHPeclipsePlugin.log(e); - } catch (IllegalAccessException e) { - PHPeclipsePlugin.log(e); - } - if (page == null) { - page = new UnknownElementWizardPage(); - } - page.setElementName(elementName); - page.setWizard(this); - - return page; - } + static Object[] elementEditPages = new Object[] { + // "a", AElementWizardPage.class, + // "img", ImgElementWizardPage.class, + "dl", ListElementWizardPage.class, "ul", + ListElementWizardPage.class, "ol", ListElementWizardPage.class, + "table", TableElementWizardPage.class }; + + String targetElemName; + + ITextEditor htEditor; + + EditElementWizardPage rootPage; + + /** + * Second argument specify element name, If specify null, call new element + * edit wizard page. + */ + public EditElementWizard(ITextEditor editor, String targetElemName) { + htEditor = editor; + this.targetElemName = targetElemName; + + setWindowTitle("Edit HTML Element"); + setDefaultPageImageDescriptor(PHPUiImages + .getDescriptor("wizban/editelem_wiz.gif")); + + setForcePreviousAndNextButtons(true); + } + + public void addPages() { + if (targetElemName == null) { + rootPage = new NewElementWizardPage(); + } else { + IDocument doc = getDocument(); + rootPage = createElementEditPage(targetElemName); + rootPage.setEditType(EditElementWizardPage.MODIFY); + } + addPage(rootPage); + } + + public boolean performFinish() { + IWizardPage page = rootPage; + for (IWizardPage p; (p = page.getNextPage()) != null;) { + page = p; + } + if (page instanceof EditElementWizardPage) { + ((EditElementWizardPage) page).performFinish(); + } + return true; + } + + public IDocument getDocument() { + return htEditor.getDocumentProvider().getDocument( + htEditor.getEditorInput()); + } + + public ITextSelection getSelection() { + return (ITextSelection) htEditor.getSelectionProvider().getSelection(); + } + + public void setSelection(ITextSelection sel) { + htEditor.getSelectionProvider().setSelection(sel); + } + + public IFile getCurrentEditFile() { + IEditorInput input = htEditor.getEditorInput(); + return (input instanceof IFileEditorInput) ? ((IFileEditorInput) input) + .getFile() : null; + } + + /** + * If not edit target returns UnknownElementWizardPage. + */ + public EditElementWizardPage createElementEditPage(String elementName) { + EditElementWizardPage page = null; + try { + for (int i = 0; i < elementEditPages.length; i += 2) { + if (((String) elementEditPages[i]) + .equalsIgnoreCase(elementName)) { + Class klass = (Class) elementEditPages[i + 1]; + page = (EditElementWizardPage) klass.newInstance(); + } + } + } catch (InstantiationException e) { + PHPeclipsePlugin.log(e); + } catch (IllegalAccessException e) { + PHPeclipsePlugin.log(e); + } + if (page == null) { + page = new UnknownElementWizardPage(); + } + page.setElementName(elementName); + page.setWizard(this); + + return page; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/EditElementWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/EditElementWizardPage.java index 144e166..44d1a27 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/EditElementWizardPage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/EditElementWizardPage.java @@ -1,5 +1,5 @@ /* - * $Id: EditElementWizardPage.java,v 1.1 2004-10-05 20:51:57 jsurfer Exp $ + * $Id: EditElementWizardPage.java,v 1.2 2006-10-21 23:18:43 pombredanne Exp $ * Copyright Narushima Hironori. All rights reserved. */ package net.sourceforge.phpeclipse.wizards.html; @@ -33,154 +33,160 @@ import org.xml.sax.SAXException; /** * - * + * */ -public abstract class EditElementWizardPage extends WizardPage implements IPreviewer { - - final public static int NEW = 0, MODIFY = 1; - - private static DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); - - Composite extendComp; - - Text preview; - - private String elementName = null; - - int editType = NEW; - - protected EditElementWizardPage(String pageName) { - super(pageName); - } - - public void createControl(Composite parent) { - Composite base = new Composite(parent, SWT.NONE); - setControl(base); - base.setLayout(new GridLayout(1, false)); - - // create child control. - Composite childControlBase = new Composite(base, SWT.NONE); - childControlBase.setLayoutData(new GridData(GridData.FILL_BOTH)); - try { - createChildControl(childControlBase); - } catch (CoreException e) { - PHPeclipsePlugin.log(e); - return; - } - - // preview components. - Composite previewBase = new Composite(base, SWT.NONE); - - GridData gd = new GridData(GridData.FILL_HORIZONTAL); - previewBase.setLayoutData(gd); - previewBase.setLayout(new GridLayout(1, false)); - - Label labe = new Label(previewBase, SWT.NONE); - labe.setText("Preview:"); - gd = new GridData(GridData.FILL_HORIZONTAL); - labe.setLayoutData(gd); - - preview = new Text(previewBase, SWT.BORDER | SWT.MULTI | SWT.READ_ONLY | SWT.WRAP | SWT.V_SCROLL | SWT.H_SCROLL); - gd = new GridData(GridData.FILL_HORIZONTAL); - gd.widthHint = 0; - gd.heightHint = preview.getLineHeight() * 4; - preview.setLayoutData(gd); - - refreshPreview(); - } - - abstract protected void createChildControl(Composite parent) throws CoreException; - - public abstract String getPreviewText(); - - public void refreshPreview() { - if (preview != null) { - String text = getPreviewText(); - preview.setText(text == null ? "" : text); - } - } - - public String getElementName() { - return elementName; - } - - public void setElementName(String string) { - elementName = string; - } - - protected IFile getEditFile() { - IFile file = null; - IWizard wiz = getWizard(); - if (wiz instanceof EditElementWizard) { - file = ((EditElementWizard) wiz).getCurrentEditFile(); - } - return file; - } - - protected void performFinish() { - EditElementWizard wiz = (EditElementWizard) getWizard(); - ITextSelection sel = wiz.getSelection(); - IDocument doc = wiz.getDocument(); - int offset = sel.getOffset(); - try { - doc.replace(offset, sel.getLength(), getPreviewText()); - } catch (BadLocationException e) { - PHPeclipsePlugin.log(e); - } - int index = doc.get().indexOf('>', offset); - if (index != -1) { - wiz.setSelection(new TextSelection(index + 1, 0)); - } - } - - /** - * Returns edit type. - */ - public int getEditType() { - return editType; - } - - /** - * Sets edit type that types are EditElementWizardPage.NEW, EditElementWizardPage.MODIFY. Default value is NEW. - */ - public void setEditType(int i) { - editType = i; - } - - protected String getSelectionText() { - return ((EditElementWizard) getWizard()).getSelection().getText(); - } - - protected Element getParsedSelectionText() { - String selText = getSelectionText(); - try { - InputSource source = new InputSource(new StringReader(selText)); - Document doc = docBuilderFactory.newDocumentBuilder().parse(source); - return doc.getDocumentElement(); - } catch (SAXException e) { - } catch (IOException e) { - } catch (ParserConfigurationException e) { - } - return null; - - } - - protected static String chooseContent(String text) { - int b = -1, e = -1, len = text.length(); - for (int i = 0; i < len; i++) { - if (text.charAt(i) == '>') { - b = i + 1; - break; - } - } - for (int i = len - 1; i >= 0; i--) { - if (text.charAt(i) == '<') { - e = i; - break; - } - } - return (b != -1 && e != -1 && b < len && e < len) ? text.substring(b, e) : ""; - - } +public abstract class EditElementWizardPage extends WizardPage implements + IPreviewer { + + final public static int NEW = 0, MODIFY = 1; + + private static DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory + .newInstance(); + + Composite extendComp; + + Text preview; + + private String elementName = null; + + int editType = NEW; + + protected EditElementWizardPage(String pageName) { + super(pageName); + } + + public void createControl(Composite parent) { + Composite base = new Composite(parent, SWT.NONE); + setControl(base); + base.setLayout(new GridLayout(1, false)); + + // create child control. + Composite childControlBase = new Composite(base, SWT.NONE); + childControlBase.setLayoutData(new GridData(GridData.FILL_BOTH)); + try { + createChildControl(childControlBase); + } catch (CoreException e) { + PHPeclipsePlugin.log(e); + return; + } + + // preview components. + Composite previewBase = new Composite(base, SWT.NONE); + + GridData gd = new GridData(GridData.FILL_HORIZONTAL); + previewBase.setLayoutData(gd); + previewBase.setLayout(new GridLayout(1, false)); + + Label labe = new Label(previewBase, SWT.NONE); + labe.setText("Preview:"); + gd = new GridData(GridData.FILL_HORIZONTAL); + labe.setLayoutData(gd); + + preview = new Text(previewBase, SWT.BORDER | SWT.MULTI | SWT.READ_ONLY + | SWT.WRAP | SWT.V_SCROLL | SWT.H_SCROLL); + gd = new GridData(GridData.FILL_HORIZONTAL); + gd.widthHint = 0; + gd.heightHint = preview.getLineHeight() * 4; + preview.setLayoutData(gd); + + refreshPreview(); + } + + abstract protected void createChildControl(Composite parent) + throws CoreException; + + public abstract String getPreviewText(); + + public void refreshPreview() { + if (preview != null) { + String text = getPreviewText(); + preview.setText(text == null ? "" : text); + } + } + + public String getElementName() { + return elementName; + } + + public void setElementName(String string) { + elementName = string; + } + + protected IFile getEditFile() { + IFile file = null; + IWizard wiz = getWizard(); + if (wiz instanceof EditElementWizard) { + file = ((EditElementWizard) wiz).getCurrentEditFile(); + } + return file; + } + + protected void performFinish() { + EditElementWizard wiz = (EditElementWizard) getWizard(); + ITextSelection sel = wiz.getSelection(); + IDocument doc = wiz.getDocument(); + int offset = sel.getOffset(); + try { + doc.replace(offset, sel.getLength(), getPreviewText()); + } catch (BadLocationException e) { + PHPeclipsePlugin.log(e); + } + int index = doc.get().indexOf('>', offset); + if (index != -1) { + wiz.setSelection(new TextSelection(index + 1, 0)); + } + } + + /** + * Returns edit type. + */ + public int getEditType() { + return editType; + } + + /** + * Sets edit type that types are EditElementWizardPage.NEW, + * EditElementWizardPage.MODIFY. Default value is NEW. + */ + public void setEditType(int i) { + editType = i; + } + + protected String getSelectionText() { + return ((EditElementWizard) getWizard()).getSelection().getText(); + } + + protected Element getParsedSelectionText() { + String selText = getSelectionText(); + try { + InputSource source = new InputSource(new StringReader(selText)); + Document doc = docBuilderFactory.newDocumentBuilder().parse(source); + return doc.getDocumentElement(); + } catch (SAXException e) { + } catch (IOException e) { + } catch (ParserConfigurationException e) { + } + return null; + + } + + protected static String chooseContent(String text) { + int b = -1, e = -1, len = text.length(); + for (int i = 0; i < len; i++) { + if (text.charAt(i) == '>') { + b = i + 1; + break; + } + } + for (int i = len - 1; i >= 0; i--) { + if (text.charAt(i) == '<') { + e = i; + break; + } + } + return (b != -1 && e != -1 && b < len && e < len) ? text + .substring(b, e) : ""; + + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/ElementWriter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/ElementWriter.java index 25573cf..8bd46ee 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/ElementWriter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/ElementWriter.java @@ -1,5 +1,5 @@ /* - * $Id: ElementWriter.java,v 1.2 2005-05-06 00:57:33 stefanbjarni Exp $ + * $Id: ElementWriter.java,v 1.3 2006-10-21 23:18:43 pombredanne Exp $ * Copyright Narushima Hironori. All rights reserved. */ package net.sourceforge.phpeclipse.wizards.html; @@ -20,92 +20,94 @@ import org.w3c.dom.Text; */ public class ElementWriter { - final public static int - BEGIN_CHANGELINE = 1, - END_CHANGELINE = 2; - + final public static int BEGIN_CHANGELINE = 1, END_CHANGELINE = 2; + boolean trim = true; + HashMap expandOptions = new HashMap(); + int defaultExpandOption; + String indent; - + public ElementWriter() { this(0, " "); } - + public ElementWriter(int defaultExpandOption, String indent) { this.defaultExpandOption = defaultExpandOption; this.indent = indent; } - public void setExpandOption(String elementName, int value){ + public void setExpandOption(String elementName, int value) { expandOptions.put(elementName, new Integer(value)); } - - public int getExpandOption(String elementName){ - if( expandOptions.containsKey(elementName)){ - return ((Integer)expandOptions.get(elementName)).intValue(); + + public int getExpandOption(String elementName) { + if (expandOptions.containsKey(elementName)) { + return ((Integer) expandOptions.get(elementName)).intValue(); } return defaultExpandOption; } - - boolean isBeginChangeLine(String elementName){ + + boolean isBeginChangeLine(String elementName) { return (getExpandOption(elementName) & BEGIN_CHANGELINE) != 0; } - - boolean isEndChangeLine(String elementName){ + + boolean isEndChangeLine(String elementName) { return (getExpandOption(elementName) & END_CHANGELINE) != 0; } - public String expandTag(Element element){ + public String expandTag(Element element) { StringBuffer buff = new StringBuffer(); expandTag(element, 0, buff); return buff.toString(); } - + public void writeTag(Element element, OutputStream out) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(out); - try{ + try { writer.write("\n\n"); writer.write(new ElementWriter().expandTag(element)); - }finally{ - if(writer != null){ + } finally { + if (writer != null) { writer.close(); } } } - - void expandTag(Element element, int level, StringBuffer buff){ + + void expandTag(Element element, int level, StringBuffer buff) { expandIndent(level, buff); - + String elementName = element.getNodeName(); - buff.append('<' + elementName ); + buff.append('<' + elementName); NamedNodeMap attrs = element.getAttributes(); - for(int i=0; i'); - if(!emptyElem ){ + if (!emptyElem) { NodeList childElements = element.getChildNodes(); - if(isBeginChangeLine(elementName)){ + if (isBeginChangeLine(elementName)) { buff.append('\n'); } - for(int i=0; i'); } // already inserted change line. - if( isEndChangeLine(elementName) ){ + if (isEndChangeLine(elementName)) { buff.append('\n'); } } - - void expandIndent(int level, StringBuffer buff){ - if(indent != null){ - for(int i=0; i\n"); - buff.append( getSelectionText() ); + buff.append(getSelectionText()); buff.append("\n\n"); - + return buff.toString(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/HTMLUtilities.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/HTMLUtilities.java index 945bbcf..8f9db38 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/HTMLUtilities.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/HTMLUtilities.java @@ -1,37 +1,29 @@ /* - * $Id: HTMLUtilities.java,v 1.1 2004-10-05 20:51:57 jsurfer Exp $ + * $Id: HTMLUtilities.java,v 1.2 2006-10-21 23:18:43 pombredanne Exp $ * Copyright Narushima Hironori. All rights reserved. */ package net.sourceforge.phpeclipse.wizards.html; - /** * */ public class HTMLUtilities { - final static String[] specialMarks = { - "&", "&", - "<", "<", - ">", ">", - "\"", """, - }; + final static String[] specialMarks = { "&", "&", "<", "<", ">", + ">", "\"", """, }; - public static String escape(String text){ - for (int i = 0; i < specialMarks.length; i+=2) { - text = text.replaceAll(specialMarks[i], specialMarks[i+1]); + public static String escape(String text) { + for (int i = 0; i < specialMarks.length; i += 2) { + text = text.replaceAll(specialMarks[i], specialMarks[i + 1]); } return text; } - - public static String unescape(String text){ - for (int i = specialMarks.length-1; i>=0 ; i-=2) { - text = text.replaceAll(specialMarks[i], specialMarks[i-1]); + + public static String unescape(String text) { + for (int i = specialMarks.length - 1; i >= 0; i -= 2) { + text = text.replaceAll(specialMarks[i], specialMarks[i - 1]); } return text; } - - - - + } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/IPreviewer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/IPreviewer.java index bd2f1e5..7f1fc83 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/IPreviewer.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/IPreviewer.java @@ -1,5 +1,5 @@ /* - * $Id: IPreviewer.java,v 1.1 2004-10-05 20:51:57 jsurfer Exp $ + * $Id: IPreviewer.java,v 1.2 2006-10-21 23:18:43 pombredanne Exp $ * Copyright Narushima Hironori. All rights reserved. */ package net.sourceforge.phpeclipse.wizards.html; @@ -8,7 +8,7 @@ package net.sourceforge.phpeclipse.wizards.html; * */ public interface IPreviewer { - + String getPreviewText(); - + } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/InsertHTMLElementAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/InsertHTMLElementAction.java index 137b8dc..5ca0f4a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/InsertHTMLElementAction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/InsertHTMLElementAction.java @@ -1,5 +1,5 @@ /* - * $Id: InsertHTMLElementAction.java,v 1.2 2005-05-06 00:57:33 stefanbjarni Exp $ + * $Id: InsertHTMLElementAction.java,v 1.3 2006-10-21 23:18:43 pombredanne Exp $ * Copyright Narushima Hironori. All rights reserved. */ package net.sourceforge.phpeclipse.wizards.html; @@ -12,7 +12,6 @@ import org.eclipse.ui.IEditorActionDelegate; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.texteditor.ITextEditor; - /** * InsertTagAction */ @@ -22,25 +21,23 @@ public class InsertHTMLElementAction implements IEditorActionDelegate { public InsertHTMLElementAction() { } - + public void setActiveEditor(IAction action, IEditorPart targetEditor) { - if(targetEditor instanceof ITextEditor){ - this.targetEditor = (ITextEditor)targetEditor; + if (targetEditor instanceof ITextEditor) { + this.targetEditor = (ITextEditor) targetEditor; } } public void run(IAction action) { - - WizardDialog wizDialog = - new WizardDialog( - targetEditor.getSite().getShell(), - new EditElementWizard(targetEditor, null) ){ + + WizardDialog wizDialog = new WizardDialog(targetEditor.getSite() + .getShell(), new EditElementWizard(targetEditor, null)) { protected int getShellStyle() { return super.getShellStyle() | SWT.RESIZE; } }; - + wizDialog.open(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/ListElementWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/ListElementWizardPage.java index b736cff..d49f96d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/ListElementWizardPage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/ListElementWizardPage.java @@ -1,5 +1,5 @@ /* - * $Id: ListElementWizardPage.java,v 1.2 2005-05-06 00:57:33 stefanbjarni Exp $ + * $Id: ListElementWizardPage.java,v 1.3 2006-10-21 23:18:43 pombredanne Exp $ * Copyright Narushima Hironori. All rights reserved. */ package net.sourceforge.phpeclipse.wizards.html; @@ -18,10 +18,10 @@ import org.eclipse.swt.widgets.Label; */ public class ListElementWizardPage extends EditElementWizardPage { - final static String[] LIST_TYPES = {"ul", "ol", "dl"}; + final static String[] LIST_TYPES = { "ul", "ol", "dl" }; Combo types; - + public ListElementWizardPage() { super("ListElementWizardPage"); setTitle("List"); @@ -32,52 +32,56 @@ public class ListElementWizardPage extends EditElementWizardPage { parent.setLayout(new GridLayout(2, false)); Label labe = new Label(parent, SWT.NONE); labe.setText("List &Type:"); - + types = new Combo(parent, SWT.DROP_DOWN | SWT.READ_ONLY); - + for (int i = 0; i < LIST_TYPES.length; i++) { String type = LIST_TYPES[i]; types.add(type); - if( getElementName().equals(type) ){ + if (getElementName().equals(type)) { types.select(i); } } - + types.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); types.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { - setElementName( types.getText() ); + setElementName(types.getText()); refreshPreview(); } - public void widgetDefaultSelected(SelectionEvent e) {} + + public void widgetDefaultSelected(SelectionEvent e) { + } }); } - + public String getPreviewText() { - String content = ((EditElementWizard) getWizard() ).getSelection().getText().trim(); - + String content = ((EditElementWizard) getWizard()).getSelection() + .getText().trim(); + String elemName = getElementName(); switch (getEditType()) { - case MODIFY: - content = chooseContent(content).trim(); - break; + case MODIFY: + content = chooseContent(content).trim(); + break; - case NEW: - String[] lines = content.split("\n+"); - StringBuffer result = new StringBuffer(); - for (int i = 0; i < lines.length; i++) { - String itemElemName; - if(elemName.equals("dl")){ - itemElemName = (i % 2 == 0) ? "dt" : "dd"; - }else{ - itemElemName = "li"; - } - result.append( "<" + itemElemName + ">" + lines[i].trim() + "\n"); + case NEW: + String[] lines = content.split("\n+"); + StringBuffer result = new StringBuffer(); + for (int i = 0; i < lines.length; i++) { + String itemElemName; + if (elemName.equals("dl")) { + itemElemName = (i % 2 == 0) ? "dt" : "dd"; + } else { + itemElemName = "li"; } - content = result.toString(); - break; + result.append("<" + itemElemName + ">" + lines[i].trim() + "\n"); + } + content = result.toString(); + break; } - + return "<" + elemName + ">\n" + content + "\n"; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/NewElementWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/NewElementWizardPage.java index 909fb3b..933317a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/NewElementWizardPage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/NewElementWizardPage.java @@ -1,5 +1,5 @@ /* - * $Id: NewElementWizardPage.java,v 1.2 2005-05-06 00:57:33 stefanbjarni Exp $ + * $Id: NewElementWizardPage.java,v 1.3 2006-10-21 23:18:43 pombredanne Exp $ * Copyright Narushima Hironori. All rights reserved. */ package net.sourceforge.phpeclipse.wizards.html; @@ -14,13 +14,13 @@ import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; - /** * */ public class NewElementWizardPage extends EditElementWizardPage { Text elementName; + EditElementWizardPage nextPage = null; public NewElementWizardPage() { @@ -28,30 +28,32 @@ public class NewElementWizardPage extends EditElementWizardPage { setTitle("Create HTML Element"); setDescription("Specify new HTML tag (dl,ul,ol or table) and configure that tag."); } - + protected void createChildControl(Composite base) { // create foundation component base.setLayout(new GridLayout(1, false)); - + // element input components new Label(base, SWT.NONE).setText("&Element Name:"); - + elementName = new Text(base, SWT.BORDER | SWT.SINGLE); - elementName.setLayoutData( new GridData(GridData.FILL_HORIZONTAL)); - elementName.addModifyListener( new ModifyListener() { + elementName.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + elementName.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String eName = elementName.getText(); - if( eName.indexOf(' ') != -1 ){ + if (eName.indexOf(' ') != -1) { setErrorMessage("Don't contain blink in speicfied element name."); - } else if (eName.length() == 0){ + } else if (eName.length() == 0) { setErrorMessage("Need to specify element name."); } else { setErrorMessage(null); - nextPage = ((EditElementWizard)getWizard()).createElementEditPage(eName); + nextPage = ((EditElementWizard) getWizard()) + .createElementEditPage(eName); nextPage.setElementName(eName); - if( nextPage instanceof UnknownElementWizardPage){ - setMessage("This editor does not known element name.", WARNING); - }else{ + if (nextPage instanceof UnknownElementWizardPage) { + setMessage("This editor does not known element name.", + WARNING); + } else { setMessage(null, NONE); } } @@ -60,17 +62,17 @@ public class NewElementWizardPage extends EditElementWizardPage { } }); } - - public String getPreviewText(){ - if(nextPage instanceof EditElementWizardPage){ - return ((EditElementWizardPage)nextPage).getPreviewText(); + + public String getPreviewText() { + if (nextPage instanceof EditElementWizardPage) { + return ((EditElementWizardPage) nextPage).getPreviewText(); } return null; } - + public void setErrorMessage(String newMessage) { super.setErrorMessage(newMessage); - if( newMessage != null){ + if (newMessage != null) { nextPage = null; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/NumVerifyListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/NumVerifyListener.java index ff35f2c..6cdfee5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/NumVerifyListener.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/NumVerifyListener.java @@ -1,5 +1,5 @@ /* - * $Id: NumVerifyListener.java,v 1.2 2005-05-06 00:57:33 stefanbjarni Exp $ + * $Id: NumVerifyListener.java,v 1.3 2006-10-21 23:18:43 pombredanne Exp $ * Copyright Narushima Hironori. All rights reserved. */ package net.sourceforge.phpeclipse.wizards.html; @@ -11,10 +11,11 @@ import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; public class NumVerifyListener implements VerifyListener { - + Pattern numPattern = Pattern.compile("^\\d+$"); - + public void verifyText(VerifyEvent ev) { - ev.doit = numPattern.matcher( ev.text ).matches() || ev.keyCode == SWT.DEL || ev.character == SWT.BS; + ev.doit = numPattern.matcher(ev.text).matches() + || ev.keyCode == SWT.DEL || ev.character == SWT.BS; } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/SomeItemInputDialog.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/SomeItemInputDialog.java index 653bb1f..fdbfeb0 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/SomeItemInputDialog.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/SomeItemInputDialog.java @@ -1,5 +1,5 @@ /* - * $Id: SomeItemInputDialog.java,v 1.2 2005-05-06 00:57:33 stefanbjarni Exp $ + * $Id: SomeItemInputDialog.java,v 1.3 2006-10-21 23:18:43 pombredanne Exp $ * Copyright Narushima Hironori. All rights reserved. */ package net.sourceforge.phpeclipse.wizards.html; @@ -26,26 +26,32 @@ import org.eclipse.swt.widgets.Text; public class SomeItemInputDialog extends Dialog { String dialogTitle; + String[] inputMessages; - + IInputValidator[] validators; + Text[] texts; + Text error; - + String[] errorMsgs; + String[] resultValues; - public SomeItemInputDialog(Shell parentShell, String dialogTitle, String[] inputMessages, IInputValidator[] validators) { + public SomeItemInputDialog(Shell parentShell, String dialogTitle, + String[] inputMessages, IInputValidator[] validators) { super(parentShell); - if(inputMessages.length != validators.length){ - throw new IllegalArgumentException("Specify validator counts and input message count is not same."); + if (inputMessages.length != validators.length) { + throw new IllegalArgumentException( + "Specify validator counts and input message count is not same."); } - + this.dialogTitle = dialogTitle; - this.inputMessages = (String[])inputMessages.clone(); - this.validators = (IInputValidator[])validators.clone(); + this.inputMessages = (String[]) inputMessages.clone(); + this.validators = (IInputValidator[]) validators.clone(); this.errorMsgs = new String[validators.length]; - + setShellStyle(SWT.RESIZE | getShellStyle()); } @@ -55,16 +61,16 @@ public class SomeItemInputDialog extends Dialog { } protected Control createDialogArea(Composite parent) { - Composite base = (Composite)super.createDialogArea(parent); + Composite base = (Composite) super.createDialogArea(parent); GridLayout gl = new GridLayout(2, false); gl.marginWidth = 4; gl.marginHeight = 6; base.setLayout(gl); - + texts = new Text[inputMessages.length]; - for(int i=0; i"); + static Pattern tagNameChoosePattern = Pattern + .compile("<[\\s/]*(\\w+)\\s*.*>"); + + String[] splitRegexpCandidates = { "\t", ",", "\\s", "\\s+", }; - String[] splitRegexpCandidates = { - "\t", - ",", - "\\s", - "\\s+", - }; - public StringDivider() { } - public String[][] divide(String content){ + public String[][] divide(String content) { return divide(content, getDivideSuitedRegexp(content)); } - - public String[][] divide(String content, String regexp){ + + public String[][] divide(String content, String regexp) { String[] lines = content.split("\n"); int len = lines.length; String[][] dist = new String[len][]; - + int max = Integer.MIN_VALUE; for (int i = 0; i < len; i++) { String line = lines[i]; String[] cells = line.split(regexp); dist[i] = cells; - if(max < cells.length){ + if (max < cells.length) { max = cells.length; } } @@ -47,27 +43,27 @@ public class StringDivider { } return dist; } - - public String getDivideSuitedRegexp(String content){ + + public String getDivideSuitedRegexp(String content) { String[] lines = content.split("\n"); - + String resultRegexp = null; int score = Integer.MAX_VALUE, cellCount = Integer.MIN_VALUE; - + for (int i = 0; i < splitRegexpCandidates.length; i++) { String regexp = splitRegexpCandidates[i]; int max = Integer.MIN_VALUE, min = Integer.MAX_VALUE; for (int j = 0; j < lines.length; j++) { String[] vals = lines[j].split(regexp); - if(max < vals.length){ + if (max < vals.length) { max = vals.length; } - if(min > vals.length){ + if (min > vals.length) { min = vals.length; } } int s = max - min; - if( score > s || (score == s && max > cellCount)){ + if (score > s || (score == s && max > cellCount)) { cellCount = max; score = s; resultRegexp = regexp; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/TableElementCellModifier.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/TableElementCellModifier.java index 36efe07..62e767d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/TableElementCellModifier.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/TableElementCellModifier.java @@ -1,5 +1,5 @@ /* - * $Id: TableElementCellModifier.java,v 1.2 2005-05-06 00:57:33 stefanbjarni Exp $ + * $Id: TableElementCellModifier.java,v 1.3 2006-10-21 23:18:43 pombredanne Exp $ * Copyright Narushima Hironori. All rights reserved. */ package net.sourceforge.phpeclipse.wizards.html; @@ -22,6 +22,7 @@ import org.w3c.dom.Text; public class TableElementCellModifier implements ICellModifier { DocumentBuilderFactory builderFactory; + IPropertyChangeListener listener; public TableElementCellModifier(IPropertyChangeListener listener) { @@ -32,18 +33,18 @@ public class TableElementCellModifier implements ICellModifier { public boolean canModify(Object element, String property) { return getValue(element, property) != null; } - + public Object getValue(Object trElem, String property) { - if(trElem instanceof Element){ - Element e = (Element)trElem; - if( e.getNodeName().equals("tr") ){ + if (trElem instanceof Element) { + Element e = (Element) trElem; + if (e.getNodeName().equals("tr")) { int v = TableElementModel.toNumeric(property); Element[] cells = TableElementModel.chooseCellElements(e); - if(v >= 0 && v < cells.length){ + if (v >= 0 && v < cells.length) { NodeList nodes = cells[v].getChildNodes(); - if(nodes.getLength() == 1){ + if (nodes.getLength() == 1) { Node n = nodes.item(0); - if(n instanceof Text){ + if (n instanceof Text) { return n.getNodeValue(); } } @@ -57,23 +58,24 @@ public class TableElementCellModifier implements ICellModifier { if (element instanceof Item) { element = ((Item) element).getData(); } - Element trElem = (Element)element; + Element trElem = (Element) element; int index = TableElementModel.toNumeric(property); Element cellElem = TableElementModel.chooseCellElements(trElem)[index]; - + NodeList nodes = cellElem.getChildNodes(); - for(int i=0; i 0){ + if (cells.length > 0) { for (int i = 0; i < cells.length; i++) { String[] rows = cells[i]; Element tr = document.createElement("tr"); @@ -92,144 +103,143 @@ public class TableElementModel { } tableElement.appendChild(tr); } - + setColumnCount(cells[0].length); - }else{ + } else { Element tr = document.createElement("tr"); Element td = document.createElement("td"); td.appendChild(document.createTextNode("")); tr.appendChild(td); tableElement.appendChild(tr); - + setColumnCount(1); } } - String[] createColumnProperties(){ + String[] createColumnProperties() { int len = getColumnCount(); String[] props = new String[len]; - for(int i=0; i rows.length){ - for(int i=rows.length; i rows.length) { + for (int i = rows.length; i < rowCount; i++) { + tableElement.appendChild(createRowElement()); } - }else if(rowCount < rows.length){ - for(int i=rowCount; i colLen ){ - for(int j=0, len = newLength - colLen; j colLen) { + for (int j = 0, len = newLength - colLen; j < len; j++) { Element cell = document.createElement("td"); cell.appendChild(document.createTextNode("")); tr.appendChild(cell); } - }else if( newLength < colLen ){ - for(int j=newLength; j 0){ - Element tr = (Element)trs.item(0); + if (trs.getLength() > 0) { + Element tr = (Element) trs.item(0); return chooseCellElements(tr).length; - }else{ + } else { return 0; } } - - public static Element[] chooseCellElements(Element tr){ + + public static Element[] chooseCellElements(Element tr) { NodeList nodeList = tr.getChildNodes(); - + ArrayList result = new ArrayList(); - for(int i=0; i 0){ - buff.append(CHAR_TABLE[u-1]); + if (u > 0) { + buff.append(CHAR_TABLE[u - 1]); } - buff.append( CHAR_TABLE[i % CHAR_TABLE.length] ); + buff.append(CHAR_TABLE[i % CHAR_TABLE.length]); return buff.toString(); } - + /** * Return index of char map. If can not parse values return -1. - */ - public static int toNumeric(String code){ + */ + public static int toNumeric(String code) { int result = -1; - for(int i=0; i= 0){ - if(result == -1){ + if (match >= 0) { + if (result == -1) { result = 0; } int v = match; - int u = code.length()-1-i; - if(u>0){ - v = CHAR_TABLE.length * u * (v+1); + int u = code.length() - 1 - i; + if (u > 0) { + v = CHAR_TABLE.length * u * (v + 1); } result += v; } @@ -237,47 +247,48 @@ public class TableElementModel { return result; } - public void move(Element tr, int moveCount){ + public void move(Element tr, int moveCount) { Element[] rows = getRows(); int index = -1; - for(int i=0;i 0){ + if (moveCount > 0) { // move down; - for(int i=index; i=moveCount+index+1 && i >= 1; i--){ - tableElement.insertBefore(rows[index], rows[i-1]); + for (int i = index; i >= moveCount + index + 1 && i >= 1; i--) { + tableElement.insertBefore(rows[index], rows[i - 1]); } - }else{ + } else { return; } } - - public void insertNewRowBefore(Element tr){ + + public void insertNewRowBefore(Element tr) { Element newRow = createRowElement(); - if( tr == null){ + if (tr == null) { tableElement.appendChild(newRow); - }else{ + } else { tableElement.insertBefore(newRow, tr); } } - - public void removeRow(Element tr){ + + public void removeRow(Element tr) { tableElement.removeChild(tr); } public String[] getColumnProperties() { - return (String[])columnProperties.clone(); + return (String[]) columnProperties.clone(); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/TableElementWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/TableElementWizardPage.java index cce7813..93b35ec 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/TableElementWizardPage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/TableElementWizardPage.java @@ -1,5 +1,5 @@ /* - * $Id: TableElementWizardPage.java,v 1.1 2004-10-05 20:51:57 jsurfer Exp $ + * $Id: TableElementWizardPage.java,v 1.2 2006-10-21 23:18:43 pombredanne Exp $ * Copyright Narushima Hironori. All rights reserved. */ package net.sourceforge.phpeclipse.wizards.html; @@ -40,246 +40,251 @@ import org.xml.sax.SAXException; */ public class TableElementWizardPage extends EditElementWizardPage { - final public static int COLUMNS_MAX = 32, ROWS_MAX = 256; - - final static String[] expandStyleLabels = { "Flat", "Table", "Enumerate", }; - - TableElementModel model; - - TableViewer viewer; - - CellEditor[] editors; - - Combo expandStyleCombo = null; - - Text colsText, rowsText; - - Button addButton, removeButton, upButton, downButton; - - SelectionListener buttonListener = new SelectionListener() { - public void widgetSelected(SelectionEvent ev) { - Element e = getCurrentSelection(); - if (ev.widget == addButton) { - model.insertNewRowBefore(e); - } else if (ev.widget == removeButton) { - model.removeRow(e); - } else if (ev.widget == upButton) { - model.move(e, -1); - } else if (ev.widget == downButton) { - model.move(e, 1); - } - refreshAll(); - } - - public void widgetDefaultSelected(SelectionEvent e) { - } - }; - - ModifyListener cellCountChangeListener = new ModifyListener() { - public void modifyText(ModifyEvent e) { - try { - if (e.widget == colsText) { - int cols = Integer.parseInt(colsText.getText()); - if (cols < 1) - cols = 1; - if (cols > COLUMNS_MAX) - cols = COLUMNS_MAX; - model.setColumnCount(cols); - } else if (e.widget == rowsText) { - int rows = Integer.parseInt(rowsText.getText()); - if (rows < 1) - rows = 1; - if (rows > ROWS_MAX) - rows = ROWS_MAX; - model.setRowCount(rows); - } - refreshAll(); - } catch (NumberFormatException x) { - } - } - }; - - public TableElementWizardPage() { - super("TableElementWizardPage"); - setTitle("Table"); - setDescription("Edit table element and cells modifier."); - } - - public String getPreviewText() { - if (model == null) { - initModel(); - } - return (model != null) ? model.expandCodes() : null; - } - - void initModel() { - String content = ((EditElementWizard) getWizard()).getSelection().getText().trim(); - try { - model = new TableElementModel(content, getEditType() == NEW); - } catch (ParserConfigurationException e) { - PHPeclipsePlugin.log(e); - } catch (SAXException e) { - PHPeclipsePlugin.log(e); - } catch (IOException e) { - PHPeclipsePlugin.log(e); - } - } - - protected void createChildControl(Composite parent) { - parent.setLayout(new GridLayout(2, false)); - - // table settings - viewer = new TableViewer(parent, SWT.SINGLE | SWT.FULL_SELECTION | SWT.BORDER); - refreshTableHeaderColumns(); - - viewer.setContentProvider(new TableElementContentProvider()); - viewer.setLabelProvider(new TableElementLabelProvider()); - viewer.setCellModifier(new TableElementCellModifier(new IPropertyChangeListener() { - public void propertyChange(PropertyChangeEvent event) { - refreshAll(); - } - })); - - viewer.setInput(model); - viewer.addSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - refreshButtonState(); - refreshPreview(); - } - }); - - Table table = viewer.getTable(); - table.setLinesVisible(true); - table.setHeaderVisible(true); - - GridData gd = new GridData(GridData.FILL_BOTH); - gd.verticalSpan = 2; - table.setLayoutData(gd); - - // text input area setting - Composite textInputArea = new Composite(parent, SWT.NONE); - textInputArea.setLayout(new GridLayout(1, false)); - textInputArea.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_BEGINNING)); - rowsText = createNumInputText(textInputArea, "&Rows:"); - colsText = createNumInputText(textInputArea, "&Columns:"); - - // button area. - Composite buttonArea = new Composite(parent, SWT.NONE); - buttonArea.setLayout(new GridLayout(1, false)); - buttonArea.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_END)); - addButton = createButton(buttonArea, "&Add"); - removeButton = createButton(buttonArea, "&Remove"); - upButton = createButton(buttonArea, "&Up"); - downButton = createButton(buttonArea, "&Down"); - - // init state - TableColumn[] cols = table.getColumns(); - for (int i = 0; i < cols.length; i++) { - cols[i].pack(); - } - refreshTableLengthText(); - refreshButtonState(); - } - - Button createButton(Composite parent, String text) { - Button button = new Button(parent, SWT.NONE); - button.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); - button.setText(text); - button.addSelectionListener(buttonListener); - return button; - } - - Text createNumInputText(Composite parent, String label) { - Label labe = new Label(parent, SWT.NONE); - labe.setText(label); - - Text text = new Text(parent, SWT.BORDER); - text.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); - text.setTextLimit(2); - text.addVerifyListener(new NumVerifyListener()); - text.addModifyListener(cellCountChangeListener); - return text; - } - - void refreshAll() { - refreshTableHeaderColumns(); - refreshTableLengthText(); - refreshButtonState(); - refreshPreview(); - viewer.refresh(); - } - - void refreshTableHeaderColumns() { - if (model == null) { - initModel(); - } - - Table table = viewer.getTable(); - TableColumn[] cols = table.getColumns(); - CellEditor[] editors = viewer.getCellEditors(); - - String[] props = model.getColumnProperties(); - viewer.setColumnProperties(props); - // modify cell length - if (props.length > cols.length) { - CellEditor[] newEditors = new CellEditor[props.length]; - if (editors != null) { - System.arraycopy(editors, 0, newEditors, 0, editors.length); - } - for (int i = cols.length; i < props.length; i++) { - TableColumn col = new TableColumn(table, SWT.LEFT); - col.setText(TableElementModel.toColumnName(i)); - newEditors[i] = new TextCellEditor(table); - } - viewer.setCellEditors(newEditors); - } else if (props.length < cols.length) { - for (int i = props.length; i < cols.length; i++) { - cols[i].dispose(); - editors[i].dispose(); - } - CellEditor[] newEditors = new CellEditor[props.length]; - System.arraycopy(editors, 0, newEditors, 0, props.length); - viewer.setCellEditors(newEditors); - } - - // adjust table fields. - viewer.refresh(); - cols = table.getColumns(); - for (int i = 0; i < cols.length; i++) { - cols[i].pack(); - } - } - - void refreshTableLengthText() { - String cols = String.valueOf(model.getColumnCount()); - if (!cols.equals(colsText.getText())) { - colsText.setText(cols); - } - String rows = String.valueOf(model.getRowCount()); - if (!rows.equals(rowsText.getText())) { - rowsText.setText(rows); - } - } - - void refreshButtonState() { - Element e = getCurrentSelection(); - boolean enable = (e != null); - - removeButton.setEnabled(enable); - int currentIndex = -1; - Element[] rows = model.getRows(); - for (int i = 0; i < rows.length; i++) { - if (rows[i].equals(e)) { - currentIndex = i; - } - } - upButton.setEnabled(enable && currentIndex > 0); - downButton.setEnabled(enable && currentIndex < rows.length - 1); - } - - Element getCurrentSelection() { - IStructuredSelection sel = (IStructuredSelection) viewer.getSelection(); - return (sel != null) ? (Element) sel.getFirstElement() : null; - } + final public static int COLUMNS_MAX = 32, ROWS_MAX = 256; + + final static String[] expandStyleLabels = { "Flat", "Table", "Enumerate", }; + + TableElementModel model; + + TableViewer viewer; + + CellEditor[] editors; + + Combo expandStyleCombo = null; + + Text colsText, rowsText; + + Button addButton, removeButton, upButton, downButton; + + SelectionListener buttonListener = new SelectionListener() { + public void widgetSelected(SelectionEvent ev) { + Element e = getCurrentSelection(); + if (ev.widget == addButton) { + model.insertNewRowBefore(e); + } else if (ev.widget == removeButton) { + model.removeRow(e); + } else if (ev.widget == upButton) { + model.move(e, -1); + } else if (ev.widget == downButton) { + model.move(e, 1); + } + refreshAll(); + } + + public void widgetDefaultSelected(SelectionEvent e) { + } + }; + + ModifyListener cellCountChangeListener = new ModifyListener() { + public void modifyText(ModifyEvent e) { + try { + if (e.widget == colsText) { + int cols = Integer.parseInt(colsText.getText()); + if (cols < 1) + cols = 1; + if (cols > COLUMNS_MAX) + cols = COLUMNS_MAX; + model.setColumnCount(cols); + } else if (e.widget == rowsText) { + int rows = Integer.parseInt(rowsText.getText()); + if (rows < 1) + rows = 1; + if (rows > ROWS_MAX) + rows = ROWS_MAX; + model.setRowCount(rows); + } + refreshAll(); + } catch (NumberFormatException x) { + } + } + }; + + public TableElementWizardPage() { + super("TableElementWizardPage"); + setTitle("Table"); + setDescription("Edit table element and cells modifier."); + } + + public String getPreviewText() { + if (model == null) { + initModel(); + } + return (model != null) ? model.expandCodes() : null; + } + + void initModel() { + String content = ((EditElementWizard) getWizard()).getSelection() + .getText().trim(); + try { + model = new TableElementModel(content, getEditType() == NEW); + } catch (ParserConfigurationException e) { + PHPeclipsePlugin.log(e); + } catch (SAXException e) { + PHPeclipsePlugin.log(e); + } catch (IOException e) { + PHPeclipsePlugin.log(e); + } + } + + protected void createChildControl(Composite parent) { + parent.setLayout(new GridLayout(2, false)); + + // table settings + viewer = new TableViewer(parent, SWT.SINGLE | SWT.FULL_SELECTION + | SWT.BORDER); + refreshTableHeaderColumns(); + + viewer.setContentProvider(new TableElementContentProvider()); + viewer.setLabelProvider(new TableElementLabelProvider()); + viewer.setCellModifier(new TableElementCellModifier( + new IPropertyChangeListener() { + public void propertyChange(PropertyChangeEvent event) { + refreshAll(); + } + })); + + viewer.setInput(model); + viewer.addSelectionChangedListener(new ISelectionChangedListener() { + public void selectionChanged(SelectionChangedEvent event) { + refreshButtonState(); + refreshPreview(); + } + }); + + Table table = viewer.getTable(); + table.setLinesVisible(true); + table.setHeaderVisible(true); + + GridData gd = new GridData(GridData.FILL_BOTH); + gd.verticalSpan = 2; + table.setLayoutData(gd); + + // text input area setting + Composite textInputArea = new Composite(parent, SWT.NONE); + textInputArea.setLayout(new GridLayout(1, false)); + textInputArea.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL + | GridData.VERTICAL_ALIGN_BEGINNING)); + rowsText = createNumInputText(textInputArea, "&Rows:"); + colsText = createNumInputText(textInputArea, "&Columns:"); + + // button area. + Composite buttonArea = new Composite(parent, SWT.NONE); + buttonArea.setLayout(new GridLayout(1, false)); + buttonArea.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL + | GridData.VERTICAL_ALIGN_END)); + addButton = createButton(buttonArea, "&Add"); + removeButton = createButton(buttonArea, "&Remove"); + upButton = createButton(buttonArea, "&Up"); + downButton = createButton(buttonArea, "&Down"); + + // init state + TableColumn[] cols = table.getColumns(); + for (int i = 0; i < cols.length; i++) { + cols[i].pack(); + } + refreshTableLengthText(); + refreshButtonState(); + } + + Button createButton(Composite parent, String text) { + Button button = new Button(parent, SWT.NONE); + button.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); + button.setText(text); + button.addSelectionListener(buttonListener); + return button; + } + + Text createNumInputText(Composite parent, String label) { + Label labe = new Label(parent, SWT.NONE); + labe.setText(label); + + Text text = new Text(parent, SWT.BORDER); + text.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); + text.setTextLimit(2); + text.addVerifyListener(new NumVerifyListener()); + text.addModifyListener(cellCountChangeListener); + return text; + } + + void refreshAll() { + refreshTableHeaderColumns(); + refreshTableLengthText(); + refreshButtonState(); + refreshPreview(); + viewer.refresh(); + } + + void refreshTableHeaderColumns() { + if (model == null) { + initModel(); + } + + Table table = viewer.getTable(); + TableColumn[] cols = table.getColumns(); + CellEditor[] editors = viewer.getCellEditors(); + + String[] props = model.getColumnProperties(); + viewer.setColumnProperties(props); + // modify cell length + if (props.length > cols.length) { + CellEditor[] newEditors = new CellEditor[props.length]; + if (editors != null) { + System.arraycopy(editors, 0, newEditors, 0, editors.length); + } + for (int i = cols.length; i < props.length; i++) { + TableColumn col = new TableColumn(table, SWT.LEFT); + col.setText(TableElementModel.toColumnName(i)); + newEditors[i] = new TextCellEditor(table); + } + viewer.setCellEditors(newEditors); + } else if (props.length < cols.length) { + for (int i = props.length; i < cols.length; i++) { + cols[i].dispose(); + editors[i].dispose(); + } + CellEditor[] newEditors = new CellEditor[props.length]; + System.arraycopy(editors, 0, newEditors, 0, props.length); + viewer.setCellEditors(newEditors); + } + + // adjust table fields. + viewer.refresh(); + cols = table.getColumns(); + for (int i = 0; i < cols.length; i++) { + cols[i].pack(); + } + } + + void refreshTableLengthText() { + String cols = String.valueOf(model.getColumnCount()); + if (!cols.equals(colsText.getText())) { + colsText.setText(cols); + } + String rows = String.valueOf(model.getRowCount()); + if (!rows.equals(rowsText.getText())) { + rowsText.setText(rows); + } + } + + void refreshButtonState() { + Element e = getCurrentSelection(); + boolean enable = (e != null); + + removeButton.setEnabled(enable); + int currentIndex = -1; + Element[] rows = model.getRows(); + for (int i = 0; i < rows.length; i++) { + if (rows[i].equals(e)) { + currentIndex = i; + } + } + upButton.setEnabled(enable && currentIndex > 0); + downButton.setEnabled(enable && currentIndex < rows.length - 1); + } + + Element getCurrentSelection() { + IStructuredSelection sel = (IStructuredSelection) viewer.getSelection(); + return (sel != null) ? (Element) sel.getFirstElement() : null; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/UnknownElementWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/UnknownElementWizardPage.java index d6ad3a5..817451d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/UnknownElementWizardPage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/UnknownElementWizardPage.java @@ -1,5 +1,5 @@ /* - * $Id: UnknownElementWizardPage.java,v 1.1 2004-10-05 20:51:57 jsurfer Exp $ + * $Id: UnknownElementWizardPage.java,v 1.2 2006-10-21 23:18:43 pombredanne Exp $ * Copyright Narushima Hironori. All rights reserved. */ package net.sourceforge.phpeclipse.wizards.html; @@ -32,25 +32,22 @@ import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; - /** * - * + * */ public class UnknownElementWizardPage extends EditElementWizardPage { // key of TableCell for attribute editor. - final static String - NAME = "ColumnProperty-name", - VALUE = "ColumnProperty-value"; - + final static String NAME = "ColumnProperty-name", + VALUE = "ColumnProperty-value"; + Button emptyElementCheck, addButton, removeButton, upButton, downButton; - + TableViewer unknownElementAttrs; - ArrayList - attrs = new ArrayList(), - listeners = new ArrayList(); - + + ArrayList attrs = new ArrayList(), listeners = new ArrayList(); + SelectionListener elemTypeChangeListener = new SelectionListener() { public void widgetSelected(SelectionEvent e) { refreshPreview(); @@ -59,8 +56,8 @@ public class UnknownElementWizardPage extends EditElementWizardPage { public void widgetDefaultSelected(SelectionEvent e) { } }; - - public UnknownElementWizardPage(){ + + public UnknownElementWizardPage() { super("UnknownElementEditPage"); setTitle("Unknown"); setDescription("Editor for any HTML element."); @@ -68,10 +65,11 @@ public class UnknownElementWizardPage extends EditElementWizardPage { static IInputValidator attrValidator = new IInputValidator() { public String isValid(String newText) { - if( newText.length() == 0){ + if (newText.length() == 0) { return "Need to specify name"; } - if( newText.indexOf(' ') != -1 || newText.indexOf('\n') != -1 || newText.indexOf('\t') != -1 ){ + if (newText.indexOf(' ') != -1 || newText.indexOf('\n') != -1 + || newText.indexOf('\t') != -1) { return "Not contain blank"; } return null; @@ -80,76 +78,80 @@ public class UnknownElementWizardPage extends EditElementWizardPage { protected void createChildControl(Composite parent) { // empty eleemnt - parent.setLayout( new GridLayout(2, false) ); - - //// attribute editor + parent.setLayout(new GridLayout(2, false)); + + // // attribute editor Label labe = new Label(parent, SWT.NONE); labe.setText("Element &Attribute:"); GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); labe.setLayoutData(gd); new Label(parent, SWT.NONE); - + // attribute display table setting - unknownElementAttrs = new TableViewer(parent, SWT.BORDER | SWT.SINGLE | SWT.FULL_SELECTION); + unknownElementAttrs = new TableViewer(parent, SWT.BORDER | SWT.SINGLE + | SWT.FULL_SELECTION); gd = new GridData(GridData.FILL_BOTH); gd.horizontalSpan = 1; gd.verticalSpan = 4; unknownElementAttrs.getControl().setLayoutData(gd); - + final Table table = unknownElementAttrs.getTable(); new TableColumn(table, SWT.LEFT).setText("Name"); new TableColumn(table, SWT.LEFT).setText("Value"); - + table.setLinesVisible(true); table.setHeaderVisible(true); // modifier setting - unknownElementAttrs.setColumnProperties(new String[]{ NAME, VALUE }); + unknownElementAttrs.setColumnProperties(new String[] { NAME, VALUE }); unknownElementAttrs.setContentProvider(new ArrayContentProvider()); - - unknownElementAttrs.setCellEditors( new CellEditor[]{ - new TextCellEditor(table), - new TextCellEditor(table) - }); + + unknownElementAttrs.setCellEditors(new CellEditor[] { + new TextCellEditor(table), new TextCellEditor(table) }); unknownElementAttrs.setCellModifier(new ICellModifier() { public boolean canModify(Object element, String property) { return true; } public Object getValue(Object element, String property) { - return ((String[])element)[property.equals(NAME) ? 0 : 1]; + return ((String[]) element)[property.equals(NAME) ? 0 : 1]; } public void modify(Object element, String property, Object value) { if (element instanceof Item) { - ((String[])((Item) element).getData())[property.equals(NAME) ? 0 : 1] = HTMLUtilities.unescape( (String)value ); + ((String[]) ((Item) element).getData())[property + .equals(NAME) ? 0 : 1] = HTMLUtilities + .unescape((String) value); refreshPreview(); } } }); - - unknownElementAttrs.setLabelProvider( new ITableLabelProvider() { + + unknownElementAttrs.setLabelProvider(new ITableLabelProvider() { public Image getColumnImage(Object element, int columnIndex) { return null; } public String getColumnText(Object element, int columnIndex) { - return ((String[])element)[columnIndex]; + return ((String[]) element)[columnIndex]; } - public void addListener(ILabelProviderListener listener) {} + public void addListener(ILabelProviderListener listener) { + } - public void removeListener(ILabelProviderListener listener) {} + public void removeListener(ILabelProviderListener listener) { + } - public void dispose() {} + public void dispose() { + } public boolean isLabelProperty(Object element, String property) { return property.equals(NAME) || property.equals(VALUE); } }); - + resetAttributes(); unknownElementAttrs.setInput(attrs); - + TableColumn[] columns = table.getColumns(); for (int i = 0; i < columns.length; i++) { columns[i].pack(); @@ -158,66 +160,72 @@ public class UnknownElementWizardPage extends EditElementWizardPage { // buttonss upButton = createButton(parent, "&Up"); upButton.addSelectionListener(new SelectionListener() { - + public void widgetSelected(SelectionEvent e) { int index = getSelectionIndex(); - if( index > 0){ - attrs.add(index-1, attrs.remove(index)); + if (index > 0) { + attrs.add(index - 1, attrs.remove(index)); refreshPreview(); } } - public void widgetDefaultSelected(SelectionEvent e) {} + + public void widgetDefaultSelected(SelectionEvent e) { + } }); - + downButton = createButton(parent, "&Down"); downButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { int index = getSelectionIndex(); - if( index < attrs.size()-1 ){ - attrs.add(index+1, attrs.remove(index)); + if (index < attrs.size() - 1) { + attrs.add(index + 1, attrs.remove(index)); refreshPreview(); } } - public void widgetDefaultSelected(SelectionEvent e) {} + + public void widgetDefaultSelected(SelectionEvent e) { + } }); - + addButton = createButton(parent, "&Add"); addButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { int insertIndex = getSelectionIndex(); String[] newData = inputValue(); - if(newData != null){ + if (newData != null) { attrs.add(newData); refreshPreview(); } } - String[] inputValue(){ + String[] inputValue() { SomeItemInputDialog dialog = new SomeItemInputDialog( - getShell(), - "Input new attribute", - new String[]{"Attribute name", "Attribute value"}, - new IInputValidator[] {attrValidator, null}); - - - if( dialog.open() == Window.OK){ + getShell(), "Input new attribute", new String[] { + "Attribute name", "Attribute value" }, + new IInputValidator[] { attrValidator, null }); + + if (dialog.open() == Window.OK) { return dialog.getValues(); } return null; } - public void widgetDefaultSelected(SelectionEvent e) {} + + public void widgetDefaultSelected(SelectionEvent e) { + } }); - + removeButton = createButton(parent, "&Remove"); removeButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { int index = getSelectionIndex(); - if( index != -1){ + if (index != -1) { attrs.remove(index); refreshPreview(); - } + } + } + + public void widgetDefaultSelected(SelectionEvent e) { } - public void widgetDefaultSelected(SelectionEvent e) {} }); emptyElementCheck = new Button(parent, SWT.CHECK); @@ -226,89 +234,89 @@ public class UnknownElementWizardPage extends EditElementWizardPage { emptyElementCheck.setText("&Empty Element"); emptyElementCheck.addSelectionListener(elemTypeChangeListener); emptyElementCheck.setSelection(isEmptyAsText()); - + new Label(parent, SWT.NONE); } - - static Button createButton(Composite parent, String text){ + + static Button createButton(Composite parent, String text) { Button button = new Button(parent, SWT.PUSH); - GridData gd = new GridData( - GridData.VERTICAL_ALIGN_BEGINNING | GridData.HORIZONTAL_ALIGN_END); + GridData gd = new GridData(GridData.VERTICAL_ALIGN_BEGINNING + | GridData.HORIZONTAL_ALIGN_END); gd.widthHint = 60; - button.setLayoutData( gd); + button.setLayoutData(gd); button.setText(text); return button; } - - public String getPreviewText(){ + + public String getPreviewText() { String elemName = getElementName(); - if(elemName == null){ + if (elemName == null) { return null; } - + // sets values - + boolean empty = false; - if( emptyElementCheck == null ){ + if (emptyElementCheck == null) { // ui uninitialized empty = isEmptyAsText(); - }else{ + } else { // ui initialized empty = emptyElementCheck.getSelection(); } - + String content = getSelectionText(); - if( !empty && getEditType() == MODIFY){ - content = chooseContent( content ); + if (!empty && getEditType() == MODIFY) { + content = chooseContent(content); } - + String previewText = "<" + elemName + attrsCode(); - if(empty){ - previewText += " />"; - }else{ + if (empty) { + previewText += " />"; + } else { previewText += ">" + content + ""; } return previewText; } - - boolean isEmptyAsText(){ + + boolean isEmptyAsText() { String selText = getSelectionText(); - if(getEditType() == MODIFY){ + if (getEditType() == MODIFY) { int len = selText.length(); - return selText.substring(len-2, len).equals("/>"); + return selText.substring(len - 2, len).equals("/>"); } return false; } - - void resetAttributes(){ + + void resetAttributes() { attrs.clear(); - + Element elem = getParsedSelectionText(); - if( elem != null){ + if (elem != null) { NamedNodeMap as = elem.getAttributes(); for (int i = 0; i < as.getLength(); i++) { Node n = as.item(i); - attrs.add( new String[]{ n.getNodeName(), n.getNodeValue()}); + attrs.add(new String[] { n.getNodeName(), n.getNodeValue() }); } } } - - String attrsCode(){ + + String attrsCode() { StringBuffer buff = new StringBuffer(); Object[] as = attrs.toArray(); for (int i = 0; i < as.length; i++) { - String[] a = (String[])as[i]; + String[] a = (String[]) as[i]; buff.append(" " + a[0] + "=\"" + HTMLUtilities.escape(a[1]) + "\""); } return buff.toString(); } - int getSelectionIndex(){ + int getSelectionIndex() { Object sel = unknownElementAttrs.getSelection(); - if( sel instanceof IStructuredSelection){ - Object item = ((IStructuredSelection)sel).getFirstElement(); + if (sel instanceof IStructuredSelection) { + Object item = ((IStructuredSelection) sel).getFirstElement(); return attrs.indexOf(item); - }else{ + } else { return -1; } } -- 1.7.1